@openchambery/web 1.19.7-beta.21 → 1.19.7-beta.22

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.
Files changed (38) hide show
  1. package/dist/assets/{AssistantView-sV1PVQiM.js → AssistantView-CWWBbBFK.js} +1 -1
  2. package/dist/assets/{DiagramView-D2hqP5VV.js → DiagramView-D31BqN_E.js} +1 -1
  3. package/dist/assets/{MarkdownRenderer-x091Z--3.js → MarkdownRenderer-DayesgSP.js} +2 -2
  4. package/dist/assets/{MarkdownRendererImpl-DML8BSro.js → MarkdownRendererImpl-QFNxMPzf.js} +1 -1
  5. package/dist/assets/{MarkstreamRendererImpl-BK-HM2k3.js → MarkstreamRendererImpl-BQv6Uaiz.js} +1 -1
  6. package/dist/assets/{MobileDetailNavigation-DcxkWiks.js → MobileDetailNavigation-NfSgzdcm.js} +1 -1
  7. package/dist/assets/{MobileShareBridge-TAGcOiyb.js → MobileShareBridge-DeTlirad.js} +1 -1
  8. package/dist/assets/{MobileSurface-zqlZzEFQ.js → MobileSurface-Dn2m2j6W.js} +1 -1
  9. package/dist/assets/{MultiRunWindow-iH1d9S14.js → MultiRunWindow-Cgib9eyw.js} +1 -1
  10. package/dist/assets/{SettingsView-CzW23DZA.js → SettingsView-C9RWio_j.js} +10 -10
  11. package/dist/assets/{SettingsWindow-DZXCWZid.js → SettingsWindow-BNRKLcRY.js} +1 -1
  12. package/dist/assets/{TerminalView-pU0wpD8s.js → TerminalView-D8Yncxaz.js} +1 -1
  13. package/dist/assets/{ToolOutputDialog-Bt7JChFG.js → ToolOutputDialog-C7cKReps.js} +1 -1
  14. package/dist/assets/{appThemeRegistry-BI7WR2Wo.js → appThemeRegistry-CgqQtWC4.js} +1 -1
  15. package/dist/assets/{gitApi-CeFszLvk.js → gitApi-Dxz3xwNw.js} +1 -1
  16. package/dist/assets/{insertionBoundaries-DDJNusn2.js → insertionBoundaries-ChFLgDUk.js} +1 -1
  17. package/dist/assets/{main-CjnOsKDL.js → main-BJXPFVHt.js} +4 -4
  18. package/dist/assets/{main-j-Ij13jc.js → main-DCo2l5VZ.js} +2 -2
  19. package/dist/assets/{miniChat-DgxavREE.js → miniChat-B5UVU_Mb.js} +2 -2
  20. package/dist/assets/{mobile-C0rwPMPM.js → mobile-BqjS1dv6.js} +2 -2
  21. package/dist/assets/{multirun-ot7-bKg7.js → multirun-M_Me-_4l.js} +1 -1
  22. package/dist/assets/{projectMeta-3yOEc0oI.js → projectMeta-CPkhOD4P.js} +1 -1
  23. package/dist/assets/{renderElectronMiniChatApp-BPNvFA_N.js → renderElectronMiniChatApp-Cdh5V0yR.js} +2 -2
  24. package/dist/assets/{renderMobileApp-CNog29Xy.js → renderMobileApp-Cg-ElUGy.js} +4 -4
  25. package/dist/assets/{runtimeConfig-D28kNEYO.js → runtimeConfig-BKoKWlKL.js} +1 -1
  26. package/dist/assets/{runtimeEndpointReset-CorvFIRk.js → runtimeEndpointReset-B83TIZZ3.js} +1 -1
  27. package/dist/assets/{sessionLookup-CbatbQf7.js → sessionLookup-T_RCkXuF.js} +1 -1
  28. package/dist/assets/{src-Af9cMFKF.css → src-CIorwNis.css} +1 -1
  29. package/dist/assets/{useAppFontEffects-CDpeZWK4.js → useAppFontEffects-P8YxQpca.js} +7 -7
  30. package/dist/assets/{useDesktopWindowControlsLayout-D-xPByG0.js → useDesktopWindowControlsLayout-DWs0P-Nn.js} +1 -1
  31. package/dist/assets/{useEffectiveDirectory-Dp-tez_r.js → useEffectiveDirectory-DKaOxQUi.js} +1 -1
  32. package/dist/assets/{useMobileNavigationStore-DE1Pe9A9.js → useMobileNavigationStore-C1gtZTkJ.js} +1 -1
  33. package/dist/assets/{useSessionAutoCleanup-jNJ_WC38.js → useSessionAutoCleanup-nycHB0Ra.js} +1 -1
  34. package/dist/assets/{useWorkerHighlightedLines-MDnGj3yv.js → useWorkerHighlightedLines-DyJgEWoO.js} +1 -1
  35. package/dist/index.html +3 -3
  36. package/dist/mini-chat.html +3 -3
  37. package/dist/mobile.html +3 -3
  38. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ToolOutputDialog-Bt7JChFG.js","assets/rolldown-runtime-C0FnF6B9.js","assets/useUIStore-CqqO11ZI.js","assets/vendor-zustand-B4dlGEM2.js","assets/vendor-base-ui-CnHfUmDN.js","assets/persistence-CSZp1CNB.js","assets/vendor-pathe-vBmvQE8f.js","assets/vendor-react-DLPElpoQ.js","assets/vendor-tanstack-query-core-BWz0ose6.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-DDoDDyM9.js","assets/vendor-lodash-es-DfLbG5Af.js","assets/vendor-js-cookie-hSOiFTtX.js","assets/clipboard-BXxLshVq.js","assets/store-BDFdnk6l.js","assets/dialog-BkhHBTd4.js","assets/utils-B0mQXN9L.js","assets/vendor-class-variance-authority-BLUaYARZ.js","assets/vendor-tailwind-merge-BicNWLTg.js","assets/Icon-4My8YZwt.js","assets/button-Or0daT9o.js","assets/useThemeSystem-DMzWVJaW.js","assets/markdownTheme-CVS01wHf.js","assets/path-utils-jGozTg9d.js","assets/appThemeRegistry-BI7WR2Wo.js","assets/platform-CenlWqxu.js","assets/vendor-opencode-sdk-C07HQypa.js","assets/useMobileNavigationStore-DE1Pe9A9.js","assets/vendor-tanstack-react-query-D7pys_c9.js","assets/vendor-sonner-DVzioF3d.js","assets/useAssistantUIStore-BHacrxe_.js","assets/vendor-fuse.js-DB5wDJbI.js","assets/MarkdownRenderer-x091Z--3.js","assets/MarkdownLoadingSkeleton-Vezjvk9B.js","assets/markdownHeightCache-CvUyZT4q.js","assets/toolHelpers-DEvVP9U0.js","assets/useEffectiveDirectory-Dp-tez_r.js","assets/useWorkerHighlightedLines-MDnGj3yv.js","assets/tooltip-BSrJYYYc.js","assets/vendor-tanstack-react-virtual-tlDgH6PG.js","assets/markdown-worker-BuveaH3O.js","assets/vendor-capacitor-app-PzT84wSx.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,C as n,E as r,J as i,O as a,P as o,T as s,U as c,V as l,d as u,g as d,h as f,j as p,m,s as h,t as g,v as _,w as v,y}from"./useUIStore-CqqO11ZI.js";import{$ as b,$t as x,B as S,C,Ct as w,Dt as T,Ft as E,G as D,I as O,J as k,K as A,M as j,Mt as M,N,Q as P,R as F,S as I,T as L,U as R,V as z,W as B,Wt as V,Xt as H,Y as ee,Yt as U,Z as te,Zt as W,_ as ne,at as G,b as K,c as re,ct as ie,d as ae,en as oe,et as se,ft as ce,g as le,h as ue,it as de,j as fe,kn as pe,lt as me,m as he,mt as ge,n as _e,nt as ve,ot as ye,pt as be,q as xe,qt as Se,r as Ce,st as we,t as Te,u as Ee,ut as De,v as Oe,wt as ke,x as Ae,xn as je,y as Me,yt as Ne,z as Pe}from"./persistence-CSZp1CNB.js";import{_ as Fe,c as Ie,d as Le,f as Re,h as ze,i as Be,l as Ve,m as He,n as Ue,o as We,p as Ge,r as Ke,s as qe}from"./desktopHosts-BzSE0sK7.js";import{r as Je}from"./desktopRelayRestore-BaKjk1kQ.js";import{a as Ye,i as Xe,r as Ze,t as Qe}from"./vendor-zustand-B4dlGEM2.js";import{c as $e,d as et,f as tt,l as nt,nt as rt,rt as it,tt as at,u as ot}from"./vendor-base-ui-CnHfUmDN.js";import{At as st,Bt as ct,Ct as lt,Gt as ut,Ht as dt,Jt as ft,Kt as pt,Nt as mt,Ot as ht,Pt as gt,Rt as _t,St as vt,Ut as yt,Wt as bt,Yt as xt,jt as St,kt as Ct,n as wt,t as Tt,zt as Et}from"./platform-CenlWqxu.js";import{a as Dt,n as Ot,o as kt}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{n as At}from"./vendor-react-DLPElpoQ.js";import{c as jt,i as Mt,n as Nt,s as Pt,t as Ft}from"./vendor-tanstack-react-query-D7pys_c9.js";import{B as It,R as Lt,V as Rt,c as zt}from"./vendor-codemirror-autocomplete-DHomsvW7.js";import{i as Bt,u as Vt}from"./vendor-pierre-diffs-DX7XTPG3.js";import{t as Ht}from"./vendor-sonner-DVzioF3d.js";import{a as Ut,d as Wt,i as Gt,l as Kt,n as q,o as qt,r as Jt,u as Yt}from"./vendor-reactuses-core-DDoDDyM9.js";import{c as Xt,n as Zt,r as Qt,s as $t,t as en}from"./clipboard-BXxLshVq.js";import{i as tn,t as nn}from"./store-BDFdnk6l.js";import{$ as rn,$a as an,$i as on,$n as sn,$r as cn,A as ln,Ai as un,Ar as dn,At as fn,B as pn,Ba as mn,Br as hn,C as gn,Ca as _n,Cr as vn,Ct as yn,D as bn,Da as xn,Di as Sn,Dn as Cn,Do as wn,Dr as Tn,Dt as En,E as Dn,Ei as On,En as kn,Er as An,Et as jn,F as Mn,Fa as Nn,Fi as Pn,Fn,Fr as In,Ft as Ln,G as Rn,Gt as zn,H as Bn,Ha as Vn,Hr as Hn,Ht as Un,I as Wn,Ia as Gn,Ii as Kn,In as qn,Ir as Jn,It as Yn,J as Xn,Ji as Zn,Jr as Qn,K as $n,Kr as er,Kt as tr,L as nr,La as rr,Li as ir,Ln as ar,Lr as or,Lt as sr,M as cr,Mi as lr,Mr as ur,Mt as dr,N as fr,Ni as pr,O as mr,Oi as hr,On as gr,Oo as _r,Or as vr,Ot as yr,P as br,Pi as xr,Pr as Sr,Q as Cr,Qi as wr,Qn as Tr,Qr as Er,Qt as Dr,R as Or,Ra as kr,Ri as Ar,Rr as jr,Si as Mr,Sn as Nr,Sr as Pr,St as Fr,T as Ir,Ta as Lr,Ti as Rr,Tn as zr,Tt as Br,U as Vr,Ua as Hr,Ui as Ur,Ut as Wr,V as Gr,Va as Kr,Vr as qr,W as Jr,Wa as Yr,Wr as Xr,Wt as Zr,X as Qr,Xa as $r,Xi as ei,Xn as ti,Xr as ni,Xt as ri,Y as ii,Ya as ai,Yi as oi,Yr as si,Yt as ci,Z as li,Zi as ui,Zn as di,Zt as fi,_i as pi,_t as mi,a as hi,aa as gi,ai as _i,b as vi,ba as yi,bi,br as xi,bt as Si,c as J,ca as Ci,ci as wi,cn as Ti,d as Ei,da as Di,di as Oi,dn as ki,dr as Ai,en as ji,et as Mi,fa as Ni,fi as Pi,fn as Fi,ft as Ii,ga as Li,gi as Ri,gn as zi,gt as Bi,h as Vi,ha as Hi,hi as Ui,hn as Wi,ho as Gi,ht as Ki,i as qi,ii as Ji,in as Yi,it as Xi,j as Zi,ja as Qi,ji as $i,jt as ea,k as ta,ki as na,kn as ra,kt as ia,la as aa,li as oa,ln as sa,ma as ca,mi as la,mn as ua,mo as da,mr as fa,mt as pa,n as ma,na as ha,ni as ga,nn as _a,nt as va,on as ya,p as ba,pi as xa,pn as Sa,pt as Ca,q as wa,qi as Ta,qr as Ea,ra as Da,ri as Oa,rn as ka,rt as Aa,sa as ja,si as Ma,sn as Na,ta as Pa,tn as Fa,tt as Ia,ua as La,ui as Ra,un as za,ur as Ba,ut as Va,va as Ha,vi as Ua,vt as Wa,w as Ga,wa as Ka,wn as qa,wo as Ja,wt as Ya,x as Xa,xi as Za,xn as Qa,xr as $a,xt as eo,yi as to,yt as no,z as ro,za as io,zi as ao,zn as oo,zt as so}from"./useMobileNavigationStore-DE1Pe9A9.js";import{a as co,i as lo,l as uo,n as fo,o as po,r as mo,s as ho,t as go}from"./dialog-BkhHBTd4.js";import{n as _o,t as Y}from"./utils-B0mQXN9L.js";import{t as vo}from"./AgentAvatar-DI2zs2WH.js";import{n as X}from"./Icon-4My8YZwt.js";import{t as yo}from"./button-Or0daT9o.js";import{E as bo,n as xo}from"./gitApi-CeFszLvk.js";import{a as So}from"./vendor-simplewebauthn-browser-Dwhcdg_5.js";import{C as Co,D as wo,H as To,J as Eo,O as Do,S as Oo,U as ko,Y as Ao,Z as jo,_ as Mo,a as No,b as Po,f as Fo,h as Io,i as Lo,k as Ro,l as zo,m as Bo,n as Vo,o as Ho,q as Uo,s as Wo,u as Go,w as Ko,x as qo,y as Jo}from"./projectMeta-3yOEc0oI.js";import{t as Yo}from"./input-BUsGnzwe.js";import{i as Xo,n as Zo,t as Qo}from"./tooltip-BSrJYYYc.js";import{A as $o,B as es,D as ts,E as ns,F as rs,H as is,I as as,J as os,Mt as ss,Nt as cs,O as ls,R as us,T as ds,Tt as fs,U as ps,_ as ms,dt as hs,et as gs,ft as _s,g as vs,h as ys,ht as bs,j as xs,jt as Ss,k as Cs,mt as ws,n as Ts,nt as Es,ot as Ds,p as Os,pt as ks,rt as As,st as js,t as Ms,tt as Ns,ut as Ps,v as Fs,vt as Is,w as Ls,xt as Rs,yt as zs,z as Bs}from"./useSessionAutoCleanup-jNJ_WC38.js";import{n as Vs,r as Hs,t as Us}from"./useThemeSystem-DMzWVJaW.js";import{i as Ws,t as Gs}from"./OverlayScrollbar-BZB21Yp_.js";import{_ as Ks,a as qs,d as Js,f as Ys,g as Xs,h as Zs,i as Qs,l as $s,m as ec,n as tc,p as nc,u as rc}from"./markdownTheme-CVS01wHf.js";import{n as ic,r as ac,t as oc}from"./useRuntimeAPIs-DSLXJybW.js";import{A as sc,B as cc,C as lc,D as uc,E as dc,F as fc,H as pc,I as mc,L as hc,M as gc,N as _c,O as vc,R as yc,S as bc,T as xc,U as Sc,V as Cc,a as wc,b as Tc,c as Ec,f as Dc,i as Oc,j as kc,k as Ac,l as jc,m as Mc,n as Nc,o as Pc,p as Fc,r as Ic,s as Lc,t as Rc,u as zc,w as Bc,x as Vc,z as Hc}from"./insertionBoundaries-DDJNusn2.js";import{C as Uc,D as Wc,E as Gc,M as Kc,O as qc,S as Jc,T as Yc,_ as Xc,b as Zc,c as Qc,d as $c,f as el,g as tl,h as nl,i as rl,k as il,l as al,m as ol,o as sl,p as cl,s as ll,t as ul,u as dl,v as fl,w as pl,x as ml,y as hl}from"./appThemeRegistry-BI7WR2Wo.js";import{a as gl,n as _l,o as vl,r as yl,t as bl}from"./MarkdownRenderer-x091Z--3.js";import{n as xl,r as Sl}from"./textarea-CIO34TZz.js";import{_ as Cl,a as wl,c as Tl,g as El,l as Dl,o as Ol,t as kl,v as Al,y as jl}from"./vendor-dnd-kit-core-CvWxUPdb.js";import{i as Ml,n as Nl,o as Pl,s as Fl,t as Il}from"./vendor-dnd-kit-sortable-hHdP9lLb.js";import{a as Ll,n as Rl,t as zl}from"./url-CE_gAfNa.js";import{a as Bl,i as Vl,l as Hl}from"./toolHelpers-DEvVP9U0.js";import{n as Ul,t as Wl}from"./useEffectiveDirectory-Dp-tez_r.js";import{a as Gl,i as Kl,l as ql,n as Jl,o as Yl,r as Xl,s as Zl,t as Ql,u as $l}from"./FadeInOnReveal-BWJcUp5P.js";import{a as eu,i as tu,n as nu,o as ru,t as iu}from"./path-utils-jGozTg9d.js";import{A as au,C as ou,D as su,E as cu,M as lu,O as uu,S as du,T as fu,a as pu,b as mu,c as hu,g as gu,h as _u,i as vu,j as yu,k as bu,o as xu,p as Su,r as Cu,s as wu,t as Tu,v as Eu,w as Du,x as Ou,y as ku}from"./useWorkerHighlightedLines-MDnGj3yv.js";import{a as Au,c as ju,o as Mu,s as Nu,u as Pu}from"./sessionChangeSummary-CX2MJIkc.js";import{t as Fu}from"./vendor-cmdk-CeAGfrLo.js";import{t as Iu}from"./sortable-tabs-strip-C5gGnikj.js";import{n as Lu}from"./MarkdownLoadingSkeleton-Vezjvk9B.js";import{n as Ru,t as zu}from"./vendor-tanstack-react-virtual-tlDgH6PG.js";import{i as Bu}from"./markdownHeightCache-CvUyZT4q.js";import{t as Vu}from"./outsideFileGrants-BB4GPvCq.js";import{i as Hu,t as Uu}from"./vendor-framer-motion-DFy_BSVd.js";import{t as Wu}from"./vendor-legendapp-list-WE32lwNk.js";import{n as Gu,t as Ku}from"./useFontPreferences-BxOHKuVw.js";typeof window<`u`&&(window.__opencodeDebug={getLastAssistantMessage(){let e=J.getState().currentSessionId;if(!e)return null;let t=Pa(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=(ha(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:(ha(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=J.getState().currentSessionId;if(!t)return[];let n=Pa(t);return`${n.length}`,n.forEach((e,t)=>{let n=ha(e.id)||[];`${t}${e.role}${e.id}${n.length}`}),e?this.truncateMessages(n):n},async getAppStatus(){let e=lt.getState(),t=J.getState(),n=Gi.getState(),r=e.currentDirectory||null,i=mt.getDirectory()??null,a=Da(),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=je(),u=typeof window<`u`&&!!window.__OPENCHAMBER_ELECTRON__,d=async e=>{try{return await e.json()}catch{return null}},f=async e=>{try{return await e.text()}catch{return null}},p=async e=>{try{let t=await pe(e);return t.ok?await d(t):{status:t.status}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},m=null,h=null,g=null,_=null;try{let e=await mt.getSdkClient().path.get(r?{directory:r}:void 0);m=e.error?{error:e.error}:e.data}catch(e){m={error:e instanceof Error?e.message:String(e)}}try{let e=await mt.getSdkClient().project.current(r?{directory:r}:void 0);h=e.error?{error:e.error}:e.data}catch(e){h={error:e instanceof Error?e.message:String(e)}}g=await p(`/api/config/settings`);try{let e=await pe(`/api/health`),t=e.headers.get(`content-type`)||``,n=await f(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}_={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){_={error:e instanceof Error?e.message:String(e)}}let v={isGitRepo:null};if(r)try{v.isGitRepo=await xo(r)}catch(e){v={isGitRepo:null,error:e instanceof Error?e.message:String(e)}}let y=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:m?.directory||m?.worktree||i,homeDirectory:e.homeDirectory||null,isHomeReady:e.isHomeReady,hasPersistedDirectory:e.hasPersistedDirectory,isSwitchingDirectory:e.isSwitchingDirectory},projects:{total:n.projects.length,activeProjectId:n.activeProjectId,samples:y},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:v,localStorage:c,opencode:{pathInfo:m,projectInfo:h,health:_},openchamber:{settingsInfo:g}}},async buildDiagnosticsReport(){let e=await this.getAppStatus();return JSON.stringify(e,null,2)},async copyTextToClipboard(e){return en(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=J.getState(),t=qa.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=J.getState().currentSessionId;if(!e)return[];let t=Pa(e).filter(e=>e.role===`assistant`).filter(e=>{let t=ha(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=ha(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=J.getState().currentSessionId;if(!i)return{summary:null,rows:[]};let a=Pa(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=ha(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=J.getState().currentSessionId;if(!e)return null;let t=Pa(e).filter(e=>e.role===`assistant`);if(t.length===0)return null;let n=t[t.length-1],r=(ha(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=qa.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}}},ht(),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(it(),1),Q=At(),qu=async()=>{if(typeof window>`u`)return;let e=null;try{e=M(`lastDirectory`)}catch(e){console.warn(`Failed to read saved directory preferences:`,e)}e&&!x()&&lt.getState().setDirectory(e,{showOverlay:!1})},Ju=new Map,Yu=e=>Ju.get(e)??null,Xu=({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:i},a={})=>{let o=Ju.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 Ju.set(e,s),s},Zu=async({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,startWatchers:i,onError:a})=>{await Xu({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:a})&&i()},Qu=(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 $u(e){return!e||e===`idle`?null:e===`ready`?`ok`:e===`error`?`unreachable`:`auth`}function ed(e,t){let n=e.via===`relay`;return t?n:!n}function td(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?$u(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||ed(o,a))&&(u=Math.max(0,Math.round(o.latencyMs))),{statusKind:c,showViaRelay:l,latencyMs:u}}var $=rt(),nd=`local`,rd=9e4,id=`SSH connection cancelled`,ad=e=>Je(e),od={},sd=e=>{let t=Ge(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}},cd=()=>typeof window>`u`?``:window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,ld=async()=>W()?We().catch(()=>``):``,ud=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`,dd=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`,fd=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,pd=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,md=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`,hd=e=>new Promise(t=>window.setTimeout(t,e)),gd=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`}},_d=async()=>{let e=await fs().catch(()=>[]),t={};for(let n of e)t[n.id]=n;return t},vd=async(e,t,n,r)=>{let i=Date.now()+t;for(;Date.now()<i;){if(r?.())throw Error(id);let t=(await fs(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 hd(700)}throw r?.()?Error(id):Error(`Timed out waiting for SSH connection`)},yd=e=>({id:nd,label:`Local`,url:e||cd()}),bd=e=>{let t=typeof window>`u`?``:window.location.href,r=e.find(e=>e.id===nd)?.url||cd(),i=n(),a=Ge(r)||r,o=Ge(t)||t,c=s(),l=e.find(e=>e.relay&&ad(e)===c);if(l)return{id:l.id,label:l.label,url:l.url};if(i&&Re(i,r))return{id:nd,label:`Local`,url:a};let u=e.find(e=>i?Re(i,Ve(e)):!1);if(u)return{id:u.id,label:u.label,url:Ge(Ve(u))||Ve(u)};if(t&&Re(t,r))return{id:nd,label:`Local`,url:a};let d=e.find(e=>t?Re(t,e.url):!1);return d?{id:d.id,label:d.label,url:Ge(d.url)||d.url}:t.startsWith(`openchamber-ui://`)?{id:nd,label:`Local`,url:a}:{id:`custom`,label:ze(o||`Instance`),url:o}};function xd({open:e,onOpenChange:n,embedded:i=!1,onHostSwitched:a}){let{t:o}=Zt(),s=g(e=>e.setSettingsDialogOpen),c=g(e=>e.setSettingsPage),l=ui(e=>e.isConnected),u=ui(e=>e.connectionPhase),[d,f]=Z.useState([]),[p,m]=Z.useState(null),[h,_]=Z.useState(()=>({...od}));Z.useEffect(()=>{Object.assign(od,h)},[h]);let[v,y]=Z.useState(!1),[b,x]=Z.useState(!1),[S,C]=Z.useState(!1),w=ss(),T=cs(),[E,D]=Z.useState(null),O=E||T,[k,A]=Z.useState({}),[j,M]=Z.useState({}),[N,P]=Z.useState({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),[F,I]=Z.useState(``),[L,R]=Z.useState(()=>cd()),[z,B]=Z.useState(null),[V,ee]=Z.useState(``),[U,te]=Z.useState(``),[ne,G]=Z.useState(0),K=Z.useRef(0),re=Z.useMemo(()=>[yd(L),...d.map(e=>({...e,url:Ge(e.url)||e.url}))],[d,L]),ie=Z.useMemo(()=>new Set(Object.keys(k)),[k]),ae=Z.useMemo(()=>re.filter(e=>e.id===nd||Le(e,ie)),[re,ie]);Z.useEffect(()=>t(()=>G(e=>e+1)),[]);let oe=Z.useMemo(()=>bd(re),[re,ne]),se=Z.useMemo(()=>r().startsWith(`relay:`),[ne]),ce=Z.useMemo(()=>{let e=p||nd;return re.find(t=>t.id===e)?.label||o(`desktopHostSwitcher.instance.local`)},[re,p,o]),le=Z.useCallback(async(e,t)=>{if(H()){C(!0),I(``);try{let n=e.filter(e=>e.id!==nd);await Be({hosts:n,defaultHostId:t}),f(n),m(t)}catch(e){I(e instanceof Error?e.message:o(`desktopHostSwitcher.error.failedToSave`))}finally{C(!1)}}},[o]),ue=Z.useCallback(()=>{c(`remote-instances`),s(!0),n(!1)},[n,s,c]),de=Z.useCallback(async()=>{if(H()){y(!0),I(``);try{let[e,t,n]=await Promise.all([Ke(),Rs().catch(()=>({instances:[]})),_d()]);e.localOrigin&&R(e.localOrigin);let r={};for(let e of t.instances)r[e.id]=!0;f(e.hosts||[]),m(e.defaultHostId??null),A(r),M(n)}catch(e){I(e instanceof Error?e.message:o(`desktopHostSwitcher.error.failedToLoad`)),f([]),m(null),A({}),M({})}finally{y(!1)}}},[o]),fe=Z.useCallback(async e=>{if(H()){x(!0);try{let t=await ld(),n=await Promise.all(e.map(async e=>{let n=async()=>{let t=await He(e.relay).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=Ge(W()?Ve(e):e.url);if(!r)return[e.id,{status:`unreachable`,latencyMs:0}];let i=e.id===nd?t:e.clientToken||``,a=await Ue(r,{clientToken:i||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(fd(a.status)&&e.relay){let t=await n();if(t.status===`ok`)return[e.id,t]}return[e.id,{status:a.status,latencyMs:a.latencyMs}]})),r={};for(let[e,t]of n)r[e]=t;_(r)}finally{x(!1)}}},[]);Z.useEffect(()=>{if(!e){B(null),ee(``),te(``),D(null),P({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),I(``);return}de()},[e,de]),Z.useEffect(()=>{e&&fe(ae)},[e,ae,fe]),Z.useEffect(()=>{if(!e||!H())return;let t=!1,n=async()=>{let e=await _d();t||M(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===nd?L:Ge(e.url)||``,n=e.id===nd?L:Ge(Ve(e))||``,r=!!e.relay&&!e.apiUrl&&e.id!==nd;if(!t&&!r)return;if(W()){if(!n&&!e.relay||w)return;let t=e.id===nd?await ld():null,r=await Ss({host:e,cachedProbe:h[e.id]||null,...e.id===nd?{localApiOrigin:n,localClientToken:t}:{}});_(t=>({...t,[e.id]:r.status})),r.ok&&a?.();return}let i=!!k[e.id];if(e.id!==nd&&i&&H()){let n=j[e.id],r=await fs(e.id).then(t=>t.find(t=>t.id===e.id)||null).catch(()=>null);r&&(n=r,M(t=>({...t,[e.id]:r})));let i=Ge(n?.localUrl||e.url||``);if(n?.phase===`ready`&&i){let e=sd(i);a?.(),window.location.assign(e);return}D(e.id);let s=K.current+1;K.current=s,P({open:!0,hostId:e.id,hostLabel:ze(e.label),phase:`master_connecting`,detail:null,error:null,errorCode:null});try{if(await Is(e.id),s!==K.current)return;let n=await vd(e.id,rd,e=>{M(t=>({...t,[e.id]:e})),P(t=>({...t,phase:e.phase,detail:e.detail||null,errorCode:e.errorCode||null}))},()=>s!==K.current);if(s!==K.current)return;let r=sd(Ge(n.localUrl||``)||t);a?.(),window.location.assign(r);return}catch(t){if(s!==K.current)return;let n=t instanceof Error?t.message:String(t);if(n===id)return;let r=ks(N.errorCode,n);P(e=>({...e,error:n,errorCode:r})),fa.error(o(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:ze(e.label)}),{description:_s(o(ws(r)),r,n)});return}finally{s===K.current&&D(null)}}if(e.id!==nd&&H()){D(e.id);let n=await Ue(t,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(_(t=>({...t,[e.id]:{status:n.status,latencyMs:n.latencyMs}})),fd(n.status)){fa.error(o(`desktopHostSwitcher.toast.instanceUnreachable`,{host:ze(e.label)})),D(null);return}}let s=sd(t);a?.();try{window.location.assign(s)}catch{window.location.href=s}}),me=Z.useCallback(()=>{B(null),ee(``),te(``)},[]),he=Z.useCallback(e=>{e.stopPropagation()},[]),ge=Z.useCallback(async()=>{if(!z)return;if(z===nd){me();return}let e=Fe(U);if(!e){I(o(`desktopHostSwitcher.error.invalidUrl`));return}let t=e.persistedUrl,n=(V||ze(t)).trim(),r=d.map(e=>e.id===z?{...e,label:n,url:t,apiUrl:t}:e);await le(r,p),me(),e.redeemUrl&&window.location.assign(e.redeemUrl)},[me,d,p,V,U,z,le,o]),_e=Z.useCallback(async e=>{await le(d,e===nd?nd:e)},[d,le]),ve=Z.useCallback(e=>{let t=e=>{fa.error(o(`desktopHostSwitcher.error.failedToOpenNewWindow`),{description:e instanceof Error?e.message:String(e)})};if(e.relay&&e.id!==nd){Ie(e.id).catch(t);return}let n=e.id===nd?L:Ve(e);if(!n)return;let r=sd(n);qe(r,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(t)},[L,o]),ye=q(async()=>{K.current+=1,D(null),P(e=>({...e,open:!1,hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}));let e=sd(L);if(W()){if(w)return;let e=await ld();(await Ss({host:yd(L),localApiOrigin:L,localClientToken:e})).ok&&a?.();return}a?.(),window.location.assign(e)}),be=Z.useCallback(async()=>{let e=N.hostId||O;K.current+=1,D(null),P({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),!(!e||e===nd||!H())&&await zs(e).catch(()=>{})},[N.hostId,O]),xe=Z.useCallback(()=>{let e=N.hostId;if(!e)return;let t=re.find(t=>t.id===e);t&&pe(t)},[re,pe,N.hostId]),Se=Z.useCallback(async e=>{if(H()){D(e.id);try{await Is(e.id),(await vd(e.id,rd,e=>{M(t=>({...t,[e.id]:e}))})).phase===`ready`&&fa.success(o(`desktopHostSwitcher.toast.sshConnected`,{host:ze(e.label)}))}catch(t){let n=t instanceof Error?t.message:String(t);if(n!==id){let t=ks(null,n);fa.error(o(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:ze(e.label)}),{description:_s(o(ws(t)),t,n)})}}finally{D(null)}}},[o]);if(!H())return null;let Ce=H(),we=(0,$.jsxs)($.Fragment,{children:[i?(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:o(`desktopHostSwitcher.header.current`)}),(0,$.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:ze(oe.label)}),(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`•`}),(0,$.jsx)(`span`,{className:`font-medium text-foreground`,children:o(`desktopHostSwitcher.header.default`)}),(0,$.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:ze(ce)})]}),(0,$.jsx)(`button`,{type:`button`,className:Y(`inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors`,`hover:text-foreground hover:bg-interactive-hover`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary`),onClick:()=>void fe(ae),disabled:!Ce||v||b,"aria-label":o(`desktopHostSwitcher.actions.refreshInstancesAria`),children:(0,$.jsx)(X,{name:`refresh`,className:Y(`h-4 w-4`,b&&`animate-spin`)})})]})}):(0,$.jsxs)(co,{className:`flex-shrink-0`,children:[(0,$.jsxs)(po,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`server`,className:`h-5 w-5`}),o(`desktopHostSwitcher.title`)]}),(0,$.jsx)(mo,{children:o(`desktopHostSwitcher.description`)})]}),!i&&(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:o(`desktopHostSwitcher.header.currentColon`)}),(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:ze(oe.label)}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:o(`desktopHostSwitcher.header.currentDefaultColon`)}),(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:ze(ce)})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,$.jsxs)(yo,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>void fe(ae),disabled:!Ce||v||b,children:[(0,$.jsx)(X,{name:`refresh`,className:Y(`h-4 w-4`,b&&`animate-spin`)}),o(`desktopHostSwitcher.actions.refresh`)]})})]}),!Ce&&(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:o(`desktopHostSwitcher.state.limitedOnPage`)})}),(0,$.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:(0,$.jsx)(`div`,{className:Y(`space-y-1`,i&&`space-y-1.5 px-3 py-1`),children:v?(0,$.jsx)(`div`,{className:`px-2 py-2 text-muted-foreground text-sm`,children:o(`desktopHostSwitcher.state.loading`)}):ae.map(e=>{let t=e.id===nd,n=!!k[e.id],r=e.id===oe.id,a=(p||nd)===e.id,s=h[e.id]||null,c=j[e.id]||null,d=td({isActive:r,isSsh:n,runtimeIsConnected:l,runtimeConnectionPhase:u,currentTransportIsRelay:se,probe:s,sshPhase:c?.phase}),f=d.statusKind,m=d.showViaRelay,g=z===e.id,_=t?L:Ge(e.url)||e.url,v=e.id===nd?o(`desktopHostSwitcher.instance.local`):ze(e.label),y=e.relay&&!e.apiUrl?o(`mobile.connect.relay.badge`):ze(_);return(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 px-2.5 py-2 rounded-md overflow-hidden`,i&&`rounded-xl bg-[var(--surface-muted)] px-3 py-2.5`,i&&r&&`bg-[var(--interactive-selection)]/25`,g?`bg-interactive-hover/20`:`hover:bg-interactive-hover/30`),children:[(0,$.jsxs)(`button`,{type:`button`,className:Y(`flex items-center gap-2 flex-1 min-w-0 text-left`,g&&`pointer-events-none opacity-70`),onClick:()=>void pe(e),disabled:O===e.id,"aria-label":o(`desktopHostSwitcher.actions.switchToAria`,{instance:v}),children:[(0,$.jsx)(`span`,{className:Y(`h-2 w-2 rounded-full flex-shrink-0`,ud(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}),r&&(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:o(`desktopHostSwitcher.header.current`)}),n&&(0,$.jsx)(`span`,{className:`typography-micro flex-shrink-0 px-1 rounded leading-none pb-px text-[var(--status-info)] bg-[var(--status-info)]/10`,children:`SSH`})]}),(0,$.jsxs)(`div`,{className:Y(`typography-micro truncate`,dd(f)),children:[o(n&&!r?gd(c?.phase):md(f)),d.latencyMs==null?``:o(`desktopHostSwitcher.status.ping`,{ms:d.latencyMs}),m?` · ${o(`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:[n&&!t&&(c?.phase===`idle`||!c?.phase?(0,$.jsxs)(yo,{type:`button`,variant:`outline`,size:`sm`,className:`h-8 px-2.5`,disabled:O===e.id,onClick:t=>{t.stopPropagation(),Se(e)},children:[O===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`}),o(`desktopHostSwitcher.actions.connect`)]}):(0,$.jsx)(`div`,{className:`h-8 w-8 opacity-0 pointer-events-none`,"aria-hidden":`true`})),(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:Y(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,a?`text-primary hover:text-primary/80`:`text-muted-foreground/60 hover:text-primary/80`),onClick:()=>void _e(e.id),"aria-label":o(a?`desktopHostSwitcher.actions.defaultInstanceAria`:`desktopHostSwitcher.actions.setAsDefaultAria`),disabled:S||!a&&pd(f),children:a?(0,$.jsx)(X,{name:`star-fill`,className:`h-4 w-4`}):(0,$.jsx)(X,{name:`star`,className:`h-4 w-4`})})}),(0,$.jsx)(Zo,{sideOffset:6,children:o(a?`desktopHostSwitcher.header.default`:`desktopHostSwitcher.actions.setAsDefault`)})]}),(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:Y(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,pd(f)?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground/60 hover:text-foreground`),onClick:t=>{t.stopPropagation(),ve(e)},disabled:pd(f),"aria-label":o(`desktopHostSwitcher.actions.openInNewWindowAria`),children:(0,$.jsx)(X,{name:`window`,className:`h-4 w-4`})})}),(0,$.jsx)(Zo,{sideOffset:6,children:pd(f)?o(`desktopHostSwitcher.state.instanceUnreachable`):o(`desktopHostSwitcher.actions.openInNewWindow`)})]})]})]},e.id)})})}),Ce&&z&&z!==nd&&(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:o(`desktopHostSwitcher.edit.title`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(yo,{type:`button`,variant:`outline`,size:`sm`,onClick:me,disabled:S,children:o(`desktopHostSwitcher.actions.cancel`)}),(0,$.jsxs)(yo,{type:`button`,size:`sm`,onClick:()=>void ge(),disabled:S,children:[S?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):null,o(`desktopHostSwitcher.actions.save`)]})]})]}),(0,$.jsxs)(`div`,{className:`mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[(0,$.jsx)(Yo,{value:V,onChange:e=>ee(e.target.value),onKeyDown:he,placeholder:o(`desktopHostSwitcher.field.labelPlaceholder`),disabled:S}),(0,$.jsx)(Yo,{value:U,onChange:e=>te(e.target.value),onKeyDown:he,placeholder:o(`desktopHostSwitcher.field.urlPlaceholder`),disabled:S})]})]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 border-t border-[var(--interactive-border)]`,children:(0,$.jsxs)(`button`,{type:`button`,className:`w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,onClick:ue,children:[(0,$.jsx)(X,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`typography-ui-label`,children:o(`desktopHostSwitcher.actions.addInstance`)})]})}),F&&(0,$.jsx)(`div`,{className:`flex-shrink-0 typography-meta text-status-error`,children:F})]}),Te=(0,$.jsx)(go,{open:N.open,onOpenChange:e=>{if(!e&&O){be();return}P(t=>({...t,open:e,...e?{}:{hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}}))},children:(0,$.jsxs)(fo,{className:`w-[min(28rem,calc(100vw-2rem))] max-w-none`,children:[(0,$.jsxs)(co,{children:[(0,$.jsxs)(po,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`loader-4`,className:Y(`h-4 w-4`,!N.error&&`animate-spin`)}),o(`desktopHostSwitcher.ssh.connectingTo`,{host:N.hostLabel||o(`desktopHostSwitcher.ssh.instanceFallback`)})]}),N.error?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(mo,{className:`sr-only`,children:o(bs(ks(N.errorCode,N.error)))}),(0,$.jsx)(hs,{errorCode:N.errorCode,detail:N.error})]}):(0,$.jsx)(mo,{children:N.detail||o(gd(N.phase))})]}),N.error?(0,$.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,$.jsx)(yo,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{ue(),be()},children:o(`desktopHostSwitcher.sshError.openRemoteSettings`)}),(0,$.jsx)(yo,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void ye(),children:o(`desktopHostSwitcher.actions.switchToLocal`)}),(0,$.jsx)(yo,{type:`button`,size:`sm`,onClick:xe,disabled:!N.hostId,children:o(`desktopHostSwitcher.actions.retry`)})]}):null]})});return i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`w-full max-h-[70vh] flex flex-col overflow-hidden gap-2`,children:we}),Te]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(go,{open:e,onOpenChange:n,children:(0,$.jsx)(fo,{className:`w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3`,children:we})}),Te]})}function Sd(){let e=(0,Q.c)(11),[t,n]=Z.useState(!1),{t:r}=Zt();if(!H())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)(yo,{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)(xd,{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 Cd=e=>e.shouldUseDesktopShellPasswordLogin?`locked`:`error`,wd=`/auth/session`,Td=4,Ed=1500,Dd=`openchamber.uiAuth.trustDevice`,Od=`desktop-local`,kd=`desktop-local`,Ad=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},jd=(e,t)=>{let n=Ge(e),r=Ge(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},Md=()=>H(),Nd=e=>{let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`},Pd=()=>{if(!H())return!1;let e=Ad();if(!e)return!1;let t=n()||(typeof window<`u`?window.location.origin:``);if(jd(e,t))return!0;try{let e=Ge(t);return!!(e&&Nd(new URL(e).hostname))}catch{return!1}},Fd=()=>Pd()?{clientKind:Od,dedupeKey:kd}:{},Id=async()=>await pe(wd,{method:`GET`,credentials:`include`,headers:{Accept:`application/json`}}),Ld=()=>typeof window>`u`?!1:window.localStorage.getItem(Dd)===`true`,Rd=async(e,t)=>{let n=Md();return await pe(wd,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:`OpenChamber Desktop`,...Fd()})})},zd=async()=>{if(!H())return``;let e=await pe(`/api/client-auth/clients`,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:`OpenChamber Desktop`,...Fd()})}).catch(()=>null);if(!e?.ok)return``;let t=await e.json().catch(()=>null);return typeof t?.token==`string`?t.token.trim():``},Bd=()=>H()&&!Pd(),Vd=async(e,t)=>{if(!H()||typeof window>`u`)return null;let r=await Se(`desktop_remote_password_login`,{url:n(),password:e,trustDevice:t,requestHeaders:l()}).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}:{}}},Hd=async(e,t)=>{if(!H()||!t)return;let n=await Ke().catch(()=>null);if(!n)return;if(n.localOrigin&&jd(n.localOrigin,e)){await Be({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>void 0);return}let r=!1,i=n.hosts.map(n=>!jd(Ve(n),e)||n.clientToken===t?n:(r=!0,{...n,clientToken:t}));r&&await Be({hosts:i,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0)},Ud=async e=>{if(!e)return;let t=n(),r=l();await Hd(t,e),p({apiBaseUrl:t,clientToken:e,requestHeaders:Object.keys(r).length>0?r:null,relay:i()})},Wd=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},Gd=()=>{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)(Ps,{width:120,height:120})}),e[0]=t):t=e[0],t},Kd=e=>{let t=(0,Q.c)(23),{onRetry:n,errorType:r,retryAfter:i,children:a}=e,o=r===void 0?`network`:r,{t:s}=Zt(),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)(yo,{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)(Wd,{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],_},qd=({children:e})=>{let{t:n}=Zt(),r=Z.useMemo(()=>x(),[]),i=r,o=Z.useMemo(()=>H()&&!r,[r]),[c,l]=Z.useState(()=>i?`authenticated`:`pending`),[u,d]=Z.useState(``),[f,p]=Z.useState(!1),[m,h]=Z.useState(``),[g,_]=Z.useState(void 0),[v,y]=Z.useState(!1),[b,S]=Z.useState(Es),[C,w]=Z.useState(!1),[T,E]=Z.useState(!1),[D,O]=Z.useState(()=>Ld()),[k,A]=Z.useState(null),[j,M]=Z.useState(i),N=Z.useRef(null),P=Z.useRef(i);Z.useEffect(()=>{typeof window>`u`||window.localStorage.setItem(Dd,D?`true`:`false`)},[D]);let F=Z.useCallback(async()=>{if(i)return Es;try{let e=await As();return S(e),e}catch{return S(Es),Es}},[i]);Z.useEffect(()=>{let e=!1;if(!i)return(async()=>{try{if(!window.isSecureContext||!So()){e||w(!1);return}e||w(!0)}catch{e||w(!1)}})(),()=>{e=!0}},[i]);let I=Z.useRef(0),L=Z.useRef(null),R=Z.useRef(null),z=Z.useCallback(()=>{L.current!==null&&(window.clearTimeout(L.current),L.current=null)},[]),B=Z.useCallback(()=>{I.current=0,z()},[z]),V=Z.useCallback(()=>I.current>=Td?!1:(I.current+=1,z(),L.current=window.setTimeout(()=>{L.current=null,R.current?.()},Ed*I.current),!0),[z]);Z.useEffect(()=>z,[z]);let ee=Z.useCallback(async()=>{if(i){l(`authenticated`);return}l(e=>e===`authenticated`?e:`pending`);try{let[e,t]=await Promise.all([Id(),F()]),n=await e.text();if(e.ok){B(),l(`authenticated`),y(!1),h(``),_(void 0);return}if(e.status===401){let e={};try{e=JSON.parse(n)}catch{e={}}B(),y(e.tunnelLocked===!0),S(t),l(`locked`),_(void 0);return}if(e.status===429){let e={};try{e=JSON.parse(n)}catch{e={}}B(),_(e.retryAfter),y(!1),l(`rate-limited`);return}if(V())return;l(`error`),y(!1)}catch(e){if(console.warn(`Failed to check session status:`,e),Cd({shouldUseDesktopShellPasswordLogin:Bd()})===`locked`){l(`locked`),_(void 0),y(!1);return}if(V())return;l(`error`),y(!1)}},[F,B,V,i]);Z.useEffect(()=>{R.current=ee},[ee]),Z.useEffect(()=>{i||ee()},[ee,i]),Z.useEffect(()=>{if(c===`pending`||c===`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)}},[c]),Z.useEffect(()=>{if(i)return;let e=Qu(e=>{a(e)&&(d(``),h(``),_(void 0),y(!1),B(),M(!1),P.current=!1,l(`pending`),ee())}),n=t(t=>e.schedule(t));return()=>{n(),e.cancel()}},[ee,B,i]),Z.useEffect(()=>{!i&&c===`locked`&&(P.current=!1,M(!1))},[i,c]),Z.useEffect(()=>{c===`locked`&&N.current&&(N.current.focus(),N.current.select())},[c]),Z.useEffect(()=>{if(!i&&c===`authenticated`&&!P.current){P.current=!0;let e=!1;return Xu({runtimeKey:s(),initializeAppearance:Te,syncSettings:_e,applyDirectory:qu,onError:(e,t)=>{console.error(`[SessionAuthGate] ${e} settings hydration failed:`,t)}},{force:!0}).then(()=>{e||M(!0)}),()=>{e=!0}}},[i,c]);let U=async e=>{e.preventDefault(),await ne(!1)},te=Z.useCallback(async()=>{A(`register`),E(!0);try{await js()}finally{A(null),E(!1)}await F()},[F]),W=Z.useCallback(()=>{Ns(),A(null),E(!1)},[]),ne=Z.useCallback(async e=>{if(!v&&!(!u||f)){T&&W(),p(!0),h(``);try{if(Bd()){let e=await Vd(u,D);if(e?.token){d(``),y(!1),await Ud(e.token),l(`authenticated`);return}if(e?.status===401){h(n(`sessionAuth.error.incorrectPassword`)),y(!1),l(`locked`);return}if(e?.status===429){_(void 0),y(!1),l(`rate-limited`);return}}let t=await Rd(u,D);if(t.ok){let r=await t.json().catch(()=>null),i=Md(),a=``;if(i&&(a=typeof r?.clientToken==`string`&&r.clientToken.trim()?r.clientToken.trim():``,a||=(await Vd(u,D))?.token||await zd()),d(``),y(!1),a&&await Ud(a),e&&C)try{await te(),fa.success(n(`sessionAuth.toast.passkeyAdded`)),l(`authenticated`);return}catch(e){if(Ds(e))fa.message(n(`sessionAuth.toast.passkeySetupCanceled`));else{let t=e instanceof Error?e.message:n(`sessionAuth.error.passkeySetupFailed`);fa.error(t)}l(`authenticated`);return}l(`authenticated`);return}if(t.status===401){h(n(`sessionAuth.error.incorrectPassword`)),y(!1),l(`locked`);return}if(t.status===429){let e=await t.json().catch(()=>({}));_(e.retryAfter),y(!1),l(`rate-limited`);return}h(n(`sessionAuth.error.unexpectedResponse`)),y(!1),l(`error`)}catch(e){console.warn(`Failed to submit UI password:`,e);let t=Bd()?await Vd(u,D):null;if(t?.token){d(``),y(!1),await Ud(t.token),l(`authenticated`);return}if(t?.status===401){h(n(`sessionAuth.error.incorrectPassword`)),y(!1),l(`locked`);return}if(t?.status===429){_(void 0),y(!1),l(`rate-limited`);return}h(n(`sessionAuth.error.networkRetry`)),y(!1),l(`error`)}finally{p(!1)}}},[W,T,f,v,u,te,C,n,D]),G=Z.useCallback(async()=>{if(!(f||!C)){if(T){W();return}E(!0),A(`auth`),h(``);try{let e=await gs(D,{issueClientToken:Md(),clientLabel:`OpenChamber Desktop`,...Fd()}),t=Md()&&typeof e?.clientToken==`string`&&e.clientToken.trim()?e.clientToken.trim():``;t&&await Ud(t),d(``),l(`authenticated`)}catch(e){if(Ds(e))h(``);else{let t=e instanceof Error?e.message:n(`sessionAuth.error.passkeySignInCanceled`);h(t)}}finally{A(null),E(!1)}}},[W,T,f,C,n,D]),K=Z.useCallback(async()=>{if(!(f||v||!C)){if(T){W();return}if(c!==`authenticated`){if(!u){h(n(`sessionAuth.error.enterPasswordForPasskey`));return}await ne(!0);return}h(``);try{await te(),fa.success(n(`sessionAuth.toast.passkeyAdded`))}catch(e){if(Ds(e)){fa.message(n(`sessionAuth.toast.passkeySetupCanceled`));return}let t=e instanceof Error?e.message:n(`sessionAuth.error.passkeySetupFailed`);fa.error(t)}}},[W,ne,T,f,v,u,te,c,C,n]),re=C&&b.enabled,ie=re&&b.hasPasskeys;return c===`pending`||c===`authenticated`&&!j?(0,$.jsx)(Gd,{}):c===`error`?(0,$.jsx)(Kd,{onRetry:()=>{B(),ee()},errorType:`network`,children:o&&(0,$.jsxs)(`div`,{className:`w-full max-w-xs`,children:[(0,$.jsx)(Sd,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:n(`sessionAuth.locked.hostSwitcherHint`)})]})}):c===`rate-limited`?(0,$.jsx)(Kd,{onRetry:()=>void ee(),errorType:`rate-limit`,retryAfter:g}):c===`locked`?(0,$.jsx)(Wd,{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:n(v?`sessionAuth.locked.tunnelTitle`:`sessionAuth.locked.unlockTitle`)}),(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:n(v?`sessionAuth.locked.tunnelDescription`:`sessionAuth.locked.passwordDescription`)})]}),!v&&(0,$.jsxs)(`form`,{onSubmit:U,className:`w-full space-y-2`,children:[ie&&(0,$.jsxs)(yo,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>void G(),disabled:f||T&&k!==`auth`,children:[T?(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:n(T&&k===`auth`?`sessionAuth.actions.cancelPasskey`:`sessionAuth.actions.usePasskey`)})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(X,{name:`lock`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60`}),(0,$.jsx)(Yo,{id:`openchamber-ui-password`,ref:N,type:`password`,autoComplete:`current-password`,placeholder:n(`sessionAuth.password.placeholder`),value:u,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)(yo,{type:`submit`,size:`icon`,disabled:!u||f,"aria-label":n(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)(jo,{checked:D,onChange:O,disabled:f,ariaLabel:n(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,$.jsx)(`span`,{children:n(`sessionAuth.actions.trustDevice`)})]}),(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`sm`,className:`text-muted-foreground hover:text-foreground`,onClick:()=>void K(),disabled:f,children:n(T&&k===`register`?`sessionAuth.actions.cancelPasskeySetup`:`sessionAuth.actions.addPasskey`)})]}):(0,$.jsxs)(`label`,{className:`flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground`,children:[(0,$.jsx)(jo,{checked:D,onChange:O,disabled:f,ariaLabel:n(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,$.jsx)(`span`,{children:n(`sessionAuth.actions.trustDevice`)})]}),m&&(0,$.jsx)(`p`,{id:`oc-ui-auth-error`,className:`typography-meta text-destructive`,children:m})]}),o&&(0,$.jsxs)(`div`,{className:`w-full`,children:[(0,$.jsx)(Sd,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:n(`sessionAuth.locked.hostSwitcherHint`)})]})]})}):(0,$.jsx)($.Fragment,{children:e})},Jd=e=>{let t=(0,Q.c)(14),{children:n}=e,r=g(Yd),i=g(Xd),a=g(Zd),o=g(Qd),s=g($d),{deviceType:c,hasTouchInput:l}=Ws(),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=typeof document<`u`&&_(),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 Yd(e){return e.fontSize}function Xd(e){return e.codeFontSize}function Zd(e){return e.applyTypography}function Qd(e){return e.padding}function $d(e){return e.applyPadding}var ef=e(at(),1),tf=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}`},nf=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-C7cKReps.js","assets/rolldown-runtime-C0FnF6B9.js","assets/useUIStore-CqqO11ZI.js","assets/vendor-zustand-B4dlGEM2.js","assets/vendor-base-ui-CnHfUmDN.js","assets/persistence-CSZp1CNB.js","assets/vendor-pathe-vBmvQE8f.js","assets/vendor-react-DLPElpoQ.js","assets/vendor-tanstack-query-core-BWz0ose6.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-DDoDDyM9.js","assets/vendor-lodash-es-DfLbG5Af.js","assets/vendor-js-cookie-hSOiFTtX.js","assets/clipboard-BXxLshVq.js","assets/store-BDFdnk6l.js","assets/dialog-BkhHBTd4.js","assets/utils-B0mQXN9L.js","assets/vendor-class-variance-authority-BLUaYARZ.js","assets/vendor-tailwind-merge-BicNWLTg.js","assets/Icon-4My8YZwt.js","assets/button-Or0daT9o.js","assets/useThemeSystem-DMzWVJaW.js","assets/markdownTheme-CVS01wHf.js","assets/path-utils-jGozTg9d.js","assets/appThemeRegistry-CgqQtWC4.js","assets/platform-CenlWqxu.js","assets/vendor-opencode-sdk-C07HQypa.js","assets/useMobileNavigationStore-C1gtZTkJ.js","assets/vendor-tanstack-react-query-D7pys_c9.js","assets/vendor-sonner-DVzioF3d.js","assets/useAssistantUIStore-BHacrxe_.js","assets/vendor-fuse.js-DB5wDJbI.js","assets/MarkdownRenderer-DayesgSP.js","assets/MarkdownLoadingSkeleton-Vezjvk9B.js","assets/markdownHeightCache-CvUyZT4q.js","assets/toolHelpers-DEvVP9U0.js","assets/useEffectiveDirectory-DKaOxQUi.js","assets/useWorkerHighlightedLines-DyJgEWoO.js","assets/tooltip-BSrJYYYc.js","assets/vendor-tanstack-react-virtual-tlDgH6PG.js","assets/markdown-worker-BuveaH3O.js","assets/vendor-capacitor-app-PzT84wSx.js"])))=>i.map(i=>d[i]);
2
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,C as n,E as r,J as i,O as a,P as o,T as s,U as c,V as l,d as u,g as d,h as f,j as p,m,s as h,t as g,v as _,w as v,y}from"./useUIStore-CqqO11ZI.js";import{$ as b,$t as x,B as S,C,Ct as w,Dt as T,Ft as E,G as D,I as O,J as k,K as A,M as j,Mt as M,N,Q as P,R as F,S as I,T as L,U as R,V as z,W as B,Wt as V,Xt as H,Y as ee,Yt as U,Z as te,Zt as W,_ as ne,at as G,b as K,c as re,ct as ie,d as ae,en as oe,et as se,ft as ce,g as le,h as ue,it as de,j as fe,kn as pe,lt as me,m as he,mt as ge,n as _e,nt as ve,ot as ye,pt as be,q as xe,qt as Se,r as Ce,st as we,t as Te,u as Ee,ut as De,v as Oe,wt as ke,x as Ae,xn as je,y as Me,yt as Ne,z as Pe}from"./persistence-CSZp1CNB.js";import{_ as Fe,c as Ie,d as Le,f as Re,h as ze,i as Be,l as Ve,m as He,n as Ue,o as We,p as Ge,r as Ke,s as qe}from"./desktopHosts-BzSE0sK7.js";import{r as Je}from"./desktopRelayRestore-BaKjk1kQ.js";import{a as Ye,i as Xe,r as Ze,t as Qe}from"./vendor-zustand-B4dlGEM2.js";import{c as $e,d as et,f as tt,l as nt,nt as rt,rt as it,tt as at,u as ot}from"./vendor-base-ui-CnHfUmDN.js";import{At as st,Bt as ct,Ct as lt,Gt as ut,Ht as dt,Jt as ft,Kt as pt,Nt as mt,Ot as ht,Pt as gt,Rt as _t,St as vt,Ut as yt,Wt as bt,Yt as xt,jt as St,kt as Ct,n as wt,t as Tt,zt as Et}from"./platform-CenlWqxu.js";import{a as Dt,n as Ot,o as kt}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{n as At}from"./vendor-react-DLPElpoQ.js";import{c as jt,i as Mt,n as Nt,s as Pt,t as Ft}from"./vendor-tanstack-react-query-D7pys_c9.js";import{B as It,R as Lt,V as Rt,c as zt}from"./vendor-codemirror-autocomplete-DHomsvW7.js";import{i as Bt,u as Vt}from"./vendor-pierre-diffs-DX7XTPG3.js";import{t as Ht}from"./vendor-sonner-DVzioF3d.js";import{a as Ut,d as Wt,i as Gt,l as Kt,n as q,o as qt,r as Jt,u as Yt}from"./vendor-reactuses-core-DDoDDyM9.js";import{c as Xt,n as Zt,r as Qt,s as $t,t as en}from"./clipboard-BXxLshVq.js";import{i as tn,t as nn}from"./store-BDFdnk6l.js";import{$ as rn,$a as an,$i as on,$n as sn,$r as cn,A as ln,Ai as un,Ar as dn,At as fn,B as pn,Ba as mn,Br as hn,C as gn,Ca as _n,Cr as vn,Ct as yn,D as bn,Da as xn,Di as Sn,Dn as Cn,Do as wn,Dr as Tn,Dt as En,E as Dn,Ei as On,En as kn,Er as An,Et as jn,F as Mn,Fa as Nn,Fi as Pn,Fn,Fr as In,Ft as Ln,G as Rn,Gt as zn,H as Bn,Ha as Vn,Hr as Hn,Ht as Un,I as Wn,Ia as Gn,Ii as Kn,In as qn,Ir as Jn,It as Yn,J as Xn,Ji as Zn,Jr as Qn,K as $n,Kr as er,Kt as tr,L as nr,La as rr,Li as ir,Ln as ar,Lr as or,Lt as sr,M as cr,Mi as lr,Mr as ur,Mt as dr,N as fr,Ni as pr,O as mr,Oi as hr,On as gr,Oo as _r,Or as vr,Ot as yr,P as br,Pi as xr,Pr as Sr,Q as Cr,Qi as wr,Qn as Tr,Qr as Er,Qt as Dr,R as Or,Ra as kr,Ri as Ar,Rr as jr,Si as Mr,Sn as Nr,Sr as Pr,St as Fr,T as Ir,Ta as Lr,Ti as Rr,Tn as zr,Tt as Br,U as Vr,Ua as Hr,Ui as Ur,Ut as Wr,V as Gr,Va as Kr,Vr as qr,W as Jr,Wa as Yr,Wr as Xr,Wt as Zr,X as Qr,Xa as $r,Xi as ei,Xn as ti,Xr as ni,Xt as ri,Y as ii,Ya as ai,Yi as oi,Yr as si,Yt as ci,Z as li,Zi as ui,Zn as di,Zt as fi,_i as pi,_t as mi,a as hi,aa as gi,ai as _i,b as vi,ba as yi,bi,br as xi,bt as Si,c as J,ca as Ci,ci as wi,cn as Ti,d as Ei,da as Di,di as Oi,dn as ki,dr as Ai,en as ji,et as Mi,fa as Ni,fi as Pi,fn as Fi,ft as Ii,ga as Li,gi as Ri,gn as zi,gt as Bi,h as Vi,ha as Hi,hi as Ui,hn as Wi,ho as Gi,ht as Ki,i as qi,ii as Ji,in as Yi,it as Xi,j as Zi,ja as Qi,ji as $i,jt as ea,k as ta,ki as na,kn as ra,kt as ia,la as aa,li as oa,ln as sa,ma as ca,mi as la,mn as ua,mo as da,mr as fa,mt as pa,n as ma,na as ha,ni as ga,nn as _a,nt as va,on as ya,p as ba,pi as xa,pn as Sa,pt as Ca,q as wa,qi as Ta,qr as Ea,ra as Da,ri as Oa,rn as ka,rt as Aa,sa as ja,si as Ma,sn as Na,ta as Pa,tn as Fa,tt as Ia,ua as La,ui as Ra,un as za,ur as Ba,ut as Va,va as Ha,vi as Ua,vt as Wa,w as Ga,wa as Ka,wn as qa,wo as Ja,wt as Ya,x as Xa,xi as Za,xn as Qa,xr as $a,xt as eo,yi as to,yt as no,z as ro,za as io,zi as ao,zn as oo,zt as so}from"./useMobileNavigationStore-C1gtZTkJ.js";import{a as co,i as lo,l as uo,n as fo,o as po,r as mo,s as ho,t as go}from"./dialog-BkhHBTd4.js";import{n as _o,t as Y}from"./utils-B0mQXN9L.js";import{t as vo}from"./AgentAvatar-DI2zs2WH.js";import{n as X}from"./Icon-4My8YZwt.js";import{t as yo}from"./button-Or0daT9o.js";import{E as bo,n as xo}from"./gitApi-Dxz3xwNw.js";import{a as So}from"./vendor-simplewebauthn-browser-Dwhcdg_5.js";import{C as Co,D as wo,H as To,J as Eo,O as Do,S as Oo,U as ko,Y as Ao,Z as jo,_ as Mo,a as No,b as Po,f as Fo,h as Io,i as Lo,k as Ro,l as zo,m as Bo,n as Vo,o as Ho,q as Uo,s as Wo,u as Go,w as Ko,x as qo,y as Jo}from"./projectMeta-CPkhOD4P.js";import{t as Yo}from"./input-BUsGnzwe.js";import{i as Xo,n as Zo,t as Qo}from"./tooltip-BSrJYYYc.js";import{A as $o,B as es,D as ts,E as ns,F as rs,H as is,I as as,J as os,Mt as ss,Nt as cs,O as ls,R as us,T as ds,Tt as fs,U as ps,_ as ms,dt as hs,et as gs,ft as _s,g as vs,h as ys,ht as bs,j as xs,jt as Ss,k as Cs,mt as ws,n as Ts,nt as Es,ot as Ds,p as Os,pt as ks,rt as As,st as js,t as Ms,tt as Ns,ut as Ps,v as Fs,vt as Is,w as Ls,xt as Rs,yt as zs,z as Bs}from"./useSessionAutoCleanup-nycHB0Ra.js";import{n as Vs,r as Hs,t as Us}from"./useThemeSystem-DMzWVJaW.js";import{i as Ws,t as Gs}from"./OverlayScrollbar-BZB21Yp_.js";import{_ as Ks,a as qs,d as Js,f as Ys,g as Xs,h as Zs,i as Qs,l as $s,m as ec,n as tc,p as nc,u as rc}from"./markdownTheme-CVS01wHf.js";import{n as ic,r as ac,t as oc}from"./useRuntimeAPIs-DSLXJybW.js";import{A as sc,B as cc,C as lc,D as uc,E as dc,F as fc,H as pc,I as mc,L as hc,M as gc,N as _c,O as vc,R as yc,S as bc,T as xc,U as Sc,V as Cc,a as wc,b as Tc,c as Ec,f as Dc,i as Oc,j as kc,k as Ac,l as jc,m as Mc,n as Nc,o as Pc,p as Fc,r as Ic,s as Lc,t as Rc,u as zc,w as Bc,x as Vc,z as Hc}from"./insertionBoundaries-ChFLgDUk.js";import{C as Uc,D as Wc,E as Gc,M as Kc,O as qc,S as Jc,T as Yc,_ as Xc,b as Zc,c as Qc,d as $c,f as el,g as tl,h as nl,i as rl,k as il,l as al,m as ol,o as sl,p as cl,s as ll,t as ul,u as dl,v as fl,w as pl,x as ml,y as hl}from"./appThemeRegistry-CgqQtWC4.js";import{a as gl,n as _l,o as vl,r as yl,t as bl}from"./MarkdownRenderer-DayesgSP.js";import{n as xl,r as Sl}from"./textarea-CIO34TZz.js";import{_ as Cl,a as wl,c as Tl,g as El,l as Dl,o as Ol,t as kl,v as Al,y as jl}from"./vendor-dnd-kit-core-CvWxUPdb.js";import{i as Ml,n as Nl,o as Pl,s as Fl,t as Il}from"./vendor-dnd-kit-sortable-hHdP9lLb.js";import{a as Ll,n as Rl,t as zl}from"./url-CE_gAfNa.js";import{a as Bl,i as Vl,l as Hl}from"./toolHelpers-DEvVP9U0.js";import{n as Ul,t as Wl}from"./useEffectiveDirectory-DKaOxQUi.js";import{a as Gl,i as Kl,l as ql,n as Jl,o as Yl,r as Xl,s as Zl,t as Ql,u as $l}from"./FadeInOnReveal-BWJcUp5P.js";import{a as eu,i as tu,n as nu,o as ru,t as iu}from"./path-utils-jGozTg9d.js";import{A as au,C as ou,D as su,E as cu,M as lu,O as uu,S as du,T as fu,a as pu,b as mu,c as hu,g as gu,h as _u,i as vu,j as yu,k as bu,o as xu,p as Su,r as Cu,s as wu,t as Tu,v as Eu,w as Du,x as Ou,y as ku}from"./useWorkerHighlightedLines-DyJgEWoO.js";import{a as Au,c as ju,o as Mu,s as Nu,u as Pu}from"./sessionChangeSummary-CX2MJIkc.js";import{t as Fu}from"./vendor-cmdk-CeAGfrLo.js";import{t as Iu}from"./sortable-tabs-strip-C5gGnikj.js";import{n as Lu}from"./MarkdownLoadingSkeleton-Vezjvk9B.js";import{n as Ru,t as zu}from"./vendor-tanstack-react-virtual-tlDgH6PG.js";import{i as Bu}from"./markdownHeightCache-CvUyZT4q.js";import{t as Vu}from"./outsideFileGrants-BB4GPvCq.js";import{i as Hu,t as Uu}from"./vendor-framer-motion-DFy_BSVd.js";import{t as Wu}from"./vendor-legendapp-list-WE32lwNk.js";import{n as Gu,t as Ku}from"./useFontPreferences-BxOHKuVw.js";typeof window<`u`&&(window.__opencodeDebug={getLastAssistantMessage(){let e=J.getState().currentSessionId;if(!e)return null;let t=Pa(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=(ha(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:(ha(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=J.getState().currentSessionId;if(!t)return[];let n=Pa(t);return`${n.length}`,n.forEach((e,t)=>{let n=ha(e.id)||[];`${t}${e.role}${e.id}${n.length}`}),e?this.truncateMessages(n):n},async getAppStatus(){let e=lt.getState(),t=J.getState(),n=Gi.getState(),r=e.currentDirectory||null,i=mt.getDirectory()??null,a=Da(),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=je(),u=typeof window<`u`&&!!window.__OPENCHAMBER_ELECTRON__,d=async e=>{try{return await e.json()}catch{return null}},f=async e=>{try{return await e.text()}catch{return null}},p=async e=>{try{let t=await pe(e);return t.ok?await d(t):{status:t.status}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},m=null,h=null,g=null,_=null;try{let e=await mt.getSdkClient().path.get(r?{directory:r}:void 0);m=e.error?{error:e.error}:e.data}catch(e){m={error:e instanceof Error?e.message:String(e)}}try{let e=await mt.getSdkClient().project.current(r?{directory:r}:void 0);h=e.error?{error:e.error}:e.data}catch(e){h={error:e instanceof Error?e.message:String(e)}}g=await p(`/api/config/settings`);try{let e=await pe(`/api/health`),t=e.headers.get(`content-type`)||``,n=await f(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}_={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){_={error:e instanceof Error?e.message:String(e)}}let v={isGitRepo:null};if(r)try{v.isGitRepo=await xo(r)}catch(e){v={isGitRepo:null,error:e instanceof Error?e.message:String(e)}}let y=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:m?.directory||m?.worktree||i,homeDirectory:e.homeDirectory||null,isHomeReady:e.isHomeReady,hasPersistedDirectory:e.hasPersistedDirectory,isSwitchingDirectory:e.isSwitchingDirectory},projects:{total:n.projects.length,activeProjectId:n.activeProjectId,samples:y},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:v,localStorage:c,opencode:{pathInfo:m,projectInfo:h,health:_},openchamber:{settingsInfo:g}}},async buildDiagnosticsReport(){let e=await this.getAppStatus();return JSON.stringify(e,null,2)},async copyTextToClipboard(e){return en(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=J.getState(),t=qa.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=J.getState().currentSessionId;if(!e)return[];let t=Pa(e).filter(e=>e.role===`assistant`).filter(e=>{let t=ha(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=ha(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=J.getState().currentSessionId;if(!i)return{summary:null,rows:[]};let a=Pa(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=ha(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=J.getState().currentSessionId;if(!e)return null;let t=Pa(e).filter(e=>e.role===`assistant`);if(t.length===0)return null;let n=t[t.length-1],r=(ha(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=qa.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}}},ht(),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(it(),1),Q=At(),qu=async()=>{if(typeof window>`u`)return;let e=null;try{e=M(`lastDirectory`)}catch(e){console.warn(`Failed to read saved directory preferences:`,e)}e&&!x()&&lt.getState().setDirectory(e,{showOverlay:!1})},Ju=new Map,Yu=e=>Ju.get(e)??null,Xu=({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:i},a={})=>{let o=Ju.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 Ju.set(e,s),s},Zu=async({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,startWatchers:i,onError:a})=>{await Xu({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:a})&&i()},Qu=(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 $u(e){return!e||e===`idle`?null:e===`ready`?`ok`:e===`error`?`unreachable`:`auth`}function ed(e,t){let n=e.via===`relay`;return t?n:!n}function td(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?$u(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||ed(o,a))&&(u=Math.max(0,Math.round(o.latencyMs))),{statusKind:c,showViaRelay:l,latencyMs:u}}var $=rt(),nd=`local`,rd=9e4,id=`SSH connection cancelled`,ad=e=>Je(e),od={},sd=e=>{let t=Ge(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}},cd=()=>typeof window>`u`?``:window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,ld=async()=>W()?We().catch(()=>``):``,ud=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`,dd=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`,fd=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,pd=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,md=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`,hd=e=>new Promise(t=>window.setTimeout(t,e)),gd=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`}},_d=async()=>{let e=await fs().catch(()=>[]),t={};for(let n of e)t[n.id]=n;return t},vd=async(e,t,n,r)=>{let i=Date.now()+t;for(;Date.now()<i;){if(r?.())throw Error(id);let t=(await fs(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 hd(700)}throw r?.()?Error(id):Error(`Timed out waiting for SSH connection`)},yd=e=>({id:nd,label:`Local`,url:e||cd()}),bd=e=>{let t=typeof window>`u`?``:window.location.href,r=e.find(e=>e.id===nd)?.url||cd(),i=n(),a=Ge(r)||r,o=Ge(t)||t,c=s(),l=e.find(e=>e.relay&&ad(e)===c);if(l)return{id:l.id,label:l.label,url:l.url};if(i&&Re(i,r))return{id:nd,label:`Local`,url:a};let u=e.find(e=>i?Re(i,Ve(e)):!1);if(u)return{id:u.id,label:u.label,url:Ge(Ve(u))||Ve(u)};if(t&&Re(t,r))return{id:nd,label:`Local`,url:a};let d=e.find(e=>t?Re(t,e.url):!1);return d?{id:d.id,label:d.label,url:Ge(d.url)||d.url}:t.startsWith(`openchamber-ui://`)?{id:nd,label:`Local`,url:a}:{id:`custom`,label:ze(o||`Instance`),url:o}};function xd({open:e,onOpenChange:n,embedded:i=!1,onHostSwitched:a}){let{t:o}=Zt(),s=g(e=>e.setSettingsDialogOpen),c=g(e=>e.setSettingsPage),l=ui(e=>e.isConnected),u=ui(e=>e.connectionPhase),[d,f]=Z.useState([]),[p,m]=Z.useState(null),[h,_]=Z.useState(()=>({...od}));Z.useEffect(()=>{Object.assign(od,h)},[h]);let[v,y]=Z.useState(!1),[b,x]=Z.useState(!1),[S,C]=Z.useState(!1),w=ss(),T=cs(),[E,D]=Z.useState(null),O=E||T,[k,A]=Z.useState({}),[j,M]=Z.useState({}),[N,P]=Z.useState({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),[F,I]=Z.useState(``),[L,R]=Z.useState(()=>cd()),[z,B]=Z.useState(null),[V,ee]=Z.useState(``),[U,te]=Z.useState(``),[ne,G]=Z.useState(0),K=Z.useRef(0),re=Z.useMemo(()=>[yd(L),...d.map(e=>({...e,url:Ge(e.url)||e.url}))],[d,L]),ie=Z.useMemo(()=>new Set(Object.keys(k)),[k]),ae=Z.useMemo(()=>re.filter(e=>e.id===nd||Le(e,ie)),[re,ie]);Z.useEffect(()=>t(()=>G(e=>e+1)),[]);let oe=Z.useMemo(()=>bd(re),[re,ne]),se=Z.useMemo(()=>r().startsWith(`relay:`),[ne]),ce=Z.useMemo(()=>{let e=p||nd;return re.find(t=>t.id===e)?.label||o(`desktopHostSwitcher.instance.local`)},[re,p,o]),le=Z.useCallback(async(e,t)=>{if(H()){C(!0),I(``);try{let n=e.filter(e=>e.id!==nd);await Be({hosts:n,defaultHostId:t}),f(n),m(t)}catch(e){I(e instanceof Error?e.message:o(`desktopHostSwitcher.error.failedToSave`))}finally{C(!1)}}},[o]),ue=Z.useCallback(()=>{c(`remote-instances`),s(!0),n(!1)},[n,s,c]),de=Z.useCallback(async()=>{if(H()){y(!0),I(``);try{let[e,t,n]=await Promise.all([Ke(),Rs().catch(()=>({instances:[]})),_d()]);e.localOrigin&&R(e.localOrigin);let r={};for(let e of t.instances)r[e.id]=!0;f(e.hosts||[]),m(e.defaultHostId??null),A(r),M(n)}catch(e){I(e instanceof Error?e.message:o(`desktopHostSwitcher.error.failedToLoad`)),f([]),m(null),A({}),M({})}finally{y(!1)}}},[o]),fe=Z.useCallback(async e=>{if(H()){x(!0);try{let t=await ld(),n=await Promise.all(e.map(async e=>{let n=async()=>{let t=await He(e.relay).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=Ge(W()?Ve(e):e.url);if(!r)return[e.id,{status:`unreachable`,latencyMs:0}];let i=e.id===nd?t:e.clientToken||``,a=await Ue(r,{clientToken:i||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(fd(a.status)&&e.relay){let t=await n();if(t.status===`ok`)return[e.id,t]}return[e.id,{status:a.status,latencyMs:a.latencyMs}]})),r={};for(let[e,t]of n)r[e]=t;_(r)}finally{x(!1)}}},[]);Z.useEffect(()=>{if(!e){B(null),ee(``),te(``),D(null),P({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),I(``);return}de()},[e,de]),Z.useEffect(()=>{e&&fe(ae)},[e,ae,fe]),Z.useEffect(()=>{if(!e||!H())return;let t=!1,n=async()=>{let e=await _d();t||M(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===nd?L:Ge(e.url)||``,n=e.id===nd?L:Ge(Ve(e))||``,r=!!e.relay&&!e.apiUrl&&e.id!==nd;if(!t&&!r)return;if(W()){if(!n&&!e.relay||w)return;let t=e.id===nd?await ld():null,r=await Ss({host:e,cachedProbe:h[e.id]||null,...e.id===nd?{localApiOrigin:n,localClientToken:t}:{}});_(t=>({...t,[e.id]:r.status})),r.ok&&a?.();return}let i=!!k[e.id];if(e.id!==nd&&i&&H()){let n=j[e.id],r=await fs(e.id).then(t=>t.find(t=>t.id===e.id)||null).catch(()=>null);r&&(n=r,M(t=>({...t,[e.id]:r})));let i=Ge(n?.localUrl||e.url||``);if(n?.phase===`ready`&&i){let e=sd(i);a?.(),window.location.assign(e);return}D(e.id);let s=K.current+1;K.current=s,P({open:!0,hostId:e.id,hostLabel:ze(e.label),phase:`master_connecting`,detail:null,error:null,errorCode:null});try{if(await Is(e.id),s!==K.current)return;let n=await vd(e.id,rd,e=>{M(t=>({...t,[e.id]:e})),P(t=>({...t,phase:e.phase,detail:e.detail||null,errorCode:e.errorCode||null}))},()=>s!==K.current);if(s!==K.current)return;let r=sd(Ge(n.localUrl||``)||t);a?.(),window.location.assign(r);return}catch(t){if(s!==K.current)return;let n=t instanceof Error?t.message:String(t);if(n===id)return;let r=ks(N.errorCode,n);P(e=>({...e,error:n,errorCode:r})),fa.error(o(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:ze(e.label)}),{description:_s(o(ws(r)),r,n)});return}finally{s===K.current&&D(null)}}if(e.id!==nd&&H()){D(e.id);let n=await Ue(t,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(_(t=>({...t,[e.id]:{status:n.status,latencyMs:n.latencyMs}})),fd(n.status)){fa.error(o(`desktopHostSwitcher.toast.instanceUnreachable`,{host:ze(e.label)})),D(null);return}}let s=sd(t);a?.();try{window.location.assign(s)}catch{window.location.href=s}}),me=Z.useCallback(()=>{B(null),ee(``),te(``)},[]),he=Z.useCallback(e=>{e.stopPropagation()},[]),ge=Z.useCallback(async()=>{if(!z)return;if(z===nd){me();return}let e=Fe(U);if(!e){I(o(`desktopHostSwitcher.error.invalidUrl`));return}let t=e.persistedUrl,n=(V||ze(t)).trim(),r=d.map(e=>e.id===z?{...e,label:n,url:t,apiUrl:t}:e);await le(r,p),me(),e.redeemUrl&&window.location.assign(e.redeemUrl)},[me,d,p,V,U,z,le,o]),_e=Z.useCallback(async e=>{await le(d,e===nd?nd:e)},[d,le]),ve=Z.useCallback(e=>{let t=e=>{fa.error(o(`desktopHostSwitcher.error.failedToOpenNewWindow`),{description:e instanceof Error?e.message:String(e)})};if(e.relay&&e.id!==nd){Ie(e.id).catch(t);return}let n=e.id===nd?L:Ve(e);if(!n)return;let r=sd(n);qe(r,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(t)},[L,o]),ye=q(async()=>{K.current+=1,D(null),P(e=>({...e,open:!1,hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}));let e=sd(L);if(W()){if(w)return;let e=await ld();(await Ss({host:yd(L),localApiOrigin:L,localClientToken:e})).ok&&a?.();return}a?.(),window.location.assign(e)}),be=Z.useCallback(async()=>{let e=N.hostId||O;K.current+=1,D(null),P({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),!(!e||e===nd||!H())&&await zs(e).catch(()=>{})},[N.hostId,O]),xe=Z.useCallback(()=>{let e=N.hostId;if(!e)return;let t=re.find(t=>t.id===e);t&&pe(t)},[re,pe,N.hostId]),Se=Z.useCallback(async e=>{if(H()){D(e.id);try{await Is(e.id),(await vd(e.id,rd,e=>{M(t=>({...t,[e.id]:e}))})).phase===`ready`&&fa.success(o(`desktopHostSwitcher.toast.sshConnected`,{host:ze(e.label)}))}catch(t){let n=t instanceof Error?t.message:String(t);if(n!==id){let t=ks(null,n);fa.error(o(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:ze(e.label)}),{description:_s(o(ws(t)),t,n)})}}finally{D(null)}}},[o]);if(!H())return null;let Ce=H(),we=(0,$.jsxs)($.Fragment,{children:[i?(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:o(`desktopHostSwitcher.header.current`)}),(0,$.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:ze(oe.label)}),(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`•`}),(0,$.jsx)(`span`,{className:`font-medium text-foreground`,children:o(`desktopHostSwitcher.header.default`)}),(0,$.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:ze(ce)})]}),(0,$.jsx)(`button`,{type:`button`,className:Y(`inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors`,`hover:text-foreground hover:bg-interactive-hover`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary`),onClick:()=>void fe(ae),disabled:!Ce||v||b,"aria-label":o(`desktopHostSwitcher.actions.refreshInstancesAria`),children:(0,$.jsx)(X,{name:`refresh`,className:Y(`h-4 w-4`,b&&`animate-spin`)})})]})}):(0,$.jsxs)(co,{className:`flex-shrink-0`,children:[(0,$.jsxs)(po,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`server`,className:`h-5 w-5`}),o(`desktopHostSwitcher.title`)]}),(0,$.jsx)(mo,{children:o(`desktopHostSwitcher.description`)})]}),!i&&(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:o(`desktopHostSwitcher.header.currentColon`)}),(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:ze(oe.label)}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:o(`desktopHostSwitcher.header.currentDefaultColon`)}),(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:ze(ce)})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,$.jsxs)(yo,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>void fe(ae),disabled:!Ce||v||b,children:[(0,$.jsx)(X,{name:`refresh`,className:Y(`h-4 w-4`,b&&`animate-spin`)}),o(`desktopHostSwitcher.actions.refresh`)]})})]}),!Ce&&(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:o(`desktopHostSwitcher.state.limitedOnPage`)})}),(0,$.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:(0,$.jsx)(`div`,{className:Y(`space-y-1`,i&&`space-y-1.5 px-3 py-1`),children:v?(0,$.jsx)(`div`,{className:`px-2 py-2 text-muted-foreground text-sm`,children:o(`desktopHostSwitcher.state.loading`)}):ae.map(e=>{let t=e.id===nd,n=!!k[e.id],r=e.id===oe.id,a=(p||nd)===e.id,s=h[e.id]||null,c=j[e.id]||null,d=td({isActive:r,isSsh:n,runtimeIsConnected:l,runtimeConnectionPhase:u,currentTransportIsRelay:se,probe:s,sshPhase:c?.phase}),f=d.statusKind,m=d.showViaRelay,g=z===e.id,_=t?L:Ge(e.url)||e.url,v=e.id===nd?o(`desktopHostSwitcher.instance.local`):ze(e.label),y=e.relay&&!e.apiUrl?o(`mobile.connect.relay.badge`):ze(_);return(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 px-2.5 py-2 rounded-md overflow-hidden`,i&&`rounded-xl bg-[var(--surface-muted)] px-3 py-2.5`,i&&r&&`bg-[var(--interactive-selection)]/25`,g?`bg-interactive-hover/20`:`hover:bg-interactive-hover/30`),children:[(0,$.jsxs)(`button`,{type:`button`,className:Y(`flex items-center gap-2 flex-1 min-w-0 text-left`,g&&`pointer-events-none opacity-70`),onClick:()=>void pe(e),disabled:O===e.id,"aria-label":o(`desktopHostSwitcher.actions.switchToAria`,{instance:v}),children:[(0,$.jsx)(`span`,{className:Y(`h-2 w-2 rounded-full flex-shrink-0`,ud(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}),r&&(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:o(`desktopHostSwitcher.header.current`)}),n&&(0,$.jsx)(`span`,{className:`typography-micro flex-shrink-0 px-1 rounded leading-none pb-px text-[var(--status-info)] bg-[var(--status-info)]/10`,children:`SSH`})]}),(0,$.jsxs)(`div`,{className:Y(`typography-micro truncate`,dd(f)),children:[o(n&&!r?gd(c?.phase):md(f)),d.latencyMs==null?``:o(`desktopHostSwitcher.status.ping`,{ms:d.latencyMs}),m?` · ${o(`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:[n&&!t&&(c?.phase===`idle`||!c?.phase?(0,$.jsxs)(yo,{type:`button`,variant:`outline`,size:`sm`,className:`h-8 px-2.5`,disabled:O===e.id,onClick:t=>{t.stopPropagation(),Se(e)},children:[O===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`}),o(`desktopHostSwitcher.actions.connect`)]}):(0,$.jsx)(`div`,{className:`h-8 w-8 opacity-0 pointer-events-none`,"aria-hidden":`true`})),(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:Y(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,a?`text-primary hover:text-primary/80`:`text-muted-foreground/60 hover:text-primary/80`),onClick:()=>void _e(e.id),"aria-label":o(a?`desktopHostSwitcher.actions.defaultInstanceAria`:`desktopHostSwitcher.actions.setAsDefaultAria`),disabled:S||!a&&pd(f),children:a?(0,$.jsx)(X,{name:`star-fill`,className:`h-4 w-4`}):(0,$.jsx)(X,{name:`star`,className:`h-4 w-4`})})}),(0,$.jsx)(Zo,{sideOffset:6,children:o(a?`desktopHostSwitcher.header.default`:`desktopHostSwitcher.actions.setAsDefault`)})]}),(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:Y(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,pd(f)?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground/60 hover:text-foreground`),onClick:t=>{t.stopPropagation(),ve(e)},disabled:pd(f),"aria-label":o(`desktopHostSwitcher.actions.openInNewWindowAria`),children:(0,$.jsx)(X,{name:`window`,className:`h-4 w-4`})})}),(0,$.jsx)(Zo,{sideOffset:6,children:pd(f)?o(`desktopHostSwitcher.state.instanceUnreachable`):o(`desktopHostSwitcher.actions.openInNewWindow`)})]})]})]},e.id)})})}),Ce&&z&&z!==nd&&(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:o(`desktopHostSwitcher.edit.title`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(yo,{type:`button`,variant:`outline`,size:`sm`,onClick:me,disabled:S,children:o(`desktopHostSwitcher.actions.cancel`)}),(0,$.jsxs)(yo,{type:`button`,size:`sm`,onClick:()=>void ge(),disabled:S,children:[S?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):null,o(`desktopHostSwitcher.actions.save`)]})]})]}),(0,$.jsxs)(`div`,{className:`mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[(0,$.jsx)(Yo,{value:V,onChange:e=>ee(e.target.value),onKeyDown:he,placeholder:o(`desktopHostSwitcher.field.labelPlaceholder`),disabled:S}),(0,$.jsx)(Yo,{value:U,onChange:e=>te(e.target.value),onKeyDown:he,placeholder:o(`desktopHostSwitcher.field.urlPlaceholder`),disabled:S})]})]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 border-t border-[var(--interactive-border)]`,children:(0,$.jsxs)(`button`,{type:`button`,className:`w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,onClick:ue,children:[(0,$.jsx)(X,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`typography-ui-label`,children:o(`desktopHostSwitcher.actions.addInstance`)})]})}),F&&(0,$.jsx)(`div`,{className:`flex-shrink-0 typography-meta text-status-error`,children:F})]}),Te=(0,$.jsx)(go,{open:N.open,onOpenChange:e=>{if(!e&&O){be();return}P(t=>({...t,open:e,...e?{}:{hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}}))},children:(0,$.jsxs)(fo,{className:`w-[min(28rem,calc(100vw-2rem))] max-w-none`,children:[(0,$.jsxs)(co,{children:[(0,$.jsxs)(po,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`loader-4`,className:Y(`h-4 w-4`,!N.error&&`animate-spin`)}),o(`desktopHostSwitcher.ssh.connectingTo`,{host:N.hostLabel||o(`desktopHostSwitcher.ssh.instanceFallback`)})]}),N.error?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(mo,{className:`sr-only`,children:o(bs(ks(N.errorCode,N.error)))}),(0,$.jsx)(hs,{errorCode:N.errorCode,detail:N.error})]}):(0,$.jsx)(mo,{children:N.detail||o(gd(N.phase))})]}),N.error?(0,$.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,$.jsx)(yo,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{ue(),be()},children:o(`desktopHostSwitcher.sshError.openRemoteSettings`)}),(0,$.jsx)(yo,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void ye(),children:o(`desktopHostSwitcher.actions.switchToLocal`)}),(0,$.jsx)(yo,{type:`button`,size:`sm`,onClick:xe,disabled:!N.hostId,children:o(`desktopHostSwitcher.actions.retry`)})]}):null]})});return i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`w-full max-h-[70vh] flex flex-col overflow-hidden gap-2`,children:we}),Te]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(go,{open:e,onOpenChange:n,children:(0,$.jsx)(fo,{className:`w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3`,children:we})}),Te]})}function Sd(){let e=(0,Q.c)(11),[t,n]=Z.useState(!1),{t:r}=Zt();if(!H())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)(yo,{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)(xd,{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 Cd=e=>e.shouldUseDesktopShellPasswordLogin?`locked`:`error`,wd=`/auth/session`,Td=4,Ed=1500,Dd=`openchamber.uiAuth.trustDevice`,Od=`desktop-local`,kd=`desktop-local`,Ad=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},jd=(e,t)=>{let n=Ge(e),r=Ge(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},Md=()=>H(),Nd=e=>{let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`},Pd=()=>{if(!H())return!1;let e=Ad();if(!e)return!1;let t=n()||(typeof window<`u`?window.location.origin:``);if(jd(e,t))return!0;try{let e=Ge(t);return!!(e&&Nd(new URL(e).hostname))}catch{return!1}},Fd=()=>Pd()?{clientKind:Od,dedupeKey:kd}:{},Id=async()=>await pe(wd,{method:`GET`,credentials:`include`,headers:{Accept:`application/json`}}),Ld=()=>typeof window>`u`?!1:window.localStorage.getItem(Dd)===`true`,Rd=async(e,t)=>{let n=Md();return await pe(wd,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:`OpenChamber Desktop`,...Fd()})})},zd=async()=>{if(!H())return``;let e=await pe(`/api/client-auth/clients`,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:`OpenChamber Desktop`,...Fd()})}).catch(()=>null);if(!e?.ok)return``;let t=await e.json().catch(()=>null);return typeof t?.token==`string`?t.token.trim():``},Bd=()=>H()&&!Pd(),Vd=async(e,t)=>{if(!H()||typeof window>`u`)return null;let r=await Se(`desktop_remote_password_login`,{url:n(),password:e,trustDevice:t,requestHeaders:l()}).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}:{}}},Hd=async(e,t)=>{if(!H()||!t)return;let n=await Ke().catch(()=>null);if(!n)return;if(n.localOrigin&&jd(n.localOrigin,e)){await Be({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>void 0);return}let r=!1,i=n.hosts.map(n=>!jd(Ve(n),e)||n.clientToken===t?n:(r=!0,{...n,clientToken:t}));r&&await Be({hosts:i,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0)},Ud=async e=>{if(!e)return;let t=n(),r=l();await Hd(t,e),p({apiBaseUrl:t,clientToken:e,requestHeaders:Object.keys(r).length>0?r:null,relay:i()})},Wd=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},Gd=()=>{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)(Ps,{width:120,height:120})}),e[0]=t):t=e[0],t},Kd=e=>{let t=(0,Q.c)(23),{onRetry:n,errorType:r,retryAfter:i,children:a}=e,o=r===void 0?`network`:r,{t:s}=Zt(),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)(yo,{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)(Wd,{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],_},qd=({children:e})=>{let{t:n}=Zt(),r=Z.useMemo(()=>x(),[]),i=r,o=Z.useMemo(()=>H()&&!r,[r]),[c,l]=Z.useState(()=>i?`authenticated`:`pending`),[u,d]=Z.useState(``),[f,p]=Z.useState(!1),[m,h]=Z.useState(``),[g,_]=Z.useState(void 0),[v,y]=Z.useState(!1),[b,S]=Z.useState(Es),[C,w]=Z.useState(!1),[T,E]=Z.useState(!1),[D,O]=Z.useState(()=>Ld()),[k,A]=Z.useState(null),[j,M]=Z.useState(i),N=Z.useRef(null),P=Z.useRef(i);Z.useEffect(()=>{typeof window>`u`||window.localStorage.setItem(Dd,D?`true`:`false`)},[D]);let F=Z.useCallback(async()=>{if(i)return Es;try{let e=await As();return S(e),e}catch{return S(Es),Es}},[i]);Z.useEffect(()=>{let e=!1;if(!i)return(async()=>{try{if(!window.isSecureContext||!So()){e||w(!1);return}e||w(!0)}catch{e||w(!1)}})(),()=>{e=!0}},[i]);let I=Z.useRef(0),L=Z.useRef(null),R=Z.useRef(null),z=Z.useCallback(()=>{L.current!==null&&(window.clearTimeout(L.current),L.current=null)},[]),B=Z.useCallback(()=>{I.current=0,z()},[z]),V=Z.useCallback(()=>I.current>=Td?!1:(I.current+=1,z(),L.current=window.setTimeout(()=>{L.current=null,R.current?.()},Ed*I.current),!0),[z]);Z.useEffect(()=>z,[z]);let ee=Z.useCallback(async()=>{if(i){l(`authenticated`);return}l(e=>e===`authenticated`?e:`pending`);try{let[e,t]=await Promise.all([Id(),F()]),n=await e.text();if(e.ok){B(),l(`authenticated`),y(!1),h(``),_(void 0);return}if(e.status===401){let e={};try{e=JSON.parse(n)}catch{e={}}B(),y(e.tunnelLocked===!0),S(t),l(`locked`),_(void 0);return}if(e.status===429){let e={};try{e=JSON.parse(n)}catch{e={}}B(),_(e.retryAfter),y(!1),l(`rate-limited`);return}if(V())return;l(`error`),y(!1)}catch(e){if(console.warn(`Failed to check session status:`,e),Cd({shouldUseDesktopShellPasswordLogin:Bd()})===`locked`){l(`locked`),_(void 0),y(!1);return}if(V())return;l(`error`),y(!1)}},[F,B,V,i]);Z.useEffect(()=>{R.current=ee},[ee]),Z.useEffect(()=>{i||ee()},[ee,i]),Z.useEffect(()=>{if(c===`pending`||c===`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)}},[c]),Z.useEffect(()=>{if(i)return;let e=Qu(e=>{a(e)&&(d(``),h(``),_(void 0),y(!1),B(),M(!1),P.current=!1,l(`pending`),ee())}),n=t(t=>e.schedule(t));return()=>{n(),e.cancel()}},[ee,B,i]),Z.useEffect(()=>{!i&&c===`locked`&&(P.current=!1,M(!1))},[i,c]),Z.useEffect(()=>{c===`locked`&&N.current&&(N.current.focus(),N.current.select())},[c]),Z.useEffect(()=>{if(!i&&c===`authenticated`&&!P.current){P.current=!0;let e=!1;return Xu({runtimeKey:s(),initializeAppearance:Te,syncSettings:_e,applyDirectory:qu,onError:(e,t)=>{console.error(`[SessionAuthGate] ${e} settings hydration failed:`,t)}},{force:!0}).then(()=>{e||M(!0)}),()=>{e=!0}}},[i,c]);let U=async e=>{e.preventDefault(),await ne(!1)},te=Z.useCallback(async()=>{A(`register`),E(!0);try{await js()}finally{A(null),E(!1)}await F()},[F]),W=Z.useCallback(()=>{Ns(),A(null),E(!1)},[]),ne=Z.useCallback(async e=>{if(!v&&!(!u||f)){T&&W(),p(!0),h(``);try{if(Bd()){let e=await Vd(u,D);if(e?.token){d(``),y(!1),await Ud(e.token),l(`authenticated`);return}if(e?.status===401){h(n(`sessionAuth.error.incorrectPassword`)),y(!1),l(`locked`);return}if(e?.status===429){_(void 0),y(!1),l(`rate-limited`);return}}let t=await Rd(u,D);if(t.ok){let r=await t.json().catch(()=>null),i=Md(),a=``;if(i&&(a=typeof r?.clientToken==`string`&&r.clientToken.trim()?r.clientToken.trim():``,a||=(await Vd(u,D))?.token||await zd()),d(``),y(!1),a&&await Ud(a),e&&C)try{await te(),fa.success(n(`sessionAuth.toast.passkeyAdded`)),l(`authenticated`);return}catch(e){if(Ds(e))fa.message(n(`sessionAuth.toast.passkeySetupCanceled`));else{let t=e instanceof Error?e.message:n(`sessionAuth.error.passkeySetupFailed`);fa.error(t)}l(`authenticated`);return}l(`authenticated`);return}if(t.status===401){h(n(`sessionAuth.error.incorrectPassword`)),y(!1),l(`locked`);return}if(t.status===429){let e=await t.json().catch(()=>({}));_(e.retryAfter),y(!1),l(`rate-limited`);return}h(n(`sessionAuth.error.unexpectedResponse`)),y(!1),l(`error`)}catch(e){console.warn(`Failed to submit UI password:`,e);let t=Bd()?await Vd(u,D):null;if(t?.token){d(``),y(!1),await Ud(t.token),l(`authenticated`);return}if(t?.status===401){h(n(`sessionAuth.error.incorrectPassword`)),y(!1),l(`locked`);return}if(t?.status===429){_(void 0),y(!1),l(`rate-limited`);return}h(n(`sessionAuth.error.networkRetry`)),y(!1),l(`error`)}finally{p(!1)}}},[W,T,f,v,u,te,C,n,D]),G=Z.useCallback(async()=>{if(!(f||!C)){if(T){W();return}E(!0),A(`auth`),h(``);try{let e=await gs(D,{issueClientToken:Md(),clientLabel:`OpenChamber Desktop`,...Fd()}),t=Md()&&typeof e?.clientToken==`string`&&e.clientToken.trim()?e.clientToken.trim():``;t&&await Ud(t),d(``),l(`authenticated`)}catch(e){if(Ds(e))h(``);else{let t=e instanceof Error?e.message:n(`sessionAuth.error.passkeySignInCanceled`);h(t)}}finally{A(null),E(!1)}}},[W,T,f,C,n,D]),K=Z.useCallback(async()=>{if(!(f||v||!C)){if(T){W();return}if(c!==`authenticated`){if(!u){h(n(`sessionAuth.error.enterPasswordForPasskey`));return}await ne(!0);return}h(``);try{await te(),fa.success(n(`sessionAuth.toast.passkeyAdded`))}catch(e){if(Ds(e)){fa.message(n(`sessionAuth.toast.passkeySetupCanceled`));return}let t=e instanceof Error?e.message:n(`sessionAuth.error.passkeySetupFailed`);fa.error(t)}}},[W,ne,T,f,v,u,te,c,C,n]),re=C&&b.enabled,ie=re&&b.hasPasskeys;return c===`pending`||c===`authenticated`&&!j?(0,$.jsx)(Gd,{}):c===`error`?(0,$.jsx)(Kd,{onRetry:()=>{B(),ee()},errorType:`network`,children:o&&(0,$.jsxs)(`div`,{className:`w-full max-w-xs`,children:[(0,$.jsx)(Sd,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:n(`sessionAuth.locked.hostSwitcherHint`)})]})}):c===`rate-limited`?(0,$.jsx)(Kd,{onRetry:()=>void ee(),errorType:`rate-limit`,retryAfter:g}):c===`locked`?(0,$.jsx)(Wd,{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:n(v?`sessionAuth.locked.tunnelTitle`:`sessionAuth.locked.unlockTitle`)}),(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:n(v?`sessionAuth.locked.tunnelDescription`:`sessionAuth.locked.passwordDescription`)})]}),!v&&(0,$.jsxs)(`form`,{onSubmit:U,className:`w-full space-y-2`,children:[ie&&(0,$.jsxs)(yo,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>void G(),disabled:f||T&&k!==`auth`,children:[T?(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:n(T&&k===`auth`?`sessionAuth.actions.cancelPasskey`:`sessionAuth.actions.usePasskey`)})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(X,{name:`lock`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60`}),(0,$.jsx)(Yo,{id:`openchamber-ui-password`,ref:N,type:`password`,autoComplete:`current-password`,placeholder:n(`sessionAuth.password.placeholder`),value:u,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)(yo,{type:`submit`,size:`icon`,disabled:!u||f,"aria-label":n(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)(jo,{checked:D,onChange:O,disabled:f,ariaLabel:n(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,$.jsx)(`span`,{children:n(`sessionAuth.actions.trustDevice`)})]}),(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`sm`,className:`text-muted-foreground hover:text-foreground`,onClick:()=>void K(),disabled:f,children:n(T&&k===`register`?`sessionAuth.actions.cancelPasskeySetup`:`sessionAuth.actions.addPasskey`)})]}):(0,$.jsxs)(`label`,{className:`flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground`,children:[(0,$.jsx)(jo,{checked:D,onChange:O,disabled:f,ariaLabel:n(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,$.jsx)(`span`,{children:n(`sessionAuth.actions.trustDevice`)})]}),m&&(0,$.jsx)(`p`,{id:`oc-ui-auth-error`,className:`typography-meta text-destructive`,children:m})]}),o&&(0,$.jsxs)(`div`,{className:`w-full`,children:[(0,$.jsx)(Sd,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:n(`sessionAuth.locked.hostSwitcherHint`)})]})]})}):(0,$.jsx)($.Fragment,{children:e})},Jd=e=>{let t=(0,Q.c)(14),{children:n}=e,r=g(Yd),i=g(Xd),a=g(Zd),o=g(Qd),s=g($d),{deviceType:c,hasTouchInput:l}=Ws(),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=typeof document<`u`&&_(),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 Yd(e){return e.fontSize}function Xd(e){return e.codeFontSize}function Zd(e){return e.applyTypography}function Qd(e){return e.padding}function $d(e){return e.applyPadding}var ef=e(at(),1),tf=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}`},nf=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=tf(e.colors.surface.muted),r=tf(e.colors.surface.subtle),i=tf(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=x()?f:m;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()}},rf=`openchamber:close-embedded-session-chat`,af=`openchamber:embedded-visibility`,of=`openchamber:embedded-visibility-request`,sf=e=>new URLSearchParams(e).get(`ocPanel`)===`session-chat`,cf=(e,t,n)=>JSON.stringify({sessionID:e,directory:t||``,readOnly:n===!0}),lf=(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()},uf=(e,t,n,r,i,a)=>{let o=cf(n,r,i),s=e.get(t);if(s?.signature===o)return s.src;let c=lf(n,r,i,a);return e.set(t,{signature:o,src:c}),c},df=null,ff=()=>{if(df!==null)return df;if(typeof window>`u`)return df=!1,!1;try{return df=new URLSearchParams(window.location.search).get(`ocPanel`)===`session-chat`,df}catch{return df=!1,!1}},pf=()=>{if(!ff())return null;try{let e=new URLSearchParams(window.location.search).get(`sessionId`);return e&&e.trim().length>0?e.trim():null}catch{return null}},mf=()=>ff()?new URLSearchParams(window.location.search):null,hf=()=>typeof window>`u`||window.matchMedia(`(prefers-color-scheme: dark)`).matches,gf=()=>{let e=mf()?.get(`themeVariant`);return e===`dark`||e===`light`?e===`dark`:hf()},_f=(e,t)=>t.reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e),vf=e=>typeof e==`string`&&e.trim().length>0,yf=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(!vf(_f(e,t)))return!1;let t=_f(e,[`metadata`,`variant`]);return t===`light`||t===`dark`},bf=e=>yf(e.currentTheme)?e.currentTheme:null,xf=e=>bf(e)?.metadata.variant??null,Sf=ec,Cf=nc,wf=()=>{let e=mf()?.get(`currentTheme`);if(!e)return null;try{let t=JSON.parse(e);return yf(t)?t:null}catch{return null}},Tf=e=>Zs(e===`dark`),Ef=typeof window<`u`?Z.useLayoutEffect:Z.useEffect,Df=()=>{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`)}},Of=e=>{let t=Sf,n=Cf,r=`system`;if(typeof window<`u`){let e=mf(),i=e?.get(`themeMode`),a=e?.get(`lightThemeId`),o=e?.get(`darkThemeId`),s=ue(`themeMode`),c=ue(`lightThemeId`),l=ue(`darkThemeId`),u=ue(`useSystemTheme`),d=ue(`selectedThemeId`),f=ue(`selectedThemeVariant`);if(i===`light`||i===`dark`||i===`system`)r=i;else if(s===`light`||s===`dark`||s===`system`)r=s;else if(u!==null){if(u===`true`)r=`system`;else if(d){let e=Xs(d);e&&(r=e.metadata.variant===`dark`?`dark`:`light`,e.metadata.variant===`dark`?n=e.metadata.id:t=e.metadata.id)}}else(f===`light`||f===`dark`)&&(r=f);typeof a==`string`&&a.trim().length>0?t=a.trim():typeof c==`string`&&c.trim().length>0&&(t=c.trim()),typeof o==`string`&&o.trim().length>0?n=o.trim():typeof l==`string`&&l.trim().length>0&&(n=l.trim())}if(e){let r=Xs(e);r&&(r.metadata.variant===`light`?t=r.metadata.id:n=r.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function kf({children:e,defaultThemeId:n}){let r=(0,Z.useMemo)(()=>new nf,[]),[i,o]=(0,Z.useState)(()=>Of(n)),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(()=>gf()),[d,f]=(0,Z.useState)([]),[p]=(0,Z.useState)(()=>wf()),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(()=>typeof window>`u`||!x()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),b=(0,Z.useMemo)(()=>x(),[]),S=(0,Z.useMemo)(()=>U(),[]),C=(0,Z.useMemo)(()=>H(),[]),w=(0,Z.useMemo)(()=>typeof window>`u`?!1:mf()!==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 b&&v&&n(v),m&&n(m),p&&n(p),d.forEach(n),Ks.forEach(n),e},[d,p,m,b,v]),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)??Tf(t)},[T,E]),O=(0,Z.useMemo)(()=>b&&v?v:i.themeMode===`light`?D(i.lightThemeId,`light`):i.themeMode===`dark`||l?D(i.darkThemeId,`dark`):D(i.lightThemeId,`light`),[D,b,i,l,v]),k=q(async()=>{if(!(typeof window>`u`||b)){_(!0);try{let e=await pe(`/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(yf);f(n)}catch{}finally{_(!1)}}});(0,Z.useEffect)(()=>{k()},[k]),(0,Z.useEffect)(()=>{if(!b)return;let e=e=>{y(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)},[b]);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)});Ef(()=>{if(typeof window>`u`)return;let e=Df();r.apply(O),j(b),A(O);let t=document.documentElement;return t.classList.remove(`light`,`dark`),t.classList.add(O.metadata.variant),e},[j,r,O,b,A]),(0,Z.useEffect)(()=>{if(i.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)},[i.themeMode,w]),(0,Z.useEffect)(()=>{if(w||typeof window>`u`)return;le(`themeMode`,i.themeMode),le(`lightThemeId`,i.lightThemeId),le(`darkThemeId`,i.darkThemeId),le(`useSystemTheme`,String(i.themeMode===`system`)),le(`selectedThemeId`,O.metadata.id),le(`selectedThemeVariant`,O.metadata.variant===`light`?`light`:`dark`);let e=D(i.lightThemeId,`light`),t=D(i.darkThemeId,`dark`);le(`splashBgLight`,e.colors.surface.background),le(`splashFgLight`,e.colors.surface.foreground),le(`splashBgDark`,t.colors.surface.background),le(`splashFgDark`,t.colors.surface.foreground),S&&(localStorage.setItem(`themeMode`,i.themeMode),localStorage.setItem(`useSystemTheme`,String(i.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))},[i,O,D,S,w]),(0,Z.useEffect)(()=>{if(typeof window>`u`||w)return;let e=e=>{e.storageArea===window.localStorage&&(he(e.key,`themeMode`)||he(e.key,`lightThemeId`)||he(e.key,`darkThemeId`))&&o(e=>{let t=ue(`themeMode`),n=t===`light`||t===`dark`||t===`system`?t:e.themeMode,r=ue(`lightThemeId`),i=typeof r==`string`&&r.trim().length>0?r.trim():e.lightThemeId,a=ue(`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=xf(e),a=bf(e);if(t!==`light`&&t!==`dark`&&t!==`system`||typeof n!=`string`||typeof r!=`string`)return;let s=n.trim(),c=r.trim();!s||!c||(Df(),(0,ef.flushSync)(()=>{w&&a&&h(a),t===`system`&&i&&u(i===`dark`),o(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||!s)return;let e=D(i.lightThemeId,`light`),t=D(i.darkThemeId,`dark`);Ce({themeId:O.metadata.id,themeVariant:O.metadata.variant===`light`?`light`:`dark`,useSystemTheme:i.themeMode===`system`,lightThemeId:i.lightThemeId,darkThemeId:i.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,i.themeMode,i.lightThemeId,i.darkThemeId,w,s]),(0,Z.useEffect)(()=>{w||!C||(async()=>{await $t(i.themeMode,O.metadata.variant)})()},[O.metadata.variant,C,i.themeMode,w]),(0,Z.useEffect)(()=>{if(typeof window>`u`)return;let e=e=>{let t=e.detail;t&&(o(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}}),c(!0))};return window.addEventListener(`openchamber:settings-synced`,e),()=>window.removeEventListener(`openchamber:settings-synced`,e)},[]),(0,Z.useEffect)(()=>{if(!(w||typeof window>`u`))return t(e=>{a(e)&&(o(e=>{let t=ue(`themeMode`),n=t===`light`||t===`dark`||t===`system`?t:e.themeMode,r=ue(`lightThemeId`),i=typeof r==`string`&&r.trim().length>0?r.trim():e.lightThemeId,a=ue(`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}}),c(!1))})},[w]);let N=q(e=>{let t=T.find(t=>t.metadata.id===e);t&&o(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=>{o(t=>t.themeMode===e?t:{...t,themeMode:e})}),F=q(e=>{if(e){o(e=>e.themeMode===`system`?e:{...e,themeMode:`system`});return}let t=O.metadata.variant===`dark`?`dark`:`light`;o(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&&o(e=>e.lightThemeId===t.metadata.id?e:{...e,lightThemeId:t.metadata.id})}),L=q(e=>{let t=T.find(t=>t.metadata.id===e&&t.metadata.variant===`dark`);t&&o(e=>e.darkThemeId===t.metadata.id?e:{...e,darkThemeId:t.metadata.id})}),R=(0,Z.useMemo)(()=>({currentTheme:O,availableThemes:T,setTheme:N,customThemesLoading:g,reloadCustomThemes:k,isSystemPreference:i.themeMode===`system`,setSystemPreference:F,themeMode:i.themeMode,setThemeMode:P,lightThemeId:i.lightThemeId,darkThemeId:i.darkThemeId,setLightThemePreference:I,setDarkThemePreference:L}),[T,O,g,i.darkThemeId,i.lightThemeId,i.themeMode,k,L,I,F,N,P]);return(0,$.jsx)(Hs.Provider,{value:R,children:e})}var Af=!1,jf=()=>{if(Af||typeof window>`u`)return;Af=!0;let e={showReasoningTraces:g.getState().showReasoningTraces,sessionTitleRefreshEnabled:g.getState().sessionTitleRefreshEnabled,sessionGoalEnabled:g.getState().sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:g.getState().sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:g.getState().sessionGoalDefaultBudget,collapsibleThinkingBlocks:g.getState().collapsibleThinkingBlocks,showDeletionDialog:g.getState().showDeletionDialog,nativeNotificationsEnabled:g.getState().nativeNotificationsEnabled,notificationMode:g.getState().notificationMode,notifyOnSubtasks:g.getState().notifyOnSubtasks,notifyOnCompletion:g.getState().notifyOnCompletion,notifyOnError:g.getState().notifyOnError,notifyOnQuestion:g.getState().notifyOnQuestion,notificationTemplates:g.getState().notificationTemplates,summarizeLastMessage:g.getState().summarizeLastMessage,summaryThreshold:g.getState().summaryThreshold,summaryLength:g.getState().summaryLength,maxLastMessageLength:g.getState().maxLastMessageLength,autoDeleteEnabled:g.getState().autoDeleteEnabled,autoDeleteAfterDays:g.getState().autoDeleteAfterDays,sessionRetentionAction:g.getState().sessionRetentionAction,fontSize:g.getState().fontSize,terminalFontSize:g.getState().terminalFontSize,editorFontSize:g.getState().editorFontSize,uiFont:g.getState().uiFont,monoFont:g.getState().monoFont,padding:g.getState().padding,cornerRadius:g.getState().cornerRadius,inputBarOffset:g.getState().inputBarOffset,mobileKeyboardMode:g.getState().mobileKeyboardMode,diffLayoutPreference:g.getState().diffLayoutPreference,gitChangesViewMode:g.getState().gitChangesViewMode},t=null,n=null,r=()=>{let e=t;t=null,n=null,e&&Object.keys(e).length>0&&Ce(e)},i=e=>{t={...t??{},...e},!n&&(n=setTimeout(r,150))};g.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)})},Mf=(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},Nf=(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},Pf=(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},Ff=(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])&&Pf(e[n],t[n]))},If=()=>{let e=g.getState();return{favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts}},Lf=(e,t)=>Mf(e.favoriteModels,t.favoriteModels)&&Nf(e.hiddenModels,t.hiddenModels)&&Pf(e.collapsedModelProviders,t.collapsedModelProviders)&&Mf(e.recentModels,t.recentModels)&&Pf(e.recentAgents,t.recentAgents)&&Ff(e.recentEfforts,t.recentEfforts),Rf=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()]))}),zf=()=>{if(typeof window>`u`)return()=>{};let e=null,t=null,n=!1,r=()=>{e=null;let n=If();t&&Lf(t,n)||(t=Rf(n),Ce(n).catch(()=>{}))},i=()=>{if(!n){n=!0;return}e!==null&&window.clearTimeout(e),e=window.setTimeout(r,1200)},a=g.subscribe((e,t)=>{Lf({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)}},Bf=!1,Vf=`openchamber-typography-base`,Hf=()=>{if(typeof document>`u`)return;let e=`:root {\n${Object.entries(m).map(([e,t])=>` --text-${e.replace(/([A-Z])/g,`-$1`).toLowerCase()}: ${t};`).join(`
4
4
  `)}\n}\n`,t=document.getElementById(Vf);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=Vf,n.textContent=e,document.head.appendChild(n)},Uf=()=>{Bf||typeof window>`u`||(Bf=!0,Hf())};function Wf(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)(Gf,r);let i;return t[1]===n?i=t[2]:(i=(0,$.jsx)(jt,{client:Ee,children:n}),t[1]=n,t[2]=i),i}function Gf(){return re(Ee)}var Kf=15,qf=2e3,Jf=e=>{let t=ui(e=>e.isConnected),n=ui(e=>e.providers.length),r=ui(e=>e.agents.length),i=ui(e=>e.activeDirectoryKey),a=ui(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>=Kf){u(!0);return}let e=ui.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]),Ut(f,o&&!l?qf:null)},Yf=40,Xf=20971520,Zf=new Map,Qf=0;function $f(e){return e.length*2}function ep(e,t){let n=Zf.get(e);n!==void 0&&(Qf-=n),Zf.delete(e),Zf.set(e,t),Qf+=t}function tp(e,t){let n=Zf.get(e);(n!==void 0||t!==void 0)&&ep(e,t??n??0)}function np(e){let t=Zf.get(e);t!==void 0&&(Zf.delete(e),Qf-=t)}function rp(e,t){let n=e??new Set;for(;Zf.size>Yf||Qf>Xf;){let e=Zf.keys().next().value;if(!e)return;if(n.has(e)){if(tp(e),Zf.size<=n.size)return;continue}np(e),t(e)}}function ip(e,t){ep(e,t)}function ap(e){np(e)}function op(e,t){tp(e,t)}function sp(e){let t=new Map,n=e=>{t.delete(e),ap(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=$f(n.content);return t.set(e,{...n,size:r?.isFile?r.size:void 0,mtimeMs:r?.isFile?r.mtimeMs:void 0}),ip(e,i),rp(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 op(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 cp(e){let t=(0,Q.c)(8),{apis:n,children:r}=e,i;t[0]===n.files?i=t[1]:(i=sp(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)(ac.Provider,{value:o,children:r}),t[5]=o,t[6]=r,t[7]=s):s=t[7],s}var lp=`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))`,up=`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))`,dp={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 fp(){let e=(0,Q.c)(2),t=pp,[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 pp(){return typeof document<`u`&&document.documentElement.classList.contains(`dark`)}function mp(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 hp=e=>{let t=(0,Q.c)(7),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r=fp();mp(r?lp:up);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)(Ht,{theme:i,className:`toaster group`,closeButton:!1,icons:dp,toastOptions:a,style:o,...n}),t[4]=n,t[5]=i,t[6]=s):s=t[6],s},gp=Dt(`OpenChamberMedia`);function _p(){return wt()&&Ot.getPlatform()===`android`&&Ot.isPluginAvailable(`OpenChamberMedia`)}async function vp(e){if(!_p())return null;let t=await gp.pickMedia({limit:e});if(t.cancelled)return[];let n=[];for(let e of t.files){let t=await fetch(Ot.convertFileSrc(e.path));if(!t.ok)throw Error(`Native media fetch failed (${t.status})`);let r=await t.blob();n.push(new File([r],e.name,{type:e.mimeType}))}return n}var yp=(e,t)=>{let n=t.trim();if(!n.length)return[...e].sort((e,t)=>e.scope===`project`&&t.scope!==`project`?-1:e.scope!==`project`&&t.scope===`project`?1:e.name.localeCompare(t.name));let r=Ii([...e],n,e=>[e.name,e.description??``]);return r.sort((e,t)=>e.score===t.score?e.item.scope===`project`&&t.item.scope!==`project`?-1:e.item.scope!==`project`&&t.item.scope===`project`?1:e.item.name.localeCompare(t.item.name):e.score-t.score),r.map(e=>e.item)},bp=new Map,xp=(e,t,n)=>`${+!!t}:${n}:${e.map(e=>`${e.id}\0${e.title}\0${e.subtitle??``}\0${e.badge??``}\0${e.iconName}`).join(`|`)}`,Sp=async e=>{let t=Gc(`--surface-foreground`);return Promise.all(e.slice(0,40).map(async e=>{let n=`${e.iconName}:${t}`,r=bp.get(n);return r===void 0&&(r=await Sc(e.iconName,t)??``,bp.set(n,r)),{id:e.id,title:e.title,subtitle:e.subtitle??``,badge:e.badge??``,iconBase64:r}}))},Cp=[],wp=e=>void 0,Tp=()=>void 0;function Ep(e){let t=Kc()&&e.enabled&&cl(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)(ol()),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??wp),x=q(e.onAutocompleteDismiss??Tp),S=q(e=>{typeof document>`u`||al(document.documentElement,e)});ll.bind({onText:(e,t,n)=>{il({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:ft(e.text,e.attachments.map(e=>e.filename)),chipRanges:$c(fl(e.text,e.chipHighlights),Gc(`--primary`)),appearance:typeof document>`u`?`dark`:ml(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:Zc(e.agentName||void 0),agentIdenticon:Jc(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 qc(e,!0),()=>{qc(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,ll.rememberText(i.text),ll.retain(e,i);let a=sl();return()=>{n.current=null,a(),ll.release(e)}},[t]),(0,Z.useEffect)(()=>{if(!t)return;let r=!1,i=Eo(e.modelId,e.providerId),a={modelIcon:``,modelLabel:e.modelLabel,modelVariantLabel:e.modelVariantLabel};if(s.current=``,n.current&&={...n.current,...a},nl().update(a),i)return pl(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},nl().update(a)}),()=>{r=!0}},[t,e.modelId,e.providerId,e.modelLabel,e.modelVariantLabel]);let w=dl(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:[]},ll.rememberState(n.current)),nl().update({attachmentPreviews:[]});return}return Promise.all(i.map(async t=>{let n=t.mimeType.startsWith(`image/`)&&t.dataUrl?await Uc(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},ll.rememberState(n.current)),nl().update({attachmentPreviews:e}))}),()=>{r=!0}},[t,w]);let T=e.autocompleteRows??Cp,E=e.autocompleteOpen===!0,D=e.autocompleteHighlightedIndex??0,O=xp(T,E,D);(0,Z.useEffect)(()=>{if(!t)return;let e=!1;if(!(E&&T.length>0)){let e=ol();Xc(l.current,e)||(l.current=e,n.current&&(n.current={...n.current,autocomplete:e},ll.rememberState(n.current)),nl().update({autocomplete:e}));return}return Sp(T).then(t=>{if(e)return;let r={open:t.length>0,highlightedIndex:Math.max(0,Math.min(D,Math.max(t.length-1,0))),rows:t};Xc(l.current,r)||(l.current=r,n.current&&(n.current={...n.current,autocomplete:r},ll.rememberState(n.current)),nl().update({autocomplete:r}))}),()=>{e=!0}},[t,O]);let k=t?fl(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&&hl(c,s)){i.current=!1,a.current=e.textPresetEpoch;return}n.current=s,ll.rememberState(s);let l=e.textPresetEpoch!==a.current;a.current=e.textPresetEpoch;let u=Wc({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=el(c,s,u,{caret:e.caret});d&&nl().update(d)},[t,e.text,e.textPresetEpoch,e.placeholder,e.modelLabel,e.modelVariantLabel,e.modelId,e.providerId,e.canSend,e.canAbort,e.attachmentCount,w,e.suppressed,e.attachAria,e.attachTitle,e.attachPhotosLabel,e.attachFilesLabel,e.attachCancelLabel,e.sendAria,e.queueAria,e.stopAria,e.modelAria,e.agentName,e.agentLabel,e.agentAria,e.showScrollToBottom,e.scrollAria,k]),t}var Dp=(e,t,n)=>{let r=Error(e);return r.name=`DictationStreamError`,r.retryable=t,n&&(r.reasonCode=n),r},Op=1e4,kp=15e3,Ap=3e4,jp=3e4,Mp=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 c()}catch{}this.connectPromise=new Promise((e,t)=>{let n=!1,r;try{let e=o().websocket(`/api/dictation/ws`);r=vt(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`))}},Op);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`))},kp);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`))},jp),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=Dp(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)}}},Ap))}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`,()=>{Mp.cancelAllForRuntimeSwitch()});var Np=128,Pp=`audio/pcm;rate=16000;bits=16`,Fp=()=>new Promise(e=>setTimeout(e,0)),Ip=()=>{let e=Math.random().toString(36).slice(2,10);return`dic_${Date.now().toString(16)}${e}`},Lp=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??Pp,this.getStartOptions=e.getStartOptions,this.createDictationId=e.createDictationId??Ip}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<Np;){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 Fp()}}resolveDrainWaiters(){let e=this.drainWaiters;this.drainWaiters=[];for(let t of e)t()}},Rp=16e3,zp=Rp,Bp=()=>{if(typeof window>`u`)return null;let e=window;return e.AudioContext||e.webkitAudioContext||null},Vp=e=>{let t=Math.max(-1,Math.min(1,e));return Math.round(t<0?t*32768:t*32767)},Hp=(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]=Vp(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]=Vp(e[i]*(1-s)+e[o]*s)}return a},Up=(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},Wp=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)},Gp=()=>({stream:null,context:null,source:null,processor:null,gain:null,pending:new Int16Array,started:!1}),Kp=e=>{if(e)try{e.disconnect()}catch{}},qp=()=>typeof navigator>`u`||typeof window>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`?!1:Bp()!==null;function Jp(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=Gp(),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=Bp();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(Zp);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=Hp(a,n.sampleRate,Rp);for(t.pending=Up(t.pending,c);t.pending.length>=zp;){let e=t.pending.slice(0,zp);t.pending=t.pending.slice(zp),i.current(Wp(e))}},e.connect(a),a.connect(o),o.connect(n.destination)}catch(e){let r=e;t.getTracks().forEach(Xp);try{await n.close()}catch{}throw l.current=Gp(),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{}Kp(e.processor),Kp(e.source),Kp(e.gain),e.stream&&e.stream.getTracks().forEach(Yp);let t=e.pending;if(e.pending=new Int16Array,t.length>0&&i.current(Wp(t)),e.context)try{await e.context.close()}catch{}l.current===e&&(l.current=Gp())},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 Yp(e){try{e.stop()}catch{}}function Xp(e){try{e.stop()}catch{}}function Zp(){}var Qp=1e3,$p=e=>e instanceof Error?e:Error(String(e)),em=()=>{let e=ui.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 tm(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 Lp({client:Mp,getStartOptions:em});let x=(0,Z.useCallback)(()=>{g.current&&=(clearInterval(g.current),null)},[]),S=(0,Z.useCallback)(()=>{g.current||=setInterval(()=>{l(e=>e+1)},Qp)},[]),C=(0,Z.useCallback)(e=>{let t=$p(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)(()=>Mp.onPartial((e,t)=>{let n=b.current?.getDictationId();!n||e!==n||(h.current=t,s(t))}),[]),(0,Z.useEffect)(()=>Mp.subscribeConnectionStatus(e=>{e&&m.current===`recording`&&b.current?.restartStream().catch(e=>{C(e)})}),[C]);let E=Jp({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 nm=e=>{let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`},rm=e=>{let t=(0,Q.c)(4),{volume:n}=e,{currentTheme:r}=Vs(),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},im=e=>{let t=ui(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 pe(`/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},am=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:_}=Zt(),{currentTheme:v}=Vs(),y=ui(om),b=g(sm),x;t[0]===b?x=t[1]:(x=es(is(`toggle_dictation`,b)),t[0]=b,t[1]=x);let S=x,[C]=Z.useState(cm),w=Z.useRef(null),T=Z.useRef(l),E=Z.useRef(u),D,O;t[2]!==l||t[3]!==u?(D=()=>{T.current=l,E.current=u},O=[l,u],t[2]=l,t[3]=u,t[4]=D,t[5]=O):(D=t[4],O=t[5]),Z.useEffect(D,O);let k;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(k={onTranscript:e=>{let t=w.current;w.current=null,t===`send`?E.current(e):T.current(e)}},t[6]=k):k=t[6];let{status:A,partialTranscript:j,volume:M,duration:N,error:P,errorReason:F,startDictation:I,confirmDictation:L,cancelDictation:R,retryFailedDictation:z,acceptPartialTranscript:B,discardFailedDictation:V}=tm(k),H=A===`recording`&&F===`model_download_in_progress`,ee=im(H),U=Z.useRef(A),te,W;t[7]===A?(te=t[8],W=t[9]):(te=()=>{U.current=A},W=[A],t[7]=A,t[8]=te,t[9]=W),Z.useEffect(te,W);let ne,G;t[10]!==d||t[11]!==A?(ne=()=>{d?.(A!==`idle`)},G=[A,d],t[10]=d,t[11]=A,t[12]=ne,t[13]=G):(ne=t[12],G=t[13]),Z.useLayoutEffect(ne,G);let K,re;t[14]!==L||t[15]!==I?(K=()=>{let e=()=>{U.current===`idle`?I():U.current===`recording`&&(w.current=`insert`,L())};return window.addEventListener(`openchamber:dictation-toggle`,e),()=>window.removeEventListener(`openchamber:dictation-toggle`,e)},re=[I,L],t[14]=L,t[15]=I,t[16]=K,t[17]=re):(K=t[16],re=t[17]),Z.useEffect(K,re);let ie,ae;t[18]!==R||t[19]!==L||t[20]!==A?(ie=()=>{if(A!==`recording`)return;let e=e=>{if(!e.isComposing){if(e.key===`Enter`&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey){e.preventDefault(),e.stopPropagation(),w.current=`insert`,L();return}e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),R())}};return window.addEventListener(`keydown`,e,{capture:!0}),()=>window.removeEventListener(`keydown`,e,{capture:!0})},ae=[A,L,R],t[18]=R,t[19]=L,t[20]=A,t[21]=ie,t[22]=ae):(ie=t[21],ae=t[22]),Z.useEffect(ie,ae);let oe=Z.useRef(null),se=Z.useRef(null),ce=Z.useRef(null),[le,ue]=Z.useState(null),de=A!==`idle`,fe=Z.useRef(f),pe,me;t[23]===f?(pe=t[24],me=t[25]):(pe=()=>{fe.current=f},me=[f],t[23]=f,t[24]=pe,t[25]=me),Z.useEffect(pe,me);let he=Z.useRef(!1),ge;t[26]===de?ge=t[27]:(ge=()=>{if(!de){he.current&&(he.current=!1,fe.current?.(null));return}let e=se.current,t=ce.current;if(!e||!t)return;let n=window.getComputedStyle(e),r=(parseFloat(n.paddingTop)||0)+(parseFloat(n.paddingBottom)||0);he.current=!0,fe.current?.(t.offsetHeight+r),e.scrollTop=e.scrollHeight},t[26]=de,t[27]=ge);let _e;t[28]!==P||t[29]!==de||t[30]!==j||t[31]!==A?(_e=[de,j,A,P],t[28]=P,t[29]=de,t[30]=j,t[31]=A,t[32]=_e):_e=t[32],Z.useLayoutEffect(ge,_e);let ve,ye;t[33]===Symbol.for(`react.memo_cache_sentinel`)?(ve=()=>()=>{he.current&&(he.current=!1,fe.current?.(null))},ye=[],t[33]=ve,t[34]=ye):(ve=t[33],ye=t[34]),Z.useEffect(ve,ye);let be,xe;if(t[35]===de?(be=t[36],xe=t[37]):(be=()=>{if(!de)return;let e=oe.current?.closest(`[data-chat-input-footer="true"]`);e&&e.offsetHeight>0&&ue(e.offsetHeight)},xe=[de],t[35]=de,t[36]=be,t[37]=xe),Z.useLayoutEffect(be,xe),!C||!y)return null;let Se=A!==`idle`,Ce;t[38]===L?Ce=t[39]:(Ce=e=>{w.current=e,L()},t[38]=L,t[39]=Ce);let we=Ce,Te;t[40]===z?Te=t[41]:(Te=()=>{w.current=`insert`,z()},t[40]=z,t[41]=Te);let Ee=Te,De;bb0:{if(A===`failed`){De=``;break bb0}if(A===`uploading`){let e;t[42]===_?e=t[43]:(e=_(`chat.dictation.processing`),t[42]=_,t[43]=e),De=e;break bb0}if(H){let e;t[44]!==ee||t[45]!==_?(e=ee===null?_(`chat.dictation.downloadingModel`):_(`chat.dictation.downloadingModelProgress`,{percent:String(ee)}),t[44]=ee,t[45]=_,t[46]=e):e=t[46],De=e;break bb0}let e;t[47]===_?e=t[48]:(e=_(`chat.dictation.listening`),t[47]=_,t[48]=e),De=e}let Oe=De,ke;t[49]===Symbol.for(`react.memo_cache_sentinel`)?(ke={onMouseDown:lm,onPointerDownCapture:um},t[49]=ke):ke=t[49];let Ae=ke,je;t[50]!==S||t[51]!==c||t[52]!==i||t[53]!==o||t[54]!==Se||t[55]!==h||t[56]!==I||t[57]!==_?(je=h?(0,$.jsx)(`button`,{type:`button`,...Ae,className:i,onClick:()=>{I()},disabled:c||Se,title:S?`${_(`chat.dictation.start`)} (${S})`:_(`chat.dictation.start`),"aria-label":_(`chat.dictation.start`),children:(0,$.jsx)(X,{name:`mic`,className:Y(o,`text-current`)})}):null,t[50]=S,t[51]=c,t[52]=i,t[53]=o,t[54]=Se,t[55]=h,t[56]=I,t[57]=_,t[58]=je):je=t[58];let Me;t[59]!==B||t[60]!==R||t[61]!==we||t[62]!==v||t[63]!==V||t[64]!==N||t[65]!==P||t[66]!==le||t[67]!==i||t[68]!==a||t[69]!==o||t[70]!==Se||t[71]!==r||t[72]!==H||t[73]!==j||t[74]!==Oe||t[75]!==n||t[76]!==Ee||t[77]!==s||t[78]!==A||t[79]!==_||t[80]!==m||t[81]!==M?(Me=Se?(0,$.jsxs)(`div`,{ref:oe,className:Y(`absolute inset-0 z-50 flex flex-col overflow-x-hidden overflow-y-hidden`,r&&`oc-composer-morph-content-fade`),style:{borderRadius:n,backgroundColor:v.colors.surface.subtle},role:`dialog`,"aria-label":_(`chat.dictation.overlayAria`),children:[m,(0,$.jsx)(`div`,{ref:se,className:Y(`scrollbar-none flex-1 min-h-0 overflow-y-auto px-3`,r?`pt-3.5 pb-2.5`:`pt-5 pb-2`),children:(0,$.jsxs)(`div`,{ref:ce,className:Y(!j&&`translate-y-1.5`),children:[j?(0,$.jsx)(`p`,{className:`typography-markdown md:typography-ui-label whitespace-pre-wrap`,style:{color:v.colors.surface.foreground},children:j}):A===`recording`?(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,style:{color:v.colors.surface.mutedForeground},children:[(0,$.jsx)(rm,{volume:M}),(0,$.jsx)(`p`,{className:`typography-markdown md:typography-ui-label`,children:Oe})]}):(0,$.jsx)(`p`,{className:`typography-markdown md:typography-ui-label`,style:{color:v.colors.surface.mutedForeground},children:Oe}),A===`failed`?(0,$.jsx)(`p`,{className:`typography-meta mt-1`,style:{color:v.colors.status.error},children:P||_(`chat.dictation.failed`)}):null,A===`recording`&&P&&!H?(0,$.jsx)(`p`,{className:`typography-meta mt-1`,style:{color:v.colors.status.warning},children:P}):null]})}),(0,$.jsxs)(`div`,{className:Y(`flex flex-shrink-0 items-center gap-x-3`,a),style:le?{height:le}:void 0,children:[A===`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:v.colors.status.error}}),(0,$.jsx)(`span`,{className:`relative inline-flex h-2 w-2 rounded-full`,style:{backgroundColor:v.colors.status.error}})]}),(0,$.jsx)(rm,{volume:M}),(0,$.jsx)(`span`,{className:`typography-meta tabular-nums`,style:{color:v.colors.surface.mutedForeground},children:nm(N)})]}):A===`uploading`?(0,$.jsx)(X,{name:`loader-4`,className:`ml-1 h-4 w-4 animate-spin`,style:{color:v.colors.surface.mutedForeground}}):null,(0,$.jsx)(`div`,{className:Y(`ml-auto flex items-center`,r?`gap-x-1`:`gap-x-1.5 md:gap-x-3`),children:A===`recording`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,...Ae,className:Y(i,`text-muted-foreground hover:text-foreground`),onClick:()=>{R()},title:_(`chat.dictation.cancel`),"aria-label":_(`chat.dictation.cancel`),children:(0,$.jsx)(X,{name:`close`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...Ae,className:i,onClick:()=>we(`insert`),title:_(`chat.dictation.insert`),"aria-label":_(`chat.dictation.insert`),children:(0,$.jsx)(X,{name:`check`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...Ae,className:Y(i,`text-primary hover:text-primary`),onClick:()=>we(`send`),title:_(`chat.dictation.insertAndSend`),"aria-label":_(`chat.dictation.insertAndSend`),children:(0,$.jsx)(X,{name:`send-plane-2`,className:s})})]}):A===`uploading`?(0,$.jsx)(`button`,{type:`button`,...Ae,className:Y(i,`text-muted-foreground hover:text-foreground`),onClick:()=>{R()},title:_(`chat.dictation.cancel`),"aria-label":_(`chat.dictation.cancel`),children:(0,$.jsx)(X,{name:`close`,className:o})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,...Ae,className:Y(i,`text-muted-foreground hover:text-foreground`),onClick:V,title:_(`chat.dictation.discard`),"aria-label":_(`chat.dictation.discard`),children:(0,$.jsx)(X,{name:`close`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...Ae,className:i,onClick:Ee,title:_(`chat.dictation.retry`),"aria-label":_(`chat.dictation.retry`),children:(0,$.jsx)(X,{name:`refresh`,className:o})}),j.trim()?(0,$.jsx)(`button`,{type:`button`,...Ae,className:i,onClick:()=>{w.current=`insert`,B()},title:_(`chat.dictation.insert`),"aria-label":_(`chat.dictation.insert`),children:(0,$.jsx)(X,{name:`check`,className:o})}):null]})})]})]}):null,t[59]=B,t[60]=R,t[61]=we,t[62]=v,t[63]=V,t[64]=N,t[65]=P,t[66]=le,t[67]=i,t[68]=a,t[69]=o,t[70]=Se,t[71]=r,t[72]=H,t[73]=j,t[74]=Oe,t[75]=n,t[76]=Ee,t[77]=s,t[78]=A,t[79]=_,t[80]=m,t[81]=M,t[82]=Me):Me=t[82];let Ne;return t[83]!==je||t[84]!==Me?(Ne=(0,$.jsxs)($.Fragment,{children:[je,Me]}),t[83]=je,t[84]=Me,t[85]=Ne):Ne=t[85],Ne};function om(e){return e.dictationEnabled}function sm(e){return e.shortcutOverrides}function cm(){return!x()&&qp()}function lm(e){return e.preventDefault()}function um(e){e.pointerType===`touch`&&e.preventDefault()}var dm=2e3,fm=Ye((e,t)=>({pending:!1,expiresAt:null,arm:(t=dm)=>{let n=Date.now()+t;return e({pending:!0,expiresAt:n}),n},clear:()=>{!t().pending&&t().expiresAt===null||e({pending:!1,expiresAt:null})}})),pm=new class{inFlightByScope=new WeakMap;generationByScope=new WeakMap;run(e){let t=this.inFlightByScope.get(e.scope);t||(t=new Map,this.inFlightByScope.set(e.scope,t));let n=t.get(e.key);if(n)return n;let r=this.generationByScope.get(e.scope);r||(r=new Map,this.generationByScope.set(e.scope,r));let i=(r.get(e.key)??0)+1;r.set(e.key,i);let a=e.request(()=>r?.get(e.key)!==i);return t.set(e.key,a),a.finally(()=>{t?.get(e.key)===a&&t.delete(e.key)}).catch(()=>{}),a}},mm=15e3,hm=100,gm=new Map,_m=new Map,vm=e=>`${e.runtimeKey}\n${e.directory}\n${e.sessionID}`,ym=e=>{let t=vm(e),n=e.now??Date.now(),r=_m.get(t);if(r&&n-r.loadedAt<mm)return Promise.resolve(r.sessions);let i=gm.get(t);if(i)return i;let a=e.request().then(e=>{for(_m.delete(t);_m.size>=hm;){let e=_m.keys().next().value;if(typeof e!=`string`)break;_m.delete(e)}return _m.set(t,{loadedAt:Date.now(),sessions:e}),e});return gm.set(t,a),a.then(()=>{gm.get(t)===a&&gm.delete(t)},()=>{gm.get(t)===a&&gm.delete(t)}),a},bm=(e,t)=>e.id<t.id?-1:+(e.id>t.id),xm=(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(bm)},Sm=30;function Cm(e){return e===`busy`||e===`retry`}var wm=new Map;function Tm(e,t=!1){return{limit:e.loadedTurns,cursor:e.kind===`has-more`?e.cursor:void 0,complete:e.kind===`exhausted`,loading:t}}function Em(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`){let t=e.message;if(typeof t==`string`&&t.length>0)return t}try{return JSON.stringify(e)}catch{return String(e)}}function Dm(e,t){if(!e.error)return;let n=e.response?.status;throw Error(`${t} failed${n?` (${n})`:``}: ${Em(e.error)}`)}function Om(e,t){let n=Ni();if(!n)return!1;let r=n.getTranscript(yi(e,t));return r.messageOrder.length!==0&&r.messageOrder.length>Sn()}function km(e){return!!e.force||!e.hasSession||e.shouldLoadMessages}function Am(e,t,n){let r=[...e.getState().session],i=Lr.search(r,t,e=>e.id);i.found?r[i.index]=n:r.splice(i.index,0,n),e.setState({session:r})}function jm(){let e=Wi(),t=Zr(),n=Un(),r=(0,Z.useCallback)((t,n=e)=>`${n}\n${t}`,[e]),i=(0,Z.useCallback)((t,n=e)=>{let r=Ni();if(!r||!t)return Tm({kind:`unknown`,loadedTurns:0},!1);let i=yi(n,t),a=r.getPagination(i),o=r.getRequestState?.(i);return Tm(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}};kn(a,t),Ln(r,t),r.setState(a);for(let n of t)Hi(e,n)},[n]),o=(0,Z.useCallback)((t=e)=>{let n=wm.get(t);if(n)return wm.delete(t),wm.set(t,n),n;let r=new Set;for(wm.set(t,r);wm.size>Sm;){let e=wm.keys().next().value;if(!e)break;let t=[...wm.get(e)??[]];wm.delete(e),a(e,t)}return r},[e,a]),c=(0,Z.useCallback)((r,i=e)=>{let s=i===e?t:n.ensureChild(i,{bootstrap:!1}),c=o(i),l=Cn(s.getState()),u=Rr(),d=gr({seen:c,keep:r,limit:u,preserve:l});if(a(i,d),On()){let e=new Set([r,...c,...l]),t=(Ni()?.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:Om(i,t));if(n.length>0){for(let e of n)c.delete(e);a(i,n)}}},[n,e,o,a,t]),l=(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 La(a,r):await aa(a,r)}catch{return}if(i?.isStale?.())return;let u=Ni()?.getTranscript(yi(a,r));Qn({directory:a,sessionID:r,store:o,transcript:u,isStale:i?.isStale}),await cn({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]),u=(0,Z.useCallback)(async(t,i)=>{await wn();let a=typeof i==`boolean`?i:i?.force,o=typeof i==`object`?i.directory??e:e,s=n.ensureChild(o,{bootstrap:!1}),u=mt.getScopedSdkClient(o);c(t,o);let d=r(t,o);return pm.run({scope:s,key:d,request:async e=>{let n=s.getState(),r=Ni(),i=yi(o,t),c=r?.hasSession?.(i)??(r?.getTranscript(i).messageOrder.length??0)>0,d=r?.getPagination(i)?.boundary??{kind:`unknown`,loadedTurns:0},f=Lr.search(n.session,t,e=>e.id).found,p=r?.getRequestState?.(i);if(!a&&c&&d.kind!==`unknown`&&p?.status!==`error`&&f&&na(o,t)){Qn({directory:o,sessionID:t,store:s,isStale:e});return}let m=!!(a||!c||f),h=km({hasSession:f,shouldLoadMessages:m,force:!!a});await Promise.all([h?(async()=>{try{let n=await Zn(async()=>{let e=await u.session.get({sessionID:t,directory:o});return Dm(e,`session.get`),e});if(n.data&&!e()){let r=Ta(n.data);e()||Am(s,t,r)}}catch(e){console.error(`[sync] failed to fetch session`,t,e)}})():Promise.resolve(),m?l(t,{isStale:e,directory:o}):Promise.resolve()])}})},[n,r,c,l,e]),d=(0,Z.useCallback)(async(t,r)=>{let i=r||e;if(!t||!i)return;let a=n.ensureChild(i,{bootstrap:!1}),o=mt.getScopedSdkClient(i),c=await ym({runtimeKey:s(),directory:i,sessionID:t,request:async()=>{let e=await o.session.children({sessionID:t,directory:i});return Dm(e,`session.children`),e.data??[]}});a.setState(e=>{let n=xm(e.session,c,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;Ci(yi(n,t.sessionID),{type:`optimistic-add`,message:t.message,parts:t.parts})},[e]),g=(0,Z.useCallback)(t=>{let n=t.directory||e;Ci(yi(n,t.sessionID),{type:`optimistic-remove`,messageID:t.messageID})},[e]),_=(0,Z.useCallback)(t=>{let n=t.directory||e;Ci(yi(n,t.sessionID),{type:`optimistic-confirm`,messageID:t.messageID})},[e]),v=(0,Z.useCallback)(async(t,r)=>{if(!t)return;await wn();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(Cm(o))throw Error(`refresh transcript busy`);try{await Li(i,t),Qn({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:u,syncSession:u,loadChildren:d,hasMore:f,isLoading:p,isComplete:m,refreshSessionTranscript:v,optimistic:{add:h,remove:g,confirm:_}}),[u,d,f,p,m,v,h,g,_])}var Mm=e=>e===`diff`||e===`file`||e===`preview-console`||e===`preview-annotation`,Nm=e=>e===`original`||e===`modified`,Pm=e=>{let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.floor(t)):null},Fm=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.sessionKey!=`string`||t.sessionKey.trim().length===0||!Mm(t.source))return null;let n=Pm(t.startLine),r=Pm(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:Nm(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()}},Im=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(Fm).filter(e=>!!e).filter(t=>t.sessionKey===e);t.length>0&&(n[e]=t)}return n},Lm=Ye()(Ze(Xe((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:y(),version:1,migrate:e=>!e||typeof e!=`object`?{drafts:{}}:{drafts:Im(e.drafts)}}),{name:`inline-comment-draft-store`}));function Rm(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 zm(e){return e.length===0?``:e.every(e=>e.source===`preview-annotation`)?e.map(Rm).join(`
5
5
 
@@ -6523,7 +6523,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,C as n,E as r,J
6523
6523
  `))r.startsWith(`+`)&&!r.startsWith(`+++`)&&t++,r.startsWith(`-`)&&!r.startsWith(`---`)&&n++;return{added:t,removed:n}},ob=e=>{let t=[],n=new Set;for(let r of e){if(r.type!==`tool`||!nb.has(r.tool))continue;let e=r.state;if(e.status&&e.status!==`completed`)continue;let i=t.length,a=e.metadata,o=Array.isArray(a?.files)?a.files:[];for(let e of o){if(!e||typeof e!=`object`)continue;let i=e,a=i.relativePath||i.filePath||``;!a||n.has(a)||(n.add(a),t.push({path:a,tool:r.tool,partId:r.id,messageID:r.messageID,additions:ib(i.additions)??void 0,deletions:ib(i.deletions)??void 0,patch:typeof i.patch==`string`?i.patch:void 0}))}if(o.length===0&&a?.filediff&&typeof a.filediff==`object`){let e=a.filediff,i=typeof e.file==`string`?e.file:``;i&&!n.has(i)&&(n.add(i),t.push({path:i,tool:r.tool,partId:r.id,messageID:r.messageID,additions:ib(e.additions)??void 0,deletions:ib(e.deletions)??void 0,patch:typeof e.patch==`string`?e.patch:void 0}))}if(o.length===0&&Array.isArray(a?.results))for(let e of a.results){if(!e||typeof e!=`object`)continue;let i=e.filediff;if(!i||typeof i!=`object`)continue;let a=typeof i.file==`string`?i.file:``;!a||n.has(a)||(n.add(a),t.push({path:a,tool:r.tool,partId:r.id,messageID:r.messageID,additions:ib(i.additions)??void 0,deletions:ib(i.deletions)??void 0,patch:typeof i.patch==`string`?i.patch:void 0}))}if(t.length===i){let i=e.input,a=typeof i?.filePath==`string`?i.filePath:typeof i?.file_path==`string`?i.file_path:typeof i?.path==`string`?i.path:void 0;a&&!n.has(a)&&(n.add(a),t.push({path:a,tool:r.tool,partId:r.id,messageID:r.messageID}))}if(t.length===i){let e=typeof a?.patch==`string`?a.patch.trim():typeof a?.diff==`string`?a.diff.trim():``;if(e&&!n.has(`Diff`)){n.add(`Diff`);let i=ab(e);t.push({path:`Diff`,tool:r.tool,partId:r.id,messageID:r.messageID,additions:i.added,deletions:i.removed})}}}return t},sb=(e,t,n)=>{let r=[];for(let i of e){let e=i.index?.trim()??``,a=i.working_dir?.trim()??``,o=!!(e&&e!==`?`),s=!!(a||e===`?`),c=a||e;if(!c||c===`!`)continue;let l=t?.[i.path];r.push({path:ru(n,i.path),relativePath:i.path,insertions:l?.insertions??0,deletions:l?.deletions??0,status:c,hasStagedChanges:o,hasWorkingChanges:s})}return r},cb=e=>{for(let t of e){let e=t.index?.trim()??``,n=(t.working_dir?.trim()??``)||e;if(!(!n||n===`!`))return!0}return!1},lb=(e,t)=>nu(e,t),ub=(e,t)=>{let n=rb(e)&&e.relativePath?e.relativePath:lb(e.path,t);return{fileName:n.split(`/`).pop()??n,dirPart:n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)):``}},db=e=>rb(e)?{additions:e.insertions,deletions:e.deletions}:{additions:e.additions??0,deletions:e.deletions??0},fb=2;function pb(e){let t=e.lastIndexOf(`.`);return t<=0||t===e.length-1?{stem:e,ext:``}:{stem:e.slice(0,t),ext:e.slice(t)}}function mb(e,t=fb){let n=e??``,r=n.startsWith(`/`),i=n.split(`/`).filter(Boolean);if(i.length===0)return{prefix:``,parent:``,stem:``,ext:``,name:``,leadingSlash:r};let a=i[i.length-1]??``,{stem:o,ext:s}=pb(a),c=Math.max(1,Math.floor(t)),l=Math.min(i.length-1,c-1),u=i.length-1-l,d=l>0?i.slice(u,-1).join(`/`):``,f=i.slice(0,u).join(`/`),p=f?r?`/${f}`:f:``;return{prefix:p,parent:d,stem:o,ext:s,name:a,leadingSlash:r&&!p}}function hb(e){let t=(0,Q.c)(36),{path:n,className:r,title:i,dirClassName:a,nameClassName:o}=e,s=a===void 0?`text-muted-foreground`:a,c=o===void 0?`text-foreground`:o,l;t[0]===n?l=t[1]:(l=mb(n),t[0]=n,t[1]=l);let{prefix:u,parent:d,stem:f,ext:p,leadingSlash:m}=l,h=!!(u||d),g;t[2]===r?g=t[3]:(g=Y(`flex min-w-0 items-baseline overflow-hidden`,r),t[2]=r,t[3]=g);let _=i??n,v;t[4]!==s||t[5]!==m?(v=m?(0,$.jsx)(`span`,{className:Y(`shrink-0`,s),children:`/`}):null,t[4]=s,t[5]=m,t[6]=v):v=t[6];let y;t[7]!==s||t[8]!==u?(y=u?(0,$.jsx)(`span`,{className:Y(`min-w-0 shrink-[9999] truncate`,s),children:u}):null,t[7]=s,t[8]=u,t[9]=y):y=t[9];let b;t[10]!==s||t[11]!==d||t[12]!==u?(b=d?(0,$.jsxs)(`span`,{className:Y(`shrink-0`,s),children:[u?`/`:``,d]}):null,t[10]=s,t[11]=d,t[12]=u,t[13]=b):b=t[13];let x;t[14]!==s||t[15]!==h?(x=h?(0,$.jsx)(`span`,{className:s,children:`/`}):null,t[14]=s,t[15]=h,t[16]=x):x=t[16];let S;t[17]===c?S=t[18]:(S=Y(`min-w-0 truncate`,c),t[17]=c,t[18]=S);let C;t[19]!==f||t[20]!==S?(C=(0,$.jsx)(`span`,{className:S,children:f}),t[19]=f,t[20]=S,t[21]=C):C=t[21];let w;t[22]!==p||t[23]!==c?(w=p?(0,$.jsx)(`span`,{className:Y(`shrink-0`,c),children:p}):null,t[22]=p,t[23]=c,t[24]=w):w=t[24];let T;t[25]!==C||t[26]!==w||t[27]!==x?(T=(0,$.jsxs)(`span`,{className:`flex min-w-0 shrink items-baseline`,children:[x,C,w]}),t[25]=C,t[26]=w,t[27]=x,t[28]=T):T=t[28];let E;return t[29]!==T||t[30]!==g||t[31]!==_||t[32]!==v||t[33]!==y||t[34]!==b?(E=(0,$.jsxs)(`span`,{className:g,title:_,children:[v,y,b,T]}),t[29]=T,t[30]=g,t[31]=_,t[32]=v,t[33]=y,t[34]=b,t[35]=E):E=t[35],E}var gb=e=>{let t=(0,Q.c)(23),{files:n,currentDirectory:r,onOpenFile:i}=e,{t:a}=Zt(),o;t[0]===a?o=t[1]:(o=a(`chat.changedFiles.title`),t[0]=a,t[1]=o);let s;t[2]===o?s=t[3]:(s=(0,$.jsx)(`span`,{className:ou,children:o}),t[2]=o,t[3]=s);let c;t[4]===n.length?c=t[5]:(c=(0,$.jsx)(`span`,{className:du,children:n.length}),t[4]=n.length,t[5]=c);let l;t[6]!==s||t[7]!==c?(l=(0,$.jsxs)(`div`,{className:Ou,children:[s,c]}),t[6]=s,t[7]=c,t[8]=l):l=t[8];let u;if(t[9]!==r||t[10]!==n||t[11]!==i||t[12]!==a){let e;t[14]!==r||t[15]!==i||t[16]!==a?(e=(e,t)=>{let{fileName:n,dirPart:o}=ub(e,r),s=db(e);return(0,$.jsxs)(`button`,{type:`button`,className:Y(`relative flex w-full cursor-pointer items-center gap-2.5 outline-hidden select-none text-left hover:bg-interactive-hover`,fu),title:a(`chat.changedFiles.actions.openFileTitle`,{path:e.path}),onClick:()=>i(e),children:[(0,$.jsx)(xh,{filePath:e.path,className:`h-3 w-3 shrink-0 md:h-3.5 md:w-3.5`}),(0,$.jsx)(hb,{path:o?`${o}/${n}`:n,title:e.path,className:`min-w-0 flex-1`}),s.additions>0||s.deletions>0?(0,$.jsxs)(`span`,{className:`flex-shrink-0 inline-flex items-baseline gap-1 text-xs tabular-nums leading-4 md:text-[0.8125rem] md:leading-5`,children:[s.additions>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,s.additions]}):null,s.deletions>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-error)`},children:[`-`,s.deletions]}):null]}):null]},`${e.path}:${t}`)},t[14]=r,t[15]=i,t[16]=a,t[17]=e):e=t[17],u=n.map(e),t[9]=r,t[10]=n,t[11]=i,t[12]=a,t[13]=u}else u=t[13];let d;t[18]===u?d=t[19]:(d=(0,$.jsx)(`div`,{className:Du,children:u}),t[18]=u,t[19]=d);let f;return t[20]!==l||t[21]!==d?(f=(0,$.jsxs)($.Fragment,{children:[l,d]}),t[20]=l,t[21]=d,t[22]=f):f=t[22],f},_b=`${mu} origin-[var(--transform-origin)]`,vb=cu,yb=Z.memo(()=>{let e=(0,Q.c)(60),{t}=Zt(),[n,r]=Z.useState(!1),i=Z.useRef(null),a=Ul()??null,o=Z.useContext(ac),s=Vc(a),c;e[0]===a?c=e[1]:(c=e=>a?e.directories.get(a)?.status??null:null,e[0]=a,e[1]=c);let l=Tc(c),u=Pu(),d,f;e[2]===n?(d=e[3],f=e[4]):(d=()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},f=[n],e[2]=n,e[3]=d,e[4]=f),Z.useEffect(d,f);let p;bb0:{if(!a||s!==!0||!l||l.isClean){let t;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[5]=t):t=e[5],p=t;break bb0}let t;e[6]!==a||e[7]!==l.diffStats||e[8]!==l.files?(t=sb(l.files,l.diffStats,a),e[6]=a,e[7]=l.diffStats,e[8]=l.files,e[9]=t):t=e[9],p=t}let m=p,h=0,_=0;if(e[10]!==h||e[11]!==m||e[12]!==_){for(let e of m)h+=e.insertions,_+=e.deletions;e[10]=h,e[11]=m,e[12]=_,e[13]=h,e[14]=_}else h=e[13],_=e[14];let v;e[15]!==h||e[16]!==_?(v={totalAdded:h,totalRemoved:_},e[15]=h,e[16]=_,e[17]=v):v=e[17];let{totalAdded:y,totalRemoved:b}=v;if(!a||s!==!0||m.length===0)return null;let x;e[18]!==a||e[19]!==u||e[20]!==o?.editor?(x=e=>{if(!a||!rb(e))return;r(!1);let t=e.path;if(u){u.openChanges({diffPath:e.relativePath,staged:e.hasStagedChanges&&!e.hasWorkingChanges});return}let n=o?.editor;if(n){n.openFile(t);return}let i=g.getState(),s=e.hasStagedChanges&&!e.hasWorkingChanges;if(!i.isMobile){i.openContextDiff(a,e.relativePath,s);return}i.navigateToDiff(e.relativePath,s),i.setRightSidebarOpen(!1)},e[18]=a,e[19]=u,e[20]=o?.editor,e[21]=x):x=e[21];let S=x,C=m.length,w;e[22]!==C||e[23]!==t?(w=t(C===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:C}),e[22]=C,e[23]=t,e[24]=w):w=e[24];let T=w,E,D;e[25]===Symbol.for(`react.memo_cache_sentinel`)?(E=Y(su,`max-w-full text-left`),D=()=>r(bb),e[25]=E,e[26]=D):(E=e[25],D=e[26]);let O,k;e[27]===Symbol.for(`react.memo_cache_sentinel`)?(k=(0,$.jsx)(X,{name:`file-edit`,className:uu}),O=Y(bu,`shrink-0`),e[27]=O,e[28]=k):(O=e[27],k=e[28]);let A;e[29]===T?A=e[30]:(A=(0,$.jsx)(`span`,{className:O,children:T}),e[29]=T,e[30]=A);let j;e[31]===Symbol.for(`react.memo_cache_sentinel`)?(j=Y(`status-row__changed-label`,bu),e[31]=j):j=e[31];let M;e[32]===t?M=e[33]:(M=t(`chat.pendingChanges.changedInWorkspace`),e[32]=t,e[33]=M);let N;e[34]===M?N=e[35]:(N=(0,$.jsx)(`span`,{className:j,children:M}),e[34]=M,e[35]=N);let P;e[36]===Symbol.for(`react.memo_cache_sentinel`)?(P=Y(au,`items-baseline gap-0.5`),e[36]=P):P=e[36];let F;e[37]===y?F=e[38]:(F=y>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,y]}):null,e[37]=y,e[38]=F);let I;e[39]===b?I=e[40]:(I=b>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-error)`},children:[`-`,b]}):null,e[39]=b,e[40]=I);let L;e[41]!==F||e[42]!==I?(L=(0,$.jsxs)(`span`,{className:P,children:[F,I]}),e[41]=F,e[42]=I,e[43]=L):L=e[43];let R;e[44]===n?R=e[45]:(R=n?(0,$.jsx)(X,{name:`arrow-up-s`,className:uu}):(0,$.jsx)(X,{name:`arrow-down-s`,className:uu}),e[44]=n,e[45]=R);let z;e[46]!==n||e[47]!==A||e[48]!==N||e[49]!==L||e[50]!==R?(z=(0,$.jsxs)(`button`,{type:`button`,className:E,onClick:D,"aria-expanded":n,children:[k,A,N,L,R]}),e[46]=n,e[47]=A,e[48]=N,e[49]=L,e[50]=R,e[51]=z):z=e[51];let B;e[52]!==a||e[53]!==m||e[54]!==S||e[55]!==n?(B=n&&(0,$.jsx)(`div`,{style:vb,className:Y(_b,`absolute left-0 bottom-full mb-1 z-50`,`animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2`,`duration-150`),children:(0,$.jsx)(gb,{files:m,currentDirectory:a,onOpenFile:S})}),e[52]=a,e[53]=m,e[54]=S,e[55]=n,e[56]=B):B=e[56];let V;return e[57]!==z||e[58]!==B?(V=(0,$.jsxs)(`div`,{className:`relative`,ref:i,children:[z,B]}),e[57]=z,e[58]=B,e[59]=V):V=e[59],V});yb.displayName=`PendingChangesBar`;function bb(e){return!e}var xb=Z.memo(e=>{let t=(0,Q.c)(22),{visible:n,onClick:r,placement:i}=e,a=i===void 0?`default`:i,{t:o}=Zt(),s=a===`compact`;if(s&&!n)return null;let c=a==="default"&&`absolute left-1/2 bottom-full mb-2 -translate-x-1/2`,l=a===`expanded`&&`absolute left-1/2 -translate-x-1/2 oc-scroll-to-bottom--expanded mb-2`,u=a===`compact`&&`oc-scroll-to-bottom--compact relative shrink-0`,d;t[0]!==a||t[1]!==c||t[2]!==l||t[3]!==u||t[4]!==n?(d=Y(c,l,u,n?Y(`pointer-events-auto`,a==="default"&&`opacity-100`):Y(`opacity-0 pointer-events-none`,a===`expanded`&&`oc-scroll-to-bottom--hidden`)),t[0]=a,t[1]=c,t[2]=l,t[3]=u,t[4]=n,t[5]=d):d=t[5];let f=s?`ghost`:`outline`,p=s?`composer-mobile-actions h-8 w-8 rounded-none bg-transparent hover:bg-transparent text-foreground`:`size-8 rounded-full [corner-shape:round] bg-background/95 hover:bg-interactive-hover`,m;t[6]===p?m=t[7]:(m=Y(`p-0 shadow-none`,p),t[6]=p,t[7]=m);let h;t[8]===o?h=t[9]:(h=o(`chat.scrollToBottom.aria`),t[8]=o,t[9]=h);let g=s?`size-5`:`size-4`,_=s?`medium`:`regular`,v;t[10]!==g||t[11]!==_?(v=(0,$.jsx)(X,{name:`arrow-down`,className:g,weight:_}),t[10]=g,t[11]=_,t[12]=v):v=t[12];let y;t[13]!==r||t[14]!==v||t[15]!==f||t[16]!==m||t[17]!==h?(y=(0,$.jsx)(yo,{variant:f,size:`sm`,onClick:r,className:m,"aria-label":h,children:v}),t[13]=r,t[14]=v,t[15]=f,t[16]=m,t[17]=h,t[18]=y):y=t[18];let b;return t[19]!==y||t[20]!==d?(b=(0,$.jsx)(`div`,{className:d,children:y}),t[19]=y,t[20]=d,t[21]=b):b=t[21],b}),Sb=Z.createContext(`default`),Cb=()=>Z.useContext(Sb),wb=500,Tb=e=>{let t=(0,Q.c)(31),{onCycleAgent:n,onOpenAgentPanel:r,className:i,agentName:a,agents:o,disabled:s}=e,c;t[0]===o?c=t[1]:(c=o===void 0?[]:o,t[0]=o,t[1]=c);let l=c,u=s!==void 0&&s,d=a??void 0,f;t[2]!==l||t[3]!==d?(f=rr(l,d),t[2]=l,t[3]=d,t[4]=f):f=t[4];let p=f,m=fv(d),h;t[5]===d?h=t[6]:(h=uo(d),t[5]=d,t[6]=h);let g=h,_=Z.useRef(null),v=Z.useRef(!1),y;t[7]!==u||t[8]!==r?(y=e=>{e.preventDefault(),!u&&(v.current=!1,_.current=setTimeout(()=>{v.current=!0,r()},wb))},t[7]=u,t[8]=r,t[9]=y):y=t[9];let b=y,x;t[10]!==u||t[11]!==n?(x=()=>{_.current&&=(clearTimeout(_.current),null),!u&&!v.current&&n()},t[10]=u,t[11]=n,t[12]=x):x=t[12];let S=x,C;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(C=()=>{_.current&&=(clearTimeout(_.current),null)},t[13]=C):C=t[13];let w=C,T,E;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(E=()=>()=>{_.current&&clearTimeout(_.current)},T=[],t[14]=T,t[15]=E):(T=t[14],E=t[15]),Z.useEffect(E,T);let D;t[16]===i?D=t[17]:(D=Y(`inline-flex flex-shrink-0 items-center select-none focus:outline-none touch-none disabled:cursor-not-allowed disabled:opacity-40`,yv,i),t[16]=i,t[17]=D);let O;t[18]===Symbol.for(`react.memo_cache_sentinel`)?(O={height:`26px`,maxHeight:`26px`,minHeight:`26px`},t[18]=O):O=t[18];let k;t[19]!==g.var||t[20]!==p||t[21]!==d||t[22]!==m?(k=(0,$.jsx)(dv,{name:d,label:p,revealed:m,avatarSize:16,slotClassName:`h-[26px] w-6`,colorVar:g.var}),t[19]=g.var,t[20]=p,t[21]=d,t[22]=m,t[23]=k):k=t[23];let A;return t[24]!==p||t[25]!==u||t[26]!==b||t[27]!==S||t[28]!==D||t[29]!==k?(A=(0,$.jsx)(`button`,{type:`button`,disabled:u,onPointerDown:b,onPointerUp:S,onPointerLeave:w,onContextMenu:Eb,onMouseDown:Db,className:D,style:O,title:p,"aria-label":p,children:k}),t[24]=p,t[25]=u,t[26]=b,t[27]=S,t[28]=D,t[29]=k,t[30]=A):A=t[30],A};function Eb(e){return e.preventDefault()}function Db(e){return e.preventDefault()}var Ob=e=>{let t=(0,Q.c)(28),{onOpenModel:n,className:r,providerID:i,modelID:a,provider:o,variant:s,disabled:c}=e,l=c!==void 0&&c,{t:u}=Zt(),d;t[0]!==a||t[1]!==o||t[2]!==u?(d=io(o,a,u(`chat.modelControls.selectModel`)),t[0]=a,t[1]=o,t[2]=u,t[3]=d):d=t[3];let f=d,p;t[4]===s?p=t[5]:(p=s?.trim()?Gn(s):null,t[4]=s,t[5]=p);let m=p,h=m?`${f} ${m}`:f,g;t[6]===r?g=t[7]:(g=Y(`inline-flex min-w-0 max-w-36 items-stretch`,`rounded-lg`,`focus:outline-none hover:bg-[var(--interactive-hover)] disabled:cursor-not-allowed disabled:opacity-40`,r),t[6]=r,t[7]=g);let _;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(_={height:`26px`,maxHeight:`26px`,minHeight:`26px`},t[8]=_):_=t[8];let v;t[9]!==a||t[10]!==i?(v=a||i?(0,$.jsx)(Do,{modelId:a,providerId:i,className:`size-4 flex-shrink-0`}):null,t[9]=a,t[10]=i,t[11]=v):v=t[11];let y;t[12]===f?y=t[13]:(y=(0,$.jsx)(`span`,{className:`truncate text-[11px] leading-none font-medium text-foreground/80`,children:f}),t[12]=f,t[13]=y);let b;t[14]===m?b=t[15]:(b=m?(0,$.jsx)(`span`,{className:`shrink-0 text-[11px] leading-none font-normal text-muted-foreground`,children:m}):null,t[14]=m,t[15]=b);let x;t[16]!==y||t[17]!==b?(x=(0,$.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-1`,children:[y,b]}),t[16]=y,t[17]=b,t[18]=x):x=t[18];let S;t[19]!==v||t[20]!==x?(S=(0,$.jsxs)(`span`,{className:`flex h-full w-full min-w-0 items-center gap-1`,children:[v,x]}),t[19]=v,t[20]=x,t[21]=S):S=t[21];let C;return t[22]!==h||t[23]!==l||t[24]!==n||t[25]!==S||t[26]!==g?(C=(0,$.jsx)(`button`,{type:`button`,disabled:l,onClick:n,onMouseDown:kb,onPointerDownCapture:Ab,className:g,style:_,title:h,"aria-label":h,children:S}),t[22]=h,t[23]=l,t[24]=n,t[25]=S,t[26]=g,t[27]=C):C=t[27],C};function kb(e){return e.preventDefault()}function Ab(e){e.preventDefault()}var jb={phase:`idle`,isWorking:!1,isBusy:!1,isCooldown:!1},Mb=e=>e.hasPendingAssistant?e.messages.some(e=>e.role===`assistant`&&typeof e.time?.completed==`number`):!1;function Nb(e,t){let n=(0,Q.c)(6),r=sa(e??``,t),i=za(e??``,t),a=Yi(e??``,t),o=Na(e??``,t),s=Ti(e??``,t),c=ki(t),l;bb0:{if(!e){l=jb;break bb0}if(o.length>0||s.length>0){l=jb;break bb0}let t=r?.type??`idle`,u=a[a.length-1],d=!!(u&&u.role===`assistant`&&typeof u.time?.completed!=`number`),f=a,p;n[0]!==d||n[1]!==f?(p=Mb({messages:f,hasPendingAssistant:d}),n[0]=d,n[1]=f,n[2]=p):p=n[2];let m=p,h=u?.time?.created,g=!!(m&&typeof c==`number`&&typeof h==`number`&&h<=c),_=r!==void 0,v=_&&t!==`idle`,y=v||m&&!g;if(_&&!v&&(!m||_&&!v&&typeof i==`number`&&typeof h==`number`&&h<=i)){l=jb;break bb0}if(!y){l=jb;break bb0}let b=v?t:`busy`,x=t===`busy`||!v&&m,S;n[3]!==b||n[4]!==x?(S={phase:b,isWorking:!0,isBusy:x,isCooldown:!1},n[3]=b,n[4]=x,n[5]=S):S=n[5],l=S}return l}var Pb=e=>!(!e.sessionId||e.composerSurfaceKind===`secondary`||e.hasSessionEntity||e.hasRenderableSessionSnapshot),Fb=e=>{let t=e.isSubagentSession&&!e.allowPromptingSubagentSessions;return{showReadOnlyBanner:e.isSubagentSession&&(e.readOnly||t),blockSubmission:e.sessionIdentityPending}},Ib=(e,t)=>({agentName:t.agentName??e?.agentName,providerId:t.providerId??e?.providerId,modelId:t.modelId??e?.modelId}),Lb=(e,t)=>e.id===t.id&&e.directory===t.directory,Rb=(e,t)=>e.agentName===t.agentName&&e.providerId===t.providerId&&e.modelId===t.modelId,zb=(e,t,n,r)=>{if(!t)return null;let i=n??(e?.viewKey===t?e.parentTarget:null);if(!i)return null;let a=Ib(e?.viewKey===t?e.execution:void 0,r);return e&&e.viewKey===t&&Lb(e.parentTarget,i)&&Rb(e.execution,a)?e:{viewKey:t,parentTarget:i,execution:a}},Bb=e=>{let{inFlight:t,establishing:n}=e.sendPhase,r=!n&&(e.draftSubmitting||t);return{sendDisabled:!e.canSend||!e.hasSessionTarget||e.submissionBlocked||r,queueDisabled:!e.hasSessionTarget||e.submissionBlocked||!n&&t||e.queueFrozen&&!e.queueFallbackAvailable,disabledClass:`opacity-30 pointer-events-none`}},Vb=`data-mobile-overlay-active`,Hb=e=>Array.from(e).some(e=>e.getAttribute(Vb)!==`false`),Ub=`artful.bionic.cosmic.disco.focal.groovy.jammy.kinetic.lunar.noble.bold.brave.calm.eager.gentle.happy.keen.lively.merry.swift.warm.wise.bright.clever.daring.agile.crisp.fresh.lucid.quick.sharp.vivid.zealous`.split(`.`),Wb=`aardvark.beaver.chipmunk.dolphin.falcon.gopher.hedgehog.jackal.koala.lemur.mongoose.narwhal.otter.pangolin.quokka.raccoon.salamander.toucan.walrus.yak.zebra.badger.condor.dingo.egret.ferret.gecko.heron.iguana`.split(`.`);function Gb(){return`${Ub[Math.floor(Math.random()*Ub.length)]}-${Wb[Math.floor(Math.random()*Wb.length)]}`}function Kb(e){let t=Gb();return e&&e.trim()?`${e.trim().replace(/\/+$/,``)}/${t}`:t}var qb=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||e,Jb=e=>({agentName:e.currentAgentName,providerId:e.currentProviderId,modelId:e.currentModelId,variant:e.currentVariant}),Yb=(e,t,n)=>{let r=t.agentName?.trim()||void 0,i=t.providerId?.trim()||void 0,a=t.modelId?.trim()||void 0;!r||!i||!a||(n.saveSessionAgentSelection(e,r),n.saveSessionModelSelection(e,i,a),n.saveAgentModelForSession(e,r,i,a),n.saveAgentModelVariantForSession(e,r,i,a,t.variant))},Xb=async(e,t)=>{await ar(e)&&await ti(t)},Zb=e=>{let t=qb(e),n=Gi.getState().projects;if(n.length===0)return null;let r=Gi.getState().getActiveProject();if(r?.path){let e=qb(r.path);if(t===e||t.startsWith(`${e}/`))return{id:r.id,path:r.path}}let i=n.filter(e=>{let n=qb(e.path);return t===n||t.startsWith(`${n}/`)}).sort((e,t)=>qb(t.path).length-qb(e.path).length)[0];return i?{id:i.id,path:i.path}:null},Qb=!1,$b=async(e,t)=>{try{let n=Gi.getState().projects.find(e=>e.id===t.id)??Gi.getState().projects.find(e=>qb(e.path)===qb(t.path)),r=ei(t.path);await ui.getState().activateDirectory(t.path,{source:`worktreeSessionCreator`});let i=ui.getState();if(i.activeDirectoryKey!==r||i.providers.length===0||i.agents.length===0)return;i.applyDefaultModelAgentSelection({projectDefaultModel:n?.defaultModel??void 0}),Yb(e,Jb(ui.getState()),Nn.getState())}catch{}},ex=async(e,t,n)=>{let r=J.getState(),i=ui.getState();r.initializeNewOpenChamberSession(e,i.agents),r.setSessionDirectory(e,t.path),r.setWorktreeMetadata(e,t),await $b(e,n),lt.getState().setDirectory(t.path,{showOverlay:!1})},tx=e=>e.trim().replace(/^remotes\//,``).replace(/[^A-Za-z0-9._/-]+/g,`-`).replace(/\/+/g,`-`).replace(/-+/g,`-`).replace(/^-+|-+$/g,``)||`worktree`,nx=async e=>{if(Qb)return null;let t=Gi.getState().getActiveProject(),n=e?.projectDirectory?.trim()||t?.path;if(!n)return fa.error(`No active project`,{description:`Please select a project first.`}),null;let r=Zb(n)??(t?.path?{id:t.id,path:t.path}:null);if(!r)return fa.error(`No active project`,{description:`Please select a project first.`}),null;let i=!1;try{i=await xo(r.path)}catch{}if(!i)return fa.error(`Not a Git repository`,{description:`Worktrees can only be created in Git repositories.`}),null;Qb=!0;try{let t=di(),n=e?.existingBranch?.trim().replace(/^remotes\//,``)||``,i=n?tx(n):Kb(),a=n?`existing`:`new`,o=J.getState();o.newSessionDraft?.open?o.overrideNewSessionDraftTarget({projectId:r.id,directoryOverride:o.newSessionDraft.directoryOverride??r.path,pendingWorktreeRequestId:t,preserveDirectoryOverride:!0,title:e?.title,initialPrompt:e?.initialPrompt}):o.openNewSessionDraft({selectedProjectId:r.id,directoryOverride:r.path,pendingWorktreeRequestId:t,preserveDirectoryOverride:!0,title:e?.title,initialPrompt:e?.initialPrompt});let s=await bo(r.path,{mode:a,...a===`new`?{branchName:i,worktreeName:i}:{existingBranch:n,worktreeName:i}}).catch(()=>null);s?.path&&(J.getState().overrideNewSessionDraftTarget({projectId:r.id,directoryOverride:s.path,pendingWorktreeRequestId:t,bootstrapPendingDirectory:s.path,preserveDirectoryOverride:!0,title:e?.title,initialPrompt:e?.initialPrompt}),lt.getState().setDirectory(s.path,{showOverlay:!1}));let c=await qn(r),l=await Ec(r,{preferredName:i,mode:a,worktreeName:i,setupCommands:c,returnAfterDirectoryCreated:!0,...a===`new`?{branchName:i}:{existingBranch:n}});return sn(t,l.path),J.getState().overrideNewSessionDraftTarget({projectId:r.id,directoryOverride:l.path,pendingWorktreeRequestId:null,bootstrapPendingDirectory:l.path,preserveDirectoryOverride:!0,title:e?.title,initialPrompt:e?.initialPrompt}),lt.getState().setDirectory(l.path,{showOverlay:!1}),l.path}catch(e){let t=e instanceof Error?e.message:`Failed to create worktree`,n=J.getState().newSessionDraft.pendingWorktreeRequestId;return n&&(Tr(n,e instanceof Error?e:Error(t)),J.getState().resolvePendingDraftWorktreeTarget(n,null)),J.getState().setDraftBootstrapPendingDirectory(null),fa.error(`Failed to create worktree`,{description:t}),null}finally{Qb=!1}};async function rx(){return nx()}async function ix(e){let t=e.branch?.trim();return t?nx({existingBranch:t,projectDirectory:e.projectDirectory,initialPrompt:e.initialPrompt,title:e.title}):null}async function ax(e,t,n,r){if(Qb)return null;Qb=!0;try{let i=n?.trim()||`HEAD`,a=t?.trim();if(!a)throw Error(`Branch name is required`);let o=r?.kind??`standard`,s=Zb(e);if(!s)throw Error(`Project is not registered in OpenChamber`);let c=!1;try{c=await xo(s.path)}catch{}if(!c)return fa.error(`Not a Git repository`,{description:`Worktrees can only be created in Git repositories.`}),null;let l=await qn(s),u=await Fo(s.path);try{let e=await Ec(s,{preferredName:a,mode:`new`,branchName:a,worktreeName:r?.worktreeName||a,startRef:i,setUpstream:r?.setUpstream,upstreamRemote:r?.upstreamRemote,upstreamBranch:r?.upstreamBranch,ensureRemoteName:r?.ensureRemoteName,ensureRemoteUrl:r?.ensureRemoteUrl,setupCommands:l,returnAfterDirectoryCreated:r?.returnAfterDirectoryCreated}),t={...e,createdFromBranch:r?.createdFromBranch||u||i,kind:o};await Xb(s,e.path);let n=await J.getState().createSession(void 0,e.path);if(!n)throw await zo(s,e,{deleteLocalBranch:!0}).catch(()=>void 0),Error(`Could not create a session for the worktree.`);return await ex(n.id,t,s),{id:n.id,branch:e.branch||a,path:e.path}}catch(e){let t=e instanceof Error?e.message:`Failed to create worktree session`;return fa.error(`Failed to create worktree`,{description:t}),null}}finally{Qb=!1}}var ox=e=>{let t=e.trim();if(!t)return null;let n=t.match(/\/issues\/(\d+)(?:\b|\/|$)/i);if(n){let e=Number(n[1]);return Number.isFinite(e)&&e>0?e:null}let r=t.match(/^#?(\d+)$/);if(r){let e=Number(r[1]);return Number.isFinite(e)&&e>0?e:null}return null},sx=e=>{let t={repo:e.repo??null,issue:e.issue,comments:e.comments};return`GitHub issue context (JSON)\n${JSON.stringify(t,null,2)}`};function cx({open:e,onOpenChange:t,mode:n=`createSession`,onSelect:r}){let{t:i}=Zt(),{github:a}=ic(),o=Ls(),s=o.data??null,c=o.isFetched,l=g(e=>e.setSettingsDialogOpen),u=g(e=>e.setSettingsPage),d=g(e=>e.isMobile),{isTablet:f}=Ws(),p=d||f,m=Gi(e=>e.getActiveProject()),h=lt(e=>e.currentDirectory),_=Z.useMemo(()=>m?.path?.trim()||h?.trim()||null,[m?.path,h]),[v,y]=Z.useState(``),[b,x]=Z.useState(!1),[S,C]=Z.useState(null),w=Z.useRef(0),T=Z.useMemo(()=>ox(v),[v]),E=_c(v,350),D=T?``:E.trim(),O=!!T||v===E,k=e&&O&&!!_&&!!a?.issuesList&&!(c&&s?.connected===!1),A=Ft({queryKey:ae.scoped(`github-issues`,_,D),enabled:k,initialPageParam:1,refetchOnMount:`always`,queryFn:({pageParam:e})=>a.issuesList(_,{page:e,...D?{query:D}:{}}),getNextPageParam:e=>e.hasMore?(e.page??1)+1:void 0}),j=O?A.data?.pages.at(-1)??null:null,M=O?A.data?.pages.flatMap(e=>e.issues??[])??[]:[],N=O&&A.hasNextPage,P=!T&&!O||A.isLoading,F=O&&A.isFetchingNextPage,I=O&&A.error?A.error instanceof Error?A.error.message:String(A.error):null,L=Z.useCallback(()=>A.refetch(),[A]),R=Z.useCallback(async()=>{try{await A.fetchNextPage()}catch(e){let t=e instanceof Error?e.message:String(e);fa.error(i(`session.githubIssuePicker.toast.loadMoreFailed`),{description:t})}},[A,i]);Z.useEffect(()=>{e||(++w.current,y(``),x(!1),C(null))},[e]),Z.useEffect(()=>{++w.current},[e,_]);let z=!c||s?.connected!==!1&&j?.connected!==!1,B=j?.repo?.url??null,V=Z.useCallback(()=>{u(`github`),l(!0)},[l,u]),H=Z.useCallback(()=>{let e=ui.getState(),t=e.getVisibleAgents();if(e.settingsDefaultAgent){let n=t.find(t=>t.name===e.settingsDefaultAgent);if(n)return n.name}return t.find(e=>e.name===`build`)?.name||t[0]?.name},[]),ee=Z.useCallback(()=>{let e=ui.getState(),t=e.settingsDefaultModel;if(!t)return null;let n=Qi(t);if(!n)return null;let{providerId:r,modelId:i}=n;return e.getModelMetadata(r,i)?{providerID:r,modelID:i}:null},[]),U=Z.useCallback((e,t)=>{let n=ui.getState(),r=n.settingsDefaultVariant,i=n.currentProviderId===e&&n.currentModelId===t?n.currentVariant:void 0,a=n.providers.find(t=>t.id===e)?.models.find(e=>e.id===t)?.variants;if(!a)return r||i||void 0;if(r&&Object.prototype.hasOwnProperty.call(a,r))return r;if(i&&Object.prototype.hasOwnProperty.call(a,i))return i},[]),te=Z.useCallback(async(e,o)=>{let s=++w.current,c=()=>w.current===s;if(n===`select`){if(!_){fa.error(i(`session.githubIssuePicker.error.noActiveProject`));return}if(!a?.issueGet||!a?.issueComments){fa.error(i(`session.githubIssuePicker.error.runtimeUnavailable`));return}if(S)return;C(e);try{let n=await a.issueGet(_,e,{sourceRepo:o});if(!c())return;if(n.connected===!1){fa.error(i(`session.githubIssuePicker.error.notConnected`));return}if(!n.repo){fa.error(i(`session.githubIssuePicker.error.repoNotResolvable`),{description:i(`session.githubIssuePicker.error.repoMustBeGithub`)});return}let s=n.issue;if(!s){fa.error(i(`session.githubIssuePicker.error.issueNotFound`));return}let l=await a.issueComments(_,e,{sourceRepo:o});if(!c())return;if(l.connected===!1){fa.error(i(`session.githubIssuePicker.error.notConnected`));return}let u=l.comments??[],d=sx({repo:n.repo,issue:s,comments:u});r&&r({number:s.number,title:s.title,url:s.url,contextText:d,author:s.author?{login:s.author.login,avatarUrl:s.author.avatarUrl}:void 0}),t(!1)}catch(e){if(!c())return;let t=e instanceof Error?e.message:String(e);fa.error(i(`session.githubIssuePicker.toast.loadIssueDetailsFailed`),{description:t})}finally{c()&&C(null)}return}if(!_){fa.error(i(`session.githubIssuePicker.error.noActiveProject`));return}if(!a?.issueGet||!a?.issueComments){fa.error(i(`session.githubIssuePicker.error.runtimeUnavailable`));return}if(!S){C(e);try{let n=await a.issueGet(_,e,{sourceRepo:o});if(!c())return;if(n.connected===!1){fa.error(i(`session.githubIssuePicker.error.notConnected`));return}if(!n.repo){fa.error(i(`session.githubIssuePicker.error.repoNotResolvable`),{description:i(`session.githubIssuePicker.error.repoMustBeGithub`)});return}let r=n.issue;if(!r){fa.error(i(`session.githubIssuePicker.error.issueNotFound`));return}let s=await a.issueComments(_,e,{sourceRepo:o});if(!c())return;if(s.connected===!1){fa.error(i(`session.githubIssuePicker.error.notConnected`));return}let l=s.comments??[],u=`#${r.number} ${r.title}`.trim(),{sessionId:d}=await(async()=>{if(b){let e=`issue-${r.number}-${Gb()}`,t=await ax(_,e,void 0,{returnAfterDirectoryCreated:!0});if(!t?.id)throw Error(`Failed to create worktree session`);return{sessionId:t.id,sessionDirectory:t.path}}let e=await In(u,_,null);if(!e?.id)throw Error(`Failed to create session`);return{sessionId:e.id,sessionDirectory:e.directory??_}})();if(!c())return;er(d,u).catch(()=>void 0);try{J.getState().initializeNewOpenChamberSession(d,ui.getState().agents)}catch{}t(!1);let f=ui.getState(),p=Nn.getState().lastUsedProvider,m=ee(),h=m?.providerID||f.currentProviderId||p?.providerID,g=m?.modelID||f.currentModelId||p?.modelID,v=H()||f.currentAgentName||void 0;if(!h||!g){fa.error(i(`session.githubIssuePicker.error.noModelSelected`));return}let y=U(h,g),x=await Ur(`github.issue.review.visible`,{issue_number:String(r.number)});if(!c())return;let S=await Ur(`github.issue.review.instructions`);if(!c())return;let C=sx({repo:n.repo,issue:r,comments:l});J.getState().sendMessage(x,h,g,v,void 0,void 0,[{text:S,synthetic:!0},{text:C,synthetic:!0}],y,void 0,{sessionId:d}).catch(e=>{let t=e instanceof Error?e.message:String(e);fa.error(i(`session.githubIssuePicker.toast.sendContextFailed`),{description:t})}),fa.success(i(`session.githubIssuePicker.toast.sessionCreated`))}catch(e){if(!c())return;let t=e instanceof Error?e.message:String(e);fa.error(i(`session.githubIssuePicker.toast.startSessionFailed`),{description:t})}finally{c()&&C(null)}}},[b,a,n,t,r,_,H,ee,U,S,i]),W=i(n===`select`?`session.githubIssuePicker.title.select`:`session.githubIssuePicker.title.createSession`),ne=i(n===`select`?`session.githubIssuePicker.description.select`:`session.githubIssuePicker.description.createSession`),G=(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[(0,$.jsx)(X,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),(0,$.jsx)(Yo,{placeholder:i(`session.githubIssuePicker.searchPlaceholder`),value:v,onChange:e=>{y(e.target.value)},className:`pl-9 w-full`})]}),(0,$.jsxs)(`div`,{className:Y(d?`min-h-0 mt-2`:`flex-1 overflow-y-auto mt-2`),children:[_?null:(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:i(`session.githubIssuePicker.empty.noActiveProject`)}),a?null:(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:i(`session.githubIssuePicker.empty.runtimeUnavailable`)}),P?(0,$.jsxs)(`div`,{className:`text-center text-muted-foreground py-8 flex items-center justify-center gap-2`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),i(`session.githubIssuePicker.loading.issues`)]}):null,z===!1?(0,$.jsxs)(`div`,{className:`text-center text-muted-foreground py-8 space-y-3`,children:[(0,$.jsx)(`div`,{children:i(`session.githubIssuePicker.empty.notConnected`)}),(0,$.jsx)(`div`,{className:`flex justify-center`,children:(0,$.jsx)(yo,{variant:`outline`,size:`sm`,onClick:V,children:i(`session.githubIssuePicker.actions.openSettings`)})})]}):null,I?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8 break-words`,children:I}):null,T&&_&&a&&z?(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,S===T&&`bg-interactive-selection/30`),onClick:()=>void te(T),children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground w-5 text-right flex-shrink-0`,children:`#`}),(0,$.jsx)(`p`,{className:`flex-1 min-w-0 typography-small text-foreground truncate ml-0.5`,children:i(`session.githubIssuePicker.actions.useIssue`,{number:T})}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:S===T?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`}):null})]}):null,M.length===0&&!P&&!I&&z&&a&&_?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:E.trim()?i(`session.githubIssuePicker.empty.noIssuesFound`):i(`session.githubIssuePicker.empty.noOpenIssuesFound`)}):null,M.map(e=>(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,S===e.number&&`bg-interactive-selection/30`),onClick:()=>void te(e.number,e.sourceRepo),children:[(0,$.jsxs)(`span`,{className:`typography-meta text-muted-foreground w-12 text-right flex-shrink-0`,children:[`#`,e.number]}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 ml-0.5`,children:[(0,$.jsx)(`p`,{className:`typography-small text-foreground truncate`,children:e.title}),e.sourceRepo?.source===`upstream`?(0,$.jsxs)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info mt-0.5 inline-block`,children:[e.sourceRepo.owner,`/`,e.sourceRepo.repo]}):null]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:S===e.number?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`}):(0,$.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:Y(`h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,p?`flex`:`hidden group-hover:flex`),onClick:e=>e.stopPropagation(),"aria-label":i(`session.githubIssuePicker.actions.openInGitHubAria`),children:(0,$.jsx)(X,{name:`external-link`,className:`h-4 w-4`})})})]},`${e.sourceRepo?.owner??``}-${e.sourceRepo?.repo??``}-${e.number}`)),N&&z&&_&&a?(0,$.jsx)(`div`,{className:`py-2 flex justify-center`,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>void R(),disabled:F||!!S,className:Y(`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4`,(F||!!S)&&`opacity-50 cursor-not-allowed hover:text-muted-foreground`),children:F?(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),i(`session.githubIssuePicker.loading.more`)]}):i(`session.githubIssuePicker.actions.loadMore`)})}):null]}),n!==`select`&&(0,$.jsxs)(`div`,{className:`mt-4 p-3 bg-muted/30 rounded-lg`,children:[(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground font-medium mb-2`,children:i(`session.githubIssuePicker.actions.sectionTitle`)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 cursor-pointer`,role:`button`,tabIndex:0,"aria-pressed":b,onClick:()=>x(e=>!e),onKeyDown:e=>{(e.key===` `||e.key===`Enter`)&&(e.preventDefault(),x(e=>!e))},children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.preventDefault(),e.stopPropagation(),x(e=>!e)},"aria-label":i(`session.githubIssuePicker.actions.toggleWorktreeAria`),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary`,children:b?(0,$.jsx)(X,{name:`checkbox`,className:`h-4 w-4 text-primary`}):(0,$.jsx)(X,{name:`checkbox-blank`,className:`h-4 w-4`})}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:i(`session.githubIssuePicker.actions.createInWorktree`)}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/70 hidden sm:inline`,children:`(issue-<number>-<slug>)`})]}),(0,$.jsx)(`div`,{className:`hidden sm:block sm:flex-1`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[B?(0,$.jsx)(yo,{variant:`outline`,size:`sm`,asChild:!0,children:(0,$.jsxs)(`a`,{href:B,target:`_blank`,rel:`noopener noreferrer`,children:[(0,$.jsx)(X,{name:`external-link`,className:`size-4`}),i(`session.githubIssuePicker.actions.openRepo`)]})}):null,(0,$.jsx)(yo,{variant:`outline`,size:`sm`,onClick:L,disabled:P||!!S,children:i(`session.githubIssuePicker.actions.refresh`)})]})]})]})]});return d?(0,$.jsx)(cv,{open:e,title:W,onClose:()=>t(!1),renderHeader:e=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 px-3 py-2 border-b border-border/40`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`typography-ui-label font-semibold text-foreground`,children:W}),e]}),(0,$.jsx)(`p`,{className:`typography-small text-muted-foreground`,children:ne})]}),children:G}):(0,$.jsx)(go,{open:e,onOpenChange:t,children:(0,$.jsxs)(fo,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:[(0,$.jsxs)(co,{className:`flex-shrink-0`,children:[(0,$.jsxs)(po,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`github`,className:`h-5 w-5`}),W]}),(0,$.jsx)(mo,{children:ne})]}),G]})})}var lx=e=>{let t=e.trim();if(!t)return null;let n=t.match(/\/pull\/(\d+)(?:\b|\/|$)/i);if(n){let e=Number(n[1]);return Number.isFinite(e)&&e>0?e:null}let r=t.match(/^#?(\d+)$/);if(r){let e=Number(r[1]);return Number.isFinite(e)&&e>0?e:null}return null},ux=e=>`GitHub pull request context (JSON)\n${JSON.stringify(e,null,2)}`;function dx({open:e,onOpenChange:t,onSelect:n}){let{t:r}=Zt(),{github:i}=ic(),a=Ls(),o=a.data??null,s=a.isFetched,c=g(e=>e.setSettingsDialogOpen),l=g(e=>e.setSettingsPage),u=g(e=>e.isMobile),{isTablet:d}=Ws(),f=u||d,p=Gi(e=>e.getActiveProject())?.path??null,[m,h]=Z.useState(``),[_,v]=Z.useState(!1),[y,b]=Z.useState(null),x=Z.useRef(0),S=Z.useMemo(()=>lx(m),[m]),C=_c(m,350),w=S?``:C.trim(),T=!!S||m===C,E=e&&T&&!!p&&!!i?.prsList&&!(s&&o?.connected===!1),D=Ft({queryKey:ae.scoped(`github-prs`,p,w),enabled:E,initialPageParam:1,refetchOnMount:`always`,queryFn:({pageParam:e})=>i.prsList(p,{page:e,...w?{query:w}:{}}),getNextPageParam:e=>e.hasMore?(e.page??1)+1:void 0}),O=T?D.data?.pages.at(-1)??null:null,k=T?D.data?.pages.flatMap(e=>e.prs??[])??[]:[],A=T&&D.hasNextPage,j=!S&&!T||D.isLoading,M=T&&D.isFetchingNextPage,N=T&&D.error?D.error instanceof Error?D.error.message:String(D.error):null,P=q(async()=>{try{await D.fetchNextPage()}catch(e){let t=e instanceof Error?e.message:String(e);fa.error(r(`session.githubPrPicker.toast.loadMoreFailed`),{description:t})}});Z.useEffect(()=>{e||(++x.current,h(``),v(!1),b(null))},[e]),Z.useEffect(()=>{++x.current},[e,p]);let F=!s||o?.connected!==!1&&O?.connected!==!1,I=q(()=>{l(`github`),c(!0)}),L=q(async(e,a)=>{if(!p){fa.error(r(`session.githubPrPicker.error.noActiveProject`));return}if(!i?.prContext){fa.error(r(`session.githubPrPicker.error.runtimeUnavailable`));return}if(y)return;let o=++x.current,s=()=>x.current===o;b(e);try{let o=await i.prContext(p,e,{includeDiff:_,includeCheckDetails:!1,sourceRepo:a});if(!s())return;if(o.connected===!1){fa.error(r(`session.githubPrPicker.error.notConnected`));return}if(!o.pr){fa.error(r(`session.githubPrPicker.error.prNotFound`));return}if(!o.repo){fa.error(r(`session.githubPrPicker.error.repoNotResolvable`),{description:r(`session.githubPrPicker.error.repoMustBeGithub`)});return}if(n){let e=await Ur(`github.pr.review.instructions`);if(!s())return;n({number:o.pr.number,title:o.pr.title,url:o.pr.url,head:o.pr.head,base:o.pr.base,includeDiff:_,instructionsText:e,contextText:ux(o),author:o.pr.author?{login:o.pr.author.login,avatarUrl:o.pr.author.avatarUrl}:void 0})}t(!1)}catch(e){if(!s())return;let t=e instanceof Error?e.message:String(e);fa.error(r(`session.githubPrPicker.toast.loadDetailsFailed`),{description:t})}finally{s()&&b(null)}}),R=r(`session.githubPrPicker.title`),z=r(`session.githubPrPicker.description`),B=(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`mt-2 flex items-center gap-3`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1 min-w-0`,children:[(0,$.jsx)(X,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),(0,$.jsx)(Yo,{placeholder:r(`session.githubPrPicker.searchPlaceholder`),value:m,onChange:e=>{h(e.target.value)},className:`pl-9 w-full`})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),className:`h-9 shrink-0 flex items-center gap-2 text-left`,"aria-pressed":_,"aria-label":r(`session.githubPrPicker.includeDiffAria`),children:[(0,$.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,$.jsx)(jo,{checked:_,onChange:e=>v(e),ariaLabel:r(`session.githubPrPicker.includeDiffAria`)})}),(0,$.jsx)(`span`,{className:`typography-small text-muted-foreground whitespace-nowrap`,children:r(`session.githubPrPicker.includeDiff`)})]})]}),(0,$.jsxs)(`div`,{className:Y(u?`min-h-0`:`flex-1 overflow-y-auto`),children:[p?null:(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:r(`session.githubPrPicker.empty.noActiveProject`)}),i?null:(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:r(`session.githubPrPicker.empty.runtimeUnavailable`)}),j?(0,$.jsxs)(`div`,{className:`text-center text-muted-foreground py-8 flex items-center justify-center gap-2`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),r(`session.githubPrPicker.loading.pullRequests`)]}):null,F===!1?(0,$.jsxs)(`div`,{className:`text-center text-muted-foreground py-8 space-y-3`,children:[(0,$.jsx)(`div`,{children:r(`session.githubPrPicker.empty.notConnected`)}),(0,$.jsx)(`div`,{className:`flex justify-center`,children:(0,$.jsx)(yo,{variant:`outline`,size:`sm`,onClick:I,children:r(`session.githubPrPicker.actions.openSettings`)})})]}):null,N?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8 break-words`,children:N}):null,S&&p&&i&&F?(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,y===S&&`bg-interactive-selection/30`),onClick:()=>void L(S),children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground w-5 text-right flex-shrink-0`,children:`#`}),(0,$.jsx)(`p`,{className:`flex-1 min-w-0 typography-small text-foreground truncate ml-0.5`,children:r(`session.githubPrPicker.actions.usePullRequest`,{number:S})}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:y===S?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`}):null})]}):null,k.length===0&&!j&&!N&&F&&i&&p?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:C.trim()?r(`session.githubPrPicker.empty.noPullRequestsFound`):r(`session.githubPrPicker.empty.noOpenPullRequestsFound`)}):null,k.map(e=>(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,y===e.number&&`bg-interactive-selection/30`),onClick:()=>void L(e.number,e.sourceRepo),children:[(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 ml-0.5`,children:[(0,$.jsxs)(`p`,{className:`typography-small text-foreground truncate`,children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground mr-1`,children:[`#`,e.number]}),e.title]}),e.sourceRepo?.source===`upstream`?(0,$.jsxs)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info`,children:[e.sourceRepo.owner,`/`,e.sourceRepo.repo]}):null,(0,$.jsxs)(`p`,{className:`typography-meta text-muted-foreground truncate`,children:[e.head,` → `,e.base]})]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:y===e.number?(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`}):(0,$.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:Y(`h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,f?`flex`:`hidden group-hover:flex`),onClick:e=>e.stopPropagation(),"aria-label":r(`session.githubPrPicker.actions.openInGitHubAria`),children:(0,$.jsx)(X,{name:`external-link`,className:`h-4 w-4`})})})]},`${e.sourceRepo?.owner??``}-${e.sourceRepo?.repo??``}-${e.number}`)),A&&F&&p&&i?(0,$.jsx)(`div`,{className:`py-2 flex justify-center`,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>void P(),disabled:M||!!y,className:Y(`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4`,(M||!!y)&&`opacity-50 cursor-not-allowed hover:text-muted-foreground`),children:M?(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),r(`session.githubPrPicker.loading.more`)]}):r(`session.githubPrPicker.actions.loadMore`)})}):null]})]});return u?(0,$.jsx)(cv,{open:e,title:R,onClose:()=>t(!1),renderHeader:e=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 px-3 py-2 border-b border-border/40`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`typography-ui-label font-semibold text-foreground`,children:R}),e]}),(0,$.jsx)(`p`,{className:`typography-small text-muted-foreground`,children:z})]}),children:B}):(0,$.jsx)(go,{open:e,onOpenChange:t,children:(0,$.jsxs)(fo,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:[(0,$.jsxs)(co,{className:`flex-shrink-0`,children:[(0,$.jsxs)(po,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`github`,className:`h-5 w-5`}),R]}),(0,$.jsx)(mo,{children:z})]}),B]})})}function fx(e){let t=(0,Q.c)(12),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({className:n,style:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a;t[4]===i?a=t[5]:(a={color:`var(--surface-elevated-foreground)`,...i},t[4]=i,t[5]=a);let o;t[6]===n?o=t[7]:(o=Y(`flex h-full w-full flex-col overflow-hidden rounded-xl`,n),t[6]=n,t[7]=o);let s;return t[8]!==r||t[9]!==a||t[10]!==o?(s=(0,$.jsx)(Fu,{"data-slot":`command`,style:a,className:o,...r}),t[8]=r,t[9]=a,t[10]=o,t[11]=s):s=t[11],s}var px=Z.forwardRef((e,t)=>{let n=(0,Q.c)(11),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a,o;n[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=Y(`flex h-8 items-center gap-2 rounded-lg px-3`,`bg-[var(--surface-elevated)] ring-1 ring-inset ring-border/60 transition duration-200 ease-out`,`hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)] hover:[&:not(:focus-within)]:ring-transparent`,`focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]`),o=(0,$.jsx)(X,{name:`search`,className:`size-4 shrink-0 opacity-50`}),n[3]=a,n[4]=o):(a=n[3],o=n[4]);let s;n[5]===r?s=n[6]:(s=Y(`placeholder:text-muted-foreground flex h-8 w-full bg-transparent typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50`,r),n[5]=r,n[6]=s);let c;return n[7]!==i||n[8]!==t||n[9]!==s?(c=(0,$.jsx)(`div`,{"data-slot":`command-input-wrapper`,className:`p-1.5 pb-1`,children:(0,$.jsxs)(`div`,{"data-slot":`command-input-field`,className:a,children:[o,(0,$.jsx)(Fu.Input,{ref:t,"data-slot":`command-input`,className:s,...i})]})}),n[7]=i,n[8]=t,n[9]=s,n[10]=c):c=n[10],c});px.displayName=`CommandInput`;function mx(e){let t=(0,Q.c)(14),n,r,i,a,o;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5]):({className:r,children:n,scrollbarClassName:o,disableHorizontal:i,...a}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o);let s;t[6]===r?s=t[7]:(s=Y(`scroll-py-1 overflow-x-hidden h-full min-h-0`,r),t[6]=r,t[7]=s);let c=o??`overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero`,l=i??!0,u;return t[8]!==n||t[9]!==a||t[10]!==s||t[11]!==c||t[12]!==l?(u=(0,$.jsx)(xl,{as:Fu.List,"data-slot":`command-list`,outerClassName:`max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0`,className:s,scrollbarClassName:c,disableHorizontal:l,...a,children:n}),t[8]=n,t[9]=a,t[10]=s,t[11]=c,t[12]=l,t[13]=u):u=t[13],u}function hx(e){let t=(0,Q.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,$.jsx)(Fu.Empty,{"data-slot":`command-empty`,className:`py-6 text-center typography-ui-label`,...n}),t[2]=n,t[3]=r),r}function gx(e){let t=(0,Q.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,$.jsx)(Fu.Group,{"data-slot":`command-group`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function _x(e){let t=(0,Q.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`bg-border -mx-1 h-px`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,$.jsx)(Fu.Separator,{"data-slot":`command-separator`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function vx(e){let t=(0,Q.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`data-[selected=true]:bg-interactive-selection data-[selected=true]:text-interactive-selection-foreground data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,$.jsx)(Fu.Item,{"data-slot":`command-item`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}var yx=(e,t)=>`${e}:${L(t)}`,bx=e=>e.type===`skill`||!Ae(e.name);function xx(e){let{t}=Zt(),n=Z.useMemo(()=>x(),[]),r=g(e=>e.globalDraftStarters),i=Gi(e=>e.activeProjectId),a=Gi(e=>e.projects),o=Z.useMemo(()=>{if(!i)return null;let e=a.find(e=>e.id===i);return e?.path?{id:e.id,path:e.path}:null},[i,a]),[s,c]=Z.useState([]),l=Z.useMemo(()=>r??Me,[r]),u=l.some(bx)||s.some(bx),d=da({directory:e,enabled:u}),f=Z.useMemo(()=>d.data??[],[d.data]),{refetch:p}=d,m=an({directory:e,enabled:u}),h=Z.useMemo(()=>m.data??[],[m.data]),{refetch:_}=m;Z.useEffect(()=>{let e=!1;if(!o){c([]);return}return Fn(o).then(t=>{e||c(t)}).catch(()=>{e||c([])}),()=>{e=!0}},[o?.id]);let v=Z.useCallback(()=>{p(),_()},[p,_]),y=Z.useMemo(()=>new Set(f.map(e=>e.name)),[f]),b=Z.useMemo(()=>new Set(h.map(e=>e.name)),[h]),S=Z.useCallback((e,r)=>{if(n&&e.type===`command`&&e.name===`craft-goal`)return null;if(e.type===`command`){let n=Ae(e.name);return n?{id:yx(r,e),ref:e,group:r,label:t(n.labelKey),icon:n.icon,submitText:n.command}:y.has(e.name)?{id:yx(r,e),ref:e,group:r,label:I(e.name),icon:Oe,submitText:`/${e.name}`}:null}return b.has(e.name)?{id:yx(r,e),ref:e,group:r,label:I(e.name),icon:K,submitText:`/${e.name}`}:null},[t,y,b,n]),w=Z.useMemo(()=>l.map(e=>S(e,`global`)).filter(e=>e!==null),[l,S]),T=Z.useMemo(()=>s.map(e=>S(e,`project`)).filter(e=>e!==null),[s,S]),E=Z.useMemo(()=>{let e=new Set;for(let t of l)e.add(L(t));for(let t of s)e.add(L(t));return e},[l,s]),D=Z.useMemo(()=>{let e=[];for(let r of ne)n&&r.name===`craft-goal`||e.push({type:`command`,name:r.name,label:t(r.labelKey),icon:r.icon,section:`built-in`,scope:`user`});for(let t of f)t.isBuiltIn||t.source===`skill`||Ae(t.name)||e.push({type:`command`,name:t.name,label:I(t.name),icon:Oe,section:`command`,scope:t.scope===`project`?`project`:`user`});for(let t of h)e.push({type:`skill`,name:t.name,label:I(t.name),icon:K,section:`skill`,scope:t.scope===`project`?`project`:`user`});return e.filter(e=>!E.has(`${e.type}:${e.name}`))},[t,f,h,E,n]),O=Z.useCallback(e=>{g.getState().setGlobalDraftStarters(e),Ce({draftStarters:e})},[]),k=Z.useCallback(e=>{c(e),o&&oo(o,e)},[o]),A=Z.useCallback(e=>{let t={type:e.type,name:e.name};if(e.scope===`project`){if(!o||s.some(e=>C(e,t)))return;k([...s,t])}else{let e=r??Me;if(e.some(e=>C(e,t)))return;O([...e,t])}},[o,s,r,k,O]),j=Z.useCallback((e,t)=>{e===`project`?k(s.filter(e=>!C(e,t))):O((r??Me).filter(e=>!C(e,t)))},[s,r,k,O]),M=Z.useCallback((e,t,n)=>{let i=e===`project`?s:r??Me,a=i.findIndex(n=>yx(e,n)===t),o=i.findIndex(t=>yx(e,t)===n);if(a<0||o<0||a===o)return;let c=Nl([...i],a,o);e===`project`?k(c):O(c)},[s,r,k,O]);return{global:w,project:T,pinnable:D,hasProject:!!o,ensureLoaded:v,addStarter:A,removeStarter:j,reorder:M}}var Sx=`__draft-starter-trash__`,Cx=`inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-[var(--interactive-hover)] hover:text-foreground`,wx=`max-h-7`,Tx=[{key:`built-in`,headingKey:`chat.draftStarters.sectionBuiltIn`},{key:`command`,headingKey:`chat.draftStarters.sectionCommands`},{key:`skill`,headingKey:`chat.draftStarters.sectionSkills`}],Ex=e=>{let t=(0,Q.c)(35),{item:n,onSubmit:r,onRemove:i,hideRemove:a}=e,{t:o}=Zt(),s;t[0]===n.id?s=t[1]:(s={id:n.id},t[0]=n.id,t[1]=s);let{attributes:c,listeners:l,setNodeRef:u,transform:d,transition:f,isDragging:p}=Pl(s),m;t[2]===d?m=t[3]:(m=jl.Translate.toString(d),t[2]=d,t[3]=m);let h;t[4]!==m||t[5]!==f?(h={transform:m,transition:f},t[4]=m,t[5]=f,t[6]=h):h=t[6];let g=p&&`z-10 opacity-60`,_;t[7]===g?_=t[8]:(_=Y(`group/chip relative`,g),t[7]=g,t[8]=_);let v;t[9]!==n.submitText||t[10]!==r?(v=()=>r(n.submitText),t[9]=n.submitText,t[10]=r,t[11]=v):v=t[11];let y=!a&&`pr-5`,b;t[12]===y?b=t[13]:(b=Y(`group inline-flex touch-none select-none items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors`,`hover:bg-[var(--interactive-hover)] hover:text-foreground`,y),t[12]=y,t[13]=b);let x;t[14]===n.icon?x=t[15]:(x=(0,$.jsx)(X,{name:n.icon,className:`h-3 w-3 shrink-0 opacity-60 transition-opacity group-hover:opacity-100`}),t[14]=n.icon,t[15]=x);let S;t[16]===n.label?S=t[17]:(S=(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:n.label}),t[16]=n.label,t[17]=S);let C;t[18]!==c||t[19]!==l||t[20]!==S||t[21]!==v||t[22]!==b||t[23]!==x?(C=(0,$.jsxs)(`button`,{type:`button`,...c,...l,onClick:v,className:b,children:[x,S]}),t[18]=c,t[19]=l,t[20]=S,t[21]=v,t[22]=b,t[23]=x,t[24]=C):C=t[24];let w;t[25]!==a||t[26]!==i||t[27]!==o?(w=a?null:(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i()},"aria-label":o(`chat.draftStarters.remove`),title:o(`chat.draftStarters.remove`),className:`absolute right-0.5 top-1/2 hidden h-4 w-4 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:text-foreground group-hover/chip:flex`,children:(0,$.jsx)(X,{name:`close`,className:`h-2.5 w-2.5`})}),t[25]=a,t[26]=i,t[27]=o,t[28]=w):w=t[28];let T;return t[29]!==u||t[30]!==C||t[31]!==w||t[32]!==h||t[33]!==_?(T=(0,$.jsxs)(`div`,{ref:u,style:h,className:_,children:[C,w]}),t[29]=u,t[30]=C,t[31]=w,t[32]=h,t[33]=_,t[34]=T):T=t[34],T},Dx=e=>{let t=(0,Q.c)(14),{items:n,onSubmit:r,onRemove:i,hideRemove:a}=e,o;t[0]===n?o=t[1]:(o=n.map(Mx),t[0]=n,t[1]=o);let s;if(t[2]!==a||t[3]!==n||t[4]!==i||t[5]!==r){let e;t[7]!==a||t[8]!==i||t[9]!==r?(e=e=>(0,$.jsx)(Ex,{item:e,onSubmit:r,onRemove:()=>i(e),hideRemove:a},e.id),t[7]=a,t[8]=i,t[9]=r,t[10]=e):e=t[10],s=n.map(e),t[2]=a,t[3]=n,t[4]=i,t[5]=r,t[6]=s}else s=t[6];let c;return t[11]!==o||t[12]!==s?(c=(0,$.jsx)(Il,{items:o,strategy:Ml,children:s}),t[11]=o,t[12]=s,t[13]=c):c=t[13],c},Ox=()=>{let e=(0,Q.c)(13),{t}=Zt(),n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n={id:Sx},e[0]=n):n=e[0];let{setNodeRef:r,isOver:i}=El(n),a;e[1]===t?a=e[2]:(a=t(`chat.draftStarters.remove`),e[1]=t,e[2]=a);let o;e[3]===t?o=e[4]:(o=t(`chat.draftStarters.remove`),e[3]=t,e[4]=o);let s=i&&`text-destructive hover:text-destructive`,c;e[5]===s?c=e[6]:(c=Y(Cx,s),e[5]=s,e[6]=c);let l;e[7]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,$.jsx)(X,{name:`delete-bin`,className:`h-3.5 w-3.5`}),e[7]=l):l=e[7];let u;return e[8]!==r||e[9]!==a||e[10]!==o||e[11]!==c?(u=(0,$.jsx)(`button`,{type:`button`,ref:r,"aria-label":a,title:o,className:c,children:l}),e[8]=r,e[9]=a,e[10]=o,e[11]=c,e[12]=u):u=e[12],u},kx=e=>{let t=(0,Q.c)(21),{pinnable:n,onPick:r,className:i}=e,{t:a}=Zt(),o;t[0]===i?o=t[1]:(o=Y(`min-h-0`,i),t[0]=i,t[1]=o);let s;t[2]===a?s=t[3]:(s=a(`chat.draftStarters.searchPlaceholder`),t[2]=a,t[3]=s);let c;t[4]===s?c=t[5]:(c=(0,$.jsx)(px,{placeholder:s}),t[4]=s,t[5]=c);let l;t[6]===a?l=t[7]:(l=a(`chat.draftStarters.empty`),t[6]=a,t[7]=l);let u;t[8]===l?u=t[9]:(u=(0,$.jsx)(hx,{children:l}),t[8]=l,t[9]=u);let d;t[10]!==r||t[11]!==n||t[12]!==a?(d=Tx.map(e=>{let t=n.filter(t=>t.section===e.key);return t.length===0?null:(0,$.jsx)(gx,{heading:a(e.headingKey),children:t.map(e=>(0,$.jsx)(vx,{value:`${e.section} ${e.label} ${e.name}`,onSelect:()=>r(e),children:(0,$.jsx)(`span`,{className:`truncate`,children:e.label})},`${e.type}:${e.name}`))},e.key)}),t[10]=r,t[11]=n,t[12]=a,t[13]=d):d=t[13];let f;t[14]!==u||t[15]!==d?(f=(0,$.jsxs)(mx,{children:[u,d]}),t[14]=u,t[15]=d,t[16]=f):f=t[16];let p;return t[17]!==o||t[18]!==c||t[19]!==f?(p=(0,$.jsxs)(fx,{className:o,children:[c,f]}),t[17]=o,t[18]=c,t[19]=f,t[20]=p):p=t[20],p},Ax=e=>{let t=(0,Q.c)(27),{pinnable:n,onOpen:r,onAdd:i}=e,{t:a}=Zt(),[o,s]=Z.useState(!1),c;t[0]===r?c=t[1]:(c=e=>{s(e),e&&r()},t[0]=r,t[1]=c);let l;t[2]===a?l=t[3]:(l=a(`chat.draftStarters.add`),t[2]=a,t[3]=l);let u;t[4]===a?u=t[5]:(u=a(`chat.draftStarters.add`),t[4]=a,t[5]=u);let d;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,$.jsx)(X,{name:`add`,className:`h-3.5 w-3.5`}),t[6]=d):d=t[6];let f;t[7]!==l||t[8]!==u?(f=(0,$.jsx)(ho,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,"aria-label":l,title:u,className:Cx,children:d})}),t[7]=l,t[8]=u,t[9]=f):f=t[9];let p;t[10]===a?p=t[11]:(p=a(`chat.draftStarters.add`),t[10]=a,t[11]=p);let m;t[12]===p?m=t[13]:(m=(0,$.jsx)(co,{className:`px-4 pb-2 pt-4 text-left`,children:(0,$.jsx)(po,{children:p})}),t[12]=p,t[13]=m);let h;t[14]===i?h=t[15]:(h=e=>{i(e),s(!1)},t[14]=i,t[15]=h);let g;t[16]!==n||t[17]!==h?(g=(0,$.jsx)(kx,{pinnable:n,onPick:h,className:`flex max-h-[60vh] flex-col`}),t[16]=n,t[17]=h,t[18]=g):g=t[18];let _;t[19]!==m||t[20]!==g?(_=(0,$.jsxs)(fo,{className:`gap-0 overflow-hidden p-0 sm:max-w-sm`,children:[m,g]}),t[19]=m,t[20]=g,t[21]=_):_=t[21];let v;return t[22]!==o||t[23]!==c||t[24]!==_||t[25]!==f?(v=(0,$.jsxs)(go,{open:o,onOpenChange:c,children:[f,_]}),t[22]=o,t[23]=c,t[24]=_,t[25]=f,t[26]=v):v=t[26],v},jx=e=>{let t=(0,Q.c)(63),{onSubmit:n,className:r}=e,{t:i}=Zt(),{global:a,project:o,pinnable:s,ensureLoaded:c,addStarter:l,removeStarter:u,reorder:d}=xx(Ul()),{isMobile:f}=Ws(),[p,m]=Z.useState(!1),[h,g]=Z.useState(!1),[_,v]=Z.useState(!1),y=Z.useRef(null),b;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(b={activationConstraint:{distance:8}},t[0]=b):b=t[0];let x;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(x={activationConstraint:{delay:200,tolerance:6}},t[1]=x):x=t[1];let S=Al(Cl(Ol,b),Cl(Tl,x)),C;t[2]!==a||t[3]!==o?(C=e=>a.find(t=>t.id===e)??o.find(t=>t.id===e),t[2]=a,t[3]=o,t[4]=C):C=t[4];let w=C,T=a.length+o.length,E;t[5]===T?E=t[6]:(E=()=>{let e=y.current;if(!e||T===0){v(!1);return}let t=()=>{let t=e.firstElementChild?.offsetHeight??28;v(e.scrollHeight>t+4)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},t[5]=T,t[6]=E);let D;t[7]!==h||t[8]!==a||t[9]!==o||t[10]!==T?(D=[T,h,a,o],t[7]=h,t[8]=a,t[9]=o,t[10]=T,t[11]=D):D=t[11],Z.useLayoutEffect(E,D);let O,k;t[12]!==_||t[13]!==h?(O=()=>{!_&&h&&g(!1)},k=[_,h],t[12]=_,t[13]=h,t[14]=O,t[15]=k):(O=t[14],k=t[15]),Z.useEffect(O,k);let A;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(A=()=>m(!0),t[16]=A):A=t[16];let j=A,M;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(M=()=>m(!1),t[17]=M):M=t[17];let N=M,P;t[18]!==w||t[19]!==u||t[20]!==d?(P=e=>{m(!1);let{active:t,over:n}=e;if(!n)return;let r=String(t.id),i=w(r);if(!i)return;if(String(n.id)===Sx){u(i.group,i.ref);return}let a=String(n.id);if(r===a)return;let o=w(a);o&&o.group===i.group&&d(i.group,r,a)},t[18]=w,t[19]=u,t[20]=d,t[21]=P):P=t[21];let F=P,I=_||h,L;t[22]===Symbol.for(`react.memo_cache_sentinel`)?(L={droppable:{strategy:wl.Always}},t[22]=L):L=t[22];let R;t[23]===r?R=t[24]:(R=Y(`flex min-w-0 max-w-full items-start justify-center gap-0.5`,r),t[23]=r,t[24]=R);let z=!h&&wx,B=!h&&`overflow-clip`,V;t[25]!==z||t[26]!==B?(V=Y(`flex min-w-0 flex-1 flex-wrap items-center justify-center gap-x-0.5 gap-y-0.5`,z,B),t[25]=z,t[26]=B,t[27]=V):V=t[27];let H;t[28]!==a||t[29]!==f||t[30]!==n||t[31]!==u?(H=a.length>0?(0,$.jsx)(Dx,{items:a,onSubmit:n,onRemove:e=>u(`global`,e.ref),hideRemove:f}):null,t[28]=a,t[29]=f,t[30]=n,t[31]=u,t[32]=H):H=t[32];let ee;t[33]!==f||t[34]!==n||t[35]!==o||t[36]!==u?(ee=o.length>0?(0,$.jsx)(Dx,{items:o,onSubmit:n,onRemove:e=>u(`project`,e.ref),hideRemove:f}):null,t[33]=f,t[34]=n,t[35]=o,t[36]=u,t[37]=ee):ee=t[37];let U;t[38]!==V||t[39]!==H||t[40]!==ee?(U=(0,$.jsxs)(`div`,{ref:y,className:V,children:[H,ee]}),t[38]=V,t[39]=H,t[40]=ee,t[41]=U):U=t[41];let te;t[42]!==h||t[43]!==I||t[44]!==i?(te=I?(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(Nx),"aria-expanded":h,"aria-label":i(h?`chat.draftStarters.collapse`:`chat.draftStarters.expand`),title:i(h?`chat.draftStarters.collapse`:`chat.draftStarters.expand`),className:Cx,children:(0,$.jsx)(X,{name:h?`arrow-up-s`:`arrow-down-s`,className:`h-3.5 w-3.5`})}):null,t[42]=h,t[43]=I,t[44]=i,t[45]=te):te=t[45];let W;t[46]!==l||t[47]!==c||t[48]!==p||t[49]!==f||t[50]!==s?(W=f&&p?(0,$.jsx)(Ox,{}):(0,$.jsx)(Ax,{pinnable:s,onOpen:c,onAdd:l}),t[46]=l,t[47]=c,t[48]=p,t[49]=f,t[50]=s,t[51]=W):W=t[51];let ne;t[52]!==te||t[53]!==W?(ne=(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-0.5 self-start`,children:[te,W]}),t[52]=te,t[53]=W,t[54]=ne):ne=t[54];let G;t[55]!==R||t[56]!==U||t[57]!==ne?(G=(0,$.jsxs)(`div`,{className:R,children:[U,ne]}),t[55]=R,t[56]=U,t[57]=ne,t[58]=G):G=t[58];let K;return t[59]!==F||t[60]!==S||t[61]!==G?(K=(0,$.jsx)(kl,{sensors:S,collisionDetection:Dl,measuring:L,onDragStart:j,onDragCancel:N,onDragEnd:F,children:G}),t[59]=F,t[60]=S,t[61]=G,t[62]=K):K=t[62],K};function Mx(e){return e.id}function Nx(e){return!e}var Px=e=>e.trim().replace(/\s+/g,`-`).replace(/[^A-Za-z0-9._/-]/g,`-`).replace(/-+/g,`-`).replace(/\/{2,}/g,`/`).replace(/\/-+/g,`/`).replace(/-+\//g,`/`).replace(/^[-/]+/,``).replace(/[-/]+$/,``),Fx=({currentBranch:e,localBranches:t,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:o=[],disabled:s=!1,iconOnly:c=!1,trigger:l,triggerLabel:u,contentAlign:d,hideTooltip:f=!1,projectRootOption:p=null,worktreeOptions:m=[],selectedDirectory:h=null,onSelectDirectory:g,onCreateWorktree:_,worktreesLabel:v,worktreeNewLabel:y,projectRootLabel:b,onOpenChange:x,open:S,presentation:C=`dropdown`})=>{let{t:w}=Zt(),[T,E]=Z.useState(!1),[D,O]=Z.useState(``),[k,A]=Z.useState(!1),[j,M]=Z.useState(!1),[N,P]=Z.useState(``),[F,I]=Z.useState(!1),L=Z.useRef(null),R=Z.useId(),z=S??T,B=e=>{S===void 0&&E(e),x?.(e)},V=Z.useCallback(e=>{e.stopPropagation()},[]),H=o.length>1,ee=!!(g||_),U=Z.useMemo(()=>Px(N),[N]),te=Z.useMemo(()=>{let e=D.trim();return e?Ii(t,e,e=>e).map(e=>e.item):t},[D,t]),W=Z.useMemo(()=>{let e=D.trim();return e?Ii(n,e,e=>e).map(e=>e.item):n},[D,n]),ne=Z.useMemo(()=>{let e=D.trim();return e?Ii(m,e,e=>e.label).map(e=>e.item):m},[D,m]),G=Z.useMemo(()=>{if(!p)return!1;let e=D.trim();return!e||Ii([p],e,e=>[e.label,b??``]).length>0},[b,p,D]),K=t=>{if(t===e){B(!1);return}i(t),B(!1),O(``)},re=e=>{g?.(e),B(!1),O(``)},ie=()=>{A(!0),setTimeout(()=>L.current?.focus(),50)},ae=async()=>{if(!(!U||F)){if(H){M(!0);return}I(!0);try{await a(U,o[0]),P(``),A(!1),B(!1)}finally{I(!1)}}},oe=async e=>{if(!(!U||F)){I(!0);try{await a(U,e),P(``),A(!1),M(!1),B(!1)}finally{I(!1)}}},se=()=>{M(!1)},ce=()=>{P(``),A(!1),M(!1)};Z.useEffect(()=>{z||(O(``),A(!1),M(!1),P(``))},[z]);let le=u||e||w(`gitView.branch.detachedHead`),ue=d??(c?`end`:`start`),de=v??w(`chat.chatInput.worktrees`),fe=y??w(`chat.chatInput.worktreeNew`),pe=b??w(`chat.chatInput.projectRoot`),me=c?(0,$.jsx)(`button`,{type:`button`,className:`flex size-6 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] disabled:cursor-not-allowed disabled:opacity-50`,disabled:s,"aria-label":le,children:(0,$.jsx)(X,{name:`git-branch`,className:`size-3.5`})}):(0,$.jsxs)(yo,{variant:`ghost`,size:`xs`,className:`h-6 min-w-0 max-w-full justify-start gap-1 px-0 hover:bg-transparent`,disabled:s,"aria-label":le,children:[(0,$.jsx)(X,{name:`git-branch`,className:`size-3.5 text-primary`}),(0,$.jsx)(`span`,{className:`min-w-0 truncate typography-ui-label font-semibold text-left text-foreground`,children:le}),(0,$.jsx)(X,{name:`arrow-down-s`,className:`size-3 shrink-0 text-muted-foreground`})]}),he=(0,$.jsx)(as,{asChild:!0,disabled:s,children:l??me}),ge=(0,$.jsxs)(fx,{className:`h-full min-h-0`,children:[(0,$.jsx)(`div`,{"data-mobile-sheet-no-dismiss":C===`mobile-sheet`?``:void 0,children:(0,$.jsx)(px,{placeholder:w(`gitView.branch.searchPlaceholder`),value:D,onValueChange:O,onKeyDown:V})}),(0,$.jsxs)(mx,{scrollbarClassName:`overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero`,disableHorizontal:!0,children:[(0,$.jsx)(hx,{children:w(`gitView.branch.empty`)}),(0,$.jsx)(gx,{children:j?(0,$.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:se,disabled:F,className:`shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50`,children:(0,$.jsx)(X,{name:`arrow-left`,className:`size-4`})}),(0,$.jsxs)(`span`,{className:`typography-meta text-muted-foreground`,children:[w(`gitView.branch.pushToPrefix`),` `,(0,$.jsx)(`span`,{className:`text-foreground font-medium`,children:U}),` `,w(`gitView.branch.pushToSuffix`)]})]}),(0,$.jsx)(`div`,{className:`flex flex-col gap-1`,children:o.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>oe(e),disabled:F,className:`flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50`,children:[(0,$.jsxs)(`span`,{className:`typography-ui-label text-foreground`,children:[F?(0,$.jsx)(X,{name:`loader-4`,className:`inline size-3 mr-1.5 animate-spin`}):null,e.name]}),(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground truncate max-w-full`,children:e.pushUrl})]},e.name))})]}):k?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 rounded-lg`,children:[(0,$.jsx)(`input`,{ref:L,placeholder:w(`gitView.branch.newBranchPlaceholder`),value:N,onChange:e=>P(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{V(e),e.key===`Enter`?(e.preventDefault(),ae()):e.key===`Escape`&&(e.preventDefault(),ce())},className:`flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground`}),(0,$.jsx)(`button`,{type:`button`,onClick:ae,disabled:!U||F,className:`shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50`,children:F?(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}):(0,$.jsx)(X,{name:`add`,className:`size-4`})}),(0,$.jsx)(`button`,{type:`button`,onClick:ce,disabled:F,className:`shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50`,children:(0,$.jsx)(X,{name:`close`,className:`size-4`})})]}):(0,$.jsxs)(vx,{onSelect:ie,children:[(0,$.jsx)(X,{name:`add`,className:`size-4`}),(0,$.jsx)(`span`,{children:w(`gitView.branch.create`)})]})}),(0,$.jsx)(_x,{}),(0,$.jsxs)(gx,{heading:w(`gitView.branch.localBranches`),children:[te.map(t=>(0,$.jsxs)(vx,{onSelect:()=>K(t),children:[(0,$.jsxs)(`span`,{className:`flex flex-1 flex-col`,children:[(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground`,children:t}),(r?.[t]?.ahead||r?.[t]?.behind)&&(0,$.jsxs)(`span`,{className:`typography-micro text-muted-foreground`,children:[r[t].ahead||0,` ahead ·`,` `,r[t].behind||0,` behind`]})]}),e===t&&(0,$.jsx)(`span`,{className:`typography-micro text-primary`,children:w(`gitView.branch.currentBadge`)})]},`local-${t}`)),te.length===0&&(0,$.jsx)(vx,{disabled:!0,className:`justify-center`,children:(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:w(`gitView.branch.noLocalBranches`)})})]}),(0,$.jsx)(_x,{}),(0,$.jsxs)(gx,{heading:w(`gitView.branch.remoteBranches`),children:[W.map(e=>(0,$.jsx)(vx,{onSelect:()=>K(e),children:(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground`,children:e})},`remote-${e}`)),W.length===0&&(0,$.jsx)(vx,{disabled:!0,className:`justify-center`,children:(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:w(`gitView.branch.noRemoteBranches`)})})]}),ee?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(_x,{}),(0,$.jsxs)(gx,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-2 py-1.5`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground typography-meta`,children:de}),_?(0,$.jsx)(`button`,{type:`button`,className:`cursor-pointer text-muted-foreground typography-meta hover:text-foreground`,onPointerDown:e=>{e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation(),B(!1),_()},children:fe}):null]}),p&&G?(0,$.jsxs)(vx,{onSelect:()=>re(p.value),children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground`,children:pe}),(0,$.jsx)(`span`,{className:`truncate typography-ui-label text-foreground`,children:p.label})]}),h===p.value?(0,$.jsx)(`span`,{className:`typography-micro text-primary`,children:w(`gitView.branch.currentBadge`)}):null]}):null,ne.map(e=>(0,$.jsxs)(vx,{onSelect:()=>re(e.value),children:[(0,$.jsxs)(`span`,{className:`truncate typography-ui-label text-foreground`,children:[e.pending?`⏳ `:``,e.label]}),h===e.value?(0,$.jsx)(`span`,{className:`typography-micro text-primary`,children:w(`gitView.branch.currentBadge`)}):null]},`worktree-${e.value}`))]})]}):null]})]});if(C===`mobile-sheet`){let e=Z.cloneElement(l??me,{onClick:()=>B(!0),"data-popup-open":z?``:void 0});return(0,$.jsxs)($.Fragment,{children:[e,(0,$.jsx)(Ro,{id:`mobile-draft-branch-picker-sheet-${R}`,open:z,onOpenChange:B,ariaLabel:w(`gitView.branch.selectBranch`),closeAriaLabel:w(`mobile.surface.closeAria`),resizeAriaLabel:w(`mobile.sessions.sheet.resizeAria`),children:ge})]})}return(0,$.jsxs)(Cs,{open:z,onOpenChange:B,children:[f||l?he:(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:he}),(0,$.jsx)(Zo,{sideOffset:8,children:c?le:w(`gitView.branch.currentBranchTooltip`)})]}),(0,$.jsx)($o,{align:ue,className:`w-72 p-0 max-h-[60vh] flex flex-col`,children:ge})]})};function Ix(e){let{localBranches:t,remoteBranches:n,query:r}=e,i=r.trim();if(!i)return{matching:[],otherLocal:t,otherRemote:n};let a=Ii(t,i,e=>e),o=Ii(n,i,e=>e),s=new Set(a.map(e=>e.item)),c=new Set(o.map(e=>e.item));return{matching:[...a.map(e=>({label:e.item,value:e.item,source:`local`,score:e.score})),...o.map(e=>({label:e.item,value:`remotes/${e.item}`,source:`remote`,score:e.score}))].sort((e,t)=>e.score===t.score?e.source===t.source?e.label.length===t.label.length?e.label.localeCompare(t.label,void 0,{sensitivity:`accent`}):e.label.length-t.label.length:e.source===`local`?-1:1:e.score-t.score).map(({label:e,value:t,source:n})=>({label:e,value:t,source:n})),otherLocal:t.filter(e=>!s.has(e)),otherRemote:n.filter(e=>!c.has(e))}}function Lx(e,t){return`${e}\0${t}`}function Rx({open:e,onOpenChange:t,onSelect:n}){let{t:r}=Zt(),i=g(e=>e.isMobile),{github:a}=ic(),o=Ls(),s=o.data??null,c=o.isFetched,l=g(e=>e.setSettingsDialogOpen),u=g(e=>e.setSettingsPage),d=Gi(e=>e.getActiveProject()),f=d?.id??null,p=d?.path??null,m=Z.useMemo(()=>p&&f?{id:f,path:p}:null,[f,p]),[h,_]=Z.useState(`issues`),[v,y]=Z.useState(``),[b,x]=Z.useState([]),[S,C]=Z.useState([]),[w,T]=Z.useState(!1),[E,D]=Z.useState(!1),[O,k]=Z.useState(null),[A,j]=Z.useState(null),[M,N]=Z.useState(null),[P,F]=Z.useState(!1),[I,L]=Z.useState(new Map),[R,z]=Z.useState(1),[B,V]=Z.useState(!1),H=Z.useRef(0),ee=_c(v,350),U=q(async e=>{if(!(!p||!a)&&!(c&&s?.connected===!1)){T(!0),k(null),z(1),V(!1);try{if(h===`issues`&&a.issuesList){let t=await a.issuesList(p,{page:1,query:e});t.connected===!1?(k(r(`session.githubIntegration.error.notConnected`)),x([])):(x(t.issues??[]),z(t.page??1),V(!!t.hasMore))}else if(h===`prs`&&a.prsList){let t=await a.prsList(p,{page:1,query:e});t.connected===!1?(k(r(`session.githubIntegration.error.notConnected`)),C([])):(C(t.prs??[]),z(t.page??1),V(!!t.hasMore))}}catch(e){k(e instanceof Error?e.message:r(`session.githubIntegration.error.loadDataFailed`))}finally{T(!1)}}});Z.useEffect(()=>{if(!e||!p||c&&s?.connected===!1||!a)return;if(!ee.trim()){U();return}let t=new AbortController;T(!0),k(null),z(1),V(!1);let n=h===`issues`&&a.issuesList?a.issuesList(p,{page:1,query:ee.trim()}):h===`prs`&&a.prsList?a.prsList(p,{page:1,query:ee.trim()}):null;if(!n){T(!1);return}return n.then(e=>{t.signal.aborted||(`issues`in e?e.connected===!1?(k(r(`session.githubIntegration.error.notConnected`)),x([])):(x(e.issues??[]),z(e.page??1),V(!!e.hasMore)):`prs`in e&&(e.connected===!1?(k(r(`session.githubIntegration.error.notConnected`)),C([])):(C(e.prs??[]),z(e.page??1),V(!!e.hasMore))))}).catch(e=>{t.signal.aborted||k(e instanceof Error?e.message:r(`session.githubIntegration.error.loadDataFailed`))}).finally(()=>{t.signal.aborted||T(!1)}),()=>t.abort()},[e,p,a,c,s,h,ee,U,r]);let te=q(async()=>{if(!(!p||!a)&&!(w||E)&&B){D(!0);try{let e=R+1;if(h===`issues`&&a.issuesList){let t=ee.trim()?await a.issuesList(p,{page:e,query:ee.trim()}):await a.issuesList(p,{page:e});t.connected!==!1&&(x(e=>[...e,...t.issues??[]]),z(t.page??e),V(!!t.hasMore))}else if(h===`prs`&&a.prsList){let t=ee.trim()?await a.prsList(p,{page:e,query:ee.trim()}):await a.prsList(p,{page:e});t.connected!==!1&&(C(e=>[...e,...t.prs??[]]),z(t.page??e),V(!!t.hasMore))}}catch{}finally{D(!1)}}});Z.useEffect(()=>{if(!e){_(`issues`),y(``),x([]),C([]),j(null),N(null),F(!1),k(null),L(new Map),z(1),V(!1);return}U()},[e,U]),Z.useEffect(()=>{H.current+=1,L(new Map)},[p,m]);let W=q(async e=>{if(!m||!e)return;let t=Lx(m.path,e);if(I.has(t))return;let n=H.current;try{let i=await Go(m,{mode:`new`,branchName:e,worktreeName:e});if(n!==H.current)return;let a=i.errors.find(e=>e.code===`branch_in_use`);L(e=>new Map(e).set(t,{isValid:!a,error:a?r(a.code===`branch_exists`?`session.githubIntegration.validation.branchAlreadyExists`:`session.githubIntegration.validation.branchAlreadyCheckedOut`):null}))}catch{if(n!==H.current)return;L(e=>new Map(e).set(t,{isValid:!1,error:r(`session.githubIntegration.validation.failed`)}))}});Z.useEffect(()=>{!e||h!==`prs`||S.forEach(e=>{e.head&&W(e.head)})},[e,h,S,p,m,W]);let ne=c&&s?.connected===!0,G=()=>{u(`github`),l(!0)},K=e=>{j(e),N(null)},re=e=>{N(e),j(null)},ie=()=>{A?n({type:`issue`,item:A}):M&&n({type:`pr`,item:M,includeDiff:P}),t(!1)},ae=()=>{j(null),N(null),F(!1)},oe=A||(M?.head&&p?I.get(Lx(p,M.head))?.isValid!==!1:!1),se=e=>!e.head||(p?I.get(Lx(p,e.head)):void 0)?.isValid===!1,ce=(0,$.jsx)($.Fragment,{children:ne?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[(0,$.jsx)(X,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),(0,$.jsx)(Yo,{value:v,onChange:e=>y(e.target.value),placeholder:r(h===`issues`?`session.githubIntegration.search.issuesPlaceholder`:`session.githubIntegration.search.prsPlaceholder`),className:`h-8 pl-9`})]}),(0,$.jsx)(`div`,{className:`mt-2 h-[300px] overflow-hidden`,children:(0,$.jsxs)(`div`,{className:`h-full overflow-y-auto`,children:[w&&(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsx)(X,{name:`loader-4`,className:`h-5 w-5 animate-spin text-muted-foreground`})}),O&&(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2 p-2 rounded-md bg-destructive/10 text-destructive`,children:[(0,$.jsx)(X,{name:`error-warning`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`typography-small`,children:O})]})}),!w&&!O&&h===`issues`&&(0,$.jsxs)(`div`,{className:`space-y-0.5 min-h-full`,children:[b.length>0?b.map(e=>(0,$.jsx)(`button`,{onClick:()=>K(e),className:Y(`w-full text-left px-2 py-1.5 rounded transition-colors`,A?.number===e.number?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground shrink-0 typography-micro`,children:[`#`,e.number]}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`typography-small line-clamp-2`,children:e.title}),e.sourceRepo?.source===`upstream`?(0,$.jsxs)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info mt-0.5 inline-block`,children:[e.sourceRepo.owner,`/`,e.sourceRepo.repo]}):null]})]})},`${e.sourceRepo?.owner??``}-${e.sourceRepo?.repo??``}-${e.number}`)):(0,$.jsx)(`div`,{className:`flex items-center justify-center h-[300px] text-center typography-small text-muted-foreground`,children:r(`session.githubIntegration.empty.noIssuesFound`)}),B&&!E&&(0,$.jsx)(`div`,{className:`flex justify-center pt-2`,children:(0,$.jsx)(yo,{variant:`ghost`,size:`sm`,onClick:()=>void te(),className:`h-7 text-xs`,children:r(`session.githubIntegration.actions.loadMore`)})}),E&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-2`,children:(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`})})]}),!w&&!O&&h===`prs`&&(0,$.jsxs)(`div`,{className:`space-y-0.5 min-h-full`,children:[S.length>0?S.map(e=>{let t=se(e),n=e.head&&p?I.get(Lx(p,e.head)):void 0;return(0,$.jsx)(`button`,{onClick:()=>!t&&re(e),disabled:t,className:Y(`w-full text-left px-2 py-1.5 rounded transition-colors`,M?.number===e.number?`bg-interactive-selection text-interactive-selection-foreground`:t?`opacity-50 cursor-not-allowed`:`hover:bg-interactive-hover`),children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground shrink-0 typography-micro`,children:[`#`,e.number]}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`typography-small line-clamp-1`,children:e.title}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-0.5`,children:[(0,$.jsxs)(`span`,{className:`typography-micro text-muted-foreground`,children:[e.head,` → `,e.base]}),e.sourceRepo?.source===`upstream`?(0,$.jsxs)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info`,children:[e.sourceRepo.owner,`/`,e.sourceRepo.repo]}):null,t&&n?.error&&(0,$.jsx)(`span`,{className:`typography-micro text-destructive`,children:n.error})]})]})]})},`${e.sourceRepo?.owner??``}-${e.sourceRepo?.repo??``}-${e.number}`)}):(0,$.jsx)(`div`,{className:`flex items-center justify-center h-[300px] text-center typography-small text-muted-foreground`,children:r(`session.githubIntegration.empty.noPullRequestsFound`)}),B&&!E&&(0,$.jsx)(`div`,{className:`flex justify-center pt-2`,children:(0,$.jsx)(yo,{variant:`ghost`,size:`sm`,onClick:()=>void te(),className:`h-7 text-xs`,children:r(`session.githubIntegration.actions.loadMore`)})}),E&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-2`,children:(0,$.jsx)(X,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`})})]})]})})]}):(0,$.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center p-8 gap-4`,children:[(0,$.jsx)(X,{name:`github`,className:`h-12 w-12 text-muted-foreground`}),(0,$.jsxs)(`div`,{className:`text-center`,children:[(0,$.jsx)(`p`,{className:`typography-ui-label text-foreground`,children:r(`session.githubIntegration.connect.title`)}),(0,$.jsx)(`p`,{className:`typography-small text-muted-foreground mt-1`,children:r(`session.githubIntegration.connect.description`)})]}),(0,$.jsx)(yo,{onClick:G,size:`sm`,children:r(`session.githubIntegration.connect.action`)})]})}),le=(0,$.jsxs)(`div`,{className:Y(`w-full`,i?`flex flex-col gap-2`:`flex flex-row items-center`),children:[(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-4`,i?`w-full justify-center order-1`:`flex-1`),children:[!i&&(A||M)&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 h-8 rounded-md bg-muted/50 border border-border/50`,children:[(0,$.jsx)(X,{name:`check`,className:`h-3.5 w-3.5 text-status-success shrink-0`}),(0,$.jsx)(`span`,{className:`typography-small truncate max-w-[150px]`,children:A?r(`session.githubIntegration.selected.issueNumber`,{number:A.number}):r(`session.githubIntegration.selected.prNumber`,{number:M?.number??``})}),(0,$.jsx)(`button`,{onClick:ae,className:`text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors`,children:(0,$.jsx)(X,{name:`close`,className:`h-3.5 w-3.5`})})]}),h===`prs`&&M&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2 cursor-pointer h-8`,children:[(0,$.jsx)(jo,{checked:P,onChange:e=>F(e),ariaLabel:r(`session.githubIntegration.includeDiffAria`)}),(0,$.jsx)(`span`,{className:`typography-small text-foreground`,children:r(`session.githubIntegration.includeDiff`)})]})]}),(0,$.jsxs)(`div`,{className:Y(`flex gap-2`,i?`w-full order-2`:`justify-end`),children:[(0,$.jsx)(yo,{variant:`outline`,size:`sm`,onClick:()=>t(!1),className:Y(i&&`flex-1`),children:r(`session.githubIntegration.actions.cancel`)}),(0,$.jsx)(yo,{size:`sm`,onClick:ie,disabled:!oe,className:Y(i&&`flex-1`),children:r(`session.githubIntegration.actions.select`)})]})]});return(0,$.jsx)($.Fragment,{children:i?(0,$.jsx)(cv,{open:e,title:r(`session.githubIntegration.title`),onClose:()=>t(!1),footer:ne?le:void 0,renderHeader:e=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 px-3 py-2 border-b border-border/40`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`typography-ui-label font-semibold text-foreground`,children:r(`session.githubIntegration.title`)}),e]}),(0,$.jsx)(`div`,{className:`w-full`,children:(0,$.jsx)(Iu,{items:[{id:`issues`,label:r(`session.githubIntegration.tabs.issues`),icon:(0,$.jsx)(X,{name:`git-branch`,className:`h-3.5 w-3.5`})},{id:`prs`,label:r(`session.githubIntegration.tabs.pullRequests`),icon:(0,$.jsx)(X,{name:`git-pull-request`,className:`h-3.5 w-3.5`})}],activeId:h,onSelect:e=>{_(e),y(``)},variant:`active-pill`,layoutMode:`fit`})}),(A||M)&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1 rounded-md bg-muted/50 border border-border/50`,children:[(0,$.jsx)(X,{name:`check`,className:`h-3.5 w-3.5 text-status-success shrink-0`}),(0,$.jsx)(`span`,{className:`typography-small truncate flex-1`,children:A?r(`session.githubIntegration.selected.issueNumber`,{number:A.number}):r(`session.githubIntegration.selected.prNumber`,{number:M?.number??``})}),(0,$.jsx)(`button`,{onClick:ae,className:`text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors`,children:(0,$.jsx)(X,{name:`close`,className:`h-3.5 w-3.5`})})]})]}),children:ce}):(0,$.jsx)(go,{open:e,onOpenChange:t,children:(0,$.jsxs)(fo,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:[(0,$.jsx)(co,{className:`flex flex-row items-center justify-between`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsxs)(po,{className:`flex items-center gap-2 shrink-0`,children:[(0,$.jsx)(X,{name:`github`,className:`h-5 w-5`}),r(`session.githubIntegration.title`)]}),(0,$.jsx)(`div`,{className:`w-[220px]`,children:(0,$.jsx)(Iu,{items:[{id:`issues`,label:r(`session.githubIntegration.tabs.issues`),icon:(0,$.jsx)(X,{name:`git-branch`,className:`h-3.5 w-3.5`})},{id:`prs`,label:r(`session.githubIntegration.tabs.pullRequests`),icon:(0,$.jsx)(X,{name:`git-pull-request`,className:`h-3.5 w-3.5`})}],activeId:h,onSelect:e=>{_(e),y(``)},variant:`active-pill`,layoutMode:`fit`})})]})}),ce,(0,$.jsx)(lo,{className:`mt-1`,children:le})]})})})}var zx=(e,t,n)=>{let r=n??t;return r?e.find(e=>e.id===r)??null:null},Bx=e=>e.trim().replace(/^refs\/heads\//,``).replace(/^heads\//,``).replace(/\s+/g,`-`).replace(/^\/+|\/+$/g,``),Vx=e=>e.trim().replace(/^refs\/heads\//,``).replace(/^heads\//,``).replace(/\s+/g,`-`).replace(/^\/+|\/+$/g,``).split(`/`).join(`-`).replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/-+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80),Hx=e=>String(e||``).trim().toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/-+/g,`-`).replace(/^-+|-+$/g,``)||`pr-head`,Ux=(e,t,n)=>{let r=Bx(e.head||``);if(!r)throw Error(`PR head branch is missing`);if(t.includes(r))return{existingBranch:r,setUpstream:void 0,upstreamRemote:void 0,upstreamBranch:void 0,ensureRemoteName:void 0,ensureRemoteUrl:void 0,sourceLabel:r};let i=n.find(e=>{let t=e.indexOf(`/`);return t<=0||t>=e.length-1?!1:e.slice(t+1)===r});if(i){let e=i.indexOf(`/`),t=i.slice(0,e);return{existingBranch:`remotes/${i}`,setUpstream:!0,upstreamRemote:t,upstreamBranch:r,ensureRemoteName:void 0,ensureRemoteUrl:void 0,sourceLabel:`${t}/${r}`}}let a=String(e.headLabel||``).split(`:`)[0]?.trim(),o=`pr-${Hx(e.headRepo?.owner||a||`pr-head`)}`,s=e.headRepo?.sshUrl||e.headRepo?.cloneUrl||``;if(!s)throw Error(`PR head repository URL is unavailable`);return{existingBranch:`remotes/${o}/${r}`,setUpstream:!0,upstreamRemote:o,upstreamBranch:r,ensureRemoteName:o,ensureRemoteUrl:s,sourceLabel:`${o}/${r}`}},Wx=e=>{let t={repo:e.repo??null,issue:e.issue,comments:e.comments};return`GitHub issue context (JSON)\n${JSON.stringify(t,null,2)}`},Gx=e=>`GitHub pull request context (JSON)\n${JSON.stringify(e,null,2)}`;function Kx({open:e,onOpenChange:t,onWorktreeCreated:n,projectId:r}){let{t:i}=Zt(),{github:a,git:o}=ic(),s=g(e=>e.isMobile),c=Z.useId(),l=Ls(),u=l.data??null,d=l.isFetched,f=Gi(e=>zx(e.projects,e.activeProjectId,r)),p=f?.path??null,m=Z.useMemo(()=>p&&f?{id:f.id,path:p}:null,[f,p]),[h,_]=Z.useState(`new-branch`),[v,y]=Z.useState({branchName:``,worktreeName:``,isSyncingWorktreeName:!0,sourceBranch:``,linkedIssue:null,linkedPr:null,includePrDiff:!1}),[b,x]=Z.useState({selectedBranch:``,worktreeName:``}),S=Fc(p),C=Mc(p),w=Tc(e=>e.fetchBranches),T=Z.useMemo(()=>S?.all?S.all.filter(e=>!e.startsWith(`remotes/`)).sort():[],[S]),E=Z.useMemo(()=>S?.all?S.all.filter(e=>e.startsWith(`remotes/`)).map(e=>e.replace(/^remotes\//,``)).sort():[],[S]),D=J(e=>e.availableWorktreesByProject),O=Z.useMemo(()=>{if(!p)return new Set;let e=D.get(p)??[];return new Set(e.map(e=>e.name))},[D,p]),k=Z.useCallback((e=10)=>{for(let t=0;t<e;t++){let e=Gb();if(!O.has(e))return e}return`${Gb()}-${Date.now().toString(36).slice(-4)}`},[O]),[A,j]=Z.useState(!1),[M,N]=Z.useState(!1),[P,F]=Z.useState(!1),[I,L]=Z.useState(!1),[R,z]=Z.useState(!1),[B,V]=Z.useState(``),[H,ee]=Z.useState(``),U=Z.useRef(null),te=Z.useRef(null),W=Z.useRef(null),ne=Z.useRef(null),G=Z.useCallback(e=>{e.stopPropagation()},[]),K=Z.useCallback(e=>{let t=e;for(;t&&t!==document.body;){let{overflowY:e}=window.getComputedStyle(t);if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null},[]),re=Z.useCallback(e=>{e&&(e.scrollTop=0)},[]),ie=Z.useCallback(e=>{let t=e.current?.querySelector(`[data-slot="command-list"]`)??null;re(t)},[re]),ae=Z.useCallback(e=>{let t=K(e.current);re(t)},[K,re]),oe=Z.useMemo(()=>Ix({localBranches:T,remoteBranches:E,query:B}),[T,E,B]),se=Z.useMemo(()=>Ix({localBranches:T,remoteBranches:E,query:H}),[T,E,H]),ce=B.trim().length>0,le=H.trim().length>0,ue=oe.matching.length>0,de=se.matching.length>0,fe=!!(p&&o),pe=Z.useCallback(()=>{!p||!o||w(p,o)},[p,o,w]);Z.useEffect(()=>{!e||!p||!o||S?.all||w(p,o)},[e,p,o,S?.all,w]),Z.useEffect(()=>{!M&&!I&&V(``)},[M,I]),Z.useEffect(()=>{!P&&!R&&ee(``)},[P,R]),Z.useEffect(()=>{M&&ie(U),I&&ae(W)},[M,I,B,ie,ae]),Z.useEffect(()=>{P&&ie(te),R&&ae(ne)},[P,R,H,ie,ae]);let[me,he]=Z.useState({isValidating:!1,branchError:null,worktreeError:null,touched:!1}),[ge,_e]=Z.useState(!1),[ve,ye]=Z.useState(null),be=Z.useCallback(()=>{let e=ui.getState(),t=e.getVisibleAgents();if(e.settingsDefaultAgent){let n=t.find(t=>t.name===e.settingsDefaultAgent);if(n)return n.name}return t.find(e=>e.name===`build`)?.name||t[0]?.name},[]),xe=Z.useCallback(()=>{let e=ui.getState(),t=e.settingsDefaultModel;if(!t)return null;let n=Qi(t);if(!n)return null;let{providerId:r,modelId:i}=n;return e.getModelMetadata(r,i)?{providerID:r,modelID:i}:null},[]),Se=Z.useCallback((e,t)=>{let n=ui.getState(),r=n.settingsDefaultVariant,i=n.currentProviderId===e&&n.currentModelId===t?n.currentVariant:void 0,a=n.providers.find(t=>t.id===e)?.models.find(e=>e.id===t)?.variants;if(!a)return r||i||void 0;if(r&&Object.prototype.hasOwnProperty.call(a,r))return r;if(i&&Object.prototype.hasOwnProperty.call(a,i))return i},[]),Ce=Z.useCallback(async e=>{if(!p||!a)return;let t=ui.getState(),n=Nn.getState().lastUsedProvider,r=xe(),o=r?.providerID||t.currentProviderId||n?.providerID,s=r?.modelID||t.currentModelId||n?.modelID,c=be()||t.currentAgentName||void 0;if(!o||!s){fa.error(i(`session.newWorktree.error.noModelSelected`));return}let l=Se(o,s);if(e.issue){if(!a.issueGet||!a.issueComments)return;let t=await a.issueGet(p,e.issue.number,{sourceRepo:e.issue.sourceRepo??null});if(t.connected===!1||!t.repo||!t.issue)throw Error(`Failed to load issue context`);let n=await a.issueComments(p,e.issue.number,{sourceRepo:e.issue.sourceRepo??null});if(n.connected===!1)throw Error(`Failed to load issue comments`);let r=await Ur(`github.issue.review.visible`,{issue_number:String(e.issue.number)}),u=await Ur(`github.issue.review.instructions`),d=Wx({repo:t.repo,issue:t.issue,comments:n.comments??[]});await J.getState().sendMessage(r,o,s,c,void 0,void 0,[{text:u,synthetic:!0},{text:d,synthetic:!0}],l,void 0,{sessionId:e.sessionId}),fa.success(i(`session.newWorktree.toast.sessionFromIssue`));return}if(e.pr){if(!a.prContext)return;let t=await a.prContext(p,e.pr.number,{sourceRepo:e.pr.sourceRepo??null,includeDiff:e.includeDiff,includeCheckDetails:!1});if(t.connected===!1||!t.repo||!t.pr)throw Error(`Failed to load PR context`);let n=await Ur(`github.pr.review.visible`,{pr_number:String(e.pr.number)}),r=await Ur(`github.pr.review.instructions`),u=Gx(t);await J.getState().sendMessage(n,o,s,c,void 0,void 0,[{text:r,synthetic:!0},{text:u,synthetic:!0}],l,void 0,{sessionId:e.sessionId}),fa.success(i(`session.newWorktree.toast.sessionFromPr`))}},[a,p,be,xe,Se,i]),we=h===`new-branch`?v:b;Z.useEffect(()=>{if(!e||!S?.all||!p||v.sourceBranch)return;let t=v.sourceBranch,n=!1;return(async()=>{try{let e=await Fo(p).catch(()=>null);if(n)return;let r=localStorage.getItem(wc),{sourceBranch:i,shouldClearSavedSourceBranch:a}=Pc({branches:S.all,savedSourceBranch:r,rootBranch:e});if(a&&localStorage.removeItem(wc),n||t)return;i&&y(e=>({...e,sourceBranch:i}))}catch{}})(),()=>{n=!0}},[e,S?.all,p,v.sourceBranch]),Z.useLayoutEffect(()=>{if(!e)return;_(`new-branch`),x({selectedBranch:``,worktreeName:``}),N(!1),F(!1),L(!1),z(!1),V(``),ee(``),he({isValidating:!1,branchError:null,worktreeError:null,touched:!1});let t=k();y({branchName:t,worktreeName:t,isSyncingWorktreeName:!0,sourceBranch:``,linkedIssue:null,linkedPr:null,includePrDiff:!1})},[e,k]),Z.useEffect(()=>{if(h!==`new-branch`||!v.isSyncingWorktreeName)return;let e=Vx(Bx(v.branchName));y(t=>({...t,worktreeName:e}))},[h,v.branchName,v.isSyncingWorktreeName]);let Te=Z.useCallback(async()=>{if(!m||!me.touched||ge)return;ve&&ve.abort();let e=new AbortController;ye(e),he(e=>({...e,isValidating:!0}));try{let t=h===`new-branch`?v.branchName:b.selectedBranch,n=we.worktreeName,r=Bx(t),a=Vx(n),o=null,s=null;if(r||(o=i(`session.newWorktree.error.branchNameRequired`)),a||(s=i(`session.newWorktree.error.worktreeDirectoryRequired`)),r&&a){let t=h===`new-branch`?v.linkedPr:null,n=t?Ux(t,T,E):null,i=await Go(m,{mode:h===`existing-branch`||n?`existing`:`new`,branchName:r,worktreeName:a,existingBranch:n?.existingBranch??(h===`existing-branch`?r:void 0),...n?.ensureRemoteName?{ensureRemoteName:n.ensureRemoteName}:{},...n?.ensureRemoteUrl?{ensureRemoteUrl:n.ensureRemoteUrl}:{}});if(e.signal.aborted)return;i.ok||i.errors.forEach(e=>{if(e.code===`worktree_exists`){s??=e.message;return}e.code.startsWith(`branch_`)&&(o??=e.message)})}e.signal.aborted||he(e=>({...e,isValidating:!1,branchError:o,worktreeError:s}))}catch{e.signal.aborted||he(e=>({...e,isValidating:!1}))}},[m,h,v.branchName,v.linkedPr,b.selectedBranch,we.worktreeName,T,E,me.touched,ve,ge,i]),Ee=h===`new-branch`?v.branchName:b.selectedBranch;Z.useEffect(()=>{if(!e||!m||!me.touched||ge)return;let t=setTimeout(()=>{Te()},300);return()=>clearTimeout(t)},[we.worktreeName,Ee,e,m,Te,me.touched,ge]);let De=async()=>{if(!m||!p){fa.error(i(`session.newWorktree.error.noActiveProject`));return}he(e=>({...e,touched:!0}));let e=h===`new-branch`?v.branchName:b.selectedBranch,r=we.worktreeName,a=Bx(e),o=Vx(r);if(!a){fa.error(i(`session.newWorktree.error.branchNameRequired`));return}if(!o){fa.error(i(`session.newWorktree.error.worktreeDirectoryRequired`));return}ve&&(ve.abort(),ye(null)),he(e=>({...e,isValidating:!1,branchError:null,worktreeError:null})),_e(!0);try{let e=h===`new-branch`?v.linkedPr:null,r=h===`new-branch`?v.linkedIssue:null,s=h===`new-branch`?v.linkedPr:null,c=h===`new-branch`&&v.includePrDiff,l=!!(r||s),[u,d]=await Promise.all([qn(m),jc(p)]),f=v.sourceBranch,g=``,_=(()=>{if(e){let t=Ux(e,T,E);return g=t.sourceLabel,{preferredName:a||o,mode:`existing`,branchName:a,worktreeName:o,existingBranch:t.existingBranch,setupCommands:u,setUpstream:t.setUpstream,upstreamRemote:t.upstreamRemote,upstreamBranch:t.upstreamBranch,returnAfterDirectoryCreated:!0,...t.ensureRemoteName?{ensureRemoteName:t.ensureRemoteName}:{},...t.ensureRemoteUrl?{ensureRemoteUrl:t.ensureRemoteUrl}:{}}}return g=h===`new-branch`?f:``,{preferredName:a||o,mode:h===`existing-branch`?`existing`:`new`,branchName:h===`existing-branch`?void 0:a,worktreeName:o,existingBranch:h===`existing-branch`?a:void 0,setupCommands:u,returnAfterDirectoryCreated:!0,...f&&h===`new-branch`?{startRef:f}:{}}})(),y=await zc(p,_,{resolvedRootTrackingRemote:d}),x=await Ho(m,y),S=null;if(l){await ar(m)&&await ti(x.path);let e=r?`#${r.number} ${r.title}`.trim():s?`#${s.number} ${s.title}`.trim():i(`session.newWorktree.newSessionTitle`),a=await In(e,x.path,null);if(!a?.id)throw Error(`Failed to create session`);S=a.id,n?.(x.path,{sessionId:S}),t(!1),_e(!1),er(a.id,e).catch(()=>void 0);try{J.getState().initializeNewOpenChamberSession(a.id,ui.getState().agents)}catch{}}else t(!1),_e(!1);let C=Lc({mode:h,sourceBranch:v.sourceBranch,linkedPr:!!v.linkedPr,selectedBranch:b.selectedBranch});C&&localStorage.setItem(wc,C),fa.success(i(`session.newWorktree.toast.worktreeCreated`),{description:i(`session.newWorktree.toast.worktreeCreatedDescription`,{target:`${x.branch||x.name}${g?` ${i(`session.newWorktree.fromSource`,{source:g})}`:``}`})}),S?Ce({sessionId:S,directory:x.path,issue:r,pr:s,includeDiff:c}).catch(e=>{let t=e instanceof Error?e.message:i(`session.newWorktree.error.sendGitHubContextFailed`);fa.error(i(`session.newWorktree.error.sendGitHubContextFailed`),{description:t})}):n?.(x.path)}catch(e){let t=e instanceof Error?e.message:i(`session.newWorktree.error.createWorktreeFailed`);fa.error(i(`session.newWorktree.error.createWorktreeFailed`),{description:t})}finally{_e(!1)}},Oe=e=>{_(e),he(e=>({...e,touched:!1,branchError:null,worktreeError:null}))},ke=e=>{if(!e){y(e=>({...e,linkedIssue:null,linkedPr:null,includePrDiff:!1,branchName:``}));return}if(e.type===`issue`){let t=e.item,n=`issue-${t.number}-${Gb()}`;y(e=>({...e,linkedIssue:t,linkedPr:null,includePrDiff:!1,branchName:n,worktreeName:Vx(n),isSyncingWorktreeName:!0}))}else if(e.type===`pr`){let t=e.item;y(n=>({...n,linkedPr:t,linkedIssue:null,includePrDiff:e.includeDiff??!1,branchName:t.head,worktreeName:Vx(t.head),isSyncingWorktreeName:!0}))}},Ae=d&&u?.connected===!0,je=(h===`existing-branch`?!!b.selectedBranch&&!!b.worktreeName&&!me.branchError&&!me.worktreeError:!!Bx(v.branchName)&&!!v.worktreeName&&!me.branchError&&!me.worktreeError)&&!ge,Me=()=>{y(e=>({...e,linkedIssue:null,linkedPr:null,branchName:``,includePrDiff:!1,isSyncingWorktreeName:!0}))},Ne=(0,$.jsxs)(`div`,{className:Y(`flex gap-2`,s?`flex-col w-full`:`flex-row items-center`),children:[(0,$.jsx)(`div`,{className:Y(`flex items-center gap-1.5 text-destructive`,s?`w-full justify-center order-first`:`mr-auto`),children:me.touched&&(me.branchError||me.worktreeError)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{name:`error-warning`,className:`h-3.5 w-3.5`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:me.branchError||me.worktreeError})]})}),(0,$.jsxs)(`div`,{className:Y(`flex gap-2`,s&&`w-full`),children:[(0,$.jsx)(yo,{variant:`outline`,size:`sm`,onClick:()=>t(!1),disabled:ge,className:Y(s&&`flex-1`),children:i(`session.newWorktree.actions.cancel`)}),(0,$.jsxs)(yo,{size:`sm`,onClick:De,disabled:!je||ge,className:Y(`gap-1.5`,s&&`flex-1`),children:[ge&&(0,$.jsx)(X,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}),i(ge?`session.newWorktree.actions.creating`:`session.newWorktree.actions.createWorktree`)]})]})]});return(0,$.jsxs)($.Fragment,{children:[s?(0,$.jsx)(Ro,{id:`new-worktree-sheet-${c}`,open:e,onOpenChange:t,title:(0,$.jsx)(`h2`,{className:`truncate typography-ui-label font-semibold text-foreground`,children:i(`session.newWorktree.title`)}),ariaLabel:i(`session.newWorktree.title`),closeAriaLabel:i(`mobile.surface.closeAria`),resizeAriaLabel:i(`mobile.sessions.sheet.resizeAria`),children:(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,$.jsxs)(xl,{useScrollShadow:!0,disableHorizontal:!0,preventOverscroll:!0,outerClassName:`min-h-0 flex-1`,className:`overscroll-contain px-4 pb-4 pt-2`,children:[(0,$.jsx)(`div`,{className:`w-full mb-4`,children:(0,$.jsx)(Iu,{items:[{id:`new-branch`,label:i(`session.newWorktree.mode.newBranch`),icon:(0,$.jsx)(X,{name:`git-branch`,className:`h-3.5 w-3.5`})},{id:`existing-branch`,label:i(`session.newWorktree.mode.existingBranch`),icon:(0,$.jsx)(X,{name:`git-repository`,className:`h-3.5 w-3.5`})}],activeId:h,onSelect:e=>Oe(e),variant:`active-pill`,layoutMode:`fit`,className:`w-full`})}),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[h===`existing-branch`?(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.selectBranch`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(yo,{variant:`outline`,size:`sm`,onClick:()=>L(!0),className:`flex-1 justify-between h-9`,children:[(0,$.jsx)(`span`,{className:b.selectedBranch?`text-foreground`:`text-muted-foreground`,children:b.selectedBranch||i(`session.newWorktree.chooseBranch`)}),(0,$.jsx)(X,{name:`git-branch`,className:`h-4 w-4 text-muted-foreground`})]}),(0,$.jsx)(yo,{variant:`ghost`,size:`sm`,className:`h-8 w-8 px-0 shrink-0`,onClick:pe,disabled:!fe||C,title:i(`session.newWorktree.fetchBranches`),children:C?(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}):(0,$.jsx)(X,{name:`refresh`,className:`size-4`})})]}),(0,$.jsx)(cv,{open:I,title:i(`session.newWorktree.selectBranch`),onClose:()=>L(!1),children:(0,$.jsxs)(`div`,{className:`space-y-4`,ref:W,children:[(0,$.jsx)(Yo,{value:B,onChange:e=>V(e.target.value),placeholder:i(`session.newWorktree.searchBranches`),className:`h-8`}),C?(0,$.jsx)(`div`,{className:`px-2 py-8 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.loadingBranches`)}):T.length===0&&E.length===0?(0,$.jsx)(`div`,{className:`px-2 py-8 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noBranchesFound`)}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[ce&&ue&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(`session.newWorktree.matchingBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:oe.matching.map(e=>(0,$.jsx)(`button`,{onClick:()=>{x(t=>({...t,selectedBranch:e.value,worktreeName:Vx(e.label)})),he(e=>({...e,touched:!0})),L(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,b.selectedBranch===e.value?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e.label})},`${e.source}-${e.value}`))})]}),ce&&!ue&&(0,$.jsx)(`div`,{className:`px-2 py-1 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noMatchingBranches`)}),oe.otherLocal.length>0&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(ce?`session.newWorktree.otherLocalBranches`:`session.newWorktree.localBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:oe.otherLocal.map(e=>(0,$.jsx)(`button`,{onClick:()=>{x(t=>({...t,selectedBranch:e,worktreeName:Vx(e)})),he(e=>({...e,touched:!0})),L(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,b.selectedBranch===e?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},e))})]}),oe.otherRemote.length>0&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(ce?`session.newWorktree.otherRemoteBranches`:`session.newWorktree.remoteBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:oe.otherRemote.map(e=>(0,$.jsx)(`button`,{onClick:()=>{x(t=>({...t,selectedBranch:`remotes/${e}`,worktreeName:Vx(e)})),he(e=>({...e,touched:!0})),L(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,b.selectedBranch===`remotes/${e}`?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`remotes/${e}`))})]})]})]})})]}):(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col items-start gap-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.branchName`)}),h===`new-branch`&&Ae&&(0,$.jsxs)(yo,{variant:`outline`,size:`sm`,onClick:()=>j(!0),className:`gap-1.5 h-7`,children:[(0,$.jsx)(X,{name:`github`,className:`size-4 text-status-success`}),v.linkedIssue||v.linkedPr?i(`session.newWorktree.actions.change`):i(`session.newWorktree.actions.startFromGitHubIssuePr`)]})]}),(0,$.jsx)(Yo,{value:v.branchName,onChange:e=>{y(t=>({...t,branchName:e.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>he(e=>({...e,touched:!0})),placeholder:i(`session.newWorktree.branchNamePlaceholder`),disabled:!!v.linkedPr,className:Y(`h-8`,me.touched&&me.branchError&&`border-destructive`,v.linkedPr&&`bg-muted text-muted-foreground`)}),v.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground`,children:[(0,$.jsx)(X,{name:`check`,className:`h-3.5 w-3.5 text-status-success`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:i(`session.newWorktree.usingPrBranch`,{branch:v.linkedPr.head})})]}),v.linkedIssue&&!v.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground`,children:[(0,$.jsx)(X,{name:`check`,className:`h-3.5 w-3.5 text-status-success`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:i(`session.newWorktree.fromIssue`,{number:v.linkedIssue.number,title:v.linkedIssue.title})})]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground font-semibold`,children:i(`session.newWorktree.worktreeDirectory`)}),h!==`existing-branch`&&(0,$.jsxs)(`button`,{onClick:()=>{let e=Vx(h===`new-branch`?v.branchName:``);y(t=>({...t,worktreeName:e,isSyncingWorktreeName:!0}))},disabled:!v.branchName||v.worktreeName===Vx(v.branchName),className:Y(`flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded`,v.worktreeName===Vx(v.branchName)||!v.branchName?`text-muted-foreground/40 cursor-not-allowed`:`text-muted-foreground hover:text-foreground hover:bg-muted`),title:i(`session.newWorktree.resetToMatchBranchName`),children:[(0,$.jsx)(X,{name:`refresh`,className:`h-3 w-3`}),(0,$.jsx)(`span`,{children:i(`session.newWorktree.actions.reset`)})]})]}),(0,$.jsx)(Yo,{value:we.worktreeName,onChange:e=>{h===`new-branch`?y(t=>({...t,worktreeName:e.target.value,isSyncingWorktreeName:!1})):x(t=>({...t,worktreeName:e.target.value}))},onBlur:()=>he(e=>({...e,touched:!0})),placeholder:i(`session.newWorktree.worktreeDirectoryPlaceholder`),className:Y(`h-8`,me.touched&&me.worktreeError&&`border-destructive`)})]}),h===`new-branch`&&!v.linkedPr&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.sourceBranch`)}),(0,$.jsxs)(yo,{variant:`outline`,size:`sm`,onClick:()=>z(!0),className:`w-full justify-between h-9`,children:[(0,$.jsx)(`span`,{className:v.sourceBranch?`text-foreground`:`text-muted-foreground`,children:v.sourceBranch||i(`session.newWorktree.selectSourceBranchPlaceholder`)}),(0,$.jsx)(X,{name:`git-branch`,className:`h-4 w-4 text-muted-foreground`})]}),v.sourceBranch&&(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:i(`session.newWorktree.newBranchFromSource`,{source:v.sourceBranch})}),(0,$.jsx)(cv,{open:R,title:i(`session.newWorktree.selectSourceBranch`),onClose:()=>z(!1),children:(0,$.jsxs)(`div`,{className:`space-y-4`,ref:ne,children:[(0,$.jsx)(Yo,{value:H,onChange:e=>ee(e.target.value),placeholder:i(`session.newWorktree.searchBranches`),className:`h-8`}),C?(0,$.jsx)(`div`,{className:`px-2 py-8 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.loadingBranches`)}):T.length===0&&E.length===0?(0,$.jsx)(`div`,{className:`px-2 py-8 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noBranchesFound`)}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[le&&de&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(`session.newWorktree.matchingBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:se.matching.map(e=>(0,$.jsx)(`button`,{onClick:()=>{y(t=>({...t,sourceBranch:e.value})),z(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,v.sourceBranch===e.value?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e.label})},`${e.source}-${e.value}`))})]}),le&&!de&&(0,$.jsx)(`div`,{className:`px-2 py-1 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noMatchingBranches`)}),se.otherLocal.length>0&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(le?`session.newWorktree.otherLocalBranches`:`session.newWorktree.localBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:se.otherLocal.map(e=>(0,$.jsx)(`button`,{onClick:()=>{y(t=>({...t,sourceBranch:e})),z(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,v.sourceBranch===e?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},e))})]}),se.otherRemote.length>0&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(le?`session.newWorktree.otherRemoteBranches`:`session.newWorktree.remoteBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:se.otherRemote.map(e=>(0,$.jsx)(`button`,{onClick:()=>{y(t=>({...t,sourceBranch:`remotes/${e}`})),z(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,v.sourceBranch===`remotes/${e}`?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`remotes/${e}`))})]})]})]})})]}),(v.linkedIssue||v.linkedPr)&&h===`new-branch`&&(0,$.jsxs)(`div`,{className:`mt-2 px-2 py-1.5 rounded bg-muted/30`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`github`,className:`h-3.5 w-3.5 text-status-success shrink-0`}),v.linkedIssue&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground shrink-0`,children:i(`session.newWorktree.issueNumber`,{number:v.linkedIssue.number})}),v.linkedPr&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground shrink-0`,children:i(`session.newWorktree.prNumber`,{number:v.linkedPr.number})}),(0,$.jsx)(`span`,{className:`typography-micro text-foreground truncate flex-1`,children:v.linkedIssue?.title||v.linkedPr?.title}),(0,$.jsx)(`a`,{href:v.linkedIssue?.url||v.linkedPr?.url,target:`_blank`,rel:`noopener noreferrer`,className:`text-muted-foreground hover:text-foreground shrink-0`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(X,{name:`external-link`,className:`h-3 w-3`})}),(0,$.jsx)(`button`,{onClick:Me,className:`text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors`,children:(0,$.jsx)(X,{name:`close`,className:`h-3.5 w-3.5`})})]}),v.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-0.5 pl-5`,children:[(0,$.jsxs)(`span`,{className:`typography-micro text-muted-foreground`,children:[v.linkedPr.head,` → `,v.linkedPr.base]}),v.includePrDiff&&(0,$.jsx)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-success/10 text-status-success`,children:i(`session.newWorktree.includeDiffBadge`)})]})]})]})]}),(0,$.jsx)(`div`,{className:`shrink-0 border-t border-border/50 px-4 pb-3 pt-2`,children:Ne})]})}):(0,$.jsx)(go,{open:e,onOpenChange:t,children:(0,$.jsxs)(fo,{className:`max-w-lg max-h-[80vh] flex flex-col`,children:[(0,$.jsx)(co,{className:`flex flex-row items-center justify-between`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsxs)(po,{className:`flex items-center gap-2 shrink-0`,children:[(0,$.jsx)(X,{name:`git-branch`,className:`h-5 w-5`}),i(`session.newWorktree.title`)]}),(0,$.jsx)(`div`,{className:`w-[280px] shrink-0`,children:(0,$.jsx)(Iu,{items:[{id:`new-branch`,label:i(`session.newWorktree.mode.newBranch`),icon:(0,$.jsx)(X,{name:`git-branch`,className:`h-3.5 w-3.5`})},{id:`existing-branch`,label:i(`session.newWorktree.mode.existingBranch`),icon:(0,$.jsx)(X,{name:`git-repository`,className:`h-3.5 w-3.5`})}],activeId:h,onSelect:e=>Oe(e),variant:`active-pill`,layoutMode:`fit`,className:`w-full`})})]})}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto mt-2 space-y-6`,children:[h===`existing-branch`?(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.selectBranch`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(Cs,{open:M,onOpenChange:N,children:[(0,$.jsx)(as,{asChild:!0,children:(0,$.jsxs)(yo,{variant:`outline`,size:`sm`,className:`h-9 min-w-[220px] max-w-full justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:Y(`truncate`,b.selectedBranch?`text-foreground`:`text-muted-foreground`),children:b.selectedBranch||i(`session.newWorktree.chooseBranch`)}),(0,$.jsx)(X,{name:`arrow-down-s`,className:`h-4 w-4 shrink-0 text-muted-foreground`})]})}),(0,$.jsx)($o,{align:`start`,sideOffset:6,portalToBody:!0,className:`w-[min(42rem,calc(100vw-2rem))] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden`,ref:U,children:(0,$.jsxs)(fx,{shouldFilter:!1,children:[(0,$.jsx)(px,{placeholder:i(`session.newWorktree.searchBranches`),value:B,onValueChange:V,onKeyDown:G}),(0,$.jsx)(mx,{disableHorizontal:!0,children:C?(0,$.jsx)(`div`,{className:`px-2 py-4 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.loadingBranches`)}):T.length===0&&E.length===0?(0,$.jsx)(hx,{children:i(`session.newWorktree.noBranchesFound`)}):(0,$.jsxs)($.Fragment,{children:[ce&&ue&&(0,$.jsx)(gx,{heading:i(`session.newWorktree.matchingBranches`),children:oe.matching.map(e=>(0,$.jsx)(vx,{value:e.value,onSelect:()=>{x(t=>({...t,selectedBranch:e.value,worktreeName:Vx(e.label)})),he(e=>({...e,touched:!0})),N(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e.label})},`${e.source}-${e.value}`))}),ce&&!ue&&(0,$.jsx)(`div`,{className:`px-2 py-1 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noMatchingBranches`)}),oe.otherLocal.length>0&&(0,$.jsxs)($.Fragment,{children:[ce&&(0,$.jsx)(_x,{}),(0,$.jsx)(gx,{heading:i(ce?`session.newWorktree.otherLocalBranches`:`session.newWorktree.localBranches`),children:oe.otherLocal.map(e=>(0,$.jsx)(vx,{value:e,onSelect:()=>{x(t=>({...t,selectedBranch:e,worktreeName:Vx(e)})),he(e=>({...e,touched:!0})),N(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`local-${e}`))})]}),oe.otherRemote.length>0&&(0,$.jsxs)($.Fragment,{children:[(oe.otherLocal.length>0||ce)&&(0,$.jsx)(_x,{}),(0,$.jsx)(gx,{heading:i(ce?`session.newWorktree.otherRemoteBranches`:`session.newWorktree.remoteBranches`),children:oe.otherRemote.map(e=>(0,$.jsx)(vx,{value:`remotes/${e}`,onSelect:()=>{x(t=>({...t,selectedBranch:`remotes/${e}`,worktreeName:Vx(e)})),he(e=>({...e,touched:!0})),N(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`remote-${e}`))})]})]})})]})})]}),(0,$.jsx)(yo,{variant:`ghost`,size:`sm`,className:`h-8 w-8 px-0 shrink-0`,onClick:pe,disabled:!fe||C,title:i(`session.newWorktree.fetchBranches`),children:C?(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}):(0,$.jsx)(X,{name:`refresh`,className:`size-4`})})]})]}):(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.branchName`)}),h===`new-branch`&&Ae&&(0,$.jsxs)(yo,{variant:`outline`,size:`sm`,onClick:()=>j(!0),className:`gap-1.5 h-7`,children:[(0,$.jsx)(X,{name:`github`,className:`size-4 text-status-success`}),v.linkedIssue||v.linkedPr?i(`session.newWorktree.actions.change`):i(`session.newWorktree.actions.startFromGitHubIssuePr`)]})]}),(0,$.jsx)(Yo,{value:v.branchName,onChange:e=>{y(t=>({...t,branchName:e.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>he(e=>({...e,touched:!0})),placeholder:i(`session.newWorktree.branchNamePlaceholder`),disabled:!!v.linkedPr,className:Y(`h-8`,me.touched&&me.branchError&&`border-destructive`,v.linkedPr&&`bg-muted text-muted-foreground`)}),v.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground`,children:[(0,$.jsx)(X,{name:`check`,className:`h-3.5 w-3.5 text-status-success`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:i(`session.newWorktree.usingPrBranch`,{branch:v.linkedPr.head})})]}),v.linkedIssue&&!v.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground`,children:[(0,$.jsx)(X,{name:`check`,className:`h-3.5 w-3.5 text-status-success`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:i(`session.newWorktree.fromIssue`,{number:v.linkedIssue.number,title:v.linkedIssue.title})})]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground font-semibold`,children:i(`session.newWorktree.worktreeDirectory`)}),h!==`existing-branch`&&(0,$.jsxs)(`button`,{onClick:()=>{let e=Vx(h===`new-branch`?v.branchName:``);y(t=>({...t,worktreeName:e,isSyncingWorktreeName:!0}))},disabled:!v.branchName||v.worktreeName===Vx(v.branchName),className:Y(`flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded`,v.worktreeName===Vx(v.branchName)||!v.branchName?`text-muted-foreground/40 cursor-not-allowed`:`text-muted-foreground hover:text-foreground hover:bg-muted`),title:i(`session.newWorktree.resetToMatchBranchName`),children:[(0,$.jsx)(X,{name:`refresh`,className:`h-3 w-3`}),(0,$.jsx)(`span`,{children:i(`session.newWorktree.actions.reset`)})]})]}),(0,$.jsx)(Yo,{value:we.worktreeName,onChange:e=>{h===`new-branch`?y(t=>({...t,worktreeName:e.target.value,isSyncingWorktreeName:!1})):x(t=>({...t,worktreeName:e.target.value}))},onBlur:()=>he(e=>({...e,touched:!0})),placeholder:i(`session.newWorktree.worktreeDirectoryPlaceholder`),className:Y(`h-8`,me.touched&&me.worktreeError&&`border-destructive`)})]}),h===`new-branch`&&!v.linkedPr&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.sourceBranch`)}),(0,$.jsxs)(Cs,{open:P,onOpenChange:F,children:[(0,$.jsx)(as,{asChild:!0,children:(0,$.jsxs)(yo,{variant:`outline`,size:`sm`,className:`h-9 min-w-[220px] max-w-full justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:Y(`truncate`,v.sourceBranch?`text-foreground`:`text-muted-foreground`),children:v.sourceBranch||i(`session.newWorktree.selectSourceBranchPlaceholder`)}),(0,$.jsx)(X,{name:`arrow-down-s`,className:`h-4 w-4 shrink-0 text-muted-foreground`})]})}),(0,$.jsx)($o,{align:`start`,portalToBody:!0,className:`w-[min(42rem,calc(100vw-2rem))] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden`,ref:te,children:(0,$.jsxs)(fx,{shouldFilter:!1,children:[(0,$.jsx)(px,{placeholder:i(`session.newWorktree.searchBranches`),value:H,onValueChange:ee,onKeyDown:G}),(0,$.jsx)(mx,{disableHorizontal:!0,children:C?(0,$.jsx)(`div`,{className:`px-2 py-4 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.loadingBranches`)}):T.length===0&&E.length===0?(0,$.jsx)(hx,{children:i(`session.newWorktree.noBranchesFound`)}):(0,$.jsxs)($.Fragment,{children:[le&&de&&(0,$.jsx)(gx,{heading:i(`session.newWorktree.matchingBranches`),children:se.matching.map(e=>(0,$.jsx)(vx,{value:e.value,onSelect:()=>{y(t=>({...t,sourceBranch:e.value})),F(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e.label})},`${e.source}-${e.value}`))}),le&&!de&&(0,$.jsx)(`div`,{className:`px-2 py-1 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noMatchingBranches`)}),se.otherLocal.length>0&&(0,$.jsxs)($.Fragment,{children:[le&&(0,$.jsx)(_x,{}),(0,$.jsx)(gx,{heading:i(le?`session.newWorktree.otherLocalBranches`:`session.newWorktree.localBranches`),children:se.otherLocal.map(e=>(0,$.jsx)(vx,{value:e,onSelect:()=>{y(t=>({...t,sourceBranch:e})),F(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`local-${e}`))})]}),se.otherRemote.length>0&&(0,$.jsxs)($.Fragment,{children:[(se.otherLocal.length>0||le)&&(0,$.jsx)(_x,{}),(0,$.jsx)(gx,{heading:i(le?`session.newWorktree.otherRemoteBranches`:`session.newWorktree.remoteBranches`),children:se.otherRemote.map(e=>(0,$.jsx)(vx,{value:`remotes/${e}`,onSelect:()=>{y(t=>({...t,sourceBranch:`remotes/${e}`})),F(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`remote-${e}`))})]})]})})]})})]}),v.sourceBranch&&(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:i(`session.newWorktree.newBranchFromSource`,{source:v.sourceBranch})})]}),(v.linkedIssue||v.linkedPr)&&h===`new-branch`&&(0,$.jsxs)(`div`,{className:`mt-2 px-2 py-1.5 rounded bg-muted/30`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`github`,className:`h-3.5 w-3.5 text-status-success shrink-0`}),v.linkedIssue&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground shrink-0`,children:i(`session.newWorktree.issueNumber`,{number:v.linkedIssue.number})}),v.linkedPr&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground shrink-0`,children:i(`session.newWorktree.prNumber`,{number:v.linkedPr.number})}),(0,$.jsx)(`span`,{className:`typography-micro text-foreground truncate flex-1`,children:v.linkedIssue?.title||v.linkedPr?.title}),(0,$.jsx)(`a`,{href:v.linkedIssue?.url||v.linkedPr?.url,target:`_blank`,rel:`noopener noreferrer`,className:`text-muted-foreground hover:text-foreground shrink-0`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(X,{name:`external-link`,className:`h-3 w-3`})}),(0,$.jsx)(`button`,{onClick:Me,className:`text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors`,children:(0,$.jsx)(X,{name:`close`,className:`h-3.5 w-3.5`})})]}),v.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-0.5 pl-5`,children:[(0,$.jsxs)(`span`,{className:`typography-micro text-muted-foreground`,children:[v.linkedPr.head,` → `,v.linkedPr.base]}),v.includePrDiff&&(0,$.jsx)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-success/10 text-status-success`,children:i(`session.newWorktree.includeDiffBadge`)})]})]})]}),(0,$.jsxs)(lo,{className:`mt-1 flex items-center justify-between`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-1.5 text-destructive`,children:me.touched&&(me.branchError||me.worktreeError)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{name:`error-warning`,className:`h-3.5 w-3.5`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:me.branchError||me.worktreeError})]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(yo,{variant:`outline`,size:`sm`,onClick:()=>t(!1),disabled:ge,children:i(`session.newWorktree.actions.cancel`)}),(0,$.jsxs)(yo,{size:`sm`,onClick:De,disabled:!je||ge,className:`gap-1.5`,children:[ge&&(0,$.jsx)(X,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}),i(ge?`session.newWorktree.actions.creating`:`session.newWorktree.actions.createWorktree`)]})]})]})]})}),(0,$.jsx)(Rx,{open:A,onOpenChange:j,onSelect:ke})]})}function qx(e){let t=e.selectedDirectory??e.projectRootOption?.value??e.worktreeOptions[0]?.value??null;return t?e.projectRootOption?.value===t?e.projectRootOption.label?.trim()||null:e.worktreeOptions.find(e=>e.value===t)?.label?.trim()||null:null}function Jx(e,t){if(!e||!t)return!1;let n=t.replace(/\\/g,`/`).replace(/\/+$/,``);if(!n)return!1;let r=n===`/`?`/`:n.split(`/`).pop()||``;return!!r&&e===r}var Yx=(e,t)=>e??t??null,Xx=(e,t)=>!!e&&t!==!1,Zx=e=>e?.length?{localBranches:e.filter(e=>!e.startsWith(`remotes/`)).sort(),remoteBranches:e.filter(e=>e.startsWith(`remotes/`)).map(e=>e.replace(/^remotes\//,``)).sort()}:{localBranches:[],remoteBranches:[]},Qx=e=>e.replace(/^remotes\//,``).trim(),$x=e=>{let t=Qx(e),n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t},eS=({directory:e,projectDirectory:t,label:n,projectRootOption:r,worktreeOptions:i,onSelectDirectory:a,className:o,maxWidthClassName:s=`max-w-[48vw] sm:max-w-[20rem]`,presentation:c=`dropdown`})=>{let{t:l}=Zt(),{git:u}=ic(),d=Yx(t,e),f=e,p=Vc(d),m=Vc(f),h=Xx(d,p),g=f!==d&&Xx(f,m),_=lc(d,u,h),v=lc(f,u,g),y=_.data,x=f===d?y:v.data,S=Tc(e=>e.fetchStatus),C=Tc(e=>f&&e.directories.get(f)?.status?.current?.trim()||null),[w,T]=Z.useState(!1),E=Bc(d,u,h&&w).data??[],[D,O]=Z.useState(null),[k,A]=Z.useState(!1),[j,M]=Z.useState(!1),N=Gi(e=>e.projects),P=Gi(e=>e.activeProjectId);Z.useEffect(()=>{u&&(d&&p===null&&S(d,u,{silent:!0}),f&&f!==d&&m===null&&S(f,u,{silent:!0}))},[S,u,p,m,d,f]);let F=Z.useMemo(()=>{let e=b(t);if(e){let t=N.find(t=>b(t.path)===e);if(t)return t.id}return P},[P,t,N]),{localBranches:I,remoteBranches:L}=Z.useMemo(()=>Zx(y?.all),[y]),R=x?.current?.trim()||C||null,z=!Jx(n,e)&&n||R||n||l(`chat.chatInput.branch`),B=q(async()=>{if(!u)return;let e=new Set;d&&e.add(d),f&&e.add(f),await Promise.all([...e].map(async e=>{await bc(e,u),await S(e,u,{silent:!0})}))}),V=q(e=>{let t=Qx(e),n=$x(t);return i.find(e=>{let r=e.label.trim();return r===t||r===n})??null}),H=q(async e=>{if(!f||!u)return;let t=Qx(e);if(R!==t&&R!==$x(t))try{await u.checkoutBranch(f,t),fa.success(l(`gitView.toast.checkedOut`,{name:t})),await B()}catch(e){let n=e instanceof Error?e.message:l(`gitView.toast.checkoutFailed`,{name:t});fa.error(n)}}),ee=q(e=>{let t=Qx(e);if(!t||R===t||R===$x(t))return;let n=V(t);if(n){a(n.value);return}O(t)}),U=q(async()=>{if(!(!D||k)){A(!0);try{await H(D),O(null)}finally{A(!1)}}}),te=q(async()=>{if(!(!D||k)){A(!0);try{await ix({branch:D,projectDirectory:t??void 0})&&O(null)}finally{A(!1)}}}),W=q(async(e,t)=>{if(!f||!u)return;let n=t?.name??`origin`;try{await u.createBranch(f,e,R??`HEAD`),fa.success(l(`gitView.toast.createdBranch`,{name:e})),O(e),u.gitPush(f,{remote:n,branch:e,options:[`--set-upstream`]}).then(async()=>{await B(),fa.success(l(`gitView.toast.upstreamSet`,{branch:e,remote:n}))}).catch(async e=>{let t=e instanceof Error?e.message:l(`gitView.toast.branchCreatedLocally`);fa.warning(l(`gitView.toast.branchCreatedLocally`),{description:(0,$.jsx)(`span`,{className:`text-foreground/80 dark:text-foreground/70`,children:t})}),await B()})}catch(e){let t=e instanceof Error?e.message:l(`gitView.toast.createBranchFailed`);throw fa.error(t),e}}),ne=q(()=>{let e=Gi.getState(),n=b(t),r=n?e.projects.find(e=>b(e.path)===n)??null:null;r&&e.activeProjectId!==r.id&&e.setActiveProjectIdOnly(r.id),M(!0)}),G=q((e,n)=>{if(M(!1),n?.sessionId){J.getState().setCurrentSession(n.sessionId,e);return}let r=Gi.getState(),i=b(t),a=(i?r.projects.find(e=>b(e.path)===i)??null:null)?.id??r.activeProjectId??null,o=J.getState();if(o.newSessionDraft?.open){o.overrideNewSessionDraftTarget({...a?{selectedProjectId:a}:{},directoryOverride:e,bootstrapPendingDirectory:e,preserveDirectoryOverride:!0}),lt.getState().setDirectory(e,{showOverlay:!1});return}o.openNewSessionDraft({...a?{selectedProjectId:a}:{},directoryOverride:e,preserveDirectoryOverride:!0})}),K=(0,$.jsxs)(`button`,{type:`button`,className:Y(`group relative inline-flex min-w-0 w-fit items-center gap-1.5 rounded-lg !border-0 px-1.5 font-medium text-foreground/80`,c===`mobile-sheet`?`h-[26px] text-[11px] leading-none`:`h-6 py-1 pr-1.5 typography-micro transition-[padding] hover:pr-5 focus-visible:pr-5 data-[popup-open]:pr-5`,s,_v,o),"aria-label":z,children:[(0,$.jsx)(X,{name:`git-branch`,className:`size-3.5 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:z}),c===`dropdown`?(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`}):null]});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Fx,{currentBranch:R,localBranches:I,remoteBranches:L,branchInfo:y?.branches,onCheckout:ee,onCreate:W,remotes:E,trigger:K,triggerLabel:z,hideTooltip:!0,projectRootOption:r,worktreeOptions:i,selectedDirectory:e,onSelectDirectory:a,onCreateWorktree:ne,open:w,presentation:c,onOpenChange:T}),j?(0,$.jsx)(Kx,{open:!0,projectId:F,onOpenChange:M,onWorktreeCreated:G}):null,(0,$.jsx)(go,{open:!!D,onOpenChange:e=>{!e&&!k&&O(null)},children:(0,$.jsxs)(fo,{showCloseButton:!1,className:`max-w-sm gap-4`,children:[(0,$.jsxs)(co,{children:[(0,$.jsx)(po,{children:l(`chat.chatInput.branchSwitch.title`,{branch:D??``})}),(0,$.jsx)(mo,{children:l(`chat.chatInput.branchSwitch.description`)})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`button`,{type:`button`,disabled:k,onClick:()=>{U()},className:`flex w-full flex-col items-start gap-0.5 rounded-lg border border-border px-3 py-2.5 text-left hover:bg-interactive-hover disabled:opacity-50`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 typography-ui-label font-medium text-foreground`,children:[k?(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin`}):(0,$.jsx)(X,{name:`arrow-left-right`,className:`size-3.5 text-muted-foreground`}),l(`chat.chatInput.branchSwitch.checkoutHere`)]}),(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground`,children:l(`chat.chatInput.branchSwitch.checkoutHereDescription`)})]}),(0,$.jsxs)(`button`,{type:`button`,disabled:k,onClick:()=>{te()},className:`flex w-full flex-col items-start gap-0.5 rounded-lg border border-border px-3 py-2.5 text-left hover:bg-interactive-hover disabled:opacity-50`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 typography-ui-label font-medium text-foreground`,children:[k?(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin`}):(0,$.jsx)(X,{name:`git-branch`,className:`size-3.5 text-muted-foreground`}),l(`chat.chatInput.branchSwitch.createWorktree`)]}),(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground`,children:l(`chat.chatInput.branchSwitch.createWorktreeDescription`)})]})]}),(0,$.jsx)(lo,{children:(0,$.jsx)(`button`,{type:`button`,disabled:k,onClick:()=>O(null),className:`inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 disabled:opacity-50`,children:l(`chat.chatInput.branchSwitch.cancel`)})})]})})]})},tS=[],nS=[],rS={revertMessageID:void 0,records:nS},iS=e=>e.role===`user`,aS=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.message!==t[n]?.message||e[n]?.parts!==t[n]?.parts)return!1;return!0},oS=(e,t,n=rS)=>{if(!t)return rS;let r=(`session`in e?e.session:[]).find(e=>e.id===t)?.revert?.messageID;if(!r)return rS;let i=`messages`in e?e.messages:e.message[t]??[],a=`partsByMessageID`in e?e.partsByMessageID:e.part,o=[];for(let e of i)!iS(e)||!Ka(i,e.id,r)||o.push({message:e,parts:a[e.id]??tS});let s=o.length===0?nS:o;return n.revertMessageID===r&&aS(n.records,s)?n:{revertMessageID:r,records:s}},sS={mentionFile:100,mentionAgent:100,mentionSession:100,mentionCommand:100,mentionSnippet:100,mentionPaste:100,code:90,codeFence:90,link:80,linkUrl:78,heading:70,blockquote:40,listMarker:35,marker:10},cS={mentionFile:`text-[var(--primary)]`,mentionAgent:`text-[var(--primary)]`,mentionSession:`text-[var(--primary)]`,mentionCommand:`text-[var(--primary)]`,mentionSnippet:`text-[var(--primary)]`,mentionPaste:`text-[var(--primary)]`,code:`rounded-[3px] bg-[var(--surface-subtle)] text-[var(--markdown-inline-code)]`,codeFence:`bg-[var(--surface-subtle)] text-[var(--markdown-inline-code)]`,link:`text-[var(--status-info)] underline`,linkUrl:`text-muted-foreground`,heading:`text-[var(--syntax-keyword)]`,blockquote:`text-muted-foreground`,listMarker:`text-[var(--syntax-keyword)]`,marker:`text-muted-foreground`},lS=`text-foreground`;function uS(e,t,n){let r=0,i=e.length;for(;r<i;){let i=e[r];if(i==="`"){let i=/^`+/.exec(e.slice(r))?.[0]??``,a=e.indexOf(i,r+i.length);if(a!==-1){let e=a+i.length;n.push({start:t+r,end:t+e,style:`code`}),r=e;continue}}if(i===`[`){let i=/^\[([^\]\n]*)\]\(([^)\n]*)\)/.exec(e.slice(r));if(i){let e=t+r,a=i[1].length,o=i[2].length,s=e+1,c=s+a,l=c+2,u=l+o,d=u+1;n.push({start:e,end:s,style:`marker`}),a>0&&n.push({start:s,end:c,style:`link`}),n.push({start:c,end:l,style:`marker`}),o>0&&n.push({start:l,end:u,style:`linkUrl`}),n.push({start:u,end:d,style:`marker`}),r+=i[0].length;continue}}r+=1}}var dS=/^(\s*)(`{3,}|~{3,})\s*(\S*)/;function fS(e){let t=dS.exec(e);return t?{marker:t[2],lang:t[3]||``}:null}function pS(e,t){return RegExp(`^\\s*\\${t[0]}{${t.length},}\\s*$`).test(e)}function mS(e){let t=[];if(!e)return t;let n=0,r=!1,i=``,a=e.split(`
6524
6524
  `);for(let e=0;e<a.length;e+=1){let o=a[e],s=n,c=s+o.length;if(n=c+1,r){t.push({start:s,end:c,style:`codeFence`}),pS(o,i)&&(r=!1);continue}let l=fS(o);if(l){r=!0,i=l.marker,t.push({start:s,end:c,style:`codeFence`});continue}let u=/^(\s*)(#{1,6})(\s+)/.exec(o);if(u){let e=s+u[1].length,n=e+u[2].length;t.push({start:e,end:n,style:`marker`});let r=n+u[3].length;c>r&&(t.push({start:r,end:c,style:`heading`}),uS(o.slice(r-s),r,t));continue}let d=/^(\s*)(>+)(\s?)/.exec(o);if(d){let e=s+d[1].length,n=e+d[2].length;t.push({start:e,end:n,style:`marker`});let r=n+d[3].length;c>r&&(t.push({start:r,end:c,style:`blockquote`}),uS(o.slice(r-s),r,t));continue}let f=/^(\s*)([-*+]|\d{1,9}[.)])(\s+)/.exec(o);if(f){let e=s+f[1].length,n=e+f[2].length;t.push({start:e,end:n,style:`listMarker`});let r=n+f[3].length;uS(o.slice(r-s),r,t);continue}uS(o,s,t)}return t}function hS(e,t){if(!e||t.length===0)return null;let n=e.length,r=new Set([0,n]);for(let e of t)e.start>0&&e.start<n&&r.add(e.start),e.end>0&&e.end<n&&r.add(e.end);let i=[...r].sort((e,t)=>e-t),a=t.map((e,t)=>({range:e,index:t})).filter(e=>e.range.end>e.range.start).sort((e,t)=>e.range.start-t.range.start),o=[],s=[],c=0;for(let t=0;t<i.length-1;t+=1){let n=i[t],r=i[t+1];if(r<=n)continue;for(;c<a.length&&a[c].range.start<=n;)s.push(a[c]),c+=1;for(let e=s.length-1;e>=0;--e)s[e].range.end<=n&&s.splice(e,1);let l=null,u=-1,d=1/0;for(let{range:e,index:t}of s){let n=e.priority??sS[e.style];(n>u||n===u&&t<d)&&(u=n,d=t,l=e)}let f=l?l.className??cS[l.style]:lS,p=e.slice(n,r),m=l?.visual,h=l?.skillName,g=o[o.length-1];g&&g.className===f&&ce(g.visual,m)&&g.skillName===h?g.text+=p:o.push({text:p,className:f,visual:m,skillName:h})}return o.length>0?o:null}function gS(e,t){let n=new Set(Array.from(t,e=>e.toLowerCase())),r=[],i=/(^|\s)\/(\u2003)?([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)/gi,a;for(;(a=i.exec(e))!==null;){let e=a[2]??``,t=a[3]||``;if(!n.has(t.toLowerCase()))continue;let i=a.index+(a[1]?.length??0);r.push({start:i,end:i+1+e.length+t.length,name:t})}return r}function _S(e,t,n){if(e===t){let t=n.find(t=>e>t.start&&e<t.end);return t?{start:t.start,end:t.end}:null}let r=n.filter(n=>n.start<t&&n.end>e);return r.length===0?null:{start:Math.min(e,...r.map(e=>e.start)),end:Math.max(t,...r.map(e=>e.end))}}function vS(e,t,n){let r=gS(e,t),i=Math.max(0,Math.min(n.selectionStart,e.length)),a=Math.max(i,Math.min(n.selectionEnd,e.length)),o=i,s=a;if(i===a)if(n.altKey)if(n.key===`Backspace`){for(;o>0&&/\s/.test(e[o-1]);)--o;for(;o>0&&!/\s/.test(e[o-1]);)--o}else{for(;s<e.length&&/\s/.test(e[s]);)s+=1;for(;s<e.length&&!/\s/.test(e[s]);)s+=1}else n.key===`Backspace`?o=Math.max(0,i-1):s=Math.min(e.length,i+1);if(o===s)return null;let c=r.filter(e=>e.start<s&&e.end>o);if(c.length===0)return null;let l=Math.min(o,...c.map(e=>e.start)),u=Math.max(s,...c.map(e=>e.end));return u<e.length&&/\s/.test(e[u])&&(l===0||/\s/.test(e[l-1]))?u+=1:u===e.length&&l>0&&/\s/.test(e[l-1])&&--l,{text:`${e.slice(0,l)}${e.slice(u)}`,caret:l,removedSkillNames:c.map(e=>e.name)}}function yS(e){return e.map(e=>({start:e.start,end:e.end,style:e.kind===`file`?`mentionFile`:e.kind===`session`?`mentionSession`:`mentionAgent`,visual:e.kind===`session`&&e.label?De({trigger:`@`,icon:`chat-thread`,label:e.label},me({trigger:`@`,icon:`chat-thread`,label:e.label})):void 0}))}function bS(e){let t=(0,Q.c)(28),{visual:n,text:r}=e,i=n.trigger.length,a=i+n.label.length,o=a+(n.suffix?.length??0),s;t[0]!==a||t[1]!==i||t[2]!==r?(s=r.slice(i,Math.min(a,r.length)),t[0]=a,t[1]=i,t[2]=r,t[3]=s):s=t[3];let c=s,l;t[4]!==a||t[5]!==o||t[6]!==r?(l=r.slice(a,Math.min(o,r.length)),t[4]=a,t[5]=o,t[6]=r,t[7]=l):l=t[7];let u=l,d;t[8]!==o||t[9]!==r?(d=r.slice(Math.min(o,r.length)),t[8]=o,t[9]=r,t[10]=d):d=t[10];let f=d,p;t[11]===Symbol.for(`react.memo_cache_sentinel`)?(p={left:de,right:de},t[11]=p):p=t[11];let m=n.icon,h;t[12]===m?h=t[13]:(h=(0,$.jsx)(`span`,{className:`pointer-events-none absolute inset-y-0 inline-flex items-center justify-center`,style:p,children:(0,$.jsx)(X,{name:m,className:`${G} shrink-0 text-[var(--primary)]`,"aria-hidden":`true`})}),t[12]=m,t[13]=h);let g;t[14]!==h||t[15]!==n.trigger?(g=(0,$.jsxs)(`span`,{className:`relative inline-block align-baseline text-transparent leading-none`,children:[n.trigger,h]}),t[14]=h,t[15]=n.trigger,t[16]=g):g=t[16];let _;t[17]===c?_=t[18]:(_=(0,$.jsx)(`span`,{children:c}),t[17]=c,t[18]=_);let v;t[19]===u?v=t[20]:(v=u?(0,$.jsx)(`span`,{className:`text-transparent`,children:u}):null,t[19]=u,t[20]=v);let y;t[21]===f?y=t[22]:(y=f?(0,$.jsx)(`span`,{className:`text-transparent`,children:f}):null,t[21]=f,t[22]=y);let b;return t[23]!==y||t[24]!==g||t[25]!==_||t[26]!==v?(b=(0,$.jsxs)($.Fragment,{children:[g,_,v,y]}),t[23]=y,t[24]=g,t[25]=_,t[26]=v,t[27]=b):b=t[27],b}var xS=`bg-[var(--surface-subtle)]`,SS=91,CS=94,wS={keyword:8,function:7,type:6,string:5,number:5,variable:4,operator:3,comment:2},TS={keyword:`${xS} text-[var(--syntax-keyword)]`,string:`${xS} text-[var(--syntax-string)]`,number:`${xS} text-[var(--syntax-number)]`,comment:`${xS} text-[var(--syntax-comment)]`,function:`${xS} text-[var(--syntax-function)]`,type:`${xS} text-[var(--syntax-type)]`,variable:`${xS} text-[var(--syntax-variable)]`,operator:`${xS} text-[var(--syntax-operator)]`},ES=It([{tag:[Rt.comment,Rt.lineComment,Rt.blockComment,Rt.docComment,Rt.meta],class:`comment`},{tag:[Rt.keyword,Rt.modifier,Rt.controlKeyword,Rt.operatorKeyword,Rt.definitionKeyword,Rt.moduleKeyword,Rt.self,Rt.null],class:`keyword`},{tag:[Rt.string,Rt.special(Rt.string),Rt.docString,Rt.character,Rt.regexp],class:`string`},{tag:[Rt.number,Rt.integer,Rt.float,Rt.bool,Rt.atom],class:`number`},{tag:[Rt.function(Rt.variableName),Rt.function(Rt.propertyName),Rt.macroName,Rt.standard(Rt.variableName)],class:`function`},{tag:[Rt.typeName,Rt.className,Rt.namespace,Rt.tagName],class:`type`},{tag:[Rt.variableName,Rt.propertyName,Rt.attributeName,Rt.labelName,Rt.definition(Rt.variableName)],class:`variable`},{tag:[Rt.operator,Rt.punctuation,Rt.bracket,Rt.derefOperator,Rt.separator],class:`operator`},{tag:[Rt.heading,Rt.heading1,Rt.heading2,Rt.heading3,Rt.heading4,Rt.heading5,Rt.heading6,Rt.strong],class:`keyword`},{tag:[Rt.emphasis,Rt.quote],class:`type`},{tag:[Rt.link,Rt.url],class:`function`},{tag:[Rt.monospace],class:`string`},{tag:[Rt.strikethrough],class:`comment`}]),DS=e=>{let t=null;for(let n of e.split(` `)){let e=n;wS[e]!==void 0&&(t===null||wS[e]>wS[t])&&(t=e)}return t?TS[t]:null},OS=2e4,kS=e=>{if(!e)return null;try{let t=Fs(e);return t instanceof zt?t:null}catch{return null}};function AS(e){if(!e||!e.includes("```")&&!e.includes(`~~~`))return[];let t=[],n=e.split(`
6525
6525
  `),r=0;for(let e=0;e<n.length;e+=1){let i=n[e];r+=i.length+1;let a=fS(i);if(!a)continue;let o=kS(a.lang),s=r,c=[],l=e+1,u=r;for(;l<n.length;l+=1){let e=n[l];if(pS(e,a.marker)){u+=e.length+1;break}c.push(e),u+=e.length+1}if(e=l,r=u,!o||c.length===0)continue;let d=c.join(`
6526
- `);if(d.trim()&&(t.push({start:s,end:s+d.length,style:`codeFence`,className:`${xS} text-[var(--syntax-foreground)]`,priority:SS}),!(d.length>OS)))try{let e=o.parser.parse(d);Lt(e,ES,(e,n,r)=>{let i=DS(r);i&&t.push({start:s+e,end:s+n,style:`codeFence`,className:i,priority:CS})})}catch{}}return t}var jS=[`CodeFiles`,`codefiles`,`application/vnd.code.tree`,`application/vnd.code.tree.explorer`,`text/uri-list`,`text/plain`],MS=e=>e.startsWith(`/`)||e.startsWith(`//`)||e.startsWith(`\\\\`)||/^[A-Za-z]:[\\/]/.test(e),NS=e=>{if(!MS(e)||/\s/.test(e))return!1;if(e.startsWith(`//`)||e.startsWith(`\\\\`)){let t=e.replace(/^[\\/]+/,``);return/[\\/]/.test(t)}if(/^[A-Za-z]:[\\/]/.test(e)){let t=e.slice(3);return t.includes(`\\`)||t.includes(`/`)||t.includes(`.`)}return e.replace(/^\/+/,``).includes(`/`)},PS=(e,{fromPlainText:t=!1}={})=>{let n=e.trim().replace(/^['"]+|['"]+$/g,``);return!n||n===`/>`||/[\r\n]/.test(n)?null:n.toLowerCase().startsWith(`file://`)||(t?NS(n):MS(n))?n:null},FS=(e,t,n=0)=>{if(!(n>6||e==null)){if(typeof e==`string`){t.add(e);return}if(Array.isArray(e)){for(let r of e)FS(r,t,n+1);return}if(typeof e==`object`)for(let r of Object.values(e))FS(r,t,n+1)}},IS=(e,{allowMultipleLines:t=!0,allowStructuredPayload:n=!0,fromPlainText:r=!1}={})=>{let i=new Set,a=e=>{let n=PS(e,{fromPlainText:r});if(n){i.add(n);return}if(t)for(let t of e.split(/\r?\n/)){let e=PS(t,{fromPlainText:r});e&&i.add(e)}};if(a(e),n)try{let t=JSON.parse(e),n=new Set;FS(t,n);for(let e of n)a(e)}catch{}return Array.from(i)},LS=e=>{if(!e||typeof e.getData!=`function`)return[];let t=new Set;for(let n of jS){let r=``;try{r=e.getData(n)}catch{continue}let i=n===`text/plain`?{allowMultipleLines:!1,allowStructuredPayload:!1,fromPlainText:!0}:n===`text/uri-list`?{allowStructuredPayload:!1}:void 0;for(let e of IS(r,i))t.add(e)}return Array.from(t)},RS=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(`file://`))return t;try{let e=new URL(t),n=decodeURIComponent(e.pathname||``);return e.hostname&&e.hostname!==`localhost`&&(n=`//${e.hostname}${n}`),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1)),n||t}catch{let e=t.replace(/^file:\/\//i,``);try{return decodeURIComponent(e)}catch{return e}}},zS=e=>MS(e);function BS(e,t){let n=(0,Q.c)(5),r=Dr(e,t),i=g(VS),a;n[0]===r?a=n[1]:(a=Zi(r),n[0]=r,n[1]=a);let o;return n[2]!==i||n[3]!==a?(o={goal:a,enabled:i},n[2]=i,n[3]=a,n[4]=o):o=n[4],o}function VS(e){return e.sessionGoalEnabled}function HS(e,t){let n=(0,Q.c)(4),[r,i]=Z.useState(null),a=t?.objectiveFile?`${e}:${t.id}:${t.updatedAt}`:``,o,s;return n[0]!==a||n[1]!==e?(o=()=>{if(!a){i(null);return}let t=!0;return Ir(e).then(e=>{t&&i(e)}),()=>{t=!1}},s=[a,e],n[0]=a,n[1]=e,n[2]=o,n[3]=s):(o=n[2],s=n[3]),Z.useEffect(o,s),t?t.objectiveFile?r:t.objective:null}var US={active:`var(--status-info)`,paused:`var(--surface-muted-foreground)`,blocked:`var(--status-warning)`,budgetLimited:`var(--status-warning)`,complete:`var(--status-success)`},WS={active:`chat.goal.status.active`,paused:`chat.goal.status.paused`,blocked:`chat.goal.status.blocked`,budgetLimited:`chat.goal.status.budgetLimited`,complete:`chat.goal.status.complete`},GS=Z.memo(({sessionId:e,directory:t,className:n})=>{let{t:r}=Zt(),i=g(e=>e.isMobile),{goal:a,enabled:o}=BS(e??``,t),s=HS(e??``,a),c=sa(e??``,t),l=fi(e,t),u=Z.useRef(null),[d,f]=Z.useState(!1),[p,m]=Z.useState(()=>Date.now());Z.useEffect(()=>{if(!a||a.status===`complete`||a.status===`blocked`||a.status===`budgetLimited`)return;let e=window.setInterval(()=>m(Date.now()),1e3);return()=>window.clearInterval(e)},[a?.id,a?.status]),Z.useEffect(()=>{if(!e||!a||a.status!==`active`)return;let n=l[0]?.id;if(!n)return;let r=`${e}:${a.id}:${n}`;u.current!==r&&(u.current=r,Dn(e,t))},[e,t,a,l]);let h=q(async n=>{if(!(!e||d)){f(!0);try{await bn(e,t,n)}catch(e){console.warn(`[session-goal] status change failed:`,e),fa.error(r(`chat.goal.toast.actionFailed`))}finally{f(!1)}}});if(!e||!o||!a)return null;let _=Math.max(0,(a.status===`complete`||a.status===`blocked`||a.status===`budgetLimited`?a.updatedAt:p)-(a.createdAt||p)),v=ta(_),y=a.tokenBudget?`${ln(a.tokensUsed)}/${ln(a.tokenBudget)}`:a.tokensUsed>0?ln(a.tokensUsed):null,b=a.status===`active`?{icon:`pause`,labelKey:`chat.goal.action.pause`,next:`paused`}:a.status===`paused`||a.status===`blocked`||a.status===`budgetLimited`?{icon:`play`,labelKey:`chat.goal.action.resume`,next:`active`}:null,x=i?`text-[11px] leading-none text-muted-foreground`:`typography-meta text-muted-foreground`,S=i?`text-xs leading-5 text-foreground`:`typography-ui-label leading-5 text-foreground`,C=i?`size-3`:`size-3.5`;return(0,$.jsxs)(`div`,{className:Y(`flex w-full min-w-0 items-center`,i?`gap-1 py-0.5`:`gap-1.5 py-0.5 md:gap-2`,n),"aria-label":r(`chat.goal.row.aria`),title:s??void 0,children:[(0,$.jsx)(X,{name:`target`,className:Y(C,`flex-shrink-0`),style:{color:US[a.status]},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`min-w-0 flex-1 truncate`,S),children:a.note||s||``}),a.status===`active`&&(!c||c.type===`idle`)?(0,$.jsxs)(`span`,{className:Y(`flex flex-shrink-0 items-center gap-1`,x),children:[(0,$.jsx)(X,{name:`loader-4`,className:Y(C,`animate-spin`),"aria-hidden":`true`}),r(`chat.goal.status.evaluating`)]}):(0,$.jsx)(`span`,{className:Y(`flex-shrink-0`,x),children:r(WS[a.status])}),(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums`,x,`text-muted-foreground/70`),children:v}),y?(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums`,x,`text-muted-foreground/70`),children:y}):null,b?(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void h(b.next),disabled:d,className:Y(`inline-flex flex-shrink-0 cursor-pointer items-center bg-transparent text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50`,i?`h-7 gap-1.5 px-0 text-[11px]`:`h-7 gap-1 px-0.5`),"aria-label":r(b.labelKey),children:[(0,$.jsx)(X,{name:b.icon,className:C,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`font-medium`,i?`leading-none`:`typography-ui-label`),children:r(b.labelKey)})]}):null]})});GS.displayName=`SessionGoalRow`;var KS=Z.memo(({sessionId:e,directory:t,draftOpen:n=!1})=>{let{t:r}=Zt(),{goal:i,enabled:a}=BS(e??``,t),o=En(e=>e.armed),s=En(e=>e.setArmed),[c,l]=Z.useState(!1);if(x()||!a||!e&&!n||!o&&!i)return null;let u=i?.status===`complete`?`text-[var(--status-success)]`:i?.status===`blocked`||i?.status===`budgetLimited`?`text-[var(--status-error)]`:o||i?.status===`active`||i?.status===`paused`?`text-[var(--status-info)]`:``,d=async()=>{if(o){s(!1);return}if(!(!e||c)){l(!0);try{await Ga(e,t)}catch(e){console.warn(`[session-goal] clear failed:`,e),fa.error(r(`chat.goal.toast.actionFailed`))}finally{l(!1)}}};return(0,$.jsxs)(`span`,{className:Y(`inline-flex h-7 items-center gap-1 rounded-full bg-[var(--surface-muted)] py-1 pl-2 pr-1 typography-ui-label`,u),children:[(0,$.jsx)(X,{name:`target`,className:`h-4 w-4`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:r(`chat.goal.chip.label`)}),(0,$.jsx)(`button`,{type:`button`,className:`flex h-5 w-5 items-center justify-center rounded-full text-current hover:bg-[var(--interactive-hover)] disabled:opacity-50`,onClick:()=>void d(),disabled:c,"aria-label":r(o?`chat.goal.button.disarmAria`:`chat.goal.action.clear`),title:r(o?`chat.goal.button.disarmAria`:`chat.goal.action.clear`),children:(0,$.jsx)(X,{name:`close`,className:`h-3 w-3`,"aria-hidden":`true`})})]})});KS.displayName=`SessionGoalButton`;var qS=Z.memo(e=>{let t=(0,Q.c)(11),{length:n}=e,{t:r}=Zt();if(!En(JS)||n===0)return null;let i=n>5e3?`text-[var(--status-error)]`:`text-muted-foreground/70`,a;t[0]===i?a=t[1]:(a=Y(`flex-shrink-0 self-center typography-micro tabular-nums`,i),t[0]=i,t[1]=a);let o;t[2]===r?o=t[3]:(o=r(`chat.goal.counter.aria`),t[2]=r,t[3]=o);let s;t[4]===r?s=t[5]:(s=r(`chat.goal.counter.aria`),t[4]=r,t[5]=s);let c;return t[6]!==n||t[7]!==a||t[8]!==o||t[9]!==s?(c=(0,$.jsxs)(`span`,{className:a,"aria-label":o,title:s,children:[n,`/`,mr]}),t[6]=n,t[7]=a,t[8]=o,t[9]=s,t[10]=c):c=t[10],c});qS.displayName=`SessionGoalObjectiveCounter`;function JS(e){return e.armed}var YS=new Set([`new`,`fork`,`compact`,`undo`,`redo`,`timeline`,`model`,`summary`,`workspace-review`,`handoff-review`,`goal`,`craft-goal`,`catch-up`,`debug`,`weigh`,`explore`]),XS=new Set([`new`,`compact`,`fork`,`undo`,`redo`]),ZS=/^\/\u2003?([^\s]+)/i,QS=/^\/\u2003?goal\b/i,$S=(e,t)=>{if(t!==`normal`)return null;let n=e.trimStart().match(ZS)?.[1]?.toLowerCase();return n&&YS.has(n)?n:null},eC=(e,t)=>$S(e,t)===`goal`?e.trimStart().replace(QS,``).trim():null,tC=(e,t)=>$S(e,t)!==null,nC=(e,t)=>{let n=$S(e,t);return n!==null&&XS.has(n)},rC=({currentSessionId:e,messageRef:t,replacePlainDocument:n})=>{let r=e;return t.current=``,n(``),r},iC=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()}},aC=e=>!e.queuedOnly&&!e.resourcePolicy&&e.rootAttachmentCount>0,oC=e=>e.surfaceKind===`primary`&&!!e.currentSessionId&&!e.queuedOnly&&!e.resourcePolicy&&e.inputMode!==`shell`&&!e.localCommand,sC=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},cC=e=>({state:`bound`,transportIdentity:e.transportIdentity,directory:e.directory,sessionID:e.sessionID,deliveryTarget:{kind:`primary`},runtimeGeneration:e.runtimeGeneration}),lC=(e,t)=>{let n=F.getState();return n.bindLegacyQueue(N(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},uC=async e=>{let t=dr.getState().takeEstablishingPending(e.draftID);if(t.length===0)return{drained:0,failed:0};let n=cC(e),r=0,i=0;for(let a of t)try{if(e.admitServer&&(await e.admitServer(a)).status===`committed`){r+=1;continue}lC(n,a)?r+=1:i+=1}catch{try{lC(n,a)?r+=1:i+=1}catch{i+=1}}return{drained:r,failed:i}},dC=(e,t)=>Promise.resolve().then(()=>e()).catch(()=>{t()}),fC=e=>e===`allow`||e===`ask`||e===`deny`,pC=e=>{if(fC(e))return[{permission:`*`,pattern:`*`,action:e}];if(Array.isArray(e))return e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.permission==`string`&&typeof t.pattern==`string`&&fC(t.action)?[{permission:t.permission,pattern:t.pattern,action:t.action}]:[]});if(!e||typeof e!=`object`)return[];let t=[];for(let[n,r]of Object.entries(e))if(n!==`__originalKeys`){if(fC(r)){t.push({permission:n,pattern:`*`,action:r});continue}if(!(!r||typeof r!=`object`||Array.isArray(r)))for(let[e,i]of Object.entries(r))fC(i)&&t.push({permission:n,pattern:e,action:i})}return t},mC=e=>{let t=pC(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.permission===`*`&&n.pattern===`*`)return n.action===`ask`;if(n.action===`ask`)return!0}return!0},hC=(e,t)=>{let n=t?.trim();if(!n)return e.length===0||e.some(e=>mC(e.permission));let r=e.find(e=>e?.name===n);return!r||mC(r.permission)},gC=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)},_C=null,vC=new Set,yC=()=>{for(let e of vC)e()},bC=e=>e===`chat`||e===`assistant`,xC=()=>_C,SC=e=>{_C!==e&&(_C=e,yC())},CC=e=>{_C&&(e&&_C.surfaceID!==e||(_C=null,yC()))},wC=(e,t)=>{if(e.transportIdentity!==t.transportIdentity||e.runtimeGeneration!==t.runtimeGeneration)throw Error(`chat-input-delivery-runtime-stale`)},TC=e=>{let t={...e.options?.delivery===`steer`?{delivery:`steer`}:{},...e.options?.commitStagedMessageEdit===void 0?{}:{commitStagedMessageEdit:e.options.commitStagedMessageEdit},...e.options?.messageID?{messageID:e.options.messageID}:{},...e.options?.ticket?{ticket:e.options.ticket}:{}},n=e.options?.sessionId??e.sessionID??void 0;if(!n)return t;let r=e.options?.directoryHint===void 0?e.directory||null:e.options.directoryHint;return{...t,sessionId:n,directoryHint:r}},EC=(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}),DC=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=EC(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=EC(e,`send`,i),o=Jv(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=EC(e,`create`);return await e.selection.flush(),e.backend.create(t)},compact:async t=>{let n=EC(e,`compact`,t);return await e.selection.flush(),e.backend.compact(n)},abort:async()=>{let t=EC(e,`abort`);return await e.selection.flush(),e.backend.abort(t)},queueScope:Jv(e),canAbort:n,canQueue:t===`busy`||t===`retry`,allowsCommand:t=>Vv(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=EC(e,`abort`);await e.selection.flush(),await e.backend.abort(t);return}if(t===`new`){let t=EC(e,`create`);await e.selection.flush(),await e.backend.create(t);return}t!==`submit`&&await e.shortcuts?.cycle(n)},resources:e.resources??null}},OC=(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)))},kC=(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},AC=(e,t)=>e.agents.some(e=>e.name===t),jC=(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},MC=e=>{let{catalog:t,providerID:n,modelID:r,historyVariant:i,memoryVariant:a}=e;if(i)return jC(t,n,r,i)?i:void 0;if(a&&jC(t,n,r,a))return a},NC=e=>{let{sessionId:t,choice:n,catalog:r,memory:i,fallbackAgentName:a,source:o}=e;if(!n.providerID||!n.modelID||!kC(r,n.providerID,n.modelID))return null;let s=n.agent&&AC(r,n.agent)?n.agent:i?.getSessionAgentSelection?.(t)&&AC(r,i.getSessionAgentSelection(t))?i.getSessionAgentSelection(t):a&&AC(r,a)?a:void 0,c=s?i?.getAgentModelVariantForSession?.(t,s,n.providerID,n.modelID):void 0,l=MC({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}},PC=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=NC({sessionId:t,choice:r,catalog:i,memory:a,fallbackAgentName:s,source:`execution`});if(e)return e}if(c&&n){let e=NC({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&&AC(i,e)?e:s&&AC(i,s)?s:void 0;if(n){let e=a.getAgentModelForSession?.(t,n);if(e&&kC(i,e.providerId,e.modelId)){let r=a.getAgentModelVariantForSession?.(t,n,e.providerId,e.modelId),o=r&&jC(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&&kC(i,r.providerId,r.modelId)){let e=n?a.getAgentModelVariantForSession?.(t,n,r.providerId,r.modelId):void 0,o=e&&jC(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&&kC(i,l.providerID,l.id)){let e=a?.getSessionAgentSelection?.(t)??null,n=(o?.agent&&AC(i,o.agent)?o.agent:void 0)??(e&&AC(i,e)?e:s&&AC(i,s)?s:void 0),r=l.variant,c=r&&jC(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},FC=(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))},IC=(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}},LC=e=>e.editRevision<=0?!1:e.pinnedHistoryMessageId==null||e.latestHistoryMessageId==null||e.latestHistoryMessageId===e.pinnedHistoryMessageId,RC=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}:{}}},zC=e=>typeof e==`string`&&e.trim().length>0?e:void 0,BC=e=>zC(e.agent)??zC(e.mode),VC=e=>zC(e.model?.variant)??zC(e.variant),HC=e=>{let t=zC(e.model?.providerID),n=zC(e.model?.modelID);return!t||!n?null:{providerID:t,modelID:n}},UC=e=>{let t=zC(e.providerID)??zC(e.model?.providerID),n=zC(e.modelID)??zC(e.model?.modelID);return!t||!n?null:{providerID:t,modelID:n}},WC=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role!==`user`)continue;let r=HC(n);return{id:typeof n.id==`string`?n.id:void 0,agent:BC(n),providerID:r?.providerID,modelID:r?.modelID,variant:VC(n)}}return null},GC=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`){if(HC(n))return null;continue}if(n.role!==`assistant`)continue;let r=UC(n);if(r)return{id:typeof n.id==`string`?n.id:void 0,agent:BC(n),providerID:r.providerID,modelID:r.modelID,variant:VC(n)}}return null},KC=500,qC=e=>Array.from(e).length,JC=e=>{let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(36)},YC=e=>qC(e)>=KC,XC=e=>{let t=k(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},ZC=(e,t)=>{let n=t??e;return typeof n!=`string`||!YC(n)?!1:Pe(typeof e==`string`?{text:``,references:[]}:e,n)},QC=(e,t,n,r,i=1)=>{let a=qC(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}-${JC(e)}`,token:i,text:e,characterCount:a,index:n}}throw Error(`Unable to create a unique pasted text reference`)},$C=e=>({text:e.text,references:e.references.map(e=>({...e}))}),ew=e=>e.map(e=>({...e,range:{...e.range}})),tw=(e,t)=>e.text===t.text&&JSON.stringify(e.references)===JSON.stringify(t.references),nw=(e,t,n)=>({document:$C(e),mentions:ew(t),selection:{...n}}),rw=()=>({undo:[],redo:[]}),iw=(e,t)=>({undo:[...e.undo,t].slice(-100),redo:[]}),aw=(e,t)=>{let n=e.undo.at(-1);return!n||!tw(n.after.document,t)?null:{history:{undo:e.undo.slice(0,-1),redo:[...e.redo,n]},snapshot:nw(n.before.document,n.before.mentions,n.before.selection)}},ow=(e,t)=>{let n=e.redo.at(-1);return!n||!tw(n.before.document,t)?null:{history:{undo:[...e.undo,n],redo:e.redo.slice(0,-1)},snapshot:nw(n.after.document,n.after.mentions,n.after.selection)}},sw=e=>({text:e?.text??``,references:e?.composerReferences??[]}),cw=e=>({text:e.text,references:e.references.map(e=>({...e}))}),lw=e=>({transportIdentity:e.transportIdentity,owner:{...e.owner}}),uw=e=>JSON.stringify([e.text,e.references]),dw=(e,t)=>e!==null&&t!==null&&Ne(e)===t,fw=(e,t,n)=>{let r=e?lw(e):null,i=r?n(r):void 0;return{document:z(sw(i),t),mentions:i?.mentions??[],revision:i?.revision??0,key:r,keyID:r?Ne(r):null}},pw=(e,t,n,r)=>{if(!t||Ne(t.key)!==r.keyID||t.revision<r.appliedRevision)return`ignore`;let i=uw(sw(t));return n?.keyID===r.keyID&&n.revision===t.revision&&n.fingerprint===i?`local-echo`:t.revision===r.appliedRevision?`ignore`:i===uw(e)?`same-document-metadata`:`external-document`},mw=(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}]:[]})},hw=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),gw=(e,t,n,r,i=r)=>{let a=D(e,n,r,i);return{document:a.document,mentions:mw(t,a.document,a.edit),requiresTextCorrection:a.requiresTextCorrection,selectionStart:a.selectionStart,selectionEnd:a.selectionEnd,removedReferences:a.removedReferences}},_w=(e,t,n)=>({preview:{real:cw(e),realMentions:[...t]},document:{text:n.text,references:[]},mentions:[]}),vw=e=>({document:e.real,mentions:e.realMentions}),yw=(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)})},bw=(e,t)=>{let n=sw(t),r=R(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:yw(e.mentions,t?.mentions??[],r,i)}},xw=({draftKey:e,sessionTitles:t,persistenceEnabled:n,onResourcesChanged:r,store:i=Ja})=>{let a=e?Ne(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)(()=>fw(e,t,i.getState().getDraft).document),[d,f]=(0,Z.useState)(()=>fw(e,t,i.getState().getDraft).mentions),[p,m]=(0,Z.useState)(`compose`),[h,g]=(0,Z.useState)(0),_=(0,Z.useRef)(l),v=(0,Z.useRef)(d),y=(0,Z.useRef)(t),b=(0,Z.useRef)(r),x=(0,Z.useRef)(e),C=(0,Z.useRef)(e?lw(e):null),w=(0,Z.useRef)(a),T=(0,Z.useRef)(a),E=(0,Z.useRef)(0),O=(0,Z.useRef)(o?.revision??0),j=(0,Z.useRef)(void 0),M=(0,Z.useRef)(void 0),N=(0,Z.useRef)(rw());_.current=l,v.current=d,y.current=t,b.current=r,x.current=e,w.current=a;let P=(0,Z.useCallback)((e,t)=>{_.current=e,v.current=t,u(e),f(t)},[]),F=(0,Z.useCallback)((e,t)=>{let n=te(e,t);b.current?.(n)},[]);(0,Z.useEffect)(()=>{i.getState().setDraftPersistenceEnabled(n)},[n,i]),(0,Z.useLayoutEffect)(()=>{E.current+=1;let e=E.current;T.current=a;let t=fw(x.current,y.current,i.getState().getDraft),n=t.key;if(C.current=t.key,j.current=void 0,M.current=void 0,N.current=rw(),m(`compose`),O.current=t.revision,P(t.document,t.mentions),g(e=>e+1),n?.owner.kind===`draft`){let r=t.revision;i.getState().claimLegacyNewDraft(n).then(t=>{let o=i.getState().getDraft(n);!t||!dw(C.current,a)||T.current!==a||w.current!==a||E.current!==e||O.current!==r||o?.revision!==t.revision||(O.current=t.revision,P(z(sw(t),y.current),t.mentions))})}},[a,P,i]),(0,Z.useEffect)(()=>{if(!a||T.current!==a||M.current)return;let e=pw(_.current,o,j.current,{keyID:a,epoch:E.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&&(j.current=void 0,P(z(sw(o),y.current),o.mentions),m(`compose`),g(e=>e+1))}},[a,P,o]);let I=(0,Z.useCallback)((e,t)=>{let n=C.current;if(!dw(n,w.current)||M.current)return;let r=_.current,a=i.getState().setDraftComposerState(n,{document:e,mentions:hw(t)});if(!a)return;let o=sw(a);return j.current={keyID:Ne(n),revision:a.revision,fingerprint:uw(o)},O.current=a.revision,P(o,a.mentions),F(r,o),a},[i,P,F]),L=(0,Z.useCallback)((e,t,n,r,i,a)=>{N.current=iw(N.current,{before:nw(e,t,n),after:nw(r,i,a)})},[]),R=(0,Z.useCallback)(()=>M.current?(M.current=void 0,m(`compose`),!0):!1,[]),V=(0,Z.useCallback)(e=>(R(),I({text:e,references:[]},[])),[I,R]),H=(0,Z.useCallback)((e,t=[])=>{R();let n=ke(e.text,e.references);return n?I(z(n,y.current),t):void 0},[I,R]),ee=(0,Z.useCallback)((e,t,n=t,r)=>{let i=R(),a=cw(_.current),o=i?[]:v.current,s=gw(a,o,e,t,n),c=r?r(s.mentions,s.document):s.mentions;return I(s.document,c),s.removedReferences.length>0&&L(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}},[I,R,L]),U=(0,Z.useCallback)((e,t)=>{let n=_.current,r=Math.max(0,Math.min(e.start,n.text.length)),i=Math.max(r,Math.min(e.end,n.text.length)),a=R(),o=D(n,`${n.text.slice(0,r)}${e.text}${n.text.slice(i)}`,r+e.text.length),s=mw(a?[]:v.current,o.document,o.edit);return I(o.document,t?t(s,o.document):s),{start:o.selectionStart,end:o.selectionEnd}},[I,R]),W=(0,Z.useCallback)((e,t)=>{let n=_.current;return U({start:0,end:n.text.length,text:e},t)},[U]),ne=(0,Z.useCallback)((e,t,n,r)=>{let i=R(),a=S(_.current,e,t,n,r);return I(a.document,mw(i?[]:v.current,a.document,a.edit)),{start:a.caret,end:a.caret,caret:a.caret,document:a.document}},[I,R]),G=(0,Z.useCallback)(e=>{let t=cw(_.current),n=A(t,e);if(!n)return null;let r=R()?[]:v.current,i=mw(r,n.document,n.edit),a=B(n.document.text,n.caret),o=D(n.document,a.text,a.caret),s=mw(i,o.document,o.edit);return I(o.document,s),L(t,r,{start:e.selectionStart,end:e.selectionEnd},o.document,s,{start:o.selectionStart,end:o.selectionEnd}),{start:o.selectionStart,end:o.selectionEnd}},[I,R,L]),K=(0,Z.useCallback)(e=>{if(M.current)return null;let t=e===`undo`?aw(N.current,_.current):ow(N.current,_.current);return!t||!I(t.snapshot.document,t.snapshot.mentions)?null:(N.current=t.history,t.snapshot.selection)},[I]),re=(0,Z.useCallback)(e=>I(_.current,e),[I]),ie=(0,Z.useCallback)(e=>{let t=M.current?{document:{text:e.text,references:[]},mentions:[]}:_w(_.current,v.current,e);`preview`in t&&(M.current=t.preview),m(`history-preview`),P(t.document,t.mentions),g(e=>e+1)},[P]),ae=(0,Z.useCallback)(()=>{let e=M.current;if(!e)return;M.current=void 0,m(`compose`);let t=vw(e);P(t.document,t.mentions),g(e=>e+1)},[P]),oe=(0,Z.useCallback)(()=>{let e=C.current;if(!dw(e,w.current))return null;let t=i.getState().getDraft(e);return{key:lw(e),keyID:Ne(e),revision:t?.revision??0,document:cw(_.current),mentions:v.current.map(e=>({...e,range:{...e.range}})),epoch:E.current,runtime:i.getState().captureDraftRuntime()}},[i]),se=(0,Z.useCallback)(e=>{let t=bw(e,i.getState().getDraft(e.key)),n=sw(i.getState().getDraft(e.key)),r=k(n.text,n.references).document,a=i.getState().setDraftComposerState(e.key,{...t,mentions:hw(t.mentions)});if(a){let e=sw(a);F(r,e)}return a},[F,i]),ce=(0,Z.useCallback)(()=>_.current,[]);return(0,Z.useMemo)(()=>({document:l,mentions:d,confirmedFileMentions:d.filter(e=>e.kind===`file`||e.kind===`directory`),inputMode:p,hydration:s,persistence:c,textPresetEpoch:h,getDocument:ce,replacePlainDocument:V,replaceMaterializedDocument:H,applyBrowserEdit:ee,applyProgrammaticEdit:U,replaceProgrammaticText:W,insertReference:ne,deleteReference:G,restoreReferenceHistory:K,commitMentions:re,enterHistoryPreview:ie,exitHistoryPreview:ae,captureSubmission:oe,recoverSubmission:se}),[ee,U,oe,re,G,l,ie,ae,ce,s,p,ne,d,c,se,H,V,W,K,h])};function Sw(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 Cw=`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`,ww=vl(()=>kt(()=>import(`./ToolOutputDialog-Bt7JChFG.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]))),Tw=[],Ew=[],Dw=[],Ow=[],kw=/^@[^\s]+$/,Aw=({inputMode:e,message:t,showCommandAutocomplete:n,showSkillAutocomplete:r})=>e!==`shell`&&(n||r||/(^|\s)\/[A-Za-z0-9_-]*/.test(t)),jw=/^(https?:\/\/|mailto:)\S+$/i,Mw=560,Nw=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),Pw=(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)},Fw=e=>e.includes(`@`)?`paste`:`manual`,Iw=(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}},Lw=(e,t)=>Pa(e,t).some(e=>e.role===`user`),Rw=(e,t)=>{let n=e.filter(e=>e.type===`text`&&!ir(e)).map(e=>{let t=e;return typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:``}).join(`
6526
+ `);if(d.trim()&&(t.push({start:s,end:s+d.length,style:`codeFence`,className:`${xS} text-[var(--syntax-foreground)]`,priority:SS}),!(d.length>OS)))try{let e=o.parser.parse(d);Lt(e,ES,(e,n,r)=>{let i=DS(r);i&&t.push({start:s+e,end:s+n,style:`codeFence`,className:i,priority:CS})})}catch{}}return t}var jS=[`CodeFiles`,`codefiles`,`application/vnd.code.tree`,`application/vnd.code.tree.explorer`,`text/uri-list`,`text/plain`],MS=e=>e.startsWith(`/`)||e.startsWith(`//`)||e.startsWith(`\\\\`)||/^[A-Za-z]:[\\/]/.test(e),NS=e=>{if(!MS(e)||/\s/.test(e))return!1;if(e.startsWith(`//`)||e.startsWith(`\\\\`)){let t=e.replace(/^[\\/]+/,``);return/[\\/]/.test(t)}if(/^[A-Za-z]:[\\/]/.test(e)){let t=e.slice(3);return t.includes(`\\`)||t.includes(`/`)||t.includes(`.`)}return e.replace(/^\/+/,``).includes(`/`)},PS=(e,{fromPlainText:t=!1}={})=>{let n=e.trim().replace(/^['"]+|['"]+$/g,``);return!n||n===`/>`||/[\r\n]/.test(n)?null:n.toLowerCase().startsWith(`file://`)||(t?NS(n):MS(n))?n:null},FS=(e,t,n=0)=>{if(!(n>6||e==null)){if(typeof e==`string`){t.add(e);return}if(Array.isArray(e)){for(let r of e)FS(r,t,n+1);return}if(typeof e==`object`)for(let r of Object.values(e))FS(r,t,n+1)}},IS=(e,{allowMultipleLines:t=!0,allowStructuredPayload:n=!0,fromPlainText:r=!1}={})=>{let i=new Set,a=e=>{let n=PS(e,{fromPlainText:r});if(n){i.add(n);return}if(t)for(let t of e.split(/\r?\n/)){let e=PS(t,{fromPlainText:r});e&&i.add(e)}};if(a(e),n)try{let t=JSON.parse(e),n=new Set;FS(t,n);for(let e of n)a(e)}catch{}return Array.from(i)},LS=e=>{if(!e||typeof e.getData!=`function`)return[];let t=new Set;for(let n of jS){let r=``;try{r=e.getData(n)}catch{continue}let i=n===`text/plain`?{allowMultipleLines:!1,allowStructuredPayload:!1,fromPlainText:!0}:n===`text/uri-list`?{allowStructuredPayload:!1}:void 0;for(let e of IS(r,i))t.add(e)}return Array.from(t)},RS=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(`file://`))return t;try{let e=new URL(t),n=decodeURIComponent(e.pathname||``);return e.hostname&&e.hostname!==`localhost`&&(n=`//${e.hostname}${n}`),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1)),n||t}catch{let e=t.replace(/^file:\/\//i,``);try{return decodeURIComponent(e)}catch{return e}}},zS=e=>MS(e);function BS(e,t){let n=(0,Q.c)(5),r=Dr(e,t),i=g(VS),a;n[0]===r?a=n[1]:(a=Zi(r),n[0]=r,n[1]=a);let o;return n[2]!==i||n[3]!==a?(o={goal:a,enabled:i},n[2]=i,n[3]=a,n[4]=o):o=n[4],o}function VS(e){return e.sessionGoalEnabled}function HS(e,t){let n=(0,Q.c)(4),[r,i]=Z.useState(null),a=t?.objectiveFile?`${e}:${t.id}:${t.updatedAt}`:``,o,s;return n[0]!==a||n[1]!==e?(o=()=>{if(!a){i(null);return}let t=!0;return Ir(e).then(e=>{t&&i(e)}),()=>{t=!1}},s=[a,e],n[0]=a,n[1]=e,n[2]=o,n[3]=s):(o=n[2],s=n[3]),Z.useEffect(o,s),t?t.objectiveFile?r:t.objective:null}var US={active:`var(--status-info)`,paused:`var(--surface-muted-foreground)`,blocked:`var(--status-warning)`,budgetLimited:`var(--status-warning)`,complete:`var(--status-success)`},WS={active:`chat.goal.status.active`,paused:`chat.goal.status.paused`,blocked:`chat.goal.status.blocked`,budgetLimited:`chat.goal.status.budgetLimited`,complete:`chat.goal.status.complete`},GS=Z.memo(({sessionId:e,directory:t,className:n})=>{let{t:r}=Zt(),i=g(e=>e.isMobile),{goal:a,enabled:o}=BS(e??``,t),s=HS(e??``,a),c=sa(e??``,t),l=fi(e,t),u=Z.useRef(null),[d,f]=Z.useState(!1),[p,m]=Z.useState(()=>Date.now());Z.useEffect(()=>{if(!a||a.status===`complete`||a.status===`blocked`||a.status===`budgetLimited`)return;let e=window.setInterval(()=>m(Date.now()),1e3);return()=>window.clearInterval(e)},[a?.id,a?.status]),Z.useEffect(()=>{if(!e||!a||a.status!==`active`)return;let n=l[0]?.id;if(!n)return;let r=`${e}:${a.id}:${n}`;u.current!==r&&(u.current=r,Dn(e,t))},[e,t,a,l]);let h=q(async n=>{if(!(!e||d)){f(!0);try{await bn(e,t,n)}catch(e){console.warn(`[session-goal] status change failed:`,e),fa.error(r(`chat.goal.toast.actionFailed`))}finally{f(!1)}}});if(!e||!o||!a)return null;let _=Math.max(0,(a.status===`complete`||a.status===`blocked`||a.status===`budgetLimited`?a.updatedAt:p)-(a.createdAt||p)),v=ta(_),y=a.tokenBudget?`${ln(a.tokensUsed)}/${ln(a.tokenBudget)}`:a.tokensUsed>0?ln(a.tokensUsed):null,b=a.status===`active`?{icon:`pause`,labelKey:`chat.goal.action.pause`,next:`paused`}:a.status===`paused`||a.status===`blocked`||a.status===`budgetLimited`?{icon:`play`,labelKey:`chat.goal.action.resume`,next:`active`}:null,x=i?`text-[11px] leading-none text-muted-foreground`:`typography-meta text-muted-foreground`,S=i?`text-xs leading-5 text-foreground`:`typography-ui-label leading-5 text-foreground`,C=i?`size-3`:`size-3.5`;return(0,$.jsxs)(`div`,{className:Y(`flex w-full min-w-0 items-center`,i?`gap-1 py-0.5`:`gap-1.5 py-0.5 md:gap-2`,n),"aria-label":r(`chat.goal.row.aria`),title:s??void 0,children:[(0,$.jsx)(X,{name:`target`,className:Y(C,`flex-shrink-0`),style:{color:US[a.status]},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`min-w-0 flex-1 truncate`,S),children:a.note||s||``}),a.status===`active`&&(!c||c.type===`idle`)?(0,$.jsxs)(`span`,{className:Y(`flex flex-shrink-0 items-center gap-1`,x),children:[(0,$.jsx)(X,{name:`loader-4`,className:Y(C,`animate-spin`),"aria-hidden":`true`}),r(`chat.goal.status.evaluating`)]}):(0,$.jsx)(`span`,{className:Y(`flex-shrink-0`,x),children:r(WS[a.status])}),(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums`,x,`text-muted-foreground/70`),children:v}),y?(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums`,x,`text-muted-foreground/70`),children:y}):null,b?(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void h(b.next),disabled:d,className:Y(`inline-flex flex-shrink-0 cursor-pointer items-center bg-transparent text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50`,i?`h-7 gap-1.5 px-0 text-[11px]`:`h-7 gap-1 px-0.5`),"aria-label":r(b.labelKey),children:[(0,$.jsx)(X,{name:b.icon,className:C,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`font-medium`,i?`leading-none`:`typography-ui-label`),children:r(b.labelKey)})]}):null]})});GS.displayName=`SessionGoalRow`;var KS=Z.memo(({sessionId:e,directory:t,draftOpen:n=!1})=>{let{t:r}=Zt(),{goal:i,enabled:a}=BS(e??``,t),o=En(e=>e.armed),s=En(e=>e.setArmed),[c,l]=Z.useState(!1);if(x()||!a||!e&&!n||!o&&!i)return null;let u=i?.status===`complete`?`text-[var(--status-success)]`:i?.status===`blocked`||i?.status===`budgetLimited`?`text-[var(--status-error)]`:o||i?.status===`active`||i?.status===`paused`?`text-[var(--status-info)]`:``,d=async()=>{if(o){s(!1);return}if(!(!e||c)){l(!0);try{await Ga(e,t)}catch(e){console.warn(`[session-goal] clear failed:`,e),fa.error(r(`chat.goal.toast.actionFailed`))}finally{l(!1)}}};return(0,$.jsxs)(`span`,{className:Y(`inline-flex h-7 items-center gap-1 rounded-full bg-[var(--surface-muted)] py-1 pl-2 pr-1 typography-ui-label`,u),children:[(0,$.jsx)(X,{name:`target`,className:`h-4 w-4`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:r(`chat.goal.chip.label`)}),(0,$.jsx)(`button`,{type:`button`,className:`flex h-5 w-5 items-center justify-center rounded-full text-current hover:bg-[var(--interactive-hover)] disabled:opacity-50`,onClick:()=>void d(),disabled:c,"aria-label":r(o?`chat.goal.button.disarmAria`:`chat.goal.action.clear`),title:r(o?`chat.goal.button.disarmAria`:`chat.goal.action.clear`),children:(0,$.jsx)(X,{name:`close`,className:`h-3 w-3`,"aria-hidden":`true`})})]})});KS.displayName=`SessionGoalButton`;var qS=Z.memo(e=>{let t=(0,Q.c)(11),{length:n}=e,{t:r}=Zt();if(!En(JS)||n===0)return null;let i=n>5e3?`text-[var(--status-error)]`:`text-muted-foreground/70`,a;t[0]===i?a=t[1]:(a=Y(`flex-shrink-0 self-center typography-micro tabular-nums`,i),t[0]=i,t[1]=a);let o;t[2]===r?o=t[3]:(o=r(`chat.goal.counter.aria`),t[2]=r,t[3]=o);let s;t[4]===r?s=t[5]:(s=r(`chat.goal.counter.aria`),t[4]=r,t[5]=s);let c;return t[6]!==n||t[7]!==a||t[8]!==o||t[9]!==s?(c=(0,$.jsxs)(`span`,{className:a,"aria-label":o,title:s,children:[n,`/`,mr]}),t[6]=n,t[7]=a,t[8]=o,t[9]=s,t[10]=c):c=t[10],c});qS.displayName=`SessionGoalObjectiveCounter`;function JS(e){return e.armed}var YS=new Set([`new`,`fork`,`compact`,`undo`,`redo`,`timeline`,`model`,`summary`,`workspace-review`,`handoff-review`,`goal`,`craft-goal`,`catch-up`,`debug`,`weigh`,`explore`]),XS=new Set([`new`,`compact`,`fork`,`undo`,`redo`]),ZS=/^\/\u2003?([^\s]+)/i,QS=/^\/\u2003?goal\b/i,$S=(e,t)=>{if(t!==`normal`)return null;let n=e.trimStart().match(ZS)?.[1]?.toLowerCase();return n&&YS.has(n)?n:null},eC=(e,t)=>$S(e,t)===`goal`?e.trimStart().replace(QS,``).trim():null,tC=(e,t)=>$S(e,t)!==null,nC=(e,t)=>{let n=$S(e,t);return n!==null&&XS.has(n)},rC=({currentSessionId:e,messageRef:t,replacePlainDocument:n})=>{let r=e;return t.current=``,n(``),r},iC=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()}},aC=e=>!e.queuedOnly&&!e.resourcePolicy&&e.rootAttachmentCount>0,oC=e=>e.surfaceKind===`primary`&&!!e.currentSessionId&&!e.queuedOnly&&!e.resourcePolicy&&e.inputMode!==`shell`&&!e.localCommand,sC=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},cC=e=>({state:`bound`,transportIdentity:e.transportIdentity,directory:e.directory,sessionID:e.sessionID,deliveryTarget:{kind:`primary`},runtimeGeneration:e.runtimeGeneration}),lC=(e,t)=>{let n=F.getState();return n.bindLegacyQueue(N(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},uC=async e=>{let t=dr.getState().takeEstablishingPending(e.draftID);if(t.length===0)return{drained:0,failed:0};let n=cC(e),r=0,i=0;for(let a of t)try{if(e.admitServer&&(await e.admitServer(a)).status===`committed`){r+=1;continue}lC(n,a)?r+=1:i+=1}catch{try{lC(n,a)?r+=1:i+=1}catch{i+=1}}return{drained:r,failed:i}},dC=(e,t)=>Promise.resolve().then(()=>e()).catch(()=>{t()}),fC=e=>e===`allow`||e===`ask`||e===`deny`,pC=e=>{if(fC(e))return[{permission:`*`,pattern:`*`,action:e}];if(Array.isArray(e))return e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.permission==`string`&&typeof t.pattern==`string`&&fC(t.action)?[{permission:t.permission,pattern:t.pattern,action:t.action}]:[]});if(!e||typeof e!=`object`)return[];let t=[];for(let[n,r]of Object.entries(e))if(n!==`__originalKeys`){if(fC(r)){t.push({permission:n,pattern:`*`,action:r});continue}if(!(!r||typeof r!=`object`||Array.isArray(r)))for(let[e,i]of Object.entries(r))fC(i)&&t.push({permission:n,pattern:e,action:i})}return t},mC=e=>{let t=pC(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.permission===`*`&&n.pattern===`*`)return n.action===`ask`;if(n.action===`ask`)return!0}return!0},hC=(e,t)=>{let n=t?.trim();if(!n)return e.length===0||e.some(e=>mC(e.permission));let r=e.find(e=>e?.name===n);return!r||mC(r.permission)},gC=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)},_C=null,vC=new Set,yC=()=>{for(let e of vC)e()},bC=e=>e===`chat`||e===`assistant`,xC=()=>_C,SC=e=>{_C!==e&&(_C=e,yC())},CC=e=>{_C&&(e&&_C.surfaceID!==e||(_C=null,yC()))},wC=(e,t)=>{if(e.transportIdentity!==t.transportIdentity||e.runtimeGeneration!==t.runtimeGeneration)throw Error(`chat-input-delivery-runtime-stale`)},TC=e=>{let t={...e.options?.delivery===`steer`?{delivery:`steer`}:{},...e.options?.commitStagedMessageEdit===void 0?{}:{commitStagedMessageEdit:e.options.commitStagedMessageEdit},...e.options?.messageID?{messageID:e.options.messageID}:{},...e.options?.ticket?{ticket:e.options.ticket}:{}},n=e.options?.sessionId??e.sessionID??void 0;if(!n)return t;let r=e.options?.directoryHint===void 0?e.directory||null:e.options.directoryHint;return{...t,sessionId:n,directoryHint:r}},EC=(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}),DC=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=EC(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=EC(e,`send`,i),o=Jv(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=EC(e,`create`);return await e.selection.flush(),e.backend.create(t)},compact:async t=>{let n=EC(e,`compact`,t);return await e.selection.flush(),e.backend.compact(n)},abort:async()=>{let t=EC(e,`abort`);return await e.selection.flush(),e.backend.abort(t)},queueScope:Jv(e),canAbort:n,canQueue:t===`busy`||t===`retry`,allowsCommand:t=>Vv(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=EC(e,`abort`);await e.selection.flush(),await e.backend.abort(t);return}if(t===`new`){let t=EC(e,`create`);await e.selection.flush(),await e.backend.create(t);return}t!==`submit`&&await e.shortcuts?.cycle(n)},resources:e.resources??null}},OC=(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)))},kC=(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},AC=(e,t)=>e.agents.some(e=>e.name===t),jC=(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},MC=e=>{let{catalog:t,providerID:n,modelID:r,historyVariant:i,memoryVariant:a}=e;if(i)return jC(t,n,r,i)?i:void 0;if(a&&jC(t,n,r,a))return a},NC=e=>{let{sessionId:t,choice:n,catalog:r,memory:i,fallbackAgentName:a,source:o}=e;if(!n.providerID||!n.modelID||!kC(r,n.providerID,n.modelID))return null;let s=n.agent&&AC(r,n.agent)?n.agent:i?.getSessionAgentSelection?.(t)&&AC(r,i.getSessionAgentSelection(t))?i.getSessionAgentSelection(t):a&&AC(r,a)?a:void 0,c=s?i?.getAgentModelVariantForSession?.(t,s,n.providerID,n.modelID):void 0,l=MC({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}},PC=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=NC({sessionId:t,choice:r,catalog:i,memory:a,fallbackAgentName:s,source:`execution`});if(e)return e}if(c&&n){let e=NC({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&&AC(i,e)?e:s&&AC(i,s)?s:void 0;if(n){let e=a.getAgentModelForSession?.(t,n);if(e&&kC(i,e.providerId,e.modelId)){let r=a.getAgentModelVariantForSession?.(t,n,e.providerId,e.modelId),o=r&&jC(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&&kC(i,r.providerId,r.modelId)){let e=n?a.getAgentModelVariantForSession?.(t,n,r.providerId,r.modelId):void 0,o=e&&jC(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&&kC(i,l.providerID,l.id)){let e=a?.getSessionAgentSelection?.(t)??null,n=(o?.agent&&AC(i,o.agent)?o.agent:void 0)??(e&&AC(i,e)?e:s&&AC(i,s)?s:void 0),r=l.variant,c=r&&jC(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},FC=(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))},IC=(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}},LC=e=>e.editRevision<=0?!1:e.pinnedHistoryMessageId==null||e.latestHistoryMessageId==null||e.latestHistoryMessageId===e.pinnedHistoryMessageId,RC=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}:{}}},zC=e=>typeof e==`string`&&e.trim().length>0?e:void 0,BC=e=>zC(e.agent)??zC(e.mode),VC=e=>zC(e.model?.variant)??zC(e.variant),HC=e=>{let t=zC(e.model?.providerID),n=zC(e.model?.modelID);return!t||!n?null:{providerID:t,modelID:n}},UC=e=>{let t=zC(e.providerID)??zC(e.model?.providerID),n=zC(e.modelID)??zC(e.model?.modelID);return!t||!n?null:{providerID:t,modelID:n}},WC=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role!==`user`)continue;let r=HC(n);return{id:typeof n.id==`string`?n.id:void 0,agent:BC(n),providerID:r?.providerID,modelID:r?.modelID,variant:VC(n)}}return null},GC=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`){if(HC(n))return null;continue}if(n.role!==`assistant`)continue;let r=UC(n);if(r)return{id:typeof n.id==`string`?n.id:void 0,agent:BC(n),providerID:r.providerID,modelID:r.modelID,variant:VC(n)}}return null},KC=500,qC=e=>Array.from(e).length,JC=e=>{let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(36)},YC=e=>qC(e)>=KC,XC=e=>{let t=k(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},ZC=(e,t)=>{let n=t??e;return typeof n!=`string`||!YC(n)?!1:Pe(typeof e==`string`?{text:``,references:[]}:e,n)},QC=(e,t,n,r,i=1)=>{let a=qC(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}-${JC(e)}`,token:i,text:e,characterCount:a,index:n}}throw Error(`Unable to create a unique pasted text reference`)},$C=e=>({text:e.text,references:e.references.map(e=>({...e}))}),ew=e=>e.map(e=>({...e,range:{...e.range}})),tw=(e,t)=>e.text===t.text&&JSON.stringify(e.references)===JSON.stringify(t.references),nw=(e,t,n)=>({document:$C(e),mentions:ew(t),selection:{...n}}),rw=()=>({undo:[],redo:[]}),iw=(e,t)=>({undo:[...e.undo,t].slice(-100),redo:[]}),aw=(e,t)=>{let n=e.undo.at(-1);return!n||!tw(n.after.document,t)?null:{history:{undo:e.undo.slice(0,-1),redo:[...e.redo,n]},snapshot:nw(n.before.document,n.before.mentions,n.before.selection)}},ow=(e,t)=>{let n=e.redo.at(-1);return!n||!tw(n.before.document,t)?null:{history:{undo:[...e.undo,n],redo:e.redo.slice(0,-1)},snapshot:nw(n.after.document,n.after.mentions,n.after.selection)}},sw=e=>({text:e?.text??``,references:e?.composerReferences??[]}),cw=e=>({text:e.text,references:e.references.map(e=>({...e}))}),lw=e=>({transportIdentity:e.transportIdentity,owner:{...e.owner}}),uw=e=>JSON.stringify([e.text,e.references]),dw=(e,t)=>e!==null&&t!==null&&Ne(e)===t,fw=(e,t,n)=>{let r=e?lw(e):null,i=r?n(r):void 0;return{document:z(sw(i),t),mentions:i?.mentions??[],revision:i?.revision??0,key:r,keyID:r?Ne(r):null}},pw=(e,t,n,r)=>{if(!t||Ne(t.key)!==r.keyID||t.revision<r.appliedRevision)return`ignore`;let i=uw(sw(t));return n?.keyID===r.keyID&&n.revision===t.revision&&n.fingerprint===i?`local-echo`:t.revision===r.appliedRevision?`ignore`:i===uw(e)?`same-document-metadata`:`external-document`},mw=(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}]:[]})},hw=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),gw=(e,t,n,r,i=r)=>{let a=D(e,n,r,i);return{document:a.document,mentions:mw(t,a.document,a.edit),requiresTextCorrection:a.requiresTextCorrection,selectionStart:a.selectionStart,selectionEnd:a.selectionEnd,removedReferences:a.removedReferences}},_w=(e,t,n)=>({preview:{real:cw(e),realMentions:[...t]},document:{text:n.text,references:[]},mentions:[]}),vw=e=>({document:e.real,mentions:e.realMentions}),yw=(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)})},bw=(e,t)=>{let n=sw(t),r=R(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:yw(e.mentions,t?.mentions??[],r,i)}},xw=({draftKey:e,sessionTitles:t,persistenceEnabled:n,onResourcesChanged:r,store:i=Ja})=>{let a=e?Ne(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)(()=>fw(e,t,i.getState().getDraft).document),[d,f]=(0,Z.useState)(()=>fw(e,t,i.getState().getDraft).mentions),[p,m]=(0,Z.useState)(`compose`),[h,g]=(0,Z.useState)(0),_=(0,Z.useRef)(l),v=(0,Z.useRef)(d),y=(0,Z.useRef)(t),b=(0,Z.useRef)(r),x=(0,Z.useRef)(e),C=(0,Z.useRef)(e?lw(e):null),w=(0,Z.useRef)(a),T=(0,Z.useRef)(a),E=(0,Z.useRef)(0),O=(0,Z.useRef)(o?.revision??0),j=(0,Z.useRef)(void 0),M=(0,Z.useRef)(void 0),N=(0,Z.useRef)(rw());_.current=l,v.current=d,y.current=t,b.current=r,x.current=e,w.current=a;let P=(0,Z.useCallback)((e,t)=>{_.current=e,v.current=t,u(e),f(t)},[]),F=(0,Z.useCallback)((e,t)=>{let n=te(e,t);b.current?.(n)},[]);(0,Z.useEffect)(()=>{i.getState().setDraftPersistenceEnabled(n)},[n,i]),(0,Z.useLayoutEffect)(()=>{E.current+=1;let e=E.current;T.current=a;let t=fw(x.current,y.current,i.getState().getDraft),n=t.key;if(C.current=t.key,j.current=void 0,M.current=void 0,N.current=rw(),m(`compose`),O.current=t.revision,P(t.document,t.mentions),g(e=>e+1),n?.owner.kind===`draft`){let r=t.revision;i.getState().claimLegacyNewDraft(n).then(t=>{let o=i.getState().getDraft(n);!t||!dw(C.current,a)||T.current!==a||w.current!==a||E.current!==e||O.current!==r||o?.revision!==t.revision||(O.current=t.revision,P(z(sw(t),y.current),t.mentions))})}},[a,P,i]),(0,Z.useEffect)(()=>{if(!a||T.current!==a||M.current)return;let e=pw(_.current,o,j.current,{keyID:a,epoch:E.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&&(j.current=void 0,P(z(sw(o),y.current),o.mentions),m(`compose`),g(e=>e+1))}},[a,P,o]);let I=(0,Z.useCallback)((e,t)=>{let n=C.current;if(!dw(n,w.current)||M.current)return;let r=_.current,a=i.getState().setDraftComposerState(n,{document:e,mentions:hw(t)});if(!a)return;let o=sw(a);return j.current={keyID:Ne(n),revision:a.revision,fingerprint:uw(o)},O.current=a.revision,P(o,a.mentions),F(r,o),a},[i,P,F]),L=(0,Z.useCallback)((e,t,n,r,i,a)=>{N.current=iw(N.current,{before:nw(e,t,n),after:nw(r,i,a)})},[]),R=(0,Z.useCallback)(()=>M.current?(M.current=void 0,m(`compose`),!0):!1,[]),V=(0,Z.useCallback)(e=>(R(),I({text:e,references:[]},[])),[I,R]),H=(0,Z.useCallback)((e,t=[])=>{R();let n=ke(e.text,e.references);return n?I(z(n,y.current),t):void 0},[I,R]),ee=(0,Z.useCallback)((e,t,n=t,r)=>{let i=R(),a=cw(_.current),o=i?[]:v.current,s=gw(a,o,e,t,n),c=r?r(s.mentions,s.document):s.mentions;return I(s.document,c),s.removedReferences.length>0&&L(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}},[I,R,L]),U=(0,Z.useCallback)((e,t)=>{let n=_.current,r=Math.max(0,Math.min(e.start,n.text.length)),i=Math.max(r,Math.min(e.end,n.text.length)),a=R(),o=D(n,`${n.text.slice(0,r)}${e.text}${n.text.slice(i)}`,r+e.text.length),s=mw(a?[]:v.current,o.document,o.edit);return I(o.document,t?t(s,o.document):s),{start:o.selectionStart,end:o.selectionEnd}},[I,R]),W=(0,Z.useCallback)((e,t)=>{let n=_.current;return U({start:0,end:n.text.length,text:e},t)},[U]),ne=(0,Z.useCallback)((e,t,n,r)=>{let i=R(),a=S(_.current,e,t,n,r);return I(a.document,mw(i?[]:v.current,a.document,a.edit)),{start:a.caret,end:a.caret,caret:a.caret,document:a.document}},[I,R]),G=(0,Z.useCallback)(e=>{let t=cw(_.current),n=A(t,e);if(!n)return null;let r=R()?[]:v.current,i=mw(r,n.document,n.edit),a=B(n.document.text,n.caret),o=D(n.document,a.text,a.caret),s=mw(i,o.document,o.edit);return I(o.document,s),L(t,r,{start:e.selectionStart,end:e.selectionEnd},o.document,s,{start:o.selectionStart,end:o.selectionEnd}),{start:o.selectionStart,end:o.selectionEnd}},[I,R,L]),K=(0,Z.useCallback)(e=>{if(M.current)return null;let t=e===`undo`?aw(N.current,_.current):ow(N.current,_.current);return!t||!I(t.snapshot.document,t.snapshot.mentions)?null:(N.current=t.history,t.snapshot.selection)},[I]),re=(0,Z.useCallback)(e=>I(_.current,e),[I]),ie=(0,Z.useCallback)(e=>{let t=M.current?{document:{text:e.text,references:[]},mentions:[]}:_w(_.current,v.current,e);`preview`in t&&(M.current=t.preview),m(`history-preview`),P(t.document,t.mentions),g(e=>e+1)},[P]),ae=(0,Z.useCallback)(()=>{let e=M.current;if(!e)return;M.current=void 0,m(`compose`);let t=vw(e);P(t.document,t.mentions),g(e=>e+1)},[P]),oe=(0,Z.useCallback)(()=>{let e=C.current;if(!dw(e,w.current))return null;let t=i.getState().getDraft(e);return{key:lw(e),keyID:Ne(e),revision:t?.revision??0,document:cw(_.current),mentions:v.current.map(e=>({...e,range:{...e.range}})),epoch:E.current,runtime:i.getState().captureDraftRuntime()}},[i]),se=(0,Z.useCallback)(e=>{let t=bw(e,i.getState().getDraft(e.key)),n=sw(i.getState().getDraft(e.key)),r=k(n.text,n.references).document,a=i.getState().setDraftComposerState(e.key,{...t,mentions:hw(t.mentions)});if(a){let e=sw(a);F(r,e)}return a},[F,i]),ce=(0,Z.useCallback)(()=>_.current,[]);return(0,Z.useMemo)(()=>({document:l,mentions:d,confirmedFileMentions:d.filter(e=>e.kind===`file`||e.kind===`directory`),inputMode:p,hydration:s,persistence:c,textPresetEpoch:h,getDocument:ce,replacePlainDocument:V,replaceMaterializedDocument:H,applyBrowserEdit:ee,applyProgrammaticEdit:U,replaceProgrammaticText:W,insertReference:ne,deleteReference:G,restoreReferenceHistory:K,commitMentions:re,enterHistoryPreview:ie,exitHistoryPreview:ae,captureSubmission:oe,recoverSubmission:se}),[ee,U,oe,re,G,l,ie,ae,ce,s,p,ne,d,c,se,H,V,W,K,h])};function Sw(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 Cw=`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`,ww=vl(()=>kt(()=>import(`./ToolOutputDialog-C7cKReps.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]))),Tw=[],Ew=[],Dw=[],Ow=[],kw=/^@[^\s]+$/,Aw=({inputMode:e,message:t,showCommandAutocomplete:n,showSkillAutocomplete:r})=>e!==`shell`&&(n||r||/(^|\s)\/[A-Za-z0-9_-]*/.test(t)),jw=/^(https?:\/\/|mailto:)\S+$/i,Mw=560,Nw=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),Pw=(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)},Fw=e=>e.includes(`@`)?`paste`:`manual`,Iw=(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}},Lw=(e,t)=>Pa(e,t).some(e=>e.role===`user`),Rw=(e,t)=>{let n=e.filter(e=>e.type===`text`&&!ir(e)).map(e=>{let t=e;return typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:``}).join(`
6527
6527
  `).replace(/\s+/g,` `).trim();if(n)return n;let r=e.find(e=>e.type===`file`);return r?.filename?`[${r.filename}]`:t},zw=`file://`,Bw=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(`/`)},Vw=e=>{let t=e.replace(/\\/g,`/`).trim();return t.toLowerCase().startsWith(zw)?t:`file://${Bw(t)}`},Hw=e=>{if(!e)return[];let t=[...LS(e).map(RS),...Array.from(e.files||[]).map(e=>V(e)).filter(e=>!!e)];return Array.from(new Set(t.filter(zS)))},Uw=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},Ww=e=>_o(e.path),Gw=(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)]})},Kw=Z.memo(my),qw=Z.memo(am),Jw=Z.memo(Tb),Yw=Z.memo(Ob),Xw=Z.memo(Wy),Zw=Z.memo(({sessionId:e,directory:t})=>{let{t:n}=Zt(),r=g(e=>e.isMobile),i=J(e=>e.revertToMessage),a=J(e=>e.forkFromMessage),o=J(e=>e.handleSlashRedo),[s,c]=Z.useState(null),[l,u]=Z.useState(null),[d,f]=Z.useState(!0),p=Z.useRef(rS),m=Wi(),h=t||m,_=Zr(h),v=ja(e??``,h,_),y=zn(e=>e.session,h),b=Z.useMemo(()=>{let t=v.messageOrder.map(e=>v.messagesByID[e]).filter(e=>!!e),n=oS({session:y,messages:t,partsByMessageID:v.partsByMessageID},e,p.current);return p.current=n,n},[e,y,v]),x=b.revertMessageID,S=Z.useMemo(()=>b.records.map(e=>e.message),[b]),C=n(`chat.revertPopover.noTextContent`),w=Z.useMemo(()=>x?b.records.map(e=>({id:e.message.id,text:Rw(e.parts,C)})):[],[C,x,b]),T=w[0]?.id;Z.useEffect(()=>{f(!0)},[x,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:Y(`w-full px-1`,r?`pb-1 text-xs`:`pb-2`),children:(0,$.jsxs)(`div`,{className:Y(`border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm dark:shadow-none overflow-hidden`,r?`rounded-lg`:`rounded-xl`),children:[(0,$.jsxs)(`button`,{type:`button`,className:Y(`flex w-full items-center text-left hover:bg-[var(--interactive-hover)] transition-colors`,r?`gap-1.5 px-2 py-1`:`gap-2 px-3 py-2`),onClick:()=>f(e=>!e),"aria-expanded":!d,children:[(0,$.jsxs)(`span`,{className:`typography-ui-label font-medium text-foreground flex-shrink-0`,children:[n(`chat.revertPopover.title`),` messages `,w.length]}),(0,$.jsx)(X,{name:`arrow-down-s`,className:Y(`ml-auto text-muted-foreground transition-transform`,r?`size-3.5`:`size-4`,!d&&`rotate-180`),"aria-hidden":`true`})]}),!d&&(0,$.jsx)(`div`,{className:Y(`flex flex-col overflow-y-auto`,r?`max-h-[8rem] gap-1 px-2 pb-1.5`:`max-h-[10.5rem] gap-1.5 px-3 pb-3`),children:w.map(e=>(0,$.jsxs)(`div`,{className:Y(`flex min-w-0 items-center`,r?`gap-1.5`:`gap-2 py-1`),children:[(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate typography-ui-label text-foreground`,children:e.text}),(0,$.jsxs)(yo,{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)(yo,{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))})]})})});Zw.displayName=`RevertedMessageDock`;var Qw=Z.memo(function(e){let t=(0,Q.c)(41),{t:n}=Zt(),{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?cT:void 0,v=f?lT:void 0,y;t[5]===a?y=t[6]:(y=Y(a,`text-current`),t[5]=a,t[6]=y);let b;t[7]===y?b=t[8]:(b=(0,$.jsx)(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)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:S}),(0,$.jsx)(Zo,{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:Y(a,`text-current`)})}):null,t[33]=i,t[34]=a,t[35]=l,t[36]=n,t[37]=E):E=t[37];let D;return t[38]!==T||t[39]!==E?(D=(0,$.jsxs)(`div`,{className:`flex items-center gap-x-1.5`,children:[T,E]}),t[38]=T,t[39]=E,t[40]=D):D=t[40],D},(e,t)=>e.isVSCode===t.isVSCode&&e.footerIconButtonClass===t.footerIconButtonClass&&e.iconSizeClass===t.iconSizeClass&&e.onOpenSettings===t.onOpenSettings&&e.onMenuOpenChange===t.onMenuOpenChange&&e.onOpenMobileSheet===t.onOpenMobileSheet&&e.onOpenAndroidPickSheet===t.onOpenAndroidPickSheet&&e.withTooltip===t.withTooltip),$w=Z.memo(function(e){let t=(0,Q.c)(29),{t:n}=Zt(),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=()=>gC({permissionScopeSessionId:e.sessionId,newSessionDraftOpen:e.draftOpen,draftPermissionAutoAcceptEnabled:e.draftEnabled,permissionAutoAcceptEnabled:e.enabled,setDraftPermissionAutoAcceptEnabled:e.onSetDraftEnabled,setSessionAutoAccept:e.onSetSessionEnabled,onOpenSessionFirst:e.onOpenSessionFirst,onToggleFailed:e.onToggleFailed}),t[3]=e.draftEnabled,t[4]=e.draftOpen,t[5]=e.enabled,t[6]=e.onOpenSessionFirst,t[7]=e.onSetDraftEnabled,t[8]=e.onSetSessionEnabled,t[9]=e.onToggleFailed,t[10]=e.sessionId,t[11]=l):l=t[11];let u=e.enabled?`shield-check`:`shield`,d;t[12]===e.iconSizeClass?d=t[13]:(d=Y(e.iconSizeClass,`text-current`),t[12]=e.iconSizeClass,t[13]=d);let f;t[14]!==u||t[15]!==d?(f=(0,$.jsx)(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)(Xo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,disabled:o,"aria-pressed":s,"aria-label":a,className:c,onClick:l,onMouseDown:uT,onPointerDownCapture:dT,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)(Zo,{side:`top`,sideOffset:8,children:a}),t[24]=a,t[25]=m);let h;return t[26]!==m||t[27]!==p?(h=(0,$.jsxs)(Qo,{children:[p,m]}),t[26]=m,t[27]=p,t[28]=h):h=t[28],h}),eT=Z.memo(function(e){let t=(0,Q.c)(67),{isMobile:n,compact:r,footerIconButtonClass:i,stopFooterIconButtonClass:a,compactCircleButtonClass:o,sendIconSizeClass:s,stopIconSizeClass:c,canSend:l,canAbort:u,hasContent:d,currentSessionId:f,newSessionDraftOpen:p,draftSubmitting:m,submissionBlocked:h,sendPhase:g,queueFrozen:_,queueFallbackAvailable:v,onPrimaryAction:y,onAbort:b}=e,x=r!==void 0&&r,{t:S}=Zt(),C,w,T,E,D;if(t[0]!==u||t[1]!==l||t[2]!==x||t[3]!==o||t[4]!==f||t[5]!==m||t[6]!==i||t[7]!==d||t[8]!==n||t[9]!==p||t[10]!==y||t[11]!==v||t[12]!==_||t[13]!==s||t[14]!==g||t[15]!==a||t[16]!==c||t[17]!==h||t[18]!==S){D=Symbol.for(`react.early_return_sentinel`);bb0:{let e=Bb({canSend:l,hasSessionTarget:!!(f||p),draftSubmitting:!!m,submissionBlocked:h,sendPhase:g,queueFrozen:_,queueFallbackAvailable:v}),r;t[24]===n?r=t[25]:(r=n?{onMouseDown:fT,onPointerDownCapture:pT}:{},t[24]=n,t[25]=r);let b=r,O=g.inFlight,k=O&&g.flightKind===`queue`,A=O&&g.flightKind!==`queue`,j;t[26]!==u||t[27]!==v||t[28]!==_||t[29]!==k||t[30]!==A||t[31]!==S?(j=S(k?`chat.chatInput.actions.queuingMessageAria`:A?`chat.chatInput.actions.sendingMessageAria`:_&&v&&u?`chat.chatInput.actions.sendMessageAria`:u?`chat.chatInput.actions.queueMessageAria`:`chat.chatInput.actions.sendMessageAria`),t[26]=u,t[27]=v,t[28]=_,t[29]=k,t[30]=A,t[31]=S,t[32]=j):j=t[32];let M=j;C=x?o??a??i:a??i,w=c;let N=!u&&(!e.sendDisabled||O),P;t[33]!==n||t[34]!==y?(P=e=>{n&&(e.preventDefault(),y())},t[33]=n,t[34]=y,t[35]=P):P=t[35];let F;t[36]!==u||t[37]!==O||t[38]!==k||t[39]!==A||t[40]!==S?(F=S(A||!u&&O?k?`chat.chatInput.actions.queuingMessageAria`:`chat.chatInput.actions.sendingMessageAria`:`chat.chatInput.actions.sendMessageAria`),t[36]=u,t[37]=O,t[38]=k,t[39]=A,t[40]=S,t[41]=F):F=t[41];let I;t[42]!==u||t[43]!==w||t[44]!==O||t[45]!==s||t[46]!==N?(I=N?(0,$.jsx)(Mu,{className:w,spinning:!!(O&&!u)}):(0,$.jsx)(X,{name:`send-plane-2`,className:s}),t[42]=u,t[43]=w,t[44]=O,t[45]=s,t[46]=N,t[47]=I):I=t[47];let L=(0,$.jsx)(`button`,{type:n?`button`:`submit`,"data-composer-send":`true`,"data-composer-circle":N?`true`:void 0,disabled:e.sendDisabled,"aria-busy":O||void 0,...b,onClick:P,className:Y(N?C:i,N?void 0:e.sendDisabled?e.disabledClass:`text-primary hover:text-primary`),"aria-label":F,children:I});if(!u){D=L;break bb0}let R=!x&&(d||k),z=!e.sendDisabled&&!k,B=x&&`h-full`;t[48]===B?T=t[49]:(T=Y(`relative z-30 overflow-visible`,B),t[48]=B,t[49]=T),E=R?(0,$.jsx)(`button`,{type:`button`,"data-composer-send":`true`,"data-composer-circle":z||k?`true`:void 0,disabled:e.sendDisabled||k,"aria-busy":k||void 0,...b,onClick:e=>{e.preventDefault(),!k&&y()},className:Y(z||k?C:i,`absolute z-30 bottom-full left-1/2 -translate-x-1/2 mb-1`,z||k?void 0:e.disabledClass),"aria-label":M,children:z||k?(0,$.jsx)(Mu,{className:w,spinning:k}):(0,$.jsx)(X,{name:`send-plane-2`,className:s})}):null}t[0]=u,t[1]=l,t[2]=x,t[3]=o,t[4]=f,t[5]=m,t[6]=i,t[7]=d,t[8]=n,t[9]=p,t[10]=y,t[11]=v,t[12]=_,t[13]=s,t[14]=g,t[15]=a,t[16]=c,t[17]=h,t[18]=S,t[19]=C,t[20]=w,t[21]=T,t[22]=E,t[23]=D}else C=t[19],w=t[20],T=t[21],E=t[22],D=t[23];if(D!==Symbol.for(`react.early_return_sentinel`))return D;let O;t[50]===C?O=t[51]:(O=Y(C,`relative z-30`),t[50]=C,t[51]=O);let k;t[52]===S?k=t[53]:(k=S(`chat.chatInput.actions.stopGeneratingAria`),t[52]=S,t[53]=k);let A;t[54]===w?A=t[55]:(A=Y(w),t[54]=w,t[55]=A);let j;t[56]===A?j=t[57]:(j=(0,$.jsx)(Nu,{className:A}),t[56]=A,t[57]=j);let M;t[58]!==b||t[59]!==O||t[60]!==k||t[61]!==j?(M=(0,$.jsx)(`button`,{type:`button`,"data-composer-stop":`true`,onClick:b,className:O,"aria-label":k,children:j}),t[58]=b,t[59]=O,t[60]=k,t[61]=j,t[62]=M):M=t[62];let N;return t[63]!==T||t[64]!==E||t[65]!==M?(N=(0,$.jsxs)(`div`,{className:T,children:[E,M]}),t[63]=T,t[64]=E,t[65]=M,t[66]=N):N=t[66],N},(e,t)=>e.isMobile===t.isMobile&&e.compact===t.compact&&e.footerIconButtonClass===t.footerIconButtonClass&&e.stopFooterIconButtonClass===t.stopFooterIconButtonClass&&e.compactCircleButtonClass===t.compactCircleButtonClass&&e.sendIconSizeClass===t.sendIconSizeClass&&e.stopIconSizeClass===t.stopIconSizeClass&&e.canSend===t.canSend&&e.canAbort===t.canAbort&&e.hasContent===t.hasContent&&e.currentSessionId===t.currentSessionId&&e.newSessionDraftOpen===t.newSessionDraftOpen&&e.draftSubmitting===t.draftSubmitting&&e.submissionBlocked===t.submissionBlocked&&e.sendPhase===t.sendPhase&&e.queueFrozen===t.queueFrozen&&e.queueFallbackAvailable===t.queueFallbackAvailable&&e.onPrimaryAction===t.onPrimaryAction&&e.onAbort===t.onAbort),tT=(e,t)=>`${e}${e?e.endsWith(`
6528
6528
 
6529
6529
  `)?``:e.endsWith(`
@@ -6534,7 +6534,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,C as n,E as r,J
6534
6534
 
6535
6535
  `)?t:t.endsWith(`
6536
6536
  `)?`${t}\n`:`${t}\n\n`}`,nT=(e,t)=>{let n=t.trim();return n?e?`${e}${/[\s\n]$/.test(e)?``:` `}${n} `:`${n} `:e},rT=(e,t,n,r)=>t?T({transportIdentity:e},t):n?w({transportIdentity:e},n):r,iT=[],aT=({onOpenSettings:e,scrollToBottom:n,showScrollToBottom:i=!1,onScrollToBottom:a,submissionBlocked:o=!1,surface:c})=>{let{t:l}=Zt(),u=Kc(),[d,f]=Z.useState({open:!1,title:``,content:``}),[p,m]=Z.useState(`normal`),[h,_]=Z.useState(!1),[y,b]=Z.useState(!1),[S,C]=Z.useState(!1),[w,T]=Z.useState(``),[E,D]=Z.useState(!1),[A,M]=Z.useState(``),[I,L]=Z.useState(!1),[R,z]=Z.useState(``),[B,V]=Z.useState(!1),[H,U]=Z.useState(``),[te,W]=Z.useState([]),[ne,G]=Z.useState(0),[K,re]=Z.useState(null),[ae,oe]=Z.useState(null),ce=Z.useRef(null),le=Z.useRef(null),[ue,de]=Z.useState(!1),pe=Z.useRef(null);Z.useEffect(()=>()=>{pe.current!==null&&window.clearTimeout(pe.current),ce.current!==null&&window.clearTimeout(ce.current),le.current!==null&&window.clearTimeout(le.current)},[]);let[me,he]=Z.useState(!1),[_e,Se]=Z.useState(!1),[Ce,we]=Z.useState(null),Te=Z.useId(),[Oe,ke]=Z.useState(``),[Ae,je]=Z.useState(``),[Me,Pe]=Z.useState(!1),[Fe,Ie]=Z.useState(!1),Le=Z.useRef(0),Re=Z.useCallback(()=>{Le.current=Date.now()+500},[]),ze=Z.useRef(0),Be=Z.useRef(!1),[Ve,He]=Z.useState(-1),Ue=Z.useRef(()=>{}),We=Z.useRef((...e)=>Promise.resolve().then(()=>J.getState().sendMessage(...e))).current,Ge=J(e=>e.currentSessionId),Ke=ui(e=>e.currentProviderId),qe=ui(e=>e.currentModelId),Je=ui(e=>e.currentAgentName),Ye=ui(e=>e.currentVariant),Xe=ui(e=>e.providers),Ze=ui(e=>e.agents),Qe=ui(e=>e.getVisibleAgents),$e=Z.useMemo(()=>jv(Qe()),[Qe,Ze]),et=ui(e=>e.providerConfigLoadingByDirectory[e.activeDirectoryKey]===!0),tt=ui(e=>e.agentConfigLoadingByDirectory[e.activeDirectoryKey]===!0),nt=Z.useMemo(()=>{let e=Xe.find(e=>e.id===Ke)?.models?.find(e=>e.id===qe);return Rv(e)},[qe,Ke,Xe]),rt=lt(e=>e.currentDirectory),it=Ul()??rt,{ensureSessionRenderable:at}=jm(),ot=J(Z.useCallback(e=>Ge?e.getDirectoryForSession(Ge):null,[Ge])),st=Yi(Ge??``,ot??void 0),dt=Z.useMemo(()=>WC(st),[st]),ht=Z.useMemo(()=>GC(st),[st]),gt=ji(Ge??``,ot??void 0).renderable,vt=Dr(Ge,ot??void 0),yt=vt?.agent,bt=vt?.model?.id,St=vt?.model?.providerID,Ct=vt?.model?.variant,Tt=ui(e=>e.activeDirectoryKey),Dt=Z.useRef(0),Ot=Z.useRef(null),kt=Z.useRef(null),At=J(e=>e.newSessionDraft),jt=!!At?.open,Mt=J(e=>e.newSessionDraft.draftSubmitting??!1),Nt=J(e=>e.newSessionDraft.draftEstablishing??!1),Pt=Mt||Nt,Ft=J(e=>e.openNewSessionDraft),It=J(e=>e.setDraftPermissionAutoAcceptEnabled),Lt=Qa(e=>e.autoAccept),Rt=Qa(e=>e.saving),zt=Qa(e=>e.setSessionAutoAccept),Bt=J(e=>e.setNewSessionDraftTarget),Vt=J(e=>e.availableWorktreesByProject),Ht=J(e=>e.abortPromptSessionId),Ut=J(e=>e.abortPromptExpiresAt),Wt=J(e=>e.clearAbortPrompt),Gt=Ja(e=>e.consumePendingInputText),Kt=Ja(e=>e.pendingPresetSubmit),qt=Ja(e=>e.pendingInputText),Jt=Ja(e=>e.pendingInputMode),Xt=Ja(e=>e.consumePendingSyntheticParts),Qt=Ja(e=>e.activeAttachmentDraft),$t=Lm(Z.useCallback(e=>{let t=Ge??(jt?`draft`:``);return t?e.drafts[t]??Ew:Ew},[jt,Ge])),en=zi(Ge??``),tn=Z.useSyncExternalStore(t,r,r),nn=Qt?.transportIdentity??null,on=Qt?.owner.kind??null,sn=Qt?.owner.ownerID??null,cn=Z.useMemo(()=>rT(tn,Ge,At.draftID,nn&&on&&sn?{transportIdentity:nn,owner:{kind:on,ownerID:sn}}:null),[sn,on,nn,tn,Ge,At.draftID]),ln=cn?Ne(cn):null,pn=Ja(Z.useCallback(e=>ln?e.draftAttachmentViews[ln]:void 0,[ln])),mn=Ja(Z.useCallback(e=>ln?e.drafts[ln]:void 0,[ln])),hn=Z.useMemo(()=>{if(!mn||!pn)return iT;let e=mn.attachments.flatMap(e=>{let t=pn[e.attachmentRefID];return t?[t]:[]});return e.length===0?iT:e},[pn,mn]);Z.useEffect(()=>{cn&&Ja.getState().hydrateDraftAttachments(cn)},[cn]);let _n=Uv(),vn=g(e=>e.activeMainTab===`chat`),yn=sa(Ge??``,it??void 0),bn=Wv({kind:`primary`,surfaceID:`primary`,active:vn,sessionID:Ge,directory:it??null,activity:{phase:yn?.type===`busy`?`busy`:yn?.type===`retry`?`retry`:`idle`,canAbort:yn?.type===`busy`||yn?.type===`retry`},draftKey:cn,transportIdentity:tn,runtimeGeneration:v(),selection:{value:{providerID:Ke,modelID:qe,agent:Je,variant:Ye},catalog:{providers:Xe,agents:$e,variants:nt,variantsReady:!et,ready:!et&&!tt,loading:et||tt},flush:async()=>{let e=J.getState().currentSessionId;if(!e)return;let t=v(),n=r(),i=Dt.current,a=e,o=J.getState().getDirectoryForSession(a)??null,s=ei(o);if(ui.getState().activeDirectoryKey!==s&&await ui.getState().activateDirectory(o),v()!==t||r()!==n||J.getState().currentSessionId!==a||ui.getState().activeDirectoryKey!==s||Dt.current!==i)return;await at(a,{directory:o??void 0});let c=J.getState().getDirectoryForSession(a)??null,l=ei(c);if(v()!==t||r()!==n||J.getState().currentSessionId!==a||c!==o||l!==s||ui.getState().activeDirectoryKey!==s||Dt.current!==i)return;let u=ui.getState(),d={providers:u.providers,agents:u.getVisibleAgents()};if(d.providers.length===0||d.agents.length===0)return;let f=Pa(a,c??void 0),p=WC(f),m=GC(f);if(LC({editRevision:i,pinnedHistoryMessageId:Ot.current,latestHistoryMessageId:p?.id??null}))return;let h=Nn.getState(),g=wr().get(a),_=PC({sessionId:a,latestUserChoice:p,latestExecution:m,catalog:d,memory:h,sessionEntity:g?.model?{agent:g.agent,model:{id:g.model.id,providerID:g.model.providerID,variant:g.model.variant}}:g?.agent?{agent:g.agent}:null,fallbackAgentName:u.currentAgentName});if(!_)return;let y=[a,_.source,_.messageId??``,_.agent??``,_.providerID,_.modelID,_.variant??``,s].join(`|`);kt.current!==y&&(FC(_,{currentAgentName:u.currentAgentName,setAgent:u.setAgent,setProvider:u.setProvider,setModel:u.setModel,setCurrentVariant:u.setCurrentVariant},{sessionId:a,memory:h}),kt.current=y)},change:async e=>{Dt.current+=1;let t=J.getState().currentSessionId;if(t){let e=J.getState().getDirectoryForSession(t)??void 0,n=WC(Pa(t,e));Ot.current=n?.id??null}else Ot.current=null;let n=ui.getState();OC(e,{currentAgentName:n.currentAgentName,setAgent:n.setAgent,setProvider:n.setProvider,setModel:n.setModel,setCurrentVariant:n.setCurrentVariant,saveAgentModelSelection:n.saveAgentModelSelection},{sessionId:t,memory:Nn.getState()})}},resources:{attachments:hn,addAttachment:async e=>{cn&&await un(cn,()=>Ja.getState()).addLocal(e)},removeAttachment:async e=>cn?un(cn,()=>Ja.getState()).removeByAttachmentID(e):!1,clearAttachments:async()=>cn?un(cn,()=>Ja.getState()).clearRootAttachments():!1,restoreAttachments:async e=>cn?un(cn,()=>Ja.getState()).restoreRootAttachments(e):!1,pendingInput:qt===null?null:{text:qt,mode:Jt},consumePendingInput:Gt,pendingPreset:Kt,consumePendingPreset:()=>Ja.getState().consumePendingPresetSubmit(),consumeSyntheticParts:Xt,restoreSyntheticParts:e=>Ja.setState(t=>({pendingSyntheticParts:[...e,...t.pendingSyntheticParts??[]]})),inlineDrafts:$t,removeInlineDraft:e=>{let t=Ge??(jt?`draft`:``);t&&Lm.getState().removeDraft(t,e)},restoreInlineDrafts:e=>{let t=Ge??(jt?`draft`:``);!t||e.length===0||Lm.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:en,captureRuntime:()=>Ja.getState().captureDraftRuntime(),getDraft:e=>Ja.getState().getDraft(e),abortPrompt:{sessionID:Ht,clear:Wt}},backend:{send:e=>{wC(e,{transportIdentity:r(),runtimeGeneration:v()});let t=TC(e);return We(e.text??``,e.providerID,e.modelID,e.agent,e.attachments??[],e.agentMention,e.parts,e.variant,e.inputMode,t)},sendQueued:e=>Or(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()=>Ft(),compact:async e=>mt.summarizeSession(e.sessionID??``,e.providerID??``,e.modelID??``,e.directory),abort:e=>(e.sessionID&&br(e.sessionID),dn(e.sessionID??``))},shortcuts:{cycle:e=>Ue.current(e),new:()=>Ft(),abort:()=>(Ge&&br(Ge),dn(Ge??``)),submit:()=>{}},deliveryTarget:{kind:`primary`}}),Sn=Gv(bn,c??_n);Kv(Sn),Z.useLayoutEffect(()=>{if(!Sn.active){CC(Sn.surfaceID);return}return SC(Sn),()=>CC(Sn.surfaceID)},[Sn]);let Cn=DC(Sn),wn=Sn.resources??(Sn.kind===`primary`?bn.resources:void 0);if(!wn)throw Error(`chat-input-surface-resources-incomplete`);let Tn=[...wn.attachments],Dn=Sn.sessionID,On=qv(Sn,Pt),kn=Sn.kind===`secondary`?Sn.commands.hasNewDraft:jt,An=kn,jn=Sn.directory??it,Mn=Sn.draftKey??cn,Pn=Z.useMemo(()=>{if(Sn.kind===`secondary`)return Yv(Sn,!1,!1);let e=Dn?Lw(Dn,ot??void 0):!1;return Yv(Sn,e,kn)},[Sn,Dn,ot,kn]),Fn=(e,t,n,r,i,a,o,s,c,l)=>Cn?Cn.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`)),In=Z.useCallback(()=>Cn?Cn.abort():Promise.reject(Error(`chat-input-surface-incomplete`)),[Cn]),Ln=Gi(e=>e.projects),zn=Gi(e=>e.activeProjectId),Bn=Gi(e=>e.setActiveProjectIdOnly),[Vn,Un]=Z.useState(!1),[Wn,Kn]=Z.useState(!1),qn=Z.useMemo(()=>Dn?Nr({autoAccept:Lt,sessions:[],sessionById:wr(),sessionID:Dn}):At.permissionAutoAcceptEnabled===!0,[Dn,At.permissionAutoAcceptEnabled,Lt]),Yn=ui(e=>e.agents),Zn=Sn.kind===`secondary`?Sn.selection.value.agent:Je,Qn=Sn.kind===`secondary`?jv(Sn.selection.catalog?.agents):Yn,er=x()||hC(Qn,Zn),tr=Z.useCallback(()=>{fa.error(l(`chat.chatInput.toast.togglePermissionAutoAcceptFailed`))},[l]),nr=Sn.selection.value,ir=Sn.selection.change,ar=Sn.selection.catalog,or=Z.useMemo(()=>({selection:{providerID:nr.providerID??``,modelID:nr.modelID??``,agent:nr.agent??null,variant:nr.variant},onChange:async e=>{if(!ir)throw Error(`chat-input-surface-selection-readonly`);await ir({...e,agent:e.agent??void 0,variant:e.variant})},disabled:!Sn.active,catalog:ar}),[ar,ir,nr.agent,nr.modelID,nr.providerID,nr.variant,Sn.active]);Z.useEffect(()=>{Dt.current=0,Ot.current=null,kt.current=null},[Ge]),Z.useEffect(()=>{if(Sn.kind!==`primary`||!Ge||et||tt||Xe.length===0||$e.length===0)return;let e=ei(ot);if(Tt!==e)return;let t=Nn.getState(),n={providers:Xe,agents:$e};if(LC({editRevision:Dt.current,pinnedHistoryMessageId:Ot.current,latestHistoryMessageId:dt?.id??null}))return;let r=PC({sessionId:Ge,latestUserChoice:dt,latestExecution:ht,catalog:n,memory:t,sessionEntity:St&&bt?{agent:yt,model:{id:bt,providerID:St,variant:Ct}}:yt?{agent:yt}:null,fallbackAgentName:Je,transcriptReady:gt});if(!r)return;let i=[Ge,r.source,r.messageId??``,r.agent??``,r.providerID,r.modelID,r.variant??``,Tt].join(`|`);if(kt.current===i)return;if((r.agent===void 0||r.agent===Je)&&r.providerID===Ke&&r.modelID===qe&&r.variant===Ye){kt.current=i;return}if(ui.getState().activeDirectoryKey!==e)return;let a=ui.getState();FC(r,{currentAgentName:a.currentAgentName,setAgent:a.setAgent,setProvider:a.setProvider,setModel:a.setModel,setCurrentVariant:a.setCurrentVariant},{sessionId:Ge,memory:t}),kt.current=i},[Sn.kind,Ge,dt,ht,gt,Xe,$e,et,tt,Tt,ot,Je,Ke,qe,Ye,yt,bt,St,Ct]);let sr=ui(e=>e.getVisibleAgents),cr=Sn.kind===`primary`?sr():Dw,fr=ui(e=>Sn.kind===`primary`?e.providers:Ow),pr=Sn.kind===`secondary`?jv(Sn.selection.catalog?.agents):cr,mr=Sn.kind===`secondary`?Sn.selection.catalog?.providers??Ow:fr,hr=Sn.kind===`secondary`&&(!Sn.selection.catalog?.ready||!!Sn.selection.catalog.error),gr=!Sn.active||!Sn.selection.change||hr,_r=g(e=>e.isMobile),xr=g(e=>e.setImagePreviewOpen),Tr=Z.useCallback(e=>{e.image&&(f(e),xr(!0))},[xr]),Er=Z.useCallback(e=>{f(t=>({...t,open:e})),xr(e)},[xr]),jr=fm(e=>e.pending),Mr=g(e=>e.inputBarOffset),Pr=g(e=>e.persistChatDraft),Fr=g(e=>e.inputSpellcheckEnabled),Ir=g(e=>e.isExpandedInput),Lr=g(e=>e.setExpandedInput),Rr=g(e=>e.setTimelineDialogOpen),zr=xw({draftKey:Mn,sessionTitles:new Map(Array.from(wr(),([e,t])=>[e,t.title||e])),persistenceEnabled:Pr}),Br=zr.document,Hr=Br.text,{replacePlainDocument:Wr,replaceProgrammaticText:Gr,applyBrowserEdit:qr,insertReference:Yr,deleteReference:Xr,enterHistoryPreview:Zr,exitHistoryPreview:ti,captureSubmission:ri,recoverSubmission:ii,confirmedFileMentions:ai,mentions:oi}=zr,si=Z.useCallback((e,t)=>Gr(e,t),[Gr]),ci=Z.useMemo(()=>new Set(ai.map(e=>e.value)),[ai]),di=Z.useRef(null),fi=Z.useRef(!1),pi=Z.useRef(0),mi=Z.useRef(null),_i=Z.useRef(Hr.length),vi=Z.useRef(null),yi=Z.useRef(0),bi=Z.useRef(!1),xi=Z.useRef(null),Si=Z.useRef(!1),Ci=Z.useRef(null),wi=Z.useRef([]),Ti=Z.useRef(!1),Ei=Z.useRef(null),Di=Z.useRef(!1),Oi=Z.useRef(null),ki=Z.useRef(null),Ai=Z.useRef(null),Ni=Z.useRef(Hr),Pi=Z.useRef(new Set),Fi=zr.getDocument,Ii=Z.useCallback((e,t,n=[])=>si(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}`))]}),[si]),Li=By(zy()),{git:Ri,vscode:Bi}=ic(),Hi=g(e=>e.shortcutOverrides.cycle_agent),Ui=g(e=>e.shortcutOverrides),Wi=Z.useMemo(()=>is(`cycle_agent`,Hi?{cycle_agent:Hi}:void 0),[Hi]),Ji=Z.useMemo(()=>is(`clear_all_messages`,Ui),[Ui]),{currentTheme:Zi}=Vs(),Qi=gc(),ta=Vc(jn),na=Tc(e=>jn?e.directories.get(jn)?.status??null:null),ra=Tc(e=>e.ensureStatus),aa=Tc(e=>e.fetchStatus),[oa,ca]=Z.useState(!1),la=Z.useRef(null),[ua,ma]=Z.useState(!1);Z.useEffect(()=>{!jn||!Ri||ra(jn,Ri)},[jn,Ri,ra]),Z.useEffect(()=>{if(!(!jn||!Ri))return ni.onGitRefreshHint(e=>{Uw(e.directory)===Uw(jn)&&aa(jn,Ri)})},[jn,Ri,aa]);let ha=Z.useCallback(async e=>{if(!Dn)return;let t=J.getState().getDirectoryForSession(Dn)||jn||``;if(!t){fa.error(l(`diffView.reviewDialog.toast.noSessionDirectory`));return}Kn(!0);try{await vr({originalSessionID:Dn,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}),Un(!1)}catch(e){console.error(`[review-flow] failed to start review flow`,e),fa.error(e instanceof Error?e.message:l(`diffView.reviewDialog.toast.startFailed`))}finally{Kn(!1)}},[Dn,jn,l]),ga=Ir&&!_r,_a=Ir&&_r,ya=ga||_a,ba=`1.5rem`,xa=l(Dn||kn?p===`shell`?`chat.chatInput.placeholder.shell`:_r||ua?`chat.chatInput.placeholder.chatCompact`:`chat.chatInput.placeholder.chat`:`chat.chatInput.placeholder.selectSession`),Sa=l(`chat.chatInput.placeholder.compactTap`);Z.useEffect(()=>{let e=vi.current;if(!e)return;let t=e=>{let t=e>0&&e<Mw;ma(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 Ta=Tn,Da=Z.useMemo(()=>new Set(pr.map(e=>e.name.toLowerCase())),[pr]),Oa=Z.useRef(Da);Oa.current=Da;let ka=Aw({inputMode:p,message:Hr,showCommandAutocomplete:E,showSkillAutocomplete:I}),ja=da({directory:jn,enabled:ka}),Ma=Z.useMemo(()=>ja.data??[],[ja.data]),Na=an({directory:jn,enabled:ka}),Fa=Z.useMemo(()=>Na.data??[],[Na.data]),La=Z.useMemo(()=>new Map(Fa.map(e=>[e.name.toLowerCase(),e.name])),[Fa]),Ra=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`]);!_r&&!x()&&e.add(`handoff-review`);for(let t of Ma)e.add(t.name.toLowerCase());for(let t of Fa)e.add(t.name.toLowerCase());return e},[Ma,Fa,_r]),za=Z.useMemo(()=>{if(!Hr||!Hr.includes(`/`)||p===`shell`||Ra.size===0)return[];let e=[],t=RegExp(`(^|\\s)/(${ye})?([A-Za-z0-9][A-Za-z0-9_-]*)`,`g`),n;for(;(n=t.exec(Hr))!==null;){let t=n[2]??``,r=n[3];if(!Ra.has(r.toLowerCase()))continue;let i=n.index+n[1].length,a=1+t.length+r.length,o=La.get(r.toLowerCase());e.push(o?{start:i,end:i+a,style:`mentionCommand`,priority:102,skillName:o,visual:De({trigger:`/`,icon:`book-open`,label:o},Hr.slice(i,i+a))}:{start:i,end:i+a,style:`mentionCommand`,visual:De({trigger:`/`,icon:`command`,label:r},Hr.slice(i,i+a))})}return e},[La,p,Ra,Hr]),Ba=Uo(e=>e.snippets),Ha=Z.useMemo(()=>{let e=new Set;for(let t of Ba){e.add(t.name.toLowerCase());for(let n of t.aliases??[])e.add(n.toLowerCase())}return e},[Ba]),Ua=Z.useMemo(()=>{if(!Hr||!Hr.includes(`#`)||p===`shell`||Ha.size===0)return[];let e=[],t=/(^|\s)#([A-Za-z0-9][A-Za-z0-9_-]*)/g,n;for(;(n=t.exec(Hr))!==null;){let t=n[2];if(!Ha.has(t.toLowerCase()))continue;let r=n.index+n[1].length;e.push({start:r,end:r+1+t.length,style:`mentionSnippet`})}return e},[p,Ha,Hr]),Wa=Z.useMemo(()=>!Hr||!Hr.includes(`@`)||p===`shell`?[]:Aa(Hr,{confirmedValues:ci,agentNames:Da}),[ci,p,Da,Hr]),Ga=Z.useMemo(()=>{if(!Hr||!Hr.includes(`[`)||p===`shell`||Ta.length===0)return[];let e=Ta.filter(xt),t=new Map(e.map(e=>[e.filename.trim().toLowerCase(),e.mimeType.startsWith(`image/`)?`image`:`attachment`]));return ft(Hr,e.map(e=>e.filename)).flatMap(e=>{let n=be(Hr.slice(e.start+1,e.end-1)).trim(),r=t.get(n.toLowerCase());return[{...e,style:`mentionFile`,priority:101,visual:De({trigger:`[`,icon:r===`image`?`file-image`:`attachment-2`,label:n,suffix:`]`},Hr.slice(e.start,e.end))}]})},[p,Hr,Ta]),Ka=u&&cl(_r)&&Sn.kind===`primary`,qa=Z.useMemo(()=>{if(!Hr||p===`shell`)return null;let e=[...Ka?[]:mS(Hr),...Ka?[]:AS(Hr),...yS(Wa),...za,...Ua,...Ga,...Br.references.map(e=>({start:e.start,end:e.end,priority:103,...ee(e)}))];return hS(Hr,e)},[Ga,za,Ua,Wa,Br.references,p,Hr,Ka]),Ya=Z.useCallback(e=>(e??[]).map(e=>({...e,dataUrl:e.source===`server`&&e.serverPath?Vw(e.serverPath):e.dataUrl})),[]),[Xa,Za]=Z.useState(null),$a=Z.useRef(null),[eo,to]=Z.useState(!1),[no,ro]=Z.useState(!1),[ao,oo]=Z.useState(null),[so,co]=Z.useState(null),lo=F(e=>e.followUpBehavior),uo=Z.useMemo(()=>{let e=Cn?.queueScope;return e?{state:`bound`,transportIdentity:e.transportIdentity,directory:e.directory,sessionID:e.sessionID,deliveryTarget:e.deliveryTarget,runtimeGeneration:e.runtimeGeneration}:null},[Cn]),fo=Xm({transportIdentity:uo?.transportIdentity??``,directory:uo?.directory??``,sessionID:uo?.sessionID??``}),po=Z.useMemo(()=>Dn?N(Dn):null,[Dn]),mo=F(Z.useCallback(e=>uo?j(e,uo):Tw,[uo])),ho=F(Z.useCallback(e=>po?j(e,po):Tw,[po])),go=Z.useMemo(()=>ho.length===0?mo:mo.length===0?ho:[...ho,...mo],[mo,ho]),vo=fo.mode===`server`?Tw:go,bo=F(Z.useCallback(e=>uo?fe(e,uo):Tw,[uo])),xo=F(e=>e.clearQueue),So=F(e=>e.removeFromQueue),wo=wn.inlineDrafts,To=wo.length>0,[Eo,Do,Oo]=Z.useMemo(()=>{let e=0,t=0,n=0;for(let r of wo)r.source===`preview-console`?e+=1:r.source===`preview-annotation`?t+=1:n+=1;return[e,t,n]},[wo]),ko=Z.useCallback(e=>{for(let t of wn.inlineDrafts)t.source===e&&wn.removeInlineDraft(t.id)},[wn]),jo=Z.useCallback(()=>{for(let e of wn.inlineDrafts)e.source!==`preview-console`&&e.source!==`preview-annotation`&&wn.removeInlineDraft(e.id)},[wn]),Fo=wn.history;Z.useEffect(()=>{Ni.current=Hr},[Hr]),Z.useLayoutEffect(()=>{m(`normal`),He(-1)},[Mn?.transportIdentity,Mn?.owner.kind,Mn?.owner.ownerID]),Z.useLayoutEffect(()=>{if(!kn||_r)return;let e=()=>{let e=di.current;!e||e.disabled||e.focus({preventScroll:!0})};e();let t=window.requestAnimationFrame(e);return()=>window.cancelAnimationFrame(t)},[kn,_r]);let zo=Nb(Sn.kind===`primary`?Dn:null,Sn.kind===`primary`?jn??void 0:void 0),Ho=Sn.activity?.phase??zo.phase,Wo=Ar(Z.useCallback(e=>{if(!Dn)return!1;let t=e.runsByOriginalSessionID[Dn];return t?.status===`running`&&t.runtimeKey===s()},[Dn])),Go=q(e=>{_r&&(Re(),oe(e),di.current?.blur(),ui.getState().refreshCatalogsOnPickerOpen({source:`chatInput:mobilePanel`}))}),Ko=wn.pendingInput,Xo=wn.consumePendingInput;Z.useEffect(()=>{if(Ko===null)return;let e=Xo();if(e){if(e.mode===`append`){if(!e.text.trim())return;let t=tT(Ni.current,e.text);Ni.current=t,si(t)}else if(e.mode===`append-inline`){let t=nT(Ni.current,e.text);Ni.current=t,si(t)}else Wr(e.text);setTimeout(()=>{di.current?.focus()},0)}},[Ko,Xo,Wr,si]);let Zo=Hr.trim().length>0||Ta.length>0||To,Qo=fo.mode===`server`?fo.items.length>0:vo.length>0||bo.length>0,$o=!Wg(fo.mode),es=Zo||Qo,ts=J(e=>e.stagedMessageEdit?.sessionId===Dn?e.stagedMessageEdit.messageId:null),ns=Ho===`busy`||Ho===`retry`,rs=Sn.activity?.canAbort??ns,as=Z.useCallback(()=>{let e=di.current,t=e?.value??Fi().text;t!==Fi().text&&qr(t,e?.selectionStart??t.length,e?.selectionEnd??e?.selectionStart??t.length);let n=Fi();return{message:n.text,document:n,hasContent:n.text.trim().length>0||Ta.length>0||To}},[qr,Fi,To,Ta.length]),ss=Z.useRef(async()=>{}),cs=Sn.surfaceID,ls=At?.draftID??null,ds=dr(Z.useMemo(()=>ia(cs),[cs])),fs=dr(Z.useMemo(()=>ea(ls),[ls])),ps=Z.useMemo(()=>yr(ds,fs),[ds,fs]),ms=(e=`send`)=>dr.getState().beginFlight(cs,e),hs=()=>{dr.getState().endFlight(cs)},gs=()=>dr.getState().isInFlight(cs),_s=Z.useRef(null);Z.useEffect(()=>{if(Sn.kind!==`primary`||!ts){_s.current=null;return}if(_s.current!==ts){if(_s.current=ts,Ka){nl().focus();return}Iv(di)||requestAnimationFrame(()=>Iv(di))}},[Ka,ts,Sn.kind]);let vs=dr(Z.useMemo(()=>fn(ls),[ls])),ys=q(async()=>{let e=J.getState().newSessionDraft.draftID;if(!e||!dr.getState().isEstablishing(e))return!1;let t=as();if(!t.hasContent)return!1;let n=xe(t.document,`queue-canonical`);if(!n.ok)return fa.error(l(`chat.chatInput.toast.messageSendFailed`)),!1;if(await Sn.selection.flush(),!dr.getState().isEstablishing(e))return!1;let r=IC(ui.getState());if(!r?.providerID||!r?.modelID)return fa.error(l(`chat.chatInput.toast.messageSendFailed`)),!1;let i=Ya(Ta);return dr.getState().enqueueEstablishingFollowUp({draftID:e,content:n.text,sendConfig:{providerID:r.providerID,modelID:r.modelID,...r.agent?{agent:r.agent}:{},...r.variant?{variant:r.variant}:{}},attachments:i,composerDocument:t.document})?(Wr(``),He(-1),Lr(!1),i.length>0&&wn.clearAttachments(),!0):!1}),bs=()=>{if(Dn)return!1;let e=J.getState().newSessionDraft.draftID;return dr.getState().isEstablishing(e)?(ys(),!0):!1},xs=q(async()=>{if(!Sn.active||gs())return;if(Dn){let e=J.getState().stagedMessageEdit;if(e&&e.sessionId===Dn){J.getState().beginMessageEditCommit(e.sessionId,e.messageId);try{await Sr(e.sessionId,e.messageId)}catch(e){console.warn(`[chat-input] staged-edit delete failed before queue admission`,e);return}finally{J.getState().endMessageEditCommit(e.sessionId,e.messageId)}J.getState().stagedMessageEdit===e&&J.getState().clearStagedMessageEdit(e.sessionId)}}let e=as(),t=xe(e.document);if(!t.ok){fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}let n={chunks:t.chunks??[],semantics:t.semantics??[]},i=t.text,a=i.trimStart(),s=n.chunks.every(e=>e.provenance===`authored`)&&p===`normal`&&a.startsWith(`/`)?Cc(a.slice(1).trim()).split(/\s+/)[0]?.toLowerCase():void 0;if(s&&!vc(s,e=>Vv(Sn,{name:e.name,source:`openchamber`}))||o||!e.hasContent||!Dn)return;if($o||!Jr(Sn.deliveryTarget?.kind,fo.mode)){ss.current(ns?{delivery:`steer`}:void 0);return}if(n.chunks.every(e=>e.provenance===`authored`)&&tC(i,p)){ss.current();return}if(!ms(`queue`))return;let c=Sn.transportIdentity,u=Sn.runtimeGeneration,d=wn.captureRuntime(),f=uo,m=Sn.kind===`primary`?uo?.sessionID??Dn:null,h=[...wn.inlineDrafts].sort((e,t)=>e.createdAt-t.createdAt),g=h.length>0?k(Bm(e.document.text,h),e.document.references).document:e.document,_=xe(g,`queue-canonical`);if(!_.ok){hs(),fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}let y=Ya(Ta),b=ri(),x=y,S=Xn(),C=!1,w=null,T=()=>{C&&f&&(fo.actions.unstageAdmission({requestID:S.requestID,scope:{directory:f.directory,sessionID:f.sessionID}}),C=!1),w&&f&&(F.getState().unstageAdmission(f,w),w=null)},E=async e=>{T(),b&&ii(b),x.length>0&&await wn.restoreAttachments(x),e&&wn.restoreSyntheticParts(e),h.length>0&&wn.restoreInlineDrafts(h)};try{if(!f){fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}if(fo.mode===`server`){if(!Mn){fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}$n({stage:()=>{fo.actions.stageAdmission({requestID:S.requestID,scope:{directory:f.directory,sessionID:f.sessionID},item:{queueItemID:S.queueItemID,operationID:S.operationID,messageID:S.messageID,content:_.text,createdAt:S.createdAt,attachmentCount:y.length,composerDocument:g,composerMentions:oi}}),C=!0},clearComposer:()=>{Wr(``),He(-1),Lr(!1)}})}else $n({stage:()=>{F.getState().bindLegacyQueue(N(f.sessionID),f),F.getState().stageAdmission(f,{requestID:S.requestID,queueItemID:S.queueItemID,operationID:S.operationID,messageID:S.messageID,content:_.text,createdAt:S.createdAt,attachmentCount:y.length,composerDocument:g,composerMentions:oi}),w=S.requestID},clearComposer:()=>{Wr(``),He(-1),Lr(!1)}});if(await Sn.selection.flush(),!li({transportIdentity:c,generation:u},{transportIdentity:r(),generation:v()})){await E();return}if(!li(d,wn.captureRuntime())){await E();return}if(m&&J.getState().currentSessionId!==m){await E();return}if(f.transportIdentity!==r()||f.runtimeGeneration!==v()||f.sessionID!==(m??f.sessionID)||m&&P(J.getState().getDirectoryForSession(m))!==P(f.directory)){await E();return}let t=f,n=Sn.kind===`primary`?(()=>{let e=ui.getState(),t=m?J.getState().getDirectoryForSession(m)??null:null;return IC(e,{expectedConfigKey:ei(t),activeDirectoryKey:e.activeDirectoryKey})})():Sn.selection.value.providerID&&Sn.selection.value.modelID?{...Sn.selection.value,providerID:Sn.selection.value.providerID,modelID:Sn.selection.value.modelID}:void 0;if(!Qr(n)){await E();return}if(fo.mode===`server`){if(!Mn){await E(),fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}let r=wa({draftKey:Mn,runtime:d,document:e.document,attachments:Ta,inlineDrafts:h}),i=t.deliveryTarget.kind===`assistant`?wn.consumeSyntheticParts()?.map(e=>({...e,partID:e.partID??se()}))??null:null,a,o=[],s=t.deliveryTarget.kind===`assistant`?(()=>{let e=Ia({plan:{chunks:_.chunks??[],semantics:_.semantics??[]},agents:pr,installedSkillNames:new Set($r(Ee,jn).map(e=>e.name)),directory:jn,root:Qi||jn,confirmedFilePaths:ai.map(e=>e.path),confirmedDirectoryPaths:ai.filter(e=>e.kind===`directory`).map(e=>e.path),citationAttachments:Ta});return o=e.attachments,Cr({text:h.length>0?Bm(e.text,h):e.text,attachments:[...y,...e.attachments],semanticParts:Ca(e.semantics,t.directory),syntheticParts:i})})():void 0;try{let e=[...Rn(y),...Rn(o),...(i??[]).flatMap(e=>Rn(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 E(i),fa.error(l(e instanceof RangeError?`chat.chatInput.toast.attachmentsTooLarge`:`chat.chatInput.toast.messageSendFailed`));return}let c=s&&i?rn(s,i.map(e=>({...e,partID:e.partID}))):void 0;try{let e=!1,o=await Vr({capture:r,admit:async()=>{let r=await fo.actions.admit({requestID:S.requestID,scope:{directory:t.directory,sessionID:t.sessionID},item:{queueItemID:S.queueItemID,operationID:S.operationID,messageID:S.messageID,content:_.text,composerDocument:g,composerMentions:oi,sendConfig:n,deliveryTarget:t.deliveryTarget,...s?{deliveryParts:s}:{},...c?{syntheticParts:c}:{},attachmentIssues:[],createdAt:S.createdAt},attachments:a});return r.status===`committed`&&(e=!0,C=!1),r},captureRuntime:wn.captureRuntime,getCurrentDraftKey:()=>Mn,getDocument:Fi,consumeBody:()=>Wr(``),getAttachments:()=>wn.attachments,removeAttachment:wn.removeAttachment,getInlineDrafts:()=>wn.inlineDrafts,removeInlineDraft:wn.removeInlineDraft});if(!e){await E(i),o.status===`stale`&&fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}if(o.status===`partial`){fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}o.status===`committed`&&!_r&&di.current?.focus()}catch(e){await E(i),fa.error(l(e instanceof RangeError?`chat.chatInput.toast.attachmentsTooLarge`:`chat.chatInput.toast.messageSendFailed`))}return}if(!F.getState().confirmAdmission(t,{requestID:S.requestID,sendConfig:n,attachments:y.length>0?y:void 0}).ok){await E(),fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}w=null;for(let e of h)wn.removeInlineDraft(e.id);y.length>0&&wn.clearAttachments(),_r||di.current?.focus()}catch(e){await E(),fa.error(l(e instanceof RangeError?`chat.chatInput.toast.attachmentsTooLarge`:`chat.chatInput.toast.messageSendFailed`))}finally{hs()}}),Ss=q(()=>{dC(()=>xs(),()=>{fa.error(l(`chat.chatInput.toast.messageSendFailed`))})}),Cs=q(async(e,t,n,r)=>{if($o||!Sn.draftKey)return!1;try{let i=await lr({content:e,composerDocument:n,composerMentions:r,attachments:t}),a=Ja.getState(),o=a.getDraft(Sn.draftKey);return Kg(await $i({key:Sn.draftKey,expectedRevision:o?.revision??`absent`,payload:i,runtime:a.captureDraftRuntime()}))?!0:(fa.error(l(`chat.chatInput.toast.messageSendFailed`)),!1)}catch{return fa.error(l(`chat.chatInput.toast.messageSendFailed`)),!1}}),ws=q(e=>{if(!(o||$o)){if(Cn){Cn.sendQueued(e,{options:{delivery:`steer`},manual:!0});return}fa.error(l(`chat.chatInput.toast.messageSendFailed`))}}),Ts=q(()=>{Re(),oe(`agent`),di.current?.blur(),ui.getState().refreshCatalogsOnPickerOpen({source:`chatInput:mobileAgentPanel`})}),Es=Z.useCallback(()=>{to(!0)},[]),Ds=Z.useCallback(()=>{ro(!0)},[]),Os=async e=>{if(!Sn.active||o||bs()||gs())return;let t=e?.queuedOnly??!1,i=e?.queuedMessageId,a=e?.delivery===`steer`&&ns?`steer`:void 0,s=e?.presetText==null?as():{message:e.presetText,document:{text:e.presetText,references:[]},hasContent:e.presetText.trim().length>0||Ta.length>0||To},c=e?.presetText==null?ri():null,u=Tn,d=xe(s.document,`direct-send-display`);if(!d.ok){fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}let f=d.text,m={chunks:d.chunks??[],semantics:d.semantics??[]},h=m.chunks.every(e=>e.provenance===`authored`),_=f.trimStart(),y=h?$S(_,p):null,b=h&&tC(f,p),S=h&&p===`normal`&&/^\/model(?:\s|$)/i.test(_),C=h&&p===`normal`&&_.startsWith(`/`)?Cc(_.slice(1).trim()).split(/\s+/)[0]?.toLowerCase():void 0;if(C&&!vc(C,e=>Vv(Sn,{name:e.name,source:`openchamber`}))||t&&$o)return;if(!t&&S){D(!1),M(``),_r?Go(`model`):(g.getState().setModelSelectorOpen(!0),ui.getState().refreshCatalogsOnPickerOpen({source:`chatInput:modelCommand`}));return}if(!(!t&&y&&y!==`model`)){if(!t&&Dn&&Qo&&$o)return;if(!t&&Dn&&Qo&&fo.mode===`server`){s.hasContent&&Ss();return}if(!t&&Dn&&Qo){s.hasContent&&Ss();let e=vo[0];e&&Cn&&await Cn.sendQueued(e.queueItemID,{options:ns?{delivery:`steer`}:void 0});return}}let w=b?[]:i?vo.filter(e=>e.id===i):vo;if(t&&Wo)return;if(t){if(w.length===0||!Dn)return}else if(!s.hasContent&&!Qo||!Dn&&!kn)return;if(!Dn&&On||!ms())return;let T=!Dn&&kn&&!t&&!b?J.getState().newSessionDraft.draftID??null:null,E=T?ve(`msg`):void 0;if(T&&E&&!dr.getState().beginEstablishing({draftID:T,primaryMessageID:E})){hs();return}let k=()=>{hi(),T&&dr.getState().clearEstablishing(T)},A=e=>{let t=J.getState().currentSessionId,n=(t?J.getState().getDirectoryForSession(t):null)??jn??``;if(!t||!n){dr.getState().clearEstablishing(e);return}uC({draftID:e,sessionID:t,directory:n,transportIdentity:r(),runtimeGeneration:v(),admitServer:fo.mode===`server`?async e=>fo.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?Rn(e.attachments):void 0}):void 0})};if(Dn&&!t&&!b&&Wo){hs(),Ss();return}let N=!t&&!b;N&&(Wr(``),He(-1),Lr(!1));let P=!1,I,L,R=!1;try{if(oC({surfaceKind:Sn.kind,currentSessionId:Dn,queuedOnly:t,resourcePolicy:b,inputMode:p,localCommand:y})&&Dn){let e=J.getState().getDirectoryForSession(Dn)??jn??null,t=J.getState().stagedMessageEdit;t&&t.sessionId===Dn&&(L={sessionId:t.sessionId,messageId:t.messageId},J.getState().beginMessageEditCommit(t.sessionId,t.messageId));let n=ui.getState(),r=IC(n,{expectedConfigKey:ei(e),activeDirectoryKey:n.activeDirectoryKey});if(r?.providerID&&r?.modelID){let t=Ya(Ta);I=ur({sessionId:Dn,directory:e,content:s.message,providerID:r.providerID,modelID:r.modelID,agent:r.agent,files:t.map(e=>({type:`file`,mime:e.mimeType,url:e.dataUrl,filename:e.filename}))})}}let e=Sn.kind===`primary`?(()=>{if(t){let e=w[0]?.owner;if(e?.state===`bound`||e?.state===`unbound-legacy`)return e.sessionID;if(uo?.sessionID)return uo.sessionID}return Dn})():null,r=t?w[0]?.sendConfig:void 0;if(t&&r||await Sn.selection.flush(),e!==null&&J.getState().currentSessionId!==e)return;let o=async()=>{let t=r?{...r}:Sn.kind===`primary`?(()=>{let t=ui.getState();if(!e)return RC({captured:IC(t),surfaceSelection:Sn.selection.value});let n=J.getState().getDirectoryForSession(e)??jn??null;return RC({captured:IC(t,{expectedConfigKey:ei(n),activeDirectoryKey:t.activeDirectoryKey}),surfaceSelection:Sn.selection.value})})():Sn.selection.value.providerID&&Sn.selection.value.modelID?{...Sn.selection.value,providerID:Sn.selection.value.providerID,modelID:Sn.selection.value.modelID}:void 0;if(Sn.kind===`primary`&&e&&(!t?.providerID||!t?.modelID)){let n=J.getState().getDirectoryForSession(e)??jn??null,r=ei(n);if(ui.getState().activeDirectoryKey!==r&&await ui.getState().activateDirectory(n),J.getState().currentSessionId===e){let e=ui.getState();t=RC({captured:IC(e,{expectedConfigKey:ei(n),activeDirectoryKey:e.activeDirectoryKey}),surfaceSelection:Sn.selection.value})}}return t},d=await o(),f=!1,h=d?.providerID,g=d?.modelID,_=d?.agent,v=d?.variant;if(!h||!g){if(!f){f=!0;try{await ui.getState().loadProviders({forceRefresh:!0,source:`chat-input-send-recovery`}),d=await o(),h=d?.providerID,g=d?.modelID,_=d?.agent,v=d?.variant}catch{}}if(!h||!g){console.warn(`Cannot send message: provider or model not selected`),fa.error(l(`chat.chatInput.toast.messageSendFailed`));return}}Dn&&!t&&!b&&await Jn(Dn)&&await dn(Dn);let S={...a?{delivery:a}:{},commitStagedMessageEdit:!t,...I?{messageID:I.messageID,ticket:I}:E?{messageID:E}:{},...e?{sessionId:e,directoryHint:J.getState().getDirectoryForSession(e)??jn??null}:Sn.kind===`primary`&&Dn?{sessionId:Dn,directoryHint:J.getState().getDirectoryForSession(Dn)??jn??null}:{}},C=``,D=[],M,N=[],z=new Set($r(Ee,jn).map(e=>e.name)),B=[],V=b?void 0:wn.consumeSyntheticParts();for(let e=0;e<w.length;e++){let t=w[e],n=t.composerDocument&&xe(t.composerDocument,`direct-send-display`),r=n&&n.ok?{chunks:n.chunks??[],semantics:n.semantics??[]}:null,i=t.owner?.state===`bound`?t.owner.directory:jn,a=new Set($r(Ee,i).map(e=>e.name)),o=Ia({plan:r??va(t.content),agents:pr,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(B.push(...o.semantics),!M&&o.agent&&(M=o.agent),e===0)C=o.text,D=pa([...Ya(t.attachments),...o.attachments]);else{let e=Ya(t.attachments);N.push({text:o.text,attachments:pa([...e,...o.attachments])})}}if(!t&&s.hasContent){let e=Ya(Ta),t=Ia({plan:m,agents:pr,installedSkillNames:z,directory:jn,root:Qi||jn,confirmedFilePaths:ai.map(e=>e.path),confirmedDirectoryPaths:ai.filter(e=>e.kind===`directory`).map(e=>e.path),citationAttachments:Ta});B.push(...t.semantics),!M&&t.agent&&(M=t.agent),w.length===0?(C=t.text,D=pa([...e,...t.attachments])):N.push({text:t.text,attachments:pa([...e,...t.attachments])})}let H=Dn??(kn?`draft`:null),ee=[];if(!t&&H&&!b&&(ee=[...wn.inlineDrafts].sort((e,t)=>e.createdAt-t.createdAt)),ee.length>0)if(w.length===0)C=Bm(C,ee);else if(N.length>0){let e=N[N.length-1];e.text=Bm(e.text,ee)}else C=Bm(C,ee);if(V&&V.length>0&&N.push(...Mi(V)),ao&&N.push({text:ao.contextText,synthetic:!0}),so&&(N.push({text:so.instructionsText,synthetic:!0}),N.push({text:so.contextText,synthetic:!0})),N.push(...Ca(B,Dn&&J.getState().getDirectoryForSession(Dn)||jn)),!C&&D.length===0&&N.length===0)return;if(T&&E){if(!await qi({messageID:E,providerID:h,modelID:g,agent:_,text:C,attachments:D,additionalParts:N,agentMentionName:M}))return;if(!dr.getState().isEstablishing(T)){k();return}}let U=async()=>{if(k(),uo&&w.length>0&&F.setState(e=>{let t=O(uo),n=e.queuedMessages[t]??[],r=new Set(w.map(e=>e.id));return{queuedMessages:{...e.queuedMessages,[t]:[...w,...n.filter(e=>!r.has(e.id))]}}}),t)return V&&wn.restoreSyntheticParts(V),!0;wn.pendingInput?.text===s.message&&wn.consumePendingInput(),c&&ii(c);let e=!0;return u.length>0&&(e=await wn.restoreAttachments(u)),V&&wn.restoreSyntheticParts(V),ee.length>0&&wn.restoreInlineDrafts(ee),e};if(!b&&Dn&&i){let e=uo?j(F.getState(),uo).find(e=>e.id===i||e.queueItemID===i):void 0;uo&&e?.queueItemID&&e.operationID&&So(uo,e.queueItemID,e.operationID)}else!b&&Dn&&Qo&&uo&&xo(uo);!t&&!b&&(Wr(``),He(-1),Lr(!1),aC({queuedOnly:t,resourcePolicy:b,rootAttachmentCount:u.length})&&wn.clearAttachments());let te=()=>rC({currentSessionId:Dn,messageRef:Ni,replacePlainDocument:Wr}),W=C.trimStart();if(p===`normal`&&W.startsWith(`/`)){let e=Cc(W.slice(1).trim()).split(/\s+/)[0]?.toLowerCase();if(!vc(e,e=>Vv(Sn,{name:e.name,source:`openchamber`})))return;if(Dn&&(e===`undo`||e===`redo`)&&nC(W,p)&&te(),e===`undo`&&Dn){try{await J.getState().handleSlashUndo(Dn),n?.()}catch(e){fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.messageSendFailed`))}return}if(e===`new`){nC(W,p)&&te(),await Cn?.shortcut(`new`);return}if(e===`redo`&&Dn){try{await J.getState().handleSlashRedo(Dn),n?.()}catch(e){fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.messageSendFailed`))}return}if(e===`fork`&&Dn){await iC({command:`fork`,consumeCommandText:te,forkSession:()=>J.getState().forkCurrentSession(Dn),waitForConnection:Ea,getDirectoryForSession:()=>J.getState().getDirectoryForSession(Dn),summarizeSession:async()=>void 0,onCompactError:()=>void 0,onForkError:e=>{fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.messageSendFailed`))}});return}if(e===`timeline`&&Dn&&Li.timeline){Rr(!0);return}if(e===`compact`&&Dn){iC({command:`compact`,consumeCommandText:te,forkSession:async()=>void 0,waitForConnection:Ea,getDirectoryForSession:()=>Sn.directory??``,summarizeSession:e=>Mn?Sn.backend.compact({operation:`compact`,surfaceID:Sn.surfaceID,transportIdentity:Sn.transportIdentity,runtimeGeneration:Sn.runtimeGeneration,sessionID:Dn,directory:e,draftKey:Mn,deliveryTarget:Sn.deliveryTarget,providerID:h,modelID:g,agent:_,variant:v}):Promise.reject(Error(`chat-input-surface-incomplete`)),onCompactError:()=>{fa.error(l(`chat.chatInput.toast.compactFailed`))},onForkError:()=>void 0});return}if(e===`summary`&&Dn){try{await Ea();let e=W.replace(/^\/\u2003?summary\b/i,``).trim(),t=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 Ur(`session.summary.visible`,{topic_line:t}),a=await Ur(`session.summary.instructions`,{topic_block:r});await Fn(i,h,g,_,[],M,[{text:a,synthetic:!0}],v,p,S),n?.()}catch(e){await U(),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.summaryFailed`))}return}if(e===`workspace-review`&&(Dn||kn)){try{await Ea();let e=await Ur(`session.review.visible`),t=await Ur(`session.review.instructions`);await Fn(e,h,g,_,[],M,[{text:t,synthetic:!0}],v,p,S),n?.()}catch(e){await U(),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.reviewFailed`))}return}if(e===`handoff-review`&&Dn&&!_r&&!x()){Un(!0);return}if(e===`goal`&&(Dn||kn)){k(),En.getState().setArmed(!0);let e=eC(W,p)??``;Wr(e),Ni.current=e,He(-1),e||Lr(!1);return}if(e===`craft-goal`&&(Dn||kn)){try{await Ea();let e=W.replace(/^\/\u2003?craft-goal\b/i,``).trim(),t=await Ur(`session.craftGoal.visible`,{idea_block:e?`\n\nHere is my initial idea:\n${e}`:``}),r=await Ur(`session.craftGoal.instructions`);await Fn(t,h,g,_,[],M,[{text:r,synthetic:!0}],v,p,S),n?.()}catch(e){await U(),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.craftGoalFailed`))}return}if(e===`catch-up`&&(Dn||kn)){try{await Ea();let e=await Ur(`session.catchup.visible`),t=await Ur(`session.catchup.instructions`);await Fn(e,h,g,_,[],M,[{text:t,synthetic:!0}],v,p,S),n?.()}catch(e){await U(),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.catchUpFailed`))}return}if(e===`debug`&&(Dn||kn)){try{await Ea();let e=await Ur(`session.debug.visible`),t=await Ur(`session.debug.instructions`);await Fn(e,h,g,_,[],M,[{text:t,synthetic:!0}],v,p,S),n?.()}catch(e){await U(),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.debugFailed`))}return}if(e===`weigh`&&(Dn||kn)){try{await Ea();let e=await Ur(`session.weigh.visible`),t=await Ur(`session.weigh.instructions`);await Fn(e,h,g,_,[],M,[{text:t,synthetic:!0}],v,p,S),n?.()}catch(e){await U(),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.weighFailed`))}return}if(e===`explore`&&(Dn||kn)){try{await Ea();let e=await Ur(`session.explore.visible`),t=await Ur(`session.explore.instructions`);await Fn(e,h,g,_,[],M,[{text:t,synthetic:!0}],v,p,S),n?.()}catch(e){await U(),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.exploreFailed`))}return}}let ne=Dn&&J.getState().getDirectoryForSession(Dn)||jn;if(An||Dn&&!Lw(Dn,ne)){let e=await xn().catch(()=>null);e&&N.push({text:gn(e),synthetic:!0})}try{let e=Uo.getState().expandText;C=await e(C);for(let t of N)t.synthetic||(t.text=await e(t.text))}catch(e){console.warn(`[ChatInput] Failed to expand snippets, sending original text:`,e)}R=!0;let G=Fn(C,h,g,_,D,M,N.length>0?N:void 0,v,p,S);P=!0,G.finally(()=>{hs(),L&&J.getState().endMessageEditCommit(L.sessionId,L.messageId)}),T&&G.then(()=>{A(T)}).catch(()=>{dr.getState().clearEstablishing(T)}),typeof window>`u`?n?.():window.requestAnimationFrame(()=>{n?.()}),G.then(()=>{ao&&oo(null),so&&co(null)}).catch(e=>{I&&Hn(I),U().then(e=>{e||fa.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`)){fa.error(l(`chat.chatInput.toast.attachmentsTooLarge`));return}if(r){u.length>0&&fa.error(l(`chat.chatInput.toast.sendAttachmentsFailed`));return}fa.error(t||l(`chat.chatInput.toast.messageSendFailed`))}),_r||di.current?.focus()}finally{R||(I&&Hn(I),L&&J.getState().endMessageEditCommit(L.sessionId,L.messageId)),P||(N&&c&&ii(c),hs(),T&&A(T))}};ss.current=Os;let ks=Z.useCallback(()=>{if(bs()||gs())return;let e=as(),t=p===`normal`&&e.hasContent&&Dn&&(ns||Wo),n=t&&Wg(fo.mode)&&Jr(Sn.deliveryTarget?.kind,fo.mode);lo===`queue`&&n?Ss():lo===`steer`&&t||lo===`queue`&&t&&!n?ss.current(t?{delivery:`steer`}:void 0):ss.current()},[p,as,Dn,ns,Wo,lo,Ss,fo.mode,Sn.deliveryTarget?.kind,ys]),As=Z.useCallback(e=>{if(gs())return;let t=(di.current?.value??Ni.current).trim(),n=t?`${e}\n${t}`:e;ss.current({presetText:n})},[]),js=Z.useCallback(e=>{let t=nT(Fi().text,e);si(t),di.current&&(di.current.value=t),setTimeout(()=>{di.current?.focus()},0)},[si]),Ms=Z.useCallback(e=>{if(gs())return;let t=nT(di.current?.value??Ni.current,e);ss.current({presetText:t})},[]),Ns=wn.pendingPreset,Ps=wn.consumePendingPreset;Z.useEffect(()=>{if(Ns==null)return;let e=Ps();e&&As(e)},[Ns,Ps,As]);let Fs=Z.useCallback(()=>{Wr(``),He(-1),Tn.length>0&&wn.clearAttachments(),uo&&xo(uo),D(!1),L(!1),V(!1),C(!1),p===`shell`&&m(`normal`)},[Tn.length,wn,xo,uo,Wr,p]),Is=e=>{if(!Sn.active||ju(e))return;if(Ji&&us(e,Ji)&&!jr){let t=di.current;if(!(t&&t.selectionStart!==t.selectionEnd)){e.preventDefault(),Fs();return}}if(p===`shell`&&e.key===`Escape`){e.preventDefault(),m(`normal`);return}if(p===`shell`&&e.key===`Backspace`&&Hr.length===0){e.preventDefault(),m(`normal`);return}if((e.key===`Backspace`||e.key===`Delete`)&&!e.metaKey&&!e.ctrlKey){let t=di.current,n=t?.selectionStart??Hr.length,r=t?.selectionEnd??Hr.length,i=Xr({key:e.key,selectionStart:n,selectionEnd:r,altKey:e.altKey});if(i){let t=Iw(zr.getDocument().text,i.start);e.preventDefault(),si(t.text),requestAnimationFrame(()=>{di.current?.setSelectionRange(t.caret,t.caret),qs()}),Js(t.text,t.caret);return}let a=pt(Hr,Tn.filter(xt).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=Iw(a.text,a.caret);e.preventDefault(),si(n.text);for(let e of Tn)t.has(e.filename.toLowerCase())&&wn.removeAttachment(e.id);requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=n.caret,di.current.selectionEnd=n.caret),qs()}),Js(n.text,n.caret);return}let o=vS(Hr,La.keys(),{key:e.key,selectionStart:n,selectionEnd:r,altKey:e.altKey});if(o){let t=Iw(o.text,o.caret);e.preventDefault(),si(t.text),requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=t.caret,di.current.selectionEnd=t.caret),qs()}),Js(t.text,t.caret);return}if(n===r&&!e.altKey){let t=e.key===`Backspace`?n-1:n;if(t>=0&&t<Hr.length){let n=ft(Hr,Tn.map(e=>e.filename)).find(e=>t>=e.start&&t<e.end);if(n){let t=be(Hr.slice(n.start+1,n.end-1)).trim(),r=Tn.find(e=>e.filename.toLowerCase()===t.toLowerCase()),i=Hr[n.end]===` `?n.end+1:n.end,a=`${Hr.slice(0,n.start)}${Hr.slice(i)}`;e.preventDefault(),si(a),r&&wn.removeAttachment(r.id),requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=n.start,di.current.selectionEnd=n.start),qs()}),Js(a,n.start);return}let r=t;for(;r>0&&!/\s/.test(Hr[r-1]);)--r;let i=t+1;for(;i<Hr.length&&!/\s/.test(Hr[i]);)i+=1;let a=Hr.slice(r,i),o=a.slice(1);if(kw.test(a)&&!Oa.current.has(o.toLowerCase())&&Va({mention:o,confirmed:ci.has(o),terminated:i<Hr.length&&/\s/.test(Hr[i])})){let t=Hr[i]===` `?i+1:i,n=`${Hr.slice(0,r)}${Hr.slice(t)}`;e.preventDefault(),si(n),requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=r,di.current.selectionEnd=r),qs()}),Js(n,r);return}}}}let t=(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.metaKey&&!e.ctrlKey;if(E&&Oi.current&&(e.key===`Enter`||e.key===`Escape`||e.key===`Tab`||t)){e.preventDefault(),e.stopPropagation(),Oi.current.handleKeyDown(e.key);return}if(I&&ki.current&&(e.key===`Enter`||e.key===`Escape`||e.key===`Tab`||t)){e.preventDefault(),e.stopPropagation(),ki.current.handleKeyDown(e.key);return}if(B&&Ai.current&&(e.key===`Enter`||e.key===`Escape`||e.key===`Tab`||t)){e.preventDefault(),e.stopPropagation(),Ai.current.handleKeyDown(e.key);return}if(S&&Ei.current&&(e.key===`Enter`||e.key===`Escape`||e.key===`Tab`||t)){e.preventDefault(),e.stopPropagation(),Ei.current.handleKeyDown(e.key);return}if(ga&&e.key===`Escape`){e.preventDefault(),Lr(!1);return}let n=Wi&&!Wi.includes(`shift`)?os(`shift+${Wi}`):``,r=n&&us(e,n)?-1:+!!us(e,Wi);if(r!==0&&!E&&!I&&!B&&!S){e.preventDefault(),e.stopPropagation(),Cn?.shortcut(`cycle`,r),requestAnimationFrame(()=>{di.current?.focus({preventScroll:!0})});return}let i=E||I||B||S,a=di.current?.selectionStart===0&&di.current?.selectionEnd===0,o=di.current?.selectionStart===Hr.length&&di.current?.selectionEnd===Hr.length,s=!i&&(Hr.length===0||a),c=!i&&(Hr.length===0||o);if(p===`normal`&&!i&&!e.metaKey&&!e.ctrlKey&&!e.altKey){let t=di.current,n=t?.selectionStart??-1,r=t?.selectionEnd??-1;if(t&&n>=0){let t=(t,n,r)=>{e.preventDefault(),si(t),requestAnimationFrame(()=>{let e=di.current;e&&(e.selectionStart=n,e.selectionEnd=r),qs()}),Js(t,r)},i={"`":["`","`"],"*":[`*`,`*`],_:[`_`,`_`],"~":[`~`,`~`],"(":[`(`,`)`],"[":[`[`,`]`],"{":[`{`,`}`],'"':[`"`,`"`],"'":[`'`,`'`]};if(r>n&&i[e.key]){let[a,o]=i[e.key],s=Hr.slice(n,r);t(`${Hr.slice(0,n)}${a}${s}${o}${Hr.slice(r)}`,n+a.length,r+a.length);return}if(e.key==="`"&&n===r){let e=Hr.slice(0,n);if(/(^|\n)``$/.test(e)){let n=`${e}\`\n\n\`\`\`${Hr.slice(r)}`,i=e.length+2;t(n,i,i);return}}}}if(e.key===`ArrowUp`&&!e.metaKey&&!e.ctrlKey&&s&&Fo.length>0){if(e.preventDefault(),Ve===-1)He(0),Zr({text:Fo[0],references:[]});else if(Ve<Fo.length-1){let e=Ve+1;He(e),Zr({text:Fo[e],references:[]})}requestAnimationFrame(()=>{di.current?.setSelectionRange(0,0)});return}if(e.key===`ArrowDown`&&!e.metaKey&&!e.ctrlKey&&c&&Ve>=0){if(e.preventDefault(),Ve===0)He(-1),ti();else{let e=Ve-1;He(e),Zr({text:Fo[e],references:[]})}return}if(e.key===`Enter`&&!e.shiftKey){if(e.preventDefault(),bs()||gs())return;let t=e.ctrlKey||e.metaKey,n=p===`normal`&&Zo&&Dn&&(ns||Wo),r=n&&Wg(fo.mode)&&Jr(Sn.deliveryTarget?.kind,fo.mode);lo===`queue`?t||!n?Os():r?Ss():Os({delivery:`steer`}):t||!n?Os():Os({delivery:`steer`})}},Ls=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}},[]),Rs=Z.useCallback(()=>{if(!ga){Za(null);return}if(!E&&!I&&!B&&!S){Za(null);return}let e=di.current,t=vi.current;if(!e||!t)return;let n=e.selectionStart??Hr.length,r=Ls(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=S?520:E||B?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));Za({top:u===`below`?o+22:o-6,left:f,place:u,maxHeight:p})},[ga,Ls,Hr.length,E,S,B,I]);Z.useLayoutEffect(()=>{Rs()},[Rs,Hr,E,I,B,S,ga]),Z.useEffect(()=>{if(!ga)return;let e=()=>Rs();return window.addEventListener(`resize`,e),()=>{window.removeEventListener(`resize`,e)}},[ga,Rs]);let zs=Z.useCallback(()=>{$a.current&&=(clearTimeout($a.current),null),ca(!0),$a.current=setTimeout(()=>{ca(!1),$a.current=null},1800)},[]),Bs=Z.useCallback(()=>{if(wn.abortPrompt.clear(),zs(),Sn.kind===`secondary`){Cn?.shortcut(`abort`);return}In()},[In,Cn,zs,Sn.kind,wn]),Hs=Z.useCallback((e=1)=>{if(hr)return;let t=kr(pr,Sn.selection.value.agent??Zn,e);if(!t||!Sn.selection.change)return;let n=Kr({providerID:Sn.selection.value.providerID??``,modelID:Sn.selection.value.modelID??``,agent:Sn.selection.value.agent??null},t,pr,mr);Sn.selection.change({...Sn.selection.value,...n,agent:n.agent??void 0}),Sn.kind===`primary`&&(g.getState().addRecentAgent(t),Sn.sessionID&&Nn.getState().saveSessionAgentSelection(Sn.sessionID,t))},[pr,Zn,mr,hr,Sn.kind,Sn.selection,Sn.sessionID]);Ue.current=Hs;let Us=Z.useRef(null),[Ws,Gs]=Z.useState(null),Ks=Z.useCallback(e=>{Gs(t=>t===e?t:e)},[]),qs=Z.useCallback(e=>{let t=di.current;if(!t)return;let n=t.scrollTop;if(ya){t.style.height=`100%`,t.style.maxHeight=`none`,t.style.overflowY=`auto`,re(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=Sw({scrollHeight:t.scrollHeight||t.offsetHeight,dictationHeight:Us.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),re(e=>e&&e.height===u.height&&e.maxHeight===u.maxHeight?e:{height:u.height,maxHeight:u.maxHeight})},[ya]);Z.useLayoutEffect(()=>{let e=Hr.length<_i.current;_i.current=Hr.length,qs({allowShrink:e})},[qs,Hr,_r]),Z.useLayoutEffect(()=>{Us.current=Ws,qs({allowShrink:Ws===null})},[qs,Ws]);let Js=Z.useCallback((e,t,n=`manual`,r)=>{let i=Hc({text:e,cursor:t,inputMode:p,mentionInputSource:n,insertedText:r});if(mi.current=i,!i){D(!1),C(!1),L(!1),V(!1),z(``);return}if(i.kind===`slash-command`){M(i.query),D(!0),C(!1),L(!1),V(!1);return}if(D(!1),i.kind===`slash-skill`){z(i.query),L(!0),C(!1),V(!1);return}if(L(!1),z(``),i.kind===`snippet`){U(i.query),V(!0),C(!1);return}V(!1),T(i.query),C(!0)},[p,M,T,D,C,L,V,z,U]),Ys=Z.useCallback((e,t,n,r=`manual`,i)=>{let a=e,o=t,s=n;if(p===`normal`&&!fi.current&&Ra.size>0&&e.includes(`/`)){let r=cc(e,Ra,n);r&&(a=r.text,o=t+(r.caret-n),s=r.caret)}let c=qr(a,o,s,(e,t)=>{let n=[...e];for(let e of Xi(t.text,{agentNames:Da,includeUnterminatedPastedReferences:r===`paste`}))n=Nc(n,{kind:e.kind,value:e.value,path:e.value,label:e.value,range:{start:e.start,end:e.end}});return n}),l=Fi(),u=c.requiresTextCorrection||o!==c.start||s!==c.end||a!==e;return requestAnimationFrame(()=>{let e=di.current;e&&Lv(u,fi.current)&&(e.value=l.text,e.setSelectionRange(c.start,c.end)),qs()}),Js(l.text,c.end,r,i),{document:l,selection:c}},[qs,qr,Fi,p,Da,Ra,Js]),Xs=Z.useCallback((e,t=`manual`)=>{if(!e)return;let n=di.current;if(!n){let n=Hr+e;Ys(n,n.length,n.length,t,e);return}let r=n.selectionStart??Hr.length,i=n.selectionEnd??Hr.length,a=`${Hr.substring(0,r)}${e}${Hr.substring(i)}`,o=r+e.length;Ys(a,o,o,t,e)},[Ys,Hr]),Zs=q((e,t)=>{let n=new Set(ct(Tn.map(e=>e.filename),e,t));if(n.size!==0)for(let e of Tn)n.has(e.filename)&&wn.removeAttachment(e.id)}),Qs=Z.useCallback(e=>{wn.removeAttachment(e.id)},[wn]),$s=Z.useCallback(()=>{bi.current=!1,wi.current=[],xi.current&&=(clearTimeout(xi.current),null)},[]),ec=Z.useCallback(()=>{xi.current&&clearTimeout(xi.current),xi.current=setTimeout(()=>{$s()},700)},[$s]),tc=Z.useCallback(()=>{Si.current=!1,Ci.current&&=(clearTimeout(Ci.current),null)},[]),nc=Z.useCallback(()=>{Si.current=!0,Ci.current&&clearTimeout(Ci.current),Ci.current=setTimeout(()=>{Si.current=!1,Ci.current=null},700)},[]),rc=Z.useCallback(e=>{!x()||!bi.current||e.nativeEvent?.inputType===`insertFromDrop`&&(e.preventDefault(),$s())},[$s]),ac=e=>{if(jr)return;let t=e.nativeEvent;if(x()&&bi.current){let n=wi.current;if(t?.inputType===`insertFromDrop`||n.some(t=>t.length>0&&e.target.value.includes(t))){$s();return}}let n=e.target.value;Zs(Ni.current,n);let r=e.target.selectionStart??n.length,i=t?.inputType?.startsWith(`insertFromPaste`)?Pw(Ni.current,n):``,a=i.includes(`@`)||Si.current;Si.current&&tc();let o=a?`paste`:`manual`;if(p===`normal`&&n.startsWith(`!`)){let e=n.slice(1),t=Math.max(0,r-1);m(`shell`),Wr(e),qs(),D(!1),L(!1),C(!1),requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=t,di.current.selectionEnd=t)});return}Ys(n,r,e.target.selectionEnd??r,o,i)};Z.useEffect(()=>()=>{$s(),tc()},[$s,tc]);let oc=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=di.current,i=r?.selectionStart??Hr.length,a=r?.selectionEnd??Hr.length,o=Oc(n,Hr.slice(0,i),Hr.slice(a)),s=`${Hr.slice(0,i)}${o}${Hr.slice(a)}`;Zs(Hr,s),Ii(s,t)},[Hr,Ii,Zs]),sc=Z.useCallback(async e=>{let t=Hw(e.clipboardData);if(t.length>0&&(Dn||kn)){e.preventDefault(),oc(t);return}if(p===`normal`&&(Dn||kn)){let t=di.current,n=t?.selectionStart??-1,r=t?.selectionEnd??-1;if(t&&r>n){let t=e.clipboardData.getData(`text`).trim(),i=Hr.slice(n,r);if(jw.test(t)&&!/\s/.test(t)&&i.trim().length>0&&!i.includes(`](`)){e.preventDefault();let a=`${Hr.slice(0,n)}[${i}](${t})${Hr.slice(r)}`,o=n+1+i.length+2+t.length+1;si(a),requestAnimationFrame(()=>{let e=di.current;e&&(e.selectionStart=o,e.selectionEnd=o),qs()}),Js(a,o,Fw(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(p===`normal`&&ZC(Fi(),a)){e.preventDefault();let t=Fi().text,n=di.current,r=n?.selectionStart??Hr.length,i=n?.selectionEnd??Hr.length,o=QC(a,Hr,Fi().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}),XC(Fi())),s=Yr(r,i,{id:o.id,kind:`paste`,text:o.text,characterCount:o.characterCount,index:o.index,display:o.token},{inlineBoundaries:!0,padDocumentEdges:!0}),c=Rc(s.document.text,s.caret);di.current&&(di.current.value=s.document.text),requestAnimationFrame(()=>{di.current?.setSelectionRange(c,c),qs()}),Js(s.document.text,c),Zs(t,s.document.text);return}a.includes(`@`)&&nc();return}if(!Dn&&!kn){a.includes(`@`)&&nc();return}e.preventDefault();let o=_t(i,[...Tn.map(e=>e.filename),...Pi.current]),s=Et(o),c=Fi().text,u=di.current,d=u?.selectionStart??Hr.length,f=u?.selectionEnd??Hr.length,m=p===`normal`&&ZC(Fi(),a)?QC(a,Hr,Fi().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}),XC(Fi())):null,h=a?`${a}${/\s$/.test(a)?``:` `}${s}`:s,g=Oc(h,Hr.slice(0,d),Hr.slice(f));if(m){let e=Yr(d,f,{id:m.id,kind:`paste`,text:m.text,characterCount:m.characterCount,index:m.index,display:m.token},{inlineBoundaries:!0,padDocumentEdges:!0}),t=Rc(e.document.text,e.caret),n=`${e.document.text.slice(0,t)}${s}${e.document.text.slice(t)}`;Ys(n,t+s.length,t+s.length,Fw(n),s),Zs(c,n)}else Xs(g,Fw(g)),Zs(c,`${Hr.slice(0,d)}${g}${Hr.slice(f)}`);for(let e=0;e<i.length;e+=1){let t=o[e],n=Nw(i[e],t);Pi.current.add(t);try{await wn.addAttachment(n)}catch(e){console.error(`Clipboard image attach failed`,e),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.clipboardAttachFailed`))}finally{Pi.current.delete(t)}}},[wn,oc,Tn,qs,Dn,Fi,p,Yr,nc,Hr,kn,Xs,l,Js,Ys,si,Zs]),lc=Z.useCallback((e,t)=>{let n=e.currentTarget,r=n.selectionStart??0,i=n.selectionEnd??r;if(i<=r)return;let a=_S(r,i,[...ft(Hr,Tn.filter(xt).map(e=>e.filename)),...gS(Hr,La.keys()),...Fi().references]),o=a?.start??r,s=a?.end??i,c=Hr.slice(o,s),l=ge(c);if(!(l===c&&!a))if(e.preventDefault(),e.clipboardData.setData(`text/plain`,l),t===`cut`){let e=`${Hr.slice(0,o)}${Hr.slice(s)}`;Ys(e,o,o),requestAnimationFrame(()=>{di.current?.setSelectionRange(o,o),qs()})}else a&&(a.start!==r||a.end!==i)&&requestAnimationFrame(()=>{di.current?.setSelectionRange(o,s)})},[qs,Tn,La,Ys,Fi,Hr]),pc=Z.useCallback(e=>{lc(e,`copy`)},[lc]),mc=Z.useCallback(e=>{lc(e,`cut`)},[lc]),hc=e=>{let t=di.current,n=t&&document.activeElement===t?t.selectionStart??pi.current:pi.current;return Yc(e,n)},_c=()=>{cl(_r)||di.current?.focus()},bc=e=>{let t=hc(Hr.length),n=yc(Hr,t,mi.current),r=Hr.substring(0,t).lastIndexOf(`@`),i=e.relativePath&&e.relativePath.trim().length>0?e.relativePath.trim():Uc(e.path)||e.name,a=e.isDirectory?[i]:[],o=n?.start??(r===-1?t:r),s=n?.end??t,c=Ic(Hr,o,s,`@${i}`);Ii(c.text,[i],a),pi.current=c.caret,requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=c.caret,di.current.selectionEnd=c.caret),qs(),Js(c.text,c.caret)}),C(!1),T(``),_c()},Sc=e=>{let t=hc(Hr.length),n=yc(Hr,t,mi.current),r=Hr.substring(0,t).lastIndexOf(`@`),i=n?.start??(r===-1?t:r),a=n?.end??t,o=Ic(Hr,i,a,`@${e}`);si(o.text,t=>Nc(t,{kind:`agent`,value:e,path:e,label:e,range:{start:o.start,end:o.end}})),pi.current=o.caret,requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=o.caret,di.current.selectionEnd=o.caret),qs(),Js(o.text,o.caret)}),C(!1),T(``),_c()},wc=q(e=>{Di.current||(Di.current=!0,(async()=>{try{let t=J.getState().getAuthoritativeDirectoryForSession(e.id);if(!t){fa.error(l(`chat.chatInput.toast.sessionReferenceLoadFailed`));return}if(await at(e.id,{directory:t}),!gi(e.id,t)){fa.error(l(`chat.chatInput.toast.sessionReferenceLoadFailed`));return}Ki([{type:`session`,sessionId:e.id}],t).catch(()=>void 0);let n=Fi(),r=hc(n.text.length),i=yc(n.text,r,mi.current),a=n.text.substring(0,r).lastIndexOf(`@`),o=wr().get(e.id)?.title||e.title||e.id,s=i?.start??(a===-1?r:a),c=i?.end??r,u={id:`session:${e.id}:${se()}`,kind:`session`,sessionId:e.id,display:ie({trigger:`@`,icon:`chat-thread`,label:o})},d=Yr(s,c,u,{inlineBoundaries:!0,padDocumentEdges:!0}),f=Rc(d.document.text,d.caret);pi.current=f,requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=f,di.current.selectionEnd=f),qs(),Js(d.document.text,f)}),C(!1),T(``),_c()}catch{fa.error(l(`chat.chatInput.toast.sessionReferenceLoadFailed`))}finally{Di.current=!1}})())}),Ec=q(e=>{let t=Fi(),n=hc(t.text.length),r=yc(t.text,n,mi.current)??uc(t.text,n);if(!r)return!1;let i=Yr(r.start,r.end,e,{inlineBoundaries:!0,padDocumentEdges:!0,padLeadingDocumentEdge:!1}),a=i.document.references.some(t=>t.id===e.id),o=Rc(i.document.text,i.caret);return pi.current=o,requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=o,di.current.selectionEnd=o),qs(),Js(i.document.text,o),a&&(D(!1),L(!1))}),_c(),a}),kc=e=>{Ec({id:`skill:${e.name}:${se()}`,kind:`skill`,skillName:e.name,display:ie({trigger:`/`,icon:`book-open`,label:e.name})})&&z(``)},jc=(e,t)=>{let n=hc(Hr.length),r=yc(Hr,n,mi.current),i=Hr.substring(0,n).lastIndexOf(`#`),a=r?.start??(i===-1?n:i),o=r?.end??n,s=`${Hr.substring(0,a)}#${t} ${Hr.substring(o)}`;si(s);let c=a+t.length+2;pi.current=c,requestAnimationFrame(()=>{di.current&&(di.current.selectionStart=c,di.current.selectionEnd=c),qs(),Js(s,c)}),V(!1),U(``),_c()},Mc=(e,t=!1)=>{if(!Vv(Sn,e))return;let n=`/${e.name}`;if(!t&&e.isSkill){Ec({id:`skill:${e.name}:${se()}`,kind:`skill`,skillName:e.name,display:ie({trigger:`/`,icon:`book-open`,label:e.name})})&&M(``);return}if(!t&&e.source===`opencode`&&!e.isSkill&&e.isBuiltIn!==!0&&Ec({id:`command:${e.name}:${se()}`,kind:`command`,commandName:e.name,reference:e.reference??e.name,display:ie({trigger:`/`,icon:`command`,label:e.name})})){M(``);return}let r=e.isSkill?` ${n} `:`${n} `,i=cc(r,new Set([...Ra,e.name.toLowerCase()]),r.length);Wr(i?.text??r);let a=di.current;if(a&&(a._commandMetadata=e),D(!1),M(``),t){Os({presetText:n});return}let o=()=>{if(!cl(_r)&&di.current){try{di.current.focus({preventScroll:!0})}catch{di.current.focus()}di.current.setSelectionRange(di.current.value.length,di.current.value.length)}};requestAnimationFrame(()=>{o(),requestAnimationFrame(o)}),setTimeout(o,60)};Z.useEffect(()=>{Dn&&di.current&&!_r&&di.current.focus()},[Dn,_r]),Z.useEffect(()=>{_r||oe(null)},[_r]);let Pc=wn.abortPrompt.sessionID,Lc=wn.abortPrompt.clear;Z.useEffect(()=>{Pc&&Pc!==Dn&&Lc()},[Dn,Pc,Lc]),Z.useEffect(()=>{Ti.current=!!(Dn||kn)},[Dn,kn]);let zc=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 LS(e).length>0},[]),Bc=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)},[]),Uc=Z.useCallback(e=>{let t=e.replace(/\\/g,`/`).trim(),n=(Qi||``).replace(/\\/g,`/`).replace(/\/+$/,``);if(!n||t===n)return t;let r=`${n}/`;return t.startsWith(r)?t.slice(r.length):t},[Qi]),Wc=e=>{if(!zc(e.dataTransfer))return;e.preventDefault(),e.stopPropagation(),yi.current++;let t=e.dataTransfer.types?.includes(`application/x-openchamber-file-path`)??!1;t!==y&&b(t),(Dn||kn)&&!h&&_(!0)},Gc=e=>{zc(e.dataTransfer)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect=`copy`,(Dn||kn)&&!h&&_(!0))},qc=e=>{e.preventDefault(),e.stopPropagation(),yi.current--,yi.current<=0&&(yi.current=0,_(!1),b(!1),$s())},Jc=()=>{yi.current=0,_(!1),b(!1),$s()},Xc=async e=>{if(yi.current=0,!zc(e.dataTransfer)){$s();return}if(e.preventDefault(),e.stopPropagation(),_(!1),!Dn&&!kn)return;let t=e.dataTransfer.getData(`application/x-openchamber-file-path`);if(t&&t!==`.`){let e=`@${t}`,n=di.current,r=Ni.current;if(n){let t=n.selectionStart??pi.current,i=n.selectionEnd??t,a=Ic(r,t,i,e);si(a.text),requestAnimationFrame(()=>{n.selectionStart=a.caret,n.selectionEnd=a.caret,pi.current=a.caret,n.focus()})}else{let t=Ic(r,r.length,r.length,e);si(t.text)}$s();return}let n=Hw(e.dataTransfer);if(n.length>0){x()&&(wi.current=n),oc(n),x()||$s();return}let r=Bc(e.dataTransfer);if(r.length>0){let e=Et(r.map(e=>e.name)),t=Oc(e,Ni.current.slice(0,di.current?.selectionStart??Ni.current.length),Ni.current.slice(di.current?.selectionEnd??Ni.current.length));Xs(t);for(let e of r)try{await wn.addAttachment(e)}catch(e){console.error(`File attach failed`,e),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.attachFileFailed`))}}$s()},Zc=e=>{zc(e.dataTransfer)&&(e.preventDefault(),x()&&(bi.current=!0,ec()))},$c=Z.useRef(null),el=Z.useRef(null),rl=q((e=!0)=>{Le.current=0;let t=()=>{let t=Fv(di);if(!t||(Iv(di),!e))return;let n=t.value.length;try{t.setSelectionRange(n,n)}catch{}};t(),window.requestAnimationFrame(t)}),il=Z.useCallback(async e=>{let t=Array.isArray(e)?e:Array.from(e);if(t.length>0){let e=Et(t.map(e=>e.name)),n=Oc(e,Ni.current.slice(0,di.current?.selectionStart??Ni.current.length),Ni.current.slice(di.current?.selectionEnd??Ni.current.length));Xs(n)}for(let e of t)try{await wn.addAttachment(e)}catch(e){console.error(`File attach failed`,e),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.attachFileFailed`))}},[wn,Xs,l]),al=Z.useCallback(async()=>{try{let e=await Bi?.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(`
6537
- `);fa.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&&(rl(!1),await il(r),rl())}catch(e){console.error(`VS Code file pick failed`,e),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.vscodePickFailed`))}},[il,rl,l,Bi]),ol=Z.useCallback(()=>{if(x()){al();return}$c.current?.click()},[al]),sl=Z.useCallback(()=>{if(x()){al();return}el.current?.click()},[al]),ll=Z.useCallback(async()=>{if(!_p()){sl();return}try{let e=await vp(20);if(e===null){sl();return}e.length>0&&(rl(!1),await il(e),rl())}catch(e){console.error(`Native photo pick failed`,e),fa.error(l(`chat.chatInput.toast.attachFileFailed`))}},[il,rl,sl,l]),ul=Z.useCallback(async e=>{let t=e.target.files;!t||t.length===0||(rl(!1),await il(t),e.target.value=``,rl())},[il,rl]),dl=`gap-x-1.5 gap-y-0`,fl=x(),pl=Sn.kind===`primary`&&An&&!fl,ml=Z.useMemo(()=>(At?.selectedProjectId?Ln.find(e=>e.id===At.selectedProjectId)??null:null)||(zn?Ln.find(e=>e.id===zn)??null:null)||(Ln[0]??null),[zn,At?.selectedProjectId,Ln]),hl=Z.useMemo(()=>Uw(ml?.path??null),[ml?.path]),gl=ml?Ww(ml):null,_l=Fc(hl),vl=Tc(e=>hl?e.directories.get(hl)?.lastBranchesFetch??0:0),yl=Vc(hl),bl=!!_l?.all,Sl=Tc(e=>e.fetchBranches),[Cl,wl]=Z.useState(!1);Z.useEffect(()=>{!pl||!hl||!Ri||yl!==null||aa(hl,Ri,{silent:!0})},[aa,Ri,yl,hl,pl]),Z.useEffect(()=>{if(!pl||!hl||!ml||!Ri||yl!==!0){wl(!1);return}let e=!vl||Date.now()-vl>3e4;if(bl&&!e){wl(!1);return}let t=!1;return wl(!bl),Sl(hl,Ri).finally(()=>{t||wl(!1)}),()=>{t=!0}},[Sl,Ri,ml,vl,bl,yl,hl,pl]);let Tl=Dc(hl),El=_l?.current?.trim()||Tl?.trim()||``,Dl=Z.useMemo(()=>{if(!ml)return null;let e=Uw(ml.path);return!e||!El?null:{value:e,label:El}},[ml,El]),Ol=Z.useMemo(()=>{if(!ml)return[];let e=hl?Vt.get(hl)??Vt.get(ml.path)??[]:[];return Vi({projectRoot:Uw(ml.path)??``,rootBranch:El,worktrees:e,pendingBootstrapDirectory:At?.bootstrapPendingDirectory??null}).filter(e=>e.kind===`worktree`)},[Vt,At?.bootstrapPendingDirectory,ml,El,hl]),kl=Z.useMemo(()=>Uw(At?.bootstrapPendingDirectory??null)??Uw(At?.directoryOverride??null)??hl,[At?.bootstrapPendingDirectory,At?.directoryOverride,hl]),Al=Z.useMemo(()=>{let e=Uw(At?.bootstrapPendingDirectory??null);return!!(At?.preserveDirectoryOverride||At?.pendingWorktreeRequestId||e&&e===kl)},[At?.bootstrapPendingDirectory,At?.pendingWorktreeRequestId,At?.preserveDirectoryOverride,kl]),jl=Z.useMemo(()=>{let e=[];return Dl&&e.push(Dl),e.push(...Ol),!kl||e.some(e=>e.value===kl)||!Al?e:[...e,{value:kl,label:_o(kl)}]},[Dl,kl,Al,Ol]),Ml=Z.useMemo(()=>qx({selectedDirectory:kl,projectRootOption:Dl,worktreeOptions:Ol}),[Dl,kl,Ol]),Nl=Cb()===`mini-chat`,Pl=Z.useMemo(()=>Nl||ta!==!0||!na||na.isClean?!1:cb(na.files),[na,ta,Nl]),Fl=Z.useMemo(()=>!kl||Dl?.value===kl||Ol.some(e=>e.value===kl),[Dl?.value,kl,Ol]);Z.useEffect(()=>{At?.open&&(!At.preserveDirectoryOverride&&!At.bootstrapPendingDirectory||!kl||!Fl||(At.preserveDirectoryOverride&&J.getState().setDraftPreserveDirectoryOverride(!1),At.bootstrapPendingDirectory&&J.getState().setDraftBootstrapPendingDirectory(null)))},[At?.bootstrapPendingDirectory,At?.open,At?.preserveDirectoryOverride,Fl,kl]);let Il=Z.useMemo(()=>yl!==!0||Cl?!1:Dl?!0:Ol.length>0,[Cl,Dl,yl,Ol.length]),Ll=Z.useCallback(e=>{if(J.getState().newSessionDraft?.pendingWorktreeRequestId)return;let t=Ln.find(t=>t.id===e);t&&(zn!==e&&Bn(e),Bt({projectId:e,directoryOverride:t.path},{force:!0}))},[zn,Ln,Bn,Bt]),Rl=Z.useCallback(e=>{J.getState().newSessionDraft?.pendingWorktreeRequestId||ml&&Bt({projectId:ml.id,directoryOverride:e},{force:!0})},[ml,Bt]),zl=Z.useCallback(e=>{let t=e.icon?Lo[e.icon]:null,n=e.color?Vo[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)(No,{project:e,className:`size-full object-contain`,fallback:r}):r}),(0,$.jsx)(`span`,{className:`truncate`,children:Ww(e)})]})},[]);Z.useEffect(()=>{!pl||!ml||!kl||At?.pendingWorktreeRequestId||At?.bootstrapPendingDirectory||At?.preserveDirectoryOverride||jl.some(e=>e.value===kl)||Bt({projectId:ml.id,directoryOverride:ml.path})},[jl,At?.bootstrapPendingDirectory,At?.pendingWorktreeRequestId,At?.preserveDirectoryOverride,kl,ml,Bt,pl]);let Bl=Z.useCallback(()=>{Re(),he(!0),di.current?.blur()},[Re]),Vl=Z.useCallback(()=>{Re(),Se(!0),di.current?.blur()},[Re]);Z.useEffect(()=>{if(!_r||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=()=>Ie(Hb(t.children));n();let r=new MutationObserver(n);return r.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[Vb]}),()=>r.disconnect()},[_r]);let Hl=Fe||!!ae||me||_e||eo||no,Wl=io(mr.find(e=>e.id===Sn.selection.value.providerID),Sn.selection.value.modelID,l(`chat.modelControls.selectModel`)),Gl=Sn.selection.value.variant?.trim(),Kl=q(e=>{W(t=>fc(t,e.rows)),G(t=>t===e.highlightedIndex?t:e.highlightedIndex)}),ql=q(e=>Vv(Sn,e)),Jl=q(e=>{if(E){Oi.current?.acceptIndex(e,!0);return}if(I){ki.current?.acceptIndex(e);return}S&&Ei.current?.acceptIndex(e)}),Yl=q(()=>{mi.current=null,D(!1),L(!1),V(!1),C(!1),W([]),G(0)}),Xl=Ep({enabled:_r&&Sn.kind===`primary`,isMobile:_r,text:Hr,textPresetEpoch:zr.textPresetEpoch,placeholder:Sa,modelLabel:Wl,modelVariantLabel:Gl?Gn(Gl):``,canSend:es,canAbort:rs,attachmentCount:Tn.length,suppressed:Hl,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:Sn.selection.value.modelID,providerId:Sn.selection.value.providerID,agentName:Sn.selection.value.agent??``,agentLabel:rr(pr,Sn.selection.value.agent??void 0),agentAria:l(`chat.modelControls.selectAgent`),attachments:Tn,removeAttachmentNamedAria:e=>l(`chat.fileAttachment.actions.removeNamed`,{name:e}),onText:(e,t,n)=>{let r=Yc(e.length,n?.end??n?.start??e.length);if(pi.current=r,t){di.current&&(di.current.value=e),si(e);return}let i=Ni.current,a=ut(i,e,Tn.filter(xt).map(e=>e.filename)),o=a?.text??e;di.current&&(di.current.value=o),si(o);let s=Yc(o.length,n?.end??n?.start??o.length);if(pi.current=s,Js(o,s),!a)return;let c=new Set(a.removedFilenames.map(e=>e.toLowerCase()));for(let e of Tn)c.has(e.filename.toLowerCase())&&wn.removeAttachment(e.id)},onSend:e=>{di.current&&(di.current.value=e),tl({text:e,applyDocument:si,submit:ks})},onAbort:Bs,onAttach:Re,onFiles:(e,t)=>{t.length>0&&fa.error(l(`chat.chatInput.toast.someFilesSkipped`,{summary:t.join(`
6537
+ `);fa.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&&(rl(!1),await il(r),rl())}catch(e){console.error(`VS Code file pick failed`,e),fa.error(e instanceof Error?e.message:l(`chat.chatInput.toast.vscodePickFailed`))}},[il,rl,l,Bi]),ol=Z.useCallback(()=>{if(x()){al();return}$c.current?.click()},[al]),sl=Z.useCallback(()=>{if(x()){al();return}el.current?.click()},[al]),ll=Z.useCallback(async()=>{if(!_p()){sl();return}try{let e=await vp(20);if(e===null){sl();return}e.length>0&&(rl(!1),await il(e),rl())}catch(e){console.error(`Native photo pick failed`,e),fa.error(l(`chat.chatInput.toast.attachFileFailed`))}},[il,rl,sl,l]),ul=Z.useCallback(async e=>{let t=e.target.files;!t||t.length===0||(rl(!1),await il(t),e.target.value=``,rl())},[il,rl]),dl=`gap-x-1.5 gap-y-0`,fl=x(),pl=Sn.kind===`primary`&&An&&!fl&&!Pt,ml=Z.useMemo(()=>(At?.selectedProjectId?Ln.find(e=>e.id===At.selectedProjectId)??null:null)||(zn?Ln.find(e=>e.id===zn)??null:null)||(Ln[0]??null),[zn,At?.selectedProjectId,Ln]),hl=Z.useMemo(()=>Uw(ml?.path??null),[ml?.path]),gl=ml?Ww(ml):null,_l=Fc(hl),vl=Tc(e=>hl?e.directories.get(hl)?.lastBranchesFetch??0:0),yl=Vc(hl),bl=!!_l?.all,Sl=Tc(e=>e.fetchBranches),[Cl,wl]=Z.useState(!1);Z.useEffect(()=>{!pl||!hl||!Ri||yl!==null||aa(hl,Ri,{silent:!0})},[aa,Ri,yl,hl,pl]),Z.useEffect(()=>{if(!pl||!hl||!ml||!Ri||yl!==!0){wl(!1);return}let e=!vl||Date.now()-vl>3e4;if(bl&&!e){wl(!1);return}let t=!1;return wl(!bl),Sl(hl,Ri).finally(()=>{t||wl(!1)}),()=>{t=!0}},[Sl,Ri,ml,vl,bl,yl,hl,pl]);let Tl=Dc(hl),El=_l?.current?.trim()||Tl?.trim()||``,Dl=Z.useMemo(()=>{if(!ml)return null;let e=Uw(ml.path);return!e||!El?null:{value:e,label:El}},[ml,El]),Ol=Z.useMemo(()=>{if(!ml)return[];let e=hl?Vt.get(hl)??Vt.get(ml.path)??[]:[];return Vi({projectRoot:Uw(ml.path)??``,rootBranch:El,worktrees:e,pendingBootstrapDirectory:At?.bootstrapPendingDirectory??null}).filter(e=>e.kind===`worktree`)},[Vt,At?.bootstrapPendingDirectory,ml,El,hl]),kl=Z.useMemo(()=>Uw(At?.bootstrapPendingDirectory??null)??Uw(At?.directoryOverride??null)??hl,[At?.bootstrapPendingDirectory,At?.directoryOverride,hl]),Al=Z.useMemo(()=>{let e=Uw(At?.bootstrapPendingDirectory??null);return!!(At?.preserveDirectoryOverride||At?.pendingWorktreeRequestId||e&&e===kl)},[At?.bootstrapPendingDirectory,At?.pendingWorktreeRequestId,At?.preserveDirectoryOverride,kl]),jl=Z.useMemo(()=>{let e=[];return Dl&&e.push(Dl),e.push(...Ol),!kl||e.some(e=>e.value===kl)||!Al?e:[...e,{value:kl,label:_o(kl)}]},[Dl,kl,Al,Ol]),Ml=Z.useMemo(()=>qx({selectedDirectory:kl,projectRootOption:Dl,worktreeOptions:Ol}),[Dl,kl,Ol]),Nl=Cb()===`mini-chat`,Pl=Z.useMemo(()=>Nl||ta!==!0||!na||na.isClean?!1:cb(na.files),[na,ta,Nl]),Fl=Z.useMemo(()=>!kl||Dl?.value===kl||Ol.some(e=>e.value===kl),[Dl?.value,kl,Ol]);Z.useEffect(()=>{At?.open&&(!At.preserveDirectoryOverride&&!At.bootstrapPendingDirectory||!kl||!Fl||(At.preserveDirectoryOverride&&J.getState().setDraftPreserveDirectoryOverride(!1),At.bootstrapPendingDirectory&&J.getState().setDraftBootstrapPendingDirectory(null)))},[At?.bootstrapPendingDirectory,At?.open,At?.preserveDirectoryOverride,Fl,kl]);let Il=Z.useMemo(()=>yl!==!0||Cl?!1:Dl?!0:Ol.length>0,[Cl,Dl,yl,Ol.length]),Ll=Z.useCallback(e=>{if(J.getState().newSessionDraft?.pendingWorktreeRequestId)return;let t=Ln.find(t=>t.id===e);t&&(zn!==e&&Bn(e),Bt({projectId:e,directoryOverride:t.path},{force:!0}))},[zn,Ln,Bn,Bt]),Rl=Z.useCallback(e=>{J.getState().newSessionDraft?.pendingWorktreeRequestId||ml&&Bt({projectId:ml.id,directoryOverride:e},{force:!0})},[ml,Bt]),zl=Z.useCallback(e=>{let t=e.icon?Lo[e.icon]:null,n=e.color?Vo[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)(No,{project:e,className:`size-full object-contain`,fallback:r}):r}),(0,$.jsx)(`span`,{className:`truncate`,children:Ww(e)})]})},[]);Z.useEffect(()=>{!pl||!ml||!kl||At?.pendingWorktreeRequestId||At?.bootstrapPendingDirectory||At?.preserveDirectoryOverride||jl.some(e=>e.value===kl)||Bt({projectId:ml.id,directoryOverride:ml.path})},[jl,At?.bootstrapPendingDirectory,At?.pendingWorktreeRequestId,At?.preserveDirectoryOverride,kl,ml,Bt,pl]);let Bl=Z.useCallback(()=>{Re(),he(!0),di.current?.blur()},[Re]),Vl=Z.useCallback(()=>{Re(),Se(!0),di.current?.blur()},[Re]);Z.useEffect(()=>{if(!_r||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=()=>Ie(Hb(t.children));n();let r=new MutationObserver(n);return r.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[Vb]}),()=>r.disconnect()},[_r]);let Hl=Fe||!!ae||me||_e||eo||no,Wl=io(mr.find(e=>e.id===Sn.selection.value.providerID),Sn.selection.value.modelID,l(`chat.modelControls.selectModel`)),Gl=Sn.selection.value.variant?.trim(),Kl=q(e=>{W(t=>fc(t,e.rows)),G(t=>t===e.highlightedIndex?t:e.highlightedIndex)}),ql=q(e=>Vv(Sn,e)),Jl=q(e=>{if(E){Oi.current?.acceptIndex(e,!0);return}if(I){ki.current?.acceptIndex(e);return}S&&Ei.current?.acceptIndex(e)}),Yl=q(()=>{mi.current=null,D(!1),L(!1),V(!1),C(!1),W([]),G(0)}),Xl=Ep({enabled:_r&&Sn.kind===`primary`,isMobile:_r,text:Hr,textPresetEpoch:zr.textPresetEpoch,placeholder:Sa,modelLabel:Wl,modelVariantLabel:Gl?Gn(Gl):``,canSend:es,canAbort:rs,attachmentCount:Tn.length,suppressed:Hl,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:Sn.selection.value.modelID,providerId:Sn.selection.value.providerID,agentName:Sn.selection.value.agent??``,agentLabel:rr(pr,Sn.selection.value.agent??void 0),agentAria:l(`chat.modelControls.selectAgent`),attachments:Tn,removeAttachmentNamedAria:e=>l(`chat.fileAttachment.actions.removeNamed`,{name:e}),onText:(e,t,n)=>{let r=Yc(e.length,n?.end??n?.start??e.length);if(pi.current=r,t){di.current&&(di.current.value=e),si(e);return}let i=Ni.current,a=ut(i,e,Tn.filter(xt).map(e=>e.filename)),o=a?.text??e;di.current&&(di.current.value=o),si(o);let s=Yc(o.length,n?.end??n?.start??o.length);if(pi.current=s,Js(o,s),!a)return;let c=new Set(a.removedFilenames.map(e=>e.toLowerCase()));for(let e of Tn)c.has(e.filename.toLowerCase())&&wn.removeAttachment(e.id)},onSend:e=>{di.current&&(di.current.value=e),tl({text:e,applyDocument:si,submit:ks})},onAbort:Bs,onAttach:Re,onFiles:(e,t)=>{t.length>0&&fa.error(l(`chat.chatInput.toast.someFilesSkipped`,{summary:t.join(`
6538
6538
  `)})),e.length!==0&&il(e)},onRemoveAttachment:e=>{wn.removeAttachment(e)},onOpenModel:()=>Go(`model`),onCycleAgent:()=>Hs(),onOpenAgent:Ts,showScrollToBottom:!!(i&&a),scrollAria:l(`chat.scrollToBottom.aria`),onScrollToBottom:a??(()=>{}),autocompleteOpen:te.length>0&&(E||I||S),autocompleteHighlightedIndex:ne,autocompleteRows:te,caret:pi.current,onAutocompleteAccept:Jl,onAutocompleteDismiss:Yl,chipHighlights:qa}),Zl=Z.useRef(null);Yt(Xl?Zl:null,()=>{let e=Zl.current?.getBoundingClientRect().height??0;Qc(document.documentElement,e)});let Ql=Z.useRef(!1);Ql.current=eo||no;let $l=Z.useRef(!1),eu=Z.useRef(0),tu=Z.useRef(0),nu=q(()=>{let e=J.getState().stagedMessageEdit;!e||e.sessionId!==Dn||window.setTimeout(()=>{let t=J.getState().stagedMessageEdit,n=document.activeElement,r=sC({surfaceKind:Sn.kind,stagedSessionId:t?.sessionId??null,stagedMessageId:t?.messageId??null,blurredMessageId:e.messageId,submitInFlight:gs(),focusHeld:Date.now()<tu.current,overlayOpen:eu.current>0||Ql.current,focusInsideComposer:n instanceof Element&&!!(n.closest(`[data-composer-content="true"]`)||n.closest(`[data-slot="dropdown-menu-content"]`))||Date.now()<Le.current});r.action===`disarm`&&J.getState().clearStagedMessageEdit(r.sessionId)},0)});Z.useEffect(()=>{if(!_r||wt()||typeof window>`u`||!window.matchMedia?.(`(display-mode: standalone)`)?.matches)return;let e=()=>{eu.current+=1},t=()=>{if(eu.current=Math.max(0,eu.current-1),$l.current){$l.current=!1;return}if(!Be.current||Ql.current||eu.current>0)return;if(Ao()){Be.current=!1;return}Be.current=!1,tu.current=Date.now()+600,di.current?.focus(),document.activeElement===di.current&&de(!0);let e=()=>{let e=di.current;!e||document.activeElement!==e||(ru.current??e).scrollIntoView({block:`end`})};ce.current!==null&&(window.clearTimeout(ce.current),ce.current=null),le.current!==null&&(window.clearTimeout(le.current),le.current=null),ce.current=window.setTimeout(()=>{ce.current=null,e()},300),le.current=window.setTimeout(()=>{le.current=null,e()},650)};return window.addEventListener(`oc:mobile-overlay-opened`,e),window.addEventListener(`oc:mobile-overlay-closed`,t),()=>{ce.current!==null&&(window.clearTimeout(ce.current),ce.current=null),le.current!==null&&(window.clearTimeout(le.current),le.current=null),window.removeEventListener(`oc:mobile-overlay-opened`,e),window.removeEventListener(`oc:mobile-overlay-closed`,t)}},[_r]),Z.useEffect(()=>{if(!_r)return;if(Hl){(ue||Date.now()-ze.current<800)&&(Be.current=!0);return}if(!Be.current)return;let e=window.setTimeout(()=>{if(Be.current=!1,Ao())return;let e=di.current;e&&document.activeElement!==e&&e.focus({preventScroll:wt()})},180);return()=>window.clearTimeout(e)},[_r,Hl,ue]),Z.useEffect(()=>{if(!_r||wt()||typeof document>`u`||ue||!window.matchMedia?.(`(display-mode: standalone)`)?.matches)return;let e=document.documentElement,t=window.setTimeout(()=>{document.activeElement!==di.current&&(window.scrollTo(0,0),document.body.scrollTop=0,e.scrollTop=0)},350);return()=>window.clearTimeout(t)},[_r,ue]),Z.useEffect(()=>{ke(``)},[Ce]);let ru=Z.useRef(null),iu=_r?`px-1.5 py-1.5`:fl?`px-1.5 py-1`:`px-2.5 py-1.5`,au=_r?`h-8 w-8`:fl?`h-5 w-5`:`h-6 w-6`,ou=_r?`h-4 w-4`:fl?`h-3.5 w-3.5`:`h-4 w-4`,su=_r?`h-6 w-6`:`size-full`,cu=_r?`h-[1.125rem] w-[1.125rem]`:fl?`h-4 w-4`:`h-[1.125rem] w-[1.125rem]`,lu=Y(`flex cursor-pointer items-center justify-center text-foreground transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed`,yv),uu=Y(lu,au),du=Y(`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),fu=Y(`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(()=>()=>{$a.current&&=(clearTimeout($a.current),null)},[]);let pu=_r?(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)(Jw,{onOpenAgentPanel:Ts,onCycleAgent:()=>{Re(),Hs()},agentName:Sn.selection.value.agent,agents:pr,disabled:gr}),(0,$.jsx)(Yw,{onOpenModel:()=>Go(`model`),providerID:Sn.selection.value.providerID,modelID:Sn.selection.value.modelID,provider:mr.find(e=>e.id===Sn.selection.value.providerID),variant:Sn.selection.value.variant})]}):null,mu=(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)(Eh,{attachments:Tn,onShowPopup:Tr,onRemoveAttachedFile:Qs}),Sn.kind===`primary`?(0,$.jsx)(Ah,{attachedFiles:Tn,onAddVSCodeFile:(e,t,n)=>{Mn&&un(Mn,()=>Ja.getState()).addVSCodeFile(e,t,n)},onAddVSCodeSelection:(e,t)=>{if(Mn)return un(Mn,()=>Ja.getState()).addVSCodeSelection(e,t)}}):null]}),hu=qa?.map((e,t)=>(0,$.jsx)(`span`,{className:e.className,children:e.visual?(0,$.jsx)(bS,{visual:e.visual,text:e.text}):e.text},`${t}-${e.text.length}`)),gu=_r?(0,$.jsxs)(`div`,{className:Y(`oc-mobile-composer-compact-chrome`,rs&&`oc-mobile-composer-compact-chrome--aborting`,es&&!rs&&`oc-mobile-composer-compact-chrome--sending`,i&&a&&`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)(Qw,{isVSCode:fl,footerIconButtonClass:uu,iconSizeClass:cu,handlePickLocalFiles:ol,handlePickLocalImages:sl,openIssuePicker:Es,openPrPicker:Ds,onOpenMobileSheet:Bl,onOpenAndroidPickSheet:_p()?Vl: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:[i&&a?(0,$.jsx)(`div`,{"data-composer-action":`true`,className:`flex shrink-0 items-center`,children:(0,$.jsx)(xb,{placement:`compact`,visible:i,onClick:a})}):null,rs||es?(0,$.jsx)(`div`,{"data-mobile-composer-compact-slot":`action`,"data-composer-action":`true`,className:`flex shrink-0 items-center justify-end`,children:(0,$.jsx)(eT,{isMobile:!0,compact:!0,footerIconButtonClass:uu,stopFooterIconButtonClass:du,compactCircleButtonClass:fu,sendIconSizeClass:ou,stopIconSizeClass:su,canSend:es,canAbort:rs,hasContent:!1,currentSessionId:Dn,newSessionDraftOpen:kn,draftSubmitting:On,submissionBlocked:o,sendPhase:ps,queueFrozen:$o,queueFallbackAvailable:rs||ns,onPrimaryAction:ks,onAbort:Bs})}):null]})]}):null,_u=_r?(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)(Qw,{isVSCode:fl,footerIconButtonClass:uu,iconSizeClass:cu,handlePickLocalFiles:ol,handlePickLocalImages:sl,openIssuePicker:Es,openPrPicker:Ds,onOpenSettings:e,onOpenMobileSheet:Bl,onOpenAndroidPickSheet:_p()?Vl:void 0}),er?(0,$.jsx)($w,{sessionId:Dn,draftOpen:kn,draftEnabled:At.permissionAutoAcceptEnabled===!0,enabled:qn,saving:Dn?Rt:!1,footerIconButtonClass:uu,iconSizeClass:cu,onSetDraftEnabled:It,onSetSessionEnabled:zt,onOpenSessionFirst:Ft,onToggleFailed:tr}):null,(0,$.jsx)(KS,{sessionId:Dn,directory:ot??jn,draftOpen:kn}),(0,$.jsx)(qS,{length:Hr.length})]}),pu,(0,$.jsx)(`div`,{className:`relative z-30 flex shrink-0 items-center justify-end gap-x-1.5`,children:(0,$.jsx)(eT,{isMobile:_r,footerIconButtonClass:uu,stopFooterIconButtonClass:du,sendIconSizeClass:ou,stopIconSizeClass:su,canSend:es,canAbort:rs,hasContent:!!Zo,currentSessionId:Dn,newSessionDraftOpen:kn,draftSubmitting:On,submissionBlocked:o,sendPhase:ps,queueFrozen:$o,queueFallbackAvailable:rs||ns,onPrimaryAction:ks,onAbort:Bs})})]})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:Y(`flex flex-shrink-0 items-center`,dl),children:[(0,$.jsx)(Qw,{isVSCode:fl,footerIconButtonClass:uu,iconSizeClass:cu,handlePickLocalFiles:ol,handlePickLocalImages:sl,openIssuePicker:Es,openPrPicker:Ds,onOpenSettings:e,withTooltip:!0}),er?(0,$.jsx)($w,{sessionId:Dn,draftOpen:kn,draftEnabled:At.permissionAutoAcceptEnabled===!0,enabled:qn,saving:Dn?Rt:!1,footerIconButtonClass:uu,iconSizeClass:cu,onSetDraftEnabled:It,onSetSessionEnabled:zt,onOpenSessionFirst:Ft,onToggleFailed:tr}):null,(0,$.jsx)(KS,{sessionId:Dn,directory:ot??jn,draftOpen:kn}),(0,$.jsx)(qS,{length:Hr.length})]}),(0,$.jsxs)(`div`,{className:Y(`relative z-30 flex flex-1 items-center justify-end md:gap-x-1.5`,dl),children:[(0,$.jsx)(Kw,{className:`min-w-0 flex-1 justify-end`,composerTextareaRef:di,selectionAdapter:or}),(0,$.jsx)(qw,{radius:ba,isMobile:_r,footerIconButtonClass:uu,footerPaddingClass:iu,iconSizeClass:cu,sendIconSizeClass:ou,onInsert:js,onInsertAndSend:Ms,onContentHeightChange:Ks,renderTrigger:!1,topAccessory:(0,$.jsx)(`span`,{"data-oc-composer-dictation-active":`true`,className:`hidden`,"aria-hidden":`true`})}),(0,$.jsx)(eT,{isMobile:_r,footerIconButtonClass:uu,stopFooterIconButtonClass:du,sendIconSizeClass:ou,stopIconSizeClass:su,canSend:es,canAbort:rs,hasContent:!!Zo,currentSessionId:Dn,newSessionDraftOpen:kn,draftSubmitting:On,submissionBlocked:o,sendPhase:ps,queueFrozen:$o,queueFallbackAvailable:rs||ns,onPrimaryAction:ks,onAbort:Bs})]})]}),vu=q(()=>{if(_r){tu.current=Date.now()+600;let e=()=>{di.current?.focus({preventScroll:wt()}),document.activeElement===di.current&&de(!0)};e(),window.requestAnimationFrame(e);return}let e=()=>{if(!Iv(di))return;let e=Fv(di);if(!e)return;let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}};e(),window.requestAnimationFrame(()=>{e(),window.setTimeout(e,0)})}),yu=ot??jn,{goal:bu,enabled:xu}=BS(Dn??``,yu),Su=(0,$.jsx)(D_,{onEditMessage:Cs,onSendMessage:ws,onEditCommitted:vu,draftKey:Mn,scope:uo,draftTarget:Mn?{key:Mn,expectedRevision:()=>wn.getDraft(Mn)?.revision??`absent`}:null,clientPendingItems:vs,onRemoveClientPending:e=>{let t=dr.getState().removeEstablishingFollowUp(e);t&&(t.content&&Wr(t.content),t.attachments.length>0&&wn.restoreAttachments(t.attachments))},trailing:Dn&&xu&&bu?(0,$.jsx)(GS,{sessionId:Dn,directory:yu}):null});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`form`,{ref:ru,onSubmit:e=>{e.preventDefault(),ks()},onPointerDownCapture:e=>{if(!_r)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"]`)&&(Re(),e.preventDefault()))},className:Y(`relative w-full pt-0 pb-4`,ga&&`flex h-full min-h-0 flex-col pt-4`,_a&&`flex h-full min-h-0 flex-col pt-1`,_r&&`bottom-safe-area oc-mobile-composer`),"data-native-ios-composer":Xl?`true`:void 0,style:_r&&wt()&&!Xl&&Mr>0&&!ue?{marginBottom:`${Mr}px`}:void 0,children:[An&&!ga&&!_r&&!fl&&!Nl?(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:Gw(gl?l(`chat.emptyState.draftTitleWithProject`,{project:gl}):l(`chat.emptyState.draftTitle`),gl)})}):null,(0,$.jsxs)(`div`,{className:Y(`chat-input-column relative overflow-visible`,ya&&`flex flex-1 min-h-0 flex-col`),children:[Xl?null:(0,$.jsx)(Dh,{attachments:Tn,onShowPopup:Tr,onRemoveAttachedFile:Qs}),(0,$.jsx)(G_,{}),To&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 pb-2`,children:[Oo>0?(0,$.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 rounded-xl border px-2.5 py-1`,style:{backgroundColor:Zi?.colors?.surface?.elevated,borderColor:Zi?.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:Zi?.colors?.status?.info},children:Oo}),(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:jo,"aria-label":l(`chat.chatInput.reviewCommentsRemove`),title:l(`chat.chatInput.reviewCommentsRemove`),children:(0,$.jsx)(X,{name:`close`,className:`h-3 w-3`})})]}):null,Eo>0?(0,$.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 rounded-xl border px-2.5 py-1`,style:{backgroundColor:Zi?.colors?.surface?.elevated,borderColor:Zi?.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:Zi?.colors?.status?.info},children:Eo}),(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:()=>ko(`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,Do>0?(0,$.jsxs)(`div`,{className:`inline-flex items-center gap-1.5 rounded-xl border px-2.5 py-1`,style:{backgroundColor:Zi?.colors?.surface?.elevated,borderColor:Zi?.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:Zi?.colors?.status?.info},children:Do}),(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:()=>ko(`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]}),ao&&!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:()=>to(!0),className:`flex min-w-0 flex-1 items-center gap-1.5 text-left hover:opacity-80 transition-opacity`,children:[ao.author?.avatarUrl&&(0,$.jsx)(`img`,{src:ao.author.avatarUrl,alt:ao.author.login,className:`h-5 w-5 rounded-full flex-shrink-0`}),(0,$.jsxs)(`span`,{className:`text-muted-foreground flex-shrink-0`,children:[`#`,ao.number,ao.author&&(0,$.jsx)(`span`,{className:`ml-1`,children:l(`chat.chatInput.linked.byAuthor`,{author:ao.author.login})})]}),(0,$.jsx)(`span`,{className:`text-foreground truncate`,children:ao.title})]}),(0,$.jsxs)(`span`,{className:`flex items-center gap-0.5 flex-shrink-0`,children:[(0,$.jsx)(`a`,{href:ao.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:()=>{oo(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`})})]})]})}),so&&!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:()=>ro(!0),className:`flex min-w-0 flex-1 items-center gap-1.5 text-left hover:opacity-80 transition-opacity`,children:[so.author?.avatarUrl&&(0,$.jsx)(`img`,{src:so.author.avatarUrl,alt:so.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:so.number}),so.author&&(0,$.jsx)(`span`,{className:`ml-1`,children:l(`chat.chatInput.linked.byAuthor`,{author:so.author.login})})]}),(0,$.jsx)(`span`,{className:`text-foreground truncate`,children:so.title}),(0,$.jsxs)(`span`,{className:`text-muted-foreground flex-shrink-0 typography-meta`,children:[so.head,` → `,so.base]})]}),(0,$.jsxs)(`span`,{className:`flex items-center gap-0.5 flex-shrink-0`,children:[(0,$.jsx)(`a`,{href:so.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:()=>{co(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)(Zw,{sessionId:Dn,directory:ot??jn}),(0,$.jsxs)(`div`,{className:_r?`relative oc-mobile-composer-stack`:`contents`,children:[(0,$.jsxs)(`div`,{className:_r?`oc-mobile-composer-expanded-layer`:`contents`,children:[(0,$.jsx)(`div`,{className:_r?`oc-mobile-composer-reveal`:`contents`,children:(0,$.jsxs)(`div`,{ref:Zl,"data-native-composer-accessories":`true`,children:[(0,$.jsx)(Xw,{showAbortStatus:oa,showAbortPrompt:!!(ga&&Dn&&Ht===Dn&&typeof Ut==`number`&&Ut>Date.now()),showAssistantStatus:!1,showTodos:!0,leftAccessory:kn||!Pl?null:(0,$.jsx)(yb,{})}),!_r&&pl?(0,$.jsxs)(`div`,{className:`mb-1.5 flex min-w-0 items-center gap-1.5 px-0.5`,children:[ml?(0,$.jsxs)(Bo,{value:ml.id,open:Me,onValueChange:Ll,onOpenChange:e=>{Pe(e),e||je(``)},children:[(0,$.jsx)(Po,{asChild:!0,size:`sm`,children:(0,$.jsxs)(`button`,{type:`button`,className:Y(`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]`,_v),children:[(0,$.jsx)(qo,{children:zl(ml)}),(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)(Io,{fitContent:!0,children:[(0,$.jsx)(Yo,{autoFocus:!0,value:Ae,onChange:e=>je(e.target.value),onKeyDown:e=>e.stopPropagation(),placeholder:l(`chat.chatInput.draftPicker.searchProjects`),className:`mb-1 h-8 min-w-56`}),Ln.filter(e=>Co(Ww(e),Ae)||Co(e.path,Ae)).map(e=>(0,$.jsx)(Mo,{value:e.id,className:`max-w-[24rem] truncate`,children:zl(e)},e.id)),(0,$.jsx)(Jo,{}),(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(),Pe(!1),requestAnimationFrame(()=>ni.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:Y(`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`,_v),onClick:()=>ni.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`)})]}),ml&&Il?(0,$.jsx)(eS,{directory:kl,projectDirectory:hl,label:Ml,projectRootOption:Dl,worktreeOptions:Ol,onSelectDirectory:Rl}):null]}):null,_r&&pl?(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:[ml?(0,$.jsx)(`button`,{type:`button`,className:Y(`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`,_v),onClick:()=>we(`project`),children:zl(ml)}):(0,$.jsxs)(`button`,{type:`button`,className:Y(`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`,_v),onClick:()=>ni.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`)})]}),ml&&Il?(0,$.jsx)(eS,{directory:kl,projectDirectory:hl,label:Ml,projectRootOption:Dl,worktreeOptions:Ol,onSelectDirectory:Rl,maxWidthClassName:`max-w-[50%]`,presentation:`mobile-sheet`}):null]}):null,Su]})}),(0,$.jsx)(`div`,{className:Y(!_r&&`contents`,_r&&`contents`,_a&&`flex min-h-0 flex-1 flex-col`),children:(0,$.jsxs)(`div`,{className:_r?`oc-mobile-composer-motion-viewport`:`contents`,children:[(0,$.jsxs)(Au,{value:Hr,attachments:[],disabled:!Dn&&!kn||On&&!ps.establishing,pending:rs||ps.inFlight&&!ps.establishing,isMobile:_r,onSubmit:ks,"data-mobile-composer-surface":_r?`true`:void 0,"data-session-swipe-surface":_r?`true`:void 0,expanded:ya,focusedTone:p===`shell`?`info`:`primary`,className:Y(`relative z-10`,h&&`ring-2 ring-primary ring-offset-2`,jr&&`ring-1 ring-[var(--interactive-selection)] border-[var(--interactive-selection)]`,_r&&`oc-mobile-composer-surface`),style:{borderRadius:ba},ref:vi,onDropCapture:Zc,onDragEnter:Wc,onDragOver:Gc,onDragLeave:qc,onDrop:Xc,onDragEnd:Jc,autoResize:!1,disableInputWhilePending:!1,contentClassName:ya?`flex-1 min-h-0`:void 0,inputHeader:void 0,attachmentContent:mu,highlightedContent:hu,highlightRef:la,inputRef:di,textLayoutClassName:Y(Cw,ya?Y(`h-full min-h-0`,_r?`py-2.5`:`py-4`):_r?`py-2.5`:`pt-4 pb-2`,p===`shell`?`font-mono`:`typography-markdown md:typography-ui-label`),inputOuterClassName:Y(ya&&`flex-1 min-h-0`),inputStyle:{flex:ya?`1 1 auto`:`none`,height:!ya&&K?`${K.height}px`:void 0,maxHeight:!ya&&K?`${K.maxHeight}px`:void 0,"--oc-composer-textarea-resting-height":ya?`100%`:K?`${K.height}px`:`auto`,"--oc-composer-textarea-resting-max-height":!ya&&K?`${K.maxHeight}px`:`none`,borderTopLeftRadius:ba,borderTopRightRadius:ba},footerClassName:Y(`z-30 bg-transparent flex-shrink-0`,iu,_r?`flex items-center gap-x-1.5`:Y(`flex items-center justify-between`,dl)),footerStyle:{borderBottomLeftRadius:ba,borderBottomRightRadius:ba},footerContent:_u,placeholder:xa,onChange:(e,t)=>ac(t),textareaProps:{readOnly:jr,onCompositionStart:()=>{fi.current=!0},onCompositionEnd:e=>{fi.current=!1;let t=e.currentTarget;Ys(t.value,t.selectionStart??t.value.length,t.selectionEnd??t.selectionStart??t.value.length)},onBeforeInput:rc,onKeyDown:Is,onCopy:pc,onCut:mc,onPaste:sc,onDragEnter:Wc,onDragOver:Gc,onDropCapture:Zc,onDrop:Xc,onDragEnd:Jc,onKeyUp:Rs,onClick:()=>{Rs()},onScroll:e=>{Rs();let t=e.currentTarget.scrollTop;la.current&&(la.current.style.transform=`translateY(-${t}px)`)},onSelect:e=>{let t=e.currentTarget,n=t.selectionStart??0,r=t.selectionEnd??n;if(fi.current){pi.current=r;return}let i=_S(n,r,[...ft(Hr,Tn.filter(xt).map(e=>e.filename)),...gS(Hr,La.keys()),...Br.references]);i&&(i.start!==n||i.end!==r)?(t.setSelectionRange(i.start,i.end),pi.current=i.end):pi.current=n,Rs()},onFocus:()=>{if(_r){if(Date.now()<Le.current){let e=di.current;e&&e.blur();return}pe.current!==null&&(window.clearTimeout(pe.current),pe.current=null),de(!0)}},onBlur:e=>{if(fi.current=!1,pi.current=e.currentTarget.selectionStart??pi.current,nu(),_r){if(Date.now()<tu.current){let e=di.current;if(e){e.focus(),window.setTimeout(()=>{Date.now()<tu.current&&document.activeElement!==e&&e.focus()},50);return}}if(ze.current=Date.now(),wt()){de(!1);return}pe.current!==null&&window.clearTimeout(pe.current),pe.current=window.setTimeout(()=>{pe.current=null,de(!1)},120)}},autoCorrect:_r?`on`:`off`,autoCapitalize:_r?`sentences`:`off`,spellCheck:_r||Fr,fillContainer:ya,rows:1},children:[(0,$.jsx)(gy,{}),h&&(0,$.jsx)(`div`,{className:`absolute inset-0 z-50 flex items-center justify-center bg-background/90`,style:{borderRadius:ba},children:(0,$.jsxs)(`div`,{className:`text-center`,children:[(0,$.jsx)(`div`,{className:`inline-flex justify-center`,children:(0,$.jsx)(`button`,{type:`button`,className:lu,onClick:()=>ol(),title:l(`chat.chatInput.actions.attachFiles`),"aria-label":l(`chat.chatInput.actions.attachFiles`),children:(0,$.jsx)(X,{name:`attachment-2`,className:Y(cu,`text-current`)})})}),(0,$.jsx)(`p`,{className:`mt-2 typography-ui-label text-muted-foreground`,children:l(y?`chat.chatInput.drop.insertMention`:`chat.chatInput.drop.attachFiles`)})]})}),E&&(0,$.jsx)(dc,{ref:Oi,searchQuery:A,directory:jn,onCommandSelect:Mc,onClose:()=>D(!1),commandPolicy:ql,commandContext:Pn,onRowsChange:Xl?Kl:void 0,style:ga&&Xa?{left:`${Xa.left}px`,top:`${Xa.top}px`,bottom:`auto`,width:`min(450px, calc(100% - ${Xa.left+8}px))`,maxHeight:`${Xa.maxHeight}px`,transform:Xa.place===`above`?`translateY(-100%)`:void 0}:void 0}),I&&(0,$.jsx)(X_,{ref:ki,searchQuery:R,directory:jn,onSkillSelect:kc,onClose:()=>L(!1),onRowsChange:Xl?Kl:void 0,style:ga&&Xa?{left:`${Xa.left}px`,top:`${Xa.top}px`,bottom:`auto`,width:`min(360px, calc(100% - ${Xa.left+8}px))`,maxHeight:`${Xa.maxHeight}px`,transform:Xa.place===`above`?`translateY(-100%)`:void 0}:void 0}),B&&(0,$.jsx)(xc,{ref:Ai,searchQuery:H,onSnippetSelect:jc,onClose:()=>V(!1),style:ga&&Xa?{left:`${Xa.left}px`,top:`${Xa.top}px`,bottom:`auto`,width:`min(450px, calc(100% - ${Xa.left+8}px))`,maxHeight:`${Xa.maxHeight}px`,transform:Xa.place===`above`?`translateY(-100%)`:void 0}:void 0}),S&&(0,$.jsx)(Ac,{ref:Ei,searchQuery:w,onFileSelect:bc,onAgentSelect:Sc,onSessionSelect:wc,onClose:()=>C(!1),onRowsChange:Xl?Kl:void 0,style:ga&&Xa?{left:`${Xa.left}px`,top:`${Xa.top}px`,bottom:`auto`,width:`min(520px, calc(100% - ${Xa.left+8}px))`,maxHeight:`${Xa.maxHeight}px`,transform:Xa.place===`above`?`translateY(-100%)`:void 0}:void 0})]}),_r?(0,$.jsx)(qw,{radius:ba,isMobile:_r,footerIconButtonClass:uu,footerPaddingClass:iu,iconSizeClass:cu,sendIconSizeClass:ou,onInsert:js,onInsertAndSend:Ms,onContentHeightChange:Ks,renderTrigger:!1,topAccessory:(0,$.jsx)(`span`,{"data-oc-composer-dictation-active":`true`,className:`hidden`,"aria-hidden":`true`})}):null]})})]}),_r?(0,$.jsxs)(`div`,{className:`oc-mobile-composer-compact-layer`,"data-oc-composer-compact-surface":`true`,children:[gu,(0,$.jsx)(`div`,{className:Y(`oc-mobile-composer-compact-preview`,!Hr.trim()&&`oc-mobile-composer-compact-preview--placeholder`),"aria-hidden":`true`,children:Hr.trim()?Hr:Sa})]}):null]}),_r?(0,$.jsx)(Kw,{className:`hidden`,composerTextareaRef:di,selectionAdapter:or,mobilePanel:ae,onMobilePanelChange:oe}):null]}),kn&&!ga&&!_r&&!fl&&!Nl?(0,$.jsx)(jx,{onSubmit:As,className:`chat-input-column mt-4`}):null]}),d.open?(0,$.jsx)(Z.Suspense,{fallback:null,children:(0,$.jsx)(ww,{popup:d,onOpenChange:Er,isMobile:_r})}):null,(0,$.jsx)(cx,{open:eo,onOpenChange:to,mode:`select`,onSelect:e=>{oo(e),co(null)}}),(0,$.jsx)(dx,{open:no,onOpenChange:ro,onSelect:e=>{co(e),oo(null)}}),(0,$.jsx)($m,{open:Vn,onOpenChange:Un,projectDirectory:ot??jn??null,submitting:Wn,onConfirm:ha}),(0,$.jsx)(`input`,{ref:$c,type:`file`,multiple:!0,className:`hidden`,onChange:ul,accept:`*/*`}),(0,$.jsx)(`input`,{ref:el,type:`file`,multiple:!0,className:`hidden`,onChange:ul,accept:`image/*`}),null,_r?(0,$.jsx)(Ro,{id:`android-media-pick-sheet`,open:_e,onOpenChange:e=>{e||Se(!1)},title:(0,$.jsx)(`h2`,{className:`truncate typography-ui-label font-semibold`,children:l(`chat.chatInput.actions.addAttachment`)}),ariaLabel:l(`chat.chatInput.actions.addAttachment`),closeAriaLabel:l(`mobile.surface.closeAria`),resizeAriaLabel:l(`mobile.sessions.sheet.resizeAria`),fitContent:!0,children:(0,$.jsx)(`div`,{className:`flex min-h-0 flex-col overflow-y-auto overscroll-contain px-3 pb-3`,children:(0,$.jsxs)(`div`,{className:`overflow-hidden rounded-2xl bg-[var(--surface-muted)]`,"data-page-scroll-lock":`true`,children:[(0,$.jsxs)(yo,{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`,onClick:()=>{Be.current=!1,Se(!1),requestAnimationFrame(ll)},children:[(0,$.jsx)(X,{name:`file-image`,className:`size-5 flex-shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`truncate`,children:l(`chat.chatInput.actions.attachPhotos`)})]}),(0,$.jsxs)(yo,{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`,onClick:()=>{Be.current=!1,Se(!1),requestAnimationFrame(ol)},children:[(0,$.jsx)(X,{name:`attachment-2`,className:`size-5 flex-shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`truncate`,children:l(`chat.chatInput.actions.attachFiles`)})]})]})})}):null,_r&&pl&&ml?(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(Ro,{id:`mobile-draft-project-picker-sheet-${Te}`,open:Ce===`project`,onOpenChange:e=>{e||we(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)(Yo,{value:Oe,onChange:e=>ke(e.target.value),placeholder:l(`chat.chatInput.draftPicker.searchProjects`),className:`h-9`})}),(0,$.jsx)(xl,{outerClassName:`min-h-0 flex-1`,disableHorizontal:!0,children:(0,$.jsx)(`div`,{className:`flex flex-col px-3 pb-2`,children:Ln.filter(e=>Co(Ww(e),Oe)||Co(e.path,Oe)).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:()=>{Ll(e.id),we(null)},children:[(0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:zl(e)}),e.id===ml.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:()=>{we(null),ni.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]})},oT=e=>{let t=(0,Q.c)(3),n=Uv(),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)(aT,{...e,surface:i}),t[0]=e,t[1]=i,t[2]=a):a=t[2],a};oT.displayName=`ChatInput`;var sT=Z.memo(oT);function cT(e){return e.preventDefault()}function lT(e){e.preventDefault()}function uT(e){return e.preventDefault()}function dT(e){e.pointerType===`touch`&&e.preventDefault()}function fT(e){e.preventDefault()}function pT(e){e.pointerType===`touch`&&e.preventDefault()}function mT(){let e=(0,Q.c)(47),{t}=Zt(),[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=()=>Js(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],rl(p);let m;e[8]!==i||e[9]!==t||e[10]!==n?(m=async()=>{if(!(!n||i)){a(!0);try{await Eu(n),fa.success(t(`chat.image.actions.saveSuccess`)),r(null)}catch(e){let n=e;if(n instanceof DOMException&&n.name===`AbortError`){a(!1);return}fa.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=wt()?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)(yo,{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)(Ro,{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 hT=(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(Ui(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]},gT=(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},_T=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}},vT=e=>e.syncLoading||e.assistantLoading,yT=e=>e.isMobile&&(e.canLoadEarlier||e.isLoadingOlder),bT=e=>e.isLoadingOlder,xT=e=>!e.isMobile&&e.isLoadingOlder,ST=e=>e.transcriptMessageCount>0||e.pendingUserCount>0||e.historyPrefixCount>0,CT=e=>e.hasTranscriptShell||e.hasBusyShell||e.hasImmediateShell||e.hasPaintedTranscript?`pass`:e.prefetchStatus===`loading`||e.syncLoading||e.userRetrying?`hydrating`:e.prefetchStatus===`error`?`load-error`:e.hasRenderableSessionSnapshot?`pass`:`hydrating`,wT=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}},TT=e=>({newSessionDraft:e?.features?.newSessionDraft??!e,promptNavigator:e?.features?.promptNavigator??!e,returnToParent:e?.features?.returnToParent??!e}),ET=`text-[13px] leading-4 sm:text-[length:var(--text-micro)] sm:leading-5`,DT=`relative bottom-safe-area oc-mobile-readonly-prompt-foot`,OT=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)(Do,{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},kT=e=>{let t=(0,Q.c)(42),{t:n}=Zt(),r=g(AT),i=`agentName`in e||`providerId`in e||`modelId`in e||`modelName`in e;if(!i){let e=r&&DT,i;t[0]===e?i=t[1]:(i=Y(`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 ${ET}`,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&&DT,h;t[18]===m?h=t[19]:(h=Y(`shrink-0 border-t border-border/70 bg-[var(--surface-background)] p-3`,m),t[18]=m,t[19]=h);let _=r&&`oc-mobile-readonly-prompt-surface`,v;t[20]===_?v=t[21]:(v=Y(`rounded-2xl border border-border/70 bg-[var(--surface-elevated)] px-3 py-2.5 sm:px-4 sm:py-3`,_),t[20]=_,t[21]=v);let y;t[22]===n?y=t[23]:(y=n(`chat.container.readOnlySubagentPromptBanner`),t[22]=n,t[23]=y);let b;t[24]===y?b=t[25]:(b=(0,$.jsx)(`div`,{className:`text-muted-foreground ${ET}`,children:y}),t[24]=y,t[25]=b);let x;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?(x=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)(vo,{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)(OT,{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]=x):x=t[34];let S;t[35]!==x||t[36]!==v||t[37]!==b?(S=(0,$.jsxs)(`div`,{className:v,children:[b,x]}),t[35]=x,t[36]=v,t[37]=b,t[38]=S):S=t[38];let C;return t[39]!==S||t[40]!==h?(C=(0,$.jsx)(`aside`,{className:h,children:S}),t[39]=S,t[40]=h,t[41]=C):C=t[41],C};function AT(e){return e.isMobile}var jT=Z.memo(()=>{let e=(0,Q.c)(5),{t}=Zt(),{currentTheme:n}=Vs(),r=zr(MT),i=n?.colors?.surface?.mutedForeground||`var(--muted-foreground)`,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(Ps,{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 MT(e){return e.error}var NT=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)}}},PT=e=>{if(!e?.trim())return null;let t=e.trim();return t.toLowerCase()==="default"?null:Gn(t)},FT=Z.memo(e=>{let t=(0,Q.c)(31),{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?PT(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=Y(`mb-1.5`),p=Y(`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)(Do,{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(${uo(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=Y(`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]!==r||t[23]!==n?(x=!n&&o&&(0,$.jsxs)(`div`,{className:Y(`agent-badge inline-flex items-center gap-1 cursor-default rounded font-normal leading-tight`,r?`px-1 py-px text-[10px]`:`px-1.5 py-0.5 typography-micro`,uo(o).class),children:[(0,$.jsx)(vo,{name:o,size:10}),(0,$.jsx)(`span`,{children:o.charAt(0).toUpperCase()+o.slice(1)})]}),t[21]=o,t[22]=r,t[23]=n,t[24]=x):x=t[24];let S;t[25]!==b||t[26]!==x?(S=(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[b,x]}),t[25]=b,t[26]=x,t[27]=S):S=t[27];let C;return t[28]!==S||t[29]!==m?(C=(0,$.jsx)(`div`,{className:f,children:(0,$.jsx)(`div`,{className:p,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[m,S]})})}),t[28]=S,t[29]=m,t[30]=C):C=t[30],C}),IT=/(^|\s)\/([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)/g,LT=/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g,RT=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#x27;`),zT=(e,t)=>e.split(LT).map((e,n)=>n%2==1?e:t(e)).join(``),BT=e=>zT(e,e=>e.replace(/ *\n/g,`
6539
6539
  `)),VT=({textContent:e,agentMention:t,skillNames:n,decorateInlineReferences:r=!0})=>{let i=zT(e,RT);if(r){if(t?.token&&i.includes(t.token)){let e=`[${t.token}](${Gl(t.name)})`;i=i.replace(t.token,e)}i=i.replace(IT,(e,t,r)=>n.has(r)?`${t}[/${r}](${Zl(r)})`:e)}return BT(i)},HT=e=>(IT.lastIndex=0,IT.test(e)||e.includes(`[skill:`)),UT=e=>e===`markdown`?`markdown`:`plain`,WT=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)},GT=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,c]=Z.useState(!1),[l,u]=Z.useState(!1),d=g(e=>e.userMessageRenderingMode),f=g(e=>e.collapsibleUserMessages),p=Ul(),m=an({directory:p,enabled:HT(o)}),h=Z.useMemo(()=>m.data??[],[m.data]),_=g(e=>e.openContextFile),{t:v}=Zt(),y=UT(d),b=f&&!s,x=Z.useRef(null),S=Z.useMemo(()=>new Map(h.map(e=>[e.name,e])),[h]),C=Z.useMemo(()=>Bg(r,o),[r,o]),w=Z.useMemo(()=>{let e=new Map;for(let t of r??[]){if(t.type!==`text`||!ir(t))continue;let n=t.text;if(typeof n==`string`)for(let t of Bi(n))e.set(t.id,{sessionId:t.id,sessionLabel:t.title||t.id})}if(o.includes(`@`))for(let[t,n]of wr()){let r=typeof n.title==`string`?n.title.trim():``;!r||e.has(t)||(o.includes(`@${r}`)||o.includes(`@${ye}${r}`))&&e.set(t,{sessionId:t,sessionLabel:r})}return Array.from(e.values())},[r,o]),T=q(e=>{let t=S.get(e),n=typeof t?.path==`string`?t.path:``,r=eu(n);if(!r||r===`<built-in>`)return;let i=r.toLowerCase().endsWith(`/skill.md`)?r:`${r}/SKILL.md`,a=p||iu(``,i)||`/`,o=()=>{_(a,i)};if(p&&!tu(i,p)){Vu(i,p).then(o);return}o()});Z.useEffect(()=>{let e=x.current;if(!e)return;let t=()=>{f&&!s&&e.scrollHeight>e.clientHeight&&u(!0)};u(!1),t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[f,o,s]),Z.useEffect(()=>{f||(c(!1),u(!1))},[f]);let E=q(e=>{let t=e.target,n=(t?.closest(`[data-skill-name]`))?.dataset.skillName??ql(t?.closest(`a[href]`)?.getAttribute(`href`));if(n){e.preventDefault(),e.stopPropagation(),T(n);return}let r=x.current;r&&(WT(r)||f&&!s&&l&&c(!0))}),D=q(e=>{e.stopPropagation(),c(!1)}),O=Z.useMemo(()=>Pg(o,{skillNames:new Set(S.keys()),citationIcons:C.icons,citationDisplayNames:C.displayNames,sessionMentions:w,agentNames:n?.name?new Set([n.name.toLowerCase(),n.token.replace(/^@/,``).toLowerCase()]):void 0,allowPathHeuristics:!0}),[n,C,w,S,o]),k=Z.useMemo(()=>VT({textContent:o,agentMention:n,skillNames:new Set(S.keys()),decorateInlineReferences:!O}),[n,O,S,o]),A=(e,t)=>{if(!e)return null;if(y===`markdown`){let n=VT({textContent:e,skillNames:new Set,decorateInlineReferences:!1});return(0,$.jsx)(_l,{content:n,className:Y(`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`,b&&[`[&_.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)},j=e=>e.map((e,t)=>e.type===`text`?A(e.text,`text-${t}`):(0,$.jsx)(Hg,{decoration:e.decoration,onOpenSkill:T},`ref-${t}-${e.span.start}`)),M=Z.useMemo(()=>{if(O)return j(O);let e=[],t=0,r=!1,i;for(IT.lastIndex=0;(i=IT.exec(o))!==null;){let n=i[1]||``,r=i[2],a=i.index+n.length;S.has(r)&&(i.index>t&&e.push(o.slice(t,i.index)),n&&e.push(n),e.push((0,$.jsxs)(`button`,{type:`button`,className:`text-primary hover:underline`,onClick:e=>{e.stopPropagation(),T(r)},children:[`/`,r]},`skill-${a}-${r}`)),t=a+r.length+1)}t<o.length&&e.push(o.slice(t));let a=e.length>0?e:[o];return!n?.token||!o.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:Yl(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,T,O,j,S,o]);return!o||o.trim().length===0?null:(0,$.jsxs)(`div`,{className:`relative`,"data-user-message-clamp":b&&l?`true`:void 0,children:[f&&s&&(0,$.jsx)(`button`,{type:`button`,onClick:D,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":v(`chat.message.userText.collapseAria`),children:(0,$.jsx)(X,{name:`arrow-up-s`,className:`h-3.5 w-3.5`})}),(0,$.jsx)(`div`,{className:Y(`break-words font-sans typography-markdown-body`,s&&`pb-3`,y===`plain`&&`whitespace-pre-wrap`,b&&`line-clamp-10`,f&&l&&!s&&`cursor-pointer`),"data-user-message-collapse":b?`true`:void 0,ref:x,onClick:E,children:y===`markdown`?O?j(O):(0,$.jsx)(_l,{content:k,className:Y(`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,b&&[`[&_.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}):M})]},e.id||`${t}-user-text`)}),KT=[{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:Y(`inline-block align-baseline`,t),children:r.split(``).map((e,t)=>(0,Z.createElement)(Hu.span,{...n,key:e+String(t),className:Y(`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:Y(`invisible`,t),children:e}),(0,$.jsx)(`span`,{...n,className:Y(`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:Y(`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)(Hu.span,{...n,className:Y(`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)(Hu.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:Y(`absolute inset-0`),children:a.map((e,t)=>(0,$.jsx)(Hu.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:Y(`text-primary-muted hover:animate-text-shake`,t),children:e})},{variant:`hover-decoration`,component:({children:e,className:t,...n})=>(0,$.jsx)(`div`,{className:Y(`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:Y(`text-primary-muted`,t),children:e})})}];function qT(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=KT.find(e=>e.variant===a)?.component,t[4]=a,t[5]=o);let s=o||KT[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 JT=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===`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===`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===`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`?(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})},YT=new Map,XT=e=>{let t=YT.get(e);if(t)return t;let n={subscribers:new Set,timerId:null};return YT.set(e,n),n},ZT=(e,t)=>{let n=XT(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=YT.get(e);n&&(n.subscribers.delete(t),!(n.subscribers.size>0)&&(n.timerId!==null&&typeof window<`u`&&window.clearInterval(n.timerId),YT.delete(e)))}},QT=(e,t)=>{let n=(0,Q.c)(4),r=t===void 0?250:t,[i,a]=Z.useState($T),o,s;return n[0]!==e||n[1]!==r?(o=()=>{if(e)return ZT(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 $T(){return Date.now()}var eE=e=>e.match(/<task\s+id="([^"]+)"(?:\s+[^>]*)?>/i)?.[1],tE=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},nE=e=>{if(!e||typeof e!=`object`)return;let t=e;return tE(t.sessionId)??tE(t.sessionID)},rE=(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},iE=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},aE=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:tE(e.sessionId)??tE(e.sessionID),status:tE(e.status),summaryEntries:iE(e.summary??e.entries??e.tools??e.calls)}}catch{return{summaryEntries:[]}}},oE=e=>{if(typeof e!=`string`||e.trim().length===0)return;let t=aE(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 tE((n?.[1]??r?.[1])||eE(e))},sE=e=>{if(!(!e||typeof e!=`object`))return tE(e.status)},cE=/"status"\s*:\s*"running"/i,lE=/\bstatus\s*[:=]\s*["'`]?running\b/i,uE=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]&&cE.test(t[1])?!0:lE.test(e)},dE=/<subagent\s+([^>]*?)>([\s\S]*?)<\/subagent>/i,fE=(e,t)=>tE(e.match(RegExp(`${t}\\s*=\\s*"([^"]*)"`,`i`))?.[1]),pE=e=>{if(e===`completed`||e===`error`||e===`cancelled`)return e},mE=e=>{if(typeof e!=`string`||e.trim().length===0)return;let t=e.trim().match(dE);if(!t)return;let n=fE(t[1],`sessionID`)??fE(t[1],`sessionId`),r=pE(fE(t[1],`state`));if(!(!n||!r))return{sessionID:n,state:r,description:fE(t[1],`description`),body:t[2].trim()}},hE=new WeakMap,gE=e=>{let t=hE.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||e===`task`||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 hE.set(e,n),n},_E=e=>{let t=[];for(let n of e)t.push(...gE(n));return t},vE=e=>e.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,``).trimEnd(),yE=[`summary`,`changes`,`verification`],bE={summary:`Summary`,changes:`Changes`,verification:`Verification`},xE=/<(summary|changes|verification)(?:\s[^>]*)?>/i,SE=()=>RegExp(`<(${yE.join(`|`)})(?:\\s[^>]*)?>\\s*([\\s\\S]*?)\\s*<\\/\\1>`,`gi`),CE=e=>typeof e!=`string`||e.length===0?!1:xE.test(e),wE=e=>typeof e!=`string`||e.length===0||!e.includes(`<`)||!CE(e)?e:e.replace(SE(),(e,t,n)=>{let r=bE[t.toLowerCase()]??t,i=n.trim();return i.length>0?`## ${r}\n\n${i}`:`## ${r}`}).trimEnd(),TE=e=>wE(vE(e)),EE=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}};function DE(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 OE=(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},kE=e=>{if(!e)return null;let t=e.id;return typeof t==`string`&&t.length>0?t:null},AE=e=>{let t=e?.state?.status;return typeof t==`string`?t:null},jE=e=>e?.state,ME=e=>e?.metadata,NE=e=>{let t=e?.time;return{start:typeof t?.start==`number`?t.start:null,end:typeof t?.end==`number`?t.end:null}},PE=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,``):``},FE=(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||kE(r)!==kE(i))return!1;if(r.type===`tool`){if(jE(r)!==jE(i)||ME(r)!==ME(i)||AE(r)!==AE(i))return!1;let e=NE(r),t=NE(i);if(e.start!==t.start||e.end!==t.end||r.tool!==i.tool||r.output!==i.output)return!1;continue}let a=NE(r),o=NE(i);if(a.start!==o.start||a.end!==o.end)return!1;if(r.type===`text`||r.type===`reasoning`){if(PE(r)!==PE(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},IE=(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.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)&&OE(e.tokens,t.tokens),LE=(e,t)=>IE(e.info,t.info)&&FE(e.parts,t.parts),RE=(e,t)=>!e||!t?e===t:LE(e,t),zE=(e,t)=>!e||!t?e===t:e.additions===t.additions&&e.deletions===t.deletions&&e.files===t.files&&e.hasDiffs===t.hasDiffs,BE=(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},VE=(e,t)=>e.id===t.id&&e.messageId===t.messageId&&e.kind===t.kind&&e.partIndex===t.partIndex&&e.endedAt===t.endedAt&&FE([e.part],[t.part]),HE=(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(!VE(a,o))return!1;r+=1,i+=1}},UE=(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(!VE(e.parts[n],t.parts[n]))return!1;return!0},WE=(e,t)=>!!e?.some(e=>e.anchorMessageId===t),GE=(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(!UE(a,o))return!1;r+=1,i+=1}},KE=(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.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||!HE(e.activityParts,t.activityParts,n)||!GE(e.activityGroupSegments,t.activityGroupSegments,n))return!1;let a=WE(e.activityGroupSegments,n)||WE(t.activityGroupSegments,n);return!((i||a)&&e.toggleGroup!==t.toggleGroup||(i||a||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!zE(e.diffStats,t.diffStats)||(i||a||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!BE(e.changedFiles,t.changedFiles))},qE=/^\*\*\*\s+(?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)/m,JE=/^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@/m,YE=/(?=^diff --git\s+)/gm,XE=/^diff --git\s+/m,ZE=/(?=^---\s+\S)/gm,QE=/^---\s+\S/m,$E=e=>typeof e==`object`&&!!e,eD=e=>e.replace(/\r\n/g,`
6540
6540
  `).replace(/\r/g,`
@@ -6558,7 +6558,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,C as n,E as r,J
6558
6558
  height: 24px !important;
6559
6559
  }
6560
6560
  }
6561
- `,XO={hunkLineCount:50,lineHeight:24,diffHeaderHeight:44,hunkSeparatorHeight:24,spacing:0},ZO={...d.getCollapsedStyles(),padding:0,overflow:`visible`},QO={style:{background:`transparent`,backgroundColor:`transparent`}},$O={color:`var(--status-error)`},ek={color:`var(--tools-icon)`},tk={color:`var(--status-error)`},nk={color:`var(--tools-title)`},rk=(e,t=!0)=>{let n=e.lastIndexOf(`/`);if(n===-1)return(0,$.jsx)(`span`,{className:Y(`min-w-0 truncate typography-ui-label text-foreground`,t&&`flex-1`),style:{direction:`rtl`,textAlign:`left`,unicodeBidi:`plaintext`},title:e,children:e});let r=e.slice(0,n),i=e.slice(n+1),a=r.startsWith(`/`),o=a?r.slice(1):r;return(0,$.jsxs)(`span`,{className:Y(`min-w-0 flex items-baseline overflow-hidden typography-ui-label`,t&&`flex-1`),title:e,children:[a?(0,$.jsx)(`span`,{className:`flex-shrink-0 text-muted-foreground`,children:`/`}):null,(0,$.jsx)(`span`,{className:`min-w-0 truncate text-muted-foreground`,style:{direction:`rtl`,textAlign:`left`,unicodeBidi:`plaintext`},children:o}),(0,$.jsxs)(`span`,{className:`flex-shrink-0`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`/`}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:i})]})]})},ik=(e,t=!0,n=!0,r=!0,i=nO)=>{let a=e.lastIndexOf(`/`),o=i===rO?`h-3 w-3 flex-shrink-0`:`h-3.5 w-3.5 flex-shrink-0`;if(a===-1)return(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex items-center gap-1 overflow-hidden`,n&&`flex-1`),title:e,children:[r?(0,$.jsx)(xh,{filePath:e,className:o}):null,(0,$.jsx)(qT,{variant:t?`generate-effect`:`static`,className:Y(`min-w-0 truncate whitespace-nowrap`,i,n&&`flex-1`),style:{color:`var(--tools-description)`},children:e})]});let s=e.slice(0,a),c=e.slice(a+1),l=s.startsWith(`/`),u=l?s.slice(1):s;return(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex items-center gap-1 overflow-hidden`,n&&`flex-1`),title:e,children:[r?(0,$.jsx)(xh,{filePath:e,className:o}):null,(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex max-w-full items-baseline overflow-hidden`,i,n&&`flex-1`),children:[l?(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:u}),(0,$.jsx)(`span`,{className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:`/`}),(0,$.jsx)(qT,{variant:t?`generate-effect`:`static`,className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:c})]})]})},ak=e=>{let t=(0,Q.c)(3),{diff:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={backgroundColor:`var(--syntax-base-background)`,color:`var(--syntax-base-foreground)`},t[0]=r):r=t[0];let i;return t[1]===n?i=t[2]:(i=(0,$.jsx)(`pre`,{className:`m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg p-2 typography-code`,style:r,children:n}),t[1]=n,t[2]=i),i},ok=class extends Z.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidUpdate(e){e.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:!1})}componentDidCatch(e){}render(){return this.state.hasError?this.props.fallback:this.props.children}},sk=Z.memo(e=>{let t=(0,Q.c)(13),{diff:n,pierreTheme:r,pierreThemeType:i,diffViewMode:a}=e,o=a===`side-by-side`?`split`:`unified`,s;t[0]!==r||t[1]!==i||t[2]!==o?(s={diffStyle:o,diffIndicators:`none`,hunkSeparators:`line-info-basic`,lineDiffType:`none`,disableFileHeader:!0,maxLineDiffLength:1e3,expansionLineCount:20,overflow:`wrap`,theme:r,themeType:i,unsafeCSS:YO},t[0]=r,t[1]=i,t[2]=o,t[3]=s):s=t[3];let c=s,l;t[4]===n?l=t[5]:(l=(0,$.jsx)(ak,{diff:n}),t[4]=n,t[5]=l);let u=l,d;t[6]!==n||t[7]!==c?(d=(0,$.jsx)(Bt,{patch:n,metrics:XO,options:c,className:`block w-full`}),t[6]=n,t[7]=c,t[8]=d):d=t[8];let f;return t[9]!==n||t[10]!==u||t[11]!==d?(f=(0,$.jsx)(`div`,{className:`typography-code px-1 pb-1 pt-0`,children:(0,$.jsx)(ok,{resetKey:n,fallback:u,children:d})}),t[9]=n,t[10]=u,t[11]=d,t[12]=f):f=t[12],f});sk.displayName=`DiffPreview`;var ck=Z.memo(({part:e,state:t,currentDirectory:n,isExpanded:r,isMobile:i,onShowPopup:a})=>{let{t:o}=Zt(),{pierreTheme:s,pierreThemeType:c}=MO(),[l,u]=Z.useState(`unified`),d=t,f=d.metadata,p=d.input,m=d.output,h=typeof m==`string`&&m.length>0,g=typeof m==`string`?m:``,_=OO(f?.filediff)?f.filediff:void 0,v=oD(f?.patch)??oD(f?.diff)??oD(_?.patch)??oD(_?.diff)??null,y=Z.useMemo(()=>mD(f,v??void 0,e=>EO(e,n)),[n,v,f]),b=e.tool===`apply_patch`||e.tool===`edit`||e.tool===`multiedit`,x=Z.useMemo(()=>jO(e.tool,p,f,n),[n,p,f,e.tool]),S=Z.useMemo(()=>!p||typeof p!=`object`||Object.keys(p).length===0?``:`command`in p&&typeof p.command==`string`&&e.tool===`bash`?wu(p,e.tool):typeof p.content==`string`?p.content??``:wu(p,e.tool),[p,e.tool]),C=!b&&S.trim().length>0,w=e.tool===`write`||e.tool===`create`||e.tool===`file_write`,T=e.tool===`todowrite`||e.tool===`todoread`,E=Z.useMemo(()=>Array.isArray(p?.todos)?JSON.stringify(p.todos):g,[p?.todos,g]),D=Z.useMemo(()=>!w||!C?void 0:SO(typeof p?.filePath==`string`?p.filePath:typeof p?.file_path==`string`?p.file_path:typeof p?.path==`string`?p.path:void 0,S),[C,p?.filePath,p?.file_path,p?.path,S,w]);Z.useEffect(()=>{u(`unified`)},[e.id]);let O=(e,t)=>(0,$.jsx)(LO,{isMobile:i,maxHeightClass:t?.maxHeightClass,className:t?.className,disableHorizontal:t?.disableHorizontal,outerClassName:t?.outerClassName,children:e}),k=()=>{let n=()=>x?(0,$.jsxs)(`div`,{className:`tool-output-surface flex flex-col gap-2 rounded-xl border p-2`,style:{borderColor:`var(--status-error-border)`,backgroundColor:`var(--status-error-background)`},children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium`,style:{color:`var(--status-error)`},children:o(`chat.toolPart.lspErrors`)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-1 min-w-0`,children:rk(x.displayPath,!1)}),(0,$.jsx)(`div`,{className:`flex flex-col gap-1`,children:x.diagnostics.map((e,t)=>(0,$.jsx)(`div`,{className:`rounded-md border px-2 py-1`,style:{borderColor:`var(--status-error-border)`,backgroundColor:`var(--surface-elevated)`},children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2 min-w-0`,children:[(0,$.jsxs)(`span`,{className:`typography-micro shrink-0`,style:{color:`var(--status-error)`},children:[`[`,e.line,`:`,e.character,`]`]}),(0,$.jsx)(`span`,{className:`typography-meta text-foreground whitespace-pre-wrap break-words`,children:e.message})]})},`${x.displayPath}:${e.line}:${e.character}:${t}`))}),x.remaining>0?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:o(`chat.toolPart.moreErrors`,{count:x.remaining})}):null]})]}):null;if(e.tool===`question`){if(t.status===`completed`&&h){let e=NO(g);if(e&&e.length>0)return O((0,$.jsx)(`div`,{className:`flex flex-col gap-2`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:e.question}),(0,$.jsx)(`div`,{className:`typography-meta text-foreground whitespace-pre-wrap`,children:e.answer})]},t))}),{maxHeightClass:`max-h-[40vh]`})}if(t.status===`error`&&`error`in t)return(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-muted-foreground`,children:o(`chat.toolPart.error`)}),(0,$.jsx)(`div`,{className:`typography-meta p-2 rounded-xl border`,style:{backgroundColor:`var(--status-error-background)`,color:`var(--status-error)`,borderColor:`var(--status-error-border)`},children:vu(t.error)})]});let e=p;return e?.questions&&Array.isArray(e.questions)&&e.questions.length>0?O((0,$.jsx)(`div`,{className:`flex flex-col gap-2`,children:e.questions.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[e.header?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:vu(e.header)}):null,(0,$.jsx)(`div`,{className:`typography-meta text-foreground`,children:vu(e.question)}),Array.isArray(e.options)&&e.options.length>0?(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-0.5`,children:e.options.map(e=>(0,$.jsx)(`span`,{className:`typography-micro px-1.5 py-0.5 rounded bg-muted/30 border border-border/30 text-muted-foreground`,children:vu(e.label)},vu(e.label)))}):null]},t))}),{maxHeightClass:`max-h-[40vh]`}):(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground`,children:o(`chat.toolPart.awaitingResponse`)})}return e.tool===`task`&&h?O((0,$.jsx)(`div`,{className:`w-full min-w-0`,children:(0,$.jsx)(_l,{content:vu(g),variant:`tool`,onShowPopup:a})})):(e.tool===`edit`||e.tool===`multiedit`||e.tool===`apply_patch`||e.tool===`write`)&&(y.length>0||x)?O((0,$.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[y.map(e=>(0,$.jsx)(`div`,{className:`w-full min-w-0`,children:e.renderMode===`diff`?(0,$.jsx)(sk,{diff:e.patch,pierreTheme:s,pierreThemeType:c,diffViewMode:l}):(0,$.jsx)(ak,{diff:e.patch})},e.id)),n()]}),{className:`p-1`}):e.tool===`write`&&x?O((0,$.jsx)(`div`,{className:`flex flex-col gap-3`,children:n()}),{className:`p-1`}):w?null:h&&g.trim()?O((0,$.jsx)(BO,{output:vu(g),part:e,metadata:f,input:p,isMobile:i}),{className:e.tool===`bash`?`p-1 rounded-none`:`p-1`,maxHeightClass:e.tool===`bash`?`max-h-[46vh]`:void 0}):O((0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground/70`,children:o(`chat.toolPart.noOutputProduced`)}),{maxHeightClass:`max-h-60`})};if(T){if(t.status===`error`&&`error`in t)return(0,$.jsxs)(`div`,{className:ED(i,`todo-error`),children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-muted-foreground/80`,children:o(`chat.toolPart.error`)}),(0,$.jsx)(`div`,{className:`typography-meta p-2 rounded-none border`,style:{backgroundColor:`var(--status-error-background)`,color:`var(--status-error)`,borderColor:`var(--status-error-border)`},children:t.error})]});let n=Su(E,void 0,{listClassName:yu});return(0,$.jsx)(`div`,{className:ED(i,`todo`),children:O(n??(0,$.jsx)(BO,{output:E,part:e,metadata:f,input:p,isMobile:i}),lu)})}return(0,$.jsx)(`div`,{className:ED(i,`default`,e.tool===`bash`),children:e.tool===`question`?k():(0,$.jsxs)($.Fragment,{children:[C?(0,$.jsx)(`div`,{children:O(e.tool===`bash`?(0,$.jsx)(`pre`,{className:`tool-input-text whitespace-pre-wrap break-words typography-code text-muted-foreground/90 m-0 p-0`,style:i?{lineHeight:OD}:void 0,children:S}):w&&D?(0,$.jsx)(sk,{diff:D,pierreTheme:s,pierreThemeType:c,diffViewMode:l}):(0,$.jsx)(`blockquote`,{className:`tool-input-text m-0 whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70`,children:S}),{maxHeightClass:w&&D&&r?`max-h-[50vh]`:`max-h-60`,className:e.tool===`bash`?`tool-input-surface p-0 rounded-none`:`tool-input-surface`})}):null,t.status===`completed`&&`output`in t&&(0,$.jsx)(`div`,{children:k()}),t.status===`error`&&`error`in t&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-muted-foreground/80`,children:o(`chat.toolPart.error`)}),(0,$.jsx)(`div`,{className:`typography-meta p-2 rounded-xl border`,style:{backgroundColor:`var(--status-error-background)`,color:`var(--status-error)`,borderColor:`var(--status-error-border)`},children:vu(t.error)})]})]})})});ck.displayName=`ToolExpandedContent`;var lk=({part:e,messageId:t,isExpanded:n,onToggle:r,isMobile:i,onContentChange:a,onShowPopup:o,animateTailText:s=!0})=>{let c=e.state,l=g(e=>e.showToolFileIcons),u=g(e=>e.showSubagentTaskDetails),d=g(e=>e.openContextPanelTab),f=g(e=>e.openContextDiff),p=g(e=>e.openContextToolDiff),m=g(e=>e.navigateToDiff),{t:h}=Zt(),_=Ul(),v=J(e=>e.setCurrentSession),y=Pu(),b=zy(),x=b.directory||_||``,S=uO(e.tool),C=S===`task`,w=S===`todowrite`||S===`todoread`,T=mO(S),E=c?.status,D=ZD(e),O=E===`error`||E===`failed`,[k,A]=Z.useState(!D),j=Z.useRef(e.id),M=Z.useRef(``);Z.useEffect(()=>{j.current!==e.id&&(j.current=e.id,M.current=``,A(!D))},[D,e.id]),Z.useEffect(()=>{D||A(!0)},[D]),Z.useEffect(()=>{if(!D||O||!x||!fO.has(S))return;let t=`${e.id}:${E??`unknown`}`;M.current!==t&&(M.current=t,ni.requestGitRefresh({directory:x}))},[x,O,D,S,e.id,E]);let N=D||C,P=Z.useRef(a);P.current=a;let F=Z.useRef(null);Z.useLayoutEffect(()=>{if(C||T)return;let e=F.current;if(!e){N&&P.current?.(`structural`);return}e.style.height=n?`auto`:`0px`,e.style.overflow=n?`visible`:`hidden`,N&&P.current?.(`structural`)},[n,T,C,N]);let I=c,L=I.metadata,R=e.metadata,z=I.input,B=I.time,[V,H]=Z.useState(()=>({start:typeof B?.start==`number`?B.start:void 0,end:typeof B?.end==`number`?B.end:void 0})),[ee,U]=Z.useState(void 0),[te,W]=Z.useState(void 0);Z.useEffect(()=>{H({}),U(void 0),W(void 0)},[e.id]),Z.useEffect(()=>{D||typeof B?.start!=`number`&&U(e=>e??Date.now())},[D,B?.start]),Z.useEffect(()=>{H(e=>{let t={...e},n=!1;return typeof B?.start==`number`&&(typeof e.start!=`number`||B.start<e.start)&&(t.start=B.start,n=!0),typeof B?.end==`number`&&(typeof e.end!=`number`||B.end>e.end)&&(t.end=B.end,n=!0),n?t:e})},[B?.end,B?.start]);let ne=Z.useMemo(()=>{if(typeof ee==`number`)return ee;let e=[V.start,B?.start].filter(e=>typeof e==`number`);if(e.length!==0)return Math.min(...e)},[ee,V.start,B?.start]),G=Z.useMemo(()=>typeof I.output==`string`?I.output:void 0,[I.output]),K=Z.useMemo(()=>aE(G),[G]),re=Z.useMemo(()=>{if(!C)return[];let e=L,t=iE(e?.summary??e?.entries??e?.tools??e?.calls);return t.length>0?t:K.summaryEntries},[C,L,K.summaryEntries]),ie=D&&re.length>0,ae=Z.useMemo(()=>C?nE(L)||nE(I)||nE(z)||nE(R)||(K.sessionId?K.sessionId:oE(G)):void 0,[z,C,L,K.sessionId,R,I,G]),oe=Z.useMemo(()=>C&&D&&!!(sE(L)===`running`||sE(I)===`running`||sE(R)===`running`||K.status===`running`||uE(G)),[C,D,L,K.status,R,I,G]),[se,ce]=Z.useState(!0),le=C&&(!D&&k||oe&&se),ue=le?ae:void 0,de=le&&!ae?e.sessionID:void 0,fe=ue??de,pe=sa(ue??``,x),me=sa(de??``,x),he=za(fe??``,x),ge=ki(x,le),_e=!!(oe&&pe?.type===`idle`&&typeof ne==`number`&&(typeof he==`number`&&ne<=he||typeof ge==`number`&&ne<=ge));Z.useEffect(()=>{_e&&ce(!1)},[_e]);let ve=!!(oe&&se&&ae&&pe?.type!==`idle`),ye=!u||ie?``:ae??``,be=ka(ye,x);tr(ye,x);let xe=Z.useMemo(()=>!C||!ae||!Array.isArray(be)||be.length===0?[]:_E(be),[be,C,ae]);Z.useEffect(()=>{if(typeof B?.end==`number`||typeof V.end==`number`){W(void 0);return}typeof ne==`number`&&D&&W(e=>e??Date.now())},[ne,D,V.end,B?.end]);let Se=D?V.end??B?.end??te:void 0,Ce=!D&&k,we=DE({isTaskTool:C,isFinalized:D,taskSessionId:ae,childSessionStatus:pe,parentSessionStatus:me,statusObservedAt:he,taskStartedAt:ne,statusSnapshotAt:ge}),Te=Ce&&!we||ve,Ee=!!(C&&Te&&!O);Z.useEffect(()=>{we&&A(!1)},[we]);let De=D,Oe=Z.useMemo(()=>xe.length>0?xe:re,[xe,re]),ke=Z.useMemo(()=>Oe.map(WO).join(`\0`),[Oe]),Ae=Z.useRef(null);Z.useEffect(()=>{if(!C){Ae.current=null;return}let e=Ae.current;Ae.current=ke,e!==null&&e!==ke&&Oe.length!==0&&P.current?.(`structural`)},[C,Oe.length,ke]);let je=Z.useMemo(()=>S===`edit`||S===`multiedit`||S===`apply_patch`?yO(L):null,[L,S]),Me=Z.useMemo(()=>S===`write`?bO(z):null,[z,S]),Ne=S===`apply_patch`&&Array.isArray(L?.files)&&(L?.files).length>1,Pe=S===e.tool?e:{...e,tool:S},Fe=PO(Pe,c,x),Ie=IO(Pe,c,x),Le=Hl(S||e.tool,h),Re=Dr(C?ae:void 0,x),ze=Dr(C?ae:void 0),Be=C?oO(z,L,R,Re??ze):void 0,Ve=EE({isTaskTool:C,isFinalized:D,taskSessionId:ae,taskAgentName:Be,displayName:Le,delegatingLabel:h(`chat.assistantStatus.delegatingTask`),formatName:sO}),He=C&&Ve.isDelegating,Ue=Ve.title,We=typeof e.sessionID==`string`?e.sessionID.trim():``,Ge=Z.useMemo(()=>{if(!C||!We)return null;let n=typeof ae==`string`&&ae.trim().length>0?ae.trim():void 0,r=typeof e.id==`string`&&e.id.trim().length>0?e.id.trim():void 0,i=typeof e.messageID==`string`&&e.messageID.trim().length>0?e.messageID.trim():typeof t==`string`&&t.trim().length>0?t.trim():void 0;return{sessionID:We,...r?{partID:r}:{},...i?{messageID:i}:{},...x?{directory:x}:{},directoryPresent:!!x,childSessionPresent:!!n,...n?{childSessionID:n}:{},...E?{toolStatus:E}:{},finalized:D,backgroundRunning:ve,effectiveActive:Te,suppressLoading:we,delegating:He,childStatus:wi(pe),parentStatus:wi(me),idleConfirmed:_e,navigateCapability:b.capabilities.navigateNestedSession,surfaceKind:b.kind,...typeof ne==`number`?{taskStartedAt:ne}:{},...typeof he==`number`?{statusObservedAt:he}:{},...typeof ge==`number`?{statusSnapshotAt:ge}:{}}},[_e,pe,x,Te,ne,He,D,C,t,We,me,e.id,e.messageID,b.capabilities.navigateNestedSession,b.kind,E,he,ge,we,ve,ae]),Ke=Ge?Ra(Ge):``,qe=Z.useRef(Ge);qe.current=Ge,Z.useEffect(()=>{let e=qe.current;!e||!Ke||Oa(e)},[Ke]);let Je=q((e,t)=>{let n=qe.current;n&&ga({...n,opened:e,clickSource:t})}),Ye=He?{"data-delegating":`true`}:void 0,Xe=Z.useMemo(()=>{if(S===`bash`||S===`apply_patch`||S===`lsp`||Fe&&(S===`apply_patch`||S===`edit`||S===`multiedit`||S===`write`))return null;let e=I.title;if(typeof e==`string`&&e.trim().length>0)return e;let t=z?.description;return typeof t==`string`&&t.trim().length>0?t:null},[Fe,S,I,z]),Ze=Z.useContext(ac),Qe=Z.useRef(!1),$e=q(e=>{let t=e??ae;return!t||!x?!1:(Qe.current=!1,Vy(b,t,x,()=>{if(!ma({sessionId:t,directory:x})){if(i||Ze?.runtime.isVSCode){v(t,x);return}d(x,{mode:`chat`,dedupeKey:`session:${t}`,label:Ue,readOnly:!0})}}))});Z.useEffect(()=>{!Qe.current||!ae||Je($e(ae),`queued-effect`)},[ae]);let et=n=>{if(C){n.stopPropagation();let e=b.capabilities.navigateNestedSession,t=e?$e():!1;Je(t,`row`),e&&!t&&(Qe.current=!0);return}if(T&&!x)return;let a,o,s;if(S===`edit`||S===`multiedit`||S===`apply_patch`)a=AO(S,z,L),o=CO(S,L,typeof a==`string`?a:void 0),typeof a==`string`&&(s=wO(S,L,a));else if([`write`,`create`,`file_write`].includes(S))a=z?.filePath||z?.file_path||z?.path||L?.filePath||L?.file_path||L?.path,o=1,typeof a==`string`&&typeof z?.content==`string`&&(s=SO(a,z.content));else if(S===`lsp`){a=z?.filePath||z?.file_path||z?.path;let e=z?.line;o=typeof e==`number`&&Number.isFinite(e)?Math.trunc(e):void 0}if(typeof a==`string`){n.stopPropagation();let r=ru(x,a)||(a.startsWith(`/`)?a:x.endsWith(`/`)?x+a:`${x}/${a}`);if(T){let e=EO(r,x),n=s?gD(S,L,s,e,e=>EO(e,x)):[],a=hO(S)&&n.length===1&&n[0]?[{path:e,patch:n[0].patch}]:n.map(e=>({path:e.title,patch:e.patch}));if(Ze?.runtime.isVSCode&&Ze.editor&&s){let t=`${e} (changes)`;Ze.editor.openDiff(``,r,t,{line:o,patch:s});return}if(tu(r,x)){y?a.length>0?y.openToolDiff({diffPath:e,patches:a,targetLine:o}):S===`apply_patch`?y.openTurnDiff(t,b.sessionId):y.openChanges({diffPath:e,staged:!1,targetLine:o}):i?m(e,!1,hO(S)?`working`:`turn`,o):a.length>0?p(x,e,a,o,t,b.sessionId):f(x,e,!1,hO(S)?`working`:`turn`,o,t,b.sessionId);return}if(Ze?.editor){Ze.editor.openFile(r,o);return}Vu(r,x).then(()=>{let e=g.getState(),t=iu(x,r);if(typeof o==`number`&&Number.isFinite(o)){e.openContextFileAtLine(t,r,Math.max(1,Math.trunc(o)),1);return}e.openContextFile(t,r)});return}if(S===`lsp`){if(Ze?.editor){Ze.editor.openFile(r,o);return}let e=()=>{let e=g.getState(),t=iu(x,r);if(typeof o==`number`&&Number.isFinite(o)){e.openContextFileAtLine(t,r,Math.max(1,Math.trunc(o)),1);return}e.openContextFile(t,r)};if(!tu(r,x)){Vu(r,x).then(e);return}e();return}if(Ze?.editor){if(Ze.runtime.isVSCode&&s&&(e.tool===`edit`||e.tool===`multiedit`||e.tool===`apply_patch`)){let e=`${EO(r,x)} (changes)`;Ze.editor.openDiff(``,r,e,{line:o,patch:s});return}Ze.editor.openFile(r,o);return}}if(S===`apply_patch`&&y){n.stopPropagation(),y.openTurnDiff(t,b.sessionId);return}if(S===`apply_patch`&&x&&!y&&!i&&!Ze?.runtime.isVSCode){n.stopPropagation(),d(x,{mode:`diff`,diffScope:`turn`,diffTurnMessageId:t,diffSessionId:b.sessionId});return}T||r(e.id)},tt=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),et(e))},nt=!C&&O?$O:ek,rt=!C&&O?tk:nk,it=C&&u&&(Oe.length>0||Te||De||!!ae),at=!C&&!T&&n;return!De&&!Ce&&!C?null:(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:Y(`group/tool flex gap-1.5 cursor-pointer`,gv,C&&`hover:!bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)]`,Ne?`flex-wrap items-start`:`items-center`),"data-mobile-press-feedback":`soft`,...Ye,onClick:et,onKeyDown:tt,role:`button`,tabIndex:0,children:[(0,$.jsxs)(`div`,{className:Y(`flex gap-1.5`,Ne?`w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5`:`items-center flex-shrink-0`),children:[(0,$.jsx)(`div`,{className:Y(`relative flex-shrink-0`,i?`size-4`:`size-3.5`),children:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,style:C&&Ve.showAvatar?void 0:nt,children:C&&Ve.showAvatar?(0,$.jsx)(vo,{name:e.id||Be||`subagent`,size:14,label:Ue}):Te?(0,$.jsx)(FD,{isMobile:i,className:`text-[var(--tools-icon)]`,label:h(`chat.assistantStatus.usingTool`,{tool:Ue})}):JT(S||e.tool)})}),Ne?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:Y(tO,`flex-shrink-0`),style:rt,title:Le,children:Le}),lO(L,s,l)]}):(0,$.jsxs)($.Fragment,{children:[Ee?(0,$.jsx)(`span`,{className:Y(tO,`shrink-0 whitespace-nowrap animate-text-shimmer`),style:{color:`var(--tools-title)`,"--oc-text-shimmer-base":`var(--tools-title)`},title:Ue,children:Ue}):(0,$.jsx)(`span`,{className:Y(tO,`shrink-0 whitespace-nowrap`),style:rt,title:Ue,children:Ue}),S===`bash`&&typeof ne==`number`?(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums text-muted-foreground/80`,nO),children:(0,$.jsx)(_O,{start:ne,end:typeof Se==`number`?Se:void 0,active:!!(Te&&typeof Se!=`number`)})}):null]})]}),!Ne&&(0,$.jsx)(`div`,{className:Y(`flex items-center gap-1 flex-1 min-w-0`,nO),style:{color:`var(--tools-description)`},children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1 flex-1 min-w-0`,children:[Xe&&(0,$.jsx)(`span`,{className:Y(`min-w-0 truncate`,nO,Ee&&`animate-text-shimmer`),style:{color:`var(--tools-description)`,...Ee?{"--oc-text-shimmer-base":`var(--tools-description)`}:{opacity:.8}},title:Xe,children:Xe}),!Xe&&S===`lsp`&&Fe?ik(Fe,s,!1,l):null,!Xe&&S!==`lsp`&&Ie&&(Fe&&Ie===Fe?ik(Fe,s,!1,l):(0,$.jsx)(qT,{variant:s?`generate-effect`:`static`,className:Y(`min-w-0 truncate`,nO),style:{color:`var(--tools-description)`},title:Ie,children:Ie})),je&&(0,$.jsxs)(`span`,{className:`flex-shrink-0 inline-flex items-center gap-0 typography-meta`,children:[(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,je.added]}),(0,$.jsx)(`span`,{style:{color:`var(--tools-description)`},children:`/`}),(0,$.jsxs)(`span`,{style:{color:`var(--status-error)`},children:[`-`,je.removed]})]}),Me&&(0,$.jsx)(`span`,{className:`flex-shrink-0 inline-flex items-center gap-0 typography-meta`,children:(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,Me]})})]})}),!T&&(!C||u)?(0,$.jsx)(`span`,{className:`ml-auto inline-flex size-3.5 flex-shrink-0 items-center justify-center text-muted-foreground opacity-70`,onClick:C?t=>{t.stopPropagation(),r(e.id)}:void 0,children:(0,$.jsx)(X,{name:n?`arrow-down-s`:`arrow-right-s`,className:`size-3.5`})}):null]}),it?(0,$.jsx)(JO,{entries:Oe,isExpanded:n,isMobile:i,output:G,sessionId:ae,onShowPopup:o,input:z,animateTailText:s,isActive:Te}):null,!C&&!T&&n?(0,$.jsx)(`div`,{ref:F,"aria-hidden":!1,style:{height:`auto`,overflow:`visible`,overflowAnchor:`none`},children:at?(0,$.jsxs)(`div`,{className:w?`relative ml-0.5 pl-1.5`:TD,children:[(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)`}}),(0,$.jsx)(ck,{part:e,state:c,currentDirectory:x,isExpanded:n,isMobile:i,onShowPopup:o})]}):null}):null]})},uk=class extends Z.Component{state={hasError:!1};static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidUpdate(e){e.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:!1,error:void 0})}componentDidCatch(e){}render(){if(!this.state.hasError)return this.props.children;let e=this.state.error?.message;return(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-1.5 min-w-0`,pv),children:[(0,$.jsx)(`div`,{className:`h-3.5 w-3.5 flex-shrink-0`,style:$O,children:JT(this.props.toolName)}),(0,$.jsx)(`span`,{className:Y(tO,`flex-shrink-0`),style:tk,children:this.props.displayName}),e?(0,$.jsxs)(`span`,{className:Y(nO,`min-w-0 truncate`),style:{color:`var(--tools-description)`},title:e,children:[this.props.errorLabel,`: `,e]}):null]})}},dk=Z.memo(e=>{let t=(0,Q.c)(30),{t:n}=Zt(),r=wD(),i,a;t[0]!==e.part.tool||t[1]!==n?(a=uO(e.part.tool)||`tool`,i=Hl(a,n),t[0]=e.part.tool,t[1]=n,t[2]=i,t[3]=a):(i=t[2],a=t[3]);let o=i,s;t[4]!==r||t[5]!==e.part.id?(s=()=>!r||cO.get(e.part.id)===!0,t[4]=r,t[5]=e.part.id,t[6]=s):s=t[6];let[c,l]=Z.useState(s),u,d;if(t[7]!==r||t[8]!==c||t[9]!==e.part.id?(u=()=>{if(!(!r||c))return Kl(()=>{cO.set(e.part.id,!0,e.part.id.length*2+8),Z.startTransition(()=>{l(!0)})})},d=[r,c,e.part.id],t[7]=r,t[8]=c,t[9]=e.part.id,t[10]=u,t[11]=d):(u=t[10],d=t[11]),Z.useEffect(u,d),!c){let e,n,r;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(e=Y(`flex min-w-0 items-center gap-2`,pv),n=(0,$.jsx)(`span`,{className:`h-3.5 w-3.5 shrink-0 rounded bg-muted/50`,"aria-hidden":`true`}),r=Y(tO,`shrink-0 text-muted-foreground`),t[12]=e,t[13]=n,t[14]=r):(e=t[12],n=t[13],r=t[14]);let i;t[15]===o?i=t[16]:(i=(0,$.jsx)(`span`,{className:r,children:o}),t[15]=o,t[16]=i);let a;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(`span`,{className:`h-3 w-24 min-w-0 rounded bg-muted/40`,"aria-hidden":`true`}),t[17]=a):a=t[17];let s;return t[18]===i?s=t[19]:(s=(0,$.jsxs)(`div`,{className:e,children:[n,i,a]}),t[18]=i,t[19]=s),s}let f;t[20]===n?f=t[21]:(f=n(`chat.toolPart.error`),t[20]=n,t[21]=f);let p;t[22]===e?p=t[23]:(p=(0,$.jsx)(lk,{...e}),t[22]=e,t[23]=p);let m;return t[24]!==o||t[25]!==e.part||t[26]!==f||t[27]!==p||t[28]!==a?(m=(0,$.jsx)(uk,{displayName:o,errorLabel:f,resetKey:e.part,toolName:a,children:p}),t[24]=o,t[25]=e.part,t[26]=f,t[27]=p,t[28]=a,t[29]=m):m=t[29],m},(e,t)=>FE([e.part],[t.part])&&e.messageId===t.messageId&&e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.alwaysShowActions===t.alwaysShowActions&&e.onContentChange===t.onContentChange&&e.onShowPopup===t.onShowPopup&&e.animateTailText===t.animateTailText);function fk(e){return e.stopPropagation()}function pk(e){return e.stopPropagation()}function mk(e){return e.stopPropagation()}function hk(e){return e.setCurrentSession}function gk(e){return e.openContextPanelTab}function _k(e){return e.showToolFileIcons}function vk(e){return e.stopPropagation()}function yk(e){return e.stopPropagation()}function bk(e){return!e}var xk=(e,t,n)=>{let r=t-e;return Math.max(0,n-r)},Sk=e=>{e.timer&&=(clearTimeout(e.timer),null)},Ck=({text:e,isStreaming:t,throttleMs:n=Xl(Tt()).textThrottleMs,identityKey:r})=>{let[i,a]=Z.useState(e),o=Z.useRef(e),s=Z.useRef(i),c=Z.useRef({timer:null,pendingText:e,lastEmitAt:0});return Z.useEffect(()=>{o.current=e},[e]),Z.useEffect(()=>{s.current=i},[i]),Z.useEffect(()=>{let e=c.current;Sk(e),e.pendingText=o.current,e.lastEmitAt=0,a(o.current)},[r]),Z.useEffect(()=>{let r=c.current;r.pendingText=e;let i=s.current,o=t&&i.length>e.length?i:e;if(!t){Sk(r),r.lastEmitAt=Date.now(),a(o);return}let l=Date.now(),u=xk(r.lastEmitAt,l,n);if(u<=0){Sk(r),r.lastEmitAt=l,a(o);return}return Sk(r),r.timer=setTimeout(()=>{r.timer=null,r.lastEmitAt=Date.now(),a(e=>t&&e.length>r.pendingText.length?e:r.pendingText)},u),()=>{Sk(r)}},[t,e,n]),Z.useEffect(()=>{let e=c.current;return()=>{Sk(e)}},[]),i},wk=e=>e.isStreaming?e.throttledTextContent:e.textContent,Tk=e=>!e.isFinalized&&e.displayTextContent.trim().length===0?!1:e.displayTextContent.trim().length>0,Ek=e=>{let t=(0,Q.c)(44),{result:n}=e,{t:r}=Zt(),[i,a]=Z.useState(!1),o=Z.useRef(null),s,c;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>()=>{o.current!==null&&window.clearTimeout(o.current)},c=[],t[0]=s,t[1]=c):(s=t[0],c=t[1]),Z.useEffect(s,c);let l;bb0:{if(n.kind===`commit`){let e;t[2]!==n.highlights||t[3]!==n.subject?(e=[n.subject,...n.highlights.map(Dk)],t[2]=n.highlights,t[3]=n.subject,t[4]=e):e=t[4],l=e.join(`
6561
+ `,XO={hunkLineCount:50,lineHeight:24,diffHeaderHeight:44,hunkSeparatorHeight:24,spacing:0},ZO={...d.getCollapsedStyles(),padding:0,overflow:`visible`},QO={style:{background:`transparent`,backgroundColor:`transparent`}},$O={color:`var(--status-error)`},ek={color:`var(--tools-icon)`},tk={color:`var(--status-error)`},nk={color:`var(--tools-title)`},rk=(e,t=!0)=>{let n=e.lastIndexOf(`/`);if(n===-1)return(0,$.jsx)(`span`,{className:Y(`min-w-0 truncate typography-ui-label text-foreground`,t&&`flex-1`),style:{direction:`rtl`,textAlign:`left`,unicodeBidi:`plaintext`},title:e,children:e});let r=e.slice(0,n),i=e.slice(n+1),a=r.startsWith(`/`),o=a?r.slice(1):r;return(0,$.jsxs)(`span`,{className:Y(`min-w-0 flex items-baseline overflow-hidden typography-ui-label`,t&&`flex-1`),title:e,children:[a?(0,$.jsx)(`span`,{className:`flex-shrink-0 text-muted-foreground`,children:`/`}):null,(0,$.jsx)(`span`,{className:`min-w-0 truncate text-muted-foreground`,style:{direction:`rtl`,textAlign:`left`,unicodeBidi:`plaintext`},children:o}),(0,$.jsxs)(`span`,{className:`flex-shrink-0`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`/`}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:i})]})]})},ik=(e,t=!0,n=!0,r=!0,i=nO)=>{let a=e.lastIndexOf(`/`),o=i===rO?`h-3 w-3 flex-shrink-0`:`h-3.5 w-3.5 flex-shrink-0`;if(a===-1)return(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex items-center gap-1 overflow-hidden`,n&&`flex-1`),title:e,children:[r?(0,$.jsx)(xh,{filePath:e,className:o}):null,(0,$.jsx)(qT,{variant:t?`generate-effect`:`static`,className:Y(`min-w-0 truncate whitespace-nowrap`,i,n&&`flex-1`),style:{color:`var(--tools-description)`},children:e})]});let s=e.slice(0,a),c=e.slice(a+1),l=s.startsWith(`/`),u=l?s.slice(1):s;return(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex items-center gap-1 overflow-hidden`,n&&`flex-1`),title:e,children:[r?(0,$.jsx)(xh,{filePath:e,className:o}):null,(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex max-w-full items-baseline overflow-hidden`,i,n&&`flex-1`),children:[l?(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:u}),(0,$.jsx)(`span`,{className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:`/`}),(0,$.jsx)(qT,{variant:t?`generate-effect`:`static`,className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:c})]})]})},ak=e=>{let t=(0,Q.c)(3),{diff:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={backgroundColor:`var(--syntax-base-background)`,color:`var(--syntax-base-foreground)`},t[0]=r):r=t[0];let i;return t[1]===n?i=t[2]:(i=(0,$.jsx)(`pre`,{className:`m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg p-2 typography-code`,style:r,children:n}),t[1]=n,t[2]=i),i},ok=class extends Z.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidUpdate(e){e.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:!1})}componentDidCatch(e){}render(){return this.state.hasError?this.props.fallback:this.props.children}},sk=Z.memo(e=>{let t=(0,Q.c)(13),{diff:n,pierreTheme:r,pierreThemeType:i,diffViewMode:a}=e,o=a===`side-by-side`?`split`:`unified`,s;t[0]!==r||t[1]!==i||t[2]!==o?(s={diffStyle:o,diffIndicators:`none`,hunkSeparators:`line-info-basic`,lineDiffType:`none`,disableFileHeader:!0,maxLineDiffLength:1e3,expansionLineCount:20,overflow:`wrap`,theme:r,themeType:i,unsafeCSS:YO},t[0]=r,t[1]=i,t[2]=o,t[3]=s):s=t[3];let c=s,l;t[4]===n?l=t[5]:(l=(0,$.jsx)(ak,{diff:n}),t[4]=n,t[5]=l);let u=l,d;t[6]!==n||t[7]!==c?(d=(0,$.jsx)(Bt,{patch:n,metrics:XO,options:c,className:`block w-full`}),t[6]=n,t[7]=c,t[8]=d):d=t[8];let f;return t[9]!==n||t[10]!==u||t[11]!==d?(f=(0,$.jsx)(`div`,{className:`typography-code px-1 pb-1 pt-0`,children:(0,$.jsx)(ok,{resetKey:n,fallback:u,children:d})}),t[9]=n,t[10]=u,t[11]=d,t[12]=f):f=t[12],f});sk.displayName=`DiffPreview`;var ck=Z.memo(({part:e,state:t,currentDirectory:n,isExpanded:r,isMobile:i,onShowPopup:a})=>{let{t:o}=Zt(),{pierreTheme:s,pierreThemeType:c}=MO(),[l,u]=Z.useState(`unified`),d=t,f=d.metadata,p=d.input,m=d.output,h=typeof m==`string`&&m.length>0,g=typeof m==`string`?m:``,_=OO(f?.filediff)?f.filediff:void 0,v=oD(f?.patch)??oD(f?.diff)??oD(_?.patch)??oD(_?.diff)??null,y=Z.useMemo(()=>mD(f,v??void 0,e=>EO(e,n)),[n,v,f]),b=e.tool===`apply_patch`||e.tool===`edit`||e.tool===`multiedit`,x=Z.useMemo(()=>jO(e.tool,p,f,n),[n,p,f,e.tool]),S=Z.useMemo(()=>!p||typeof p!=`object`||Object.keys(p).length===0?``:`command`in p&&typeof p.command==`string`&&e.tool===`bash`?wu(p,e.tool):typeof p.content==`string`?p.content??``:wu(p,e.tool),[p,e.tool]),C=!b&&S.trim().length>0,w=e.tool===`write`||e.tool===`create`||e.tool===`file_write`,T=e.tool===`todowrite`||e.tool===`todoread`,E=Z.useMemo(()=>Array.isArray(p?.todos)?JSON.stringify(p.todos):g,[p?.todos,g]),D=Z.useMemo(()=>!w||!C?void 0:SO(typeof p?.filePath==`string`?p.filePath:typeof p?.file_path==`string`?p.file_path:typeof p?.path==`string`?p.path:void 0,S),[C,p?.filePath,p?.file_path,p?.path,S,w]);Z.useEffect(()=>{u(`unified`)},[e.id]);let O=(e,t)=>(0,$.jsx)(LO,{isMobile:i,maxHeightClass:t?.maxHeightClass,className:t?.className,disableHorizontal:t?.disableHorizontal,outerClassName:t?.outerClassName,children:e}),k=()=>{let n=()=>x?(0,$.jsxs)(`div`,{className:`tool-output-surface flex flex-col gap-2 rounded-xl border p-2`,style:{borderColor:`var(--status-error-border)`,backgroundColor:`var(--status-error-background)`},children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium`,style:{color:`var(--status-error)`},children:o(`chat.toolPart.lspErrors`)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-1 min-w-0`,children:rk(x.displayPath,!1)}),(0,$.jsx)(`div`,{className:`flex flex-col gap-1`,children:x.diagnostics.map((e,t)=>(0,$.jsx)(`div`,{className:`rounded-md border px-2 py-1`,style:{borderColor:`var(--status-error-border)`,backgroundColor:`var(--surface-elevated)`},children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2 min-w-0`,children:[(0,$.jsxs)(`span`,{className:`typography-micro shrink-0`,style:{color:`var(--status-error)`},children:[`[`,e.line,`:`,e.character,`]`]}),(0,$.jsx)(`span`,{className:`typography-meta text-foreground whitespace-pre-wrap break-words`,children:e.message})]})},`${x.displayPath}:${e.line}:${e.character}:${t}`))}),x.remaining>0?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:o(`chat.toolPart.moreErrors`,{count:x.remaining})}):null]})]}):null;if(e.tool===`question`){if(t.status===`completed`&&h){let e=NO(g);if(e&&e.length>0)return O((0,$.jsx)(`div`,{className:`flex flex-col gap-2`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:e.question}),(0,$.jsx)(`div`,{className:`typography-meta text-foreground whitespace-pre-wrap`,children:e.answer})]},t))}),{maxHeightClass:`max-h-[40vh]`})}if(t.status===`error`&&`error`in t)return(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-muted-foreground`,children:o(`chat.toolPart.error`)}),(0,$.jsx)(`div`,{className:`typography-meta p-2 rounded-xl border`,style:{backgroundColor:`var(--status-error-background)`,color:`var(--status-error)`,borderColor:`var(--status-error-border)`},children:vu(t.error)})]});let e=p;return e?.questions&&Array.isArray(e.questions)&&e.questions.length>0?O((0,$.jsx)(`div`,{className:`flex flex-col gap-2`,children:e.questions.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[e.header?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:vu(e.header)}):null,(0,$.jsx)(`div`,{className:`typography-meta text-foreground`,children:vu(e.question)}),Array.isArray(e.options)&&e.options.length>0?(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-0.5`,children:e.options.map(e=>(0,$.jsx)(`span`,{className:`typography-micro px-1.5 py-0.5 rounded bg-muted/30 border border-border/30 text-muted-foreground`,children:vu(e.label)},vu(e.label)))}):null]},t))}),{maxHeightClass:`max-h-[40vh]`}):(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground`,children:o(`chat.toolPart.awaitingResponse`)})}return e.tool===`task`&&h?O((0,$.jsx)(`div`,{className:`w-full min-w-0`,children:(0,$.jsx)(_l,{content:vu(g),variant:`tool`,onShowPopup:a})})):(e.tool===`edit`||e.tool===`multiedit`||e.tool===`apply_patch`||e.tool===`write`)&&(y.length>0||x)?O((0,$.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[y.map(e=>(0,$.jsx)(`div`,{className:`w-full min-w-0`,children:e.renderMode===`diff`?(0,$.jsx)(sk,{diff:e.patch,pierreTheme:s,pierreThemeType:c,diffViewMode:l}):(0,$.jsx)(ak,{diff:e.patch})},e.id)),n()]}),{className:`p-1`}):e.tool===`write`&&x?O((0,$.jsx)(`div`,{className:`flex flex-col gap-3`,children:n()}),{className:`p-1`}):w?null:h&&g.trim()?O((0,$.jsx)(BO,{output:vu(g),part:e,metadata:f,input:p,isMobile:i}),{className:e.tool===`bash`?`p-1 rounded-none`:`p-1`,maxHeightClass:e.tool===`bash`?`max-h-[46vh]`:void 0}):O((0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground/70`,children:o(`chat.toolPart.noOutputProduced`)}),{maxHeightClass:`max-h-60`})};if(T){if(t.status===`error`&&`error`in t)return(0,$.jsxs)(`div`,{className:ED(i,`todo-error`),children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-muted-foreground/80`,children:o(`chat.toolPart.error`)}),(0,$.jsx)(`div`,{className:`typography-meta p-2 rounded-none border`,style:{backgroundColor:`var(--status-error-background)`,color:`var(--status-error)`,borderColor:`var(--status-error-border)`},children:t.error})]});let n=Su(E,void 0,{listClassName:yu});return(0,$.jsx)(`div`,{className:ED(i,`todo`),children:O(n??(0,$.jsx)(BO,{output:E,part:e,metadata:f,input:p,isMobile:i}),lu)})}return(0,$.jsx)(`div`,{className:ED(i,`default`,e.tool===`bash`),children:e.tool===`question`?k():(0,$.jsxs)($.Fragment,{children:[C?(0,$.jsx)(`div`,{children:O(e.tool===`bash`?(0,$.jsx)(`pre`,{className:`tool-input-text whitespace-pre-wrap break-words typography-code text-muted-foreground/90 m-0 p-0`,style:i?{lineHeight:OD}:void 0,children:S}):w&&D?(0,$.jsx)(sk,{diff:D,pierreTheme:s,pierreThemeType:c,diffViewMode:l}):(0,$.jsx)(`blockquote`,{className:`tool-input-text m-0 whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70`,children:S}),{maxHeightClass:w&&D&&r?`max-h-[50vh]`:`max-h-60`,className:e.tool===`bash`?`tool-input-surface p-0 rounded-none`:`tool-input-surface`})}):null,t.status===`completed`&&`output`in t&&(0,$.jsx)(`div`,{children:k()}),t.status===`error`&&`error`in t&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-muted-foreground/80`,children:o(`chat.toolPart.error`)}),(0,$.jsx)(`div`,{className:`typography-meta p-2 rounded-xl border`,style:{backgroundColor:`var(--status-error-background)`,color:`var(--status-error)`,borderColor:`var(--status-error-border)`},children:vu(t.error)})]})]})})});ck.displayName=`ToolExpandedContent`;var lk=({part:e,messageId:t,isExpanded:n,onToggle:r,isMobile:i,onContentChange:a,onShowPopup:o,animateTailText:s=!0})=>{let c=e.state,l=g(e=>e.showToolFileIcons),u=g(e=>e.showSubagentTaskDetails),d=g(e=>e.openContextPanelTab),f=g(e=>e.openContextDiff),p=g(e=>e.openContextToolDiff),m=g(e=>e.navigateToDiff),{t:h}=Zt(),_=Ul(),v=J(e=>e.setCurrentSession),y=Pu(),b=zy(),x=b.directory||_||``,S=uO(e.tool),C=S===`task`,w=S===`todowrite`||S===`todoread`,T=mO(S),E=c?.status,D=ZD(e),O=E===`error`||E===`failed`,[k,A]=Z.useState(!D),j=Z.useRef(e.id),M=Z.useRef(``);Z.useEffect(()=>{j.current!==e.id&&(j.current=e.id,M.current=``,A(!D))},[D,e.id]),Z.useEffect(()=>{D||A(!0)},[D]),Z.useEffect(()=>{if(!D||O||!x||!fO.has(S))return;let t=`${e.id}:${E??`unknown`}`;M.current!==t&&(M.current=t,ni.requestGitRefresh({directory:x}))},[x,O,D,S,e.id,E]);let N=D||C,P=Z.useRef(a);P.current=a;let F=Z.useRef(null);Z.useLayoutEffect(()=>{if(C||T)return;let e=F.current;if(!e){N&&P.current?.(`structural`);return}e.style.height=n?`auto`:`0px`,e.style.overflow=n?`visible`:`hidden`,N&&P.current?.(`structural`)},[n,T,C,N]);let I=c,L=I.metadata,R=e.metadata,z=I.input,B=I.time,[V,H]=Z.useState(()=>({start:typeof B?.start==`number`?B.start:void 0,end:typeof B?.end==`number`?B.end:void 0})),[ee,U]=Z.useState(void 0),[te,W]=Z.useState(void 0);Z.useEffect(()=>{H({}),U(void 0),W(void 0)},[e.id]),Z.useEffect(()=>{D||typeof B?.start!=`number`&&U(e=>e??Date.now())},[D,B?.start]),Z.useEffect(()=>{H(e=>{let t={...e},n=!1;return typeof B?.start==`number`&&(typeof e.start!=`number`||B.start<e.start)&&(t.start=B.start,n=!0),typeof B?.end==`number`&&(typeof e.end!=`number`||B.end>e.end)&&(t.end=B.end,n=!0),n?t:e})},[B?.end,B?.start]);let ne=Z.useMemo(()=>{if(typeof ee==`number`)return ee;let e=[V.start,B?.start].filter(e=>typeof e==`number`);if(e.length!==0)return Math.min(...e)},[ee,V.start,B?.start]),G=Z.useMemo(()=>typeof I.output==`string`?I.output:void 0,[I.output]),K=Z.useMemo(()=>aE(G),[G]),re=Z.useMemo(()=>{if(!C)return[];let e=L,t=iE(e?.summary??e?.entries??e?.tools??e?.calls);return t.length>0?t:K.summaryEntries},[C,L,K.summaryEntries]),ie=D&&re.length>0,ae=Z.useMemo(()=>C?nE(L)||nE(I)||nE(z)||nE(R)||(K.sessionId?K.sessionId:oE(G)):void 0,[z,C,L,K.sessionId,R,I,G]),oe=Z.useMemo(()=>C&&D&&!!(sE(L)===`running`||sE(I)===`running`||sE(R)===`running`||K.status===`running`||uE(G)),[C,D,L,K.status,R,I,G]),[se,ce]=Z.useState(!0),le=C&&(!D&&k||oe&&se),ue=le?ae:void 0,de=le&&!ae?e.sessionID:void 0,fe=ue??de,pe=sa(ue??``,x),me=sa(de??``,x),he=za(fe??``,x),ge=ki(x,le),_e=!!(oe&&pe?.type===`idle`&&typeof ne==`number`&&(typeof he==`number`&&ne<=he||typeof ge==`number`&&ne<=ge));Z.useEffect(()=>{_e&&ce(!1)},[_e]);let ve=!!(oe&&se&&ae&&pe?.type!==`idle`),ye=!u||ie?``:ae??``,be=ka(ye,x);tr(ye,x);let xe=Z.useMemo(()=>!C||!ae||!Array.isArray(be)||be.length===0?[]:_E(be),[be,C,ae]);Z.useEffect(()=>{if(typeof B?.end==`number`||typeof V.end==`number`){W(void 0);return}typeof ne==`number`&&D&&W(e=>e??Date.now())},[ne,D,V.end,B?.end]);let Se=D?V.end??B?.end??te:void 0,Ce=!D&&k,we=DE({isTaskTool:C,isFinalized:D,taskSessionId:ae,childSessionStatus:pe,parentSessionStatus:me,statusObservedAt:he,taskStartedAt:ne,statusSnapshotAt:ge}),Te=Ce&&!we||ve,Ee=!!(C&&Te&&!O);Z.useEffect(()=>{we&&A(!1)},[we]);let De=D,Oe=Z.useMemo(()=>xe.length>0?xe:re,[xe,re]),ke=Z.useMemo(()=>Oe.map(WO).join(`\0`),[Oe]),Ae=Z.useRef(null);Z.useEffect(()=>{if(!C){Ae.current=null;return}let e=Ae.current;Ae.current=ke,e!==null&&e!==ke&&Oe.length!==0&&P.current?.(`structural`)},[C,Oe.length,ke]);let je=Z.useMemo(()=>S===`edit`||S===`multiedit`||S===`apply_patch`?yO(L):null,[L,S]),Me=Z.useMemo(()=>S===`write`?bO(z):null,[z,S]),Ne=S===`apply_patch`&&Array.isArray(L?.files)&&(L?.files).length>1,Pe=S===e.tool?e:{...e,tool:S},Fe=PO(Pe,c,x),Ie=IO(Pe,c,x),Le=Hl(S||e.tool,h),Re=Dr(C?ae:void 0,x),ze=Dr(C?ae:void 0),Be=C?oO(z,L,R,Re??ze):void 0,Ve=EE({isTaskTool:C,isFinalized:D,taskSessionId:ae,taskAgentName:Be,displayName:Le,delegatingLabel:h(`chat.assistantStatus.delegatingTask`),formatName:sO}),He=C&&Ve.isDelegating,Ue=Ve.title,We=typeof e.sessionID==`string`?e.sessionID.trim():``,Ge=Z.useMemo(()=>{if(!C||!We)return null;let n=typeof ae==`string`&&ae.trim().length>0?ae.trim():void 0,r=typeof e.id==`string`&&e.id.trim().length>0?e.id.trim():void 0,i=typeof e.messageID==`string`&&e.messageID.trim().length>0?e.messageID.trim():typeof t==`string`&&t.trim().length>0?t.trim():void 0;return{sessionID:We,...r?{partID:r}:{},...i?{messageID:i}:{},...x?{directory:x}:{},directoryPresent:!!x,childSessionPresent:!!n,...n?{childSessionID:n}:{},...E?{toolStatus:E}:{},finalized:D,backgroundRunning:ve,effectiveActive:Te,suppressLoading:we,delegating:He,childStatus:wi(pe),parentStatus:wi(me),idleConfirmed:_e,navigateCapability:b.capabilities.navigateNestedSession,surfaceKind:b.kind,...typeof ne==`number`?{taskStartedAt:ne}:{},...typeof he==`number`?{statusObservedAt:he}:{},...typeof ge==`number`?{statusSnapshotAt:ge}:{}}},[_e,pe,x,Te,ne,He,D,C,t,We,me,e.id,e.messageID,b.capabilities.navigateNestedSession,b.kind,E,he,ge,we,ve,ae]),Ke=Ge?Ra(Ge):``,qe=Z.useRef(Ge);qe.current=Ge,Z.useEffect(()=>{let e=qe.current;!e||!Ke||Oa(e)},[Ke]);let Je=q((e,t)=>{let n=qe.current;n&&ga({...n,opened:e,clickSource:t})}),Ye=He?{"data-delegating":`true`}:void 0,Xe=Z.useMemo(()=>{if(S===`bash`||S===`apply_patch`||S===`lsp`||Fe&&(S===`apply_patch`||S===`edit`||S===`multiedit`||S===`write`))return null;let e=I.title;if(typeof e==`string`&&e.trim().length>0)return e;let t=z?.description;return typeof t==`string`&&t.trim().length>0?t:null},[Fe,S,I,z]),Ze=Z.useContext(ac),Qe=Z.useRef(!1),$e=q(e=>{let t=e??ae;return!t||!x?!1:(Qe.current=!1,Vy(b,t,x,()=>{if(!ma({sessionId:t,directory:x})){if(i||Ze?.runtime.isVSCode){v(t,x);return}d(x,{mode:`chat`,dedupeKey:`session:${t}`,label:Ue,readOnly:!0})}}))});Z.useEffect(()=>{!Qe.current||!ae||Je($e(ae),`queued-effect`)},[ae]);let et=n=>{if(C){n.stopPropagation();let e=b.capabilities.navigateNestedSession,t=e?$e():!1;Je(t,`row`),e&&!t&&(Qe.current=!0);return}if(T&&!x)return;let a,o,s;if(S===`edit`||S===`multiedit`||S===`apply_patch`)a=AO(S,z,L),o=CO(S,L,typeof a==`string`?a:void 0),typeof a==`string`&&(s=wO(S,L,a));else if([`write`,`create`,`file_write`].includes(S))a=z?.filePath||z?.file_path||z?.path||L?.filePath||L?.file_path||L?.path,o=1,typeof a==`string`&&typeof z?.content==`string`&&(s=SO(a,z.content));else if(S===`lsp`){a=z?.filePath||z?.file_path||z?.path;let e=z?.line;o=typeof e==`number`&&Number.isFinite(e)?Math.trunc(e):void 0}if(typeof a==`string`){n.stopPropagation();let r=ru(x,a)||(a.startsWith(`/`)?a:x.endsWith(`/`)?x+a:`${x}/${a}`);if(T){let e=EO(r,x),n=s?gD(S,L,s,e,e=>EO(e,x)):[],a=hO(S)&&n.length===1&&n[0]?[{path:e,patch:n[0].patch}]:n.map(e=>({path:e.title,patch:e.patch}));if(Ze?.runtime.isVSCode&&Ze.editor&&s){let t=`${e} (changes)`;Ze.editor.openDiff(``,r,t,{line:o,patch:s});return}if(tu(r,x)){y?a.length>0?y.openToolDiff({diffPath:e,patches:a,targetLine:o}):S===`apply_patch`?y.openTurnDiff(t,b.sessionId):y.openChanges({diffPath:e,staged:!1,targetLine:o}):i?m(e,!1,hO(S)?`working`:`turn`,o):a.length>0?p(x,e,a,o,t,b.sessionId):f(x,e,!1,hO(S)?`working`:`turn`,o,t,b.sessionId);return}if(Ze?.editor){Ze.editor.openFile(r,o);return}Vu(r,x).then(()=>{let e=g.getState(),t=iu(x,r);if(typeof o==`number`&&Number.isFinite(o)){e.openContextFileAtLine(t,r,Math.max(1,Math.trunc(o)),1);return}e.openContextFile(t,r)});return}if(S===`lsp`){if(Ze?.editor){Ze.editor.openFile(r,o);return}let e=()=>{let e=g.getState(),t=iu(x,r);if(typeof o==`number`&&Number.isFinite(o)){e.openContextFileAtLine(t,r,Math.max(1,Math.trunc(o)),1);return}e.openContextFile(t,r)};if(!tu(r,x)){Vu(r,x).then(e);return}e();return}if(Ze?.editor){if(Ze.runtime.isVSCode&&s&&(e.tool===`edit`||e.tool===`multiedit`||e.tool===`apply_patch`)){let e=`${EO(r,x)} (changes)`;Ze.editor.openDiff(``,r,e,{line:o,patch:s});return}Ze.editor.openFile(r,o);return}}if(S===`apply_patch`&&y){n.stopPropagation(),y.openTurnDiff(t,b.sessionId);return}if(S===`apply_patch`&&x&&!y&&!i&&!Ze?.runtime.isVSCode){n.stopPropagation(),d(x,{mode:`diff`,diffScope:`turn`,diffTurnMessageId:t,diffSessionId:b.sessionId});return}T||r(e.id)},tt=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),et(e))},nt=!C&&O?$O:ek,rt=!C&&O?tk:nk,it=C&&u&&(Oe.length>0||Te||De||!!ae),at=!C&&!T&&n;return!De&&!Ce&&!C?null:(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:Y(`group/tool flex gap-1.5 cursor-pointer`,gv,C&&`hover:!bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)]`,Ne?`flex-wrap items-start`:`items-center`),"data-mobile-press-feedback":`soft`,...Ye,onClick:et,onKeyDown:tt,role:`button`,tabIndex:0,children:[(0,$.jsxs)(`div`,{className:Y(`flex gap-1.5`,Ne?`w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5`:`items-center flex-shrink-0`),children:[(0,$.jsx)(`div`,{className:Y(`relative flex-shrink-0`,i?`size-4`:`size-3.5`),children:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,style:C&&Ve.showAvatar?void 0:nt,children:C&&Ve.showAvatar?(0,$.jsx)(vo,{name:e.id||Be||`subagent`,size:14,label:Ue}):Te?(0,$.jsx)(FD,{isMobile:i,className:`text-[var(--tools-icon)]`,label:h(`chat.assistantStatus.usingTool`,{tool:Ue})}):JT(S||e.tool)})}),Ne?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:Y(tO,`flex-shrink-0`),style:rt,title:Le,children:Le}),lO(L,s,l)]}):(0,$.jsxs)($.Fragment,{children:[Ee?(0,$.jsx)(`span`,{className:Y(tO,`shrink-0 whitespace-nowrap animate-text-shimmer`),style:{color:`var(--tools-title)`,"--oc-text-shimmer-base":`var(--tools-title)`},title:Ue,children:Ue}):(0,$.jsx)(`span`,{className:Y(tO,`shrink-0 whitespace-nowrap`),style:rt,title:Ue,children:Ue}),S===`bash`&&typeof ne==`number`?(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums text-muted-foreground/80`,nO),children:(0,$.jsx)(_O,{start:ne,end:typeof Se==`number`?Se:void 0,active:!!(Te&&typeof Se!=`number`)})}):null]})]}),!Ne&&(0,$.jsx)(`div`,{className:Y(`flex items-center gap-1 flex-1 min-w-0`,nO),style:{color:`var(--tools-description)`},children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1 flex-1 min-w-0`,children:[Xe&&(0,$.jsx)(`span`,{className:Y(`min-w-0 truncate`,nO,Ee&&`animate-text-shimmer`),style:{color:Ee?`var(--tools-title)`:`var(--tools-description)`,...Ee?{"--oc-text-shimmer-base":`var(--tools-title)`}:{opacity:.8}},title:Xe,children:Xe}),!Xe&&S===`lsp`&&Fe?ik(Fe,s,!1,l):null,!Xe&&S!==`lsp`&&Ie&&(Fe&&Ie===Fe?ik(Fe,s,!1,l):(0,$.jsx)(qT,{variant:s?`generate-effect`:`static`,className:Y(`min-w-0 truncate`,nO),style:{color:`var(--tools-description)`},title:Ie,children:Ie})),je&&(0,$.jsxs)(`span`,{className:`flex-shrink-0 inline-flex items-center gap-0 typography-meta`,children:[(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,je.added]}),(0,$.jsx)(`span`,{style:{color:`var(--tools-description)`},children:`/`}),(0,$.jsxs)(`span`,{style:{color:`var(--status-error)`},children:[`-`,je.removed]})]}),Me&&(0,$.jsx)(`span`,{className:`flex-shrink-0 inline-flex items-center gap-0 typography-meta`,children:(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,Me]})})]})}),!T&&(!C||u)?(0,$.jsx)(`span`,{className:`ml-auto inline-flex size-3.5 flex-shrink-0 items-center justify-center text-muted-foreground opacity-70`,onClick:C?t=>{t.stopPropagation(),r(e.id)}:void 0,children:(0,$.jsx)(X,{name:n?`arrow-down-s`:`arrow-right-s`,className:`size-3.5`})}):null]}),it?(0,$.jsx)(JO,{entries:Oe,isExpanded:n,isMobile:i,output:G,sessionId:ae,onShowPopup:o,input:z,animateTailText:s,isActive:Te}):null,!C&&!T&&n?(0,$.jsx)(`div`,{ref:F,"aria-hidden":!1,style:{height:`auto`,overflow:`visible`,overflowAnchor:`none`},children:at?(0,$.jsxs)(`div`,{className:w?`relative ml-0.5 pl-1.5`:TD,children:[(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)`}}),(0,$.jsx)(ck,{part:e,state:c,currentDirectory:x,isExpanded:n,isMobile:i,onShowPopup:o})]}):null}):null]})},uk=class extends Z.Component{state={hasError:!1};static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidUpdate(e){e.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:!1,error:void 0})}componentDidCatch(e){}render(){if(!this.state.hasError)return this.props.children;let e=this.state.error?.message;return(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-1.5 min-w-0`,pv),children:[(0,$.jsx)(`div`,{className:`h-3.5 w-3.5 flex-shrink-0`,style:$O,children:JT(this.props.toolName)}),(0,$.jsx)(`span`,{className:Y(tO,`flex-shrink-0`),style:tk,children:this.props.displayName}),e?(0,$.jsxs)(`span`,{className:Y(nO,`min-w-0 truncate`),style:{color:`var(--tools-description)`},title:e,children:[this.props.errorLabel,`: `,e]}):null]})}},dk=Z.memo(e=>{let t=(0,Q.c)(30),{t:n}=Zt(),r=wD(),i,a;t[0]!==e.part.tool||t[1]!==n?(a=uO(e.part.tool)||`tool`,i=Hl(a,n),t[0]=e.part.tool,t[1]=n,t[2]=i,t[3]=a):(i=t[2],a=t[3]);let o=i,s;t[4]!==r||t[5]!==e.part.id?(s=()=>!r||cO.get(e.part.id)===!0,t[4]=r,t[5]=e.part.id,t[6]=s):s=t[6];let[c,l]=Z.useState(s),u,d;if(t[7]!==r||t[8]!==c||t[9]!==e.part.id?(u=()=>{if(!(!r||c))return Kl(()=>{cO.set(e.part.id,!0,e.part.id.length*2+8),Z.startTransition(()=>{l(!0)})})},d=[r,c,e.part.id],t[7]=r,t[8]=c,t[9]=e.part.id,t[10]=u,t[11]=d):(u=t[10],d=t[11]),Z.useEffect(u,d),!c){let e,n,r;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(e=Y(`flex min-w-0 items-center gap-2`,pv),n=(0,$.jsx)(`span`,{className:`h-3.5 w-3.5 shrink-0 rounded bg-muted/50`,"aria-hidden":`true`}),r=Y(tO,`shrink-0 text-muted-foreground`),t[12]=e,t[13]=n,t[14]=r):(e=t[12],n=t[13],r=t[14]);let i;t[15]===o?i=t[16]:(i=(0,$.jsx)(`span`,{className:r,children:o}),t[15]=o,t[16]=i);let a;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(`span`,{className:`h-3 w-24 min-w-0 rounded bg-muted/40`,"aria-hidden":`true`}),t[17]=a):a=t[17];let s;return t[18]===i?s=t[19]:(s=(0,$.jsxs)(`div`,{className:e,children:[n,i,a]}),t[18]=i,t[19]=s),s}let f;t[20]===n?f=t[21]:(f=n(`chat.toolPart.error`),t[20]=n,t[21]=f);let p;t[22]===e?p=t[23]:(p=(0,$.jsx)(lk,{...e}),t[22]=e,t[23]=p);let m;return t[24]!==o||t[25]!==e.part||t[26]!==f||t[27]!==p||t[28]!==a?(m=(0,$.jsx)(uk,{displayName:o,errorLabel:f,resetKey:e.part,toolName:a,children:p}),t[24]=o,t[25]=e.part,t[26]=f,t[27]=p,t[28]=a,t[29]=m):m=t[29],m},(e,t)=>FE([e.part],[t.part])&&e.messageId===t.messageId&&e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.alwaysShowActions===t.alwaysShowActions&&e.onContentChange===t.onContentChange&&e.onShowPopup===t.onShowPopup&&e.animateTailText===t.animateTailText);function fk(e){return e.stopPropagation()}function pk(e){return e.stopPropagation()}function mk(e){return e.stopPropagation()}function hk(e){return e.setCurrentSession}function gk(e){return e.openContextPanelTab}function _k(e){return e.showToolFileIcons}function vk(e){return e.stopPropagation()}function yk(e){return e.stopPropagation()}function bk(e){return!e}var xk=(e,t,n)=>{let r=t-e;return Math.max(0,n-r)},Sk=e=>{e.timer&&=(clearTimeout(e.timer),null)},Ck=({text:e,isStreaming:t,throttleMs:n=Xl(Tt()).textThrottleMs,identityKey:r})=>{let[i,a]=Z.useState(e),o=Z.useRef(e),s=Z.useRef(i),c=Z.useRef({timer:null,pendingText:e,lastEmitAt:0});return Z.useEffect(()=>{o.current=e},[e]),Z.useEffect(()=>{s.current=i},[i]),Z.useEffect(()=>{let e=c.current;Sk(e),e.pendingText=o.current,e.lastEmitAt=0,a(o.current)},[r]),Z.useEffect(()=>{let r=c.current;r.pendingText=e;let i=s.current,o=t&&i.length>e.length?i:e;if(!t){Sk(r),r.lastEmitAt=Date.now(),a(o);return}let l=Date.now(),u=xk(r.lastEmitAt,l,n);if(u<=0){Sk(r),r.lastEmitAt=l,a(o);return}return Sk(r),r.timer=setTimeout(()=>{r.timer=null,r.lastEmitAt=Date.now(),a(e=>t&&e.length>r.pendingText.length?e:r.pendingText)},u),()=>{Sk(r)}},[t,e,n]),Z.useEffect(()=>{let e=c.current;return()=>{Sk(e)}},[]),i},wk=e=>e.isStreaming?e.throttledTextContent:e.textContent,Tk=e=>!e.isFinalized&&e.displayTextContent.trim().length===0?!1:e.displayTextContent.trim().length>0,Ek=e=>{let t=(0,Q.c)(44),{result:n}=e,{t:r}=Zt(),[i,a]=Z.useState(!1),o=Z.useRef(null),s,c;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>()=>{o.current!==null&&window.clearTimeout(o.current)},c=[],t[0]=s,t[1]=c):(s=t[0],c=t[1]),Z.useEffect(s,c);let l;bb0:{if(n.kind===`commit`){let e;t[2]!==n.highlights||t[3]!==n.subject?(e=[n.subject,...n.highlights.map(Dk)],t[2]=n.highlights,t[3]=n.subject,t[4]=e):e=t[4],l=e.join(`
6562
6562
  `);break bb0}let e;t[5]!==n.body||t[6]!==n.title?(e=[n.title,n.body].filter(Boolean),t[5]=n.body,t[6]=n.title,t[7]=e):e=t[7],l=e.join(`
6563
6563
 
6564
6564
  `)}let u=l,d;t[8]!==u||t[9]!==n.raw?(d=async()=>{(await en(u||n.raw)).ok&&(o.current!==null&&window.clearTimeout(o.current),a(!0),o.current=window.setTimeout(()=>{o.current=null,a(!1)},2e3))},t[8]=u,t[9]=n.raw,t[10]=d):d=t[10];let f=q(d),p;t[11]!==n.kind||t[12]!==r?(p=n.kind===`commit`?r(`chat.generatedResult.commit.title`):r(`chat.generatedResult.pullRequest.title`),t[11]=n.kind,t[12]=r,t[13]=p):p=t[13];let m;t[14]===p?m=t[15]:(m=(0,$.jsx)(`span`,{className:`font-mono text-[13px] text-muted-foreground`,children:p}),t[14]=p,t[15]=m);let h;t[16]===f?h=t[17]:(h=()=>{f()},t[16]=f,t[17]=h);let g;t[18]!==i||t[19]!==r?(g=r(i?`chat.generatedResult.actions.copied`:`chat.generatedResult.actions.copy`),t[18]=i,t[19]=r,t[20]=g):g=t[20];let _;t[21]!==i||t[22]!==r?(_=r(i?`chat.generatedResult.actions.copied`:`chat.generatedResult.actions.copy`),t[21]=i,t[22]=r,t[23]=_):_=t[23];let v;t[24]===i?v=t[25]:(v=i?(0,$.jsx)(X,{name:`check`,className:`size-3.5`}):(0,$.jsx)(X,{name:`file-copy`,className:`size-3.5`}),t[24]=i,t[25]=v);let y;t[26]!==v||t[27]!==h||t[28]!==g||t[29]!==_?(y=(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`xs`,onClick:h,title:g,"aria-label":_,className:`text-muted-foreground hover:text-foreground md:opacity-0 md:group-hover:opacity-100`,children:v}),t[26]=v,t[27]=h,t[28]=g,t[29]=_,t[30]=y):y=t[30];let b;t[31]!==y||t[32]!==m?(b=(0,$.jsxs)(`div`,{className:`flex items-center justify-between border-b border-border/70 px-3 py-1.5`,children:[m,y]}),t[31]=y,t[32]=m,t[33]=b):b=t[33];let x;t[34]!==n.body||t[35]!==n.highlights||t[36]!==n.kind||t[37]!==n.subject||t[38]!==n.title||t[39]!==r?(x=(0,$.jsx)(`div`,{className:`space-y-3 px-3 py-3`,children:n.kind===`commit`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`typography-ui-label text-foreground`,children:n.subject}),n.highlights.length>0?(0,$.jsx)(`ul`,{className:`space-y-1 text-sm text-muted-foreground`,children:n.highlights.map(Ok)}):null]}):(0,$.jsxs)($.Fragment,{children:[n.title?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`typography-micro uppercase tracking-[0.12em] text-muted-foreground`,children:r(`chat.generatedResult.pullRequest.titleLabel`)}),(0,$.jsx)(`div`,{className:`mt-1 typography-ui-label text-foreground`,children:n.title})]}):null,n.body?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`typography-micro uppercase tracking-[0.12em] text-muted-foreground`,children:r(`chat.generatedResult.pullRequest.bodyLabel`)}),(0,$.jsx)(`pre`,{className:`mt-1 whitespace-pre-wrap break-words text-sm leading-relaxed text-muted-foreground font-sans`,children:n.body})]}):null]})}),t[34]=n.body,t[35]=n.highlights,t[36]=n.kind,t[37]=n.subject,t[38]=n.title,t[39]=r,t[40]=x):x=t[40];let S;return t[41]!==b||t[42]!==x?(S=(0,$.jsxs)(`div`,{"data-component":`generated-json-result`,className:`my-4 group overflow-hidden rounded-2xl border border-border/80 bg-[var(--surface-elevated)]`,children:[b,x]}),t[41]=b,t[42]=x,t[43]=S):S=t[43],S};function Dk(e){return`- ${e}`}function Ok(e,t){return(0,$.jsxs)(`li`,{className:`flex gap-2`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground/70`,children:`-`}),(0,$.jsx)(`span`,{children:e})]},`${t}-${e}`)}var kk=e=>{let t=e.trim(),n=[],r=t.match(/^```(?:json)?\s*([\s\S]*?)```$/i);r?.[1]&&n.push(r[1].trim()),t.startsWith(`{`)&&t.endsWith(`}`)&&n.push(t);let i=[];for(let e of n)try{let t=JSON.parse(e);t&&typeof t==`object`&&!Array.isArray(t)&&i.push(t)}catch{}return i},Ak=e=>{for(let t of kk(e)){let e=typeof t.subject==`string`?t.subject.trim():``,n=Array.isArray(t.highlights)?t.highlights.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean).slice(0,3):[];if(e)return{kind:`commit`,subject:e,highlights:n,raw:JSON.stringify({subject:e,highlights:n},null,2)};let r=typeof t.title==`string`?t.title.trim():``,i=typeof t.body==`string`?t.body.trim():``;if(r||i)return{kind:`pr`,title:r,body:i,raw:JSON.stringify({title:r,body:i},null,2)}}return null},jk=Z.memo(e=>{let t=(0,Q.c)(32),{part:n,sessionId:r,messageId:i,streamPhase:a,chatRenderMode:o,allowSortedFinalStreaming:s,hasStreamingHapticLifecycle:c,onShowPopup:l}=e,u=o===void 0?`live`:o,d=s!==void 0&&s,f=c!==void 0&&c,p=n,m=[typeof p.text==`string`?p.text:``,typeof p.content==`string`?p.content:``,typeof p.value==`string`?p.value:``].reduce(Mk,``),h=(u===`live`||d)&&(a===`streaming`||a===`cooldown`);Ct(`ui.assistant_text_part.render`),h&&Ct(`ui.assistant_text_part.render.streaming`);let g=wk({textContent:m,throttledTextContent:Ck({text:m,isStreaming:h,identityKey:`${i}:${n.id??`text`}`}),isStreaming:h}),_=`${i}:${n.id??`text`}`,v=Z.useRef(null),y,b;t[0]!==g||t[1]!==_||t[2]!==f||t[3]!==i||t[4]!==n.id||t[5]!==n.type||t[6]!==r?(y=()=>{if(!Pr())return;let e=n.type===`text`||n.type===`reasoning`,t=$a(v.current,{identity:_,content:g,isActive:f&&e,mode:n.type===`reasoning`?`appearance`:`changes`});v.current=t.nextState,!(!t.shouldEmit||!r)&&xi({sessionID:r,messageID:i,partID:n.id,kind:n.type===`reasoning`?`thinking`:`text`})},b=[g,_,f,i,n.id,n.type,r],t[0]=g,t[1]=_,t[2]=f,t[3]=i,t[4]=n.id,t[5]=n.type,t[6]=r,t[7]=y,t[8]=b):(y=t[7],b=t[8]),Z.useEffect(y,b),St(`ui.assistant_text_part.display_len`,g.length);let x=p.time,S=!!(x&&x.end!==void 0);if(n.type!==`text`&&n.type!==`reasoning`||!Tk({displayTextContent:g,isFinalized:S}))return null;let C;t[9]!==g||t[10]!==S||t[11]!==h?(C=!h&&S?Ak(g):null,t[9]=g,t[10]=S,t[11]=h,t[12]=C):C=t[12];let w=C;if(w){let e=`group/assistant-text relative break-words ${u===`live`?`my-1`:``}`,r=n.id||`${i}-text`,a;t[13]===w?a=t[14]:(a=(0,$.jsx)(Ek,{result:w}),t[13]=w,t[14]=a);let o;return t[15]!==e||t[16]!==r||t[17]!==a?(o=(0,$.jsx)(`div`,{className:e,children:a},r),t[15]=e,t[16]=r,t[17]=a,t[18]=o):o=t[18],o}let T=`group/assistant-text relative break-words ${u===`live`?`my-1`:``}`,E=n.id||`${i}-text`,D=u===`sorted`&&!d,O=n.type===`reasoning`?`reasoning`:`assistant`,k;t[19]!==g||t[20]!==S||t[21]!==h||t[22]!==i||t[23]!==l||t[24]!==n||t[25]!==O||t[26]!==D?(k=(0,$.jsx)(bl,{content:g,part:n,messageId:i,isAnimated:!1,isStreaming:h,disableStreamAnimation:D,variant:O,enableFileReferences:S,onShowPopup:l}),t[19]=g,t[20]=S,t[21]=h,t[22]=i,t[23]=l,t[24]=n,t[25]=O,t[26]=D,t[27]=k):k=t[27];let A;return t[28]!==k||t[29]!==T||t[30]!==E?(A=(0,$.jsx)(`div`,{className:T,children:k},E),t[28]=k,t[29]=T,t[30]=E,t[31]=A):A=t[31],A});function Mk(e,t){return t.length>e.length?t:e}var Nk=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,Pk=Y(`typography-meta font-medium`,Nk),Fk=Y(`typography-meta`,Nk),Ik=e=>typeof e!=`string`||e.trim().length===0?``:e.split(`
@@ -6573,7 +6573,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,C as n,E as r,J
6573
6573
 
6574
6574
  `):AA(Array.from(t.childNodes).map(e=>FA(e)).join(``))},RA=e=>Array.from(e.childNodes).every(e=>{if(e.nodeType===Node.TEXT_NODE||e.nodeType!==Node.ELEMENT_NODE)return!0;let t=e;return!OA.has(t.tagName.toLowerCase())}),zA=(e,t)=>{let n=e.cloneContents();if(RA(n)){let e=AA(Array.from(n.childNodes).map(e=>FA(e)).join(``));if(e)return e}return Array.from(n.childNodes).map(e=>LA(e)).filter(e=>e.length>0).join(`
6575
6575
 
6576
- `).trim()||AA(t)},BA=({containerRef:e})=>{let{t}=Zt(),[n,r]=Z.useState({x:0,y:0,show:!1}),[i,a]=Z.useState(``),[o,s]=Z.useState(``),c=Z.useRef(!1),[l,u]=Z.useState(!1),d=Z.useRef(null),f=Z.useRef(EA),p=Z.useRef(null),m=Z.useRef(null),h=Z.useRef(null),_=Z.useRef(!1),v=J(e=>e.createSession),y=Ja(e=>e.setPendingInputText),b=g(e=>e.isMobile),x=By(zy()).textSelectionMutation;Z.useEffect(()=>{_.current=n.show},[n.show]),Z.useEffect(()=>()=>{m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),h.current!==null&&(window.clearTimeout(h.current),h.current=null)},[]);let S=Z.useCallback(()=>{p.current=null,DA===S&&(DA=null),_.current&&=(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),u(!1),r(e=>({...e,show:!1})),a(``),s(``),!1)},[]);Z.useEffect(()=>()=>{DA===S&&(DA=null)},[S]);let C=Z.useCallback(e=>{if(typeof window>`u`)return e;let t=window.innerWidth,n=f.current/2,r=TA+n,i=t-TA-n;return r>i?t/2:Math.min(Math.max(e,r),i)},[]),w=Z.useCallback(()=>{if(!p.current)return;DA!==S&&(DA?.(),DA=S);let{plainText:e,markdownText:t,rect:i}=p.current,o=!n.show,c=b?i.left+i.width/2:C(i.left+i.width/2),l=i.top-10;a(e),s(t),r({x:c,y:l,show:!0}),_.current=!0,o&&(u(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{u(!1),m.current=null}))},[C,S,b,n.show]);Z.useLayoutEffect(()=>{if(!n.show||b||!d.current)return;let e=d.current.offsetWidth;!Number.isFinite(e)||e<=0||e===f.current||(f.current=e,r(e=>({...e,x:C(e.x)})))},[C,b,n.show]),Z.useEffect(()=>{if(!n.show||b)return;let e=()=>{r(e=>({...e,x:C(e.x)}))};return window.addEventListener(`resize`,e),()=>{window.removeEventListener(`resize`,e)}},[C,b,n.show]);let T=Z.useCallback(()=>{let t=window.getSelection(),n=e.current;if(!t||!n){c.current||S();return}let r=AA(t.toString());if(!r){c.current||S();return}let i=NA(t,n);if(!i){c.current||S();return}let a=i.getBoundingClientRect();p.current={plainText:r,markdownText:zA(i,r),rect:a},c.current||w()},[e,S,w]);Z.useEffect(()=>{let t=e.current;if(!t)return;let n=()=>{c.current=!0,S()},r=()=>{c.current=!1,h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{h.current=null,T()},10)},i=new Set,a=()=>{for(let e of MA(t))i.has(e)||(i.add(e),e.addEventListener(`selectionchange`,T))};a();let o=new MutationObserver(a);o.observe(t,{childList:!0,subtree:!0}),document.addEventListener(`selectionchange`,T),t.addEventListener(`mousedown`,n),document.addEventListener(`mouseup`,r);let s=e=>{d.current&&!d.current.contains(e.target)&&!window.getSelection()?.toString().trim()&&S()};return document.addEventListener(`mousedown`,s),()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),o.disconnect();for(let e of i)e.removeEventListener(`selectionchange`,T);document.removeEventListener(`selectionchange`,T),t.removeEventListener(`mousedown`,n),document.removeEventListener(`mouseup`,r),document.removeEventListener(`mousedown`,s)}},[e,T,S,w]),Z.useEffect(()=>{if(!n.show)return;let e=e=>{d.current&&e.target instanceof Node&&d.current.contains(e.target)||S()};return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),()=>{window.removeEventListener(`scroll`,e,!0)}},[n.show,S]);let E=Z.useCallback(e=>{if(!e)return;let t=`\`\`\`md\n${e}\n\`\`\``;y(t,`append`),S(),window.getSelection()?.removeAllRanges()},[y,S]),D=Z.useCallback(()=>{E(o)},[E,o]);Z.useEffect(()=>{let t=t=>{if(!x||!t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||t.key.toLowerCase()!==`i`)return;let n=window.getSelection(),r=e.current;if(!n||!r||!n.toString().trim())return;let i=NA(n,r);i&&(t.preventDefault(),E(zA(i,n.toString())))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[E,x,e]);let O=Z.useCallback(async()=>{i&&(await v(void 0,null,null)&&y(i,`replace`),S(),window.getSelection()?.removeAllRanges())},[i,v,y,S]),k=Z.useCallback(async()=>{if(!i)return;let e=await en(i);e.ok||console.error(`Failed to copy:`,e.error),S(),window.getSelection()?.removeAllRanges()},[i,S]);return n.show?b?(0,ef.createPortal)((0,$.jsx)(`div`,{ref:d,className:Y(`fixed left-3 right-3 bottom-0 z-50 mx-auto max-w-[420px]`,`rounded-2xl border border-[var(--interactive-border)]`,`bg-[var(--surface-elevated)] p-2 shadow-lg`,`safe-area-bottom`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,l?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),style:{bottom:`calc(0.5rem + env(safe-area-inset-bottom, 0px))`},children:(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[x?(0,$.jsxs)(`button`,{onClick:D,className:Y(`flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--primary-base)] text-[var(--primary-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.title.addToCurrentChat`),type:`button`,children:[(0,$.jsx)(X,{name:`add`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.addToChat`)})]}):null,x?(0,$.jsxs)(`button`,{onClick:O,className:Y(`flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.title.newSessionWithSelection`),type:`button`,children:[(0,$.jsx)(X,{name:`chat-new`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.newSession`)})]}):null,(0,$.jsxs)(`button`,{onClick:k,className:Y(`col-span-2 flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--surface-muted)] text-[var(--surface-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.actions.copy`),type:`button`,children:[(0,$.jsx)(X,{name:`file-copy`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.copy`)})]})]})}),document.body):(0,ef.createPortal)((0,$.jsx)(`div`,{ref:d,className:`fixed z-50`,style:{left:n.x,top:n.y,transform:`translate(-50%, -100%)`},children:(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-1 whitespace-nowrap`,`rounded-lg border border-[var(--interactive-border)]`,`bg-[var(--surface-elevated)] shadow-none`,`px-1.5 py-1`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,l?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),children:[x?(0,$.jsxs)(`button`,{onClick:D,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.title.addToCurrentChat`),type:`button`,children:[(0,$.jsx)(X,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.addToChat`)}),(0,$.jsx)(Q_,{shortcut:`⌘+I`})]}):null,x?(0,$.jsx)(`div`,{className:`w-px h-4 bg-[var(--interactive-border)]`}):null,x?(0,$.jsxs)(`button`,{onClick:O,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.title.newSessionWithSelection`),type:`button`,children:[(0,$.jsx)(X,{name:`chat-new`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.newSession`)})]}):null,x?(0,$.jsx)(`div`,{className:`w-px h-4 bg-[var(--interactive-border)]`}):null,(0,$.jsxs)(`button`,{onClick:k,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.actions.copy`),type:`button`,children:[(0,$.jsx)(X,{name:`file-copy`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.copy`)})]})]})}),document.body):null},VA=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),HA=(e,t)=>{let n=new Date(t);return n.setDate(t.getDate()-1),VA(e,n)},UA=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),WA=(e,t)=>{if(!UA(e))return``;let n=new Date(e),r=new Date,i=ys(n,t),a=Qt(),o=tn.getState().dictionary;if(VA(n,r))return i;if(HA(n,r))return nn(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}`},GA=e=>typeof e!=`number`||!Number.isFinite(e)||e<0?0:e,KA=e=>e,qA=e=>{if(!Array.isArray(e)||e.length===0)return 0;let t=0;for(let n of e){let e=KA(n);if(e.type!==`tool`)continue;let r=e.state,i=r?.time?.start,a=r?.time?.end;typeof i!=`number`||!Number.isFinite(i)||typeof a!=`number`||!Number.isFinite(a)||a<i||(t+=a-i)}return t},JA=(e,t,n,r)=>{let i=(typeof e==`number`&&Number.isFinite(e)&&e>0&&typeof t==`number`&&Number.isFinite(t)&&t>e?t-e:null)??(typeof r==`number`&&Number.isFinite(r)&&r>0?r:null);if(i===null)return null;let a=i-qA(n);return!Number.isFinite(a)||a<=0?null:a},YA=e=>{let t=JA(e.createdAt,e.completedAt,e.parts,e.fallbackDurationMs);if(t===null)return null;let n=GA(e.outputTokens)+GA(e.reasoningTokens);if(n<=0)return null;let r=t/1e3;if(r<=0)return null;let i=n/r;return!Number.isFinite(i)||i<=0?null:i},XA=e=>{if(!Number.isFinite(e)||e<=0)return``;if(e>=1e3){let t=e/1e3;return`${t>=10?t.toFixed(0):t.toFixed(1)}k tok/s`}return e>=100?`${Math.round(e)} tok/s`:e>=10?`${e.toFixed(1)} tok/s`:`${e.toFixed(2)} tok/s`},ZA=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=Y(`oc-summary-flip-viewport relative block h-5 min-h-0 w-full min-w-0 max-w-full overflow-clip sm:h-6`,i),t[5]=i,t[6]=m);let h=c&&`invisible`,g;t[7]===h?g=t[8]:(g=Y(`block h-full min-w-0 truncate leading-5 sm:leading-6`,h),t[7]=h,t[8]=g);let _;t[9]!==o||t[10]!==g?(_=(0,$.jsx)(`span`,{className:g,children:o}),t[9]=o,t[10]=g,t[11]=_):_=t[11];let v;t[12]!==o||t[13]!==p||t[14]!==c?(v=c?(0,$.jsxs)(`span`,{className:`oc-summary-flip-stage absolute inset-0 block overflow-clip`,children:[(0,$.jsx)(`span`,{className:`oc-summary-flip-out absolute inset-x-0 top-0 block h-full truncate`,"aria-hidden":`true`,children:c}),(0,$.jsx)(`span`,{className:`oc-summary-flip-in absolute inset-x-0 top-0 block h-full truncate`,onAnimationEnd:p,children:o})]}):null,t[12]=o,t[13]=p,t[14]=c,t[15]=v):v=t[15];let y;return t[16]!==m||t[17]!==_||t[18]!==v?(y=(0,$.jsxs)(`span`,{className:m,children:[_,v]}),t[16]=m,t[17]=_,t[18]=v,t[19]=y):y=t[19],y},QA=[`search`,`read`,`list`];function $A(e){let t=$D(e);return t===`read`?`read`:t===`glob`||t===`grep`?`search`:t===`list`?`list`:null}function ej(e){let t={read:0,search:0,list:0};for(let n of e){let e=$A(n);e&&(t[e]+=1)}return t}var tj=[`edit`,`command`,`other`],nj=new Set([`edit`,`multiedit`,`write`,`create`,`file_write`,`apply_patch`,`patch`]),rj=new Set([`bash`,`shell`,`cmd`,`command`,`exec`,`terminal`]);function ij(e){if(!YD(e))return null;let t=$D(e);return nj.has(t)?`edit`:rj.has(t)?`command`:`other`}function aj(e){let t={edit:0,command:0,other:0};for(let n of e){let e=ij(n);e&&(t[e]+=1)}return t}function oj(e){return SD(e)}var sj=[...QA,...tj];function cj(e){return{...ej(e),...aj(e)}}function lj(e){return QD(e)}function uj(e){return e.kind===`reasoning`||e.type===`reasoning`?!1:e.kind===`justification`||e.type===`text`?!0:e.kind===`tool`||e.type===`tool`?!XD(e.toolName):e.kind!=null||e.type!=null}function dj(e,t,n){for(let r=t;r<e.length;r+=1)if(uj(n(e[r])))return!0;return!1}function fj(e){return`parts`in e?e.parts.some(e=>lj(e))?!0:!e.hasFollowingOtherType&&e.isTurnLive:e.some(e=>lj(e))}function pj(e,t,n){let r=[],i=t;for(;i<e.length&&XD(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var mj=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,hj=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=Y(`inline-flex flex-none items-center gap-0.5 tabular-nums`,mj),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},gj=({activities:e,isMobile:t,isTurnLive:n=!1,hasFollowingOtherType:r=!1,exploring:i,children:a})=>{let{t:o}=Zt(),[s,c]=Z.useState(!1),l=Z.useId(),u=e.map(e=>e.part),d=i??fj({parts:u,hasFollowingOtherType:r,isTurnLive:n}),f=cj(u.map(e=>e.tool)),p=oj(u),m=sj.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:mv(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":s,"aria-controls":l,"aria-label":_,"data-mobile-press-feedback":`soft`,className:Y(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,gv),onClick:h,onKeyDown:g,children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center self-center`,y,t?`w-4`:`w-3.5`),style:{color:`var(--tools-icon)`},children:d?(0,$.jsx)(FD,{isMobile:t,label:o(`chat.usedGroup.running`),className:`block`}):(0,$.jsx)(X,{name:`search`,className:`block h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:Y(`typography-meta inline-flex flex-none items-center self-center font-medium`,y,mj,d&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...d?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:v}),m?(0,$.jsx)(`span`,{className:Y(`typography-meta inline-flex min-h-0 w-0 min-w-0 max-w-full flex-1 items-center self-center overflow-clip`,y,mj),style:{color:`var(--tools-description)`},children:(0,$.jsx)(ZA,{text:m,active:d,className:t?`!h-5 sm:!h-5`:`!h-6 sm:!h-6`})}):null,(0,$.jsx)(hj,{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:hv(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 _j(e,t,n){let r=[],i=t;for(;i<e.length&&JD(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var vj=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null};function yj(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=vj(n.metadata.name);if(e)return e}if(n.input&&typeof n.input==`object`){let e=n.input,t=vj(e.name);if(t)return t;let r=vj(e.id);if(r)return r}if(n.output&&typeof n.output==`object`){let e=vj(n.output.name);if(e)return e}return null}function bj(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 xj=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,Sj=({activities:e,isMobile:t,children:n})=>{let{t:r}=Zt(),[i,a]=Z.useState(!1),o=Z.useId(),s=e.map(e=>e.part),c=s.some(e=>QD(e)),{joinedVisible:l,hiddenCount:u}=bj(s.map(yj)),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:mv(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":i,"aria-controls":o,"aria-label":m,"data-mobile-press-feedback":`soft`,className:Y(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,gv),onClick:f,onKeyDown:p,children:[(0,$.jsx)(`span`,{className:Y(`flex flex-none items-center justify-center`,t?`size-4`:`size-3.5`),style:{color:`var(--tools-icon)`},children:c?(0,$.jsx)(FD,{isMobile:t,label:h,className:`block`}):(0,$.jsx)(X,{name:`book`,className:`h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:Y(`typography-meta flex-none font-medium`,xj,c&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...c?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:h}),d?(0,$.jsx)(`span`,{className:Y(`typography-meta h-5 min-h-0 w-0 min-w-0 max-w-full flex-1 overflow-clip sm:h-6`,xj),style:{color:`var(--tools-description)`},children:(0,$.jsx)(ZA,{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:hv(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]})},Cj=Z.memo(e=>{let t=(0,Q.c)(18),{part:n,messageId:r,onContentChange:i,actions:a,streamPhase:o,onShowPopup:s}=e,c=g(wj),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`,_,v;if(t[0]!==i||t[1]!==f?(_=()=>{f.trim().length!==0&&i?.(`structural`)},v=[i,f],t[0]=i,t[1]=f,t[2]=_,t[3]=v):(_=t[2],v=t[3]),Z.useEffect(_,v),!f||f.trim().length===0)return null;let y=o??`streaming`,b=h&&typeof p?.end!=`number`,x;t[4]!==c||t[5]!==r||t[6]!==i||t[7]!==s||t[8]!==n||t[9]!==m||t[10]!==y||t[11]!==b?(x=(0,$.jsx)(`div`,{"data-message-text-export-source":`true`,children:(0,$.jsx)(jk,{part:n,sessionId:m,messageId:r,streamPhase:y,chatRenderMode:c,hasStreamingHapticLifecycle:b,onContentChange:i,onShowPopup:s})}),t[4]=c,t[5]=r,t[6]=i,t[7]=s,t[8]=n,t[9]=m,t[10]=y,t[11]=b,t[12]=x):x=t[12];let S;t[13]===a?S=t[14]:(S=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]=S);let C;return t[15]!==x||t[16]!==S?(C=(0,$.jsxs)(`div`,{"data-message-text-export-root":`true`,children:[x,S]}),t[15]=x,t[16]=S,t[17]=C):C=t[17],C});function wj(e){return e.chatRenderMode}var Tj=e=>{let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`},Ej=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,Dj=Y(`typography-meta font-medium`,Ej),Oj=Y(`typography-meta`,Ej),kj=[],Aj=e=>{let t=e.part;return t.slim===!0&&(t.type===`tool`||t.type===`reasoning`||t.type===`file`)},jj=e=>{let t=new Set;for(let n of e)Aj(n)&&n.messageId&&t.add(n.messageId);return[...t]},Mj=(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}),Nj=e=>{let t=(0,Q.c)(5),{href:n}=e,[r,i]=Z.useState(!1),a;t[0]===n?a=t[1]:(a=Rl(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},Pj=e=>e,Fj=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},Ij=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},Lj=e=>{let t=e.part.state?.metadata?.dir;return typeof t==`string`&&t.trim().length>0?t:null},Rj=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},zj=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=Rj(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`}`},Bj=e=>{let t=e.part.state,n=t?.input,r=t?.output;if(Array.isArray(n?.todos)){let e=zj(n.todos);if(e)return e}if(Array.isArray(r)){let e=zj(r);if(e)return e}if(r&&typeof r==`object`&&Array.isArray(r.todos)){let e=zj(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=zj(e);if(t)return t}if(e&&typeof e==`object`&&Array.isArray(e.todos)){let t=zj(e.todos);if(t)return t}}catch{}return null},Vj=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)},Hj=(e,t=!0)=>{let n=e.lastIndexOf(`/`);if(n===-1)return(0,$.jsx)(qT,{variant:t?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,Oj),style:{color:`var(--tools-description)`},title:e,children:e});let r=e.slice(0,n),i=e.slice(n+1),a=r.startsWith(`/`),o=a?r.slice(1):r;return(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex max-w-full flex-1 items-baseline overflow-hidden`,Oj),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)(qT,{variant:t?`generate-effect`:`static`,className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:i})]})},Uj=e=>{let t=eu(e);return t?t.toLowerCase().endsWith(`/skill.md`)?t:`${t}/SKILL.md`:``},Wj=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 yj(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`?Bj(e):Fj(e)},Gj=e=>{let t=[],n=[];for(let r of e){if(r.kind!==`tool`)continue;let e=r.part;if(e.tool?.trim().toLowerCase()!==`task`)continue;let i=typeof e.id==`string`?e.id.trim():``;if(!i)continue;let a=e.state;if(!a||typeof a!=`object`)continue;let o=a;n.push(i),(o.status===`pending`||o.status===`running`)&&t.push(i)}return{active:t,all:n}},Kj=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=mv(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)(dk,{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&&FE([e.activity.part],[t.activity.part])),qj=Z.memo(e=>{let t=(0,Q.c)(9),{toolName:n,activities:r,isMobile:i}=e,a;t[0]===i?a=t[1]:(a=mv(i),t[0]=i,t[1]=a);let o;t[2]!==r||t[3]!==i||t[4]!==n?(o=(0,$.jsx)(Xj,{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&&Yj(e.activities,t.activities)),Jj=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.kind===`reasoning`){if(!Ua(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(XD(i)){let r=pj(e,n,e=>e.part.tool);t.push({type:`tool-context-group`,activities:r.items,hasFollowingOtherType:dj(e,r.end,e=>({kind:e.kind,toolName:e.part.tool}))}),n=r.end;continue}if(JD(i)){let r=_j(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(GD(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(WD(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(KD(i)){t.push({type:`tool-static-group`,toolName:i,activities:[r]}),n++;continue}t.push({type:`tool-fallback`,activity:r}),n++}return t},Yj=(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||!FE([r.part],[i.part]))return!1}return!0},Xj=Z.memo(e=>{let t=(0,Q.c)(106),{toolName:n,activities:r,isMobile:i,animateTailText:a}=e,{t:o}=Zt(),s=g(eM),c=Hl(n,o),l;t[0]===n?l=t[1]:(l=JT(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(ac),m=Pu(),h=lt(tM),_=zy(),v=_.kind===`embedded`?_.directory:h,y;t[4]===n?y=t[5]:(y=n.toLowerCase(),t[4]=n,t[5]=y);let b=y===`skill`,x;t[6]===b?x=t[7]:(x={enabled:b},t[6]=b,t[7]=x);let S=an(x),C;t[8]===S.data?C=t[9]:(C=S.data??[],t[8]=S.data,t[9]=C);let w=C,T;t[10]===w?T=t[11]:(T=new Map(w.map(nM)),t[10]=w,t[11]=T);let E=T,D=r[0]??null,O=!D||QD(D.part),k;t[12]===D?k=t[13]:(k=D?Wj(D):null,t[12]=D,t[13]=k);let A=k,j;if(t[14]!==A||t[15]!==D||t[16]!==E||t[17]!==n){bb0:{if(n.toLowerCase()!==`skill`||!D||!A){j=null;break bb0}let e=E.get(A)?.path||Lj(D);if(!e||e===`<built-in>`){j=null;break bb0}let r=Uj(e);if(!r){j=null;break bb0}let i;t[19]!==A||t[20]!==r?(i={name:A,path:r},t[19]=A,t[20]=r,t[21]=i):i=t[21],j=i}t[14]=A,t[15]=D,t[16]=E,t[17]=n,t[18]=j}else j=t[18];let M=j,N;if(t[22]!==v||t[23]!==f||t[24]!==D){bb1:{if(!f||!D){N=null;break bb1}let e=Ij(D);if(!e){N=null;break bb1}let n=nu(e,v);if(!n){N=null;break bb1}let r;t[26]===D?r=t[27]:(r=Vj(D),t[26]=D,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],N=i}t[22]=v,t[23]=f,t[24]=D,t[25]=N}else N=t[25];let P=N,F;t[32]!==v||t[33]!==m||t[34]!==p?(F=(e,t)=>{if(!v)return;let n=ru(v,e);if(!n)return;if(m){m.openFile({path:n,targetLine:t&&Number.isFinite(t)?Math.max(1,Math.trunc(t)):void 0});return}if(p?.editor){p.editor.openFile(n,t);return}if(!tu(n,v)){Vu(n,v).then(()=>{let e=g.getState(),r=v||iu(v,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=g.getState(),i=iu(v,n);if(t&&Number.isFinite(t)){r.openContextFileAtLine(i,n,Math.max(1,Math.trunc(t)),1);return}r.openContextFile(i,n)},t[32]=v,t[33]=m,t[34]=p,t[35]=F):F=t[35];let I=q(F),L;t[36]!==v||t[37]!==m?(L=e=>{let t=eu(e);if(!t)return;let n=()=>{if(m){m.openFile({path:t});return}let e=g.getState(),n=v||iu(``,t);e.openContextFile(n,t)};if(v&&!tu(t,v)){Vu(t,v).then(n);return}n()},t[36]=v,t[37]=m,t[38]=L):L=t[38];let R=q(L),z;t[39]===n?z=t[40]:(z=n.toLowerCase(),t[39]=n,t[40]=z);let B=z,V=B===`grep`||B===`search`||B===`find`||B===`ripgrep`||B===`glob`,H=B===`webfetch`||B===`fetch`||B===`curl`||B===`wget`,ee=B===`skill`,U=!!(P||M),te=!!(P&&v||M),W;t[41]!==te||t[42]!==I||t[43]!==R||t[44]!==U||t[45]!==P||t[46]!==M?(W=()=>{if(!(!U||!te)){if(P){I(P.path,P.offset);return}M&&R(M.path)}},t[41]=te,t[42]=I,t[43]=R,t[44]=U,t[45]=P,t[46]=M,t[47]=W):W=t[47];let ne=q(W),G;t[48]===ne?G=t[49]:(G=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),ne())},t[48]=ne,t[49]=G);let K=q(G),re=U&&te&&`cursor-pointer`,ie=U&&!te&&`cursor-default opacity-70`,ae;t[50]!==re||t[51]!==ie?(ae=Y(`flex w-full items-center gap-x-1.5 min-w-0`,gv,re,ie),t[50]=re,t[51]=ie,t[52]=ae):ae=t[52];let oe=U?`soft`:void 0,se=U?ne:void 0,ce=U?K:void 0,le=U?`button`:void 0,ue=U&&te?0:void 0,de=U&&!te?!0:void 0,fe=i?`size-4`:`size-3.5`,pe;t[53]===fe?pe=t[54]:(pe=Y(`inline-flex items-center justify-center flex-shrink-0`,fe),t[53]=fe,t[54]=pe);let me;t[55]===Symbol.for(`react.memo_cache_sentinel`)?(me={color:`var(--tools-icon)`},t[55]=me):me=t[55];let he=O?(0,$.jsx)(FD,{isMobile:i,label:o(`chat.assistantStatus.usingTool`,{tool:c})}):u,ge;t[56]!==pe||t[57]!==me||t[58]!==he?(ge=(0,$.jsx)(`div`,{className:pe,style:me,children:he}),t[56]=pe,t[57]=me,t[58]=he,t[59]=ge):ge=t[59];let _e,ve;t[60]===Symbol.for(`react.memo_cache_sentinel`)?(_e=Y(Dj,`inline-flex items-center flex-shrink-0 opacity-85`),ve={color:`var(--tools-title)`},t[60]=_e,t[61]=ve):(_e=t[60],ve=t[61]);let ye;t[62]===c?ye=t[63]:(ye=(0,$.jsx)(`span`,{className:_e,style:ve,title:c,children:c}),t[62]=c,t[63]=ye);let be;t[64]!==a||t[65]!==f||t[66]!==P||t[67]!==s?(be=f&&P?(0,$.jsxs)(`span`,{className:Y(`inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left`,Oj),style:{color:`var(--tools-description)`},title:P.offset?`${P.displayPath}:${P.offset}`:P.displayPath,children:[s?(0,$.jsx)(xh,{filePath:P.path,className:`h-3.5 w-3.5`}):null,Hj(P.displayPath,a)]}):null,t[64]=a,t[65]=f,t[66]=P,t[67]=s,t[68]=be):be=t[68];let xe;t[69]!==a||t[70]!==A||t[71]!==V?(xe=V&&A?(0,$.jsx)(`span`,{className:`inline-flex min-w-0 flex-1`,children:(0,$.jsxs)(qT,{variant:a?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,Oj),style:{color:`var(--tools-description)`},title:A,children:[`"`,A,`"`]})}):null,t[69]=a,t[70]=A,t[71]=V,t[72]=xe):xe=t[72];let Se;t[73]!==A||t[74]!==H?(Se=H&&A?(0,$.jsxs)(`a`,{href:A,target:`_blank`,rel:`noopener noreferrer`,onClick:rM,className:Y(`min-w-0 flex-1 inline-flex items-center gap-1.5 underline decoration-[color:var(--status-info)] underline-offset-2 hover:opacity-90`,`truncate whitespace-nowrap`,Oj),style:{color:`var(--status-info)`},title:A,children:[(0,$.jsx)(Nj,{href:A}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:A})]}):null,t[73]=A,t[74]=H,t[75]=Se):Se=t[75];let Ce;t[76]!==ee||t[77]!==M?(Ce=ee&&M?(0,$.jsx)(`span`,{className:Y(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,Oj),style:{color:`var(--tools-description)`},title:M.path,children:M.name}):null,t[76]=ee,t[77]=M,t[78]=Ce):Ce=t[78];let we;t[79]!==A||t[80]!==ee||t[81]!==M?(we=ee&&!M&&A?(0,$.jsx)(`span`,{className:Y(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,Oj),style:{color:`var(--tools-description)`},title:A,children:A}):null,t[79]=A,t[80]=ee,t[81]=M,t[82]=we):we=t[82];let Te;t[83]!==a||t[84]!==A||t[85]!==H||t[86]!==f||t[87]!==V||t[88]!==ee?(Te=!f&&!V&&!H&&!ee&&A?(0,$.jsx)(qT,{variant:a?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,Oj),style:{color:`var(--tools-description)`},children:A}):null,t[83]=a,t[84]=A,t[85]=H,t[86]=f,t[87]=V,t[88]=ee,t[89]=Te):Te=t[89];let Ee;return t[90]!==ae||t[91]!==oe||t[92]!==se||t[93]!==ce||t[94]!==le||t[95]!==ue||t[96]!==de||t[97]!==ge||t[98]!==ye||t[99]!==be||t[100]!==xe||t[101]!==Se||t[102]!==Ce||t[103]!==we||t[104]!==Te?(Ee=(0,$.jsxs)(`div`,{className:ae,"data-mobile-press-feedback":oe,onClick:se,onKeyDown:ce,role:le,tabIndex:ue,"aria-disabled":de,children:[ge,ye,be,xe,Se,Ce,we,Te]}),t[90]=ae,t[91]=oe,t[92]=se,t[93]=ce,t[94]=le,t[95]=ue,t[96]=de,t[97]=ge,t[98]=ye,t[99]=be,t[100]=xe,t[101]=Se,t[102]=Ce,t[103]=we,t[104]=Te,t[105]=Ee):Ee=t[105],Ee},(e,t)=>e.toolName===t.toolName&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&Yj(e.activities,t.activities)),Zj=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)(Uk,{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}),Qj=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)(Cj,{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}),$j=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}=Zt(),_=Ul()??``,v=Z.useMemo(()=>jj(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?Tj(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(()=>Gj(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=Di(_,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=ca(_,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 Di(_,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)&&Aj(e)),ne=te&&!W&&!Mj(t,V),G=Z.useMemo(()=>B?Pj(e):kj,[e,B]),K=Z.useMemo(()=>B?Jj(G):[],[B,G]),re=Z.useMemo(()=>L||z===0?0:Math.max(0,K.length-z),[L,z,K.length]),ie=Z.useMemo(()=>L||z===0?K:K.slice(-z),[L,z,K]);if((!m||I&&!O)&&K.length===0)return null;let ae=(e,t)=>{let n=(0,$.jsx)(`div`,{className:mv(c),children:t});return(0,$.jsx)(Z.Fragment,{children:n},e)},oe=B?ie.map((e,t)=>{switch(e.type){case`reasoning`:return ae(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(Zj,{activity:e.activity,streamPhase:p,onContentChange:f})}));case`justification`:return ae(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(Qj,{activity:e.activity,onContentChange:f,onShowPopup:d,actions:h?.(e.activity),streamPhase:p})}));case`tool-expandable`:return(0,$.jsx)(Kj,{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)(qj,{toolName:e.toolName,activities:e.activities,isMobile:c},e.activities[0]?.id??`static-${e.toolName}-${t}`);case`tool-context-group`:return(0,$.jsx)(gj,{activities:e.activities,isMobile:c,isTurnLive:T,hasFollowingOtherType:e.hasFollowingOtherType,children:e.activities.map(e=>{let t=e.part,n=t.tool?.toLowerCase()??``;return qD(n)?(0,$.jsx)(Xj,{toolName:n,activities:[e],isMobile:c,animateTailText:!1},e.id):(0,$.jsx)(dk,{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)(Sj,{activities:e.activities,isMobile:c,children:e.activities.map(e=>{let t=e.part;return(0,$.jsx)(Xj,{toolName:t.tool?.toLowerCase()??``,activities:[e],isMobile:c,animateTailText:!1},e.id)})},e.activities[0]?.id??`skill-${t}`);case`tool-fallback`:return(0,$.jsx)(Kj,{activity:e.activity,isExpanded:l.has(e.activity.id),isMobile:c,onToggleTool:u,onShowPopup:d,onContentChange:f},e.activity.id);default:return null}}):null,se=ie.length>0;return m?(0,$.jsxs)(`div`,{className:mv(c),children:[(0,$.jsxs)(`button`,{ref:C,type:`button`,className:Y(`group/tool flex w-full min-w-0 flex-nowrap items-center text-left`,c?`gap-x-1`:`gap-x-2`,!I&&gv,I&&`oc-tool-row -mx-2 rounded-lg px-2 py-0.5 cursor-default`,c&&`pr-0`),"data-mobile-press-feedback":I?void 0:`soft`,onClick:I?void 0:R,"aria-expanded":L,"aria-disabled":I||void 0,"aria-label":I?A:g(L?`chat.activity.collapseAria`:`chat.activity.expandAria`),children:[(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 flex-1 items-center overflow-clip`,c?`gap-x-1`:`gap-x-1.5`),children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center`,c?`h-5 w-4`:`h-6 w-3.5`),style:{color:`var(--tools-icon)`},children:T&&!O?(0,$.jsx)(FD,{isMobile:c,label:A,className:`block`}):(0,$.jsx)(X,{name:k,className:`h-3.5 w-3.5`})}),(0,$.jsx)(`span`,{className:Y(`inline-flex flex-shrink-0 items-center`,c?`typography-meta h-5`:`typography-ui-label h-5 font-semibold`,T?`animate-text-shimmer text-[var(--status-info)] [--oc-text-shimmer-base:var(--status-info)]`:`text-foreground/85`),children:A}),E?(0,$.jsx)(`span`,{className:`typography-meta shrink-0 tabular-nums text-muted-foreground`,children:E}):null]}),(0,$.jsxs)(`span`,{className:Y(`ml-auto inline-flex max-w-[min(14rem,55%)] shrink-0 items-center justify-end`,c?`gap-0.5`:`gap-1`),children:[M.length>0?(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 items-center text-muted-foreground`,c?`gap-1`:`gap-1.5`),children:[(0,$.jsx)(`span`,{className:`inline-flex shrink-0 items-center gap-0.5`,"aria-hidden":`true`,children:N.map((e,t)=>(0,$.jsx)(vo,{name:e,size:c?12:14,className:Y(`flex-none`,c?`size-3 min-h-3 min-w-3 max-h-3 max-w-3`:`size-3.5 min-h-3.5 min-w-3.5 max-h-3.5 max-w-3.5`)},`${e}-${t}`))}),(0,$.jsx)(`span`,{className:`typography-meta min-w-0 truncate`,children:g(T?`chat.activity.agentsWorking`:`chat.activity.agentsInvolved`,{count:M.length})})]}):null,I?null:(0,$.jsx)(X,{name:L?`arrow-down-s`:`arrow-right-s`,className:Y(`flex-shrink-0 text-muted-foreground opacity-70`,c&&`-mr-0.5`,c?`size-3`:`size-3.5`)})]})]}),se?(0,$.jsxs)(`div`,{className:I?void 0:`relative ml-2 pl-3`,children:[I?null:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute left-0 top-px bottom-0 w-px opacity-40`,style:{backgroundColor:`var(--tools-border)`}}),re>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:[`+`,re,` more...`]}):null,(0,$.jsx)(`div`,{className:`flow-root`,children:oe})]}):null,L&&(ee||U||ne)?(0,$.jsx)(`div`,{className:Y(`typography-meta flex min-h-9 items-center gap-2 px-2 text-muted-foreground`,I?void 0:`ml-5`,U&&`text-[var(--status-error)]`),role:U?`alert`:`status`,children:ee?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(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)(yo,{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:mv(c),children:oe})});function eM(e){return e.showToolFileIcons}function tM(e){return e.currentDirectory}function nM(e){return[e.name,e]}function rM(e){e.stopPropagation()}var iM=Z.memo(e=>{let t=(0,Q.c)(2),n;return t[0]===e?n=t[1]:(n=(0,$.jsx)($j,{...e}),t[0]=e,t[1]=n),n}),aM={contain:`layout`},oM={containerType:`inline-size`,containerName:`message-footer`},sM=`mt-1.5 mb-0.5 flex items-center justify-start gap-1.5`,cM=`mt-3 mb-0.5 flex items-center justify-start gap-1.5`,lM=`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`,uM=`size-3.5!`,dM=`mt-1.5 mb-0.5 flex flex-wrap items-center gap-3`,fM=`mt-3 mb-0.5 flex flex-wrap items-center gap-3 -ml-[5px]`,pM=`flex items-center gap-2`,mM=`flex items-center gap-2 text-muted-foreground`,hM=`inline-flex h-3.5 items-center gap-1 text-[11px] leading-none tabular-nums text-muted-foreground`,gM=`size-3.5!`,_M=`medium`,vM=e=>e.replace(/\\/g,`/`).split(`/`).filter(Boolean).at(-1)??e,yM=`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)]`,bM=`h-7 gap-1.5`,xM=`h-6 gap-1`,SM=`text-[11px] leading-none`,CM=`size-3.5`,wM=`size-3`,TM=5,EM=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=Y(`flex min-w-0 flex-1 items-center leading-none text-muted-foreground`,i),t[0]=i,t[1]=a);let o=n.file,s=r?`h-3 w-3`:`h-3.5 w-3.5`,c;t[2]===s?c=t[3]:(c=Y(`flex-shrink-0`,s),t[2]=s,t[3]=c);let l;t[4]!==n.file||t[5]!==c?(l=(0,$.jsx)(xh,{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=vM(n.file),t[7]=n.file,t[8]=d);let f;t[9]!==n.file||t[10]!==d?(f=(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-left text-foreground/80`,title:u,children:d}),t[9]=n.file,t[10]=d,t[11]=f):f=t[11];let p=r?`text-[11px]`:`typography-meta`,m;t[12]===p?m=t[13]:(m=Y(`inline-flex flex-shrink-0 items-center gap-0 leading-none tabular-nums`,p),t[12]=p,t[13]=m);let h;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(h={color:`var(--status-success)`},t[14]=h):h=t[14];let g;t[15]===n.additions?g=t[16]:(g=(0,$.jsxs)(`span`,{style:h,children:[`+`,n.additions]}),t[15]=n.additions,t[16]=g);let _,v;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(_=(0,$.jsx)(`span`,{className:`text-muted-foreground/70`,children:`/`}),v={color:`var(--status-error)`},t[17]=_,t[18]=v):(_=t[17],v=t[18]);let y;t[19]===n.deletions?y=t[20]:(y=(0,$.jsxs)(`span`,{style:v,children:[`-`,n.deletions]}),t[19]=n.deletions,t[20]=y);let b;t[21]!==m||t[22]!==g||t[23]!==y?(b=(0,$.jsxs)(`span`,{className:m,children:[g,_,y]}),t[21]=m,t[22]=g,t[23]=y,t[24]=b):b=t[24];let x;return t[25]!==b||t[26]!==a||t[27]!==l||t[28]!==f?(x=(0,$.jsxs)(`span`,{className:a,children:[l,f,b]}),t[25]=b,t[26]=a,t[27]=l,t[28]=f,t[29]=x):x=t[29],x}),DM=Z.memo(e=>{let t=(0,Q.c)(18),{file:n,canOpen:r,isMobile:i,onOpen:a}=e,{t:o}=Zt(),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?xM:bM,d;t[3]===u?d=t[4]:(d=Y(yM,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)(EM,{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)(yo,{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}),OM=Z.memo(e=>{let t=(0,Q.c)(53),{fileCount:n,changedFiles:r,turnId:i,isLatestTurn:a,isMobile:o}=e,{t:s}=Zt(),c=Ul(),l=zy(),u=l.directory||c,d=l.sessionId,f=Pu(),p=g(HM),m;t[0]===r?m=t[1]:(m=r??[],t[0]=r,t[1]=m);let h=m,_;t[2]===h?_=t[3]:(_=h.slice(0,TM),t[2]=h,t[3]=_);let v=_,y=Math.max(0,h.length-v.length),b=h.length>0?h.length:n,x=!!(f||!o&&u||o&&a),S;t[4]!==b||t[5]!==s?(S=s(b===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:b}),t[4]=b,t[5]=s,t[6]=S):S=t[6];let C=S,w;t[7]!==y||t[8]!==s?(w=s(y===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:y}),t[7]=y,t[8]=s,t[9]=w):w=t[9];let T=w,E=Y(yM,o?xM:bM),D=o?wM:CM,O;t[10]===o?O=t[11]:(O=o?Y(SM,`font-semibold text-foreground/85`):`typography-meta font-semibold text-foreground/85`,t[10]=o,t[11]=O);let k=O,A;t[12]===o?A=t[13]:(A=o?Y(SM,`text-muted-foreground`):`typography-meta text-muted-foreground`,t[12]=o,t[13]=A);let j=A,M;t[14]===o?M=t[15]:(M=o?Y(SM,`font-medium`):`typography-meta font-medium`,t[14]=o,t[15]=M);let N=M,P;t[16]!==u||t[17]!==d||t[18]!==a||t[19]!==o||t[20]!==f||t[21]!==i?(P=e=>{if(f){f.openTurnDiff(i,d,e);return}if(!o&&u){Kk({directory:u,filePath:e,turnMessageId:i,sessionId:d});return}o&&a&&u&&Kk({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]=P):P=t[22];let F=q(P),I;t[23]!==u||t[24]!==d||t[25]!==a||t[26]!==o||t[27]!==f||t[28]!==p||t[29]!==i||t[30]!==v[0]?.file?(I=()=>{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=v[0]?.file;e&&o&&a&&u&&Kk({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]=v[0]?.file,t[31]=I):I=t[31];let L=q(I),R=o?`gap-0 border-foreground/15 p-1`:`gap-0.5 border-border/50 p-1.5`,z;t[32]===R?z=t[33]:(z=Y(`mt-4 flex min-w-0 flex-col rounded-[var(--radius-lg)] border bg-muted/20`,R),t[32]=R,t[33]=z);let B=Y(E,`max-w-full text-muted-foreground hover:text-foreground`),V;t[34]===s?V=t[35]:(V=s(`diffView.actions.reviewAria`),t[34]=s,t[35]=V);let H;t[36]===s?H=t[37]:(H=s(`diffView.actions.reviewAria`),t[36]=s,t[37]=H);let ee;t[38]===D?ee=t[39]:(ee=(0,$.jsx)(X,{name:`file-edit`,className:D}),t[38]=D,t[39]=ee);let U=`turn-changes-${i}`,te;t[40]===s?te=t[41]:(te=s(`chat.changedFiles.title`),t[40]=s,t[41]=te);let W;t[42]!==U||t[43]!==te||t[44]!==k?(W=(0,$.jsx)(`span`,{id:U,className:k,children:te}),t[42]=U,t[43]=te,t[44]=k,t[45]=W):W=t[45];let ne;t[46]!==C||t[47]!==j?(ne=(0,$.jsx)(`span`,{className:j,children:C}),t[46]=C,t[47]=j,t[48]=ne):ne=t[48];let G;t[49]===D?G=t[50]:(G=Y(D,`opacity-60`),t[49]=D,t[50]=G);let K;return t[51]===G?K=t[52]:(K=(0,$.jsx)(X,{name:`arrow-right-s`,className:G}),t[51]=G,t[52]=K),(0,$.jsxs)(`section`,{className:z,"data-turn-changes-preview":`true`,"data-message-action-group":`true`,"aria-labelledby":`turn-changes-${i}`,children:[(0,$.jsxs)(yo,{type:`button`,variant:`ghost`,size:`xs`,disabled:!x,onClick:L,className:B,"aria-label":V,title:H,children:[ee,W,ne,K]}),v.length>0?(0,$.jsxs)(`div`,{className:Y(`flex min-w-0 flex-col`,o?`gap-0`:`gap-0.5`),children:[v.map(e=>(0,$.jsx)(DM,{file:e,canOpen:x,isMobile:o,onOpen:F},e.file)),y>0?(0,$.jsxs)(yo,{type:`button`,variant:`ghost`,size:`xs`,disabled:!x,className:Y(E,`text-muted-foreground hover:text-foreground`),onClick:L,"aria-label":s(`diffView.actions.reviewAria`),title:s(`diffView.actions.reviewAria`),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:Y(D,`flex-shrink-0`)}),(0,$.jsxs)(`span`,{className:N,children:[`+`,T]}),(0,$.jsx)(X,{name:`arrow-right-s`,className:D})]}):null]}):null]})}),kM=e=>e.type===`subtask`,AM=e=>{let t=e;return t.type===`text`&&typeof t.shellAction==`object`&&t.shellAction!==null},jM=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}`},MM=e=>{let t=(0,Q.c)(49),{part:n}=e,[r,i]=Z.useState(!1),a=Ul(),{isMobile:o}=Ws(),s=J(UM),c=g(WM),l=zy(),{t:u}=Zt(),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 _=h,v;t[6]===n.prompt?v=t[7]:(v=typeof n.prompt==`string`?n.prompt.trim():``,t[6]=n.prompt,t[7]=v);let y=v,b;t[8]===n.taskSessionID?b=t[9]:(b=typeof n.taskSessionID==`string`?n.taskSessionID.trim():``,t[8]=n.taskSessionID,t[9]=b);let S=b,C;t[10]===n.model?C=t[11]:(C=jM(n.model),t[10]=n.model,t[11]=C);let w=C,T=!!y&&!(o&&l.kind===`primary`),E;t[12]===u?E=t[13]:(E=u(`chat.messageBody.subtask.title`),t[12]=u,t[13]=E);let D;t[14]===E?D=t[15]:(D=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:E}),t[14]=E,t[15]=D);let O;t[16]===m?O=t[17]:(O=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]=O);let k;t[18]===_?k=t[19]:(k=_?(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:[`@`,_]}):null,t[18]=_,t[19]=k);let A;t[20]===w?A=t[21]:(A=w?(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:w}):null,t[20]=w,t[21]=A);let j;t[22]!==k||t[23]!==A||t[24]!==D||t[25]!==O?(j=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[D,O,k,A]}),t[22]=k,t[23]=A,t[24]=D,t[25]=O,t[26]=j):j=t[26];let M;t[27]===f?M=t[28]:(M=f?(0,$.jsx)(`div`,{className:`typography-ui-label text-foreground/90 mt-1.5`,children:f}):null,t[27]=f,t[28]=M);let N;t[29]!==r||t[30]!==y||t[31]!==T||t[32]!==u?(N=T?(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(GM),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:y}):null]}):null,t[29]=r,t[30]=y,t[31]=T,t[32]=u,t[33]=N):N=t[33];let P;t[34]!==_||t[35]!==f||t[36]!==a||t[37]!==o||t[38]!==c||t[39]!==l||t[40]!==s||t[41]!==u||t[42]!==S?(P=S&&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&&Vy(l,S,e,()=>{if(!ma({sessionId:S,directory:e})){if(ff()||o||x()){s(S,e);return}c(e,{mode:`chat`,dedupeKey:`session:${S}`,label:f||_||u(`contextPanel.mode.chat`),readOnly:!0})}})},children:u(`chat.messageBody.subtask.openSession`)})}):null,t[34]=_,t[35]=f,t[36]=a,t[37]=o,t[38]=c,t[39]=l,t[40]=s,t[41]=u,t[42]=S,t[43]=P):P=t[43];let F;return t[44]!==j||t[45]!==M||t[46]!==N||t[47]!==P?(F=(0,$.jsxs)(`div`,{className:`mt-2`,children:[j,M,N,P]}),t[44]=j,t[45]=M,t[46]=N,t[47]=P,t[48]=F):F=t[48],F},NM=e=>{let t=(0,Q.c)(34),{notification:n}=e,r=Ul(),i=g(KM),{isMobile:a}=Ws(),{t:o}=Zt(),s;t[0]!==r||t[1]!==a?(s=r&&!a&&!x(),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),_=c&&`cursor-pointer hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]`,v;t[8]===_?v=t[9]:(v=Y(`mt-2 flex min-w-0 gap-2.5 rounded-[var(--radius-lg)] border border-border/60 bg-muted/20 px-3 py-2.5`,_),t[8]=_,t[9]=v);let y=c?`button`:void 0,b=c?0:void 0,S=c?o(`chat.messageBody.subagent.openSession`,{label:f}):void 0,C=c?p:void 0,w=c?h:void 0,T;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(T=(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]=T):T=t[10];let E;t[11]===f?E=t[12]:(E=(0,$.jsx)(`span`,{className:`typography-meta min-w-0 flex-1 truncate font-semibold text-foreground/90`,children:f}),t[11]=f,t[12]=E);let D=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`,O;t[13]===D?O=t[14]:(O=Y(`inline-flex h-5 flex-shrink-0 items-center rounded px-1.5 text-[11px] leading-none`,D),t[13]=D,t[14]=O);let k;t[15]!==u||t[16]!==O?(k=(0,$.jsx)(`span`,{className:O,children:u}),t[15]=u,t[16]=O,t[17]=k):k=t[17];let A;t[18]!==E||t[19]!==k?(A=(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[E,k]}),t[18]=E,t[19]=k,t[20]=A):A=t[20];let j;t[21]===n.body?j=t[22]:(j=n.body?(0,$.jsx)(`div`,{className:`typography-meta mt-1 max-h-16 overflow-hidden text-muted-foreground [&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,children:(0,$.jsx)(_l,{content:n.body,variant:`tool`,enableFileReferences:!1})}):null,t[21]=n.body,t[22]=j);let M;t[23]!==A||t[24]!==j?(M=(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[A,j]}),t[23]=A,t[24]=j,t[25]=M):M=t[25];let N;return t[26]!==w||t[27]!==M||t[28]!==v||t[29]!==y||t[30]!==b||t[31]!==S||t[32]!==C?(N=(0,$.jsxs)(`div`,{className:v,role:y,tabIndex:b,"aria-label":S,onClick:C,onKeyDown:w,children:[T,M]}),t[26]=w,t[27]=M,t[28]=v,t[29]=y,t[30]=b,t[31]=S,t[32]=C,t[33]=N):N=t[33],N},PM={background:`transparent`,backgroundColor:`transparent`},FM=e=>{let t=(0,Q.c)(36),{part:n}=e,[r,i]=Z.useState(!1),[a,o]=Z.useState(!1),s=Z.useRef(null),{t:c}=Zt(),l;t[0]===n.shellAction?l=t[1]:(l=typeof n.shellAction?.command==`string`?n.shellAction.command.trim():``,t[0]=n.shellAction,t[1]=l);let u=l,d=typeof n.shellAction?.output==`string`?n.shellAction.output:``,f;t[2]===n.shellAction?f=t[3]:(f=typeof n.shellAction?.status==`string`?n.shellAction.status.trim().toLowerCase():``,t[2]=n.shellAction,t[3]=f);let p=f,m;t[4]===d?m=t[5]:(m=d.trim(),t[4]=d,t[5]=m);let h=m.length>0,g;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>{s.current!==null&&typeof window<`u`&&(window.clearTimeout(s.current),s.current=null)},t[6]=g):g=t[6];let _=q(g),v,y;t[7]===_?(v=t[8],y=t[9]):(v=()=>()=>{_()},y=[_],t[7]=_,t[8]=v,t[9]=y),Z.useEffect(v,y);let b;t[10]!==_||t[11]!==h||t[12]!==d?(b=async()=>{h&&(await en(d)).ok&&(_(),o(!0),typeof window<`u`&&(s.current=window.setTimeout(()=>{o(!1),s.current=null},2e3)))},t[10]=_,t[11]=h,t[12]=d,t[13]=b):b=t[13];let x=q(b),S;t[14]===c?S=t[15]:(S=c(`chat.messageBody.shellCommand.title`),t[14]=c,t[15]=S);let C;t[16]===S?C=t[17]:(C=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:S}),t[16]=S,t[17]=C);let w;t[18]===p?w=t[19]:(w=p?(0,$.jsx)(`span`,{className:Y(`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none`,p===`error`?`bg-[var(--status-error-background)] text-[var(--status-error)]`:`bg-foreground/5 text-muted-foreground`),children:p}):null,t[18]=p,t[19]=w);let T;t[20]!==w||t[21]!==C?(T=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[C,w]}),t[20]=w,t[21]=C,t[22]=T):T=t[22];let E;t[23]===u?E=t[24]:(E=u?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 overflow-x-auto font-mono`,children:(0,$.jsx)(gu,{language:`bash`,code:u,codeStyle:PM,wrap:!0})}):null,t[23]=u,t[24]=E);let D;t[25]!==a||t[26]!==x||t[27]!==r||t[28]!==h||t[29]!==d||t[30]!==c?(D=h?(0,$.jsxs)(`div`,{className:`mt-2 border-t border-border/60 pt-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 flex-wrap`,children:[(0,$.jsx)(`button`,{type:`button`,className:`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2`,onClick:()=>i(qM),children:c(r?`chat.messageBody.shellCommand.hideOutput`:`chat.messageBody.shellCommand.showOutput`)}),(0,$.jsx)(`button`,{type:`button`,className:`inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,onClick:()=>{x()},"aria-label":c(a?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),title:c(a?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),children:a?(0,$.jsx)(X,{name:`check`,className:`h-3.5 w-3.5`}):(0,$.jsx)(X,{name:`file-copy`,className:`h-3.5 w-3.5`})})]}),r?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 max-h-56 overflow-auto font-mono text-foreground/85`,children:(0,$.jsx)(gu,{language:`bash`,code:d,codeStyle:PM,wrap:!0})}):null]}):null,t[25]=a,t[26]=x,t[27]=r,t[28]=h,t[29]=d,t[30]=c,t[31]=D):D=t[31];let O;return t[32]!==T||t[33]!==E||t[34]!==D?(O=(0,$.jsxs)(`div`,{className:`mt-2`,children:[T,E,D]}),t[32]=T,t[33]=E,t[34]=D,t[35]=O):O=t[35],O},IM=e=>{let t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`},LM=(e,t)=>{if(t&&typeof t==`object`)return{output:typeof t.output==`number`&&Number.isFinite(t.output)?Math.max(0,t.output):0,reasoning:typeof t.reasoning==`number`&&Number.isFinite(t.reasoning)?Math.max(0,t.reasoning):0};for(let t of e){let e=t.tokens;if(!(!e||typeof e!=`object`))return{output:typeof e.output==`number`&&Number.isFinite(e.output)?Math.max(0,e.output):0,reasoning:typeof e.reasoning==`number`&&Number.isFinite(e.reasoning)?Math.max(0,e.reasoning):0}}return{output:0,reasoning:0}},RM=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:_,editing:v,editStaged:y,onCancelEdit:b,userActionsMode:x=`inline`,stickyUserHeaderEnabled:S=!0})=>{let{locale:C,t:w}=Zt(),T=Cb(),E=By(zy()),D=g(e=>e.timeFormatPreference),[O,k]=Z.useState(!1),A=Z.useRef(null),j=Z.useMemo(()=>n.filter(e=>e.type===`text`?!bi(e):!!(kM(e)||AM(e))),[n]),M=Z.useMemo(()=>j.map(e=>ir(e)?mE(Ua(e)):void 0),[j]),N=f?.token,P=!1,F=!!l,I=!!u,L=!!(s??a),R=!!c,z=x!==`external-actions`,B=x!==`external-content`,V=S&&x===`inline`,H=q(()=>{A.current!==null&&typeof window<`u`&&(window.clearTimeout(A.current),A.current=null)}),ee=q(()=>{!L||!F||!R||typeof window>`u`||(H(),k(!0),A.current=window.setTimeout(()=>{k(!1),A.current=null},1800))});Z.useEffect(()=>{R||(k(!1),H())},[H,R]);let U=q(e=>{!l||!R||(e.stopPropagation(),e.preventDefault(),l(),L&&ee())}),te=T===`mini-chat`||!E.fork?void 0:h,W=Z.useMemo(()=>{if(typeof i!=`number`||i<=0)return null;let e=WA(i,D);return e.length>0?e:null},[C,i,D]),ne=Y(`group/user-actions`,a?x===`inline`?`flex items-center justify-end pt-2 pb-3`:S?`flex h-9 items-start justify-end pt-0`:`flex h-11 items-start justify-end pt-0`:x===`inline`?`absolute top-full left-0 right-0 z-10 pt-5`:`flex h-8 items-start justify-end pt-2`),G=!v&&y&&B?(0,$.jsx)(`div`,{className:ne,children:(0,$.jsxs)(`div`,{className:Y(pM,`justify-end`,!a&&x===`inline`&&`translate-x-5`,`pointer-events-auto opacity-100`),"data-message-action-group":`true`,children:[(0,$.jsxs)(`span`,{className:Y(hM,`text-primary`),"aria-live":`polite`,children:[(0,$.jsx)(X,{weight:_M,name:`edit`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:w(`chat.messageBody.actions.editStaged`)})]}),b?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":w(`chat.messageBody.actions.cancelEdit`),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),b()},children:(0,$.jsx)(X,{weight:_M,name:`close`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.cancelEdit`)})]}):null]})}):null,K=(v&&B?(0,$.jsx)(`div`,{className:ne,children:(0,$.jsx)(`div`,{className:Y(pM,`justify-end`,!a&&x===`inline`&&`translate-x-5`,`pointer-events-none opacity-100`),children:(0,$.jsx)(`span`,{className:Y(hM,`animate-text-shimmer`),"aria-live":`polite`,children:w(`chat.messageBody.actions.editing`)})})}):null)??G??((F&&R||p||m||te)&&B?(0,$.jsx)(`div`,{className:ne,children:(0,$.jsxs)(`div`,{className:Y(pM,`justify-end`,!a&&x===`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:[W?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:Y(hM,`mr-1`),"aria-label":`Message time: ${W}`,children:[(0,$.jsx)(X,{weight:_M,name:`time`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:W})]})}),(0,$.jsx)(Zo,{children:W})]}):null,m&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":w(`chat.messageBody.actions.revertAria`),"aria-busy":_===`revert`,disabled:!!_,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),m()},children:(0,$.jsx)(X,{weight:_M,name:_===`revert`?`loader-4`:`arrow-go-back`,className:Y(uM,_===`revert`&&`animate-spin`)})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.revert`)})]}),p&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":w(`chat.messageBody.actions.editAria`),disabled:!!_,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),p()},children:(0,$.jsx)(X,{weight:_M,name:`edit`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.edit`)})]}),te&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":w(`chat.messageBody.actions.forkAria`),"aria-busy":_===`fork`,disabled:!!_,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),te()},children:(0,$.jsx)(X,{weight:_M,name:_===`fork`?`loader-4`:`git-branch`,className:Y(uM,_===`fork`&&`animate-spin`)})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.fork`)})]}),F&&R&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":O||I?`true`:void 0,className:lM,"aria-label":w(`chat.messageBody.actions.copyMessageAria`),onPointerDown:e=>e.stopPropagation(),onClick:U,onFocus:()=>k(!0),onBlur:()=>{I||k(!1)},children:I?(0,$.jsx)(X,{weight:_M,name:`check`,className:Y(uM,`text-[color:var(--status-success)]`)}):(0,$.jsx)(X,{weight:_M,name:`file-copy`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.copyMessage`)})]})]})}):null);return z?(0,$.jsxs)(`div`,{className:`relative w-full group/message`,"data-user-message-body":`true`,style:aM,onTouchStart:L&&F&&R?ee:void 0,children:[(0,$.jsx)(`div`,{className:Y(`leading-relaxed text-foreground/90 text-base overflow-x-hidden`,V?`overflow-y-auto overscroll-contain scrollbar-none`:`overflow-y-hidden`),style:V?{maxHeight:`calc(var(--chat-scroll-height, 100dvh) * 0.4)`}:void 0,children:j.map((e,i)=>{if(kM(e))return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(MM,{part:e})},e.id??`user-subtask-${i}`);if(AM(e))return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(FM,{part:e})},e.id??`user-shell-${i}`);let o=M[i];if(o)return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(NM,{notification:o})},e.id??`subagent-notification-${i}`);let s;return f&&N&&!P&&Ua(e).includes(N)&&(s=f,P=!0),(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(GT,{part:e,messageId:t,isMobile:a,agentMention:s,messageParts:r??n})},e.id??`user-text-${i}`)})}),(0,$.jsx)(qh,{files:n,messageID:t,sessionID:e,onShowPopup:d,compact:!0}),K]}):(0,$.jsx)($.Fragment,{children:K})}),zM=Z.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,reviewTransferAction:r,ttsText:i,sessionId:a})=>{let{t:o}=Zt(),s=Cb(),c=zy(),l=By(c),{isPlaying:u,play:d,stop:f}=wA(),p=ui(e=>e.showMessageTTSButtons),m=ui(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)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":h||_?`true`:void 0,className:Y(lM,!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:_M,name:`check`,className:Y(uM,`text-[color:var(--status-success)]`)}):(0,$.jsx)(X,{weight:_M,name:`file-copy`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:o(`chat.messageBody.actions.copyAnswer`)})]}),w?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":o(`chat.messageBody.actions.openSourceSessionAria`),onPointerDown:e=>e.stopPropagation(),onClick:A,children:(0,$.jsx)(X,{weight:_M,name:`target`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:o(`chat.messageBody.actions.openSourceSession`)})]}):null,r&&s!==`mini-chat`&&l.reviewTransfer?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,size:`icon`,variant:`ghost`,disabled:y||!e,className:Y(lM,(!e||y)&&`opacity-50`),"aria-label":r.ariaLabel,onPointerDown:e=>e.stopPropagation(),onClick:e=>{k(e)},children:y?(0,$.jsx)(X,{weight:_M,name:`loader-4`,className:Y(uM,`animate-spin`)}):(0,$.jsx)(X,{weight:_M,name:`arrow-left-right`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:r.tooltip})]}):null,s!==`mini-chat`&&p&&e&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:Y(lM,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:_M,name:`stop`,className:uM}):(0,$.jsx)(X,{weight:_M,name:`volume-up`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:j})]})]})}),BM=Z.memo(({sessionId:e,messageId:t,parts:n,sourceParts:r,isMessageCompleted:i,messageFinish:a,messageCompletedAt:o,messageCreatedAt:s,messageTokens:c,isMobile:l,alwaysShowActions:u,hasTouchInput:d,expandedTools:f,onToggleTool:p,onShowPopup:m,streamPhase:h,allowAnimation:_,onContentChange:v,hasTextContent:y=!1,onCopyMessage:b,onAuxiliaryContentComplete:S,showReasoningTraces:C=!1,turnGroupingContext:w,errorMessage:T,errorVariant:E=`error`,reviewTransferDirection:D=null})=>{let{t:O,locale:k}=Zt(),A=Cb(),j=By(zy()),M=h,N=Z.useRef(null),P=Z.useRef(null),F=h===`streaming`||h===`cooldown`,I=Z.useRef({messageId:t,experiencedStreamingOrCooldown:F});I.current.messageId===t?F&&(I.current.experiencedStreamingOrCooldown=!0):I.current={messageId:t,experiencedStreamingOrCooldown:F};let L=!!(d??l),R=!!(u??l),z=l?fM:dM,B=!i,V=Z.useMemo(()=>n.filter(e=>!bi(e)).filter(e=>e.type!==`compaction`),[n]),H=Z.useMemo(()=>V.filter(e=>e.type===`tool`),[V]),ee=Z.useMemo(()=>V.filter(e=>e.type===`text`),[V]),U=Z.useMemo(()=>ao(ee),[ee]),te=g(e=>e.openContextPreview),W=x(),ne=A===`mini-chat`,G=Z.useMemo(()=>{if(W||l||ne)return null;for(let e of ee){let t=e.text;if(typeof t!=`string`||t.length===0)continue;let n=zl(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 H){let t=e.state,n=t&&typeof t.output==`string`?t.output:null;if(!n)continue;let r=zl(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},[ee,l,ne,W,H]),K=J(e=>e.forkFromMessage),re=J(e=>e.forkTransition),ie=J(e=>e.currentSessionId),ae=J(e=>e.getDirectoryForSession),oe=Ul(),se=D===`review-to-original`,ce=!l&&!W?D:null,le=Z.useMemo(()=>{let t=U.trim();if(!(!e||!oe||!t||!ce))return ce===`review-to-original`?{ariaLabel:O(`chat.messageBody.actions.sendReviewFeedback`),tooltip:O(`chat.messageBody.actions.sendReviewFeedback`),onClick:async()=>{try{await Tn(e,oe,t)}catch(e){console.error(`[review-flow] failed to send review feedback`,e)}}}:{ariaLabel:O(`chat.messageBody.actions.sendImplementationResponse`),tooltip:O(`chat.messageBody.actions.sendImplementationResponse`),onClick:async()=>{try{await An(e,oe,t)}catch(e){console.error(`[review-flow] failed to send implementation response`,e)}}}},[U,oe,ce,e,O]),[ue,de]=Z.useState(!1),fe=g(e=>e.chatRenderMode),pe=g(e=>e.collapsibleThinkingBlocks),me=g(e=>e.showSplitAssistantMessageActions),he=g(e=>e.showAssistantTps),ge=g(e=>e.timeFormatPreference),_e=fe===`sorted`,ve=w?.isLastAssistantInTurn??!1,ye=a===`stop`,be=(ye||i||!!T)&&(w?.isTurnSettled??!0),xe=ye?`completed`:M,Se=H.length>0,Ce=Z.useMemo(()=>H.some(e=>QD(e)),[H]),we=QD,Te=ZD,Ee=I.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||!Pr())return;let n=De.current,r=!n.initialized;n.initialized=!0;for(let i of H){if(n.observedPartIds.has(i.id))continue;if(!vn(r,we(i))){n.observedPartIds.add(i.id);continue}let a=e??i.sessionID;a&&(n.observedPartIds.add(i.id),xi({sessionID:a,messageID:t,partID:i.id,kind:`tool`}))}},[Ee,we,t,e,H]);let Oe=Z.useMemo(()=>H.length===0||!Ce&&H.every(e=>Te(e)),[H,Ce,Te]),ke=Z.useMemo(()=>V.filter(e=>e.type===`reasoning`),[V]),Ae=Z.useMemo(()=>ke.length===0||ke.every(e=>typeof e.time?.end==`number`),[ke]),je=typeof a!=`string`,Me=ke.length>0&&Se&&(Ce||je||!Oe),Ne=B||Se&&(Ce||je||!Oe),Pe=B||Me,Fe=Se||ke.length>0,Ie=ee.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,S?.())},[Le,S]),Z.useEffect(()=>{if(B){ze.current=!1;return}if(Se){ze.current=!1;return}ke.length!==0&&(Pe||!Ae||ze.current||(ze.current=!0,v?.(`structural`)))},[B,Se,v,Ae,ke.length,Pe]);let Be=!!y&&!B,Ve=q(async n=>{if(n.stopPropagation(),n.preventDefault(),!(!e||!t||ue||re)){de(!0);try{await K(e,t)}finally{de(!1)}}}),He=Z.useMemo(()=>{let e=w?.activityParts;return!_e||!e?[]:e},[_e,w?.activityParts]),Ue=Z.useMemo(()=>{let e=w?.activityGroupSegments;return!_e||!e?[]:e.filter(e=>e.anchorMessageId===t)},[_e,t,w?.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=w?.toggleGroup,qe=w?.activityPresentationKind===`compaction`,Je=w?.isGroupExpanded===!0,Ye=_e&&qe&&!Je,Xe=_e?w?.activityOwnerMessageId===t||We:!w?.activityOwnerMessageId||w.activityOwnerMessageId===t||We,Ze=_e&&Xe&&(We||qe)&&!!Ke,Qe=$k(a,V),$e={finish:a,parts:V,streamPhase:xe,error:T,isLastAssistantInTurn:ve},et=iA($e),tt=_e&&aA($e),nt=_e&&!et&&!(qe&&Je),rt=!!T,it=E===`info`?`information`:`error-warning`,at=E===`muted`,ot=Be,st=ve&&be&&!Ye&&(y||!!T||i),ct=w?.diffStats?.hasDiffs===!0,lt=!ne&&ve&&Qe&&be&&!Ye&&w?.diffStats?.hasDiffs===!0,ut=me&&ot&&!st&&!_e,dt=Z.useMemo(()=>(0,$.jsx)(zM,{hasCopyableText:Be,isTouchContext:L,onCopyMessage:b,ttsText:U,reviewTransferAction:le,sessionId:e}),[U,Be,L,b,le,e]),ft=Z.useMemo(()=>e=>{if(!me||!_e)return null;let t=Ua(e.part).trim();return t?(0,$.jsx)(zM,{hasCopyableText:!0,isTouchContext:L,onCopyMessage:async()=>(await en(t)).ok,ttsText:t}):null},[_e,L,me]),pt=Z.useMemo(()=>{if(!ut)return-1;let e=-1;for(let t=0;t<V.length;t+=1){let n=V[t];!n||n.type!==`text`||nt||Ge.get(n)?.kind!==`justification`&&(e=t)}return e},[Ge,nt,ut,V]),mt=ut&&pt<0,ht=Z.useMemo(()=>{let n=[];if(Ze&&Ke&&w){let e=(e,t,r=t)=>{n.push((0,$.jsx)(`div`,{children:(0,$.jsx)(iM,{parts:t,materializationParts:r,isExpanded:w.isGroupExpanded===!0,collapsedPreviewCount:0,completionDisposition:w.completionDisposition,activityPresentationKind:w.activityPresentationKind,durationMs:w.durationMs,startedAt:w.userMessageCreatedAt,onToggle:Ke,isMobile:l,expandedTools:f,onToggleTool:p,onShowPopup:m,onContentChange:v,streamPhase:xe,showHeader:!0,diffStats:w.diffStats,renderJustificationActions:ft})},`progressive-group-${e}`))};Ue.length>0?Ue.forEach(t=>{let n=C?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<V.length;){let i=V[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:P,"data-message-text-export-source":`true`,children:(0,$.jsx)(jk,{part:i,sessionId:e,messageId:t,streamPhase:xe,chatRenderMode:fe,allowSortedFinalStreaming:tt,hasStreamingHapticLifecycle:Ee,onContentChange:v,onShowPopup:m})},`assistant-text-${t}-${i.id??r}`)),ut&&r===pt&&n.push((0,$.jsx)(`div`,{className:l?cM:sM,"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:pM,"data-message-action-group":`true`,children:dt})},`message-actions-${t}`)),r++;continue}if(i.type===`reasoning`){if(Ge.get(i)?.kind===`reasoning`){r+=1;continue}if(!Ua(i).trim()){r+=1;continue}C&&(pe?n.push((0,$.jsx)(`div`,{className:mv(l),children:(0,$.jsx)(Uk,{part:i,messageId:t,streamPhase:xe,onContentChange:v})},`reasoning-${t}-${i.id??r}`)):n.push((0,$.jsx)(jk,{part:i,sessionId:e,messageId:t,streamPhase:xe,chatRenderMode:fe,hasStreamingHapticLifecycle:Ee,onContentChange:v,onShowPopup:m},`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(XD(a)){let e=pj(V,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)(gj,{activities:i,isMobile:l,isTurnLive:xe!==`completed`,hasFollowingOtherType:dj(V,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 qD(n)?(0,$.jsx)(Xj,{toolName:n,activities:[e],isMobile:l,animateTailText:!1},e.id):(0,$.jsx)(dk,{part:e.part,messageId:t,isExpanded:f.has(e.part.id),onToggle:p,isMobile:l,alwaysShowActions:R,onContentChange:v,onShowPopup:m,animateTailText:!1},e.id)})},`context-tools-${i[0].id}`)),r=e.end;continue}}if(JD(a)){let e=_j(V,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)(Sj,{activities:i,isMobile:l,children:i.map(e=>(0,$.jsx)(Xj,{toolName:e.part.tool?.toLowerCase()??``,activities:[e],isMobile:l,animateTailText:!1},e.id))},`skill-tools-${i[0].id}`)),r=e.end;continue}}if(WD(a)){n.push((0,$.jsx)(`div`,{className:mv(l),children:(0,$.jsx)(dk,{part:e,messageId:t,isExpanded:f.has(e.id),onToggle:p,isMobile:l,alwaysShowActions:R,onContentChange:v,onShowPopup:m,animateTailText:!1})},`tool-${e.id}`)),r++;continue}n.push((0,$.jsx)(`div`,{className:mv(l),children:(0,$.jsx)(Xj,{toolName:a,activities:[{id:e.id,turnId:``,messageId:t,partIndex:r,part:e,kind:`tool`}],isMobile:l,animateTailText:!1})},`static-tools-${e.id}`)),r++;continue}r++}return n},[Ge,Ue,R,fe,pe,0,f,Ye,qe,l,Xe,_e,pt,t,dt,ft,e,v,m,p,Ze,ut,xe,Ee,C,nt,tt,Ke,w,V]),gt=Z.useMemo(()=>{if(!ve||!be)return;let e=w?.durationMs;if(!(typeof e!=`number`||e<=0))return IM(e)},[ve,be,w?.durationMs]),_t=Z.useMemo(()=>{let e=typeof o==`number`&&o>0?o:typeof s==`number`&&s>0?s:null;if(e===null)return null;let t=WA(e,ge);return t.length>0?t:null},[o,s,ge,k]),vt=Z.useMemo(()=>{if(!he||!ve||!be)return null;let e=r??n,t=LM(e,c),i=YA({createdAt:s,completedAt:o,fallbackDurationMs:w?.durationMs,outputTokens:t.output,reasoningTokens:t.reasoning,parts:e});if(i===null)return null;let a=XA(i);return a.length>0?a:null},[he,ve,be,n,r,c,s,o,w?.durationMs]),yt=(0,$.jsxs)($.Fragment,{children:[!ne&&!l&&!W&&G?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":O(`chat.messageBody.actions.openPreviewAria`),onPointerDown:e=>e.stopPropagation(),onClick:()=>{let e=oe??(ie?ae(ie):null);e&&te(e,G)},children:(0,$.jsx)(X,{weight:_M,name:`global`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:O(`chat.messageBody.actions.openPreview`)})]}):null,!ne&&!se&&j.fork?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,size:`icon`,variant:`ghost`,className:lM,"aria-label":O(`chat.messageBody.actions.forkAria`),"aria-busy":ue,disabled:ue||!!re,onPointerDown:e=>e.stopPropagation(),onClick:e=>{Ve(e)},children:(0,$.jsx)(X,{weight:_M,name:ue?`loader-4`:`git-branch`,className:Y(uM,ue&&`animate-spin`)})})}),(0,$.jsx)(Zo,{sideOffset:6,children:O(`chat.messageBody.actions.fork`)})]}):null]});return(0,$.jsxs)(`div`,{ref:N,"data-message-text-export-root":`true`,className:Y(`relative w-full group/message`),style:aM,children:[(0,$.jsx)(BA,{containerRef:N}),(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:[ht,rt&&(0,$.jsx)(Jl,{children:at?(0,$.jsxs)(`div`,{role:`status`,className:`my-1.5 flex max-w-full items-center gap-1.5 break-words typography-meta text-muted-foreground`,children:[(0,$.jsx)(X,{name:`stop-circle`,className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`min-w-0`,children:T})]}):(0,$.jsxs)(`div`,{className:Y(`group/assistant-text relative flow-root my-1.5 break-words max-w-full`,E===`info`?Y(`inline-flex w-fit max-w-full border border-[var(--status-info-border)]/45 bg-[var(--status-info-background)]/40`,l?`items-start gap-1.5 rounded-lg px-2.5 py-1.5`:Y(`items-center gap-1.5`,`rounded-lg px-2 py-0.5`)):`mt-3 flex items-center gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3`),children:[E===`info`&&l?(0,$.jsx)(`span`,{className:`inline-flex h-5 w-3.5 shrink-0 items-center justify-center translate-y-[2px]`,"aria-hidden":`true`,children:(0,$.jsx)(X,{name:it,weight:_M,className:Y(uM,`text-[var(--status-info)]/80`)})}):(0,$.jsx)(X,{name:it,weight:E===`info`?_M:void 0,className:Y(`shrink-0`,E===`info`?Y(uM,`text-[var(--status-info)]/80`):`h-4 w-4 text-[var(--status-error)]`)}),(0,$.jsx)(`div`,{className:Y(`min-w-0 break-words`,E===`info`?Y(`text-muted-foreground [&_.markdown-content]:text-muted-foreground [&_p]:m-0`,`[&_.markdown-content]:!leading-5`,l?`[&_.markdown-content]:!text-[length:var(--text-meta)]`:`[&_.markdown-content]:!text-[13px]`):`flex-1`),children:(0,$.jsx)(_l,{content:T??``,onShowPopup:m,className:`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,enableFileReferences:!1})})]})},`assistant-error`)]}),lt&&w?.diffStats?(0,$.jsx)(OM,{fileCount:w.diffStats.files,changedFiles:w.changedFiles,turnId:w.turnId,isLatestTurn:w.isLatestTurn,isMobile:l}):null,(0,$.jsx)(qh,{files:n,messageID:t,sessionID:e,onShowPopup:m}),mt&&(0,$.jsx)(`div`,{className:Y(l?cM:sM),"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:pM,"data-message-action-group":`true`,children:dt})}),st&&(0,$.jsxs)(`div`,{className:z,"data-message-footer":`true`,style:oM,children:[(0,$.jsxs)(`div`,{className:pM,"data-message-action-group":`true`,children:[dt,yt]}),vt||gt||_t?(0,$.jsxs)(`div`,{className:mM,children:[vt?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:hM,"aria-label":O(`chat.messageBody.meta.tpsAria`,{rate:vt}),children:[(0,$.jsx)(X,{weight:_M,name:`pulse`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:vt})]})}),(0,$.jsx)(Zo,{children:O(`chat.messageBody.meta.tpsTooltip`)})]}):null,gt?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:hM,children:[(0,$.jsx)(X,{weight:_M,name:`hourglass`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:gt})]})}),(0,$.jsx)(Zo,{children:gt})]}):null,_t?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:hM,"aria-label":`Message time: ${_t}`,children:[(0,$.jsx)(X,{weight:_M,name:`time`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:_t})]})}),(0,$.jsx)(Zo,{children:_t})]}):null]}):null,!ne&&ve&&ye&&!ct?(0,$.jsx)(qk,{activityParts:w?.activityParts}):null]})]})]})}),VM=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)(RM,{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)(BM,{...r}),t[26]=r,t[27]=i),i});function HM(e){return e.openContextPanelTab}function UM(e){return e.setCurrentSession}function WM(e){return e.openContextPanelTab}function GM(e){return!e}function KM(e){return e.openContextPanelTab}function qM(e){return!e}var JM=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}},YM=(e,t,n)=>e===`active`||n?.isLastTurn&&n.hasConfirmedFinalBody!==!0?!0:t===`summary`,XM=e=>!e,ZM=e=>e.completionDisposition===`active`?e.isLastTurn&&e.sessionIsWorking?{completionDisposition:`active`,durationMs:e.durationMs}:{completionDisposition:`abnormal`,durationMs:e.durationMs}:{completionDisposition:e.completionDisposition,durationMs:e.durationMs},QM=e=>!(e.completionDisposition===`active`||e.isLastTurn&&e.sessionIsWorking&&!e.hasConfirmedSettledAssistant),$M=e=>e.isWorking?!0:e.isInActiveTurn?e.headerCompletionDisposition!==`normal`&&e.headerCompletionDisposition!==`abnormal`:!1,eN=e=>e.turnCompletionDisposition===`active`&&(e.isLastTurn||e.hasAssistantMessages)?`active`:e.headerPresentationDisposition,tN=`Authentication failed for this provider. Please re-authenticate and retry.`,nN=e=>{if(typeof e!=`string`)return!1;let t=e.toLowerCase().trim();if(!t)return!1;if(t.includes(`token refresh failed`)||t.includes(`unauthorized`)||t.includes(`invalid token`)||t.includes(`expired token`))return!0;let n=t.includes(`oauth`),r=t.includes(`failed`)||t.includes(`invalid`)||t.includes(`expired`);if(n&&r)return!0;let i=/\b401\b/.test(t),a=t.includes(`auth`)||t.includes(`token`)||t.includes(`unauthorized`);return i&&a};function rN(e,t){if(!e||typeof e!=`object`)return;let n=e,r=typeof n.data?.message==`string`?n.data.message:void 0,i=typeof n.message==`string`?n.message:void 0,a=typeof n.name==`string`?n.name:void 0,o=r||i||a;if(o)return a===`SessionRetry`?{text:`Opencode failed to send a message. Retry attempt info: \n\`${o}\``,variant:`info`}:nN(o)?{text:tN,variant:`error`}:a===`MessageAbortedError`||o.trim().toLowerCase()===`aborted`?{text:t,variant:`muted`}:{text:`Opencode failed to send message with error:\n\`${o}\``,variant:`error`}}var iN=vl(()=>kt(()=>import(`./ToolOutputDialog-Bt7JChFG.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]))),aN=4e3,oN=new Map,sN=new Map,cN=new Set([`bash`,`shell`,`cmd`,`terminal`]),lN=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},uN=e=>{let t=oN.get(e);return t?new Set(t):new Set},dN=(e,t)=>{if(oN.size>=aN&&!oN.has(e)){let e=oN.keys().next().value;typeof e==`string`&&oN.delete(e)}oN.set(e,new Set(t))},fN=e=>{let t=sN.get(e);return t?new Set(t):new Set},pN=(e,t)=>{if(sN.size>=aN&&!sN.has(e)){let e=sN.keys().next().value;typeof e==`string`&&sN.delete(e)}sN.set(e,new Set(t))},mN=200,hN=new Map,gN=e=>hN.get(e),_N=(e,t)=>{if(!t.agent&&!t.provider&&!t.model)return;let n=hN.get(e);if(!(n&&n.agent===t.agent&&n.provider===t.provider&&n.model===t.model)){if(hN.size>=mN&&!hN.has(e)){let e=hN.keys().next().value;typeof e==`string`&&hN.delete(e)}hN.set(e,t)}};function vN(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 yN=(e,t)=>{if(typeof e==`object`&&e)return e[t]},bN=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}=Zt(),{isMobile:m,isTablet:h,hasTouchInput:_}=Ws(),v=zy(),y=By(v),b=m||h,x=Z.useRef(null),S=J(e=>e.currentSessionId),C=Nn(e=>e.getAgentModelForSession),w=Nn(e=>e.getSessionModelSelection),T=J(e=>e.revertToMessage),E=J(e=>e.editMessagePreservingChanges),D=J(e=>e.forkFromMessage),O=J(t=>t.messageEditCommitting?.messageId===e.info.id&&t.messageEditCommitting?.sessionId===e.info.sessionID),k=J(t=>t.stagedMessageEdit?.messageId===e.info.id&&t.stagedMessageEdit?.sessionId===e.info.sessionID),A=J(e=>e.clearStagedMessageEdit);Ct(`ui.chat_message.render`),c&&Ct(`ui.chat_message.render.streaming`);let j=ui(e=>e.providers),{showReasoningTraces:M,stickyUserHeader:N,chatRenderMode:P,showExpandedBashTools:F}=g(Qe(e=>({showReasoningTraces:e.showReasoningTraces,stickyUserHeader:e.stickyUserHeader,chatRenderMode:e.chatRenderMode,showExpandedBashTools:e.showExpandedBashTools})));Z.useEffect(()=>{S&&NT.getInstance().recordSessionStart(S)},[S]);let[I,L]=Z.useState(null),[R,z]=Z.useState(!1),[B,V]=Z.useState(null),H=Z.useRef(null),[ee,U]=Z.useState(()=>uN(e.info.id)),[te,W]=Z.useState(()=>fN(e.info.id)),[ne,G]=Z.useState({open:!1,title:``,content:``});Z.useEffect(()=>{U(uN(e.info.id)),W(fN(e.info.id))},[e.info.id]);let K=Z.useMemo(()=>JM(e.info),[e.info]).isUser,re=K&&(m||!N),ie=K&&!m&&N&&!re,ae=e.info.sessionID,{currentContextAgent:oe,savedSessionAgentSelection:se}=Av(Qe(e=>({currentContextAgent:c&&ae?e.currentAgentContext.get(ae):void 0,savedSessionAgentSelection:c&&ae?e.sessionAgentSelections.get(ae):void 0}))),ce=Z.useMemo(()=>Za(e.sourceParts??e.parts),[e.parts,e.sourceParts]),le=Z.useMemo(()=>K?pi(ce):Za(e.parts),[K,e.parts,ce]),ue=Z.useMemo(()=>{if(K||!t)return null;let e=yN(t.info,`clientRole`),n=yN(t.info,`role`);if((typeof e==`string`?e:typeof n==`string`?n:void 0)!==`user`)return null;let r=yN(t.info,`mode`),i=yN(t.info,`agent`),a=yN(t.info,`providerID`),o=yN(t.info,`modelID`),s=yN(t.info,`model`),c=typeof s==`object`&&s?s.variant:void 0,l=yN(t.info,`variant`),u=c??l,d=typeof s==`object`&&s?s.providerID:void 0,f=typeof s==`object`&&s?s.modelID:void 0,p=typeof r==`string`&&r.trim().length>0?r:typeof i==`string`&&i.trim().length>0?i:void 0,m=typeof a==`string`&&a.trim().length>0?a:typeof d==`string`&&d.trim().length>0?d:void 0,h=typeof o==`string`&&o.trim().length>0?o:typeof f==`string`&&f.trim().length>0?f:void 0,g=typeof u==`string`&&u.trim().length>0?u:void 0;return!p&&!m&&!h&&!g?null:{agentName:p,providerId:m,modelId:h,variant:g}},[K,t]),de=Z.useMemo(()=>{if(K)return;let t=yN(e.info,`mode`);if(typeof t==`string`&&t.trim().length>0)return t;let n=yN(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)},[K,e.info,ue,ae,oe,se]),fe=K?null:yN(e.info,`providerID`),pe=K?null:yN(e.info,`modelID`),me=Z.useMemo(()=>{if(K||!ae)return null;if(ue?.providerId&&ue?.modelId)return{providerId:ue.providerId,modelId:ue.modelId};if(de){let e=C(ae,de);if(e?.providerId&&e?.modelId)return e}let e=w(ae);return e?.providerId&&e?.modelId?e:null},[K,ae,de,ue,C,w]),he=Z.useMemo(()=>K?null:typeof fe==`string`&&fe.trim().length>0?fe:me?.providerId??null,[K,fe,me]),ge=Z.useMemo(()=>K?null:typeof pe==`string`&&pe.trim().length>0?pe:me?.modelId??null,[K,pe,me]),_e=e.info.id?gN(e.info.id):void 0;K||_N(e.info.id,{agent:de,provider:he??void 0,model:ge??void 0});let ve=de??_e?.agent,ye=he??_e?.provider??null,be=ge??_e?.model??null,xe=Z.useMemo(()=>{if(K)return;let e=ye&&j.length>0?j.find(e=>e.id===ye):void 0;return Hr(e,be)||void 0},[K,ye,be,j]),Se=Z.useMemo(()=>{if(K||!he||!ge)return!1;let e=j.find(e=>e.id===he);if(!e?.models||!Array.isArray(e.models))return!1;let t=e.models.find(e=>e.id===ge)?.variants;return!!(t&&Object.keys(t).length>0)},[K,ge,he,j]),Ce=vN(ve),we=vN(ye??void 0),Te=vN(be??void 0),Ee=vN(xe),De=Ce??void 0,Oe=we??null,ke=Te??null,Ae=Ee??void 0,je=Z.useMemo(()=>{let t=e.info.time;return typeof t?.completed==`number`?t.completed:null},[e.info.time]),Me=Z.useMemo(()=>{let t=e.info.time;return typeof t?.created==`number`?t.created:null},[e.info.time]),Ne=Z.useMemo(()=>K?!0:!!(je&&je>0),[K,je]),Pe=Z.useMemo(()=>{let t=e.info.finish;return typeof t==`string`?t:void 0},[e.info]),Fe=Z.useMemo(()=>{if(K)return null;let t=e.info.tokens;return!t||typeof t!=`object`?null:{output:typeof t.output==`number`?t.output:void 0,reasoning:typeof t.reasoning==`number`?t.reasoning:void 0}},[K,e.info]),Ie=Z.useMemo(()=>to(le,{includeReasoning:M}),[le,M]),Le=Z.useMemo(()=>K?Ie:!Ne&&P===`sorted`?[]:Ie,[P,Ne,K,Ie]),Re=Z.useMemo(()=>K?[]:Ie.filter(e=>e.type===`text`),[K,Ie]),ze=Z.useMemo(()=>K?[]:Ie.filter(e=>e.type===`tool`),[K,Ie]),Be=Z.useMemo(()=>{if(!F)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=lN(t.tool);!r||!cN.has(r)||e.add(n)}for(let t of a?.activityParts??[]){if(t.kind!==`tool`)continue;let n=lN(t.part.tool);!n||!cN.has(n)||e.add(t.id)}return e},[F,ze,a?.activityParts]),Ve=Z.useMemo(()=>{if(Be.size===0&&te.size===0)return ee;let e=new Set(ee);return Be.forEach(t=>{te.has(t)||e.add(t)}),te.forEach(t=>{e.delete(t)}),e},[te,Be,ee]),He=Z.useMemo(()=>{if(!K)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}`}},[K,le]),Ue=K&&!Ri(Le),We=typeof Pe!=`string`,Ge=Z.useMemo(()=>K?!1:Re.length===0||ze.length===0?We:!0,[Re.length,ze.length,We,K]),Ke=Z.useMemo(()=>!K&&NT.getInstance().shouldAnimateMessage(e.info,S||e.info.sessionID),[e.info,S,K]),[qe,Je]=Z.useState(!1),Ye=Z.useMemo(()=>n?JM(n.info):null,[n]),Xe=!!a,Ze=a?.isLastAssistantInTurn??!1,$e=$M({isWorking:a?.isWorking===!0,isInActiveTurn:c,headerCompletionDisposition:a?.completionDisposition}),et=Z.useMemo(()=>K?!1:Xe?!Ze:Ye?!Ye.isUser&&Ye.role===`assistant`:!1,[Xe,Ze,K,Ye]),tt=Z.useMemo(()=>Ne?`completed`:c?l??`streaming`:`completed`,[l,c,Ne]);Z.useEffect(()=>{!K||!u||d?.(e.info.id)},[u,K,e.info.id,d]),Z.useEffect(()=>{Je(!1)},[e.info.id]),Z.useEffect(()=>{let t=o??a?.headerMessageId;K||!t||t!==e.info.id||(tt===`streaming`||tt===`cooldown`)&&Je(!0)},[o,K,e.info.id,tt,a?.headerMessageId]);let nt=Z.useMemo(()=>{if(K)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,K,a,tt,e.info.id,s]),rt=Z.useCallback(e=>{en(e).then(t=>{t.ok&&(L(e),setTimeout(()=>L(null),2e3))})},[]),it=K?void 0:a?.userMessageVariant??ue?.variant,at=!K&&Se&&typeof it==`string`&&it.trim().length>0?it:void 0,ot=Z.useMemo(()=>{if(!K)return rN(e.info?.error,p(`chat.messageBody.aborted`))},[K,e.info,p]),st=ot?.text,ct=ot?.variant,lt=Z.useMemo(()=>{if(K){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(`
6576
+ `).trim()||AA(t)},BA=({containerRef:e})=>{let{t}=Zt(),[n,r]=Z.useState({x:0,y:0,show:!1}),[i,a]=Z.useState(``),[o,s]=Z.useState(``),c=Z.useRef(!1),[l,u]=Z.useState(!1),d=Z.useRef(null),f=Z.useRef(EA),p=Z.useRef(null),m=Z.useRef(null),h=Z.useRef(null),_=Z.useRef(!1),v=J(e=>e.createSession),y=Ja(e=>e.setPendingInputText),b=g(e=>e.isMobile),x=By(zy()).textSelectionMutation;Z.useEffect(()=>{_.current=n.show},[n.show]),Z.useEffect(()=>()=>{m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),h.current!==null&&(window.clearTimeout(h.current),h.current=null)},[]);let S=Z.useCallback(()=>{p.current=null,DA===S&&(DA=null),_.current&&=(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),u(!1),r(e=>({...e,show:!1})),a(``),s(``),!1)},[]);Z.useEffect(()=>()=>{DA===S&&(DA=null)},[S]);let C=Z.useCallback(e=>{if(typeof window>`u`)return e;let t=window.innerWidth,n=f.current/2,r=TA+n,i=t-TA-n;return r>i?t/2:Math.min(Math.max(e,r),i)},[]),w=Z.useCallback(()=>{if(!p.current)return;DA!==S&&(DA?.(),DA=S);let{plainText:e,markdownText:t,rect:i}=p.current,o=!n.show,c=b?i.left+i.width/2:C(i.left+i.width/2),l=i.top-10;a(e),s(t),r({x:c,y:l,show:!0}),_.current=!0,o&&(u(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{u(!1),m.current=null}))},[C,S,b,n.show]);Z.useLayoutEffect(()=>{if(!n.show||b||!d.current)return;let e=d.current.offsetWidth;!Number.isFinite(e)||e<=0||e===f.current||(f.current=e,r(e=>({...e,x:C(e.x)})))},[C,b,n.show]),Z.useEffect(()=>{if(!n.show||b)return;let e=()=>{r(e=>({...e,x:C(e.x)}))};return window.addEventListener(`resize`,e),()=>{window.removeEventListener(`resize`,e)}},[C,b,n.show]);let T=Z.useCallback(()=>{let t=window.getSelection(),n=e.current;if(!t||!n){c.current||S();return}let r=AA(t.toString());if(!r){c.current||S();return}let i=NA(t,n);if(!i){c.current||S();return}let a=i.getBoundingClientRect();p.current={plainText:r,markdownText:zA(i,r),rect:a},c.current||w()},[e,S,w]);Z.useEffect(()=>{let t=e.current;if(!t)return;let n=()=>{c.current=!0,S()},r=()=>{c.current=!1,h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{h.current=null,T()},10)},i=new Set,a=()=>{for(let e of MA(t))i.has(e)||(i.add(e),e.addEventListener(`selectionchange`,T))};a();let o=new MutationObserver(a);o.observe(t,{childList:!0,subtree:!0}),document.addEventListener(`selectionchange`,T),t.addEventListener(`mousedown`,n),document.addEventListener(`mouseup`,r);let s=e=>{d.current&&!d.current.contains(e.target)&&!window.getSelection()?.toString().trim()&&S()};return document.addEventListener(`mousedown`,s),()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),o.disconnect();for(let e of i)e.removeEventListener(`selectionchange`,T);document.removeEventListener(`selectionchange`,T),t.removeEventListener(`mousedown`,n),document.removeEventListener(`mouseup`,r),document.removeEventListener(`mousedown`,s)}},[e,T,S,w]),Z.useEffect(()=>{if(!n.show)return;let e=e=>{d.current&&e.target instanceof Node&&d.current.contains(e.target)||S()};return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),()=>{window.removeEventListener(`scroll`,e,!0)}},[n.show,S]);let E=Z.useCallback(e=>{if(!e)return;let t=`\`\`\`md\n${e}\n\`\`\``;y(t,`append`),S(),window.getSelection()?.removeAllRanges()},[y,S]),D=Z.useCallback(()=>{E(o)},[E,o]);Z.useEffect(()=>{let t=t=>{if(!x||!t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||t.key.toLowerCase()!==`i`)return;let n=window.getSelection(),r=e.current;if(!n||!r||!n.toString().trim())return;let i=NA(n,r);i&&(t.preventDefault(),E(zA(i,n.toString())))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[E,x,e]);let O=Z.useCallback(async()=>{i&&(await v(void 0,null,null)&&y(i,`replace`),S(),window.getSelection()?.removeAllRanges())},[i,v,y,S]),k=Z.useCallback(async()=>{if(!i)return;let e=await en(i);e.ok||console.error(`Failed to copy:`,e.error),S(),window.getSelection()?.removeAllRanges()},[i,S]);return n.show?b?(0,ef.createPortal)((0,$.jsx)(`div`,{ref:d,className:Y(`fixed left-3 right-3 bottom-0 z-50 mx-auto max-w-[420px]`,`rounded-2xl border border-[var(--interactive-border)]`,`bg-[var(--surface-elevated)] p-2 shadow-lg`,`safe-area-bottom`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,l?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),style:{bottom:`calc(0.5rem + env(safe-area-inset-bottom, 0px))`},children:(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[x?(0,$.jsxs)(`button`,{onClick:D,className:Y(`flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--primary-base)] text-[var(--primary-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.title.addToCurrentChat`),type:`button`,children:[(0,$.jsx)(X,{name:`add`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.addToChat`)})]}):null,x?(0,$.jsxs)(`button`,{onClick:O,className:Y(`flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.title.newSessionWithSelection`),type:`button`,children:[(0,$.jsx)(X,{name:`chat-new`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.newSession`)})]}):null,(0,$.jsxs)(`button`,{onClick:k,className:Y(`col-span-2 flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--surface-muted)] text-[var(--surface-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.actions.copy`),type:`button`,children:[(0,$.jsx)(X,{name:`file-copy`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.copy`)})]})]})}),document.body):(0,ef.createPortal)((0,$.jsx)(`div`,{ref:d,className:`fixed z-50`,style:{left:n.x,top:n.y,transform:`translate(-50%, -100%)`},children:(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-1 whitespace-nowrap`,`rounded-lg border border-[var(--interactive-border)]`,`bg-[var(--surface-elevated)] shadow-none`,`px-1.5 py-1`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,l?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),children:[x?(0,$.jsxs)(`button`,{onClick:D,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.title.addToCurrentChat`),type:`button`,children:[(0,$.jsx)(X,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.addToChat`)}),(0,$.jsx)(Q_,{shortcut:`⌘+I`})]}):null,x?(0,$.jsx)(`div`,{className:`w-px h-4 bg-[var(--interactive-border)]`}):null,x?(0,$.jsxs)(`button`,{onClick:O,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.title.newSessionWithSelection`),type:`button`,children:[(0,$.jsx)(X,{name:`chat-new`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.newSession`)})]}):null,x?(0,$.jsx)(`div`,{className:`w-px h-4 bg-[var(--interactive-border)]`}):null,(0,$.jsxs)(`button`,{onClick:k,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.actions.copy`),type:`button`,children:[(0,$.jsx)(X,{name:`file-copy`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.copy`)})]})]})}),document.body):null},VA=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),HA=(e,t)=>{let n=new Date(t);return n.setDate(t.getDate()-1),VA(e,n)},UA=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),WA=(e,t)=>{if(!UA(e))return``;let n=new Date(e),r=new Date,i=ys(n,t),a=Qt(),o=tn.getState().dictionary;if(VA(n,r))return i;if(HA(n,r))return nn(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}`},GA=e=>typeof e!=`number`||!Number.isFinite(e)||e<0?0:e,KA=e=>e,qA=e=>{if(!Array.isArray(e)||e.length===0)return 0;let t=0;for(let n of e){let e=KA(n);if(e.type!==`tool`)continue;let r=e.state,i=r?.time?.start,a=r?.time?.end;typeof i!=`number`||!Number.isFinite(i)||typeof a!=`number`||!Number.isFinite(a)||a<i||(t+=a-i)}return t},JA=(e,t,n,r)=>{let i=(typeof e==`number`&&Number.isFinite(e)&&e>0&&typeof t==`number`&&Number.isFinite(t)&&t>e?t-e:null)??(typeof r==`number`&&Number.isFinite(r)&&r>0?r:null);if(i===null)return null;let a=i-qA(n);return!Number.isFinite(a)||a<=0?null:a},YA=e=>{let t=JA(e.createdAt,e.completedAt,e.parts,e.fallbackDurationMs);if(t===null)return null;let n=GA(e.outputTokens)+GA(e.reasoningTokens);if(n<=0)return null;let r=t/1e3;if(r<=0)return null;let i=n/r;return!Number.isFinite(i)||i<=0?null:i},XA=e=>{if(!Number.isFinite(e)||e<=0)return``;if(e>=1e3){let t=e/1e3;return`${t>=10?t.toFixed(0):t.toFixed(1)}k tok/s`}return e>=100?`${Math.round(e)} tok/s`:e>=10?`${e.toFixed(1)} tok/s`:`${e.toFixed(2)} tok/s`},ZA=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=Y(`oc-summary-flip-viewport relative block h-5 min-h-0 w-full min-w-0 max-w-full overflow-clip sm:h-6`,i),t[5]=i,t[6]=m);let h=c&&`invisible`,g;t[7]===h?g=t[8]:(g=Y(`block h-full min-w-0 truncate leading-5 sm:leading-6`,h),t[7]=h,t[8]=g);let _;t[9]!==o||t[10]!==g?(_=(0,$.jsx)(`span`,{className:g,children:o}),t[9]=o,t[10]=g,t[11]=_):_=t[11];let v;t[12]!==o||t[13]!==p||t[14]!==c?(v=c?(0,$.jsxs)(`span`,{className:`oc-summary-flip-stage absolute inset-0 block overflow-clip`,children:[(0,$.jsx)(`span`,{className:`oc-summary-flip-out absolute inset-x-0 top-0 block h-full truncate`,"aria-hidden":`true`,children:c}),(0,$.jsx)(`span`,{className:`oc-summary-flip-in absolute inset-x-0 top-0 block h-full truncate`,onAnimationEnd:p,children:o})]}):null,t[12]=o,t[13]=p,t[14]=c,t[15]=v):v=t[15];let y;return t[16]!==m||t[17]!==_||t[18]!==v?(y=(0,$.jsxs)(`span`,{className:m,children:[_,v]}),t[16]=m,t[17]=_,t[18]=v,t[19]=y):y=t[19],y},QA=[`search`,`read`,`list`];function $A(e){let t=$D(e);return t===`read`?`read`:t===`glob`||t===`grep`?`search`:t===`list`?`list`:null}function ej(e){let t={read:0,search:0,list:0};for(let n of e){let e=$A(n);e&&(t[e]+=1)}return t}var tj=[`edit`,`command`,`other`],nj=new Set([`edit`,`multiedit`,`write`,`create`,`file_write`,`apply_patch`,`patch`]),rj=new Set([`bash`,`shell`,`cmd`,`command`,`exec`,`terminal`]);function ij(e){if(!YD(e))return null;let t=$D(e);return nj.has(t)?`edit`:rj.has(t)?`command`:`other`}function aj(e){let t={edit:0,command:0,other:0};for(let n of e){let e=ij(n);e&&(t[e]+=1)}return t}function oj(e){return SD(e)}var sj=[...QA,...tj];function cj(e){return{...ej(e),...aj(e)}}function lj(e){return QD(e)}function uj(e){return e.kind===`reasoning`||e.type===`reasoning`?!1:e.kind===`justification`||e.type===`text`?!0:e.kind===`tool`||e.type===`tool`?!XD(e.toolName):e.kind!=null||e.type!=null}function dj(e,t,n){for(let r=t;r<e.length;r+=1)if(uj(n(e[r])))return!0;return!1}function fj(e){return`parts`in e?e.parts.some(e=>lj(e))?!0:!e.hasFollowingOtherType&&e.isTurnLive:e.some(e=>lj(e))}function pj(e,t,n){let r=[],i=t;for(;i<e.length&&XD(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var mj=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,hj=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=Y(`inline-flex flex-none items-center gap-0.5 tabular-nums`,mj),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},gj=({activities:e,isMobile:t,isTurnLive:n=!1,hasFollowingOtherType:r=!1,exploring:i,children:a})=>{let{t:o}=Zt(),[s,c]=Z.useState(!1),l=Z.useId(),u=e.map(e=>e.part),d=i??fj({parts:u,hasFollowingOtherType:r,isTurnLive:n}),f=cj(u.map(e=>e.tool)),p=oj(u),m=sj.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:mv(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":s,"aria-controls":l,"aria-label":_,"data-mobile-press-feedback":`soft`,className:Y(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,gv),onClick:h,onKeyDown:g,children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center self-center`,y,t?`w-4`:`w-3.5`),style:{color:`var(--tools-icon)`},children:d?(0,$.jsx)(FD,{isMobile:t,label:o(`chat.usedGroup.running`),className:`block`}):(0,$.jsx)(X,{name:`search`,className:`block h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:Y(`typography-meta inline-flex flex-none items-center self-center font-medium`,y,mj,d&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...d?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:v}),m?(0,$.jsx)(`span`,{className:Y(`typography-meta inline-flex min-h-0 w-0 min-w-0 max-w-full flex-1 items-center self-center overflow-clip`,y,mj),style:{color:`var(--tools-description)`},children:(0,$.jsx)(ZA,{text:m,active:d,className:t?`!h-5 sm:!h-5`:`!h-6 sm:!h-6`})}):null,(0,$.jsx)(hj,{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:hv(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 _j(e,t,n){let r=[],i=t;for(;i<e.length&&JD(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var vj=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null};function yj(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=vj(n.metadata.name);if(e)return e}if(n.input&&typeof n.input==`object`){let e=n.input,t=vj(e.name);if(t)return t;let r=vj(e.id);if(r)return r}if(n.output&&typeof n.output==`object`){let e=vj(n.output.name);if(e)return e}return null}function bj(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 xj=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,Sj=({activities:e,isMobile:t,children:n})=>{let{t:r}=Zt(),[i,a]=Z.useState(!1),o=Z.useId(),s=e.map(e=>e.part),c=s.some(e=>QD(e)),{joinedVisible:l,hiddenCount:u}=bj(s.map(yj)),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:mv(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":i,"aria-controls":o,"aria-label":m,"data-mobile-press-feedback":`soft`,className:Y(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,gv),onClick:f,onKeyDown:p,children:[(0,$.jsx)(`span`,{className:Y(`flex flex-none items-center justify-center`,t?`size-4`:`size-3.5`),style:{color:`var(--tools-icon)`},children:c?(0,$.jsx)(FD,{isMobile:t,label:h,className:`block`}):(0,$.jsx)(X,{name:`book`,className:`h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:Y(`typography-meta flex-none font-medium`,xj,c&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...c?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:h}),d?(0,$.jsx)(`span`,{className:Y(`typography-meta h-5 min-h-0 w-0 min-w-0 max-w-full flex-1 overflow-clip sm:h-6`,xj),style:{color:`var(--tools-description)`},children:(0,$.jsx)(ZA,{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:hv(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]})},Cj=Z.memo(e=>{let t=(0,Q.c)(18),{part:n,messageId:r,onContentChange:i,actions:a,streamPhase:o,onShowPopup:s}=e,c=g(wj),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`,_,v;if(t[0]!==i||t[1]!==f?(_=()=>{f.trim().length!==0&&i?.(`structural`)},v=[i,f],t[0]=i,t[1]=f,t[2]=_,t[3]=v):(_=t[2],v=t[3]),Z.useEffect(_,v),!f||f.trim().length===0)return null;let y=o??`streaming`,b=h&&typeof p?.end!=`number`,x;t[4]!==c||t[5]!==r||t[6]!==i||t[7]!==s||t[8]!==n||t[9]!==m||t[10]!==y||t[11]!==b?(x=(0,$.jsx)(`div`,{"data-message-text-export-source":`true`,children:(0,$.jsx)(jk,{part:n,sessionId:m,messageId:r,streamPhase:y,chatRenderMode:c,hasStreamingHapticLifecycle:b,onContentChange:i,onShowPopup:s})}),t[4]=c,t[5]=r,t[6]=i,t[7]=s,t[8]=n,t[9]=m,t[10]=y,t[11]=b,t[12]=x):x=t[12];let S;t[13]===a?S=t[14]:(S=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]=S);let C;return t[15]!==x||t[16]!==S?(C=(0,$.jsxs)(`div`,{"data-message-text-export-root":`true`,children:[x,S]}),t[15]=x,t[16]=S,t[17]=C):C=t[17],C});function wj(e){return e.chatRenderMode}var Tj=e=>{let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`},Ej=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,Dj=Y(`typography-meta font-medium`,Ej),Oj=Y(`typography-meta`,Ej),kj=[],Aj=e=>{let t=e.part;return t.slim===!0&&(t.type===`tool`||t.type===`reasoning`||t.type===`file`)},jj=e=>{let t=new Set;for(let n of e)Aj(n)&&n.messageId&&t.add(n.messageId);return[...t]},Mj=(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}),Nj=e=>{let t=(0,Q.c)(5),{href:n}=e,[r,i]=Z.useState(!1),a;t[0]===n?a=t[1]:(a=Rl(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},Pj=e=>e,Fj=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},Ij=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},Lj=e=>{let t=e.part.state?.metadata?.dir;return typeof t==`string`&&t.trim().length>0?t:null},Rj=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},zj=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=Rj(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`}`},Bj=e=>{let t=e.part.state,n=t?.input,r=t?.output;if(Array.isArray(n?.todos)){let e=zj(n.todos);if(e)return e}if(Array.isArray(r)){let e=zj(r);if(e)return e}if(r&&typeof r==`object`&&Array.isArray(r.todos)){let e=zj(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=zj(e);if(t)return t}if(e&&typeof e==`object`&&Array.isArray(e.todos)){let t=zj(e.todos);if(t)return t}}catch{}return null},Vj=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)},Hj=(e,t=!0)=>{let n=e.lastIndexOf(`/`);if(n===-1)return(0,$.jsx)(qT,{variant:t?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,Oj),style:{color:`var(--tools-description)`},title:e,children:e});let r=e.slice(0,n),i=e.slice(n+1),a=r.startsWith(`/`),o=a?r.slice(1):r;return(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex max-w-full flex-1 items-baseline overflow-hidden`,Oj),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)(qT,{variant:t?`generate-effect`:`static`,className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:i})]})},Uj=e=>{let t=eu(e);return t?t.toLowerCase().endsWith(`/skill.md`)?t:`${t}/SKILL.md`:``},Wj=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 yj(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`?Bj(e):Fj(e)},Gj=e=>{let t=[],n=[];for(let r of e){if(r.kind!==`tool`)continue;let e=r.part;if(e.tool?.trim().toLowerCase()!==`task`)continue;let i=typeof e.id==`string`?e.id.trim():``;if(!i)continue;let a=e.state;if(!a||typeof a!=`object`)continue;let o=a;n.push(i),(o.status===`pending`||o.status===`running`)&&t.push(i)}return{active:t,all:n}},Kj=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=mv(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)(dk,{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&&FE([e.activity.part],[t.activity.part])),qj=Z.memo(e=>{let t=(0,Q.c)(9),{toolName:n,activities:r,isMobile:i}=e,a;t[0]===i?a=t[1]:(a=mv(i),t[0]=i,t[1]=a);let o;t[2]!==r||t[3]!==i||t[4]!==n?(o=(0,$.jsx)(Xj,{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&&Yj(e.activities,t.activities)),Jj=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.kind===`reasoning`){if(!Ua(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(XD(i)){let r=pj(e,n,e=>e.part.tool);t.push({type:`tool-context-group`,activities:r.items,hasFollowingOtherType:dj(e,r.end,e=>({kind:e.kind,toolName:e.part.tool}))}),n=r.end;continue}if(JD(i)){let r=_j(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(GD(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(WD(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(KD(i)){t.push({type:`tool-static-group`,toolName:i,activities:[r]}),n++;continue}t.push({type:`tool-fallback`,activity:r}),n++}return t},Yj=(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||!FE([r.part],[i.part]))return!1}return!0},Xj=Z.memo(e=>{let t=(0,Q.c)(106),{toolName:n,activities:r,isMobile:i,animateTailText:a}=e,{t:o}=Zt(),s=g(eM),c=Hl(n,o),l;t[0]===n?l=t[1]:(l=JT(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(ac),m=Pu(),h=lt(tM),_=zy(),v=_.kind===`embedded`?_.directory:h,y;t[4]===n?y=t[5]:(y=n.toLowerCase(),t[4]=n,t[5]=y);let b=y===`skill`,x;t[6]===b?x=t[7]:(x={enabled:b},t[6]=b,t[7]=x);let S=an(x),C;t[8]===S.data?C=t[9]:(C=S.data??[],t[8]=S.data,t[9]=C);let w=C,T;t[10]===w?T=t[11]:(T=new Map(w.map(nM)),t[10]=w,t[11]=T);let E=T,D=r[0]??null,O=!D||QD(D.part),k;t[12]===D?k=t[13]:(k=D?Wj(D):null,t[12]=D,t[13]=k);let A=k,j;if(t[14]!==A||t[15]!==D||t[16]!==E||t[17]!==n){bb0:{if(n.toLowerCase()!==`skill`||!D||!A){j=null;break bb0}let e=E.get(A)?.path||Lj(D);if(!e||e===`<built-in>`){j=null;break bb0}let r=Uj(e);if(!r){j=null;break bb0}let i;t[19]!==A||t[20]!==r?(i={name:A,path:r},t[19]=A,t[20]=r,t[21]=i):i=t[21],j=i}t[14]=A,t[15]=D,t[16]=E,t[17]=n,t[18]=j}else j=t[18];let M=j,N;if(t[22]!==v||t[23]!==f||t[24]!==D){bb1:{if(!f||!D){N=null;break bb1}let e=Ij(D);if(!e){N=null;break bb1}let n=nu(e,v);if(!n){N=null;break bb1}let r;t[26]===D?r=t[27]:(r=Vj(D),t[26]=D,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],N=i}t[22]=v,t[23]=f,t[24]=D,t[25]=N}else N=t[25];let P=N,F;t[32]!==v||t[33]!==m||t[34]!==p?(F=(e,t)=>{if(!v)return;let n=ru(v,e);if(!n)return;if(m){m.openFile({path:n,targetLine:t&&Number.isFinite(t)?Math.max(1,Math.trunc(t)):void 0});return}if(p?.editor){p.editor.openFile(n,t);return}if(!tu(n,v)){Vu(n,v).then(()=>{let e=g.getState(),r=v||iu(v,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=g.getState(),i=iu(v,n);if(t&&Number.isFinite(t)){r.openContextFileAtLine(i,n,Math.max(1,Math.trunc(t)),1);return}r.openContextFile(i,n)},t[32]=v,t[33]=m,t[34]=p,t[35]=F):F=t[35];let I=q(F),L;t[36]!==v||t[37]!==m?(L=e=>{let t=eu(e);if(!t)return;let n=()=>{if(m){m.openFile({path:t});return}let e=g.getState(),n=v||iu(``,t);e.openContextFile(n,t)};if(v&&!tu(t,v)){Vu(t,v).then(n);return}n()},t[36]=v,t[37]=m,t[38]=L):L=t[38];let R=q(L),z;t[39]===n?z=t[40]:(z=n.toLowerCase(),t[39]=n,t[40]=z);let B=z,V=B===`grep`||B===`search`||B===`find`||B===`ripgrep`||B===`glob`,H=B===`webfetch`||B===`fetch`||B===`curl`||B===`wget`,ee=B===`skill`,U=!!(P||M),te=!!(P&&v||M),W;t[41]!==te||t[42]!==I||t[43]!==R||t[44]!==U||t[45]!==P||t[46]!==M?(W=()=>{if(!(!U||!te)){if(P){I(P.path,P.offset);return}M&&R(M.path)}},t[41]=te,t[42]=I,t[43]=R,t[44]=U,t[45]=P,t[46]=M,t[47]=W):W=t[47];let ne=q(W),G;t[48]===ne?G=t[49]:(G=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),ne())},t[48]=ne,t[49]=G);let K=q(G),re=U&&te&&`cursor-pointer`,ie=U&&!te&&`cursor-default opacity-70`,ae;t[50]!==re||t[51]!==ie?(ae=Y(`flex w-full items-center gap-x-1.5 min-w-0`,gv,re,ie),t[50]=re,t[51]=ie,t[52]=ae):ae=t[52];let oe=U?`soft`:void 0,se=U?ne:void 0,ce=U?K:void 0,le=U?`button`:void 0,ue=U&&te?0:void 0,de=U&&!te?!0:void 0,fe=i?`size-4`:`size-3.5`,pe;t[53]===fe?pe=t[54]:(pe=Y(`inline-flex items-center justify-center flex-shrink-0`,fe),t[53]=fe,t[54]=pe);let me;t[55]===Symbol.for(`react.memo_cache_sentinel`)?(me={color:`var(--tools-icon)`},t[55]=me):me=t[55];let he=O?(0,$.jsx)(FD,{isMobile:i,label:o(`chat.assistantStatus.usingTool`,{tool:c})}):u,ge;t[56]!==pe||t[57]!==me||t[58]!==he?(ge=(0,$.jsx)(`div`,{className:pe,style:me,children:he}),t[56]=pe,t[57]=me,t[58]=he,t[59]=ge):ge=t[59];let _e,ve;t[60]===Symbol.for(`react.memo_cache_sentinel`)?(_e=Y(Dj,`inline-flex items-center flex-shrink-0 opacity-85`),ve={color:`var(--tools-title)`},t[60]=_e,t[61]=ve):(_e=t[60],ve=t[61]);let ye;t[62]===c?ye=t[63]:(ye=(0,$.jsx)(`span`,{className:_e,style:ve,title:c,children:c}),t[62]=c,t[63]=ye);let be;t[64]!==a||t[65]!==f||t[66]!==P||t[67]!==s?(be=f&&P?(0,$.jsxs)(`span`,{className:Y(`inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left`,Oj),style:{color:`var(--tools-description)`},title:P.offset?`${P.displayPath}:${P.offset}`:P.displayPath,children:[s?(0,$.jsx)(xh,{filePath:P.path,className:`h-3.5 w-3.5`}):null,Hj(P.displayPath,a)]}):null,t[64]=a,t[65]=f,t[66]=P,t[67]=s,t[68]=be):be=t[68];let xe;t[69]!==a||t[70]!==A||t[71]!==V?(xe=V&&A?(0,$.jsx)(`span`,{className:`inline-flex min-w-0 flex-1`,children:(0,$.jsxs)(qT,{variant:a?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,Oj),style:{color:`var(--tools-description)`},title:A,children:[`"`,A,`"`]})}):null,t[69]=a,t[70]=A,t[71]=V,t[72]=xe):xe=t[72];let Se;t[73]!==A||t[74]!==H?(Se=H&&A?(0,$.jsxs)(`a`,{href:A,target:`_blank`,rel:`noopener noreferrer`,onClick:rM,className:Y(`min-w-0 flex-1 inline-flex items-center gap-1.5 underline decoration-[color:var(--status-info)] underline-offset-2 hover:opacity-90`,`truncate whitespace-nowrap`,Oj),style:{color:`var(--status-info)`},title:A,children:[(0,$.jsx)(Nj,{href:A}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:A})]}):null,t[73]=A,t[74]=H,t[75]=Se):Se=t[75];let Ce;t[76]!==ee||t[77]!==M?(Ce=ee&&M?(0,$.jsx)(`span`,{className:Y(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,Oj),style:{color:`var(--tools-description)`},title:M.path,children:M.name}):null,t[76]=ee,t[77]=M,t[78]=Ce):Ce=t[78];let we;t[79]!==A||t[80]!==ee||t[81]!==M?(we=ee&&!M&&A?(0,$.jsx)(`span`,{className:Y(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,Oj),style:{color:`var(--tools-description)`},title:A,children:A}):null,t[79]=A,t[80]=ee,t[81]=M,t[82]=we):we=t[82];let Te;t[83]!==a||t[84]!==A||t[85]!==H||t[86]!==f||t[87]!==V||t[88]!==ee?(Te=!f&&!V&&!H&&!ee&&A?(0,$.jsx)(qT,{variant:a?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,Oj),style:{color:`var(--tools-description)`},children:A}):null,t[83]=a,t[84]=A,t[85]=H,t[86]=f,t[87]=V,t[88]=ee,t[89]=Te):Te=t[89];let Ee;return t[90]!==ae||t[91]!==oe||t[92]!==se||t[93]!==ce||t[94]!==le||t[95]!==ue||t[96]!==de||t[97]!==ge||t[98]!==ye||t[99]!==be||t[100]!==xe||t[101]!==Se||t[102]!==Ce||t[103]!==we||t[104]!==Te?(Ee=(0,$.jsxs)(`div`,{className:ae,"data-mobile-press-feedback":oe,onClick:se,onKeyDown:ce,role:le,tabIndex:ue,"aria-disabled":de,children:[ge,ye,be,xe,Se,Ce,we,Te]}),t[90]=ae,t[91]=oe,t[92]=se,t[93]=ce,t[94]=le,t[95]=ue,t[96]=de,t[97]=ge,t[98]=ye,t[99]=be,t[100]=xe,t[101]=Se,t[102]=Ce,t[103]=we,t[104]=Te,t[105]=Ee):Ee=t[105],Ee},(e,t)=>e.toolName===t.toolName&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&Yj(e.activities,t.activities)),Zj=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)(Uk,{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}),Qj=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)(Cj,{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}),$j=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}=Zt(),_=Ul()??``,v=Z.useMemo(()=>jj(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?Tj(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(()=>Gj(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=Di(_,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=ca(_,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 Di(_,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)&&Aj(e)),ne=te&&!W&&!Mj(t,V),G=Z.useMemo(()=>B?Pj(e):kj,[e,B]),K=Z.useMemo(()=>B?Jj(G):[],[B,G]),re=Z.useMemo(()=>L||z===0?0:Math.max(0,K.length-z),[L,z,K.length]),ie=Z.useMemo(()=>L||z===0?K:K.slice(-z),[L,z,K]);if((!m||I&&!O)&&K.length===0)return null;let ae=(e,t)=>{let n=(0,$.jsx)(`div`,{className:mv(c),children:t});return(0,$.jsx)(Z.Fragment,{children:n},e)},oe=B?ie.map((e,t)=>{switch(e.type){case`reasoning`:return ae(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(Zj,{activity:e.activity,streamPhase:p,onContentChange:f})}));case`justification`:return ae(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(Qj,{activity:e.activity,onContentChange:f,onShowPopup:d,actions:h?.(e.activity),streamPhase:p})}));case`tool-expandable`:return(0,$.jsx)(Kj,{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)(qj,{toolName:e.toolName,activities:e.activities,isMobile:c},e.activities[0]?.id??`static-${e.toolName}-${t}`);case`tool-context-group`:return(0,$.jsx)(gj,{activities:e.activities,isMobile:c,isTurnLive:T,hasFollowingOtherType:e.hasFollowingOtherType,children:e.activities.map(e=>{let t=e.part,n=t.tool?.toLowerCase()??``;return qD(n)?(0,$.jsx)(Xj,{toolName:n,activities:[e],isMobile:c,animateTailText:!1},e.id):(0,$.jsx)(dk,{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)(Sj,{activities:e.activities,isMobile:c,children:e.activities.map(e=>{let t=e.part;return(0,$.jsx)(Xj,{toolName:t.tool?.toLowerCase()??``,activities:[e],isMobile:c,animateTailText:!1},e.id)})},e.activities[0]?.id??`skill-${t}`);case`tool-fallback`:return(0,$.jsx)(Kj,{activity:e.activity,isExpanded:l.has(e.activity.id),isMobile:c,onToggleTool:u,onShowPopup:d,onContentChange:f},e.activity.id);default:return null}}):null,se=ie.length>0;return m?(0,$.jsxs)(`div`,{className:mv(c),children:[(0,$.jsxs)(`button`,{ref:C,type:`button`,className:Y(`group/tool flex w-full min-w-0 flex-nowrap items-center text-left`,c?`gap-x-1`:`gap-x-2`,!I&&gv,I&&`oc-tool-row -mx-2 rounded-lg px-2 py-0.5 cursor-default`,c&&`pr-0`),"data-mobile-press-feedback":I?void 0:`soft`,onClick:I?void 0:R,"aria-expanded":L,"aria-disabled":I||void 0,"aria-label":I?A:g(L?`chat.activity.collapseAria`:`chat.activity.expandAria`),children:[(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 flex-1 items-center overflow-clip`,c?`gap-x-1`:`gap-x-1.5`),children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center`,c?`h-5 w-4`:`h-6 w-3.5`),style:{color:`var(--tools-icon)`},children:T&&!O?(0,$.jsx)(FD,{isMobile:c,label:A,className:`block`}):(0,$.jsx)(X,{name:k,className:`h-3.5 w-3.5`})}),(0,$.jsx)(`span`,{className:Y(`inline-flex flex-shrink-0 items-center`,c?`typography-meta h-5`:`typography-ui-label h-5 font-semibold`,T?`animate-text-shimmer text-[var(--status-info)] [--oc-text-shimmer-base:var(--status-info)]`:`text-foreground/85`),children:A}),E?(0,$.jsx)(`span`,{className:`typography-meta shrink-0 tabular-nums text-muted-foreground`,children:E}):null]}),(0,$.jsxs)(`span`,{className:Y(`ml-auto inline-flex max-w-[min(14rem,55%)] shrink-0 items-center justify-end`,c?`gap-0.5`:`gap-1`),children:[M.length>0?(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 items-center text-muted-foreground`,c?`gap-1`:`gap-1.5`),children:[(0,$.jsx)(`span`,{className:`inline-flex shrink-0 items-center gap-0.5`,"aria-hidden":`true`,children:N.map((e,t)=>(0,$.jsx)(vo,{name:e,size:c?12:14,className:Y(`flex-none`,c?`size-3 min-h-3 min-w-3 max-h-3 max-w-3`:`size-3.5 min-h-3.5 min-w-3.5 max-h-3.5 max-w-3.5`)},`${e}-${t}`))}),(0,$.jsx)(`span`,{className:`typography-meta min-w-0 truncate`,children:g(T?`chat.activity.agentsWorking`:`chat.activity.agentsInvolved`,{count:M.length})})]}):null,I?null:(0,$.jsx)(X,{name:L?`arrow-down-s`:`arrow-right-s`,className:Y(`flex-shrink-0 text-muted-foreground opacity-70`,c&&`-mr-0.5`,c?`size-3`:`size-3.5`)})]})]}),se?(0,$.jsxs)(`div`,{className:I?void 0:`relative ml-2 pl-3`,children:[I?null:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute left-0 top-px bottom-0 w-px opacity-40`,style:{backgroundColor:`var(--tools-border)`}}),re>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:[`+`,re,` more...`]}):null,(0,$.jsx)(`div`,{className:`flow-root`,children:oe})]}):null,L&&(ee||U||ne)?(0,$.jsx)(`div`,{className:Y(`typography-meta flex min-h-9 items-center gap-2 px-2 text-muted-foreground`,I?void 0:`ml-5`,U&&`text-[var(--status-error)]`),role:U?`alert`:`status`,children:ee?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(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)(yo,{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:mv(c),children:oe})});function eM(e){return e.showToolFileIcons}function tM(e){return e.currentDirectory}function nM(e){return[e.name,e]}function rM(e){e.stopPropagation()}var iM=Z.memo(e=>{let t=(0,Q.c)(2),n;return t[0]===e?n=t[1]:(n=(0,$.jsx)($j,{...e}),t[0]=e,t[1]=n),n}),aM={contain:`layout`},oM={containerType:`inline-size`,containerName:`message-footer`},sM=`mt-1.5 mb-0.5 flex items-center justify-start gap-1.5`,cM=`mt-3 mb-0.5 flex items-center justify-start gap-1.5`,lM=`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`,uM=`size-3.5!`,dM=`mt-1.5 mb-0.5 flex flex-wrap items-center gap-3`,fM=`mt-3 mb-0.5 flex flex-wrap items-center gap-3 -ml-[5px]`,pM=`flex items-center gap-2`,mM=`flex items-center gap-2 text-muted-foreground`,hM=`inline-flex h-3.5 items-center gap-1 text-[11px] leading-none tabular-nums text-muted-foreground`,gM=`size-3.5!`,_M=`medium`,vM=e=>e.replace(/\\/g,`/`).split(`/`).filter(Boolean).at(-1)??e,yM=`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)]`,bM=`h-7 gap-1.5`,xM=`h-6 gap-1`,SM=`text-[11px] leading-none`,CM=`size-3.5`,wM=`size-3`,TM=5,EM=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=Y(`flex min-w-0 flex-1 items-center leading-none text-muted-foreground`,i),t[0]=i,t[1]=a);let o=n.file,s=r?`h-3 w-3`:`h-3.5 w-3.5`,c;t[2]===s?c=t[3]:(c=Y(`flex-shrink-0`,s),t[2]=s,t[3]=c);let l;t[4]!==n.file||t[5]!==c?(l=(0,$.jsx)(xh,{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=vM(n.file),t[7]=n.file,t[8]=d);let f;t[9]!==n.file||t[10]!==d?(f=(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-left text-foreground/80`,title:u,children:d}),t[9]=n.file,t[10]=d,t[11]=f):f=t[11];let p=r?`text-[11px]`:`typography-meta`,m;t[12]===p?m=t[13]:(m=Y(`inline-flex flex-shrink-0 items-center gap-0 leading-none tabular-nums`,p),t[12]=p,t[13]=m);let h;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(h={color:`var(--status-success)`},t[14]=h):h=t[14];let g;t[15]===n.additions?g=t[16]:(g=(0,$.jsxs)(`span`,{style:h,children:[`+`,n.additions]}),t[15]=n.additions,t[16]=g);let _,v;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(_=(0,$.jsx)(`span`,{className:`text-muted-foreground/70`,children:`/`}),v={color:`var(--status-error)`},t[17]=_,t[18]=v):(_=t[17],v=t[18]);let y;t[19]===n.deletions?y=t[20]:(y=(0,$.jsxs)(`span`,{style:v,children:[`-`,n.deletions]}),t[19]=n.deletions,t[20]=y);let b;t[21]!==m||t[22]!==g||t[23]!==y?(b=(0,$.jsxs)(`span`,{className:m,children:[g,_,y]}),t[21]=m,t[22]=g,t[23]=y,t[24]=b):b=t[24];let x;return t[25]!==b||t[26]!==a||t[27]!==l||t[28]!==f?(x=(0,$.jsxs)(`span`,{className:a,children:[l,f,b]}),t[25]=b,t[26]=a,t[27]=l,t[28]=f,t[29]=x):x=t[29],x}),DM=Z.memo(e=>{let t=(0,Q.c)(18),{file:n,canOpen:r,isMobile:i,onOpen:a}=e,{t:o}=Zt(),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?xM:bM,d;t[3]===u?d=t[4]:(d=Y(yM,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)(EM,{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)(yo,{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}),OM=Z.memo(e=>{let t=(0,Q.c)(53),{fileCount:n,changedFiles:r,turnId:i,isLatestTurn:a,isMobile:o}=e,{t:s}=Zt(),c=Ul(),l=zy(),u=l.directory||c,d=l.sessionId,f=Pu(),p=g(HM),m;t[0]===r?m=t[1]:(m=r??[],t[0]=r,t[1]=m);let h=m,_;t[2]===h?_=t[3]:(_=h.slice(0,TM),t[2]=h,t[3]=_);let v=_,y=Math.max(0,h.length-v.length),b=h.length>0?h.length:n,x=!!(f||!o&&u||o&&a),S;t[4]!==b||t[5]!==s?(S=s(b===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:b}),t[4]=b,t[5]=s,t[6]=S):S=t[6];let C=S,w;t[7]!==y||t[8]!==s?(w=s(y===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:y}),t[7]=y,t[8]=s,t[9]=w):w=t[9];let T=w,E=Y(yM,o?xM:bM),D=o?wM:CM,O;t[10]===o?O=t[11]:(O=o?Y(SM,`font-semibold text-foreground/85`):`typography-meta font-semibold text-foreground/85`,t[10]=o,t[11]=O);let k=O,A;t[12]===o?A=t[13]:(A=o?Y(SM,`text-muted-foreground`):`typography-meta text-muted-foreground`,t[12]=o,t[13]=A);let j=A,M;t[14]===o?M=t[15]:(M=o?Y(SM,`font-medium`):`typography-meta font-medium`,t[14]=o,t[15]=M);let N=M,P;t[16]!==u||t[17]!==d||t[18]!==a||t[19]!==o||t[20]!==f||t[21]!==i?(P=e=>{if(f){f.openTurnDiff(i,d,e);return}if(!o&&u){Kk({directory:u,filePath:e,turnMessageId:i,sessionId:d});return}o&&a&&u&&Kk({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]=P):P=t[22];let F=q(P),I;t[23]!==u||t[24]!==d||t[25]!==a||t[26]!==o||t[27]!==f||t[28]!==p||t[29]!==i||t[30]!==v[0]?.file?(I=()=>{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=v[0]?.file;e&&o&&a&&u&&Kk({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]=v[0]?.file,t[31]=I):I=t[31];let L=q(I),R=o?`gap-0 border-foreground/15 p-1`:`gap-0.5 border-border/50 p-1.5`,z;t[32]===R?z=t[33]:(z=Y(`mt-4 flex min-w-0 flex-col rounded-[var(--radius-lg)] border bg-muted/20`,R),t[32]=R,t[33]=z);let B=Y(E,`max-w-full text-muted-foreground hover:text-foreground`),V;t[34]===s?V=t[35]:(V=s(`diffView.actions.reviewAria`),t[34]=s,t[35]=V);let H;t[36]===s?H=t[37]:(H=s(`diffView.actions.reviewAria`),t[36]=s,t[37]=H);let ee;t[38]===D?ee=t[39]:(ee=(0,$.jsx)(X,{name:`file-edit`,className:D}),t[38]=D,t[39]=ee);let U=`turn-changes-${i}`,te;t[40]===s?te=t[41]:(te=s(`chat.changedFiles.title`),t[40]=s,t[41]=te);let W;t[42]!==U||t[43]!==te||t[44]!==k?(W=(0,$.jsx)(`span`,{id:U,className:k,children:te}),t[42]=U,t[43]=te,t[44]=k,t[45]=W):W=t[45];let ne;t[46]!==C||t[47]!==j?(ne=(0,$.jsx)(`span`,{className:j,children:C}),t[46]=C,t[47]=j,t[48]=ne):ne=t[48];let G;t[49]===D?G=t[50]:(G=Y(D,`opacity-60`),t[49]=D,t[50]=G);let K;return t[51]===G?K=t[52]:(K=(0,$.jsx)(X,{name:`arrow-right-s`,className:G}),t[51]=G,t[52]=K),(0,$.jsxs)(`section`,{className:z,"data-turn-changes-preview":`true`,"data-message-action-group":`true`,"aria-labelledby":`turn-changes-${i}`,children:[(0,$.jsxs)(yo,{type:`button`,variant:`ghost`,size:`xs`,disabled:!x,onClick:L,className:B,"aria-label":V,title:H,children:[ee,W,ne,K]}),v.length>0?(0,$.jsxs)(`div`,{className:Y(`flex min-w-0 flex-col`,o?`gap-0`:`gap-0.5`),children:[v.map(e=>(0,$.jsx)(DM,{file:e,canOpen:x,isMobile:o,onOpen:F},e.file)),y>0?(0,$.jsxs)(yo,{type:`button`,variant:`ghost`,size:`xs`,disabled:!x,className:Y(E,`text-muted-foreground hover:text-foreground`),onClick:L,"aria-label":s(`diffView.actions.reviewAria`),title:s(`diffView.actions.reviewAria`),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:Y(D,`flex-shrink-0`)}),(0,$.jsxs)(`span`,{className:N,children:[`+`,T]}),(0,$.jsx)(X,{name:`arrow-right-s`,className:D})]}):null]}):null]})}),kM=e=>e.type===`subtask`,AM=e=>{let t=e;return t.type===`text`&&typeof t.shellAction==`object`&&t.shellAction!==null},jM=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}`},MM=e=>{let t=(0,Q.c)(49),{part:n}=e,[r,i]=Z.useState(!1),a=Ul(),{isMobile:o}=Ws(),s=J(UM),c=g(WM),l=zy(),{t:u}=Zt(),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 _=h,v;t[6]===n.prompt?v=t[7]:(v=typeof n.prompt==`string`?n.prompt.trim():``,t[6]=n.prompt,t[7]=v);let y=v,b;t[8]===n.taskSessionID?b=t[9]:(b=typeof n.taskSessionID==`string`?n.taskSessionID.trim():``,t[8]=n.taskSessionID,t[9]=b);let S=b,C;t[10]===n.model?C=t[11]:(C=jM(n.model),t[10]=n.model,t[11]=C);let w=C,T=!!y&&!(o&&l.kind===`primary`),E;t[12]===u?E=t[13]:(E=u(`chat.messageBody.subtask.title`),t[12]=u,t[13]=E);let D;t[14]===E?D=t[15]:(D=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:E}),t[14]=E,t[15]=D);let O;t[16]===m?O=t[17]:(O=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]=O);let k;t[18]===_?k=t[19]:(k=_?(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:[`@`,_]}):null,t[18]=_,t[19]=k);let A;t[20]===w?A=t[21]:(A=w?(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:w}):null,t[20]=w,t[21]=A);let j;t[22]!==k||t[23]!==A||t[24]!==D||t[25]!==O?(j=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[D,O,k,A]}),t[22]=k,t[23]=A,t[24]=D,t[25]=O,t[26]=j):j=t[26];let M;t[27]===f?M=t[28]:(M=f?(0,$.jsx)(`div`,{className:`typography-ui-label text-foreground/90 mt-1.5`,children:f}):null,t[27]=f,t[28]=M);let N;t[29]!==r||t[30]!==y||t[31]!==T||t[32]!==u?(N=T?(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(GM),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:y}):null]}):null,t[29]=r,t[30]=y,t[31]=T,t[32]=u,t[33]=N):N=t[33];let P;t[34]!==_||t[35]!==f||t[36]!==a||t[37]!==o||t[38]!==c||t[39]!==l||t[40]!==s||t[41]!==u||t[42]!==S?(P=S&&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&&Vy(l,S,e,()=>{if(!ma({sessionId:S,directory:e})){if(ff()||o||x()){s(S,e);return}c(e,{mode:`chat`,dedupeKey:`session:${S}`,label:f||_||u(`contextPanel.mode.chat`),readOnly:!0})}})},children:u(`chat.messageBody.subtask.openSession`)})}):null,t[34]=_,t[35]=f,t[36]=a,t[37]=o,t[38]=c,t[39]=l,t[40]=s,t[41]=u,t[42]=S,t[43]=P):P=t[43];let F;return t[44]!==j||t[45]!==M||t[46]!==N||t[47]!==P?(F=(0,$.jsxs)(`div`,{className:`mt-2`,children:[j,M,N,P]}),t[44]=j,t[45]=M,t[46]=N,t[47]=P,t[48]=F):F=t[48],F},NM=e=>{let t=(0,Q.c)(34),{notification:n}=e,r=Ul(),i=g(KM),{isMobile:a}=Ws(),{t:o}=Zt(),s;t[0]!==r||t[1]!==a?(s=r&&!a&&!x(),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),_=c&&`cursor-pointer hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]`,v;t[8]===_?v=t[9]:(v=Y(`mt-2 flex min-w-0 gap-2.5 rounded-[var(--radius-lg)] border border-border/60 bg-muted/20 px-3 py-2.5`,_),t[8]=_,t[9]=v);let y=c?`button`:void 0,b=c?0:void 0,S=c?o(`chat.messageBody.subagent.openSession`,{label:f}):void 0,C=c?p:void 0,w=c?h:void 0,T;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(T=(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]=T):T=t[10];let E;t[11]===f?E=t[12]:(E=(0,$.jsx)(`span`,{className:`typography-meta min-w-0 flex-1 truncate font-semibold text-foreground/90`,children:f}),t[11]=f,t[12]=E);let D=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`,O;t[13]===D?O=t[14]:(O=Y(`inline-flex h-5 flex-shrink-0 items-center rounded px-1.5 text-[11px] leading-none`,D),t[13]=D,t[14]=O);let k;t[15]!==u||t[16]!==O?(k=(0,$.jsx)(`span`,{className:O,children:u}),t[15]=u,t[16]=O,t[17]=k):k=t[17];let A;t[18]!==E||t[19]!==k?(A=(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[E,k]}),t[18]=E,t[19]=k,t[20]=A):A=t[20];let j;t[21]===n.body?j=t[22]:(j=n.body?(0,$.jsx)(`div`,{className:`typography-meta mt-1 max-h-16 overflow-hidden text-muted-foreground [&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,children:(0,$.jsx)(_l,{content:n.body,variant:`tool`,enableFileReferences:!1})}):null,t[21]=n.body,t[22]=j);let M;t[23]!==A||t[24]!==j?(M=(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[A,j]}),t[23]=A,t[24]=j,t[25]=M):M=t[25];let N;return t[26]!==w||t[27]!==M||t[28]!==v||t[29]!==y||t[30]!==b||t[31]!==S||t[32]!==C?(N=(0,$.jsxs)(`div`,{className:v,role:y,tabIndex:b,"aria-label":S,onClick:C,onKeyDown:w,children:[T,M]}),t[26]=w,t[27]=M,t[28]=v,t[29]=y,t[30]=b,t[31]=S,t[32]=C,t[33]=N):N=t[33],N},PM={background:`transparent`,backgroundColor:`transparent`},FM=e=>{let t=(0,Q.c)(36),{part:n}=e,[r,i]=Z.useState(!1),[a,o]=Z.useState(!1),s=Z.useRef(null),{t:c}=Zt(),l;t[0]===n.shellAction?l=t[1]:(l=typeof n.shellAction?.command==`string`?n.shellAction.command.trim():``,t[0]=n.shellAction,t[1]=l);let u=l,d=typeof n.shellAction?.output==`string`?n.shellAction.output:``,f;t[2]===n.shellAction?f=t[3]:(f=typeof n.shellAction?.status==`string`?n.shellAction.status.trim().toLowerCase():``,t[2]=n.shellAction,t[3]=f);let p=f,m;t[4]===d?m=t[5]:(m=d.trim(),t[4]=d,t[5]=m);let h=m.length>0,g;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>{s.current!==null&&typeof window<`u`&&(window.clearTimeout(s.current),s.current=null)},t[6]=g):g=t[6];let _=q(g),v,y;t[7]===_?(v=t[8],y=t[9]):(v=()=>()=>{_()},y=[_],t[7]=_,t[8]=v,t[9]=y),Z.useEffect(v,y);let b;t[10]!==_||t[11]!==h||t[12]!==d?(b=async()=>{h&&(await en(d)).ok&&(_(),o(!0),typeof window<`u`&&(s.current=window.setTimeout(()=>{o(!1),s.current=null},2e3)))},t[10]=_,t[11]=h,t[12]=d,t[13]=b):b=t[13];let x=q(b),S;t[14]===c?S=t[15]:(S=c(`chat.messageBody.shellCommand.title`),t[14]=c,t[15]=S);let C;t[16]===S?C=t[17]:(C=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:S}),t[16]=S,t[17]=C);let w;t[18]===p?w=t[19]:(w=p?(0,$.jsx)(`span`,{className:Y(`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none`,p===`error`?`bg-[var(--status-error-background)] text-[var(--status-error)]`:`bg-foreground/5 text-muted-foreground`),children:p}):null,t[18]=p,t[19]=w);let T;t[20]!==w||t[21]!==C?(T=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[C,w]}),t[20]=w,t[21]=C,t[22]=T):T=t[22];let E;t[23]===u?E=t[24]:(E=u?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 overflow-x-auto font-mono`,children:(0,$.jsx)(gu,{language:`bash`,code:u,codeStyle:PM,wrap:!0})}):null,t[23]=u,t[24]=E);let D;t[25]!==a||t[26]!==x||t[27]!==r||t[28]!==h||t[29]!==d||t[30]!==c?(D=h?(0,$.jsxs)(`div`,{className:`mt-2 border-t border-border/60 pt-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 flex-wrap`,children:[(0,$.jsx)(`button`,{type:`button`,className:`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2`,onClick:()=>i(qM),children:c(r?`chat.messageBody.shellCommand.hideOutput`:`chat.messageBody.shellCommand.showOutput`)}),(0,$.jsx)(`button`,{type:`button`,className:`inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,onClick:()=>{x()},"aria-label":c(a?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),title:c(a?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),children:a?(0,$.jsx)(X,{name:`check`,className:`h-3.5 w-3.5`}):(0,$.jsx)(X,{name:`file-copy`,className:`h-3.5 w-3.5`})})]}),r?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 max-h-56 overflow-auto font-mono text-foreground/85`,children:(0,$.jsx)(gu,{language:`bash`,code:d,codeStyle:PM,wrap:!0})}):null]}):null,t[25]=a,t[26]=x,t[27]=r,t[28]=h,t[29]=d,t[30]=c,t[31]=D):D=t[31];let O;return t[32]!==T||t[33]!==E||t[34]!==D?(O=(0,$.jsxs)(`div`,{className:`mt-2`,children:[T,E,D]}),t[32]=T,t[33]=E,t[34]=D,t[35]=O):O=t[35],O},IM=e=>{let t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`},LM=(e,t)=>{if(t&&typeof t==`object`)return{output:typeof t.output==`number`&&Number.isFinite(t.output)?Math.max(0,t.output):0,reasoning:typeof t.reasoning==`number`&&Number.isFinite(t.reasoning)?Math.max(0,t.reasoning):0};for(let t of e){let e=t.tokens;if(!(!e||typeof e!=`object`))return{output:typeof e.output==`number`&&Number.isFinite(e.output)?Math.max(0,e.output):0,reasoning:typeof e.reasoning==`number`&&Number.isFinite(e.reasoning)?Math.max(0,e.reasoning):0}}return{output:0,reasoning:0}},RM=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:_,editing:v,editStaged:y,onCancelEdit:b,userActionsMode:x=`inline`,stickyUserHeaderEnabled:S=!0})=>{let{locale:C,t:w}=Zt(),T=Cb(),E=By(zy()),D=g(e=>e.timeFormatPreference),[O,k]=Z.useState(!1),A=Z.useRef(null),j=Z.useMemo(()=>n.filter(e=>e.type===`text`?!bi(e):!!(kM(e)||AM(e))),[n]),M=Z.useMemo(()=>j.map(e=>ir(e)?mE(Ua(e)):void 0),[j]),N=f?.token,P=!1,F=!!l,I=!!u,L=!!(s??a),R=!!c,z=x!==`external-actions`,B=x!==`external-content`,V=S&&x===`inline`,H=q(()=>{A.current!==null&&typeof window<`u`&&(window.clearTimeout(A.current),A.current=null)}),ee=q(()=>{!L||!F||!R||typeof window>`u`||(H(),k(!0),A.current=window.setTimeout(()=>{k(!1),A.current=null},1800))});Z.useEffect(()=>{R||(k(!1),H())},[H,R]);let U=q(e=>{!l||!R||(e.stopPropagation(),e.preventDefault(),l(),L&&ee())}),te=T===`mini-chat`||!E.fork?void 0:h,W=Z.useMemo(()=>{if(typeof i!=`number`||i<=0)return null;let e=WA(i,D);return e.length>0?e:null},[C,i,D]),ne=Y(`group/user-actions`,a?x===`inline`?`flex items-center justify-end pt-2 pb-3`:S?`flex h-9 items-start justify-end pt-0`:`flex h-11 items-start justify-end pt-0`:x===`inline`?`absolute top-full left-0 right-0 z-10 pt-5`:`flex h-8 items-start justify-end pt-2`),G=!v&&y&&B?(0,$.jsx)(`div`,{className:ne,children:(0,$.jsxs)(`div`,{className:Y(pM,`justify-end`,!a&&x===`inline`&&`translate-x-5`,`pointer-events-auto opacity-100`),"data-message-action-group":`true`,children:[(0,$.jsxs)(`span`,{className:Y(hM,`text-primary`),"aria-live":`polite`,children:[(0,$.jsx)(X,{weight:_M,name:`edit`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:w(`chat.messageBody.actions.editStaged`)})]}),b?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":w(`chat.messageBody.actions.cancelEdit`),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),b()},children:(0,$.jsx)(X,{weight:_M,name:`close`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.cancelEdit`)})]}):null]})}):null,K=(v&&B?(0,$.jsx)(`div`,{className:ne,children:(0,$.jsx)(`div`,{className:Y(pM,`justify-end`,!a&&x===`inline`&&`translate-x-5`,`pointer-events-none opacity-100`),children:(0,$.jsx)(`span`,{className:Y(hM,`animate-text-shimmer`),"aria-live":`polite`,children:w(`chat.messageBody.actions.editing`)})})}):null)??G??((F&&R||p||m||te)&&B?(0,$.jsx)(`div`,{className:ne,children:(0,$.jsxs)(`div`,{className:Y(pM,`justify-end`,!a&&x===`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:[W?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:Y(hM,`mr-1`),"aria-label":`Message time: ${W}`,children:[(0,$.jsx)(X,{weight:_M,name:`time`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:W})]})}),(0,$.jsx)(Zo,{children:W})]}):null,m&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":w(`chat.messageBody.actions.revertAria`),"aria-busy":_===`revert`,disabled:!!_,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),m()},children:(0,$.jsx)(X,{weight:_M,name:_===`revert`?`loader-4`:`arrow-go-back`,className:Y(uM,_===`revert`&&`animate-spin`)})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.revert`)})]}),p&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":w(`chat.messageBody.actions.editAria`),disabled:!!_,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),p()},children:(0,$.jsx)(X,{weight:_M,name:`edit`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.edit`)})]}),te&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":w(`chat.messageBody.actions.forkAria`),"aria-busy":_===`fork`,disabled:!!_,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),te()},children:(0,$.jsx)(X,{weight:_M,name:_===`fork`?`loader-4`:`git-branch`,className:Y(uM,_===`fork`&&`animate-spin`)})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.fork`)})]}),F&&R&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":O||I?`true`:void 0,className:lM,"aria-label":w(`chat.messageBody.actions.copyMessageAria`),onPointerDown:e=>e.stopPropagation(),onClick:U,onFocus:()=>k(!0),onBlur:()=>{I||k(!1)},children:I?(0,$.jsx)(X,{weight:_M,name:`check`,className:Y(uM,`text-[color:var(--status-success)]`)}):(0,$.jsx)(X,{weight:_M,name:`file-copy`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:w(`chat.messageBody.actions.copyMessage`)})]})]})}):null);return z?(0,$.jsxs)(`div`,{className:`relative w-full group/message`,"data-user-message-body":`true`,style:aM,onTouchStart:L&&F&&R?ee:void 0,children:[(0,$.jsx)(`div`,{className:Y(`leading-relaxed text-foreground/90 text-base overflow-x-hidden`,V?`overflow-y-auto overscroll-contain scrollbar-none`:`overflow-y-hidden`),style:V?{maxHeight:`calc(var(--chat-scroll-height, 100dvh) * 0.4)`}:void 0,children:j.map((e,i)=>{if(kM(e))return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(MM,{part:e})},e.id??`user-subtask-${i}`);if(AM(e))return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(FM,{part:e})},e.id??`user-shell-${i}`);let o=M[i];if(o)return(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(NM,{notification:o})},e.id??`subagent-notification-${i}`);let s;return f&&N&&!P&&Ua(e).includes(N)&&(s=f,P=!0),(0,$.jsx)(Z.Fragment,{children:(0,$.jsx)(GT,{part:e,messageId:t,isMobile:a,agentMention:s,messageParts:r??n})},e.id??`user-text-${i}`)})}),(0,$.jsx)(qh,{files:n,messageID:t,sessionID:e,onShowPopup:d,compact:!0}),K]}):(0,$.jsx)($.Fragment,{children:K})}),zM=Z.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,reviewTransferAction:r,ttsText:i,sessionId:a})=>{let{t:o}=Zt(),s=Cb(),c=zy(),l=By(c),{isPlaying:u,play:d,stop:f}=wA(),p=ui(e=>e.showMessageTTSButtons),m=ui(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)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":h||_?`true`:void 0,className:Y(lM,!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:_M,name:`check`,className:Y(uM,`text-[color:var(--status-success)]`)}):(0,$.jsx)(X,{weight:_M,name:`file-copy`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:o(`chat.messageBody.actions.copyAnswer`)})]}),w?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":o(`chat.messageBody.actions.openSourceSessionAria`),onPointerDown:e=>e.stopPropagation(),onClick:A,children:(0,$.jsx)(X,{weight:_M,name:`target`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:o(`chat.messageBody.actions.openSourceSession`)})]}):null,r&&s!==`mini-chat`&&l.reviewTransfer?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,size:`icon`,variant:`ghost`,disabled:y||!e,className:Y(lM,(!e||y)&&`opacity-50`),"aria-label":r.ariaLabel,onPointerDown:e=>e.stopPropagation(),onClick:e=>{k(e)},children:y?(0,$.jsx)(X,{weight:_M,name:`loader-4`,className:Y(uM,`animate-spin`)}):(0,$.jsx)(X,{weight:_M,name:`arrow-left-right`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:r.tooltip})]}):null,s!==`mini-chat`&&p&&e&&(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:Y(lM,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:_M,name:`stop`,className:uM}):(0,$.jsx)(X,{weight:_M,name:`volume-up`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:j})]})]})}),BM=Z.memo(({sessionId:e,messageId:t,parts:n,sourceParts:r,isMessageCompleted:i,messageFinish:a,messageCompletedAt:o,messageCreatedAt:s,messageTokens:c,isMobile:l,alwaysShowActions:u,hasTouchInput:d,expandedTools:f,onToggleTool:p,onShowPopup:m,streamPhase:h,allowAnimation:_,onContentChange:v,hasTextContent:y=!1,onCopyMessage:b,onAuxiliaryContentComplete:S,showReasoningTraces:C=!1,turnGroupingContext:w,errorMessage:T,errorVariant:E=`error`,reviewTransferDirection:D=null})=>{let{t:O,locale:k}=Zt(),A=Cb(),j=By(zy()),M=h,N=Z.useRef(null),P=Z.useRef(null),F=h===`streaming`||h===`cooldown`,I=Z.useRef({messageId:t,experiencedStreamingOrCooldown:F});I.current.messageId===t?F&&(I.current.experiencedStreamingOrCooldown=!0):I.current={messageId:t,experiencedStreamingOrCooldown:F};let L=!!(d??l),R=!!(u??l),z=l?fM:dM,B=!i,V=Z.useMemo(()=>n.filter(e=>!bi(e)).filter(e=>e.type!==`compaction`),[n]),H=Z.useMemo(()=>V.filter(e=>e.type===`tool`),[V]),ee=Z.useMemo(()=>V.filter(e=>e.type===`text`),[V]),U=Z.useMemo(()=>ao(ee),[ee]),te=g(e=>e.openContextPreview),W=x(),ne=A===`mini-chat`,G=Z.useMemo(()=>{if(W||l||ne)return null;for(let e of ee){let t=e.text;if(typeof t!=`string`||t.length===0)continue;let n=zl(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 H){let t=e.state,n=t&&typeof t.output==`string`?t.output:null;if(!n)continue;let r=zl(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},[ee,l,ne,W,H]),K=J(e=>e.forkFromMessage),re=J(e=>e.forkTransition),ie=J(e=>e.currentSessionId),ae=J(e=>e.getDirectoryForSession),oe=Ul(),se=D===`review-to-original`,ce=!l&&!W?D:null,le=Z.useMemo(()=>{let t=U.trim();if(!(!e||!oe||!t||!ce))return ce===`review-to-original`?{ariaLabel:O(`chat.messageBody.actions.sendReviewFeedback`),tooltip:O(`chat.messageBody.actions.sendReviewFeedback`),onClick:async()=>{try{await Tn(e,oe,t)}catch(e){console.error(`[review-flow] failed to send review feedback`,e)}}}:{ariaLabel:O(`chat.messageBody.actions.sendImplementationResponse`),tooltip:O(`chat.messageBody.actions.sendImplementationResponse`),onClick:async()=>{try{await An(e,oe,t)}catch(e){console.error(`[review-flow] failed to send implementation response`,e)}}}},[U,oe,ce,e,O]),[ue,de]=Z.useState(!1),fe=g(e=>e.chatRenderMode),pe=g(e=>e.collapsibleThinkingBlocks),me=g(e=>e.showSplitAssistantMessageActions),he=g(e=>e.showAssistantTps),ge=g(e=>e.timeFormatPreference),_e=fe===`sorted`,ve=w?.isLastAssistantInTurn??!1,ye=a===`stop`,be=(ye||i||!!T)&&(w?.isTurnSettled??!0),xe=ye?`completed`:M,Se=H.length>0,Ce=Z.useMemo(()=>H.some(e=>QD(e)),[H]),we=QD,Te=ZD,Ee=I.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||!Pr())return;let n=De.current,r=!n.initialized;n.initialized=!0;for(let i of H){if(n.observedPartIds.has(i.id))continue;if(!vn(r,we(i))){n.observedPartIds.add(i.id);continue}let a=e??i.sessionID;a&&(n.observedPartIds.add(i.id),xi({sessionID:a,messageID:t,partID:i.id,kind:`tool`}))}},[Ee,we,t,e,H]);let Oe=Z.useMemo(()=>H.length===0||!Ce&&H.every(e=>Te(e)),[H,Ce,Te]),ke=Z.useMemo(()=>V.filter(e=>e.type===`reasoning`),[V]),Ae=Z.useMemo(()=>ke.length===0||ke.every(e=>typeof e.time?.end==`number`),[ke]),je=typeof a!=`string`,Me=ke.length>0&&Se&&(Ce||je||!Oe),Ne=B||Se&&(Ce||je||!Oe),Pe=B||Me,Fe=Se||ke.length>0,Ie=ee.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,S?.())},[Le,S]),Z.useEffect(()=>{if(B){ze.current=!1;return}if(Se){ze.current=!1;return}ke.length!==0&&(Pe||!Ae||ze.current||(ze.current=!0,v?.(`structural`)))},[B,Se,v,Ae,ke.length,Pe]);let Be=!!y&&!B,Ve=q(async n=>{if(n.stopPropagation(),n.preventDefault(),!(!e||!t||ue||re)){de(!0);try{await K(e,t)}finally{de(!1)}}}),He=Z.useMemo(()=>{let e=w?.activityParts;return!_e||!e?[]:e},[_e,w?.activityParts]),Ue=Z.useMemo(()=>{let e=w?.activityGroupSegments;return!_e||!e?[]:e.filter(e=>e.anchorMessageId===t)},[_e,t,w?.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=w?.toggleGroup,qe=w?.activityPresentationKind===`compaction`,Je=w?.isGroupExpanded===!0,Ye=_e&&qe&&!Je,Xe=_e?w?.activityOwnerMessageId===t||We:!w?.activityOwnerMessageId||w.activityOwnerMessageId===t||We,Ze=_e&&Xe&&(We||qe)&&!!Ke,Qe=$k(a,V),$e={finish:a,parts:V,streamPhase:xe,error:T,isLastAssistantInTurn:ve},et=iA($e),tt=_e&&aA($e),nt=_e&&!et&&!(qe&&Je),rt=!!T,it=E===`info`?`information`:`error-warning`,at=E===`muted`,ot=Be,st=ve&&be&&!Ye&&(y||!!T||i),ct=w?.diffStats?.hasDiffs===!0,lt=!ne&&ve&&Qe&&be&&!Ye&&w?.diffStats?.hasDiffs===!0,ut=me&&ot&&!st&&!_e,dt=Z.useMemo(()=>(0,$.jsx)(zM,{hasCopyableText:Be,isTouchContext:L,onCopyMessage:b,ttsText:U,reviewTransferAction:le,sessionId:e}),[U,Be,L,b,le,e]),ft=Z.useMemo(()=>e=>{if(!me||!_e)return null;let t=Ua(e.part).trim();return t?(0,$.jsx)(zM,{hasCopyableText:!0,isTouchContext:L,onCopyMessage:async()=>(await en(t)).ok,ttsText:t}):null},[_e,L,me]),pt=Z.useMemo(()=>{if(!ut)return-1;let e=-1;for(let t=0;t<V.length;t+=1){let n=V[t];!n||n.type!==`text`||nt||Ge.get(n)?.kind!==`justification`&&(e=t)}return e},[Ge,nt,ut,V]),mt=ut&&pt<0,ht=Z.useMemo(()=>{let n=[];if(Ze&&Ke&&w){let e=(e,t,r=t)=>{n.push((0,$.jsx)(`div`,{children:(0,$.jsx)(iM,{parts:t,materializationParts:r,isExpanded:w.isGroupExpanded===!0,collapsedPreviewCount:0,completionDisposition:w.completionDisposition,activityPresentationKind:w.activityPresentationKind,durationMs:w.durationMs,startedAt:w.userMessageCreatedAt,onToggle:Ke,isMobile:l,expandedTools:f,onToggleTool:p,onShowPopup:m,onContentChange:v,streamPhase:xe,showHeader:!0,diffStats:w.diffStats,renderJustificationActions:ft})},`progressive-group-${e}`))};Ue.length>0?Ue.forEach(t=>{let n=C?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<V.length;){let i=V[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:P,"data-message-text-export-source":`true`,children:(0,$.jsx)(jk,{part:i,sessionId:e,messageId:t,streamPhase:xe,chatRenderMode:fe,allowSortedFinalStreaming:tt,hasStreamingHapticLifecycle:Ee,onContentChange:v,onShowPopup:m})},`assistant-text-${t}-${i.id??r}`)),ut&&r===pt&&n.push((0,$.jsx)(`div`,{className:l?cM:sM,"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:pM,"data-message-action-group":`true`,children:dt})},`message-actions-${t}`)),r++;continue}if(i.type===`reasoning`){if(Ge.get(i)?.kind===`reasoning`){r+=1;continue}if(!Ua(i).trim()){r+=1;continue}C&&(pe?n.push((0,$.jsx)(`div`,{className:mv(l),children:(0,$.jsx)(Uk,{part:i,messageId:t,streamPhase:xe,onContentChange:v})},`reasoning-${t}-${i.id??r}`)):n.push((0,$.jsx)(jk,{part:i,sessionId:e,messageId:t,streamPhase:xe,chatRenderMode:fe,hasStreamingHapticLifecycle:Ee,onContentChange:v,onShowPopup:m},`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(XD(a)){let e=pj(V,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)(gj,{activities:i,isMobile:l,isTurnLive:xe!==`completed`,hasFollowingOtherType:dj(V,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 qD(n)?(0,$.jsx)(Xj,{toolName:n,activities:[e],isMobile:l,animateTailText:!1},e.id):(0,$.jsx)(dk,{part:e.part,messageId:t,isExpanded:f.has(e.part.id),onToggle:p,isMobile:l,alwaysShowActions:R,onContentChange:v,onShowPopup:m,animateTailText:!1},e.id)})},`context-tools-${i[0].id}`)),r=e.end;continue}}if(JD(a)){let e=_j(V,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)(Sj,{activities:i,isMobile:l,children:i.map(e=>(0,$.jsx)(Xj,{toolName:e.part.tool?.toLowerCase()??``,activities:[e],isMobile:l,animateTailText:!1},e.id))},`skill-tools-${i[0].id}`)),r=e.end;continue}}if(WD(a)){n.push((0,$.jsx)(`div`,{className:mv(l),children:(0,$.jsx)(dk,{part:e,messageId:t,isExpanded:f.has(e.id),onToggle:p,isMobile:l,alwaysShowActions:R,onContentChange:v,onShowPopup:m,animateTailText:!1})},`tool-${e.id}`)),r++;continue}n.push((0,$.jsx)(`div`,{className:mv(l),children:(0,$.jsx)(Xj,{toolName:a,activities:[{id:e.id,turnId:``,messageId:t,partIndex:r,part:e,kind:`tool`}],isMobile:l,animateTailText:!1})},`static-tools-${e.id}`)),r++;continue}r++}return n},[Ge,Ue,R,fe,pe,0,f,Ye,qe,l,Xe,_e,pt,t,dt,ft,e,v,m,p,Ze,ut,xe,Ee,C,nt,tt,Ke,w,V]),gt=Z.useMemo(()=>{if(!ve||!be)return;let e=w?.durationMs;if(!(typeof e!=`number`||e<=0))return IM(e)},[ve,be,w?.durationMs]),_t=Z.useMemo(()=>{let e=typeof o==`number`&&o>0?o:typeof s==`number`&&s>0?s:null;if(e===null)return null;let t=WA(e,ge);return t.length>0?t:null},[o,s,ge,k]),vt=Z.useMemo(()=>{if(!he||!ve||!be)return null;let e=r??n,t=LM(e,c),i=YA({createdAt:s,completedAt:o,fallbackDurationMs:w?.durationMs,outputTokens:t.output,reasoningTokens:t.reasoning,parts:e});if(i===null)return null;let a=XA(i);return a.length>0?a:null},[he,ve,be,n,r,c,s,o,w?.durationMs]),yt=(0,$.jsxs)($.Fragment,{children:[!ne&&!l&&!W&&G?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:lM,"aria-label":O(`chat.messageBody.actions.openPreviewAria`),onPointerDown:e=>e.stopPropagation(),onClick:()=>{let e=oe??(ie?ae(ie):null);e&&te(e,G)},children:(0,$.jsx)(X,{weight:_M,name:`global`,className:uM})})}),(0,$.jsx)(Zo,{sideOffset:6,children:O(`chat.messageBody.actions.openPreview`)})]}):null,!ne&&!se&&j.fork?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,size:`icon`,variant:`ghost`,className:lM,"aria-label":O(`chat.messageBody.actions.forkAria`),"aria-busy":ue,disabled:ue||!!re,onPointerDown:e=>e.stopPropagation(),onClick:e=>{Ve(e)},children:(0,$.jsx)(X,{weight:_M,name:ue?`loader-4`:`git-branch`,className:Y(uM,ue&&`animate-spin`)})})}),(0,$.jsx)(Zo,{sideOffset:6,children:O(`chat.messageBody.actions.fork`)})]}):null]});return(0,$.jsxs)(`div`,{ref:N,"data-message-text-export-root":`true`,className:Y(`relative w-full group/message`),style:aM,children:[(0,$.jsx)(BA,{containerRef:N}),(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:[ht,rt&&(0,$.jsx)(Jl,{children:at?(0,$.jsxs)(`div`,{role:`status`,className:`my-1.5 flex max-w-full items-center gap-1.5 break-words typography-meta text-muted-foreground`,children:[(0,$.jsx)(X,{name:`stop-circle`,className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`min-w-0`,children:T})]}):(0,$.jsxs)(`div`,{className:Y(`group/assistant-text relative flow-root my-1.5 break-words max-w-full`,E===`info`?Y(`inline-flex w-fit max-w-full border border-[var(--status-info-border)]/45 bg-[var(--status-info-background)]/40`,l?`items-start gap-1.5 rounded-lg px-2.5 py-1.5`:Y(`items-center gap-1.5`,`rounded-lg px-2 py-0.5`)):`mt-3 flex items-center gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3`),children:[E===`info`&&l?(0,$.jsx)(`span`,{className:`inline-flex h-5 w-3.5 shrink-0 items-center justify-center translate-y-[2px]`,"aria-hidden":`true`,children:(0,$.jsx)(X,{name:it,weight:_M,className:Y(uM,`text-[var(--status-info)]/80`)})}):(0,$.jsx)(X,{name:it,weight:E===`info`?_M:void 0,className:Y(`shrink-0`,E===`info`?Y(uM,`text-[var(--status-info)]/80`):`h-4 w-4 text-[var(--status-error)]`)}),(0,$.jsx)(`div`,{className:Y(`min-w-0 break-words`,E===`info`?Y(`text-muted-foreground [&_.markdown-content]:text-muted-foreground [&_p]:m-0`,`[&_.markdown-content]:!leading-5`,l?`[&_.markdown-content]:!text-[length:var(--text-meta)]`:`[&_.markdown-content]:!text-[13px]`):`flex-1`),children:(0,$.jsx)(_l,{content:T??``,onShowPopup:m,className:`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,enableFileReferences:!1})})]})},`assistant-error`)]}),lt&&w?.diffStats?(0,$.jsx)(OM,{fileCount:w.diffStats.files,changedFiles:w.changedFiles,turnId:w.turnId,isLatestTurn:w.isLatestTurn,isMobile:l}):null,(0,$.jsx)(qh,{files:n,messageID:t,sessionID:e,onShowPopup:m}),mt&&(0,$.jsx)(`div`,{className:Y(l?cM:sM),"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:pM,"data-message-action-group":`true`,children:dt})}),st&&(0,$.jsxs)(`div`,{className:z,"data-message-footer":`true`,style:oM,children:[(0,$.jsxs)(`div`,{className:pM,"data-message-action-group":`true`,children:[dt,yt]}),vt||gt||_t?(0,$.jsxs)(`div`,{className:mM,children:[vt?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:hM,"aria-label":O(`chat.messageBody.meta.tpsAria`,{rate:vt}),children:[(0,$.jsx)(X,{weight:_M,name:`pulse`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:vt})]})}),(0,$.jsx)(Zo,{children:O(`chat.messageBody.meta.tpsTooltip`)})]}):null,gt?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:hM,children:[(0,$.jsx)(X,{weight:_M,name:`hourglass`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:gt})]})}),(0,$.jsx)(Zo,{children:gt})]}):null,_t?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:hM,"aria-label":`Message time: ${_t}`,children:[(0,$.jsx)(X,{weight:_M,name:`time`,className:gM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:_t})]})}),(0,$.jsx)(Zo,{children:_t})]}):null]}):null,!ne&&ve&&ye&&!ct?(0,$.jsx)(qk,{activityParts:w?.activityParts}):null]})]})]})}),VM=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)(RM,{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)(BM,{...r}),t[26]=r,t[27]=i),i});function HM(e){return e.openContextPanelTab}function UM(e){return e.setCurrentSession}function WM(e){return e.openContextPanelTab}function GM(e){return!e}function KM(e){return e.openContextPanelTab}function qM(e){return!e}var JM=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}},YM=(e,t,n)=>e===`active`||n?.isLastTurn&&n.hasConfirmedFinalBody!==!0?!0:t===`summary`,XM=e=>!e,ZM=e=>e.completionDisposition===`active`?e.isLastTurn&&e.sessionIsWorking?{completionDisposition:`active`,durationMs:e.durationMs}:{completionDisposition:`abnormal`,durationMs:e.durationMs}:{completionDisposition:e.completionDisposition,durationMs:e.durationMs},QM=e=>!(e.completionDisposition===`active`||e.isLastTurn&&e.sessionIsWorking&&!e.hasConfirmedSettledAssistant),$M=e=>e.isWorking?!0:e.isInActiveTurn?e.headerCompletionDisposition!==`normal`&&e.headerCompletionDisposition!==`abnormal`:!1,eN=e=>e.turnCompletionDisposition===`active`&&(e.isLastTurn||e.hasAssistantMessages)?`active`:e.headerPresentationDisposition,tN=`Authentication failed for this provider. Please re-authenticate and retry.`,nN=e=>{if(typeof e!=`string`)return!1;let t=e.toLowerCase().trim();if(!t)return!1;if(t.includes(`token refresh failed`)||t.includes(`unauthorized`)||t.includes(`invalid token`)||t.includes(`expired token`))return!0;let n=t.includes(`oauth`),r=t.includes(`failed`)||t.includes(`invalid`)||t.includes(`expired`);if(n&&r)return!0;let i=/\b401\b/.test(t),a=t.includes(`auth`)||t.includes(`token`)||t.includes(`unauthorized`);return i&&a};function rN(e,t){if(!e||typeof e!=`object`)return;let n=e,r=typeof n.data?.message==`string`?n.data.message:void 0,i=typeof n.message==`string`?n.message:void 0,a=typeof n.name==`string`?n.name:void 0,o=r||i||a;if(o)return a===`SessionRetry`?{text:`Opencode failed to send a message. Retry attempt info: \n\`${o}\``,variant:`info`}:nN(o)?{text:tN,variant:`error`}:a===`MessageAbortedError`||o.trim().toLowerCase()===`aborted`?{text:t,variant:`muted`}:{text:`Opencode failed to send message with error:\n\`${o}\``,variant:`error`}}var iN=vl(()=>kt(()=>import(`./ToolOutputDialog-C7cKReps.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]))),aN=4e3,oN=new Map,sN=new Map,cN=new Set([`bash`,`shell`,`cmd`,`terminal`]),lN=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},uN=e=>{let t=oN.get(e);return t?new Set(t):new Set},dN=(e,t)=>{if(oN.size>=aN&&!oN.has(e)){let e=oN.keys().next().value;typeof e==`string`&&oN.delete(e)}oN.set(e,new Set(t))},fN=e=>{let t=sN.get(e);return t?new Set(t):new Set},pN=(e,t)=>{if(sN.size>=aN&&!sN.has(e)){let e=sN.keys().next().value;typeof e==`string`&&sN.delete(e)}sN.set(e,new Set(t))},mN=200,hN=new Map,gN=e=>hN.get(e),_N=(e,t)=>{if(!t.agent&&!t.provider&&!t.model)return;let n=hN.get(e);if(!(n&&n.agent===t.agent&&n.provider===t.provider&&n.model===t.model)){if(hN.size>=mN&&!hN.has(e)){let e=hN.keys().next().value;typeof e==`string`&&hN.delete(e)}hN.set(e,t)}};function vN(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 yN=(e,t)=>{if(typeof e==`object`&&e)return e[t]},bN=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}=Zt(),{isMobile:m,isTablet:h,hasTouchInput:_}=Ws(),v=zy(),y=By(v),b=m||h,x=Z.useRef(null),S=J(e=>e.currentSessionId),C=Nn(e=>e.getAgentModelForSession),w=Nn(e=>e.getSessionModelSelection),T=J(e=>e.revertToMessage),E=J(e=>e.editMessagePreservingChanges),D=J(e=>e.forkFromMessage),O=J(t=>t.messageEditCommitting?.messageId===e.info.id&&t.messageEditCommitting?.sessionId===e.info.sessionID),k=J(t=>t.stagedMessageEdit?.messageId===e.info.id&&t.stagedMessageEdit?.sessionId===e.info.sessionID),A=J(e=>e.clearStagedMessageEdit);Ct(`ui.chat_message.render`),c&&Ct(`ui.chat_message.render.streaming`);let j=ui(e=>e.providers),{showReasoningTraces:M,stickyUserHeader:N,chatRenderMode:P,showExpandedBashTools:F}=g(Qe(e=>({showReasoningTraces:e.showReasoningTraces,stickyUserHeader:e.stickyUserHeader,chatRenderMode:e.chatRenderMode,showExpandedBashTools:e.showExpandedBashTools})));Z.useEffect(()=>{S&&NT.getInstance().recordSessionStart(S)},[S]);let[I,L]=Z.useState(null),[R,z]=Z.useState(!1),[B,V]=Z.useState(null),H=Z.useRef(null),[ee,U]=Z.useState(()=>uN(e.info.id)),[te,W]=Z.useState(()=>fN(e.info.id)),[ne,G]=Z.useState({open:!1,title:``,content:``});Z.useEffect(()=>{U(uN(e.info.id)),W(fN(e.info.id))},[e.info.id]);let K=Z.useMemo(()=>JM(e.info),[e.info]).isUser,re=K&&(m||!N),ie=K&&!m&&N&&!re,ae=e.info.sessionID,{currentContextAgent:oe,savedSessionAgentSelection:se}=Av(Qe(e=>({currentContextAgent:c&&ae?e.currentAgentContext.get(ae):void 0,savedSessionAgentSelection:c&&ae?e.sessionAgentSelections.get(ae):void 0}))),ce=Z.useMemo(()=>Za(e.sourceParts??e.parts),[e.parts,e.sourceParts]),le=Z.useMemo(()=>K?pi(ce):Za(e.parts),[K,e.parts,ce]),ue=Z.useMemo(()=>{if(K||!t)return null;let e=yN(t.info,`clientRole`),n=yN(t.info,`role`);if((typeof e==`string`?e:typeof n==`string`?n:void 0)!==`user`)return null;let r=yN(t.info,`mode`),i=yN(t.info,`agent`),a=yN(t.info,`providerID`),o=yN(t.info,`modelID`),s=yN(t.info,`model`),c=typeof s==`object`&&s?s.variant:void 0,l=yN(t.info,`variant`),u=c??l,d=typeof s==`object`&&s?s.providerID:void 0,f=typeof s==`object`&&s?s.modelID:void 0,p=typeof r==`string`&&r.trim().length>0?r:typeof i==`string`&&i.trim().length>0?i:void 0,m=typeof a==`string`&&a.trim().length>0?a:typeof d==`string`&&d.trim().length>0?d:void 0,h=typeof o==`string`&&o.trim().length>0?o:typeof f==`string`&&f.trim().length>0?f:void 0,g=typeof u==`string`&&u.trim().length>0?u:void 0;return!p&&!m&&!h&&!g?null:{agentName:p,providerId:m,modelId:h,variant:g}},[K,t]),de=Z.useMemo(()=>{if(K)return;let t=yN(e.info,`mode`);if(typeof t==`string`&&t.trim().length>0)return t;let n=yN(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)},[K,e.info,ue,ae,oe,se]),fe=K?null:yN(e.info,`providerID`),pe=K?null:yN(e.info,`modelID`),me=Z.useMemo(()=>{if(K||!ae)return null;if(ue?.providerId&&ue?.modelId)return{providerId:ue.providerId,modelId:ue.modelId};if(de){let e=C(ae,de);if(e?.providerId&&e?.modelId)return e}let e=w(ae);return e?.providerId&&e?.modelId?e:null},[K,ae,de,ue,C,w]),he=Z.useMemo(()=>K?null:typeof fe==`string`&&fe.trim().length>0?fe:me?.providerId??null,[K,fe,me]),ge=Z.useMemo(()=>K?null:typeof pe==`string`&&pe.trim().length>0?pe:me?.modelId??null,[K,pe,me]),_e=e.info.id?gN(e.info.id):void 0;K||_N(e.info.id,{agent:de,provider:he??void 0,model:ge??void 0});let ve=de??_e?.agent,ye=he??_e?.provider??null,be=ge??_e?.model??null,xe=Z.useMemo(()=>{if(K)return;let e=ye&&j.length>0?j.find(e=>e.id===ye):void 0;return Hr(e,be)||void 0},[K,ye,be,j]),Se=Z.useMemo(()=>{if(K||!he||!ge)return!1;let e=j.find(e=>e.id===he);if(!e?.models||!Array.isArray(e.models))return!1;let t=e.models.find(e=>e.id===ge)?.variants;return!!(t&&Object.keys(t).length>0)},[K,ge,he,j]),Ce=vN(ve),we=vN(ye??void 0),Te=vN(be??void 0),Ee=vN(xe),De=Ce??void 0,Oe=we??null,ke=Te??null,Ae=Ee??void 0,je=Z.useMemo(()=>{let t=e.info.time;return typeof t?.completed==`number`?t.completed:null},[e.info.time]),Me=Z.useMemo(()=>{let t=e.info.time;return typeof t?.created==`number`?t.created:null},[e.info.time]),Ne=Z.useMemo(()=>K?!0:!!(je&&je>0),[K,je]),Pe=Z.useMemo(()=>{let t=e.info.finish;return typeof t==`string`?t:void 0},[e.info]),Fe=Z.useMemo(()=>{if(K)return null;let t=e.info.tokens;return!t||typeof t!=`object`?null:{output:typeof t.output==`number`?t.output:void 0,reasoning:typeof t.reasoning==`number`?t.reasoning:void 0}},[K,e.info]),Ie=Z.useMemo(()=>to(le,{includeReasoning:M}),[le,M]),Le=Z.useMemo(()=>K?Ie:!Ne&&P===`sorted`?[]:Ie,[P,Ne,K,Ie]),Re=Z.useMemo(()=>K?[]:Ie.filter(e=>e.type===`text`),[K,Ie]),ze=Z.useMemo(()=>K?[]:Ie.filter(e=>e.type===`tool`),[K,Ie]),Be=Z.useMemo(()=>{if(!F)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=lN(t.tool);!r||!cN.has(r)||e.add(n)}for(let t of a?.activityParts??[]){if(t.kind!==`tool`)continue;let n=lN(t.part.tool);!n||!cN.has(n)||e.add(t.id)}return e},[F,ze,a?.activityParts]),Ve=Z.useMemo(()=>{if(Be.size===0&&te.size===0)return ee;let e=new Set(ee);return Be.forEach(t=>{te.has(t)||e.add(t)}),te.forEach(t=>{e.delete(t)}),e},[te,Be,ee]),He=Z.useMemo(()=>{if(!K)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}`}},[K,le]),Ue=K&&!Ri(Le),We=typeof Pe!=`string`,Ge=Z.useMemo(()=>K?!1:Re.length===0||ze.length===0?We:!0,[Re.length,ze.length,We,K]),Ke=Z.useMemo(()=>!K&&NT.getInstance().shouldAnimateMessage(e.info,S||e.info.sessionID),[e.info,S,K]),[qe,Je]=Z.useState(!1),Ye=Z.useMemo(()=>n?JM(n.info):null,[n]),Xe=!!a,Ze=a?.isLastAssistantInTurn??!1,$e=$M({isWorking:a?.isWorking===!0,isInActiveTurn:c,headerCompletionDisposition:a?.completionDisposition}),et=Z.useMemo(()=>K?!1:Xe?!Ze:Ye?!Ye.isUser&&Ye.role===`assistant`:!1,[Xe,Ze,K,Ye]),tt=Z.useMemo(()=>Ne?`completed`:c?l??`streaming`:`completed`,[l,c,Ne]);Z.useEffect(()=>{!K||!u||d?.(e.info.id)},[u,K,e.info.id,d]),Z.useEffect(()=>{Je(!1)},[e.info.id]),Z.useEffect(()=>{let t=o??a?.headerMessageId;K||!t||t!==e.info.id||(tt===`streaming`||tt===`cooldown`)&&Je(!0)},[o,K,e.info.id,tt,a?.headerMessageId]);let nt=Z.useMemo(()=>{if(K)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,K,a,tt,e.info.id,s]),rt=Z.useCallback(e=>{en(e).then(t=>{t.ok&&(L(e),setTimeout(()=>L(null),2e3))})},[]),it=K?void 0:a?.userMessageVariant??ue?.variant,at=!K&&Se&&typeof it==`string`&&it.trim().length>0?it:void 0,ot=Z.useMemo(()=>{if(!K)return rN(e.info?.error,p(`chat.messageBody.aborted`))},[K,e.info,p]),st=ot?.text,ct=ot?.variant,lt=Z.useMemo(()=>{if(K){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(`
6577
6577
 
6578
6578
  `);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(`
6579
6579
  `):Le.filter(e=>e.type===`text`).map(e=>(e.text||e.content||``).trim()).filter(e=>e.length>0).join(`
@@ -6582,7 +6582,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{A as t,C as n,E as r,J
6582
6582
  `),[i]),s=Tu(o,a),c=0;return(0,$.jsx)(`div`,{className:`typography-code px-1 pb-1 pt-0 space-y-0`,style:r,children:i.map((e,n)=>(0,$.jsxs)(`div`,{className:`-mx-1 px-1 border-b border-border/20 last:border-b-0`,children:[(0,$.jsx)(`div`,{className:`bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1`,children:`${e.file||t?.split(`/`).pop()||`file`} (line ${e.oldStart})`}),(0,$.jsx)(`div`,{children:e.lines.map((e,t)=>{let n=s?.[c];return c+=1,(0,$.jsxs)(`div`,{className:Y(`typography-code font-mono px-2 py-0.5 flex -mx-2`,e.type===`context`&&`bg-transparent`,e.type===`removed`&&`bg-transparent`,e.type===`added`&&`bg-transparent`),style:e.type===`removed`?{backgroundColor:`var(--tools-edit-removed-bg)`}:e.type===`added`?{backgroundColor:`var(--tools-edit-added-bg)`}:{},children:[(0,$.jsx)(`span`,{className:`w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5`,style:{color:`var(--tools-edit-line-number)`,borderColor:`var(--tools-border)`},children:e.lineNumber||``}),(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsx)(yR,{content:e.content,html:n})})]},t)})})]},n))})},xR=e=>{let t=(0,Q.c)(21),{content:n,filePath:r}=e,{currentTheme:i}=Vs(),a;t[0]===i?a=t[1]:(a=tc(i),t[0]=i,t[1]=a);let o=a,s;t[2]===n?s=t[3]:(s=n.split(`
6583
6583
  `),t[2]=n,t[3]=s);let c=s,l;t[4]===r?l=t[5]:(l=Vl(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=Tu(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)(yR,{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},SR=new Set([`id`,`identifier`,`title`,`name`]),CR=e=>typeof e==`object`&&!!e&&!Array.isArray(e),wR=e=>e.replace(/([A-Z])/g,` $1`).replace(/[_-]/g,` `).replace(/^./,e=>e.toUpperCase()),TR=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},ER=e=>{try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}},DR=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?`${wR(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)(DR,{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(CR(n)){let e;t[18]===n?e=t[19]:(e=TR(n),t[18]=n,t[19]=e);let a=e,o;t[20]===n?o=t[21]:(o=Object.entries(n).filter(kR),t[20]=n,t[21]=o);let s=o,c;t[22]!==a||t[23]!==r?(c=r?`${wR(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)(DR,{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?wR(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`&&ER(n)?(0,$.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`truncate text-[var(--status-info)] underline underline-offset-2 hover:opacity-80`,title:n,children:n}):(0,$.jsx)(`span`,{className:Y(`min-w-0 break-words`,n===null?`text-[var(--surface-mutedForeground)]`:`text-[var(--surface-foreground)]`),children:a}),t[46]=a,t[47]=n,t[48]=o):o=t[48];let s=o,c;t[49]===r?c=t[50]:(c=r?(0,$.jsx)(`span`,{className:`truncate text-[var(--surface-mutedForeground)]`,title:r,children:wR(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});DR.displayName=`JsonSummaryValue`;var OR=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)(DR,{value:n,depth:0})}),t[0]=n,t[1]=r),r});OR.displayName=`JsonSummaryView`;function kR(e){let[t]=e;return!SR.has(t)}var AR={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`},jR={style:{whiteSpace:`pre-wrap`,wordBreak:`break-word`,overflowWrap:`break-word`}},MR=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})},NR=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},PR=e=>e===`filepath`||e===`file_path`?`filePath`:e===`parentDir`||e===`parent_dir`?`parentDirectory`:e,FR=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)(OR,{data:n})}),t[0]=n,t[1]=r),r},IR=({permission:e,onResponse:t})=>{let{t:n}=Zt(),[r,i]=Z.useState(!1),[a,o]=Z.useState(!1),s=hn,c=ua(),l=J(e=>e.currentSessionId),u=Z.useMemo(()=>{if(!l||e.sessionID===l)return!1;let t=c.find(t=>t.id===e.sessionID);return!!(t?.parentID&&t.parentID===l)},[e.sessionID,l,c]),d=async n=>{i(!0);try{await s(e.sessionID,e.id,n),o(!0),t?.(n)}catch(e){console.error(`[PermissionCard] Failed to respond to permission:`,e)}finally{i(!1)}};if(a)return null;let f=e.permission||`unknown`,p=f.toLowerCase(),m=(t,n=``)=>{let r=e.metadata[t];return typeof r==`string`?r:typeof r==`number`?String(r):n},h=t=>{let n=e.metadata[t];return typeof n==`number`?n:void 0},g=t=>!!e.metadata[t],_=NR(f),v=Object.fromEntries(Object.entries(e.metadata).filter(([e])=>e!==`always`).map(([e,t])=>[PR(e),t]));return(0,$.jsx)(`div`,{className:`group w-full pt-0 pb-2`,children:(0,$.jsx)(`div`,{className:`chat-column`,children:(0,$.jsxs)(`div`,{className:`-mt-1 overflow-hidden border border-border/30 rounded-xl bg-muted/10`,children:[(0,$.jsx)(`div`,{className:`px-2.5 py-2 sm:px-2 sm:py-1.5 border-b border-border/20 bg-muted/5`,children:(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center justify-between gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5 sm:gap-2`,children:[(0,$.jsx)(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`)}),u?(0,$.jsx)(`span`,{className:`hidden sm:inline typography-micro text-muted-foreground px-1.5 py-0.5 rounded bg-foreground/5`,children:n(`chat.questionCard.fromSubagent`)}):null]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 max-w-[48%] items-center gap-1.5`,children:[MR(f),(0,$.jsx)(`span`,{className:`truncate text-xs leading-4 sm:text-[length:var(--text-meta)] text-muted-foreground font-medium`,children:_})]})]})}),(0,$.jsxs)(`div`,{className:`px-2.5 py-2 sm:px-2 [&_.typography-meta]:!text-xs [&_.typography-micro]:!text-[0.6875rem]`,children:[e.patterns.length>0&&(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:n(`chat.permissionCard.patterns`)}),(0,$.jsx)(`div`,{className:`overflow-hidden rounded-lg border border-border/20 bg-muted/15`,children:e.patterns.map((e,t)=>(0,$.jsx)(`code`,{className:Y(`block break-all px-2 py-1.5 text-xs leading-4 sm:text-[length:var(--text-meta)]`,t>0&&`border-t border-border/15`),children:e},`${e}-${t}`))})]}),(()=>{if(p===`bash`||p===`shell`||p===`shell_command`){let e=m(`command`)||m(`cmd`)||m(`script`),t=m(`description`),r=m(`cwd`)||m(`working_directory`)||m(`directory`)||m(`path`),i=h(`timeout`);return(0,$.jsxs)($.Fragment,{children:[t&&(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-2`,children:t}),r&&(0,$.jsxs)(`div`,{className:`typography-meta text-muted-foreground mb-2`,children:[(0,$.jsx)(`span`,{className:`font-semibold`,children:n(`chat.permissionCard.workingDirectory`)}),` `,(0,$.jsx)(`code`,{className:`px-1 py-0.5 bg-muted/30 rounded`,children:r})]}),i&&(0,$.jsxs)(`div`,{className:`typography-meta text-muted-foreground mb-2`,children:[(0,$.jsx)(`span`,{className:`font-semibold`,children:n(`chat.permissionCard.timeout`)}),` `,i,`ms`]}),e&&(0,$.jsx)(`div`,{children:(0,$.jsx)(gu,{language:`bash`,code:e,style:AR,codeStyle:jR.style,wrap:!0})})]})}if(p===`edit`||p===`multiedit`||p===`str_replace`||p===`str_replace_based_edit_tool`){let e=m(`path`)||m(`file_path`)||m(`filename`)||m(`filePath`),t=m(`changes`)||m(`diff`),r=g(`replace_all`)||g(`replaceAll`);return(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-2`,children:(0,$.jsxs)(`span`,{className:`font-semibold`,children:[`⚠️ `,n(`chat.permissionCard.replaceAll`)]})}),t&&(0,$.jsx)(xl,{outerClassName:`max-h-[60vh]`,className:`tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent`,children:(0,$.jsx)(bR,{diff:t,filePath:e})})]})}if(p===`write`||p===`create`||p===`file_write`){let e=m(`path`)||m(`file_path`)||m(`filename`)||m(`filePath`),t=m(`content`)||m(`text`)||m(`data`);return t?(0,$.jsx)(xl,{outerClassName:`max-h-[60vh]`,className:`tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent`,children:(0,$.jsx)(xR,{content:t,filePath:e})}):null}if(p===`webfetch`||p===`fetch`||p===`curl`||p===`wget`){let t=m(`url`)||m(`uri`)||m(`endpoint`),r=m(`method`)||`GET`,i=e.metadata.headers&&typeof e.metadata.headers==`object`?e.metadata.headers:void 0,a=e.metadata.body??e.metadata.data??e.metadata.payload,o=h(`timeout`),s=m(`format`)||m(`responseType`);return(0,$.jsxs)($.Fragment,{children:[t&&(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-1`,children:n(`chat.permissionCard.request`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded`,children:r}),(0,$.jsx)(`code`,{className:`typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all`,children:t})]})]}),i&&Object.keys(i).length>0&&(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-1`,children:n(`chat.permissionCard.headers`)}),(0,$.jsx)(xl,{outerClassName:`max-h-32`,className:`p-0`,children:(0,$.jsx)(FR,{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)(xl,{outerClassName:`max-h-32`,className:`p-0`,children:typeof a==`object`&&a?(0,$.jsx)(FR,{data:a}):(0,$.jsx)(`pre`,{className:`typography-meta font-mono px-2 py-1.5 bg-muted/20 border border-border/20 rounded-lg whitespace-pre-wrap break-all`,children:String(a)})})]}),(o||s)&&(0,$.jsxs)(`div`,{className:`typography-micro text-muted-foreground`,children:[o&&(0,$.jsxs)(`span`,{children:[n(`chat.permissionCard.timeout`),` `,o,`ms`]}),o&&s&&(0,$.jsx)(`span`,{children:` • `}),s&&(0,$.jsxs)(`span`,{children:[n(`chat.permissionCard.responseFormat`),` `,s]})]})]})}return Object.keys(v).length===0?null:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:n(`chat.permissionCard.details`)}),(0,$.jsx)(xl,{outerClassName:`max-h-48`,className:`p-0`,children:(0,$.jsx)(FR,{data:v})})]})})()]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-3 gap-1 border-t border-border/20 px-1.5 py-1.5 sm:flex sm:items-center sm:flex-wrap sm:px-2 sm:py-1`,children:[(0,$.jsxs)(yo,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>d(`once`),disabled:r,className:`h-8 min-w-0 w-full gap-1 px-1 !text-xs leading-4 text-foreground sm:h-6 sm:w-auto sm:px-2`,children:[(0,$.jsx)(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)(yo,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>d(`always`),disabled:r,className:`h-8 min-w-0 w-full gap-1 px-1 !text-xs leading-4 text-foreground sm:h-6 sm:w-auto sm:px-2`,children:[(0,$.jsx)(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)(yo,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>d(`reject`),disabled:r,className:`h-8 min-w-0 w-full gap-1 px-1 !text-xs leading-4 text-[var(--status-error)] sm:h-6 sm:w-auto sm:px-2`,children:[(0,$.jsx)(X,{name:`close`,className:`size-3.5 shrink-0 sm:size-3`}),(0,$.jsx)(`span`,{className:`truncate`,children:n(`chat.permissionToast.actions.deny`)})]}),r&&(0,$.jsx)(`div`,{className:`col-span-3 flex justify-center w-full sm:w-auto sm:ml-auto py-1 sm:py-0 typography-meta text-muted-foreground`,children:(0,$.jsx)(`div`,{className:`animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full`})})]})]})})})};function LR(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(`
6584
6584
  `).trimEnd()}function RR(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 zR=200;function BR(e){return Math.min(Math.max(e,40),zR)}var VR=`summary`,HR=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=BR(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=Y(`w-full bg-transparent border border-border/30 focus:border-primary rounded px-2 py-1 outline-none typography-meta text-foreground placeholder:text-muted-foreground/50 transition-colors resize-none`,E),t[16]=E,t[17]=D);let O;return t[18]!==i||t[19]!==_||t[20]!==c||t[21]!==o||t[22]!==r||t[23]!==T||t[24]!==D||t[25]!==w?(O=(0,$.jsx)(`textarea`,{ref:s,value:c,onChange:w,placeholder:r,disabled:i,rows:2,onKeyDown:o,onFocus:_,style:T,className:D,autoFocus:!0}),t[18]=i,t[19]=_,t[20]=c,t[21]=o,t[22]=r,t[23]=T,t[24]=D,t[25]=w,t[26]=O):O=t[26],O}),UR=({question:e})=>{let{t}=Zt(),n=qr,r=jr,i=g(e=>e.isMobile),a=ua(),o=J(e=>e.currentSessionId),s=Z.useMemo(()=>{if(!o||e.sessionID===o)return!1;let t=a.find(t=>t.id===e.sessionID);return!!(t?.parentID&&t.parentID===o)},[e.sessionID,o,a]),[c,l]=Z.useState(`0`),[u,d]=Z.useState(!1),[f,p]=Z.useState(!1),[m,h]=Z.useState({}),[_,v]=Z.useState({}),y=Z.useRef({}),[b,x]=Z.useState({}),S=Z.useMemo(()=>e.questions??[],[e.questions]),C=c===VR,w=C?-1:Math.max(0,Math.min(S.length-1,Number(c)||0)),T=C?null:S[w],E=Z.useMemo(()=>{if(C)return null;let e=T?.header?.trim();return e&&e.length>0?e:null},[T?.header,C]);Z.useEffect(()=>{l(`0`),h({}),v({}),y.current={},x({}),p(!1)},[e.id]);let D=Z.useMemo(()=>{let e=S.map((e,t)=>({value:String(t),label:e.header?.trim()||`Q${t+1}`}));return S.length>1&&e.push({value:VR,label:t(`chat.questionCard.summaryTab`)}),e},[S,t]),O=Z.useCallback(e=>{if(_[e])return(y.current[e]??``).trim()||t(`chat.questionCard.noAnswer`);let n=m[e]??[];return n.length>0?n.join(`, `):t(`chat.questionCard.noAnswer`)},[_,m,t]),k=!!T?.multiple,A=m[w]??[],j=!!_[w],M=Z.useMemo(()=>{let e=[];for(let t=0;t<S.length;t+=1){if(_[t]){b[t]||e.push(t);continue}(m[t]??[]).length===0&&e.push(t)}return e},[_,b,S.length,m]),N=Z.useMemo(()=>S.length!==0&&M.length===0,[S.length,M.length]),P=Z.useCallback(()=>{if(S.length===0||M.length===0)return;let e=C?-1:w;for(let t=1;t<=S.length;t+=1){let n=(e+t+S.length)%S.length;if(M.includes(n)){l(String(n));return}}l(String(M[0]))},[w,C,S.length,M]),F=Z.useCallback(()=>{let e=[];for(let t=0;t<S.length;t+=1){if(_[t]){let n=(y.current[t]??``).trim();e.push(n?[n]:[]);continue}e.push(m[t]??[])}return e},[_,S.length,m]),I=Z.useCallback(e=>{T&&(v(e=>({...e,[w]:!1})),x(e=>e[w]?{...e,[w]:!1}:e),h(t=>{let n=t[w]??[];if(k){let r=n.includes(e)?n.filter(t=>t!==e):[...n,e];return{...t,[w]:r}}return{...t,[w]:[e]}}))},[w,T,k]),L=Z.useCallback(()=>{v(e=>({...e,[w]:!0})),h(e=>({...e,[w]:[]}));let e=(y.current[w]??``).trim().length>0;x(t=>t[w]===e?t:{...t,[w]:e})},[w]),R=Z.useCallback(e=>{y.current[w]=e;let t=e.trim().length>0;x(e=>e[w]===t?e:{...e,[w]:t})},[w]),z=Z.useCallback(async()=>{if(N){d(!0);try{let t=F();await n(e.sessionID,e.id,t),p(!0)}catch(e){or(e)?(fa.info(t(`chat.questionCard.noLongerPending`)),p(!0)):fa.error(t(`chat.questionCard.submitFailed`),{description:t(`chat.questionCard.tryAgain`)})}finally{d(!1)}}},[F,e.id,e.sessionID,N,n,t]),B=Z.useCallback(e=>{ju(e)||e.key===`Enter`&&!e.shiftKey&&(!i||e.ctrlKey||e.metaKey)&&(e.preventDefault(),N?z():P())},[z,P,i,N]),V=Z.useCallback(async()=>{d(!0);try{await r(e.sessionID,e.id),p(!0)}catch(e){or(e)?(fa.info(t(`chat.questionCard.noLongerPending`)),p(!0)):fa.error(t(`chat.questionCard.dismissFailed`),{description:t(`chat.questionCard.tryAgain`)})}finally{d(!1)}},[e.id,e.sessionID,r,t]),H=Z.useCallback(async()=>{let n=LR(e);if((await en(n)).ok){fa.success(t(`chat.questionCard.copiedMarkdown`));return}fa.error(t(`chat.questionCard.copyFailed`))},[e,t]),ee=Z.useCallback(async()=>{let n=RR(e);if((await en(n)).ok){fa.success(t(`chat.questionCard.copiedJson`));return}fa.error(t(`chat.questionCard.copyFailed`))},[e,t]);return f||S.length===0?null:(0,$.jsx)(`div`,{className:`group w-full pt-0 pb-2`,children:(0,$.jsx)(`div`,{className:`chat-column`,children:(0,$.jsxs)(`div`,{"data-question-card":!0,className:`-mt-1 border border-border/30 rounded-xl bg-muted/10`,children:[(0,$.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border/20`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`question`,className:`h-3.5 w-3.5 text-primary`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-muted-foreground`,children:t(`chat.questionCard.inputNeeded`)}),s?(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,E?(0,$.jsx)(`span`,{className:`ml-auto typography-micro font-medium text-foreground/70 px-1.5 py-0.5 rounded bg-muted/30 border border-border/20`,children:E}):null,(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-0.5`,E?null:`ml-auto`),children:[(0,$.jsx)(`button`,{type:`button`,onClick:H,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:ee,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`})})]})]})}),(0,$.jsxs)(`div`,{className:`px-2 py-2`,children:[D.length>1?(0,$.jsx)(`div`,{className:`flex items-center gap-1 mb-2 flex-wrap`,children:D.map(e=>{let t=c===e.value,n=e.value===VR,r=n?-1:Number(e.value),i=!n&&Number.isFinite(r)&&!M.includes(r);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>l(e.value),className:Y(`px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1`,t?`bg-interactive-selection/40 text-foreground`:n?`text-muted-foreground hover:text-foreground hover:bg-interactive-hover/20`:i?`text-muted-foreground/60 hover:text-muted-foreground hover:bg-interactive-hover/20`:`text-foreground/85 hover:text-foreground hover:bg-interactive-hover/20`),children:[n?(0,$.jsx)(X,{name:`list-check-3`,className:`h-3 w-3`}):null,e.label]},e.value)})}):null,C?(0,$.jsx)(`div`,{className:`space-y-2`,children:S.map((e,n)=>{let r=O(n),i=r!==t(`chat.questionCard.noAnswer`);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>l(String(n)),className:`w-full text-left rounded px-1.5 py-1 hover:bg-interactive-hover/20 transition-colors`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:e.header||t(`chat.questionCard.questionFallback`,{index:n+1})}),(0,$.jsx)(`div`,{className:Y(`typography-meta`,i?`text-foreground`:`text-muted-foreground/50 italic`),children:r})]},n)})}):T?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-foreground mb-1.5`,children:T.question}),k?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1.5`,children:t(`chat.questionCard.selectMultiple`)}):null,(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[T.options.map((e,n)=>{let r=A.includes(e.label),i=/\(recommended\)/i.test(e.label);return(0,$.jsx)(`button`,{type:`button`,onClick:()=>I(e.label),disabled:u,className:Y(`w-full px-1.5 py-1 text-left rounded transition-colors`,`hover:bg-interactive-hover/30`,r?`bg-interactive-selection/20`:null,u?`opacity-60 cursor-not-allowed`:null),children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:k?(0,$.jsx)(jo,{checked:r,onChange:()=>I(e.label),disabled:u}):(0,$.jsx)(Os,{checked:r,onChange:()=>I(e.label),disabled:u})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:Y(`typography-meta break-all`,r?`text-foreground font-medium`:`text-foreground/80`),children:e.label}),i?(0,$.jsx)(`span`,{className:`typography-micro text-primary/80`,children:t(`chat.questionCard.recommended`)}):null]}),e.description?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground break-words`,children:e.description}):null]})]})},`${n}:${e.label}`)}),(0,$.jsx)(`button`,{type:`button`,onClick:L,disabled:u,className:Y(`w-full px-1.5 py-1 text-left rounded transition-colors`,`hover:bg-interactive-hover/30`,j?`bg-interactive-selection/20`:null,u?`opacity-60 cursor-not-allowed`:null),children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`edit`,className:Y(`h-3.5 w-3.5`,j?`text-primary`:`text-muted-foreground/50`)}),(0,$.jsx)(`span`,{className:Y(`typography-meta`,j?`text-foreground font-medium`:`text-muted-foreground`),children:t(`chat.questionCard.other`)})]})}),j?(0,$.jsx)(`div`,{className:`pl-6 pr-1 pt-0.5`,children:(0,$.jsx)(HR,{value:y.current[w]??``,onValueChange:R,placeholder:t(`chat.questionCard.yourAnswer`),disabled:u,onKeyDown:B})}):null]})]}):null]}),(0,$.jsxs)(`div`,{className:`px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:N?z:P,disabled:u,className:Y(`flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors`,`bg-[rgb(var(--status-success)/0.1)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]`,`disabled:opacity-50 disabled:cursor-not-allowed`),children:[N?(0,$.jsx)(X,{name:`check`,className:`h-3 w-3`}):(0,$.jsx)(X,{name:`arrow-right-s`,className:`h-3 w-3`}),t(N?`chat.questionCard.submit`:`chat.questionCard.next`)]}),(0,$.jsxs)(`button`,{type:`button`,onClick:V,disabled:u,className:Y(`flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors`,`bg-[rgb(var(--status-error)/0.1)] text-[var(--status-error)] hover:bg-[rgb(var(--status-error)/0.2)]`,`disabled:opacity-50 disabled:cursor-not-allowed`),children:[(0,$.jsx)(X,{name:`close`,className:`h-3 w-3`}),t(`chat.questionCard.dismiss`)]}),u?(0,$.jsx)(`div`,{className:`ml-auto`,children:(0,$.jsx)(`div`,{className:`animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full`})}):null]})]})})})};function WR(e){return e.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
6585
- `)}function GR(e,t=80){let n=WR(e).replace(/\n/g,` `);return n.length>t?`${n.slice(0,t)}…`:n}var KR=160,qR=28,JR=12,YR=6,XR=30,ZR=12,QR=18,$R=80,ez=4,tz=10,nz=14,rz=20,iz=54,az=4,oz=8,sz=2,cz=160,lz=(e,t)=>e.map(e=>({turnId:e,preview:GR(t.get(e)??[],KR)})),uz=[1,.6,.35,.15],dz=(e,t,n)=>{let r=n?nz:tz;if(t===null)return r;let i=uz[Math.abs(e-t)]??0;return Math.round(r+(rz-r)*i)};function fz({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:i,isLoadingOlder:a,onLoadEarlier:o}){let{t:s}=Zt(),c=g(e=>e.isPromptNavigatorPanelOpen),l=g(e=>e.setPromptNavigatorPanelOpen),u=Z.useRef(null),d=Z.useRef(null),[f,p]=Z.useState(null),[m,h]=Z.useState(0),[_,v]=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){v(!1);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=n.right-YR-qR;v(r.right>i)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let y=Z.useMemo(()=>lz(e,t),[t,e]),b=Math.min(y.length,XR),x=Math.max(0,y.length-b),S=Math.min(m,x),C=S+b,w=S>0,T=C<y.length,E=s(`chat.timeline.noTextContent`),D=s(`chat.promptNavigator.currentPrompt`),O=s(`chat.promptNavigator.loadMore`),k=Z.useMemo(()=>n?y.findIndex(e=>e.turnId===n):-1,[n,y]),A=Z.useRef(S);A.current=S;let j=Z.useRef(y.length);j.current=y.length;let M=Z.useRef(null),N=Z.useRef(null),P=Z.useRef(0),F=Z.useCallback(e=>{h(t=>{let n=j.current,r=Math.min(n,XR),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})},[]),I=Z.useRef(y[0]?.turnId),L=Z.useRef(y.length);Z.useLayoutEffect(()=>{let e=I.current,t=L.current,n=y.length-t;n>0&&t>0&&e&&y[0]?.turnId!==e&&(h(e=>e+n),p(e=>e===null?null:e+n)),I.current=y[0]?.turnId,L.current=y.length},[y]),Z.useEffect(()=>{if(f!==null)return;let e=k>=0?k:y.length-1;h(()=>{let t=j.current,n=Math.min(t,XR),r=Math.max(0,t-n);return Math.max(0,Math.min(r,e-Math.floor(n/2)))})},[k,f,y.length]);let R=Z.useCallback(e=>{let t=u.current;if(!t)return null;let n=t.getBoundingClientRect(),r=Math.floor((e-n.top)/ZR),i=Math.min(j.current,XR);return i===0?null:Math.max(0,Math.min(i-1,r))},[]),z=Z.useCallback(()=>{P.current=0,N.current!==null&&(window.clearInterval(N.current),N.current=null)},[]),B=Z.useCallback(()=>{let e=P.current;if(e===0){z();return}let t=j.current,n=Math.max(0,t-Math.min(t,XR)),r=Math.min(A.current,n),i=Math.max(0,Math.min(n,r+e));if(i===r){z();return}A.current=i,h(i);let a=M.current;if(a!==null){let e=R(a);e!==null&&p(Math.min(t-1,i+e))}},[R,z]),V=Z.useCallback(e=>{let t=u.current;if(!t)return;let n=t.getBoundingClientRect(),r=e-n.top,i=0;if(r<=QR&&w?i=-1:r>=n.height-QR&&T&&(i=1),P.current=i,i===0){z();return}N.current===null&&(N.current=window.setInterval(B,$R))},[B,w,T,z]);Z.useEffect(()=>()=>{N.current!==null&&window.clearInterval(N.current)},[]);let H=Z.useRef(null),ee=Z.useCallback(()=>{H.current!==null&&(window.clearTimeout(H.current),H.current=null)},[]),U=Z.useCallback(()=>{ee(),H.current=window.setTimeout(()=>{H.current=null,p(null)},cz)},[ee]);Z.useEffect(()=>()=>{H.current!==null&&window.clearTimeout(H.current)},[]);let te=Z.useCallback(e=>{ee(),M.current=e.clientY;let t=R(e.clientY);t!==null&&p(Math.min(j.current-1,A.current+t)),V(e.clientY)},[ee,R,V]),W=Z.useCallback(()=>{M.current=null,z(),U()},[U,z]),ne=Z.useCallback(()=>{l(!1)},[l]),G=Z.useCallback(e=>{if(e===null)return;let t=y[e];t&&(r(t.turnId),z(),p(null),ne(),u.current?.blur())},[ne,r,y,z]),K=Z.useCallback(e=>{let t=R(e.clientY);t!==null&&G(Math.min(y.length-1,A.current+t))},[G,y.length,R]);Z.useEffect(()=>{if(!c)return;let e=u.current;!e||e===document.activeElement||(e.focus(),p(e=>{if(e!==null)return e;let t=k>=0?k:y.length-1;return F(t),t}))},[k,F,c,y.length]),Z.useEffect(()=>()=>{l(!1)},[l]);let re=Z.useCallback(e=>{if(y.length===0)return;let t=f??(k>=0?k:y.length-1),n=e=>{let t=Math.max(0,Math.min(y.length-1,e));F(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(y.length-1);return}if(e.key===`Enter`||e.key===` `){e.preventDefault(),G(t);return}e.key===`Escape`&&(e.preventDefault(),p(null),ne(),u.current?.blur())},[k,ne,F,G,f,y.length]),ie=Z.useCallback(()=>{z(),p(null),ne()},[ne,z]),ae=Z.useRef(null),oe=Z.useRef(f);oe.current=f;let se=f!==null,ce=Z.useRef(0);Z.useEffect(()=>{let e=ae.current;if(!e)return;let t=e=>{e.preventDefault(),e.stopPropagation(),ce.current+=e.deltaY;let t=Math.trunc(ce.current/iz);if(t===0)return;ce.current-=t*iz;let n=oe.current;if(n===null)return;let r=Math.max(0,Math.min(j.current-1,n+t));r!==n&&(F(r),p(r))};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[F,se]);let le=f===null?void 0:y[f],ue=Math.min(y.length,oz),de=ue*iz,fe=y.length*iz-de,pe=e=>Math.max(0,Math.min(fe,e)),me=Z.useRef(null),he=0;if(f===null)me.current=null;else if(me.current===null)he=pe(f*iz-(de-iz)/2),me.current=he;else{let e=me.current,t=(f-sz)*iz,n=(f+1+sz)*iz-de;e>t?e=t:e<n&&(e=n),he=pe(e),me.current=he}let ge=Math.floor(he/iz),_e=Math.max(0,ge-ez),ve=Math.min(y.length,ge+ue+ez),ye=he>0,be=he<fe,xe=ye||be?`linear-gradient(to bottom, ${ye?`transparent, black 10%`:`black`}, ${be?`black 90%, transparent`:`black`})`:void 0,Se=Math.max(0,S-ez),Ce=Math.min(y.length,C+ez),we=y.slice(Se,Ce),Te=w||T?`linear-gradient(to bottom, ${w?`transparent, black 14%`:`black`}, ${T?`black 86%, transparent`:`black`})`:void 0;return y.length===0?null:(0,$.jsx)(`nav`,{ref:d,"aria-label":s(`chat.promptNavigator.aria`),className:`pointer-events-none absolute right-1.5 top-1/2 z-20 -translate-y-1/2`,children:(0,$.jsxs)(`div`,{className:`pointer-events-auto flex flex-col items-end`,children:[i?(0,$.jsx)(`button`,{type:`button`,tabIndex:-1,className:Y(`-mr-px mb-1.5 flex size-5 shrink-0 items-center justify-center rounded-full`,`text-[var(--surface-mutedForeground)] transition-colors`,`hover:bg-[var(--interactive-hover)]/60 hover:text-[var(--surface-foreground)]`,a?`cursor-wait opacity-70`:void 0),"aria-label":O,title:O,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":le?`prompt-rail-tick-${le.turnId}`:void 0,className:`relative cursor-pointer outline-none`,style:{width:`${_?JR:qR}px`,height:`${b*ZR}px`},onMouseMove:te,onMouseLeave:W,onClick:K,onKeyDown:re,onBlur:ie,children:[(0,$.jsx)(`div`,{className:`absolute inset-0 overflow-hidden`,style:Te?{maskImage:Te,WebkitMaskImage:Te}:void 0,children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-300 ease-out`,style:{transform:`translateY(-${S*ZR}px)`},children:we.map((e,t)=>{let r=Se+t,i=e.turnId===n,a=f===r,o=dz(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()||E,className:`pointer-events-none absolute right-1 flex items-center justify-end`,style:{top:`${r*ZR}px`,height:`${ZR}px`},children:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:Y(`block h-0.5 rounded-full transition-all duration-200 ease-out`,i?`bg-[var(--surface-foreground)]`:a?`bg-[var(--surface-foreground)]/80`:`bg-[var(--surface-foreground)]/30`),style:{width:`${o}px`}})},e.turnId)})},y[0]?.turnId)}),le&&f!==null?(0,$.jsx)(`div`,{ref:ae,className:Y(`pointer-events-auto absolute right-full top-1/2 z-30 mr-3 -translate-y-1/2`,`w-[min(20rem,calc(100vw-6rem))] overflow-hidden rounded-xl`,`border border-[var(--interactive-border)]/60 bg-[var(--surface-elevated)] py-1 shadow-md`),onMouseEnter:ee,onMouseLeave:U,onMouseMove:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:(0,$.jsx)(`div`,{className:`relative overflow-hidden`,style:{height:`${ue*iz}px`,maskImage:xe,WebkitMaskImage:xe},children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-200 ease-out`,style:{height:`${y.length*iz}px`,transform:`translateY(-${he}px)`},children:y.slice(_e,ve).map((e,t)=>{let r=_e+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?D:void 0,className:`absolute inset-x-0 cursor-pointer px-1.5`,style:{top:`${r*iz+az}px`,height:`46px`},onMouseMove:()=>{ee(),oe.current!==r&&(F(r),p(r))},onClick:()=>G(r),children:(0,$.jsx)(`div`,{className:Y(`flex h-full items-center rounded-lg border px-2 transition-colors`,i?`border-transparent bg-[var(--interactive-selection)]`:a?`border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]`:`border-[var(--interactive-border)]/40`),children:(0,$.jsx)(`span`,{className:Y(`min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] typography-meta`,i?`text-[var(--interactive-selectionForeground)]`:`text-[var(--surface-mutedForeground)]`),children:e.preview.trim()||E})})},e.turnId)})})})}):null]})]})})}var pz=100,mz=(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},hz=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=mz(p,t.scrollTop+pz);!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}},gz=10,_z=`${gz}vh`,vz=`80px`,yz=`calc(${vz} + var(--oc-chat-foot-inset))`,bz=(e,t)=>e?80:t<=0?96:Math.max(48,gz/100*t),xz=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return!1;switch(e.key){case`ArrowUp`:case`PageUp`:case`Home`:return!0;default:return!1}},Sz=(e,t)=>{let n=t instanceof Element?t:t instanceof Node?t.parentElement:null;for(;n&&n!==e;){if(n instanceof HTMLElement&&n.scrollTop>0&&n.scrollHeight>n.clientHeight+1)return!0;n=n.parentElement}return!1},Cz=e=>{let t=(0,Q.c)(15),{scrollRef:n,enabled:r,onUpwardIntent:i}=e,a=r===void 0||r,o=Z.useRef(null),s;t[0]===i?s=t[1]:(s=()=>{i()},t[0]=i,t[1]=s);let c=q(s),l;t[2]!==c||t[3]!==n?(l=e=>{let t=n.current;t&&(e.deltaY>=0||t instanceof HTMLElement&&(Sz(t,e.target)||c()))},t[2]=c,t[3]=n,t[4]=l):l=t[4];let u=q(l),d;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(d=e=>{let t=e.touches.item(0);o.current=t?t.clientY:null},t[5]=d):d=t[5];let f=q(d),p;t[6]!==c||t[7]!==n?(p=e=>{let t=n.current,r=e.touches.item(0);if(!r){o.current=null;return}let i=o.current;o.current=r.clientY,i!==null&&(r.clientY-i<=2||!t||!(t instanceof HTMLElement)||Sz(t,e.target)||c())},t[6]=c,t[7]=n,t[8]=p):p=t[8];let m=q(p),h;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(h=()=>{o.current=null},t[9]=h):h=t[9];let g=q(h),_;t[10]===c?_=t[11]:(_=e=>{xz(e)&&c()},t[10]=c,t[11]=_);let v=q(_),[y,b]=Z.useState(null),x;t[12]===n?x=t[13]:(x=()=>{let e=n.current??null;b(t=>t===e?t:e)},t[12]=n,t[13]=x),Z.useEffect(x);let S=a&&y?y:wz,C;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(C={passive:!0},t[14]=C):C=t[14];let w=C;Jt(`wheel`,u,S,w),Jt(`touchstart`,f,S,w),Jt(`touchmove`,m,S,w),Jt(`touchend`,g,S,w),Jt(`touchcancel`,g,S,w),Jt(`keydown`,v,S)};function wz(){}var Tz=(e,t)=>({sessionId:e,viewportKey:t}),Ez=(e,t)=>e?.sessionId===t?.sessionId&&e?.viewportKey===t?.viewportKey,Dz=(e,t)=>Ez(e,t),Oz=(e,t,n)=>({identity:e,anchor:t,scrollPosition:n}),kz=150,Az=1500,jz=2,Mz=350,Nz=600,Pz=8e3,Fz=24,Iz=2,Lz=(e,t)=>e<t,Rz=()=>typeof performance<`u`?performance.now():Date.now(),zz=e=>({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}),Bz=e=>e.scrollHeight-e.scrollTop-e.clientHeight,Vz=e=>Bz(zz(e)),Hz=e=>e.scrollHeight-e.clientHeight>1,Uz=(e,t)=>Bz(e)<=bz(t,e.clientHeight),Wz=({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(Tz(t,n));C.current=Tz(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=Rz()+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=Xa(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:Rz()},E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{T.current=null,E.current=null},Az)}),G=q(e=>{let t=T.current;return t?Rz()-t.time>Az?(T.current=null,!1):Math.abs(e.scrollTop-t.top)<jz:!1}),K=q(()=>Rz()<A.current),re=q(()=>{L.current=!1,R.current&&=(clearTimeout(R.current),null),z.current&&=(clearTimeout(z.current),null)}),ie=q(()=>{R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{R.current=null,re()},Nz)}),ae=q(()=>{let e=c.current;e&&(L.current=!0,B.current=e.scrollHeight,ie(),z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{z.current=null,re()},Pz))}),oe=q(e=>{let t=c.current;if(!t){h(!1),_(!1);return}let n=e??zz(t),r=Hz(n);if(h(r),!r){_(!1);return}let i=b.current===`released`&&!Uz(n,x.current);_(i)}),se=q(()=>{D.current+=1,O.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(O.current),O.current=null),k.current?.(),k.current=null});Z.useEffect(()=>()=>se(),[l]);let ce=q(()=>{if(!e)return;let t=c.current;if(!t)return;se();let n=D.current,r=t.style.overflow,i=t.style.scrollBehavior;t.style.scrollBehavior=`auto`,t.style.overflow=`hidden`,t.scrollTop=t.scrollHeight,t.scrollHeight,t.style.overflow=r,t.style.scrollBehavior=i;let a=()=>{ne(t),t.scrollTop=t.scrollHeight,I.current=t.scrollTop};if(a(),oe(),typeof window>`u`)return;let o=0,s=()=>{Lz(Rz(),P.current)||se()};t.addEventListener(`touchstart`,s,{passive:!0,once:!0}),k.current=()=>t.removeEventListener(`touchstart`,s);let l=()=>{if(n===D.current){if(Vz(t)>Iz&&a(),o+=1,o>=Fz){O.current=null,k.current?.(),k.current=null,oe();return}O.current=window.requestAnimationFrame(l)}};O.current=window.requestAnimationFrame(l)}),le=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}}),ue=q((t,n=`auto`)=>{if(!e)return;let r=c.current;if(t&&b.current!==`following`&&W(`following`),r&&!(!t&&b.current!==`following`)){if(Vz(r)<jz){ne(r);return}le(t?n:`auto`)}}),de=q(e=>{let t=c.current;if(!t)return;let n=e??zz(t);if(!Hz(n)){W(`following`);return}b.current!==`released`&&(W(`released`),oe(n))}),fe=q((e=`instant`)=>{if(V.current=!1,W(`following`),re(),e===`instant`){ce();return}se(),ue(!0,`smooth`),oe()}),pe=q(()=>{V.current=!1,ue(!0)}),me=q(()=>{se(),re(),W(`released`),oe()}),he=q(()=>{V.current=!0,me()}),ge=q(()=>{V.current=!1}),_e=Z.useRef(s);_e.current=s;let ve=q(()=>{Lz(Rz(),P.current)||(se(),re(),de())}),ye=q(()=>{ve(),_e.current?.()}),be=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}}),xe=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=Oz(e,o,{scrollTop:n,scrollHeight:r,clientHeight:i}),H.current===null&&(H.current=setTimeout(()=>{H.current=null,be()},kz))}),Se=q(()=>{be()}),Ce=q(async(e=C.current)=>{if(!e.sessionId)return!1;V.current=!1;let t=vi(e.sessionId,e.viewportKey);return c.current?(U.current=null,I.current=t?.scrollPosition?.scrollTop??0,W(`following`),F(),x.current?ce():ue(!0),ae(),oe(),!1):(U.current=e,W(`following`),!1)});Z.useEffect(()=>{let e=C.current,n=w.current;Ez(e,n)||(be(),se(),F(),w.current=e,T.current=null,I.current=0,re(),V.current=!1,W(`following`),U.current=null,t&&t!==n?.sessionId&&NT.getInstance().recordSessionStart(t))},[t,n]),Z.useEffect(()=>{i&&!V.current&&b.current===`following`&&ue(!0)},[i]),Z.useEffect(()=>{y(f===`following`&&i)},[f,i]),Z.useLayoutEffect(()=>{if(!l)return;let e=U.current;e&&Dz(e,C.current)&&Ce(e)},[l,t,n]);let we=q(()=>{let e=c.current;if(!e)return;let t=zz(e),n=I.current;I.current=t.scrollTop;let r=t.scrollTop>n+.5,i=Math.abs(t.scrollTop-n)<.5;if(oe(t),V.current){xe();return}if(!Hz(t)){W(`following`);return}if(Uz(t,x.current)){let e=Bz(t)<=jz;(r||b.current===`following`||e)&&W(`following`),xe();return}if(b.current===`following`&&(G(e)||K()||i)){j.current||ue(!1),xe();return}de(t),xe()});Z.useEffect(()=>{!e||!l||(I.current=l.scrollTop)},[l,e]);let Te=Z.useRef(null),Ee=q(e=>{let t=c.current;t&&(e.deltaY>=0||Sz(t,e.target)||ye())}),De=q(e=>{let t=e.touches.item(0);Te.current=t?t.clientY:null}),Oe=q(e=>{let t=c.current,n=e.touches.item(0);if(!n){Te.current=null;return}let r=Te.current;Te.current=n.clientY,r!==null&&(n.clientY-r<=2||t&&(Sz(t,e.target)||ye()))}),ke=q(()=>{Te.current=null}),Ae=q(e=>{xz(e)&&ye()}),je=q(e=>{let t=e.target;t instanceof Element&&t.closest(`[data-overlay-scrollbar-thumb]`)&&ve()}),Me=Z.useMemo(()=>()=>void 0,[]),Ne=e&&l?l:Me,Pe=Z.useMemo(()=>({passive:!0}),[]);Jt(`scroll`,we,Ne,Pe),Jt(`wheel`,Ee,Ne,Pe),Jt(`touchstart`,De,Ne,Pe),Jt(`touchmove`,Oe,Ne,Pe),Jt(`touchend`,ke,Ne,Pe),Jt(`touchcancel`,ke,Ne,Pe),Jt(`keydown`,Ae,Ne),Jt(`pointerdown`,je,e&&typeof window<`u`?window:Me,!0);let Fe=q(()=>{let e=c.current;if(j.current){oe(e?zz(e):void 0);return}if(V.current){oe(e?zz(e):void 0);return}if(!e){oe(void 0);return}let t=zz(e);if(!Hz(t)){W(`following`),oe(t);return}if(oe(t),L.current){let n=t.scrollHeight>B.current+1;B.current=t.scrollHeight,Bz(t)<=jz?ne(e):ue(!0),n&&ie();return}if(b.current===`following`){if(Bz(t)<=jz){ne(e);return}ue(!1)}}),Ie=typeof ResizeObserver<`u`,Le=Ie&&e?l:null,Re=Ie&&e&&l&&l.firstElementChild instanceof Element?l.firstElementChild:null;Yt(Le,Fe),Yt(Re,Fe);let ze=q(()=>{N.current!==null&&(clearTimeout(N.current),N.current=null)}),Be=q(e=>{j.current=!0,typeof e==`number`&&e>0?A.current=Rz()+e+Mz:A.current=Math.max(A.current,Rz()+Mz)}),Ve=q(e=>{let t=e.detail;if(t){if(t.open===!0){Be(),ze(),N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},1500);return}ze(),Be()}}),He=q(e=>{let t=e.detail;t&&(ze(),Be(t.durationMs))}),Ue=q(e=>{let t=e.detail;ze(),t?.open===!0?(M.current=!0,j.current=!0):(M.current=!1,j.current=!0,N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},Mz)),oe()}),We=e&&typeof window<`u`?window:Me;Jt(`oc:keyboard-intent`,Ve,We),Jt(`oc:keyboard-anim`,He,We),Jt(`oc:keyboard-settled`,Ue,We),Z.useEffect(()=>{if(!(!e||typeof window>`u`))return()=>{ze(),j.current=!1,M.current=!1}},[e]),Z.useEffect(()=>{e&&oe()},[e,r]);let Ge=q(t=>{if(e){if(t===`animation`&&(A.current=Rz()+Mz),oe(),L.current){ue(!0),ie();return}b.current===`following`&&ue(!1)}}),Ke=Z.useRef(new Map),qe=q(t=>{let n=Ke.current.get(t);if(n)return n;let r=()=>{e&&b.current===`following`&&ue(!1)},i={onChunk:r,onComplete:()=>{e&&oe()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:r,onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return Ke.current.set(t,i),i});Z.useEffect(()=>()=>{E.current&&=(clearTimeout(E.current),null),se(),re(),be(),H.current!==null&&(clearTimeout(H.current),H.current=null)},[]);let Je=q(e=>{o?.(e)}),Ye=!!o;return Z.useEffect(()=>{if(!e||!Ye)return;let t=l;if(!t)return;let n=null,r=hz({onActive:e=>{e!==n&&(n=e,Je(e))}});r.setContainer(t);let i=new Map,a=e=>{let t=e.dataset.turnId;return t?(i.set(t,e),r.register(e,t),!0):!1},o=e=>{let t=e.dataset.turnId;return!t||i.get(t)!==e?!1:(i.delete(t),r.unregister(t),!0)},s=e=>{if(!(e instanceof HTMLElement))return[];let t=[];return e.matches(`[data-turn-id]`)&&t.push(e),e.querySelectorAll(`[data-turn-id]`).forEach(e=>t.push(e)),t};t.querySelectorAll(`[data-turn-id]`).forEach(a),r.markDirty();let c=new MutationObserver(e=>{let t=!1;e.forEach(e=>{e.removedNodes.forEach(e=>{s(e).forEach(e=>{o(e)&&(t=!0)})}),e.addedNodes.forEach(e=>{s(e).forEach(e=>{a(e)&&(t=!0)})})}),t&&r.markDirty()});c.observe(t,{subtree:!0,childList:!0});let u=()=>r.onScroll();return t.addEventListener(`scroll`,u,{passive:!0}),()=>{t.removeEventListener(`scroll`,u),c.disconnect(),r.destroy()}},[l,e,Ye]),{scrollRef:c,state:f,isPinned:f===`following`,isOverflowing:m,isFollowingProgrammatically:v,showScrollButton:g,notifyContentChange:Ge,getAnimationHandlers:qe,goToBottom:fe,scrollToBottomOnSend:pe,releaseAutoFollow:me,beginHistoryViewportPreservation:he,endHistoryViewportPreservation:ge,saveSnapshotNow:Se,restoreSnapshot:Ce}},Gz=`--oc-mobile-composer-swap`,Kz=`--oc-native-composer-dock`,qz=()=>({phase:`rest`,rest:`expanded`,progress:0,pinned:!1}),Jz=(e,t,n)=>Math.min(n,Math.max(t,e)),Yz=(e,t)=>e.phase===t.phase&&e.rest===t.rest&&e.progress===t.progress&&e.pinned===t.pinned,Xz=(e,t)=>{let n={phase:t.phase,rest:t.rest,progress:t.progress,pinned:t.pinned??e.pinned};return Yz(e,n)?e:n},Zz=(e,t)=>t?Xz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0}):e.pinned?Xz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!1}):e,Qz=(e,t)=>{if(e.pinned&&t===`compact`)return e;let n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:Xz(e,{phase:`snapping`,rest:t,progress:n})},$z=e=>Jz(e/80,0,1),eB=e=>e>=80?1:Jz(e/80,0,1),tB=(e,t,n={})=>{if(e.pinned)return e;let r=Math.max(0,t),i=e.phase===`snapping`?Xz(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e;if(i.rest===`expanded`){if(r<=2||n.holdExpanded||n.userDriven===!1)return Xz(i,{phase:`rest`,rest:`expanded`,progress:0});let e=$z(r);return e>=1?Xz(i,{phase:`rest`,rest:`compact`,progress:1}):Xz(i,{phase:`tracking`,rest:`expanded`,progress:e})}if(r<=2)return Xz(i,{phase:`rest`,rest:`expanded`,progress:0});if(n.suppressReturn)return Xz(i,{phase:`rest`,rest:`compact`,progress:1});if(n.towardBottom&&r>=80)return Xz(i,{phase:`snapping`,rest:`expanded`,progress:0});let a=eB(r);return a>=1?Xz(i,{phase:`rest`,rest:`compact`,progress:1}):Xz(i,{phase:`tracking`,rest:`compact`,progress:a})},nB=e=>e.pinned?`expanded`:e.rest===`expanded`?e.progress>=.5?`compact`:`expanded`:e.progress<=.5?`expanded`:`compact`,rB=e=>{if(e.pinned)return Xz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0});if(e.phase===`snapping`)return e;let t=nB(e),n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:Xz(e,{phase:`snapping`,rest:t,progress:n})},iB=e=>e.phase===`snapping`?Xz(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e,aB=e=>Jz(Math.max(0,e)/80,0,1),oB=(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:aB(n),rest:`bottom`}},sB=e=>{e.style.removeProperty(Gz),e.style.removeProperty(Kz),delete e.dataset.ocComposerSwapPhase,delete e.dataset.ocComposerSwapRest,delete e.dataset.ocNativeComposerDock},cB=(e,t,n)=>{let r=oB(t,n?.rest===`bottom`?`bottom`:`away`),i=String(r.progress),a=r.rest;return n?.progress!==i&&e.style.setProperty(Kz,i),n?.rest!==a&&(e.dataset.ocNativeComposerDock=a),{progress:i,rest:a}},lB=(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(Gz,r),n?.rest!==a&&(e.dataset.ocComposerSwapRest=a),{progress:r,phase:i,rest:a}},uB=e=>({scrollHeight:e.scrollHeight,scrollTop:e.scrollTop,clientHeight:e.clientHeight}),dB=()=>{let e=document.documentElement;return e.classList.contains(`oc-keyboard-open`)||e.classList.contains(`oc-kb-animating`)},fB=e=>{if(dB()||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)},pB=e=>{let t=Z.useRef(qz()),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(0),u=Z.useRef(null),d=Z.useRef(0),f=Z.useRef(0),p=Z.useRef(!1),m=Z.useRef(e.enabled);m.current=e.enabled;let h=e=>{e.current!==null&&(window.clearTimeout(e.current),e.current=null)},g=q(t=>{let r=e.scopeRef.current;r&&(n.current=lB(r,t,n.current))}),_=q(e=>{e!==t.current&&(t.current=e,g(e))}),v=q(()=>{if(h(a),t.current.phase!==`snapping`)return;let e=t.current.rest;a.current=window.setTimeout(()=>{a.current=null;let n=iB(t.current);_(n),n.rest===`compact`&&e===`compact`&&(o.current=Date.now()+320,s.current=!0)},240)}),y=q(()=>{let n=e.scopeRef.current;!n||!m.current||_(Zz(t.current,fB(n)))}),b=q(e=>s.current?Date.now()>=o.current?(s.current=!1,!1):e>=80?(s.current=!1,o.current=0,!1):!0:!1),x=q(()=>{if(h(i),!m.current||c.current>0||t.current.phase!==`tracking`)return;let e=rB(t.current);_(e),v()}),S=q(()=>{m.current&&(l.current=Date.now())}),C=q(()=>{m.current&&(l.current=Date.now(),c.current+=1,h(i))}),w=q(()=>{if(!m.current)return;let n=e.scrollRef.current,a=e.scopeRef.current;if(!n||!a)return;let o=fB(a),s=uB(n),g=pI(s,dI(n)),y=u.current;if(u.current=g,n.hasAttribute(`data-oc-timeline-anchoring`)){d.current=0,f.current=0;return}r.current=cB(a,g,r.current);let S=c.current>0||Date.now()-l.current<=1200,C=y===null?0:y-g;S?C>0?(f.current=0,s.scrollTop>0&&(d.current+=C)):C<0&&(d.current=0,f.current+=-C,f.current>=24&&(p.current=!1)):(d.current=0,f.current=0),g<=2&&(p.current=!1);let w=Zz(t.current,o);if(!o){let e=w.rest===`compact`;w=tB(w,g,{suppressReturn:b(g),towardBottom:d.current>=24,holdExpanded:p.current,userDriven:S}),e&&w.rest===`expanded`&&g>2&&(p.current=!0,d.current=0)}if(_(w),h(i),w.phase===`snapping`){v();return}w.phase===`tracking`&&c.current===0&&(i.current=window.setTimeout(()=>{i.current=null,x()},120))}),T=q(()=>{x()}),E=q(()=>{m.current&&(l.current=Date.now(),c.current=Math.max(0,c.current-1),!(c.current>0)&&t.current.phase===`tracking`&&(h(i),i.current=window.setTimeout(()=>{i.current=null,x()},120)))}),D=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)}),O=q(n=>{if(!m.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(),p.current=!0,d.current=0,f.current=0,_(Qz(t.current,`expanded`)),v(),D(),(e.scopeRef.current?.querySelector(`textarea[data-chat-input="true"]`))?.focus({preventScroll:!0})))}),[k,A]=Z.useState(null),[j,M]=Z.useState(null),N=Z.useRef(null),P=q(e=>{e&&sB(e),n.current=void 0,r.current=void 0,s.current=!1,o.current=0,c.current=0,l.current=0,u.current=null,d.current=0,f.current=0,p.current=!1,_(qz())});Z.useLayoutEffect(()=>{let t=e.enabled?e.scrollRef.current:null,n=e.enabled?e.scopeRef.current:null;N.current&&N.current!==n&&P(N.current),N.current=n,A(e=>e===t?e:t),M(e=>e===n?e:n)});let F=Z.useMemo(()=>()=>void 0,[]),I=e.enabled&&k?k:F,L=e.enabled&&j?j:F,R=e.enabled&&typeof window<`u`?window:F,z=Z.useMemo(()=>({passive:!0}),[]);Jt(`scroll`,w,I,z),Jt(`scrollend`,T,I,z),Jt(`touchstart`,C,I,z),Jt(`touchmove`,S,I,z),Jt(`touchend`,E,I,z),Jt(`touchcancel`,E,I,z),Jt(`pointerdown`,O,L),Jt(`focusin`,y,L),Jt(`focusout`,y,L),Jt(`oc:keyboard-intent`,y,R),Jt(`oc:keyboard-anim`,y,R),Jt(`oc:keyboard-settled`,y,R),Z.useEffect(()=>{if(!e.enabled){P(N.current),N.current=null;return}return y(),w(),()=>{h(i),h(a)}},[e.enabled,k,j])},mB=e=>{let t=e.info.clientRole??e.info.role;return typeof t==`string`?t:``},hB=e=>{let t=e.info.parentID;if(typeof t==`string`&&t.trim().length!==0)return t},gB=e=>{if(!e)return null;let t=mB(e);return`${typeof e.info?.id==`string`?e.info.id:``}::${t}::${hB(e)??``}`},_B=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}),vB=(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&&gB(t[r])===gB(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=mB(r),a=r.info.id,o=_B(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=hB(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},yB=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=mB(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=hB(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}},bB=200,xB={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:6e5},SB=()=>bB,CB=()=>Math.round(SB()*.6),wB={MAX_SESSIONS:xB.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(bB*.6),HISTORICAL_MESSAGES:bB,FETCH_BUFFER:20,HISTORY_CHUNK:bB,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:xB.ZOMBIE_TIMEOUT},TB=()=>{let e=SB(),t=CB();return{...wB,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},EB=wB,DB=600,OB=6e3,kB=.5,AB=(e,t)=>e.querySelector(`[data-message-id="${CSS.escape(t)}"]`),jB=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},MB=(e,t)=>{let n=AB(e,t);if(n||=jB(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}},NB=e=>{let{container:t,quiesceMs:n=DB,maxLifetimeMs:r=OB}=e,i={messageId:e.anchor.messageId,offsetTop:e.anchor.offsetTop},a=!1,o=null,s=null,c=!1,l=t.scrollTop,u=()=>{o!==null&&(clearTimeout(o),o=null)},d=()=>{s!==null&&(clearTimeout(s),s=null)},f=()=>{a||(a=!0,y.disconnect(),t.removeEventListener(`scroll`,v),u(),d())},p=()=>{u(),!a&&(o=setTimeout(()=>{o=null,f()},n))},m=()=>{d(),!a&&(s=setTimeout(()=>{s=null,f()},r))},h=()=>{if(a)return;let e=MB(t,i.messageId);if(!e){f();return}i.messageId=e.messageId,i.offsetTop=e.offsetTop,l=t.scrollTop},g=()=>{if(a)return;if(Math.abs(t.scrollTop-l)>kB){h();return}let e=AB(t,i.messageId);if(!e){let n=jB(t);if(!n){f();return}let r=n.dataset.messageId;if(!r){f();return}let a=t.getBoundingClientRect();i.messageId=r,i.offsetTop=n.getBoundingClientRect().top-a.top,e=n,l=t.scrollTop}let n=t.getBoundingClientRect(),r=e.getBoundingClientRect().top-n.top-i.offsetTop;Math.abs(r)>kB&&(t.scrollTop+=r),l=t.scrollTop},_=()=>{a||c||(c=!0,queueMicrotask(()=>{c=!1,g()}))},v=()=>{h(),p(),m()},y=new MutationObserver(()=>{a||(_(),p())});return y.observe(t,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`style`,`class`]}),t.addEventListener(`scroll`,v,{passive:!0}),m(),p(),{rebase:h,dispose:f}},PB=30,FB=1200,IB=1.5,LB=e=>Math.max(FB,e*IB),RB=4,zB=30,BB=4,VB=30,HB=250,UB=2e3,WB=Mr+2e3,GB=40,KB=`history-loading-timeout`,qB=e=>!!(e&&typeof e==`object`&&e.code===`history-loading-timeout`),JB=()=>{let e=Error(`chat history pagination wait timed out`);return e.code=KB,e},YB=(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)},XB=2500,ZB=new Map,QB=()=>x()?RB:hr()?BB:PB,$B=e=>x()?e.length<=zB:!hr()||e.length<=VB,eV=(e,t)=>{if(ZB.delete(e),!$B(t.messages))return;let n=QB();for(;ZB.size>=n;){let e=ZB.keys().next().value;if(typeof e!=`string`)break;ZB.delete(e)}ZB.set(e,t)},tV=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),nV=e=>e?{owner:`tanstack-core`}:{owner:`controller`},rV=(e,t)=>e?e.canLoadEarlier:t>=TB().HISTORICAL_MESSAGES,iV=e=>!(e.isMobile||e.isLoadingOlder||e.pendingRevealWork||!e.canLoadEarlier||e.source===`scroll`&&e.isPinned||e.scrollTop>=LB(e.clientHeight)),aV=e=>e.pagesLoaded>=e.maxPages?`stop-bounded`:e.hasMoreAbove?e.scrollHeightAfter-e.scrollHeightBefore>1?`stop-visible`:e.messageCountAfter>e.messageCountBefore||typeof e.oldestIdBefore==`string`&&typeof e.oldestIdAfter==`string`&&e.oldestIdBefore!==e.oldestIdAfter||e.limitAfter>e.limitBefore?`continue`:`stop-no-growth`:`stop-exhausted`,oV=1,sV=8,cV=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),lV=e=>[`chat-timeline-auto-fill`,e.runtimeKey,e.sessionId,e.oldestMessageId,e.messageCount,e.canLoadEarlier],uV=e=>[`chat-timeline-load-earlier`,e.runtimeKey,e.sessionId],dV=20,fV=4,pV=80,mV=new WeakMap,hV=new WeakMap,gV=e=>{let t=hV.get(e)??{generation:0};return t.generation+=1,hV.set(e,t),t.generation},_V=e=>{let t=mV.get(e);t&&(t.touches=0,t.pending=null,t.settleScheduled=!1),gV(e)},vV=e=>{yV(e)},yV=e=>{let t=mV.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&&bV(e,n)};return e.addEventListener(`touchend`,r,{passive:!0}),e.addEventListener(`touchcancel`,r,{passive:!0}),mV.set(e,n),n},bV=(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+pV||xV(e,n.anchorTop+n.delta))}))},xV=(e,t)=>{let n=gV(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((hV.get(e)?.generation??0)!==n){e.removeEventListener(`touchstart`,o);return}e.scrollTop<t-fV&&(e.scrollTop=t),a+=1,a<dV?window.requestAnimationFrame(s):e.removeEventListener(`touchstart`,o)}};window.requestAnimationFrame(s)},SV=(e,t,n)=>{let r=yV(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,xV(e,t)},CV=(e,t,n)=>!e||!t||t===e?!1:n.some(t=>t.info.id===e),wV=(e,t)=>e.scrollHeight===t.scrollHeight&&e.clientHeight===t.clientHeight?e:t,TV=({sessionId:e,directory:t=null,messages:n,historyMeta:r,scrollRef:i,messageListRef:a,loadMoreMessages:o,goToBottom:c,releaseAutoFollow:l,beginHistoryViewportPreservation:u,endHistoryViewportPreservation:d,isPinned:f,showScrollButton:p,autoFillEnabled:m=!1,onWillLoadEarlier:h})=>{let g=Z.useRef(null),_=Z.useRef(null),v=Z.useMemo(()=>{let t=e??``,r=t?ZB.get(t):void 0;if(r&&r.messages===n)return eV(t,r),g.current=r.model,_.current=n,r.model;let i=vB(g.current,_.current,n)??yB(n);return g.current=i,_.current=n,t&&n.length>0&&eV(t,{messages:n,model:i}),i},[n,e]),[y,b]=Z.useState(!1),[x,S]=Z.useState(!1),[C,w]=Z.useState(null),[T,E]=Z.useState(!1),[D,O]=Z.useState(null),[k,A]=Z.useState({scrollHeight:0,clientHeight:0}),j=Z.useRef(v),M=Z.useRef(f),N=Z.useRef(y),P=Z.useRef(x),F=Z.useRef(e),I=Z.useRef(t??null),L=Z.useRef(n),R=Z.useRef(r),z=Z.useRef(D),B=Z.useRef([]),V=Z.useRef(null),H=Z.useRef(null),ee=Z.useRef(!1),U=Z.useRef(null),[te,W]=Z.useState(e);te!==e&&(W(e),U.current!==null&&typeof window<`u`&&(window.clearTimeout(U.current),U.current=null),ee.current=!1,N.current=!1,H.current=null,b(!1),S(!1),w(null),E(!1),z.current=null,O(null),A({scrollHeight:0,clientHeight:0}));let ne=Z.useMemo(()=>{let e=r?.limit!==D&&rV(r,n.length);return{hasBufferedTurns:!1,hasMoreAboveTurns:e,historyLoading:!!r?.loading,canLoadEarlier:e}},[r,n.length]),G=Z.useRef(ne);j.current=v,M.current=f,P.current=x,G.current=ne,F.current=e,I.current=t??null,L.current=n,R.current=r,z.current=D;let K=q(()=>{ee.current=!0,U.current!==null&&typeof window<`u`&&(window.clearTimeout(U.current),U.current=null)}),re=q(()=>{if(typeof window>`u`){ee.current=!1;return}U.current!==null&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>{U.current=null,ee.current=!1},UB)}),ie=q(()=>{let e=B.current;e.length!==0&&(B.current=[],e.forEach(e=>e()))}),ae=q(()=>new Promise(e=>{if(typeof window>`u`){e();return}let t=!1,n=()=>{t||(t=!0,window.clearTimeout(r),e())};B.current.push(n);let r=window.setTimeout(n,HB)})),oe=q(e=>{let t=V.current;t&&(V.current=null,t.resolve(e))}),se=q(()=>{let e=V.current;if(e){if(e.sessionId!==F.current){oe(!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&&(H.current={turnId:e.turnId,expiresAt:Date.now()+XB},w(e.turnId)),oe(!0);return}typeof(e.kind===`turn`?j.current.turnIndexById.get(e.id):j.current.messageToTurnIndex.get(e.id))==`number`&&oe(!1)}}),ce=Z.useRef(null),le=q(()=>{let e=ce.current;e&&(ce.current=null,e.dispose())});Wt(()=>{U.current!==null&&typeof window<`u`&&(window.clearTimeout(U.current),U.current=null),le(),ie(),oe(!1)});let ue=n;qt(()=>{ie(),se()},[ue]);let de=q(()=>{let e=i.current;if(!e){A(e=>wV(e,{scrollHeight:0,clientHeight:0}));return}A(t=>wV(t,{scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}))});Yt(typeof ResizeObserver<`u`?i:null,de),qt(()=>{de()},[e,y]);let fe=Z.useRef(null),pe=q(()=>a.current?.captureViewportAnchor()??null),me=q(e=>a.current?.restoreViewportAnchor(e)??!1),he=q(()=>{if(hr())return;le();let e=i.current;if(!e)return;let t=pe();t&&(ce.current=NB({container:e,anchor:t}))}),ge=Z.useRef(null);qt(()=>{if(!hr())return;let e=i.current;e&&(vV(e),_V(e))},[e,i]),qt(()=>{le(),fe.current=null,ge.current=null,a.current?.cancelViewportAnchorHold()},[e]),qt(()=>{let e=i.current;if(!e)return;let t=fe.current;t&&Math.abs(e.scrollTop-t.top)>sV&&(fe.current=null,t=null);let n=ge.current,r=ue[0]?.info?.id??null,o=ue[ue.length-1]?.info?.id??null,s=n?tV({previousOldestId:n.oldestId,previousNewestId:n.newestId,currentOldestId:r,currentNewestId:o})||CV(n.oldestId,r,ue):!1;t&&t.sessionId!==F.current&&(fe.current=null,t=null);let l=t?tV({previousOldestId:t.oldestId,previousNewestId:t.newestId,currentOldestId:r,currentNewestId:o})||CV(t.oldestId,r,ue):!1,u=s||l,d=e=>{ge.current={oldestId:r,newestId:o,scrollHeight:e??ge.current?.scrollHeight??0}};if(M.current&&!t){le(),u?(fe.current=null,c(`instant`),d(e.scrollHeight)):d();return}let f=nV(a.current?.isHistoryVirtualized()??!1);if(t){if(f.owner===`tanstack-core`){a.current?.cancelViewportAnchorHold();let e=t.anchor;e&&me(e),d();return}let n=e.scrollHeight,r=n-t.height;if(hr()){r>0&&SV(e,t.top+r,r),d(n);return}let i=t.anchor;!(i&&me(i))&&r>0&&(e.scrollTop=t.top+r),d(n);return}if(s&&n&&f.owner===`controller`){let t=e.scrollHeight,r=t-n.scrollHeight;if(r>0){let t=e.scrollTop+r;hr()?SV(e,t,r):e.scrollTop=t}d(t),he();return}d()},[ue,c]);let _e=q(async()=>!1),ve=q(async e=>{let t=Date.now(),n=t+WB,r=I.current,i=r?Ni()?.getRequestState?.(yi(r,e)):void 0;for(G.current.historyLoading,R.current,i?.status,i?.error;G.current.historyLoading;){if(F.current!==e)return Date.now()-t,`switched`;if(Date.now()>=n){let n=r?Ni()?.getRequestState?.(yi(r,e)):void 0;return console.error(`[chat-history] historyLoading wait timed out — sync flag still true`,{sessionId:e,directory:r,elapsedMs:Date.now()-t,waitMs:WB,hostTurnPageTimeoutMs:Mr,historyLoading:G.current.historyLoading,historyMeta:R.current,requestStatusAtStart:i?.status??null,requestStatusAtTimeout:n?.status??null,requestErrorAtTimeout:n?.error??null,likelyStaleLoadingFlag:n?.status===`ready`||n?.status===`error`||n==null}),`timeout`}await new Promise(e=>{if(typeof window>`u`){e();return}window.setTimeout(e,GB)})}return Date.now()-t,r&&Ni()?.getRequestState?.(yi(r,e))?.status,F.current===e?`cleared`:`switched`}),ye=q(async e=>{if(!F.current||N.current||!G.current.hasMoreAboveTurns)return!1;N.current=!0,K(),b(!0);let t=F.current,n=null,r=!!e.userInitiated;r&&u();let s=()=>{n&&fe.current===n&&(fe.current=null,a.current?.cancelViewportAnchorHold()),r&&(r=!1,d())};try{if(G.current.historyLoading){if(!e.userInitiated)return!1;let n=await ve(t);if(n===`timeout`)throw JB();if(n===`switched`||!G.current.hasMoreAboveTurns)return!1}if(!F.current||F.current!==t)return!1;let r=i.current,a=L.current,c=a.length,l=a[0]?.info?.id??null,u=R.current?.limit??TB().HISTORICAL_MESSAGES;e.preserveViewport&&r&&(n={sessionId:F.current,height:r.scrollHeight,top:r.scrollTop,anchor:pe(),oldestId:l,newestId:a[a.length-1]?.info?.id??null},fe.current=n,he());let d=c,f=l,p=u,m=0;for(;;){if(G.current.historyLoading)if(e.userInitiated){let e=await ve(t);if(e===`timeout`)throw s(),JB();if(e===`switched`)return s(),!1}else return s(),!1;let n=i.current?.scrollHeight??0,r=d,a=f,c=p;if(await o(t,`up`),m+=1,F.current!==t)return s(),!1;await ae();let l=L.current,u=l.length,h=l[0]?.info?.id??null,g=R.current?.limit??p,_=aV({scrollHeightBefore:n,scrollHeightAfter:i.current?.scrollHeight??n,messageCountBefore:r,messageCountAfter:u,oldestIdBefore:a,oldestIdAfter:h,limitBefore:c,limitAfter:g,hasMoreAbove:G.current.hasMoreAboveTurns,pagesLoaded:m,maxPages:oV});if(_===`continue`){d=u,f=h,p=g;continue}if(_===`stop-no-growth`){if(G.current.historyLoading){if(e.userInitiated){let e=await ve(t);if(e===`timeout`)throw s(),JB();if(e===`switched`)return s(),!1;--m;continue}return s(),!1}let n=R.current?.limit??c;return z.current=n,O(n),G.current={...G.current,hasMoreAboveTurns:!1,canLoadEarlier:!1},s(),!1}return!0}}catch(e){throw s(),e}finally{N.current=!1,b(!1),re(),ae().then(s)}}),{t:be}=Zt(),xe=Nt({mutationKey:uV({runtimeKey:s(),sessionId:e??``}),mutationFn:async e=>{if(F.current!==e.sessionId)return!1;K(),e.userInitiated&&l();try{return await ye({preserveViewport:!0,userInitiated:!!e.userInitiated})}finally{re()}}}),Se=q(async e=>{let t=F.current;if(t&&!(xe.isPending&&xe.variables?.sessionId===t)){e?.userInitiated&&h?.();try{let n=await xe.mutateAsync({sessionId:t,userInitiated:!!e?.userInitiated});if(n===!1&&G.current.canLoadEarlier){let r={sessionId:t,grew:n,userInitiated:!!e?.userInitiated,canLoadEarlier:G.current.canLoadEarlier,hasMoreAboveTurns:G.current.hasMoreAboveTurns,historyLoading:G.current.historyLoading,historyMeta:R.current,messageCount:L.current.length,oldestMessageId:L.current[0]?.info?.id??null};YB(`no-growth`,Error(`chat history pagination returned no growth`),r),e?.userInitiated&&fa.error(be(`chat.history.loadOlderFailed`))}}catch(n){let r={sessionId:t,userInitiated:!!e?.userInitiated,waitMs:WB,hostTurnPageTimeoutMs:Mr,canLoadEarlier:G.current.canLoadEarlier,historyLoading:G.current.historyLoading,historyMeta:R.current,messageCount:L.current.length,oldestMessageId:L.current[0]?.info?.id??null};qB(n)?YB(`timeout`,n,r):YB(`failed`,n,r),e?.userInitiated&&fa.error(qB(n)?be(`chat.history.loadOlderTimeout`):be(`chat.history.loadOlderFailed`))}}}),Ce=xe.isPending&&xe.variables?.sessionId===e||y,we=n[0]?.info?.id??null,Te=cV({enabled:m,isMobile:hr(),sessionReady:!!e,messageReady:n.length>0||!!r,historyLoading:ne.historyLoading,canLoadEarlier:ne.canLoadEarlier,isPinned:f,fillBlocked:T,scrollHeight:k.scrollHeight,clientHeight:k.clientHeight,pendingRevealWork:x,isLoadingOlder:!1,hasMessages:n.length>0});Pt({queryKey:lV({runtimeKey:s(),sessionId:e??``,oldestMessageId:we,messageCount:n.length,canLoadEarlier:ne.canLoadEarlier}),enabled:!!e&&Te,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()=>{let e=F.current;if(!e)return{status:`skip`};if(G.current.historyLoading||N.current){let e=Error(`auto-fill-busy`);throw e.code=`auto-fill-busy`,e}if(!G.current.canLoadEarlier)return{status:`skip`};let t=i.current;if(!t||t.clientHeight<=0)return{status:`skip`};if(t.scrollHeight>t.clientHeight+48)return{status:`tall`};try{let t=await ye({preserveViewport:!0});return t?{status:`grew`}:(G.current.canLoadEarlier&&YB(`no-growth`,Error(`chat history pagination returned no growth`),{sessionId:e,source:`auto-fill`,grew:t,canLoadEarlier:G.current.canLoadEarlier,hasMoreAboveTurns:G.current.hasMoreAboveTurns,historyLoading:G.current.historyLoading,historyMeta:R.current,messageCount:L.current.length,oldestMessageId:L.current[0]?.info?.id??null}),E(!0),{status:`blocked`})}catch(t){if(t?.code===`auto-fill-busy`)throw t;let n={sessionId:e,source:`auto-fill`,waitMs:WB,canLoadEarlier:G.current.canLoadEarlier,historyLoading:G.current.historyLoading,historyMeta:R.current,messageCount:L.current.length,oldestMessageId:L.current[0]?.info?.id??null};throw qB(t)?YB(`timeout`,t,n):YB(`failed`,t,n),E(!0),t instanceof Error?t:Error(`chat timeline auto-fill failed`)}}});let Ee=q(e=>{let t=i.current;t&&iV({source:e,isMobile:hr(),isPinned:M.current,scrollTop:t.scrollTop,clientHeight:t.clientHeight,canLoadEarlier:G.current.canLoadEarlier,isLoadingOlder:N.current,pendingRevealWork:P.current})&&Se({userInitiated:!0})}),De=q(()=>{Ee(`scroll`)}),Oe=q(()=>{Ee(`upward-intent`)}),ke=q(async(t,n)=>{if(!t||!F.current)return!1;l(),S(!0);try{return F.current!==e||typeof j.current.turnIndexById.get(t)!=`number`?!1:!!await new Promise(r=>{V.current={sessionId:F.current??e??``,kind:`turn`,id:t,behavior:n?.behavior??`auto`,turnId:t,resolve:r},se()})}finally{S(!1)}}),Ae=q(async(t,n)=>{if(!t||!F.current)return!1;l(),S(!0);try{if(F.current!==e)return!1;let r=j.current.messageToTurnId.get(t);return typeof j.current.messageToTurnIndex.get(t)==`number`&&!!await new Promise(i=>{V.current={sessionId:F.current??e??``,kind:`message`,id:t,behavior:n?.behavior??`auto`,turnId:r??null,resolve:i},se()})}finally{S(!1)}}),je=q(async()=>{S(!1),N.current=!1,b(!1),a.current?.scrollToBottom(),c(`smooth`)}),Me=q(async()=>{S(!1),N.current=!1,b(!1),a.current?.scrollToBottom(),c(`instant`)}),Ne=q(e=>{let t=H.current;if(t){if(e!==t.turnId&&Date.now()<t.expiresAt)return;H.current=null}w(e)});return{turnIds:v.turnIds,turnStart:0,renderedMessages:ue,historySignals:ne,isLoadingOlder:Ce,pendingRevealWork:x,activeTurnId:C,showScrollToBottom:p&&!x,turnWindowModel:v,loadEarlier:Se,revealBufferedTurns:_e,resumeToBottom:je,resumeToBottomInstant:Me,scrollToTurn:ke,scrollToMessage:Ae,handleHistoryScroll:De,handleHistoryUpwardIntent:Oe,captureViewportAnchor:pe,restoreViewportAnchor:me,handleActiveTurnChange:Ne}},EV=({mutateSession:e,forkSession:t})=>({revert:e,fork:t}),DV=({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{t:d}=Zt(),f=zy(),p=n,m=ka(p??``,r),h=J(e=>e.revertToMessage),g=J(e=>e.forkFromMessage),_=EV(f.capabilities),{isMobile:v,isTablet:y}=Ws(),b=v||y,[x,S]=Z.useState(null),C=Z.useRef(!1),[w,T]=Z.useState(``),[E,D]=Z.useState(0),O=Z.useRef([]),k=Z.useRef(null),A=Z.useRef(null),j=Z.useRef(!1),M=Z.useRef(e),N=e=>new Date(e).toLocaleDateString(Qt(),{year:`numeric`,month:`short`,day:`numeric`}),P=e=>new Date(e).toLocaleTimeString(Qt(),{hour:`numeric`,minute:`2-digit`}),F=Z.useMemo(()=>m.filter(e=>e.info.role===`user`).map(e=>({message:e})),[m]),I=Z.useMemo(()=>{let e=w.trim();if(!e)return F;let t=e.toLowerCase();return F.filter(({message:e})=>WR(e.parts).toLowerCase().includes(t))},[F,w]);Z.useEffect(()=>{j.current||D(w.trim()?0:Math.max(0,I.length-1))},[I,w]),Z.useEffect(()=>{O.current=O.current.slice(0,I.length)},[I.length]),Z.useEffect(()=>{j.current||O.current[E]?.scrollIntoView({block:`nearest`})},[E]),Z.useEffect(()=>{!j.current||A.current||c||(j.current=!1)},[I.length,c]),Z.useLayoutEffect(()=>{let t=M.current;if(M.current=e,!e||t||j.current||w.trim())return;let n=k.current;n&&(n.scrollTop=n.scrollHeight)},[e,w]),Z.useLayoutEffect(()=>{let e=A.current,t=k.current;if(!e||!t||c)return;A.current=null;let n=O.current.find(t=>t?.dataset.timelineMessageId===e.messageId);if(!n)return;let r=n.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=r-e.top},[I.length,c]);let L=q(()=>{let e=k.current;if(e){let t=e.getBoundingClientRect().top,n=O.current.find(e=>e?e.getBoundingClientRect().bottom>=t:!1);n?.dataset.timelineMessageId&&(A.current={messageId:n.dataset.timelineMessageId,top:n.getBoundingClientRect().top-t})}j.current=!0,l?.()}),R=q(async e=>{await i?.(e)!==!1&&t(!1)}),z=q(e=>{let t=I.length;if(t!==0){if(e.key===`ArrowDown`){e.preventDefault(),D(e=>(e+1)%t);return}if(e.key===`ArrowUp`){e.preventDefault(),D(e=>(e-1+t)%t);return}if(e.key===`Enter`){e.preventDefault();let n=(E%t+t)%t,r=I[n];r&&R(r.message.info.id)}}}),B=q(async(e,n)=>{if(!(!p||C.current)){C.current=!0,S({type:e,messageId:n});try{e===`revert`?u?await u(n):await h(p,n,{directory:r}):await g(p,n,{directory:r}),t(!1)}finally{C.current=!1,S(null)}}});return p?(0,$.jsx)(go,{open:e,onOpenChange:t,children:(0,$.jsxs)(fo,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:[(0,$.jsxs)(co,{children:[(0,$.jsxs)(po,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`time`,className:`h-5 w-5`}),d(`chat.timeline.title`)]}),(0,$.jsx)(mo,{children:d(`chat.timeline.description`)})]}),(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[(0,$.jsx)(X,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),(0,$.jsx)(Yo,{autoFocus:!0,placeholder:d(`chat.timeline.searchPlaceholder`),value:w,onChange:e=>T(e.target.value),onKeyDown:z,className:`pl-9 w-full`})]}),s&&l&&(0,$.jsx)(`div`,{className:`flex justify-center py-1`,children:(0,$.jsxs)(yo,{type:`button`,variant:`link`,size:`sm`,onClick:L,disabled:c,className:`h-auto px-1 py-0 text-muted-foreground hover:text-foreground`,children:[c&&(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}),d(`chat.history.loadOlder`)]})}),(0,$.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto`,children:I.length===0?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:d(w?`chat.timeline.empty.search`:`chat.timeline.empty.session`)}):I.map(({message:e},t)=>{let n=GR(e.parts),r=e.info.time.created,i=N(r),a=I[t-1],o=i!==(a?N(a.message.info.time.created):null),s=P(r),c=t===E,l=w.trim()?OV(WR(e.parts),w):null;return(0,$.jsxs)(Z.Fragment,{children:[o&&(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:i}),(0,$.jsx)(`div`,{className:`h-px flex-1 bg-border/60`})]}),(0,$.jsxs)(`div`,{ref:e=>{O.current[t]=e},"data-timeline-message-id":e.info.id,className:Y(`group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,c&&`bg-interactive-selection text-interactive-selection-foreground`),onClick:()=>void R(e.info.id),onMouseEnter:()=>D(t),children:[(0,$.jsx)(`span`,{className:Y(`typography-meta w-16 flex-shrink-0 text-right tabular-nums`,c?`text-interactive-selection-foreground/70`:`text-muted-foreground`),children:s}),(0,$.jsxs)(`p`,{className:Y(`flex-1 min-w-0 typography-micro truncate`,c?`text-interactive-selection-foreground`:`text-foreground`),children:[l??(n||d(`chat.timeline.noTextContent`)),!l&&n&&n.length>=80&&`…`]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:(0,$.jsxs)(`div`,{className:Y(`gap-1`,b?`flex`:`hidden group-hover:flex`),children:[_.revert?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:`size-5 text-muted-foreground hover:text-foreground`,"aria-busy":x?.type===`revert`&&x.messageId===e.info.id,disabled:x!==null,onClick:t=>{t.stopPropagation(),B(`revert`,e.info.id)},children:(0,$.jsx)(X,{name:x?.type===`revert`&&x.messageId===e.info.id?`loader-4`:`arrow-go-back`,className:Y(`h-4 w-4`,x?.type===`revert`&&x.messageId===e.info.id&&`animate-spin`)})})}),(0,$.jsx)(Zo,{sideOffset:6,children:d(`chat.timeline.actions.revertFromHere`)})]}):null,_.fork?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:`size-5 text-muted-foreground hover:text-foreground`,"aria-busy":x?.type===`fork`&&x.messageId===e.info.id,onClick:t=>{t.stopPropagation(),B(`fork`,e.info.id)},disabled:x!==null,children:x?.type===`fork`&&x.messageId===e.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)(Zo,{sideOffset:6,children:d(`chat.timeline.actions.forkFromHere`)})]}):null]})})]})]},e.info.id)})}),(0,$.jsxs)(`div`,{className:`mt-4 p-3 bg-muted/30 rounded-lg`,children:[(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground font-medium mb-2`,children:d(`chat.timeline.actions.title`)}),(0,$.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:()=>{a?.(-1),t(!1)},children:d(`chat.timeline.actions.previousTurn`)}),(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`/`}),(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:()=>{o?.(),t(!1)},children:d(`chat.timeline.actions.latest`)})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 typography-meta text-muted-foreground`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,$.jsx)(`span`,{children:d(`chat.timeline.help.clickMessage`)})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`arrow-go-back`,className:`h-4 w-4 flex-shrink-0`}),(0,$.jsx)(`span`,{children:d(`chat.timeline.help.undoToPoint`)})]}),_.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:d(`chat.timeline.help.createSessionFromHere`)})]}):null]})]})]})}):null};function OV(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?`…`:``}`}var kV=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},AV=(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`}},jV=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)},MV=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&&jV(`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&&jV(`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=AV(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 jV(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=()=>{jV(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=kV(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},NV=2e4,PV=6e4,FV=2e3,IV=e=>e?(typeof e.text==`string`?e.text.length:0)+(typeof e.state?.output==`string`?e.state.output.length:0):0,LV=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+=IV(e);return[e.length,t.info.id,n.length,r?.id??``,r?.state?.status??``,i].join(`:`)},RV={sessionKey:null,fingerprint:null,lastMovementAt:null,lastRefreshAt:null,attempts:0},zV=(e,t)=>{let{sessionKey:n,working:r,streaming:i,fingerprint:a,now:o}=t;if(!n)return{state:RV,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}},BV=e=>{console.warn(`[transcript] tail frozen while session is working — refetching authority`,e)};function VV(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 HV(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 UV(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||VV(i)==null}function WV(e){let t=[];for(let n of e){let e=Array.isArray(n.parts)?n.parts:[];for(let n of e){if(!UV(n))continue;let e=HV(n);e&&t.push(e)}}return t}function GV(e,t){return`${e}:${t.join(`,`)}`}function KV(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=GV(t,e.unansweredToolIds);return e.attemptedKey===r?{recover:!1,attemptKey:r}:{recover:!0,attemptKey:r}}function qV(e,t,n,r){let i=(0,Q.c)(7),a=Un(),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=KV({sessionId:e,directory:t,sessionQuestionCount:r,unansweredToolIds:WV(n),attemptedKey:o.current});if(!c.recover||!e||!t||!c.attemptKey)return;let l=a.getChild(t);l&&(o.current=c.attemptKey,Yn(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 JV=e=>!Number.isFinite(e)||e<0?0:Math.ceil(e),YV=(e,t)=>({...e,key:XV(e),estimatedBytes:JV(t)}),XV=({runtimeKey:e,sessionId:t,directory:n})=>JSON.stringify([e,n??``,t]),ZV=e=>({key:e?XV(e):null,selection:e}),QV=(e,t,n)=>{let r=Math.max(1,Math.floor(n.maxEntries)),i=Math.max(0,n.maxEstimatedBytes),a=e.reduce((e,t)=>e+t.estimatedBytes,0);if(e.length<=r&&a<=i)return e;let o=[...e];for(;o.length>r||a>i;){let e=o.findIndex(e=>e.key!==t);if(e===-1)break;let[n]=o.splice(e,1);a-=n?.estimatedBytes??0}return o},$V=(e,t,n,r)=>{let i=XV(t),a=e.findIndex(e=>e.key===i),o=a>=0?e[a]:void 0;if(o&&a===e.length-1)return QV(e,i,n);let s=o||YV(t,r),c=a>=0?e.filter((e,t)=>t!==a):[...e];return c.push(s),QV(c,i,n)},eH=(e,t,n)=>{let r=JV(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)},tH=(e,t)=>t&&e.some(e=>e.key===t)?t:null,nH=(e,t,n)=>{let r=t.key?e.cachedSessionViews.find(e=>e.key===t.key):void 0,i=r&&t.selection?$V(e.cachedSessionViews,t.selection,n,r.estimatedBytes):QV(e.cachedSessionViews,t.key??``,n),a=!r&&e.pendingSessionView?.intent===t?e.pendingSessionView:null;return e.activeIntent===t&&!e.cacheNeedsTrim&&i===e.cachedSessionViews&&a===e.pendingSessionView?e:{activeIntent:t,cacheNeedsTrim:!1,cachedSessionViews:i,pendingSessionView:a}},rH=(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:YV(t.selection,r),intent:t};return e.pendingSessionView?.intent===t?e:{activeIntent:e.activeIntent,cacheNeedsTrim:e.cacheNeedsTrim,cachedSessionViews:e.cachedSessionViews,pendingSessionView:i}},iH=(e,t,n)=>{let r=e.pendingSessionView;return e.activeIntent!==t||r?.intent!==t||!t.selection?e:{activeIntent:e.activeIntent,cacheNeedsTrim:!1,cachedSessionViews:$V(e.cachedSessionViews,t.selection,n,r.entry.estimatedBytes),pendingSessionView:null}},aH=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},oH=e=>{if(!(!e.info||typeof e.info!=`object`))return e.info},sH=e=>oH(e)?.role===`assistant`,cH=(e,t)=>{let n=oH(t);n&&(e.agentName??=aH(n.agent),e.providerId??=aH(n.providerID),e.modelId??=aH(n.modelID))},lH=e=>!!(e.agentName&&e.providerId&&e.modelId),uH=e=>{let t={};for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||!sH(r))&&(cH(t,r),lH(t)))return t}for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||sH(r))&&(cH(t,r),lH(t)))break}return t},dH=e=>!!e.sessionId&&!(e.hasRenderableSessionSnapshot&&e.hasCurrentSessionEntity),fH=[],pH=[],mH={type:`idle`},hH=`openchamber:chat-force-scroll-bottom`,gH=()=>void 0,_H=`Quota limit reached. Retrying automatically.`,vH=1048576,yH=vH,bH=20,xH=vH,SH=16*vH,CH={maxEntries:3,maxEstimatedBytes:32*vH},wH={maxEntries:2,maxEstimatedBytes:32*vH},TH=e=>t(()=>e()),EH={overflowAnchor:`none`,overscrollBehavior:`contain`,overscrollBehaviorY:`contain`},DH={scrollbar:`chat`,scrollShadow:`true`,orientation:`vertical`},OH=()=>{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},kH=`calc(max(0.625rem, var(--oc-safe-area-top, 0px)) + var(--oc-mobile-detail-navigation-height) + 1.25rem)`,AH=yz,jH=[`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(`,`),MH=e=>e instanceof HTMLElement,NH=e=>MH(e)?!!e.closest(jH):!1,PH=(e,t)=>typeof document>`u`||!e||e===document.body||e===document.documentElement||NH(e)?!0:!t?.contains(e),FH=()=>{let{isAboutDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isImagePreviewOpen:r,isMultiRunLauncherOpen:i,isSessionSwitcherOpen:a,isSettingsDialogOpen:o}=g.getState();return e||t||n||r||i||a||o},IH=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,isProgrammaticFollowActive:E,showLoadOlderButton:D,onLoadOlder:O,turnIds:k,activeTurnId:A,onSelectTurn:j,showPromptNavigator:M,canLoadEarlierPrompts:N,isLoadingOlderPrompts:P,onLoadEarlierPrompts:F,transcriptStatusRow:I})=>{let{t:L}=Zt(),R=gl(e=>e.legendTimelineEnabled),z=bT({isLoadingOlder:d}),B=xT({isMobile:r,isLoadingOlder:z}),V=Z.useRef(new Map),H=Z.useRef(new WeakMap),ee=Z.useRef(new Map),U=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(qI(n)){let r=YI(u,t)??``,i=ee.current.get(n.info.id);if(i&&i.command===r)e.set(n.info.id,i.parts);else{let t=[{type:`text`,text:r?`$ ${r}`:`/shell`}];ee.current.set(n.info.id,{command:r,parts:t}),e.set(n.info.id,t)}continue}if(Kn(n.parts))continue;let r=H.current.get(n.parts);r||(r=pi(n.parts),H.current.set(n.parts,r)),r.length!==0&&e.set(n.info.id,r)}let t=V.current;if(t.size===e.size){let n=!0;for(let[r,i]of e)if(t.get(r)!==i){n=!1;break}if(n)return t}return V.current=e,e},[u]),te=Z.useMemo(()=>k.filter(e=>U.has(e)),[U,k]),W=Z.useMemo(()=>{if(!A||U.has(A))return A;let e=k.indexOf(A);for(let t=e-1;t>=0;--t){let e=k[t];if(U.has(e))return e}return null},[A,U,k]),ne=q(e=>{e.defaultPrevented||NH(e.target)||typeof window<`u`&&window.getSelection()?.type===`Range`||o.current?.focus({preventScroll:!0})});return Cz({scrollRef:o,enabled:R,onUpwardIntent:y}),R?(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,n?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":n,children:(0,$.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,$.jsx)(_R,{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:EH,timelineScrollDataset:DH,timelineOnScroll:v,timelineFollowEnabled:!c&&!x,timelineHistoryAnchorToken:S,timelineOnIsAtEndChange:b,headerSlot:(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:kH},"aria-hidden":`true`}),D&&(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsxs)(yo,{variant:`secondary`,size:`sm`,onClick:O,disabled:z,"aria-busy":z,children:[z&&(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}),L(`chat.history.loadOlder`)]})}),B&&(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex justify-center pointer-events-none`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin text-[var(--surface-mutedForeground)]`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta text-[var(--surface-mutedForeground)]`,children:L(`chat.history.loadingMore`)})]})})]}),footerSlot:(0,$.jsxs)($.Fragment,{children:[(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(UR,{question:e},e.id)),T.map(e=>(0,$.jsx)(IR,{permission:e},e.id))]}),I?(0,$.jsx)(`div`,{className:`mb-1`,children:I}):null,(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?AH:_z},"aria-hidden":`true`})]})}),(0,$.jsx)(Gs,{containerRef:o,suppressVisibility:E,userIntentOnly:!0,observeMutations:!1}),M&&te.length>=2?(0,$.jsx)(fz,{turnIds:te,previewsByTurnId:U,activeTurnId:W,onSelectTurn:j,canLoadEarlier:N,isLoadingOlder:P,onLoadEarlier:F}):null]})}):(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,n?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":n,children:(0,$.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,$.jsx)(Sl,{className:Y(`absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target`),ref:o,style:EH,observeMutations:!1,hideTopShadow:r&&i,hideBottomShadow:r,tabIndex:0,onClick:ne,onScroll:v,"data-scroll-shadow":`true`,"data-scrollbar":`chat`,children:(0,$.jsxs)(`div`,{className:Y(`oc-chat-scroll-content relative z-0 min-h-full`,r&&`chat-scroll-foot-inset`),children:[D&&(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsxs)(yo,{variant:`secondary`,size:`sm`,onClick:O,disabled:z,"aria-busy":z,children:[z&&(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}),L(`chat.history.loadOlder`)]})}),B&&(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex justify-center pointer-events-none`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin text-[var(--surface-mutedForeground)]`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta text-[var(--surface-mutedForeground)]`,children:L(`chat.history.loadingMore`)})]})}),(0,$.jsx)(_R,{ref:s,sessionKey:e,virtualizerKey:t,disableStaging:c,initialPinRevealComplete:l,messages:u,sessionIsWorking:f,activeStreamingMessageId:p,activeStreamingPhase:m,retryOverlay:h,onMessageContentChange:g,getAnimationHandlers:_,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:a,liveStatusSlot:u.length>0?(0,$.jsx)(`div`,{className:`mb-1`,children:I??(0,$.jsx)(JN,{})}):null}),(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(UR,{question:e},e.id)),T.map(e=>(0,$.jsx)(IR,{permission:e},e.id))]}),(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?vz:_z},"aria-hidden":`true`})]})}),(0,$.jsx)(Gs,{containerRef:o,suppressVisibility:E,userIntentOnly:!0,observeMutations:!1}),M&&te.length>=2?(0,$.jsx)(fz,{turnIds:te,previewsByTurnId:U,activeTurnId:W,onSelectTurn:j,canLoadEarlier:N,isLoadingOlder:P,onLoadEarlier:F}):null]})})},(e,t)=>e.currentSessionId===t.currentSessionId&&e.virtualizerKey===t.virtualizerKey&&e.isDesktopExpandedInput===t.isDesktopExpandedInput&&e.isMobile===t.isMobile&&e.stickyUserHeader===t.stickyUserHeader&&e.directory===t.directory&&e.scrollRef===t.scrollRef&&e.messageListRef===t.messageListRef&&e.pendingRevealWork===t.pendingRevealWork&&e.initialPinRevealComplete===t.initialPinRevealComplete&&e.renderedMessages===t.renderedMessages&&e.isLoadingOlder===t.isLoadingOlder&&e.sessionIsWorking===t.sessionIsWorking&&e.streamingMessageId===t.streamingMessageId&&e.activeStreamingPhase===t.activeStreamingPhase&&e.retryOverlay===t.retryOverlay&&e.handleMessageContentChange===t.handleMessageContentChange&&e.getAnimationHandlers===t.getAnimationHandlers&&e.handleHistoryScroll===t.handleHistoryScroll&&e.handleHistoryUpwardIntent===t.handleHistoryUpwardIntent&&e.onTimelineIsAtEndChange===t.onTimelineIsAtEndChange&&e.timelineFollowSuspended===t.timelineFollowSuspended&&e.timelineHistoryAnchorToken===t.timelineHistoryAnchorToken&&e.scrollToBottom===t.scrollToBottom&&e.sessionQuestions===t.sessionQuestions&&e.sessionPermissions===t.sessionPermissions&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&e.onLoadOlder===t.onLoadOlder&&e.turnIds===t.turnIds&&e.activeTurnId===t.activeTurnId&&e.onSelectTurn===t.onSelectTurn&&e.showPromptNavigator===t.showPromptNavigator&&e.canLoadEarlierPrompts===t.canLoadEarlierPrompts&&e.isLoadingOlderPrompts===t.isLoadingOlderPrompts&&e.onLoadEarlierPrompts===t.onLoadEarlierPrompts&&e.transcriptStatusRow===t.transcriptStatusRow);IH.displayName=`ChatViewport`;var LH=[{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%]`]}],RH=e=>_o(e.path),zH=(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)]})},BH=e=>{let t=Math.ceil(Math.max(0,e)/bH);return Math.min(SH,yH+t*xH)},VH=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=pH,onPendingUserMessagesMaterialized:p,committedDraftHandoffMessageId:m=null})=>{let h=c??TT(void 0),{t:_}=Zt();qt(()=>{ba()},[]);let v=J(e=>e.openNewSessionDraft),y=J(e=>e.setCurrentSession),b=J(e=>e.newSessionDraft),S=J(e=>e.newSessionDraft.draftSubmitting??!1),C=J(e=>e.newSessionDraft.draftEstablishing??!1),w=J(e=>e.forkTransition),T=Gi(e=>e.projects),E=Gi(e=>e.activeProjectId),D=ui(e=>e.providers),O=jm(),k=Wi(),A=i??k;qt(()=>{!n||!r||!A||sr(A,r)},[n,r,A]);let j=q(e=>O.ensureSessionRenderable(e,{directory:A})),M=g(e=>e.isExpandedInput),N=g(e=>e.stickyUserHeader),P=g(e=>e.promptNavigatorEnabled),F=g(e=>e.allowPromptingSubagentSessions),I=g(e=>e.isTimelineDialogOpen),L=g(e=>e.setTimelineDialogOpen),R=qa(e=>n&&r?e.streamingMessageIds.get(r)??null:null),z=qa(e=>R?e.messageStreamStates.get(R)?.phase??null:null),B=Fa(r??``,A),V=BH(B);Z.useEffect(()=>{!a||!o||o(a,V)},[o,V,a]);let H=ji(r??``,A).renderable,ee=Dr(r,A),U=Wr(r),te=ee??U,W=Pb({sessionId:r,hasSessionEntity:!!te,hasRenderableSessionSnapshot:H,composerSurfaceKind:s?.kind}),ne=r?JSON.stringify([A,r]):null,[G,K]=Z.useState({key:ne,attempt:0}),re=ka(r??``,A,{suspendPartUpdates:!!R,suspendPartUpdatesForMessageId:R}),ie=r?re:fH,ae=b.pendingUserMessage,oe=J(e=>r?e.retainedPendingUserMessages.get(r):void 0)??pH,se=!!(m||oe.length>0),ce=J(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(()=>uH(ie),[ie]),de=Z.useMemo(()=>{if(!ue.modelId)return _(`common.unavailable`);let e=D.find(e=>e.id===ue.providerId);return Hr(e,ue.modelId)||ue.modelId},[D,ue.modelId,ue.providerId,_]),fe=_a(r??``,A),pe=Fi(r??``,A),[me,he]=Z.useState(null),ge=!!r&&me===r,_e=q(()=>{if(!r||ge)return;let e=r,t=A;he(e);let n=Ma(()=>{let n=Ni();if(!n)throw Error(`unbound`);return n.getTranscript(yi(t,e))});Ji(oa({kind:`refresh`,sessionID:e,directory:t,purpose:`retry`,source:`network`,request:fe?{sessionID:e,status:fe.status===`ready`?`ready`:fe.status,error:fe.error}:void 0,hydration:pe,error:fe?.error})),(async()=>{try{await Ha(t,e),await O.ensureSessionRenderable(e,{directory:t});try{let r=Ma(()=>{let n=Ni();if(!n)throw Error(`unbound`);return n.getTranscript(yi(t,e))});n&&r&&_i({trigger:`user-refresh`,sessionID:e,directory:t,purpose:`retry`,before:n,after:r})}catch{}}catch(n){Ji(oa({kind:`request-error`,sessionID:e,directory:t,purpose:`retry`,source:`network`,hydration:pe,error:n}))}finally{he(t=>t===e?null:t)}})()}),ve=Sa(r??``,A).boundary,ye=q(async e=>{if(ve.kind===`has-more`){await La(A,e);return}if(ve.kind===`unknown`){await aa(A,e);return}l&&!l.complete&&await l.fetchPrevious()}),be=sa(r??``,A),xe=za(r??``,A),Se=ki(A),Ce=be??mH,we=ri(r,A),Te=fi(r,A);qV(r,A,ie,Te.length);let Ee=Z.useMemo(()=>{if(!r||we.length>0||Te.length>0)return!1;let e=Ce.type??`idle`;if(e===`busy`||e===`retry`||gT(le,{resolvedSessionStatus:be,sessionStatusObservedAt:xe}))return!0;let t=ie[ie.length-1]?.info,n=t?.time?.created;return be&&typeof xe==`number`&&typeof n==`number`&&n<=xe||typeof Se==`number`&&typeof n==`number`&&n<=Se?!1:!!(t&&t.role===`assistant`&&typeof t.time?.completed!=`number`)},[r,le,be,ie,we.length,Te.length,Ce.type,xe,Se]),De=Z.useMemo(()=>!r||Ce.type!==`retry`?null:{sessionId:r,message:(typeof Ce.message==`string`?(Ce.message??``).trim():``)||_H,confirmedAt:Ce.confirmedAt},[r,Ce]),[Oe,ke]=Z.useState(0),Ae=Z.useRef(null);Z.useEffect(()=>{if(!De||typeof De.confirmedAt==`number`){Ae.current=null,ke(0);return}Ae.current!==De.sessionId&&(Ae.current=De.sessionId,ke(Date.now()))},[De]);let je=Z.useMemo(()=>De?{...De,fallbackTimestamp:Oe}:null,[De,Oe]),Me=!!(r&&O.isLoading(r,{directory:A})),Ne=Z.useMemo(()=>{if(!r)return null;let e=_T({boundary:ve,assistantComplete:l?.complete??!0});return{limit:ve.loadedTurns,complete:e.complete,canLoadEarlier:e.canLoadEarlier,loading:vT({syncLoading:Me,assistantLoading:!!l?.loading})}},[l?.complete,l?.loading,r,ve,Me]),Pe=g(e=>e.isMobile),Fe=Pu()!==null,Ie=x(),Le=Cb(),Re=!!b?.open,ze=zr(e=>e.error),Be=M,Ve=Fe||Pe||Ie||Le===`mini-chat`,He=Z.useRef(null),Ue=Z.useMemo(()=>{let e=b?.selectedProjectId?T.find(e=>e.id===b.selectedProjectId)??null:null,t=E?T.find(e=>e.id===E)??null:null,n=e??t??T[0]??null;return n?RH(n):null},[E,b?.selectedProjectId,T]),We=ci(r,A),Ge=a??r??``,[Ke,qe]=Z.useState(null),Je=zb(Ke,Ge,We,ue);qt(()=>{qe(e=>zb(e,Ge,We,ue))},[We,ue,Ge]);let Ye=We??Je?.parentTarget??null,Xe=Je?.execution??ue,Ze=pf(),Qe=Ze!==null&&r===Ze,$e=q(()=>{Ye&&y(Ye.id,Ye.directory)}),et=Ye?.session?.title,tt=h.returnToParent&&Ye&&!Qe?(0,$.jsxs)(yo,{type:`button`,variant:`outline`,size:`xs`,onClick:$e,className:`absolute left-3 top-3 z-20 !font-normal bg-[var(--surface-background)]/95`,"aria-label":_(`chat.container.returnToParent.aria`),title:et?.trim()?_(`chat.container.returnToParent.titleNamed`,{title:et}):_(`chat.container.returnToParent.title`),children:[(0,$.jsx)(X,{name:`arrow-left`,className:`h-4 w-4`}),_(`chat.container.returnToParent.label`)]}):null,nt=Fb({readOnly:t,sessionIdentityPending:W,isSubagentSession:!!te?.parentID||!!Je,allowPromptingSubagentSessions:F}),rt=Xe.modelId===ue.modelId?de:Xe.modelId?Hr(D.find(e=>e.id===Xe.providerId),Xe.modelId)||Xe.modelId:_(`common.unavailable`),it=Ye?(0,$.jsx)(kT,{agentName:Xe.agentName,providerId:Xe.providerId,modelId:Xe.modelId,modelName:rt}):(0,$.jsx)(kT,{}),at=q(e=>{g.getState().setAllowPromptingSubagentSessions(e.allowPromptingSubagentSessions)}),ot=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`&&at({allowPromptingSubagentSessions:t.payload.allowPromptingSubagentSessions})}),st=typeof window<`u`&&window.parent!==window;Jt(`message`,ot,st?window:gH),Kt(()=>{if(!st)return;let e=window;e.__openchamberApplyChatSettingsSync=at,window.parent.postMessage({type:`openchamber:chat-settings-request`},window.location.origin)}),Wt(()=>{if(typeof window>`u`)return;let e=window;e.__openchamberApplyChatSettingsSync===at&&delete e.__openchamberApplyChatSettingsSync}),Z.useEffect(()=>{h.newSessionDraft&&e&&!r&&!Re&&v()},[e,r,Re,h.newSessionDraft,v]);let ct=Z.useRef(()=>{}),lt=q(e=>{ct.current(e)}),ut=Z.useRef(()=>{}),dt=q(()=>{ut.current()}),ft=gl(e=>e.legendTimelineEnabled),[pt,mt]=Z.useState(!0),[ht,gt]=Z.useState(!1),[_t,vt]=Z.useState(!1),[yt,bt]=Z.useState(0),xt=q(()=>{bt(e=>e+1)}),St=q((e,t)=>{mt(e),e&&vt(!1),t!==void 0&&gt(t)});Z.useEffect(()=>{mt(!0),gt(!1),vt(!1)},[r]);let{scrollRef:Ct,notifyContentChange:wt,getAnimationHandlers:Tt,goToBottom:Et,scrollToBottomOnSend:Dt,releaseAutoFollow:Ot,beginHistoryViewportPreservation:kt,endHistoryViewportPreservation:At,restoreSnapshot:jt,isPinned:Mt,isFollowingProgrammatically:Nt,showScrollButton:Pt}=Wz({enabled:n&&!ft,currentSessionId:r,viewportKey:a,sessionMessageCount:B,sessionIsWorking:Ee,isMobile:Pe,onActiveTurnChange:lt,onUpwardUserIntent:dt}),Ft=Z.useRef(null);pB({enabled:Pe,scrollRef:Ct,scopeRef:Ft});let It=Z.useRef([]),Lt=Z.useMemo(()=>{let e=la(l?.entries??[],r,It.current);return It.current=e,e},[l?.entries,r]),Rt=Z.useRef([]),zt=Z.useMemo(()=>{if(!l)return ie;let e=xa(l.entries,r,ie,Rt.current);return Rt.current=e,e},[l,r,ie]),Bt=Z.useMemo(()=>hT(Lt.length===0?zt:r?[...Lt,Oi(r),...zt]:Lt,le),[r,zt,Lt,le]),Vt=Z.useRef(null),Ht=Z.useMemo(()=>wT({sessionId:r,messages:Bt,retained:Vt.current}),[r,Bt]);Vt.current=Ht.retained;let Ut=Ht.messages,Gt=Z.useRef(null),Xt=Gt.current===r,Qt=Z.useRef(RV),$t=r?`${A}\n${r}`:null,en=q(()=>LV(Ut));Z.useEffect(()=>{if(!r||!$t||!Ee){Qt.current={...Qt.current,lastMovementAt:null};return}let e=r,t=A,n=setInterval(()=>{let n=en(),r=zV(Qt.current,{sessionKey:$t,working:!0,streaming:!!R,fingerprint:n,now:Date.now(),thresholdMs:NV,cooldownMs:PV,maxAttempts:3});Qt.current=r.state,r.shouldRefresh&&(BV({sessionId:e,directory:t,stalledForMs:r.stalledForMs,attempt:r.state.attempts,fingerprint:n}),Li(t,e).catch(()=>{}))},FV);return()=>clearInterval(n)},[r,A,en,Ee,R,$t]);let tn=Z.useMemo(()=>{if(le.length===0)return[];let e=new Set([...Lt,...zt].filter(e=>Ui(e.parts)).map(e=>e.info.id));return le.map(e=>e.info.id).filter(t=>e.has(t))},[zt,Lt,le]);Z.useEffect(()=>{tn.length!==0&&(p?.(tn),r&&ce(r,tn))},[ce,r,tn,p]);let nn=TV({sessionId:r,directory:A,messages:Ut,historyMeta:Ne,scrollRef:Ct,messageListRef:He,loadMoreMessages:ye,goToBottom:Et,releaseAutoFollow:Ot,beginHistoryViewportPreservation:kt,endHistoryViewportPreservation:At,isPinned:ft?pt:Mt,showScrollButton:ft?ht:Pt,autoFillEnabled:n&&!Be,onWillLoadEarlier:xt}),rn=q(()=>{vt(!1),He.current?.scrollToBottom(),Et(`instant`)}),an=q(()=>{vt(!1),Dt()}),on=q(()=>{vt(!0),nn.handleHistoryUpwardIntent()}),sn=yT({isMobile:Pe,canLoadEarlier:nn.historySignals.canLoadEarlier,isLoadingOlder:nn.isLoadingOlder}),cn=nn.isLoadingOlder,ln=nn.loadEarlier,un=q(()=>{vt(!0),ln({userInitiated:!0})});ct.current=nn.handleActiveTurnChange,ut.current=nn.handleHistoryUpwardIntent,Z.useEffect(()=>{(we.length!==0||Te.length!==0)&&wt(`permission`)},[wt,we,Te]);let dn=MV({sessionId:r,turnIds:nn.turnIds,activeTurnId:nn.activeTurnId,scrollToTurn:nn.scrollToTurn,scrollToMessage:nn.scrollToMessage,resumeToBottom:rn}),fn=nt.showReadOnlyBanner?it:t?null:(0,$.jsx)(sT,{surface:s,scrollToBottom:an,showScrollToBottom:Pe&&nn.showScrollToBottom,onScrollToBottom:dn.resumeToLatest,submissionBlocked:nt.blockSubmission}),pn=q(e=>{dn.scrollToTurnId(e,{behavior:`smooth`})}),mn=nn.historySignals.canLoadEarlier,hn=h.promptNavigator&&!Pe&&!Ie&&!Be&&P&&nn.turnIds.length>=2;Z.useEffect(()=>{hn||g.getState().setPromptNavigatorPanelOpen(!1)},[hn]);let gn=q(e=>{if(!n||!r)return;let t=e;t.detail?.sessionId&&t.detail.sessionId!==r||Et(`instant`)});Jt(hH,gn,n&&r&&typeof window<`u`?window:gH);let _n=q(e=>{if(!n||!r||Be||e.defaultPrevented||e.isComposing||e.key!==`ArrowUp`&&e.key!==`ArrowDown`||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let{activeMainTab:t}=g.getState();if(t!==`chat`||FH())return;let i=Ct.current;if(PH(document.activeElement,i)||NH(e.target))return;e.preventDefault();let a=e.key===`ArrowUp`?-1:1;dn.scrollByTurnOffset(a,{resumePastEnd:!1})});Jt(`keydown`,_n,n&&r&&!Be&&typeof window<`u`?window:gH);let vn=Z.useRef(0),yn=q(()=>{let e=Ct.current;e&&e.style.setProperty(`--chat-scroll-height`,`${e.clientHeight}px`)}),bn=q(()=>{vn.current||=requestAnimationFrame(()=>{vn.current=0,yn()})});qt(()=>{n&&yn()},[n,r,Be,yn]);let xn=typeof ResizeObserver<`u`;Yt(n&&xn?Ct:null,bn),Jt(`resize`,bn,n&&!xn&&typeof window<`u`?window:gH),Wt(()=>{vn.current&&=(cancelAnimationFrame(vn.current),0)});let Sn=Z.useRef(null),Cn=Z.useRef(0),wn=ST({transcriptMessageCount:ie.length,pendingUserCount:le.length,historyPrefixCount:Lt.length}),Tn=CT({hasTranscriptShell:wn,p0Satisfied:pe.p0Satisfied,hasBusyShell:Ee&&wn,hasImmediateShell:le.length>0||Lt.length>0,hasRenderableSessionSnapshot:H,prefetchStatus:fe?.status,syncLoading:!!(r&&O.isLoading(r,{directory:A})),userRetrying:ge,hasPaintedTranscript:Xt});Tn===`pass`&&Ut.length>0&&(Gt.current=r);let En=!!r&&Tn===`hydrating`,Dn=!!r&&Tn===`load-error`;Z.useEffect(()=>{!Dn||!r||Ji(oa({kind:`request-error`,sessionID:r,directory:A,purpose:`load-failed`,source:`network`,request:fe?{sessionID:r,status:fe.status===`ready`?`ready`:fe.status,error:fe.error}:void 0,hydration:pe,error:fe?.error}))},[r,A,Dn,fe,pe]),Z.useEffect(()=>{if(!n||!r||En)return;let e=Ut.length,t=Sn.current!==r,i=!t&&Cn.current===0&&e>0;if(!t&&!i){Sn.current===r&&(Cn.current=e);return}let a=typeof window<`u`&&window.location.hash.length>0;if(Sn.current=r,Cn.current=e,a){Ot();return}let o=()=>{jt()};typeof window>`u`?o():window.requestAnimationFrame(o)},[n,r,En,Ot,jt,Ut.length]),Z.useEffect(()=>{K(e=>e.key===ne?e:{key:ne,attempt:0})},[ne]),Z.useEffect(()=>{if(!n||!r||G.key!==ne||!dH({sessionId:r,hasRenderableSessionSnapshot:H,hasCurrentSessionEntity:!!te})||(j(r),te||G.attempt>=2))return;let e=G.attempt+1,t=window.setTimeout(()=>{K(t=>t.key===ne&&t.attempt===G.attempt?{key:ne,attempt:e}:t)},e*1e3);return()=>window.clearTimeout(t)},[n,te,r,A,j,H,ne,G]);let On=w&&r&&(w.targetSessionId?r===w.targetSessionId:r===w.sourceSessionId)?w:null;if(On){let e=On.stage===`preparing`?`chat.forkTransition.preparing`:On.stage===`copying`?`chat.forkTransition.copying`:On.stage===`opening`?`chat.forkTransition.opening`:`chat.forkTransition.loading`,t=[`preparing`,`copying`,`opening`,`loading`],n=_(`chat.forkTransition.progress`,{current:Math.max(1,t.indexOf(On.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":`${_(e)}. ${n}`,children:[(0,$.jsxs)(`span`,{className:`typography-ui-header text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:_(e)}),(0,$.jsx)(U_,{})]}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground/70 tabular-nums`,children:n})]})})}if(!r&&!Re)return e&&!ze?(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)(jT,{})});if(!r&&Re){if((S||C)&&ae){let e=`draft:${b.draftID??`pending`}`;return(0,$.jsxs)(`div`,{ref:Ft,className:Y(`relative flex h-full flex-col bg-background`,Pe&&`oc-chat-composer-swap-scope`),children:[(0,$.jsx)(IH,{currentSessionId:e,virtualizerKey:e,isDesktopExpandedInput:!1,isMobile:Pe,stickyUserHeader:N,directory:A,scrollRef:Ct,messageListRef:He,pendingRevealWork:!1,initialPinRevealComplete:!0,renderedMessages:[ae],isLoadingOlder:!1,sessionIsWorking:!0,streamingMessageId:null,activeStreamingPhase:null,retryOverlay:null,handleMessageContentChange:wt,getAnimationHandlers:Tt,handleHistoryScroll:nn.handleHistoryScroll,handleHistoryUpwardIntent:on,onTimelineIsAtEndChange:St,timelineFollowSuspended:!1,timelineHistoryAnchorToken:yt,scrollToBottom:rn,sessionQuestions:[],sessionPermissions:[],isProgrammaticFollowActive:Nt,showLoadOlderButton:!1,onLoadOlder:un,turnIds:[],activeTurnId:null,onSelectTurn:pn,showPromptNavigator:!1,canLoadEarlierPrompts:!1,isLoadingOlderPrompts:!1,onLoadEarlierPrompts:un,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:_(`chat.emptyState.establishingConversation`)}),(0,$.jsx)(U_,{})]})})},e),(0,$.jsxs)(`div`,{className:Y(`invisible pointer-events-none relative z-10`,Pe&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,Be?`absolute inset-0 bg-background`:`bg-background`),"aria-hidden":`true`,children:[!Pe&&!Be?(0,$.jsx)(OH,{}):null,fn]}),(0,$.jsx)(mT,{})]})}return S||C?(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":_(`chat.emptyState.establishingConversation`),children:(0,$.jsxs)(`span`,{className:`typography-ui-header text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:_(`chat.emptyState.establishingConversation`)}),(0,$.jsx)(U_,{})]})})}):(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[Ve&&!Be?(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:zH(Ue?_(`chat.emptyState.draftTitleWithProject`,{project:Ue}):_(`chat.emptyState.draftTitle`),Ue)}),(0,$.jsx)(jx,{onSubmit:e=>Ja.getState().requestPresetSubmit(e),className:`oc-draft-starters mt-8 max-w-md`})]}):null,(0,$.jsx)(`div`,{className:Y(`relative z-10 flex min-h-0`,Pe&&`oc-mobile-composer-foot`,Be?`flex-1 bg-background`:Ve?Y(`bg-background`,`px-0`):`flex-1 items-center justify-center bg-background px-0 pb-[6vh]`),children:fn})]})}return r?Dn?(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[tt,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,Be?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":Be,children:Be?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:_(`chat.history.loadFailedTitle`)}),(0,$.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:_(`chat.history.loadFailedDescription`)}),(0,$.jsxs)(yo,{type:`button`,className:`mt-5`,onClick:_e,children:[(0,$.jsx)(X,{name:`refresh`,className:`size-4`,"aria-hidden":`true`}),_(`chat.history.retry`)]})]})})}),(0,$.jsx)(`div`,{className:Y(`relative z-10`,Pe&&`oc-mobile-composer-foot`,Be?`flex-1 min-h-0 bg-background`:`bg-background`),children:fn})]}):En?(0,$.jsxs)(`div`,{ref:Ft,className:Y(`relative flex flex-col h-full bg-background`,Pe&&`oc-chat-composer-swap-scope`),children:[tt,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,Be?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":Be,children:(0,$.jsx)(`div`,{ref:Ct,className:`absolute inset-0 overflow-y-auto overflow-x-hidden bg-background pt-6 chat-scroll`,style:EH,children:(0,$.jsx)(`div`,{className:`space-y-4 chat-scroll-foot-inset`,children:LH.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)(Lu,{className:`h-3.5 w-3.5 rounded-full flex-shrink-0`}),(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,t.titleWidth)}),(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,t.detailWidth)})]},`${e.id}-${t.id}`))}),(0,$.jsxs)(`div`,{className:`space-y-1.5 pt-1`,children:[(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,e.textWidths[0])}),(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,e.textWidths[1])}),(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,e.textWidths[2])})]})]})})},e.id))})})}),(0,$.jsxs)(`div`,{className:Y(`relative z-10`,Pe&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,Be?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Pe&&!Be?(0,$.jsx)(OH,{}):null,fn]})]}):Ut.length===0&&!Ee?(0,$.jsxs)(`div`,{className:`relative flex flex-col h-full bg-background`,children:[tt,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,Be?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":Be,children:Be?null:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,$.jsx)(jT,{})})}),(0,$.jsx)(`div`,{className:Y(`relative z-10`,Pe&&`oc-mobile-composer-foot`,Be?`flex-1 min-h-0 bg-background`:`bg-background`),children:fn}),(0,$.jsx)(mT,{})]}):(0,$.jsxs)(`div`,{ref:Ft,className:Y(`relative flex flex-col h-full bg-background`,Pe&&`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,tt,(0,$.jsx)(IH,{currentSessionId:r,virtualizerKey:a??r,isDesktopExpandedInput:Be,isMobile:Pe,stickyUserHeader:N,directory:A,scrollRef:Ct,messageListRef:He,pendingRevealWork:nn.pendingRevealWork,initialPinRevealComplete:se,renderedMessages:nn.renderedMessages,isLoadingOlder:cn,sessionIsWorking:Ee,streamingMessageId:R,activeStreamingPhase:z,retryOverlay:je,handleMessageContentChange:wt,getAnimationHandlers:Tt,handleHistoryScroll:nn.handleHistoryScroll,handleHistoryUpwardIntent:on,onTimelineIsAtEndChange:St,timelineFollowSuspended:_t,timelineHistoryAnchorToken:yt,scrollToBottom:rn,sessionQuestions:Te,sessionPermissions:we,isProgrammaticFollowActive:Nt,showLoadOlderButton:sn,onLoadOlder:un,turnIds:nn.turnIds,activeTurnId:nn.activeTurnId,onSelectTurn:pn,showPromptNavigator:hn,canLoadEarlierPrompts:mn,isLoadingOlderPrompts:cn,onLoadEarlierPrompts:un},r),(0,$.jsxs)(`div`,{className:Y(`relative z-10`,Pe&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,Be?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Pe&&!Be?(0,$.jsx)(OH,{}):null,!Be&&Ut.length>0&&(Pe?(0,$.jsx)(xb,{placement:`expanded`,visible:nn.showScrollToBottom,onClick:dn.resumeToLatest}):(0,$.jsx)(xb,{visible:nn.showScrollToBottom,onClick:dn.resumeToLatest})),fn]}),(0,$.jsx)(mT,{}),(0,$.jsx)(DV,{open:I,onOpenChange:L,sessionID:r??void 0,directory:A,onRevertMessage:u,onScrollToMessage:nn.scrollToMessage,onScrollByTurnOffset:dn.scrollByTurnOffset,onResumeToLatest:rn,canLoadEarlier:nn.historySignals.canLoadEarlier,isLoadingEarlier:cn,onLoadEarlier:un})]}):null});VH.displayName=`MemoizedChatContainerContent`;var HH=()=>{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)(Lu,{className:`h-4 w-4/5 animate-none rounded-md`}),(0,$.jsx)(Lu,{className:`h-4 w-2/3 animate-none rounded-md`}),(0,$.jsx)(Lu,{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)(Lu,{className:`h-4 w-5/6 animate-none rounded-md`}),(0,$.jsx)(Lu,{className:`h-4 w-3/5 animate-none rounded-md`})]}),(0,$.jsx)(Lu,{className:`h-24 w-full animate-none rounded-xl`})]})})}),e[1]=n):n=e[1],n},UH=({runtimeKey:e,...t})=>{let n=Cb(),r=Wi(),i=J(Qe(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),qt(()=>{!o||!i.draftPendingMessageId||(a.current={identity:o,messageId:i.draftPendingMessageId})},[o,i.draftPendingMessageId]);let s=J(e=>i.sessionId?e.retainedPendingUserMessages.get(i.sessionId)??pH:pH),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(()=>ZV(u),[u]),f=d.key,p=hr()||x()||n===`mini-chat`?wH:CH,[m,h]=Z.useState(()=>({activeIntent:d,cacheNeedsTrim:!1,cachedSessionViews:u?$V([],u,p,yH):[],pendingSessionView:null})),g=Z.useRef(d),_=Z.useRef(f),{cacheNeedsTrim:v,cachedSessionViews:y,pendingSessionView:b}=m,S=b?.intent===d?b.entry:null,C=Z.useMemo(()=>!u||!l?null:$V([],u,p,yH)[0]??null,[p,l,u]),w=Z.useMemo(()=>{let e=[...y];return S&&!e.some(e=>e.key===S.key)&&e.push(S),C&&!e.some(e=>e.key===C.key)&&e.push(C),e.sort((e,t)=>e.key.localeCompare(t.key))},[y,C,S]),T=tH(w,f),E=!!(f&&!T);qt(()=>{g.current=d,_.current=f,h(e=>{let t=nH(e,d,p);return l?rH(t,d,d,yH):t})},[p,v,l,d,f]);let D=b?.intent??null;qt(()=>{D&&h(e=>iH(e,D,p))},[p,D]),Z.useEffect(()=>{if(!d.selection||T)return;let e=d,t=f;return Kl(()=>{g.current===e&&_.current===t&&h(n=>_.current===t?rH(n,e,g.current,yH):n)},{priority:`user-blocking`})},[T,p,d,f]);let O=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=eH(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":E||void 0,children:[E?(0,$.jsx)(HH,{},f):null,w.map(e=>(0,$.jsx)(Z.Activity,{name:`chat-session-${e.sessionId}`,mode:T===e.key?`visible`:`hidden`,children:(0,$.jsx)(VH,{...t,sessionId:e.sessionId,sessionDirectory:e.directory,sessionViewKey:e.key,onSessionViewEstimateChange:O,committedDraftHandoffMessageId:T===e.key?l:null})},e.key)),f?null:(0,$.jsx)(VH,{...t,sessionId:null,sessionDirectory:i.directory})]})},WH=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=TT(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)(VH,{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)(Ry.Provider,{value:u,children:f}),t[21]=u,t[22]=f,t[23]=p):p=t[23],p},GH=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=Wi(),o=n.directory??a,s;t[4]!==o||t[5]!==n?(s=Ly({...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)(VH,{...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)(Ry.Provider,{value:c,children:u}),t[13]=c,t[14]=u,t[15]=d):d=t[15],d},KH=e=>{let t=(0,Q.c)(14),n=Z.useSyncExternalStore(TH,s,s);if(e.host){let r=`${n}:${e.host.sessionSurface.surfaceId}`,i;return t[0]!==e||t[1]!==n||t[2]!==r?(i=(0,$.jsx)(WH,{...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)(GH,{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)(UH,{...e,runtimeKey:n},n),t[11]=e,t[12]=n,t[13]=r):r=t[13],r},qH=(e,t)=>nn(tn.getState().dictionary,e,t),JH=e=>{let t=new Date(e),n=new Date,r=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),i=new Date(n);return i.setDate(n.getDate()-1),r(t,n)?qH(`common.date.today`):r(t,i)?qH(`common.date.yesterday`):t.toLocaleDateString(Qt(),{month:`short`,day:`numeric`,year:`numeric`}).replace(`,`,``)},YH=e=>{let t=new Date;if(((e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate())(new Date(e),t)){let t=Date.now()-e;return t<6e4?qH(`common.relative.justNow`):t<36e5?qH(`common.relative.minutesAgoShort`,{count:Math.floor(t/6e4)}):qH(`common.relative.hoursAgoShort`,{count:Math.floor(t/36e5)})}return JH(e)},XH=e=>{let t=Math.max(0,Date.now()-e),n=6e4,r=60*n,i=24*r,a=7*i,o=365*i;return t<r?qH(`common.relative.minutesAgoCompact`,{count:Math.max(1,Math.floor(t/n))}):t<i?qH(`common.relative.hoursAgoCompact`,{count:Math.floor(t/r)}):t<a?qH(`common.relative.daysAgoCompact`,{count:Math.floor(t/i)}):t<5*a?qH(`common.relative.weeksAgoCompact`,{count:Math.floor(t/a)}):t<o?qH(`common.relative.monthsAgoCompact`,{count:Math.floor(t/2592e6)}):qH(`common.relative.yearsAgoCompact`,{count:Math.floor(t/o)})},ZH=(e,t)=>QH(b(e),b(t)),QH=(e,t)=>!e||!t?!1:e===t?!0:t===`/`?e.startsWith(`/`):e.startsWith(`${t}/`),$H=e=>e.toLowerCase().replace(/^opencode[/-]?/i,``).replace(/[-_]/g,``).trim(),eU=(e,t)=>e?$H(e)!==$H(t):!1,tU=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim().length>0){let t=Number(e);if(Number.isFinite(t))return t}},nU=e=>tU(e.time?.created)??0,rU=(e,t,n)=>{let r=n.has(e.id),i=n.has(t.id);return r===i?r&&i?nU(t)-nU(e):oi(t)-oi(e):r?-1:1},iU=e=>{let t=new Map;return e.forEach(e=>{t.set(e.id,e)}),Array.from(t.values())},aU=e=>`__archived__:${e}`,oU=(e,t)=>{let n=b(e.directory??null),r=b(e.project?.worktree??null),i=n??r;if(!i)return`unassigned`;if(t&&i===t)return`project root`;let a=(t&&i.startsWith(`${t}/`)?i.slice(t.length+1):i).split(`/`).filter(Boolean);return a[a.length-1]??`unassigned`},sU=`box-border w-full px-2 py-1.5 text-left typography-micro text-muted-foreground/70 select-none`,cU=`bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)] dark:bg-[color-mix(in_srgb,var(--surface-foreground)_11%,transparent)]`,lU=`hover:bg-[color-mix(in_srgb,var(--surface-foreground)_3.5%,transparent)] dark:hover:bg-[color-mix(in_srgb,var(--surface-foreground)_8%,transparent)]`,uU=e=>{let t=Math.max(0,e);return t===0?8:30+(t-1)*14},dU=(e,t)=>{if(!t)return e;let n=e.toLowerCase(),r=t.toLowerCase(),i=r.length;if(i===0)return e;let a=[],o=0,s=n.indexOf(r,o);for(;s!==-1;){s>o&&a.push(e.slice(o,s));let t=e.slice(s,s+i);a.push((0,$.jsx)(`mark`,{className:`bg-primary text-primary-foreground ring-1 ring-primary/90`,children:t},`${s}-${t}`)),o=s+i,s=n.indexOf(r,o)}return o<e.length&&a.push(e.slice(o)),a.length>0?a:e},fU=2e4,pU=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus()?`visible`:`hidden`,mU=e=>{if(!oe()&&!wt())return;let t=je();t?.push?.setVisibility&&t.push.setVisibility({visible:e,platform:Tt()})},hU=e=>{let t=e?.enabled??!0;Z.useEffect(()=>{if(!t||!oe()&&!wt()||typeof window>`u`)return;if(wt()){let e=!0,t=!1,n=null,r=()=>mU(e);kt(async()=>{let{App:e}=await import(`./vendor-capacitor-app-PzT84wSx.js`).then(e=>e.t);return{App:e}},__vite__mapDeps([51,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&&mU(!0)},fU);return()=>{t=!0,window.clearInterval(i),n?.()}}if(typeof document>`u`)return;let e=()=>{mU(pU()===`visible`)},n=()=>{pU()===`visible`&&mU(!0)},r=()=>{mU(!1)};e();let i=window.setInterval(n,fU);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])},gU=`OpenChamber`,_U=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``).split(`/`).filter(Boolean);return t[t.length-1]??``},vU=(e,t)=>[e,t,gU].filter(e=>typeof e==`string`&&e.trim().length>0).join(` | `),yU=()=>{let e=Gi(e=>e.activeProjectId?e.projects.find(t=>t.id===e.activeProjectId)??null:null),t=Z.useMemo(()=>e&&_U(e.path)||null,[e]),[r,i]=Z.useState(null);Z.useEffect(()=>{if(typeof window>`u`||!H()){i(null);return}let e=!1,t=async()=>{try{if(U()){e||i(null);return}let t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,r=n();if(r&&Re(r,t)){e||i(null);return}let a=(await Ke()).hosts.find(e=>r?Re(r,Ve(e)):!1),o=a?.label?.trim()?ze(a.label.trim()):`Instance`;e||i(o)}catch{e||i(`Instance`)}};t();let r=()=>{t()};return window.addEventListener(`focus`,r),()=>{e=!0,window.removeEventListener(`focus`,r)}},[]);let a=Z.useMemo(()=>vU(t,r),[t,r]);Z.useEffect(()=>{typeof document<`u`&&(document.title=a),H()&&(async()=>{try{if(typeof navigator<`u`&&/Macintosh|Mac OS X/.test(navigator.userAgent||``))return;await Xt(a)}catch{return}})()},[a])},bU=()=>{let e=J.getState().currentSessionId;if(!e)return``;let t=Da().find(t=>t.id===e);return typeof t?.directory==`string`?t.directory:``},xU=async(e,t=6e3)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t),i=Date.now();try{let t=await pe(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)}},SU=e=>{if(!e||!Number.isFinite(e))return`(n/a)`;try{return new Date(e).toISOString()}catch{return`(invalid)`}},CU=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},wU=e=>!!e&&typeof e==`object`&&!Array.isArray(e),TU=(e,t=`(n/a)`)=>typeof e==`string`?e.trim()||t:typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`boolean`?e?`true`:`false`:t,EU=(e,t,n)=>e===`node-shebang`||e===`node-launcher`?t?`node (${t})`:`node`:e===`bun-shebang`?n?`bun (${n})`:`bun`:e||`direct executable`,DU=async()=>{let e=new Date,t=typeof navigator<`u`?navigator.userAgent:`(no navigator)`,n=bU(),r=g.getState().eventStreamStatus,i=typeof window<`u`?window.location.origin:``,a=o(),s=a.health(),c=a.api(`/api/`),l=await(async()=>{if(!s)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),5e3);try{let t=await pe(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 pe(a.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()},f=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 xU(t,typeof e.timeoutMs==`number`?e.timeoutMs:void 0);return{label:e.label,url:t,result:n}})):[],p=[];p.push(`Time: ${e.toISOString()}`),p.push(`OpenChamber version: 1.19.7-beta.21`),p.push(`Runtime: ${i||`(unknown)`} (api=${c||`(unknown)`})`),p.push(`OpenCode SDK base: ${mt.getBaseUrl()}`),p.push(`Event stream: ${r}`),p.push(`Directory: ${n||`(none)`}`),p.push(`Platform: ${t}`);let m=CU(l?.openCodePort);if(p.push(`OpenCode runtime port: ${m??`(unknown)`}`),typeof l?.openCodeRunning==`boolean`&&p.push(`OpenCode runtime running: ${l.openCodeRunning?`yes`:`no`}`),typeof l?.openCodeSecureConnection==`boolean`&&p.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?`true`:`false`}`),typeof l?.openCodeAuthSource==`string`&&l.openCodeAuthSource.trim()&&p.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<`u`){let e=window.__OPENCHAMBER_MACOS_MAJOR__;typeof e==`number`&&Number.isFinite(e)&&e>0&&p.push(`macOS major: ${e}`)}if(/Mac OS X|Macintosh/.test(t)){p.push(``),p.push(`OpenCode CLI resolution:`);let e=wU(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:``,m=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&&p.push(`- configured: ${r.trim().length===0?`(cleared)`:r}`),i){let e=a||(i.includes(`/`)?i.split(`/`).slice(0,-1).join(`/`)||`/`:``);p.push(`- opencode: ${i}${e?` (dir=${e})`:``}`)}else p.push(`- opencode: (n/a)`);p.push(`- source: ${o||`(n/a)`}`),h&&(p.push(`- detected-now: ${h}`),p.push(`- detected-source: ${g||`(n/a)`}`)),e?(p.push(`- launched-at: ${TU(e.launchedAt)}`),p.push(`- launch: ${TU(e.binary)} ${t.join(` `)}`.trim()),p.push(`- cwd: ${TU(e.cwd)}`),p.push(`- wrapper: ${TU(e.wrapperType)}`),p.push(`- runtime: ${EU(TU(e.wrapperType,``),f,m)}`),p.push(`- PATH entries: ${TU(e.pathEntryCount,`(unknown)`)}`),p.push(`- shell env: ${TU(e.hasShellEnv,`(unknown)`)} (${TU(e.shellEnvKeysCount,`?`)} keys)`)):(p.push(`- launch-binary: ${s||`(n/a)`}`),p.push(`- launch-wrapper: ${c||`(n/a)`}`),p.push(`- launch-args: ${d.length?d.join(` `):`(none)`}`),p.push(`- runtime: ${EU(c||``,f,m)}`)),!n&&u.error&&p.push(`- resolution-endpoint: ${u.error}`)}if(p.push(``),f.length){p.push(`OpenCode API probes:`);for(let e of f){if(!e.result){p.push(`- ${e.label}: (no url)`);continue}let{ok:t,status:n,elapsedMs:r,summary:i}=e.result,a=t?``:` url=${e.url}`;p.push(`- ${e.label}: ${t?`ok`:`fail`} status=${n} time=${r}ms ${i}${a}`)}}else p.push(`OpenCode API probes: (skipped)`);return p.push(``),p.push(`Generated: ${SU(Date.now())}`),p.join(`
6585
+ `)}function GR(e,t=80){let n=WR(e).replace(/\n/g,` `);return n.length>t?`${n.slice(0,t)}…`:n}var KR=160,qR=28,JR=12,YR=6,XR=30,ZR=12,QR=18,$R=80,ez=4,tz=10,nz=14,rz=20,iz=54,az=4,oz=8,sz=2,cz=160,lz=(e,t)=>e.map(e=>({turnId:e,preview:GR(t.get(e)??[],KR)})),uz=[1,.6,.35,.15],dz=(e,t,n)=>{let r=n?nz:tz;if(t===null)return r;let i=uz[Math.abs(e-t)]??0;return Math.round(r+(rz-r)*i)};function fz({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:i,isLoadingOlder:a,onLoadEarlier:o}){let{t:s}=Zt(),c=g(e=>e.isPromptNavigatorPanelOpen),l=g(e=>e.setPromptNavigatorPanelOpen),u=Z.useRef(null),d=Z.useRef(null),[f,p]=Z.useState(null),[m,h]=Z.useState(0),[_,v]=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){v(!1);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=n.right-YR-qR;v(r.right>i)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let y=Z.useMemo(()=>lz(e,t),[t,e]),b=Math.min(y.length,XR),x=Math.max(0,y.length-b),S=Math.min(m,x),C=S+b,w=S>0,T=C<y.length,E=s(`chat.timeline.noTextContent`),D=s(`chat.promptNavigator.currentPrompt`),O=s(`chat.promptNavigator.loadMore`),k=Z.useMemo(()=>n?y.findIndex(e=>e.turnId===n):-1,[n,y]),A=Z.useRef(S);A.current=S;let j=Z.useRef(y.length);j.current=y.length;let M=Z.useRef(null),N=Z.useRef(null),P=Z.useRef(0),F=Z.useCallback(e=>{h(t=>{let n=j.current,r=Math.min(n,XR),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})},[]),I=Z.useRef(y[0]?.turnId),L=Z.useRef(y.length);Z.useLayoutEffect(()=>{let e=I.current,t=L.current,n=y.length-t;n>0&&t>0&&e&&y[0]?.turnId!==e&&(h(e=>e+n),p(e=>e===null?null:e+n)),I.current=y[0]?.turnId,L.current=y.length},[y]),Z.useEffect(()=>{if(f!==null)return;let e=k>=0?k:y.length-1;h(()=>{let t=j.current,n=Math.min(t,XR),r=Math.max(0,t-n);return Math.max(0,Math.min(r,e-Math.floor(n/2)))})},[k,f,y.length]);let R=Z.useCallback(e=>{let t=u.current;if(!t)return null;let n=t.getBoundingClientRect(),r=Math.floor((e-n.top)/ZR),i=Math.min(j.current,XR);return i===0?null:Math.max(0,Math.min(i-1,r))},[]),z=Z.useCallback(()=>{P.current=0,N.current!==null&&(window.clearInterval(N.current),N.current=null)},[]),B=Z.useCallback(()=>{let e=P.current;if(e===0){z();return}let t=j.current,n=Math.max(0,t-Math.min(t,XR)),r=Math.min(A.current,n),i=Math.max(0,Math.min(n,r+e));if(i===r){z();return}A.current=i,h(i);let a=M.current;if(a!==null){let e=R(a);e!==null&&p(Math.min(t-1,i+e))}},[R,z]),V=Z.useCallback(e=>{let t=u.current;if(!t)return;let n=t.getBoundingClientRect(),r=e-n.top,i=0;if(r<=QR&&w?i=-1:r>=n.height-QR&&T&&(i=1),P.current=i,i===0){z();return}N.current===null&&(N.current=window.setInterval(B,$R))},[B,w,T,z]);Z.useEffect(()=>()=>{N.current!==null&&window.clearInterval(N.current)},[]);let H=Z.useRef(null),ee=Z.useCallback(()=>{H.current!==null&&(window.clearTimeout(H.current),H.current=null)},[]),U=Z.useCallback(()=>{ee(),H.current=window.setTimeout(()=>{H.current=null,p(null)},cz)},[ee]);Z.useEffect(()=>()=>{H.current!==null&&window.clearTimeout(H.current)},[]);let te=Z.useCallback(e=>{ee(),M.current=e.clientY;let t=R(e.clientY);t!==null&&p(Math.min(j.current-1,A.current+t)),V(e.clientY)},[ee,R,V]),W=Z.useCallback(()=>{M.current=null,z(),U()},[U,z]),ne=Z.useCallback(()=>{l(!1)},[l]),G=Z.useCallback(e=>{if(e===null)return;let t=y[e];t&&(r(t.turnId),z(),p(null),ne(),u.current?.blur())},[ne,r,y,z]),K=Z.useCallback(e=>{let t=R(e.clientY);t!==null&&G(Math.min(y.length-1,A.current+t))},[G,y.length,R]);Z.useEffect(()=>{if(!c)return;let e=u.current;!e||e===document.activeElement||(e.focus(),p(e=>{if(e!==null)return e;let t=k>=0?k:y.length-1;return F(t),t}))},[k,F,c,y.length]),Z.useEffect(()=>()=>{l(!1)},[l]);let re=Z.useCallback(e=>{if(y.length===0)return;let t=f??(k>=0?k:y.length-1),n=e=>{let t=Math.max(0,Math.min(y.length-1,e));F(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(y.length-1);return}if(e.key===`Enter`||e.key===` `){e.preventDefault(),G(t);return}e.key===`Escape`&&(e.preventDefault(),p(null),ne(),u.current?.blur())},[k,ne,F,G,f,y.length]),ie=Z.useCallback(()=>{z(),p(null),ne()},[ne,z]),ae=Z.useRef(null),oe=Z.useRef(f);oe.current=f;let se=f!==null,ce=Z.useRef(0);Z.useEffect(()=>{let e=ae.current;if(!e)return;let t=e=>{e.preventDefault(),e.stopPropagation(),ce.current+=e.deltaY;let t=Math.trunc(ce.current/iz);if(t===0)return;ce.current-=t*iz;let n=oe.current;if(n===null)return;let r=Math.max(0,Math.min(j.current-1,n+t));r!==n&&(F(r),p(r))};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[F,se]);let le=f===null?void 0:y[f],ue=Math.min(y.length,oz),de=ue*iz,fe=y.length*iz-de,pe=e=>Math.max(0,Math.min(fe,e)),me=Z.useRef(null),he=0;if(f===null)me.current=null;else if(me.current===null)he=pe(f*iz-(de-iz)/2),me.current=he;else{let e=me.current,t=(f-sz)*iz,n=(f+1+sz)*iz-de;e>t?e=t:e<n&&(e=n),he=pe(e),me.current=he}let ge=Math.floor(he/iz),_e=Math.max(0,ge-ez),ve=Math.min(y.length,ge+ue+ez),ye=he>0,be=he<fe,xe=ye||be?`linear-gradient(to bottom, ${ye?`transparent, black 10%`:`black`}, ${be?`black 90%, transparent`:`black`})`:void 0,Se=Math.max(0,S-ez),Ce=Math.min(y.length,C+ez),we=y.slice(Se,Ce),Te=w||T?`linear-gradient(to bottom, ${w?`transparent, black 14%`:`black`}, ${T?`black 86%, transparent`:`black`})`:void 0;return y.length===0?null:(0,$.jsx)(`nav`,{ref:d,"aria-label":s(`chat.promptNavigator.aria`),className:`pointer-events-none absolute right-1.5 top-1/2 z-20 -translate-y-1/2`,children:(0,$.jsxs)(`div`,{className:`pointer-events-auto flex flex-col items-end`,children:[i?(0,$.jsx)(`button`,{type:`button`,tabIndex:-1,className:Y(`-mr-px mb-1.5 flex size-5 shrink-0 items-center justify-center rounded-full`,`text-[var(--surface-mutedForeground)] transition-colors`,`hover:bg-[var(--interactive-hover)]/60 hover:text-[var(--surface-foreground)]`,a?`cursor-wait opacity-70`:void 0),"aria-label":O,title:O,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":le?`prompt-rail-tick-${le.turnId}`:void 0,className:`relative cursor-pointer outline-none`,style:{width:`${_?JR:qR}px`,height:`${b*ZR}px`},onMouseMove:te,onMouseLeave:W,onClick:K,onKeyDown:re,onBlur:ie,children:[(0,$.jsx)(`div`,{className:`absolute inset-0 overflow-hidden`,style:Te?{maskImage:Te,WebkitMaskImage:Te}:void 0,children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-300 ease-out`,style:{transform:`translateY(-${S*ZR}px)`},children:we.map((e,t)=>{let r=Se+t,i=e.turnId===n,a=f===r,o=dz(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()||E,className:`pointer-events-none absolute right-1 flex items-center justify-end`,style:{top:`${r*ZR}px`,height:`${ZR}px`},children:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:Y(`block h-0.5 rounded-full transition-all duration-200 ease-out`,i?`bg-[var(--surface-foreground)]`:a?`bg-[var(--surface-foreground)]/80`:`bg-[var(--surface-foreground)]/30`),style:{width:`${o}px`}})},e.turnId)})},y[0]?.turnId)}),le&&f!==null?(0,$.jsx)(`div`,{ref:ae,className:Y(`pointer-events-auto absolute right-full top-1/2 z-30 mr-3 -translate-y-1/2`,`w-[min(20rem,calc(100vw-6rem))] overflow-hidden rounded-xl`,`border border-[var(--interactive-border)]/60 bg-[var(--surface-elevated)] py-1 shadow-md`),onMouseEnter:ee,onMouseLeave:U,onMouseMove:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:(0,$.jsx)(`div`,{className:`relative overflow-hidden`,style:{height:`${ue*iz}px`,maskImage:xe,WebkitMaskImage:xe},children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-200 ease-out`,style:{height:`${y.length*iz}px`,transform:`translateY(-${he}px)`},children:y.slice(_e,ve).map((e,t)=>{let r=_e+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?D:void 0,className:`absolute inset-x-0 cursor-pointer px-1.5`,style:{top:`${r*iz+az}px`,height:`46px`},onMouseMove:()=>{ee(),oe.current!==r&&(F(r),p(r))},onClick:()=>G(r),children:(0,$.jsx)(`div`,{className:Y(`flex h-full items-center rounded-lg border px-2 transition-colors`,i?`border-transparent bg-[var(--interactive-selection)]`:a?`border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]`:`border-[var(--interactive-border)]/40`),children:(0,$.jsx)(`span`,{className:Y(`min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] typography-meta`,i?`text-[var(--interactive-selectionForeground)]`:`text-[var(--surface-mutedForeground)]`),children:e.preview.trim()||E})})},e.turnId)})})})}):null]})]})})}var pz=100,mz=(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},hz=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=mz(p,t.scrollTop+pz);!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}},gz=10,_z=`${gz}vh`,vz=`80px`,yz=`calc(${vz} + var(--oc-chat-foot-inset))`,bz=(e,t)=>e?80:t<=0?96:Math.max(48,gz/100*t),xz=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return!1;switch(e.key){case`ArrowUp`:case`PageUp`:case`Home`:return!0;default:return!1}},Sz=(e,t)=>{let n=t instanceof Element?t:t instanceof Node?t.parentElement:null;for(;n&&n!==e;){if(n instanceof HTMLElement&&n.scrollTop>0&&n.scrollHeight>n.clientHeight+1)return!0;n=n.parentElement}return!1},Cz=e=>{let t=(0,Q.c)(15),{scrollRef:n,enabled:r,onUpwardIntent:i}=e,a=r===void 0||r,o=Z.useRef(null),s;t[0]===i?s=t[1]:(s=()=>{i()},t[0]=i,t[1]=s);let c=q(s),l;t[2]!==c||t[3]!==n?(l=e=>{let t=n.current;t&&(e.deltaY>=0||t instanceof HTMLElement&&(Sz(t,e.target)||c()))},t[2]=c,t[3]=n,t[4]=l):l=t[4];let u=q(l),d;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(d=e=>{let t=e.touches.item(0);o.current=t?t.clientY:null},t[5]=d):d=t[5];let f=q(d),p;t[6]!==c||t[7]!==n?(p=e=>{let t=n.current,r=e.touches.item(0);if(!r){o.current=null;return}let i=o.current;o.current=r.clientY,i!==null&&(r.clientY-i<=2||!t||!(t instanceof HTMLElement)||Sz(t,e.target)||c())},t[6]=c,t[7]=n,t[8]=p):p=t[8];let m=q(p),h;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(h=()=>{o.current=null},t[9]=h):h=t[9];let g=q(h),_;t[10]===c?_=t[11]:(_=e=>{xz(e)&&c()},t[10]=c,t[11]=_);let v=q(_),[y,b]=Z.useState(null),x;t[12]===n?x=t[13]:(x=()=>{let e=n.current??null;b(t=>t===e?t:e)},t[12]=n,t[13]=x),Z.useEffect(x);let S=a&&y?y:wz,C;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(C={passive:!0},t[14]=C):C=t[14];let w=C;Jt(`wheel`,u,S,w),Jt(`touchstart`,f,S,w),Jt(`touchmove`,m,S,w),Jt(`touchend`,g,S,w),Jt(`touchcancel`,g,S,w),Jt(`keydown`,v,S)};function wz(){}var Tz=(e,t)=>({sessionId:e,viewportKey:t}),Ez=(e,t)=>e?.sessionId===t?.sessionId&&e?.viewportKey===t?.viewportKey,Dz=(e,t)=>Ez(e,t),Oz=(e,t,n)=>({identity:e,anchor:t,scrollPosition:n}),kz=150,Az=1500,jz=2,Mz=350,Nz=600,Pz=8e3,Fz=24,Iz=2,Lz=(e,t)=>e<t,Rz=()=>typeof performance<`u`?performance.now():Date.now(),zz=e=>({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}),Bz=e=>e.scrollHeight-e.scrollTop-e.clientHeight,Vz=e=>Bz(zz(e)),Hz=e=>e.scrollHeight-e.clientHeight>1,Uz=(e,t)=>Bz(e)<=bz(t,e.clientHeight),Wz=({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(Tz(t,n));C.current=Tz(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=Rz()+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=Xa(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:Rz()},E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{T.current=null,E.current=null},Az)}),G=q(e=>{let t=T.current;return t?Rz()-t.time>Az?(T.current=null,!1):Math.abs(e.scrollTop-t.top)<jz:!1}),K=q(()=>Rz()<A.current),re=q(()=>{L.current=!1,R.current&&=(clearTimeout(R.current),null),z.current&&=(clearTimeout(z.current),null)}),ie=q(()=>{R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{R.current=null,re()},Nz)}),ae=q(()=>{let e=c.current;e&&(L.current=!0,B.current=e.scrollHeight,ie(),z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{z.current=null,re()},Pz))}),oe=q(e=>{let t=c.current;if(!t){h(!1),_(!1);return}let n=e??zz(t),r=Hz(n);if(h(r),!r){_(!1);return}let i=b.current===`released`&&!Uz(n,x.current);_(i)}),se=q(()=>{D.current+=1,O.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(O.current),O.current=null),k.current?.(),k.current=null});Z.useEffect(()=>()=>se(),[l]);let ce=q(()=>{if(!e)return;let t=c.current;if(!t)return;se();let n=D.current,r=t.style.overflow,i=t.style.scrollBehavior;t.style.scrollBehavior=`auto`,t.style.overflow=`hidden`,t.scrollTop=t.scrollHeight,t.scrollHeight,t.style.overflow=r,t.style.scrollBehavior=i;let a=()=>{ne(t),t.scrollTop=t.scrollHeight,I.current=t.scrollTop};if(a(),oe(),typeof window>`u`)return;let o=0,s=()=>{Lz(Rz(),P.current)||se()};t.addEventListener(`touchstart`,s,{passive:!0,once:!0}),k.current=()=>t.removeEventListener(`touchstart`,s);let l=()=>{if(n===D.current){if(Vz(t)>Iz&&a(),o+=1,o>=Fz){O.current=null,k.current?.(),k.current=null,oe();return}O.current=window.requestAnimationFrame(l)}};O.current=window.requestAnimationFrame(l)}),le=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}}),ue=q((t,n=`auto`)=>{if(!e)return;let r=c.current;if(t&&b.current!==`following`&&W(`following`),r&&!(!t&&b.current!==`following`)){if(Vz(r)<jz){ne(r);return}le(t?n:`auto`)}}),de=q(e=>{let t=c.current;if(!t)return;let n=e??zz(t);if(!Hz(n)){W(`following`);return}b.current!==`released`&&(W(`released`),oe(n))}),fe=q((e=`instant`)=>{if(V.current=!1,W(`following`),re(),e===`instant`){ce();return}se(),ue(!0,`smooth`),oe()}),pe=q(()=>{V.current=!1,ue(!0)}),me=q(()=>{se(),re(),W(`released`),oe()}),he=q(()=>{V.current=!0,me()}),ge=q(()=>{V.current=!1}),_e=Z.useRef(s);_e.current=s;let ve=q(()=>{Lz(Rz(),P.current)||(se(),re(),de())}),ye=q(()=>{ve(),_e.current?.()}),be=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}}),xe=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=Oz(e,o,{scrollTop:n,scrollHeight:r,clientHeight:i}),H.current===null&&(H.current=setTimeout(()=>{H.current=null,be()},kz))}),Se=q(()=>{be()}),Ce=q(async(e=C.current)=>{if(!e.sessionId)return!1;V.current=!1;let t=vi(e.sessionId,e.viewportKey);return c.current?(U.current=null,I.current=t?.scrollPosition?.scrollTop??0,W(`following`),F(),x.current?ce():ue(!0),ae(),oe(),!1):(U.current=e,W(`following`),!1)});Z.useEffect(()=>{let e=C.current,n=w.current;Ez(e,n)||(be(),se(),F(),w.current=e,T.current=null,I.current=0,re(),V.current=!1,W(`following`),U.current=null,t&&t!==n?.sessionId&&NT.getInstance().recordSessionStart(t))},[t,n]),Z.useEffect(()=>{i&&!V.current&&b.current===`following`&&ue(!0)},[i]),Z.useEffect(()=>{y(f===`following`&&i)},[f,i]),Z.useLayoutEffect(()=>{if(!l)return;let e=U.current;e&&Dz(e,C.current)&&Ce(e)},[l,t,n]);let we=q(()=>{let e=c.current;if(!e)return;let t=zz(e),n=I.current;I.current=t.scrollTop;let r=t.scrollTop>n+.5,i=Math.abs(t.scrollTop-n)<.5;if(oe(t),V.current){xe();return}if(!Hz(t)){W(`following`);return}if(Uz(t,x.current)){let e=Bz(t)<=jz;(r||b.current===`following`||e)&&W(`following`),xe();return}if(b.current===`following`&&(G(e)||K()||i)){j.current||ue(!1),xe();return}de(t),xe()});Z.useEffect(()=>{!e||!l||(I.current=l.scrollTop)},[l,e]);let Te=Z.useRef(null),Ee=q(e=>{let t=c.current;t&&(e.deltaY>=0||Sz(t,e.target)||ye())}),De=q(e=>{let t=e.touches.item(0);Te.current=t?t.clientY:null}),Oe=q(e=>{let t=c.current,n=e.touches.item(0);if(!n){Te.current=null;return}let r=Te.current;Te.current=n.clientY,r!==null&&(n.clientY-r<=2||t&&(Sz(t,e.target)||ye()))}),ke=q(()=>{Te.current=null}),Ae=q(e=>{xz(e)&&ye()}),je=q(e=>{let t=e.target;t instanceof Element&&t.closest(`[data-overlay-scrollbar-thumb]`)&&ve()}),Me=Z.useMemo(()=>()=>void 0,[]),Ne=e&&l?l:Me,Pe=Z.useMemo(()=>({passive:!0}),[]);Jt(`scroll`,we,Ne,Pe),Jt(`wheel`,Ee,Ne,Pe),Jt(`touchstart`,De,Ne,Pe),Jt(`touchmove`,Oe,Ne,Pe),Jt(`touchend`,ke,Ne,Pe),Jt(`touchcancel`,ke,Ne,Pe),Jt(`keydown`,Ae,Ne),Jt(`pointerdown`,je,e&&typeof window<`u`?window:Me,!0);let Fe=q(()=>{let e=c.current;if(j.current){oe(e?zz(e):void 0);return}if(V.current){oe(e?zz(e):void 0);return}if(!e){oe(void 0);return}let t=zz(e);if(!Hz(t)){W(`following`),oe(t);return}if(oe(t),L.current){let n=t.scrollHeight>B.current+1;B.current=t.scrollHeight,Bz(t)<=jz?ne(e):ue(!0),n&&ie();return}if(b.current===`following`){if(Bz(t)<=jz){ne(e);return}ue(!1)}}),Ie=typeof ResizeObserver<`u`,Le=Ie&&e?l:null,Re=Ie&&e&&l&&l.firstElementChild instanceof Element?l.firstElementChild:null;Yt(Le,Fe),Yt(Re,Fe);let ze=q(()=>{N.current!==null&&(clearTimeout(N.current),N.current=null)}),Be=q(e=>{j.current=!0,typeof e==`number`&&e>0?A.current=Rz()+e+Mz:A.current=Math.max(A.current,Rz()+Mz)}),Ve=q(e=>{let t=e.detail;if(t){if(t.open===!0){Be(),ze(),N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},1500);return}ze(),Be()}}),He=q(e=>{let t=e.detail;t&&(ze(),Be(t.durationMs))}),Ue=q(e=>{let t=e.detail;ze(),t?.open===!0?(M.current=!0,j.current=!0):(M.current=!1,j.current=!0,N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},Mz)),oe()}),We=e&&typeof window<`u`?window:Me;Jt(`oc:keyboard-intent`,Ve,We),Jt(`oc:keyboard-anim`,He,We),Jt(`oc:keyboard-settled`,Ue,We),Z.useEffect(()=>{if(!(!e||typeof window>`u`))return()=>{ze(),j.current=!1,M.current=!1}},[e]),Z.useEffect(()=>{e&&oe()},[e,r]);let Ge=q(t=>{if(e){if(t===`animation`&&(A.current=Rz()+Mz),oe(),L.current){ue(!0),ie();return}b.current===`following`&&ue(!1)}}),Ke=Z.useRef(new Map),qe=q(t=>{let n=Ke.current.get(t);if(n)return n;let r=()=>{e&&b.current===`following`&&ue(!1)},i={onChunk:r,onComplete:()=>{e&&oe()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:r,onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return Ke.current.set(t,i),i});Z.useEffect(()=>()=>{E.current&&=(clearTimeout(E.current),null),se(),re(),be(),H.current!==null&&(clearTimeout(H.current),H.current=null)},[]);let Je=q(e=>{o?.(e)}),Ye=!!o;return Z.useEffect(()=>{if(!e||!Ye)return;let t=l;if(!t)return;let n=null,r=hz({onActive:e=>{e!==n&&(n=e,Je(e))}});r.setContainer(t);let i=new Map,a=e=>{let t=e.dataset.turnId;return t?(i.set(t,e),r.register(e,t),!0):!1},o=e=>{let t=e.dataset.turnId;return!t||i.get(t)!==e?!1:(i.delete(t),r.unregister(t),!0)},s=e=>{if(!(e instanceof HTMLElement))return[];let t=[];return e.matches(`[data-turn-id]`)&&t.push(e),e.querySelectorAll(`[data-turn-id]`).forEach(e=>t.push(e)),t};t.querySelectorAll(`[data-turn-id]`).forEach(a),r.markDirty();let c=new MutationObserver(e=>{let t=!1;e.forEach(e=>{e.removedNodes.forEach(e=>{s(e).forEach(e=>{o(e)&&(t=!0)})}),e.addedNodes.forEach(e=>{s(e).forEach(e=>{a(e)&&(t=!0)})})}),t&&r.markDirty()});c.observe(t,{subtree:!0,childList:!0});let u=()=>r.onScroll();return t.addEventListener(`scroll`,u,{passive:!0}),()=>{t.removeEventListener(`scroll`,u),c.disconnect(),r.destroy()}},[l,e,Ye]),{scrollRef:c,state:f,isPinned:f===`following`,isOverflowing:m,isFollowingProgrammatically:v,showScrollButton:g,notifyContentChange:Ge,getAnimationHandlers:qe,goToBottom:fe,scrollToBottomOnSend:pe,releaseAutoFollow:me,beginHistoryViewportPreservation:he,endHistoryViewportPreservation:ge,saveSnapshotNow:Se,restoreSnapshot:Ce}},Gz=`--oc-mobile-composer-swap`,Kz=`--oc-native-composer-dock`,qz=()=>({phase:`rest`,rest:`expanded`,progress:0,pinned:!1}),Jz=(e,t,n)=>Math.min(n,Math.max(t,e)),Yz=(e,t)=>e.phase===t.phase&&e.rest===t.rest&&e.progress===t.progress&&e.pinned===t.pinned,Xz=(e,t)=>{let n={phase:t.phase,rest:t.rest,progress:t.progress,pinned:t.pinned??e.pinned};return Yz(e,n)?e:n},Zz=(e,t)=>t?Xz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0}):e.pinned?Xz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!1}):e,Qz=(e,t)=>{if(e.pinned&&t===`compact`)return e;let n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:Xz(e,{phase:`snapping`,rest:t,progress:n})},$z=e=>Jz(e/80,0,1),eB=e=>e>=80?1:Jz(e/80,0,1),tB=(e,t,n={})=>{if(e.pinned)return e;let r=Math.max(0,t),i=e.phase===`snapping`?Xz(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e;if(i.rest===`expanded`){if(r<=2||n.holdExpanded||n.userDriven===!1)return Xz(i,{phase:`rest`,rest:`expanded`,progress:0});let e=$z(r);return e>=1?Xz(i,{phase:`rest`,rest:`compact`,progress:1}):Xz(i,{phase:`tracking`,rest:`expanded`,progress:e})}if(r<=2)return Xz(i,{phase:`rest`,rest:`expanded`,progress:0});if(n.suppressReturn)return Xz(i,{phase:`rest`,rest:`compact`,progress:1});if(n.towardBottom&&r>=80)return Xz(i,{phase:`snapping`,rest:`expanded`,progress:0});let a=eB(r);return a>=1?Xz(i,{phase:`rest`,rest:`compact`,progress:1}):Xz(i,{phase:`tracking`,rest:`compact`,progress:a})},nB=e=>e.pinned?`expanded`:e.rest===`expanded`?e.progress>=.5?`compact`:`expanded`:e.progress<=.5?`expanded`:`compact`,rB=e=>{if(e.pinned)return Xz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0});if(e.phase===`snapping`)return e;let t=nB(e),n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:Xz(e,{phase:`snapping`,rest:t,progress:n})},iB=e=>e.phase===`snapping`?Xz(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e,aB=e=>Jz(Math.max(0,e)/80,0,1),oB=(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:aB(n),rest:`bottom`}},sB=e=>{e.style.removeProperty(Gz),e.style.removeProperty(Kz),delete e.dataset.ocComposerSwapPhase,delete e.dataset.ocComposerSwapRest,delete e.dataset.ocNativeComposerDock},cB=(e,t,n)=>{let r=oB(t,n?.rest===`bottom`?`bottom`:`away`),i=String(r.progress),a=r.rest;return n?.progress!==i&&e.style.setProperty(Kz,i),n?.rest!==a&&(e.dataset.ocNativeComposerDock=a),{progress:i,rest:a}},lB=(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(Gz,r),n?.rest!==a&&(e.dataset.ocComposerSwapRest=a),{progress:r,phase:i,rest:a}},uB=e=>({scrollHeight:e.scrollHeight,scrollTop:e.scrollTop,clientHeight:e.clientHeight}),dB=()=>{let e=document.documentElement;return e.classList.contains(`oc-keyboard-open`)||e.classList.contains(`oc-kb-animating`)},fB=e=>{if(dB()||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)},pB=e=>{let t=Z.useRef(qz()),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(0),u=Z.useRef(null),d=Z.useRef(0),f=Z.useRef(0),p=Z.useRef(!1),m=Z.useRef(e.enabled);m.current=e.enabled;let h=e=>{e.current!==null&&(window.clearTimeout(e.current),e.current=null)},g=q(t=>{let r=e.scopeRef.current;r&&(n.current=lB(r,t,n.current))}),_=q(e=>{e!==t.current&&(t.current=e,g(e))}),v=q(()=>{if(h(a),t.current.phase!==`snapping`)return;let e=t.current.rest;a.current=window.setTimeout(()=>{a.current=null;let n=iB(t.current);_(n),n.rest===`compact`&&e===`compact`&&(o.current=Date.now()+320,s.current=!0)},240)}),y=q(()=>{let n=e.scopeRef.current;!n||!m.current||_(Zz(t.current,fB(n)))}),b=q(e=>s.current?Date.now()>=o.current?(s.current=!1,!1):e>=80?(s.current=!1,o.current=0,!1):!0:!1),x=q(()=>{if(h(i),!m.current||c.current>0||t.current.phase!==`tracking`)return;let e=rB(t.current);_(e),v()}),S=q(()=>{m.current&&(l.current=Date.now())}),C=q(()=>{m.current&&(l.current=Date.now(),c.current+=1,h(i))}),w=q(()=>{if(!m.current)return;let n=e.scrollRef.current,a=e.scopeRef.current;if(!n||!a)return;let o=fB(a),s=uB(n),g=pI(s,dI(n)),y=u.current;if(u.current=g,n.hasAttribute(`data-oc-timeline-anchoring`)){d.current=0,f.current=0;return}r.current=cB(a,g,r.current);let S=c.current>0||Date.now()-l.current<=1200,C=y===null?0:y-g;S?C>0?(f.current=0,s.scrollTop>0&&(d.current+=C)):C<0&&(d.current=0,f.current+=-C,f.current>=24&&(p.current=!1)):(d.current=0,f.current=0),g<=2&&(p.current=!1);let w=Zz(t.current,o);if(!o){let e=w.rest===`compact`;w=tB(w,g,{suppressReturn:b(g),towardBottom:d.current>=24,holdExpanded:p.current,userDriven:S}),e&&w.rest===`expanded`&&g>2&&(p.current=!0,d.current=0)}if(_(w),h(i),w.phase===`snapping`){v();return}w.phase===`tracking`&&c.current===0&&(i.current=window.setTimeout(()=>{i.current=null,x()},120))}),T=q(()=>{x()}),E=q(()=>{m.current&&(l.current=Date.now(),c.current=Math.max(0,c.current-1),!(c.current>0)&&t.current.phase===`tracking`&&(h(i),i.current=window.setTimeout(()=>{i.current=null,x()},120)))}),D=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)}),O=q(n=>{if(!m.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(),p.current=!0,d.current=0,f.current=0,_(Qz(t.current,`expanded`)),v(),D(),(e.scopeRef.current?.querySelector(`textarea[data-chat-input="true"]`))?.focus({preventScroll:!0})))}),[k,A]=Z.useState(null),[j,M]=Z.useState(null),N=Z.useRef(null),P=q(e=>{e&&sB(e),n.current=void 0,r.current=void 0,s.current=!1,o.current=0,c.current=0,l.current=0,u.current=null,d.current=0,f.current=0,p.current=!1,_(qz())});Z.useLayoutEffect(()=>{let t=e.enabled?e.scrollRef.current:null,n=e.enabled?e.scopeRef.current:null;N.current&&N.current!==n&&P(N.current),N.current=n,A(e=>e===t?e:t),M(e=>e===n?e:n)});let F=Z.useMemo(()=>()=>void 0,[]),I=e.enabled&&k?k:F,L=e.enabled&&j?j:F,R=e.enabled&&typeof window<`u`?window:F,z=Z.useMemo(()=>({passive:!0}),[]);Jt(`scroll`,w,I,z),Jt(`scrollend`,T,I,z),Jt(`touchstart`,C,I,z),Jt(`touchmove`,S,I,z),Jt(`touchend`,E,I,z),Jt(`touchcancel`,E,I,z),Jt(`pointerdown`,O,L),Jt(`focusin`,y,L),Jt(`focusout`,y,L),Jt(`oc:keyboard-intent`,y,R),Jt(`oc:keyboard-anim`,y,R),Jt(`oc:keyboard-settled`,y,R),Z.useEffect(()=>{if(!e.enabled){P(N.current),N.current=null;return}return y(),w(),()=>{h(i),h(a)}},[e.enabled,k,j])},mB=e=>{let t=e.info.clientRole??e.info.role;return typeof t==`string`?t:``},hB=e=>{let t=e.info.parentID;if(typeof t==`string`&&t.trim().length!==0)return t},gB=e=>{if(!e)return null;let t=mB(e);return`${typeof e.info?.id==`string`?e.info.id:``}::${t}::${hB(e)??``}`},_B=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}),vB=(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&&gB(t[r])===gB(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=mB(r),a=r.info.id,o=_B(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=hB(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},yB=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=mB(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=hB(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}},bB=200,xB={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:6e5},SB=()=>bB,CB=()=>Math.round(SB()*.6),wB={MAX_SESSIONS:xB.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(bB*.6),HISTORICAL_MESSAGES:bB,FETCH_BUFFER:20,HISTORY_CHUNK:bB,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:xB.ZOMBIE_TIMEOUT},TB=()=>{let e=SB(),t=CB();return{...wB,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},EB=wB,DB=600,OB=6e3,kB=.5,AB=(e,t)=>e.querySelector(`[data-message-id="${CSS.escape(t)}"]`),jB=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},MB=(e,t)=>{let n=AB(e,t);if(n||=jB(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}},NB=e=>{let{container:t,quiesceMs:n=DB,maxLifetimeMs:r=OB}=e,i={messageId:e.anchor.messageId,offsetTop:e.anchor.offsetTop},a=!1,o=null,s=null,c=!1,l=t.scrollTop,u=()=>{o!==null&&(clearTimeout(o),o=null)},d=()=>{s!==null&&(clearTimeout(s),s=null)},f=()=>{a||(a=!0,y.disconnect(),t.removeEventListener(`scroll`,v),u(),d())},p=()=>{u(),!a&&(o=setTimeout(()=>{o=null,f()},n))},m=()=>{d(),!a&&(s=setTimeout(()=>{s=null,f()},r))},h=()=>{if(a)return;let e=MB(t,i.messageId);if(!e){f();return}i.messageId=e.messageId,i.offsetTop=e.offsetTop,l=t.scrollTop},g=()=>{if(a)return;if(Math.abs(t.scrollTop-l)>kB){h();return}let e=AB(t,i.messageId);if(!e){let n=jB(t);if(!n){f();return}let r=n.dataset.messageId;if(!r){f();return}let a=t.getBoundingClientRect();i.messageId=r,i.offsetTop=n.getBoundingClientRect().top-a.top,e=n,l=t.scrollTop}let n=t.getBoundingClientRect(),r=e.getBoundingClientRect().top-n.top-i.offsetTop;Math.abs(r)>kB&&(t.scrollTop+=r),l=t.scrollTop},_=()=>{a||c||(c=!0,queueMicrotask(()=>{c=!1,g()}))},v=()=>{h(),p(),m()},y=new MutationObserver(()=>{a||(_(),p())});return y.observe(t,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`style`,`class`]}),t.addEventListener(`scroll`,v,{passive:!0}),m(),p(),{rebase:h,dispose:f}},PB=30,FB=1200,IB=1.5,LB=e=>Math.max(FB,e*IB),RB=4,zB=30,BB=4,VB=30,HB=250,UB=2e3,WB=Mr+2e3,GB=40,KB=`history-loading-timeout`,qB=e=>!!(e&&typeof e==`object`&&e.code===`history-loading-timeout`),JB=()=>{let e=Error(`chat history pagination wait timed out`);return e.code=KB,e},YB=(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)},XB=2500,ZB=new Map,QB=()=>x()?RB:hr()?BB:PB,$B=e=>x()?e.length<=zB:!hr()||e.length<=VB,eV=(e,t)=>{if(ZB.delete(e),!$B(t.messages))return;let n=QB();for(;ZB.size>=n;){let e=ZB.keys().next().value;if(typeof e!=`string`)break;ZB.delete(e)}ZB.set(e,t)},tV=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),nV=e=>e?{owner:`tanstack-core`}:{owner:`controller`},rV=(e,t)=>e?e.canLoadEarlier:t>=TB().HISTORICAL_MESSAGES,iV=e=>!(e.isMobile||e.isLoadingOlder||e.pendingRevealWork||!e.canLoadEarlier||e.source===`scroll`&&e.isPinned||e.scrollTop>=LB(e.clientHeight)),aV=e=>e.pagesLoaded>=e.maxPages?`stop-bounded`:e.hasMoreAbove?e.scrollHeightAfter-e.scrollHeightBefore>1?`stop-visible`:e.messageCountAfter>e.messageCountBefore||typeof e.oldestIdBefore==`string`&&typeof e.oldestIdAfter==`string`&&e.oldestIdBefore!==e.oldestIdAfter||e.limitAfter>e.limitBefore?`continue`:`stop-no-growth`:`stop-exhausted`,oV=1,sV=8,cV=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),lV=e=>[`chat-timeline-auto-fill`,e.runtimeKey,e.sessionId,e.oldestMessageId,e.messageCount,e.canLoadEarlier],uV=e=>[`chat-timeline-load-earlier`,e.runtimeKey,e.sessionId],dV=20,fV=4,pV=80,mV=new WeakMap,hV=new WeakMap,gV=e=>{let t=hV.get(e)??{generation:0};return t.generation+=1,hV.set(e,t),t.generation},_V=e=>{let t=mV.get(e);t&&(t.touches=0,t.pending=null,t.settleScheduled=!1),gV(e)},vV=e=>{yV(e)},yV=e=>{let t=mV.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&&bV(e,n)};return e.addEventListener(`touchend`,r,{passive:!0}),e.addEventListener(`touchcancel`,r,{passive:!0}),mV.set(e,n),n},bV=(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+pV||xV(e,n.anchorTop+n.delta))}))},xV=(e,t)=>{let n=gV(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((hV.get(e)?.generation??0)!==n){e.removeEventListener(`touchstart`,o);return}e.scrollTop<t-fV&&(e.scrollTop=t),a+=1,a<dV?window.requestAnimationFrame(s):e.removeEventListener(`touchstart`,o)}};window.requestAnimationFrame(s)},SV=(e,t,n)=>{let r=yV(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,xV(e,t)},CV=(e,t,n)=>!e||!t||t===e?!1:n.some(t=>t.info.id===e),wV=(e,t)=>e.scrollHeight===t.scrollHeight&&e.clientHeight===t.clientHeight?e:t,TV=({sessionId:e,directory:t=null,messages:n,historyMeta:r,scrollRef:i,messageListRef:a,loadMoreMessages:o,goToBottom:c,releaseAutoFollow:l,beginHistoryViewportPreservation:u,endHistoryViewportPreservation:d,isPinned:f,showScrollButton:p,autoFillEnabled:m=!1,onWillLoadEarlier:h})=>{let g=Z.useRef(null),_=Z.useRef(null),v=Z.useMemo(()=>{let t=e??``,r=t?ZB.get(t):void 0;if(r&&r.messages===n)return eV(t,r),g.current=r.model,_.current=n,r.model;let i=vB(g.current,_.current,n)??yB(n);return g.current=i,_.current=n,t&&n.length>0&&eV(t,{messages:n,model:i}),i},[n,e]),[y,b]=Z.useState(!1),[x,S]=Z.useState(!1),[C,w]=Z.useState(null),[T,E]=Z.useState(!1),[D,O]=Z.useState(null),[k,A]=Z.useState({scrollHeight:0,clientHeight:0}),j=Z.useRef(v),M=Z.useRef(f),N=Z.useRef(y),P=Z.useRef(x),F=Z.useRef(e),I=Z.useRef(t??null),L=Z.useRef(n),R=Z.useRef(r),z=Z.useRef(D),B=Z.useRef([]),V=Z.useRef(null),H=Z.useRef(null),ee=Z.useRef(!1),U=Z.useRef(null),[te,W]=Z.useState(e);te!==e&&(W(e),U.current!==null&&typeof window<`u`&&(window.clearTimeout(U.current),U.current=null),ee.current=!1,N.current=!1,H.current=null,b(!1),S(!1),w(null),E(!1),z.current=null,O(null),A({scrollHeight:0,clientHeight:0}));let ne=Z.useMemo(()=>{let e=r?.limit!==D&&rV(r,n.length);return{hasBufferedTurns:!1,hasMoreAboveTurns:e,historyLoading:!!r?.loading,canLoadEarlier:e}},[r,n.length]),G=Z.useRef(ne);j.current=v,M.current=f,P.current=x,G.current=ne,F.current=e,I.current=t??null,L.current=n,R.current=r,z.current=D;let K=q(()=>{ee.current=!0,U.current!==null&&typeof window<`u`&&(window.clearTimeout(U.current),U.current=null)}),re=q(()=>{if(typeof window>`u`){ee.current=!1;return}U.current!==null&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>{U.current=null,ee.current=!1},UB)}),ie=q(()=>{let e=B.current;e.length!==0&&(B.current=[],e.forEach(e=>e()))}),ae=q(()=>new Promise(e=>{if(typeof window>`u`){e();return}let t=!1,n=()=>{t||(t=!0,window.clearTimeout(r),e())};B.current.push(n);let r=window.setTimeout(n,HB)})),oe=q(e=>{let t=V.current;t&&(V.current=null,t.resolve(e))}),se=q(()=>{let e=V.current;if(e){if(e.sessionId!==F.current){oe(!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&&(H.current={turnId:e.turnId,expiresAt:Date.now()+XB},w(e.turnId)),oe(!0);return}typeof(e.kind===`turn`?j.current.turnIndexById.get(e.id):j.current.messageToTurnIndex.get(e.id))==`number`&&oe(!1)}}),ce=Z.useRef(null),le=q(()=>{let e=ce.current;e&&(ce.current=null,e.dispose())});Wt(()=>{U.current!==null&&typeof window<`u`&&(window.clearTimeout(U.current),U.current=null),le(),ie(),oe(!1)});let ue=n;qt(()=>{ie(),se()},[ue]);let de=q(()=>{let e=i.current;if(!e){A(e=>wV(e,{scrollHeight:0,clientHeight:0}));return}A(t=>wV(t,{scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}))});Yt(typeof ResizeObserver<`u`?i:null,de),qt(()=>{de()},[e,y]);let fe=Z.useRef(null),pe=q(()=>a.current?.captureViewportAnchor()??null),me=q(e=>a.current?.restoreViewportAnchor(e)??!1),he=q(()=>{if(hr())return;le();let e=i.current;if(!e)return;let t=pe();t&&(ce.current=NB({container:e,anchor:t}))}),ge=Z.useRef(null);qt(()=>{if(!hr())return;let e=i.current;e&&(vV(e),_V(e))},[e,i]),qt(()=>{le(),fe.current=null,ge.current=null,a.current?.cancelViewportAnchorHold()},[e]),qt(()=>{let e=i.current;if(!e)return;let t=fe.current;t&&Math.abs(e.scrollTop-t.top)>sV&&(fe.current=null,t=null);let n=ge.current,r=ue[0]?.info?.id??null,o=ue[ue.length-1]?.info?.id??null,s=n?tV({previousOldestId:n.oldestId,previousNewestId:n.newestId,currentOldestId:r,currentNewestId:o})||CV(n.oldestId,r,ue):!1;t&&t.sessionId!==F.current&&(fe.current=null,t=null);let l=t?tV({previousOldestId:t.oldestId,previousNewestId:t.newestId,currentOldestId:r,currentNewestId:o})||CV(t.oldestId,r,ue):!1,u=s||l,d=e=>{ge.current={oldestId:r,newestId:o,scrollHeight:e??ge.current?.scrollHeight??0}};if(M.current&&!t){le(),u?(fe.current=null,c(`instant`),d(e.scrollHeight)):d();return}let f=nV(a.current?.isHistoryVirtualized()??!1);if(t){if(f.owner===`tanstack-core`){a.current?.cancelViewportAnchorHold();let e=t.anchor;e&&me(e),d();return}let n=e.scrollHeight,r=n-t.height;if(hr()){r>0&&SV(e,t.top+r,r),d(n);return}let i=t.anchor;!(i&&me(i))&&r>0&&(e.scrollTop=t.top+r),d(n);return}if(s&&n&&f.owner===`controller`){let t=e.scrollHeight,r=t-n.scrollHeight;if(r>0){let t=e.scrollTop+r;hr()?SV(e,t,r):e.scrollTop=t}d(t),he();return}d()},[ue,c]);let _e=q(async()=>!1),ve=q(async e=>{let t=Date.now(),n=t+WB,r=I.current,i=r?Ni()?.getRequestState?.(yi(r,e)):void 0;for(G.current.historyLoading,R.current,i?.status,i?.error;G.current.historyLoading;){if(F.current!==e)return Date.now()-t,`switched`;if(Date.now()>=n){let n=r?Ni()?.getRequestState?.(yi(r,e)):void 0;return console.error(`[chat-history] historyLoading wait timed out — sync flag still true`,{sessionId:e,directory:r,elapsedMs:Date.now()-t,waitMs:WB,hostTurnPageTimeoutMs:Mr,historyLoading:G.current.historyLoading,historyMeta:R.current,requestStatusAtStart:i?.status??null,requestStatusAtTimeout:n?.status??null,requestErrorAtTimeout:n?.error??null,likelyStaleLoadingFlag:n?.status===`ready`||n?.status===`error`||n==null}),`timeout`}await new Promise(e=>{if(typeof window>`u`){e();return}window.setTimeout(e,GB)})}return Date.now()-t,r&&Ni()?.getRequestState?.(yi(r,e))?.status,F.current===e?`cleared`:`switched`}),ye=q(async e=>{if(!F.current||N.current||!G.current.hasMoreAboveTurns)return!1;N.current=!0,K(),b(!0);let t=F.current,n=null,r=!!e.userInitiated;r&&u();let s=()=>{n&&fe.current===n&&(fe.current=null,a.current?.cancelViewportAnchorHold()),r&&(r=!1,d())};try{if(G.current.historyLoading){if(!e.userInitiated)return!1;let n=await ve(t);if(n===`timeout`)throw JB();if(n===`switched`||!G.current.hasMoreAboveTurns)return!1}if(!F.current||F.current!==t)return!1;let r=i.current,a=L.current,c=a.length,l=a[0]?.info?.id??null,u=R.current?.limit??TB().HISTORICAL_MESSAGES;e.preserveViewport&&r&&(n={sessionId:F.current,height:r.scrollHeight,top:r.scrollTop,anchor:pe(),oldestId:l,newestId:a[a.length-1]?.info?.id??null},fe.current=n,he());let d=c,f=l,p=u,m=0;for(;;){if(G.current.historyLoading)if(e.userInitiated){let e=await ve(t);if(e===`timeout`)throw s(),JB();if(e===`switched`)return s(),!1}else return s(),!1;let n=i.current?.scrollHeight??0,r=d,a=f,c=p;if(await o(t,`up`),m+=1,F.current!==t)return s(),!1;await ae();let l=L.current,u=l.length,h=l[0]?.info?.id??null,g=R.current?.limit??p,_=aV({scrollHeightBefore:n,scrollHeightAfter:i.current?.scrollHeight??n,messageCountBefore:r,messageCountAfter:u,oldestIdBefore:a,oldestIdAfter:h,limitBefore:c,limitAfter:g,hasMoreAbove:G.current.hasMoreAboveTurns,pagesLoaded:m,maxPages:oV});if(_===`continue`){d=u,f=h,p=g;continue}if(_===`stop-no-growth`){if(G.current.historyLoading){if(e.userInitiated){let e=await ve(t);if(e===`timeout`)throw s(),JB();if(e===`switched`)return s(),!1;--m;continue}return s(),!1}let n=R.current?.limit??c;return z.current=n,O(n),G.current={...G.current,hasMoreAboveTurns:!1,canLoadEarlier:!1},s(),!1}return!0}}catch(e){throw s(),e}finally{N.current=!1,b(!1),re(),ae().then(s)}}),{t:be}=Zt(),xe=Nt({mutationKey:uV({runtimeKey:s(),sessionId:e??``}),mutationFn:async e=>{if(F.current!==e.sessionId)return!1;K(),e.userInitiated&&l();try{return await ye({preserveViewport:!0,userInitiated:!!e.userInitiated})}finally{re()}}}),Se=q(async e=>{let t=F.current;if(t&&!(xe.isPending&&xe.variables?.sessionId===t)){e?.userInitiated&&h?.();try{let n=await xe.mutateAsync({sessionId:t,userInitiated:!!e?.userInitiated});if(n===!1&&G.current.canLoadEarlier){let r={sessionId:t,grew:n,userInitiated:!!e?.userInitiated,canLoadEarlier:G.current.canLoadEarlier,hasMoreAboveTurns:G.current.hasMoreAboveTurns,historyLoading:G.current.historyLoading,historyMeta:R.current,messageCount:L.current.length,oldestMessageId:L.current[0]?.info?.id??null};YB(`no-growth`,Error(`chat history pagination returned no growth`),r),e?.userInitiated&&fa.error(be(`chat.history.loadOlderFailed`))}}catch(n){let r={sessionId:t,userInitiated:!!e?.userInitiated,waitMs:WB,hostTurnPageTimeoutMs:Mr,canLoadEarlier:G.current.canLoadEarlier,historyLoading:G.current.historyLoading,historyMeta:R.current,messageCount:L.current.length,oldestMessageId:L.current[0]?.info?.id??null};qB(n)?YB(`timeout`,n,r):YB(`failed`,n,r),e?.userInitiated&&fa.error(qB(n)?be(`chat.history.loadOlderTimeout`):be(`chat.history.loadOlderFailed`))}}}),Ce=xe.isPending&&xe.variables?.sessionId===e||y,we=n[0]?.info?.id??null,Te=cV({enabled:m,isMobile:hr(),sessionReady:!!e,messageReady:n.length>0||!!r,historyLoading:ne.historyLoading,canLoadEarlier:ne.canLoadEarlier,isPinned:f,fillBlocked:T,scrollHeight:k.scrollHeight,clientHeight:k.clientHeight,pendingRevealWork:x,isLoadingOlder:!1,hasMessages:n.length>0});Pt({queryKey:lV({runtimeKey:s(),sessionId:e??``,oldestMessageId:we,messageCount:n.length,canLoadEarlier:ne.canLoadEarlier}),enabled:!!e&&Te,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()=>{let e=F.current;if(!e)return{status:`skip`};if(G.current.historyLoading||N.current){let e=Error(`auto-fill-busy`);throw e.code=`auto-fill-busy`,e}if(!G.current.canLoadEarlier)return{status:`skip`};let t=i.current;if(!t||t.clientHeight<=0)return{status:`skip`};if(t.scrollHeight>t.clientHeight+48)return{status:`tall`};try{let t=await ye({preserveViewport:!0});return t?{status:`grew`}:(G.current.canLoadEarlier&&YB(`no-growth`,Error(`chat history pagination returned no growth`),{sessionId:e,source:`auto-fill`,grew:t,canLoadEarlier:G.current.canLoadEarlier,hasMoreAboveTurns:G.current.hasMoreAboveTurns,historyLoading:G.current.historyLoading,historyMeta:R.current,messageCount:L.current.length,oldestMessageId:L.current[0]?.info?.id??null}),E(!0),{status:`blocked`})}catch(t){if(t?.code===`auto-fill-busy`)throw t;let n={sessionId:e,source:`auto-fill`,waitMs:WB,canLoadEarlier:G.current.canLoadEarlier,historyLoading:G.current.historyLoading,historyMeta:R.current,messageCount:L.current.length,oldestMessageId:L.current[0]?.info?.id??null};throw qB(t)?YB(`timeout`,t,n):YB(`failed`,t,n),E(!0),t instanceof Error?t:Error(`chat timeline auto-fill failed`)}}});let Ee=q(e=>{let t=i.current;t&&iV({source:e,isMobile:hr(),isPinned:M.current,scrollTop:t.scrollTop,clientHeight:t.clientHeight,canLoadEarlier:G.current.canLoadEarlier,isLoadingOlder:N.current,pendingRevealWork:P.current})&&Se({userInitiated:!0})}),De=q(()=>{Ee(`scroll`)}),Oe=q(()=>{Ee(`upward-intent`)}),ke=q(async(t,n)=>{if(!t||!F.current)return!1;l(),S(!0);try{return F.current!==e||typeof j.current.turnIndexById.get(t)!=`number`?!1:!!await new Promise(r=>{V.current={sessionId:F.current??e??``,kind:`turn`,id:t,behavior:n?.behavior??`auto`,turnId:t,resolve:r},se()})}finally{S(!1)}}),Ae=q(async(t,n)=>{if(!t||!F.current)return!1;l(),S(!0);try{if(F.current!==e)return!1;let r=j.current.messageToTurnId.get(t);return typeof j.current.messageToTurnIndex.get(t)==`number`&&!!await new Promise(i=>{V.current={sessionId:F.current??e??``,kind:`message`,id:t,behavior:n?.behavior??`auto`,turnId:r??null,resolve:i},se()})}finally{S(!1)}}),je=q(async()=>{S(!1),N.current=!1,b(!1),a.current?.scrollToBottom(),c(`smooth`)}),Me=q(async()=>{S(!1),N.current=!1,b(!1),a.current?.scrollToBottom(),c(`instant`)}),Ne=q(e=>{let t=H.current;if(t){if(e!==t.turnId&&Date.now()<t.expiresAt)return;H.current=null}w(e)});return{turnIds:v.turnIds,turnStart:0,renderedMessages:ue,historySignals:ne,isLoadingOlder:Ce,pendingRevealWork:x,activeTurnId:C,showScrollToBottom:p&&!x,turnWindowModel:v,loadEarlier:Se,revealBufferedTurns:_e,resumeToBottom:je,resumeToBottomInstant:Me,scrollToTurn:ke,scrollToMessage:Ae,handleHistoryScroll:De,handleHistoryUpwardIntent:Oe,captureViewportAnchor:pe,restoreViewportAnchor:me,handleActiveTurnChange:Ne}},EV=({mutateSession:e,forkSession:t})=>({revert:e,fork:t}),DV=({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{t:d}=Zt(),f=zy(),p=n,m=ka(p??``,r),h=J(e=>e.revertToMessage),g=J(e=>e.forkFromMessage),_=EV(f.capabilities),{isMobile:v,isTablet:y}=Ws(),b=v||y,[x,S]=Z.useState(null),C=Z.useRef(!1),[w,T]=Z.useState(``),[E,D]=Z.useState(0),O=Z.useRef([]),k=Z.useRef(null),A=Z.useRef(null),j=Z.useRef(!1),M=Z.useRef(e),N=e=>new Date(e).toLocaleDateString(Qt(),{year:`numeric`,month:`short`,day:`numeric`}),P=e=>new Date(e).toLocaleTimeString(Qt(),{hour:`numeric`,minute:`2-digit`}),F=Z.useMemo(()=>m.filter(e=>e.info.role===`user`).map(e=>({message:e})),[m]),I=Z.useMemo(()=>{let e=w.trim();if(!e)return F;let t=e.toLowerCase();return F.filter(({message:e})=>WR(e.parts).toLowerCase().includes(t))},[F,w]);Z.useEffect(()=>{j.current||D(w.trim()?0:Math.max(0,I.length-1))},[I,w]),Z.useEffect(()=>{O.current=O.current.slice(0,I.length)},[I.length]),Z.useEffect(()=>{j.current||O.current[E]?.scrollIntoView({block:`nearest`})},[E]),Z.useEffect(()=>{!j.current||A.current||c||(j.current=!1)},[I.length,c]),Z.useLayoutEffect(()=>{let t=M.current;if(M.current=e,!e||t||j.current||w.trim())return;let n=k.current;n&&(n.scrollTop=n.scrollHeight)},[e,w]),Z.useLayoutEffect(()=>{let e=A.current,t=k.current;if(!e||!t||c)return;A.current=null;let n=O.current.find(t=>t?.dataset.timelineMessageId===e.messageId);if(!n)return;let r=n.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=r-e.top},[I.length,c]);let L=q(()=>{let e=k.current;if(e){let t=e.getBoundingClientRect().top,n=O.current.find(e=>e?e.getBoundingClientRect().bottom>=t:!1);n?.dataset.timelineMessageId&&(A.current={messageId:n.dataset.timelineMessageId,top:n.getBoundingClientRect().top-t})}j.current=!0,l?.()}),R=q(async e=>{await i?.(e)!==!1&&t(!1)}),z=q(e=>{let t=I.length;if(t!==0){if(e.key===`ArrowDown`){e.preventDefault(),D(e=>(e+1)%t);return}if(e.key===`ArrowUp`){e.preventDefault(),D(e=>(e-1+t)%t);return}if(e.key===`Enter`){e.preventDefault();let n=(E%t+t)%t,r=I[n];r&&R(r.message.info.id)}}}),B=q(async(e,n)=>{if(!(!p||C.current)){C.current=!0,S({type:e,messageId:n});try{e===`revert`?u?await u(n):await h(p,n,{directory:r}):await g(p,n,{directory:r}),t(!1)}finally{C.current=!1,S(null)}}});return p?(0,$.jsx)(go,{open:e,onOpenChange:t,children:(0,$.jsxs)(fo,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:[(0,$.jsxs)(co,{children:[(0,$.jsxs)(po,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`time`,className:`h-5 w-5`}),d(`chat.timeline.title`)]}),(0,$.jsx)(mo,{children:d(`chat.timeline.description`)})]}),(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[(0,$.jsx)(X,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),(0,$.jsx)(Yo,{autoFocus:!0,placeholder:d(`chat.timeline.searchPlaceholder`),value:w,onChange:e=>T(e.target.value),onKeyDown:z,className:`pl-9 w-full`})]}),s&&l&&(0,$.jsx)(`div`,{className:`flex justify-center py-1`,children:(0,$.jsxs)(yo,{type:`button`,variant:`link`,size:`sm`,onClick:L,disabled:c,className:`h-auto px-1 py-0 text-muted-foreground hover:text-foreground`,children:[c&&(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}),d(`chat.history.loadOlder`)]})}),(0,$.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto`,children:I.length===0?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:d(w?`chat.timeline.empty.search`:`chat.timeline.empty.session`)}):I.map(({message:e},t)=>{let n=GR(e.parts),r=e.info.time.created,i=N(r),a=I[t-1],o=i!==(a?N(a.message.info.time.created):null),s=P(r),c=t===E,l=w.trim()?OV(WR(e.parts),w):null;return(0,$.jsxs)(Z.Fragment,{children:[o&&(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:i}),(0,$.jsx)(`div`,{className:`h-px flex-1 bg-border/60`})]}),(0,$.jsxs)(`div`,{ref:e=>{O.current[t]=e},"data-timeline-message-id":e.info.id,className:Y(`group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,c&&`bg-interactive-selection text-interactive-selection-foreground`),onClick:()=>void R(e.info.id),onMouseEnter:()=>D(t),children:[(0,$.jsx)(`span`,{className:Y(`typography-meta w-16 flex-shrink-0 text-right tabular-nums`,c?`text-interactive-selection-foreground/70`:`text-muted-foreground`),children:s}),(0,$.jsxs)(`p`,{className:Y(`flex-1 min-w-0 typography-micro truncate`,c?`text-interactive-selection-foreground`:`text-foreground`),children:[l??(n||d(`chat.timeline.noTextContent`)),!l&&n&&n.length>=80&&`…`]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:(0,$.jsxs)(`div`,{className:Y(`gap-1`,b?`flex`:`hidden group-hover:flex`),children:[_.revert?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:`size-5 text-muted-foreground hover:text-foreground`,"aria-busy":x?.type===`revert`&&x.messageId===e.info.id,disabled:x!==null,onClick:t=>{t.stopPropagation(),B(`revert`,e.info.id)},children:(0,$.jsx)(X,{name:x?.type===`revert`&&x.messageId===e.info.id?`loader-4`:`arrow-go-back`,className:Y(`h-4 w-4`,x?.type===`revert`&&x.messageId===e.info.id&&`animate-spin`)})})}),(0,$.jsx)(Zo,{sideOffset:6,children:d(`chat.timeline.actions.revertFromHere`)})]}):null,_.fork?(0,$.jsxs)(Qo,{children:[(0,$.jsx)(Xo,{asChild:!0,children:(0,$.jsx)(yo,{type:`button`,variant:`ghost`,size:`icon`,className:`size-5 text-muted-foreground hover:text-foreground`,"aria-busy":x?.type===`fork`&&x.messageId===e.info.id,onClick:t=>{t.stopPropagation(),B(`fork`,e.info.id)},disabled:x!==null,children:x?.type===`fork`&&x.messageId===e.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)(Zo,{sideOffset:6,children:d(`chat.timeline.actions.forkFromHere`)})]}):null]})})]})]},e.info.id)})}),(0,$.jsxs)(`div`,{className:`mt-4 p-3 bg-muted/30 rounded-lg`,children:[(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground font-medium mb-2`,children:d(`chat.timeline.actions.title`)}),(0,$.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:()=>{a?.(-1),t(!1)},children:d(`chat.timeline.actions.previousTurn`)}),(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`/`}),(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:()=>{o?.(),t(!1)},children:d(`chat.timeline.actions.latest`)})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 typography-meta text-muted-foreground`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,$.jsx)(`span`,{children:d(`chat.timeline.help.clickMessage`)})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(X,{name:`arrow-go-back`,className:`h-4 w-4 flex-shrink-0`}),(0,$.jsx)(`span`,{children:d(`chat.timeline.help.undoToPoint`)})]}),_.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:d(`chat.timeline.help.createSessionFromHere`)})]}):null]})]})]})}):null};function OV(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?`…`:``}`}var kV=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},AV=(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`}},jV=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)},MV=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&&jV(`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&&jV(`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=AV(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 jV(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=()=>{jV(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=kV(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},NV=2e4,PV=6e4,FV=2e3,IV=e=>e?(typeof e.text==`string`?e.text.length:0)+(typeof e.state?.output==`string`?e.state.output.length:0):0,LV=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+=IV(e);return[e.length,t.info.id,n.length,r?.id??``,r?.state?.status??``,i].join(`:`)},RV={sessionKey:null,fingerprint:null,lastMovementAt:null,lastRefreshAt:null,attempts:0},zV=(e,t)=>{let{sessionKey:n,working:r,streaming:i,fingerprint:a,now:o}=t;if(!n)return{state:RV,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}},BV=e=>{console.warn(`[transcript] tail frozen while session is working — refetching authority`,e)};function VV(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 HV(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 UV(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||VV(i)==null}function WV(e){let t=[];for(let n of e){let e=Array.isArray(n.parts)?n.parts:[];for(let n of e){if(!UV(n))continue;let e=HV(n);e&&t.push(e)}}return t}function GV(e,t){return`${e}:${t.join(`,`)}`}function KV(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=GV(t,e.unansweredToolIds);return e.attemptedKey===r?{recover:!1,attemptKey:r}:{recover:!0,attemptKey:r}}function qV(e,t,n,r){let i=(0,Q.c)(7),a=Un(),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=KV({sessionId:e,directory:t,sessionQuestionCount:r,unansweredToolIds:WV(n),attemptedKey:o.current});if(!c.recover||!e||!t||!c.attemptKey)return;let l=a.getChild(t);l&&(o.current=c.attemptKey,Yn(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 JV=e=>!Number.isFinite(e)||e<0?0:Math.ceil(e),YV=(e,t)=>({...e,key:XV(e),estimatedBytes:JV(t)}),XV=({runtimeKey:e,sessionId:t,directory:n})=>JSON.stringify([e,n??``,t]),ZV=e=>({key:e?XV(e):null,selection:e}),QV=(e,t,n)=>{let r=Math.max(1,Math.floor(n.maxEntries)),i=Math.max(0,n.maxEstimatedBytes),a=e.reduce((e,t)=>e+t.estimatedBytes,0);if(e.length<=r&&a<=i)return e;let o=[...e];for(;o.length>r||a>i;){let e=o.findIndex(e=>e.key!==t);if(e===-1)break;let[n]=o.splice(e,1);a-=n?.estimatedBytes??0}return o},$V=(e,t,n,r)=>{let i=XV(t),a=e.findIndex(e=>e.key===i),o=a>=0?e[a]:void 0;if(o&&a===e.length-1)return QV(e,i,n);let s=o||YV(t,r),c=a>=0?e.filter((e,t)=>t!==a):[...e];return c.push(s),QV(c,i,n)},eH=(e,t,n)=>{let r=JV(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)},tH=(e,t)=>t&&e.some(e=>e.key===t)?t:null,nH=(e,t,n)=>{let r=t.key?e.cachedSessionViews.find(e=>e.key===t.key):void 0,i=r&&t.selection?$V(e.cachedSessionViews,t.selection,n,r.estimatedBytes):QV(e.cachedSessionViews,t.key??``,n),a=!r&&e.pendingSessionView?.intent===t?e.pendingSessionView:null;return e.activeIntent===t&&!e.cacheNeedsTrim&&i===e.cachedSessionViews&&a===e.pendingSessionView?e:{activeIntent:t,cacheNeedsTrim:!1,cachedSessionViews:i,pendingSessionView:a}},rH=(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:YV(t.selection,r),intent:t};return e.pendingSessionView?.intent===t?e:{activeIntent:e.activeIntent,cacheNeedsTrim:e.cacheNeedsTrim,cachedSessionViews:e.cachedSessionViews,pendingSessionView:i}},iH=(e,t,n)=>{let r=e.pendingSessionView;return e.activeIntent!==t||r?.intent!==t||!t.selection?e:{activeIntent:e.activeIntent,cacheNeedsTrim:!1,cachedSessionViews:$V(e.cachedSessionViews,t.selection,n,r.entry.estimatedBytes),pendingSessionView:null}},aH=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},oH=e=>{if(!(!e.info||typeof e.info!=`object`))return e.info},sH=e=>oH(e)?.role===`assistant`,cH=(e,t)=>{let n=oH(t);n&&(e.agentName??=aH(n.agent),e.providerId??=aH(n.providerID),e.modelId??=aH(n.modelID))},lH=e=>!!(e.agentName&&e.providerId&&e.modelId),uH=e=>{let t={};for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||!sH(r))&&(cH(t,r),lH(t)))return t}for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||sH(r))&&(cH(t,r),lH(t)))break}return t},dH=e=>!!e.sessionId&&!(e.hasRenderableSessionSnapshot&&e.hasCurrentSessionEntity),fH=[],pH=[],mH={type:`idle`},hH=`openchamber:chat-force-scroll-bottom`,gH=()=>void 0,_H=`Quota limit reached. Retrying automatically.`,vH=1048576,yH=vH,bH=20,xH=vH,SH=16*vH,CH={maxEntries:3,maxEstimatedBytes:32*vH},wH={maxEntries:2,maxEstimatedBytes:32*vH},TH=e=>t(()=>e()),EH={overflowAnchor:`none`,overscrollBehavior:`contain`,overscrollBehaviorY:`contain`},DH={scrollbar:`chat`,scrollShadow:`true`,orientation:`vertical`},OH=()=>{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},kH=`calc(max(0.625rem, var(--oc-safe-area-top, 0px)) + var(--oc-mobile-detail-navigation-height) + 1.25rem)`,AH=yz,jH=[`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(`,`),MH=e=>e instanceof HTMLElement,NH=e=>MH(e)?!!e.closest(jH):!1,PH=(e,t)=>typeof document>`u`||!e||e===document.body||e===document.documentElement||NH(e)?!0:!t?.contains(e),FH=()=>{let{isAboutDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isImagePreviewOpen:r,isMultiRunLauncherOpen:i,isSessionSwitcherOpen:a,isSettingsDialogOpen:o}=g.getState();return e||t||n||r||i||a||o},IH=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,isProgrammaticFollowActive:E,showLoadOlderButton:D,onLoadOlder:O,turnIds:k,activeTurnId:A,onSelectTurn:j,showPromptNavigator:M,canLoadEarlierPrompts:N,isLoadingOlderPrompts:P,onLoadEarlierPrompts:F,transcriptStatusRow:I})=>{let{t:L}=Zt(),R=gl(e=>e.legendTimelineEnabled),z=bT({isLoadingOlder:d}),B=xT({isMobile:r,isLoadingOlder:z}),V=Z.useRef(new Map),H=Z.useRef(new WeakMap),ee=Z.useRef(new Map),U=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(qI(n)){let r=YI(u,t)??``,i=ee.current.get(n.info.id);if(i&&i.command===r)e.set(n.info.id,i.parts);else{let t=[{type:`text`,text:r?`$ ${r}`:`/shell`}];ee.current.set(n.info.id,{command:r,parts:t}),e.set(n.info.id,t)}continue}if(Kn(n.parts))continue;let r=H.current.get(n.parts);r||(r=pi(n.parts),H.current.set(n.parts,r)),r.length!==0&&e.set(n.info.id,r)}let t=V.current;if(t.size===e.size){let n=!0;for(let[r,i]of e)if(t.get(r)!==i){n=!1;break}if(n)return t}return V.current=e,e},[u]),te=Z.useMemo(()=>k.filter(e=>U.has(e)),[U,k]),W=Z.useMemo(()=>{if(!A||U.has(A))return A;let e=k.indexOf(A);for(let t=e-1;t>=0;--t){let e=k[t];if(U.has(e))return e}return null},[A,U,k]),ne=q(e=>{e.defaultPrevented||NH(e.target)||typeof window<`u`&&window.getSelection()?.type===`Range`||o.current?.focus({preventScroll:!0})});return Cz({scrollRef:o,enabled:R,onUpwardIntent:y}),R?(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,n?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":n,children:(0,$.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,$.jsx)(_R,{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:EH,timelineScrollDataset:DH,timelineOnScroll:v,timelineFollowEnabled:!c&&!x,timelineHistoryAnchorToken:S,timelineOnIsAtEndChange:b,headerSlot:(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:kH},"aria-hidden":`true`}),D&&(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsxs)(yo,{variant:`secondary`,size:`sm`,onClick:O,disabled:z,"aria-busy":z,children:[z&&(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}),L(`chat.history.loadOlder`)]})}),B&&(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex justify-center pointer-events-none`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin text-[var(--surface-mutedForeground)]`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta text-[var(--surface-mutedForeground)]`,children:L(`chat.history.loadingMore`)})]})})]}),footerSlot:(0,$.jsxs)($.Fragment,{children:[(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(UR,{question:e},e.id)),T.map(e=>(0,$.jsx)(IR,{permission:e},e.id))]}),I?(0,$.jsx)(`div`,{className:`mb-1`,children:I}):null,(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?AH:_z},"aria-hidden":`true`})]})}),(0,$.jsx)(Gs,{containerRef:o,suppressVisibility:E,userIntentOnly:!0,observeMutations:!1}),M&&te.length>=2?(0,$.jsx)(fz,{turnIds:te,previewsByTurnId:U,activeTurnId:W,onSelectTurn:j,canLoadEarlier:N,isLoadingOlder:P,onLoadEarlier:F}):null]})}):(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,n?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":n,children:(0,$.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,$.jsx)(Sl,{className:Y(`absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target`),ref:o,style:EH,observeMutations:!1,hideTopShadow:r&&i,hideBottomShadow:r,tabIndex:0,onClick:ne,onScroll:v,"data-scroll-shadow":`true`,"data-scrollbar":`chat`,children:(0,$.jsxs)(`div`,{className:Y(`oc-chat-scroll-content relative z-0 min-h-full`,r&&`chat-scroll-foot-inset`),children:[D&&(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsxs)(yo,{variant:`secondary`,size:`sm`,onClick:O,disabled:z,"aria-busy":z,children:[z&&(0,$.jsx)(X,{name:`loader-4`,className:`size-4 animate-spin`}),L(`chat.history.loadOlder`)]})}),B&&(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex justify-center pointer-events-none`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:[(0,$.jsx)(X,{name:`loader-4`,className:`size-3.5 animate-spin text-[var(--surface-mutedForeground)]`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta text-[var(--surface-mutedForeground)]`,children:L(`chat.history.loadingMore`)})]})}),(0,$.jsx)(_R,{ref:s,sessionKey:e,virtualizerKey:t,disableStaging:c,initialPinRevealComplete:l,messages:u,sessionIsWorking:f,activeStreamingMessageId:p,activeStreamingPhase:m,retryOverlay:h,onMessageContentChange:g,getAnimationHandlers:_,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:a,liveStatusSlot:u.length>0?(0,$.jsx)(`div`,{className:`mb-1`,children:I??(0,$.jsx)(JN,{})}):null}),(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(UR,{question:e},e.id)),T.map(e=>(0,$.jsx)(IR,{permission:e},e.id))]}),(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?vz:_z},"aria-hidden":`true`})]})}),(0,$.jsx)(Gs,{containerRef:o,suppressVisibility:E,userIntentOnly:!0,observeMutations:!1}),M&&te.length>=2?(0,$.jsx)(fz,{turnIds:te,previewsByTurnId:U,activeTurnId:W,onSelectTurn:j,canLoadEarlier:N,isLoadingOlder:P,onLoadEarlier:F}):null]})})},(e,t)=>e.currentSessionId===t.currentSessionId&&e.virtualizerKey===t.virtualizerKey&&e.isDesktopExpandedInput===t.isDesktopExpandedInput&&e.isMobile===t.isMobile&&e.stickyUserHeader===t.stickyUserHeader&&e.directory===t.directory&&e.scrollRef===t.scrollRef&&e.messageListRef===t.messageListRef&&e.pendingRevealWork===t.pendingRevealWork&&e.initialPinRevealComplete===t.initialPinRevealComplete&&e.renderedMessages===t.renderedMessages&&e.isLoadingOlder===t.isLoadingOlder&&e.sessionIsWorking===t.sessionIsWorking&&e.streamingMessageId===t.streamingMessageId&&e.activeStreamingPhase===t.activeStreamingPhase&&e.retryOverlay===t.retryOverlay&&e.handleMessageContentChange===t.handleMessageContentChange&&e.getAnimationHandlers===t.getAnimationHandlers&&e.handleHistoryScroll===t.handleHistoryScroll&&e.handleHistoryUpwardIntent===t.handleHistoryUpwardIntent&&e.onTimelineIsAtEndChange===t.onTimelineIsAtEndChange&&e.timelineFollowSuspended===t.timelineFollowSuspended&&e.timelineHistoryAnchorToken===t.timelineHistoryAnchorToken&&e.scrollToBottom===t.scrollToBottom&&e.sessionQuestions===t.sessionQuestions&&e.sessionPermissions===t.sessionPermissions&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&e.onLoadOlder===t.onLoadOlder&&e.turnIds===t.turnIds&&e.activeTurnId===t.activeTurnId&&e.onSelectTurn===t.onSelectTurn&&e.showPromptNavigator===t.showPromptNavigator&&e.canLoadEarlierPrompts===t.canLoadEarlierPrompts&&e.isLoadingOlderPrompts===t.isLoadingOlderPrompts&&e.onLoadEarlierPrompts===t.onLoadEarlierPrompts&&e.transcriptStatusRow===t.transcriptStatusRow);IH.displayName=`ChatViewport`;var LH=[{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%]`]}],RH=e=>_o(e.path),zH=(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)]})},BH=e=>{let t=Math.ceil(Math.max(0,e)/bH);return Math.min(SH,yH+t*xH)},VH=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=pH,onPendingUserMessagesMaterialized:p,committedDraftHandoffMessageId:m=null})=>{let h=c??TT(void 0),{t:_}=Zt();qt(()=>{ba()},[]);let v=J(e=>e.openNewSessionDraft),y=J(e=>e.setCurrentSession),b=J(e=>e.newSessionDraft),S=J(e=>e.newSessionDraft.draftSubmitting??!1),C=J(e=>e.newSessionDraft.draftEstablishing??!1),w=J(e=>e.forkTransition),T=Gi(e=>e.projects),E=Gi(e=>e.activeProjectId),D=ui(e=>e.providers),O=jm(),k=Wi(),A=i??k;qt(()=>{!n||!r||!A||sr(A,r)},[n,r,A]);let j=q(e=>O.ensureSessionRenderable(e,{directory:A})),M=g(e=>e.isExpandedInput),N=g(e=>e.stickyUserHeader),P=g(e=>e.promptNavigatorEnabled),F=g(e=>e.allowPromptingSubagentSessions),I=g(e=>e.isTimelineDialogOpen),L=g(e=>e.setTimelineDialogOpen),R=qa(e=>n&&r?e.streamingMessageIds.get(r)??null:null),z=qa(e=>R?e.messageStreamStates.get(R)?.phase??null:null),B=Fa(r??``,A),V=BH(B);Z.useEffect(()=>{!a||!o||o(a,V)},[o,V,a]);let H=ji(r??``,A).renderable,ee=Dr(r,A),U=Wr(r),te=ee??U,W=Pb({sessionId:r,hasSessionEntity:!!te,hasRenderableSessionSnapshot:H,composerSurfaceKind:s?.kind}),ne=r?JSON.stringify([A,r]):null,[G,K]=Z.useState({key:ne,attempt:0}),re=ka(r??``,A,{suspendPartUpdates:!!R,suspendPartUpdatesForMessageId:R}),ie=r?re:fH,ae=b.pendingUserMessage,oe=J(e=>r?e.retainedPendingUserMessages.get(r):void 0)??pH,se=!!(m||oe.length>0),ce=J(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(()=>uH(ie),[ie]),de=Z.useMemo(()=>{if(!ue.modelId)return _(`common.unavailable`);let e=D.find(e=>e.id===ue.providerId);return Hr(e,ue.modelId)||ue.modelId},[D,ue.modelId,ue.providerId,_]),fe=_a(r??``,A),pe=Fi(r??``,A),[me,he]=Z.useState(null),ge=!!r&&me===r,_e=q(()=>{if(!r||ge)return;let e=r,t=A;he(e);let n=Ma(()=>{let n=Ni();if(!n)throw Error(`unbound`);return n.getTranscript(yi(t,e))});Ji(oa({kind:`refresh`,sessionID:e,directory:t,purpose:`retry`,source:`network`,request:fe?{sessionID:e,status:fe.status===`ready`?`ready`:fe.status,error:fe.error}:void 0,hydration:pe,error:fe?.error})),(async()=>{try{await Ha(t,e),await O.ensureSessionRenderable(e,{directory:t});try{let r=Ma(()=>{let n=Ni();if(!n)throw Error(`unbound`);return n.getTranscript(yi(t,e))});n&&r&&_i({trigger:`user-refresh`,sessionID:e,directory:t,purpose:`retry`,before:n,after:r})}catch{}}catch(n){Ji(oa({kind:`request-error`,sessionID:e,directory:t,purpose:`retry`,source:`network`,hydration:pe,error:n}))}finally{he(t=>t===e?null:t)}})()}),ve=Sa(r??``,A).boundary,ye=q(async e=>{if(ve.kind===`has-more`){await La(A,e);return}if(ve.kind===`unknown`){await aa(A,e);return}l&&!l.complete&&await l.fetchPrevious()}),be=sa(r??``,A),xe=za(r??``,A),Se=ki(A),Ce=be??mH,we=ri(r,A),Te=fi(r,A);qV(r,A,ie,Te.length);let Ee=Z.useMemo(()=>{if(!r||we.length>0||Te.length>0)return!1;let e=Ce.type??`idle`;if(e===`busy`||e===`retry`||gT(le,{resolvedSessionStatus:be,sessionStatusObservedAt:xe}))return!0;let t=ie[ie.length-1]?.info,n=t?.time?.created;return be&&typeof xe==`number`&&typeof n==`number`&&n<=xe||typeof Se==`number`&&typeof n==`number`&&n<=Se?!1:!!(t&&t.role===`assistant`&&typeof t.time?.completed!=`number`)},[r,le,be,ie,we.length,Te.length,Ce.type,xe,Se]),De=Z.useMemo(()=>!r||Ce.type!==`retry`?null:{sessionId:r,message:(typeof Ce.message==`string`?(Ce.message??``).trim():``)||_H,confirmedAt:Ce.confirmedAt},[r,Ce]),[Oe,ke]=Z.useState(0),Ae=Z.useRef(null);Z.useEffect(()=>{if(!De||typeof De.confirmedAt==`number`){Ae.current=null,ke(0);return}Ae.current!==De.sessionId&&(Ae.current=De.sessionId,ke(Date.now()))},[De]);let je=Z.useMemo(()=>De?{...De,fallbackTimestamp:Oe}:null,[De,Oe]),Me=!!(r&&O.isLoading(r,{directory:A})),Ne=Z.useMemo(()=>{if(!r)return null;let e=_T({boundary:ve,assistantComplete:l?.complete??!0});return{limit:ve.loadedTurns,complete:e.complete,canLoadEarlier:e.canLoadEarlier,loading:vT({syncLoading:Me,assistantLoading:!!l?.loading})}},[l?.complete,l?.loading,r,ve,Me]),Pe=g(e=>e.isMobile),Fe=Pu()!==null,Ie=x(),Le=Cb(),Re=!!b?.open,ze=zr(e=>e.error),Be=M,Ve=Fe||Pe||Ie||Le===`mini-chat`,He=Z.useRef(null),Ue=Z.useMemo(()=>{let e=b?.selectedProjectId?T.find(e=>e.id===b.selectedProjectId)??null:null,t=E?T.find(e=>e.id===E)??null:null,n=e??t??T[0]??null;return n?RH(n):null},[E,b?.selectedProjectId,T]),We=ci(r,A),Ge=a??r??``,[Ke,qe]=Z.useState(null),Je=zb(Ke,Ge,We,ue);qt(()=>{qe(e=>zb(e,Ge,We,ue))},[We,ue,Ge]);let Ye=We??Je?.parentTarget??null,Xe=Je?.execution??ue,Ze=pf(),Qe=Ze!==null&&r===Ze,$e=q(()=>{Ye&&y(Ye.id,Ye.directory)}),et=Ye?.session?.title,tt=h.returnToParent&&Ye&&!Qe?(0,$.jsxs)(yo,{type:`button`,variant:`outline`,size:`xs`,onClick:$e,className:`absolute left-3 top-3 z-20 !font-normal bg-[var(--surface-background)]/95`,"aria-label":_(`chat.container.returnToParent.aria`),title:et?.trim()?_(`chat.container.returnToParent.titleNamed`,{title:et}):_(`chat.container.returnToParent.title`),children:[(0,$.jsx)(X,{name:`arrow-left`,className:`h-4 w-4`}),_(`chat.container.returnToParent.label`)]}):null,nt=Fb({readOnly:t,sessionIdentityPending:W,isSubagentSession:!!te?.parentID||!!Je,allowPromptingSubagentSessions:F}),rt=Xe.modelId===ue.modelId?de:Xe.modelId?Hr(D.find(e=>e.id===Xe.providerId),Xe.modelId)||Xe.modelId:_(`common.unavailable`),it=Ye?(0,$.jsx)(kT,{agentName:Xe.agentName,providerId:Xe.providerId,modelId:Xe.modelId,modelName:rt}):(0,$.jsx)(kT,{}),at=q(e=>{g.getState().setAllowPromptingSubagentSessions(e.allowPromptingSubagentSessions)}),ot=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`&&at({allowPromptingSubagentSessions:t.payload.allowPromptingSubagentSessions})}),st=typeof window<`u`&&window.parent!==window;Jt(`message`,ot,st?window:gH),Kt(()=>{if(!st)return;let e=window;e.__openchamberApplyChatSettingsSync=at,window.parent.postMessage({type:`openchamber:chat-settings-request`},window.location.origin)}),Wt(()=>{if(typeof window>`u`)return;let e=window;e.__openchamberApplyChatSettingsSync===at&&delete e.__openchamberApplyChatSettingsSync}),Z.useEffect(()=>{h.newSessionDraft&&e&&!r&&!Re&&v()},[e,r,Re,h.newSessionDraft,v]);let ct=Z.useRef(()=>{}),lt=q(e=>{ct.current(e)}),ut=Z.useRef(()=>{}),dt=q(()=>{ut.current()}),ft=gl(e=>e.legendTimelineEnabled),[pt,mt]=Z.useState(!0),[ht,gt]=Z.useState(!1),[_t,vt]=Z.useState(!1),[yt,bt]=Z.useState(0),xt=q(()=>{bt(e=>e+1)}),St=q((e,t)=>{mt(e),e&&vt(!1),t!==void 0&&gt(t)});Z.useEffect(()=>{mt(!0),gt(!1),vt(!1)},[r]);let{scrollRef:Ct,notifyContentChange:wt,getAnimationHandlers:Tt,goToBottom:Et,scrollToBottomOnSend:Dt,releaseAutoFollow:Ot,beginHistoryViewportPreservation:kt,endHistoryViewportPreservation:At,restoreSnapshot:jt,isPinned:Mt,isFollowingProgrammatically:Nt,showScrollButton:Pt}=Wz({enabled:n&&!ft,currentSessionId:r,viewportKey:a,sessionMessageCount:B,sessionIsWorking:Ee,isMobile:Pe,onActiveTurnChange:lt,onUpwardUserIntent:dt}),Ft=Z.useRef(null);pB({enabled:Pe,scrollRef:Ct,scopeRef:Ft});let It=Z.useRef([]),Lt=Z.useMemo(()=>{let e=la(l?.entries??[],r,It.current);return It.current=e,e},[l?.entries,r]),Rt=Z.useRef([]),zt=Z.useMemo(()=>{if(!l)return ie;let e=xa(l.entries,r,ie,Rt.current);return Rt.current=e,e},[l,r,ie]),Bt=Z.useMemo(()=>hT(Lt.length===0?zt:r?[...Lt,Oi(r),...zt]:Lt,le),[r,zt,Lt,le]),Vt=Z.useRef(null),Ht=Z.useMemo(()=>wT({sessionId:r,messages:Bt,retained:Vt.current}),[r,Bt]);Vt.current=Ht.retained;let Ut=Ht.messages,Gt=Z.useRef(null),Xt=Gt.current===r,Qt=Z.useRef(RV),$t=r?`${A}\n${r}`:null,en=q(()=>LV(Ut));Z.useEffect(()=>{if(!r||!$t||!Ee){Qt.current={...Qt.current,lastMovementAt:null};return}let e=r,t=A,n=setInterval(()=>{let n=en(),r=zV(Qt.current,{sessionKey:$t,working:!0,streaming:!!R,fingerprint:n,now:Date.now(),thresholdMs:NV,cooldownMs:PV,maxAttempts:3});Qt.current=r.state,r.shouldRefresh&&(BV({sessionId:e,directory:t,stalledForMs:r.stalledForMs,attempt:r.state.attempts,fingerprint:n}),Li(t,e).catch(()=>{}))},FV);return()=>clearInterval(n)},[r,A,en,Ee,R,$t]);let tn=Z.useMemo(()=>{if(le.length===0)return[];let e=new Set([...Lt,...zt].filter(e=>Ui(e.parts)).map(e=>e.info.id));return le.map(e=>e.info.id).filter(t=>e.has(t))},[zt,Lt,le]);Z.useEffect(()=>{tn.length!==0&&(p?.(tn),r&&ce(r,tn))},[ce,r,tn,p]);let nn=TV({sessionId:r,directory:A,messages:Ut,historyMeta:Ne,scrollRef:Ct,messageListRef:He,loadMoreMessages:ye,goToBottom:Et,releaseAutoFollow:Ot,beginHistoryViewportPreservation:kt,endHistoryViewportPreservation:At,isPinned:ft?pt:Mt,showScrollButton:ft?ht:Pt,autoFillEnabled:n&&!Be,onWillLoadEarlier:xt}),rn=q(()=>{vt(!1),He.current?.scrollToBottom(),Et(`instant`)}),an=q(()=>{vt(!1),Dt()}),on=q(()=>{vt(!0),nn.handleHistoryUpwardIntent()}),sn=yT({isMobile:Pe,canLoadEarlier:nn.historySignals.canLoadEarlier,isLoadingOlder:nn.isLoadingOlder}),cn=nn.isLoadingOlder,ln=nn.loadEarlier,un=q(()=>{vt(!0),ln({userInitiated:!0})});ct.current=nn.handleActiveTurnChange,ut.current=nn.handleHistoryUpwardIntent,Z.useEffect(()=>{(we.length!==0||Te.length!==0)&&wt(`permission`)},[wt,we,Te]);let dn=MV({sessionId:r,turnIds:nn.turnIds,activeTurnId:nn.activeTurnId,scrollToTurn:nn.scrollToTurn,scrollToMessage:nn.scrollToMessage,resumeToBottom:rn}),fn=nt.showReadOnlyBanner?it:t?null:(0,$.jsx)(sT,{surface:s,scrollToBottom:an,showScrollToBottom:Pe&&nn.showScrollToBottom,onScrollToBottom:dn.resumeToLatest,submissionBlocked:nt.blockSubmission}),pn=q(e=>{dn.scrollToTurnId(e,{behavior:`smooth`})}),mn=nn.historySignals.canLoadEarlier,hn=h.promptNavigator&&!Pe&&!Ie&&!Be&&P&&nn.turnIds.length>=2;Z.useEffect(()=>{hn||g.getState().setPromptNavigatorPanelOpen(!1)},[hn]);let gn=q(e=>{if(!n||!r)return;let t=e;t.detail?.sessionId&&t.detail.sessionId!==r||Et(`instant`)});Jt(hH,gn,n&&r&&typeof window<`u`?window:gH);let _n=q(e=>{if(!n||!r||Be||e.defaultPrevented||e.isComposing||e.key!==`ArrowUp`&&e.key!==`ArrowDown`||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let{activeMainTab:t}=g.getState();if(t!==`chat`||FH())return;let i=Ct.current;if(PH(document.activeElement,i)||NH(e.target))return;e.preventDefault();let a=e.key===`ArrowUp`?-1:1;dn.scrollByTurnOffset(a,{resumePastEnd:!1})});Jt(`keydown`,_n,n&&r&&!Be&&typeof window<`u`?window:gH);let vn=Z.useRef(0),yn=q(()=>{let e=Ct.current;e&&e.style.setProperty(`--chat-scroll-height`,`${e.clientHeight}px`)}),bn=q(()=>{vn.current||=requestAnimationFrame(()=>{vn.current=0,yn()})});qt(()=>{n&&yn()},[n,r,Be,yn]);let xn=typeof ResizeObserver<`u`;Yt(n&&xn?Ct:null,bn),Jt(`resize`,bn,n&&!xn&&typeof window<`u`?window:gH),Wt(()=>{vn.current&&=(cancelAnimationFrame(vn.current),0)});let Sn=Z.useRef(null),Cn=Z.useRef(0),wn=ST({transcriptMessageCount:ie.length,pendingUserCount:le.length,historyPrefixCount:Lt.length}),Tn=CT({hasTranscriptShell:wn,p0Satisfied:pe.p0Satisfied,hasBusyShell:Ee&&wn,hasImmediateShell:le.length>0||Lt.length>0,hasRenderableSessionSnapshot:H,prefetchStatus:fe?.status,syncLoading:!!(r&&O.isLoading(r,{directory:A})),userRetrying:ge,hasPaintedTranscript:Xt});Tn===`pass`&&Ut.length>0&&(Gt.current=r);let En=!!r&&Tn===`hydrating`,Dn=!!r&&Tn===`load-error`;Z.useEffect(()=>{!Dn||!r||Ji(oa({kind:`request-error`,sessionID:r,directory:A,purpose:`load-failed`,source:`network`,request:fe?{sessionID:r,status:fe.status===`ready`?`ready`:fe.status,error:fe.error}:void 0,hydration:pe,error:fe?.error}))},[r,A,Dn,fe,pe]),Z.useEffect(()=>{if(!n||!r||En)return;let e=Ut.length,t=Sn.current!==r,i=!t&&Cn.current===0&&e>0;if(!t&&!i){Sn.current===r&&(Cn.current=e);return}let a=typeof window<`u`&&window.location.hash.length>0;if(Sn.current=r,Cn.current=e,a){Ot();return}let o=()=>{jt()};typeof window>`u`?o():window.requestAnimationFrame(o)},[n,r,En,Ot,jt,Ut.length]),Z.useEffect(()=>{K(e=>e.key===ne?e:{key:ne,attempt:0})},[ne]),Z.useEffect(()=>{if(!n||!r||G.key!==ne||!dH({sessionId:r,hasRenderableSessionSnapshot:H,hasCurrentSessionEntity:!!te})||(j(r),te||G.attempt>=2))return;let e=G.attempt+1,t=window.setTimeout(()=>{K(t=>t.key===ne&&t.attempt===G.attempt?{key:ne,attempt:e}:t)},e*1e3);return()=>window.clearTimeout(t)},[n,te,r,A,j,H,ne,G]);let On=w&&r&&(w.targetSessionId?r===w.targetSessionId:r===w.sourceSessionId)?w:null;if(On){let e=On.stage===`preparing`?`chat.forkTransition.preparing`:On.stage===`copying`?`chat.forkTransition.copying`:On.stage===`opening`?`chat.forkTransition.opening`:`chat.forkTransition.loading`,t=[`preparing`,`copying`,`opening`,`loading`],n=_(`chat.forkTransition.progress`,{current:Math.max(1,t.indexOf(On.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":`${_(e)}. ${n}`,children:[(0,$.jsxs)(`span`,{className:`typography-ui-header text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:_(e)}),(0,$.jsx)(U_,{})]}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground/70 tabular-nums`,children:n})]})})}if(!r&&!Re)return e&&!ze?(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)(jT,{})});if(!r&&Re){if((S||C)&&ae){let e=`draft:${b.draftID??`pending`}`;return(0,$.jsxs)(`div`,{ref:Ft,className:Y(`relative flex h-full flex-col bg-background`,Pe&&`oc-chat-composer-swap-scope`),children:[(0,$.jsx)(IH,{currentSessionId:e,virtualizerKey:e,isDesktopExpandedInput:!1,isMobile:Pe,stickyUserHeader:N,directory:A,scrollRef:Ct,messageListRef:He,pendingRevealWork:!1,initialPinRevealComplete:!0,renderedMessages:[ae],isLoadingOlder:!1,sessionIsWorking:!0,streamingMessageId:null,activeStreamingPhase:null,retryOverlay:null,handleMessageContentChange:wt,getAnimationHandlers:Tt,handleHistoryScroll:nn.handleHistoryScroll,handleHistoryUpwardIntent:on,onTimelineIsAtEndChange:St,timelineFollowSuspended:!1,timelineHistoryAnchorToken:yt,scrollToBottom:rn,sessionQuestions:[],sessionPermissions:[],isProgrammaticFollowActive:Nt,showLoadOlderButton:!1,onLoadOlder:un,turnIds:[],activeTurnId:null,onSelectTurn:pn,showPromptNavigator:!1,canLoadEarlierPrompts:!1,isLoadingOlderPrompts:!1,onLoadEarlierPrompts:un,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:_(`chat.emptyState.establishingConversation`)}),(0,$.jsx)(U_,{})]})})},e),(0,$.jsxs)(`div`,{className:Y(`invisible pointer-events-none relative z-10`,Pe&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,Be?`absolute inset-0 bg-background`:`bg-background`),"aria-hidden":`true`,children:[!Pe&&!Be?(0,$.jsx)(OH,{}):null,fn]}),(0,$.jsx)(mT,{})]})}return S||C?(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":_(`chat.emptyState.establishingConversation`),children:(0,$.jsxs)(`span`,{className:`typography-ui-header text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:_(`chat.emptyState.establishingConversation`)}),(0,$.jsx)(U_,{})]})})}):(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[Ve&&!Be?(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:zH(Ue?_(`chat.emptyState.draftTitleWithProject`,{project:Ue}):_(`chat.emptyState.draftTitle`),Ue)}),(0,$.jsx)(jx,{onSubmit:e=>Ja.getState().requestPresetSubmit(e),className:`oc-draft-starters mt-8 max-w-md`})]}):null,(0,$.jsx)(`div`,{className:Y(`relative z-10 flex min-h-0`,Pe&&`oc-mobile-composer-foot`,Be?`flex-1 bg-background`:Ve?Y(`bg-background`,`px-0`):`flex-1 items-center justify-center bg-background px-0 pb-[6vh]`),children:fn})]})}return r?Dn?(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[tt,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,Be?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":Be,children:Be?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:_(`chat.history.loadFailedTitle`)}),(0,$.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:_(`chat.history.loadFailedDescription`)}),(0,$.jsxs)(yo,{type:`button`,className:`mt-5`,onClick:_e,children:[(0,$.jsx)(X,{name:`refresh`,className:`size-4`,"aria-hidden":`true`}),_(`chat.history.retry`)]})]})})}),(0,$.jsx)(`div`,{className:Y(`relative z-10`,Pe&&`oc-mobile-composer-foot`,Be?`flex-1 min-h-0 bg-background`:`bg-background`),children:fn})]}):En?(0,$.jsxs)(`div`,{ref:Ft,className:Y(`relative flex flex-col h-full bg-background`,Pe&&`oc-chat-composer-swap-scope`),children:[tt,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,Be?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":Be,children:(0,$.jsx)(`div`,{ref:Ct,className:`absolute inset-0 overflow-y-auto overflow-x-hidden bg-background pt-6 chat-scroll`,style:EH,children:(0,$.jsx)(`div`,{className:`space-y-4 chat-scroll-foot-inset`,children:LH.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)(Lu,{className:`h-3.5 w-3.5 rounded-full flex-shrink-0`}),(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,t.titleWidth)}),(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,t.detailWidth)})]},`${e.id}-${t.id}`))}),(0,$.jsxs)(`div`,{className:`space-y-1.5 pt-1`,children:[(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,e.textWidths[0])}),(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,e.textWidths[1])}),(0,$.jsx)(Lu,{className:Y(`h-4 rounded-md`,e.textWidths[2])})]})]})})},e.id))})})}),(0,$.jsxs)(`div`,{className:Y(`relative z-10`,Pe&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,Be?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Pe&&!Be?(0,$.jsx)(OH,{}):null,fn]})]}):Ut.length===0&&!Ee?(0,$.jsxs)(`div`,{className:`relative flex flex-col h-full bg-background`,children:[tt,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,Be?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":Be,children:Be?null:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,$.jsx)(jT,{})})}),(0,$.jsx)(`div`,{className:Y(`relative z-10`,Pe&&`oc-mobile-composer-foot`,Be?`flex-1 min-h-0 bg-background`:`bg-background`),children:fn}),(0,$.jsx)(mT,{})]}):(0,$.jsxs)(`div`,{ref:Ft,className:Y(`relative flex flex-col h-full bg-background`,Pe&&`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,tt,(0,$.jsx)(IH,{currentSessionId:r,virtualizerKey:a??r,isDesktopExpandedInput:Be,isMobile:Pe,stickyUserHeader:N,directory:A,scrollRef:Ct,messageListRef:He,pendingRevealWork:nn.pendingRevealWork,initialPinRevealComplete:se,renderedMessages:nn.renderedMessages,isLoadingOlder:cn,sessionIsWorking:Ee,streamingMessageId:R,activeStreamingPhase:z,retryOverlay:je,handleMessageContentChange:wt,getAnimationHandlers:Tt,handleHistoryScroll:nn.handleHistoryScroll,handleHistoryUpwardIntent:on,onTimelineIsAtEndChange:St,timelineFollowSuspended:_t,timelineHistoryAnchorToken:yt,scrollToBottom:rn,sessionQuestions:Te,sessionPermissions:we,isProgrammaticFollowActive:Nt,showLoadOlderButton:sn,onLoadOlder:un,turnIds:nn.turnIds,activeTurnId:nn.activeTurnId,onSelectTurn:pn,showPromptNavigator:hn,canLoadEarlierPrompts:mn,isLoadingOlderPrompts:cn,onLoadEarlierPrompts:un},r),(0,$.jsxs)(`div`,{className:Y(`relative z-10`,Pe&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,Be?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Pe&&!Be?(0,$.jsx)(OH,{}):null,!Be&&Ut.length>0&&(Pe?(0,$.jsx)(xb,{placement:`expanded`,visible:nn.showScrollToBottom,onClick:dn.resumeToLatest}):(0,$.jsx)(xb,{visible:nn.showScrollToBottom,onClick:dn.resumeToLatest})),fn]}),(0,$.jsx)(mT,{}),(0,$.jsx)(DV,{open:I,onOpenChange:L,sessionID:r??void 0,directory:A,onRevertMessage:u,onScrollToMessage:nn.scrollToMessage,onScrollByTurnOffset:dn.scrollByTurnOffset,onResumeToLatest:rn,canLoadEarlier:nn.historySignals.canLoadEarlier,isLoadingEarlier:cn,onLoadEarlier:un})]}):null});VH.displayName=`MemoizedChatContainerContent`;var HH=()=>{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)(Lu,{className:`h-4 w-4/5 animate-none rounded-md`}),(0,$.jsx)(Lu,{className:`h-4 w-2/3 animate-none rounded-md`}),(0,$.jsx)(Lu,{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)(Lu,{className:`h-4 w-5/6 animate-none rounded-md`}),(0,$.jsx)(Lu,{className:`h-4 w-3/5 animate-none rounded-md`})]}),(0,$.jsx)(Lu,{className:`h-24 w-full animate-none rounded-xl`})]})})}),e[1]=n):n=e[1],n},UH=({runtimeKey:e,...t})=>{let n=Cb(),r=Wi(),i=J(Qe(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),qt(()=>{!o||!i.draftPendingMessageId||(a.current={identity:o,messageId:i.draftPendingMessageId})},[o,i.draftPendingMessageId]);let s=J(e=>i.sessionId?e.retainedPendingUserMessages.get(i.sessionId)??pH:pH),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(()=>ZV(u),[u]),f=d.key,p=hr()||x()||n===`mini-chat`?wH:CH,[m,h]=Z.useState(()=>({activeIntent:d,cacheNeedsTrim:!1,cachedSessionViews:u?$V([],u,p,yH):[],pendingSessionView:null})),g=Z.useRef(d),_=Z.useRef(f),{cacheNeedsTrim:v,cachedSessionViews:y,pendingSessionView:b}=m,S=b?.intent===d?b.entry:null,C=Z.useMemo(()=>!u||!l?null:$V([],u,p,yH)[0]??null,[p,l,u]),w=Z.useMemo(()=>{let e=[...y];return S&&!e.some(e=>e.key===S.key)&&e.push(S),C&&!e.some(e=>e.key===C.key)&&e.push(C),e.sort((e,t)=>e.key.localeCompare(t.key))},[y,C,S]),T=tH(w,f),E=!!(f&&!T);qt(()=>{g.current=d,_.current=f,h(e=>{let t=nH(e,d,p);return l?rH(t,d,d,yH):t})},[p,v,l,d,f]);let D=b?.intent??null;qt(()=>{D&&h(e=>iH(e,D,p))},[p,D]),Z.useEffect(()=>{if(!d.selection||T)return;let e=d,t=f;return Kl(()=>{g.current===e&&_.current===t&&h(n=>_.current===t?rH(n,e,g.current,yH):n)},{priority:`user-blocking`})},[T,p,d,f]);let O=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=eH(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":E||void 0,children:[E?(0,$.jsx)(HH,{},f):null,w.map(e=>(0,$.jsx)(Z.Activity,{name:`chat-session-${e.sessionId}`,mode:T===e.key?`visible`:`hidden`,children:(0,$.jsx)(VH,{...t,sessionId:e.sessionId,sessionDirectory:e.directory,sessionViewKey:e.key,onSessionViewEstimateChange:O,committedDraftHandoffMessageId:T===e.key?l:null})},e.key)),f?null:(0,$.jsx)(VH,{...t,sessionId:null,sessionDirectory:i.directory})]})},WH=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=TT(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)(VH,{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)(Ry.Provider,{value:u,children:f}),t[21]=u,t[22]=f,t[23]=p):p=t[23],p},GH=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=Wi(),o=n.directory??a,s;t[4]!==o||t[5]!==n?(s=Ly({...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)(VH,{...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)(Ry.Provider,{value:c,children:u}),t[13]=c,t[14]=u,t[15]=d):d=t[15],d},KH=e=>{let t=(0,Q.c)(14),n=Z.useSyncExternalStore(TH,s,s);if(e.host){let r=`${n}:${e.host.sessionSurface.surfaceId}`,i;return t[0]!==e||t[1]!==n||t[2]!==r?(i=(0,$.jsx)(WH,{...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)(GH,{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)(UH,{...e,runtimeKey:n},n),t[11]=e,t[12]=n,t[13]=r):r=t[13],r},qH=(e,t)=>nn(tn.getState().dictionary,e,t),JH=e=>{let t=new Date(e),n=new Date,r=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),i=new Date(n);return i.setDate(n.getDate()-1),r(t,n)?qH(`common.date.today`):r(t,i)?qH(`common.date.yesterday`):t.toLocaleDateString(Qt(),{month:`short`,day:`numeric`,year:`numeric`}).replace(`,`,``)},YH=e=>{let t=new Date;if(((e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate())(new Date(e),t)){let t=Date.now()-e;return t<6e4?qH(`common.relative.justNow`):t<36e5?qH(`common.relative.minutesAgoShort`,{count:Math.floor(t/6e4)}):qH(`common.relative.hoursAgoShort`,{count:Math.floor(t/36e5)})}return JH(e)},XH=e=>{let t=Math.max(0,Date.now()-e),n=6e4,r=60*n,i=24*r,a=7*i,o=365*i;return t<r?qH(`common.relative.minutesAgoCompact`,{count:Math.max(1,Math.floor(t/n))}):t<i?qH(`common.relative.hoursAgoCompact`,{count:Math.floor(t/r)}):t<a?qH(`common.relative.daysAgoCompact`,{count:Math.floor(t/i)}):t<5*a?qH(`common.relative.weeksAgoCompact`,{count:Math.floor(t/a)}):t<o?qH(`common.relative.monthsAgoCompact`,{count:Math.floor(t/2592e6)}):qH(`common.relative.yearsAgoCompact`,{count:Math.floor(t/o)})},ZH=(e,t)=>QH(b(e),b(t)),QH=(e,t)=>!e||!t?!1:e===t?!0:t===`/`?e.startsWith(`/`):e.startsWith(`${t}/`),$H=e=>e.toLowerCase().replace(/^opencode[/-]?/i,``).replace(/[-_]/g,``).trim(),eU=(e,t)=>e?$H(e)!==$H(t):!1,tU=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim().length>0){let t=Number(e);if(Number.isFinite(t))return t}},nU=e=>tU(e.time?.created)??0,rU=(e,t,n)=>{let r=n.has(e.id),i=n.has(t.id);return r===i?r&&i?nU(t)-nU(e):oi(t)-oi(e):r?-1:1},iU=e=>{let t=new Map;return e.forEach(e=>{t.set(e.id,e)}),Array.from(t.values())},aU=e=>`__archived__:${e}`,oU=(e,t)=>{let n=b(e.directory??null),r=b(e.project?.worktree??null),i=n??r;if(!i)return`unassigned`;if(t&&i===t)return`project root`;let a=(t&&i.startsWith(`${t}/`)?i.slice(t.length+1):i).split(`/`).filter(Boolean);return a[a.length-1]??`unassigned`},sU=`box-border w-full px-2 py-1.5 text-left typography-micro text-muted-foreground/70 select-none`,cU=`bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)] dark:bg-[color-mix(in_srgb,var(--surface-foreground)_11%,transparent)]`,lU=`hover:bg-[color-mix(in_srgb,var(--surface-foreground)_3.5%,transparent)] dark:hover:bg-[color-mix(in_srgb,var(--surface-foreground)_8%,transparent)]`,uU=e=>{let t=Math.max(0,e);return t===0?8:30+(t-1)*14},dU=(e,t)=>{if(!t)return e;let n=e.toLowerCase(),r=t.toLowerCase(),i=r.length;if(i===0)return e;let a=[],o=0,s=n.indexOf(r,o);for(;s!==-1;){s>o&&a.push(e.slice(o,s));let t=e.slice(s,s+i);a.push((0,$.jsx)(`mark`,{className:`bg-primary text-primary-foreground ring-1 ring-primary/90`,children:t},`${s}-${t}`)),o=s+i,s=n.indexOf(r,o)}return o<e.length&&a.push(e.slice(o)),a.length>0?a:e},fU=2e4,pU=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus()?`visible`:`hidden`,mU=e=>{if(!oe()&&!wt())return;let t=je();t?.push?.setVisibility&&t.push.setVisibility({visible:e,platform:Tt()})},hU=e=>{let t=e?.enabled??!0;Z.useEffect(()=>{if(!t||!oe()&&!wt()||typeof window>`u`)return;if(wt()){let e=!0,t=!1,n=null,r=()=>mU(e);kt(async()=>{let{App:e}=await import(`./vendor-capacitor-app-PzT84wSx.js`).then(e=>e.t);return{App:e}},__vite__mapDeps([51,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&&mU(!0)},fU);return()=>{t=!0,window.clearInterval(i),n?.()}}if(typeof document>`u`)return;let e=()=>{mU(pU()===`visible`)},n=()=>{pU()===`visible`&&mU(!0)},r=()=>{mU(!1)};e();let i=window.setInterval(n,fU);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])},gU=`OpenChamber`,_U=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``).split(`/`).filter(Boolean);return t[t.length-1]??``},vU=(e,t)=>[e,t,gU].filter(e=>typeof e==`string`&&e.trim().length>0).join(` | `),yU=()=>{let e=Gi(e=>e.activeProjectId?e.projects.find(t=>t.id===e.activeProjectId)??null:null),t=Z.useMemo(()=>e&&_U(e.path)||null,[e]),[r,i]=Z.useState(null);Z.useEffect(()=>{if(typeof window>`u`||!H()){i(null);return}let e=!1,t=async()=>{try{if(U()){e||i(null);return}let t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,r=n();if(r&&Re(r,t)){e||i(null);return}let a=(await Ke()).hosts.find(e=>r?Re(r,Ve(e)):!1),o=a?.label?.trim()?ze(a.label.trim()):`Instance`;e||i(o)}catch{e||i(`Instance`)}};t();let r=()=>{t()};return window.addEventListener(`focus`,r),()=>{e=!0,window.removeEventListener(`focus`,r)}},[]);let a=Z.useMemo(()=>vU(t,r),[t,r]);Z.useEffect(()=>{typeof document<`u`&&(document.title=a),H()&&(async()=>{try{if(typeof navigator<`u`&&/Macintosh|Mac OS X/.test(navigator.userAgent||``))return;await Xt(a)}catch{return}})()},[a])},bU=()=>{let e=J.getState().currentSessionId;if(!e)return``;let t=Da().find(t=>t.id===e);return typeof t?.directory==`string`?t.directory:``},xU=async(e,t=6e3)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t),i=Date.now();try{let t=await pe(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)}},SU=e=>{if(!e||!Number.isFinite(e))return`(n/a)`;try{return new Date(e).toISOString()}catch{return`(invalid)`}},CU=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},wU=e=>!!e&&typeof e==`object`&&!Array.isArray(e),TU=(e,t=`(n/a)`)=>typeof e==`string`?e.trim()||t:typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`boolean`?e?`true`:`false`:t,EU=(e,t,n)=>e===`node-shebang`||e===`node-launcher`?t?`node (${t})`:`node`:e===`bun-shebang`?n?`bun (${n})`:`bun`:e||`direct executable`,DU=async()=>{let e=new Date,t=typeof navigator<`u`?navigator.userAgent:`(no navigator)`,n=bU(),r=g.getState().eventStreamStatus,i=typeof window<`u`?window.location.origin:``,a=o(),s=a.health(),c=a.api(`/api/`),l=await(async()=>{if(!s)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),5e3);try{let t=await pe(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 pe(a.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()},f=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 xU(t,typeof e.timeoutMs==`number`?e.timeoutMs:void 0);return{label:e.label,url:t,result:n}})):[],p=[];p.push(`Time: ${e.toISOString()}`),p.push(`OpenChamber version: 1.19.7-beta.22`),p.push(`Runtime: ${i||`(unknown)`} (api=${c||`(unknown)`})`),p.push(`OpenCode SDK base: ${mt.getBaseUrl()}`),p.push(`Event stream: ${r}`),p.push(`Directory: ${n||`(none)`}`),p.push(`Platform: ${t}`);let m=CU(l?.openCodePort);if(p.push(`OpenCode runtime port: ${m??`(unknown)`}`),typeof l?.openCodeRunning==`boolean`&&p.push(`OpenCode runtime running: ${l.openCodeRunning?`yes`:`no`}`),typeof l?.openCodeSecureConnection==`boolean`&&p.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?`true`:`false`}`),typeof l?.openCodeAuthSource==`string`&&l.openCodeAuthSource.trim()&&p.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<`u`){let e=window.__OPENCHAMBER_MACOS_MAJOR__;typeof e==`number`&&Number.isFinite(e)&&e>0&&p.push(`macOS major: ${e}`)}if(/Mac OS X|Macintosh/.test(t)){p.push(``),p.push(`OpenCode CLI resolution:`);let e=wU(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:``,m=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&&p.push(`- configured: ${r.trim().length===0?`(cleared)`:r}`),i){let e=a||(i.includes(`/`)?i.split(`/`).slice(0,-1).join(`/`)||`/`:``);p.push(`- opencode: ${i}${e?` (dir=${e})`:``}`)}else p.push(`- opencode: (n/a)`);p.push(`- source: ${o||`(n/a)`}`),h&&(p.push(`- detected-now: ${h}`),p.push(`- detected-source: ${g||`(n/a)`}`)),e?(p.push(`- launched-at: ${TU(e.launchedAt)}`),p.push(`- launch: ${TU(e.binary)} ${t.join(` `)}`.trim()),p.push(`- cwd: ${TU(e.cwd)}`),p.push(`- wrapper: ${TU(e.wrapperType)}`),p.push(`- runtime: ${EU(TU(e.wrapperType,``),f,m)}`),p.push(`- PATH entries: ${TU(e.pathEntryCount,`(unknown)`)}`),p.push(`- shell env: ${TU(e.hasShellEnv,`(unknown)`)} (${TU(e.shellEnvKeysCount,`?`)} keys)`)):(p.push(`- launch-binary: ${s||`(n/a)`}`),p.push(`- launch-wrapper: ${c||`(n/a)`}`),p.push(`- launch-args: ${d.length?d.join(` `):`(none)`}`),p.push(`- runtime: ${EU(c||``,f,m)}`)),!n&&u.error&&p.push(`- resolution-endpoint: ${u.error}`)}if(p.push(``),f.length){p.push(`OpenCode API probes:`);for(let e of f){if(!e.result){p.push(`- ${e.label}: (no url)`);continue}let{ok:t,status:n,elapsedMs:r,summary:i}=e.result,a=t?``:` url=${e.url}`;p.push(`- ${e.label}: ${t?`ok`:`fail`} status=${n} time=${r}ms ${i}${a}`)}}else p.push(`OpenCode API probes: (skipped)`);return p.push(``),p.push(`Generated: ${SU(Date.now())}`),p.join(`
6586
6586
  `)},OU=async()=>{let e=await DU(),t=g.getState();t.setOpenCodeStatusText(e),t.setOpenCodeStatusDialogOpen(!0)},kU=(e,t)=>e===t?!0:!e||!t?!1:e.scope===t.scope&&e.sessionId===t.sessionId&&e.projectId===t.projectId,AU=e=>e?`${e.scope}:${e.projectId??``}:${e.sessionId}`:null,jU=e=>({scope:`project`,sessionId:e,projectId:null}),MU=Ye()(e=>({focus:null,setFocus:t=>e(e=>kU(e.focus,t)?e:{focus:t})})),NU=null,PU=0,FU=(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},IU=e=>{let t=++PU;return NU={pinned:FU(`pinned`,e.pinned),project:FU(`project`,e.project)},()=>{PU===t&&(NU=null)}},LU=()=>NU,RU=e=>!!e.parentID,zU=(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&&RU(r);){let e=r.parentID;if(!e)break;let t=n.get(e);if(!t)return e;r=t}return r?.id??e},BU=()=>{let e=Ai.getState().activeSessions;if(e.length>0)return e;let t=on();return t.length>0?t:Da()},VU=(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)},HU=e=>[...e.pinned,...e.project],UU=(e,t,n,r)=>{if(e.length===0)return null;let i=VU(e,n,r);return i<0?t>0?e[0]??null:e[e.length-1]??null:e[(i+t+e.length)%e.length]??null},WU=(e,t,n=MU.getState().focus)=>{let r=zU(t,BU()),i=n?.sessionId===t?n:null,a=LU();return a?UU(HU(a),e,r,i):null},GU=(e,t,n=e=>{J.getState().setCurrentSession(e.sessionId,e.directory)})=>{let r=WU(e,t);return r?(MU.getState().setFocus({scope:r.scope,sessionId:r.sessionId,projectId:r.projectId}),n(r),r):null},KU=.5,qU=.1,JU=`oc.webviewZoomFactor`,YU=e=>Number.isFinite(e)?Math.min(3,Math.max(KU,Math.round(e*100)/100)):1,XU=()=>{if(typeof window>`u`)return 1;try{let e=window.localStorage.getItem(JU);return e?YU(Number.parseFloat(e)):1}catch{return 1}},ZU=e=>{if(!(typeof window>`u`))try{window.localStorage.setItem(JU,String(e))}catch{}},QU=e=>{let t=YU(e);return typeof document<`u`&&(document.documentElement.style.zoom=t===1?``:String(t)),ZU(t),t},$U=()=>{if(typeof document>`u`)return 1;let e=document.documentElement.style.zoom;if(!e)return XU();let t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?YU(t):XU()},eW=()=>{if(E())return;let e=XU();e!==1&&QU(e)},tW=async()=>{if(E())try{let e=await Se(`desktop_zoom_in`);if(typeof e==`number`&&Number.isFinite(e))return YU(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_in failed, using CSS zoom`,e)}return QU($U()+qU)},nW=async()=>{if(E())try{let e=await Se(`desktop_zoom_out`);if(typeof e==`number`&&Number.isFinite(e))return YU(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_out failed, using CSS zoom`,e)}return QU($U()-qU)},rW=async()=>{if(E())try{let e=await Se(`desktop_zoom_reset`);if(typeof e==`number`&&Number.isFinite(e))return YU(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_reset failed, using CSS zoom`,e)}return QU(1)},iW=9,aW=null,oW=0,sW=({pinnedTargets:e,projectTargets:t})=>[...e,...t].slice(0,iW),cW=(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},lW=e=>{let t=++oW;return aW={targets:e.targets.slice(0,iW),activate:e.activate},()=>{oW===t&&(aW=null)}},uW=e=>{if(!Number.isInteger(e)||e<1||e>iW)return!1;let t=aW,n=t?.targets[e-1];return!t||!n?!1:(t.activate(n),!0)},dW=e=>{let t=e.trim();if(!t)return null;let n=Gu.getState(),r=n.createTab(t);return!r||r===`tab-invalid`?null:(n.setActiveTab(t,r),r)},fW=e=>{let t=e.trim();if(!t)return null;let n=g.getState();return!n.isBottomTerminalOpen&&n.activeMainTab!==`terminal`&&n.setBottomTerminalOpen(!0),dW(t)},pW=(e,t)=>{let n=e.trim();if(!n)return!1;let r=Gu.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)},mW=e=>{let t=e.trim();if(!t)return{closed:!1,wasLastTab:!1};let n=Gu.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}},hW=()=>typeof window>`u`||window.parent===window||!sf(window.location.search)?!1:(window.parent.postMessage({type:rf},window.location.origin),!0),gW=()=>{let{isMobile:e,closeActiveContextPanelTab:t}=g.getState();if(e)return!1;let n=Wl();return n&&t(n)?!0:E()?(Se(`desktop_close_current_window`).catch(e=>{console.warn(`[keyboard-shortcuts] failed to close current window`,e)}),!0):!1},_W=({sessionId:e,surfaceKind:t,wiringCanAbort:n,primaryCanAbort:r,pendingSend:i=!1})=>e?i||n?!0:t!==`secondary`&&r:!1,vW=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)}},yW=()=>{let e=(0,Q.c)(69),{t}=Zt(),n=J(bW),r=J(xW),i=J(SW),a=J(CW),o=dn,s=g(wW),c=g(TW),l=g(EW),u=g(DW),d=g(OW),f=g(kW),p=g(AW),m=g(jW),h=g(MW),_=g(NW),v=g(PW),y=g(FW),b=g(IW),S=g(LW),C=g(RW),w=g(zW),T=g(BW),D=g(VW),O=g(HW),k=lt(UW),A=Gi(WW),{themeMode:j,setThemeMode:M}=Vs(),{working:N}=qN(),P=Z.useRef(null),F=Z.useRef(null),I=Z.useRef(null),L=Z.useRef(!1),R=Z.useRef(j),z,B;e[0]===j?(z=e[1],B=e[2]):(z=()=>{R.current=j},B=[j],e[0]=j,e[1]=z,e[2]=B),Z.useEffect(z,B);let V;e[3]===i?V=e[4]:(V=()=>{F.current&&=(clearTimeout(F.current),null),P.current=null,i()},e[3]=i,e[4]=V);let H=V,ee;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(ee=()=>{I.current&&=(clearTimeout(I.current),null),fm.getState().clear()},e[5]=ee):ee=e[5];let U=ee,te;e[6]===Symbol.for(`react.memo_cache_sentinel`)?(te=()=>{I.current&&=(clearTimeout(I.current),null);let e=fm.getState().arm(dm);I.current=setTimeout(()=>{let{expiresAt:e}=fm.getState();e&&Date.now()>=e&&fm.getState().clear(),I.current=null},Math.max(0,e-Date.now()))},e[6]=te):te=e[6];let W=te,ne;e[7]!==A?.id||e[8]!==A?.path||e[9]!==r||e[10]!==k||e[11]!==h||e[12]!==n||e[13]!==H||e[14]!==v||e[15]!==S||e[16]!==m||e[17]!==b||e[18]!==T||e[19]!==d||e[20]!==f||e[21]!==_||e[22]!==y||e[23]!==M||e[24]!==C||e[25]!==O||e[26]!==t||e[27]!==p||e[28]!==s||e[29]!==D||e[30]!==c||e[31]!==w||e[32]!==u||e[33]!==l||e[34]!==N?(ne=()=>{let e=e=>is(e,O),i=e=>ps(e,O),a=GW,j=[`[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(`,`),I=e=>e instanceof Element&&!!e.closest(j),z=qW,B=YW,V=XW,ee=async()=>{let e=xC(),n=e?DC(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;fa.error(n instanceof Error?n.message:t(`chat.chatInput.toast.compactFailed`))}return}let r=J.getState().currentSessionId;if(!r)return;let{currentProviderId:i,currentModelId:a}=ui.getState();await vW({sessionId:r,currentProviderId:i,currentModelId:a,waitForConnectionOrThrow:Ea,getAuthoritativeDirectoryForSession:J.getState().getAuthoritativeDirectoryForSession,summarizeSession:ZW,onCompactFailed:e=>{fa.error(e instanceof Error?e.message:t(`chat.chatInput.toast.compactFailed`))}})},te=t=>{let r=fm.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=()=>{L.current=!0,window.setTimeout(()=>{L.current=!1},0)};if(i&&us(t,i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),W();return}let r=t.key.toLowerCase();if(r===`escape`){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),U();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(),U();return}let{activeMainTab:a,isModelSelectorOpen:o,isAgentSelectorOpen:s}=g.getState(),c=bC(a)&&!V();if(r===`m`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),U(),window.requestAnimationFrame(()=>{b(!o,{instant:!0})});return}if(r===`a`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),U(),S(!s,{instant:!0});return}if(r===`n`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),U();let r=xC(),i=r?DC(r):null;i?i.shortcut(`new`):(v(`chat`),_(!1),n());return}if(r===`c`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),U(),ee(),B();return}t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),U(),B();return}if(!i||!us(t,i)||V())return;let{activeMainTab:o}=g.getState();bC(o)&&(t.preventDefault(),t.stopPropagation(),W())},ne=()=>fm.getState().pending||L.current,G=e=>{ne()&&e.preventDefault()},K=e=>{ne()&&(e.preventDefault(),e.stopPropagation())},re=t=>{if(a(t.target)){if(!x()&&us(t,e(`new_terminal_tab`))){let e=Wl();if(!e||!dW(e))return;t.preventDefault(),t.stopPropagation();return}if(!x()&&us(t,e(`previous_terminal_tab`))){let e=Wl();if(!e||!pW(e,-1))return;t.preventDefault(),t.stopPropagation();return}if(!x()&&us(t,e(`next_terminal_tab`))){let e=Wl();if(!e||!pW(e,1))return;t.preventDefault(),t.stopPropagation();return}if(us(t,e(`close_context_panel_tab`))){let e=Wl();if(!e)return;let{closed:n,wasLastTab:r}=mW(e);if(!n)return;if(t.preventDefault(),t.stopPropagation(),r){let e=g.getState();e.setBottomTerminalOpen(!1),e.activeMainTab===`terminal`&&e.setActiveMainTab(`chat`)}return}if(us(t,e(`toggle_terminal`))){let{isMobile:e}=g.getState();if(e)return;t.preventDefault(),t.stopPropagation(),p();return}if(us(t,e(`toggle_bottom_panel`))){let{isMobile:e}=g.getState();if(e)return;t.preventDefault(),t.stopPropagation(),p();return}if(us(t,e(`toggle_terminal_expanded`))){let{isMobile:e,isBottomTerminalExpanded:n}=g.getState();if(e)return;t.preventDefault(),t.stopPropagation(),m(!n);return}}},ie=QW,ae=t=>{if(t.defaultPrevented)return;if(us(t,e(`close_context_panel_tab`))){(hW()||gW())&&(t.preventDefault(),t.stopPropagation());return}if(a(t.target))return;let r=$W;if(r(t.target)&&t.ctrlKey&&!t.metaKey&&!t.shiftKey&&!t.altKey&&t.key.toLowerCase()===`t`){t.preventDefault(),ie();return}if(us(t,e(`open_command_palette`))){t.preventDefault(),s();return}if(us(t,e(`open_timeline_dialog`))){t.preventDefault(),C(!0);return}if(us(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}=g.getState();if(!n||h||x()||e!==`chat`||r||i||a||o||s||c||l||u)return;t.preventDefault(),w();return}if(us(t,e(`open_status`))){t.preventDefault(),OU();return}if(us(t,e(`open_help`))){t.preventDefault(),c();return}if(E()&&us(t,e(`new_mini_chat`))){t.preventDefault(),Se(`desktop_open_draft_mini_chat_window`,{directory:k||A?.path||``,projectId:A?.id??null}).catch(eG);return}let o=us(t,e(`new_chat`)),S=us(t,e(`new_chat_worktree`));if(o||S){if(t.preventDefault(),v(`chat`),_(!1),!x()&&S){rx();return}n();return}if(us(t,e(`cycle_theme`))){if(t.preventDefault(),mf()!==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(R.current)+1)%e.length;M(e[r]),requestAnimationFrame(()=>{typeof document>`u`||typeof window>`u`||(document.hasFocus()||window.focus(),n&&document.contains(n)&&n.focus({preventScroll:!0}))});return}if(Bs(t,`in`,e(`zoom_in`))){t.preventDefault(),tW();return}if(Bs(t,`out`,e(`zoom_out`))){t.preventDefault(),nW();return}if(us(t,e(`zoom_reset`))){t.preventDefault(),rW();return}if(us(t,e(`open_settings`))){t.preventDefault();let{isSettingsDialogOpen:e}=g.getState();y(!e);return}if(us(t,e(`toggle_sidebar`))){t.preventDefault();let{isMobile:e,isSessionSwitcherOpen:n}=g.getState();e?_(!n):l();return}if(us(t,e(`focus_input`))){t.preventDefault(),document.querySelector(`textarea[data-chat-input="true"]`)?.focus();return}let T=e(`cycle_agent`),O=T&&!T.includes(`shift`)?os(`shift+${T}`):``,j=O&&us(t,O)?-1:+!!us(t,T);if(j!==0){let{isSettingsDialogOpen:e,isCommandPaletteOpen:n,isHelpDialogOpen:i,isSessionSwitcherOpen:a,isAboutDialogOpen:o,activeMainTab:s}=g.getState();if(e||n||i||a||o||!bC(s)||!r(t.target))return;let c=xC(),l=c?DC(c):null;if(l){t.preventDefault(),l.shortcut(`cycle`,j);return}let u=ui.getState(),d=kr(u.getVisibleAgents(),u.currentAgentName,j);if(!d)return;t.preventDefault(),u.setAgent(d),g.getState().addRecentAgent(d);let f=J.getState().currentSessionId;f&&Nn.getState().saveSessionAgentSelection(f,d);return}if(i(`toggle_right_sidebar`).some(e=>us(t,e))){let{isMobile:e}=g.getState();if(e)return;t.preventDefault(),u();return}if(us(t,e(`open_right_sidebar_git`))){let{isMobile:e}=g.getState();if(e)return;t.preventDefault(),d(!0),f(`git`);return}if(us(t,e(`open_right_sidebar_files`))){let{isMobile:e}=g.getState();if(e)return;t.preventDefault(),d(!0),f(`files`);return}if(us(t,e(`cycle_right_sidebar_tab`))){let{isMobile:e,rightSidebarTab:n}=g.getState();if(e)return;let r=[`git`,`files`],i=r[(r.indexOf(n)+1)%r.length];t.preventDefault(),d(!0),f(i);return}let N=e=>GU(e,J.getState().currentSessionId,e=>{v(`chat`),_(!1),J.getState().setCurrentSession(e.sessionId,e.directory)});if(i(`previous_session`).some(e=>us(t,e))){t.preventDefault(),N(-1);return}if(i(`next_session`).some(e=>us(t,e))){t.preventDefault(),N(1);return}for(let n=1;n<=9;n+=1)if(us(t,e(`switch_tab_${n}`))){uW(n)&&t.preventDefault();return}if(us(t,e(`toggle_terminal`))){let{isMobile:e}=g.getState();if(e)return;t.preventDefault(),p();return}if(us(t,e(`open_new_terminal`))){let{isMobile:e}=g.getState();if(e||x())return;let n=Wl();if(!n||!fW(n))return;t.preventDefault();return}if(us(t,e(`toggle_bottom_panel`))){let{isMobile:e}=g.getState();if(e)return;t.preventDefault(),p();return}if(us(t,e(`toggle_terminal_expanded`))){let{isMobile:e,isBottomTerminalExpanded:n}=g.getState();if(e)return;t.preventDefault(),m(!n);return}if(us(t,e(`open_model_selector`))){let{isSettingsDialogOpen:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isAboutDialogOpen:a,activeMainTab:o,isModelSelectorOpen:s}=g.getState();if(e)return;let c=n||r||i||a,l=bC(o);if(c||!l)return;t.preventDefault(),b(!s,{instant:!0});return}if(us(t,e(`cycle_thinking_variant`))){ie()&&t.preventDefault();return}if(us(t,e(`cycle_favorite_model_forward`))||us(t,e(`cycle_favorite_model_backward`))){let{isSettingsDialogOpen:n,isCommandPaletteOpen:r,isHelpDialogOpen:i,isSessionSwitcherOpen:a,isAboutDialogOpen:o,activeMainTab:s,favoriteModels:c,addRecentModel:l}=g.getState();if(n)return;let u=r||i||a||o,d=bC(s);if(u||!d||c.length===0)return;t.preventDefault();let f=c.length,p=us(t,e(`cycle_favorite_model_forward`))?1:-1,m=xC();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=ui.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:_,providers:v,setProvider:y,setModel:b,setCurrentVariant:x}=ui.getState(),S=c[(c.findIndex(e=>e.providerID===h&&e.modelID===_)+p+f)%f];y(S.providerID),b(S.modelID);let C=v.find(e=>e.id===S.providerID)?.models?.find(e=>e.id===S.modelID),w=C?.variants?Object.keys(C.variants):[],T=S.variant!==void 0&&w.includes(S.variant)?S.variant:void 0;x(T),l(S.providerID,S.modelID,T);return}if(us(t,e(`expand_input`))){if(h)return;t.preventDefault(),D();return}if(us(t,e(`toggle_dictation`))){let{activeMainTab:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isSettingsDialogOpen:a}=g.getState();if(!bC(e)||n||r||i||a)return;t.preventDefault(),window.dispatchEvent(new CustomEvent(`openchamber:dictation-toggle`));return}},oe=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=I(t)||z(),{isSettingsDialogOpen:c,isCommandPaletteOpen:l,isHelpDialogOpen:u,isSessionSwitcherOpen:d,isAboutDialogOpen:f,isMultiRunLauncherOpen:p,isImagePreviewOpen:m,isPromptNavigatorPanelOpen:h}=g.getState();if(n||a||s){H();return}if(h){e.preventDefault(),T(!1),H();return}if(c){e.preventDefault(),y(!1),H();return}if(i){H();return}if(l||u||d||f||p||m){H();return}let _=xC(),v=_?DC(_):null,b=_?.sessionID??J.getState().currentSessionId,x=!!(b&&J.getState().pendingSendMessageIDs.get(b));if(!_W({sessionId:b,surfaceKind:_?.kind,wiringCanAbort:v?.canAbort,primaryCanAbort:N.canAbort,pendingSend:x})){H();return}e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();let S=Date.now(),C=P.current;if(C&&S<C){H(),v?v.abort():(b&&br(b),o(b??``));return}let w=_?.kind===`secondary`?S+3e3:r(3e3)??S+3e3;P.current=w,F.current&&clearTimeout(F.current);let E=Math.max(w-S,0);F.current=setTimeout(()=>{P.current&&Date.now()>=P.current&&H()},E||0)};return window.addEventListener(`keydown`,te,!0),window.addEventListener(`beforeinput`,G,!0),window.addEventListener(`compositionstart`,K,!0),window.addEventListener(`compositionupdate`,K,!0),window.addEventListener(`compositionend`,K,!0),window.addEventListener(`keydown`,re,!0),window.addEventListener(`keydown`,oe,!0),window.addEventListener(`keydown`,ae),()=>{window.removeEventListener(`keydown`,te,!0),window.removeEventListener(`beforeinput`,G,!0),window.removeEventListener(`compositionstart`,K,!0),window.removeEventListener(`compositionupdate`,K,!0),window.removeEventListener(`compositionend`,K,!0),window.removeEventListener(`keydown`,re,!0),window.removeEventListener(`keydown`,oe,!0),window.removeEventListener(`keydown`,ae)}},e[7]=A?.id,e[8]=A?.path,e[9]=r,e[10]=k,e[11]=h,e[12]=n,e[13]=H,e[14]=v,e[15]=S,e[16]=m,e[17]=b,e[18]=T,e[19]=d,e[20]=f,e[21]=_,e[22]=y,e[23]=M,e[24]=C,e[25]=O,e[26]=t,e[27]=p,e[28]=s,e[29]=D,e[30]=c,e[31]=w,e[32]=u,e[33]=l,e[34]=N,e[35]=ne):ne=e[35];let G=A?.id,K=A?.path,re;e[36]!==r||e[37]!==k||e[38]!==a||e[39]!==h||e[40]!==n||e[41]!==H||e[42]!==v||e[43]!==S||e[44]!==m||e[45]!==b||e[46]!==T||e[47]!==d||e[48]!==f||e[49]!==_||e[50]!==y||e[51]!==M||e[52]!==C||e[53]!==O||e[54]!==t||e[55]!==G||e[56]!==K||e[57]!==p||e[58]!==s||e[59]!==D||e[60]!==c||e[61]!==w||e[62]!==u||e[63]!==l||e[64]!==N?(re=[n,o,s,c,l,u,d,f,p,m,h,_,v,y,b,S,C,w,T,D,M,N,r,H,W,U,a,k,G,K,O,t],e[36]=r,e[37]=k,e[38]=a,e[39]=h,e[40]=n,e[41]=H,e[42]=v,e[43]=S,e[44]=m,e[45]=b,e[46]=T,e[47]=d,e[48]=f,e[49]=_,e[50]=y,e[51]=M,e[52]=C,e[53]=O,e[54]=t,e[55]=G,e[56]=K,e[57]=p,e[58]=s,e[59]=D,e[60]=c,e[61]=w,e[62]=u,e[63]=l,e[64]=N,e[65]=re):re=e[65],Z.useEffect(ne,re);let ie,ae;e[66]===H?(ie=e[67],ae=e[68]):(ae=()=>()=>{H(),U()},ie=[H,U],e[66]=H,e[67]=ie,e[68]=ae),Z.useEffect(ae,ie)};function bW(e){return e.openNewSessionDraft}function xW(e){return e.armAbortPrompt}function SW(e){return e.clearAbortPrompt}function CW(e){return e.currentSessionId}function wW(e){return e.toggleCommandPalette}function TW(e){return e.toggleHelpDialog}function EW(e){return e.toggleSidebar}function DW(e){return e.toggleRightSidebar}function OW(e){return e.setRightSidebarOpen}function kW(e){return e.setRightSidebarTab}function AW(e){return e.toggleBottomTerminal}function jW(e){return e.setBottomTerminalExpanded}function MW(e){return e.isMobile}function NW(e){return e.setSessionSwitcherOpen}function PW(e){return e.setActiveMainTab}function FW(e){return e.setSettingsDialogOpen}function IW(e){return e.setModelSelectorOpen}function LW(e){return e.setAgentSelectorOpen}function RW(e){return e.setTimelineDialogOpen}function zW(e){return e.togglePromptNavigatorPanel}function BW(e){return e.setPromptNavigatorPanelOpen}function VW(e){return e.toggleExpandedInput}function HW(e){return e.shortcutOverrides}function UW(e){return e.currentDirectory}function WW(e){return e.getActiveProject()}function GW(e){return e instanceof Element&&!!(e.closest(`[data-terminal-view="true"]`)||e.closest(`.terminal-viewport-container`)||e.getAttribute(`data-terminal-hidden-input`)===`true`)}function KW(e){return e.getClientRects().length>0}function qW(){let e=document.querySelectorAll(`[data-slot="dropdown-menu-content"], [data-slot="select-content"], [role="listbox"], [role="menu"], [data-radix-popper-content-wrapper]`);return Array.from(e).some(KW)}function JW(){document.querySelector(`textarea[data-chat-input="true"]`)?.focus({preventScroll:!0})}function YW(){window.requestAnimationFrame(JW)}function XW(){let{isSettingsDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isSessionSwitcherOpen:r,isAboutDialogOpen:i}=g.getState();return e||t||n||r||i}function ZW(e,t,n,r){return mt.summarizeSession(e,t,n,r)}function QW(){let{isSettingsDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isSessionSwitcherOpen:r,isAboutDialogOpen:i,activeMainTab:a}=g.getState();if(e||t||n||r||i||!bC(a))return!1;let o=xC();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=ui.getState();if(s.getCurrentModelVariants().length===0)return!1;s.cycleCurrentVariant();let c=ui.getState().currentVariant,l=J.getState().currentSessionId,u=ui.getState().currentAgentName,d=ui.getState().currentProviderId,f=ui.getState().currentModelId;return l&&u&&d&&f&&Nn.getState().saveAgentModelVariantForSession(l,u,d,f,c),u&&d&&f&&ui.getState().saveAgentModelSelection(u,d,f,c),!0}function $W(e){return e instanceof HTMLTextAreaElement&&e.getAttribute(`data-chat-input`)===`true`}function eG(e){console.warn(`[keyboard-shortcuts] failed to open draft mini chat window`,e)}var tG=3,nG=(e,t)=>{if(typeof e!=`string`)return t;let n=e.trim().replace(/\s+/g,` `);return n?n.slice(0,48):t},rG=(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:nG(e.title,`Session ${r.length+1}`)}),r.length>=tG))break}return r},iG=()=>{let e=(0,Q.c)(9),t=ua(),n=J(aG),r;e[0]!==n||e[1]!==t?(r=rG(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`||!oe())){try{i.length===0?localStorage.removeItem(Ts):localStorage.setItem(Ts,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 aG(e){return e.currentSessionId}var oG=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:`0px`,sG=(e,t,n,r)=>{e.style.setProperty(`--oc-wco-left-inset`,oG(t)),e.style.setProperty(`--oc-wco-right-inset`,oG(n)),e.style.setProperty(`--oc-wco-titlebar-height`,oG(r))},cG=()=>{let e=(0,Q.c)(1),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0],Z.useEffect(lG,t)};function lG(){if(typeof window>`u`||!oe())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){sG(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));sG(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),sG(e,0,0,0)}}var uG=null,dG=e=>{let t=uG;return uG=e,()=>{uG===e&&(uG=t)}},fG=()=>({orderByProject:{},pendingProjectIDs:{}}),pG=(e,t)=>!!(e&&e.length===t.length&&e.every((e,n)=>e===t[n])),mG=r(),hG=Ye()(Xe((e,t)=>({runtimeIdentity:mG,...fG(),serverRevisionByProject:{},deferredServerOrderByProject:{},runtimeOrdersByIdentity:{[mG]:fG()},activateWorktreeOrderRuntime:t=>e(e=>{if(e.runtimeIdentity===t)return e;let n=e.runtimeOrdersByIdentity[t]??fG();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=pG(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&&uG?.(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(pG(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&&!pG(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:{[mG]:{orderByProject:t.orderByProject??{},pendingProjectIDs:t.pendingProjectIDs??{}}}}},merge:(e,t)=>{let n=e.runtimeOrdersByIdentity??t.runtimeOrdersByIdentity,r=n[t.runtimeIdentity]??fG();return{...t,runtimeOrdersByIdentity:n,orderByProject:r.orderByProject,pendingProjectIDs:r.pendingProjectIDs}}})),gG=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``),_G=(e,t)=>{if(!e||e.length===0)return t;let n=new Map(e.map((e,t)=>[gG(e),t]));return t.map((e,t)=>({worktree:e,index:t})).sort((e,t)=>(n.get(gG(e.worktree.path))??2**53-1)-(n.get(gG(t.worktree.path))??2**53-1)||e.index-t.index).map(e=>e.worktree)},vG=3e4,yG=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||`/`,bG=e=>e instanceof Fr?e.status===501?`unsupported`:e.status>=400&&e.status<500&&e.status!==408&&e.status!==429&&e.code!==`revision_conflict`?`permanent`:`retry`:`retry`,xG=(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})}),SG=(e,t)=>e.then(e=>{if(t?.aborted)throw new DOMException(`Aborted`,`AbortError`);return e}),CG={fetchSnapshot:e=>SG(Si(Ee),e),refreshSnapshot:e=>SG(eo(Ee),e),fetchOrder:Ya,setOrder:Br,waitInvalidation:jn,captureRuntime:()=>({transportIdentity:r(),generation:v()}),isCurrent:e=>e.transportIdentity===r()&&e.generation===v(),sleep:xG,createRequestID:()=>typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`worktree-order-${Date.now()}-${Math.random().toString(36).slice(2)}`},wG=new Map,TG=()=>{for(let e of wG.values())e.controller.abort();wG.clear()},EG=(e,t,n,r=CG)=>{wG.get(e)?.controller.abort();let i={projectDirectory:yG(t),orderedPaths:[...n],capture:r.captureRuntime(),controller:new AbortController,backoffMs:500,running:!1};wG.set(e,i),DG(e,r)},DG=async(e,t=CG)=>{let n=wG.get(e);if(!(!n||n.running)){n.running=!0;try{for(;;){let n=wG.get(e);if(!n||!t.isCurrent(n.capture)||n.controller.signal.aborted)return;let r=hG.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)||wG.get(e)!==n)return;let a=i.worktreeOrder??{projectDirectory:n.projectDirectory,orderedPaths:n.orderedPaths,revision:i.revision};hG.getState().setServerRevision(e,a.revision),hG.getState().resolvePendingWorktreeOrder(e,a.revision),wG.delete(e);return}catch(r){if(n.controller.signal.aborted||!t.isCurrent(n.capture)||wG.get(e)!==n)return;if(r instanceof Fr&&r.code===`revision_conflict`)try{let r=await t.fetchOrder(n.projectDirectory,n.controller.signal);if(wG.get(e)!==n||!t.isCurrent(n.capture))return;hG.getState().applyServerWorktreeOrder(e,r.orderedPaths,r.revision),n.expectedRevision=void 0,n.requestID=void 0,n.backoffMs=500;continue}catch(e){if(bG(e)!==`retry`)return}else if(bG(r)!==`retry`)return;if(await t.sleep(n.backoffMs,n.controller.signal).catch(()=>{}),n.backoffMs=Math.min(n.backoffMs*2,vG),n.controller.signal.aborted)return}}}finally{wG.get(e)===n&&(!t.isCurrent(n.capture)||n.controller.signal.aborted)&&wG.delete(e),wG.get(e)===n&&(n.running=!1)}}},OG=(e,t,n,r)=>{let i=new Map(t.map(e=>[yG(e.path),e.id]));for(let t of e){let e=i.get(yG(t.projectDirectory));e&&r.isCurrent(n)&&hG.getState().applyServerWorktreeOrder(e,t.orderedPaths,t.revision)}},kG=(e,t=CG)=>{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();OG(r.worktreeOrders,o,a,t);let s=new Set(r.worktreeOrders.map(e=>yG(e.projectDirectory)));for(let e of o){let n=hG.getState(),r=n.orderByProject[e.id];n.pendingProjectIDs[e.id]?EG(e.id,e.path,r??[],t):r?.length&&!s.has(yG(e.path))&&(n.markPendingWorktreeOrder(e.id),EG(e.id,e.path,r,t))}break}catch(e){if(bG(e)!==`retry`)return;await t.sleep(r,i).catch(()=>{}),r=Math.min(r*2,vG)}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,OG(s.worktreeOrders,e(),a,t),r=500}catch(e){if(bG(e)!==`retry`)return;await t.sleep(r,i).catch(()=>{}),r=Math.min(r*2,vG)}})()},stop:r}},AG=()=>{let e=(0,Q.c)(2),t=Gi(MG),n;e[0]===t?n=e[1]:(n=[t],e[0]=t,e[1]=n),Z.useEffect(FG,n)};function jG(e){return[e.id,yG(e.path)]}function MG(e){return JSON.stringify(e.projects.map(jG))}function NG(e,t,n){return EG(e,t,n)}function PG(){return Gi.getState().projects}function FG(){let e=r();hG.getState().activateWorktreeOrderRuntime(e);let n=dG(NG),i=kG(PG);i.start();let o=t(e=>{a(e)&&(TG(),hG.getState().activateWorktreeOrderRuntime(r()),i.start())});return()=>{n(),o(),i.stop(),TG()}}var IG=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||`/`,LG=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=IG(t);return e.getProjects().find(e=>IG(e.path)===n)},g=(n,i=150)=>{let s=IG(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(IG(e));if(e.needsSessionSync)for(let t of i.worktrees){let n=IG(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])=>IG(e)===n||t.some(e=>IG(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(IG(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=IG(n.path),i=t.get(r)?.some(t=>IG(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${IG(e.path)}`).sort().join(`
6587
6587
  `),m.push(e.subscribeProjects(()=>{let t=e.getProjects().map(e=>`${e.id}\u0000${IG(e.path)}`).sort().join(`
6588
6588
  `);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}},RG=null,zG=0,BG=()=>(RG||=LG({isVSCode:x,getProjects:()=>Gi.getState().projects,getCatalog:()=>J.getState().availableWorktreesByProject,getActiveDirectories:()=>{let e=Ai.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=>!Ai.getState().loadedDirectories.has(IG(e)),refresh:Wo,syncAdded:e=>Ba(e,Ai.getState().activeSessions),subscribeProjects:e=>Gi.subscribe(e),subscribeCatalog:e=>J.subscribe((t,n)=>{t.availableWorktreesByProject!==n.availableWorktreesByProject&&e()}),subscribeSessions:e=>Ai.subscribe((t,n)=>{(t.activeSessions!==n.activeSessions||t.cachedDirectories!==n.cachedDirectories)&&e()}),subscribeEvents:_r,subscribeRuntime:e=>t(t=>e(a(t))),generation:v,setTimer:(e,t)=>globalThis.setTimeout(e,t),clearTimer:e=>globalThis.clearTimeout(e)}),zG+=1,RG.start(),()=>{zG=Math.max(0,zG-1),zG===0&&RG?.stop()}),VG=`openchamber:mini-chat-presence`,HG=()=>{let e=jm(),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(()=>{Xr(e=>t.current(e),e=>n.current(e),e=>r.current(e))},[]),Z.useEffect(()=>BG(),[]),null},UG=()=>{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(YG,t),null};function WG(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),Ms(r);let i=Z.useSyncExternalStore(pn,ro,ro);Bn(n&&i===`legacy-enabled`),Wn();let a;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=[],t[2]=a):a=t[2],Z.useEffect(GG,a);let o;return t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,$.jsx)(HG,{}),t[3]=o):o=t[3],o}function GG(){let e=mi(),t=nr();e.start(),t.start();let n=Wa(e);return()=>{n(),t.stop(),e.stop()}}function KG(e){let t=(0,Q.c)(6),{embeddedBackgroundWorkEnabled:n}=e;iG(),cG(),yW(),AG();let r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0],Z.useEffect(qG,r);let i;t[1]===n?i=t[2]:(i=(0,$.jsx)(WG,{embeddedBackgroundWorkEnabled:n}),t[1]=n,t[2]=i);let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(UG,{}),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 qG(){eW()}function JG(e){let t=e.data;if(t?.type!==`mini-chat-session-presence`||!t.sessionId||!t.directory)return;let n=t.viewed!==!1;so(t.directory,t.sessionId,n),n&&ra(t.sessionId)}function YG(){if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(VG);return e.onmessage=JG,()=>e.close()}var XG=new Set,ZG=new Map,QG=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace(`%40`,`@`).replace(`%2F`,`/`)}/files/${e.filePrefix}-latin-${t}-normal.woff2`,$G=(e,t)=>{let n=`${e.family}:${t}`;if(XG.has(n))return Promise.resolve();let r=ZG.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(${QG(e,t)}) format('woff2')`,{style:`normal`,weight:String(t),display:`swap`});document.fonts.add(i);let a=i.load().then(()=>{XG.add(n)}).catch(n=>{document.fonts.delete(i),console.warn(`Failed to load font: ${e.family} ${t}`,n)}).finally(()=>{ZG.delete(n)});return ZG.set(n,a),a},eK=e=>e?Promise.all(e.weights.map(t=>$G(e,t))).then(()=>void 0):Promise.resolve(),tK=e=>eK(u[e]?.source),nK=e=>eK(h[e]?.source),rK={family:`Syne`,packageName:`@fontsource/syne`,filePrefix:`syne`,weights:[700]},iK=()=>eK(rK);function aK(){let e=(0,Q.c)(4),{uiFont:t,monoFont:n}=Ku(),r,i;e[0]!==n||e[1]!==t?(r=()=>{if(typeof document>`u`)return;let e=document.documentElement,r=u[t]?.stack??u.system.stack,i=h[n]?.stack??h[`system-mono`].stack;tK(t),nK(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{Kx as $,YH as A,jf as At,EB as B,Qu as Bt,hU as C,jm as Ct,rU as D,Wf as Dt,lU as E,Jf as Et,$H as F,uf as Ft,_R as G,Wz as H,Zu as Ht,dU as I,ff as It,JA as J,JM as K,oU as L,Jd as Lt,uU as M,rf as Mt,eU as N,af as Nt,iU as O,Uf as Ot,ZH as P,of as Pt,kT as Q,KH as R,qd as Rt,yU as S,Lm as St,cU as T,cp as Tt,Cz as U,qu as Ut,CB as V,Yu as Vt,_z as W,BA as X,XA as Y,wA as Z,jU as _,Z_ as _t,WG as a,vx as at,MU as b,xh as bt,fW as c,Vb as ct,lW as d,xb as dt,Fx as et,rW as f,hb as ft,IU as g,cv as gt,GU as h,Ev as ht,KG as i,px as it,aU as j,kf as jt,XH as k,zf as kt,sW as l,Hb as lt,nW as m,Ry as mt,iK as n,hx as nt,_G as o,mx as ot,tW as p,Fy as pt,YA as q,tK as r,gx as rt,hG as s,rx as st,aK as t,fx as tt,cW as u,Sb as ut,AU as v,Q_ as vt,sU as w,hp as wt,OU as x,$m as xt,kU as y,U_ as yt,uH as z,xd as zt};