@openchambery/web 2.0.0 → 2.0.1
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/{AgentAvatar-C1MGZ7qC.js → AgentAvatar-DGyF86jy.js} +1 -1
- package/dist/assets/{AssistantView-vqCFvVo0.js → AssistantView-ByGdaGiF.js} +3 -3
- package/dist/assets/{DiagramView-CYO5iVVm.js → DiagramView-PB0pBILb.js} +1 -1
- package/dist/assets/{FadeInOnReveal-BMSk_tY-.js → FadeInOnReveal-B_a083XJ.js} +1 -1
- package/dist/assets/{Icon-BdzPRCSy.js → Icon-BE2hkaYc.js} +1 -1
- package/dist/assets/{MarkdownRenderer-FMynjkGR.js → MarkdownRenderer-H1MIHXzt.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-DoWvw5jj.js → MarkdownRendererImpl-CZ8GeckU.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-DoeYajmw.js → MarkstreamRendererImpl-BKE6YZ2N.js} +1 -1
- package/dist/assets/MobileDetailNavigation-D9KkIrWy.js +1 -0
- package/dist/assets/{MobileShareBridge-D1Uoj6l_.js → MobileShareBridge-1yCjq-60.js} +3 -3
- package/dist/assets/{MobileSurface-8YpZ51Qo.js → MobileSurface-Dqn3OPVX.js} +1 -1
- package/dist/assets/{MultiRunWindow-BxcYUPta.js → MultiRunWindow-YCFM6or1.js} +1 -1
- package/dist/assets/{OnboardingScreen-yRdQTR1M.js → OnboardingScreen-CTmsNR65.js} +1 -1
- package/dist/assets/{OverlayScrollbar-BUjtqnxn.js → OverlayScrollbar-CVgW_Z9B.js} +1 -1
- package/dist/assets/{SettingsView-D7KrvqvH.js → SettingsView-CbiuXtYG.js} +2 -2
- package/dist/assets/{SettingsWindow-DX2w-cDc.js → SettingsWindow-jOZ7L6K8.js} +1 -1
- package/dist/assets/{TerminalView-CiUcCQPm.js → TerminalView-CI-KsDdH.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DQvXtK71.js → ToolOutputDialog-izZjgkkg.js} +1 -1
- package/dist/assets/{appThemeRegistry-BXC6cIDE.js → appThemeRegistry-MiWlVk4e.js} +1 -1
- package/dist/assets/{button-CUwjpv-i.js → button-CcOoDLE1.js} +1 -1
- package/dist/assets/{collapsible-paItOH3A.js → collapsible-CSa0Ndgm.js} +1 -1
- package/dist/assets/{context-menu-K6zNumqN.js → context-menu-DoTwmMb5.js} +1 -1
- package/dist/assets/{desktopHosts-DuftEj8B.js → desktopHosts-BsbquPqS.js} +1 -1
- package/dist/assets/{desktopRelayRestore-g378BdZf.js → desktopRelayRestore-yyvjztgj.js} +1 -1
- package/dist/assets/{diagram-D6nY5hbD.js → diagram-CZKDkADZ.js} +1 -1
- package/dist/assets/{dialog-PjKWayIU.js → dialog-Csvrld51.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-78v5mNTE.js → fileMentionTouchSelection-Bn0f83D3.js} +1 -1
- package/dist/assets/{fileQueries-DuF89nFO.js → fileQueries-B0hhXD86.js} +1 -1
- package/dist/assets/{gitApi-eoKSJcvW.js → gitApi-DpwH7xTg.js} +1 -1
- package/dist/assets/{input-BeVw4D0W.js → input-C6Y7mytw.js} +1 -1
- package/dist/assets/{insertionBoundaries-BI3RHOpf.js → insertionBoundaries-Cst5Z6Cd.js} +1 -1
- package/dist/assets/{main-MN0YKJ0_.js → main-CEs8ipuu.js} +2 -2
- package/dist/assets/main-Dkzuy7EG.js +169 -0
- package/dist/assets/{markdownHeightCache-CGCWmHgq.js → markdownHeightCache-DhLhFBWX.js} +1 -1
- package/dist/assets/{mcpQueries-X424Iq2z.js → mcpQueries-BBpCJgvK.js} +1 -1
- package/dist/assets/{miniChat-DFIl76ku.js → miniChat-CR7k42bZ.js} +2 -2
- package/dist/assets/{mobile-C3fWXGQJ.js → mobile-rvypjUpd.js} +2 -2
- package/dist/assets/{multirun-DuSX3YRs.js → multirun-DqmJk0mh.js} +1 -1
- package/dist/assets/{persistence-Dnj1QOdX.js → persistence-CwHY3fDg.js} +1 -1
- package/dist/assets/{platform-jCZ3KfMQ.js → platform-Bxaalnc8.js} +1 -1
- package/dist/assets/{projectMeta-Cn08pTNi.js → projectMeta-BhKfv5cj.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-CRPdctIn.js → renderElectronMiniChatApp-BLay6f9j.js} +2 -2
- package/dist/assets/{renderMobileApp-CVURQbeh.js → renderMobileApp-BrikirqO.js} +4 -4
- package/dist/assets/{runtimeConfig-xivE1wxC.js → runtimeConfig-DjKsteH0.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-B8DzKzwg.js → runtimeEndpointReset-DbfaE3dL.js} +3 -3
- package/dist/assets/{sessionChangeSummary-yBsR2pyd.js → sessionChangeSummary-Cgq9RPUq.js} +1 -1
- package/dist/assets/{sessionLookup-1Z1FWZRB.js → sessionLookup-BiE36BTy.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-D611LPyd.js → sortable-tabs-strip-CKKp4p3Y.js} +1 -1
- package/dist/assets/src-BZ0tISrf.css +2 -0
- package/dist/assets/{terminalApi-BZW_rAc3.js → terminalApi-DSJOXNRQ.js} +1 -1
- package/dist/assets/{textarea-QtZjf4L8.js → textarea-DUjc3iDJ.js} +1 -1
- package/dist/assets/{tooltip-DDNnmcXI.js → tooltip-CBHR50fA.js} +1 -1
- package/dist/assets/{url-DNRMq_0R.js → url-CEnO45_n.js} +1 -1
- package/dist/assets/{useAppFontEffects-DJy8P5By.js → useAppFontEffects-CWzjhjXr.js} +6 -6
- package/dist/assets/{useAssistantUIStore-DBwfg9nX.js → useAssistantUIStore-CXj8c_tt.js} +1 -1
- package/dist/assets/{useDesktopWindowControlsLayout-DlwSomVK.js → useDesktopWindowControlsLayout-Dtqco-Um.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-eJorVTT9.js → useEffectiveDirectory-DNbDaaNV.js} +1 -1
- package/dist/assets/{useFontPreferences-Bjgt_lzl.js → useFontPreferences-DGbTdGy3.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-A_ZNTfpl.js → useMobileNavigationStore-DYKC2swj.js} +6 -6
- package/dist/assets/{useSessionAutoCleanup-CqC3dEou.js → useSessionAutoCleanup-BI0xQcio.js} +1 -1
- package/dist/assets/{useUIStore-Dfx6TKvi.js → useUIStore-DNkuudYO.js} +1 -1
- package/dist/assets/{useWorkerHighlightedLines-B0vSL6jr.js → useWorkerHighlightedLines-BoyYALWC.js} +1 -1
- package/dist/index.html +9 -9
- package/dist/mini-chat.html +9 -9
- package/dist/mobile.html +9 -9
- package/package.json +1 -1
- package/dist/assets/MobileDetailNavigation-BzBz-co_.js +0 -1
- package/dist/assets/main-CQpUPjPK.js +0 -169
- package/dist/assets/src-TBM7scxy.css +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-BJM2k_uH.js";import{n as f}from"./runtime-fetch-CiqQd__Y.js";import{$ as p,At as m,C as h,E as g,F as _,G as v,H as y,Ht as b,I as x,J as S,O as C,On as w,P as T,Pt as E,Q as D,S as O,T as k,Tt as A,V as j,W as M,X as N,Y as P,Z as F,Zt as I,_ as L,at as R,b as z,c as B,d as V,dt as H,en as ee,et as U,f as te,ft as W,h as ne,ht as re,in as ie,it as ae,jt as oe,kt as se,lt as ce,n as le,nn as ue,nt as de,on as fe,pt as pe,r as me,rn as he,rt as ge,sn as _e,st as ve,t as ye,ut as be,vt as xe,w as Se,wt as Ce,x as we,y as Te,yt as Ee,z as De,zt as Oe}from"./persistence-Dnj1QOdX.js";import{_ as ke,c as Ae,d as je,f as Me,h as Ne,i as Pe,l as Fe,m as Ie,n as Le,o as Re,p as ze,r as Be,s as Ve}from"./desktopHosts-DuftEj8B.js";import{r as He}from"./desktopRelayRestore-g378BdZf.js";import{a as Ue,i as We,o as Ge,r as Ke,s as qe,t as Je}from"./vendor-zustand-DzRqcymP.js";import{c as Ye,d as Xe,f as Ze,l as Qe,nt as $e,rt as et,tt,u as nt}from"./vendor-base-ui-CnHfUmDN.js";import{Ai as rt,An as it,At as at,Bn as ot,Ci as st,Cn as ct,Ct as lt,Dn as ut,Ei as dt,En as ft,Er as pt,Fi as mt,Fn as ht,Hn as gt,Ii as _t,It as vt,Li as yt,Lt as bt,Nt as xt,Ot as St,Pn as Ct,Qt as wt,St as Tt,Ti as Et,Tn as Dt,Tr as Ot,Wn as kt,Xt as At,Yt as jt,an as Mt,bi as Nt,bn as Pt,br as Ft,cn as It,en as Lt,fn as Rt,gr as zt,hn as Bt,jr as Vt,jt as Ht,kn as Ut,kr as Wt,kt as Gt,lr as Kt,mi as qt,mn as Jt,n as Yt,nn as Xt,on as Zt,pn as Qt,qt as $t,rn as en,sn as tn,t as nn,tn as rn,tr as an,vi as on,vr as sn,wn as cn,wr as ln,xn as un,xr as dn,yn as fn,yr as pn,zn as mn}from"./platform-jCZ3KfMQ.js";import{_ as hn,b as gn,c as _n,f as vn,g as G,h as yn,n as K,y as bn}from"./useUIStore-Dfx6TKvi.js";import{n as xn}from"./vendor-react-DLPElpoQ.js";import{o as Sn}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{c as Cn,i as wn,n as Tn,s as En,t as Dn}from"./vendor-tanstack-react-query-D7pys_c9.js";import{B as On,R as kn,V as An,c as jn}from"./vendor-codemirror-autocomplete-DHomsvW7.js";import{i as Mn,u as Nn}from"./vendor-pierre-diffs-DX7XTPG3.js";import{t as Pn}from"./vendor-sonner-DVzioF3d.js";import{a as Fn,f as In,i as Ln,m as Rn,n as q,o as zn,r as Bn,u as Vn}from"./vendor-reactuses-core-Dq5ocTF8.js";import{_ as Hn,d as Un,f as Wn,i as Gn,l as Kn,p as qn,r as J,t as Jn,v as Yn}from"./button-CUwjpv-i.js";import{i as Xn,t as Zn}from"./store-l_X_jQNz.js";import{$ as Qn,$i as $n,$r as er,$t as tr,A as nr,Ai as rr,At as ir,B as ar,Bi as or,Br as sr,Bt as cr,C as lr,Ca as ur,Ci as dr,Cn as fr,Ct as pr,D as mr,Da as hr,Di as gr,Dn as _r,Dr as vr,Dt as yr,E as br,Ea as xr,Ei as Sr,En as Cr,Er as wr,Et as Tr,F as Er,Fa as Dr,Fi as Or,Fn as kr,G as Ar,Gi as jr,Gr as Mr,Gt as Nr,H as Pr,Hi as Fr,Hn as Ir,I as Lr,Ii as Rr,In as zr,It as Br,J as Vr,Ji as Hr,Jt as Ur,K as Wr,Ki as Gr,Kt as Kr,L as qr,Li as Jr,Ln as Yr,Lr as Xr,Lt as Zr,M as Qr,Ma as $r,Mn as ei,Mt as ti,N as ni,Ni as ri,Nn as ii,Nt as ai,O as oi,Oa as si,Oi as ci,On as li,Ot as ui,P as di,Pa as fi,Pi as pi,Pn as mi,Q as hi,Qi as gi,Qn as _i,Qr as vi,Qt as yi,R as bi,Ra as xi,Ri as Si,Rn as Ci,Rr as wi,Rt as Ti,Sa as Ei,Si as Di,St as Oi,Ta as ki,Ti as Ai,Tn as ji,Tt as Mi,U as Ni,Ui as Pi,Un as Fi,Ur as Ii,Ut as Li,V as Ri,Vi as zi,W as Bi,Wi as Vi,Wr as Hi,Wt as Ui,X as Wi,Xa as Gi,Xi as Ki,Xn as qi,Xt as Ji,Y as Yi,Yi as Xi,Yr as Zi,Z as Qi,Zi as $i,Zn as ea,Zr as ta,Zt as na,_n as ra,aa as ia,ai as aa,an as oa,at as sa,ba as ca,bi as la,bn as ua,bt as da,c as fa,ci as pa,cn as ma,ct as ha,d as Y,di as ga,dn as _a,do as va,dr as ya,ea as ba,ei as xa,en as Sa,eo as Ca,er as wa,et as Ta,fa as Ea,fi as Da,fn as Oa,fr as ka,g as Aa,gi as ja,gn as Ma,gt as Na,ha as Pa,hn as Fa,ht as Ia,i as La,ii as Ra,in as za,it as Ba,j as Va,jr as Ha,jt as Ua,k as Wa,ki as Ga,kt as Ka,la as qa,lt as Ja,m as Ya,mi as Xa,mn as Za,mr as Qa,n as $a,ni as eo,nt as to,oi as no,on as ro,ot as io,pa as ao,pi as oo,pn as so,pr as co,q as lo,qi as uo,qr as fo,qt as po,r as mo,rn as ho,rt as go,s as _o,sn as vo,so as yo,st as bo,ta as xo,ti as So,to as Co,tt as wo,ua as To,ui as Eo,un as Do,uo as Oo,v as ko,vn as Ao,vt as jo,w as Mo,wa as No,wn as Po,wt as Fo,xa as Io,xi as Lo,xt as Ro,ya as zo,yn as Bo,yt as Vo,z as Ho,zi as Uo,zn as Wo,zr as Go}from"./useMobileNavigationStore-A_ZNTfpl.js";import{a as Ko,i as qo,l as Jo,n as Yo,o as Xo,r as Zo,s as Qo,t as $o}from"./dialog-PjKWayIU.js";import{t as es}from"./AgentAvatar-C1MGZ7qC.js";import{n as X}from"./Icon-BdzPRCSy.js";import{E as ts,n as ns}from"./gitApi-eoKSJcvW.js";import{a as rs}from"./vendor-simplewebauthn-browser-Dwhcdg_5.js";import{A as is,C as as,D as os,O as ss,S as cs,_ as ls,a as us,b as ds,f as fs,h as ps,i as ms,k as hs,l as gs,m as _s,n as vs,o as ys,s as bs,u as xs,w as Ss,x as Cs,y as ws}from"./projectMeta-Cn08pTNi.js";import{t as Ts}from"./input-BeVw4D0W.js";import{i as Es,n as Ds,t as Os}from"./tooltip-DDNnmcXI.js";import{$ as ks,$t as As,At as js,B as Ms,Bt as Ns,F as Ps,Ft as Fs,Ht as Is,I as Ls,J as Rs,K as zs,Kt as Bs,L as Vs,Ot as Hs,Pt as Us,Q as Ws,Rt as Gs,St as Ks,Ut as qs,Vt as Js,X as Ys,Y as Xs,Yt as Zs,Z as Qs,_t as $s,an as ec,at as tc,et as nc,ft as rc,gt as ic,i as ac,it as oc,jt as sc,kt as cc,l as lc,lt as uc,mt as dc,n as fc,nt as pc,on as mc,pt as hc,q as gc,qt as _c,rt as vc,sn as yc,t as bc,tt as xc,ut as Sc,z as Cc,zt as wc}from"./useSessionAutoCleanup-CqC3dEou.js";import{n as Tc,r as Ec,t as Dc}from"./useThemeSystem-DMzWVJaW.js";import{i as Oc,t as kc}from"./OverlayScrollbar-BUjtqnxn.js";import{a as Ac,c as jc,i as Mc,l as Nc,n as Pc,o as Fc,r as Ic,s as Lc}from"./markdownTheme-DM5h1i18.js";import{n as Rc,r as zc,t as Bc}from"./useRuntimeAPIs-DSLXJybW.js";import{S as Vc,i as Hc,n as Uc,r as Wc}from"./textarea-QtZjf4L8.js";import{A as Gc,C as Kc,D as qc,O as Jc,S as Yc,T as Xc,_ as Zc,a as Qc,b as $c,c as el,d as tl,f as nl,g as rl,h as il,j as al,k as ol,l as sl,m as cl,o as ll,p as ul,s as dl,u as fl,v as pl,w as ml,x as hl,y as gl}from"./sessionChangeSummary-yBsR2pyd.js";import{C as _l,D as vl,E as yl,O as bl,S as xl,T as Sl,a as Cl,b as wl,c as Tl,d as El,f as Dl,i as Ol,j as kl,k as Al,l as jl,n as Ml,o as Nl,p as Pl,r as Fl,s as Il,t as Ll,u as Rl,w as zl,x as Bl,y as Vl}from"./insertionBoundaries-BI3RHOpf.js";import{a as Hl,c as Ul,i as Wl,o as Gl,s as Kl}from"./fileMentionTouchSelection-78v5mNTE.js";import{A as ql,C as Jl,D as Yl,E as Xl,N as Zl,O as Ql,S as $l,T as eu,_ as tu,b as nu,c as ru,d as iu,f as au,g as ou,h as su,i as cu,k as lu,l as uu,m as du,o as fu,p as pu,s as mu,t as hu,u as gu,v as _u,w as vu,x as yu,y as bu}from"./appThemeRegistry-BXC6cIDE.js";import{a as xu,n as Su,o as Cu,r as wu,t as Tu}from"./MarkdownRenderer-FMynjkGR.js";import{_ as Eu,a as Du,c as Ou,g as ku,l as Au,o as ju,t as Mu,v as Nu,y as Pu}from"./vendor-dnd-kit-core-CvWxUPdb.js";import{i as Fu,n as Iu,o as Lu,s as Ru,t as zu}from"./vendor-dnd-kit-sortable-hHdP9lLb.js";import{a as Bu,n as Vu,t as Hu}from"./url-DNRMq_0R.js";import{a as Uu,l as Wu,m as Gu,u as Ku}from"./markdown-worker-bS5OgGO3.js";import{n as qu,t as Ju}from"./useEffectiveDirectory-eJorVTT9.js";import{a as Yu,c as Xu,d as Zu,f as Qu,i as $u,l as ed,n as td,r as nd,s as rd,t as id}from"./FadeInOnReveal-BMSk_tY-.js";import{c as ad,f as od,l as sd,m as cd,n as ld,p as ud,r as dd,s as fd,u as pd}from"./imageSource-BpUsiwFd.js";import{A as md,C as hd,D as gd,E as _d,M as vd,O as yd,S as bd,T as xd,a as Sd,b as Cd,c as wd,g as Td,h as Ed,i as Dd,j as Od,k as kd,o as Ad,p as jd,r as Md,s as Nd,t as Pd,v as Fd,w as Id,x as Ld,y as Rd}from"./useWorkerHighlightedLines-B0vSL6jr.js";import{t as zd}from"./vendor-cmdk-CeAGfrLo.js";import{t as Bd}from"./sortable-tabs-strip-D611LPyd.js";import{a as Vd}from"./markdownHeightCache-CGCWmHgq.js";import{t as Hd}from"./dualLimitLru-D8Sphgua.js";import{n as Ud,t as Wd}from"./vendor-tanstack-react-virtual-tlDgH6PG.js";import{i as Gd,t as Kd}from"./vendor-framer-motion-DFy_BSVd.js";import{t as qd}from"./vendor-legendapp-list-WE32lwNk.js";import{n as Jd,t as Yd}from"./useFontPreferences-Bjgt_lzl.js";var Xd=e=>{if(typeof e!=`string`)return;let t=e.trim();if(t)return{location:{directory:t}}};typeof window<`u`&&(window.__opencodeDebug={getLastAssistantMessage(){let e=Y.getState().currentSessionId;if(!e)return null;let t=mn(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=(ot(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:(ot(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=Y.getState().currentSessionId;if(!t)return[];let n=mn(t);return`${n.length}`,n.forEach((e,t)=>{let n=ot(e.id)||[];`${t}${e.role}${e.id}${n.length}`}),e?this.truncateMessages(n):n},async getAppStatus(){let e=lt.getState(),t=Y.getState(),n=Co.getState(),r=e.currentDirectory||null,i=xt.getDirectory()??null,a=gt(),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=w(),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,g=null,_=null,v=null;try{let e=await xt.getSdkClient().location.get(Xd(r));h=bt(e)}catch(e){h={error:e instanceof Error?e.message:String(e)}}try{g=(await xt.getSdkClient().location.get(Xd(r)))?.project??null}catch(e){g={error:e instanceof Error?e.message:String(e)}}_=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}v={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){v={error:e instanceof Error?e.message:String(e)}}let y={isGitRepo:null};if(r)try{y.isGitRepo=await ns(r)}catch(e){y={isGitRepo:null,error:e instanceof Error?e.message:String(e)}}let b=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:b},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:y,localStorage:c,opencode:{pathInfo:h,projectInfo:g,health:v},openchamber:{settingsInfo:_}}},async buildDiagnosticsReport(){let e=await this.getAppStatus();return JSON.stringify(e,null,2)},async copyTextToClipboard(e){return Un(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=Y.getState(),t=ei.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=Y.getState().currentSessionId;if(!e)return[];let t=mn(e).filter(e=>e.role===`assistant`).filter(e=>{let t=ot(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=ot(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=Y.getState().currentSessionId;if(!i)return{summary:null,rows:[]};let a=mn(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=ot(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=Y.getState().currentSessionId;if(!e)return null;let t=mn(e).filter(e=>e.role===`assistant`);if(t.length===0)return null;let n=t[t.length-1],r=(ot(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=ei.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}}},St(),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 Z=e(et(),1),Q=xn(),Zd=async()=>{if(typeof window>`u`)return;let e=null;try{e=Oe(`lastDirectory`)}catch(e){console.warn(`Failed to read saved directory preferences:`,e)}e&&!fe()&<.getState().setDirectory(e,{showOverlay:!1})},Qd=new Map,$d=e=>Qd.get(e)??null,ef=({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:i},a={})=>{let o=Qd.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 Qd.set(e,s),s},tf=async({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,startWatchers:i,onError:a})=>{await ef({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:a})&&i()},nf=(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 rf(e){return!e||e===`idle`?null:e===`ready`?`ok`:e===`error`?`unreachable`:`auth`}function af(e,t){let n=e.via===`relay`;return t?n:!n}function of(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?rf(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||af(o,a))&&(u=Math.max(0,Math.round(o.latencyMs))),{statusKind:c,showViaRelay:l,latencyMs:u}}var $=$e(),sf=`local`,cf=9e4,lf=`SSH connection cancelled`,uf=e=>He(e),df={},ff=e=>{let t=ze(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}},pf=()=>typeof window>`u`?``:window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,mf=async()=>ie()?Re().catch(()=>``):``,hf=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`,gf=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`,_f=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,vf=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,yf=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`,bf=e=>new Promise(t=>window.setTimeout(t,e)),xf=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`}},Sf=async()=>{let e=await As().catch(()=>[]),t={};for(let n of e)t[n.id]=n;return t},Cf=async(e,t,n,r)=>{let i=Date.now()+t;for(;Date.now()<i;){if(r?.())throw Error(lf);let t=(await As(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 bf(700)}throw r?.()?Error(lf):Error(`Timed out waiting for SSH connection`)},wf=e=>({id:sf,label:`Local`,url:e||pf()}),Tf=e=>{let t=typeof window>`u`?``:window.location.href,n=e.find(e=>e.id===sf)?.url||pf(),r=d(),i=ze(n)||n,a=ze(t)||t,o=u(),s=e.find(e=>e.relay&&uf(e)===o);if(s)return{id:s.id,label:s.label,url:s.url};if(r&&Me(r,n))return{id:sf,label:`Local`,url:i};let c=e.find(e=>r?Me(r,Fe(e)):!1);if(c)return{id:c.id,label:c.label,url:ze(Fe(c))||Fe(c)};if(t&&Me(t,n))return{id:sf,label:`Local`,url:i};let l=e.find(e=>t?Me(t,e.url):!1);return l?{id:l.id,label:l.label,url:ze(l.url)||l.url}:t.startsWith(`openchamber-ui://`)?{id:sf,label:`Local`,url:i}:{id:`custom`,label:Ne(a||`Instance`),url:a}};function Ef({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){let{t:a}=Wn(),s=K(e=>e.setSettingsDialogOpen),c=K(e=>e.setSettingsPage),l=ao(e=>e.isConnected),u=ao(e=>e.connectionPhase),[d,f]=Z.useState([]),[p,m]=Z.useState(null),[h,g]=Z.useState(()=>({...df}));Z.useEffect(()=>{Object.assign(df,h)},[h]);let[_,v]=Z.useState(!1),[y,b]=Z.useState(!1),[x,S]=Z.useState(!1),C=mc(),w=yc(),[T,E]=Z.useState(null),D=T||w,[O,k]=Z.useState({}),[A,j]=Z.useState({}),[M,N]=Z.useState({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),[P,F]=Z.useState(``),[I,L]=Z.useState(()=>pf()),[R,z]=Z.useState(null),[B,V]=Z.useState(``),[H,ee]=Z.useState(``),[U,te]=Z.useState(0),W=Z.useRef(0),ne=Z.useMemo(()=>[wf(I),...d.map(e=>({...e,url:ze(e.url)||e.url}))],[d,I]),re=Z.useMemo(()=>new Set(Object.keys(O)),[O]),ae=Z.useMemo(()=>ne.filter(e=>e.id===sf||je(e,re)),[ne,re]);Z.useEffect(()=>i(()=>te(e=>e+1)),[]);let oe=Z.useMemo(()=>Tf(ne),[ne,U]),se=Z.useMemo(()=>o().startsWith(`relay:`),[U]),ce=Z.useMemo(()=>{let e=p||sf;return ne.find(t=>t.id===e)?.label||a(`desktopHostSwitcher.instance.local`)},[ne,p,a]),le=Z.useCallback(async(e,t)=>{if(he()){S(!0),F(``);try{let n=e.filter(e=>e.id!==sf);await Pe({hosts:n,defaultHostId:t}),f(n),m(t)}catch(e){F(e instanceof Error?e.message:a(`desktopHostSwitcher.error.failedToSave`))}finally{S(!1)}}},[a]),ue=Z.useCallback(()=>{c(`remote-instances`),s(!0),t(!1)},[t,s,c]),de=Z.useCallback(async()=>{if(he()){v(!0),F(``);try{let[e,t,n]=await Promise.all([Be(),Zs().catch(()=>({instances:[]})),Sf()]);e.localOrigin&&L(e.localOrigin);let r={};for(let e of t.instances)r[e.id]=!0;f(e.hosts||[]),m(e.defaultHostId??null),k(r),j(n)}catch(e){F(e instanceof Error?e.message:a(`desktopHostSwitcher.error.failedToLoad`)),f([]),m(null),k({}),j({})}finally{v(!1)}}},[a]),fe=Z.useCallback(async e=>{if(he()){b(!0);try{let t=await mf(),n=await Promise.all(e.map(async e=>{let n=async()=>{let t=await Ie(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=ze(ie()?Fe(e):e.url);if(!r)return[e.id,{status:`unreachable`,latencyMs:0}];let i=e.id===sf?t:e.clientToken||``,a=await Le(r,{clientToken:i||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(_f(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;g(r)}finally{b(!1)}}},[]);Z.useEffect(()=>{if(!e){z(null),V(``),ee(``),E(null),N({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),F(``);return}de()},[e,de]),Z.useEffect(()=>{e&&fe(ae)},[e,ae,fe]),Z.useEffect(()=>{if(!e||!he())return;let t=!1,n=async()=>{let e=await Sf();t||j(e)};n();let r=window.setInterval(()=>{typeof document<`u`&&document.visibilityState!==`visible`||n()},1500);return()=>{t=!0,window.clearInterval(r)}},[e]);let pe=q(async e=>{let t=e.id===sf?I:ze(e.url)||``,n=e.id===sf?I:ze(Fe(e))||``,i=!!e.relay&&!e.apiUrl&&e.id!==sf;if(!t&&!i)return;if(ie()){if(!n&&!e.relay||C)return;let t=e.id===sf?await mf():null,i=await ec({host:e,cachedProbe:h[e.id]||null,...e.id===sf?{localApiOrigin:n,localClientToken:t}:{}});g(t=>({...t,[e.id]:i.status})),i.ok&&r?.();return}let o=!!O[e.id];if(e.id!==sf&&o&&he()){let n=A[e.id],i=await As(e.id).then(t=>t.find(t=>t.id===e.id)||null).catch(()=>null);i&&(n=i,j(t=>({...t,[e.id]:i})));let o=ze(n?.localUrl||e.url||``);if(n?.phase===`ready`&&o){let e=ff(o);r?.(),window.location.assign(e);return}E(e.id);let s=W.current+1;W.current=s,N({open:!0,hostId:e.id,hostLabel:Ne(e.label),phase:`master_connecting`,detail:null,error:null,errorCode:null});try{if(await Bs(e.id),s!==W.current)return;let n=await Cf(e.id,cf,e=>{j(t=>({...t,[e.id]:e})),N(t=>({...t,phase:e.phase,detail:e.detail||null,errorCode:e.errorCode||null}))},()=>s!==W.current);if(s!==W.current)return;let i=ff(ze(n.localUrl||``)||t);r?.(),window.location.assign(i);return}catch(t){if(s!==W.current)return;let n=t instanceof Error?t.message:String(t);if(n===lf)return;let r=Js(M.errorCode,n);N(e=>({...e,error:n,errorCode:r})),Ha.error(a(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:Ne(e.label)}),{description:Ns(a(Is(r)),r,n)});return}finally{s===W.current&&E(null)}}if(e.id!==sf&&he()){E(e.id);let n=await Le(t,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(g(t=>({...t,[e.id]:{status:n.status,latencyMs:n.latencyMs}})),_f(n.status)){Ha.error(a(`desktopHostSwitcher.toast.instanceUnreachable`,{host:Ne(e.label)})),E(null);return}}let s=ff(t);r?.();try{window.location.assign(s)}catch{window.location.href=s}}),me=Z.useCallback(()=>{z(null),V(``),ee(``)},[]),ge=Z.useCallback(e=>{e.stopPropagation()},[]),_e=Z.useCallback(async()=>{if(!R)return;if(R===sf){me();return}let e=ke(H);if(!e){F(a(`desktopHostSwitcher.error.invalidUrl`));return}let t=e.persistedUrl,n=(B||Ne(t)).trim(),r=d.map(e=>e.id===R?{...e,label:n,url:t,apiUrl:t}:e);await le(r,p),me(),e.redeemUrl&&window.location.assign(e.redeemUrl)},[me,d,p,B,H,R,le,a]),ve=Z.useCallback(async e=>{await le(d,e===sf?sf:e)},[d,le]),ye=Z.useCallback(e=>{let t=e=>{Ha.error(a(`desktopHostSwitcher.error.failedToOpenNewWindow`),{description:e instanceof Error?e.message:String(e)})};if(e.relay&&e.id!==sf){Ae(e.id).catch(t);return}let n=e.id===sf?I:Fe(e);if(!n)return;let r=ff(n);Ve(r,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(t)},[I,a]),be=q(async()=>{W.current+=1,E(null),N(e=>({...e,open:!1,hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}));let e=ff(I);if(ie()){if(C)return;let e=await mf();(await ec({host:wf(I),localApiOrigin:I,localClientToken:e})).ok&&r?.();return}r?.(),window.location.assign(e)}),xe=Z.useCallback(async()=>{let e=M.hostId||D;W.current+=1,E(null),N({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),!(!e||e===sf||!he())&&await _c(e).catch(()=>{})},[M.hostId,D]),Se=Z.useCallback(()=>{let e=M.hostId;if(!e)return;let t=ne.find(t=>t.id===e);t&&pe(t)},[ne,pe,M.hostId]),Ce=Z.useCallback(async e=>{if(he()){E(e.id);try{await Bs(e.id),(await Cf(e.id,cf,e=>{j(t=>({...t,[e.id]:e}))})).phase===`ready`&&Ha.success(a(`desktopHostSwitcher.toast.sshConnected`,{host:Ne(e.label)}))}catch(t){let n=t instanceof Error?t.message:String(t);if(n!==lf){let t=Js(null,n);Ha.error(a(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:Ne(e.label)}),{description:Ns(a(Is(t)),t,n)})}}finally{E(null)}}},[a]);if(!he())return null;let we=he(),Te=(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:Ne(oe.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:Ne(ce)})]}),(0,$.jsx)(`button`,{type:`button`,className:J(`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 fe(ae),disabled:!we||_||y,"aria-label":a(`desktopHostSwitcher.actions.refreshInstancesAria`),children:(0,$.jsx)(X,{name:`refresh`,className:J(`h-4 w-4`,y&&`animate-spin`)})})]})}):(0,$.jsxs)(Ko,{className:`flex-shrink-0`,children:[(0,$.jsxs)(Xo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`server`,className:`h-5 w-5`}),a(`desktopHostSwitcher.title`)]}),(0,$.jsx)(Zo,{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:Ne(oe.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:Ne(ce)})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,$.jsxs)(Jn,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>void fe(ae),disabled:!we||_||y,children:[(0,$.jsx)(X,{name:`refresh`,className:J(`h-4 w-4`,y&&`animate-spin`)}),a(`desktopHostSwitcher.actions.refresh`)]})})]}),!we&&(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:J(`space-y-1`,n&&`space-y-1.5 px-3 py-1`),children:_?(0,$.jsx)(`div`,{className:`px-2 py-2 text-muted-foreground text-sm`,children:a(`desktopHostSwitcher.state.loading`)}):ae.map(e=>{let t=e.id===sf,r=!!O[e.id],i=e.id===oe.id,o=(p||sf)===e.id,s=h[e.id]||null,c=A[e.id]||null,d=of({isActive:i,isSsh:r,runtimeIsConnected:l,runtimeConnectionPhase:u,currentTransportIsRelay:se,probe:s,sshPhase:c?.phase}),f=d.statusKind,m=d.showViaRelay,g=R===e.id,_=t?I:ze(e.url)||e.url,v=e.id===sf?a(`desktopHostSwitcher.instance.local`):Ne(e.label),y=e.relay&&!e.apiUrl?a(`mobile.connect.relay.badge`):Ne(_);return(0,$.jsxs)(`div`,{className:J(`app-region-no-drag 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`,g?`bg-interactive-hover/20`:`hover:bg-interactive-hover/30`),children:[(0,$.jsxs)(`button`,{type:`button`,className:J(`flex items-center gap-2 flex-1 min-w-0 text-left`,g&&`pointer-events-none opacity-70`),onClick:()=>void pe(e),disabled:D===e.id,"aria-label":a(`desktopHostSwitcher.actions.switchToAria`,{instance:v}),children:[(0,$.jsx)(`span`,{className:J(`h-2 w-2 rounded-full flex-shrink-0`,hf(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:J(`typography-micro truncate`,gf(f)),children:[a(r&&!i?xf(c?.phase):yf(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)(Jn,{type:`button`,variant:`outline`,size:`sm`,className:`h-8 px-2.5`,disabled:D===e.id,onClick:t=>{t.stopPropagation(),Ce(e)},children:[D===e.id?(0,$.jsx)(X,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(X,{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)(Os,{delayDuration:600,children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:J(`app-region-no-drag 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 ve(e.id),"aria-label":a(o?`desktopHostSwitcher.actions.defaultInstanceAria`:`desktopHostSwitcher.actions.setAsDefaultAria`),disabled:x||!o&&vf(f),children:o?(0,$.jsx)(X,{name:`star-fill`,className:`h-4 w-4`}):(0,$.jsx)(X,{name:`star`,className:`h-4 w-4`})})}),(0,$.jsx)(Ds,{sideOffset:6,children:a(o?`desktopHostSwitcher.header.default`:`desktopHostSwitcher.actions.setAsDefault`)})]}),(0,$.jsxs)(Os,{delayDuration:600,children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:J(`app-region-no-drag h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,vf(f)?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground/60 hover:text-foreground`),onClick:t=>{t.stopPropagation(),ye(e)},disabled:vf(f),"aria-label":a(`desktopHostSwitcher.actions.openInNewWindowAria`),children:(0,$.jsx)(X,{name:`window`,className:`h-4 w-4`})})}),(0,$.jsx)(Ds,{sideOffset:6,children:vf(f)?a(`desktopHostSwitcher.state.instanceUnreachable`):a(`desktopHostSwitcher.actions.openInNewWindow`)})]})]})]},e.id)})})}),we&&R&&R!==sf&&(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)(Jn,{type:`button`,variant:`outline`,size:`sm`,onClick:me,disabled:x,children:a(`desktopHostSwitcher.actions.cancel`)}),(0,$.jsxs)(Jn,{type:`button`,size:`sm`,onClick:()=>void _e(),disabled:x,children:[x?(0,$.jsx)(X,{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)(Ts,{value:B,onChange:e=>V(e.target.value),onKeyDown:ge,placeholder:a(`desktopHostSwitcher.field.labelPlaceholder`),disabled:x}),(0,$.jsx)(Ts,{value:H,onChange:e=>ee(e.target.value),onKeyDown:ge,placeholder:a(`desktopHostSwitcher.field.urlPlaceholder`),disabled:x})]})]}),(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:ue,children:[(0,$.jsx)(X,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`typography-ui-label`,children:a(`desktopHostSwitcher.actions.addInstance`)})]})}),P&&(0,$.jsx)(`div`,{className:`flex-shrink-0 typography-meta text-status-error`,children:P})]}),Ee=(0,$.jsx)($o,{open:M.open,onOpenChange:e=>{if(!e&&D){xe();return}N(t=>({...t,open:e,...e?{}:{hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}}))},children:(0,$.jsxs)(Yo,{className:`w-[min(28rem,calc(100vw-2rem))] max-w-none`,children:[(0,$.jsxs)(Ko,{children:[(0,$.jsxs)(Xo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`loader-4`,className:J(`h-4 w-4`,!M.error&&`animate-spin`)}),a(`desktopHostSwitcher.ssh.connectingTo`,{host:M.hostLabel||a(`desktopHostSwitcher.ssh.instanceFallback`)})]}),M.error?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Zo,{className:`sr-only`,children:a(qs(Js(M.errorCode,M.error)))}),(0,$.jsx)(wc,{errorCode:M.errorCode,detail:M.error})]}):(0,$.jsx)(Zo,{children:M.detail||a(xf(M.phase))})]}),M.error?(0,$.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,$.jsx)(Jn,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{ue(),xe()},children:a(`desktopHostSwitcher.sshError.openRemoteSettings`)}),(0,$.jsx)(Jn,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void be(),children:a(`desktopHostSwitcher.actions.switchToLocal`)}),(0,$.jsx)(Jn,{type:`button`,size:`sm`,onClick:Se,disabled:!M.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:Te}),Ee]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)($o,{open:e,onOpenChange:t,children:(0,$.jsx)(Yo,{className:`w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3`,children:Te})}),Ee]})}function Df(){let e=(0,Q.c)(11),[t,n]=Z.useState(!1),{t:r}=Wn();if(!he())return null;let i,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>n(!0),a=(0,$.jsx)(X,{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)(Jn,{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)(Ef,{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 Of=e=>e.shouldUseDesktopShellPasswordLogin?`locked`:`error`,kf=`/auth/session`,Af=4,jf=1500,Mf=`openchamber.uiAuth.trustDevice`,Nf=`desktop-local`,Pf=`desktop-local`,Ff=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},If=(e,t)=>{let n=ze(e),r=ze(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},Lf=()=>he(),Rf=e=>{let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`},zf=()=>{if(!he())return!1;let e=Ff();if(!e)return!1;let t=d()||(typeof window<`u`?window.location.origin:``);if(If(e,t))return!0;try{let e=ze(t);return!!(e&&Rf(new URL(e).hostname))}catch{return!1}},Bf=()=>zf()?{clientKind:Nf,dedupeKey:Pf}:{},Vf=async()=>await f(kf,{method:`GET`,credentials:`include`,headers:{Accept:`application/json`}}),Hf=()=>typeof window>`u`?!1:window.localStorage.getItem(Mf)===`true`,Uf=async(e,t)=>{let n=Lf();return await f(kf,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:`OpenChamber Desktop`,...Bf()})})},Wf=async()=>{if(!he())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`,...Bf()})}).catch(()=>null);if(!e?.ok)return``;let t=await e.json().catch(()=>null);return typeof t?.token==`string`?t.token.trim():``},Gf=()=>he()&&!zf(),Kf=async(e,t)=>{if(!he()||typeof window>`u`)return null;let r=await ee(`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}:{}}},qf=async(e,t)=>{if(!he()||!t)return;let n=await Be().catch(()=>null);if(!n)return;if(n.localOrigin&&If(n.localOrigin,e)){await Pe({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>void 0);return}let r=!1,i=n.hosts.map(n=>!If(Fe(n),e)||n.clientToken===t?n:(r=!0,{...n,clientToken:t}));r&&await Pe({hosts:i,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0)},Jf=async e=>{if(!e)return;let r=d(),i=n();await qf(r,e),s({apiBaseUrl:r,clientToken:e,requestHeaders:Object.keys(i).length>0?i:null,relay:t()})},Yf=e=>{let t=(0,Q.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},Xf=()=>{let e=(0,Q.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)(Gs,{width:120,height:120})}),e[0]=t):t=e[0],t},Zf=e=>{let t=(0,Q.c)(23),{onRetry:n,errorType:r,retryAfter:i,children:a}=e,o=r===void 0?`network`:r,{t:s}=Wn(),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)(Jn,{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)(Yf,{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],_},Qf=({children:e})=>{let{t}=Wn(),n=Z.useMemo(()=>fe(),[]),r=n,a=Z.useMemo(()=>he()&&!n,[n]),[o,s]=Z.useState(()=>r?`authenticated`:`pending`),[c,d]=Z.useState(``),[f,p]=Z.useState(!1),[m,h]=Z.useState(``),[g,_]=Z.useState(void 0),[v,y]=Z.useState(!1),[b,x]=Z.useState(js),[S,C]=Z.useState(!1),[w,T]=Z.useState(!1),[E,D]=Z.useState(()=>Hf()),[O,k]=Z.useState(null),[A,j]=Z.useState(r),M=Z.useRef(null),N=Z.useRef(r);Z.useEffect(()=>{typeof window>`u`||window.localStorage.setItem(Mf,E?`true`:`false`)},[E]);let P=Z.useCallback(async()=>{if(r)return js;try{let e=await sc();return x(e),e}catch{return x(js),js}},[r]);Z.useEffect(()=>{let e=!1;if(!r)return(async()=>{try{if(!window.isSecureContext||!rs()){e||C(!1);return}e||C(!0)}catch{e||C(!1)}})(),()=>{e=!0}},[r]);let F=Z.useRef(0),I=Z.useRef(null),L=Z.useRef(null),R=Z.useCallback(()=>{I.current!==null&&(window.clearTimeout(I.current),I.current=null)},[]),z=Z.useCallback(()=>{F.current=0,R()},[R]),B=Z.useCallback(()=>F.current>=Af?!1:(F.current+=1,R(),I.current=window.setTimeout(()=>{I.current=null,L.current?.()},jf*F.current),!0),[R]);Z.useEffect(()=>R,[R]);let V=Z.useCallback(async()=>{if(r){s(`authenticated`);return}s(e=>e===`authenticated`?e:`pending`);try{let[e,t]=await Promise.all([Vf(),P()]),n=await e.text();if(e.ok){z(),s(`authenticated`),y(!1),h(``),_(void 0);return}if(e.status===401){let e={};try{e=JSON.parse(n)}catch{e={}}z(),y(e.tunnelLocked===!0),x(t),s(`locked`),_(void 0);return}if(e.status===429){let e={};try{e=JSON.parse(n)}catch{e={}}z(),_(e.retryAfter),y(!1),s(`rate-limited`);return}if(B())return;s(`error`),y(!1)}catch(e){if(console.warn(`Failed to check session status:`,e),Of({shouldUseDesktopShellPasswordLogin:Gf()})===`locked`){s(`locked`),_(void 0),y(!1);return}if(B())return;s(`error`),y(!1)}},[P,z,B,r]);Z.useEffect(()=>{L.current=V},[V]),Z.useEffect(()=>{r||V()},[V,r]),Z.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]),Z.useEffect(()=>{if(r)return;let e=nf(e=>{l(e)&&(d(``),h(``),_(void 0),y(!1),z(),j(!1),N.current=!1,s(`pending`),V())}),t=i(t=>e.schedule(t));return()=>{t(),e.cancel()}},[V,z,r]),Z.useEffect(()=>{!r&&o===`locked`&&(N.current=!1,j(!1))},[r,o]),Z.useEffect(()=>{o===`locked`&&M.current&&(M.current.focus(),M.current.select())},[o]),Z.useEffect(()=>{if(!r&&o===`authenticated`&&!N.current){N.current=!0;let e=!1;return ef({runtimeKey:u(),initializeAppearance:ye,syncSettings:le,applyDirectory:Zd,onError:(e,t)=>{console.error(`[SessionAuthGate] ${e} settings hydration failed:`,t)}},{force:!0}).then(()=>{e||j(!0)}),()=>{e=!0}}},[r,o]);let H=async e=>{e.preventDefault(),await te(!1)},ee=Z.useCallback(async()=>{k(`register`),T(!0);try{await Fs()}finally{k(null),T(!1)}await P()},[P]),U=Z.useCallback(()=>{cc(),k(null),T(!1)},[]),te=Z.useCallback(async e=>{if(!v&&!(!c||f)){w&&U(),p(!0),h(``);try{if(Gf()){let e=await Kf(c,E);if(e?.token){d(``),y(!1),await Jf(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 Uf(c,E);if(n.ok){let r=await n.json().catch(()=>null),i=Lf(),a=``;if(i&&(a=typeof r?.clientToken==`string`&&r.clientToken.trim()?r.clientToken.trim():``,a||=(await Kf(c,E))?.token||await Wf()),d(``),y(!1),a&&await Jf(a),e&&S)try{await ee(),Ha.success(t(`sessionAuth.toast.passkeyAdded`)),s(`authenticated`);return}catch(e){if(Us(e))Ha.message(t(`sessionAuth.toast.passkeySetupCanceled`));else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);Ha.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=Gf()?await Kf(c,E):null;if(n?.token){d(``),y(!1),await Jf(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)}}},[U,w,f,v,c,ee,S,t,E]),W=Z.useCallback(async()=>{if(!(f||!S)){if(w){U();return}T(!0),k(`auth`),h(``);try{let e=await Hs(E,{issueClientToken:Lf(),clientLabel:`OpenChamber Desktop`,...Bf()}),t=Lf()&&typeof e?.clientToken==`string`&&e.clientToken.trim()?e.clientToken.trim():``;t&&await Jf(t),d(``),s(`authenticated`)}catch(e){if(Us(e))h(``);else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySignInCanceled`);h(n)}}finally{k(null),T(!1)}}},[U,w,f,S,t,E]),ne=Z.useCallback(async()=>{if(!(f||v||!S)){if(w){U();return}if(o!==`authenticated`){if(!c){h(t(`sessionAuth.error.enterPasswordForPasskey`));return}await te(!0);return}h(``);try{await ee(),Ha.success(t(`sessionAuth.toast.passkeyAdded`))}catch(e){if(Us(e)){Ha.message(t(`sessionAuth.toast.passkeySetupCanceled`));return}let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);Ha.error(n)}}},[U,te,w,f,v,c,ee,o,S,t]),re=S&&b.enabled,ie=re&&b.hasPasskeys;return o===`pending`||o===`authenticated`&&!A?(0,$.jsx)(Xf,{}):o===`error`?(0,$.jsx)(Zf,{onRetry:()=>{z(),V()},errorType:`network`,children:a&&(0,$.jsxs)(`div`,{className:`w-full max-w-xs`,children:[(0,$.jsx)(Df,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})}):o===`rate-limited`?(0,$.jsx)(Zf,{onRetry:()=>void V(),errorType:`rate-limit`,retryAfter:g}):o===`locked`?(0,$.jsx)(Yf,{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:H,className:`w-full space-y-2`,children:[ie&&(0,$.jsxs)(Jn,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>void W(),disabled:f||w&&O!==`auth`,children:[w?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(X,{name:`lock-unlock`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{children:t(w&&O===`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)(X,{name:`lock`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60`}),(0,$.jsx)(Ts,{id:`openchamber-ui-password`,ref:M,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)(Jn,{type:`submit`,size:`icon`,disabled:!c||f,"aria-label":t(f?`sessionAuth.actions.unlockingAria`:`sessionAuth.actions.unlockAria`),children:f?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(X,{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)(is,{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)(Jn,{type:`button`,variant:`ghost`,size:`sm`,className:`text-muted-foreground hover:text-foreground`,onClick:()=>void ne(),disabled:f,children:t(w&&O===`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)(is,{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)(Df,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})]})}):(0,$.jsx)($.Fragment,{children:e})},$f=e=>!!e&&typeof e==`object`&&!Array.isArray(e),ep=e=>typeof e==`string`&&e.trim()?e.trim():null,tp=e=>{if(!$f(e))throw Error(`Could not check OpenCode compatibility`);let t=e.state,n=e.installation;if(t!==`compatible`&&t!==`incompatible`&&t!==`unavailable`||n!==`managed`&&n!==`external`&&n!==`bundled`)throw Error(`Could not check OpenCode compatibility`);let r=ep(e.minimumVersion),i=ep(e.targetVersion);if(!r||!i||typeof e.canInstall!=`boolean`)throw Error(`Could not check OpenCode compatibility`);return{state:t,version:ep(e.version),installation:n,minimumVersion:r,targetVersion:i,canInstall:e.canInstall,guidance:ep(e.guidance)}},np=async()=>{let e=await f(`/api/opencode/compatibility`,{signal:AbortSignal.timeout(2e4)});if(!e.ok)throw Error(`Could not check OpenCode compatibility`);return tp(await e.json())},rp=async()=>{let e=await f(`/api/opencode/install-required`,{method:`POST`}),t=await e.json().catch(()=>null),n=$f(t)?t:null,r=ep(n?.error);if(!e.ok||n?.success!==!0||n?.upgraded!==!0)throw Error(r||`OpenCode installation failed`);let i=ep(n.version);if(!i)throw Error(r||`OpenCode installation did not report a verified version`);return{version:i}},ip=(e,t)=>e instanceof Error&&e.message.trim()?e.message.trim():t,ap=({children:e})=>{let{t}=Wn(),[n,r]=Z.useState(null),[a,o]=Z.useState(!1),[s,c]=Z.useState(null),[l,u]=Z.useState(null),d=Z.useId(),f=Z.useRef(null),p=Z.useRef(0);Z.useEffect(()=>{let e=!0,t=async()=>{let t=++p.current;try{let n=await np();if(!e||t!==p.current)return;r(n),n.state!==`incompatible`&&u(null)}catch{}finally{e&&t===p.current&&o(!0)}};t();let n=i(()=>{e&&(r(null),o(!1),c(null),u(null),t())});return()=>{e=!1,p.current+=1,n()}},[]);let m=n?.state===`incompatible`;Z.useEffect(()=>{m&&(document.getElementById(`initial-loading`)?.remove(),f.current?.focus())},[m]);let h=q(async e=>{if(s)return;let n=++p.current;c(e),u(null);try{if(e===`install`){let e=await rp();if(n!==p.current)return;if(!e.version)throw Error(t(`opencodeUpgrade.screen.failedGeneric`));window.location.reload();return}let i=await np();if(n!==p.current)return;if(i.state===`incompatible`){r(i);return}if(i.state!==`compatible`)throw Error(t(`opencodeUpgrade.screen.failedGeneric`));window.location.reload()}catch(e){if(n!==p.current)return;u(ip(e,t(`opencodeUpgrade.screen.failedGeneric`)))}finally{n===p.current&&c(null)}});if(!a)return null;if(!m||!n)return(0,$.jsx)($.Fragment,{children:e});let g=!!n.version?.startsWith(`2.`),_=n.installation===`bundled`?`opencodeUpgrade.screen.bundled`:n.installation===`external`?g?`opencodeUpgrade.screen.outdatedExternal`:`opencodeUpgrade.screen.external`:g?`opencodeUpgrade.screen.outdatedLocal`:`opencodeUpgrade.screen.local`,v=n.minimumVersion,y=s!==null;return(0,$.jsx)(`section`,{className:`app-region-drag flex h-full min-h-dvh min-h-0 items-center justify-center overflow-y-auto bg-background px-4 py-10 text-foreground select-none sm:px-6`,"aria-labelledby":d,"aria-busy":y,"data-opencode-upgrade-screen":`true`,children:(0,$.jsxs)(`div`,{className:`flex w-full max-w-sm flex-col items-center text-center`,children:[(0,$.jsx)(Gs,{width:48,height:48}),(0,$.jsx)(`h1`,{id:d,ref:f,tabIndex:-1,className:`mt-6 text-xl font-semibold tracking-tight text-balance outline-none`,children:t(g?`opencodeUpgrade.screen.outdatedTitle`:`opencodeUpgrade.screen.title`)}),(0,$.jsxs)(`p`,{className:`mt-2 text-sm leading-relaxed text-muted-foreground text-balance`,children:[t(_,{version:n.version??``,minimum:v}),n.canInstall?(0,$.jsxs)($.Fragment,{children:[` `,t(`opencodeUpgrade.screen.installDescription`,{minimum:v})]}):null]}),n.canInstall?null:(0,$.jsx)(`p`,{className:`mt-3 text-sm leading-relaxed text-muted-foreground text-balance`,children:t(`opencodeUpgrade.screen.manualGuidance`)}),n.version?(0,$.jsxs)(`div`,{className:`mt-5 inline-flex max-w-full items-center gap-2 rounded-md border border-border px-2.5 py-1 font-mono text-xs`,"aria-hidden":!0,children:[(0,$.jsx)(`span`,{className:`truncate text-muted-foreground`,children:n.version}),(0,$.jsx)(X,{name:`arrow-right`,className:`size-3.5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`text-foreground`,children:[v,`+`]})]}):null,l?(0,$.jsxs)(`p`,{role:`alert`,className:`mt-5 w-full break-words rounded-md border border-[var(--status-error)]/30 bg-[var(--status-error-background)] px-3 py-2 text-left text-sm text-[var(--status-error-text)]`,children:[(0,$.jsx)(`span`,{className:`font-medium`,children:t(`opencodeUpgrade.screen.failedTitle`)}),` `,l]}):null,(0,$.jsxs)(`div`,{className:`app-region-no-drag mt-7 flex w-full flex-wrap items-center justify-center gap-2`,children:[n.canInstall?(0,$.jsxs)(Jn,{type:`button`,disabled:y,onClick:()=>void h(`install`),children:[(0,$.jsx)(X,{name:s===`install`?`refresh`:`download`,className:s===`install`?`size-4 motion-safe:animate-spin`:`size-4`}),(0,$.jsx)(`span`,{role:s===`install`?`status`:void 0,children:s===`install`?t(g?`opencodeUpgrade.screen.updating`:`opencodeUpgrade.screen.installing`):t(g?`opencodeUpgrade.screen.update`:`opencodeUpgrade.screen.install`,{minimum:v})})]}):null,(0,$.jsxs)(Jn,{type:`button`,variant:n.canInstall?`ghost`:`default`,disabled:y,onClick:()=>void h(`reconnect`),children:[(0,$.jsx)(X,{name:`refresh`,className:s===`reconnect`?`size-4 motion-safe:animate-spin`:`size-4`}),(0,$.jsx)(`span`,{role:s===`reconnect`?`status`:void 0,children:t(s===`reconnect`?`opencodeUpgrade.screen.reconnecting`:`opencodeUpgrade.screen.reconnect`)})]})]}),(0,$.jsxs)(`a`,{className:`app-region-no-drag mt-6 inline-flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,href:`https://opencode.ai/download`,target:`_blank`,rel:`noopener noreferrer`,children:[t(`opencodeUpgrade.screen.guide`),(0,$.jsx)(X,{name:`external-link`,className:`size-3`})]}),(0,$.jsx)(`div`,{className:`app-region-no-drag mt-3 w-full`,children:(0,$.jsx)(Df,{})})]})})},op=e=>{let t=(0,Q.c)(14),{children:n}=e,r=K(sp),i=K(cp),a=K(lp),o=K(up),s=K(dp),{deviceType:c,hasTouchInput:l}=Oc(),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=typeof document<`u`&&bn(),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],Z.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 sp(e){return e.fontSize}function cp(e){return e.codeFontSize}function lp(e){return e.applyTypography}function up(e){return e.padding}function dp(e){return e.applyPadding}var fp=e(tt(),1),pp=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}`},mp=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-izZjgkkg.js","assets/rolldown-runtime-C0FnF6B9.js","assets/runtime-fetch-CiqQd__Y.js","assets/runtime-auth-D66yq6ie.js","assets/runtime-switch-BJM2k_uH.js","assets/vendor-base-ui-CnHfUmDN.js","assets/useUIStore-DNkuudYO.js","assets/vendor-zustand-DzRqcymP.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-Dq5ocTF8.js","assets/vendor-lodash-es-DfLbG5Af.js","assets/vendor-js-cookie-hSOiFTtX.js","assets/button-CcOoDLE1.js","assets/persistence-CwHY3fDg.js","assets/vendor-pathe-vBmvQE8f.js","assets/vendor-tanstack-query-core-BWz0ose6.js","assets/store-l_X_jQNz.js","assets/vendor-class-variance-authority-BLUaYARZ.js","assets/vendor-tailwind-merge-BicNWLTg.js","assets/dialog-Csvrld51.js","assets/Icon-BE2hkaYc.js","assets/useThemeSystem-DMzWVJaW.js","assets/markdownTheme-DM5h1i18.js","assets/appThemeRegistry-MiWlVk4e.js","assets/platform-Bxaalnc8.js","assets/vendor-opencode-client-MF2GBrFx.js","assets/useMobileNavigationStore-DYKC2swj.js","assets/vendor-tanstack-react-query-D7pys_c9.js","assets/vendor-sonner-DVzioF3d.js","assets/useAssistantUIStore-CXj8c_tt.js","assets/vendor-zod-Dzk5kdUU.js","assets/vendor-fuse.js-DB5wDJbI.js","assets/MarkdownRenderer-H1MIHXzt.js","assets/markdownHeightCache-DhLhFBWX.js","assets/dualLimitLru-D8Sphgua.js","assets/markdown-worker-bS5OgGO3.js","assets/useEffectiveDirectory-DNbDaaNV.js","assets/imageSource-BpUsiwFd.js","assets/relay-image-stream-D2XooXKZ.js","assets/useWorkerHighlightedLines-BoyYALWC.js","assets/tooltip-CBHR50fA.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-BJM2k_uH.js";import{n as f}from"./runtime-fetch-CiqQd__Y.js";import{$ as p,At as m,C as h,E as g,F as _,G as v,H as y,Ht as b,I as x,J as S,O as C,On as w,P as T,Pt as E,Q as D,S as O,T as k,Tt as A,V as j,W as M,X as N,Y as P,Z as F,Zt as I,_ as L,at as R,b as z,c as B,d as V,dt as H,en as ee,et as U,f as te,ft as W,h as ne,ht as re,in as ie,it as ae,jt as oe,kt as se,lt as ce,n as le,nn as ue,nt as de,on as fe,pt as pe,r as me,rn as he,rt as ge,sn as _e,st as ve,t as ye,ut as be,vt as xe,w as Se,wt as Ce,x as we,y as Te,yt as Ee,z as De,zt as Oe}from"./persistence-CwHY3fDg.js";import{_ as ke,c as Ae,d as je,f as Me,h as Ne,i as Pe,l as Fe,m as Ie,n as Le,o as Re,p as ze,r as Be,s as Ve}from"./desktopHosts-BsbquPqS.js";import{r as He}from"./desktopRelayRestore-yyvjztgj.js";import{a as Ue,i as We,o as Ge,r as Ke,s as qe,t as Je}from"./vendor-zustand-DzRqcymP.js";import{c as Ye,d as Xe,f as Ze,l as Qe,nt as $e,rt as et,tt,u as nt}from"./vendor-base-ui-CnHfUmDN.js";import{Ai as rt,An as it,At as at,Bn as ot,Ci as st,Cn as ct,Ct as lt,Dn as ut,Ei as dt,En as ft,Er as pt,Fi as mt,Fn as ht,Hn as gt,Ii as _t,It as vt,Li as yt,Lt as bt,Nt as xt,Ot as St,Pn as Ct,Qt as wt,St as Tt,Ti as Et,Tn as Dt,Tr as Ot,Wn as kt,Xt as At,Yt as jt,an as Mt,bi as Nt,bn as Pt,br as Ft,cn as It,en as Lt,fn as Rt,gr as zt,hn as Bt,jr as Vt,jt as Ht,kn as Ut,kr as Wt,kt as Gt,lr as Kt,mi as qt,mn as Jt,n as Yt,nn as Xt,on as Zt,pn as Qt,qt as $t,rn as en,sn as tn,t as nn,tn as rn,tr as an,vi as on,vr as sn,wn as cn,wr as ln,xn as un,xr as dn,yn as fn,yr as pn,zn as mn}from"./platform-Bxaalnc8.js";import{_ as hn,b as gn,c as _n,f as vn,g as G,h as yn,n as K,y as bn}from"./useUIStore-DNkuudYO.js";import{n as xn}from"./vendor-react-DLPElpoQ.js";import{o as Sn}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{c as Cn,i as wn,n as Tn,s as En,t as Dn}from"./vendor-tanstack-react-query-D7pys_c9.js";import{B as On,R as kn,V as An,c as jn}from"./vendor-codemirror-autocomplete-DHomsvW7.js";import{i as Mn,u as Nn}from"./vendor-pierre-diffs-DX7XTPG3.js";import{t as Pn}from"./vendor-sonner-DVzioF3d.js";import{a as Fn,f as In,i as Ln,m as Rn,n as q,o as zn,r as Bn,u as Vn}from"./vendor-reactuses-core-Dq5ocTF8.js";import{_ as Hn,d as Un,f as Wn,i as Gn,l as Kn,p as qn,r as J,t as Jn,v as Yn}from"./button-CcOoDLE1.js";import{i as Xn,t as Zn}from"./store-l_X_jQNz.js";import{$ as Qn,$i as $n,$r as er,$t as tr,A as nr,Ai as rr,At as ir,B as ar,Bi as or,Br as sr,Bt as cr,C as lr,Ca as ur,Ci as dr,Cn as fr,Ct as pr,D as mr,Da as hr,Di as gr,Dn as _r,Dr as vr,Dt as yr,E as br,Ea as xr,Ei as Sr,En as Cr,Er as wr,Et as Tr,F as Er,Fa as Dr,Fi as Or,Fn as kr,G as Ar,Gi as jr,Gr as Mr,Gt as Nr,H as Pr,Hi as Fr,Hn as Ir,I as Lr,Ii as Rr,In as zr,It as Br,J as Vr,Ji as Hr,Jt as Ur,K as Wr,Ki as Gr,Kt as Kr,L as qr,Li as Jr,Ln as Yr,Lr as Xr,Lt as Zr,M as Qr,Ma as $r,Mn as ei,Mt as ti,N as ni,Ni as ri,Nn as ii,Nt as ai,O as oi,Oa as si,Oi as ci,On as li,Ot as ui,P as di,Pa as fi,Pi as pi,Pn as mi,Q as hi,Qi as gi,Qn as _i,Qr as vi,Qt as yi,R as bi,Ra as xi,Ri as Si,Rn as Ci,Rr as wi,Rt as Ti,Sa as Ei,Si as Di,St as Oi,Ta as ki,Ti as Ai,Tn as ji,Tt as Mi,U as Ni,Ui as Pi,Un as Fi,Ur as Ii,Ut as Li,V as Ri,Vi as zi,W as Bi,Wi as Vi,Wr as Hi,Wt as Ui,X as Wi,Xa as Gi,Xi as Ki,Xn as qi,Xt as Ji,Y as Yi,Yi as Xi,Yr as Zi,Z as Qi,Zi as $i,Zn as ea,Zr as ta,Zt as na,_n as ra,aa as ia,ai as aa,an as oa,at as sa,ba as ca,bi as la,bn as ua,bt as da,c as fa,ci as pa,cn as ma,ct as ha,d as Y,di as ga,dn as _a,do as va,dr as ya,ea as ba,ei as xa,en as Sa,eo as Ca,er as wa,et as Ta,fa as Ea,fi as Da,fn as Oa,fr as ka,g as Aa,gi as ja,gn as Ma,gt as Na,ha as Pa,hn as Fa,ht as Ia,i as La,ii as Ra,in as za,it as Ba,j as Va,jr as Ha,jt as Ua,k as Wa,ki as Ga,kt as Ka,la as qa,lt as Ja,m as Ya,mi as Xa,mn as Za,mr as Qa,n as $a,ni as eo,nt as to,oi as no,on as ro,ot as io,pa as ao,pi as oo,pn as so,pr as co,q as lo,qi as uo,qr as fo,qt as po,r as mo,rn as ho,rt as go,s as _o,sn as vo,so as yo,st as bo,ta as xo,ti as So,to as Co,tt as wo,ua as To,ui as Eo,un as Do,uo as Oo,v as ko,vn as Ao,vt as jo,w as Mo,wa as No,wn as Po,wt as Fo,xa as Io,xi as Lo,xt as Ro,ya as zo,yn as Bo,yt as Vo,z as Ho,zi as Uo,zn as Wo,zr as Go}from"./useMobileNavigationStore-DYKC2swj.js";import{a as Ko,i as qo,l as Jo,n as Yo,o as Xo,r as Zo,s as Qo,t as $o}from"./dialog-Csvrld51.js";import{t as es}from"./AgentAvatar-DGyF86jy.js";import{n as X}from"./Icon-BE2hkaYc.js";import{E as ts,n as ns}from"./gitApi-DpwH7xTg.js";import{a as rs}from"./vendor-simplewebauthn-browser-Dwhcdg_5.js";import{A as is,C as as,D as os,O as ss,S as cs,_ as ls,a as us,b as ds,f as fs,h as ps,i as ms,k as hs,l as gs,m as _s,n as vs,o as ys,s as bs,u as xs,w as Ss,x as Cs,y as ws}from"./projectMeta-BhKfv5cj.js";import{t as Ts}from"./input-C6Y7mytw.js";import{i as Es,n as Ds,t as Os}from"./tooltip-CBHR50fA.js";import{$ as ks,$t as As,At as js,B as Ms,Bt as Ns,F as Ps,Ft as Fs,Ht as Is,I as Ls,J as Rs,K as zs,Kt as Bs,L as Vs,Ot as Hs,Pt as Us,Q as Ws,Rt as Gs,St as Ks,Ut as qs,Vt as Js,X as Ys,Y as Xs,Yt as Zs,Z as Qs,_t as $s,an as ec,at as tc,et as nc,ft as rc,gt as ic,i as ac,it as oc,jt as sc,kt as cc,l as lc,lt as uc,mt as dc,n as fc,nt as pc,on as mc,pt as hc,q as gc,qt as _c,rt as vc,sn as yc,t as bc,tt as xc,ut as Sc,z as Cc,zt as wc}from"./useSessionAutoCleanup-BI0xQcio.js";import{n as Tc,r as Ec,t as Dc}from"./useThemeSystem-DMzWVJaW.js";import{i as Oc,t as kc}from"./OverlayScrollbar-CVgW_Z9B.js";import{a as Ac,c as jc,i as Mc,l as Nc,n as Pc,o as Fc,r as Ic,s as Lc}from"./markdownTheme-DM5h1i18.js";import{n as Rc,r as zc,t as Bc}from"./useRuntimeAPIs-DSLXJybW.js";import{S as Vc,i as Hc,n as Uc,r as Wc}from"./textarea-DUjc3iDJ.js";import{A as Gc,C as Kc,D as qc,O as Jc,S as Yc,T as Xc,_ as Zc,a as Qc,b as $c,c as el,d as tl,f as nl,g as rl,h as il,j as al,k as ol,l as sl,m as cl,o as ll,p as ul,s as dl,u as fl,v as pl,w as ml,x as hl,y as gl}from"./sessionChangeSummary-Cgq9RPUq.js";import{C as _l,D as vl,E as yl,O as bl,S as xl,T as Sl,a as Cl,b as wl,c as Tl,d as El,f as Dl,i as Ol,j as kl,k as Al,l as jl,n as Ml,o as Nl,p as Pl,r as Fl,s as Il,t as Ll,u as Rl,w as zl,x as Bl,y as Vl}from"./insertionBoundaries-Cst5Z6Cd.js";import{a as Hl,c as Ul,i as Wl,o as Gl,s as Kl}from"./fileMentionTouchSelection-Bn0f83D3.js";import{A as ql,C as Jl,D as Yl,E as Xl,N as Zl,O as Ql,S as $l,T as eu,_ as tu,b as nu,c as ru,d as iu,f as au,g as ou,h as su,i as cu,k as lu,l as uu,m as du,o as fu,p as pu,s as mu,t as hu,u as gu,v as _u,w as vu,x as yu,y as bu}from"./appThemeRegistry-MiWlVk4e.js";import{a as xu,n as Su,o as Cu,r as wu,t as Tu}from"./MarkdownRenderer-H1MIHXzt.js";import{_ as Eu,a as Du,c as Ou,g as ku,l as Au,o as ju,t as Mu,v as Nu,y as Pu}from"./vendor-dnd-kit-core-CvWxUPdb.js";import{i as Fu,n as Iu,o as Lu,s as Ru,t as zu}from"./vendor-dnd-kit-sortable-hHdP9lLb.js";import{a as Bu,n as Vu,t as Hu}from"./url-CEnO45_n.js";import{a as Uu,l as Wu,m as Gu,u as Ku}from"./markdown-worker-bS5OgGO3.js";import{n as qu,t as Ju}from"./useEffectiveDirectory-DNbDaaNV.js";import{a as Yu,c as Xu,d as Zu,f as Qu,i as $u,l as ed,n as td,r as nd,s as rd,t as id}from"./FadeInOnReveal-B_a083XJ.js";import{c as ad,f as od,l as sd,m as cd,n as ld,p as ud,r as dd,s as fd,u as pd}from"./imageSource-BpUsiwFd.js";import{A as md,C as hd,D as gd,E as _d,M as vd,O as yd,S as bd,T as xd,a as Sd,b as Cd,c as wd,g as Td,h as Ed,i as Dd,j as Od,k as kd,o as Ad,p as jd,r as Md,s as Nd,t as Pd,v as Fd,w as Id,x as Ld,y as Rd}from"./useWorkerHighlightedLines-BoyYALWC.js";import{t as zd}from"./vendor-cmdk-CeAGfrLo.js";import{t as Bd}from"./sortable-tabs-strip-CKKp4p3Y.js";import{a as Vd}from"./markdownHeightCache-DhLhFBWX.js";import{t as Hd}from"./dualLimitLru-D8Sphgua.js";import{n as Ud,t as Wd}from"./vendor-tanstack-react-virtual-tlDgH6PG.js";import{i as Gd,t as Kd}from"./vendor-framer-motion-DFy_BSVd.js";import{t as qd}from"./vendor-legendapp-list-WE32lwNk.js";import{n as Jd,t as Yd}from"./useFontPreferences-DGbTdGy3.js";var Xd=e=>{if(typeof e!=`string`)return;let t=e.trim();if(t)return{location:{directory:t}}};typeof window<`u`&&(window.__opencodeDebug={getLastAssistantMessage(){let e=Y.getState().currentSessionId;if(!e)return null;let t=mn(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=(ot(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:(ot(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=Y.getState().currentSessionId;if(!t)return[];let n=mn(t);return`${n.length}`,n.forEach((e,t)=>{let n=ot(e.id)||[];`${t}${e.role}${e.id}${n.length}`}),e?this.truncateMessages(n):n},async getAppStatus(){let e=lt.getState(),t=Y.getState(),n=Co.getState(),r=e.currentDirectory||null,i=xt.getDirectory()??null,a=gt(),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=w(),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,g=null,_=null,v=null;try{let e=await xt.getSdkClient().location.get(Xd(r));h=bt(e)}catch(e){h={error:e instanceof Error?e.message:String(e)}}try{g=(await xt.getSdkClient().location.get(Xd(r)))?.project??null}catch(e){g={error:e instanceof Error?e.message:String(e)}}_=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}v={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){v={error:e instanceof Error?e.message:String(e)}}let y={isGitRepo:null};if(r)try{y.isGitRepo=await ns(r)}catch(e){y={isGitRepo:null,error:e instanceof Error?e.message:String(e)}}let b=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:b},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:y,localStorage:c,opencode:{pathInfo:h,projectInfo:g,health:v},openchamber:{settingsInfo:_}}},async buildDiagnosticsReport(){let e=await this.getAppStatus();return JSON.stringify(e,null,2)},async copyTextToClipboard(e){return Un(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=Y.getState(),t=ei.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=Y.getState().currentSessionId;if(!e)return[];let t=mn(e).filter(e=>e.role===`assistant`).filter(e=>{let t=ot(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=ot(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=Y.getState().currentSessionId;if(!i)return{summary:null,rows:[]};let a=mn(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=ot(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=Y.getState().currentSessionId;if(!e)return null;let t=mn(e).filter(e=>e.role===`assistant`);if(t.length===0)return null;let n=t[t.length-1],r=(ot(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=ei.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}}},St(),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 Z=e(et(),1),Q=xn(),Zd=async()=>{if(typeof window>`u`)return;let e=null;try{e=Oe(`lastDirectory`)}catch(e){console.warn(`Failed to read saved directory preferences:`,e)}e&&!fe()&<.getState().setDirectory(e,{showOverlay:!1})},Qd=new Map,$d=e=>Qd.get(e)??null,ef=({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:i},a={})=>{let o=Qd.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 Qd.set(e,s),s},tf=async({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,startWatchers:i,onError:a})=>{await ef({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:a})&&i()},nf=(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 rf(e){return!e||e===`idle`?null:e===`ready`?`ok`:e===`error`?`unreachable`:`auth`}function af(e,t){let n=e.via===`relay`;return t?n:!n}function of(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?rf(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||af(o,a))&&(u=Math.max(0,Math.round(o.latencyMs))),{statusKind:c,showViaRelay:l,latencyMs:u}}var $=$e(),sf=`local`,cf=9e4,lf=`SSH connection cancelled`,uf=e=>He(e),df={},ff=e=>{let t=ze(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}},pf=()=>typeof window>`u`?``:window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,mf=async()=>ie()?Re().catch(()=>``):``,hf=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`,gf=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`,_f=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,vf=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,yf=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`,bf=e=>new Promise(t=>window.setTimeout(t,e)),xf=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`}},Sf=async()=>{let e=await As().catch(()=>[]),t={};for(let n of e)t[n.id]=n;return t},Cf=async(e,t,n,r)=>{let i=Date.now()+t;for(;Date.now()<i;){if(r?.())throw Error(lf);let t=(await As(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 bf(700)}throw r?.()?Error(lf):Error(`Timed out waiting for SSH connection`)},wf=e=>({id:sf,label:`Local`,url:e||pf()}),Tf=e=>{let t=typeof window>`u`?``:window.location.href,n=e.find(e=>e.id===sf)?.url||pf(),r=d(),i=ze(n)||n,a=ze(t)||t,o=u(),s=e.find(e=>e.relay&&uf(e)===o);if(s)return{id:s.id,label:s.label,url:s.url};if(r&&Me(r,n))return{id:sf,label:`Local`,url:i};let c=e.find(e=>r?Me(r,Fe(e)):!1);if(c)return{id:c.id,label:c.label,url:ze(Fe(c))||Fe(c)};if(t&&Me(t,n))return{id:sf,label:`Local`,url:i};let l=e.find(e=>t?Me(t,e.url):!1);return l?{id:l.id,label:l.label,url:ze(l.url)||l.url}:t.startsWith(`openchamber-ui://`)?{id:sf,label:`Local`,url:i}:{id:`custom`,label:Ne(a||`Instance`),url:a}};function Ef({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){let{t:a}=Wn(),s=K(e=>e.setSettingsDialogOpen),c=K(e=>e.setSettingsPage),l=ao(e=>e.isConnected),u=ao(e=>e.connectionPhase),[d,f]=Z.useState([]),[p,m]=Z.useState(null),[h,g]=Z.useState(()=>({...df}));Z.useEffect(()=>{Object.assign(df,h)},[h]);let[_,v]=Z.useState(!1),[y,b]=Z.useState(!1),[x,S]=Z.useState(!1),C=mc(),w=yc(),[T,E]=Z.useState(null),D=T||w,[O,k]=Z.useState({}),[A,j]=Z.useState({}),[M,N]=Z.useState({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),[P,F]=Z.useState(``),[I,L]=Z.useState(()=>pf()),[R,z]=Z.useState(null),[B,V]=Z.useState(``),[H,ee]=Z.useState(``),[U,te]=Z.useState(0),W=Z.useRef(0),ne=Z.useMemo(()=>[wf(I),...d.map(e=>({...e,url:ze(e.url)||e.url}))],[d,I]),re=Z.useMemo(()=>new Set(Object.keys(O)),[O]),ae=Z.useMemo(()=>ne.filter(e=>e.id===sf||je(e,re)),[ne,re]);Z.useEffect(()=>i(()=>te(e=>e+1)),[]);let oe=Z.useMemo(()=>Tf(ne),[ne,U]),se=Z.useMemo(()=>o().startsWith(`relay:`),[U]),ce=Z.useMemo(()=>{let e=p||sf;return ne.find(t=>t.id===e)?.label||a(`desktopHostSwitcher.instance.local`)},[ne,p,a]),le=Z.useCallback(async(e,t)=>{if(he()){S(!0),F(``);try{let n=e.filter(e=>e.id!==sf);await Pe({hosts:n,defaultHostId:t}),f(n),m(t)}catch(e){F(e instanceof Error?e.message:a(`desktopHostSwitcher.error.failedToSave`))}finally{S(!1)}}},[a]),ue=Z.useCallback(()=>{c(`remote-instances`),s(!0),t(!1)},[t,s,c]),de=Z.useCallback(async()=>{if(he()){v(!0),F(``);try{let[e,t,n]=await Promise.all([Be(),Zs().catch(()=>({instances:[]})),Sf()]);e.localOrigin&&L(e.localOrigin);let r={};for(let e of t.instances)r[e.id]=!0;f(e.hosts||[]),m(e.defaultHostId??null),k(r),j(n)}catch(e){F(e instanceof Error?e.message:a(`desktopHostSwitcher.error.failedToLoad`)),f([]),m(null),k({}),j({})}finally{v(!1)}}},[a]),fe=Z.useCallback(async e=>{if(he()){b(!0);try{let t=await mf(),n=await Promise.all(e.map(async e=>{let n=async()=>{let t=await Ie(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=ze(ie()?Fe(e):e.url);if(!r)return[e.id,{status:`unreachable`,latencyMs:0}];let i=e.id===sf?t:e.clientToken||``,a=await Le(r,{clientToken:i||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(_f(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;g(r)}finally{b(!1)}}},[]);Z.useEffect(()=>{if(!e){z(null),V(``),ee(``),E(null),N({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),F(``);return}de()},[e,de]),Z.useEffect(()=>{e&&fe(ae)},[e,ae,fe]),Z.useEffect(()=>{if(!e||!he())return;let t=!1,n=async()=>{let e=await Sf();t||j(e)};n();let r=window.setInterval(()=>{typeof document<`u`&&document.visibilityState!==`visible`||n()},1500);return()=>{t=!0,window.clearInterval(r)}},[e]);let pe=q(async e=>{let t=e.id===sf?I:ze(e.url)||``,n=e.id===sf?I:ze(Fe(e))||``,i=!!e.relay&&!e.apiUrl&&e.id!==sf;if(!t&&!i)return;if(ie()){if(!n&&!e.relay||C)return;let t=e.id===sf?await mf():null,i=await ec({host:e,cachedProbe:h[e.id]||null,...e.id===sf?{localApiOrigin:n,localClientToken:t}:{}});g(t=>({...t,[e.id]:i.status})),i.ok&&r?.();return}let o=!!O[e.id];if(e.id!==sf&&o&&he()){let n=A[e.id],i=await As(e.id).then(t=>t.find(t=>t.id===e.id)||null).catch(()=>null);i&&(n=i,j(t=>({...t,[e.id]:i})));let o=ze(n?.localUrl||e.url||``);if(n?.phase===`ready`&&o){let e=ff(o);r?.(),window.location.assign(e);return}E(e.id);let s=W.current+1;W.current=s,N({open:!0,hostId:e.id,hostLabel:Ne(e.label),phase:`master_connecting`,detail:null,error:null,errorCode:null});try{if(await Bs(e.id),s!==W.current)return;let n=await Cf(e.id,cf,e=>{j(t=>({...t,[e.id]:e})),N(t=>({...t,phase:e.phase,detail:e.detail||null,errorCode:e.errorCode||null}))},()=>s!==W.current);if(s!==W.current)return;let i=ff(ze(n.localUrl||``)||t);r?.(),window.location.assign(i);return}catch(t){if(s!==W.current)return;let n=t instanceof Error?t.message:String(t);if(n===lf)return;let r=Js(M.errorCode,n);N(e=>({...e,error:n,errorCode:r})),Ha.error(a(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:Ne(e.label)}),{description:Ns(a(Is(r)),r,n)});return}finally{s===W.current&&E(null)}}if(e.id!==sf&&he()){E(e.id);let n=await Le(t,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(g(t=>({...t,[e.id]:{status:n.status,latencyMs:n.latencyMs}})),_f(n.status)){Ha.error(a(`desktopHostSwitcher.toast.instanceUnreachable`,{host:Ne(e.label)})),E(null);return}}let s=ff(t);r?.();try{window.location.assign(s)}catch{window.location.href=s}}),me=Z.useCallback(()=>{z(null),V(``),ee(``)},[]),ge=Z.useCallback(e=>{e.stopPropagation()},[]),_e=Z.useCallback(async()=>{if(!R)return;if(R===sf){me();return}let e=ke(H);if(!e){F(a(`desktopHostSwitcher.error.invalidUrl`));return}let t=e.persistedUrl,n=(B||Ne(t)).trim(),r=d.map(e=>e.id===R?{...e,label:n,url:t,apiUrl:t}:e);await le(r,p),me(),e.redeemUrl&&window.location.assign(e.redeemUrl)},[me,d,p,B,H,R,le,a]),ve=Z.useCallback(async e=>{await le(d,e===sf?sf:e)},[d,le]),ye=Z.useCallback(e=>{let t=e=>{Ha.error(a(`desktopHostSwitcher.error.failedToOpenNewWindow`),{description:e instanceof Error?e.message:String(e)})};if(e.relay&&e.id!==sf){Ae(e.id).catch(t);return}let n=e.id===sf?I:Fe(e);if(!n)return;let r=ff(n);Ve(r,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(t)},[I,a]),be=q(async()=>{W.current+=1,E(null),N(e=>({...e,open:!1,hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}));let e=ff(I);if(ie()){if(C)return;let e=await mf();(await ec({host:wf(I),localApiOrigin:I,localClientToken:e})).ok&&r?.();return}r?.(),window.location.assign(e)}),xe=Z.useCallback(async()=>{let e=M.hostId||D;W.current+=1,E(null),N({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),!(!e||e===sf||!he())&&await _c(e).catch(()=>{})},[M.hostId,D]),Se=Z.useCallback(()=>{let e=M.hostId;if(!e)return;let t=ne.find(t=>t.id===e);t&&pe(t)},[ne,pe,M.hostId]),Ce=Z.useCallback(async e=>{if(he()){E(e.id);try{await Bs(e.id),(await Cf(e.id,cf,e=>{j(t=>({...t,[e.id]:e}))})).phase===`ready`&&Ha.success(a(`desktopHostSwitcher.toast.sshConnected`,{host:Ne(e.label)}))}catch(t){let n=t instanceof Error?t.message:String(t);if(n!==lf){let t=Js(null,n);Ha.error(a(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:Ne(e.label)}),{description:Ns(a(Is(t)),t,n)})}}finally{E(null)}}},[a]);if(!he())return null;let we=he(),Te=(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:Ne(oe.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:Ne(ce)})]}),(0,$.jsx)(`button`,{type:`button`,className:J(`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 fe(ae),disabled:!we||_||y,"aria-label":a(`desktopHostSwitcher.actions.refreshInstancesAria`),children:(0,$.jsx)(X,{name:`refresh`,className:J(`h-4 w-4`,y&&`animate-spin`)})})]})}):(0,$.jsxs)(Ko,{className:`flex-shrink-0`,children:[(0,$.jsxs)(Xo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`server`,className:`h-5 w-5`}),a(`desktopHostSwitcher.title`)]}),(0,$.jsx)(Zo,{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:Ne(oe.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:Ne(ce)})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,$.jsxs)(Jn,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>void fe(ae),disabled:!we||_||y,children:[(0,$.jsx)(X,{name:`refresh`,className:J(`h-4 w-4`,y&&`animate-spin`)}),a(`desktopHostSwitcher.actions.refresh`)]})})]}),!we&&(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:J(`space-y-1`,n&&`space-y-1.5 px-3 py-1`),children:_?(0,$.jsx)(`div`,{className:`px-2 py-2 text-muted-foreground text-sm`,children:a(`desktopHostSwitcher.state.loading`)}):ae.map(e=>{let t=e.id===sf,r=!!O[e.id],i=e.id===oe.id,o=(p||sf)===e.id,s=h[e.id]||null,c=A[e.id]||null,d=of({isActive:i,isSsh:r,runtimeIsConnected:l,runtimeConnectionPhase:u,currentTransportIsRelay:se,probe:s,sshPhase:c?.phase}),f=d.statusKind,m=d.showViaRelay,g=R===e.id,_=t?I:ze(e.url)||e.url,v=e.id===sf?a(`desktopHostSwitcher.instance.local`):Ne(e.label),y=e.relay&&!e.apiUrl?a(`mobile.connect.relay.badge`):Ne(_);return(0,$.jsxs)(`div`,{className:J(`app-region-no-drag 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`,g?`bg-interactive-hover/20`:`hover:bg-interactive-hover/30`),children:[(0,$.jsxs)(`button`,{type:`button`,className:J(`flex items-center gap-2 flex-1 min-w-0 text-left`,g&&`pointer-events-none opacity-70`),onClick:()=>void pe(e),disabled:D===e.id,"aria-label":a(`desktopHostSwitcher.actions.switchToAria`,{instance:v}),children:[(0,$.jsx)(`span`,{className:J(`h-2 w-2 rounded-full flex-shrink-0`,hf(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:J(`typography-micro truncate`,gf(f)),children:[a(r&&!i?xf(c?.phase):yf(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)(Jn,{type:`button`,variant:`outline`,size:`sm`,className:`h-8 px-2.5`,disabled:D===e.id,onClick:t=>{t.stopPropagation(),Ce(e)},children:[D===e.id?(0,$.jsx)(X,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(X,{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)(Os,{delayDuration:600,children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:J(`app-region-no-drag 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 ve(e.id),"aria-label":a(o?`desktopHostSwitcher.actions.defaultInstanceAria`:`desktopHostSwitcher.actions.setAsDefaultAria`),disabled:x||!o&&vf(f),children:o?(0,$.jsx)(X,{name:`star-fill`,className:`h-4 w-4`}):(0,$.jsx)(X,{name:`star`,className:`h-4 w-4`})})}),(0,$.jsx)(Ds,{sideOffset:6,children:a(o?`desktopHostSwitcher.header.default`:`desktopHostSwitcher.actions.setAsDefault`)})]}),(0,$.jsxs)(Os,{delayDuration:600,children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:J(`app-region-no-drag h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,vf(f)?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground/60 hover:text-foreground`),onClick:t=>{t.stopPropagation(),ye(e)},disabled:vf(f),"aria-label":a(`desktopHostSwitcher.actions.openInNewWindowAria`),children:(0,$.jsx)(X,{name:`window`,className:`h-4 w-4`})})}),(0,$.jsx)(Ds,{sideOffset:6,children:vf(f)?a(`desktopHostSwitcher.state.instanceUnreachable`):a(`desktopHostSwitcher.actions.openInNewWindow`)})]})]})]},e.id)})})}),we&&R&&R!==sf&&(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)(Jn,{type:`button`,variant:`outline`,size:`sm`,onClick:me,disabled:x,children:a(`desktopHostSwitcher.actions.cancel`)}),(0,$.jsxs)(Jn,{type:`button`,size:`sm`,onClick:()=>void _e(),disabled:x,children:[x?(0,$.jsx)(X,{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)(Ts,{value:B,onChange:e=>V(e.target.value),onKeyDown:ge,placeholder:a(`desktopHostSwitcher.field.labelPlaceholder`),disabled:x}),(0,$.jsx)(Ts,{value:H,onChange:e=>ee(e.target.value),onKeyDown:ge,placeholder:a(`desktopHostSwitcher.field.urlPlaceholder`),disabled:x})]})]}),(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:ue,children:[(0,$.jsx)(X,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`typography-ui-label`,children:a(`desktopHostSwitcher.actions.addInstance`)})]})}),P&&(0,$.jsx)(`div`,{className:`flex-shrink-0 typography-meta text-status-error`,children:P})]}),Ee=(0,$.jsx)($o,{open:M.open,onOpenChange:e=>{if(!e&&D){xe();return}N(t=>({...t,open:e,...e?{}:{hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}}))},children:(0,$.jsxs)(Yo,{className:`w-[min(28rem,calc(100vw-2rem))] max-w-none`,children:[(0,$.jsxs)(Ko,{children:[(0,$.jsxs)(Xo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`loader-4`,className:J(`h-4 w-4`,!M.error&&`animate-spin`)}),a(`desktopHostSwitcher.ssh.connectingTo`,{host:M.hostLabel||a(`desktopHostSwitcher.ssh.instanceFallback`)})]}),M.error?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Zo,{className:`sr-only`,children:a(qs(Js(M.errorCode,M.error)))}),(0,$.jsx)(wc,{errorCode:M.errorCode,detail:M.error})]}):(0,$.jsx)(Zo,{children:M.detail||a(xf(M.phase))})]}),M.error?(0,$.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,$.jsx)(Jn,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{ue(),xe()},children:a(`desktopHostSwitcher.sshError.openRemoteSettings`)}),(0,$.jsx)(Jn,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void be(),children:a(`desktopHostSwitcher.actions.switchToLocal`)}),(0,$.jsx)(Jn,{type:`button`,size:`sm`,onClick:Se,disabled:!M.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:Te}),Ee]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)($o,{open:e,onOpenChange:t,children:(0,$.jsx)(Yo,{className:`w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3`,children:Te})}),Ee]})}function Df(){let e=(0,Q.c)(11),[t,n]=Z.useState(!1),{t:r}=Wn();if(!he())return null;let i,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>n(!0),a=(0,$.jsx)(X,{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)(Jn,{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)(Ef,{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 Of=e=>e.shouldUseDesktopShellPasswordLogin?`locked`:`error`,kf=`/auth/session`,Af=4,jf=1500,Mf=`openchamber.uiAuth.trustDevice`,Nf=`desktop-local`,Pf=`desktop-local`,Ff=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},If=(e,t)=>{let n=ze(e),r=ze(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},Lf=()=>he(),Rf=e=>{let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`},zf=()=>{if(!he())return!1;let e=Ff();if(!e)return!1;let t=d()||(typeof window<`u`?window.location.origin:``);if(If(e,t))return!0;try{let e=ze(t);return!!(e&&Rf(new URL(e).hostname))}catch{return!1}},Bf=()=>zf()?{clientKind:Nf,dedupeKey:Pf}:{},Vf=async()=>await f(kf,{method:`GET`,credentials:`include`,headers:{Accept:`application/json`}}),Hf=()=>typeof window>`u`?!1:window.localStorage.getItem(Mf)===`true`,Uf=async(e,t)=>{let n=Lf();return await f(kf,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:`OpenChamber Desktop`,...Bf()})})},Wf=async()=>{if(!he())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`,...Bf()})}).catch(()=>null);if(!e?.ok)return``;let t=await e.json().catch(()=>null);return typeof t?.token==`string`?t.token.trim():``},Gf=()=>he()&&!zf(),Kf=async(e,t)=>{if(!he()||typeof window>`u`)return null;let r=await ee(`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}:{}}},qf=async(e,t)=>{if(!he()||!t)return;let n=await Be().catch(()=>null);if(!n)return;if(n.localOrigin&&If(n.localOrigin,e)){await Pe({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>void 0);return}let r=!1,i=n.hosts.map(n=>!If(Fe(n),e)||n.clientToken===t?n:(r=!0,{...n,clientToken:t}));r&&await Pe({hosts:i,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0)},Jf=async e=>{if(!e)return;let r=d(),i=n();await qf(r,e),s({apiBaseUrl:r,clientToken:e,requestHeaders:Object.keys(i).length>0?i:null,relay:t()})},Yf=e=>{let t=(0,Q.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},Xf=()=>{let e=(0,Q.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)(Gs,{width:120,height:120})}),e[0]=t):t=e[0],t},Zf=e=>{let t=(0,Q.c)(23),{onRetry:n,errorType:r,retryAfter:i,children:a}=e,o=r===void 0?`network`:r,{t:s}=Wn(),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)(Jn,{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)(Yf,{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],_},Qf=({children:e})=>{let{t}=Wn(),n=Z.useMemo(()=>fe(),[]),r=n,a=Z.useMemo(()=>he()&&!n,[n]),[o,s]=Z.useState(()=>r?`authenticated`:`pending`),[c,d]=Z.useState(``),[f,p]=Z.useState(!1),[m,h]=Z.useState(``),[g,_]=Z.useState(void 0),[v,y]=Z.useState(!1),[b,x]=Z.useState(js),[S,C]=Z.useState(!1),[w,T]=Z.useState(!1),[E,D]=Z.useState(()=>Hf()),[O,k]=Z.useState(null),[A,j]=Z.useState(r),M=Z.useRef(null),N=Z.useRef(r);Z.useEffect(()=>{typeof window>`u`||window.localStorage.setItem(Mf,E?`true`:`false`)},[E]);let P=Z.useCallback(async()=>{if(r)return js;try{let e=await sc();return x(e),e}catch{return x(js),js}},[r]);Z.useEffect(()=>{let e=!1;if(!r)return(async()=>{try{if(!window.isSecureContext||!rs()){e||C(!1);return}e||C(!0)}catch{e||C(!1)}})(),()=>{e=!0}},[r]);let F=Z.useRef(0),I=Z.useRef(null),L=Z.useRef(null),R=Z.useCallback(()=>{I.current!==null&&(window.clearTimeout(I.current),I.current=null)},[]),z=Z.useCallback(()=>{F.current=0,R()},[R]),B=Z.useCallback(()=>F.current>=Af?!1:(F.current+=1,R(),I.current=window.setTimeout(()=>{I.current=null,L.current?.()},jf*F.current),!0),[R]);Z.useEffect(()=>R,[R]);let V=Z.useCallback(async()=>{if(r){s(`authenticated`);return}s(e=>e===`authenticated`?e:`pending`);try{let[e,t]=await Promise.all([Vf(),P()]),n=await e.text();if(e.ok){z(),s(`authenticated`),y(!1),h(``),_(void 0);return}if(e.status===401){let e={};try{e=JSON.parse(n)}catch{e={}}z(),y(e.tunnelLocked===!0),x(t),s(`locked`),_(void 0);return}if(e.status===429){let e={};try{e=JSON.parse(n)}catch{e={}}z(),_(e.retryAfter),y(!1),s(`rate-limited`);return}if(B())return;s(`error`),y(!1)}catch(e){if(console.warn(`Failed to check session status:`,e),Of({shouldUseDesktopShellPasswordLogin:Gf()})===`locked`){s(`locked`),_(void 0),y(!1);return}if(B())return;s(`error`),y(!1)}},[P,z,B,r]);Z.useEffect(()=>{L.current=V},[V]),Z.useEffect(()=>{r||V()},[V,r]),Z.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]),Z.useEffect(()=>{if(r)return;let e=nf(e=>{l(e)&&(d(``),h(``),_(void 0),y(!1),z(),j(!1),N.current=!1,s(`pending`),V())}),t=i(t=>e.schedule(t));return()=>{t(),e.cancel()}},[V,z,r]),Z.useEffect(()=>{!r&&o===`locked`&&(N.current=!1,j(!1))},[r,o]),Z.useEffect(()=>{o===`locked`&&M.current&&(M.current.focus(),M.current.select())},[o]),Z.useEffect(()=>{if(!r&&o===`authenticated`&&!N.current){N.current=!0;let e=!1;return ef({runtimeKey:u(),initializeAppearance:ye,syncSettings:le,applyDirectory:Zd,onError:(e,t)=>{console.error(`[SessionAuthGate] ${e} settings hydration failed:`,t)}},{force:!0}).then(()=>{e||j(!0)}),()=>{e=!0}}},[r,o]);let H=async e=>{e.preventDefault(),await te(!1)},ee=Z.useCallback(async()=>{k(`register`),T(!0);try{await Fs()}finally{k(null),T(!1)}await P()},[P]),U=Z.useCallback(()=>{cc(),k(null),T(!1)},[]),te=Z.useCallback(async e=>{if(!v&&!(!c||f)){w&&U(),p(!0),h(``);try{if(Gf()){let e=await Kf(c,E);if(e?.token){d(``),y(!1),await Jf(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 Uf(c,E);if(n.ok){let r=await n.json().catch(()=>null),i=Lf(),a=``;if(i&&(a=typeof r?.clientToken==`string`&&r.clientToken.trim()?r.clientToken.trim():``,a||=(await Kf(c,E))?.token||await Wf()),d(``),y(!1),a&&await Jf(a),e&&S)try{await ee(),Ha.success(t(`sessionAuth.toast.passkeyAdded`)),s(`authenticated`);return}catch(e){if(Us(e))Ha.message(t(`sessionAuth.toast.passkeySetupCanceled`));else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);Ha.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=Gf()?await Kf(c,E):null;if(n?.token){d(``),y(!1),await Jf(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)}}},[U,w,f,v,c,ee,S,t,E]),W=Z.useCallback(async()=>{if(!(f||!S)){if(w){U();return}T(!0),k(`auth`),h(``);try{let e=await Hs(E,{issueClientToken:Lf(),clientLabel:`OpenChamber Desktop`,...Bf()}),t=Lf()&&typeof e?.clientToken==`string`&&e.clientToken.trim()?e.clientToken.trim():``;t&&await Jf(t),d(``),s(`authenticated`)}catch(e){if(Us(e))h(``);else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySignInCanceled`);h(n)}}finally{k(null),T(!1)}}},[U,w,f,S,t,E]),ne=Z.useCallback(async()=>{if(!(f||v||!S)){if(w){U();return}if(o!==`authenticated`){if(!c){h(t(`sessionAuth.error.enterPasswordForPasskey`));return}await te(!0);return}h(``);try{await ee(),Ha.success(t(`sessionAuth.toast.passkeyAdded`))}catch(e){if(Us(e)){Ha.message(t(`sessionAuth.toast.passkeySetupCanceled`));return}let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);Ha.error(n)}}},[U,te,w,f,v,c,ee,o,S,t]),re=S&&b.enabled,ie=re&&b.hasPasskeys;return o===`pending`||o===`authenticated`&&!A?(0,$.jsx)(Xf,{}):o===`error`?(0,$.jsx)(Zf,{onRetry:()=>{z(),V()},errorType:`network`,children:a&&(0,$.jsxs)(`div`,{className:`w-full max-w-xs`,children:[(0,$.jsx)(Df,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})}):o===`rate-limited`?(0,$.jsx)(Zf,{onRetry:()=>void V(),errorType:`rate-limit`,retryAfter:g}):o===`locked`?(0,$.jsx)(Yf,{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:H,className:`w-full space-y-2`,children:[ie&&(0,$.jsxs)(Jn,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>void W(),disabled:f||w&&O!==`auth`,children:[w?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(X,{name:`lock-unlock`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{children:t(w&&O===`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)(X,{name:`lock`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60`}),(0,$.jsx)(Ts,{id:`openchamber-ui-password`,ref:M,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)(Jn,{type:`submit`,size:`icon`,disabled:!c||f,"aria-label":t(f?`sessionAuth.actions.unlockingAria`:`sessionAuth.actions.unlockAria`),children:f?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(X,{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)(is,{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)(Jn,{type:`button`,variant:`ghost`,size:`sm`,className:`text-muted-foreground hover:text-foreground`,onClick:()=>void ne(),disabled:f,children:t(w&&O===`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)(is,{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)(Df,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})]})}):(0,$.jsx)($.Fragment,{children:e})},$f=e=>!!e&&typeof e==`object`&&!Array.isArray(e),ep=e=>typeof e==`string`&&e.trim()?e.trim():null,tp=e=>{if(!$f(e))throw Error(`Could not check OpenCode compatibility`);let t=e.state,n=e.installation;if(t!==`compatible`&&t!==`incompatible`&&t!==`unavailable`||n!==`managed`&&n!==`external`&&n!==`bundled`)throw Error(`Could not check OpenCode compatibility`);let r=ep(e.minimumVersion),i=ep(e.targetVersion);if(!r||!i||typeof e.canInstall!=`boolean`)throw Error(`Could not check OpenCode compatibility`);return{state:t,version:ep(e.version),installation:n,minimumVersion:r,targetVersion:i,canInstall:e.canInstall,guidance:ep(e.guidance)}},np=async()=>{let e=await f(`/api/opencode/compatibility`,{signal:AbortSignal.timeout(2e4)});if(!e.ok)throw Error(`Could not check OpenCode compatibility`);return tp(await e.json())},rp=async()=>{let e=await f(`/api/opencode/install-required`,{method:`POST`}),t=await e.json().catch(()=>null),n=$f(t)?t:null,r=ep(n?.error);if(!e.ok||n?.success!==!0||n?.upgraded!==!0)throw Error(r||`OpenCode installation failed`);let i=ep(n.version);if(!i)throw Error(r||`OpenCode installation did not report a verified version`);return{version:i}},ip=(e,t)=>e instanceof Error&&e.message.trim()?e.message.trim():t,ap=({children:e})=>{let{t}=Wn(),[n,r]=Z.useState(null),[a,o]=Z.useState(!1),[s,c]=Z.useState(null),[l,u]=Z.useState(null),d=Z.useId(),f=Z.useRef(null),p=Z.useRef(0);Z.useEffect(()=>{let e=!0,t=async()=>{let t=++p.current;try{let n=await np();if(!e||t!==p.current)return;r(n),n.state!==`incompatible`&&u(null)}catch{}finally{e&&t===p.current&&o(!0)}};t();let n=i(()=>{e&&(r(null),o(!1),c(null),u(null),t())});return()=>{e=!1,p.current+=1,n()}},[]);let m=n?.state===`incompatible`;Z.useEffect(()=>{m&&(document.getElementById(`initial-loading`)?.remove(),f.current?.focus())},[m]);let h=q(async e=>{if(s)return;let n=++p.current;c(e),u(null);try{if(e===`install`){let e=await rp();if(n!==p.current)return;if(!e.version)throw Error(t(`opencodeUpgrade.screen.failedGeneric`));window.location.reload();return}let i=await np();if(n!==p.current)return;if(i.state===`incompatible`){r(i);return}if(i.state!==`compatible`)throw Error(t(`opencodeUpgrade.screen.failedGeneric`));window.location.reload()}catch(e){if(n!==p.current)return;u(ip(e,t(`opencodeUpgrade.screen.failedGeneric`)))}finally{n===p.current&&c(null)}});if(!a)return null;if(!m||!n)return(0,$.jsx)($.Fragment,{children:e});let g=!!n.version?.startsWith(`2.`),_=n.installation===`bundled`?`opencodeUpgrade.screen.bundled`:n.installation===`external`?g?`opencodeUpgrade.screen.outdatedExternal`:`opencodeUpgrade.screen.external`:g?`opencodeUpgrade.screen.outdatedLocal`:`opencodeUpgrade.screen.local`,v=n.minimumVersion,y=s!==null;return(0,$.jsx)(`section`,{className:`app-region-drag flex h-full min-h-dvh min-h-0 items-center justify-center overflow-y-auto bg-background px-4 py-10 text-foreground select-none sm:px-6`,"aria-labelledby":d,"aria-busy":y,"data-opencode-upgrade-screen":`true`,children:(0,$.jsxs)(`div`,{className:`flex w-full max-w-sm flex-col items-center text-center`,children:[(0,$.jsx)(Gs,{width:48,height:48}),(0,$.jsx)(`h1`,{id:d,ref:f,tabIndex:-1,className:`mt-6 text-xl font-semibold tracking-tight text-balance outline-none`,children:t(g?`opencodeUpgrade.screen.outdatedTitle`:`opencodeUpgrade.screen.title`)}),(0,$.jsxs)(`p`,{className:`mt-2 text-sm leading-relaxed text-muted-foreground text-balance`,children:[t(_,{version:n.version??``,minimum:v}),n.canInstall?(0,$.jsxs)($.Fragment,{children:[` `,t(`opencodeUpgrade.screen.installDescription`,{minimum:v})]}):null]}),n.canInstall?null:(0,$.jsx)(`p`,{className:`mt-3 text-sm leading-relaxed text-muted-foreground text-balance`,children:t(`opencodeUpgrade.screen.manualGuidance`)}),n.version?(0,$.jsxs)(`div`,{className:`mt-5 inline-flex max-w-full items-center gap-2 rounded-md border border-border px-2.5 py-1 font-mono text-xs`,"aria-hidden":!0,children:[(0,$.jsx)(`span`,{className:`truncate text-muted-foreground`,children:n.version}),(0,$.jsx)(X,{name:`arrow-right`,className:`size-3.5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`text-foreground`,children:[v,`+`]})]}):null,l?(0,$.jsxs)(`p`,{role:`alert`,className:`mt-5 w-full break-words rounded-md border border-[var(--status-error)]/30 bg-[var(--status-error-background)] px-3 py-2 text-left text-sm text-[var(--status-error-text)]`,children:[(0,$.jsx)(`span`,{className:`font-medium`,children:t(`opencodeUpgrade.screen.failedTitle`)}),` `,l]}):null,(0,$.jsxs)(`div`,{className:`app-region-no-drag mt-7 flex w-full flex-wrap items-center justify-center gap-2`,children:[n.canInstall?(0,$.jsxs)(Jn,{type:`button`,disabled:y,onClick:()=>void h(`install`),children:[(0,$.jsx)(X,{name:s===`install`?`refresh`:`download`,className:s===`install`?`size-4 motion-safe:animate-spin`:`size-4`}),(0,$.jsx)(`span`,{role:s===`install`?`status`:void 0,children:s===`install`?t(g?`opencodeUpgrade.screen.updating`:`opencodeUpgrade.screen.installing`):t(g?`opencodeUpgrade.screen.update`:`opencodeUpgrade.screen.install`,{minimum:v})})]}):null,(0,$.jsxs)(Jn,{type:`button`,variant:n.canInstall?`ghost`:`default`,disabled:y,onClick:()=>void h(`reconnect`),children:[(0,$.jsx)(X,{name:`refresh`,className:s===`reconnect`?`size-4 motion-safe:animate-spin`:`size-4`}),(0,$.jsx)(`span`,{role:s===`reconnect`?`status`:void 0,children:t(s===`reconnect`?`opencodeUpgrade.screen.reconnecting`:`opencodeUpgrade.screen.reconnect`)})]})]}),(0,$.jsxs)(`a`,{className:`app-region-no-drag mt-6 inline-flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,href:`https://opencode.ai/download`,target:`_blank`,rel:`noopener noreferrer`,children:[t(`opencodeUpgrade.screen.guide`),(0,$.jsx)(X,{name:`external-link`,className:`size-3`})]}),(0,$.jsx)(`div`,{className:`app-region-no-drag mt-3 w-full`,children:(0,$.jsx)(Df,{})})]})})},op=e=>{let t=(0,Q.c)(14),{children:n}=e,r=K(sp),i=K(cp),a=K(lp),o=K(up),s=K(dp),{deviceType:c,hasTouchInput:l}=Oc(),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=typeof document<`u`&&bn(),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],Z.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 sp(e){return e.fontSize}function cp(e){return e.codeFontSize}function lp(e){return e.applyTypography}function up(e){return e.padding}function dp(e){return e.applyPadding}var fp=e(tt(),1),pp=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}`},mp=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=pp(e.colors.surface.muted),r=pp(e.colors.surface.subtle),i=pp(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=fe()?G:yn;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()}},hp=`openchamber:close-embedded-session-chat`,gp=`openchamber:embedded-visibility`,_p=`openchamber:embedded-visibility-request`,vp=e=>new URLSearchParams(e).get(`ocPanel`)===`session-chat`,yp=(e,t,n)=>JSON.stringify({sessionID:e,directory:t||``,readOnly:n===!0}),bp=(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()},xp=(e,t,n,r,i,a)=>{let o=yp(n,r,i),s=e.get(t);if(s?.signature===o)return s.src;let c=bp(n,r,i,a);return e.set(t,{signature:o,src:c}),c},Sp=null,Cp=()=>{if(Sp!==null)return Sp;if(typeof window>`u`)return Sp=!1,!1;try{return Sp=new URLSearchParams(window.location.search).get(`ocPanel`)===`session-chat`,Sp}catch{return Sp=!1,!1}},wp=()=>{if(!Cp())return null;try{let e=new URLSearchParams(window.location.search).get(`sessionId`);return e&&e.trim().length>0?e.trim():null}catch{return null}},Tp=()=>Cp()?new URLSearchParams(window.location.search):null,Ep=()=>typeof window>`u`||window.matchMedia(`(prefers-color-scheme: dark)`).matches,Dp=()=>{let e=Tp()?.get(`themeVariant`);return e===`dark`||e===`light`?e===`dark`:Ep()},Op=(e,t)=>t.reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e),kp=e=>typeof e==`string`&&e.trim().length>0,Ap=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(!kp(Op(e,t)))return!1;let t=Op(e,[`metadata`,`variant`]);return t===`light`||t===`dark`},jp=e=>Ap(e.currentTheme)?e.currentTheme:null,Mp=e=>jp(e)?.metadata.variant??null,Np=Fc,Pp=Ac,Fp=()=>{let e=Tp()?.get(`currentTheme`);if(!e)return null;try{let t=JSON.parse(e);return Ap(t)?t:null}catch{return null}},Ip=e=>Lc(e===`dark`),Lp=typeof window<`u`?Z.useLayoutEffect:Z.useEffect,Rp=()=>{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`)}},zp=e=>{let t=Np,n=Pp,r=`system`;if(typeof window<`u`){let e=Tp(),i=e?.get(`themeMode`),a=e?.get(`lightThemeId`),o=e?.get(`darkThemeId`),s=L(`themeMode`),c=L(`lightThemeId`),l=L(`darkThemeId`),u=L(`useSystemTheme`),d=L(`selectedThemeId`),f=L(`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=jc(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=jc(e);r&&(r.metadata.variant===`light`?t=r.metadata.id:n=r.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function Bp({children:e,defaultThemeId:t}){let n=(0,Z.useMemo)(()=>new mp,[]),[r,a]=(0,Z.useState)(()=>zp(t)),[o,s]=(0,Z.useState)(!1),[c,u]=(0,Z.useState)(()=>Dp()),[d,p]=(0,Z.useState)([]),[m]=(0,Z.useState)(()=>Fp()),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(()=>typeof window>`u`||!fe()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),x=(0,Z.useMemo)(()=>fe(),[]),S=(0,Z.useMemo)(()=>ue(),[]),C=(0,Z.useMemo)(()=>he(),[]),w=(0,Z.useMemo)(()=>typeof window>`u`?!1:Tp()!==null,[]),T=(0,Z.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),Nc.forEach(n),e},[d,m,h,x,y]),E=(0,Z.useMemo)(()=>e=>T.find(t=>t.metadata.id===e),[T]),D=(0,Z.useMemo)(()=>(e,t)=>{let n=E(e);return n&&n.metadata.variant===t?n:T.find(e=>e.metadata.variant===t)??Ip(t)},[T,E]),O=(0,Z.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]),k=q(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(Ap);p(n)}catch{}finally{v(!1)}}});(0,Z.useEffect)(()=>{k()},[k]),(0,Z.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 A=q(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)}),j=q(e=>{typeof document>`u`||document.documentElement.classList.toggle(`vscode-runtime`,e)});Lp(()=>{if(typeof window>`u`)return;let e=Rp();n.apply(O),j(x),A(O);let t=document.documentElement;return t.classList.remove(`light`,`dark`),t.classList.add(O.metadata.variant),e},[j,n,O,x,A]),(0,Z.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,Z.useEffect)(()=>{if(w||typeof window>`u`)return;Te(`themeMode`,r.themeMode),Te(`lightThemeId`,r.lightThemeId),Te(`darkThemeId`,r.darkThemeId),Te(`useSystemTheme`,String(r.themeMode===`system`)),Te(`selectedThemeId`,O.metadata.id),Te(`selectedThemeVariant`,O.metadata.variant===`light`?`light`:`dark`);let e=D(r.lightThemeId,`light`),t=D(r.darkThemeId,`dark`);Te(`splashBgLight`,e.colors.surface.background),Te(`splashFgLight`,e.colors.surface.foreground),Te(`splashBgDark`,t.colors.surface.background),Te(`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,O,D,S,w]),(0,Z.useEffect)(()=>{if(typeof window>`u`||w)return;let e=e=>{e.storageArea===window.localStorage&&(ne(e.key,`themeMode`)||ne(e.key,`lightThemeId`)||ne(e.key,`darkThemeId`))&&a(e=>{let t=L(`themeMode`),n=t===`light`||t===`dark`||t===`system`?t:e.themeMode,r=L(`lightThemeId`),i=typeof r==`string`&&r.trim().length>0?r.trim():e.lightThemeId,a=L(`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 M=q(e=>{let t=e.themeMode,n=e.lightThemeId,r=e.darkThemeId,i=Mp(e),o=jp(e);if(t!==`light`&&t!==`dark`&&t!==`system`||typeof n!=`string`||typeof r!=`string`)return;let s=n.trim(),c=r.trim();!s||!c||(Rp(),(0,fp.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,Z.useEffect)(()=>{if(typeof window>`u`)return;let e=window;return e.__openchamberApplyThemeSync=M,()=>{e.__openchamberApplyThemeSync===M&&delete e.__openchamberApplyThemeSync}},[M]),(0,Z.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||M(t.payload)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[M]),(0,Z.useEffect)(()=>{if(w||!o)return;let e=D(r.lightThemeId,`light`),t=D(r.darkThemeId,`dark`);me({themeId:O.metadata.id,themeVariant:O.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})},[O.metadata.id,O.metadata.variant,D,r.themeMode,r.lightThemeId,r.darkThemeId,w,o]),(0,Z.useEffect)(()=>{w||!C||(async()=>{await Hn(r.themeMode,O.metadata.variant)})()},[O.metadata.variant,C,r.themeMode,w]),(0,Z.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,Z.useEffect)(()=>{if(!(w||typeof window>`u`))return i(e=>{l(e)&&(a(e=>{let t=L(`themeMode`),n=t===`light`||t===`dark`||t===`system`?t:e.themeMode,r=L(`lightThemeId`),i=typeof r==`string`&&r.trim().length>0?r.trim():e.lightThemeId,a=L(`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 N=q(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`})}),P=q(e=>{a(t=>t.themeMode===e?t:{...t,themeMode:e})}),F=q(e=>{if(e){a(e=>e.themeMode===`system`?e:{...e,themeMode:`system`});return}let t=O.metadata.variant===`dark`?`dark`:`light`;a(e=>e.themeMode===t?e:{...e,themeMode:t})}),I=q(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})}),R=q(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})}),z=(0,Z.useMemo)(()=>({currentTheme:O,availableThemes:T,setTheme:N,customThemesLoading:_,reloadCustomThemes:k,isSystemPreference:r.themeMode===`system`,setSystemPreference:F,themeMode:r.themeMode,setThemeMode:P,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:I,setDarkThemePreference:R}),[T,O,_,r.darkThemeId,r.lightThemeId,r.themeMode,k,R,I,F,N,P]);return(0,$.jsx)(Ec.Provider,{value:z,children:e})}var Vp=!1,Hp=()=>{if(Vp||typeof window>`u`)return;Vp=!0;let e={showReasoningTraces:K.getState().showReasoningTraces,sessionTitleRefreshEnabled:K.getState().sessionTitleRefreshEnabled,sessionGoalEnabled:K.getState().sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:K.getState().sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:K.getState().sessionGoalDefaultBudget,collapsibleThinkingBlocks:K.getState().collapsibleThinkingBlocks,showDeletionDialog:K.getState().showDeletionDialog,nativeNotificationsEnabled:K.getState().nativeNotificationsEnabled,notificationMode:K.getState().notificationMode,notifyOnSubtasks:K.getState().notifyOnSubtasks,notifyOnCompletion:K.getState().notifyOnCompletion,notifyOnError:K.getState().notifyOnError,notifyOnQuestion:K.getState().notifyOnQuestion,notificationTemplates:K.getState().notificationTemplates,summarizeLastMessage:K.getState().summarizeLastMessage,summaryThreshold:K.getState().summaryThreshold,summaryLength:K.getState().summaryLength,maxLastMessageLength:K.getState().maxLastMessageLength,autoDeleteEnabled:K.getState().autoDeleteEnabled,autoDeleteAfterDays:K.getState().autoDeleteAfterDays,sessionRetentionAction:K.getState().sessionRetentionAction,fontSize:K.getState().fontSize,terminalFontSize:K.getState().terminalFontSize,editorFontSize:K.getState().editorFontSize,uiFont:K.getState().uiFont,monoFont:K.getState().monoFont,padding:K.getState().padding,cornerRadius:K.getState().cornerRadius,inputBarOffset:K.getState().inputBarOffset,mobileKeyboardMode:K.getState().mobileKeyboardMode,diffLayoutPreference:K.getState().diffLayoutPreference,gitChangesViewMode:K.getState().gitChangesViewMode},t=null,n=null,r=()=>{let e=t;t=null,n=null,e&&Object.keys(e).length>0&&me(e)},i=e=>{t={...t??{},...e},!n&&(n=setTimeout(r,150))};K.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)})},Up=(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},Wp=(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},Gp=(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},Kp=(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])&&Gp(e[n],t[n]))},qp=()=>{let e=K.getState();return{favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts}},Jp=(e,t)=>Up(e.favoriteModels,t.favoriteModels)&&Wp(e.hiddenModels,t.hiddenModels)&&Gp(e.collapsedModelProviders,t.collapsedModelProviders)&&Up(e.recentModels,t.recentModels)&&Gp(e.recentAgents,t.recentAgents)&&Kp(e.recentEfforts,t.recentEfforts),Yp=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()]))}),Xp=()=>{if(typeof window>`u`)return()=>{};let e=null,t=null,n=!1,r=()=>{e=null;let n=qp();t&&Jp(t,n)||(t=Yp(n),me(n).catch(()=>{}))},i=()=>{if(!n){n=!0;return}e!==null&&window.clearTimeout(e),e=window.setTimeout(r,1200)},a=K.subscribe((e,t)=>{Jp({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)}},Zp=!1,Qp=`openchamber-typography-base`,$p=()=>{if(typeof document>`u`)return;let e=`:root {\n${Object.entries(yn).map(([e,t])=>` --text-${e.replace(/([A-Z])/g,`-$1`).toLowerCase()}: ${t};`).join(`
|
|
4
4
|
`)}\n}\n`,t=document.getElementById(Qp);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=Qp,n.textContent=e,document.head.appendChild(n)},em=()=>{Zp||typeof window>`u`||(Zp=!0,$p())};function tm(e){let t=(0,Q.c)(3),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0],(0,Z.useEffect)(nm,r);let i;return t[1]===n?i=t[2]:(i=(0,$.jsx)(Cn,{client:V,children:n}),t[1]=n,t[2]=i),i}function nm(){return B(V)}var rm=15,im=2e3,am=e=>{let t=ao(e=>e.isConnected),n=ao(e=>e.providers.length),r=ao(e=>e.agents.length),i=ao(e=>e.activeDirectoryKey),a=ao(e=>e.refreshMissingCatalogs),o=e.enabled&&t&&(n===0||r===0),s=Z.useRef(0),c=Z.useRef(!1),[l,u]=Z.useState(!1),d=e.source,f=q(async()=>{if(!o||c.current)return;if(s.current>=rm){u(!0);return}let e=ao.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}}});Z.useEffect(()=>{s.current=0,c.current=!1,u(!1),o&&f()},[o,i]),Fn(f,o&&!l?im:null)},om=40,sm=20971520,cm=new Map,lm=0;function um(e){return e.length*2}function dm(e,t){let n=cm.get(e);n!==void 0&&(lm-=n),cm.delete(e),cm.set(e,t),lm+=t}function fm(e,t){let n=cm.get(e);(n!==void 0||t!==void 0)&&dm(e,t??n??0)}function pm(e){let t=cm.get(e);t!==void 0&&(cm.delete(e),lm-=t)}function mm(e,t){let n=e??new Set;for(;cm.size>om||lm>sm;){let e=cm.keys().next().value;if(!e)return;if(n.has(e)){if(fm(e),cm.size<=n.size)return;continue}pm(e),t(e)}}function hm(e,t){dm(e,t)}function gm(e){pm(e)}function _m(e,t){fm(e,t)}function vm(e){let t=new Map,n=e=>{t.delete(e),gm(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=um(n.content);return t.set(e,{...n,size:r?.isFile?r.size:void 0,mtimeMs:r?.isFile?r.mtimeMs:void 0}),hm(e,i),mm(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 _m(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 ym(e){let t=(0,Q.c)(8),{apis:n,children:r}=e,i;t[0]===n.files?i=t[1]:(i=vm(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)(zc.Provider,{value:o,children:r}),t[5]=o,t[6]=r,t[7]=s):s=t[7],s}var bm=`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))`,xm=`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))`,Sm={success:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{name:`checkbox-circle-fill`,className:`oc-toast-status-icon-desktop size-5`}),(0,$.jsx)(X,{name:`check`,className:`oc-toast-status-icon-mobile hidden size-[18px]`})]}),info:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{name:`information-fill`,className:`oc-toast-status-icon-desktop size-5`}),(0,$.jsx)(X,{name:`information`,className:`oc-toast-status-icon-mobile hidden size-[18px]`})]}),warning:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{name:`alert-fill`,className:`oc-toast-status-icon-desktop size-5`}),(0,$.jsx)(X,{name:`error-warning`,className:`oc-toast-status-icon-mobile hidden size-[18px]`})]}),error:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{name:`error-warning-fill`,className:`oc-toast-status-icon-desktop size-5`}),(0,$.jsx)(X,{name:`alert`,className:`oc-toast-status-icon-mobile hidden size-[18px]`})]})};function Cm(){let e=(0,Q.c)(2),t=wm,[n,r]=Z.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]),Z.useEffect(i,a),n}function wm(){return typeof document<`u`&&document.documentElement.classList.contains(`dark`)}function Tm(e){let t=(0,Q.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),Z.useEffect(n,r)}var Em=e=>{let t=(0,Q.c)(7),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r=Cm();Tm(r?bm:xm);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)(Pn,{theme:i,className:`toaster group`,closeButton:!1,icons:Sm,toastOptions:a,style:o,...n}),t[4]=n,t[5]=i,t[6]=s):s=t[6],s},Dm=new Map,Om=(e,t,n)=>`${+!!t}:${n}:${e.map(e=>`${e.id}\0${e.title}\0${e.subtitle??``}\0${e.badge??``}\0${e.iconName}`).join(`|`)}`,km=async e=>{let t=Yl(`--surface-foreground`);return Promise.all(e.slice(0,40).map(async e=>{let n=`${e.iconName}:${t}`,r=Dm.get(n);return r===void 0&&(r=await Ul(e.iconName,t)??``,Dm.set(n,r)),{id:e.id,title:e.title,subtitle:e.subtitle??``,badge:e.badge??``,iconBase64:r}}))},Am=[],jm=e=>void 0,Mm=()=>void 0;function Nm(e){let t=Zl()&&e.enabled&&du(e.isMobile),n=(0,Z.useRef)(null),r=(0,Z.useRef)(e.text),i=(0,Z.useRef)(!1),a=(0,Z.useRef)(-1),o=(0,Z.useRef)(null),s=(0,Z.useRef)(``),c=(0,Z.useRef)([]),l=(0,Z.useRef)(su()),u=q(e.onText),d=q(e.onSend),f=q(e.onAbort),p=q(e.onAttach),m=q(e.onFiles),h=q(e.onRemoveAttachment),g=q(e.onOpenModel),_=q(e.onCycleAgent),v=q(e.onOpenAgent),y=q(e.onScrollToBottom),b=q(e.onAutocompleteAccept??jm),x=q(e.onAutocompleteDismiss??Mm),S=q(e=>{typeof document>`u`||gu(document.documentElement,e)});mu.bind({onText:(e,t,n)=>{ql({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:Ut(e.text,e.attachments.map(e=>e.filename)),chipRanges:au(bu(e.text,e.chipHighlights),Yl(`--primary`)),appearance:typeof document>`u`?`dark`:$l(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:yu(e.agentName||void 0),agentIdenticon:Jl(e.agentName||void 0),suppressed:e.suppressed,showScrollToBottom:e.showScrollToBottom,scrollAria:e.scrollAria,autocomplete:l.current});(0,Z.useLayoutEffect)(()=>{if(!t||typeof document>`u`)return;let e=document.documentElement;return lu(e,!0),()=>{lu(e,!1)}},[t]),(0,Z.useEffect)(()=>{if(!t||typeof document>`u`)return;let e=document.documentElement,i=C();n.current=i,r.current=i.text,mu.rememberText(i.text),mu.retain(e,i);let a=fu();return()=>{n.current=null,a(),mu.release(e)}},[t]),(0,Z.useEffect)(()=>{if(!t)return;let r=!1,i=hs(e.modelId,e.providerId),a={modelIcon:``,modelLabel:e.modelLabel,modelVariantLabel:e.modelVariantLabel};if(s.current=``,n.current&&={...n.current,...a},ou().update(a),i)return eu(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},ou().update(a)}),()=>{r=!0}},[t,e.modelId,e.providerId,e.modelLabel,e.modelVariantLabel]);let w=iu(e.attachments);(0,Z.useEffect)(()=>{if(!t)return;let r=!1,i=e.attachments;if(i.length===0){c.current=[],n.current&&(n.current={...n.current,attachmentPreviews:[]},mu.rememberState(n.current)),ou().update({attachmentPreviews:[]});return}return Promise.all(i.map(async t=>{let n=t.mimeType.startsWith(`image/`)&&t.dataUrl?await vu(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},mu.rememberState(n.current)),ou().update({attachmentPreviews:e}))}),()=>{r=!0}},[t,w]);let T=e.autocompleteRows??Am,E=e.autocompleteOpen===!0,D=e.autocompleteHighlightedIndex??0,O=e.autocompleteQuery??``,k=`${Om(T,E,D)}\0${O}`;(0,Z.useEffect)(()=>{if(!t)return;let e=!1;if(!(E&&T.length>0)){let e=su();_u(l.current,e)||(l.current=e,n.current&&(n.current={...n.current,autocomplete:e},mu.rememberState(n.current)),ou().update({autocomplete:e}));return}return km(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))),query:O,highlightColor:Yl(`--primary-base`)||Yl(`--primary`),rows:t};_u(l.current,r)||(l.current=r,n.current&&(n.current={...n.current,autocomplete:r},mu.rememberState(n.current)),ou().update({autocomplete:r}))}),()=>{e=!0}},[t,k]);let A=t?bu(e.text,e.chipHighlights).map(e=>`${e.start}:${e.end}:${e.triggerLength}`).join(`|`):``;return(0,Z.useEffect)(()=>{if(!t)return;let s=C(),c=n.current;if(c&&nu(c,s)){i.current=!1,a.current=e.textPresetEpoch;return}n.current=s,mu.rememberState(s);let l=e.textPresetEpoch!==a.current;a.current=e.textPresetEpoch;let u=Ql({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=pu(c,s,u,{caret:e.caret});d&&ou().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,A]),t}var Pm=(e,t,n)=>{let r=Error(e);return r.name=`DictationStreamError`,r.retryable=t,n&&(r.reasonCode=n),r},Fm=1e4,Im=15e3,Lm=3e4,Rm=3e4,zm=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=Tt(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`))}},Fm);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`))},Im);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`))},Rm),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=Pm(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)}}},Lm))}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`,()=>{zm.cancelAllForRuntimeSwitch()});var Bm=128,Vm=`audio/pcm;rate=16000;bits=16`,Hm=()=>new Promise(e=>setTimeout(e,0)),Um=()=>{let e=Math.random().toString(36).slice(2,10);return`dic_${Date.now().toString(16)}${e}`},Wm=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??Vm,this.getStartOptions=e.getStartOptions,this.createDictationId=e.createDictationId??Um}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<Bm;){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 Hm()}}resolveDrainWaiters(){let e=this.drainWaiters;this.drainWaiters=[];for(let t of e)t()}},Gm=16e3,Km=Gm,qm=()=>{if(typeof window>`u`)return null;let e=window;return e.AudioContext||e.webkitAudioContext||null},Jm=e=>{let t=Math.max(-1,Math.min(1,e));return Math.round(t<0?t*32768:t*32767)},Ym=(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]=Jm(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]=Jm(e[i]*(1-s)+e[o]*s)}return a},Xm=(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},Zm=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)},Qm=()=>({stream:null,context:null,source:null,processor:null,gain:null,pending:new Int16Array,started:!1}),$m=e=>{if(e)try{e.disconnect()}catch{}},eh=()=>typeof navigator>`u`||typeof window>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`?!1:qm()!==null;function th(e){let t=(0,Q.c)(12),[n,r]=(0,Z.useState)(0),i=(0,Z.useRef)(e.onPcmSegment),a=(0,Z.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,Z.useEffect)(o,s);let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=Qm(),t[4]=c):c=t[4];let l=(0,Z.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=qm();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(ih);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=Ym(a,n.sampleRate,Gm);for(t.pending=Xm(t.pending,c);t.pending.length>=Km;){let e=t.pending.slice(0,Km);t.pending=t.pending.slice(Km),i.current(Zm(e))}},e.connect(a),a.connect(o),o.connect(n.destination)}catch(e){let r=e;t.getTracks().forEach(rh);try{await n.close()}catch{}throw l.current=Qm(),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{}$m(e.processor),$m(e.source),$m(e.gain),e.stream&&e.stream.getTracks().forEach(nh);let t=e.pending;if(e.pending=new Int16Array,t.length>0&&i.current(Zm(t)),e.context)try{await e.context.close()}catch{}l.current===e&&(l.current=Qm())},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,Z.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 nh(e){try{e.stop()}catch{}}function rh(e){try{e.stop()}catch{}}function ih(){}var ah=1e3,oh=e=>e instanceof Error?e:Error(String(e)),sh=()=>{let e=ao.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 ch(e={}){let{onTranscript:t,onError:n,canStart:r}=e,[i,a]=(0,Z.useState)(`idle`),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(0),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(i);(0,Z.useEffect)(()=>{m.current=i},[i]);let h=(0,Z.useRef)(``),g=(0,Z.useRef)(null),_=(0,Z.useRef)({starting:!1,confirming:!1,cancelling:!1}),v=(0,Z.useRef)(t),y=(0,Z.useRef)(n);(0,Z.useEffect)(()=>{v.current=t,y.current=n},[t,n]);let b=(0,Z.useRef)(null);b.current||=new Wm({client:zm,getStartOptions:sh});let x=(0,Z.useCallback)(()=>{g.current&&=(clearInterval(g.current),null)},[]),S=(0,Z.useCallback)(()=>{g.current||=setInterval(()=>{l(e=>e+1)},ah)},[]),C=(0,Z.useCallback)(e=>{let t=oh(e);d(t.message);let n=t.reasonCode;p(typeof n==`string`?n:null),y.current?.(t)},[]),w=(0,Z.useCallback)(()=>{d(null),p(null)},[]),T=(0,Z.useCallback)(()=>{b.current?.clearAll(),h.current=``,s(``)},[]);(0,Z.useEffect)(()=>zm.onPartial((e,t)=>{let n=b.current?.getDictationId();!n||e!==n||(h.current=t,s(t))}),[]),(0,Z.useEffect)(()=>zm.subscribeConnectionStatus(e=>{e&&m.current===`recording`&&b.current?.restartStream().catch(e=>{C(e)})}),[C]);let E=th({onPcmSegment:e=>{b.current?.enqueueSegment(e)},onError:e=>{y.current?.(e)}}),D=(0,Z.useRef)(E.stop);(0,Z.useEffect)(()=>{D.current=E.stop},[E.stop]);let O=(0,Z.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,Z.useCallback)(e=>{b.current?.hasSegments()?a(`failed`):a(`idle`),C(e)},[C]),A=(0,Z.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,Z.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,Z.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,Z.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,Z.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,Z.useCallback)(()=>{l(0),a(`idle`),m.current=`idle`,w(),T()},[w,T]);return(0,Z.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,Z.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 lh=e=>{let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`},uh=e=>{let t=(0,Q.c)(4),{volume:n}=e,{currentTheme:r}=Tc(),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},dh=e=>{let t=ao(e=>e.sttLocalModel),[n,r]=Z.useState(null);return Z.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},fh=e=>{let t=(0,Q.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}=Wn(),{currentTheme:_}=Tc(),v=ao(ph),y=K(mh),b;t[0]===y?b=t[1]:(b=dc(ic(`toggle_dictation`,y)),t[0]=y,t[1]=b);let x=b,[S]=Z.useState(hh),C=Z.useRef(null),w=Z.useRef(l),T=Z.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]),Z.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}=ch(O),V=k===`recording`&&P===`model_download_in_progress`,H=dh(V),ee=Z.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),Z.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]),Z.useLayoutEffect(W,ne);let re,ie;t[14]!==I||t[15]!==F?(re=()=>{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)},ie=[F,I],t[14]=I,t[15]=F,t[16]=re,t[17]=ie):(re=t[16],ie=t[17]),Z.useEffect(re,ie);let ae,oe;t[18]!==L||t[19]!==I||t[20]!==k?(ae=()=>{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})},oe=[k,I,L],t[18]=L,t[19]=I,t[20]=k,t[21]=ae,t[22]=oe):(ae=t[21],oe=t[22]),Z.useEffect(ae,oe);let se=Z.useRef(null),ce=Z.useRef(null),le=Z.useRef(null),[ue,de]=Z.useState(null),fe=k!==`idle`,pe=Z.useRef(f),me,he;t[23]===f?(me=t[24],he=t[25]):(me=()=>{pe.current=f},he=[f],t[23]=f,t[24]=me,t[25]=he),Z.useEffect(me,he);let ge=Z.useRef(!1),_e;t[26]===fe?_e=t[27]:(_e=()=>{if(!fe){ge.current&&(ge.current=!1,pe.current?.(null));return}let e=ce.current,t=le.current;if(!e||!t)return;let n=window.getComputedStyle(e),r=(parseFloat(n.paddingTop)||0)+(parseFloat(n.paddingBottom)||0);ge.current=!0,pe.current?.(t.offsetHeight+r),e.scrollTop=e.scrollHeight},t[26]=fe,t[27]=_e);let ve;t[28]!==N||t[29]!==fe||t[30]!==A||t[31]!==k?(ve=[fe,A,k,N],t[28]=N,t[29]=fe,t[30]=A,t[31]=k,t[32]=ve):ve=t[32],Z.useLayoutEffect(_e,ve);let ye,be;t[33]===Symbol.for(`react.memo_cache_sentinel`)?(ye=()=>()=>{ge.current&&(ge.current=!1,pe.current?.(null))},be=[],t[33]=ye,t[34]=be):(ye=t[33],be=t[34]),Z.useEffect(ye,be);let xe,Se;if(t[35]===fe?(xe=t[36],Se=t[37]):(xe=()=>{if(!fe)return;let e=se.current?.closest(`[data-chat-input-footer="true"]`);e&&e.offsetHeight>0&&de(e.offsetHeight)},Se=[fe],t[35]=fe,t[36]=xe,t[37]=Se),Z.useLayoutEffect(xe,Se),!S||!v)return null;let Ce=k!==`idle`,we;t[38]===I?we=t[39]:(we=e=>{C.current=e,I()},t[38]=I,t[39]=we);let Te=we,Ee;t[40]===R?Ee=t[41]:(Ee=()=>{C.current=`insert`,R()},t[40]=R,t[41]=Ee);let De=Ee,Oe;bb0:{if(k===`failed`){Oe=``;break bb0}if(k===`uploading`){let e;t[42]===g?e=t[43]:(e=g(`chat.dictation.processing`),t[42]=g,t[43]=e),Oe=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],Oe=e;break bb0}let e;t[47]===g?e=t[48]:(e=g(`chat.dictation.listening`),t[47]=g,t[48]=e),Oe=e}let ke=Oe,Ae;t[49]===Symbol.for(`react.memo_cache_sentinel`)?(Ae={onMouseDown:gh,onPointerDownCapture:_h},t[49]=Ae):Ae=t[49];let je=Ae,Me;t[50]!==x||t[51]!==c||t[52]!==i||t[53]!==o||t[54]!==Ce||t[55]!==h||t[56]!==F||t[57]!==g?(Me=h?(0,$.jsx)(`button`,{type:`button`,...je,className:i,onClick:()=>{F()},disabled:c||Ce,title:x?`${g(`chat.dictation.start`)} (${x})`:g(`chat.dictation.start`),"aria-label":g(`chat.dictation.start`),children:(0,$.jsx)(X,{name:`mic`,className:J(o,`text-current`)})}):null,t[50]=x,t[51]=c,t[52]=i,t[53]=o,t[54]=Ce,t[55]=h,t[56]=F,t[57]=g,t[58]=Me):Me=t[58];let Ne;t[59]!==z||t[60]!==L||t[61]!==Te||t[62]!==_||t[63]!==B||t[64]!==M||t[65]!==N||t[66]!==ue||t[67]!==i||t[68]!==a||t[69]!==o||t[70]!==Ce||t[71]!==r||t[72]!==V||t[73]!==A||t[74]!==ke||t[75]!==n||t[76]!==De||t[77]!==s||t[78]!==k||t[79]!==g||t[80]!==m||t[81]!==j?(Ne=Ce?(0,$.jsxs)(`div`,{ref:se,className:J(`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:ce,className:J(`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:le,className:J(!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)(uh,{volume:j}),(0,$.jsx)(`p`,{className:`typography-markdown md:typography-ui-label`,children:ke})]}):(0,$.jsx)(`p`,{className:`typography-markdown md:typography-ui-label`,style:{color:_.colors.surface.mutedForeground},children:ke}),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:J(`flex flex-shrink-0 items-center gap-x-3`,a),style:ue?{height:ue}: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)(uh,{volume:j}),(0,$.jsx)(`span`,{className:`typography-meta tabular-nums`,style:{color:_.colors.surface.mutedForeground},children:lh(M)})]}):k===`uploading`?(0,$.jsx)(X,{name:`loader-4`,className:`ml-1 h-4 w-4 animate-spin`,style:{color:_.colors.surface.mutedForeground}}):null,(0,$.jsx)(`div`,{className:J(`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`,...je,className:J(i,`text-muted-foreground hover:text-foreground`),onClick:()=>{L()},title:g(`chat.dictation.cancel`),"aria-label":g(`chat.dictation.cancel`),children:(0,$.jsx)(X,{name:`close`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...je,className:i,onClick:()=>Te(`insert`),title:g(`chat.dictation.insert`),"aria-label":g(`chat.dictation.insert`),children:(0,$.jsx)(X,{name:`check`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...je,className:J(i,`text-primary hover:text-primary`),onClick:()=>Te(`send`),title:g(`chat.dictation.insertAndSend`),"aria-label":g(`chat.dictation.insertAndSend`),children:(0,$.jsx)(X,{name:`send-plane-2`,className:s})})]}):k===`uploading`?(0,$.jsx)(`button`,{type:`button`,...je,className:J(i,`text-muted-foreground hover:text-foreground`),onClick:()=>{L()},title:g(`chat.dictation.cancel`),"aria-label":g(`chat.dictation.cancel`),children:(0,$.jsx)(X,{name:`close`,className:o})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,...je,className:J(i,`text-muted-foreground hover:text-foreground`),onClick:B,title:g(`chat.dictation.discard`),"aria-label":g(`chat.dictation.discard`),children:(0,$.jsx)(X,{name:`close`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...je,className:i,onClick:De,title:g(`chat.dictation.retry`),"aria-label":g(`chat.dictation.retry`),children:(0,$.jsx)(X,{name:`refresh`,className:o})}),A.trim()?(0,$.jsx)(`button`,{type:`button`,...je,className:i,onClick:()=>{C.current=`insert`,z()},title:g(`chat.dictation.insert`),"aria-label":g(`chat.dictation.insert`),children:(0,$.jsx)(X,{name:`check`,className:o})}):null]})})]})]}):null,t[59]=z,t[60]=L,t[61]=Te,t[62]=_,t[63]=B,t[64]=M,t[65]=N,t[66]=ue,t[67]=i,t[68]=a,t[69]=o,t[70]=Ce,t[71]=r,t[72]=V,t[73]=A,t[74]=ke,t[75]=n,t[76]=De,t[77]=s,t[78]=k,t[79]=g,t[80]=m,t[81]=j,t[82]=Ne):Ne=t[82];let Pe;return t[83]!==Me||t[84]!==Ne?(Pe=(0,$.jsxs)($.Fragment,{children:[Me,Ne]}),t[83]=Me,t[84]=Ne,t[85]=Pe):Pe=t[85],Pe};function ph(e){return e.dictationEnabled}function mh(e){return e.shortcutOverrides}function hh(){return!fe()&&eh()}function gh(e){return e.preventDefault()}function _h(e){e.pointerType===`touch`&&e.preventDefault()}var vh=2e3,yh=Ue((e,t)=>({pending:!1,expiresAt:null,arm:(t=vh)=>{let n=Date.now()+t;return e({pending:!0,expiresAt:n}),n},clear:()=>{!t().pending&&t().expiresAt===null||e({pending:!1,expiresAt:null})}})),bh=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}},xh=15e3,Sh=100,Ch=new Map,wh=new Map,Th=e=>`${e.runtimeKey}\n${e.directory}\n${e.sessionID}`,Eh=e=>{let t=Th(e),n=e.now??Date.now(),r=wh.get(t);if(r&&n-r.loadedAt<xh)return Promise.resolve(r.sessions);let i=Ch.get(t);if(i)return i;let a=e.request().then(e=>{for(wh.delete(t);wh.size>=Sh;){let e=wh.keys().next().value;if(typeof e!=`string`)break;wh.delete(e)}return wh.set(t,{loadedAt:Date.now(),sessions:e}),e});return Ch.set(t,a),a.then(()=>{Ch.get(t)===a&&Ch.delete(t)},()=>{Ch.get(t)===a&&Ch.delete(t)}),a},Dh=(e,t)=>e.id<t.id?-1:+(e.id>t.id),Oh=(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(Dh)},kh=30;function Ah(e){return e===`busy`||e===`retry`}var jh=new Map;function Mh(e,t=!1){return{limit:e.loadedTurns,cursor:e.kind===`has-more`?e.cursor:void 0,complete:e.kind===`exhausted`,loading:t}}function Nh(e,t){let n=dn();if(!n)return!1;let r=n.getTranscript(Vt(e,t));return r.messageOrder.length!==0&&r.messageOrder.length>Or()}function Ph(e){return!!e.force||!e.hasSession||e.shouldLoadMessages}function Fh(e,t,n){let r=[...e.getState().session],i=$n.search(r,t,e=>e.id);i.found?r[i.index]=n:r.splice(i.index,0,n),e.setState({session:r})}function Ih(){let e=Bo(),t=Nr(),n=Li(),r=(0,Z.useCallback)((t,n=e)=>`${n}\n${t}`,[e]),i=(0,Z.useCallback)((t,n=e)=>{let r=dn();if(!r||!t)return Mh({kind:`unknown`,loadedTurns:0},!1);let i=Vt(n,t),a=r.getPagination(i),o=r.getRequestState?.(i);return Mh(a.boundary,o?.status===`loading`)},[e]),a=(0,Z.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}};mi(a,t),Br(r,t),r.setState(a);for(let n of t)Ot(e,n)},[n]),o=(0,Z.useCallback)((t=e)=>{let n=jh.get(t);if(n)return jh.delete(t),jh.set(t,n),n;let r=new Set;for(jh.set(t,r);jh.size>kh;){let e=jh.keys().next().value;if(!e)break;let t=[...jh.get(e)??[]];jh.delete(e),a(e,t)}return r},[e,a]),s=(0,Z.useCallback)((r,i=e)=>{let s=i===e?t:n.ensureChild(i,{bootstrap:!1}),c=o(i),l=kr(s.getState()),u=ri(),d=zr({seen:c,keep:r,limit:u,preserve:l});if(a(i,d),pi()){let e=new Set([r,...c,...l]),t=(dn()?.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:Nh(i,t));if(n.length>0){for(let e of n)c.delete(e);a(i,n)}}},[n,e,o,a,t]),c=(0,Z.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 pn(a,r):await pt(a,r)}catch{return}if(i?.isStale?.())return;let u=dn()?.getTranscript(Vt(a,r));Da({directory:a,sessionID:r,store:o,transcript:u,isStale:i?.isStale}),await rr({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,Z.useCallback)(async(t,i)=>{await Oo();let a=typeof i==`boolean`?i:i?.force,o=typeof i==`object`?i.directory??e:e,l=n.ensureChild(o,{bootstrap:!1}),u=xt.getScopedSdkClient(o);s(t,o);let d=r(t,o);return bh.run({scope:l,key:d,request:async e=>{let n=l.getState(),r=dn(),i=Vt(o,t),s=r?.hasSession?.(i)??(r?.getTranscript(i).messageOrder.length??0)>0,d=r?.getPagination(i)?.boundary??{kind:`unknown`,loadedTurns:0},f=$n.search(n.session,t,e=>e.id).found,p=r?.getRequestState?.(i);if(!a&&s&&d.kind!==`unknown`&&p?.status!==`error`&&f&&Jr(o,t)){Da({directory:o,sessionID:t,store:l,isStale:e});return}let m=!!(a||!s||f),h=Ph({hasSession:f,shouldLoadMessages:m,force:!!a});await Promise.all([h?(async()=>{try{let n=await To(async()=>u.session.get({sessionID:t}));if(n&&!e()){let r=qa(mt(n));e()||Fh(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,Z.useCallback)(async(t,r)=>{let i=r||e;if(!t||!i)return;let a=n.ensureChild(i,{bootstrap:!1}),o=xt.getScopedSdkClient(i),s=await Eh({runtimeKey:u(),directory:i,sessionID:t,request:async()=>((await o.session.list({directory:i,parentID:t})).data??[]).map(mt)});a.setState(e=>{let n=Oh(e.session,s,t);return n===e.session?e:{session:n,limit:Math.max(e.limit,n.length)}})},[n,e]),f=(0,Z.useCallback)((t,n)=>{let r=i(t,n?.directory??e);return!r.complete&&!!r.cursor},[e,i]),p=(0,Z.useCallback)((t,n)=>i(t,n?.directory??e).loading,[e,i]),m=(0,Z.useCallback)((t,n)=>i(t,n?.directory??e).complete,[e,i]),h=(0,Z.useCallback)(t=>{let n=t.directory||e;zt(Vt(n,t.sessionID),{type:`optimistic-add`,message:t.message,parts:t.parts})},[e]),g=(0,Z.useCallback)(t=>{let n=t.directory||e;zt(Vt(n,t.sessionID),{type:`optimistic-remove`,messageID:t.messageID})},[e]),_=(0,Z.useCallback)(t=>{let n=t.directory||e;zt(Vt(n,t.sessionID),{type:`optimistic-confirm`,messageID:t.messageID})},[e]),v=(0,Z.useCallback)(async(t,r)=>{if(!t)return;await Oo();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(Ah(o))throw Error(`refresh transcript busy`);try{await pt(i,t),Da({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,Z.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 Lh=e=>e===`diff`||e===`file`||e===`preview-console`||e===`preview-annotation`,Rh=e=>e===`original`||e===`modified`,zh=e=>{let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.floor(t)):null},Bh=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.sessionKey!=`string`||t.sessionKey.trim().length===0||!Lh(t.source))return null;let n=zh(t.startLine),r=zh(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:Rh(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()}},Vh=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(Bh).filter(e=>!!e).filter(t=>t.sessionKey===e);t.length>0&&(n[e]=t)}return n},Hh=Ue()(Ke(We((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:gn(),version:1,migrate:e=>!e||typeof e!=`object`?{drafts:{}}:{drafts:Vh(e.drafts)}}),{name:`inline-comment-draft-store`}));function Uh(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 Wh(e){return e.length===0?``:e.every(e=>e.source===`preview-annotation`)?e.map(Uh).join(`
|
|
5
5
|
|
|
@@ -6541,7 +6541,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}f
|
|
|
6541
6541
|
|
|
6542
6542
|
`),`Follow-up question:`,ww(t)].join(`
|
|
6543
6543
|
|
|
6544
|
-
`)},Ew=(e,t,n,r,i)=>{if(hw(e,n)&&dw===r.epoch){if(o()!==r.transport||c()!==r.generation){Sw(e,t,{pending:!1});return}Sw(e,t,i)}},Dw=e=>{let t=typeof e.sessionId==`string`?e.sessionId.trim():``;return t?{sessionId:t,directory:typeof e.directory==`string`&&e.directory.trim()?e.directory:e.directory??null}:null},Ow=e=>{let t=lw.get(e);t&&(vw(e),Sw(e,t.turnId,{pending:!1}))},kw=e=>{let t=Dw(e);if(!t)return null;let n=cw(t),r=zw.getState().sendSelection[n];if(r?.providerID&&r?.modelID)return r;let i=zo.getState().getSessionModelSelection(t.sessionId);if(i)return{providerID:i.providerId,modelID:i.modelId,agent:zo.getState().getSessionAgentSelection(t.sessionId)??void 0};let a=ao.getState();return a.currentProviderId&&a.currentModelId?{providerID:a.currentProviderId,modelID:a.currentModelId,agent:a.currentAgentName??void 0,variant:a.currentVariant??null}:null},Aw=async e=>{let t=kw({sessionId:e.sessionId,directory:e.directory});if(!t)return;let n=typeof t.variant==`string`&&t.variant.trim()?t.variant.trim():void 0;await xt.applySendSelection(e.sessionId,{model:{providerID:t.providerID,id:t.modelID,...n?{variant:n}:{}},...t.agent?{agent:t.agent}:{}},e.directory)},jw=(e,t)=>{let n=Dw(e);if(!n)return;let r=cw(n);zw.setState(e=>({sendSelection:{...e.sendSelection,[r]:t}})),zo.getState().saveSessionModelSelection(n.sessionId,t.providerID,t.modelID),t.agent&&zo.getState().saveSessionAgentSelection(n.sessionId,t.agent)},Mw=async(e,t,n,r)=>{let i=n.id,a={epoch:dw,transport:o(),generation:c()},s=new AbortController;lw.set(t,{controller:s,turnId:i});try{if(await Aw(e),!hw(t,s))return;let o=await xt.generateSessionAside({sessionId:e.sessionId,directory:e.directory,prompt:Tw(r,n),signal:s.signal}),c=typeof o?.text==`string`?o.text.trim():``;Ew(t,i,s,a,c?{answer:c,error:null,pending:!1}:{answer:``,error:`empty response`,pending:!1})}catch(e){Ew(t,i,s,a,mw(e,s.signal)?{pending:!1}:{error:pw(e),pending:!1})}finally{hw(t,s)&&lw.delete(t)}},Nw=async(e,t)=>{let n=typeof t==`string`?t.trim():``,r=Dw(e);if(!n||!r)return;let i=cw(r);Ow(i);let a=zw.getState().entries[i]??sw;fw+=1;let o={id:`btw_${fw}`,quotes:a.quotes,question:n,answer:``,error:null,pending:!0};bw(i,e=>({turns:[...e.turns,o].slice(-50),quotes:sw.quotes})),await Mw(r,i,o,a.turns)},Pw=async e=>{let t=Dw(e);if(!t)return;let n=cw(t),r=zw.getState().entries[n]?.turns??[],i=r[r.length-1];i&&(Ow(n),Sw(n,i.id,{answer:``,error:null,pending:!0}),await Mw(t,n,i,r.slice(0,-1)))},Fw=(e,t)=>{let n=typeof t==`string`?t.trim():``;!n||!Dw(e)||bw(cw(e),e=>e.quotes.includes(n)?null:{...e,quotes:[...e.quotes,n].slice(-10)})},Iw=(e,t)=>{let n=cw(e);zw.getState().entries[n]&&bw(n,e=>t<0||t>=e.quotes.length?null:{...e,quotes:e.quotes.filter((e,n)=>n!==t)})},Lw=e=>{Ow(cw(e))},Rw=e=>{let t=cw(e);vw(t),uw=uw.filter(e=>e!==t),zw.setState(e=>{let n=t in e.entries,r=t in e.sendSelection;if(!n&&!r)return e;let i=n?{...e.entries}:e.entries,a=r?{...e.sendSelection}:e.sendSelection;return n&&delete i[t],r&&delete a[t],{entries:i,sendSelection:a}})},zw=Ue(()=>({entries:{},sendSelection:{},setSendSelection:jw,ask:Nw,retry:Pw,cancel:Lw,addQuote:Fw,removeQuote:Iw,clear:Rw})),Bw=()=>{dw+=1;for(let{controller:e}of lw.values())e.abort();lw.clear(),uw=[],zw.setState({entries:{},sendSelection:{}})},Vw=(e=>{let t=new Map,n=()=>{let e=0;for(let n of t.values())e+=n;return e};return{hold(r){let i=(t.get(r)??0)+1;t.set(r,i),n()===1&&e.conceal();let a=!1;return()=>{if(a)return;a=!0;let i=(t.get(r)??1)-1;i<=0?t.delete(r):t.set(r,i),n()===0&&e.reveal()}}}})(mu),Hw=new Map,Uw=e=>Vw.hold(e),Ww=e=>{Hw.has(e)||Hw.set(e,Vw.hold(e))},Gw=e=>{let t=Hw.get(e);t&&(Hw.delete(e),t())},Kw=`btw-page`,qw=`btw-sheet`,Jw=`text-selection`,Yw=`1.5rem`,Xw=`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 pt-4 pb-2`,Zw=`box-border w-full whitespace-pre-wrap break-words px-3 py-2.5 typography-markdown [font-family:inherit] [font-style:inherit] [font-weight:inherit] leading-[inherit] tracking-[inherit]`;function Qw(e){let t=(0,Q.c)(40),{turn:n,isLast:r,scope:i}=e,{t:a}=Wn(),o;t[0]!==a||t[1]!==n.error?(o=n.error===`empty response`||n.error===`session.btw failed`?a(`chat.btw.failed`):n.error,t[0]=a,t[1]=n.error,t[2]=o):o=t[2];let s=o,c=!n.pending&&!n.error&&!n.answer,l;t[3]!==a||t[4]!==n.answer?(l=async()=>{(await Un(n.answer)).ok?Ha.success(a(`contextSidebar.actions.copied`)):Ha.error(a(`filesView.toast.copyFailed`))},t[3]=a,t[4]=n.answer,t[5]=l):l=t[5];let u=q(l),d=n.id,f;t[6]===n.quotes?f=t[7]:(f=n.quotes.map($w),t[6]=n.quotes,t[7]=f);let p;t[8]===n.question?p=t[9]:(p=(0,$.jsx)(`div`,{className:`whitespace-pre-wrap break-words typography-markdown text-foreground`,children:n.question}),t[8]=n.question,t[9]=p);let m;t[10]!==f||t[11]!==p?(m=(0,$.jsxs)(`div`,{className:`ml-8 flex flex-col gap-1.5 self-end rounded-xl bg-[var(--surface-elevated)] px-3 py-2`,children:[f,p]}),t[10]=f,t[11]=p,t[12]=m):m=t[12];let h;t[13]!==a||t[14]!==n.pending?(h=n.pending?(0,$.jsxs)(`p`,{role:`status`,className:`flex items-center gap-1.5 typography-meta text-muted-foreground`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin`,"aria-hidden":`true`}),a(`chat.btw.pending`)]}):null,t[13]=a,t[14]=n.pending,t[15]=h):h=t[15];let g;t[16]===s?g=t[17]:(g=s?(0,$.jsxs)(`p`,{role:`alert`,className:`whitespace-pre-wrap break-words typography-meta text-muted-foreground`,children:[(0,$.jsx)(X,{name:`error-warning`,className:`mr-1.5 inline size-3.5 align-[-2px] text-[var(--status-error)]/85`,"aria-hidden":`true`}),s]}):null,t[16]=s,t[17]=g);let _;t[18]!==c||t[19]!==a?(_=c?(0,$.jsx)(`p`,{role:`status`,className:`typography-meta text-muted-foreground`,children:a(`chat.btw.cancelled`)}):null,t[18]=c,t[19]=a,t[20]=_):_=t[20];let v;t[21]===n.answer?v=t[22]:(v=n.answer?(0,$.jsx)(`div`,{className:`min-w-0 text-foreground`,children:(0,$.jsx)(Su,{content:n.answer,enableFileReferences:!1})}):null,t[21]=n.answer,t[22]=v);let y;t[23]!==c||t[24]!==u||t[25]!==s||t[26]!==r||t[27]!==i||t[28]!==a||t[29]!==n.answer||t[30]!==n.pending?(y=!n.pending&&(n.answer||r&&(s||c))?(0,$.jsxs)(`div`,{className:`-ml-2 flex items-center gap-0.5`,children:[n.answer?(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`xs`,onClick:u,"aria-label":a(`contextSidebar.actions.copy`),children:(0,$.jsx)(X,{name:`file-copy`,className:`size-3.5`})}):null,r?(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`xs`,onClick:()=>void zw.getState().retry(i),"aria-label":a(`contextPanel.preview.actions.retry`),children:(0,$.jsx)(X,{name:`refresh`,className:`size-3.5`})}):null]}):null,t[23]=c,t[24]=u,t[25]=s,t[26]=r,t[27]=i,t[28]=a,t[29]=n.answer,t[30]=n.pending,t[31]=y):y=t[31];let b;return t[32]!==v||t[33]!==y||t[34]!==m||t[35]!==h||t[36]!==g||t[37]!==_||t[38]!==n.id?(b=(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,"data-btw-turn":d,children:[m,h,g,_,v,y]}),t[32]=v,t[33]=y,t[34]=m,t[35]=h,t[36]=g,t[37]=_,t[38]=n.id,t[39]=b):b=t[39],b}function $w(e,t){return(0,$.jsx)(`p`,{"data-btw-quote":!0,"data-conversation-quote":!0,className:`m-0 whitespace-pre-wrap break-words border-l-2 border-border pl-1.5 typography-meta text-muted-foreground`,children:e},t)}function eT(e){let t=(0,Q.c)(62),{scope:n,pending:r,quotes:i,foot:a}=e,{t:o}=Wn(),s;t[0]===n?s=t[1]:(s=e=>e.sendSelection[cw(n)],t[0]=n,t[1]=s);let c=zw(s),l;t[2]!==n||t[3]!==c?(l=c??kw(n),t[2]=n,t[3]=c,t[4]=l):l=t[4];let u=l,d=ao(tT),f;bb0:{if(!u?.providerID||!u?.modelID){f=null;break bb0}let e;if(t[5]!==d||t[6]!==u.modelID||t[7]!==u.providerID){let n;t[9]===u.providerID?n=t[10]:(n=e=>e.id===u.providerID,t[9]=u.providerID,t[10]=n);let r=d.find(n);e=hr(r,u.modelID)||u.modelID,t[5]=d,t[6]=u.modelID,t[7]=u.providerID,t[8]=e}else e=t[8];f=e}let p=f,[m,h]=Z.useState(``),g=Z.useRef(null),_;t[11]!==m||t[12]!==r||t[13]!==n?(_=()=>{let e=m.trim();!e||r||(h(``),zw.getState().ask(n,e))},t[11]=m,t[12]=r,t[13]=n,t[14]=_):_=t[14];let v=q(_),y;t[15]!==p||t[16]!==u?(y=u&&p?(0,$.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-1.5 rounded-lg px-2.5 py-1`,"aria-label":p,children:[(0,$.jsx)(ss,{modelId:u.modelID,providerId:u.providerID,className:`size-4 shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 truncate typography-meta font-medium text-foreground`,children:p})]}):null,t[15]=p,t[16]=u,t[17]=y):y=t[17];let b=y,x=a!==`panel`,S=x?`oc-mobile-composer`:`pb-3`,C=a===`page`?`bottom-safe-area`:``,w;t[18]!==S||t[19]!==C?(w=[`shrink-0 px-3 pt-1`,S,C].filter(Boolean),t[18]=S,t[19]=C,t[20]=w):w=t[20];let T=w.join(` `),E;t[21]===v?E=t[22]:(E=e=>{e.preventDefault(),v()},t[21]=v,t[22]=E);let D;t[23]===Symbol.for(`react.memo_cache_sentinel`)?(D=e=>h(e),t[23]=D):D=t[23];let O;t[24]===n?O=t[25]:(O=()=>zw.getState().cancel(n),t[24]=n,t[25]=O);let k;t[26]===o?k=t[27]:(k=o(`chat.btw.placeholder`),t[26]=o,t[27]=k);let A;t[28]===o?A=t[29]:(A=o(`chat.chatInput.actions.sendMessageAria`),t[28]=o,t[29]=A);let j;t[30]===o?j=t[31]:(j=o(`chat.statusRow.actions.stopGeneratingAria`),t[30]=o,t[31]=j);let M;t[32]===Symbol.for(`react.memo_cache_sentinel`)?(M={autoFocus:!0},t[32]=M):M=t[32];let N=x?`relative z-10 oc-mobile-composer-surface`:`relative z-10`,P;t[33]===Symbol.for(`react.memo_cache_sentinel`)?(P={borderRadius:Yw},t[33]=P):P=t[33];let F=x?Zw:Xw,I;t[34]===Symbol.for(`react.memo_cache_sentinel`)?(I={borderTopLeftRadius:Yw,borderTopRightRadius:Yw},t[34]=I):I=t[34];let L;t[35]===Symbol.for(`react.memo_cache_sentinel`)?(L={borderBottomLeftRadius:Yw,borderBottomRightRadius:Yw},t[35]=L):L=t[35];let R;t[36]===o?R=t[37]:(R=o(`chat.btw.removeQuoteAria`),t[36]=o,t[37]=R);let z;t[38]===n?z=t[39]:(z=e=>zw.getState().removeQuote(n,e),t[38]=n,t[39]=z);let B;t[40]!==i||t[41]!==R||t[42]!==z?(B=(0,$.jsx)(hg,{quotes:i,removeLabel:R,onRemove:z}),t[40]=i,t[41]=R,t[42]=z,t[43]=B):B=t[43];let V;t[44]!==m||t[45]!==x||t[46]!==b||t[47]!==r||t[48]!==v||t[49]!==O||t[50]!==k||t[51]!==A||t[52]!==j||t[53]!==N||t[54]!==F||t[55]!==B?(V=(0,$.jsx)(Yc,{value:m,onChange:D,onSubmit:v,onStop:O,pending:r,disableInputWhilePending:!1,isMobile:x,placeholder:k,sendLabel:A,stopLabel:j,inputRef:g,textareaProps:M,leftControls:b,className:N,style:P,textLayoutClassName:F,inputStyle:I,footerClassName:`z-30 bg-transparent flex-shrink-0 px-2.5 py-1.5`,footerStyle:L,inputHeader:B}),t[44]=m,t[45]=x,t[46]=b,t[47]=r,t[48]=v,t[49]=O,t[50]=k,t[51]=A,t[52]=j,t[53]=N,t[54]=F,t[55]=B,t[56]=V):V=t[56];let H;return t[57]!==a||t[58]!==E||t[59]!==V||t[60]!==T?(H=(0,$.jsx)(`form`,{"data-btw-composer":!0,"data-btw-composer-foot":a,className:T,onSubmit:E,children:V}),t[57]=a,t[58]=E,t[59]=V,t[60]=T,t[61]=H):H=t[61],H}function tT(e){return e.providers}function nT(e){let t=(0,Q.c)(29),{scope:n,foot:r}=e,i=r===void 0?`panel`:r,{t:a}=Wn(),o;t[0]===n?o=t[1]:(o=cw(n),t[0]=n,t[1]=o);let s=o,c;t[2]===s?c=t[3]:(c=e=>(e.entries[s]??sw).turns,t[2]=s,t[3]=c);let l=zw(c),u;t[4]===s?u=t[5]:(u=e=>(e.entries[s]??sw).quotes,t[4]=s,t[5]=u);let d=zw(u),f;t[6]===l?f=t[7]:(f=l.some(rT),t[6]=l,t[7]=f);let p=f,m=Z.useRef(null),h=l[l.length-1],g;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>{let e=m.current;e&&(e.scrollTop=e.scrollHeight)},t[8]=g):g=t[8];let _=h?.answer,v=h?.pending,y;t[9]!==_||t[10]!==v||t[11]!==l.length?(y=[l.length,_,v],t[9]=_,t[10]=v,t[11]=l.length,t[12]=y):y=t[12],Z.useLayoutEffect(g,y);let b;t[13]===a?b=t[14]:(b=a(`chat.btw.title`),t[13]=a,t[14]=b);let x;t[15]!==n||t[16]!==a||t[17]!==l?(x=(0,$.jsx)(`div`,{ref:m,className:`overlay-scrollbar-container min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-3`,children:l.length===0?(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:a(`chat.btw.description`)}):(0,$.jsx)(`div`,{className:`flex flex-col gap-5`,children:l.map((e,t)=>(0,$.jsx)(Qw,{turn:e,isLast:t===l.length-1,scope:n},e.id))})}),t[15]=n,t[16]=a,t[17]=l,t[18]=x):x=t[18];let S;t[19]!==i||t[20]!==s||t[21]!==p||t[22]!==d||t[23]!==n?(S=(0,$.jsx)(eT,{scope:n,pending:p,quotes:d,foot:i},s),t[19]=i,t[20]=s,t[21]=p,t[22]=d,t[23]=n,t[24]=S):S=t[24];let C;return t[25]!==b||t[26]!==x||t[27]!==S?(C=(0,$.jsxs)(`section`,{className:`flex h-full min-h-0 min-w-0 flex-col text-foreground`,"aria-label":b,children:[x,S]}),t[25]=b,t[26]=x,t[27]=S,t[28]=C):C=t[28],C}function rT(e){return e.pending}function iT(e){let t=(0,Q.c)(53),{scope:n,active:r,mobile:i}=e,{t:a}=Wn(),{sessionId:o,directory:s}=n,c;t[0]===n?c=t[1]:(c=cw(n),t[0]=n,t[1]=c);let l=c,u;t[2]===s?u=t[3]:(u=ge(s),t[2]=s,t[3]=u);let d=u,f;t[4]===d?f=t[5]:(f=e=>e.contextPanelByDirectory[d],t[4]=d,t[5]=f);let p=K(f),m;t[6]!==r||t[7]!==p?(m=r&&!!(p?.isOpen&&p.tabs.find(e=>e.id===p.activeTabId)?.mode===`btw`),t[6]=r,t[7]=p,t[8]=m):m=t[8];let h=m,g;t[9]===p?g=t[10]:(g=p?.isOpen&&p.tabs.some(oT),t[9]=p,t[10]=g);let _=!!g,v;t[11]!==l||t[12]!==_?(v={key:l,retained:_},t[11]=l,t[12]=_,t[13]=v):v=t[13];let y=Z.useRef(v),b,x;t[14]!==l||t[15]!==_||t[16]!==s||t[17]!==o?(b=()=>{let e={sessionId:o,directory:s},t=y.current;y.current={key:l,retained:_},t.key===l&&t.retained&&!_&&zw.getState().clear(e)},x=[l,_,o,s],t[14]=l,t[15]=_,t[16]=s,t[17]=o,t[18]=b,t[19]=x):(b=t[18],x=t[19]),Z.useEffect(b,x);let S=Z.useRef(null),C,w;t[20]!==r||t[21]!==l||t[22]!==s||t[23]!==o?(w=()=>{let e={sessionId:o,directory:s},t={key:l,active:r};S.current=t;let n=()=>$a({sessionId:o,directory:s??null});return!r&&!n()&&zw.getState().cancel(e),()=>{let r=zw.getState().entries[l];queueMicrotask(()=>{let i=S.current;i!==t&&i?.key===l&&i.active||n()||cw(e)===l&&zw.getState().entries[l]===r&&zw.getState().cancel(e)})}},C=[l,r,o,s],t[20]=r,t[21]=l,t[22]=s,t[23]=o,t[24]=C,t[25]=w):(C=t[24],w=t[25]),Z.useEffect(w,C);let T;t[26]!==d||t[27]!==n?(T=()=>{zw.getState().clear(n),K.getState().closeContextPanel(d)},t[26]=d,t[27]=n,t[28]=T):T=t[28];let E=q(T),D,O;if(t[29]!==i||t[30]!==h?(D=()=>{if(!i||!h){Gw(qw);return}return Ww(qw),aT},O=[i,h],t[29]=i,t[30]=h,t[31]=D,t[32]=O):(D=t[31],O=t[32]),Z.useEffect(D,O),!i)return null;let k;t[33]===E?k=t[34]:(k=e=>{e||E()},t[33]=E,t[34]=k);let A;t[35]===a?A=t[36]:(A=a(`chat.btw.title`),t[35]=a,t[36]=A);let j;t[37]===a?j=t[38]:(j=a(`chat.btw.title`),t[37]=a,t[38]=j);let M;t[39]===a?M=t[40]:(M=a(`gitView.common.close`),t[39]=a,t[40]=M);let N;t[41]===a?N=t[42]:(N=a(`chat.btw.resize`),t[41]=a,t[42]=N);let P;t[43]===n?P=t[44]:(P=(0,$.jsx)(nT,{scope:n,foot:`sheet`}),t[43]=n,t[44]=P);let F;return t[45]!==h||t[46]!==k||t[47]!==A||t[48]!==j||t[49]!==M||t[50]!==N||t[51]!==P?(F=(0,$.jsx)(Hc,{id:`session-btw`,open:h,onOpenChange:k,title:A,ariaLabel:j,closeAriaLabel:M,resizeAriaLabel:N,children:P}),t[45]=h,t[46]=k,t[47]=A,t[48]=j,t[49]=M,t[50]=N,t[51]=P,t[52]=F):F=t[52],F}function aT(){return Gw(qw)}function oT(e){return e.mode===`btw`}var sT=()=>{typeof window>`u`||window.requestAnimationFrame(()=>{document.querySelector(`[data-btw-composer] textarea`)?.focus()})},cT=e=>{let t=e.directory??null;mo({sessionId:e.sessionId,directory:t})?Ww(Kw):K.getState().openContextPanelTab(t??``,{mode:`btw`}),sT()},lT=({currentSessionId:e,messageRef:t,replacePlainDocument:n})=>{let r=e;return t.current=``,n(``),r},uT=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()}},dT=e=>!e.queuedOnly&&!e.resourcePolicy&&e.rootAttachmentCount>0,fT=e=>e.surfaceKind===`primary`&&!!e.currentSessionId&&!e.queuedOnly&&e.delivery!==`queue`&&!e.resourcePolicy&&e.inputMode!==`shell`&&!e.localCommand,pT=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},mT=e=>({state:`bound`,transportIdentity:e.transportIdentity,directory:e.directory,sessionID:e.sessionID,deliveryTarget:{kind:`primary`},runtimeGeneration:e.runtimeGeneration}),hT=(e,t)=>{let n=j.getState();return n.bindLegacyQueue(x(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},gT=async e=>{let t=ai.getState().takeEstablishingPending(e.draftID);if(t.length===0)return{drained:0,failed:0};let n=mT(e),r=0,i=0;for(let a of t)try{if(e.admitServer&&(await e.admitServer(a)).status===`committed`){r+=1;continue}hT(n,a)?r+=1:i+=1}catch{try{hT(n,a)?r+=1:i+=1}catch{i+=1}}return{drained:r,failed:i}},_T=(e,t)=>Promise.resolve().then(()=>e()).catch(()=>{t()}),vT=e=>{let t=e.ctrlEnter&&e.canQueue&&e.primary&&e.sessionIsRunning&&!e.autoReviewRunning;return e.followUpBehavior===`queue`?t?{kind:`submit`,steerAfterAdmit:!0}:e.ctrlEnter||!e.canQueue?{kind:`submit`}:e.primary?{kind:`submit`,delivery:`queue`}:e.queueUsable?{kind:`queue`}:{kind:`submit`,delivery:`steer`}:t?{kind:`submit`,steerAfterAdmit:!0}:e.ctrlEnter||!e.canQueue?{kind:`submit`}:{kind:`submit`,delivery:`steer`}},yT=e=>Object.prototype.hasOwnProperty.call(e,`permissions`)?e.permissions:e.permission,bT=e=>{let t=Cc(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n){if(n.action===`*`&&n.resource===`*`)return n.effect===`ask`;if(n.effect===`ask`)return!0}}return!0},xT=(e,t)=>{let n=t?.trim();if(!n)return e.length===0||e.some(e=>bT(yT(e)));let r=e.find(e=>e?.name===n);return!r||bT(yT(r))},ST=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)},CT=null,wT=new Set,TT=()=>{for(let e of wT)e()},ET=e=>e===`chat`||e===`assistant`,DT=()=>CT,OT=e=>{CT!==e&&(CT=e,TT())},kT=e=>{CT&&(e&&CT.surfaceID!==e||(CT=null,TT()))},AT=(e,t)=>{if(e.transportIdentity!==t.transportIdentity||e.runtimeGeneration!==t.runtimeGeneration)throw Error(`chat-input-delivery-runtime-stale`)},jT=e=>{let t=e.options?.delivery===`steer`?`steer`:e.options?.delivery===`queue`?`queue`:void 0,n={...t?{delivery:t}:{},...e.options?.commitStagedMessageEdit===void 0?{}:{commitStagedMessageEdit:e.options.commitStagedMessageEdit},...e.options?.messageID?{messageID:e.options.messageID}:{},...e.options?.ticket?{ticket:e.options.ticket}:{}},r=e.options?.sessionId??e.sessionID??void 0;if(!r)return n;let i=e.options?.directoryHint===void 0?e.directory||null:e.options.directoryHint;return{...n,sessionId:r,directoryHint:i}},MT=(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}),NT=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=MT(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=MT(e,`send`,i),o=ub(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=MT(e,`create`);return await e.selection.flush(),e.backend.create(t)},compact:async t=>{let n=MT(e,`compact`,t);return await e.selection.flush(),e.backend.compact(n)},abort:async()=>{let t=MT(e,`abort`);return await e.selection.flush(),e.backend.abort(t)},queueScope:ub(e),canAbort:n,canQueue:t===`busy`||t===`retry`,allowsCommand:t=>rb(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=MT(e,`abort`);await e.selection.flush(),await e.backend.abort(t);return}if(t===`new`){let t=MT(e,`create`);await e.selection.flush(),await e.backend.create(t);return}t!==`submit`&&await e.shortcuts?.cycle(n)},resources:e.resources??null}},PT=(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)))},FT=(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},IT=(e,t)=>e.agents.some(e=>e.name===t),LT=(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},RT=e=>{let{catalog:t,providerID:n,modelID:r,historyVariant:i,memoryVariant:a}=e;if(i)return LT(t,n,r,i)?i:void 0;if(a&<(t,n,r,a))return a},zT=e=>{let{sessionId:t,choice:n,catalog:r,memory:i,fallbackAgentName:a,source:o}=e;if(!n.providerID||!n.modelID||!FT(r,n.providerID,n.modelID))return null;let s=n.agent&&IT(r,n.agent)?n.agent:i?.getSessionAgentSelection?.(t)&&IT(r,i.getSessionAgentSelection(t))?i.getSessionAgentSelection(t):a&&IT(r,a)?a:void 0,c=s?i?.getAgentModelVariantForSession?.(t,s,n.providerID,n.modelID):void 0,l=RT({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}},BT=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=zT({sessionId:t,choice:r,catalog:i,memory:a,fallbackAgentName:s,source:`execution`});if(e)return e}if(c&&n){let e=zT({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&&IT(i,e)?e:s&&IT(i,s)?s:void 0;if(n){let e=a.getAgentModelForSession?.(t,n);if(e&&FT(i,e.providerId,e.modelId)){let r=a.getAgentModelVariantForSession?.(t,n,e.providerId,e.modelId),o=r&<(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&&FT(i,r.providerId,r.modelId)){let e=n?a.getAgentModelVariantForSession?.(t,n,r.providerId,r.modelId):void 0,o=e&<(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&&FT(i,l.providerID,l.id)){let e=a?.getSessionAgentSelection?.(t)??null,n=(o?.agent&&IT(i,o.agent)?o.agent:void 0)??(e&&IT(i,e)?e:s&&IT(i,s)?s:void 0),r=l.variant,c=r&<(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},VT=(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))},HT=(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}},UT=e=>e.editRevision<=0?!1:e.pinnedHistoryMessageId==null||e.latestHistoryMessageId==null||e.latestHistoryMessageId===e.pinnedHistoryMessageId,WT=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}:{}}},GT=e=>typeof e==`string`&&e.trim().length>0?e:void 0,KT=e=>GT(e.agent)??GT(e.mode),qT=e=>GT(typeof e.model==`object`?e.model?.variant:void 0)??GT(e.variant),JT=e=>{let t=typeof e.model==`object`?e.model:void 0,n=GT(e.providerID)??GT(t?.providerID),r=GT(e.modelID)??GT(t?.modelID)??GT(t?.id);return!n||!r?null:{providerID:n,modelID:r}},YT=e=>JT(e),XT=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role!==`user`)continue;let r=JT(n);return{id:typeof n.id==`string`?n.id:void 0,agent:KT(n),providerID:r?.providerID,modelID:r?.modelID,variant:qT(n)}}return null},ZT=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`){if(JT(n))return null;continue}if(n.role!==`assistant`)continue;let r=YT(n);if(r)return{id:typeof n.id==`string`?n.id:void 0,agent:KT(n),providerID:r.providerID,modelID:r.modelID,variant:qT(n)}}return null},QT=500,$T=e=>Array.from(e).length,eE=e=>{let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(36)},tE=e=>$T(e)>=QT,nE=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},rE=(e,t)=>{let n=t??e;return typeof n!=`string`||!tE(n)?!1:y(typeof e==`string`?{text:``,references:[]}:e,n)},iE=(e,t,n,r,i=1)=>{let a=$T(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}-${eE(e)}`,token:i,text:e,characterCount:a,index:n}}throw Error(`Unable to create a unique pasted text reference`)},aE=e=>({text:e?.text??``,references:e?.composerReferences??[]}),oE=e=>({text:e.text,references:e.references.map(e=>({...e}))}),sE=e=>({transportIdentity:e.transportIdentity,owner:{...e.owner}}),cE=e=>JSON.stringify([e.text,e.references]),lE=(e,t)=>e!==null&&t!==null&&A(e)===t,uE=(e,t,n)=>{let r=e?sE(e):null,i=r?n(r):void 0;return{document:v(aE(i),t),mentions:i?.mentions??[],revision:i?.revision??0,key:r,keyID:r?A(r):null}},dE=(e,t,n,r)=>{if(!t||A(t.key)!==r.keyID||t.revision<r.appliedRevision)return`ignore`;let i=cE(aE(t));return n?.keyID===r.keyID&&n.revision===t.revision&&n.fingerprint===i?`local-echo`:t.revision===r.appliedRevision?`ignore`:i===cE(e)?`same-document-metadata`:`external-document`},fE=(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}]:[]})},pE=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),mE=(e,t,n,r,i=r)=>{let a=N(e,n,r,i);return{document:a.document,mentions:fE(t,a.document,a.edit),requiresTextCorrection:a.requiresTextCorrection,selectionStart:a.selectionStart,selectionEnd:a.selectionEnd,removedReferences:a.removedReferences}},hE=(e,t,n)=>({preview:{real:oE(e),realMentions:[...t]},document:{text:n.text,references:[]},mentions:[]}),gE=e=>({document:e.real,mentions:e.realMentions}),_E=(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)})},vE=(e,t)=>{let n=aE(t),r=S(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:_E(e.mentions,t?.mentions??[],r,i)}},yE=({draftKey:e,sessionTitles:t,persistenceEnabled:n,onResourcesChanged:r,store:i=yo})=>{let a=e?A(e):null,o=(0,Z.useSyncExternalStore)(i.subscribe,()=>a?i.getState().drafts[a]:void 0,()=>void 0),s=(0,Z.useSyncExternalStore)(i.subscribe,()=>a?i.getState().draftHydration[a]??`idle`:`idle`,()=>`idle`),c=(0,Z.useSyncExternalStore)(i.subscribe,()=>a?i.getState().draftPersistence[a]:void 0,()=>void 0),[l,u]=(0,Z.useState)(()=>uE(e,t,i.getState().getDraft).document),[d,f]=(0,Z.useState)(()=>uE(e,t,i.getState().getDraft).mentions),[m,h]=(0,Z.useState)(`compose`),[g,_]=(0,Z.useState)(0),y=(0,Z.useRef)(l),b=(0,Z.useRef)(d),x=(0,Z.useRef)(t),S=(0,Z.useRef)(r),C=(0,Z.useRef)(e),w=(0,Z.useRef)(e?sE(e):null),T=(0,Z.useRef)(a),E=(0,Z.useRef)(a),D=(0,Z.useRef)(0),O=(0,Z.useRef)(o?.revision??0),k=(0,Z.useRef)(void 0),j=(0,Z.useRef)(void 0),I=(0,Z.useRef)(sl());y.current=l,b.current=d,x.current=t,S.current=r,C.current=e,T.current=a;let L=(0,Z.useCallback)((e,t)=>{y.current=e,b.current=t,u(e),f(t)},[]),R=(0,Z.useCallback)((e,t)=>{let n=de(e,t);S.current?.(n)},[]);(0,Z.useEffect)(()=>{i.getState().setDraftPersistenceEnabled(n)},[n,i]),(0,Z.useLayoutEffect)(()=>{D.current+=1;let e=D.current;E.current=a;let t=uE(C.current,x.current,i.getState().getDraft),n=t.key;if(w.current=t.key,k.current=void 0,j.current=void 0,I.current=sl(),h(`compose`),O.current=t.revision,L(t.document,t.mentions),_(e=>e+1),n?.owner.kind===`draft`){let r=t.revision;i.getState().claimLegacyNewDraft(n).then(t=>{let o=i.getState().getDraft(n);!t||!lE(w.current,a)||E.current!==a||T.current!==a||D.current!==e||O.current!==r||o?.revision!==t.revision||(O.current=t.revision,L(v(aE(t),x.current),t.mentions))})}},[a,L,i]),(0,Z.useEffect)(()=>{if(!a||E.current!==a||j.current)return;let e=dE(y.current,o,k.current,{keyID:a,epoch:D.current,appliedRevision:O.current});if(e!==`ignore`){if(o&&(O.current=o.revision),e===`local-echo`||e===`same-document-metadata`){o&&f(o.mentions);return}e===`external-document`&&o&&(k.current=void 0,L(v(aE(o),x.current),o.mentions),h(`compose`),_(e=>e+1))}},[a,L,o]);let z=(0,Z.useCallback)((e,t)=>{let n=w.current;if(!lE(n,T.current)||j.current)return;let r=y.current,a=i.getState().setDraftComposerState(n,{document:e,mentions:pE(t)});if(!a)return;let o=aE(a);return k.current={keyID:A(n),revision:a.revision,fingerprint:cE(o)},O.current=a.revision,L(o,a.mentions),R(r,o),a},[i,L,R]),B=(0,Z.useCallback)((e,t,n,r,i,a)=>{I.current=fl(I.current,{before:el(e,t,n),after:el(r,i,a)})},[]),V=(0,Z.useCallback)(()=>j.current?(j.current=void 0,h(`compose`),!0):!1,[]),H=(0,Z.useCallback)(e=>(V(),z({text:e,references:[]},[])),[z,V]),ee=(0,Z.useCallback)((e,t=[])=>{V();let n=oe(e.text,e.references);return n?z(v(n,x.current),t):void 0},[z,V]),U=(0,Z.useCallback)((e,t,n=t,r)=>{let i=V(),a=oE(y.current),o=i?[]:b.current,s=mE(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,Z.useCallback)((e,t)=>{let n=y.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=N(n,`${n.text.slice(0,r)}${e.text}${n.text.slice(i)}`,r+e.text.length),s=fE(a?[]:b.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,Z.useCallback)((e,t)=>{let n=y.current;return te({start:0,end:n.text.length,text:e},t)},[te]),ne=(0,Z.useCallback)((e,t,n,r)=>{let i=V(),a=M(y.current,e,t,n,r);return z(a.document,fE(i?[]:b.current,a.document,a.edit)),{start:a.caret,end:a.caret,caret:a.caret,document:a.document}},[z,V]),re=(0,Z.useCallback)(e=>{let t=oE(y.current),n=F(t,e);if(!n)return null;let r=V()?[]:b.current,i=fE(r,n.document,n.edit),a=P(n.document.text,n.caret),o=N(n.document,a.text,a.caret),s=fE(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]),ie=(0,Z.useCallback)(e=>{if(j.current)return null;let t=e===`undo`?nl(I.current,y.current):tl(I.current,y.current);return!t||!z(t.snapshot.document,t.snapshot.mentions)?null:(I.current=t.history,t.snapshot.selection)},[z]),ae=(0,Z.useCallback)(e=>z(y.current,e),[z]),se=(0,Z.useCallback)(e=>{let t=j.current?{document:{text:e.text,references:[]},mentions:[]}:hE(y.current,b.current,e);`preview`in t&&(j.current=t.preview),h(`history-preview`),L(t.document,t.mentions),_(e=>e+1)},[L]),ce=(0,Z.useCallback)(()=>{let e=j.current;if(!e)return;j.current=void 0,h(`compose`);let t=gE(e);L(t.document,t.mentions),_(e=>e+1)},[L]),le=(0,Z.useCallback)(()=>{let e=w.current;if(!lE(e,T.current))return null;let t=i.getState().getDraft(e);return{key:sE(e),keyID:A(e),revision:t?.revision??0,document:oE(y.current),mentions:b.current.map(e=>({...e,range:{...e.range}})),epoch:D.current,runtime:i.getState().captureDraftRuntime()}},[i]),ue=(0,Z.useCallback)(e=>{let t=vE(e,i.getState().getDraft(e.key)),n=aE(i.getState().getDraft(e.key)),r=p(n.text,n.references).document,a=i.getState().setDraftComposerState(e.key,{...t,mentions:pE(t.mentions)});if(a){let e=aE(a);R(r,e)}return a},[R,i]),fe=(0,Z.useCallback)(()=>y.current,[]);return(0,Z.useMemo)(()=>({document:l,mentions:d,confirmedFileMentions:d.filter(e=>e.kind===`file`||e.kind===`directory`),inputMode:m,hydration:s,persistence:c,textPresetEpoch:g,getDocument:fe,replacePlainDocument:H,replaceMaterializedDocument:ee,applyBrowserEdit:U,applyProgrammaticEdit:te,replaceProgrammaticText:W,insertReference:ne,deleteReference:re,restoreReferenceHistory:ie,commitMentions:ae,enterHistoryPreview:se,exitHistoryPreview:ce,captureSubmission:le,recoverSubmission:ue}),[U,te,le,ae,re,l,se,ce,fe,s,m,ne,d,c,ue,ee,H,W,ie,g])};function bE(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 xE=`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`,SE=Cu(()=>Sn(()=>import(`./ToolOutputDialog-DQvXtK71.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]))),CE=[],wE=[],TE=[],EE=[],DE=/^@[^\s]+$/,OE=({inputMode:e,message:t,showCommandAutocomplete:n})=>e!==`shell`&&(n||/(^|\s)\/[A-Za-z0-9_-]*/.test(t)),kE=/^(https?:\/\/|mailto:)\S+$/i,AE=560,jE=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),ME=(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)},NE=e=>e.includes(`@`)?`paste`:`manual`,PE=(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}},FE=(e,t)=>mn(e,t).some(e=>e.role===`user`),IE=(e,t)=>{let n=e.filter(e=>e.type===`text`&&!gi(e)).map(e=>{let t=e;return typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:``}).join(`
|
|
6544
|
+
`)},Ew=(e,t,n,r,i)=>{if(hw(e,n)&&dw===r.epoch){if(o()!==r.transport||c()!==r.generation){Sw(e,t,{pending:!1});return}Sw(e,t,i)}},Dw=e=>{let t=typeof e.sessionId==`string`?e.sessionId.trim():``;return t?{sessionId:t,directory:typeof e.directory==`string`&&e.directory.trim()?e.directory:e.directory??null}:null},Ow=e=>{let t=lw.get(e);t&&(vw(e),Sw(e,t.turnId,{pending:!1}))},kw=e=>{let t=Dw(e);if(!t)return null;let n=cw(t),r=zw.getState().sendSelection[n];if(r?.providerID&&r?.modelID)return r;let i=zo.getState().getSessionModelSelection(t.sessionId);if(i)return{providerID:i.providerId,modelID:i.modelId,agent:zo.getState().getSessionAgentSelection(t.sessionId)??void 0};let a=ao.getState();return a.currentProviderId&&a.currentModelId?{providerID:a.currentProviderId,modelID:a.currentModelId,agent:a.currentAgentName??void 0,variant:a.currentVariant??null}:null},Aw=async e=>{let t=kw({sessionId:e.sessionId,directory:e.directory});if(!t)return;let n=typeof t.variant==`string`&&t.variant.trim()?t.variant.trim():void 0;await xt.applySendSelection(e.sessionId,{model:{providerID:t.providerID,id:t.modelID,...n?{variant:n}:{}},...t.agent?{agent:t.agent}:{}},e.directory)},jw=(e,t)=>{let n=Dw(e);if(!n)return;let r=cw(n);zw.setState(e=>({sendSelection:{...e.sendSelection,[r]:t}})),zo.getState().saveSessionModelSelection(n.sessionId,t.providerID,t.modelID),t.agent&&zo.getState().saveSessionAgentSelection(n.sessionId,t.agent)},Mw=async(e,t,n,r)=>{let i=n.id,a={epoch:dw,transport:o(),generation:c()},s=new AbortController;lw.set(t,{controller:s,turnId:i});try{if(await Aw(e),!hw(t,s))return;let o=await xt.generateSessionAside({sessionId:e.sessionId,directory:e.directory,prompt:Tw(r,n),signal:s.signal}),c=typeof o?.text==`string`?o.text.trim():``;Ew(t,i,s,a,c?{answer:c,error:null,pending:!1}:{answer:``,error:`empty response`,pending:!1})}catch(e){Ew(t,i,s,a,mw(e,s.signal)?{pending:!1}:{error:pw(e),pending:!1})}finally{hw(t,s)&&lw.delete(t)}},Nw=async(e,t)=>{let n=typeof t==`string`?t.trim():``,r=Dw(e);if(!n||!r)return;let i=cw(r);Ow(i);let a=zw.getState().entries[i]??sw;fw+=1;let o={id:`btw_${fw}`,quotes:a.quotes,question:n,answer:``,error:null,pending:!0};bw(i,e=>({turns:[...e.turns,o].slice(-50),quotes:sw.quotes})),await Mw(r,i,o,a.turns)},Pw=async e=>{let t=Dw(e);if(!t)return;let n=cw(t),r=zw.getState().entries[n]?.turns??[],i=r[r.length-1];i&&(Ow(n),Sw(n,i.id,{answer:``,error:null,pending:!0}),await Mw(t,n,i,r.slice(0,-1)))},Fw=(e,t)=>{let n=typeof t==`string`?t.trim():``;!n||!Dw(e)||bw(cw(e),e=>e.quotes.includes(n)?null:{...e,quotes:[...e.quotes,n].slice(-10)})},Iw=(e,t)=>{let n=cw(e);zw.getState().entries[n]&&bw(n,e=>t<0||t>=e.quotes.length?null:{...e,quotes:e.quotes.filter((e,n)=>n!==t)})},Lw=e=>{Ow(cw(e))},Rw=e=>{let t=cw(e);vw(t),uw=uw.filter(e=>e!==t),zw.setState(e=>{let n=t in e.entries,r=t in e.sendSelection;if(!n&&!r)return e;let i=n?{...e.entries}:e.entries,a=r?{...e.sendSelection}:e.sendSelection;return n&&delete i[t],r&&delete a[t],{entries:i,sendSelection:a}})},zw=Ue(()=>({entries:{},sendSelection:{},setSendSelection:jw,ask:Nw,retry:Pw,cancel:Lw,addQuote:Fw,removeQuote:Iw,clear:Rw})),Bw=()=>{dw+=1;for(let{controller:e}of lw.values())e.abort();lw.clear(),uw=[],zw.setState({entries:{},sendSelection:{}})},Vw=(e=>{let t=new Map,n=()=>{let e=0;for(let n of t.values())e+=n;return e};return{hold(r){let i=(t.get(r)??0)+1;t.set(r,i),n()===1&&e.conceal();let a=!1;return()=>{if(a)return;a=!0;let i=(t.get(r)??1)-1;i<=0?t.delete(r):t.set(r,i),n()===0&&e.reveal()}}}})(mu),Hw=new Map,Uw=e=>Vw.hold(e),Ww=e=>{Hw.has(e)||Hw.set(e,Vw.hold(e))},Gw=e=>{let t=Hw.get(e);t&&(Hw.delete(e),t())},Kw=`btw-page`,qw=`btw-sheet`,Jw=`text-selection`,Yw=`1.5rem`,Xw=`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 pt-4 pb-2`,Zw=`box-border w-full whitespace-pre-wrap break-words px-3 py-2.5 typography-markdown [font-family:inherit] [font-style:inherit] [font-weight:inherit] leading-[inherit] tracking-[inherit]`;function Qw(e){let t=(0,Q.c)(40),{turn:n,isLast:r,scope:i}=e,{t:a}=Wn(),o;t[0]!==a||t[1]!==n.error?(o=n.error===`empty response`||n.error===`session.btw failed`?a(`chat.btw.failed`):n.error,t[0]=a,t[1]=n.error,t[2]=o):o=t[2];let s=o,c=!n.pending&&!n.error&&!n.answer,l;t[3]!==a||t[4]!==n.answer?(l=async()=>{(await Un(n.answer)).ok?Ha.success(a(`contextSidebar.actions.copied`)):Ha.error(a(`filesView.toast.copyFailed`))},t[3]=a,t[4]=n.answer,t[5]=l):l=t[5];let u=q(l),d=n.id,f;t[6]===n.quotes?f=t[7]:(f=n.quotes.map($w),t[6]=n.quotes,t[7]=f);let p;t[8]===n.question?p=t[9]:(p=(0,$.jsx)(`div`,{className:`whitespace-pre-wrap break-words typography-markdown text-foreground`,children:n.question}),t[8]=n.question,t[9]=p);let m;t[10]!==f||t[11]!==p?(m=(0,$.jsxs)(`div`,{className:`ml-8 flex flex-col gap-1.5 self-end rounded-xl bg-[var(--surface-elevated)] px-3 py-2`,children:[f,p]}),t[10]=f,t[11]=p,t[12]=m):m=t[12];let h;t[13]!==a||t[14]!==n.pending?(h=n.pending?(0,$.jsxs)(`p`,{role:`status`,className:`flex items-center gap-1.5 typography-meta text-muted-foreground`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin`,"aria-hidden":`true`}),a(`chat.btw.pending`)]}):null,t[13]=a,t[14]=n.pending,t[15]=h):h=t[15];let g;t[16]===s?g=t[17]:(g=s?(0,$.jsxs)(`p`,{role:`alert`,className:`whitespace-pre-wrap break-words typography-meta text-muted-foreground`,children:[(0,$.jsx)(X,{name:`error-warning`,className:`mr-1.5 inline size-3.5 align-[-2px] text-[var(--status-error)]/85`,"aria-hidden":`true`}),s]}):null,t[16]=s,t[17]=g);let _;t[18]!==c||t[19]!==a?(_=c?(0,$.jsx)(`p`,{role:`status`,className:`typography-meta text-muted-foreground`,children:a(`chat.btw.cancelled`)}):null,t[18]=c,t[19]=a,t[20]=_):_=t[20];let v;t[21]===n.answer?v=t[22]:(v=n.answer?(0,$.jsx)(`div`,{className:`min-w-0 text-foreground`,children:(0,$.jsx)(Su,{content:n.answer,enableFileReferences:!1})}):null,t[21]=n.answer,t[22]=v);let y;t[23]!==c||t[24]!==u||t[25]!==s||t[26]!==r||t[27]!==i||t[28]!==a||t[29]!==n.answer||t[30]!==n.pending?(y=!n.pending&&(n.answer||r&&(s||c))?(0,$.jsxs)(`div`,{className:`-ml-2 flex items-center gap-0.5`,children:[n.answer?(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`xs`,onClick:u,"aria-label":a(`contextSidebar.actions.copy`),children:(0,$.jsx)(X,{name:`file-copy`,className:`size-3.5`})}):null,r?(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`xs`,onClick:()=>void zw.getState().retry(i),"aria-label":a(`contextPanel.preview.actions.retry`),children:(0,$.jsx)(X,{name:`refresh`,className:`size-3.5`})}):null]}):null,t[23]=c,t[24]=u,t[25]=s,t[26]=r,t[27]=i,t[28]=a,t[29]=n.answer,t[30]=n.pending,t[31]=y):y=t[31];let b;return t[32]!==v||t[33]!==y||t[34]!==m||t[35]!==h||t[36]!==g||t[37]!==_||t[38]!==n.id?(b=(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,"data-btw-turn":d,children:[m,h,g,_,v,y]}),t[32]=v,t[33]=y,t[34]=m,t[35]=h,t[36]=g,t[37]=_,t[38]=n.id,t[39]=b):b=t[39],b}function $w(e,t){return(0,$.jsx)(`p`,{"data-btw-quote":!0,"data-conversation-quote":!0,className:`m-0 whitespace-pre-wrap break-words border-l-2 border-border pl-1.5 typography-meta text-muted-foreground`,children:e},t)}function eT(e){let t=(0,Q.c)(62),{scope:n,pending:r,quotes:i,foot:a}=e,{t:o}=Wn(),s;t[0]===n?s=t[1]:(s=e=>e.sendSelection[cw(n)],t[0]=n,t[1]=s);let c=zw(s),l;t[2]!==n||t[3]!==c?(l=c??kw(n),t[2]=n,t[3]=c,t[4]=l):l=t[4];let u=l,d=ao(tT),f;bb0:{if(!u?.providerID||!u?.modelID){f=null;break bb0}let e;if(t[5]!==d||t[6]!==u.modelID||t[7]!==u.providerID){let n;t[9]===u.providerID?n=t[10]:(n=e=>e.id===u.providerID,t[9]=u.providerID,t[10]=n);let r=d.find(n);e=hr(r,u.modelID)||u.modelID,t[5]=d,t[6]=u.modelID,t[7]=u.providerID,t[8]=e}else e=t[8];f=e}let p=f,[m,h]=Z.useState(``),g=Z.useRef(null),_;t[11]!==m||t[12]!==r||t[13]!==n?(_=()=>{let e=m.trim();!e||r||(h(``),zw.getState().ask(n,e))},t[11]=m,t[12]=r,t[13]=n,t[14]=_):_=t[14];let v=q(_),y;t[15]!==p||t[16]!==u?(y=u&&p?(0,$.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-1.5 rounded-lg px-2.5 py-1`,"aria-label":p,children:[(0,$.jsx)(ss,{modelId:u.modelID,providerId:u.providerID,className:`size-4 shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 truncate typography-meta font-medium text-foreground`,children:p})]}):null,t[15]=p,t[16]=u,t[17]=y):y=t[17];let b=y,x=a!==`panel`,S=x?`oc-mobile-composer`:`pb-3`,C=a===`page`?`bottom-safe-area`:``,w;t[18]!==S||t[19]!==C?(w=[`shrink-0 px-3 pt-1`,S,C].filter(Boolean),t[18]=S,t[19]=C,t[20]=w):w=t[20];let T=w.join(` `),E;t[21]===v?E=t[22]:(E=e=>{e.preventDefault(),v()},t[21]=v,t[22]=E);let D;t[23]===Symbol.for(`react.memo_cache_sentinel`)?(D=e=>h(e),t[23]=D):D=t[23];let O;t[24]===n?O=t[25]:(O=()=>zw.getState().cancel(n),t[24]=n,t[25]=O);let k;t[26]===o?k=t[27]:(k=o(`chat.btw.placeholder`),t[26]=o,t[27]=k);let A;t[28]===o?A=t[29]:(A=o(`chat.chatInput.actions.sendMessageAria`),t[28]=o,t[29]=A);let j;t[30]===o?j=t[31]:(j=o(`chat.statusRow.actions.stopGeneratingAria`),t[30]=o,t[31]=j);let M;t[32]===Symbol.for(`react.memo_cache_sentinel`)?(M={autoFocus:!0},t[32]=M):M=t[32];let N=x?`relative z-10 oc-mobile-composer-surface`:`relative z-10`,P;t[33]===Symbol.for(`react.memo_cache_sentinel`)?(P={borderRadius:Yw},t[33]=P):P=t[33];let F=x?Zw:Xw,I;t[34]===Symbol.for(`react.memo_cache_sentinel`)?(I={borderTopLeftRadius:Yw,borderTopRightRadius:Yw},t[34]=I):I=t[34];let L;t[35]===Symbol.for(`react.memo_cache_sentinel`)?(L={borderBottomLeftRadius:Yw,borderBottomRightRadius:Yw},t[35]=L):L=t[35];let R;t[36]===o?R=t[37]:(R=o(`chat.btw.removeQuoteAria`),t[36]=o,t[37]=R);let z;t[38]===n?z=t[39]:(z=e=>zw.getState().removeQuote(n,e),t[38]=n,t[39]=z);let B;t[40]!==i||t[41]!==R||t[42]!==z?(B=(0,$.jsx)(hg,{quotes:i,removeLabel:R,onRemove:z}),t[40]=i,t[41]=R,t[42]=z,t[43]=B):B=t[43];let V;t[44]!==m||t[45]!==x||t[46]!==b||t[47]!==r||t[48]!==v||t[49]!==O||t[50]!==k||t[51]!==A||t[52]!==j||t[53]!==N||t[54]!==F||t[55]!==B?(V=(0,$.jsx)(Yc,{value:m,onChange:D,onSubmit:v,onStop:O,pending:r,disableInputWhilePending:!1,isMobile:x,placeholder:k,sendLabel:A,stopLabel:j,inputRef:g,textareaProps:M,leftControls:b,className:N,style:P,textLayoutClassName:F,inputStyle:I,footerClassName:`z-30 bg-transparent flex-shrink-0 px-2.5 py-1.5`,footerStyle:L,inputHeader:B}),t[44]=m,t[45]=x,t[46]=b,t[47]=r,t[48]=v,t[49]=O,t[50]=k,t[51]=A,t[52]=j,t[53]=N,t[54]=F,t[55]=B,t[56]=V):V=t[56];let H;return t[57]!==a||t[58]!==E||t[59]!==V||t[60]!==T?(H=(0,$.jsx)(`form`,{"data-btw-composer":!0,"data-btw-composer-foot":a,className:T,onSubmit:E,children:V}),t[57]=a,t[58]=E,t[59]=V,t[60]=T,t[61]=H):H=t[61],H}function tT(e){return e.providers}function nT(e){let t=(0,Q.c)(29),{scope:n,foot:r}=e,i=r===void 0?`panel`:r,{t:a}=Wn(),o;t[0]===n?o=t[1]:(o=cw(n),t[0]=n,t[1]=o);let s=o,c;t[2]===s?c=t[3]:(c=e=>(e.entries[s]??sw).turns,t[2]=s,t[3]=c);let l=zw(c),u;t[4]===s?u=t[5]:(u=e=>(e.entries[s]??sw).quotes,t[4]=s,t[5]=u);let d=zw(u),f;t[6]===l?f=t[7]:(f=l.some(rT),t[6]=l,t[7]=f);let p=f,m=Z.useRef(null),h=l[l.length-1],g;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>{let e=m.current;e&&(e.scrollTop=e.scrollHeight)},t[8]=g):g=t[8];let _=h?.answer,v=h?.pending,y;t[9]!==_||t[10]!==v||t[11]!==l.length?(y=[l.length,_,v],t[9]=_,t[10]=v,t[11]=l.length,t[12]=y):y=t[12],Z.useLayoutEffect(g,y);let b;t[13]===a?b=t[14]:(b=a(`chat.btw.title`),t[13]=a,t[14]=b);let x;t[15]!==n||t[16]!==a||t[17]!==l?(x=(0,$.jsx)(`div`,{ref:m,className:`overlay-scrollbar-container min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-3`,children:l.length===0?(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:a(`chat.btw.description`)}):(0,$.jsx)(`div`,{className:`flex flex-col gap-5`,children:l.map((e,t)=>(0,$.jsx)(Qw,{turn:e,isLast:t===l.length-1,scope:n},e.id))})}),t[15]=n,t[16]=a,t[17]=l,t[18]=x):x=t[18];let S;t[19]!==i||t[20]!==s||t[21]!==p||t[22]!==d||t[23]!==n?(S=(0,$.jsx)(eT,{scope:n,pending:p,quotes:d,foot:i},s),t[19]=i,t[20]=s,t[21]=p,t[22]=d,t[23]=n,t[24]=S):S=t[24];let C;return t[25]!==b||t[26]!==x||t[27]!==S?(C=(0,$.jsxs)(`section`,{className:`flex h-full min-h-0 min-w-0 flex-col text-foreground`,"aria-label":b,children:[x,S]}),t[25]=b,t[26]=x,t[27]=S,t[28]=C):C=t[28],C}function rT(e){return e.pending}function iT(e){let t=(0,Q.c)(53),{scope:n,active:r,mobile:i}=e,{t:a}=Wn(),{sessionId:o,directory:s}=n,c;t[0]===n?c=t[1]:(c=cw(n),t[0]=n,t[1]=c);let l=c,u;t[2]===s?u=t[3]:(u=ge(s),t[2]=s,t[3]=u);let d=u,f;t[4]===d?f=t[5]:(f=e=>e.contextPanelByDirectory[d],t[4]=d,t[5]=f);let p=K(f),m;t[6]!==r||t[7]!==p?(m=r&&!!(p?.isOpen&&p.tabs.find(e=>e.id===p.activeTabId)?.mode===`btw`),t[6]=r,t[7]=p,t[8]=m):m=t[8];let h=m,g;t[9]===p?g=t[10]:(g=p?.isOpen&&p.tabs.some(oT),t[9]=p,t[10]=g);let _=!!g,v;t[11]!==l||t[12]!==_?(v={key:l,retained:_},t[11]=l,t[12]=_,t[13]=v):v=t[13];let y=Z.useRef(v),b,x;t[14]!==l||t[15]!==_||t[16]!==s||t[17]!==o?(b=()=>{let e={sessionId:o,directory:s},t=y.current;y.current={key:l,retained:_},t.key===l&&t.retained&&!_&&zw.getState().clear(e)},x=[l,_,o,s],t[14]=l,t[15]=_,t[16]=s,t[17]=o,t[18]=b,t[19]=x):(b=t[18],x=t[19]),Z.useEffect(b,x);let S=Z.useRef(null),C,w;t[20]!==r||t[21]!==l||t[22]!==s||t[23]!==o?(w=()=>{let e={sessionId:o,directory:s},t={key:l,active:r};S.current=t;let n=()=>$a({sessionId:o,directory:s??null});return!r&&!n()&&zw.getState().cancel(e),()=>{let r=zw.getState().entries[l];queueMicrotask(()=>{let i=S.current;i!==t&&i?.key===l&&i.active||n()||cw(e)===l&&zw.getState().entries[l]===r&&zw.getState().cancel(e)})}},C=[l,r,o,s],t[20]=r,t[21]=l,t[22]=s,t[23]=o,t[24]=C,t[25]=w):(C=t[24],w=t[25]),Z.useEffect(w,C);let T;t[26]!==d||t[27]!==n?(T=()=>{zw.getState().clear(n),K.getState().closeContextPanel(d)},t[26]=d,t[27]=n,t[28]=T):T=t[28];let E=q(T),D,O;if(t[29]!==i||t[30]!==h?(D=()=>{if(!i||!h){Gw(qw);return}return Ww(qw),aT},O=[i,h],t[29]=i,t[30]=h,t[31]=D,t[32]=O):(D=t[31],O=t[32]),Z.useEffect(D,O),!i)return null;let k;t[33]===E?k=t[34]:(k=e=>{e||E()},t[33]=E,t[34]=k);let A;t[35]===a?A=t[36]:(A=a(`chat.btw.title`),t[35]=a,t[36]=A);let j;t[37]===a?j=t[38]:(j=a(`chat.btw.title`),t[37]=a,t[38]=j);let M;t[39]===a?M=t[40]:(M=a(`gitView.common.close`),t[39]=a,t[40]=M);let N;t[41]===a?N=t[42]:(N=a(`chat.btw.resize`),t[41]=a,t[42]=N);let P;t[43]===n?P=t[44]:(P=(0,$.jsx)(nT,{scope:n,foot:`sheet`}),t[43]=n,t[44]=P);let F;return t[45]!==h||t[46]!==k||t[47]!==A||t[48]!==j||t[49]!==M||t[50]!==N||t[51]!==P?(F=(0,$.jsx)(Hc,{id:`session-btw`,open:h,onOpenChange:k,title:A,ariaLabel:j,closeAriaLabel:M,resizeAriaLabel:N,children:P}),t[45]=h,t[46]=k,t[47]=A,t[48]=j,t[49]=M,t[50]=N,t[51]=P,t[52]=F):F=t[52],F}function aT(){return Gw(qw)}function oT(e){return e.mode===`btw`}var sT=()=>{typeof window>`u`||window.requestAnimationFrame(()=>{document.querySelector(`[data-btw-composer] textarea`)?.focus()})},cT=e=>{let t=e.directory??null;mo({sessionId:e.sessionId,directory:t})?Ww(Kw):K.getState().openContextPanelTab(t??``,{mode:`btw`}),sT()},lT=({currentSessionId:e,messageRef:t,replacePlainDocument:n})=>{let r=e;return t.current=``,n(``),r},uT=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()}},dT=e=>!e.queuedOnly&&!e.resourcePolicy&&e.rootAttachmentCount>0,fT=e=>e.surfaceKind===`primary`&&!!e.currentSessionId&&!e.queuedOnly&&e.delivery!==`queue`&&!e.resourcePolicy&&e.inputMode!==`shell`&&!e.localCommand,pT=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},mT=e=>({state:`bound`,transportIdentity:e.transportIdentity,directory:e.directory,sessionID:e.sessionID,deliveryTarget:{kind:`primary`},runtimeGeneration:e.runtimeGeneration}),hT=(e,t)=>{let n=j.getState();return n.bindLegacyQueue(x(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},gT=async e=>{let t=ai.getState().takeEstablishingPending(e.draftID);if(t.length===0)return{drained:0,failed:0};let n=mT(e),r=0,i=0;for(let a of t)try{if(e.admitServer&&(await e.admitServer(a)).status===`committed`){r+=1;continue}hT(n,a)?r+=1:i+=1}catch{try{hT(n,a)?r+=1:i+=1}catch{i+=1}}return{drained:r,failed:i}},_T=(e,t)=>Promise.resolve().then(()=>e()).catch(()=>{t()}),vT=e=>{let t=e.ctrlEnter&&e.canQueue&&e.primary&&e.sessionIsRunning&&!e.autoReviewRunning;return e.followUpBehavior===`queue`?t?{kind:`submit`,steerAfterAdmit:!0}:e.ctrlEnter||!e.canQueue?{kind:`submit`}:e.primary?{kind:`submit`,delivery:`queue`}:e.queueUsable?{kind:`queue`}:{kind:`submit`,delivery:`steer`}:t?{kind:`submit`,steerAfterAdmit:!0}:e.ctrlEnter||!e.canQueue?{kind:`submit`}:{kind:`submit`,delivery:`steer`}},yT=e=>Object.prototype.hasOwnProperty.call(e,`permissions`)?e.permissions:e.permission,bT=e=>{let t=Cc(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n){if(n.action===`*`&&n.resource===`*`)return n.effect===`ask`;if(n.effect===`ask`)return!0}}return!0},xT=(e,t)=>{let n=t?.trim();if(!n)return e.length===0||e.some(e=>bT(yT(e)));let r=e.find(e=>e?.name===n);return!r||bT(yT(r))},ST=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)},CT=null,wT=new Set,TT=()=>{for(let e of wT)e()},ET=e=>e===`chat`||e===`assistant`,DT=()=>CT,OT=e=>{CT!==e&&(CT=e,TT())},kT=e=>{CT&&(e&&CT.surfaceID!==e||(CT=null,TT()))},AT=(e,t)=>{if(e.transportIdentity!==t.transportIdentity||e.runtimeGeneration!==t.runtimeGeneration)throw Error(`chat-input-delivery-runtime-stale`)},jT=e=>{let t=e.options?.delivery===`steer`?`steer`:e.options?.delivery===`queue`?`queue`:void 0,n={...t?{delivery:t}:{},...e.options?.commitStagedMessageEdit===void 0?{}:{commitStagedMessageEdit:e.options.commitStagedMessageEdit},...e.options?.messageID?{messageID:e.options.messageID}:{},...e.options?.ticket?{ticket:e.options.ticket}:{}},r=e.options?.sessionId??e.sessionID??void 0;if(!r)return n;let i=e.options?.directoryHint===void 0?e.directory||null:e.options.directoryHint;return{...n,sessionId:r,directoryHint:i}},MT=(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}),NT=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=MT(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=MT(e,`send`,i),o=ub(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=MT(e,`create`);return await e.selection.flush(),e.backend.create(t)},compact:async t=>{let n=MT(e,`compact`,t);return await e.selection.flush(),e.backend.compact(n)},abort:async()=>{let t=MT(e,`abort`);return await e.selection.flush(),e.backend.abort(t)},queueScope:ub(e),canAbort:n,canQueue:t===`busy`||t===`retry`,allowsCommand:t=>rb(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=MT(e,`abort`);await e.selection.flush(),await e.backend.abort(t);return}if(t===`new`){let t=MT(e,`create`);await e.selection.flush(),await e.backend.create(t);return}t!==`submit`&&await e.shortcuts?.cycle(n)},resources:e.resources??null}},PT=(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)))},FT=(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},IT=(e,t)=>e.agents.some(e=>e.name===t),LT=(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},RT=e=>{let{catalog:t,providerID:n,modelID:r,historyVariant:i,memoryVariant:a}=e;if(i)return LT(t,n,r,i)?i:void 0;if(a&<(t,n,r,a))return a},zT=e=>{let{sessionId:t,choice:n,catalog:r,memory:i,fallbackAgentName:a,source:o}=e;if(!n.providerID||!n.modelID||!FT(r,n.providerID,n.modelID))return null;let s=n.agent&&IT(r,n.agent)?n.agent:i?.getSessionAgentSelection?.(t)&&IT(r,i.getSessionAgentSelection(t))?i.getSessionAgentSelection(t):a&&IT(r,a)?a:void 0,c=s?i?.getAgentModelVariantForSession?.(t,s,n.providerID,n.modelID):void 0,l=RT({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}},BT=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=zT({sessionId:t,choice:r,catalog:i,memory:a,fallbackAgentName:s,source:`execution`});if(e)return e}if(c&&n){let e=zT({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&&IT(i,e)?e:s&&IT(i,s)?s:void 0;if(n){let e=a.getAgentModelForSession?.(t,n);if(e&&FT(i,e.providerId,e.modelId)){let r=a.getAgentModelVariantForSession?.(t,n,e.providerId,e.modelId),o=r&<(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&&FT(i,r.providerId,r.modelId)){let e=n?a.getAgentModelVariantForSession?.(t,n,r.providerId,r.modelId):void 0,o=e&<(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&&FT(i,l.providerID,l.id)){let e=a?.getSessionAgentSelection?.(t)??null,n=(o?.agent&&IT(i,o.agent)?o.agent:void 0)??(e&&IT(i,e)?e:s&&IT(i,s)?s:void 0),r=l.variant,c=r&<(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},VT=(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))},HT=(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}},UT=e=>e.editRevision<=0?!1:e.pinnedHistoryMessageId==null||e.latestHistoryMessageId==null||e.latestHistoryMessageId===e.pinnedHistoryMessageId,WT=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}:{}}},GT=e=>typeof e==`string`&&e.trim().length>0?e:void 0,KT=e=>GT(e.agent)??GT(e.mode),qT=e=>GT(typeof e.model==`object`?e.model?.variant:void 0)??GT(e.variant),JT=e=>{let t=typeof e.model==`object`?e.model:void 0,n=GT(e.providerID)??GT(t?.providerID),r=GT(e.modelID)??GT(t?.modelID)??GT(t?.id);return!n||!r?null:{providerID:n,modelID:r}},YT=e=>JT(e),XT=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role!==`user`)continue;let r=JT(n);return{id:typeof n.id==`string`?n.id:void 0,agent:KT(n),providerID:r?.providerID,modelID:r?.modelID,variant:qT(n)}}return null},ZT=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`){if(JT(n))return null;continue}if(n.role!==`assistant`)continue;let r=YT(n);if(r)return{id:typeof n.id==`string`?n.id:void 0,agent:KT(n),providerID:r.providerID,modelID:r.modelID,variant:qT(n)}}return null},QT=500,$T=e=>Array.from(e).length,eE=e=>{let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(36)},tE=e=>$T(e)>=QT,nE=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},rE=(e,t)=>{let n=t??e;return typeof n!=`string`||!tE(n)?!1:y(typeof e==`string`?{text:``,references:[]}:e,n)},iE=(e,t,n,r,i=1)=>{let a=$T(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}-${eE(e)}`,token:i,text:e,characterCount:a,index:n}}throw Error(`Unable to create a unique pasted text reference`)},aE=e=>({text:e?.text??``,references:e?.composerReferences??[]}),oE=e=>({text:e.text,references:e.references.map(e=>({...e}))}),sE=e=>({transportIdentity:e.transportIdentity,owner:{...e.owner}}),cE=e=>JSON.stringify([e.text,e.references]),lE=(e,t)=>e!==null&&t!==null&&A(e)===t,uE=(e,t,n)=>{let r=e?sE(e):null,i=r?n(r):void 0;return{document:v(aE(i),t),mentions:i?.mentions??[],revision:i?.revision??0,key:r,keyID:r?A(r):null}},dE=(e,t,n,r)=>{if(!t||A(t.key)!==r.keyID||t.revision<r.appliedRevision)return`ignore`;let i=cE(aE(t));return n?.keyID===r.keyID&&n.revision===t.revision&&n.fingerprint===i?`local-echo`:t.revision===r.appliedRevision?`ignore`:i===cE(e)?`same-document-metadata`:`external-document`},fE=(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}]:[]})},pE=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),mE=(e,t,n,r,i=r)=>{let a=N(e,n,r,i);return{document:a.document,mentions:fE(t,a.document,a.edit),requiresTextCorrection:a.requiresTextCorrection,selectionStart:a.selectionStart,selectionEnd:a.selectionEnd,removedReferences:a.removedReferences}},hE=(e,t,n)=>({preview:{real:oE(e),realMentions:[...t]},document:{text:n.text,references:[]},mentions:[]}),gE=e=>({document:e.real,mentions:e.realMentions}),_E=(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)})},vE=(e,t)=>{let n=aE(t),r=S(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:_E(e.mentions,t?.mentions??[],r,i)}},yE=({draftKey:e,sessionTitles:t,persistenceEnabled:n,onResourcesChanged:r,store:i=yo})=>{let a=e?A(e):null,o=(0,Z.useSyncExternalStore)(i.subscribe,()=>a?i.getState().drafts[a]:void 0,()=>void 0),s=(0,Z.useSyncExternalStore)(i.subscribe,()=>a?i.getState().draftHydration[a]??`idle`:`idle`,()=>`idle`),c=(0,Z.useSyncExternalStore)(i.subscribe,()=>a?i.getState().draftPersistence[a]:void 0,()=>void 0),[l,u]=(0,Z.useState)(()=>uE(e,t,i.getState().getDraft).document),[d,f]=(0,Z.useState)(()=>uE(e,t,i.getState().getDraft).mentions),[m,h]=(0,Z.useState)(`compose`),[g,_]=(0,Z.useState)(0),y=(0,Z.useRef)(l),b=(0,Z.useRef)(d),x=(0,Z.useRef)(t),S=(0,Z.useRef)(r),C=(0,Z.useRef)(e),w=(0,Z.useRef)(e?sE(e):null),T=(0,Z.useRef)(a),E=(0,Z.useRef)(a),D=(0,Z.useRef)(0),O=(0,Z.useRef)(o?.revision??0),k=(0,Z.useRef)(void 0),j=(0,Z.useRef)(void 0),I=(0,Z.useRef)(sl());y.current=l,b.current=d,x.current=t,S.current=r,C.current=e,T.current=a;let L=(0,Z.useCallback)((e,t)=>{y.current=e,b.current=t,u(e),f(t)},[]),R=(0,Z.useCallback)((e,t)=>{let n=de(e,t);S.current?.(n)},[]);(0,Z.useEffect)(()=>{i.getState().setDraftPersistenceEnabled(n)},[n,i]),(0,Z.useLayoutEffect)(()=>{D.current+=1;let e=D.current;E.current=a;let t=uE(C.current,x.current,i.getState().getDraft),n=t.key;if(w.current=t.key,k.current=void 0,j.current=void 0,I.current=sl(),h(`compose`),O.current=t.revision,L(t.document,t.mentions),_(e=>e+1),n?.owner.kind===`draft`){let r=t.revision;i.getState().claimLegacyNewDraft(n).then(t=>{let o=i.getState().getDraft(n);!t||!lE(w.current,a)||E.current!==a||T.current!==a||D.current!==e||O.current!==r||o?.revision!==t.revision||(O.current=t.revision,L(v(aE(t),x.current),t.mentions))})}},[a,L,i]),(0,Z.useEffect)(()=>{if(!a||E.current!==a||j.current)return;let e=dE(y.current,o,k.current,{keyID:a,epoch:D.current,appliedRevision:O.current});if(e!==`ignore`){if(o&&(O.current=o.revision),e===`local-echo`||e===`same-document-metadata`){o&&f(o.mentions);return}e===`external-document`&&o&&(k.current=void 0,L(v(aE(o),x.current),o.mentions),h(`compose`),_(e=>e+1))}},[a,L,o]);let z=(0,Z.useCallback)((e,t)=>{let n=w.current;if(!lE(n,T.current)||j.current)return;let r=y.current,a=i.getState().setDraftComposerState(n,{document:e,mentions:pE(t)});if(!a)return;let o=aE(a);return k.current={keyID:A(n),revision:a.revision,fingerprint:cE(o)},O.current=a.revision,L(o,a.mentions),R(r,o),a},[i,L,R]),B=(0,Z.useCallback)((e,t,n,r,i,a)=>{I.current=fl(I.current,{before:el(e,t,n),after:el(r,i,a)})},[]),V=(0,Z.useCallback)(()=>j.current?(j.current=void 0,h(`compose`),!0):!1,[]),H=(0,Z.useCallback)(e=>(V(),z({text:e,references:[]},[])),[z,V]),ee=(0,Z.useCallback)((e,t=[])=>{V();let n=oe(e.text,e.references);return n?z(v(n,x.current),t):void 0},[z,V]),U=(0,Z.useCallback)((e,t,n=t,r)=>{let i=V(),a=oE(y.current),o=i?[]:b.current,s=mE(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,Z.useCallback)((e,t)=>{let n=y.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=N(n,`${n.text.slice(0,r)}${e.text}${n.text.slice(i)}`,r+e.text.length),s=fE(a?[]:b.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,Z.useCallback)((e,t)=>{let n=y.current;return te({start:0,end:n.text.length,text:e},t)},[te]),ne=(0,Z.useCallback)((e,t,n,r)=>{let i=V(),a=M(y.current,e,t,n,r);return z(a.document,fE(i?[]:b.current,a.document,a.edit)),{start:a.caret,end:a.caret,caret:a.caret,document:a.document}},[z,V]),re=(0,Z.useCallback)(e=>{let t=oE(y.current),n=F(t,e);if(!n)return null;let r=V()?[]:b.current,i=fE(r,n.document,n.edit),a=P(n.document.text,n.caret),o=N(n.document,a.text,a.caret),s=fE(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]),ie=(0,Z.useCallback)(e=>{if(j.current)return null;let t=e===`undo`?nl(I.current,y.current):tl(I.current,y.current);return!t||!z(t.snapshot.document,t.snapshot.mentions)?null:(I.current=t.history,t.snapshot.selection)},[z]),ae=(0,Z.useCallback)(e=>z(y.current,e),[z]),se=(0,Z.useCallback)(e=>{let t=j.current?{document:{text:e.text,references:[]},mentions:[]}:hE(y.current,b.current,e);`preview`in t&&(j.current=t.preview),h(`history-preview`),L(t.document,t.mentions),_(e=>e+1)},[L]),ce=(0,Z.useCallback)(()=>{let e=j.current;if(!e)return;j.current=void 0,h(`compose`);let t=gE(e);L(t.document,t.mentions),_(e=>e+1)},[L]),le=(0,Z.useCallback)(()=>{let e=w.current;if(!lE(e,T.current))return null;let t=i.getState().getDraft(e);return{key:sE(e),keyID:A(e),revision:t?.revision??0,document:oE(y.current),mentions:b.current.map(e=>({...e,range:{...e.range}})),epoch:D.current,runtime:i.getState().captureDraftRuntime()}},[i]),ue=(0,Z.useCallback)(e=>{let t=vE(e,i.getState().getDraft(e.key)),n=aE(i.getState().getDraft(e.key)),r=p(n.text,n.references).document,a=i.getState().setDraftComposerState(e.key,{...t,mentions:pE(t.mentions)});if(a){let e=aE(a);R(r,e)}return a},[R,i]),fe=(0,Z.useCallback)(()=>y.current,[]);return(0,Z.useMemo)(()=>({document:l,mentions:d,confirmedFileMentions:d.filter(e=>e.kind===`file`||e.kind===`directory`),inputMode:m,hydration:s,persistence:c,textPresetEpoch:g,getDocument:fe,replacePlainDocument:H,replaceMaterializedDocument:ee,applyBrowserEdit:U,applyProgrammaticEdit:te,replaceProgrammaticText:W,insertReference:ne,deleteReference:re,restoreReferenceHistory:ie,commitMentions:ae,enterHistoryPreview:se,exitHistoryPreview:ce,captureSubmission:le,recoverSubmission:ue}),[U,te,le,ae,re,l,se,ce,fe,s,m,ne,d,c,ue,ee,H,W,ie,g])};function bE(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 xE=`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`,SE=Cu(()=>Sn(()=>import(`./ToolOutputDialog-izZjgkkg.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]))),CE=[],wE=[],TE=[],EE=[],DE=/^@[^\s]+$/,OE=({inputMode:e,message:t,showCommandAutocomplete:n})=>e!==`shell`&&(n||/(^|\s)\/[A-Za-z0-9_-]*/.test(t)),kE=/^(https?:\/\/|mailto:)\S+$/i,AE=560,jE=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),ME=(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)},NE=e=>e.includes(`@`)?`paste`:`manual`,PE=(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}},FE=(e,t)=>mn(e,t).some(e=>e.role===`user`),IE=(e,t)=>{let n=e.filter(e=>e.type===`text`&&!gi(e)).map(e=>{let t=e;return typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:``}).join(`
|
|
6545
6545
|
`).replace(/\s+/g,` `).trim();if(n)return n;let r=e.find(e=>e.type===`file`);return r?.filename?`[${r.filename}]`:t},LE=`file://`,RE=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(`/`)},zE=e=>{let t=e.replace(/\\/g,`/`).trim();return t.toLowerCase().startsWith(LE)?t:`file://${RE(t)}`},BE=e=>{if(!e)return[];let t=[...LC(e).map(RC),...Array.from(e.files||[]).map(e=>I(e)).filter(e=>!!e)];return Array.from(new Set(t.filter(zC)))},VE=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},HE=e=>Gn(e.path),UE=(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)]})},WE=Z.memo(Ab),GE=Z.memo(fh),KE=Z.memo(Rx),qE=Z.memo(Vx),JE=Z.memo(rx),YE=Z.memo(({sessionId:e,directory:t})=>{let{t:n}=Wn(),r=K(e=>e.isMobile),i=Y(e=>e.revertToMessage),a=Y(e=>e.forkFromMessage),o=Y(e=>e.handleSlashRedo),[s,c]=Z.useState(null),[l,u]=Z.useState(null),[d,f]=Z.useState(!0),p=Z.useRef(gC),m=Bo(),h=t||m,g=Nr(h),_=an(e??``,h,g),v=Kr(e=>e.session,h),y=Z.useMemo(()=>{let t=_.messageOrder.map(e=>_.messagesByID[e]).filter(e=>!!e),n=yC({session:v,messages:t,partsByMessageID:_.partsByMessageID},e,p.current);return p.current=n,n},[e,v,_]),b=y.revertMessageID,x=Z.useMemo(()=>{let t=v.find(t=>t.id===e);return $t(t?.revert)},[e,v]),S=Z.useMemo(()=>y.records.map(e=>e.message),[y]),C=n(`chat.revertPopover.noTextContent`),w=Z.useMemo(()=>b?y.records.map(e=>({id:e.message.id,text:IE(e.parts,C)})):[],[C,b,y]),T=w[0]?.id;Z.useEffect(()=>{f(!0)},[b,T]);let E=Z.useCallback(async t=>{if(!(!e||s)){c(t);try{let n=S.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,S]),D=Z.useCallback(async t=>{if(!(!e||l)){u(t);try{await a(e,t)}finally{u(null)}}},[a,l,e]);return!e||w.length===0?null:(0,$.jsx)(`div`,{className:J(`w-full px-1`,r?`pb-1 text-xs`:`pb-2`),children:(0,$.jsxs)(`div`,{className:J(`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:J(`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 `,w.length]}),x.length>0&&(0,$.jsxs)(`span`,{className:`min-w-0 truncate typography-ui-label text-muted-foreground`,children:[n(`chat.revertPopover.files`),`: `,x.join(`, `)]}),(0,$.jsx)(X,{name:`arrow-down-s`,className:J(`ml-auto text-muted-foreground transition-transform`,r?`size-3.5`:`size-4`,!d&&`rotate-180`),"aria-hidden":`true`})]}),!d&&(0,$.jsx)(`div`,{className:J(`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:w.map(e=>(0,$.jsxs)(`div`,{className:J(`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)(Jn,{type:`button`,variant:`secondary`,size:`xs`,disabled:!!(s||l),onClick:()=>{D(e.id)},children:[l===e.id?(0,$.jsx)(X,{name:`loader-4`,className:`h-3 w-3 animate-spin`,"aria-hidden":`true`}):(0,$.jsx)(X,{name:`git-branch`,className:`h-3 w-3`,"aria-hidden":`true`}),n(`chat.revertPopover.fork`)]}),(0,$.jsxs)(Jn,{type:`button`,variant:`secondary`,size:`xs`,disabled:!!(s||l),onClick:()=>{E(e.id)},children:[s===e.id?(0,$.jsx)(X,{name:`loader-4`,className:`h-3 w-3 animate-spin`,"aria-hidden":`true`}):(0,$.jsx)(X,{name:`arrow-go-forward`,className:`h-3 w-3`,"aria-hidden":`true`}),n(`chat.revertPopover.restore`)]})]},e.id))})]})})});YE.displayName=`RevertedMessageDock`;var XE=Z.memo(function(e){let t=(0,Q.c)(41),{t:n}=Wn(),{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?oD:void 0,v=f?sD:void 0,y;t[5]===a?y=t[6]:(y=J(a,`text-current`),t[5]=a,t[6]=y);let b;t[7]===y?b=t[8]:(b=(0,$.jsx)(X,{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)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:S}),(0,$.jsx)(Ds,{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)(X,{name:`ai-agent`,className:J(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),ZE=Z.memo(function(e){let t=(0,Q.c)(29),{t:n}=Wn(),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=()=>ST({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=J(e.iconSizeClass,`text-current`),t[12]=e.iconSizeClass,t[13]=d);let f;t[14]!==u||t[15]!==d?(f=(0,$.jsx)(X,{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)(Es,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,disabled:o,"aria-pressed":s,"aria-label":a,className:c,onClick:l,onMouseDown:cD,onPointerDownCapture:lD,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)(Ds,{side:`top`,sideOffset:8,children:a}),t[24]=a,t[25]=m);let h;return t[26]!==m||t[27]!==p?(h=(0,$.jsxs)(Os,{children:[p,m]}),t[26]=m,t[27]=p,t[28]=h):h=t[28],h}),QE=Z.memo(function(e){let t=(0,Q.c)(65),{isMobile:n,compact:r,footerIconButtonClass:i,stopFooterIconButtonClass:a,compactCircleButtonClass:o,sendIconSizeClass:s,stopIconSizeClass:c,canSend:l,canAbort:u,abortPending:d,hasContent:f,currentSessionId:p,newSessionDraftOpen:m,draftSubmitting:h,submissionBlocked:g,sendPhase:_,queueFrozen:v,queueFallbackAvailable:y,onPrimaryAction:b,onAbort:x}=e,S=r!==void 0&&r,{t:C}=Wn(),w=u,T,E,D,O,k;if(t[0]!==w||t[1]!==l||t[2]!==S||t[3]!==o||t[4]!==p||t[5]!==h||t[6]!==i||t[7]!==f||t[8]!==n||t[9]!==m||t[10]!==b||t[11]!==y||t[12]!==v||t[13]!==s||t[14]!==_||t[15]!==a||t[16]!==c||t[17]!==g||t[18]!==C){k=Symbol.for(`react.early_return_sentinel`);bb0:{let e=$x({canSend:l,hasSessionTarget:!!(p||m),draftSubmitting:!!h,submissionBlocked:g,sendPhase:_,queueFrozen:v,queueFallbackAvailable:y}),r;t[24]===n?r=t[25]:(r=n?{onMouseDown:uD,onPointerDownCapture:dD}:{},t[24]=n,t[25]=r);let u=r,d=_.inFlight,x=d&&_.flightKind===`queue`,A=d&&_.flightKind!==`queue`,j;t[26]!==x||t[27]!==A||t[28]!==C?(j=C(x?`chat.chatInput.actions.queuingMessageAria`:A?`chat.chatInput.actions.sendingMessageAria`:`chat.chatInput.actions.sendMessageAria`),t[26]=x,t[27]=A,t[28]=C,t[29]=j):j=t[29];let M=j;T=S?o??a??i:a??i,E=c;let N=!w&&(!e.sendDisabled||d),P;t[30]!==n||t[31]!==b?(P=e=>{n&&(e.preventDefault(),b())},t[30]=n,t[31]=b,t[32]=P):P=t[32];let F;t[33]!==w||t[34]!==d||t[35]!==x||t[36]!==A||t[37]!==C?(F=C(A||!w&&d?x?`chat.chatInput.actions.queuingMessageAria`:`chat.chatInput.actions.sendingMessageAria`:`chat.chatInput.actions.sendMessageAria`),t[33]=w,t[34]=d,t[35]=x,t[36]=A,t[37]=C,t[38]=F):F=t[38];let I;t[39]!==w||t[40]!==E||t[41]!==d||t[42]!==s||t[43]!==N?(I=N?(0,$.jsx)(Kc,{className:E,spinning:!!(d&&!w)}):(0,$.jsx)(X,{name:`send-plane-2`,className:s}),t[39]=w,t[40]=E,t[41]=d,t[42]=s,t[43]=N,t[44]=I):I=t[44];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":d||void 0,...u,onClick:P,className:J(N?T:i,N?void 0:e.sendDisabled?e.disabledClass:`text-primary hover:text-primary`),"aria-label":F,children:I});if(!w){k=L;break bb0}let R=!S&&(f||x),z=!e.sendDisabled&&!x,B=S&&`h-full`;t[45]===B?D=t[46]:(D=J(`relative z-30 overflow-visible`,B),t[45]=B,t[46]=D),O=R?(0,$.jsx)(`button`,{type:`button`,"data-composer-send":`true`,"data-composer-circle":z||x?`true`:void 0,disabled:e.sendDisabled||x,"aria-busy":x||void 0,...u,onClick:e=>{e.preventDefault(),!x&&b()},className:J(z||x?T:i,`absolute z-30 bottom-full left-1/2 -translate-x-1/2 mb-1`,z||x?void 0:e.disabledClass),"aria-label":M,children:z||x?(0,$.jsx)(Kc,{className:E,spinning:x}):(0,$.jsx)(X,{name:`send-plane-2`,className:s})}):null}t[0]=w,t[1]=l,t[2]=S,t[3]=o,t[4]=p,t[5]=h,t[6]=i,t[7]=f,t[8]=n,t[9]=m,t[10]=b,t[11]=y,t[12]=v,t[13]=s,t[14]=_,t[15]=a,t[16]=c,t[17]=g,t[18]=C,t[19]=T,t[20]=E,t[21]=D,t[22]=O,t[23]=k}else T=t[19],E=t[20],D=t[21],O=t[22],k=t[23];if(k!==Symbol.for(`react.early_return_sentinel`))return k;let A=d||void 0,j;t[47]===T?j=t[48]:(j=J(T,`relative z-30`),t[47]=T,t[48]=j);let M;t[49]===C?M=t[50]:(M=C(`chat.chatInput.actions.stopGeneratingAria`),t[49]=C,t[50]=M);let N;t[51]!==d||t[52]!==E?(N=d?(0,$.jsx)(Kc,{className:E,spinning:!0}):(0,$.jsx)(ml,{className:J(E)}),t[51]=d,t[52]=E,t[53]=N):N=t[53];let P;t[54]!==d||t[55]!==x||t[56]!==A||t[57]!==j||t[58]!==M||t[59]!==N?(P=(0,$.jsx)(`button`,{type:`button`,"data-composer-stop":`true`,onClick:x,disabled:d,"aria-busy":A,className:j,"aria-label":M,children:N}),t[54]=d,t[55]=x,t[56]=A,t[57]=j,t[58]=M,t[59]=N,t[60]=P):P=t[60];let F;return t[61]!==D||t[62]!==O||t[63]!==P?(F=(0,$.jsxs)(`div`,{className:D,children:[O,P]}),t[61]=D,t[62]=O,t[63]=P,t[64]=F):F=t[64],F},(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.abortPending===t.abortPending&&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),$E=(e,t)=>`${e}${e?e.endsWith(`
|
|
6546
6546
|
|
|
6547
6547
|
`)?``:e.endsWith(`
|
|
@@ -6554,7 +6554,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}f
|
|
|
6554
6554
|
`)?`${t}\n`:`${t}\n\n`}`,eD=(e,t)=>{let n=t.trim();return n?e?`${e}${/[\s\n]$/.test(e)?``:` `}${n} `:`${n} `:e},tD=(e,t,n,r)=>t?E({transportIdentity:e},t):n?m({transportIdentity:e},n):r,nD=[],rD=({onOpenSettings:e,scrollToBottom:t,showScrollToBottom:n=!1,onScrollToBottom:r,submissionBlocked:a=!1,surface:s})=>{let{t:l}=Wn(),d=Zl(),[f,m]=Z.useState({open:!1,title:``,content:``}),[h,g]=Z.useState(`normal`),[v,y]=Z.useState(!1),[b,S]=Z.useState(!1),[C,w]=Z.useState(!1),[E,O]=Z.useState(``),[k,M]=Z.useState(!1),[N,P]=Z.useState(``),[F,I]=Z.useState([]),[L,z]=Z.useState(0),[B,ee]=Z.useState(null),[te,W]=Z.useState(null),ne=Z.useRef(null),ie=Z.useRef(null),[ae,oe]=Z.useState(!1),se=Z.useRef(null);Z.useEffect(()=>()=>{se.current!==null&&window.clearTimeout(se.current),ne.current!==null&&window.clearTimeout(ne.current),ie.current!==null&&window.clearTimeout(ie.current)},[]);let[ce,le]=Z.useState(!1),[ue,de]=Z.useState(!1),[me,he]=Z.useState(null),_e=Z.useId(),[ye,be]=Z.useState(``),[Se,Ce]=Z.useState(``),[we,Te]=Z.useState(!1),[Oe,ke]=Z.useState(!1),Ae=Z.useRef(0),je=Z.useCallback(()=>{Ae.current=Date.now()+500},[]),Me=Z.useRef(0),Ne=Z.useRef(!1),[Pe,Fe]=Z.useState(-1),Ie=Z.useRef(()=>{}),Le=Z.useRef((...e)=>Promise.resolve().then(()=>Y.getState().sendMessage(...e))).current,Re=Y(e=>e.currentSessionId),ze=ao(e=>e.currentProviderId),Be=ao(e=>e.currentModelId),Ve=ao(e=>e.currentAgentName),He=ao(e=>e.currentVariant),Ue=ao(e=>e.providers),We=ao(e=>e.agents),Ge=ao(e=>e.getVisibleAgents),Ke=Z.useMemo(()=>qy(Ge()),[Ge,We]),qe=ao(e=>e.providerConfigLoadingByDirectory[e.activeDirectoryKey]===!0),Je=ao(e=>e.agentConfigLoadingByDirectory[e.activeDirectoryKey]===!0),Ye=Z.useMemo(()=>{let e=Ue.find(e=>e.id===ze)?.models?.find(e=>e.id===Be);return eb(e)},[Be,ze,Ue]),Xe=lt(e=>e.currentDirectory),Ze=qu()??Xe,{ensureSessionRenderable:Qe}=Ih(),$e=Y(Z.useCallback(e=>Re?e.getDirectoryForSession(Re):null,[Re])),et=ma(Re??``,$e??void 0),tt=Z.useMemo(()=>XT(et),[et]),nt=Z.useMemo(()=>ZT(et),[et]),rt=za(Re??``,$e??void 0).renderable,at=Sa(Re,$e??void 0),ot=at?.agent,st=at?.model?.id,ct=at?.model?.providerID,dt=at?.model?.variant,pt=ao(e=>e.activeDirectoryKey),mt=Z.useRef(0),ht=Z.useRef(null),gt=Z.useRef(null),_t=Y(e=>e.newSessionDraft),vt=!!_t?.open,yt=Y(e=>e.newSessionDraft.draftSubmitting??!1),bt=Y(e=>e.newSessionDraft.draftEstablishing??!1),St=yt||bt,wt=Y(e=>e.openNewSessionDraft),Tt=Y(e=>e.setDraftPermissionAutoAcceptEnabled),Et=fr(e=>e.autoAccept),Dt=fr(e=>e.saving),Ot=fr(e=>e.setSessionAutoAccept),jt=Y(e=>e.setNewSessionDraftTarget),Mt=Y(e=>e.availableWorktreesByProject),Ft=Y(e=>e.abortPromptSessionId),It=Y(e=>e.abortPromptExpiresAt),zt=Y(e=>e.clearAbortPrompt),Bt=yo(e=>e.consumePendingInputText),Vt=yo(e=>e.pendingPresetSubmit),Ht=yo(e=>e.pendingInputText),Wt=yo(e=>e.pendingInputMode),Gt=yo(e=>e.consumePendingSyntheticParts),Kt=yo(e=>e.activeAttachmentDraft),qt=Hh(Z.useCallback(e=>{let t=Re??(vt?`draft`:``);return t?e.drafts[t]??wE:wE},[vt,Re])),$t=ua(Re??``),en=Z.useSyncExternalStore(i,o,o),tn=Kt?.transportIdentity??null,nn=Kt?.owner.kind??null,an=Kt?.owner.ownerID??null,sn=Z.useMemo(()=>tD(en,Re,_t.draftID,tn&&nn&&an?{transportIdentity:tn,owner:{kind:nn,ownerID:an}}:null),[an,nn,tn,en,Re,_t.draftID]),cn=sn?A(sn):null,ln=yo(Z.useCallback(e=>cn?e.draftAttachmentViews[cn]:void 0,[cn])),dn=yo(Z.useCallback(e=>cn?e.drafts[cn]:void 0,[cn])),pn=Z.useMemo(()=>{if(!dn||!ln)return nD;let e=dn.attachments.flatMap(e=>{let t=ln[e.attachmentRefID];return t?[t]:[]});return e.length===0?nD:e},[ln,dn]);Z.useEffect(()=>{sn&&yo.getState().hydrateDraftAttachments(sn)},[sn]);let hn=ab(),gn=K(e=>e.activeMainTab===`chat`),_n=so(Re??``,Ze??void 0),vn=ob({kind:`primary`,surfaceID:`primary`,active:gn,sessionID:Re,directory:Ze??null,activity:{phase:_n?.type===`busy`?`busy`:_n?.type===`retry`?`retry`:`idle`,canAbort:_n?.type===`busy`||_n?.type===`retry`},draftKey:sn,transportIdentity:en,runtimeGeneration:c(),selection:{value:{providerID:ze,modelID:Be,agent:Ve,variant:He},catalog:{providers:Ue,agents:Ke,variants:Ye,variantsReady:!qe,ready:!qe&&!Je,loading:qe||Je},flush:async()=>{let e=Y.getState().currentSessionId;if(!e)return;let t=c(),n=o(),r=mt.current,i=e,a=Y.getState().getDirectoryForSession(i)??null,s=Ea(a);if(ao.getState().activeDirectoryKey!==s&&await ao.getState().activateDirectory(a),c()!==t||o()!==n||Y.getState().currentSessionId!==i||ao.getState().activeDirectoryKey!==s||mt.current!==r)return;await Qe(i,{directory:a??void 0});let l=Y.getState().getDirectoryForSession(i)??null,u=Ea(l);if(c()!==t||o()!==n||Y.getState().currentSessionId!==i||l!==a||u!==s||ao.getState().activeDirectoryKey!==s||mt.current!==r)return;let d=ao.getState(),f={providers:d.providers,agents:d.getVisibleAgents()};if(f.providers.length===0||f.agents.length===0)return;let p=mn(i,l??void 0),m=XT(p),h=ZT(p);if(UT({editRevision:r,pinnedHistoryMessageId:ht.current,latestHistoryMessageId:m?.id??null}))return;let g=zo.getState(),_=Ct().get(i),v=BT({sessionId:i,latestUserChoice:m,latestExecution:h,catalog:f,memory:g,sessionEntity:_?.model?{agent:_.agent,model:{id:_.model.id,providerID:_.model.providerID,variant:_.model.variant}}:_?.agent?{agent:_.agent}:null,fallbackAgentName:d.currentAgentName});if(!v)return;let y=[i,v.source,v.messageId??``,v.agent??``,v.providerID,v.modelID,v.variant??``,s].join(`|`);gt.current!==y&&(VT(v,{currentAgentName:d.currentAgentName,setAgent:d.setAgent,setProvider:d.setProvider,setModel:d.setModel,setCurrentVariant:d.setCurrentVariant},{sessionId:i,memory:g}),gt.current=y)},change:async e=>{mt.current+=1;let t=Y.getState().currentSessionId;if(t){let e=Y.getState().getDirectoryForSession(t)??void 0,n=XT(mn(t,e));ht.current=n?.id??null}else ht.current=null;let n=ao.getState();PT(e,{currentAgentName:n.currentAgentName,setAgent:n.setAgent,setProvider:n.setProvider,setModel:n.setModel,setCurrentVariant:n.setCurrentVariant,saveAgentModelSelection:n.saveAgentModelSelection},{sessionId:t,memory:zo.getState()})}},resources:{attachments:pn,addAttachment:async e=>{sn&&await Si(sn,()=>yo.getState()).addLocal(e)},removeAttachment:async e=>sn?Si(sn,()=>yo.getState()).removeByAttachmentID(e):!1,clearAttachments:async()=>sn?Si(sn,()=>yo.getState()).clearRootAttachments():!1,restoreAttachments:async e=>sn?Si(sn,()=>yo.getState()).restoreRootAttachments(e):!1,pendingInput:Ht===null?null:{text:Ht,mode:Wt},consumePendingInput:Bt,pendingPreset:Vt,consumePendingPreset:()=>yo.getState().consumePendingPresetSubmit(),consumeSyntheticParts:Gt,restoreSyntheticParts:e=>yo.setState(t=>({pendingSyntheticParts:[...e,...t.pendingSyntheticParts??[]]})),inlineDrafts:qt,removeInlineDraft:e=>{let t=Re??(vt?`draft`:``);t&&Hh.getState().removeDraft(t,e)},restoreInlineDrafts:e=>{let t=Re??(vt?`draft`:``);!t||e.length===0||Hh.setState(n=>{let r=n.drafts[t]??[],i=new Set(e.map(e=>e.id));return{drafts:{...n.drafts,[t]:[...e,...r.filter(e=>!i.has(e.id))]}}})},history:$t,captureRuntime:()=>yo.getState().captureDraftRuntime(),getDraft:e=>yo.getState().getDraft(e),abortPrompt:{sessionID:Ft,clear:zt}},backend:{send:e=>{AT(e,{transportIdentity:o(),runtimeGeneration:c()});let t=jT(e);return Le(e.text??``,e.providerID,e.modelID,e.agent,e.attachments??[],e.agentMention,e.parts,e.variant,e.inputMode,t)},sendQueued:e=>Pr(e.sessionID??``,{delivery:e.options?.delivery===`steer`?`steer`:void 0,queueItemID:e.queueItemID,manual:e.manual,scope:e.queueScope?{state:`bound`,...e.queueScope}:void 0}),create:async()=>wt(),compact:async e=>xt.summarizeSession(e.sessionID??``,e.providerID??``,e.modelID??``,e.directory),abort:e=>(e.sessionID&&bi(e.sessionID),fo(e.sessionID??``))},shortcuts:{cycle:e=>Ie.current(e),new:()=>wt(),abort:()=>(Re&&bi(Re),fo(Re??``)),submit:()=>{}},deliveryTarget:{kind:`primary`}}),G=sb(vn,s??hn);cb(G),Z.useLayoutEffect(()=>{if(!G.active){kT(G.surfaceID);return}return OT(G),()=>kT(G.surfaceID)},[G]);let yn=NT(G),bn=G.resources??(G.kind===`primary`?vn.resources:void 0);if(!bn)throw Error(`chat-input-surface-resources-incomplete`);let xn=[...bn.attachments],Sn=G.sessionID,Cn=lb(G,St),wn=G.kind===`secondary`?G.commands.hasNewDraft:vt,Tn=wn,En=G.directory??Ze,Dn=G.draftKey??sn,On=Z.useMemo(()=>{if(G.kind===`secondary`)return db(G,!1,!1);let e=Sn?FE(Sn,$e??void 0):!1;return db(G,e,wn)},[G,Sn,$e,wn]),kn=(e,t,n,r,i,a,o,s,c,l)=>yn?yn.send({providerID:t,modelID:n,agent:r,variant:s,text:e,attachments:i,agentMention:a,parts:o,systemContext:o?.filter(e=>e.synthetic).map(e=>({text:e.text,synthetic:!0})),inputMode:c,options:l}):Promise.reject(Error(`chat-input-surface-incomplete`)),An=Z.useCallback(()=>yn?yn.abort():Promise.reject(Error(`chat-input-surface-incomplete`)),[yn]),jn=Co(e=>e.projects),Mn=Co(e=>e.activeProjectId),Nn=Co(e=>e.setActiveProjectIdOnly),[Pn,Fn]=Z.useState(!1),[Ln,Rn]=Z.useState(!1),zn=Z.useMemo(()=>Sn?Po({autoAccept:Et,sessions:[],sessionById:Ct(),sessionID:Sn}):_t.permissionAutoAcceptEnabled===!0,[Sn,_t.permissionAutoAcceptEnabled,Et]),Bn=ao(e=>e.agents),Vn=G.kind===`secondary`?G.selection.value.agent:Ve,Hn=G.kind===`secondary`?qy(G.selection.catalog?.agents):Bn,Un=fe()||xT(Hn,Vn),Kn=Z.useCallback(()=>{Ha.error(l(`chat.chatInput.toast.togglePermissionAutoAcceptFailed`))},[l]),qn=G.selection.value,Jn=G.selection.change,Yn=G.selection.catalog,Xn=Z.useMemo(()=>({selection:{providerID:qn.providerID??``,modelID:qn.modelID??``,agent:qn.agent??null,variant:qn.variant},onChange:async e=>{if(!Jn)throw Error(`chat-input-surface-selection-readonly`);await Jn({...e,agent:e.agent??void 0,variant:e.variant})},disabled:!G.active,catalog:Yn}),[Yn,Jn,qn.agent,qn.modelID,qn.providerID,qn.variant,G.active]);Z.useEffect(()=>{mt.current=0,ht.current=null,gt.current=null},[Re]),Z.useEffect(()=>{if(G.kind!==`primary`||!Re||qe||Je||Ue.length===0||Ke.length===0)return;let e=Ea($e);if(pt!==e)return;let t=zo.getState(),n={providers:Ue,agents:Ke};if(UT({editRevision:mt.current,pinnedHistoryMessageId:ht.current,latestHistoryMessageId:tt?.id??null}))return;let r=BT({sessionId:Re,latestUserChoice:tt,latestExecution:nt,catalog:n,memory:t,sessionEntity:ct&&st?{agent:ot,model:{id:st,providerID:ct,variant:dt}}:ot?{agent:ot}:null,fallbackAgentName:Ve,transcriptReady:rt});if(!r)return;let i=[Re,r.source,r.messageId??``,r.agent??``,r.providerID,r.modelID,r.variant??``,pt].join(`|`);if(gt.current===i)return;if((r.agent===void 0||r.agent===Ve)&&r.providerID===ze&&r.modelID===Be&&r.variant===He){gt.current=i;return}if(ao.getState().activeDirectoryKey!==e)return;let a=ao.getState();VT(r,{currentAgentName:a.currentAgentName,setAgent:a.setAgent,setProvider:a.setProvider,setModel:a.setModel,setCurrentVariant:a.setCurrentVariant},{sessionId:Re,memory:t}),gt.current=i},[G.kind,Re,tt,nt,rt,Ue,Ke,qe,Je,pt,$e,Ve,ze,Be,He,ot,st,ct,dt]);let Zn=ao(e=>e.getVisibleAgents),Qn=G.kind===`primary`?Zn():TE,$n=ao(e=>G.kind===`primary`?e.providers:EE),tr=G.kind===`secondary`?qy(G.selection.catalog?.agents):Qn,nr=G.kind===`secondary`?G.selection.catalog?.providers??EE:$n,rr=G.kind===`secondary`&&(!G.selection.catalog?.ready||!!G.selection.catalog.error),ar=!G.active||!G.selection.change||rr,or=K(e=>e.isMobile),sr=al(),cr=K(e=>e.setImagePreviewOpen),lr=Z.useCallback(e=>{e.image&&(m(e),cr(!0))},[cr]),dr=Z.useCallback(e=>{m(t=>({...t,open:e})),cr(e)},[cr]),pr=yh(e=>e.pending),hr=K(e=>e.inputBarOffset),gr=K(e=>e.persistChatDraft),_r=K(e=>e.inputSpellcheckEnabled),vr=K(e=>e.isExpandedInput),yr=K(e=>e.setExpandedInput),br=K(e=>e.setTimelineDialogOpen),xr=yE({draftKey:Dn,sessionTitles:new Map(Array.from(Ct(),([e,t])=>[e,t.title||e])),persistenceEnabled:gr}),Sr=xr.document,Cr=Sr.text,{replacePlainDocument:wr,replaceProgrammaticText:Tr,applyBrowserEdit:Er,insertReference:Or,deleteReference:kr,enterHistoryPreview:Ar,exitHistoryPreview:Nr,captureSubmission:Fr,recoverSubmission:Ir,confirmedFileMentions:Lr,mentions:Rr}=xr,zr=Z.useCallback((e,t)=>Tr(e,t),[Tr]),Br=Z.useMemo(()=>new Set(Lr.map(e=>e.value)),[Lr]),Hr=Z.useRef(null),Ur=Z.useRef(!1),Wr=Z.useRef(0),Gr=Z.useRef(null),Kr=Z.useRef(Cr.length),qr=Z.useRef(null),Jr=Z.useRef(0),Yr=Z.useRef(!1),Xr=Z.useRef(null),Zr=Z.useRef(!1),Qr=Z.useRef(null),ei=Z.useRef([]),ni=Z.useRef(!1),ri=Z.useRef(null),ii=Z.useRef(!1),oi=Z.useRef(null),si=Z.useRef(Cr),ci=Z.useRef(new Set),li=xr.getDocument,di=Z.useCallback((e,t,n=[])=>zr(e,(e,r)=>{let i=[],a=new Set(n);for(let e of t){let t=0,n=`@${e}`;for(;t<r.text.length;){let o=r.text.indexOf(n,t);if(o<0)break;i.push({kind:a.has(e)?`directory`:`file`,value:e,path:e,label:e,range:{start:o,end:o+n.length}}),t=o+n.length}}let o=new Set(e.map(e=>`${e.kind}:${e.value}:${e.range.start}:${e.range.end}`));return[...e,...i.filter(e=>!o.has(`${e.kind}:${e.value}:${e.range.start}:${e.range.end}`))]}),[zr]),fi=$b(Qb()),{git:pi,vscode:mi}=Rc(),gi=K(e=>e.shortcutOverrides.cycle_agent),_i=K(e=>e.shortcutOverrides),vi=Z.useMemo(()=>ic(`cycle_agent`,gi?{cycle_agent:gi}:void 0),[gi]),yi=Z.useMemo(()=>ic(`clear_all_messages`,_i),[_i]),{currentTheme:Ci}=Tc(),wi=bl(),Ti=wl(En),Di=Vl(e=>En?e.directories.get(En)?.status??null:null),Oi=Vl(e=>e.ensureStatus),Ai=Vl(e=>e.fetchStatus),[ji,Mi]=Z.useState(!1),Ni=Z.useRef(null),[Fi,Ii]=Z.useState(!1);Z.useEffect(()=>{!En||!pi||Oi(En,pi)},[En,pi,Oi]),Z.useEffect(()=>{if(!(!En||!pi))return Xa.onGitRefreshHint(e=>{VE(e.directory)===VE(En)&&Ai(En,pi)})},[En,pi,Ai]);let Li=Z.useCallback(async e=>{if(!Sn)return;let t=Y.getState().getDirectoryForSession(Sn)||En||``;if(!t){Ha.error(l(`diffView.reviewDialog.toast.noSessionDirectory`));return}Rn(!0);try{await Mr({originalSessionID:Sn,directory:t,providerID:e.providerID,modelID:e.modelID,agent:e.agent||void 0,variant:e.variant||void 0,generateHandoff:e.generateHandoff,returnAfterHandoffRequest:e.generateHandoff,autoReview:e.autoReview}),Fn(!1)}catch(e){console.error(`[review-flow] failed to start review flow`,e),Ha.error(e instanceof Error?e.message:l(`diffView.reviewDialog.toast.startFailed`))}finally{Rn(!1)}},[Sn,En,l]),Ri=vr&&!or,Bi=vr&&or,Hi=Ri||Bi,Ui=`1.5rem`,Gi=l(Sn||wn?h===`shell`?`chat.chatInput.placeholder.shell`:or||Fi?`chat.chatInput.placeholder.chatCompact`:`chat.chatInput.placeholder.chat`:`chat.chatInput.placeholder.selectSession`),Ki=l(`chat.chatInput.placeholder.compactTap`);Z.useEffect(()=>{let e=qr.current;if(!e)return;let t=e=>{let t=e>0&&e<AE;Ii(e=>e===t?e:t)};if(t(e.clientWidth),typeof ResizeObserver>`u`){let n=()=>t(e.clientWidth);return window.addEventListener(`resize`,n),()=>window.removeEventListener(`resize`,n)}let n=new ResizeObserver(n=>{t(n[0]?.contentRect.width??e.clientWidth)});return n.observe(e),()=>n.disconnect()},[]);let qi=xn,Ji=Z.useMemo(()=>new Set(tr.map(e=>e.name.toLowerCase())),[tr]),Xi=Z.useRef(Ji);Xi.current=Ji;let $i=OE({inputMode:h,message:Cr,showCommandAutocomplete:k}),ea=Ca({directory:En,enabled:$i}),na=Z.useMemo(()=>ea.data??[],[ea.data]),ra=xi({directory:En,enabled:h!==`shell`}),aa=Z.useMemo(()=>ra.data??[],[ra.data]),oa=Z.useMemo(()=>new Map(aa.map(e=>[e.name.toLowerCase(),e.name])),[aa]),la=Z.useMemo(()=>{let e=new Set([`init`,`review`,`undo`,`redo`,`fork`,`timeline`,`model`,`compact`,`summary`,`workspace-review`,`craft-goal`,`goal`,`catch-up`,`debug`,`weigh`,`explore`]);fe()&&e.add(`reload`),!or&&!fe()&&e.add(`handoff-review`);for(let t of na)t.source!==`skill`&&e.add(t.name.toLowerCase());return e},[na,or]),da=Z.useMemo(()=>{if(!Cr||!Cr.includes(`/`)||h===`shell`||la.size===0)return[];let e=[],t=RegExp(`(^|\\s)/(${H})?([A-Za-z0-9][A-Za-z0-9_-]*)`,`g`),n;for(;(n=t.exec(Cr))!==null;){let t=n[2]??``,r=n[3];if(!la.has(r.toLowerCase()))continue;let i=n.index+n[1].length,a=1+t.length+r.length;e.push({start:i,end:i+a,style:`mentionCommand`,visual:re({trigger:`/`,icon:`command`,label:r},Cr.slice(i,i+a))})}return e},[h,la,Cr]),pa=Z.useMemo(()=>!Cr||!Cr.includes(`@`)||h===`shell`?[]:ha(Cr,{confirmedValues:Br,agentNames:Ji}),[Br,h,Ji,Cr]),_a=Z.useMemo(()=>{if(!Cr||!Cr.includes(`[`)||h===`shell`||qi.length===0)return[];let e=qi.filter(it),t=new Map(e.map(e=>[e.filename.trim().toLowerCase(),e.mimeType.startsWith(`image/`)?`image`:`attachment`]));return Ut(Cr,e.map(e=>e.filename)).flatMap(e=>{let n=xe(Cr.slice(e.start+1,e.end-1)).trim(),r=t.get(n.toLowerCase());return[{...e,style:`mentionFile`,priority:101,visual:re({trigger:`[`,icon:r===`image`?`file-image`:`attachment-2`,label:n,suffix:`]`},Cr.slice(e.start,e.end))}]})},[h,Cr,qi]),va=d&&du(or)&&G.kind===`primary`,ya=Z.useMemo(()=>{if(!Cr||h===`shell`)return null;let e=[...va?[]:hl(Cr),...va?[]:kC(Cr),...pl(pa),...da,..._a,...Sr.references.map(e=>({start:e.start,end:e.end,priority:103,...U(e)}))];return cl(Cr,e)},[_a,da,pa,Sr.references,h,Cr,va]),xa=Z.useCallback(e=>(e??[]).map(e=>({...e,dataUrl:e.source===`server`&&e.serverPath?zE(e.serverPath):e.dataUrl})),[]),[wa,Da]=Z.useState(null),Oa=Z.useRef(null),[ka,Aa]=Z.useState(!1),[ja,Ma]=Z.useState(!1),[Na,Fa]=Z.useState(null),[La,Ra]=Z.useState(null),Va=j(e=>e.followUpBehavior),Wa=Z.useMemo(()=>{let e=yn?.queueScope;return e?{state:`bound`,transportIdentity:e.transportIdentity,directory:e.directory,sessionID:e.sessionID,deliveryTarget:e.deliveryTarget,runtimeGeneration:e.runtimeGeneration}:null},[yn]),Ga=tg({transportIdentity:Wa?.transportIdentity??``,directory:Wa?.directory??``,sessionID:Wa?.sessionID??``}),qa=Z.useMemo(()=>Sn?x(Sn):null,[Sn]),Ya=j(Z.useCallback(e=>Wa?_(e,Wa):CE,[Wa])),Za=j(Z.useCallback(e=>qa?_(e,qa):CE,[qa])),Qa=Z.useMemo(()=>Za.length===0?Ya:Ya.length===0?Za:[...Za,...Ya],[Ya,Za]),$a=Ga.mode===`server`?CE:Qa,eo=j(Z.useCallback(e=>Wa?T(e,Wa):CE,[Wa])),ro=j(e=>e.clearQueue),oo=j(e=>e.removeFromQueue),co=bn.inlineDrafts,uo=co.length>0,[po,mo,ho]=Z.useMemo(()=>{let e=0,t=0,n=0;for(let r of co)r.source===`preview-console`?e+=1:r.source===`preview-annotation`?t+=1:n+=1;return[e,t,n]},[co]),vo=Z.useCallback(e=>{for(let t of bn.inlineDrafts)t.source===e&&bn.removeInlineDraft(t.id)},[bn]),xo=Z.useCallback(()=>{for(let e of bn.inlineDrafts)e.source!==`preview-console`&&e.source!==`preview-annotation`&&bn.removeInlineDraft(e.id)},[bn]),So=bn.history;Z.useEffect(()=>{si.current=Cr},[Cr]),Z.useLayoutEffect(()=>{g(`normal`),Fe(-1)},[Dn?.transportIdentity,Dn?.owner.kind,Dn?.owner.ownerID]),Z.useLayoutEffect(()=>{if(!wn||or)return;let e=()=>{let e=Hr.current;!e||e.disabled||e.focus({preventScroll:!0})};e();let t=window.requestAnimationFrame(e);return()=>window.cancelAnimationFrame(t)},[wn,or]);let To=Kx(G.kind===`primary`?Sn:null,G.kind===`primary`?En??void 0:void 0),Eo=G.activity?.phase??To.phase,Do=ba(Z.useCallback(e=>{if(!Sn)return!1;let t=e.runsByOriginalSessionID[Sn];return t?.status===`running`&&t.runtimeKey===u()},[Sn])),Oo=q(e=>{or&&(je(),W(e),Hr.current?.blur(),ao.getState().refreshCatalogsOnPickerOpen({source:`chatInput:mobilePanel`}))}),Ao=bn.pendingInput,jo=bn.consumePendingInput;Z.useEffect(()=>{if(Ao===null)return;let e=jo();if(e){if(e.mode===`append`){if(!e.text.trim())return;let t=$E(si.current,e.text);si.current=t,zr(t)}else if(e.mode===`append-inline`){let t=eD(si.current,e.text);si.current=t,zr(t)}else wr(e.text);setTimeout(()=>{Hr.current?.focus()},0)}},[Ao,jo,wr,zr]);let Mo=g_(Sn,_t.draftID),No=O_(k_(Mo)),Fo=Cr.trim().length>0||qi.length>0||uo||No.length>0,Lo=G.kind===`primary`&&ew(Cr,h)===`btw`,Ro=Ga.mode===`server`?Ga.items.length>0:$a.length>0||eo.length>0,Bo=!Lo&&!fv(Ga.mode),Vo=Fo||Ro,Ho=Y(e=>e.stagedMessageEdit?.sessionId===Sn?e.stagedMessageEdit.messageId:null),Wo=Eo===`busy`||Eo===`retry`,Go=!Lo&&(G.activity?.canAbort??Wo),Ko=Z.useCallback(()=>{let e=Hr.current,t=e?.value??li().text;t!==li().text&&Er(t,e?.selectionStart??t.length,e?.selectionEnd??e?.selectionStart??t.length);let n=li();return{message:n.text,document:n,hasContent:n.text.trim().length>0||qi.length>0||uo||No.length>0}},[Er,No.length,li,uo,qi.length]),qo=Z.useRef(async()=>{}),Jo=G.surfaceID,Yo=_t?.draftID??null,Xo=ai(Z.useMemo(()=>ir(Jo),[Jo])),Zo=ai(Z.useMemo(()=>ti(Yo),[Yo])),Qo=Z.useMemo(()=>Ka(Lo?null:Xo,!Lo&&Zo),[Xo,Zo,Lo]),$o=(e=`send`)=>ai.getState().beginFlight(Jo,e),es=()=>{ai.getState().endFlight(Jo)},ts=()=>ai.getState().isInFlight(Jo),ns=Z.useRef(null);Z.useEffect(()=>{if(G.kind!==`primary`||!Ho){ns.current=null;return}if(ns.current!==Ho){if(ns.current=Ho,va){ou().focus();return}Qy(Hr)||requestAnimationFrame(()=>Qy(Hr))}},[va,Ho,G.kind]);let rs=ai(Z.useMemo(()=>Ua(Yo),[Yo])),is=Jt(Z.useCallback(e=>Sn?e.bySession[Sn]:void 0,[Sn])),os=Z.useMemo(()=>is?is.filter(e=>e.wasQueued).map(Rt):Xt,[is]),[ss,cs]=Z.useState(null),[fs,hs]=Z.useState(()=>new Set),gs=ss&&ss.sessionID===Sn&&wo(ss.runtime,bn.captureRuntime())&&!Zt(ss.sessionID,ss.item.messageID)&&!os.some(e=>e.messageID===ss.item.messageID)?ss.item:null,ys=Z.useMemo(()=>[...rs,...os,...gs?[gs]:[]],[rs,os,gs]);Z.useEffect(()=>{hs(e=>{if(e.size===0)return e;let t=new Set;for(let e of os)t.add(e.messageID);gs&&t.add(gs.messageID);let n=!1;for(let r of e)if(!t.has(r)){n=!0;break}if(!n)return e;let r=new Set;for(let n of e)t.has(n)&&r.add(n);return r})},[os,gs]);let bs=Nt(Z.useCallback(e=>Sn?e.runningBySession[Sn]===!0:!1,[Sn])),xs=q(async()=>{let e=Y.getState().newSessionDraft.draftID;if(!e||!ai.getState().isEstablishing(e))return!1;let t=Ko();if(!t.hasContent)return!1;let n=g_(null,e),r=n?O_.getState().quotesByKey[n]??[]:[],i=E_(t.document,r),a=D(i,`queue-canonical`);if(!a.ok)return Ha.error(l(`chat.chatInput.toast.messageSendFailed`)),!1;if(await G.selection.flush(),!ai.getState().isEstablishing(e))return!1;let o=HT(ao.getState());if(!o?.providerID||!o?.modelID)return Ha.error(l(`chat.chatInput.toast.messageSendFailed`)),!1;let s=xa(qi);return ai.getState().enqueueEstablishingFollowUp({draftID:e,content:a.text,sendConfig:{providerID:o.providerID,modelID:o.modelID,...o.agent?{agent:o.agent}:{},...o.variant?{variant:o.variant}:{}},attachments:s,composerDocument:i})?(wr(``),n&&i!==t.document&&O_.getState().clear(n),Fe(-1),yr(!1),s.length>0&&bn.clearAttachments(),!0):!1}),Ss=()=>{if(Sn)return!1;let e=Y.getState().newSessionDraft.draftID;return ai.getState().isEstablishing(e)?(xs(),!0):!1},Es=q(async()=>{if(!G.active||ts())return;if(Sn){let e=Y.getState().stagedMessageEdit;if(e&&e.sessionId===Sn){if(Y.getState().messageEditCommitting)return;let t=bn.captureRuntime(),n=Y.getState().getDirectoryForSession(Sn),r=()=>wo(t,bn.captureRuntime());Y.getState().beginMessageEditCommit(e.sessionId,e.messageId);try{await ta(e.sessionId,e.messageId,{directory:n??void 0})}catch(e){console.warn(`[chat-input] staged-edit commit failed before queue admission`,e);return}finally{r()&&Y.getState().endMessageEditCommit(e.sessionId,e.messageId)}if(!r()||Y.getState().currentSessionId!==Sn)return;Y.getState().stagedMessageEdit===e&&Y.getState().clearStagedMessageEdit(e.sessionId)}}let e=Ko(),t=D(e.document);if(!t.ok){Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}let n={chunks:t.chunks??[],semantics:t.semantics??[]},r=t.text,i=r.trimStart(),s=n.chunks.every(e=>e.provenance===`authored`)&&h===`normal`&&i.startsWith(`/`)?Kl(i.slice(1).trim()).split(/\s+/)[0]?.toLowerCase():void 0;if(s&&!yl(s,e=>rb(G,{name:e.name,source:`openchamber`}))||a||!e.hasContent||!Sn)return;if(Bo||!Vr(G.deliveryTarget?.kind,Ga.mode)){qo.current(Wo?{delivery:`steer`}:void 0);return}if(n.chunks.every(e=>e.provenance===`authored`)&&nw(r,h)){qo.current();return}if(!$o(`queue`))return;let u=G.transportIdentity,d=G.runtimeGeneration,f=bn.captureRuntime(),m=Wa,g=G.kind===`primary`?Wa?.sessionID??Sn:null,_=[...bn.inlineDrafts].sort((e,t)=>e.createdAt-t.createdAt),v=_.length>0?p(Gh(e.document.text,_),e.document.references).document:e.document,y=Mo?O_.getState().quotesByKey[Mo]??[]:[],b=E_(v,y),S=b!==v,C=D(b,`queue-canonical`);if(!C.ok){es(),Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}let w=xa(qi),T=Fr(),E=w,O=hi(),k=!1,A=null,M=()=>{k&&m&&(Ga.actions.unstageAdmission({requestID:O.requestID,scope:{directory:m.directory,sessionID:m.sessionID}}),k=!1),A&&m&&(j.getState().unstageAdmission(m,A),A=null)},N=async e=>{M(),T&&Ir(T),E.length>0&&await bn.restoreAttachments(E),e&&bn.restoreSyntheticParts(e),_.length>0&&bn.restoreInlineDrafts(_),S&&Mo&&O_.getState().restore(Mo,y)};try{if(!m){Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}if(Ga.mode===`server`){if(!Dn){Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}Wi({stage:()=>{Ga.actions.stageAdmission({requestID:O.requestID,scope:{directory:m.directory,sessionID:m.sessionID},item:{queueItemID:O.queueItemID,operationID:O.operationID,messageID:O.messageID,content:C.text,createdAt:O.createdAt,attachmentCount:w.length,composerDocument:b,composerMentions:Rr}}),k=!0},clearComposer:()=>{wr(``),S&&Mo&&O_.getState().clear(Mo),Fe(-1),yr(!1)}})}else Wi({stage:()=>{j.getState().bindLegacyQueue(x(m.sessionID),m),j.getState().stageAdmission(m,{requestID:O.requestID,queueItemID:O.queueItemID,operationID:O.operationID,messageID:O.messageID,content:C.text,createdAt:O.createdAt,attachmentCount:w.length,composerDocument:b,composerMentions:Rr}),A=O.requestID},clearComposer:()=>{wr(``),S&&Mo&&O_.getState().clear(Mo),Fe(-1),yr(!1)}});if(await G.selection.flush(),!wo({transportIdentity:u,generation:d},{transportIdentity:o(),generation:c()})){await N();return}if(!wo(f,bn.captureRuntime())){await N();return}if(g&&Y.getState().currentSessionId!==g){await N();return}if(m.transportIdentity!==o()||m.runtimeGeneration!==c()||m.sessionID!==(g??m.sessionID)||g&&ge(Y.getState().getDirectoryForSession(g))!==ge(m.directory)){await N();return}let t=m,n=G.kind===`primary`?(()=>{let e=ao.getState(),t=g?Y.getState().getDirectoryForSession(g)??null:null;return HT(e,{expectedConfigKey:Ea(t),activeDirectoryKey:e.activeDirectoryKey})})():G.selection.value.providerID&&G.selection.value.modelID?{...G.selection.value,providerID:G.selection.value.providerID,modelID:G.selection.value.modelID}:void 0;if(!Ta(n)){await N();return}if(Ga.mode===`server`){if(!Dn){await N(),Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}let r=Qi({draftKey:Dn,runtime:f,document:e.document,attachments:qi,inlineDrafts:_}),i=t.deliveryTarget.kind===`assistant`?bn.consumeSyntheticParts()?.map(e=>({...e,partID:e.partID??R()}))??null:null,a,o=[],s=t.deliveryTarget.kind===`assistant`?(()=>{let e=io({plan:{chunks:C.chunks??[],semantics:C.semantics??[]},agents:tr,installedSkillNames:new Set(Dr(V,En).map(e=>e.name)),directory:En,root:wi||En,confirmedFilePaths:Lr.map(e=>e.path),confirmedDirectoryPaths:Lr.filter(e=>e.kind===`directory`).map(e=>e.path),citationAttachments:qi});return o=e.attachments,go({text:_.length>0?Gh(e.text,_):e.text,attachments:[...w,...e.attachments],semanticParts:Pi(e.semantics,t.directory),syntheticParts:i})})():void 0;try{let e=[...Yi(w),...Yi(o),...(i??[]).flatMap(e=>Yi(e.attachments??[],e.partID))],t=s?new Set(s.flatMap(e=>e.type===`file`?[e.attachmentID]:[])):null;a=e.filter((n,r)=>e.findIndex(e=>e.attachmentID===n.attachmentID)===r&&(!t||t.has(n.attachmentID)))}catch(e){await N(i),Ha.error(l(e instanceof RangeError?`chat.chatInput.toast.attachmentsTooLarge`:`chat.chatInput.toast.messageSendFailed`));return}let c=s&&i?Ba(s,i.map(e=>({...e,partID:e.partID}))):void 0;try{let e=!1,o=await lo({capture:r,admit:async()=>{let r=await Ga.actions.admit({requestID:O.requestID,scope:{directory:t.directory,sessionID:t.sessionID},item:{queueItemID:O.queueItemID,operationID:O.operationID,messageID:O.messageID,content:C.text,composerDocument:b,composerMentions:Rr,sendConfig:n,deliveryTarget:t.deliveryTarget,...s?{deliveryParts:s}:{},...c?{syntheticParts:c}:{},attachmentIssues:[],createdAt:O.createdAt},attachments:a});return r.status===`committed`&&(e=!0,k=!1),r},captureRuntime:bn.captureRuntime,getCurrentDraftKey:()=>Dn,getDocument:li,consumeBody:()=>wr(``),getAttachments:()=>bn.attachments,removeAttachment:bn.removeAttachment,getInlineDrafts:()=>bn.inlineDrafts,removeInlineDraft:bn.removeInlineDraft});if(!e){await N(i),o.status===`stale`&&Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}if(o.status===`partial`){Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}o.status===`committed`&&!or&&Hr.current?.focus()}catch(e){await N(i),Ha.error(l(e instanceof RangeError?`chat.chatInput.toast.attachmentsTooLarge`:`chat.chatInput.toast.messageSendFailed`))}return}if(!j.getState().confirmAdmission(t,{requestID:O.requestID,sendConfig:n,attachments:w.length>0?w:void 0}).ok){await N(),Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}A=null;for(let e of _)bn.removeInlineDraft(e.id);w.length>0&&bn.clearAttachments(),or||Hr.current?.focus()}catch(e){await N(),Ha.error(l(e instanceof RangeError?`chat.chatInput.toast.attachmentsTooLarge`:`chat.chatInput.toast.messageSendFailed`))}finally{es()}}),Ds=q(()=>{_T(()=>Es(),()=>{Ha.error(l(`chat.chatInput.toast.messageSendFailed`))})}),Os=q(async(e,t,n,r)=>{if(Bo||!G.draftKey)return!1;try{let i=await zi({content:e,composerDocument:n,composerMentions:r,attachments:t}),a=yo.getState(),o=a.getDraft(G.draftKey);return mv(await Uo({key:G.draftKey,expectedRevision:o?.revision??`absent`,payload:i,runtime:a.captureDraftRuntime()}))?!0:(Ha.error(l(`chat.chatInput.toast.messageSendFailed`)),!1)}catch{return Ha.error(l(`chat.chatInput.toast.messageSendFailed`)),!1}}),ks=q(e=>{if(!(a||Bo)){if(yn){yn.sendQueued(e,{options:{delivery:`steer`},manual:!0});return}Ha.error(l(`chat.chatInput.toast.messageSendFailed`))}}),As=q(()=>{je(),W(`agent`),Hr.current?.blur(),ao.getState().refreshCatalogsOnPickerOpen({source:`chatInput:mobileAgentPanel`})}),js=Z.useCallback(()=>{Aa(!0)},[]),Ms=Z.useCallback(()=>{Ma(!0)},[]),Ns=async e=>{if(!G.active||a)return;if(!e?.queuedOnly){let t=e?.presetText==null?Ko():null;if(iw({text:e?.presetText??t?.message??``,inputMode:h,scope:Sn&&En?{sessionId:Sn,directory:En}:null,hasReferences:!!(t?.document.references.length||Rr.length),allowed:G.kind===`primary`&&rb(G,{name:`btw`,source:`openchamber`}),ask:zw.getState().ask,clearText:()=>{wr(``),M(!1),P(``)},open:()=>{or&&(je(),Hr.current?.blur()),Sn&&cT({sessionId:Sn,directory:En??null})},notify:e=>Ha.error(l(`chat.btw.${e}`))}))return}if(Ss()||ts())return;let n=e?.queuedOnly??!1,r=e?.queuedMessageId,i=e?.steerAfterAdmit===!0&&Wo&&!Do&&G.kind===`primary`,s=i?`queue`:e?.delivery,u=s===`queue`&&(Wo||Do)?`queue`:s===`steer`&&Wo?`steer`:void 0,d=e?.presetText==null?Ko():{message:e.presetText,document:{text:e.presetText,references:[]},hasContent:e.presetText.trim().length>0||qi.length>0||uo},f=e?.presetText==null?Fr():null,p=xn,m=D(d.document,`direct-send-display`);if(!m.ok){Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}let g=m.text,v={chunks:m.chunks??[],semantics:m.semantics??[]},y=v.chunks.every(e=>e.provenance===`authored`),b=g.trimStart(),x=y?ew(b,h):null,S=y&&nw(g,h),C=y&&h===`normal`&&/^\/model(?:\s|$)/i.test(b),w=y&&h===`normal`&&b.startsWith(`/`)?Kl(b.slice(1).trim()).split(/\s+/)[0]?.toLowerCase():void 0;if(w&&!yl(w,e=>rb(G,{name:e.name,source:`openchamber`}))||n&&Bo)return;if(!n&&C){M(!1),P(``),or?Oo(`model`):(K.getState().setModelSelectorOpen(!0),ao.getState().refreshCatalogsOnPickerOpen({source:`chatInput:modelCommand`}));return}let T=!i&&to({hasQueuedMessages:Ro,sessionIsRunning:Wo,autoReviewRunning:Do,queuedOnly:n,delivery:u});if(!(!n&&x&&x!==`model`)){if(Sn&&T&&Bo)return;if(Sn&&T&&Ga.mode===`server`){d.hasContent&&Ds();return}if(Sn&&T){d.hasContent&&Ds();let e=$a[0];e&&yn&&await yn.sendQueued(e.queueItemID,{options:Wo?{delivery:`steer`}:void 0});return}}let E=S||!n&&d.hasContent&&!r?[]:r?$a.filter(e=>e.id===r):$a;if(n&&Do)return;if(n){if(E.length===0||!Sn)return}else if(!d.hasContent&&!Ro||!Sn&&!wn)return;if(!Sn&&Cn||!$o(u===`queue`?`queue`:`send`))return;let O=!Sn&&wn&&!n&&!S?Y.getState().newSessionDraft.draftID??null:null,k=O?ve(`msg`):void 0;if(O&&k&&!ai.getState().beginEstablishing({draftID:O,primaryMessageID:k})){es();return}let A=()=>{fa(),O&&ai.getState().clearEstablishing(O)},N=e=>{let t=Y.getState().currentSessionId,n=(t?Y.getState().getDirectoryForSession(t):null)??En??``;if(!t||!n){ai.getState().clearEstablishing(e);return}gT({draftID:e,sessionID:t,directory:n,transportIdentity:o(),runtimeGeneration:c(),admitServer:Ga.mode===`server`?async e=>Ga.actions.admit({requestID:e.requestID,scope:{directory:n,sessionID:t},item:{queueItemID:e.queueItemID,operationID:e.operationID,messageID:e.messageID,content:e.content,createdAt:e.createdAt,sendConfig:e.sendConfig,attachmentIssues:[],...e.composerDocument?{composerDocument:e.composerDocument}:{},...e.composerMentions?{composerMentions:e.composerMentions}:{}},attachments:e.attachments.length>0?Yi(e.attachments):void 0}):void 0})};if(Sn&&!n&&!S&&Do){es(),Ds();return}let F=!n&&!S,I=G.kind===`primary`&&Sn&&u===`queue`&&!n&&!S&&!x&&h===`normal`?ve(`msg`):void 0,L=()=>{I&&cs(e=>e?.item.messageID===I?null:e)};I&&Sn&&(i&&hs(e=>{if(e.has(I))return e;let t=new Set(e);return t.add(I),t}),cs({sessionID:Sn,runtime:bn.captureRuntime(),item:{kind:`pending-admission`,requestID:I,queueItemID:I,operationID:I,messageID:I,content:g,createdAt:Date.now(),phase:`admitting`,attachmentCount:qi.length,composerDocument:d.document,composerMentions:Rr}}));let R=Mo?O_.getState().quotesByKey[Mo]??[]:[],z=C_(R,g)!==g,B=!1,H=()=>{!B||!Mo||(O_.getState().restore(Mo,R),B=!1)};F&&(wr(``),z&&Mo&&(O_.getState().clear(Mo),B=!0),Fe(-1),yr(!1));let ee=!1,U,te,W=bn.captureRuntime(),ne=!1;try{if(fT({surfaceKind:G.kind,currentSessionId:Sn,queuedOnly:n,delivery:u,resourcePolicy:S,inputMode:h,localCommand:x})&&Sn){let e=Y.getState().getDirectoryForSession(Sn)??En??null,t=Y.getState().stagedMessageEdit;t&&t.sessionId===Sn&&(te={sessionId:t.sessionId,messageId:t.messageId},Y.getState().beginMessageEditCommit(t.sessionId,t.messageId));let n=ao.getState(),r=WT({captured:HT(n,{expectedConfigKey:Ea(e),activeDirectoryKey:n.activeDirectoryKey}),surfaceSelection:G.selection.value});if(!te&&r?.providerID&&r?.modelID){let t=xa(qi);U=Zi({sessionId:Sn,directory:e,content:z?C_(R,g):d.message,providerID:r.providerID,modelID:r.modelID,agent:r.agent,variant:r.variant,files:t.map(e=>({type:`file`,mime:e.mimeType,url:e.dataUrl,filename:e.filename}))})}}let e=G.kind===`primary`?(()=>{if(n){let e=E[0]?.owner;if(e?.state===`bound`||e?.state===`unbound-legacy`)return e.sessionID;if(Wa?.sessionID)return Wa.sessionID}return Sn})():null,a=n?E[0]?.sendConfig:void 0;if(n&&a||await G.selection.flush(),e!==null&&Y.getState().currentSessionId!==e)return;let o=async()=>{let t=a?{...a}:G.kind===`primary`?(()=>{let t=ao.getState();if(!e)return WT({captured:HT(t),surfaceSelection:G.selection.value});let n=Y.getState().getDirectoryForSession(e)??En??null;return WT({captured:HT(t,{expectedConfigKey:Ea(n),activeDirectoryKey:t.activeDirectoryKey}),surfaceSelection:G.selection.value})})():G.selection.value.providerID&&G.selection.value.modelID?{...G.selection.value,providerID:G.selection.value.providerID,modelID:G.selection.value.modelID}:void 0;if(G.kind===`primary`&&e&&(!t?.providerID||!t?.modelID)){let n=Y.getState().getDirectoryForSession(e)??En??null,r=Ea(n);if(ao.getState().activeDirectoryKey!==r&&await ao.getState().activateDirectory(n),Y.getState().currentSessionId===e){let e=ao.getState();t=WT({captured:HT(e,{expectedConfigKey:Ea(n),activeDirectoryKey:e.activeDirectoryKey}),surfaceSelection:G.selection.value})}}return t},s=await o(),c=!1,m=s?.providerID,y=s?.modelID,b=s?.agent,C=s?.variant;if(!m||!y){if(!c){c=!0;try{await ao.getState().loadProviders({forceRefresh:!0,source:`chat-input-send-recovery`}),s=await o(),m=s?.providerID,y=s?.modelID,b=s?.agent,C=s?.variant}catch{}}if(!m||!y){console.warn(`Cannot send message: provider or model not selected`),Ha.error(l(`chat.chatInput.toast.messageSendFailed`));return}}Sn&&!n&&!S&&u!==`queue`&&await er(Sn)&&await fo(Sn);let w={...u?{delivery:u}:{},commitStagedMessageEdit:!n&&u!==`queue`,...U?{messageID:U.messageID,ticket:U}:I||k?{messageID:I??k}:{},...e?{sessionId:e,directoryHint:Y.getState().getDirectoryForSession(e)??En??null}:G.kind===`primary`&&Sn?{sessionId:Sn,directoryHint:Y.getState().getDirectoryForSession(Sn)??En??null}:{}},T=``,M=[],P,F=[],B=new Set(Dr(V,En).map(e=>e.name)),re=[],ie=S?void 0:bn.consumeSyntheticParts();for(let e=0;e<E.length;e++){let t=E[e],n=t.composerDocument&&D(t.composerDocument,`direct-send-display`),r=n&&n.ok?{chunks:n.chunks??[],semantics:n.semantics??[]}:null,i=t.owner?.state===`bound`?t.owner.directory:En,a=new Set(Dr(V,i).map(e=>e.name)),o=io({plan:r??bo(t.content),agents:tr,installedSkillNames:a,directory:i,root:i,confirmedFilePaths:t.composerMentions?.filter(e=>e.kind===`file`||e.kind===`directory`).map(e=>e.path||e.value),confirmedDirectoryPaths:t.composerMentions?.filter(e=>e.kind===`directory`).map(e=>e.path||e.value),citationAttachments:t.attachments});if(re.push(...o.semantics),!P&&o.agent&&(P=o.agent),e===0)T=o.text,M=Vi([...xa(t.attachments),...o.attachments]);else{let e=xa(t.attachments);F.push({text:o.text,attachments:Vi([...e,...o.attachments])})}}if(!n&&d.hasContent){let e=xa(qi),t=io({plan:v,agents:tr,installedSkillNames:B,directory:En,root:wi||En,confirmedFilePaths:Lr.map(e=>e.path),confirmedDirectoryPaths:Lr.filter(e=>e.kind===`directory`).map(e=>e.path),citationAttachments:qi});re.push(...t.semantics),!P&&t.agent&&(P=t.agent);let n=z?C_(R,t.text):t.text;E.length===0?(T=n,M=Vi([...e,...t.attachments])):F.push({text:n,attachments:Vi([...e,...t.attachments])})}let ae=Sn??(wn?`draft`:null),oe=[];if(!n&&ae&&!S&&(oe=[...bn.inlineDrafts].sort((e,t)=>e.createdAt-t.createdAt)),oe.length>0)if(E.length===0)T=Gh(T,oe);else if(F.length>0){let e=F[F.length-1];e.text=Gh(e.text,oe)}else T=Gh(T,oe);if(ie&&ie.length>0&&F.push(...sa(ie)),Na&&F.push({text:Na.contextText,synthetic:!0}),La&&(F.push({text:La.instructionsText,synthetic:!0}),F.push({text:La.contextText,synthetic:!0})),F.push(...Pi(re,Sn&&Y.getState().getDirectoryForSession(Sn)||En)),!T&&M.length===0&&F.length===0)return;if(O&&k){if(!await _o({messageID:k,providerID:m,modelID:y,agent:b,text:T,attachments:M,additionalParts:F,agentMentionName:P}))return;if(!ai.getState().isEstablishing(O)){A();return}}let se=async()=>{if(H(),A(),Wa&&E.length>0&&j.setState(e=>{let t=De(Wa),n=e.queuedMessages[t]??[],r=new Set(E.map(e=>e.id));return{queuedMessages:{...e.queuedMessages,[t]:[...E,...n.filter(e=>!r.has(e.id))]}}}),n)return ie&&bn.restoreSyntheticParts(ie),!0;bn.pendingInput?.text===d.message&&bn.consumePendingInput(),f&&Ir(f);let e=!0;return p.length>0&&(e=await bn.restoreAttachments(p)),ie&&bn.restoreSyntheticParts(ie),oe.length>0&&bn.restoreInlineDrafts(oe),e};if(!S&&Sn&&r){let e=Wa?_(j.getState(),Wa).find(e=>e.id===r||e.queueItemID===r):void 0;Wa&&e?.queueItemID&&e.operationID&&oo(Wa,e.queueItemID,e.operationID)}else!S&&Sn&&E.length>0&&Wa&&ro(Wa);!n&&!S&&(wr(``),Fe(-1),yr(!1),dT({queuedOnly:n,resourcePolicy:S,rootAttachmentCount:p.length})&&bn.clearAttachments());let ce=()=>lT({currentSessionId:Sn,messageRef:si,replacePlainDocument:wr}),le=T.trimStart();if(h===`normal`&&le.startsWith(`/`)){let e=Kl(le.slice(1).trim()).split(/\s+/)[0]?.toLowerCase();if(!yl(e,e=>rb(G,{name:e.name,source:`openchamber`})))return;if(Sn&&(e===`undo`||e===`redo`)&&rw(le,h)&&ce(),e===`undo`&&Sn){try{await Y.getState().handleSlashUndo(Sn),t?.()}catch(e){Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.messageSendFailed`))}return}if(e===`new`){rw(le,h)&&ce(),await yn?.shortcut(`new`);return}if(e===`redo`&&Sn){try{await Y.getState().handleSlashRedo(Sn),t?.()}catch(e){Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.messageSendFailed`))}return}if(e===`fork`&&Sn){await uT({command:`fork`,consumeCommandText:ce,forkSession:()=>Y.getState().forkCurrentSession(Sn),waitForConnection:ga,getDirectoryForSession:()=>Y.getState().getDirectoryForSession(Sn),summarizeSession:async()=>void 0,onCompactError:()=>void 0,onForkError:e=>{Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.messageSendFailed`))}});return}if(e===`timeline`&&Sn&&fi.timeline){br(!0);return}if(e===`reload`&&fe()){ce(),Ha.info(l(`chat.chatInput.toast.reloadStarted`)),$r().then(()=>{Ha.success(l(`chat.chatInput.toast.reloadSucceeded`))},()=>{Ha.error(l(`chat.chatInput.toast.reloadFailed`))});return}if(e===`compact`&&Sn){uT({command:`compact`,consumeCommandText:ce,forkSession:async()=>void 0,waitForConnection:ga,getDirectoryForSession:()=>G.directory??``,summarizeSession:e=>Dn?G.backend.compact({operation:`compact`,surfaceID:G.surfaceID,transportIdentity:G.transportIdentity,runtimeGeneration:G.runtimeGeneration,sessionID:Sn,directory:e,draftKey:Dn,deliveryTarget:G.deliveryTarget,providerID:m,modelID:y,agent:b,variant:C}):Promise.reject(Error(`chat-input-surface-incomplete`)),onCompactError:()=>{Ha.error(l(`chat.chatInput.toast.compactFailed`))},onForkError:()=>void 0});return}if(e===`summary`&&Sn){try{await ga();let e=le.replace(/^\/\u2003?summary\b/i,``).trim(),n=e?` focused on: ${e}`:``,r=e?`The user asked you to focus this summary on: ${e}. Prioritize that topic; mention unrelated threads only in passing.`:``,i=await ia(`session.summary.visible`,{topic_line:n}),a=await ia(`session.summary.instructions`,{topic_block:r});await kn(i,m,y,b,[],P,[{text:a,synthetic:!0}],C,h,w),t?.()}catch(e){await se(),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.summaryFailed`))}return}if(e===`workspace-review`&&(Sn||wn)){try{await ga();let e=await ia(`session.review.visible`),n=await ia(`session.review.instructions`);await kn(e,m,y,b,[],P,[{text:n,synthetic:!0}],C,h,w),t?.()}catch(e){await se(),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.reviewFailed`))}return}if(e===`handoff-review`&&Sn&&!or&&!fe()){Fn(!0);return}if(e===`goal`&&(Sn||wn)){A(),ui.getState().setArmed(!0);let e=tw(le,h)??``;wr(e),si.current=e,Fe(-1),e||yr(!1);return}if(e===`craft-goal`&&(Sn||wn)){try{await ga();let e=le.replace(/^\/\u2003?craft-goal\b/i,``).trim(),n=await ia(`session.craftGoal.visible`,{idea_block:e?`\n\nHere is my initial idea:\n${e}`:``}),r=await ia(`session.craftGoal.instructions`);await kn(n,m,y,b,[],P,[{text:r,synthetic:!0}],C,h,w),t?.()}catch(e){await se(),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.craftGoalFailed`))}return}if(e===`catch-up`&&(Sn||wn)){try{await ga();let e=await ia(`session.catchup.visible`),n=await ia(`session.catchup.instructions`);await kn(e,m,y,b,[],P,[{text:n,synthetic:!0}],C,h,w),t?.()}catch(e){await se(),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.catchUpFailed`))}return}if(e===`debug`&&(Sn||wn)){try{await ga();let e=await ia(`session.debug.visible`),n=await ia(`session.debug.instructions`);await kn(e,m,y,b,[],P,[{text:n,synthetic:!0}],C,h,w),t?.()}catch(e){await se(),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.debugFailed`))}return}if(e===`weigh`&&(Sn||wn)){try{await ga();let e=await ia(`session.weigh.visible`),n=await ia(`session.weigh.instructions`);await kn(e,m,y,b,[],P,[{text:n,synthetic:!0}],C,h,w),t?.()}catch(e){await se(),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.weighFailed`))}return}if(e===`explore`&&(Sn||wn)){try{await ga();let e=await ia(`session.explore.visible`),n=await ia(`session.explore.instructions`);await kn(e,m,y,b,[],P,[{text:n,synthetic:!0}],C,h,w),t?.()}catch(e){await se(),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.exploreFailed`))}return}}let ue=Sn&&Y.getState().getDirectoryForSession(Sn)||En;if(Tn||Sn&&!FE(Sn,ue)){let e=await Pa().catch(()=>null);e&&F.push({text:mr(e),synthetic:!0})}ne=!0;let de=kn(T,m,y,b,M,P,F.length>0?F:void 0,C,h,w);ee=!0,de.finally(()=>{L(),es(),te&&wo(W,bn.captureRuntime())&&Y.getState().endMessageEditCommit(te.sessionId,te.messageId)}).catch(()=>{}),O&&de.then(()=>{N(O)}).catch(()=>{ai.getState().clearEstablishing(O)}),typeof window>`u`?t?.():window.requestAnimationFrame(()=>{t?.()}),de.then(async()=>{if(i&&I&&e){let t=()=>{hs(e=>{if(!e.has(I))return e;let t=new Set(e);return t.delete(I),t})};if(Zt(e,I)||!on({sessionID:e}))t();else{let n=Y.getState().getDirectoryForSession(e)??En??``;try{await rn({sessionID:e,inboxID:I,directory:n})}catch{t(),Jt.getState().list(e).some(e=>e.id===I)&&Ha.error(l(`chat.chatInput.toast.messageSendFailed`))}}}Na&&Fa(null),La&&Ra(null)}).catch(e=>{U&&no(U),se().then(e=>{e||Ha.error(l(`chat.chatInput.toast.messageSendFailed`))});let t=e instanceof Error?e.message:typeof e==`string`?e:String(e??``),n=t.toLowerCase();console.error(`Message send failed:`,t||e);let r=n.includes(`timeout`)||n.includes(`timed out`)||n.includes(`may still be processing`)||n.includes(`being processed`)||n.includes(`failed to fetch`)||n.includes(`networkerror`)||n.includes(`network error`)||n.includes(`gateway timeout`)||n===`failed to send message`;if(n.includes(`payload too large`)||n.includes(`413`)||n.includes(`entity too large`)){Ha.error(l(`chat.chatInput.toast.attachmentsTooLarge`));return}if(r){p.length>0&&Ha.error(l(`chat.chatInput.toast.sendAttachmentsFailed`));return}Ha.error(t||l(`chat.chatInput.toast.messageSendFailed`))}),or||Hr.current?.focus()}finally{ne||(U&&no(U),te&&wo(W,bn.captureRuntime())&&Y.getState().endMessageEditCommit(te.sessionId,te.messageId)),ee||(L(),F&&f&&(Ir(f),H()),es(),O&&N(O))}};qo.current=Ns;let Ps=q(()=>{if(ew(Ko().message,h)===`btw`){qo.current();return}if(Ss()||ts())return;let e=Ko(),t=h===`normal`&&e.hasContent&&Sn&&(Wo||Do),n=t&&fv(Ga.mode)&&Vr(G.deliveryTarget?.kind,Ga.mode),r=vT({followUpBehavior:Va,ctrlEnter:!1,canQueue:!!t,queueUsable:!!n,primary:G.kind===`primary`,sessionIsRunning:Wo,autoReviewRunning:Do});r.kind===`queue`?Ds():r.delivery?qo.current({delivery:r.delivery}):qo.current()}),Fs=Z.useCallback(e=>{if(ts())return;let t=(Hr.current?.value??si.current).trim(),n=t?`${e}\n${t}`:e;qo.current({presetText:n})},[]),Is=Z.useCallback(e=>{let t=eD(li().text,e);zr(t),Hr.current&&(Hr.current.value=t),setTimeout(()=>{Hr.current?.focus()},0)},[zr]),Ls=Z.useCallback(e=>{if(ts())return;let t=eD(Hr.current?.value??si.current,e);qo.current({presetText:t})},[]),Rs=bn.pendingPreset,zs=bn.consumePendingPreset;Z.useEffect(()=>{if(Rs==null)return;let e=zs();e&&Fs(e)},[Rs,zs,Fs]);let Bs=Z.useCallback(()=>{wr(``),Fe(-1),xn.length>0&&bn.clearAttachments(),Wa&&ro(Wa),M(!1),w(!1),h===`shell`&&g(`normal`)},[xn.length,bn,ro,Wa,wr,h]),Vs=e=>{if(!G.active||Xc(e))return;if(yi&&rc(e,yi)&&!pr){let t=Hr.current;if(!(t&&t.selectionStart!==t.selectionEnd)){e.preventDefault(),Bs();return}}if(h===`shell`&&e.key===`Escape`){e.preventDefault(),g(`normal`);return}if(h===`shell`&&e.key===`Backspace`&&Cr.length===0){e.preventDefault(),g(`normal`);return}if(e.key===`Backspace`&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey&&No.length>0){let t=Hr.current,n=t?.selectionStart??0,r=t?.selectionEnd??0;if(n===0&&r===0&&Mo){e.preventDefault(),O_.getState().removeLast(Mo);return}}if((e.key===`Backspace`||e.key===`Delete`)&&!e.metaKey&&!e.ctrlKey){let t=Hr.current,n=t?.selectionStart??Cr.length,r=t?.selectionEnd??Cr.length,i=kr({key:e.key,selectionStart:n,selectionEnd:r,altKey:e.altKey});if(i){let t=PE(xr.getDocument().text,i.start);e.preventDefault(),zr(t.text),requestAnimationFrame(()=>{Hr.current?.setSelectionRange(t.caret,t.caret),ac()}),oc(t.text,t.caret);return}let a=ut(Cr,xn.filter(it).map(e=>e.filename),{key:e.key,selectionStart:n,selectionEnd:r,altKey:e.altKey});if(a){let t=new Set(a.removedFilenames.map(e=>e.toLowerCase())),n=PE(a.text,a.caret);e.preventDefault(),zr(n.text);for(let e of xn)t.has(e.filename.toLowerCase())&&bn.removeAttachment(e.id);requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=n.caret,Hr.current.selectionEnd=n.caret),ac()}),oc(n.text,n.caret);return}let o=$c(Cr,oa.keys(),{key:e.key,selectionStart:n,selectionEnd:r,altKey:e.altKey});if(o){let t=PE(o.text,o.caret);e.preventDefault(),zr(t.text),requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=t.caret,Hr.current.selectionEnd=t.caret),ac()}),oc(t.text,t.caret);return}if(n===r&&!e.altKey){let t=e.key===`Backspace`?n-1:n;if(t>=0&&t<Cr.length){let n=Ut(Cr,xn.map(e=>e.filename)).find(e=>t>=e.start&&t<e.end);if(n){let t=xe(Cr.slice(n.start+1,n.end-1)).trim(),r=xn.find(e=>e.filename.toLowerCase()===t.toLowerCase()),i=Cr[n.end]===` `?n.end+1:n.end,a=`${Cr.slice(0,n.start)}${Cr.slice(i)}`;e.preventDefault(),zr(a),r&&bn.removeAttachment(r.id),requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=n.start,Hr.current.selectionEnd=n.start),ac()}),oc(a,n.start);return}let r=Rr.find(n=>(n.kind===`file`||n.kind===`directory`)&&Cr.slice(n.range.start,n.range.end)===`@${n.value}`&&(t>=n.range.start&&t<n.range.end||e.key===`Backspace`&&Cr[t]===` `&&n.range.end===t));if(r){let t=Cr[r.range.end]===` `?r.range.end+1:r.range.end,n=`${Cr.slice(0,r.range.start)}${Cr.slice(t)}`;e.preventDefault(),zr(n),requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=r.range.start,Hr.current.selectionEnd=r.range.start),ac()}),oc(n,r.range.start);return}let i=t;for(;i>0&&!/\s/.test(Cr[i-1]);)--i;let a=t+1;for(;a<Cr.length&&!/\s/.test(Cr[a]);)a+=1;let o=Cr.slice(i,a),s=o.slice(1);if(DE.test(o)&&!Xi.current.has(s.toLowerCase())&&Ia({mention:s,confirmed:Br.has(s),terminated:a<Cr.length&&/\s/.test(Cr[a])})){let t=Cr[a]===` `?a+1:a,n=`${Cr.slice(0,i)}${Cr.slice(t)}`;e.preventDefault(),zr(n),requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=i,Hr.current.selectionEnd=i),ac()}),oc(n,i);return}}}}let t=(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.metaKey&&!e.ctrlKey;if(k&&oi.current&&(e.key===`Enter`||e.key===`Escape`||e.key===`Tab`||t)){e.preventDefault(),e.stopPropagation(),oi.current.handleKeyDown(e.key);return}if(C&&ri.current&&(e.key===`Enter`||e.key===`Escape`||e.key===`Tab`||t)){e.preventDefault(),e.stopPropagation(),ri.current.handleKeyDown(e.key);return}if(Ri&&e.key===`Escape`){e.preventDefault(),yr(!1);return}let n=vi&&!vi.includes(`shift`)?Ks(`shift+${vi}`):``,r=n&&rc(e,n)?-1:+!!rc(e,vi);if(r!==0&&!k&&!C){e.preventDefault(),e.stopPropagation(),yn?.shortcut(`cycle`,r),requestAnimationFrame(()=>{Hr.current?.focus({preventScroll:!0})});return}let i=k||C,a=Hr.current?.selectionStart===0&&Hr.current?.selectionEnd===0,o=Hr.current?.selectionStart===Cr.length&&Hr.current?.selectionEnd===Cr.length,s=!i&&(Cr.length===0||a),c=!i&&(Cr.length===0||o);if(h===`normal`&&!i&&!e.metaKey&&!e.ctrlKey&&!e.altKey){let t=Hr.current,n=t?.selectionStart??-1,r=t?.selectionEnd??-1;if(t&&n>=0){let t=(t,n,r)=>{e.preventDefault(),zr(t),requestAnimationFrame(()=>{let e=Hr.current;e&&(e.selectionStart=n,e.selectionEnd=r),ac()}),oc(t,r)},i={"`":["`","`"],"*":[`*`,`*`],_:[`_`,`_`],"~":[`~`,`~`],"(":[`(`,`)`],"[":[`[`,`]`],"{":[`{`,`}`],'"':[`"`,`"`],"'":[`'`,`'`]};if(r>n&&i[e.key]){let[a,o]=i[e.key],s=Cr.slice(n,r);t(`${Cr.slice(0,n)}${a}${s}${o}${Cr.slice(r)}`,n+a.length,r+a.length);return}if(e.key==="`"&&n===r){let e=Cr.slice(0,n);if(/(^|\n)``$/.test(e)){let n=`${e}\`\n\n\`\`\`${Cr.slice(r)}`,i=e.length+2;t(n,i,i);return}}}}if(e.key===`ArrowUp`&&!e.metaKey&&!e.ctrlKey&&s&&So.length>0){if(e.preventDefault(),Pe===-1)Fe(0),Ar({text:So[0],references:[]});else if(Pe<So.length-1){let e=Pe+1;Fe(e),Ar({text:So[e],references:[]})}requestAnimationFrame(()=>{Hr.current?.setSelectionRange(0,0)});return}if(e.key===`ArrowDown`&&!e.metaKey&&!e.ctrlKey&&c&&Pe>=0){if(e.preventDefault(),Pe===0)Fe(-1),Nr();else{let e=Pe-1;Fe(e),Ar({text:So[e],references:[]})}return}if(e.key===`Enter`&&!e.shiftKey){if(e.preventDefault(),ew(Ko().message,h)===`btw`){Ns();return}if(Ss()||ts())return;let t=e.ctrlKey||e.metaKey,n=h===`normal`&&Fo&&Sn&&(Wo||Do),r=n&&fv(Ga.mode)&&Vr(G.deliveryTarget?.kind,Ga.mode),i=vT({followUpBehavior:Va,ctrlEnter:t,canQueue:!!n,queueUsable:!!r,primary:G.kind===`primary`,sessionIsRunning:Wo,autoReviewRunning:Do});i.kind===`queue`?Ds():i.steerAfterAdmit?Ns({steerAfterAdmit:!0}):i.delivery?Ns({delivery:i.delivery}):Ns()}},Hs=Z.useCallback((e,t)=>{let n=e.ownerDocument,r=n.defaultView;if(!r)return null;let i=r.getComputedStyle(e),a=n.createElement(`div`),o=a.style;o.position=`absolute`,o.visibility=`hidden`,o.pointerEvents=`none`,o.whiteSpace=`pre-wrap`,o.wordWrap=`break-word`,o.overflow=`hidden`,o.left=`-9999px`,o.top=`0`,o.width=`${e.clientWidth}px`,o.font=i.font,o.fontSize=i.fontSize,o.fontFamily=i.fontFamily,o.fontWeight=i.fontWeight,o.fontStyle=i.fontStyle,o.fontVariant=i.fontVariant,o.letterSpacing=i.letterSpacing,o.textTransform=i.textTransform,o.textIndent=i.textIndent,o.padding=i.padding,o.border=i.border,o.boxSizing=i.boxSizing,o.lineHeight=i.lineHeight,o.tabSize=i.tabSize,a.textContent=e.value.slice(0,t);let s=n.createElement(`span`);s.textContent=e.value.slice(t,t+1)||` `,a.appendChild(s),n.body.appendChild(a);let c=s.offsetTop,l=s.offsetLeft;return n.body.removeChild(a),{top:c,left:l}},[]),Us=Z.useCallback(()=>{if(!Ri){Da(null);return}if(!k&&!C){Da(null);return}let e=Hr.current,t=qr.current;if(!e||!t)return;let n=e.selectionStart??Cr.length,r=Hs(e,n);if(!r)return;let i=e.getBoundingClientRect(),a=t.getBoundingClientRect(),o=i.top-a.top+(r.top-e.scrollTop),s=i.left-a.left+(r.left-e.scrollLeft),c=o-8,l=a.height-o-8,u=l>=260||l>=c?`below`:`above`,d=C?520:k?450:360,f=Math.max(8,Math.min(s-24,a.width-d-8)),p=Math.max(120,Math.min(260,u===`below`?l:c));Da({top:u===`below`?o+22:o-6,left:f,place:u,maxHeight:p})},[Ri,Hs,Cr.length,k,C]);Z.useLayoutEffect(()=>{Us()},[Us,Cr,k,C,Ri]),Z.useEffect(()=>{if(!Ri)return;let e=()=>Us();return window.addEventListener(`resize`,e),()=>{window.removeEventListener(`resize`,e)}},[Ri,Us]);let Ws=Z.useCallback(()=>{Oa.current&&=(clearTimeout(Oa.current),null),Mi(!0),Oa.current=setTimeout(()=>{Mi(!1),Oa.current=null},1800)},[]),Gs=Z.useRef(new Set),[qs,Js]=Z.useState(()=>new Set),Ys=JSON.stringify([G.transportIdentity,G.runtimeGeneration,G.surfaceID,G.directory,Sn]),Xs=Go&&qs.has(Ys),Zs=q(async()=>{if(Gs.current.has(Ys))return;let e=Ys;Gs.current.add(e),Js(new Set(Gs.current)),bn.abortPrompt.clear(),Ws();let t;try{let e=G.kind===`secondary`?yn?.shortcut(`abort`):An();await Promise.race([e,new Promise(e=>{t=setTimeout(()=>{G.kind===`secondary`&&Ha.error(l(`chat.chatInput.stopUnconfirmed`)),e()},5e3)})])}catch(e){console.error(`[ChatInput] abort failed`,e)}finally{clearTimeout(t),Gs.current.delete(e),Js(new Set(Gs.current))}}),Qs=Z.useCallback((e=1)=>{if(rr)return;let t=Ei(tr,G.selection.value.agent??Vn,e);if(!t||!G.selection.change)return;let n=ki({providerID:G.selection.value.providerID??``,modelID:G.selection.value.modelID??``,agent:G.selection.value.agent??null},t,tr,nr);G.selection.change({...G.selection.value,...n,agent:n.agent??void 0}),G.kind===`primary`&&(K.getState().addRecentAgent(t),G.sessionID&&zo.getState().saveSessionAgentSelection(G.sessionID,t))},[tr,Vn,nr,rr,G.kind,G.selection,G.sessionID]);Ie.current=Qs;let $s=Z.useRef(null),[ec,tc]=Z.useState(null),nc=Z.useCallback(e=>{tc(t=>t===e?t:e)},[]),ac=Z.useCallback(e=>{let t=Hr.current;if(!t)return;let n=t.scrollTop;if(Hi){t.style.height=`100%`,t.style.maxHeight=`none`,t.style.overflowY=`auto`,ee(null),t.scrollTop!==n&&(t.scrollTop=n);return}t.style.overflow=`hidden`,t.style.overflowX=`hidden`,t.style.overflowY=`hidden`,(e?.allowShrink??!0)&&(t.style.height=`auto`);let r=t.ownerDocument?.defaultView,i=r?r.getComputedStyle(t):null,a=i?parseFloat(i.lineHeight):NaN,o=i?parseFloat(i.paddingTop):NaN,s=i?parseFloat(i.paddingBottom):NaN,c=Number.isNaN(o)||Number.isNaN(s)?16:o+s,l=Number.isNaN(a)?22:a,u=bE({scrollHeight:t.scrollHeight||t.offsetHeight,dictationHeight:$s.current??0,lineHeight:l,paddingTotal:c});t.style.height=`${u.height}px`,t.style.maxHeight=`${u.maxHeight}px`,t.style.overflowY=u.overflowY,t.scrollTop!==n&&(t.scrollTop=n),ee(e=>e&&e.height===u.height&&e.maxHeight===u.maxHeight?e:{height:u.height,maxHeight:u.maxHeight})},[Hi]);Z.useLayoutEffect(()=>{let e=Cr.length<Kr.current;Kr.current=Cr.length,ac({allowShrink:e})},[ac,Cr,or]),Z.useLayoutEffect(()=>{$s.current=ec,ac({allowShrink:ec===null})},[ac,ec]);let oc=Z.useCallback((e,t,n=`manual`,r)=>{let i=Hl({text:e,cursor:t,inputMode:h,mentionInputSource:n,insertedText:r});if(Gr.current=i,!i){M(!1),w(!1);return}if(i.kind===`slash-command`){P(i.query),M(!0),w(!1);return}M(!1),O(i.query),w(!0)},[h,P,O,M,w]),sc=Z.useCallback((e,t,n,r=`manual`,i)=>{let a=e,o=t,s=n;if(h===`normal`&&!Ur.current&&la.size>0&&e.includes(`/`)){let r=Gl(e,la,n);r&&(a=r.text,o=t+(r.caret-n),s=r.caret)}let c=Er(a,o,s,(e,t)=>{let n=[...e];for(let i of Ja(t.text,{agentNames:Ji,includeUnterminatedPastedReferences:r===`paste`,confirmedValues:new Set(e.flatMap(e=>e.kind===`file`||e.kind===`directory`?[e.value]:[]))}))n=Ml(n,{kind:i.kind,value:i.value,path:i.value,label:i.value,range:{start:i.start,end:i.end}});return n}),l=li(),u=c.requiresTextCorrection||o!==c.start||s!==c.end||a!==e;return requestAnimationFrame(()=>{let e=Hr.current;e&&$y(u,Ur.current)&&(e.value=l.text,e.setSelectionRange(c.start,c.end)),ac()}),oc(l.text,c.end,r,i),{document:l,selection:c}},[ac,Er,li,h,Ji,la,oc]),cc=Z.useCallback((e,t=`manual`)=>{if(!e)return;let n=Hr.current;if(!n){let n=Cr+e;sc(n,n.length,n.length,t,e);return}let r=n.selectionStart??Cr.length,i=n.selectionEnd??Cr.length,a=`${Cr.substring(0,r)}${e}${Cr.substring(i)}`,o=r+e.length;sc(a,o,o,t,e)},[sc,Cr]),lc=q((e,t)=>{let n=new Set(un(xn.map(e=>e.filename),e,t));if(n.size!==0)for(let e of xn)n.has(e.filename)&&bn.removeAttachment(e.id)}),uc=Z.useCallback(e=>{bn.removeAttachment(e.id)},[bn]),dc=Z.useCallback(()=>{Yr.current=!1,ei.current=[],Xr.current&&=(clearTimeout(Xr.current),null)},[]),fc=Z.useCallback(()=>{Xr.current&&clearTimeout(Xr.current),Xr.current=setTimeout(()=>{dc()},700)},[dc]),pc=Z.useCallback(()=>{Zr.current=!1,Qr.current&&=(clearTimeout(Qr.current),null)},[]),mc=Z.useCallback(()=>{Zr.current=!0,Qr.current&&clearTimeout(Qr.current),Qr.current=setTimeout(()=>{Zr.current=!1,Qr.current=null},700)},[]),hc=Z.useCallback(e=>{!fe()||!Yr.current||e.nativeEvent?.inputType===`insertFromDrop`&&(e.preventDefault(),dc())},[dc]),gc=e=>{if(pr)return;let t=e.nativeEvent;if(fe()&&Yr.current){let n=ei.current;if(t?.inputType===`insertFromDrop`||n.some(t=>t.length>0&&e.target.value.includes(t))){dc();return}}let n=e.target.value;lc(si.current,n);let r=e.target.selectionStart??n.length,i=t?.inputType?.startsWith(`insertFromPaste`)?ME(si.current,n):``,a=i.includes(`@`)||Zr.current;Zr.current&&pc();let o=a?`paste`:`manual`;if(h===`normal`&&n.startsWith(`!`)){let e=n.slice(1),t=Math.max(0,r-1);g(`shell`),wr(e),ac(),M(!1),w(!1),requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=t,Hr.current.selectionEnd=t)});return}sc(n,r,e.target.selectionEnd??r,o,i)};Z.useEffect(()=>()=>{dc(),pc()},[dc,pc]);let _c=Z.useCallback(e=>{let t=Array.from(new Set(e.map(e=>e.trim()).filter(Boolean)));if(t.length===0)return;let n=t.map(e=>`@${e}`).join(` `),r=Hr.current,i=r?.selectionStart??Cr.length,a=r?.selectionEnd??Cr.length,o=Ol(n,Cr.slice(0,i),Cr.slice(a)),s=`${Cr.slice(0,i)}${o}${Cr.slice(a)}`;lc(Cr,s),di(s,t);let c=Ll(s,i+o.length);Wr.current=c,w(!1),O(``),requestAnimationFrame(()=>{Hr.current?.setSelectionRange(c,c),ac(),oc(s,c)})},[ac,lc,Cr,di,O,w,oc]),vc=Z.useCallback(async e=>{let t=BE(e.clipboardData);if(t.length>0&&(Sn||wn)){e.preventDefault(),_c(t);return}if(h===`normal`&&(Sn||wn)){let t=Hr.current,n=t?.selectionStart??-1,r=t?.selectionEnd??-1;if(t&&r>n){let t=e.clipboardData.getData(`text`).trim(),i=Cr.slice(n,r);if(kE.test(t)&&!/\s/.test(t)&&i.trim().length>0&&!i.includes(`](`)){e.preventDefault();let a=`${Cr.slice(0,n)}[${i}](${t})${Cr.slice(r)}`,o=n+1+i.length+2+t.length+1;zr(a),requestAnimationFrame(()=>{let e=Hr.current;e&&(e.selectionStart=o,e.selectionEnd=o),ac()}),oc(a,o,NE(t),t);return}}}let n=Array.from(e.clipboardData.files||[]).filter(e=>e.type.startsWith(`image/`)),r=Array.from(e.clipboardData.items||[]).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>!!e),i=n.length>0?n:(()=>{if(r.length<=1)return r;let e=r.find(e=>/image\/(png|webp|jpe?g|gif)/i.test(e.type));return e?[e]:[r[0]]})(),a=e.clipboardData.getData(`text`);if(i.length===0){if(h===`normal`&&rE(li(),a)){e.preventDefault();let t=li().text,n=Hr.current,r=n?.selectionStart??Cr.length,i=n?.selectionEnd??Cr.length,o=iE(a,Cr,li().references.flatMap(e=>e.kind===`paste`?[{id:e.id,token:e.display,text:e.text,characterCount:e.characterCount,index:e.index}]:[]),({index:e,count:t})=>l(`chat.chatInput.pastedTextReference`,{index:e,count:t}),nE(li())),s=Or(r,i,{id:o.id,kind:`paste`,text:o.text,characterCount:o.characterCount,index:o.index,display:o.token},{inlineBoundaries:!0,padDocumentEdges:!0}),c=Ll(s.document.text,s.caret);Hr.current&&(Hr.current.value=s.document.text),requestAnimationFrame(()=>{Hr.current?.setSelectionRange(c,c),ac()}),oc(s.document.text,c),lc(t,s.document.text);return}a.includes(`@`)&&mc();return}if(!Sn&&!wn){a.includes(`@`)&&mc();return}e.preventDefault();let o=fn(i,[...xn.map(e=>e.filename),...ci.current]),s=Pt(o),c=li().text,u=Hr.current,d=u?.selectionStart??Cr.length,f=u?.selectionEnd??Cr.length,p=h===`normal`&&rE(li(),a)?iE(a,Cr,li().references.flatMap(e=>e.kind===`paste`?[{id:e.id,token:e.display,text:e.text,characterCount:e.characterCount,index:e.index}]:[]),({index:e,count:t})=>l(`chat.chatInput.pastedTextReference`,{index:e,count:t}),nE(li())):null,m=a?`${a}${/\s$/.test(a)?``:` `}${s}`:s,g=Ol(m,Cr.slice(0,d),Cr.slice(f));if(p){let e=Or(d,f,{id:p.id,kind:`paste`,text:p.text,characterCount:p.characterCount,index:p.index,display:p.token},{inlineBoundaries:!0,padDocumentEdges:!0}),t=Ll(e.document.text,e.caret),n=`${e.document.text.slice(0,t)}${s}${e.document.text.slice(t)}`;sc(n,t+s.length,t+s.length,NE(n),s),lc(c,n)}else cc(g,NE(g)),lc(c,`${Cr.slice(0,d)}${g}${Cr.slice(f)}`);for(let e=0;e<i.length;e+=1){let t=o[e],n=jE(i[e],t);ci.current.add(t);try{await bn.addAttachment(n)}catch(e){console.error(`Clipboard image attach failed`,e),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.clipboardAttachFailed`))}finally{ci.current.delete(t)}}},[bn,_c,xn,ac,Sn,li,h,Or,mc,Cr,wn,cc,l,oc,sc,zr,lc]),yc=Z.useCallback((e,t)=>{let n=e.currentTarget,r=n.selectionStart??0,i=n.selectionEnd??r;if(i<=r)return;let a=gl(r,i,[...Ut(Cr,xn.filter(it).map(e=>e.filename)),...il(Cr,oa.keys()),...li().references]),o=a?.start??r,s=a?.end??i,c=Cr.slice(o,s),l=Ee(c);if(!(l===c&&!a))if(e.preventDefault(),e.clipboardData.setData(`text/plain`,l),t===`cut`){let e=`${Cr.slice(0,o)}${Cr.slice(s)}`;sc(e,o,o),requestAnimationFrame(()=>{Hr.current?.setSelectionRange(o,o),ac()})}else a&&(a.start!==r||a.end!==i)&&requestAnimationFrame(()=>{Hr.current?.setSelectionRange(o,s)})},[ac,xn,oa,sc,li,Cr]),bc=Z.useCallback(e=>{yc(e,`copy`)},[yc]),xc=Z.useCallback(e=>{yc(e,`cut`)},[yc]),Sc=e=>{let t=Hr.current,n=t&&document.activeElement===t?t.selectionStart??Wr.current:Wr.current;return Xl(e,n)},Cc=()=>{du(or)||Hr.current?.focus()},wc=e=>{let t=Sc(Cr.length),n=Wl(Cr,t,Gr.current),r=Cr.substring(0,t).lastIndexOf(`@`),i=e.relativePath&&e.relativePath.trim().length>0?e.relativePath.trim():Fc(e.path)||e.name,a=e.isDirectory?[i]:[],o=n?.start??(r===-1?t:r),s=n?.end??t,c=Fl(Cr,o,s,`@${i}`);di(c.text,[i],a),Wr.current=c.caret,requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=c.caret,Hr.current.selectionEnd=c.caret),ac(),oc(c.text,c.caret)}),w(!1),O(``),Cc()},Ec=e=>{let t=Sc(Cr.length),n=Wl(Cr,t,Gr.current),r=Cr.substring(0,t).lastIndexOf(`@`),i=n?.start??(r===-1?t:r),a=n?.end??t,o=Fl(Cr,i,a,`@${e}`);zr(o.text,t=>Ml(t,{kind:`agent`,value:e,path:e,label:e,range:{start:o.start,end:o.end}})),Wr.current=o.caret,requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=o.caret,Hr.current.selectionEnd=o.caret),ac(),oc(o.text,o.caret)}),w(!1),O(``),Cc()},Dc=q(e=>{ii.current||(ii.current=!0,(async()=>{try{let t=Y.getState().getAuthoritativeDirectoryForSession(e.id);if(!t){Ha.error(l(`chat.chatInput.toast.sessionReferenceLoadFailed`));return}if(await Qe(e.id,{directory:t}),!kt(e.id,t)){Ha.error(l(`chat.chatInput.toast.sessionReferenceLoadFailed`));return}jr([{type:`session`,sessionId:e.id}],t).catch(()=>void 0);let n=li(),r=Sc(n.text.length),i=Wl(n.text,r,Gr.current),a=n.text.substring(0,r).lastIndexOf(`@`),o=Ct().get(e.id)?.title||e.title||e.id,s=i?.start??(a===-1?r:a),c=i?.end??r,u={id:`session:${e.id}:${R()}`,kind:`session`,sessionId:e.id,display:pe({trigger:`@`,icon:`chat-thread`,label:o})},d=Or(s,c,u,{inlineBoundaries:!0,padDocumentEdges:!0}),f=Ll(d.document.text,d.caret);Wr.current=f,requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=f,Hr.current.selectionEnd=f),ac(),oc(d.document.text,f)}),w(!1),O(``),Cc()}catch{Ha.error(l(`chat.chatInput.toast.sessionReferenceLoadFailed`))}finally{ii.current=!1}})())}),Oc=q(e=>{let t=li(),n=Sc(t.text.length),r=Wl(t.text,n,Gr.current)??Sl(t.text,n);if(!r)return!1;let i=Or(r.start,r.end,e,{inlineBoundaries:!0,padDocumentEdges:!0,padLeadingDocumentEdge:!1}),a=i.document.references.some(t=>t.id===e.id),o=Ll(i.document.text,i.caret);return Wr.current=o,requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=o,Hr.current.selectionEnd=o),ac(),oc(i.document.text,o),a&&(M(!1),w(!1))}),Cc(),a}),kc=e=>{let t=li(),n=Sc(t.text.length),r=Wl(t.text,n,Gr.current);if(!r)return;let i=Or(r.start,r.end,{id:`skill:${e.name}:${R()}`,kind:`skill`,skillName:e.name,display:pe({trigger:`@`,icon:`book-open`,label:e.name})},{inlineBoundaries:!0,padDocumentEdges:!0,padLeadingDocumentEdge:!1}),a=Ll(i.document.text,i.caret);Wr.current=a,requestAnimationFrame(()=>{Hr.current&&(Hr.current.selectionStart=a,Hr.current.selectionEnd=a),ac(),oc(i.document.text,a),w(!1),O(``)}),Cc()},Ac=(e,t=!1)=>{if(!rb(G,e))return;let n=`/${e.name}`;if(!t&&e.isSkill){Oc({id:`skill:${e.name}:${R()}`,kind:`skill`,skillName:e.name,display:pe({trigger:`@`,icon:`book-open`,label:e.name})})&&P(``);return}if(!t&&e.source===`opencode`&&!e.isSkill&&e.isBuiltIn!==!0&&Oc({id:`command:${e.name}:${R()}`,kind:`command`,commandName:e.name,reference:e.reference??e.name,display:pe({trigger:`/`,icon:`command`,label:e.name})})){P(``);return}let r=e.isSkill?` ${n} `:`${n} `,i=Gl(r,new Set([...la,e.name.toLowerCase()]),r.length);if(e.name===`btw`){let e=li(),t=Sl(e.text,Hr.current?.selectionStart??e.text.length);if(t){let n=i?.text??r;zr(e.text.slice(0,t.start)+n+e.text.slice(t.end))}}else wr(i?.text??r);let a=Hr.current;if(a&&(a._commandMetadata=e),M(!1),P(``),t){Ns({presetText:n});return}let o=()=>{if(!du(or)&&Hr.current){try{Hr.current.focus({preventScroll:!0})}catch{Hr.current.focus()}Hr.current.setSelectionRange(Hr.current.value.length,Hr.current.value.length)}};requestAnimationFrame(()=>{o(),requestAnimationFrame(o)}),setTimeout(o,60)};Z.useEffect(()=>{Sn&&Hr.current&&!or&&Hr.current.focus()},[Sn,or]),Z.useEffect(()=>{or||W(null)},[or]);let jc=bn.abortPrompt.sessionID,Mc=bn.abortPrompt.clear;Z.useEffect(()=>{jc&&jc!==Sn&&Mc()},[Sn,jc,Mc]),Z.useEffect(()=>{ni.current=!!(Sn||wn)},[Sn,wn]);let Nc=Z.useCallback(e=>{if(!e)return!1;if(e.files&&e.files.length>0)return!0;if(e.types){let t=Array.from(e.types).map(e=>e.toLowerCase());if(t.includes(`files`)||t.includes(`text/uri-list`)||t.includes(`codefiles`)||t.includes(`application/x-openchamber-file-path`)||t.some(e=>e.includes(`vnd.code.tree`)))return!0}return LC(e).length>0},[]),Pc=Z.useCallback(e=>{if(!e)return[];let t=Array.from(e.files||[]);return t.length>0?t:Array.from(e.items||[]).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>!!e)},[]),Fc=Z.useCallback(e=>{let t=e.replace(/\\/g,`/`).trim(),n=(wi||``).replace(/\\/g,`/`).replace(/\/+$/,``);if(!n||t===n)return t;let r=`${n}/`;return t.startsWith(r)?t.slice(r.length):t},[wi]),Ic=e=>{if(!Nc(e.dataTransfer))return;e.preventDefault(),e.stopPropagation(),Jr.current++;let t=e.dataTransfer.types?.includes(`application/x-openchamber-file-path`)??!1;t!==b&&S(t),(Sn||wn)&&!v&&y(!0)},Lc=e=>{Nc(e.dataTransfer)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect=`copy`,(Sn||wn)&&!v&&y(!0))},zc=e=>{e.preventDefault(),e.stopPropagation(),Jr.current--,Jr.current<=0&&(Jr.current=0,y(!1),S(!1),dc())},Bc=()=>{Jr.current=0,y(!1),S(!1),dc()},Wc=async e=>{if(Jr.current=0,!Nc(e.dataTransfer)){dc();return}if(e.preventDefault(),e.stopPropagation(),y(!1),!Sn&&!wn)return;let t=e.dataTransfer.getData(`application/x-openchamber-file-path`);if(t&&t!==`.`){let e=`@${t}`,n=Hr.current,r=si.current;if(n){let t=n.selectionStart??Wr.current,i=n.selectionEnd??t,a=Fl(r,t,i,e);zr(a.text),requestAnimationFrame(()=>{n.selectionStart=a.caret,n.selectionEnd=a.caret,Wr.current=a.caret,n.focus()})}else{let t=Fl(r,r.length,r.length,e);zr(t.text)}dc();return}let n=BE(e.dataTransfer);if(n.length>0){fe()&&(ei.current=n),_c(n),fe()||dc();return}let r=Pc(e.dataTransfer);if(r.length>0){let e=Pt(r.map(e=>e.name)),t=Ol(e,si.current.slice(0,Hr.current?.selectionStart??si.current.length),si.current.slice(Hr.current?.selectionEnd??si.current.length));cc(t);for(let e of r)try{await bn.addAttachment(e)}catch(e){console.error(`File attach failed`,e),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.attachFileFailed`))}}dc()},Kc=e=>{Nc(e.dataTransfer)&&(e.preventDefault(),fe()&&(Yr.current=!0,fc()))},qc=Z.useRef(null),Zc=Z.useRef(null),Qc=q((e=!0)=>{Ae.current=0;let t=()=>{let t=Zy(Hr);if(!t||(Qy(Hr),!e))return;let n=t.value.length;try{t.setSelectionRange(n,n)}catch{}};t(),window.requestAnimationFrame(t)}),el=Z.useCallback(async e=>{let t=Array.isArray(e)?e:Array.from(e);if(t.length>0){let e=Pt(t.map(e=>e.name)),n=Ol(e,si.current.slice(0,Hr.current?.selectionStart??si.current.length),si.current.slice(Hr.current?.selectionEnd??si.current.length));cc(n)}for(let e of t)try{await bn.addAttachment(e)}catch(e){console.error(`File attach failed`,e),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.attachFileFailed`))}},[bn,cc,l]),tl=Z.useCallback(async()=>{try{let e=await mi?.pickFiles?.(),t=Array.isArray(e?.files)?e.files:[],n=Array.isArray(e?.skipped)?e.skipped:[];if(n.length>0){let e=n.map(e=>`${e?.name||`file`}: ${e?.reason||`skipped`}`).join(`
|
|
6555
6555
|
`);Ha.error(l(`chat.chatInput.toast.someFilesSkipped`,{summary:e}))}let r=t.map(e=>{if(!e?.dataUrl)return null;try{let[t,n]=e.dataUrl.split(`,`),r=e.mimeType||t?.match(/data:(.*);base64/)?.[1]||`application/octet-stream`;if(!n)return null;let i=atob(n),a=new Uint8Array(i.length);for(let e=0;e<i.length;e++)a[e]=i.charCodeAt(e);let o=new Blob([a],{type:r});return new File([o],e.name||`file`,{type:r})}catch(e){return console.error(`Failed to decode VS Code picked file`,e),null}}).filter(Boolean);r.length>0&&(Qc(!1),await el(r),Qc())}catch(e){console.error(`VS Code file pick failed`,e),Ha.error(e instanceof Error?e.message:l(`chat.chatInput.toast.vscodePickFailed`))}},[el,Qc,l,mi]),nl=Z.useCallback(()=>{if(fe()){tl();return}qc.current?.click()},[tl]),rl=Z.useCallback(()=>{if(fe()){tl();return}Zc.current?.click()},[tl]),sl=Z.useCallback(async()=>{if(!ol()){rl();return}try{let e=await Gc(20);if(e===null){rl();return}e.length>0&&(Qc(!1),await el(e),Qc())}catch(e){console.error(`Native photo pick failed`,e),Ha.error(l(`chat.chatInput.toast.attachFileFailed`))}},[el,Qc,rl,l]),ll=Z.useCallback(async e=>{let t=e.target.files;!t||t.length===0||(Qc(!1),await el(t),e.target.value=``,Qc())},[el,Qc]),dl=`gap-x-1.5 gap-y-0`,fl=fe(),ml=G.kind===`primary`&&Tn&&!fl&&!St,_l=Z.useMemo(()=>(_t?.selectedProjectId?jn.find(e=>e.id===_t.selectedProjectId)??null:null)||(Mn?jn.find(e=>e.id===Mn)??null:null)||(jn[0]??null),[Mn,_t?.selectedProjectId,jn]),xl=Z.useMemo(()=>VE(_l?.path??null),[_l?.path]),Cl=_l?HE(_l):null,Tl=Dl(xl),Al=Vl(e=>xl?e.directories.get(xl)?.lastBranchesFetch??0:0),jl=wl(xl),Nl=!!Tl?.all,Pl=Vl(e=>e.fetchBranches),[Il,Rl]=Z.useState(!1);Z.useEffect(()=>{!ml||!xl||!pi||jl!==null||Ai(xl,pi,{silent:!0})},[Ai,pi,jl,xl,ml]),Z.useEffect(()=>{if(!ml||!xl||!_l||!pi||jl!==!0){Rl(!1);return}let e=!Al||Date.now()-Al>3e4;if(Nl&&!e){Rl(!1);return}let t=!1;return Rl(!Nl),Pl(xl,pi).finally(()=>{t||Rl(!1)}),()=>{t=!0}},[Pl,pi,_l,Al,Nl,jl,xl,ml]);let Bl=El(xl),Ul=Tl?.current?.trim()||Bl?.trim()||``,ql=Z.useMemo(()=>{if(!_l)return null;let e=VE(_l.path);return!e||!Ul?null:{value:e,label:Ul}},[_l,Ul]),Jl=Z.useMemo(()=>{if(!_l)return[];let e=xl?Mt.get(xl)??Mt.get(_l.path)??[]:[];return ko({projectRoot:VE(_l.path)??``,rootBranch:Ul,worktrees:e,pendingBootstrapDirectory:_t?.bootstrapPendingDirectory??null}).filter(e=>e.kind===`worktree`)},[Mt,_t?.bootstrapPendingDirectory,_l,Ul,xl]),Yl=Z.useMemo(()=>VE(_t?.bootstrapPendingDirectory??null)??VE(_t?.directoryOverride??null)??xl,[_t?.bootstrapPendingDirectory,_t?.directoryOverride,xl]),Ql=Z.useMemo(()=>{let e=VE(_t?.bootstrapPendingDirectory??null);return!!(_t?.preserveDirectoryOverride||_t?.pendingWorktreeRequestId||e&&e===Yl)},[_t?.bootstrapPendingDirectory,_t?.pendingWorktreeRequestId,_t?.preserveDirectoryOverride,Yl]),$l=Z.useMemo(()=>{let e=[];return ql&&e.push(ql),e.push(...Jl),!Yl||e.some(e=>e.value===Yl)||!Ql?e:[...e,{value:Yl,label:Gn(Yl)}]},[ql,Yl,Ql,Jl]),eu=Z.useMemo(()=>oC({selectedDirectory:Yl,projectRootOption:ql,worktreeOptions:Jl}),[ql,Yl,Jl]),nu=Ix()===`mini-chat`,ru=Z.useMemo(()=>nu||Ti!==!0||!Di||Di.isClean?!1:xx(Di.files),[Di,Ti,nu]),iu=Z.useMemo(()=>!Yl||ql?.value===Yl||Jl.some(e=>e.value===Yl),[ql?.value,Yl,Jl]);Z.useEffect(()=>{_t?.open&&(!_t.preserveDirectoryOverride&&!_t.bootstrapPendingDirectory||!Yl||!iu||(_t.preserveDirectoryOverride&&Y.getState().setDraftPreserveDirectoryOverride(!1),_t.bootstrapPendingDirectory&&Y.getState().setDraftBootstrapPendingDirectory(null)))},[_t?.bootstrapPendingDirectory,_t?.open,_t?.preserveDirectoryOverride,iu,Yl]);let au=Z.useMemo(()=>jl!==!0||Il?!1:ql?!0:Jl.length>0,[Il,ql,jl,Jl.length]),su=Z.useCallback(e=>{if(Y.getState().newSessionDraft?.pendingWorktreeRequestId)return;let t=jn.find(t=>t.id===e);t&&(Mn!==e&&Nn(e),jt({projectId:e,directoryOverride:t.path},{force:!0}))},[Mn,jn,Nn,jt]),cu=Z.useCallback(e=>{Y.getState().newSessionDraft?.pendingWorktreeRequestId||_l&&jt({projectId:_l.id,directoryOverride:e},{force:!0})},[_l,jt]),lu=Z.useCallback(e=>{let t=e.icon?ms[e.icon]:null,n=e.color?vs[e.color]:void 0,r=(0,$.jsx)(X,{name:t??`folder`,className:`h-3.5 w-3.5`,style:n?{color:n}:void 0});return(0,$.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`flex h-4 w-4 shrink-0 items-center justify-center overflow-hidden text-muted-foreground`,children:e.iconImage?(0,$.jsx)(us,{project:e,className:`size-full object-contain`,fallback:r}):r}),(0,$.jsx)(`span`,{className:`truncate`,children:HE(e)})]})},[]);Z.useEffect(()=>{!ml||!_l||!Yl||_t?.pendingWorktreeRequestId||_t?.bootstrapPendingDirectory||_t?.preserveDirectoryOverride||$l.some(e=>e.value===Yl)||jt({projectId:_l.id,directoryOverride:_l.path})},[$l,_t?.bootstrapPendingDirectory,_t?.pendingWorktreeRequestId,_t?.preserveDirectoryOverride,Yl,_l,jt,ml]);let fu=Z.useCallback(()=>{je(),le(!0),Hr.current?.blur()},[je]),pu=Z.useCallback(()=>{je(),de(!0),Hr.current?.blur()},[je]);Z.useEffect(()=>{if(!or||typeof document>`u`)return;let e=document.getElementById(`mobile-overlay-root`);e||(e=document.createElement(`div`),e.id=`mobile-overlay-root`,document.body.appendChild(e));let t=e,n=()=>ke(tS(t.children));n();let r=new MutationObserver(n);return r.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[eS]}),()=>r.disconnect()},[or]);let mu=Oe||!!te||ce||ue||ka||ja,hu=ur(nr.find(e=>e.id===G.selection.value.providerID),G.selection.value.modelID,l(`chat.modelControls.selectModel`)),gu=G.selection.value.variant?.trim(),_u=q(e=>{I(t=>kl(t,e.rows)),z(t=>t===e.highlightedIndex?t:e.highlightedIndex)}),vu=q(e=>(e.name!==`btw`||G.kind===`primary`)&&rb(G,e)),yu=q(e=>{if(k){oi.current?.acceptIndex(e,!0);return}C&&ri.current?.acceptIndex(e)}),bu=q(()=>{Gr.current=null,M(!1),w(!1),I([]),z(0)}),xu=Nm({enabled:or&&G.kind===`primary`,isMobile:or,text:Cr,textPresetEpoch:xr.textPresetEpoch,placeholder:Ki,modelLabel:hu,modelVariantLabel:gu?ca(gu):``,canSend:Vo,canAbort:Go,attachmentCount:xn.length,suppressed:mu,attachAria:l(`chat.chatInput.actions.addAttachment`),attachTitle:l(`chat.chatInput.actions.addAttachment`),attachPhotosLabel:l(`chat.chatInput.actions.attachPhotos`),attachFilesLabel:l(`chat.chatInput.actions.attachFiles`),attachCancelLabel:l(`chat.chatInput.actions.attachCancel`),sendAria:l(`chat.chatInput.actions.sendMessageAria`),queueAria:l(`chat.chatInput.actions.queueMessageAria`),stopAria:l(`chat.chatInput.actions.stopGeneratingAria`),modelAria:l(`chat.modelControls.selectModel`),modelId:G.selection.value.modelID,providerId:G.selection.value.providerID,agentName:G.selection.value.agent??``,agentLabel:Io(tr,G.selection.value.agent??void 0),agentAria:l(`chat.modelControls.selectAgent`),attachments:xn,removeAttachmentNamedAria:e=>l(`chat.fileAttachment.actions.removeNamed`,{name:e}),onText:(e,t,n)=>{let r=Xl(e.length,n?.end??n?.start??e.length);if(Wr.current=r,t){Hr.current&&(Hr.current.value=e),zr(e);return}let i=si.current,a=ft(i,e,xn.filter(it).map(e=>e.filename)),o=a?.text??e;Hr.current&&(Hr.current.value=o),zr(o);let s=Xl(o.length,n?.end??n?.start??o.length);if(Wr.current=s,oc(o,s),!a)return;let c=new Set(a.removedFilenames.map(e=>e.toLowerCase()));for(let e of xn)c.has(e.filename.toLowerCase())&&bn.removeAttachment(e.id)},onSend:e=>{Hr.current&&(Hr.current.value=e),tu({text:e,applyDocument:zr,submit:Ps})},onAbort:Zs,onAttach:je,onFiles:(e,t)=>{t.length>0&&Ha.error(l(`chat.chatInput.toast.someFilesSkipped`,{summary:t.join(`
|
|
6556
6556
|
`)})),e.length!==0&&el(e)},onRemoveAttachment:e=>{bn.removeAttachment(e)},onOpenModel:()=>Oo(`model`),onCycleAgent:()=>Qs(),onOpenAgent:As,showScrollToBottom:!!(n&&r),scrollAria:l(`chat.scrollToBottom.aria`),onScrollToBottom:r??(()=>{}),autocompleteOpen:F.length>0&&(k||C),autocompleteHighlightedIndex:L,autocompleteRows:F,autocompleteQuery:C?E:N,caret:Wr.current,onAutocompleteAccept:yu,onAutocompleteDismiss:bu,chipHighlights:ya}),Su=Z.useRef(null);In(xu?Su:null,()=>{let e=Su.current?.getBoundingClientRect().height??0;uu(document.documentElement,e)});let Cu=Z.useRef(!1);Cu.current=ka||ja;let wu=Z.useRef(!1),Tu=Z.useRef(0),Eu=Z.useRef(0),Du=q(()=>{let e=Y.getState().stagedMessageEdit;!e||e.sessionId!==Sn||window.setTimeout(()=>{let t=Y.getState().stagedMessageEdit,n=document.activeElement,r=pT({surfaceKind:G.kind,stagedSessionId:t?.sessionId??null,stagedMessageId:t?.messageId??null,blurredMessageId:e.messageId,submitInFlight:ts(),focusHeld:Date.now()<Eu.current,overlayOpen:Tu.current>0||Cu.current,focusInsideComposer:n instanceof Element&&!!(n.closest(`[data-composer-content="true"]`)||n.closest(`[data-slot="dropdown-menu-content"]`))||Date.now()<Ae.current});r.action===`disarm`&&Y.getState().clearStagedMessageEdit(r.sessionId)},0)});Z.useEffect(()=>{if(!or||Yt()||typeof window>`u`||!window.matchMedia?.(`(display-mode: standalone)`)?.matches)return;let e=()=>{Tu.current+=1},t=()=>{if(Tu.current=Math.max(0,Tu.current-1),wu.current){wu.current=!1;return}if(!Ne.current||Cu.current||Tu.current>0)return;if(Vc()){Ne.current=!1;return}Ne.current=!1,Eu.current=Date.now()+600,Hr.current?.focus(),document.activeElement===Hr.current&&oe(!0);let e=()=>{let e=Hr.current;!e||document.activeElement!==e||(Ou.current??e).scrollIntoView({block:`end`})};ne.current!==null&&(window.clearTimeout(ne.current),ne.current=null),ie.current!==null&&(window.clearTimeout(ie.current),ie.current=null),ne.current=window.setTimeout(()=>{ne.current=null,e()},300),ie.current=window.setTimeout(()=>{ie.current=null,e()},650)};return window.addEventListener(`oc:mobile-overlay-opened`,e),window.addEventListener(`oc:mobile-overlay-closed`,t),()=>{ne.current!==null&&(window.clearTimeout(ne.current),ne.current=null),ie.current!==null&&(window.clearTimeout(ie.current),ie.current=null),window.removeEventListener(`oc:mobile-overlay-opened`,e),window.removeEventListener(`oc:mobile-overlay-closed`,t)}},[or]),Z.useEffect(()=>{if(!or)return;if(mu){(ae||Date.now()-Me.current<800)&&(Ne.current=!0);return}if(!Ne.current)return;let e=window.setTimeout(()=>{if(Ne.current=!1,Vc())return;let e=Hr.current;e&&document.activeElement!==e&&e.focus({preventScroll:Yt()})},180);return()=>window.clearTimeout(e)},[or,mu,ae]),Z.useEffect(()=>{if(!or||Yt()||typeof document>`u`||ae||!window.matchMedia?.(`(display-mode: standalone)`)?.matches)return;let e=document.documentElement,t=window.setTimeout(()=>{document.activeElement!==Hr.current&&(window.scrollTo(0,0),document.body.scrollTop=0,e.scrollTop=0)},350);return()=>window.clearTimeout(t)},[or,ae]),Z.useEffect(()=>{be(``)},[me]);let Ou=Z.useRef(null),ku=or?`px-1.5 py-1.5`:fl?`px-1.5 py-1`:`px-2.5 py-1.5`,Au=or?`h-8 w-8`:fl?`h-5 w-5`:`h-6 w-6`,ju=or?`h-4 w-4`:fl?`h-3.5 w-3.5`:`h-4 w-4`,Mu=or?`h-6 w-6`:`size-full`,Nu=or?`h-[1.125rem] w-[1.125rem]`:fl?`h-4 w-4`:`h-[1.125rem] w-[1.125rem]`,Pu=J(`flex cursor-pointer items-center justify-center text-foreground transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed`,Fy),Fu=J(Pu,Au),Iu=J(`flex cursor-pointer items-center justify-center transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed rounded-full hover:opacity-80`,Au),Lu=J(`flex cursor-pointer items-center justify-center transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed rounded-full hover:opacity-80`,`h-6 w-6`);Z.useEffect(()=>()=>{Oa.current&&=(clearTimeout(Oa.current),null)},[]);let Ru=(0,$.jsx)(hg,{quotes:No,removeLabel:l(`chat.btw.removeQuoteAria`),onRemove:e=>{Mo&&O_.getState().removeQuote(Mo,e)}}),zu=or?(0,$.jsxs)(`div`,{"data-composer-action":`true`,className:`composer-mobile-model-controls flex min-w-0 flex-1 items-center justify-end gap-x-1.5`,children:[(0,$.jsx)(KE,{onOpenAgentPanel:As,onCycleAgent:()=>{je(),Qs()},agentName:G.selection.value.agent,agents:tr,disabled:ar}),(0,$.jsx)(qE,{onOpenModel:()=>Oo(`model`),providerID:G.selection.value.providerID,modelID:G.selection.value.modelID,provider:nr.find(e=>e.id===G.selection.value.providerID),variant:G.selection.value.variant})]}):null,Bu=(0,$.jsxs)(`div`,{className:`oc-mobile-composer-attachment-content relative z-10 flex flex-wrap items-center gap-1 px-3 pt-1`,children:[(0,$.jsx)(Mg,{attachments:xn,onShowPopup:lr,onRemoveAttachedFile:uc}),G.kind===`primary`?(0,$.jsx)(Ig,{attachedFiles:xn,onAddVSCodeFile:(e,t,n)=>{Dn&&Si(Dn,()=>yo.getState()).addVSCodeFile(e,t,n)},onAddVSCodeSelection:(e,t)=>{if(Dn)return Si(Dn,()=>yo.getState()).addVSCodeSelection(e,t)}}):null]}),Vu=ya?.map((e,t)=>(0,$.jsx)(`span`,{className:e.className,children:e.visual?(0,$.jsx)(ul,{visual:e.visual,text:e.text}):e.text},`${t}-${e.text.length}`)),Hu=or?(0,$.jsxs)(`div`,{className:J(`oc-mobile-composer-compact-chrome`,Go&&`oc-mobile-composer-compact-chrome--aborting`,Vo&&!Go&&`oc-mobile-composer-compact-chrome--sending`,n&&r&&`oc-mobile-composer-compact-chrome--with-scroll`),children:[(0,$.jsx)(`div`,{"data-mobile-composer-compact-slot":`attach`,"data-composer-action":`true`,className:`composer-mobile-actions flex shrink-0 items-center`,children:(0,$.jsx)(XE,{isVSCode:fl,footerIconButtonClass:Fu,iconSizeClass:Nu,handlePickLocalFiles:nl,handlePickLocalImages:rl,openIssuePicker:js,openPrPicker:Ms,onOpenMobileSheet:fu,onOpenAndroidPickSheet:sr?pu:void 0})}),(0,$.jsxs)(`div`,{"data-mobile-composer-compact-slot":`trailing`,className:`ml-auto flex shrink-0 items-center justify-end gap-x-1`,children:[n&&r?(0,$.jsx)(`div`,{"data-composer-action":`true`,className:`flex shrink-0 items-center`,children:(0,$.jsx)(Px,{placement:`compact`,visible:n,onClick:r})}):null,Go||Vo||Xs?(0,$.jsx)(`div`,{"data-mobile-composer-compact-slot":`action`,"data-composer-action":`true`,className:`flex shrink-0 items-center justify-end`,children:(0,$.jsx)(QE,{isMobile:!0,compact:!0,footerIconButtonClass:Fu,stopFooterIconButtonClass:Iu,compactCircleButtonClass:Lu,sendIconSizeClass:ju,stopIconSizeClass:Mu,canSend:Vo,canAbort:Go,abortPending:Xs,hasContent:!1,currentSessionId:Sn,newSessionDraftOpen:wn,draftSubmitting:Cn,submissionBlocked:a,sendPhase:Qo,queueFrozen:Bo,queueFallbackAvailable:Go||Wo,onPrimaryAction:Ps,onAbort:Zs})}):null]})]}):null,Uu=or?(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`oc-mobile-composer-full-chrome flex w-full min-w-0 items-center gap-x-1.5`,"data-composer-action":`true`,children:[(0,$.jsxs)(`div`,{className:`composer-mobile-actions flex shrink-0 items-center gap-x-2 pl-1`,children:[(0,$.jsx)(XE,{isVSCode:fl,footerIconButtonClass:Fu,iconSizeClass:Nu,handlePickLocalFiles:nl,handlePickLocalImages:rl,openIssuePicker:js,openPrPicker:Ms,onOpenSettings:e,onOpenMobileSheet:fu,onOpenAndroidPickSheet:sr?pu:void 0}),Un?(0,$.jsx)(ZE,{sessionId:Sn,draftOpen:wn,draftEnabled:_t.permissionAutoAcceptEnabled===!0,enabled:zn,saving:Sn?Dt:!1,footerIconButtonClass:Fu,iconSizeClass:Nu,onSetDraftEnabled:Tt,onSetSessionEnabled:Ot,onOpenSessionFirst:wt,onToggleFailed:Kn}):null,(0,$.jsx)(KC,{sessionId:Sn,directory:$e??En,draftOpen:wn}),(0,$.jsx)(qC,{length:Cr.length})]}),zu,(0,$.jsx)(`div`,{className:`relative z-30 flex shrink-0 items-center justify-end gap-x-1.5`,children:(0,$.jsx)(QE,{isMobile:or,footerIconButtonClass:Fu,stopFooterIconButtonClass:Iu,sendIconSizeClass:ju,stopIconSizeClass:Mu,canSend:Vo,canAbort:Go,abortPending:Xs,hasContent:!!Fo,currentSessionId:Sn,newSessionDraftOpen:wn,draftSubmitting:Cn,submissionBlocked:a,sendPhase:Qo,queueFrozen:Bo,queueFallbackAvailable:Go||Wo,onPrimaryAction:Ps,onAbort:Zs})})]})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:J(`flex flex-shrink-0 items-center`,dl),children:[(0,$.jsx)(XE,{isVSCode:fl,footerIconButtonClass:Fu,iconSizeClass:Nu,handlePickLocalFiles:nl,handlePickLocalImages:rl,openIssuePicker:js,openPrPicker:Ms,onOpenSettings:e,withTooltip:!0}),Un?(0,$.jsx)(ZE,{sessionId:Sn,draftOpen:wn,draftEnabled:_t.permissionAutoAcceptEnabled===!0,enabled:zn,saving:Sn?Dt:!1,footerIconButtonClass:Fu,iconSizeClass:Nu,onSetDraftEnabled:Tt,onSetSessionEnabled:Ot,onOpenSessionFirst:wt,onToggleFailed:Kn}):null,(0,$.jsx)(KC,{sessionId:Sn,directory:$e??En,draftOpen:wn}),(0,$.jsx)(qC,{length:Cr.length})]}),(0,$.jsxs)(`div`,{className:J(`relative z-30 flex flex-1 items-center justify-end md:gap-x-1.5`,dl),children:[(0,$.jsx)(WE,{className:`min-w-0 flex-1 justify-end`,composerTextareaRef:Hr,selectionAdapter:Xn}),(0,$.jsx)(GE,{radius:Ui,isMobile:or,footerIconButtonClass:Fu,footerPaddingClass:ku,iconSizeClass:Nu,sendIconSizeClass:ju,onInsert:Is,onInsertAndSend:Ls,onContentHeightChange:nc,renderTrigger:!1,topAccessory:(0,$.jsx)(`span`,{"data-oc-composer-dictation-active":`true`,className:`hidden`,"aria-hidden":`true`})}),(0,$.jsx)(QE,{isMobile:or,footerIconButtonClass:Fu,stopFooterIconButtonClass:Iu,sendIconSizeClass:ju,stopIconSizeClass:Mu,canSend:Vo,canAbort:Go,abortPending:Xs,hasContent:!!Fo,currentSessionId:Sn,newSessionDraftOpen:wn,draftSubmitting:Cn,submissionBlocked:a,sendPhase:Qo,queueFrozen:Bo,queueFallbackAvailable:Go||Wo,onPrimaryAction:Ps,onAbort:Zs})]})]}),Wu=q(()=>{if(or){Eu.current=Date.now()+600;let e=()=>{Hr.current?.focus({preventScroll:Yt()}),document.activeElement===Hr.current&&oe(!0)};e(),window.requestAnimationFrame(e);return}let e=()=>{if(!Qy(Hr))return;let e=Zy(Hr);if(!e)return;let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}};e(),window.requestAnimationFrame(()=>{e(),window.setTimeout(e,0)})}),Gu=$e??En,Ku=G.kind===`secondary`?G.directory:$e,{goal:Ju,enabled:Yu}=BC(Sn??``,Gu),Xu=(0,$.jsx)(Xv,{onEditMessage:Os,onSendMessage:ks,onEditCommitted:Wu,draftKey:Dn,scope:Wa,draftTarget:Dn?{key:Dn,expectedRevision:()=>bn.getDraft(Dn)?.revision??`absent`}:null,clientPendingItems:ys,compactionBarrier:bs,steeringMessageIDs:fs,onSteerClientPending:e=>{if(!Sn||!on({sessionID:Sn}))return;let t=$e??En??``,n=Sn;return hs(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n}),rn({sessionID:n,inboxID:e,directory:t}).catch(()=>{hs(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),Ha.error(l(`chat.chatInput.toast.messageSendFailed`))})},onQueueClientPending:e=>{Sn&&Lt({sessionID:Sn,inboxID:e,directory:$e??En??``}).then(()=>{Qt(Sn,e,`queue`)}).catch(()=>{Ha.error(l(`chat.chatInput.toast.messageSendFailed`))})},onRemoveClientPending:e=>{let t=ai.getState().removeEstablishingFollowUp(e);if(!t){Sn&&At({sessionID:Sn,inboxID:e,directory:$e??En??``}).catch(()=>{Ha.error(l(`chat.chatInput.toast.messageSendFailed`))});return}t.content&&wr(t.content),t.attachments.length>0&&bn.restoreAttachments(t.attachments)},trailing:Sn&&Yu&&Ju?(0,$.jsx)(GC,{sessionId:Sn,directory:Gu}):null});return(0,$.jsxs)($.Fragment,{children:[G.kind===`primary`&&Sn?(0,$.jsx)(iT,{scope:{sessionId:Sn,directory:En},active:G.active,mobile:or}):null,(0,$.jsxs)(`form`,{ref:Ou,onSubmit:e=>{e.preventDefault(),Ps()},onPointerDownCapture:e=>{if(!or)return;let t=e.target;t instanceof Element&&(t.closest(`textarea[data-chat-input="true"]`)||t.closest(`[data-chat-prompt-attachments="true"]`)||t.closest(`button, [role="button"], a, label, input, select, [data-composer-action="true"], [data-chat-input-footer="true"]`)&&(je(),e.preventDefault()))},className:J(`relative w-full pt-0 pb-4`,Ri&&`flex h-full min-h-0 flex-col pt-4`,Bi&&`flex h-full min-h-0 flex-col pt-1`,or&&`bottom-safe-area oc-mobile-composer`),"data-native-ios-composer":xu?`true`:void 0,style:or&&Yt()&&!xu&&hr>0&&!ae?{marginBottom:`${hr}px`}:void 0,children:[Tn&&!Ri&&!or&&!fl&&!nu?(0,$.jsx)(`div`,{className:`chat-input-column mb-7 text-center`,children:(0,$.jsx)(`h1`,{className:`text-balance text-2xl font-normal tracking-tight text-foreground md:text-3xl`,children:UE(Cl?l(`chat.emptyState.draftTitleWithProject`,{project:Cl}):l(`chat.emptyState.draftTitle`),Cl)})}):null,(0,$.jsxs)(`div`,{className:J(`chat-input-column relative overflow-visible`,Hi&&`flex flex-1 min-h-0 flex-col`),children:[xu?null:(0,$.jsx)(Ng,{attachments:xn,onShowPopup:lr,onRemoveAttachedFile:uc}),(0,$.jsx)(gy,{}),uo&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 pb-2`,children:[ho>0?(0,$.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 rounded-xl border px-2.5 py-1`,style:{backgroundColor:Ci?.colors?.surface?.elevated,borderColor:Ci?.colors?.interactive?.border},children:[(0,$.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:l(`chat.chatInput.reviewComments`)}),(0,$.jsx)(`span`,{className:`text-xs font-semibold`,style:{color:Ci?.colors?.status?.info},children:ho}),(0,$.jsx)(`button`,{type:`button`,className:`ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground`,style:{minHeight:0,minWidth:0},onClick:xo,"aria-label":l(`chat.chatInput.reviewCommentsRemove`),title:l(`chat.chatInput.reviewCommentsRemove`),children:(0,$.jsx)(X,{name:`close`,className:`h-3 w-3`})})]}):null,po>0?(0,$.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 rounded-xl border px-2.5 py-1`,style:{backgroundColor:Ci?.colors?.surface?.elevated,borderColor:Ci?.colors?.interactive?.border},children:[(0,$.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:l(`chat.chatInput.devServerLogs`)}),(0,$.jsx)(`span`,{className:`text-xs font-semibold`,style:{color:Ci?.colors?.status?.info},children:po}),(0,$.jsx)(`button`,{type:`button`,className:`ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground`,style:{minHeight:0,minWidth:0},onClick:()=>vo(`preview-console`),"aria-label":l(`chat.chatInput.devServerLogsRemove`),title:l(`chat.chatInput.devServerLogsRemove`),children:(0,$.jsx)(X,{name:`close`,className:`h-3 w-3`})})]}):null,mo>0?(0,$.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 rounded-xl border px-2.5 py-1`,style:{backgroundColor:Ci?.colors?.surface?.elevated,borderColor:Ci?.colors?.interactive?.border},children:[(0,$.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:l(`chat.chatInput.previewAnnotations`)}),(0,$.jsx)(`span`,{className:`text-xs font-semibold`,style:{color:Ci?.colors?.status?.info},children:mo}),(0,$.jsx)(`button`,{type:`button`,className:`ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground`,style:{minHeight:0,minWidth:0},onClick:()=>vo(`preview-annotation`),"aria-label":l(`chat.chatInput.previewContextRemove`),title:l(`chat.chatInput.previewContextRemove`),children:(0,$.jsx)(X,{name:`close`,className:`h-3 w-3`})})]}):null]}),Na&&!fl&&(0,$.jsx)(`div`,{className:`pb-2 w-full px-1`,children:(0,$.jsxs)(`div`,{className:`flex w-full items-center gap-1.5 text-sm h-5 px-1`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>Aa(!0),className:`flex min-w-0 flex-1 items-center gap-1.5 text-left hover:opacity-80 transition-opacity`,children:[Na.author?.avatarUrl&&(0,$.jsx)(`img`,{src:Na.author.avatarUrl,alt:Na.author.login,className:`h-5 w-5 rounded-full flex-shrink-0`}),(0,$.jsxs)(`span`,{className:`text-muted-foreground flex-shrink-0`,children:[`#`,Na.number,Na.author&&(0,$.jsx)(`span`,{className:`ml-1`,children:l(`chat.chatInput.linked.byAuthor`,{author:Na.author.login})})]}),(0,$.jsx)(`span`,{className:`text-foreground truncate`,children:Na.title})]}),(0,$.jsxs)(`span`,{className:`flex items-center gap-0.5 flex-shrink-0`,children:[(0,$.jsx)(`a`,{href:Na.url,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center justify-center h-6 w-6 hover:bg-[var(--interactive-hover)] rounded-full transition-colors`,"aria-label":l(`chat.chatInput.linked.issue.openInBrowserAria`),children:(0,$.jsx)(X,{name:`external-link`,className:`h-4 w-4 text-muted-foreground`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{Fa(null)},className:`flex items-center justify-center h-6 w-6 hover:bg-[var(--interactive-hover)] rounded-full transition-colors`,"aria-label":l(`chat.chatInput.linked.issue.removeAria`),title:l(`chat.chatInput.linked.issue.removeAria`),children:(0,$.jsx)(X,{name:`close`,className:`h-4 w-4 text-muted-foreground`})})]})]})}),La&&!fl&&(0,$.jsx)(`div`,{className:`pb-2 w-full px-1`,children:(0,$.jsxs)(`div`,{className:`flex w-full items-center gap-1.5 text-sm h-5 px-1`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>Ma(!0),className:`flex min-w-0 flex-1 items-center gap-1.5 text-left hover:opacity-80 transition-opacity`,children:[La.author?.avatarUrl&&(0,$.jsx)(`img`,{src:La.author.avatarUrl,alt:La.author.login,className:`h-5 w-5 rounded-full flex-shrink-0`}),(0,$.jsxs)(`span`,{className:`text-muted-foreground flex-shrink-0`,children:[l(`chat.chatInput.linked.pr.number`,{number:La.number}),La.author&&(0,$.jsx)(`span`,{className:`ml-1`,children:l(`chat.chatInput.linked.byAuthor`,{author:La.author.login})})]}),(0,$.jsx)(`span`,{className:`text-foreground truncate`,children:La.title}),(0,$.jsxs)(`span`,{className:`text-muted-foreground flex-shrink-0 typography-meta`,children:[La.head,` → `,La.base]})]}),(0,$.jsxs)(`span`,{className:`flex items-center gap-0.5 flex-shrink-0`,children:[(0,$.jsx)(`a`,{href:La.url,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center justify-center h-6 w-6 hover:bg-[var(--interactive-hover)] rounded-full transition-colors`,"aria-label":l(`chat.chatInput.linked.pr.openInBrowserAria`),children:(0,$.jsx)(X,{name:`external-link`,className:`h-4 w-4 text-muted-foreground`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{Ra(null)},className:`flex items-center justify-center h-6 w-6 hover:bg-[var(--interactive-hover)] rounded-full transition-colors`,"aria-label":l(`chat.chatInput.linked.pr.removeAria`),title:l(`chat.chatInput.linked.pr.removeAria`),children:(0,$.jsx)(X,{name:`close`,className:`h-4 w-4 text-muted-foreground`})})]})]})}),(0,$.jsx)(YE,{sessionId:Sn,directory:$e??En}),(0,$.jsxs)(`div`,{className:or?`relative oc-mobile-composer-stack`:`contents`,children:[(0,$.jsxs)(`div`,{className:or?`oc-mobile-composer-expanded-layer`:`contents`,children:[(0,$.jsx)(`div`,{className:or?`oc-mobile-composer-reveal`:`contents`,children:(0,$.jsxs)(`div`,{ref:Su,"data-native-composer-accessories":`true`,children:[(0,$.jsx)(JE,{showAbortStatus:ji,showAbortPrompt:!!(Ri&&Sn&&Ft===Sn&&typeof It==`number`&&It>Date.now()),showAssistantStatus:!1,showTodos:!0,leftAccessory:wn||!ru?null:(0,$.jsx)(Mx,{})}),!or&&ml?(0,$.jsxs)(`div`,{className:`mb-1.5 flex min-w-0 items-center gap-1.5 px-0.5`,children:[_l?(0,$.jsxs)(_s,{value:_l.id,open:we,onValueChange:su,onOpenChange:e=>{Te(e),e||Ce(``)},children:[(0,$.jsx)(ds,{asChild:!0,size:`sm`,children:(0,$.jsxs)(`button`,{type:`button`,className:J(`group relative inline-flex h-6 min-w-0 w-fit max-w-[42vw] items-center rounded-lg !border-0 px-1.5 py-1 pr-1.5 typography-micro font-medium text-foreground/80 transition-[padding] hover:pr-5 focus-visible:pr-5 data-[popup-open]:pr-5 sm:max-w-[18rem]`,Ny),children:[(0,$.jsx)(Cs,{children:lu(_l)}),(0,$.jsx)(X,{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`})]})}),(0,$.jsxs)(ps,{fitContent:!0,children:[(0,$.jsx)(Ts,{autoFocus:!0,value:Se,onChange:e=>Ce(e.target.value),onKeyDown:e=>e.stopPropagation(),placeholder:l(`chat.chatInput.draftPicker.searchProjects`),className:`mb-1 h-8 min-w-56`}),jn.filter(e=>as(HE(e),Se)||as(e.path,Se)).map(e=>(0,$.jsx)(ls,{value:e.id,className:`max-w-[24rem] truncate`,children:lu(e)},e.id)),(0,$.jsx)(ws,{}),(0,$.jsxs)(`button`,{type:`button`,className:`flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left typography-ui-label text-foreground hover:bg-interactive-hover`,onPointerDown:e=>{e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation(),Te(!1),requestAnimationFrame(()=>Xa.requestDirectoryDialog())},children:[(0,$.jsx)(X,{name:`folder-add`,className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{children:l(`chat.chatInput.draftPicker.newProject`)})]})]})]}):(0,$.jsxs)(`button`,{type:`button`,className:J(`inline-flex h-auto min-h-6 cursor-pointer items-center gap-1.5 rounded-lg px-2.5 py-1 typography-micro font-medium text-foreground/80`,Ny),onClick:()=>Xa.requestDirectoryDialog(),children:[(0,$.jsx)(X,{name:`folder-add`,className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{children:l(`chat.chatInput.draftPicker.newProject`)})]}),_l&&au?(0,$.jsx)(pC,{directory:Yl,projectDirectory:xl,label:eu,projectRootOption:ql,worktreeOptions:Jl,onSelectDirectory:cu}):null]}):null,or&&ml?(0,$.jsxs)(`div`,{className:`oc-mobile-draft-target-selectors mb-1.5 flex min-w-0 items-center gap-1.5 px-0.5`,children:[_l?(0,$.jsx)(`button`,{type:`button`,className:J(`inline-flex h-[1.625rem] min-w-0 max-w-[46%] shrink items-center gap-1.5 rounded-lg px-1.5 text-[11px] leading-none font-medium text-foreground/80`,Ny),onClick:()=>he(`project`),children:lu(_l)}):(0,$.jsxs)(`button`,{type:`button`,className:J(`inline-flex h-[1.625rem] min-w-0 max-w-[46%] items-center gap-1.5 rounded-lg px-1.5 text-[11px] leading-none font-medium text-foreground/80`,Ny),onClick:()=>Xa.requestDirectoryDialog(),children:[(0,$.jsx)(X,{name:`folder-add`,className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{children:l(`chat.chatInput.draftPicker.newProject`)})]}),_l&&au?(0,$.jsx)(pC,{directory:Yl,projectDirectory:xl,label:eu,projectRootOption:ql,worktreeOptions:Jl,onSelectDirectory:cu,maxWidthClassName:`max-w-[50%]`,presentation:`mobile-sheet`}):null]}):null,G.active&&Sn&&Ku?(0,$.jsx)(fy,{sessionId:Sn,directory:Ku}):null,Xu]})}),(0,$.jsx)(`div`,{className:J(!or&&`contents`,or&&`contents`,Bi&&`flex min-h-0 flex-1 flex-col`),children:(0,$.jsxs)(`div`,{className:or?`oc-mobile-composer-motion-viewport`:`contents`,children:[(0,$.jsxs)(Yc,{value:Cr,attachments:[],disabled:!Sn&&!wn||Cn&&!Qo.establishing,pending:Go||Qo.inFlight&&!Qo.establishing,isMobile:or,onSubmit:Ps,"data-mobile-composer-surface":or?`true`:void 0,"data-session-swipe-surface":or?`true`:void 0,expanded:Hi,focusedTone:h===`shell`?`info`:`primary`,className:J(`relative z-10`,v&&`ring-2 ring-primary ring-offset-2`,pr&&`ring-1 ring-[var(--interactive-selection)] border-[var(--interactive-selection)]`,or&&`oc-mobile-composer-surface`),style:{borderRadius:Ui},ref:qr,onDropCapture:Kc,onDragEnter:Ic,onDragOver:Lc,onDragLeave:zc,onDrop:Wc,onDragEnd:Bc,autoResize:!1,disableInputWhilePending:!1,contentClassName:Hi?`flex-1 min-h-0`:void 0,inputHeader:Ru,attachmentContent:Bu,highlightedContent:Vu,highlightRef:Ni,inputRef:Hr,textLayoutClassName:J(xE,Hi?J(`h-full min-h-0`,or?`py-2.5`:`py-4`):or?`py-2.5`:`pt-4 pb-2`,h===`shell`?`font-mono`:`typography-markdown md:typography-ui-label`),inputOuterClassName:J(Hi&&`flex-1 min-h-0`),inputStyle:{flex:Hi?`1 1 auto`:`none`,height:!Hi&&B?`${B.height}px`:void 0,maxHeight:!Hi&&B?`${B.maxHeight}px`:void 0,"--oc-composer-textarea-resting-height":Hi?`100%`:B?`${B.height}px`:`auto`,"--oc-composer-textarea-resting-max-height":!Hi&&B?`${B.maxHeight}px`:`none`,borderTopLeftRadius:Ui,borderTopRightRadius:Ui},footerClassName:J(`z-30 bg-transparent flex-shrink-0`,ku,or?`flex items-center gap-x-1.5`:J(`flex items-center justify-between`,dl)),footerStyle:{borderBottomLeftRadius:Ui,borderBottomRightRadius:Ui},footerContent:Uu,placeholder:Gi,onChange:(e,t)=>gc(t),textareaProps:{readOnly:pr,onCompositionStart:()=>{Ur.current=!0},onCompositionEnd:e=>{Ur.current=!1;let t=e.currentTarget;sc(t.value,t.selectionStart??t.value.length,t.selectionEnd??t.selectionStart??t.value.length)},onBeforeInput:hc,onKeyDown:Vs,onCopy:bc,onCut:xc,onPaste:vc,onDragEnter:Ic,onDragOver:Lc,onDropCapture:Kc,onDrop:Wc,onDragEnd:Bc,onKeyUp:Us,onClick:()=>{Us()},onScroll:e=>{Us();let t=e.currentTarget.scrollTop;Ni.current&&(Ni.current.style.transform=`translateY(-${t}px)`)},onSelect:e=>{let t=e.currentTarget,n=t.selectionStart??0,r=t.selectionEnd??n;if(Ur.current){Wr.current=r;return}let i=gl(n,r,[...Ut(Cr,xn.filter(it).map(e=>e.filename)),...il(Cr,oa.keys()),...Sr.references]);i&&(i.start!==n||i.end!==r)?(t.setSelectionRange(i.start,i.end),Wr.current=i.end):Wr.current=n,Us()},onFocus:()=>{if(or){if(Date.now()<Ae.current){let e=Hr.current;e&&e.blur();return}se.current!==null&&(window.clearTimeout(se.current),se.current=null),oe(!0)}},onBlur:e=>{if(Ur.current=!1,Wr.current=e.currentTarget.selectionStart??Wr.current,Du(),or){if(Date.now()<Eu.current){let e=Hr.current;if(e){e.focus(),window.setTimeout(()=>{Date.now()<Eu.current&&document.activeElement!==e&&e.focus()},50);return}}if(Me.current=Date.now(),Yt()){oe(!1);return}se.current!==null&&window.clearTimeout(se.current),se.current=window.setTimeout(()=>{se.current=null,oe(!1)},120)}},autoCorrect:or?`on`:`off`,autoCapitalize:or?`sentences`:`off`,spellCheck:or||_r,fillContainer:Hi,rows:1},children:[(0,$.jsx)(Mb,{}),v&&(0,$.jsx)(`div`,{className:`absolute inset-0 z-50 flex items-center justify-center bg-background/90`,style:{borderRadius:Ui},children:(0,$.jsxs)(`div`,{className:`text-center`,children:[(0,$.jsx)(`div`,{className:`inline-flex justify-center`,children:(0,$.jsx)(`button`,{type:`button`,className:Pu,onClick:()=>nl(),title:l(`chat.chatInput.actions.attachFiles`),"aria-label":l(`chat.chatInput.actions.attachFiles`),children:(0,$.jsx)(X,{name:`attachment-2`,className:J(Nu,`text-current`)})})}),(0,$.jsx)(`p`,{className:`mt-2 typography-ui-label text-muted-foreground`,children:l(b?`chat.chatInput.drop.insertMention`:`chat.chatInput.drop.attachFiles`)})]})}),k&&(0,$.jsx)(zl,{ref:oi,searchQuery:N,directory:En,onCommandSelect:Ac,onClose:()=>M(!1),commandPolicy:vu,commandContext:On,onRowsChange:xu?_u:void 0,style:Ri&&wa?{left:`${wa.left}px`,top:`${wa.top}px`,bottom:`auto`,width:`min(450px, calc(100% - ${wa.left+8}px))`,maxHeight:`${wa.maxHeight}px`,transform:wa.place===`above`?`translateY(-100%)`:void 0}:void 0}),C&&(0,$.jsx)(vl,{ref:ri,searchQuery:E,onFileSelect:wc,onAgentSelect:Ec,onSkillSelect:kc,onSessionSelect:Dc,onClose:()=>w(!1),onRowsChange:xu?_u:void 0,style:Ri&&wa?{left:`${wa.left}px`,top:`${wa.top}px`,bottom:`auto`,width:`min(520px, calc(100% - ${wa.left+8}px))`,maxHeight:`${wa.maxHeight}px`,transform:wa.place===`above`?`translateY(-100%)`:void 0}:void 0})]}),or?(0,$.jsx)(GE,{radius:Ui,isMobile:or,footerIconButtonClass:Fu,footerPaddingClass:ku,iconSizeClass:Nu,sendIconSizeClass:ju,onInsert:Is,onInsertAndSend:Ls,onContentHeightChange:nc,renderTrigger:!1,topAccessory:(0,$.jsx)(`span`,{"data-oc-composer-dictation-active":`true`,className:`hidden`,"aria-hidden":`true`})}):null]})})]}),or?(0,$.jsxs)(`div`,{className:`oc-mobile-composer-compact-layer`,"data-oc-composer-compact-surface":`true`,children:[Hu,(0,$.jsx)(`div`,{className:J(`oc-mobile-composer-compact-preview`,!Cr.trim()&&`oc-mobile-composer-compact-preview--placeholder`),"aria-hidden":`true`,children:Cr.trim()?Cr:Ki})]}):null]}),or?(0,$.jsx)(WE,{className:`hidden`,composerTextareaRef:Hr,selectionAdapter:Xn,mobilePanel:te,onMobilePanelChange:W}):null]}),wn&&!Ri&&!or&&!fl&&!nu?(0,$.jsx)(WS,{onSubmit:Fs,className:`chat-input-column mt-4`}):null]}),f.open?(0,$.jsx)(Z.Suspense,{fallback:null,children:(0,$.jsx)(SE,{popup:f,onOpenChange:dr,isMobile:or})}):null,(0,$.jsx)(xS,{open:ka,onOpenChange:Aa,mode:`select`,onSelect:e=>{Fa(e),Ra(null)}}),(0,$.jsx)(wS,{open:ja,onOpenChange:Ma,onSelect:e=>{Ra(e),Fa(null)}}),(0,$.jsx)(ig,{open:Pn,onOpenChange:Fn,projectDirectory:$e??En??null,submitting:Ln,onConfirm:Li}),(0,$.jsx)(`input`,{ref:qc,type:`file`,multiple:!0,className:`hidden`,onChange:ll,accept:`*/*`}),(0,$.jsx)(`input`,{ref:Zc,type:`file`,multiple:!0,className:`hidden`,onChange:ll,accept:`image/*`}),null,sr?(0,$.jsx)(Jc,{id:`android-media-pick-sheet`,open:ue,onOpenChange:e=>{e||de(!1)},onPickPhotos:()=>{Ne.current=!1,de(!1),requestAnimationFrame(sl)},onPickFiles:()=>{Ne.current=!1,de(!1),requestAnimationFrame(nl)}}):null,or&&ml&&_l?(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(Hc,{id:`mobile-draft-project-picker-sheet-${_e}`,open:me===`project`,onOpenChange:e=>{e||he(null)},ariaLabel:l(`chat.chatInput.draftPicker.projectTitle`),closeAriaLabel:l(`mobile.surface.closeAria`),resizeAriaLabel:l(`mobile.sessions.sheet.resizeAria`),children:[(0,$.jsx)(`div`,{className:`shrink-0 px-3 pb-2 pt-1`,"data-mobile-sheet-no-dismiss":``,children:(0,$.jsx)(Ts,{value:ye,onChange:e=>be(e.target.value),placeholder:l(`chat.chatInput.draftPicker.searchProjects`),className:`h-9`})}),(0,$.jsx)(Uc,{outerClassName:`min-h-0 flex-1`,disableHorizontal:!0,children:(0,$.jsx)(`div`,{className:`flex flex-col px-3 pb-2`,children:jn.filter(e=>as(HE(e),ye)||as(e.path,ye)).map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2.5 text-left typography-ui-label hover:bg-[var(--interactive-hover)]`,onClick:()=>{su(e.id),he(null)},children:[(0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:lu(e)}),e.id===_l.id?(0,$.jsx)(X,{name:`check`,className:`h-4 w-4 flex-shrink-0 text-muted-foreground`}):null]},e.id))})}),(0,$.jsx)(`div`,{className:`shrink-0 px-3 pb-4 pt-1`,children:(0,$.jsxs)(`button`,{type:`button`,className:`flex w-full cursor-pointer items-center gap-2 rounded-lg border-t border-border/50 px-2 py-2.5 text-left typography-ui-label hover:bg-[var(--interactive-hover)]`,onClick:()=>{he(null),Xa.requestDirectoryDialog()},children:[(0,$.jsx)(X,{name:`folder-add`,className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{children:l(`chat.chatInput.draftPicker.newProject`)})]})})]})}):null]})},iD=e=>{let t=(0,Q.c)(3),n=ab(),r=e.surface??n;if(r&&!r.active)return null;let i=r??void 0,a;return t[0]!==e||t[1]!==i?(a=(0,$.jsx)(rD,{...e,surface:i}),t[0]=e,t[1]=i,t[2]=a):a=t[2],a};iD.displayName=`ChatInput`;var aD=Z.memo(iD);function oD(e){return e.preventDefault()}function sD(e){e.preventDefault()}function cD(e){return e.preventDefault()}function lD(e){e.pointerType===`touch`&&e.preventDefault()}function uD(e){e.preventDefault()}function dD(e){e.pointerType===`touch`&&e.preventDefault()}function fD(){let e=(0,Q.c)(47),{t}=Wn(),[n,r]=Z.useState(null),[i,a]=Z.useState(!1),o=Z.useRef(null),s=!!n,c,l;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(c=()=>Ic(e=>{r(e),a(!1)}),l=[],e[0]=c,e[1]=l):(c=e[0],l=e[1]),Z.useEffect(c,l);let u;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(u=e=>{e||(r(null),a(!1))},e[2]=u):u=e[2];let d=q(u),f;e[3]===d?f=e[4]:(f=()=>(d(!1),!0),e[3]=d,e[4]=f);let p;e[5]!==s||e[6]!==f?(p={id:`image-save-actions`,active:s,layer:`overlay`,onBack:f,surfaceRef:o},e[5]=s,e[6]=f,e[7]=p):p=e[7],cu(p);let m;e[8]!==i||e[9]!==t||e[10]!==n?(m=async()=>{if(!(!n||i)){a(!0);try{await Fd(n),Ha.success(t(`chat.image.actions.saveSuccess`)),r(null)}catch(e){let n=e;if(n instanceof DOMException&&n.name===`AbortError`){a(!1);return}Ha.error(t(`chat.image.actions.saveFailed`)),a(!1);return}a(!1)}},e[8]=i,e[9]=t,e[10]=n,e[11]=m):m=e[11];let h=q(m);if(!n)return null;let g;e[12]!==t||e[13]!==n.filename?(g=n.filename?.trim()||t(`chat.image.actions.sheetTitle`),e[12]=t,e[13]=n.filename,e[14]=g):g=e[14];let _=g,v;e[15]===t?v=e[16]:(v=Yt()?t(`chat.image.actions.saveToPhotos`):t(`chat.image.actions.saveImage`),e[15]=t,e[16]=v);let y=v,b;e[17]===_?b=e[18]:(b=(0,$.jsx)(`h2`,{className:`truncate typography-ui-label font-semibold`,children:_}),e[17]=_,e[18]=b);let x;e[19]===t?x=e[20]:(x=t(`mobile.surface.closeAria`),e[19]=t,e[20]=x);let S;e[21]===t?S=e[22]:(S=t(`mobile.sessions.sheet.resizeAria`),e[21]=t,e[22]=S);let C;e[23]===h?C=e[24]:(C=()=>{h()},e[23]=h,e[24]=C);let w=i?`loader-4`:`download`,T=i?`size-5 animate-spin`:`size-5`,E;e[25]!==w||e[26]!==T?(E=(0,$.jsx)(X,{name:w,className:T}),e[25]=w,e[26]=T,e[27]=E):E=e[27];let D;e[28]!==y||e[29]!==i||e[30]!==t?(D=i?t(`chat.image.actions.saving`):y,e[28]=y,e[29]=i,e[30]=t,e[31]=D):D=e[31];let O;e[32]===D?O=e[33]:(O=(0,$.jsx)(`span`,{className:`truncate`,children:D}),e[32]=D,e[33]=O);let k;e[34]!==i||e[35]!==C||e[36]!==E||e[37]!==O?(k=(0,$.jsx)(`div`,{className:`flex min-h-0 flex-col overflow-y-auto overscroll-contain px-3 pb-3`,children:(0,$.jsx)(`div`,{className:`overflow-hidden rounded-2xl bg-[var(--surface-muted)]`,"data-page-scroll-lock":`true`,children:(0,$.jsxs)(Jn,{type:`button`,variant:`ghost`,size:`lg`,className:`h-auto min-h-12 w-full justify-start gap-3 rounded-none supports-[corner-shape:squircle]:rounded-none px-4 border-b border-[var(--surface-subtle)] last:border-b-0`,"data-mobile-press-feedback":`none`,disabled:i,onClick:C,children:[E,O]})})}),e[34]=i,e[35]=C,e[36]=E,e[37]=O,e[38]=k):k=e[38];let A;return e[39]!==d||e[40]!==s||e[41]!==S||e[42]!==k||e[43]!==b||e[44]!==x||e[45]!==_?(A=(0,$.jsx)(`div`,{ref:o,children:(0,$.jsx)(Hc,{id:`image-save-actions-sheet`,open:s,onOpenChange:d,title:b,ariaLabel:_,closeAriaLabel:x,resizeAriaLabel:S,fitContent:!0,children:k})}),e[39]=d,e[40]=s,e[41]=S,e[42]=k,e[43]=b,e[44]=x,e[45]=_,e[46]=A):A=e[46],A}var pD=e=>!!(e&&typeof e==`object`&&typeof e.type==`string`),mD=e=>e.filter(pD),hD=e=>{let t=e,n=t.text;return typeof n==`string`?n:t.content||t.value||``},gD=e=>{if(e.type!==`text`)return!1;let t=hD(e);return!t||t.trim().length===0},_D=(e,t={})=>{let{includeReasoning:n=!0}=t,r=mD(e),i=r.some(e=>!e.synthetic);return r.filter(e=>{let t=!!e.synthetic;if(e.type===`text`){let t=hD(e);if(t.includes(`<system-reminder>`)&&br(t).length===0)return!1}return t&&i||!n&&e.type===`reasoning`?!1:e.type!==`patch`})},vD=`GitHub issue context (JSON)`,yD=`GitHub pull request context (JSON)`,bD=`The user referenced these OpenCode sessions (id, title, owning directory).`,xD=e=>typeof e==`number`&&Number.isFinite(e)&&e>0,SD=(e,t)=>{let n=e.trimStart();if(!n.startsWith(t))return null;let r=n.indexOf(`{`);if(r<0)return null;try{return JSON.parse(n.slice(r))}catch{return null}},CD=e=>{let t=SD(e,vD);if(t){let e=t.issue,n=e?.number,r=e?.title,i=e?.url;return!xD(n)||typeof r!=`string`||typeof i!=`string`?null:{type:`file`,mime:`application/vnd.github.issue-link`,filename:`Issue #${n}: ${r}`,url:i}}let n=SD(e,yD);if(n){let e=n.pr,t=e?.number,r=e?.title,i=e?.url;return!xD(t)||typeof r!=`string`||typeof i!=`string`?null:{type:`file`,mime:`application/vnd.github.pull-request-link`,filename:`PR #${t}: ${r}`,url:i}}return null},wD=e=>!!e.trim().startsWith(`The following tool was executed by the user`),TD=e=>e.trimStart().startsWith(`Continue working toward the active session goal.`),ED=e=>e.trim()===`/compact`,DD=e=>e.flatMap(e=>{if(e.type===`compaction`)return[];if(e.type===`text`){let t=e.text;if(typeof t==`string`){let n=uo(t);if(n.trim().length===0||TD(n)||ED(n)||n.trimStart().startsWith(bD)||n.includes(`<system-reminder>`)&&br(n).length===0)return[];n!==t&&(e={...e,text:n})}}if(e.synthetic!==!0)return[e];if(e.type!==`text`)return[];let t=e.text;if(typeof t!=`string`)return[];let n=t.trimStart();return wD(t)||n.startsWith(vD)||n.startsWith(yD)?[e]:[]}).map(e=>{let t=e;if(t.type===`text`){let n=typeof t.text==`string`?t.text.trim():``;if(t.synthetic===!0){let e=CD(n);if(e)return e}if(n.startsWith(`The following tool was executed by the user`))return{...e,type:`text`,text:`/shell`};if(n.includes(`<system-reminder>`))return{...e,type:`text`,text:br(n)}}return e}),OD=e=>e.some(e=>{if(e.type===`text`)return!gD(e);if(e.type===`file`){let t=e,n=typeof t.mime==`string`?t.mime:``,r=typeof t.url==`string`?t.url:``;return(!!n||!!r)&&!!r&&!ct(e)}return!0}),kD=e=>e?.length?OD(DD(e)):!1,AD=(e,t)=>{if(t.length===0)return e;let n=new Map(t.map(e=>[e.info.id,e])),r=!1,i=e.map(e=>{if(kD(e.parts))return e;let t=n.get(e.info.id);return t?(r=!0,t):e}),a=r?i:e,o=new Set(e.map(e=>e.info.id)),s=t.filter(e=>!o.has(e.info.id));return s.length===0?a:[...a,...s]},jD=(e,t)=>{if(e.length===0)return!1;let n;for(let t of e){let e=t.info.time?.created;typeof e==`number`&&(n===void 0||e>n)&&(n=e)}return!t.resolvedSessionStatus||typeof t.sessionStatusObservedAt!=`number`||typeof n!=`number`||n>t.sessionStatusObservedAt},MD=e=>{let t=e.boundary.kind===`exhausted`,n=e.boundary.kind===`has-more`,r=t&&!e.assistantComplete,i=n||r;return{complete:t&&e.assistantComplete,canLoadEarlier:i}},ND=e=>e.syncLoading||e.assistantLoading,PD=e=>e.isMobile&&(e.canLoadEarlier||e.isLoadingOlder),FD=e=>e.isLoadingOlder,ID=e=>!e.isMobile&&e.isLoadingOlder,LD=e=>e.transcriptMessageCount>0||e.pendingUserCount>0||e.historyPrefixCount>0,RD=e=>e.hasImmediateShell||e.hasTranscriptShell&&e.hasRenderableSessionSnapshot||e.transcriptRecords?.some(e=>e.info.role===`user`?kD(e.parts):e.parts.some(e=>e.type===`tool`||e.type===`text`&&e.text.trim().length>0))||e.hasPaintedTranscript?`pass`:e.prefetchStatus===`loading`||e.syncLoading||e.userRetrying?`hydrating`:e.prefetchStatus===`error`?`load-error`:e.hasRenderableSessionSnapshot?`pass`:`hydrating`,zD=e=>{let{sessionId:t,messages:n,retained:r}=e;return t?n.length>0?{messages:n,retained:{sessionId:t,messages:n}}:r?.sessionId===t?{messages:r.messages,retained:r}:{messages:n,retained:null}:{messages:n,retained:null}},BD=e=>({newSessionDraft:e?.features?.newSessionDraft??!e,promptNavigator:e?.features?.promptNavigator??!e,returnToParent:e?.features?.returnToParent??!e}),VD=`text-[13px] leading-4 sm:text-[length:var(--text-micro)] sm:leading-5`,HD=`relative bottom-safe-area oc-mobile-readonly-prompt-foot`,UD=e=>{let t=(0,Q.c)(8),{providerId:n,modelId:r,label:i}=e,a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(X,{name:`brain-ai-3`,className:`size-3.5`}),t[0]=a):a=t[0];let o;t[1]===i?o=t[2]:(o=(0,$.jsx)(`span`,{role:`img`,"aria-label":i,className:`inline-flex size-3.5 shrink-0 items-center justify-center`,children:a}),t[1]=i,t[2]=o);let s;return t[3]!==i||t[4]!==r||t[5]!==n||t[6]!==o?(s=(0,$.jsx)(ss,{modelId:r,providerId:n,alt:i,className:`size-3.5 shrink-0`,fallback:o}),t[3]=i,t[4]=r,t[5]=n,t[6]=o,t[7]=s):s=t[7],s},WD=e=>{let t=(0,Q.c)(42),{t:n}=Wn(),r=K(GD),i=`agentName`in e||`providerId`in e||`modelId`in e||`modelName`in e;if(!i){let e=r&&HD,i;t[0]===e?i=t[1]:(i=J(`p-3`,e),t[0]=e,t[1]=i);let a;t[2]===n?a=t[3]:(a=n(`chat.container.readOnlySubagentPromptBanner`),t[2]=n,t[3]=a);let o;t[4]===a?o=t[5]:(o=(0,$.jsx)(`div`,{className:`rounded-2xl border border-border/70 bg-[var(--surface-background)] px-4 py-3 text-muted-foreground ${VD}`,children:a}),t[4]=a,t[5]=o);let s;return t[6]!==i||t[7]!==o?(s=(0,$.jsx)(`div`,{className:i,children:o}),t[6]=i,t[7]=o,t[8]=s):s=t[8],s}let a;t[9]===n?a=t[10]:(a=n(`common.unavailable`),t[9]=n,t[10]=a);let o=a,s;t[11]!==e.agentName||t[12]!==o?(s=e.agentName?e.agentName.charAt(0).toUpperCase()+e.agentName.slice(1):o,t[11]=e.agentName,t[12]=o,t[13]=s):s=t[13];let c=s,l=e.modelName||o,u;t[14]===n?u=t[15]:(u=n(`chat.leaderKey.action.agent`),t[14]=n,t[15]=u);let d=`${u}: ${c}`,f;t[16]===n?f=t[17]:(f=n(`chat.leaderKey.action.model`),t[16]=n,t[17]=f);let p=`${f}: ${l}`,m=r&&HD,h;t[18]===m?h=t[19]:(h=J(`shrink-0 border-t border-border/70 bg-[var(--surface-background)] p-3`,m),t[18]=m,t[19]=h);let g=r&&`oc-mobile-readonly-prompt-surface`,_;t[20]===g?_=t[21]:(_=J(`rounded-2xl border border-border/70 bg-[var(--surface-elevated)] px-3 py-2.5 sm:px-4 sm:py-3`,g),t[20]=g,t[21]=_);let v;t[22]===n?v=t[23]:(v=n(`chat.container.readOnlySubagentPromptBanner`),t[22]=n,t[23]=v);let y;t[24]===v?y=t[25]:(y=(0,$.jsx)(`div`,{className:`text-muted-foreground ${VD}`,children:v}),t[24]=v,t[25]=y);let b;t[26]!==d||t[27]!==c||t[28]!==p||t[29]!==l||t[30]!==e.agentName||t[31]!==e.modelId||t[32]!==e.providerId||t[33]!==i?(b=i?(0,$.jsxs)(`div`,{"data-testid":`read-only-prompt-banner-meta`,className:`mt-1.5 flex min-w-0 items-center justify-between gap-3 border-t border-border/70 pt-1.5 text-[13px] leading-none sm:text-[length:var(--text-micro)]`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5 overflow-hidden`,children:[(0,$.jsx)(es,{name:e.agentName,size:14,label:d}),(0,$.jsx)(`span`,{className:`min-w-0 truncate text-foreground`,title:c,children:c})]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 max-w-[55%] items-center justify-end gap-1.5 overflow-hidden`,children:[(0,$.jsx)(UD,{providerId:e.providerId,modelId:e.modelId,label:p}),(0,$.jsx)(`span`,{className:`min-w-0 truncate text-right text-foreground`,title:l,children:l})]})]}):null,t[26]=d,t[27]=c,t[28]=p,t[29]=l,t[30]=e.agentName,t[31]=e.modelId,t[32]=e.providerId,t[33]=i,t[34]=b):b=t[34];let x;t[35]!==b||t[36]!==_||t[37]!==y?(x=(0,$.jsxs)(`div`,{className:_,children:[y,b]}),t[35]=b,t[36]=_,t[37]=y,t[38]=x):x=t[38];let S;return t[39]!==x||t[40]!==h?(S=(0,$.jsx)(`aside`,{className:h,children:x}),t[39]=x,t[40]=h,t[41]=S):S=t[41],S};function GD(e){return e.isMobile}var KD=Z.memo(()=>{let e=(0,Q.c)(5),{t}=Wn(),{currentTheme:n}=Tc(),r=ii(qD),i=n?.colors?.surface?.mutedForeground||`var(--muted-foreground)`,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(Gs,{width:140,height:140,className:`opacity-20`}),e[0]=a):a=e[0];let o;return e[1]!==r||e[2]!==t||e[3]!==i?(o=(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-full w-full gap-6`,children:[a,r?(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-2 max-w-md text-center px-4`,children:[(0,$.jsx)(`span`,{className:`typography-markdown font-medium text-destructive`,children:t(`chat.emptyState.opencodeUnreachable`)}),(0,$.jsx)(`span`,{className:`typography-meta`,style:{color:i},children:r.message})]}):(0,$.jsx)(`span`,{className:`typography-markdown`,style:{color:i},children:t(`chat.emptyState.startNewChat`)})]}),e[1]=r,e[2]=t,e[3]=i,e[4]=o):o=e[4],o});function qD(e){return e.error}var JD=`oc_asst_session_divider:`,YD=[],XD=e=>typeof e?.info?.id==`string`&&e.info.id.startsWith(`oc_asst_session_divider:`),ZD=(e,t=0)=>({info:{id:`${JD}${e}`,role:`system`,time:{created:t}},parts:[]}),QD=e=>!!(e?.info&&typeof e.info==`object`&&e.info.openchamberAssistantAdmission),$D=(e,t,n=YD)=>{if(!e.length)return YD;let r=[],i=!1,a=null;for(let n of e)n.sessionID!==t&&(i&&a!==n.sessionID&&r.push(ZD(n.sessionID,Number(n.info.time?.created??0))),r.push({info:n.info,parts:n.parts,sourceSessionID:n.sessionID,sourceDirectory:n.directory}),i=!0,a=n.sessionID);return r.length===0?YD:iO(n,r)?n:r},eO=(e,t)=>{if(t.length===0)return e;if(e.length===0)return t;let n=new Map;for(let e of t)e?.id&&n.set(e.id,e);for(let t of e)t?.id&&n.set(t.id,t);let r=new Set,i=[];for(let e of t){if(!e?.id||r.has(e.id))continue;let t=n.get(e.id);t&&(i.push(t),r.add(e.id))}for(let t of e)!t?.id||r.has(t.id)||(i.push(t),r.add(t.id));return i.length===e.length&&i.every((t,n)=>t===e[n])?e:i},tO=(e,t)=>{if(!t)return e;if(e.info.role===`assistant`&&t.parts.length>0){let n=eO(e.parts,t.parts);return n===e.parts&&e.info===t.info?e:n===t.parts&&e.info===t.info&&e.parts===t.parts?t:{...e,parts:n,...t.sourceParts&&!e.sourceParts?{sourceParts:t.sourceParts}:{}}}return kD(e.parts)?e:kD(t.parts)?e.info===t.info&&e.parts===t.parts?t:{...e,parts:t.parts,...t.sourceParts&&!e.sourceParts?{sourceParts:t.sourceParts}:{}}:e.parts.length>0||t.parts.length===0?e:e.info===t.info&&e.parts===t.parts?t:{...e,parts:t.parts,...t.sourceParts&&!e.sourceParts?{sourceParts:t.sourceParts}:{}}},nO=(e,t,n,r=YD)=>{if(!t)return n.length>0?Array.from(n):YD;let i=new Map,a=0;for(let n of e)n.sessionID===t&&(QD(n)||i.set(n.info.id,{message:{info:n.info,parts:n.parts},order:a++}));for(let e of n){let t=i.get(e.info.id);i.set(e.info.id,{message:tO(e,t?.message),order:t?.order??a++})}if(i.size===0)return YD;let o=[...i.values()].sort((e,t)=>Number(e.message.info.time?.created??0)-Number(t.message.info.time?.created??0)||e.order-t.order).map(({message:e})=>e);return iO(r,o)?r:o},rO=(e,t)=>{if(!XD(e)||!XD(t))return!1;let n=Number(e.info.time?.created??0),r=Number(t.info.time?.created??0);return e.info.id===t.info.id&&n===r},iO=(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||!i||!(r===i||rO(r,i))&&(r?.info!==i?.info||r?.parts!==i?.parts||r.sourceSessionID!==i.sourceSessionID||r.sourceDirectory!==i.sourceDirectory))return!1}return!0},aO=()=>qe(e=>({expanded:new Set,toggle:t=>e(e=>{let n=new Set(e.expanded);return n.has(t)?n.delete(t):n.add(t),{expanded:n}})})),oO=(0,Z.createContext)(null);function sO(e){let t=(0,Q.c)(7),n=(0,Z.useContext)(oO),r;t[0]===n?r=t[1]:(r=()=>n??aO(),t[0]=n,t[1]=r);let[i]=(0,Z.useState)(r),a=n??i,o;t[2]===e?o=t[3]:(o=t=>t.expanded.has(e),t[2]=e,t[3]=o);let s=Ge(a,o),c=Ge(a,cO),l;return t[4]!==s||t[5]!==c?(l={expanded:s,toggle:c},t[4]=s,t[5]=c,t[6]=l):l=t[6],l}function cO(e){return e.toggle}var lO=class e{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return e.instance||=new e,e.instance}recordSessionStart(e){this.sessionStartTimes.set(e,Date.now())}getSessionStartTime(e){return this.sessionStartTimes.get(e)}shouldAnimateMessage(e,t){if(e.role!==`assistant`||this.seenMessageIds.has(e.id))return!1;let n=this.sessionStartTimes.get(t);if(!n)return this.seenMessageIds.add(e.id),this.messageCreationTimes.set(e.id,e.time.created),!1;let r=e.time.created>n-5e3;return r||(this.seenMessageIds.add(e.id),this.messageCreationTimes.set(e.id,e.time.created)),r}clearSession(e){this.sessionStartTimes.delete(e)}hasSessionTiming(e){return this.sessionStartTimes.has(e)}hasBeenAnimated(e){return this.seenMessageIds.has(e)}markMessageAsAnimated(e,t){this.seenMessageIds.add(e),this.messageCreationTimes.set(e,t)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}},uO=e=>{if(!e?.trim())return null;let t=e.trim();return t.toLowerCase()==="default"?null:ca(t)},dO=Z.memo(e=>{let t=(0,Q.c)(30),{isUser:n,isMobile:r,providerID:i,modelID:a,agentName:o,modelName:s,variant:c}=e,l;t[0]!==r||t[1]!==n||t[2]!==c?(l=!n&&!r?uO(c):null,t[0]=r,t[1]=n,t[2]=c,t[3]=l):l=t[3];let u=l,d=s||`Assistant`,f,p;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(f=J(`mb-1.5`),p=J(`flex items-center justify-between gap-2`),t[4]=f,t[5]=p):(f=t[4],p=t[5]);let m;t[6]!==o||t[7]!==n||t[8]!==a||t[9]!==i?(m=(0,$.jsx)(`div`,{className:`flex-shrink-0`,children:n?(0,$.jsx)(`div`,{className:`w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center`,children:(0,$.jsx)(X,{name:`user-3`,className:`h-4 w-4 text-primary`})}):(0,$.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,$.jsx)(ss,{modelId:a,providerId:i,className:`h-4 w-4`,fallback:(0,$.jsx)(X,{name:`brain-ai-3`,className:`h-4 w-4`,style:{color:`var(${Jo(o).var})`}})})})}),t[6]=o,t[7]=n,t[8]=a,t[9]=i,t[10]=m):m=t[10];let h=n?`text-primary`:`text-foreground`,g;t[11]===h?g=t[12]:(g=J(`inline-flex min-w-0 items-center gap-1.5 font-semibold typography-ui-header tracking-tight leading-tight`,h),t[11]=h,t[12]=g);let _=n?`You`:d,v;t[13]===_?v=t[14]:(v=(0,$.jsx)(`span`,{className:`truncate`,children:_}),t[13]=_,t[14]=v);let y;t[15]===u?y=t[16]:(y=u?(0,$.jsx)(`span`,{className:`shrink-0 text-xs font-normal leading-tight text-muted-foreground`,children:u}):null,t[15]=u,t[16]=y);let b;t[17]!==g||t[18]!==v||t[19]!==y?(b=(0,$.jsxs)(`h3`,{className:g,children:[v,y]}),t[17]=g,t[18]=v,t[19]=y,t[20]=b):b=t[20];let x;t[21]!==o||t[22]!==n?(x=!n&&o&&(0,$.jsxs)(`div`,{className:J(`agent-badge inline-flex shrink-0 items-center gap-1 cursor-default rounded px-1.5 py-0 font-normal leading-none text-[10px]`,Jo(o).class),children:[(0,$.jsx)(es,{name:o,size:10}),(0,$.jsx)(`span`,{children:o.charAt(0).toUpperCase()+o.slice(1)})]}),t[21]=o,t[22]=n,t[23]=x):x=t[23];let S;t[24]!==b||t[25]!==x?(S=(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[b,x]}),t[24]=b,t[25]=x,t[26]=S):S=t[26];let C;return t[27]!==S||t[28]!==m?(C=(0,$.jsx)(`div`,{className:f,children:(0,$.jsx)(`div`,{className:p,children:(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[m,S]})})}),t[27]=S,t[28]=m,t[29]=C):C=t[29],C}),fO=/(^|\s)\/([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)/g,pO=/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g,mO=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),hO=(e,t)=>e.split(pO).map((e,n)=>n%2==1?e:t(e)).join(``),gO=e=>hO(e,e=>e.replace(/ *\n/g,`
|
|
6557
|
-
`)),_O=({textContent:e,agentMention:t,skillNames:n,decorateInlineReferences:r=!0})=>{let i=hO(e,mO);if(r){if(t?.token&&i.includes(t.token)){let e=`[${t.token}](${rd(t.name)})`;i=i.replace(t.token,e)}i=i.replace(fO,(e,t,r)=>n.has(r)?`${t}[/${r}](${ed(r)})`:e)}return gO(i)},vO=e=>(fO.lastIndex=0,fO.test(e)||e.includes(`[skill:`)),yO=e=>e===`markdown`?`markdown`:`plain`,bO=e=>{if(typeof window>`u`)return!1;let t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0)return!1;let n=t.getRangeAt(0);return e.contains(n.startContainer)||e.contains(n.endContainer)},xO=Z.memo(({part:e,messageId:t,agentMention:n,messageParts:r})=>{let i=e,a=i.text,o=typeof a==`string`?a:i.content||i.value||``,s=Z.useMemo(()=>S_(o),[o]),c=s?s.body:o,[l,u]=Z.useState(!1),[d,f]=Z.useState(!1),p=K(e=>e.userMessageRenderingMode),m=K(e=>e.collapsibleUserMessages),h=qu(),g=xi({directory:h,enabled:vO(c)}),_=Z.useMemo(()=>g.data??[],[g.data]),v=K(e=>e.openContextFile),{t:y}=Wn(),b=yO(p),x=m&&!l,S=Z.useRef(null),C=Z.useMemo(()=>new Map(_.map(e=>[e.name,e])),[_]),w=Z.useMemo(()=>cv(r,c),[r,c]),T=Z.useMemo(()=>{let e=new Map;for(let t of r??[]){if(t.type!==`text`||!gi(t))continue;let n=t.text;if(typeof n==`string`)for(let t of Gr(n))e.set(t.id,{sessionId:t.id,sessionLabel:t.title||t.id})}if(c.includes(`@`))for(let[t,n]of Ct()){let r=typeof n.title==`string`?n.title.trim():``;!r||e.has(t)||(c.includes(`@${r}`)||c.includes(`@${H}${r}`))&&e.set(t,{sessionId:t,sessionLabel:r})}return Array.from(e.values())},[r,c]),E=q(e=>{let t=C.get(e),n=typeof t?.path==`string`?t.path:``,r=ud(n);if(!r||r===`<built-in>`)return;let i=r.toLowerCase().endsWith(`/skill.md`)?r:`${r}/SKILL.md`,a=h||sd(``,i)||`/`,o=()=>{v(a,i)};if(h&&!od(i,h)){Yu(i,h).then(o);return}o()});Z.useEffect(()=>{let e=S.current;if(!e)return;let t=()=>{m&&!l&&e.scrollHeight>e.clientHeight&&f(!0)};f(!1),t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[m,c,l]),Z.useEffect(()=>{m||(u(!1),f(!1))},[m]);let D=q(e=>{let t=e.target,n=(t?.closest(`[data-skill-name]`))?.dataset.skillName??Zu(t?.closest(`a[href]`)?.getAttribute(`href`));if(n){e.preventDefault(),e.stopPropagation(),E(n);return}let r=S.current;r&&(bO(r)||m&&!l&&d&&u(!0))}),O=q(e=>{e.stopPropagation(),u(!1)}),k=Z.useMemo(()=>nv(c,{skillNames:new Set(C.keys()),citationIcons:w.icons,citationDisplayNames:w.displayNames,sessionMentions:T,agentNames:n?.name?new Set([n.name.toLowerCase(),n.token.replace(/^@/,``).toLowerCase()]):void 0,allowPathHeuristics:!0}),[n,w,T,C,c]),A=Z.useMemo(()=>_O({textContent:c,agentMention:n,skillNames:new Set(C.keys()),decorateInlineReferences:!k}),[n,k,C,c]),j=(e,t)=>{if(!e)return null;if(b===`markdown`){let n=_O({textContent:e,skillNames:new Set,decorateInlineReferences:!1});return(0,$.jsx)(Su,{content:n,className:J(`inline w-auto align-baseline [&_.markdown-content]:contents [&_.markdown-content_p]:inline [&_[data-markdown-size-spacer]]:inline`,`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,x&&[`[&_.markdown-content>*]:my-0`,`[&_[data-component='markdown-code']]:my-0`,`[&_[data-component='markdown-code']]:inline`,`[&_[data-component='markdown-code']]:border-0`,`[&_[data-component='markdown-code']]:bg-transparent`,`[&_[data-component='markdown-code']>*:first-child]:hidden`,`[&_[data-component='markdown-code']>div]:inline`,`[&_[data-component='markdown-code']>div]:p-0`,`[&_[data-component='markdown-code']_pre]:inline`,`[&_[data-component='markdown-code']_code]:inline`,`[&_[data-md-code-line-numbers]]:hidden`]),disableLinkSafety:!0,enableFileReferences:!1},t)}return(0,$.jsx)(Z.Fragment,{children:e},t)},M=e=>e.map((e,t)=>e.type===`text`?j(e.text,`text-${t}`):(0,$.jsx)(uv,{decoration:e.decoration,onOpenSkill:E},`ref-${t}-${e.span.start}`)),N=Z.useMemo(()=>{if(k)return M(k);let e=[],t=0,r=!1,i;for(fO.lastIndex=0;(i=fO.exec(c))!==null;){let n=i[1]||``,r=i[2],a=i.index+n.length;C.has(r)&&(i.index>t&&e.push(c.slice(t,i.index)),n&&e.push(n),e.push((0,$.jsxs)(`button`,{type:`button`,className:`text-primary hover:underline`,onClick:e=>{e.stopPropagation(),E(r)},children:[`/`,r]},`skill-${a}-${r}`)),t=a+r.length+1)}t<c.length&&e.push(c.slice(t));let a=e.length>0?e:[c];return!n?.token||!c.includes(n.token)?a:a.flatMap((e,t)=>{if(r||typeof e!=`string`)return e;let i=e.indexOf(n.token);return i===-1?e:(r=!0,[e.slice(0,i),(0,$.jsx)(`a`,{href:Xu(n.name),className:`text-primary hover:underline`,target:`_blank`,rel:`noopener noreferrer`,onClick:e=>e.stopPropagation(),children:n.token},`agent-${t}`),e.slice(i+n.token.length)])})},[n,E,k,M,C,c]);return(!c||c.trim().length===0)&&!s?.quotes.length?null:(0,$.jsxs)(`div`,{className:`relative`,"data-user-message-clamp":x&&d?`true`:void 0,children:[m&&l&&(0,$.jsx)(`button`,{type:`button`,onClick:O,className:`absolute top-0 right-0 z-10 flex items-center justify-center rounded-sm bg-[var(--surface-elevated)] p-0.5 text-[var(--surface-mutedForeground)] hover:text-[var(--surface-foreground)] hover:bg-[var(--interactive-hover)] transition-colors`,"aria-label":y(`chat.message.userText.collapseAria`),children:(0,$.jsx)(X,{name:`arrow-up-s`,className:`h-3.5 w-3.5`})}),s&&s.quotes.length>0?(0,$.jsx)(`div`,{className:`mb-1 flex flex-col gap-0.5`,"data-conversation-quotes":!0,"aria-label":y(`chat.message.conversationQuotesLabel`),children:s.quotes.map((n,r)=>(0,$.jsx)(`p`,{"data-conversation-quote":!0,className:`m-0 whitespace-pre-wrap break-words border-l-2 border-border pl-1.5 typography-meta text-muted-foreground`,children:n},`${e.id||t}-quote-${r}`))}):null,c.trim().length>0?(0,$.jsx)(`div`,{className:J(`break-words font-sans typography-markdown-body`,l&&`pb-3`,b===`plain`&&`whitespace-pre-wrap`,x&&`line-clamp-10`,m&&d&&!l&&`cursor-pointer`),"data-user-message-collapse":x?`true`:void 0,ref:S,onClick:D,children:b===`markdown`?k?M(k):(0,$.jsx)(Su,{content:A,className:J(`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,x&&[`[&_.markdown-content>*]:my-0`,`[&_[data-component='markdown-code']]:my-0`,`[&_[data-component='markdown-code']]:inline`,`[&_[data-component='markdown-code']]:border-0`,`[&_[data-component='markdown-code']]:bg-transparent`,`[&_[data-component='markdown-code']>*:first-child]:hidden`,`[&_[data-component='markdown-code']>div]:inline`,`[&_[data-component='markdown-code']>div]:p-0`,`[&_[data-component='markdown-code']_pre]:inline`,`[&_[data-component='markdown-code']_code]:inline`,`[&_[data-md-code-line-numbers]]:hidden`]),disableLinkSafety:!0,enableFileReferences:!1}):N}):null]},e.id||`${t}-user-text`)}),SO=[{variant:`static`,component:({children:e,className:t,...n})=>(0,$.jsx)(`span`,{...n,className:t,children:e})},{variant:`generate-effect`,component:({children:e,className:t,...n})=>{if(e==null)return null;let r=typeof e==`string`?e:typeof e==`number`?String(e):Array.isArray(e)?e.map(e=>typeof e==`string`||typeof e==`number`?String(e):``).join(``):``;return r?(0,$.jsx)(`span`,{className:J(`inline-block align-baseline`,t),children:r.split(``).map((e,t)=>(0,Z.createElement)(Gd.span,{...n,key:e+String(t),className:J(`inline-block whitespace-pre align-baseline`),initial:{opacity:0},animate:{opacity:1},transition:{ease:`easeOut`,duration:.14,delay:Math.min(t*.0045,.14)}},e))}):null}},{variant:`glitch`,component:({children:e,className:t,...n})=>(0,$.jsxs)(`div`,{className:`group relative overflow-hidden font-medium`,children:[(0,$.jsx)(`span`,{...n,className:J(`invisible`,t),children:e}),(0,$.jsx)(`span`,{...n,className:J(`absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out`,`group-hover:-translate-y-full hover:duration-300`,t),children:e}),(0,$.jsx)(`span`,{...n,className:J(`absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500`,`ease-in-out hover:duration-300 group-hover:translate-y-0`,t),children:e})]})},{variant:`hover-enter`,component:({children:e,className:t,...n})=>{if(typeof e!=`string`)return null;let r=.25,i=.025,a=e.split(``).map(e=>e===` `?`\xA0`:e);return(0,$.jsxs)(Gd.span,{...n,className:J(`relative block select-none overflow-hidden whitespace-nowrap text-primary-muted`,t),initial:`initial`,whileHover:`hovered`,style:{lineHeight:.9},children:[(0,$.jsx)(`div`,{children:a.map((e,t)=>(0,$.jsx)(Gd.span,{className:`inline-block`,variants:{initial:{y:0},hovered:{y:`-100%`}},transition:{duration:r,ease:`easeInOut`,delay:i*t},children:e},String(t)))}),(0,$.jsx)(`div`,{className:J(`absolute inset-0`),children:a.map((e,t)=>(0,$.jsx)(Gd.span,{className:`inline-block`,variants:{initial:{y:`100%`},hovered:{y:0}},transition:{duration:r,ease:`easeInOut`,delay:i*t},children:e},String(t)))})]})}},{variant:`shake`,component:({children:e,className:t,...n})=>(0,$.jsx)(`span`,{...n,className:J(`text-primary-muted hover:animate-text-shake`,t),children:e})},{variant:`hover-decoration`,component:({children:e,className:t,...n})=>(0,$.jsx)(`div`,{className:J(`relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right`,`after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100`),children:(0,$.jsx)(`span`,{...n,className:J(`text-primary-muted`,t),children:e})})}];function CO(e){let t=(0,Q.c)(10),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({variant:i,className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a=i===void 0?`static`:i,o;t[4]===a?o=t[5]:(o=SO.find(e=>e.variant===a)?.component,t[4]=a,t[5]=o);let s=o||SO[0].component,c;return t[6]!==s||t[7]!==n||t[8]!==r?(c=(0,$.jsx)(s,{...r,className:n}),t[6]=s,t[7]=n,t[8]=r,t[9]=c):c=t[9],c}var wO=e=>{let t=`h-3.5 w-3.5 flex-shrink-0`,n=`h-[13px] w-[13px] flex-shrink-0`,r=e.toLowerCase();return r===`edit`||r===`multiedit`||r===`apply_patch`||r===`patch`||r===`str_replace`||r===`str_replace_based_edit_tool`?(0,$.jsx)(X,{name:`pencil`,className:n}):r===`write`||r===`create`||r===`file_write`?(0,$.jsx)(X,{name:`file-edit`,className:n}):r===`read`||r===`view`||r===`file_read`||r===`cat`?(0,$.jsx)(X,{name:`file-text`,className:t}):r===`bash`||r===`shell`||r===`cmd`||r===`terminal`?(0,$.jsx)(X,{name:`terminal-box`,className:t}):r===`execute`?(0,$.jsx)(X,{name:`code-box`,className:t}):r===`list`||r===`ls`||r===`dir`||r===`list_files`?(0,$.jsx)(X,{name:`folder-6`,className:t}):r===`search`||r===`grep`||r===`find`||r===`ripgrep`?(0,$.jsx)(X,{name:`menu-search`,className:t}):r===`glob`?(0,$.jsx)(X,{name:`file-search`,className:t}):r===`fetch`||r===`curl`||r===`wget`||r===`webfetch`||r===`browser`||r===`web-search`||r===`websearch`||r===`search_web`||r===`codesearch`||r===`google`||r===`bing`||r===`duckduckgo`||r===`perplexity`?(0,$.jsx)(X,{name:`global`,className:t}):r===`todowrite`||r===`todoread`?(0,$.jsx)(X,{name:`list-check-3`,className:t}):r===`structuredoutput`||r===`structured_output`?(0,$.jsx)(X,{name:`list-check-2`,className:t}):r===`skill`?(0,$.jsx)(X,{name:`book`,className:t}):r===`task`||r===`subagent`?(0,$.jsx)(X,{name:`ai-agent`,className:t}):r===`question`?(0,$.jsx)(X,{name:`survey`,className:t}):r===`lsp`?(0,$.jsx)(X,{name:`scan-2`,className:t}):r.startsWith(`git`)?(0,$.jsx)(X,{name:`git-branch`,className:t}):(0,$.jsx)(X,{name:`tools`,className:t})},TO=new Map,EO=e=>{let t=TO.get(e);if(t)return t;let n={subscribers:new Set,timerId:null};return TO.set(e,n),n},DO=(e,t)=>{let n=EO(e);return n.subscribers.add(t),t(Date.now()),n.timerId===null&&typeof window<`u`&&(n.timerId=window.setInterval(()=>{let e=Date.now();n.subscribers.forEach(t=>{t(e)})},e)),()=>{let n=TO.get(e);n&&(n.subscribers.delete(t),!(n.subscribers.size>0)&&(n.timerId!==null&&typeof window<`u`&&window.clearInterval(n.timerId),TO.delete(e)))}},OO=(e,t)=>{let n=(0,Q.c)(4),r=t===void 0?250:t,[i,a]=Z.useState(kO),o,s;return n[0]!==e||n[1]!==r?(o=()=>{if(e)return DO(r,a)},s=[e,r],n[0]=e,n[1]=r,n[2]=o,n[3]=s):(o=n[2],s=n[3]),Z.useEffect(o,s),i};function kO(){return Date.now()}var AO=e=>e.match(/<task\s+id="([^"]+)"(?:\s+[^>]*)?>/i)?.[1],jO=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},MO=e=>{if(typeof e!=`string`)return``;let t=e.trim().toLowerCase();if(!t)return``;let n=t.replace(/:\d+$/,``);if(n.includes(`.`)){let e=n.split(`.`).filter(Boolean);return e[e.length-1]??n}return n},NO=e=>{let t=MO(e);return t===`task`||t===`subagent`},PO=e=>{let t=MO(e);return t===`shell`||t===`bash`||t===`cmd`||t===`terminal`},FO=e=>NO(e)||PO(e),IO=e=>{if(!e||typeof e!=`object`)return;let t=e;return jO(t.sessionId)??jO(t.sessionID)},LO=(e,t)=>{if(!t)return e;let n=!1,r=e.map(e=>e?.type!==`subtask`||e.taskSessionID===t?e:(n=!0,{...e,taskSessionID:t}));return n?r:e},RO=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n==`string`){t.push({tool:`tool`,state:{status:`completed`,title:n}});continue}if(!n||typeof n!=`object`)continue;let e=n;t.push({id:typeof e.id==`string`?e.id:void 0,tool:typeof e.tool==`string`?e.tool:`tool`,state:{status:typeof e.state?.status==`string`?e.state.status:typeof e.status==`string`?e.status:void 0,title:typeof e.state?.title==`string`?e.state.title:typeof e.title==`string`?e.title:void 0,input:e.state?.input&&typeof e.state.input==`object`?e.state.input:void 0}})}return t},zO=e=>{if(typeof e!=`string`||e.trim().length===0)return{summaryEntries:[]};let t=e.match(/<task_metadata>\s*([\s\S]*?)\s*<\/task_metadata>/i);if(!t?.[1])return{summaryEntries:[]};try{let e=JSON.parse(t[1].trim());return{sessionId:jO(e.sessionId)??jO(e.sessionID),status:jO(e.status),summaryEntries:RO(e.summary??e.entries??e.tools??e.calls)}}catch{return{summaryEntries:[]}}},BO=e=>{if(typeof e!=`string`||e.trim().length===0)return;let t=zO(e);if(t.sessionId)return t.sessionId;let n=e.match(/task_id\s*:\s*([^\s<"']+)/i),r=e.match(/session[_\s-]?id\s*:\s*([^\s<"']+)/i);return jO((n?.[1]??r?.[1])||AO(e))},VO=e=>{if(!(!e||typeof e!=`object`))return jO(e.status)},HO=/"status"\s*:\s*"running"/i,UO=/\bstatus\s*[:=]\s*["'`]?running\b/i,WO=e=>{if(typeof e!=`string`||e.trim().length===0)return!1;let t=e.match(/<task_metadata>\s*([\s\S]*?)\s*<\/task_metadata>/i);return t?.[1]&&HO.test(t[1])?!0:UO.test(e)},GO=/<subagent\s+([^>]*?)>([\s\S]*?)<\/subagent>/i,KO=(e,t)=>jO(e.match(RegExp(`${t}\\s*=\\s*"([^"]*)"`,`i`))?.[1]),qO=e=>{if(e===`completed`||e===`error`||e===`cancelled`)return e},JO=e=>{if(typeof e!=`string`||e.trim().length===0)return;let t=e.trim().match(GO);if(!t)return;let n=KO(t[1],`sessionID`)??KO(t[1],`sessionId`),r=qO(KO(t[1],`state`));if(!(!n||!r))return{sessionID:n,state:r,description:KO(t[1],`description`),body:t[2].trim()}},YO=/<shell\s+([^>]*?)>([\s\S]*?)<\/shell>/i,XO=e=>{if(typeof e!=`string`||e.trim().length===0)return;let t=e.trim().match(YO);if(!t)return;let n=KO(t[1],`id`),r=qO(KO(t[1],`state`));if(!(!n||!r))return{id:n,state:r,command:KO(t[1],`command`),body:t[2].trim()}},ZO=new WeakMap,QO=e=>{let t=ZO.get(e);if(t)return t;let n=[];if(e.info.role===`assistant`)for(let t of e.parts){if(t.type!==`tool`)continue;let e=t.tool?.trim().toLowerCase();if(!e||NO(e)||e===`todowrite`||e===`todoread`)continue;let r=t.state;n.push({id:t.id,tool:t.tool,state:{status:r?.status,title:r?.title,input:r?.input&&typeof r.input==`object`?r.input:void 0}})}return ZO.set(e,n),n},$O=e=>{let t=[];for(let n of e)t.push(...QO(n));return t},ek=e=>e.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,``).trimEnd(),tk=[`summary`,`changes`,`verification`],nk={summary:`Summary`,changes:`Changes`,verification:`Verification`},rk=/<(summary|changes|verification)(?:\s[^>]*)?>/i,ik=()=>RegExp(`<(${tk.join(`|`)})(?:\\s[^>]*)?>\\s*([\\s\\S]*?)\\s*<\\/\\1>`,`gi`),ak=e=>typeof e!=`string`||e.length===0?!1:rk.test(e),ok=e=>typeof e!=`string`||e.length===0||!e.includes(`<`)||!ak(e)?e:e.replace(ik(),(e,t,n)=>{let r=nk[t.toLowerCase()]??t,i=n.trim();return i.length>0?`## ${r}\n\n${i}`:`## ${r}`}).trimEnd(),sk=e=>ok(ek(e)),ck=e=>{if(!e.isTaskTool)return{isDelegating:!1,showAvatar:!1,title:e.displayName};let t=e.taskAgentName?e.formatName(e.taskAgentName):void 0,n=!!(e.taskSessionId||t);return!e.isFinalized&&!n?{isDelegating:!0,showAvatar:!1,title:e.delegatingLabel}:{isDelegating:!1,showAvatar:n,title:t??e.displayName}},lk=e=>{if(!(!e||typeof e!=`object`||Array.isArray(e)))return e},uk=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},dk=e=>MO(e.tool??e.name),fk=e=>lk(e.state),pk=e=>lk(fk(e)?.metadata)??lk(e.metadata),mk=e=>lk(fk(e)?.input)??lk(e.input),hk=e=>uk(fk(e)?.status)?.toLowerCase(),gk=e=>(Array.isArray(e.parts)?e.parts:Array.isArray(e.content)?e.content:[]).filter(e=>!!e&&typeof e==`object`),_k=e=>{let t=[],n=uk(lk(e.metadata)?.text);n&&t.push(n);for(let n of gk(e)){let e=uk(n.text);e&&t.push(e)}let r=uk(e.text);return r&&t.push(r),t},vk=e=>{let t=uk(e)?.toLowerCase();if(t===`completed`||t===`error`||t===`cancelled`)return t},yk=e=>{let t=new Map,n=new Map,r=(e,n)=>{e&&t.set(e,n)},i=(e,t)=>{e&&n.set(e,t)};for(let t of e){let e=lk(t.metadata),n=uk(e?.source)?.toLowerCase(),a=vk(e?.state);n===`shell`&&a&&(r(uk(e?.shellID),a),r(uk(e?.jobID),a),r(uk(e?.id),a)),n===`subagent`&&a&&i(uk(e?.childID)??uk(e?.sessionID)??uk(e?.sessionId),a);for(let e of _k(t)){let t=XO(e);t&&(r(t.id,t.state),r(t.shellID,t.state),r(t.jobID,t.state));let n=JO(e);n&&i(n.sessionID,n.state)}}return{byShellOrJobID:t,byChildSessionID:n}},bk=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return t.type!==void 0&&t.type!==`tool`||!FO(dk(t))||hk(t)!==`completed`?!1:VO(pk(t))===`running`||VO(fk(t))===`running`},xk=e=>{if(!e||typeof e!=`object`)return!1;let t=e;if(t.type!==void 0&&t.type!==`tool`||!FO(dk(t)))return!1;let n=hk(t);return n===`running`||n===`pending`||n===`started`},Sk=e=>{if(!e||typeof e!=`object`)return;let t=e,n=dk(t);if(!FO(n))return;let r=pk(t),i=mk(t);if(NO(n)){let e=IO(r)??IO(fk(t))??IO(i),n=uk(i?.description),a=uk(i?.agent)??uk(i?.subagent_type)??uk(i?.subagentType);return{type:`subagent`,id:e,label:n??e,agent:a}}let a=uk(r?.shellID)??uk(fk(t)?.shellID),o=uk(r?.jobID)??uk(fk(t)?.jobID),s=uk(i?.command),c=uk(t.id);return{type:`shell`,id:a??o??c,label:s??a??o??c}},Ck=(e,t,n)=>{if(!n)return;let r=pk(t),i=fk(t),a=[e.id,uk(r?.shellID),uk(r?.jobID),uk(i?.shellID),uk(i?.jobID),uk(t.id)];for(let e of a){if(!e)continue;let t=n.byShellOrJobID.get(e);if(t)return t}},wk=(e,t)=>{if(!(!t||!e.id))return t.byChildSessionID.get(e.id)},Tk=e=>{let{part:t,completions:n,childSessionStatusType:r}=e;if(!t||typeof t!=`object`)return{kind:`settled`};let i=t;if(i.type!==void 0&&i.type!==`tool`||!FO(dk(i)))return{kind:`settled`};if(xk(t))return{kind:`blocking`};let a=Sk(t);if(!a)return{kind:`settled`};if(a.type===`shell`){let e=Ck(a,i,n);return e?{kind:`terminal`,state:e}:bk(t)?{kind:`background-running`}:{kind:`settled`}}let o=uk(r)?.toLowerCase();if(o===`idle`)return{kind:`settled`};if(o===`busy`||o===`retry`)return{kind:`background-running`};let s=wk(a,n);return s?{kind:`terminal`,state:s}:bk(t)?(a.id,{kind:`background-running`}):{kind:`settled`}},Ek=async(e,t)=>{let n=e.trim();if(!n)return{ok:!1,error:`sessionID required`};try{return await t.session.background({sessionID:n}),{ok:!0}}catch(e){return{ok:!1,error:(e instanceof Error?e.message:String(e))||`session.background failed`}}},Dk=e=>{if(!e||typeof e!=`object`)return;let t=e;if(!PO(dk(t)))return;let n=pk(t),r=fk(t),i=uk(n?.shellID)??uk(r?.shellID),a=uk(n?.jobID)??uk(r?.jobID),o=uk(t.id);return{shellID:i,jobID:a,workID:i??a??o}};function Ok(e){if(!e.isTaskTool||e.isFinalized)return!1;let t=e.taskSessionId?e.childSessionStatus:e.parentSessionStatus;if(t){if(t.type!==`idle`)return!1;if(typeof e.taskStartedAt==`number`&&typeof e.statusObservedAt==`number`&&e.taskStartedAt<=e.statusObservedAt)return!0}return typeof e.taskStartedAt==`number`&&typeof e.statusSnapshotAt==`number`&&e.taskStartedAt<=e.statusSnapshotAt}var kk=(e,t)=>{if(e===t)return!0;if(!e||!t||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t;return n.input===r.input&&n.output===r.output&&n.reasoning===r.reasoning&&n.cache?.read===r.cache?.read&&n.cache?.write===r.cache?.write},Ak=e=>{if(!e)return null;let t=e.id;return typeof t==`string`&&t.length>0?t:null},jk=e=>{let t=e?.state?.status;return typeof t==`string`?t:null},Mk=e=>e?.state,Nk=e=>e?.metadata,Pk=e=>{let t=e?.time;return{start:typeof t?.start==`number`?t.start:null,end:typeof t?.end==`number`?t.end:null}},Fk=e=>{let t=e;return t?[typeof t.text==`string`?t.text:``,typeof t.content==`string`?t.content:``,typeof t.value==`string`?t.value:``].reduce((e,t)=>t.length>e.length?t:e,``):``},Ik=(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.type!==i.type||Ak(r)!==Ak(i))return!1;if(r.type===`tool`){if(Mk(r)!==Mk(i)||Nk(r)!==Nk(i)||jk(r)!==jk(i))return!1;let e=Pk(r),t=Pk(i);if(e.start!==t.start||e.end!==t.end||r.tool!==i.tool||r.output!==i.output)return!1;continue}let a=Pk(r),o=Pk(i);if(a.start!==o.start||a.end!==o.end)return!1;if(r.type===`text`||r.type===`reasoning`){if(Fk(r)!==Fk(i))return!1;let e=r.shellAction,t=i.shellAction;if((e||t)&&(e?.command!==t?.command||e?.output!==t?.output||e?.status!==t?.status))return!1}}return!0},Lk=(e,t)=>e===t||e.id===t.id&&e.role===t.role&&e.sessionID===t.sessionID&&e.finish===t.finish&&e.status===t.status&&e.error===t.error&&e.mode===t.mode&&e.agent===t.agent&&e.providerID===t.providerID&&e.modelID===t.modelID&&e.variant===t.variant&&e.clientRole===t.clientRole&&e.userMessageMarker===t.userMessageMarker&&(e.time?.created??null)===(t.time?.created??null)&&(e.time?.completed??null)===(t.time?.completed??null)&&e.time?.streamed===t.time?.streamed&&kk(e.tokens,t.tokens),Rk=(e,t)=>Lk(e.info,t.info)&&Ik(e.parts,t.parts),zk=(e,t)=>!e||!t?e===t:Rk(e,t),Bk=(e,t)=>!e||!t?e===t:e.additions===t.additions&&e.deletions===t.deletions&&e.files===t.files&&e.hasDiffs===t.hasDiffs,Vk=(e,t)=>{if(e===t)return!0;if(!e||!t)return!e&&!t;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.file!==i.file||r.additions!==i.additions||r.deletions!==i.deletions)return!1}return!0},Hk=(e,t)=>e.id===t.id&&e.messageId===t.messageId&&e.kind===t.kind&&e.partIndex===t.partIndex&&e.endedAt===t.endedAt&&Ik([e.part],[t.part]),Uk=(e,t,n)=>{let r=0,i=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.messageId!==n;)r+=1;for(;i<(t?.length??0)&&t?.[i]?.messageId!==n;)i+=1;let a=e?.[r],o=t?.[i];if(!a||!o)return a===o;if(!Hk(a,o))return!1;r+=1,i+=1}},Wk=(e,t)=>{if(e.id!==t.id||e.anchorMessageId!==t.anchorMessageId||e.afterToolPartId!==t.afterToolPartId||e.parts.length!==t.parts.length)return!1;for(let n=0;n<e.parts.length;n+=1)if(!Hk(e.parts[n],t.parts[n]))return!1;return!0},Gk=(e,t)=>!!e?.some(e=>e.anchorMessageId===t),Kk=(e,t,n)=>{let r=0,i=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.anchorMessageId!==n;)r+=1;for(;i<(t?.length??0)&&t?.[i]?.anchorMessageId!==n;)i+=1;let a=e?.[r],o=t?.[i];if(!a||!o)return a===o;if(!Wk(a,o))return!1;r+=1,i+=1}},qk=(e,t,n,r)=>{if(e===t)return!0;if(!e||!t)return e===t;if(r)return!0;if(e.isGroupExpanded!==t.isGroupExpanded||e.turnId!==t.turnId||e.isFirstAssistantInTurn!==t.isFirstAssistantInTurn||e.isLastAssistantInTurn!==t.isLastAssistantInTurn||e.isLatestTurn!==t.isLatestTurn||e.isWorking!==t.isWorking||e.isTurnSettled!==t.isTurnSettled||e.hasTools!==t.hasTools||e.hasReasoning!==t.hasReasoning||e.userMessageCreatedAt!==t.userMessageCreatedAt||e.userMessageVariant!==t.userMessageVariant||e.assistantTps!==t.assistantTps||(e.headerMessageId===n||t.headerMessageId===n)&&e.headerMessageId!==t.headerMessageId)return!1;let i=e.activityOwnerMessageId===n||t.activityOwnerMessageId===n;if(i&&e.activityOwnerMessageId!==t.activityOwnerMessageId||!Uk(e.activityParts,t.activityParts,n)||!Kk(e.activityGroupSegments,t.activityGroupSegments,n))return!1;let a=Gk(e.activityGroupSegments,n)||Gk(t.activityGroupSegments,n);return!((i||a)&&e.toggleGroup!==t.toggleGroup||(i||a||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!Bk(e.diffStats,t.diffStats)||(i||a||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!Vk(e.changedFiles,t.changedFiles))},Jk=/^\*\*\*\s+(?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)/m,Yk=/^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@/m,Xk=/(?=^diff --git\s+)/gm,Zk=/^diff --git\s+/m,Qk=/(?=^---\s+\S)/gm,$k=/^---\s+\S/m,eA=e=>typeof e==`object`&&!!e,tA=e=>e.replace(/\r\n/g,`
|
|
6557
|
+
`)),_O=({textContent:e,agentMention:t,skillNames:n,decorateInlineReferences:r=!0})=>{let i=hO(e,mO);if(r){if(t?.token&&i.includes(t.token)){let e=`[${t.token}](${rd(t.name)})`;i=i.replace(t.token,e)}i=i.replace(fO,(e,t,r)=>n.has(r)?`${t}[/${r}](${ed(r)})`:e)}return gO(i)},vO=e=>(fO.lastIndex=0,fO.test(e)||e.includes(`[skill:`)),yO=e=>e===`markdown`?`markdown`:`plain`,bO=e=>{if(typeof window>`u`)return!1;let t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0)return!1;let n=t.getRangeAt(0);return e.contains(n.startContainer)||e.contains(n.endContainer)},xO=Z.memo(({part:e,messageId:t,agentMention:n,messageParts:r})=>{let i=e,a=i.text,o=typeof a==`string`?a:i.content||i.value||``,s=Z.useMemo(()=>S_(o),[o]),c=s?s.body:o,[l,u]=Z.useState(!1),[d,f]=Z.useState(!1),p=K(e=>e.userMessageRenderingMode),m=K(e=>e.collapsibleUserMessages),h=qu(),g=xi({directory:h,enabled:vO(c)}),_=Z.useMemo(()=>g.data??[],[g.data]),v=K(e=>e.openContextFile),{t:y}=Wn(),b=yO(p),x=m&&!l,S=Z.useRef(null),C=Z.useMemo(()=>new Map(_.map(e=>[e.name,e])),[_]),w=Z.useMemo(()=>cv(r,c),[r,c]),T=Z.useMemo(()=>{let e=new Map;for(let t of r??[]){if(t.type!==`text`||!gi(t))continue;let n=t.text;if(typeof n==`string`)for(let t of Gr(n))e.set(t.id,{sessionId:t.id,sessionLabel:t.title||t.id})}if(c.includes(`@`))for(let[t,n]of Ct()){let r=typeof n.title==`string`?n.title.trim():``;!r||e.has(t)||(c.includes(`@${r}`)||c.includes(`@${H}${r}`))&&e.set(t,{sessionId:t,sessionLabel:r})}return Array.from(e.values())},[r,c]),E=q(e=>{let t=C.get(e),n=typeof t?.path==`string`?t.path:``,r=ud(n);if(!r||r===`<built-in>`)return;let i=r.toLowerCase().endsWith(`/skill.md`)?r:`${r}/SKILL.md`,a=h||sd(``,i)||`/`,o=()=>{v(a,i)};if(h&&!od(i,h)){Yu(i,h).then(o);return}o()});Z.useEffect(()=>{let e=S.current;if(!e)return;let t=()=>{m&&!l&&e.scrollHeight>e.clientHeight&&f(!0)};f(!1),t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[m,c,l]),Z.useEffect(()=>{m||(u(!1),f(!1))},[m]);let D=q(e=>{let t=e.target,n=(t?.closest(`[data-skill-name]`))?.dataset.skillName??Zu(t?.closest(`a[href]`)?.getAttribute(`href`));if(n){e.preventDefault(),e.stopPropagation(),E(n);return}let r=S.current;r&&(bO(r)||m&&!l&&d&&u(!0))}),O=q(e=>{e.stopPropagation(),u(!1)}),k=Z.useMemo(()=>nv(c,{skillNames:new Set(C.keys()),citationIcons:w.icons,citationDisplayNames:w.displayNames,sessionMentions:T,agentNames:n?.name?new Set([n.name.toLowerCase(),n.token.replace(/^@/,``).toLowerCase()]):void 0,allowPathHeuristics:!0}),[n,w,T,C,c]),A=Z.useMemo(()=>_O({textContent:c,agentMention:n,skillNames:new Set(C.keys()),decorateInlineReferences:!k}),[n,k,C,c]),j=(e,t)=>{if(!e)return null;if(b===`markdown`){let n=_O({textContent:e,skillNames:new Set,decorateInlineReferences:!1});return(0,$.jsx)(Su,{content:n,className:J(`inline w-auto align-baseline [&_.markdown-content]:contents [&_.markdown-content_p]:inline [&_[data-markdown-size-spacer]]:inline`,`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,x&&[`[&_.markdown-content>*]:my-0`,`[&_[data-component='markdown-code']]:my-0`,`[&_[data-component='markdown-code']]:inline`,`[&_[data-component='markdown-code']]:border-0`,`[&_[data-component='markdown-code']]:bg-transparent`,`[&_[data-component='markdown-code']>*:first-child]:hidden`,`[&_[data-component='markdown-code']>div]:inline`,`[&_[data-component='markdown-code']>div]:p-0`,`[&_[data-component='markdown-code']_pre]:inline`,`[&_[data-component='markdown-code']_code]:inline`,`[&_[data-md-code-line-numbers]]:hidden`]),disableLinkSafety:!0,enableFileReferences:!1},t)}return(0,$.jsx)(Z.Fragment,{children:e},t)},M=e=>e.map((e,t)=>e.type===`text`?j(e.text,`text-${t}`):(0,$.jsx)(uv,{decoration:e.decoration,onOpenSkill:E},`ref-${t}-${e.span.start}`)),N=Z.useMemo(()=>{if(k)return M(k);let e=[],t=0,r=!1,i;for(fO.lastIndex=0;(i=fO.exec(c))!==null;){let n=i[1]||``,r=i[2],a=i.index+n.length;C.has(r)&&(i.index>t&&e.push(c.slice(t,i.index)),n&&e.push(n),e.push((0,$.jsxs)(`button`,{type:`button`,className:`text-primary hover:underline`,onClick:e=>{e.stopPropagation(),E(r)},children:[`/`,r]},`skill-${a}-${r}`)),t=a+r.length+1)}t<c.length&&e.push(c.slice(t));let a=e.length>0?e:[c];return!n?.token||!c.includes(n.token)?a:a.flatMap((e,t)=>{if(r||typeof e!=`string`)return e;let i=e.indexOf(n.token);return i===-1?e:(r=!0,[e.slice(0,i),(0,$.jsx)(`a`,{href:Xu(n.name),className:`text-primary hover:underline`,target:`_blank`,rel:`noopener noreferrer`,onClick:e=>e.stopPropagation(),children:n.token},`agent-${t}`),e.slice(i+n.token.length)])})},[n,E,k,M,C,c]);return(!c||c.trim().length===0)&&!s?.quotes.length?null:(0,$.jsxs)(`div`,{className:`relative`,"data-user-message-clamp":x&&d?`true`:void 0,children:[m&&l&&(0,$.jsx)(`button`,{type:`button`,onClick:O,className:`absolute top-0 right-0 z-10 flex items-center justify-center rounded-sm bg-[var(--surface-elevated)] p-0.5 text-[var(--surface-mutedForeground)] hover:text-[var(--surface-foreground)] hover:bg-[var(--interactive-hover)] transition-colors`,"aria-label":y(`chat.message.userText.collapseAria`),children:(0,$.jsx)(X,{name:`arrow-up-s`,className:`h-3.5 w-3.5`})}),s&&s.quotes.length>0?(0,$.jsx)(`div`,{className:`mb-1 flex flex-col gap-0.5`,"data-conversation-quotes":!0,"aria-label":y(`chat.message.conversationQuotesLabel`),children:s.quotes.map((n,r)=>(0,$.jsx)(`p`,{"data-conversation-quote":!0,className:`m-0 whitespace-pre-wrap break-words border-l-2 border-border pl-1.5 typography-meta text-muted-foreground`,children:n},`${e.id||t}-quote-${r}`))}):null,c.trim().length>0?(0,$.jsx)(`div`,{className:J(`break-words font-sans typography-markdown-body`,l&&`pb-3`,b===`plain`&&`whitespace-pre-wrap`,x&&`line-clamp-10`,m&&d&&!l&&`cursor-pointer`),"data-user-message-collapse":x?`true`:void 0,ref:S,onClick:D,children:b===`markdown`?k?M(k):(0,$.jsx)(Su,{content:A,className:J(`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,x&&[`[&_.markdown-content>*]:my-0`,`[&_[data-component='markdown-code']]:my-0`,`[&_[data-component='markdown-code']]:inline`,`[&_[data-component='markdown-code']]:border-0`,`[&_[data-component='markdown-code']]:bg-transparent`,`[&_[data-component='markdown-code']>*:first-child]:hidden`,`[&_[data-component='markdown-code']>div]:inline`,`[&_[data-component='markdown-code']>div]:p-0`,`[&_[data-component='markdown-code']_pre]:inline`,`[&_[data-component='markdown-code']_code]:inline`,`[&_[data-md-code-line-numbers]]:hidden`]),disableLinkSafety:!0,enableFileReferences:!1}):N}):null]},e.id||`${t}-user-text`)}),SO=[{variant:`static`,component:({children:e,className:t,...n})=>(0,$.jsx)(`span`,{...n,className:t,children:e})},{variant:`generate-effect`,component:({children:e,className:t,...n})=>{if(e==null)return null;let r=typeof e==`string`?e:typeof e==`number`?String(e):Array.isArray(e)?e.map(e=>typeof e==`string`||typeof e==`number`?String(e):``).join(``):``;return r?(0,$.jsx)(`span`,{className:J(`inline-block align-baseline`,t),children:r.split(``).map((e,t)=>(0,Z.createElement)(Gd.span,{...n,key:e+String(t),className:J(`inline-block whitespace-pre align-baseline`),initial:{opacity:0},animate:{opacity:1},transition:{ease:`easeOut`,duration:.14,delay:Math.min(t*.0045,.14)}},e))}):null}},{variant:`glitch`,component:({children:e,className:t,...n})=>(0,$.jsxs)(`div`,{className:`group relative overflow-hidden font-medium`,children:[(0,$.jsx)(`span`,{...n,className:J(`invisible`,t),children:e}),(0,$.jsx)(`span`,{...n,className:J(`absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out`,`group-hover:-translate-y-full hover:duration-300`,t),children:e}),(0,$.jsx)(`span`,{...n,className:J(`absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500`,`ease-in-out hover:duration-300 group-hover:translate-y-0`,t),children:e})]})},{variant:`hover-enter`,component:({children:e,className:t,...n})=>{if(typeof e!=`string`)return null;let r=.25,i=.025,a=e.split(``).map(e=>e===` `?`\xA0`:e);return(0,$.jsxs)(Gd.span,{...n,className:J(`relative block select-none overflow-hidden whitespace-nowrap text-primary-muted`,t),initial:`initial`,whileHover:`hovered`,style:{lineHeight:.9},children:[(0,$.jsx)(`div`,{children:a.map((e,t)=>(0,$.jsx)(Gd.span,{className:`inline-block`,variants:{initial:{y:0},hovered:{y:`-100%`}},transition:{duration:r,ease:`easeInOut`,delay:i*t},children:e},String(t)))}),(0,$.jsx)(`div`,{className:J(`absolute inset-0`),children:a.map((e,t)=>(0,$.jsx)(Gd.span,{className:`inline-block`,variants:{initial:{y:`100%`},hovered:{y:0}},transition:{duration:r,ease:`easeInOut`,delay:i*t},children:e},String(t)))})]})}},{variant:`shake`,component:({children:e,className:t,...n})=>(0,$.jsx)(`span`,{...n,className:J(`text-primary-muted hover:animate-text-shake`,t),children:e})},{variant:`hover-decoration`,component:({children:e,className:t,...n})=>(0,$.jsx)(`div`,{className:J(`relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right`,`after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100`),children:(0,$.jsx)(`span`,{...n,className:J(`text-primary-muted`,t),children:e})})}];function CO(e){let t=(0,Q.c)(10),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({variant:i,className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a=i===void 0?`static`:i,o;t[4]===a?o=t[5]:(o=SO.find(e=>e.variant===a)?.component,t[4]=a,t[5]=o);let s=o||SO[0].component,c;return t[6]!==s||t[7]!==n||t[8]!==r?(c=(0,$.jsx)(s,{...r,className:n}),t[6]=s,t[7]=n,t[8]=r,t[9]=c):c=t[9],c}var wO=e=>{let t=`h-3.5 w-3.5 flex-shrink-0`,n=`h-[13px] w-[13px] flex-shrink-0`,r=e.toLowerCase();return r===`edit`||r===`multiedit`||r===`apply_patch`||r===`patch`||r===`str_replace`||r===`str_replace_based_edit_tool`?(0,$.jsx)(X,{name:`pencil`,className:n}):r===`write`||r===`create`||r===`file_write`?(0,$.jsx)(X,{name:`file-edit`,className:n}):r===`read`||r===`view`||r===`file_read`||r===`cat`?(0,$.jsx)(X,{name:`file-text`,className:t}):r===`bash`||r===`shell`||r===`cmd`||r===`terminal`?(0,$.jsx)(X,{name:`terminal-box`,className:t}):r===`execute`?(0,$.jsx)(X,{name:`code-box`,className:t}):r===`list`||r===`ls`||r===`dir`||r===`list_files`?(0,$.jsx)(X,{name:`folder-6`,className:t}):r===`search`||r===`grep`||r===`find`||r===`ripgrep`?(0,$.jsx)(X,{name:`menu-search`,className:t}):r===`glob`?(0,$.jsx)(X,{name:`file-search`,className:t}):r===`fetch`||r===`curl`||r===`wget`||r===`webfetch`||r===`browser`||r===`web-search`||r===`websearch`||r===`search_web`||r===`codesearch`||r===`google`||r===`bing`||r===`duckduckgo`||r===`perplexity`?(0,$.jsx)(X,{name:`global`,className:t}):r===`todowrite`||r===`todoread`?(0,$.jsx)(X,{name:`list-check-3`,className:t}):r===`structuredoutput`||r===`structured_output`?(0,$.jsx)(X,{name:`list-check-2`,className:t}):r===`skill`?(0,$.jsx)(X,{name:`book`,className:t}):r===`task`||r===`subagent`?(0,$.jsx)(X,{name:`ai-agent`,className:t}):r===`question`?(0,$.jsx)(X,{name:`survey`,className:t}):r===`lsp`?(0,$.jsx)(X,{name:`scan-2`,className:t}):r.startsWith(`git`)?(0,$.jsx)(X,{name:`git-branch`,className:t}):(0,$.jsx)(X,{name:`tools`,className:t})},TO=new Map,EO=e=>{let t=TO.get(e);if(t)return t;let n={subscribers:new Set,timerId:null};return TO.set(e,n),n},DO=(e,t)=>{let n=EO(e);return n.subscribers.add(t),t(Date.now()),n.timerId===null&&typeof window<`u`&&(n.timerId=window.setInterval(()=>{let e=Date.now();n.subscribers.forEach(t=>{t(e)})},e)),()=>{let n=TO.get(e);n&&(n.subscribers.delete(t),!(n.subscribers.size>0)&&(n.timerId!==null&&typeof window<`u`&&window.clearInterval(n.timerId),TO.delete(e)))}},OO=(e,t)=>{let n=(0,Q.c)(4),r=t===void 0?250:t,[i,a]=Z.useState(kO),o,s;return n[0]!==e||n[1]!==r?(o=()=>{if(e)return DO(r,a)},s=[e,r],n[0]=e,n[1]=r,n[2]=o,n[3]=s):(o=n[2],s=n[3]),Z.useEffect(o,s),i};function kO(){return Date.now()}var AO=e=>e.match(/<task\s+id="([^"]+)"(?:\s+[^>]*)?>/i)?.[1],jO=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},MO=e=>{if(typeof e!=`string`)return``;let t=e.trim().toLowerCase();if(!t)return``;let n=t.replace(/:\d+$/,``);if(n.includes(`.`)){let e=n.split(`.`).filter(Boolean);return e[e.length-1]??n}return n},NO=e=>{let t=MO(e);return t===`task`||t===`subagent`},PO=e=>{let t=MO(e);return t===`shell`||t===`bash`||t===`cmd`||t===`terminal`},FO=e=>NO(e)||PO(e),IO=e=>{if(!e||typeof e!=`object`)return;let t=e;return jO(t.sessionId)??jO(t.sessionID)},LO=(e,t)=>{if(!t)return e;let n=!1,r=e.map(e=>e?.type!==`subtask`||e.taskSessionID===t?e:(n=!0,{...e,taskSessionID:t}));return n?r:e},RO=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n==`string`){t.push({tool:`tool`,state:{status:`completed`,title:n}});continue}if(!n||typeof n!=`object`)continue;let e=n;t.push({id:typeof e.id==`string`?e.id:void 0,tool:typeof e.tool==`string`?e.tool:`tool`,state:{status:typeof e.state?.status==`string`?e.state.status:typeof e.status==`string`?e.status:void 0,title:typeof e.state?.title==`string`?e.state.title:typeof e.title==`string`?e.title:void 0,input:e.state?.input&&typeof e.state.input==`object`?e.state.input:void 0}})}return t},zO=e=>{if(typeof e!=`string`||e.trim().length===0)return{summaryEntries:[]};let t=e.match(/<task_metadata>\s*([\s\S]*?)\s*<\/task_metadata>/i);if(!t?.[1])return{summaryEntries:[]};try{let e=JSON.parse(t[1].trim());return{sessionId:jO(e.sessionId)??jO(e.sessionID),status:jO(e.status),summaryEntries:RO(e.summary??e.entries??e.tools??e.calls)}}catch{return{summaryEntries:[]}}},BO=e=>{if(typeof e!=`string`||e.trim().length===0)return;let t=zO(e);if(t.sessionId)return t.sessionId;let n=e.match(/task_id\s*:\s*([^\s<"']+)/i),r=e.match(/session[_\s-]?id\s*:\s*([^\s<"']+)/i);return jO((n?.[1]??r?.[1])||AO(e))},VO=e=>{if(!(!e||typeof e!=`object`))return jO(e.status)},HO=/"status"\s*:\s*"running"/i,UO=/\bstatus\s*[:=]\s*["'`]?running\b/i,WO=e=>{if(typeof e!=`string`||e.trim().length===0)return!1;let t=e.match(/<task_metadata>\s*([\s\S]*?)\s*<\/task_metadata>/i);return t?.[1]&&HO.test(t[1])?!0:UO.test(e)},GO=/<subagent\s+([^>]*?)>([\s\S]*?)<\/subagent>/i,KO=(e,t)=>jO(e.match(RegExp(`${t}\\s*=\\s*"([^"]*)"`,`i`))?.[1]),qO=e=>{if(e===`completed`||e===`error`||e===`cancelled`)return e},JO=e=>{if(typeof e!=`string`||e.trim().length===0)return;let t=e.trim().match(GO);if(!t)return;let n=KO(t[1],`sessionID`)??KO(t[1],`sessionId`),r=qO(KO(t[1],`state`));if(!(!n||!r))return{sessionID:n,state:r,description:KO(t[1],`description`),body:t[2].trim()}},YO=/<shell\s+([^>]*?)>([\s\S]*?)<\/shell>/i,XO=e=>{if(typeof e!=`string`||e.trim().length===0)return;let t=e.trim().match(YO);if(!t)return;let n=KO(t[1],`id`),r=qO(KO(t[1],`state`));if(!(!n||!r))return{id:n,state:r,command:KO(t[1],`command`),body:t[2].trim()}},ZO=new WeakMap,QO=e=>{let t=ZO.get(e);if(t)return t;let n=[];if(e.info.role===`assistant`)for(let t of e.parts){if(t.type!==`tool`)continue;let e=t.tool?.trim().toLowerCase();if(!e||NO(e)||e===`todowrite`||e===`todoread`)continue;let r=t.state;n.push({id:t.id,tool:t.tool,state:{status:r?.status,title:r?.title,input:r?.input&&typeof r.input==`object`?r.input:void 0}})}return ZO.set(e,n),n},$O=e=>{let t=[];for(let n of e)t.push(...QO(n));return t},ek=e=>e.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,``).trimEnd(),tk=[`summary`,`changes`,`verification`],nk={summary:`Summary`,changes:`Changes`,verification:`Verification`},rk=/<(summary|changes|verification)(?:\s[^>]*)?>/i,ik=()=>RegExp(`<(${tk.join(`|`)})(?:\\s[^>]*)?>\\s*([\\s\\S]*?)\\s*<\\/\\1>`,`gi`),ak=e=>typeof e!=`string`||e.length===0?!1:rk.test(e),ok=e=>typeof e!=`string`||e.length===0||!e.includes(`<`)||!ak(e)?e:e.replace(ik(),(e,t,n)=>{let r=nk[t.toLowerCase()]??t,i=n.trim();return i.length>0?`## ${r}\n\n${i}`:`## ${r}`}).trimEnd(),sk=e=>ok(ek(e)),ck=e=>{if(!e.isTaskTool)return{isDelegating:!1,showAvatar:!1,title:e.displayName};let t=e.taskAgentName?e.formatName(e.taskAgentName):void 0,n=!!(e.taskSessionId||t);return!e.isFinalized&&!n?{isDelegating:!0,showAvatar:!1,title:e.delegatingLabel}:{isDelegating:!1,showAvatar:n,title:t??e.displayName}},lk=e=>{if(!(!e||typeof e!=`object`||Array.isArray(e)))return e},uk=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},dk=e=>MO(e.tool??e.name),fk=e=>lk(e.state),pk=e=>lk(fk(e)?.metadata)??lk(e.metadata),mk=e=>lk(fk(e)?.input)??lk(e.input),hk=e=>uk(fk(e)?.status)?.toLowerCase(),gk=e=>(Array.isArray(e.parts)?e.parts:Array.isArray(e.content)?e.content:[]).filter(e=>!!e&&typeof e==`object`),_k=e=>{let t=[],n=uk(lk(e.metadata)?.text);n&&t.push(n);for(let n of gk(e)){let e=uk(n.text);e&&t.push(e)}let r=uk(e.text);return r&&t.push(r),t},vk=e=>{let t=uk(e)?.toLowerCase();if(t===`completed`||t===`error`||t===`cancelled`)return t},yk=e=>{let t=new Map,n=new Map,r=(e,n)=>{e&&t.set(e,n)},i=(e,t)=>{e&&n.set(e,t)};for(let t of e){let e=lk(t.metadata),n=uk(e?.source)?.toLowerCase(),a=vk(e?.state);n===`shell`&&a&&(r(uk(e?.shellID),a),r(uk(e?.jobID),a),r(uk(e?.id),a)),n===`subagent`&&a&&i(uk(e?.childID)??uk(e?.sessionID)??uk(e?.sessionId),a);for(let e of _k(t)){let t=XO(e);t&&(r(t.id,t.state),r(t.shellID,t.state),r(t.jobID,t.state));let n=JO(e);n&&i(n.sessionID,n.state)}}return{byShellOrJobID:t,byChildSessionID:n}},bk=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return t.type!==void 0&&t.type!==`tool`||!FO(dk(t))||hk(t)!==`completed`?!1:VO(pk(t))===`running`||VO(fk(t))===`running`},xk=e=>{if(!e||typeof e!=`object`)return!1;let t=e;if(t.type!==void 0&&t.type!==`tool`||!FO(dk(t)))return!1;let n=hk(t);return n===`running`||n===`pending`||n===`started`},Sk=e=>{if(!e||typeof e!=`object`)return;let t=e,n=dk(t);if(!FO(n))return;let r=pk(t),i=mk(t);if(NO(n)){let e=IO(r)??IO(fk(t))??IO(i),n=uk(i?.description),a=uk(i?.agent)??uk(i?.subagent_type)??uk(i?.subagentType);return{type:`subagent`,id:e,label:n??e,agent:a}}let a=uk(r?.shellID)??uk(fk(t)?.shellID),o=uk(r?.jobID)??uk(fk(t)?.jobID),s=uk(i?.command),c=uk(t.id);return{type:`shell`,id:a??o??c,label:s??a??o??c}},Ck=(e,t,n)=>{if(!n)return;let r=pk(t),i=fk(t),a=[e.id,uk(r?.shellID),uk(r?.jobID),uk(i?.shellID),uk(i?.jobID),uk(t.id)];for(let e of a){if(!e)continue;let t=n.byShellOrJobID.get(e);if(t)return t}},wk=(e,t)=>{if(!(!t||!e.id))return t.byChildSessionID.get(e.id)},Tk=e=>{let{part:t,completions:n,childSessionStatusType:r}=e;if(!t||typeof t!=`object`)return{kind:`settled`};let i=t;if(i.type!==void 0&&i.type!==`tool`||!FO(dk(i)))return{kind:`settled`};if(xk(t))return{kind:`blocking`};let a=Sk(t);if(!a)return{kind:`settled`};if(a.type===`shell`){let e=Ck(a,i,n);return e?{kind:`terminal`,state:e}:bk(t)?{kind:`background-running`}:{kind:`settled`}}let o=uk(r)?.toLowerCase();if(o===`idle`)return{kind:`settled`};if(o===`busy`||o===`retry`)return{kind:`background-running`};let s=wk(a,n);return s?{kind:`terminal`,state:s}:bk(t)?(a.id,{kind:`background-running`}):{kind:`settled`}},Ek=async(e,t)=>{let n=e.trim();if(!n)return{ok:!1,error:`sessionID required`};try{return await t.session.background({sessionID:n}),{ok:!0}}catch(e){return{ok:!1,error:(e instanceof Error?e.message:String(e))||`session.background failed`}}},Dk=e=>{if(!e||typeof e!=`object`)return;let t=e;if(!PO(dk(t)))return;let n=pk(t),r=fk(t),i=uk(n?.shellID)??uk(r?.shellID),a=uk(n?.jobID)??uk(r?.jobID),o=uk(t.id);return{shellID:i,jobID:a,workID:i??a??o}};function Ok(e){if(!e.isTaskTool||e.isFinalized)return!1;let t=e.taskSessionId?e.childSessionStatus:e.parentSessionStatus;if(t){if(t.type!==`idle`)return!1;if(typeof e.taskStartedAt==`number`&&typeof e.statusObservedAt==`number`&&e.taskStartedAt<=e.statusObservedAt)return!0}return typeof e.taskStartedAt==`number`&&typeof e.statusSnapshotAt==`number`&&e.taskStartedAt<=e.statusSnapshotAt}var kk=(e,t)=>{if(e===t)return!0;if(!e||!t||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t;return n.input===r.input&&n.output===r.output&&n.reasoning===r.reasoning&&n.cache?.read===r.cache?.read&&n.cache?.write===r.cache?.write},Ak=e=>{if(!e)return null;let t=e.id;return typeof t==`string`&&t.length>0?t:null},jk=e=>{let t=e?.state?.status;return typeof t==`string`?t:null},Mk=e=>e?.state,Nk=e=>e?.metadata,Pk=e=>{let t=e?.time;return{start:typeof t?.start==`number`?t.start:null,end:typeof t?.end==`number`?t.end:null}},Fk=e=>{let t=e;return t?[typeof t.text==`string`?t.text:``,typeof t.content==`string`?t.content:``,typeof t.value==`string`?t.value:``].reduce((e,t)=>t.length>e.length?t:e,``):``},Ik=(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.type!==i.type||Ak(r)!==Ak(i))return!1;if(r.type===`compaction`){let e=r,t=i;if(e.status!==t.status||e.summary!==t.summary||e.reason!==t.reason||e.recent!==t.recent||e.error?.type!==t.error?.type||e.error?.message!==t.error?.message||e.error?.status!==t.error?.status)return!1}if(r.type===`tool`){if(Mk(r)!==Mk(i)||Nk(r)!==Nk(i)||jk(r)!==jk(i))return!1;let e=Pk(r),t=Pk(i);if(e.start!==t.start||e.end!==t.end||r.tool!==i.tool||r.output!==i.output)return!1;continue}let a=Pk(r),o=Pk(i);if(a.start!==o.start||a.end!==o.end)return!1;if(r.type===`text`||r.type===`reasoning`){if(Fk(r)!==Fk(i))return!1;let e=r.shellAction,t=i.shellAction;if((e||t)&&(e?.command!==t?.command||e?.output!==t?.output||e?.status!==t?.status))return!1}}return!0},Lk=(e,t)=>e===t||e.id===t.id&&e.role===t.role&&e.sessionID===t.sessionID&&e.finish===t.finish&&e.status===t.status&&e.error===t.error&&e.mode===t.mode&&e.agent===t.agent&&e.providerID===t.providerID&&e.modelID===t.modelID&&e.variant===t.variant&&e.clientRole===t.clientRole&&e.userMessageMarker===t.userMessageMarker&&(e.time?.created??null)===(t.time?.created??null)&&(e.time?.completed??null)===(t.time?.completed??null)&&e.time?.streamed===t.time?.streamed&&kk(e.tokens,t.tokens),Rk=(e,t)=>Lk(e.info,t.info)&&Ik(e.parts,t.parts),zk=(e,t)=>!e||!t?e===t:Rk(e,t),Bk=(e,t)=>!e||!t?e===t:e.additions===t.additions&&e.deletions===t.deletions&&e.files===t.files&&e.hasDiffs===t.hasDiffs,Vk=(e,t)=>{if(e===t)return!0;if(!e||!t)return!e&&!t;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.file!==i.file||r.additions!==i.additions||r.deletions!==i.deletions)return!1}return!0},Hk=(e,t)=>e.id===t.id&&e.messageId===t.messageId&&e.kind===t.kind&&e.partIndex===t.partIndex&&e.endedAt===t.endedAt&&Ik([e.part],[t.part]),Uk=(e,t,n)=>{let r=0,i=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.messageId!==n;)r+=1;for(;i<(t?.length??0)&&t?.[i]?.messageId!==n;)i+=1;let a=e?.[r],o=t?.[i];if(!a||!o)return a===o;if(!Hk(a,o))return!1;r+=1,i+=1}},Wk=(e,t)=>{if(e.id!==t.id||e.anchorMessageId!==t.anchorMessageId||e.afterToolPartId!==t.afterToolPartId||e.parts.length!==t.parts.length)return!1;for(let n=0;n<e.parts.length;n+=1)if(!Hk(e.parts[n],t.parts[n]))return!1;return!0},Gk=(e,t)=>!!e?.some(e=>e.anchorMessageId===t),Kk=(e,t,n)=>{let r=0,i=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.anchorMessageId!==n;)r+=1;for(;i<(t?.length??0)&&t?.[i]?.anchorMessageId!==n;)i+=1;let a=e?.[r],o=t?.[i];if(!a||!o)return a===o;if(!Wk(a,o))return!1;r+=1,i+=1}},qk=(e,t,n,r)=>{if(e===t)return!0;if(!e||!t)return e===t;if(r)return!0;if(e.isGroupExpanded!==t.isGroupExpanded||e.turnId!==t.turnId||e.isFirstAssistantInTurn!==t.isFirstAssistantInTurn||e.isLastAssistantInTurn!==t.isLastAssistantInTurn||e.isLatestTurn!==t.isLatestTurn||e.isWorking!==t.isWorking||e.isTurnSettled!==t.isTurnSettled||e.hasTools!==t.hasTools||e.hasReasoning!==t.hasReasoning||e.userMessageCreatedAt!==t.userMessageCreatedAt||e.userMessageVariant!==t.userMessageVariant||e.assistantTps!==t.assistantTps||(e.headerMessageId===n||t.headerMessageId===n)&&e.headerMessageId!==t.headerMessageId)return!1;let i=e.activityOwnerMessageId===n||t.activityOwnerMessageId===n;if(i&&e.activityOwnerMessageId!==t.activityOwnerMessageId||!Uk(e.activityParts,t.activityParts,n)||!Kk(e.activityGroupSegments,t.activityGroupSegments,n))return!1;let a=Gk(e.activityGroupSegments,n)||Gk(t.activityGroupSegments,n);return!((i||a)&&e.toggleGroup!==t.toggleGroup||(i||a||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!Bk(e.diffStats,t.diffStats)||(i||a||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!Vk(e.changedFiles,t.changedFiles))},Jk=/^\*\*\*\s+(?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)/m,Yk=/^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@/m,Xk=/(?=^diff --git\s+)/gm,Zk=/^diff --git\s+/m,Qk=/(?=^---\s+\S)/gm,$k=/^---\s+\S/m,eA=e=>typeof e==`object`&&!!e,tA=e=>e.replace(/\r\n/g,`
|
|
6558
6558
|
`).replace(/\r/g,`
|
|
6559
6559
|
`).trim(),nA=e=>{let t=!1;return e.split(`
|
|
6560
6560
|
`).map(e=>{if(e.startsWith(`@@`))return t=!0,e;if(t)return e;let n=e.match(/^\s*(---|\+\+\+)\s+(.+)$/);if(!n)return e;let r=n[1],i=n[2]??``;return i.trim()===`/dev/null`?`${r} /dev/null`:`${r} ${i.replace(/\\/g,`/`)}`}).join(`
|
|
@@ -6591,7 +6591,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}f
|
|
|
6591
6591
|
|
|
6592
6592
|
`):WN(Array.from(t.childNodes).map(e=>YN(e)).join(``))},QN=e=>Array.from(e.childNodes).every(e=>{if(e.nodeType===Node.TEXT_NODE||e.nodeType!==Node.ELEMENT_NODE)return!0;let t=e;return!HN.has(t.tagName.toLowerCase())}),$N=(e,t)=>{let n=e.cloneContents();if(QN(n)){let e=WN(Array.from(n.childNodes).map(e=>YN(e)).join(``));if(e)return e}return Array.from(n.childNodes).map(e=>ZN(e)).filter(e=>e.length>0).join(`
|
|
6593
6593
|
|
|
6594
|
-
`).trim()||WN(t)},eP=({containerRef:e})=>{let{t}=Wn(),[n,r]=Z.useState({x:0,y:0,show:!1}),[i,a]=Z.useState(``),o=Z.useRef(!1),[s,c]=Z.useState(!1),l=Z.useRef(null),u=Z.useRef(RN),d=Z.useRef(null),f=Z.useRef(null),p=Z.useRef(null),m=Z.useRef(!1),h=Z.useRef(0),[g,_]=Z.useState(null),v=Y(e=>e.currentSessionId),y=qu()??null,b=K(e=>e.isMobile),x=Qb(),S=$b(x).textSelectionMutation,C=x.kind===`primary`&&!!v;Z.useEffect(()=>{m.current=n.show},[n.show]),Z.useEffect(()=>()=>{f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null),p.current!==null&&(window.clearTimeout(p.current),p.current=null)},[]);let w=Z.useCallback(()=>{d.current=null,VN===w&&(VN=null),m.current&&=(f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null),c(!1),r(e=>({...e,show:!1})),a(``),!1)},[]);Z.useEffect(()=>()=>{VN===w&&(VN=null)},[w]);let T=Z.useCallback(e=>{if(typeof window>`u`)return e;let t=window.innerWidth,n=u.current/2,r=NN+n,i=t-NN-n;return r>i?t/2:Math.min(Math.max(e,r),i)},[]),E=Z.useCallback(()=>{if(!d.current)return;VN!==w&&(VN?.(),VN=w);let{markdownText:e,rect:t}=d.current,i=!n.show,o=b?t.left+t.width/2:T(t.left+t.width/2),s=t.top-10;a(e),r({x:o,y:s,show:!0}),m.current=!0,i&&(c(!0),f.current!==null&&window.cancelAnimationFrame(f.current),f.current=window.requestAnimationFrame(()=>{c(!1),f.current=null}))},[T,w,b,n.show]);Z.useLayoutEffect(()=>{if(!n.show||b||!l.current)return;let e=l.current.offsetWidth;!Number.isFinite(e)||e<=0||e===u.current||(u.current=e,r(e=>({...e,x:T(e.x)})))},[T,b,n.show]),Z.useEffect(()=>{if(!n.show||b)return;let e=()=>{r(e=>({...e,x:T(e.x)}))};return window.addEventListener(`resize`,e),()=>{window.removeEventListener(`resize`,e)}},[T,b,n.show]);let D=Z.useCallback(()=>{let t=window.getSelection(),n=e.current;if(!t||!n){o.current||w();return}let r=WN(t.toString());if(!r){o.current||w();return}let i=qN(t,n);if(!i){o.current||w();return}let a=i.getBoundingClientRect();d.current={plainText:r,markdownText:$N(i,r),rect:a},o.current||E()},[e,w,E]);Z.useEffect(()=>{let t=e.current;if(!t)return;let n=()=>{o.current=!0,w()},r=()=>{o.current=!1,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{p.current=null,D()},10)},i=new Set,a=()=>{for(let e of KN(t))i.has(e)||(i.add(e),e.addEventListener(`selectionchange`,D))};a();let s=new MutationObserver(a);s.observe(t,{childList:!0,subtree:!0}),document.addEventListener(`selectionchange`,D),t.addEventListener(`mousedown`,n),document.addEventListener(`mouseup`,r);let c=e=>{l.current&&!l.current.contains(e.target)&&!window.getSelection()?.toString().trim()&&w()};return document.addEventListener(`mousedown`,c),()=>{p.current!==null&&(window.clearTimeout(p.current),p.current=null),s.disconnect();for(let e of i)e.removeEventListener(`selectionchange`,D);document.removeEventListener(`selectionchange`,D),t.removeEventListener(`mousedown`,n),document.removeEventListener(`mouseup`,r),document.removeEventListener(`mousedown`,c)}},[e,D,w,E]),Z.useLayoutEffect(()=>{if(!b||!n.show){h.current=0,_(null);return}let e=Uw(Jw),t=0,r=0,i=()=>{let e=BN(h.current);h.current=e.height,_(t=>t&&t.left===e.left&&t.top===e.top&&t.width===e.width&&t.height===e.height?t:e)},a=e=>{i(),e<r&&(t=window.requestAnimationFrame(a))},o=()=>{r=performance.now()+320,window.cancelAnimationFrame(t),t=window.requestAnimationFrame(a)};i(),o();let s=window.visualViewport;return s?.addEventListener(`resize`,o),s?.addEventListener(`scroll`,o),window.addEventListener(`resize`,o),window.addEventListener(`oc:keyboard-anim`,o),window.addEventListener(`oc:keyboard-settled`,o),()=>{window.cancelAnimationFrame(t),s?.removeEventListener(`resize`,o),s?.removeEventListener(`scroll`,o),window.removeEventListener(`resize`,o),window.removeEventListener(`oc:keyboard-anim`,o),window.removeEventListener(`oc:keyboard-settled`,o),e()}},[b,n.show]),Z.useEffect(()=>{if(!n.show)return;let e=e=>{l.current&&e.target instanceof Node&&l.current.contains(e.target)||w()};return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),()=>{window.removeEventListener(`scroll`,e,!0)}},[n.show,w]);let O=()=>{w(),window.getSelection()?.removeAllRanges()},k=q(e=>{if(!e)return;let t=Y.getState().newSessionDraft.draftID,n=g_(v,t);n&&(O_.getState().addQuote(n,e),O(),requestAnimationFrame(()=>{Array.from(document.querySelectorAll(`textarea[data-chat-input="true"]`)).find(e=>!e.closest(`[data-btw-composer]`))?.focus()}))}),A=q(e=>{if(!e||!v)return;let t={sessionId:v,directory:y};zw.getState().addQuote(t,e),O(),cT(t)});if(Z.useEffect(()=>{if(!S)return;let t=t=>{let n=rc(t,PN),r=C&&rc(t,FN);if(!n&&!r)return;let i=window.getSelection(),a=e.current;if(!i||!a||!i.toString().trim())return;let o=qN(i,a);if(!o)return;t.preventDefault(),t.stopPropagation();let s=$N(o,i.toString());n?k(s):A(s)};return window.addEventListener(`keydown`,t,!0),()=>window.removeEventListener(`keydown`,t,!0)},[k,A,C,S,e]),!n.show||!S)return null;let j=[{id:`chat`,label:t(`chat.textSelection.actions.addToChat`),shortcut:PN,run:()=>k(i)},...C?[{id:`side`,label:t(`chat.textSelection.actions.addToSideChat`),shortcut:FN,run:()=>A(i)}]:[]];if(b){let e=g??{left:0,top:Math.max(0,window.innerHeight-88),width:window.innerWidth,height:88};return(0,fp.createPortal)((0,$.jsx)(`div`,{ref:l,"data-text-selection-menu":!0,className:J(`fixed z-50 flex items-center justify-center gap-2 bg-background px-4`,`transition-opacity duration-200 ease-out`,s?`opacity-0`:`opacity-100`),style:{left:e.left,top:e.top,width:e.width,height:e.height,paddingBottom:`max(0.75rem, var(--oc-safe-area-bottom-visual, env(safe-area-inset-bottom, 0px)))`},onPointerDown:e=>{e.preventDefault()},children:j.map(e=>(0,$.jsx)(Jn,{type:`button`,variant:`secondary`,size:`sm`,onClick:e.run,className:`max-w-[11rem] min-w-0`,children:(0,$.jsx)(`span`,{className:`truncate`,children:e.label})},e.id))}),document.body)}return(0,fp.createPortal)((0,$.jsx)(`div`,{ref:l,"data-text-selection-menu":!0,className:`fixed z-50`,style:{left:n.x,top:n.y,transform:`translate(-50%, -100%)`},children:(0,$.jsx)(`div`,{className:J(`flex items-center gap-0.5 whitespace-nowrap rounded-lg p-0.5`,`border border-[var(--interactive-border)] bg-[var(--surface-elevated)] shadow-sm`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,s?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),children:j.map((e,t)=>(0,$.jsxs)(Z.Fragment,{children:[t>0?(0,$.jsx)(`div`,{className:`h-3 w-px shrink-0 bg-[var(--interactive-border)]`}):null,(0,$.jsxs)(`button`,{type:`button`,onClick:e.run,className:`flex h-6 items-center gap-1.5 rounded-md px-2 typography-meta text-[var(--surface-foreground)] transition-colors duration-150 hover:bg-[var(--interactive-hover)]`,children:[(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(`span`,{className:`tracking-[0.08em] text-[var(--surface-muted-foreground)]`,"aria-hidden":`true`,children:LN(e.shortcut)})]})]},e.id))})}),document.body)},tP=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),nP=(e,t)=>{let n=new Date(t);return n.setDate(t.getDate()-1),tP(e,n)},rP=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),iP=(e,t)=>{if(!rP(e))return``;let n=new Date(e),r=new Date,i=Ps(n,t),a=qn(),o=Xn.getState().dictionary;if(tP(n,r))return i;if(nP(n,r))return Zn(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}`},aP=e=>typeof e!=`number`||!Number.isFinite(e)||e<0?0:e,oP=e=>{let t=0,n=0,r=!0;return e.map(e=>{if(typeof e.createdAt==`number`&&Number.isFinite(e.createdAt)&&typeof e.streamedAt==`number`&&Number.isFinite(e.streamedAt)?n+=Math.max(0,e.streamedAt-e.createdAt):r=!1,t+=aP(e.outputTokens)+aP(e.reasoningTokens),!r||t<=0||n<=0)return null;let i=t/(n/1e3);return Number.isFinite(i)&&i>0?i:null})},sP=e=>{let t=oP(e);return t[t.length-1]??null},cP=e=>e.completionDisposition!==`active`&&typeof e.tps==`number`&&Number.isFinite(e.tps)&&e.tps>0,lP=e=>!Number.isFinite(e)||e<=0?``:`${e.toFixed(1)} tok/s`,uP=e=>{let t=(0,Q.c)(20),{text:n,active:r,className:i}=e,a=Z.useRef(n),[o,s]=Z.useState(n),[c,l]=Z.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]),Z.useEffect(u,d);let f;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(f=()=>{l(null)},t[4]=f):f=t[4];let p=q(f),m;t[5]===i?m=t[6]:(m=J(`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=J(`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},dP=[`search`,`read`,`list`];function fP(e){let t=rj(e);return t===`read`?`read`:t===`glob`||t===`grep`?`search`:t===`list`?`list`:null}function pP(e){let t={read:0,search:0,list:0};for(let n of e){let e=fP(n);e&&(t[e]+=1)}return t}var mP=[`edit`,`command`,`other`],hP=new Set([`edit`,`multiedit`,`write`,`create`,`file_write`,`apply_patch`,`patch`]),gP=new Set([`bash`,`shell`,`cmd`,`command`,`exec`,`terminal`]);function _P(e){if(!$A(e))return null;let t=rj(e);return hP.has(t)?`edit`:gP.has(t)?`command`:`other`}function vP(e){let t={edit:0,command:0,other:0};for(let n of e){let e=_P(n);e&&(t[e]+=1)}return t}function yP(e){return EA(e)}var bP=[...dP,...mP];function xP(e){return{...pP(e),...vP(e)}}function SP(e){return nj(e)}function CP(e){return e.kind===`reasoning`||e.type===`reasoning`?!1:e.kind===`justification`||e.type===`text`?!0:e.kind===`tool`||e.type===`tool`?!ej(e.toolName):e.kind!=null||e.type!=null}function wP(e,t,n){for(let r=t;r<e.length;r+=1)if(CP(n(e[r])))return!0;return!1}function TP(e){return`parts`in e?e.parts.some(e=>SP(e))?!0:!e.hasFollowingOtherType&&e.isTurnLive:e.some(e=>SP(e))}function EP(e,t,n){let r=[],i=t;for(;i<e.length&&ej(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var DP=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,OP=e=>{let t=(0,Q.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=J(`inline-flex flex-none items-center gap-0.5 tabular-nums`,DP),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},kP=({activities:e,isMobile:t,isTurnLive:n=!1,hasFollowingOtherType:r=!1,exploring:i,children:a})=>{let{t:o}=Wn(),[s,c]=Z.useState(!1),l=Z.useId(),u=e.map(e=>e.part),d=i??TP({parts:u,hasFollowingOtherType:r,isTurnLive:n}),f=xP(u.map(e=>e.tool)),p=yP(u),m=bP.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=q(()=>{c(e=>!e)}),g=q(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:ky(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":s,"aria-controls":l,"aria-label":_,"data-mobile-press-feedback":`soft`,className:J(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,My),onClick:h,onKeyDown:g,children:[(0,$.jsx)(`span`,{className:J(`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)(zA,{isMobile:t,label:o(`chat.usedGroup.running`),className:`block`}):(0,$.jsx)(X,{name:`search`,className:`block h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:J(`typography-meta inline-flex flex-none items-center self-center font-medium`,y,DP,d&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...d?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:v}),m?(0,$.jsx)(`span`,{className:J(`typography-meta inline-flex min-h-0 w-0 min-w-0 max-w-full flex-1 items-center self-center overflow-clip`,y,DP),style:{color:`var(--tools-description)`},children:(0,$.jsx)(uP,{text:m,active:d,className:t?`!h-5 sm:!h-5`:`!h-6 sm:!h-6`})}):null,(0,$.jsx)(OP,{added:p.added,removed:p.removed}),(0,$.jsx)(X,{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:Ay(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 AP(e,t,n){let r=[],i=t;for(;i<e.length&&QA(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var jP=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null};function MP(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=jP(n.metadata.name);if(e)return e}if(n.input&&typeof n.input==`object`){let e=n.input,t=jP(e.name);if(t)return t;let r=jP(e.id);if(r)return r}if(n.output&&typeof n.output==`object`){let e=jP(n.output.name);if(e)return e}return null}function NP(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 PP=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,FP=({activities:e,isMobile:t,children:n})=>{let{t:r}=Wn(),[i,a]=Z.useState(!1),o=Z.useId(),s=e.map(e=>e.part),c=s.some(e=>nj(e)),{joinedVisible:l,hiddenCount:u}=NP(s.map(MP)),d=u>0?r(`chat.skillGroup.summaryOverflow`,{names:l,count:u}):l,f=q(()=>{a(e=>!e)}),p=q(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:ky(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":i,"aria-controls":o,"aria-label":m,"data-mobile-press-feedback":`soft`,className:J(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,My),onClick:f,onKeyDown:p,children:[(0,$.jsx)(`span`,{className:J(`flex flex-none items-center justify-center`,t?`size-4`:`size-3.5`),style:{color:`var(--tools-icon)`},children:c?(0,$.jsx)(zA,{isMobile:t,label:h,className:`block`}):(0,$.jsx)(X,{name:`book`,className:`h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:J(`typography-meta flex-none font-medium`,PP,c&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...c?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:h}),d?(0,$.jsx)(`span`,{className:J(`typography-meta h-5 min-h-0 w-0 min-w-0 max-w-full flex-1 overflow-clip sm:h-6`,PP),style:{color:`var(--tools-description)`},children:(0,$.jsx)(uP,{text:d,active:c})}):null,(0,$.jsx)(X,{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:Ay(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]})},IP=Z.memo(e=>{let t=(0,Q.c)(18),{part:n,messageId:r,onContentChange:i,actions:a,streamPhase:o,onShowPopup:s}=e,c=K(LP),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]),Z.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)(PM,{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 LP(e){return e.chatRenderMode}var RP=e=>{let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`},zP=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,BP=J(`typography-meta font-medium`,zP),VP=J(`typography-meta`,zP),HP=[],UP=e=>{let t=e.part;return t.slim===!0&&(t.type===`tool`||t.type===`reasoning`||t.type===`file`)},WP=e=>{let t=new Set;for(let n of e)UP(n)&&n.messageId&&t.add(n.messageId);return[...t]},GP=(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}),KP=e=>{let t=(0,Q.c)(5),{href:n}=e,[r,i]=Z.useState(!1),a;t[0]===n?a=t[1]:(a=Vu(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},qP=e=>e,JP=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},YP=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},XP=e=>{let t=e.part.state?.metadata?.dir;return typeof t==`string`&&t.trim().length>0?t:null},ZP=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},QP=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=ZP(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`}`},$P=e=>{let t=e.part.state,n=t?.input,r=t?.output;if(Array.isArray(n?.todos)){let e=QP(n.todos);if(e)return e}if(Array.isArray(r)){let e=QP(r);if(e)return e}if(r&&typeof r==`object`&&Array.isArray(r.todos)){let e=QP(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=QP(e);if(t)return t}if(e&&typeof e==`object`&&Array.isArray(e.todos)){let t=QP(e.todos);if(t)return t}}catch{}return null},eF=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)},tF=(e,t=!0)=>{let n=e.lastIndexOf(`/`);if(n===-1)return(0,$.jsx)(CO,{variant:t?`generate-effect`:`static`,className:J(`min-w-0 flex-1 truncate whitespace-nowrap`,VP),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:J(`min-w-0 inline-flex max-w-full flex-1 items-baseline overflow-hidden`,VP),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)(CO,{variant:t?`generate-effect`:`static`,className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:i})]})},nF=e=>{let t=ud(e);return t?t.toLowerCase().endsWith(`/skill.md`)?t:`${t}/SKILL.md`:``},rF=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 MP(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`?$P(e):JP(e)},iF=e=>{let t=[],n=[];for(let r of e){if(r.kind!==`tool`)continue;let e=r.part,i=e.tool?.trim().toLowerCase()??``;if(i!==`task`&&i!==`subagent`)continue;let a=typeof e.id==`string`?e.id.trim():``;if(!a)continue;let o=e.state;if(!o||typeof o!=`object`)continue;let s=o;n.push(a),(s.status===`pending`||s.status===`running`)&&t.push(a)}return{active:t,all:n}},aF=Z.memo(e=>{let t=(0,Q.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=q(c),u;t[3]===i?u=t[4]:(u=ky(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)(mM,{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&&Ik([e.activity.part],[t.activity.part])),oF=Z.memo(e=>{let t=(0,Q.c)(9),{toolName:n,activities:r,isMobile:i}=e,a;t[0]===i?a=t[1]:(a=ky(i),t[0]=i,t[1]=a);let o;t[2]!==r||t[3]!==i||t[4]!==n?(o=(0,$.jsx)(lF,{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&&cF(e.activities,t.activities)),sF=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.kind===`reasoning`){if(!hD(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(ej(i)){let r=EP(e,n,e=>e.part.tool);t.push({type:`tool-context-group`,activities:r.items,hasFollowingOtherType:wP(e,r.end,e=>({kind:e.kind,toolName:e.part.tool}))}),n=r.end;continue}if(QA(i)){let r=AP(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(YA(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(JA(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(XA(i)){t.push({type:`tool-static-group`,toolName:i,activities:[r]}),n++;continue}t.push({type:`tool-fallback`,activity:r}),n++}return t},cF=(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||!Ik([r.part],[i.part]))return!1}return!0},lF=Z.memo(e=>{let t=(0,Q.c)(106),{toolName:n,activities:r,isMobile:i,animateTailText:a}=e,{t:o}=Wn(),s=K(pF),c=Gu(n,o),l;t[0]===n?l=t[1]:(l=wO(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=Z.useContext(zc),m=qc(),h=lt(mF),g=Qb(),_=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=xi(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(hF)),t[10]=C,t[11]=w);let T=w,E=r[0]??null,D=!E||nj(E.part),O;t[12]===E?O=t[13]:(O=E?rF(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||XP(E);if(!e||e===`<built-in>`){A=null;break bb0}let r=nF(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=YP(E);if(!e){M=null;break bb1}let n=pd(e,_);if(!n){M=null;break bb1}let r;t[26]===E?r=t[27]:(r=eF(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=cd(_,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(!od(n,_)){Yu(n,_).then(()=>{let e=K.getState(),r=_||sd(_,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=K.getState(),i=sd(_,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=q(P),I;t[36]!==_||t[37]!==m?(I=e=>{let t=ud(e);if(!t)return;let n=()=>{if(m){m.openFile({path:t});return}let e=K.getState(),n=_||sd(``,t);e.openContextFile(n,t)};if(_&&!od(t,_)){Yu(t,_).then(n);return}n()},t[36]=_,t[37]=m,t[38]=I):I=t[38];let L=q(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=q(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 re=q(ne),ie=ee&&U&&`cursor-pointer`,ae=ee&&!U&&`cursor-default opacity-70`,oe;t[50]!==ie||t[51]!==ae?(oe=J(`flex w-full items-center gap-x-1.5 min-w-0`,My,ie,ae),t[50]=ie,t[51]=ae,t[52]=oe):oe=t[52];let se=ee?`soft`:void 0,ce=ee?W:void 0,le=ee?re:void 0,ue=ee?`button`:void 0,de=ee&&U?0:void 0,fe=ee&&!U?!0:void 0,pe=i?`size-4`:`size-3.5`,me;t[53]===pe?me=t[54]:(me=J(`inline-flex items-center justify-center flex-shrink-0`,pe),t[53]=pe,t[54]=me);let he;t[55]===Symbol.for(`react.memo_cache_sentinel`)?(he={color:`var(--tools-icon)`},t[55]=he):he=t[55];let ge=D?(0,$.jsx)(zA,{isMobile:i,label:o(`chat.assistantStatus.usingTool`,{tool:c})}):u,_e;t[56]!==me||t[57]!==he||t[58]!==ge?(_e=(0,$.jsx)(`div`,{className:me,style:he,children:ge}),t[56]=me,t[57]=he,t[58]=ge,t[59]=_e):_e=t[59];let ve,ye;t[60]===Symbol.for(`react.memo_cache_sentinel`)?(ve=J(BP,`inline-flex items-center flex-shrink-0 opacity-85`),ye={color:`var(--tools-title)`},t[60]=ve,t[61]=ye):(ve=t[60],ye=t[61]);let be;t[62]===c?be=t[63]:(be=(0,$.jsx)(`span`,{className:ve,style:ye,title:c,children:c}),t[62]=c,t[63]=be);let xe;t[64]!==a||t[65]!==f||t[66]!==N||t[67]!==s?(xe=f&&N?(0,$.jsxs)(`span`,{className:J(`inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left`,VP),style:{color:`var(--tools-description)`},title:N.offset?`${N.displayPath}:${N.offset}`:N.displayPath,children:[s?(0,$.jsx)(Dg,{filePath:N.path,className:`h-3.5 w-3.5`}):null,tF(N.displayPath,a)]}):null,t[64]=a,t[65]=f,t[66]=N,t[67]=s,t[68]=xe):xe=t[68];let Se;t[69]!==a||t[70]!==k||t[71]!==B?(Se=B&&k?(0,$.jsx)(`span`,{className:`inline-flex min-w-0 flex-1`,children:(0,$.jsxs)(CO,{variant:a?`generate-effect`:`static`,className:J(`min-w-0 flex-1 truncate whitespace-nowrap`,VP),style:{color:`var(--tools-description)`},title:k,children:[`"`,k,`"`]})}):null,t[69]=a,t[70]=k,t[71]=B,t[72]=Se):Se=t[72];let Ce;t[73]!==k||t[74]!==V?(Ce=V&&k?(0,$.jsxs)(`a`,{href:k,target:`_blank`,rel:`noopener noreferrer`,onClick:gF,className:J(`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`,VP),style:{color:`var(--status-info)`},title:k,children:[(0,$.jsx)(KP,{href:k}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:k})]}):null,t[73]=k,t[74]=V,t[75]=Ce):Ce=t[75];let we;t[76]!==H||t[77]!==j?(we=H&&j?(0,$.jsx)(`span`,{className:J(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,VP),style:{color:`var(--tools-description)`},title:j.path,children:j.name}):null,t[76]=H,t[77]=j,t[78]=we):we=t[78];let Te;t[79]!==k||t[80]!==H||t[81]!==j?(Te=H&&!j&&k?(0,$.jsx)(`span`,{className:J(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,VP),style:{color:`var(--tools-description)`},title:k,children:k}):null,t[79]=k,t[80]=H,t[81]=j,t[82]=Te):Te=t[82];let Ee;t[83]!==a||t[84]!==k||t[85]!==V||t[86]!==f||t[87]!==B||t[88]!==H?(Ee=!f&&!B&&!V&&!H&&k?(0,$.jsx)(CO,{variant:a?`generate-effect`:`static`,className:J(`min-w-0 flex-1 truncate whitespace-nowrap`,VP),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]=Ee):Ee=t[89];let De;return t[90]!==oe||t[91]!==se||t[92]!==ce||t[93]!==le||t[94]!==ue||t[95]!==de||t[96]!==fe||t[97]!==_e||t[98]!==be||t[99]!==xe||t[100]!==Se||t[101]!==Ce||t[102]!==we||t[103]!==Te||t[104]!==Ee?(De=(0,$.jsxs)(`div`,{className:oe,"data-mobile-press-feedback":se,onClick:ce,onKeyDown:le,role:ue,tabIndex:de,"aria-disabled":fe,children:[_e,be,xe,Se,Ce,we,Te,Ee]}),t[90]=oe,t[91]=se,t[92]=ce,t[93]=le,t[94]=ue,t[95]=de,t[96]=fe,t[97]=_e,t[98]=be,t[99]=xe,t[100]=Se,t[101]=Ce,t[102]=we,t[103]=Te,t[104]=Ee,t[105]=De):De=t[105],De},(e,t)=>e.toolName===t.toolName&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&cF(e.activities,t.activities)),uF=Z.memo(e=>{let t=(0,Q.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)(KM,{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}),dF=Z.memo(e=>{let t=(0,Q.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)(IP,{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}),fF=Z.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}=Wn(),_=qu()??``,v=Z.useMemo(()=>WP(t),[t]),y=Z.useRef(new Set),b=Z.useRef(new Map),x=Z.useRef(new Set),[,S]=Z.useState(0),C=Z.useRef(null),w=Z.useRef(null),T=i===`active`,E=!T&&(i===`normal`||i===`abnormal`)&&typeof o==`number`&&Number.isFinite(o)&&o>=0?RP(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=Z.useMemo(()=>iF(e),[e]),M=T?j.active:j.all,N=M.slice(0,c?2:3),P=q((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=Ft(_,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=ln(_,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=q(e=>{e.stopPropagation(),P(!0)}),I=T,L=I||n,R=q(()=>{if(I)return;let e=C.current;w.current=e?{top:e.getBoundingClientRect().top,scrollContainer:e.closest(`[data-scrollbar="chat"]`)}:null,L||P(),s()});Z.useEffect(()=>{T||!L||P(!1,!0)},[T,L]),Z.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 Ft(_,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)&&UP(e)),ne=te&&!W&&!GP(t,V),re=Z.useMemo(()=>B?qP(e):HP,[e,B]),ie=Z.useMemo(()=>B?sF(re):[],[B,re]),ae=Z.useMemo(()=>L||z===0?0:Math.max(0,ie.length-z),[L,z,ie.length]),oe=Z.useMemo(()=>L||z===0?ie:ie.slice(-z),[L,z,ie]),se=!!m&&!(T&&!O);if((!se||I&&!O)&&ie.length===0)return null;let ce=(e,t)=>{let n=(0,$.jsx)(`div`,{className:ky(c),children:t});return(0,$.jsx)(Z.Fragment,{children:n},e)},le=B?oe.map((e,t)=>{switch(e.type){case`reasoning`:return ce(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(uF,{activity:e.activity,streamPhase:p,onContentChange:f})}));case`justification`:return ce(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(dF,{activity:e.activity,onContentChange:f,onShowPopup:d,actions:h?.(e.activity),streamPhase:p})}));case`tool-expandable`:return(0,$.jsx)(aF,{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)(oF,{toolName:e.toolName,activities:e.activities,isMobile:c},e.activities[0]?.id??`static-${e.toolName}-${t}`);case`tool-context-group`:return(0,$.jsx)(kP,{activities:e.activities,isMobile:c,isTurnLive:T,hasFollowingOtherType:e.hasFollowingOtherType,children:e.activities.map(e=>{let t=e.part,n=t.tool?.toLowerCase()??``;return ZA(n)?(0,$.jsx)(lF,{toolName:n,activities:[e],isMobile:c,animateTailText:!1},e.id):(0,$.jsx)(mM,{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)(FP,{activities:e.activities,isMobile:c,children:e.activities.map(e=>{let t=e.part;return(0,$.jsx)(lF,{toolName:t.tool?.toLowerCase()??``,activities:[e],isMobile:c,animateTailText:!1},e.id)})},e.activities[0]?.id??`skill-${t}`);case`tool-fallback`:return(0,$.jsx)(aF,{activity:e.activity,isExpanded:l.has(e.activity.id),isMobile:c,onToggleTool:u,onShowPopup:d,onContentChange:f},e.activity.id);default:return null}}):null,ue=oe.length>0;return se?(0,$.jsxs)(`div`,{className:ky(c),children:[(0,$.jsxs)(`button`,{ref:C,type:`button`,className:J(`group/tool flex w-full min-w-0 flex-nowrap items-center text-left`,c?`gap-x-1`:`gap-x-2`,!I&&My,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:J(`inline-flex min-w-0 flex-1 items-center overflow-clip`,c?`gap-x-1`:`gap-x-1.5`),children:[(0,$.jsx)(`span`,{className:J(`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)(zA,{isMobile:c,label:A,className:`block`}):(0,$.jsx)(X,{name:k,className:`h-3.5 w-3.5`})}),(0,$.jsx)(`span`,{className:J(`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:J(`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:J(`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)(es,{name:e,size:c?12:14,className:J(`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)(X,{name:L?`arrow-down-s`:`arrow-right-s`,className:J(`flex-shrink-0 text-muted-foreground opacity-70`,c&&`-mr-0.5`,c?`size-3`:`size-3.5`)})]})]}),ue?(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)`}}),ae>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:[`+`,ae,` more...`]}):null,(0,$.jsx)(`div`,{className:`flow-root`,children:le})]}):null,L&&(ee||U||ne)?(0,$.jsx)(`div`,{className:J(`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)(X,{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)(X,{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)(Jn,{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:ky(c),children:le})});function pF(e){return e.showToolFileIcons}function mF(e){return e.currentDirectory}function hF(e){return[e.name,e]}function gF(e){e.stopPropagation()}var _F=Z.memo(e=>{let t=(0,Q.c)(2),n;return t[0]===e?n=t[1]:(n=(0,$.jsx)(fF,{...e}),t[0]=e,t[1]=n),n});function vF(e){let t=(0,Q.c)(9),{presentation:n,sessionId:r,messageId:i,directory:a}=e,o;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(o={bootstrap:!1},t[0]=o):o=t[0];let s=Nr(a,o),c;t[1]===r?c=t[2]:(c=e=>!!e.session_execution_recovery[r],t[1]=r,t[2]=c);let l=Ge(s,c),u;t[3]===r?u=t[4]:(u=e=>e.session_status[r]?.type===`retry`,t[3]=r,t[4]=u);let d=Ge(s,u),f=ma(r,a);if(!l&&!d){let e;return t[5]===n?e=t[6]:(e=(0,$.jsx)(dy,{presentation:n}),t[5]=n,t[6]=e),e}let p;for(let e=f.length-1;e>=0;--e)if(f[e].role===`assistant`){p=f[e].id;break}if(p===i&&(d||l&&n.detail===`aborted`&&n.icon===`pause-circle`))return null;let m;return t[7]===n?m=t[8]:(m=(0,$.jsx)(dy,{presentation:n}),t[7]=n,t[8]=m),m}function yF(e){let t=(0,Q.c)(5),n=Qb();if(!e.sessionId||!n.active||!n.capabilities.compose){let n;return t[0]===e.presentation?n=t[1]:(n=(0,$.jsx)(dy,{presentation:e.presentation}),t[0]=e.presentation,t[1]=n),n}let r=n.directory??e.directory,i;return t[2]!==e||t[3]!==r?(i=(0,$.jsx)(vF,{...e,sessionId:e.sessionId,directory:r}),t[2]=e,t[3]=r,t[4]=i):i=t[4],i}var bF={contain:`layout`},xF={containerType:`inline-size`,containerName:`message-footer`},SF=`mt-1.5 mb-0.5 flex items-center justify-start gap-1.5`,CF=`mt-3 mb-0.5 flex items-center justify-start gap-1.5`,wF=`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`,TF=`size-3.5!`,EF=`mt-1.5 mb-0.5 flex flex-wrap items-center gap-3`,DF=`mt-3 mb-0.5 flex flex-wrap items-center gap-3 -ml-[5px]`,OF=`flex items-center gap-2`,kF=`flex items-center gap-2 text-muted-foreground`,AF=`inline-flex h-3.5 items-center gap-1 text-[11px] leading-none tabular-nums text-muted-foreground`,jF=`size-3.5!`,MF=`medium`,NF=e=>{let t=(0,Q.c)(16),{label:n}=e,{t:r}=Wn(),i;t[0]!==n||t[1]!==r?(i=r(`chat.messageBody.meta.tpsAria`,{rate:n}),t[0]=n,t[1]=r,t[2]=i):i=t[2];let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(X,{weight:MF,name:`pulse`,className:jF}),t[3]=a):a=t[3];let o;t[4]===n?o=t[5]:(o=(0,$.jsx)(`span`,{className:`message-footer__label`,children:n}),t[4]=n,t[5]=o);let s;t[6]!==i||t[7]!==o?(s=(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsxs)(`span`,{className:AF,"aria-label":i,children:[a,o]})}),t[6]=i,t[7]=o,t[8]=s):s=t[8];let c;t[9]===r?c=t[10]:(c=r(`chat.messageBody.meta.tpsTooltip`),t[9]=r,t[10]=c);let l;t[11]===c?l=t[12]:(l=(0,$.jsx)(Ds,{children:c}),t[11]=c,t[12]=l);let u;return t[13]!==s||t[14]!==l?(u=(0,$.jsxs)(Os,{children:[s,l]}),t[13]=s,t[14]=l,t[15]=u):u=t[15],u},PF=e=>e.replace(/\\/g,`/`).split(`/`).filter(Boolean).at(-1)??e,FF=`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)]`,IF=`h-7 gap-1.5`,LF=`h-6 gap-1`,RF=`text-[11px] leading-none`,zF=`size-3.5`,BF=`size-3`,VF=5,HF=Z.memo(e=>{let t=(0,Q.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=J(`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=J(`flex-shrink-0`,s),t[2]=s,t[3]=c);let l;t[4]!==n.file||t[5]!==c?(l=(0,$.jsx)(Dg,{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=PF(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=J(`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}),UF=Z.memo(e=>{let t=(0,Q.c)(18),{file:n,canOpen:r,isMobile:i,onOpen:a}=e,{t:o}=Wn(),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=q(s),l=!r,u=i?LF:IF,d;t[3]===u?d=t[4]:(d=J(FF,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)(HF,{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)(Jn,{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}),WF=Z.memo(e=>{let t=(0,Q.c)(53),{fileCount:n,changedFiles:r,turnId:i,isLatestTurn:a,isMobile:o}=e,{t:s}=Wn(),c=qu(),l=Qb(),u=l.directory||c,d=l.sessionId,f=qc(),p=K(rI),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,VF),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=J(FF,o?LF:IF),E=o?BF:zF,D;t[10]===o?D=t[11]:(D=o?J(RF,`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?J(RF,`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?J(RF,`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){YM({directory:u,filePath:e,turnMessageId:i,sessionId:d});return}o&&a&&u&&YM({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=q(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&&YM({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=q(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=J(`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=J(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)(X,{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=J(E,`opacity-60`),t[49]=E,t[50]=ne);let re;return t[51]===ne?re=t[52]:(re=(0,$.jsx)(X,{name:`arrow-right-s`,className:ne}),t[51]=ne,t[52]=re),(0,$.jsxs)(`section`,{className:R,"data-turn-changes-preview":`true`,"data-message-action-group":`true`,"aria-labelledby":`turn-changes-${i}`,children:[(0,$.jsxs)(Jn,{type:`button`,variant:`ghost`,size:`xs`,disabled:!b,onClick:I,className:z,"aria-label":B,title:V,children:[H,te,W,re]}),_.length>0?(0,$.jsxs)(`div`,{className:J(`flex min-w-0 flex-col`,o?`gap-0`:`gap-0.5`),children:[_.map(e=>(0,$.jsx)(UF,{file:e,canOpen:b,isMobile:o,onOpen:P},e.file)),v>0?(0,$.jsxs)(Jn,{type:`button`,variant:`ghost`,size:`xs`,disabled:!b,className:J(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:J(E,`flex-shrink-0`)}),(0,$.jsxs)(`span`,{className:M,children:[`+`,w]}),(0,$.jsx)(X,{name:`arrow-right-s`,className:E})]}):null]}):null]})}),GF=e=>e.type===`subtask`,KF=e=>{let t=e;return t.type===`text`&&typeof t.shellAction==`object`&&t.shellAction!==null},qF=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}`},JF=e=>{let t=(0,Q.c)(49),{part:n}=e,[r,i]=Z.useState(!1),a=qu(),{isMobile:o}=Oc(),s=Y(iI),c=K(aI),l=Qb(),{t:u}=Wn(),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=qF(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(oI),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&&ex(l,b,e,()=>{if(!La({sessionId:b,directory:e})){if(Cp()||o||fe()){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},YF=e=>{let t=(0,Q.c)(34),{notification:n}=e,r=qu(),i=K(sI),{isMobile:a}=Oc(),{t:o}=Wn(),s;t[0]!==r||t[1]!==a?(s=r&&!a&&!fe(),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=q(()=>{!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=q(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]:(_=J(`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)(X,{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=J(`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)(Su,{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},XF={background:`transparent`,backgroundColor:`transparent`},ZF=e=>{let t=(0,Q.c)(37),{part:n}=e,[r,i]=Z.useState(!1),a=Z.useRef(null),{t:o}=Wn(),s;t[0]===n.shellAction?s=t[1]:(s=typeof n.shellAction?.command==`string`?n.shellAction.command.trim():``,t[0]=n.shellAction,t[1]=s);let c=s,l=typeof n.shellAction?.output==`string`?n.shellAction.output:``,u;t[2]===n.shellAction?u=t[3]:(u=typeof n.shellAction?.status==`string`?n.shellAction.status.trim().toLowerCase():``,t[2]=n.shellAction,t[3]=u);let d=u,f=l.length>0,p;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(p=()=>{a.current!==null&&typeof window<`u`&&(window.clearTimeout(a.current),a.current=null)},t[4]=p):p=t[4];let m=q(p),h,g;t[5]===m?(h=t[6],g=t[7]):(h=()=>()=>{m()},g=[m],t[5]=m,t[6]=h,t[7]=g),Z.useEffect(h,g);let _;t[8]!==m||t[9]!==f||t[10]!==l?(_=async()=>{f&&(await Un(l)).ok&&(m(),i(!0),typeof window<`u`&&(a.current=window.setTimeout(()=>{i(!1),a.current=null},2e3)))},t[8]=m,t[9]=f,t[10]=l,t[11]=_):_=t[11];let v=q(_),y;t[12]===o?y=t[13]:(y=o(`chat.messageBody.shellCommand.title`),t[12]=o,t[13]=y);let b;t[14]===y?b=t[15]:(b=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:y}),t[14]=y,t[15]=b);let x;t[16]!==d||t[17]!==o?(x=d&&d!==`completed`?(0,$.jsx)(`span`,{className:J(`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none`,d===`error`?`bg-[var(--status-error-background)] text-[var(--status-error)]`:`bg-foreground/5 text-muted-foreground`),role:d===`error`?`alert`:`status`,children:d===`running`?o(`chat.assistantStatus.runningCommand`):d===`pending`?o(`chat.statusRow.todo.status.pending`):d===`error`?o(`chat.toolPart.error`):d}):null,t[16]=d,t[17]=o,t[18]=x):x=t[18];let S;t[19]!==r||t[20]!==v||t[21]!==f||t[22]!==o?(S=f?(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`xs`,className:`ml-auto text-muted-foreground`,onClick:()=>{v()},"aria-label":o(r?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),title:o(r?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),children:(0,$.jsx)(X,{name:r?`check`:`file-copy`,className:`h-3.5 w-3.5`})}):null,t[19]=r,t[20]=v,t[21]=f,t[22]=o,t[23]=S):S=t[23];let C;t[24]!==S||t[25]!==b||t[26]!==x?(C=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[b,x,S]}),t[24]=S,t[25]=b,t[26]=x,t[27]=C):C=t[27];let w;t[28]===c?w=t[29]:(w=c?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 overflow-x-auto font-mono`,children:(0,$.jsx)(Td,{language:`bash`,code:c,codeStyle:XF,wrap:!0})}):null,t[28]=c,t[29]=w);let T;t[30]!==f||t[31]!==l?(T=f?(0,$.jsx)(`div`,{className:`mt-2 border-t border-border/60 pt-1.5`,children:(0,$.jsx)(`pre`,{className:`typography-meta max-h-56 overflow-auto whitespace-pre-wrap break-words font-mono text-foreground/85`,tabIndex:0,children:l})}):null,t[30]=f,t[31]=l,t[32]=T):T=t[32];let E;return t[33]!==C||t[34]!==w||t[35]!==T?(E=(0,$.jsxs)(`div`,{className:`min-w-0 rounded-lg border border-border/60 bg-[var(--surface-elevated)] px-3 py-2`,children:[C,w,T]}),t[33]=C,t[34]=w,t[35]=T,t[36]=E):E=t[36],E},QF=e=>{let t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`},$F=Z.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}=Wn(),w=Ix(),T=$b(Qb()),E=K(e=>e.timeFormatPreference),[D,O]=Z.useState(!1),k=Z.useRef(null),A=Z.useMemo(()=>n.filter(e=>e.type===`text`?!gD(e):!!(GF(e)||KF(e))),[n]),j=Z.useMemo(()=>A.map(e=>gi(e)?JO(hD(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=q(()=>{k.current!==null&&typeof window<`u`&&(window.clearTimeout(k.current),k.current=null)}),H=q(()=>{!I||!P||!L||typeof window>`u`||(V(),O(!0),k.current=window.setTimeout(()=>{O(!1),k.current=null},1800))});Z.useEffect(()=>{L||(O(!1),V())},[V,L]);let ee=q(e=>{!l||!L||(e.stopPropagation(),e.preventDefault(),l(),I&&H())}),U=w===`mini-chat`||!T.fork?void 0:h,te=Z.useMemo(()=>{if(typeof i!=`number`||i<=0)return null;let e=iP(i,E);return e.length>0?e:null},[S,i,E]),W=J(`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:J(OF,`justify-end`,!a&&b===`inline`&&`translate-x-5`,`pointer-events-auto opacity-100`),"data-message-action-group":`true`,children:[(0,$.jsxs)(`span`,{className:J(AF,`text-primary`),"aria-live":`polite`,children:[(0,$.jsx)(X,{weight:MF,name:`edit`,className:jF}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:C(`chat.messageBody.actions.editStaged`)})]}),y?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"aria-label":C(`chat.messageBody.actions.cancelEdit`),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),y()},children:(0,$.jsx)(X,{weight:MF,name:`close`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:C(`chat.messageBody.actions.cancelEdit`)})]}):null]})}):null,re=(_&&z?(0,$.jsx)(`div`,{className:W,children:(0,$.jsx)(`div`,{className:J(OF,`justify-end`,!a&&b===`inline`&&`translate-x-5`,`pointer-events-none opacity-100`),children:(0,$.jsx)(`span`,{className:J(AF,`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:J(OF,`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)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsxs)(`span`,{className:J(AF,`mr-1`),"aria-label":`Message time: ${te}`,children:[(0,$.jsx)(X,{weight:MF,name:`time`,className:jF}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:te})]})}),(0,$.jsx)(Ds,{children:te})]}):null,m&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"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)(X,{weight:MF,name:g===`revert`?`loader-4`:`arrow-go-back`,className:J(TF,g===`revert`&&`animate-spin`)})})}),(0,$.jsx)(Ds,{sideOffset:6,children:C(`chat.messageBody.actions.revert`)})]}),p&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"aria-label":C(`chat.messageBody.actions.editAria`),disabled:!!g,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),p()},children:(0,$.jsx)(X,{weight:MF,name:`edit`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:C(`chat.messageBody.actions.edit`)})]}),U&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"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)(X,{weight:MF,name:g===`fork`?`loader-4`:`git-branch`,className:J(TF,g===`fork`&&`animate-spin`)})})}),(0,$.jsx)(Ds,{sideOffset:6,children:C(`chat.messageBody.actions.fork`)})]}),P&&L&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":D||F?`true`:void 0,className:wF,"aria-label":C(`chat.messageBody.actions.copyMessageAria`),onPointerDown:e=>e.stopPropagation(),onClick:ee,onFocus:()=>O(!0),onBlur:()=>{F||O(!1)},children:F?(0,$.jsx)(X,{weight:MF,name:`check`,className:J(TF,`text-[color:var(--status-success)]`)}):(0,$.jsx)(X,{weight:MF,name:`file-copy`,className:TF})})}),(0,$.jsx)(Ds,{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:bF,onTouchStart:I&&P&&L?H:void 0,children:[(0,$.jsx)(`div`,{className:J(`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(GF(e))return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(JF,{part:e})},e.id??`user-subtask-${i}`);if(KF(e))return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(ZF,{part:e})},e.id??`user-shell-${i}`);let o=j[i];if(o)return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(YF,{notification:o})},e.id??`subagent-notification-${i}`);let s;return f&&M&&!N&&hD(e).includes(M)&&(s=f,N=!0),(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(xO,{part:e,messageId:t,isMobile:a,agentMention:s,messageParts:r??n})},e.id??`user-text-${i}`)})}),(0,$.jsx)($g,{files:n,messageID:t,sessionID:e,onShowPopup:d,compact:!0}),re]}):(0,$.jsx)($.Fragment,{children:re})}),eI=Z.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,reviewTransferAction:r,ttsText:i,sessionId:a})=>{let{t:o}=Wn(),s=Ix(),c=Qb(),l=$b(c),{isPlaying:u,play:d,stop:f}=DN(),p=ao(e=>e.showMessageTTSButtons),m=ao(e=>e.voiceProvider),[h,g]=Z.useState(!1),[_,v]=Z.useState(!1),[y,b]=Z.useState(!1),x=Z.useRef(null),S=Z.useRef(null),C=!!n,w=!!((c.sessionId||a)&&c.directory&&l.openSourceSession&&s!==`mini-chat`),T=q(()=>{x.current!==null&&typeof window<`u`&&(window.clearTimeout(x.current),x.current=null)}),E=q(()=>{S.current!==null&&typeof window<`u`&&(window.clearTimeout(S.current),S.current=null)});Z.useEffect(()=>()=>{T(),E()},[E,T]),Z.useEffect(()=>{(!e||!C)&&(g(!1),v(!1),T(),E())},[C,E,T,e]);let D=q(()=>{!t||!C||!e||typeof window>`u`||(T(),g(!0),x.current=window.setTimeout(()=>{g(!1),x.current=null},1800))}),O=q(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=q(async t=>{if(t.stopPropagation(),t.preventDefault(),!(!r||y||!e)){b(!0);try{await r.onClick()}finally{b(!1)}}}),A=q(e=>{e.stopPropagation(),e.preventDefault();let t=c.sessionId||a;!t||!c.directory||!c.openSourceSession||c.openSourceSession(t,c.directory)}),j=Z.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=q(e=>{if(e.stopPropagation(),e.preventDefault(),u){f();return}i.trim()&&d(i)});return(0,$.jsxs)($.Fragment,{children:[n&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":h||_?`true`:void 0,className:J(wF,!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)(X,{weight:MF,name:`check`,className:J(TF,`text-[color:var(--status-success)]`)}):(0,$.jsx)(X,{weight:MF,name:`file-copy`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:o(`chat.messageBody.actions.copyAnswer`)})]}),w?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"aria-label":o(`chat.messageBody.actions.openSourceSessionAria`),onPointerDown:e=>e.stopPropagation(),onClick:A,children:(0,$.jsx)(X,{weight:MF,name:`target`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:o(`chat.messageBody.actions.openSourceSession`)})]}):null,r&&s!==`mini-chat`&&l.reviewTransfer?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,size:`icon`,variant:`ghost`,disabled:y||!e,className:J(wF,(!e||y)&&`opacity-50`),"aria-label":r.ariaLabel,onPointerDown:e=>e.stopPropagation(),onClick:e=>{k(e)},children:y?(0,$.jsx)(X,{weight:MF,name:`loader-4`,className:J(TF,`animate-spin`)}):(0,$.jsx)(X,{weight:MF,name:`arrow-left-right`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:r.tooltip})]}):null,s!==`mini-chat`&&p&&e&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:J(wF,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)(X,{weight:MF,name:`stop`,className:TF}):(0,$.jsx)(X,{weight:MF,name:`volume-up`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:j})]})]})}),tI=Z.memo(({sessionId:e,messageId:t,parts:n,isMessageCompleted:r,messageFinish:i,messageCompletedAt:a,messageCreatedAt:o,isMobile:s,alwaysShowActions:c,hasTouchInput:l,expandedTools:u,onToggleTool:d,onShowPopup:f,streamPhase:p,allowAnimation:m,onContentChange:h,hasTextContent:g=!1,onCopyMessage:_,onAuxiliaryContentComplete:v,showReasoningTraces:y=!1,turnGroupingContext:b,errorPresentation:x,reviewTransferDirection:S=null})=>{let C=x?.text,{t:w,locale:T}=Wn(),E=Ix(),D=$b(Qb()),O=p,k=Z.useRef(null),A=Z.useRef(null),j=p===`streaming`||p===`cooldown`,M=Z.useRef({messageId:t,experiencedStreamingOrCooldown:j});M.current.messageId===t?j&&(M.current.experiencedStreamingOrCooldown=!0):M.current={messageId:t,experiencedStreamingOrCooldown:j};let N=!!(l??s),P=!!(c??s),F=s?DF:EF,I=!r,L=Z.useMemo(()=>n.filter(e=>!gD(e)).filter(e=>e.type!==`compaction`),[n]),R=Z.useMemo(()=>L.filter(e=>e.type===`tool`),[L]),z=Z.useMemo(()=>L.filter(e=>e.type===`text`),[L]),B=Z.useMemo(()=>xo(z),[z]),V=K(e=>e.openContextPreview),H=fe(),ee=E===`mini-chat`,U=Z.useMemo(()=>{if(H||s||ee)return null;for(let e of z){let t=e.text;if(typeof t!=`string`||t.length===0)continue;let n=Hu(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 R){let t=e.state,n=t&&typeof t.output==`string`?t.output:null;if(!n)continue;let r=Hu(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},[z,s,ee,H,R]),te=Y(e=>e.forkFromMessage),W=Y(e=>e.forkTransition),ne=Y(e=>e.currentSessionId),re=Y(e=>e.getDirectoryForSession),ie=qu(),ae=S===`review-to-original`,oe=!s&&!H?S:null,se=Z.useMemo(()=>{let t=B.trim();if(!(!e||!ie||!t||!oe))return oe===`review-to-original`?{ariaLabel:w(`chat.messageBody.actions.sendReviewFeedback`),tooltip:w(`chat.messageBody.actions.sendReviewFeedback`),onClick:async()=>{try{await Hi(e,ie,t)}catch(e){console.error(`[review-flow] failed to send review feedback`,e)}}}:{ariaLabel:w(`chat.messageBody.actions.sendImplementationResponse`),tooltip:w(`chat.messageBody.actions.sendImplementationResponse`),onClick:async()=>{try{await Ii(e,ie,t)}catch(e){console.error(`[review-flow] failed to send implementation response`,e)}}}},[B,ie,oe,e,w]),[ce,le]=Z.useState(!1),ue=K(e=>e.chatRenderMode),de=b?ue:`live`,pe=K(e=>e.collapsibleThinkingBlocks),me=K(e=>e.showSplitAssistantMessageActions),he=K(e=>e.showAssistantTps),ge=K(e=>e.timeFormatPreference),_e=de===`sorted`,ve=b?.isLastAssistantInTurn??!1,ye=i===`stop`,be=(ye||r||!!C)&&(b?.isTurnSettled??!0),xe=ye?`completed`:O,Se=R.length>0,Ce=Z.useMemo(()=>R.some(e=>nj(e)),[R]),we=nj,Te=tj,Ee=M.current.experiencedStreamingOrCooldown,De=Z.useRef({messageId:t,initialized:!1,observedPartIds:new Set});Z.useEffect(()=>{if(De.current.messageId!==t&&(De.current={messageId:t,initialized:!1,observedPartIds:new Set}),!Ee||!Go())return;let n=De.current,r=!n.initialized;n.initialized=!0;for(let i of R){if(n.observedPartIds.has(i.id))continue;if(!sr(r,we(i))){n.observedPartIds.add(i.id);continue}let a=e??i.sessionID;a&&(n.observedPartIds.add(i.id),Xr({sessionID:a,messageID:t,partID:i.id,kind:`tool`}))}},[Ee,we,t,e,R]);let Oe=Z.useMemo(()=>R.length===0||!Ce&&R.every(e=>Te(e)),[R,Ce,Te]),ke=Z.useMemo(()=>L.filter(e=>e.type===`reasoning`),[L]),Ae=Z.useMemo(()=>ke.length===0||ke.every(e=>typeof e.time?.end==`number`),[ke]),je=typeof i!=`string`,Me=ke.length>0&&Se&&(Ce||je||!Oe),Ne=I||Se&&(Ce||je||!Oe),Pe=I||Me,Fe=Se||ke.length>0,Ie=z.length===0,Le=Fe&&Ie&&!Ne&&!Pe&&Oe&&Ae,Re=Z.useRef(!1),ze=Z.useRef(!1);Z.useEffect(()=>{ze.current=!1},[t]),Z.useEffect(()=>{if(!Le){Re.current=!1;return}Re.current||(Re.current=!0,v?.())},[Le,v]),Z.useEffect(()=>{if(I){ze.current=!1;return}if(Se){ze.current=!1;return}ke.length!==0&&(Pe||!Ae||ze.current||(ze.current=!0,h?.(`structural`)))},[I,Se,h,Ae,ke.length,Pe]);let Be=!!g&&!I,Ve=q(async n=>{if(n.stopPropagation(),n.preventDefault(),!(!e||!t||ce||W)){le(!0);try{await te(e,t)}finally{le(!1)}}}),He=Z.useMemo(()=>{let e=b?.activityParts;return!_e||!e?[]:e},[_e,b?.activityParts]),Ue=Z.useMemo(()=>{let e=b?.activityGroupSegments;return!_e||!e?[]:e.filter(e=>e.anchorMessageId===t)},[_e,t,b?.activityGroupSegments]),We=Ue.length>0,Ge=Z.useMemo(()=>{let e=new Map,t=new Map;return He.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)}}},[He]),Ke=b?.toggleGroup,qe=b?.activityPresentationKind===`compaction`,Je=b?.isGroupExpanded===!0,Ye=_e&&qe&&!Je,Xe=_e?b?.activityOwnerMessageId===t||We:!b?.activityOwnerMessageId||b.activityOwnerMessageId===t||We,Ze=_e&&Xe&&(We||qe)&&!!Ke,Qe=nN(i,L),$e={finish:i,parts:L,streamPhase:xe,error:C,isLastAssistantInTurn:ve},et=sN($e),tt=_e&&cN($e),nt=_e&&!et&&!(qe&&Je),rt=Be,it=ve&&be&&x?.variant!==`error`&&!Ye&&(g||!!C||r),at=b?.diffStats?.hasDiffs===!0,ot=!ee&&ve&&Qe&&be&&!Ye&&b?.diffStats?.hasDiffs===!0,st=me&&rt&&!it&&!_e,ct=Z.useMemo(()=>(0,$.jsx)(eI,{hasCopyableText:Be,isTouchContext:N,onCopyMessage:_,ttsText:B,reviewTransferAction:se,sessionId:e}),[B,Be,N,_,se,e]),lt=Z.useMemo(()=>e=>{if(!me||!_e)return null;let t=hD(e.part).trim();return t?(0,$.jsx)(eI,{hasCopyableText:!0,isTouchContext:N,onCopyMessage:async()=>(await Un(t)).ok,ttsText:t}):null},[_e,N,me]),ut=Z.useMemo(()=>{if(!st)return-1;let e=-1;for(let t=0;t<L.length;t+=1){let n=L[t];!n||n.type!==`text`||nt||Ge.get(n)?.kind!==`justification`&&(e=t)}return e},[Ge,nt,st,L]),dt=st&&ut<0,ft=Z.useMemo(()=>{let n=[];if(Ze&&Ke&&b){let e=(e,t,r=t)=>{n.push((0,$.jsx)(`div`,{children:(0,$.jsx)(_F,{parts:t,materializationParts:r,isExpanded:b.isGroupExpanded===!0,collapsedPreviewCount:0,completionDisposition:b.completionDisposition,activityPresentationKind:b.activityPresentationKind,durationMs:b.durationMs,startedAt:b.userMessageCreatedAt,onToggle:Ke,isMobile:s,expandedTools:u,onToggleTool:d,onShowPopup:f,onContentChange:h,streamPhase:xe,showHeader:!0,diffStats:b.diffStats,renderJustificationActions:lt})},`progressive-group-${e}`))};Ue.length>0?Ue.forEach(t=>{let n=y?t.parts:t.parts.filter(e=>e.kind!==`reasoning`);e(t.id,n,t.parts)}):qe&&e(`${t}:compaction-status`,[])}let r=0;for(;r<L.length;){let i=L[r];if(i.type===`text`){let a=Ge.get(i);if(nt){r+=1;continue}if(Ye){r+=1;continue}if(a?.kind===`justification`){r+=1;continue}n.push((0,$.jsx)(`div`,{ref:A,"data-message-text-export-source":`true`,children:(0,$.jsx)(PM,{part:i,sessionId:e,messageId:t,streamPhase:xe,chatRenderMode:de,allowSortedFinalStreaming:tt,hasStreamingHapticLifecycle:Ee,onContentChange:h,onShowPopup:f})},`assistant-text-${t}-${i.id??r}`)),st&&r===ut&&n.push((0,$.jsx)(`div`,{className:s?CF:SF,"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:OF,"data-message-action-group":`true`,children:ct})},`message-actions-${t}`)),r++;continue}if(i.type===`reasoning`){if(Ge.get(i)?.kind===`reasoning`){r+=1;continue}if(!hD(i).trim()){r+=1;continue}y&&(pe?n.push((0,$.jsx)(`div`,{className:ky(s),children:(0,$.jsx)(KM,{part:i,messageId:t,streamPhase:xe,onContentChange:h})},`reasoning-${t}-${i.id??r}`)):n.push((0,$.jsx)(PM,{part:i,sessionId:e,messageId:t,streamPhase:xe,chatRenderMode:de,hasStreamingHapticLifecycle:Ee,onContentChange:h,onShowPopup:f},`reasoning-${t}-${i.id??r}`))),r++;continue}if(i.type===`tool`){let e=i,a=e.tool?.toLowerCase()??``;if(_e&&!Xe){r+=1;continue}if(Ge.get(i)?.kind===`tool`){r+=1;continue}if(ej(a)){let e=EP(L,r,e=>e.type!==`tool`||Ge.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)(kP,{activities:i,isMobile:s,isTurnLive:xe!==`completed`,hasFollowingOtherType:wP(L,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 ZA(n)?(0,$.jsx)(lF,{toolName:n,activities:[e],isMobile:s,animateTailText:!1},e.id):(0,$.jsx)(mM,{part:e.part,messageId:t,isExpanded:u.has(e.part.id),onToggle:d,isMobile:s,alwaysShowActions:P,onContentChange:h,onShowPopup:f,animateTailText:!1},e.id)})},`context-tools-${i[0].id}`)),r=e.end;continue}}if(QA(a)){let e=AP(L,r,e=>e.type!==`tool`||Ge.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)(FP,{activities:i,isMobile:s,children:i.map(e=>(0,$.jsx)(lF,{toolName:e.part.tool?.toLowerCase()??``,activities:[e],isMobile:s,animateTailText:!1},e.id))},`skill-tools-${i[0].id}`)),r=e.end;continue}}if(JA(a)){n.push((0,$.jsx)(`div`,{className:ky(s),children:(0,$.jsx)(mM,{part:e,messageId:t,isExpanded:u.has(e.id),onToggle:d,isMobile:s,alwaysShowActions:P,onContentChange:h,onShowPopup:f,animateTailText:!1})},`tool-${e.id}`)),r++;continue}n.push((0,$.jsx)(`div`,{className:ky(s),children:(0,$.jsx)(lF,{toolName:a,activities:[{id:e.id,turnId:``,messageId:t,partIndex:r,part:e,kind:`tool`}],isMobile:s,animateTailText:!1})},`static-tools-${e.id}`)),r++;continue}r++}let i=n.at(-1);if(Z.isValidElement(i)&&i.props[`data-message-text-export-source`]===`true`&&xe!==`completed`&&!be&&!x&&(!b||b.isLastAssistantInTurn)){let e=i;n[n.length-1]=Z.cloneElement(e,{className:J(typeof e.props.className==`string`?e.props.className:void 0,s?`pb-1`:`pb-1.5`),"data-live-status-text-gap":``})}return n},[Ge,Ue,P,de,pe,0,u,Ye,qe,s,Xe,_e,ut,t,ct,lt,e,h,f,d,Ze,st,xe,x,Ee,be,y,nt,tt,Ke,b,L]),pt=Z.useMemo(()=>{if(!ve||!be)return;let e=b?.durationMs;if(!(typeof e!=`number`||e<=0))return QF(e)},[ve,be,b?.durationMs]),mt=Z.useMemo(()=>{let e=typeof a==`number`&&a>0?a:typeof o==`number`&&o>0?o:null;if(e===null)return null;let t=iP(e,ge);return t.length>0?t:null},[a,o,ge,T]),ht=Z.useMemo(()=>{if(!he||!ve||x?.variant===`error`)return null;let e=b?.assistantTps;if(!cP({completionDisposition:b?.completionDisposition,tps:e}))return null;let t=lP(e??0);return t.length>0?t:null},[he,x?.variant,ve,b?.assistantTps,b?.completionDisposition]),gt=(0,$.jsxs)($.Fragment,{children:[!ee&&!s&&!H&&U?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"aria-label":w(`chat.messageBody.actions.openPreviewAria`),onPointerDown:e=>e.stopPropagation(),onClick:()=>{let e=ie??(ne?re(ne):null);e&&V(e,U)},children:(0,$.jsx)(X,{weight:MF,name:`global`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:w(`chat.messageBody.actions.openPreview`)})]}):null,!ee&&!ae&&D.fork?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,size:`icon`,variant:`ghost`,className:wF,"aria-label":w(`chat.messageBody.actions.forkAria`),"aria-busy":ce,disabled:ce||!!W,onPointerDown:e=>e.stopPropagation(),onClick:e=>{Ve(e)},children:(0,$.jsx)(X,{weight:MF,name:ce?`loader-4`:`git-branch`,className:J(TF,ce&&`animate-spin`)})})}),(0,$.jsx)(Ds,{sideOffset:6,children:w(`chat.messageBody.actions.fork`)})]}):null]});return(0,$.jsxs)(`div`,{ref:k,"data-message-text-export-root":`true`,className:J(`relative w-full group/message`),style:bF,children:[(0,$.jsx)(eP,{containerRef:k}),(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:[ft,x&&(0,$.jsx)(td,{children:(0,$.jsx)(`div`,{className:`my-1.5`,"data-assistant-error":x.variant,children:(0,$.jsx)(yF,{presentation:x,sessionId:e,messageId:t,directory:ie??void 0})})},`assistant-error`)]}),ot&&b?.diffStats?(0,$.jsx)(WF,{fileCount:b.diffStats.files,changedFiles:b.changedFiles,turnId:b.turnId,isLatestTurn:b.isLatestTurn,isMobile:s}):null,(0,$.jsx)($g,{files:n,messageID:t,sessionID:e,onShowPopup:f}),dt&&(0,$.jsx)(`div`,{className:J(s?CF:SF),"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:OF,"data-message-action-group":`true`,children:ct})}),it&&(0,$.jsxs)(`div`,{className:F,"data-message-footer":`true`,style:xF,children:[(0,$.jsxs)(`div`,{className:OF,"data-message-action-group":`true`,children:[ct,gt]}),ht||pt||mt?(0,$.jsxs)(`div`,{className:kF,children:[ht?(0,$.jsx)(NF,{label:ht}):null,pt?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsxs)(`span`,{className:AF,children:[(0,$.jsx)(X,{weight:MF,name:`hourglass`,className:jF}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:pt})]})}),(0,$.jsx)(Ds,{children:pt})]}):null,mt?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsxs)(`span`,{className:AF,"aria-label":`Message time: ${mt}`,children:[(0,$.jsx)(X,{weight:MF,name:`time`,className:jF}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:mt})]})}),(0,$.jsx)(Ds,{children:mt})]}):null]}):null,!ee&&ve&&ye&&!at?(0,$.jsx)(XM,{activityParts:b?.activityParts}):null]}),!it&&!Ye&&ht?(0,$.jsx)(`div`,{className:F,"data-message-footer":`true`,"data-message-tps":`interrupted`,style:xF,children:(0,$.jsx)(`div`,{className:kF,children:(0,$.jsx)(NF,{label:ht})})}):null]})]})}),nI=Z.memo(e=>{let t=(0,Q.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)($F,{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)(tI,{...r}),t[26]=r,t[27]=i),i});function rI(e){return e.openContextPanelTab}function iI(e){return e.setCurrentSession}function aI(e){return e.openContextPanelTab}function oI(e){return!e}function sI(e){return e.openContextPanelTab}var cI=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}},lI=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},uI={"provider.rate-limit":`chat.response.rateLimit`,"provider.auth":`chat.response.auth`,"provider.quota":`chat.response.quota`,"provider.content-filter":`chat.response.contentFilter`,"provider.transport":`chat.response.transport`,"provider.internal":`chat.response.internal`,"provider.invalid-output":`chat.response.invalidOutput`,"provider.invalid-request":`chat.response.invalidRequest`,"provider.unsupported-operation":`chat.response.unsupportedOperation`,"provider.no-route":`chat.response.noRoute`,"provider.unknown":`chat.response.providerUnknown`,"provider.timeout":`chat.response.timeout`,"permission.rejected":`chat.response.permissionRejected`,"tool.execution":`chat.response.toolExecution`,"compaction.failed":`chat.response.compactionFailed`,"compaction.unavailable":`chat.response.compactionUnavailable`,"compaction.interrupted":`chat.response.compactionInterrupted`},dI={icon:`pause-circle`,variant:`muted`};function fI(e,t){if(!e||typeof e!=`object`)return;let n=e,r=typeof n.data?.message==`string`?n.data.message:typeof n.message==`string`?n.message:void 0,i=typeof n.name==`string`?n.name:void 0,a=typeof n.type==`string`?n.type.trim():void 0,o=typeof n.status==`number`&&Number.isInteger(n.status)&&n.status>=100&&n.status<=599?n.status:void 0;if(!r&&!a&&!i&&o===void 0)return;let s=[a&&a!==`unknown`&&a!==`error`?a:void 0,o].filter(e=>e!==void 0).join(` · `)||void 0,c=(e,n,i=`error`,a=!1)=>({text:t(e),icon:n,variant:i,...r&&!a?{rawMessage:r}:{},...s?{detail:s}:{}});if(i===`SessionRetry`)return c(`chat.response.retrying`,`refresh`,`info`);if(a===`aborted`)return r===`Execution was interrupted repeatedly and will not be resumed automatically.`?c(`chat.response.resumeExhausted`,`error-warning`,`error`,!0):r===`Session interrupted by user`?c(`chat.response.stopped`,`stop-circle`,`muted`,!0):r===`Compaction cancelled`?c(`chat.response.compactionCancelled`,`stop-circle`,`muted`,!0):r===`Tool execution interrupted`?c(`chat.response.toolInterrupted`,dI.icon,dI.variant,!0):c(`chat.response.interrupted`,dI.icon,dI.variant,r===`Step interrupted`);if(i===`MessageAbortedError`||!a&&r?.trim().toLowerCase()===`aborted`)return c(`chat.response.stopped`,`stop-circle`,`muted`,!0);if(a&&Object.hasOwn(uI,a)){if(a===`compaction.interrupted`)return c(uI[a],dI.icon,dI.variant,r===`Compaction was interrupted`);if(a===`compaction.unavailable`)return c(uI[a],`information`,`info`,r===`Nothing to compact yet`);let e=a===`provider.auth`||a===`permission.rejected`?`lock`:a===`provider.timeout`?`time`:`error-warning`;return c(uI[a],e)}return(!a||a===`unknown`||a===`error`)&&lI(r)?c(`chat.response.auth`,`lock`):{...c(`chat.response.failed`,`error-warning`),...!r&&i?{rawMessage:i}:{}}}function pI(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.nativeType===`synthetic`&&t.description===`Continuing after restart`}function mI(e,t){if(pI(e))return{text:t(`chat.response.continuingAfterRestart`),icon:`restart`,variant:`info`}}function hI(e){return!e}function gI(e){let t=(0,Q.c)(60),{part:n,isMobile:r}=e,i=r!==void 0&&r,{t:a}=Wn(),o;t[0]!==n.id||t[1]!==n.messageID||t[2]!==n.sessionID?(o=JSON.stringify([n.sessionID,n.messageID,n.id]),t[0]=n.id,t[1]=n.messageID,t[2]=n.sessionID,t[3]=o):o=t[3];let s=o,{expanded:c,toggle:l}=sO(s),u=(0,Z.useId)(),d;t[4]!==s||t[5]!==l?(d=()=>l(s),t[4]=s,t[5]=l,t[6]=d):d=t[6];let f=q(d),p=n.status===`running`,m=n.status===`failed`,h;t[7]!==m||t[8]!==p||t[9]!==a?(h=a(p?`chat.activity.compacting`:m?`chat.activity.compactionFailed`:`chat.activity.compactionCompleted`),t[7]=m,t[8]=p,t[9]=a,t[10]=h):h=t[10];let g=h,_;t[11]!==m||t[12]!==n.error||t[13]!==a?(_=m?fI(n.error,a):void 0,t[11]=m,t[12]=n.error,t[13]=a,t[14]=_):_=t[14];let v=_,y;t[15]!==m||t[16]!==n.summary?(y=m?``:n.summary?.trim()??``,t[15]=m,t[16]=n.summary,t[17]=y):y=t[17];let b=y,x,S,C,w,T,E,D,O,k;if(t[18]!==u||t[19]!==c||t[20]!==v?.text||t[21]!==m||t[22]!==i||t[23]!==p||t[24]!==n.status||t[25]!==b||t[26]!==g||t[27]!==f){let e=J(`shrink-0 typography-meta`,p?`animate-text-shimmer text-[var(--status-info)] [--oc-text-shimmer-base:var(--status-info)]`:m?`text-[var(--status-error)]/85`:`text-muted-foreground`);E=`w-full min-w-0`,D=``,O=n.status;let r=i?`min-h-7`:`min-h-8`;t[37]===r?k=t[38]:(k=J(`flex w-full items-center gap-3`,r),t[37]=r,t[38]=k),x=`separator`,S=p?`polite`:void 0,C=v?.text??g,t[39]===Symbol.for(`react.memo_cache_sentinel`)?(w=(0,$.jsx)(`span`,{className:`min-w-0 flex-1 border-t`,"aria-hidden":`true`}),t[39]=w):w=t[39],T=b?(0,$.jsxs)(Jn,{variant:`ghost`,size:`sm`,className:J(e,jy),"aria-expanded":c,"aria-controls":u,onClick:f,children:[g,(0,$.jsx)(X,{name:`arrow-down-s`,className:J(`size-4 transition-transform`,c&&`rotate-180`)})]}):(0,$.jsx)(`span`,{className:e,children:g}),t[18]=u,t[19]=c,t[20]=v?.text,t[21]=m,t[22]=i,t[23]=p,t[24]=n.status,t[25]=b,t[26]=g,t[27]=f,t[28]=x,t[29]=S,t[30]=C,t[31]=w,t[32]=T,t[33]=E,t[34]=D,t[35]=O,t[36]=k}else x=t[28],S=t[29],C=t[30],w=t[31],T=t[32],E=t[33],D=t[34],O=t[35],k=t[36];let A;t[40]===Symbol.for(`react.memo_cache_sentinel`)?(A=(0,$.jsx)(`span`,{className:`min-w-0 flex-1 border-t`,"aria-hidden":`true`}),t[40]=A):A=t[40];let j;t[41]!==x||t[42]!==S||t[43]!==C||t[44]!==w||t[45]!==T||t[46]!==D||t[47]!==O||t[48]!==k?(j=(0,$.jsxs)(`div`,{"data-compaction-card":D,"data-compaction-status":O,className:k,role:x,"aria-live":S,"aria-label":C,children:[w,T,A]}),t[41]=x,t[42]=S,t[43]=C,t[44]=w,t[45]=T,t[46]=D,t[47]=O,t[48]=k,t[49]=j):j=t[49];let M;t[50]!==u||t[51]!==c||t[52]!==p||t[53]!==n.messageID||t[54]!==b?(M=b&&c?(0,$.jsx)(`div`,{id:u,className:`py-2`,children:(0,$.jsx)(Tu,{content:b,messageId:n.messageID,isStreaming:p})}):null,t[50]=u,t[51]=c,t[52]=p,t[53]=n.messageID,t[54]=b,t[55]=M):M=t[55];let N;return t[56]!==E||t[57]!==j||t[58]!==M?(N=(0,$.jsxs)(`div`,{className:E,children:[j,M]}),t[56]=E,t[57]=j,t[58]=M,t[59]=N):N=t[59],N}var _I=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},vI=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.model==`object`&&t.model!==null?t.model:void 0,r=typeof t.metadata==`object`&&t.metadata!==null?t.metadata:void 0,i=typeof r?.model==`object`&&r.model!==null?r.model:void 0,a=_I(t.mode)??_I(t.agent)??_I(r?.agent),o=_I(t.providerID)??_I(n?.providerID)??_I(i?.providerID),s=_I(t.modelID)??_I(n?.modelID)??_I(n?.id)??_I(i?.modelID)??_I(i?.id),c=_I(n?.variant)??_I(i?.variant)??_I(t.variant)??_I(r?.variant);return!a&&!o&&!s&&!c?null:{agentName:a,providerId:o,modelId:s,variant:c}},yI=e=>{let t=e?.providerId?.trim(),n=e?.modelId?.trim();return!t||!n?null:{providerId:t,modelId:n}},bI=e=>yI(e.assistantIdentity)??yI(e.userIdentity)??(e.allowComposerFallback?yI(e.composerSelection):null)??yI(e.sessionSelection),xI=e=>{let t=e?.modelId??null;return{providerID:e?.providerId??null,modelID:t,agentName:e?.agentName,modelName:hr(void 0,t)||void 0,variant:e?.variant}},SI=e=>!(!e.isLastTurn||!e.sessionIsWorking||e.hasAssistantMessages||e.activityPresentationKind===`compaction`||e.hasActiveStreamingMessage),CI=(e,t,n)=>e===`active`||n?.isLastTurn&&n.hasConfirmedFinalBody!==!0?!0:t===`summary`,wI=e=>!e,TI=e=>e.completionDisposition===`active`?e.isLastTurn&&e.sessionIsWorking?{completionDisposition:`active`,durationMs:e.durationMs}:{completionDisposition:`abnormal`,durationMs:e.durationMs}:{completionDisposition:e.completionDisposition,durationMs:e.durationMs},EI=e=>!(e.completionDisposition===`active`||e.isLastTurn&&e.sessionIsWorking&&!e.hasConfirmedSettledAssistant),DI=e=>e.isWorking?!0:e.isInActiveTurn?e.headerCompletionDisposition!==`normal`&&e.headerCompletionDisposition!==`abnormal`:!1,OI=e=>e.turnCompletionDisposition===`active`&&(e.isLastTurn||e.hasAssistantMessages)?`active`:e.headerPresentationDisposition,kI=e=>{let t=e.info;return(typeof t.clientRole==`string`?t.clientRole:null)??(typeof t.role==`string`?t.role:null)??null},AI=e=>{let t=e.info;return typeof t.parentID==`string`&&t.parentID.length>0?t.parentID:null},jI=e=>!e||kI(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`)}),MI=e=>kI(e)===`user`?jI(e)||e.parts.some(e=>{let t=e.shellAction;return e.type===`text`&&typeof t==`object`&&!!t}):!1,NI=(e,t)=>{if(kI(e)!==`assistant`||t&&AI(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}}},PI=(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(kI(t)===`user`)break;let{hide:i,details:a}=NI(t,r);if(i){let e=typeof a?.command==`string`?a.command.trim():``;return e.length>0?e:null}}return null},FI=Cu(()=>Sn(()=>import(`./ToolOutputDialog-DQvXtK71.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]))),II=4e3,LI=new Map,RI=new Map,zI=new Set([`bash`,`shell`,`cmd`,`terminal`]),BI=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},VI=e=>{let t=LI.get(e);return t?new Set(t):new Set},HI=(e,t)=>{if(LI.size>=II&&!LI.has(e)){let e=LI.keys().next().value;typeof e==`string`&&LI.delete(e)}LI.set(e,new Set(t))},UI=e=>{let t=RI.get(e);return t?new Set(t):new Set},WI=(e,t)=>{if(RI.size>=II&&!RI.has(e)){let e=RI.keys().next().value;typeof e==`string`&&RI.delete(e)}RI.set(e,new Set(t))},GI=200,KI=new Map,qI=e=>KI.get(e),JI=(e,t)=>{if(!t.agent&&!t.provider&&!t.model)return;let n=KI.get(e);if(!(n&&n.agent===t.agent&&n.provider===t.provider&&n.model===t.model)){if(KI.size>=GI&&!KI.has(e)){let e=KI.keys().next().value;typeof e==`string`&&KI.delete(e)}KI.set(e,t)}};function YI(e){let t=(0,Q.c)(3),[n,r]=Z.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),Z.useEffect(i,a),e??n}var XI=(e,t)=>{if(typeof e==`object`&&e)return e[t]},ZI=Z.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}=Wn(),{isMobile:m,isTablet:h,hasTouchInput:g}=Oc(),_=Qb(),v=$b(_),y=m||h,b=Z.useRef(null),x=Y(e=>e.currentSessionId),S=Y(e=>e.revertToMessage),C=Y(e=>e.editMessagePreservingChanges),w=Y(e=>e.forkFromMessage),T=Y(t=>t.messageEditCommitting?.messageId===e.info.id&&t.messageEditCommitting?.sessionId===e.info.sessionID),E=Y(t=>t.stagedMessageEdit?.messageId===e.info.id&&t.stagedMessageEdit?.sessionId===e.info.sessionID),D=Y(e=>e.clearStagedMessageEdit);Gt(`ui.chat_message.render`),c&&Gt(`ui.chat_message.render.streaming`);let O=ao(e=>e.providers),{showReasoningTraces:k,stickyUserHeader:A,chatRenderMode:j,showExpandedBashTools:M}=K(Je(e=>({showReasoningTraces:e.showReasoningTraces,stickyUserHeader:e.stickyUserHeader,chatRenderMode:e.chatRenderMode,showExpandedBashTools:e.showExpandedBashTools})));Z.useEffect(()=>{x&&lO.getInstance().recordSessionStart(x)},[x]);let[N,P]=Z.useState(null),[F,I]=Z.useState(!1),[L,R]=Z.useState(null),z=Z.useRef(null),[B,V]=Z.useState(()=>VI(e.info.id)),[H,ee]=Z.useState(()=>UI(e.info.id)),[U,te]=Z.useState({open:!1,title:``,content:``});Z.useEffect(()=>{V(VI(e.info.id)),ee(UI(e.info.id))},[e.info.id]);let W=Z.useMemo(()=>cI(e.info),[e.info]).isUser,ne=Z.useMemo(()=>st(e.parts),[e.parts]),re=W&&(m||!A),ie=W&&!m&&A&&!re,ae=e.info.sessionID,{currentContextAgent:oe,savedSessionAgentSelection:se}=Ky(Je(e=>({currentContextAgent:c&&ae?e.currentAgentContext.get(ae):void 0,savedSessionAgentSelection:c&&ae?e.sessionAgentSelections.get(ae):void 0}))),ce=Z.useMemo(()=>mD(e.sourceParts??e.parts),[e.parts,e.sourceParts]),le=Z.useMemo(()=>W?DD(ce):mD(e.parts),[W,e.parts,ce]),ue=Z.useMemo(()=>{if(W||!t)return null;let e=XI(t.info,`clientRole`),n=XI(t.info,`role`);return(typeof e==`string`?e:typeof n==`string`?n:void 0)===`user`&&vI(t.info)||null},[W,t]),de=Z.useMemo(()=>{if(W)return;let t=XI(e.info,`mode`);if(typeof t==`string`&&t.trim().length>0)return t;let n=XI(e.info,`agent`);if(typeof n==`string`&&n.trim().length>0)return n;if(ue?.agentName)return ue.agentName;if(ae)return oe||(se??void 0)},[W,e.info,ue,ae,oe,se]),fe=W?null:vI(e.info),pe=fe?.providerId??null,me=fe?.modelId??null,he=zo(Je(e=>{if(W||!ae)return null;if(ue?.providerId&&ue?.modelId)return{providerId:ue.providerId,modelId:ue.modelId};if(de){let t=e.getAgentModelForSession(ae,de);if(t?.providerId&&t?.modelId)return t}let t=e.getSessionModelSelection(ae);return t?.providerId&&t?.modelId?t:null})),ge=Z.useMemo(()=>W?null:typeof pe==`string`&&pe.trim().length>0?pe:he?.providerId??null,[W,pe,he]),_e=Z.useMemo(()=>W?null:typeof me==`string`&&me.trim().length>0?me:he?.modelId??null,[W,me,he]),ve=e.info.id?qI(e.info.id):void 0;W||JI(e.info.id,{agent:de,provider:ge??void 0,model:_e??void 0});let ye=de??ve?.agent,be=ge??ve?.provider??null,xe=_e??ve?.model??null,Se=Z.useMemo(()=>{if(W)return;let e=be&&O.length>0?O.find(e=>e.id===be):void 0;return hr(e,xe)||void 0},[W,be,xe,O]),Ce=Z.useMemo(()=>{if(W||!ge||!_e)return!1;let e=O.find(e=>e.id===ge);if(!e?.models||!Array.isArray(e.models))return!1;let t=e.models.find(e=>e.id===_e)?.variants;return!!(t&&Object.keys(t).length>0)},[W,_e,ge,O]),we=YI(ye),Te=YI(be??void 0),Ee=YI(xe??void 0),De=YI(Se),Oe=we??void 0,ke=Te??null,Ae=Ee??null,je=De??void 0,Me=Z.useMemo(()=>{let t=e.info.time;return typeof t?.completed==`number`?t.completed:null},[e.info.time]),Ne=Z.useMemo(()=>{let t=e.info.time;return typeof t?.created==`number`?t.created:null},[e.info.time]),Pe=Z.useMemo(()=>W?!0:!!(Me&&Me>0),[W,Me]),Fe=Z.useMemo(()=>{let t=e.info.finish;return typeof t==`string`?t:void 0},[e.info]),Ie=Z.useMemo(()=>_D(le,{includeReasoning:k}),[le,k]),Le=Z.useMemo(()=>W?Ie:!Pe&&j===`sorted`?[]:Ie,[j,Pe,W,Ie]),Re=Z.useMemo(()=>W?[]:Ie.filter(e=>e.type===`text`),[W,Ie]),ze=Z.useMemo(()=>W?[]:Ie.filter(e=>e.type===`tool`),[W,Ie]),Be=Z.useMemo(()=>{if(!M)return new Set;let e=new Set;for(let t of ze){let n=typeof t?.id==`string`?t.id:``;if(!n)continue;let r=BI(t.tool);!r||!zI.has(r)||e.add(n)}for(let t of a?.activityParts??[]){if(t.kind!==`tool`)continue;let n=BI(t.part.tool);!n||!zI.has(n)||e.add(t.id)}return e},[M,ze,a?.activityParts]),Ve=Z.useMemo(()=>{if(Be.size===0&&H.size===0)return B;let e=new Set(B);return Be.forEach(t=>{H.has(t)||e.add(t)}),H.forEach(t=>{e.delete(t)}),e},[H,Be,B]),He=Z.useMemo(()=>{if(!W)return;let e=le.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}`}},[W,le]),Ue=W&&!OD(Le),We=typeof Fe!=`string`,Ge=Z.useMemo(()=>W?!1:Re.length===0||ze.length===0?We:!0,[Re.length,ze.length,We,W]),Ke=Z.useMemo(()=>!W&&lO.getInstance().shouldAnimateMessage(e.info,x||e.info.sessionID),[e.info,x,W]),[qe,Ye]=Z.useState(!1),Xe=Z.useMemo(()=>n?cI(n.info):null,[n]),Ze=!!a,Qe=a?.isLastAssistantInTurn??!1,$e=DI({isWorking:a?.isWorking===!0,isInActiveTurn:c,headerCompletionDisposition:a?.completionDisposition}),et=Z.useMemo(()=>W?!1:Ze?!Qe:Xe?!Xe.isUser&&Xe.role===`assistant`:!1,[Ze,Qe,W,Xe]),tt=Z.useMemo(()=>Pe?`completed`:c?l??`streaming`:`completed`,[l,c,Pe]);Z.useEffect(()=>{!W||!u||d?.(e.info.id)},[u,W,e.info.id,d]),Z.useEffect(()=>{Ye(!1)},[e.info.id]),Z.useEffect(()=>{let t=o??a?.headerMessageId;W||!t||t!==e.info.id||(tt===`streaming`||tt===`cooldown`)&&Ye(!0)},[o,W,e.info.id,tt,a?.headerMessageId]);let nt=Z.useMemo(()=>{if(W)return!0;if(s)return!1;let t=o??a?.headerMessageId;return t?e.info.id===t?tt===`completed`||qe||tt===`streaming`||tt===`cooldown`:!1:!0},[o,qe,W,a,tt,e.info.id,s]),rt=Z.useCallback(e=>{Un(e).then(t=>{t.ok&&(P(e),setTimeout(()=>P(null),2e3))})},[]),it=W?void 0:a?.userMessageVariant??ue?.variant,at=!W&&Ce&&typeof it==`string`&&it.trim().length>0?it:void 0,ot=Z.useMemo(()=>{if(!W&&!hI(Ze?Qe:!et))return fI(e.info?.error,p)},[Ze,et,Qe,W,e.info,p]),ct=ot?.text,lt=Z.useMemo(()=>{if(W){let e=Le.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(`
|
|
6594
|
+
`).trim()||WN(t)},eP=({containerRef:e})=>{let{t}=Wn(),[n,r]=Z.useState({x:0,y:0,show:!1}),[i,a]=Z.useState(``),o=Z.useRef(!1),[s,c]=Z.useState(!1),l=Z.useRef(null),u=Z.useRef(RN),d=Z.useRef(null),f=Z.useRef(null),p=Z.useRef(null),m=Z.useRef(!1),h=Z.useRef(0),[g,_]=Z.useState(null),v=Y(e=>e.currentSessionId),y=qu()??null,b=K(e=>e.isMobile),x=Qb(),S=$b(x).textSelectionMutation,C=x.kind===`primary`&&!!v;Z.useEffect(()=>{m.current=n.show},[n.show]),Z.useEffect(()=>()=>{f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null),p.current!==null&&(window.clearTimeout(p.current),p.current=null)},[]);let w=Z.useCallback(()=>{d.current=null,VN===w&&(VN=null),m.current&&=(f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null),c(!1),r(e=>({...e,show:!1})),a(``),!1)},[]);Z.useEffect(()=>()=>{VN===w&&(VN=null)},[w]);let T=Z.useCallback(e=>{if(typeof window>`u`)return e;let t=window.innerWidth,n=u.current/2,r=NN+n,i=t-NN-n;return r>i?t/2:Math.min(Math.max(e,r),i)},[]),E=Z.useCallback(()=>{if(!d.current)return;VN!==w&&(VN?.(),VN=w);let{markdownText:e,rect:t}=d.current,i=!n.show,o=b?t.left+t.width/2:T(t.left+t.width/2),s=t.top-10;a(e),r({x:o,y:s,show:!0}),m.current=!0,i&&(c(!0),f.current!==null&&window.cancelAnimationFrame(f.current),f.current=window.requestAnimationFrame(()=>{c(!1),f.current=null}))},[T,w,b,n.show]);Z.useLayoutEffect(()=>{if(!n.show||b||!l.current)return;let e=l.current.offsetWidth;!Number.isFinite(e)||e<=0||e===u.current||(u.current=e,r(e=>({...e,x:T(e.x)})))},[T,b,n.show]),Z.useEffect(()=>{if(!n.show||b)return;let e=()=>{r(e=>({...e,x:T(e.x)}))};return window.addEventListener(`resize`,e),()=>{window.removeEventListener(`resize`,e)}},[T,b,n.show]);let D=Z.useCallback(()=>{let t=window.getSelection(),n=e.current;if(!t||!n){o.current||w();return}let r=WN(t.toString());if(!r){o.current||w();return}let i=qN(t,n);if(!i){o.current||w();return}let a=i.getBoundingClientRect();d.current={plainText:r,markdownText:$N(i,r),rect:a},o.current||E()},[e,w,E]);Z.useEffect(()=>{let t=e.current;if(!t)return;let n=()=>{o.current=!0,w()},r=()=>{o.current=!1,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{p.current=null,D()},10)},i=new Set,a=()=>{for(let e of KN(t))i.has(e)||(i.add(e),e.addEventListener(`selectionchange`,D))};a();let s=new MutationObserver(a);s.observe(t,{childList:!0,subtree:!0}),document.addEventListener(`selectionchange`,D),t.addEventListener(`mousedown`,n),document.addEventListener(`mouseup`,r);let c=e=>{l.current&&!l.current.contains(e.target)&&!window.getSelection()?.toString().trim()&&w()};return document.addEventListener(`mousedown`,c),()=>{p.current!==null&&(window.clearTimeout(p.current),p.current=null),s.disconnect();for(let e of i)e.removeEventListener(`selectionchange`,D);document.removeEventListener(`selectionchange`,D),t.removeEventListener(`mousedown`,n),document.removeEventListener(`mouseup`,r),document.removeEventListener(`mousedown`,c)}},[e,D,w,E]),Z.useLayoutEffect(()=>{if(!b||!n.show){h.current=0,_(null);return}let e=Uw(Jw),t=0,r=0,i=()=>{let e=BN(h.current);h.current=e.height,_(t=>t&&t.left===e.left&&t.top===e.top&&t.width===e.width&&t.height===e.height?t:e)},a=e=>{i(),e<r&&(t=window.requestAnimationFrame(a))},o=()=>{r=performance.now()+320,window.cancelAnimationFrame(t),t=window.requestAnimationFrame(a)};i(),o();let s=window.visualViewport;return s?.addEventListener(`resize`,o),s?.addEventListener(`scroll`,o),window.addEventListener(`resize`,o),window.addEventListener(`oc:keyboard-anim`,o),window.addEventListener(`oc:keyboard-settled`,o),()=>{window.cancelAnimationFrame(t),s?.removeEventListener(`resize`,o),s?.removeEventListener(`scroll`,o),window.removeEventListener(`resize`,o),window.removeEventListener(`oc:keyboard-anim`,o),window.removeEventListener(`oc:keyboard-settled`,o),e()}},[b,n.show]),Z.useEffect(()=>{if(!n.show)return;let e=e=>{l.current&&e.target instanceof Node&&l.current.contains(e.target)||w()};return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),()=>{window.removeEventListener(`scroll`,e,!0)}},[n.show,w]);let O=()=>{w(),window.getSelection()?.removeAllRanges()},k=q(e=>{if(!e)return;let t=Y.getState().newSessionDraft.draftID,n=g_(v,t);n&&(O_.getState().addQuote(n,e),O(),requestAnimationFrame(()=>{Array.from(document.querySelectorAll(`textarea[data-chat-input="true"]`)).find(e=>!e.closest(`[data-btw-composer]`))?.focus()}))}),A=q(e=>{if(!e||!v)return;let t={sessionId:v,directory:y};zw.getState().addQuote(t,e),O(),cT(t)});if(Z.useEffect(()=>{if(!S)return;let t=t=>{let n=rc(t,PN),r=C&&rc(t,FN);if(!n&&!r)return;let i=window.getSelection(),a=e.current;if(!i||!a||!i.toString().trim())return;let o=qN(i,a);if(!o)return;t.preventDefault(),t.stopPropagation();let s=$N(o,i.toString());n?k(s):A(s)};return window.addEventListener(`keydown`,t,!0),()=>window.removeEventListener(`keydown`,t,!0)},[k,A,C,S,e]),!n.show||!S)return null;let j=[{id:`chat`,label:t(`chat.textSelection.actions.addToChat`),shortcut:PN,run:()=>k(i)},...C?[{id:`side`,label:t(`chat.textSelection.actions.addToSideChat`),shortcut:FN,run:()=>A(i)}]:[]];if(b){let e=g??{left:0,top:Math.max(0,window.innerHeight-88),width:window.innerWidth,height:88};return(0,fp.createPortal)((0,$.jsx)(`div`,{ref:l,"data-text-selection-menu":!0,className:J(`fixed z-50 flex items-center justify-center gap-2 bg-background px-4`,`transition-opacity duration-200 ease-out`,s?`opacity-0`:`opacity-100`),style:{left:e.left,top:e.top,width:e.width,height:e.height,paddingBottom:`max(0.75rem, var(--oc-safe-area-bottom-visual, env(safe-area-inset-bottom, 0px)))`},onPointerDown:e=>{e.preventDefault()},children:j.map(e=>(0,$.jsx)(Jn,{type:`button`,variant:`secondary`,size:`sm`,onClick:e.run,className:`max-w-[11rem] min-w-0`,children:(0,$.jsx)(`span`,{className:`truncate`,children:e.label})},e.id))}),document.body)}return(0,fp.createPortal)((0,$.jsx)(`div`,{ref:l,"data-text-selection-menu":!0,className:`fixed z-50`,style:{left:n.x,top:n.y,transform:`translate(-50%, -100%)`},children:(0,$.jsx)(`div`,{className:J(`flex items-center gap-0.5 whitespace-nowrap rounded-lg p-0.5`,`border border-[var(--interactive-border)] bg-[var(--surface-elevated)] shadow-sm`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,s?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),children:j.map((e,t)=>(0,$.jsxs)(Z.Fragment,{children:[t>0?(0,$.jsx)(`div`,{className:`h-3 w-px shrink-0 bg-[var(--interactive-border)]`}):null,(0,$.jsxs)(`button`,{type:`button`,onClick:e.run,className:`flex h-6 items-center gap-1.5 rounded-md px-2 typography-meta text-[var(--surface-foreground)] transition-colors duration-150 hover:bg-[var(--interactive-hover)]`,children:[(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(`span`,{className:`tracking-[0.08em] text-[var(--surface-muted-foreground)]`,"aria-hidden":`true`,children:LN(e.shortcut)})]})]},e.id))})}),document.body)},tP=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),nP=(e,t)=>{let n=new Date(t);return n.setDate(t.getDate()-1),tP(e,n)},rP=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),iP=(e,t)=>{if(!rP(e))return``;let n=new Date(e),r=new Date,i=Ps(n,t),a=qn(),o=Xn.getState().dictionary;if(tP(n,r))return i;if(nP(n,r))return Zn(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}`},aP=e=>typeof e!=`number`||!Number.isFinite(e)||e<0?0:e,oP=e=>{let t=0,n=0,r=!0;return e.map(e=>{if(typeof e.createdAt==`number`&&Number.isFinite(e.createdAt)&&typeof e.streamedAt==`number`&&Number.isFinite(e.streamedAt)?n+=Math.max(0,e.streamedAt-e.createdAt):r=!1,t+=aP(e.outputTokens)+aP(e.reasoningTokens),!r||t<=0||n<=0)return null;let i=t/(n/1e3);return Number.isFinite(i)&&i>0?i:null})},sP=e=>{let t=oP(e);return t[t.length-1]??null},cP=e=>e.completionDisposition!==`active`&&typeof e.tps==`number`&&Number.isFinite(e.tps)&&e.tps>0,lP=e=>!Number.isFinite(e)||e<=0?``:`${e.toFixed(1)} tok/s`,uP=e=>{let t=(0,Q.c)(20),{text:n,active:r,className:i}=e,a=Z.useRef(n),[o,s]=Z.useState(n),[c,l]=Z.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]),Z.useEffect(u,d);let f;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(f=()=>{l(null)},t[4]=f):f=t[4];let p=q(f),m;t[5]===i?m=t[6]:(m=J(`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=J(`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},dP=[`search`,`read`,`list`];function fP(e){let t=rj(e);return t===`read`?`read`:t===`glob`||t===`grep`?`search`:t===`list`?`list`:null}function pP(e){let t={read:0,search:0,list:0};for(let n of e){let e=fP(n);e&&(t[e]+=1)}return t}var mP=[`edit`,`command`,`other`],hP=new Set([`edit`,`multiedit`,`write`,`create`,`file_write`,`apply_patch`,`patch`]),gP=new Set([`bash`,`shell`,`cmd`,`command`,`exec`,`terminal`]);function _P(e){if(!$A(e))return null;let t=rj(e);return hP.has(t)?`edit`:gP.has(t)?`command`:`other`}function vP(e){let t={edit:0,command:0,other:0};for(let n of e){let e=_P(n);e&&(t[e]+=1)}return t}function yP(e){return EA(e)}var bP=[...dP,...mP];function xP(e){return{...pP(e),...vP(e)}}function SP(e){return nj(e)}function CP(e){return e.kind===`reasoning`||e.type===`reasoning`?!1:e.kind===`justification`||e.type===`text`?!0:e.kind===`tool`||e.type===`tool`?!ej(e.toolName):e.kind!=null||e.type!=null}function wP(e,t,n){for(let r=t;r<e.length;r+=1)if(CP(n(e[r])))return!0;return!1}function TP(e){return`parts`in e?e.parts.some(e=>SP(e))?!0:!e.hasFollowingOtherType&&e.isTurnLive:e.some(e=>SP(e))}function EP(e,t,n){let r=[],i=t;for(;i<e.length&&ej(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var DP=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,OP=e=>{let t=(0,Q.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=J(`inline-flex flex-none items-center gap-0.5 tabular-nums`,DP),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},kP=({activities:e,isMobile:t,isTurnLive:n=!1,hasFollowingOtherType:r=!1,exploring:i,children:a})=>{let{t:o}=Wn(),[s,c]=Z.useState(!1),l=Z.useId(),u=e.map(e=>e.part),d=i??TP({parts:u,hasFollowingOtherType:r,isTurnLive:n}),f=xP(u.map(e=>e.tool)),p=yP(u),m=bP.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=q(()=>{c(e=>!e)}),g=q(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:ky(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":s,"aria-controls":l,"aria-label":_,"data-mobile-press-feedback":`soft`,className:J(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,My),onClick:h,onKeyDown:g,children:[(0,$.jsx)(`span`,{className:J(`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)(zA,{isMobile:t,label:o(`chat.usedGroup.running`),className:`block`}):(0,$.jsx)(X,{name:`search`,className:`block h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:J(`typography-meta inline-flex flex-none items-center self-center font-medium`,y,DP,d&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...d?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:v}),m?(0,$.jsx)(`span`,{className:J(`typography-meta inline-flex min-h-0 w-0 min-w-0 max-w-full flex-1 items-center self-center overflow-clip`,y,DP),style:{color:`var(--tools-description)`},children:(0,$.jsx)(uP,{text:m,active:d,className:t?`!h-5 sm:!h-5`:`!h-6 sm:!h-6`})}):null,(0,$.jsx)(OP,{added:p.added,removed:p.removed}),(0,$.jsx)(X,{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:Ay(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 AP(e,t,n){let r=[],i=t;for(;i<e.length&&QA(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var jP=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null};function MP(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=jP(n.metadata.name);if(e)return e}if(n.input&&typeof n.input==`object`){let e=n.input,t=jP(e.name);if(t)return t;let r=jP(e.id);if(r)return r}if(n.output&&typeof n.output==`object`){let e=jP(n.output.name);if(e)return e}return null}function NP(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 PP=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,FP=({activities:e,isMobile:t,children:n})=>{let{t:r}=Wn(),[i,a]=Z.useState(!1),o=Z.useId(),s=e.map(e=>e.part),c=s.some(e=>nj(e)),{joinedVisible:l,hiddenCount:u}=NP(s.map(MP)),d=u>0?r(`chat.skillGroup.summaryOverflow`,{names:l,count:u}):l,f=q(()=>{a(e=>!e)}),p=q(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:ky(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":i,"aria-controls":o,"aria-label":m,"data-mobile-press-feedback":`soft`,className:J(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,My),onClick:f,onKeyDown:p,children:[(0,$.jsx)(`span`,{className:J(`flex flex-none items-center justify-center`,t?`size-4`:`size-3.5`),style:{color:`var(--tools-icon)`},children:c?(0,$.jsx)(zA,{isMobile:t,label:h,className:`block`}):(0,$.jsx)(X,{name:`book`,className:`h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:J(`typography-meta flex-none font-medium`,PP,c&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...c?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:h}),d?(0,$.jsx)(`span`,{className:J(`typography-meta h-5 min-h-0 w-0 min-w-0 max-w-full flex-1 overflow-clip sm:h-6`,PP),style:{color:`var(--tools-description)`},children:(0,$.jsx)(uP,{text:d,active:c})}):null,(0,$.jsx)(X,{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:Ay(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]})},IP=Z.memo(e=>{let t=(0,Q.c)(18),{part:n,messageId:r,onContentChange:i,actions:a,streamPhase:o,onShowPopup:s}=e,c=K(LP),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]),Z.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)(PM,{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 LP(e){return e.chatRenderMode}var RP=e=>{let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`},zP=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,BP=J(`typography-meta font-medium`,zP),VP=J(`typography-meta`,zP),HP=[],UP=e=>{let t=e.part;return t.slim===!0&&(t.type===`tool`||t.type===`reasoning`||t.type===`file`)},WP=e=>{let t=new Set;for(let n of e)UP(n)&&n.messageId&&t.add(n.messageId);return[...t]},GP=(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}),KP=e=>{let t=(0,Q.c)(5),{href:n}=e,[r,i]=Z.useState(!1),a;t[0]===n?a=t[1]:(a=Vu(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},qP=e=>e,JP=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},YP=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},XP=e=>{let t=e.part.state?.metadata?.dir;return typeof t==`string`&&t.trim().length>0?t:null},ZP=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},QP=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=ZP(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`}`},$P=e=>{let t=e.part.state,n=t?.input,r=t?.output;if(Array.isArray(n?.todos)){let e=QP(n.todos);if(e)return e}if(Array.isArray(r)){let e=QP(r);if(e)return e}if(r&&typeof r==`object`&&Array.isArray(r.todos)){let e=QP(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=QP(e);if(t)return t}if(e&&typeof e==`object`&&Array.isArray(e.todos)){let t=QP(e.todos);if(t)return t}}catch{}return null},eF=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)},tF=(e,t=!0)=>{let n=e.lastIndexOf(`/`);if(n===-1)return(0,$.jsx)(CO,{variant:t?`generate-effect`:`static`,className:J(`min-w-0 flex-1 truncate whitespace-nowrap`,VP),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:J(`min-w-0 inline-flex max-w-full flex-1 items-baseline overflow-hidden`,VP),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)(CO,{variant:t?`generate-effect`:`static`,className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:i})]})},nF=e=>{let t=ud(e);return t?t.toLowerCase().endsWith(`/skill.md`)?t:`${t}/SKILL.md`:``},rF=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 MP(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`?$P(e):JP(e)},iF=e=>{let t=[],n=[];for(let r of e){if(r.kind!==`tool`)continue;let e=r.part,i=e.tool?.trim().toLowerCase()??``;if(i!==`task`&&i!==`subagent`)continue;let a=typeof e.id==`string`?e.id.trim():``;if(!a)continue;let o=e.state;if(!o||typeof o!=`object`)continue;let s=o;n.push(a),(s.status===`pending`||s.status===`running`)&&t.push(a)}return{active:t,all:n}},aF=Z.memo(e=>{let t=(0,Q.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=q(c),u;t[3]===i?u=t[4]:(u=ky(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)(mM,{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&&Ik([e.activity.part],[t.activity.part])),oF=Z.memo(e=>{let t=(0,Q.c)(9),{toolName:n,activities:r,isMobile:i}=e,a;t[0]===i?a=t[1]:(a=ky(i),t[0]=i,t[1]=a);let o;t[2]!==r||t[3]!==i||t[4]!==n?(o=(0,$.jsx)(lF,{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&&cF(e.activities,t.activities)),sF=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.kind===`reasoning`){if(!hD(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(ej(i)){let r=EP(e,n,e=>e.part.tool);t.push({type:`tool-context-group`,activities:r.items,hasFollowingOtherType:wP(e,r.end,e=>({kind:e.kind,toolName:e.part.tool}))}),n=r.end;continue}if(QA(i)){let r=AP(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(YA(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(JA(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(XA(i)){t.push({type:`tool-static-group`,toolName:i,activities:[r]}),n++;continue}t.push({type:`tool-fallback`,activity:r}),n++}return t},cF=(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||!Ik([r.part],[i.part]))return!1}return!0},lF=Z.memo(e=>{let t=(0,Q.c)(106),{toolName:n,activities:r,isMobile:i,animateTailText:a}=e,{t:o}=Wn(),s=K(pF),c=Gu(n,o),l;t[0]===n?l=t[1]:(l=wO(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=Z.useContext(zc),m=qc(),h=lt(mF),g=Qb(),_=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=xi(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(hF)),t[10]=C,t[11]=w);let T=w,E=r[0]??null,D=!E||nj(E.part),O;t[12]===E?O=t[13]:(O=E?rF(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||XP(E);if(!e||e===`<built-in>`){A=null;break bb0}let r=nF(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=YP(E);if(!e){M=null;break bb1}let n=pd(e,_);if(!n){M=null;break bb1}let r;t[26]===E?r=t[27]:(r=eF(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=cd(_,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(!od(n,_)){Yu(n,_).then(()=>{let e=K.getState(),r=_||sd(_,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=K.getState(),i=sd(_,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=q(P),I;t[36]!==_||t[37]!==m?(I=e=>{let t=ud(e);if(!t)return;let n=()=>{if(m){m.openFile({path:t});return}let e=K.getState(),n=_||sd(``,t);e.openContextFile(n,t)};if(_&&!od(t,_)){Yu(t,_).then(n);return}n()},t[36]=_,t[37]=m,t[38]=I):I=t[38];let L=q(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=q(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 re=q(ne),ie=ee&&U&&`cursor-pointer`,ae=ee&&!U&&`cursor-default opacity-70`,oe;t[50]!==ie||t[51]!==ae?(oe=J(`flex w-full items-center gap-x-1.5 min-w-0`,My,ie,ae),t[50]=ie,t[51]=ae,t[52]=oe):oe=t[52];let se=ee?`soft`:void 0,ce=ee?W:void 0,le=ee?re:void 0,ue=ee?`button`:void 0,de=ee&&U?0:void 0,fe=ee&&!U?!0:void 0,pe=i?`size-4`:`size-3.5`,me;t[53]===pe?me=t[54]:(me=J(`inline-flex items-center justify-center flex-shrink-0`,pe),t[53]=pe,t[54]=me);let he;t[55]===Symbol.for(`react.memo_cache_sentinel`)?(he={color:`var(--tools-icon)`},t[55]=he):he=t[55];let ge=D?(0,$.jsx)(zA,{isMobile:i,label:o(`chat.assistantStatus.usingTool`,{tool:c})}):u,_e;t[56]!==me||t[57]!==he||t[58]!==ge?(_e=(0,$.jsx)(`div`,{className:me,style:he,children:ge}),t[56]=me,t[57]=he,t[58]=ge,t[59]=_e):_e=t[59];let ve,ye;t[60]===Symbol.for(`react.memo_cache_sentinel`)?(ve=J(BP,`inline-flex items-center flex-shrink-0 opacity-85`),ye={color:`var(--tools-title)`},t[60]=ve,t[61]=ye):(ve=t[60],ye=t[61]);let be;t[62]===c?be=t[63]:(be=(0,$.jsx)(`span`,{className:ve,style:ye,title:c,children:c}),t[62]=c,t[63]=be);let xe;t[64]!==a||t[65]!==f||t[66]!==N||t[67]!==s?(xe=f&&N?(0,$.jsxs)(`span`,{className:J(`inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left`,VP),style:{color:`var(--tools-description)`},title:N.offset?`${N.displayPath}:${N.offset}`:N.displayPath,children:[s?(0,$.jsx)(Dg,{filePath:N.path,className:`h-3.5 w-3.5`}):null,tF(N.displayPath,a)]}):null,t[64]=a,t[65]=f,t[66]=N,t[67]=s,t[68]=xe):xe=t[68];let Se;t[69]!==a||t[70]!==k||t[71]!==B?(Se=B&&k?(0,$.jsx)(`span`,{className:`inline-flex min-w-0 flex-1`,children:(0,$.jsxs)(CO,{variant:a?`generate-effect`:`static`,className:J(`min-w-0 flex-1 truncate whitespace-nowrap`,VP),style:{color:`var(--tools-description)`},title:k,children:[`"`,k,`"`]})}):null,t[69]=a,t[70]=k,t[71]=B,t[72]=Se):Se=t[72];let Ce;t[73]!==k||t[74]!==V?(Ce=V&&k?(0,$.jsxs)(`a`,{href:k,target:`_blank`,rel:`noopener noreferrer`,onClick:gF,className:J(`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`,VP),style:{color:`var(--status-info)`},title:k,children:[(0,$.jsx)(KP,{href:k}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:k})]}):null,t[73]=k,t[74]=V,t[75]=Ce):Ce=t[75];let we;t[76]!==H||t[77]!==j?(we=H&&j?(0,$.jsx)(`span`,{className:J(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,VP),style:{color:`var(--tools-description)`},title:j.path,children:j.name}):null,t[76]=H,t[77]=j,t[78]=we):we=t[78];let Te;t[79]!==k||t[80]!==H||t[81]!==j?(Te=H&&!j&&k?(0,$.jsx)(`span`,{className:J(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,VP),style:{color:`var(--tools-description)`},title:k,children:k}):null,t[79]=k,t[80]=H,t[81]=j,t[82]=Te):Te=t[82];let Ee;t[83]!==a||t[84]!==k||t[85]!==V||t[86]!==f||t[87]!==B||t[88]!==H?(Ee=!f&&!B&&!V&&!H&&k?(0,$.jsx)(CO,{variant:a?`generate-effect`:`static`,className:J(`min-w-0 flex-1 truncate whitespace-nowrap`,VP),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]=Ee):Ee=t[89];let De;return t[90]!==oe||t[91]!==se||t[92]!==ce||t[93]!==le||t[94]!==ue||t[95]!==de||t[96]!==fe||t[97]!==_e||t[98]!==be||t[99]!==xe||t[100]!==Se||t[101]!==Ce||t[102]!==we||t[103]!==Te||t[104]!==Ee?(De=(0,$.jsxs)(`div`,{className:oe,"data-mobile-press-feedback":se,onClick:ce,onKeyDown:le,role:ue,tabIndex:de,"aria-disabled":fe,children:[_e,be,xe,Se,Ce,we,Te,Ee]}),t[90]=oe,t[91]=se,t[92]=ce,t[93]=le,t[94]=ue,t[95]=de,t[96]=fe,t[97]=_e,t[98]=be,t[99]=xe,t[100]=Se,t[101]=Ce,t[102]=we,t[103]=Te,t[104]=Ee,t[105]=De):De=t[105],De},(e,t)=>e.toolName===t.toolName&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&cF(e.activities,t.activities)),uF=Z.memo(e=>{let t=(0,Q.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)(KM,{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}),dF=Z.memo(e=>{let t=(0,Q.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)(IP,{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}),fF=Z.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}=Wn(),_=qu()??``,v=Z.useMemo(()=>WP(t),[t]),y=Z.useRef(new Set),b=Z.useRef(new Map),x=Z.useRef(new Set),[,S]=Z.useState(0),C=Z.useRef(null),w=Z.useRef(null),T=i===`active`,E=!T&&(i===`normal`||i===`abnormal`)&&typeof o==`number`&&Number.isFinite(o)&&o>=0?RP(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=Z.useMemo(()=>iF(e),[e]),M=T?j.active:j.all,N=M.slice(0,c?2:3),P=q((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=Ft(_,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=ln(_,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=q(e=>{e.stopPropagation(),P(!0)}),I=T,L=I||n,R=q(()=>{if(I)return;let e=C.current;w.current=e?{top:e.getBoundingClientRect().top,scrollContainer:e.closest(`[data-scrollbar="chat"]`)}:null,L||P(),s()});Z.useEffect(()=>{T||!L||P(!1,!0)},[T,L]),Z.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 Ft(_,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)&&UP(e)),ne=te&&!W&&!GP(t,V),re=Z.useMemo(()=>B?qP(e):HP,[e,B]),ie=Z.useMemo(()=>B?sF(re):[],[B,re]),ae=Z.useMemo(()=>L||z===0?0:Math.max(0,ie.length-z),[L,z,ie.length]),oe=Z.useMemo(()=>L||z===0?ie:ie.slice(-z),[L,z,ie]),se=!!m&&!(T&&!O);if((!se||I&&!O)&&ie.length===0)return null;let ce=(e,t)=>{let n=(0,$.jsx)(`div`,{className:ky(c),children:t});return(0,$.jsx)(Z.Fragment,{children:n},e)},le=B?oe.map((e,t)=>{switch(e.type){case`reasoning`:return ce(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(uF,{activity:e.activity,streamPhase:p,onContentChange:f})}));case`justification`:return ce(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(dF,{activity:e.activity,onContentChange:f,onShowPopup:d,actions:h?.(e.activity),streamPhase:p})}));case`tool-expandable`:return(0,$.jsx)(aF,{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)(oF,{toolName:e.toolName,activities:e.activities,isMobile:c},e.activities[0]?.id??`static-${e.toolName}-${t}`);case`tool-context-group`:return(0,$.jsx)(kP,{activities:e.activities,isMobile:c,isTurnLive:T,hasFollowingOtherType:e.hasFollowingOtherType,children:e.activities.map(e=>{let t=e.part,n=t.tool?.toLowerCase()??``;return ZA(n)?(0,$.jsx)(lF,{toolName:n,activities:[e],isMobile:c,animateTailText:!1},e.id):(0,$.jsx)(mM,{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)(FP,{activities:e.activities,isMobile:c,children:e.activities.map(e=>{let t=e.part;return(0,$.jsx)(lF,{toolName:t.tool?.toLowerCase()??``,activities:[e],isMobile:c,animateTailText:!1},e.id)})},e.activities[0]?.id??`skill-${t}`);case`tool-fallback`:return(0,$.jsx)(aF,{activity:e.activity,isExpanded:l.has(e.activity.id),isMobile:c,onToggleTool:u,onShowPopup:d,onContentChange:f},e.activity.id);default:return null}}):null,ue=oe.length>0;return se?(0,$.jsxs)(`div`,{className:ky(c),children:[(0,$.jsxs)(`button`,{ref:C,type:`button`,className:J(`group/tool flex w-full min-w-0 flex-nowrap items-center text-left`,c?`gap-x-1`:`gap-x-2`,!I&&My,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:J(`inline-flex min-w-0 flex-1 items-center overflow-clip`,c?`gap-x-1`:`gap-x-1.5`),children:[(0,$.jsx)(`span`,{className:J(`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)(zA,{isMobile:c,label:A,className:`block`}):(0,$.jsx)(X,{name:k,className:`h-3.5 w-3.5`})}),(0,$.jsx)(`span`,{className:J(`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:J(`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:J(`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)(es,{name:e,size:c?12:14,className:J(`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)(X,{name:L?`arrow-down-s`:`arrow-right-s`,className:J(`flex-shrink-0 text-muted-foreground opacity-70`,c&&`-mr-0.5`,c?`size-3`:`size-3.5`)})]})]}),ue?(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)`}}),ae>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:[`+`,ae,` more...`]}):null,(0,$.jsx)(`div`,{className:`flow-root`,children:le})]}):null,L&&(ee||U||ne)?(0,$.jsx)(`div`,{className:J(`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)(X,{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)(X,{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)(Jn,{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:ky(c),children:le})});function pF(e){return e.showToolFileIcons}function mF(e){return e.currentDirectory}function hF(e){return[e.name,e]}function gF(e){e.stopPropagation()}var _F=Z.memo(e=>{let t=(0,Q.c)(2),n;return t[0]===e?n=t[1]:(n=(0,$.jsx)(fF,{...e}),t[0]=e,t[1]=n),n});function vF(e){let t=(0,Q.c)(9),{presentation:n,sessionId:r,messageId:i,directory:a}=e,o;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(o={bootstrap:!1},t[0]=o):o=t[0];let s=Nr(a,o),c;t[1]===r?c=t[2]:(c=e=>!!e.session_execution_recovery[r],t[1]=r,t[2]=c);let l=Ge(s,c),u;t[3]===r?u=t[4]:(u=e=>e.session_status[r]?.type===`retry`,t[3]=r,t[4]=u);let d=Ge(s,u),f=ma(r,a);if(!l&&!d){let e;return t[5]===n?e=t[6]:(e=(0,$.jsx)(dy,{presentation:n}),t[5]=n,t[6]=e),e}let p;for(let e=f.length-1;e>=0;--e)if(f[e].role===`assistant`){p=f[e].id;break}if(p===i&&(d||l&&n.detail===`aborted`&&n.icon===`pause-circle`))return null;let m;return t[7]===n?m=t[8]:(m=(0,$.jsx)(dy,{presentation:n}),t[7]=n,t[8]=m),m}function yF(e){let t=(0,Q.c)(5),n=Qb();if(!e.sessionId||!n.active||!n.capabilities.compose){let n;return t[0]===e.presentation?n=t[1]:(n=(0,$.jsx)(dy,{presentation:e.presentation}),t[0]=e.presentation,t[1]=n),n}let r=n.directory??e.directory,i;return t[2]!==e||t[3]!==r?(i=(0,$.jsx)(vF,{...e,sessionId:e.sessionId,directory:r}),t[2]=e,t[3]=r,t[4]=i):i=t[4],i}var bF={contain:`layout`},xF={containerType:`inline-size`,containerName:`message-footer`},SF=`mt-1.5 mb-0.5 flex items-center justify-start gap-1.5`,CF=`mt-3 mb-0.5 flex items-center justify-start gap-1.5`,wF=`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`,TF=`size-3.5!`,EF=`mt-1.5 mb-0.5 flex flex-wrap items-center gap-3`,DF=`mt-3 mb-0.5 flex flex-wrap items-center gap-3 -ml-[5px]`,OF=`flex items-center gap-2`,kF=`flex items-center gap-2 text-muted-foreground`,AF=`inline-flex h-3.5 items-center gap-1 text-[11px] leading-none tabular-nums text-muted-foreground`,jF=`size-3.5!`,MF=`medium`,NF=e=>{let t=(0,Q.c)(16),{label:n}=e,{t:r}=Wn(),i;t[0]!==n||t[1]!==r?(i=r(`chat.messageBody.meta.tpsAria`,{rate:n}),t[0]=n,t[1]=r,t[2]=i):i=t[2];let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(X,{weight:MF,name:`pulse`,className:jF}),t[3]=a):a=t[3];let o;t[4]===n?o=t[5]:(o=(0,$.jsx)(`span`,{className:`message-footer__label`,children:n}),t[4]=n,t[5]=o);let s;t[6]!==i||t[7]!==o?(s=(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsxs)(`span`,{className:AF,"aria-label":i,children:[a,o]})}),t[6]=i,t[7]=o,t[8]=s):s=t[8];let c;t[9]===r?c=t[10]:(c=r(`chat.messageBody.meta.tpsTooltip`),t[9]=r,t[10]=c);let l;t[11]===c?l=t[12]:(l=(0,$.jsx)(Ds,{children:c}),t[11]=c,t[12]=l);let u;return t[13]!==s||t[14]!==l?(u=(0,$.jsxs)(Os,{children:[s,l]}),t[13]=s,t[14]=l,t[15]=u):u=t[15],u},PF=e=>e.replace(/\\/g,`/`).split(`/`).filter(Boolean).at(-1)??e,FF=`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)]`,IF=`h-7 gap-1.5`,LF=`h-6 gap-1`,RF=`text-[11px] leading-none`,zF=`size-3.5`,BF=`size-3`,VF=5,HF=Z.memo(e=>{let t=(0,Q.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=J(`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=J(`flex-shrink-0`,s),t[2]=s,t[3]=c);let l;t[4]!==n.file||t[5]!==c?(l=(0,$.jsx)(Dg,{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=PF(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=J(`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}),UF=Z.memo(e=>{let t=(0,Q.c)(18),{file:n,canOpen:r,isMobile:i,onOpen:a}=e,{t:o}=Wn(),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=q(s),l=!r,u=i?LF:IF,d;t[3]===u?d=t[4]:(d=J(FF,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)(HF,{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)(Jn,{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}),WF=Z.memo(e=>{let t=(0,Q.c)(53),{fileCount:n,changedFiles:r,turnId:i,isLatestTurn:a,isMobile:o}=e,{t:s}=Wn(),c=qu(),l=Qb(),u=l.directory||c,d=l.sessionId,f=qc(),p=K(rI),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,VF),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=J(FF,o?LF:IF),E=o?BF:zF,D;t[10]===o?D=t[11]:(D=o?J(RF,`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?J(RF,`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?J(RF,`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){YM({directory:u,filePath:e,turnMessageId:i,sessionId:d});return}o&&a&&u&&YM({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=q(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&&YM({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=q(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=J(`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=J(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)(X,{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=J(E,`opacity-60`),t[49]=E,t[50]=ne);let re;return t[51]===ne?re=t[52]:(re=(0,$.jsx)(X,{name:`arrow-right-s`,className:ne}),t[51]=ne,t[52]=re),(0,$.jsxs)(`section`,{className:R,"data-turn-changes-preview":`true`,"data-message-action-group":`true`,"aria-labelledby":`turn-changes-${i}`,children:[(0,$.jsxs)(Jn,{type:`button`,variant:`ghost`,size:`xs`,disabled:!b,onClick:I,className:z,"aria-label":B,title:V,children:[H,te,W,re]}),_.length>0?(0,$.jsxs)(`div`,{className:J(`flex min-w-0 flex-col`,o?`gap-0`:`gap-0.5`),children:[_.map(e=>(0,$.jsx)(UF,{file:e,canOpen:b,isMobile:o,onOpen:P},e.file)),v>0?(0,$.jsxs)(Jn,{type:`button`,variant:`ghost`,size:`xs`,disabled:!b,className:J(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:J(E,`flex-shrink-0`)}),(0,$.jsxs)(`span`,{className:M,children:[`+`,w]}),(0,$.jsx)(X,{name:`arrow-right-s`,className:E})]}):null]}):null]})}),GF=e=>e.type===`subtask`,KF=e=>{let t=e;return t.type===`text`&&typeof t.shellAction==`object`&&t.shellAction!==null},qF=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}`},JF=e=>{let t=(0,Q.c)(49),{part:n}=e,[r,i]=Z.useState(!1),a=qu(),{isMobile:o}=Oc(),s=Y(iI),c=K(aI),l=Qb(),{t:u}=Wn(),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=qF(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(oI),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&&ex(l,b,e,()=>{if(!La({sessionId:b,directory:e})){if(Cp()||o||fe()){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},YF=e=>{let t=(0,Q.c)(34),{notification:n}=e,r=qu(),i=K(sI),{isMobile:a}=Oc(),{t:o}=Wn(),s;t[0]!==r||t[1]!==a?(s=r&&!a&&!fe(),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=q(()=>{!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=q(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]:(_=J(`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)(X,{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=J(`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)(Su,{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},XF={background:`transparent`,backgroundColor:`transparent`},ZF=e=>{let t=(0,Q.c)(37),{part:n}=e,[r,i]=Z.useState(!1),a=Z.useRef(null),{t:o}=Wn(),s;t[0]===n.shellAction?s=t[1]:(s=typeof n.shellAction?.command==`string`?n.shellAction.command.trim():``,t[0]=n.shellAction,t[1]=s);let c=s,l=typeof n.shellAction?.output==`string`?n.shellAction.output:``,u;t[2]===n.shellAction?u=t[3]:(u=typeof n.shellAction?.status==`string`?n.shellAction.status.trim().toLowerCase():``,t[2]=n.shellAction,t[3]=u);let d=u,f=l.length>0,p;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(p=()=>{a.current!==null&&typeof window<`u`&&(window.clearTimeout(a.current),a.current=null)},t[4]=p):p=t[4];let m=q(p),h,g;t[5]===m?(h=t[6],g=t[7]):(h=()=>()=>{m()},g=[m],t[5]=m,t[6]=h,t[7]=g),Z.useEffect(h,g);let _;t[8]!==m||t[9]!==f||t[10]!==l?(_=async()=>{f&&(await Un(l)).ok&&(m(),i(!0),typeof window<`u`&&(a.current=window.setTimeout(()=>{i(!1),a.current=null},2e3)))},t[8]=m,t[9]=f,t[10]=l,t[11]=_):_=t[11];let v=q(_),y;t[12]===o?y=t[13]:(y=o(`chat.messageBody.shellCommand.title`),t[12]=o,t[13]=y);let b;t[14]===y?b=t[15]:(b=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:y}),t[14]=y,t[15]=b);let x;t[16]!==d||t[17]!==o?(x=d&&d!==`completed`?(0,$.jsx)(`span`,{className:J(`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none`,d===`error`?`bg-[var(--status-error-background)] text-[var(--status-error)]`:`bg-foreground/5 text-muted-foreground`),role:d===`error`?`alert`:`status`,children:d===`running`?o(`chat.assistantStatus.runningCommand`):d===`pending`?o(`chat.statusRow.todo.status.pending`):d===`error`?o(`chat.toolPart.error`):d}):null,t[16]=d,t[17]=o,t[18]=x):x=t[18];let S;t[19]!==r||t[20]!==v||t[21]!==f||t[22]!==o?(S=f?(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`xs`,className:`ml-auto text-muted-foreground`,onClick:()=>{v()},"aria-label":o(r?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),title:o(r?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),children:(0,$.jsx)(X,{name:r?`check`:`file-copy`,className:`h-3.5 w-3.5`})}):null,t[19]=r,t[20]=v,t[21]=f,t[22]=o,t[23]=S):S=t[23];let C;t[24]!==S||t[25]!==b||t[26]!==x?(C=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[b,x,S]}),t[24]=S,t[25]=b,t[26]=x,t[27]=C):C=t[27];let w;t[28]===c?w=t[29]:(w=c?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 overflow-x-auto font-mono`,children:(0,$.jsx)(Td,{language:`bash`,code:c,codeStyle:XF,wrap:!0})}):null,t[28]=c,t[29]=w);let T;t[30]!==f||t[31]!==l?(T=f?(0,$.jsx)(`div`,{className:`mt-2 border-t border-border/60 pt-1.5`,children:(0,$.jsx)(`pre`,{className:`typography-meta max-h-56 overflow-auto whitespace-pre-wrap break-words font-mono text-foreground/85`,tabIndex:0,children:l})}):null,t[30]=f,t[31]=l,t[32]=T):T=t[32];let E;return t[33]!==C||t[34]!==w||t[35]!==T?(E=(0,$.jsxs)(`div`,{className:`min-w-0 rounded-lg border border-border/60 bg-[var(--surface-elevated)] px-3 py-2`,children:[C,w,T]}),t[33]=C,t[34]=w,t[35]=T,t[36]=E):E=t[36],E},QF=e=>{let t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`},$F=Z.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}=Wn(),w=Ix(),T=$b(Qb()),E=K(e=>e.timeFormatPreference),[D,O]=Z.useState(!1),k=Z.useRef(null),A=Z.useMemo(()=>n.filter(e=>e.type===`text`?!gD(e):!!(GF(e)||KF(e))),[n]),j=Z.useMemo(()=>A.map(e=>gi(e)?JO(hD(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=q(()=>{k.current!==null&&typeof window<`u`&&(window.clearTimeout(k.current),k.current=null)}),H=q(()=>{!I||!P||!L||typeof window>`u`||(V(),O(!0),k.current=window.setTimeout(()=>{O(!1),k.current=null},1800))});Z.useEffect(()=>{L||(O(!1),V())},[V,L]);let ee=q(e=>{!l||!L||(e.stopPropagation(),e.preventDefault(),l(),I&&H())}),U=w===`mini-chat`||!T.fork?void 0:h,te=Z.useMemo(()=>{if(typeof i!=`number`||i<=0)return null;let e=iP(i,E);return e.length>0?e:null},[S,i,E]),W=J(`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:J(OF,`justify-end`,!a&&b===`inline`&&`translate-x-5`,`pointer-events-auto opacity-100`),"data-message-action-group":`true`,children:[(0,$.jsxs)(`span`,{className:J(AF,`text-primary`),"aria-live":`polite`,children:[(0,$.jsx)(X,{weight:MF,name:`edit`,className:jF}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:C(`chat.messageBody.actions.editStaged`)})]}),y?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"aria-label":C(`chat.messageBody.actions.cancelEdit`),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),y()},children:(0,$.jsx)(X,{weight:MF,name:`close`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:C(`chat.messageBody.actions.cancelEdit`)})]}):null]})}):null,re=(_&&z?(0,$.jsx)(`div`,{className:W,children:(0,$.jsx)(`div`,{className:J(OF,`justify-end`,!a&&b===`inline`&&`translate-x-5`,`pointer-events-none opacity-100`),children:(0,$.jsx)(`span`,{className:J(AF,`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:J(OF,`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)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsxs)(`span`,{className:J(AF,`mr-1`),"aria-label":`Message time: ${te}`,children:[(0,$.jsx)(X,{weight:MF,name:`time`,className:jF}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:te})]})}),(0,$.jsx)(Ds,{children:te})]}):null,m&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"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)(X,{weight:MF,name:g===`revert`?`loader-4`:`arrow-go-back`,className:J(TF,g===`revert`&&`animate-spin`)})})}),(0,$.jsx)(Ds,{sideOffset:6,children:C(`chat.messageBody.actions.revert`)})]}),p&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"aria-label":C(`chat.messageBody.actions.editAria`),disabled:!!g,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),p()},children:(0,$.jsx)(X,{weight:MF,name:`edit`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:C(`chat.messageBody.actions.edit`)})]}),U&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"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)(X,{weight:MF,name:g===`fork`?`loader-4`:`git-branch`,className:J(TF,g===`fork`&&`animate-spin`)})})}),(0,$.jsx)(Ds,{sideOffset:6,children:C(`chat.messageBody.actions.fork`)})]}),P&&L&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":D||F?`true`:void 0,className:wF,"aria-label":C(`chat.messageBody.actions.copyMessageAria`),onPointerDown:e=>e.stopPropagation(),onClick:ee,onFocus:()=>O(!0),onBlur:()=>{F||O(!1)},children:F?(0,$.jsx)(X,{weight:MF,name:`check`,className:J(TF,`text-[color:var(--status-success)]`)}):(0,$.jsx)(X,{weight:MF,name:`file-copy`,className:TF})})}),(0,$.jsx)(Ds,{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:bF,onTouchStart:I&&P&&L?H:void 0,children:[(0,$.jsx)(`div`,{className:J(`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(GF(e))return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(JF,{part:e})},e.id??`user-subtask-${i}`);if(KF(e))return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(ZF,{part:e})},e.id??`user-shell-${i}`);let o=j[i];if(o)return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(YF,{notification:o})},e.id??`subagent-notification-${i}`);let s;return f&&M&&!N&&hD(e).includes(M)&&(s=f,N=!0),(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(xO,{part:e,messageId:t,isMobile:a,agentMention:s,messageParts:r??n})},e.id??`user-text-${i}`)})}),(0,$.jsx)($g,{files:n,messageID:t,sessionID:e,onShowPopup:d,compact:!0}),re]}):(0,$.jsx)($.Fragment,{children:re})}),eI=Z.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,reviewTransferAction:r,ttsText:i,sessionId:a})=>{let{t:o}=Wn(),s=Ix(),c=Qb(),l=$b(c),{isPlaying:u,play:d,stop:f}=DN(),p=ao(e=>e.showMessageTTSButtons),m=ao(e=>e.voiceProvider),[h,g]=Z.useState(!1),[_,v]=Z.useState(!1),[y,b]=Z.useState(!1),x=Z.useRef(null),S=Z.useRef(null),C=!!n,w=!!((c.sessionId||a)&&c.directory&&l.openSourceSession&&s!==`mini-chat`),T=q(()=>{x.current!==null&&typeof window<`u`&&(window.clearTimeout(x.current),x.current=null)}),E=q(()=>{S.current!==null&&typeof window<`u`&&(window.clearTimeout(S.current),S.current=null)});Z.useEffect(()=>()=>{T(),E()},[E,T]),Z.useEffect(()=>{(!e||!C)&&(g(!1),v(!1),T(),E())},[C,E,T,e]);let D=q(()=>{!t||!C||!e||typeof window>`u`||(T(),g(!0),x.current=window.setTimeout(()=>{g(!1),x.current=null},1800))}),O=q(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=q(async t=>{if(t.stopPropagation(),t.preventDefault(),!(!r||y||!e)){b(!0);try{await r.onClick()}finally{b(!1)}}}),A=q(e=>{e.stopPropagation(),e.preventDefault();let t=c.sessionId||a;!t||!c.directory||!c.openSourceSession||c.openSourceSession(t,c.directory)}),j=Z.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=q(e=>{if(e.stopPropagation(),e.preventDefault(),u){f();return}i.trim()&&d(i)});return(0,$.jsxs)($.Fragment,{children:[n&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":h||_?`true`:void 0,className:J(wF,!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)(X,{weight:MF,name:`check`,className:J(TF,`text-[color:var(--status-success)]`)}):(0,$.jsx)(X,{weight:MF,name:`file-copy`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:o(`chat.messageBody.actions.copyAnswer`)})]}),w?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"aria-label":o(`chat.messageBody.actions.openSourceSessionAria`),onPointerDown:e=>e.stopPropagation(),onClick:A,children:(0,$.jsx)(X,{weight:MF,name:`target`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:o(`chat.messageBody.actions.openSourceSession`)})]}):null,r&&s!==`mini-chat`&&l.reviewTransfer?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,size:`icon`,variant:`ghost`,disabled:y||!e,className:J(wF,(!e||y)&&`opacity-50`),"aria-label":r.ariaLabel,onPointerDown:e=>e.stopPropagation(),onClick:e=>{k(e)},children:y?(0,$.jsx)(X,{weight:MF,name:`loader-4`,className:J(TF,`animate-spin`)}):(0,$.jsx)(X,{weight:MF,name:`arrow-left-right`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:r.tooltip})]}):null,s!==`mini-chat`&&p&&e&&(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:J(wF,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)(X,{weight:MF,name:`stop`,className:TF}):(0,$.jsx)(X,{weight:MF,name:`volume-up`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:j})]})]})}),tI=Z.memo(({sessionId:e,messageId:t,parts:n,isMessageCompleted:r,messageFinish:i,messageCompletedAt:a,messageCreatedAt:o,isMobile:s,alwaysShowActions:c,hasTouchInput:l,expandedTools:u,onToggleTool:d,onShowPopup:f,streamPhase:p,allowAnimation:m,onContentChange:h,hasTextContent:g=!1,onCopyMessage:_,onAuxiliaryContentComplete:v,showReasoningTraces:y=!1,turnGroupingContext:b,errorPresentation:x,reviewTransferDirection:S=null})=>{let C=x?.text,{t:w,locale:T}=Wn(),E=Ix(),D=$b(Qb()),O=p,k=Z.useRef(null),A=Z.useRef(null),j=p===`streaming`||p===`cooldown`,M=Z.useRef({messageId:t,experiencedStreamingOrCooldown:j});M.current.messageId===t?j&&(M.current.experiencedStreamingOrCooldown=!0):M.current={messageId:t,experiencedStreamingOrCooldown:j};let N=!!(l??s),P=!!(c??s),F=s?DF:EF,I=!r,L=Z.useMemo(()=>n.filter(e=>!gD(e)).filter(e=>e.type!==`compaction`),[n]),R=Z.useMemo(()=>L.filter(e=>e.type===`tool`),[L]),z=Z.useMemo(()=>L.filter(e=>e.type===`text`),[L]),B=Z.useMemo(()=>xo(z),[z]),V=K(e=>e.openContextPreview),H=fe(),ee=E===`mini-chat`,U=Z.useMemo(()=>{if(H||s||ee)return null;for(let e of z){let t=e.text;if(typeof t!=`string`||t.length===0)continue;let n=Hu(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 R){let t=e.state,n=t&&typeof t.output==`string`?t.output:null;if(!n)continue;let r=Hu(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},[z,s,ee,H,R]),te=Y(e=>e.forkFromMessage),W=Y(e=>e.forkTransition),ne=Y(e=>e.currentSessionId),re=Y(e=>e.getDirectoryForSession),ie=qu(),ae=S===`review-to-original`,oe=!s&&!H?S:null,se=Z.useMemo(()=>{let t=B.trim();if(!(!e||!ie||!t||!oe))return oe===`review-to-original`?{ariaLabel:w(`chat.messageBody.actions.sendReviewFeedback`),tooltip:w(`chat.messageBody.actions.sendReviewFeedback`),onClick:async()=>{try{await Hi(e,ie,t)}catch(e){console.error(`[review-flow] failed to send review feedback`,e)}}}:{ariaLabel:w(`chat.messageBody.actions.sendImplementationResponse`),tooltip:w(`chat.messageBody.actions.sendImplementationResponse`),onClick:async()=>{try{await Ii(e,ie,t)}catch(e){console.error(`[review-flow] failed to send implementation response`,e)}}}},[B,ie,oe,e,w]),[ce,le]=Z.useState(!1),ue=K(e=>e.chatRenderMode),de=b?ue:`live`,pe=K(e=>e.collapsibleThinkingBlocks),me=K(e=>e.showSplitAssistantMessageActions),he=K(e=>e.showAssistantTps),ge=K(e=>e.timeFormatPreference),_e=de===`sorted`,ve=b?.isLastAssistantInTurn??!1,ye=i===`stop`,be=(ye||r||!!C)&&(b?.isTurnSettled??!0),xe=ye?`completed`:O,Se=R.length>0,Ce=Z.useMemo(()=>R.some(e=>nj(e)),[R]),we=nj,Te=tj,Ee=M.current.experiencedStreamingOrCooldown,De=Z.useRef({messageId:t,initialized:!1,observedPartIds:new Set});Z.useEffect(()=>{if(De.current.messageId!==t&&(De.current={messageId:t,initialized:!1,observedPartIds:new Set}),!Ee||!Go())return;let n=De.current,r=!n.initialized;n.initialized=!0;for(let i of R){if(n.observedPartIds.has(i.id))continue;if(!sr(r,we(i))){n.observedPartIds.add(i.id);continue}let a=e??i.sessionID;a&&(n.observedPartIds.add(i.id),Xr({sessionID:a,messageID:t,partID:i.id,kind:`tool`}))}},[Ee,we,t,e,R]);let Oe=Z.useMemo(()=>R.length===0||!Ce&&R.every(e=>Te(e)),[R,Ce,Te]),ke=Z.useMemo(()=>L.filter(e=>e.type===`reasoning`),[L]),Ae=Z.useMemo(()=>ke.length===0||ke.every(e=>typeof e.time?.end==`number`),[ke]),je=typeof i!=`string`,Me=ke.length>0&&Se&&(Ce||je||!Oe),Ne=I||Se&&(Ce||je||!Oe),Pe=I||Me,Fe=Se||ke.length>0,Ie=z.length===0,Le=Fe&&Ie&&!Ne&&!Pe&&Oe&&Ae,Re=Z.useRef(!1),ze=Z.useRef(!1);Z.useEffect(()=>{ze.current=!1},[t]),Z.useEffect(()=>{if(!Le){Re.current=!1;return}Re.current||(Re.current=!0,v?.())},[Le,v]),Z.useEffect(()=>{if(I){ze.current=!1;return}if(Se){ze.current=!1;return}ke.length!==0&&(Pe||!Ae||ze.current||(ze.current=!0,h?.(`structural`)))},[I,Se,h,Ae,ke.length,Pe]);let Be=!!g&&!I,Ve=q(async n=>{if(n.stopPropagation(),n.preventDefault(),!(!e||!t||ce||W)){le(!0);try{await te(e,t)}finally{le(!1)}}}),He=Z.useMemo(()=>{let e=b?.activityParts;return!_e||!e?[]:e},[_e,b?.activityParts]),Ue=Z.useMemo(()=>{let e=b?.activityGroupSegments;return!_e||!e?[]:e.filter(e=>e.anchorMessageId===t)},[_e,t,b?.activityGroupSegments]),We=Ue.length>0,Ge=Z.useMemo(()=>{let e=new Map,t=new Map;return He.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)}}},[He]),Ke=b?.toggleGroup,qe=b?.activityPresentationKind===`compaction`,Je=b?.isGroupExpanded===!0,Ye=_e&&qe&&!Je,Xe=_e?b?.activityOwnerMessageId===t||We:!b?.activityOwnerMessageId||b.activityOwnerMessageId===t||We,Ze=_e&&Xe&&(We||qe)&&!!Ke,Qe=nN(i,L),$e={finish:i,parts:L,streamPhase:xe,error:C,isLastAssistantInTurn:ve},et=sN($e),tt=_e&&cN($e),nt=_e&&!et&&!(qe&&Je),rt=Be,it=ve&&be&&x?.variant!==`error`&&!Ye&&(g||!!C||r),at=b?.diffStats?.hasDiffs===!0,ot=!ee&&ve&&Qe&&be&&!Ye&&b?.diffStats?.hasDiffs===!0,st=me&&rt&&!it&&!_e,ct=Z.useMemo(()=>(0,$.jsx)(eI,{hasCopyableText:Be,isTouchContext:N,onCopyMessage:_,ttsText:B,reviewTransferAction:se,sessionId:e}),[B,Be,N,_,se,e]),lt=Z.useMemo(()=>e=>{if(!me||!_e)return null;let t=hD(e.part).trim();return t?(0,$.jsx)(eI,{hasCopyableText:!0,isTouchContext:N,onCopyMessage:async()=>(await Un(t)).ok,ttsText:t}):null},[_e,N,me]),ut=Z.useMemo(()=>{if(!st)return-1;let e=-1;for(let t=0;t<L.length;t+=1){let n=L[t];!n||n.type!==`text`||nt||Ge.get(n)?.kind!==`justification`&&(e=t)}return e},[Ge,nt,st,L]),dt=st&&ut<0,ft=Z.useMemo(()=>{let n=[];if(Ze&&Ke&&b){let e=(e,t,r=t)=>{n.push((0,$.jsx)(`div`,{children:(0,$.jsx)(_F,{parts:t,materializationParts:r,isExpanded:b.isGroupExpanded===!0,collapsedPreviewCount:0,completionDisposition:b.completionDisposition,activityPresentationKind:b.activityPresentationKind,durationMs:b.durationMs,startedAt:b.userMessageCreatedAt,onToggle:Ke,isMobile:s,expandedTools:u,onToggleTool:d,onShowPopup:f,onContentChange:h,streamPhase:xe,showHeader:!0,diffStats:b.diffStats,renderJustificationActions:lt})},`progressive-group-${e}`))};Ue.length>0?Ue.forEach(t=>{let n=y?t.parts:t.parts.filter(e=>e.kind!==`reasoning`);e(t.id,n,t.parts)}):qe&&e(`${t}:compaction-status`,[])}let r=0;for(;r<L.length;){let i=L[r];if(i.type===`text`){let a=Ge.get(i);if(nt){r+=1;continue}if(Ye){r+=1;continue}if(a?.kind===`justification`){r+=1;continue}n.push((0,$.jsx)(`div`,{ref:A,"data-message-text-export-source":`true`,children:(0,$.jsx)(PM,{part:i,sessionId:e,messageId:t,streamPhase:xe,chatRenderMode:de,allowSortedFinalStreaming:tt,hasStreamingHapticLifecycle:Ee,onContentChange:h,onShowPopup:f})},`assistant-text-${t}-${i.id??r}`)),st&&r===ut&&n.push((0,$.jsx)(`div`,{className:s?CF:SF,"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:OF,"data-message-action-group":`true`,children:ct})},`message-actions-${t}`)),r++;continue}if(i.type===`reasoning`){if(Ge.get(i)?.kind===`reasoning`){r+=1;continue}if(!hD(i).trim()){r+=1;continue}y&&(pe?n.push((0,$.jsx)(`div`,{className:ky(s),children:(0,$.jsx)(KM,{part:i,messageId:t,streamPhase:xe,onContentChange:h})},`reasoning-${t}-${i.id??r}`)):n.push((0,$.jsx)(PM,{part:i,sessionId:e,messageId:t,streamPhase:xe,chatRenderMode:de,hasStreamingHapticLifecycle:Ee,onContentChange:h,onShowPopup:f},`reasoning-${t}-${i.id??r}`))),r++;continue}if(i.type===`tool`){let e=i,a=e.tool?.toLowerCase()??``;if(_e&&!Xe){r+=1;continue}if(Ge.get(i)?.kind===`tool`){r+=1;continue}if(ej(a)){let e=EP(L,r,e=>e.type!==`tool`||Ge.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)(kP,{activities:i,isMobile:s,isTurnLive:xe!==`completed`,hasFollowingOtherType:wP(L,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 ZA(n)?(0,$.jsx)(lF,{toolName:n,activities:[e],isMobile:s,animateTailText:!1},e.id):(0,$.jsx)(mM,{part:e.part,messageId:t,isExpanded:u.has(e.part.id),onToggle:d,isMobile:s,alwaysShowActions:P,onContentChange:h,onShowPopup:f,animateTailText:!1},e.id)})},`context-tools-${i[0].id}`)),r=e.end;continue}}if(QA(a)){let e=AP(L,r,e=>e.type!==`tool`||Ge.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)(FP,{activities:i,isMobile:s,children:i.map(e=>(0,$.jsx)(lF,{toolName:e.part.tool?.toLowerCase()??``,activities:[e],isMobile:s,animateTailText:!1},e.id))},`skill-tools-${i[0].id}`)),r=e.end;continue}}if(JA(a)){n.push((0,$.jsx)(`div`,{className:ky(s),children:(0,$.jsx)(mM,{part:e,messageId:t,isExpanded:u.has(e.id),onToggle:d,isMobile:s,alwaysShowActions:P,onContentChange:h,onShowPopup:f,animateTailText:!1})},`tool-${e.id}`)),r++;continue}n.push((0,$.jsx)(`div`,{className:ky(s),children:(0,$.jsx)(lF,{toolName:a,activities:[{id:e.id,turnId:``,messageId:t,partIndex:r,part:e,kind:`tool`}],isMobile:s,animateTailText:!1})},`static-tools-${e.id}`)),r++;continue}r++}let i=n.at(-1);if(Z.isValidElement(i)&&i.props[`data-message-text-export-source`]===`true`&&xe!==`completed`&&!be&&!x&&(!b||b.isLastAssistantInTurn)){let e=i;n[n.length-1]=Z.cloneElement(e,{className:J(typeof e.props.className==`string`?e.props.className:void 0,s?`pb-1`:`pb-1.5`),"data-live-status-text-gap":``})}return n},[Ge,Ue,P,de,pe,0,u,Ye,qe,s,Xe,_e,ut,t,ct,lt,e,h,f,d,Ze,st,xe,x,Ee,be,y,nt,tt,Ke,b,L]),pt=Z.useMemo(()=>{if(!ve||!be)return;let e=b?.durationMs;if(!(typeof e!=`number`||e<=0))return QF(e)},[ve,be,b?.durationMs]),mt=Z.useMemo(()=>{let e=typeof a==`number`&&a>0?a:typeof o==`number`&&o>0?o:null;if(e===null)return null;let t=iP(e,ge);return t.length>0?t:null},[a,o,ge,T]),ht=Z.useMemo(()=>{if(!he||!ve||x?.variant===`error`)return null;let e=b?.assistantTps;if(!cP({completionDisposition:b?.completionDisposition,tps:e}))return null;let t=lP(e??0);return t.length>0?t:null},[he,x?.variant,ve,b?.assistantTps,b?.completionDisposition]),gt=(0,$.jsxs)($.Fragment,{children:[!ee&&!s&&!H&&U?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`icon`,className:wF,"aria-label":w(`chat.messageBody.actions.openPreviewAria`),onPointerDown:e=>e.stopPropagation(),onClick:()=>{let e=ie??(ne?re(ne):null);e&&V(e,U)},children:(0,$.jsx)(X,{weight:MF,name:`global`,className:TF})})}),(0,$.jsx)(Ds,{sideOffset:6,children:w(`chat.messageBody.actions.openPreview`)})]}):null,!ee&&!ae&&D.fork?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{type:`button`,size:`icon`,variant:`ghost`,className:wF,"aria-label":w(`chat.messageBody.actions.forkAria`),"aria-busy":ce,disabled:ce||!!W,onPointerDown:e=>e.stopPropagation(),onClick:e=>{Ve(e)},children:(0,$.jsx)(X,{weight:MF,name:ce?`loader-4`:`git-branch`,className:J(TF,ce&&`animate-spin`)})})}),(0,$.jsx)(Ds,{sideOffset:6,children:w(`chat.messageBody.actions.fork`)})]}):null]});return(0,$.jsxs)(`div`,{ref:k,"data-message-text-export-root":`true`,className:J(`relative w-full group/message`),style:bF,children:[(0,$.jsx)(eP,{containerRef:k}),(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:[ft,x&&(0,$.jsx)(td,{children:(0,$.jsx)(`div`,{className:`my-1.5`,"data-assistant-error":x.variant,children:(0,$.jsx)(yF,{presentation:x,sessionId:e,messageId:t,directory:ie??void 0})})},`assistant-error`)]}),ot&&b?.diffStats?(0,$.jsx)(WF,{fileCount:b.diffStats.files,changedFiles:b.changedFiles,turnId:b.turnId,isLatestTurn:b.isLatestTurn,isMobile:s}):null,(0,$.jsx)($g,{files:n,messageID:t,sessionID:e,onShowPopup:f}),dt&&(0,$.jsx)(`div`,{className:J(s?CF:SF),"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:OF,"data-message-action-group":`true`,children:ct})}),it&&(0,$.jsxs)(`div`,{className:F,"data-message-footer":`true`,style:xF,children:[(0,$.jsxs)(`div`,{className:OF,"data-message-action-group":`true`,children:[ct,gt]}),ht||pt||mt?(0,$.jsxs)(`div`,{className:kF,children:[ht?(0,$.jsx)(NF,{label:ht}):null,pt?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsxs)(`span`,{className:AF,children:[(0,$.jsx)(X,{weight:MF,name:`hourglass`,className:jF}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:pt})]})}),(0,$.jsx)(Ds,{children:pt})]}):null,mt?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsxs)(`span`,{className:AF,"aria-label":`Message time: ${mt}`,children:[(0,$.jsx)(X,{weight:MF,name:`time`,className:jF}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:mt})]})}),(0,$.jsx)(Ds,{children:mt})]}):null]}):null,!ee&&ve&&ye&&!at?(0,$.jsx)(XM,{activityParts:b?.activityParts}):null]}),!it&&!Ye&&ht?(0,$.jsx)(`div`,{className:F,"data-message-footer":`true`,"data-message-tps":`interrupted`,style:xF,children:(0,$.jsx)(`div`,{className:kF,children:(0,$.jsx)(NF,{label:ht})})}):null]})]})}),nI=Z.memo(e=>{let t=(0,Q.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)($F,{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)(tI,{...r}),t[26]=r,t[27]=i),i});function rI(e){return e.openContextPanelTab}function iI(e){return e.setCurrentSession}function aI(e){return e.openContextPanelTab}function oI(e){return!e}function sI(e){return e.openContextPanelTab}var cI=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}},lI=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},uI={"provider.rate-limit":`chat.response.rateLimit`,"provider.auth":`chat.response.auth`,"provider.quota":`chat.response.quota`,"provider.content-filter":`chat.response.contentFilter`,"provider.transport":`chat.response.transport`,"provider.internal":`chat.response.internal`,"provider.invalid-output":`chat.response.invalidOutput`,"provider.invalid-request":`chat.response.invalidRequest`,"provider.unsupported-operation":`chat.response.unsupportedOperation`,"provider.no-route":`chat.response.noRoute`,"provider.unknown":`chat.response.providerUnknown`,"provider.timeout":`chat.response.timeout`,"permission.rejected":`chat.response.permissionRejected`,"tool.execution":`chat.response.toolExecution`,"compaction.failed":`chat.response.compactionFailed`,"compaction.unavailable":`chat.response.compactionUnavailable`,"compaction.interrupted":`chat.response.compactionInterrupted`},dI={icon:`pause-circle`,variant:`muted`};function fI(e,t){if(!e||typeof e!=`object`)return;let n=e,r=typeof n.data?.message==`string`?n.data.message:typeof n.message==`string`?n.message:void 0,i=typeof n.name==`string`?n.name:void 0,a=typeof n.type==`string`?n.type.trim():void 0,o=typeof n.status==`number`&&Number.isInteger(n.status)&&n.status>=100&&n.status<=599?n.status:void 0;if(!r&&!a&&!i&&o===void 0)return;let s=[a&&a!==`unknown`&&a!==`error`?a:void 0,o].filter(e=>e!==void 0).join(` · `)||void 0,c=(e,n,i=`error`,a=!1)=>({text:t(e),icon:n,variant:i,...r&&!a?{rawMessage:r}:{},...s?{detail:s}:{}});if(i===`SessionRetry`)return c(`chat.response.retrying`,`refresh`,`info`);if(a===`aborted`)return r===`Execution was interrupted repeatedly and will not be resumed automatically.`?c(`chat.response.resumeExhausted`,`error-warning`,`error`,!0):r===`Session interrupted by user`?c(`chat.response.stopped`,`stop-circle`,`muted`,!0):r===`Compaction cancelled`?c(`chat.response.compactionCancelled`,`stop-circle`,`muted`,!0):r===`Tool execution interrupted`?c(`chat.response.toolInterrupted`,dI.icon,dI.variant,!0):c(`chat.response.interrupted`,dI.icon,dI.variant,r===`Step interrupted`);if(i===`MessageAbortedError`||!a&&r?.trim().toLowerCase()===`aborted`)return c(`chat.response.stopped`,`stop-circle`,`muted`,!0);if(a&&Object.hasOwn(uI,a)){if(a===`compaction.interrupted`)return c(uI[a],dI.icon,dI.variant,r===`Compaction was interrupted`);if(a===`compaction.unavailable`)return c(uI[a],`information`,`info`,r===`Nothing to compact yet`);let e=a===`provider.auth`||a===`permission.rejected`?`lock`:a===`provider.timeout`?`time`:`error-warning`;return c(uI[a],e)}return(!a||a===`unknown`||a===`error`)&&lI(r)?c(`chat.response.auth`,`lock`):{...c(`chat.response.failed`,`error-warning`),...!r&&i?{rawMessage:i}:{}}}function pI(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.nativeType===`synthetic`&&t.description===`Continuing after restart`}function mI(e,t){if(pI(e))return{text:t(`chat.response.continuingAfterRestart`),icon:`restart`,variant:`info`}}function hI(e){return!e}function gI(e){let t=(0,Q.c)(60),{part:n,isMobile:r}=e,i=r!==void 0&&r,{t:a}=Wn(),o;t[0]!==n.id||t[1]!==n.messageID||t[2]!==n.sessionID?(o=JSON.stringify([n.sessionID,n.messageID,n.id]),t[0]=n.id,t[1]=n.messageID,t[2]=n.sessionID,t[3]=o):o=t[3];let s=o,{expanded:c,toggle:l}=sO(s),u=(0,Z.useId)(),d;t[4]!==s||t[5]!==l?(d=()=>l(s),t[4]=s,t[5]=l,t[6]=d):d=t[6];let f=q(d),p=n.status===`running`,m=n.status===`failed`,h;t[7]!==m||t[8]!==p||t[9]!==a?(h=a(p?`chat.activity.compacting`:m?`chat.activity.compactionFailed`:`chat.activity.compactionCompleted`),t[7]=m,t[8]=p,t[9]=a,t[10]=h):h=t[10];let g=h,_;t[11]!==m||t[12]!==n.error||t[13]!==a?(_=m?fI(n.error,a):void 0,t[11]=m,t[12]=n.error,t[13]=a,t[14]=_):_=t[14];let v=_,y;t[15]!==m||t[16]!==n.summary?(y=m?``:n.summary?.trim()??``,t[15]=m,t[16]=n.summary,t[17]=y):y=t[17];let b=y,x,S,C,w,T,E,D,O,k;if(t[18]!==u||t[19]!==c||t[20]!==v?.text||t[21]!==m||t[22]!==i||t[23]!==p||t[24]!==n.status||t[25]!==b||t[26]!==g||t[27]!==f){let e=J(`shrink-0 typography-meta`,m?`text-[var(--status-error)]/85`:`text-muted-foreground`);E=`w-full min-w-0`,D=``,O=n.status;let r=i?`min-h-7`:`min-h-8`;t[37]===r?k=t[38]:(k=J(`flex w-full items-center gap-3`,r),t[37]=r,t[38]=k),x=`separator`,S=p?`polite`:void 0,C=v?.text??g,t[39]===Symbol.for(`react.memo_cache_sentinel`)?(w=(0,$.jsx)(`span`,{className:`min-w-0 flex-1 border-t`,"aria-hidden":`true`}),t[39]=w):w=t[39],T=b?(0,$.jsxs)(Jn,{variant:`ghost`,size:`sm`,className:J(e,jy),"aria-expanded":c,"aria-controls":u,onClick:f,children:[g,(0,$.jsx)(X,{name:`arrow-down-s`,className:J(`size-4 transition-transform`,c&&`rotate-180`)})]}):(0,$.jsx)(`span`,{className:e,children:g}),t[18]=u,t[19]=c,t[20]=v?.text,t[21]=m,t[22]=i,t[23]=p,t[24]=n.status,t[25]=b,t[26]=g,t[27]=f,t[28]=x,t[29]=S,t[30]=C,t[31]=w,t[32]=T,t[33]=E,t[34]=D,t[35]=O,t[36]=k}else x=t[28],S=t[29],C=t[30],w=t[31],T=t[32],E=t[33],D=t[34],O=t[35],k=t[36];let A;t[40]===Symbol.for(`react.memo_cache_sentinel`)?(A=(0,$.jsx)(`span`,{className:`min-w-0 flex-1 border-t`,"aria-hidden":`true`}),t[40]=A):A=t[40];let j;t[41]!==x||t[42]!==S||t[43]!==C||t[44]!==w||t[45]!==T||t[46]!==D||t[47]!==O||t[48]!==k?(j=(0,$.jsxs)(`div`,{"data-compaction-card":D,"data-compaction-status":O,className:k,role:x,"aria-live":S,"aria-label":C,children:[w,T,A]}),t[41]=x,t[42]=S,t[43]=C,t[44]=w,t[45]=T,t[46]=D,t[47]=O,t[48]=k,t[49]=j):j=t[49];let M;t[50]!==u||t[51]!==c||t[52]!==p||t[53]!==n.messageID||t[54]!==b?(M=b&&c?(0,$.jsx)(`div`,{id:u,className:`py-2`,children:(0,$.jsx)(Tu,{content:b,messageId:n.messageID,isStreaming:p})}):null,t[50]=u,t[51]=c,t[52]=p,t[53]=n.messageID,t[54]=b,t[55]=M):M=t[55];let N;return t[56]!==E||t[57]!==j||t[58]!==M?(N=(0,$.jsxs)(`div`,{className:E,children:[j,M]}),t[56]=E,t[57]=j,t[58]=M,t[59]=N):N=t[59],N}var _I=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},vI=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.model==`object`&&t.model!==null?t.model:void 0,r=typeof t.metadata==`object`&&t.metadata!==null?t.metadata:void 0,i=typeof r?.model==`object`&&r.model!==null?r.model:void 0,a=_I(t.mode)??_I(t.agent)??_I(r?.agent),o=_I(t.providerID)??_I(n?.providerID)??_I(i?.providerID),s=_I(t.modelID)??_I(n?.modelID)??_I(n?.id)??_I(i?.modelID)??_I(i?.id),c=_I(n?.variant)??_I(i?.variant)??_I(t.variant)??_I(r?.variant);return!a&&!o&&!s&&!c?null:{agentName:a,providerId:o,modelId:s,variant:c}},yI=e=>{let t=e?.providerId?.trim(),n=e?.modelId?.trim();return!t||!n?null:{providerId:t,modelId:n}},bI=e=>yI(e.assistantIdentity)??yI(e.userIdentity)??(e.allowComposerFallback?yI(e.composerSelection):null)??yI(e.sessionSelection),xI=e=>{let t=e?.modelId??null;return{providerID:e?.providerId??null,modelID:t,agentName:e?.agentName,modelName:hr(void 0,t)||void 0,variant:e?.variant}},SI=e=>!(!e.isLastTurn||!e.sessionIsWorking||e.hasAssistantMessages||e.activityPresentationKind===`compaction`||e.hasActiveStreamingMessage),CI=(e,t,n)=>e===`active`||n?.isLastTurn&&n.hasConfirmedFinalBody!==!0?!0:t===`summary`,wI=e=>!e,TI=e=>e.completionDisposition===`active`?e.isLastTurn&&e.sessionIsWorking?{completionDisposition:`active`,durationMs:e.durationMs}:{completionDisposition:`abnormal`,durationMs:e.durationMs}:{completionDisposition:e.completionDisposition,durationMs:e.durationMs},EI=e=>!(e.completionDisposition===`active`||e.isLastTurn&&e.sessionIsWorking&&!e.hasConfirmedSettledAssistant),DI=e=>e.isWorking?!0:e.isInActiveTurn?e.headerCompletionDisposition!==`normal`&&e.headerCompletionDisposition!==`abnormal`:!1,OI=e=>e.turnCompletionDisposition===`active`&&(e.isLastTurn||e.hasAssistantMessages)?`active`:e.headerPresentationDisposition,kI=e=>{let t=e.info;return(typeof t.clientRole==`string`?t.clientRole:null)??(typeof t.role==`string`?t.role:null)??null},AI=e=>{let t=e.info;return typeof t.parentID==`string`&&t.parentID.length>0?t.parentID:null},jI=e=>!e||kI(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`)}),MI=e=>kI(e)===`user`?jI(e)||e.parts.some(e=>{let t=e.shellAction;return e.type===`text`&&typeof t==`object`&&!!t}):!1,NI=(e,t)=>{if(kI(e)!==`assistant`||t&&AI(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}}},PI=(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(kI(t)===`user`)break;let{hide:i,details:a}=NI(t,r);if(i){let e=typeof a?.command==`string`?a.command.trim():``;return e.length>0?e:null}}return null},FI=Cu(()=>Sn(()=>import(`./ToolOutputDialog-izZjgkkg.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]))),II=4e3,LI=new Map,RI=new Map,zI=new Set([`bash`,`shell`,`cmd`,`terminal`]),BI=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},VI=e=>{let t=LI.get(e);return t?new Set(t):new Set},HI=(e,t)=>{if(LI.size>=II&&!LI.has(e)){let e=LI.keys().next().value;typeof e==`string`&&LI.delete(e)}LI.set(e,new Set(t))},UI=e=>{let t=RI.get(e);return t?new Set(t):new Set},WI=(e,t)=>{if(RI.size>=II&&!RI.has(e)){let e=RI.keys().next().value;typeof e==`string`&&RI.delete(e)}RI.set(e,new Set(t))},GI=200,KI=new Map,qI=e=>KI.get(e),JI=(e,t)=>{if(!t.agent&&!t.provider&&!t.model)return;let n=KI.get(e);if(!(n&&n.agent===t.agent&&n.provider===t.provider&&n.model===t.model)){if(KI.size>=GI&&!KI.has(e)){let e=KI.keys().next().value;typeof e==`string`&&KI.delete(e)}KI.set(e,t)}};function YI(e){let t=(0,Q.c)(3),[n,r]=Z.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),Z.useEffect(i,a),e??n}var XI=(e,t)=>{if(typeof e==`object`&&e)return e[t]},ZI=Z.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}=Wn(),{isMobile:m,isTablet:h,hasTouchInput:g}=Oc(),_=Qb(),v=$b(_),y=m||h,b=Z.useRef(null),x=Y(e=>e.currentSessionId),S=Y(e=>e.revertToMessage),C=Y(e=>e.editMessagePreservingChanges),w=Y(e=>e.forkFromMessage),T=Y(t=>t.messageEditCommitting?.messageId===e.info.id&&t.messageEditCommitting?.sessionId===e.info.sessionID),E=Y(t=>t.stagedMessageEdit?.messageId===e.info.id&&t.stagedMessageEdit?.sessionId===e.info.sessionID),D=Y(e=>e.clearStagedMessageEdit);Gt(`ui.chat_message.render`),c&&Gt(`ui.chat_message.render.streaming`);let O=ao(e=>e.providers),{showReasoningTraces:k,stickyUserHeader:A,chatRenderMode:j,showExpandedBashTools:M}=K(Je(e=>({showReasoningTraces:e.showReasoningTraces,stickyUserHeader:e.stickyUserHeader,chatRenderMode:e.chatRenderMode,showExpandedBashTools:e.showExpandedBashTools})));Z.useEffect(()=>{x&&lO.getInstance().recordSessionStart(x)},[x]);let[N,P]=Z.useState(null),[F,I]=Z.useState(!1),[L,R]=Z.useState(null),z=Z.useRef(null),[B,V]=Z.useState(()=>VI(e.info.id)),[H,ee]=Z.useState(()=>UI(e.info.id)),[U,te]=Z.useState({open:!1,title:``,content:``});Z.useEffect(()=>{V(VI(e.info.id)),ee(UI(e.info.id))},[e.info.id]);let W=Z.useMemo(()=>cI(e.info),[e.info]).isUser,ne=Z.useMemo(()=>st(e.parts),[e.parts]),re=W&&(m||!A),ie=W&&!m&&A&&!re,ae=e.info.sessionID,{currentContextAgent:oe,savedSessionAgentSelection:se}=Ky(Je(e=>({currentContextAgent:c&&ae?e.currentAgentContext.get(ae):void 0,savedSessionAgentSelection:c&&ae?e.sessionAgentSelections.get(ae):void 0}))),ce=Z.useMemo(()=>mD(e.sourceParts??e.parts),[e.parts,e.sourceParts]),le=Z.useMemo(()=>W?DD(ce):mD(e.parts),[W,e.parts,ce]),ue=Z.useMemo(()=>{if(W||!t)return null;let e=XI(t.info,`clientRole`),n=XI(t.info,`role`);return(typeof e==`string`?e:typeof n==`string`?n:void 0)===`user`&&vI(t.info)||null},[W,t]),de=Z.useMemo(()=>{if(W)return;let t=XI(e.info,`mode`);if(typeof t==`string`&&t.trim().length>0)return t;let n=XI(e.info,`agent`);if(typeof n==`string`&&n.trim().length>0)return n;if(ue?.agentName)return ue.agentName;if(ae)return oe||(se??void 0)},[W,e.info,ue,ae,oe,se]),fe=W?null:vI(e.info),pe=fe?.providerId??null,me=fe?.modelId??null,he=zo(Je(e=>{if(W||!ae)return null;if(ue?.providerId&&ue?.modelId)return{providerId:ue.providerId,modelId:ue.modelId};if(de){let t=e.getAgentModelForSession(ae,de);if(t?.providerId&&t?.modelId)return t}let t=e.getSessionModelSelection(ae);return t?.providerId&&t?.modelId?t:null})),ge=Z.useMemo(()=>W?null:typeof pe==`string`&&pe.trim().length>0?pe:he?.providerId??null,[W,pe,he]),_e=Z.useMemo(()=>W?null:typeof me==`string`&&me.trim().length>0?me:he?.modelId??null,[W,me,he]),ve=e.info.id?qI(e.info.id):void 0;W||JI(e.info.id,{agent:de,provider:ge??void 0,model:_e??void 0});let ye=de??ve?.agent,be=ge??ve?.provider??null,xe=_e??ve?.model??null,Se=Z.useMemo(()=>{if(W)return;let e=be&&O.length>0?O.find(e=>e.id===be):void 0;return hr(e,xe)||void 0},[W,be,xe,O]),Ce=Z.useMemo(()=>{if(W||!ge||!_e)return!1;let e=O.find(e=>e.id===ge);if(!e?.models||!Array.isArray(e.models))return!1;let t=e.models.find(e=>e.id===_e)?.variants;return!!(t&&Object.keys(t).length>0)},[W,_e,ge,O]),we=YI(ye),Te=YI(be??void 0),Ee=YI(xe??void 0),De=YI(Se),Oe=we??void 0,ke=Te??null,Ae=Ee??null,je=De??void 0,Me=Z.useMemo(()=>{let t=e.info.time;return typeof t?.completed==`number`?t.completed:null},[e.info.time]),Ne=Z.useMemo(()=>{let t=e.info.time;return typeof t?.created==`number`?t.created:null},[e.info.time]),Pe=Z.useMemo(()=>W?!0:!!(Me&&Me>0),[W,Me]),Fe=Z.useMemo(()=>{let t=e.info.finish;return typeof t==`string`?t:void 0},[e.info]),Ie=Z.useMemo(()=>_D(le,{includeReasoning:k}),[le,k]),Le=Z.useMemo(()=>W?Ie:!Pe&&j===`sorted`?[]:Ie,[j,Pe,W,Ie]),Re=Z.useMemo(()=>W?[]:Ie.filter(e=>e.type===`text`),[W,Ie]),ze=Z.useMemo(()=>W?[]:Ie.filter(e=>e.type===`tool`),[W,Ie]),Be=Z.useMemo(()=>{if(!M)return new Set;let e=new Set;for(let t of ze){let n=typeof t?.id==`string`?t.id:``;if(!n)continue;let r=BI(t.tool);!r||!zI.has(r)||e.add(n)}for(let t of a?.activityParts??[]){if(t.kind!==`tool`)continue;let n=BI(t.part.tool);!n||!zI.has(n)||e.add(t.id)}return e},[M,ze,a?.activityParts]),Ve=Z.useMemo(()=>{if(Be.size===0&&H.size===0)return B;let e=new Set(B);return Be.forEach(t=>{H.has(t)||e.add(t)}),H.forEach(t=>{e.delete(t)}),e},[H,Be,B]),He=Z.useMemo(()=>{if(!W)return;let e=le.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}`}},[W,le]),Ue=W&&!OD(Le),We=typeof Fe!=`string`,Ge=Z.useMemo(()=>W?!1:Re.length===0||ze.length===0?We:!0,[Re.length,ze.length,We,W]),Ke=Z.useMemo(()=>!W&&lO.getInstance().shouldAnimateMessage(e.info,x||e.info.sessionID),[e.info,x,W]),[qe,Ye]=Z.useState(!1),Xe=Z.useMemo(()=>n?cI(n.info):null,[n]),Ze=!!a,Qe=a?.isLastAssistantInTurn??!1,$e=DI({isWorking:a?.isWorking===!0,isInActiveTurn:c,headerCompletionDisposition:a?.completionDisposition}),et=Z.useMemo(()=>W?!1:Ze?!Qe:Xe?!Xe.isUser&&Xe.role===`assistant`:!1,[Ze,Qe,W,Xe]),tt=Z.useMemo(()=>Pe?`completed`:c?l??`streaming`:`completed`,[l,c,Pe]);Z.useEffect(()=>{!W||!u||d?.(e.info.id)},[u,W,e.info.id,d]),Z.useEffect(()=>{Ye(!1)},[e.info.id]),Z.useEffect(()=>{let t=o??a?.headerMessageId;W||!t||t!==e.info.id||(tt===`streaming`||tt===`cooldown`)&&Ye(!0)},[o,W,e.info.id,tt,a?.headerMessageId]);let nt=Z.useMemo(()=>{if(W)return!0;if(s)return!1;let t=o??a?.headerMessageId;return t?e.info.id===t?tt===`completed`||qe||tt===`streaming`||tt===`cooldown`:!1:!0},[o,qe,W,a,tt,e.info.id,s]),rt=Z.useCallback(e=>{Un(e).then(t=>{t.ok&&(P(e),setTimeout(()=>P(null),2e3))})},[]),it=W?void 0:a?.userMessageVariant??ue?.variant,at=!W&&Ce&&typeof it==`string`&&it.trim().length>0?it:void 0,ot=Z.useMemo(()=>{if(!W&&!hI(Ze?Qe:!et))return fI(e.info?.error,p)},[Ze,et,Qe,W,e.info,p]),ct=ot?.text,lt=Z.useMemo(()=>{if(W){let e=Le.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(`
|
|
6595
6595
|
|
|
6596
6596
|
`);let t=Le.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(`
|
|
6597
6597
|
`):Le.filter(e=>e.type===`text`).map(e=>(e.text||e.content||``).trim()).filter(e=>e.length>0).join(`
|
|
@@ -6600,7 +6600,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}f
|
|
|
6600
6600
|
`),[i]),s=Pd(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:J(`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)(UV,{content:e.content,html:n})})]},t)})})]},n))})},GV=e=>{let t=(0,Q.c)(21),{content:n,filePath:r}=e,{currentTheme:i}=Tc(),a;t[0]===i?a=t[1]:(a=Pc(i),t[0]=i,t[1]=a);let o=a,s;t[2]===n?s=t[3]:(s=n.split(`
|
|
6601
6601
|
`),t[2]=n,t[3]=s);let c=s,l;t[4]===r?l=t[5]:(l=Wu(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=Pd(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)(UV,{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},KV=new Set([`id`,`identifier`,`title`,`name`]),qV=e=>typeof e==`object`&&!!e&&!Array.isArray(e),JV=e=>e.replace(/([A-Z])/g,` $1`).replace(/[_-]/g,` `).replace(/^./,e=>e.toUpperCase()),YV=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},XV=e=>{try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}},ZV=Z.memo(e=>{let t=(0,Q.c)(54),{value:n,label:r,depth:i}=e;if(Array.isArray(n)){let e;t[0]!==r||t[1]!==n.length?(e=r?`${JV(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)(X,{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)(ZV,{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(qV(n)){let e;t[18]===n?e=t[19]:(e=YV(n),t[18]=n,t[19]=e);let a=e,o;t[20]===n?o=t[21]:(o=Object.entries(n).filter($V),t[20]=n,t[21]=o);let s=o,c;t[22]!==a||t[23]!==r?(c=r?`${JV(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)(ZV,{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)(X,{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?JV(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`&&XV(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:J(`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:JV(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});ZV.displayName=`JsonSummaryValue`;var QV=Z.memo(e=>{let t=(0,Q.c)(2),{data:n}=e,r;return t[0]===n?r=t[1]:(r=(0,$.jsx)(`div`,{className:`space-y-1`,children:(0,$.jsx)(ZV,{value:n,depth:0})}),t[0]=n,t[1]=r),r});QV.displayName=`JsonSummaryView`;function $V(e){let[t]=e;return!KV.has(t)}function eH(e){let t=(0,Q.c)(20),{header:n,children:r,footer:i,afterBody:a,mobile:o,questionCard:s,onInteraction:c}=e,l=o!==void 0&&o,u=s!==void 0&&s?``:void 0,d=l?`px-3 py-2`:`px-2 py-1.5`,f;t[0]===d?f=t[1]:(f=J(`border-b border-border/20`,d),t[0]=d,t[1]=f);let p;t[2]!==n||t[3]!==f?(p=(0,$.jsx)(`div`,{className:f,children:n}),t[2]=n,t[3]=f,t[4]=p):p=t[4];let m=l?`px-3 py-3`:`px-2 py-2`,h;t[5]===m?h=t[6]:(h=J(m),t[5]=m,t[6]=h);let g;t[7]!==r||t[8]!==h?(g=(0,$.jsx)(`div`,{className:h,children:r}),t[7]=r,t[8]=h,t[9]=g):g=t[9];let _;t[10]!==i||t[11]!==l?(_=i?(0,$.jsx)(`div`,{className:J(`flex flex-wrap items-center gap-1.5 border-t border-border/20`,l?`px-3 py-2`:`px-2 pb-1.5 pt-1`),children:i}):null,t[10]=i,t[11]=l,t[12]=_):_=t[12];let v;return t[13]!==a||t[14]!==c||t[15]!==_||t[16]!==u||t[17]!==p||t[18]!==g?(v=(0,$.jsx)(`div`,{className:`group w-full pt-0 pb-2`,children:(0,$.jsx)(`div`,{className:`chat-column`,children:(0,$.jsxs)(`div`,{"data-interaction-card":!0,"data-question-card":u,className:`-mt-1 overflow-hidden rounded-xl border border-border/30 bg-muted/10`,onPointerDownCapture:c,onClickCapture:c,onKeyDownCapture:c,onInputCapture:c,onPasteCapture:c,onCompositionStartCapture:c,children:[p,g,a,_]})})}),t[13]=a,t[14]=c,t[15]=_,t[16]=u,t[17]=p,t[18]=g,t[19]=v):v=t[19],v}var tH={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`},nH={style:{whiteSpace:`pre-wrap`,wordBreak:`break-word`,overflowWrap:`break-word`}},rH=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)(X,{name:`pencil-ai`,className:t}):n===`write`||n===`create`||n===`file_write`?(0,$.jsx)(X,{name:`file-edit`,className:t}):n===`bash`||n===`shell`||n===`cmd`||n===`terminal`||n===`shell_command`?(0,$.jsx)(X,{name:`terminal-box`,className:t}):n===`webfetch`||n===`fetch`||n===`curl`||n===`wget`?(0,$.jsx)(X,{name:`global`,className:t}):(0,$.jsx)(X,{name:`tools`,className:t})},iH=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},aH=e=>e===`filepath`||e===`file_path`?`filePath`:e===`parentDir`||e===`parent_dir`?`parentDirectory`:e,oH=e=>{let t=(0,Q.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)(QV,{data:n})}),t[0]=n,t[1]=r),r},sH=({permission:e,onResponse:t})=>{let{t:n}=Wn(),r=K(e=>e.isMobile),[i,a]=Z.useState(!1),[o,s]=Z.useState(!1),c=Ra,l=Ao(),u=Y(e=>e.currentSessionId),d=Z.useMemo(()=>{if(!u||e.sessionID===u)return!1;let t=l.find(t=>t.id===e.sessionID);return!!(t?.parentID&&t.parentID===u)},[e.sessionID,u,l]),f=async n=>{a(!0);try{await c(e.sessionID,e.id,n),s(!0),t?.(n)}catch(e){console.error(`[PermissionCard] Failed to respond to permission:`,e)}finally{a(!1)}};if(o)return null;let p=e.permission||`unknown`,m=p.toLowerCase(),h=(t,n=``)=>{let r=e.metadata[t];return typeof r==`string`?r:typeof r==`number`?String(r):n},g=t=>{let n=e.metadata[t];return typeof n==`number`?n:void 0},_=t=>!!e.metadata[t],v=iH(p),y=Object.fromEntries(Object.entries(e.metadata).filter(([e])=>e!==`always`).map(([e,t])=>[aH(e),t]));return(0,$.jsx)(eH,{mobile:r,header:(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)(X,{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`)}),d?(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:[rH(p),(0,$.jsx)(`span`,{className:`truncate text-xs leading-4 sm:text-[length:var(--text-meta)] text-muted-foreground font-medium`,children:v})]})]}),footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`grid w-full grid-cols-1 gap-1.5 sm:flex sm:items-center sm:flex-wrap`,children:[(0,$.jsxs)(Jn,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(`once`),disabled:i,className:`min-h-9 min-w-0 w-full gap-1.5 px-2 !text-xs leading-4 text-foreground sm:w-auto`,children:[(0,$.jsx)(X,{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)(Jn,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(`always`),disabled:i,className:`min-h-9 min-w-0 w-full gap-1.5 px-2 !text-xs leading-4 text-foreground sm:w-auto`,children:[(0,$.jsx)(X,{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)(Jn,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(`reject`),disabled:i,className:`min-h-9 min-w-0 w-full gap-1.5 px-2 !text-xs leading-4 text-[var(--status-error)] sm:w-auto`,children:[(0,$.jsx)(X,{name:`close`,className:`size-3.5 shrink-0 sm:size-3`}),(0,$.jsx)(`span`,{className:`truncate`,children:n(`chat.permissionToast.actions.deny`)})]})]}),i?(0,$.jsx)(`div`,{className:`flex justify-center w-full py-1 sm:w-auto sm:ml-auto typography-meta text-muted-foreground`,children:(0,$.jsx)(`div`,{className:`animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full`})}):null]}),children:(0,$.jsxs)(`div`,{className:`[&_.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:J(`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(m===`bash`||m===`shell`||m===`shell_command`){let e=h(`command`)||h(`cmd`)||h(`script`),t=h(`description`),r=h(`cwd`)||h(`working_directory`)||h(`directory`)||h(`path`),i=g(`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)(Td,{language:`bash`,code:e,style:tH,codeStyle:nH.style,wrap:!0})})]})}if(m===`edit`||m===`multiedit`||m===`str_replace`||m===`str_replace_based_edit_tool`){let e=h(`path`)||h(`file_path`)||h(`filename`)||h(`filePath`),t=h(`changes`)||h(`diff`),r=_(`replace_all`)||_(`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)(Uc,{outerClassName:`max-h-[60vh]`,className:`tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent`,children:(0,$.jsx)(WV,{diff:t,filePath:e})})]})}if(m===`write`||m===`create`||m===`file_write`){let e=h(`path`)||h(`file_path`)||h(`filename`)||h(`filePath`),t=h(`content`)||h(`text`)||h(`data`);return t?(0,$.jsx)(Uc,{outerClassName:`max-h-[60vh]`,className:`tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent`,children:(0,$.jsx)(GV,{content:t,filePath:e})}):null}if(m===`webfetch`||m===`fetch`||m===`curl`||m===`wget`){let t=h(`url`)||h(`uri`)||h(`endpoint`),r=h(`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=g(`timeout`),s=h(`format`)||h(`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)(Uc,{outerClassName:`max-h-32`,className:`p-0`,children:(0,$.jsx)(oH,{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)(Uc,{outerClassName:`max-h-32`,className:`p-0`,children:typeof a==`object`&&a?(0,$.jsx)(oH,{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(y).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)(Uc,{outerClassName:`max-h-48`,className:`p-0`,children:(0,$.jsx)(oH,{data:y})})]})})()]})})};function cH(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(`
|
|
6602
6602
|
`).trimEnd()}function lH(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 uH=200;function dH(e){return Math.min(Math.max(e,40),uH)}var fH=`summary`,pH=Z.memo(function(e){let t=(0,Q.c)(27),{value:n,placeholder:r,disabled:i,onValueChange:a,onKeyDown:o}=e,s=Z.useRef(null),[c,l]=Z.useState(n),[u,d]=Z.useState(40),[f,p]=Z.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=q(m),g;t[1]===h?g=t[2]:(g=()=>{requestAnimationFrame(h)},t[1]=h,t[2]=g);let _=q(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],Z.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),Z.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=dH(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),Z.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=J(`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}),mH=({question:e})=>{let{t}=Wn(),n=Ci(e),r=aa,i=xa,a=K(e=>e.isMobile),o=Ao(),s=Y(e=>e.currentSessionId),c=Z.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]=Z.useState(`0`),[d,f]=Z.useState(!1),p=d||n.claimed||n.pending===`delegate`||n.request?.state===`submitting`||n.request?.state===`uncertain`||n.request?.state===`settled`,[m,h]=Z.useState(!1),[g,_]=Z.useState({}),[v,y]=Z.useState({}),b=Z.useRef({}),[x,S]=Z.useState({}),C=Z.useMemo(()=>e.questions??[],[e.questions]),w=l===fH,T=w?-1:Math.max(0,Math.min(C.length-1,Number(l)||0)),E=w?null:C[T],D=Z.useMemo(()=>{if(w)return null;let e=E?.header?.trim();return e&&e.length>0?e:null},[E?.header,w]);Z.useEffect(()=>{u(`0`),_({}),y({}),b.current={},S({}),h(!1)},[e.id]);let O=Z.useMemo(()=>{let e=C.map((e,t)=>({value:String(t),label:e.header?.trim()||`Q${t+1}`}));return C.length>1&&e.push({value:fH,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=Z.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=Z.useMemo(()=>C.length!==0&&N.length===0,[C.length,N.length]),F=q(()=>{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=q(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=q(()=>{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=q(e=>{b.current[T]=e;let t=e.trim().length>0;S(e=>e[T]===t?e:{...e,[T]:t})}),B=q(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){eo(e)?await n.submissionClaimed(i):So(e)?(Ha.info(t(`chat.questionCard.noLongerPending`)),h(!0)):Ha.error(t(`chat.questionCard.submitFailed`),{description:t(`chat.questionCard.tryAgain`)})}finally{f(!1)}}),V=q(e=>{Xc(e)||e.key===`Enter`&&!e.shiftKey&&(!a||e.ctrlKey||e.metaKey)&&(e.preventDefault(),P?B():F())}),H=q(async()=>{if(p)return;let r=n.scope;f(!0);try{await i(e.sessionID,e.id,n.request?.directory),h(!0)}catch(e){eo(e)?await n.submissionClaimed(r):So(e)?(Ha.info(t(`chat.questionCard.noLongerPending`)),h(!0)):Ha.error(t(`chat.questionCard.dismissFailed`),{description:t(`chat.questionCard.tryAgain`)})}finally{f(!1)}}),ee=q(async()=>{let n=cH(e);if((await Un(n)).ok){Ha.success(t(`chat.questionCard.copiedMarkdown`));return}Ha.error(t(`chat.questionCard.copyFailed`))}),U=q(async()=>{let n=lH(e);if((await Un(n)).ok){Ha.success(t(`chat.questionCard.copiedJson`));return}Ha.error(t(`chat.questionCard.copyFailed`))});return m||C.length===0?null:(0,$.jsxs)(eH,{mobile:a,questionCard:!0,onInteraction:n.interaction,header:(0,$.jsxs)(`div`,{className:J(`flex min-w-0 items-center gap-2`,a&&`flex-wrap`),children:[(0,$.jsx)(X,{name:`question`,className:`h-3.5 w-3.5 text-primary`}),(0,$.jsx)(`span`,{className:`min-w-0 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 min-w-0 truncate 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:J(`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)(X,{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)(X,{name:`code-box`,className:`h-3 w-3`})})]})]}),afterBody:(0,$.jsx)(Yr,{delegation:n}),footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:P?B:F,disabled:p,className:J(`flex min-h-9 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)(X,{name:`check`,className:`h-3 w-3`}):(0,$.jsx)(X,{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:J(`flex min-h-9 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)(X,{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]}),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===fH,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:J(`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)(X,{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:J(`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:J(`space-y-0.5`,a&&`space-y-1`),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,"aria-pressed":r,className:J(`w-full min-h-9 px-2 py-1.5 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`,"aria-hidden":`true`,children:A?(0,$.jsx)(`span`,{className:J(`flex size-4 items-center justify-center rounded border`,r?`border-primary bg-primary text-primary-foreground`:`border-border bg-background`),children:r?(0,$.jsx)(X,{name:`check`,className:`size-3`}):null}):(0,$.jsx)(`span`,{className:`flex size-4 items-center justify-center rounded-full border border-border bg-background`,children:r?(0,$.jsx)(`span`,{className:`size-2 rounded-full bg-primary`}):null})}),(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:J(`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,"aria-pressed":M,className:J(`w-full min-h-9 px-2 py-1.5 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)(X,{name:`edit`,className:J(`h-3.5 w-3.5`,M?`text-primary`:`text-muted-foreground/50`)}),(0,$.jsx)(`span`,{className:J(`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)(pH,{value:b.current[T]??``,onValueChange:z,placeholder:t(`chat.questionCard.yourAnswer`),disabled:p,onKeyDown:V})}):null]})]}):null]})};function hH(e){if(e.type!==`external`)return e.type===`multiselect`?e.default??[]:e.type===`boolean`?e.default??!1:e.type===`number`||e.type===`integer`?e.default:e.default??(e.type===`string`?e.options?.[0]?.value:void 0)??``}var gH=({form:e,directory:t})=>{let{t:n}=Wn(),r=K(e=>e.isMobile),[i,a]=Z.useState(!1),[o,s]=Z.useState(null),[c,l]=Z.useState(()=>{let t={};for(let n of e.fields){let e=hH(n);e!==void 0&&(t[n.key]=e)}return t}),u=(e,t)=>{l(n=>({...n,[e]:t}))},d=q(async()=>{if(!i){s(null),a(!0);try{await li({sessionID:e.sessionID,formID:e.id,answer:c,directory:t}),Cr.getState().remove(e.sessionID,e.id)}catch{s(`reply`)}finally{a(!1)}}}),f=q(async()=>{if(!i){s(null),a(!0);try{await _r({sessionID:e.sessionID,formID:e.id,directory:t}),Cr.getState().remove(e.sessionID,e.id)}catch{s(`cancel`)}finally{a(!1)}}});return(0,$.jsxs)(eH,{mobile:r,header:(0,$.jsx)(`div`,{className:`typography-meta font-medium text-muted-foreground`,children:e.title||n(`chat.form.title`)}),footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Jn,{type:`button`,variant:`default`,size:`sm`,onClick:()=>void d(),disabled:i,children:n(`chat.form.reply`)}),(0,$.jsx)(Jn,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>void f(),disabled:i,children:n(`chat.form.cancel`)})]}),children:[(0,$.jsx)(`div`,{className:`space-y-2`,children:e.fields.map(e=>{if(e.type===`external`)return(0,$.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`block typography-meta text-primary underline`,children:e.title||e.url},e.key);if(e.type===`boolean`)return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 typography-meta`,children:[(0,$.jsx)(is,{checked:!!c[e.key],onChange:t=>u(e.key,t),disabled:i}),(0,$.jsx)(`span`,{children:e.title||e.key})]},e.key);if(e.type===`multiselect`){let t=Array.isArray(c[e.key])?c[e.key]:[];return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground`,children:e.title||e.key}),e.options.map(n=>(0,$.jsxs)(`label`,{className:`flex items-center gap-2 typography-meta`,children:[(0,$.jsx)(is,{checked:t.includes(n.value),onChange:r=>{let i=r?[...t,n.value]:t.filter(e=>e!==n.value);u(e.key,i)},disabled:i}),(0,$.jsx)(`span`,{children:n.label})]},n.value))]},e.key)}if(e.type===`number`||e.type===`integer`)return(0,$.jsxs)(`label`,{className:`block space-y-1`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:e.title||e.key}),(0,$.jsx)(Ts,{type:`number`,value:typeof c[e.key]==`number`?String(c[e.key]):``,onChange:t=>u(e.key,t.target.value===``?``:Number(t.target.value)),disabled:i})]},e.key);let t=e.type===`string`?e.options:void 0;return t&&t.length>0?(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:e.title||e.key}),e.description?(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:e.description}):null,(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,role:`group`,"aria-label":e.title||e.key,children:t.map(t=>(0,$.jsx)(Jn,{type:`button`,variant:`chip`,size:`sm`,"aria-pressed":c[e.key]===t.value,disabled:i,onClick:()=>u(e.key,t.value),children:t.label},t.value))}),e.type===`string`&&e.custom?(0,$.jsx)(Ts,{"aria-label":e.title||e.key,value:typeof c[e.key]==`string`?c[e.key]:``,disabled:i,onChange:t=>u(e.key,t.target.value)}):null]},e.key):(0,$.jsxs)(`label`,{className:`block space-y-1`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:e.title||e.key}),(0,$.jsx)(Ts,{value:typeof c[e.key]==`string`?c[e.key]:``,placeholder:e.type===`string`?e.placeholder:void 0,onChange:t=>u(e.key,t.target.value),disabled:i})]},e.key)})}),o?(0,$.jsx)(`div`,{role:`alert`,className:`mt-2 typography-meta text-[var(--status-error)]`,children:n(o===`reply`?`chat.questionCard.submitFailed`:`chat.questionCard.dismissFailed`)}):null]})};function _H(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function vH(e){return typeof e==`string`&&e.length>0?e:void 0}function yH(e){if(!_H(e))return null;let t=vH(e.reason),n=vH(e.provider),r=vH(e.title),i=vH(e.message),a=vH(e.label);return!t||!n||!r||!i||!a?null:{reason:t,provider:n,title:r,message:i,label:a,...vH(e.link)?{link:vH(e.link)}:{}}}function bH(e){return!_H(e)||e.type!==`retry`?!1:yH(e.action)!==null}function xH(e,t){if(!bH(e))return null;let n=e.action,r=n.reason===`account_rate_limit`?t(`chat.retry.action.account`):t(`chat.retry.action.quota`);return{title:n.title||r,message:n.message||e.message||r,label:n.label||t(`chat.retry.action.open`),...n.link?{link:n.link}:{}}}var SH=e=>{let t=new Set;for(let n of e.messageOrder)for(let r of e.partsByMessageID[n]??[]){if(!bk(r))continue;let e=Sk(r);e?.type===`subagent`&&e.id&&t.add(e.id)}return[...t]},CH=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),wH=Z.memo(e=>{let t=(0,Q.c)(8),{sessionID:n,directory:r}=e,{t:i}=Wn(),a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a={bootstrap:!1},t[0]=a):a=t[0];let o=Nr(r,a),s=!!(n&&r),c;t[1]===s?c=t[2]:(c={enabled:s},t[1]=s,t[2]=c);let l=Kt(n,r,o,SH,CH,c),u=na(l);if(u===0)return null;let d;t[3]!==u||t[4]!==i?(d=i(`chat.sessionBackground.tasksRunning`,{count:u}),t[3]=u,t[4]=i,t[5]=d):d=t[5];let f;return t[6]===d?f=t[7]:(f=(0,$.jsx)(`div`,{className:`chat-column py-1 typography-meta text-muted-foreground`,role:`status`,"aria-live":`polite`,children:d}),t[6]=d,t[7]=f),f});wH.displayName=`BackgroundWorkHint`;function TH(e){return e.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
6603
|
-
`)}function EH(e,t=80){let n=TH(e).replace(/\n/g,` `);return n.length>t?`${n.slice(0,t)}…`:n}var DH=160,OH=28,kH=12,AH=6,jH=30,MH=12,NH=18,PH=80,FH=4,IH=10,LH=14,RH=20,zH=54,BH=4,VH=8,HH=2,UH=160,WH=(e,t)=>e.map(e=>({turnId:e,preview:EH(t.get(e)??[],DH)})),GH=[1,.6,.35,.15],KH=(e,t,n)=>{let r=n?LH:IH;if(t===null)return r;let i=GH[Math.abs(e-t)]??0;return Math.round(r+(RH-r)*i)};function qH({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:i,isLoadingOlder:a,onLoadEarlier:o}){let{t:s}=Wn(),c=K(e=>e.isPromptNavigatorPanelOpen),l=K(e=>e.setPromptNavigatorPanelOpen),u=Z.useRef(null),d=Z.useRef(null),[f,p]=Z.useState(null),[m,h]=Z.useState(0),[g,_]=Z.useState(!1);Z.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-AH-OH;_(r.right>i)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let v=Z.useMemo(()=>WH(e,t),[t,e]),y=Math.min(v.length,jH),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=Z.useMemo(()=>n?v.findIndex(e=>e.turnId===n):-1,[n,v]),k=Z.useRef(x);k.current=x;let A=Z.useRef(v.length);A.current=v.length;let j=Z.useRef(null),M=Z.useRef(null),N=Z.useRef(0),P=Z.useCallback(e=>{h(t=>{let n=A.current,r=Math.min(n,jH),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=Z.useRef(v[0]?.turnId),I=Z.useRef(v.length);Z.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]),Z.useEffect(()=>{if(f!==null)return;let e=O>=0?O:v.length-1;h(()=>{let t=A.current,n=Math.min(t,jH),r=Math.max(0,t-n);return Math.max(0,Math.min(r,e-Math.floor(n/2)))})},[O,f,v.length]);let L=Z.useCallback(e=>{let t=u.current;if(!t)return null;let n=t.getBoundingClientRect(),r=Math.floor((e-n.top)/MH),i=Math.min(A.current,jH);return i===0?null:Math.max(0,Math.min(i-1,r))},[]),R=Z.useCallback(()=>{N.current=0,M.current!==null&&(window.clearInterval(M.current),M.current=null)},[]),z=Z.useCallback(()=>{let e=N.current;if(e===0){R();return}let t=A.current,n=Math.max(0,t-Math.min(t,jH)),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=Z.useCallback(e=>{let t=u.current;if(!t)return;let n=t.getBoundingClientRect(),r=e-n.top,i=0;if(r<=NH&&C?i=-1:r>=n.height-NH&&w&&(i=1),N.current=i,i===0){R();return}M.current===null&&(M.current=window.setInterval(z,PH))},[z,C,w,R]);Z.useEffect(()=>()=>{M.current!==null&&window.clearInterval(M.current)},[]);let V=Z.useRef(null),H=Z.useCallback(()=>{V.current!==null&&(window.clearTimeout(V.current),V.current=null)},[]),ee=Z.useCallback(()=>{H(),V.current=window.setTimeout(()=>{V.current=null,p(null)},UH)},[H]);Z.useEffect(()=>()=>{V.current!==null&&window.clearTimeout(V.current)},[]);let U=Z.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=Z.useCallback(()=>{j.current=null,R(),ee()},[ee,R]),W=Z.useCallback(()=>{l(!1)},[l]),ne=Z.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]),re=Z.useCallback(e=>{let t=L(e.clientY);t!==null&&ne(Math.min(v.length-1,k.current+t))},[ne,v.length,L]);Z.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]),Z.useEffect(()=>()=>{l(!1)},[l]);let ie=Z.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]),ae=Z.useCallback(()=>{R(),p(null),W()},[W,R]),oe=Z.useRef(null),se=Z.useRef(f);se.current=f;let ce=f!==null,le=Z.useRef(0);Z.useEffect(()=>{let e=oe.current;if(!e)return;let t=e=>{e.preventDefault(),e.stopPropagation(),le.current+=e.deltaY;let t=Math.trunc(le.current/zH);if(t===0)return;le.current-=t*zH;let n=se.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,ce]);let ue=f===null?void 0:v[f],de=Math.min(v.length,VH),fe=de*zH,pe=v.length*zH-fe,me=e=>Math.max(0,Math.min(pe,e)),he=Z.useRef(null),ge=0;if(f===null)he.current=null;else if(he.current===null)ge=me(f*zH-(fe-zH)/2),he.current=ge;else{let e=he.current,t=(f-HH)*zH,n=(f+1+HH)*zH-fe;e>t?e=t:e<n&&(e=n),ge=me(e),he.current=ge}let _e=Math.floor(ge/zH),ve=Math.max(0,_e-FH),ye=Math.min(v.length,_e+de+FH),be=ge>0,xe=ge<pe,Se=be||xe?`linear-gradient(to bottom, ${be?`transparent, black 10%`:`black`}, ${xe?`black 90%, transparent`:`black`})`:void 0,Ce=Math.max(0,x-FH),we=Math.min(v.length,S+FH),Te=v.slice(Ce,we),Ee=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:J(`-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)(X,{name:`loader-4`,className:`size-3.5 animate-spin`}):(0,$.jsx)(X,{name:`arrow-up-s`,className:`size-3.5`})}):null,(0,$.jsxs)(`div`,{ref:u,role:`listbox`,tabIndex:-1,"aria-activedescendant":ue?`prompt-rail-tick-${ue.turnId}`:void 0,className:`relative cursor-pointer outline-none`,style:{width:`${g?kH:OH}px`,height:`${y*MH}px`},onMouseMove:U,onMouseLeave:te,onClick:re,onKeyDown:ie,onBlur:ae,children:[(0,$.jsx)(`div`,{className:`absolute inset-0 overflow-hidden`,style:Ee?{maskImage:Ee,WebkitMaskImage:Ee}:void 0,children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-300 ease-out`,style:{transform:`translateY(-${x*MH}px)`},children:Te.map((e,t)=>{let r=Ce+t,i=e.turnId===n,a=f===r,o=KH(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*MH}px`,height:`${MH}px`},children:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:J(`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)}),ue&&f!==null?(0,$.jsx)(`div`,{ref:oe,className:J(`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:`${de*zH}px`,maskImage:Se,WebkitMaskImage:Se},children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-200 ease-out`,style:{height:`${v.length*zH}px`,transform:`translateY(-${ge}px)`},children:v.slice(ve,ye).map((e,t)=>{let r=ve+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*zH+BH}px`,height:`46px`},onMouseMove:()=>{H(),se.current!==r&&(P(r),p(r))},onClick:()=>ne(r),children:(0,$.jsx)(`div`,{className:J(`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:J(`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 JH=100,YH=(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},XH=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=YH(p,t.scrollTop+JH);!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}},ZH=10,QH=`${ZH}vh`,$H=`80px`,eU=`calc(${$H} + var(--oc-chat-foot-inset))`,tU=(e,t)=>e?80:t<=0?96:Math.max(48,ZH/100*t),nU=(e,t)=>({sessionId:e,viewportKey:t}),rU=(e,t)=>e?.sessionId===t?.sessionId&&e?.viewportKey===t?.viewportKey,iU=(e,t)=>rU(e,t),aU=(e,t,n)=>({identity:e,anchor:t,scrollPosition:n}),oU=150,sU=1500,cU=2,lU=350,uU=600,dU=8e3,fU=24,pU=2,mU=(e,t)=>e<t,hU=()=>typeof performance<`u`?performance.now():Date.now(),gU=e=>({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}),_U=e=>e.scrollHeight-e.scrollTop-e.clientHeight,vU=e=>_U(gU(e)),yU=e=>e.scrollHeight-e.clientHeight>1,bU=(e,t)=>_U(e)<=tU(t,e.clientHeight),xU=({enabled:e=!0,currentSessionId:t,viewportKey:n,sessionMessageCount:r,sessionIsWorking:i,isMobile:a,onActiveTurnChange:o,onUpwardUserIntent:s})=>{let c=Z.useRef(null),[l,u]=Z.useState(null),d=Z.useRef(null),[f,p]=Z.useState(`following`),[m,h]=Z.useState(!1),[g,_]=Z.useState(!1),[v,y]=Z.useState(!1),b=Z.useRef(`following`),x=Z.useRef(a);x.current=a;let S=Z.useRef(r);S.current=r;let C=Z.useRef(nU(t,n));C.current=nU(t,n);let w=Z.useRef(null),T=Z.useRef(null),E=Z.useRef(null),D=Z.useRef(0),O=Z.useRef(null),k=Z.useRef(null),A=Z.useRef(0),j=Z.useRef(!1),M=Z.useRef(!1),N=Z.useRef(null),P=Z.useRef(0),F=q(()=>{P.current=hU()+450}),I=Z.useRef(0),L=Z.useRef(!1),R=Z.useRef(null),z=Z.useRef(null),B=Z.useRef(0),V=Z.useRef(!1),H=Z.useRef(null),ee=Z.useRef(null),U=Z.useRef(null),te=Mo(e=>e.updateViewportAnchor);Z.useLayoutEffect(()=>{c.current!==d.current&&(d.current=c.current,u(c.current))});let W=q(e=>{b.current!==e&&(b.current=e,p(e))}),ne=q(e=>{T.current={top:Math.max(0,e.scrollHeight-e.clientHeight),time:hU()},E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{T.current=null,E.current=null},sU)}),re=q(e=>{let t=T.current;return t?hU()-t.time>sU?(T.current=null,!1):Math.abs(e.scrollTop-t.top)<cU:!1}),ie=q(()=>hU()<A.current),ae=q(()=>{L.current=!1,R.current&&=(clearTimeout(R.current),null),z.current&&=(clearTimeout(z.current),null)}),oe=q(()=>{R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{R.current=null,ae()},uU)}),se=q(()=>{let e=c.current;e&&(L.current=!0,B.current=e.scrollHeight,oe(),z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{z.current=null,ae()},dU))}),ce=q(e=>{let t=c.current;if(!t){h(!1),_(!1);return}let n=e??gU(t),r=yU(n);if(h(r),!r){_(!1);return}let i=b.current===`released`&&!bU(n,x.current);_(i)}),le=q(()=>{D.current+=1,O.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(O.current),O.current=null),k.current?.(),k.current=null});Z.useEffect(()=>()=>le(),[l]);let ue=q(()=>{if(!e)return;let t=c.current;if(!t)return;le();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(),ce(),typeof window>`u`)return;let o=0,s=()=>{mU(hU(),P.current)||le()};t.addEventListener(`touchstart`,s,{passive:!0,once:!0}),k.current=()=>t.removeEventListener(`touchstart`,s);let l=()=>{if(n===D.current){if(vU(t)>pU&&a(),o+=1,o>=fU){O.current=null,k.current?.(),k.current=null,ce();return}O.current=window.requestAnimationFrame(l)}};O.current=window.requestAnimationFrame(l)}),de=q(e=>{let t=c.current;if(t){if(ne(t),e===`smooth`){t.scrollTo({top:t.scrollHeight,behavior:e});return}t.scrollTop=t.scrollHeight}}),fe=q((t,n=`auto`)=>{if(!e)return;let r=c.current;if(t&&b.current!==`following`&&W(`following`),r&&!(!t&&b.current!==`following`)){if(vU(r)<cU){ne(r);return}de(t?n:`auto`)}}),pe=q(e=>{let t=c.current;if(!t)return;let n=e??gU(t);if(!yU(n)){W(`following`);return}b.current!==`released`&&(W(`released`),ce(n))}),me=q((e=`instant`)=>{if(V.current=!1,W(`following`),ae(),e===`instant`){ue();return}le(),fe(!0,`smooth`),ce()}),he=q(()=>{V.current=!1,fe(!0)}),ge=q(()=>{le(),ae(),W(`released`),ce()}),_e=q(()=>{V.current=!0,ge()}),ve=q(()=>{V.current=!1}),ye=Z.useRef(s);ye.current=s;let be=q(()=>{mU(hU(),P.current)||(le(),ae(),pe())}),xe=q(()=>{be(),ye.current?.()}),Se=q(()=>{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}}),Ce=q(()=>{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=aU(e,o,{scrollTop:n,scrollHeight:r,clientHeight:i}),H.current===null&&(H.current=setTimeout(()=>{H.current=null,Se()},oU))}),we=q(()=>{Se()}),Te=q(async(e=C.current)=>{if(!e.sessionId)return!1;V.current=!1;let t=lr(e.sessionId,e.viewportKey);return c.current?(U.current=null,I.current=t?.scrollPosition?.scrollTop??0,W(`following`),F(),x.current?ue():fe(!0),se(),ce(),!1):(U.current=e,W(`following`),!1)});Z.useEffect(()=>{let e=C.current,n=w.current;rU(e,n)||(Se(),le(),F(),w.current=e,T.current=null,I.current=0,ae(),V.current=!1,W(`following`),U.current=null,t&&t!==n?.sessionId&&lO.getInstance().recordSessionStart(t))},[t,n]),Z.useEffect(()=>{i&&!V.current&&b.current===`following`&&fe(!0)},[i]),Z.useEffect(()=>{y(f===`following`&&i)},[f,i]),Z.useLayoutEffect(()=>{if(!l)return;let e=U.current;e&&iU(e,C.current)&&Te(e)},[l,t,n]);let Ee=q(()=>{let e=c.current;if(!e)return;let t=gU(e),n=I.current;I.current=t.scrollTop;let r=t.scrollTop>n+.5,i=Math.abs(t.scrollTop-n)<.5;if(ce(t),V.current){Ce();return}if(!yU(t)){W(`following`);return}if(bU(t,x.current)){let e=Math.min(n,Math.max(0,t.scrollHeight-t.clientHeight));if(t.scrollTop<e-.5){be(),Ce();return}(r||b.current===`following`)&&W(`following`),Ce();return}if(b.current===`following`&&(re(e)||ie()||i)){j.current||fe(!1),Ce();return}pe(t),Ce()});Z.useEffect(()=>{!e||!l||(I.current=l.scrollTop)},[l,e]);let De=Z.useRef(null),Oe=q(e=>{let t=c.current;t&&(e.deltaY>=0||ll(t,e.target)||xe())}),ke=q(e=>{let t=e.touches.item(0);De.current=t?{x:t.clientX,y:t.clientY,dx:0,dy:0}:null}),Ae=q(e=>{let t=c.current,n=e.touches.item(0);if(!n){De.current=null;return}let r=De.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(De.current={x:n.clientX,y:n.clientY,dx:o,dy:s},!(s<=0||Math.abs(o)>=s)&&t){if(ll(t,e.target)){De.current.dx=0,De.current.dy=0;return}s<=2||xe()}}),je=q(()=>{De.current=null}),Me=q(e=>{Qc(e)&&xe()}),Ne=q(e=>{let t=e.target;t instanceof Element&&t.closest(`[data-overlay-scrollbar-thumb]`)&&be()}),Pe=Z.useMemo(()=>()=>void 0,[]),Fe=e&&l?l:Pe,Ie=Z.useMemo(()=>({passive:!0}),[]);Bn(`scroll`,Ee,Fe,Ie),Bn(`wheel`,Oe,Fe,Ie),Bn(`touchstart`,ke,Fe,Ie),Bn(`touchmove`,Ae,Fe,Ie),Bn(`touchend`,je,Fe,Ie),Bn(`touchcancel`,je,Fe,Ie),Bn(`keydown`,Me,Fe),Bn(`pointerdown`,Ne,e&&typeof window<`u`?window:Pe,!0);let Le=q(()=>{let e=c.current;if(j.current){ce(e?gU(e):void 0);return}if(V.current){ce(e?gU(e):void 0);return}if(!e){ce(void 0);return}let t=gU(e);if(!yU(t)){W(`following`),ce(t);return}if(ce(t),L.current){let n=t.scrollHeight>B.current+1;B.current=t.scrollHeight,_U(t)<=cU?ne(e):fe(!0),n&&oe();return}if(b.current===`following`){if(_U(t)<=cU){ne(e);return}fe(!1)}}),Re=typeof ResizeObserver<`u`,ze=Re&&e?l:null,Be=Re&&e&&l&&l.firstElementChild instanceof Element?l.firstElementChild:null;In(ze,Le),In(Be,Le);let Ve=q(()=>{N.current!==null&&(clearTimeout(N.current),N.current=null)}),He=q(e=>{j.current=!0,typeof e==`number`&&e>0?A.current=hU()+e+lU:A.current=Math.max(A.current,hU()+lU)}),Ue=q(e=>{let t=e.detail;if(t){if(t.open===!0){He(),Ve(),N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},1500);return}Ve(),He()}}),We=q(e=>{let t=e.detail;t&&(Ve(),He(t.durationMs))}),Ge=q(e=>{let t=e.detail;Ve(),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)},lU)),ce()}),Ke=e&&typeof window<`u`?window:Pe;Bn(`oc:keyboard-intent`,Ue,Ke),Bn(`oc:keyboard-anim`,We,Ke),Bn(`oc:keyboard-settled`,Ge,Ke),Z.useEffect(()=>{if(!(!e||typeof window>`u`))return()=>{Ve(),j.current=!1,M.current=!1}},[e]),Z.useEffect(()=>{e&&ce()},[e,r]);let qe=q(t=>{if(e){if(t===`animation`&&(A.current=hU()+lU),ce(),L.current){fe(!0),oe();return}b.current===`following`&&fe(!1)}}),Je=Z.useRef(new Map),Ye=q(t=>{let n=Je.current.get(t);if(n)return n;let r=()=>{e&&b.current===`following`&&fe(!1)},i={onChunk:r,onComplete:()=>{e&&ce()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:r,onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return Je.current.set(t,i),i});Z.useEffect(()=>()=>{E.current&&=(clearTimeout(E.current),null),le(),ae(),Se(),H.current!==null&&(clearTimeout(H.current),H.current=null)},[]);let Xe=q(e=>{o?.(e)}),Ze=!!o;return Z.useEffect(()=>{if(!e||!Ze)return;let t=l;if(!t)return;let n=null,r=XH({onActive:e=>{e!==n&&(n=e,Xe(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,Ze]),{scrollRef:c,state:f,isPinned:f===`following`,isOverflowing:m,isFollowingProgrammatically:v,showScrollButton:g,notifyContentChange:qe,getAnimationHandlers:Ye,goToBottom:me,scrollToBottomOnSend:he,releaseAutoFollow:ge,beginHistoryViewportPreservation:_e,endHistoryViewportPreservation:ve,saveSnapshotNow:we,restoreSnapshot:Te}},SU=`--oc-mobile-composer-swap`,CU=`--oc-native-composer-dock`,wU=()=>({phase:`rest`,rest:`expanded`,progress:0,pinned:!1}),TU=(e,t,n)=>Math.min(n,Math.max(t,e)),EU=(e,t)=>e.phase===t.phase&&e.rest===t.rest&&e.progress===t.progress&&e.pinned===t.pinned,DU=(e,t)=>{let n={phase:t.phase,rest:t.rest,progress:t.progress,pinned:t.pinned??e.pinned};return EU(e,n)?e:n},OU=(e,t)=>t?DU(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0}):e.pinned?DU(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!1}):e,kU=(e,t)=>{if(e.pinned&&t===`compact`)return e;let n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:DU(e,{phase:`snapping`,rest:t,progress:n})},AU=e=>TU(e/80,0,1),jU=e=>e>=80?1:TU(e/80,0,1),MU=(e,t,n={})=>{if(e.pinned||n.userDriven===!1)return e;let r=Math.max(0,t),i=e.phase===`snapping`?DU(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e;if(i.rest===`expanded`){if(r<=2||n.holdExpanded)return DU(i,{phase:`rest`,rest:`expanded`,progress:0});let e=AU(r);return e>=1?DU(i,{phase:`rest`,rest:`compact`,progress:1}):DU(i,{phase:`tracking`,rest:`expanded`,progress:e})}if(r<=2)return DU(i,{phase:`rest`,rest:`expanded`,progress:0});if(n.suppressReturn)return DU(i,{phase:`rest`,rest:`compact`,progress:1});if(n.towardBottom&&r>=80)return DU(i,{phase:`snapping`,rest:`expanded`,progress:0});let a=jU(r);return a>=1?DU(i,{phase:`rest`,rest:`compact`,progress:1}):DU(i,{phase:`tracking`,rest:`compact`,progress:a})},NU=e=>e.pinned?`expanded`:e.rest===`expanded`?e.progress>=.5?`compact`:`expanded`:e.progress<=.5?`expanded`:`compact`,PU=e=>{if(e.pinned)return DU(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0});if(e.phase===`snapping`)return e;let t=NU(e),n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:DU(e,{phase:`snapping`,rest:t,progress:n})},FU=e=>e.phase===`snapping`?DU(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e,IU=e=>TU(Math.max(0,e)/80,0,1),LU=(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:IU(n),rest:`bottom`}},RU=e=>{e.style.removeProperty(SU),e.style.removeProperty(CU),delete e.dataset.ocComposerSwapPhase,delete e.dataset.ocComposerSwapRest,delete e.dataset.ocNativeComposerDock},zU=(e,t,n)=>{let r=LU(t,n?.rest===`bottom`?`bottom`:`away`),i=String(r.progress),a=r.rest;return n?.progress!==i&&e.style.setProperty(CU,i),n?.rest!==a&&(e.dataset.ocNativeComposerDock=a),{progress:i,rest:a}},BU=(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(SU,r),n?.rest!==a&&(e.dataset.ocComposerSwapRest=a),{progress:r,phase:i,rest:a}},VU=e=>({scrollHeight:e.scrollHeight,scrollTop:e.scrollTop,clientHeight:e.clientHeight}),HU=()=>{let e=document.documentElement;return e.classList.contains(`oc-keyboard-open`)||e.classList.contains(`oc-kb-animating`)},UU=e=>{if(HU()||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)},WU=e=>{let t=Z.useRef(wU()),n=Z.useRef(void 0),r=Z.useRef(void 0),i=Z.useRef(null),a=Z.useRef(null),o=Z.useRef(0),s=Z.useRef(!1),c=Z.useRef(0),l=Z.useRef(new Map),u=Z.useRef(!1),d=Z.useRef(0),f=Z.useRef(null),p=Z.useRef(null),m=Z.useRef(0),h=Z.useRef(0),g=Z.useRef(!1),_=Z.useRef(e.enabled);_.current=e.enabled;let v=e=>{e.current!==null&&(window.clearTimeout(e.current),e.current=null)},y=q(t=>{let r=e.scopeRef.current;r&&(n.current=BU(r,t,n.current))}),b=q(e=>{e!==t.current&&(t.current=e,y(e))}),x=q(()=>{if(v(a),t.current.phase!==`snapping`)return;let e=t.current.rest;a.current=window.setTimeout(()=>{a.current=null;let n=FU(t.current);b(n),n.rest===`compact`&&e===`compact`&&(o.current=Date.now()+320,s.current=!0)},240)}),S=q(()=>{let n=e.scopeRef.current;!n||!_.current||b(OU(t.current,UU(n)))}),C=q(e=>s.current?Date.now()>=o.current?(s.current=!1,!1):e>=80?(s.current=!1,o.current=0,!1):!0:!1),w=q(()=>{if(v(i),!_.current||c.current>0||t.current.phase!==`tracking`)return;let e=PU(t.current);b(e),x()}),T=q(()=>{u.current=!1,d.current=0;for(let e of l.current.values())e.startX=e.currentX,e.startY=e.currentY}),E=q(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=q(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=VU(t);p.current=e,f.current=Qz(e,Xz(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=q(()=>{if(!_.current)return;let n=e.scrollRef.current,o=e.scopeRef.current;if(!n||!o)return;let s=UU(o),l=VU(n),y=Qz(l,Xz(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=zU(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=OU(j,s);if(!s){let e=M.rest===`compact`;M=MU(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=q(()=>{u.current&&(c.current>0||Date.now()-d.current<=1200)&&w()}),A=q((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=q(e=>{A(e,!0)}),M=q(e=>{A(e,!1)}),N=q(()=>{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=q(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(kU(t.current,`expanded`)),x(),N(),(e.scopeRef.current?.querySelector(`textarea[data-chat-input="true"]`))?.focus({preventScroll:!0})))}),[F,I]=Z.useState(null),[L,R]=Z.useState(null),z=Z.useRef(null),B=q(e=>{e&&RU(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(wU())});Z.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=Z.useMemo(()=>()=>void 0,[]),H=e.enabled&&F?F:V,ee=e.enabled&&L?L:V,U=e.enabled&&typeof window<`u`?window:V,te=Z.useMemo(()=>({passive:!0}),[]);Bn(`scroll`,O,H,te),Bn(`scrollend`,k,H,te),Bn(`touchstart`,D,H,te),Bn(`touchmove`,E,H,te),Bn(`touchend`,j,H,te),Bn(`touchcancel`,M,H,te),Bn(`pointerdown`,P,ee),Bn(`focusin`,S,ee),Bn(`focusout`,S,ee),Bn(`oc:keyboard-intent`,S,U),Bn(`oc:keyboard-anim`,S,U),Bn(`oc:keyboard-settled`,S,U),Z.useEffect(()=>{if(!e.enabled){B(z.current),z.current=null;return}return S(),O(),()=>{v(i),v(a)}},[e.enabled,F,L])},GU=e=>{let t=e.info.clientRole??e.info.role;return typeof t==`string`?t:``},KU=e=>{let t=e.info.parentID;if(typeof t==`string`&&t.trim().length!==0)return t},qU=e=>{if(!e)return null;let t=GU(e);return`${typeof e.info?.id==`string`?e.info.id:``}::${t}::${KU(e)??``}`},JU=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}),YU=(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&&qU(t[r])===qU(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=GU(r),a=r.info.id,o=JU(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=KU(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},XU=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=GU(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=KU(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}},ZU=200,QU={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:6e5},$U=()=>ZU,eW=()=>Math.round($U()*.6),tW={MAX_SESSIONS:QU.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(ZU*.6),HISTORICAL_MESSAGES:ZU,FETCH_BUFFER:20,HISTORY_CHUNK:ZU,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:QU.ZOMBIE_TIMEOUT},nW=()=>{let e=$U(),t=eW();return{...tW,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},rW=tW,iW=600,aW=6e3,oW=.5,sW=(e,t)=>e.querySelector(`[data-message-id="${CSS.escape(t)}"]`),cW=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},lW=(e,t)=>{let n=sW(e,t);if(n||=cW(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}},uW=e=>{let{container:t,quiesceMs:n=iW,maxLifetimeMs:r=aW}=e,i={messageId:e.anchor.messageId,offsetTop:e.anchor.offsetTop},a=!1,o=e.pending??!1,s=null,c=null,l=!1,u=t.scrollTop,d=()=>{s!==null&&(clearTimeout(s),s=null)},f=()=>{c!==null&&(clearTimeout(c),c=null)},p=()=>{a||(a=!0,b.disconnect(),t.removeEventListener(`scroll`,y),d(),f())},m=()=>{d(),!(a||o)&&(s=setTimeout(()=>{s=null,p()},n))},h=()=>{f(),!(a||o)&&(c=setTimeout(()=>{c=null,p()},r))},g=()=>{if(a)return;let e=lW(t,i.messageId);if(!e){p();return}i.messageId=e.messageId,i.offsetTop=e.offsetTop,u=t.scrollTop},_=()=>{if(a)return;if(Math.abs(t.scrollTop-u)>oW){g();return}let e=sW(t,i.messageId);if(!e){let n=cW(t);if(!n){p();return}let r=n.dataset.messageId;if(!r){p();return}let a=t.getBoundingClientRect();i.messageId=r,i.offsetTop=n.getBoundingClientRect().top-a.top,e=n,u=t.scrollTop}let n=t.getBoundingClientRect(),r=e.getBoundingClientRect().top-n.top-i.offsetTop;Math.abs(r)>oW&&(t.scrollTop+=r),u=t.scrollTop},v=()=>{a||l||(l=!0,queueMicrotask(()=>{l=!1,_()}))},y=()=>{g(),m(),h()},b=new MutationObserver(()=>{a||(v(),m())});return b.observe(t,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`style`,`class`]}),t.addEventListener(`scroll`,y,{passive:!0}),h(),m(),{rebase:g,dispose:p,settle(){a||!o||(o=!1,m(),h())}}},dW=30,fW=1200,pW=1.5,mW=e=>Math.max(fW,e*pW),hW=4,gW=30,_W=4,vW=30,yW=250,bW=1500,xW=2e3,SW=ja+2e3,CW=40,wW=`history-loading-timeout`,TW=e=>!!(e&&typeof e==`object`&&e.code===`history-loading-timeout`),EW=()=>{let e=Error(`chat history pagination wait timed out`);return e.code=wW,e},DW=(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)},OW=2500,kW=new Map,AW=()=>fe()?hW:Rr()?_W:dW,jW=e=>fe()?e.length<=gW:!Rr()||e.length<=vW,MW=(e,t)=>{if(kW.delete(e),!jW(t.messages))return;let n=AW();for(;kW.size>=n;){let e=kW.keys().next().value;if(typeof e!=`string`)break;kW.delete(e)}kW.set(e,t)},NW=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),PW=e=>e?{owner:`tanstack-core`}:{owner:`controller`},FW=(e,t)=>e?e.canLoadEarlier:t>=nW().HISTORICAL_MESSAGES,IW=e=>!(e.isLoadingOlder||e.pendingRevealWork||!e.canLoadEarlier||e.source===`scroll`&&e.isPinned||e.scrollTop>=mW(e.clientHeight)),LW=e=>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.cursorBefore==null&&e.limitAfter>e.limitBefore||typeof e.cursorAfter==`string`&&e.cursorAfter!==e.cursorBefore?e.pagesLoaded>=e.maxPages?`stop-bounded`:`continue`:`stop-no-growth`:`stop-exhausted`,RW=8,zW=1,BW=8,VW=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),HW=e=>[`chat-timeline-auto-fill`,e.runtimeKey,e.sessionId,e.oldestMessageId,e.messageCount,e.canLoadEarlier],UW=e=>[`chat-timeline-load-earlier`,e.runtimeKey,e.sessionId],WW=20,GW=4,KW=80,qW=new WeakMap,JW=new WeakMap,YW=e=>{let t=JW.get(e)??{generation:0};return t.generation+=1,JW.set(e,t),t.generation},XW=e=>{let t=qW.get(e);t&&(t.touches=0,t.pending=null,t.settleScheduled=!1),YW(e)},ZW=e=>{QW(e)},QW=e=>{let t=qW.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&&$W(e,n)};return e.addEventListener(`touchend`,r,{passive:!0}),e.addEventListener(`touchcancel`,r,{passive:!0}),qW.set(e,n),n},$W=(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+KW||eG(e,n.anchorTop+n.delta))}))},eG=(e,t)=>{let n=YW(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((JW.get(e)?.generation??0)!==n){e.removeEventListener(`touchstart`,o);return}e.scrollTop<t-GW&&(e.scrollTop=t),a+=1,a<WW?window.requestAnimationFrame(s):e.removeEventListener(`touchstart`,o)}};window.requestAnimationFrame(s)},tG=(e,t,n)=>{let r=QW(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,eG(e,t)},nG=(e,t,n)=>!e||!t||t===e?!1:n.some(t=>t.info.id===e),rG=(e,t)=>e.scrollHeight===t.scrollHeight&&e.clientHeight===t.clientHeight?e:t,iG=({sessionId:e,directory:t=null,messages:n,historyMeta:r,scrollRef:i,messageListRef:a,loadMoreMessages:o,goToBottom:s,releaseAutoFollow:l,beginHistoryViewportPreservation:d,endHistoryViewportPreservation:f,isPinned:p,showScrollButton:m,isMobile:h,autoFillEnabled:g=!1,onWillLoadEarlier:_})=>{let v=Z.useRef(h),y=Z.useRef(g);v.current=h,y.current=g;let b=Z.useRef(null),x=Z.useRef(null),S=Z.useMemo(()=>{let t=e??``,r=t?kW.get(t):void 0;if(r&&r.messages===n)return MW(t,r),b.current=r.model,x.current=n,r.model;let i=YU(b.current,x.current,n)??XU(n);return b.current=i,x.current=n,t&&n.length>0&&MW(t,{messages:n,model:i}),i},[n,e]),[C,w]=Z.useState(!1),[T,E]=Z.useState(!1),[D,O]=Z.useState(null),[k,A]=Z.useState(!1),j=Z.useRef(!1),M=Z.useRef(0),N=u(),P=c(),F=Z.useMemo(()=>({runtimeKey:N,runtimeGeneration:P,sessionId:e,directory:t}),[N,P,e,t]),I=Z.useRef(F);I.current=F;let L=`chat-history-error:${JSON.stringify([N,t??null,e])}`;zn(()=>(I.current=F,()=>{I.current===F&&(I.current=null),Ha.dismiss(L)}),[F,L]);let[R,z]=Z.useState({scrollHeight:0,clientHeight:0}),B=Z.useRef(S),V=Z.useRef(p),H=Z.useRef(C),ee=Z.useRef(T),U=Z.useRef(e),te=Z.useRef(t??null),W=Z.useRef(n),ne=Z.useRef(r),re=Z.useRef([]),ie=Z.useRef(null),ae=Z.useRef(null),oe=Z.useRef(!1),se=Z.useRef(null),ce=Z.useRef({authorized:!1,consumed:!1,top:0}),le=q(()=>{ce.current={authorized:!1,consumed:H.current,top:i.current?.scrollTop??0}}),ue=()=>h?i.current??void 0:void 0,de=q(e=>{e.repeat||le()});Bn(`touchstart`,le,ue,{passive:!0,capture:!0}),Bn(`wheel`,le,ue,{passive:!0,capture:!0}),Bn(`keydown`,de,ue,{capture:!0});let[fe,pe]=Z.useState(F);fe!==F&&(pe(F),se.current!==null&&typeof window<`u`&&(window.clearTimeout(se.current),se.current=null),oe.current=!1,H.current=!1,ae.current=null,w(!1),E(!1),O(null),A(!1),j.current=!1,M.current=0,ce.current={authorized:!1,consumed:!1,top:0},z({scrollHeight:0,clientHeight:0}));let me=Z.useMemo(()=>{let e=FW(r,n.length);return{hasBufferedTurns:!1,hasMoreAboveTurns:e,historyLoading:!!r?.loading,canLoadEarlier:e}},[r,n.length]),he=Z.useRef(me);B.current=S,V.current=p,ee.current=T,he.current=me,U.current=e,te.current=t??null,W.current=n,ne.current=r,zn(()=>{r?.complete&&(j.current=!1,A(!1),Ha.dismiss(L))},[r?.complete,L]);let ge=q(()=>{oe.current=!0,se.current!==null&&typeof window<`u`&&(window.clearTimeout(se.current),se.current=null)}),_e=q(()=>{if(typeof window>`u`){oe.current=!1;return}se.current!==null&&window.clearTimeout(se.current),se.current=window.setTimeout(()=>{se.current=null,oe.current=!1},xW)}),ve=q(()=>{let e=re.current;e.length!==0&&(re.current=[],e.forEach(e=>e()))}),ye=q(()=>new Promise(e=>{if(typeof window>`u`){e();return}let t=!1,n=()=>{t||(t=!0,window.clearTimeout(r),e())};re.current.push(n);let r=window.setTimeout(n,yW)})),be=q(e=>{let t=ie.current;t&&(ie.current=null,t.resolve(e))}),xe=q(()=>{let e=ie.current;if(e){if(e.sessionId!==U.current){be(!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&&(ae.current={turnId:e.turnId,expiresAt:Date.now()+OW},O(e.turnId)),be(!0);return}typeof(e.kind===`turn`?B.current.turnIndexById.get(e.id):B.current.messageToTurnIndex.get(e.id))==`number`&&be(!1)}}),Se=Z.useRef(null),Ce=q(()=>{let e=Se.current;e&&(Se.current=null,e.dispose())});Rn(()=>{se.current!==null&&typeof window<`u`&&(window.clearTimeout(se.current),se.current=null),Ce(),ve(),be(!1)});let we=n;zn(()=>{ve(),xe()},[we]);let Te=q(()=>{let e=i.current;if(!e){z(e=>rG(e,{scrollHeight:0,clientHeight:0}));return}z(t=>rG(t,{scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}))});In(typeof ResizeObserver<`u`?i:null,Te),zn(()=>{Te()},[F,C]);let Ee=Z.useRef(null),De=q(()=>a.current?.captureViewportAnchor()??null),Oe=q(e=>a.current?.restoreViewportAnchor(e)??!1),ke=q(()=>{if(Ce(),a.current?.isHistoryVirtualized())return;let e=i.current;if(!e)return;let t=De();if(t)return Se.current=uW({container:e,anchor:t,pending:!0}),Se.current}),Ae=Z.useRef(null);zn(()=>{if(!Rr())return;let e=i.current;e&&(ZW(e),XW(e))},[F,i]),zn(()=>{Ce(),Ee.current=null,Ae.current=null,a.current?.cancelViewportAnchorHold()},[F]),zn(()=>{let e=i.current;if(!e)return;let t=Ee.current;a.current?.isHistoryVirtualized()&&Ce(),t&&Math.abs(e.scrollTop-t.top)>BW&&(Ee.current=null,t=null);let n=Ae.current,r=we[0]?.info?.id??null,o=we[we.length-1]?.info?.id??null,c=n?NW({previousOldestId:n.oldestId,previousNewestId:n.newestId,currentOldestId:r,currentNewestId:o})||nG(n.oldestId,r,we):!1;t&&t.sessionId!==U.current&&(Ee.current=null,t=null);let l=t?NW({previousOldestId:t.oldestId,previousNewestId:t.newestId,currentOldestId:r,currentNewestId:o})||nG(t.oldestId,r,we):!1,u=c||l,d=e=>{Ae.current={oldestId:r,newestId:o,scrollHeight:e??Ae.current?.scrollHeight??0}};if(V.current&&!t){Ce(),u?(Ee.current=null,s(`instant`),d(e.scrollHeight)):d();return}let f=PW(a.current?.isHistoryVirtualized()??!1);if(t){if(f.owner===`tanstack-core`){a.current?.cancelViewportAnchorHold();let e=t.anchor;e&&Oe(e),d();return}let n=e.scrollHeight,r=n-t.height;if(Rr()){r>0&&tG(e,t.top+r,r),d(n);return}let i=t.anchor;!(i&&Oe(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;Rr()?tG(e,t,r):e.scrollTop=t}d(t),ke();return}d()},[we,s]);let je=q(async()=>!1),Me=q(async e=>{let t=I.current,n=()=>t===I.current&&t?.runtimeKey===u()&&t?.runtimeGeneration===c(),r=Date.now(),i=r+SW,a=te.current,o=a?dn()?.getRequestState?.(Vt(a,e)):void 0;for(he.current.historyLoading,ne.current,o?.status,o?.error;he.current.historyLoading;){if(!n()||U.current!==e)return Date.now()-r,`switched`;if(Date.now()>=i){let t=a?dn()?.getRequestState?.(Vt(a,e)):void 0;return console.error(`[chat-history] historyLoading wait timed out — sync flag still true`,{sessionId:e,directory:a,elapsedMs:Date.now()-r,waitMs:SW,hostTurnPageTimeoutMs:ja,historyLoading:he.current.historyLoading,historyMeta:ne.current,requestStatusAtStart:o?.status??null,requestStatusAtTimeout:t?.status??null,requestErrorAtTimeout:t?.error??null,likelyStaleLoadingFlag:t?.status===`ready`||t?.status===`error`||t==null}),`timeout`}await new Promise(e=>{if(typeof window>`u`){e();return}window.setTimeout(e,CW)})}return Date.now()-r,a&&dn()?.getRequestState?.(Vt(a,e))?.status,n()&&U.current===e?`cleared`:`switched`}),Ne=q(async e=>{if(!U.current||H.current||!he.current.hasMoreAboveTurns)return!1;H.current=!0,ge(),w(!0);let t=U.current,n=I.current,r=()=>n===I.current&&n?.runtimeKey===u()&&n?.runtimeGeneration===c(),s=()=>n?.directory?dn()?.getPagination(Vt(n.directory,t)).cursor??null:null,l=L,p=null,m=null,h=!!e.userInitiated;h&&d();let g=()=>{r()&&(m?.settle(),p&&Ee.current===p&&(Ee.current=null,a.current?.cancelViewportAnchorHold()),h&&(h=!1,f()))};try{if(he.current.historyLoading){if(!e.userInitiated)return!1;let n=await Me(t);if(n===`timeout`)throw EW();if(n===`switched`||!he.current.hasMoreAboveTurns)return!1}if(!r()||!U.current||U.current!==t)return!1;let n=i.current,a=W.current,c=a.length,u=a[0]?.info?.id??null,d=ne.current?.limit??nW().HISTORICAL_MESSAGES;e.preserveViewport&&n&&(p={sessionId:U.current,height:n.scrollHeight,top:n.scrollTop,anchor:De(),oldestId:u,newestId:a[a.length-1]?.info?.id??null},Ee.current=p,m=ke()??null);let f=c,h=u,_=d,v=0,y=0;for(;;){if(he.current.historyLoading)if(e.userInitiated){let e=await Me(t);if(e===`timeout`)throw g(),EW();if(e===`switched`)return g(),!1}else return g(),!1;let n=i.current?.scrollHeight??0,a=f,c=h,u=_,d=s();if(await o(t,`up`),v+=1,!r()||U.current!==t)return g(),!1;if(await ye(),!r())return!1;let p=(()=>{let t=W.current;return LW({scrollHeightBefore:n,scrollHeightAfter:i.current?.scrollHeight??n,messageCountBefore:a,messageCountAfter:t.length,oldestIdBefore:c,oldestIdAfter:t[0]?.info?.id??null,limitBefore:u,limitAfter:ne.current?.limit??_,cursorBefore:d,cursorAfter:s(),hasMoreAbove:he.current.hasMoreAboveTurns,pagesLoaded:v,maxPages:e.singlePage?1:RW})})();if(p===`continue`){let e=W.current;f=e.length,h=e[0]?.info?.id??null,_=ne.current?.limit??_;continue}if(p===`stop-no-growth`){if(e.singlePage)return g(),!1;if(he.current.historyLoading){if(e.userInitiated){let e=await Me(t);if(e===`timeout`)throw g(),EW();if(e===`switched`)return g(),!1;--v;continue}return g(),!1}if(y<zW){y+=1,--v;continue}return j.current=!0,M.current=Date.now()+bW,A(!0),g(),!1}return j.current=!1,M.current=0,A(!1),Ha.dismiss(l),!0}}catch(e){throw r()&&(j.current=!0,M.current=Date.now()+bW,A(!0)),g(),e}finally{r()&&(H.current=!1,w(!1),_e(),ye().then(g))}}),{t:Pe}=Wn(),Fe=Tn({mutationKey:UW({runtimeKey:u(),sessionId:e??``}),mutationFn:async e=>{if(I.current!==e.scope||u()!==e.scope.runtimeKey||c()!==e.scope.runtimeGeneration||U.current!==e.sessionId)return!1;ge(),e.userInitiated&&l();try{return await Ne({preserveViewport:!0,userInitiated:!!e.userInitiated,singlePage:e.singlePage})}finally{I.current===e.scope&&c()===e.scope.runtimeGeneration&&_e()}}}),Ie=q(async e=>{let t=U.current;if(!t||!he.current.canLoadEarlier)return;let n=F,r=L,i=()=>I.current===n&&u()===n.runtimeKey&&c()===n.runtimeGeneration;if(!(Fe.isPending&&Fe.variables?.sessionId===t&&Fe.variables?.scope===n)){e?.userInitiated&&_?.();try{let r=await Fe.mutateAsync({sessionId:t,scope:n,userInitiated:!!e?.userInitiated,singlePage:e?.singlePage});if(!i())return;if(r===!1&&he.current.canLoadEarlier){let n={sessionId:t,grew:r,userInitiated:!!e?.userInitiated,canLoadEarlier:he.current.canLoadEarlier,hasMoreAboveTurns:he.current.hasMoreAboveTurns,historyLoading:he.current.historyLoading,historyMeta:ne.current,messageCount:W.current.length,oldestMessageId:W.current[0]?.info?.id??null};DW(`no-growth`,Error(`chat history pagination returned no growth`),n)}}catch(n){let a={sessionId:t,userInitiated:!!e?.userInitiated,waitMs:SW,hostTurnPageTimeoutMs:ja,canLoadEarlier:he.current.canLoadEarlier,historyLoading:he.current.historyLoading,historyMeta:ne.current,messageCount:W.current.length,oldestMessageId:W.current[0]?.info?.id??null};TW(n)?DW(`timeout`,n,a):DW(`failed`,n,a),i()&&e?.userInitiated&&Ha.error(TW(n)?Pe(`chat.history.loadOlderTimeout`):Pe(`chat.history.loadOlderFailed`),{id:r})}}}),Le=Fe.isPending&&Fe.variables?.sessionId===e&&Fe.variables?.scope===F||C,Re=n[0]?.info?.id??null,ze=e&&t?dn()?.getPagination(Vt(t,e)).cursor??null:null,Be=VW({enabled:g,isMobile:h,sessionReady:!!e,messageReady:n.length>0||!!r,historyLoading:me.historyLoading,canLoadEarlier:me.canLoadEarlier,isPinned:p,fillBlocked:k,scrollHeight:R.scrollHeight,clientHeight:R.clientHeight,pendingRevealWork:T,isLoadingOlder:!1,hasMessages:n.length>0});En({queryKey:[...HW({runtimeKey:u(),sessionId:e??``,oldestMessageId:Re,messageCount:n.length,canLoadEarlier:me.canLoadEarlier}),P,t??null,ze],enabled:!!e&&Be,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(!y.current||v.current||j.current||!V.current)return{status:`skip`};let e=U.current;if(!e)return{status:`skip`};let t=F,n=()=>I.current===t&&u()===t.runtimeKey&&c()===t.runtimeGeneration;if(!n())return{status:`skip`};if(he.current.historyLoading||H.current){let e=Error(`auto-fill-busy`);throw e.code=`auto-fill-busy`,e}if(!he.current.canLoadEarlier)return{status:`skip`};let r=i.current;if(!r||r.clientHeight<=0)return{status:`skip`};if(r.scrollHeight>r.clientHeight+48)return{status:`tall`};try{let t=await Ne({preserveViewport:!0});return n()?t?{status:`grew`}:(he.current.canLoadEarlier&&DW(`no-growth`,Error(`chat history pagination returned no growth`),{sessionId:e,source:`auto-fill`,grew:t,canLoadEarlier:he.current.canLoadEarlier,hasMoreAboveTurns:he.current.hasMoreAboveTurns,historyLoading:he.current.historyLoading,historyMeta:ne.current,messageCount:W.current.length,oldestMessageId:W.current[0]?.info?.id??null}),A(!0),{status:`blocked`}):{status:`skip`}}catch(t){if(t?.code===`auto-fill-busy`)throw t;let r={sessionId:e,source:`auto-fill`,waitMs:SW,canLoadEarlier:he.current.canLoadEarlier,historyLoading:he.current.historyLoading,historyMeta:ne.current,messageCount:W.current.length,oldestMessageId:W.current[0]?.info?.id??null};throw TW(t)?DW(`timeout`,t,r):DW(`failed`,t,r),n()&&A(!0),t instanceof Error?t:Error(`chat timeline auto-fill failed`)}}});let Ve=q(e=>{if(Date.now()<M.current)return;let t=i.current;if(t){if(v.current){let n=ce.current,r=t.scrollTop<n.top;if(n.top=t.scrollTop,n.consumed||(e===`upward-intent`&&(n.authorized=!0),!n.authorized||e===`scroll`&&!r))return}IW({source:e,isMobile:v.current,isPinned:V.current,scrollTop:t.scrollTop,clientHeight:t.clientHeight,canLoadEarlier:he.current.canLoadEarlier,isLoadingOlder:H.current,pendingRevealWork:ee.current})&&(v.current&&(ce.current.consumed=!0),Ie({userInitiated:!0,singlePage:v.current}))}}),He=q(()=>{Ve(`scroll`)}),Ue=q(()=>{Ve(`upward-intent`)}),We=q(async(t,n)=>{if(!t||!U.current)return!1;l(),E(!0);try{return U.current!==e||typeof B.current.turnIndexById.get(t)!=`number`?!1:!!await new Promise(r=>{ie.current={sessionId:U.current??e??``,kind:`turn`,id:t,behavior:n?.behavior??`auto`,turnId:t,resolve:r},xe()})}finally{E(!1)}}),Ge=q(async(t,n)=>{if(!t||!U.current)return!1;l(),E(!0);try{if(U.current!==e)return!1;let r=B.current.messageToTurnId.get(t);return typeof B.current.messageToTurnIndex.get(t)==`number`&&!!await new Promise(i=>{ie.current={sessionId:U.current??e??``,kind:`message`,id:t,behavior:n?.behavior??`auto`,turnId:r??null,resolve:i},xe()})}finally{E(!1)}}),Ke=q(async()=>{E(!1),H.current=!1,w(!1),a.current?.scrollToBottom(),s(`smooth`)}),qe=q(async()=>{E(!1),H.current=!1,w(!1),a.current?.scrollToBottom(),s(`instant`)}),Je=q(e=>{let t=ae.current;if(t){if(e!==t.turnId&&Date.now()<t.expiresAt)return;ae.current=null}O(e)});return{turnIds:S.turnIds,turnStart:0,renderedMessages:we,historySignals:me,isLoadingOlder:Le,pendingRevealWork:T,activeTurnId:D,showScrollToBottom:m&&!T,turnWindowModel:S,loadEarlier:Ie,revealBufferedTurns:je,resumeToBottom:Ke,resumeToBottomInstant:qe,scrollToTurn:We,scrollToMessage:Ge,handleHistoryScroll:He,handleHistoryUpwardIntent:Ue,captureViewportAnchor:De,restoreViewportAnchor:Oe,handleActiveTurnChange:Je}},aG=({mutateSession:e,forkSession:t})=>({revert:e,fork:t}),oG=({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]=Z.useState(null),[p,m]=Z.useState(``),[h,g]=Z.useState(0),_=Z.useRef(!1),v=Z.useRef(0),y=q(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)(Yo,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:(0,$.jsx)(sG,{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},sG=e=>{let t=(0,Q.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}=Wn(),b=Qb(),x=i,S=vo(x??``,a),C=Y(lG),w=Y(uG),T;t[0]===b.capabilities?T=t[1]:(T=aG(b.capabilities),t[0]=b.capabilities,t[1]=T);let E=T,{isMobile:D,isTablet:O}=Oc(),k=D||O,A;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(A=[],t[2]=A):A=t[2];let j=Z.useRef(A),M=Z.useRef(null),N=Z.useRef(null),P=Z.useRef(!1),F=Z.useRef(!1),I=dG,L=fG,R;t[3]===S?R=t[4]:(R=S.filter(pG).map(mG),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 TH(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],Z.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),Z.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),Z.useEffect(ne,W);let re;t[22]===u?re=t[23]:(re=()=>{!P.current||N.current||u||(P.current=!1)},t[22]=u,t[23]=re);let ie;t[24]!==V.length||t[25]!==u?(ie=[V.length,u],t[24]=V.length,t[25]=u,t[26]=ie):ie=t[26],Z.useEffect(re,ie);let ae,oe;t[27]!==n||t[28]!==p?(ae=()=>{let e=F.current;if(F.current=n,!n||e||P.current||p.trim())return;let t=M.current;t&&(t.scrollTop=t.scrollHeight)},oe=[n,p],t[27]=n,t[28]=p,t[29]=ae,t[30]=oe):(ae=t[29],oe=t[30]),Z.useLayoutEffect(ae,oe);let se;t[31]===u?se=t[32]:(se=()=>{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]=se);let ce;t[33]!==V.length||t[34]!==u?(ce=[V.length,u],t[33]=V.length,t[34]=u,t[35]=ce):ce=t[35],Z.useLayoutEffect(se,ce);let le;t[36]===d?le=t[37]:(le=()=>{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]=le);let ue=q(le),de;t[38]!==r||t[39]!==o?(de=async e=>{await o?.(e)!==!1&&r(!1)},t[38]=r,t[39]=o,t[40]=de):de=t[40];let fe=q(de),pe;t[41]!==V||t[42]!==fe||t[43]!==g||t[44]!==h?(pe=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&&fe(r.message.info.id)}}},t[41]=V,t[42]=fe,t[43]=g,t[44]=h,t[45]=pe):pe=t[45];let me=q(pe),he;t[46]!==x||t[47]!==a||t[48]!==w||t[49]!==f||t[50]!==C||t[51]!==v?(he=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]=he):he=t[52];let ge=q(he),_e;t[53]===Symbol.for(`react.memo_cache_sentinel`)?(_e=(0,$.jsx)(X,{name:`time`,className:`h-5 w-5`}),t[53]=_e):_e=t[53];let ve;t[54]===y?ve=t[55]:(ve=y(`chat.timeline.title`),t[54]=y,t[55]=ve);let ye;t[56]===ve?ye=t[57]:(ye=(0,$.jsxs)(Xo,{className:`flex items-center gap-2`,children:[_e,ve]}),t[56]=ve,t[57]=ye);let be;t[58]===y?be=t[59]:(be=y(`chat.timeline.description`),t[58]=y,t[59]=be);let xe;t[60]===be?xe=t[61]:(xe=(0,$.jsx)(Zo,{children:be}),t[60]=be,t[61]=xe);let Se;t[62]!==ye||t[63]!==xe?(Se=(0,$.jsxs)(Ko,{children:[ye,xe]}),t[62]=ye,t[63]=xe,t[64]=Se):Se=t[64];let Ce;t[65]===Symbol.for(`react.memo_cache_sentinel`)?(Ce=(0,$.jsx)(X,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),t[65]=Ce):Ce=t[65];let we;t[66]===y?we=t[67]:(we=y(`chat.timeline.searchPlaceholder`),t[66]=y,t[67]=we);let Te;t[68]===m?Te=t[69]:(Te=e=>m(e.target.value),t[68]=m,t[69]=Te);let Ee;t[70]!==me||t[71]!==p||t[72]!==we||t[73]!==Te?(Ee=(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[Ce,(0,$.jsx)(Ts,{autoFocus:!0,placeholder:we,value:p,onChange:Te,onKeyDown:me,className:`pl-9 w-full`})]}),t[70]=me,t[71]=p,t[72]=we,t[73]=Te,t[74]=Ee):Ee=t[74];let De;t[75]!==l||t[76]!==ue||t[77]!==u||t[78]!==d||t[79]!==y?(De=l&&d&&(0,$.jsx)(`div`,{className:`flex justify-center py-1`,children:(0,$.jsxs)(Jn,{type:`button`,variant:`link`,size:`sm`,onClick:ue,disabled:u,className:`h-auto px-1 py-0 text-muted-foreground hover:text-foreground`,children:[u&&(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}),y(`chat.history.loadOlder`)]})}),t[75]=l,t[76]=ue,t[77]=u,t[78]=d,t[79]=y,t[80]=De):De=t[80];let Oe;t[81]!==E.fork||t[82]!==E.revert||t[83]!==k||t[84]!==V||t[85]!==ge||t[86]!==fe||t[87]!==g||t[88]!==_||t[89]!==p||t[90]!==h||t[91]!==y?(Oe=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=EH(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()?cG(TH(n.parts),p):null;return(0,$.jsxs)(Z.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:J(`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 fe(n.info.id),onMouseEnter:()=>g(t),children:[(0,$.jsx)(`span`,{className:J(`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:J(`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:J(`gap-1`,k?`flex`:`hidden group-hover:flex`),children:[E.revert?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{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(),ge(`revert`,n.info.id)},children:(0,$.jsx)(X,{name:_?.type===`revert`&&_.messageId===n.info.id?`loader-4`:`arrow-go-back`,className:J(`h-4 w-4`,_?.type===`revert`&&_.messageId===n.info.id&&`animate-spin`)})})}),(0,$.jsx)(Ds,{sideOffset:6,children:y(`chat.timeline.actions.revertFromHere`)})]}):null,E.fork?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{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(),ge(`fork`,n.info.id)},disabled:_!==null,children:_?.type===`fork`&&_.messageId===n.info.id?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(X,{name:`git-branch`,className:`h-4 w-4`})})}),(0,$.jsx)(Ds,{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]=ge,t[86]=fe,t[87]=g,t[88]=_,t[89]=p,t[90]=h,t[91]=y,t[92]=Oe):Oe=t[92];let ke;t[93]===Oe?ke=t[94]:(ke=(0,$.jsx)(`div`,{ref:M,className:`flex-1 overflow-y-auto`,children:Oe}),t[93]=Oe,t[94]=ke);let Ae;t[95]===y?Ae=t[96]:(Ae=y(`chat.timeline.actions.title`),t[95]=y,t[96]=Ae);let je;t[97]===Ae?je=t[98]:(je=(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground font-medium mb-2`,children:Ae}),t[97]=Ae,t[98]=je);let Me;t[99]!==r||t[100]!==s?(Me=()=>{s?.(-1),r(!1)},t[99]=r,t[100]=s,t[101]=Me):Me=t[101];let Ne;t[102]===y?Ne=t[103]:(Ne=y(`chat.timeline.actions.previousTurn`),t[102]=y,t[103]=Ne);let Pe;t[104]!==Me||t[105]!==Ne?(Pe=(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:Me,children:Ne}),t[104]=Me,t[105]=Ne,t[106]=Pe):Pe=t[106];let Fe;t[107]===Symbol.for(`react.memo_cache_sentinel`)?(Fe=(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`/`}),t[107]=Fe):Fe=t[107];let Ie;t[108]!==r||t[109]!==c?(Ie=()=>{c?.(),r(!1)},t[108]=r,t[109]=c,t[110]=Ie):Ie=t[110];let Le;t[111]===y?Le=t[112]:(Le=y(`chat.timeline.actions.latest`),t[111]=y,t[112]=Le);let Re;t[113]!==Ie||t[114]!==Le?(Re=(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:Ie,children:Le}),t[113]=Ie,t[114]=Le,t[115]=Re):Re=t[115];let ze;t[116]!==Pe||t[117]!==Re?(ze=(0,$.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[Pe,Fe,Re]}),t[116]=Pe,t[117]=Re,t[118]=ze):ze=t[118];let Be;t[119]===y?Be=t[120]:(Be=y(`chat.timeline.help.clickMessage`),t[119]=y,t[120]=Be);let Ve;t[121]===Be?Ve=t[122]:(Ve=(0,$.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,$.jsx)(`span`,{children:Be})}),t[121]=Be,t[122]=Ve);let He;t[123]===Symbol.for(`react.memo_cache_sentinel`)?(He=(0,$.jsx)(X,{name:`arrow-go-back`,className:`h-4 w-4 flex-shrink-0`}),t[123]=He):He=t[123];let Ue;t[124]===y?Ue=t[125]:(Ue=y(`chat.timeline.help.undoToPoint`),t[124]=y,t[125]=Ue);let We;t[126]===Ue?We=t[127]:(We=(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[He,(0,$.jsx)(`span`,{children:Ue})]}),t[126]=Ue,t[127]=We);let Ge;t[128]!==E.fork||t[129]!==y?(Ge=E.fork?(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{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]=Ge):Ge=t[130];let Ke;t[131]!==Ve||t[132]!==We||t[133]!==Ge?(Ke=(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 typography-meta text-muted-foreground`,children:[Ve,We,Ge]}),t[131]=Ve,t[132]=We,t[133]=Ge,t[134]=Ke):Ke=t[134];let qe;t[135]!==je||t[136]!==ze||t[137]!==Ke?(qe=(0,$.jsxs)(`div`,{className:`mt-4 p-3 bg-muted/30 rounded-lg`,children:[je,ze,Ke]}),t[135]=je,t[136]=ze,t[137]=Ke,t[138]=qe):qe=t[138];let Je;return t[139]!==Se||t[140]!==Ee||t[141]!==De||t[142]!==ke||t[143]!==qe?(Je=(0,$.jsxs)($.Fragment,{children:[Se,Ee,De,ke,qe]}),t[139]=Se,t[140]=Ee,t[141]=De,t[142]=ke,t[143]=qe,t[144]=Je):Je=t[144],Je};function cG(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 lG(e){return e.revertToMessage}function uG(e){return e.forkFromMessage}function dG(e){return Ws(e)}function fG(e){return ks(e)}function pG(e){return e.info.role===`user`}function mG(e){return{message:e}}var hG=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},gG=(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`}},_G=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)},vG=e=>{let t=(0,Q.c)(29),{sessionId:n,turnIds:r,activeTurnId:i,scrollToTurn:a,scrollToMessage:o,resumeToBottom:s}=e,c=Z.useRef(r),l=Z.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),Z.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),Z.useEffect(f,p);let m;t[6]===a?m=t[7]:(m=async(e,t)=>e?(t?.updateHash!==!1&&_G(`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&&_G(`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=gG(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 _G(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=()=>{_G(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=hG(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],Z.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},yG=2e4,bG=6e4,xG=2e3,SG=e=>e?(typeof e.text==`string`?e.text.length:0)+(typeof e.state?.output==`string`?e.state.output.length:0):0,CG=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+=SG(e);return[e.length,t.info.id,n.length,r?.id??``,r?.state?.status??``,i].join(`:`)},wG={sessionKey:null,fingerprint:null,lastMovementAt:null,lastRefreshAt:null,attempts:0},TG=(e,t)=>{let{sessionKey:n,working:r,streaming:i,fingerprint:a,now:o}=t;if(!n)return{state:wG,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}},EG=e=>{console.warn(`[transcript] tail frozen while session is working — refetching authority`,e)};function DG(e){return!!(e.active&&e.sessionId&&e.sessionKey&&e.sessionIsWorking)}function OG(e){return e===wG?e:wG}function kG(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 AG(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 jG(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||kG(i)==null}function MG(e){let t=[];for(let n of e){let e=Array.isArray(n.parts)?n.parts:[];for(let n of e){if(!jG(n))continue;let e=AG(n);e&&t.push(e)}}return t}function NG(e,t){return`${e}:${t.join(`,`)}`}function PG(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=NG(t,e.unansweredToolIds);return e.attemptedKey===r?{recover:!1,attemptKey:r}:{recover:!0,attemptKey:r}}function FG(e,t,n,r){let i=(0,Q.c)(7),a=Li(),o=Z.useRef(null),s=Z.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=PG({sessionId:e,directory:t,sessionQuestionCount:r,unansweredToolIds:MG(n),attemptedKey:o.current});if(!c.recover||!e||!t||!c.attemptKey)return;let l=a.getChild(t);l&&(o.current=c.attemptKey,Zr(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]),Z.useEffect(c,l)}var IG=e=>!Number.isFinite(e)||e<0?0:Math.ceil(e),LG=(e,t)=>({...e,key:RG(e),estimatedBytes:IG(t)}),RG=({runtimeKey:e,sessionId:t,directory:n})=>JSON.stringify([e,n??``,t]),zG=e=>({key:e?RG(e):null,selection:e}),BG=(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},VG=(e,t,n,r)=>{let i=RG(t),a=e.findIndex(e=>e.key===i),o=a>=0?e[a]:void 0;if(o&&a===e.length-1)return BG(e,i,n);let s=o||LG(t,r),c=a>=0?e.filter((e,t)=>t!==a):[...e];return c.push(s),BG(c,i,n)},HG=(e,t,n)=>{let r=IG(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)},UG=(e,t)=>t&&e.some(e=>e.key===t)?t:null,WG=(e,t,n)=>{let r=t.key?e.cachedSessionViews.find(e=>e.key===t.key):void 0,i=r&&t.selection?VG(e.cachedSessionViews,t.selection,n,r.estimatedBytes):BG(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}},GG=(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:LG(t.selection,r),intent:t};return e.pendingSessionView?.intent===t?e:{activeIntent:e.activeIntent,cacheNeedsTrim:e.cacheNeedsTrim,cachedSessionViews:e.cachedSessionViews,pendingSessionView:i}},KG=(e,t,n)=>{let r=e.pendingSessionView;return e.activeIntent!==t||r?.intent!==t||!t.selection?e:{activeIntent:e.activeIntent,cacheNeedsTrim:!1,cachedSessionViews:VG(e.cachedSessionViews,t.selection,n,r.entry.estimatedBytes),pendingSessionView:null}},qG=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},JG=e=>{if(!(!e.info||typeof e.info!=`object`))return e.info},YG=e=>JG(e)?.role===`assistant`,XG=(e,t)=>{let n=JG(t);n&&(e.agentName??=qG(n.agent),e.providerId??=qG(n.providerID),e.modelId??=qG(n.modelID))},ZG=e=>!!(e.agentName&&e.providerId&&e.modelId),QG=e=>{let t={};for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||!YG(r))&&(XG(t,r),ZG(t)))return t}for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||YG(r))&&(XG(t,r),ZG(t)))break}return t},$G=e=>!!e.sessionId&&!(e.hasRenderableSessionSnapshot&&e.hasCurrentSessionEntity),eK=[],tK=[],nK=[],rK={type:`idle`},iK=`openchamber:chat-force-scroll-bottom`,aK=()=>void 0,oK=`Quota limit reached. Retrying automatically.`,sK=1048576,cK=sK,lK=20,uK=sK,dK=16*sK,fK={maxEntries:3,maxEstimatedBytes:32*sK},pK={maxEntries:2,maxEstimatedBytes:32*sK},mK=e=>i(()=>e()),hK={overflowAnchor:`none`,overscrollBehavior:`contain`,overscrollBehaviorY:`contain`},gK={scrollbar:`chat`,scrollShadow:`true`,orientation:`vertical`},_K=()=>{let e=(0,Q.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},vK=`calc(max(0.625rem, var(--oc-safe-area-top, 0px)) + var(--oc-mobile-detail-navigation-height) + 1.25rem)`,yK=eU,bK=[`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(`,`),xK=e=>e instanceof HTMLElement,SK=e=>xK(e)?!!e.closest(bK):!1,CK=(e,t)=>typeof document>`u`||!e||e===document.body||e===document.documentElement||SK(e)?!0:!t?.contains(e),wK=()=>{let{isAboutDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isImagePreviewOpen:r,isMultiRunLauncherOpen:i,isSessionSwitcherOpen:a,isSettingsDialogOpen:o}=K.getState();return e||t||n||r||i||a||o},TK=Z.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,sessionForms:E,retryActionCopy:D,isProgrammaticFollowActive:O,showLoadOlderButton:k,turnIds:A,activeTurnId:j,onSelectTurn:M,showPromptNavigator:N,canLoadEarlierPrompts:P,isLoadingOlderPrompts:F,onLoadEarlierPrompts:I,transcriptStatusRow:L})=>{let{t:R}=Wn(),z=xu(e=>e.legendTimelineEnabled),B=FD({isLoadingOlder:d}),[V,H]=Z.useState({sessionId:e,directory:a,reserved:k}),ee=V.sessionId===e&&V.directory===a,U=ee&&V.reserved||k;(!ee||V.reserved!==U)&&H({sessionId:e,directory:a,reserved:U});let te=ID({isMobile:r,isLoadingOlder: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,$.jsx)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:(0,$.jsx)(`span`,{className:`oc-mobile-glass-control flex size-8 items-center justify-center rounded-full text-[var(--surface-mutedForeground)]`,"aria-label":R(`chat.history.loadingMore`),children:(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`,"aria-hidden":`true`})})})}):null,W=r&&U?(0,$.jsx)(`div`,{className:J(`flex justify-center pt-3 pb-1`,!B&&`invisible`),"aria-hidden":!B,children:(0,$.jsxs)(`span`,{role:`status`,className:`flex items-center gap-1.5 text-[var(--surface-mutedForeground)]`,"aria-busy":B,children:[(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta`,children:R(`chat.history.loadingMore`)})]})}):null,ne=Z.useRef(new Map),re=Z.useRef(new WeakMap),ie=Z.useRef(new Map),ae=Z.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(jI(n)){let r=PI(u,t)??``,i=ie.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`}];ie.current.set(n.info.id,{command:r,parts:t}),e.set(n.info.id,t)}continue}if($i(n.parts))continue;let r=re.current.get(n.parts);r||(r=DD(n.parts),re.current.set(n.parts,r)),r.length!==0&&e.set(n.info.id,r)}let t=ne.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 ne.current=e,e},[u]),oe=Z.useMemo(()=>A.filter(e=>ae.has(e)),[ae,A]),se=Z.useMemo(()=>{if(!j||ae.has(j))return j;let e=A.indexOf(j);for(let t=e-1;t>=0;--t){let e=A[t];if(ae.has(e))return e}return null},[j,ae,A]),ce=q(e=>{e.defaultPrevented||SK(e.target)||typeof window<`u`&&window.getSelection()?.type===`Range`||o.current?.focus({preventScroll:!0})});return dl({scrollRef:o,enabled:z,onUpwardIntent:y}),z?(0,$.jsx)(`div`,{className:J(`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)(VV,{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:hK,timelineScrollDataset:gK,timelineOnScroll:v,timelineFollowEnabled:!c&&!x,timelineHistoryAnchorToken:S,timelineOnIsAtEndChange:b,headerSlot:(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:vK},"aria-hidden":`true`}),W,te]}),footerSlot:(0,$.jsxs)($.Fragment,{children:[(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(mH,{question:e},e.id)),T.map(e=>(0,$.jsx)(sH,{permission:e},e.id))]}),L?(0,$.jsx)(`div`,{className:`mb-1`,children:L}):null,a&&(0,$.jsx)(wH,{sessionID:e,directory:a}),(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?yK:QH},"aria-hidden":`true`})]})}),(0,$.jsx)(kc,{containerRef:o,suppressVisibility:O,userIntentOnly:!0,observeMutations:!1}),N&&oe.length>=2?(0,$.jsx)(qH,{turnIds:oe,previewsByTurnId:ae,activeTurnId:se,onSelectTurn:M,canLoadEarlier:P,isLoadingOlder:F,onLoadEarlier:I}):null]})}):(0,$.jsx)(`div`,{className:J(`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)(Wc,{className:J(`absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target`),ref:o,style:hK,observeMutations:!1,hideTopShadow:r&&i,hideBottomShadow:r,tabIndex:0,onClick:ce,onScroll:v,"data-scroll-shadow":`true`,"data-scrollbar":`chat`,children:(0,$.jsxs)(`div`,{className:J(`oc-chat-scroll-content relative z-0 min-h-full`,r&&`chat-scroll-foot-inset`),children:[W,te,(0,$.jsx)(VV,{ref:s,sessionKey:e,virtualizerKey:t,timelineHistoryAnchorToken:S,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:L??(0,$.jsx)(TL,{})}):null}),(w.length>0||T.length>0||E.length>0||D)&&(0,$.jsxs)(`div`,{children:[D?(0,$.jsxs)(`div`,{className:`mb-2 rounded-xl border border-border/20 bg-muted/10 px-2.5 py-2`,children:[(0,$.jsx)(`div`,{className:`typography-ui-label text-foreground`,children:D.title}),(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mt-1`,children:D.message}),D.link?(0,$.jsx)(`a`,{href:D.link,target:`_blank`,rel:`noreferrer`,className:`mt-2 inline-block typography-meta text-primary underline`,children:D.label}):null]}):null,w.map(e=>(0,$.jsx)(mH,{question:e},e.id)),T.map(e=>(0,$.jsx)(sH,{permission:e},e.id)),E.map(e=>(0,$.jsx)(gH,{form:e,directory:a},e.id))]}),a&&(0,$.jsx)(wH,{sessionID:e,directory:a}),(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?$H:QH},"aria-hidden":`true`})]})}),(0,$.jsx)(kc,{containerRef:o,suppressVisibility:O,userIntentOnly:!0,observeMutations:!1}),N&&oe.length>=2?(0,$.jsx)(qH,{turnIds:oe,previewsByTurnId:ae,activeTurnId:se,onSelectTurn:M,canLoadEarlier:P,isLoadingOlder:F,onLoadEarlier:I}):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.sessionForms===t.sessionForms&&e.retryActionCopy===t.retryActionCopy&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&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);TK.displayName=`ChatViewport`;var EK=[{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%]`]}],DK=e=>Gn(e.path),OK=(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)]})},kK=e=>{let t=Math.ceil(Math.max(0,e)/lK);return Math.min(dK,cK+t*uK)},AK=Z.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=tK,onPendingUserMessagesMaterialized:p,committedDraftHandoffMessageId:m=null})=>{let h=c??BD(void 0),{t:g}=Wn();zn(()=>{Aa()},[]);let _=Y(e=>e.openNewSessionDraft),v=Y(e=>e.setCurrentSession),y=Y(e=>e.newSessionDraft),b=Y(e=>e.newSessionDraft.draftSubmitting??!1),x=Y(e=>e.newSessionDraft.draftEstablishing??!1),S=Y(e=>e.forkTransition),C=Co(e=>e.projects),w=Co(e=>e.activeProjectId),T=ao(e=>e.providers),E=Ih(),D=Bo(),O=i??D;zn(()=>{!n||!r||!O||Ti(O,r)},[n,r,O]);let k=q(e=>E.ensureSessionRenderable(e,{directory:O})),A=K(e=>e.isExpandedInput),j=K(e=>e.stickyUserHeader),M=K(e=>e.promptNavigatorEnabled),N=K(e=>e.allowPromptingSubagentSessions),P=K(e=>e.isTimelineDialogOpen),F=K(e=>e.setTimelineDialogOpen),I=ei(e=>n&&r?e.streamingMessageIds.get(r)??null:null),L=ei(e=>I?e.messageStreamStates.get(I)?.phase??null:null),R=oa(r??``,O),z=kK(R);Z.useEffect(()=>{!a||!o||o(a,z)},[o,z,a]);let B=za(r??``,O).renderable,V=Sa(r,O),H=Ui(r),ee=V??H,U=qx({sessionId:r,hasSessionEntity:!!ee,hasRenderableSessionSnapshot:B,composerSurfaceKind:s?.kind}),te=r?JSON.stringify([O,r]):null,[W,ne]=Z.useState({key:te,attempt:0}),re=vo(r??``,O,{suspendPartUpdates:!!I,suspendPartUpdatesForMessageId:I,enabled:n}),ie=r?re:eK,ae=y.pendingUserMessage,oe=Y(e=>r?e.retainedPendingUserMessages.get(r):void 0)??tK,se=!!(m||oe.length>0),ce=Y(e=>e.clearRetainedPendingUserMessages),le=Z.useMemo(()=>{if(oe.length===0)return f;if(f.length===0)return oe;let e=new Set(f.map(e=>e.info.id));return[...f,...oe.filter(t=>!e.has(t.info.id))]},[f,oe]),ue=Z.useMemo(()=>QG(ie),[ie]),de=Z.useMemo(()=>{if(!ue.modelId)return g(`common.unavailable`);let e=T.find(e=>e.id===ue.providerId);return hr(e,ue.modelId)||ue.modelId},[T,ue.modelId,ue.providerId,g]),pe=ro(r??``,O),me=Ma(r??``,O),[he,ge]=Z.useState(null),_e=!!r&&he===r,ve=q(()=>{if(!r||_e)return;let e=r,t=O;ge(e);let n=Ai(()=>{let n=dn();if(!n)throw Error(`unbound`);return n.getTranscript(Vt(t,e))});Di(gr({kind:`refresh`,sessionID:e,directory:t,purpose:`retry`,source:`network`,request:pe?{sessionID:e,status:pe.status===`ready`?`ready`:pe.status,error:pe.error}:void 0,hydration:me,error:pe?.error})),(async()=>{try{await Wt(t,e),await E.ensureSessionRenderable(e,{directory:t});try{let r=Ai(()=>{let n=dn();if(!n)throw Error(`unbound`);return n.getTranscript(Vt(t,e))});n&&r&&dr({trigger:`user-refresh`,sessionID:e,directory:t,purpose:`retry`,before:n,after:r})}catch{}}catch(n){Di(gr({kind:`request-error`,sessionID:e,directory:t,purpose:`retry`,source:`network`,hydration:me,error:n}))}finally{ge(t=>t===e?null:t)}})()}),ye=ra(r??``,O).boundary,be=q(async e=>{if(ye.kind===`has-more`){await pn(O,e);return}if(ye.kind===`unknown`){await sn(O,e);return}l&&!l.complete&&await l.fetchPrevious()}),xe=so(r??``,O),Se=Za(r??``,O),Ce=Fa(O),we=xe??rK,Te=yi(r,O),Ee=tr(r,O),De=Cr(e=>r?e.forms[r]??nK:nK),Oe=Z.useMemo(()=>De.filter(e=>!vt(e.metadata)),[De]);Z.useEffect(()=>{r&&ji({sessionID:r,directory:O}).catch(e=>{console.error(`[ChatContainer] Failed to list session forms:`,e)})},[r,O]),FG(r,O,ie,Ee.length);let ke=Z.useMemo(()=>{if(!r||Te.length>0||Ee.length>0)return!1;let e=we.type??`idle`;if(e===`busy`||e===`retry`||jD(le,{resolvedSessionStatus:xe,sessionStatusObservedAt:Se}))return!0;let t=ie[ie.length-1]?.info,n=t?.time?.created;return xe&&typeof Se==`number`&&typeof n==`number`&&n<=Se||typeof Ce==`number`&&typeof n==`number`&&n<=Ce?!1:!!(t&&t.role===`assistant`&&typeof t.time?.completed!=`number`)},[r,le,xe,ie,Te.length,Ee.length,we.type,Se,Ce]),Ae=Z.useMemo(()=>!r||we.type!==`retry`?null:{sessionId:r,message:(typeof we.message==`string`?(we.message??``).trim():``)||oK,confirmedAt:we.confirmedAt},[r,we]),[je,Me]=Z.useState(0),Ne=Z.useRef(null);Z.useEffect(()=>{if(!Ae||typeof Ae.confirmedAt==`number`){Ne.current=null,Me(0);return}Ne.current!==Ae.sessionId&&(Ne.current=Ae.sessionId,Me(Date.now()))},[Ae]);let Pe=Z.useMemo(()=>!Ae||bH(we)?null:{...Ae,fallbackTimestamp:je},[Ae,je,we]),Fe=Z.useMemo(()=>xH(we,e=>g(e)),[we,g]),Ie=!!(r&&E.isLoading(r,{directory:O})),Le=Z.useMemo(()=>{if(!r)return null;let e=MD({boundary:ye,assistantComplete:l?.complete??!0});return{limit:ye.loadedTurns,complete:e.complete,canLoadEarlier:e.canLoadEarlier,loading:ND({syncLoading:Ie,assistantLoading:!!l?.loading})}},[l?.complete,l?.loading,r,ye,Ie]),Re=K(e=>e.isMobile),ze=qc()!==null,Be=fe(),Ve=Ix(),He=!!y?.open,Ue=ii(e=>e.error),We=A,Ge=ze||Re||Be||Ve===`mini-chat`,Ke=Z.useRef(null),qe=Z.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?DK(n):null},[w,y?.selectedProjectId,C]),Je=Ji(r,O),Ye=a??r??``,[Xe,Ze]=Z.useState(null),Qe=Qx(Xe,Ye,Je,ue);zn(()=>{Ze(e=>Qx(e,Ye,Je,ue))},[Je,ue,Ye]);let $e=Je??Qe?.parentTarget??null,et=Qe?.execution??ue,tt=wp(),nt=tt!==null&&r===tt,rt=q(()=>{$e&&v($e.id,$e.directory)}),it=$e?.session?.title,at=h.returnToParent&&$e&&!nt?(0,$.jsxs)(Jn,{type:`button`,variant:`outline`,size:`xs`,onClick:rt,className:`absolute left-3 top-3 z-20 !font-normal bg-[var(--surface-background)]/95`,"aria-label":g(`chat.container.returnToParent.aria`),title:it?.trim()?g(`chat.container.returnToParent.titleNamed`,{title:it}):g(`chat.container.returnToParent.title`),children:[(0,$.jsx)(X,{name:`arrow-left`,className:`h-4 w-4`}),g(`chat.container.returnToParent.label`)]}):null,ot=Jx({readOnly:t,sessionIdentityPending:U,isSubagentSession:!!ee?.parentID||!!Qe,allowPromptingSubagentSessions:N}),st=et.modelId===ue.modelId?de:et.modelId?hr(T.find(e=>e.id===et.providerId),et.modelId)||et.modelId:g(`common.unavailable`),ct=$e?(0,$.jsx)(WD,{agentName:et.agentName,providerId:et.providerId,modelId:et.modelId,modelName:st}):(0,$.jsx)(WD,{}),lt=q(e=>{K.getState().setAllowPromptingSubagentSessions(e.allowPromptingSubagentSessions)}),ut=q(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`&<({allowPromptingSubagentSessions:t.payload.allowPromptingSubagentSessions})}),dt=typeof window<`u`&&window.parent!==window;Bn(`message`,ut,dt?window:aK),Vn(()=>{if(!dt)return;let e=window;e.__openchamberApplyChatSettingsSync=lt,window.parent.postMessage({type:`openchamber:chat-settings-request`},window.location.origin)}),Rn(()=>{if(typeof window>`u`)return;let e=window;e.__openchamberApplyChatSettingsSync===lt&&delete e.__openchamberApplyChatSettingsSync}),Z.useEffect(()=>{h.newSessionDraft&&e&&!r&&!He&&_()},[e,r,He,h.newSessionDraft,_]);let ft=Z.useRef(()=>{}),mt=q(e=>{ft.current(e)}),ht=Z.useRef(()=>{}),gt=q(()=>{ht.current()}),_t=xu(e=>e.legendTimelineEnabled),[yt,bt]=Z.useState(!0),[xt,St]=Z.useState(!1),[Ct,wt]=Z.useState(!1),[Tt,Et]=Z.useState(0),Dt=q(()=>{Et(e=>e+1)}),Ot=q((e,t)=>{bt(e),e&&wt(!1),t!==void 0&&St(t)});Z.useEffect(()=>{bt(!0),St(!1),wt(!1)},[r]);let{scrollRef:kt,notifyContentChange:At,getAnimationHandlers:jt,goToBottom:Mt,scrollToBottomOnSend:Nt,releaseAutoFollow:Pt,beginHistoryViewportPreservation:Ft,endHistoryViewportPreservation:It,restoreSnapshot:Lt,isPinned:Rt,isFollowingProgrammatically:zt,showScrollButton:Bt}=xU({enabled:n&&!_t,currentSessionId:r,viewportKey:a,sessionMessageCount:R,sessionIsWorking:ke,isMobile:Re,onActiveTurnChange:mt,onUpwardUserIntent:gt}),Ht=Z.useRef(null);WU({enabled:Re,scrollRef:kt,scopeRef:Ht});let Ut=Z.useRef([]),Gt=Z.useMemo(()=>{let e=$D(l?.entries??[],r,Ut.current);return Ut.current=e,e},[l?.entries,r]),Kt=Z.useRef([]),qt=Z.useMemo(()=>{if(!l)return ie;let e=nO(l.entries,r,ie,Kt.current);return Kt.current=e,e},[l,r,ie]),Jt=Z.useMemo(()=>AD(Gt.length===0?qt:r?[...Gt,ZD(r),...qt]:Gt,le),[r,qt,Gt,le]),Yt=Z.useRef(null),Xt=Z.useMemo(()=>zD({sessionId:r,messages:Jt,retained:Yt.current}),[r,Jt]);Yt.current=Xt.retained;let Zt=Xt.messages,Qt=Z.useRef(null),$t=Qt.current===r,en=Z.useRef(wG),tn=r?`${O}\n${r}`:null,nn=q(()=>CG(Zt));Z.useEffect(()=>{if(!DG({active:n,sessionId:r,sessionKey:tn,sessionIsWorking:ke})){en.current=OG(en.current);return}let e=r,t=O,i=setInterval(()=>{let n=nn(),r=TG(en.current,{sessionKey:tn,working:!0,streaming:!!I,fingerprint:n,now:Date.now(),thresholdMs:yG,cooldownMs:bG,maxAttempts:3});en.current=r.state,r.shouldRefresh&&(EG({sessionId:e,directory:t,stalledForMs:r.stalledForMs,attempt:r.state.attempts,fingerprint:n}),pt(t,e).catch(()=>{}))},xG);return()=>clearInterval(i)},[n,r,O,nn,ke,I,tn]);let rn=Z.useMemo(()=>{if(le.length===0)return[];let e=new Set([...Gt,...qt].filter(e=>kD(e.parts)).map(e=>e.info.id));return le.map(e=>e.info.id).filter(t=>e.has(t))},[qt,Gt,le]);Z.useEffect(()=>{rn.length!==0&&(p?.(rn),r&&ce(r,rn))},[ce,r,rn,p]);let an=iG({sessionId:r,directory:O,messages:Zt,historyMeta:Le,scrollRef:kt,messageListRef:Ke,loadMoreMessages:be,goToBottom:Mt,releaseAutoFollow:Pt,beginHistoryViewportPreservation:Ft,endHistoryViewportPreservation:It,isPinned:_t?yt:Rt,showScrollButton:_t?xt:Bt,isMobile:Re,autoFillEnabled:n&&!We,onWillLoadEarlier:Dt}),on=q(()=>{wt(!1),Ke.current?.scrollToBottom(),Mt(`instant`)}),cn=q(()=>{wt(!1),Nt()}),ln=q(()=>{wt(!0),an.handleHistoryUpwardIntent()}),un=PD({isMobile:Re,canLoadEarlier:an.historySignals.canLoadEarlier,isLoadingOlder:an.isLoadingOlder}),fn=an.isLoadingOlder,mn=an.loadEarlier,hn=q(()=>{wt(!0),mn({userInitiated:!0})});ft.current=an.handleActiveTurnChange,ht.current=an.handleHistoryUpwardIntent,Z.useEffect(()=>{(Te.length!==0||Ee.length!==0)&&At(`permission`)},[At,Te,Ee]);let gn=vG({sessionId:r,turnIds:an.turnIds,activeTurnId:an.activeTurnId,scrollToTurn:an.scrollToTurn,scrollToMessage:an.scrollToMessage,resumeToBottom:on}),_n=ot.showReadOnlyBanner?ct:t?null:(0,$.jsx)(aD,{surface:s,scrollToBottom:cn,showScrollToBottom:Re&&an.showScrollToBottom,onScrollToBottom:gn.resumeToLatest,submissionBlocked:ot.blockSubmission}),vn=q(e=>{gn.scrollToTurnId(e,{behavior:`smooth`})}),G=an.historySignals.canLoadEarlier,yn=h.promptNavigator&&!Re&&!Be&&!We&&M&&an.turnIds.length>=2;Z.useEffect(()=>{yn||K.getState().setPromptNavigatorPanelOpen(!1)},[yn]);let bn=q(e=>{if(!n||!r)return;let t=e;t.detail?.sessionId&&t.detail.sessionId!==r||Mt(`instant`)});Bn(iK,bn,n&&r&&typeof window<`u`?window:aK);let xn=q(e=>{if(!n||!r||We||e.defaultPrevented||e.isComposing||e.key!==`ArrowUp`&&e.key!==`ArrowDown`||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let{activeMainTab:t}=K.getState();if(t!==`chat`||wK())return;let i=kt.current;if(CK(document.activeElement,i)||SK(e.target))return;e.preventDefault();let a=e.key===`ArrowUp`?-1:1;gn.scrollByTurnOffset(a,{resumePastEnd:!1})});Bn(`keydown`,xn,n&&r&&!We&&typeof window<`u`?window:aK);let Sn=Z.useRef(0),Cn=q(()=>{let e=kt.current;e&&e.style.setProperty(`--chat-scroll-height`,`${e.clientHeight}px`)}),wn=q(()=>{Sn.current||=requestAnimationFrame(()=>{Sn.current=0,Cn()})});zn(()=>{n&&Cn()},[n,r,We,Cn]);let Tn=typeof ResizeObserver<`u`;In(n&&Tn?kt:null,wn),Bn(`resize`,wn,n&&!Tn&&typeof window<`u`?window:aK),Rn(()=>{Sn.current&&=(cancelAnimationFrame(Sn.current),0)});let En=Z.useRef(null),Dn=Z.useRef(0),On=LD({transcriptMessageCount:ie.length,pendingUserCount:le.length,historyPrefixCount:Gt.length}),kn=RD({hasTranscriptShell:On,transcriptRecords:ie,p0Satisfied:me.p0Satisfied,hasBusyShell:ke&&On,hasImmediateShell:le.length>0||Gt.length>0,hasRenderableSessionSnapshot:B,prefetchStatus:pe?.status,syncLoading:!!(r&&E.isLoading(r,{directory:O})),userRetrying:_e,hasPaintedTranscript:$t});kn===`pass`&&Zt.length>0&&(Qt.current=r);let An=!!r&&kn===`hydrating`,jn=!!r&&kn===`load-error`;Z.useEffect(()=>{!jn||!r||Di(gr({kind:`request-error`,sessionID:r,directory:O,purpose:`load-failed`,source:`network`,request:pe?{sessionID:r,status:pe.status===`ready`?`ready`:pe.status,error:pe.error}:void 0,hydration:me,error:pe?.error}))},[r,O,jn,pe,me]),Z.useEffect(()=>{if(!n||!r||An)return;let e=Zt.length,t=En.current!==r,i=!t&&Dn.current===0&&e>0;if(!t&&!i){En.current===r&&(Dn.current=e);return}let a=typeof window<`u`&&window.location.hash.length>0;if(En.current=r,Dn.current=e,a){Pt();return}let o=()=>{Lt()};typeof window>`u`?o():window.requestAnimationFrame(o)},[n,r,An,Pt,Lt,Zt.length]),Z.useEffect(()=>{ne(e=>e.key===te?e:{key:te,attempt:0})},[te]),Z.useEffect(()=>{if(!n||!r||W.key!==te||!$G({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)(my,{})]}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground/70 tabular-nums`,children:n})]})})}if(!r&&!He)return e&&!Ue?(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)(KD,{})});if(!r&&He){if((b||x)&&ae){let e=`draft:${y.draftID??`pending`}`;return(0,$.jsxs)(`div`,{ref:Ht,className:J(`relative flex h-full flex-col bg-background`,Re&&`oc-chat-composer-swap-scope`),children:[(0,$.jsx)(TK,{currentSessionId:e,virtualizerKey:e,isDesktopExpandedInput:!1,isMobile:Re,stickyUserHeader:j,directory:O,scrollRef:kt,messageListRef:Ke,pendingRevealWork:!1,initialPinRevealComplete:!0,renderedMessages:[ae],isLoadingOlder:!1,sessionIsWorking:!0,streamingMessageId:null,activeStreamingPhase:null,retryOverlay:null,handleMessageContentChange:At,getAnimationHandlers:jt,handleHistoryScroll:an.handleHistoryScroll,handleHistoryUpwardIntent:ln,onTimelineIsAtEndChange:Ot,timelineFollowSuspended:!1,timelineHistoryAnchorToken:Tt,scrollToBottom:on,sessionQuestions:[],sessionPermissions:[],sessionForms:[],retryActionCopy:null,isProgrammaticFollowActive:zt,showLoadOlderButton:!1,turnIds:[],activeTurnId:null,onSelectTurn:vn,showPromptNavigator:!1,canLoadEarlierPrompts:!1,isLoadingOlderPrompts:!1,onLoadEarlierPrompts:hn,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)(my,{})]})})},e),(0,$.jsxs)(`div`,{className:J(`invisible pointer-events-none relative z-10`,Re&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,We?`absolute inset-0 bg-background`:`bg-background`),"aria-hidden":`true`,children:[!Re&&!We?(0,$.jsx)(_K,{}):null,_n]}),(0,$.jsx)(fD,{})]})}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)(my,{})]})})}):(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[Ge&&!We?(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:OK(qe?g(`chat.emptyState.draftTitleWithProject`,{project:qe}):g(`chat.emptyState.draftTitle`),qe)}),(0,$.jsx)(WS,{onSubmit:e=>yo.getState().requestPresetSubmit(e),className:`oc-draft-starters mt-8 max-w-md`})]}):null,(0,$.jsx)(`div`,{className:J(`relative z-10 flex min-h-0`,Re&&`oc-mobile-composer-foot`,We?`flex-1 bg-background`:Ge?J(`bg-background`,`px-0`):`flex-1 items-center justify-center bg-background px-0 pb-[6vh]`),children:_n})]})}return r?jn?(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[at,(0,$.jsx)(`div`,{className:J(`relative min-h-0`,We?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":We,children:We?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)(X,{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)(Jn,{type:`button`,className:`mt-5`,onClick:ve,children:[(0,$.jsx)(X,{name:`refresh`,className:`size-4`,"aria-hidden":`true`}),g(`chat.history.retry`)]})]})})}),(0,$.jsx)(`div`,{className:J(`relative z-10`,Re&&`oc-mobile-composer-foot`,We?`flex-1 min-h-0 bg-background`:`bg-background`),children:_n})]}):An?(0,$.jsxs)(`div`,{ref:Ht,className:J(`relative flex flex-col h-full bg-background`,Re&&`oc-chat-composer-swap-scope`),children:[at,(0,$.jsx)(`div`,{className:J(`relative min-h-0`,We?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":We,children:(0,$.jsx)(`div`,{ref:kt,className:`absolute inset-0 overflow-y-auto overflow-x-hidden bg-background pt-6 chat-scroll`,style:hK,children:(0,$.jsx)(`div`,{className:`space-y-4 chat-scroll-foot-inset`,children:EK.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)(Vd,{className:`h-3.5 w-3.5 rounded-full flex-shrink-0`}),(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,t.titleWidth)}),(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,t.detailWidth)})]},`${e.id}-${t.id}`))}),(0,$.jsxs)(`div`,{className:`space-y-1.5 pt-1`,children:[(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,e.textWidths[0])}),(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,e.textWidths[1])}),(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,e.textWidths[2])})]})]})})},e.id))})})}),(0,$.jsxs)(`div`,{className:J(`relative z-10`,Re&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,We?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Re&&!We?(0,$.jsx)(_K,{}):null,_n]})]}):Zt.length===0&&!ke?(0,$.jsxs)(`div`,{className:`relative flex flex-col h-full bg-background`,children:[at,(0,$.jsx)(`div`,{className:J(`relative min-h-0`,We?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":We,children:We?null:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,$.jsx)(KD,{})})}),(0,$.jsx)(`div`,{className:J(`relative z-10`,Re&&`oc-mobile-composer-foot`,We?`flex-1 min-h-0 bg-background`:`bg-background`),children:_n}),(0,$.jsx)(fD,{})]}):(0,$.jsxs)(`div`,{ref:Ht,className:J(`relative flex flex-col h-full bg-background`,Re&&`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,at,(0,$.jsx)(TK,{currentSessionId:r,virtualizerKey:a??r,isDesktopExpandedInput:We,isMobile:Re,stickyUserHeader:j,directory:O,scrollRef:kt,messageListRef:Ke,pendingRevealWork:an.pendingRevealWork,initialPinRevealComplete:se,renderedMessages:an.renderedMessages,isLoadingOlder:fn,sessionIsWorking:ke,streamingMessageId:I,activeStreamingPhase:L,retryOverlay:Pe,handleMessageContentChange:At,getAnimationHandlers:jt,handleHistoryScroll:an.handleHistoryScroll,handleHistoryUpwardIntent:ln,onTimelineIsAtEndChange:Ot,timelineFollowSuspended:Ct,timelineHistoryAnchorToken:Tt,scrollToBottom:on,sessionQuestions:Ee,sessionPermissions:Te,sessionForms:Oe,retryActionCopy:Fe,isProgrammaticFollowActive:zt,showLoadOlderButton:un,turnIds:an.turnIds,activeTurnId:an.activeTurnId,onSelectTurn:vn,showPromptNavigator:yn,canLoadEarlierPrompts:G,isLoadingOlderPrompts:fn,onLoadEarlierPrompts:hn},r),(0,$.jsxs)(`div`,{className:J(`relative z-10`,Re&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,We?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Re&&!We?(0,$.jsx)(_K,{}):null,!We&&Zt.length>0&&(Re?(0,$.jsx)(Px,{placement:`expanded`,visible:an.showScrollToBottom,onClick:gn.resumeToLatest}):(0,$.jsx)(Px,{visible:an.showScrollToBottom,onClick:gn.resumeToLatest})),_n]}),(0,$.jsx)(fD,{}),(0,$.jsx)(oG,{open:P,onOpenChange:F,sessionID:r??void 0,directory:O,onRevertMessage:u,onScrollToMessage:an.scrollToMessage,onScrollByTurnOffset:gn.scrollByTurnOffset,onResumeToLatest:on,canLoadEarlier:an.historySignals.canLoadEarlier,isLoadingEarlier:fn,onLoadEarlier:hn})]}):null});AK.displayName=`MemoizedChatContainerContent`;var jK=()=>{let e=(0,Q.c)(2),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Vd,{className:`h-4 w-4/5 animate-none rounded-md`}),(0,$.jsx)(Vd,{className:`h-4 w-2/3 animate-none rounded-md`}),(0,$.jsx)(Vd,{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)(Vd,{className:`h-4 w-5/6 animate-none rounded-md`}),(0,$.jsx)(Vd,{className:`h-4 w-3/5 animate-none rounded-md`})]}),(0,$.jsx)(Vd,{className:`h-24 w-full animate-none rounded-xl`})]})})}),e[1]=n):n=e[1],n},MK=({runtimeKey:e,...t})=>{let n=Ix(),r=Bo(),i=Y(Je(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=Z.useRef(null),o=i.draftID&&i.draftPendingMessageId?`${i.draftID}:${i.draftPendingMessageId}`:null;o&&a.current?.identity!==o&&(a.current=null),zn(()=>{!o||!i.draftPendingMessageId||(a.current={identity:o,messageId:i.draftPendingMessageId})},[o,i.draftPendingMessageId]);let s=Y(e=>i.sessionId?e.retainedPendingUserMessages.get(i.sessionId)??tK:tK),c=a.current,l=c&&s.some(e=>e.info.id===c.messageId)?c.messageId:null,u=Z.useMemo(()=>i.sessionId?{runtimeKey:e,sessionId:i.sessionId,directory:i.directory??r}:null,[e,i.directory,i.sessionId,r]),d=Z.useMemo(()=>zG(u),[u]),f=d.key,p=Rr()||fe()||n===`mini-chat`?pK:fK,[m,h]=Z.useState(()=>({activeIntent:d,cacheNeedsTrim:!1,cachedSessionViews:u?VG([],u,p,cK):[],pendingSessionView:null})),g=Z.useRef(d),_=Z.useRef(f),{cacheNeedsTrim:v,cachedSessionViews:y,pendingSessionView:b}=m,x=b?.intent===d?b.entry:null,S=Z.useMemo(()=>!u||!l?null:VG([],u,p,cK)[0]??null,[p,l,u]),C=Z.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=UG(C,f),T=!!(f&&!w);zn(()=>{g.current=d,_.current=f,h(e=>{let t=WG(e,d,p);return l?GG(t,d,d,cK):t})},[p,v,l,d,f]);let E=b?.intent??null;zn(()=>{E&&h(e=>KG(e,E,p))},[p,E]),Z.useEffect(()=>{if(!d.selection||w)return;let e=d,t=f;return $u(()=>{g.current===e&&_.current===t&&h(n=>_.current===t?GG(n,e,g.current,cK):n)},{priority:`user-blocking`})},[w,p,d,f]);let D=q((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=HG(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)(jK,{},f):null,C.map(e=>(0,$.jsx)(Z.Activity,{name:`chat-session-${e.sessionId}`,mode:w===e.key?`visible`:`hidden`,children:(0,$.jsx)(AK,{...t,sessionId:e.sessionId,sessionDirectory:e.directory,sessionViewKey:e.key,onSessionViewEstimateChange:D,committedDraftHandoffMessageId:w===e.key?l:null})},e.key)),f?null:(0,$.jsx)(AK,{...t,sessionId:null,sessionDirectory:i.directory})]})},NK=e=>{let t=(0,Q.c)(24),{host:n,runtimeKey:r,readOnly:i}=e,a=i!==void 0&&i,o;t[0]===n?o=t[1]:(o=BD(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)(AK,{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)(Zb.Provider,{value:u,children:f}),t[21]=u,t[22]=f,t[23]=p):p=t[23],p},PK=e=>{let t=(0,Q.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=Bo(),o=n.directory??a,s;t[4]!==o||t[5]!==n?(s=Xb({...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)(AK,{...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)(Zb.Provider,{value:c,children:u}),t[13]=c,t[14]=u,t[15]=d):d=t[15],d},FK=e=>{let t=(0,Q.c)(14),n=Z.useSyncExternalStore(mK,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)(NK,{...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)(PK,{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)(MK,{...e,runtimeKey:n},n),t[11]=e,t[12]=n,t[13]=r):r=t[13],r},IK=2e4,LK=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus()?`visible`:`hidden`,RK=e=>{if(!_e()&&!Yt())return;let t=w();t?.push?.setVisibility&&t.push.setVisibility({visible:e,platform:nn()})},zK=e=>{let t=e?.enabled??!0;Z.useEffect(()=>{if(!t||!_e()&&!Yt()||typeof window>`u`)return;if(Yt()){let e=!0,t=!1,n=null,r=()=>RK(e);Sn(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&&RK(!0)},IK);return()=>{t=!0,window.clearInterval(i),n?.()}}if(typeof document>`u`)return;let e=()=>{RK(LK()===`visible`)},n=()=>{LK()===`visible`&&RK(!0)},r=()=>{RK(!1)};e();let i=window.setInterval(n,IK);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])},BK=`OpenChamber`,VK=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``).split(`/`).filter(Boolean);return t[t.length-1]??``},HK=(e,t)=>[e,t,BK].filter(e=>typeof e==`string`&&e.trim().length>0).join(` | `),UK=()=>{let e=Co(e=>e.activeProjectId?e.projects.find(t=>t.id===e.activeProjectId)??null:null),t=Z.useMemo(()=>e&&VK(e.path)||null,[e]),[n,r]=Z.useState(null);Z.useEffect(()=>{if(typeof window>`u`||!he()){r(null);return}let e=!1,t=async()=>{try{if(ue()){e||r(null);return}let t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,n=d();if(n&&Me(n,t)){e||r(null);return}let i=(await Be()).hosts.find(e=>n?Me(n,Fe(e)):!1),a=i?.label?.trim()?Ne(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=Z.useMemo(()=>HK(t,n),[t,n]);Z.useEffect(()=>{typeof document<`u`&&(document.title=i),he()&&(async()=>{try{if(typeof navigator<`u`&&/Macintosh|Mac OS X/.test(navigator.userAgent||``))return;await Yn(i)}catch{return}})()},[i])},WK=e=>{let t=[];return e.hideGit||t.push(`git`),t.push(`files`),e.showBrowser&&t.push(`browser`),t},GK=e=>e===`git`||e===`files`||e===`browser`,KK=()=>{let e=Y.getState().currentSessionId;if(!e)return``;let t=gt().find(t=>t.id===e);return typeof t?.directory==`string`?t.directory:``},qK=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)}},JK=e=>{if(!e||!Number.isFinite(e))return`(n/a)`;try{return new Date(e).toISOString()}catch{return`(invalid)`}},YK=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},XK=e=>!!e&&typeof e==`object`&&!Array.isArray(e),ZK=(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,QK=(e,t,n)=>e===`node-shebang`||e===`node-launcher`?t?`node (${t})`:`node`:e===`bun-shebang`?n?`bun (${n})`:`bun`:e||`direct executable`,$K=async()=>{let e=new Date,t=typeof navigator<`u`?navigator.userAgent:`(no navigator)`,n=KK(),r=K.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 qK(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: 2.0.0`),m.push(`Runtime: ${i||`(unknown)`} (api=${c||`(unknown)`})`),m.push(`OpenCode SDK base: ${xt.getBaseUrl()}`),m.push(`Event stream: ${r}`),m.push(`Directory: ${n||`(none)`}`),m.push(`Platform: ${t}`);let h=YK(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 l?.openCodeServeVersion==`string`&&l.openCodeServeVersion.trim()&&m.push(`OpenCode serve version: ${l.openCodeServeVersion}`),typeof l?.openCodeCliVersion==`string`&&l.openCodeCliVersion.trim()&&m.push(`OpenCode CLI version: ${l.openCodeCliVersion}`),XK(l?.runtimeContract)){let e=l.runtimeContract,t=typeof e.phase==`string`?e.phase:`(unknown)`,n=e.executionAllowed===!0?`allowed`:`limited`,r=e.protocolCompatible===!0?`compatible`:`incompatible`;m.push(`OpenCode runtime contract: phase=${t} protocol=${r} execution=${n}`),Array.isArray(e.reasons)&&e.reasons.length>0&&m.push(`OpenCode contract reasons: ${e.reasons.filter(e=>typeof e==`string`).join(`, `)}`)}if(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=XK(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: ${ZK(e.launchedAt)}`),m.push(`- launch: ${ZK(e.binary)} ${t.join(` `)}`.trim()),m.push(`- cwd: ${ZK(e.cwd)}`),m.push(`- wrapper: ${ZK(e.wrapperType)}`),m.push(`- runtime: ${QK(ZK(e.wrapperType,``),f,p)}`),m.push(`- PATH entries: ${ZK(e.pathEntryCount,`(unknown)`)}`),m.push(`- shell env: ${ZK(e.hasShellEnv,`(unknown)`)} (${ZK(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: ${QK(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: ${JK(Date.now())}`),m.join(`
|
|
6603
|
+
`)}function EH(e,t=80){let n=TH(e).replace(/\n/g,` `);return n.length>t?`${n.slice(0,t)}…`:n}var DH=160,OH=28,kH=12,AH=6,jH=30,MH=12,NH=18,PH=80,FH=4,IH=10,LH=14,RH=20,zH=54,BH=4,VH=8,HH=2,UH=160,WH=(e,t)=>e.map(e=>({turnId:e,preview:EH(t.get(e)??[],DH)})),GH=[1,.6,.35,.15],KH=(e,t,n)=>{let r=n?LH:IH;if(t===null)return r;let i=GH[Math.abs(e-t)]??0;return Math.round(r+(RH-r)*i)};function qH({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:i,isLoadingOlder:a,onLoadEarlier:o}){let{t:s}=Wn(),c=K(e=>e.isPromptNavigatorPanelOpen),l=K(e=>e.setPromptNavigatorPanelOpen),u=Z.useRef(null),d=Z.useRef(null),[f,p]=Z.useState(null),[m,h]=Z.useState(0),[g,_]=Z.useState(!1);Z.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-AH-OH;_(r.right>i)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let v=Z.useMemo(()=>WH(e,t),[t,e]),y=Math.min(v.length,jH),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=Z.useMemo(()=>n?v.findIndex(e=>e.turnId===n):-1,[n,v]),k=Z.useRef(x);k.current=x;let A=Z.useRef(v.length);A.current=v.length;let j=Z.useRef(null),M=Z.useRef(null),N=Z.useRef(0),P=Z.useCallback(e=>{h(t=>{let n=A.current,r=Math.min(n,jH),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=Z.useRef(v[0]?.turnId),I=Z.useRef(v.length);Z.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]),Z.useEffect(()=>{if(f!==null)return;let e=O>=0?O:v.length-1;h(()=>{let t=A.current,n=Math.min(t,jH),r=Math.max(0,t-n);return Math.max(0,Math.min(r,e-Math.floor(n/2)))})},[O,f,v.length]);let L=Z.useCallback(e=>{let t=u.current;if(!t)return null;let n=t.getBoundingClientRect(),r=Math.floor((e-n.top)/MH),i=Math.min(A.current,jH);return i===0?null:Math.max(0,Math.min(i-1,r))},[]),R=Z.useCallback(()=>{N.current=0,M.current!==null&&(window.clearInterval(M.current),M.current=null)},[]),z=Z.useCallback(()=>{let e=N.current;if(e===0){R();return}let t=A.current,n=Math.max(0,t-Math.min(t,jH)),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=Z.useCallback(e=>{let t=u.current;if(!t)return;let n=t.getBoundingClientRect(),r=e-n.top,i=0;if(r<=NH&&C?i=-1:r>=n.height-NH&&w&&(i=1),N.current=i,i===0){R();return}M.current===null&&(M.current=window.setInterval(z,PH))},[z,C,w,R]);Z.useEffect(()=>()=>{M.current!==null&&window.clearInterval(M.current)},[]);let V=Z.useRef(null),H=Z.useCallback(()=>{V.current!==null&&(window.clearTimeout(V.current),V.current=null)},[]),ee=Z.useCallback(()=>{H(),V.current=window.setTimeout(()=>{V.current=null,p(null)},UH)},[H]);Z.useEffect(()=>()=>{V.current!==null&&window.clearTimeout(V.current)},[]);let U=Z.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=Z.useCallback(()=>{j.current=null,R(),ee()},[ee,R]),W=Z.useCallback(()=>{l(!1)},[l]),ne=Z.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]),re=Z.useCallback(e=>{let t=L(e.clientY);t!==null&&ne(Math.min(v.length-1,k.current+t))},[ne,v.length,L]);Z.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]),Z.useEffect(()=>()=>{l(!1)},[l]);let ie=Z.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]),ae=Z.useCallback(()=>{R(),p(null),W()},[W,R]),oe=Z.useRef(null),se=Z.useRef(f);se.current=f;let ce=f!==null,le=Z.useRef(0);Z.useEffect(()=>{let e=oe.current;if(!e)return;let t=e=>{e.preventDefault(),e.stopPropagation(),le.current+=e.deltaY;let t=Math.trunc(le.current/zH);if(t===0)return;le.current-=t*zH;let n=se.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,ce]);let ue=f===null?void 0:v[f],de=Math.min(v.length,VH),fe=de*zH,pe=v.length*zH-fe,me=e=>Math.max(0,Math.min(pe,e)),he=Z.useRef(null),ge=0;if(f===null)he.current=null;else if(he.current===null)ge=me(f*zH-(fe-zH)/2),he.current=ge;else{let e=he.current,t=(f-HH)*zH,n=(f+1+HH)*zH-fe;e>t?e=t:e<n&&(e=n),ge=me(e),he.current=ge}let _e=Math.floor(ge/zH),ve=Math.max(0,_e-FH),ye=Math.min(v.length,_e+de+FH),be=ge>0,xe=ge<pe,Se=be||xe?`linear-gradient(to bottom, ${be?`transparent, black 10%`:`black`}, ${xe?`black 90%, transparent`:`black`})`:void 0,Ce=Math.max(0,x-FH),we=Math.min(v.length,S+FH),Te=v.slice(Ce,we),Ee=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:J(`-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)(X,{name:`loader-4`,className:`size-3.5 animate-spin`}):(0,$.jsx)(X,{name:`arrow-up-s`,className:`size-3.5`})}):null,(0,$.jsxs)(`div`,{ref:u,role:`listbox`,tabIndex:-1,"aria-activedescendant":ue?`prompt-rail-tick-${ue.turnId}`:void 0,className:`relative cursor-pointer outline-none`,style:{width:`${g?kH:OH}px`,height:`${y*MH}px`},onMouseMove:U,onMouseLeave:te,onClick:re,onKeyDown:ie,onBlur:ae,children:[(0,$.jsx)(`div`,{className:`absolute inset-0 overflow-hidden`,style:Ee?{maskImage:Ee,WebkitMaskImage:Ee}:void 0,children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-300 ease-out`,style:{transform:`translateY(-${x*MH}px)`},children:Te.map((e,t)=>{let r=Ce+t,i=e.turnId===n,a=f===r,o=KH(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*MH}px`,height:`${MH}px`},children:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:J(`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)}),ue&&f!==null?(0,$.jsx)(`div`,{ref:oe,className:J(`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:`${de*zH}px`,maskImage:Se,WebkitMaskImage:Se},children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-200 ease-out`,style:{height:`${v.length*zH}px`,transform:`translateY(-${ge}px)`},children:v.slice(ve,ye).map((e,t)=>{let r=ve+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*zH+BH}px`,height:`46px`},onMouseMove:()=>{H(),se.current!==r&&(P(r),p(r))},onClick:()=>ne(r),children:(0,$.jsx)(`div`,{className:J(`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:J(`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 JH=100,YH=(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},XH=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=YH(p,t.scrollTop+JH);!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}},ZH=10,QH=`${ZH}vh`,$H=`80px`,eU=`calc(${$H} + var(--oc-chat-foot-inset))`,tU=(e,t)=>e?80:t<=0?96:Math.max(48,ZH/100*t),nU=(e,t)=>({sessionId:e,viewportKey:t}),rU=(e,t)=>e?.sessionId===t?.sessionId&&e?.viewportKey===t?.viewportKey,iU=(e,t)=>rU(e,t),aU=(e,t,n)=>({identity:e,anchor:t,scrollPosition:n}),oU=150,sU=1500,cU=2,lU=350,uU=600,dU=8e3,fU=24,pU=2,mU=(e,t)=>e<t,hU=()=>typeof performance<`u`?performance.now():Date.now(),gU=e=>({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}),_U=e=>e.scrollHeight-e.scrollTop-e.clientHeight,vU=e=>_U(gU(e)),yU=e=>e.scrollHeight-e.clientHeight>1,bU=(e,t)=>_U(e)<=tU(t,e.clientHeight),xU=({enabled:e=!0,currentSessionId:t,viewportKey:n,sessionMessageCount:r,sessionIsWorking:i,isMobile:a,onActiveTurnChange:o,onUpwardUserIntent:s})=>{let c=Z.useRef(null),[l,u]=Z.useState(null),d=Z.useRef(null),[f,p]=Z.useState(`following`),[m,h]=Z.useState(!1),[g,_]=Z.useState(!1),[v,y]=Z.useState(!1),b=Z.useRef(`following`),x=Z.useRef(a);x.current=a;let S=Z.useRef(r);S.current=r;let C=Z.useRef(nU(t,n));C.current=nU(t,n);let w=Z.useRef(null),T=Z.useRef(null),E=Z.useRef(null),D=Z.useRef(0),O=Z.useRef(null),k=Z.useRef(null),A=Z.useRef(0),j=Z.useRef(!1),M=Z.useRef(!1),N=Z.useRef(null),P=Z.useRef(0),F=q(()=>{P.current=hU()+450}),I=Z.useRef(0),L=Z.useRef(!1),R=Z.useRef(null),z=Z.useRef(null),B=Z.useRef(0),V=Z.useRef(!1),H=Z.useRef(null),ee=Z.useRef(null),U=Z.useRef(null),te=Mo(e=>e.updateViewportAnchor);Z.useLayoutEffect(()=>{c.current!==d.current&&(d.current=c.current,u(c.current))});let W=q(e=>{b.current!==e&&(b.current=e,p(e))}),ne=q(e=>{T.current={top:Math.max(0,e.scrollHeight-e.clientHeight),time:hU()},E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{T.current=null,E.current=null},sU)}),re=q(e=>{let t=T.current;return t?hU()-t.time>sU?(T.current=null,!1):Math.abs(e.scrollTop-t.top)<cU:!1}),ie=q(()=>hU()<A.current),ae=q(()=>{L.current=!1,R.current&&=(clearTimeout(R.current),null),z.current&&=(clearTimeout(z.current),null)}),oe=q(()=>{R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{R.current=null,ae()},uU)}),se=q(()=>{let e=c.current;e&&(L.current=!0,B.current=e.scrollHeight,oe(),z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{z.current=null,ae()},dU))}),ce=q(e=>{let t=c.current;if(!t){h(!1),_(!1);return}let n=e??gU(t),r=yU(n);if(h(r),!r){_(!1);return}let i=b.current===`released`&&!bU(n,x.current);_(i)}),le=q(()=>{D.current+=1,O.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(O.current),O.current=null),k.current?.(),k.current=null});Z.useEffect(()=>()=>le(),[l]);let ue=q(()=>{if(!e)return;let t=c.current;if(!t)return;le();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(),ce(),typeof window>`u`)return;let o=0,s=()=>{mU(hU(),P.current)||le()};t.addEventListener(`touchstart`,s,{passive:!0,once:!0}),k.current=()=>t.removeEventListener(`touchstart`,s);let l=()=>{if(n===D.current){if(vU(t)>pU&&a(),o+=1,o>=fU){O.current=null,k.current?.(),k.current=null,ce();return}O.current=window.requestAnimationFrame(l)}};O.current=window.requestAnimationFrame(l)}),de=q(e=>{let t=c.current;if(t){if(ne(t),e===`smooth`){t.scrollTo({top:t.scrollHeight,behavior:e});return}t.scrollTop=t.scrollHeight}}),fe=q((t,n=`auto`)=>{if(!e)return;let r=c.current;if(t&&b.current!==`following`&&W(`following`),r&&!(!t&&b.current!==`following`)){if(vU(r)<cU){ne(r);return}de(t?n:`auto`)}}),pe=q(e=>{let t=c.current;if(!t)return;let n=e??gU(t);if(!yU(n)){W(`following`);return}b.current!==`released`&&(W(`released`),ce(n))}),me=q((e=`instant`)=>{if(V.current=!1,W(`following`),ae(),e===`instant`){ue();return}le(),fe(!0,`smooth`),ce()}),he=q(()=>{V.current=!1,fe(!0)}),ge=q(()=>{le(),ae(),W(`released`),ce()}),_e=q(()=>{V.current=!0,ge()}),ve=q(()=>{V.current=!1}),ye=Z.useRef(s);ye.current=s;let be=q(()=>{mU(hU(),P.current)||(le(),ae(),pe())}),xe=q(()=>{be(),ye.current?.()}),Se=q(()=>{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}}),Ce=q(()=>{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=aU(e,o,{scrollTop:n,scrollHeight:r,clientHeight:i}),H.current===null&&(H.current=setTimeout(()=>{H.current=null,Se()},oU))}),we=q(()=>{Se()}),Te=q(async(e=C.current)=>{if(!e.sessionId)return!1;V.current=!1;let t=lr(e.sessionId,e.viewportKey);return c.current?(U.current=null,I.current=t?.scrollPosition?.scrollTop??0,W(`following`),F(),x.current?ue():fe(!0),se(),ce(),!1):(U.current=e,W(`following`),!1)});Z.useEffect(()=>{let e=C.current,n=w.current;rU(e,n)||(Se(),le(),F(),w.current=e,T.current=null,I.current=0,ae(),V.current=!1,W(`following`),U.current=null,t&&t!==n?.sessionId&&lO.getInstance().recordSessionStart(t))},[t,n]),Z.useEffect(()=>{i&&!V.current&&b.current===`following`&&fe(!0)},[i]),Z.useEffect(()=>{y(f===`following`&&i)},[f,i]),Z.useLayoutEffect(()=>{if(!l)return;let e=U.current;e&&iU(e,C.current)&&Te(e)},[l,t,n]);let Ee=q(()=>{let e=c.current;if(!e)return;let t=gU(e),n=I.current;I.current=t.scrollTop;let r=t.scrollTop>n+.5,i=Math.abs(t.scrollTop-n)<.5;if(ce(t),V.current){Ce();return}if(!yU(t)){W(`following`);return}if(bU(t,x.current)){let e=Math.min(n,Math.max(0,t.scrollHeight-t.clientHeight));if(t.scrollTop<e-.5){be(),Ce();return}(r||b.current===`following`)&&W(`following`),Ce();return}if(b.current===`following`&&(re(e)||ie()||i)){j.current||fe(!1),Ce();return}pe(t),Ce()});Z.useEffect(()=>{!e||!l||(I.current=l.scrollTop)},[l,e]);let De=Z.useRef(null),Oe=q(e=>{let t=c.current;t&&(e.deltaY>=0||ll(t,e.target)||xe())}),ke=q(e=>{let t=e.touches.item(0);De.current=t?{x:t.clientX,y:t.clientY,dx:0,dy:0}:null}),Ae=q(e=>{let t=c.current,n=e.touches.item(0);if(!n){De.current=null;return}let r=De.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(De.current={x:n.clientX,y:n.clientY,dx:o,dy:s},!(s<=0||Math.abs(o)>=s)&&t){if(ll(t,e.target)){De.current.dx=0,De.current.dy=0;return}s<=2||xe()}}),je=q(()=>{De.current=null}),Me=q(e=>{Qc(e)&&xe()}),Ne=q(e=>{let t=e.target;t instanceof Element&&t.closest(`[data-overlay-scrollbar-thumb]`)&&be()}),Pe=Z.useMemo(()=>()=>void 0,[]),Fe=e&&l?l:Pe,Ie=Z.useMemo(()=>({passive:!0}),[]);Bn(`scroll`,Ee,Fe,Ie),Bn(`wheel`,Oe,Fe,Ie),Bn(`touchstart`,ke,Fe,Ie),Bn(`touchmove`,Ae,Fe,Ie),Bn(`touchend`,je,Fe,Ie),Bn(`touchcancel`,je,Fe,Ie),Bn(`keydown`,Me,Fe),Bn(`pointerdown`,Ne,e&&typeof window<`u`?window:Pe,!0);let Le=q(()=>{let e=c.current;if(j.current){ce(e?gU(e):void 0);return}if(V.current){ce(e?gU(e):void 0);return}if(!e){ce(void 0);return}let t=gU(e);if(!yU(t)){W(`following`),ce(t);return}if(ce(t),L.current){let n=t.scrollHeight>B.current+1;B.current=t.scrollHeight,_U(t)<=cU?ne(e):fe(!0),n&&oe();return}if(b.current===`following`){if(_U(t)<=cU){ne(e);return}fe(!1)}}),Re=typeof ResizeObserver<`u`,ze=Re&&e?l:null,Be=Re&&e&&l&&l.firstElementChild instanceof Element?l.firstElementChild:null;In(ze,Le),In(Be,Le);let Ve=q(()=>{N.current!==null&&(clearTimeout(N.current),N.current=null)}),He=q(e=>{j.current=!0,typeof e==`number`&&e>0?A.current=hU()+e+lU:A.current=Math.max(A.current,hU()+lU)}),Ue=q(e=>{let t=e.detail;if(t){if(t.open===!0){He(),Ve(),N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},1500);return}Ve(),He()}}),We=q(e=>{let t=e.detail;t&&(Ve(),He(t.durationMs))}),Ge=q(e=>{let t=e.detail;Ve(),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)},lU)),ce()}),Ke=e&&typeof window<`u`?window:Pe;Bn(`oc:keyboard-intent`,Ue,Ke),Bn(`oc:keyboard-anim`,We,Ke),Bn(`oc:keyboard-settled`,Ge,Ke),Z.useEffect(()=>{if(!(!e||typeof window>`u`))return()=>{Ve(),j.current=!1,M.current=!1}},[e]),Z.useEffect(()=>{e&&ce()},[e,r]);let qe=q(t=>{if(e){if(t===`animation`&&(A.current=hU()+lU),ce(),L.current){fe(!0),oe();return}b.current===`following`&&fe(!1)}}),Je=Z.useRef(new Map),Ye=q(t=>{let n=Je.current.get(t);if(n)return n;let r=()=>{e&&b.current===`following`&&fe(!1)},i={onChunk:r,onComplete:()=>{e&&ce()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:r,onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return Je.current.set(t,i),i});Z.useEffect(()=>()=>{E.current&&=(clearTimeout(E.current),null),le(),ae(),Se(),H.current!==null&&(clearTimeout(H.current),H.current=null)},[]);let Xe=q(e=>{o?.(e)}),Ze=!!o;return Z.useEffect(()=>{if(!e||!Ze)return;let t=l;if(!t)return;let n=null,r=XH({onActive:e=>{e!==n&&(n=e,Xe(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,Ze]),{scrollRef:c,state:f,isPinned:f===`following`,isOverflowing:m,isFollowingProgrammatically:v,showScrollButton:g,notifyContentChange:qe,getAnimationHandlers:Ye,goToBottom:me,scrollToBottomOnSend:he,releaseAutoFollow:ge,beginHistoryViewportPreservation:_e,endHistoryViewportPreservation:ve,saveSnapshotNow:we,restoreSnapshot:Te}},SU=`--oc-mobile-composer-swap`,CU=`--oc-native-composer-dock`,wU=()=>({phase:`rest`,rest:`expanded`,progress:0,pinned:!1}),TU=(e,t,n)=>Math.min(n,Math.max(t,e)),EU=(e,t)=>e.phase===t.phase&&e.rest===t.rest&&e.progress===t.progress&&e.pinned===t.pinned,DU=(e,t)=>{let n={phase:t.phase,rest:t.rest,progress:t.progress,pinned:t.pinned??e.pinned};return EU(e,n)?e:n},OU=(e,t)=>t?DU(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0}):e.pinned?DU(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!1}):e,kU=(e,t)=>{if(e.pinned&&t===`compact`)return e;let n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:DU(e,{phase:`snapping`,rest:t,progress:n})},AU=e=>TU(e/80,0,1),jU=e=>e>=80?1:TU(e/80,0,1),MU=(e,t,n={})=>{if(e.pinned||n.userDriven===!1)return e;let r=Math.max(0,t),i=e.phase===`snapping`?DU(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e;if(i.rest===`expanded`){if(r<=2||n.holdExpanded)return DU(i,{phase:`rest`,rest:`expanded`,progress:0});let e=AU(r);return e>=1?DU(i,{phase:`rest`,rest:`compact`,progress:1}):DU(i,{phase:`tracking`,rest:`expanded`,progress:e})}if(r<=2)return DU(i,{phase:`rest`,rest:`expanded`,progress:0});if(n.suppressReturn)return DU(i,{phase:`rest`,rest:`compact`,progress:1});if(n.towardBottom&&r>=80)return DU(i,{phase:`snapping`,rest:`expanded`,progress:0});let a=jU(r);return a>=1?DU(i,{phase:`rest`,rest:`compact`,progress:1}):DU(i,{phase:`tracking`,rest:`compact`,progress:a})},NU=e=>e.pinned?`expanded`:e.rest===`expanded`?e.progress>=.5?`compact`:`expanded`:e.progress<=.5?`expanded`:`compact`,PU=e=>{if(e.pinned)return DU(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0});if(e.phase===`snapping`)return e;let t=NU(e),n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:DU(e,{phase:`snapping`,rest:t,progress:n})},FU=e=>e.phase===`snapping`?DU(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e,IU=e=>TU(Math.max(0,e)/80,0,1),LU=(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:IU(n),rest:`bottom`}},RU=e=>{e.style.removeProperty(SU),e.style.removeProperty(CU),delete e.dataset.ocComposerSwapPhase,delete e.dataset.ocComposerSwapRest,delete e.dataset.ocNativeComposerDock},zU=(e,t,n)=>{let r=LU(t,n?.rest===`bottom`?`bottom`:`away`),i=String(r.progress),a=r.rest;return n?.progress!==i&&e.style.setProperty(CU,i),n?.rest!==a&&(e.dataset.ocNativeComposerDock=a),{progress:i,rest:a}},BU=(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(SU,r),n?.rest!==a&&(e.dataset.ocComposerSwapRest=a),{progress:r,phase:i,rest:a}},VU=e=>({scrollHeight:e.scrollHeight,scrollTop:e.scrollTop,clientHeight:e.clientHeight}),HU=()=>{let e=document.documentElement;return e.classList.contains(`oc-keyboard-open`)||e.classList.contains(`oc-kb-animating`)},UU=e=>{if(HU()||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)},WU=e=>{let t=Z.useRef(wU()),n=Z.useRef(void 0),r=Z.useRef(void 0),i=Z.useRef(null),a=Z.useRef(null),o=Z.useRef(0),s=Z.useRef(!1),c=Z.useRef(0),l=Z.useRef(new Map),u=Z.useRef(!1),d=Z.useRef(0),f=Z.useRef(null),p=Z.useRef(null),m=Z.useRef(0),h=Z.useRef(0),g=Z.useRef(!1),_=Z.useRef(e.enabled);_.current=e.enabled;let v=e=>{e.current!==null&&(window.clearTimeout(e.current),e.current=null)},y=q(t=>{let r=e.scopeRef.current;r&&(n.current=BU(r,t,n.current))}),b=q(e=>{e!==t.current&&(t.current=e,y(e))}),x=q(()=>{if(v(a),t.current.phase!==`snapping`)return;let e=t.current.rest;a.current=window.setTimeout(()=>{a.current=null;let n=FU(t.current);b(n),n.rest===`compact`&&e===`compact`&&(o.current=Date.now()+320,s.current=!0)},240)}),S=q(()=>{let n=e.scopeRef.current;!n||!_.current||b(OU(t.current,UU(n)))}),C=q(e=>s.current?Date.now()>=o.current?(s.current=!1,!1):e>=80?(s.current=!1,o.current=0,!1):!0:!1),w=q(()=>{if(v(i),!_.current||c.current>0||t.current.phase!==`tracking`)return;let e=PU(t.current);b(e),x()}),T=q(()=>{u.current=!1,d.current=0;for(let e of l.current.values())e.startX=e.currentX,e.startY=e.currentY}),E=q(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=q(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=VU(t);p.current=e,f.current=Qz(e,Xz(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=q(()=>{if(!_.current)return;let n=e.scrollRef.current,o=e.scopeRef.current;if(!n||!o)return;let s=UU(o),l=VU(n),y=Qz(l,Xz(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=zU(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=OU(j,s);if(!s){let e=M.rest===`compact`;M=MU(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=q(()=>{u.current&&(c.current>0||Date.now()-d.current<=1200)&&w()}),A=q((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=q(e=>{A(e,!0)}),M=q(e=>{A(e,!1)}),N=q(()=>{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=q(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(kU(t.current,`expanded`)),x(),N(),(e.scopeRef.current?.querySelector(`textarea[data-chat-input="true"]`))?.focus({preventScroll:!0})))}),[F,I]=Z.useState(null),[L,R]=Z.useState(null),z=Z.useRef(null),B=q(e=>{e&&RU(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(wU())});Z.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=Z.useMemo(()=>()=>void 0,[]),H=e.enabled&&F?F:V,ee=e.enabled&&L?L:V,U=e.enabled&&typeof window<`u`?window:V,te=Z.useMemo(()=>({passive:!0}),[]);Bn(`scroll`,O,H,te),Bn(`scrollend`,k,H,te),Bn(`touchstart`,D,H,te),Bn(`touchmove`,E,H,te),Bn(`touchend`,j,H,te),Bn(`touchcancel`,M,H,te),Bn(`pointerdown`,P,ee),Bn(`focusin`,S,ee),Bn(`focusout`,S,ee),Bn(`oc:keyboard-intent`,S,U),Bn(`oc:keyboard-anim`,S,U),Bn(`oc:keyboard-settled`,S,U),Z.useEffect(()=>{if(!e.enabled){B(z.current),z.current=null;return}return S(),O(),()=>{v(i),v(a)}},[e.enabled,F,L])},GU=e=>{let t=e.info.clientRole??e.info.role;return typeof t==`string`?t:``},KU=e=>{let t=e.info.parentID;if(typeof t==`string`&&t.trim().length!==0)return t},qU=e=>{if(!e)return null;let t=GU(e);return`${typeof e.info?.id==`string`?e.info.id:``}::${t}::${KU(e)??``}`},JU=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}),YU=(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&&qU(t[r])===qU(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=GU(r),a=r.info.id,o=JU(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=KU(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},XU=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=GU(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=KU(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}},ZU=200,QU={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:6e5},$U=()=>ZU,eW=()=>Math.round($U()*.6),tW={MAX_SESSIONS:QU.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(ZU*.6),HISTORICAL_MESSAGES:ZU,FETCH_BUFFER:20,HISTORY_CHUNK:ZU,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:QU.ZOMBIE_TIMEOUT},nW=()=>{let e=$U(),t=eW();return{...tW,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},rW=tW,iW=600,aW=6e3,oW=.5,sW=(e,t)=>e.querySelector(`[data-message-id="${CSS.escape(t)}"]`),cW=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},lW=(e,t)=>{let n=sW(e,t);if(n||=cW(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}},uW=e=>{let{container:t,quiesceMs:n=iW,maxLifetimeMs:r=aW}=e,i={messageId:e.anchor.messageId,offsetTop:e.anchor.offsetTop},a=!1,o=e.pending??!1,s=null,c=null,l=!1,u=t.scrollTop,d=()=>{s!==null&&(clearTimeout(s),s=null)},f=()=>{c!==null&&(clearTimeout(c),c=null)},p=()=>{a||(a=!0,b.disconnect(),t.removeEventListener(`scroll`,y),d(),f())},m=()=>{d(),!(a||o)&&(s=setTimeout(()=>{s=null,p()},n))},h=()=>{f(),!(a||o)&&(c=setTimeout(()=>{c=null,p()},r))},g=()=>{if(a)return;let e=lW(t,i.messageId);if(!e){p();return}i.messageId=e.messageId,i.offsetTop=e.offsetTop,u=t.scrollTop},_=()=>{if(a)return;if(Math.abs(t.scrollTop-u)>oW){g();return}let e=sW(t,i.messageId);if(!e){let n=cW(t);if(!n){p();return}let r=n.dataset.messageId;if(!r){p();return}let a=t.getBoundingClientRect();i.messageId=r,i.offsetTop=n.getBoundingClientRect().top-a.top,e=n,u=t.scrollTop}let n=t.getBoundingClientRect(),r=e.getBoundingClientRect().top-n.top-i.offsetTop;Math.abs(r)>oW&&(t.scrollTop+=r),u=t.scrollTop},v=()=>{a||l||(l=!0,queueMicrotask(()=>{l=!1,_()}))},y=()=>{g(),m(),h()},b=new MutationObserver(()=>{a||(v(),m())});return b.observe(t,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`style`,`class`]}),t.addEventListener(`scroll`,y,{passive:!0}),h(),m(),{rebase:g,dispose:p,settle(){a||!o||(o=!1,m(),h())}}},dW=30,fW=1200,pW=1.5,mW=e=>Math.max(fW,e*pW),hW=4,gW=30,_W=4,vW=30,yW=250,bW=1500,xW=2e3,SW=ja+2e3,CW=40,wW=`history-loading-timeout`,TW=e=>!!(e&&typeof e==`object`&&e.code===`history-loading-timeout`),EW=()=>{let e=Error(`chat history pagination wait timed out`);return e.code=wW,e},DW=(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)},OW=2500,kW=new Map,AW=()=>fe()?hW:Rr()?_W:dW,jW=e=>fe()?e.length<=gW:!Rr()||e.length<=vW,MW=(e,t)=>{if(kW.delete(e),!jW(t.messages))return;let n=AW();for(;kW.size>=n;){let e=kW.keys().next().value;if(typeof e!=`string`)break;kW.delete(e)}kW.set(e,t)},NW=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),PW=e=>e?{owner:`tanstack-core`}:{owner:`controller`},FW=(e,t)=>e?e.canLoadEarlier:t>=nW().HISTORICAL_MESSAGES,IW=e=>!(e.isLoadingOlder||e.pendingRevealWork||!e.canLoadEarlier||e.source===`scroll`&&e.isPinned||e.scrollTop>=mW(e.clientHeight)),LW=e=>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.cursorBefore==null&&e.limitAfter>e.limitBefore||typeof e.cursorAfter==`string`&&e.cursorAfter!==e.cursorBefore?e.pagesLoaded>=e.maxPages?`stop-bounded`:`continue`:`stop-no-growth`:`stop-exhausted`,RW=8,zW=1,BW=8,VW=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),HW=e=>[`chat-timeline-auto-fill`,e.runtimeKey,e.sessionId,e.oldestMessageId,e.messageCount,e.canLoadEarlier],UW=e=>[`chat-timeline-load-earlier`,e.runtimeKey,e.sessionId],WW=20,GW=4,KW=80,qW=new WeakMap,JW=new WeakMap,YW=e=>{let t=JW.get(e)??{generation:0};return t.generation+=1,JW.set(e,t),t.generation},XW=e=>{let t=qW.get(e);t&&(t.touches=0,t.pending=null,t.settleScheduled=!1),YW(e)},ZW=e=>{QW(e)},QW=e=>{let t=qW.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&&$W(e,n)};return e.addEventListener(`touchend`,r,{passive:!0}),e.addEventListener(`touchcancel`,r,{passive:!0}),qW.set(e,n),n},$W=(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+KW||eG(e,n.anchorTop+n.delta))}))},eG=(e,t)=>{let n=YW(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((JW.get(e)?.generation??0)!==n){e.removeEventListener(`touchstart`,o);return}e.scrollTop<t-GW&&(e.scrollTop=t),a+=1,a<WW?window.requestAnimationFrame(s):e.removeEventListener(`touchstart`,o)}};window.requestAnimationFrame(s)},tG=(e,t,n)=>{let r=QW(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,eG(e,t)},nG=(e,t,n)=>!e||!t||t===e?!1:n.some(t=>t.info.id===e),rG=(e,t)=>e.scrollHeight===t.scrollHeight&&e.clientHeight===t.clientHeight?e:t,iG=({sessionId:e,directory:t=null,messages:n,historyMeta:r,scrollRef:i,messageListRef:a,loadMoreMessages:o,goToBottom:s,releaseAutoFollow:l,beginHistoryViewportPreservation:d,endHistoryViewportPreservation:f,isPinned:p,showScrollButton:m,isMobile:h,autoFillEnabled:g=!1,onWillLoadEarlier:_})=>{let v=Z.useRef(h),y=Z.useRef(g);v.current=h,y.current=g;let b=Z.useRef(null),x=Z.useRef(null),S=Z.useMemo(()=>{let t=e??``,r=t?kW.get(t):void 0;if(r&&r.messages===n)return MW(t,r),b.current=r.model,x.current=n,r.model;let i=YU(b.current,x.current,n)??XU(n);return b.current=i,x.current=n,t&&n.length>0&&MW(t,{messages:n,model:i}),i},[n,e]),[C,w]=Z.useState(!1),[T,E]=Z.useState(!1),[D,O]=Z.useState(null),[k,A]=Z.useState(!1),j=Z.useRef(!1),M=Z.useRef(0),N=u(),P=c(),F=Z.useMemo(()=>({runtimeKey:N,runtimeGeneration:P,sessionId:e,directory:t}),[N,P,e,t]),I=Z.useRef(F);I.current=F;let L=`chat-history-error:${JSON.stringify([N,t??null,e])}`;zn(()=>(I.current=F,()=>{I.current===F&&(I.current=null),Ha.dismiss(L)}),[F,L]);let[R,z]=Z.useState({scrollHeight:0,clientHeight:0}),B=Z.useRef(S),V=Z.useRef(p),H=Z.useRef(C),ee=Z.useRef(T),U=Z.useRef(e),te=Z.useRef(t??null),W=Z.useRef(n),ne=Z.useRef(r),re=Z.useRef([]),ie=Z.useRef(null),ae=Z.useRef(null),oe=Z.useRef(!1),se=Z.useRef(null),ce=Z.useRef({authorized:!1,consumed:!1,top:0}),le=q(()=>{ce.current={authorized:!1,consumed:H.current,top:i.current?.scrollTop??0}}),ue=()=>h?i.current??void 0:void 0,de=q(e=>{e.repeat||le()});Bn(`touchstart`,le,ue,{passive:!0,capture:!0}),Bn(`wheel`,le,ue,{passive:!0,capture:!0}),Bn(`keydown`,de,ue,{capture:!0});let[fe,pe]=Z.useState(F);fe!==F&&(pe(F),se.current!==null&&typeof window<`u`&&(window.clearTimeout(se.current),se.current=null),oe.current=!1,H.current=!1,ae.current=null,w(!1),E(!1),O(null),A(!1),j.current=!1,M.current=0,ce.current={authorized:!1,consumed:!1,top:0},z({scrollHeight:0,clientHeight:0}));let me=Z.useMemo(()=>{let e=FW(r,n.length);return{hasBufferedTurns:!1,hasMoreAboveTurns:e,historyLoading:!!r?.loading,canLoadEarlier:e}},[r,n.length]),he=Z.useRef(me);B.current=S,V.current=p,ee.current=T,he.current=me,U.current=e,te.current=t??null,W.current=n,ne.current=r,zn(()=>{r?.complete&&(j.current=!1,A(!1),Ha.dismiss(L))},[r?.complete,L]);let ge=q(()=>{oe.current=!0,se.current!==null&&typeof window<`u`&&(window.clearTimeout(se.current),se.current=null)}),_e=q(()=>{if(typeof window>`u`){oe.current=!1;return}se.current!==null&&window.clearTimeout(se.current),se.current=window.setTimeout(()=>{se.current=null,oe.current=!1},xW)}),ve=q(()=>{let e=re.current;e.length!==0&&(re.current=[],e.forEach(e=>e()))}),ye=q(()=>new Promise(e=>{if(typeof window>`u`){e();return}let t=!1,n=()=>{t||(t=!0,window.clearTimeout(r),e())};re.current.push(n);let r=window.setTimeout(n,yW)})),be=q(e=>{let t=ie.current;t&&(ie.current=null,t.resolve(e))}),xe=q(()=>{let e=ie.current;if(e){if(e.sessionId!==U.current){be(!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&&(ae.current={turnId:e.turnId,expiresAt:Date.now()+OW},O(e.turnId)),be(!0);return}typeof(e.kind===`turn`?B.current.turnIndexById.get(e.id):B.current.messageToTurnIndex.get(e.id))==`number`&&be(!1)}}),Se=Z.useRef(null),Ce=q(()=>{let e=Se.current;e&&(Se.current=null,e.dispose())});Rn(()=>{se.current!==null&&typeof window<`u`&&(window.clearTimeout(se.current),se.current=null),Ce(),ve(),be(!1)});let we=n;zn(()=>{ve(),xe()},[we]);let Te=q(()=>{let e=i.current;if(!e){z(e=>rG(e,{scrollHeight:0,clientHeight:0}));return}z(t=>rG(t,{scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}))});In(typeof ResizeObserver<`u`?i:null,Te),zn(()=>{Te()},[F,C]);let Ee=Z.useRef(null),De=q(()=>a.current?.captureViewportAnchor()??null),Oe=q(e=>a.current?.restoreViewportAnchor(e)??!1),ke=q(()=>{if(Ce(),a.current?.isHistoryVirtualized())return;let e=i.current;if(!e)return;let t=De();if(t)return Se.current=uW({container:e,anchor:t,pending:!0}),Se.current}),Ae=Z.useRef(null);zn(()=>{if(!Rr())return;let e=i.current;e&&(ZW(e),XW(e))},[F,i]),zn(()=>{Ce(),Ee.current=null,Ae.current=null,a.current?.cancelViewportAnchorHold()},[F]),zn(()=>{let e=i.current;if(!e)return;let t=Ee.current;a.current?.isHistoryVirtualized()&&Ce(),t&&Math.abs(e.scrollTop-t.top)>BW&&(Ee.current=null,t=null);let n=Ae.current,r=we[0]?.info?.id??null,o=we[we.length-1]?.info?.id??null,c=n?NW({previousOldestId:n.oldestId,previousNewestId:n.newestId,currentOldestId:r,currentNewestId:o})||nG(n.oldestId,r,we):!1;t&&t.sessionId!==U.current&&(Ee.current=null,t=null);let l=t?NW({previousOldestId:t.oldestId,previousNewestId:t.newestId,currentOldestId:r,currentNewestId:o})||nG(t.oldestId,r,we):!1,u=c||l,d=e=>{Ae.current={oldestId:r,newestId:o,scrollHeight:e??Ae.current?.scrollHeight??0}};if(V.current&&!t){Ce(),u?(Ee.current=null,s(`instant`),d(e.scrollHeight)):d();return}let f=PW(a.current?.isHistoryVirtualized()??!1);if(t){if(f.owner===`tanstack-core`){a.current?.cancelViewportAnchorHold();let e=t.anchor;e&&Oe(e),d();return}let n=e.scrollHeight,r=n-t.height;if(Rr()){r>0&&tG(e,t.top+r,r),d(n);return}let i=t.anchor;!(i&&Oe(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;Rr()?tG(e,t,r):e.scrollTop=t}d(t),ke();return}d()},[we,s]);let je=q(async()=>!1),Me=q(async e=>{let t=I.current,n=()=>t===I.current&&t?.runtimeKey===u()&&t?.runtimeGeneration===c(),r=Date.now(),i=r+SW,a=te.current,o=a?dn()?.getRequestState?.(Vt(a,e)):void 0;for(he.current.historyLoading,ne.current,o?.status,o?.error;he.current.historyLoading;){if(!n()||U.current!==e)return Date.now()-r,`switched`;if(Date.now()>=i){let t=a?dn()?.getRequestState?.(Vt(a,e)):void 0;return console.error(`[chat-history] historyLoading wait timed out — sync flag still true`,{sessionId:e,directory:a,elapsedMs:Date.now()-r,waitMs:SW,hostTurnPageTimeoutMs:ja,historyLoading:he.current.historyLoading,historyMeta:ne.current,requestStatusAtStart:o?.status??null,requestStatusAtTimeout:t?.status??null,requestErrorAtTimeout:t?.error??null,likelyStaleLoadingFlag:t?.status===`ready`||t?.status===`error`||t==null}),`timeout`}await new Promise(e=>{if(typeof window>`u`){e();return}window.setTimeout(e,CW)})}return Date.now()-r,a&&dn()?.getRequestState?.(Vt(a,e))?.status,n()&&U.current===e?`cleared`:`switched`}),Ne=q(async e=>{if(!U.current||H.current||!he.current.hasMoreAboveTurns)return!1;H.current=!0,ge(),w(!0);let t=U.current,n=I.current,r=()=>n===I.current&&n?.runtimeKey===u()&&n?.runtimeGeneration===c(),s=()=>n?.directory?dn()?.getPagination(Vt(n.directory,t)).cursor??null:null,l=L,p=null,m=null,h=!!e.userInitiated;h&&d();let g=()=>{r()&&(m?.settle(),p&&Ee.current===p&&(Ee.current=null,a.current?.cancelViewportAnchorHold()),h&&(h=!1,f()))};try{if(he.current.historyLoading){if(!e.userInitiated)return!1;let n=await Me(t);if(n===`timeout`)throw EW();if(n===`switched`||!he.current.hasMoreAboveTurns)return!1}if(!r()||!U.current||U.current!==t)return!1;let n=i.current,a=W.current,c=a.length,u=a[0]?.info?.id??null,d=ne.current?.limit??nW().HISTORICAL_MESSAGES;e.preserveViewport&&n&&(p={sessionId:U.current,height:n.scrollHeight,top:n.scrollTop,anchor:De(),oldestId:u,newestId:a[a.length-1]?.info?.id??null},Ee.current=p,m=ke()??null);let f=c,h=u,_=d,v=0,y=0;for(;;){if(he.current.historyLoading)if(e.userInitiated){let e=await Me(t);if(e===`timeout`)throw g(),EW();if(e===`switched`)return g(),!1}else return g(),!1;let n=i.current?.scrollHeight??0,a=f,c=h,u=_,d=s();if(await o(t,`up`),v+=1,!r()||U.current!==t)return g(),!1;if(await ye(),!r())return!1;let p=(()=>{let t=W.current;return LW({scrollHeightBefore:n,scrollHeightAfter:i.current?.scrollHeight??n,messageCountBefore:a,messageCountAfter:t.length,oldestIdBefore:c,oldestIdAfter:t[0]?.info?.id??null,limitBefore:u,limitAfter:ne.current?.limit??_,cursorBefore:d,cursorAfter:s(),hasMoreAbove:he.current.hasMoreAboveTurns,pagesLoaded:v,maxPages:e.singlePage?1:RW})})();if(p===`continue`){let e=W.current;f=e.length,h=e[0]?.info?.id??null,_=ne.current?.limit??_;continue}if(p===`stop-no-growth`){if(e.singlePage)return g(),!1;if(he.current.historyLoading){if(e.userInitiated){let e=await Me(t);if(e===`timeout`)throw g(),EW();if(e===`switched`)return g(),!1;--v;continue}return g(),!1}if(y<zW){y+=1,--v;continue}return j.current=!0,M.current=Date.now()+bW,A(!0),g(),!1}return j.current=!1,M.current=0,A(!1),Ha.dismiss(l),!0}}catch(e){throw r()&&(j.current=!0,M.current=Date.now()+bW,A(!0)),g(),e}finally{r()&&(H.current=!1,w(!1),_e(),ye().then(g))}}),{t:Pe}=Wn(),Fe=Tn({mutationKey:UW({runtimeKey:u(),sessionId:e??``}),mutationFn:async e=>{if(I.current!==e.scope||u()!==e.scope.runtimeKey||c()!==e.scope.runtimeGeneration||U.current!==e.sessionId)return!1;ge(),e.userInitiated&&l();try{return await Ne({preserveViewport:!0,userInitiated:!!e.userInitiated,singlePage:e.singlePage})}finally{I.current===e.scope&&c()===e.scope.runtimeGeneration&&_e()}}}),Ie=q(async e=>{let t=U.current;if(!t||!he.current.canLoadEarlier)return;let n=F,r=L,i=()=>I.current===n&&u()===n.runtimeKey&&c()===n.runtimeGeneration;if(!(Fe.isPending&&Fe.variables?.sessionId===t&&Fe.variables?.scope===n)){e?.userInitiated&&_?.();try{let r=await Fe.mutateAsync({sessionId:t,scope:n,userInitiated:!!e?.userInitiated,singlePage:e?.singlePage});if(!i())return;if(r===!1&&he.current.canLoadEarlier){let n={sessionId:t,grew:r,userInitiated:!!e?.userInitiated,canLoadEarlier:he.current.canLoadEarlier,hasMoreAboveTurns:he.current.hasMoreAboveTurns,historyLoading:he.current.historyLoading,historyMeta:ne.current,messageCount:W.current.length,oldestMessageId:W.current[0]?.info?.id??null};DW(`no-growth`,Error(`chat history pagination returned no growth`),n)}}catch(n){let a={sessionId:t,userInitiated:!!e?.userInitiated,waitMs:SW,hostTurnPageTimeoutMs:ja,canLoadEarlier:he.current.canLoadEarlier,historyLoading:he.current.historyLoading,historyMeta:ne.current,messageCount:W.current.length,oldestMessageId:W.current[0]?.info?.id??null};TW(n)?DW(`timeout`,n,a):DW(`failed`,n,a),i()&&e?.userInitiated&&Ha.error(TW(n)?Pe(`chat.history.loadOlderTimeout`):Pe(`chat.history.loadOlderFailed`),{id:r})}}}),Le=Fe.isPending&&Fe.variables?.sessionId===e&&Fe.variables?.scope===F||C,Re=n[0]?.info?.id??null,ze=e&&t?dn()?.getPagination(Vt(t,e)).cursor??null:null,Be=VW({enabled:g,isMobile:h,sessionReady:!!e,messageReady:n.length>0||!!r,historyLoading:me.historyLoading,canLoadEarlier:me.canLoadEarlier,isPinned:p,fillBlocked:k,scrollHeight:R.scrollHeight,clientHeight:R.clientHeight,pendingRevealWork:T,isLoadingOlder:!1,hasMessages:n.length>0});En({queryKey:[...HW({runtimeKey:u(),sessionId:e??``,oldestMessageId:Re,messageCount:n.length,canLoadEarlier:me.canLoadEarlier}),P,t??null,ze],enabled:!!e&&Be,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(!y.current||v.current||j.current||!V.current)return{status:`skip`};let e=U.current;if(!e)return{status:`skip`};let t=F,n=()=>I.current===t&&u()===t.runtimeKey&&c()===t.runtimeGeneration;if(!n())return{status:`skip`};if(he.current.historyLoading||H.current){let e=Error(`auto-fill-busy`);throw e.code=`auto-fill-busy`,e}if(!he.current.canLoadEarlier)return{status:`skip`};let r=i.current;if(!r||r.clientHeight<=0)return{status:`skip`};if(r.scrollHeight>r.clientHeight+48)return{status:`tall`};try{let t=await Ne({preserveViewport:!0});return n()?t?{status:`grew`}:(he.current.canLoadEarlier&&DW(`no-growth`,Error(`chat history pagination returned no growth`),{sessionId:e,source:`auto-fill`,grew:t,canLoadEarlier:he.current.canLoadEarlier,hasMoreAboveTurns:he.current.hasMoreAboveTurns,historyLoading:he.current.historyLoading,historyMeta:ne.current,messageCount:W.current.length,oldestMessageId:W.current[0]?.info?.id??null}),A(!0),{status:`blocked`}):{status:`skip`}}catch(t){if(t?.code===`auto-fill-busy`)throw t;let r={sessionId:e,source:`auto-fill`,waitMs:SW,canLoadEarlier:he.current.canLoadEarlier,historyLoading:he.current.historyLoading,historyMeta:ne.current,messageCount:W.current.length,oldestMessageId:W.current[0]?.info?.id??null};throw TW(t)?DW(`timeout`,t,r):DW(`failed`,t,r),n()&&A(!0),t instanceof Error?t:Error(`chat timeline auto-fill failed`)}}});let Ve=q(e=>{if(Date.now()<M.current)return;let t=i.current;if(t){if(v.current){let n=ce.current,r=t.scrollTop<n.top;if(n.top=t.scrollTop,n.consumed||(e===`upward-intent`&&(n.authorized=!0),!n.authorized||e===`scroll`&&!r))return}IW({source:e,isMobile:v.current,isPinned:V.current,scrollTop:t.scrollTop,clientHeight:t.clientHeight,canLoadEarlier:he.current.canLoadEarlier,isLoadingOlder:H.current,pendingRevealWork:ee.current})&&(v.current&&(ce.current.consumed=!0),Ie({userInitiated:!0,singlePage:v.current}))}}),He=q(()=>{Ve(`scroll`)}),Ue=q(()=>{Ve(`upward-intent`)}),We=q(async(t,n)=>{if(!t||!U.current)return!1;l(),E(!0);try{return U.current!==e||typeof B.current.turnIndexById.get(t)!=`number`?!1:!!await new Promise(r=>{ie.current={sessionId:U.current??e??``,kind:`turn`,id:t,behavior:n?.behavior??`auto`,turnId:t,resolve:r},xe()})}finally{E(!1)}}),Ge=q(async(t,n)=>{if(!t||!U.current)return!1;l(),E(!0);try{if(U.current!==e)return!1;let r=B.current.messageToTurnId.get(t);return typeof B.current.messageToTurnIndex.get(t)==`number`&&!!await new Promise(i=>{ie.current={sessionId:U.current??e??``,kind:`message`,id:t,behavior:n?.behavior??`auto`,turnId:r??null,resolve:i},xe()})}finally{E(!1)}}),Ke=q(async()=>{E(!1),H.current=!1,w(!1),a.current?.scrollToBottom(),s(`smooth`)}),qe=q(async()=>{E(!1),H.current=!1,w(!1),a.current?.scrollToBottom(),s(`instant`)}),Je=q(e=>{let t=ae.current;if(t){if(e!==t.turnId&&Date.now()<t.expiresAt)return;ae.current=null}O(e)});return{turnIds:S.turnIds,turnStart:0,renderedMessages:we,historySignals:me,isLoadingOlder:Le,pendingRevealWork:T,activeTurnId:D,showScrollToBottom:m&&!T,turnWindowModel:S,loadEarlier:Ie,revealBufferedTurns:je,resumeToBottom:Ke,resumeToBottomInstant:qe,scrollToTurn:We,scrollToMessage:Ge,handleHistoryScroll:He,handleHistoryUpwardIntent:Ue,captureViewportAnchor:De,restoreViewportAnchor:Oe,handleActiveTurnChange:Je}},aG=({mutateSession:e,forkSession:t})=>({revert:e,fork:t}),oG=({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]=Z.useState(null),[p,m]=Z.useState(``),[h,g]=Z.useState(0),_=Z.useRef(!1),v=Z.useRef(0),y=q(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)(Yo,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:(0,$.jsx)(sG,{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},sG=e=>{let t=(0,Q.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}=Wn(),b=Qb(),x=i,S=vo(x??``,a),C=Y(lG),w=Y(uG),T;t[0]===b.capabilities?T=t[1]:(T=aG(b.capabilities),t[0]=b.capabilities,t[1]=T);let E=T,{isMobile:D,isTablet:O}=Oc(),k=D||O,A;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(A=[],t[2]=A):A=t[2];let j=Z.useRef(A),M=Z.useRef(null),N=Z.useRef(null),P=Z.useRef(!1),F=Z.useRef(!1),I=dG,L=fG,R;t[3]===S?R=t[4]:(R=S.filter(pG).map(mG),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 TH(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],Z.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),Z.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),Z.useEffect(ne,W);let re;t[22]===u?re=t[23]:(re=()=>{!P.current||N.current||u||(P.current=!1)},t[22]=u,t[23]=re);let ie;t[24]!==V.length||t[25]!==u?(ie=[V.length,u],t[24]=V.length,t[25]=u,t[26]=ie):ie=t[26],Z.useEffect(re,ie);let ae,oe;t[27]!==n||t[28]!==p?(ae=()=>{let e=F.current;if(F.current=n,!n||e||P.current||p.trim())return;let t=M.current;t&&(t.scrollTop=t.scrollHeight)},oe=[n,p],t[27]=n,t[28]=p,t[29]=ae,t[30]=oe):(ae=t[29],oe=t[30]),Z.useLayoutEffect(ae,oe);let se;t[31]===u?se=t[32]:(se=()=>{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]=se);let ce;t[33]!==V.length||t[34]!==u?(ce=[V.length,u],t[33]=V.length,t[34]=u,t[35]=ce):ce=t[35],Z.useLayoutEffect(se,ce);let le;t[36]===d?le=t[37]:(le=()=>{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]=le);let ue=q(le),de;t[38]!==r||t[39]!==o?(de=async e=>{await o?.(e)!==!1&&r(!1)},t[38]=r,t[39]=o,t[40]=de):de=t[40];let fe=q(de),pe;t[41]!==V||t[42]!==fe||t[43]!==g||t[44]!==h?(pe=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&&fe(r.message.info.id)}}},t[41]=V,t[42]=fe,t[43]=g,t[44]=h,t[45]=pe):pe=t[45];let me=q(pe),he;t[46]!==x||t[47]!==a||t[48]!==w||t[49]!==f||t[50]!==C||t[51]!==v?(he=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]=he):he=t[52];let ge=q(he),_e;t[53]===Symbol.for(`react.memo_cache_sentinel`)?(_e=(0,$.jsx)(X,{name:`time`,className:`h-5 w-5`}),t[53]=_e):_e=t[53];let ve;t[54]===y?ve=t[55]:(ve=y(`chat.timeline.title`),t[54]=y,t[55]=ve);let ye;t[56]===ve?ye=t[57]:(ye=(0,$.jsxs)(Xo,{className:`flex items-center gap-2`,children:[_e,ve]}),t[56]=ve,t[57]=ye);let be;t[58]===y?be=t[59]:(be=y(`chat.timeline.description`),t[58]=y,t[59]=be);let xe;t[60]===be?xe=t[61]:(xe=(0,$.jsx)(Zo,{children:be}),t[60]=be,t[61]=xe);let Se;t[62]!==ye||t[63]!==xe?(Se=(0,$.jsxs)(Ko,{children:[ye,xe]}),t[62]=ye,t[63]=xe,t[64]=Se):Se=t[64];let Ce;t[65]===Symbol.for(`react.memo_cache_sentinel`)?(Ce=(0,$.jsx)(X,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),t[65]=Ce):Ce=t[65];let we;t[66]===y?we=t[67]:(we=y(`chat.timeline.searchPlaceholder`),t[66]=y,t[67]=we);let Te;t[68]===m?Te=t[69]:(Te=e=>m(e.target.value),t[68]=m,t[69]=Te);let Ee;t[70]!==me||t[71]!==p||t[72]!==we||t[73]!==Te?(Ee=(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[Ce,(0,$.jsx)(Ts,{autoFocus:!0,placeholder:we,value:p,onChange:Te,onKeyDown:me,className:`pl-9 w-full`})]}),t[70]=me,t[71]=p,t[72]=we,t[73]=Te,t[74]=Ee):Ee=t[74];let De;t[75]!==l||t[76]!==ue||t[77]!==u||t[78]!==d||t[79]!==y?(De=l&&d&&(0,$.jsx)(`div`,{className:`flex justify-center py-1`,children:(0,$.jsxs)(Jn,{type:`button`,variant:`link`,size:`sm`,onClick:ue,disabled:u,className:`h-auto px-1 py-0 text-muted-foreground hover:text-foreground`,children:[u&&(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}),y(`chat.history.loadOlder`)]})}),t[75]=l,t[76]=ue,t[77]=u,t[78]=d,t[79]=y,t[80]=De):De=t[80];let Oe;t[81]!==E.fork||t[82]!==E.revert||t[83]!==k||t[84]!==V||t[85]!==ge||t[86]!==fe||t[87]!==g||t[88]!==_||t[89]!==p||t[90]!==h||t[91]!==y?(Oe=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=EH(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()?cG(TH(n.parts),p):null;return(0,$.jsxs)(Z.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:J(`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 fe(n.info.id),onMouseEnter:()=>g(t),children:[(0,$.jsx)(`span`,{className:J(`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:J(`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:J(`gap-1`,k?`flex`:`hidden group-hover:flex`),children:[E.revert?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{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(),ge(`revert`,n.info.id)},children:(0,$.jsx)(X,{name:_?.type===`revert`&&_.messageId===n.info.id?`loader-4`:`arrow-go-back`,className:J(`h-4 w-4`,_?.type===`revert`&&_.messageId===n.info.id&&`animate-spin`)})})}),(0,$.jsx)(Ds,{sideOffset:6,children:y(`chat.timeline.actions.revertFromHere`)})]}):null,E.fork?(0,$.jsxs)(Os,{children:[(0,$.jsx)(Es,{asChild:!0,children:(0,$.jsx)(Jn,{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(),ge(`fork`,n.info.id)},disabled:_!==null,children:_?.type===`fork`&&_.messageId===n.info.id?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(X,{name:`git-branch`,className:`h-4 w-4`})})}),(0,$.jsx)(Ds,{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]=ge,t[86]=fe,t[87]=g,t[88]=_,t[89]=p,t[90]=h,t[91]=y,t[92]=Oe):Oe=t[92];let ke;t[93]===Oe?ke=t[94]:(ke=(0,$.jsx)(`div`,{ref:M,className:`flex-1 overflow-y-auto`,children:Oe}),t[93]=Oe,t[94]=ke);let Ae;t[95]===y?Ae=t[96]:(Ae=y(`chat.timeline.actions.title`),t[95]=y,t[96]=Ae);let je;t[97]===Ae?je=t[98]:(je=(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground font-medium mb-2`,children:Ae}),t[97]=Ae,t[98]=je);let Me;t[99]!==r||t[100]!==s?(Me=()=>{s?.(-1),r(!1)},t[99]=r,t[100]=s,t[101]=Me):Me=t[101];let Ne;t[102]===y?Ne=t[103]:(Ne=y(`chat.timeline.actions.previousTurn`),t[102]=y,t[103]=Ne);let Pe;t[104]!==Me||t[105]!==Ne?(Pe=(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:Me,children:Ne}),t[104]=Me,t[105]=Ne,t[106]=Pe):Pe=t[106];let Fe;t[107]===Symbol.for(`react.memo_cache_sentinel`)?(Fe=(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`/`}),t[107]=Fe):Fe=t[107];let Ie;t[108]!==r||t[109]!==c?(Ie=()=>{c?.(),r(!1)},t[108]=r,t[109]=c,t[110]=Ie):Ie=t[110];let Le;t[111]===y?Le=t[112]:(Le=y(`chat.timeline.actions.latest`),t[111]=y,t[112]=Le);let Re;t[113]!==Ie||t[114]!==Le?(Re=(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:Ie,children:Le}),t[113]=Ie,t[114]=Le,t[115]=Re):Re=t[115];let ze;t[116]!==Pe||t[117]!==Re?(ze=(0,$.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[Pe,Fe,Re]}),t[116]=Pe,t[117]=Re,t[118]=ze):ze=t[118];let Be;t[119]===y?Be=t[120]:(Be=y(`chat.timeline.help.clickMessage`),t[119]=y,t[120]=Be);let Ve;t[121]===Be?Ve=t[122]:(Ve=(0,$.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,$.jsx)(`span`,{children:Be})}),t[121]=Be,t[122]=Ve);let He;t[123]===Symbol.for(`react.memo_cache_sentinel`)?(He=(0,$.jsx)(X,{name:`arrow-go-back`,className:`h-4 w-4 flex-shrink-0`}),t[123]=He):He=t[123];let Ue;t[124]===y?Ue=t[125]:(Ue=y(`chat.timeline.help.undoToPoint`),t[124]=y,t[125]=Ue);let We;t[126]===Ue?We=t[127]:(We=(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[He,(0,$.jsx)(`span`,{children:Ue})]}),t[126]=Ue,t[127]=We);let Ge;t[128]!==E.fork||t[129]!==y?(Ge=E.fork?(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{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]=Ge):Ge=t[130];let Ke;t[131]!==Ve||t[132]!==We||t[133]!==Ge?(Ke=(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 typography-meta text-muted-foreground`,children:[Ve,We,Ge]}),t[131]=Ve,t[132]=We,t[133]=Ge,t[134]=Ke):Ke=t[134];let qe;t[135]!==je||t[136]!==ze||t[137]!==Ke?(qe=(0,$.jsxs)(`div`,{className:`mt-4 p-3 bg-muted/30 rounded-lg`,children:[je,ze,Ke]}),t[135]=je,t[136]=ze,t[137]=Ke,t[138]=qe):qe=t[138];let Je;return t[139]!==Se||t[140]!==Ee||t[141]!==De||t[142]!==ke||t[143]!==qe?(Je=(0,$.jsxs)($.Fragment,{children:[Se,Ee,De,ke,qe]}),t[139]=Se,t[140]=Ee,t[141]=De,t[142]=ke,t[143]=qe,t[144]=Je):Je=t[144],Je};function cG(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 lG(e){return e.revertToMessage}function uG(e){return e.forkFromMessage}function dG(e){return Ws(e)}function fG(e){return ks(e)}function pG(e){return e.info.role===`user`}function mG(e){return{message:e}}var hG=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},gG=(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`}},_G=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)},vG=e=>{let t=(0,Q.c)(29),{sessionId:n,turnIds:r,activeTurnId:i,scrollToTurn:a,scrollToMessage:o,resumeToBottom:s}=e,c=Z.useRef(r),l=Z.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),Z.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),Z.useEffect(f,p);let m;t[6]===a?m=t[7]:(m=async(e,t)=>e?(t?.updateHash!==!1&&_G(`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&&_G(`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=gG(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 _G(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=()=>{_G(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=hG(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],Z.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},yG=2e4,bG=6e4,xG=2e3,SG=e=>e?(typeof e.text==`string`?e.text.length:0)+(typeof e.state?.output==`string`?e.state.output.length:0):0,CG=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+=SG(e);return[e.length,t.info.id,n.length,r?.id??``,r?.state?.status??``,i].join(`:`)},wG={sessionKey:null,fingerprint:null,lastMovementAt:null,lastRefreshAt:null,attempts:0},TG=(e,t)=>{let{sessionKey:n,working:r,streaming:i,fingerprint:a,now:o}=t;if(!n)return{state:wG,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}},EG=e=>{console.warn(`[transcript] tail frozen while session is working — refetching authority`,e)};function DG(e){return!!(e.active&&e.sessionId&&e.sessionKey&&e.sessionIsWorking)}function OG(e){return e===wG?e:wG}function kG(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 AG(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 jG(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||kG(i)==null}function MG(e){let t=[];for(let n of e){let e=Array.isArray(n.parts)?n.parts:[];for(let n of e){if(!jG(n))continue;let e=AG(n);e&&t.push(e)}}return t}function NG(e,t){return`${e}:${t.join(`,`)}`}function PG(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=NG(t,e.unansweredToolIds);return e.attemptedKey===r?{recover:!1,attemptKey:r}:{recover:!0,attemptKey:r}}function FG(e,t,n,r){let i=(0,Q.c)(7),a=Li(),o=Z.useRef(null),s=Z.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=PG({sessionId:e,directory:t,sessionQuestionCount:r,unansweredToolIds:MG(n),attemptedKey:o.current});if(!c.recover||!e||!t||!c.attemptKey)return;let l=a.getChild(t);l&&(o.current=c.attemptKey,Zr(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]),Z.useEffect(c,l)}var IG=e=>!Number.isFinite(e)||e<0?0:Math.ceil(e),LG=(e,t)=>({...e,key:RG(e),estimatedBytes:IG(t)}),RG=({runtimeKey:e,sessionId:t,directory:n})=>JSON.stringify([e,n??``,t]),zG=e=>({key:e?RG(e):null,selection:e}),BG=(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},VG=(e,t,n,r)=>{let i=RG(t),a=e.findIndex(e=>e.key===i),o=a>=0?e[a]:void 0;if(o&&a===e.length-1)return BG(e,i,n);let s=o||LG(t,r),c=a>=0?e.filter((e,t)=>t!==a):[...e];return c.push(s),BG(c,i,n)},HG=(e,t,n)=>{let r=IG(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)},UG=(e,t)=>t&&e.some(e=>e.key===t)?t:null,WG=(e,t,n)=>{let r=t.key?e.cachedSessionViews.find(e=>e.key===t.key):void 0,i=r&&t.selection?VG(e.cachedSessionViews,t.selection,n,r.estimatedBytes):BG(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}},GG=(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:LG(t.selection,r),intent:t};return e.pendingSessionView?.intent===t?e:{activeIntent:e.activeIntent,cacheNeedsTrim:e.cacheNeedsTrim,cachedSessionViews:e.cachedSessionViews,pendingSessionView:i}},KG=(e,t,n)=>{let r=e.pendingSessionView;return e.activeIntent!==t||r?.intent!==t||!t.selection?e:{activeIntent:e.activeIntent,cacheNeedsTrim:!1,cachedSessionViews:VG(e.cachedSessionViews,t.selection,n,r.entry.estimatedBytes),pendingSessionView:null}},qG=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},JG=e=>{if(!(!e.info||typeof e.info!=`object`))return e.info},YG=e=>JG(e)?.role===`assistant`,XG=(e,t)=>{let n=JG(t);n&&(e.agentName??=qG(n.agent),e.providerId??=qG(n.providerID),e.modelId??=qG(n.modelID))},ZG=e=>!!(e.agentName&&e.providerId&&e.modelId),QG=e=>{let t={};for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||!YG(r))&&(XG(t,r),ZG(t)))return t}for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||YG(r))&&(XG(t,r),ZG(t)))break}return t},$G=e=>!!e.sessionId&&!(e.hasRenderableSessionSnapshot&&e.hasCurrentSessionEntity),eK=[],tK=[],nK=[],rK={type:`idle`},iK=`openchamber:chat-force-scroll-bottom`,aK=()=>void 0,oK=`Quota limit reached. Retrying automatically.`,sK=1048576,cK=sK,lK=20,uK=sK,dK=16*sK,fK={maxEntries:3,maxEstimatedBytes:32*sK},pK={maxEntries:2,maxEstimatedBytes:32*sK},mK=e=>i(()=>e()),hK={overflowAnchor:`none`,overscrollBehavior:`contain`,overscrollBehaviorY:`contain`},gK={scrollbar:`chat`,scrollShadow:`true`,orientation:`vertical`},_K=()=>{let e=(0,Q.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},vK=`calc(max(0.625rem, var(--oc-safe-area-top, 0px)) + var(--oc-mobile-detail-navigation-height) + 1.25rem)`,yK=eU,bK=[`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(`,`),xK=e=>e instanceof HTMLElement,SK=e=>xK(e)?!!e.closest(bK):!1,CK=(e,t)=>typeof document>`u`||!e||e===document.body||e===document.documentElement||SK(e)?!0:!t?.contains(e),wK=()=>{let{isAboutDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isImagePreviewOpen:r,isMultiRunLauncherOpen:i,isSessionSwitcherOpen:a,isSettingsDialogOpen:o}=K.getState();return e||t||n||r||i||a||o},TK=Z.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,sessionForms:E,retryActionCopy:D,isProgrammaticFollowActive:O,showLoadOlderButton:k,turnIds:A,activeTurnId:j,onSelectTurn:M,showPromptNavigator:N,canLoadEarlierPrompts:P,isLoadingOlderPrompts:F,onLoadEarlierPrompts:I,transcriptStatusRow:L})=>{let{t:R}=Wn(),z=xu(e=>e.legendTimelineEnabled),B=FD({isLoadingOlder:d}),[V,H]=Z.useState({sessionId:e,directory:a,reserved:k}),ee=V.sessionId===e&&V.directory===a,U=ee&&V.reserved||k;(!ee||V.reserved!==U)&&H({sessionId:e,directory:a,reserved:U});let te=ID({isMobile:r,isLoadingOlder: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,$.jsx)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:(0,$.jsx)(`span`,{className:`oc-mobile-glass-control flex size-8 items-center justify-center rounded-full text-[var(--surface-mutedForeground)]`,"aria-label":R(`chat.history.loadingMore`),children:(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`,"aria-hidden":`true`})})})}):null,W=r&&U?(0,$.jsx)(`div`,{className:J(`flex justify-center pt-3 pb-1`,!B&&`invisible`),"aria-hidden":!B,children:(0,$.jsxs)(`span`,{role:`status`,className:`flex items-center gap-1.5 text-[var(--surface-mutedForeground)]`,"aria-busy":B,children:[(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta`,children:R(`chat.history.loadingMore`)})]})}):null,ne=Z.useRef(new Map),re=Z.useRef(new WeakMap),ie=Z.useRef(new Map),ae=Z.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(jI(n)){let r=PI(u,t)??``,i=ie.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`}];ie.current.set(n.info.id,{command:r,parts:t}),e.set(n.info.id,t)}continue}if($i(n.parts))continue;let r=re.current.get(n.parts);r||(r=DD(n.parts),re.current.set(n.parts,r)),r.length!==0&&e.set(n.info.id,r)}let t=ne.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 ne.current=e,e},[u]),oe=Z.useMemo(()=>A.filter(e=>ae.has(e)),[ae,A]),se=Z.useMemo(()=>{if(!j||ae.has(j))return j;let e=A.indexOf(j);for(let t=e-1;t>=0;--t){let e=A[t];if(ae.has(e))return e}return null},[j,ae,A]),ce=q(e=>{e.defaultPrevented||SK(e.target)||typeof window<`u`&&window.getSelection()?.type===`Range`||o.current?.focus({preventScroll:!0})});return dl({scrollRef:o,enabled:z,onUpwardIntent:y}),z?(0,$.jsx)(`div`,{className:J(`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)(VV,{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:hK,timelineScrollDataset:gK,timelineOnScroll:v,timelineFollowEnabled:!c&&!x,timelineHistoryAnchorToken:S,timelineOnIsAtEndChange:b,headerSlot:(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:vK},"aria-hidden":`true`}),W,te]}),footerSlot:(0,$.jsxs)($.Fragment,{children:[(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(mH,{question:e},e.id)),T.map(e=>(0,$.jsx)(sH,{permission:e},e.id))]}),L?(0,$.jsx)(`div`,{className:`mb-1`,children:L}):null,a&&(0,$.jsx)(wH,{sessionID:e,directory:a}),(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?yK:QH},"aria-hidden":`true`})]})}),(0,$.jsx)(kc,{containerRef:o,suppressVisibility:O,userIntentOnly:!0,observeMutations:!1}),N&&oe.length>=2?(0,$.jsx)(qH,{turnIds:oe,previewsByTurnId:ae,activeTurnId:se,onSelectTurn:M,canLoadEarlier:P,isLoadingOlder:F,onLoadEarlier:I}):null]})}):(0,$.jsx)(`div`,{className:J(`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)(Wc,{className:J(`absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target`),ref:o,style:hK,observeMutations:!1,hideTopShadow:r&&i,hideBottomShadow:r,tabIndex:0,onClick:ce,onScroll:v,"data-scroll-shadow":`true`,"data-scrollbar":`chat`,children:(0,$.jsxs)(`div`,{className:J(`oc-chat-scroll-content relative z-0 min-h-full`,r&&`chat-scroll-foot-inset`),children:[W,te,(0,$.jsx)(VV,{ref:s,sessionKey:e,virtualizerKey:t,timelineHistoryAnchorToken:S,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:L??(0,$.jsx)(TL,{})}):null}),(w.length>0||T.length>0||E.length>0||D)&&(0,$.jsxs)(`div`,{children:[D?(0,$.jsxs)(`div`,{className:`mb-2 rounded-xl border border-border/20 bg-muted/10 px-2.5 py-2`,children:[(0,$.jsx)(`div`,{className:`typography-ui-label text-foreground`,children:D.title}),(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mt-1`,children:D.message}),D.link?(0,$.jsx)(`a`,{href:D.link,target:`_blank`,rel:`noreferrer`,className:`mt-2 inline-block typography-meta text-primary underline`,children:D.label}):null]}):null,w.map(e=>(0,$.jsx)(mH,{question:e},e.id)),T.map(e=>(0,$.jsx)(sH,{permission:e},e.id)),E.map(e=>(0,$.jsx)(gH,{form:e,directory:a},e.id))]}),a&&(0,$.jsx)(wH,{sessionID:e,directory:a}),(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?$H:QH},"aria-hidden":`true`})]})}),(0,$.jsx)(kc,{containerRef:o,suppressVisibility:O,userIntentOnly:!0,observeMutations:!1}),N&&oe.length>=2?(0,$.jsx)(qH,{turnIds:oe,previewsByTurnId:ae,activeTurnId:se,onSelectTurn:M,canLoadEarlier:P,isLoadingOlder:F,onLoadEarlier:I}):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.sessionForms===t.sessionForms&&e.retryActionCopy===t.retryActionCopy&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&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);TK.displayName=`ChatViewport`;var EK=[{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%]`]}],DK=e=>Gn(e.path),OK=(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)]})},kK=e=>{let t=Math.ceil(Math.max(0,e)/lK);return Math.min(dK,cK+t*uK)},AK=Z.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=tK,onPendingUserMessagesMaterialized:p,committedDraftHandoffMessageId:m=null})=>{let h=c??BD(void 0),{t:g}=Wn();zn(()=>{Aa()},[]);let _=Y(e=>e.openNewSessionDraft),v=Y(e=>e.setCurrentSession),y=Y(e=>e.newSessionDraft),b=Y(e=>e.newSessionDraft.draftSubmitting??!1),x=Y(e=>e.newSessionDraft.draftEstablishing??!1),S=Y(e=>e.forkTransition),C=Co(e=>e.projects),w=Co(e=>e.activeProjectId),T=ao(e=>e.providers),E=Ih(),D=Bo(),O=i??D;zn(()=>{!n||!r||!O||Ti(O,r)},[n,r,O]);let k=q(e=>E.ensureSessionRenderable(e,{directory:O})),A=K(e=>e.isExpandedInput),j=K(e=>e.stickyUserHeader),M=K(e=>e.promptNavigatorEnabled),N=K(e=>e.allowPromptingSubagentSessions),P=K(e=>e.isTimelineDialogOpen),F=K(e=>e.setTimelineDialogOpen),I=ei(e=>n&&r?e.streamingMessageIds.get(r)??null:null),L=ei(e=>I?e.messageStreamStates.get(I)?.phase??null:null),R=oa(r??``,O),z=kK(R);Z.useEffect(()=>{!a||!o||o(a,z)},[o,z,a]);let B=za(r??``,O).renderable,V=Sa(r,O),H=Ui(r),ee=V??H,U=qx({sessionId:r,hasSessionEntity:!!ee,hasRenderableSessionSnapshot:B,composerSurfaceKind:s?.kind}),te=r?JSON.stringify([O,r]):null,[W,ne]=Z.useState({key:te,attempt:0}),re=vo(r??``,O,{suspendPartUpdates:!!I,suspendPartUpdatesForMessageId:I,enabled:n}),ie=r?re:eK,ae=y.pendingUserMessage,oe=Y(e=>r?e.retainedPendingUserMessages.get(r):void 0)??tK,se=!!(m||oe.length>0),ce=Y(e=>e.clearRetainedPendingUserMessages),le=Z.useMemo(()=>{if(oe.length===0)return f;if(f.length===0)return oe;let e=new Set(f.map(e=>e.info.id));return[...f,...oe.filter(t=>!e.has(t.info.id))]},[f,oe]),ue=Z.useMemo(()=>QG(ie),[ie]),de=Z.useMemo(()=>{if(!ue.modelId)return g(`common.unavailable`);let e=T.find(e=>e.id===ue.providerId);return hr(e,ue.modelId)||ue.modelId},[T,ue.modelId,ue.providerId,g]),pe=ro(r??``,O),me=Ma(r??``,O),[he,ge]=Z.useState(null),_e=!!r&&he===r,ve=q(()=>{if(!r||_e)return;let e=r,t=O;ge(e);let n=Ai(()=>{let n=dn();if(!n)throw Error(`unbound`);return n.getTranscript(Vt(t,e))});Di(gr({kind:`refresh`,sessionID:e,directory:t,purpose:`retry`,source:`network`,request:pe?{sessionID:e,status:pe.status===`ready`?`ready`:pe.status,error:pe.error}:void 0,hydration:me,error:pe?.error})),(async()=>{try{await Wt(t,e),await E.ensureSessionRenderable(e,{directory:t});try{let r=Ai(()=>{let n=dn();if(!n)throw Error(`unbound`);return n.getTranscript(Vt(t,e))});n&&r&&dr({trigger:`user-refresh`,sessionID:e,directory:t,purpose:`retry`,before:n,after:r})}catch{}}catch(n){Di(gr({kind:`request-error`,sessionID:e,directory:t,purpose:`retry`,source:`network`,hydration:me,error:n}))}finally{ge(t=>t===e?null:t)}})()}),ye=ra(r??``,O).boundary,be=q(async e=>{if(ye.kind===`has-more`){await pn(O,e);return}if(ye.kind===`unknown`){await sn(O,e);return}l&&!l.complete&&await l.fetchPrevious()}),xe=so(r??``,O),Se=Za(r??``,O),Ce=Fa(O),we=xe??rK,Te=yi(r,O),Ee=tr(r,O),De=Cr(e=>r?e.forms[r]??nK:nK),Oe=Z.useMemo(()=>De.filter(e=>!vt(e.metadata)),[De]);Z.useEffect(()=>{r&&ji({sessionID:r,directory:O}).catch(e=>{console.error(`[ChatContainer] Failed to list session forms:`,e)})},[r,O]),FG(r,O,ie,Ee.length);let ke=Z.useMemo(()=>{if(!r||Te.length>0||Ee.length>0)return!1;let e=we.type??`idle`;if(e===`busy`||e===`retry`||jD(le,{resolvedSessionStatus:xe,sessionStatusObservedAt:Se}))return!0;let t=ie[ie.length-1]?.info,n=t?.time?.created;return xe&&typeof Se==`number`&&typeof n==`number`&&n<=Se||typeof Ce==`number`&&typeof n==`number`&&n<=Ce?!1:!!(t&&t.role===`assistant`&&typeof t.time?.completed!=`number`)},[r,le,xe,ie,Te.length,Ee.length,we.type,Se,Ce]),Ae=Z.useMemo(()=>!r||we.type!==`retry`?null:{sessionId:r,message:(typeof we.message==`string`?(we.message??``).trim():``)||oK,confirmedAt:we.confirmedAt},[r,we]),[je,Me]=Z.useState(0),Ne=Z.useRef(null);Z.useEffect(()=>{if(!Ae||typeof Ae.confirmedAt==`number`){Ne.current=null,Me(0);return}Ne.current!==Ae.sessionId&&(Ne.current=Ae.sessionId,Me(Date.now()))},[Ae]);let Pe=Z.useMemo(()=>!Ae||bH(we)?null:{...Ae,fallbackTimestamp:je},[Ae,je,we]),Fe=Z.useMemo(()=>xH(we,e=>g(e)),[we,g]),Ie=!!(r&&E.isLoading(r,{directory:O})),Le=Z.useMemo(()=>{if(!r)return null;let e=MD({boundary:ye,assistantComplete:l?.complete??!0});return{limit:ye.loadedTurns,complete:e.complete,canLoadEarlier:e.canLoadEarlier,loading:ND({syncLoading:Ie,assistantLoading:!!l?.loading})}},[l?.complete,l?.loading,r,ye,Ie]),Re=K(e=>e.isMobile),ze=qc()!==null,Be=fe(),Ve=Ix(),He=!!y?.open,Ue=ii(e=>e.error),We=A,Ge=ze||Re||Be||Ve===`mini-chat`,Ke=Z.useRef(null),qe=Z.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?DK(n):null},[w,y?.selectedProjectId,C]),Je=Ji(r,O),Ye=a??r??``,[Xe,Ze]=Z.useState(null),Qe=Qx(Xe,Ye,Je,ue);zn(()=>{Ze(e=>Qx(e,Ye,Je,ue))},[Je,ue,Ye]);let $e=Je??Qe?.parentTarget??null,et=Qe?.execution??ue,tt=wp(),nt=tt!==null&&r===tt,rt=q(()=>{$e&&v($e.id,$e.directory)}),it=$e?.session?.title,at=h.returnToParent&&$e&&!nt?(0,$.jsxs)(Jn,{type:`button`,variant:`outline`,size:`xs`,onClick:rt,className:`absolute left-3 top-3 z-20 !font-normal bg-[var(--surface-background)]/95`,"aria-label":g(`chat.container.returnToParent.aria`),title:it?.trim()?g(`chat.container.returnToParent.titleNamed`,{title:it}):g(`chat.container.returnToParent.title`),children:[(0,$.jsx)(X,{name:`arrow-left`,className:`h-4 w-4`}),g(`chat.container.returnToParent.label`)]}):null,ot=Jx({readOnly:t,sessionIdentityPending:U,isSubagentSession:!!ee?.parentID||!!Qe,allowPromptingSubagentSessions:N}),st=et.modelId===ue.modelId?de:et.modelId?hr(T.find(e=>e.id===et.providerId),et.modelId)||et.modelId:g(`common.unavailable`),ct=$e?(0,$.jsx)(WD,{agentName:et.agentName,providerId:et.providerId,modelId:et.modelId,modelName:st}):(0,$.jsx)(WD,{}),lt=q(e=>{K.getState().setAllowPromptingSubagentSessions(e.allowPromptingSubagentSessions)}),ut=q(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`&<({allowPromptingSubagentSessions:t.payload.allowPromptingSubagentSessions})}),dt=typeof window<`u`&&window.parent!==window;Bn(`message`,ut,dt?window:aK),Vn(()=>{if(!dt)return;let e=window;e.__openchamberApplyChatSettingsSync=lt,window.parent.postMessage({type:`openchamber:chat-settings-request`},window.location.origin)}),Rn(()=>{if(typeof window>`u`)return;let e=window;e.__openchamberApplyChatSettingsSync===lt&&delete e.__openchamberApplyChatSettingsSync}),Z.useEffect(()=>{h.newSessionDraft&&e&&!r&&!He&&_()},[e,r,He,h.newSessionDraft,_]);let ft=Z.useRef(()=>{}),mt=q(e=>{ft.current(e)}),ht=Z.useRef(()=>{}),gt=q(()=>{ht.current()}),_t=xu(e=>e.legendTimelineEnabled),[yt,bt]=Z.useState(!0),[xt,St]=Z.useState(!1),[Ct,wt]=Z.useState(!1),[Tt,Et]=Z.useState(0),Dt=q(()=>{Et(e=>e+1)}),Ot=q((e,t)=>{bt(e),e&&wt(!1),t!==void 0&&St(t)});Z.useEffect(()=>{bt(!0),St(!1),wt(!1)},[r]);let{scrollRef:kt,notifyContentChange:At,getAnimationHandlers:jt,goToBottom:Mt,scrollToBottomOnSend:Nt,releaseAutoFollow:Pt,beginHistoryViewportPreservation:Ft,endHistoryViewportPreservation:It,restoreSnapshot:Lt,isPinned:Rt,isFollowingProgrammatically:zt,showScrollButton:Bt}=xU({enabled:n&&!_t,currentSessionId:r,viewportKey:a,sessionMessageCount:R,sessionIsWorking:ke,isMobile:Re,onActiveTurnChange:mt,onUpwardUserIntent:gt}),Ht=Z.useRef(null);WU({enabled:Re,scrollRef:kt,scopeRef:Ht});let Ut=Z.useRef([]),Gt=Z.useMemo(()=>{let e=$D(l?.entries??[],r,Ut.current);return Ut.current=e,e},[l?.entries,r]),Kt=Z.useRef([]),qt=Z.useMemo(()=>{if(!l)return ie;let e=nO(l.entries,r,ie,Kt.current);return Kt.current=e,e},[l,r,ie]),Jt=Z.useMemo(()=>AD(Gt.length===0?qt:r?[...Gt,ZD(r),...qt]:Gt,le),[r,qt,Gt,le]),Yt=Z.useRef(null),Xt=Z.useMemo(()=>zD({sessionId:r,messages:Jt,retained:Yt.current}),[r,Jt]);Yt.current=Xt.retained;let Zt=Xt.messages,Qt=Z.useRef(null),$t=Qt.current===r,en=Z.useRef(wG),tn=r?`${O}\n${r}`:null,nn=q(()=>CG(Zt));Z.useEffect(()=>{if(!DG({active:n,sessionId:r,sessionKey:tn,sessionIsWorking:ke})){en.current=OG(en.current);return}let e=r,t=O,i=setInterval(()=>{let n=nn(),r=TG(en.current,{sessionKey:tn,working:!0,streaming:!!I,fingerprint:n,now:Date.now(),thresholdMs:yG,cooldownMs:bG,maxAttempts:3});en.current=r.state,r.shouldRefresh&&(EG({sessionId:e,directory:t,stalledForMs:r.stalledForMs,attempt:r.state.attempts,fingerprint:n}),pt(t,e).catch(()=>{}))},xG);return()=>clearInterval(i)},[n,r,O,nn,ke,I,tn]);let rn=Z.useMemo(()=>{if(le.length===0)return[];let e=new Set([...Gt,...qt].filter(e=>kD(e.parts)).map(e=>e.info.id));return le.map(e=>e.info.id).filter(t=>e.has(t))},[qt,Gt,le]);Z.useEffect(()=>{rn.length!==0&&(p?.(rn),r&&ce(r,rn))},[ce,r,rn,p]);let an=iG({sessionId:r,directory:O,messages:Zt,historyMeta:Le,scrollRef:kt,messageListRef:Ke,loadMoreMessages:be,goToBottom:Mt,releaseAutoFollow:Pt,beginHistoryViewportPreservation:Ft,endHistoryViewportPreservation:It,isPinned:_t?yt:Rt,showScrollButton:_t?xt:Bt,isMobile:Re,autoFillEnabled:n&&!We,onWillLoadEarlier:Dt}),on=q(()=>{wt(!1),Ke.current?.scrollToBottom(),Mt(`instant`)}),cn=q(()=>{wt(!1),Nt()}),ln=q(()=>{wt(!0),an.handleHistoryUpwardIntent()}),un=PD({isMobile:Re,canLoadEarlier:an.historySignals.canLoadEarlier,isLoadingOlder:an.isLoadingOlder}),fn=an.isLoadingOlder,mn=an.loadEarlier,hn=q(()=>{wt(!0),mn({userInitiated:!0})});ft.current=an.handleActiveTurnChange,ht.current=an.handleHistoryUpwardIntent,Z.useEffect(()=>{(Te.length!==0||Ee.length!==0)&&At(`permission`)},[At,Te,Ee]);let gn=vG({sessionId:r,turnIds:an.turnIds,activeTurnId:an.activeTurnId,scrollToTurn:an.scrollToTurn,scrollToMessage:an.scrollToMessage,resumeToBottom:on}),_n=ot.showReadOnlyBanner?ct:t?null:(0,$.jsx)(aD,{surface:s,scrollToBottom:cn,showScrollToBottom:Re&&an.showScrollToBottom,onScrollToBottom:gn.resumeToLatest,submissionBlocked:ot.blockSubmission}),vn=q(e=>{gn.scrollToTurnId(e,{behavior:`smooth`})}),G=an.historySignals.canLoadEarlier,yn=h.promptNavigator&&!Re&&!Be&&!We&&M&&an.turnIds.length>=2;Z.useEffect(()=>{yn||K.getState().setPromptNavigatorPanelOpen(!1)},[yn]);let bn=q(e=>{if(!n||!r)return;let t=e;t.detail?.sessionId&&t.detail.sessionId!==r||Mt(`instant`)});Bn(iK,bn,n&&r&&typeof window<`u`?window:aK);let xn=q(e=>{if(!n||!r||We||e.defaultPrevented||e.isComposing||e.key!==`ArrowUp`&&e.key!==`ArrowDown`||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let{activeMainTab:t}=K.getState();if(t!==`chat`||wK())return;let i=kt.current;if(CK(document.activeElement,i)||SK(e.target))return;e.preventDefault();let a=e.key===`ArrowUp`?-1:1;gn.scrollByTurnOffset(a,{resumePastEnd:!1})});Bn(`keydown`,xn,n&&r&&!We&&typeof window<`u`?window:aK);let Sn=Z.useRef(0),Cn=q(()=>{let e=kt.current;e&&e.style.setProperty(`--chat-scroll-height`,`${e.clientHeight}px`)}),wn=q(()=>{Sn.current||=requestAnimationFrame(()=>{Sn.current=0,Cn()})});zn(()=>{n&&Cn()},[n,r,We,Cn]);let Tn=typeof ResizeObserver<`u`;In(n&&Tn?kt:null,wn),Bn(`resize`,wn,n&&!Tn&&typeof window<`u`?window:aK),Rn(()=>{Sn.current&&=(cancelAnimationFrame(Sn.current),0)});let En=Z.useRef(null),Dn=Z.useRef(0),On=LD({transcriptMessageCount:ie.length,pendingUserCount:le.length,historyPrefixCount:Gt.length}),kn=RD({hasTranscriptShell:On,transcriptRecords:ie,p0Satisfied:me.p0Satisfied,hasBusyShell:ke&&On,hasImmediateShell:le.length>0||Gt.length>0,hasRenderableSessionSnapshot:B,prefetchStatus:pe?.status,syncLoading:!!(r&&E.isLoading(r,{directory:O})),userRetrying:_e,hasPaintedTranscript:$t});kn===`pass`&&Zt.length>0&&(Qt.current=r);let An=!!r&&kn===`hydrating`,jn=!!r&&kn===`load-error`;Z.useEffect(()=>{!jn||!r||Di(gr({kind:`request-error`,sessionID:r,directory:O,purpose:`load-failed`,source:`network`,request:pe?{sessionID:r,status:pe.status===`ready`?`ready`:pe.status,error:pe.error}:void 0,hydration:me,error:pe?.error}))},[r,O,jn,pe,me]),Z.useEffect(()=>{if(!n||!r||An)return;let e=Zt.length,t=En.current!==r,i=!t&&Dn.current===0&&e>0;if(!t&&!i){En.current===r&&(Dn.current=e);return}let a=typeof window<`u`&&window.location.hash.length>0;if(En.current=r,Dn.current=e,a){Pt();return}let o=()=>{Lt()};typeof window>`u`?o():window.requestAnimationFrame(o)},[n,r,An,Pt,Lt,Zt.length]),Z.useEffect(()=>{ne(e=>e.key===te?e:{key:te,attempt:0})},[te]),Z.useEffect(()=>{if(!n||!r||W.key!==te||!$G({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)(my,{})]}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground/70 tabular-nums`,children:n})]})})}if(!r&&!He)return e&&!Ue?(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)(KD,{})});if(!r&&He){if((b||x)&&ae){let e=`draft:${y.draftID??`pending`}`;return(0,$.jsxs)(`div`,{ref:Ht,className:J(`relative flex h-full flex-col bg-background`,Re&&`oc-chat-composer-swap-scope`),children:[(0,$.jsx)(TK,{currentSessionId:e,virtualizerKey:e,isDesktopExpandedInput:!1,isMobile:Re,stickyUserHeader:j,directory:O,scrollRef:kt,messageListRef:Ke,pendingRevealWork:!1,initialPinRevealComplete:!0,renderedMessages:[ae],isLoadingOlder:!1,sessionIsWorking:!0,streamingMessageId:null,activeStreamingPhase:null,retryOverlay:null,handleMessageContentChange:At,getAnimationHandlers:jt,handleHistoryScroll:an.handleHistoryScroll,handleHistoryUpwardIntent:ln,onTimelineIsAtEndChange:Ot,timelineFollowSuspended:!1,timelineHistoryAnchorToken:Tt,scrollToBottom:on,sessionQuestions:[],sessionPermissions:[],sessionForms:[],retryActionCopy:null,isProgrammaticFollowActive:zt,showLoadOlderButton:!1,turnIds:[],activeTurnId:null,onSelectTurn:vn,showPromptNavigator:!1,canLoadEarlierPrompts:!1,isLoadingOlderPrompts:!1,onLoadEarlierPrompts:hn,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)(my,{})]})})},e),(0,$.jsxs)(`div`,{className:J(`invisible pointer-events-none relative z-10`,Re&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,We?`absolute inset-0 bg-background`:`bg-background`),"aria-hidden":`true`,children:[!Re&&!We?(0,$.jsx)(_K,{}):null,_n]}),(0,$.jsx)(fD,{})]})}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)(my,{})]})})}):(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[Ge&&!We?(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:OK(qe?g(`chat.emptyState.draftTitleWithProject`,{project:qe}):g(`chat.emptyState.draftTitle`),qe)}),(0,$.jsx)(WS,{onSubmit:e=>yo.getState().requestPresetSubmit(e),className:`oc-draft-starters mt-8 max-w-md`})]}):null,(0,$.jsx)(`div`,{className:J(`relative z-10 flex min-h-0`,Re&&`oc-mobile-composer-foot`,We?`flex-1 bg-background`:Ge?J(`bg-background`,`px-0`):`flex-1 items-center justify-center bg-background px-0 pb-[6vh]`),children:_n})]})}return r?jn?(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[at,(0,$.jsx)(`div`,{className:J(`relative min-h-0`,We?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":We,children:We?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)(X,{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)(Jn,{type:`button`,className:`mt-5`,onClick:ve,children:[(0,$.jsx)(X,{name:`refresh`,className:`size-4`,"aria-hidden":`true`}),g(`chat.history.retry`)]})]})})}),(0,$.jsx)(`div`,{className:J(`relative z-10`,Re&&`oc-mobile-composer-foot`,We?`flex-1 min-h-0 bg-background`:`bg-background`),children:_n})]}):An?(0,$.jsxs)(`div`,{ref:Ht,className:J(`relative flex flex-col h-full bg-background`,Re&&`oc-chat-composer-swap-scope`),children:[at,(0,$.jsx)(`div`,{className:J(`relative min-h-0`,We?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":We,children:(0,$.jsx)(`div`,{ref:kt,className:`absolute inset-0 overflow-y-auto overflow-x-hidden bg-background pt-6 chat-scroll`,style:hK,children:(0,$.jsx)(`div`,{className:`space-y-4 chat-scroll-foot-inset`,children:EK.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)(Vd,{className:`h-3.5 w-3.5 rounded-full flex-shrink-0`}),(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,t.titleWidth)}),(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,t.detailWidth)})]},`${e.id}-${t.id}`))}),(0,$.jsxs)(`div`,{className:`space-y-1.5 pt-1`,children:[(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,e.textWidths[0])}),(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,e.textWidths[1])}),(0,$.jsx)(Vd,{className:J(`h-4 rounded-md`,e.textWidths[2])})]})]})})},e.id))})})}),(0,$.jsxs)(`div`,{className:J(`relative z-10`,Re&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,We?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Re&&!We?(0,$.jsx)(_K,{}):null,_n]})]}):Zt.length===0&&!ke?(0,$.jsxs)(`div`,{className:`relative flex flex-col h-full bg-background`,children:[at,(0,$.jsx)(`div`,{className:J(`relative min-h-0`,We?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":We,children:We?null:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,$.jsx)(KD,{})})}),(0,$.jsx)(`div`,{className:J(`relative z-10`,Re&&`oc-mobile-composer-foot`,We?`flex-1 min-h-0 bg-background`:`bg-background`),children:_n}),(0,$.jsx)(fD,{})]}):(0,$.jsxs)(`div`,{ref:Ht,className:J(`relative flex flex-col h-full bg-background`,Re&&`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,at,(0,$.jsx)(TK,{currentSessionId:r,virtualizerKey:a??r,isDesktopExpandedInput:We,isMobile:Re,stickyUserHeader:j,directory:O,scrollRef:kt,messageListRef:Ke,pendingRevealWork:an.pendingRevealWork,initialPinRevealComplete:se,renderedMessages:an.renderedMessages,isLoadingOlder:fn,sessionIsWorking:ke,streamingMessageId:I,activeStreamingPhase:L,retryOverlay:Pe,handleMessageContentChange:At,getAnimationHandlers:jt,handleHistoryScroll:an.handleHistoryScroll,handleHistoryUpwardIntent:ln,onTimelineIsAtEndChange:Ot,timelineFollowSuspended:Ct,timelineHistoryAnchorToken:Tt,scrollToBottom:on,sessionQuestions:Ee,sessionPermissions:Te,sessionForms:Oe,retryActionCopy:Fe,isProgrammaticFollowActive:zt,showLoadOlderButton:un,turnIds:an.turnIds,activeTurnId:an.activeTurnId,onSelectTurn:vn,showPromptNavigator:yn,canLoadEarlierPrompts:G,isLoadingOlderPrompts:fn,onLoadEarlierPrompts:hn},r),(0,$.jsxs)(`div`,{className:J(`relative z-10`,Re&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,We?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Re&&!We?(0,$.jsx)(_K,{}):null,!We&&Zt.length>0&&(Re?(0,$.jsx)(Px,{placement:`expanded`,visible:an.showScrollToBottom,onClick:gn.resumeToLatest}):(0,$.jsx)(Px,{visible:an.showScrollToBottom,onClick:gn.resumeToLatest})),_n]}),(0,$.jsx)(fD,{}),(0,$.jsx)(oG,{open:P,onOpenChange:F,sessionID:r??void 0,directory:O,onRevertMessage:u,onScrollToMessage:an.scrollToMessage,onScrollByTurnOffset:gn.scrollByTurnOffset,onResumeToLatest:on,canLoadEarlier:an.historySignals.canLoadEarlier,isLoadingEarlier:fn,onLoadEarlier:hn})]}):null});AK.displayName=`MemoizedChatContainerContent`;var jK=()=>{let e=(0,Q.c)(2),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Vd,{className:`h-4 w-4/5 animate-none rounded-md`}),(0,$.jsx)(Vd,{className:`h-4 w-2/3 animate-none rounded-md`}),(0,$.jsx)(Vd,{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)(Vd,{className:`h-4 w-5/6 animate-none rounded-md`}),(0,$.jsx)(Vd,{className:`h-4 w-3/5 animate-none rounded-md`})]}),(0,$.jsx)(Vd,{className:`h-24 w-full animate-none rounded-xl`})]})})}),e[1]=n):n=e[1],n},MK=({runtimeKey:e,...t})=>{let n=Ix(),r=Bo(),i=Y(Je(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=Z.useRef(null),o=i.draftID&&i.draftPendingMessageId?`${i.draftID}:${i.draftPendingMessageId}`:null;o&&a.current?.identity!==o&&(a.current=null),zn(()=>{!o||!i.draftPendingMessageId||(a.current={identity:o,messageId:i.draftPendingMessageId})},[o,i.draftPendingMessageId]);let s=Y(e=>i.sessionId?e.retainedPendingUserMessages.get(i.sessionId)??tK:tK),c=a.current,l=c&&s.some(e=>e.info.id===c.messageId)?c.messageId:null,u=Z.useMemo(()=>i.sessionId?{runtimeKey:e,sessionId:i.sessionId,directory:i.directory??r}:null,[e,i.directory,i.sessionId,r]),d=Z.useMemo(()=>zG(u),[u]),f=d.key,p=Rr()||fe()||n===`mini-chat`?pK:fK,[m,h]=Z.useState(()=>({activeIntent:d,cacheNeedsTrim:!1,cachedSessionViews:u?VG([],u,p,cK):[],pendingSessionView:null})),g=Z.useRef(d),_=Z.useRef(f),{cacheNeedsTrim:v,cachedSessionViews:y,pendingSessionView:b}=m,x=b?.intent===d?b.entry:null,S=Z.useMemo(()=>!u||!l?null:VG([],u,p,cK)[0]??null,[p,l,u]),C=Z.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=UG(C,f),T=!!(f&&!w);zn(()=>{g.current=d,_.current=f,h(e=>{let t=WG(e,d,p);return l?GG(t,d,d,cK):t})},[p,v,l,d,f]);let E=b?.intent??null;zn(()=>{E&&h(e=>KG(e,E,p))},[p,E]),Z.useEffect(()=>{if(!d.selection||w)return;let e=d,t=f;return $u(()=>{g.current===e&&_.current===t&&h(n=>_.current===t?GG(n,e,g.current,cK):n)},{priority:`user-blocking`})},[w,p,d,f]);let D=q((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=HG(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)(jK,{},f):null,C.map(e=>(0,$.jsx)(Z.Activity,{name:`chat-session-${e.sessionId}`,mode:w===e.key?`visible`:`hidden`,children:(0,$.jsx)(AK,{...t,sessionId:e.sessionId,sessionDirectory:e.directory,sessionViewKey:e.key,onSessionViewEstimateChange:D,committedDraftHandoffMessageId:w===e.key?l:null})},e.key)),f?null:(0,$.jsx)(AK,{...t,sessionId:null,sessionDirectory:i.directory})]})},NK=e=>{let t=(0,Q.c)(24),{host:n,runtimeKey:r,readOnly:i}=e,a=i!==void 0&&i,o;t[0]===n?o=t[1]:(o=BD(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)(AK,{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)(Zb.Provider,{value:u,children:f}),t[21]=u,t[22]=f,t[23]=p):p=t[23],p},PK=e=>{let t=(0,Q.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=Bo(),o=n.directory??a,s;t[4]!==o||t[5]!==n?(s=Xb({...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)(AK,{...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)(Zb.Provider,{value:c,children:u}),t[13]=c,t[14]=u,t[15]=d):d=t[15],d},FK=e=>{let t=(0,Q.c)(14),n=Z.useSyncExternalStore(mK,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)(NK,{...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)(PK,{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)(MK,{...e,runtimeKey:n},n),t[11]=e,t[12]=n,t[13]=r):r=t[13],r},IK=2e4,LK=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus()?`visible`:`hidden`,RK=e=>{if(!_e()&&!Yt())return;let t=w();t?.push?.setVisibility&&t.push.setVisibility({visible:e,platform:nn()})},zK=e=>{let t=e?.enabled??!0;Z.useEffect(()=>{if(!t||!_e()&&!Yt()||typeof window>`u`)return;if(Yt()){let e=!0,t=!1,n=null,r=()=>RK(e);Sn(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&&RK(!0)},IK);return()=>{t=!0,window.clearInterval(i),n?.()}}if(typeof document>`u`)return;let e=()=>{RK(LK()===`visible`)},n=()=>{LK()===`visible`&&RK(!0)},r=()=>{RK(!1)};e();let i=window.setInterval(n,IK);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])},BK=`OpenChamber`,VK=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``).split(`/`).filter(Boolean);return t[t.length-1]??``},HK=(e,t)=>[e,t,BK].filter(e=>typeof e==`string`&&e.trim().length>0).join(` | `),UK=()=>{let e=Co(e=>e.activeProjectId?e.projects.find(t=>t.id===e.activeProjectId)??null:null),t=Z.useMemo(()=>e&&VK(e.path)||null,[e]),[n,r]=Z.useState(null);Z.useEffect(()=>{if(typeof window>`u`||!he()){r(null);return}let e=!1,t=async()=>{try{if(ue()){e||r(null);return}let t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,n=d();if(n&&Me(n,t)){e||r(null);return}let i=(await Be()).hosts.find(e=>n?Me(n,Fe(e)):!1),a=i?.label?.trim()?Ne(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=Z.useMemo(()=>HK(t,n),[t,n]);Z.useEffect(()=>{typeof document<`u`&&(document.title=i),he()&&(async()=>{try{if(typeof navigator<`u`&&/Macintosh|Mac OS X/.test(navigator.userAgent||``))return;await Yn(i)}catch{return}})()},[i])},WK=e=>{let t=[];return e.hideGit||t.push(`git`),t.push(`files`),e.showBrowser&&t.push(`browser`),t},GK=e=>e===`git`||e===`files`||e===`browser`,KK=()=>{let e=Y.getState().currentSessionId;if(!e)return``;let t=gt().find(t=>t.id===e);return typeof t?.directory==`string`?t.directory:``},qK=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)}},JK=e=>{if(!e||!Number.isFinite(e))return`(n/a)`;try{return new Date(e).toISOString()}catch{return`(invalid)`}},YK=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},XK=e=>!!e&&typeof e==`object`&&!Array.isArray(e),ZK=(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,QK=(e,t,n)=>e===`node-shebang`||e===`node-launcher`?t?`node (${t})`:`node`:e===`bun-shebang`?n?`bun (${n})`:`bun`:e||`direct executable`,$K=async()=>{let e=new Date,t=typeof navigator<`u`?navigator.userAgent:`(no navigator)`,n=KK(),r=K.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 qK(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: 2.0.1`),m.push(`Runtime: ${i||`(unknown)`} (api=${c||`(unknown)`})`),m.push(`OpenCode SDK base: ${xt.getBaseUrl()}`),m.push(`Event stream: ${r}`),m.push(`Directory: ${n||`(none)`}`),m.push(`Platform: ${t}`);let h=YK(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 l?.openCodeServeVersion==`string`&&l.openCodeServeVersion.trim()&&m.push(`OpenCode serve version: ${l.openCodeServeVersion}`),typeof l?.openCodeCliVersion==`string`&&l.openCodeCliVersion.trim()&&m.push(`OpenCode CLI version: ${l.openCodeCliVersion}`),XK(l?.runtimeContract)){let e=l.runtimeContract,t=typeof e.phase==`string`?e.phase:`(unknown)`,n=e.executionAllowed===!0?`allowed`:`limited`,r=e.protocolCompatible===!0?`compatible`:`incompatible`;m.push(`OpenCode runtime contract: phase=${t} protocol=${r} execution=${n}`),Array.isArray(e.reasons)&&e.reasons.length>0&&m.push(`OpenCode contract reasons: ${e.reasons.filter(e=>typeof e==`string`).join(`, `)}`)}if(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=XK(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: ${ZK(e.launchedAt)}`),m.push(`- launch: ${ZK(e.binary)} ${t.join(` `)}`.trim()),m.push(`- cwd: ${ZK(e.cwd)}`),m.push(`- wrapper: ${ZK(e.wrapperType)}`),m.push(`- runtime: ${QK(ZK(e.wrapperType,``),f,p)}`),m.push(`- PATH entries: ${ZK(e.pathEntryCount,`(unknown)`)}`),m.push(`- shell env: ${ZK(e.hasShellEnv,`(unknown)`)} (${ZK(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: ${QK(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: ${JK(Date.now())}`),m.join(`
|
|
6604
6604
|
`)},eq=async()=>{let e=await $K(),t=K.getState();t.setOpenCodeStatusText(e),t.setOpenCodeStatusDialogOpen(!0)},tq=(e,t)=>e===t?!0:!e||!t?!1:e.scope===t.scope&&e.sessionId===t.sessionId&&e.projectId===t.projectId,nq=e=>e?`${e.scope}:${e.projectId??``}:${e.sessionId}`:null,rq=e=>({scope:`project`,sessionId:e,projectId:null}),iq=Ue()(e=>({focus:null,setFocus:t=>e(e=>tq(e.focus,t)?e:{focus:t})})),aq=null,oq=0,sq=(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},cq=e=>{let t=++oq;return aq={pinned:sq(`pinned`,e.pinned),project:sq(`project`,e.project)},()=>{oq===t&&(aq=null)}},lq=()=>aq,uq=e=>!!e.parentID,dq=(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&&uq(r);){let e=r.parentID;if(!e)break;let t=n.get(e);if(!t)return e;r=t}return r?.id??e},fq=()=>{let e=vr.getState().activeSessions;if(e.length>0)return e;let t=ht();return t.length>0?t:gt()},pq=(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)},mq=e=>[...e.pinned,...e.project],hq=(e,t,n,r)=>{if(e.length===0)return null;let i=pq(e,n,r);return i<0?t>0?e[0]??null:e[e.length-1]??null:e[(i+t+e.length)%e.length]??null},gq=(e,t,n=iq.getState().focus)=>{let r=dq(t,fq()),i=n?.sessionId===t?n:null,a=lq();return a?hq(mq(a),e,r,i):null},_q=(e,t,n=e=>{Y.getState().setCurrentSession(e.sessionId,e.directory)})=>{let r=gq(e,t);return r?(iq.getState().setFocus({scope:r.scope,sessionId:r.sessionId,projectId:r.projectId}),n(r),r):null},vq=.5,yq=.1,bq=`oc.webviewZoomFactor`,xq=e=>Number.isFinite(e)?Math.min(3,Math.max(vq,Math.round(e*100)/100)):1,Sq=()=>{if(typeof window>`u`)return 1;try{let e=window.localStorage.getItem(bq);return e?xq(Number.parseFloat(e)):1}catch{return 1}},Cq=e=>{if(!(typeof window>`u`))try{window.localStorage.setItem(bq,String(e))}catch{}},wq=e=>{let t=xq(e);return typeof document<`u`&&(document.documentElement.style.zoom=t===1?``:String(t)),Cq(t),t},Tq=()=>{if(typeof document>`u`)return 1;let e=document.documentElement.style.zoom;if(!e)return Sq();let t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?xq(t):Sq()},Eq=()=>{if(b())return;let e=Sq();e!==1&&wq(e)},Dq=async()=>{if(b())try{let e=await ee(`desktop_zoom_in`);if(typeof e==`number`&&Number.isFinite(e))return xq(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_in failed, using CSS zoom`,e)}return wq(Tq()+yq)},Oq=async()=>{if(b())try{let e=await ee(`desktop_zoom_out`);if(typeof e==`number`&&Number.isFinite(e))return xq(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_out failed, using CSS zoom`,e)}return wq(Tq()-yq)},kq=async()=>{if(b())try{let e=await ee(`desktop_zoom_reset`);if(typeof e==`number`&&Number.isFinite(e))return xq(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_reset failed, using CSS zoom`,e)}return wq(1)},Aq=9,jq=null,Mq=0,Nq=({pinnedTargets:e,projectTargets:t})=>[...e,...t].slice(0,Aq),Pq=(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},Fq=e=>{let t=++Mq;return jq={targets:e.targets.slice(0,Aq),activate:e.activate},()=>{Mq===t&&(jq=null)}},Iq=e=>{if(!Number.isInteger(e)||e<1||e>Aq)return!1;let t=jq,n=t?.targets[e-1];return!t||!n?!1:(t.activate(n),!0)},Lq=e=>{let t=e.trim();if(!t)return null;let n=Jd.getState(),r=n.createTab(t);return!r||r===`tab-invalid`?null:(n.setActiveTab(t,r),r)},Rq=e=>{let t=e.trim();if(!t)return null;let n=K.getState();return!n.isBottomTerminalOpen&&n.activeMainTab!==`terminal`&&n.setBottomTerminalOpen(!0),Lq(t)},zq=(e,t)=>{let n=e.trim();if(!n)return!1;let r=Jd.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)},Bq=e=>{let t=e.trim();if(!t)return{closed:!1,wasLastTab:!1};let n=Jd.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}},Vq=()=>typeof window>`u`||window.parent===window||!vp(window.location.search)?!1:(window.parent.postMessage({type:hp},window.location.origin),!0),Hq=()=>{let{isMobile:e,closeActiveContextPanelTab:t}=K.getState();if(e)return!1;let n=Ju();return n&&t(n)?!0:b()?(ee(`desktop_close_current_window`).catch(e=>{console.warn(`[keyboard-shortcuts] failed to close current window`,e)}),!0):!1},Uq=({sessionId:e,surfaceKind:t,wiringCanAbort:n,primaryCanAbort:r,pendingSend:i=!1})=>e?i||n?!0:t!==`secondary`&&r:!1,Wq=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)}},Gq=()=>{let e=(0,Q.c)(69),{t}=Wn(),n=Y(Kq),r=Y(qq),i=Y(Jq),a=Y(Yq),o=fo,s=K(Xq),c=K(Zq),l=K(Qq),u=K($q),d=K(eJ),f=K(tJ),p=K(nJ),m=K(rJ),h=K(iJ),g=K(aJ),_=K(oJ),v=K(sJ),y=K(cJ),x=K(lJ),S=K(uJ),C=K(dJ),w=K(fJ),T=K(pJ),E=K(mJ),D=lt(hJ),O=Co(gJ),{themeMode:k,setThemeMode:A}=Tc(),{working:j}=wL(),M=Z.useRef(null),N=Z.useRef(null),P=Z.useRef(null),F=Z.useRef(!1),I=Z.useRef(k),L,R;e[0]===k?(L=e[1],R=e[2]):(L=()=>{I.current=k},R=[k],e[0]=k,e[1]=L,e[2]=R),Z.useEffect(L,R);let z;e[3]===i?z=e[4]:(z=()=>{N.current&&=(clearTimeout(N.current),null),M.current=null,i()},e[3]=i,e[4]=z);let B=z,V;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(V=()=>{P.current&&=(clearTimeout(P.current),null),yh.getState().clear()},e[5]=V):V=e[5];let H=V,U;e[6]===Symbol.for(`react.memo_cache_sentinel`)?(U=()=>{P.current&&=(clearTimeout(P.current),null);let e=yh.getState().arm(vh);P.current=setTimeout(()=>{let{expiresAt:e}=yh.getState();e&&Date.now()>=e&&yh.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]!==B||e[14]!==_||e[15]!==x||e[16]!==m||e[17]!==y||e[18]!==w||e[19]!==d||e[20]!==f||e[21]!==g||e[22]!==v||e[23]!==A||e[24]!==S||e[25]!==E||e[26]!==t||e[27]!==p||e[28]!==s||e[29]!==T||e[30]!==c||e[31]!==C||e[32]!==u||e[33]!==l||e[34]!==j?(W=()=>{let e=e=>ic(e,E),i=e=>$s(e,E),a=_J,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),L=yJ,R=xJ,z=SJ,V=async()=>{let e=DT(),n=e?NT(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;Ha.error(n instanceof Error?n.message:t(`chat.chatInput.toast.compactFailed`))}return}let r=Y.getState().currentSessionId;if(!r)return;let{currentProviderId:i,currentModelId:a}=ao.getState();await Wq({sessionId:r,currentProviderId:i,currentModelId:a,waitForConnectionOrThrow:ga,getAuthoritativeDirectoryForSession:Y.getState().getAuthoritativeDirectoryForSession,summarizeSession:CJ,onCompactFailed:e=>{Ha.error(e instanceof Error?e.message:t(`chat.chatInput.toast.compactFailed`))}})},U=t=>{let r=yh.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&&rc(t,i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),te();return}let r=t.key.toLowerCase();if(r===`escape`){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),H();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(),H();return}let{activeMainTab:a,isModelSelectorOpen:o,isAgentSelectorOpen:s}=K.getState(),c=ET(a)&&!z();if(r===`m`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H(),window.requestAnimationFrame(()=>{y(!o,{instant:!0})});return}if(r===`a`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H(),x(!s,{instant:!0});return}if(r===`n`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H();let r=DT(),i=r?NT(r):null;i?i.shortcut(`new`):(_(`chat`),g(!1),n());return}if(r===`c`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H(),V(),R();return}t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H(),R();return}if(!i||!rc(t,i)||z())return;let{activeMainTab:o}=K.getState();ET(o)&&(t.preventDefault(),t.stopPropagation(),te())},W=()=>yh.getState().pending||F.current,ne=e=>{W()&&e.preventDefault()},re=e=>{W()&&(e.preventDefault(),e.stopPropagation())},ie=t=>{if(a(t.target)){if(!fe()&&rc(t,e(`new_terminal_tab`))){let e=Ju();if(!e||!Lq(e))return;t.preventDefault(),t.stopPropagation();return}if(!fe()&&rc(t,e(`previous_terminal_tab`))){let e=Ju();if(!e||!zq(e,-1))return;t.preventDefault(),t.stopPropagation();return}if(!fe()&&rc(t,e(`next_terminal_tab`))){let e=Ju();if(!e||!zq(e,1))return;t.preventDefault(),t.stopPropagation();return}if(rc(t,e(`close_context_panel_tab`))){let e=Ju();if(!e)return;let{closed:n,wasLastTab:r}=Bq(e);if(!n)return;if(t.preventDefault(),t.stopPropagation(),r){let e=K.getState();e.setBottomTerminalOpen(!1),e.activeMainTab===`terminal`&&e.setActiveMainTab(`chat`)}return}if(rc(t,e(`toggle_terminal`))){let{isMobile:e}=K.getState();if(e)return;t.preventDefault(),t.stopPropagation(),p();return}if(rc(t,e(`toggle_bottom_panel`))){let{isMobile:e}=K.getState();if(e)return;t.preventDefault(),t.stopPropagation(),p();return}if(rc(t,e(`toggle_terminal_expanded`))){let{isMobile:e,isBottomTerminalExpanded:n}=K.getState();if(e)return;t.preventDefault(),t.stopPropagation(),m(!n);return}}},ae=wJ,oe=t=>{if(t.defaultPrevented)return;if(rc(t,e(`close_context_panel_tab`))){(Vq()||Hq())&&(t.preventDefault(),t.stopPropagation());return}if(a(t.target))return;let r=TJ;if(r(t.target)&&t.ctrlKey&&!t.metaKey&&!t.shiftKey&&!t.altKey&&t.key.toLowerCase()===`t`){t.preventDefault(),ae();return}if(rc(t,e(`open_command_palette`))){t.preventDefault(),s();return}if(rc(t,e(`open_timeline_dialog`))){t.preventDefault(),S(!0);return}if(rc(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}=K.getState();if(!n||h||fe()||e!==`chat`||r||i||a||o||s||c||l||u)return;t.preventDefault(),C();return}if(rc(t,e(`open_status`))){t.preventDefault(),eq();return}if(rc(t,e(`open_help`))){t.preventDefault(),c();return}if(b()&&rc(t,e(`new_mini_chat`))){t.preventDefault(),ee(`desktop_open_draft_mini_chat_window`,{directory:D||O?.path||``,projectId:O?.id??null}).catch(EJ);return}let o=rc(t,e(`new_chat`)),x=rc(t,e(`new_chat_worktree`));if(o||x){if(t.preventDefault(),_(`chat`),g(!1),!fe()&&x){gS();return}n();return}if(rc(t,e(`cycle_theme`))){if(t.preventDefault(),Tp()!==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(I.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(hc(t,`in`,e(`zoom_in`))){t.preventDefault(),Dq();return}if(hc(t,`out`,e(`zoom_out`))){t.preventDefault(),Oq();return}if(rc(t,e(`zoom_reset`))){t.preventDefault(),kq();return}if(rc(t,e(`open_settings`))){t.preventDefault();let{isSettingsDialogOpen:e}=K.getState();v(!e);return}if(rc(t,e(`toggle_sidebar`))){t.preventDefault();let{isMobile:e,isSessionSwitcherOpen:n}=K.getState();e?g(!n):l();return}if(rc(t,e(`focus_input`))){t.preventDefault(),document.querySelector(`textarea[data-chat-input="true"]`)?.focus();return}let w=e(`cycle_agent`),E=w&&!w.includes(`shift`)?Ks(`shift+${w}`):``,k=E&&rc(t,E)?-1:+!!rc(t,w);if(k!==0){let{isSettingsDialogOpen:e,isCommandPaletteOpen:n,isHelpDialogOpen:i,isSessionSwitcherOpen:a,isAboutDialogOpen:o,activeMainTab:s}=K.getState();if(e||n||i||a||o||!ET(s)||!r(t.target))return;let c=DT(),l=c?NT(c):null;if(l){t.preventDefault(),l.shortcut(`cycle`,k);return}let u=ao.getState(),d=Ei(u.getVisibleAgents(),u.currentAgentName,k);if(!d)return;t.preventDefault(),u.setAgent(d),K.getState().addRecentAgent(d);let f=Y.getState().currentSessionId;f&&zo.getState().saveSessionAgentSelection(f,d);return}if(i(`toggle_right_sidebar`).some(e=>rc(t,e))){let{isMobile:e}=K.getState();if(e)return;t.preventDefault(),u();return}if(rc(t,e(`open_right_sidebar_git`))){let{isMobile:e}=K.getState();if(e)return;t.preventDefault(),d(!0),f(`git`);return}if(rc(t,e(`open_right_sidebar_files`))){let{isMobile:e}=K.getState();if(e)return;t.preventDefault(),d(!0),f(`files`);return}if(rc(t,e(`cycle_right_sidebar_tab`))){let{isMobile:e,rightSidebarTab:n}=K.getState();if(e)return;let r=WK({hideGit:K.getState().activeMainTab===`git`,showBrowser:lc(ac())}),i=r[(r.indexOf(n)+1)%r.length];t.preventDefault(),d(!0),f(i);return}let j=e=>_q(e,Y.getState().currentSessionId,e=>{_(`chat`),g(!1),Y.getState().setCurrentSession(e.sessionId,e.directory)});if(i(`previous_session`).some(e=>rc(t,e))){t.preventDefault(),j(-1);return}if(i(`next_session`).some(e=>rc(t,e))){t.preventDefault(),j(1);return}for(let n=1;n<=9;n+=1)if(rc(t,e(`switch_tab_${n}`))){Iq(n)&&t.preventDefault();return}if(rc(t,e(`toggle_terminal`))){let{isMobile:e}=K.getState();if(e)return;t.preventDefault(),p();return}if(rc(t,e(`open_new_terminal`))){let{isMobile:e}=K.getState();if(e||fe())return;let n=Ju();if(!n||!Rq(n))return;t.preventDefault();return}if(rc(t,e(`toggle_bottom_panel`))){let{isMobile:e}=K.getState();if(e)return;t.preventDefault(),p();return}if(rc(t,e(`toggle_terminal_expanded`))){let{isMobile:e,isBottomTerminalExpanded:n}=K.getState();if(e)return;t.preventDefault(),m(!n);return}if(rc(t,e(`open_model_selector`))){let{isSettingsDialogOpen:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isAboutDialogOpen:a,activeMainTab:o,isModelSelectorOpen:s}=K.getState();if(e)return;let c=n||r||i||a,l=ET(o);if(c||!l)return;t.preventDefault(),y(!s,{instant:!0});return}if(rc(t,e(`cycle_thinking_variant`))){ae()&&t.preventDefault();return}if(rc(t,e(`cycle_favorite_model_forward`))||rc(t,e(`cycle_favorite_model_backward`))){let{isSettingsDialogOpen:n,isCommandPaletteOpen:r,isHelpDialogOpen:i,isSessionSwitcherOpen:a,isAboutDialogOpen:o,activeMainTab:s,favoriteModels:c,addRecentModel:l}=K.getState();if(n)return;let u=r||i||a||o,d=ET(s);if(u||!d||c.length===0)return;t.preventDefault();let f=c.length,p=rc(t,e(`cycle_favorite_model_forward`))?1:-1,m=DT();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=ao.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}=ao.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(rc(t,e(`expand_input`))){if(h)return;t.preventDefault(),T();return}if(rc(t,e(`toggle_dictation`))){let{activeMainTab:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isSettingsDialogOpen:a}=K.getState();if(!ET(e)||n||r||i||a)return;t.preventDefault(),window.dispatchEvent(new CustomEvent(`openchamber:dictation-toggle`));return}},se=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)||L(),{isSettingsDialogOpen:c,isCommandPaletteOpen:l,isHelpDialogOpen:u,isSessionSwitcherOpen:d,isAboutDialogOpen:f,isMultiRunLauncherOpen:p,isImagePreviewOpen:m,isPromptNavigatorPanelOpen:h}=K.getState();if(n||a||s){B();return}if(h){e.preventDefault(),w(!1),B();return}if(c){e.preventDefault(),v(!1),B();return}if(i){B();return}if(l||u||d||f||p||m){B();return}let g=DT(),_=g?NT(g):null,y=g?.sessionID??Y.getState().currentSessionId,b=!!(y&&Y.getState().pendingSendMessageIDs.get(y));if(!Uq({sessionId:y,surfaceKind:g?.kind,wiringCanAbort:_?.canAbort,primaryCanAbort:j.canAbort,pendingSend:b})){B();return}e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();let x=Date.now(),S=M.current;if(S&&x<S){B(),_?_.abort():(y&&bi(y),o(y??``));return}let C=g?.kind===`secondary`?x+3e3:r(3e3)??x+3e3;M.current=C,N.current&&clearTimeout(N.current);let T=Math.max(C-x,0);N.current=setTimeout(()=>{M.current&&Date.now()>=M.current&&B()},T||0)};return window.addEventListener(`keydown`,U,!0),window.addEventListener(`beforeinput`,ne,!0),window.addEventListener(`compositionstart`,re,!0),window.addEventListener(`compositionupdate`,re,!0),window.addEventListener(`compositionend`,re,!0),window.addEventListener(`keydown`,ie,!0),window.addEventListener(`keydown`,se,!0),window.addEventListener(`keydown`,oe),()=>{window.removeEventListener(`keydown`,U,!0),window.removeEventListener(`beforeinput`,ne,!0),window.removeEventListener(`compositionstart`,re,!0),window.removeEventListener(`compositionupdate`,re,!0),window.removeEventListener(`compositionend`,re,!0),window.removeEventListener(`keydown`,ie,!0),window.removeEventListener(`keydown`,se,!0),window.removeEventListener(`keydown`,oe)}},e[7]=O?.id,e[8]=O?.path,e[9]=r,e[10]=D,e[11]=h,e[12]=n,e[13]=B,e[14]=_,e[15]=x,e[16]=m,e[17]=y,e[18]=w,e[19]=d,e[20]=f,e[21]=g,e[22]=v,e[23]=A,e[24]=S,e[25]=E,e[26]=t,e[27]=p,e[28]=s,e[29]=T,e[30]=c,e[31]=C,e[32]=u,e[33]=l,e[34]=j,e[35]=W):W=e[35];let ne=O?.id,re=O?.path,ie;e[36]!==r||e[37]!==D||e[38]!==a||e[39]!==h||e[40]!==n||e[41]!==B||e[42]!==_||e[43]!==x||e[44]!==m||e[45]!==y||e[46]!==w||e[47]!==d||e[48]!==f||e[49]!==g||e[50]!==v||e[51]!==A||e[52]!==S||e[53]!==E||e[54]!==t||e[55]!==ne||e[56]!==re||e[57]!==p||e[58]!==s||e[59]!==T||e[60]!==c||e[61]!==C||e[62]!==u||e[63]!==l||e[64]!==j?(ie=[n,o,s,c,l,u,d,f,p,m,h,g,_,v,y,x,S,C,w,T,A,j,r,B,te,H,a,D,ne,re,E,t],e[36]=r,e[37]=D,e[38]=a,e[39]=h,e[40]=n,e[41]=B,e[42]=_,e[43]=x,e[44]=m,e[45]=y,e[46]=w,e[47]=d,e[48]=f,e[49]=g,e[50]=v,e[51]=A,e[52]=S,e[53]=E,e[54]=t,e[55]=ne,e[56]=re,e[57]=p,e[58]=s,e[59]=T,e[60]=c,e[61]=C,e[62]=u,e[63]=l,e[64]=j,e[65]=ie):ie=e[65],Z.useEffect(W,ie);let ae,oe;e[66]===B?(ae=e[67],oe=e[68]):(oe=()=>()=>{B(),H()},ae=[B,H],e[66]=B,e[67]=ae,e[68]=oe),Z.useEffect(oe,ae)};function Kq(e){return e.openNewSessionDraft}function qq(e){return e.armAbortPrompt}function Jq(e){return e.clearAbortPrompt}function Yq(e){return e.currentSessionId}function Xq(e){return e.toggleCommandPalette}function Zq(e){return e.toggleHelpDialog}function Qq(e){return e.toggleSidebar}function $q(e){return e.toggleRightSidebar}function eJ(e){return e.setRightSidebarOpen}function tJ(e){return e.setRightSidebarTab}function nJ(e){return e.toggleBottomTerminal}function rJ(e){return e.setBottomTerminalExpanded}function iJ(e){return e.isMobile}function aJ(e){return e.setSessionSwitcherOpen}function oJ(e){return e.setActiveMainTab}function sJ(e){return e.setSettingsDialogOpen}function cJ(e){return e.setModelSelectorOpen}function lJ(e){return e.setAgentSelectorOpen}function uJ(e){return e.setTimelineDialogOpen}function dJ(e){return e.togglePromptNavigatorPanel}function fJ(e){return e.setPromptNavigatorPanelOpen}function pJ(e){return e.toggleExpandedInput}function mJ(e){return e.shortcutOverrides}function hJ(e){return e.currentDirectory}function gJ(e){return e.getActiveProject()}function _J(e){return e instanceof Element&&!!(e.closest(`[data-terminal-view="true"]`)||e.closest(`.terminal-viewport-container`)||e.getAttribute(`data-terminal-hidden-input`)===`true`)}function vJ(e){return e.getClientRects().length>0}function yJ(){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(vJ)}function bJ(){document.querySelector(`textarea[data-chat-input="true"]`)?.focus({preventScroll:!0})}function xJ(){window.requestAnimationFrame(bJ)}function SJ(){let{isSettingsDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isSessionSwitcherOpen:r,isAboutDialogOpen:i}=K.getState();return e||t||n||r||i}function CJ(e,t,n,r){return xt.summarizeSession(e,t,n,r)}function wJ(){let{isSettingsDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isSessionSwitcherOpen:r,isAboutDialogOpen:i,activeMainTab:a}=K.getState();if(e||t||n||r||i||!ET(a))return!1;let o=DT();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=ao.getState();if(s.getCurrentModelVariants().length===0)return!1;s.cycleCurrentVariant();let c=ao.getState().currentVariant,l=Y.getState().currentSessionId,u=ao.getState().currentAgentName,d=ao.getState().currentProviderId,f=ao.getState().currentModelId;return l&&u&&d&&f&&zo.getState().saveAgentModelVariantForSession(l,u,d,f,c),u&&d&&f&&ao.getState().saveAgentModelSelection(u,d,f,c),!0}function TJ(e){return e instanceof HTMLTextAreaElement&&e.getAttribute(`data-chat-input`)===`true`}function EJ(e){console.warn(`[keyboard-shortcuts] failed to open draft mini chat window`,e)}var DJ=3,OJ=(e,t)=>{if(typeof e!=`string`)return t;let n=e.trim().replace(/\s+/g,` `);return n?n.slice(0,48):t},kJ=(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:OJ(e.title,`Session ${r.length+1}`)}),r.length>=DJ))break}return r},AJ=()=>{let e=(0,Q.c)(9),t=Ao(),n=Y(jJ),r;e[0]!==n||e[1]!==t?(r=kJ(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`||!_e())){try{i.length===0?localStorage.removeItem(fc):localStorage.setItem(fc,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]),Z.useEffect(s,c)};function jJ(e){return e.currentSessionId}var MJ=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:`0px`,NJ=(e,t,n,r)=>{e.style.setProperty(`--oc-wco-left-inset`,MJ(t)),e.style.setProperty(`--oc-wco-right-inset`,MJ(n)),e.style.setProperty(`--oc-wco-titlebar-height`,MJ(r))},PJ=()=>{let e=(0,Q.c)(1),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0],Z.useEffect(FJ,t)};function FJ(){if(typeof window>`u`||!_e())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){NJ(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));NJ(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),NJ(e,0,0,0)}}var IJ=null,LJ=e=>{let t=IJ;return IJ=e,()=>{IJ===e&&(IJ=t)}},RJ=()=>({orderByProject:{},pendingProjectIDs:{}}),zJ=(e,t)=>!!(e&&e.length===t.length&&e.every((e,n)=>e===t[n])),BJ=o(),VJ=Ue()(We((e,t)=>({runtimeIdentity:BJ,...RJ(),serverRevisionByProject:{},deferredServerOrderByProject:{},runtimeOrdersByIdentity:{[BJ]:RJ()},activateWorktreeOrderRuntime:t=>e(e=>{if(e.runtimeIdentity===t)return e;let n=e.runtimeOrdersByIdentity[t]??RJ();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=zJ(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&&IJ?.(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(zJ(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&&!zJ(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:{[BJ]:{orderByProject:t.orderByProject??{},pendingProjectIDs:t.pendingProjectIDs??{}}}}},merge:(e,t)=>{let n=e.runtimeOrdersByIdentity??t.runtimeOrdersByIdentity,r=n[t.runtimeIdentity]??RJ();return{...t,runtimeOrdersByIdentity:n,orderByProject:r.orderByProject,pendingProjectIDs:r.pendingProjectIDs}}})),HJ=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``),UJ=(e,t)=>{if(!e||e.length===0)return t;let n=new Map(e.map((e,t)=>[HJ(e),t]));return t.map((e,t)=>({worktree:e,index:t})).sort((e,t)=>(n.get(HJ(e.worktree.path))??2**53-1)-(n.get(HJ(t.worktree.path))??2**53-1)||e.index-t.index).map(e=>e.worktree)},WJ=3e4,GJ=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||`/`,KJ=e=>e instanceof pr?e.status===501?`unsupported`:e.status>=400&&e.status<500&&e.status!==408&&e.status!==429&&e.code!==`revision_conflict`?`permanent`:`retry`:`retry`,qJ=(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})}),JJ=(e,t)=>e.then(e=>{if(t?.aborted)throw new DOMException(`Aborted`,`AbortError`);return e}),YJ={fetchSnapshot:e=>JJ(Ro(V),e),refreshSnapshot:e=>JJ(Oi(V),e),fetchOrder:Mi,setOrder:Tr,waitInvalidation:yr,captureRuntime:()=>({transportIdentity:o(),generation:c()}),isCurrent:e=>e.transportIdentity===o()&&e.generation===c(),sleep:qJ,createRequestID:()=>typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`worktree-order-${Date.now()}-${Math.random().toString(36).slice(2)}`},XJ=new Map,ZJ=()=>{for(let e of XJ.values())e.controller.abort();XJ.clear()},QJ=(e,t,n,r=YJ)=>{XJ.get(e)?.controller.abort();let i={projectDirectory:GJ(t),orderedPaths:[...n],capture:r.captureRuntime(),controller:new AbortController,backoffMs:500,running:!1};XJ.set(e,i),$J(e,r)},$J=async(e,t=YJ)=>{let n=XJ.get(e);if(!(!n||n.running)){n.running=!0;try{for(;;){let n=XJ.get(e);if(!n||!t.isCurrent(n.capture)||n.controller.signal.aborted)return;let r=VJ.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)||XJ.get(e)!==n)return;let a=i.worktreeOrder??{projectDirectory:n.projectDirectory,orderedPaths:n.orderedPaths,revision:i.revision};VJ.getState().setServerRevision(e,a.revision),VJ.getState().resolvePendingWorktreeOrder(e,a.revision),XJ.delete(e);return}catch(r){if(n.controller.signal.aborted||!t.isCurrent(n.capture)||XJ.get(e)!==n)return;if(r instanceof pr&&r.code===`revision_conflict`)try{let r=await t.fetchOrder(n.projectDirectory,n.controller.signal);if(XJ.get(e)!==n||!t.isCurrent(n.capture))return;VJ.getState().applyServerWorktreeOrder(e,r.orderedPaths,r.revision),n.expectedRevision=void 0,n.requestID=void 0,n.backoffMs=500;continue}catch(e){if(KJ(e)!==`retry`)return}else if(KJ(r)!==`retry`)return;if(await t.sleep(n.backoffMs,n.controller.signal).catch(()=>{}),n.backoffMs=Math.min(n.backoffMs*2,WJ),n.controller.signal.aborted)return}}}finally{XJ.get(e)===n&&(!t.isCurrent(n.capture)||n.controller.signal.aborted)&&XJ.delete(e),XJ.get(e)===n&&(n.running=!1)}}},eY=(e,t,n,r)=>{let i=new Map(t.map(e=>[GJ(e.path),e.id]));for(let t of e){let e=i.get(GJ(t.projectDirectory));e&&r.isCurrent(n)&&VJ.getState().applyServerWorktreeOrder(e,t.orderedPaths,t.revision)}},tY=(e,t=YJ)=>{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();eY(r.worktreeOrders,o,a,t);let s=new Set(r.worktreeOrders.map(e=>GJ(e.projectDirectory)));for(let e of o){let n=VJ.getState(),r=n.orderByProject[e.id];n.pendingProjectIDs[e.id]?QJ(e.id,e.path,r??[],t):r?.length&&!s.has(GJ(e.path))&&(n.markPendingWorktreeOrder(e.id),QJ(e.id,e.path,r,t))}break}catch(e){if(KJ(e)!==`retry`)return;await t.sleep(r,i).catch(()=>{}),r=Math.min(r*2,WJ)}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,eY(s.worktreeOrders,e(),a,t),r=500}catch(e){if(KJ(e)!==`retry`)return;await t.sleep(r,i).catch(()=>{}),r=Math.min(r*2,WJ)}})()},stop:r}},nY=()=>{let e=(0,Q.c)(2),t=Co(iY),n;e[0]===t?n=e[1]:(n=[t],e[0]=t,e[1]=n),Z.useEffect(sY,n)};function rY(e){return[e.id,GJ(e.path)]}function iY(e){return JSON.stringify(e.projects.map(rY))}function aY(e,t,n){return QJ(e,t,n)}function oY(){return Co.getState().projects}function sY(){let e=o();VJ.getState().activateWorktreeOrderRuntime(e);let t=LJ(aY),n=tY(oY);n.start();let r=i(e=>{l(e)&&(ZJ(),VJ.getState().activateWorktreeOrderRuntime(o()),n.start())});return()=>{t(),r(),n.stop(),ZJ()}}var cY=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||`/`,lY=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=cY(t);return e.getProjects().find(e=>cY(e.path)===n)},g=(n,i=150)=>{let s=cY(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(cY(e));if(e.needsSessionSync)for(let t of i.worktrees){let n=cY(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])=>cY(e)===n||t.some(e=>cY(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(cY(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=cY(n.path),i=t.get(r)?.some(t=>cY(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${cY(e.path)}`).sort().join(`
|
|
6605
6605
|
`),m.push(e.subscribeProjects(()=>{let t=e.getProjects().map(e=>`${e.id}\u0000${cY(e.path)}`).sort().join(`
|
|
6606
6606
|
`);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}},uY=null,dY=0,fY=()=>(uY||=lY({isVSCode:fe,getProjects:()=>Co.getState().projects,getCatalog:()=>Y.getState().availableWorktreesByProject,getActiveDirectories:()=>{let e=vr.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=>!vr.getState().loadedDirectories.has(cY(e)),refresh:bs,syncAdded:e=>wr(e,vr.getState().activeSessions),subscribeProjects:e=>Co.subscribe(e),subscribeCatalog:e=>Y.subscribe((t,n)=>{t.availableWorktreesByProject!==n.availableWorktreesByProject&&e()}),subscribeSessions:e=>vr.subscribe((t,n)=>{(t.activeSessions!==n.activeSessions||t.cachedDirectories!==n.cachedDirectories)&&e()}),subscribeEvents:va,subscribeRuntime:e=>i(t=>e(l(t))),generation:c,setTimer:(e,t)=>globalThis.setTimeout(e,t),clearTimer:e=>globalThis.clearTimeout(e)}),dY+=1,uY.start(),()=>{dY=Math.max(0,dY-1),dY===0&&uY?.stop()}),pY=`openchamber:mini-chat-presence`,mY=()=>{let e=Ih(),t=Z.useRef(e.optimistic.add),n=Z.useRef(e.optimistic.remove),r=Z.useRef(e.optimistic.confirm);return t.current=e.optimistic.add,n.current=e.optimistic.remove,r.current=e.optimistic.confirm,Z.useEffect(()=>{pa(e=>t.current(e),e=>n.current(e),e=>r.current(e))},[]),Z.useEffect(()=>fY(),[]),null},hY=()=>{let e=(0,Q.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0],Z.useEffect(xY,t),null};function gY(e){let t=(0,Q.c)(4),{embeddedBackgroundWorkEnabled:n}=e,r;t[0]===n?r=t[1]:(r={enabled:n,autoRun:!1},t[0]=n,t[1]=r),bc(r);let i=Z.useSyncExternalStore(Bi,Ni,Ni);Wr(n&&i===`legacy-enabled`),ar();let a;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=[],t[2]=a):a=t[2],Z.useEffect(_Y,a);let o;return t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,$.jsx)(mY,{}),t[3]=o):o=t[3],o}function _Y(){let e=jo(),t=Ri();e.start(),t.start();let n=Vo(e);return()=>{n(),t.stop(),e.stop()}}function vY(e){let t=(0,Q.c)(6),{embeddedBackgroundWorkEnabled:n}=e;AJ(),PJ(),Gq(),nY();let r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0],Z.useEffect(yY,r);let i;t[1]===n?i=t[2]:(i=(0,$.jsx)(gY,{embeddedBackgroundWorkEnabled:n}),t[1]=n,t[2]=i);let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(hY,{}),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 yY(){Eq()}function bY(e){let t=e.data;if(t?.type!==`mini-chat-session-presence`||!t.sessionId||!t.directory)return;let n=t.viewed!==!1;cr(t.directory,t.sessionId,n),n&&Ir(t.sessionId)}function xY(){if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(pY);return e.onmessage=bY,()=>e.close()}var SY=new Set,CY=new Map,wY=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace(`%40`,`@`).replace(`%2F`,`/`)}/files/${e.filePrefix}-latin-${t}-normal.woff2`,TY=(e,t)=>{let n=`${e.family}:${t}`;if(SY.has(n))return Promise.resolve();let r=CY.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(${wY(e,t)}) format('woff2')`,{style:`normal`,weight:String(t),display:`swap`});document.fonts.add(i);let a=i.load().then(()=>{SY.add(n)}).catch(n=>{document.fonts.delete(i),console.warn(`Failed to load font: ${e.family} ${t}`,n)}).finally(()=>{CY.delete(n)});return CY.set(n,a),a},EY=e=>e?Promise.all(e.weights.map(t=>TY(e,t))).then(()=>void 0):Promise.resolve(),DY=e=>EY(vn[e]?.source),OY=e=>EY(_n[e]?.source),kY={family:`Syne`,packageName:`@fontsource/syne`,filePrefix:`syne`,weights:[700]},AY=()=>EY(kY);function jY(){let e=(0,Q.c)(4),{uiFont:t,monoFont:n}=Yd(),r,i;e[0]!==n||e[1]!==t?(r=()=>{if(typeof document>`u`)return;let e=document.documentElement,r=vn[t]?.stack??vn.system.stack,i=_n[n]?.stack??_n[`system-mono`].stack;DY(t),OY(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]),Z.useEffect(r,i)}export{OS as $,xU as A,_p as At,NO as B,Zd as Bt,WK as C,tm as Ct,QG as D,Bp as Dt,FK as E,Hp as Et,sP as F,Qf as Ft,Ww as G,WD as H,oP as I,Ef as It,Bw as J,Uw as K,lP as L,nf as Lt,VV as M,Cp as Mt,bR as N,op as Nt,rW as O,hp as Ot,cI as P,ap as Pt,TS as Q,eP as R,$d as Rt,GK as S,am as St,zK as T,Xp as Tt,nT as U,IO as V,Kw as W,aC as X,zw as Y,JS as Z,rq as _,ig as _t,gY as a,eS as at,iq as b,Em as bt,Rq as c,Px as ct,Fq as d,Zb as dt,kS as et,kq as f,Hy as ft,cq as g,Dg as gt,_q as h,my as ht,vY as i,gS as it,QH as j,xp as jt,eW as k,gp as kt,Nq as l,Ox as lt,Oq as m,Sy as mt,AY as n,jS as nt,UJ as o,tS as ot,Dq as p,xy as pt,Gw as q,DY as r,DS as rt,VJ as s,Fx as st,jY as t,ES as tt,Pq as u,Jb as ut,nq as v,Hh as vt,UK as w,em as wt,eq as x,ym as xt,tq as y,Ih as yt,DN as z,tf as zt};
|