@pi-chamber/web 1.0.6-rc.3 → 1.0.6-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramView-Dq5w8TCG.js → DiagramView--XO16VPB.js} +1 -1
- package/dist/assets/DiffView-Duy2_7Gp.js +18 -0
- package/dist/assets/{FileSaveConflictDialog-dFqLbFzT.js → FileSaveConflictDialog-B1DvL9zy.js} +2 -2
- package/dist/assets/FilesView-CjjPpE4c.js +6 -0
- package/dist/assets/{GitHubDetailScaffold-B2HRjT8V.js → GitHubDetailScaffold-DqxAKqCT.js} +4 -4
- package/dist/assets/{GitHubLinkPicker-D7I3J9_O.js → GitHubLinkPicker-ELF_chia.js} +1 -1
- package/dist/assets/GitHubListPrimitives-C2nGTntk.js +1 -0
- package/dist/assets/GitView-5fIq2nzM.js +9 -0
- package/dist/assets/IssuesSurface-Dq5A_bWq.js +7 -0
- package/dist/assets/{JsonTreeView-BJr5kBg4.js → JsonTreeView-BjFFSUwi.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-B9Cu4TCh.js +12 -0
- package/dist/assets/{PatchDiff-B6RBZULC.js → PatchDiff-CTqTTcg7.js} +1 -1
- package/dist/assets/{PierreDiffViewer-YJJQkE7t.js → PierreDiffViewer-H2f4pJ1k.js} +15 -3
- package/dist/assets/PullRequestsSurface-DPpb2RW_.js +2 -0
- package/dist/assets/SessionSwitcherContent-B5DaBWZU.js +1 -0
- package/dist/assets/{SessionSwitcherDropdown-CEAid1Bd.js → SessionSwitcherDropdown-D86FaZg_.js} +2 -2
- package/dist/assets/SessionUnreadDot-CY9-1iV2.js +1 -0
- package/dist/assets/SettingsView-CiIuOi_E.js +6 -0
- package/dist/assets/{SettingsWindow-5dK-buUn.js → SettingsWindow-Bw1dUoJ1.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-p7EbL2-E.js → StickyHorizontalScrollbar-DNsbTLS7.js} +1 -1
- package/dist/assets/{ToolOutputDialog-gITobhpo.js → ToolOutputDialog-aR4kcgKL.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-nOJxBl-Y.js → ToolPartDiffPreview-B_wWmhtE.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-BmJk6XJm.js → VirtualizedFileDiff-BYby097w.js} +4 -4
- package/dist/assets/{Virtualizer-DNJrJKVb.js → Virtualizer-okhy9Aq3.js} +1 -1
- package/dist/assets/{collapsible-0yfy07W2.js → collapsible-Dz0bPrJ_.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-BCFpa-1q.js → computeVirtualFileMetrics-8MuwxSC6.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-BCi5nTZp.js → contextFileOpenGuard-fZ2NIQMQ.js} +1 -1
- package/dist/assets/fileTreeStatus-BzhMMLA9.js +7 -0
- package/dist/assets/gitStatusPredicates-Cyh9UhYX.js +1 -0
- package/dist/assets/{githubLink-CCmFsyTF.js → githubLink-D2PznPcI.js} +2 -2
- package/dist/assets/{index-BaeFf5Q8.js → index-BX5pAOQX.js} +1 -1
- package/dist/assets/index-Cs2nBW_t.js +11 -0
- package/dist/assets/index-tmO0fZa4.css +1 -0
- package/dist/assets/main-7vBNPBMb.js +137 -0
- package/dist/assets/{main-CgXs2e27.js → main-BI6qe8pz.js} +2 -2
- package/dist/assets/{markdownCore-DTNVLpYS.js → markdownCore-D5jiabKe.js} +1 -1
- package/dist/assets/{miniChat-CrAin_em.js → miniChat-B3up4Bnz.js} +2 -2
- package/dist/assets/{mobile-EK9oTupb.js → mobile-B4vLFgBc.js} +2 -2
- package/dist/assets/{nativeFileSave-Bhafll_7.js → nativeFileSave-DpBH1Sa3.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-BoN1cyoG.js → pi-session-focus-preference-BrB72skF.js} +3 -3
- package/dist/assets/{renderDiffWithHighlighter-DixZh5Zd.js → renderDiffWithHighlighter-B6T04JGG.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-CX10w321.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-s6fQq9eg.js → renderFileWithHighlighter-DtAcGyJr.js} +1 -1
- package/dist/assets/renderMobileApp-C9n-BhPZ.js +11 -0
- package/dist/assets/runtimeEndpointReset-aGyXPXPs.js +62 -0
- package/dist/assets/{runtimeSurface-CJN1oo_1.js → runtimeSurface-DiP2a57a.js} +1 -1
- package/dist/assets/useAppFontEffects-Oyin3dgQ.js +215 -0
- package/dist/assets/useGitHubRemoteSearch-CZ9Hauw0.js +1 -0
- package/dist/assets/useSwitcherItems-BSqDA1IF.js +1 -0
- package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js → vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js} +1 -1
- package/dist/assets/{vendor-base-ui-C7vVMZTg.js → vendor-base-ui-BCqPBzDj.js} +1 -1
- package/dist/assets/{vendor-boot-CoTxysn6.js → vendor-boot-3SaHYVb1.js} +18 -18
- package/dist/assets/{vendor-capacitor-app-NX6DULfp.js → vendor-capacitor-app-NbQ-WiPS.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-DJD81I9f.js → vendor-capacitor-keyboard-CgrHt8iN.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-DV24OoQV.js → vendor-capacitor-status-bar-CWt0OF5t.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-qsuH4Dh-.js → vendor-codemirror-autocomplete-WThuuUAz.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-ZHWyBf7j.js → vendor-codemirror-lang-angular-BbLGCxF6.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-pCTOmv-k.js → vendor-codemirror-lang-cpp-Cceks-9O.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-2bFuyM70.js → vendor-codemirror-lang-css-D1wpUg3Z.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-DrG_c7D7.js → vendor-codemirror-lang-go-Cv0zXHHM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-BV8lrR8v.js → vendor-codemirror-lang-html-DbL8oT9H.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-DrsvH6T2.js → vendor-codemirror-lang-java-CNugenuC.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-Dkzl3s07.js → vendor-codemirror-lang-javascript-Bx_FIyZF.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-8Nn3bnoP.js → vendor-codemirror-lang-jinja-DDGjB3Zq.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-CsdmtHhi.js → vendor-codemirror-lang-json-DIvqf9Pb.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-DJuZ4cZe.js → vendor-codemirror-lang-less-D8r9dGG1.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-D2RO-Pzr.js → vendor-codemirror-lang-liquid-B24mguYi.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-C0Zu3b3n.js → vendor-codemirror-lang-markdown-v3yG2sbf.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-CuDtt2Zj.js → vendor-codemirror-lang-php-BcZGalqy.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-Cv2exx_M.js → vendor-codemirror-lang-python-b-JqEwQy.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-C4TxJ6Rg.js → vendor-codemirror-lang-rust-B1uZxDW-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-BmtPz8kf.js → vendor-codemirror-lang-sass-DqPrngKp.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-BF1ZaXqJ.js → vendor-codemirror-lang-sql-UyCnpt-k.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-DZgXrP2k.js → vendor-codemirror-lang-vue-xDwYkovV.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-DsnaGtL_.js → vendor-codemirror-lang-wast-CF3169p_.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-D8DzzFat.js → vendor-codemirror-lang-xml-FCtVhuOb.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-D5hBv7m6.js → vendor-codemirror-lang-yaml-g0sPmAnv.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-vn2RyN9T.js → vendor-codemirror-language-data-B03xgzP2.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-BVCYIV0D.js → vendor-codemirror-search-Dw3Wpu15.js} +1 -1
- package/dist/assets/{vendor-lezer-cpp-vqXSn3lv.js → vendor-lezer-cpp-Cu3E-KUI.js} +1 -1
- package/dist/assets/{vendor-lezer-css-JnEzSyZR.js → vendor-lezer-css-Cb8vp67u.js} +1 -1
- package/dist/assets/{vendor-lezer-go-dD2gQMIL.js → vendor-lezer-go-BTsIaOm7.js} +1 -1
- package/dist/assets/{vendor-lezer-html-Cr3U-1pu.js → vendor-lezer-html-UQMsUwj-.js} +1 -1
- package/dist/assets/{vendor-lezer-java-CRM0IMCo.js → vendor-lezer-java-BIWrFrAx.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-B3s21DIS.js → vendor-lezer-javascript-BH2Etgoy.js} +1 -1
- package/dist/assets/{vendor-lezer-json-DPFM6EBV.js → vendor-lezer-json-CE-QUCwM.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-Bllrq8hY.js → vendor-lezer-lr-HY6Yc0Vr.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-6-3PLvXG.js → vendor-lezer-markdown-xFL3Evwf.js} +1 -1
- package/dist/assets/{vendor-lezer-php-DOyzfHRl.js → vendor-lezer-php-Cr_mQGrG.js} +1 -1
- package/dist/assets/{vendor-lezer-python-CdHdN5qt.js → vendor-lezer-python-BNRFWCb0.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-CqnW8EMH.js → vendor-lezer-rust-BvfOK5cU.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-BbcF4y6A.js → vendor-lezer-sass-qoxiLisk.js} +1 -1
- package/dist/assets/{vendor-lezer-xml-C31AyWoo.js → vendor-lezer-xml--x8SSpqU.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-Cv908yC2.js → vendor-lezer-yaml-BDo1JaEr.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-Cwhyn_5f.js → vendor-replit-codemirror-vim-D1Fe7FiY.js} +1 -1
- package/dist/assets/{web-components-Bz5oGa3p.js → web-components-CkTNGkJ2.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/git/DOCUMENTATION.md +1 -0
- package/server/lib/git/routes.js +14 -0
- package/server/lib/git/routes.test.js +37 -0
- package/server/lib/git/service.js +27 -0
- package/server/lib/git/service.test.js +32 -0
- package/server/lib/pi/archive-store.js +38 -10
- package/server/lib/pi/archive-store.test.js +10 -0
- package/server/lib/pi/routes.js +107 -2
- package/server/lib/pi/routes.test.js +255 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -1
- package/server/lib/pi/session-daemon/session-daemon-engines.test.js +18 -0
- package/server/lib/pi/session-daemon/session-daemon.js +24 -1
- package/server/lib/pi/session-shelf-store.js +252 -0
- package/server/lib/pi/session-shelf-store.test.js +174 -0
- package/server/lib/pi/ui-settings-store.js +60 -0
- package/server/lib/pi/ui-settings-store.test.js +105 -6
- package/dist/assets/DiffView-CFIjN2zy.js +0 -18
- package/dist/assets/FilesView-D0b2mEKA.js +0 -6
- package/dist/assets/GitHubListPrimitives-Dw5LAmzm.js +0 -1
- package/dist/assets/GitView-Dhr7qVeI.js +0 -9
- package/dist/assets/IssuesSurface-Bya7OsRl.js +0 -7
- package/dist/assets/MarkdownRendererImpl-DadkFPCz.js +0 -12
- package/dist/assets/PullRequestsSurface-D8JpzP5l.js +0 -2
- package/dist/assets/SessionSwitcherContent-CJ6C2ZKG.js +0 -1
- package/dist/assets/SessionUnreadDot-I1_tmqY9.js +0 -1
- package/dist/assets/SettingsView-B-b76XDV.js +0 -6
- package/dist/assets/gitStatusPredicates-BQOqDJU1.js +0 -1
- package/dist/assets/index-C2ISrmRR.js +0 -11
- package/dist/assets/index-DgwThEwf.css +0 -1
- package/dist/assets/main-DoVzQV56.js +0 -137
- package/dist/assets/renderElectronMiniChatApp-0MqKeGfI.js +0 -2
- package/dist/assets/renderMobileApp-BLoXL_J8.js +0 -11
- package/dist/assets/runtimeEndpointReset-Bv2Y1fMm.js +0 -62
- package/dist/assets/useAppFontEffects-D2xXdmYC.js +0 -215
- package/dist/assets/useFilesViewSearch-BKotcAUN.js +0 -7
- package/dist/assets/useGitHubRemoteSearch-CZ92xKSw.js +0 -1
- package/dist/assets/useSwitcherItems-BfA4omGb.js +0 -1
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-sztndhZI.js","assets/vendor-react-Bz1tRBxM.js","assets/document-attachments-CZl9rK1z.js","assets/vendor-fflate-C7GOKjkv.js","assets/vendor-capacitor-status-bar-CWt0OF5t.js","assets/vendor-boot-3SaHYVb1.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-capacitor-app-NbQ-WiPS.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-keyboard-CgrHt8iN.js","assets/permissionStore-zIpxq9Pq.js","assets/vendor-zustand-CXhN0IMY.js","assets/MarkdownRendererImpl-B9Cu4TCh.js","assets/vendor-morphdom-B7dS_VPB.js","assets/vendor-beautiful-mermaid-b48gT2g0.js","assets/vendor-elkjs-D1S1RCAO.js","assets/vendor-entities-C3BA0AJP.js","assets/index-Cs2nBW_t.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-tmO0fZa4.css","assets/markdownCore-D5jiabKe.js","assets/vendor-marked-Be78pDn1.js","assets/vendor-dompurify-BGCr_sdL.js","assets/vendor-remend-DcBOpbSu.js","assets/registerCustomTheme-C-h6lsYW.js","assets/themeResolver-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/nativeFileSave-DpBH1Sa3.js","assets/runtimeSurface-DiP2a57a.js","assets/vendor-codemirror-lang-javascript-Bx_FIyZF.js","assets/vendor-lezer-javascript-BH2Etgoy.js","assets/vendor-lezer-lr-HY6Yc0Vr.js","assets/vendor-codemirror-autocomplete-WThuuUAz.js","assets/vendor-codemirror-lang-json-DIvqf9Pb.js","assets/vendor-lezer-json-CE-QUCwM.js","assets/vendor-codemirror-lang-css-D1wpUg3Z.js","assets/vendor-lezer-css-Cb8vp67u.js","assets/vendor-codemirror-lang-html-DbL8oT9H.js","assets/vendor-lezer-html-UQMsUwj-.js","assets/vendor-codemirror-lang-markdown-v3yG2sbf.js","assets/vendor-lezer-markdown-xFL3Evwf.js","assets/vendor-codemirror-lang-python-b-JqEwQy.js","assets/vendor-lezer-python-BNRFWCb0.js","assets/GitHubLinkPicker-ELF_chia.js","assets/GitHubListPrimitives-C2nGTntk.js","assets/GitHubDetailScaffold-DqxAKqCT.js","assets/githubLink-D2PznPcI.js","assets/ToolOutputDialog-aR4kcgKL.js","assets/JsonTreeView-BjFFSUwi.js","assets/web-components-CkTNGkJ2.js","assets/computeVirtualFileMetrics-8MuwxSC6.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/Virtualizer-okhy9Aq3.js","assets/renderFileWithHighlighter-DtAcGyJr.js","assets/PatchDiff-CTqTTcg7.js","assets/VirtualizedFileDiff-BYby097w.js","assets/renderDiffWithHighlighter-B6T04JGG.js","assets/vendor-diff-C3JhlQdm.js","assets/appThemeRegistry-Ca8eGRB9.js","assets/ToolPartDiffPreview-B_wWmhtE.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{av as Vr,a as xt,a1 as dr,aw as xS,ax as bS,ay as Kl,az as Dh,aA as Gl,aB as _5,aC as j5,x as Ie,aD as at,aE as T5,e as Gt,n as ce,u as nt,z as Rt,aF as pm,w as A5,V as $r,k as qd,aG as wS,v as zr,b as Y,aH as mm,aI as Wd,h as re,aJ as Xo,J as N5,aK as gm,aL as ft,p as en,aM as Kd,aN as Oh,r as Rr,aO as SS,aP as CS,aQ as kS,S as MS,aR as IS,aa as Jo,aS as qg,aT as ES,aU as _S,aV as jS,A as TS,aW as AS,t as NS,aX as LS,aY as Zu,aZ as Wg,a_ as RS,f as R,ai as PS,a$ as Pr,aj as DS,al as gn,ah as ym,b0 as Zl,b1 as OS,b2 as Kg,am as Wn,b3 as HS,b4 as gl,s as yl,b5 as Yu,b6 as Xu,b7 as Gg,b8 as FS,b9 as BS,ak as VS,ba as $S,bb as zS,bc as US,bd as qS,m as WS,be as Zg,bf as KS,bg as Yg,bh as GS,i as lr,bi as vm,d as ZS,bj as YS,bk as XS,bl as JS,bm as Yl,bn as QS,P as eC,bo as Xg,bp as Jg,j as gs,bq as L5,br as Ji,bs as tC,ao as Tt,a0 as nC,bt as rC,X as sC,bu as oC,bv as Qg,bw as iC,bx as aC,by as cC,bz as R5,bA as lC,bB as P5,bC as dC,bD as uC,bE as fC,bF as hC,bG as Ju,bH as Qu,bI as Mc,bJ as pC,bK as Hh,bL as Ic,bM as yo,au as mC,as as gC,bN as yC,bO as e0,M as vC,N as xC,O as bC,L as wC,bP as D5,W as SC,Q as _s,bQ as CC,bR as kC,bS as MC,bT as Da,bU as vl,U as IC,bV as Fh,a7 as Bh,bW as EC,a8 as _C}from"./index-Cs2nBW_t.js";import{j as c,aS as jC,aV as TC,aY as AC,aW as NC,aX as LC,aT as RC,aU as PC,bm as DC,bn as O5,bo as OC,bp as HC,b7 as H5,bq as F5,b9 as B5,ba as FC,bb as BC,br as VC,bs as $C,bt as zC,bj as UC,bk as qC,bu as fi,bv as WC,bw as KC,bx as GC,by as ZC,bz as YC,bA as XC,bB as JC,aP as ba,bC as QC,bD as e8,bE as t8,bF as n8,bG as r8,bH as s8,bI as o8,bJ as i8,Q as bn,bK as a8,bL as c8,bM as l8,bN as d8,bO as u8,bP as f8,bQ as h8,bR as p8,bS as m8,bT as g8,bU as y8,bV as v8,aZ as xm,a_ as wa,be as V5,bf as $5,b0 as bm,b1 as wm,bc as Sm,bd as z5,bg as Cm,bh as km,a$ as x8,bW as U5,bX as q5,bY as W5,bZ as K5,b_ as G5,b$ as Ds,c0 as b8,c1 as w8,c2 as S8,b4 as C8,aj as k8,c3 as M8,c4 as I8,E as Pe,S as Z5,O as Y5,ap as E8,aq as _8,M as j8,af as T8,c5 as A8,c6 as N8,R as L8,U as t0,c7 as R8,c8 as P8,c9 as X5,ca as n0,cb as D8,aQ as Ec,cc as J5,bl as O8,cd as H8}from"./vendor-boot-3SaHYVb1.js";import{a as H,R as p}from"./vendor-react-Bz1tRBxM.js";import{c as Et,d as gr,p as Gd}from"./vendor-zustand-CXhN0IMY.js";import{_ as mt}from"./vendor-vite-runtime-DD1OZmLC.js";import{i as un}from"./runtimeSurface-DiP2a57a.js";import{saveOrShareFile as F8}from"./nativeFileSave-DpBH1Sa3.js";const TX=()=>{if(!Vr())return!1;const e=xS();return e==="win32"||e==="linux"},AX=async()=>{if(!xt())return!1;try{return await dr("desktop_start_window_drag"),!0}catch{return!1}},B8=24;class ys{constructor(t,n,r){this.parent=t,this.overlay=n,this.depth=r}parent;overlay;depth;static empty(){return new ys(null,new Map,0)}static from(t){return new ys(null,new Map(t),0)}get(t){return this.overlay.has(t)?this.overlay.get(t):this.parent?.get(t)}has(t){return this.overlay.has(t)?!0:this.parent?.has(t)??!1}set(t,n){return this.overlay.set(t,n),this}fork(){return this.depth>=B8?this.compact().fork():new ys(this,new Map,this.depth+1)}compact(){if(!this.parent)return this;const t=new Map;return this.collect(t),new ys(null,t,0)}get size(){return this.parent?[...this.entries()].length:this.overlay.size}*entries(){const t=new Set;yield*this.walk(t)}*values(){for(const[,t]of this.entries())yield t}*keys(){for(const[t]of this.entries())yield t}[Symbol.iterator](){return this.entries()}*walk(t){for(const[n,r]of this.overlay)t.has(n)||(t.add(n),yield[n,r]);this.parent&&(yield*this.parent.walk(t))}collect(t){this.parent?.collect(t);for(const[n,r]of this.overlay)t.set(n,r)}}const Xl=e=>e?ys.from(e):ys.empty(),Jl=()=>({bySession:new Map,lastSequence:new Map}),Q5=()=>Xl(),V8=10,$8=50;let z8=0;const eb=()=>`ext-${Date.now().toString(36)}-${z8+=1}`,tb=(e,t,n=V8)=>{const r=[...e,t];return r.length>n?r.slice(r.length-n):r},Un=(e,t,n)=>{t&&(e.lastMutatedMessageId=e.messages.get(t)?.id??t,e.lastMutationKind=n)},ss=e=>{e.parts=e.parts.fork()},U8=(e,t,n)=>{const r=e.bySession.get(t);if(r)return r;const s={sessionId:t,directory:n,lastSequence:-1,lifecycle:"idle",messages:new Map,partOrder:new Map,parts:Q5(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};return e.bySession.set(t,s),s},Zd=(e,t)=>e.startsWith(`user-${t}-`),q8=250,r0=new WeakMap,W8=(e,t)=>{if(e.size!==t.size)return!1;for(const n of e.list)if(t.get(n.id)!==n)return!1;return!0},Oa=e=>{const t=r0.get(e.messages);if(t&&W8(t,e.messages))return t.list;const n=new Set,r=[];for(const s of e.messages.values())n.has(s.id)||(n.add(s.id),r.push(s));for(let s=1;s<r.length;s+=1){const o=r[s-1],i=r[s];if(!(!o||!i||i.createdAt>=o.createdAt)){r.sort((a,l)=>a.createdAt-l.createdAt);break}}return r0.set(e.messages,{size:e.messages.size,list:r}),r},nb=(e,t,n)=>{if(!t)return;let r,s=Number.POSITIVE_INFINITY;for(const o of Oa(e)){if(o.role!=="user"||o.text!==t||Zd(o.id,e.sessionId))continue;const i=Math.abs(o.createdAt-n);i<=q8&&i<s&&(r=o,s=i)}return r},K8=(e,t,n)=>{if(n.role==="user"&&Zd(t,e.sessionId)){const r=nb(e,n.text,n.createdAt);if(r){e.messages.set(t,r);return}}e.messages.set(t,n)},Yd=(e,t)=>{if(!t)return;const n=e.messages.get(t)?.id;if(n)return n;if(Zd(t,e.sessionId)){const r=Oa(e);for(let s=r.length-1;s>=0;s-=1){const o=r[s];if(o?.role==="user")return o.id}}return t},G8=(e,t,n)=>{const r=e.messages.get(t.messageId);if(r)return r;if(t.role==="user"&&Zd(t.messageId,e.sessionId)){const i=nb(e,t.text??"",t.startedAt);if(i)return e.messages.set(t.messageId,i),i}const s=Yd(e,t.parentId),o={id:t.messageId,sessionId:e.sessionId,directory:n,role:t.role,...s?{parentId:s}:{},createdAt:t.startedAt,text:t.role==="user"?t.text??"":"",thinking:"",streaming:t.role==="assistant",...t.model?{model:t.model}:{},...t.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}};if(e.messages.set(t.messageId,o),t.role==="user"&&t.files?.length){const i=[];for(const a of t.files){const l={id:a.id,index:a.index,type:"file",text:"",streaming:!1,file:{...a.mime?{mime:a.mime}:{},...a.filename?{filename:a.filename}:{},...a.url?{url:a.url}:{}}};e.parts.set(l.id,l),i.push(l.id)}e.partOrder.set(o.id,i)}return o},rb=(e,t,n,r)=>{const s=r??`${t.id}:${n}`,o=e.parts.get(s);if(o)return o;const i={id:s,index:(e.partOrder.get(t.id)??[]).length,type:n,text:"",streaming:!0};e.parts.set(s,i);const a=[...e.partOrder.get(t.id)??[]];return a.includes(i.id)||a.push(i.id),e.partOrder.set(t.id,a),i},Z8=(e,t)=>{if(!e.messages.get(t))return{text:"",thinking:""};const r=e.partOrder.get(t)??[];let s="",o="";for(const i of r){const a=e.parts.get(i);a&&(a.type==="text"?s+=a.text:a.type==="thinking"&&(o+=a.text))}return{text:s,thinking:o}},s0=(e,t,n,r)=>{const o=(e.partOrder.get(t)??[]).map(l=>e.parts.get(l)).filter(l=>l?.type===n);if(o.length===0){if(!r)return;const l=e.messages.get(t);if(!l)return;const d=rb(e,l,n);e.parts.set(d.id,{...d,text:r,streaming:!1});return}const[i,...a]=o;if(i){e.parts.set(i.id,{...i,text:r,streaming:!1});for(const l of a)e.parts.set(l.id,{...l,text:"",streaming:!1})}},Mm=(e,t)=>{const n=e.messages.get(t);if(n&&n.role==="assistant")return n;const r=Oa(e);for(let o=r.length-1;o>=0;o-=1){const i=r[o];if(i.role==="assistant"&&(i.streaming||i.durationMs===void 0))return e.messages.set(t,i),!e.partOrder.has(t)&&e.partOrder.has(i.id)&&e.partOrder.set(t,e.partOrder.get(i.id)),i}const s=r[r.length-1];if(s&&s.role==="assistant")return e.messages.set(t,s),!e.partOrder.has(t)&&e.partOrder.has(s.id)&&e.partOrder.set(t,e.partOrder.get(s.id)),s},Y8=(e,t,n)=>{const r=new Set(e.partOrder.get(t)??[]);if(r.size!==0)for(const[s,o]of e.parts)!o.streaming||!n(o)||!r.has(o.id)&&!r.has(s)||e.parts.set(s,{...o,streaming:!1})},sb=(e,t)=>{Y8(e,t,n=>n.type==="thinking")},X8=256,ob=(e,t)=>{if(!t)return e;if(!e)return t;if(t===e)return e;if(t.startsWith(e))return t;if(e.startsWith(t))return e;const n=Math.min(X8,e.length,t.length);for(let r=n;r>0;r-=1)if(e.endsWith(t.slice(0,r)))return e+t.slice(r);return e+t},Fo=(e,t,n=Date.now())=>{if(!(typeof e!="number"||!Number.isFinite(e)))return typeof t!="number"||!Number.isFinite(t)?e:e-(t-n)},J8=(e,t)=>{if(t.state==="busy"&&typeof t.command=="string"?e.runningCommand=t.command:delete e.runningCommand,t.state==="retry"){e.lifecycle="retry",e.retry={...t.attempt!==void 0?{attempt:t.attempt}:{},...t.next!==void 0?{next:t.next}:{},...t.message!==void 0?{message:t.message}:{}};return}if(t.state==="busy"&&e.retry){e.lifecycle="retry";return}if(e.lifecycle=t.state,e.retry=void 0,t.state!=="busy"){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[n,r]of e.messages)r.streaming&&e.messages.set(n,{...r,streaming:!1})}},Q8=(e,t,n)=>{G8(e,n,t)},o0=(e,t,n)=>{const r=Mm(e,t.messageId);if(!r)return!1;r.streaming=!0,e.streamingMessages.add(r.id),e.streamingMessages.add(t.messageId),n==="text"&&sb(e,r.id);const s=t.partId??`${r.id}:${n}`;let o=e.parts.get(s);if(!o){const a=t.contentIndex;if(typeof a=="number"){const l=[`${r.id}:${n}:${a}`,`${r.id}:${a}`,`${r.id}:${n}`];for(const d of l){const f=e.parts.get(d);if(f&&f.type===n){o=f;break}}if(!o){const d=e.partOrder.get(r.id)??[];for(const f of d){const u=e.parts.get(f);if(u&&u.type===n&&u.index===a){o=u;break}}}}}if(o){if(o.type!==n)return!1;const a={...o,text:ob(o.text,t.delta),streaming:!0};return e.parts.set(o.id,a),s!==o.id&&e.parts.set(s,a),!0}const i=rb(e,r,n,s);return e.parts.set(i.id,{...i,text:t.delta,streaming:!0}),!0},e6=(e,t)=>{const n=Mm(e,t.messageId);if(!n)return;const{text:r,thinking:s}=Z8(e,n.id);n.text=typeof t.text=="string"?t.text:r,n.thinking=typeof t.thinking=="string"?t.thinking:s,s0(e,n.id,"text",n.text),s0(e,n.id,"thinking",n.thinking),t.continuing===!0&&!t.error?(n.streaming=!0,e.streamingMessages.add(n.id),e.streamingMessages.add(t.messageId)):n.streaming=!1,typeof t.durationMs=="number"?n.durationMs=t.durationMs:typeof n.createdAt=="number"&&n.createdAt>0&&(n.durationMs=Math.max(100,Date.now()-n.createdAt)),t.thinkingLevel&&(n.thinkingLevel=t.thinkingLevel),t.error&&(n.error=t.error),t.usage&&(n.usage=t.usage),t.continuing!==!0&&!t.error&&(e.streamingMessages.delete(n.id),e.streamingMessages.delete(t.messageId))},ef=(e,t,n)=>{const r=e.toolsByCallId.get(n.toolCallId)??n.messageId,s=Mm(e,r);if(!s)return!1;sb(e,s.id);const o=Date.now(),i=Fo(n.startedAt,n.serverNow,o),a=Fo(n.endedAt,n.serverNow,o);t!=="end"&&(s.streaming=!0,e.streamingMessages.add(s.id));const l=e.parts.get(n.partId)??Array.from(e.parts.values()).find(h=>h.type==="tool"&&h.tool?.toolCallId===n.toolCallId);if(t==="start"&&!l){const h={id:n.partId,index:(e.partOrder.get(s.id)??[]).length,type:"tool",text:"",streaming:!1,tool:{toolCallId:n.toolCallId,name:n.name,...n.input!==void 0?{input:n.input}:{},...n.render!==void 0?{render:n.render}:{},state:n.state,...i!==void 0?{startedAt:i}:{}}};e.parts.set(h.id,h);const m=[...e.partOrder.get(s.id)??[]];return m.push(h.id),e.partOrder.set(s.id,m),e.toolsByCallId.set(n.toolCallId,s.id),!0}if(!l||l.type!=="tool")return!1;const d={...l},f=l.tool,u=n.render!==void 0?{...f?.render??{},...n.render}:f?.render;return d.tool={toolCallId:n.toolCallId,name:n.name,...n.input!==void 0?{input:n.input}:f?.input!==void 0?{input:f.input}:{},...n.output!==void 0?{output:n.output}:f?.output!==void 0?{output:f.output}:{},...u!==void 0?{render:u}:{},...n.error!==void 0?{error:n.error}:f?.error!==void 0?{error:f.error}:{},...n.metadata!==void 0?{metadata:n.metadata}:f?.metadata!==void 0?{metadata:f.metadata}:{},...n.isError!==void 0?{isError:n.isError}:f?.isError!==void 0?{isError:f.isError}:{},state:n.state,...i!==void 0?{startedAt:i}:f?.startedAt!==void 0?{startedAt:f.startedAt}:{},...a!==void 0?{endedAt:a}:f?.endedAt!==void 0?{endedAt:f.endedAt}:{}},t==="end"&&(d.streaming=!1),e.parts.set(d.id,d),!0},t6=(e,t)=>{if(e.lifecycle="interrupted",e.retry=void 0,!!t){for(const n of e.streamingMessages){const r=e.messages.get(n);r&&(r.streaming=!1,r.error={code:"SESSION_INTERRUPTED"})}e.streamingMessages.clear()}},n6=(e,t,n)=>{e.lifecycle="error",e.retry=void 0;const r=Date.now();e.parts=e.parts.fork(),e.partOrder=new Map(e.partOrder);const s=[...e.streamingMessages].map(i=>e.messages.get(i)).filter((i,a,l)=>!!i&&l.indexOf(i)===a),o=s.reduce((i,a)=>!i||a.createdAt>=i.createdAt?a:i,void 0);for(const i of s){i.streaming=!1,i.error=i===o?{code:t,...n?{message:n}:{}}:void 0,i.durationMs===void 0&&i.createdAt>0&&(i.durationMs=Math.max(100,r-i.createdAt));for(const a of e.partOrder.get(i.id)??[]){const l=e.parts.get(a);if(!l)continue;const d=l.tool?.state==="running"||l.tool?.state==="pending";if(!l.streaming&&!d)continue;const f={...l,streaming:!1};d&&f.tool&&(f.tool={...f.tool,state:"error",...n?{error:n}:{},endedAt:f.tool.endedAt??r}),e.parts.set(a,f)}}e.streamingMessages.clear()},r6="pichamber.ui",s6="pichamber.",o6="pichamber-extension-ui",i6=1,a6=new Set(["info","success","warning","error","neutral"]),Kn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,tt=e=>typeof e=="string"?e:void 0,Vh=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ib=e=>{const t=tt(e);return t&&a6.has(t)?t:"neutral"},i0=e=>{if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=Kn(n);if(!r)continue;const s=tt(r.label);s!==void 0&&t.push({label:s,value:tt(r.value)??"",...r.tone!==void 0?{tone:ib(r.tone)}:{}})}return t},c6=128,hi=(e,t)=>e.length>t?e.slice(0,t):e,l6=e=>bS(e),a0=e=>{if(!Array.isArray(e))return;const t=[];for(const n of e.slice(0,8)){const r=Kn(n);if(!r)continue;const s=tt(r.label),o=tt(r.command);if(!s||!o||o.includes("/")||o.startsWith("."))continue;const i=Kn(r.promptForArgs),a=i?tt(i.label):void 0,l=i?tt(i.placeholder):void 0;t.push({label:hi(s,c6),command:o,...tt(r.args)!==void 0?{args:l6(tt(r.args))}:{},...r.variant==="outline"||r.variant==="ghost"?{variant:r.variant}:{},...tt(r.icon)!==void 0?{icon:hi(tt(r.icon)??"",64)}:{},...r.disabled===!0?{disabled:!0}:{},...r.loading===!0?{loading:!0}:{},...tt(r.confirm)!==void 0?{confirm:hi(tt(r.confirm)??"",500)}:{},...i?{promptForArgs:{...a!==void 0?{label:hi(a,256)}:{},...l!==void 0?{placeholder:hi(l,256)}:{}}}:{}})}return t.length>0?t:void 0},d6=(e,t)=>{switch(e){case"markdown":{const n=tt(t.body)??tt(t.text);return n!==void 0?{component:"markdown",body:n}:null}case"kv":{const n=i0(t.rows);return n&&n.length>0?{component:"kv",rows:n}:null}case"list":{const n=i0(t.items??t.rows);return n&&n.length>0?{component:"list",items:n}:null}case"table":{if(!Array.isArray(t.columns)||!Array.isArray(t.rows))return null;const n=t.columns.map(s=>tt(s)??"").filter(s=>s.length>0);if(n.length===0)return null;const r=[];for(const s of t.rows.slice(0,200))Array.isArray(s)&&r.push(s.map(o=>tt(o)??"").slice(0,n.length));return r.length>0?{component:"table",columns:n,rows:r}:null}case"progress":{const n=Vh(t.value);if(n===void 0)return null;const r=Vh(t.max)??100;return{component:"progress",value:n,max:r>0?r:100,...tt(t.label)!==void 0?{label:tt(t.label)}:{}}}case"badges":{if(!Array.isArray(t.items))return null;const n=t.items.map(r=>{const s=Kn(r);if(s){const i=tt(s.label);return i?{label:i,tone:ib(s.tone)}:null}const o=tt(r);return o?{label:o,tone:"neutral"}:null}).filter(r=>r!==null).slice(0,24);return n.length>0?{component:"badges",items:n}:null}case"code":{const n=tt(t.code);return n!==void 0?{component:"code",code:n,...tt(t.language)!==void 0?{language:tt(t.language)}:{}}:null}default:return null}},c0=(e,t=2e3)=>e.length>t?`${e.slice(0,t)}…`:e,l0=e=>{if(!Array.isArray(e)||e.length===0)return;const t=[];for(const n of e){if(typeof n!="string")return;t.push(n)}return t},ab=e=>{const t=Kn(e);if(!t)return;const n=l0(t.message);if(!n)return;if(t.messageExpanded===void 0)return{message:n};const r=l0(t.messageExpanded);return r?{message:n,messageExpanded:r}:{message:n}},cb=e=>{const n=e.customType===r6||(e.customType?.startsWith(s6)??!1)?Kn(Kn(e.data)?.ui??null)??Kn(e.data)??Kn(e.details):null;if(n){const s=tt(n.protocol),o=Vh(n.version);if(!(s&&s!==o6)){if(!(o!==void 0&&o!==i6)){const i=tt(n.component)??tt(n.type);if(i){const a=Kn(n.props)??{},l=d6(i,a),d=a0(n.actions);if(l||d){const f=tt(n.title);return{kind:"ui",descriptor:{...tt(n.id)!==void 0?{id:tt(n.id)?.slice(0,128)}:{},...f!==void 0?{title:f.slice(0,256)}:{},component:l??{component:"markdown",body:""},...d?{actions:d}:{}}}}}if(tt(n.title)||tt(n.text)||tt(n.body)){const a=tt(n.text)??tt(n.body)??"";if(a){const l=a0(n.actions);return{kind:"ui",descriptor:{...tt(n.id)!==void 0?{id:tt(n.id)?.slice(0,128)}:{},...tt(n.title)!==void 0?{title:tt(n.title)?.slice(0,256)}:{},component:{component:"markdown",body:a.slice(0,5e3)},...l?{actions:l}:{}}}}}}}}const r=[];if(typeof e.text=="string"&&e.text.trim().length>0&&r.push(e.text.trim()),e.data!==void 0)try{r.push(c0(JSON.stringify(e.data,null,2)))}catch{r.push("[unserializable data]")}else if(e.details!==void 0)try{r.push(c0(JSON.stringify(e.details,null,2)))}catch{r.push("[unserializable details]")}return{kind:"fallback",title:e.customType??"Extension",body:r.join(`
|
|
3
|
+
|
|
4
|
+
`)}},u6=(e,t,n,r)=>{if(!r.customType)return;const s={id:r.id,sessionId:n,directory:t,role:"extension",customType:r.customType,...r.data!==void 0?{data:r.data}:{},createdAt:r.createdAt,text:"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(s.id,s),Un(e,s.id,"structure")},f6=(e,t,n,r)=>{if(!r.customType)return;const s=ab(r.render),o={id:r.id,sessionId:n,directory:t,role:"extension",customType:r.customType,...r.details!==void 0?{details:r.details}:{},...s?{render:s}:{},createdAt:r.createdAt,text:r.text??"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(o.id,o),Un(e,o.id,"structure")},h6=(e,t)=>{e.extensionStatuses=new Map(e.extensionStatuses),typeof t.text=="string"&&t.text.length>0?e.extensionStatuses.set(t.key,t.text):e.extensionStatuses.delete(t.key)},p6=(e,t)=>{e.extensionWidgets=new Map(e.extensionWidgets),Array.isArray(t.lines)&&t.lines.length>0?e.extensionWidgets.set(t.key,{lines:t.lines,placement:t.placement==="belowEditor"?"belowEditor":"aboveEditor"}):e.extensionWidgets.delete(t.key)},m6=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)||(e.extensionDialogs=[...e.extensionDialogs,t])},g6=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)&&(e.extensionDialogs=e.extensionDialogs.filter(n=>n.requestId!==t.requestId))},y6=(e,t)=>{const n=typeof t.id=="string"&&t.id.length>0?t.id:eb();e.extensionNotices.some(r=>r.id===n)||(e.extensionNotices=tb(e.extensionNotices,{id:n,message:t.message,level:t.level,createdAt:typeof t.createdAt=="number"&&Number.isFinite(t.createdAt)?t.createdAt:Date.now()},$8))},v6=(e,t)=>{t.commands===!0&&(e.extensionCatalogRevision=(e.extensionCatalogRevision??0)+1)},x6=(e,t,n)=>{const r=t.mode==="paste"?"paste":"set",s={text:t.text,mode:r,sequence:n};if(r==="set")e.extensionEditorOps=[s];else{const i=[...e.extensionEditorOps??(e.extensionEditor?[e.extensionEditor]:[]),s];i.length>32&&i.splice(0,i.length-32),e.extensionEditorOps=i}e.extensionEditor=s},b6=(e,t)=>{e.extensionTitle=t.title},w6=(e,t)=>{e.extensionPanels=new Map(e.extensionPanels);const n=t.component!==void 0||t.title!==void 0||t.actions!==void 0;t.removed===!0||!n?e.extensionPanels.delete(t.id):e.extensionPanels.set(t.id,t)},S6=(e,t)=>{e.extensionApps=new Map(e.extensionApps),t.removed===!0||typeof t.html!="string"||t.html.length===0?e.extensionApps.delete(t.appId):e.extensionApps.set(t.appId,t)},C6=(e,t)=>{e.extensionErrors=tb(e.extensionErrors,{id:eb(),source:t.source,...t.event!==void 0?{event:t.event}:{},message:t.message,createdAt:Date.now()})},k6=(e,t)=>{const n=t.message||void 0,r=t.visible;n===void 0&&r===void 0?delete e.extensionWorking:e.extensionWorking={...n!==void 0?{message:n}:{},...r!==void 0?{visible:r}:{}}},M6=(e,t,n)=>{const r=e.bySession.get(t);if(!r||r.extensionDialogs.findIndex(i=>i.requestId===n)===-1)return e;const o={...r,extensionDialogs:r.extensionDialogs.filter(i=>i.requestId!==n)};return{bySession:new Map(e.bySession).set(t,o),lastSequence:new Map(e.lastSequence)}},lb=e=>({surfaceId:e.surfaceId,...e.parentId?{parentId:e.parentId}:{},title:e.title,mode:e.mode,capturing:e.capturing,hidden:e.hidden,focused:e.focused,z:e.z,...e.blocked?{blocked:{...e.blocked}}:{}}),db=e=>({version:e.version,lines:e.lines,cells:e.lines.map((t,n)=>e.cells?.[n]),cursor:e.cursor,layout:e.layout,visible:e.visible,columns:e.columns,screenColumns:e.screenColumns,rows:e.rows}),ub=e=>Array.isArray(e.lines),fb=e=>{if(!Array.isArray(e)||e.length===0)return;const t=new Map;for(const n of e){if(typeof n?.surfaceId!="string"||n.surfaceId.length===0)continue;const r=n.frame&&n.frame.surfaceId===n.surfaceId&&ub(n.frame)?db(n.frame):null;t.set(n.surfaceId,{...lb(n),frame:r})}return t.size>0?t:void 0},xl=(e,t)=>{const n=new Map(e.extensionSurfaces??[]);n.set(t.surfaceId,t),e.extensionSurfaces=n},I6=(e,t)=>{const n=e.extensionSurfaces?.get(t.surfaceId);xl(e,{...lb(t),frame:n?.frame??null,...n?.stale?{stale:!0}:{}})},E6=(e,t)=>{const n=e.extensionSurfaces?.get(t.surfaceId);if(!n||n.frame&&t.version<=n.frame.version)return;if(ub(t)){xl(e,{...n,frame:db(t),stale:!1});return}if(!n.frame||n.frame.version!==t.base){n.stale||xl(e,{...n,stale:!0});return}const r=n.frame.lines.slice(0,t.length),s=n.frame.cells.slice(0,t.length);for(;r.length<t.length;)r.push(""),s.push(void 0);for(const o of t.changes)r[o.index]=o.line,s[o.index]=o.cells;xl(e,{...n,frame:{version:t.version,lines:r,cells:s,cursor:t.cursor,layout:t.layout,visible:t.visible,columns:t.columns,screenColumns:t.screenColumns,rows:t.rows},stale:!1})},hb=(e,t)=>{if(!e.extensionSurfaces?.has(t.surfaceId))return;const n=new Map(e.extensionSurfaces);n.delete(t.surfaceId),n.size===0?delete e.extensionSurfaces:e.extensionSurfaces=n},_6=(e,t,n)=>{const r=e.bySession.get(t);if(!r?.extensionSurfaces?.has(n))return e;const s={...r};return hb(s,{surfaceId:n}),{bySession:new Map(e.bySession).set(t,s),lastSequence:new Map(e.lastSequence)}},j6=new Set(["running","completed","cancelled","failed"]),Ql=e=>e.length>Dh?e.slice(-Dh):e,pb=e=>{const t=e;return!!t&&typeof t.id=="string"&&t.id.length>0&&typeof t.command=="string"&&j6.has(t.phase)&&typeof t.startedAt=="number"},T6=e=>{if(Array.isArray(e))return e.filter(pb).map(t=>typeof t.output=="string"&&t.output.length>Dh?{...t,output:Ql(t.output)}:t)},mb=(e,t)=>{const n=T6(t);if(n){if(n.length===0){e.bashExecutions?.length&&delete e.bashExecutions;return}e.bashExecutions=n}},A6=(e,t)=>{if(!pb(t))return;const n=e.bashExecutions??[],r=n.findIndex(l=>l.id===t.id),s=r>=0?n[r]:void 0,o=typeof t.output=="string"?Ql(t.output):s?.output,i={...t,...o?{output:o}:{}};o||delete i.output;const a=[...n];r>=0?a[r]=i:a.push(i),e.bashExecutions=a},N6=(e,t)=>{const n=e.bashExecutions;if(!n)return;const r=n.findIndex(a=>a.id===t.id);if(r<0)return;const s=n[r],o=t.reset===!0?Ql(t.output):Ql(`${s.output??""}${t.delta}`);if(o===(s.output??""))return;const i=[...n];i[r]={...s,output:o},e.bashExecutions=i},L6=(e,t,n,r)=>{if(r.id&&e.bashExecutions?.some(i=>i.id===r.id)){const i=e.bashExecutions.filter(a=>a.id!==r.id);i.length>0?e.bashExecutions=i:delete e.bashExecutions}const{message:s}=r;if(!s||typeof s.id!="string"||s.customType!==Kl)return;const o={id:s.id,sessionId:n,directory:t,role:"extension",customType:Kl,details:s.details,createdAt:s.createdAt,text:"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(o.id,o),Un(e,o.id,"structure")},jr=["off","minimal","low","medium","high","xhigh","max"],R6={off:"Off",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},Ht=e=>e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",dn=e=>Ht(e)?e:null,P6=(e,t)=>{const n=e.filter(Ht),r=n.length>0?n:["off"];if(t&&r.includes(t))return t;const s=jr.indexOf(t);if(s===-1)return r[0];for(let o=s+1;o<jr.length;o+=1)if(r.includes(jr[o]))return jr[o];for(let o=s-1;o>=0;o-=1)if(r.includes(jr[o]))return jr[o];return r[0]},Im=e=>{if(Array.isArray(e?.thinkingLevels)&&e.thinkingLevels.length>0){const t=e.thinkingLevels,n=jr.filter(r=>t.includes(r));return n.length>0?n:["off"]}return e?.reasoning===!0||e?.supportsThinking===!0?jr.filter(t=>t!=="xhigh"&&t!=="max"):["off"]},Xd=e=>e.some(t=>t!=="off"&&Ht(t)),Em=e=>{const t=Im(e);return Xd(t)?t:[]},Ur=e=>e?Ht(e)?R6[e]:`${e.charAt(0).toUpperCase()}${e.slice(1)}`:"Default",D6=(e,t)=>t<=1||!Number.isFinite(e)?0:Math.min(t-1,Math.max(0,Math.round(e*(t-1)))),_m=(e,t,n)=>{const r=e.filter(Ht);if(!Xd(r))return;const s=[void 0,...r],o=Ht(t)&&r.includes(t)?t:void 0,i=s.indexOf(o);return s[(i+n+s.length)%s.length]},gb=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return`${t}/${n}`},yb=(e,t)=>{if(!(!t||!e))return dn(e[t])??void 0},d0=e=>{if(e.thinking)return e.thinking;const t=gb(e.model);return yb(e.defaultThinkingByModel,t)??dn(e.defaultThinking)??void 0},_c=e=>{const t=Im(e);if(!Xd(t))return;const n=gb({providerId:e.providerId,modelId:e.modelId}),r=yb(e.defaultThinkingByModel,n)??(Ht(e.previousThinking)?e.previousThinking:void 0)??dn(e.defaultThinking)??void 0;if(r)return P6(t,r)},u0=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return{providerId:t,modelId:n}},O6=e=>{let t;if(e.messages)for(const s of e.messages){if(s.role!=="assistant")continue;const o=u0(s.model),i=dn(s.thinkingLevel)??void 0;if(!o&&!i)continue;const a=typeof s.createdAt=="number"&&Number.isFinite(s.createdAt)?s.createdAt:0;(!t||a>=t.createdAt)&&(t={createdAt:a,...o?{model:o}:{},...i?{thinkingLevel:i}:{}})}const n=t?.model??u0(e.model),r=t?.thinkingLevel??dn(e.thinking)??void 0;return{...n?{model:n}:{},...r?{thinking:r}:{}}},f0=new WeakMap,H6=e=>{const t=f0.get(e);if(t)return t;const n={id:e.id,type:e.type,text:e.text,streaming:e.streaming,...e.tool?{tool:e.tool}:{},...e.attachment?{attachment:e.attachment}:{},...e.file?{file:e.file}:{}};return f0.set(e,n),n},F6=(e,t)=>{const n=new Set,r=new Set;for(let s=t.length-1;s>=0;s-=1){const o=t[s];if(!o||o.role!=="assistant")continue;const i=Yd(e,o.parentId);if(!i)continue;const a=!!(o.text||o.thinking||(e.partOrder.get(o.id)?.length??0)>0);if(o.error&&!a&&n.has(i)){r.add(o.id);continue}o.error||n.add(i)}return r},B6=(e,t,n,r)=>n.id===t.id&&n.role===t.role&&n.parentId===Yd(e,t.parentId)&&n.text===t.text&&n.thinking===t.thinking&&n.render===t.render&&n.streaming===t.streaming&&n.createdAt===t.createdAt&&n.durationMs===t.durationMs&&n.error===t.error&&n.model===t.model&&n.thinkingLevel===t.thinkingLevel&&n.usage===t.usage&&n.parts.length===r.length&&n.parts.every((s,o)=>s===r[o]),V6=(e,t,n)=>{const r=e.partOrder.get(t.id)??[],s=[];for(const i of r){const a=e.parts.get(i);a&&s.push(H6(a))}if(n&&B6(e,t,n,s))return n;const o=Yd(e,t.parentId);return{id:t.id,role:t.role,...o?{parentId:o}:{},...t.customType!==void 0?{customType:t.customType}:{},...t.data!==void 0?{data:t.data}:{},...t.details!==void 0?{details:t.details}:{},...t.render!==void 0?{render:t.render}:{},text:t.text,thinking:t.thinking,streaming:t.streaming,createdAt:t.createdAt,...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.error?{error:t.error}:{},...t.model?{model:t.model}:{},...t.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{},...t.usage?{usage:t.usage}:{},parts:s}},vb=(e,t)=>{const n=Oa(e),r=F6(e,n),s=t?new Map(t.projection.messages.map(i=>[i.id,i])):null,o=[];for(const i of n)r.has(i.id)||o.push(V6(e,i,s?.get(i.id)));return t&&t.projection.sessionId===e.sessionId&&t.projection.directory===e.directory&&t.projection.lifecycle===e.lifecycle&&t.projection.model===e.model&&t.projection.thinking===e.thinking&&t.projection.queue.steering===e.queue.steering&&t.projection.queue.followUp===e.queue.followUp&&t.projection.messages.length===o.length&&t.projection.messages.every((i,a)=>i===o[a])?t.projection:{sessionId:e.sessionId,directory:e.directory,lifecycle:e.lifecycle,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},queue:{...e.queue},messages:o}},xb=(e,t)=>{if(delete e.runningCommand,t?.lifecycle==="busy"&&t.command&&t.isStreaming!==!0){if(e.lifecycle="busy",e.retry=void 0,e.runningCommand=t.command,t.settleWhenIdle){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[a,l]of e.messages)l.streaming&&e.messages.set(a,{...l,streaming:!1})}return}const n=[],r=[];for(const[a,l]of e.parts){const d=l.tool?.state;if(l.type!=="tool"||d!=="running"&&d!=="pending")continue;r.push(a);const f=l.tool?.toolCallId?e.toolsByCallId.get(l.tool.toolCallId):void 0;f&&n.push(f)}if(!(t?.isStreaming===!0||t?.lifecycle==="busy"||t?.lifecycle==="retry"||t?.inferFromRunningTools===!0&&n.length>0)){if(e.retry=void 0,t?.settleWhenIdle){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[a,l]of e.messages)l.streaming&&e.messages.set(a,{...l,streaming:!1})}return}e.lifecycle=t?.lifecycle==="retry"?"retry":"busy",e.retry=e.lifecycle==="retry"?t?.retry:void 0,e.streamingMessages=new Set(e.streamingMessages);for(const a of r){const l=e.parts.get(a);l&&e.parts.set(a,{...l,streaming:!0})}let o=n[n.length-1];if(!o){const a=Oa(e);for(let l=a.length-1;l>=0;l-=1){const d=a[l];if(d?.role==="assistant"){o=d.id;break}}}if(!o)return;const i=e.messages.get(o);!i||i.role!=="assistant"||(e.messages.set(o,{...i,streaming:!0}),e.streamingMessages.add(o))},ed=e=>{const t=Jl(),n=Date.now(),r=U8(t,e.session.id,e.session.directory);r.lastSequence=e.lastSequence,r.hasMoreBefore=e.hasMoreBefore===!0,r.beforeCursor=e.hasMoreBefore===!0&&typeof e.beforeCursor=="string"?e.beforeCursor:void 0,Array.isArray(e.extensionStatuses)&&(r.extensionStatuses=new Map(e.extensionStatuses.map(i=>[i.key,i.text]))),Array.isArray(e.extensionWidgets)&&(r.extensionWidgets=new Map(e.extensionWidgets.map(i=>[i.key,{lines:i.lines,placement:i.placement==="belowEditor"?"belowEditor":"aboveEditor"}]))),Array.isArray(e.extensionDialogs)&&(r.extensionDialogs=e.extensionDialogs.filter(i=>typeof i.requestId=="string"&&typeof i.method=="string"&&typeof i.title=="string")),Array.isArray(e.extensionPanels)&&(r.extensionPanels=new Map(e.extensionPanels.filter(i=>typeof i?.id=="string"&&i.id.length>0).map(i=>[i.id,i]))),Array.isArray(e.extensionApps)&&(r.extensionApps=new Map(e.extensionApps.filter(i=>typeof i?.appId=="string"&&i.appId.length>0).map(i=>[i.appId,i]))),r.extensionTitle=e.extensionTitle,e.extensionWorking&&(r.extensionWorking={...e.extensionWorking}),e.extensionDraftTracked===!0&&(r.extensionDraftTracked=!0);const s=fb(e.extensionSurfaces);s&&(r.extensionSurfaces=s),mb(r,e.bashExecutions);for(const{message:i,parts:a}of e.messages??[]){const l=i.role==="extension",d=l?ab(i.render):void 0,f={id:i.id,sessionId:e.session.id,directory:e.session.directory,role:i.role,...l&&i.customType?{customType:i.customType}:{},...l&&i.data!==void 0?{data:i.data}:{},...l&&i.details!==void 0?{details:i.details}:{},...d?{render:d}:{},...i.parentId?{parentId:i.parentId}:{},createdAt:i.createdAt,text:i.text??"",thinking:i.role==="assistant"?i.thinking??"":"",streaming:!1,...i.role==="assistant"&&i.durationMs!==void 0?{durationMs:i.durationMs}:{},...i.role==="assistant"&&i.error?{error:i.error}:{},...i.role==="assistant"&&i.model?{model:i.model}:{},...i.role==="assistant"&&i.thinkingLevel?{thinkingLevel:i.thinkingLevel}:{},...i.role==="assistant"&&i.usage?{usage:i.usage}:{}};r.messages.set(i.id,f);const u=[];for(const h of a){const m=h.type==="tool"?Fo(h.startedAt,e.serverNow,n):void 0,g=h.type==="tool"?Fo(h.endedAt,e.serverNow,n):void 0,x={id:h.id,index:h.index,type:h.type,text:h.text??"",streaming:!1,...h.type==="tool"?{tool:{toolCallId:h.toolCallId??h.id,name:h.name??"unknown",...h.input!==void 0?{input:h.input}:{},...h.output!==void 0?{output:h.output}:{},...h.render!==void 0?{render:h.render}:{},...typeof h.error=="string"?{error:h.error}:{},...h.metadata!==void 0?{metadata:h.metadata}:{},...h.isError!==void 0?{isError:h.isError}:{},state:h.state??"completed",...m!==void 0?{startedAt:m}:{},...g!==void 0?{endedAt:g}:{}}}:{},...h.type==="attachment"&&h.attachment?{attachment:h.attachment}:{},...h.type==="file"?{file:{...typeof h.mime=="string"?{mime:h.mime}:{},...typeof h.filename=="string"?{filename:h.filename}:{},...typeof h.url=="string"?{url:h.url}:{}}}:{}};r.parts.set(h.id,x),u.push(h.id),h.type==="tool"&&h.toolCallId&&r.toolsByCallId.set(h.toolCallId,i.id)}r.partOrder.set(i.id,u)}const o=O6({model:e.session.model,thinking:e.session.thinking,messages:r.messages.values()});return o.model&&(r.model=o.model),o.thinking&&(r.thinking=o.thinking),r.compaction=e.compaction,xb(r,{...e.isStreaming!==void 0?{isStreaming:e.isStreaming}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.command?{command:e.command}:{},...e.retry?{retry:e.retry}:{},inferFromRunningTools:!0}),t.lastSequence.set(e.session.id,e.lastSequence),{state:t,session:r}},tf=(e,t)=>{const n=e.lastSequence.get(t.sessionId)??-1;if(t.sequence<=n)return{state:e,didApply:!1};if(t.name==="session.deleted"){const i=new Map(e.bySession);i.delete(t.sessionId);const a=new Map(e.lastSequence);return a.set(t.sessionId,t.sequence),{state:{bySession:i,lastSequence:a},didApply:!0,sessionId:t.sessionId}}if(t.name==="session.openUrl"||t.name==="session.archive"){const i=new Map(e.lastSequence);return i.set(t.sessionId,t.sequence),{state:{bySession:e.bySession,lastSequence:i},didApply:!0,sessionId:t.sessionId}}const r=e.bySession.get(t.sessionId),s=r?{...r,lastSequence:t.sequence,...t.name==="session.lifecycle"?{lifecycle:t.payload.state}:{},...t.name==="session.queue"?{queue:{...t.payload}}:{},...t.name==="session.model"?{model:t.payload.model}:{},...t.name==="session.thinking"?{thinking:t.payload.thinking}:{}}:{sessionId:t.sessionId,directory:t.directory,lastSequence:t.sequence,lifecycle:"idle",messages:new Map,partOrder:new Map,parts:Q5(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};switch(t.name){case"session.snapshot":if(t.payload?.snapshot){if(s.lifecycle=t.payload.snapshot.lifecycle??(t.payload.snapshot.isStreaming?"busy":"idle"),s.retry=s.lifecycle==="retry"?t.payload.snapshot.retry:void 0,s.compaction=t.payload.snapshot.compaction,t.payload.snapshot.model&&(s.model=t.payload.snapshot.model),t.payload.snapshot.thinking&&(s.thinking=t.payload.snapshot.thinking),t.payload.snapshot.queue&&(s.queue={...t.payload.snapshot.queue}),Array.isArray(t.payload.snapshot.extensionStatuses)&&(s.extensionStatuses=new Map(t.payload.snapshot.extensionStatuses.map(a=>[a.key,a.text]))),Array.isArray(t.payload.snapshot.extensionWidgets)&&(s.extensionWidgets=new Map(t.payload.snapshot.extensionWidgets.map(a=>[a.key,{lines:a.lines,placement:a.placement==="belowEditor"?"belowEditor":"aboveEditor"}]))),Array.isArray(t.payload.snapshot.extensionDialogs)&&(s.extensionDialogs=t.payload.snapshot.extensionDialogs.filter(a=>typeof a.requestId=="string"&&typeof a.method=="string"&&typeof a.title=="string")),Array.isArray(t.payload.snapshot.extensionPanels)){const a=new Map;for(const l of t.payload.snapshot.extensionPanels)typeof l?.id=="string"&&l.id.length>0&&a.set(l.id,l);s.extensionPanels=a}if(Array.isArray(t.payload.snapshot.extensionApps)){const a=new Map;for(const l of t.payload.snapshot.extensionApps)typeof l?.appId=="string"&&l.appId.length>0&&a.set(l.appId,l);s.extensionApps=a}s.extensionTitle=t.payload.snapshot.extensionTitle,t.payload.snapshot.extensionWorking?s.extensionWorking={...t.payload.snapshot.extensionWorking}:delete s.extensionWorking,t.payload.snapshot.extensionDraftTracked===!0?s.extensionDraftTracked=!0:delete s.extensionDraftTracked;const i=fb(t.payload.snapshot.extensionSurfaces);i?s.extensionSurfaces=i:delete s.extensionSurfaces,mb(s,t.payload.snapshot.bashExecutions),xb(s,{isStreaming:t.payload.snapshot.isStreaming,lifecycle:s.lifecycle,...t.payload.snapshot.command?{command:t.payload.snapshot.command}:{},...t.payload.snapshot.retry?{retry:t.payload.snapshot.retry}:{},settleWhenIdle:!0})}break;case"session.lifecycle":J8(s,t.payload);break;case"assistant.message.start":s.lifecycle=s.retry?"retry":"busy",delete s.runningCommand,s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages),t.payload.files?.length&&(ss(s),s.partOrder=new Map(s.partOrder)),Q8(s,t.directory,t.payload),t.payload.role==="assistant"&&s.streamingMessages.add(t.payload.messageId),Un(s,t.payload.messageId,"structure");break;case"assistant.message.delta":ss(s),o0(s,t.payload,"text")&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"assistant.message.end":s.messages=new Map(s.messages),ss(s),s.partOrder=new Map(s.partOrder),s.streamingMessages=new Set(s.streamingMessages),e6(s,t.payload),Un(s,t.payload.messageId,"structure");break;case"assistant.thinking.delta":ss(s),o0(s,t.payload,"thinking")&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"session.tool.start":ss(s),s.partOrder=new Map(s.partOrder),s.toolsByCallId=new Map(s.toolsByCallId),ef(s,"start",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"session.tool.update":ss(s),ef(s,"update",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"session.tool.end":ss(s),ef(s,"end",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"session.queue":s.queue={steering:t.payload.steering,followUp:t.payload.followUp};break;case"session.model":s.model=t.payload.model;break;case"session.thinking":s.thinking=t.payload.thinking;break;case"session.compaction":s.compaction={...t.payload};break;case"session.updated":break;case"session.input":break;case"session.bash":A6(s,t.payload.bash);break;case"session.bash.output":N6(s,t.payload);break;case"session.bash.recorded":L6(s,t.directory,t.sessionId,t.payload);break;case"session.tree.updated":s.sessionTreeRevision=(s.sessionTreeRevision??0)+1;break;case"session.error":s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages);for(const i of s.streamingMessages){const a=s.messages.get(i);a&&s.messages.set(i,{...a})}n6(s,t.payload.code,t.payload.message);break;case"session.interrupted":s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages);for(const i of s.streamingMessages){const a=s.messages.get(i);a&&s.messages.set(i,{...a})}t6(s,t.payload.streaming);break;case"extension.entry":u6(s,t.directory,t.sessionId,t.payload);break;case"extension.message":f6(s,t.directory,t.sessionId,t.payload);break;case"extension.notify":{const i=typeof t.payload.id=="string"&&t.payload.id.length>0?t.payload.id:void 0;if(i&&s.extensionNotices.some(a=>a.id===i)){const a=new Map(e.lastSequence);return a.set(t.sessionId,t.sequence),{state:{bySession:e.bySession,lastSequence:a},didApply:!0,sessionId:t.sessionId}}y6(s,t.payload);break}case"extension.catalog":v6(s,t.payload);break;case"extension.editor":x6(s,t.payload,t.sequence);break;case"extension.title":b6(s,t.payload);break;case"extension.status":h6(s,t.payload);break;case"extension.widget":p6(s,t.payload);break;case"extension.dialog":m6(s,t.payload);break;case"extension.dialog.dismiss":g6(s,t.payload);break;case"extension.ui":w6(s,t.payload);break;case"extension.app":S6(s,t.payload);break;case"extension.working":k6(s,t.payload);break;case"extension.editor.track":t.payload.enabled?s.extensionDraftTracked=!0:delete s.extensionDraftTracked;break;case"extension.custom":I6(s,t.payload);break;case"extension.custom.frame":E6(s,t.payload);break;case"extension.custom.dismiss":hb(s,t.payload);break;case"extension.error":C6(s,t.payload);break}const o={bySession:new Map(e.bySession),lastSequence:new Map(e.lastSequence)};return o.bySession.set(t.sessionId,s),o.lastSequence.set(t.sessionId,t.sequence),{state:o,didApply:!0,sessionId:t.sessionId}},$6={fetchHealth:_5,createStream:Gl},nf=e=>e instanceof at?{code:e.code,...e.message?{message:e.message}:{},...e.status!==void 0?{status:e.status}:{}}:e instanceof Error?{code:"DAEMON_REQUEST_FAILED",message:e.message}:{code:"DAEMON_REQUEST_FAILED"},z6=async(e,t=$6)=>{const n={phase:"idle",reducerState:{bySession:new Map,lastSequence:new Map},lastSequence:new Map,stream:null,errors:[],health:{state:"pending"}},r=async a=>e.retry?e.retry(a):a();n.phase="runtime-probe";const s=e.initialHealth??await r(()=>t.fetchHealth(e.signal,e.runtimeKey));if(s.state==="ready"){if(!(s.capabilities.includes(j5)&&typeof s.streamEpoch=="string"&&s.streamEpoch.length>0)){const l={code:"DAEMON_PROTOCOL_MISMATCH",message:"The Pi runtime does not advertise a restart-safe event stream (events.streamEpoch). Update the server."};return n.health={state:"unavailable",protocolVersion:s.protocolVersion,error:l},n.phase="failed",n.errors.push({phase:"runtime-probe",error:l}),n}n.health={state:"ready",protocolVersion:s.protocolVersion,capabilities:[...s.capabilities],streamEpoch:s.streamEpoch},n.streamEpoch=s.streamEpoch}else return n.health={state:"unavailable",protocolVersion:s.protocolVersion,error:{code:s.error?.code??"DAEMON_UNAVAILABLE",...s.error?.message?{message:s.error.message}:{}}},n.phase="failed",n.errors.push({phase:"runtime-probe",error:n.health.error}),n;n.phase="session-list";const o=a=>{for(const l of a)n.lastSequence.set(l.session.id,-1)};if(e.initialSessions)o(e.initialSessions);else try{const a=await r(()=>Ie.listSessions({...e.scope,directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new at("DAEMON_PROTOCOL_MISMATCH","Session list omitted the current stream epoch");if(a.streamEpoch!==n.streamEpoch)throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");o(a.sessions)}catch(a){if(n.errors.push({phase:"session-list",error:nf(a)}),a instanceof at&&a.code==="DAEMON_PROTOCOL_MISMATCH")return n.phase="failed",n}if(e.selectedSessionId){n.phase="session-hydrate";try{const a=e.initialDetail??await r(()=>Ie.getSession(e.selectedSessionId,{...e.scope,directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new at("DAEMON_PROTOCOL_MISMATCH","Session detail omitted the current stream epoch");if(a.streamEpoch!==n.streamEpoch)throw new at("DAEMON_REQUEST_FAILED","Session detail predates the current stream epoch");n.selectedSessionTiming={sessionId:a.session.id,isStreaming:a.isStreaming,lifecycle:a.lifecycle,...Number.isFinite(a.runStartedAt)?{runStartedAt:a.runStartedAt}:{},...Number.isFinite(a.serverNow)?{serverNow:a.serverNow}:{}};const{state:l}=ed(a);n.reducerState=l,n.lastSequence.set(a.session.id,a.lastSequence)}catch(a){if(n.errors.push({phase:"session-hydrate",error:nf(a)}),a instanceof at&&a.code==="DAEMON_PROTOCOL_MISMATCH")return n.phase="failed",n}}n.phase="stream-attach";try{const a=e.selectedSessionId?n.lastSequence.get(e.selectedSessionId):e.fromSequence,l=t.createStream({onEvent:e.onEvent,onDisconnect:d=>e.onStreamDisconnect?.(d),onReconnect:()=>e.onStreamReconnect?.(),onTransportSwitch:()=>e.onTransportSwitch?.(),onEpochChange:d=>e.onEpochChange?.(d),onAuthRequired:()=>e.onAuthRequired?.()},{...typeof a=="number"&&a>=0?{fromSequence:a}:{},...n.streamEpoch?{streamEpoch:n.streamEpoch}:{},...e.runtimeKey?{runtimeKey:e.runtimeKey}:{},signal:e.signal});n.stream=l}catch(a){n.errors.push({phase:"stream-attach",error:nf(a)})}const i=n.errors.some(a=>a.phase==="runtime-probe");return n.phase=i?"failed":"ready",n};let h0=null;const bb=()=>(h0??=T5(),h0),U6=e=>({sessionId:e.sessionId,directory:e.directory,isStreaming:e.isStreaming,lastSequence:e.lastSequence,queue:e.queue??{steering:0,followUp:0},...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.compaction?{compaction:e.compaction}:{},...e.lastText?{lastText:e.lastText}:{},...e.lastThinking?{lastThinking:e.lastThinking}:{},...e.lastToolPart?{lastToolPart:e.lastToolPart}:{},lifecycle:e.lifecycle}),q6=()=>({bySession:new Map,lastSequence:new Map}),W6=(e,t)=>{const n=e.lastSequence.get(t.sessionId)??-1;if(t.lastSequence<=n)return{state:e,didUpdate:!1};const r={bySession:new Map(e.bySession),lastSequence:new Map(e.lastSequence)};return r.bySession.set(t.sessionId,U6(t)),r.lastSequence.set(t.sessionId,t.lastSequence),{state:r,didUpdate:!0}},K6={fetchHealth:_5,createStream:Gl},p0=e=>e instanceof at?{code:e.code,...e.message?{message:e.message}:{},...e.status!==void 0?{status:e.status}:{}}:e instanceof Error?{code:"DAEMON_REQUEST_FAILED",message:e.message}:{code:"DAEMON_REQUEST_FAILED"},G6=async(e,t=K6)=>{const n={phase:"idle",snapshotState:q6(),reducerState:{bySession:new Map,lastSequence:new Map},stream:null,lastSequence:e.lastKnownSequence??-1},r=async a=>e.retry?e.retry(a):a();n.phase="health-check";const s=await r(()=>t.fetchHealth(e.signal,e.runtimeKey,{fresh:!0}));if(s.state!=="ready")return n.phase="unavailable",n.error={code:s.error?.code??"DAEMON_UNAVAILABLE",...s.error?.message?{message:s.error.message}:{}},n;if(!s.capabilities.includes(j5)||typeof s.streamEpoch!="string"||s.streamEpoch.length===0)return n.phase="failed",n.error={code:"DAEMON_PROTOCOL_MISMATCH",message:"The Pi runtime does not advertise a restart-safe event stream (events.streamEpoch). Update the server."},n;n.epoch=s.streamEpoch;const o=typeof e.streamEpoch=="string"&&e.streamEpoch.length>0?e.streamEpoch:null,i=o!==null&&o!==n.epoch;i&&(n.epochChanged=!0),n.phase="snapshot-fetch";try{const a=await r(()=>Ie.getSession(e.sessionId,{directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new at("DAEMON_PROTOCOL_MISMATCH","Session detail omitted the current stream epoch");if(a.streamEpoch!==n.epoch)throw new at("DAEMON_REQUEST_FAILED","Session detail predates the current stream epoch");const l=ed(a);n.reducerState=l.state,(a.lifecycle==="busy"||a.lifecycle==="retry")&&Number.isFinite(a.runStartedAt)&&(n.runStartedAt=a.runStartedAt,Number.isFinite(a.serverNow)&&(n.serverNow=a.serverNow));const d={protocolVersion:1,kind:"event",name:"session.snapshot",sequence:a.lastSequence,sessionId:a.session.id,directory:a.session.directory,payload:{snapshot:{sessionId:a.session.id,directory:a.session.directory,lastSequence:a.lastSequence,isStreaming:a.isStreaming===!0,queue:{steering:0,followUp:0},lifecycle:a.lifecycle??(a.isStreaming?"busy":"idle"),...a.command?{command:a.command}:{},...a.retry?{retry:a.retry}:{},...a.compaction?{compaction:a.compaction}:{},...Number.isFinite(a.runStartedAt)?{runStartedAt:a.runStartedAt}:{},...Number.isFinite(a.serverNow)?{serverNow:a.serverNow}:{},...a.session.model?{model:a.session.model}:{},...a.session.thinking?{thinking:a.session.thinking}:{}}}},f=W6(n.snapshotState,d.payload.snapshot);n.snapshotState=f.state;const u=e.lastKnownSequence??-1;n.lastSequence=i?a.lastSequence:o!==null&&u>=0?u:Math.max(u,a.lastSequence)}catch(a){const l=p0(a);return l.code==="INVALID_SESSION",n.phase="failed",n.error=l,n}n.phase="stream-attach";try{n.stream=t.createStream({onEvent:e.onEvent,onDisconnect:a=>e.onStreamDisconnect?.(a),onReconnect:()=>e.onStreamReconnect?.(),onTransportSwitch:()=>e.onTransportSwitch?.(),onEpochChange:a=>e.onEpochChange?.(a),onAuthRequired:()=>e.onAuthRequired?.()},{fromSequence:n.lastSequence,streamEpoch:n.epoch,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{},signal:e.signal})}catch(a){return n.phase="failed",n.error=p0(a),n}return n.phase="ready",n},Z6=new Set(["assistant.message.delta","assistant.thinking.delta","session.tool.update"]),Y6=e=>Z6.has(e.name),td=e=>e.name==="assistant.message.delta"||e.name==="assistant.thinking.delta"?e:null,X6=(e,t)=>{const n=td(e),r=td(t);return!n||!r||n.name!==r.name||n.sessionId!==r.sessionId?!1:n.payload.messageId===r.payload.messageId&&n.payload.contentIndex===r.payload.contentIndex&&(n.payload.partId??"")===(r.payload.partId??"")},J6=(e,t)=>{const n=td(e),r=td(t);return!n||!r||n.name!==r.name?t:{...r,payload:{...r.payload,delta:ob(n.payload.delta,r.payload.delta)}}},Q6=(e,t)=>e.name==="session.tool.update"&&t.name==="session.tool.update"&&e.sessionId===t.sessionId&&e.payload.toolCallId===t.payload.toolCallId&&e.payload.partId===t.payload.partId&&e.payload.messageId===t.payload.messageId,rf=e=>{const t=[];for(const n of e){const r=t[t.length-1];r&&X6(r,n)?t[t.length-1]=J6(r,n):r&&Q6(r,n)?t[t.length-1]=n:t.push(n)}return t};class ek{constructor(t){this.publish=t}publish;buffer=[];scheduled="none";generation=0;rafId=0;push(t){if(!Y6(t)){const n=this.takeBuffer();this.publish(rf([...n,t]));return}this.buffer.push(t),this.schedule()}flush(){const t=this.takeBuffer();t.length!==0&&this.publish(rf(t))}dispose(){this.flush()}takeBuffer(){if(this.generation+=1,this.scheduled="none",this.rafId&&typeof globalThis.cancelAnimationFrame=="function"&&globalThis.cancelAnimationFrame(this.rafId),this.rafId=0,this.buffer.length===0)return[];const t=this.buffer;return this.buffer=[],t}schedule(){if(this.scheduled!=="none")return;const t=++this.generation,n=()=>{if(t!==this.generation)return;this.scheduled="none",this.rafId=0;const r=this.buffer;this.buffer=[],r.length!==0&&this.publish(rf(r))};if(typeof globalThis.requestAnimationFrame=="function"){this.scheduled="frame",this.rafId=globalThis.requestAnimationFrame(n);return}this.scheduled="microtask",queueMicrotask(n)}}const tk=[{name:"undo",description:"Undo the last message"},{name:"redo",description:"Redo previously undone messages"},{name:"timeline",description:"Open the conversation timeline"},{name:"compact",description:"Compress session history using AI to reduce context size"}],Mr=()=>tk.map(e=>({id:`system:${e.name}`,name:e.name,invocationName:e.name,source:"system",description:e.description})),nk=e=>e.map(t=>{if(t.source==="skill"){const n=t.name.startsWith("skill:")?t.name:`skill:${t.name}`,r=n.slice(6);return{id:`skill:${t.scope??"runtime"}:${n}`,name:r,invocationName:n,source:"skill",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}}return t.source==="extension"?{id:`extension:${t.scope??"runtime"}:${t.name}`,name:t.name,invocationName:t.name,source:"extension",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}:{id:`prompt:${t.scope??"runtime"}:${t.name}`,name:t.name,invocationName:t.name,source:"prompt",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}}),rk=3e4,Xt=new Map;let wb=0;const $h=new Set,Sb=()=>{wb+=1;for(const e of $h)e()},sf=()=>wb,sk=e=>($h.add(e),()=>$h.delete(e)),ok=20,Jd=(e,t)=>`${e}
|
|
5
|
+
${t?.trim()??""}`,m0=(e,t)=>Xt.get(Jd(e,t))?.commands,ik=(e,t)=>{const n=Xt.get(Jd(e,t));return n?{...n}:void 0},ak=(e,t=Date.now())=>t-e.fetchedAt<rk,ck=(e,t,n,r)=>{const s=Jd(e,t);for(Xt.delete(s),Xt.set(s,{commands:n,fetchedAt:r?.fetchedAt??Date.now(),promptSignature:r?.promptSignature??"",skillSignature:r?.skillSignature??""});Xt.size>ok;){const o=Xt.keys().next().value;if(typeof o!="string")break;Xt.delete(o)}},lk=(e,t,n,r)=>{const s=Jd(e,t),o=Xt.get(s);return o?(Xt.delete(s),Xt.set(s,{...o,promptSignature:n,skillSignature:r}),!0):!1},bl=e=>{if(typeof e=="string"&&e.trim().length>0){const t=`
|
|
6
|
+
${e.trim()}`;for(const n of[...Xt.keys()])n.endsWith(t)&&Xt.delete(n)}else Xt.clear();Sb()},dk=()=>{Xt.clear(),Sb()};function zh(e,t=50){if(typeof e!="string"||e.trim().length===0)return"";const r=e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[attachment:[^\]]+\]/g," ").replace(/(^|\s)@[\w.-]+/g," ").replace(/<[^>]+>/g," ").replace(/\r\n/g,`
|
|
7
|
+
`).split(`
|
|
8
|
+
`).map(o=>o.trim()).find(o=>o.length>0);if(!r)return"";const s=r.replace(/\s+/g," ");return s.length<=t?s:`${s.slice(0,t).trimEnd()}…`}const of="pichamber.piSessionCatalog.v1",nd=1,uk=250,Cb=4,kb=512,Uh=2e3,g0=512,fk=8192,hk=4096,pk=16384,pi=(e,t,n=!1)=>typeof e=="string"&&e.length<=t&&(n||e.length>0),wl=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,y0=e=>{if(!e||typeof e!="object")return null;const t=e;if(!wl(t.updatedAt)||!Array.isArray(t.directories)||t.directories.length>kb)return null;const n=new Map,r=new Map,s=new Map;let o=0;for(const i of t.directories){if(!i||typeof i!="object")return null;const a=i.directory,l=i.sessions;if(!pi(a,fk)||!Array.isArray(l))return null;const d=ce(a);if(!d||r.has(d)||(o+=l.length,o>Uh))return null;const f=[];for(const u of l){if(!u||typeof u!="object")return null;const h=u;if(!pi(h.id,g0)||h.parentId!==null&&!pi(h.parentId,g0)||!pi(h.title,hk,!0)||typeof h.archived!="boolean"||!wl(h.createdAt)||!wl(h.updatedAt)||h.preview!==void 0&&!pi(h.preview,pk,!0)||h.messageCount!==void 0&&(!Number.isSafeInteger(h.messageCount)||h.messageCount<0)||n.has(h.id))return null;const m=h.id;n.set(m,{id:m,directory:d,parentId:h.parentId,title:h.title,archived:h.archived,createdAt:h.createdAt,updatedAt:h.updatedAt,...h.preview!==void 0?{preview:h.preview}:{},...h.messageCount!==void 0?{messageCount:h.messageCount}:{},lifecycle:"idle",hydrated:!1}),f.push(m)}r.set(d,f),s.set(d,"idle")}return{byId:n,byDirectory:r,listStatusByDirectory:s}},v0=e=>{if(!e)return null;try{const t=JSON.parse(e);if(t.version!==nd||!t.runtimes||typeof t.runtimes!="object"||Array.isArray(t.runtimes))return null;const n=Object.entries(t.runtimes);return n.length>Cb?null:{version:nd,runtimes:Object.fromEntries(n)}}catch{return null}},mk=(e,t)=>{const n=[];let r=0;const s=new Set([...e.byDirectory.keys(),...e.listStatusByDirectory.keys()]);for(const o of s){if(n.length>=kb||r>=Uh)break;const i=ce(o);if(!i)continue;const a=[];for(const l of e.byDirectory.get(o)??[]){if(r>=Uh)break;const d=e.byId.get(l);!d||ce(d.directory)!==i||(a.push({id:d.id,parentId:d.parentId,title:d.title,archived:d.archived,createdAt:d.createdAt,updatedAt:d.updatedAt,...d.preview!==void 0?{preview:d.preview}:{},...d.messageCount!==void 0?{messageCount:d.messageCount}:{}}),r+=1)}n.push({directory:i,sessions:a})}return{updatedAt:t,directories:n}},gk=(e=Gt(),t={})=>{const n=t.flushDelayMs??uk,r=new Map;let s=null,o=!1;const i=u=>{if(!u)return null;try{const h=v0(e.getItem(of));return!h||!Object.prototype.hasOwnProperty.call(h.runtimes,u)?null:y0(h.runtimes[u])}catch{return null}},a=()=>{if(s!==null&&clearTimeout(s),s=null,r.size===0)return;let u={version:nd,runtimes:{}};try{const x=v0(e.getItem(of));x&&(u=x)}catch{}const h=new Map(Object.entries(u.runtimes));let m=[...h.values()].reduce((x,b)=>wl(b?.updatedAt)?Math.max(x,b.updatedAt):x,0);for(const[x,b]of r)m=Math.max(Date.now(),m+1),h.set(x,mk(b,m));r.clear();const g=[...h.entries()].filter(([,x])=>y0(x)!==null).sort(([,x],[,b])=>b.updatedAt-x.updatedAt).slice(0,Cb);try{e.setItem(of,JSON.stringify({version:nd,runtimes:Object.fromEntries(g)}))}catch{}},l=(u,h)=>{o||!u||(r.set(u,h),s===null&&(s=setTimeout(a,Math.max(0,n))))},d=()=>a(),f=()=>{document.visibilityState==="hidden"&&a()};return t.registerLifecycleListeners&&typeof window<"u"&&(window.addEventListener("pagehide",d,{capture:!0}),window.addEventListener("beforeunload",d,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",f),document.addEventListener("freeze",d))),{read:i,schedule:l,flush:a,dispose:()=>{o||(a(),o=!0,t.registerLifecycleListeners&&typeof window<"u"&&(window.removeEventListener("pagehide",d,{capture:!0}),window.removeEventListener("beforeunload",d,{capture:!0}),typeof document<"u"&&(document.removeEventListener("visibilitychange",f),document.removeEventListener("freeze",d))))}}},yk={read:()=>null,schedule:()=>{},flush:()=>{},dispose:()=>{}};let x0=null;const vk=()=>typeof window>"u"?yk:(x0??=gk(Gt(),{registerLifecycleListeners:!0}),x0),Yn=Gt(),qh="projects",Wh="activeProjectId",xk=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim().replace(/\/+$/,""):""},jm=()=>{const e=qd().trim().replace(/\/+$/,"");return e||""},Qd=()=>{const e=jm();return e?`${qh}:${encodeURIComponent(e)}`:qh},Mb=()=>{const e=jm();return e?`${Wh}:${encodeURIComponent(e)}`:Wh},Ib=()=>{const e=jm();if(!e)return!0;const t=xk();return!!(t&&e===t)},bk=(e,t)=>{const n=e.trim();return!n.startsWith("~")||!t?n:n==="~"?t:n.startsWith("~/")||n.startsWith("~\\")?`${t}${n.slice(1)}`:n},wk=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Eb=e=>{if(typeof e!="string")return;const t=e.trim();if(!t)return;const n=t.indexOf("/");if(!(n<=0||n>=t.length-1))return t},_b=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&wk.test(t)?t.toLowerCase():null},Tm=e=>{const t=e.trim();if(!t)return"";const n=Yn.getItem("homeDirectory")||nt.getState().homeDirectory||"",s=bk(t,n).replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},Sk=e=>{const t=Tm(e);if(!t||t==="/")return"Root";const n=t.split("/").filter(Boolean);return(n[n.length-1]||t).replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase())},Ck=e=>{if(!e||typeof e!="object")return;const t=e,n=typeof t.mime=="string"?t.mime.trim():"",r=typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?Math.max(0,Math.round(t.updatedAt)):0,s=t.source==="custom"||t.source==="auto"?t.source:null;if(!(!n||!r||!s))return{mime:n,updatedAt:r,source:s}},kk=e=>{const t=typeof e.type=="string"?e.type.trim().toLowerCase():"";if(t==="image/png"||t==="image/jpeg"||t==="image/svg+xml")return t;const n=e.name.toLowerCase();return n.endsWith(".png")?"image/png":n.endsWith(".jpg")||n.endsWith(".jpeg")?"image/jpeg":n.endsWith(".svg")?"image/svg+xml":null},Mk=async e=>await new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>{n(new Error("Failed to read icon file"))},r.onload=()=>{const s=typeof r.result=="string"?r.result:"";if(!s){n(new Error("Failed to read icon file"));return}t(s)},r.readAsDataURL(e)}),jb=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set,r=new Set;for(const s of e){if(!s||typeof s!="object")continue;const o=s,i=typeof o.path=="string"?o.path.trim():"";if(!i)continue;const a=Tm(i);if(!a)continue;const l=pm(a);if(!l||n.has(l)||r.has(a))continue;n.add(l),r.add(a);const d={id:l,path:a};if(typeof o.label=="string"&&o.label.trim().length>0&&(d.label=o.label.trim()),typeof o.icon=="string"&&o.icon.trim().length>0&&(d.icon=o.icon.trim()),o.iconImage===null)d.iconImage=null;else{const u=Ck(o.iconImage);u&&(d.iconImage=u)}typeof o.color=="string"&&o.color.trim().length>0&&(d.color=o.color.trim());const f=Eb(o.defaultModel);if(f&&(d.defaultModel=f),o.iconBackground===null)d.iconBackground=null;else{const u=_b(o.iconBackground);u&&(d.iconBackground=u)}typeof o.addedAt=="number"&&Number.isFinite(o.addedAt)&&o.addedAt>=0&&(d.addedAt=o.addedAt),typeof o.lastOpenedAt=="number"&&Number.isFinite(o.lastOpenedAt)&&o.lastOpenedAt>=0&&(d.lastOpenedAt=o.lastOpenedAt),typeof o.sidebarCollapsed=="boolean"&&(d.sidebarCollapsed=o.sidebarCollapsed),t.push(d)}return t},Ik=()=>{try{const e=Yn.getItem(Qd())||(Ib()?Yn.getItem(qh):null);return e?jb(JSON.parse(e)):[]}catch{return[]}},Ek=()=>{try{const e=Yn.getItem(Qd()+":manualOrder");if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}},b0=()=>{try{const e=Yn.getItem(Mb())||(Ib()?Yn.getItem(Wh):null);if(typeof e=="string"&&e.trim().length>0)return e.trim()}catch{return null}return null},Tb=e=>{try{const t=Mb();e?Yn.setItem(t,e):Yn.removeItem(t)}catch{}},Ab=(e,t)=>{try{Yn.setItem(Qd(),JSON.stringify(e))}catch{}Tb(t)},_k=e=>{Tb(e),$r({activeProjectId:e})},mi=(e,t,n)=>{Ab(e,t),n&&Kh(n),$r({projects:e,activeProjectId:t??void 0})},Kh=e=>{try{Yn.setItem(Qd()+":manualOrder",JSON.stringify(e))}catch{}},Gh=Ik(),jk=Gh.some(e=>e.id===b0())?b0():Gh[0]?.id??null,ct=Et()(gr((e,t)=>({projects:Gh,activeProjectId:jk,manualProjectOrder:Ek(),validateProjectPath:n=>{if(typeof n!="string"||n.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const r=Tm(n);return r?{ok:!0,normalizedPath:r}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(n,r)=>{const{validateProjectPath:s}=t(),o=s(n);if(!o.ok||!o.normalizedPath)return null;const i=o.normalizedPath,a=t().projects.find(m=>m.path===i);if(a)return t().setActiveProject(a.id),a;const l=Date.now(),d=r?.label?.trim()||Sk(i),u={id:pm(i),path:i,label:d,addedAt:l,lastOpenedAt:l},h=[...t().projects,u];return e({projects:h}),A5()&&console.info("[ProjectsStore] Added project",u),t().setActiveProject(u.id),u},removeProject:n=>{const r=t(),s=r.projects.filter(a=>a.id!==n);let o=r.activeProjectId;r.activeProjectId===n&&(o=s[0]?.id??null);const i=t().manualProjectOrder.filter(a=>a!==n);if(e({projects:s,activeProjectId:o,manualProjectOrder:i}),mi(s,o,i),o){const a=s.find(l=>l.id===o);a&&nt.getState().setDirectory(a.path,{showOverlay:!1})}else nt.getState().goHome()},setActiveProject:n=>{const{projects:r,activeProjectId:s}=t();if(s===n)return;const o=r.find(l=>l.id===n);if(!o)return;const i=Date.now(),a=r.map(l=>l.id===n?{...l,lastOpenedAt:i}:l);e({projects:a,activeProjectId:n}),mi(a,n,t().manualProjectOrder),nt.getState().setDirectory(o.path,{showOverlay:!1})},setActiveProjectIdOnly:n=>{const{projects:r,activeProjectId:s}=t();s===n||!r.some(o=>o.id===n)||(e({activeProjectId:n}),_k(n))},renameProject:(n,r)=>{const s=r.trim();if(!s)return;const{projects:o,activeProjectId:i}=t(),a=o.map(l=>l.id===n?{...l,label:s}:l);e({projects:a}),mi(a,i,t().manualProjectOrder)},updateProjectMeta:(n,r)=>{const{projects:s,activeProjectId:o}=t(),i=s.map(a=>{if(a.id!==n)return a;const l={...a};if(r.label!==void 0){const d=r.label.trim();d&&(l.label=d)}if(r.icon!==void 0&&(l.icon=r.icon),r.color!==void 0&&(l.color=r.color),r.iconBackground!==void 0&&(l.iconBackground=_b(r.iconBackground)),r.defaultModel!==void 0){const d=Eb(r.defaultModel);d?l.defaultModel=d:delete l.defaultModel}return l});e({projects:i}),mi(i,o,t().manualProjectOrder)},uploadProjectIcon:async(n,r)=>{const s=kk(r);if(!s)return{ok:!1,error:"Only PNG, JPEG, and SVG are supported"};if(!Number.isFinite(r.size)||r.size<=0)return{ok:!1,error:"Icon file is empty"};if(r.size>5*1024*1024)return{ok:!1,error:"Icon exceeds size limit (5 MB)"};try{const i=(await Mk(r)).replace(/^data:[^;]+;/i,`data:${s};`),a=await Rt(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:i})});if(!a.ok)return{ok:!1,error:(await a.json().catch(()=>null))?.error||"Failed to upload project icon"};const l=await a.json().catch(()=>null);return l?.settings&&t().synchronizeFromSettings(l.settings),{ok:!0}}catch(o){return{ok:!1,error:(o instanceof Error?o.message:String(o))||"Failed to upload project icon"}}},removeProjectIcon:async n=>{try{const r=await Rt(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"DELETE",headers:{Accept:"application/json"}});if(!r.ok)return{ok:!1,error:(await r.json().catch(()=>null))?.error||"Failed to remove project icon"};const s=await r.json().catch(()=>null);return s?.settings&&t().synchronizeFromSettings(s.settings),{ok:!0}}catch(r){return{ok:!1,error:(r instanceof Error?r.message:String(r))||"Failed to remove project icon"}}},discoverProjectIcon:async()=>({ok:!0,skipped:!0,reason:"unsupported"}),reorderProjects:(n,r)=>{const{projects:s,activeProjectId:o}=t();if(n<0||n>=s.length||r<0||r>=s.length||n===r)return;const i=[...s],[a]=i.splice(n,1);i.splice(r,0,a);const l=i.map(d=>d.id);e({projects:i,manualProjectOrder:l}),mi(i,o,l)},resetForRuntimeSwitch:()=>{e({projects:[],activeProjectId:null,manualProjectOrder:[]})},synchronizeFromSettings:n=>{const r=jb(n.projects??[]),s=t(),o=n.activeProjectId===void 0?r.some(f=>f.id===s.activeProjectId)?s.activeProjectId:null:typeof n.activeProjectId=="string"&&n.activeProjectId.trim()?n.activeProjectId.trim():null,i=r.map(f=>f.id),a=JSON.stringify(s.projects)!==JSON.stringify(r),l=s.activeProjectId!==o,d=s.manualProjectOrder.length!==i.length||s.manualProjectOrder.some((f,u)=>f!==i[u]);if(!a&&!l){d&&(e({manualProjectOrder:i}),Kh(i));return}if(e({projects:r,activeProjectId:o,manualProjectOrder:i}),Ab(r,o),Kh(i),o&&(l||n.activeProjectId!==void 0)){const f=r.find(u=>u.id===o);f&&nt.getState().setDirectory(f.path,{showOverlay:!1})}},getActiveProject:()=>{const{projects:n,activeProjectId:r}=t();return r?n.find(s=>s.id===r)??null:null}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("pichamber:settings-synced",e=>{const t=e.detail;t&&typeof t=="object"&&ct.getState().synchronizeFromSettings(t)});const vs=ce,Tk=(e,t)=>{const n=vs(t);if(!n)return null;let r=null;for(const s of e){const o=vs(s.path);o&&(n!==o&&!n.startsWith(`${o}/`)||(!r||o.length>(vs(r.path)?.length??0))&&(r=s))}return r},Zn=(e,t,n)=>{const s=vs((typeof t=="string"?t:n)??null);if(!s)return null;const o=Tk(e,s);if(o)return o;if(!(t instanceof Map))return null;const i=new Map;for(const l of e){const d=vs(l.path);d&&i.set(d,l)}let a=null;for(const[l,d]of t){const f=vs(l),u=f?i.get(f):null;if(u)for(const h of d??[]){const m=vs(h?.path??null);m&&(s!==m&&!s.startsWith(`${m}/`)||(!a||m.length>a.worktreePath.length)&&(a={project:u,worktreePath:m}))}}return a?.project??null},w0=500,Ak=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("PICHAMBER_STARTUP_TRACE")==="1"}catch{return!1}},it=(e,t)=>{if(!Ak())return;const n=typeof performance<"u"?performance.now():Date.now();window.__PICHAMBER_STARTUP_TRACE_START__??=n,window.__PICHAMBER_STARTUP_TRACE__??=[],window.__PICHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__PICHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__PICHAMBER_STARTUP_TRACE__.length>w0&&window.__PICHAMBER_STARTUP_TRACE__.splice(0,window.__PICHAMBER_STARTUP_TRACE__.length-w0)},Nk=()=>{const e=typeof window<"u"?window.__PICHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(r=>r.name==="ModelControls:ready"),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(r=>r.name.includes("checkConnection")||r.name.includes("checkHealth")||r.name.includes("initializeApp")||r.name.includes("initApp")||r.name.includes("loadProviders")||r.name.includes("config.defaults")||r.name.includes("modelsMetadata")||r.name.includes("ModelControls")||r.name.includes("activateDirectory"))};typeof window<"u"&&(window.__PICHAMBER_STARTUP_TRACE_SUMMARY__=Nk);const Zh=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();it(`${e}:start`,n);try{const s=await t(),o=typeof performance<"u"?performance.now():Date.now();return it(`${e}:end`,{durationMs:Math.round(o-r)}),s}catch(s){const o=typeof performance<"u"?performance.now():Date.now();throw it(`${e}:error`,{durationMs:Math.round(o-r),error:s instanceof Error?s.message:String(s)}),s}},jc="https://models.dev/api.json",Sa=e=>typeof e=="object"&&e!==null,rd=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Lk=e=>{if(!Sa(e))return!1;const t=e;if(!t.modalities)return!0;const{input:n,output:r}=t.modalities;return(!n||rd(n))&&(!r||rd(r))},Rk=e=>{if(!Sa(e))return!1;const t=e;return t.models===void 0||Sa(t.models)},Nb=(e,t)=>{const n=e?.toLowerCase?.()??"";return!n||!t?"":`${n}/${t}`},S0=e=>{if(!e)return[];const t=[];return e.text&&t.push("text"),e.audio&&t.push("audio"),e.image&&t.push("image"),e.video&&t.push("video"),e.pdf&&t.push("pdf"),t},Pk=(e,t)=>({id:t.id,providerId:e,name:t.name,tool_call:t.capabilities?.toolcall,reasoning:t.capabilities?.reasoning,temperature:t.capabilities?.temperature,attachment:t.capabilities?.attachment,modalities:t.capabilities?{input:S0(t.capabilities.input),output:S0(t.capabilities.output)}:void 0,cost:t.cost?{input:t.cost.input,output:t.cost.output,cache_read:t.cost.cache?.read,cache_write:t.cost.cache?.write}:void 0,limit:t.limit,release_date:t.release_date}),Dk=e=>{const t=new Map;if(!Sa(e))return t;for(const[n,r]of Object.entries(e)){if(!Rk(r))continue;const s=typeof r.id=="string"&&r.id.length>0?r.id:n,o=r.models;if(!(!o||!Sa(o)))for(const[i,a]of Object.entries(o)){if(!Lk(a))continue;const l=i||a.id;if(!l)continue;const d=Nb(s,l);d&&t.set(d,{id:typeof a.id=="string"&&a.id.length>0?a.id:l,providerId:s,name:typeof a.name=="string"?a.name:void 0,tool_call:typeof a.tool_call=="boolean"?a.tool_call:void 0,reasoning:typeof a.reasoning=="boolean"?a.reasoning:void 0,temperature:typeof a.temperature=="boolean"?a.temperature:void 0,attachment:typeof a.attachment=="boolean"?a.attachment:void 0,structured_output:typeof a.structured_output=="boolean"?a.structured_output:void 0,modalities:a.modalities?{input:rd(a.modalities.input)?a.modalities.input:void 0,output:rd(a.modalities.output)?a.modalities.output:void 0}:void 0,cost:a.cost,limit:a.limit,knowledge:typeof a.knowledge=="string"?a.knowledge:void 0,release_date:typeof a.release_date=="string"?a.release_date:void 0,last_updated:typeof a.last_updated=="string"?a.last_updated:void 0})}}return t},Ok=async()=>{if(typeof fetch!="function")return new Map;const e=typeof AbortController<"u"?new AbortController:void 0,t=e?setTimeout(()=>e.abort(),8e3):void 0;try{const n=await fetch(jc,{signal:e?.signal,headers:{Accept:"application/json"},cache:"no-store",mode:"cors"});if(!n.ok)throw new Error(`Metadata request to ${jc} returned status ${n.status}`);return Dk(await n.json())}catch(n){return n?.name==="AbortError"?console.warn(`Model metadata request aborted (${jc})`):console.warn(`Failed to fetch model metadata from ${jc}:`,n),new Map}finally{t&&clearTimeout(t)}};let Qi=null;const Hk=3e4;let ro=null;const Fk=1500;let Tc=null;const Bk=()=>{if(typeof window<"u"&&typeof window.requestIdleCallback=="function")return window.requestIdleCallback.bind(window);const e=globalThis.requestIdleCallback;return typeof e=="function"?e:null},Yh=(e,t)=>{e().size>0||Qi||ro!==null&&Date.now()-ro<Hk||(it("modelsMetadata:queued"),Qi=Zh("modelsMetadata",Ok).then(n=>(n.size>0?(ro=null,it("modelsMetadata:set",{entries:n.size}),t(n)):ro=Date.now(),n)).catch(()=>(ro=Date.now(),new Map)).finally(()=>{Qi=null}))},Vk=()=>{Qi=null,ro=null},$k=(e,t)=>{if(e().size>0||Qi||Tc)return;it("modelsMetadata:scheduledIdle");const n=()=>{Tc=null,it("modelsMetadata:idleFired"),Yh(e,t)},r=Bk();if(r){Tc={kind:"idle",handle:r(n,{timeout:5e3})};return}Tc={kind:"timeout",handle:setTimeout(n,Fk)}},zk=(e,t,n,r)=>{const s=Nb(t,n);if(s)return e.get(s)??(r?Pk(t,r):void 0)},Lb=e=>{if(!e)return null;const t=e.indexOf("/");return t<=0||t>=e.length-1?null:{providerId:e.slice(0,t),modelId:e.slice(t+1)}},Uk=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!Lb(n))continue;const s=dn(r);s&&(t[n]=s)}return t},qk=async()=>{try{const e=await Rt("/api/pi/settings",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return{ok:!1};const n=(await e.json())?.pichamber,r=n?.defaultModel;let s;if(r&&typeof r.providerId=="string"&&typeof r.modelId=="string"){const o=r.providerId.trim(),i=r.modelId.trim();o&&i&&(s=`${o}/${i}`)}return{ok:!0,defaultModel:s,defaultThinking:dn(n?.defaultThinking)??void 0,defaultThinkingByModel:Uk(n?.defaultThinkingByModel)}}catch{return{ok:!1}}},af=e=>{const t=typeof e.defaultModel=="string"?e.defaultModel.trim():"",n=typeof e.defaultVariant=="string"?e.defaultVariant.trim():"",r=typeof e.zenModel=="string"?e.zenModel.trim():"",s=e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse"||e.messageStreamTransport==="auto"?e.messageStreamTransport:void 0;return{defaultModel:t.length>0?t:void 0,defaultVariant:n.length>0?n:void 0,autoCreateWorktree:typeof e.autoCreateWorktree=="boolean"?e.autoCreateWorktree:void 0,zenModel:r.length>0?r:void 0,messageStreamTransport:s}},Wk=async()=>{it("config.defaults:start");const e=typeof performance<"u"?performance.now():Date.now(),t=(n,r)=>{const s=typeof performance<"u"?performance.now():Date.now();return it("config.defaults:end",{source:n,durationMs:Math.round(s-e),hasDefaultModel:!!r.defaultModel}),r};try{const n=await qk(),r=(l,d)=>n.ok?t(l,{...d,defaultModel:n.defaultModel,defaultThinking:n.defaultThinking,defaultThinkingByModel:n.defaultThinkingByModel}):t(l,d),s=await wS().catch(()=>null);if(s)return r("shared-settings",af(s));const o=zr()?.settings;if(o)try{const d=(await o.load())?.settings;if(d)return r("runtime-settings",af(d))}catch{}const i=await Rt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!i.ok)return r("settings-route-not-ok",{});const a=await i.json();return r("settings-route",a&&typeof a=="object"&&!Array.isArray(a)?af(a):{})}catch(n){return it("config.defaults:error",{error:n instanceof Error?n.message:String(n)}),t("error",{})}},Kk=3e4,Ac=new Map,C0=new WeakMap;let Nc=0;const Gk=(e,t)=>JSON.stringify([e,ce(t)??t]),Zk=(e,t)=>e.length===t.length&&e.every((n,r)=>{const s=t[r];return s&&n.path===s.path&&n.head===s.head&&n.branch===s.branch&&n.name===s.name&&n.isPrimary===s.isPrimary&&n.detached===s.detached&&n.locked===s.locked&&n.prunable===s.prunable}),k0=()=>({worktrees:[],status:"idle",error:null,fetchedAt:0}),Qt=Et()((e,t)=>({runtimeKey:Y(),projects:new Map,refreshProject:async(n,r,s)=>{const o=ce(n);if(!o)return null;const i=Y(),a=Nc,l=Gk(i,o),d=Ac.get(l);if(d)return d;const f=t().projects.get(o)??k0();if(!s?.force&&f.status==="ready"&&f.error===null&&Date.now()-f.fetchedAt<Kk)return f.worktrees;f.status==="idle"&&e(h=>{const m=new Map(h.projects);return m.set(o,{...f,status:"loading"}),{projects:m}});const u=(async()=>{try{const m=await r.checkIsGitRepository(o)?await(()=>{if(!r.listGitWorktrees)throw new Error("Git worktrees are unavailable for this runtime.");return r.listGitWorktrees(o)})():[];return a!==Nc||i!==Y()||t().runtimeKey!==i?null:(e(g=>{const x=g.projects.get(o)??k0(),b=Zk(x.worktrees,m);if(b&&x.status==="ready"&&x.error===null)return g;const S=new Map(g.projects);return S.set(o,{worktrees:b?x.worktrees:m,status:"ready",error:null,fetchedAt:Date.now()}),{projects:S}}),m)}catch(h){if(a!==Nc||i!==Y()||t().runtimeKey!==i)return null;const m=h instanceof Error?h.message:"Failed to discover Git worktrees.";return e(g=>{const x=g.projects.get(o)??f,b=new Map(g.projects);return b.set(o,{...x,status:"failed",error:m}),{projects:b}}),null}finally{Ac.delete(l)}})();return Ac.set(l,u),u},resetForRuntimeSwitch:n=>{Nc+=1,Ac.clear(),e({runtimeKey:n,projects:new Map})}})),Yk=(e,t)=>{const n=ce(t??null);if(!n)return[];const r=e.projects.get(n)?.worktrees;if(!r)return[];const s=C0.get(r);if(s)return s;const o=r.filter(i=>!i.isPrimary&&!i.prunable);return C0.set(r,o),o},Ln=(e,t)=>{const n=new Map;for(const r of e){const s=ce(r.path??null);s&&n.set(s,Yk(t,s))}return n},Am="__global__",xs=e=>{const t=typeof e=="string"?e.trim():"";return t.length>0?t:Am},ls=e=>e===Am?null:e,Xk=()=>typeof window>"u"?Am:Cl(nt.getState().currentDirectory),Rb="oc.worktreeProjectMap.v2",Xh="oc.worktreeProjectMap",Jk=8,M0=new Map,Pb=()=>{try{const e=typeof localStorage<"u"?localStorage.getItem(Rb):null;if(!e)return{version:2,legacyClaimed:!1,runtimes:{}};const t=JSON.parse(e);return t.version!==2||!t.runtimes||typeof t.runtimes!="object"?{version:2,legacyClaimed:!1,runtimes:{}}:{version:2,legacyClaimed:t.legacyClaimed===!0,runtimes:t.runtimes}}catch{return{version:2,legacyClaimed:!1,runtimes:{}}}},Db=e=>{const t=Object.fromEntries(Object.entries(e.runtimes).sort(([,n],[,r])=>r.updatedAt-n.updatedAt).slice(0,Jk));localStorage.setItem(Rb,JSON.stringify({...e,runtimes:t}))},Ob=()=>{const e=Y()||"default",t=M0.get(e);if(t)return t;const n=Pb();let r=n.runtimes[e]?.entries??null;if(!r&&!n.legacyClaimed)try{const o=typeof localStorage<"u"?localStorage.getItem(Xh):null;r=o?JSON.parse(o):{},n.legacyClaimed=!0,n.runtimes[e]={updatedAt:Date.now(),entries:r},Db(n),localStorage.removeItem(Xh)}catch{r={}}const s=r??{};return M0.set(e,s),s},Qk=(e,t)=>{if(!e||!t||e===t)return;const n=Ob();if(n[e]!==t){n[e]=t;try{const r=Y()||"default",s=Pb();s.legacyClaimed=!0,s.runtimes[r]={updatedAt:Date.now(),entries:n},Db(s),localStorage.removeItem(Xh)}catch{}}},ea=e=>{const t=ce(e);return t===null?null:t||"/"},eM=()=>{try{return ct.getState().projects.map(e=>ea(e.path)).filter(e=>!!e)}catch{return[]}},tM=()=>{try{const{projects:e,activeProjectId:t}=ct.getState(),n=t?e.find(r=>r.id===t):null;return ea(n?.path??e[0]?.path??null)}catch{return null}},Sl=e=>{const t=ea(e),n=eM();if(!t)return null;if(n.includes(t))return t;const r=ea(Ob()[t]);if(r)return r;try{const s=ct.getState().projects,o=Zn(s,Ln(s,Qt.getState()),t),i=ea(o?.path??null);if(i&&i!==t)return Qk(t,i),i}catch{return null}return null},Cl=e=>xs(Sl(e)),Hb="__add_provider__",os="zen",I0="big-pickle",Fb=e=>Lb(e),Bb=(e,t)=>{const n=dn(t);return n&&Em(e).includes(n)?n:void 0},E0=e=>e===Hb?"":e??"",sd=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},od=(e,t,n)=>{const r=e.find(s=>s.id===t);return r?r.models.some(s=>s.id===n):!1},nM=({providers:e,currentProviderId:t,currentModelId:n,currentVariant:r,settingsDefaultModel:s,settingsDefaultVariant:o})=>{const i=(d,f,u)=>{if(!u)return;const h=e.find(m=>m.id===d)?.models.find(m=>m.id===f);return Bb(h,u)};if(t&&n&&od(e,t,n))return{providerId:t,modelId:n,variant:i(t,n,r)};if(s){const d=Fb(s);if(d&&od(e,d.providerId,d.modelId))return{providerId:d.providerId,modelId:d.modelId,variant:i(d.providerId,d.modelId,o)}}const a=e.find(d=>d.authenticated&&d.models.length>0)||e.find(d=>d.models.length>0)||e[0],l=a?.models[0];return a&&l?{providerId:a.id,modelId:l.id}:null},cf=({providers:e,settingsZenModel:t})=>{const n=sd(t);if(!Array.isArray(e)||e.length===0)return n?{providerId:os,modelId:n}:null;if(n&&od(e,os,n))return{providerId:os,modelId:n};if(od(e,os,I0))return{providerId:os,modelId:I0};const r=e.find(s=>s.id===os);if(r?.models.length){const s=Math.floor(Math.random()*r.models.length),o=sd(r.models[s]?.id);if(o)return{providerId:os,modelId:o}}return null},rM=4,sM=800,oM=3e4,iM=1e3,aM=e=>{const t={...e};delete t.agents,delete t.currentAgentName,delete t.agentModelSelections,delete t.runtimeDefaultAgent,delete t.runtimeDefaultModel,delete t.settingsDefaultFileViewerPreview,delete t.defaultFileViewerPreview,delete t.settingsGitmojiEnabled,delete t.gitmojiEnabled;const n=e.directoryScoped;if(n&&typeof n=="object"){const a={};for(const[l,d]of Object.entries(n)){if(!d||typeof d!="object"){a[l]=d;continue}const f={...d};delete f.agents,delete f.currentAgentName,delete f.agentModelSelections,delete f.runtimeDefaultAgent,delete f.runtimeDefaultModel,delete f.settingsDefaultFileViewerPreview,delete f.defaultFileViewerPreview,a[l]=f}t.directoryScoped=a}const r=t.directoryScoped,s=t.activeDirectoryKey;if(!r||!s)return t;const o=r[s];if(!o)return t;const i={...t};return(!i.providers||i.providers.length===0)&&o.providers?.length&&(i.providers=o.providers),(!i.defaultProviders||Object.keys(i.defaultProviders).length===0)&&o.defaultProviders&&Object.keys(o.defaultProviders).length>0&&(i.defaultProviders=o.defaultProviders),o.selectionSource&&(i.selectionSource=o.selectionSource),i},_0=new Map,cM=(e,t)=>{const n=e.get(t);return typeof n=="number"&&Date.now()-n<oM},lM=e=>new Promise(t=>setTimeout(t,e)),Vb=async()=>(await Ie.health({runtimeKey:Y()})).state==="ready",dM=async(e=sM)=>Promise.race([Vb().catch(()=>!1),lM(Math.max(1,e)).then(()=>!1)]),j0=new Set;function uM(e){return j0.add(e),()=>{j0.delete(e)}}function fM(e,t){return e.scopes.includes("all")||e.scopes.includes(t)}const hM=async(e,t)=>{const n=e.getState(),r=Array.from(new Set([n.activeDirectoryKey,...Object.keys(n.directoryScoped)])).filter(a=>a.length>0);n.invalidateProviderCache();let s=0;const o=Math.min(rM,r.length),i=Array.from({length:o},async()=>{for(;s<r.length;){const a=r[s];s+=1,await e.getState().loadProviders({directory:ls(a),source:t})}});await Promise.all(i)};let T0=null,A0=null;const pM=e=>{typeof window<"u"&&(window.__zustand_config_store__=e),T0||(T0=uM(async t=>{fM(t,"providers")&&await hM(e,"configChange:providers")})),typeof window<"u"&&!A0&&(A0=nt.subscribe((t,n)=>{const r=xs(t.currentDirectory),s=xs(n.currentDirectory);r!==s&&(it("directoryStore:changed",{previous:s,next:r}),e.getState().activateDirectory(t.currentDirectory))}))},mM=e=>{if(e.authenticated!==!0)return!1;const t=e.models;return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!1},gM=e=>e.filter(mM),yM=async()=>{const e=await Ie.listProviders({runtimeKey:Y()}),n=gM(e.providers).map(s=>{const o=s.models.map(i=>({id:i.id,name:i.label??i.id,providerID:i.providerId,reasoning:i.supportsThinking===!0,...Number.isSafeInteger(i.contextWindow)?{limit:{context:i.contextWindow}}:{},...Array.isArray(i.thinkingLevels)&&i.thinkingLevels.length>0?{thinkingLevels:i.thinkingLevels}:{}}));return{id:s.id,name:s.label??s.id,authenticated:s.authenticated===!0,models:o}}),r=e.default?{[e.default.providerId]:e.default.modelId}:{};return{providers:n,defaults:r}},lf=e=>new Promise(t=>setTimeout(t,e)),df=new Map;let Lc=null;const We=Et()(gr(Gd((e,t)=>({activeDirectoryKey:Xk(),directoryScoped:{},providers:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,selectedProviderId:"",defaultProviders:{},selectionSource:"auto",isConnected:!1,hasEverConnected:!1,connectionPhase:"connecting",lastDisconnectReason:null,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultThinking:void 0,settingsDefaultThinkingByModel:{},settingsAutoCreateWorktree:!1,settingsZenModel:void 0,activateDirectory:async n=>{const r=Sl(n),s=typeof n=="string"&&n.trim().length>0;if(!r&&s){it("activateDirectory:skippedUnknownDirectory",{directory:n});return}const o=xs(r);let i=!1;e(a=>{const l=a.directoryScoped[o];return l?(i=l.providers.length>0,{activeDirectoryKey:o,providers:l.providers,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,selectedProviderId:l.selectedProviderId,defaultProviders:l.defaultProviders,selectionSource:l.selectionSource??"auto"}):{activeDirectoryKey:o,providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{},selectionSource:"auto"}}),t().isConnected&&(i?cM(_0,o)?it("activateDirectory:providersFresh",{directoryKey:o}):(it("activateDirectory:refreshProvidersBackground",{directoryKey:o}),t().loadProviders({directory:ls(o),source:"activateDirectory:refresh"})):await t().loadProviders({directory:ls(o),source:"activateDirectory"}))},invalidateProviderCache:n=>{const r=n===void 0?null:xs(n);e(s=>{const o={};let i=!1;const a={...s.directoryScoped},l=d=>d.providers.length===0&&Object.keys(d.defaultProviders).length===0?d:(i=!0,{...d,providers:[],defaultProviders:{}});if(r){const d=s.directoryScoped[r];d&&(a[r]=l(d))}else for(const[d,f]of Object.entries(s.directoryScoped))a[d]=l(f);return i&&(o.directoryScoped=a),(r===null||r===s.activeDirectoryKey)&&(s.providers.length>0&&(o.providers=[]),Object.keys(s.defaultProviders).length>0&&(o.defaultProviders={})),Object.keys(o).length>0?o:s})},loadProviders:async n=>{const r=n?.directory??ls(t().activeDirectoryKey),s=Sl(r),o=typeof r=="string"&&r.trim().length>0;if(!s&&o){it("loadProviders:skippedUnknownDirectory",{requestedDirectory:r,source:n?.source??"unknown"});return}const i=s??null,a=xs(s),l=n?.source??"unknown";it("loadProviders:called",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i});const d=df.get(a);if(d)return it("loadProviders:deduped",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i}),d;const f=(async()=>{const u=typeof performance<"u"?performance.now():Date.now();it("loadProviders:start",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i});const h=t().directoryScoped[a],m=h?.providers??(t().activeDirectoryKey===a?t().providers:[]),g=h?.defaultProviders??(t().activeDirectoryKey===a?t().defaultProviders:{});let x=null;for(let b=0;b<3;b++)try{const S=await Zh("loadProviders:api",async()=>yM(),{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,attempt:b+1}),y=S?.providers??[],v=S?.defaults??{};e(w=>{const I=w.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},E=w.activeDirectoryKey===a?w.currentProviderId:I.currentProviderId,T=w.activeDirectoryKey===a?w.currentModelId:I.currentModelId,A=w.activeDirectoryKey===a?w.currentVariant:I.currentVariant,j=nM({providers:y,currentProviderId:E,currentModelId:T,currentVariant:A,settingsDefaultModel:w.settingsDefaultModel,settingsDefaultVariant:w.settingsDefaultVariant}),k=w.activeDirectoryKey===a?w.selectedProviderId:I.selectedProviderId,_=k===Hb||y.some(O=>O.id===k)?k:j?.providerId??y[0]?.id??"",M={...I,providers:y,defaultProviders:v,currentProviderId:j?.providerId??"",currentModelId:j?.modelId??"",currentVariant:j?.variant,selectedProviderId:_},L={directoryScoped:{...w.directoryScoped,[a]:M}};return w.activeDirectoryKey===a&&(L.providers=y,L.defaultProviders=v,L.currentProviderId=M.currentProviderId,L.currentModelId=M.currentModelId,L.currentVariant=M.currentVariant,L.selectedProviderId=_),L});const C=typeof performance<"u"?performance.now():Date.now();it("loadProviders:end",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,durationMs:Math.round(C-u),providers:y.length,models:y.reduce((w,I)=>w+I.models.length,0)}),_0.set(a,Date.now());return}catch(S){x=S,it("loadProviders:attemptError",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,attempt:b+1,error:S instanceof Error?S.message:String(S)});const y=200*(b+1);await new Promise(v=>setTimeout(v,y))}console.error("Failed to load providers:",x),it("loadProviders:error",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,error:x instanceof Error?x.message:String(x)}),e(b=>{const y={...b.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},providers:m,defaultProviders:g},v={directoryScoped:{...b.directoryScoped,[a]:y}};if(b.activeDirectoryKey===a&&(v.providers=m,v.defaultProviders=g,!b.currentProviderId&&!b.currentModelId&&b.settingsDefaultModel)){const C=Fb(b.settingsDefaultModel);if(C){const w=m.find(I=>I.id===C.providerId);if(w?.models.some(I=>I.id===C.modelId)){const I=w.models.find(T=>T.id===C.modelId),E=Bb(I,b.settingsDefaultVariant);v.currentProviderId=C.providerId,v.currentModelId=C.modelId,v.currentVariant=E,v.selectedProviderId=C.providerId,y.currentProviderId=C.providerId,y.currentModelId=C.modelId,y.currentVariant=E,y.selectedProviderId=C.providerId}}}return v})})().finally(()=>df.delete(a));return df.set(a,f),f},setProvider:n=>{const{providers:r}=t(),s=r.find(a=>a.id===n);if(!s)return;const i=s.models[0]?.id||"";e(a=>{const l=a.activeDirectoryKey,f={...a.directoryScoped[l]??{providers:a.providers,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,selectedProviderId:a.selectedProviderId,defaultProviders:a.defaultProviders},currentProviderId:n,currentModelId:i,selectedProviderId:n,selectionSource:"manual"};return{currentProviderId:n,currentModelId:i,selectedProviderId:n,selectionSource:"manual",directoryScoped:{...a.directoryScoped,[l]:f}}})},setModel:n=>{e(r=>{const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentVariant:r.currentVariant,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},currentModelId:n,selectionSource:"manual"};return{currentModelId:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},setCurrentVariant:n=>{e(r=>{if(r.currentVariant===n)return r;const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentVariant:r.currentVariant,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},currentVariant:n,selectionSource:"manual"};return{currentVariant:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},getCurrentModelVariants:()=>Em(t().getCurrentModel()),cycleCurrentVariant:()=>{const n=_m(t().getCurrentModelVariants(),t().currentVariant,1);t().setCurrentVariant(n)},setSelectedProvider:n=>{e(r=>{const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},selectedProviderId:n,selectionSource:"manual"};return{selectedProviderId:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},invalidateModelMetadataCache:()=>{Vk(),e({modelsMetadata:new Map})},ensureModelMetadata:()=>{Yh(()=>t().modelsMetadata,n=>e({modelsMetadata:n}))},setSettingsDefaultModel:n=>{e({settingsDefaultModel:n})},setSettingsDefaultVariant:n=>{e({settingsDefaultVariant:n})},setSettingsDefaultThinking:n=>{e({settingsDefaultThinking:n})},setSettingsDefaultThinkingByModel:n=>{e({settingsDefaultThinkingByModel:n})},setSettingsAutoCreateWorktree:n=>{e({settingsAutoCreateWorktree:n})},setSettingsZenModel:n=>{e({settingsZenModel:n})},getResolvedGitGenerationModel:()=>{const n=t();return cf({providers:n.providers,settingsZenModel:n.settingsZenModel})},probeConnection:async n=>{if(await dM(n?.timeoutMs))return e({isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),!0;const s=t();return s.isConnected?!0:(e({isConnected:!1,connectionPhase:s.hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"health_probe_unhealthy"}),!1)},checkConnection:async()=>{it("checkConnection:start");const n=5;let r=0,s=null;for(;r<n;)try{it("checkConnection:attempt",{attempt:r+1});const o=await Zh("checkConnection:health",()=>Vb(),{attempt:r+1});if(!o&&r<n-1){const a=t().hasEverConnected;e({isConnected:!1,connectionPhase:a?"reconnecting":"connecting",lastDisconnectReason:"health_check_unhealthy"}),r+=1,await lf(400*r);continue}const i=t().hasEverConnected;return e(o?{isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}:{isConnected:!1,connectionPhase:i?"reconnecting":"connecting",lastDisconnectReason:"health_check_unhealthy"}),it("checkConnection:end",{healthy:o,attempts:r+1}),o}catch(o){s=o,r+=1;const i=400*r;await lf(i)}return s&&console.warn("[ConfigStore] Failed to reach Pi after retrying:",s),e({isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"health_check_failed"}),it("checkConnection:end",{healthy:!1,attempts:n}),!1},initializeApp:async()=>{if(Lc)return it("initializeApp:deduped"),Lc;const n=(async()=>{const r=typeof performance<"u"?performance.now():Date.now();it("initializeApp:start");try{const s=A5();s&&console.log("Starting app initialization...");const o=await t().checkConnection();if(s&&console.log("Connection check result:",o),!o){s&&console.log("Server not connected"),e({isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting"});return}s&&console.log("Initializing app..."),it("initApp:skipped",{reason:"checkConnection already verified health"});const i=nt.getState().currentDirectory??ls(t().activeDirectoryKey),a=Zn(ct.getState().projects,null,i??null),l=Sl(a?.path??i??null),d=l??tM();d||it("initializeApp:globalConfigScope"),d&&!l&&i!==d&&(it("initializeApp:normalizedUnknownDirectoryToProject",{initialDirectory:i,configDirectory:d}),nt.getState().setDirectory(d,{showOverlay:!1}));const f=xs(d);t().activeDirectoryKey!==f&&e({activeDirectoryKey:f}),s&&console.log("Loading providers..."),await t().loadProviders({directory:d,source:"initializeApp"});const u=await Wk(),h=t().providers,m=sd(t().settingsZenModel),g=sd(u.zenModel),b=(cf({providers:h,settingsZenModel:m})??cf({providers:h,settingsZenModel:g}))?.modelId||g||m;e({settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultThinking:u.defaultThinking,settingsDefaultThinkingByModel:u.defaultThinkingByModel??{},settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsZenModel:b}),b&&b!==g&&$r({zenModel:b,gitProviderId:"",gitModelId:""}).catch(()=>{}),e({isInitialized:!0,isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),$k(()=>t().modelsMetadata,y=>e({modelsMetadata:y})),t().prewarmProjectConfigs(d);const S=typeof performance<"u"?performance.now():Date.now();it("initializeApp:end",{durationMs:Math.round(S-r),providers:t().providers.length}),s&&console.log("App initialized successfully")}catch(s){console.error("Failed to initialize app:",s),e({isInitialized:!1,isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"init_error"}),it("initializeApp:error",{error:s instanceof Error?s.message:String(s)})}})().finally(()=>{Lc=null});return Lc=n,n},prewarmProjectConfigs:async n=>{if(!t().isConnected)return;const r=Cl(n??ls(t().activeDirectoryKey)),s=ct.getState().projects.map(a=>a.path).filter(a=>typeof a=="string"&&a.trim().length>0),o=new Set([r]),i=[];for(const a of s){const l=Cl(a);if(o.has(l)||(o.add(l),t().directoryScoped[l]?.providers.length))continue;const f=ls(l);f&&i.push(f)}for(const a of i){if(await lf(iM),!t().isConnected)return;const l=Cl(a),d=t().directoryScoped[l],f=[];d?.providers.length||f.push(t().loadProviders({directory:a,source:"projectConfigPrewarm"})),f.length>0&&await Promise.allSettled(f)}},getCurrentProvider:()=>{const{providers:n,currentProviderId:r}=t();return n.find(s=>s.id===r)},getCurrentModel:()=>{const n=t().getCurrentProvider(),{currentModelId:r}=t();if(n)return n.models.find(s=>s.id===r)},getModelMetadata:(n,r)=>{Yh(()=>t().modelsMetadata,a=>e({modelsMetadata:a}));const{modelsMetadata:s,providers:o}=t(),i=o.find(a=>a.id===n)?.models.find(a=>a.id===r);return zk(s,n,r,i)}}),{name:"config-store",storage:mm(),merge:(e,t)=>aM({...t,...e&&typeof e=="object"?e:{}}),partialize:e=>({activeDirectoryKey:e.activeDirectoryKey,directoryScoped:Object.fromEntries(Object.entries(e.directoryScoped).map(([t,n])=>[t,{...n,selectedProviderId:E0(n.selectedProviderId)}])),providers:e.providers,currentProviderId:e.currentProviderId,currentModelId:e.currentModelId,currentVariant:e.currentVariant,selectedProviderId:E0(e.selectedProviderId),defaultProviders:e.defaultProviders,settingsDefaultModel:e.settingsDefaultModel,settingsDefaultVariant:e.settingsDefaultVariant,settingsDefaultThinking:e.settingsDefaultThinking,settingsDefaultThinkingByModel:e.settingsDefaultThinkingByModel,settingsAutoCreateWorktree:e.settingsAutoCreateWorktree,settingsZenModel:e.settingsZenModel})})));pM(We);const vM=5e3,wo=new Map,So=new Map,id=e=>{const t=Y();wo.delete(t),So.delete(t),(!t||t==="local")&&(wo.clear(),So.clear())},$b=()=>{wo.clear(),So.clear()},Hr=Et()(gr(Gd((e,t)=>({selectedSkillName:null,skills:[],isLoading:!1,setSelectedSkill:n=>e({selectedSkillName:n}),loadSkills:async()=>{const n=Y(),r=Date.now(),s=wo.get(n)??0;if(s>0&&r-s<vM)return!0;const o=So.get(n);if(o)return o;const i=(async()=>{e({isLoading:!0});try{const l=(await Ie.listResources({runtimeKey:n})).skills.map(d=>({id:d.id,name:d.name,path:d.id,scope:d.location==="project"?"project":"user",source:"agents",...d.description?{description:d.description}:{},location:d.location,...typeof d.content=="string"&&d.content.length>0?{content:d.content}:{},...d.editable===!0?{editable:!0}:{}}));return e(d=>({skills:l,isLoading:!1,...d.selectedSkillName&&!l.some(f=>f.name===d.selectedSkillName)?{selectedSkillName:null}:{}})),wo.set(n,Date.now()),!0}catch{return e({isLoading:!1}),!1}})();So.set(n,i);try{return await i}finally{So.delete(n)}},renameSkill:async()=>!1,updateSkillContent:async(n,r)=>{const s=t().skills.find(o=>o.name===n);if(!s)return!1;try{const i=(await Ie.updateResource({resourceId:s.id,content:r},{runtimeKey:Y()})).skills.map(a=>({id:a.id,name:a.name,path:a.id,scope:a.location==="project"?"project":"user",source:"agents",...a.description?{description:a.description}:{},location:a.location,...typeof a.content=="string"&&a.content.length>0?{content:a.content}:{},...a.editable===!0?{editable:!0}:{}}));return e({skills:i}),wo.set(Y(),Date.now()),!0}catch{return!1}},getSkillByName:n=>t().skills.find(r=>r.name===n),resetForRuntimeSwitch:()=>{$b(),e({skills:[],isLoading:!1,selectedSkillName:null})}}),{name:"skills-store",storage:mm(),partialize:e=>({selectedSkillName:e.selectedSkillName})}),{name:"skills-store"})),NX=Object.freeze(Object.defineProperty({__proto__:null,invalidateSkillsLoadCache:id,resetSkillsForRuntimeSwitch:$b,useSkillsStore:Hr},Symbol.toStringTag,{value:"Module"})),xM=200,zb=1440*60*1e3,bM=3e4,wM=15e3,SM=9e4,Jh="oc.session-activity.v1",CM=new Set,kM=new Map,Rn=Et(()=>({startedAt:new Map,settledMs:new Map})),js=new Map;let Nm=0,ad=null;const MM=()=>typeof performance<"u"&&Number.isFinite(performance.timeOrigin)?performance.timeOrigin:Date.now();let Lm=MM();const Ub=(e,t)=>e.start<=t&&t-e.start<=zb&&e.seen<=t&&Lm-e.seen<=bM,IM=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const{start:t,seen:n}=e;return typeof t!="number"||!Number.isFinite(t)||typeof n!="number"||!Number.isFinite(n)?null:{start:t,seen:n}},EM=()=>{const e=new Map;let t=null;try{t=Wd().getItem(Jh)}catch{return e}if(!t)return e;let n;try{n=JSON.parse(t)}catch{return e}if(!n||typeof n!="object"||Array.isArray(n))return e;const r=Date.now();for(const[s,o]of Object.entries(n)){const i=IM(o);i&&Ub(i,r)&&e.set(s,i)}return e},eu=()=>(ad??=EM(),ad),_M=e=>e-Lm>SM?(ad?.clear(),kM):eu(),ks=(e,t)=>{const n={};for(const[r,s]of eu())Ub(s,t)&&(n[r]=s);for(const[r,s]of e)n[r]={start:s,seen:js.get(r)??t};Nm=t;try{const r=Wd();if(Object.keys(n).length===0){r.removeItem(Jh);return}r.setItem(Jh,JSON.stringify(n))}catch{}},uf=()=>{const{startedAt:e}=Rn.getState();if(e.size===0)return;const t=Date.now();for(const n of e.keys())js.set(n,t);ks(e,t)};let N0=!1;const qb=()=>{if(!(N0||typeof window>"u")){N0=!0;try{window.addEventListener("pagehide",uf,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&uf()}),document.addEventListener("freeze",uf))}catch{}}},jM=e=>{for(;e.size>xM;){const t=e.keys().next();if(t.done)return;e.delete(t.value)}},L0=(e,t)=>{const n=Date.now(),r=_M(n),s=Rn.getState(),o={started:null,settled:null};let i=!1,a=!1;const l=()=>o.started??=new Map(s.startedAt),d=()=>o.settled??=new Map(s.settledMs);for(const u of e)i=!0,js.set(u,n),!(o.started??s.startedAt).has(u)&&(l().set(u,r.get(u)?.start??n),(o.settled??s.settledMs).has(u)&&d().delete(u));const f=(u,h)=>{l().delete(u),js.delete(u),d().set(u,Math.max(0,n-h))};if(t!==null){eu().delete(t)&&(a=!0);const u=s.startedAt.get(t);u!==void 0&&f(t,u)}if(o.settled&&jM(o.settled),(o.started||o.settled)&&Rn.setState({startedAt:o.started??s.startedAt,settledMs:o.settled??s.settledMs}),o.started){o.started.size>0&&qb(),ks(o.started,n);return}if(a){ks(s.startedAt,n);return}i&&s.startedAt.size>0&&n-Nm>=wM&&ks(s.startedAt,n)},R0=(e,t)=>{if(t==="active"){L0(new Set([e]),null);return}L0(CM,e)},Mn=(e,t,n)=>{if(!Number.isFinite(t))return;const r=Date.now(),s=Fo(t,n,r);if(s===void 0||r-s>zb||s>r+6e4)return;const o=Rn.getState(),i=o.startedAt.get(e);if(i!==void 0&&s>=i)return;const a=new Map(o.startedAt);a.set(e,s);const l=new Map(o.settledMs);l.delete(e),js.set(e,r),Rn.setState({startedAt:a,settledMs:l}),qb(),ks(a,r)},P0=e=>{const t=eu().delete(e),n=Rn.getState(),r=n.startedAt.has(e),s=n.settledMs.has(e);if(js.delete(e),!r&&!s){t&&ks(n.startedAt,Date.now());return}let o=n.startedAt;if(r){const a=new Map(n.startedAt);a.delete(e),o=a}let i=n.settledMs;if(s){const a=new Map(n.settledMs);a.delete(e),i=a}Rn.setState({startedAt:o,settledMs:i}),(r||t)&&ks(o,Date.now())},LX=(e={})=>{ad=null,js.clear(),Nm=0,Lm=e.pageLoadAt??Date.now(),Rn.setState({startedAt:new Map,settledMs:new Map})},Wb=e=>Rn(H.useCallback(t=>t.startedAt.get(e),[e])),RX=e=>Rn(H.useCallback(t=>t.settledMs.get(e),[e])),PX=(e,t)=>Rn(H.useCallback(n=>t?n.startedAt.has(e):n.settledMs.has(e),[t,e])),Qh="oc.sessions.pinned.v2",TM="oc.sessions.pinned",kl=Gt(),ep=(e,t,n)=>{const r=ce(t);return!e||!r||!n?null:JSON.stringify([e,r,n])},Kb=e=>{try{const t=JSON.parse(e);if(!Array.isArray(t)||t.length!==3)return null;const[n,r,s]=t;if(typeof n!="string"||typeof r!="string"||typeof s!="string")return null;const o=ce(r);return!n||!o||o!==r||!s?null:[n,o,s]}catch{return null}},cd=(e,t,n)=>{if(!t)return!1;const r=ep(Y(),t,n);return r?e.has(r):!1},AM=()=>{kl.removeItem(TM);const e=kl.getItem(Qh);if(e===null)return{ids:new Set,touchedAt:{}};try{const t=JSON.parse(e);if(t.version!==2||!t.sessions||typeof t.sessions!="object")return{ids:new Set,touchedAt:{}};const n=Object.entries(t.sessions).filter(([r,s])=>Kb(r)&&typeof s=="number"&&Number.isFinite(s)).sort((r,s)=>s[1]-r[1]);return{ids:new Set(n.map(([r])=>r)),touchedAt:Object.fromEntries(n)}}catch{return kl.removeItem(Qh),{ids:new Set,touchedAt:{}}}},D0=(e,t)=>{const n=[...e].filter(r=>Kb(r)!==null).map(r=>[r,t[r]??Date.now()]).sort((r,s)=>s[1]-r[1]);return{ids:new Set(n.map(([r])=>r)),touchedAt:Object.fromEntries(n)}},O0=({ids:e,touchedAt:t})=>{const n=Object.fromEntries([...e].map(r=>[r,t[r]??Date.now()]));kl.setItem(Qh,JSON.stringify({version:2,sessions:n}))},H0=AM(),Rm=Et((e,t)=>({ids:H0.ids,touchedAt:H0.touchedAt,setIds:n=>{const r=t().ids,s=typeof n=="function"?n(r):n;if(s===r)return;const o=D0(s,t().touchedAt);e(o),O0(o)},toggle:n=>{const r=ep(Y(),n.directory,n.sessionId);if(!r)return;const s=new Set(t().ids),o={...t().touchedAt};s.has(r)?(s.delete(r),delete o[r]):(s.add(r),o[r]=Date.now());const i=D0(s,o);e(i),O0(i)},clearPinnedSession:(n,r,s)=>{const o=ep(n,r,s);if(!o||!t().ids.has(o))return;const i=new Set(t().ids);i.delete(o),t().setIds(i)}})),DX=new Map,ld=new Map,Bo=new Map;let Ml=0;const Ca=Et(()=>({rankById:new Map})),F0=()=>(Ml=Math.max(Ml+1,Date.now()),Ml),NM=(e,t=!1)=>{const n=[...e];n.length!==0&&Ca.setState(r=>{const s=new Map(r.rankById),o=t?F0():null;for(const i of n)s.set(i,o??F0());return{rankById:s}})},LM=(e,t)=>{const n=ld.get(e);ld.set(e,t),t==="active"&&n!=="active"&&NM([e])},RM=e=>{ld.delete(e),Bo.delete(e),Ca.setState(t=>{if(!t.rankById.has(e))return t;const n=new Map(t.rankById);return n.delete(e),{rankById:n}})},OX=()=>{ld.clear(),Bo.clear(),Ml=0,Ca.setState({rankById:new Map})},tp=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Gb=e=>tp(e.time?.updated)||tp(e.time?.created),PM=e=>tp(e.time?.created),np=e=>e.parentID??null,rp=e=>{const t=e;return ce(t.directory??null)??ce(t.project?.worktree??null)},Di=(e,t)=>{const n=Bo.get(e.id),r=t?"created":"updated",s=n?.[r];if(s!==void 0)return s;const o=t?PM(e):Gb(e);return Bo.set(e.id,{...n,[r]:o}),o},DM=e=>{const t=Ca.getState().rankById;let n=!1;for(const r of e){const s=Gb(r);if(t.get(r.id)!==void 0)continue;const o=Bo.get(r.id);o?.updated!==void 0&&o.updated>=s||(Bo.set(r.id,{...o,updated:s}),n=!0)}n&&Ca.setState(r=>({rankById:new Map(r.rankById)}))},B0=(e,t,n=!1)=>t.get(e.id)??Di(e,n),Zb=(e,t,n,r,s)=>{if(n!==r)return n?-1:1;const o=Di(e,n),i=Di(t,r);if(np(e)===np(t)){const d=B0(t,s,r)-B0(e,s,n);if(d!==0)return d}const a=i-o;if(a!==0)return a;const l=Di(t,!0)-Di(e,!0);return l!==0?l:e.id.localeCompare(t.id)},HX=(e,t,n,r)=>Zb(e,t,cd(n,rp(e),e.id),cd(n,rp(t),t.id),r),OM=(e,t,n=r=>r)=>{const r=new Map,s=o=>{let i=r.get(o);return i===void 0&&(i=cd(e,rp(o),o.id),r.set(o,i)),i};return(o,i)=>{const a=n(o),l=n(i);return Zb(a,l,s(a),s(l),t)}},FX=(e,t,n)=>{const r=new Set(e.map(f=>f.id)),s=[],o=new Map;for(const f of e){const u=np(f);if(!u||!r.has(u)){s.push(f);continue}const h=o.get(u);h?h.push(f):o.set(u,[f])}const i=OM(t,n);s.sort(i);for(const f of o.values())f.sort(i);const a=[],l=new Set,d=f=>{if(!l.has(f.id)){l.add(f.id),a.push(f);for(const u of o.get(f.id)??[])d(u)}};for(const f of s)d(f);for(const f of e)d(f);return a},V0=500,HM=1e3*60*60*24*30;function FM(e){const t=Date.now()-HM,n=e.filter(r=>r.time>=t);return n.length<=V0?n:n.slice(n.length-V0)}function ff(e){const t={session:{unseenCount:{},unseenHasError:{}},project:{unseenCount:{},unseenHasError:{}}};for(const n of e)n.viewed||(n.session&&(t.session.unseenCount[n.session]=(t.session.unseenCount[n.session]??0)+1,n.type==="error"&&(t.session.unseenHasError[n.session]=!0)),n.directory&&(t.project.unseenCount[n.directory]=(t.project.unseenCount[n.directory]??0)+1,n.type==="error"&&(t.project.unseenHasError[n.directory]=!0)));return t}const tu=Et((e,t)=>({list:[],index:{session:{unseenCount:{},unseenHasError:{}},project:{unseenCount:{},unseenHasError:{}}},append:n=>{const r=t().list,s=FM([...r,n]);e({list:s,index:ff(s)})},markSessionViewed:n=>{const r=t();if((r.index.session.unseenCount[n]??0)===0)return;const o=r.list.map(i=>i.session===n&&!i.viewed?{...i,viewed:!0}:i);e({list:o,index:ff(o)})},markProjectViewed:n=>{const r=t();if((r.index.project.unseenCount[n]??0)===0)return;const o=r.list.map(i=>i.directory===n&&!i.viewed?{...i,viewed:!0}:i);e({list:o,index:ff(o)})},sessionUnseenCount:n=>t().index.session.unseenCount[n]??0,sessionHasError:n=>t().index.session.unseenHasError[n]??!1,projectUnseenCount:n=>t().index.project.unseenCount[n]??0,projectHasError:n=>t().index.project.unseenHasError[n]??!1}));function nu(e){tu.getState().markSessionViewed(e)}function Yb(e,t,n){const r=tu.getState();(r.index.session.unseenCount[e]??0)>0||r.append(n?.error?{type:"error",session:e,directory:t,error:n.error,time:Date.now(),viewed:!1}:{type:"turn-complete",session:e,directory:t,time:Date.now(),viewed:!1})}function Xb(e){const t=re.getState();if(!t.nativeNotificationsEnabled||e.kind==="completion"&&!t.notifyOnCompletion||e.kind==="error"&&!t.notifyOnError)return;const n=zr()?.notifications;if(!n)return;const r=e.title?.trim()||"Open PiChamber to review the session.";n.notify({title:e.kind==="error"?"Work failed":"Work completed",body:r,tag:`pichamber:${e.kind}:${e.sessionId}:${e.sequence}`,kind:e.kind,sessionId:e.sessionId,directory:e.directory,requireHidden:t.notificationMode!=="always"})}function Pm(e,t){return`pichamber:input:${e}:${t}`}function Jb(e){const t=re.getState();if(!t.nativeNotificationsEnabled||t.notifyOnInputNeeded===!1)return;const n=zr()?.notifications;if(!n)return;const r=e.title?.trim()||"Open PiChamber to answer.";n.notify({title:e.kind==="approval"?"Approval needed":"Input needed",body:r,tag:Pm(e.sessionId,e.since),kind:"input",sessionId:e.sessionId,directory:e.directory,requireHidden:t.notificationMode!=="always"})}function BM(e){return tu(t=>t.index.session.unseenCount[e]??0)}const BX=Object.freeze(Object.defineProperty({__proto__:null,dispatchInputNeededNotification:Jb,dispatchSessionNotification:Xb,inputNeededNotificationTag:Pm,markSessionViewed:nu,notifySessionTurnComplete:Yb,useNotificationStore:tu,useSessionUnseenCount:BM},Symbol.toStringTag,{value:"Module"})),VM="pichamber_sync_perf",Dm=()=>({pipelineRawEvents:0,pipelineCoalescedEvents:0,pipelineDeliveredEvents:0,reducerEvents:0,reducerChangedEvents:0,directoryStorePublications:0,streamingFullReconciliations:0,streamingIncrementalReconciliations:0,streamingStatusEntriesVisited:0,streamingSessionCandidatesVisited:0,streamingMessagesVisited:0,streamingHeartbeatAttempts:0,streamingHeartbeatCommits:0,permissionChangeCallbacks:0,questionChangeCallbacks:0,sessionMessageChangeCallbacks:0,sessionRenderableNotificationSkips:0,userMessageHistoryNotificationSkips:0,sessionMessageRecordNotificationSkips:0,materializationEnqueues:0,materializationEmptyAssistantEnqueues:0,materializationMissingMessageEnqueues:0,materializationMissingPartEnqueues:0,materializationLifecycleEnqueues:0,materializationPreflightSkips:0,materializationRequests:0,statusAggregationSessionEntries:0,statusAggregationCandidates:0,persistenceSerializations:0,persistenceStorageWrites:0,persistenceUtf8Bytes:0}),$M=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(VM)==="1"}catch{return!1}},Qb=$M();let Il=Qb||Xo()?Dm():null;const zM=()=>Xo()||Qb,Om=()=>zM()?(Il||(Il=Dm()),Il):null;function ew(){Om()&&(Il=Dm())}function tw(){const e=Om();return e?{...e}:null}function UM(e){const t=Om();t&&(t.persistenceSerializations+=1,t.persistenceUtf8Bytes+=new TextEncoder().encode(e).byteLength)}typeof window<"u"&&(window.__pichamberSyncPerformance={getSnapshot:tw,reset:ew});const sp="pichamber.chatDrafts.v2",qM=50,op=Gt(),ip=new Set;let Oi,or;const Qo=(e,t,n)=>{const r=ce(t);return!e||!r?null:{runtimeKey:e,directory:r,sessionId:n}},Jt=e=>JSON.stringify([e.runtimeKey,e.directory,e.sessionId]),nw=()=>{const e=op.getItem(sp);if(e===Oi&&or)return or;try{const t=JSON.parse(e??"");if(t.version!==2||!t.drafts||typeof t.drafts!="object"||Array.isArray(t.drafts))return Oi=e,or={version:2,drafts:{}},or;const n={};for(const[r,s]of Object.entries(t.drafts)){if(!s||typeof s!="object")continue;const o=s;typeof o.text!="string"||!Array.isArray(o.confirmedMentions)||typeof o.touchedAt!="number"||(n[r]={text:o.text,confirmedMentions:o.confirmedMentions.filter(i=>typeof i=="string"),touchedAt:o.touchedAt})}return Oi=e,or={version:2,drafts:n},or}catch{return op.removeItem(sp),Oi=null,or={version:2,drafts:{}},or}},WM=e=>{const t=JSON.stringify(e);Oi=t,or=e,UM(t),op.setItem(sp,t)},ru=e=>{if(!e)return{text:"",confirmedMentions:new Set};const t=nw().drafts[Jt(e)];return t?{text:t.text,confirmedMentions:new Set(t.confirmedMentions)}:{text:"",confirmedMentions:new Set}},Ts=(e,t,n)=>{if(!e)return;const r=nw(),s=Jt(e),o=Array.from(new Set(n));if(!t&&o.length===0){if(!(s in r.drafts))return;delete r.drafts[s]}else r.drafts[s]={text:t,confirmedMentions:o,touchedAt:Date.now()};const i=Object.entries(r.drafts).sort((a,l)=>l[1].touchedAt-a[1].touchedAt).slice(0,qM);WM({version:2,drafts:Object.fromEntries(i)})},KM=(e,t=!1)=>{Ts(e,"",[]),t&&ip.forEach(n=>n(e))},GM=e=>(ip.add(e),()=>ip.delete(e)),su=e=>({...e,previewUrl:void 0,uploadState:e.uploadState?{...e.uploadState}:e.uploadState}),ZM=["image/png","image/jpeg","image/gif","image/webp","image/heic","image/heif","application/pdf","application/zip","application/x-zip-compressed","application/gzip","application/x-tar","application/x-7z-compressed","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.presentation","application/vnd.oasis.opendocument.spreadsheet","text/*","application/json","application/ld+json","application/toml","application/x-toml","application/x-yaml","application/xml","application/yaml",".bat",".c",".cc",".cjs",".cmd",".conf",".cpp",".cs",".css",".csv",".cts",".dart",".diff",".docx",".drawio",".env",".erl",".ex",".exs",".fs",".fsx",".go",".gql",".graphql",".h",".har",".hh",".hcl",".heic",".heif",".hpp",".hrl",".htm",".html",".ini",".ipynb",".java",".jl",".js",".json",".jsonl",".jsx",".kt",".kts",".log",".lua",".md",".mdx",".mjs",".mts",".ndjson",".odp",".ods",".odt",".patch",".php",".proto",".pptx",".ps1",".py",".r",".rb",".rs",".sass",".scala",".scss",".sh",".sol",".sql",".svelte",".svg",".swift",".tf",".toml",".ts",".tsx",".txt",".vue",".xml",".xlsx",".yaml",".yml",".zig",".zip",".7z",".gz",".rar",".tar",".tgz",".zsh"],YM=ZM.join(","),XM=e=>{const t=e.toLowerCase().split(";",1)[0]?.trim()??"";if(t.startsWith("image/"))return"image";if(t.startsWith("audio/"))return"audio";if(t.startsWith("video/"))return"video";if(t==="application/pdf")return"pdf";if(t.startsWith("text/"))return"text"},JM=(e,t)=>{const n=new Set(t.map(s=>s.toLowerCase())),r=[];for(const s of e){const o=XM(s.mimeType);o&&!n.has(o)&&r.push({attachment:s,modality:o})}return r},QM=new Map([["image/png","image/png"],["image/jpeg","image/jpeg"],["image/gif","image/gif"],["image/webp","image/webp"],["application/pdf","application/pdf"]]),eI=new Map([["gif","image/gif"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["pdf","application/pdf"],["png","image/png"],["webp","image/webp"]]),tI=new Set(["application/json","application/ld+json","application/toml","application/x-toml","application/x-yaml","application/xml","application/yaml","image/svg+xml"]),nI=4096,rI=new Set(["docx","pptx","xlsx","odt","odp","ods"]),El="[REDACTED]",sI="[OMITTED BY PICHAMBER]",ap=/^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api[-_]?key|client[-_]?secret|password|secret|access[-_]?token|refresh[-_]?token|id[-_]?token|token)$/i,Hm=e=>{const t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()},rw=e=>e.type.split(";",1)[0]?.trim().toLowerCase()??"",oI=async e=>{const t=new Uint8Array(await e.slice(0,nI).arrayBuffer());if(t.some(r=>r===0))return;const n=t.filter(r=>r<9||r>13&&r<32).length;if(!(t.length>0&&n/t.length>.3))return"text/plain"},iI=e=>{const t=rw(e),n=QM.get(t);if(n)return n;const r=Hm(e.name),s=eI.get(r);return(!t||t==="application/octet-stream")&&s?s:t.startsWith("text/")||tI.has(t)||t.endsWith("+json")||t.endsWith("+xml")?"text/plain":oI(e).then(o=>o||t||"application/octet-stream")},Rc=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string").join(""):"",aI=(e,t)=>{if(!e||typeof e!="object")return;const n=e;if(!Array.isArray(n.cells))return;const r=typeof n.metadata?.kernelspec?.language=="string"?n.metadata.kernelspec.language:"",s=[`# Notebook: ${t}`];return n.cells.forEach((o,i)=>{if(!o||typeof o!="object")return;const a=o,l=Rc(a.source).trimEnd();if(a.cell_type==="markdown"){s.push(`## Markdown cell ${i+1}
|
|
9
|
+
|
|
10
|
+
${l}`);return}if(a.cell_type!=="code"||(s.push(`## Code cell ${i+1}
|
|
11
|
+
|
|
12
|
+
\`\`\`${r}
|
|
13
|
+
${l}
|
|
14
|
+
\`\`\``),!Array.isArray(a.outputs)))return;const d=[];for(const f of a.outputs){if(!f||typeof f!="object")continue;const u=f,h=Rc(u.text)||Rc(u.traceback);if(h){d.push(h.trimEnd());continue}if(u.data&&typeof u.data=="object"){const m=u.data,g=Rc(m["text/plain"]);g&&d.push(g.trimEnd());const x=Object.keys(m).filter(b=>b!=="text/plain");x.length>0&&d.push(`[Non-text output omitted: ${x.join(", ")}]`);continue}(typeof u.ename=="string"||typeof u.evalue=="string")&&d.push(`${String(u.ename??"Error")}: ${String(u.evalue??"")}`.trimEnd())}d.length>0&&s.push(`### Output
|
|
15
|
+
|
|
16
|
+
${d.join(`
|
|
17
|
+
|
|
18
|
+
`)}`)}),`${s.join(`
|
|
19
|
+
|
|
20
|
+
`)}
|
|
21
|
+
`},cI=e=>{try{const t=new URL(e);for(const n of Array.from(t.searchParams.keys()))ap.test(n)&&t.searchParams.set(n,El);return t.toString()}catch{return e}},cp=(e,t)=>{if(t&&ap.test(t))return El;if(t==="cookies"&&Array.isArray(e))return e.map(s=>!s||typeof s!="object"?s:{...s,value:El});if(t==="text"||t==="encoding")return sI;if(typeof e=="string")return t==="url"?cI(e):e;if(Array.isArray(e))return e.map(s=>cp(s));if(!e||typeof e!="object")return e;const n=e,r=typeof n.name=="string"&&ap.test(n.name);return Object.fromEntries(Object.entries(n).map(([s,o])=>[s,r&&s==="value"?El:cp(o,s)]))},lI=async(e,t)=>{const n=await e.text();if(t==="har")try{const r=cp(JSON.parse(n));return new File([`${JSON.stringify(r,null,2)}
|
|
22
|
+
`],e.name,{type:"text/plain"})}catch{return}if(t==="ipynb")try{const r=aI(JSON.parse(n),e.name);if(r)return new File([r],e.name,{type:"text/plain"})}catch{}return new File([n],e.name,{type:"text/plain"})},dI=async e=>{try{const t=(await mt(async()=>{const{default:o}=await import("./vendor-heic2any-sztndhZI.js").then(i=>i.h);return{default:o}},__vite__mapDeps([0,1]))).default,n=await t({blob:e,toType:"image/jpeg",quality:.9}),r=Array.isArray(n)?n[0]:n;if(!r)return;const s=e.name.replace(/\.(heic|heif)$/i,".jpg");return new File([r],s,{type:"image/jpeg"})}catch(t){console.warn("Failed to convert HEIC attachment to JPEG",t);return}},$0=e=>{const t=Hm(e.name),n=rw(e);if(n==="image/heic"||n==="image/heif"||t==="heic"||t==="heif")return dI(e).then(s=>s?{file:s,mimeType:"image/jpeg"}:void 0);if(t==="har"||t==="ipynb")return lI(e,t).then(s=>s?{file:s,mimeType:"text/plain"}:void 0);const r=iI(e);return typeof r=="string"?{file:e,mimeType:r}:r?.then(s=>s?{file:e,mimeType:s}:void 0)},uI=(e,t=[])=>{if(!rI.has(Hm(e.name))){const n=$0(e);return n instanceof Promise?n.then(r=>r?[r]:void 0):n?[n]:void 0}return mt(()=>import("./document-attachments-CZl9rK1z.js"),__vite__mapDeps([2,3])).then(async({extractDocumentAttachments:n})=>{const r=await n(e,t);if(!r)return;const s=[{file:r.textFile,mimeType:"text/plain"}];for(const o of r.images){const i=await $0(o);if(!i||!i.mimeType.startsWith("image/"))return;s.push(i)}return s})},fI=3,hI=3,pI=100*1024*1024,Zs=20;let so=0,hf=0;const Vo=[],Co=new Map,ps=new Map,dd=new Map,z0=(e,t)=>{if(e.length===0)return!1;const n=new Set(t.map(r=>r.filename.toLowerCase()));return e.some(r=>n.has(r.toLowerCase()))},Pc=(e="attachment")=>`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`,mI=(e,t)=>{if(!(!t.startsWith("image/")||typeof URL.createObjectURL!="function"))return URL.createObjectURL(e)},U0=new Set,sw=e=>{!e||U0.has(e)||(U0.add(e),typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(e))},gI=e=>{for(const t of e)sw(t.previewUrl)},yI=(e,t)=>new Promise((n,r)=>{const s=new FileReader;s.onload=()=>{const o=typeof s.result=="string"?s.result:"",i=o.indexOf(",");n(i===-1?o:`data:${t};base64,${o.slice(i+1)}`)},s.onerror=()=>r(s.error??new Error("Failed to read file")),s.onabort=()=>r(new Error("File read aborted")),s.readAsDataURL(e)}),ow=async e=>Promise.all(e.map(async t=>{if(t.source!=="local"||t.dataUrl.startsWith("data:"))return{...t,previewUrl:void 0};const n=t.file instanceof Blob?t.file:null;if(!n)throw new Error("Attachment data is unavailable");return{...t,dataUrl:await yI(n,t.mimeType),previewUrl:void 0}})),vI=e=>{if(!e.startsWith("data:"))return 0;const t=e.indexOf(",");if(t<0)return 0;const n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);if(!n.endsWith(";base64"))return 0;let s=0;return r.endsWith("==")?s=2:r.endsWith("=")&&(s=1),Math.max(0,Math.floor(r.length*3/4)-s)},xI=(e,t)=>{const n=e.indexOf(",");if(!e.startsWith("data:")||n<0)return null;const r=e.slice(5,n);if(!r.toLowerCase().endsWith(";base64"))return null;try{const s=atob(e.slice(n+1)),o=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)o[i]=s.charCodeAt(i);return new Blob([o],{type:r.slice(0,-7)||t})}catch{return null}},bI=e=>{const t=typeof e=="object"&&e&&"code"in e?String(e.code):"";return t==="ATTACHMENT_TOO_LARGE"?"File exceeds the 100 MB upload limit.":t==="ATTACHMENT_LIMIT_REACHED"?"Too many unused uploads. Remove a file and retry.":t==="DAEMON_UNAVAILABLE"?"The runtime changed or is unavailable. Retry the upload.":e instanceof DOMException&&e.name==="AbortError"?"Upload canceled.":"Upload failed. Retry or remove this file."},cn=(e,t)=>{let n=!1;return Ye.setState(r=>({attachedFiles:r.attachedFiles.map(s=>s.id!==e?s:(n=!0,t(s)))})),n},iw=()=>{for(;hf<hI&&Vo.length>0;){const e=Vo.shift();if(!e)continue;const t=Ye.getState().attachedFiles.find(n=>n.id===e);!t||t.source!=="local"||t.uploadState?.status!=="preparing"||(hf+=1,wI(e).finally(()=>{hf-=1,iw()}))}},pf=e=>{Vo.includes(e)||Co.has(e)||(Vo.push(e),iw())},wI=async e=>{const t=Ye.getState().attachedFiles.find(a=>a.id===e);if(!t||t.source!=="local")return;const n=t.file instanceof Blob?t.file:xI(t.dataUrl,t.mimeType);if(!n||n.size===0){cn(e,a=>({...a,uploadState:{status:"failed",error:"The file data is no longer available."}}));return}const r=Y(),s=(ps.get(e)??0)+1;ps.set(e,s);const o=new AbortController;Co.set(e,o);let i=-1;cn(e,a=>({...a,uploadState:{status:"uploading",progress:n.size>0?0:null}}));try{const a=await Ie.uploadAttachment(n,{filename:t.filename,mime:t.mimeType,signal:o.signal,onProgress:({loaded:d,total:f})=>{const u=f>0?Math.min(99,Math.floor(d/f*100)):null;u!==i&&(i=u??i,!(ps.get(e)!==s||r!==Y())&&cn(e,h=>h.uploadState?.status==="uploading"?{...h,uploadState:{status:"uploading",progress:u}}:h))}},{runtimeKey:r});if(ps.get(e)!==s||r!==Y()){Ie.deleteAttachment(a.id,{runtimeKey:r}).catch(()=>{});return}cn(e,d=>({...d,uploadState:{status:"ready",attachmentId:a.id,expiresAt:a.expiresAt}}));const l=setTimeout(()=>{dd.delete(e),cn(e,d=>d.uploadState?.status==="ready"&&d.uploadState.attachmentId===a.id?{...d,uploadState:{status:"failed",error:"Upload expired. Retry the upload."}}:d)},Math.max(0,a.expiresAt-Date.now()+1));dd.set(e,l)}catch(a){if(ps.get(e)!==s)return;cn(e,l=>({...l,uploadState:{status:"failed",error:bI(a)}}))}finally{Co.get(e)===o&&Co.delete(e)}},lp=e=>{ps.set(e.id,(ps.get(e.id)??0)+1),Co.get(e.id)?.abort(),Co.delete(e.id);const t=dd.get(e.id);t&&clearTimeout(t),dd.delete(e.id);const n=Vo.indexOf(e.id);n>=0&&Vo.splice(n,1)},SI=(e,t)=>{lp(e),sw(e.previewUrl),t&&e.uploadState?.status==="ready"&&Ie.deleteAttachment(e.uploadState.attachmentId,{runtimeKey:Y()}).catch(()=>{})},nr=(e,t)=>{for(const n of e)SI(n,t)},CI=10,kI=50*1024*1024,MI=e=>{let t=0;for(const n of Object.values(e))for(const r of n)t+=Number.isFinite(r.size)?r.size:0;return t};let q0=0;const II=(e,t,n)=>!e||e.draftKey!==t?!1:n===e.text,Ye=Et()((e,t)=>({pendingInputText:null,pendingInputMode:"replace",pendingRevertText:null,pendingSyntheticParts:null,pendingStarterInsert:null,pendingWorktreeRestore:null,attachedFiles:[],stashedAttachmentsByDraft:{},activeAttachmentsDraftKey:null,sentDraftClear:null,setPendingInputText:(n,r="replace")=>e({pendingInputText:n,pendingInputMode:r}),consumePendingInputText:()=>{const{pendingInputText:n,pendingInputMode:r}=t();return n===null?null:(e({pendingInputText:null,pendingInputMode:"replace"}),{text:n,mode:r})},setPendingRevertText:n=>e({pendingRevertText:n}),consumePendingRevertText:()=>{const{pendingRevertText:n}=t();return n===null?null:(e({pendingRevertText:null}),n)},requestStarterInsert:n=>e({pendingStarterInsert:{name:n}}),requestStarterTextInsert:n=>e({pendingStarterInsert:{text:n}}),consumePendingStarterInsert:()=>{const{pendingStarterInsert:n}=t();return n===null?null:(e({pendingStarterInsert:null}),n)},setPendingSyntheticParts:n=>e({pendingSyntheticParts:n}),consumePendingSyntheticParts:()=>{const{pendingSyntheticParts:n}=t();return n!==null&&e({pendingSyntheticParts:null}),n},requestWorktreeRestore:n=>e({pendingWorktreeRestore:n}),consumePendingWorktreeRestore:()=>{const{pendingWorktreeRestore:n}=t();return n===null?null:(e({pendingWorktreeRestore:null}),n)},resetForRuntimeSwitch:()=>{t().pendingWorktreeRestore!==null&&e({pendingWorktreeRestore:null}),t().sentDraftClear!==null&&e({sentDraftClear:null})},publishSentDraftClear:(n,r)=>{n&&(q0+=1,e({sentDraftClear:{draftKey:n,text:r,nonce:q0}}))},consumeSentDraftClear:n=>{t().sentDraftClear?.nonce===n&&e({sentDraftClear:null})},addAttachedFile:async n=>{const r=so,s=Pc("preparing"),o={id:s,file:n,dataUrl:"",mimeType:n.type||"application/octet-stream",filename:n.name,size:n.size,source:"local",uploadState:{status:"preparing"}};if(e(i=>({attachedFiles:[...i.attachedFiles,o]})),t().attachedFiles.length>Zs)return cn(s,i=>({...i,uploadState:{status:"failed",error:`You can attach up to ${Zs} files to one message.`}})),!1;for(let i=0;i<fI;i+=1){const a=t().attachedFiles.filter(h=>h.id!==s).map(h=>h.filename);let l;try{const h=uI(n,a);l=h instanceof Promise?await h:h}catch{l=null}if(r!==so||!t().attachedFiles.some(h=>h.id===s))return!1;if(!l||l.length===0)return cn(s,h=>({...h,uploadState:{status:"failed",error:"This file could not be prepared."}})),!1;if(t().attachedFiles.length-1+l.length>Zs)return cn(s,h=>({...h,uploadState:{status:"failed",error:`You can attach up to ${Zs} files to one message.`}})),!1;if(l.some(h=>h.file.size>pI))return cn(s,h=>({...h,uploadState:{status:"failed",error:"File exceeds the 100 MB upload limit."}})),!1;const d=l.slice(1).map(h=>h.file.name);if(z0(d,t().attachedFiles.filter(h=>h.id!==s)))continue;const f=l.length>1?Pc("document"):void 0,u=l.map(h=>({id:Pc(),file:h.file,dataUrl:"",previewUrl:mI(h.file,h.mimeType),mimeType:h.mimeType,filename:h.file.name,size:h.file.size,source:"local",uploadState:{status:"preparing"},sourceDocumentId:f}));if(r!==so)return nr(u,!1),!1;if(z0(d,t().attachedFiles.filter(h=>h.id!==s))){nr(u,!1);continue}e(h=>({attachedFiles:h.attachedFiles.flatMap(m=>m.id===s?u:[m])}));for(const h of u)pf(h.id);return!0}return cn(s,i=>({...i,uploadState:{status:"failed",error:"Generated filenames conflict with existing attachments."}})),!1},retryAttachmentUpload:n=>{const r=t().attachedFiles.find(s=>s.id===n);if(!(!r||r.source!=="local")){if(r.sourceDocumentId){for(const s of t().attachedFiles.filter(o=>o.sourceDocumentId===r.sourceDocumentId))(s.uploadState?.status==="failed"||s.uploadState?.status==="ready"&&s.uploadState.expiresAt<=Date.now())&&(cn(s.id,o=>({...o,uploadState:{status:"preparing"}})),pf(s.id));return}cn(n,s=>({...s,uploadState:{status:"preparing"}})),pf(n)}},removeAttachedFile:n=>{const r=t().attachedFiles.find(i=>i.id===n);if(!r)return;const s=r.sourceDocumentId?t().attachedFiles.filter(i=>i.sourceDocumentId===r.sourceDocumentId):[r];nr(s,!0);const o=new Set(s.map(i=>i.id));e(i=>({attachedFiles:i.attachedFiles.filter(a=>!o.has(a.id))}))},detachAttachedFiles:n=>{const r=new Set(n),s=t().attachedFiles.filter(a=>r.has(a.id));nr(s,!1);const o=t().stashedAttachmentsByDraft;let i=o;if(o){i={};for(const[a,l]of Object.entries(o)){const d=l.filter(f=>!r.has(f.id));gI(l.filter(f=>r.has(f.id))),d.length>0&&(i[a]=d)}}e(a=>({attachedFiles:a.attachedFiles.filter(l=>!r.has(l.id)),stashedAttachmentsByDraft:i}))},restoreAttachmentsForRetry:n=>{const r=t().attachedFiles.length;if(!n||n.length===0)return{ok:!0,restoredCount:0,totalCount:r};const s=new Set(t().attachedFiles.map(f=>f.id)),o=new Set,i=[];for(const f of n)s.has(f.id)||o.has(f.id)||(o.add(f.id),i.push(f));if(i.length===0)return{ok:!0,restoredCount:0,totalCount:r};if(r+i.length>Zs)return{ok:!1,reason:"attachment-limit",limit:Zs,currentCount:r,missingCount:i.length};const a=new Set(i.map(f=>f.id)),l=t().stashedAttachmentsByDraft??{},d={};for(const[f,u]of Object.entries(l)){const h=u.filter(m=>!a.has(m.id));h.length>0&&(d[f]=h)}return e(f=>({attachedFiles:[...f.attachedFiles,...i.map(su)],stashedAttachmentsByDraft:d})),{ok:!0,restoredCount:i.length,totalCount:r+i.length}},activateAttachmentsDraft:n=>{const r=t().activeAttachmentsDraftKey;if(r===null){e({activeAttachmentsDraftKey:n});return}if(r===n)return;const s=t().stashedAttachmentsByDraft,o=t().attachedFiles,i=s[n]??[],a={};for(const[d,f]of Object.entries(s))d!==r&&d!==n&&(a[d]=f);o.length>0&&(a[r]=o);const l=Object.keys(a);for(;l.length>CI||MI(a)>kI;){const d=l.shift();if(!d)break;nr(a[d]??[],!0),delete a[d]}e({attachedFiles:i,stashedAttachmentsByDraft:a,activeAttachmentsDraftKey:n})},clearStashedAttachmentsForSession:n=>{const r=a=>{try{const l=JSON.parse(a);return Array.isArray(l)&&l[0]===n.runtimeKey&&l[1]===n.directory&&l[2]===n.sessionId}catch{return!1}},s=t(),o={};for(const[a,l]of Object.entries(s.stashedAttachmentsByDraft))r(a)?nr(l,!0):o[a]=l;const i=s.activeAttachmentsDraftKey!==null&&r(s.activeAttachmentsDraftKey);i&&nr(s.attachedFiles,!0),e({attachedFiles:i?[]:s.attachedFiles,stashedAttachmentsByDraft:o})},setAttachedFiles:n=>{so+=1;const r=new Set(n.map(s=>s.id));nr(t().attachedFiles.filter(s=>!r.has(s.id)),!1),e({attachedFiles:n.map(s=>s.source==="local"&&s.uploadState===void 0?{...s,uploadState:{status:"failed",error:"Upload needs to be refreshed. Retry the upload."}}:s)})},clearAttachedFiles:()=>{so+=1,nr(t().attachedFiles,!0),e({attachedFiles:[]})},addRestoredAttachment:({url:n,mimeType:r,filename:s})=>{const o=Pc("restored"),i=new File([],s,{type:r}),a={id:o,file:i,dataUrl:n,mimeType:r,filename:s,size:vI(n),source:"server",serverPath:n};e(l=>({attachedFiles:[...l.attachedFiles,a]}))}}));N5(()=>{so+=1;const e=s=>s.map(o=>o.source==="local"?{...o,uploadState:{status:"failed",error:"The runtime changed. Retry the upload."}}:o),t=Ye.getState().attachedFiles;for(const s of t)lp(s);const n=Ye.getState().stashedAttachmentsByDraft??{},r={};for(const[s,o]of Object.entries(n)){for(const i of o)lp(i);r[s]=e(o)}Ye.setState({attachedFiles:e(t),stashedAttachmentsByDraft:r,pendingWorktreeRestore:null,sentDraftClear:null})});const ko="oc.sessions.folders",Mo="oc.sessions.folderCollapse",ud="oc.sessions.folders.v2.index",aw="/api/pi/session-folders",EI=250,zt=Gt(),mf=Wd();let bs=null,ta=!1,_l=!1,na=!1,ra,sa,oa=null,ia=null,$o=null,Pn=Y(),Ms=0,fd=0;const hd=new Map,qr=(e,t)=>`${e}.v2:${encodeURIComponent(t)}`,Fm=()=>{try{const e=JSON.parse(zt.getItem(ud)??"");return e.version===2&&Array.isArray(e.runtimes)?{version:2,legacyClaimed:!!e.legacyClaimed,runtimes:e.runtimes}:{version:2,legacyClaimed:!1,runtimes:[]}}catch{return{version:2,legacyClaimed:!1,runtimes:[]}}},ka=(e,t=Date.now(),n=zt)=>{const r=Fm(),s=[{runtimeKey:e,updatedAt:t},...r.runtimes.filter(o=>o.runtimeKey!==e)];n.setItem(ud,JSON.stringify({version:2,legacyClaimed:r.legacyClaimed,runtimes:s}))},cw=e=>{const t=Fm();if(t.legacyClaimed)return;const n=zt.getItem(ko),r=zt.getItem(Mo);n&&zt.setItem(qr(ko,e),n),r&&zt.setItem(qr(Mo,e),r);const s={...t,legacyClaimed:!0};zt.setItem(ud,JSON.stringify(s)),zt.getItem(ud)===JSON.stringify(s)&&(zt.removeItem(ko),zt.removeItem(Mo)),ka(e,0)},_I=(e,t)=>{if(typeof window>"u")return;bs&&clearTimeout(bs);const n=JSON.parse(JSON.stringify(e)),r=Array.from(t),s=Pn,o=Ms;bs=setTimeout(()=>{if(bs=null,s!==Y()||o!==Ms)return;const i=Math.max(Date.now(),(hd.get(s)??0)+1);hd.set(s,i),Rt(aw,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:1,foldersMap:n,collapsedFolderIds:r,updatedAt:i})}).then(l=>{l.status===409&&(s!==Y()||o!==Ms||(ta=!1,na=!0,ou()))}).catch(()=>{})},EI)},W0=(e=Pn)=>{try{cw(e);const t=zt.getItem(qr(ko,e));if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};const r={};for(const[s,o]of Object.entries(n)){if(!Array.isArray(o))continue;const i=[];for(const a of o){if(!a||typeof a!="object")continue;const l=a,d=typeof l.id=="string"?l.id.trim():"",f=typeof l.name=="string"?l.name.trim():"",u=typeof l.createdAt=="number"?l.createdAt:0;if(!d||!f)continue;const h=Array.isArray(l.sessionIds)?l.sessionIds.filter(g=>typeof g=="string"&&g.trim().length>0):[],m=typeof l.parentId=="string"?l.parentId:null;i.push({id:d,name:f,sessionIds:h,createdAt:u,parentId:m})}i.length>0&&(r[s]=i)}return r}catch{return{}}},K0=(e=Pn)=>{try{cw(e);const t=zt.getItem(qr(Mo,e));if(!t)return new Set;const n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}},lw=e=>{oa=e,$o=Pn,clearTimeout(ra),ra=setTimeout(()=>{try{const t=$o??Pn;zt.setItem(qr(ko,t),JSON.stringify(e)),ka(t),oa=null}catch{}},300)},dw=e=>{ia=e,$o=Pn,clearTimeout(sa),sa=setTimeout(()=>{try{const t=$o??Pn;zt.setItem(qr(Mo,t),JSON.stringify(Array.from(e))),ka(t),ia=null}catch{}},300)},uw=()=>{ra&&clearTimeout(ra),sa&&clearTimeout(sa),ra=void 0,sa=void 0;const e=$o??Pn;let t=!1;if(oa!==null){const n=qr(ko,e),r=JSON.stringify(oa);zt.setItem(n,r),mf.setItem(n,r),oa=null,t=!0}if(ia!==null){const n=qr(Mo,e),r=JSON.stringify(Array.from(ia));zt.setItem(n,r),mf.setItem(n,r),ia=null,t=!0}if(t){const n=Date.now();ka(e,n),ka(e,n,mf)}$o=null};if(typeof window<"u"){const e=()=>{try{uw()}catch{}};window.addEventListener("pagehide",e,{capture:!0}),window.addEventListener("beforeunload",e,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()}),document.addEventListener("freeze",e))}const rr=(e,t)=>{fd+=1,lw(e),dw(t),_I(e,t)},jI=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`folder_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,gi=(e,t,n)=>{const r=new Set(t.map(o=>o.id));let s=null;for(const o of e)!r.has(o.id)&&n.has(o.id)&&(s||(s=new Set(n)),s.delete(o.id));return s},Bm=Et()(gr((e,t)=>({foldersMap:W0(),collapsedFolderIds:K0(),resetForRuntimeSwitch:n=>{try{uw()}catch{}Pn=n,Ms+=1,fd=0,ta=!1,_l=!1,na=!1,bs&&clearTimeout(bs),bs=null,e({foldersMap:W0(n),collapsedFolderIds:K0(n)}),queueMicrotask(()=>{ou()})},getFoldersForScope:n=>n?t().foldersMap[n]??[]:[],createFolder:(n,r,s)=>{const o=r.trim()||"New folder",i={id:jI(),name:o,sessionIds:[],createdAt:Date.now(),parentId:s??null},a=t().foldersMap,l=a[n]??[],d={...a,[n]:[...l,i]};return e({foldersMap:d}),rr(d,t().collapsedFolderIds),i},renameFolder:(n,r,s)=>{const o=s.trim();if(!o||!n)return;const i=t().foldersMap,a=i[n];if(!a)return;const l=a.map(f=>f.id===r?{...f,name:o}:f),d={...i,[n]:l};e({foldersMap:d}),rr(d,t().collapsedFolderIds)},deleteFolder:(n,r)=>{if(!n)return;const s=t().foldersMap,o=s[n];if(!o)return;const i=new Set([r]);let a=!0;for(;a;){a=!1;for(const h of o)h.parentId&&i.has(h.parentId)&&!i.has(h.id)&&(i.add(h.id),a=!0)}const l=o.filter(h=>!i.has(h.id)),d={...s,[n]:l},f=t().collapsedFolderIds,u=gi(o,l,f);e(u?{foldersMap:d,collapsedFolderIds:u}:{foldersMap:d}),rr(d,u??f)},addSessionToFolder:(n,r,s)=>{if(!n||!r||!s)return;const o=t().foldersMap,i=o[n];if(!i)return;const a=i.find(h=>h.id===r);if(!a)return;const l=i.reduce((h,m)=>h+(m.sessionIds.includes(s)?1:0),0);if(a.sessionIds.includes(s)&&l===1)return;const d=i.map(h=>{const m=h.sessionIds.filter(g=>g!==s);return h.id===r?{...h,sessionIds:[...m,s]}:m.length!==h.sessionIds.length?{...h,sessionIds:m}:h}),f={...o,[n]:d},u=gi(i,d,t().collapsedFolderIds);e(u?{foldersMap:f,collapsedFolderIds:u}:{foldersMap:f}),rr(f,u??t().collapsedFolderIds)},addSessionsToFolder:(n,r,s)=>{if(!n||!r||s.length===0)return;const o=t().foldersMap,i=o[n];if(!i)return;const a=new Set(s.filter(m=>typeof m=="string"&&m.length>0));if(a.size===0)return;const l=i.find(m=>m.id===r);if(!l)return;let d=!1;for(const m of i){for(const g of a)if(m.sessionIds.includes(g)&&(m.id!==r||!l.sessionIds.includes(g))){d=!0;break}if(d)break}if(!d){for(const m of a)if(!l.sessionIds.includes(m)){d=!0;break}}if(!d)return;const f=i.map(m=>{const g=m.sessionIds.filter(x=>!a.has(x));return m.id===r?{...m,sessionIds:[...g,...a]}:g.length!==m.sessionIds.length?{...m,sessionIds:g}:m}),u={...o,[n]:f},h=gi(i,f,t().collapsedFolderIds);e(h?{foldersMap:u,collapsedFolderIds:h}:{foldersMap:u}),rr(u,h??t().collapsedFolderIds)},removeSessionsFromFolders:(n,r)=>{if(!n||r.length===0)return;const s=t().foldersMap,o=s[n];if(!o)return;const i=new Set(r.filter(u=>typeof u=="string"&&u.length>0));if(i.size===0)return;let a=!1;const l=o.map(u=>{const h=u.sessionIds.filter(m=>!i.has(m));return h.length!==u.sessionIds.length?(a=!0,{...u,sessionIds:h}):u});if(!a)return;const d={...s,[n]:l},f=gi(o,l,t().collapsedFolderIds);e(f?{foldersMap:d,collapsedFolderIds:f}:{foldersMap:d}),rr(d,f??t().collapsedFolderIds)},removeSessionFromFolder:(n,r)=>{if(!n||!r)return;const s=t().foldersMap,o=s[n];if(!o)return;let i=!1;const a=o.map(f=>{const u=f.sessionIds.filter(h=>h!==r);return u.length!==f.sessionIds.length?(i=!0,{...f,sessionIds:u}):f});if(!i)return;const l={...s,[n]:a},d=gi(o,a,t().collapsedFolderIds);e(d?{foldersMap:l,collapsedFolderIds:d}:{foldersMap:l}),rr(l,d??t().collapsedFolderIds)},removeSessionEverywhere:(n,r)=>{if(!n||n!==Pn||n!==Y()||!r)return;const s=t().foldersMap;let o=null;for(const[i,a]of Object.entries(s)){let l=!1;const d=a.map(f=>{const u=f.sessionIds.filter(h=>h!==r);return u.length===f.sessionIds.length?f:(l=!0,{...f,sessionIds:u})});l&&(o??={...s},o[i]=d)}o&&(e({foldersMap:o}),rr(o,t().collapsedFolderIds))},toggleFolderCollapse:n=>{const r=t().collapsedFolderIds,s=new Set(r);s.has(n)?s.delete(n):s.add(n),e({collapsedFolderIds:s}),rr(t().foldersMap,s)},getSessionFolderId:(n,r)=>{if(!n||!r)return null;const s=t().foldersMap[n];if(!s)return null;for(const o of s)if(o.sessionIds.includes(r))return o.id;return null}}),{name:"session-folders-store"})),ou=async()=>{if(typeof window>"u"||_l||ta&&!na)return;na=!1,_l=!0;const e=Pn,t=Ms,n=fd;let r=!1;try{const s=await Rt(aw).catch(()=>null);if(!s||!s.ok)return;const o=await s.json().catch(()=>null);if(!o)return;if(o.exists===!1){r=!0;return}const i=o.foldersMap&&typeof o.foldersMap=="object"?o.foldersMap:{},a=Array.isArray(o.collapsedFolderIds)?new Set(o.collapsedFolderIds.filter(u=>typeof u=="string")):new Set;if(t!==Ms||e!==Y())return;const l=Fm().runtimes.find(u=>u.runtimeKey===e)?.updatedAt??0,d=typeof o.updatedAt=="number"&&Number.isFinite(o.updatedAt)?o.updatedAt:0;d>0&&hd.set(e,Math.max(hd.get(e)??0,d)),(o.exists===!0||d>0)&&fd===n&&d>=l&&(Bm.setState({foldersMap:i,collapsedFolderIds:a}),lw(i),dw(a)),r=!0}catch{}finally{t===Ms&&e===Y()&&(_l=!1,r&&(ta=!0),na&&(ta=!1,queueMicrotask(()=>{ou()})))}},TI=()=>{typeof window>"u"||ou()};TI();const AI=e=>{if(e.runtimeKey!==Y()||!e.directory||e.directory==="global"||!e.sessionId)return;const t=gm(e.sessionId,e.directory,e.runtimeKey);t&&ft.getState().clearQueue(t),Bm.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),Rm.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=Qo(e.runtimeKey,e.directory,e.sessionId);n&&KM(n,!0),Ye.getState().clearStashedAttachmentsForSession(e)},Ma=e=>{if(!e||e.streamingMessages.size===0)return null;let t=null;for(const n of e.streamingMessages){const r=e.messages.get(n);r?.role==="assistant"&&(t=r.id)}return t},NI=(e,t)=>e.sessionId===t.sessionId&&e.directory===t.directory&&e.messages===t.messages&&e.parts===t.parts&&e.partOrder===t.partOrder&&e.streamingMessages===t.streamingMessages&&e.lifecycle===t.lifecycle&&e.model===t.model&&e.thinking===t.thinking&&e.queue===t.queue,LI=e=>{let t=null;for(const n of e.messages.values())n.role==="user"&&(t=n.id);return t},fw=e=>{const t=e?.awaitingPromptEcho?.baselineUserMessageId;return!e||e.awaitingPromptEcho===void 0?!1:LI(e)===t},RI=(e,t)=>{if(e===t||e.messages===t.messages&&e.parts===t.parts&&e.partOrder===t.partOrder)return!0;if(e.messages.size!==t.messages.size||t.lastMutationKind==="structure")return!1;if(t.lastMutationKind==="part"&&t.lastMutatedMessageId)return t.messages.get(t.lastMutatedMessageId)?.role!=="user";const n=Ma(t);return n?dp(e,t,n):!1},dp=(e,t,n)=>e===t?!0:e.messages.size!==t.messages.size||e.messages!==t.messages||t.lastMutationKind==="structure"?!1:t.lastMutationKind==="part"&&t.lastMutatedMessageId===n?!0:t.lastMutationKind==="part"&&t.lastMutatedMessageId&&t.lastMutatedMessageId!==n?!1:DI(e,t,n),PI=(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},DI=(e,t,n)=>{for(const[r,s]of t.messages){const o=e.messages.get(r);if(!o||o.id!==s.id)return!1;if(r===n)continue;if(o!==s)return!1;const i=e.partOrder.get(r)??[],a=t.partOrder.get(r)??[];if(!PI(i,a))return!1;for(const l of a)if(e.parts.get(l)!==t.parts.get(l))return!1}for(const r of e.messages.keys())if(!t.messages.has(r))return!1;return!0},OI="selection-store",HI=3,G0="context-store",Z0=1,Io=500,Ia=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),As=e=>typeof e=="string",Vm=e=>typeof e=="object"&&e!==null&&typeof e.providerId=="string"&&typeof e.modelId=="string",Y0=(e,t)=>`${e}/${t}`,X0=(e,t,n)=>JSON.stringify([e,t,n]),FI=(e,t)=>JSON.stringify([e,t]),Tn=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===3&&t.every(As))return t}catch{}return null},gf=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===2&&t.every(As))return t}catch{}return null},oo=new Set,io=new Set,_r=new Set;let up=!1;const BI=()=>{oo.clear(),io.clear(),_r.clear(),up=!1},iu=e=>{if(!Array.isArray(e))return[];const t=new Set,n=[];for(const r of e)typeof r!="string"||t.has(r)||(t.add(r),n.push(r));return n},VI=e=>{const t=iu(e.sessionRecency),n=new Set(t),r=s=>{n.has(s)||(n.add(s),t.push(s))};for(const s of e.sessionModelSelections.keys())r(s);for(const s of e.sessionAgentSelections.keys())r(s);for(const s of e.sessionAgentModelSelections.keys())r(s);for(const s of e.sessionAgentModelVariantSelections.keys())r(s);for(const s of e.clearedVariantKeys){const o=typeof s=="string"?Tn(s):null;o&&r(o[0])}return t},Dc=(e,t)=>{let n=null;for(const r of t)(n??e).has(r)&&(n||(n=new Map(e)),n.delete(r));return n??e},Oc=(e,t)=>{if(!e.has(t))return e;const n=new Map(e);return n.delete(t),n},is=(e,t=[])=>{const n=VI(e);for(const o of t){const i=n.indexOf(o);i!==-1&&n.splice(i,1),n.push(o)}if(n.length<=Io){const o=e.sessionRecency;return o.length===n.length&&o.every((a,l)=>a===n[l])?e:{...e,sessionRecency:n}}const r=new Set(n.slice(0,n.length-Io));let s=e.clearedVariantKeys;return s.some(o=>{const i=typeof o=="string"?Tn(o):null;return i!==null&&r.has(i[0])})&&(s=s.filter(o=>{const i=typeof o=="string"?Tn(o):null;return i===null||!r.has(i[0])})),{sessionModelSelections:Dc(e.sessionModelSelections,r),sessionAgentSelections:Dc(e.sessionAgentSelections,r),sessionAgentModelSelections:Dc(e.sessionAgentModelSelections,r),sessionAgentModelVariantSelections:Dc(e.sessionAgentModelVariantSelections,r),clearedVariantKeys:s,sessionRecency:n.slice(n.length-Io)}},J0=(e,t)=>e.sessionModelSelections.has(t)||e.sessionAgentSelections.has(t)||e.sessionAgentModelSelections.has(t)||e.sessionAgentModelVariantSelections.has(t)||e.sessionRecency.includes(t)?!0:e.clearedVariantKeys.some(n=>Tn(n)?.[0]===t),$I=e=>{const t=iu(e.sessionRecency),n=new Set(t),r=o=>{typeof o=="string"&&!n.has(o)&&(n.add(o),t.push(o))},s=o=>{if(Array.isArray(o))for(const i of o)Array.isArray(i)&&i.length>0&&r(i[0])};if(s(e.sessionModelSelections),s(e.sessionAgentSelections),s(e.sessionAgentModelSelections),s(e.sessionAgentModelVariantSelections),Array.isArray(e.clearedVariantKeys)){for(const o of e.clearedVariantKeys)if(typeof o=="string"){const i=Tn(o);i&&r(i[0])}}return t},Hc=(e,t)=>Array.isArray(e)?e.filter(n=>{const r=Array.isArray(n)&&n.length>0&&typeof n[0]=="string"?n[0]:null;return r===null||t.has(r)}):e,zI=(e,t)=>Array.isArray(e)?e.filter(n=>{if(typeof n!="string")return!0;const r=Tn(n);return r===null||t.has(r[0])}):e,UI=e=>{if(!Ia(e))return e;try{const t=$I(e),n=iu(e.sessionRecency),r=n.length===t.length&&n.every((o,i)=>o===t[i])&&Array.isArray(e.sessionRecency)&&e.sessionRecency.length===n.length;if(t.length<=Io)return r?e:{...e,sessionRecency:t};const s=new Set(t.slice(t.length-Io));return{...e,sessionModelSelections:Hc(e.sessionModelSelections,s),sessionAgentSelections:Hc(e.sessionAgentSelections,s),sessionAgentModelSelections:Hc(e.sessionAgentModelSelections,s),sessionAgentModelVariantSelections:Hc(e.sessionAgentModelVariantSelections,s),clearedVariantKeys:zI(e.clearedVariantKeys,s),sessionRecency:t.slice(t.length-Io)}}catch{return e}},Q0=(e,t,n)=>{e.delete(t),e.set(t,n)},Is=(e,t)=>{const n=new Map;if(e===void 0)return{value:n,failed:!1};if(!Array.isArray(e))return{value:n,failed:!0};let r=!1;for(const s of e){if(!Array.isArray(s)||s.length!==2){r=!0;continue}const[o,i]=s;if(typeof o!="string"||!t(i)){r=!0;continue}n.set(o,i)}return{value:n,failed:r}},hw=e=>{const t=new Map;if(e===void 0)return{value:t,failed:!1};if(!Array.isArray(e))return{value:t,failed:!0};let n=!1;for(const r of e){if(!Array.isArray(r)||r.length!==2){n=!0;continue}const[s,o]=r;if(typeof s!="string"||!Array.isArray(o)){n=!0;continue}const i=Is(o,Vm);i.failed&&(n=!0),(i.value.size>0||o.length===0)&&t.set(s,i.value)}return{value:t,failed:n}},pw=e=>{const t=new Map;if(e===void 0)return{value:t,failed:!1};if(!Array.isArray(e))return{value:t,failed:!0};let n=!1;for(const r of e){if(!Array.isArray(r)||r.length!==2){n=!0;continue}const[s,o]=r;if(typeof s!="string"||!Array.isArray(o)){n=!0;continue}const i=new Map;for(const a of o){if(!Array.isArray(a)||a.length!==2){n=!0;continue}const[l,d]=a;if(typeof l!="string"||!Array.isArray(d)){n=!0;continue}const f=Is(d,As);f.failed&&(n=!0),f.value.size>0&&i.set(l,f.value)}i.size>0&&t.set(s,i)}return{value:t,failed:n}},ws=()=>({models:new Map,agents:new Map,agentModels:new Map,variants:new Map,currentAgentContext:new Map}),e2=e=>{if(e===null)return{status:"missing",failed:!1,data:ws()};let t;try{t=JSON.parse(e)}catch{return{status:"failed",failed:!0,data:ws()}}if(!Ia(t))return{status:"failed",failed:!0,data:ws()};const n="state"in t?t.state:t;if(!Ia(n))return{status:"failed",failed:!0,data:ws()};const r=Is(n.sessionModelSelections??void 0,Vm),s=Is(n.sessionAgentSelections??void 0,As),o=hw(n.sessionAgentModelSelections??void 0),i=pw(n.sessionAgentModelVariantSelections??void 0),a=Is(n.currentAgentContext??void 0,As),l=r.failed||s.failed||o.failed||i.failed||a.failed;return{status:l?"failed":"ok",failed:l,data:{models:r.value,agents:s.value,agentModels:o.value,variants:i.value,currentAgentContext:a.value}}},qI=()=>{try{if(typeof window<"u"&&window.localStorage)return e2(window.localStorage.getItem(G0))}catch{return{status:"failed",failed:!0,data:ws()}}try{return e2(Wd().getItem(G0))}catch{return{status:"failed",failed:!0,data:ws()}}},WI=(e,t,n,r)=>{const s=e.get(t),o=s?.get(n);return o?.has(r)?(o.delete(r),o.size===0&&s?.delete(n),s&&s.size===0&&e.delete(t),!0):!1},Lt=Et()(Gd((e,t)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,lastUsedProvider:null,hasHydrated:typeof window>"u",contextStoreMigrationVersion:void 0,clearedVariantKeys:[],sessionRecency:[],saveSessionModelSelection:(n,r,s)=>{oo.add(n),up=!0,e(o=>{const i=new Map(o.sessionModelSelections);return i.delete(n),i.set(n,{providerId:r,modelId:s}),{...is({...o,sessionModelSelections:i},[n]),lastUsedProvider:{providerID:r,modelID:s}}})},getSessionModelSelection:n=>t().sessionModelSelections.get(n)??null,saveSessionAgentSelection:(n,r)=>{t().sessionAgentSelections.get(n)!==r&&(oo.add(n),e(s=>{if(s.sessionAgentSelections.get(n)===r)return s;const o=new Map(s.sessionAgentSelections);return o.delete(n),o.set(n,r),is({...s,sessionAgentSelections:o},[n])}))},getSessionAgentSelection:n=>t().sessionAgentSelections.get(n)??null,saveAgentModelForSession:(n,r,s,o)=>{const i=t().sessionAgentModelSelections.get(n)?.get(r);i?.providerId===s&&i?.modelId===o||(io.add(FI(n,r)),e(a=>{const l=a.sessionAgentModelSelections.get(n)?.get(r);if(l?.providerId===s&&l?.modelId===o)return a;const d=new Map(a.sessionAgentModelSelections),f=new Map(d.get(n)??new Map);return d.delete(n),f.set(r,{providerId:s,modelId:o}),d.set(n,f),is({...a,sessionAgentModelSelections:d},[n])}))},getAgentModelForSession:(n,r)=>t().sessionAgentModelSelections.get(n)?.get(r)??null,saveAgentModelVariantForSession:(n,r,s,o,i)=>{const a=Y0(s,o),l=X0(n,r,a);if(i===void 0){if(t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0){t().hasHydrated||(_r.add(l),e(f=>f.clearedVariantKeys.includes(l)?f:is({...f,clearedVariantKeys:[...f.clearedVariantKeys,l]},[n])));return}_r.add(l),e(f=>{if(f.sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0)return f;const u=new Map(f.sessionAgentModelVariantSelections),h=new Map(u.get(n)??new Map),m=new Map(h.get(r)??new Map);m.delete(a),m.size===0?h.delete(r):h.set(r,m),h.size===0?u.delete(n):(u.delete(n),u.set(n,h));const g=f.clearedVariantKeys.includes(l)?f.clearedVariantKeys:[...f.clearedVariantKeys,l];return is({...f,sessionAgentModelVariantSelections:u,clearedVariantKeys:g},[n])});return}t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)!==i&&(_r.add(l),e(d=>{if(d.sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===i)return d;const f=new Map(d.sessionAgentModelVariantSelections),u=new Map(f.get(n)??new Map),h=new Map(u.get(r)??new Map);return f.delete(n),h.set(a,i),u.set(r,h),f.set(n,u),is({...d,sessionAgentModelVariantSelections:f},[n])}))},getAgentModelVariantForSession:(n,r,s,o)=>{const i=Y0(s,o);return t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(i)},forgetSession:n=>{if(!(!n||!J0(t(),n))){oo.delete(n);for(const r of Array.from(io))gf(r)?.[0]===n&&io.delete(r);for(const r of Array.from(_r))Tn(r)?.[0]===n&&_r.delete(r);e(r=>{if(!J0(r,n))return r;let s=r.clearedVariantKeys;s.some(i=>Tn(i)?.[0]===n)&&(s=s.filter(i=>Tn(i)?.[0]!==n));let o=r.sessionRecency;return o.includes(n)&&(o=o.filter(i=>i!==n)),{sessionModelSelections:Oc(r.sessionModelSelections,n),sessionAgentSelections:Oc(r.sessionAgentSelections,n),sessionAgentModelSelections:Oc(r.sessionAgentModelSelections,n),sessionAgentModelVariantSelections:Oc(r.sessionAgentModelVariantSelections,n),clearedVariantKeys:s,sessionRecency:o}})}}}),{name:OI,version:HI,storage:mm(),partialize:e=>({sessionModelSelections:Array.from(e.sessionModelSelections.entries()),sessionAgentSelections:Array.from(e.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(e.sessionAgentModelSelections.entries()).map(([t,n])=>[t,Array.from(n.entries())]),sessionAgentModelVariantSelections:Array.from(e.sessionAgentModelVariantSelections.entries()).map(([t,n])=>[t,Array.from(n.entries()).map(([r,s])=>[r,Array.from(s.entries())])]),lastUsedProvider:e.lastUsedProvider,contextStoreMigrationVersion:e.contextStoreMigrationVersion,clearedVariantKeys:e.clearedVariantKeys,sessionRecency:e.sessionRecency}),merge:(e,t)=>{let n=!1,r;e===void 0?r=void 0:Ia(e)?r=e:(n=!0,r=void 0);const s=Is(r?.sessionModelSelections??void 0,Vm),o=Is(r?.sessionAgentSelections??void 0,As),i=hw(r?.sessionAgentModelSelections??void 0),a=pw(r?.sessionAgentModelVariantSelections??void 0);r!==void 0&&(n=n||s.failed||o.failed||i.failed||a.failed);let l=t.lastUsedProvider;if(r?.lastUsedProvider!==void 0){const w=r.lastUsedProvider;w===null||Ia(w)&&typeof w.providerID=="string"&&typeof w.modelID=="string"?l=w:n=!0}let d=[];if(r?.clearedVariantKeys!==void 0){const w=r.clearedVariantKeys;Array.isArray(w)&&w.every(As)?d=[...w]:n=!0}const f=r?.contextStoreMigrationVersion===Z0,u=f?{status:"missing",failed:!1,data:ws()}:qI(),h=u.failed,m=new Map(s.value),g=new Map(o.value),x=new Map(Array.from(i.value.entries()).map(([w,I])=>[w,new Map(I)])),b=new Map(Array.from(a.value.entries()).map(([w,I])=>[w,new Map(Array.from(I.entries()).map(([E,T])=>[E,new Map(T)]))])),S=new Set([...d,...t.clearedVariantKeys]);if(u.status==="ok"||u.status==="failed"){const w=u.data;for(const[I,E]of w.models)m.has(I)||m.set(I,E);for(const[I,E]of w.agents)g.has(I)||g.set(I,E);for(const[I,E]of w.currentAgentContext)g.has(I)||g.set(I,E);for(const[I,E]of w.agentModels){let T=x.get(I);T||(T=new Map,x.set(I,T));for(const[A,j]of E)T.has(A)||T.set(A,j)}for(const[I,E]of w.variants)for(const[T,A]of E)for(const[j,k]of A){if(S.has(X0(I,T,j)))continue;let _=b.get(I);_||(_=new Map,b.set(I,_));let M=_.get(T);M||(M=new Map,_.set(T,M)),M.has(j)||M.set(j,k)}}for(const w of oo){const I=t.sessionModelSelections.get(w);I&&Q0(m,w,I);const E=t.sessionAgentSelections.get(w);E!==void 0&&Q0(g,w,E)}for(const w of io){const I=gf(w);if(!I)continue;const[E,T]=I,A=t.sessionAgentModelSelections.get(E)?.get(T);if(!A)continue;let j=x.get(E);j||(j=new Map,x.set(E,j)),j.set(T,A),x.delete(E),x.set(E,j)}for(const w of _r){const I=Tn(w);if(!I)continue;const[E,T,A]=I,j=t.sessionAgentModelVariantSelections.get(E)?.get(T)?.get(A);if(j!==void 0){let k=b.get(E);k||(k=new Map,b.set(E,k));let _=k.get(T);_||(_=new Map,k.set(T,_)),_.set(A,j)}else WI(b,E,T,A)}up&&t.lastUsedProvider!==null&&(l=t.lastUsedProvider);const y=new Set;for(const w of oo)y.add(w);for(const w of io){const I=gf(w);I&&y.add(I[0])}for(const w of _r){const I=Tn(w);I&&y.add(I[0])}const v=is({sessionModelSelections:m,sessionAgentSelections:g,sessionAgentModelSelections:x,sessionAgentModelVariantSelections:b,clearedVariantKeys:Array.from(S),sessionRecency:iu(r?.sessionRecency)},Array.from(y)),C=f||!n&&!h;return BI(),{...t,sessionModelSelections:v.sessionModelSelections,sessionAgentSelections:v.sessionAgentSelections,sessionAgentModelSelections:v.sessionAgentModelSelections,sessionAgentModelVariantSelections:v.sessionAgentModelVariantSelections,lastUsedProvider:l,hasHydrated:!0,clearedVariantKeys:C?[]:v.clearedVariantKeys,sessionRecency:v.sessionRecency,contextStoreMigrationVersion:C?Z0:t.contextStoreMigrationVersion}},migrate:e=>UI(e)}));if(typeof window<"u"){const e=Lt.persist,t=()=>{Lt.getState().hasHydrated||Lt.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const $m=(e,t)=>`${e}::${t}`,ei=Et(e=>({byKey:new Map,setEntry:t=>e(n=>{const r=new Map(n.byKey);return r.set($m(t.runtimeKey,t.sessionId),t),{byKey:r}}),clearForSession:t=>e(n=>{const r=new Map(n.byKey);let s=!1;for(const o of r.keys())o.endsWith(`::${t}`)&&(r.delete(o),s=!0);return s?{byKey:r}:n}),clearAll:()=>e({byKey:new Map}),clearForRuntime:t=>e(n=>{const r=`${t}::`,s=new Map(n.byKey);let o=!1;for(const i of s.keys())i.startsWith(r)&&(s.delete(i),o=!0);return o?{byKey:s}:n})}));typeof window<"u"&&en(e=>{e.runtimeKey!==e.previousRuntimeKey&&e.previousRuntimeKey&&ei.getState().clearForRuntime(e.previousRuntimeKey)});const KI=(e,t,n)=>{const r=Y();ei.getState().setEntry({sessionId:e,runtimeKey:r,targetEntryId:t.targetEntryId,previousLeafId:t.previousLeafId,newLeafId:t.newLeafId,...t.editorText!==void 0?{editorText:t.editorText}:{},abandoned:n,createdAt:Date.now()})},yf=e=>{ei.getState().clearForSession(e)},vf=()=>{ei.getState().clearAll()},zm=e=>{const t=Y();return ei.getState().byKey.get($m(t,e))},GI=e=>ei(t=>{if(e)return t.byKey.get($m(Y(),e))}),Um=e=>{const t=["~"],n=r=>{const s=ce(r);s&&!t.includes(s)&&t.push(s)};n(e);try{n(Gt().getItem("homeDirectory"))}catch{}try{typeof window<"u"&&n(window.__PICHAMBER_HOME__)}catch{}return t},ZI=(e,t)=>{const n=ce(e);return!!(n&&Um(t).includes(n))},fp=()=>({byId:new Map,byDirectory:new Map,listStatusByDirectory:new Map}),Ss=(e,t,n,r,s)=>{if(e.byId.has(t))return e;const o=Wr(n),i=s??Date.now(),a={id:t,directory:o,parentId:null,title:"",archived:!1,createdAt:i,updatedAt:i,lifecycle:r,hydrated:!1},l=new Map(e.byId);l.set(t,a);const d=e.byDirectory.get(o),f=new Map(e.byDirectory);return d&&d.includes(t)?f.set(o,d):d?f.set(o,[t,...d]):f.set(o,[t]),{...e,byId:l,byDirectory:f}},Wr=e=>ce(e)??e,Ea=(e,t)=>e===void 0||t===void 0||e===null||t===null?e===t:e.count===t.count&&e.kind===t.kind&&e.since===t.since,mw=(e,t)=>e.id===t.id&&e.directory===t.directory&&e.parentId===t.parentId&&e.title===t.title&&e.archived===t.archived&&e.archivedAt===t.archivedAt&&e.createdAt===t.createdAt&&e.updatedAt===t.updatedAt&&e.preview===t.preview&&e.messageCount===t.messageCount&&e.lifecycle===t.lifecycle&&e.retry===t.retry&&e.hydrated===t.hydrated&&Ea(e.pendingInput,t.pendingInput),YI=(e,t,n,r)=>{const s=t.get(n)??[];for(const o of s){if(r.includes(o))continue;const i=e.get(o);i&&i.directory!==n||e.delete(o)}t.set(n,[...r])},XI=(e,t)=>e===t||!!e&&!!t&&e.attempt===t.attempt&&e.next===t.next&&e.message===t.message,JI=(e,t,n,r,s)=>{const o=Wr(t),i=[];let a=null,l=null;for(const m of n){const g=m?.session;if(!g?.id||!g.directory)continue;const x=Wr(g.directory);if(x!==o)continue;const b=typeof g.timeArchived=="number"?g.timeArchived>0:!!g.archived,S=e.byId.get(g.id),y=typeof m.updatedAt=="number"&&Number.isFinite(m.updatedAt)?m.updatedAt:typeof g.updatedAt=="number"&&Number.isFinite(g.updatedAt)?g.updatedAt:r,v=m.live&&s?.acceptLiveObservation?.(g.id,m.live.sequence)?m.live:void 0,C=v?v.lifecycle:S?.lifecycle??"idle",w=v?.lifecycle==="retry"?v.retry??{}:void 0,I=v?XI(S?.retry,w)?S?.retry:w:S?.retry,E=m.inputState&&s?.acceptPendingInputObservation?.(g.id,m.inputState.sequence)?m.inputState.pending:void 0,T=E==null||Kd(E)?E:void 0,A=T!==void 0?T:S?.pendingInput,j={id:g.id,directory:x,parentId:g.parentId??null,title:g.title??"",archived:b,...b&&typeof g.timeArchived=="number"&&Number.isFinite(g.timeArchived)?{archivedAt:g.timeArchived}:{},createdAt:g.createdAt,updatedAt:S?S.updatedAt:y,...typeof m.preview=="string"?{preview:m.preview}:{},...typeof g.messageCount=="number"?{messageCount:g.messageCount}:S?.messageCount!==void 0?{messageCount:S.messageCount}:{},lifecycle:C,...I?{retry:I}:{},...A!==void 0?{pendingInput:A}:{},hydrated:S?.hydrated??!1};if(S&&mw(S,j)){i.push(g.id);continue}a||(a=new Map(e.byId),l=new Map(e.byDirectory)),a.set(g.id,j),i.push(g.id)}const f=e.byDirectory.get(o)??[],u=f.length!==i.length||f.some((m,g)=>m!==i[g]);if(!a&&!u){if(e.listStatusByDirectory.get(o)!=="ready"){const m=new Map(e.listStatusByDirectory);return m.set(o,"ready"),{...e,listStatusByDirectory:m}}return e}a||(a=new Map(e.byId)),l||(l=new Map(e.byDirectory)),YI(a,l,o,i);let h=null;return e.listStatusByDirectory.get(o)!=="ready"&&(h=new Map(e.listStatusByDirectory),h.set(o,"ready")),{byId:a,byDirectory:l,listStatusByDirectory:h??e.listStatusByDirectory}},QI=(e,t)=>{const n=Wr(t),r=e.listStatusByDirectory.get(n);if(r==="loading"||r==="ready")return e;const s=new Map(e.listStatusByDirectory);return s.set(n,"loading"),{...e,listStatusByDirectory:s}},eE=(e,t)=>{const n=Wr(t);if(e.listStatusByDirectory.get(n)==="failed")return e;const s=new Map(e.listStatusByDirectory);return s.set(n,"failed"),{...e,listStatusByDirectory:s}},Ys=(e,t,n,r)=>{const s=e.byId.get(t);if(!s)return e;const o=n==="retry"?r:void 0;if(s.lifecycle===n&&s.retry===o)return e;const i=new Map(e.byId);return i.set(t,{...s,lifecycle:n,retry:o}),{...e,byId:i}},xf=(e,t,n)=>{const r=e.byId.get(t);if(!r||r.hydrated===n)return e;const s=new Map(e.byId);return s.set(t,{...r,hydrated:n}),{...e,byId:s}},Fc=(e,t,n,r)=>{const s=e.byId.get(t);if(!s||s.title===n&&s.updatedAt===r)return e;const o=new Map(e.byId);return o.set(t,{...s,title:n,updatedAt:r}),{...e,byId:o}},t2=(e,t,n,r)=>{const s=e.byId.get(t);if(!s){if(!r)return e;const i=Ss(e,t,r.directory,r.lifecycle,n),a=i.byId.get(t);if(!a||a.updatedAt===n)return i;const l=new Map(i.byId);return l.set(t,{...a,updatedAt:n}),{...i,byId:l}}if(s.updatedAt>=n&&s.lifecycle===(r?.lifecycle??s.lifecycle))return e;const o=new Map(e.byId);return o.set(t,{...s,updatedAt:Math.max(s.updatedAt,n),...r?.lifecycle?{lifecycle:r.lifecycle}:{}}),{...e,byId:o}},n2=(e,t,n,r,s)=>{const o=e.byId.get(t);if(!o)return e;const i=n?s??(o.archived?o.archivedAt:void 0):void 0;if(o.archived===n&&o.updatedAt===r&&o.archivedAt===i)return e;const a={...o,archived:n,updatedAt:r};i===void 0?delete a.archivedAt:a.archivedAt=i;const l=new Map(e.byId);return l.set(t,a),{...e,byId:l}},aa=(e,t,n,r,s,o)=>{if(r!==null&&!Kd(r))return e;const i=e.byId.get(t);if(i){if(Ea(i.pendingInput,r))return e;const f=new Map(e.byId);return f.set(t,{...i,pendingInput:r}),{...e,byId:f}}if(r===null)return e;const a=Ss(e,t,n,"idle"),l=a.byId.get(t);if(!l||Ea(l.pendingInput,r))return a;const d=new Map(a.byId);return d.set(t,{...l,pendingInput:r}),{...a,byId:d}},tE=(e,t,n)=>{const r=n?.streamEpoch??null;if(r!==null&&(typeof t.streamEpoch!="string"||t.streamEpoch!==r))return e;const s=t.sequence;if(!Number.isSafeInteger(s)||s<0)return e;const o=n?.acceptPendingInputObservation??(()=>!0),i=new Set;let a=e;for(const l of t.sessions)!l||typeof l.sessionId!="string"||l.sessionId.length===0||typeof l.directory!="string"||l.directory.length===0||i.has(l.sessionId)||(i.add(l.sessionId),Kd(l.pending)&&o(l.sessionId,s)&&(a=aa(a,l.sessionId,l.directory,l.pending)));for(const[l,d]of a.byId)i.has(l)||d.pendingInput!=null&&o(l,s)&&(a=aa(a,l,d.directory,null));return a},nE=e=>{let t=null;for(const[n,r]of e.byId)r.pendingInput!==void 0&&(t||(t=new Map(e.byId)),t.set(n,{...r,pendingInput:void 0}));return t?{...e,byId:t}:e},rE=[],qm=e=>{const t=[];for(const n of e.byId.values())n.pendingInput!=null&&t.push({sessionId:n.id,directory:n.directory,pending:n.pendingInput});return t.length===0?rE:(t.sort((n,r)=>n.pending.since-r.pending.since||(n.sessionId<r.sessionId?-1:n.sessionId>r.sessionId?1:0)),t)},sE=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(r.sessionId!==s.sessionId||r.directory!==s.directory||!Ea(r.pending,s.pending))return!1}return!0},r2=(e,t)=>{const n=e.byId.get(t.id);if(n&&mw(n,t))return e;const r=new Map(e.byId);r.set(t.id,t);const s=e.byDirectory.get(t.directory);if(s){const i=s.filter(l=>l!==t.id),a=new Map(e.byDirectory);return a.set(t.directory,[t.id,...i]),{...e,byId:r,byDirectory:a}}const o=new Map(e.byDirectory);return o.set(t.directory,[t.id]),{...e,byId:r,byDirectory:o}},oE=(e,t)=>{const n=e.byId.get(t);if(!n)return e;const r=new Map(e.byId);r.delete(t);const s=e.byDirectory.get(n.directory);let o=null;if(s){const i=s.filter(a=>a!==t);o=new Map(e.byDirectory),i.length===0?o.delete(n.directory):o.set(n.directory,i)}return{byId:r,byDirectory:o??e.byDirectory,listStatusByDirectory:e.listStatusByDirectory}},s2=new WeakMap,Ns=e=>{const t=s2.get(e);if(t)return t;const n={id:e.id,directory:e.directory,parentID:e.parentId,title:e.title,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:{},time:{created:e.createdAt,updated:e.updatedAt,...e.archived?{archived:e.updatedAt}:{}}};return s2.set(e,n),n},o2=[],iE=(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},pd=(e,t)=>{const n=t?.archived??!1,r=t?.directory;let s;if(typeof r=="string"&&r.length>0){const i=Wr(r),a=e.byDirectory.get(i)??[],l=Um();if(!l.includes(i))s=a;else{const d=[],f=new Set(a);for(const u of l){if(u===i)continue;const h=e.byDirectory.get(u);if(h)for(const m of h)f.has(m)||(f.add(m),d.push(m))}s=d.length>0?[...a,...d]:a}}else{if(r===null||r==="")return o2;s=[...e.byId.keys()]}const o=[];for(const i of s){const a=e.byId.get(i);a&&!!a.archived===n&&o.push(Ns(a))}return o.length===0?o2:o},aE=e=>{const t=[];for(const n of e.byId.values())(n.lifecycle==="busy"||n.lifecycle==="retry")&&t.push(n);return t},VX=e=>{const t=[];for(const n of e.byId.values())(n.lifecycle==="busy"||n.lifecycle==="retry")&&t.push(n.id);return t.sort(),t.join("|")},bf=(e,t,n,r,s,o,i)=>{const a=Wr(n),l=[],d=[],f=new Set;for(const O of r){const N=O?.session;!N?.id||!N.directory||Wr(N.directory)===a&&(f.has(N.id)||(f.add(N.id),l.push(N.id),d.push(O)))}const u=new Set(l),h=e.byDirectory.get(a)??[],m=t.byDirectory.get(a)??[],g=new Set(h),x=new Set;for(const O of g)t.byId.has(O)||x.add(O);const b=new Map,S=new Map,y=new Map,v=new Map,C=new Set,w=new Set;for(const O of h)w.add(O);for(const O of m)w.add(O);for(const O of l)w.add(O);for(const O of w){const N=t.byId.get(O);if(!N)continue;const D=e.byId.get(O);if(D===N)continue;if(N.directory!==a){D&&(D.directory===a||g.has(O)||u.has(O))&&C.add(O);continue}if(!D){if(u.has(O))continue;b.set(O,N);continue}const W=N.title!==D.title,z=N.archived!==D.archived;if(u.has(O)){(W||z)&&v.set(O,{rec:N,titleChanged:W,archivedChanged:z});continue}W||z?S.set(O,N):y.set(O,N)}const I=d.filter(O=>{const N=O.session.id;return!(x.has(N)||o?.has(N)||C.has(N))}),E=JI(t,a,I,s,i);let T=null;for(const[O,N]of v){const D=E.byId.get(O);if(!D){S.set(O,N.rec);continue}const W=N.titleChanged?N.rec.title:D.title,z=N.archivedChanged?N.rec.archived:D.archived;if(D.title!==W||D.archived!==z){T||(T=new Map(E.byId));const X=N.archivedChanged?N.rec.archivedAt:D.archivedAt,F={...D,title:W,archived:z};z&&X!==void 0?F.archivedAt=X:delete F.archivedAt,T.set(O,F)}}if(b.size===0&&S.size===0&&y.size===0&&!T)return E;const A=T??E.byId,j=E.byDirectory.get(a)??[],k=new Set(j),_=new Map([...b,...S,...y]),M=[];for(const O of m)_.has(O)&&!k.has(O)&&M.push(O);let L=null;if(M.length>0){L=new Map(E.byDirectory),L.set(a,[...M,...j]),T||(T=new Map(A));for(const O of M){const N=_.get(O);N&&T.set(O,N)}}return!T&&!L?E:{byId:T??E.byId,byDirectory:L??E.byDirectory,listStatusByDirectory:E.listStatusByDirectory}},cE=2,lE=(e,t)=>Oh([...e],cE,async n=>t(n)),i2="*",yt="catalog",Bc="dialogs",At="chrome",wf=16,a2=2,dE=5,uE=300,fE=new Set(["DAEMON_UNAVAILABLE","DAEMON_TIMEOUT","DAEMON_START_TIMEOUT","DAEMON_SPAWN_FAILED","DAEMON_REQUEST_FAILED"]),Vc=e=>e==="busy"||e==="retry"?e:e==="error"?"error":"idle",gw=e=>{if(e.name==="session.lifecycle"){const t=e.payload&&typeof e.payload=="object"?e.payload.state:void 0;return t==="busy"||t==="retry"||t==="error"?t:t==="idle"?"idle":void 0}if(e.name==="assistant.message.start")return"busy";if(e.name==="session.error")return"error"},In=e=>e instanceof at?e:new at("DAEMON_REQUEST_FAILED",e instanceof Error?e.message:void 0),yi=e=>e instanceof at&&e.code==="INVALID_SESSION",Sf=e=>e instanceof at&&e.code==="SESSION_IN_USE",hE=e=>e instanceof at&&e.code==="SESSION_RUNTIME_CONFLICT",c2=async()=>{await new Promise(e=>setTimeout(e,uE))},$c=(e=fp())=>({directory:null,sessions:[],selectedSessionId:null,reducer:Jl(),connection:"loading",error:null,showArchived:!1,hydratedSessionIds:new Set,sessionLoadErrorById:new Map,focusPending:!1,sessionsListStatus:"idle",catalog:e,syncReadiness:"ready",syncRecovery:{directories:[],residents:[]}}),pE=(e,t,n)=>{const r=n?.now??Date.now(),s=t.byId.get(e.id),o=ce(e.directory)??e.directory,i=typeof e.timeArchived=="number"?e.timeArchived>0:!!e.archived;return{id:e.id,directory:o,parentId:e.parentId??null,title:e.title??"",archived:i,createdAt:e.createdAt,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:r,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:s?.messageCount!==void 0?{messageCount:s.messageCount}:{},lifecycle:s?.lifecycle??"idle",hydrated:s?.hydrated??!1,...s?.pendingInput!==void 0?{pendingInput:s.pendingInput}:{}}},l2=(e,t,n,r)=>{if(typeof r!="number"||!Number.isSafeInteger(r)||r<0)return e;const s=e.byId.get(t);if(s){if(s.messageCount===r)return e;const l=new Map(e.byId);return l.set(t,{...s,messageCount:r}),{...e,byId:l}}const o=Ss(e,t,n,"idle"),i=o.byId.get(t);if(!i||i.messageCount===r)return o;const a=new Map(o.byId);return a.set(t,{...i,messageCount:r}),{...o,byId:a}},mE=(e,t,n={})=>{if(!t||t.sessionId!==e.sessionId)return e;const r=e.lifecycle!=="busy"&&e.lifecycle!=="retry"&&e.streamingMessages.size===0&&e.lastSequence>=t.lastSequence&&n.localSendPending!==!0,o=(t.lifecycle==="busy"||t.lifecycle==="retry")&&!r||t.lastSequence>e.lastSequence,i=t.lastSequence>e.lastSequence,a=e.hasMoreBefore===!0&&t.messages.size>0,l={extensionNotices:t.extensionNotices,extensionErrors:t.extensionErrors,extensionCatalogRevision:t.extensionCatalogRevision,sessionTreeRevision:t.sessionTreeRevision,extensionEditor:t.extensionEditor,extensionEditorOps:t.extensionEditorOps,...t.awaitingPromptEcho!==void 0?{awaitingPromptEcho:t.awaitingPromptEcho}:{}};if(t.messages.size===0&&!o)return{...e,...l};const d={...e,...a&&t.hasMoreBefore!==void 0?{hasMoreBefore:t.hasMoreBefore,beforeCursor:t.beforeCursor}:{},lifecycle:o?t.lifecycle:e.lifecycle,lastSequence:Math.max(e.lastSequence,t.lastSequence),messages:new Map(e.messages),partOrder:new Map(e.partOrder),parts:Xl(e.parts),toolsByCallId:new Map(e.toolsByCallId),streamingMessages:new Set(o?t.streamingMessages:e.streamingMessages),queue:t.queue.steering>0||t.queue.followUp>0?t.queue:e.queue,...t.model&&(o||!e.model)?{model:t.model}:{},...t.thinking&&(o||!e.thinking)?{thinking:t.thinking}:{},...i?{extensionStatuses:t.extensionStatuses,extensionWidgets:t.extensionWidgets,extensionDialogs:t.extensionDialogs,extensionPanels:t.extensionPanels,extensionApps:t.extensionApps,extensionTitle:t.extensionTitle,...t.extensionWorking?{extensionWorking:t.extensionWorking}:{},...t.extensionDraftTracked?{extensionDraftTracked:!0}:{},extensionSurfaces:t.extensionSurfaces,bashExecutions:t.bashExecutions}:{},...l},f=o?t.runningCommand:e.runningCommand;if(f?d.runningCommand=f:delete d.runningCommand,o||a){for(const[u,h]of t.messages)(o||!d.messages.has(u))&&K8(d,u,h);for(const[u,h]of t.partOrder)if(!(!o&&d.partOrder.has(u))){d.partOrder.set(u,h);for(const m of h){const g=t.parts.get(m);g&&d.parts.set(m,g)}}for(const[u,h]of t.toolsByCallId)(o||!d.toolsByCallId.has(u))&&d.toolsByCallId.set(u,h)}return d};let d2=null;const gE=new Set(["session.snapshot","session.interrupted","session.deleted"]),u2=e=>gw(e)!==void 0||gE.has(e.name),vi=e=>e.inputState?{pending:e.inputState.pending,sequence:e.lastSequence}:void 0,qe=()=>(d2??=new Wm,d2),$X=e=>qe().subscribeOpenRequests(e),yE=e=>qe().subscribePendingInputTransitions(e),vE=e=>e instanceof at&&typeof e.status=="number"&&e.status>=400&&e.status<500&&e.status!==408;class Wm{state;listenersByTopic=new Map;stream=null;streamGeneration=0;streamReadyRevision=0;runtimeGeneration=0;archiveRevision=0;archiveRevisionById=new Map;focusGeneration=0;recovering=!1;pendingFocus=null;pendingPreferredSessionId=null;selectionRevision=0;userSelection=null;newerSelection(t,n){const r=this.userSelection;return r&&r.revision>t&&(!r.directory||ce(r.directory)===ce(n))?r.id:null}hydratedSessionIds=new Set;activityPhaseById=new Map;pendingPromptById=new Set;promptGenerationById=new Map;acceptedPromptGenerationById=new Map;acceptedPromptReconcileInFlight=new Map;lastAccessById=new Map;lastAccessClock=0;lastSelectedByDirectory=new Map;directoryRefreshGenerationByDirectory=new Map;pendingCatalogPassByKey=new Map;deletedSessionIds=new Set;static MAX_DELETED_SESSION_TOMBSTONES=4096;isDeleted=t=>this.deletedSessionIds.has(t);deletedSessionCountForTests=()=>this.deletedSessionIds.size;providerRefreshRevisionByDirectory=new Map;providerRefreshTaskByDirectory=new Map;evictionScheduled=!1;restoringTranscriptById=new Set;hydrateInflightById=new Map;transcriptPrefetch=null;historyInflightById=new Map;navigationGenerationById=new Map;navigationCounter=0;streamEpoch=null;lifecycleSequenceById=new Map;pendingInputSequenceById=new Map;pendingInputUnsupported=!1;pendingInputFetchInFlight=null;pendingInputRefetchRequested=!1;pendingMetadataBackfillAttempted=new Set;retiredStreamEpochs=new Set;recoveryDirectories=new Set;recoveryResidents=new Set;recoveryRunning=!1;recoveryRevision=0;recoveryAttempt=0;recoveryTimer=null;adoptStreamEpoch(t){return typeof t!="string"||t.length===0||this.streamEpoch===t?!1:(this.streamEpoch!==null&&this.retiredStreamEpochs.add(this.streamEpoch),this.streamEpoch=t,!0)}isResponseEpochCurrent(t){const n=typeof t?.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:void 0;return n?this.retiredStreamEpochs.has(n)?!1:this.streamEpoch===null?(this.streamEpoch=n,!0):n===this.streamEpoch:this.streamEpoch===null}createListLiveGate(t,{streamAttaching:n=!1}={}){const r=typeof t.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:null;if(!r||r!==this.streamEpoch)return{options:void 0,commit:()=>{}};if(!this.stream&&!n)return{options:void 0,commit:()=>{}};const s=new Set,o=new Set;return{options:{acceptLiveObservation:(l,d)=>{if(!Number.isSafeInteger(d)||d<0)return!1;const f=Math.max(this.lifecycleSequenceById.get(l)??-1,this.hydratedSessionIds.has(l)?this.state.reducer.lastSequence.get(l)??-1:-1);if(d<f)return!1;if(this.pendingPromptById.has(l)){const u=this.promptGenerationById.get(l);return u!==void 0&&this.acceptedPromptGenerationById.get(l)===u&&o.add(l),!1}return s.add(l),!0}},commit:l=>{if(r===this.streamEpoch){for(const d of l)d.live?.lifecycle==="idle"&&o.has(d.session.id)&&this.reconcileAcceptedPromptFromList(d.session.id);if(s.size!==0)for(const d of l){const f=d.live;if(!f||!s.has(d.session.id))continue;const u=d.session.id;(this.lifecycleSequenceById.get(u)??-1)<f.sequence&&this.lifecycleSequenceById.set(u,f.sequence),!(f.lifecycle==="idle"||typeof f.runStartedAt!="number")&&this.state.catalog.byId.get(u)?.lifecycle===f.lifecycle&&Mn(u,f.runStartedAt,f.serverNow)}}}}}createListPendingInputGate(t,{streamAttaching:n=!1}={}){const r=typeof t.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:null;if(!r||r!==this.streamEpoch)return{options:void 0,commit:()=>{}};if(!this.stream&&!n)return{options:void 0,commit:()=>{}};const s=new Map;return{options:{acceptPendingInputObservation:(a,l)=>{if(!Number.isSafeInteger(l)||l<0||l<(this.pendingInputSequenceById.get(a)??-1))return!1;const d=s.get(a);return(d===void 0||l>d)&&s.set(a,l),!0}},commit:a=>{if(r!==this.streamEpoch||s.size===0)return;const l=new Map;for(const d of a)d.inputState&&s.has(d.session.id)&&l.set(d.session.id,d.inputState.sequence);for(const[d,f]of s){const u=l.get(d)??f;(this.pendingInputSequenceById.get(d)??-1)<u&&this.pendingInputSequenceById.set(d,u)}}}}createDirectoryListGates(t,{streamAttaching:n=!1}={}){const r=this.createListLiveGate(t,{streamAttaching:n}),s=this.createListPendingInputGate(t,{streamAttaching:n});return{options:r.options||s.options?{...r.options,...s.options}:void 0,commit:a=>{r.commit(a),s.commit(a)}}}applyVerifiedEpochChange(t){const n=this.streamEpoch!==null&&this.streamEpoch!==t;if(!this.adoptStreamEpoch(t)||!n)return null;const r=this.resetForEpochChange();return this.state={...this.state,reducer:Jl(),hydratedSessionIds:new Set(this.hydratedSessionIds)},this.queueSyncRecovery({directories:"all-known",residents:r}),r}handleVerifiedEpochChange(t){const n=this.applyVerifiedEpochChange(t);n&&this.emit([At,yt,...[...n].map(r=>`session:${r}`)])}resetForEpochChange(){const t=new Set(this.hydratedSessionIds),n=[];for(const s of this.state.catalog.byId.values())s.pendingInput!=null&&n.push({type:"cleared",sessionId:s.id,directory:s.directory,pending:null});for(const[s,o]of this.openedPendingInputById)this.state.catalog.byId.has(s)||n.push({type:"cleared",sessionId:s,directory:o,pending:null});this.lifecycleSequenceById.clear(),this.pendingInputSequenceById.clear(),this.pendingInputUnsupported=!1,this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested=!1,this.pendingMetadataBackfillAttempted.clear(),this.hydratedSessionIds.clear(),this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch();for(const[s,o]of this.navigationGenerationById)this.navigationGenerationById.set(s,o+1);this.settleCarriedOverActivity();const r=nE(this.state.catalog);return r!==this.state.catalog&&(this.state={...this.state,catalog:r}),this.emitPendingInputTransitions(n),t}settleCarriedOverActivity(){let t=this.state.catalog;for(const n of t.byId.values())n.lifecycle!=="busy"&&n.lifecycle!=="retry"||this.pendingPromptById.has(n.id)||(t=Ys(t,n.id,"idle"),P0(n.id));t!==this.state.catalog&&(this.state={...this.state,catalog:t})}queueSyncRecovery(t){this.refreshPendingInputList();let n=!1,r=!1;if(t.directories==="all-known")for(const s of this.state.catalog.listStatusByDirectory.keys())s&&(n=!0,this.recoveryDirectories.has(s)||(this.recoveryDirectories.add(s),r=!0));else if(t.directories)for(const s of t.directories){const o=ce(s);o&&(n=!0,this.recoveryDirectories.has(o)||(this.recoveryDirectories.add(o),r=!0))}if(t.residents)for(const s of t.residents)s&&(n=!0,this.recoveryResidents.has(s)||(this.recoveryResidents.add(s),r=!0));n&&(this.recoveryRevision+=1,this.recoveryAttempt=0,this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,r&&this.publishSyncRecoveryState(),this.runSyncRecovery())}publishSyncRecoveryState(){const t=[...this.recoveryDirectories],n=[...this.recoveryResidents],r=t.length===0&&n.length===0?"ready":"recovering",s=this.state.syncRecovery;r===this.state.syncReadiness&&s.directories.length===t.length&&s.residents.length===n.length&&t.every((i,a)=>s.directories[a]===i)&&n.every((i,a)=>s.residents[a]===i)||(this.state={...this.state,syncReadiness:r,syncRecovery:{directories:t,residents:n}},this.emitChrome())}clearSyncRecovery(){this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,this.recoveryDirectories.clear(),this.recoveryResidents.clear(),this.recoveryRunning=!1,this.recoveryRevision+=1,this.recoveryAttempt=0,this.publishSyncRecoveryState()}async runSyncRecovery(){if(this.recoveryRunning)return;if(this.recoveryDirectories.size===0&&this.recoveryResidents.size===0){this.publishSyncRecoveryState();return}this.recoveryRunning=!0;const t=this.runtimeGeneration,n=Y(),r=this.streamEpoch,s=this.recoveryRevision,o=()=>t===this.runtimeGeneration&&n===Y()&&r===this.streamEpoch&&s===this.recoveryRevision;try{const i=this.state.selectedSessionId,a=[...this.recoveryResidents].sort((f,u)=>f===i?-1:u===i?1:0);if(await Oh(a,a2,async f=>{if(!o()||!this.recoveryResidents.has(f))return;if(this.isDeleted(f)){this.recoveryResidents.delete(f);return}const u=this.resolveSessionDirectory(f)??this.state.directory??void 0;if(u){try{const h=await Ie.getSession(f,{directory:u,runtimeKey:n});if(!o()||h.session.id!==f)return;if(this.isDeleted(f)){this.recoveryResidents.delete(f);return}if(!this.isResponseEpochCurrent(h)||!o())return;const m=this.state.reducer.bySession.get(f);(!m||m.lastSequence<=h.lastSequence)&&((h.lifecycle==="busy"||h.lifecycle==="retry")&&typeof h.runStartedAt=="number"&&Mn(h.session.id,h.runStartedAt,h.serverNow),this.commitSessionDetail(h)),this.recoveryResidents.delete(f)}catch(h){o()&&yi(h)&&(this.commitDeletion(f,u),this.recoveryResidents.delete(f))}this.publishSyncRecoveryState()}}),!o())return;const l=this.state.directory?ce(this.state.directory):null,d=[...this.recoveryDirectories].sort((f,u)=>f===l?-1:u===l?1:0);await Oh(d,a2,async f=>{if(o()&&this.recoveryDirectories.has(f)){try{(await this.refreshDirectoryCatalog(f)).ok&&o()&&this.recoveryDirectories.delete(f)}catch{}this.publishSyncRecoveryState()}})}finally{this.recoveryRunning=!1,t===this.runtimeGeneration&&n===Y()&&(this.recoveryDirectories.size>0||this.recoveryResidents.size>0)&&(s!==this.recoveryRevision||r!==this.streamEpoch)&&this.runSyncRecovery()}if(!(t!==this.runtimeGeneration||n!==Y())&&(this.publishSyncRecoveryState(),this.recoveryDirectories.size>0||this.recoveryResidents.size>0)){if(s!==this.recoveryRevision||r!==this.streamEpoch){this.runSyncRecovery();return}if(this.recoveryAttempt+=1,this.recoveryAttempt<=dE){const i=Math.min(16e3,1e3*2**(this.recoveryAttempt-1));this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=null,this.runSyncRecovery()},i)}}}commitMissedDeletion=(t,n)=>this.commitDeletion(t,n);commitDeletion(t,n){if(!t)return!1;const r=this.deletedSessionIds.has(t);this.deletedSessionIds.add(t);let s;this.deletedSessionIds.size>Wm.MAX_DELETED_SESSION_TOMBSTONES&&(s=this.deletedSessionIds.values().next().value,s&&this.deletedSessionIds.delete(s));const o=n??this.state.catalog.byId.get(t)?.directory??this.state.sessions.find(C=>C.session.id===t)?.session.directory??this.state.reducer.bySession.get(t)?.directory;if(o&&o!=="global")try{AI({runtimeKey:Y(),directory:o,sessionId:t})}catch{}try{Lt.getState().forgetSession(t)}catch{}P0(t),RM(t),yf(t),this.navigationGenerationById.delete(t),this.pendingInputSequenceById.delete(t),this.historyInflightById.delete(t),this.hydrateInflightById.delete(t),this.restoringTranscriptById.delete(t);const i=this.state.reducer.bySession.has(t)||this.hydratedSessionIds.has(t)||this.state.catalog.byId.has(t)||this.state.sessions.some(C=>C.session.id===t),a=this.state.catalog.byId.get(t)?.pendingInput??null,l=this.state.catalog.byId.get(t)?.directory??n??"",d=this.state.sessions.filter(C=>C.session.id!==t),f=this.state.selectedSessionId===t?d.find(C=>!C.session.archived)?.session.id??null:this.state.selectedSessionId,u=new Map(this.state.reducer.bySession);u.delete(t);const h=new Map(this.state.reducer.lastSequence);s&&h.delete(s);const m=this.state.reducer.lastSequence.get(t);m!==void 0?h.set(t,m):h.delete(t),this.hydratedSessionIds.delete(t),this.activityPhaseById.delete(t),this.pendingPromptById.delete(t),this.promptGenerationById.delete(t),this.acceptedPromptGenerationById.delete(t),this.lastAccessById.delete(t);const g=oE(this.state.catalog,t),x=g!==this.state.catalog,b=f!==this.state.selectedSessionId;let S=this.state.sessionLoadErrorById;if(S.has(t)){const C=new Map(S);C.delete(t),S=C}const y=S!==this.state.sessionLoadErrorById;if(!i&&r&&!x&&!b&&!y)return!1;this.state={...this.state,sessions:d,selectedSessionId:f,hydratedSessionIds:new Set(this.hydratedSessionIds),reducer:{bySession:u,lastSequence:h},catalog:g,sessionLoadErrorById:S};const v=[`session:${t}`,At];return x&&v.push(yt),this.emit(v),a!=null&&this.emitPendingInputTransitions([{type:"cleared",sessionId:t,directory:l,pending:null}]),!0}handleInvalidSession(t,n,r,s=[]){if(!t||r!==this.runtimeGeneration)return;const o=this.state.selectedSessionId===t;if(this.commitDeletion(t,n),s.length>0&&this.commitEvents(s),r!==this.runtimeGeneration||!o)return;const i=this.state.selectedSessionId,a=i&&!this.hydratedSessionIds.has(i);!!a!==this.state.focusPending&&(this.state={...this.state,focusPending:!!a},this.emitChrome()),i&&!this.hydratedSessionIds.has(i)&&this.hydrate(i,this.runtimeGeneration)}filterDeletedListItems(t){return this.deletedSessionIds.size===0?t:t.filter(n=>!this.deletedSessionIds.has(n.session.id))}cadence=new ek(t=>this.commitEvents(t));remoteSendRefreshDelayMs=1500;remoteSendRefreshTimers=new Map;sendUnarchiveTokenById=new Map;sendUnarchiveCounter=0;catalogCache;unsubscribeRuntime;constructor(t=vk()){this.catalogCache=t,this.state=$c(this.readCachedCatalog(Y())),this.unsubscribeRuntime=en(n=>{if(n.runtimeKey===n.previousRuntimeKey){this.reconnectAfterTransportSwitch();return}this.resetForRuntime()})}getRuntimeGeneration=()=>this.runtimeGeneration;getFocusGeneration=()=>this.focusGeneration;hasClusterAttached=()=>this.stream!==null||this.state.connection==="ready";getState=()=>this.state;subscribe=(t,n=i2)=>{let r=this.listenersByTopic.get(n);return r||(r=new Set,this.listenersByTopic.set(n,r)),r.add(t),()=>{const s=this.listenersByTopic.get(n);s&&s.delete(t)}};pendingInputTransitionListeners=new Set;extensionSurfaceDismissListeners=new Set;subscribeExtensionSurfaceDismissals=t=>(this.extensionSurfaceDismissListeners.add(t),()=>{this.extensionSurfaceDismissListeners.delete(t)});openedPendingInputById=new Map;subscribePendingInputTransitions=t=>(this.pendingInputTransitionListeners.add(t),()=>{this.pendingInputTransitionListeners.delete(t)});openRequestListeners=new Set;subscribeOpenRequests=t=>(this.openRequestListeners.add(t),()=>{this.openRequestListeners.delete(t)});emitOpenRequest(t){for(const n of[...this.openRequestListeners])try{n(t)}catch(r){console.error("[pi-session-store] open-request listener failed",r)}}emitPendingInputTransitions(t){for(const n of t)n.type==="opened"?this.openedPendingInputById.set(n.sessionId,n.directory):this.openedPendingInputById.delete(n.sessionId);if(!(t.length===0||this.pendingInputTransitionListeners.size===0))for(const n of[...this.pendingInputTransitionListeners])for(const r of t)try{n(r)}catch(s){console.error("[pi-session-store] pending-input listener failed",s)}}resetLiveRuntimeState(){this.providerRefreshRevisionByDirectory.clear(),this.deletedSessionIds.clear(),this.runtimeGeneration+=1,this.focusGeneration+=1,this.pendingFocus=null,this.pendingPreferredSessionId=null,this.userSelection=null,this.hydratedSessionIds.clear(),this.activityPhaseById.clear(),this.pendingPromptById.clear(),this.promptGenerationById.clear(),this.acceptedPromptGenerationById.clear(),this.lastAccessById.clear(),this.lastAccessClock=0,this.lastSelectedByDirectory.clear(),this.directoryRefreshGenerationByDirectory.clear();for(const t of this.remoteSendRefreshTimers.values())clearTimeout(t);this.remoteSendRefreshTimers.clear(),this.sendUnarchiveTokenById.clear(),this.streamEpoch=null,this.retiredStreamEpochs.clear(),this.lifecycleSequenceById.clear(),this.pendingInputSequenceById.clear(),this.openedPendingInputById.clear(),this.pendingInputUnsupported=!1,this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested=!1,this.pendingMetadataBackfillAttempted.clear(),this.clearSyncRecovery(),this.evictionScheduled=!1,this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch(),this.cadence.dispose(),this.stream?.dispose(),this.stream=null,this.streamGeneration+=1,this.streamReadyRevision+=1}raiseOrderingBaselinesForDirectory(t){const n=ce(t);if(!n)return;const r=this.state.catalog.byDirectory.get(n);if(!r||r.length===0)return;const s=[];for(const o of r){const i=this.state.catalog.byId.get(o);!i||i.archived||s.push(Ns(i))}s.length>0&&DM(s)}recordClusterConnectionChange(t,n){this.state.connection!==t&&Rr("pi-connection",{code:t,detail:(t==="error"||t==="unavailable")&&n?n.code:void 0})}dispose=()=>{this.catalogCache.flush(),this.resetLiveRuntimeState(),this.unsubscribeRuntime(),vf(),this.navigationGenerationById.clear(),this.navigationCounter=0;const t=$c();this.recordClusterConnectionChange(t.connection),this.state=t,this.emitBroadcast(),this.listenersByTopic.clear()};setShowArchived=t=>{t!==this.state.showArchived&&(this.state={...this.state,showArchived:t},this.emitChrome())};clearError=()=>{this.state.error&&(this.state={...this.state,error:null},this.emitChrome())};reportError=t=>{const n=In(t);this.recordClusterConnectionChange("error",n),this.state={...this.state,error:n,connection:"error"},this.emitChrome(),this.ensureConnectionRecovery(n)};ensureConnectionRecovery(t){if(this.stream||!fE.has(t.code))return;const n=this.runtimeGeneration,r=Y(),s=this.streamGeneration+1;this.streamGeneration=s;const o=this.streamCursor();let i=null;i=Gl({onEvent:()=>{},onAuthRequired:()=>this.handleStreamAuthRequired(),onReconnect:()=>{if(n!==this.runtimeGeneration||r!==Y()||s!==this.streamGeneration||this.stream!==i)return;i?.dispose(),this.stream=null,this.streamGeneration+=1,this.streamReadyRevision+=1;const{directory:a,selectedSessionId:l}=this.state;this.start({...a?{directory:a}:{},...l?{sessionId:l}:{}})}},{...o!==void 0?{fromSequence:o}:{},runtimeKey:r}),this.stream=i}handleStreamAuthRequired(){this.reportError(new at("DAEMON_AUTH_FAILED","The Pi runtime rejected the client authorization.")),SS()}failSessionLoad(t,n){const r=new Map(this.state.sessionLoadErrorById);r.set(t,n);const s=this.state.selectedSessionId===t;this.state={...this.state,sessionLoadErrorById:r,focusPending:s?!1:this.state.focusPending},this.emitChrome()}clearSessionLoadError(t){if(!this.state.sessionLoadErrorById.has(t))return;const n=new Map(this.state.sessionLoadErrorById);n.delete(t),this.state={...this.state,sessionLoadErrorById:n},this.emitChrome()}clear=()=>{this.resetLiveRuntimeState(),this.recordClusterConnectionChange("ready"),this.state={...$c(),connection:"ready"},vf(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()};acceptPendingInputSequence(t,n){return!Number.isSafeInteger(n)||n<0||n<(this.pendingInputSequenceById.get(t)??-1)?!1:(this.pendingInputSequenceById.set(t,n),!0)}applyPendingInputList(t){if(!this.isResponseEpochCurrent(t))return;const n=tE(this.state.catalog,t,{acceptPendingInputObservation:(r,s)=>this.acceptPendingInputSequence(r,s),streamEpoch:this.streamEpoch});n!==this.state.catalog&&(this.state={...this.state,catalog:n},this.emit([yt])),this.requestNeedingSessionMetadataBackfill(t.sessions.map(r=>r.sessionId))}requestNeedingSessionMetadataBackfill(t){for(const n of t){if(!n||this.pendingMetadataBackfillAttempted.has(n))continue;const r=this.state.catalog.byId.get(n);!r||r.pendingInput==null||r.title.trim()||typeof r.messageCount!="number"&&(this.hydratedSessionIds.has(n)||this.hydrateInflightById.has(n)||this.isDeleted(n)||(this.pendingMetadataBackfillAttempted.add(n),this.ensureHydrated(n).then(()=>{this.hydratedSessionIds.has(n)||this.pendingMetadataBackfillAttempted.delete(n)},()=>{this.pendingMetadataBackfillAttempted.delete(n)})))}}refreshPendingInputList(){if(this.pendingInputUnsupported)return;if(this.pendingInputFetchInFlight){this.pendingInputRefetchRequested=!0;return}if(this.streamEpoch===null)return;const t=this.runtimeGeneration,n=Y(),r=Ie.listPendingInput({runtimeKey:n}).then(s=>{t!==this.runtimeGeneration||n!==Y()||this.applyPendingInputList(s)},s=>{t!==this.runtimeGeneration||n!==Y()||s instanceof at&&s.status===404&&(this.pendingInputUnsupported=!0)}).finally(()=>{this.pendingInputFetchInFlight===r&&(this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested&&(this.pendingInputRefetchRequested=!1,this.refreshPendingInputList()))});this.pendingInputFetchInFlight=r}adoptDetailPendingInput(t,n,r,s,o){return!s||!this.acceptPendingInputSequence(n,o)?t:aa(t,n,r,s.pending)}async refreshDirectoryCatalog(t){const n=ce(t);if(!n)return{ok:!1,error:In(new at("INVALID_ARGUMENT","directory is required"))};const r=Y(),s=(this.directoryRefreshGenerationByDirectory.get(n)??0)+1;this.directoryRefreshGenerationByDirectory.set(n,s);const o=this.runtimeGeneration,i=this.state.catalog,a=QI(this.state.catalog,n);a!==this.state.catalog&&(this.state={...this.state,catalog:a},this.emit([yt]));try{const l=await Ie.listSessions({directory:n,runtimeKey:r});if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==Y())return{ok:!0};if(!this.isResponseEpochCurrent(l))throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const d=this.filterDeletedListItems(l.sessions),f=this.createDirectoryListGates(l),u=bf(i,this.state.catalog,n,d,Date.now(),this.deletedSessionIds,f.options);return u!==this.state.catalog?(this.state={...this.state,catalog:u},f.commit(d),this.emit([yt]),this.raiseOrderingBaselinesForDirectory(n)):f.commit(d),{ok:!0}}catch(l){if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==Y())return{ok:!0};const d=In(l),f=eE(this.state.catalog,n),u=ce(this.state.directory)===n,h=[];return f!==this.state.catalog&&(this.state={...this.state,catalog:f},h.push(yt)),u&&(this.state={...this.state,error:d},h.push(At)),h.length>0&&this.emit(h),{ok:!1,error:d}}}async refreshAllDirectoryCatalogs(t){const n=[...new Set(t)].map(d=>ce(d)).filter(d=>!!d);if(n.length===0)return;const r=this.runtimeGeneration,s=[],o=[],i=new Map,a=new Map;for(const d of n){const f=`${r}\0${d}`,u=this.pendingCatalogPassByKey.get(f);if(u){s.push(u);continue}o.push(d);const h=new Promise(m=>i.set(d,m));a.set(d,h),this.pendingCatalogPassByKey.set(f,h)}const l=lE(o,async d=>{const f=`${r}\0${d}`;try{return await this.refreshDirectoryCatalog(d)}finally{this.pendingCatalogPassByKey.get(f)===a.get(d)&&this.pendingCatalogPassByKey.delete(f),i.get(d)?.()}});try{await Promise.all([l,...s])}finally{for(const d of o){const f=`${r}\0${d}`;this.pendingCatalogPassByKey.get(f)===a.get(d)&&this.pendingCatalogPassByKey.delete(f),i.get(d)?.()}}}async start(t={}){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){await this.focusProject(t.directory??null,t.sessionId??null);return}try{const n=typeof t.directory=="string"&&t.directory.trim()?t.directory:null,r=!!(t.sessionId&&t.sessionDirectoryKnown===!1);if(n&&!r){await this.open(n,t.sessionId);return}if(t.sessionId&&(!t.sessionDirectoryKnown||r))try{const a=await Ie.getSession(t.sessionId,{...r?{}:{directory:n??void 0},runtimeKey:Y()});if(a?.session?.directory){await this.open(a.session.directory,t.sessionId);return}}catch{}const s=r?void 0:t.sessionId;if(n){await this.open(n,s);return}const o=await Ie.listProjects({runtimeKey:Y()}),i=o.projects.find(a=>a.selected)?.directory??o.projects[0]?.directory;if(!i){await this.connectWithoutProject();return}await this.open(i,s)}catch(n){this.reportError(n)}}async connectWithoutProject(){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){await this.focusProject(null,null);return}const t=++this.runtimeGeneration;this.focusGeneration=t,this.pendingFocus=null,this.pendingPreferredSessionId=null,this.clearTranscriptPrefetch(),this.recordClusterConnectionChange("loading"),this.state={...this.state,directory:null,sessions:[],selectedSessionId:null,connection:"loading",sessionsListStatus:"idle",focusPending:!1,error:null},this.emitChrome();try{const n=await Ie.health({runtimeKey:Y()});if(t!==this.runtimeGeneration)return;if(n.state!=="ready")throw new at(n.error?.code??"DAEMON_UNAVAILABLE",n.error?.message);const r=n.streamEpoch;typeof r=="string"&&r.length>0&&this.streamEpoch!==null&&r!==this.streamEpoch?this.applyVerifiedEpochChange(r):this.adoptStreamEpoch(r),this.recordClusterConnectionChange("ready"),this.state={...this.state,directory:null,sessions:[],selectedSessionId:null,connection:"ready",sessionsListStatus:"idle",focusPending:!1,error:null},this.attachClusterStream(t,Y()),this.emit([At,yt]),this.refreshPendingInputList()}catch(n){t===this.runtimeGeneration&&this.reportError(n)}}attachClusterStream(t,n){if(this.stream||t!==this.runtimeGeneration)return;const r=this.streamGeneration+1;this.streamGeneration=r;const s=()=>t===this.runtimeGeneration&&n===Y()&&r===this.streamGeneration,o=this.streamEpoch?this.streamCursor():void 0;this.stream=Gl({onEvent:i=>{s()&&this.apply(i)},onReconnect:()=>this.markStreamReconnected(t,n,r),onEpochChange:i=>{s()&&this.handleVerifiedEpochChange(i)},onAuthRequired:()=>{s()&&this.handleStreamAuthRequired()}},{...this.streamEpoch?{streamEpoch:this.streamEpoch}:{},...o!==void 0?{fromSequence:o}:{},runtimeKey:n})}async focusProject(t,n){const r=typeof t=="string"&&t.trim()?t.trim():null,s=ce(r)===ce(this.state.directory),o=n??null;if(s){if(!o||o===this.state.selectedSessionId)return;await this.select(o);return}if(!r){this.state={...this.state,directory:null,sessions:[],sessionsListStatus:"idle",focusPending:!1,error:null},this.emitChrome();return}const i=++this.focusGeneration,a=this.selectionRevision;this.pendingFocus={directory:r,expected:i,preferredSessionId:o},this.pendingPreferredSessionId=o,this.clearTranscriptPrefetch();const l=!!o&&this.hydratedSessionIds.has(o);this.state={...this.state,directory:r,sessions:[],selectedSessionId:l?o:o??null,sessionsListStatus:"loading",focusPending:!l,error:null},this.emitChrome(),l&&this.touchLastAccess(o),await this.resolveFocus(i,r,a)}async resolveFocus(t,n,r){const s=Y(),o=this.runtimeGeneration,i=this.state.catalog;let a=this.pendingPreferredSessionId,l=n;try{try{const v=await Ie.selectProject(n,{runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;l=v.directory,ce(l)!==ce(this.state.directory)&&(this.state={...this.state,directory:l},this.emitChrome())}catch(v){if(!this.shouldRetryFocusError(v))throw v;if(await c2(),t!==this.focusGeneration||o!==this.runtimeGeneration)return;l=(await Ie.selectProject(n,{runtimeKey:s})).directory,ce(l)!==ce(this.state.directory)&&(this.state={...this.state,directory:l},this.emitChrome())}const d=await this.fetchFocusListWithRetry(l,t,o,s);if(d.kind==="stale")return;if(d.kind==="failed"){this.failFocus(t,d.error);return}const f={sessions:this.filterDeletedListItems(d.payload.sessions)};if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;a=this.newerSelection(r,l)??a;let u=a?f.sessions.find(v=>v.session.id===a):void 0;if(a&&!u&&!this.isDeleted(a))try{const v=await Ie.getSession(a,{directory:l,runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;if(v?.session?.id)if(v.session.directory&&ce(v.session.directory)!==ce(l)&&t===this.focusGeneration){if(!this.newerSelection(r,l)){await this.focusProject(v.session.directory,a);return}}else f.sessions.unshift({session:v.session,updatedAt:v.session.updatedAt}),u={session:v.session,updatedAt:v.session.updatedAt}}catch(v){if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;yi(v)&&this.commitDeletion(a,l)}if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;const h=this.newerSelection(r,l),m=a&&!this.isDeleted(a),g=(h&&!this.isDeleted(h)?h:null)??u?.session.id??(m?a:f.sessions.find(v=>!v.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const x=this.createDirectoryListGates(d.payload),b=bf(i,this.state.catalog,l,f.sessions,Date.now(),this.deletedSessionIds,x.options),S=b!==this.state.catalog;this.state={...this.state,sessions:f.sessions,selectedSessionId:g,sessionsListStatus:"ready",focusPending:!!g&&!this.hydratedSessionIds.has(g),error:null,catalog:b},x.commit(f.sessions);const y=[At];S&&y.push(yt),this.emit(y),S&&this.raiseOrderingBaselinesForDirectory(l),g&&this.touchLastAccess(g),g&&!this.hydratedSessionIds.has(g)?(await this.hydrate(g,this.runtimeGeneration),t===this.focusGeneration&&this.state.focusPending&&this.state.selectedSessionId===g&&this.hydratedSessionIds.has(g)&&(this.state={...this.state,focusPending:!1},this.emitChrome())):g&&this.hydratedSessionIds.has(g)&&this.state.focusPending&&(this.state={...this.state,focusPending:!1},this.emitChrome())}catch(d){t===this.focusGeneration&&o===this.runtimeGeneration&&this.failFocus(t,In(d))}finally{t===this.focusGeneration&&this.pendingFocus?.expected===t&&(this.pendingFocus=null)}}failFocus(t,n){t===this.focusGeneration&&(this.state={...this.state,sessions:[],sessionsListStatus:"failed",focusPending:!1,error:n},this.emitChrome())}shouldRetryFocusError(t){if(t instanceof at){if(t.code==="DAEMON_UNAVAILABLE")return!0;const n=t.status;return typeof n=="number"&&n>=500&&n<600||n===408||n===429}return!0}async fetchFocusListWithRetry(t,n,r,s){try{const o=await Ie.listSessions({directory:t,runtimeKey:s});if(n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};if(!this.isResponseEpochCurrent(o))throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");return{kind:"ok",payload:o}}catch(o){if(!this.shouldRetryFocusError(o))return{kind:"failed",error:In(o)};if(await c2(),n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};try{const i=await Ie.listSessions({directory:t,runtimeKey:s});if(n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};if(!this.isResponseEpochCurrent(i))throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");return{kind:"ok",payload:i}}catch(i){return{kind:"failed",error:In(i)}}}}startTranscriptPrefetch(t,n,r,s){if(!t||this.isDeleted(t))return;const o=Ie.getSession(t,{directory:n,runtimeKey:r});o.catch(()=>{}),this.transcriptPrefetch={sessionId:t,directory:n,runtimeKey:r,generation:s,promise:o}}clearTranscriptPrefetch(){this.transcriptPrefetch=null}takeTranscriptPrefetch(t,n,r,s){const o=this.transcriptPrefetch;return this.transcriptPrefetch=null,!o||o.generation!==s||o.sessionId!==t||o.directory!==n||o.runtimeKey!==r||this.isDeleted(t)?null:o.promise}async consumeTranscriptPrefetch(t,n,r,s){const o=this.takeTranscriptPrefetch(t,n,r,s);if(o)try{const i=await o;return s!==this.runtimeGeneration?void 0:i}catch{return}}async open(t,n){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){if(ce(t)===ce(this.state.directory)){n&&n!==this.state.selectedSessionId&&await this.select(n);return}await this.focusProject(t,n??null);return}if(t===this.state.directory&&this.state.connection==="loading"){n&&n!==this.state.selectedSessionId&&(this.pendingPreferredSessionId=n,this.state={...this.state,selectedSessionId:n,error:null},this.emitChrome());return}if(t===this.state.directory&&this.state.connection==="ready"){n&&n!==this.state.selectedSessionId&&await this.select(n);return}this.providerRefreshRevisionByDirectory.clear();const r=++this.runtimeGeneration;this.focusGeneration=r,this.pendingFocus=null;const s=!n&&this.userSelection&&(!this.userSelection.directory||ce(this.userSelection.directory)===ce(t))?this.userSelection.id:null;this.pendingPreferredSessionId=n??s;const o=this.selectionRevision;this.hydratedSessionIds.clear(),this.activityPhaseById.clear(),this.pendingPromptById.clear(),this.promptGenerationById.clear(),this.acceptedPromptGenerationById.clear(),this.lastAccessById.clear(),this.lastAccessClock=0,this.lastSelectedByDirectory.clear(),this.directoryRefreshGenerationByDirectory.clear(),this.evictionScheduled=!1,this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch(),this.cadence.dispose(),this.stream?.dispose(),this.stream=null,this.recordClusterConnectionChange("loading"),this.state={...this.state,directory:t,selectedSessionId:this.pendingPreferredSessionId,connection:"loading",hydratedSessionIds:new Set,reducer:{bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)}},this.stripAwaitingPromptEchoMarkers(),this.emitChrome();const i=Y(),a=this.state.catalog;this.pendingPreferredSessionId&&this.startTranscriptPrefetch(this.pendingPreferredSessionId,t,i,r);try{const l=await Ie.selectProject(t,{runtimeKey:i});if(r!==this.runtimeGeneration)return;const d={directory:l.directory,runtimeKey:i};l.directory!==t&&(this.state={...this.state,directory:l.directory},this.emitChrome());const f=await Ie.health(d);if(r!==this.runtimeGeneration)return;if(f.state!=="ready")throw new at(f.error?.code??"DAEMON_UNAVAILABLE",f.error?.message);const u=f.streamEpoch;typeof u=="string"&&u.length>0&&this.streamEpoch!==null&&u!==this.streamEpoch?(this.applyVerifiedEpochChange(u),this.emit([At,yt])):this.adoptStreamEpoch(u);const h={state:"ready",protocolVersion:f.protocolVersion,capabilities:[...f.capabilities],...typeof f.streamEpoch=="string"?{streamEpoch:f.streamEpoch}:{}},m=await Ie.listSessions(d);if(r!==this.runtimeGeneration)return;if(!this.isResponseEpochCurrent(m))throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const g=this.filterDeletedListItems(m.sessions),x=this.newerSelection(o,l.directory)??this.pendingPreferredSessionId??n;let b=x?g.find(A=>A.session.id===x):void 0,S=null;if(x&&!b&&!this.isDeleted(x))try{const A=await(this.takeTranscriptPrefetch(x,t,i,r)??Ie.getSession(x,{directory:t,runtimeKey:i}));if(r!==this.runtimeGeneration)return;if(A?.session?.directory&&A.session.directory!==t){if(r!==this.runtimeGeneration)return;if(!this.newerSelection(o,l.directory)){await this.open(A.session.directory,x);return}}else A?.session?.id&&(g.unshift({session:A.session,updatedAt:A.session.updatedAt}),b={session:A.session,updatedAt:A.session.updatedAt},S=A)}catch(A){if(r!==this.runtimeGeneration)return;yi(A)&&this.commitDeletion(x,t)}const y=this.newerSelection(o,l.directory),v=x&&!this.isDeleted(x),C=(y&&!this.isDeleted(y)?y:null)??b?.session.id??(v?x:g.find(A=>!A.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const w=this.createDirectoryListGates(m,{streamAttaching:!0}),I=bf(a,this.state.catalog,l.directory,g,Date.now(),this.deletedSessionIds,w.options),E=I!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,sessions:g,selectedSessionId:C,connection:"ready",catalog:I},w.commit(g);const T=[At];if(E&&T.push(yt),this.emit(T),E&&this.raiseOrderingBaselinesForDirectory(l.directory),this.refreshPendingInputList(),C){let A;C===x?A=S??await this.consumeTranscriptPrefetch(C,t,i,r):this.clearTranscriptPrefetch(),await this.hydrate(C,r,void 0,{initialHealth:h,initialSessions:g,...A?{initialDetail:A}:{}})}}catch(l){r===this.runtimeGeneration&&this.reportError(l)}}async select(t,n){if(!t)return;const r=n??this.state.reducer.bySession.get(t)?.directory??this.state.sessions.find(o=>o.session.id===t)?.session.directory;if(this.userSelection={id:t,directory:r??this.state.directory,revision:++this.selectionRevision},r&&ce(r)!==ce(this.state.directory)){if(this.stream!==null){await this.focusProject(r,t);return}await this.open(r,t);return}if(this.state.connection==="loading"){if(this.state.selectedSessionId===t)return;this.pendingPreferredSessionId=t,this.state={...this.state,selectedSessionId:t,error:null},this.emitChrome();return}if(!this.state.directory){await this.focusProject(null,t);return}if(t===this.state.selectedSessionId){this.touchLastAccess(t);const o=this.state.reducer.bySession.get(t);(!this.hydratedSessionIds.has(t)||!o)&&await this.hydrate(t,this.runtimeGeneration),this.scheduleIdleEviction();return}this.state.directory&&this.lastSelectedByDirectory.set(ce(this.state.directory)??this.state.directory,t),this.cadence.flush(),this.state={...this.state,selectedSessionId:t,error:null,focusPending:!1},this.emitChrome(),this.touchLastAccess(t);const s=this.state.reducer.bySession.get(t);if(this.stream&&this.hydratedSessionIds.has(t)&&s){this.scheduleIdleEviction();return}await this.hydrate(t,this.runtimeGeneration)}lastSelectedSessionForDirectory(t){return t?this.lastSelectedByDirectory.get(ce(t)??t)??null:null}async ensureHydrated(t){if(!t)return;const n=this.state.reducer.bySession.get(t);if(this.hydratedSessionIds.has(t)&&n){this.touchLastAccess(t);return}await this.hydrate(t,this.runtimeGeneration)}async create(t,n){const r=n?.directory||this.directory(),s=this.runtimeGeneration;let o=n?.model,i=n?.thinking;if(!o||!i&&!We.getState().isInitialized){const u=await Ie.getSettings({directory:r,runtimeKey:Y()});o??=u.pichamber.defaultModel,i=d0({thinking:i,model:o,defaultThinkingByModel:u.pichamber.defaultThinkingByModel,defaultThinking:u.pichamber.defaultThinking})}else if(!i){const u=We.getState();i=d0({model:o,defaultThinkingByModel:u.settingsDefaultThinkingByModel,defaultThinking:u.settingsDefaultThinking})}const a=await Ie.createSession({cwd:r,...t?{title:t}:{},...o?{model:o}:{},...i?{thinking:i}:{}},{directory:r,runtimeKey:Y()});if(s!==this.runtimeGeneration)return a.session.id;this.state={...this.state,sessions:[{session:a.session,updatedAt:a.session.updatedAt},...this.state.sessions],selectedSessionId:n?.select===!1?this.state.selectedSessionId:a.session.id};const l=r2(this.state.catalog,this.recordFromPiSession(a.session)),d=l!==this.state.catalog;this.state={...this.state,catalog:l};const f=[At];return d&&f.push(yt),this.emit(f),await this.hydrate(a.session.id,s,a),a.session.id}async rename(t,n){const r=this.runtimeGeneration,s=Y();if(await Ie.renameSession({sessionId:t,title:n},this.scope()),r!==this.runtimeGeneration||s!==Y())return;const o=Date.now(),i=Fc(this.state.catalog,t,n,o),a=i!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(d=>d.session.id===t?{...d,session:{...d.session,title:n}}:d),catalog:i};const l=[At];a&&l.push(yt),this.emit(l)}resolveSessionDirectory(t,n){return n??this.state.catalog.byId.get(t)?.directory??this.state.sessions.find(r=>r.session.id===t)?.session.directory}async archive(t,n,r){const s=this.runtimeGeneration,o=Y(),i=this.resolveSessionDirectory(t,r),a=this.state.catalog.byId.get(t),l=a?.archived??this.state.sessions.find(m=>m.session.id===t)?.session.archived,d=a?.updatedAt,f=a?.archivedAt,u=++this.archiveRevision;this.archiveRevisionById.set(t,u);const h=Date.now();this.commitArchiveFlag(t,n,h,n?h:void 0);try{await Ie.archiveSession({sessionId:t,archived:n},this.scope(i))}catch(m){if(s===this.runtimeGeneration&&o===Y()&&this.archiveRevisionById.get(t)===u&&typeof l=="boolean"){const x=this.state.catalog.byId.get(t)?.updatedAt,b=x===h&&d!==void 0?d:x??h;this.commitArchiveFlag(t,l,b,f)}throw m}finally{this.archiveRevisionById.get(t)===u&&this.archiveRevisionById.delete(t)}}commitArchiveFlag(t,n,r,s){const o=n2(this.state.catalog,t,n,r,s),i=o!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(l=>l.session.id===t?{...l,session:{...l.session,archived:n}}:l),catalog:o};const a=[At];i&&a.push(yt),this.emit(a)}unarchiveForSend(t){const n=this.state.catalog.byId.get(t);if(!n?.archived)return()=>{};const r=++this.sendUnarchiveCounter;this.sendUnarchiveTokenById.set(t,r),this.setArchivedLocally(t,!1);const s=this.runtimeGeneration,o=n.directory,i=n.archivedAt;return a=>{if(!(s!==this.runtimeGeneration||this.sendUnarchiveTokenById.get(t)!==r)&&(this.sendUnarchiveTokenById.delete(t),a!==void 0)){if(vE(a)){this.state.catalog.byId.get(t)?.archived===!1&&this.setArchivedLocally(t,!0,i);return}o&&this.refreshDirectoryCatalog(o)}}}setArchivedLocally(t,n,r){const s=this.state.catalog.byId.get(t);if(!s)return;const o=n2(this.state.catalog,t,n,s.updatedAt,r),i=o!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(l=>l.session.id===t?{...l,session:{...l.session,archived:n}}:l),catalog:o};const a=[At];i&&a.push(yt),this.emit(a)}scheduleRemoteSendRefresh(t){if(!t||this.remoteSendRefreshTimers.has(t))return;const n=this.runtimeGeneration,r=setTimeout(()=>{this.remoteSendRefreshTimers.delete(t),n===this.runtimeGeneration&&this.refreshDirectoryCatalog(t)},this.remoteSendRefreshDelayMs);this.remoteSendRefreshTimers.set(t,r)}async remove(t,n){const r=this.runtimeGeneration,s=Y(),o=this.resolveSessionDirectory(t,n);if(await Ie.deleteSession({sessionId:t,ignoreMissing:!0},o?this.scope(o):this.scope()),r!==this.runtimeGeneration||s!==Y())return;const i=this.state.selectedSessionId;this.commitDeletion(t,o);const a=this.state.selectedSessionId;a&&a!==i&&await this.hydrate(a,r)}async fork(t,n){const r=this.state.sessions.find(l=>l.session.id===t)?.session.title??this.state.catalog.byId.get(t)?.title??"",s=this.runtimeGeneration,o=Y(),i=await Ie.forkSession({sessionId:t,...n?{messageId:n}:{}},this.scope());if(s!==this.runtimeGeneration||o!==Y())return;this.upsertAndHydrate(i);const a=i.session.title?.trim()||r.trim()||"Untitled";if(!a.includes("(Fork)")){const l=`${a} (Fork)`;this.rename(i.session.id,l).catch(()=>{})}}async clone(t){const n=this.runtimeGeneration,r=Y(),s=await Ie.cloneSession({sessionId:t},this.scope());n!==this.runtimeGeneration||r!==Y()||this.upsertAndHydrate(s)}async navigate(t,n){const r=this.state.reducer.bySession.get(t),s=r?[...r.messages.values()]:[],o=new Map;for(const l of s){const d=typeof l.text=="string"?l.text.trim():"";d&&o.set(l.id,d)}const i=this.runtimeGeneration,a=(this.navigationGenerationById.get(t)??0)+1;this.navigationGenerationById.set(t,a),this.navigationCounter=Math.max(this.navigationCounter,a),this.hydrateInflightById.delete(t),this.historyInflightById.delete(t);try{const l=await Ie.navigateSession(t,n,this.scope());if((this.navigationGenerationById.get(t)??0)!==a||i!==this.runtimeGeneration||!this.isResponseEpochCurrent(l))return l;const d=this.sessionFromDetail(l);this.commitNavigationSession(d,vi(l),l.session);const f=l.navigation;if(f&&typeof f.targetEntryId=="string"&&l.hasMoreBefore!==!0){const u=new Set(l.messages.map(b=>b.message.id)),h=s.filter(b=>!u.has(b.id)).map(b=>{const S=(o.get(b.id)??"").replace(/\s+/g," ").slice(0,120)||"[No text]",y=b.role==="assistant"?"assistant":"user";return{id:b.id,role:y,preview:S}}),m=zm(t),g=new Set(h.map(b=>b.id)),x=[...h];for(const b of m?.abandoned??[])!u.has(b.id)&&!g.has(b.id)&&(x.push(b),g.add(b.id));x.length===0?yf(t):KI(t,m?{...f,previousLeafId:m.previousLeafId}:f,x)}return l}catch(l){throw this.navigationGenerationById.get(t)===a&&(a<=1?this.navigationGenerationById.delete(t):this.navigationGenerationById.set(t,a-1)),l}}async prompt(t,n,r,s,o){const i=this.runtimeGeneration,a=o?.runtimeKey??Y(),l={directory:this.resolveSessionDirectory(t,o?.directory),runtimeKey:a,...o?.streamEpoch?{streamEpoch:o.streamEpoch}:{}};if(a!==Y())throw new Error("Runtime changed before sending message.");let d=this.state.reducer.bySession.get(t);const f=o?.knownEmptyTranscript===!0&&this.hydratedSessionIds.has(t)&&d!==void 0&&d.messages.size===0;if((!d||d.messages.size===0)&&!f){if(await this.hydrate(t,i),i!==this.runtimeGeneration||a!==Y())throw new Error("Runtime changed before sending message.");d=this.state.reducer.bySession.get(t)}const u=o?.operationId??T5(),h={sessionId:t,text:n,operationId:u,messageId:`msg_${u}`,clientId:bb(),...s?.length?{attachments:s}:{}},m=d?{...d,lifecycle:"busy"}:{sessionId:t,directory:this.state.directory??this.state.sessions.find(w=>w.session.id===t)?.session.directory??"",lastSequence:this.state.reducer.lastSequence.get(t)??-1,lifecycle:"busy",messages:new Map,partOrder:new Map,parts:Xl(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};if(r==="prompt"){let w=null;if(d)for(const I of d.messages.values())I.role==="user"&&(w=I.id);m.awaitingPromptEcho={baselineUserMessageId:w}}else m.awaitingPromptEcho=void 0;const g=new Map(this.state.reducer.bySession);g.set(t,m),this.state={...this.state,reducer:{...this.state.reducer,bySession:g}};const x=(this.promptGenerationById.get(t)??0)+1;this.promptGenerationById.set(t,x),this.pendingPromptById.add(t),this.promoteSession(t,"active",{reorder:!0}),this.touchSessionList(t);const b=Date.now(),S=t2(Ys(this.state.catalog,t,"busy"),t,b,{directory:m.directory||this.state.directory||"",lifecycle:"busy"}),y=S!==this.state.catalog;this.state={...this.state,catalog:S};const v=[`session:${t}`,At];y&&v.push(yt),this.emit(v);const C=this.unarchiveForSend(t);try{let w;return r==="steer"?w=await Ie.sendSteer(h,l):r==="followUp"?w=await Ie.sendFollowUp(h,l):w=await Ie.sendPrompt(h,l),this.promptGenerationById.get(t)===x&&this.acceptedPromptGenerationById.set(t,x),yf(t),r==="prompt"&&n.trimStart().startsWith("/")&&this.reconcileAcceptedSlashPrompt(t,x,i),C(),w}catch(w){if(C(w),CS("prompt-send",w),i!==this.runtimeGeneration||a!==Y())throw w;if(Sf(w)&&this.failSessionLoad(t,w),this.promptGenerationById.get(t)===x){this.pendingPromptById.delete(t);const I=this.state.reducer.bySession.get(t);if(I?.lifecycle==="busy"&&I.streamingMessages.size===0){const E=new Map(this.state.reducer.bySession);E.set(t,{...I,lifecycle:"error",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:E}},this.promoteSession(t,"settled"),this.emit([`session:${t}`,At])}}throw w}}async reconcilePendingPromptSnapshot(t,n,r){const o=this.state.reducer.bySession.get(t)?.directory||this.resolveSessionDirectory(t)||this.state.directory;if(!o)return!1;try{const i=await Ie.getSession(t,{directory:o,runtimeKey:Y()});if(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n||i.session.id!==t||!this.isResponseEpochCurrent(i)||(this.state.reducer.lastSequence.get(t)??this.state.reducer.bySession.get(t)?.lastSequence??-1)>i.lastSequence)return!1;(i.lifecycle==="busy"||i.lifecycle==="retry")&&typeof i.runStartedAt=="number"&&Mn(i.session.id,i.runStartedAt,i.serverNow);const l=i.lifecycle!=="busy"&&i.lifecycle!=="retry"&&i.isStreaming!==!0;if(l){this.pendingPromptById.delete(t);const d=this.state.reducer.bySession.get(t);if(d?.lifecycle==="busy"||d?.lifecycle==="retry"){const f=new Map(this.state.reducer.bySession);f.set(t,{...d,lifecycle:"idle",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:f}}}}return this.commitSessionDetail(i),l}catch{return!1}}reconcileAcceptedPromptFromList(t){const n=this.promptGenerationById.get(t);if(n!==void 0){if(this.acceptedPromptReconcileInFlight.has(t)){this.acceptedPromptReconcileInFlight.set(t,!0);return}this.acceptedPromptReconcileInFlight.set(t,!1),this.reconcilePendingPromptSnapshot(t,n,this.runtimeGeneration).catch(()=>!1).finally(()=>{const r=this.acceptedPromptReconcileInFlight.get(t)===!0;this.acceptedPromptReconcileInFlight.delete(t);const s=this.promptGenerationById.get(t);r&&this.pendingPromptById.has(t)&&s!==void 0&&this.acceptedPromptGenerationById.get(t)===s&&this.reconcileAcceptedPromptFromList(t)})}}async reconcileAcceptedSlashPrompt(t,n,r){await new Promise(s=>setTimeout(s,750)),!(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n||!this.pendingPromptById.has(t))&&await this.reconcilePendingPromptSnapshot(t,n,r)&&(await new Promise(s=>setTimeout(s,2e3)),!(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n)&&await this.reconcilePendingPromptSnapshot(t,n,r))}abort=t=>Ie.abortSession({sessionId:t},this.scope());compact=(t,n)=>Ie.compactSession({sessionId:t,...n?{customInstructions:n}:{}},this.scope());runBash=async(t,n,r)=>{const s=this.scope(),o=this.unarchiveForSend(t);try{const i=await Ie.runBash({sessionId:t,command:n,...r?.excludeFromContext?{excludeFromContext:!0}:{}},s);return o(),i}catch(i){throw o(i),i}};abortBash=t=>Ie.abortBash({sessionId:t},this.scope());setModel=(t,n,r)=>Ie.setSessionModel({sessionId:t,model:{providerId:n,modelId:r}},this.scope());setThinking=(t,n)=>Ie.setSessionThinking({sessionId:t,thinking:n},this.scope());tree=t=>Ie.getSessionTree(t,this.scope());providers=()=>Ie.listProviders({runtimeKey:Y()});upload=t=>Ie.createAttachment(t,this.scope());uploadFile=(t,n)=>Ie.uploadAttachment(t,n,this.scope());deleteUpload=t=>Ie.deleteAttachment(t,this.scope());selected(){const t=this.state.selectedSessionId,n=t?this.state.reducer.bySession.get(t):void 0;return n?vb(n):null}consumeExtensionEditor(t,n){const r=this.state.reducer.bySession.get(t);if(!r)return;const o=(r.extensionEditorOps??(r.extensionEditor?[r.extensionEditor]:[])).filter(l=>l.sequence>n),i=o.length>0?o[o.length-1]:void 0;if(r.extensionEditor===void 0&&r.extensionEditorOps===void 0&&o.length===0)return;const a=new Map(this.state.reducer.bySession);a.set(t,{...r,extensionEditorOps:o.length>0?o:void 0,extensionEditor:i}),this.state={...this.state,reducer:{...this.state.reducer,bySession:a}},this.emit([`session:${t}`])}dismissExtensionDialog(t,n){const r=M6(this.state.reducer,t,n);r!==this.state.reducer&&(this.state={...this.state,reducer:r},this.emit([`session:${t}`,Bc]))}dropExtensionSurface(t,n){const r=_6(this.state.reducer,t,n);r!==this.state.reducer&&(this.state={...this.state,reducer:r},this.emit([`session:${t}`]))}sessionFromDetail(t){return ed(t).session}async loadOlderMessages(t){const n=this.historyInflightById.get(t);if(n)return n;const r=this.state.reducer.bySession.get(t);if(!r?.hasMoreBefore||!r.beforeCursor||this.isDeleted(t))return!1;const s=this.runtimeGeneration,o=this.navigationGenerationById.get(t)??0,i=r.beforeCursor,a=Y(),l=Ie.getSessionMessages(t,{before:i},{directory:r.directory,runtimeKey:a}).then(d=>{if(s!==this.runtimeGeneration||a!==Y()||(this.navigationGenerationById.get(t)??0)!==o)return!1;const f=this.state.reducer.bySession.get(t);if(!f||f.beforeCursor!==i||d.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(d))return!1;const u=ed(d).session,h=new Map(u.messages);for(const[y,v]of f.messages)h.set(y,v);const m=new Map(u.partOrder);for(const[y,v]of f.partOrder)m.set(y,v);const g=Xl(u.parts);for(const[y,v]of f.parts)g.set(y,v);const x=new Map(u.toolsByCallId);for(const[y,v]of f.toolsByCallId)x.set(y,v);const b={...f,messages:h,partOrder:m,parts:g,toolsByCallId:x,hasMoreBefore:u.hasMoreBefore===!0,beforeCursor:u.beforeCursor,lastSequence:f.lastSequence},S={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};return S.bySession.set(t,b),this.state={...this.state,reducer:S},this.touchLastAccess(t),this.emit([`session:${t}`]),b.hasMoreBefore===!0}).finally(()=>{this.historyInflightById.get(t)===l&&this.historyInflightById.delete(t)});return this.historyInflightById.set(t,l),l}recordFromPiSession(t,n){return pE(t,this.state.catalog,n)}mergeHydratedSession(t,n){return mE(t,n,{localSendPending:this.pendingPromptById.has(t.sessionId)})}touchLastAccess(t){t&&(this.lastAccessClock+=1,this.lastAccessById.set(t,this.lastAccessClock))}commitNavigationSession(t,n,r){this.cadence.flush();const s=this.state.reducer.bySession.get(t.sessionId),o=s?{...t,lastSequence:Math.max(t.lastSequence,s.lastSequence),...s.model&&!t.model?{model:s.model}:{},...s.thinking&&!t.thinking?{thinking:s.thinking}:{},queue:s.queue.steering>0||s.queue.followUp>0?s.queue:t.queue}:t,i={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};i.bySession.set(o.sessionId,o),i.lastSequence.set(o.sessionId,o.lastSequence),this.hydratedSessionIds.add(o.sessionId),this.touchLastAccess(o.sessionId);const l=this.state.selectedSessionId===o.sessionId?!1:this.state.focusPending&&!this.hydratedSessionIds.has(this.state.selectedSessionId??"");let d=this.state.sessionLoadErrorById;if(d.has(o.sessionId)){const g=new Map(d);g.delete(o.sessionId),d=g}const f=Vc(o.lifecycle);let u=this.state.catalog;u.byId.has(o.sessionId)||(u=Ss(u,o.sessionId,o.directory,f)),u=xf(u,o.sessionId,!0),u=Ys(u,o.sessionId,f,o.retry),n&&(u=this.adoptDetailPendingInput(u,o.sessionId,o.directory,{pending:n.pending},n.sequence)),r&&(u=l2(u,o.sessionId,o.directory,r.messageCount));const h=u!==this.state.catalog;this.state={...this.state,reducer:i,error:null,focusPending:l,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:d,catalog:u};const m=[`session:${o.sessionId}`,At];h&&m.push(yt),this.emit(m),this.scheduleIdleEviction()}commitSessionDetail(t,n=[]){this.commitHydratedSession(this.sessionFromDetail(t),n,vi(t),t.session)}commitHydratedSession(t,n=[],r,s){if(this.isDeleted(t.sessionId))return;this.cadence.flush();const o=this.state.reducer.bySession.get(t.sessionId),i=this.mergeHydratedSession(t,o);(i.lifecycle==="busy"||i.lifecycle==="retry")&&R0(i.sessionId,"active");let a={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};a.bySession.set(i.sessionId,i),a.lastSequence.set(i.sessionId,i.lastSequence);for(const S of n){const y=tf(a,S);a=y.state,y.didApply&&this.observeActivity(S)}this.hydratedSessionIds.add(i.sessionId),this.touchLastAccess(i.sessionId);const d=this.state.selectedSessionId===i.sessionId?!1:this.state.focusPending&&!this.hydratedSessionIds.has(this.state.selectedSessionId??"");let f=this.state.sessionLoadErrorById;if(f.has(i.sessionId)){const S=new Map(f);S.delete(i.sessionId),f=S}let u=this.applyCatalogFromEvents(n,a);r&&(u=this.adoptDetailPendingInput(u,i.sessionId,i.directory,{pending:r.pending},r.sequence));const h=a.bySession.get(i.sessionId),m=h?.lifecycle,g=m?Vc(m):void 0;u.byId.has(i.sessionId)||(u=Ss(u,i.sessionId,i.directory,g??"idle")),u=xf(u,i.sessionId,!0),g!==void 0&&(u=Ys(u,i.sessionId,g,h?.retry)),s&&(u=l2(u,i.sessionId,i.directory,s.messageCount));const x=u!==this.state.catalog;this.state={...this.state,reducer:a,error:null,focusPending:d,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:f,catalog:u};const b=[`session:${i.sessionId}`,At,Bc];x&&b.push(yt),this.emit(b),this.scheduleIdleEviction()}async hydrate(t,n,r,s){if(n!==this.runtimeGeneration||this.isDeleted(t))return;const o=this.hydrateInflightById.get(t);if(o)return o;const i=this.hydrateUnshared(t,n,r,s).finally(()=>{this.hydrateInflightById.get(t)===i&&this.hydrateInflightById.delete(t)});return this.hydrateInflightById.set(t,i),i}async hydrateUnshared(t,n,r,s){if(n!==this.runtimeGeneration||this.isDeleted(t))return;const o=this.resolveSessionDirectory(t)||this.directory(),i=Y(),l=!!(this.state.reducer.bySession.get(t)&&this.hydratedSessionIds.has(t)),d=this.navigationGenerationById.get(t)??0;if(!s?.force&&this.stream&&l&&!r){this.state.connection==="error"||this.state.connection==="unavailable"?this.reconnect(t,n,i):this.state.connection==="ready"&&this.state.error&&(this.state={...this.state,error:null},this.emitChrome());return}this.clearSessionLoadError(t);const f=this.stream;try{if(this.stream){const w=r??await Ie.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration||w.session.id!==t||!this.isResponseEpochCurrent(w)||this.isDeleted(t)||(this.navigationGenerationById.get(t)??0)!==d)return;(w.lifecycle==="busy"||w.lifecycle==="retry")&&typeof w.runStartedAt=="number"&&Mn(w.session.id,w.runStartedAt,w.serverNow),this.commitSessionDetail(w);return}const u=[];let h=!1;const m=this.streamGeneration+1;this.streamGeneration=m;const g=()=>n===this.runtimeGeneration&&i===Y()&&m===this.streamGeneration,x=w=>{g()&&(h?this.apply(w):u.push(w))},b=await z6({directory:o,selectedSessionId:t,runtimeKey:i,...s?.initialHealth?{initialHealth:s.initialHealth}:{},...s?.initialSessions?{initialSessions:s.initialSessions}:{},...s?.initialDetail?{initialDetail:s.initialDetail}:{},onEvent:x,onStreamDisconnect:()=>{g()&&this.reconnect(this.state.selectedSessionId??t,n,i)},onStreamReconnect:()=>this.markStreamReconnected(n,i,m),onEpochChange:w=>{g()&&this.handleVerifiedEpochChange(w)},onAuthRequired:()=>{g()&&this.handleStreamAuthRequired()}});if(!g()){b.stream?.dispose();return}if(b.phase==="failed")throw b.stream?.dispose(),b.errors.at(-1)?.error??new at("DAEMON_PROTOCOL_MISMATCH","The Pi runtime returned an incompatible bootstrap response.");const S=b.selectedSessionTiming;S&&S.sessionId===t&&(S.lifecycle==="busy"||S.lifecycle==="retry")&&typeof S.runStartedAt=="number"&&Mn(S.sessionId,S.runStartedAt,S.serverNow);let y=r?this.sessionFromDetail(r):b.reducerState.bySession.get(t),v=r?vi(r):s?.initialDetail?vi(s.initialDetail):void 0,C=r?.session??s?.initialDetail?.session;if(r&&(r.lifecycle==="busy"||r.lifecycle==="retry")&&typeof r.runStartedAt=="number"&&Mn(r.session.id,r.runStartedAt,r.serverNow),!y)try{const w=r??await Ie.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration){b.stream?.dispose();return}if(this.isDeleted(t)){b.stream?.dispose();return}if(!this.isResponseEpochCurrent(w)){b.stream?.dispose();return}(w.lifecycle==="busy"||w.lifecycle==="retry")&&typeof w.runStartedAt=="number"&&Mn(w.session.id,w.runStartedAt,w.serverNow),v=vi(w),y=this.sessionFromDetail(w),C=w.session}catch(w){if(this.stream=b.stream,h=!0,n===this.runtimeGeneration&&yi(w)){this.handleInvalidSession(t,o,n,u);return}if(n===this.runtimeGeneration&&Sf(w)){u.length>0&&this.commitEvents(u),this.failSessionLoad(t,In(w));return}throw b.stream?.dispose(),this.stream=null,w}if(y.sessionId!==t){b.stream?.dispose();return}if(this.isDeleted(t)){b.stream?.dispose();return}if((this.navigationGenerationById.get(t)??0)!==d){b.stream?.dispose();return}this.stream=b.stream,this.commitHydratedSession(y,u,v,C),h=!0}catch(u){if(n!==this.runtimeGeneration)return;if(yi(u)){this.handleInvalidSession(t,o,n);return}if(Sf(u)){this.failSessionLoad(t,In(u));return}if(hE(u)){try{const h=await Ie.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration||h.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(h)||(this.navigationGenerationById.get(t)??0)!==d)return;(h.lifecycle==="busy"||h.lifecycle==="retry")&&typeof h.runStartedAt=="number"&&Mn(h.session.id,h.runStartedAt,h.serverNow),this.commitSessionDetail(h)}catch(h){if(n!==this.runtimeGeneration)return;this.failSessionLoad(t,In(h))}return}if(f&&this.stream===f&&In(u).code!=="DAEMON_AUTH_FAILED"){this.failSessionLoad(t,In(u));return}this.reportError(u)}}markStreamReconnected(t,n,r){if(!(t!==this.runtimeGeneration||n!==Y()||r!==this.streamGeneration)){if(this.streamReadyRevision+=1,this.state.connection==="ready"&&!this.state.error){(this.recoveryDirectories.size>0||this.recoveryResidents.size>0)&&(this.recoveryAttempt=0,this.runSyncRecovery());return}this.recordClusterConnectionChange("ready"),this.state={...this.state,connection:"ready",error:null},this.emitChrome()}}async reconnect(t,n,r){if(this.recovering||n!==this.runtimeGeneration)return;this.recovering=!0,this.cadence.flush();const s=this.stream,o=this.streamReadyRevision,i=this.streamGeneration+1,a=this.streamCursor(),l=()=>n===this.runtimeGeneration&&r===Y()&&(this.streamGeneration===i||this.streamGeneration===i-1&&o===this.streamReadyRevision);let d=!1;try{let f=!1;const u=await G6({directory:this.directory(),sessionId:t,runtimeKey:r,lastKnownSequence:a,streamEpoch:this.streamEpoch??void 0,onEvent:h=>{l()&&(!f&&h.name==="session.snapshot"&&h.payload?.snapshot?.resync===!0&&(f=!0,this.queueSyncRecovery({directories:"all-known",residents:this.hydratedSessionIds})),this.apply(h))},onStreamDisconnect:()=>{l()&&this.reconnect(this.state.selectedSessionId??t,n,r)},onStreamReconnect:()=>this.markStreamReconnected(n,r,i),onAuthRequired:()=>{l()&&(d=!0,this.handleStreamAuthRequired())},onEpochChange:h=>{l()&&this.handleVerifiedEpochChange(h)}});if(n!==this.runtimeGeneration||r!==Y()){u.stream?.dispose();return}if(o!==this.streamReadyRevision){u.stream?.dispose();return}if(u.phase==="ready"){typeof u.runStartedAt=="number"&&Mn(t,u.runStartedAt,u.serverNow);let h=!1;typeof u.epoch=="string"&&u.epoch.length>0&&this.streamEpoch!==u.epoch&&(h=this.applyVerifiedEpochChange(u.epoch)!==null),s?.dispose(),this.streamGeneration=i,this.stream=u.stream;const m={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)},g=[],x=[];for(const[v,C]of u.reducerState.bySession.entries()){const w=m.bySession.get(v),I=this.mergeHydratedSession(C,w);m.bySession.set(v,I),m.lastSequence.set(v,I.lastSequence),this.touchLastAccess(v),g.push(v),(w?.lifecycle==="busy"||w?.lifecycle==="retry")&&I.lifecycle!=="busy"&&I.lifecycle!=="retry"&&x.push(v)}for(const v of u.reducerState.bySession.keys())this.hydratedSessionIds.add(v);let b=this.state.catalog;for(const v of g){const C=m.bySession.get(v);C&&(b=Ys(b,v,Vc(C.lifecycle),C.retry))}const S=b!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,reducer:m,connection:"ready",error:null,hydratedSessionIds:new Set(this.hydratedSessionIds),...S?{catalog:b}:{}};const y=[At,Bc];for(const v of g)y.push(`session:${v}`);(S||h)&&y.push(yt),this.emit(y),this.refreshPendingInputList();for(const v of x)this.promoteSession(v,"settled");for(const v of g){if(!this.pendingPromptById.has(v))continue;const C=this.promptGenerationById.get(v);if(C===void 0||this.acceptedPromptGenerationById.get(v)!==C)continue;const w=u.reducerState.bySession.get(v)?.lifecycle;w==="busy"||w==="retry"||this.reconcileAcceptedPromptFromList(v)}this.scheduleIdleEviction(),h&&this.publishSyncRecoveryState()}else d||this.reportError(new at(u.error?.code??"DAEMON_UNAVAILABLE",u.error?.message))}finally{this.recovering=!1}}apply(t){this.cadence.push(t)}observeActivity(t){if(t.name==="session.lifecycle"){const n=t.payload.state==="busy"||t.payload.state==="retry";n&&typeof t.payload.runStartedAt=="number"&&Mn(t.sessionId,t.payload.runStartedAt,t.payload.serverNow),this.promoteSession(t.sessionId,n?"active":"settled",{notification:!n&&(t.payload.state==="idle"||t.payload.state==="error")?{kind:t.payload.state==="error"?"error":"completion",sequence:t.sequence,directory:t.directory}:void 0})}else if(t.name==="session.snapshot"){const n=t.payload.snapshot,r=n.lifecycle==="busy"||n.lifecycle==="retry"||n.isStreaming===!0;r&&typeof n.runStartedAt=="number"&&Mn(t.sessionId,n.runStartedAt,n.serverNow),this.promoteSession(t.sessionId,r?"active":"settled")}else t.name==="assistant.message.start"?this.promoteSession(t.sessionId,"active"):t.name==="session.interrupted"?this.promoteSession(t.sessionId,"settled"):t.name==="session.openUrl"?this.emitOpenRequest(t):t.name==="session.error"&&this.promoteSession(t.sessionId,"settled",{notification:{kind:"error",sequence:t.sequence,directory:t.directory,error:{code:t.payload.code,message:t.payload.message}}})}stripAwaitingPromptEchoMarkers(){let t=null;for(const[n,r]of this.state.reducer.bySession)r.awaitingPromptEcho!==void 0&&(t||(t=new Map(this.state.reducer.bySession)),t.set(n,{...r,awaitingPromptEcho:void 0}));t&&(this.state={...this.state,reducer:{...this.state.reducer,bySession:t}})}notePromptProgress(t){if(t.name==="assistant.message.start"||t.name==="session.lifecycle"&&(t.payload.state==="busy"||t.payload.state==="retry")){this.pendingPromptById.delete(t.sessionId);return}(t.name==="session.error"||t.name==="session.interrupted"||t.name==="session.lifecycle"&&t.payload.state!=="busy"&&t.payload.state!=="retry")&&this.pendingPromptById.delete(t.sessionId)}retainPendingPrompt(t,n){if(!this.pendingPromptById.has(n))return t;const r=t.bySession.get(n);if(!r||r.lifecycle==="busy"||r.lifecycle==="retry")return t;const s=new Map(t.bySession);return s.set(n,{...r,lifecycle:"busy"}),{...t,bySession:s}}promoteSession(t,n,r){const s=this.activityPhaseById.get(t);this.activityPhaseById.set(t,n),R0(t,n),r?.reorder&&LM(t,n);const o=r?.notification;if(!(n==="settled"&&s==="active"&&(r?.notifyIfSettled||o!==void 0)))return;const a=o?.directory??this.state.catalog.byId.get(t)?.directory??this.state.directory??void 0;this.state.selectedSessionId!==t&&Yb(t,a,o?.kind==="error"?{error:o.error??{}}:void 0),o&&Xb({sessionId:t,directory:a,sequence:o.sequence,kind:o.kind,title:this.state.catalog.byId.get(t)?.title})}touchSessionList(t){const n=this.state.sessions.findIndex(i=>i.session.id===t);if(n<0)return;const r=Date.now(),s=this.state.sessions[n];if(!s)return;const o=this.state.sessions.slice();o.splice(n,1),o.unshift({...s,updatedAt:r,session:{...s.session,updatedAt:r}}),this.state={...this.state,sessions:o}}requestProviderCatalogRefresh(t,n=!0){if(n){const i=(this.providerRefreshRevisionByDirectory.get(t)??0)+1;this.providerRefreshRevisionByDirectory.set(t,i)}if(this.providerRefreshTaskByDirectory.has(t))return;const r=this.runtimeGeneration;let s=0;const o=(async()=>{for(;r===this.runtimeGeneration;){const i=this.providerRefreshRevisionByDirectory.get(t)??0;if(i<=s)return;try{await We.getState().loadProviders({directory:t,source:"extension.catalog"})}finally{s=i}}})().catch(()=>{}).finally(()=>{if(this.providerRefreshTaskByDirectory.get(t)!==o)return;this.providerRefreshTaskByDirectory.delete(t);const i=this.providerRefreshRevisionByDirectory.get(t)??0;(r!==this.runtimeGeneration&&i>0||i>s)&&this.requestProviderCatalogRefresh(t,!1)});this.providerRefreshTaskByDirectory.set(t,o)}restoreTranscript(t){if(!t||this.restoringTranscriptById.has(t))return;this.restoringTranscriptById.add(t);const n=this.runtimeGeneration;this.hydrate(t,n,void 0,{force:!0}).finally(()=>{this.restoringTranscriptById.delete(t)})}commitEvents(t){if(t.length===0)return;let n=this.state.reducer,r=!1,s=!1;const o=new Set,i=new Set,a=new Map,l=[],d=[],f=new Map,u=new Map;for(const y of t){if(y.name!=="session.deleted")continue;const v=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0,C=u.get(v)??new Set;C.add(y.sessionId),u.set(v,C)}let h=null;for(const y of t){const v=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0;if(!v&&this.streamEpoch!==null||v&&this.retiredStreamEpochs.has(v))continue;if(v&&this.streamEpoch!==null&&v!==this.streamEpoch){if(y.name!=="session.snapshot")continue;this.adoptStreamEpoch(v);const j=this.resetForEpochChange();if(n=Jl(),o.clear(),h)for(const k of j)h.add(k);else h=j;i.clear(),a.clear(),f.clear(),l.length=0,r=!1,s=!1}if(v&&this.adoptStreamEpoch(v),this.deletedSessionIds.has(y.sessionId))continue;if(y.name==="session.deleted"){const j=tf(n,y);if(n=j.state,!j.didApply)continue;r=!0,i.add(y.sessionId),l.push(y),f.set(y.sessionId,y.directory),o.delete(y.sessionId),this.restoringTranscriptById.delete(y.sessionId);continue}if(u.get(v)?.has(y.sessionId))continue;const C=!n.bySession.has(y.sessionId),w=(n.lastSequence.get(y.sessionId)??-1)>=0,I=y.name==="extension.custom.dismiss"?n.bySession.get(y.sessionId)?.extensionSurfaces?.get(y.payload.surfaceId):void 0,E=tf(n,y);if(n=E.state,!E.didApply)continue;if(l.push(y),I&&y.name==="extension.custom.dismiss"&&d.push({sessionId:y.sessionId,reason:y.payload.reason,surface:I}),C&&w&&o.add(y.sessionId),y.name==="session.snapshot"&&o.add(y.sessionId),r=!0,i.add(y.sessionId),y.name==="extension.catalog"){const j=a.get(y.directory)??{providers:!1,resources:!1,commands:!1};a.set(y.directory,{providers:j.providers||y.payload.providers===!0,resources:j.resources||y.payload.resources===!0,commands:j.commands||y.payload.commands===!0})}this.notePromptProgress(y);const T=y.name==="session.error"||y.name==="session.interrupted"||y.name==="session.lifecycle"&&y.payload.state!=="busy"&&y.payload.state!=="retry",A=y.name==="assistant.message.start"&&y.payload.role==="user"||y.name==="session.snapshot";if(T||A){const j=n.bySession.get(y.sessionId);if(j?.awaitingPromptEcho!==void 0&&(T||!fw(j))){const k=new Map(n.bySession);k.set(y.sessionId,{...j,awaitingPromptEcho:void 0}),n={...n,bySession:k}}}if(this.pendingPromptById.has(y.sessionId)&&y.name==="session.snapshot"&&!y.payload.snapshot.isStreaming){n=this.retainPendingPrompt(n,y.sessionId),this.promoteSession(y.sessionId,"active");continue}this.observeActivity(y),this.lastAccessClock+=1,this.lastAccessById.set(y.sessionId,this.lastAccessClock),s=!0}if(!r){h&&(this.state={...this.state,reducer:n,hydratedSessionIds:new Set(this.hydratedSessionIds)},this.emit([At,yt,...[...h].map(y=>`session:${y}`)]),this.queueSyncRecovery({directories:"all-known",residents:h}));return}this.state={...this.state,reducer:n,...h?{hydratedSessionIds:new Set(this.hydratedSessionIds)}:{}};for(const[y,v]of f)this.commitDeletion(y,v);for(const y of l)u2(y)&&Number.isSafeInteger(y.sequence)&&(this.lifecycleSequenceById.get(y.sessionId)??-1)<y.sequence&&this.lifecycleSequenceById.set(y.sessionId,y.sequence);const m=this.applyCatalogFromEvents(l,n),g=m!==this.state.catalog;for(const y of l){if(y.name==="session.archive"){const w=m.byId.get(y.sessionId);w&&w.archived!==y.payload.archived&&this.scheduleRemoteSendRefresh(w.directory||y.directory);continue}if(!(y.name==="assistant.message.start"&&y.payload.role==="user"||y.name==="session.bash"))continue;const C=m.byId.get(y.sessionId);C?.archived&&this.scheduleRemoteSendRefresh(C.directory||y.directory)}const x=[];if(g){const y=this.state.catalog,v=new Map;for(const C of l){if(C.name!=="session.input")continue;const w=v.get(C.sessionId);w?w.push(C):v.set(C.sessionId,[C])}for(const[C,w]of v){const I=m.byId.get(C);if(!I)continue;const E=y.byId.get(C)?.pendingInput,T=I.pendingInput;let A=E;const j=[];for(const k of w){if(k.name!=="session.input")continue;const _=k.payload.pending,M=_===null?null:Kd(_)?_:void 0;if(M===void 0)continue;const L=k.payload.serverNow,O=typeof L=="number"&&Number.isFinite(L)&&L>0?L:void 0,N=A!=null,D=M!=null;!N&&D&&M?j.push({type:"opened",sessionId:C,directory:I.directory??k.directory,pending:M,...O!==void 0?{serverNow:O}:{}}):N&&!D&&j.push({type:"cleared",sessionId:C,directory:I.directory??k.directory,pending:null}),A=M}if(Ea(A,T))for(const k of j)x.push(k);else{const k=E!=null,_=T!=null;!k&&_&&T?x.push({type:"opened",sessionId:C,directory:I.directory,pending:T}):k&&!_&&x.push({type:"cleared",sessionId:C,directory:I.directory,pending:null})}}this.state={...this.state,catalog:m}}const b=new Map;for(const y of l)y.name==="session.input"&&b.set(y.sessionId,y);for(const[y,v]of b){if(v.payload.pending!==null||m.byId.has(y)||this.pendingInputSequenceById.get(y)!==v.sequence)continue;const C=this.openedPendingInputById.get(y);C!==void 0&&x.push({type:"cleared",sessionId:y,directory:C,pending:null})}const S=[];(g||h)&&S.push(yt),l.some(y=>y.name==="extension.dialog"||y.name==="extension.dialog.dismiss"||y.name==="session.snapshot")&&S.push(Bc);for(const y of i)S.push(`session:${y}`);S.length>0&&this.emit(S),this.emitPendingInputTransitions(x);for(const y of d)for(const v of[...this.extensionSurfaceDismissListeners])try{v(y)}catch(C){console.error("[pi-session-store] surface dismiss listener failed",C)}l.some(y=>y.name==="session.input")&&this.requestNeedingSessionMetadataBackfill(l.filter(y=>y.name==="session.input").map(y=>y.sessionId)),s&&this.scheduleIdleEviction();for(const y of o)this.restoreTranscript(y);h&&this.queueSyncRecovery({directories:"all-known",residents:h});for(const[y,v]of a)v.providers&&this.requestProviderCatalogRefresh(y),v.commands&&bl(y),v.resources&&(id(),ce(y)===ce(this.state.directory??"")&&Hr.getState().loadSkills())}applyCatalogFromEvents(t,n){let r=this.state.catalog;for(const s of t){if(this.deletedSessionIds.has(s.sessionId))continue;const o=n.bySession.get(s.sessionId),i=o?.lifecycle,a=gw(s);if(a!==void 0&&!r.byId.has(s.sessionId)&&(r=Ss(r,s.sessionId,s.directory,a)),i!==void 0&&(this.hydratedSessionIds.has(s.sessionId)||u2(s))&&(r=Ys(r,s.sessionId,Vc(i),o?.retry)),s.name==="session.input"&&this.acceptPendingInputSequence(s.sessionId,s.sequence)&&(r=aa(r,s.sessionId,s.directory,s.payload.pending,s.sequence)),s.name==="session.snapshot"){const l=s.payload.snapshot.inputState;l&&this.acceptPendingInputSequence(s.sessionId,s.sequence)&&(r=aa(r,s.sessionId,s.directory,l.pending,s.sequence))}if(s.name==="session.updated"){const l=typeof s.payload.title=="string"?s.payload.title.trim():"";if(l){r.byId.has(s.sessionId)||(r=Ss(r,s.sessionId,s.directory,a??"idle"));const d=r.byId.get(s.sessionId);r=Fc(r,s.sessionId,l,d?.updatedAt??Date.now())}else{const d=r.byId.get(s.sessionId);if(d){const f=zh(d.preview??"");r=Fc(r,s.sessionId,f,d.updatedAt)}}}if(s.name==="assistant.message.start"&&s.payload.role==="user"){r=t2(r,s.sessionId,Date.now(),{directory:s.directory,lifecycle:"busy"});const l=r.byId.get(s.sessionId),d=zh(s.payload.text??"");d&&l&&l.title.trim().length===0&&(r=Fc(r,s.sessionId,d,l.updatedAt))}}return r}scheduleIdleEviction(){this.evictionScheduled||this.state.reducer.bySession.size<=wf||(this.evictionScheduled=!0,queueMicrotask(()=>{this.evictionScheduled=!1,this.evictIdleTranscripts()}))}evictIdleTranscripts(){const t=this.state.reducer.bySession;if(t.size<=wf)return;const n=new Set;this.state.selectedSessionId&&n.add(this.state.selectedSessionId);for(const[h,m]of t)(m.lifecycle==="busy"||m.lifecycle==="retry")&&n.add(h),m.extensionDialogs.length>0&&n.add(h),m.extensionSurfaces&&m.extensionSurfaces.size>0&&n.add(h),this.state.catalog.byId.get(h)?.pendingInput!=null&&n.add(h);for(const h of this.pendingPromptById)n.add(h);const r=[];for(const h of t.keys()){if(n.has(h))continue;const m=this.lastAccessById.get(h)??0;r.push([h,m])}r.sort((h,m)=>h[1]-m[1]);let s=null,o=null,i=null,a=null;const l=[];let d=0;for(const[h]of r){if(t.size-d<=wf)break;s||(s=new Map(t)),o||(o=new Set(this.hydratedSessionIds)),i||(i=new Map(this.lastAccessById)),s.delete(h),o.delete(h),i.delete(h),this.activityPhaseById.delete(h),a=a??this.state.catalog,a=xf(a,h,!1),d+=1,l.push(h)}if(!s||!o||!i)return;this.lastAccessById=i;const f=!!a&&a!==this.state.catalog;this.state={...this.state,reducer:{bySession:s,lastSequence:new Map(this.state.reducer.lastSequence)},hydratedSessionIds:o,...a?{catalog:a}:{}};const u=[At];for(const h of l)u.push(`session:${h}`);f&&u.push(yt),this.emit(u)}async upsertAndHydrate(t){const n=this.runtimeGeneration,r=r2(this.state.catalog,this.recordFromPiSession(t.session)),s=r!==this.state.catalog;this.state={...this.state,sessions:[{session:t.session,updatedAt:t.session.updatedAt},...this.state.sessions.filter(i=>i.session.id!==t.session.id)],selectedSessionId:t.session.id,catalog:r};const o=[At];s&&o.push(yt),this.emit(o),await this.hydrate(t.session.id,n,t)}directory(){if(!this.state.directory)throw new at("DAEMON_UNAVAILABLE");return this.state.directory}streamCursor(){let t=-1;for(const n of this.state.reducer.lastSequence.values())n>t&&(t=n);return t>=0?t:void 0}scope(t){return{directory:t||this.directory(),runtimeKey:Y()}}reconnectAfterTransportSwitch(){const t=this.state.selectedSessionId;!this.stream||!t||!this.state.directory||this.reconnect(t,this.runtimeGeneration,Y())}resetForRuntime(){this.catalogCache.flush(),this.resetLiveRuntimeState(),this.state=$c(this.readCachedCatalog(Y())),vf(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()}emit(t){if(t.length===0)return;t.includes(yt)&&this.catalogCache.schedule(Y(),this.state.catalog);const n=new Set;for(const s of t){const o=this.listenersByTopic.get(s);if(o)for(const i of o)n.has(i)||(n.add(i),i())}const r=this.listenersByTopic.get(i2);if(r)for(const s of r)n.has(s)||(n.add(s),s())}readCachedCatalog(t){try{return this.catalogCache.read(t)??fp()}catch{return fp()}}emitBroadcast(){const t=new Set;for(const n of this.listenersByTopic.values())for(const r of n)t.has(r)||(t.add(r),r())}emitChrome(){this.emit([At])}}const Eo=new Map,f2=e=>{Eo.set(e,(Eo.get(e)??0)+1)},xE=e=>(Eo.get(e)??0)>0,bE=e=>{const t=Eo.get(e)??0;return t<=0?!1:(t===1?Eo.delete(e):Eo.set(e,t-1),!0)};function yw(){return pd(qe().getState().catalog,{archived:!1})}function Km(){const e=qe().getState().catalog;return[...pd(e,{archived:!1}),...pd(e,{archived:!0})]}function wE(e){const t=qe().getState();return t.catalog.byId.get(e)?.directory??t.sessions.find(n=>n.session.id===e)?.session.directory??t.directory}function SE(){return aE(qe().getState().catalog).map(e=>({id:e.id,title:e.title.trim()||null,directory:e.directory}))}function zX(e,t){return[]}function UX(e,t){return[]}const Gm=2048,h2=new WeakMap,CE=e=>e==="running"||e==="pending",vw=e=>{if(e==null)return 0;if(typeof e=="string")return e.length;if(typeof e=="number"||typeof e=="boolean")return String(e).length;try{return JSON.stringify(e)?.length??0}catch{return Gm+1}},kE=e=>{if(!e)return e;const t=e.patch??e.diff??e.filediff?.patch??e.filediff?.diff;if(vw(t)<=Gm)return e;const n={...e};if(delete n.patch,delete n.diff,n.filediff&&typeof n.filediff=="object"){const r={...n.filediff};delete r.patch,delete r.diff,n.filediff=r}return n.deferredBody=!0,n},Zm=(e,t)=>{if(e.type==="thinking")return{id:e.id,type:"reasoning",text:e.text,streaming:e.streaming};if(e.type==="attachment")return{id:e.id,type:"file",filename:e.attachment?.name,mime:e.attachment?.mime,size:e.attachment?.size};if(e.type==="file")return{id:e.id,type:"file",filename:e.file?.filename,mime:e.file?.mime,url:e.file?.url};if(e.type==="tool"){const n=CE(e.tool?.state),r=t?.full===!0||n,s=!r&&vw(e.tool?.output)>Gm,o=r?e.tool?.metadata:kE(e.tool?.metadata),i=!!(!r&&(s||o?.deferredBody)),a=e.tool?.render;let l;return a&&(i&&a.resultExpanded!==void 0?l={...a.call!==void 0?{call:a.call}:{},...a.result!==void 0?{result:a.result}:{}}:l=a),{id:e.id,type:"tool",tool:e.tool?.name,callID:e.tool?.toolCallId,state:{status:e.tool?.state==="running"||e.tool?.state==="pending"?"running":e.tool?.state==="error"?"error":e.tool?.state==="cancelled"?"cancelled":"completed",input:e.tool?.input,...s?{}:{output:e.tool?.output},...l!==void 0?{render:l}:{},error:e.tool?.error,time:{start:e.tool?.startedAt,end:e.tool?.endedAt},metadata:o,...i?{deferredBody:!0}:{}}}}return{id:e.id,type:"text",text:e.text}},ME=e=>({id:e.id,directory:e.directory,parentID:e.parentId??null,title:e.title,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:{},time:{created:e.createdAt,updated:e.updatedAt,...e.archived?{archived:e.timeArchived??e.updatedAt}:{}}}),IE=(e,t)=>{const n=[];if(e.parts.length>0){const i=e.parts.some(l=>l.type==="thinking"),a=e.parts.some(l=>l.type==="text");!i&&e.thinking&&n.push({id:`${e.id}:thinking`,type:"reasoning",text:e.thinking,streaming:!1}),n.push(...e.parts.map(l=>Zm(l))),!a&&e.text&&n.push({id:`${e.id}:text`,type:"text",text:e.text})}else e.thinking&&n.push({id:`${e.id}:thinking`,type:"reasoning",text:e.thinking,streaming:!1}),e.text&&n.push({id:`${e.id}:text`,type:"text",text:e.text});const s=e.role==="assistant"&&!e.streaming?e.error?"error":"stop":void 0;return{info:{id:e.id,sessionID:t,role:e.role,...e.role==="extension"?{customType:e.customType,data:e.data,details:e.details,...e.render?{render:e.render}:{},...e.text?{text:e.text}:{}}:{},...e.parentId?{parentID:e.parentId}:{},time:{created:e.createdAt,...e.streaming?{}:typeof e.durationMs=="number"&&e.durationMs>0?{completed:e.createdAt+e.durationMs}:{completed:e.createdAt}},...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.error?{error:{name:e.error.code,message:e.error.message}}:{},...e.model?{model:{providerID:e.model.providerId,modelID:e.model.modelId},providerID:e.model.providerId,modelID:e.model.modelId}:{},...e.thinkingLevel?{variant:e.thinkingLevel}:{},...e.role==="assistant"&&e.usage?{usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,totalTokens:e.usage.totalTokens,cost:e.usage.cost},cost:e.usage.cost.total}:{},...s?{finish:s}:{}},parts:n}},EE=e=>e?e.messages.map(t=>{const n=h2.get(t);if(n&&n.info.sessionID===e.sessionId)return n;const r=IE(t,e.sessionId);return h2.set(t,r),r}):[],_E=["chat","git","diff","terminal","files","diagram"],jE=["settings","skills","providers","git-identities"],Dr={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function xw(e){const t=TE();return{sessionId:AE(t),tab:NE(t),settingsPath:LE(t),diffFile:RE(t)}}function TE(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function AE(e){const t=e.get(Dr.SESSION)??e.get("s");if(t&&t.trim().length>0)return t.trim();if(typeof window<"u"){const n=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i);if(n?.[1])return decodeURIComponent(n[1].trim())}return null}function NE(e){const t=e.get(Dr.TAB);if(!t)return null;const n=t.toLowerCase().trim();return _E.includes(n)?n:null}function LE(e){const t=e.get(Dr.SETTINGS);if(!t)return null;const n=t.toLowerCase().trim();return n.length===0?null:n==="pichamber"||n==="general"||n==="preferences"?"home":(jE.includes(n),n)}function RE(e){const t=e.get(Dr.FILE);if(!t||t.trim().length===0)return null;try{return decodeURIComponent(t.trim())}catch{return t.trim()}}function qX(){if(typeof window>"u")return!1;try{const e=new URLSearchParams(window.location.search);return/^\/(?:session|s)\/[^/?#]+/i.test(window.location.pathname)||e.has(Dr.SESSION)||e.has("s")||e.has(Dr.TAB)||e.has(Dr.SETTINGS)||e.has(Dr.FILE)}catch{return!1}}const Ym=(e,t)=>e?.open===!0&&t===null,WX=e=>e.currentSessionId??(Ym(e.draft,e.currentSessionId)?null:e.piSelectedSessionId),PE=()=>{let e=!1,t,n;return(r,s,o=Object.is)=>{if(e&&Object.is(t,r))return n;const i=s(r);return e&&(typeof o=="function"?o:Object.is)(n,i)?(t=r,n):(e=!0,t=r,n=i,i)}},bw="oc.lastSession.v1",DE=8,Cf=()=>({version:1,runtimes:{}}),Xm=e=>{try{const t=e.getItem(bw);if(!t)return Cf();const n=JSON.parse(t);if(n.version!==1||!n.runtimes||typeof n.runtimes!="object")return Cf();const r={};for(const[s,o]of Object.entries(n.runtimes))!s||!o||typeof o.sessionId!="string"||o.sessionId.length===0||(r[s]={sessionId:o.sessionId,directory:typeof o.directory=="string"&&o.directory.length>0?o.directory:null,updatedAt:typeof o.updatedAt=="number"?o.updatedAt:0});return{version:1,runtimes:r}}catch{return Cf()}},ww=(e,t)=>{const n=Object.entries(t.runtimes).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,DE);try{e.setItem(bw,JSON.stringify({...t,runtimes:Object.fromEntries(n)}))}catch{}};function OE(e,t,n=Gt()){if(!t.sessionId)return;const r=Xm(n),s=Object.values(r.runtimes).reduce((o,i)=>Math.max(o,i.updatedAt),0);r.runtimes[e]={...t,updatedAt:Math.max(Date.now(),s+1)},ww(n,r)}function hp(e,t=Gt()){if(!e)return null;const n=Xm(t).runtimes[e];return n?{sessionId:n.sessionId,directory:n.directory}:null}function HE(e,t=Gt()){if(!e)return;const n=Xm(t);n.runtimes[e]&&(delete n.runtimes[e],ww(t,n))}const FE=120,BE=600,Sw=typeof window<"u"&&typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"?window.__PICHAMBER_HARDWARE_KEYBOARD__:null;let md=Sw===!0,au=Sw!==null,ca=null,kf=!1;const pp=new Set;md&&typeof document<"u"&&document.documentElement.classList.add("oc-hardware-keyboard");const cu=()=>{ca!==null&&(window.clearTimeout(ca),ca=null)},lu=e=>{if(md!==e){md=e,typeof document<"u"&&document.documentElement.classList.toggle("oc-hardware-keyboard",e);for(const t of pp)t()}},VE=()=>{if(typeof window>"u")return()=>{};const e=n=>{au=!0,cu(),lu(n)};if(typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"&&e(window.__PICHAMBER_HARDWARE_KEYBOARD__),kf)return()=>{};kf=!0;const t=n=>{const r=n.detail;e(r?.attached===!0)};return window.addEventListener("oc:hardware-keyboard",t),()=>{window.removeEventListener("oc:hardware-keyboard",t),kf=!1}},p2=e=>{au||!Number.isFinite(e)||(cu(),lu(e>0&&e<FE))},$E=()=>{au||typeof window>"u"||typeof document>"u"||document.documentElement.classList.contains("oc-keyboard-open")||(cu(),ca=window.setTimeout(()=>{ca=null,lu(!0)},BE))},zE=()=>{cu(),!au&&lu(!1)},UE=()=>md,qE=e=>(pp.add(e),()=>{pp.delete(e)});function WE(){return p.useSyncExternalStore(qE,UE,()=>!1)}const zo=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0?!0:window.location.protocol==="capacitor:",KX=()=>{p.useEffect(()=>{if(!zo())return;let e=!1;const t=[],n=document.documentElement;n.classList.add("oc-capacitor-app"),window.Capacitor?.getPlatform?.()==="android"&&n.classList.add("oc-platform-android"),Cw(),t.push(VE());const s=o=>{n.style.setProperty("--oc-keyboard-inset",`${Math.max(0,Math.round(o))}px`)};return mt(()=>import("./vendor-capacitor-status-bar-CWt0OF5t.js"),__vite__mapDeps([4,5,1,6])).then(async({StatusBar:o,Style:i})=>{if(e)return;const a=window.Capacitor?.getPlatform?.(),l=async()=>{if(a==="android"){const h=document.documentElement.classList.contains("dark"),m=(h?localStorage.getItem("splashBgDark"):localStorage.getItem("splashBgLight"))||(h?"#171515":"#fffdf4");await o.setOverlaysWebView({overlay:!1}).catch(()=>{}),await o.setBackgroundColor({color:m}).catch(()=>{}),await o.setStyle({style:h?i.Dark:i.Light}).catch(()=>{}),await o.show().catch(()=>{});return}await o.setStyle({style:i.Default}).catch(()=>{}),await o.setOverlaysWebView({overlay:!0}).catch(()=>{}),await o.show().catch(()=>{})};await l();const d=window.setTimeout(()=>{l()},400);t.push(()=>window.clearTimeout(d));const{App:f}=await mt(async()=>{const{App:h}=await import("./vendor-capacitor-app-NbQ-WiPS.js");return{App:h}},__vite__mapDeps([7,8,5,1,6])),u=await f.addListener("appStateChange",({isActive:h})=>{h&&l()});if(e){u.remove();return}t.push(()=>{u.remove()})}).catch(()=>{}),mt(()=>import("./vendor-capacitor-keyboard-CgrHt8iN.js"),__vite__mapDeps([9,5,1,6])).then(async({Keyboard:o})=>{if(e)return;if(window.Capacitor?.getPlatform?.()==="android"){const j=await o.addListener("keyboardWillShow",O=>{p2(O.keyboardHeight),n.classList.add("oc-keyboard-open"),window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),k=await o.addListener("keyboardDidShow",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),_=await o.addListener("keyboardWillHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-intent",{detail:{open:!1}})),n.classList.remove("oc-keyboard-open")}),M=await o.addListener("keyboardDidHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!1}}))}),L=()=>{j.remove(),k.remove(),_.remove(),M.remove()};if(e){L();return}t.push(L);return}await o.setAccessoryBarVisible({isVisible:!1}).catch(()=>{});const a=250,l=200,d="cubic-bezier(0.38, 0.7, 0.125, 1)";let f=null,u=null,h=0,m=!1,g=0,x=!1;const b=(j,k)=>{n.style.setProperty(j,`${Math.max(0,Math.round(k))}px`)},S=()=>{f!==null&&(window.clearTimeout(f),f=null)},y=(j,k)=>{window.dispatchEvent(new CustomEvent(j,{detail:k}))},v=()=>{const j=[],k=document.querySelector(".oc-mobile-composer");k&&j.push({el:k,factor:1});const _=document.querySelector(".oc-draft-center");return _&&j.push({el:_,factor:.5}),j},C=()=>{for(const{el:j}of v())j.style.transition="",j.style.transform=""},w=await o.addListener("keyboardWillShow",j=>{if(S(),p2(j.keyboardHeight),x=!0,h=j.keyboardHeight,!m){const _=document.querySelector(".oc-mobile-app-shell");g=_&&parseFloat(getComputedStyle(_).paddingBottom)||0}const k=Math.max(0,h-g);n.classList.remove("oc-kb-hide"),u!==null&&(window.clearTimeout(u),u=null),n.classList.add("oc-keyboard-open","oc-kb-animating","oc-kb-caret-hold"),s(h);for(const{el:_,factor:M}of v())_.style.transition=`transform ${a}ms ${d}`,_.style.transform=`translateY(${-k*M}px)`;b("--oc-kb-scroll-inset",k),y("oc:keyboard-settled",{open:!0}),y("oc:keyboard-anim",{phase:"show",slide:k,durationMs:a,easing:d}),f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-animating"),b("--oc-kb-layout",h),m=!0,C(),y("oc:keyboard-settled",{open:!0}),u=window.setTimeout(()=>{u=null,n.classList.remove("oc-kb-caret-hold")},250)},a+20)}),I=()=>{if(!x)return;x=!1,S(),y("oc:keyboard-intent",{open:!1}),u!==null&&(window.clearTimeout(u),u=null),n.classList.remove("oc-kb-caret-hold");const j=Math.max(0,h-g);if(n.classList.remove("oc-keyboard-open"),s(0),b("--oc-kb-scroll-inset",0),m){n.classList.remove("oc-kb-animating"),b("--oc-kb-layout",0),m=!1;for(const{el:k,factor:_}of v())k.style.transition="none",k.style.transform=`translateY(${-j*_}px)`;document.querySelector(".oc-mobile-app-shell")?.offsetHeight}y("oc:keyboard-anim",{phase:"hide",slide:j,durationMs:l,easing:d}),n.classList.add("oc-kb-animating","oc-kb-hide");for(const{el:k}of v())k.style.transition=`transform ${l}ms ${d}`,k.style.transform="translateY(0px)";f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-animating","oc-kb-hide"),C(),y("oc:keyboard-settled",{open:!1})},l+20)},E=await o.addListener("keyboardWillHide",I),T=j=>j instanceof HTMLElement&&(j.tagName==="TEXTAREA"||j.tagName==="INPUT"||j.isContentEditable),A=j=>{x&&T(j.target)&&(T(j.relatedTarget)||window.setTimeout(()=>{x&&(T(document.activeElement)||I())},0))};if(document.addEventListener("focusout",A,!0),e){S(),document.removeEventListener("focusout",A,!0),w.remove(),E.remove();return}t.push(S,()=>{u!==null&&(window.clearTimeout(u),u=null)},()=>document.removeEventListener("focusout",A,!0),()=>{w.remove()},()=>{E.remove()})}).catch(()=>{}),()=>{e=!0,t.forEach(o=>o()),zE(),n.classList.remove("oc-capacitor-app","oc-keyboard-open","oc-kb-animating","oc-kb-hide","oc-kb-caret-hold","oc-platform-android"),n.style.removeProperty("--oc-keyboard-inset"),n.style.removeProperty("--oc-kb-shift"),n.style.removeProperty("--oc-kb-layout"),n.style.removeProperty("--oc-kb-scroll-inset")}},[])},GX=e=>{const t=p.useRef(!1);p.useEffect(()=>{if(!zo())return;let n=!1;const r=[],s=()=>{t.current&&(t.current=!1,e())},o=()=>{if(document.visibilityState==="hidden"){t.current=!0,Rr("app-lifecycle",{code:"hidden"});return}Rr("app-lifecycle",{code:"visible"}),s()};return document.addEventListener("visibilitychange",o),r.push(()=>document.removeEventListener("visibilitychange",o)),mt(()=>import("./vendor-capacitor-app-NbQ-WiPS.js"),__vite__mapDeps([7,8,5,1,6])).then(async({App:i})=>{if(n)return;const a=await i.addListener("appStateChange",({isActive:d})=>{if(document.documentElement.classList.toggle("oc-native-app-active",d),Rr("app-lifecycle",{code:d?"resume":"pause"}),!d){t.current=!0;return}s()}),l=await i.addListener("resume",()=>{Rr("app-lifecycle",{code:"resume"}),s()});if(n){a.remove(),l.remove();return}r.push(()=>{a.remove()},()=>{l.remove()})}).catch(()=>{}),()=>{n=!0,r.forEach(i=>i())}},[e])},la=[];let Mf=null;const KE=()=>{for(let e=la.length-1;e>=0;e--)try{if(la[e]())return!0}catch{}return!1},Cw=()=>zo()?(Mf||(Mf=mt(async()=>{const{App:e}=await import("./vendor-capacitor-app-NbQ-WiPS.js");return{App:e}},__vite__mapDeps([7,8,5,1,6])).then(({App:e})=>e.addListener("backButton",()=>{KE()||e.minimizeApp().catch(()=>{})})).catch(()=>null)),Mf.then(()=>{})):Promise.resolve(),ZX=e=>{const t=p.useRef(e);t.current=e,p.useEffect(()=>{if(!zo())return;Cw();const n=()=>t.current();return la.push(n),()=>{const r=la.lastIndexOf(n);r!==-1&&la.splice(r,1)}},[])},kw=p.createContext(null),Ha=()=>p.useContext(kw)??qe(),YX=({children:e,directory:t})=>{const n=p.useMemo(()=>qe(),[]),r=ct(o=>o.projects.find(i=>i.id===o.activeProjectId)?.path??null),s=t?.trim()||r;return H.useEffect(()=>{const o=xw(),i=he.getState(),a=Ym(i.newSessionDraft,i.currentSessionId);if(o.sessionId&&!a){const d=n.getState();if(d.selectedSessionId===o.sessionId&&d.connection==="ready")return;n.start({directory:s??void 0,sessionId:o.sessionId});return}if(!s){if(!a&&!zo()){const d=hp(Y());if(d?.sessionId){n.start({sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.connectWithoutProject();return}const l=a?null:n.lastSelectedSessionForDirectory(s);if(l){n.start({directory:s,sessionId:l,sessionDirectoryKnown:!0});return}if(!a&&!zo()){const d=hp(Y());if(d?.sessionId){n.start({directory:s,sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.start({directory:s})},[n,s]),c.jsx(kw.Provider,{value:n,children:e})},GE=e=>e;function Be(e,t,n="*",r=""){const s=Ha(),o=H.useRef(e);o.current=e;const i=H.useRef(t);i.current=t;const a=H.useRef(null),l=`${n}\0${r}`;a.current?.key!==l&&(a.current={key:l,select:PE()});const d=H.useCallback(()=>{const u=o.current??GE,h=typeof i.current=="function"?i.current:Object.is;return a.current.select(s.getState(),u,h)},[s]),f=H.useMemo(()=>u=>s.subscribe(u,n),[s,n]);return H.useSyncExternalStore(f,d,d)}const Mw={type:"idle"},ZE={type:"busy"},YE={type:"retry"},m2=new WeakMap,XE=[],JE=[],g2={loading:!1,complete:!0,status:"ready",cursor:void 0,error:null,errorCode:null},y2=[],v2=new WeakMap,Os="catalog",An="chrome",Kt=e=>`session:${e}`,QE=(e,t)=>{if(e==="busy")return ZE;if(e!=="retry")return Mw;if(!t)return YE;const n=m2.get(t);if(n)return n;const r={type:"retry",...t};return m2.set(t,r),r};function e_(e){const t=e?.archived??!1,n=e?.directory;return Be(r=>pd(r.catalog,{archived:t,directory:n}),iE,Os)}function XX(e,t){return du(e)}function JX(e){const t=Be(n=>n.catalog.byId,void 0,Os);if(e)return t.get(e)?.pendingInput}function Iw(){return Be(e=>qm(e.catalog),sE,Os)}function QX(e=!0){const t=Be(n=>{if(!e)return"";const r=[],s=[];for(const o of n.catalog.byId.values())(o.lifecycle==="busy"||o.lifecycle==="retry")&&r.push(o.id),o.pendingInput!=null&&s.push(o.id);return r.length===0&&s.length===0?"":JSON.stringify([r.sort(),s.sort()])},void 0,Os);return H.useMemo(()=>{if(!t)return{working:x2,needsInput:x2};const[n,r]=JSON.parse(t);return{working:new Set(n),needsInput:new Set(r)}},[t])}const x2=new Set;function If(e,t){qe().select(t,e||void 0)}function Jm(e,t){const n=fu(e);return H.useMemo(()=>n.map(r=>r.info),[n])}function t_(e,t,n){const r=Be(a=>e?a.reducer.bySession.get(e)??null:null,void 0,e?Kt(e):"*"),s=Be(a=>e?null:a.reducer.bySession,void 0,e?Kt(e):"*"),o=H.useMemo(()=>{if(e||!t||n!==void 0||!s)return null;for(const a of s.values())if(a.messages.has(t))return a;return null},[s,t,e,n]),i=r??o;return H.useMemo(()=>{if(!t||!i)return y2;const a=i.messages.get(t);if(!a)return y2;const l=i.partOrder.get(t)??[];if(l.length>0){const f=[];for(const u of l){const h=i.parts.get(u);if(!h)continue;const m=v2.get(h);if(m){f.push(m);continue}const g=Zm({id:h.id,type:h.type,text:h.text,streaming:h.streaming,...h.tool?{tool:h.tool}:{},...h.attachment?{attachment:h.attachment}:{}},{full:!0});v2.set(h,g),f.push(g)}return f}const d=[];return a.thinking&&d.push({id:`${a.id}:thinking`,type:"reasoning",text:a.thinking,streaming:!1}),a.text&&d.push({id:`${a.id}:text`,type:"text",text:a.text}),d},[t,i])}function du(e,t){const n=Be(s=>s.catalog.byId,void 0,Os);if(!e)return Mw;const r=n.get(e);return QE(r?.lifecycle,r?.retry)}function Ew(){return Be(e=>e.connection,void 0,An)}function n_(e){return Be(t=>e?t.reducer.bySession.get(e)?.compaction??null:null,void 0,e?Kt(e):"*")}function uu(e){return Be(t=>e?t.reducer.bySession.get(e)?.runningCommand??null:null,void 0,e?Kt(e):"*")}const b2=[];function _w(e){return Be(t=>e?t.reducer.bySession.get(e)?.extensionNotices??b2:b2,(t,n)=>t.length===n.length&&t.every((r,s)=>r.id===n[s]?.id),e?Kt(e):"*")}const w2=[];function r_(e){return Be(t=>e?t.reducer.bySession.get(e)?.bashExecutions??w2:w2,void 0,e?Kt(e):"*")}function s_(e){return Be(t=>!!(e&&t.reducer.bySession.get(e)?.bashExecutions?.length),void 0,e?Kt(e):"*")}function jw(){const e=Be(t=>t.directory,void 0,An);return e_({archived:!1,directory:e||null})}function eJ(e,t){const n=Be(s=>s.catalog.byId,void 0,Os),r=e?n.get(e)??null:null;return r?Ns(r):void 0}function o_(e){const t=Be(s=>s.catalog.byId,void 0,Os),n=Be(s=>s.directory,void 0,An);return(e?t.get(e)?.directory:void 0)??n??void 0}function i_(){return Be(e=>e.directory??"",void 0,An)}function a_(e,t){const n=Be(a=>a.hydratedSessionIds,void 0,An),r=Be(a=>a.selectedSessionId,void 0,An),s=Be(a=>a.connection,void 0,An),o=Be(a=>a.error,void 0,An),i=Be(a=>a.sessionLoadErrorById,void 0,An);return H.useMemo(()=>{if(!e||n.has(e))return g2;const l=i.get(e)??(s==="error"&&o?o:null);if(l)return{loading:!1,complete:!1,status:"error",cursor:void 0,error:l.message??"Session load failed",errorCode:l.code};const d=r===e||s==="loading";return{loading:d,complete:!1,status:d?"loading":"ready",cursor:void 0,error:null,errorCode:null}},[s,o,n,r,e,i])}function Tw(e,t){const n=Be(r=>r.hydratedSessionIds,void 0,An);return!e||n.has(e)}function c_(e){const t=Be(n=>e?n.reducer.bySession.get(e)??null:null,(n,r)=>Object.is(n,r)?!0:!n||!r?!1:RI(n,r),e?Kt(e):"*");return H.useMemo(()=>{if(!t)return XE;const n=[],r=new Set,s=[];for(const o of t.messages.values())o.role!=="user"||r.has(o.id)||(r.add(o.id),s.push(o));s.sort((o,i)=>o.createdAt-i.createdAt);for(const o of s){const i=t.partOrder.get(o.id)??[],a=i.length>0?i.map(l=>t.parts.get(l)).filter(l=>l?.type==="text").map(l=>l?.text??"").join(""):o.text??"";a&&n.push(a)}return n},[t])}function l_(e){return Be(t=>Ma(e?t.reducer.bySession.get(e)??null:null),Object.is,e?Kt(e):"*")}function d_(e){return Be(t=>fw(e?t.reducer.bySession.get(e)??null:null),Object.is,e?Kt(e):"*")}function fu(e,t,n){const r=n?.suspendPartUpdates!==!1,s=null,o=Be(a=>e?a.reducer.bySession.get(e)??null:null,(a,l)=>{if(Object.is(a,l)||a&&l&&NI(a,l))return!0;if(!a||!l)return!1;const d=Ma(l);return d?dp(a,l,d):!1},e?Kt(e):"*"),i=H.useRef(null);return H.useMemo(()=>{if(!o)return i.current=null,JE;const a=i.current,l=Ma(o);if(l&&a&&a.sessionId===e&&dp(a.session,o,l))return i.current={sessionId:e,session:o,projection:a.projection,records:a.records},a.records;const d=vb(o,a&&a.sessionId===e?{session:a.session,projection:a.projection}:null),f=EE(d),u=a?.records,h=u&&u.length===f.length&&u.every((m,g)=>m===f[g])?u:f;return i.current={sessionId:e,session:o,projection:d,records:h},h},[s,o,e,r])}function u_(e,t,n){const r=Ha(),s=n&&e?Kt(e):An,o=H.useMemo(()=>l=>r.subscribe(l,s),[r,s]),i=H.useCallback(()=>!n||!e||!t?null:r.getState().reducer.bySession.get(e)?.parts.get(t)??null,[n,t,e,r]),a=H.useSyncExternalStore(o,i,i);return H.useMemo(()=>!n||!a?null:Zm({id:a.id,type:a.type,text:a.text,streaming:a.streaming,...a.tool?{tool:a.tool}:{},...a.attachment?{attachment:a.attachment}:{}},{full:!0}),[n,a])}function f_(e,t){return Be(n=>e?n.reducer.bySession.get(e)?.messages.size??0:0,void 0,e?Kt(e):"*")}function h_(e){const t=Ha(),n=Be(o=>!!(e&&o.reducer.bySession.get(e)?.hasMoreBefore),void 0,e?Kt(e):"*"),r=Be(o=>e?o.reducer.bySession.get(e)?.beforeCursor:void 0,void 0,e?Kt(e):"*"),s=H.useCallback(()=>e?t.loadOlderMessages(e):Promise.resolve(!1),[e,t]);return{hasMoreBefore:n,beforeCursor:r,loadOlder:s}}function p_(e,t,n=!0){const r=Ha();!n||!e||r.ensureHydrated(e)}const Bt=()=>qe();async function m_(e,t,n,r){const s=await Bt().create(e,{...t?{directory:t}:{},...r?.model?{model:r.model}:{},...r?.thinking?{thinking:r.thinking}:{},...r?.select===!1?{select:!1}:{}}),o=Bt().getState().sessions.find(i=>i.session.id===s||i.session.id===Bt().getState().selectedSessionId);return o?ME(o.session):null}async function g_(e,t){return await Bt().remove(e),!0}async function y_(e,t){const n=[],r=[];for(const s of e)try{await Bt().remove(s),n.push(s)}catch{r.push(s)}return{deletedIds:n,failedIds:r}}async function v_(e){try{return await Bt().archive(e,!0),!0}catch{return!1}}const Aw=async(e,t)=>{const n=await Promise.allSettled(e.map(o=>Bt().archive(o,t))),r=[],s=[];return n.forEach((o,i)=>(o.status==="fulfilled"?r:s).push(e[i])),{done:r,failed:s}};async function x_(e,t){const{done:n,failed:r}=await Aw(e,!0);return{archivedIds:n,failedIds:r}}async function b_(e){try{return await Bt().archive(e,!1),!0}catch{return!1}}async function w_(e,t){const{done:n,failed:r}=await Aw(e,!1);return{restoredIds:n,failedIds:r}}async function S_(e,t){await Bt().rename(e,t)}async function C_(e){return null}async function k_(e){return null}async function M_(e,t){const r=(await Bt().navigate(e,t))?.navigation?.editorText;if(typeof r=="string"&&r.length>0)try{Ye.getState().setPendingRevertText(r)}catch{}}async function I_(e,t){if(!zm(e))throw new Error("No reverted conversation is available to restore.");await Bt().navigate(e,t)}async function E_(e){const t=zm(e)?.previousLeafId;if(!t)throw new Error("No reverted conversation is available to restore.");await Bt().navigate(e,t)}async function __(e,t){await Bt().fork(e,t)}async function j_(){const e=Bt().getState();if(e.connection!=="ready")throw e.error??new Error("Pi runtime is unavailable")}async function T_(e,t){await Bt().compact(e,t)}async function Nw(e){await Bt().abortBash(e)}function Qm(e){e&&Bt().abort(e)}const A_=e=>{if(typeof e!="string")return"attachment";const n=e.replace(/[\\/]/g,"_").replace(/\.\.+/g,"_").replace(/[\x00-\x1f\x7f]/g,"").replace(/^\.+/,"").trim();return n.length===0?"attachment":n.length>200?n.slice(0,200):n};function S2(e){const t=qe().getState(),n=t.reducer.bySession.get(e),r=t.sessions.find(s=>s.session.id===e)?.session;return{model:n?.model??r?.model,thinking:n?.thinking??r?.thinking}}async function mp(e){const t=e.delivery==="steer"||e.delivery==="followUp"?e.delivery:"prompt",n=e.runtimeKey??Y(),r=()=>{if(n!==Y())throw new Error("Runtime changed before sending message.")};r();const s=qe();let o=!1;if(e.sessionId&&e.providerID&&e.modelID){const l=S2(e.sessionId).model;(!l||l.providerId!==e.providerID||l.modelId!==e.modelID)&&(await s.setModel(e.sessionId,e.providerID,e.modelID),r(),o=!0)}if(e.sessionId&&Ht(e.variant)){const l=S2(e.sessionId).thinking;(o||l!==e.variant)&&(await s.setThinking(e.sessionId,e.variant),r())}const i=[...e.files??[],...(e.additionalParts??[]).flatMap(l=>l.files??[])].filter(l=>l.uploadState!==void 0||l.url.startsWith("data:")),a=[];try{const l=await Promise.all(i.map(async f=>{const u=f.uploadState;if(u?.status==="preparing"||u?.status==="uploading")throw new Error("Attachments are still uploading.");if(u?.status==="failed")throw new Error("Retry or remove failed attachments.");if(u?.status==="ready"&&u.expiresAt>Date.now())return{id:u.attachmentId};if(typeof f.url=="string"&&f.url.startsWith("data:")){const m=await(await fetch(f.url)).blob();r();const g=await s.uploadFile(m,{filename:A_(f.filename),mime:f.mime});return a.push(g.id),{id:g.id}}throw new Error("Attachment data is unavailable. Remove the attachment and add it again.")}));r();const d=l.length>0?l:void 0;await s.prompt(e.sessionId,e.content,t,d,{...e.knownEmptyTranscript?{knownEmptyTranscript:!0}:{},...e.operationId?{operationId:e.operationId}:{},...e.streamEpoch?{streamEpoch:e.streamEpoch}:{},...e.directory?{directory:e.directory}:{},runtimeKey:n})}catch(l){throw typeof l=="object"&&l!==null&&l.name==="PiSendUnconfirmedError"||await Promise.all((n===Y()?a:[]).map(d=>s.deleteUpload(d).catch(()=>{}))),l}}function N_(e){const t=ce(e.session?.directory??e.currentDirectory??null);return{directory:t,source:t?"session":void 0}}function tJ(e){return""}const jl={id:null,open:!1,directoryOverride:null,branchIntent:null,worktreeIntent:null,parentID:null},Lw=(e,t,n)=>!!(e.open&&e.id&&e.id===n&&t===null),Rw=e=>ce(e.directory??null),Pw=Gt(),Dw="oc.chatInput.lastDraftTarget",L_=()=>{try{const e=Pw.getItem(Dw);if(!e)return null;const t=JSON.parse(e);return{projectId:typeof t?.projectId=="string"?t.projectId:null,directory:ce(typeof t?.directory=="string"?t.directory:null)}}catch{return null}},gp=e=>{try{Pw.setItem(Dw,JSON.stringify(e))}catch{}},R_=e=>{const t=Km().find(s=>s.id===e),n=t?Rw(t):null;if(n)return ce(n);const r=wE(e);return r?ce(r):null},gd=new Map,Ef=new Map,ir=e=>(e??Y()).trim()||"default",yp=e=>({...e}),Xs=(e,t)=>{const n=gd.get(e);gd.set(e,{sessionId:n?.sessionId??null,directory:n?.directory??null,draft:n?.draft?yp(n.draft):{...jl},...t})},P_=e=>{const t=ir(),n=gd.get(t),r=hp(t);return{runtime:n?.sessionId===e?ce(n.directory):null,persisted:r?.sessionId===e?ce(r.directory):null}};let hu=null;const C2=()=>hu,D_=e=>{hu=e},k2=()=>{hu=null},O_=(e,t)=>({session:Km().find(n=>n.id===e)??null,currentDirectory:e===hu?null:ce(t)}),M2=(e,t=null)=>e?N_(O_(e,t))?.directory??null:null,vp=async e=>{await We.getState().activateDirectory(ce(e))},da=(e,t)=>!e||!t?!1:e.runtimeKey===t.runtimeKey&&ce(e.directory)===ce(t.directory)&&e.branch===t.branch;async function H_(e,t){const n=t.getState(),r=e.draftSnapshot??n.newSessionDraft;if(!r?.open)return null;if(r.branchIntent){const g=ce(r.branchIntent.directory),x=ce(r.directoryOverride);if(r.branchIntent.runtimeKey!==Y()||g!==x)throw new Error("The selected branch no longer matches this draft target.");if(!da(r.branchIntent,e.branchCheckoutReceipt))throw new Error("Confirm the selected branch before creating this session.")}if(r.worktreeIntent){const g=e.worktreeCreationReceipt;if(!g||g.runtimeKey!==r.worktreeIntent.runtimeKey||ce(g.projectRoot)!==ce(r.worktreeIntent.projectRoot)||ce(g.sourceDirectory)!==ce(r.worktreeIntent.sourceDirectory)||g.startRef!==r.worktreeIntent.startRef||!ce(g.path))throw new Error("Create the selected worktree before creating this session.")}const s=r.permissionAutoAcceptEnabled===!0,o=typeof e.agent=="string"&&e.agent.trim().length>0?e.agent.trim():void 0,i=e.worktreeCreationReceipt?.path??r.directoryOverride??null,a=r.selectedProjectId??null,l=r.title||(e.initialPrompt&&!e.initialPrompt.trimStart().startsWith("/")?zh(e.initialPrompt):void 0),d=await n.createSession(l,i,r.parentID??null,{model:e.providerID&&e.modelID?{providerId:e.providerID,modelId:e.modelID}:void 0,thinking:Ht(e.variant)?e.variant:void 0,select:!1},{draftSnapshot:r,closeDraft:!1});if(!d?.id)throw new Error("Failed to create session");const f=ce(d.directory??i??null),u=t.getState().newSessionDraft===r&&t.getState().currentSessionId===null;u&&gp({projectId:a,directory:f});const h=r.syntheticParts;u&&vp(f).catch(g=>{console.warn("Failed to activate directory after creating session:",g)});const m=o;return Lt.getState().saveSessionModelSelection(d.id,e.providerID,e.modelID),m&&(Lt.getState().saveSessionAgentSelection(d.id,m),Lt.getState().saveAgentModelForSession(d.id,m,e.providerID,e.modelID),Lt.getState().saveAgentModelVariantForSession(d.id,m,e.providerID,e.modelID,e.variant)),u&&n.setCurrentSession(d.id,f),s&&mt(async()=>{const{usePermissionStore:g}=await import("./permissionStore-zIpxq9Pq.js");return{usePermissionStore:g}},__vite__mapDeps([10,11,1])).then(({usePermissionStore:g})=>g.getState().setSessionAutoAccept(d.id,!0)).catch(g=>{console.warn("Failed to apply draft permission auto-accept to new session:",g)}),{sessionId:d.id,directory:f,agent:m,syntheticParts:h}}let I2=0;const F_=()=>(I2+=1,`draft-${Date.now()}-${I2}`);async function xp(e){return H_(e,he)}const he=Et()((e,t)=>({currentSessionId:null,currentSessionDirectory:null,newSessionDraft:{...jl},abortPromptSessionId:null,abortPromptExpiresAt:null,error:null,webUICreatedSessions:new Set,sessionAbortFlags:new Map,sendingNewSessionDraftId:null,pendingChangesBarDismissed:new Map,setCurrentSession:(n,r)=>{n&&t().closeNewSessionDraft();const s=ir();Ef.set(s,n);const o=nt.getState(),i=M2(n),a=qe().getState().directory??o.currentDirectory??null,l=(r?ce(r):null)??i,d=l??a,f=l===null,u=ct.getState(),h=d?Zn(u.projects,Ln(u.projects,Qt.getState()),d):null;e({currentSessionId:n,currentSessionDirectory:n?d??null:null}),D_(f&&n?n:null);const m=f?null:d??null;Xs(s,{sessionId:n,directory:m}),n&&OE(s,{sessionId:n,directory:m}),n&&qe().select(n,f?void 0:d);try{d&&o.currentDirectory!==d&&o.setDirectory(d,{showOverlay:!1}),h&&u.activeProjectId!==h.id&&u.setActiveProjectIdOnly(h.id)}catch(g){console.warn("Failed to set Pi directory for session switch:",g)}n&&(nu(n),If(d??"",n))},prepareForRuntimeSwitch:n=>{const r=ir(n),s=nt.getState().currentDirectory||null,o=t().currentSessionId;Ef.set(r,t().currentSessionId),Xs(r,{sessionId:o,directory:s,draft:yp(t().newSessionDraft)})},restoreForRuntimeSwitch:n=>{const r=ir(n),s=gd.get(r),o=s?.sessionId??Ef.get(r)??null,i=s?.draft?yp(s.draft):{...jl},a=s?.directory??null;a&&nt.getState().setDirectory(a,{showOverlay:!1}),e({currentSessionId:o,currentSessionDirectory:o?a:null,newSessionDraft:o?{...jl}:i,abortPromptSessionId:null,abortPromptExpiresAt:null,error:null,sendingNewSessionDraftId:null,sessionAbortFlags:new Map,pendingChangesBarDismissed:new Map}),o?If(a??qe().getState().directory??"",o):If("","")},openNewSessionDraft:n=>{n?.automatic||HE(ir());const r=ct.getState(),s=r.projects,o=Ln(s,Qt.getState()),i=r.getActiveProject(),a=ce(nt.getState().currentDirectory??null),l=L_(),d="__home__",f=n?.selectedProjectId===d,u=n?.directoryOverride!==void 0?ce(n.directoryOverride):null,h=n?.selectedProjectId?f?{id:d,path:u??""}:s.find(T=>T.id===n.selectedProjectId)??null:null,m=Zn(s,o,u),g=i||(r.activeProjectId?s.find(T=>T.id===r.activeProjectId)??null:s[0]??null),x=l?.projectId===d,b=l?.projectId?x?{id:d,path:l.directory??""}:s.find(T=>T.id===l.projectId)??null:null,S=Zn(s,o,l?.directory??null),y=Zn(s,o,a),v=f||h?h:u!==null?m:a?y:x?b:S??b??g,C=u!==null?u:f?u??ce(nt.getState().homeDirectory||Gt().getItem("homeDirectory")||"~")??u:h?ce(h.path??null):a||(l?.directory?l.directory:ce(v?.path??null)),w=f?d:v?.id??null;gp({projectId:w,directory:C});const I={id:F_(),open:!0,selectedProjectId:w,directoryOverride:C,branchIntent:n?.branchIntent&&n.branchIntent.runtimeKey===Y()&&ce(n.branchIntent.directory)===C?n.branchIntent:null,worktreeIntent:n?.worktreeIntent&&n.worktreeIntent.runtimeKey===Y()&&ce(n.worktreeIntent.sourceDirectory)===C?n.worktreeIntent:null,permissionAutoAcceptEnabled:n?.permissionAutoAcceptEnabled===!0,preserveDirectoryOverride:n?.preserveDirectoryOverride===!0,parentID:n?.parentID??null,title:n?.title,initialPrompt:n?.initialPrompt,syntheticParts:n?.syntheticParts,targetFolderId:n?.targetFolderId};e({newSessionDraft:{...I},currentSessionId:null,currentSessionDirectory:null,error:null}),Xs(ir(),{sessionId:null,directory:C,draft:I}),n?.initialPrompt&&Ye.getState().setPendingInputText(n.initialPrompt);const E=ce(v?.path??null)??C;vp(E),C&&C!==nt.getState().currentDirectory&&nt.getState().setDirectory(C)},closeNewSessionDraft:()=>{const n=t().newSessionDraft;if(!n.open&&n.selectedProjectId==null&&n.directoryOverride==null&&n.branchIntent==null&&n.worktreeIntent==null&&!n.preserveDirectoryOverride&&n.parentID==null&&n.title===void 0&&n.initialPrompt===void 0&&n.syntheticParts===void 0&&n.targetFolderId===void 0&&n.permissionAutoAcceptEnabled===void 0)return;const r={id:null,open:!1,selectedProjectId:null,directoryOverride:null,branchIntent:null,worktreeIntent:null,preserveDirectoryOverride:!1,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0,targetFolderId:void 0};e({newSessionDraft:r}),Xs(ir(),{draft:r})},setNewSessionDraftTarget:n=>{let r=null,s=null;e(o=>{r=ce(n.directoryOverride??o.newSessionDraft.directoryOverride),s=n.projectId??n.selectedProjectId??o.newSessionDraft.selectedProjectId??null;const i=Object.prototype.hasOwnProperty.call(n,"branchIntent"),a=Object.prototype.hasOwnProperty.call(n,"worktreeIntent"),l=ce(o.newSessionDraft.directoryOverride),d=r!==l,f=s!==(o.newSessionDraft.selectedProjectId??null),u=n.branchIntent,h=u&&u.runtimeKey===Y()&&ce(u.directory)===r?u:null,m=n.worktreeIntent,g=m&&m.runtimeKey===Y()&&ce(m.sourceDirectory)===r?m:null;return{newSessionDraft:{...o.newSessionDraft,selectedProjectId:s,directoryOverride:n.directoryOverride??o.newSessionDraft.directoryOverride,branchIntent:i?h:d||f?null:o.newSessionDraft.branchIntent,worktreeIntent:a?g:d||f?null:o.newSessionDraft.worktreeIntent}}}),gp({projectId:s,directory:r}),vp(r),r&&r!==nt.getState().currentDirectory&&nt.getState().setDirectory(r)},setDraftPreserveDirectoryOverride:n=>e(r=>r.newSessionDraft?.open?{newSessionDraft:{...r.newSessionDraft,preserveDirectoryOverride:n}}:r),setDraftPermissionAutoAcceptEnabled:n=>e(r=>r.newSessionDraft?.open?{newSessionDraft:{...r.newSessionDraft,permissionAutoAcceptEnabled:n}}:r),acknowledgeSessionAbort:n=>e(r=>{const s=new Map(r.sessionAbortFlags),o=s.get(n);return o&&s.set(n,{...o,acknowledged:!0}),{sessionAbortFlags:s}}),clearAbortPrompt:()=>e({abortPromptSessionId:null,abortPromptExpiresAt:null}),armAbortPrompt:(n=5e3)=>{const{currentSessionId:r}=t();if(!r)return null;const s=Date.now()+n;return e({abortPromptSessionId:r,abortPromptExpiresAt:s}),s},clearError:()=>e({error:null}),setSendingNewSessionDraftId:n=>{t().sendingNewSessionDraftId!==n&&e({sendingNewSessionDraftId:n})},markSessionAsPiChamberCreated:n=>e(r=>{const s=new Set(r.webUICreatedSessions);return s.add(n),{webUICreatedSessions:s}}),isPiChamberCreatedSession:n=>t().webUICreatedSessions.has(n),dismissPendingChangesBar:(n,r)=>{const s=new Map(t().pendingChangesBarDismissed);r===null?s.delete(n):s.set(n,r),e({pendingChangesBarDismissed:s})},sendMessage:async(n,r,s,o,i,a,l,d,f,u)=>{const h=u?.target;if(h&&h.runtimeKey!==Y())throw new Error("Message was not sent because the runtime changed.");const m=h?.sessionId??u?.sessionId??(u?.draftSnapshot?null:t().currentSessionId);if(m){const w=new Map(t().pendingChangesBarDismissed);w.delete(m),e({pendingChangesBarDismissed:w})}const g=t().newSessionDraft,x=typeof o=="string"&&o.trim().length>0?o.trim():void 0;if(f==="shell"){let w=h?.sessionId??u?.sessionId??null;if(!w&&(u?.draftSnapshot?.open||g?.open)){const I=await xp({providerID:r,modelID:s,agent:x,variant:d,branchCheckoutReceipt:u?.branchCheckoutReceipt,worktreeCreationReceipt:u?.worktreeCreationReceipt,draftSnapshot:u?.draftSnapshot});if(!I)throw new Error("Failed to create session");w=I.sessionId}if(w??=t().currentSessionId,!w)throw new Error("Select a session to run a shell command.");await qe().runBash(w,n,{excludeFromContext:u?.shellExcludeFromContext===!0});return}if(!h&&!u?.sessionId&&(u?.draftSnapshot?.open||g?.open)){const w=await xp({providerID:r,modelID:s,agent:x,variant:d,initialPrompt:n,branchCheckoutReceipt:u?.branchCheckoutReceipt,worktreeCreationReceipt:u?.worktreeCreationReceipt,draftSnapshot:u?.draftSnapshot,initialInputKind:u?.initialInputKind});if(!w)throw new Error("Failed to create session");const I=w.syntheticParts?.length?[...l||[],...w.syntheticParts]:l;f2(w.sessionId);const E=i?.map(T=>({type:"file",mime:T.mimeType,url:T.dataUrl,filename:T.filename,uploadState:T.uploadState}));await mp({sessionId:w.sessionId,directory:w.directory,content:n,providerID:r,modelID:s,agent:w.agent,agentMentionName:a,variant:d,inputMode:f,files:E,delivery:u?.delivery,operationId:u?.operationId,streamEpoch:u?.streamEpoch,knownEmptyTranscript:!0,additionalParts:I?.map(T=>({text:T.text,synthetic:T.synthetic,files:T.attachments?.map(A=>({type:"file",mime:A.mimeType,url:A.dataUrl,filename:A.filename,uploadState:A.uploadState}))}))});return}const b=h?.sessionId??u?.sessionId??t().currentSessionId,S=b?Lt.getState().getSessionAgentSelection(b):null,y=x||S||void 0;b&&Lt.getState().saveSessionModelSelection(b,r,s),b&&y&&(Lt.getState().saveSessionAgentSelection(b,y),Lt.getState().saveAgentModelForSession(b,y,r,s),Lt.getState().saveAgentModelVariantForSession(b,y,r,s,d));const v=b?ce(h?.directory??u?.directory??t().getDirectoryForSession(b)):null;b&&f2(b);const C=i?.map(w=>({type:"file",mime:w.mimeType,url:w.dataUrl,filename:w.filename,uploadState:w.uploadState}));await mp({runtimeKey:h?.runtimeKey,sessionId:b||"",directory:v,content:n,providerID:r,modelID:s,agent:y,agentMentionName:a,variant:d,inputMode:f,files:C,delivery:u?.delivery,operationId:u?.operationId,streamEpoch:u?.streamEpoch,additionalParts:l?.map(w=>({text:w.text,synthetic:w.synthetic,files:w.attachments?.map(I=>({type:"file",mime:I.mimeType,url:I.dataUrl,filename:I.filename,uploadState:I.uploadState}))}))})},createSession:async(n,r,s,o,i)=>{const a=i?.draftSnapshot??t().newSessionDraft,l=a.targetFolderId;try{const d=r??qe().getState().directory,f=await m_(n,d,s??null,o);if(!f)return null;if(i?.closeDraft!==!1&&t().newSessionDraft===a&&t().closeNewSessionDraft(),l){const u=r||f.directory;u&&Bm.getState().addSessionToFolder(u,l,f.id)}return f}catch(d){return console.error("[session-ui-store] createSession failed",d),null}},deleteSession:async(n,r)=>{const s=await g_(n);return s&&t().currentSessionId===n&&t().openNewSessionDraft(),s},deleteSessions:async(n,r)=>{const s=await y_(n),o=t().currentSessionId;return o&&s.deletedIds.includes(o)&&t().openNewSessionDraft(),s},archiveSession:n=>v_(n),archiveSessions:(n,r)=>x_(n),unarchiveSession:n=>b_(n),unarchiveSessions:(n,r)=>w_(n),updateSessionTitle:async(n,r)=>{await S_(n,r)},shareSession:async n=>C_(),unshareSession:async n=>k_(),revertToMessage:async(n,r)=>{await M_(n,r)},restoreToMessage:async(n,r)=>{await I_(n,r)},handleSlashUndo:async n=>{const r=qe().getState().reducer.bySession.get(n),o=(r?[...r.messages.values()]:[]).filter(l=>l.role==="user");if(o.length===0)return;const i=o[o.length-1];if(!i)return;String(i.text??"").slice(0,50)+((i.text?.length??0)>50?"...":""),await t().revertToMessage(n,i.id);const{toast:a}=await mt(async()=>{const{toast:l}=await import("./vendor-boot-3SaHYVb1.js").then(d=>d.cq);return{toast:l}},__vite__mapDeps([5,1,6]));a.success("Reverted — conversation rewound. Files on disk were not changed.")},handleSlashRedo:async n=>{await E_(n);const{toast:r}=await mt(async()=>{const{toast:s}=await import("./vendor-boot-3SaHYVb1.js").then(o=>o.cq);return{toast:s}},__vite__mapDeps([5,1,6]));r.success("Restored all messages")},forkFromMessage:async(n,r)=>{await __(n,r)},getSessionsByDirectory:n=>{const r=ce(n);return r?Km().filter(o=>Rw(o)===r):[]},getDirectoryForSession:n=>{const r=n===t().currentSessionId?t().currentSessionDirectory:null,s=M2(n,r);if(s)return s;try{return qe().getState().catalog.byId.get(n)?.directory??null}catch{return null}},adoptAuthoritativeSessionDirectory:n=>{const r=n??t().currentSessionId;if(!r||r!==C2()||r!==t().currentSessionId)return;const s=R_(r);s&&(k2(),s!==t().currentSessionDirectory&&e({currentSessionDirectory:s}),Xs(ir(),{sessionId:r,directory:s}))},setSessionDirectory:(n,r)=>{const s=ce(r);n===C2()&&k2(),n===t().currentSessionId&&(e({currentSessionDirectory:s}),Xs(ir(),{sessionId:n,directory:s}))}})),nJ=Object.freeze(Object.defineProperty({__proto__:null,draftBranchCheckoutReceiptMatches:da,getRememberedSessionDirectory:P_,materializeOpenDraftSession:xp,routeMessage:mp,useSessionUIStore:he},Symbol.toStringTag,{value:"Module"}));async function yr(e){let t=null;if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0,method:"clipboard"}}catch(n){t=n instanceof Error?n.message:String(n)}if(typeof document<"u"&&document.body){const n=document.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="-1000px",n.style.left="-1000px",document.body.appendChild(n),n.select(),n.setSelectionRange(0,n.value.length);const r=document.execCommand("copy");if(document.body.removeChild(n),r)return{ok:!0,method:"execCommand"}}return{ok:!1,error:t??"Clipboard access denied in current context"}}async function B_(e,t){if(typeof navigator<"u"&&navigator.clipboard?.write&&typeof ClipboardItem<"u")try{const n={"text/plain":new Blob([e],{type:"text/plain"}),"text/html":new Blob([t],{type:"text/html"})};return typeof ClipboardItem.supports=="function"&&ClipboardItem.supports("text/markdown")&&(n["text/markdown"]=new Blob([e],{type:"text/markdown"})),await navigator.clipboard.write([new ClipboardItem(n)]),{ok:!0,method:"clipboard"}}catch{}return yr(e)}const e1=H.createContext(void 0);function vr(){const e=H.useContext(e1);if(!e)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return e}function Ow(){return H.useContext(e1)}const Hw=async(e,t)=>{if(!kS())throw new Error("Desktop runtime is not available");return dr(e,t)},V_=async e=>{if(xt())try{await Hw("desktop_set_window_title",{title:e})}catch{}},$_=async(e,t)=>{if(xt())try{await Hw("desktop_set_window_theme",{themeMode:e,themeVariant:t})}catch{}},Fw=4.5;function yd(e){if(!e)return null;const t=e.trim();if(t.startsWith("#")){let o=t.slice(1);return(o.length===3||o.length===4)&&(o=o.split("").map(i=>i+i).join("")),/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(o)?{r:parseInt(o.slice(0,2),16),g:parseInt(o.slice(2,4),16),b:parseInt(o.slice(4,6),16),a:o.length===8?parseInt(o.slice(6,8),16)/255:1}:null}const n=t.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?\s*\)$/i);if(!n)return null;const r=n[4],s=r===void 0?1:r.endsWith("%")?parseFloat(r)/100:parseFloat(r);return{r:Number(n[1]),g:Number(n[2]),b:Number(n[3]),a:Math.min(1,Math.max(0,s))}}function bp({r:e,g:t,b:n}){return`#${[e,t,n].map(r=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}function vd(e,t){return{r:e.r*e.a+t.r*(1-e.a),g:e.g*e.a+t.g*(1-e.a),b:e.b*e.a+t.b*(1-e.a),a:1}}function Bw(e,t,n){return{r:Math.round(e.r+(t.r-e.r)*n),g:Math.round(e.g+(t.g-e.g)*n),b:Math.round(e.b+(t.b-e.b)*n),a:1}}function wp({r:e,g:t,b:n}){const r=s=>{const o=s/255;return o<=.03928?o/12.92:((o+.055)/1.055)**2.4};return .2126*r(e)+.7152*r(t)+.0722*r(n)}function z_(e,t){const[n,r]=[wp(e),wp(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)}function Sp(e,t){return Math.min(...t.map(n=>z_(vd(e,n),n)))}function Cp(e){return e.map(yd).filter(t=>t!==null).map(t=>({...t,a:1}))}function U_(e,t,n,r=Fw){const s=yd(e),o=yd(n),i=Cp(t);if(!s||!o||i.length===0||Sp(s,i)>=r)return e;const a=vd(s,i[0]),l=vd(o,i[0]);for(let d=1;d<=20;d+=1){const f=Bw(a,l,d/20);if(Sp(f,i)>=r)return bp(f)}return bp(l)}function q_(e,t,n,{min:r=Fw,maxFade:s=.3}={}){const o=yd(e),i=Cp(t),a=Cp([n])[0];if(!o||!a||i.length===0)return e;const l=vd(o,a);let d=null;for(let f=1;f<=30;f+=1){const u=s*f/30,h=Bw(l,a,u);if(Sp(h,i)<r)break;d=h}return d?bp(d):e}const _f=e=>{if(!e||typeof e!="string")return null;const t=e.trim();if(!t.startsWith("#"))return null;let n=t.slice(1);if((n.length===3||n.length===4)&&(n=n.split("").map(a=>a+a).join("")),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;const r=Number.parseInt(n,16);if(Number.isNaN(r))return null;const s=r>>16&255,o=r>>8&255,i=r&255;return`${s} ${o} ${i}`};function W_(e){const{surface:t}=e.colors,n=U_(t.mutedForeground,[t.background,t.muted,t.elevated],t.foreground);return n===t.mutedForeground?e:{...e,colors:{...e.colors,surface:{...t,mutedForeground:n}}}}class K_{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(t){const n=[],r=W_(t),{surface:s}=r.colors,o=[s.background,s.muted,s.elevated];n.push(...this.generateTailwindVariables(r));const i=q_(s.mutedForeground,o,s.background,{maxFade:.15});return n.push(` --subtle-foreground: ${i} !important;`),n.push(...this.generatePrimaryColors(r.colors.primary)),n.push(...this.generateSurfaceColors(r.colors.surface)),n.push(...this.generateInteractiveColors(r.colors.interactive)),n.push(...this.generateStatusColors(r.colors.status)),n.push(...this.generatePullRequestColors(r)),n.push(...this.generateSyntaxColors(r.colors.syntax)),n.push(...this.generateComponentColors(r.colors,r)),n.push(...this.generateTypographyVariables()),r.config&&n.push(...this.generateConfigVariables(r.config)),n.join(`
|
|
23
|
+
`)}generateTailwindVariables(t){const n=[];n.push(` --background: ${t.colors.surface.background} !important;`),n.push(` --foreground: ${t.colors.surface.foreground} !important;`),n.push(` --muted: ${t.colors.surface.muted} !important;`),n.push(` --muted-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --card: ${t.colors.surface.elevated} !important;`),n.push(` --card-foreground: ${t.colors.surface.elevatedForeground} !important;`),n.push(` --popover: ${t.colors.surface.elevated} !important;`),n.push(` --popover-foreground: ${t.colors.surface.elevatedForeground} !important;`),n.push(` --border: ${t.colors.interactive.border} !important;`),n.push(` --input: ${t.colors.interactive.border} !important;`),n.push(` --primary: ${t.colors.primary.base} !important;`),n.push(` --primary-foreground: ${t.colors.primary.foreground} !important;`),n.push(` --secondary: ${t.colors.surface.muted} !important;`),n.push(` --secondary-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --accent: ${t.colors.surface.subtle} !important;`),n.push(` --accent-foreground: ${t.colors.surface.foreground} !important;`),n.push(` --destructive: ${t.colors.status.error} !important;`),n.push(` --destructive-foreground: ${t.colors.status.errorForeground} !important;`),n.push(` --ring: ${t.colors.interactive.focusRing} !important;`);const r=_f(t.colors.surface.muted),s=_f(t.colors.surface.subtle),o=_f(t.colors.interactive.border);n.push(` --sidebar-base: ${t.colors.surface.muted} !important;`),r&&n.push(` --sidebar-base-rgb: ${r} !important;`),n.push(" --sidebar: var(--sidebar-base) !important;"),n.push(` --sidebar-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --sidebar-primary: ${t.colors.primary.base} !important;`),n.push(` --sidebar-primary-foreground: ${t.colors.primary.foreground} !important;`),n.push(` --sidebar-accent-base: ${t.colors.surface.subtle} !important;`),s&&n.push(` --sidebar-accent-base-rgb: ${s} !important;`),n.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),n.push(` --sidebar-accent-foreground: ${t.colors.surface.foreground} !important;`),n.push(` --sidebar-border: ${t.colors.interactive.border} !important;`),o&&n.push(` --sidebar-border-rgb: ${o} !important;`),n.push(` --sidebar-ring: ${t.colors.interactive.focusRing} !important;`);const i=t.metadata.variant==="dark",a=i?.15:.5,l=i?.1:.3;if(r)n.push(` --sidebar-overlay-strong: rgb(${r} / ${a}) !important;`),n.push(` --sidebar-overlay-soft: rgb(${r} / ${l}) !important;`);else{const d=t.colors.surface.muted;n.push(` --sidebar-overlay-strong: ${this.opacity(d,a)} !important;`),n.push(` --sidebar-overlay-soft: ${this.opacity(d,l)} !important;`)}return t.colors.charts?.series&&Array.isArray(t.colors.charts.series)&&t.colors.charts.series.forEach((d,f)=>{n.push(` --chart-${f+1}: ${d};`)}),t.colors.loading?(n.push(` --loading-spinner: ${t.colors.loading.spinner||t.colors.primary.base};`),n.push(` --loading-spinner-track: ${t.colors.loading.spinnerTrack||t.colors.surface.muted};`)):(n.push(` --loading-spinner: ${t.colors.primary.base};`),n.push(` --loading-spinner-track: ${t.colors.surface.muted};`)),n}apply(t){const n=this.generate(t),r=document.createElement("style");r.id="pichamber-theme-variables";let s="";t.metadata.variant==="dark"?(s=`:root {
|
|
24
|
+
${n}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
.dark {
|
|
28
|
+
${n}
|
|
29
|
+
}`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(s=`:root {
|
|
30
|
+
${n}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
:root:not(.dark) {
|
|
34
|
+
${n}
|
|
35
|
+
}`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),r.textContent=s;const o=document.getElementById("pichamber-theme-variables");o&&o.remove(),document.head.appendChild(r),document.documentElement.setAttribute("data-theme",t.metadata.variant)}generatePrimaryColors(t){const n=[];return n.push(` --primary-base: ${t.base};`),n.push(` --primary-hover: ${t.hover||this.darken(t.base,10)};`),n.push(` --primary-active: ${t.active||this.darken(t.base,20)};`),n.push(` --primary-foreground: ${t.foreground||"#ffffff"};`),n.push(` --primary-muted: ${t.muted||this.opacity(t.base,.5)};`),n.push(` --primary-emphasis: ${t.emphasis||this.lighten(t.base,10)};`),n}generateSurfaceColors(t){const n=[];return n.push(` --surface-background: ${t.background};`),n.push(` --surface-foreground: ${t.foreground};`),n.push(` --surface-muted: ${t.muted};`),n.push(` --surface-muted-foreground: ${t.mutedForeground};`),n.push(` --surface-elevated: ${t.elevated};`),n.push(` --surface-elevated-foreground: ${t.elevatedForeground};`),n.push(` --surface-overlay: ${t.overlay};`),n.push(` --surface-subtle: ${t.subtle};`),n}generateInteractiveColors(t){const n=[];return n.push(` --interactive-border: ${t.border};`),n.push(` --interactive-border-hover: ${t.borderHover};`),n.push(` --interactive-border-focus: ${t.borderFocus};`),n.push(` --interactive-selection: ${t.selection};`),n.push(` --interactive-selection-foreground: ${t.selectionForeground};`),n.push(` --interactive-focus: ${t.focus};`),n.push(` --interactive-focus-ring: ${t.focusRing};`),n.push(` --interactive-cursor: ${t.cursor};`),n.push(` --interactive-hover: ${t.hover};`),n.push(` --interactive-active: ${t.active};`),n}generateStatusColors(t){const n=[];return n.push(` --status-error: ${t.error};`),n.push(` --status-error-foreground: ${t.errorForeground};`),n.push(` --status-error-background: ${t.errorBackground};`),n.push(` --status-error-border: ${t.errorBorder};`),n.push(` --status-warning: ${t.warning};`),n.push(` --status-warning-foreground: ${t.warningForeground};`),n.push(` --status-warning-background: ${t.warningBackground};`),n.push(` --status-warning-border: ${t.warningBorder};`),n.push(` --status-success: ${t.success};`),n.push(` --status-success-foreground: ${t.successForeground};`),n.push(` --status-success-background: ${t.successBackground};`),n.push(` --status-success-border: ${t.successBorder};`),n.push(` --status-info: ${t.info};`),n.push(` --status-info-foreground: ${t.infoForeground};`),n.push(` --status-info-background: ${t.infoBackground};`),n.push(` --status-info-border: ${t.infoBorder};`),n}generatePullRequestColors(t){const n=[],r=t.colors.pr;return n.push(` --pr-open: ${r?.open||t.colors.status.success};`),n.push(` --pr-draft: ${r?.draft||t.colors.surface.mutedForeground};`),n.push(` --pr-blocked: ${r?.blocked||t.colors.status.warning};`),n.push(` --pr-merged: ${r?.merged||(t.metadata.variant==="dark"?"#8957e5":"#8250df")};`),n.push(` --pr-closed: ${r?.closed||t.colors.status.error};`),n}generateSyntaxColors(t){const n=[];n.push(` --syntax-background: ${t.base.background};`),n.push(` --syntax-foreground: ${t.base.foreground};`),n.push(` --syntax-comment: ${t.base.comment};`),n.push(` --syntax-keyword: ${t.base.keyword};`),n.push(` --syntax-string: ${t.base.string};`),n.push(` --syntax-number: ${t.base.number};`),n.push(` --syntax-function: ${t.base.function};`),n.push(` --syntax-variable: ${t.base.variable};`),n.push(` --syntax-type: ${t.base.type};`),n.push(` --syntax-operator: ${t.base.operator};`);const r=this.generateSyntaxTokens(t);for(const[s,o]of Object.entries(r))n.push(` --syntax-${this.kebabCase(s)}: ${o};`);return n}generateSyntaxTokens(t){const n=t.base,r=t.tokens||{};return{commentDoc:r.commentDoc||this.lighten(n.comment,10),stringEscape:r.stringEscape||this.darken(n.string,20),stringInterpolation:r.stringInterpolation||n.variable,stringRegex:r.stringRegex||this.adjustHue(n.string,15),keywordControl:r.keywordControl||n.keyword,keywordOperator:r.keywordOperator||n.operator,keywordImport:r.keywordImport||this.lighten(n.keyword,10),keywordReturn:r.keywordReturn||this.emphasize(n.keyword),functionCall:r.functionCall||this.lighten(n.function,5),functionBuiltin:r.functionBuiltin||this.darken(n.function,10),method:r.method||n.function,methodCall:r.methodCall||this.lighten(n.function,5),variableBuiltin:r.variableBuiltin||this.emphasize(n.variable),variableProperty:r.variableProperty||this.lighten(n.variable,10),variableReadonly:r.variableReadonly||n.number,parameter:r.parameter||n.variable,typePrimitive:r.typePrimitive||this.darken(n.type,10),typeInterface:r.typeInterface||n.type,className:r.className||this.emphasize(n.type),enum:r.enum||n.type,boolean:r.boolean||n.number,null:r.null||this.opacity(n.number,.7),constant:r.constant||n.number,punctuation:r.punctuation||this.opacity(n.foreground,.7),delimiter:r.delimiter||this.opacity(n.foreground,.8),bracket:r.bracket||n.foreground,tag:r.tag||n.keyword,tagAttribute:r.tagAttribute||n.variable,tagAttributeValue:r.tagAttributeValue||n.string,tagBracket:r.tagBracket||this.opacity(n.foreground,.8),decorator:r.decorator||n.function,annotation:r.annotation||n.function,namespace:r.namespace||this.opacity(n.type,.8),module:r.module||this.opacity(n.type,.8),...r}}generateComponentColors(t,n){const r=[];return t.markdown?r.push(...this.generateMarkdownColors(t.markdown,n)):r.push(...this.generateDefaultMarkdownColors(n)),t.chat?r.push(...this.generateChatColors(t.chat,n)):r.push(...this.generateDefaultChatColors(n)),t.tools?r.push(...this.generateToolColors(t.tools,n)):r.push(...this.generateDefaultToolColors(n)),r}generateMarkdownColors(t,n){const r=[],s=n.colors.primary.base,o=n.colors.chat?.background||n.colors.surface.background;return r.push(` --markdown-heading1: ${t.heading1||s};`),r.push(` --markdown-heading2: ${t.heading2||this.opacity(s,.9)};`),r.push(` --markdown-heading3: ${t.heading3||this.opacity(s,.8)};`),r.push(` --markdown-heading4: ${t.heading4||n.colors.surface.foreground};`),r.push(` --markdown-link: ${t.link||s};`),r.push(` --markdown-link-hover: ${t.linkHover||n.colors.primary.hover||this.darken(s,10)};`),r.push(` --markdown-inline-code: ${t.inlineCode||n.colors.syntax.base.string};`),r.push(` --markdown-inline-code-bg: ${t.inlineCodeBackground||o};`),r.push(` --markdown-blockquote: ${t.blockquote||n.colors.surface.mutedForeground};`),r.push(` --markdown-blockquote-border: ${t.blockquoteBorder||n.colors.interactive.border};`),r.push(` --markdown-list-marker: ${t.listMarker||this.opacity(s,.6)};`),r.push(` --markdown-bold: ${t.bold||n.colors.surface.foreground};`),r.push(` --markdown-italic: ${t.italic||this.opacity(n.colors.surface.foreground,.9)};`),r.push(` --markdown-strikethrough: ${t.strikethrough||n.colors.surface.mutedForeground};`),r.push(` --markdown-hr: ${t.hr||n.colors.interactive.border};`),r}generateDefaultMarkdownColors(t){const n=[],r=t.colors.primary.base,s=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${r};`),n.push(` --markdown-heading2: ${this.opacity(r,.9)};`),n.push(` --markdown-heading3: ${this.opacity(r,.8)};`),n.push(` --markdown-heading4: ${t.colors.surface.foreground};`),n.push(` --markdown-link: ${r};`),n.push(` --markdown-link-hover: ${t.colors.primary.hover||this.darken(r,10)};`),n.push(` --markdown-inline-code: ${t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${s};`),n.push(` --markdown-blockquote: ${t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${this.opacity(r,.6)};`),n.push(` --markdown-bold: ${t.colors.surface.foreground};`),n.push(` --markdown-italic: ${this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${t.colors.interactive.border};`),n}generateChatColors(t,n){const r=[],s=t.background||n.colors.surface.background;return r.push(` --chat-background: ${s};`),r.push(` --chat-user-message: ${t.userMessage||n.colors.surface.foreground};`),r.push(` --chat-user-message-bg: ${t.userMessageBackground||n.colors.surface.elevated};`),r.push(` --chat-assistant-message: ${t.assistantMessage||n.colors.surface.foreground};`),r.push(` --chat-assistant-message-bg: ${t.assistantMessageBackground||n.colors.surface.muted};`),r.push(` --chat-timestamp: ${t.timestamp||n.colors.surface.mutedForeground};`),r.push(` --chat-divider: ${t.divider||n.colors.interactive.border};`),r.push(` --chat-typing: ${t.typing||n.colors.surface.mutedForeground};`),r}generateDefaultChatColors(t){const n=[];return n.push(` --chat-background: ${t.colors.surface.background};`),n.push(` --chat-user-message: ${t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${t.colors.surface.muted};`),n.push(` --chat-timestamp: ${t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${t.colors.interactive.border};`),n.push(` --chat-typing: ${t.colors.surface.mutedForeground};`),n}generateToolColors(t,n){const r=[];return r.push(` --tools-background: ${t?.background||this.opacity(n.colors.surface.muted,.2)};`),r.push(` --tools-border: ${t?.border||this.opacity(n.colors.interactive.border,.3)};`),r.push(` --tools-header-hover: ${t?.headerHover||this.opacity(n.colors.surface.muted,.3)};`),r.push(` --tools-icon: ${t?.icon||n.colors.surface.mutedForeground};`),r.push(` --tools-title: ${t?.title||n.colors.surface.foreground};`),r.push(` --tools-description: ${t?.description||"var(--subtle-foreground)"};`),t?.edit?(r.push(` --tools-edit-added: ${t.edit.added||n.colors.status.success};`),r.push(` --tools-edit-added-bg: ${t.edit.addedBackground||n.colors.status.successBackground};`),r.push(` --tools-edit-removed: ${t.edit.removed||n.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${t.edit.removedBackground||n.colors.status.errorBackground};`),r.push(` --tools-edit-modified: ${t.edit.modified||n.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${t.edit.modifiedBackground||n.colors.status.infoBackground};`),r.push(` --tools-edit-line-number: ${t.edit.lineNumber||this.opacity(n.colors.surface.mutedForeground,.6)};`)):(r.push(` --tools-edit-added: ${n.colors.status.success};`),r.push(` --tools-edit-added-bg: ${n.colors.status.successBackground};`),r.push(` --tools-edit-removed: ${n.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${n.colors.status.errorBackground};`),r.push(` --tools-edit-modified: ${n.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${n.colors.status.infoBackground};`),r.push(` --tools-edit-line-number: ${this.opacity(n.colors.surface.mutedForeground,.6)};`)),r}generateDefaultToolColors(t){const n=[];return n.push(` --tools-background: ${this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${t.colors.surface.foreground};`),n.push(" --tools-description: var(--subtle-foreground);"),n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.successBackground),.15)};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.errorBackground),.15)};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.infoBackground),.15)};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`),n}generateConfigVariables(t){const n=[];return t&&(t.fonts&&(t.fonts.sans&&(n.push(` --font-sans: ${t.fonts.sans};`),n.push(` --font-family-sans: ${t.fonts.sans};`)),t.fonts.mono&&(n.push(` --font-mono: ${t.fonts.mono};`),n.push(` --font-family-mono: ${t.fonts.mono};`)),t.fonts.heading&&n.push(` --font-heading: ${t.fonts.heading};`)),t.transitions&&(t.transitions.fast&&n.push(` --transition-fast: ${t.transitions.fast};`),t.transitions.normal&&n.push(` --transition-normal: ${t.transitions.normal};`),t.transitions.slow&&n.push(` --transition-slow: ${t.transitions.slow};`))),n}generateTypographyVariables(){const t=[],n=MS;return t.push(" /* Semantic Typography Variables */"),t.push(" --ui-regular-font-weight: 400;"),t.push(" /* Markdown content - all markdown elements use same size */"),t.push(` --text-markdown: ${n.markdown};`),t.push(" /* Code content - all code elements use same size */"),t.push(` --text-code: ${n.code};`),t.push(" /* UI headers - dialog titles, panel headers */"),t.push(` --text-ui-header: ${n.uiHeader};`),t.push(" /* UI labels - buttons, menus, navigation */"),t.push(` --text-ui-label: ${n.uiLabel};`),t.push(" /* Metadata - timestamps, status, helper text */"),t.push(` --text-meta: ${n.meta};`),t.push(" /* Micro text - badges, shortcuts, indicators */"),t.push(` --text-micro: ${n.micro};`),t.push(" /* Settings page titles - larger than section headers */"),t.push(` --text-settings-page-title: ${n.settingsPageTitle};`),t.push(" /* Heading line height and letter spacing */"),t.push(" --h1-line-height: 1.25rem;"),t.push(" --h2-line-height: 1.25rem;"),t.push(" --h3-line-height: 1.5rem;"),t.push(" --h4-line-height: 1.5rem;"),t.push(" --h5-line-height: 1.5rem;"),t.push(" --h6-line-height: 1.5rem;"),t.push(" --h1-letter-spacing: -0.025em;"),t.push(" --h2-letter-spacing: -0.02em;"),t.push(" --h3-letter-spacing: -0.015em;"),t.push(" --h4-letter-spacing: -0.01em;"),t.push(" --h5-letter-spacing: 0;"),t.push(" --h6-letter-spacing: 0.01em;"),t.push(" /* UI element line height and letter spacing */"),t.push(" --ui-button-line-height: 1.375rem;"),t.push(" --ui-button-letter-spacing: 0.02em;"),t.push(" --ui-button-font-weight: 500;"),t.push(" --ui-label-line-height: 1rem;"),t.push(" --ui-label-letter-spacing: 0.03em;"),t.push(" --ui-label-font-weight: 500;"),t.push(" --ui-caption-line-height: 1rem;"),t.push(" --ui-caption-letter-spacing: 0.025em;"),t.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Markdown line height and letter spacing */"),t.push(" --markdown-body-line-height: 1.5rem;"),t.push(" --markdown-body-letter-spacing: 0;"),t.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-h1-line-height: 1.25rem;"),t.push(" --markdown-h1-letter-spacing: -0.025em;"),t.push(" --markdown-h2-line-height: 1.25rem;"),t.push(" --markdown-h2-letter-spacing: -0.02em;"),t.push(" --markdown-h3-line-height: 1.5rem;"),t.push(" --markdown-h3-letter-spacing: -0.015em;"),t.push(" --markdown-h4-line-height: 1.5rem;"),t.push(" --markdown-h4-letter-spacing: -0.01em;"),t.push(" --markdown-h5-line-height: 1.5rem;"),t.push(" --markdown-h5-letter-spacing: 0;"),t.push(" --markdown-h6-line-height: 1.5rem;"),t.push(" --markdown-h6-letter-spacing: 0.01em;"),t.push(" --markdown-list-line-height: 1.375rem;"),t.push(" --markdown-code-block-line-height: 1rem;"),t.push(" --ui-button-small-line-height: 1.25rem;"),t.push(" --ui-button-small-letter-spacing: 0.02em;"),t.push(" --ui-button-small-font-weight: 500;"),t.push(" --markdown-body-small-line-height: 1.375rem;"),t.push(" --markdown-body-small-letter-spacing: 0;"),t.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-button-large-line-height: 1.5rem;"),t.push(" --ui-button-large-letter-spacing: 0.02em;"),t.push(" --ui-button-large-font-weight: 500;"),t.push(" --markdown-body-large-line-height: 1.625rem;"),t.push(" --markdown-body-large-letter-spacing: 0;"),t.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Code line height and letter spacing */"),t.push(" --code-inline-line-height: 1rem;"),t.push(" --code-inline-letter-spacing: 0;"),t.push(" --code-inline-font-weight: 400;"),t.push(" --code-block-line-height: round(1.4rem, 1px);"),t.push(" --code-block-letter-spacing: 0;"),t.push(" --code-block-font-weight: 400;"),t.push(" --code-line-numbers-line-height: 1.25rem;"),t.push(" --code-line-numbers-letter-spacing: 0;"),t.push(" --code-line-numbers-font-weight: 400;"),t.push(" /* Additional UI element line height and letter spacing */"),t.push(" --ui-badge-line-height: 1rem;"),t.push(" --ui-badge-letter-spacing: 0.025em;"),t.push(" --ui-badge-font-weight: 500;"),t.push(" --ui-tooltip-line-height: 1rem;"),t.push(" --ui-tooltip-letter-spacing: 0.025em;"),t.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-input-line-height: 1.375rem;"),t.push(" --ui-input-letter-spacing: 0.02em;"),t.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-helper-text-line-height: 1rem;"),t.push(" --ui-helper-text-letter-spacing: 0.025em;"),t.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Additional markdown line height and letter spacing */"),t.push(" --markdown-blockquote-line-height: 1.5rem;"),t.push(" --markdown-blockquote-letter-spacing: 0;"),t.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-list-letter-spacing: 0;"),t.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-link-line-height: 1.5rem;"),t.push(" --markdown-link-letter-spacing: 0;"),t.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-code-line-height: round(1.35em, 1px);"),t.push(" --markdown-code-letter-spacing: 0;"),t.push(" --markdown-code-font-weight: 400;"),t.push(" --markdown-code-block-letter-spacing: 0;"),t.push(" --markdown-code-block-font-weight: 400;"),t}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(t,n){return t.startsWith("#")?`${t}${Math.round(n*255).toString(16).padStart(2,"0")}`:t.startsWith("rgb")?t.replace("rgb","rgba").replace(")",`, ${n})`):t}removeTransparency(t){return t.startsWith("#")?t.length===9?t.slice(0,7):t.length===5?t.slice(0,4):t:t.startsWith("rgba")?t.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):t}addTransparency(t,n){if(t.startsWith("#")){const r=t.slice(1);if(r.length===3){const s=parseInt(r[0]+r[0],16),o=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16);return`rgba(${s}, ${o}, ${i}, ${n})`}else if(r.length===6){const s=parseInt(r.slice(0,2),16),o=parseInt(r.slice(2,4),16),i=parseInt(r.slice(4,6),16);return`rgba(${s}, ${o}, ${i}, ${n})`}}return t.startsWith("rgb")?t.replace("rgb","rgba").replace(")",`, ${n})`):t}darken(t,n){if(t.startsWith("#")){const r=parseInt(t.slice(1),16),s=Math.round(2.55*n),o=(r>>16)-s,i=(r>>8&255)-s,a=(r&255)-s;return"#"+(16777216+(o<255?o<0?0:o:255)*65536+(i<255?i<0?0:i:255)*256+(a<255?a<0?0:a:255)).toString(16).slice(1)}return t}lighten(t,n){if(t.startsWith("#")){const r=parseInt(t.slice(1),16),s=Math.round(2.55*n),o=(r>>16)+s,i=(r>>8&255)+s,a=(r&255)+s;return"#"+(16777216+(o<255?o<0?0:o:255)*65536+(i<255?i<0?0:i:255)*256+(a<255?a<0?0:a:255)).toString(16).slice(1)}return t}adjustHue(t,n){return this.lighten(t,n/10)}emphasize(t){return this.lighten(t,15)}kebabCase(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const E2=(e,t)=>t.reduce((n,r)=>n&&typeof n=="object"?n[r]:void 0,e),G_=e=>typeof e=="string"&&e.trim().length>0,_2=e=>{if(!e||typeof e!="object")return!1;const t=[["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"]];for(const r of t)if(!G_(E2(e,r)))return!1;const n=E2(e,["metadata","variant"]);return n==="light"||n==="dark"},Z_=_S,Y_=ES,X_=e=>TS(e==="dark"),J_=typeof window<"u"?p.useLayoutEffect:p.useEffect,Q_=()=>{if(typeof document>"u")return;const e=document.documentElement;e.classList.add("oc-theme-switching");const t=window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{e.classList.remove("oc-theme-switching")})});return()=>{window.cancelAnimationFrame(t),e.classList.remove("oc-theme-switching")}},ej=e=>{let t=Z_,n=Y_,r="system";if(typeof window<"u"){const s=localStorage.getItem("themeMode"),o=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),a=localStorage.getItem("useSystemTheme"),l=localStorage.getItem("selectedThemeId"),d=localStorage.getItem("selectedThemeVariant");if(s==="light"||s==="dark"||s==="system")r=s;else if(a!==null){if(a==="true")r="system";else if(l){const u=qg(l);u&&(r=u.metadata.variant==="dark"?"dark":"light",u.metadata.variant==="dark"?n=u.metadata.id:t=u.metadata.id)}}else(d==="light"||d==="dark")&&(r=d);typeof o=="string"&&o.trim().length>0&&(t=o.trim()),typeof i=="string"&&i.trim().length>0&&(n=i.trim())}if(e){const s=qg(e);s&&(s.metadata.variant==="light"?t=s.metadata.id:n=s.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function rJ({children:e,defaultThemeId:t}){const n=H.useMemo(()=>new K_,[]),[r,s]=H.useState(()=>ej(t)),[o,i]=H.useState(()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches),[a,l]=H.useState([]),[d,f]=H.useState([]),[u,h]=H.useState(!1),m=H.useMemo(()=>xt(),[]),g=H.useRef(0),x=H.useMemo(()=>{const _=[],M=new Set,L=O=>{const N=O.metadata.id;M.has(N)||(M.add(N),_.push(O))};return a.forEach(L),d.forEach(L),IS.forEach(L),_},[a,d]);H.useEffect(()=>{const _=M=>{const L=M.detail;if(!_2(L))return;const O=jS(L);f(N=>{const D=N.findIndex(z=>z.metadata.id===O.metadata.id);if(D<0)return[...N,O];const W=[...N];return W[D]=O,W})};return window.addEventListener("pichamber:theme-hmr",_),()=>window.removeEventListener("pichamber:theme-hmr",_)},[]);const b=H.useCallback(_=>x.find(M=>M.metadata.id===_),[x]),S=H.useCallback((_,M)=>{const L=b(_);return L&&L.metadata.variant===M?L:x.find(N=>N.metadata.variant===M)??X_(M)},[x,b]),y=H.useMemo(()=>r.themeMode==="light"?S(r.lightThemeId,"light"):r.themeMode==="dark"||o?S(r.darkThemeId,"dark"):S(r.lightThemeId,"light"),[S,r,o]),v=H.useCallback(async()=>{if(typeof window>"u")return;const _=Y(),M=++g.current;h(!0);try{const L=await Rt("/api/pi/themes",{method:"GET",credentials:Jo()?"omit":"include",headers:{Accept:"application/json"}});if(L.status===401||!L.ok)return;const O=await L.json();if(M!==g.current||_!==Y())return;const D=(Array.isArray(O?.themes)?O.themes:[]).filter(_2);l(D)}catch{}finally{M===g.current&&_===Y()&&h(!1)}},[]);H.useEffect(()=>{v()},[v]),H.useEffect(()=>en(_=>{_.runtimeKey!==_.previousRuntimeKey&&(g.current+=1,l([]),h(!1),v())}),[v]);const C=H.useCallback(_=>{if(typeof document>"u")return;const M=_.colors.surface.background;document.body.style.backgroundColor=M;let L=document.querySelector('meta[name="theme-color"]');L||(L=document.createElement("meta"),L.setAttribute("name","theme-color"),document.head.appendChild(L)),L.setAttribute("content",M);const O=_.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let N=document.querySelector(`meta[name="theme-color"][media="${O}"]`);N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),N.setAttribute("media",O),document.head.appendChild(N)),N.setAttribute("content",M)},[]),w=H.useRef(!1);J_(()=>{if(typeof window>"u")return;const _=w.current?Q_():void 0;w.current=!0,n.apply(y),C(y);const M=document.documentElement;return M.classList.remove("light","dark"),M.classList.add(y.metadata.variant),_},[n,y,C]),H.useEffect(()=>{if(r.themeMode!=="system"||typeof window>"u")return;const _=window.matchMedia("(prefers-color-scheme: dark)"),M=L=>{i(L.matches)};return i(_.matches),_.addEventListener("change",M),()=>_.removeEventListener("change",M)},[r.themeMode]),H.useEffect(()=>{if(typeof window>"u")return;localStorage.setItem("themeMode",r.themeMode),localStorage.setItem("lightThemeId",r.lightThemeId),localStorage.setItem("darkThemeId",r.darkThemeId),localStorage.setItem("useSystemTheme",String(r.themeMode==="system")),localStorage.setItem("selectedThemeId",y.metadata.id),localStorage.setItem("selectedThemeVariant",y.metadata.variant==="light"?"light":"dark");const _=S(r.lightThemeId,"light"),M=S(r.darkThemeId,"dark");localStorage.setItem("splashBgLight",_.colors.surface.background),localStorage.setItem("splashFgLight",_.colors.surface.foreground),localStorage.setItem("splashBgDark",M.colors.surface.background),localStorage.setItem("splashFgDark",M.colors.surface.foreground)},[r,y,S]),H.useEffect(()=>{if(typeof window>"u")return;const _=M=>{M.storageArea===window.localStorage&&(M.key!=="themeMode"&&M.key!=="lightThemeId"&&M.key!=="darkThemeId"||s(L=>{const O=localStorage.getItem("themeMode"),N=O==="light"||O==="dark"||O==="system"?O:L.themeMode,D=localStorage.getItem("lightThemeId"),W=typeof D=="string"&&D.trim().length>0?D.trim():L.lightThemeId,z=localStorage.getItem("darkThemeId"),X=typeof z=="string"&&z.trim().length>0?z.trim():L.darkThemeId;return N===L.themeMode&&W===L.lightThemeId&&X===L.darkThemeId?L:{themeMode:N,lightThemeId:W,darkThemeId:X}}))};return window.addEventListener("storage",_),()=>window.removeEventListener("storage",_)},[]),H.useEffect(()=>{const _=S(r.lightThemeId,"light"),M=S(r.darkThemeId,"dark");$r({themeId:y.metadata.id,themeVariant:y.metadata.variant==="light"?"light":"dark",useSystemTheme:r.themeMode==="system",lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,splashBgLight:_.colors.surface.background,splashFgLight:_.colors.surface.foreground,splashBgDark:M.colors.surface.background,splashFgDark:M.colors.surface.foreground})},[y.metadata.id,y.metadata.variant,S,r.themeMode,r.lightThemeId,r.darkThemeId]),H.useEffect(()=>{m&&(async()=>await $_(r.themeMode,y.metadata.variant))()},[y.metadata.variant,m,r.themeMode]),H.useEffect(()=>{if(typeof window>"u")return;const _=M=>{const L=M.detail;L&&s(O=>{let N=O.themeMode;L.useSystemTheme===!0?N="system":L.useSystemTheme===!1&&(L.themeVariant==="dark"||L.themeVariant==="light")&&(N=L.themeVariant);let D=O.lightThemeId;typeof L.lightThemeId=="string"&&L.lightThemeId.length>0&&(D=L.lightThemeId.trim());let W=O.darkThemeId;return typeof L.darkThemeId=="string"&&L.darkThemeId.length>0&&(W=L.darkThemeId.trim()),N===O.themeMode&&D===O.lightThemeId&&W===O.darkThemeId?O:{themeMode:N,lightThemeId:D,darkThemeId:W}})};return window.addEventListener("pichamber:settings-synced",_),()=>window.removeEventListener("pichamber:settings-synced",_)},[]);const I=H.useCallback(_=>{const M=x.find(L=>L.metadata.id===_);M&&s(L=>M.metadata.variant==="dark"?L.darkThemeId===M.metadata.id&&L.themeMode==="dark"?L:{...L,darkThemeId:M.metadata.id,themeMode:"dark"}:L.lightThemeId===M.metadata.id&&L.themeMode==="light"?L:{...L,lightThemeId:M.metadata.id,themeMode:"light"})},[x]),E=H.useCallback(_=>{r.themeMode!==_&&(s(M=>({...M,themeMode:_})),$r({themeVariant:_==="system"?y.metadata.variant:_,useSystemTheme:_==="system"}))},[y.metadata.variant,r.themeMode]),T=H.useCallback(_=>{if(_){s(L=>L.themeMode==="system"?L:{...L,themeMode:"system"});return}const M=y.metadata.variant==="dark"?"dark":"light";s(L=>L.themeMode===M?L:{...L,themeMode:M})},[y.metadata.variant]),A=H.useCallback(_=>{const M=x.find(L=>L.metadata.id===_&&L.metadata.variant==="light");M&&s(L=>L.lightThemeId===M.metadata.id?L:{...L,lightThemeId:M.metadata.id})},[x]),j=H.useCallback(_=>{const M=x.find(L=>L.metadata.id===_&&L.metadata.variant==="dark");M&&s(L=>L.darkThemeId===M.metadata.id?L:{...L,darkThemeId:M.metadata.id})},[x]),k={currentTheme:y,availableThemes:x,setTheme:I,customThemesLoading:u,reloadCustomThemes:v,isSystemPreference:r.themeMode==="system",setSystemPreference:T,themeMode:r.themeMode,setThemeMode:E,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:A,setDarkThemePreference:j};return c.jsx(e1.Provider,{value:k,children:e})}let zc=null;const sJ=()=>{if(typeof window>"u"||zc)return()=>{};let e={showDeletionDialog:re.getState().showDeletionDialog,nativeNotificationsEnabled:re.getState().nativeNotificationsEnabled,notificationMode:re.getState().notificationMode,notifyOnCompletion:re.getState().notifyOnCompletion,notifyOnError:re.getState().notifyOnError,notifyOnInputNeeded:re.getState().notifyOnInputNeeded,summarizeLastMessage:re.getState().summarizeLastMessage,summaryThreshold:re.getState().summaryThreshold,summaryLength:re.getState().summaryLength,maxLastMessageLength:re.getState().maxLastMessageLength,autoDeleteEnabled:re.getState().autoDeleteEnabled,autoSaveEnabled:re.getState().autoSaveEnabled,autoDeleteAfterDays:re.getState().autoDeleteAfterDays,sessionRetentionAction:re.getState().sessionRetentionAction,fontSize:re.getState().fontSize,terminalFontSize:re.getState().terminalFontSize,terminalShell:re.getState().terminalShell,terminalLoginShells:re.getState().terminalLoginShells,editorFontSize:re.getState().editorFontSize,uiFont:re.getState().uiFont,monoFont:re.getState().monoFont,padding:re.getState().padding,cornerRadius:re.getState().cornerRadius,inputBarOffset:re.getState().inputBarOffset,mobileKeyboardMode:re.getState().mobileKeyboardMode,diffLayoutPreference:re.getState().diffLayoutPreference,gitChangesViewMode:re.getState().gitChangesViewMode};const t=re.subscribe(s=>{const o={showDeletionDialog:s.showDeletionDialog,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode,notifyOnCompletion:s.notifyOnCompletion,notifyOnError:s.notifyOnError,notifyOnInputNeeded:s.notifyOnInputNeeded,summarizeLastMessage:s.summarizeLastMessage,summaryThreshold:s.summaryThreshold,summaryLength:s.summaryLength,maxLastMessageLength:s.maxLastMessageLength,autoDeleteEnabled:s.autoDeleteEnabled,autoSaveEnabled:s.autoSaveEnabled,autoDeleteAfterDays:s.autoDeleteAfterDays,sessionRetentionAction:s.sessionRetentionAction,fontSize:s.fontSize,terminalFontSize:s.terminalFontSize,terminalShell:s.terminalShell,terminalLoginShells:s.terminalLoginShells,editorFontSize:s.editorFontSize,uiFont:s.uiFont,monoFont:s.monoFont,padding:s.padding,cornerRadius:s.cornerRadius,inputBarOffset:s.inputBarOffset,mobileKeyboardMode:s.mobileKeyboardMode,diffLayoutPreference:s.diffLayoutPreference,gitChangesViewMode:s.gitChangesViewMode},i={};o.showDeletionDialog!==e.showDeletionDialog&&(i.showDeletionDialog=o.showDeletionDialog),o.nativeNotificationsEnabled!==e.nativeNotificationsEnabled&&(i.nativeNotificationsEnabled=o.nativeNotificationsEnabled),o.notificationMode!==e.notificationMode&&(i.notificationMode=o.notificationMode),o.notifyOnCompletion!==e.notifyOnCompletion&&(i.notifyOnCompletion=o.notifyOnCompletion),o.notifyOnError!==e.notifyOnError&&(i.notifyOnError=o.notifyOnError),o.notifyOnInputNeeded!==e.notifyOnInputNeeded&&(i.notifyOnInputNeeded=o.notifyOnInputNeeded),o.summarizeLastMessage!==e.summarizeLastMessage&&(i.summarizeLastMessage=o.summarizeLastMessage),o.summaryThreshold!==e.summaryThreshold&&(i.summaryThreshold=o.summaryThreshold),o.summaryLength!==e.summaryLength&&(i.summaryLength=o.summaryLength),o.maxLastMessageLength!==e.maxLastMessageLength&&(i.maxLastMessageLength=o.maxLastMessageLength),o.autoDeleteEnabled!==e.autoDeleteEnabled&&(i.autoDeleteEnabled=o.autoDeleteEnabled),o.autoSaveEnabled!==e.autoSaveEnabled&&(i.autoSaveEnabled=o.autoSaveEnabled),o.autoDeleteAfterDays!==e.autoDeleteAfterDays&&(i.autoDeleteAfterDays=o.autoDeleteAfterDays),o.sessionRetentionAction!==e.sessionRetentionAction&&(i.sessionRetentionAction=o.sessionRetentionAction),o.fontSize!==e.fontSize&&(i.fontSize=o.fontSize),o.terminalFontSize!==e.terminalFontSize&&(i.terminalFontSize=o.terminalFontSize),o.terminalShell!==e.terminalShell&&(i.terminalShell=o.terminalShell),o.terminalLoginShells!==e.terminalLoginShells&&(i.terminalLoginShells=o.terminalLoginShells),o.editorFontSize!==e.editorFontSize&&(i.editorFontSize=o.editorFontSize),o.uiFont!==e.uiFont&&(i.uiFont=o.uiFont),o.monoFont!==e.monoFont&&(i.monoFont=o.monoFont),o.padding!==e.padding&&(i.padding=o.padding),o.cornerRadius!==e.cornerRadius&&(i.cornerRadius=o.cornerRadius),o.inputBarOffset!==e.inputBarOffset&&(i.inputBarOffset=o.inputBarOffset),o.mobileKeyboardMode!==e.mobileKeyboardMode&&(i.mobileKeyboardMode=o.mobileKeyboardMode),o.diffLayoutPreference!==e.diffLayoutPreference&&(i.diffLayoutPreference=o.diffLayoutPreference),o.gitChangesViewMode!==e.gitChangesViewMode&&(i.gitChangesViewMode=o.gitChangesViewMode),e=o,Object.keys(i).length>0&&$r(i)});let n=!1;const r=()=>{n||(n=!0,t(),zc===r&&(zc=null))};return zc=r,r},ao={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Vw={isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1,hasTouchOnlyPointer:!1},tj=()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("surface")==="desktop",nj=e=>{if(typeof navigator>"u")return{isExplicitTablet:!1};const t=navigator.userAgent||"",n=navigator.platform||"",r=/iPad/i.test(t)||(/Macintosh|MacIntel/i.test(t)||/MacIntel/i.test(n))&&e>1,s=/Android/i.test(t)&&!/Mobile/i.test(t),o=/Tablet/i.test(t);return{isExplicitTablet:r||s||o}},rj=(e,t,n)=>{if(typeof window>"u")return;const r=document.documentElement;r.classList.remove("device-mobile","device-tablet","device-desktop"),r.classList.add(t==="mobile"?"device-mobile":t==="tablet"?"device-tablet":"device-desktop"),e?(r.classList.add("desktop-runtime"),r.classList.remove("mobile-pointer")):(r.classList.remove("desktop-runtime"),n?r.classList.add("mobile-pointer"):r.classList.remove("mobile-pointer"))};function pu(){const e=window.innerWidth,t=typeof window.matchMedia=="function",n=t?window.matchMedia("(pointer: coarse)"):null,r=t?window.matchMedia("(hover: none)"):null,s=n?.matches??!1,o=r?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,a=xt()||tj(),{isExplicitTablet:l}=nj(i),d=s||o||i>0,f=s||o,u=e>ao.md&&e<=ao.lg,h=e<=ao.md;let m=d&&h,g=d&&!m&&(u||l),x=!d||!g&&e>ao.lg,b="desktop";a?(m=!1,g=!1,x=!0,b="desktop"):un()?(m=!0,g=!1,x=!1,b="mobile"):m?b="mobile":g?b="tablet":(x=!0,b="desktop"),rj(a,b,d);let S="xs";for(const[y,v]of Object.entries(ao))e>=v&&(S=y);return{isMobile:m,isTablet:g,isDesktop:x,deviceType:b,screenWidth:e,breakpoint:S,hasTouchInput:d,hasTouchOnlyPointer:f}}const sj=(e,t)=>e.isMobile===t.isMobile&&e.isTablet===t.isTablet&&e.isDesktop===t.isDesktop&&e.deviceType===t.deviceType&&e.screenWidth===t.screenWidth&&e.breakpoint===t.breakpoint&&e.hasTouchInput===t.hasTouchInput&&e.hasTouchOnlyPointer===t.hasTouchOnlyPointer,Tl=new Set;let Fr=null,_o,xi=null;const oj=()=>typeof window>"u"?Vw:(Fr||(Fr=pu()),Fr),ij=()=>{for(const e of Tl)e()},aj=()=>{_o=void 0;const e=pu();Fr&&sj(Fr,e)||(Fr=e,ij())},Uc=()=>{typeof window>"u"||_o!==void 0||(_o=window.requestAnimationFrame(aj))},xd=(e,t)=>e?typeof e.addEventListener=="function"?(e.addEventListener("change",t),()=>e.removeEventListener("change",t)):typeof e.addListener=="function"?(e.addListener(t),()=>e.removeListener(t)):()=>{}:()=>{},cj=()=>{if(typeof window>"u")return()=>{};Fr=pu(),window.addEventListener("resize",Uc);const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null,t=typeof window.matchMedia=="function"?window.matchMedia("(hover: none)"):null,n=xd(e,Uc),r=xd(t,Uc);return()=>{window.removeEventListener("resize",Uc),n(),r(),_o!==void 0&&(window.cancelAnimationFrame(_o),_o=void 0)}},lj=e=>typeof window>"u"?()=>{}:(Tl.add(e),xi||(xi=cj()),()=>{Tl.delete(e),Tl.size===0&&xi&&(xi(),xi=null,Fr=null)}),dj=()=>typeof window>"u"?!1:!!(navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)")?.matches||window.matchMedia?.("(display-mode: fullscreen)")?.matches),j2=()=>{if(typeof window>"u"||xt())return!1;const e=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return dj()&&e>0&&window.innerWidth>ao.md};function oJ(){const[e,t]=p.useState(()=>j2());return p.useEffect(()=>{if(typeof window>"u")return;const n=()=>t(j2()),r=window.matchMedia?.("(display-mode: standalone)"),s=window.matchMedia?.("(display-mode: fullscreen)");n(),window.addEventListener("resize",n),window.addEventListener("focus",n);const o=a=>{a&&(typeof a.addEventListener=="function"?a.addEventListener("change",n):typeof a.addListener=="function"&&a.addListener(n))},i=a=>{a&&(typeof a.removeEventListener=="function"?a.removeEventListener("change",n):typeof a.removeListener=="function"&&a.removeListener(n))};return o(r),o(s),()=>{window.removeEventListener("resize",n),window.removeEventListener("focus",n),i(r),i(s)}},[]),e}const uj=()=>typeof window>"u"?"portrait":window.matchMedia?.("(orientation: landscape)")?.matches?"landscape":"portrait";function iJ(){const[e,t]=p.useState(uj);return p.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(orientation: landscape)"),r=()=>t(n.matches?"landscape":"portrait");return r(),xd(n,r)},[]),e}const fj=600,hj=1e3,t1=()=>{if(typeof window>"u")return{enabled:!1,roomyForPanels:!1};const e=window.innerWidth,t=window.innerHeight,n=AS()||Math.min(e,t)>=fj;return{enabled:n,roomyForPanels:n&&e>t&&e>=hj}},pj=(e,t)=>e.enabled===t.enabled&&e.roomyForPanels===t.roomyForPanels,$w={enabled:!1,roomyForPanels:!1},Al=new Set;let Br=null,jo,bi=null;const mj=()=>typeof window>"u"?$w:(Br||(Br=t1()),Br),gj=()=>{for(const e of Al)e()},yj=()=>{jo=void 0;const e=t1();Br&&pj(Br,e)||(Br=e,gj())},jf=()=>{typeof window>"u"||jo!==void 0||(jo=window.requestAnimationFrame(yj))},vj=()=>{if(typeof window>"u")return()=>{};Br=t1(),window.addEventListener("resize",jf);const e=typeof window.matchMedia=="function"?window.matchMedia("(orientation: landscape)"):null,t=xd(e,jf);return()=>{window.removeEventListener("resize",jf),t(),jo!==void 0&&(window.cancelAnimationFrame(jo),jo=void 0)}},xj=e=>typeof window>"u"?()=>{}:(Al.add(e),bi||(bi=vj()),()=>{Al.delete(e),Al.size===0&&bi&&(bi(),bi=null,Br=null)});function mu(){return p.useSyncExternalStore(xj,mj,()=>$w)}function On(){return p.useSyncExternalStore(lj,oj,()=>Vw)}const n1=e=>{const t=e;return ce(t.directory??null)??ce(t.project?.worktree??null)};let qc=null;const aJ=()=>{if(typeof window>"u"||typeof document>"u"||qc)return()=>{};const e=()=>{document.visibilityState!=="hidden"&&NS()};document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),window.addEventListener("online",e);let t=!1;const n=()=>{t||(t=!0,document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),window.removeEventListener("online",e),qc===n&&(qc=null))};return qc=n,n},bj=(e,t)=>{const n={};return Zu(e.favoriteModels,t.favoriteModels)||(n.favoriteModels=e.favoriteModels),Zu(e.hiddenModels,t.hiddenModels)||(n.hiddenModels=e.hiddenModels),Wg(e.collapsedModelProviders,t.collapsedModelProviders)||(n.collapsedModelProviders=e.collapsedModelProviders),Zu(e.recentModels,t.recentModels)||(n.recentModels=e.recentModels),Wg(e.recentAgents,t.recentAgents)||(n.recentAgents=e.recentAgents),RS(e.recentEfforts,t.recentEfforts)||(n.recentEfforts=e.recentEfforts),n},cJ=()=>{if(typeof window>"u")return()=>{};const e=re.subscribe((t,n)=>{const r=bj(t,n);Object.keys(r).length!==0&&$r(r).catch(()=>{})});return()=>{e(),LS()}};let Tf=null;const r1=()=>(Tf??=mt(()=>import("./MarkdownRendererImpl-B9Cu4TCh.js"),__vite__mapDeps([12,5,1,6,13,14,15,16,17,11,8,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])).catch(e=>{throw Tf=null,e}),Tf),lJ=()=>{r1().catch(()=>{})},zw={add:'<path d="M11 11V5H13V11H19V13H13V19H11V13H5V11H11Z" fill="currentColor"/>',"add-circle":'<path d="M11 11V7H13V11H17V13H13V17H11V13H7V11H11ZM12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20Z" fill="currentColor"/>',"ai-agent":'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 14.7096 20.9205 17.1697 19.1709 18.9697C17.3551 20.8376 14.8124 22 12 22C9.18756 22 6.64488 20.8376 4.8291 18.9697C3.07949 17.1697 2 14.7096 2 12C2 6.47715 6.47715 2 12 2ZM12 16C10.0022 16 8.20124 16.8375 6.9248 18.1816C8.30642 19.3175 10.0724 20 12 20C13.9274 20 15.6927 19.3173 17.0742 18.1816C15.7978 16.8377 13.9975 16 12 16ZM12 4C7.58172 4 4 7.58172 4 12C4 13.7701 4.57462 15.4044 5.54785 16.7295C7.1822 15.0483 9.46797 14 12 14C14.5318 14 16.8169 15.0485 18.4512 16.7295C19.4246 15.4043 20 13.7703 20 12C20 7.58172 16.4183 4 12 4ZM11.5293 5.31934C11.7058 4.89329 12.2943 4.89329 12.4707 5.31934L12.7236 5.93066C13.1556 6.97343 13.9615 7.80622 14.9746 8.25684L15.6924 8.5752C16.1029 8.75796 16.1028 9.35627 15.6924 9.53906L14.9326 9.87695C13.9448 10.3163 13.1534 11.1193 12.7139 12.1279L12.4668 12.6934C12.2864 13.1074 11.7137 13.1074 11.5332 12.6934L11.2871 12.1279C10.8476 11.1193 10.0552 10.3163 9.06738 9.87695L8.30762 9.53906C7.89719 9.35628 7.89717 8.75795 8.30762 8.5752L9.02539 8.25684C10.0385 7.80623 10.8445 6.97345 11.2764 5.93066L11.5293 5.31934Z" fill="currentColor"/>',"ai-generate-2":'<path d="M20.4668 8.69379L20.7134 8.12811C21.1529 7.11947 21.9445 6.31641 22.9323 5.87708L23.6919 5.53922C24.1027 5.35653 24.1027 4.75881 23.6919 4.57612L22.9748 4.25714C21.9616 3.80651 21.1558 2.97373 20.7238 1.93083L20.4706 1.31953C20.2942 0.893489 19.7058 0.893489 19.5293 1.31953L19.2761 1.93083C18.8442 2.97373 18.0384 3.80651 17.0252 4.25714L16.308 4.57612C15.8973 4.75881 15.8973 5.35653 16.308 5.53922L17.0677 5.87708C18.0555 6.31641 18.8471 7.11947 19.2866 8.12811L19.5331 8.69379C19.7136 9.10792 20.2864 9.10792 20.4668 8.69379ZM5.79993 16H7.95399L8.55399 14.5H11.4459L12.0459 16H14.1999L10.9999 8H8.99993L5.79993 16ZM9.99993 10.8852L10.6459 12.5H9.35399L9.99993 10.8852ZM15 16V8H17V16H15ZM3 3C2.44772 3 2 3.44772 2 4V20C2 20.5523 2.44772 21 3 21H21C21.5523 21 22 20.5523 22 20V11H20V19H4V5H14V3H3Z" fill="currentColor"/>',alarm:'<path d="M12.0001 22.0001C7.02956 22.0001 3.00012 17.9707 3.00012 13.0001C3.00012 8.02956 7.02956 4.00012 12.0001 4.00012C16.9707 4.00012 21.0001 8.02956 21.0001 13.0001C21.0001 17.9707 16.9707 22.0001 12.0001 22.0001ZM12.0001 20.0001C15.8661 20.0001 19.0001 16.8661 19.0001 13.0001C19.0001 9.13412 15.8661 6.00012 12.0001 6.00012C8.13412 6.00012 5.00012 9.13412 5.00012 13.0001C5.00012 16.8661 8.13412 20.0001 12.0001 20.0001ZM13.0001 13.0001H16.0001V15.0001H11.0001V8.00012H13.0001V13.0001ZM1.74707 6.2826L5.2826 2.74707L6.69682 4.16128L3.16128 7.69682L1.74707 6.2826ZM18.7176 2.74707L22.2532 6.2826L20.839 7.69682L17.3034 4.16128L18.7176 2.74707Z" fill="currentColor"/>',alert:'<path d="M12.8659 3.00017L22.3922 19.5002C22.6684 19.9785 22.5045 20.5901 22.0262 20.8662C21.8742 20.954 21.7017 21.0002 21.5262 21.0002H2.47363C1.92135 21.0002 1.47363 20.5525 1.47363 20.0002C1.47363 19.8246 1.51984 19.6522 1.60761 19.5002L11.1339 3.00017C11.41 2.52187 12.0216 2.358 12.4999 2.63414C12.6519 2.72191 12.7782 2.84815 12.8659 3.00017ZM4.20568 19.0002H19.7941L11.9999 5.50017L4.20568 19.0002ZM10.9999 16.0002H12.9999V18.0002H10.9999V16.0002ZM10.9999 9.00017H12.9999V14.0002H10.9999V9.00017Z" fill="currentColor"/>',"align-justify":'<path d="M3 4H21V6H3V4ZM3 19H21V21H3V19ZM3 14H21V16H3V14ZM3 9H21V11H3V9Z" fill="currentColor"/>',apple:'<path d="M15.778 8.20793C15.3053 8.1711 14.7974 8.28434 14.0197 8.58067C14.085 8.55577 13.2775 8.87173 13.0511 8.95077C12.5494 9.12593 12.1364 9.22198 11.6734 9.22198C11.2151 9.22198 10.7925 9.13042 10.3078 8.96683C10.1524 8.91441 9.99616 8.8564 9.80283 8.7809C9.71993 8.74852 9.41997 8.62947 9.3544 8.60379C8.70626 8.34996 8.34154 8.25434 8.03885 8.26181C6.88626 8.2765 5.79557 8.9421 5.16246 10.0442C3.87037 12.2875 4.58583 16.3428 6.47459 19.075C7.4802 20.5189 8.03062 21.035 8.25199 21.0279C8.4743 21.0183 8.63777 20.9713 9.03567 20.8026C9.11485 20.7689 9.11485 20.7689 9.202 20.7317C10.2077 20.3032 10.9118 20.114 11.9734 20.114C12.9944 20.114 13.6763 20.2997 14.6416 20.7159C14.7302 20.7542 14.7302 20.7542 14.8097 20.7884C15.2074 20.9588 15.3509 20.9962 15.6016 20.9902C15.9591 20.9846 16.4003 20.5726 17.3791 19.1362C17.6471 18.7447 17.884 18.3333 18.0895 17.9168C17.9573 17.8077 17.826 17.6917 17.6975 17.5693C16.4086 16.3408 15.6114 14.6845 15.5895 12.6391C15.5756 11.0186 16.1057 9.61487 16.999 8.45797C16.6293 8.3142 16.2216 8.23805 15.778 8.20793ZM15.9334 6.21398C16.6414 6.26198 18.6694 6.47798 19.9894 8.40998C19.8814 8.46998 17.5654 9.81397 17.5894 12.622C17.6254 15.982 20.5294 17.098 20.5654 17.11C20.5414 17.194 20.0974 18.706 19.0294 20.266C18.1054 21.622 17.1454 22.966 15.6334 22.99C14.1454 23.026 13.6654 22.114 11.9734 22.114C10.2694 22.114 9.74138 22.966 8.33738 23.026C6.87338 23.074 5.76938 21.562 4.83338 20.218C2.92538 17.458 1.47338 12.442 3.42938 9.04597C4.40138 7.35397 6.12938 6.28598 8.01338 6.26198C9.44138 6.22598 10.7974 7.22198 11.6734 7.22198C12.5374 7.22198 14.0854 6.06998 15.9334 6.21398ZM14.7934 4.38998C14.0134 5.32598 12.7414 6.05798 11.5054 5.96198C11.3374 4.68998 11.9614 3.35798 12.6814 2.52998C13.4854 1.59398 14.8294 0.897976 15.9454 0.849976C16.0894 2.14598 15.5734 3.45398 14.7934 4.38998Z" fill="currentColor"/>',"arch-linux":'<path fill="currentColor" d="M12 2.2c-1.06 2.6-1.7 4.3-2.88 6.82.72.76 1.6 1.65 3.04 2.66-1.55-.64-2.61-1.29-3.4-1.96-1.5 3.13-3.83 7.57-6.76 12.08 2.3-1.33 4.09-2.15 5.76-2.47-.08-.35-.13-.73-.12-1.13l.01-.08c.06-2.25 1.23-3.98 2.61-3.87 1.38.1 2.45 2 2.39 4.25-.01.39-.06.76-.14 1.1 1.66.33 3.44 1.15 5.72 2.47-1.16-1.8-2.22-3.62-3.16-5.35-.74-.57-1.51-1.3-2.95-2.04.99.26 1.7.57 2.25.92C13.03 13.04 12.2 11.05 12 10.4c-.2.65-1.03 2.64-2.37 5.2.55-.35 1.26-.66 2.25-.92-1.44.74-2.21 1.47-2.95 2.04A78.9 78.9 0 0 1 5.77 22.07c2.28-1.32 4.06-2.14 5.72-2.47-.08-.34-.13-.71-.14-1.1-.06-2.25 1.01-4.15 2.39-4.25 1.38-.11 2.55 1.62 2.61 3.87l.01.08c.01.4-.04.78-.12 1.13 1.67.32 3.46 1.14 5.76 2.47-2.93-4.51-5.26-8.95-6.76-12.08-.79.67-1.85 1.32-3.4 1.96 1.44-1.01 2.32-1.9 3.04-2.66C13.7 6.5 13.06 4.8 12 2.2Z"/>',archive:'<path d="M3 10H2V4.00293C2 3.44903 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.43788 22 4.00293V10H21V20.0015C21 20.553 20.5551 21 20.0066 21H3.9934C3.44476 21 3 20.5525 3 20.0015V10ZM19 10H5V19H19V10ZM4 5V8H20V5H4ZM9 12H15V14H9V12Z" fill="currentColor"/>',"archive-stack":'<path d="M4 5H20V3H4V5ZM20 9H4V7H20V9ZM3 11H10V13H14V11H21V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V11ZM16 13V15H8V13H5V19H19V13H16Z" fill="currentColor"/>',"arrow-down":'<path d="M13.0001 16.1716L18.3641 10.8076L19.7783 12.2218L12.0001 20L4.22192 12.2218L5.63614 10.8076L11.0001 16.1716V4H13.0001V16.1716Z" fill="currentColor"/>',"arrow-down-s":'<path d="M11.9999 13.1714L16.9497 8.22168L18.3639 9.63589L11.9999 15.9999L5.63599 9.63589L7.0502 8.22168L11.9999 13.1714Z" fill="currentColor"/>',"arrow-go-back":'<path d="M5.82843 6.99955L8.36396 9.53509L6.94975 10.9493L2 5.99955L6.94975 1.0498L8.36396 2.46402L5.82843 4.99955H13C17.4183 4.99955 21 8.58127 21 12.9996C21 17.4178 17.4183 20.9996 13 20.9996H4V18.9996H13C16.3137 18.9996 19 16.3133 19 12.9996C19 9.68584 16.3137 6.99955 13 6.99955H5.82843Z" fill="currentColor"/>',"arrow-go-forward":'<path d="M18.1716 6.99955H11C7.68629 6.99955 5 9.68584 5 12.9996C5 16.3133 7.68629 18.9996 11 18.9996H20V20.9996H11C6.58172 20.9996 3 17.4178 3 12.9996C3 8.58127 6.58172 4.99955 11 4.99955H18.1716L15.636 2.46402L17.0503 1.0498L22 5.99955L17.0503 10.9493L15.636 9.53509L18.1716 6.99955Z" fill="currentColor"/>',"arrow-left":'<path d="M7.82843 10.9999H20V12.9999H7.82843L13.1924 18.3638L11.7782 19.778L4 11.9999L11.7782 4.22168L13.1924 5.63589L7.82843 10.9999Z" fill="currentColor"/>',"arrow-left-right":'<path d="M16.0503 12.0498L21 16.9996L16.0503 21.9493L14.636 20.5351L17.172 17.9988L4 17.9996V15.9996L17.172 15.9988L14.636 13.464L16.0503 12.0498ZM7.94975 2.0498L9.36396 3.46402L6.828 5.9988L20 5.99955V7.99955L6.828 7.9988L9.36396 10.5351L7.94975 11.9493L3 6.99955L7.94975 2.0498Z" fill="currentColor"/>',"arrow-left-s":'<path d="M10.8284 12.0007L15.7782 16.9504L14.364 18.3646L8 12.0007L14.364 5.63672L15.7782 7.05093L10.8284 12.0007Z" fill="currentColor"/>',"arrow-right":'<path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z" fill="currentColor"/>',"arrow-right-s":'<path d="M13.1717 12.0007L8.22192 7.05093L9.63614 5.63672L16.0001 12.0007L9.63614 18.3646L8.22192 16.9504L13.1717 12.0007Z" fill="currentColor"/>',"arrow-up":'<path d="M13.0001 7.82843V20H11.0001V7.82843L5.63614 13.1924L4.22192 11.7782L12.0001 4L19.7783 11.7782L18.3641 13.1924L13.0001 7.82843Z" fill="currentColor"/>',"arrow-up-double":'<path d="M12 4.83582L5.79291 11.0429L7.20712 12.4571L12 7.66424L16.7929 12.4571L18.2071 11.0429L12 4.83582ZM12 10.4857L5.79291 16.6928L7.20712 18.107L12 13.3141L16.7929 18.107L18.2071 16.6928L12 10.4857Z" fill="currentColor"/>',"arrow-up-s":'<path d="M11.9999 10.8284L7.0502 15.7782L5.63599 14.364L11.9999 8L18.3639 14.364L16.9497 15.7782L11.9999 10.8284Z" fill="currentColor"/>',"attachment-2":'<path d="M14.8287 7.75737L9.1718 13.4142C8.78127 13.8047 8.78127 14.4379 9.1718 14.8284C9.56232 15.219 10.1955 15.219 10.586 14.8284L16.2429 9.17158C17.4144 8.00001 17.4144 6.10052 16.2429 4.92894C15.0713 3.75737 13.1718 3.75737 12.0002 4.92894L6.34337 10.5858C4.39075 12.5384 4.39075 15.7042 6.34337 17.6569C8.29599 19.6095 11.4618 19.6095 13.4144 17.6569L19.0713 12L20.4855 13.4142L14.8287 19.0711C12.095 21.8047 7.66283 21.8047 4.92916 19.0711C2.19549 16.3374 2.19549 11.9053 4.92916 9.17158L10.586 3.51473C12.5386 1.56211 15.7045 1.56211 17.6571 3.51473C19.6097 5.46735 19.6097 8.63317 17.6571 10.5858L12.0002 16.2427C10.8287 17.4142 8.92916 17.4142 7.75759 16.2427C6.58601 15.0711 6.58601 13.1716 7.75759 12L13.4144 6.34316L14.8287 7.75737Z" fill="currentColor"/>',book:'<path d="M3 18.5V5C3 3.34315 4.34315 2 6 2H20C20.5523 2 21 2.44772 21 3V21C21 21.5523 20.5523 22 20 22H6.5C4.567 22 3 20.433 3 18.5ZM19 20V17H6.5C5.67157 17 5 17.6716 5 18.5C5 19.3284 5.67157 20 6.5 20H19ZM5 15.3368C5.45463 15.1208 5.9632 15 6.5 15H19V4H6C5.44772 4 5 4.44772 5 5V15.3368Z" fill="currentColor"/>',"book-open":'<path d="M13 21V23H11V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H9C10.1947 3 11.2671 3.52375 12 4.35418C12.7329 3.52375 13.8053 3 15 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H13ZM20 19V5H15C13.8954 5 13 5.89543 13 7V19H20ZM11 19V7C11 5.89543 10.1046 5 9 5H4V19H11Z" fill="currentColor"/>',brain:'<path d="M9 4C10.1046 4 11 4.89543 11 6V12.8271C10.1058 12.1373 8.96602 11.7305 7.6644 11.5136L7.3356 13.4864C8.71622 13.7165 9.59743 14.1528 10.1402 14.7408C10.67 15.3147 11 16.167 11 17.5C11 18.8807 9.88071 20 8.5 20C7.11929 20 6 18.8807 6 17.5V17.1493C6.43007 17.2926 6.87634 17.4099 7.3356 17.4864L7.6644 15.5136C6.92149 15.3898 6.1752 15.1144 5.42909 14.7599C4.58157 14.3573 4 13.499 4 12.5C4 11.6653 4.20761 11.0085 4.55874 10.5257C4.90441 10.0504 5.4419 9.6703 6.24254 9.47014L7 9.28078V6C7 4.89543 7.89543 4 9 4ZM12 3.35418C11.2671 2.52376 10.1947 2 9 2C6.79086 2 5 3.79086 5 6V7.77422C4.14895 8.11644 3.45143 8.64785 2.94126 9.34933C2.29239 10.2415 2 11.3347 2 12.5C2 14.0652 2.79565 15.4367 4 16.2422V17.5C4 19.9853 6.01472 22 8.5 22C9.91363 22 11.175 21.3482 12 20.3287C12.825 21.3482 14.0864 22 15.5 22C17.9853 22 20 19.9853 20 17.5V16.2422C21.2044 15.4367 22 14.0652 22 12.5C22 11.3347 21.7076 10.2415 21.0587 9.34933C20.5486 8.64785 19.8511 8.11644 19 7.77422V6C19 3.79086 17.2091 2 15 2C13.8053 2 12.7329 2.52376 12 3.35418ZM18 17.1493V17.5C18 18.8807 16.8807 20 15.5 20C14.1193 20 13 18.8807 13 17.5C13 16.167 13.33 15.3147 13.8598 14.7408C14.4026 14.1528 15.2838 13.7165 16.6644 13.4864L16.3356 11.5136C15.034 11.7305 13.8942 12.1373 13 12.8271V6C13 4.89543 13.8954 4 15 4C16.1046 4 17 4.89543 17 6V9.28078L17.7575 9.47014C18.5581 9.6703 19.0956 10.0504 19.4413 10.5257C19.7924 11.0085 20 11.6653 20 12.5C20 13.499 19.4184 14.3573 18.5709 14.7599C17.8248 15.1144 17.0785 15.3898 16.3356 15.5136L16.6644 17.4864C17.1237 17.4099 17.5699 17.2926 18 17.1493Z" fill="currentColor"/>',"brain-ai-3":'<path d="M19.5 4.7832V7.6709L22 9.11426V14.8867L19.499 16.3311L19.5 19.2178L14.5 22.1045L12 20.6611L9.5 22.1045L4.5 19.2178V16.3311L2 14.8877L2.00098 9.11328L4.5 7.66992V4.78418L9.5 1.89746L11.999 3.34082L14.501 1.89648L19.5 4.7832ZM13 5.07227V7H11V5.07324L9.5 4.20703L6.49902 5.93848V8.8252L4 10.2676V13.7334L6.5 15.1768V18.0635L9.5 19.7959L11 18.9287V17H13V18.9297L14.5 19.7959L17.5 18.0625V15.1768L20 13.7324V10.2695L17.499 8.8252L17.5 5.9375L14.501 4.20605L13 5.07227ZM14.2646 13.1602C14.3529 12.9473 14.6472 12.9473 14.7354 13.1602L14.8623 13.4648C15.0783 13.986 15.4807 14.4027 15.9873 14.6279L16.3457 14.7871C16.5511 14.8784 16.5511 15.1773 16.3457 15.2686L15.9658 15.4375C15.4721 15.6571 15.0761 16.0586 14.8564 16.5625L14.7334 16.8447C14.6432 17.0517 14.3569 17.0517 14.2666 16.8447L14.1436 16.5625C13.9239 16.0586 13.5279 15.6571 13.0342 15.4375L12.6543 15.2686C12.4489 15.1773 12.4489 14.8784 12.6543 14.7871L13.0127 14.6279C13.5193 14.4027 13.9217 13.986 14.1377 13.4648L14.2646 13.1602ZM9.58789 7.7793C9.74239 7.40671 10.2577 7.4067 10.4121 7.7793L10.6338 8.31445C11.0118 9.22695 11.7161 9.95624 12.6025 10.3506L13.2305 10.6289C13.5899 10.7887 13.5897 11.3117 13.2305 11.4717L12.5654 11.7676C11.7013 12.152 11.0086 12.8548 10.624 13.7373L10.4082 14.2324C10.2504 14.5948 9.74973 14.5948 9.5918 14.2324L9.37598 13.7373C8.99143 12.8548 8.29875 12.152 7.43457 11.7676L6.76953 11.4717C6.41033 11.3117 6.41022 10.7887 6.76953 10.6289L7.39746 10.3506C8.2839 9.95624 8.98832 9.22697 9.36621 8.31445L9.58789 7.7793Z" fill="currentColor"/>',brush:'<path d="M15.4565 9.67503L15.3144 9.53297C14.6661 8.90796 13.8549 8.43369 12.9235 8.18412C10.0168 7.40527 7.22541 9.05273 6.43185 12.0143C6.38901 12.1742 6.36574 12.3537 6.3285 12.8051C6.17423 14.6752 5.73449 16.0697 4.5286 17.4842C6.78847 18.3727 9.46572 18.9986 11.5016 18.9986C13.9702 18.9986 16.1644 17.3394 16.8126 14.9202C17.3306 12.9869 16.7513 11.0181 15.4565 9.67503ZM13.2886 6.21301L18.2278 2.37142C18.6259 2.0618 19.1922 2.09706 19.5488 2.45367L22.543 5.44787C22.8997 5.80448 22.9349 6.37082 22.6253 6.76891L18.7847 11.7068C19.0778 12.8951 19.0836 14.1721 18.7444 15.4379C17.8463 18.7897 14.8142 20.9986 11.5016 20.9986C8 20.9986 3.5 19.4967 1 17.9967C4.97978 14.9967 4.04722 13.1865 4.5 11.4967C5.55843 7.54658 9.34224 5.23935 13.2886 6.21301ZM16.7015 8.09161C16.7673 8.15506 16.8319 8.21964 16.8952 8.28533L18.0297 9.41984L20.5046 6.23786L18.7589 4.4921L15.5769 6.96698L16.7015 8.09161Z" fill="currentColor"/>',bug:'<path d="M13 19.9C15.2822 19.4367 17 17.419 17 15V12C17 11.299 16.8564 10.6219 16.5846 10H7.41538C7.14358 10.6219 7 11.299 7 12V15C7 17.419 8.71776 19.4367 11 19.9V14H13V19.9ZM5.5358 17.6907C5.19061 16.8623 5 15.9534 5 15H2V13H5V12C5 11.3573 5.08661 10.7348 5.2488 10.1436L3.0359 8.86602L4.0359 7.13397L6.05636 8.30049C6.11995 8.19854 6.18609 8.09835 6.25469 8H17.7453C17.8139 8.09835 17.88 8.19854 17.9436 8.30049L19.9641 7.13397L20.9641 8.86602L18.7512 10.1436C18.9134 10.7348 19 11.3573 19 12V13H22V15H19C19 15.9534 18.8094 16.8623 18.4642 17.6907L20.9641 19.134L19.9641 20.866L17.4383 19.4077C16.1549 20.9893 14.1955 22 12 22C9.80453 22 7.84512 20.9893 6.56171 19.4077L4.0359 20.866L3.0359 19.134L5.5358 17.6907ZM8 6C8 3.79086 9.79086 2 12 2C14.2091 2 16 3.79086 16 6H8Z" fill="currentColor"/>',"centos-fill":'<path d="M12 13.0607L16.47 17.531L12 22L7.53 17.53L12 13.0607ZM3.99968 16.1207L7.87868 19.9997L4 20L3.99968 16.1207ZM19.9997 16.1207L20 20L16.1207 19.9997L19.9997 16.1207ZM17.53 7.53L22 12L17.531 16.47L13.0607 12L17.53 7.53ZM6.47 7.53L10.9393 12L6.469 16.469L2 12L6.47 7.53ZM12 2L16.469 6.469L12 10.9393L7.53 6.47L12 2ZM7.87868 3.99968L3.99968 7.87868L4 4L7.87868 3.99968ZM20 4L19.9997 7.87868L16.1207 3.99968L20 4Z" fill="currentColor"/>',"chat-1":'<path d="M10 3H14C18.4183 3 22 6.58172 22 11C22 15.4183 18.4183 19 14 19V22.5C9 20.5 2 17.5 2 11C2 6.58172 5.58172 3 10 3ZM12 17H14C17.3137 17 20 14.3137 20 11C20 7.68629 17.3137 5 14 5H10C6.68629 5 4 7.68629 4 11C4 14.61 6.46208 16.9656 12 19.4798V17Z" fill="currentColor"/>',"chat-3":'<path d="M7.29117 20.8242L2 22L3.17581 16.7088C2.42544 15.3056 2 13.7025 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C10.2975 22 8.6944 21.5746 7.29117 20.8242ZM7.58075 18.711L8.23428 19.0605C9.38248 19.6745 10.6655 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 13.3345 4.32549 14.6175 4.93949 15.7657L5.28896 16.4192L4.63416 19.3658L7.58075 18.711Z" fill="currentColor"/>',"chat-4":'<path d="M5.76282 17H20V5H4V18.3851L5.76282 17ZM6.45455 19L2 22.5V4C2 3.44772 2.44772 3 3 3H21C21.5523 3 22 3.44772 22 4V18C22 18.5523 21.5523 19 21 19H6.45455Z" fill="currentColor"/>',"chat-ai-3":'<path d="M12 1.99996C12.8632 1.99996 13.701 2.10973 14.5 2.31539L14 4.25192C13.3608 4.0874 12.6906 3.99997 12 3.99997C7.58174 3.99997 4.00002 7.58172 4 12C4 13.3344 4.3255 14.6174 4.93945 15.7656L5.28906 16.4189L4.63379 19.3662L7.58105 18.7109L8.23438 19.0605C9.38255 19.6745 10.6656 20 12 20C16.4183 20 20 16.4183 20 12C20 11.6771 19.9805 11.3587 19.9434 11.0459L21.9297 10.8095C21.976 11.1999 22 11.5972 22 12C22 17.5228 17.5228 22 12 22C10.2975 22 8.69425 21.5746 7.29102 20.8242L2 22L3.17578 16.709C2.42541 15.3057 2 13.7025 2 12C2.00002 6.47714 6.47717 1.99996 12 1.99996ZM19.5293 1.3193C19.7058 0.893513 20.2942 0.8935 20.4707 1.3193L20.7236 1.93063C21.1555 2.97343 21.9615 3.80614 22.9746 4.2568L23.6914 4.57614C24.1022 4.75882 24.1022 5.35635 23.6914 5.53903L22.9326 5.87692C21.945 6.3162 21.1534 7.11943 20.7139 8.1279L20.4668 8.69333C20.2863 9.10747 19.7136 9.10747 19.5332 8.69333L19.2861 8.1279C18.8466 7.11942 18.0551 6.3162 17.0674 5.87692L16.3076 5.53903C15.8974 5.35618 15.8974 4.75895 16.3076 4.57614L17.0254 4.2568C18.0384 3.80614 18.8445 2.97343 19.2764 1.93063L19.5293 1.3193Z" fill="currentColor"/>',"chat-history":'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C10.298 22 8.69525 21.5748 7.29229 20.8248L2 22L3.17629 16.7097C2.42562 15.3063 2 13.7028 2 12C2 6.47715 6.47715 2 12 2ZM12 4C7.58172 4 4 7.58172 4 12C4 13.3347 4.32563 14.6181 4.93987 15.7664L5.28952 16.4201L4.63445 19.3663L7.58189 18.7118L8.23518 19.061C9.38315 19.6747 10.6659 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4ZM13 7V12H17V14H11V7H13Z" fill="currentColor"/>',"chat-new":'<path d="M14 3V5H4V18.3851L5.76282 17H20V10H22V18C22 18.5523 21.5523 19 21 19H6.45455L2 22.5V4C2 3.44772 2.44772 3 3 3H14ZM19 3V0H21V3H24V5H21V8H19V5H16V3H19Z" fill="currentColor"/>',check:'<path d="M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z" fill="currentColor"/>',checkbox:'<path d="M4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM5 5V19H19V5H5ZM11.0026 16L6.75999 11.7574L8.17421 10.3431L11.0026 13.1716L16.6595 7.51472L18.0737 8.92893L11.0026 16Z" fill="currentColor"/>',"checkbox-blank":'<path d="M4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM5 5V19H19V5H5Z" fill="currentColor"/>',"checkbox-blank-circle-fill":'<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" fill="currentColor"/>',"checkbox-circle":'<path d="M4 12C4 7.58172 7.58172 4 12 4C16.4183 4 20 7.58172 20 12C20 16.4183 16.4183 20 12 20C7.58172 20 4 16.4183 4 12ZM12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2ZM17.4571 9.45711L16.0429 8.04289L11 13.0858L8.20711 10.2929L6.79289 11.7071L11 15.9142L17.4571 9.45711Z" fill="currentColor"/>',"checkbox-multiple":'<path d="M6.99979 7V3C6.99979 2.44772 7.4475 2 7.99979 2H20.9998C21.5521 2 21.9998 2.44772 21.9998 3V16C21.9998 16.5523 21.5521 17 20.9998 17H17V20.9925C17 21.5489 16.551 22 15.9925 22H3.00728C2.45086 22 2 21.5511 2 20.9925L2.00276 8.00748C2.00288 7.45107 2.4518 7 3.01025 7H6.99979ZM8.99979 7H15.9927C16.549 7 17 7.44892 17 8.00748V15H19.9998V4H8.99979V7ZM15 9H4.00255L4.00021 20H15V9ZM8.50242 18L4.96689 14.4645L6.3811 13.0503L8.50242 15.1716L12.7451 10.9289L14.1593 12.3431L8.50242 18Z" fill="currentColor"/>',clipboard:'<path d="M7 4V2H17V4H20.0066C20.5552 4 21 4.44495 21 4.9934V21.0066C21 21.5552 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5551 3 21.0066V4.9934C3 4.44476 3.44495 4 3.9934 4H7ZM7 6H5V20H19V6H17V8H7V6ZM9 4V6H15V4H9Z" fill="currentColor"/>',close:'<path d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z" fill="currentColor"/>',"close-circle":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z" fill="currentColor"/>',cloud:'<path d="M12 2C15.866 2 19 5.13401 19 9C19 9.11351 18.9973 9.22639 18.992 9.33857C21.3265 10.16 23 12.3846 23 15C23 18.3137 20.3137 21 17 21H7C3.68629 21 1 18.3137 1 15C1 12.3846 2.67346 10.16 5.00804 9.33857C5.0027 9.22639 5 9.11351 5 9C5 5.13401 8.13401 2 12 2ZM12 4C9.23858 4 7 6.23858 7 9C7 9.08147 7.00193 9.16263 7.00578 9.24344L7.07662 10.7309L5.67183 11.2252C4.0844 11.7837 3 13.2889 3 15C3 17.2091 4.79086 19 7 19H17C19.2091 19 21 17.2091 21 15C21 12.79 19.21 11 17 11C15.233 11 13.7337 12.1457 13.2042 13.7347L11.3064 13.1021C12.1005 10.7185 14.35 9 17 9C17 6.23858 14.7614 4 12 4Z" fill="currentColor"/>',"cloud-off":'<path d="M3.51472 2.10051L22.6066 21.1924L21.1924 22.6066L19.1782 20.5924C18.503 20.8556 17.7684 21 17 21H7C3.68629 21 1 18.3137 1 15C1 12.3846 2.67346 10.16 5.00804 9.33857C5.0027 9.22639 5 9.11351 5 9C5 8.22228 5.12683 7.47418 5.36094 6.77527L2.10051 3.51472L3.51472 2.10051ZM7 9C7 9.08147 7.00193 9.16263 7.00578 9.24344L7.07662 10.7309L5.67183 11.2252C4.0844 11.7837 3 13.2889 3 15C3 17.2091 4.79086 19 7 19H17C17.1858 19 17.3687 18.9873 17.5478 18.9628L7.03043 8.44519C7.01032 8.62736 7 8.81247 7 9ZM12 2C15.866 2 19 5.13401 19 9C19 9.11351 18.9973 9.22639 18.992 9.33857C21.3265 10.16 23 12.3846 23 15C23 16.0883 22.7103 17.1089 22.2037 17.9889L20.7111 16.4955C20.8974 16.0335 21 15.5287 21 15C21 12.79 19.21 11 17 11C16.4711 11 15.9661 11.1027 15.5039 11.2892L14.0111 9.7964C14.8912 9.28978 15.9118 9 17 9C17 6.23858 14.7614 4 12 4C10.9295 4 9.93766 4.33639 9.12428 4.90922L7.69418 3.48056C8.88169 2.55284 10.3763 2 12 2Z" fill="currentColor"/>',code:'<path d="M23 12L15.9289 19.0711L14.5147 17.6569L20.1716 12L14.5147 6.34317L15.9289 4.92896L23 12ZM3.82843 12L9.48528 17.6569L8.07107 19.0711L1 12L8.07107 4.92896L9.48528 6.34317L3.82843 12Z" fill="currentColor"/>',"code-box":'<path d="M3 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3ZM4 5V19H20V5H4ZM20 12L16.4645 15.5355L15.0503 14.1213L17.1716 12L15.0503 9.87868L16.4645 8.46447L20 12ZM6.82843 12L8.94975 14.1213L7.53553 15.5355L4 12L7.53553 8.46447L8.94975 9.87868L6.82843 12ZM11.2443 17H9.11597L12.7557 7H14.884L11.2443 17Z" fill="currentColor"/>',"code-sslash":'<path d="M24 12L18.3431 17.6569L16.9289 16.2426L21.1716 12L16.9289 7.75736L18.3431 6.34315L24 12ZM2.82843 12L7.07107 16.2426L5.65685 17.6569L0 12L5.65685 6.34315L7.07107 7.75736L2.82843 12ZM9.78845 21H7.66009L14.2116 3H16.3399L9.78845 21Z" fill="currentColor"/>',"collapse-vertical":'<path d="M11.9995 13.4995 16.9492 18.4493 15.535 19.8635 12.9995 17.3279 12.9995 22.9995H10.9995L10.9995 17.3279 8.46643 19.861 7.05222 18.4468 11.9995 13.4995ZM10.9995.999512 10.9995 6.67035 8.46448 4.13535 7.05026 5.54956 12 10.4995 16.9497 5.54977 15.5355 4.13555 12.9995 6.67157V.999512L10.9995.999512Z" fill="currentColor"/>',command:'<path d="M10 8H14V6.5C14 4.567 15.567 3 17.5 3C19.433 3 21 4.567 21 6.5C21 8.433 19.433 10 17.5 10H16V14H17.5C19.433 14 21 15.567 21 17.5C21 19.433 19.433 21 17.5 21C15.567 21 14 19.433 14 17.5V16H10V17.5C10 19.433 8.433 21 6.5 21C4.567 21 3 19.433 3 17.5C3 15.567 4.567 14 6.5 14H8V10H6.5C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5V8ZM8 8V6.5C8 5.67157 7.32843 5 6.5 5C5.67157 5 5 5.67157 5 6.5C5 7.32843 5.67157 8 6.5 8H8ZM8 16H6.5C5.67157 16 5 16.6716 5 17.5C5 18.3284 5.67157 19 6.5 19C7.32843 19 8 18.3284 8 17.5V16ZM16 8H17.5C18.3284 8 19 7.32843 19 6.5C19 5.67157 18.3284 5 17.5 5C16.6716 5 16 5.67157 16 6.5V8ZM16 16V17.5C16 18.3284 16.6716 19 17.5 19C18.3284 19 19 18.3284 19 17.5C19 16.6716 18.3284 16 17.5 16H16ZM10 10V14H14V10H10Z" fill="currentColor"/>',"compass-3":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM16.5 7.5L14 14L7.5 16.5L10 10L16.5 7.5ZM12 13C12.5523 13 13 12.5523 13 12C13 11.4477 12.5523 11 12 11C11.4477 11 11 11.4477 11 12C11 12.5523 11.4477 13 12 13Z" fill="currentColor"/>',cursor:'<path d="M15.3873 13.4975L17.9403 20.5117L13.2418 22.2218L10.6889 15.2076L6.79004 17.6529L8.4086 1.63318L19.9457 12.8646L15.3873 13.4975ZM15.3768 19.3163L12.6618 11.8568L15.6212 11.4459L9.98201 5.9561L9.19088 13.7863L11.7221 12.1988L14.4371 19.6583L15.3768 19.3163Z" fill="currentColor"/>',debian:'<path fill="currentColor" d="M13.7 3.1c-2.8-.8-6.2.2-7.7 2.4 1.9-1.5 4.6-2 6.7-1.2 2.9 1.1 4.3 4.1 3.2 6.8-.9 2.2-3.1 3.6-5.3 3.4-1.8-.1-3.3-1.2-3.8-2.7-.5-1.4 0-2.9 1.2-3.7 1-.7 2.4-.7 3.3.1.7.6.9 1.6.5 2.4-.3.6-.9 1-1.5.9-.5 0-.9-.4-1-.8-.1-.4.1-.8.4-1 .3-.2.6-.1.8.1-.1-.5-.7-.8-1.2-.6-.7.2-1.1.9-1 1.6.1 1 1 1.7 2 1.8 1.2.1 2.4-.6 2.9-1.7.7-1.5.2-3.3-1.1-4.3-1.6-1.3-4-1.3-5.7-.1-2.1 1.5-2.9 4.2-2 6.6 1 2.7 3.6 4.5 6.6 4.7 3.8.2 7.4-2.1 8.8-5.6 1.7-4.2-.6-7.8-4.1-9.1Z"/>',"delete-bin":'<path d="M17 6H22V8H20V21C20 21.5523 19.5523 22 19 22H5C4.44772 22 4 21.5523 4 21V8H2V6H7V3C7 2.44772 7.44772 2 8 2H16C16.5523 2 17 2.44772 17 3V6ZM18 8H6V20H18V8ZM9 11H11V17H9V11ZM13 11H15V17H13V11ZM9 4V6H15V4H9Z" fill="currentColor"/>',docker:'<path fill="currentColor" d="M13.98 11.08h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9H8.92v1.9Zm-2.53 0h2.12v-1.9H6.39v1.9Zm5.06-2.3h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9H8.92v1.9Zm-2.53 0h2.12v-1.9H6.39v1.9Zm2.53-2.3h2.12v-1.9H8.92v1.9ZM3.86 11.08h2.12v-1.9H3.86v1.9Zm17.9-.13c-.46-.3-1.52-.42-2.31-.27-.1-.78-.54-1.46-1.34-2.08l-.46-.3-.31.45c-.62.93-.79 2.46-.12 3.47-.3.16-.89.38-1.68.36H2.11c-.27 1.57.18 3.63 1.36 5.05 1.15 1.38 2.88 2.08 5.15 2.08 4.92 0 8.57-2.27 10.28-6.39.67.01 2.11 0 2.85-1.42.05-.09.23-.46.3-.61l-.29-.34Z"/>',"donut-chart":'<path d="M10.9999 2.04938L11 4.06188C7.05371 4.55396 4 7.92036 4 12C4 16.4183 7.58172 20 12 20C13.8487 20 15.5509 19.3729 16.9055 18.3199L18.3289 19.7428C16.605 21.1536 14.4014 22 12 22C6.47715 22 2 17.5228 2 12C2 6.81468 5.94662 2.55115 10.9999 2.04938ZM21.9506 13.0001C21.7509 15.0111 20.9555 16.8468 19.7433 18.3283L18.3199 16.9055C19.1801 15.799 19.756 14.4606 19.9381 12.9999L21.9506 13.0001ZM13.0011 2.04948C17.725 2.51902 21.4815 6.27589 21.9506 10.9999L19.9381 11C19.4869 7.38162 16.6192 4.51364 13.001 4.062L13.0011 2.04948Z" fill="currentColor"/>',"donut-chart-fill":'<path d="M10.9999 2.04938L11 5.07088C7.6077 5.55612 5 8.47352 5 12C5 15.866 8.13401 19 12 19C13.5723 19 15.0236 18.4816 16.1922 17.6064L18.3289 19.7428C16.605 21.1536 14.4014 22 12 22C6.47715 22 2 17.5228 2 12C2 6.81468 5.94662 2.55115 10.9999 2.04938ZM21.9506 13.0001C21.7509 15.0111 20.9555 16.8468 19.7433 18.3283L17.6064 16.1922C18.2926 15.2759 18.7595 14.1859 18.9291 13L21.9506 13.0001ZM13.0011 2.04948C17.725 2.51902 21.4815 6.27589 21.9506 10.9999L18.9291 10.9998C18.4905 7.93452 16.0661 5.50992 13.001 5.07103L13.0011 2.04948Z" fill="currentColor"/>',download:'<path d="M3 19H21V21H3V19ZM13 13.1716L19.0711 7.1005L20.4853 8.51472L12 17L3.51472 8.51472L4.92893 7.1005L11 13.1716V2H13V13.1716Z" fill="currentColor"/>',"download-cloud":'<path d="M1 14.5C1 12.1716 2.22429 10.1291 4.06426 8.9812C4.56469 5.044 7.92686 2 12 2C16.0731 2 19.4353 5.044 19.9357 8.9812C21.7757 10.1291 23 12.1716 23 14.5C23 17.9216 20.3562 20.7257 17 20.9811L7 21C3.64378 20.7257 1 17.9216 1 14.5ZM16.8483 18.9868C19.1817 18.8093 21 16.8561 21 14.5C21 12.927 20.1884 11.4962 18.8771 10.6781L18.0714 10.1754L17.9517 9.23338C17.5735 6.25803 15.0288 4 12 4C8.97116 4 6.42647 6.25803 6.0483 9.23338L5.92856 10.1754L5.12288 10.6781C3.81156 11.4962 3 12.927 3 14.5C3 16.8561 4.81833 18.8093 7.1517 18.9868L7.325 19H16.675L16.8483 18.9868ZM13 12H16L12 17L8 12H11V8H13V12Z" fill="currentColor"/>',draggable:'<path d="M8.5 7C9.32843 7 10 6.32843 10 5.5C10 4.67157 9.32843 4 8.5 4C7.67157 4 7 4.67157 7 5.5C7 6.32843 7.67157 7 8.5 7ZM8.5 13.5C9.32843 13.5 10 12.8284 10 12C10 11.1716 9.32843 10.5 8.5 10.5C7.67157 10.5 7 11.1716 7 12C7 12.8284 7.67157 13.5 8.5 13.5ZM10 18.5C10 19.3284 9.32843 20 8.5 20C7.67157 20 7 19.3284 7 18.5C7 17.6716 7.67157 17 8.5 17C9.32843 17 10 17.6716 10 18.5ZM15.5 7C16.3284 7 17 6.32843 17 5.5C17 4.67157 16.3284 4 15.5 4C14.6716 4 14 4.67157 14 5.5C14 6.32843 14.6716 7 15.5 7ZM17 12C17 12.8284 16.3284 13.5 15.5 13.5C14.6716 13.5 14 12.8284 14 12C14 11.1716 14.6716 10.5 15.5 10.5C16.3284 10.5 17 11.1716 17 12ZM15.5 20C16.3284 20 17 19.3284 17 18.5C17 17.6716 16.3284 17 15.5 17C14.6716 17 14 17.6716 14 18.5C14 19.3284 14.6716 20 15.5 20Z" fill="currentColor"/>',edit:'<path d="M6.41421 15.89L16.5563 5.74785L15.1421 4.33363L5 14.4758V15.89H6.41421ZM7.24264 17.89H3V13.6473L14.435 2.21231C14.8256 1.82179 15.4587 1.82179 15.8492 2.21231L18.6777 5.04074C19.0682 5.43126 19.0682 6.06443 18.6777 6.45495L7.24264 17.89ZM3 19.89H21V21.89H3V19.89Z" fill="currentColor"/>',equalizer:'<path d="M6.17071 18C6.58254 16.8348 7.69378 16 9 16C10.3062 16 11.4175 16.8348 11.8293 18H22V20H11.8293C11.4175 21.1652 10.3062 22 9 22C7.69378 22 6.58254 21.1652 6.17071 20H2V18H6.17071ZM12.1707 11C12.5825 9.83481 13.6938 9 15 9C16.3062 9 17.4175 9.83481 17.8293 11H22V13H17.8293C17.4175 14.1652 16.3062 15 15 15C13.6938 15 12.5825 14.1652 12.1707 13H2V11H12.1707ZM6.17071 4C6.58254 2.83481 7.69378 2 9 2C10.3062 2 11.4175 2.83481 11.8293 4H22V6H11.8293C11.4175 7.16519 10.3062 8 9 8C7.69378 8 6.58254 7.16519 6.17071 6H2V4H6.17071ZM9 6C9.55228 6 10 5.55228 10 5C10 4.44772 9.55228 4 9 4C8.44772 4 8 4.44772 8 5C8 5.55228 8.44772 6 9 6ZM15 13C15.5523 13 16 12.5523 16 12C16 11.4477 15.5523 11 15 11C14.4477 11 14 11.4477 14 12C14 12.5523 14.4477 13 15 13ZM9 20C9.55228 20 10 19.5523 10 19C10 18.4477 9.55228 18 9 18C8.44772 18 8 18.4477 8 19C8 19.5523 8.44772 20 9 20Z" fill="currentColor"/>',"error-warning":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 15H13V17H11V15ZM11 7H13V13H11V7Z" fill="currentColor"/>',"expand-up-down":'<path d="M18.2072 9.0428 12.0001 2.83569 5.793 9.0428 7.20721 10.457 12.0001 5.66412 16.793 10.457 18.2072 9.0428ZM5.79285 14.9572 12 21.1643 18.2071 14.9572 16.7928 13.543 12 18.3359 7.20706 13.543 5.79285 14.9572Z" fill="currentColor"/>',"external-link":'<path d="M10 6V8H5V19H16V14H18V20C18 20.5523 17.5523 21 17 21H4C3.44772 21 3 20.5523 3 20V7C3 6.44772 3.44772 6 4 6H10ZM21 3V11H19L18.9999 6.413L11.2071 14.2071L9.79289 12.7929L17.5849 5H13V3H21Z" fill="currentColor"/>',eye:'<path d="M12.0003 3C17.3924 3 21.8784 6.87976 22.8189 12C21.8784 17.1202 17.3924 21 12.0003 21C6.60812 21 2.12215 17.1202 1.18164 12C2.12215 6.87976 6.60812 3 12.0003 3ZM12.0003 19C16.2359 19 19.8603 16.052 20.7777 12C19.8603 7.94803 16.2359 5 12.0003 5C7.7646 5 4.14022 7.94803 3.22278 12C4.14022 16.052 7.7646 19 12.0003 19ZM12.0003 16.5C9.51498 16.5 7.50026 14.4853 7.50026 12C7.50026 9.51472 9.51498 7.5 12.0003 7.5C14.4855 7.5 16.5003 9.51472 16.5003 12C16.5003 14.4853 14.4855 16.5 12.0003 16.5ZM12.0003 14.5C13.381 14.5 14.5003 13.3807 14.5003 12C14.5003 10.6193 13.381 9.5 12.0003 9.5C10.6196 9.5 9.50026 10.6193 9.50026 12C9.50026 13.3807 10.6196 14.5 12.0003 14.5Z" fill="currentColor"/>',"eye-off":'<path d="M17.8827 19.2968C16.1814 20.3755 14.1638 21.0002 12.0003 21.0002C6.60812 21.0002 2.12215 17.1204 1.18164 12.0002C1.61832 9.62282 2.81932 7.5129 4.52047 5.93457L1.39366 2.80777L2.80788 1.39355L22.6069 21.1925L21.1927 22.6068L17.8827 19.2968ZM5.9356 7.3497C4.60673 8.56015 3.6378 10.1672 3.22278 12.0002C4.14022 16.0521 7.7646 19.0002 12.0003 19.0002C13.5997 19.0002 15.112 18.5798 16.4243 17.8384L14.396 15.8101C13.7023 16.2472 12.8808 16.5002 12.0003 16.5002C9.51498 16.5002 7.50026 14.4854 7.50026 12.0002C7.50026 11.1196 7.75317 10.2981 8.19031 9.60442L5.9356 7.3497ZM12.9139 14.328L9.67246 11.0866C9.5613 11.3696 9.50026 11.6777 9.50026 12.0002C9.50026 13.3809 10.6196 14.5002 12.0003 14.5002C12.3227 14.5002 12.6309 14.4391 12.9139 14.328ZM20.8068 16.5925L19.376 15.1617C20.0319 14.2268 20.5154 13.1586 20.7777 12.0002C19.8603 7.94818 16.2359 5.00016 12.0003 5.00016C11.1544 5.00016 10.3329 5.11773 9.55249 5.33818L7.97446 3.76015C9.22127 3.26959 10.5793 3.00016 12.0003 3.00016C17.3924 3.00016 21.8784 6.87992 22.8189 12.0002C22.5067 13.6998 21.8038 15.2628 20.8068 16.5925ZM11.7229 7.50857C11.8146 7.50299 11.9071 7.50016 12.0003 7.50016C14.4855 7.50016 16.5003 9.51488 16.5003 12.0002C16.5003 12.0933 16.4974 12.1858 16.4919 12.2775L11.7229 7.50857Z" fill="currentColor"/>',fedora:'<path fill="currentColor" d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2Zm2.9 5.2h-1.35c-.83 0-1.5.67-1.5 1.5v1.35h2.35v2h-2.35v4.15a2.8 2.8 0 0 1-2.8 2.8 2.8 2.8 0 0 1-2.8-2.8c0-1.55 1.25-2.8 2.8-2.8h.8v2h-.8a.8.8 0 1 0 .8.8V8.7a3.5 3.5 0 0 1 3.5-3.5h1.35v2Z"/>',file:'<path d="M9 2.00318V2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8L9 2.00318ZM5.82918 8H9V4.83086L5.82918 8ZM11 4V9C11 9.55228 10.5523 10 10 10H5V20H19V4H11Z" fill="currentColor"/>',"file-add":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11 11V8H13V11H16V13H13V16H11V13H8V11H11Z" fill="currentColor"/>',"file-check":'<path d="M12 20V22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9998 7V14H19V8H15V4H5V20H12ZM14.4646 19.4647L18.0001 23.0002L22.9498 18.0505L21.5356 16.6362L18.0001 20.1718L15.8788 18.0505L14.4646 19.4647Z" fill="currentColor"/>',"file-check-fill":'<path d="M20.9998 7L16 2H3.9985C3.44749 2 3 2.44405 3 2.9918V21.0082C3 21.5447 3.44476 22 3.9934 22H12.3414C12.1203 21.3744 12 20.7013 12 20C12 16.6863 14.6863 14 18 14C19.0928 14 20.1174 14.2922 20.9999 14.8026L20.9998 7ZM14.4646 19.4647L18.0001 23.0002L22.9498 18.0505L21.5356 16.6362L18.0001 20.1718L15.8788 18.0505L14.4646 19.4647Z" fill="currentColor"/>',"file-code":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM17.6569 12L14.1213 15.5355L12.7071 14.1213L14.8284 12L12.7071 9.87868L14.1213 8.46447L17.6569 12ZM6.34315 12L9.87868 8.46447L11.2929 9.87868L9.17157 12L11.2929 14.1213L9.87868 15.5355L6.34315 12Z" fill="currentColor"/>',"file-copy":'<path d="M6.9998 6V3C6.9998 2.44772 7.44752 2 7.9998 2H19.9998C20.5521 2 20.9998 2.44772 20.9998 3V17C20.9998 17.5523 20.5521 18 19.9998 18H16.9998V20.9991C16.9998 21.5519 16.5499 22 15.993 22H4.00666C3.45059 22 3 21.5554 3 20.9991L3.0026 7.00087C3.0027 6.44811 3.45264 6 4.00942 6H6.9998ZM5.00242 8L5.00019 20H14.9998V8H5.00242ZM8.9998 6H16.9998V16H18.9998V4H8.9998V6Z" fill="currentColor"/>',"file-copy-2":'<path d="M6.9998 6V3C6.9998 2.44772 7.44752 2 7.9998 2H19.9998C20.5521 2 20.9998 2.44772 20.9998 3V17C20.9998 17.5523 20.5521 18 19.9998 18H16.9998V20.9991C16.9998 21.5519 16.5499 22 15.993 22H4.00666C3.45059 22 3 21.5554 3 20.9991L3.0026 7.00087C3.0027 6.44811 3.45264 6 4.00942 6H6.9998ZM5.00242 8L5.00019 20H14.9998V8H5.00242ZM8.9998 6H16.9998V16H18.9998V4H8.9998V6ZM7 11H13V13H7V11ZM7 15H13V17H7V15Z" fill="currentColor"/>',"file-download":'<path d="M13 12H16L12 16L8 12H11V8H13V12ZM15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-edit":'<path d="M21 6.75736L19 8.75736V4H10V9H5V20H19V17.2426L21 15.2426V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V6.75736ZM21.7782 8.80761L23.1924 10.2218L15.4142 18L13.9979 17.9979L14 16.5858L21.7782 8.80761Z" fill="currentColor"/>',"file-image":'<path d="M15 8V4H5V20H19V8H15ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11 9.5C11 10.3284 10.3284 11 9.5 11C8.67157 11 8 10.3284 8 9.5C8 8.67157 8.67157 8 9.5 8C10.3284 8 11 8.67157 11 9.5ZM17.5 17L13.5 10L8 17H17.5Z" fill="currentColor"/>',"file-list-2":'<path d="M20 22H4C3.44772 22 3 21.5523 3 21V3C3 2.44772 3.44772 2 4 2H20C20.5523 2 21 2.44772 21 3V21C21 21.5523 20.5523 22 20 22ZM19 20V4H5V20H19ZM8 7H16V9H8V7ZM8 11H16V13H8V11ZM8 15H13V17H8V15Z" fill="currentColor"/>',"file-music":'<path d="M16 8V10H13V14.5C13 15.8807 11.8807 17 10.5 17C9.11929 17 8 15.8807 8 14.5C8 13.1193 9.11929 12 10.5 12C10.6712 12 10.8384 12.0172 11 12.05V8H15V4H5V20H19V8H16ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-pdf":'<path d="M12 16H8V8H12C14.2091 8 16 9.79086 16 12C16 14.2091 14.2091 16 12 16ZM10 10V14H12C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10H10ZM15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-search":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM13.529 14.4464C11.9951 15.3524 9.98633 15.1464 8.66839 13.8284C7.1063 12.2663 7.1063 9.73367 8.66839 8.17157C10.2305 6.60948 12.7631 6.60948 14.3252 8.17157C15.6432 9.48951 15.8492 11.4983 14.9432 13.0322L17.1537 15.2426L15.7395 16.6569L13.529 14.4464ZM12.911 12.4142C13.6921 11.6332 13.6921 10.3668 12.911 9.58579C12.13 8.80474 10.8637 8.80474 10.0826 9.58579C9.30156 10.3668 9.30156 11.6332 10.0826 12.4142C10.8637 13.1953 12.13 13.1953 12.911 12.4142Z" fill="currentColor"/>',"file-text":'<path d="M21 8V20.9932C21 21.5501 20.5552 22 20.0066 22H3.9934C3.44495 22 3 21.556 3 21.0082V2.9918C3 2.45531 3.4487 2 4.00221 2H14.9968L21 8ZM19 9H14V4H5V20H19V9ZM8 7H11V9H8V7ZM8 11H16V13H8V11ZM8 15H16V17H8V15Z" fill="currentColor"/>',"file-transfer":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM12 11V8L16 12L12 16V13H8V11H12Z" fill="currentColor"/>',"file-video":'<path d="M15 4V8H19V20H5V4H15ZM3.9985 2C3.44749 2 3 2.44405 3 2.9918V21.0082C3 21.5447 3.44476 22 3.9934 22H20.0066C20.5551 22 21 21.5489 21 20.9925L20.9997 7L16 2H3.9985ZM15.0008 11.667L10.1219 8.41435C10.0562 8.37054 9.979 8.34717 9.9 8.34717C9.6791 8.34717 9.5 8.52625 9.5 8.74717V15.2524C9.5 15.3314 9.5234 15.4086 9.5672 15.4743C9.6897 15.6581 9.9381 15.7078 10.1219 15.5852L15.0008 12.3326C15.0447 12.3033 15.0824 12.2656 15.1117 12.2217C15.2343 12.0379 15.1846 11.7895 15.0008 11.667Z" fill="currentColor"/>',flask:'<path d="M15.9994 2V4H14.9994V7.24291C14.9994 8.40051 15.2506 9.54432 15.7357 10.5954L20.017 19.8714C20.3641 20.6236 20.0358 21.5148 19.2836 21.8619C19.0865 21.9529 18.8721 22 18.655 22H5.34375C4.51532 22 3.84375 21.3284 3.84375 20.5C3.84375 20.2829 3.89085 20.0685 3.98181 19.8714L8.26306 10.5954C8.74816 9.54432 8.99939 8.40051 8.99939 7.24291V4H7.99939V2H15.9994ZM13.3873 10.0012H10.6115C10.5072 10.3644 10.3823 10.7221 10.2371 11.0724L10.079 11.4335L6.12439 20H17.8734L13.9198 11.4335C13.7054 10.9691 13.5276 10.4902 13.3873 10.0012ZM10.9994 7.24291C10.9994 7.49626 10.9898 7.7491 10.9706 8.00087H13.0282C13.0189 7.87982 13.0119 7.75852 13.0072 7.63704L12.9994 7.24291V4H10.9994V7.24291Z" fill="currentColor"/>',folder:'<path d="M4 5V19H20V7H11.5858L9.58579 5H4ZM12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5Z" fill="currentColor"/>',"folder-3":'<path d="M12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5ZM4 7V19H20V7H4Z" fill="currentColor"/>',"folder-3-fill":'<path d="M22 8V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7H21C21.5523 7 22 7.44772 22 8ZM12.4142 5H2V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5Z" fill="currentColor"/>',"folder-6":'<path d="M2 4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21L3 21C2.45 21 2 20.55 2 20V4ZM10.5858 6L9.58579 5H4V7H9.58579L10.5858 6ZM4 9V19L20 19V7H12.4142L10.4142 9H4Z" fill="currentColor"/>',"folder-add":'<path d="M12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5ZM4 5V19H20V7H11.5858L9.58579 5H4ZM11 12V9H13V12H16V14H13V17H11V14H8V12H11Z" fill="currentColor"/>',"folder-open":'<path d="M3 21C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H20C20.5523 5 21 5.44772 21 6V9H19V7H11.5858L9.58579 5H4V16.998L5.5 11H22.5L20.1894 20.2425C20.0781 20.6877 19.6781 21 19.2192 21H3ZM19.9384 13H7.06155L5.56155 19H18.4384L19.9384 13Z" fill="currentColor"/>',"folder-open-fill":'<path d="M3 21C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H20C20.5523 5 21 5.44772 21 6V9H4V18.996L6 11H22.5L20.1894 20.2425C20.0781 20.6877 19.6781 21 19.2192 21H3Z" fill="currentColor"/>',"folder-received":'<path d="M22 13H20V7H11.5858L9.58579 5H4V19H13V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H21C21.5523 5 22 5.44772 22 6V13ZM20 17H23V19H20V22.5L15 18L20 13.5V17Z" fill="currentColor"/>',folders:'<path d="M6 7V4C6 3.44772 6.44772 3 7 3H13.4142L15.4142 5H21C21.5523 5 22 5.44772 22 6V16C22 16.5523 21.5523 17 21 17H18V20C18 20.5523 17.5523 21 17 21H3C2.44772 21 2 20.5523 2 20V8C2 7.44772 2.44772 7 3 7H6ZM6 9H4V19H16V17H6V9ZM8 5V15H20V7H14.5858L12.5858 5H8Z" fill="currentColor"/>',fullscreen:'<path d="M8 3V5H4V9H2V3H8ZM2 21V15H4V19H8V21H2ZM22 21H16V19H20V15H22V21ZM22 9H20V5H16V3H22V9Z" fill="currentColor"/>',"fullscreen-exit":'<path d="M18 7H22V9H16V3H18V7ZM8 9H2V7H6V3H8V9ZM18 17V21H16V15H22V17H18ZM8 15V21H6V17H2V15H8Z" fill="currentColor"/>',"git-branch":'<path d="M7.10508 15.2101C8.21506 15.6501 9 16.7334 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.30622 8.16519 8.41746 7 8.82929V11.9996C7.83566 11.3719 8.87439 11 10 11H14C15.3835 11 16.5482 10.0635 16.8949 8.78991C15.7849 8.34988 15 7.26661 15 6C15 4.34315 16.3431 3 18 3C19.6569 3 21 4.34315 21 6C21 7.3332 20.1303 8.46329 18.9274 8.85392C18.5222 11.2085 16.4703 13 14 13H10C8.61653 13 7.45179 13.9365 7.10508 15.2101ZM6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17ZM6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5ZM18 5C17.4477 5 17 5.44772 17 6C17 6.55228 17.4477 7 18 7C18.5523 7 19 6.55228 19 6C19 5.44772 18.5523 5 18 5Z" fill="currentColor"/>',"git-commit":'<path d="M15.874 13C15.4299 14.7252 13.8638 16 12 16C10.1362 16 8.57006 14.7252 8.12602 13H3V11H8.12602C8.57006 9.27477 10.1362 8 12 8C13.8638 8 15.4299 9.27477 15.874 11H21V13H15.874ZM12 14C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10C10.8954 10 10 10.8954 10 12C10 13.1046 10.8954 14 12 14Z" fill="currentColor"/>',"git-merge":'<path d="M7.10508 8.78991C7.45179 10.0635 8.61653 11 10 11H14C16.4703 11 18.5222 12.7915 18.9274 15.1461C20.1303 15.5367 21 16.6668 21 18C21 19.6569 19.6569 21 18 21C16.3431 21 15 19.6569 15 18C15 16.7334 15.7849 15.6501 16.8949 15.2101C16.5482 13.9365 15.3835 13 14 13H10C8.87439 13 7.83566 12.6281 7 12.0004V15.1707C8.16519 15.5825 9 16.6938 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.26661 8.21506 8.34988 7.10508 8.78991ZM6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7ZM6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19ZM18 19C18.5523 19 19 18.5523 19 18C19 17.4477 18.5523 17 18 17C17.4477 17 17 17.4477 17 18C17 18.5523 17.4477 19 18 19Z" fill="currentColor"/>',"git-pull-request":'<path d="M15 5H17C18.1046 5 19 5.89543 19 7V15.1707C20.1652 15.5825 21 16.6938 21 18C21 19.6569 19.6569 21 18 21C16.3431 21 15 19.6569 15 18C15 16.6938 15.8348 15.5825 17 15.1707V7H15V10L10.5 6L15 2V5ZM5 8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.30622 8.16519 8.41746 7 8.82929V15.1707C8.16519 15.5825 9 16.6938 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929ZM6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7ZM6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19ZM18 19C18.5523 19 19 18.5523 19 18C19 17.4477 18.5523 17 18 17C17.4477 17 17 17.4477 17 18C17 18.5523 17.4477 19 18 19Z" fill="currentColor"/>',"git-repository":'<path d="M13 21V23.5L10 21.5L7 23.5V21H6.5C4.567 21 3 19.433 3 17.5V5C3 3.34315 4.34315 2 6 2H20C20.5523 2 21 2.44772 21 3V20C21 20.5523 20.5523 21 20 21H13ZM13 19H19V16H6.5C5.67157 16 5 16.6716 5 17.5C5 18.3284 5.67157 19 6.5 19H7V17H13V19ZM19 14V4H6V14.0354C6.1633 14.0121 6.33024 14 6.5 14H19ZM7 5H9V7H7V5ZM7 8H9V10H7V8ZM7 11H9V13H7V11Z" fill="currentColor"/>',github:'<path d="M5.88401 18.6533C5.58404 18.4526 5.32587 18.1975 5.0239 17.8369C4.91473 17.7065 4.47283 17.1524 4.55811 17.2583C4.09533 16.6833 3.80296 16.417 3.50156 16.3089C2.9817 16.1225 2.7114 15.5499 2.89784 15.0301C3.08428 14.5102 3.65685 14.2399 4.17672 14.4263C4.92936 14.6963 5.43847 15.1611 6.12425 16.0143C6.03025 15.8974 6.46364 16.441 6.55731 16.5529C6.74784 16.7804 6.88732 16.9182 6.99629 16.9911C7.20118 17.1283 7.58451 17.1874 8.14709 17.1311C8.17065 16.7489 8.24136 16.3783 8.34919 16.0358C5.38097 15.3104 3.70116 13.3952 3.70116 9.63971C3.70116 8.40085 4.0704 7.28393 4.75917 6.3478C4.5415 5.45392 4.57433 4.37284 5.06092 3.15636C5.1725 2.87739 5.40361 2.66338 5.69031 2.57352C5.77242 2.54973 5.81791 2.53915 5.89878 2.52673C6.70167 2.40343 7.83573 2.69705 9.31449 3.62336C10.181 3.41879 11.0885 3.315 12.0012 3.315C12.9129 3.315 13.8196 3.4186 14.6854 3.62277C16.1619 2.69 17.2986 2.39649 18.1072 2.52651C18.1919 2.54013 18.2645 2.55783 18.3249 2.57766C18.6059 2.66991 18.8316 2.88179 18.9414 3.15636C19.4279 4.37256 19.4608 5.45344 19.2433 6.3472C19.9342 7.28337 20.3012 8.39208 20.3012 9.63971C20.3012 13.3968 18.627 15.3048 15.6588 16.032C15.7837 16.447 15.8496 16.9105 15.8496 17.4121C15.8496 18.0765 15.8471 18.711 15.8424 19.4225C15.8412 19.6127 15.8397 19.8159 15.8375 20.1281C16.2129 20.2109 16.5229 20.5077 16.6031 20.9089C16.7114 21.4504 16.3602 21.9773 15.8186 22.0856C14.6794 22.3134 13.8353 21.5538 13.8353 20.5611C13.8353 20.4708 13.836 20.3417 13.8375 20.1145C13.8398 19.8015 13.8412 19.599 13.8425 19.4094C13.8471 18.7019 13.8496 18.0716 13.8496 17.4121C13.8496 16.7148 13.6664 16.2602 13.4237 16.051C12.7627 15.4812 13.0977 14.3973 13.965 14.2999C16.9314 13.9666 18.3012 12.8177 18.3012 9.63971C18.3012 8.68508 17.9893 7.89571 17.3881 7.23559C17.1301 6.95233 17.0567 6.54659 17.199 6.19087C17.3647 5.77663 17.4354 5.23384 17.2941 4.57702L17.2847 4.57968C16.7928 4.71886 16.1744 5.0198 15.4261 5.5285C15.182 5.69438 14.8772 5.74401 14.5932 5.66413C13.7729 5.43343 12.8913 5.315 12.0012 5.315C11.111 5.315 10.2294 5.43343 9.40916 5.66413C9.12662 5.74359 8.82344 5.69492 8.57997 5.53101C7.8274 5.02439 7.2056 4.72379 6.71079 4.58376C6.56735 5.23696 6.63814 5.77782 6.80336 6.19087C6.94565 6.54659 6.87219 6.95233 6.61423 7.23559C6.01715 7.8912 5.70116 8.69376 5.70116 9.63971C5.70116 12.8116 7.07225 13.9683 10.023 14.2999C10.8883 14.3971 11.2246 15.4769 10.5675 16.0482C10.3751 16.2156 10.1384 16.7802 10.1384 17.4121V20.5611C10.1384 21.5474 9.30356 22.2869 8.17878 22.09C7.63476 21.9948 7.27093 21.4766 7.36613 20.9326C7.43827 20.5204 7.75331 20.2116 8.13841 20.1276V19.1381C7.22829 19.1994 6.47656 19.0498 5.88401 18.6533Z" fill="currentColor"/>',"github-fill":'<path d="M12.001 2C6.47598 2 2.00098 6.475 2.00098 12C2.00098 16.425 4.86348 20.1625 8.83848 21.4875C9.33848 21.575 9.52598 21.275 9.52598 21.0125C9.52598 20.775 9.51348 19.9875 9.51348 19.15C7.00098 19.6125 6.35098 18.5375 6.15098 17.975C6.03848 17.6875 5.55098 16.8 5.12598 16.5625C4.77598 16.375 4.27598 15.9125 5.11348 15.9C5.90098 15.8875 6.46348 16.625 6.65098 16.925C7.55098 18.4375 8.98848 18.0125 9.56348 17.75C9.65098 17.1 9.91348 16.6625 10.201 16.4125C7.97598 16.1625 5.65098 15.3 5.65098 11.475C5.65098 10.3875 6.03848 9.4875 6.67598 8.7875C6.57598 8.5375 6.22598 7.5125 6.77598 6.1375C6.77598 6.1375 7.61348 5.875 9.52598 7.1625C10.326 6.9375 11.176 6.825 12.026 6.825C12.876 6.825 13.726 6.9375 14.526 7.1625C16.4385 5.8625 17.276 6.1375 17.276 6.1375C17.826 7.5125 17.476 8.5375 17.376 8.7875C18.0135 9.4875 18.401 10.375 18.401 11.475C18.401 15.3125 16.0635 16.1625 13.8385 16.4125C14.201 16.725 14.5135 17.325 14.5135 18.2625C14.5135 19.6 14.501 20.675 14.501 21.0125C14.501 21.275 14.6885 21.5875 15.1885 21.4875C19.259 20.1133 21.9999 16.2963 22.001 12C22.001 6.475 17.526 2 12.001 2Z" fill="currentColor"/>',global:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM9.71002 19.6674C8.74743 17.6259 8.15732 15.3742 8.02731 13H4.06189C4.458 16.1765 6.71639 18.7747 9.71002 19.6674ZM10.0307 13C10.1811 15.4388 10.8778 17.7297 12 19.752C13.1222 17.7297 13.8189 15.4388 13.9693 13H10.0307ZM19.9381 13H15.9727C15.8427 15.3742 15.2526 17.6259 14.29 19.6674C17.2836 18.7747 19.542 16.1765 19.9381 13ZM4.06189 11H8.02731C8.15732 8.62577 8.74743 6.37407 9.71002 4.33256C6.71639 5.22533 4.458 7.8235 4.06189 11ZM10.0307 11H13.9693C13.8189 8.56122 13.1222 6.27025 12 4.24799C10.8778 6.27025 10.1811 8.56122 10.0307 11ZM14.29 4.33256C15.2526 6.37407 15.8427 8.62577 15.9727 11H19.9381C19.542 7.8235 17.2836 5.22533 14.29 4.33256Z" fill="currentColor"/>',hammer:'<path d="M20 2C20.5523 2 21 2.44772 21 3V8C21 8.55228 20.5523 9 20 9H15V22C15 22.5523 14.5523 23 14 23H10C9.44772 23 9 22.5523 9 22V9H3.5C2.94772 9 2.5 8.55228 2.5 8V5.61803C2.5 5.23926 2.714 4.893 3.05279 4.72361L8.5 2H20ZM15 4H8.97214L4.5 6.23607V7H11V21H13V7H15V4ZM19 4H17V7H19V4Z" fill="currentColor"/>',history:'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12H4C4 16.4183 7.58172 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C9.25022 4 6.82447 5.38734 5.38451 7.50024L8 7.5V9.5H2V3.5H4L3.99989 5.99918C5.82434 3.57075 8.72873 2 12 2ZM13 7L12.9998 11.585L16.2426 14.8284L14.8284 16.2426L10.9998 12.413L11 7H13Z" fill="currentColor"/>',home:'<path d="M21 20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V9.48907C3 9.18048 3.14247 8.88917 3.38606 8.69972L11.3861 2.47749C11.7472 2.19663 12.2528 2.19663 12.6139 2.47749L20.6139 8.69972C20.8575 8.88917 21 9.18048 21 9.48907V20ZM19 19V9.97815L12 4.53371L5 9.97815V19H19Z" fill="currentColor"/>',hourglass:'<path d="M6 4H4V2H20V4H18V6C18 7.61543 17.1838 8.91468 16.1561 9.97667C15.4532 10.703 14.598 11.372 13.7309 12C14.598 12.628 15.4532 13.297 16.1561 14.0233C17.1838 15.0853 18 16.3846 18 18V20H20V22H4V20H6V18C6 16.3846 6.81616 15.0853 7.8439 14.0233C8.54682 13.297 9.40202 12.628 10.2691 12C9.40202 11.372 8.54682 10.703 7.8439 9.97667C6.81616 8.91468 6 7.61543 6 6V4ZM8 4V6C8 6.88457 8.43384 7.71032 9.2811 8.58583C10.008 9.33699 10.9548 10.0398 12 10.7781C13.0452 10.0398 13.992 9.33699 14.7189 8.58583C15.5662 7.71032 16 6.88457 16 6V4H8ZM12 13.2219C10.9548 13.9602 10.008 14.663 9.2811 15.4142C8.43384 16.2897 8 17.1154 8 18V20H16V18C16 17.1154 15.5662 16.2897 14.7189 15.4142C13.992 14.663 13.0452 13.9602 12 13.2219Z" fill="currentColor"/>',image:'<path d="M2.9918 21C2.44405 21 2 20.5551 2 20.0066V3.9934C2 3.44476 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.44495 22 3.9934V20.0066C22 20.5552 21.5447 21 21.0082 21H2.9918ZM20 15V5H4V19L14 9L20 15ZM20 17.8284L14 11.8284L6.82843 19H20V17.8284ZM8 11C6.89543 11 6 10.1046 6 9C6 7.89543 6.89543 7 8 7C9.10457 7 10 7.89543 10 9C10 10.1046 9.10457 11 8 11Z" fill="currentColor"/>',"image-download":'<path d="M21 15V19H24L20 23L16 19H19V15H21ZM21.0078 3C21.5555 3 21.9999 3.44482 22 3.99316V13H20V5H4V18.999L14 9L17 12V14.8291L14 11.8281L6.82715 19H14V21H2.99219C2.44451 21 2.00013 20.5552 2 20.0068V3.99316C2.00013 3.44463 2.45577 3 2.99219 3H21.0078ZM8 7C9.10457 7 10 7.89543 10 9C10 10.1046 9.10457 11 8 11C6.89543 11 6 10.1046 6 9C6 7.89543 6.89543 7 8 7Z" fill="currentColor"/>',"inbox-archive":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM20 9H4V19H20V9ZM13 10V14H16L12 18L8 14H11V10H13ZM18.7639 5H5.23656L4.23744 7H19.7639L18.7639 5Z" fill="currentColor"/>',"inbox-unarchive":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM20 9H4V19H20V9ZM12 10L16 14H13V18H11V14H8L12 10ZM18.764 5H5.236L4.237 7H19.764L18.764 5Z" fill="currentColor"/>',"inbox-unarchive-fill":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM12 10L8 14H11V18H13V14H16L12 10ZM18.764 5H5.236L4.237 7H19.764L18.764 5Z" fill="currentColor"/>',information:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 7H13V9H11V7ZM11 11H13V17H11V11Z" fill="currentColor"/>',"layout-column":'<path d="M11 5H5V19H11V5ZM13 5V19H19V5H13ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3Z" fill="currentColor"/>',"layout-left":'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM7 5H4V19H7V5ZM20 5H9V19H20V5Z" fill="currentColor"/>',"layout-right":'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM15 5H4V19H15V5ZM20 5H17V19H20V5Z" fill="currentColor"/>',"list-check-2":'<path d="M11 4H21V6H11V4ZM11 8H17V10H11V8ZM11 14H21V16H11V14ZM11 18H17V20H11V18ZM3 4H9V10H3V4ZM5 6V8H7V6H5ZM3 14H9V20H3V14ZM5 16V18H7V16H5Z" fill="currentColor"/>',"list-check-3":'<path d="M8.00008 6V9H5.00008V6H8.00008ZM3.00008 4V11H10.0001V4H3.00008ZM13.0001 4H21.0001V6H13.0001V4ZM13.0001 11H21.0001V13H13.0001V11ZM13.0001 18H21.0001V20H13.0001V18ZM10.7072 16.2071L9.29297 14.7929L6.00008 18.0858L4.20718 16.2929L2.79297 17.7071L6.00008 20.9142L10.7072 16.2071Z" fill="currentColor"/>',"list-unordered":'<path d="M8 4H21V6H8V4ZM4.5 6.5C3.67157 6.5 3 5.82843 3 5C3 4.17157 3.67157 3.5 4.5 3.5C5.32843 3.5 6 4.17157 6 5C6 5.82843 5.32843 6.5 4.5 6.5ZM4.5 13.5C3.67157 13.5 3 12.8284 3 12C3 11.1716 3.67157 10.5 4.5 10.5C5.32843 10.5 6 11.1716 6 12C6 12.8284 5.32843 13.5 4.5 13.5ZM4.5 20.4C3.67157 20.4 3 19.7284 3 18.9C3 18.0716 3.67157 17.4 4.5 17.4C5.32843 17.4 6 18.0716 6 18.9C6 19.7284 5.32843 20.4 4.5 20.4ZM8 11H21V13H8V11ZM8 18H21V20H8V18Z" fill="currentColor"/>',loader:'<path d="M11.9995 2C12.5518 2 12.9995 2.44772 12.9995 3V6C12.9995 6.55228 12.5518 7 11.9995 7C11.4472 7 10.9995 6.55228 10.9995 6V3C10.9995 2.44772 11.4472 2 11.9995 2ZM11.9995 17C12.5518 17 12.9995 17.4477 12.9995 18V21C12.9995 21.5523 12.5518 22 11.9995 22C11.4472 22 10.9995 21.5523 10.9995 21V18C10.9995 17.4477 11.4472 17 11.9995 17ZM20.6597 7C20.9359 7.47829 20.772 8.08988 20.2937 8.36602L17.6956 9.86602C17.2173 10.1422 16.6057 9.97829 16.3296 9.5C16.0535 9.02171 16.2173 8.41012 16.6956 8.13398L19.2937 6.63397C19.772 6.35783 20.3836 6.52171 20.6597 7ZM7.66935 14.5C7.94549 14.9783 7.78161 15.5899 7.30332 15.866L4.70525 17.366C4.22695 17.6422 3.61536 17.4783 3.33922 17C3.06308 16.5217 3.22695 15.9101 3.70525 15.634L6.30332 14.134C6.78161 13.8578 7.3932 14.0217 7.66935 14.5ZM20.6597 17C20.3836 17.4783 19.772 17.6422 19.2937 17.366L16.6956 15.866C16.2173 15.5899 16.0535 14.9783 16.3296 14.5C16.6057 14.0217 17.2173 13.8578 17.6956 14.134L20.2937 15.634C20.772 15.9101 20.9359 16.5217 20.6597 17ZM7.66935 9.5C7.3932 9.97829 6.78161 10.1422 6.30332 9.86602L3.70525 8.36602C3.22695 8.08988 3.06308 7.47829 3.33922 7C3.61536 6.52171 4.22695 6.35783 4.70525 6.63397L7.30332 8.13398C7.78161 8.41012 7.94549 9.02171 7.66935 9.5Z" fill="currentColor"/>',"loader-4":'<path d="M18.364 5.63604L16.9497 7.05025C15.683 5.7835 13.933 5 12 5C8.13401 5 5 8.13401 5 12C5 15.866 8.13401 19 12 19C15.866 19 19 15.866 19 12H21C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C14.4853 3 16.7353 4.00736 18.364 5.63604Z" fill="currentColor"/>',lock:'<path d="M19 10H20C20.5523 10 21 10.4477 21 11V21C21 21.5523 20.5523 22 20 22H4C3.44772 22 3 21.5523 3 21V11C3 10.4477 3.44772 10 4 10H5V9C5 5.13401 8.13401 2 12 2C15.866 2 19 5.13401 19 9V10ZM5 12V20H19V12H5ZM11 14H13V18H11V14ZM17 10V9C17 6.23858 14.7614 4 12 4C9.23858 4 7 6.23858 7 9V10H17Z" fill="currentColor"/>',"lock-unlock":'<path d="M7 10H20C20.5523 10 21 10.4477 21 11V21C21 21.5523 20.5523 22 20 22H4C3.44772 22 3 21.5523 3 21V11C3 10.4477 3.44772 10 4 10H5V9C5 5.13401 8.13401 2 12 2C14.7405 2 17.1131 3.5748 18.2624 5.86882L16.4731 6.76344C15.6522 5.12486 13.9575 4 12 4C9.23858 4 7 6.23858 7 9V10ZM5 12V20H19V12H5ZM10 15H14V17H10V15Z" fill="currentColor"/>',"menu-2":'<path d="M3 4H21V6H3V4ZM3 11H15V13H3V11ZM3 18H21V20H3V18Z" fill="currentColor"/>',"menu-fold-2":'<path d="M4.40347 3.90332L2.98926 5.31753L6.17124 8.49951L2.98926 11.6815L4.40347 13.0957L8.99967 8.49951L4.40347 3.90332ZM20.9997 19.9995V17.9995H2.99967V19.9995H20.9997ZM20.9997 12.9995V10.9995H11.9997V12.9995H20.9997ZM20.9997 5.99951V3.99951H11.9997V5.99951H20.9997Z" fill="currentColor"/>',"menu-search":'<path d="M15.5 5C13.567 5 12 6.567 12 8.5C12 10.433 13.567 12 15.5 12C17.433 12 19 10.433 19 8.5C19 6.567 17.433 5 15.5 5ZM10 8.5C10 5.46243 12.4624 3 15.5 3C18.5376 3 21 5.46243 21 8.5C21 9.6575 20.6424 10.7315 20.0317 11.6175L22.7071 14.2929L21.2929 15.7071L18.6175 13.0317C17.7315 13.6424 16.6575 14 15.5 14C12.4624 14 10 11.5376 10 8.5ZM3 4H8V6H3V4ZM3 11H8V13H3V11ZM21 18V20H3V18H21Z" fill="currentColor"/>',mic:'<path d="M11.9998 3C10.3429 3 8.99976 4.34315 8.99976 6V10C8.99976 11.6569 10.3429 13 11.9998 13C13.6566 13 14.9998 11.6569 14.9998 10V6C14.9998 4.34315 13.6566 3 11.9998 3ZM11.9998 1C14.7612 1 16.9998 3.23858 16.9998 6V10C16.9998 12.7614 14.7612 15 11.9998 15C9.23833 15 6.99976 12.7614 6.99976 10V6C6.99976 3.23858 9.23833 1 11.9998 1ZM3.05469 11H5.07065C5.55588 14.3923 8.47329 17 11.9998 17C15.5262 17 18.4436 14.3923 18.9289 11H20.9448C20.4837 15.1716 17.1714 18.4839 12.9998 18.9451V23H10.9998V18.9451C6.82814 18.4839 3.51584 15.1716 3.05469 11Z" fill="currentColor"/>',more:'<path d="M4.5 10.5C3.675 10.5 3 11.175 3 12C3 12.825 3.675 13.5 4.5 13.5C5.325 13.5 6 12.825 6 12C6 11.175 5.325 10.5 4.5 10.5ZM19.5 10.5C18.675 10.5 18 11.175 18 12C18 12.825 18.675 13.5 19.5 13.5C20.325 13.5 21 12.825 21 12C21 11.175 20.325 10.5 19.5 10.5ZM12 10.5C11.175 10.5 10.5 11.175 10.5 12C10.5 12.825 11.175 13.5 12 13.5C12.825 13.5 13.5 12.825 13.5 12C13.5 11.175 12.825 10.5 12 10.5Z" fill="currentColor"/>',"more-2":'<path d="M12 3C11.175 3 10.5 3.675 10.5 4.5C10.5 5.325 11.175 6 12 6C12.825 6 13.5 5.325 13.5 4.5C13.5 3.675 12.825 3 12 3ZM12 18C11.175 18 10.5 18.675 10.5 19.5C10.5 20.325 11.175 21 12 21C12.825 21 13.5 20.325 13.5 19.5C13.5 18.675 12.825 18 12 18ZM12 10.5C11.175 10.5 10.5 11.175 10.5 12C10.5 12.825 11.175 13.5 12 13.5C12.825 13.5 13.5 12.825 13.5 12C13.5 11.175 12.825 10.5 12 10.5Z" fill="currentColor"/>',"more-2-fill":'<path d="M12 3C10.9 3 10 3.9 10 5C10 6.1 10.9 7 12 7C13.1 7 14 6.1 14 5C14 3.9 13.1 3 12 3ZM12 17C10.9 17 10 17.9 10 19C10 20.1 10.9 21 12 21C13.1 21 14 20.1 14 19C14 17.9 13.1 17 12 17ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10Z" fill="currentColor"/>',"more-fill":'<path d="M5 10C3.9 10 3 10.9 3 12C3 13.1 3.9 14 5 14C6.1 14 7 13.1 7 12C7 10.9 6.1 10 5 10ZM19 10C17.9 10 17 10.9 17 12C17 13.1 17.9 14 19 14C20.1 14 21 13.1 21 12C21 10.9 20.1 10 19 10ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10Z" fill="currentColor"/>',nixos:'<path fill="currentColor" d="m7.1 4.2 2.05 3.55-1.18 2.04L4.75 4.2H7.1Zm4.9-2.1 2.05 3.55h2.36L14.36 2.1H12Zm4.9 2.1-4.73 8.2h2.36l4.73-8.2H16.9Zm2.84 4.9h-4.1l-1.18 2.04h6.46l-1.18-2.04Zm-2.84 10.7-2.05-3.55 1.18-2.04 3.22 5.59H16.9ZM12 21.9l-2.05-3.55H7.59l2.05 3.55H12Zm-4.9-2.1 4.73-8.2H9.47l-4.73 8.2H7.1ZM4.26 14.9h4.1l1.18-2.04H3.08l1.18 2.04Z"/>',"node-tree":'<path d="M10 2C10.5523 2 11 2.44772 11 3V7C11 7.55228 10.5523 8 10 8H8V10H13V9C13 8.44772 13.4477 8 14 8H20C20.5523 8 21 8.44772 21 9V13C21 13.5523 20.5523 14 20 14H14C13.4477 14 13 13.5523 13 13V12H8V18H13V17C13 16.4477 13.4477 16 14 16H20C20.5523 16 21 16.4477 21 17V21C21 21.5523 20.5523 22 20 22H14C13.4477 22 13 21.5523 13 21V20H7C6.44772 20 6 19.5523 6 19V8H4C3.44772 8 3 7.55228 3 7V3C3 2.44772 3.44772 2 4 2H10ZM19 18H15V20H19V18ZM19 10H15V12H19V10ZM9 4H5V6H9V4Z" fill="currentColor"/>',"notification-3":'<path d="M20 17H22V19H2V17H4V10C4 5.58172 7.58172 2 12 2C16.4183 2 20 5.58172 20 10V17ZM18 17V10C18 6.68629 15.3137 4 12 4C8.68629 4 6 6.68629 6 10V17H18ZM9 21H15V23H9V21Z" fill="currentColor"/>',palette:'<path d="M12 2C17.5222 2 22 5.97778 22 10.8889C22 13.9556 19.5111 16.4444 16.4444 16.4444H14.4778C13.5556 16.4444 12.8111 17.1889 12.8111 18.1111C12.8111 18.5333 12.9778 18.9222 13.2333 19.2111C13.5 19.5111 13.6667 19.9 13.6667 20.3333C13.6667 21.2556 12.9 22 12 22C6.47778 22 2 17.5222 2 12C2 6.47778 6.47778 2 12 2ZM10.8111 18.1111C10.8111 16.0843 12.451 14.4444 14.4778 14.4444H16.4444C18.4065 14.4444 20 12.851 20 10.8889C20 7.1392 16.4677 4 12 4C7.58235 4 4 7.58235 4 12C4 16.19 7.2226 19.6285 11.324 19.9718C10.9948 19.4168 10.8111 18.7761 10.8111 18.1111ZM7.5 12C6.67157 12 6 11.3284 6 10.5C6 9.67157 6.67157 9 7.5 9C8.32843 9 9 9.67157 9 10.5C9 11.3284 8.32843 12 7.5 12ZM16.5 12C15.6716 12 15 11.3284 15 10.5C15 9.67157 15.6716 9 16.5 9C17.3284 9 18 9.67157 18 10.5C18 11.3284 17.3284 12 16.5 12ZM12 9C11.1716 9 10.5 8.32843 10.5 7.5C10.5 6.67157 11.1716 6 12 6C12.8284 6 13.5 6.67157 13.5 7.5C13.5 8.32843 12.8284 9 12 9Z" fill="currentColor"/>',pencil:'<path d="M15.7279 9.57627L14.3137 8.16206L5 17.4758V18.89H6.41421L15.7279 9.57627ZM17.1421 8.16206L18.5563 6.74785L17.1421 5.33363L15.7279 6.74785L17.1421 8.16206ZM7.24264 20.89H3V16.6473L16.435 3.21231C16.8256 2.82179 17.4587 2.82179 17.8492 3.21231L20.6777 6.04074C21.0682 6.43126 21.0682 7.06443 20.6777 7.45495L7.24264 20.89Z" fill="currentColor"/>',"pencil-ai":'<path d="M16.4356 3.21188C16.8261 2.82185 17.4592 2.82157 17.8496 3.21188L20.6777 6.04099C21.0681 6.43152 21.0682 7.06457 20.6777 7.45505L7.2422 20.8896H3.00001V16.6475L16.4356 3.21188ZM5.00001 17.4756V18.8896H6.41407L15.7276 9.57615L14.3135 8.16208L5.00001 17.4756ZM4.5293 1.3193C4.70583 0.893505 5.29418 0.893508 5.47071 1.3193L5.72364 1.93063C6.15555 2.97342 6.96155 3.80613 7.97462 4.2568L8.69239 4.57614C9.10267 4.75896 9.10262 5.35616 8.69239 5.53903L7.93263 5.87692C6.94497 6.3162 6.15339 7.11943 5.71387 8.1279L5.4668 8.69334C5.28636 9.10747 4.71366 9.10747 4.53321 8.69334L4.28614 8.1279C3.84661 7.11943 3.05506 6.3162 2.06739 5.87692L1.30762 5.53903C0.897483 5.35617 0.897435 4.75896 1.30762 4.57614L2.0254 4.2568C3.03845 3.80614 3.84446 2.97344 4.27637 1.93063L4.5293 1.3193ZM15.7276 6.74802L17.1426 8.16208L18.5567 6.74802L17.1426 5.33395L15.7276 6.74802Z" fill="currentColor"/>',pichamber:'<g transform="translate(12 12) scale(0.22) translate(-50 -50)"><path d="M50 3 91 27 50 51 9 27Z" fill="currentColor" fill-opacity="0.08"/><path d="M9 27 50 51V97L9 73Z" fill="currentColor" fill-opacity="0.15"/><path d="M50 51 91 27V73L50 97Z" fill="currentColor" fill-opacity="0.24"/><path d="M50 3 91 27V73L50 97 9 73V27Z" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></g>',"picture-in-picture-2":'<path d="M21 3C21.5523 3 22 3.44772 22 4V11H20V5H4V19H10V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM21 13C21.5523 13 22 13.4477 22 14V20C22 20.5523 21.5523 21 21 21H13C12.4477 21 12 20.5523 12 20V14C12 13.4477 12.4477 13 13 13H21ZM20 15H14V19H20V15ZM6.70711 6.29289L8.95689 8.54289L11 6.5V12H5.5L7.54289 9.95689L5.29289 7.70711L6.70711 6.29289Z" fill="currentColor"/>',"pie-chart":'<path d="M9 2.4578V4.58152C6.06817 5.76829 4 8.64262 4 12C4 16.4183 7.58172 20 12 20C15.3574 20 18.2317 17.9318 19.4185 15H21.5422C20.2679 19.0571 16.4776 22 12 22C6.47715 22 2 17.5228 2 12C2 7.52236 4.94289 3.73207 9 2.4578ZM12 2C17.5228 2 22 6.47715 22 12C22 12.3375 21.9833 12.6711 21.9506 13H11V2.04938C11.3289 2.01672 11.6625 2 12 2ZM13 4.06189V11H19.9381C19.4869 7.38128 16.6187 4.51314 13 4.06189Z" fill="currentColor"/>',play:'<path d="M16.3944 12.0001L10 7.7371V16.263L16.3944 12.0001ZM19.376 12.4161L8.77735 19.4818C8.54759 19.635 8.23715 19.5729 8.08397 19.3432C8.02922 19.261 8 19.1645 8 19.0658V4.93433C8 4.65818 8.22386 4.43433 8.5 4.43433C8.59871 4.43433 8.69522 4.46355 8.77735 4.5183L19.376 11.584C19.6057 11.7372 19.6678 12.0477 19.5146 12.2774C19.478 12.3323 19.4309 12.3795 19.376 12.4161Z" fill="currentColor"/>',"play-list-add":'<path d="M2 18H12V20H2V18ZM2 11H22V13H2V11ZM2 4H22V6H2V4ZM18 18V15H20V18H23V20H20V23H18V20H15V18H18Z" fill="currentColor"/>',"plug-2":'<path d="M13 18V20H19V22H13C11.8954 22 11 21.1046 11 20V18H8C5.79086 18 4 16.2091 4 14V7C4 6.44772 4.44772 6 5 6H7V2H9V6H15V2H17V6H19C19.5523 6 20 6.44772 20 7V14C20 16.2091 18.2091 18 16 18H13ZM8 16H16C17.1046 16 18 15.1046 18 14V11H6V14C6 15.1046 6.89543 16 8 16ZM18 8H6V9H18V8ZM12 14.5C11.4477 14.5 11 14.0523 11 13.5C11 12.9477 11.4477 12.5 12 12.5C12.5523 12.5 13 12.9477 13 13.5C13 14.0523 12.5523 14.5 12 14.5ZM11 2H13V5H11V2Z" fill="currentColor"/>',pushpin:'<path d="M13.8273 1.69L22.3126 10.1753L20.8984 11.5895L20.1913 10.8824L15.9486 15.125L15.2415 18.6606L13.8273 20.0748L9.58466 15.8321L4.63492 20.7819L3.2207 19.3677L8.17045 14.4179L3.92781 10.1753L5.34202 8.76107L8.87756 8.05396L13.1202 3.81132L12.4131 3.10422L13.8273 1.69ZM14.5344 5.22554L9.86358 9.89637L7.0417 10.4607L13.5418 16.9609L14.1062 14.139L18.7771 9.46818L14.5344 5.22554Z" fill="currentColor"/>',"pushpin-2":'<path d="M18 3V5H17V11L19 14V16H13V23H11V16H5V14L7 11V5H6V3H18ZM9 5V11.6056L7.4037 14H16.5963L15 11.6056V5H9Z" fill="currentColor"/>',"pushpin-2-fill":'<path d="M18 3V5H17V11L19 14V16H13V23H11V16H5V14L7 11V5H6V3H18Z" fill="currentColor"/>',puzzle:'<path d="M7 5C7 2.79086 8.79086 1 11 1C13.2091 1 15 2.79086 15 5H18C18.5523 5 19 5.44772 19 6V9C21.2091 9 23 10.7909 23 13C23 15.2091 21.2091 17 19 17V20C19 20.5523 18.5523 21 18 21H4C3.44772 21 3 20.5523 3 20V6C3 5.44772 3.44772 5 4 5H7ZM11 3C9.89543 3 9 3.89543 9 5C9 5.23554 9.0403 5.45952 9.11355 5.66675C9.22172 5.97282 9.17461 6.31235 8.98718 6.57739C8.79974 6.84243 8.49532 7 8.17071 7H5V19H17V15.8293C17 15.5047 17.1576 15.2003 17.4226 15.0128C17.6877 14.8254 18.0272 14.7783 18.3332 14.8865C18.5405 14.9597 18.7645 15 19 15C20.1046 15 21 14.1046 21 13C21 11.8954 20.1046 11 19 11C18.7645 11 18.5405 11.0403 18.3332 11.1135C18.0272 11.2217 17.6877 11.1746 17.4226 10.9872C17.1576 10.7997 17 10.4953 17 10.1707V7H13.8293C13.5047 7 13.2003 6.84243 13.0128 6.57739C12.8254 6.31235 12.7783 5.97282 12.8865 5.66675C12.9597 5.45952 13 5.23555 13 5C13 3.89543 12.1046 3 11 3Z" fill="currentColor"/>',question:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 15H13V17H11V15ZM13 13.3551V14H11V12.5C11 11.9477 11.4477 11.5 12 11.5C12.8284 11.5 13.5 10.8284 13.5 10C13.5 9.17157 12.8284 8.5 12 8.5C11.2723 8.5 10.6656 9.01823 10.5288 9.70577L8.56731 9.31346C8.88637 7.70919 10.302 6.5 12 6.5C13.933 6.5 15.5 8.067 15.5 10C15.5 11.5855 14.4457 12.9248 13 13.3551Z" fill="currentColor"/>',"record-circle":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12C15 13.6569 13.6569 15 12 15Z" fill="currentColor"/>',refresh:'<path d="M5.46257 4.43262C7.21556 2.91688 9.5007 2 12 2C17.5228 2 22 6.47715 22 12C22 14.1361 21.3302 16.1158 20.1892 17.7406L17 12H20C20 7.58172 16.4183 4 12 4C9.84982 4 7.89777 4.84827 6.46023 6.22842L5.46257 4.43262ZM18.5374 19.5674C16.7844 21.0831 14.4993 22 12 22C6.47715 22 2 17.5228 2 12C2 9.86386 2.66979 7.88416 3.8108 6.25944L7 12H4C4 16.4183 7.58172 20 12 20C14.1502 20 16.1022 19.1517 17.5398 17.7716L18.5374 19.5674Z" fill="currentColor"/>',restart:'<path d="M18.5374 19.5674C16.7844 21.0831 14.4993 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 14.1361 21.3302 16.1158 20.1892 17.7406L17 12H20C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20C14.1502 20 16.1022 19.1517 17.5398 17.7716L18.5374 19.5674Z" fill="currentColor"/>',"robot-2":'<path d="M13.5 2C13.5 2.44425 13.3069 2.84339 13 3.11805V5H18C19.6569 5 21 6.34315 21 8V18C21 19.6569 19.6569 21 18 21H6C4.34315 21 3 19.6569 3 18V8C3 6.34315 4.34315 5 6 5H11V3.11805C10.6931 2.84339 10.5 2.44425 10.5 2C10.5 1.17157 11.1716 0.5 12 0.5C12.8284 0.5 13.5 1.17157 13.5 2ZM6 7C5.44772 7 5 7.44772 5 8V18C5 18.5523 5.44772 19 6 19H18C18.5523 19 19 18.5523 19 18V8C19 7.44772 18.5523 7 18 7H13H11H6ZM2 10H0V16H2V10ZM22 10H24V16H22V10ZM9 14.5C9.82843 14.5 10.5 13.8284 10.5 13C10.5 12.1716 9.82843 11.5 9 11.5C8.17157 11.5 7.5 12.1716 7.5 13C7.5 13.8284 8.17157 14.5 9 14.5ZM15 14.5C15.8284 14.5 16.5 13.8284 16.5 13C16.5 12.1716 15.8284 11.5 15 11.5C14.1716 11.5 13.5 12.1716 13.5 13C13.5 13.8284 14.1716 14.5 15 14.5Z" fill="currentColor"/>',rocket:'<path d="M4.99958 12.9999C4.99958 7.91198 7.90222 3.5636 11.9996 1.81799C16.0969 3.5636 18.9996 7.91198 18.9996 12.9999C18.9996 13.8229 18.9236 14.6264 18.779 15.4027L20.7194 17.2353C20.8845 17.3913 20.9238 17.6389 20.815 17.8383L18.3196 22.4133C18.1873 22.6557 17.8836 22.7451 17.6412 22.6128C17.5993 22.59 17.5608 22.5612 17.5271 22.5274L15.2925 20.2928C15.1049 20.1053 14.8506 19.9999 14.5854 19.9999H9.41379C9.14857 19.9999 8.89422 20.1053 8.70668 20.2928L6.47209 22.5274C6.27683 22.7227 5.96025 22.7227 5.76498 22.5274C5.73122 22.4937 5.70246 22.4552 5.67959 22.4133L3.18412 17.8383C3.07537 17.6389 3.11464 17.3913 3.27975 17.2353L5.22014 15.4027C5.07551 14.6264 4.99958 13.8229 4.99958 12.9999ZM6.47542 19.6957L7.29247 18.8786C7.85508 18.316 8.61814 17.9999 9.41379 17.9999H14.5854C15.381 17.9999 16.1441 18.316 16.7067 18.8786L17.5237 19.6957L18.5056 17.8955L17.4058 16.8568C16.9117 16.3901 16.6884 15.7045 16.8128 15.0364C16.9366 14.3722 16.9996 13.6911 16.9996 12.9999C16.9996 9.13037 15.0045 5.69965 11.9996 4.04033C8.99462 5.69965 6.99958 9.13037 6.99958 12.9999C6.99958 13.6911 7.06255 14.3722 7.18631 15.0364C7.31078 15.7045 7.08746 16.3901 6.59338 16.8568L5.49353 17.8955L6.47542 19.6957ZM11.9996 12.9999C10.895 12.9999 9.99958 12.1045 9.99958 10.9999C9.99958 9.89537 10.895 8.99994 11.9996 8.99994C13.1041 8.99994 13.9996 9.89537 13.9996 10.9999C13.9996 12.1045 13.1041 12.9999 11.9996 12.9999Z" fill="currentColor"/>',"save-3":'<path d="M18 19H19V6.82843L17.1716 5H16V9H7V5H5V19H6V12H18V19ZM4 3H18L20.7071 5.70711C20.8946 5.89464 21 6.149 21 6.41421V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM8 14V19H16V14H8Z" fill="currentColor"/>',"scan-2":'<path d="M5.67127 4.25705L13.4142 12L12 13.4142L8.55382 9.96803C8.20193 10.5635 8 11.2582 8 12C8 14.2091 9.79086 16 12 16C14.2091 16 16 14.2091 16 12C16 9.87494 14.3429 8.13693 12.2503 8.00771L10.4459 6.20323C10.9416 6.07067 11.4625 6 12 6C15.3137 6 18 8.68629 18 12C18 15.3137 15.3137 18 12 18C8.68629 18 6 15.3137 6 12C6 10.7042 6.41079 9.50428 7.10925 8.52347L5.68014 7.09436C4.62708 8.44904 4 10.1513 4 12C4 16.4183 7.58172 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C10.8915 4 9.83557 4.22547 8.8757 4.63306L7.37443 3.13179C8.75768 2.40883 10.3311 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 8.87842 3.43029 6.09091 5.67127 4.25705Z" fill="currentColor"/>',search:'<path d="M18.031 16.6168L22.3137 20.8995L20.8995 22.3137L16.6168 18.031C15.0769 19.263 13.124 20 11 20C6.032 20 2 15.968 2 11C2 6.032 6.032 2 11 2C15.968 2 20 6.032 20 11C20 13.124 19.263 15.0769 18.031 16.6168ZM16.0247 15.8748C17.2475 14.6146 18 12.8956 18 11C18 7.1325 14.8675 4 11 4C7.1325 4 4 7.1325 4 11C4 14.8675 7.1325 18 11 18C12.8956 18 14.6146 17.2475 15.8748 16.0247L16.0247 15.8748Z" fill="currentColor"/>',"send-plane":'<path d="M21.7267 2.95694L16.2734 22.0432C16.1225 22.5716 15.7979 22.5956 15.5563 22.1126L11 13L1.9229 9.36919C1.41322 9.16532 1.41953 8.86022 1.95695 8.68108L21.0432 2.31901C21.5716 2.14285 21.8747 2.43866 21.7267 2.95694ZM19.0353 5.09647L6.81221 9.17085L12.4488 11.4255L15.4895 17.5068L19.0353 5.09647Z" fill="currentColor"/>',"send-plane-2":'<path d="M3.5 1.34558C3.58425 1.34558 3.66714 1.36687 3.74096 1.40747L22.2034 11.5618C22.4454 11.6949 22.5337 11.9989 22.4006 12.2409C22.3549 12.324 22.2865 12.3924 22.2034 12.4381L3.74096 22.5924C3.499 22.7255 3.19497 22.6372 3.06189 22.3953C3.02129 22.3214 3 22.2386 3 22.1543V1.84558C3 1.56944 3.22386 1.34558 3.5 1.34558ZM5 4.38249V10.9999H10V12.9999H5V19.6174L18.8499 11.9999L5 4.38249Z" fill="currentColor"/>',server:'<path d="M5 11H19V5H5V11ZM21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20C20.5523 3 21 3.44772 21 4ZM19 13H5V19H19V13ZM7 15H10V17H7V15ZM7 7H10V9H7V7Z" fill="currentColor"/>',"settings-3":'<path d="M3.33946 17.0002C2.90721 16.2515 2.58277 15.4702 2.36133 14.6741C3.3338 14.1779 3.99972 13.1668 3.99972 12.0002C3.99972 10.8345 3.3348 9.824 2.36353 9.32741C2.81025 7.71651 3.65857 6.21627 4.86474 4.99001C5.7807 5.58416 6.98935 5.65534 7.99972 5.072C9.01009 4.48866 9.55277 3.40635 9.4962 2.31604C11.1613 1.8846 12.8847 1.90004 14.5031 2.31862C14.4475 3.40806 14.9901 4.48912 15.9997 5.072C17.0101 5.65532 18.2187 5.58416 19.1346 4.99007C19.7133 5.57986 20.2277 6.25151 20.66 7.00021C21.0922 7.7489 21.4167 8.53025 21.6381 9.32628C20.6656 9.82247 19.9997 10.8336 19.9997 12.0002C19.9997 13.166 20.6646 14.1764 21.6359 14.673C21.1892 16.2839 20.3409 17.7841 19.1347 19.0104C18.2187 18.4163 17.0101 18.3451 15.9997 18.9284C14.9893 19.5117 14.4467 20.5941 14.5032 21.6844C12.8382 22.1158 11.1148 22.1004 9.49633 21.6818C9.55191 20.5923 9.00929 19.5113 7.99972 18.9284C6.98938 18.3451 5.78079 18.4162 4.86484 19.0103C4.28617 18.4205 3.77172 17.7489 3.33946 17.0002ZM8.99972 17.1964C10.0911 17.8265 10.8749 18.8227 11.2503 19.9659C11.7486 20.0133 12.2502 20.014 12.7486 19.9675C13.1238 18.8237 13.9078 17.8268 14.9997 17.1964C16.0916 16.5659 17.347 16.3855 18.5252 16.6324C18.8146 16.224 19.0648 15.7892 19.2729 15.334C18.4706 14.4373 17.9997 13.2604 17.9997 12.0002C17.9997 10.74 18.4706 9.5632 19.2729 8.6665C19.1688 8.4405 19.0538 8.21822 18.9279 8.00021C18.802 7.78219 18.667 7.57148 18.5233 7.36842C17.3457 7.61476 16.0911 7.43414 14.9997 6.80405C13.9083 6.17395 13.1246 5.17768 12.7491 4.03455C12.2509 3.98714 11.7492 3.98646 11.2509 4.03292C10.8756 5.17671 10.0916 6.17364 8.99972 6.80405C7.9078 7.43447 6.65245 7.61494 5.47428 7.36803C5.18485 7.77641 4.93463 8.21117 4.72656 8.66637C5.52881 9.56311 5.99972 10.74 5.99972 12.0002C5.99972 13.2604 5.52883 14.4372 4.72656 15.3339C4.83067 15.5599 4.94564 15.7822 5.07152 16.0002C5.19739 16.2182 5.3324 16.4289 5.47612 16.632C6.65377 16.3857 7.90838 16.5663 8.99972 17.1964ZM11.9997 15.0002C10.3429 15.0002 8.99972 13.6571 8.99972 12.0002C8.99972 10.3434 10.3429 9.00021 11.9997 9.00021C13.6566 9.00021 14.9997 10.3434 14.9997 12.0002C14.9997 13.6571 13.6566 15.0002 11.9997 15.0002ZM11.9997 13.0002C12.552 13.0002 12.9997 12.5525 12.9997 12.0002C12.9997 11.4479 12.552 11.0002 11.9997 11.0002C11.4474 11.0002 10.9997 11.4479 10.9997 12.0002C10.9997 12.5525 11.4474 13.0002 11.9997 13.0002Z" fill="currentColor"/>',"shield-keyhole":'<path d="M12 1L20.2169 2.82598C20.6745 2.92766 21 3.33347 21 3.80217V13.7889C21 15.795 19.9974 17.6684 18.3282 18.7812L12 23L5.6718 18.7812C4.00261 17.6684 3 15.795 3 13.7889V3.80217C3 3.33347 3.32553 2.92766 3.78307 2.82598L12 1ZM12 3.04879L5 4.60434V13.7889C5 15.1263 5.6684 16.3752 6.7812 17.1171L12 20.5963L17.2188 17.1171C18.3316 16.3752 19 15.1263 19 13.7889V4.60434L12 3.04879ZM12 7C13.1046 7 14 7.89543 14 9C14 9.73984 13.5983 10.3858 13.0011 10.7318L13 15H11L10.9999 10.7324C10.4022 10.3866 10 9.74025 10 9C10 7.89543 10.8954 7 12 7Z" fill="currentColor"/>',"split-cells-horizontal":'<path d="M20 3C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20ZM11 5H5V19H11V15H13V19H19V5H13V9H11V5ZM15 9L18 12L15 15V13H9V15L6 12L9 9V11H15V9Z" fill="currentColor"/>',stack:'<path d="M20.0833 15.1999L21.2854 15.9212C21.5221 16.0633 21.5989 16.3704 21.4569 16.6072C21.4146 16.6776 21.3557 16.7365 21.2854 16.7787L12.5144 22.0412C12.1977 22.2313 11.8021 22.2313 11.4854 22.0412L2.71451 16.7787C2.47772 16.6366 2.40093 16.3295 2.54301 16.0927C2.58523 16.0223 2.64413 15.9634 2.71451 15.9212L3.9166 15.1999L11.9999 20.0499L20.0833 15.1999ZM20.0833 10.4999L21.2854 11.2212C21.5221 11.3633 21.5989 11.6704 21.4569 11.9072C21.4146 11.9776 21.3557 12.0365 21.2854 12.0787L11.9999 17.6499L2.71451 12.0787C2.47772 11.9366 2.40093 11.6295 2.54301 11.3927C2.58523 11.3223 2.64413 11.2634 2.71451 11.2212L3.9166 10.4999L11.9999 15.3499L20.0833 10.4999ZM12.5144 1.30864L21.2854 6.5712C21.5221 6.71327 21.5989 7.0204 21.4569 7.25719C21.4146 7.32757 21.3557 7.38647 21.2854 7.42869L11.9999 12.9999L2.71451 7.42869C2.47772 7.28662 2.40093 6.97949 2.54301 6.7427C2.58523 6.67232 2.64413 6.61343 2.71451 6.5712L11.4854 1.30864C11.8021 1.11864 12.1977 1.11864 12.5144 1.30864ZM11.9999 3.33233L5.88723 6.99995L11.9999 10.6676L18.1126 6.99995L11.9999 3.33233Z" fill="currentColor"/>',star:'<path d="M12.0006 18.26L4.94715 22.2082L6.52248 14.2799L0.587891 8.7918L8.61493 7.84006L12.0006 0.5L15.3862 7.84006L23.4132 8.7918L17.4787 14.2799L19.054 22.2082L12.0006 18.26ZM12.0006 15.968L16.2473 18.3451L15.2988 13.5717L18.8719 10.2674L14.039 9.69434L12.0006 5.27502L9.96214 9.69434L5.12921 10.2674L8.70231 13.5717L7.75383 18.3451L12.0006 15.968Z" fill="currentColor"/>',"star-fill":'<path d="M12.0006 18.26L4.94715 22.2082L6.52248 14.2799L0.587891 8.7918L8.61493 7.84006L12.0006 0.5L15.3862 7.84006L23.4132 8.7918L17.4787 14.2799L19.054 22.2082L12.0006 18.26Z" fill="currentColor"/>',"sticky-note":'<path d="M21 15L15 20.996L4.00221 21C3.4487 21 3 20.5551 3 20.0066V3.9934C3 3.44476 3.44495 3 3.9934 3H20.0066C20.5552 3 21 3.45576 21 4.00247V15ZM19 5H5V19H13V14C13 13.4872 13.386 13.0645 13.8834 13.0067L14 13L19 12.999V5ZM18.171 14.999L15 15V18.169L18.171 14.999Z" fill="currentColor"/>',stop:'<path d="M7 7V17H17V7H7ZM6 5H18C18.5523 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5Z" fill="currentColor"/>',subtract:'<path d="M5 11V13H19V11H5Z" fill="currentColor"/>',survey:'<path d="M17 2V4H20.0066C20.5552 4 21 4.44495 21 4.9934V21.0066C21 21.5552 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5551 3 21.0066V4.9934C3 4.44476 3.44495 4 3.9934 4H7V2H17ZM7 6H5V20H19V6H17V8H7V6ZM9 16V18H7V16H9ZM9 13V15H7V13H9ZM9 10V12H7V10H9ZM15 4H9V6H15V4Z" fill="currentColor"/>',task:'<path d="M19 4H5V20H19V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H19.9997C20.5519 2 20.9996 2.44772 20.9997 3L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11.2929 13.1213L15.5355 8.87868L16.9497 10.2929L11.2929 15.9497L7.40381 12.0607L8.81802 10.6464L11.2929 13.1213Z" fill="currentColor"/>',terminal:'<path d="M10.9999 12L3.92886 19.0711L2.51465 17.6569L8.1715 12L2.51465 6.34317L3.92886 4.92896L10.9999 12ZM10.9999 19H20.9999V21H10.9999V19Z" fill="currentColor"/>',"terminal-box":'<path d="M3 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3ZM4 5V19H20V5H4ZM12 15H18V17H12V15ZM8.66685 12L5.83842 9.17157L7.25264 7.75736L11.4953 12L7.25264 16.2426L5.83842 14.8284L8.66685 12Z" fill="currentColor"/>',text:'<path d="M13 6V21H11V6H5V4H19V6H13Z" fill="currentColor"/>',"text-wrap":'<path d="M15 18H16.5C17.8807 18 19 16.8807 19 15.5C19 14.1193 17.8807 13 16.5 13H3V11H16.5C18.9853 11 21 13.0147 21 15.5C21 17.9853 18.9853 20 16.5 20H15V22L11 19L15 16V18ZM3 4H21V6H3V4ZM9 18V20H3V18H9Z" fill="currentColor"/>',time:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM13 12H17V14H11V7H13V12Z" fill="currentColor"/>',tools:'<path d="M5.32943 3.27158C6.56252 2.8332 7.9923 3.10749 8.97927 4.09446C10.1002 5.21537 10.3019 6.90741 9.5843 8.23385L20.293 18.9437L18.8788 20.3579L8.16982 9.64875C6.84325 10.3669 5.15069 10.1654 4.02952 9.04421C3.04227 8.05696 2.7681 6.62665 3.20701 5.39332L5.44373 7.63C6.02952 8.21578 6.97927 8.21578 7.56505 7.63C8.15084 7.04421 8.15084 6.09446 7.56505 5.50868L5.32943 3.27158ZM15.6968 5.15512L18.8788 3.38736L20.293 4.80157L18.5252 7.98355L16.7574 8.3371L14.6361 10.4584L13.2219 9.04421L15.3432 6.92289L15.6968 5.15512ZM8.97927 13.2868L10.3935 14.7011L5.09018 20.0044C4.69966 20.3949 4.06649 20.3949 3.67597 20.0044C3.31334 19.6417 3.28744 19.0699 3.59826 18.6774L3.67597 18.5902L8.97927 13.2868Z" fill="currentColor"/>',"ubuntu-fill":'<path d="M22.001 12C22.001 17.5224 17.524 22 12.001 22C6.47798 22 2.00098 17.5224 2.00098 12C2.00098 6.4771 6.47833 2 12.001 2C17.524 2 22.001 6.4771 22.001 12ZM5.20128 10.6642C4.46363 10.6642 3.86613 11.2623 3.86613 12C3.86613 12.7372 4.46363 13.3349 5.20128 13.3349C5.93848 13.3349 6.53628 12.7372 6.53628 12C6.53628 11.2622 5.93848 10.6642 5.20128 10.6642ZM14.7337 16.7325C14.0954 17.1015 13.8763 17.9175 14.2454 18.5558C14.6137 19.1942 15.4296 19.4137 16.0682 19.0448C16.7067 18.6759 16.9257 17.8595 16.5571 17.2208C16.1884 16.5832 15.3721 16.3644 14.7337 16.7325V16.7325ZM8.10133 12C8.10133 10.6808 8.75663 9.5152 9.75958 8.80915L8.78348 7.174C7.61518 7.955 6.74598 9.1485 6.38498 10.545C6.80648 10.8895 7.07613 11.4131 7.07613 12C7.07613 12.586 6.80643 13.1097 6.38493 13.4543C6.74583 14.8516 7.61503 16.0448 8.78343 16.826L9.75953 15.1903C8.75653 14.4848 8.10128 13.32 8.10128 12L8.10133 12ZM12.001 8.09975C14.0385 8.09975 15.7098 9.66175 15.8853 11.654L17.788 11.6261C17.6942 10.1551 17.0518 8.83495 16.0645 7.86435C15.5568 8.05565 14.9705 8.02685 14.4637 7.7342C13.9559 7.4412 13.6376 6.9472 13.5506 6.4104C13.0571 6.27455 12.538 6.2005 12.001 6.2005C11.0782 6.2005 10.2053 6.41685 9.43058 6.80035L10.3582 8.46275C10.8577 8.23045 11.4141 8.09975 12.001 8.09975ZM12.001 15.8995C11.4141 15.8995 10.8576 15.7691 10.3585 15.537L9.43063 17.1991C10.2055 17.5831 11.0782 17.8004 12.001 17.8004C12.538 17.8004 13.0575 17.7255 13.5506 17.5888C13.6376 17.0526 13.9561 16.5586 14.4638 16.2652C14.971 15.9726 15.5569 15.9435 16.0646 16.1349C17.0519 15.1642 17.6942 13.8441 17.7881 12.3732L15.8846 12.3456C15.7099 14.338 14.0386 15.8996 12.0011 15.8996L12.001 15.8995ZM14.7334 7.26675C15.372 7.6349 16.1883 7.4169 16.5566 6.77845C16.9257 6.1396 16.7071 5.32395 16.0683 4.95505C15.4296 4.58605 14.6138 4.8048 14.2447 5.44345C13.8763 6.08195 14.0954 6.89795 14.7334 7.2667V7.26675Z" fill="currentColor"/>',unpin:'<path d="M20.9701 17.1716 19.5559 18.5858 16.0214 15.0513 15.9476 15.1251 15.2405 18.6606 13.8263 20.0748 9.58369 15.8322 4.63394 20.7819 3.21973 19.3677 8.16947 14.418 3.92683 10.1753 5.34105 8.7611 8.87658 8.05399 8.95029 7.98028 5.41373 4.44371 6.82794 3.0295 20.9701 17.1716ZM10.3645 9.39449 9.86261 9.8964 7.04072 10.4608 13.5409 16.9609 14.1052 14.139 14.6071 13.6371 10.3645 9.39449ZM18.7761 9.46821 17.4356 10.8087 18.8498 12.2229 20.1903 10.8824 20.8974 11.5895 22.3116 10.1753 13.8263 1.69003 12.4121 3.10425 13.1192 3.81135 11.7787 5.15185 13.1929 6.56607 14.5334 5.22557 18.7761 9.46821Z" fill="currentColor"/>',user:'<path d="M4 22C4 17.5817 7.58172 14 12 14C16.4183 14 20 17.5817 20 22H18C18 18.6863 15.3137 16 12 16C8.68629 16 6 18.6863 6 22H4ZM12 13C8.685 13 6 10.315 6 7C6 3.685 8.685 1 12 1C15.315 1 18 3.685 18 7C18 10.315 15.315 13 12 13ZM12 11C14.21 11 16 9.21 16 7C16 4.79 14.21 3 12 3C9.79 3 8 4.79 8 7C8 9.21 9.79 11 12 11Z" fill="currentColor"/>',voiceprint:'<path d="M5 7H7V17H5V7ZM1 10H3V14H1V10ZM9 2H11V20H9V2ZM13 4H15V22H13V4ZM17 7H19V17H17V7ZM21 10H23V14H21V10Z" fill="currentColor"/>',window:'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM20 11H4V19H20V11ZM20 5H4V9H20V5ZM11 6V8H9V6H11ZM7 6V8H5V6H7Z" fill="currentColor"/>',windows:'<path d="M21.001 2.5V21.5L3.00098 19.5V4.5L21.001 2.5ZM19.001 12.999L12.001 13V18.487L19.001 19.2655V12.999ZM5.00098 17.7099L10.001 18.265V13L5.00098 12.999V17.7099ZM19.001 10.999V4.73453L12.001 5.512V11L19.001 10.999ZM10.001 5.734L5.00098 6.29009V10.999L10.001 11V5.734Z" fill="currentColor"/>'},T2="pichamber-icon-sprite";let Af=!1;function wj(){if(Af||typeof document>"u")return;const e=document.body;if(!e)return;if(document.getElementById(T2)){Af=!0;return}const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.id=T2,n.setAttribute("aria-hidden","true"),n.style.display="none",n.innerHTML=Object.entries(zw).map(([r,s])=>`<symbol id="oc-${r}" viewBox="0 0 24 24">${s}</symbol>`).join(""),e.insertBefore(n,e.firstChild),Af=!0}const V=p.memo(({name:e,className:t,...n})=>(typeof document<"u"&&wj(),c.jsx("svg",{className:R("remixicon",t),viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",...n,children:c.jsx("use",{href:`#oc-${e}`})})));V.displayName="Icon";let Wc=0;function Sj(e,t){return e&&H.isValidElement(t)?{render:t}:{children:t}}function gu({...e}){return c.jsx(jC,{...e})}function Cj({asChild:e,children:t,...n}){const r=Sj(e,t);return c.jsx(DC,{"data-slot":"dialog-trigger",...n,...r})}function kj({...e}){return c.jsx(RC,{...e})}const Uw=H.forwardRef(({className:e,...t},n)=>(H.useEffect(()=>(Wc+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Wc=Math.max(0,Wc-1),Wc===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),c.jsx(PC,{ref:n,"data-slot":"dialog-overlay",className:R("oc-glass-backdrop fixed inset-0 z-50 bg-black/25 dark:bg-black/40","transition-opacity duration-150 ease-out","data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",e),...t})));Uw.displayName="DialogOverlay";function yu({className:e,children:t,showCloseButton:n=!0,...r}){return c.jsxs(kj,{children:[c.jsx(Uw,{className:"rounded-none"}),c.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center pointer-events-none p-4",children:c.jsxs(TC,{"data-slot":"dialog-content","data-state-slot":"dialog",className:R("relative pointer-events-auto bg-background text-foreground flex flex-col w-full max-w-lg max-h-full gap-4 rounded-xl border p-6 shadow-none overflow-y-auto pwa-dialog-content origin-center","transition-all duration-150 ease-out","data-[starting-style]:opacity-0 data-[starting-style]:scale-[0.98]","data-[ending-style]:opacity-0 data-[ending-style]:scale-[0.98]","data-[nested-dialog-open]:brightness-[0.55] dark:data-[nested-dialog-open]:brightness-[0.4]",e),...r,children:[t,n&&c.jsxs(AC,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[open]:bg-interactive-active data-[open]:text-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[c.jsx(V,{name:"close"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})})]})}function vu({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Mj({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:R("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",e),...t})}function xu({className:e,...t}){return c.jsx(NC,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",e),...t})}function s1({className:e,...t}){return c.jsx(LC,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",e),...t})}function Ij(...e){return t=>{for(const n of e)n&&(typeof n=="function"?n(t):n.current=t)}}function Ej(e,t){const n={...t};for(const r in e){const s=t[r],o=e[r];/^on[A-Z]/.test(r)&&typeof s=="function"&&typeof o=="function"?n[r]=(...i)=>{o(...i),s(...i)}:r==="className"&&typeof s=="string"&&typeof o=="string"?n[r]=`${o} ${s}`:r==="style"&&typeof s=="object"&&typeof o=="object"?n[r]={...o,...s}:n[r]=o}return n}const _j=H.forwardRef(function({children:t,...n},r){if(!H.isValidElement(t))return null;const s=t;return H.cloneElement(s,{...Ej(s.props,n),ref:Ij(r,s.ref)})}),jj=["bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","text-[var(--primary-base)]","border border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","active:bg-[color-mix(in_srgb,var(--primary-base)_22%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--primary-base)_30%,transparent)]"].join(" "),Tj=["bg-[color-mix(in_srgb,var(--status-error)_7%,var(--background))]","text-[var(--status-error)]","border border-[color-mix(in_srgb,var(--status-error)_9%,transparent)]","hover:bg-[color-mix(in_srgb,var(--status-error)_11%,var(--background))]","active:bg-[color-mix(in_srgb,var(--status-error)_16%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--status-error)_9%,transparent)]","dark:border-[color-mix(in_srgb,var(--status-error)_14%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--status-error)_14%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--status-error)_20%,transparent)]"].join(" "),Aj=["bg-[color-mix(in_srgb,var(--status-info)_4%,var(--background))]","text-[var(--status-info)]","border border-[color-mix(in_srgb,var(--status-info)_8%,transparent)]","hover:bg-[color-mix(in_srgb,var(--status-info)_7%,var(--background))]","active:bg-[color-mix(in_srgb,var(--status-info)_10%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--status-info)_7%,transparent)]","dark:border-[color-mix(in_srgb,var(--status-info)_12%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--status-info)_10%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--status-info)_14%,transparent)]"].join(" "),Nj=O5(["group relative inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] typography-ui-label font-medium tracking-[0.01em] shrink-0 select-none","transition-[background-color,border-color,color,opacity] duration-150 ease-out outline-none","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive","disabled:pointer-events-none disabled:opacity-50","[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"],{variants:{variant:{default:jj,solid:R("bg-[var(--primary-base)] text-[var(--primary-foreground)] border border-transparent hover:bg-[var(--primary-hover)] active:opacity-90","disabled:bg-[var(--surface-elevated)] disabled:text-foreground disabled:border-border/60"),destructive:R(Tj,"focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40"),info:Aj,neutral:"bg-interactive-hover text-foreground border border-border/60 hover:bg-interactive-active",outline:"bg-[var(--surface-elevated)] text-foreground border border-border/60 hover:bg-interactive-hover hover:text-foreground",chip:R("border border-border/60 bg-transparent text-foreground hover:bg-interactive-hover hover:text-foreground","aria-pressed:bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","aria-pressed:text-[var(--primary-base)]","aria-pressed:border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","aria-pressed:hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","aria-pressed:hover:text-[var(--primary-base)]","dark:aria-pressed:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:aria-pressed:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:aria-pressed:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]","aria-checked:bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","aria-checked:text-[var(--primary-base)]","aria-checked:border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","aria-checked:hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","aria-checked:hover:text-[var(--primary-base)]","dark:aria-checked:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:aria-checked:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:aria-checked:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]"),secondary:"bg-interactive-hover text-foreground hover:bg-interactive-active",ghost:"text-foreground hover:bg-interactive-hover hover:text-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-3.5 has-[>svg]:px-3",sm:"h-8 gap-1.5 px-2.5 has-[>svg]:px-2 rounded-[9px] supports-[corner-shape:squircle]:rounded-[50px]",xs:"h-6 gap-1 px-2 typography-meta has-[>svg]:px-1.5 rounded-[7px] supports-[corner-shape:squircle]:rounded-[50px]",lg:"h-10 px-4 has-[>svg]:px-3.5 rounded-[12px] supports-[corner-shape:squircle]:rounded-[50px]",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function be({className:e,variant:t,size:n,asChild:r=!1,type:s,...o}){const i=r?_j:"button",a=r?s===void 0?{}:{type:s}:{type:s??"button"};return c.jsx(i,{"data-slot":"button",className:R(Nj({variant:t,size:n,className:e})),...a,...o})}const o1="oc-glass-popover oc-glass-floating app-region-no-drag transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 z-50 max-h-[var(--available-height)] min-w-[8rem] origin-[var(--transform-origin)] overflow-visible rounded-xl p-1",Lj="data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",Rj="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 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",Pj="bg-border -mx-1 my-0.5 h-px",bu=H.createContext(null),Dj=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function qw(e,t){return e&&H.isValidElement(t)?{render:t}:{children:t}}function Fa({...e}){const[t,n]=H.useState(null),r=H.useMemo(()=>({portalContainer:t,setPortalContainer:n}),[t]);return c.jsx(bu.Provider,{value:r,children:c.jsx(OC,{...e})})}function Ba({asChild:e,children:t,onPointerDownCapture:n,onFocusCapture:r,...s}){const o=H.useContext(bu),i=H.useCallback(l=>{if(!o)return;const d=l instanceof HTMLElement?l:null;o.setPortalContainer(Dj(d))},[o]),a=qw(e,t);return c.jsx(HC,{"data-slot":"dropdown-menu-trigger",onPointerDownCapture:l=>{i(l.currentTarget),n?.(l)},onFocusCapture:l=>{i(l.currentTarget),r?.(l)},...s,...a})}function Va({className:e,sideOffset:t=4,align:n,side:r,alignOffset:s,portalToBody:o=!1,positionerClassName:i,style:a,children:l,onCloseAutoFocus:d,...f}){const u=H.useContext(bu);return c.jsx(H5,{container:o?void 0:u?.portalContainer||void 0,children:c.jsx(F5,{sideOffset:t,align:n,side:r,alignOffset:s,className:R("app-region-no-drag z-50",i),children:c.jsx(B5,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...a},className:R(o1,e),...f,children:l})})})}function ur({className:e,inset:t,variant:n="default",asChild:r,children:s,onSelect:o,onClick:i,...a}){const l=qw(r,s),d=f=>{i?.(f),f.defaultPrevented||o?.(f)};return c.jsx(FC,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:R(Lj,e),...a,onClick:d,...l})}function Oj({...e}){return c.jsx(VC,{"data-slot":"dropdown-menu-radio-group",...e})}function Hj({className:e,children:t,...n}){return c.jsxs($C,{"data-slot":"dropdown-menu-radio-item",className:R("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[checked]:bg-interactive-selection data-[checked]:text-interactive-selection-foreground relative flex cursor-pointer items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",e),...n,children:[c.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:c.jsx(zC,{children:c.jsx(V,{name:"check",className:"size-3"})})}),t]})}function dJ({className:e,inset:t,...n}){return c.jsx("div",{"data-slot":"dropdown-menu-label","data-inset":t,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",e),...n})}function Fj({className:e,...t}){return c.jsx(BC,{"data-slot":"dropdown-menu-separator",className:R(Pj,e),...t})}function uJ({...e}){return c.jsx(UC,{...e})}function fJ({className:e,inset:t,children:n,...r}){return c.jsxs(qC,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:R(Rj,e),...r,children:[n,c.jsx(V,{name:"arrow-right-s",className:"ml-auto size-3.5"})]})}function hJ({className:e,children:t,...n}){const r=H.useContext(bu);return c.jsx(H5,{container:r?.portalContainer||void 0,children:c.jsx(F5,{className:"z-50",children:c.jsx(B5,{"data-slot":"dropdown-menu-sub-content",style:{color:"var(--surface-elevated-foreground)"},className:R(o1,e),...n,children:t})})})}const Bj={local:"This computer",lan:"Local network",tailscale:"Tailscale",relay:"PiChamber Relay",tunnel:"Tunnel",direct:"Direct"},i1={checking:{label:"Checking",tone:"info",description:"Probing the server for reachability."},connected:{label:"Connected",tone:"success",description:"The server answered and accepted the saved credential."},reachable:{label:"Reachable",tone:"info",description:"The server answered, but sign-in state is not verified."},offline:{label:"Offline",tone:"error",description:"The server did not answer."},"sign-in-required":{label:"Sign-in required",tone:"warning",description:"The server rejected the saved credential."},"update-required":{label:"Update required",tone:"error",description:"The server version is too old to connect."},"update-recommended":{label:"Update recommended",tone:"warning",description:"The server works, but a newer version is available."},incompatible:{label:"Incompatible",tone:"error",description:"The server version cannot work with this app."},"wrong-service":{label:"Wrong service",tone:"error",description:"The address answered, but it is not a PiChamber server."},unknown:{label:"Unknown",tone:"muted",description:"This server has not been probed yet."}},Ww=e=>{switch(e){case"ok":return"connected";case"auth":return"sign-in-required";case"update-required":return"update-required";case"update-recommended":return"update-recommended";case"incompatible":return"incompatible";case"wrong-service":return"wrong-service";case"unreachable":return"offline";case"reachable":return"reachable"}},Vj=(e,t)=>e?{status:Ww(e.status),latencyMs:Math.max(0,Math.round(e.latencyMs)),refreshing:t}:{status:t?"checking":"unknown",latencyMs:null,refreshing:t},$j=e=>e==="offline"||e==="wrong-service"||e==="incompatible",zj=e=>{try{return new URL(e).hostname.toLowerCase()}catch{return null}},Uj=e=>/^10\./.test(e)||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||/^192\.168\./.test(e)||/^169\.254\./.test(e),qj=e=>Uj(e)?!0:e.endsWith(".local")||e.endsWith(".lan")||e.endsWith(".home")||e.endsWith(".internal"),Wj=e=>{const t=zj(e);return t?t.endsWith(".ts.net")?"tailscale":t.endsWith(".trycloudflare.com")||t.endsWith(".cfargotunnel.com")?"tunnel":qj(t)?"lan":"direct":"direct"},Kc=(e,t)=>({kind:e,label:Bj[e],address:t}),Kj=(e,t)=>e.kind===t.kind&&(e.address||null)===(t.address||null),Nf=(e,t)=>{try{return e?e(t):t}catch{return t}},Gj=(e,t)=>{const n=Vj(t.probe,t.probing===!0),r=t.redactUrl?Nf(t.redactUrl,e.label):e.label;let s;if(t.isLocal){const a=(t.localOrigin||e.apiUrl||e.url||"").trim();s=[Kc("local",a?Nf(t.redactUrl,a):null)]}else if(e.relay&&!e.apiUrl)s=[Kc("relay",null)];else{const a=Nf(t.redactUrl,e.apiUrl||e.url),l=Kc(Wj(e.apiUrl||e.url),a);s=e.relay?[l,Kc("relay",null)]:[l]}let o=null;t.probe&&Ww(t.probe.status)==="connected"&&(t.probe.via==="relay"?o=s.find(a=>a.kind==="relay")||s[0]||null:o=s.find(a=>a.kind!=="relay")||s[0]||null);const i=!!e.relay&&!e.apiUrl&&!t.isLocal;return{id:e.id,label:r,isCurrent:t.isCurrent,isDefault:t.isDefault,isLocal:t.isLocal,routes:s,activeRoute:o,status:n.status,latencyMs:n.latencyMs,canEdit:!t.isLocal&&!i,canRemove:!t.isLocal,canOpenInNewWindow:!0}},Zj=e=>[...e].sort((t,n)=>Number(n.isCurrent)-Number(t.isCurrent)||Number(n.isDefault)-Number(t.isDefault)||t.label.localeCompare(n.label)),Yj=e=>e.activeRoute?.address?e.activeRoute.address:e.routes.find(t=>t.address)?.address||null,Nl=e=>`${e.kind}::${e.address??""}`,Xj=e=>{if(e.routes.length===0)return null;const t=e.activeRoute;if(t){const n=e.routes.find(r=>Kj(r,t));if(n)return n}return e.routes[0]??null},Jj=(e,t)=>e.routes.find(n=>Nl(n)===t)??null,Qj=(e,t)=>{const n=i1[e].tone;return R("h-2 w-2 rounded-full flex-shrink-0",n==="success"&&"bg-status-success",n==="warning"&&"bg-status-warning",n==="error"&&"bg-status-error",n==="info"&&"bg-status-info",n==="muted"&&"bg-muted-foreground/40",t&&"animate-pulse")},eT=(e,t)=>{const n=i1[e].tone;return R(t?"typography-meta block truncate":"typography-micro truncate",n==="success"&&"text-[var(--status-success)]",n==="warning"&&"text-[var(--status-warning)]",n==="error"&&"text-[var(--status-error)]",n==="info"&&"text-[var(--status-info)]",n==="muted"&&"text-muted-foreground")},tT="typography-micro truncate text-muted-foreground";function nT({item:e,onSelectRoute:t}){const n=Xj(e);return n?typeof t=="function"&&e.routes.length>1?c.jsx("span",{className:"flex min-w-0 items-center gap-1.5",children:c.jsxs(Fa,{children:[c.jsx(Ba,{asChild:!0,children:c.jsxs("button",{type:"button","data-route-picker":"",className:"inline-flex min-w-0 max-w-full items-center gap-0.5 rounded typography-micro text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":`Connection route for ${e.label}: ${n.label}`,children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-subtle-foreground",children:"·"}),c.jsx("span",{className:"truncate",children:n.label}),c.jsx(V,{name:"arrow-down-s",className:"size-3 shrink-0 opacity-70","aria-hidden":"true"})]})}),c.jsx(Va,{align:"start",portalToBody:!0,children:c.jsx(Oj,{value:Nl(n),onValueChange:s=>{const o=Jj(e,s);o&&t?.(e,o)},children:e.routes.map(s=>c.jsx(Hj,{value:Nl(s),children:s.label},Nl(s)))})})]})}):c.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-subtle-foreground",children:"·"}),c.jsx("span",{className:tT,children:n.label})]}):null}const rT=({item:e,layout:t="comfortable",guardDefaultByStatus:n=!1,switchLabel:r="Switch",refreshing:s=!1,pending:o=!1,actionsDisabled:i=!1,onSwitch:a,onSetDefault:l,onOpenInNewWindow:d,onEdit:f,onRemove:u,onSelectRoute:h})=>{const[m,g]=H.useState(!1);H.useEffect(()=>{g(!1)},[e.id]);const x=i1[e.status],b=$j(e.status),S=Yj(e),y=t==="touch",v=i||o,C=typeof a=="function",w=e.canOpenInNewWindow&&typeof d=="function",I=e.canEdit&&typeof f=="function",E=e.canRemove&&typeof u=="function",T=C||w||I||E,A=v||n&&!e.isDefault&&b,j=v||e.isCurrent,k=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:R(Qj(e.status,s||e.status==="checking"),y&&"mt-1.5"),"aria-hidden":"true"}),c.jsxs("span",{className:R("flex-1 min-w-0",y?"space-y-1":"space-y-0.5"),children:[c.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0",children:[c.jsx("span",{className:"typography-ui-label font-medium truncate text-foreground min-w-0",children:e.label}),c.jsx(nT,{item:e,onSelectRoute:h}),e.isCurrent&&c.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:"Current"})]}),c.jsxs("span",{className:eT(e.status,y),title:x.description,children:[x.label,typeof e.latencyMs=="number"&&(e.status==="connected"||e.status==="reachable")?` · ${e.latencyMs}ms`:"",s&&e.status!=="checking"?" · checking":""]}),S?c.jsx("span",{className:R("block truncate font-mono text-subtle-foreground",y?"typography-meta":"typography-micro"),children:S}):null]})]});return c.jsxs("div",{className:R("group flex gap-2 overflow-hidden rounded-md px-2.5 py-2",y?"flex-col rounded-xl bg-[var(--surface-elevated)] px-3.5 py-3":"items-center",y&&e.isCurrent&&"bg-[var(--interactive-selection)]/25"),children:[c.jsxs("div",{className:R("flex min-w-0 flex-1 gap-2",y?"items-start":"items-center"),children:[C&&!e.isCurrent?c.jsxs("div",{className:R("relative flex gap-2 flex-1 min-w-0",y?"items-start":"items-center",j&&"opacity-70"),children:[c.jsx("button",{type:"button",className:"absolute inset-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>a?.(e),disabled:j,"aria-label":`${r} to ${e.label}`}),o?c.jsx(V,{name:"loader-4",className:"h-4 w-4 animate-spin text-muted-foreground","aria-hidden":"true"}):null,c.jsx("span",{className:R("pointer-events-none flex gap-2 flex-1 min-w-0 [&_[data-route-picker]]:pointer-events-auto [&_[data-route-picker]]:relative",y?"items-start":"items-center"),children:k})]}):c.jsx("div",{className:R("flex gap-2 flex-1 min-w-0",y?"items-start":"items-center"),"aria-label":e.isCurrent?`Current server ${e.label}`:void 0,children:k}),c.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[typeof l=="function"&&c.jsx("button",{type:"button",className:R("rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors",y?"h-11 w-11":"h-8 w-8","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e.isDefault?"text-primary hover:text-primary/80":"text-subtle-foreground hover:text-primary/80",A&&"opacity-40 cursor-not-allowed"),onClick:()=>l?.(e),disabled:A,"aria-label":e.isDefault?`Default server ${e.label}`:`Set ${e.label} as default server`,"aria-pressed":e.isDefault,title:e.isDefault?"Default":"Set as default",children:c.jsx(V,{name:e.isDefault?"star-fill":"star",className:"h-4 w-4","aria-hidden":"true"})}),T&&c.jsxs(Fa,{children:[c.jsx(Ba,{asChild:!0,children:c.jsx("button",{type:"button",className:R("rounded-md inline-flex items-center justify-center text-subtle-foreground hover:text-foreground hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-40",y?"h-11 w-11":"h-8 w-8"),"aria-label":`Actions for ${e.label}`,disabled:v,children:c.jsx(V,{name:"more",className:"h-4 w-4","aria-hidden":"true"})})}),c.jsxs(Va,{align:"end",portalToBody:!0,children:[C&&c.jsx(ur,{disabled:j,onSelect:()=>a?.(e),children:e.isCurrent?"Current server":`${r} to this server`}),w&&c.jsx(ur,{disabled:v||b,onSelect:()=>d?.(e),children:b?"Server unreachable":"Open in new window"}),I&&c.jsx(ur,{disabled:v,onSelect:()=>f?.(e),children:"Edit"}),E&&(C||w||I)&&c.jsx(Fj,{}),E&&c.jsx(ur,{variant:"destructive",disabled:v,onSelect:()=>g(!0),children:"Remove"})]})]})]})]}),m&&E&&c.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-2 rounded-md border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2",children:[c.jsx("span",{className:"typography-ui-label flex-1 min-w-0 text-foreground",children:`Remove ${e.label}?`}),c.jsx(be,{type:"button",variant:"destructive",size:y?"sm":"xs",className:y?"min-h-[44px]":void 0,disabled:v,onClick:()=>{g(!1),u?.(e)},"aria-label":`Confirm remove ${e.label}`,children:"Remove"}),c.jsx(be,{type:"button",variant:"outline",size:y?"sm":"xs",className:y?"min-h-[44px]":void 0,onClick:()=>g(!1),"aria-label":`Keep ${e.label}`,children:"Keep"})]})]})},sT=({items:e,emptyMessage:t="No servers yet.",pendingId:n=null,...r})=>e.length===0?c.jsx("p",{className:"typography-meta text-muted-foreground",children:t}):c.jsx("div",{className:"space-y-1",role:"list","aria-label":"Servers",children:e.map(s=>c.jsx("div",{role:"listitem",children:c.jsx(rT,{item:s,pending:n===s.id,...r})},s.id))}),oT=()=>{const e=new Map;return(t,n)=>{const r=e.get(t);if(r)return r;const s=n().finally(()=>{e.get(t)===s&&e.delete(t)});return e.set(t,s),s}},iT=oT(),aT=(e="",t="")=>({id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`header-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:e,value:t}),cT=e=>e.trim().toLowerCase()==="authorization",Lf=e=>{const t={};for(const n of e){const r=n.name.trim(),s=n.value.trim();r&&s&&!cT(r)&&(t[r]=s)}return Object.keys(t).length>0?t:void 0},pJ=e=>Object.entries(e||{}).map(([t,n])=>aT(t,n)),A2=async e=>{const t=await yr(e);t.ok||console.error("Failed to copy to clipboard:",t.error)},bd=e=>e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(bd).join(" ").trim():H.isValidElement(e)?bd(e.props?.children):"",lT=e=>typeof e=="function"?e():e,N2=(e,t)=>{const n=bd(lT(t?.description));return n.length>0?n:bd(e)},Ce={...fi,success:(e,t)=>fi.success(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),info:(e,t)=>fi.info(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),error:(e,t)=>fi.error(e,{...t,action:t?.action||{label:"Copy",onClick:()=>A2(N2(e,t))}}),warning:(e,t)=>fi.warning(e,{...t,action:t?.action||{label:"Copy",onClick:()=>A2(N2(e,t))}})},Ll=new Map,dT=()=>Object.fromEntries(Ll),L2={status:"unreachable",latencyMs:0},Rf=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",R2=e=>{const t=Pr(e);if(!t)return e.trim();try{const n=new URL(t);return n.pathname.endsWith("/")||(n.pathname=`${n.pathname}/`),n.toString()}catch{return t}},P2=async()=>Vr()?$S().catch(()=>""):"",Pf=e=>{const t=e.trim();if(t)try{window.location.assign(t)}catch{window.location.href=t}},uT="Invalid PiChamber connection link.",Hi="Invalid URL (must be http/https)",fT=e=>(e instanceof Error?e.message:String(e))==="invalid-connect-link"?uT:Hi;function hT(e){const t=e?.autoLoad!==!1,[n,r]=H.useState([]),[s,o]=H.useState(null),[i,a]=H.useState(()=>PS()),[l,d]=H.useState(()=>dT()),[f,u]=H.useState(!1),[h,m]=H.useState(!1),[g,x]=H.useState(!1),[b,S]=H.useState(null),[y,v]=H.useState(null),[C,w]=H.useState(0);H.useEffect(()=>en(()=>w(F=>F+1)),[]);const I=H.useMemo(()=>{const F=VS(i),U=n.map(P=>({...P,url:Pr(P.url)||P.url}));return[F,...U]},[n,i]),E=H.useMemo(()=>DS(I),[I,C]),T=H.useMemo(()=>{const F=s||gn;return I.find(U=>U.id===F)?.label||"Local"},[I,s]),A=H.useMemo(()=>{const F=I.map(U=>Gj(U,{isCurrent:U.id===E.id,isDefault:(s||gn)===U.id,isLocal:U.id===gn,probe:l[U.id]||null,probing:f,localOrigin:i,redactUrl:Wn}));return Zj(F)},[I,E,s,l,f,i]),j=H.useCallback(async()=>{if(xt()){m(!0),v(null);try{const F=await ym();F.localOrigin&&a(F.localOrigin),r(F.hosts||[]),o(F.defaultHostId??null)}catch(F){v(F instanceof Error?F.message:"Failed to load"),r([]),o(null)}finally{m(!1)}}},[]);H.useEffect(()=>{t&&j()},[t,j]);const k=H.useCallback(async(F,U)=>{x(!0),v(null);try{await Zl({hosts:F,defaultHostId:U,initialHostChoiceCompleted:!0}),r(F),o(U)}catch(P){throw v(P instanceof Error?P.message:"Failed to save"),P}finally{x(!1)}},[]),_=H.useCallback(async(F,U)=>iT(F.id,async()=>{const P=F.id===gn?U:F.clientToken||"",q=F.requestHeaders||null,B=async()=>{const K=await Gg(F.relay,{clientToken:P,requestHeaders:q}).catch(()=>({status:"unreachable",latencyMs:0}));return{status:K.status,latencyMs:K.latencyMs,...K.status==="ok"?{via:"relay"}:{}}};if(F.relay&&!F.apiUrl)return B();const ee=Pr(Vr()?gl(F):F.url);if(!ee)return{...L2};const G=await Xu(ee,{clientToken:P||null,requestHeaders:q,expectedServerId:F.serverId??F.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Rf(G.status)&&F.relay){const K=await B();if(K.status==="ok")return K}return{status:G.status,latencyMs:G.latencyMs}}),[]),M=H.useCallback(async F=>{if(!xt())return{};u(!0);try{const U=await P2(),P=await Promise.all(F.map(async q=>[q.id,await _(q,U)]));for(const[q,B]of P)Ll.set(q,B);return d(q=>({...q,...Object.fromEntries(P)})),Object.fromEntries(P)}finally{u(!1)}},[_]),L=H.useCallback(async F=>{x(!0),v(null);try{const{hosts:U,hostId:P}=await OS(F,n);return await Zl({hosts:U,defaultHostId:s,initialHostChoiceCompleted:!0}),r(U),{ok:!0,hostId:P}}catch(U){const P=fT(U);return v(P),{ok:!1,error:P}}finally{x(!1)}},[n,s]),O=H.useCallback(async F=>{const U=Kg(F.url);if(!U)return v(Hi),{ok:!1,error:Hi};const P=U.persistedUrl,B={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:F.label.trim()||Wn(P),url:P,apiUrl:P,...F.token.trim()?{clientToken:F.token.trim()}:{},...Lf(F.headers)?{requestHeaders:Lf(F.headers)}:{}};try{await k([B,...n],s)}catch{return{ok:!1,error:"Failed to save"}}return U.redeemUrl&&Pf(U.redeemUrl),{ok:!0}},[n,s,k]),N=H.useCallback(async(F,U)=>{const P=Kg(U.url);if(!P)return v(Hi),{ok:!1,error:Hi};const q=P.persistedUrl,B=n.map(ee=>ee.id===F?{...HS(ee,q),label:U.label.trim()||Wn(q),clientToken:U.token.trim()||void 0,requestHeaders:Lf(U.headers)}:ee);try{await k(B,s)}catch{return{ok:!1,error:"Failed to save"}}return P.redeemUrl&&Pf(P.redeemUrl),{ok:!0}},[n,s,k]),D=H.useCallback(async F=>{const U=n.filter(q=>q.id!==F),P=s===F?gn:s;try{await k(U,P)}catch{}},[n,s,k]),W=H.useCallback(async F=>{try{await k(n,F)}catch{}},[n,k]),z=H.useCallback(async(F,U)=>{const P=I.find(K=>K.id===F);if(!P)return;const q=(K,se)=>{se&&zS({relayUrl:K.relayUrl,serverId:K.serverId,hostEncPubJwk:K.hostEncPubJwk},se),yl({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:P.clientToken||null,runtimeKey:Yu(P),relay:K}),US(P.id)},B=P.id===gn?i:Pr(P.url)||"",ee=P.id===gn?i:Pr(gl(P))||"",G=!!P.relay&&!P.apiUrl&&P.id!==gn;if(!(!B&&!G)){if(Vr()){if(!ee&&!P.relay)return;S(P.id);try{const K=P.id===gn?await P2():P.clientToken||"",se=l[P.id];if(se?.status==="ok"){se.via==="relay"&&P.relay?q(P.relay):ee?yl({apiBaseUrl:ee,clientToken:K||null,requestHeaders:P.requestHeaders||null,runtimeKey:Yu(P)}):P.relay&&q(P.relay),U?.onSwitched?.();return}let de={...L2},oe=null;if(ee){const we=await Xu(ee,{clientToken:K||null,requestHeaders:P.requestHeaders||null,expectedServerId:P.serverId??P.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));de={status:we.status,latencyMs:we.latencyMs},Rf(we.status)||(oe="direct")}let ue;if(!oe&&P.relay){const we=await Gg(P.relay,{keepTunnel:!0,clientToken:K||null,requestHeaders:P.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));we.status==="ok"&&(de={status:we.status,latencyMs:we.latencyMs,via:"relay"},oe="relay",ue="tunnel"in we?we.tunnel:void 0)}const ye=de;if(Ll.set(P.id,ye),d(we=>({...we,[P.id]:ye})),!oe){Ce.error(`Server "${Wn(P.label)}" is unreachable`);return}oe==="relay"&&P.relay?q(P.relay,ue):yl({apiBaseUrl:ee,clientToken:K||null,requestHeaders:P.requestHeaders||null,runtimeKey:Yu(P)}),U?.onSwitched?.()}finally{S(null)}return}if(P.id!==gn&&xt()){S(P.id);try{const K=await Xu(B,{clientToken:P.clientToken||null,requestHeaders:P.requestHeaders||null,expectedServerId:P.serverId??P.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0})),se={status:K.status,latencyMs:K.latencyMs};if(Ll.set(P.id,se),d(de=>({...de,[P.id]:se})),Rf(K.status)){Ce.error(`Server "${Wn(P.label)}" is unreachable`);return}}finally{S(null)}}U?.onSwitched?.(),Pf(R2(B))}},[I,i,l]),X=H.useCallback(F=>{const U=I.find(B=>B.id===F);if(!U)return;const P=B=>{Ce.error("Failed to open new window",{description:B instanceof Error?B.message:String(B)})};if(U.relay&&U.id!==gn){FS(U.id).catch(P);return}const q=U.id===gn?i:gl(U);q&&BS(R2(q),{clientToken:U.clientToken||null,requestHeaders:U.requestHeaders||null}).catch(P)},[I,i]);return{remoteHosts:n,allHosts:I,defaultHostId:s,localOrigin:i,current:E,currentDefaultLabel:T,items:A,statusById:l,probing:f,loading:h,saving:g,switchingHostId:b,error:y,setError:v,load:j,probeAll:M,importPairingLink:L,addManualServer:O,updateServer:N,removeServer:D,setDefaultServer:W,switchToHost:z,openInNewWindow:X}}function pT({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){const s=re(u=>u.setSettingsDialogOpen),o=re(u=>u.setSettingsPage),i=hT({autoLoad:!1}),a=H.useCallback(()=>{o("servers"),s(!0),t(!1)},[t,s,o]);H.useEffect(()=>{e&&i.load()},[e]);const l=i.allHosts;if(H.useEffect(()=>{e&&i.probeAll(l)},[e,l]),!xt())return null;const d=xt(),f=c.jsxs(c.Fragment,{children:[n?c.jsx("div",{className:"flex-shrink-0 border-b border-[var(--interactive-border)] px-3 py-2",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("div",{className:"min-w-0 flex items-baseline gap-1.5 typography-ui-label",children:[c.jsx("span",{className:"font-medium text-foreground",children:"Current"}),c.jsx("span",{className:"max-w-[9rem] truncate text-muted-foreground",children:Wn(i.current.label)}),c.jsx("span",{className:"text-subtle-foreground",children:"•"}),c.jsx("span",{className:"font-medium text-foreground",children:"Default"}),c.jsx("span",{className:"max-w-[9rem] truncate text-muted-foreground",children:Wn(i.currentDefaultLabel)})]}),c.jsx("button",{type:"button",className:R("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:()=>{i.probeAll(i.allHosts)},disabled:!d||i.loading||i.probing,"aria-label":"Refresh servers",children:c.jsx(V,{name:"refresh",className:R("h-4 w-4",i.probing&&"animate-spin")})})]})}):c.jsxs(vu,{className:"flex-shrink-0",children:[c.jsxs(xu,{className:"flex items-center gap-2",children:[c.jsx(V,{name:"server",className:"h-5 w-5"}),"Servers"]}),c.jsx(s1,{children:"Switch between this computer and remote PiChamber servers"})]}),!n&&c.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[c.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current:"}),c.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Wn(i.current.label)}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current default:"}),c.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Wn(i.currentDefaultLabel)})]}),c.jsx("div",{className:"flex items-center gap-1",children:c.jsxs(be,{type:"button",size:"sm",variant:"ghost",onClick:()=>{i.probeAll(i.allHosts)},disabled:!d||i.loading||i.probing,children:[c.jsx(V,{name:"refresh",className:R("h-4 w-4",i.probing&&"animate-spin")}),"Refresh"]})})]}),!d&&c.jsx("div",{className:"flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3",children:c.jsx("div",{className:"typography-meta text-muted-foreground",children:"Server switcher is limited on this page. Use Local to recover."})}),c.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:c.jsx("div",{className:R(n&&"px-3 py-1"),children:i.loading?c.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading..."}):c.jsx(sT,{items:i.items,layout:n?"touch":"comfortable",guardDefaultByStatus:!0,refreshing:i.probing,pendingId:i.switchingHostId,actionsDisabled:i.saving,onSwitch:u=>{i.switchToHost(u.id,{onSwitched:r})},onSetDefault:u=>{i.setDefaultServer(u.id)},onOpenInNewWindow:u=>i.openInNewWindow(u.id)})})}),c.jsx("div",{className:"flex-shrink-0 border-t border-[var(--interactive-border)]",children:c.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:a,children:[c.jsx(V,{name:"add",className:"h-4 w-4"}),c.jsx("span",{className:"typography-ui-label",children:"Add server"})]})}),i.error&&c.jsx("div",{className:"flex-shrink-0 typography-meta text-status-error",children:i.error})]});return n?c.jsx("div",{className:"w-full max-h-[70vh] flex flex-col overflow-hidden gap-2",children:f}):c.jsx(gu,{open:e,onOpenChange:t,children:c.jsx(yu,{className:"w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3",children:f})})}function Kw(){const[e,t]=H.useState(!1);return xt()?c.jsxs(c.Fragment,{children:[c.jsxs(be,{type:"button",variant:"ghost",size:"sm","data-oc-host-switcher":!0,className:"w-full justify-center",onClick:()=>t(!0),children:[c.jsx(V,{name:"server",className:"h-4 w-4"}),"Switch server"]}),c.jsx(pT,{open:e,onOpenChange:t})]}):null}const D2=H.memo(function({checked:t,onChange:n,disabled:r=!1,indeterminate:s,ariaLabel:o,className:i,iconClassName:a}){const l="h-[14px] w-[14px] min-h-[14px] min-w-[14px]",d="h-[10px] w-[10px] min-h-[10px] min-w-[10px]",f=t||s;return c.jsx(WC,{checked:t,onCheckedChange:u=>n(!!u),disabled:r,indeterminate:s,"aria-label":o,className:R("group/checkbox relative flex shrink-0 self-center items-center justify-center rounded-[4px] border outline-none",l,"transition-[background-color,border-color,box-shadow] duration-200 ease-out",f?"border-[color:color-mix(in_srgb,var(--primary-base)_65%,var(--interactive-border))] bg-transparent shadow-none hover:bg-[var(--interactive-hover)] hover:border-[color:color-mix(in_srgb,var(--primary-base)_75%,var(--interactive-border))]":"border-[var(--interactive-border-hover)] bg-transparent shadow-none hover:bg-[var(--interactive-hover)] hover:border-[var(--interactive-border-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-transparent","disabled:cursor-not-allowed disabled:opacity-50",i),children:c.jsx(KC,{keepMounted:!0,className:R("flex items-center justify-center text-[var(--primary-base)]","data-[unchecked]:hidden",a),children:s?c.jsx(V,{name:"subtract",className:R(d,"text-[var(--primary-base)]")}):c.jsx(V,{name:"check",className:R(d,"text-[var(--primary-base)]")})})})});function Uo({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:R("text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent","focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none","aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...n})}const a1=({className:e="",width:t=70,height:n=70,isAnimated:r=!1})=>{const s=Ow(),i=H.useId().replace(/[^a-zA-Z0-9_-]/g,""),a=`pc-shimmer-mask-${i}`,l=`pc-shimmer-grad-${i}`,d=H.useMemo(()=>{if(s)return s.currentTheme.colors.surface.foreground;if(typeof window<"u"){const f=getComputedStyle(document.documentElement).getPropertyValue("--splash-stroke").trim();return f||(window.matchMedia("(prefers-color-scheme: dark)").matches?"white":"black")}return"white"},[s]);return c.jsxs("svg",{width:t,height:n,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,role:"img","aria-label":"PiChamber logo",children:[r?c.jsxs(c.Fragment,{children:[c.jsxs("defs",{children:[c.jsxs("linearGradient",{id:l,gradientUnits:"userSpaceOnUse",x1:"0",y1:"0",x2:"100",y2:"100",children:[c.jsx("stop",{offset:"0%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"35%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"50%",stopColor:d,stopOpacity:"1"}),c.jsx("stop",{offset:"65%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"100%",stopColor:d,stopOpacity:"0"})]}),c.jsx("mask",{id:a,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:"0",y:"0",width:"100",height:"100",children:c.jsxs("g",{fill:"none",children:[c.jsx("path",{d:"M50 3 91 27 50 51 9 27Z",fill:"white",opacity:"0.3"}),c.jsx("path",{d:"M9 27 50 51V97L9 73Z",fill:"white",opacity:"0.55"}),c.jsx("path",{d:"M50 51 91 27V73L50 97Z",fill:"white",opacity:"0.85"}),c.jsx("path",{d:"M50 3 91 27V73L50 97 9 73V27Z",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68",stroke:"white",strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round"})]})})]}),c.jsx("style",{children:"@keyframes pc-shimmer-anim{0%{transform:translate(-110px,-110px)}100%{transform:translate(110px,110px)}}.pc-shimmer-sweep{animation:pc-shimmer-anim 1.8s cubic-bezier(0.4,0,0.2,1) infinite}@media (prefers-reduced-motion:reduce){.pc-shimmer-sweep{animation:none}}"})]}):null,c.jsx("path",{d:"M50 3 91 27 50 51 9 27Z",fill:d,opacity:r?.04:.08}),c.jsx("path",{d:"M9 27 50 51V97L9 73Z",fill:d,opacity:r?.08:.14}),c.jsx("path",{d:"M50 51 91 27V73L50 97Z",fill:d,opacity:r?.13:.22}),c.jsx("path",{d:"M50 3 91 27V73L50 97 9 73V27Z",stroke:d,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",opacity:r?.6:1}),c.jsx("path",{d:"M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68",stroke:d,strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round",opacity:r?.75:1}),r?c.jsx("g",{mask:`url(#${a})`,children:c.jsx("rect",{x:"-50",y:"-50",width:"200",height:"200",fill:`url(#${l})`,className:"pc-shimmer-sweep"})}):null]})},Gw=({children:e})=>{const t=p.useMemo(()=>({height:"var(--oc-wco-titlebar-height, 0px)",right:"var(--oc-wco-right-inset, 0px)"}),[]);return c.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:{fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},children:[c.jsx("div",{className:"app-region-drag fixed left-0 top-0 z-20",style:t,"aria-hidden":!0}),c.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%)"}}),c.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),c.jsx("div",{className:"app-region-no-drag relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:e})]})},mT=()=>c.jsx("div",{className:"flex h-full min-h-screen w-full items-center justify-center overflow-hidden bg-background text-foreground",children:c.jsx(a1,{width:120,height:120,isAnimated:!0})}),O2=({onRetry:e,errorType:t="network",retryAfter:n,children:r})=>{const s=t==="rate-limit",o=n?Math.ceil(n/60):1;return c.jsx(Gw,{children:c.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:s?"Too many attempts":"Unable to reach server"}),c.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:s?o>1?`Please wait ${o} minutes before trying again.`:`Please wait ${o} minute before trying again.`:"We could not verify the UI session. If you're opening PiChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings."})]}),c.jsx(be,{type:"button",onClick:e,className:"w-full max-w-xs",children:"Retry"}),r]})})},gT=({isTunnelLocked:e,password:t,setPassword:n,passwordInputRef:r,isSubmitting:s,errorMessage:o,setErrorMessage:i,trustDevice:a,setTrustDevice:l,supportsPasskeys:d,passkeyStatus:f,isPasskeyBusy:u,activePasskeyAction:h,showHostSwitcher:m,onSubmit:g,onPasskeyUnlock:x,onPasskeySetupOnly:b})=>{const S=d&&f.hasPasskeys,y=d&&!f.hasPasskeys;return c.jsx(Gw,{children:c.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[c.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[c.jsx("h1",{className:"text-xl font-semibold text-foreground",children:e?"Tunnel access required":"Unlock PiChamber"}),c.jsx("p",{className:"typography-meta text-muted-foreground",children:e?"Open this tunnel using the one-time connect link from the desktop app.":"This session is password-protected."})]}),!e&&c.jsxs("form",{onSubmit:g,className:"w-full space-y-2",children:[S&&c.jsxs(be,{type:"button",variant:"outline",className:"w-full",onClick:()=>{x()},disabled:s||u&&h!=="auth",children:[u?c.jsx(V,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx(V,{name:"lock-unlock",className:"h-4 w-4"}),c.jsx("span",{children:u&&h==="auth"?"Cancel passkey":"Use passkey"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("div",{className:"relative flex-1",children:[c.jsx(V,{name:"lock",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-subtle-foreground"}),c.jsx(Uo,{id:"pichamber-ui-password",ref:r,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:t,onChange:v=>{n(v.target.value),o&&i("")},className:"pl-10","aria-invalid":!!o||void 0,"aria-describedby":o?"oc-ui-auth-error":void 0,disabled:s})]}),c.jsx(be,{type:"submit",size:"icon",disabled:!t||s,"aria-label":s?"Unlocking":"Unlock",children:s?c.jsx(V,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx(V,{name:"lock-unlock",className:"h-4 w-4"})})]}),y?c.jsxs("div",{className:"flex items-center justify-between pt-1",children:[c.jsxs("label",{className:"flex items-center gap-2 text-center typography-micro text-muted-foreground",children:[c.jsx(D2,{checked:a,onChange:l,disabled:s,ariaLabel:"Trust this device",className:"size-4",iconClassName:"size-4"}),c.jsx("span",{children:"Trust this device"})]}),c.jsx(be,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground hover:text-foreground",onClick:()=>{b()},disabled:s,children:u&&h==="register"?"Cancel passkey setup":"Add passkey"})]}):c.jsxs("label",{className:"flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground",children:[c.jsx(D2,{checked:a,onChange:l,disabled:s,ariaLabel:"Trust this device",className:"size-4",iconClassName:"size-4"}),c.jsx("span",{children:"Trust this device"})]}),o&&c.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:o})]}),m&&c.jsxs("div",{className:"w-full",children:[c.jsx(Kw,{}),c.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})]})})},yT="/auth/passkey/authenticate/options",vT="/auth/passkey/authenticate/verify",xT="/auth/passkey/register/options",bT="/auth/passkey/register/verify",Zw="/api/passkeys",wT="/auth/passkey/status",ST="/api/auth/reset",Rl={enabled:!1,hasPasskeys:!1,passkeyCount:0,rpID:null},_a=async(e,t)=>Rt(e,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:t===void 0?void 0:JSON.stringify(t)}),Ls=async(e,t)=>{try{const n=await e.json();if(n&&typeof n.error=="string"&&n.error.trim())return n.error}catch{}return t},Df=e=>e instanceof YC&&e.code==="ERROR_CEREMONY_ABORTED",H2=()=>{GC.cancelCeremony()},Yw=()=>typeof window>"u"?{supported:!1,reason:"Passkeys are unavailable outside the browser."}:window.isSecureContext?{supported:!0,reason:""}:{supported:!1,reason:"Passkeys require HTTPS or localhost."},F2=async()=>{const e=Yw();if(!e.supported)throw new Error(e.reason);const t=typeof navigator.userAgent=="string"&&navigator.userAgent.trim()?navigator.userAgent:"This device",n=await _a(xT,{label:t});if(!n.ok)throw new Error(await Ls(n,"Could not start passkey setup."));const{requestId:r,optionsJSON:s}=await n.json(),o=await ZC({optionsJSON:s}),i=await _a(bT,{requestId:r,response:o});if(!i.ok)throw new Error(await Ls(i,"Could not finish passkey setup."));return i.json().catch(()=>null)},CT=async(e,t={})=>{const n=Yw();if(!n.supported)throw new Error(n.reason);const r=await _a(yT);if(!r.ok)throw new Error(await Ls(r,"Passkey sign-in is not available right now."));const{requestId:s,optionsJSON:o}=await r.json(),i=await XC({optionsJSON:o}),a=await _a(vT,{requestId:s,response:i,trustDevice:e,issueClientToken:t.issueClientToken===!0,clientLabel:t.clientLabel,clientKind:t.clientKind,dedupeKey:t.dedupeKey});if(!a.ok)throw new Error(await Ls(a,"Passkey sign-in failed."));return a.json().catch(()=>null)},kT=15e3,MT=async()=>{const e=new AbortController,t=setTimeout(()=>e.abort(),kT);try{const n=await Rt(wT,{method:"GET",credentials:"include",headers:{Accept:"application/json"},signal:e.signal});if(!n.ok)return Rl;const r=await n.json().catch(()=>null);return{enabled:r?.enabled===!0,hasPasskeys:r?.hasPasskeys===!0,passkeyCount:typeof r?.passkeyCount=="number"?r.passkeyCount:0,rpID:typeof r?.rpID=="string"&&r.rpID?r.rpID:null}}finally{clearTimeout(t)}},mJ=async()=>{const e=await Rt(Zw,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(await Ls(e,"Could not load passkeys."));const t=await e.json().catch(()=>null);return Array.isArray(t?.passkeys)?t.passkeys:[]},gJ=async e=>{const t=await Rt(`${Zw}/${encodeURIComponent(e)}`,{method:"DELETE",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(await Ls(t,"Could not remove passkey."));return t.json().catch(()=>null)},yJ=async()=>{const e=await _a(ST);if(!e.ok)throw new Error(await Ls(e,"Could not clear saved authentication."));return e.json().catch(()=>null)},IT=(e,t)=>e.apiBaseUrl===t.apiBaseUrl&&e.runtimeKey===t.runtimeKey,ET=e=>e.shouldUseDesktopShellPasswordLogin?"locked":"error",Xw="/auth/session",_T=4,jT=1500,Jw="pichamber.uiAuth.trustDevice",TT="desktop-local",AT="desktop-local",NT=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},LT=(e,t)=>{const n=Pr(e),r=Pr(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},kp=()=>xt(),RT=e=>{const t=e.replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"},Qw=()=>{if(!xt())return!1;const e=NT();if(!e)return!1;const n=qd()||(typeof window<"u"?window.location.origin:"");if(LT(e,n))return!0;try{const r=Pr(n);return!!(r&&RT(new URL(r).hostname))}catch{return!1}},c1=()=>Qw()?{clientKind:TT,dedupeKey:AT}:{},PT=15e3,DT=async()=>{const e=new AbortController,t=setTimeout(()=>e.abort(),PT);try{return await Rt(Xw,{method:"GET",credentials:"include",headers:{Accept:"application/json"},signal:e.signal})}finally{clearTimeout(t)}},OT=()=>typeof window>"u"?!1:window.localStorage.getItem(Jw)==="true",HT=async(e,t)=>{const n=kp();return await Rt(Xw,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:"PiChamber Desktop",...c1()})})},FT=async()=>{if(!xt())return"";const e=await Rt("/api/client-auth/clients",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:"PiChamber Desktop",...c1()})}).catch(()=>null);if(!e?.ok)return"";const t=await e.json().catch(()=>null);return typeof t?.token=="string"?t.token.trim():""},Of=()=>xt()&&!Qw(),ds=()=>({apiBaseUrl:qd(),runtimeKey:Y()}),pt=e=>IT(e,ds()),Hf=async(e,t,n,r)=>{if(!xt()||typeof window>"u")return null;const s=await dr("desktop_remote_password_login",{url:n.apiBaseUrl,password:e,trustDevice:t,requestHeaders:r}).catch(()=>null);if(!s||typeof s!="object")return null;const o=s.token,i=s.status;return{token:typeof o=="string"?o.trim():"",...typeof i=="number"?{status:i}:{}}},BT=async(e,t)=>{if(!xt()||!t||!pt(e))return!1;const n=await ym().catch(()=>null);if(!n||!pt(e))return!1;const r=qS({runtimeKey:e.runtimeKey,apiBaseUrl:e.apiBaseUrl,hosts:n.hosts,localOrigin:n.localOrigin});return r?r.kind==="local"?(await Zl({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>{}),pt(e)):r.host.clientToken===t?!0:pt(e)?(await Zl({hosts:n.hosts.map(s=>s.id===r.host.id?{...s,clientToken:t}:s),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{}),pt(e)):!1:!0},Gc=async(e,t,n)=>!e||!pt(t)||!await BT(t,e)||!pt(t)?!1:(yl({apiBaseUrl:t.apiBaseUrl,clientToken:e,requestHeaders:Object.keys(n).length>0?n:null,runtimeKey:t.runtimeKey}),!0);function VT(){const t=p.useMemo(()=>xt(),[]),[n,r]=p.useState(()=>"pending"),[s,o]=p.useState(""),[i,a]=p.useState(!1),[l,d]=p.useState(""),[f,u]=p.useState(void 0),[h,m]=p.useState(!1),[g,x]=p.useState(Rl),[b,S]=p.useState(!1),[y,v]=p.useState(!1),[C,w]=p.useState(()=>OT()),[I,E]=p.useState(null),T=p.useRef(null),A=p.useRef(!1);p.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Jw,C?"true":"false")},[C]);const j=p.useCallback(async(q=ds())=>{try{const B=await MT();return pt(q)&&x(B),B}catch{return pt(q)&&x(Rl),Rl}},[!1]);p.useEffect(()=>{let q=!1;return(async()=>{try{if(!window.isSecureContext||!JC()){q||S(!1);return}q||S(!0)}catch{q||S(!1)}})(),()=>{q=!0}},[!1]);const k=p.useRef(0),_=p.useRef(null),M=p.useRef(null),L=p.useCallback(()=>{_.current!==null&&(window.clearTimeout(_.current),_.current=null)},[]),O=p.useCallback(()=>{k.current=0,L()},[L]),N=p.useCallback(()=>k.current>=_T?!1:(k.current+=1,L(),_.current=window.setTimeout(()=>{_.current=null,M.current?.()},jT*k.current),!0),[L]);p.useEffect(()=>L,[L]);const D=p.useCallback(async()=>{const q=ds();r(B=>B==="authenticated"?B:"pending");try{const[B,ee]=await Promise.all([DT(),j(q)]),G=await B.text();if(!pt(q))return;if(B.ok){O(),r("authenticated"),m(!1),d(""),u(void 0);return}if(B.status===401){let K={};try{K=JSON.parse(G)}catch{K={}}O(),m(K.tunnelLocked===!0),x(ee),r("locked"),u(void 0);return}if(B.status===429){let K={};try{K=JSON.parse(G)}catch{K={}}O(),u(K.retryAfter),m(!1),r("rate-limited");return}if(N())return;r("error"),m(!1)}catch(B){if(!pt(q))return;if(console.warn("Failed to check session status:",B),ET({shouldUseDesktopShellPasswordLogin:Of()})==="locked"){r("locked"),u(void 0),m(!1);return}if(N())return;r("error"),m(!1)}},[j,O,N,!1]);p.useEffect(()=>{M.current=D},[D]),p.useEffect(()=>{D()},[D,!1]),p.useEffect(()=>WS(()=>{O(),D()}),[D,O,!1]),p.useEffect(()=>en(()=>{H2(),o(""),d(""),u(void 0),m(!1),a(!1),E(null),v(!1),O(),r("pending"),D()}),[D,O,!1]),p.useEffect(()=>{n==="locked"&&(A.current=!1)},[!1,n]),p.useEffect(()=>{n==="locked"&&T.current&&(T.current.focus(),T.current.select())},[n]),p.useEffect(()=>{n==="authenticated"&&(A.current=!0)},[!1,n]);const W=p.useCallback(async()=>{const q=ds();E("register"),v(!0);try{await F2()}finally{pt(q)&&(E(null),v(!1))}pt(q)&&await j(q)},[j]),z=p.useCallback(()=>{H2(),E(null),v(!1)},[]),X=p.useCallback(async q=>{if(h||!s||i)return;y&&z();const B=ds(),ee=Zg();a(!0),d("");try{if(Of()){const K=await Hf(s,C,B,ee);if(!pt(B))return;if(K?.token){if(o(""),m(!1),!await Gc(K.token,B,ee))return;r("authenticated");return}if(K?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(K?.status===429){u(void 0),m(!1),r("rate-limited");return}}const G=await HT(s,C);if(!pt(B))return;if(G.ok){const K=await G.json().catch(()=>null);if(!pt(B))return;const se=kp();let de="";if(se&&(de=typeof K?.clientToken=="string"&&K.clientToken.trim()?K.clientToken.trim():"",!de)){const oe=await Hf(s,C,B,ee);if(!pt(B)||(de=oe?.token||await FT(),!pt(B)))return}if(o(""),m(!1),de&&!await Gc(de,B,ee))return;if(q&&b)try{if(await W(),!pt(B))return;Ce.success("Passkey added"),r("authenticated");return}catch(oe){if(Df(oe))Ce.message("Passkey setup canceled");else{const ue=oe instanceof Error?oe.message:"Passkey setup failed.";Ce.error(ue)}r("authenticated");return}r("authenticated");return}if(G.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(G.status===429){const K=await G.json().catch(()=>({}));u(K.retryAfter),m(!1),r("rate-limited");return}d("Unexpected response from server."),m(!1),r("error")}catch(G){if(!pt(B))return;console.warn("Failed to submit UI password:",G);const K=Of()?await Hf(s,C,B,ee):null;if(!pt(B))return;if(K?.token){if(o(""),m(!1),!await Gc(K.token,B,ee))return;r("authenticated");return}if(K?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(K?.status===429){u(void 0),m(!1),r("rate-limited");return}d("Network error. Check connection and retry."),m(!1),r("error")}finally{pt(B)&&a(!1)}},[z,y,i,h,s,W,b,C]),F=p.useCallback(async()=>{if(i||!b)return;if(y){z();return}v(!0),E("auth"),d("");const q=ds(),B=Zg();try{const ee=await CT(C,{issueClientToken:kp(),clientLabel:"PiChamber Desktop",...c1()});if(!pt(q))return;if(typeof ee?.clientToken=="string"&&ee.clientToken.trim()){const G=ee.clientToken.trim();if(!await Gc(G,q,B))return}m(!1),r("authenticated")}catch(ee){if(!pt(q)||Df(ee))return;const G=ee instanceof Error?ee.message:"Passkey sign-in failed.";d(G)}finally{pt(q)&&(E(null),v(!1))}},[z,y,i,b,C]),U=p.useCallback(async()=>{if(i||!b)return;if(y){z();return}const q=ds();E("register"),v(!0);try{if(await F2(),!pt(q))return;Ce.success("Passkey added"),await j(q)}catch(B){if(!pt(q))return;if(Df(B))Ce.message("Passkey setup canceled");else{const ee=B instanceof Error?B.message:"Passkey setup failed.";Ce.error(ee)}}finally{pt(q)&&(E(null),v(!1))}},[z,y,i,j,b]);return{state:n,password:s,setPassword:o,passwordInputRef:T,isSubmitting:i,errorMessage:l,setErrorMessage:d,retryAfter:f,isTunnelLocked:h,passkeyStatus:g,supportsPasskeys:b,isPasskeyBusy:y,trustDevice:C,setTrustDevice:w,activePasskeyAction:I,showHostSwitcher:t,resetTransientRetry:O,checkStatus:D,handleSubmit:async q=>{q.preventDefault(),await X(!1)},handlePasswordUnlock:X,handlePasskeyUnlock:F,handlePasskeySetupOnly:U}}const vJ=({children:e})=>{const{state:t,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,retryAfter:l,isTunnelLocked:d,passkeyStatus:f,supportsPasskeys:u,isPasskeyBusy:h,trustDevice:m,setTrustDevice:g,activePasskeyAction:x,showHostSwitcher:b,resetTransientRetry:S,checkStatus:y,handleSubmit:v,handlePasskeyUnlock:C,handlePasskeySetupOnly:w}=VT();return t==="pending"?c.jsx(mT,{}):t==="error"?c.jsx(O2,{onRetry:()=>{S(),y()},errorType:"network",children:b&&c.jsxs("div",{className:"w-full max-w-xs",children:[c.jsx(Kw,{}),c.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})}):t==="rate-limited"?c.jsx(O2,{onRetry:()=>{y()},errorType:"rate-limit",retryAfter:l}):t==="locked"?c.jsx(gT,{isTunnelLocked:d,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,trustDevice:m,setTrustDevice:g,supportsPasskeys:u,passkeyStatus:f,isPasskeyBusy:h,activePasskeyAction:x,showHostSwitcher:b,onSubmit:v,onPasskeyUnlock:C,onPasskeySetupOnly:w}):c.jsx(c.Fragment,{children:e})},wu=e=>{try{return new URL(e)}catch{return null}},xJ=e=>{const t=wu(e.trim());return t?t.protocol==="http:"||t.protocol==="https:":!1},$T=e=>{const t=wu(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?null:`https://icons.duckduckgo.com/ip3/${t.hostname.toLowerCase()}.ico`},zT=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),UT=e=>{const t=wu(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?!1:zT.has(t.hostname.toLowerCase())},qT=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d{2,5})?(?:\/[^\s<>"'`\u0000-\u001f]*)?/gi,WT=e=>{if(!e)return[];const t=e.match(qT);if(!t||t.length===0)return[];const n=new Set,r=[];for(const s of t){const o=s.replace(/[),.;:!?'"`]+$/g,"");!o||!UT(o)||n.has(o)||(n.add(o),r.push(o))}return r},ja=async e=>{if(typeof window>"u")return!1;const t=e.trim();if(!t)return!1;const n=wu(t);if(!n||n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.toString(),s=window.__PICHAMBER_DESKTOP__;if(s?.openExternal)try{return await s.openExternal(r),!0}catch{}try{return window.open(r,"_blank","noopener,noreferrer"),!0}catch{return!1}};function KT(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=pu();return e}catch{return"unknown"}}function GT(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function ZT(){const e=ZS();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const t=(navigator.platform||"").toLowerCase();return t.includes("mac")?"macos":t.includes("win")?"windows":t.includes("linux")?"linux":"web"}function YT(e){const t=new URLSearchParams;return t.set("deviceClass",KT()),t.set("arch",GT()),t.set("platform",ZT()),e==="desktop"?(t.set("appType","desktop-electron"),t.set("instanceMode",Jo()?"local":"remote"),t):e==="mobile"?(t.set("appType","mobile-capacitor"),t.set("instanceMode","remote"),t):(t.set("appType","web"),t.set("instanceMode","unknown"),t)}async function wi(e,t){try{const n=YT(e);t&&n.set("currentVersion",t);const r=await Rt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const s=await r.json();return{available:s.available??!1,version:s.version,currentVersion:s.currentVersion??"unknown",body:s.body,releaseUrl:s.releaseUrl,downloadUrl:s.downloadUrl,nextSuggestedCheckInSec:typeof s.nextSuggestedCheckInSec=="number"&&Number.isFinite(s.nextSuggestedCheckInSec)?s.nextSuggestedCheckInSec:void 0,packageManager:s.packageManager,updateCommand:s.updateCommand,channel:s.channel==="rc"?"rc":"stable"}}catch(n){return console.warn("Failed to check for updates:",n),null}}function XT(){return lr()?"mobile":Vr()?"desktop":vm()?"web":null}const B2={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,serverInfo:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},JT=Et()((e,t)=>({...B2,checkForUpdates:async()=>{const n=XT();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,s=null;if(n==="desktop"){const o="1.0.6-rc.5",i=!Jo(),[a,l]=await Promise.allSettled([Yg(),i?wi("web"):wi("desktop",o)]),d=a.status==="fulfilled"?a.value:null,f=l.status==="fulfilled"?l.value:null;return s=f?.nextSuggestedCheckInSec??null,e({checking:!1,available:d?.available??!1,info:d,serverInfo:i?f:null,lastChecked:Date.now(),nextCheckInSec:s}),s}else if(n==="web")r=await wi("web"),s=r?.nextSuggestedCheckInSec??null;else if(n==="mobile"){const o="1.0.6-rc.5",[i,a]=await Promise.all([wi("mobile",o),wi("web")]);return s=i?.nextSuggestedCheckInSec??a?.nextSuggestedCheckInSec??null,e({checking:!1,available:i?.available??!1,info:i,serverInfo:a,lastChecked:Date.now(),nextCheckInSec:s}),s}return e({checking:!1,available:r?.available??!1,info:r,serverInfo:null,lastChecked:Date.now(),nextCheckInSec:s}),s}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=t();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const s=await Yg();if(!s?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(i=>({info:i.info?{...i.info,...s,body:i.info.body||s.body,available:i.info.available}:s})),!await GS(i=>{e({progress:i})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(s){e({downloading:!1,error:s instanceof Error?s.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=t();if(!(r!=="desktop"||!n))try{if(!await KS())throw new Error("Desktop restart only works on Local instance")}catch(s){e({error:s instanceof Error?s.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null,serverInfo:null})},reset:()=>{e(B2)}}));function QT({className:e,...t}){return c.jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",e),...t})}function eA({className:e,...t}){return c.jsx("div",{"data-slot":"card-header",className:R("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function tA({className:e,...t}){return c.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",e),...t})}function nA({className:e,...t}){return c.jsx("div",{"data-slot":"card-content",className:R("px-6",e),...t})}class rA extends p.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n,copied:!1}),console.error("Error caught by boundary:",t,n)}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};handleCopy=async()=>{const{strings:t}=this.props,n=this.state.error?String(this.state.error):t.unknownError,r=this.state.error?.stack?`
|
|
36
|
+
|
|
37
|
+
Stack:
|
|
38
|
+
${this.state.error.stack}`:"",s=this.state.errorInfo?.componentStack?`
|
|
39
|
+
|
|
40
|
+
${t.componentStackLabel}${this.state.errorInfo.componentStack}`:"",o=`${n}${r}${s}`;(await yr(o)).ok&&(this.setState({copied:!0}),window.setTimeout(()=>{this.setState(a=>a.copied?{copied:!1}:null)},1500))};render(){const{strings:t}=this.props;return this.state.hasError?this.props.fallback?this.props.fallback:c.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:c.jsxs(QT,{className:"w-full max-w-md",children:[c.jsx(eA,{className:"text-center",children:c.jsxs(tA,{className:"flex items-center justify-center gap-2 text-destructive",children:[c.jsx(V,{name:"error-warning",className:"h-5 w-5"}),t.title]})}),c.jsxs(nA,{className:"space-y-4",children:[c.jsx("p",{className:"text-sm text-muted-foreground text-center",children:t.description}),this.state.error&&c.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[c.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:t.detailsSummary}),c.jsxs("pre",{className:"mt-2 max-h-48 overflow-auto",children:[this.state.error.toString(),this.state.errorInfo?.componentStack?`
|
|
41
|
+
|
|
42
|
+
${t.componentStackLabel}${this.state.errorInfo.componentStack}`:""]})]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsxs(be,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[c.jsx(V,{name:"restart",className:"h-4 w-4 mr-2"}),t.tryAgain]}),c.jsx(be,{onClick:this.handleCopy,variant:"outline",className:"flex-1",children:this.state.copied?t.copied:t.copy})]})]})]})}):this.props.children}}const bJ=({children:e,fallback:t})=>{const n=p.useMemo(()=>({unknownError:"Unknown error",title:"Something went wrong",description:"The application encountered an unexpected error. This has been logged for debugging.",detailsSummary:"Error details",componentStackLabel:"Component stack:",tryAgain:"Try again",copied:"Copied",copy:"Copy"}),[]);return c.jsx(rA,{fallback:t,strings:n,children:e})},sA=1e3,V2=.5,$2={length:0,offset:0},z2=(e,t)=>Math.abs(e.length-t.length)<V2&&Math.abs(e.offset-t.offset)<V2,e3=({containerRef:e,minThumbSize:t=32,hideDelayMs:n=1e3,className:r,disableHorizontal:s=!1,observeMutations:o=!0,suppressVisibility:i=!1,userIntentOnly:a=!1})=>{const[l,d]=p.useState(!1),[f,u]=p.useState({length:0,offset:0}),[h,m]=p.useState({length:0,offset:0}),g=p.useRef(null),x=p.useRef(null),b=p.useRef(null),S=p.useRef(!1),y=p.useRef(!1),v=p.useRef(0),C=p.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),w=p.useRef(null),I=p.useRef(new Set),E=p.useCallback(()=>{const F=e.current;if(!F)return;const{scrollHeight:U,clientHeight:P,scrollTop:q,scrollWidth:B,clientWidth:ee,scrollLeft:G}=F,K=8;let se=$2;if(U>P){const oe=Math.max(P-K*2,0),ue=P/U*oe,ye=Math.max(t,Math.min(oe,ue)),we=Math.max(oe-ye,0),Me=Math.max(U-P,1),He=q/Me*we;se={length:ye,offset:He}}u(oe=>z2(oe,se)?oe:se);let de=$2;if(!s&&B>ee){const oe=Math.max(ee-K*2,0),ue=ee/B*oe,ye=Math.max(t,Math.min(oe,ue)),we=Math.max(oe-ye,0),Me=Math.max(B-ee,1),He=G/Me*we;de={length:ye,offset:He}}m(oe=>z2(oe,de)?oe:de)},[e,t,s]),T=p.useCallback(()=>{b.current===null&&(b.current=requestAnimationFrame(()=>{b.current=null,E()}))},[E]),A=p.useCallback((F,U)=>{if(!U){I.current.clear();return}const P=new Set;P.add(F),Array.from(F.children).forEach(q=>{P.add(q)}),I.current.forEach(q=>{P.has(q)||U.unobserve(q)}),P.forEach(q=>{I.current.has(q)||U.observe(q)}),I.current=P},[]),j=p.useCallback(()=>{g.current&&clearTimeout(g.current),!y.current&&(g.current=setTimeout(()=>d(!1),n))},[n]),k=p.useCallback(()=>{v.current=Date.now()},[]),_=p.useCallback(()=>{x.current&&cancelAnimationFrame(x.current),x.current=requestAnimationFrame(()=>{if(E(),i&&!S.current){d(!1);return}if(a&&!S.current&&!(Date.now()-v.current<=sA)){d(!1);return}d(!0),j()})},[j,i,E,a]);p.useEffect(()=>{const F=e.current;if(!F)return;E(),d(!1);const U=()=>_(),P=K=>{(K.key==="ArrowUp"||K.key==="ArrowDown"||K.key==="PageUp"||K.key==="PageDown"||K.key==="Home"||K.key==="End"||K.key===" ")&&k()};F.addEventListener("scroll",U,{passive:!0}),a&&(F.addEventListener("wheel",k,{passive:!0}),F.addEventListener("touchstart",k,{passive:!0}),F.addEventListener("touchmove",k,{passive:!0}),F.addEventListener("keydown",P));const q=typeof ResizeObserver<"u"?new ResizeObserver(()=>{T()}):null;A(F,q);const B=o&&typeof MutationObserver<"u"?new MutationObserver(()=>{A(F,q),T()}):null;B?.observe(F,{childList:!0});const ee=()=>T(),G=()=>T();return F.addEventListener("input",ee,!0),F.addEventListener("load",G,!0),()=>{F.removeEventListener("scroll",U),F.removeEventListener("input",ee,!0),F.removeEventListener("load",G,!0),a&&(F.removeEventListener("wheel",k),F.removeEventListener("touchstart",k),F.removeEventListener("touchmove",k),F.removeEventListener("keydown",P)),q?.disconnect(),B?.disconnect(),I.current.clear(),g.current&&clearTimeout(g.current),x.current&&cancelAnimationFrame(x.current),b.current&&cancelAnimationFrame(b.current)}},[e,_,k,o,T,A,E,a]),p.useEffect(()=>{i&&(S.current||(d(!1),g.current&&(clearTimeout(g.current),g.current=null)))},[i]);const M=(F,U)=>{const P=e.current;P&&(S.current=!0,C.current={pointerX:F.clientX,pointerY:F.clientY,scrollTop:P.scrollTop,scrollLeft:P.scrollLeft},w.current=U,k(),d(!0),g.current&&clearTimeout(g.current),F.currentTarget.setPointerCapture(F.pointerId))},L=F=>{if(!S.current)return;const U=e.current;if(!U)return;const P=w.current;if(P==="vertical"){const{pointerY:q,scrollTop:B}=C.current,ee=F.clientY-q,G=U.clientHeight,K=Math.max(G-f.length,1),se=Math.max(U.scrollHeight-U.clientHeight,1),de=ee/K*se;U.scrollTop=B+de}else if(P==="horizontal"){const{pointerX:q,scrollLeft:B}=C.current,ee=F.clientX-q,G=U.clientWidth,K=Math.max(G-h.length,1),se=Math.max(U.scrollWidth-U.clientWidth,1),de=ee/K*se;U.scrollLeft=B+de}},O=F=>{S.current&&(S.current=!1,F.currentTarget.releasePointerCapture(F.pointerId),j())},N=p.useCallback(()=>{y.current=!0,g.current&&(clearTimeout(g.current),g.current=null)},[]),D=p.useCallback(()=>{y.current=!1,j()},[j]),W=f.length>0,z=h.length>0;if(!W&&!z)return null;const X=8;return c.jsxs("div",{className:R("overlay-scrollbar",r),"aria-hidden":"true",style:{opacity:l?1:0},children:[W&&c.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical","data-overlay-scrollbar-thumb":"vertical",style:{height:`${f.length}px`,top:`${X+f.offset}px`,right:`${X/2}px`},onPointerDown:F=>M(F,"vertical"),onPointerMove:L,onPointerUp:O,onPointerCancel:O,onMouseEnter:N,onMouseLeave:D}),z&&c.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal","data-overlay-scrollbar-thumb":"horizontal",style:{width:`${h.length}px`,left:`${X+h.offset}px`,bottom:`${X/2}px`},onPointerDown:F=>M(F,"horizontal"),onPointerMove:L,onPointerUp:O,onPointerCancel:O,onMouseEnter:N,onMouseLeave:D})]})};e3.displayName="OverlayScrollbar";const t3=e3;function oA(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n&&typeof n=="object"&&(n.current=t)})}}const Su=p.forwardRef(({as:e="div",orientation:t="vertical",offset:n=0,size:r=48,isEnabled:s=!0,hideTopShadow:o=!1,hideBottomShadow:i=!1,observeMutations:a=!0,onVisibilityChange:l,style:d,className:f,children:u,...h},m)=>{const g=p.useRef(null),x=p.useRef("none"),b=h["data-scroll-shadow"];delete h["data-scroll-shadow"];const S=p.useMemo(()=>{const w={...d};return w["--scroll-shadow-size"]=`${r}px`,w},[r,d]),y=p.useCallback((w,I,E,T,A)=>{const j=`${T}${A.charAt(0).toUpperCase()}${A.slice(1)}Scroll`;I&&E?(w.dataset[j]="true",w.removeAttribute(`data-${T}-scroll`),w.removeAttribute(`data-${A}-scroll`)):(w.dataset[`${T}Scroll`]=String(I),w.dataset[`${A}Scroll`]=String(E),w.removeAttribute(`data-${T}-${A}-scroll`))},[]),v=p.useCallback(w=>{["top","bottom","top-bottom","left","right","left-right"].forEach(I=>{w.removeAttribute(`data-${I}-scroll`)})},[]),C=p.useCallback(()=>{const w=g.current;if(!w)return;if(!s){v(w);return}const I=1,E=t==="vertical"?w.scrollTop>n+I:w.scrollLeft>n+I;let T=t==="vertical"?w.scrollHeight-(w.scrollTop+w.clientHeight)>n+I:w.scrollWidth-(w.scrollLeft+w.clientWidth)>n+I;const A=o&&t==="vertical"?!1:E;i&&t==="vertical"&&(T=!1),y(w,A,T,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const j=A&&T?"both":A?t==="vertical"?"top":"left":T?t==="vertical"?"bottom":"right":"none";j!==x.current&&(x.current=j,l?.(j))},[v,o,i,s,n,l,t,y]);return p.useEffect(()=>{const w=g.current;if(!w)return;let I=null;const E=()=>{I===null&&(I=requestAnimationFrame(()=>{I=null,C()}))},T=()=>C(),A=typeof ResizeObserver<"u"?new ResizeObserver(E):null,j=a&&typeof MutationObserver<"u"?new MutationObserver(E):null;return C(),w.addEventListener("scroll",T,{passive:!0}),A?.observe(w),j?.observe(w,{childList:!0,subtree:!0,characterData:!0}),()=>{I!==null&&cancelAnimationFrame(I),w.removeEventListener("scroll",T),A?.disconnect(),j?.disconnect()}},[C,a]),c.jsx(e,{...h,ref:oA(g,m),className:f,"data-orientation":t,"data-scroll-shadow":b??!0,style:S,children:u})});Su.displayName="ScrollShadow";const Xn=p.forwardRef(({className:e,outerClassName:t,children:n,style:r,minThumbSize:s,hideDelayMs:o,as:i="div",scrollbarClassName:a,disableHorizontal:l=!1,observeMutations:d=!0,fillContainer:f=!0,preventOverscroll:u=!1,useScrollShadow:h=!1,scrollShadowSize:m,hideTopScrollShadow:g=!1,userIntentOnly:x=!1,...b},S)=>{const y=p.useRef(null);return p.useImperativeHandle(S,()=>y.current,[]),c.jsxs("div",{className:R("relative flex flex-col min-h-0 w-full overflow-hidden",u&&"overscroll-none",t),children:[h?c.jsx(Su,{as:i,ref:y,size:m,hideTopShadow:g,className:R("overlay-scrollbar-target overlay-scrollbar-container",u&&"overscroll-none",f?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",l?"overflow-y-auto overflow-x-hidden":"overflow-auto",e),style:r,observeMutations:d,...b,children:n}):c.jsx(i,{ref:y,className:R("overlay-scrollbar-target overlay-scrollbar-container",u&&"overscroll-none",f?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",l?"overflow-y-auto overflow-x-hidden":"overflow-auto",e),style:r,...b,children:n}),c.jsx(t3,{containerRef:y,minThumbSize:s,hideDelayMs:o,className:a,disableHorizontal:l,observeMutations:d,userIntentOnly:x})]})});Xn.displayName="ScrollableOverlay";const U2="mobile-overlay-root",q2=16,W2=200,iA=()=>{if(typeof document>"u")return null;let e=document.getElementById(U2);return e||(e=document.createElement("div"),e.id=U2,document.body.appendChild(e)),e},Ta=({open:e,title:t,onClose:n,children:r,footer:s,className:o,contentMaxHeightClassName:i,renderHeader:a})=>{const l=p.useRef(null),[d,f]=p.useState(!1),[u,h]=p.useState(!1);if(typeof document<"u"&&!l.current&&(l.current=iA()),p.useEffect(()=>{if(!e){f(!1),h(!1);return}const x=window.setTimeout(()=>f(!0),q2),b=window.setTimeout(()=>h(!0),q2+W2+50);return()=>{window.clearTimeout(x),window.clearTimeout(b)}},[e]),p.useLayoutEffect(()=>{if(e)return window.dispatchEvent(new Event("oc:mobile-overlay-opened")),()=>{window.dispatchEvent(new Event("oc:mobile-overlay-closed"))}},[e]),p.useEffect(()=>{if(!e)return;const x=document.body.style.overflow;document.body.style.overflow="hidden";const b=S=>{S.key==="Escape"&&n()};return document.addEventListener("keydown",b),()=>{document.body.style.overflow=x,document.removeEventListener("keydown",b)}},[e,n]),!e||!l.current)return null;const m=i??"max-h-[min(70vh,520px)]",g=c.jsx("div",{className:R("oc-keyboard-inset-surface fixed inset-0 z-[60] flex flex-col bg-[rgb(0_0_0_/_0.45)] transition-opacity duration-200 ease-out",!u&&"oc-keyboard-inset-snap",d?"opacity-100":"opacity-0"),role:"dialog","aria-modal":"true",onClick:n,style:{paddingLeft:"var(--oc-chat-inset-left, 0px)",paddingRight:"var(--oc-chat-inset-right, 0px)"},children:c.jsxs("div",{className:R("mt-auto flex max-h-[calc(100dvh-0.75rem)] min-h-0 w-full flex-col rounded-t-xl border-x border-t border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",o),style:{transform:d?"none":"translateY(100%)",transition:`transform ${W2}ms cubic-bezier(0.32, 0.72, 0, 1)`},onClick:x=>x.stopPropagation(),children:[(()=>{const x=c.jsx("button",{type:"button",onClick:n,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-interactive-hover",children:c.jsx(V,{name:"close",className:"h-4 w-4"})});return a?a(x):c.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[c.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:t}),x]})})(),c.jsx(Xn,{useScrollShadow:!0,disableHorizontal:!0,preventOverscroll:!0,outerClassName:R("min-h-0 flex-1",m),className:"px-2 py-2 pwa-overlay-scroll",children:r}),s?c.jsx("div",{className:"shrink-0 border-t border-border/40 px-3 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:s}):null]})});return ba.createPortal(g,l.current)},aA=10,K2=16,G2=4,cA=/[-_./]/;function lA(e){const t=Array.from(e);let n=aA;const r=t.lastIndexOf("/");if(r>0&&r<t.length-1){const i=t.length-r-1;i>=G2&&i<=K2&&(n=i)}if(t.length<=n+4)return null;let s=t.length-n;const o=i=>cA.test(t[i-1]??"");if(!o(s)){let i=-1;for(let a=s+1;a<=t.length-G2;a+=1)if(o(a)){i=a;break}for(let a=s-1;i<0&&a>=t.length-K2&&a>4;a-=1)o(a)&&(i=a);i>0&&(s=i)}return{head:t.slice(0,s).join(""),tail:t.slice(s).join("")}}function dA(e,t,n){t.style.clipPath="",n.style.translate="",e.removeAttribute("data-overflow");const r=t.firstChild;if(!(r instanceof Text)||t.scrollWidth<=t.clientWidth)return;e.setAttribute("data-overflow","");const s=t.clientWidth,o=t.getBoundingClientRect().left,i=document.createRange(),a=u=>(i.setStart(r,0),i.setEnd(r,u),i.getBoundingClientRect().right-o);let l=0,d=r.length;for(;d-l>1;){const u=l+d>>1;a(u)<=s?l=u:d=u}/[\uD800-\uDBFF]/.test(r.data[l-1]??"")&&(l-=1);const f=Math.max(0,s-a(l));f>0&&(t.style.clipPath=`inset(-0.25em ${f}px -0.25em 0)`,n.style.translate=`-${f}px 0`)}function l1({value:e,showTitle:t=!0,className:n,...r}){const s=lA(e),o=p.useRef(null),i=p.useRef(null),a=p.useRef(null),l=s?.head;return p.useLayoutEffect(()=>{const d=o.current,f=i.current,u=a.current;if(!d||!f||!u||l===void 0)return;const h=()=>dA(d,f,u);if(h(),typeof ResizeObserver>"u")return;const m=new ResizeObserver(h);return m.observe(d),()=>m.disconnect()},[l]),c.jsx("span",{...r,ref:o,title:t?e:void 0,className:R("group/middle-truncate inline-flex min-w-0 max-w-full overflow-hidden whitespace-nowrap",n),children:s?c.jsxs(c.Fragment,{children:[c.jsx("span",{ref:i,className:"min-w-0 overflow-hidden",children:s.head}),c.jsxs("span",{ref:a,className:"shrink-0",children:[c.jsx("span",{"aria-hidden":"true",className:"hidden group-data-[overflow]/middle-truncate:inline",children:"…"}),s.tail]})]}):c.jsx("span",{className:"min-w-0 truncate",children:e},"whole")})}const uA="Awaiting first prompt";function n3(e,t="Untitled Session"){const n=e?.title?.trim();return n||(e?.messageCount===0?uA:t)}const Ff=new Set,Bf=new Set,Vf=new Set,$f=new Set,Cu={onDeleteRequest(e){return Ff.add(e),()=>{Ff.delete(e)}},requestDelete(e){e.sessions.length&&Ff.forEach(t=>t(e))},onCreateRequest(e){return Bf.add(e),()=>{Bf.delete(e)}},requestCreate(e){const t=e??{};Bf.forEach(n=>n(t))},onDirectoryRequest(e){return Vf.add(e),()=>{Vf.delete(e)}},requestDirectoryDialog(){Vf.forEach(e=>e())},onGitRefreshHint(e){return $f.add(e),()=>{$f.delete(e)}},requestGitRefresh(e){e.directory.trim()&&$f.forEach(t=>t(e))}},$a=p.createContext(null),fA=40,Z2=20*1024*1024;function hA(e){const t=new Map;let n=0,r=0,s=!0,o=Promise.resolve();const i=(y,v)=>JSON.stringify([v?.directory??"",y]),a=y=>new TextEncoder().encode(y).byteLength,l=y=>{const v=t.get(y);v&&(n=Math.max(0,n-v.bytes)),t.delete(y)},d=y=>{const v=y.endsWith("/")?y:`${y}/`;for(const[C,w]of t)(w.sourcePath===y||w.sourcePath.startsWith(v))&&l(C)},f=(y,v)=>v.isFile&&v.mtimeMs!==void 0&&y.mtimeMs===v.mtimeMs&&y.size===v.size,u=()=>{t.clear(),n=0},h=(y,v,C,w)=>{if(!s||!w.isFile||w.mtimeMs===void 0)return C;const I=a(C.content);if(I>Z2)return C;for(l(y),t.set(y,{...C,sourcePath:v,size:w.size,mtimeMs:w.mtimeMs,bytes:I}),n+=I;t.size>fA||n>Z2;){const E=t.keys().next().value;if(!E)break;l(E)}return C},m=async(y,v,C,w)=>{const I=await e.statFile?.(v,C).catch(()=>null),E=await e.readFile(v,C),T=await e.statFile?.(v,C).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return w!==r?g(v,C):I&&T&&I.isFile&&T.isFile&&I.mtimeMs!==void 0&&T.mtimeMs!==void 0&&I.size===T.size&&I.mtimeMs===T.mtimeMs?h(y,v,E,T):E},g=e.readFile?async(y,v)=>{if(await o,!s)throw new Error("File cache owner disposed");const C=r;if(v?.allowOutsideWorkspace)return e.readFile(y,v);const w=i(y,v),I=t.get(w);if(!I)return m(w,y,v,C);const E=await e.statFile?.(y,v).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return C!==r?g(y,v):!E||!f(I,E)?(l(w),m(w,y,v,C)):(t.delete(w),t.set(w,I),{content:I.content,path:I.path,revision:I.revision})}:void 0,x=async(y,v)=>{const C=o;let w;o=new Promise(I=>{w=I}),await C,r+=1,y.forEach(d);try{return await v()}finally{y.forEach(d),r+=1,w()}},b={...e,readFile:g,writeFile:e.writeFile?(y,v,C)=>x([y],()=>e.writeFile(y,v,C)):void 0,delete:e.delete?y=>x([y],()=>e.delete(y)):void 0,rename:e.rename?(y,v)=>x([y,v],()=>e.rename(y,v)):void 0},S=N5(y=>{y.runtimeKey!==y.previousRuntimeKey&&(r+=1,u())});return{files:b,dispose:()=>{s=!1,r+=1,u(),S()}}}function wJ({apis:e,children:t}){const[n,r]=p.useState(null);p.useEffect(()=>{const i=hA(e.files);return r(i),()=>{i.dispose(),r(a=>a===i?null:a)}},[e.files]);const s=n?.files??e.files,o=p.useMemo(()=>({...e,files:s}),[e,s]);return c.jsx($a.Provider,{value:o,children:t})}const pA=600,mA=1600,Y2=10,r3=H.createContext(null);class s3 extends H.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function gA({delayDuration:e=0,skipDelayDuration:t,delay:n,closeDelay:r,...s}){return c.jsx(QC,{delay:n??e,closeDelay:r??t,...s})}function wt({delayDuration:e,open:t,onOpenChange:n,...r}){const[s,o]=H.useState(!1),i=H.useRef(null),a=H.useRef(null),l=H.useRef(null),d=H.useRef(!1),f=t!==void 0,u=f?t:s,h=H.useCallback(()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),m=H.useCallback(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[]),g=H.useCallback(y=>{f||o(y)},[f]),x=H.useMemo(()=>({handlePointerDown:y=>{y.pointerType!=="touch"&&y.pointerType!=="pen"||(h(),m(),l.current={x:y.clientX,y:y.clientY},i.current=window.setTimeout(()=>{f||(d.current=!0,g(!0))},pA))},handlePointerMove:y=>{const v=l.current;if(!v)return;const C=Math.abs(y.clientX-v.x),w=Math.abs(y.clientY-v.y);(C>Y2||w>Y2)&&(h(),l.current=null)},handlePointerEnd:()=>{h(),l.current=null,d.current&&(m(),a.current=window.setTimeout(()=>{d.current=!1,g(!1)},mA))},handleClickCapture:y=>{d.current&&(d.current=!1,y.preventDefault(),y.stopPropagation())},handleContextMenu:y=>{d.current&&y.preventDefault()}}),[m,h,f,g]);H.useEffect(()=>()=>{h(),m()},[m,h]);const b=H.useCallback((y,v)=>{f||o(y),n?.(y,v)},[f,n]),S=c.jsx(r3.Provider,{value:x,children:c.jsx(e8,{open:u,onOpenChange:b,...r})});return e===void 0?S:c.jsx(gA,{delayDuration:e,children:S})}function St({asChild:e,children:t,onPointerDown:n,onPointerMove:r,onPointerUp:s,onPointerCancel:o,onClickCapture:i,onContextMenu:a,...l}){const d=H.useContext(r3),f=e&&H.isValidElement(t)?{render:t}:{children:t};return c.jsx(s3,{fallback:t,children:c.jsx(t8,{"data-slot":"tooltip-trigger",onPointerDown:u=>{n?.(u),d?.handlePointerDown(u)},onPointerMove:u=>{r?.(u),d?.handlePointerMove(u)},onPointerUp:u=>{s?.(u),d?.handlePointerEnd()},onPointerCancel:u=>{o?.(u),d?.handlePointerEnd()},onClickCapture:u=>{d?.handleClickCapture(u),!u.defaultPrevented&&i?.(u)},onContextMenu:u=>{d?.handleContextMenu(u),!u.defaultPrevented&&a?.(u)},...l,...f})})}function Ct({className:e,sideOffset:t=0,side:n,align:r,children:s,style:o,...i}){return c.jsx(s3,{children:c.jsx(n8,{children:c.jsx(r8,{sideOffset:t,side:n,align:r,className:"z-50",children:c.jsxs(s8,{"data-slot":"tooltip-content",className:R("oc-glass-tooltip text-[var(--surface-elevated-foreground)] border border-border/60 transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 data-[instant]:transition-none data-[instant]:duration-0 z-50 w-fit origin-[var(--transform-origin)] rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden",e),style:{...o},...i,children:[s,c.jsx(o8,{className:"fill-[var(--surface-elevated)] z-50 size-2"})]})})})})}const yA="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)",vA="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)";function xA(){const e=()=>typeof document<"u"&&document.documentElement.classList.contains("dark"),[t,n]=H.useState(e);return H.useEffect(()=>{const r=()=>n(e()),s=new MutationObserver(r);return s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r(),()=>s.disconnect()},[]),t}function bA(e){H.useEffect(()=>{if(typeof document>"u")return;const t=s=>{s.style.setProperty("box-shadow",e,"important"),s.style.setProperty("outline","none","important"),s.getAttribute("tabindex")==="0"&&s.setAttribute("tabindex","-1")},n=()=>{document.querySelectorAll("[data-sonner-toast]").forEach(t)};n();const r=new MutationObserver(s=>{for(const o of s)o.addedNodes.forEach(i=>{i instanceof HTMLElement&&(i.matches?.("[data-sonner-toast]")&&t(i),i.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()},[e])}const SJ=({...e})=>{const t=xA();return bA(t?yA:vA),c.jsx(i8,{theme:t?"dark":"light",className:"toaster group",closeButton:!1,toastOptions:{classNames:{toast:"group/toast toast !rounded-[var(--radius-xl)] !border-0 !px-3.5 !py-3 !gap-2.5 !text-foreground [&_[data-cancel]+[data-button]]:!ml-2",title:"typography-ui-label !font-medium !text-foreground",description:"typography-meta !text-muted-foreground !mt-0.5",actionButton:"!rounded-[var(--radius-md)] !bg-[var(--primary-base)] !text-[var(--primary-foreground)] hover:!opacity-85 !px-2 !py-1 typography-meta !font-medium transition-opacity",cancelButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-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:"!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(--surface-elevated)"}},style:{"--normal-bg":"var(--surface-elevated)","--normal-text":"var(--foreground)","--normal-border":"transparent","--error-bg":"var(--surface-elevated)","--error-text":"var(--foreground)","--error-border":"transparent","--success-bg":"var(--surface-elevated)","--success-text":"var(--foreground)","--success-border":"transparent","--warning-bg":"var(--surface-elevated)","--warning-text":"var(--foreground)","--warning-border":"transparent","--info-bg":"var(--surface-elevated)","--info-text":"var(--foreground)","--info-border":"transparent"},...e})},$t=e=>Math.round(e*100)/100,as=e=>{if(!e)return null;const t=e.getBoundingClientRect();return{top:$t(t.top),right:$t(t.right),bottom:$t(t.bottom),left:$t(t.left),width:$t(t.width),height:$t(t.height)}},En=e=>{const t=Number.parseFloat(e);return Number.isFinite(t)?$t(t):null};function wA(){if(typeof window>"u"||typeof document>"u"||!document.body)return null;const e=document.documentElement,t=document.querySelector(".oc-mobile-composer"),n=document.querySelector(".oc-mobile-app-shell"),r=t?.querySelector("[data-composer-card]")??null,s=t?.querySelector("[data-chat-input-footer]")??null,o=t?window.getComputedStyle(t):null,i=as(n),a=as(t),l=as(r),d=window.visualViewport,f=window.getComputedStyle(document.body,"::after"),u=document.createElement("div");u.setAttribute("aria-hidden","true"),u.style.cssText="position:fixed;top:0;left:0;visibility:hidden;pointer-events:none;contain:strict;box-sizing:content-box;width:0;height:0;width:100dvh;height:100lvh;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)",document.body.appendChild(u);let h;try{const m=window.getComputedStyle(u);h={safeTop:En(m.paddingTop),safeBottom:En(m.paddingBottom),dynamicHeight:window.CSS.supports("height","100dvh")?En(m.width):null,largeHeight:window.CSS.supports("height","100lvh")?En(m.height):null}}finally{u.remove()}return{capturedAt:Date.now(),devicePixelRatio:window.devicePixelRatio,screen:{width:window.screen.width,height:window.screen.height,availableHeight:window.screen.availHeight},window:{width:window.innerWidth,height:window.innerHeight,scrollY:$t(window.scrollY)},client:{width:e.clientWidth,height:e.clientHeight},visual:d?{width:$t(d.width),height:$t(d.height),offsetTop:$t(d.offsetTop),offsetLeft:$t(d.offsetLeft),scale:$t(d.scale)}:null,css:{...h,viewportBottomStrip:En(window.getComputedStyle(e).getPropertyValue("--oc-viewport-bottom-strip"))},flags:{standalone:window.matchMedia("(display-mode: standalone)").matches,capacitor:e.classList.contains("oc-capacitor-app"),browserKeyboardOpen:e.classList.contains("oc-browser-keyboard-open"),browserFullscreen:e.classList.contains("oc-browser-kb-fullscreen")},root:as(e),body:as(document.body),appRoot:as(document.getElementById("root")),shell:i,composer:a,card:l,footer:as(s),composerStyle:o?{paddingTop:En(o.paddingTop),paddingBottom:En(o.paddingBottom),marginBottom:En(o.marginBottom),position:o.position}:null,bottomOverlay:{present:f.content!=="none"&&f.content!=="normal",height:En(f.height),bottom:En(f.bottom),position:f.position,zIndex:En(f.zIndex)},gaps:{cardToShellBottom:l&&i?$t(i.bottom-l.bottom):null,shellToClientBottom:i?$t(e.clientHeight-i.bottom):null,composerToVisualBottom:a&&d?$t(d.offsetTop+d.height-a.bottom):null}}}const SA="pichamber_session_load_perf",Mp=1e3,CA=new Set(["bootstrap.directory","bootstrap.sessions.all","bootstrap.sessions.archived","bootstrap.sessions.roots","global-sessions.active","global-sessions.archived","session-messages.initial","session-messages.older","session-messages.page","session-messages.refresh","session-messages.visible","session-prefetch"]),kA=new Set(["action-demand","current-directory","initial","initial-page","known-project","known-worktree","older","pagination","prefetch","project-expanded","refresh","selected-session","server-connected","worktree-expanded"]),MA=new Set(["complete","error","stale","deduplicated","canceled"]),o3=()=>{if(Xo())return!0;if(typeof window>"u")return!1;try{return window.localStorage.getItem(SA)==="1"}catch{return!1}};function IA(){return typeof window>"u"?0:window.__pichamberSessionLoadPerformance?.events.length??0}function EA(){typeof window>"u"||window.__pichamberSessionLoadPerformance&&(window.__pichamberSessionLoadPerformance.events=[])}const X2=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),_A=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,zf=e=>Number.isInteger(e)&&Number(e)>=0?Number(e):void 0;function jA(e){if(!o3()||!CA.has(e.operation)||e.caller!==void 0&&!kA.has(e.caller))return()=>{};const t=X2();return(n,r)=>{if(typeof window>"u"||!MA.has(n))return;const s=window.__pichamberSessionLoadPerformance??{events:[]},o=_A(e.queuedMs),i=zf(e.requestLimit),a=zf(r?.retryCount??e.retryCount),l=zf(r?.recordCount??e.recordCount);s.events.push({operation:e.operation,...e.caller!==void 0?{caller:e.caller}:{},...o!==void 0?{queuedMs:o}:{},...i!==void 0?{requestLimit:i}:{},...typeof e.cursorPresent=="boolean"?{cursorPresent:e.cursorPresent}:{},outcome:n,durationMs:Math.max(0,X2()-t),...a!==void 0?{retryCount:a}:{},...l!==void 0?{recordCount:l}:{},at:Date.now()}),s.events.length>Mp&&s.events.splice(0,s.events.length-Mp),window.__pichamberSessionLoadPerformance=s}}const J2="pichamber.chat.first_message_visible";function TA(e){const t=e?.enabled??o3,n=e?.requestFrame??(l=>window.requestAnimationFrame(l)),r=e?.cancelFrame??(l=>window.cancelAnimationFrame(l)),s=e?.markVisible??(()=>{performance.mark(J2),performance.clearMarks(J2)}),o=e?.startEvent??jA,i=new Set;let a=null;return{schedule(l,d){if(!t()||i.has(l))return()=>{};a&&(r(a.frame),a=null);const f=o({operation:"session-messages.visible",caller:"selected-session",recordCount:d}),u=n(()=>{a?.key!==l||a.frame!==u||(a=null,i.add(l),i.size>Mp&&i.delete(i.values().next().value),s(),f("complete"))});return a={key:l,frame:u},()=>{a?.key!==l||a.frame!==u||(r(u),a=null)}}}}const AA=1e3,NA=6,LA=16.7,RA=50,PA=(e,t)=>{if(e.length===0)return 0;const n=e.slice().sort((s,o)=>s-o),r=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[r]??0},DA=(e=AA)=>{const t=[],n=[];let r=0,s=!1;const o=i=>{const a=i-e;for(;t.length>0&&(t[0]??0)<a;)t.shift(),n.shift()};return{reset(){t.length=0,n.length=0,r=0,s=!1},sample(i){s&&(t.push(i),n.push(i-r),o(i)),r=i,s=!0},snapshot(){if(n.length===0||t.length<1)return{fps:0,lastMs:0,p95Ms:0,samples:0};const i=(t[t.length-1]??0)-(t[0]??0);return{fps:i>0?1e3*(t.length-1)/i:0,lastMs:n[n.length-1]??0,p95Ms:PA(n,95),samples:n.length}}}},Q2=(e,t=NA)=>e.filter(n=>n.value>0&&Number.isFinite(n.value)).sort((n,r)=>r.value-n.value||n.metric.localeCompare(r.metric)).slice(0,t).map(n=>({metric:n.metric,value:n.value})),Si=(e,t=1)=>Number.isFinite(e)?e.toFixed(t):"—",OA=e=>typeof e!="number"||!Number.isFinite(e)||e<0?null:e/(1024*1024),HA=250,FA=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),BA=()=>{if(typeof performance>"u")return null;const e=performance.memory?.usedJSHeapSize;return typeof e=="number"&&Number.isFinite(e)?e:null},VA=e=>{if(typeof PerformanceObserver>"u")return()=>{};try{const t=new PerformanceObserver(n=>{for(const r of n.getEntries())typeof r.duration=="number"&&r.duration>0&&e(r.duration)});return t.observe({type:"longtask",buffered:!0}),()=>t.disconnect()}catch{return()=>{}}},$A=(e,t={})=>{const n=(t.getStreamSnapshot??XS)(),r=(t.getSyncSnapshot??tw)(),s=(t.getSessionLoadEventCount??IA)(),o=Q2(n.entries.map(a=>({metric:a.metric,value:a.count}))),i=Q2(Object.entries(r??{}).map(([a,l])=>({metric:`sync.${a}`,value:typeof l=="number"?l:0})));return{...e,capturedAt:Date.now(),stream:o,sync:i,sessionLoadEvents:s}},zA=(e,t={})=>{const n=t.now??FA,r=t.requestFrame??(S=>window.requestAnimationFrame(S)),s=t.cancelFrame??(S=>window.cancelAnimationFrame(S)),o=t.observeLongTasks??VA,i=t.readHeapUsedBytes??BA,a=DA();let l=0,d=0,f=0,u=0,h=0,m=!1;const g=o(S=>{l+=1,d=S,f+=S}),x=S=>{const y=a.snapshot();e($A({fps:y.fps,frameMs:{last:y.lastMs,p95:y.p95Ms},longTasks:{count:l,lastMs:d,totalMs:f},heapUsedMb:OA(i())},t)),u=S},b=S=>{if(m)return;const y=typeof S=="number"&&Number.isFinite(S)?S:n();a.sample(y),(u===0||y-u>=HA)&&x(y),h=r(b)};return h=r(b),{stop(){m=!0,s(h),g(),a.reset()},reset(){a.reset(),l=0,d=0,f=0,UA(),x(n())}}},UA=()=>{YS(),ew(),EA()},qA=()=>({capturedAt:0,fps:0,frameMs:{last:0,p95:0},longTasks:{count:0,lastMs:0,totalMs:0},heapUsedMb:null,stream:[],sync:[],sessionLoadEvents:0});let Ip=qA();const WA=()=>p.useSyncExternalStore(QS,Xo,()=>!1),KA=e=>e>=RA?"var(--status-error)":e>=LA?"var(--status-warning)":"var(--surface-foreground)",Js=(e,t)=>{e&&e.textContent!==t&&(e.textContent=t)},GA=e=>{const t=[...e.stream.map(n=>`${n.metric} ${n.value}`),...e.sync.map(n=>`${n.metric} ${n.value}`)];return e.sessionLoadEvents>0&&t.push(`session-load.events ${e.sessionLoadEvents}`),t.length>0?t.join(`
|
|
43
|
+
`):"no counters yet"},Zc=8,Uf=(e,t,n,r)=>{if(typeof window>"u")return{left:e,top:t};const s=window.visualViewport,o=s?.offsetLeft??0,i=s?.offsetTop??0,a=s?.width||window.innerWidth,l=s?.height||window.innerHeight,d=o+Zc,f=i+Zc,u=Math.max(d,o+a-n-Zc),h=Math.max(f,i+l-r-Zc);return{left:Math.round(Math.min(Math.max(e,d),u)),top:Math.round(Math.min(Math.max(t,f),h))}},ey=(e,t)=>{e.style.left=`${t.left}px`,e.style.top=`${t.top}px`,e.style.right="auto",e.style.transform="none"},ZA=()=>{const[e,t]=p.useState(!1),[n,r]=p.useState(null),[s,o]=p.useState(!1),[i,a]=p.useState(null),[l,d]=p.useState(null),f=p.useRef(null),u=p.useRef(null),h=p.useRef(null),m=p.useRef(null),g=p.useRef(null),x=p.useRef(null),b=p.useRef(null),S=p.useRef(null),y=p.useRef(Ip),v=p.useRef(null),C=p.useCallback(k=>{const _=f.current;if(!_||u.current)return;const M=_.getBoundingClientRect(),L=Uf(k.left,k.top,M.width,M.height);L.left===k.left&&L.top===k.top||(ey(_,L),r(L))},[]);p.useLayoutEffect(()=>{n&&C(n)},[l,e,C,i,n]),p.useEffect(()=>{if(!n||typeof window>"u")return;const k=()=>{C(n)},_=window.visualViewport;return window.addEventListener("resize",k),_?.addEventListener("resize",k),()=>{window.removeEventListener("resize",k),_?.removeEventListener("resize",k)}},[C,n]);const w=p.useCallback(k=>{if(k.button!==0||u.current)return;const _=f.current;if(!_)return;const M=_.getBoundingClientRect();u.current={pointerId:k.pointerId,offsetX:k.clientX-M.left,offsetY:k.clientY-M.top,originLeft:M.left,originTop:M.top,left:M.left,top:M.top,width:M.width,height:M.height};try{k.currentTarget.setPointerCapture(k.pointerId)}catch{}o(!0),k.preventDefault()},[]),I=p.useCallback(k=>{const _=u.current;if(!_||_.pointerId!==k.pointerId)return;const M=Uf(k.clientX-_.offsetX,k.clientY-_.offsetY,_.width,_.height);M.left===_.left&&M.top===_.top||(_.left=M.left,_.top=M.top,f.current?.style.setProperty("transform",`translate3d(${M.left-_.originLeft}px, ${M.top-_.originTop}px, 0)`),k.cancelable&&k.preventDefault())},[]),E=p.useCallback((k,_)=>{const M=u.current;if(!M||M.pointerId!==k.pointerId)return;const L=f.current,O=L?.getBoundingClientRect(),N=_?{left:M.originLeft,top:M.originTop}:Uf(k.clientX-M.offsetX,k.clientY-M.offsetY,O?.width??M.width,O?.height??M.height);u.current=null,L&&(_?L.style.transform="none":ey(L,N)),o(!1),_||r(N);try{k.currentTarget.hasPointerCapture(k.pointerId)&&k.currentTarget.releasePointerCapture(k.pointerId)}catch{}},[]);p.useEffect(()=>()=>{u.current=null},[]),p.useEffect(()=>{const _=zA(M=>{Ip=M,y.current=M,Js(h.current,Si(M.fps,0)),Js(m.current,`${Si(M.frameMs.last)}ms`),Js(g.current,`${Si(M.frameMs.p95)}ms`),g.current&&(g.current.style.color=KA(M.frameMs.p95)),Js(x.current,`${M.longTasks.count} / ${Si(M.longTasks.lastMs,0)}ms`),Js(b.current,M.heapUsedMb==null?"—":`${Si(M.heapUsedMb,0)}MB`),Js(S.current,GA(M))});return v.current=_,()=>{_.stop(),v.current=null}},[]);const T=p.useCallback(()=>{try{const k=wA();return a(k),d(k?null:"Layout measurements unavailable."),k}catch{return a(null),d("Layout measurement failed."),null}},[]),A=p.useCallback(()=>{const k=T();yr(`${JSON.stringify({...y.current,layout:k},null,2)}
|
|
44
|
+
`).then(_=>{if(!_.ok){t(!1),d("Copy failed. Use the displayed measurements if available.");return}d(k?"Snapshot copied.":"Performance snapshot copied. Layout measurements unavailable.")}).catch(()=>{t(!1),d("Copy failed. Use the displayed measurements if available.")})},[T]),j=p.useCallback(()=>{v.current?.reset()},[]);return c.jsxs("aside",{ref:f,role:"complementary","aria-label":"Performance overlay",className:"pointer-events-auto fixed z-[300] w-[18.5rem] max-w-[calc(100vw-1.5rem)] rounded-lg border border-border bg-[var(--surface-elevated)] text-foreground [contain:layout_style]",style:{...n?{left:`${n.left}px`,top:`${n.top}px`,right:"auto"}:{top:"calc(0.5rem + env(safe-area-inset-top, 0px))",right:"calc(0.5rem + env(safe-area-inset-right, 0px))"},transform:"none"},children:[c.jsxs("div",{className:"flex items-center gap-1 px-2 py-1",children:[c.jsxs("div",{className:R("flex min-w-0 flex-1 cursor-grab touch-none select-none items-center gap-1",s?"cursor-grabbing":"active:cursor-grabbing"),title:"Drag to move performance overlay",onPointerDown:w,onPointerMove:I,onPointerUp:k=>E(k,!1),onPointerCancel:k=>E(k,!0),onLostPointerCapture:k=>E(k,!0),children:[c.jsx(V,{name:"draggable",className:"size-3.5 text-muted-foreground"}),c.jsx("p",{className:"min-w-0 flex-1 typography-micro font-medium",children:"Performance"})]}),c.jsx(be,{variant:"ghost",size:"xs","aria-label":"Copy performance and layout snapshot",onPointerDown:k=>k.preventDefault(),onClick:A,children:c.jsx(V,{name:"file-copy",className:"size-3.5"})}),c.jsx(be,{variant:"ghost",size:"xs","aria-label":"Reset performance counters",onClick:j,children:c.jsx(V,{name:"refresh",className:"size-3.5"})}),c.jsx(be,{variant:"ghost",size:"xs","aria-label":e?"Expand performance overlay":"Collapse performance overlay","aria-expanded":!e,onClick:()=>t(k=>!k),children:c.jsx(V,{name:e?"arrow-down-s":"arrow-up-s",className:"size-3.5"})}),c.jsx(be,{variant:"ghost",size:"xs","aria-label":"Turn off performance overlay",onClick:()=>Yl(!1),children:c.jsx(V,{name:"close",className:"size-3.5"})})]}),c.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 px-2 pb-2 font-mono typography-micro tabular-nums text-muted-foreground",children:[c.jsx("span",{children:"FPS"}),c.jsx("span",{ref:h,className:"text-right text-foreground",children:"0"}),c.jsx("span",{children:"Frame"}),c.jsx("span",{ref:m,className:"text-right text-foreground",children:"0.0ms"}),c.jsx("span",{children:"p95"}),c.jsx("span",{ref:g,className:"text-right",children:"0.0ms"}),c.jsx("span",{children:"Long"}),c.jsx("span",{ref:x,className:"text-right text-foreground",children:"0 / 0ms"}),c.jsx("span",{children:"Heap"}),c.jsx("span",{ref:b,className:"text-right text-foreground",children:"—"})]}),e?null:c.jsx("pre",{ref:S,className:"max-h-40 overflow-auto border-t border-border px-2 py-1.5 font-mono typography-micro text-muted-foreground whitespace-pre-wrap",children:"no counters yet"}),e?null:c.jsxs("div",{className:"border-t border-border px-2 py-1.5",children:[c.jsx(be,{variant:"ghost",size:"xs",onPointerDown:k=>k.preventDefault(),onClick:T,children:"Measure layout"}),l?c.jsx("p",{role:"status",className:"typography-micro text-muted-foreground",children:l}):null,i?c.jsx("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap font-mono typography-micro text-muted-foreground",children:JSON.stringify(i,null,2)}):null]})]})},CJ=()=>{const e=WA();return p.useLayoutEffect(()=>{JS()},[]),p.useEffect(()=>{if(!(typeof window>"u"))return window.__pichamberPerfHud={setEnabled:Yl,isEnabled:Xo,getSnapshot:()=>Ip},()=>{delete window.__pichamberPerfHud}},[]),!e||typeof document>"u"||!document.body?null:ba.createPortal(c.jsx(ZA,{}),document.body)},d1=48,YA=e=>e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,d1).replace(/-$/g,""),XA=e=>{const t=e.trim();return t.length===0||t.length>d1?null:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)?t:null},ty=e=>{const t=YA(e.trim());return t&&t.split("-").filter(Boolean).slice(0,7).join("-").slice(0,d1).replace(/-$/g,"")||null},JA=async(e,t)=>{const n=e.trim();if(!n||!t)return ty(n);try{const r=await Rt("/api/pi/small-model/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:n,directory:t})});if(r.ok){const s=await r.json().catch(()=>null);if(typeof s?.text=="string"){const o=XA(s.text);if(o)return o}}}catch{}return ty(n)},QA=500,Pl="Worktree creation superseded.",Ep=e=>{const t=ce(e.projectRoot)??e.projectRoot,n=ce(e.sourceDirectory)??e.sourceDirectory;return JSON.stringify([e.runtimeKey,t,n,e.startRef])},i3=e=>e?Ep(e):null,eN=e=>new Promise(t=>{setTimeout(t,e)}),tN=(e,t)=>!!(e&&t&&e.runtimeKey===t.runtimeKey&&ce(e.projectRoot)===ce(t.projectRoot)&&ce(e.sourceDirectory)===ce(t.sourceDirectory)&&e.startRef===t.startRef),nN=(e,t)=>({...e,path:t.path,branch:t.branch}),Ir=new Map,Ci=new Map,rN=e=>({prompt:e.prompt,confirmedMentions:Array.from(new Set(Array.isArray(e.confirmedMentions)?e.confirmedMentions:[...e.confirmedMentions])),attachments:e.attachments.map(su)}),ki=(e,t,n)=>{e(r=>{const s=r.entries.get(t),o=n(s,Date.now());if(!o&&!s)return r;const i=new Map(r.entries);return o?i.set(t,o):i.delete(t),{entries:i}})},ln=Et()((e,t)=>{const n=(a,l,d)=>{ki(e,a,(f,u)=>f?{...f,state:d,failedSend:null,updatedAt:u}:{key:a,intent:l,state:d,receipt:null,failedSend:null,notificationSent:!1,startedAt:u,updatedAt:u})},r=(a,l,d,f)=>{ki(e,a,(u,h)=>({key:a,intent:l,state:d,receipt:null,failedSend:f,notificationSent:u?.notificationSent??!1,path:u?.path??null,branch:u?.branch??null,startedAt:u?.startedAt??h,updatedAt:h}))},s=(a,l,d,f,u,h)=>{ki(e,a,(m,g)=>({key:a,intent:l,state:null,receipt:d,failedSend:f,notificationSent:m?.notificationSent??!1,path:u??d.path,branch:h??d.branch,startedAt:m?.startedAt??g,updatedAt:g}))},o=(a,l,d)=>{ki(e,a,(f,u)=>f?{...f,path:l,branch:d,updatedAt:u}:null)},i=async a=>{const{intent:l,prompt:d,git:f,refreshProject:u}=a,h=a.failedSend?rN(a.failedSend):null,m=a.pollIntervalMs??QA,g=a.taskId??Ep(l),x=(Ir.get(g)??0)+1;Ir.set(g,x);const b=()=>Ir.get(g)!==x||l.runtimeKey!==Y(),S=()=>{!f||l.runtimeKey!==Y()||u(l.projectRoot,f,{force:!0}).catch(()=>{})};if(n(g,l,{phase:"naming",label:"Naming worktree..."}),!f?.createGitWorktree||!f.getGitWorktreeBootstrapStatus){const y="Git worktrees are unavailable for this runtime.";throw r(g,l,{phase:"failed",label:"Worktree creation failed",error:y},h),new Error(y)}if(l.runtimeKey!==Y()){const y="The runtime changed. Select New worktree again.";throw r(g,l,{phase:"failed",label:"Worktree creation stopped",error:y},h),new Error(y)}try{const y=await JA(d,l.sourceDirectory);if(b())throw new Error(Pl);const v={mode:"new",startRef:l.startRef,...y?{worktreeName:y}:{},returnAfterDirectoryCreated:!0};if(f.validateGitWorktree){const E=await f.validateGitWorktree(l.sourceDirectory,v);if(!E.ok)throw new Error(E.errors.map(T=>T.message).filter(Boolean).join(`
|
|
45
|
+
`)||"The worktree request is invalid.")}if(b())throw new Error(Pl);n(g,l,{phase:"creating",label:"Creating worktree..."});const C=await f.createGitWorktree(l.sourceDirectory,v),w=nN(l,C);if(b())return w;o(g,C.path,C.branch);let I=C.bootstrapStatus;for(;I.status==="pending";){if(b()||(n(g,l,I.phase==="directory-created"?{phase:"checking-out",label:"Checking out files..."}:{phase:"setting-up",label:"Setting up project..."}),await eN(m),b()))return w;I=await f.getGitWorktreeBootstrapStatus(C.path)}if(I.status==="failed"||I.phase!=="setup-ready")throw new Error(I.error||"Worktree setup failed.");try{await u(l.projectRoot,f,{force:!0})}catch{}return b()||s(g,l,w,h,C.path,C.branch),w}catch(y){if(b())throw y;const v=y instanceof Error?y.message:"Failed to create the worktree.";throw v===Pl||(S(),r(g,l,{phase:"failed",label:"Worktree creation failed",error:v},h)),y}};return{runtimeKey:Y(),entries:new Map,getEntry:a=>{const l=i3(a);return l?t().entries.get(l)??null:null},getEntryByKey:a=>t().entries.get(a)??null,getActiveEntries:()=>{const a=[];for(const l of t().entries.values())l.state&&l.state.phase!=="failed"&&a.push(l);return a},clearEntry:a=>{e(l=>{if(!l.entries.has(a))return l;const d=new Map(l.entries);return d.delete(a),Ir.delete(a),{entries:d}})},consumeFailedSend:(a,l)=>{let d=!1;return e(f=>{const u=f.entries.get(a);if(!u||u.state?.phase!=="failed"||u.failedSend!==l)return f;const h=new Map(f.entries);return h.delete(a),Ir.delete(a),d=!0,{entries:h}}),d},markWorktreePromptSucceeded:(a,l)=>{let d=!1;return e(f=>{const u=f.entries.get(a);if(!u||!u.receipt||u.failedSend!==l)return f;const h=new Map(f.entries);return h.delete(a),Ir.delete(a),d=!0,{entries:h}}),d},markWorktreePromptFailed:(a,l,d)=>{let f=!1;return e(u=>{const h=u.entries.get(a);if(!h||!h.receipt||h.failedSend!==l)return u;const m=new Map(u.entries);return m.set(a,{...h,state:{phase:"failed",label:"Prompt failed to send",error:d},updatedAt:Date.now()}),f=!0,{entries:m}}),f},markNotificationSent:a=>{ki(e,a,(l,d)=>!l||l.notificationSent?l??null:{...l,notificationSent:!0,updatedAt:d})},dismissFailed:a=>{e(l=>{if(l.entries.get(a)?.state?.phase!=="failed")return l;const f=new Map(l.entries);return f.delete(a),Ir.delete(a),{entries:f}})},resetForRuntimeSwitch:a=>{Ir.clear(),Ci.clear(),e({runtimeKey:a,entries:new Map})},request:a=>{const l=a.taskId??Ep(a.intent),d=Ci.get(l);if(d)return d;const f=i(a).finally(()=>{Ci.get(l)===f&&Ci.delete(l)});return Ci.set(l,f),f}}}),a3=e=>i3(e),sN=tN,oN=async e=>(await ow([...e])).map(su),iN=(e,t)=>e??t,c3=(e,t)=>(e??t).map(n=>n.id),_p=e=>{const t=Math.max(1,e.currentCount+e.missingCount-e.limit),n=r=>r===1?"file":"files";return{title:"Too many attachments to restore",description:`Remove ${t} ${n(t)} to restore ${e.missingCount} ${n(e.missingCount)}. You can attach up to ${e.limit} files to one message.`}},aN=(e,t)=>e.ok?null:e.reason==="runtime-mismatch"?{title:"The runtime changed",description:"Your failed prompt was kept in Background tasks."}:e.reason==="target-occupied"?{title:"Draft already has content",description:t==="pending-composer"?"Your restored prompt was kept in Background tasks.":"Your failed prompt was kept in Background tasks."}:e.reason==="attachment-limit"?_p(e):(t==="background-task"?e.reason==="missing":e.reason==="dismissed"||e.reason==="navigated-away")?null:{title:"Could not restore the failed prompt",description:"Your prompt was kept in Background tasks."},l3=()=>{try{const e=he.getState(),t=e.newSessionDraft?.open?e.newSessionDraft.directoryOverride:null,n=e.currentSessionId,r=n?e.getDirectoryForSession(n)??e.currentSessionDirectory:t??nt.getState().currentDirectory,s=Qo(Y(),r,n);return s?Jt(s):null}catch{return null}},kJ=e=>{const t=ln.getState(),n=t.getEntryByKey(e),r=n?.failedSend;if(!n||!r)return{ok:!1,reason:"missing"};if(n.intent.runtimeKey!==Y())return{ok:!1,reason:"runtime-mismatch"};const s=Qo(Y(),n.intent.sourceDirectory,null);if(!s)return{ok:!1,reason:"invalid-target"};const o=Jt(s);try{const d=ru(s);if(d.text.trim().length>0&&d.text!==r.prompt)return{ok:!1,reason:"target-occupied"}}catch{return{ok:!1,reason:"invalid-target"}}const i=l3();if(i!==null&&i===o){try{he.getState().openNewSessionDraft({directoryOverride:n.intent.sourceDirectory,worktreeIntent:n.intent})}catch{return{ok:!1,reason:"open-failed"}}const d={entryKey:e,prompt:r.prompt,confirmedMentions:[...r.confirmedMentions],targetKey:o,attachments:r.attachments.map(su),expectedFailedSend:r};try{Ye.getState().requestWorktreeRestore(d)}catch{return{ok:!1,reason:"open-failed"}}return{ok:!0,reason:"pending"}}const l=t.getEntryByKey(e);if(!l||l.failedSend!==r)return{ok:!1,reason:"missing"};try{he.getState().openNewSessionDraft({directoryOverride:n.intent.sourceDirectory,worktreeIntent:n.intent})}catch{return{ok:!1,reason:"open-failed"}}try{Ts(s,r.prompt,r.confirmedMentions)}catch{return{ok:!1,reason:"invalid-target"}}try{Ye.getState().activateAttachmentsDraft(o);const d=Ye.getState().restoreAttachmentsForRetry(r.attachments);if(!d.ok)return{ok:!1,reason:"attachment-limit",limit:d.limit,currentCount:d.currentCount,missingCount:d.missingCount}}catch{return{ok:!1,reason:"open-failed"}}try{if(!t.consumeFailedSend(e,r))return{ok:!1,reason:"missing"}}catch{return{ok:!0}}return{ok:!0}},cN=(e,t)=>{const n=ln.getState(),r=n.getEntryByKey(e.entryKey),s=r?.failedSend;if(!r||!s)return{ok:!1,reason:"dismissed"};if(s!==e.expectedFailedSend)return{ok:!1,reason:"dismissed"};if(r.intent.runtimeKey!==Y())return{ok:!1,reason:"runtime-mismatch"};const o=Qo(Y(),r.intent.sourceDirectory,null);if(!o)return{ok:!1,reason:"invalid-target"};const i=Jt(o);if(i!==e.targetKey)return{ok:!1,reason:"invalid-target"};const a=l3();if(a!==null&&a!==i)return{ok:!1,reason:"navigated-away"};const l=t??"";if(l.trim().length>0&&l!==e.prompt)return{ok:!1,reason:"target-occupied"};try{const u=ru(o);if(u.text.trim().length>0&&u.text!==e.prompt)return{ok:!1,reason:"target-occupied"}}catch{return{ok:!1,reason:"invalid-target"}}const d=ce(r.intent.sourceDirectory),f=ce(o.directory);if(!d||d!==f)return{ok:!1,reason:"invalid-target"};try{Ts(o,e.prompt,e.confirmedMentions),Ye.getState().activateAttachmentsDraft(i);const u=Ye.getState().restoreAttachmentsForRetry(e.attachments);if(!u.ok)return{ok:!1,reason:"attachment-limit",limit:u.limit,currentCount:u.currentCount,missingCount:u.missingCount}}catch{return{ok:!1,reason:"open-failed"}}try{if(!n.consumeFailedSend(e.entryKey,s))return{ok:!1,reason:"dismissed"}}catch{return{ok:!0}}return{ok:!0}},MJ=e=>!!(e?.receipt&&e?.failedSend&&!e?.state),lN=e=>!!(e?.receipt&&!e?.state&&!e?.failedSend),IJ=e=>lN(e),EJ=e=>!!(e?.receipt&&!e?.notificationSent&&!e?.state&&!e?.failedSend),dN=(e,t,n)=>{if(!e||!t)return!1;try{return ln.getState().markWorktreePromptFailed(e,t,n)}catch{return!1}},uN=(e,t,n,r)=>{if(!e||!t)return!1;let s=!1;try{s=ln.getState().markWorktreePromptSucceeded(e,t)}catch{return!1}if(!s)return!1;if(!n||n.length===0)return!0;try{const o=c3(n,r);o.length>0&&Ye.getState().detachAttachedFiles(o)}catch{}return!0},fN=600*1e3,jp="pending-input:",hN=e=>!Number.isFinite(e.ageMs)||Math.max(0,e.ageMs)>fN||e.isCurrent&&e.visible&&e.focused?"none":!e.visible||!e.focused||e.mode==="always"&&!e.isCurrent?"toast-and-notify":"toast",wd=e=>`${jp}${e}`,pN=e=>e==="approval"?"Approval needed":"Input needed",ny=e=>{const t=qe().getState().catalog.byId.get(e);return t?n3(Ns(t),"Untitled session"):"Untitled session"},mN=(e,t,n)=>{const r=he.getState().currentSessionId===e,s=typeof document<"u"&&document.visibilityState==="visible";let o=!1;try{o=typeof document<"u"&&document.hasFocus()}catch{o=!1}const i=re.getState().notificationMode,a=Date.now(),l=Fo(t.since,n,a)??t.since;return{isCurrent:r,visible:s,focused:o,mode:i==="always"?"always":"hidden-only",ageMs:a-l}},d3=(e,t)=>{he.getState().setCurrentSession(e,t)},ry=(e,t,n,r,s)=>{Ce.warning(pN(n.kind),{id:wd(e),description:r,duration:1/0,onDismiss:s,onAutoClose:s,action:{label:"Open session",onClick:()=>d3(e,t||null)}})},gN=(e,t)=>{const n=[];for(const[r,s]of e){const o=t(r);o!==s.label&&n.push([r,o])}return n},yN=(e,t,n,r)=>{e.get(n)?.raise===r&&(e.delete(n),t.delete(wd(n)))},vN=(e,t,n)=>{const r=[];for(const s of e){if(t.has(s))continue;const o=n(s);o.exists&&o.pendingInput===null&&r.push(s)}return r},_J=()=>{const e=he(d=>d.currentSessionId),t=p.useRef(new Map),n=p.useRef(new Set),r=p.useRef(new Map),s=p.useRef(0),o=p.useCallback((d,f)=>{yN(r.current,n.current,d,f)},[]),i=p.useCallback(d=>{const f=wd(d);n.current.delete(f),r.current.delete(d),Ce.dismiss(f);const u=t.current.get(d);if(u!==void 0){t.current.delete(d);const h=zr()?.notifications?.close;h&&h(u).catch(()=>{})}},[]),a=p.useCallback(()=>{for(const f of n.current)Ce.dismiss(f);n.current.clear(),r.current.clear();const d=zr()?.notifications?.close;if(d)for(const f of t.current.values())d(f).catch(()=>{});t.current.clear()},[]);p.useEffect(()=>yE(d=>{if(d.type==="cleared"||!d.pending){i(d.sessionId);return}const f=d.pending,u=hN(mN(d.sessionId,f,d.serverNow));if(u==="none")return;const h=ny(d.sessionId),m=++s.current,g=d.sessionId;if(n.current.add(wd(g)),r.current.set(g,{directory:d.directory,pending:f,label:h,raise:m}),ry(g,d.directory,f,h,()=>o(g,m)),u==="toast-and-notify"){const x=Pm(d.sessionId,f.since);t.current.set(d.sessionId,x),Jb({sessionId:d.sessionId,directory:d.directory,since:f.since,kind:f.kind,title:h})}}),[i,o]),p.useEffect(()=>qe().subscribe(()=>{if(r.current.size!==0)for(const[d,f]of gN(r.current,ny)){const u=r.current.get(d);u&&(r.current.set(d,{...u,label:f}),ry(d,u.directory,u.pending,f,()=>o(d,u.raise)))}},yt),[o]),p.useEffect(()=>{e&&i(e)},[e,i]);const l=Iw();return p.useEffect(()=>{const d=new Set(l.map(m=>m.sessionId)),f=new Set(t.current.keys());for(const m of n.current)m.startsWith(jp)&&f.add(m.slice(jp.length));if(f.size===0)return;const u=qe().getState().catalog,h=vN([...f],d,m=>{const g=u.byId.get(m);return g?{exists:!0,pendingInput:g.pendingInput}:{exists:!1,pendingInput:void 0}});for(const m of h)i(m)},[l,i]),p.useEffect(()=>en(()=>{a()}),[a]),p.useEffect(()=>()=>{a()},[a]),null},jJ=()=>{const t=Iw().length,n=re(r=>r.dockBadgeEnabled);return p.useEffect(()=>{const r=xt()&&!n?0:t;try{zr()?.notifications?.setAttentionCount?.(r)}catch{}},[t,n]),p.useEffect(()=>()=>{try{zr()?.notifications?.setAttentionCount?.(0)}catch{}},[]),null},xN=()=>{const e=Be(t=>qm(t.catalog).length,Object.is,"catalog");return e<=0||xt()||lr()?"":`(${e}) `},TJ=()=>(p.useEffect(()=>{const e=t=>{const n=t.detail,r=typeof n?.sessionId=="string"?n.sessionId.trim():"";if(!r)return;const s=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():null;d3(r,s)};return window.addEventListener("pichamber:open-session",e),()=>window.removeEventListener("pichamber:open-session",e)},[]),null),bN=e=>e.replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase()),za=(e,t=null)=>{const n=e.label?.trim();return n||bN(eC(e.path,t)||e.path)},wN="PiChamber",SN=(e,t)=>[e,t,wN].filter(r=>typeof r=="string"&&r.trim().length>0).join(" | "),CN=()=>{const e=he(l=>l.currentSessionId),t=Be(l=>e?l.reducer.bySession.get(e)?.extensionTitle??null:null,Object.is,e?`session:${e}`:"chrome"),n=ct(l=>l.activeProjectId?l.projects.find(d=>d.id===l.activeProjectId)??null:null),r=p.useMemo(()=>n&&za(n)||null,[n]),[s,o]=p.useState(null),i=xN();p.useEffect(()=>{if(typeof window>"u"||!xt()){o(null);return}let l=!1;const d=async()=>{try{if(Jo()){l||o(null);return}const u=window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,h=qd();if(h&&Xg(h,u)){l||o(null);return}const g=(await ym()).hosts.find(b=>h?Xg(h,gl(b)):!1),x=g?.label?.trim()?Wn(g.label.trim()):"Instance";l||o(x)}catch{l||o("Instance")}};d();const f=()=>{d()};return window.addEventListener("focus",f),()=>{l=!0,window.removeEventListener("focus",f)}},[]);const a=p.useMemo(()=>`${i}${SN(t?.trim()||r,s)}`,[t,s,r,i]);p.useEffect(()=>{if(typeof document<"u"&&(document.title=a),!xt())return;(async()=>{try{if(typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""))return;await V_(a)}catch{return}})()},[a])},AJ=()=>(CN(),null),kN=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]),MN=e=>{try{const t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return!1;const n=t.hostname.toLowerCase();return kN.has(n)}catch{return!1}},u1=()=>Vr()&&Jo()?"device":"server",NJ=(e,t)=>Jg(e)??(Vr()?Jg(t):null)??u1(),IN=10*6e4,Tp=e=>MN(e)?"panel":"external",EN=e=>Math.max(0,e.serverNow-e.createdAt),LJ=e=>({showNotice:EN(e)<=IN,target:Tp(e.url)}),RJ=(e,t,n)=>t==="external"?{title:"Open this page?",description:`${e}. Opens in your browser.`,canOpen:!0}:n.isMobile?{title:"A page is ready to view",description:`${e}. Open PiChamber on a larger screen to view it.`,canOpen:!1}:{title:"Open this page?",description:`${e}. Opens in the PiChamber browser.`,canOpen:!0},_N=e=>{try{const t=new URL(e),n=t.pathname==="/"?"":t.pathname,r=`${t.host}${n}`;return r.length>80?`${r.slice(0,79)}…`:r}catch{return e.slice(0,80)}},jN=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,TN=/\bhttps?:\/\/[^\s<>"'`\u0000-\u001f]+/gi,AN=(e,t=3)=>{if(!e)return[];const n=[];for(const r of e.replace(jN," ").match(TN)??[]){const s=r.replace(/[),.;:!?'"`\]]+$/g,"");let o;try{o=new URL(s)}catch{continue}if(!(o.protocol!=="http:"&&o.protocol!=="https:")&&!n.includes(s)&&(n.push(s),n.length>=t))break}return n},NN=()=>{const{currentSessionId:e,newSessionDraft:t}=he.getState();if(e){const n=qe().getState(),r=n.catalog.byId.get(e)?.directory??n.directory;if(r)return r}return t?.open&&t.directoryOverride?t.directoryOverride:nt.getState().currentDirectory??void 0},LN=(e,t,n)=>{if(e==="external")return ja(t),!0;const r=re.getState();return r.isMobile?!1:(r.openContextBrowser(n,t,{route:u1()}),!0)},PJ=e=>{const t=re.getState(),n=t.chatLinkTarget==="pichamber"&&!t.isMobile?NN():void 0;if(!n){ja(e);return}t.openContextBrowser(n,e,{route:u1()})},sy=(e,t)=>{const n=ce(t??null);if(!n)return;const r=n.toLowerCase();e.has(r)||e.set(r,n)},u3=(e,t,n)=>{const r=new Map;for(const s of e)sy(r,s?.path);if(n?.includeWorktrees===!1||!t)return new Set(r.values());for(const s of t.values())if(s)for(const o of s)sy(r,o?.path);return new Set(r.values())},Yc=new Map,RN=e=>{const t=new Set;for(const n of e){const r=ce(n);r&&t.add(r)}return t},PN=()=>{const e=new Set,t=ct.getState().projects,n=u3(t,Ln(t,Qt.getState()),{includeWorktrees:!0});for(const o of n){const i=ce(o);i&&i!=="~"&&e.add(i)}const r=ce(qe().getState().directory);r&&e.add(r);const s=nt.getState().homeDirectory??null;for(const o of Um(s)){const i=ce(o);i&&i!=="~"&&e.add(i)}return e},DN=async(e,t,n,r,s)=>{const o=e.getState().catalog.listStatusByDirectory,i=r.filter(m=>o.get(m)!=="ready");i.length>0&&await e.refreshAllDirectoryCatalogs(i).catch(()=>{});const a=qe(),l=a!==e||Y()!==t||a.getRuntimeGeneration()!==n,d=a.getState().catalog,f=new Set,u=new Set;for(const m of r){const g=d.listStatusByDirectory.get(m);g==="ready"?f.add(m):g==="failed"&&u.add(m)}const h=!l&&u.size===0&&f.size===r.length&&(s||r.length>0);return{runtimeKey:t,catalog:d,readyDirectories:f,failedDirectories:u,complete:h,stale:l}},ON=e=>{const t=qe(),n=Y(),r=t.getRuntimeGeneration(),s=e!==void 0,i=[...e===void 0?PN():RN(e)].sort(),a=`${n}::${i.join("|")}`,l=Yc.get(a);if(l&&l.store===t&&l.runtimeKey===n&&l.generation===r)return l.promise;const d=DN(t,n,r,i,s);Yc.set(a,{store:t,runtimeKey:n,generation:r,promise:d});const f=()=>{Yc.get(a)?.promise===d&&Yc.delete(a)};return d.then(f,f),d},HN=e=>{if(typeof Element>"u"||!(e instanceof Element))return null;const t=e.closest("[data-terminal-owner]");return t?.isConnected&&t.dataset.terminalOwner||null},qf=e=>HN(e)!==null,FN=e=>{const t=e.info;if(t.finish==="stop"||t.finish==="error")return!0;const n=t.time?.completed,r=t.status;return typeof n!="number"||n<=0?!1:typeof r=="string"?r==="completed":!0},BN=e=>{const{activeStreamingMessageId:t,assistantMessages:n}=e;if(t&&n.some(r=>r.info.id===t))return t;for(let r=n.length-1;r>=0;r--)if(!FN(n[r]))return n[r].info.id;return null},VN=e=>e.connection==="ready"&&(e.authoritativeWorking||e.hasPendingAssistant),$N=e=>{const t=e.connection==="ready"&&!e.transportUncertain,n=e.authoritativeWorking||e.hasPendingAssistant;return{isWorking:t&&n,isAwaitingRecovery:!t&&(n||e.hasRetainedStream)}},zN=e=>e.turnIsInActiveStream||e.isLastTurn&&e.sessionIsWorking&&e.awaitingPromptEcho!==!0&&(e.isSteering===!0||!e.activeStreamingMessageId),UN=e=>e.isRetrying===!0||e.isAwaitingRecovery===!0||!!e.activeStreamingMessageId&&e.messageId===e.activeStreamingMessageId,Wf={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function qN(e,t){const n=Ew(),r=du(e??""),s=Jm(e??"");return p.useMemo(()=>{if(!e)return Wf;const o=r?.type??"idle",i=s[s.length-1],a=!!(i&&i.role==="assistant"&&typeof i.time?.completed!="number"),l=r!==void 0,d=l&&o!=="idle",f=VN({connection:n,authoritativeWorking:d,hasPendingAssistant:a});return l&&!d||!f?Wf:{phase:d?o:"busy",isWorking:!0,isBusy:o==="busy"||!d&&a,isCooldown:!1}},[n,e,r,s])}function f1(){const e=he(t=>t.currentSessionId);return he(t=>t.currentSessionDirectory),qN(e)}const DJ=.45,h1=[{id:"context",description:"Session context and token usage",mode:"context",icon:"pie-chart",label:"Context",availability:"always"},{id:"editor",description:"Edit project files",mode:"file",icon:"file-text",label:"Files",availability:"always"},{id:"git",description:"Review diffs, commit, and push",mode:"git",icon:"git-branch",label:"Git",availability:"always"},{id:"terminal",description:"Built-in terminal",mode:"terminal",icon:"terminal-box",label:"Terminal",availability:"always"},{id:"browser",description:"Built-in web browser",mode:"browser",icon:"global",label:"Browser",availability:"always"},{id:"preview",description:"Dev server preview",mode:"preview",icon:"window",label:"Preview",availability:"has-content"},{id:"pull-requests",description:"Browse pull requests for this repository",mode:"pull-requests",icon:"git-pull-request",label:"Pull requests",availability:"github-repo"},{id:"issues",description:"Browse issues for this repository",mode:"issues",icon:"task",label:"Issues",availability:"github-repo"},{id:"extensions",description:"Extension widgets for this session",mode:"extensions",icon:"plug-2",label:"Extensions",availability:"extensions"}],f3=new Map(h1.map(e=>[e.id,e])),Kf=h1.find(e=>e.id==="git"),OJ=e=>e===!1?{icon:"arrow-left-right",label:"Changes",description:"Review working and last-turn changes"}:{icon:Kf?.icon??"git-branch",label:Kf?.label??"Git",description:Kf?.description??"Review diffs, commit, and push"},WN=e=>typeof e=="string"&&f3.has(e),KN=e=>{const t=[],n=new Set;for(const r of e){if(!WN(r)||n.has(r))continue;const s=f3.get(r);s&&(n.add(r),t.push(s))}for(const r of h1)n.has(r.id)||t.push(r);return t},HJ=e=>{if(!e)return{isLoading:!0,hasResult:!1,hasGitHubRepo:!1,hasError:!1};const t=e.scope?.repositories??[];return{isLoading:e.isLoading,hasResult:!!(e.scope||e.error),hasGitHubRepo:t.some(n=>!!(n.host&&n.owner&&n.repo&&!n.disabledReason)),hasError:!!(e.error&&!e.scope)}},GN=e=>!e||e.isLoading&&!e.hasResult?!1:e.hasError?!0:e.hasGitHubRepo,ZN=e=>KN(e.railOrder).filter(t=>t.availability==="has-content"?e.tabs.some(n=>n.mode===t.mode):t.availability==="github-repo"?e.tabs.some(n=>n.mode===t.mode)?!0:GN(e.githubScope):t.availability==="extensions"?e.tabs.some(n=>n.mode===t.mode)?!0:!!e.hasExtensionContent:!0),h3=3e4,us=()=>({scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),Mi=new Map,YN=(e,t)=>`${e}
|
|
46
|
+
${t}`,XN=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub scope check failed"}},Dl=e=>!e.host||!e.owner||!e.repo?null:L5(`${e.host}/${e.owner}/${e.repo}`),Ol=e=>!!(e.host&&e.owner&&e.repo&&!e.disabledReason),p1=(e,t)=>{if(!e)return t;const n=new Set(e.repositories.filter(Ol).map(i=>Dl(i)).filter(i=>!!i));if(t&&n.has(t))return t;if(e.defaultSelection&&n.has(e.defaultSelection))return e.defaultSelection;const r=e.repositories.find(i=>i.kind==="containing"&&Ol(i)),s=r?Dl(r):null;if(s&&n.has(s))return s;const o=e.repositories.find(Ol);return o?Dl(o):null},Ua=Et()(gr((e,t)=>({runtimeKey:Y(),entriesByDirectory:{},resetForRuntimeSwitch:n=>{const r=n??Y();Mi.clear(),e({runtimeKey:r,entriesByDirectory:{}})},ensureScope:async(n,r)=>{const s=gs(n.trim());if(!s)return us();const o=Y();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t().entriesByDirectory[s],a=Date.now();return i?.scope&&i.fetchedAt&&a-i.fetchedAt<h3&&!i.isLoading?i:t().refreshScope(s,r)},refreshScope:async(n,r,s)=>{const o=gs(n.trim());if(!o)return us();const i=Y();t().runtimeKey!==i&&t().resetForRuntimeSwitch(i);const a=YN(i,o),l=Mi.get(a);if(l&&!s?.force)return l;const d=r??null;if(!d)return t().entriesByDirectory[o]??us();const f=t().entriesByDirectory[o]??us();f.isLoading||e(h=>({entriesByDirectory:{...h.entriesByDirectory,[o]:{...f,isLoading:!0}}}));const u=(async()=>{try{const h=await d.scope(o);if(Y()!==i)return t().entriesByDirectory[o]??us();const m={scope:h,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null};e(b=>({entriesByDirectory:{...b.entriesByDirectory,[o]:m}}));const g=re.getState().githubSelectedRepoByDirectory[o]??null,x=p1(h,g);return x!==g&&re.getState().setGitHubSelectedRepo(o,x),m}catch(h){if(Y()!==i)return t().entriesByDirectory[o]??us();const m=XN(h),g=f.scope?{...f,isLoading:!1,stale:!0,error:m}:{scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:m};return e(x=>({entriesByDirectory:{...x.entriesByDirectory,[o]:g}})),g}})();Mi.set(a,u);try{return await u}finally{Mi.get(a)===u&&Mi.delete(a)}},setSelectedRepo:(n,r)=>{const s=gs(n.trim());if(!s)return;const o=t().entriesByDirectory[s]?.scope??null;if(r!=null){const i=L5(r);if(!i||o&&!new Set(o.repositories.filter(Ol).map(l=>Dl(l)).filter(l=>!!l)).has(i))return;re.getState().setGitHubSelectedRepo(s,i);return}re.getState().setGitHubSelectedRepo(s,null)},invalidate:async(n,r)=>{const s=gs(n.trim());if(!s)return null;const o=r??null;if(o)try{await o.invalidate({directory:s})}catch{}return t().refreshScope(s,o??void 0,{force:!0})}}),{name:"github-scope-store"}));typeof window<"u"&&en(e=>{Ua.getState().resetForRuntimeSwitch(e.runtimeKey)});const oy=Object.freeze(us()),JN=e=>Ua(t=>e?t.entriesByDirectory[gs(e)]??oy:oy),QN=e=>{const t=Ua(r=>e?r.entriesByDirectory[gs(e)]?.scope??null:null),n=re(r=>e?r.githubSelectedRepoByDirectory[gs(e)]??null:null);return p.useMemo(()=>e?p1(t,n):null,[e,t,n])},FJ=Object.freeze(Object.defineProperty({__proto__:null,GITHUB_SCOPE_STALE_MS:h3,resolveGitHubSelectedRepo:p1,useGitHubScope:JN,useGitHubScopeStore:Ua,useGitHubSelectedRepo:QN},Symbol.toStringTag,{value:"Module"})),Jn=()=>{const e=he(s=>s.currentSessionId),t=he(s=>s.newSessionDraft),n=o_(e),r=nt(s=>s.currentDirectory);return e&&n?n:t?.open&&t.directoryOverride?t.directoryOverride:r??void 0},eL=()=>({setCurrentVariant:e=>We.getState().setCurrentVariant(e)}),Fi=(e,t=eL())=>(t.setCurrentVariant(e),"applied"),tL=async(e=1)=>{const t=We.getState(),n=_m(t.getCurrentModelVariants(),t.currentVariant,e);return Fi(n),n},nL='[data-chat-input="true"] .cm-content';function To(){document.querySelector(nL)?.focus()}const rL=new Set(["address","article","aside","blockquote","dd","div","dl","dt","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","ul"]),m1=e=>e.replace(/\r\n?/g,`
|
|
47
|
+
`),wn=e=>m1(e).trim(),sL=e=>e.replace(/\s+/g," ").trim(),p3=e=>(e.match(/language-([\w+#.-]+)/)?.[1]||"").trim(),oL=e=>e.closest("pre")?.getAttribute("data-md-lang")||p3(e.className),m3=e=>{if(e.nodeType===3)return{type:"text",value:e.textContent||""};if(e.nodeType!==1)return null;const t=e;return{type:"element",tag:t.tagName.toLowerCase(),className:t.getAttribute("class")||"",href:t.getAttribute("href")||"",component:t.getAttribute("data-component")||"",markdownLanguage:t.getAttribute("data-md-lang")||"",isMarkdownBlock:t.hasAttribute("data-md-block"),isCodeLines:t.hasAttribute("data-md-code-lines"),isCodeLineNumber:t.hasAttribute("data-md-code-line-number"),children:Array.from(t.childNodes).map(n=>m3(n)).filter(n=>n!==null)}},g1=e=>e.filter(t=>t.type==="text"||!t.isCodeLineNumber).map(t=>t.type==="text"?t:{...t,children:g1(t.children)}),iL=e=>Array.from(e.childNodes).map(t=>m3(t)).filter(t=>t!==null),ua=e=>e.type==="text"?e.value:e.children.map(t=>ua(t)).join(""),Ap=(e,t)=>{if(e.type==="text")return null;if(t(e))return e;for(const n of e.children){const r=Ap(n,t);if(r)return r}return null},y1=(e,t="")=>{const n=m1(e).replace(/\n$/,""),r=Math.max(0,...Array.from(n.matchAll(/`+/g),o=>o[0].length)),s="`".repeat(Math.max(3,r+1));return`${s}${t}
|
|
48
|
+
${n}
|
|
49
|
+
${s}`},Ao=e=>{if(e.type==="text")return sL(e.value);const t=e.children.map(n=>Ao(n)).join("").replace(/\s+/g," ").trim();return!t&&e.tag!=="br"?"":e.tag==="br"?`
|
|
50
|
+
`:e.tag==="strong"||e.tag==="b"?`**${t}**`:e.tag==="em"||e.tag==="i"?`*${t}*`:e.tag==="code"?`\`${t.replace(/`/g,"\\`")}\``:e.tag==="a"&&e.href?`[${t}](${e.href})`:t},iy=(e,t)=>e.children.filter(n=>n.type==="element"&&n.tag==="li").map((n,r)=>{const s=n.children.map(o=>Ao(o)).join("").replace(/\s+/g," ").trim();return s?`${t?`${r+1}.`:"-"} ${s}`:""}).filter(Boolean).join(`
|
|
51
|
+
`),Bi=e=>{if(e.type==="text")return wn(e.value);if(e.isMarkdownBlock)return e.children.map(n=>Bi(n)).filter(n=>n.length>0).join(`
|
|
52
|
+
|
|
53
|
+
`);if(e.component==="markdown-code"){const n=Ap(e,r=>r.tag==="pre");return n?Bi(n):""}if(e.tag==="pre"||e.tag==="code"&&e.isCodeLines){const n=e.tag==="code"?e:Ap(e,r=>r.tag==="code");return y1(ua(n||e),e.markdownLanguage||p3(n?.className||""))}if(e.tag==="code"){const n=m1(ua(e)).trim();return n?`\`${n.replace(/`/g,"\\`")}\``:""}if(e.tag==="ul")return iy(e,!1);if(e.tag==="ol")return iy(e,!0);if(e.tag==="blockquote")return wn(e.children.map(r=>Bi(r)).join(`
|
|
54
|
+
`)).split(`
|
|
55
|
+
`).filter(r=>r.length>0).map(r=>`> ${r}`).join(`
|
|
56
|
+
`);if(/^h[1-6]$/.test(e.tag)){const n=Number.parseInt(e.tag[1],10),r=wn(e.children.map(s=>Ao(s)).join(""));return r?`${"#".repeat(n)} ${r}`:""}if(e.tag==="p"||e.tag==="div"||e.tag==="li")return wn(e.children.map(n=>Ao(n)).join(""));const t=e.children.map(n=>Bi(n)).filter(n=>n.length>0);return t.length>0?t.join(`
|
|
57
|
+
|
|
58
|
+
`):wn(e.children.map(n=>Ao(n)).join(""))},aL=e=>e.type==="text"?!0:!e.isMarkdownBlock&&!e.isCodeLines&&e.component!=="markdown-code"&&!rL.has(e.tag),cL=(e,t)=>{const n=g1(e);if(n.every(s=>aL(s))){const s=wn(n.map(o=>Ao(o)).join(""));if(s)return s}return n.map(s=>Bi(s)).filter(s=>s.length>0).join(`
|
|
59
|
+
|
|
60
|
+
`).trim()||wn(t)},ay=e=>(e.nodeType===1?e:e.parentElement)?.closest("pre code")??null,g3=(e,t)=>{const n=ay(e.startContainer),r=ay(e.endContainer),s=g1(iL(e.cloneContents()));return n&&n===r?y1(s.map(o=>ua(o)).join(""),oL(n)):cL(s,t)},v1=e=>{const t=Math.max(0,...Array.from(e.matchAll(/`+/g),r=>r[0].length)),n="`".repeat(Math.max(3,t+1));return`${n}md
|
|
61
|
+
${e}
|
|
62
|
+
${n}`},lL='[data-chat-input="true"]',x1=e=>{if(!e)return!1;const t=e;return!!(typeof t.closest=="function"?t:e.parentElement)?.closest(lL)},dL=e=>{if(x1(e))return null;const t=e.tagName?.toLowerCase();if(t==="textarea"){const n=e,r=n.selectionStart??0,s=n.selectionEnd??0,o=wn(n.value.slice(r,s));return o?(n.selectionStart=s,n.selectionEnd=s,o):null}if(t==="input"){const n=e,r=n.type?.toLowerCase()??"text";if(!["text","search","url","tel","password"].includes(r))return null;const s=n.selectionStart??0,o=n.selectionEnd??0,i=wn(n.value.slice(s,o));return i?(n.selectionStart=o,n.selectionEnd=o,i):null}return null},uL=()=>{if(typeof document>"u")return null;const e=document.activeElement;if(!e||typeof e.tagName!="string")return null;const t=dL(e);return t?v1(t):null},fL=()=>{if(typeof document>"u")return null;const e=document.querySelector(".cm-editor.cm-focused");if(!e||x1(e))return null;const t=bn.findFromDOM(e);if(!t)return null;const{from:n,to:r}=t.state.selection.main;if(n===r)return null;const s=wn(t.state.sliceDoc(n,r));return s?(t.dispatch({selection:{anchor:r}}),y1(s)):null},hL=()=>{if(typeof window>"u")return null;const e=window.getSelection();if(!e||e.rangeCount===0||e.isCollapsed)return null;const t=e.getRangeAt(0);if(x1(t.commonAncestorContainer))return null;const n=wn(e.toString());if(!n)return null;const r=g3(t,n);return e.removeAllRanges(),v1(r)},pL=()=>fL()??uL()??hL(),y3=()=>{const e=pL();return re.getState().setActiveMainTab("chat"),re.getState().setSessionSwitcherOpen(!1),e&&Ye.getState().setPendingInputText(e,"append"),queueMicrotask(()=>{To()}),e!==null},v3="file://";function mL(e){let t=e.replace(/\\/g,"/");return/^[A-Za-z]:/.test(t)&&(t=`/${t}`),t.split("/").map((n,r)=>r===1&&/^[A-Za-z]:$/.test(n)?n:encodeURIComponent(n)).join("/")}function gL(e){const t=e.replace(/\\/g,"/").trim();return t.toLowerCase().startsWith(v3)?t:`file://${mL(t)}`}function yL(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function cy(e){const t=e.trim().replace(/^['"]+|['"]+$/g,"");return!t||/[\r\n]/.test(t)?null:t.toLowerCase().startsWith(v3)||yL(t)?t:null}function Np(e,t,n=0){if(!(n>6||e==null)){if(typeof e=="string"){t.add(e);return}if(Array.isArray(e)){for(const r of e)Np(r,t,n+1);return}if(typeof e=="object")for(const r of Object.values(e))Np(r,t,n+1)}}function vL(e){const t=new Set,n=r=>{const s=cy(r);if(s){t.add(s);return}for(const o of r.split(/\r?\n/)){const i=cy(o);i&&t.add(i)}};n(e);try{const r=JSON.parse(e),s=new Set;Np(r,s);for(const o of s)n(o)}catch{}return Array.from(t)}function Yt(e){if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return n==="/"?"/":n.length>1?n.replace(/\/+$/,""):n}function xL(e,t){const n=e.replace(/\\/g,"/").trim(),r=(t||"").replace(/\\/g,"/").replace(/\/+$/,"");if(!r||n===r)return n;const s=`${r}/`;return n.startsWith(s)?n.slice(s.length):n}const bL=["CodeFiles","codefiles","application/vnd.code.tree","application/vnd.code.tree.explorer","text/uri-list","text/plain"],fr="__home__",wL="Don't work in a folder",SL=()=>"~",CL=e=>e.enabled&&e.isDraftOpen&&!!e.activeProjectId&&e.selectedProjectId!==fr&&e.selectedProjectId!==e.activeProjectId,kL=e=>{if(e.selectedProjectId===fr)return null;const t=e.selectedProjectId??e.activeProjectId,n=(t?e.projects.find(r=>r.id===t):null)??e.projects[0]??null;return n?za(n):null};function x3(e,t){const n=e.flatMap(o=>{const i={...o,id:o.id,ownerProjectId:o.id,kind:"project"},a=t.get(Yt(o.path)??o.path)??[];return[i,...a.map(l=>({id:`worktree:${o.id}:${l.path}`,ownerProjectId:o.id,kind:"worktree",path:l.path,branch:l.branch,label:l.branch||(l.detached?"Detached HEAD":l.name)}))]}),r=SL();return[{id:fr,ownerProjectId:fr,kind:"project",path:r,label:wL},...n]}const b3=Et()(gr(e=>({selectedSpaceId:null,selectedWorktreePath:null,selectSpace:t=>{e({selectedSpaceId:t,selectedWorktreePath:null})},selectWorktree:(t,n)=>{e({selectedSpaceId:t,selectedWorktreePath:n})},clearSpaceSelection:()=>{e({selectedSpaceId:null,selectedWorktreePath:null})},clearSelectedWorktree:()=>{e({selectedWorktreePath:null})}}),{name:"sidebar-space"}));function w3(e,t){if(e.length<=1)return null;const n=t?e.indexOf(t):-1;return e[(n+1)%e.length]??null}function Lp(e=1){const t=ct.getState(),n=t.projects;if(n.length<=1)return!1;const r=n.map(f=>f.id);let s=t.activeProjectId;if(!s||!r.includes(s)){const f=ce(nt.getState().currentDirectory??null);s=Zn(n,Ln(n,Qt.getState()),f)?.id??null}const o=e===1?w3(r,s):r[((s?r.indexOf(s):0)-1+r.length)%r.length]??null;if(!o)return!1;const i=n.find(f=>f.id===o),a=ce(i?.path??null);if(!i||!a)return!1;t.setActiveProjectIdOnly(o),b3.getState().selectSpace(o),re.getState().closeMainSurfaces();const l=Ln(n,Qt.getState()),d=yw().find(f=>{const u=ce(f.directory??null);return u?Zn(n,l,u)?.id===o:!1});if(d){const f=ce(d.directory??null);return he.getState().setCurrentSession(d.id,f),!0}return he.getState().openNewSessionDraft({selectedProjectId:o,directoryOverride:a}),!0}function ML(){const e=he.getState(),t=e.newSessionDraft;if(!t?.open)return!1;const n=ct.getState(),r=n.projects,s=x3(r,Ln(r,Qt.getState()));if(s.length<=1)return!1;const o=ce(t.directoryOverride??null),i=t.selectedProjectId?s.find(f=>f.ownerProjectId===t.selectedProjectId&&(!o||ce(f.path)===o))??s.find(f=>f.id===t.selectedProjectId)??(o?s.find(f=>ce(f.path)===o)??null:null):o?s.find(f=>ce(f.path)===o)??null:null,a=w3(s.map(f=>f.id),i?.id??null),l=s.find(f=>f.id===a),d=ce(l?.path??null);return!l||!d?!1:l.ownerProjectId===fr?(e.setNewSessionDraftTarget({projectId:fr,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0):(n.activeProjectId!==l.ownerProjectId&&(n.setActiveProjectIdOnly(l.ownerProjectId),b3.getState().selectSpace(l.ownerProjectId)),e.setNewSessionDraftTarget({projectId:l.ownerProjectId,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0)}const IL=['[data-slot="dropdown-menu-content"][data-open]','[data-slot="select-content"][data-open]'].join(",");function EL(e=document){return!!e.querySelector(IL)}const _L=(e,t)=>!e.repeat&&Tt(e,t),jL=e=>{const t=he.getState().currentSessionId;t&&qe().prompt(t,oC(e),"prompt").catch(()=>{})},TL=()=>{const e=he(M=>M.openNewSessionDraft),t=he(M=>M.armAbortPrompt),n=he(M=>M.clearAbortPrompt),r=he(M=>M.currentSessionId),s=Qm,o=re(M=>M.toggleCommandPalette),i=re(M=>M.toggleHelpDialog),a=re(M=>M.toggleSidebar),l=nt(M=>M.currentDirectory),d=Jn(),f=p.useCallback(()=>{l&&re.getState().openContextSurface(Ji(l),"terminal")},[l]),u=re(M=>M.isMobile),h=re(M=>M.setSessionSwitcherOpen),m=re(M=>M.setActiveMainTab),g=re(M=>M.setSettingsDialogOpen),x=re(M=>M.setModelSelectorOpen),b=re(M=>M.setTimelineDialogOpen),S=re(M=>M.setPromptNavigatorPanelOpen),y=re(M=>M.shortcutOverrides),v=nt(M=>M.currentDirectory),C=ct(M=>M.getActiveProject()),{themeMode:w,setThemeMode:I}=vr(),{phase:E}=f1(),T=p.useRef(null),A=p.useRef(null),j=p.useRef(w),k=p.useRef(new Set);p.useEffect(()=>{j.current=w},[w]);const _=p.useCallback(()=>{A.current&&(clearTimeout(A.current),A.current=null),T.current=null,n()},[n]);p.useEffect(()=>{const M=P=>sC(P,y),L=tC("switch_context_surface",y),O=['[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(","),N=P=>P instanceof Element&&!!P.closest(O),D=P=>{if(qf(P.target)&&Tt(P,M("toggle_terminal"))){const{isMobile:q}=re.getState();if(q)return;P.preventDefault(),P.stopPropagation(),f();return}},W=P=>{if(P.key!=="Escape")return;const q=P.target,B=!!q?.closest('[role="dialog"]'),ee=!!document.querySelector('[data-settings-view="true"]'),G=qf(q),K=N(q)||EL(),{isSettingsDialogOpen:se,isCommandPaletteOpen:de,isHelpDialogOpen:oe,isSessionSwitcherOpen:ue,isImagePreviewOpen:ye,activeMainTab:we,isPromptNavigatorPanelOpen:Me}=re.getState();if(B||G||K){_();return}if(Me){P.preventDefault(),S(!1),_();return}if(se){P.preventDefault(),g(!1),_();return}if(ee){_();return}if(de||oe||ue||ye||!(we==="chat")){_();return}const Ge=r,et=!!(Ge&&qe().getState().reducer.bySession.get(Ge)?.bashExecutions?.some(Se=>Se.phase==="running"));if(E==="idle"&&!et||!Ge){_();return}const Xe=Date.now(),te=T.current;if(te&&Xe<te){P.preventDefault(),_(),et?Nw(Ge).catch(()=>{Ce.error("Failed to stop the shell command")}):s(Ge);return}P.preventDefault();const Q=t(3e3)??Xe+3e3;T.current=Q,A.current&&clearTimeout(A.current);const me=Math.max(Q-Xe,0);A.current=setTimeout(()=>{T.current&&Date.now()>=T.current&&_()},me||0)},z=P=>{if(P.key==="Escape"||qf(P.target))return;if(Tt(P,M("open_command_palette"))){P.preventDefault(),o();return}if(Tt(P,M("open_timeline_dialog"))){P.preventDefault(),b(!0);return}if(Tt(P,M("open_help"))){P.preventDefault(),i();return}if(nC()&&Tt(P,M("new_mini_chat"))){P.preventDefault(),dr("desktop_open_draft_mini_chat_window",{directory:v||C?.path||"",projectId:C?.id??null}).catch(G=>{console.warn("[keyboard-shortcuts] failed to open draft mini chat window",G)});return}if(Tt(P,M("new_chat"))){P.preventDefault(),m("chat"),h(!1),e();return}if(Tt(P,M("cycle_theme"))){P.preventDefault();const G=["light","dark","system"],K=document.activeElement,de=(G.indexOf(j.current)+1)%G.length;I(G[de]),requestAnimationFrame(()=>{typeof document>"u"||typeof window>"u"||(document.hasFocus()||window.focus(),K&&document.contains(K)&&K.focus({preventScroll:!0}))});return}if(Tt(P,M("open_settings"))){P.preventDefault();const{isSettingsDialogOpen:G}=re.getState();g(!G);return}if(Tt(P,M("add_selection_to_chat"))){P.preventDefault(),y3();return}if(Tt(P,M("toggle_sidebar"))){P.preventDefault();const{isMobile:G,isSessionSwitcherOpen:K}=re.getState();G?h(!K):a();return}if(Tt(P,M("focus_input"))){P.preventDefault(),To();return}if(Tt(P,M("cycle_session_folder"))){if(!Lp())return;P.preventDefault();return}if(Tt(P,M("cycle_draft_folder"))){if(!ML())return;P.preventDefault();return}if(Tt(P,M("open_right_sidebar"))){const G=re.getState();if(G.isMobile||!v)return;P.preventDefault();const K=Ji(v),se=G.contextPanelByDirectory[K];if(se?.isOpen)return;se?.activeTabId?G.setActiveContextPanelTab(K,se.activeTabId):G.openContextSurface(K,"git");return}if(Tt(P,M("toggle_terminal"))){const{isMobile:G}=re.getState();if(G)return;P.preventDefault(),f();return}const B=P.key.length===1&&P.key>="0"&&P.key<="9"?P.key==="0"?10:Number(P.key):null;if(B!==null&&!P.repeat&&rC(P,L,k.current)){const G=re.getState();if(G.isMobile||!d)return;const K=Ji(d),se=G.contextPanelByDirectory[K];let de;const oe=Ua.getState().entriesByDirectory[K]??null;if(oe){const we=oe.scope?.repositories??[];de={isLoading:oe.isLoading,hasResult:!!(oe.scope||oe.error),hasGitHubRepo:we.some(Me=>!!(Me.host&&Me.owner&&Me.repo&&!Me.disabledReason)),hasError:!!(oe.error&&!oe.scope)}}const ye=ZN({railOrder:G.contextRailOrder,tabs:se?.tabs??[],githubScope:de})[B-1];if(!ye)return;P.preventDefault(),G.openContextSurface(K,ye.mode);return}if(_L(P,M("open_model_selector"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:de,activeMainTab:oe,isModelSelectorOpen:ue}=re.getState();if(G||K||se||de||!(oe==="chat"))return;P.preventDefault(),x(!ue);return}if(Tt(P,M("cycle_thinking_variant"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:de,activeMainTab:oe}=re.getState();if(G||K||se||de||!(oe==="chat")||We.getState().getCurrentModelVariants().length===0)return;P.preventDefault(),tL(1).catch(()=>{Ce.error("Couldn't update thinking")});return}if(Tt(P,M("cycle_favorite_model_forward"))||Tt(P,M("cycle_favorite_model_backward"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:de,activeMainTab:oe,favoriteModels:ue,addRecentModel:ye}=re.getState();if(G||K||se||de||!(oe==="chat")||ue.length===0)return;P.preventDefault();const{currentProviderId:He,currentModelId:Ae,setProvider:Ge,setModel:et}=We.getState(),Xe=ue.length,te=ue.findIndex(Se=>Se.providerID===He&&Se.modelID===Ae),Q=Tt(P,M("cycle_favorite_model_forward"))?1:-1,me=ue[(te+Q+Xe)%Xe];Ge(me.providerID),et(me.modelID),ye(me.providerID,me.modelID);return}const ee=re.getState().commandTriggers;if(ee.length>0&&!N(P.target)){for(const G of ee)if(!(!G.combo||!Tt(P,G.combo))){P.preventDefault(),P.stopPropagation(),jL(G);return}}},X=P=>{k.current.add(P.key.toLowerCase())},F=P=>{k.current.delete(P.key.toLowerCase())},U=()=>{k.current.clear()};return window.addEventListener("keydown",X,!0),window.addEventListener("keyup",F,!0),window.addEventListener("blur",U),window.addEventListener("keydown",D,!0),window.addEventListener("keydown",W,!0),window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",X,!0),window.removeEventListener("keyup",F,!0),window.removeEventListener("blur",U),window.removeEventListener("keydown",D,!0),window.removeEventListener("keydown",W,!0),window.removeEventListener("keydown",z)}},[e,s,o,i,a,f,u,h,m,g,x,b,S,I,E,t,_,r,v,d,C?.id,C?.path,y]),p.useEffect(()=>()=>{_()},[_])},AL=3,NL=(e,t)=>{if(typeof e!="string")return t;const n=e.trim().replace(/\s+/g," ");return n?n.slice(0,48):t},LL=(e,t)=>{const n=t?[...e.filter(o=>o.id===t),...e.filter(o=>o.id!==t)]:e,r=[],s=new Set;for(const o of n){const i=typeof o.id=="string"?o.id.trim():"";if(!(!i||s.has(i))&&(s.add(i),r.push({sessionId:i,title:NL(o.title,`Session ${r.length+1}`)}),r.length>=AL))break}return r},RL=()=>{const e=jw(),t=he(o=>o.currentSessionId),n=p.useMemo(()=>LL(e,t),[t,e]),r=p.useMemo(()=>JSON.stringify(n),[n]),s=n.length>0;p.useEffect(()=>{if(typeof window>"u"||!vm())return;try{s?localStorage.setItem(Qg,r):localStorage.removeItem(Qg)}catch{return}window.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[s,r])},PL=e=>{if(!e||typeof e!="object")return"unknown";const t=e;if(t.status==="accepted"){const n=t.receipt;return n?.accepted===!0&&typeof n.messageId=="string"?"accepted":"unknown"}return t.status==="pending"?"pending":t.status==="expired"?"expired":(t.status==="unknown","unknown")},DL=async(e,t)=>{try{const n=aC(e.runtimeKey);if(!t.streamEpoch||t.streamEpoch!==n)return"unknown";const r=await Ie.getSendReceipt({sessionId:e.sessionId,kind:t.kind,operationId:t.operationId,streamEpoch:t.streamEpoch},{directory:e.directory,runtimeKey:e.runtimeKey});return PL(r)}catch{return"unknown"}},S3=e=>e instanceof iC,OL=2e3,Er="hydrate-demand",C3=2e3,HL=6e4,FL=e=>Math.min(C3*2**Math.max(e-1,0),HL),ly=(e,t,n)=>e!==void 0&&e.messageId===t&&n<e.nextAttemptAt,BL=(e,t=Date.now,n=setTimeout,r=clearTimeout)=>{let s=null,o=null;return{schedule(i){o!==null&&o<=i||(s!==null&&r(s),o=i,s=n(()=>{s=null,o=null,e()},Math.max(0,i-t())))},dispose(){s!==null&&r(s),s=null,o=null}}},VL=e=>{const t=he.getState().sessionAbortFlags.get(e);if(!t)return null;const n=t.timestamp+OL;return Date.now()<n?n:null},$L=e=>{const t=e[0];return t?{queuedMessageId:t.id,primaryText:t.content,primaryAttachments:t.attachments??[],agentMentionName:void 0,sendConfig:t.sendConfig}:null},zL=(e,t,n,r)=>he.getState().sendMessage(t.primaryText,n.providerID,n.modelID,n.agent,t.primaryAttachments,t.agentMentionName,void 0,n.variant,"normal",{target:e,delivery:"followUp",operationId:t.queuedMessageId,...r?{streamEpoch:r}:{}}),UL=e=>{const t=We.getState(),n=Lt.getState(),r=n.getSessionAgentSelection(e)??void 0,s=n.getSessionModelSelection(e),o=r?n.getAgentModelForSession(e,r):null,i=o?.providerId??s?.providerId??t.currentProviderId??n.lastUsedProvider?.providerID,a=o?.modelId??s?.modelId??t.currentModelId??n.lastUsedProvider?.modelID,l=r&&i&&a?n.getAgentModelVariantForSession(e,r,i,a):void 0;return{providerID:i,modelID:a,agent:r,variant:l}},qL=(e,t)=>{if(e.connection!=="ready")return"unknown";const n=e.catalog.byId.get(t.sessionId);return!n||ce(n.directory)!==ce(t.directory)||n.archived?"unknown":n.lifecycle==="busy"||n.lifecycle==="retry"?"busy":n.hydrated?"ready":"unknown"};function WL(e){const t=typeof e=="boolean"?e:e?.enabled??!0,n=ft(h=>h.queuedMessages),r=nt(h=>h.currentDirectory),s=Ha(),o=Be(h=>h.catalog,void 0,yt),i=Be(h=>h.connection,void 0,At),a=p.useRef(new Set),l=p.useRef(new Map),[d,f]=p.useState(0),u=p.useMemo(()=>BL(()=>f(h=>h+1)),[]);p.useEffect(()=>()=>u.dispose(),[u]),p.useEffect(()=>{if(!t)return;const h=ft.getState().queuedMessages;for(const[S,y]of l.current)y.messageId===Er&&!(S in h)&&l.current.delete(S);const m=S=>{l.current.get(S)?.messageId===Er&&l.current.delete(S)},g=async(S,y,v)=>{const C=s.getState();if(C.connection!=="ready")return;const w=C.catalog.byId.get(y);if(!w||w.archived||ce(w.directory)!==ce(S.directory))return;const I=l.current.get(v);if(I?.messageId===Er&&ly(I,Er,Date.now())){u.schedule(I.nextAttemptAt);return}if(a.current.has(v))return;a.current.add(v);try{await s.ensureHydrated(y)}finally{a.current.delete(v),f(_=>_+1)}const E=s.getState();if(s.isDeleted(y)||!E.catalog.byId.has(y)){m(v);return}if(E.catalog.byId.get(y)?.hydrated){m(v);return}const j=(I?.messageId===Er?I.failures:0)+1,k=Date.now()+FL(j);l.current.set(v,{messageId:Er,failures:j,nextAttemptAt:k}),u.schedule(k)},x=async(S,y)=>{const{sessionId:v}=S,C=R5(S);if(y.length===0||S.runtimeKey!==Y()||a.current.has(C))return;const w=VL(v);if(w!==null){u.schedule(w);return}const I=s.getState(),E=qL(I,S);if(E==="busy")return;if(E==="unknown"){await g(S,v,C);return}const T=ft.getState().getAutoSendCandidate(S);if(!T)return;const A=l.current.get(C);if(A&&A.messageId!==T.id&&A.messageId!==Er)l.current.delete(C);else if(A&&A.messageId!==Er&&ly(A,T.id,Date.now())){Number.isFinite(A.nextAttemptAt)&&u.schedule(A.nextAttemptAt);return}const j=ft.getState().claimQueuedMessage(S,T.id);if(!j)return;const k=$L([j]);if(!k){ft.getState().clearSending(S,j.id);return}const _=k.sendConfig,M=_?.providerID&&_?.modelID?_:UL(v);if(!M.providerID||!M.modelID){ft.getState().clearSending(S,j.id),u.schedule(Date.now()+C3);return}a.current.add(C);const L=ft.getState().markDeliveryAttempt(S,j.id,"followUp");if(!L?.streamEpoch){a.current.delete(C),ft.getState().clearSending(S,j.id);return}try{await zL(S,k,{providerID:M.providerID,modelID:M.modelID,agent:M.agent,variant:M.variant},L.streamEpoch),ft.getState().completeQueuedSend(S,k.queuedMessageId),l.current.delete(C)}catch(O){console.warn("[follow-up] auto-send failed:",O);const N=A?.messageId===k.queuedMessageId?A.failures:0;l.current.set(C,{messageId:k.queuedMessageId,failures:N+1,nextAttemptAt:Number.POSITIVE_INFINITY}),S3(O)?(ft.getState().markSendUnconfirmed(S,k.queuedMessageId,"followUp"),Ce.error("Follow-up status uncertain. Check status before retrying.",{id:`follow-up-unconfirmed:${C}:${k.queuedMessageId}`})):(ft.getState().markSendFailed(S,k.queuedMessageId),Ce.error("Follow-up message failed to send. Use Send now to retry.",{id:`follow-up-failed:${C}:${k.queuedMessageId}`}))}finally{a.current.delete(C),ft.getState().clearSending(S,k.queuedMessageId)}};Object.entries(n).forEach(([S,y])=>{const v=cC(S);!v||v.runtimeKey!==Y()||v.directory!==r||y.length!==0&&x(v,y)})},[t,n,r,o,i,d,u,s])}const k3=1440*60*1e3,KL=(e,t,n)=>{const r={...e};return Object.hasOwn(t,"snoozedUntil")&&(delete r.snoozedUntil,delete r.snoozedAt,typeof t.snoozedUntil=="number"&&(r.snoozedUntil=t.snoozedUntil,r.snoozedAt=n)),Object.keys(r).length>0?r:void 0},GL=(e,t,n)=>typeof e?.snoozedUntil=="number"&&e.snoozedUntil>t&&!n,ZL=(e,t)=>typeof e?.snoozedUntil=="number"&&e.snoozedUntil<=t,YL=e=>{const t=ZL(e.entry,e.now)?e.entry.snoozedUntil:0;return Math.max(e.updatedAt,t)},XL=(e,t)=>{if(!(t>0)||e.open||e.pinned||e.working||e.needsInput||typeof e.entry?.snoozedUntil=="number"&&e.entry.snoozedUntil>e.now)return!1;const n=YL(e);return n>0?n<e.now-t*k3:!1},BJ=e=>GL(e.entry,e.now,e.needsInput)?"snoozed":e.pinned?"pinned":e.workingShelf&&e.working&&!e.needsInput?"working":"active",VJ=(e,t)=>{let n=null;for(const r of Object.values(e)){const s=r.snoozedUntil;typeof s=="number"&&s>t&&(n===null||s<n)&&(n=s)}return n},JL=[{kind:"after",minutes:60},{kind:"after",minutes:180},{kind:"at",day:"today",time:"18:00"},{kind:"at",day:"tomorrow",time:"09:00"},{kind:"at",day:"monday",time:"09:00"}],Gf=(e,t)=>`${e} ${t}${e===1?"":"s"}`,QL=e=>e%1440===0?Gf(e/1440,"day"):e%60===0?Gf(e/60,"hour"):Gf(e,"minute"),M3=e=>e.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),eR=(e,t)=>e==="today"?0:e==="tomorrow"?1:(1-t.getDay()+7)%7||7,tR=(e,t)=>{if(e.kind==="after")return`In ${QL(e.minutes)}`;if(t===0){const n=Number(e.time.slice(0,2));return n<12?"This morning":n<17?"This afternoon":"This evening"}return t===1?"Tomorrow":"Next week"},nR=(e,t)=>{let n,r=0;if(e.kind==="after")n=new Date(t.getTime()+e.minutes*6e4);else if(r=eR(e.day,t),n=new Date(t.getFullYear(),t.getMonth(),t.getDate()+r),n.setHours(Number(e.time.slice(0,2)),Number(e.time.slice(3)),0,0),n.getTime()<=t.getTime())return null;const s=tR(e,r),o=e.kind==="at"&&s!=="Next week",i=M3(n);return{id:e.kind==="after"?`after:${e.minutes}`:`at:${e.day}:${e.time}`,label:s,whenLabel:o||n.toDateString()===t.toDateString()?i:`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`,snoozedUntil:n.getTime()}},$J=e=>{const t=new Set;return JL.flatMap(n=>nR(n,e)??[]).sort((n,r)=>n.snoozedUntil-r.snoozedUntil).filter(n=>{const r=Math.floor(n.snoozedUntil/6e4);return t.has(r)?!1:(t.add(r),!0)})},zJ=(e,t)=>{const n=new Date(e),r=new Date(t),s=M3(n);return n.toDateString()===r.toDateString()?s:e-t<6*k3?n.toLocaleDateString(void 0,{weekday:"short"}):n.toLocaleDateString(void 0,{month:"short",day:"numeric"})};let dy=0;const Vi=new Map;let Hl=0;const Zf=(e,t,n)=>{const r={...e};return n?r[t]=n:delete r[t],r},uy=e=>{Vi.clear(),Hl+=1,No.setState({runtimeKey:e,entries:{},status:"idle"})},No=Et((e,t)=>({runtimeKey:null,entries:{},status:"idle",load:async()=>{const n=Y();t().runtimeKey!==n&&uy(n);const r=++Hl,s=dy;t().status!=="ready"&&e({status:"loading"});try{const{sessions:o}=await Ie.getSessionShelf({runtimeKey:n});if(r!==Hl||Y()!==n)return;const i=t().entries,a={...o};for(const[l,d]of Vi)d<=s||(i[l]?a[l]=i[l]:delete a[l]);e({entries:a,status:"ready"})}catch(o){if(r!==Hl||Y()!==n)return;e({status:"failed"}),console.warn("[session-shelf] could not read the session shelf",o)}},update:async(n,r,s)=>{const o=Y();t().runtimeKey!==o&&uy(o);const i=t().entries[n],a=++dy;Vi.set(n,a),e({entries:Zf(t().entries,n,KL(i,r,Date.now()))});try{const l=await Ie.setSessionShelf({sessionId:n,...r},{runtimeKey:o,...s?{directory:s}:{}});if(Y()!==o||Vi.get(n)!==a)return;e({entries:Zf(t().entries,n,l)})}catch(l){throw Y()===o&&Vi.get(n)===a&&e({entries:Zf(t().entries,n,i)}),l}}})),rR=1440*60*1e3,sR=3600*1e3,oR=1e4,I3=(e,t)=>e.archived?!1:XL({entry:t.shelfEntries[e.id],pinned:cd(t.pinnedIds,e.directory,e.id),working:e.lifecycle==="busy"||e.lifecycle==="retry",needsInput:e.pendingInput!=null,updatedAt:e.updatedAt,now:t.now,open:e.id===t.currentSessionId},t.archiveDays),E3=(e,t)=>!(t.deleteDays>0)||!e.archived||e.id===t.currentSessionId||typeof e.archivedAt!="number"||!(e.archivedAt>0)?!1:e.archivedAt<t.now-t.deleteDays*rR,iR=(e,t)=>{const n=[],r=[];for(const s of e)I3(s,t)?n.push(s.id):E3(s,t)&&r.push(s.id);return{archive:n,delete:r}},aR=(e,t,n)=>{const r=[],s=[];for(const o of e){const i=t.get(o),a=i?n1(i):null;a&&n.has(a)?r.push(o):s.push(o)}return{actionable:r,unready:s}},cR=()=>{try{const e=qe();return{store:e,runtimeKey:Y(),generation:e.getRuntimeGeneration()}}catch{return null}},Rp=e=>{try{const t=qe();return t!==e.store||Y()!==e.runtimeKey?!1:t.getRuntimeGeneration()===e.generation}catch{return!1}},_3=()=>{const e=re.getState();return{archiveDays:e.sessionAutoArchiveAfterDays??0,deleteDays:e.sessionAutoDeleteAfterDays??0}},Pp=(e,t)=>{const n=No.getState();return{..._3(),currentSessionId:he.getState().currentSessionId??null,pinnedIds:Rm.getState().ids,shelfEntries:n.entries,shelfReady:n.status==="ready"&&n.runtimeKey===e.runtimeKey,now:t}};let Yf=!1;const sr=()=>({completedIds:[],failedIds:[],skippedReason:"disabled"}),fs=()=>({completedIds:[],failedIds:[],skippedReason:"partial"}),Xf=()=>({completedIds:[],failedIds:[],skippedReason:"stale"}),lR={isCandidate:(e,t)=>t.shelfReady&&I3(e,t),write:(e,t,n)=>e.archive(t,!0,n)},dR={isCandidate:(e,t)=>E3(e,t),write:(e,t,n)=>e.remove(t,n)},fy=async(e,t,n,r,s,o)=>{let i,a;try{const h=Pp(t,o);i=[],a=new Map;for(const m of n.byId.values())e.isCandidate(m,h)&&(i.push(m.id),a.set(m.id,Ns(m)))}catch{return fs()}const{actionable:l,unready:d}=aR(i,a,r),f=[],u=[...d];for(let h=0;h<l.length;h+=1){const m=l[h];if(!Rp(t))return u.push(...l.slice(h)),{completedIds:f,failedIds:u,skippedReason:"stale"};let g=null;try{const x=Pp(t,o),b=qe().getState().catalog,S=b.byId.get(m);if(S&&e.isCandidate(S,x)){const y=n1(Ns(S));y&&b.listStatusByDirectory.get(y)==="ready"&&(g=y)}}catch{g=null}if(!g){u.push(m);continue}try{await e.write(qe(),m,g)}catch{u.push(m);continue}if(!Rp(t))return u.push(m,...l.slice(h+1)),{completedIds:f,failedIds:u,skippedReason:"stale"};f.push(m)}return s||u.length>0?{completedIds:f,failedIds:u,skippedReason:"partial"}:{completedIds:f,failedIds:u}},uR=(e,t)=>{const n=[e.skippedReason,t.skippedReason];if(n.includes("stale"))return"stale";if(n.includes("partial"))return"partial";if(n.every(r=>r==="disabled"))return"disabled"},hy=async({now:e}={})=>{if(Yf)return{archive:sr(),delete:sr(),skippedReason:"running"};let t;try{t=_3()}catch{return{archive:fs(),delete:fs(),skippedReason:"partial"}}const n=t.archiveDays>0,r=t.deleteDays>0;if(!n&&!r)return{archive:sr(),delete:sr(),skippedReason:"disabled"};const s=(l,d)=>({archive:l,delete:d,skippedReason:uR(l,d)}),o=l=>s(n?l():sr(),r?l():sr()),i=cR();if(!i)return o(Xf);const a=e??Date.now();Yf=!0;try{let l;try{const h=n?No.getState().load():Promise.resolve();[l]=await Promise.all([ON(),h])}catch{return o(fs)}if(l.stale||!Rp(i))return o(Xf);if(l.readyDirectories.size===0)return o(fs);const d=l.failedDirectories.size>0;let f=sr();if(n&&(f=Pp(i,a).shelfReady?await fy(lR,i,l.catalog,l.readyDirectories,d,a):fs(),f.skippedReason==="stale"))return s(f,r?Xf():sr());let u=sr();return r&&(u=await fy(dR,i,qe().getState().catalog,l.readyDirectories,d,a)),s(f,u)}catch{return o(fs)}finally{Yf=!1}},fR=new Map,hR={archive:[],delete:[]},pR=e=>{const t=typeof e=="object"?e:void 0,n=t?.autoRun!==!1,r=typeof e=="boolean"?e:t?.enabled??!0,s=r&&!n,o=re(S=>S.sessionAutoArchiveAfterDays),i=re(S=>S.sessionAutoDeleteAfterDays),a=he(S=>S.currentSessionId),l=Rm(S=>S.ids),d=No(S=>S.entries),f=No(S=>S.status==="ready"&&S.runtimeKey===Y()),u=Be(S=>s?S.catalog.byId:fR,void 0,"catalog");p.useEffect(()=>{s&&No.getState().load()},[s]);const h=p.useMemo(()=>{if(!s)return hR;const S=iR(u.values(),{archiveDays:o,deleteDays:i,currentSessionId:a??null,pinnedIds:l,shelfEntries:d,now:Date.now()});return f?S:{...S,archive:[]}},[s,f,u,o,i,a,l,d]),[m,g]=p.useState(!1),x=p.useCallback(async()=>{g(!0);try{return await hy()}finally{g(!1)}},[]),b=r&&n&&(o>0||i>0);return p.useEffect(()=>{if(!b)return;const S=()=>{hy()},y=window.setTimeout(S,oR),v=window.setInterval(S,sR);return()=>{window.clearTimeout(y),window.clearInterval(v)}},[b]),{archiveCandidates:h.archive,deleteCandidates:h.delete,isRunning:m,runCleanup:x}},Jf=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:"0px",Qf=(e,t,n)=>{const r=e.style.getPropertyValue(t);r===n||!r&&n==="0px"||e.style.setProperty(t,n)},eh=(e,t,n,r)=>{Qf(e,"--oc-wco-left-inset",Jf(t)),Qf(e,"--oc-wco-right-inset",Jf(n)),Qf(e,"--oc-wco-titlebar-height",Jf(r))},mR=()=>{p.useEffect(()=>{if(typeof window>"u"||!vm())return;const e=document.documentElement,t=typeof window.matchMedia=="function"?window.matchMedia("(display-mode: window-controls-overlay)"):null,r=window.navigator.windowControlsOverlay,s=()=>{if(!r||!t?.matches||!r.visible){eh(e,0,0,0);return}const i=r.getTitlebarAreaRect(),a=Math.max(0,Number(i.x)||0),l=Math.max(0,Number(i.width)||0),d=Math.max(0,Number(i.height)||0),f=Math.max(0,window.innerWidth-(a+l));eh(e,a,f,d)},o=()=>{s()};return s(),window.addEventListener("resize",s),window.addEventListener("focus",s),t&&(typeof t.addEventListener=="function"?t.addEventListener("change",o):typeof t.addListener=="function"&&t.addListener(o)),r&&typeof r.addEventListener=="function"&&r.addEventListener("geometrychange",s),()=>{window.removeEventListener("resize",s),window.removeEventListener("focus",s),t&&(typeof t.removeEventListener=="function"?t.removeEventListener("change",o):typeof t.removeListener=="function"&&t.removeListener(o)),r&&typeof r.removeEventListener=="function"&&r.removeEventListener("geometrychange",s),eh(e,0,0,0)}},[])},gR=()=>{};async function yR(e,t){if(!e?.listen)return gR;const n=[];try{n.push(await e.listen("pichamber:menu-action",r=>{typeof r.payload=="string"&&t.onAction(r.payload)})),n.push(await e.listen("pichamber:check-for-updates",()=>{t.onCheckForUpdates()})),n.push(await e.listen("pichamber:open-mini-chat",()=>{t.onOpenMiniChat?.()}))}catch(r){for(const s of n)s();throw r}return()=>{for(const r of n)r()}}const Xc=e=>{const t=re.getState();e&&t.setSettingsPage(e),t.setSettingsDialogOpen(!0)},py=e=>{const t=yw();if(t.length<2)return;const n=he.getState(),r=t.findIndex(i=>i.id===n.currentSessionId),s=r<0?e===1?-1:0:r,o=t[(s+e+t.length)%t.length];o&&n.setCurrentSession(o.id,n1(o))};function vR(){const{setThemeMode:e}=vr(),t=p.useCallback(s=>{const o=re.getState();switch(s){case"about":Xc("about");return;case"settings":Xc();return;case"command-palette":o.setCommandPaletteOpen(!0);return;case"new-session":o.setActiveMainTab("chat"),o.setSessionSwitcherOpen(!1),he.getState().openNewSessionDraft();return;case"change-workspace":Cu.requestDirectoryDialog();return;case"add-selection-to-chat":y3();return;case"open-right-sidebar":{const i=nt.getState().currentDirectory;if(!i)return;const a=Ji(i),l=o.contextPanelByDirectory[a];if(l?.isOpen)return;l?.activeTabId?o.setActiveContextPanelTab(a,l.activeTabId):o.openContextSurface(a,"git");return}case"toggle-terminal":{const i=nt.getState().currentDirectory;i&&o.openContextSurface(Ji(i),"terminal");return}case"theme-light":e("light");return;case"theme-dark":e("dark");return;case"theme-system":e("system");return;case"toggle-sidebar":o.isMobile?o.setSessionSwitcherOpen(!o.isSessionSwitcherOpen):o.toggleSidebar();return;case"toggle-memory-debug":Yl(!Xo());return;case"go-back":window.history.back();return;case"go-forward":window.history.forward();return;case"previous-session":py(-1);return;case"next-session":py(1);return;case"previous-project":Lp(-1);return;case"next-project":Lp(1);return;case"help-dialog":o.setHelpDialogOpen(!0);return;case"download-logs":Xc("general"),Yl(!0);return;case"copy":return;default:return}},[e]),n=p.useCallback(()=>{Xc("about"),JT.getState().checkForUpdates()},[]),r=p.useCallback(()=>{const s=ct.getState().getActiveProject();dr("desktop_open_draft_mini_chat_window",{directory:nt.getState().currentDirectory||s?.path||"",projectId:s?.id??null}).catch(o=>{console.warn("[desktop-menu] failed to open draft mini chat window",o)})},[]);p.useEffect(()=>{if(!Vr())return;let s=!1,o=()=>{};return yR(lC(),{onAction:t,onCheckForUpdates:n,onOpenMiniChat:r}).then(i=>{s?i():o=i}).catch(i=>{console.warn("[desktop-menu] failed to subscribe to application menu events",i)}),()=>{s=!0,o()}},[t,n,r])}const xR=()=>{const e=ct.getState().projects,t=Ln(e,Qt.getState()),n=[...u3(e,t,{includeWorktrees:!0})];try{const r=[nt.getState().homeDirectory,Gt().getItem("homeDirectory"),typeof window<"u"?window.__PICHAMBER_HOME__:null],s=new Set(n.map(o=>ce(o)?.toLowerCase()??o));for(const o of r){if(!o)continue;const i=ce(o);if(!i)continue;const a=i.toLowerCase();s.has(a)||(s.add(a),n.push(i))}}catch{}return n},bR=e=>e.length===0?"":[...e].sort().join("|"),wR=()=>(H.useEffect(()=>{let e=!1,t="";const n=qe(),r=()=>{if(e)return;const a=xR();if(a.length===0)return;const l=bR(a);if(l===t)return;const d=n.getState();if(d.connection!=="ready"||d.sessionsListStatus==="loading"||d.selectedSessionId&&d.focusPending&&d.sessionsListStatus!=="failed")return;const f=a.filter(u=>{const h=n.getState().catalog.listStatusByDirectory.get(u);return h!=="ready"&&h!=="loading"});if(f.length===0){t=l;return}t=l,n.refreshAllDirectoryCatalogs(f)};r();const s=ct.subscribe(r),o=Qt.subscribe(r),i=n.subscribe(r,"chrome");return()=>{e=!0,s(),o(),i()}},[]),null),qa=()=>{const e=p.useContext($a);if(!e)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return e},SR=6e4,CR=2,kR=()=>{const e=ct(l=>l.projects),t=Qt(l=>l.refreshProject),{git:n}=qa(),r=p.useMemo(()=>e.map(l=>l.path).filter(l=>!!l),[e]),s=p.useMemo(()=>[...r].sort().join("\0"),[r]),o=Y(),i=p.useCallback(async()=>{if(!n||r.length===0)return;let l=0;const d=async()=>{for(;l<r.length;){const f=r[l];l+=1,await t(f,n)}};await Promise.all(Array.from({length:Math.min(CR,r.length)},()=>d()))},[n,r,t]),a=p.useRef(null);return p.useEffect(()=>{const l=`${o}\0${s}`;a.current!==l&&(a.current=l,i())},[o,s,i]),p.useEffect(()=>{const l=()=>{i()},d=()=>{document.visibilityState==="visible"&&i()};window.addEventListener("focus",l),document.addEventListener("visibilitychange",d);const f=window.setInterval(()=>{document.visibilityState==="visible"&&i()},SR);return()=>{window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",d),window.clearInterval(f)}},[i]),null},my=2e3,MR=3e4,IR=2;class ER{constructor(t){this.options=t}options;timer=null;currentDelayMs=my;inFlight=!1;disposed=!1;get isRunning(){return this.inFlight||this.timer!==null}get currentBackoffDelayMs(){return this.currentDelayMs}isMismatched(){return this.options.getConnection()==="ready"&&(!this.options.getIsInitialized()||!this.options.getIsConnected())}isHidden(){return this.options.isDocumentHidden?this.options.isDocumentHidden():typeof document<"u"&&document.visibilityState==="hidden"}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}resetDelay(){this.currentDelayMs=my}reconcile(){this.check(!1)}wake(){this.check(!0)}check(t){if(!this.disposed){if(!this.isMismatched()){this.clearTimer(),this.resetDelay();return}if(this.isHidden()){this.clearTimer();return}!t&&(this.inFlight||this.timer!==null)||this.executeAttempt()}}resetForRuntimeSwitch(){this.clearTimer(),this.resetDelay()}dispose(){this.disposed=!0,this.clearTimer()}async executeAttempt(){if(this.clearTimer(),this.disposed||this.inFlight)return;if(!this.isMismatched()){this.resetDelay();return}if(this.isHidden())return;this.inFlight=!0,Rr("config-reconcile",{code:"attempt"});try{await this.options.initializeApp()}catch{}finally{this.inFlight=!1}if(this.disposed)return;if(!this.isMismatched()){Rr("config-reconcile",{code:"success"}),this.resetDelay();return}if(Rr("config-reconcile",{code:"failure"}),this.isHidden())return;const t=this.currentDelayMs;this.currentDelayMs=Math.min(t*IR,MR),this.timer=setTimeout(()=>{this.timer=null,this.executeAttempt()},t)}}function _R({connection:e,isInitialized:t,isConnected:n,initializeApp:r}){const s=p.useRef({connection:e,isInitialized:t,isConnected:n,initializeApp:r});s.current={connection:e,isInitialized:t,isConnected:n,initializeApp:r};const o=p.useRef(null);p.useEffect(()=>{o.current?.reconcile()},[e,t,n]),p.useEffect(()=>{const i=new ER({getConnection:()=>s.current.connection,getIsInitialized:()=>s.current.isInitialized,getIsConnected:()=>s.current.isConnected,initializeApp:()=>s.current.initializeApp()});o.current=i,i.reconcile();const a=()=>{typeof document<"u"&&document.visibilityState==="visible"?i.wake():i.reconcile()},l=()=>{i.wake()};typeof document<"u"&&document.addEventListener("visibilitychange",a),typeof window<"u"&&window.addEventListener("online",l);const d=en(()=>{i.resetForRuntimeSwitch(),i.reconcile()});return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",a),typeof window<"u"&&window.removeEventListener("online",l),d(),i.dispose(),o.current===i&&(o.current=null)}},[])}const jR="pichamber:mini-chat-presence",TR=()=>(p.useEffect(()=>{if(typeof BroadcastChannel>"u")return;const e=new BroadcastChannel(jR);return e.onmessage=t=>{const n=t.data;if(n?.type!=="mini-chat-session-presence"||!n.sessionId||!n.directory)return;n.viewed!==!1&&nu(n.sessionId)},()=>e.close()},[]),null);function AR({embeddedBackgroundWorkEnabled:e}){return pR(e),WL(e),c.jsx(wR,{})}const NR=()=>{const e=p.useMemo(()=>qe(),[]),t=p.useMemo(()=>a=>e.subscribe(a,"chrome"),[e]),n=p.useSyncExternalStore(t,e.getState,e.getState),{selectedSessionId:r,directory:s,connection:o,focusPending:i}=n;return p.useEffect(()=>{if(!s||ce(e.getState().directory)!==ce(s))return;const a=nt.getState().currentDirectory;ce(a)!==ce(s)&&nt.getState().setDirectory(s,{showOverlay:!1}),We.getState().activateDirectory(s)},[s,e]),p.useEffect(()=>{const a=he.getState();if(!r||!s){if(o==="loading"||i)return;(a.currentSessionId!==null||a.currentSessionDirectory!==null)&&he.setState({currentSessionId:null,currentSessionDirectory:null});return}if(!i&&!Ym(a.newSessionDraft,a.currentSessionId)&&(a.currentSessionId!==r||a.currentSessionDirectory!==s)){const l=a.newSessionDraft?.open?{newSessionDraft:{id:null,open:!1,selectedProjectId:null,directoryOverride:null,branchIntent:null,worktreeIntent:null,preserveDirectoryOverride:!1,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0,targetFolderId:void 0}}:{};he.setState({currentSessionId:r,currentSessionDirectory:s,...l}),nu(r)}},[r,s,o,i]),null},LR=()=>{const e=p.useMemo(()=>qe(),[]),t=p.useMemo(()=>l=>e.subscribe(l,"chrome"),[e]),n=p.useSyncExternalStore(t,e.getState,e.getState),r=We(l=>l.initializeApp),s=We(l=>l.isInitialized),o=We(l=>l.isConnected),i=We(l=>l.loadProviders),a=We(l=>l.providers.length);return _R({connection:n.connection,isInitialized:s,isConnected:o,initializeApp:r}),p.useEffect(()=>{!n.directory||n.connection!=="ready"||!o||a===0&&i({source:"webApp:recovery"})},[o,i,n.connection,n.directory,a]),null};function UJ({embeddedBackgroundWorkEnabled:e}){return RL(),mR(),TL(),vR(),c.jsxs(c.Fragment,{children:[c.jsx(LR,{}),c.jsx(AR,{embeddedBackgroundWorkEnabled:e}),c.jsx(NR,{}),c.jsx(TR,{}),c.jsx(kR,{})]})}const j3=({text:e})=>c.jsx("span",{"aria-hidden":"true",className:"oc-shimmer-clip",children:c.jsx("span",{className:"oc-shimmer-band","data-shimmer-text":e})}),RR=Array.from({length:9},(e,t)=>{const n=Math.floor(t/3);return(t%3+Math.abs(n-1))*90}),PR=650;function th({compact:e=!1}){return c.jsx("span",{"aria-hidden":"true",className:e?"grid shrink-0 grid-cols-[repeat(3,3px)] gap-[1px]":"grid shrink-0 grid-cols-[repeat(3,4px)] gap-[1.5px]",children:RR.map((t,n)=>c.jsx("span",{className:e?"pixel-loader-cell size-[3px] rounded-full bg-current":"pixel-loader-cell size-[4px] rounded-full bg-current",style:{opacity:.15,animation:`pixel-on ${PR}ms ease-in-out ${t}ms infinite`}},n))})}function DR(e,t){const[n,r]=p.useState(0),[s]=p.useState(()=>Date.now());if(p.useEffect(()=>{if(!e||t===null)return;const a=setInterval(()=>r(l=>l+1),100);return()=>clearInterval(a)},[e,t]),!e||t===null)return null;const o=t??s,i=Math.max(0,(Date.now()-o)/1e3);return i<60?`${i.toFixed(1)}s`:`${Math.floor(i/60)}m ${(i%60).toFixed(1)}s`}const gy=({text:e="Thinking",className:t,variant:n="inline",showText:r=!0,showElapsed:s=!0,animateText:o=!1,startedAt:i})=>{const a=r&&e!=null&&e!=="",l=DR(a&&s,i),d=a?c.jsxs("span",{className:R("pixel-loader-label min-w-0 truncate whitespace-nowrap typography-markdown font-medium",o&&"agent-thinking-label-enter"),children:[e,c.jsx(j3,{text:e})]},o?e:void 0):null,f=a&&s&&l!==null?c.jsx("span",{className:"shrink-0 whitespace-nowrap font-mono typography-code text-muted-foreground tabular-nums",children:l}):null;return n==="badge"?c.jsxs("span",{className:R("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-normal","bg-primary/10 text-primary border border-primary/20","transition-opacity duration-300",t),role:"status","aria-live":"polite",children:[c.jsx(th,{compact:!a}),d,f]}):n==="full"?c.jsxs("div",{className:R("flex items-center gap-2.5 rounded-lg border border-primary/25 bg-primary/5 px-3 py-1.5 text-sm text-foreground",t),role:"status","aria-live":"polite",children:[c.jsx(th,{compact:!a}),d,f]}):c.jsxs("span",{className:R("inline-flex min-w-0 items-center gap-2.5",t),role:"status","aria-live":"polite",children:[c.jsx(th,{compact:!a}),d,f]})},yy="pichamber:chunk-import-reload",OR=250,HR=3e4,FR=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function T3(e){if(e instanceof Error)return`${e.name}
|
|
63
|
+
${e.message}
|
|
64
|
+
${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function vy(e){const t=T3(e);return FR.some(n=>n.test(t))}function BR(e){return`1.0.6-rc.5:${T3(e).slice(0,500)}`}function VR(e){if(typeof window>"u")return;const t=Date.now(),n=BR(e);let r=null;try{const o=window.sessionStorage.getItem(yy);if(o)try{r=JSON.parse(o)}catch{r=null}}catch{return}const s=typeof r?.timestamp=="number"?r.timestamp:0;if(!(r?.signature===n&&t-s<HR)){try{window.sessionStorage.setItem(yy,JSON.stringify({signature:n,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function $R(e,t={}){const n=t.retries??1;let r;for(let s=0;s<=n;s+=1)try{return await e()}catch(o){if(r=o,!vy(o)||s>=n)break;await new Promise(i=>setTimeout(i,OR*(s+1)))}throw vy(r)&&VR(r),r}const Hs=e=>H.lazy(()=>$R(e)),zR=Hs(()=>r1().then(e=>({default:e.MarkdownRenderer}))),UR=Hs(()=>r1().then(e=>({default:e.SimpleMarkdownRenderer}))),qR=c.jsx("div",{className:"break-words w-full min-w-0"}),WR=e=>e==="tool"?"markdown-content markdown-tool":e==="reasoning"?"markdown-content markdown-reasoning":"markdown-content leading-relaxed",A3=e=>!un()||typeof e.content!="string"||e.content.length===0?qR:c.jsx("div",{className:R("break-words w-full min-w-0 whitespace-pre-wrap",WR(e.variant),typeof e.className=="string"?e.className:void 0),children:e.content}),qo=e=>c.jsx(p.Suspense,{fallback:c.jsx(A3,{...e}),children:c.jsx(zR,{...e})}),Wa=e=>c.jsx(p.Suspense,{fallback:c.jsx(A3,{...e}),children:c.jsx(UR,{...e})}),KR=O5(["border-input flex items-center justify-between gap-2 rounded-md border bg-transparent","typography-ui-label whitespace-nowrap shadow-none outline-none text-left","hover:bg-interactive-hover data-[popup-open]:bg-interactive-active","focus-visible:outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","disabled:cursor-not-allowed disabled:opacity-50","[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='text-'])]:text-muted-foreground"].join(" "),{variants:{size:{sm:"h-6 min-h-6 px-2 [&_svg:not([class*='size-'])]:size-3.5",default:"h-8 min-h-8 px-3 [&_svg:not([class*='size-'])]:size-4"}},defaultVariants:{size:"default"}}),b1=H.createContext(null),GR=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function xy({onValueChange:e,modal:t=!1,...n}){const[r,s]=H.useState(null),o=H.useMemo(()=>({portalContainer:r,setPortalContainer:s}),[r]),i=H.useCallback((a,l)=>{typeof a=="string"&&e?.(a,l)},[e]);return c.jsx(b1.Provider,{value:o,children:c.jsx(a8,{...n,modal:t,onValueChange:i})})}function ZR({...e}){return c.jsx(y8,{"data-slot":"select-group",...e})}function by({placeholder:e,children:t,...n}){return c.jsx(d8,{"data-slot":"select-value",...n,children:r=>{const s=typeof r=="string"||r===void 0?r:r===null?void 0:String(r);return typeof t=="function"?t(s):t??(s===void 0||s===""?e:s)}})}function wy({className:e,size:t="default",children:n,asChild:r,onPointerDownCapture:s,onFocusCapture:o,...i}){const a=H.useContext(b1),l=H.useCallback(f=>{if(!a)return;const u=f instanceof HTMLElement?f:null;a.setPortalContainer(GR(u))},[a]),d=r&&H.isValidElement(n)?{render:n}:null;return c.jsx(c8,{"data-slot":"select-trigger","data-size":t,className:R(KR({size:t==="settings"||t==="lg"?"default":"sm"}),"w-fit data-[placeholder]:text-muted-foreground aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2",e),onPointerDownCapture:f=>{l(f.currentTarget),s?.(f)},onFocusCapture:f=>{l(f.currentTarget),o?.(f)},...i,...d??{},children:d?void 0:c.jsxs(c.Fragment,{children:[n,c.jsx(l8,{children:c.jsx(V,{name:"arrow-down-s",className:"size-4 opacity-70"})})]})})}function Sy({className:e,children:t,position:n="popper",fitContent:r=!1,portalToBody:s=!1,sideOffset:o,side:i,align:a,...l}){const d=H.useContext(b1),f=n==="item-aligned",u=d?.portalContainer??null;return c.jsx(u8,{container:s?void 0:u||void 0,children:c.jsx(f8,{alignItemWithTrigger:f,sideOffset:o,side:i,align:a,className:"absolute z-[120] pointer-events-auto",children:c.jsx(h8,{"data-slot":"select-content",style:{color:"var(--surface-elevated-foreground)"},className:R("oc-glass-popover oc-glass-floating pointer-events-auto transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 relative z-[120] max-h-[var(--oc-select-max-height,var(--available-height))] min-w-[8rem] origin-[var(--transform-origin)] overflow-x-hidden rounded-xl","data-[side=top]:[--oc-select-max-height:calc(var(--available-height)_-_env(safe-area-inset-top,0px))] data-[side=bottom]:[--oc-select-max-height:calc(var(--available-height)_-_env(safe-area-inset-bottom,0px))]",!f&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r&&"w-max min-w-0",e),...l,children:c.jsx(Xn,{outerClassName:R("max-h-[var(--oc-select-max-height,var(--available-height))]",r?"w-max":"w-full"),className:R("p-1",!f&&(r?"w-max min-w-0 scroll-my-1":"w-full min-w-[var(--anchor-width)] scroll-my-1")),preventOverscroll:!0,children:t})})})})}function YR({className:e,...t}){return c.jsx(v8,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",e),...t})}function Cy({className:e,children:t,...n}){return c.jsxs(p8,{"data-slot":"select-item",className:R("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[selected]:bg-interactive-selection data-[selected]:text-interactive-selection-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-pointer items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...n,children:[c.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:c.jsx(m8,{children:c.jsx(V,{name:"check",className:"size-4"})})}),c.jsx(g8,{children:t})]})}const ky=e=>e.some(t=>t.source==="local"&&(t.uploadState?.status==="preparing"||t.uploadState?.status==="uploading")),XR=e=>e.some(t=>t.source==="local"&&t.uploadState?.status==="failed"),nh=(e,t=Date.now())=>e.every(n=>n.source==="server"||n.uploadState?.status==="ready"&&n.uploadState.expiresAt>t),Fl=200,My={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:600*1e3},N3=()=>Fl,JR=()=>Math.round(N3()*.6),QR={MAX_SESSIONS:My.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(Fl*.6),HISTORICAL_MESSAGES:Fl,FETCH_BUFFER:20,HISTORY_CHUNK:Fl,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:My.ZOMBIE_TIMEOUT},Iy=()=>{const e=N3(),t=JR();return{...QR,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},eP=5e3,_n=new Map,Ar=new Map,cr=new Map,fa=new Map,co=(e,t)=>`${e}
|
|
65
|
+
${t?.trim()??""}`,Lo=e=>{fa.set(e,(fa.get(e)??0)+1),Ar.delete(e)},tP=e=>{const t=Y();if(typeof e=="string"&&e.trim().length>0){const r=co(t,e);_n.delete(r),Lo(r);return}const n=new Set([..._n.keys(),...Ar.keys(),...cr.keys()]);for(const r of n)r.startsWith(`${t}
|
|
66
|
+
`)&&(_n.delete(r),Lo(r))},rh=e=>{const t=new Set([..._n.keys(),...Ar.keys(),...cr.keys()]);for(const n of t)n.startsWith(`${e}
|
|
67
|
+
`)&&(_n.delete(n),Lo(n))},Jc=e=>e.snippets.map(t=>({id:t.id,name:t.name,content:t.content,aliases:t.aliases??[],...t.description?{description:t.description}:{},source:t.scope==="project"?"project":"global",...typeof t.directory=="string"?{directory:t.directory}:{}})),Or=Et()(gr((e,t)=>({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null,setSelectedSnippet:n=>e({selectedSnippetId:n}),setSnippetDraft:n=>e({snippetDraft:n}),resetForRuntimeSwitch:()=>{_n.clear(),Ar.clear(),cr.clear(),fa.clear(),e({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null})},loadSnippets:async n=>{const r=Y(),s=co(r,n),o=Date.now(),i=cr.get(s);e({activeCacheKey:s,snippets:i??[],isLoading:!0});const a=_n.get(s)??0;if(a>0&&o-a<eP)return e({isLoading:!1}),!0;const l=Ar.get(s);if(l)return l;const d=fa.get(s)??0,f=(async()=>{try{const u=await Ie.listSnippets(n,{runtimeKey:r});if(Y()!==r)return!1;if((fa.get(s)??0)!==d)return e(m=>m.activeCacheKey===s?{isLoading:!1}:m),!0;const h=Jc(u);return cr.set(s,h),_n.set(s,Date.now()),e(m=>m.activeCacheKey===s?{snippets:h,isLoading:!1,...m.selectedSnippetId&&!h.some(g=>g.id===m.selectedSnippetId)?{selectedSnippetId:null}:{}}:m),!0}catch{return e(u=>u.activeCacheKey===s?{isLoading:!1}:u),!1}})();Ar.set(s,f);try{return await f}finally{Ar.get(s)===f&&Ar.delete(s)}},createSnippet:async(n,r,s={})=>{const o=Y(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await Ie.createSnippet({name:n,content:r,...s.description!==void 0?{description:s.description}:{},...s.aliases!==void 0?{aliases:s.aliases}:{},scope:s.scope??"global",...i?{directory:i}:{}},{runtimeKey:o});if(Y()!==o)return!1;const l=co(o,i),d=Jc(a);Lo(l),cr.set(l,d),rh(o),_n.set(l,Date.now());const f=d.find(u=>u.name===n&&u.source===(s.scope??"global"));return e(u=>u.activeCacheKey===l?{snippets:d,snippetDraft:null,selectedSnippetId:f?.id??null,isLoading:!1}:u),!0}catch{return!1}},updateSnippet:async(n,r,s)=>{const o=Y(),i=t().snippets.find(l=>l.id===n);if(!i)return!1;const a=s?.trim()?s.trim():i.source==="project"&&i.directory?i.directory:void 0;try{const l=await Ie.updateSnippet(i.id,{...r.name!==void 0?{name:r.name}:{},...r.content!==void 0?{content:r.content}:{},...r.description!==void 0?{description:r.description}:{},...r.aliases!==void 0?{aliases:r.aliases}:{},...r.scope!==void 0?{scope:r.scope}:{},...r.directory!==void 0?{directory:r.directory}:{}},a,{runtimeKey:o});if(Y()!==o)return!1;const d=co(o,a),f=Jc(l);return Lo(d),cr.set(d,f),rh(o),_n.set(d,Date.now()),e(u=>u.activeCacheKey===d?{snippets:f,isLoading:!1}:u),!0}catch{return!1}},deleteSnippet:async(n,r)=>{const s=Y(),o=t().snippets.find(a=>a.id===n);if(!o)return!1;const i=r?.trim()?r.trim():o.source==="project"&&o.directory?o.directory:void 0;try{const a=await Ie.deleteSnippet(o.id,i,{runtimeKey:s});if(Y()!==s)return!1;const l=co(s,i),d=Jc(a);return Lo(l),cr.set(l,d),rh(s),_n.set(l,Date.now()),e(f=>f.activeCacheKey===l?{snippets:d,isLoading:!1,...f.selectedSnippetId===n?{selectedSnippetId:null}:{}}:f),!0}catch{return!1}},expandText:(n,r)=>{if(!n||!n.includes("#"))return n;const s=co(Y(),r),o=cr.get(s)??(t().activeCacheKey===s?t().snippets:[]),i=new Map,a=[...o].sort((l,d)=>+(d.source==="project")-+(l.source==="project"));for(const l of a){const d=l.name.toLowerCase();i.has(d)||i.set(d,l.content);for(const f of l.aliases??[]){const u=f.toLowerCase();i.has(u)||i.set(u,l.content)}}return i.size===0?n:n.replace(/(^|\s)#([A-Za-z0-9][A-Za-z0-9_-]*)/g,(l,d,f)=>{const u=i.get(f.toLowerCase());return u!==void 0?`${d}${u}`:l})},getSnippetByName:n=>t().snippets.find(r=>r.name===n)}),{name:"snippets-store"})),qJ=Object.freeze(Object.defineProperty({__proto__:null,invalidateSnippetsLoadCache:tP,useSnippetsStore:Or},Symbol.toStringTag,{value:"Module"}));function L3(e){const t=e.split(".").pop()?.toLowerCase(),n=e.split("/").pop()?.toLowerCase()||"",r={dockerfile:"dockerfile",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake",gemfile:"ruby",rakefile:"ruby",podfile:"ruby",vagrantfile:"ruby",guardfile:"ruby",brewfile:"ruby",fastfile:"ruby",appfile:"ruby",matchfile:"ruby",pluginfile:"ruby",scanfile:"ruby",snapfile:"ruby",".gitignore":"text",".gitattributes":"text",".gitmodules":"ini",".editorconfig":"ini",".npmrc":"ini",".yarnrc":"yaml",".prettierrc":"json",".eslintrc":"json",".babelrc":"json",".browserslistrc":"text","tsconfig.json":"jsonc","jsconfig.json":"jsonc",".env":"bash",".env.local":"bash",".env.development":"bash",".env.production":"bash",".env.test":"bash",procfile:"yaml",codeowners:"text","package-lock.json":"json","composer.lock":"json","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","cargo.lock":"toml","poetry.lock":"toml","gemfile.lock":"ruby","pubspec.lock":"yaml","packages.lock.json":"json","bun.lockb":"text","bun.lock":"json"};return r[n]?r[n]:{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",html:"html",htm:"html",xhtml:"html",vue:"html",svelte:"html",astro:"html",ejs:"html",hbs:"handlebars",handlebars:"handlebars",mustache:"handlebars",njk:"twig",nunjucks:"twig",twig:"twig",liquid:"liquid",css:"css",scss:"scss",sass:"sass",less:"less",styl:"stylus",stylus:"stylus",pcss:"css",postcss:"css",json:"json",jsonc:"json",json5:"json",jsonl:"json",ndjson:"json",geojson:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",xsl:"xml",xslt:"xml",xsd:"xml",dtd:"xml",plist:"xml",svg:"xml",rss:"xml",atom:"xml",xaml:"xml",csproj:"xml",vbproj:"xml",fsproj:"xml",props:"xml",targets:"xml",nuspec:"xml",resx:"xml",ini:"ini",cfg:"ini",conf:"ini",config:"ini",properties:"properties",env:"bash",csv:"text",tsv:"text",py:"python",pyw:"python",pyx:"python",pxd:"python",pxi:"python",pyi:"python",gyp:"python",gypi:"python",bzl:"python",rb:"ruby",erb:"erb",rake:"ruby",gemspec:"ruby",ru:"ruby",podspec:"ruby",thor:"ruby",jbuilder:"ruby",rabl:"ruby",builder:"ruby",php:"php",phtml:"php",php3:"php",php4:"php",php5:"php",php7:"php",phps:"php",inc:"php","blade.php":"php",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",sc:"scala",groovy:"groovy",gradle:"groovy",gvy:"groovy",gy:"groovy",gsh:"groovy",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp","h++":"cpp",ino:"cpp",m:"objectivec",mm:"objectivec",cs:"csharp",csx:"csharp",cake:"csharp",fs:"fsharp",fsx:"fsharp",fsi:"fsharp",vb:"vbnet",go:"go",mod:"go",sum:"text",rs:"rust",swift:"swift",dart:"dart",lua:"lua",pl:"perl",pm:"perl",pod:"perl",t:"perl",r:"r",R:"r",rmd:"markdown",rnw:"r",jl:"julia",hs:"haskell",lhs:"haskell",ex:"elixir",exs:"elixir",eex:"html",heex:"html",leex:"html",erl:"erlang",hrl:"erlang",clj:"clojure",cljs:"clojure",cljc:"clojure",edn:"clojure",lisp:"lisp",cl:"lisp",el:"lisp",scm:"scheme",ss:"scheme",rkt:"scheme",ml:"ocaml",mli:"ocaml",re:"reason",rei:"reason",nim:"nim",nims:"nim",nimble:"nim",zig:"zig",v:"v",vsh:"v",cr:"crystal",d:"d",di:"d",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ksh:"bash",csh:"bash",tcsh:"bash",ps1:"powershell",psm1:"powershell",psd1:"powershell",bat:"batch",cmd:"batch",sql:"sql",psql:"sql",plsql:"sql",mysql:"sql",pgsql:"sql",sqlite:"sql",graphql:"graphql",gql:"graphql",sol:"solidity",asm:"nasm",s:"nasm",S:"nasm",nix:"nix",tf:"hcl",tfvars:"hcl",hcl:"hcl",dockerignore:"text",pp:"puppet",tex:"latex",latex:"latex",sty:"latex",cls:"latex",bib:"bibtex",bst:"bibtex",md:"markdown",mdx:"markdown",markdown:"markdown",mdown:"markdown",mkd:"markdown",rst:"text",adoc:"asciidoc",asciidoc:"asciidoc",org:"text",txt:"text",text:"text",rtf:"text",vim:"vim",vimrc:"vim",mk:"makefile",cmake:"cmake",diff:"diff",patch:"diff",prisma:"prisma",proto:"protobuf",thrift:"thrift",wat:"wasm",wast:"wasm",glsl:"glsl",vert:"glsl",frag:"glsl",geom:"glsl",comp:"glsl",hlsl:"hlsl",fx:"hlsl",cg:"cg",shader:"glsl",htaccess:"apacheconf",nginx:"nginx",kubeconfig:"yaml",ansible:"yaml"}[t||""]||null}const nP=["drawio","dio"];function R3(e){const t=e.split(".").pop()?.toLowerCase();return nP.includes(t||"")}const P3=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function WJ(e){const t=e.split(".").pop()?.toLowerCase();return P3.includes(t||"")}function KJ(e){return e.split(".").pop()?.toLowerCase()==="pdf"}function rP(e){return e.toLowerCase().endsWith(".svg")}const sP=new Set(["pdf","doc","docx","xls","xlsx","ppt","pptx","odt","ods","odp","zip","rar","7z","gz","tgz","tar","bz2","xz","jar","war","apk","dmg","iso","deb","rpm","msi",...P3.filter(e=>e!=="svg"),"mp3","mp4","m4a","aac","flac","ogg","wav","wma","avi","mov","mkv","webm","wmv","ttf","otf","woff","woff2","eot","exe","dll","so","dylib","bin","class","o","a","lib","wasm","node","sqlite","sqlite3","db","dat","parquet","feather","pickle","pyc","pyo","lockb"]);function oP(e){const t=e.split(/[/\\]/).pop()??e,n=t.lastIndexOf(".");return n<=0||n===t.length-1?"":t.slice(n+1).toLowerCase()}function GJ(e){if(rP(e))return!1;const t=oP(e);return sP.has(t)}function ZJ(e){if(!e)return!1;const t=e.length>8192?e.slice(0,8192):e;if(t.includes("\0")||t.startsWith("%PDF")||t.startsWith("PK")||t.startsWith("PK")||t.startsWith("PK\x07\b"))return!0;let n=0;for(let r=0;r<t.length;r+=1){const s=t.charCodeAt(r);if(s===65533){n+=1;continue}(s<9||s>13&&s<32||s===127)&&(n+=1)}return t.length>0&&n/t.length>.1}function YJ(e){const t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[t||""]||"image/png"}const iP={read:{displayName:"Read file",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File path",type:"file"},{key:"offset",label:"Start line",type:"text"},{key:"limit",label:"Lines to read",type:"text"}]},write:{displayName:"Write file",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit file",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace all",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},apply_patch:{displayName:"Apply patch",category:"file",outputLanguage:"diff",inputFields:[{key:"patchText",label:"Patch",type:"code",language:"diff"}]},bash:{displayName:"Shell command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include pattern",type:"pattern"}]},glob:{displayName:"Find files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore patterns",type:"pattern"}]},task:{displayName:"Agent task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search query",type:"text"},{key:"numResults",label:"Results count",type:"text"},{key:"type",label:"Search type",type:"text"}]},codesearch:{displayName:"Code search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update todo list",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo items",type:"code",language:"json"}]},todoread:{displayName:"Read todo list",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill name",type:"text"}]},question:{displayName:"Question",category:"ai",outputLanguage:"text",inputFields:[{key:"questions",label:"Questions",type:"code",language:"json"}]},lsp:{displayName:"LSP",category:"code",outputLanguage:"json",inputFields:[{key:"operation",label:"Operation",type:"text"},{key:"filePath",label:"File path",type:"file"},{key:"line",label:"Line",type:"text"},{key:"character",label:"Character",type:"text"},{key:"query",label:"Query",type:"text"}]},pichamber:{displayName:"PiChamber",category:"system",outputLanguage:"json",inputFields:[]},plan_enter:{displayName:"Plan mode",category:"ai",outputLanguage:"text",inputFields:[]},plan_exit:{displayName:"Build mode",category:"ai",outputLanguage:"text",inputFields:[]},StructuredOutput:{displayName:"Structured output",category:"ai",outputLanguage:"json",inputFields:[]},structuredoutput:{displayName:"Structured output",category:"ai",outputLanguage:"json",inputFields:[]}};function aP(e){return e.trim().replace(/[_-]+/g," ").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase())}function Ka(e){return iP[e]||{displayName:aP(e),category:"system",outputLanguage:"text",inputFields:[]}}function cP(e,t,n){const r=Ka(e);if(r.outputLanguage==="auto"){if(n?.filePath||n?.file_path||n?.sourcePath){const s=n.filePath||n.file_path||n.sourcePath,o=L3(s);if(o)return o}if(e==="webfetch"){if(t.trim().startsWith("{")||t.trim().startsWith("["))try{return JSON.parse(t),"json"}catch{}if(t.trim().startsWith("<"))return"html";if(t.includes("```"))return"markdown"}return"text"}return r.outputLanguage||"text"}function lP(e,t){if(!e)return"";const n=r=>{const s=e[r];return typeof s=="string"?s:typeof s=="number"?String(s):null};if(t==="bash"){const r=n("command");if(r)return r}if(t==="lsp"){const r=n("operation")||"lsp",s=n("filePath")||n("file_path")||n("path"),o=n("line"),i=n("character"),a=n("query"),l=o&&i?` (Line: ${o}; Character: ${i})`:"";if(r==="workspaceSymbol")return a?`Operation: ${r} (Query: "${a}")`:`Operation: ${r}`;const d=`Operation: ${r}${l}`;return s?`${d}
|
|
68
|
+
${s}`:d}if(t==="task"){const r=n("prompt");if(r)return r;const s=n("description");if(s)return s}if(t==="apply_patch"&&typeof e=="object"){const r=n("patchText")||n("patch_text")||n("patch");if(r)return r}if((t==="edit"||t==="multiedit")&&typeof e=="object"){const r=n("filePath")||n("file_path")||n("path");if(r)return`File path: ${r}`}if(t==="write"&&typeof e=="object"){const r=n("content");if(r)return r}return typeof e=="object"?Object.entries(e).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>{const i=s.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,l=>l.toUpperCase());let a=o;return typeof o=="object"?a=JSON.stringify(o,null,2):typeof o=="boolean"&&(a=o?"Yes":"No"),`${i}: ${a}`}).join(`
|
|
69
|
+
`):String(e)}const D3="p-1.5 max-w-[260px] overflow-hidden rounded-xl bg-popover/95 border border-border shadow-lg";function O3({imageUrl:e,filename:t,metaLine:n}){return e?c.jsxs("div",{children:[c.jsx("img",{src:e,alt:t,loading:"lazy",decoding:"async",className:"max-h-48 w-auto rounded-lg object-contain mx-auto"}),c.jsxs("div",{className:"mt-1 px-1 py-0.5",children:[c.jsx("p",{className:"truncate text-xs font-medium text-foreground",children:t}),n?c.jsx("p",{className:"typography-micro text-muted-foreground",children:n}):null]})]}):c.jsxs("p",{children:[t,n?` (${n})`:""]})}const w1=new Set(["3d","3d_light","abap","abap_light","abc","abc_light","actionscript","actionscript_light","ada","ada_light","adobe-illustrator","adobe-illustrator_light","adobe-photoshop","adobe-photoshop_light","adobe-swc","adobe-swc_light","adonis","adonis_light","advpl","advpl_light","amplify","amplify_light","android","android_light","angular","angular_light","antlr","antlr_light","apiblueprint","apiblueprint_light","apollo","apollo_light","applescript","applescript_light","apps-script","apps-script_light","appveyor","appveyor_light","architecture","architecture_light","arduino","arduino_light","asciidoc","asciidoc_light","assembly","assembly_light","astro","astro_light","astro-config","astro-config_light","astyle","astyle_light","audio","audio_light","aurelia","aurelia_light","authors","authors_light","auto","auto_light","autohotkey","autohotkey_light","autoit","autoit_light","azure","azure_light","azure-pipelines","azure-pipelines_light","babel","babel_light","ballerina","ballerina_light","bazel","bazel_light","bbx","bbx_light","beancount","beancount_light","bench-js","bench-js_light","bench-jsx","bench-jsx_light","bench-ts","bench-ts_light","bibliography","bibliography_light","bibtex-style","bibtex-style_light","bicep","bicep_light","biome","biome_light","bitbucket","bitbucket_light","bithound","bithound_light","blender","blender_light","blink","blink_light","blitz","blitz_light","bower","bower_light","brainfuck","brainfuck_light","browserlist","browserlist_light","bruno","bruno_light","buck","buck_light","bucklescript","bucklescript_light","buildkite","buildkite_light","bun","bun_light","c","c_light","c3","c3_light","cabal","cabal_light","caddy","caddy_light","cadence","cadence_light","cairo","cairo_light","cake","cake_light","capacitor","capacitor_light","capnp","capnp_light","cbx","cbx_light","cds","cds_light","certificate","certificate_light","changelog","changelog_light","chess","chess_light","chrome","chrome_light","circleci","circleci_light","citation","citation_light","clangd","clangd_light","claude","claude_light","cline","cline_light","clojure","clojure_light","cloudfoundry","cloudfoundry_light","cmake","cmake_light","coala","coala_light","cobol","cobol_light","coconut","coconut_light","code-climate","code-climate_light","codecov","codecov_light","codeowners","codeowners_light","coderabbit-ai","coderabbit-ai_light","coffee","coffee_light","coldfusion","coldfusion_light","coloredpetrinets","coloredpetrinets_light","command","command_light","commitizen","commitizen_light","commitlint","commitlint_light","concourse","concourse_light","conduct","conduct_light","console","console_light","contentlayer","contentlayer_light","context","context_light","contributing","contributing_light","controller","controller_light","copilot","copilot_light","cpp","cpp_light","craco","craco_light","credits","credits_light","crystal","crystal_light","csharp","csharp_light","css","css_light","css-map","css-map_light","cucumber","cucumber_light","cuda","cuda_light","cursor","cursor_light","cypress","cypress_light","d","d_light","dart","dart_generated","dart_generated_light","dart_light","database","database_light","deepsource","deepsource_light","denizenscript","denizenscript_light","deno","deno_light","dependabot","dependabot_light","dependencies-update","dependencies-update_light","dhall","dhall_light","diff","diff_light","dinophp","dinophp_light","disc","disc_light","django","django_light","dll","dll_light","docker","docker_light","doctex-installer","doctex-installer_light","document","document_light","dotjs","dotjs_light","drawio","drawio_light","drizzle","drizzle_light","drone","drone_light","duc","duc_light","dune","dune_light","edge","edge_light","editorconfig","editorconfig_light","ejs","ejs_light","elixir","elixir_light","elm","elm_light","email","email_light","ember","ember_light","epub","epub_light","erlang","erlang_light","esbuild","esbuild_light","eslint","eslint_light","excalidraw","excalidraw_light","exe","exe_light","fastlane","fastlane_light","favicon","favicon_light","figma","figma_light","firebase","firebase_light","flash","flash_light","flow","flow_light","folder","folder_light","folder-admin","folder-admin_light","folder-admin-open","folder-admin-open_light","folder-android","folder-android_light","folder-android-open","folder-android-open_light","folder-angular","folder-angular_light","folder-angular-open","folder-angular-open_light","folder-animation","folder-animation_light","folder-animation-open","folder-animation-open_light","folder-ansible","folder-ansible_light","folder-ansible-open","folder-ansible-open_light","folder-api","folder-api_light","folder-api-open","folder-api-open_light","folder-apollo","folder-apollo_light","folder-apollo-open","folder-apollo-open_light","folder-app","folder-app_light","folder-app-open","folder-app-open_light","folder-archive","folder-archive_light","folder-archive-open","folder-archive-open_light","folder-astro","folder-astro_light","folder-astro-open","folder-astro-open_light","folder-atom","folder-atom_light","folder-atom-open","folder-atom-open_light","folder-attachment","folder-attachment_light","folder-attachment-open","folder-attachment-open_light","folder-audio","folder-audio_light","folder-audio-open","folder-audio-open_light","folder-aurelia","folder-aurelia_light","folder-aurelia-open","folder-aurelia-open_light","folder-aws","folder-aws_light","folder-aws-open","folder-aws-open_light","folder-azure-pipelines","folder-azure-pipelines_light","folder-azure-pipelines-open","folder-azure-pipelines-open_light","folder-backup","folder-backup_light","folder-backup-open","folder-backup-open_light","folder-base","folder-base_light","folder-base-open","folder-base-open_light","folder-batch","folder-batch_light","folder-batch-open","folder-batch-open_light","folder-benchmark","folder-benchmark_light","folder-benchmark-open","folder-benchmark-open_light","folder-bibliography","folder-bibliography_light","folder-bibliography-open","folder-bibliography-open_light","folder-bicep","folder-bicep_light","folder-bicep-open","folder-bicep-open_light","folder-blender","folder-blender_light","folder-blender-open","folder-blender-open_light","folder-bloc","folder-bloc_light","folder-bloc-open","folder-bloc-open_light","folder-bower","folder-bower_light","folder-bower-open","folder-bower-open_light","folder-buildkite","folder-buildkite_light","folder-buildkite-open","folder-buildkite-open_light","folder-cart","folder-cart_light","folder-cart-open","folder-cart-open_light","folder-changesets","folder-changesets_light","folder-changesets-open","folder-changesets-open_light","folder-ci","folder-ci_light","folder-ci-open","folder-ci-open_light","folder-circleci","folder-circleci_light","folder-circleci-open","folder-circleci-open_light","folder-class","folder-class_light","folder-class-open","folder-class-open_light","folder-claude","folder-claude_light","folder-claude-open","folder-claude-open_light","folder-client","folder-client_light","folder-client-open","folder-client-open_light","folder-cline","folder-cline_light","folder-cline-open","folder-cline-open_light","folder-cloud-functions","folder-cloud-functions_light","folder-cloud-functions-open","folder-cloud-functions-open_light","folder-cloudflare","folder-cloudflare_light","folder-cloudflare-open","folder-cloudflare-open_light","folder-cluster","folder-cluster_light","folder-cluster-open","folder-cluster-open_light","folder-cobol","folder-cobol_light","folder-cobol-open","folder-cobol-open_light","folder-command","folder-command_light","folder-command-open","folder-command-open_light","folder-components","folder-components_light","folder-components-open","folder-components-open_light","folder-config","folder-config_light","folder-config-open","folder-config-open_light","folder-connection","folder-connection_light","folder-connection-open","folder-connection-open_light","folder-console","folder-console_light","folder-console-open","folder-console-open_light","folder-constant","folder-constant_light","folder-constant-open","folder-constant-open_light","folder-container","folder-container_light","folder-container-open","folder-container-open_light","folder-content","folder-content_light","folder-content-open","folder-content-open_light","folder-context","folder-context_light","folder-context-open","folder-context-open_light","folder-contract","folder-contract_light","folder-contract-open","folder-contract-open_light","folder-controller","folder-controller_light","folder-controller-open","folder-controller-open_light","folder-core","folder-core_light","folder-core-open","folder-core-open_light","folder-coverage","folder-coverage_light","folder-coverage-open","folder-coverage-open_light","folder-css","folder-css_light","folder-css-open","folder-css-open_light","folder-cursor","folder-cursor_light","folder-cursor-open","folder-cursor-open_light","folder-custom","folder-custom_light","folder-custom-open","folder-custom-open_light","folder-cypress","folder-cypress_light","folder-cypress-open","folder-cypress-open_light","folder-dart","folder-dart_light","folder-dart-open","folder-dart-open_light","folder-database","folder-database_light","folder-database-open","folder-database-open_light","folder-debug","folder-debug_light","folder-debug-open","folder-debug-open_light","folder-decorators","folder-decorators_light","folder-decorators-open","folder-decorators-open_light","folder-delta","folder-delta_light","folder-delta-open","folder-delta-open_light","folder-desktop","folder-desktop_light","folder-desktop-open","folder-desktop-open_light","folder-directive","folder-directive_light","folder-directive-open","folder-directive-open_light","folder-dist","folder-dist_light","folder-dist-open","folder-dist-open_light","folder-docker","folder-docker_light","folder-docker-open","folder-docker-open_light","folder-docs","folder-docs_light","folder-docs-open","folder-docs-open_light","folder-download","folder-download_light","folder-download-open","folder-download-open_light","folder-drizzle","folder-drizzle_light","folder-drizzle-open","folder-drizzle-open_light","folder-dump","folder-dump_light","folder-dump-open","folder-dump-open_light","folder-element","folder-element_light","folder-element-open","folder-element-open_light","folder-enum","folder-enum_light","folder-enum-open","folder-enum-open_light","folder-environment","folder-environment_light","folder-environment-open","folder-environment-open_light","folder-error","folder-error_light","folder-error-open","folder-error-open_light","folder-event","folder-event_light","folder-event-open","folder-event-open_light","folder-examples","folder-examples_light","folder-examples-open","folder-examples-open_light","folder-expo","folder-expo_light","folder-expo-open","folder-expo-open_light","folder-export","folder-export_light","folder-export-open","folder-export-open_light","folder-fastlane","folder-fastlane_light","folder-fastlane-open","folder-fastlane-open_light","folder-favicon","folder-favicon_light","folder-favicon-open","folder-favicon-open_light","folder-firebase","folder-firebase_light","folder-firebase-open","folder-firebase-open_light","folder-firestore","folder-firestore_light","folder-firestore-open","folder-firestore-open_light","folder-flow","folder-flow_light","folder-flow-open","folder-flow-open_light","folder-flutter","folder-flutter_light","folder-flutter-open","folder-flutter-open_light","folder-font","folder-font_light","folder-font-open","folder-font-open_light","folder-forgejo","folder-forgejo_light","folder-forgejo-open","folder-forgejo-open_light","folder-functions","folder-functions_light","folder-functions-open","folder-functions-open_light","folder-gamemaker","folder-gamemaker_light","folder-gamemaker-open","folder-gamemaker-open_light","folder-generator","folder-generator_light","folder-generator-open","folder-generator-open_light","folder-gh-workflows","folder-gh-workflows_light","folder-gh-workflows-open","folder-gh-workflows-open_light","folder-git","folder-git_light","folder-git-open","folder-git-open_light","folder-gitea","folder-gitea_light","folder-gitea-open","folder-gitea-open_light","folder-github","folder-github_light","folder-github-open","folder-github-open_light","folder-gitlab","folder-gitlab_light","folder-gitlab-open","folder-gitlab-open_light","folder-global","folder-global_light","folder-global-open","folder-global-open_light","folder-godot","folder-godot_light","folder-godot-open","folder-godot-open_light","folder-gradle","folder-gradle_light","folder-gradle-open","folder-gradle-open_light","folder-graphql","folder-graphql_light","folder-graphql-open","folder-graphql-open_light","folder-guard","folder-guard_light","folder-guard-open","folder-guard-open_light","folder-gulp","folder-gulp_light","folder-gulp-open","folder-gulp-open_light","folder-helm","folder-helm_light","folder-helm-open","folder-helm-open_light","folder-helper","folder-helper_light","folder-helper-open","folder-helper-open_light","folder-home","folder-home_light","folder-home-open","folder-home-open_light","folder-hook","folder-hook_light","folder-hook-open","folder-hook-open_light","folder-husky","folder-husky_light","folder-husky-open","folder-husky-open_light","folder-i18n","folder-i18n_light","folder-i18n-open","folder-i18n-open_light","folder-images","folder-images_light","folder-images-open","folder-images-open_light","folder-import","folder-import_light","folder-import-open","folder-import-open_light","folder-include","folder-include_light","folder-include-open","folder-include-open_light","folder-intellij","folder-intellij_light","folder-intellij-open","folder-intellij-open_light","folder-interceptor","folder-interceptor_light","folder-interceptor-open","folder-interceptor-open_light","folder-interface","folder-interface_light","folder-interface-open","folder-interface-open_light","folder-ios","folder-ios_light","folder-ios-open","folder-ios-open_light","folder-java","folder-java_light","folder-java-open","folder-java-open_light","folder-javascript","folder-javascript_light","folder-javascript-open","folder-javascript-open_light","folder-jinja","folder-jinja_light","folder-jinja-open","folder-jinja-open_light","folder-job","folder-job_light","folder-job-open","folder-job-open_light","folder-json","folder-json_light","folder-json-open","folder-json-open_light","folder-jupyter","folder-jupyter_light","folder-jupyter-open","folder-jupyter-open_light","folder-keys","folder-keys_light","folder-keys-open","folder-keys-open_light","folder-kubernetes","folder-kubernetes_light","folder-kubernetes-open","folder-kubernetes-open_light","folder-kusto","folder-kusto_light","folder-kusto-open","folder-kusto-open_light","folder-layout","folder-layout_light","folder-layout-open","folder-layout-open_light","folder-lefthook","folder-lefthook_light","folder-lefthook-open","folder-lefthook-open_light","folder-less","folder-less_light","folder-less-open","folder-less-open_light","folder-lib","folder-lib_light","folder-lib-open","folder-lib-open_light","folder-link","folder-link_light","folder-link-open","folder-link-open_light","folder-linux","folder-linux_light","folder-linux-open","folder-linux-open_light","folder-liquibase","folder-liquibase_light","folder-liquibase-open","folder-liquibase-open_light","folder-log","folder-log_light","folder-log-open","folder-log-open_light","folder-lottie","folder-lottie_light","folder-lottie-open","folder-lottie-open_light","folder-lua","folder-lua_light","folder-lua-open","folder-lua-open_light","folder-luau","folder-luau_light","folder-luau-open","folder-luau-open_light","folder-macos","folder-macos_light","folder-macos-open","folder-macos-open_light","folder-mail","folder-mail_light","folder-mail-open","folder-mail-open_light","folder-mappings","folder-mappings_light","folder-mappings-open","folder-mappings-open_light","folder-markdown","folder-markdown_light","folder-markdown-open","folder-markdown-open_light","folder-mercurial","folder-mercurial_light","folder-mercurial-open","folder-mercurial-open_light","folder-messages","folder-messages_light","folder-messages-open","folder-messages-open_light","folder-meta","folder-meta_light","folder-meta-open","folder-meta-open_light","folder-middleware","folder-middleware_light","folder-middleware-open","folder-middleware-open_light","folder-mjml","folder-mjml_light","folder-mjml-open","folder-mjml-open_light","folder-mobile","folder-mobile_light","folder-mobile-open","folder-mobile-open_light","folder-mock","folder-mock_light","folder-mock-open","folder-mock-open_light","folder-mojo","folder-mojo_light","folder-mojo-open","folder-mojo-open_light","folder-molecule","folder-molecule_light","folder-molecule-open","folder-molecule-open_light","folder-moon","folder-moon_light","folder-moon-open","folder-moon-open_light","folder-netlify","folder-netlify_light","folder-netlify-open","folder-netlify-open_light","folder-next","folder-next_light","folder-next-open","folder-next-open_light","folder-ngrx-store","folder-ngrx-store_light","folder-ngrx-store-open","folder-ngrx-store-open_light","folder-node","folder-node_light","folder-node-open","folder-node-open_light","folder-nuxt","folder-nuxt_light","folder-nuxt-open","folder-nuxt-open_light","folder-obsidian","folder-obsidian_light","folder-obsidian-open","folder-obsidian-open_light","folder-open","folder-open_light","folder-organism","folder-organism_light","folder-organism-open","folder-organism-open_light","folder-other","folder-other_light","folder-other-open","folder-other-open_light","folder-packages","folder-packages_light","folder-packages-open","folder-packages-open_light","folder-pdf","folder-pdf_light","folder-pdf-open","folder-pdf-open_light","folder-pdm","folder-pdm_light","folder-pdm-open","folder-pdm-open_light","folder-php","folder-php_light","folder-php-open","folder-php-open_light","folder-phpmailer","folder-phpmailer_light","folder-phpmailer-open","folder-phpmailer-open_light","folder-pipe","folder-pipe_light","folder-pipe-open","folder-pipe-open_light","folder-plastic","folder-plastic_light","folder-plastic-open","folder-plastic-open_light","folder-plugin","folder-plugin_light","folder-plugin-open","folder-plugin-open_light","folder-policy","folder-policy_light","folder-policy-open","folder-policy-open_light","folder-powershell","folder-powershell_light","folder-powershell-open","folder-powershell-open_light","folder-prisma","folder-prisma_light","folder-prisma-open","folder-prisma-open_light","folder-private","folder-private_light","folder-private-open","folder-private-open_light","folder-project","folder-project_light","folder-project-open","folder-project-open_light","folder-prompts","folder-prompts_light","folder-prompts-open","folder-prompts-open_light","folder-proto","folder-proto_light","folder-proto-open","folder-proto-open_light","folder-public","folder-public_light","folder-public-open","folder-public-open_light","folder-python","folder-python_light","folder-python-open","folder-python-open_light","folder-pytorch","folder-pytorch_light","folder-pytorch-open","folder-pytorch-open_light","folder-quasar","folder-quasar_light","folder-quasar-open","folder-quasar-open_light","folder-queue","folder-queue_light","folder-queue-open","folder-queue-open_light","folder-react-components","folder-react-components_light","folder-react-components-open","folder-react-components-open_light","folder-redux-reducer","folder-redux-reducer_light","folder-redux-reducer-open","folder-redux-reducer-open_light","folder-repository","folder-repository_light","folder-repository-open","folder-repository-open_light","folder-resolver","folder-resolver_light","folder-resolver-open","folder-resolver-open_light","folder-resource","folder-resource_light","folder-resource-open","folder-resource-open_light","folder-review","folder-review_light","folder-review-open","folder-review-open_light","folder-robot","folder-robot_light","folder-robot-open","folder-robot-open_light","folder-routes","folder-routes_light","folder-routes-open","folder-routes-open_light","folder-rules","folder-rules_light","folder-rules-open","folder-rules-open_light","folder-rust","folder-rust_light","folder-rust-open","folder-rust-open_light","folder-sandbox","folder-sandbox_light","folder-sandbox-open","folder-sandbox-open_light","folder-sass","folder-sass_light","folder-sass-open","folder-sass-open_light","folder-scala","folder-scala_light","folder-scala-open","folder-scala-open_light","folder-scons","folder-scons_light","folder-scons-open","folder-scons-open_light","folder-scripts","folder-scripts_light","folder-scripts-open","folder-scripts-open_light","folder-secure","folder-secure_light","folder-secure-open","folder-secure-open_light","folder-seeders","folder-seeders_light","folder-seeders-open","folder-seeders-open_light","folder-server","folder-server_light","folder-server-open","folder-server-open_light","folder-serverless","folder-serverless_light","folder-serverless-open","folder-serverless-open_light","folder-shader","folder-shader_light","folder-shader-open","folder-shader-open_light","folder-shared","folder-shared_light","folder-shared-open","folder-shared-open_light","folder-snapcraft","folder-snapcraft_light","folder-snapcraft-open","folder-snapcraft-open_light","folder-snippet","folder-snippet_light","folder-snippet-open","folder-snippet-open_light","folder-src","folder-src_light","folder-src-open","folder-src-open_light","folder-src-tauri","folder-src-tauri_light","folder-src-tauri-open","folder-src-tauri-open_light","folder-stack","folder-stack_light","folder-stack-open","folder-stack-open_light","folder-stencil","folder-stencil_light","folder-stencil-open","folder-stencil-open_light","folder-store","folder-store_light","folder-store-open","folder-store-open_light","folder-storybook","folder-storybook_light","folder-storybook-open","folder-storybook-open_light","folder-stylus","folder-stylus_light","folder-stylus-open","folder-stylus-open_light","folder-sublime","folder-sublime_light","folder-sublime-open","folder-sublime-open_light","folder-supabase","folder-supabase_light","folder-supabase-open","folder-supabase-open_light","folder-svelte","folder-svelte_light","folder-svelte-open","folder-svelte-open_light","folder-svg","folder-svg_light","folder-svg-open","folder-svg-open_light","folder-syntax","folder-syntax_light","folder-syntax-open","folder-syntax-open_light","folder-target","folder-target_light","folder-target-open","folder-target-open_light","folder-taskfile","folder-taskfile_light","folder-taskfile-open","folder-taskfile-open_light","folder-tasks","folder-tasks_light","folder-tasks-open","folder-tasks-open_light","folder-television","folder-television_light","folder-television-open","folder-television-open_light","folder-temp","folder-temp_light","folder-temp-open","folder-temp-open_light","folder-template","folder-template_light","folder-template-open","folder-template-open_light","folder-terraform","folder-terraform_light","folder-terraform-open","folder-terraform-open_light","folder-test","folder-test_light","folder-test-open","folder-test-open_light","folder-theme","folder-theme_light","folder-theme-open","folder-theme-open_light","folder-tools","folder-tools_light","folder-tools-open","folder-tools-open_light","folder-trash","folder-trash_light","folder-trash-open","folder-trash-open_light","folder-trigger","folder-trigger_light","folder-trigger-open","folder-trigger-open_light","folder-turborepo","folder-turborepo_light","folder-turborepo-open","folder-turborepo-open_light","folder-typescript","folder-typescript_light","folder-typescript-open","folder-typescript-open_light","folder-ui","folder-ui_light","folder-ui-open","folder-ui-open_light","folder-unity","folder-unity_light","folder-unity-open","folder-unity-open_light","folder-update","folder-update_light","folder-update-open","folder-update-open_light","folder-upload","folder-upload_light","folder-upload-open","folder-upload-open_light","folder-utils","folder-utils_light","folder-utils-open","folder-utils-open_light","folder-vercel","folder-vercel_light","folder-vercel-open","folder-vercel-open_light","folder-verdaccio","folder-verdaccio_light","folder-verdaccio-open","folder-verdaccio-open_light","folder-video","folder-video_light","folder-video-open","folder-video-open_light","folder-views","folder-views_light","folder-views-open","folder-views-open_light","folder-vm","folder-vm_light","folder-vm-open","folder-vm-open_light","folder-vscode","folder-vscode_light","folder-vscode-open","folder-vscode-open_light","folder-vue","folder-vue_light","folder-vue-directives","folder-vue-directives_light","folder-vue-directives-open","folder-vue-directives-open_light","folder-vue-open","folder-vue-open_light","folder-vuepress","folder-vuepress_light","folder-vuepress-open","folder-vuepress-open_light","folder-vuex-store","folder-vuex-store_light","folder-vuex-store-open","folder-vuex-store-open_light","folder-wakatime","folder-wakatime_light","folder-wakatime-open","folder-wakatime-open_light","folder-webpack","folder-webpack_light","folder-webpack-open","folder-webpack-open_light","folder-windows","folder-windows_light","folder-windows-open","folder-windows-open_light","folder-wordpress","folder-wordpress_light","folder-wordpress-open","folder-wordpress-open_light","folder-yarn","folder-yarn_light","folder-yarn-open","folder-yarn-open_light","folder-zeabur","folder-zeabur_light","folder-zeabur-open","folder-zeabur-open_light","font","font_light","forth","forth_light","fortran","fortran_light","foxpro","foxpro_light","freemarker","freemarker_light","fsharp","fsharp_light","fusebox","fusebox_light","gamemaker","gamemaker_light","garden","garden_light","gatsby","gatsby_light","gcp","gcp_light","gemfile","gemfile_light","gemini","gemini_light","gemini-ai","gemini-ai_light","git","git_light","github-actions-workflow","github-actions-workflow_light","github-sponsors","github-sponsors_light","gitlab","gitlab_light","gitpod","gitpod_light","gleam","gleam_light","gnuplot","gnuplot_light","go","go_gopher","go_gopher_light","go_light","go-mod","go-mod_light","godot","godot_light","godot-assets","godot-assets_light","gradle","gradle_light","grafana-alloy","grafana-alloy_light","grain","grain_light","graphcool","graphcool_light","graphql","graphql_light","gridsome","gridsome_light","groovy","groovy_light","grunt","grunt_light","gulp","gulp_light","h","h_light","hack","hack_light","hadolint","hadolint_light","haml","haml_light","handlebars","handlebars_light","hardhat","hardhat_light","harmonix","harmonix_light","haskell","haskell_light","haxe","haxe_light","hcl","hcl_light","helm","helm_light","heroku","heroku_light","hex","hex_light","histoire","histoire_light","hjson","hjson_light","horusec","horusec_light","hosts","hosts_light","hpp","hpp_light","html","html_light","http","http_light","huff","huff_light","hurl","hurl_light","husky","husky_light","i18n","i18n_light","idris","idris_light","ifanr-cloud","ifanr-cloud_light","image","image_light","imba","imba_light","installation","installation_light","ionic","ionic_light","istanbul","istanbul_light","jar","jar_light","java","java_light","javaclass","javaclass_light","javascript","javascript_light","javascript-map","javascript-map_light","jenkins","jenkins_light","jest","jest_light","jinja","jinja_light","jsconfig","jsconfig_light","json","json_light","jsr","jsr_light","julia","julia_light","jupyter","jupyter_light","just","just_light","karma","karma_light","kcl","kcl_light","key","key_light","keystatic","keystatic_light","kivy","kivy_light","kl","kl_light","knip","knip_light","kotlin","kotlin_light","kubernetes","kubernetes_light","kusto","kusto_light","label","label_light","laravel","laravel_light","latexmk","latexmk_light","lbx","lbx_light","lefthook","lefthook_light","lerna","lerna_light","less","less_light","liara","liara_light","lib","lib_light","lighthouse","lighthouse_light","lilypond","lilypond_light","lintstaged","lintstaged_light","liquid","liquid_light","lisp","lisp_light","livescript","livescript_light","lock","lock_light","log","log_light","lolcode","lolcode_light","lottie","lottie_light","lua","lua_light","luau","luau_light","lyric","lyric_light","makefile","makefile_light","markdoc","markdoc_light","markdoc-config","markdoc-config_light","markdown","markdown_light","markdownlint","markdownlint_light","markojs","markojs_light","mathematica","mathematica_light","matlab","matlab_light","maven","maven_light","mdsvex","mdsvex_light","mdx","mdx_light","mercurial","mercurial_light","merlin","merlin_light","mermaid","mermaid_light","meson","meson_light","minecraft","minecraft_light","minecraft-fabric","minecraft-fabric_light","mint","mint_light","mjml","mjml_light","mocha","mocha_light","modernizr","modernizr_light","mojo","mojo_light","moon","moon_light","moonscript","moonscript_light","mxml","mxml_light","nano-staged","nano-staged_light","ndst","ndst_light","nest","nest_light","netlify","netlify_light","next","next_light","nginx","nginx_light","ngrx-actions","ngrx-actions_light","ngrx-effects","ngrx-effects_light","ngrx-entity","ngrx-entity_light","ngrx-reducer","ngrx-reducer_light","ngrx-selectors","ngrx-selectors_light","ngrx-state","ngrx-state_light","nim","nim_light","nix","nix_light","nodejs","nodejs_alt","nodejs_alt_light","nodejs_light","nodemon","nodemon_light","npm","npm_light","nuget","nuget_light","nunjucks","nunjucks_light","nuxt","nuxt_light","nx","nx_light","objective-c","objective-c_light","objective-cpp","objective-cpp_light","ocaml","ocaml_light","odin","odin_light","opa","opa_light","opam","opam_light","openapi","openapi_light","otne","otne_light","oxlint","oxlint_light","packship","packship_light","palette","palette_light","panda","panda_light","parcel","parcel_light","pascal","pascal_light","pawn","pawn_light","payload","payload_light","pdf","pdf_light","pdm","pdm_light","percy","percy_light","perl","perl_light","php","php_elephant","php_elephant_light","php_elephant_pink","php_elephant_pink_light","php_light","php-cs-fixer","php-cs-fixer_light","phpstan","phpstan_light","phpunit","phpunit_light","pinejs","pinejs_light","pipeline","pipeline_light","pkl","pkl_light","plastic","plastic_light","playwright","playwright_light","plop","plop_light","pm2-ecosystem","pm2-ecosystem_light","pnpm","pnpm_light","poetry","poetry_light","postcss","postcss_light","posthtml","posthtml_light","powerpoint","powerpoint_light","powershell","powershell_light","pre-commit","pre-commit_light","prettier","prettier_light","prisma","prisma_light","processing","processing_light","prolog","prolog_light","prompt","prompt_light","proto","proto_light","protractor","protractor_light","pug","pug_light","puppet","puppet_light","puppeteer","puppeteer_light","purescript","purescript_light","python","python_light","python-misc","python-misc_light","pytorch","pytorch_light","qsharp","qsharp_light","quarto","quarto_light","quasar","quasar_light","quokka","quokka_light","qwik","qwik_light","r","r_light","racket","racket_light","raml","raml_light","razor","razor_light","rbxmk","rbxmk_light","rc","rc_light","react","react_light","react_ts","react_ts_light","readme","readme_light","reason","reason_light","red","red_light","redux-action","redux-action_light","redux-reducer","redux-reducer_light","redux-selector","redux-selector_light","redux-store","redux-store_light","regedit","regedit_light","remark","remark_light","remix","remix_light","renovate","renovate_light","replit","replit_light","rescript","rescript_light","rescript-interface","rescript-interface_light","restql","restql_light","riot","riot_light","roadmap","roadmap_light","roblox","roblox_light","robot","robot_light","robots","robots_light","rocket","rocket_light","rojo","rojo_light","rollup","rollup_light","rome","rome_light","routing","routing_light","rspec","rspec_light","rubocop","rubocop_light","ruby","ruby_light","ruff","ruff_light","rust","rust_light","salesforce","salesforce_light","san","san_light","sas","sas_light","sass","sass_light","sbt","sbt_light","scala","scala_light","scheme","scheme_light","scons","scons_light","screwdriver","screwdriver_light","search","search_light","semantic-release","semantic-release_light","semgrep","semgrep_light","sentry","sentry_light","sequelize","sequelize_light","serverless","serverless_light","settings","settings_light","shader","shader_light","silverstripe","silverstripe_light","simulink","simulink_light","siyuan","siyuan_light","sketch","sketch_light","slim","slim_light","slint","slint_light","slug","slug_light","smarty","smarty_light","sml","sml_light","snakemake","snakemake_light","snapcraft","snapcraft_light","snowpack","snowpack_light","snyk","snyk_light","solidity","solidity_light","sonarcloud","sonarcloud_light","spwn","spwn_light","stackblitz","stackblitz_light","stan","stan_light","steadybit","steadybit_light","stencil","stencil_light","stitches","stitches_light","storybook","storybook_light","stryker","stryker_light","stylable","stylable_light","stylelint","stylelint_light","stylus","stylus_light","sublime","sublime_light","subtitles","subtitles_light","supabase","supabase_light","svelte","svelte_light","svg","svg_light","svgo","svgo_light","svgr","svgr_light","swagger","swagger_light","sway","sway_light","swc","swc_light","swift","swift_light","syncpack","syncpack_light","systemd","systemd_light","table","table_light","tailwindcss","tailwindcss_light","taskfile","taskfile_light","tauri","tauri_light","taze","taze_light","tcl","tcl_light","teal","teal_light","templ","templ_light","template","template_light","terraform","terraform_light","test-js","test-js_light","test-jsx","test-jsx_light","test-ts","test-ts_light","tex","tex_light","textlint","textlint_light","tilt","tilt_light","tldraw","tldraw_light","tobi","tobi_light","tobimake","tobimake_light","todo","todo_light","toml","toml_light","travis","travis_light","tree","tree_light","trigger","trigger_light","tsconfig","tsconfig_light","tsdoc","tsdoc_light","tsil","tsil_light","tune","tune_light","turborepo","turborepo_light","twig","twig_light","twine","twine_light","typescript","typescript_light","typescript-def","typescript-def_light","typst","typst_light","umi","umi_light","uml","uml_light","unity","unity_light","unocss","unocss_light","url","url_light","uv","uv_light","vagrant","vagrant_light","vala","vala_light","vanilla-extract","vanilla-extract_light","varnish","varnish_light","vedic","vedic_light","velite","velite_light","velocity","velocity_light","vercel","vercel_light","verdaccio","verdaccio_light","verified","verified_light","verilog","verilog_light","vfl","vfl_light","video","video_light","vim","vim_light","virtual","virtual_light","visualstudio","visualstudio_light","vite","vite_light","vitest","vitest_light","vlang","vlang_light","vscode","vscode_light","vue","vue_light","vue-config","vue-config_light","vuex-store","vuex-store_light","wakatime","wakatime_light","wallaby","wallaby_light","wally","wally_light","watchman","watchman_light","webassembly","webassembly_light","webhint","webhint_light","webpack","webpack_light","wepy","wepy_light","werf","werf_light","windicss","windicss_light","wolframlanguage","wolframlanguage_light","word","word_light","wrangler","wrangler_light","wxt","wxt_light","xaml","xaml_light","xmake","xmake_light","xml","xml_light","yaml","yaml_light","yang","yang_light","yarn","yarn_light","zeabur","zeabur_light","zig","zig_light","zip","zip_light"]),Dp="oc-file-type-icon-sprite-root",Ey="http://www.w3.org/2000/svg";let S1=null,Ii=null,ha=null;const Sd=new Set,pa=new Set;let H3=0;const Op=new Set,_y=()=>H3,dP=e=>(Op.add(e),()=>{Op.delete(e)}),uP=()=>{H3+=1;for(const e of Array.from(Op))e()},fP=()=>mt(()=>import("./sprite-HGQGInUp.js"),[]);let hP=fP;const pP=e=>{const t=new Map;for(const n of e.matchAll(/<symbol\b[^>]*\bid="([^"]+)"[^>]*>[\s\S]*?<\/symbol>/g))t.set(n[1],n[0]);return t},F3=()=>{if(typeof document>"u"||!document.body)return null;const e=document.getElementById(Dp),t=e?.querySelector("defs");if(t)return t;e?.remove(),Sd.clear();const n=document.createElement("div");n.id=Dp,n.setAttribute("aria-hidden","true"),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden";const r=document.createElementNS(Ey,"svg");r.setAttribute("width","0"),r.setAttribute("height","0");const s=document.createElementNS(Ey,"defs");return r.appendChild(s),n.appendChild(r),document.body.appendChild(n),s},mP=()=>typeof document>"u"||!document.body?!1:!!document.getElementById(Dp)?.querySelector("defs"),C1=e=>{const t=F3();if(!t||Sd.has(e)||!ha)return;const n=ha.get(e);if(n){Sd.add(e),t.insertAdjacentHTML("beforeend",n);for(const r of n.matchAll(/href="#([^"]+)"/g))ha.has(r[1])&&C1(r[1])}},gP=e=>{if(!(Sd.has(e)&&mP())){if(S1===null||ha===null){pa.add(e),B3().catch(()=>{});return}pa.delete(e),C1(e)}},yP=e=>{if(S1=e,ha=pP(e),pa.size>0&&F3()!==null){const t=Array.from(pa);pa.clear();for(const n of t)C1(n)}uP()},B3=()=>S1!==null?Promise.resolve():(Ii||(Ii=hP().then(e=>{Ii=null,yP(typeof e=="string"?e:e.default)},()=>{throw Ii=null,new Error("file-type sprite failed to load")})),Ii),vP=()=>{if(typeof window>"u"||typeof document>"u")return;const e=()=>{B3().catch(()=>{})};if(typeof window.requestIdleCallback=="function"){window.requestIdleCallback(()=>e());return}window.setTimeout(e,0)};vP();const jy={dockerfile:"docker",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake","package-lock.json":"npm","yarn.lock":"yarn","pnpm-lock.yaml":"pnpm","bun.lock":"bun","bun.lockb":"bun","tsconfig.json":"tsconfig","jsconfig.json":"jsconfig",".gitignore":"git",".gitattributes":"git",".gitmodules":"git",".editorconfig":"editorconfig",".npmrc":"npm",".yarnrc":"yarn",".prettierrc":"prettier",".eslintrc":"eslint",".babelrc":"babel"},Ty={javascript:"javascript",jsx:"react",typescript:"typescript",tsx:"react_ts",html:"html",handlebars:"handlebars",twig:"twig",liquid:"liquid",css:"css",scss:"sass",sass:"sass",less:"less",stylus:"stylus",json:"json",yaml:"yaml",toml:"toml",xml:"xml",ini:"settings",properties:"settings",bash:"console",powershell:"powershell",batch:"console",python:"python",ruby:"ruby",erb:"ruby",php:"php",java:"java",kotlin:"kotlin",scala:"scala",groovy:"groovy",c:"c",cpp:"cpp",objectivec:"objective-c",csharp:"csharp",fsharp:"fsharp",go:"go",rust:"rust",swift:"swift",dart:"dart",lua:"lua",perl:"perl",r:"r",julia:"julia",haskell:"haskell",elixir:"elixir",erlang:"erlang",clojure:"clojure",lisp:"lisp",scheme:"scheme",ocaml:"ocaml",reason:"reason",nim:"nim",zig:"zig",v:"vlang",crystal:"crystal",d:"d",sql:"database",graphql:"graphql",solidity:"solidity",nasm:"assembly",nix:"nix",hcl:"terraform",puppet:"puppet",latex:"tex",bibtex:"bibliography",markdown:"markdown",asciidoc:"asciidoc",text:"document",vim:"vim",makefile:"makefile",cmake:"cmake",diff:"diff",prisma:"prisma",protobuf:"proto",thrift:"document",wasm:"webassembly",glsl:"shader",hlsl:"shader",cg:"shader",apacheconf:"settings",nginx:"nginx"},Ay={yml:"yaml",mdx:"mdx",md:"markdown",lock:"lock",env:"settings",zip:"zip",tgz:"zip",gz:"zip",rar:"zip","7z":"zip",png:"image",jpg:"image",jpeg:"image",gif:"image",svg:"svg",webp:"image",avif:"image",bmp:"image",ico:"favicon",mp3:"audio",wav:"audio",flac:"audio",ogg:"audio",mp4:"video",mov:"video",avi:"video",mkv:"video",webm:"video",pdf:"pdf",doc:"word",docx:"word",ppt:"powerpoint",pptx:"powerpoint"},Cd="document",xP=(e,t)=>{if(!e)return t==="light"?`${Cd}_light`:Cd;if(t==="light"){const n=e.endsWith("_light")?e:`${e}_light`;return w1.has(n)?n:e}return e},bP=e=>typeof e=="string"&&e.trim().length>0,wP=(e,t)=>{const r=e.replace(/\\/g,"/").split("/").pop()?.toLowerCase()||"";if(jy[r])return jy[r];if(r.startsWith(".env"))return"settings";const s=L3(e);if(s&&Ty[s])return Ty[s];const o=bP(t)?t.toLowerCase():r.includes(".")&&r.split(".").pop()?.toLowerCase()||"";return o&&Ay[o]?Ay[o]:o&&w1.has(o)?o:Cd},SP=(e,t)=>{const n=wP(e,t?.extension),r=w1.has(n)?n:Cd,s=xP(r,t?.themeVariant);return gP(s),`#${s}`},pr=({filePath:e,extension:t,className:n})=>{const r=Ow(),s=H.useSyncExternalStore(dP,_y,_y),o=r?.currentTheme.metadata.variant==="light"?"light":"dark",i=SP(e,{extension:t,themeVariant:o});return c.jsx("svg",{className:R("block h-4 w-4 flex-shrink-0",n),"aria-hidden":"true",focusable:"false",children:c.jsx("use",{href:i,xlinkHref:i},s)})},CP=e=>e===null?null:Math.min(100,Math.max(0,e));function kP({filename:e,progress:t}){const n=CP(t);return c.jsx("span",{role:"progressbar","aria-label":`Uploading ${e}`,"aria-valuemin":0,"aria-valuemax":100,...n!==null?{"aria-valuenow":n}:{},className:"relative block size-6 shrink-0",children:c.jsx("span",{className:"block size-6",style:n===null?void 0:{opacity:.35+.65*n/100,filter:`saturate(${n/100})`},children:c.jsx(pr,{filePath:e,className:"size-6 shrink-0"})})})}const MP=H.memo(()=>{const e=H.useRef(null),t=Ye(a=>a.addAttachedFile),n=re(a=>a.isMobile),r=n?"h-9 w-9":"h-7 w-7",s=n?"h-5 w-5":"h-[18px] w-[18px]",o=async a=>{await Promise.all(Array.from(a).map(async l=>{try{await t(l)}catch(d){console.error("File attach failed",d),Ce.error(d instanceof Error?d.message:"Failed to attach file")}}))},i=async a=>{const l=a.target.files;l&&(await o(l),e.current&&(e.current.value=""))};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:e,type:"file",multiple:!0,className:"hidden",onChange:i}),c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx("button",{type:"button",onClick:()=>e.current?.click(),className:R("flex items-center justify-center rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring","hover:bg-muted text-muted-foreground",r),"aria-label":"Attach files",children:c.jsx(V,{name:"attachment-2",className:s})})}),c.jsx(Ct,{side:"top",children:c.jsx("p",{children:"Attach files"})})]})]})});MP.displayName="FileAttachmentButton";const IP=e=>!Number.isFinite(e)||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,EP=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},V3=H.memo(({file:e,onRemove:t,onRetry:n,onShowPopup:r,gallery:s,galleryIndex:o})=>{const{isMobile:i,isTablet:a}=On(),l=i||a,d=e.uploadState,f=d?.status==="ready"&&d.expiresAt<=Date.now(),u=e.mimeType.startsWith("image/"),h=u&&e.previewUrl?e.previewUrl:u&&e.dataUrl.startsWith("data:image/")?e.dataUrl:u&&e.serverPath||"",m=EP(e.filename),g=IP(e.size),x=d?.status==="preparing"?"Preparing attachment":d?.status==="uploading"?"Uploading attachment":d?.status==="failed"||f?"Attachment upload failed":d?.status==="ready"?"Attachment ready":"Server attachment ready",b=d?.status==="uploading"?d.progress:null,S=d?.status==="uploading"||d?.status==="preparing",y=d?.status==="failed"?d.error:f?"Upload expired.":null,v=()=>{!r||!h||r({open:!0,title:e.filename||"Image",content:"",metadata:{tool:"image-preview",filename:e.filename,mime:e.mimeType,size:e.size},image:{url:h,mimeType:e.mimeType,filename:e.filename,size:e.size,gallery:s,index:o}})};return c.jsxs("article",{className:R("group relative min-w-0 overflow-hidden rounded-xl border w-full",y?"border-[var(--status-error)]/50 bg-[var(--status-error-background)]/40":"border-border/60 bg-[var(--surface-elevated)]"),children:[c.jsx("span",{className:"sr-only","aria-live":"polite",children:x}),c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("div",{role:h&&r?"button":void 0,tabIndex:h&&r?0:void 0,onClick:v,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),v())},className:R("flex min-h-14 items-center gap-2.5 px-3 py-2",y?"pr-14":"pr-8",h&&r&&"cursor-pointer select-none focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"),"aria-label":h?`Preview ${e.filename}`:void 0,children:[S?c.jsx(kP,{filename:e.filename,progress:b}):c.jsx(pr,{filePath:e.filename,extension:m,className:"size-6 shrink-0"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"truncate typography-ui-label text-foreground",title:e.filename,children:e.filename}),c.jsx("p",{className:"typography-meta text-muted-foreground",children:[m.toUpperCase(),g].filter(Boolean).join(" · ")})]})]})}),c.jsx(Ct,{side:"top",className:R(h&&!y?D3:void 0),children:y?c.jsx("p",{children:y}):c.jsx(O3,{imageUrl:h||void 0,filename:e.filename,metaLine:h?[m.toUpperCase(),g].filter(Boolean).join(" · "):g})})]}),S?c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 overflow-hidden rounded-xl",children:c.jsx("span",{className:"attachment-upload-shimmer absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r from-transparent via-foreground/10 to-transparent"})}):null,c.jsx(be,{variant:"ghost",size:"xs",onClick:C=>{C.stopPropagation(),t()},className:R("absolute right-1 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",l?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),"aria-label":`Remove ${e.filename}`,title:`Remove ${e.filename}`,children:c.jsx(V,{name:"close",className:"size-3.5"})}),y?c.jsx(be,{variant:"ghost",size:"xs",onClick:C=>{C.stopPropagation(),n()},className:R("absolute right-8 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",l?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),"aria-label":`Retry upload of ${e.filename}`,title:"Retry upload",children:c.jsx(V,{name:"refresh",className:"size-3.5"})}):null]})});V3.displayName="DraftAttachmentCard";const $3=H.memo(({onShowPopup:e,className:t,isInline:n=!1,isMobile:r=!1})=>{const s=Ye(h=>h.attachedFiles),o=Ye(h=>h.removeAttachedFile),i=Ye(h=>h.retryAttachmentUpload),[,a]=p.useState(0);if(p.useEffect(()=>{const h=s.reduce((g,x)=>x.uploadState?.status!=="ready"||x.uploadState.expiresAt<=Date.now()?g:g===null?x.uploadState.expiresAt:Math.min(g,x.uploadState.expiresAt),null);if(h===null)return;const m=setTimeout(()=>a(g=>g+1),Math.max(0,h-Date.now()+1));return()=>clearTimeout(m)},[s]),s.length===0)return null;const d=s.filter(h=>h.mimeType.startsWith("image/")).flatMap(h=>{const m=h.previewUrl||h.dataUrl||h.serverPath||"";return m?[{file:h,image:{url:m,mimeType:h.mimeType,filename:h.filename,size:h.size}}]:[]}),f=d.map(h=>h.image),u=new Map(d.map((h,m)=>[h.file.id,m]));return c.jsx("div",{className:R("grid w-full gap-2 grid-cols-2 sm:grid-cols-3",n?"px-1.5 pt-1.5 pb-1":r?"px-3 pt-2.5 pb-1.5":"px-3 pt-3 pb-1.5",t),"data-no-drawer-swipe":"true",children:s.map(h=>c.jsx(V3,{file:h,onRemove:()=>o(h.id),onRetry:()=>i(h.id),onShowPopup:e,gallery:f,galleryIndex:u.get(h.id)??0},h.id))})});$3.displayName="AttachedFilesList";const _P="application/vnd.github.issue-link",jP="application/vnd.github.pull-request-link",sh=e=>e.mime===_P?"issue":e.mime===jP?"pr":null,k1=H.memo(({files:e,onShowPopup:t,compact:n=!1})=>{const r=e.filter(u=>u.type==="file"&&(u.mime||u.url)),s=u=>{if(!u)return"Unnamed file";const m=u.replace(/\\/g,"/").split("/");return m[m.length-1]||u},o=p.useCallback(u=>sh(u)!==null&&typeof u.filename=="string"&&u.filename.trim().length>0?u.filename.trim():s(u.filename||u.url),[]),i=u=>!u||!Number.isFinite(u)||u<=0?"":u<1024?`${u} B`:u<1024*1024?`${(u/1024).toFixed(1)} KB`:`${(u/(1024*1024)).toFixed(1)} MB`,a=r.filter(u=>u.mime?.startsWith("image/")&&u.url),l=r.filter(u=>!u.mime?.startsWith("image/")),d=p.useMemo(()=>a.flatMap(u=>{if(!u.url)return[];const h=o(u)||"Image";return[{url:u.url,mimeType:u.mime,filename:h,size:u.size}]}),[a,o]),f=p.useCallback(u=>{if(!t)return;const h=d[u];if(!h?.url)return;const m=h.filename||"Image";t({open:!0,title:m,content:"",metadata:{tool:"image-preview",filename:m,mime:h.mimeType,size:h.size},image:{url:h.url,mimeType:h.mimeType,filename:m,size:h.size,gallery:d,index:u}})},[d,t]);return r.length===0?null:n?c.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[l.length>0&&c.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map((u,h)=>{const m=o(u),g=m.split(".").pop()||"",x=i(u.size),b=sh(u);return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:b&&u.url?c.jsxs("button",{type:"button",onClick:()=>{ja(u.url||"")},className:"inline-flex items-center bg-muted/30 border border-border/30 typography-meta gap-1 px-2 py-0.5 rounded-lg text-foreground hover:text-primary transition-colors",children:[b==="pr"?c.jsx(V,{name:"git-pull-request",className:"text-muted-foreground h-3.5 w-3.5"}):c.jsx(V,{name:"github",className:"text-muted-foreground h-3.5 w-3.5"}),c.jsx("div",{className:"overflow-hidden max-w-[220px]",children:c.jsx("span",{className:"truncate block",title:m,children:m})})]}):c.jsxs("div",{className:"inline-flex items-center bg-muted/30 border border-border/30 typography-meta gap-1 px-2 py-0.5 rounded-lg",children:[u.mime?.includes("pdf")?c.jsx(V,{name:"file-pdf",className:"text-muted-foreground h-3.5 w-3.5"}):c.jsx(pr,{filePath:m,extension:g,className:"text-muted-foreground h-3.5 w-3.5"}),c.jsx("div",{className:"overflow-hidden max-w-[140px]",children:c.jsx("span",{className:"truncate block",title:m,children:m})})]})}),c.jsx(Ct,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},`file-${u.url||u.filename||h}`)})}),a.length>0&&c.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-0.5 scrollbar-thin","data-no-drawer-swipe":"true",children:c.jsx("div",{className:"flex snap-x snap-mandatory gap-2",children:a.map((u,h)=>{const m=o(u)||"Image";return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>f(h),className:"relative flex-none border border-border/40 bg-muted/10 overflow-hidden snap-start h-12 w-12 sm:h-14 sm:w-14 md:h-16 md:w-16 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[u.url?c.jsx("img",{src:u.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:g=>{const x=g.target;x.style.visibility="hidden"}}):c.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:c.jsx(V,{name:"file-image",className:"h-6 w-6"})}),c.jsx("span",{className:"sr-only",children:m})]})}),c.jsx(Ct,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u.url||u.filename||h}`)})})})]}):c.jsx("div",{className:R("grid gap-2",n?"grid-cols-1":"grid-cols-1 sm:grid-cols-2"),children:r.map((u,h)=>{const m=o(u),g=u.mime?.startsWith("image/"),x=i(u.size),b=sh(u);if(g&&u.url)return c.jsxs("div",{className:"relative aspect-video rounded-lg border border-border/40 bg-muted/10 overflow-hidden group",children:[c.jsx("img",{src:u.url,alt:m,className:"h-full w-full object-cover",loading:"lazy"}),c.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity"}),c.jsxs("div",{className:"absolute bottom-0 left-0 right-0 p-2 text-white opacity-0 group-hover:opacity-100 transition-opacity",children:[c.jsx("p",{className:"text-xs font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs opacity-80",children:x})]})]},u.url||`${m}-${h}`);if(b&&u.url)return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{ja(u.url||"")},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left",n?"text-xs":"text-sm"),children:[c.jsx("div",{className:"flex-shrink-0",children:b==="pr"?c.jsx(V,{name:"git-pull-request",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):c.jsx(V,{name:"github",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs text-muted-foreground",children:x})]})]})}),c.jsx(Ct,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},u.url||`${m}-${h}`);const S=u.source,y=typeof S?.type=="string"?S.type:void 0,v=S&&typeof S.path=="string"?S.path:void 0,C=y==="file"&&v?v:u.url||"";return C&&R3(C)?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{re.getState().navigateToDiagram(C)},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left cursor-pointer",n?"text-xs":"text-sm"),children:[c.jsx(V,{name:"file",className:R("text-muted-foreground shrink-0",n?"h-3.5 w-3.5":"h-4 w-4")}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),c.jsx("p",{className:"text-xs text-status-info",children:"Open in diagram view"})]}),c.jsx(V,{name:"external-link",className:R("text-muted-foreground shrink-0",n?"h-3 w-3":"h-3.5 w-3.5")})]})}),c.jsx(Ct,{children:c.jsx("p",{children:"Open in diagram view"})})]},u.url||`${m}-${h}`):c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{t&&u.url&&t({open:!0,title:m,content:"",image:{url:u.url,mimeType:u.mime,filename:m}})},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left",n?"text-xs":"text-sm"),children:[c.jsx("div",{className:"flex-shrink-0",children:u.mime?.startsWith("image/")?c.jsx(V,{name:"file-image",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):u.mime?.includes("pdf")?c.jsx(V,{name:"file-pdf",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):c.jsx(V,{name:"file",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs text-muted-foreground",children:x})]})]})}),c.jsx(Ct,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},u.url||`${m}-${h}`)})})});k1.displayName="MessageFilesDisplay";const TP=H.memo(({urls:e,caption:t,onShowPopup:n})=>{if(e.length===0)return null;const r=()=>e.length===1?"grid-cols-1":e.length===2||e.length<=4?"grid-cols-2":"grid-cols-3";return c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:R("grid gap-2",r()),children:e.map((s,o)=>c.jsxs("button",{type:"button",onClick:()=>n?.({open:!0,title:t||`Image ${o+1} of ${e.length}`,content:"",image:{url:s,gallery:e.map(i=>({url:i})),index:o}}),className:"relative aspect-square rounded-lg border border-border/40 bg-muted/10 overflow-hidden group",children:[c.jsx("img",{src:s,alt:t||`Image ${o+1}`,className:"h-full w-full object-cover transition-transform group-hover:scale-105",loading:"lazy"}),c.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors"})]},s))}),t&&c.jsx("p",{className:"text-sm text-muted-foreground italic",children:t})]})});TP.displayName="ImageGallery";const z3=H.memo(({message:e,target:t,sending:n,checking:r,canSteer:s,onEdit:o,onSend:i,onCheck:a})=>{const l=ft(C=>C.removeFromQueue),{attributes:d,listeners:f,setNodeRef:u,transform:h,transition:m,isDragging:g}=Cm({id:e.id}),x=p.useMemo(()=>{const C=e.content.split(`
|
|
70
|
+
`),w=C[0]||"",I=100;return w.length>I?w.substring(0,I)+"...":w+(C.length>1?"...":"")},[e.content]),b=e.attachments?.length??0,S=e.deliveryAttempt!==void 0,y=e.sendFailed===!0,v=n||r;return c.jsxs("div",{ref:u,style:{transform:km.Translate.toString(h),transition:m},className:R("flex min-w-0 flex-col gap-1 py-1",g&&"z-10 opacity-60"),children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("button",{type:"button",...d,...f,className:"flex flex-shrink-0 cursor-grab touch-none select-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing","aria-label":"Drag to reorder",children:c.jsx(V,{name:"draggable",className:"h-4 w-4","aria-hidden":"true"})}),c.jsxs("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:[x||"(empty)",b>0&&c.jsx("span",{className:"ml-1 text-muted-foreground",children:b===1?"+1 file":`+${b} files`})]}),c.jsxs(be,{type:"button",variant:"secondary",size:"xs",onClick:()=>o(e),disabled:v,children:[c.jsx(V,{name:"edit",className:"h-3 w-3","aria-hidden":"true"}),"Edit"]}),S?c.jsxs(be,{type:"button",variant:"secondary",size:"xs",onClick:()=>a(e),disabled:v,"aria-label":"Check delivery status",title:"Check delivery status",children:[c.jsx(V,{name:"refresh",className:"h-3 w-3","aria-hidden":"true"}),"Check status"]}):s?c.jsxs(be,{type:"button",variant:"secondary",size:"xs",onClick:()=>i(e),disabled:v,"aria-label":"Send now with steering",title:"Send now with steering",children:[c.jsx(V,{name:"send-plane",className:"h-3 w-3","aria-hidden":"true"}),"Steer"]}):null,c.jsx("button",{type:"button",onClick:()=>l(t,e.id),disabled:v,className:"flex items-center justify-center h-6 w-6 flex-shrink-0 hover:bg-[var(--interactive-hover)] rounded-full transition-colors disabled:pointer-events-none disabled:opacity-50","aria-label":"Remove follow-up",children:c.jsx(V,{name:"close",className:"h-4 w-4 text-muted-foreground"})})]}),(n||r||y||S)&&c.jsx("p",{className:R("typography-micro pl-6",y&&!n&&!r?"text-[var(--status-error)]":S&&!n&&!r?"text-[var(--status-warning)]":"text-muted-foreground"),role:y||S?"status":void 0,children:n?"Sending…":r?"Checking status…":y?"Send failed. Retry with Steer or remove.":"Delivery uncertain. Check status before retrying."})]})});z3.displayName="QueuedMessageChip";const Ny=[],Ly=[],U3=H.memo(({onEditMessage:e,onSendMessage:t})=>{const n=he(k=>k.currentSessionId),r=uu(n??""),s=he(p.useCallback(k=>n?k.getDirectoryForSession(n):null,[n])),o=n?gm(n,s):null,i=o?R5(o):null,a=ft(p.useCallback(k=>i?k.queuedMessages[i]??Ny:Ny,[i])),l=ft(p.useCallback(k=>i?k.sendingIds[i]??Ly:Ly,[i])),d=ft(k=>k.popToInput),f=ft(k=>k.reorderQueue),[u,h]=p.useState([]),m=n?`session:${n}`:"*",g=Be(k=>k.reducer.bySession,(k,_)=>{if(Object.is(k,_)||!n)return!0;const M=k.get(n)?.queue,L=_.get(n)?.queue;return!M&&!L?!0:!M||!L?!1:M.steering===L.steering&&M.followUp===L.followUp},m),x=n?g.get(n)?.queue:void 0,b=x?.steering??0,S=x?.followUp??0,y=b>0||S>0,v=!!o&&a.length>0,C=b===1?"1 steering message waiting":`${b} steering messages waiting`,w=S===1?"1 follow-up message waiting":`${S} follow-up messages waiting`,I=xm(wa($5,{activationConstraint:{distance:8}}),wa(V5,{activationConstraint:{delay:200,tolerance:6}})),E=p.useCallback(k=>{const{active:_,over:M}=k;!M||_.id===M.id||!o||f(o,String(_.id),String(M.id))},[o,f]),T=p.useCallback(k=>{if(!o)return;const _=d(o,k.id);if(_){if(_.attachments&&_.attachments.length>0){const M=Ye.getState().attachedFiles;Ye.getState().setAttachedFiles([...M,..._.attachments])}e(_.content,_.attachments)}},[o,d,e]),A=p.useCallback(k=>{t(k.id)},[t]),j=p.useCallback(async k=>{if(!o||!i||u.includes(k.id)||l.includes(k.id))return;const M=ft.getState().queuedMessages[i]?.find(L=>L.id===k.id)?.deliveryAttempt??k.deliveryAttempt;if(M){h(L=>L.includes(k.id)?L:[...L,k.id]);try{const L=await DL(o,M);L==="accepted"?ft.getState().completeQueuedSend(o,k.id):L==="pending"?Ce.info("Delivery still pending. Follow-ups are on hold. Check again later."):Ce.warning("Delivery status unknown. The message stays on hold. No resend attempted.")}finally{h(L=>L.filter(O=>O!==k.id))}}},[o,i,u,l]);return!v&&!y?null:c.jsx("div",{className:"pb-2 w-full px-1",children:c.jsxs("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm overflow-hidden",children:[v&&o&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex w-full items-center gap-2 px-3 py-2 text-left",children:[c.jsxs("span",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:["Follow-up messages"," ",a.length]}),r?c.jsx("span",{className:"ml-auto min-w-0 truncate typography-meta text-muted-foreground",children:`Sends after ${r}`}):c.jsx(V,{name:"time",className:"ml-auto h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}),c.jsx(bm,{sensors:I,collisionDetection:wm,onDragEnd:E,children:c.jsx(Sm,{items:a.map(k=>k.id),strategy:z5,children:c.jsx("div",{className:"px-3 pb-3 flex flex-col gap-1.5 max-h-[10.5rem] overflow-y-auto",children:a.map(k=>c.jsx(z3,{message:k,target:o,sending:l.includes(k.id),checking:u.includes(k.id),canSteer:!r,onEdit:T,onSend:A,onCheck:j},k.id))})})})]}),y&&c.jsxs("div",{className:R("px-3 typography-micro text-muted-foreground",v?"pb-3 pt-1":"py-2"),children:[b>0&&c.jsx("p",{role:"status",children:C}),S>0&&c.jsx("p",{role:"status",children:w})]})]})})});U3.displayName="QueuedMessageChips";let oh=Date.now();const AP=()=>(oh=Math.max(oh+1,Date.now()),oh),Ry=()=>!(typeof document>"u"||document.visibilityState!=="visible"||typeof document.hasFocus=="function"&&!document.hasFocus());function NP({sessionId:e,directory:t,text:n,debounceMs:r=250}){const s=Be(m=>e?m.reducer.bySession.get(e)?.extensionDraftTracked===!0:!1,Object.is,e?`session:${e}`:"chrome"),o=s?n:null,i=H.useRef(n);i.current=n;const a=H.useRef(t);a.current=t;const l=H.useRef(e);l.current=e;const d=H.useRef(new Map),f=H.useRef(null),u=H.useRef(new Set);H.useEffect(()=>{if(!e)return;const m=u.current,g=d.current;return()=>{m.delete(e),g.delete(e)}},[e]);const h=H.useCallback((m,g)=>{if(!Ry())return;d.current.set(m,g);const x=AP(),b=a.current;Ie.updateExtensionDraft({sessionId:m,text:g,revision:x,...b?{directory:b}:{}}).catch(()=>{d.current.get(m)===g&&d.current.delete(m)})},[]);H.useEffect(()=>{if(!e||!s)return;const m=()=>{if(!Ry())return;const g=i.current,x=d.current.get(e);g!==x&&(f.current!==null&&(clearTimeout(f.current),f.current=null),h(e,g))};return typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("focus",m),typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",m),()=>{typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener("focus",m),typeof document<"u"&&typeof document.removeEventListener=="function"&&document.removeEventListener("visibilitychange",m)}},[e,s,h]),H.useEffect(()=>{if(!e||o===null){e&&u.current.delete(e),f.current!==null&&(clearTimeout(f.current),f.current=null);return}if(!u.current.has(e)){u.current.add(e),f.current!==null&&(clearTimeout(f.current),f.current=null),h(e,o);return}const g=d.current.get(e);if(o===g){f.current!==null&&(clearTimeout(f.current),f.current=null);return}return f.current!==null&&clearTimeout(f.current),f.current=setTimeout(()=>{f.current=null;const x=i.current,b=l.current;!b||x===d.current.get(b)||h(b,x)},r),()=>{f.current!==null&&(clearTimeout(f.current),f.current=null)}},[e,o,r,h])}const LP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.9568%209.88184H22.1265L30.7753%2031.7848H35.4917L26.9568%209.88184ZM13.028%209.88184L4.4917%2031.7848H9.32203L11.2305%2027.1793H20.2166L22.0126%2031.6724H26.8444L18.0832%209.88184H13.028ZM12.5783%2023.1361L15.4987%2015.3853L18.5315%2023.1361H12.5783Z'%20fill='currentColor'/%3e%3c/svg%3e",RP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37.9998%2023.021C33.7998%2025.2889%2029.5698%2027.3649%2024.8614%2028.3069C23.8114%2028.5154%2022.6474%2028.5154%2021.5809%2028.3714C20.5639%2028.2439%2020.0554%2027.3484%2020.4169%2026.4064C20.7619%2025.5289%2021.2209%2024.635%2021.8119%2023.9C23.0899%2022.3025%2024.5329%2020.849%2025.8289%2019.268C26.6203%2018.2991%2027.3335%2017.2689%2027.9618%2016.187C28.4208%2015.4205%2028.2078%2014.4935%2027.4038%2014.111C26.0584%2013.4556%2024.6154%2012.9936%2023.1889%2012.4986C23.0239%2012.4341%2022.7779%2012.6096%2022.4509%2012.7221C22.8604%2013.0881%2023.1559%2013.3596%2023.5654%2013.727C19.3339%2014.447%2015.3305%2015.467%2011.4455%2016.874C11.4275%2016.9535%2011.396%2017.0165%2011.411%2017.0495C11.9855%2017.927%2011.723%2018.5975%2010.886%2019.1405C10.5611%2019.3531%2010.2732%2019.6176%2010.034%2019.9235C12.593%2020.6735%2014.873%2020.243%2017.0539%2018.821C16.9234%2018.6305%2016.7914%2018.455%2016.6609%2018.263C17.4799%2018.407%2017.9719%2018.854%2018.0379%2019.556C18.0544%2019.7165%2017.9569%2019.8755%2017.9074%2020.036C17.7919%2019.907%2017.6449%2019.781%2017.5474%2019.6355C17.4799%2019.5395%2017.4634%2019.4285%2017.4154%2019.268C14.8235%2020.993%2012.035%2021.425%208.96751%2020.531C8.96751%2021.137%208.93451%2021.6485%208.98401%2022.1435C9.01701%2022.574%208.83701%2022.766%208.44401%2022.9895C7.55752%2023.5325%206.63803%2024.092%205.90003%2024.8105C5.01504%2025.6879%205.34354%2026.7589%206.54053%2027.2059C7.90102%2027.7159%209.329%2027.7309%2010.7555%2027.5569C12.4445%2027.3484%2014.1005%2027.0769%2015.9394%2026.8219C13.79%2027.8269%2011.6735%2028.5319%209.4445%2028.8169C7.88452%2029.0269%206.32753%2029.1379%204.78554%2028.6909C2.57156%2028.0684%201.58607%2026.4394%202.16057%2024.251C2.70206%2022.2065%204.01455%2020.5775%205.42454%2019.076C10.133%2014.078%2016.0864%2011.5401%2022.9744%2011.0286C24.5824%2010.9176%2026.2069%2011.1246%2027.7143%2011.7951C29.8308%2012.7536%2030.7173%2014.78%2029.6838%2016.826C29.0118%2018.1835%2028.0758%2019.4285%2027.1413%2020.6585C26.2234%2021.872%2025.1899%2022.9895%2024.2224%2024.155C23.9434%2024.506%2023.6809%2024.875%2023.4679%2025.2724C23.0569%2026.0224%2023.3359%2026.5174%2024.2059%2026.4394C26.0254%2026.2624%2027.8808%2026.1199%2029.6358%2025.6729C32.2098%2025.0174%2034.7193%2024.092%2037.2618%2023.2775C37.5243%2023.213%2037.7703%2023.117%2037.9998%2023.0225V23.021Z'%20fill='currentColor'/%3e%3c/svg%3e",PP="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eCursor%3c/title%3e%3cg%20transform='translate(12%2012)%20scale(0.88)%20translate(-12%20-12)'%3e%3cpath%20d='M22.106%205.68L12.5.135a.998.998%200%2000-.998%200L1.893%205.68a.84.84%200%2000-.419.726v11.186c0%20.3.16.577.42.727l9.607%205.547a.999.999%200%2000.998%200l9.608-5.547a.84.84%200%2000.42-.727V6.407a.84.84%200%2000-.42-.726zm-.603%201.176L12.228%2022.92c-.063.108-.228.064-.228-.061V12.34a.59.59%200%2000-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264%200%20.428.286.296.514z'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",DP="data:image/svg+xml,%3csvg%20fill='%23000000'%20viewBox='0%200%2033%2025'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M79.01%205.863c-4.066%200-6.511%202.92-6.511%206.535%200%203.635%202.445%206.555%206.511%206.555%204.046%200%206.512-2.92%206.512-6.555s-2.466-6.535-6.512-6.535Zm0%2010.968c-2.633%200-4.172-1.933-4.172-4.433s1.539-4.455%204.172-4.455c2.635%200%204.151%201.933%204.151%204.434%200%202.521-1.516%204.454-4.15%204.454Zm14.393%202.096c3.393%200%205.542-1.808%205.837-4.539h-2.36c-.316%201.555-1.517%202.437-3.477%202.437-2.423%200-3.878-1.68-3.878-4.433%200-2.774%201.476-4.434%203.878-4.434%201.96%200%203.14.862%203.477%202.5h2.36c-.295-2.773-2.444-4.622-5.837-4.622-3.856%200-6.217%202.669-6.217%206.535%200%203.887%202.36%206.556%206.217%206.556Zm-29.543-.311h2.36v-6.01c0-2.752%201.348-4.244%203.772-4.244h2.276V6.177h-2.255c-2.128%200-3.288.735-3.898%202.605l-.443-.063.527-2.542h-2.36v12.439h.02Zm-24.445-7.332c.106-2.101%201.517-3.53%203.793-3.53%202.276%200%203.646%201.345%203.646%203.53h-7.439Zm9.778.4c0-3.426-2.381-5.821-5.943-5.821-3.73%200-6.174%202.563-6.174%206.535%200%204.013%202.423%206.555%206.28%206.555%202.929%200%205.247-1.597%205.669-3.887h-2.36c-.507%201.156-1.666%201.828-3.31%201.828-2.38%200-3.877-1.408-3.94-3.803h9.694c.042-.588.084-.861.084-1.408Zm5.69%206.932h1.939l5.5-12.44h-2.529L56%2015.99l-.316.021-3.793-9.833h-2.508l5.5%2012.439ZM32.23%2012.35c0-.882-.359-1.701-.99-2.437a8.594%208.594%200%200%201-1.497%201.093c.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.281.021-14.118-2.059-14.118-4.811%200-.463.168-.925.505-1.345a8.13%208.13%200%200%201-1.475-1.093c-.632.736-.99%201.555-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.87.021%2016.078-2.5%2016.078-6.535Zm-3.351%201.534c-.906-.462-1.96-.861-3.16-1.197-1.37.378-2.909.672-4.553.861%202.318.294%204.341.778%205.9%201.408.76-.336%201.37-.693%201.813-1.072Zm-17.849-.357a31.902%2031.902%200%200%201-4.467-.84c-1.18.336-2.255.735-3.16%201.197.42.379%201.01.715%201.748%201.05%201.539-.63%203.52-1.113%205.88-1.407Zm21.2-6.808c0-4.013-7.207-6.534-16.079-6.534C7.26.185.051%202.706.051%206.719c0%204.035%207.208%206.535%2016.1%206.535%208.872.021%2016.079-2.5%2016.079-6.535Zm-1.94%200c0%202.732-5.836%204.812-14.139%204.812-8.302.021-14.14-2.06-14.14-4.812%200-2.731%205.838-4.811%2014.14-4.811%207.86%200%2014.14%202.08%2014.14%204.811Zm-3.223%202.564c.758-.336%201.37-.694%201.812-1.072-2.95-1.513-7.544-2.353-12.728-2.353s-9.799.84-12.728%202.353c.422.378%201.012.715%201.75%201.05%202.507-1.05%206.363-1.68%2010.978-1.68%204.404%200%208.324.651%2010.916%201.702ZM1.042%2015.628c-.632.736-.99%201.534-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.892%200%2016.099-2.521%2016.099-6.534%200-.883-.359-1.702-.99-2.438-.422.4-.907.757-1.497%201.093.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.302%200-14.14-2.08-14.14-4.811%200-.463.17-.925.506-1.345a10.73%2010.73%200%200%201-1.475-1.093Z'/%3e%3c/svg%3e",OP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M35.3993%2026.4544C34.2871%2028.3855%2027.8314%2032.9425%2020%2032.9425C12.1686%2032.9425%205.71288%2028.3855%204.60075%2026.4544C4.5427%2026.3532%204.50826%2026.2401%204.5%2026.1237V22.418C4.51199%2022.3209%204.53496%2022.2256%204.56846%2022.1338C5.04896%2020.9261%206.30833%2019.1733%207.93325%2018.7031C8.14896%2018.149%208.468%2017.3404%208.76508%2016.7437C8.71727%2016.2776%208.69485%2015.8094%208.69792%2015.3409C8.69792%2013.6217%209.06217%2012.113%2010.1601%2010.9906C10.6729%2010.4662%2011.3097%2010.0644%2012.064%209.76091C13.871%208.29357%2016.4453%207.05745%2019.9716%207.05745C23.4978%207.05745%2026.129%208.29357%2027.936%209.76091C28.6903%2010.0644%2029.3271%2010.4662%2029.8399%2010.9906C30.9378%2012.113%2031.3021%2013.6217%2031.3021%2015.3409C31.3021%2015.8162%2031.284%2016.2877%2031.2349%2016.7437C31.532%2017.3404%2031.851%2018.149%2032.0667%2018.7031C33.6917%2019.1733%2034.951%2020.9261%2035.4315%2022.1338C35.4677%2022.2248%2035.4908%2022.3205%2035.5%2022.418V26.1237C35.4917%2026.2401%2035.4573%2026.3532%2035.3993%2026.4544ZM20.2222%2018.7147H19.7778C19.6422%2018.945%2019.4889%2019.1644%2019.3193%2019.3709C18.3247%2020.5941%2016.8419%2021.2981%2014.7881%2021.2981C12.56%2021.2981%2010.9273%2020.8344%209.90304%2019.6719C9.86495%2019.6283%209.82833%2019.5835%209.79325%2019.5375L9.66667%2019.6719V28.1775C11.5202%2029.1837%2015.4972%2030.992%2020%2030.992C24.5028%2030.992%2028.4798%2029.1837%2030.3333%2028.1775V19.6719L30.2067%2019.5375C30.2067%2019.5375%2030.1641%2019.5957%2030.097%2019.6719C29.0727%2020.8344%2027.44%2021.2981%2025.2119%2021.2981C23.1581%2021.2981%2021.6753%2020.5941%2020.6807%2019.3709C20.5111%2019.1644%2020.3578%2018.945%2020.2222%2018.7147ZM23.2292%2022.9127C23.9383%2022.9127%2024.5208%2023.4952%2024.5208%2024.2043V26.7877C24.5208%2027.4968%2023.9383%2028.0793%2023.2292%2028.0793C22.52%2028.0793%2021.9375%2027.4968%2021.9375%2026.7877V24.2043C21.9375%2023.4952%2022.52%2022.9127%2023.2292%2022.9127ZM16.7708%2022.9127C17.48%2022.9127%2018.0625%2023.4952%2018.0625%2024.2043V26.7877C18.0625%2027.4968%2017.48%2028.0793%2016.7708%2028.0793C16.0617%2028.0793%2015.4792%2027.4968%2015.4792%2026.7877V24.2043C15.4792%2023.4952%2016.0617%2022.9127%2016.7708%2022.9127ZM21.0501%2014.9237C21.2258%2016.289%2021.5707%2017.3947%2022.1842%2018.149C22.7551%2018.8517%2023.649%2019.3606%2025.2119%2019.3606C27.2437%2019.3606%2028.1724%2018.9253%2028.6438%2018.3905C29.1398%2017.8287%2029.3646%2016.9051%2029.3646%2015.3409C29.3646%2013.8684%2029.0507%2012.9552%2028.454%2012.3455C27.8378%2011.7152%2026.7502%2011.2321%2024.8063%2011.0216C22.8856%2010.8136%2021.975%2011.1998%2021.5345%2011.7049C21.187%2012.1014%2020.97%2012.7485%2020.9688%2013.7431V13.7702C20.9688%2014.1121%2020.9959%2014.4966%2021.0501%2014.9237ZM18.9499%2014.9237C19.0041%2014.4966%2019.0312%2014.1117%2019.0312%2013.7689V13.7431C19.03%2012.7485%2018.813%2012.1014%2018.4655%2011.7049C18.025%2011.1998%2017.1144%2010.8136%2015.1937%2011.0216C13.2498%2011.2321%2012.1622%2011.7152%2011.546%2012.3455C10.9493%2012.9552%2010.6354%2013.8684%2010.6354%2015.3409C10.6354%2016.9051%2010.8615%2017.8287%2011.3562%2018.3905C11.8276%2018.9253%2012.7563%2019.3606%2014.7881%2019.3606C16.351%2019.3606%2017.2449%2018.8517%2017.8158%2018.149C18.4293%2017.3947%2018.7742%2016.289%2018.9499%2014.9237Z'%20fill='currentColor'/%3e%3c/svg%3e",HP="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!--%20Uploaded%20to:%20SVG%20Repo,%20www.svgrepo.com,%20Generator:%20SVG%20Repo%20Mixer%20Tools%20--%3e%3csvg%20fill='%23000000'%20width='800px'%20height='800px'%20viewBox='0%200%2024%2024'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.702%202.29c-2.494-1.554-5.778-1.187-8.706.654C9.076%201.104%205.79.736%203.3%202.29c-3.941%202.463-4.42%208.806-1.07%2014.167%202.47%203.954%206.333%206.269%209.77%206.226%203.439.043%207.301-2.273%209.771-6.226%203.347-5.361%202.872-11.704-1.069-14.167zM4.042%2015.328a12.838%2012.838%200%200%201-1.546-3.541%2010.12%2010.12%200%200%201-.336-3.338c.15-1.98.956-3.524%202.27-4.345%201.315-.822%203.052-.87%204.903-.137.281.113.556.24.825.382A15.11%2015.11%200%200%200%207.5%207.54c-2.035%203.255-2.655%206.878-1.945%209.765a13.247%2013.247%200%200%201-1.514-1.98zm17.465-3.541a12.866%2012.866%200%200%201-1.547%203.54%2013.25%2013.25%200%200%201-1.513%201.984c.635-2.589.203-5.76-1.353-8.734a.39.39%200%200%200-.563-.153l-4.852%203.032a.397.397%200%200%200-.126.546l.712%201.139a.395.395%200%200%200%20.547.126l3.145-1.965c.101.306.203.606.28.916.296%201.086.41%202.214.335%203.337-.15%201.982-.956%203.525-2.27%204.347a4.437%204.437%200%200%201-2.25.65h-.101a4.432%204.432%200%200%201-2.25-.65c-1.314-.822-2.121-2.365-2.27-4.347a10.153%2010.153%200%200%201%20.335-3.337%2013.212%2013.212%200%200%201%204.05-6.482%2010.148%2010.148%200%200%201%202.849-1.765c1.845-.733%203.586-.685%204.9.137%201.316.822%202.122%202.365%202.271%204.345a10.146%2010.146%200%200%201-.33%203.334z'/%3e%3c/svg%3e",FP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37%2020.034C27.8809%2020.5837%2020.5808%2027.8809%2020.0326%2037H19.966C19.4163%2027.8809%2012.1177%2020.5837%203%2020.034V19.9674C12.1191%2019.4163%2019.4163%2012.1191%2019.966%203H20.0326C20.5822%2012.1191%2027.8809%2019.4163%2037%2019.9674V20.034Z'%20fill='currentColor'/%3e%3c/svg%3e",BP="/assets/kimi-for-coding-eVEHug_h.svg",VP="/assets/llmapi-detailed-Pup_107f.svg",$P="data:image/svg+xml,%3csvg%20width='72'%20height='72'%20viewBox='0%200%2072%2072'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20fill='white'%20stroke='black'%20stroke-width='3'%20stroke-linejoin='round'%3e%3cpath%20d='M12%2040L24%2034L36%2040V52L24%2059L12%2052V40Z'/%3e%3cpath%20d='M36%2040L48%2034L60%2040V52L48%2059L36%2052V40Z'/%3e%3c/g%3e%3cg%20stroke='black'%20stroke-width='3'%20stroke-linecap='round'%20stroke-linejoin='round'%3e%3cpath%20d='M12%2040L24%2046L36%2040M24%2046V59'/%3e%3cpath%20d='M36%2040L48%2046L60%2040M48%2046V59'/%3e%3c/g%3e%3ccircle%20cx='36'%20cy='25'%20r='16'%20fill='white'%20stroke='black'%20stroke-width='3'/%3e%3crect%20x='27'%20y='22'%20width='7'%20height='9'%20rx='1.5'%20fill='black'/%3e%3crect%20x='29.5'%20y='25'%20width='2'%20height='6'%20fill='white'/%3e%3crect%20x='38'%20y='22'%20width='7'%20height='9'%20rx='1.5'%20fill='black'/%3e%3crect%20x='40.5'%20y='25'%20width='2'%20height='6'%20fill='white'/%3e%3c/svg%3e",zP="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eLM%20Studio%3c/title%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h14.107a1.273%201.273%200%20100-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H22.04a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h14.106a1.274%201.274%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H15.38a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h14.106a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h9.698a1.273%201.273%200%20100-2.547h-9.698z'%20fill-opacity='.3'%3e%3c/path%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h10.287a1.274%201.274%200%20000-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H18.22a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H11.56a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h5.78a1.273%201.273%200%20100-2.547h-5.78z'%3e%3c/path%3e%3c/svg%3e",UP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",qP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",WP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.7,5.25l2.14-1.53,10.49,13.29-16.23,19.43-2.65,3L0.42,16.83l6.87-8.64,5.78,2.21,1.79-4.46L23.3,0.1l3.42,5.15ZM31.13,13.98L22.91,1.78l-7.1,4.95-5.45,13.53,20.77-6.28ZM36.74,15.57l-8.03-10.1-0.14-0.1-1.14,0.89,5.03,7.58,4.28,1.73ZM9.06,20.35l3.53-8.84-4.89-1.92-5.62,7.1,6.98,3.66ZM37.62,17.19l-5.3-2.14-9.22,19.52,14.52-17.38ZM30.95,15.24l-20.63,6.22,10.1,15.93,10.53-22.15ZM15.79,32.41l-6.86-10.82c-1.61-0.84-3.2-1.73-4.81-2.57-0.1-0.05-0.21-0.12-0.32-0.13l11.99,13.52Z'%20fill='currentColor'/%3e%3c/svg%3e",KP="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOllama%3c/title%3e%3cpath%20d='M7.905%201.09c.216.085.411.225.588.41.295.306.544.744.734%201.263.191.522.315%201.1.362%201.68a5.054%205.054%200%20012.049-.636l.051-.004c.87-.07%201.73.087%202.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67%201.67%200%2001.589-.41c.257-.1.53-.118.796-.042.401.114.745.368%201.016.737.248.337.434.769.561%201.287.23.934.27%202.163.115%203.645l.053.04.026.019c.757.576%201.284%201.397%201.563%202.35.435%201.487.216%203.155-.534%204.088l-.018.021.002.003c.417.762.67%201.567.724%202.4l.002.03c.064%201.065-.2%202.137-.814%203.19l-.007.01.01.024c.472%201.157.62%202.322.438%203.486l-.006.039a.651.651%200%2001-.747.536.648.648%200%2001-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643%200%2001.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644%200%2001.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229%204.229%200%2000-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653%200%2001-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288%203.288%200%2000-1.772-.332c-1.245.099-2.343.801-2.67%201.686a.652.652%200%2001-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066%201.588a4.07%204.07%200%2000-.068%201.886c.112.558.331%201.02.582%201.269l.008.007c.212.207.257.53.109.785-.36.622-.629%201.549-.673%202.44-.05%201.018.186%201.902.719%202.536l.016.019a.643.643%200%2001.095.69c-.576%201.236-.753%202.252-.562%203.052a.652.652%200%2001-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339%204.339%200%2001-.598-1.309l-.005-.019a5.764%205.764%200%2001-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352%205.352%200%2001.093-2.49c.262-.915.777-1.701%201.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622%201.015-.737.266-.076.54-.059.797.042zm4.116%209.09c.936%200%201.8.313%202.446.855.63.527%201.005%201.235%201.005%201.94%200%20.888-.406%201.58-1.133%202.022-.62.375-1.451.557-2.403.557-1.009%200-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845%200-.707.398-1.417%201.056-1.946.668-.537%201.55-.849%202.485-.849zm0%20.896a3.07%203.07%200%2000-1.916.65c-.461.37-.722.835-.722%201.25%200%20.428.21.829.61%201.134.455.347%201.124.548%201.943.548.799%200%201.473-.147%201.932-.426.463-.28.7-.686.7-1.257%200-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662%201.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375%200%2001-.376.373.375.375%200%2001-.376-.373v-.46l-.271-.218a.347.347%200%2001-.052-.49.353.353%200%2001.494-.051l.215.172.22-.174a.353.353%200%2001.49.051zm-5.04-1.919c.478%200%20.867.39.867.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zm8.706%200c.48%200%20.868.39.868.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zM7.44%202.3l-.003.002a.659.659%200%2000-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216%201.631-.124%202.782.43-.128.899-.208%201.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628%200%2000-.107-.09L7.44%202.3zm9.174.04l-.002.001a.628.628%200%2000-.107.09c-.156.163-.32.45-.453.814-.29.794-.387%201.776-.23%202.572l.058.097.008.014h.03a5.184%205.184%200%20011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659%200%2000-.285-.239h-.004z'%3e%3c/path%3e%3c/svg%3e",GP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M32.8377%2017.282C33.2127%2016.25%2033.3072%2015.218%2033.2127%2014.1875C33.1197%2013.1571%2032.7447%2012.1251%2032.2752%2011.1876C31.4322%209.78209%2030.2127%208.6571%2028.8072%208.0001C27.3072%207.34461%2025.7127%207.15711%2024.1197%207.53211C23.3698%206.78212%2022.5253%206.12512%2021.5878%205.65713C20.6503%205.18913%2019.5253%205.00013%2018.4948%205.00013C16.8851%204.99074%2015.3125%205.48246%2013.9948%206.40712C12.6824%207.34311%2011.7449%208.6571%2011.2754%2010.1571C10.1504%2010.4376%209.21289%2010.9071%208.27539%2011.4696C7.4324%2012.1251%206.77541%2012.9696%206.21291%2013.8126C5.36992%2015.2195%205.08792%2016.8125%205.27542%2018.407C5.46399%2019.9968%206.11605%2021.496%207.1504%2022.718C6.79608%2023.7086%206.66795%2024.7659%206.77541%2025.8124C6.86991%2026.8444%207.2449%2027.8749%207.7129%2028.8124C8.55739%2030.2194%209.77538%2031.3444%2011.1824%2031.9999C12.6824%2032.6569%2014.2753%2032.8444%2015.8698%2032.4694C16.6198%2033.2194%2017.4628%2033.8749%2018.4003%2034.3444C19.3378%2034.8139%2020.4628%2034.9999%2021.4948%2034.9999C23.1043%2035.0097%2024.6769%2034.5185%2025.9947%2033.5944C27.3072%2032.6569%2028.2447%2031.3444%2028.7127%2029.8444C29.7719%2029.6432%2030.7682%2029.1934%2031.6197%2028.5319C32.4627%2027.8749%2033.2127%2027.1249%2033.6822%2026.1874C34.5251%2024.7819%2034.8071%2023.1875%2034.6196%2021.5945C34.4322%2020%2033.8697%2018.5015%2032.8377%2017.282ZM21.5878%2033.0304C20.0878%2033.0304%2018.9628%2032.5609%2017.9323%2031.7179C17.9323%2031.7179%2018.0253%2031.6234%2018.1198%2031.6234L24.1197%2028.1554C24.2862%2028.0803%2024.4196%2027.9469%2024.4947%2027.7804C24.5698%2027.636%2024.6021%2027.4731%2024.5877%2027.3109V18.875L27.1197%2020.375V27.3124C27.1455%2028.0547%2027.0215%2028.7945%2026.755%2029.4878C26.4885%2030.181%2026.085%2030.8134%2025.5687%2031.3473C25.0523%2031.8811%2024.4337%2032.3054%2023.7497%2032.5949C23.0658%2032.8843%2022.3305%2033.0314%2021.5878%2033.0304ZM9.49488%2027.8749C8.83789%2026.7499%208.55739%2025.4374%208.83789%2024.125C8.83789%2024.125%208.93239%2024.2195%209.02539%2024.2195L15.0253%2027.6874C15.1693%2027.7638%2015.3325%2027.7966%2015.4948%2027.7819C15.6823%2027.7819%2015.8698%2027.7819%2015.9628%2027.6874L23.2753%2023.4695V26.3749L17.1823%2029.9374C16.5506%2030.3042%2015.8527%2030.5427%2015.1287%2030.6393C14.4046%2030.7358%2013.6686%2030.6884%2012.9629%2030.4999C11.4629%2030.1249%2010.2449%2029.1874%209.49488%2027.8749ZM7.9004%2014.8445C8.56239%2013.7234%209.58826%2012.8627%2010.8074%2012.4056V19.532C10.8074%2019.718%2010.8074%2019.907%2010.9004%2020C10.9755%2020.1665%2011.1089%2020.2998%2011.2754%2020.375L18.5878%2024.5944L16.0573%2026.0944L10.0574%2022.625C9.41842%2022.2639%208.85742%2021.7797%208.40684%2021.2004C7.95627%2020.6211%207.62506%2019.9582%207.4324%2019.25C7.05741%2017.8445%207.1504%2016.157%207.9004%2014.8445ZM28.6197%2019.625L21.3073%2015.407L23.8377%2013.9071L29.8377%2017.375C30.7752%2017.9375%2031.5252%2018.6875%2031.9947%2019.625C32.4642%2020.5625%2032.7447%2021.5945%2032.6502%2022.7195C32.5603%2023.7755%2032.1699%2024.7837%2031.5252%2025.6249C30.8697%2026.4694%2030.0252%2027.1249%2028.9947%2027.4999V20.375C28.9947%2020.1875%2028.9947%2020%2028.9002%2019.907C28.9002%2019.907%2028.8072%2019.718%2028.6197%2019.625ZM31.1502%2015.875C31.1502%2015.875%2031.0572%2015.782%2030.9627%2015.782L24.9627%2012.3126C24.7752%2012.2196%2024.6822%2012.2196%2024.4947%2012.2196C24.3072%2012.2196%2024.1197%2012.2196%2024.0252%2012.3126L16.7128%2016.532V13.6251L22.8073%2010.0626C23.7448%209.50009%2024.7752%209.31259%2025.9002%209.31259C26.9322%209.31259%2027.9627%209.68759%2028.9002%2010.3446C29.7447%2011.0001%2030.4947%2011.8446%2030.8697%2012.7821C31.2447%2013.7196%2031.3377%2014.8445%2031.1502%2015.875ZM15.4003%2021.125L12.8699%2019.625V12.5946C12.8699%2011.5626%2013.1503%2010.4376%2013.7128%209.59459C14.2753%208.6571%2015.1198%208.0001%2016.0573%207.53211C17.0127%207.05249%2018.0956%206.88812%2019.1503%207.06261C20.1823%207.15711%2021.2128%207.62511%2022.0573%208.2821C22.0573%208.2821%2021.9628%208.3751%2021.8698%208.3751L15.8698%2011.8446C15.7033%2011.9197%2015.57%2012.0531%2015.4948%2012.2196C15.4003%2012.4071%2015.4003%2012.5001%2015.4003%2012.6876V21.125ZM16.7128%2018.125L19.9948%2016.25L23.2753%2018.125V21.875L19.9948%2023.75L16.7128%2021.875V18.125Z'%20fill='currentColor'/%3e%3c/svg%3e",ZP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20fill='currentColor'/%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.6%207.43108L16.0037%2010.6622V4.20001L21.6%207.43108Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20fill='currentColor'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.4909%2016.7109L15.8945%2013.4798V19.942L21.4909%2016.7109Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3c/svg%3e",YP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cimage%20width='24'%20height='24'%20xlink:href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF0AAABcCAYAAAAMLblmAAAACXBIWXMAAAAAAAAAAQCEeRdzAAAHhklEQVR4nO1d21HjSBRtjJhvMhgtxlX8DRsBJgIggjERwESAiWAgAjwRYCJAGwHMH1U8VhvBst+89hxzRRkwuG+rJet1qlwSM1KrdXR1+nb37as5UzCEYbi4sLAQPj4+rs7NzX17enpaxI/7i8khs6xfWuA+1oNZV4IkB0Gwit0NEN1FpVaxHf0fyB5t8W8zrKF/zIT0hGiQuoc/uR1ZcdXI/Qi5kk6yW63WDsjdTYiuI3IhfXl5uQuSd7C7mcf1io5MSYdlh/Pz83sgvJfldcqGTEgflxH8WVsZ+QjeSRcpOTIld+2yhFfSl5aWfoLwXZ9lVhFeSKd2Q06O6WP7KG8CbvlD+TEeavz2P/HvIbfsRJkSyFlq0kVOjo3HmwWJEcr8jd0IvdPzi4uL2Pbcsc7WqMOFcrq+6uULqUiHnOzgpg58VESI/vXw8DCM4/jWtRw5N5LfqG7tdpuuKn/fPVQ1NZxJB+F7IKqf8vqUjMP7+/uDNERPw/X19RCbId6CPlzYLvbZEw6zut40OJHugfBcyH4LXCvGZsAfrL9nZkS+mnQPhA+h0z80Op0FYP0DWP4Q+r8rY0C5QUU6NTwF4THO3b66uoocz/cOecv6IH8A2Tk1OVm9Nenipbg2modoIPt5SokGIjt/4B77eVi9Fen0w6WXqQW1ex/W7cXDyRqoZ7/T6QwfHx/pAodZXceKdMdXL0aHaevy8vJcXasZgvWFja1nKTdTSWfD6XDxGI3l+qwbS1dQbkh8Vr3sT0kXHe8ryyw14QnGiD/1TfynpDvoeCUIT8CGH8Rv+ZaaD0l3kJVbanhVCE+QWDyIPzOexpcmkk5vReuP00spW6NpCxIPqd3Cm3/qo7yJpHOKTVnOYVncQlewU9dutw+xu5O2rHek08qx6SnKiNGlrsXEBe8TsruWtmF9R7rWytlwpqlA2QB+ttF5OktTxivSHax8ULWGcxrYbqWVmVekK62c7uG+64XLDI4jgStOiDh5M2/lxToYCLr2q25WnoD+O7yZQ9fBsRfSZVDf9snFQRAMXC5YFXACBtZOiVFb+7ila+YPo7paeYI01j4inTPo2HRtT6qrlr+Fq7WPSJfJWitw1r7uVp6A1g5ZPjHKKINEXjZsT2CYhOYCVQeMcABO9KSzh5WsepgGSEukr1p1IcMDnIa0lpiAei7haFOB41TRVjWCSmICWYZidTDeiL9ca1VlgJdzjcRQXjSDN5G6RjWAhARaHx/g4ND24FarFTvUqfKQ8RhrXQ/wlL7aPqWqTlL4gIRxW6lGYLvKjY1oumpVGxLabUe6sZwHhbQUMjqrQLDmh6TbWvp/ztWpASAvt7YybU068K9zjeoBlaU38ABYeUN6kdGQ7glMjaLRdNVgTYMPYT/gZSxJT9ZqNpgMTVaPwNbV0QwX1BGanj0tPTZ2PanQvUq1QGh7IIcB/rE9eGVlJWzG0yfDdtyFCGSgxurgh4eHrnleh9lgDJ1O5yXvmA0oL9YDWcwg51KpqkPLS3B/f38+Pz9vdTDeiDWnWlUcUIsN1SSGhBHExqIh4AQ251SLuh50VtBm2kh6pJxYtYpCDYKgZyS7RIOXxXD6YCOj0HVcgDEyDekCbcwLMSKdOVag67Yr6bqNxDzDIZ5/hBHpouuRsYxnZOYIbPrai1UNmnDEcbyMMqKRPLFtEJjYEg8511wtBUW6+HS4jgNZiWHTKCzW3dolnj90OfeFdJEYBodaeTF1tnbRcucUJa8mMSAxQ8mJawNmGeWFf7hevKwQRQhdz39FukSgRsayQWVaV/ipJ0XKVpQ1XD2WcbybruNyc00Pi0kbUI8/6yIzkpwhFd6RrrV2IKyLzDjmvnmHiRPTWmunzOBBnV9fX1d2lYZj7puJmEi6Y/KBg06n87uKQaYpcphNxIchGA6rgheZcGxlZaUySXYIDnnklmRH/PZt7B4rygvv7u5Oq0K8JN/3nkDt02Aj5qiVDpNmJK0SxCeE5544jYDM7OL14oxRqCi31MRnnQ9+KumUGTSQW9BrvmaawXoSf0aJkqzOpYB8PCXTFLBWsYyypoZ+uLYF50M6hn/bv7m5KfzSdtwjZZQTNJmGGVoHkDILM3zV0CUBAZOwgfjNL1++FDKbneg37yuXtFiqqF3mogXxxpH4VcjN30WzevmKwE+TYwSbOlQ6DfEErV7Govf59riU4QPSw+Q9dPO+tlN8elrizbNVHYF8nr/PfAN5yY5Y9s4sP1DivCjAA/FEiN8RZIdkDLB/koWnQ6s2z1+C6ZkCxOKnWolB4jnQZfxoYo8/lMf9SPIQRIxA0wwbj39yByR/w3azaF+ETL38hZaJGz337Nt25fXfY8gfl4Dzo1KMpTfPod1vwaUnoSxcsF6GMit4WXOUw+cNFqf1Dsv0AVmvC71E56Pmg4Gfw/vqOpkvze2jHmVEZksaafXyKZu+Kcjny4qCTNeRitb35PNlfdOQP0Iui3cnkK8dKq4Ucl0xnZDPffYM4XF8F9ewUH501pjZMvXky4ncl3EQPoQ1zSq1sqIQuQHE44mSv6Xbviodnq9GOj/m+Y0o/VvxPy8IndI+RM9sAAAAAElFTkSuQmCC'/%3e%3c/svg%3e",XP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.50002L17.4088%2011.1913H5.81625L8.5375%207.50002H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.50002L16.58%2032.5H5L23.42%207.50002H35Z'%20fill='currentColor'/%3e%3c/svg%3e",JP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.5L17.4088%2011.1912H5.81625L8.5375%207.5H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.5L16.58%2032.5H5L23.42%207.5H35Z'%20fill='currentColor'/%3e%3c/svg%3e",QP=Object.assign({"../assets/provider-logos/anthropic.svg":LP,"../assets/provider-logos/bailian-coding-plan.svg":RP,"../assets/provider-logos/cursor.svg":PP,"../assets/provider-logos/evroc.svg":DP,"../assets/provider-logos/github-copilot.svg":OP,"../assets/provider-logos/gocode.svg":HP,"../assets/provider-logos/google.svg":FP,"../assets/provider-logos/kimi-for-coding.svg":BP,"../assets/provider-logos/llmapi-detailed.svg":VP,"../assets/provider-logos/llmapi.svg":$P,"../assets/provider-logos/lmstudio.svg":zP,"../assets/provider-logos/minimax-cn-coding-plan.svg":UP,"../assets/provider-logos/minimax-coding-plan.svg":qP,"../assets/provider-logos/nano-gpt.svg":WP,"../assets/provider-logos/ollama.svg":KP,"../assets/provider-logos/openai.svg":GP,"../assets/provider-logos/openrouter.svg":ZP,"../assets/provider-logos/wafer.ai.svg":YP,"../assets/provider-logos/zai-coding-plan.svg":XP,"../assets/provider-logos/zhipuai-coding-plan.svg":JP}),Hp=new Map,ih=new Map([["codex","openai"],["openai-codex","openai"],["openai_codex","openai"],["openai.codex","openai"],["chatgpt","openai"],["claude","anthropic"],["gemini","google"],["evroc-ai","evroc"],["evrocai","evroc"],["ollama-cloud","ollama"],["wafer-ai","wafer.ai"],["wafer","wafer.ai"]]),eD=e=>(e??"").toLowerCase().trim().replace(/^models\./,"").replace(/^provider\./,"").replace(/\s+/g,"-"),tD=e=>{const t=eD(e);if(!t)return[];const n=t.replace(/[^a-z0-9_\-./:]/g,""),r=n.split(/[/:]/)[0]||n,s=r.split(/[-_.]/)[0]||r,o=[ih.get(n),ih.get(r),ih.get(s),t.includes("codex")?"openai":void 0,n,r,s].filter(i=>!!(i&&i.length>0));return[...new Set(o)]};for(const[e,t]of Object.entries(QP)){const n=e.match(/provider-logos\/([^/]+)\.svg$/i);n?.[1]&&t&&Hp.set(n[1].toLowerCase(),t)}function M1(e){const t=tD(e),n=t.find(d=>Hp.has(d))??null,r=t[0]??null,s=!!n,o=n?Hp.get(n)??null:null,[i,a]=H.useState(s?"local":"remote");H.useEffect(()=>{a(s?"local":"remote")},[s,n,r]);const l=H.useCallback(()=>{a(d=>d==="local"&&s?"remote":"none")},[s]);return!n&&!r?{src:null,onError:l,hasLogo:!1}:i==="local"&&o?{src:o,onError:l,hasLogo:!0}:i==="remote"&&r?{src:`https://models.dev/logos/${r}.svg`,onError:l,hasLogo:!0}:{src:null,onError:l,hasLogo:!1}}const Wo=({providerId:e,alt:t,className:n,onError:r})=>{const{src:s,onError:o,hasLogo:i}=M1(e),a=p.useCallback(()=>{o(),r?.()},[o,r]);return!i||!s?null:c.jsx("img",{src:s,alt:t||`${e} logo`,className:R("dark:invert object-contain",n),loading:"eager",decoding:"async",fetchPriority:"high",draggable:!1,onError:a})},Py=Et()(Gd(e=>({collapsedSections:{},toggleSection:t=>e(n=>{const r={...n.collapsedSections};return r[t]?delete r[t]:r[t]=!0,{collapsedSections:r}})}),{name:"model-picker-collapsed-sections",version:1})),Dy=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},I1=(e,t,n)=>{const r=Dy(t.limit,"context"),s=Dy(t.limit,"output"),o=r??n?.limit?.context,i=s??n?.limit?.output;return o===void 0&&i===void 0?n:{...n??{id:typeof t.id=="string"?t.id:"",providerId:e,name:typeof t.name=="string"?t.name:void 0},limit:{...n?.limit,...o!==void 0?{context:o}:{},...i!==void 0?{output:i}:{}}}},Es=e=>typeof e=="string"?e.trim():"",Oy=(e,t)=>!t||t<=0||e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`,nD={ai:"AI",api:"API",ernie:"ERNIE",glm:"GLM",gpt:"GPT",it:"IT",lfm:"LFM",lm:"LM",oss:"OSS",pdf:"PDF",rp:"RP",slerp:"SLERP",tars:"TARS",ui:"UI",vl:"VL",vlm:"VLM",aion:"Aion",anthropic:"Anthropic",chatgpt:"ChatGPT",claude:"Claude",codex:"Codex",codestral:"Codestral",command:"Command",deepseek:"DeepSeek",gemini:"Gemini",gemma:"Gemma",grok:"Grok",hunyuan:"Hunyuan",kimi:"Kimi",llama:"Llama",minimax:"MiniMax",mistral:"Mistral",mixtral:"Mixtral",nemotron:"Nemotron",openai:"OpenAI",qwen:"Qwen",rekaai:"RekaAI"},Hy=e=>e?e[0].toUpperCase()+e.slice(1).toLowerCase():"",rD=e=>{const t=e.startsWith("~")?e.slice(1):e,n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t},sD=e=>{const t=e.lastIndexOf(":");return t<=0||t>=e.length-1?{base:e,suffix:""}:{base:e.slice(0,t),suffix:e.slice(t+1)}},oD=e=>{const t=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").split(/[-_\s]+/).map(r=>r.trim()).filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){const s=t[r],o=t[r+1],i=t[r+2];if(/^(19|20)\d{2}$/.test(s)&&/^\d{2}$/.test(o??"")&&/^\d{2}$/.test(i??"")){n.push(`${s}-${o}-${i}`),r+=2;continue}if(/^\d$/.test(s)&&/^\d$/.test(o??"")){n.push(`${s}.${o}`),r+=1;continue}n.push(s)}return n},iD=e=>{const t=e.toLowerCase(),n=nD[t];if(n)return n;const r=t.match(/^qwen(\d(?:\.\d+)?)$/);return r?`Qwen${r[1]}`:/^o\d/.test(t)?t:/^v\d/.test(t)?`V${e.slice(1).toUpperCase()}`:/^\d+[on]$/.test(t)?t:/^[a-z]\d+[a-z]?$/.test(t)?t.toUpperCase():/^\d+(?:x\d+)?[a-z]+$/.test(t)?t.replace(/[a-z]+$/i,s=>s.toUpperCase()):/^\d+(?:\.\d+)?[a-z]$/.test(t)?t.replace(/[a-z]$/i,s=>s.toUpperCase()):/^[a-z]+\d+(?:\.\d+)?[a-z]*$/.test(t)?Hy(t).replace(/([a-z])(\d)/i,"$1$2"):Hy(e)},aD=e=>{const t=[...e];return t[0]==="GPT"&&t[1]&&/^(?:\d|\d+[a-z]|OSS$)/i.test(t[1])&&t.splice(0,2,`GPT-${t[1]}`),t[0]==="GLM"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`GLM-${t[1]}`),t[0]==="LFM"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`LFM${t[1]}`),t[0]==="Qwen"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`Qwen${t[1]}`),t},cD=e=>{const t=Es(e).toLowerCase();return t?t==="free"||t==="thinking"?t:q3(t):""},q3=e=>{const t=Es(e);if(!t)return"";const{base:n,suffix:r}=sD(rD(t)),s=aD(oD(n).map(iD));if(s.length>=2){const l=s[s.length-1],d=s[s.length-2];l==="Reasoning"&&d==="Non"&&s.splice(s.length-2,2,"(Non-Reasoning)")}const o=s[s.length-1];/^(19|20)\d{2}-\d{2}-\d{2}$/.test(o??"")&&(s[s.length-1]=`(${o})`);const i=s.join(" ").replace(/\s+\(/g," (").trim(),a=cD(r);return a?`${i} (${a})`:i},E1=(e,t,n={})=>{const r=Es(e?.name);if(r)return Oy(r,n.maxLength);const s=Es(e?.id)||Es(t);return s?Oy(q3(s),n.maxLength):n.fallbackLabel??""},lD=(e,t)=>{const n=e?.models;if(!(!n||!t))return Array.isArray(n)?n.find(r=>Es(r.id)===t):n[t]},_1=(e,t,n={})=>{const r=Es(t),s=lD(e,r);return E1(s,r,n)},dD=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),uD=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),Bl=e=>E1(e,void 0,{maxLength:40}),fD=e=>{if(typeof e!="number"||Number.isNaN(e))return"";if(e===0)return"0";const t=dD(e);return t.endsWith(".0")?t.slice(0,-2):t},Fy=e=>typeof e!="number"||!Number.isFinite(e)?"—":uD(e),hD=e=>e?!!(e.tool_call||e.reasoning||e.cost?.input!==void 0||e.cost?.output!==void 0||(e.modalities?.input?.length??0)>0||(e.modalities?.output?.length??0)>0):!1,pD=({metadata:e,active:t,labels:n,children:r})=>{const[s,o]=p.useState(!1);if(p.useEffect(()=>{if(!t){o(!1);return}const d=window.setTimeout(()=>o(!0),450);return()=>window.clearTimeout(d)},[t]),!hD(e))return r;const i=e?.modalities?.input??[],a=e?.modalities?.output??[],l=[e?.tool_call?n.capabilityToolCalling:null,e?.reasoning?n.capabilityReasoning:null].filter(Boolean);return c.jsxs(wt,{delayDuration:0,open:t&&s,onOpenChange:()=>{},children:[c.jsx(St,{asChild:!0,children:r}),t&&s?c.jsxs(Ct,{side:"right",align:"center",sideOffset:8,className:"z-[999] p-2 typography-micro space-y-1.5 shadow-md border pointer-events-none",children:[l.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.capabilities||"Capabilities",": "]}),c.jsx("span",{className:"font-medium",children:l.join(", ")})]}):null,i.length>0||a.length>0?c.jsxs("div",{className:"space-y-0.5",children:[i.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.input||"Input",": "]}),c.jsx("span",{className:"font-medium",children:i.join(", ")})]}):null,a.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.output||"Output",": "]}),c.jsx("span",{className:"font-medium",children:a.join(", ")})]}):null]}):null,e?.cost?.input!==void 0||e?.cost?.output!==void 0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.costPerMillion||"Cost / 1M tokens",": "]}),c.jsxs("span",{className:"font-medium",children:[Fy(e?.cost?.input)," / ",Fy(e?.cost?.output)]})]}):null]}):null]})},mD=p.memo(({store:e,index:t,children:n})=>{const[r,s]=p.useState(()=>e.getSnapshot()===t);return p.useEffect(()=>{const o=()=>s(e.getSnapshot()===t);return o(),e.subscribeIndex(t,o)},[t,e]),c.jsx(c.Fragment,{children:n(r)})}),gD=({id:e,disabled:t=!1,children:n})=>{const{attributes:r,listeners:s,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:l,isDragging:d}=Cm({id:e,disabled:t});return c.jsx("div",{ref:o,style:{transform:km.Transform.toString(a),transition:l},className:R(d&&"opacity-60"),children:n({attributes:r,listeners:s,setActivatorNodeRef:i,isDragging:d})})},yD=({entry:e,keyPrefix:t,showProviderLogo:n,rowIndex:r,dragHandleProps:s,selectionStore:o,modelsMetadata:i,selectedModel:a,disabled:l=!1,rowClassName:d,renderVersion:f,tooltipsEnabled:u=!0,labels:h,selectionCount:m,isFavorite:g,onToggleFavorite:x,onSelect:b,selectIndex:S,itemRefs:y,lastMousePositionRef:v,keyboardOwnsSelectionRef:C,reorderFavoriteAriaLabel:w,reorderFavoriteTitle:I,renderRowEnd:E})=>{const T=I1(e.providerID,e.model,i.get(`${e.providerID}/${e.modelID}`)),A=fD(T?.limit?.context),j=m?.(e)??0,k=a?.providerID===e.providerID&&a.modelID===e.modelID,_=g?.(e)??!1,M=L=>{const O={x:L.clientX,y:L.clientY},N=v.current,D=!N||N.x!==O.x||N.y!==O.y;v.current=O,!(C.current&&!N)&&(C.current&&!D||(C.current&&D&&(C.current=!1),S(r)))};return c.jsx(mD,{store:o,index:r,renderVersion:f,children:L=>{const O=c.jsxs("div",{ref:N=>{y.current[r]=N},role:"option","aria-selected":k,"aria-disabled":l||void 0,tabIndex:-1,onClick:()=>{l||b(e)},onKeyDown:N=>{l||(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),b(e))},onMouseEnter:M,onMouseMove:M,className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!l&&(L?"bg-interactive-selection":"hover:bg-interactive-hover/50"),l&&"cursor-not-allowed opacity-60",d),children:[c.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[s?c.jsx("button",{type:"button",ref:s.setActivatorNodeRef,...s.attributes,...s.listeners,disabled:l,onClick:N=>{N.preventDefault(),N.stopPropagation()},className:"model-favorite-drag-handle flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground hover:text-foreground disabled:pointer-events-none","aria-label":w,title:I,children:c.jsx(V,{name:"draggable",className:"size-3.5"})}):null,n?c.jsx(Wo,{providerId:e.providerID,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsx("span",{className:"font-medium truncate",children:Bl(e.model)}),A?c.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:A}):null]}),j>0?c.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["x",j]}):null,E?.(e,{isHighlighted:L,isSelected:k}),k?c.jsx(V,{name:"check",className:"h-4 w-4 text-primary flex-shrink-0"}):null,x?c.jsx("button",{type:"button",disabled:l,onClick:N=>{N.preventDefault(),N.stopPropagation(),x(e)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-primary/80 flex-shrink-0 disabled:pointer-events-none",_?"text-primary":"text-muted-foreground"),"aria-label":_?h.unfavorite:h.favorite,title:_?h.unfavorite:h.favorite,children:c.jsx(V,{name:_?"star-fill":"star",className:"h-3.5 w-3.5"})}):null]});return c.jsx(pD,{metadata:T,active:u&&L,labels:h,children:O})}},`${t}-${e.providerID}-${e.modelID}`)},vD=(e=0)=>{let t=e;const n=new Set,r=new Map,s=o=>{const i=r.get(o);if(i)for(const a of i)a()};return{getSnapshot:()=>t,subscribe:o=>(n.add(o),()=>{n.delete(o)}),subscribeIndex:(o,i)=>{let a=r.get(o);return a||(a=new Set,r.set(o,a)),a.add(i),()=>{a?.delete(i),a&&a.size===0&&r.delete(o)}},set:o=>{if(t===o)return;const i=t;t=o,s(i),s(o);for(const a of n)a()}}},xD=48,bD=32,wD=24;function SD({providers:e,favoriteModels:t,recentModels:n,searchQuery:r,hiddenModels:s=[],allowedProviderIds:o,isModelAllowed:i,stickyHeaders:a=!0,scrollRef:l,collapsedSections:d}){const f=p.useRef(0),u=p.useMemo(()=>o?new Set(o):null,[o]),h=p.useMemo(()=>new Map(e.map(E=>[E.id,E])),[e]),m=p.useCallback((E,T)=>s.some(A=>A.providerID===E&&A.modelID===T),[s]),g=p.useCallback((E,T)=>{const A=r.trim().toLowerCase();return A?E.toLowerCase().includes(A)||T.toLowerCase().includes(A):!0},[r]),x=p.useMemo(()=>t.filter(({model:E,providerID:T,modelID:A})=>{if(u&&!u.has(T)||i&&!i(T,A)||m(T,A))return!1;const j=h.get(T)?.name||T;return g(Bl(E),j)}),[u,t,m,i,g,h]),b=p.useMemo(()=>n.filter(({model:E,providerID:T,modelID:A})=>{if(u&&!u.has(T)||i&&!i(T,A)||m(T,A))return!1;const j=h.get(T)?.name||T;return g(Bl(E),j)}),[u,m,i,g,h,n]),S=p.useMemo(()=>e.filter(E=>!u||u.has(E.id)).map(E=>{const A=(Array.isArray(E.models)?E.models:[]).filter(j=>{const k=typeof j.id=="string"?j.id:"";return!k||m(E.id,k)||i&&!i(E.id,k)?!1:g(Bl(j),E.name||E.id)});return{...E,models:A}}).filter(E=>E.models.length>0),[u,m,i,g,e]),y=p.useMemo(()=>[...x.length>0?["favorites"]:[],...b.length>0?["recent"]:[],...S.map(E=>`provider:${E.id}`)],[x.length,S,b.length]),v=p.useCallback(E=>{const A=E.scrollTop>1?Math.min(bD+E.scrollTop,xD):0;f.current=A,E.style.setProperty("--scroll-shadow-top-size",`${A}px`),E.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(A-8,0),wD)}px`)},[]),C=p.useCallback(E=>{E.target.closest("[data-overlay-scrollbar-thumb], [data-model-picker-sticky-header]")||E.clientY-E.currentTarget.getBoundingClientRect().top>=f.current||(E.preventDefault(),E.stopPropagation())},[]);p.useLayoutEffect(()=>{a&&l.current&&v(l.current)},[l,a,v,y]);const w=p.useMemo(()=>{const E=[];return d.has("favorites")||x.forEach(T=>E.push(T)),d.has("recent")||b.forEach(T=>E.push(T)),S.forEach(T=>{d.has(`provider:${T.id}`)||T.models.forEach(A=>E.push({model:A,providerID:T.id,modelID:A.id}))}),E},[d,x,S,b]),I=p.useMemo(()=>new Map(x.map(E=>[`${E.providerID}:${E.modelID}`,E])),[x]);return{allowedProviderSet:u,providerById:h,filteredFavorites:x,filteredRecents:b,filteredProviders:S,visibleSectionKeys:y,flatModelList:w,favoriteLookup:I,syncStickyFade:v,blockStickyFadeInteraction:C}}const By=32,CD=(e,t)=>{if(!t)return;if(!e){t.scrollIntoView({block:"nearest"});return}const n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),s=r.top-n.top+e.scrollTop,o=s+r.height,i=e.scrollTop,a=i+e.clientHeight,l=i+By,d=s<l?s-By:o>a?o-e.clientHeight:i,f=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop=Math.max(0,Math.min(d,f))},kD=({providers:e,favoriteModels:t,recentModels:n,modelsMetadata:r,searchQuery:s,onSearchQueryChange:o,onSelect:i,labels:a,selectedModel:l,hiddenModels:d=[],allowedProviderIds:f,isModelAllowed:u,includeNotSelected:h=!1,onSelectNone:m,selectionCount:g,disabled:x=!1,maxHeightClassName:b="max-h-[min(400px,calc(100dvh-12rem))] flex-1",maxHeightStyle:S,sectionHeaderClassName:y,rowClassName:v,stickyHeaders:C=!0,autoFocus:w=!0,onEscape:I,isFavorite:E,onToggleFavorite:T,renderRowEnd:A,onActiveKeyDown:j,onActiveEntryChange:k,onVariantKey:_,onReorderFavorite:M,reorderFavoriteAriaLabel:L,reorderFavoriteTitle:O,renderVersion:N,tooltipsEnabled:D=!0})=>{const W=p.useRef(null);W.current||(W.current=vD());const z=W.current,X=p.useRef([]),F=p.useRef(null),U=p.useRef(!1),P=p.useRef(null),q=Py(ge=>ge.collapsedSections),B=Py(ge=>ge.toggleSection),ee=p.useMemo(()=>new Set(Object.keys(q).filter(ge=>q[ge])),[q]),G=xm(wa(x8,{activationConstraint:{distance:8}})),{filteredFavorites:K,filteredRecents:se,filteredProviders:de,flatModelList:oe,favoriteLookup:ue,syncStickyFade:ye,blockStickyFadeInteraction:we}=SD({providers:e,favoriteModels:t,recentModels:n,searchQuery:s,hiddenModels:d,allowedProviderIds:f,isModelAllowed:u,stickyHeaders:C,scrollRef:F,collapsedSections:ee}),Me=oe.length>0,He=!!M&&s.trim().length===0&&K.length>1;p.useEffect(()=>{z.set(0)},[s,z]);const Ae=p.useCallback(ge=>{z.set(ge),k?.(oe[ge])},[oe,k,z]),Ge=p.useCallback(ge=>{const Ze=oe.length;if(Ze===0)return;U.current=!0,P.current=null;const ie=(z.getSnapshot()+ge+Ze)%Ze;z.set(ie),k?.(oe[ie]),requestAnimationFrame(()=>CD(F.current,X.current[ie]))},[oe,k,z]);p.useEffect(()=>{k?.(oe[z.getSnapshot()])},[oe,k,z]);const et=p.useCallback(ge=>{if(!ge.defaultPrevented){if(ge.stopPropagation(),ge.key==="ArrowLeft"||ge.key==="ArrowRight"){const Ze=oe[z.getSnapshot()];if(Ze&&_?.(ge,Ze))return}if(j?.(ge,oe[z.getSnapshot()]),!ge.defaultPrevented){if(ge.key==="ArrowDown"){ge.preventDefault(),Ge(1);return}if(ge.key==="ArrowUp"){ge.preventDefault(),Ge(-1);return}if(ge.key==="Enter"){ge.preventDefault();const Ze=oe[z.getSnapshot()];Ze&&!x&&i(Ze);return}ge.key==="Escape"&&(ge.preventDefault(),I?.())}}},[x,oe,Ge,j,I,i,_,z]),Xe=R("typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 px-2 py-1.5",C&&"sticky top-0 z-20",y);let te=0;const Q=(ge,Ze,Ve,ie,ke)=>c.jsx(yD,{entry:ge,keyPrefix:Ze,showProviderLogo:Ve,rowIndex:ie,dragHandleProps:ke,selectionStore:z,modelsMetadata:r,selectedModel:l,disabled:x,rowClassName:v,renderVersion:N,tooltipsEnabled:D,labels:a,selectionCount:g,isFavorite:E,onToggleFavorite:T,onSelect:i,selectIndex:Ae,itemRefs:X,lastMousePositionRef:P,keyboardOwnsSelectionRef:U,reorderFavoriteAriaLabel:L,reorderFavoriteTitle:O,renderRowEnd:A},`${Ze}-${ge.providerID}-${ge.modelID}`),me=ge=>{if(!M)return;const{active:Ze,over:Ve}=ge;if(!Ve||Ze.id===Ve.id)return;const ie=ue.get(String(Ze.id)),ke=ue.get(String(Ve.id));!ie||!ke||M(ie,ke)},Se=ge=>ee.has(ge),_e=ge=>B(ge),Fe=(ge,Ze,Ve)=>{const ie=Se(ge),ke=ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),_e(ge))};return c.jsxs("button",{type:"button","aria-expanded":!ie,"data-model-picker-sticky-header":C?"true":void 0,className:R(Xe,"w-full text-left"),onClick:()=>_e(ge),onKeyDown:ke,children:[Ze,c.jsx("span",{className:"min-w-0 truncate",children:Ve}),c.jsx("span",{className:"ml-auto flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",children:c.jsx(V,{name:ie?"arrow-right-s":"arrow-down-s",className:"size-4"})})]})},ht=()=>de.map(ge=>{const Ze=Se(`provider:${ge.id}`);return c.jsxs("div",{className:"relative overflow-hidden",children:[Fe(`provider:${ge.id}`,c.jsx(Wo,{providerId:ge.id,className:"h-3.5 w-3.5 flex-shrink-0"}),ge.name||ge.id),Ze?null:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:ge.models.map(Ve=>{const ie={model:Ve,providerID:ge.id,modelID:Ve.id},ke=te;return te+=1,Q(ie,ge.id,!1,ke)})})]},ge.id)});return c.jsxs("div",{className:"flex flex-col min-h-0",children:[c.jsx("div",{className:"p-2 border-b",children:c.jsx(Uo,{placeholder:a.searchPlaceholder,value:s,onChange:ge=>o(ge.target.value),onKeyDown:et,autoFocus:w,className:"h-8 typography-meta"})}),c.jsx("div",{className:"relative flex flex-col min-h-0",onMouseDown:we,onPointerDown:we,children:c.jsxs(Xn,{ref:F,className:R(b,"p-2 space-y-3 min-h-0"),style:S,onScroll:ge=>{C&&ye(ge.currentTarget)},children:[h&&m?c.jsx("div",{className:"pb-1 border-b mb-1",children:c.jsxs("button",{type:"button",disabled:x,onClick:m,className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!x&&"hover:bg-interactive-hover/50",x&&"cursor-not-allowed opacity-60",v),children:[c.jsx("span",{className:"font-medium text-muted-foreground",children:a.notSelected||"Not selected"}),l?null:c.jsx(V,{name:"check",className:"h-4 w-4 text-primary ml-auto flex-shrink-0"})]})}):null,K.length>0?c.jsxs("div",{className:"relative overflow-hidden",children:[Fe("favorites",c.jsx(V,{name:"star-fill",className:"h-3.5 w-3.5 text-primary flex-shrink-0"}),a.favorites),Se("favorites")?null:He?c.jsx(bm,{sensors:G,collisionDetection:wm,onDragEnd:me,children:c.jsx(Sm,{items:K.map(ge=>`${ge.providerID}:${ge.modelID}`),strategy:z5,children:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:K.map(ge=>{const Ze=`${ge.providerID}:${ge.modelID}`,Ve=te;return te+=1,c.jsx(gD,{id:Ze,disabled:x,children:ie=>Q(ge,"favorite",!0,Ve,ie)},`favorite-${Ze}`)})})})}):c.jsx("div",{className:"space-y-0.5 mt-0.5",children:K.map(ge=>{const Ze=te;return te+=1,Q(ge,"favorite",!0,Ze)})})]}):null,se.length>0?c.jsxs("div",{className:"relative overflow-hidden",children:[Fe("recent",c.jsx(V,{name:"history",className:"h-3.5 w-3.5 flex-shrink-0"}),a.recent),Se("recent")?null:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:se.map(ge=>{const Ze=te;return te+=1,Q(ge,"recent",!0,Ze)})})]}):null,ht(),Me?null:c.jsx("div",{className:"p-4 text-center typography-meta text-muted-foreground",children:a.noResults})]})})]})};function W3(){const e=qe();return H.useMemo(()=>({ensureSessionRenderable:async t=>{if(!t)return;if(e.getState().selectedSessionId!==t){await e.select(t);return}await e.ensureHydrated(t)},syncSession:async t=>{if(!t)return;e.getState().selectedSessionId!==t&&await e.select(t)}}),[e])}const MD=()=>{const e=We(a=>a.providers),t=re(a=>a.favoriteModels),n=re(a=>a.recentModels),r=re(a=>a.hiddenModels),s=p.useCallback((a,l)=>r.some(d=>d.providerID===a&&d.modelID===l),[r]),o=p.useMemo(()=>t.map(({providerID:a,modelID:l})=>{const d=e.find(h=>h.id===a);if(!d)return null;const u=(Array.isArray(d.models)?d.models:[]).find(h=>h.id===l);return!u||s(a,l)?null:{provider:d,model:u,providerID:a,modelID:l}}).filter(a=>a!==null),[t,e,s]),i=p.useMemo(()=>n.map(({providerID:a,modelID:l})=>{const d=e.find(h=>h.id===a);if(!d)return null;const u=(Array.isArray(d.models)?d.models:[]).find(h=>h.id===l);return!u||s(a,l)?null:{provider:d,model:u,providerID:a,modelID:l}}).filter(a=>a!==null).filter(({providerID:a,modelID:l})=>!t.some(d=>d.providerID===a&&d.modelID===l)),[n,e,t,s]);return{favoriteModelsList:o,recentModelsList:i}},ID=typeof window<"u"?p.useLayoutEffect:p.useEffect,ED=(e,t=[])=>{const[n,r]=p.useState(!1),s=p.useCallback(()=>{const o=e.current;if(!o)return;const i=o.scrollWidth>o.clientWidth+1;r(i)},[e]);return ID(()=>{s()},[s,...t]),p.useEffect(()=>{const o=e.current;if(!o||typeof ResizeObserver>"u")return;const i=new ResizeObserver(()=>{s()});return i.observe(o),()=>i.disconnect()},[s,e]),p.useEffect(()=>{if(typeof window>"u")return;const o=()=>s();return window.addEventListener("resize",o),()=>window.removeEventListener("resize",o)},[s]),n},j1=(e,t)=>t?[void 0,...e]:[...e],K3=e=>e??"default",_D=(e,t)=>t===0?50:e/t*100,Qc=10,jD={side:"none",align:"none",fallbackAxisSide:"none"};function Vy({options:e,value:t,prefix:n="",className:r,truncateAt:s}){const o=i=>s==null||i.length<=s?i:`${i.slice(0,s)}...`;return c.jsxs("span",{className:R("grid min-w-0 justify-items-start",r),children:[e.map(i=>c.jsxs("span",{className:"invisible col-start-1 row-start-1 overflow-hidden whitespace-nowrap","aria-hidden":"true",children:[n,o(Ur(i))]},K3(i))),c.jsxs("span",{className:"col-start-1 row-start-1 truncate",children:[n,o(t)]})]})}function TD({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=p.useRef(null),i=j1(e,s),[a,l]=p.useState(null),[d,f]=p.useState(null),u=a!==null?a:t,h=Math.max(0,i.findIndex(M=>M===u)),m=Math.max(0,i.length-1),g=m===0?0:h/m,x=d!==null?d:g,b=Ur(i[h]),S=p.useRef(null),y=p.useRef(t),v=p.useRef(i),C=p.useRef(n),w=p.useRef(r),I=p.useRef(null);p.useEffect(()=>{y.current=t},[t]),p.useEffect(()=>{v.current=i},[i]),p.useEffect(()=>{C.current=n},[n]),p.useEffect(()=>{w.current=r},[r]),p.useEffect(()=>{I.current=a},[a]),p.useEffect(()=>{a!==null&&a===t&&(l(null),f(null))},[t,a]);const E=p.useCallback(M=>{const L=o.current?.getBoundingClientRect(),O=v.current;if(!L||L.width<=0||O.length===0)return{next:O[0],clamped:0};const N=Math.min(Math.max((M-L.left)/L.width,0),1),D=D6(N,O.length);return{next:O[D],clamped:N}},[]),T=M=>{M.preventDefault();const{next:L,clamped:O}=E(M.clientX);l(L),f(O),I.current=L,S.current=M.pointerId;try{M.currentTarget.setPointerCapture(M.pointerId)}catch{}!w.current&&L!==y.current&&C.current(L)},A=M=>{if(S.current!==M.pointerId)return;M.preventDefault();const{next:L,clamped:O}=E(M.clientX);f(O),L!==I.current&&(l(L),I.current=L,!w.current&&L!==y.current&&C.current(L))},j=M=>{if(S.current!==M.pointerId)return;const{next:L,clamped:O}=E(M.clientX),N=I.current??L,D=d??O;S.current=null;try{M.currentTarget.hasPointerCapture(M.pointerId)&&M.currentTarget.releasePointerCapture(M.pointerId)}catch{}w.current?(w.current(N),f(D)):N!==y.current&&C.current(N),w.current||(l(null),f(null))},k=M=>{S.current===M.pointerId&&(S.current=null,l(null),f(null))},_=M=>{let L=null;if((M.key==="ArrowRight"||M.key==="ArrowUp")&&(L=Math.min(m,h+1)),(M.key==="ArrowLeft"||M.key==="ArrowDown")&&(L=Math.max(0,h-1)),M.key==="Home"&&(L=0),M.key==="End"&&(L=m),L===null||L===h)return;M.preventDefault();const O=i[L];w.current?w.current(O):n(O)};return c.jsx("div",{role:"slider",tabIndex:0,"aria-label":"Thinking","aria-orientation":"horizontal","aria-valuemin":0,"aria-valuemax":m,"aria-valuenow":h,"aria-valuetext":b,"data-no-drawer-swipe":"true",className:"cursor-pointer touch-none select-none px-4 py-1 outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] rounded-full",style:{touchAction:"none"},onPointerDown:T,onPointerMove:A,onPointerUp:j,onPointerCancel:k,onLostPointerCapture:k,onKeyDown:_,children:c.jsxs("div",{className:"relative h-8",children:[c.jsx("div",{className:"absolute inset-x-0 top-1/2 h-5 -translate-y-1/2 rounded-full bg-muted"}),c.jsx("div",{className:"absolute left-0 top-1/2 h-5 -translate-y-1/2 rounded-full bg-primary",style:{width:`calc(${Qc}px + (100% - ${Qc*2}px) * ${x})`}}),c.jsxs("div",{ref:o,className:"absolute inset-y-0",style:{left:Qc,right:Qc},children:[i.map((M,L)=>{const O=_D(L,m),N=L<=h;return c.jsx("div",{"aria-hidden":"true",className:R("pointer-events-none absolute top-1/2 size-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full",N?"bg-primary-foreground/50":"bg-foreground/35"),style:{left:`${O}%`}},K3(M))}),c.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-1/2 h-0",children:c.jsx("div",{className:"w-full",style:{transform:`translateX(${x*100}%)`},children:c.jsx("div",{className:"absolute left-0 top-0 size-8 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground"})})})]})]})})}function T1({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=j1(e,s);return c.jsxs("div",{className:"w-full px-4 pt-3.5 pb-2","data-no-drawer-swipe":"true",children:[c.jsx(TD,{levels:e,value:t,onChange:n,onCommit:r,allowUnset:s}),c.jsxs("div",{className:"mt-1.5 flex justify-between px-4 typography-micro text-muted-foreground",children:[c.jsx("span",{children:Ur(o[0])}),c.jsx("span",{className:"text-right",children:Ur(o[o.length-1])})]})]})}function AD({levels:e,value:t,onChange:n,compact:r,keepLabel:s=!1,onCompactOpen:o,buttonHeight:i,iconSize:a,textSize:l,isMobile:d,isDesktop:f}){const[u,h]=p.useState(!1),m=Ur(t),x=!t?"text-muted-foreground":"text-foreground",b=j1(e,!0),S=d?10:void 0,y=c.jsxs("button",{type:"button",onClick:r?o:void 0,className:R("model-controls__variant-trigger flex items-center gap-1.5 min-w-0",i,"cursor-pointer hover:bg-transparent hover:opacity-70",r?"transition-opacity focus:outline-none":"transition-opacity"),"aria-label":`Thinking: ${m}`,children:[c.jsx(V,{name:"brain-ai-3",className:R(a,"flex-shrink-0",x)}),c.jsx(Vy,{options:b,value:m,truncateAt:S,className:R("model-controls__variant-label",l,"font-normal",s?"min-w-max whitespace-nowrap":null,r&&d&&!s&&"max-w-[60px]",!r&&f&&"max-w-[180px]",x)})]});return r?y:c.jsxs(U5,{open:u,onOpenChange:h,children:[c.jsxs(wt,{delayDuration:600,...u?{open:!1}:{},children:[c.jsx(St,{asChild:!0,children:c.jsx(q5,{render:y})}),c.jsx(Ct,{side:"top",align:"center",children:c.jsx(Vy,{options:b,value:m,prefix:"Thinking: ",className:"typography-meta"})})]}),c.jsx(W5,{children:c.jsx(K5,{className:"app-region-no-drag z-50",side:"top",align:"center",sideOffset:8,collisionPadding:8,collisionAvoidance:jD,children:c.jsx(G5,{className:R(o1,"w-[min(17.5rem,calc(100vw-2rem))] p-0 max-h-none"),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},children:c.jsx(T1,{levels:e,value:t,onChange:n})})})})]})}function ND(){const e=We(i=>i.isInitialized),t=We(i=>i.connectionPhase),n=We(i=>i.lastDisconnectReason),r=We(i=>i.providers.length>0),s=e||r,o=!s&&n==="init_error";return{isReady:s,isLoading:!s&&!o,isUnavailable:o,connectionPhase:t}}const LD=({authoritative:e,observed:t,composer:n})=>{if(t&&t.providerId===e.providerId&&t.modelId===e.modelId&&(t.thinking??void 0)===(e.thinking??void 0))return"ignore";const r=t?.providerId===e.providerId&&t?.modelId===e.modelId,s=n.providerId!==e.providerId||n.modelId!==e.modelId;return r&&s||n.providerId===e.providerId&&n.modelId===e.modelId&&(e.thinking===void 0||n.thinking===e.thinking)?"observe":"apply"},RD=[{key:"tool_call",icon:"tools",label:"Tool calling",isActive:e=>e?.tool_call===!0},{key:"reasoning",icon:"brain-ai-3",label:"Reasoning",isActive:e=>e?.reasoning===!0}],PD={text:{icon:"text",label:"Text"},image:{icon:"file-image",label:"Image"},video:{icon:"file-video",label:"Video"},audio:{icon:"file-music",label:"Audio"},pdf:{icon:"file-pdf",label:"PDF"}},DD=e=>e.trim().toLowerCase(),kd=(e,t)=>{const n=t==="input"?e?.modalities?.input:e?.modalities?.output;if(!Array.isArray(n)||n.length===0)return[];const r=Array.from(new Set(n.map(o=>DD(o)))),s=[];for(const o of r){const i=PD[o];i&&s.push({key:o,icon:i.icon,label:i.label})}return s},OD=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),HD=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),FD=e=>new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(e),BD=e=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e),Aa=e=>{if(typeof e!="number"||Number.isNaN(e))return"—";if(e===0)return"0";const t=OD(e);return t.endsWith(".0")?t.slice(0,-2):t},el=e=>typeof e!="number"||!Number.isFinite(e)?"—":HD(e),G3=e=>{const t=[];for(const n of RD)n.isActive(e)&&t.push({key:n.key,icon:n.icon,label:n.label});return t},Z3=e=>{if(!e)return"—";const t=e.match(/^(\d{4})-(\d{2})$/);if(t){const n=Number.parseInt(t[1],10),r=Number.parseInt(t[2],10)-1,s=new Date(Date.UTC(n,r,1));if(!Number.isNaN(s.getTime()))return FD(s)}return e},Y3=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:BD(t)},Ro=({iconName:e,label:t})=>c.jsx("span",{className:"flex size-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:t,"aria-label":t,role:"img",children:c.jsx(V,{name:e,className:"size-3.5"})}),VD=({currentMetadata:e,modelDisplayName:t,providerDisplayName:n,currentCapabilityIcons:r,inputModalityIcons:s,outputModalityIcons:o,costRows:i,limitRows:a})=>c.jsx(Ct,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e?c.jsxs("div",{className:"flex min-w-[240px] flex-col gap-3",children:[c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"typography-micro font-semibold text-foreground",children:e.name||t}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:n})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Capabilities"}),c.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:r.length>0?r.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:f},`cap-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Modalities"}),c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:"Input"}),c.jsx("div",{className:"flex items-center gap-1.5",children:s.length>0?s.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:`${f} input`},`input-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"-"})})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:"Output"}),c.jsx("div",{className:"flex items-center gap-1.5",children:o.length>0?o.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:`${f} output`},`output-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"-"})})]})]})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Cost ($/1M tokens)"}),i.map(l=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:l.label}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:l.value})]},l.label))]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Limits"}),a.map(l=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:l.label}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:l.value})]},l.label))]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Metadata"}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:"Knowledge"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Z3(e.knowledge)})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:"Release"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Y3(e.release_date)})]})]})]}):c.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),$D=({open:e,onClose:t,title:n,providerDisplayName:r,currentCapabilityIcons:s,inputModalityIcons:o,outputModalityIcons:i,currentMetadata:a})=>e?c.jsx(Ta,{open:!0,onClose:t,title:n,children:c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),c.jsx("div",{className:"typography-meta text-foreground font-medium",children:r})]}),s.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Capabilities"}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(({key:l,icon:d,label:f})=>c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(Ro,{iconName:d,label:f},`cap-${l}`),c.jsx("span",{className:"typography-meta text-foreground",children:f})]},l))})]}),(o.length>0||i.length>0)&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),c.jsxs("div",{className:"flex flex-col gap-1",children:[o.length>0&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground w-12",children:"Input"}),c.jsx("div",{className:"flex gap-1",children:o.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:`${f} input`},`input-${l}`))})]}),i.length>0&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground w-12",children:"Output"}),c.jsx("div",{className:"flex gap-1",children:i.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:`${f} output`},`output-${l}`))})]})]})]}),c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground",children:"Context"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Aa(a?.limit?.context)})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground",children:"Output"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Aa(a?.limit?.output)})]})]})]}),c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Metadata"}),c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground",children:"Knowledge"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Z3(a?.knowledge)})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground",children:"Release"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Y3(a?.release_date)})]})]})]})]})}):null,zD=({open:e,onClose:t,targetVariants:n,selectedVariant:r,onVariantLiveChange:s,onVariantCommit:o})=>!e||n.length===0?null:c.jsx(Ta,{open:!0,onClose:t,title:"Thinking",children:c.jsx(T1,{levels:n,value:dn(r)??void 0,onChange:s,onCommit:o})}),UD=e=>{if(!e||e.trim().length===0)return Ur(void 0);const t=e.trim();return/^\d+(\.\d+)?$/.test(t)?t:Ur(t)},qD=(e,t)=>`${e}:${t}`,WD=({open:e,onClose:t,mobileModelQuery:n,onMobileModelQueryChange:r,filteredFavorites:s,filteredRecents:o,filteredProviders:i,expandedMobileProviders:a,onToggleMobileProviderExpansion:l,expandedMobileModelKey:d,onToggleExpandedMobileModelKey:f,currentProviderId:u,currentModelId:h,getModelDisplayName:m,getModelMetadata:g,getModelVariantOptions:x,resolveModelVariantSelection:b,pendingThinkingVariants:S,onUpdatePendingThinkingVariant:y,isFavoriteModel:v,onToggleFavoriteModel:C,onApplyModel:w})=>{if(!e)return null;const I=n.trim(),E=s.length>0||o.length>0||i.length>0,T=({model:A,providerId:j,modelId:k,showProviderLogo:_})=>{const M=qD(j,k),L=j===u&&k===h,O=I1(j,A,g(j,k)),N=x(j,k),D=N.length>0,W=b(j,k),z=S.get(M),F=S.has(M)?z:W,U=D?UD(F):null,P=d===M,q=G3(O),B=[...kd(O,"input"),...kd(O,"output")],ee=Array.from(new Map([...q,...B].map(K=>[K.key,K])).values()),G=O?.limit?.context?`${Aa(O.limit.context)} ctx`:null;return c.jsxs("div",{className:R("border-b border-border/30 last:border-b-0",L&&"bg-interactive-selection/15 text-interactive-selection-foreground"),children:[c.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5",children:[c.jsx("button",{type:"button",onClick:()=>w(j,k,F),className:R("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-lg"),children:c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[_?c.jsx(Wo,{providerId:j,className:"size-3.5 flex-shrink-0"}):null,c.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:m(A)}),L?c.jsx(V,{name:"check",className:"size-4 flex-shrink-0 text-primary"}):null]}),G||ee.length>0?c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden typography-micro text-muted-foreground",children:[G?c.jsx("span",{className:"whitespace-nowrap flex-shrink-0",children:G}):null,G&&ee.length>0?c.jsx("span",{"aria-hidden":"true",className:"h-3 w-px flex-shrink-0 bg-border/50"}):null,ee.length>0?c.jsx("div",{className:"flex min-w-0 items-center gap-1 overflow-hidden whitespace-nowrap pl-0.5",children:ee.map(({key:K,icon:se,label:de})=>c.jsx("span",{className:"flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",title:de,"aria-label":de,children:c.jsx(V,{name:se,className:"size-3"})},`meta-${j}-${k}-${K}`))}):null]}):null]})}),D?c.jsxs("button",{type:"button",onClick:()=>f(d===M?null:M),className:"flex items-center gap-0.5 typography-micro font-medium text-muted-foreground hover:text-foreground flex-shrink-0","aria-expanded":P,"aria-label":P?"Hide thinking modes":"Show thinking modes",children:[c.jsx("span",{className:"whitespace-nowrap",children:U}),P?c.jsx(V,{name:"arrow-down-s",className:"size-3.5"}):c.jsx(V,{name:"arrow-right-s",className:"size-3.5"})]}):null,c.jsx("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:c.jsx("button",{type:"button",onClick:K=>{K.preventDefault(),K.stopPropagation(),C(j,k)},className:R("model-favorite-button flex size-5 items-center justify-center hover:text-primary/80 flex-shrink-0",v(j,k)?"text-primary":"text-muted-foreground"),"aria-label":v(j,k)?"Unfavorite":"Favorite",title:v(j,k)?"Remove from favorites":"Add to favorites",children:v(j,k)?c.jsx(V,{name:"star-fill",className:"size-4"}):c.jsx(V,{name:"star",className:"size-4"})})})]}),P&&D?c.jsx("div",{className:"border-t border-border/30 px-1 py-1","data-no-drawer-swipe":"true",children:c.jsx(T1,{levels:N,value:dn(F)??void 0,onChange:()=>{},onCommit:K=>y(M,K)})}):null]},`mobile-model-${j}-${k}`)};return c.jsx(Ta,{open:!0,onClose:t,title:"Select model",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("div",{children:c.jsxs("div",{className:"relative",children:[c.jsx(V,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground"}),c.jsx(Uo,{value:n,onChange:A=>{r(A.target.value),f(null)},placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-[var(--surface-elevated)] typography-meta"}),n&&c.jsx("button",{type:"button",onClick:()=>{r(""),f(null)},className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:c.jsx(V,{name:"close-circle",className:"size-4"})})]})}),!E&&c.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),s.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[c.jsx(V,{name:"star-fill",className:"size-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),c.jsx("div",{className:"flex flex-col border-t border-border/30",children:s.map(({model:A,providerID:j,modelID:k})=>T({model:A,providerId:j,modelId:k,showProviderLogo:!0}))})]}),o.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[c.jsx(V,{name:"time",className:"size-3 inline-block mr-1.5"}),"Recent"]}),c.jsx("div",{className:"flex flex-col border-t border-border/30",children:o.map(({model:A,providerID:j,modelID:k})=>T({model:A,providerId:j,modelId:k,showProviderLogo:!0}))})]}),i.map(({provider:A,providerModels:j})=>{if(j.length===0)return null;const k=String(A.id||""),_=String(A.name||k),M=k===u,L=a.has(k)||I.length>0;return c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("button",{type:"button",onClick:()=>{I.length>0||l(k)},className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":L,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Wo,{providerId:k,className:"size-3.5"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:_}),M&&c.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),L?c.jsx(V,{name:"arrow-down-s",className:"size-3 text-muted-foreground"}):c.jsx(V,{name:"arrow-right-s",className:"size-3 text-muted-foreground"})]}),L&&j.length>0&&c.jsx("div",{className:"flex flex-col border-t border-border/30",children:j.map(O=>T({model:O,providerId:String(A.id||""),modelId:String(O.id||""),showProviderLogo:!1}))})]},k)})]})})},ah=(e,t)=>`${e}:${t}`,KD="__add_provider__",GD=({className:e,keepLabels:t=!1,mobilePanel:n,onMobilePanelChange:r})=>{const{isReady:s,isUnavailable:o}=ND(),i=o?"Unavailable":"Loading...",a=We(Z=>Z.providers),l=We(Z=>Z.currentProviderId),d=We(Z=>Z.currentModelId),f=We(Z=>Z.currentVariant),u=We(Z=>Z.settingsDefaultThinking),h=We(Z=>Z.settingsDefaultThinkingByModel),m=We(Z=>Z.setProvider),g=We(Z=>Z.setSelectedProvider),x=We(Z=>Z.setModel),b=We(Z=>Z.setCurrentVariant),S=We(Z=>Z.getCurrentModelVariants),y=We(Z=>Z.getCurrentProvider),v=We(Z=>Z.getModelMetadata),C=p.useRef(!1);p.useEffect(()=>{C.current||!s||(C.current=!0,it("ModelControls:ready",{providers:a.length,currentProviderId:l,currentModelId:d}))},[d,l,s,a.length]);const w=he(Z=>Z.currentSessionId),I=he(Z=>Z.newSessionDraft.open),E=he(Z=>Z.getDirectoryForSession),T=W3(),A=Lt(Z=>Z.getSessionModelSelection),j=Lt(Z=>Z.saveSessionModelSelection),k=Lt(Z=>Z.hasHydrated),_=re(Z=>Z.toggleFavoriteModel),M=re(Z=>Z.reorderFavoriteModel),L=re(Z=>Z.isFavoriteModel),O=re(Z=>Z.addRecentModel),N=re(Z=>Z.addRecentEffort),D=re(Z=>Z.isModelSelectorOpen),W=re(Z=>Z.setModelSelectorOpen),z=re(Z=>Z.setSettingsDialogOpen),X=re(Z=>Z.setSettingsPage),F=re(Z=>Z.hiddenModels),{favoriteModelsList:U,recentModelsList:P}=MD(),{isMobile:q}=On(),{enabled:B}=mu(),ee=re(Z=>Z.isMobile),G=(q||ee)&&!B,K=p.useMemo(()=>xt(),[]),se=G,[de,oe]=p.useState(null),ue=n!==void 0&&typeof r=="function",ye=ue?n:de,we=ue?r:oe,[Me,He]=p.useState(null),[Ae,Ge]=p.useState(""),[et,Xe]=p.useState(null),te=p.useRef(!1),Q=p.useCallback(()=>we(null),[we]),me=p.useCallback(()=>He(null),[]),Se=p.useRef(void 0),[_e,Fe]=p.useState(()=>{const Z=new Set;return l&&Z.add(l),Z}),ht=p.useCallback(()=>{g(KD),X("providers"),z(!0),W(!1),Q()},[g,X,z,W,Q]),[ge,Ze]=p.useState(""),Ve=p.useRef(!1),ie=p.useRef(null),ke=p.useRef(void 0),ve=p.useRef(null),[xe,je]=p.useState(new Map),[le,J]=p.useState(new Set),[ne,fe]=p.useState(0);p.useEffect(()=>{ye==="model"&&(We.getState().ensureModelMetadata(),Fe(()=>{const Z=new Set;return l&&Z.add(l),Z}))},[ye,l]),p.useEffect(()=>{ye===null&&Xe(null)},[ye]),p.useEffect(()=>{ye!=="model"&&(Ge(""),Xe(null),je(new Map),J(new Set))},[ye]);const De=p.useRef(D);p.useEffect(()=>{const Z=De.current;De.current=D,D&&We.getState().ensureModelMetadata(),D||(Ze(""),Ve.current=!1,ie.current=null,je(new Map),J(new Set),Z&&!se&&requestAnimationFrame(To))},[D,se]);const Ue=G?"mobile":"default",st=Ue==="mobile"?"h-9":"h-7",Ee="size-3.5",Ke="typography-meta",_t=Ue==="mobile"?"gap-x-1":"gap-x-3",fn=y(),Sn=Array.isArray(fn?.models)?fn.models:[],Bs=p.useMemo(()=>{const Z=[];for(const pe of a){const Ne=(Array.isArray(pe.models)?pe.models:[]).filter(lt=>{const ot=typeof lt?.id=="string"?lt.id:"";return!F.some(dt=>dt.providerID===String(pe.id)&&dt.modelID===ot)});Ne.length>0&&Z.push({...pe,models:Ne})}return Z},[a,F]),Vs=p.useCallback(Z=>{const pe=Z.toLowerCase().trim(),Re=pe.replace(/[^a-z0-9]/g,""),Ne=pe.split(/[^a-z0-9]+/).filter(Boolean);return{lower:pe,compact:Re,tokens:Ne}},[]),Hn=p.useCallback((Z,pe)=>{const Re=Vs(pe);if(!Re.lower)return!0;const Ne=Vs(Z);return Ne.lower.includes(Re.lower)||Re.compact.length>=2&&Ne.compact.includes(Re.compact)?!0:Re.tokens.length===0?!1:Re.tokens.every(lt=>Ne.tokens.some(ot=>ot.startsWith(lt)||ot.includes(lt)))},[Vs]),Ja=d?Sn.find(Z=>Z.id===d):void 0,Ot=l&&d&&Ja?I1(l,Ja,v(l,d)):l&&d?v(l,d):void 0,tn=p.useCallback(Z=>Z==="Tool calling"?"Tool calling":Z==="Reasoning"?"Reasoning":Z==="Text"?"Text":Z==="Image"?"Image":Z==="Video"?"Video":Z==="Audio"?"Audio":Z==="PDF"?"PDF":Z,[]),Yr=p.useMemo(()=>G3(Ot).map(Z=>({...Z,label:tn(Z.label)})),[Ot,tn]),ni=p.useMemo(()=>kd(Ot,"input").map(Z=>({...Z,label:tn(Z.label)})),[Ot,tn]),ri=p.useMemo(()=>kd(Ot,"output").map(Z=>({...Z,label:tn(Z.label)})),[Ot,tn]),xr=S().filter(Ht),Qa=xr.length>0,ec=[{label:"Input",value:el(Ot?.cost?.input)},{label:"Output",value:el(Ot?.cost?.output)},{label:"Cache read",value:el(Ot?.cost?.cache_read)},{label:"Cache write",value:el(Ot?.cost?.cache_write)}],tc=[{label:"Context",value:Aa(Ot?.limit?.context)},{label:"Output",value:Aa(Ot?.limit?.output)}],Fn=p.useRef(null),Xr=p.useRef(null);w&&E(w);const Bn=Tw(w??""),Pt=Be(Z=>{if(!w)return null;const pe=Z.reducer.bySession.get(w);return pe?{model:pe.model,thinking:pe.thinking}:null},(Z,pe)=>Z===pe?!0:!Z||!pe?!1:Z.model?.providerId===pe.model?.providerId&&Z.model?.modelId===pe.model?.modelId&&Z.thinking===pe.thinking,w?`session:${w}`:"*"),br=p.useCallback((Z,pe)=>{if(!Z||!pe)return"model-missing";const Re=a.find(Qe=>Qe.id===Z);if(!Re)return"provider-missing";const lt=(Array.isArray(Re.models)?Re.models:[]).find(Qe=>Qe.id===pe);if(!lt)return"model-missing";if(l===Z&&d===pe)return"applied";m(Z),x(pe);const Oe=_c({providerId:Z,modelId:pe,thinkingLevels:lt.thinkingLevels,reasoning:lt.reasoning,supportsThinking:lt.supportsThinking,defaultThinkingByModel:h,defaultThinking:u,previousThinking:f});return b(Oe),w&&j(w,Z,pe),"applied"},[a,l,d,f,m,x,b,w,j,u,h]),Vt=p.useCallback((Z,pe)=>{const Re=a.find(lt=>lt.id===Z),Ne=(Array.isArray(Re?.models)?Re.models:[]).find(lt=>lt.id===pe);return Em(Ne)},[a]),Jr=p.useCallback((Z,pe,Re)=>{if(!Z||!pe)return"model-missing";const Ne=a.find(dt=>dt.id===Z);if(!Ne)return"provider-missing";if(!(Array.isArray(Ne.models)?Ne.models:[]).some(dt=>dt.id===pe))return"model-missing";l!==Z&&m(Z),(l!==Z||d!==pe)&&x(pe),w&&j(w,Z,pe);const ot=Vt(Z,pe);return b(Re&&ot.includes(Re)?Re:void 0),Xr.current={...Z?{providerId:Z}:{},...pe?{modelId:pe}:{},...Re?{thinking:Re}:{}},"applied"},[d,l,w,Vt,a,j,b,x,m]),si=p.useCallback((Z,pe)=>{const Re=Vt(Z,pe);if(Re.length!==0){if(l===Z&&d===pe&&Ht(f)&&Re.includes(f))return f;if(!w){const Ne=a.find(ot=>ot.id===Z),lt=(Array.isArray(Ne?.models)?Ne.models:[]).find(ot=>ot.id===pe);return _c({providerId:Z,modelId:pe,thinkingLevels:lt?.thinkingLevels,reasoning:lt?.reasoning,supportsThinking:lt?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u})}}},[d,l,w,f,Vt,a,u,h]),Qr=p.useCallback((Z,pe,Re)=>{const Ne=Vt(Z,pe);if(Ne.length===0){te.current=!1,Fi(void 0);return}const lt=Ht(Re)&&Ne.includes(Re)?Re:void 0;te.current=!0,Fi(lt),N(Z,pe,Re)},[N,Vt]),nc=p.useCallback((Z,pe,Re)=>{const Ne=br(Z,pe);return Ne!=="applied"?Ne:(O(Z,pe),Qr(Z,pe,Re),"applied")},[O,Qr,br]);p.useEffect(()=>{if(!w){Fn.current=null;return}if(!k||a.length===0)return;if(!Bn){T.ensureSessionRenderable(w);return}if(Fn.current===w)return;const Z=Ne=>{if(Ne&&l&&d){const lt=Vt(l,d);b(lt.includes(Ne)?Ne:void 0);return}b(void 0)},pe=Pt?.model;if(pe){if(Jr(pe.providerId,pe.modelId,Pt?.thinking)==="provider-missing")return;Fn.current=w;return}if(Pt?.thinking){Z(Pt.thinking),Fn.current=w;return}const Re=A(w);Re&&Jr(Re.providerId,Re.modelId,Pt?.thinking)==="provider-missing"||(Fn.current=w)},[Jr,k,d,l,w,Pt,Vt,A,Bn,a.length,b,T]),p.useEffect(()=>{if(!w||!k||a.length===0||!Bn||Fn.current!==w)return;const Z=Pt?.model,pe=Pt?.thinking??void 0;if(!Z?.providerId||!Z?.modelId){Xr.current=null;return}const Re=LD({authoritative:{providerId:Z.providerId,modelId:Z.modelId,thinking:pe},observed:Xr.current,composer:{providerId:l,modelId:d,thinking:dn(f)??void 0}});if(Re!=="ignore"){if(Re==="apply"){Jr(Z.providerId,Z.modelId,pe);return}Xr.current={providerId:Z.providerId,modelId:Z.modelId,...pe?{thinking:pe}:{}}}},[Jr,k,d,l,w,f,Pt,Bn,a.length]),p.useEffect(()=>{if(!k){te.current=!1,b(void 0);return}if(!l||!d){te.current=!1,b(void 0);return}const Z=a.find(Ne=>Ne.id===l),pe=(Array.isArray(Z?.models)?Z.models:[]).find(Ne=>Ne.id===d),Re=Im(pe);if(!Xd(Re)){f&&Ht(f)&&b(void 0);return}if(!w&&!f&&!te.current){const Ne=_c({providerId:l,modelId:d,thinkingLevels:pe?.thinkingLevels,reasoning:pe?.reasoning,supportsThinking:pe?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u});Ne&&b(Ne);return}if(f&&Ht(f)&&!Re.includes(f)){b(_c({providerId:l,modelId:d,thinkingLevels:pe?.thinkingLevels,reasoning:pe?.reasoning,supportsThinking:pe?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u,previousThinking:f}));return}if(w&&!f&&!te.current){const Ne=dn(Pt?.thinking);Ne&&Re.includes(Ne)&&b(Ne)}},[k,w,l,d,f,Pt,a,b,u,h]),p.useEffect(()=>{te.current=!1},[l,d]);const Lu=p.useCallback(Z=>{l&&d&&Qr(l,d,Z)},[Qr,d,l]),$s=p.useCallback(Z=>{if(!l||!d)return;const pe=Vt(l,d);if(pe.length===0){te.current=!1,Fi(void 0);return}const Re=Ht(Z)&&pe.includes(Z)?Z:void 0;te.current=!0,Fi(Re)},[l,d,Vt]),Ru=p.useCallback(Z=>{Z!==f&&$s(Z),l&&d&&N(l,d,Z)},[$s,l,d,f,N]),Pu=(Z,pe,Re)=>{try{const Ne=Re?.applyVariant?nc(Z,pe,Re.variant):br(Z,pe);if(Ne!=="applied"){Ne==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",Z):Ne==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:Z,modelId:pe});return}Re?.applyVariant||O(Z,pe),W(!1),se&&Q(),requestAnimationFrame(To)}catch(Ne){console.error("[ModelControls] Handle model change error:",Ne)}},Qn=(Z,pe)=>E1(Z,pe,{maxLength:40}),es=()=>a.find(pe=>pe.id===l)?.name||l||"",nn=()=>{if(!d)return"Select model";const Z=Sn.find(pe=>pe.id===d);return Qn(Z,d)||"Select model"},oi=p.useCallback((Z,pe)=>!G||Z.length<=pe?Z:`${Z.slice(0,pe)}...`,[G])(nn(),16),Vn=p.useRef(null),rc=ED(Vn,[oi,se]),wr=p.useCallback(Z=>{Fe(pe=>{const Re=new Set(pe);return Re.has(Z)?Re.delete(Z):Re.add(Z),Re})},[]),zs=p.useCallback(Z=>{Se.current&&clearTimeout(Se.current),Se.current=setTimeout(()=>{He(Z)},500)},[]),sc=p.useCallback(()=>{Se.current&&clearTimeout(Se.current)},[]);p.useEffect(()=>()=>{Se.current&&clearTimeout(Se.current)},[]);const oc=()=>!se||Me!=="model"?null:c.jsx($D,{open:!0,onClose:me,title:Ot?.name||nn(),providerDisplayName:es(),currentCapabilityIcons:Yr,inputModalityIcons:ni,outputModalityIcons:ri,currentMetadata:Ot}),ic=()=>{if(!se)return null;const Z=Ae.trim(),pe=U.filter(({model:ot,providerID:dt})=>{const Qe=a.find(jt=>jt.id===dt)?.name||dt,kt=Qn(ot);return Z.length===0||Hn(String(kt||""),Z)||Hn(String(Qe||""),Z)}),Re=P.filter(({model:ot,providerID:dt})=>{const Qe=a.find(jt=>jt.id===dt)?.name||dt,kt=Qn(ot);return Z.length===0||Hn(String(kt||""),Z)||Hn(String(Qe||""),Z)}),Ne=[];for(const ot of Bs){const dt=Array.isArray(ot.models)?ot.models:[],Oe=Z.length===0?!0:Hn(String(ot.name||""),Z)||Hn(String(ot.id||""),Z),Qe=Z.length===0?dt:dt.filter(jt=>{const Cn=Qn(jt),rn=typeof jt.id=="string"?jt.id:"";return Hn(String(Cn||""),Z)||Hn(String(rn||""),Z)}),kt=Oe&&Z.length>0?dt:Qe;(Oe||kt.length>0)&&Ne.push({provider:ot,providerModels:kt,matchesProvider:Oe})}const lt=(ot,dt,Oe)=>{const Qe=nc(ot,dt,Oe);if(Qe!=="applied"){Qe==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",ot):Qe==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:ot,modelId:dt});return}Xe(null),Q(),requestAnimationFrame(To)};return c.jsx(WD,{open:ye==="model",onClose:Q,mobileModelQuery:Ae,onMobileModelQueryChange:Ge,filteredFavorites:pe,filteredRecents:Re,filteredProviders:Ne,expandedMobileProviders:_e,onToggleMobileProviderExpansion:wr,expandedMobileModelKey:et,onToggleExpandedMobileModelKey:Xe,currentProviderId:l,currentModelId:d,getModelDisplayName:Qn,getModelMetadata:v,getModelVariantOptions:Vt,resolveModelVariantSelection:si,pendingThinkingVariants:xe,onUpdatePendingThinkingVariant:(ot,dt)=>{je(Oe=>{const Qe=new Map(Oe);return Qe.set(ot,dt),Qe}),J(Oe=>{const Qe=new Set(Oe);return Qe.add(ot),Qe}),fe(Oe=>Oe+1)},isFavoriteModel:L,onToggleFavoriteModel:_,onApplyModel:lt})},ac=()=>{if(!se||!l||!d)return null;const Z=Vt(l,d);return c.jsx(zD,{open:ye==="variant",onClose:Q,targetVariants:Z,selectedVariant:f,onVariantLiveChange:$s,onVariantCommit:Ru})},cc=()=>c.jsx(VD,{currentMetadata:Ot,modelDisplayName:nn(),providerDisplayName:es(),currentCapabilityIcons:Yr,inputModalityIcons:ni,outputModalityIcons:ri,costRows:ec,limitRows:tc}),lc=()=>{const Z=(Oe,Qe)=>{if(Ve.current=!0,Oe.key!=="ArrowLeft"&&Oe.key!=="ArrowRight")return!1;const{providerID:kt,modelID:jt}=Qe,Cn=Vt(kt,jt);if(Cn.length===0)return!1;Oe.preventDefault(),Oe.stopPropagation();const rn=ah(kt,jt),Us=xe.has(rn),qs=xe.get(rn),er=Us?qs:l===kt&&d===jt?f:void 0,ii=_m(Cn,Ht(er)?er:void 0,Oe.key==="ArrowRight"?1:-1);return je(Sr=>{const Cr=new Map(Sr);return Cr.set(rn,ii),Cr}),J(Sr=>{const Cr=new Set(Sr);return Cr.add(rn),Cr}),fe(Sr=>Sr+1),!0},pe=(Oe,Qe)=>{Qe&&Z(Oe,Qe)},Re=Oe=>{const Qe=ah(Oe.providerID,Oe.modelID),kt=xe.get(Qe),jt=le.has(Qe);Pu(Oe.providerID,Oe.modelID,jt?{applyVariant:!0,variant:kt}:void 0)},Ne=Oe=>{ve.current={category:Oe.key.length===1?"printable":Oe.key.startsWith("Arrow")||Oe.key==="Escape"||Oe.key==="Enter"?"navigation":"other",modifiers:Oe.altKey||Oe.ctrlKey||Oe.metaKey||Oe.shiftKey}},lt=(Oe,Qe)=>{if(!Oe){const kt=document.activeElement;console.info("[DEBUG-model-picker-close]",{reason:Qe.reason??"unknown",eventType:Qe.event?.type??"none",draftOpen:I,focusInsidePicker:kt instanceof Element&&!!kt.closest('[data-model-picker-popup="true"]'),precedingKey:ve.current})}W(Oe)},ot={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},dt=(Oe,{isHighlighted:Qe,isSelected:kt})=>{const jt=Vt(Oe.providerID,Oe.modelID).length>0,Cn=ah(Oe.providerID,Oe.modelID),rn=le.has(Cn);if(!jt||!Qe&&!kt)return null;const Us=xe.has(Cn),qs=xe.get(Cn),er=Us?qs:kt?f:void 0,ii=Ur(Ht(er)?er:void 0);return c.jsxs("span",{className:R("typography-micro whitespace-nowrap",rn?"text-foreground":"text-muted-foreground"),children:["Thinking: ",ii]})};return c.jsxs(wt,{delayDuration:600,children:[se?c.jsx("button",{type:"button",onClick:s?()=>we("model"):void 0,onTouchStart:s?()=>zs("model"):void 0,onTouchEnd:s?sc:void 0,onTouchCancel:s?sc:void 0,disabled:!s,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",s?"cursor-pointer hover:bg-transparent hover:opacity-70":"opacity-60 cursor-not-allowed",st),children:s?c.jsxs(c.Fragment,{children:[l?c.jsx(Wo,{providerId:l,className:R(Ee,"flex-shrink-0")}):c.jsx(V,{name:"pencil-ai",className:R(Ee,"text-muted-foreground")}),c.jsx("span",{ref:Vn,className:R("model-controls__model-label typography-meta font-normal overflow-hidden",t?"whitespace-nowrap":"min-w-0",!t&&(G?"max-w-[120px]":"max-w-[220px]")),children:c.jsx("span",{className:R("marquee-text",rc&&"marquee-text--active"),children:oi})}),c.jsx(V,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"})]}):c.jsxs(c.Fragment,{children:[c.jsx(V,{name:"loader-4",className:R(Ee,"animate-spin text-muted-foreground flex-shrink-0")}),c.jsx("span",{className:"typography-meta font-normal text-muted-foreground min-w-0",children:i})]})}):c.jsxs(Fa,{open:s&&D,onOpenChange:s?lt:void 0,children:[c.jsx(St,{asChild:!0,children:c.jsx(Ba,{asChild:!0,children:c.jsxs("button",{type:"button",className:R("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:bg-transparent hover:opacity-70 min-w-0",st),children:[s?l?c.jsxs(c.Fragment,{children:[c.jsx(Wo,{providerId:l,className:R(Ee,"flex-shrink-0")}),c.jsx(V,{name:"pencil-ai",className:R(Ee,"text-primary/60 hidden")})]}):c.jsx(V,{name:"pencil-ai",className:R(Ee,"text-muted-foreground")}):c.jsxs(c.Fragment,{children:[c.jsx(V,{name:"loader-4",className:R(Ee,"animate-spin text-muted-foreground flex-shrink-0")}),c.jsx("span",{className:R("model-controls__model-label",Ke,"font-normal whitespace-nowrap text-muted-foreground min-w-0"),children:i})]}),s&&c.jsx("span",{ref:Vn,className:R("model-controls__model-label overflow-hidden",Ke,"font-normal whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:c.jsx("span",{className:R("marquee-text",rc&&"marquee-text--active"),children:oi})},`${l}-${d}`),s?c.jsx(V,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"}):null]})})}),c.jsxs(Va,{"data-model-picker-popup":"true",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,onKeyDownCapture:Ne,children:[c.jsx("div",{className:"p-1 border-b border-border/40",children:c.jsxs("button",{type:"button",onClick:ht,className:"typography-meta group flex w-full items-center gap-1 rounded-md px-2 py-1.5 cursor-pointer hover:bg-interactive-hover/50",children:[c.jsx("span",{className:"flex size-4 items-center justify-center text-muted-foreground",children:c.jsx(V,{name:"add",className:"size-4 -mr-0.5"})}),c.jsx("span",{className:"font-medium text-foreground",children:"Add new provider"})]})}),c.jsx(kD,{providers:a,favoriteModels:U,recentModels:P,modelsMetadata:We.getState().modelsMetadata,searchQuery:ge,onSearchQueryChange:Ze,onSelect:Re,labels:ot,selectedModel:l&&d?{providerID:l,modelID:d}:null,hiddenModels:F,onActiveKeyDown:pe,onActiveEntryChange:Oe=>{ke.current=Oe},onVariantKey:Z,isFavorite:Oe=>L(Oe.providerID,Oe.modelID),onToggleFavorite:Oe=>_(Oe.providerID,Oe.modelID),renderRowEnd:dt,renderVersion:ne,onReorderFavorite:(Oe,Qe)=>M(Oe.providerID,Oe.modelID,Qe.providerID,Qe.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",tooltipsEnabled:D,onEscape:()=>W(!1)})]})]}),cc()]})},dc=()=>!s||!Qa?null:c.jsx(AD,{levels:xr,value:dn(f)??void 0,onChange:Lu,compact:se,keepLabel:t,onCompactOpen:()=>we("variant"),buttonHeight:st,iconSize:Ee,textSize:Ke,isMobile:G,isDesktop:K}),uc=R(!t&&"@container/model-controls","flex items-center",t?"w-max shrink-0":"min-w-0",G&&!t&&"w-full",e);return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:uc,children:c.jsxs("div",{className:R("flex items-center justify-start",_t,t?"w-max shrink-0":"min-w-0",G&&!t&&"overflow-hidden"),children:[lc(),dc()]})}),ic(),ac(),oc()]})},ZD=1e9,YD=1e12,ch="thinking",XD=e=>e>=YD?e:e>=ZD?e*1e3:Date.now()+e,JD=e=>{if(e<60)return`${e}s`;if(e<3600){const r=Math.floor(e/60),s=e%60;return s>0?`${r}m ${s}s`:`${r}m`}if(e<86400){const r=Math.floor(e/3600),s=Math.floor(e%3600/60);return s>0?`${r}h ${s}m`:`${r}h`}const t=Math.floor(e/86400),n=Math.floor(e%86400/3600);return n>0?`${t}d ${n}h`:`${t}d`};function X3({isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:s,modelName:o,providerId:i,startedAt:a=null}){const{src:l,onError:d,hasLogo:f}=M1(i??null),{currentTheme:u}=vr(),h=u?.metadata.variant==="dark",m=p.useRef(null),[g,x]=p.useState(null);if(p.useEffect(()=>{const I=s?.next;if(!I||I<=0){x(null);return}const E=XD(I),T=()=>{const j=Math.max(0,E-Date.now());x(Math.ceil(j/1e3))};T();const A=setInterval(T,500);return()=>clearInterval(A)},[s?.next,s?.attempt]),!e)return m.current=null,null;if(s){m.current=null;const I=s.attempt&&s.attempt>1?` (attempt ${s.attempt})`:"",T=`Retrying${g!==null&&g>0?` in ${JD(g)}`:""}${I}`;return c.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":"polite","aria-label":`${T}...`,"data-agent-thinking-row":"true",children:c.jsx(gy,{text:T,variant:"inline",showElapsed:!1,className:"min-w-0"})})}const b=r?"waiting for permission":t,S=!!r,y=!!n&&!S;m.current===null?m.current={text:y?ch:b??ch,permission:S}:b&&(!y||S)?m.current={text:b,permission:S}:y&&m.current.permission&&(m.current={text:ch,permission:!1});const v=m.current;if(!v)return null;const C=typeof o=="string"?o.trim():"",w=C.length>0?`${C} is ${v.text}`:v.text.charAt(0).toUpperCase()+v.text.slice(1);return c.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":v.permission?"assertive":"polite","aria-label":w,"data-agent-thinking-row":"true","data-waiting":v.permission?"true":void 0,children:c.jsxs("span",{className:"typography-markdown inline-flex min-w-0 items-center gap-1.5 leading-5",children:[f&&l?c.jsx("img",{src:l,alt:"","aria-hidden":"true",className:"inline-block h-3.5 w-3.5 mr-0.5 align-[-2px]",style:{filter:h?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:d}):null,c.jsx(gy,{text:w,variant:"inline",animationType:"spinner",animateText:!0,startedAt:a,className:"min-w-0"})]})})}const QD={containerType:"inline-size",containerName:"status-row"},$y={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},zy={high:"text-[var(--status-warning)]",medium:"text-muted-foreground",low:"text-subtle-foreground"},Uy={high:c.jsx(V,{name:"arrow-up-double",className:"h-3.5 w-3.5","aria-hidden":"true"}),medium:c.jsx(V,{name:"arrow-up-s",className:"h-3.5 w-3.5","aria-hidden":"true"}),low:c.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5","aria-hidden":"true"})},qy={in_progress:"In progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},Wy={high:"High priority",medium:"Medium priority",low:"Low priority"},eO=({todo:e})=>{const t=String(e.status||"pending"),n=String(e.priority||"medium"),r=$y[t]||$y.pending,s=qy[t]??qy.pending,o=Wy[n]??Wy.medium,i=t==="in_progress"?c.jsx(V,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]","aria-hidden":"true"}):t==="completed"?c.jsx(V,{name:"checkbox-circle",className:"h-3.5 w-3.5 text-[var(--status-success)]","aria-hidden":"true"}):c.jsx(V,{name:"time",className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":"true"});return c.jsxs("div",{className:"flex items-center min-w-0 py-0.5 gap-2",children:[c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx("span",{className:"flex-shrink-0",children:i})}),c.jsx(Ct,{side:"left",sideOffset:6,children:s})]}),c.jsx("span",{className:R("flex-1 typography-ui-label",r.textClassName),children:e.content}),c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx("span",{className:R("typography-meta flex items-center justify-center flex-shrink-0 leading-none",zy[n]??zy.medium),children:Uy[n]??Uy.medium})}),c.jsx(Ct,{side:"right",sideOffset:6,children:o})]})]})},tO=[],J3=({isWorking:e=!1,statusText:t=null,isGenericStatus:n,isWaitingForPermission:r,wasAborted:s,abortActive:o,retryInfo:i,showAbort:a,onAbort:l,showAbortStatus:d,showAssistantStatus:f=!0,showTodos:u=!0,agentName:h,modelName:m,providerId:g,leftAccessory:x,turnStartedAt:b=null})=>{const[S,y]=p.useState(!1),v=he(P=>P.currentSessionId),C=tO,w=re(P=>P.isMobile),{enabled:I}=mu(),E=w&&!I,T=E,A=p.useMemo(()=>C.filter(P=>P.status!=="cancelled"),[C]),j=p.useMemo(()=>A.find(P=>P.status==="in_progress")||A.find(P=>P.status==="pending")||null,[A]),k=p.useMemo(()=>{const P=C.filter(B=>B.status!=="cancelled").length;return{completed:C.filter(B=>B.status==="completed").length,total:P}},[C]),_=p.useMemo(()=>{const P=A.filter(B=>B.status==="in_progress").length,q=A.filter(B=>B.status==="in_progress"||B.status==="pending").length;return{active:P,left:q}},[A]),M=u&&_.left>0,L=f&&(e||!!s||!!d),O=!!x,N=!d&&(s||!o),D=L||M||O,W=p.useRef(null);p.useEffect(()=>{if(!S)return;const P=q=>{W.current&&!W.current.contains(q.target)&&y(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[S]);const z=()=>y(P=>!P),X=`${_.active} active · ${_.left} left`,F=a&&l?c.jsx("button",{type:"button",onClick:l,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:c.jsx(V,{name:"close-circle","aria-hidden":"true"})}):null,U=M?c.jsxs("button",{type:"button",onClick:z,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground","aria-label":X,title:X,children:[!T&&j?c.jsx("span",{className:"status-row__active-todo typography-ui-label text-foreground truncate max-w-[200px]",children:j.content}):c.jsx("span",{className:"typography-ui-label",children:"Tasks"}),c.jsxs("span",{className:"typography-meta flex items-center gap-1 tabular-nums","aria-hidden":"true",children:[c.jsxs("span",{className:"flex items-center gap-0.5",children:[c.jsx(V,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]"}),_.active]}),c.jsx("span",{children:"·"}),c.jsxs("span",{className:"flex items-center gap-0.5",children:[c.jsx(V,{name:"time",className:"h-3.5 w-3.5"}),_.left]})]}),S?c.jsx(V,{name:"arrow-up-s",className:"h-3.5 w-3.5"}):c.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5"})]}):null;return D?c.jsx("div",{className:R("mb-1",E&&"mt-2",!O&&"chat-column"),style:QD,children:c.jsxs("div",{className:R("flex min-h-5 items-center justify-between gap-2 py-0.5",O&&"px-0.5"),children:[c.jsx("div",{className:R("flex min-w-0 flex-1 items-center gap-2",O?"pl-1.5":"overflow-x-hidden"),children:f&&d?c.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-0.5",children:c.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[c.jsx(V,{name:"close-circle","aria-hidden":"true"}),"Aborted"]})}):f&&N?c.jsx(X3,{isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:i,agentName:h,modelName:m,providerId:g,startedAt:b},`${v??"no-session"}:${b??"no-start"}`):x||null}),c.jsxs("div",{className:R("relative flex items-center gap-2 flex-shrink-0",O?"pr-1.5":"-mr-3"),ref:W,children:[F,U,S&&M&&c.jsxs("div",{style:{maxWidth:"min(28rem, calc(100cqw - 4ch))",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:R("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px] rounded-xl p-1","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)]","dark: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)]","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[c.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 typography-ui-label font-medium text-muted-foreground",children:[c.jsx("span",{children:"Tasks"}),c.jsxs("span",{className:"typography-meta tabular-nums",children:[k.completed,"/",k.total]})]}),c.jsx("div",{className:"px-1 max-h-[200px] overflow-y-auto",children:A.map((P,q)=>c.jsx(eO,{todo:P},P.id??`todo-${q}`))})]})]})]})}):null},nO=1e4,rO=6e4,sO=5e3,oO=15e3,iO=3e4,aO=6e4,Ky=5*6e4,cO=3e4,lO=10,Gy=25,dO=40,uO=2,Zy=15e3,fO=500,hO=30,Md=20*1024*1024,Yy=200,Xy=e=>JSON.stringify({from:e.from??null,to:e.to??null,all:e.all??!1,file:e.file??null,maxCount:e.maxCount??null}),Nt=()=>({isGitRepo:null,status:null,branches:null,log:null,remotes:null,remoteUrl:null,lastRemotesFetch:0,isLoadingRemotes:!1,logQueryCache:new Map,diffCache:new Map,indexRevision:0,lastRepoCheckAt:0,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,lastBranchesFetch:0,logMaxCount:25,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1}),Jy="oc.gitBranchCache",Vl="oc.gitBranchCache.v2",pO=8,mO=50,lh=()=>({version:2,legacyClaimed:!1,runtimes:{}}),Q3=e=>{try{const t=Gt(),n=t.getItem(Vl),r=n?JSON.parse(n):lh(),s=r?.version===2&&r.runtimes&&typeof r.runtimes=="object"?{version:2,legacyClaimed:!!r.legacyClaimed,runtimes:r.runtimes}:lh();if(!s.legacyClaimed){const o=t.getItem(Jy);if(o){const a=JSON.parse(o),l={};for(const[d,f]of Object.entries(a??{}))d&&f&&Array.isArray(f.all)&&(l[d]={branches:f,updatedAt:0});Object.keys(l).length>0&&(s.runtimes[e]={updatedAt:0,directories:l})}s.legacyClaimed=!0;const i=JSON.stringify(s);t.setItem(Vl,i),t.getItem(Vl)===i&&t.removeItem(Jy)}return s}catch{return lh()}},gO=(e,t,n)=>{if(!(!t||!n))try{const r=Q3(e),s=Date.now(),i={...r.runtimes[e]?.directories??{},[t]:{branches:n,updatedAt:s}},a=Object.fromEntries(Object.entries(i).sort(([,l],[,d])=>d.updatedAt-l.updatedAt).slice(0,mO));r.runtimes[e]={updatedAt:s,directories:a},r.runtimes=Object.fromEntries(Object.entries(r.runtimes).sort(([,l],[,d])=>d.updatedAt-l.updatedAt).slice(0,pO)),Gt().setItem(Vl,JSON.stringify(r))}catch{}},Qy=e=>{const t=new Map,n=Q3(e).runtimes[e]?.directories??{};for(const[r,s]of Object.entries(n)){const o=s.branches;!r||!o||!Array.isArray(o.all)||t.set(r,{...Nt(),isGitRepo:!0,branches:o})}return t},e4=e=>{const t=new TextEncoder;return t.encode(e.original??"").byteLength+t.encode(e.modified??"").byteLength},ev=(e,t=hO,n=Md)=>{let r=0;for(const a of e.values())r+=new TextEncoder().encode(a.original??"").byteLength+new TextEncoder().encode(a.modified??"").byteLength;if(e.size<=t&&r<=n)return e;const s=Array.from(e.entries()).sort((a,l)=>a[1].fetchedAt-l[1].fetchedAt),o=new Map;let i=0;for(let a=s.length-1;a>=0;a--){const[l,d]=s[a],f=new TextEncoder().encode(d.original??"").byteLength+new TextEncoder().encode(d.modified??"").byteLength;if(o.size>=t)break;i+f>n||(o.set(l,d),i+=f)}return o},tv=e=>{const t=[];let n=0;for(const[o,i]of e)for(const[a,l]of i.diffCache){const d=e4(l);t.push({directory:o,path:a,fetchedAt:l.fetchedAt,size:d}),n+=d}if(t.length<=Yy&&n<=Md)return e;const r=new Map(e);t.sort((o,i)=>o.fetchedAt-i.fetchedAt);let s=t.length;for(const o of t){if(s<=Yy&&n<=Md)break;const i=r.get(o.directory);if(!i?.diffCache.has(o.path))continue;const a=new Map(i.diffCache);a.delete(o.path),r.set(o.directory,{...i,diffCache:a}),s-=1,n-=o.size}return r},yO=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n){const s=e[r],o=t[r];if(!(!s&&!o)&&(!s||!o||s.insertions!==o.insertions||s.deletions!==o.deletions))return!0}return!1},vO=(e,t)=>!e&&!t?!1:!e||!t?!0:e.remote!==t.remote||e.branch!==t.branch||e.ahead!==t.ahead||e.behind!==t.behind,xO=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=e.files??[],r=t.files??[];if(n.length!==r.length||e.ahead!==t.ahead||e.behind!==t.behind||e.current!==t.current||e.tracking!==t.tracking||e.isClean!==t.isClean||t.upstreamComparison!==void 0&&vO(e.upstreamComparison,t.upstreamComparison))return!0;const s=new Set(n.map(o=>`${o.path}:${o.index}:${o.working_dir}`));for(const o of r)if(!s.has(`${o.path}:${o.index}:${o.working_dir}`))return!0;return!!(t.diffStats!==void 0&&yO(e.diffStats,t.diffStats))},bO=(e,t)=>{const n=new Set;if(!t)return n;const r=e?.files??[],s=t.files??[],o=new Map(r.map(l=>[l.path,l])),i=new Map(s.map(l=>[l.path,l])),a=new Set([...o.keys(),...i.keys()]);for(const l of a){const d=o.get(l),f=i.get(l);if(!d||!f){n.add(l);continue}if(d.index!==f.index||d.working_dir!==f.working_dir){n.add(l);continue}}if(t.diffStats!==void 0){const l=e?.diffStats??{},d=t.diffStats??{},f=new Set([...Object.keys(l),...Object.keys(d)]);for(const u of f){const h=l[u],m=d[u];if(!h||!m){n.add(u);continue}(h.insertions!==m.insertions||h.deletions!==m.deletions)&&n.add(u)}}return n},wO=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=e.files??[],r=t.files??[],s=l=>{const d=l?.trim()??"";return d==="?"?"":d},o=new Map(n.map(l=>[l.path,s(l.index)])),i=new Map(r.map(l=>[l.path,s(l.index)])),a=new Set([...o.keys(),...i.keys()]);for(const l of a)if((o.get(l)??"")!==(i.get(l)??""))return!0;return!1},nv=e=>!e||e.trim().length===0,Id=e=>(e||"").trim()==="U",SO=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return Id(t)||Id(n)?e:{...e,index:t==="?"||n==="?"?"A":t||n||" ",working_dir:" "}},CO=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return Id(t)||Id(n)?e:{...e,index:" ",working_dir:n||(t==="A"||t==="?"?"?":t)||" "}},kO=e=>nv(e.index)&&nv(e.working_dir),Fp=new Map,A1=new Map,lo=new Map,$i=new Map,zi=new Map,Ui=new Map,qi=new Map,Wi=new Map,Ed=new Map,Na=new Map;let N1=0,L1=Y();const MO=()=>L1,IO=e=>{N1+=1,L1=e,Ed.clear(),Na.clear(),lo.clear(),$i.clear(),zi.clear(),Ui.clear(),qi.clear(),Wi.clear(),Fp.clear(),A1.clear()},hr=(e,t)=>JSON.stringify([e,t]),rv=(e,t,n)=>JSON.stringify([e,t,n]),EO=(e,t,n)=>JSON.stringify([e,t,n]),_O=(e,t,n)=>JSON.stringify([e,t,n]),jO=(e,t,n)=>JSON.stringify([e,t,n]),cs=(e,t,n=!1)=>{const r=Y(),s=jO(r,e,t),o=(Ed.get(s)??0)+1;return Ed.set(s,o),{runtimeKey:r,runtimeGeneration:N1,channelKey:s,requestGeneration:o,...n?{statusMutationRevision:Na.get(hr(r,e))??0}:{}}},yn=(e,t)=>e.runtimeKey===Y()&&e.runtimeKey===L1&&e.runtimeGeneration===N1&&Ed.get(e.channelKey)===e.requestGeneration&&(e.statusMutationRevision===void 0||e.statusMutationRevision===(Na.get(hr(e.runtimeKey,t))??0)),dh=(e,t)=>{const n=hr(e,t);Na.set(n,(Na.get(n)??0)+1)},$l=e=>A1.get(hr(Y(),e))??0,tl=e=>{const t=$l(e)+1;return A1.set(hr(Y(),e),t),t},TO=e=>{const t=hr(Y(),e),n=Fp.get(t);if(n)return n;const r=new Set;return Fp.set(t,r),r},sv=MO(),vt=Et()(gr((e,t)=>({runtimeKey:sv,directories:Qy(sv),activeDirectory:null,resetForRuntimeSwitch:n=>{IO(n),e({runtimeKey:n,directories:Qy(n),activeDirectory:null})},setActiveDirectory:n=>{const{activeDirectory:r,directories:s}=t();if(r!==n)if(r&&tl(r),n&&tl(n),n&&!s.has(n)){const o=new Map(s);o.set(n,Nt()),e({activeDirectory:n,directories:o})}else e({activeDirectory:n})},getDirectoryState:n=>t().directories.get(n)??null,fetchStatus:async(n,r,s={})=>{const o=s.mode??"full",i=Y(),a=rv(i,n,o),l=lo.get(a)??(o==="light"?lo.get(rv(i,n,"full")):void 0);if(l)return l;const d=cs(n,"status",!0),f=(async()=>{const{silent:u=!1}=s,{directories:h}=t();let m=h.get(n);if(m||(m=Nt()),!u){const x=new Map(t().directories),b=x.get(n)??Nt();x.set(n,{...b,isLoadingStatus:!0}),e({directories:x})}let g=!1;try{const x=Date.now(),b=m.isGitRepo!==!0||x-(m.lastRepoCheckAt||0)>rO;let S=m.isGitRepo===!0;if(b&&(S=await r.checkIsGitRepository(n),!yn(d,n)))return!1;if(!S){const C=new Map(t().directories),w=C.get(n)??m;return C.set(n,{...w,isGitRepo:!1,status:null,isLoadingStatus:!1,lastRepoCheckAt:x,lastStatusFetch:x}),e({directories:C}),!1}const y=await r.getGitStatus(n,s.mode?{mode:s.mode}:void 0);if(!yn(d,n))return!1;const v=t().directories.get(n)??Nt();if(xO(v.status,y)){g=!0;const C=new Map(t().directories),w=C.get(n)??Nt(),I=bO(w.status,y),E=wO(w.status,y),T=new Set((w.status?.files??[]).map(M=>M.path)),A=new Set((y.files??[]).map(M=>M.path)),j=new Map(w.diffCache);for(const M of T)A.has(M)||j.delete(M);for(const M of I)j.delete(M);const k=I.size>0;k&&tl(n);const _={...y,diffStats:y.diffStats===void 0&&w.status?.diffStats!==void 0?w.status.diffStats:y.diffStats,upstreamComparison:y.upstreamComparison===void 0?w.status?.upstreamComparison:y.upstreamComparison};C.set(n,{...w,isGitRepo:!0,status:_,diffCache:j,indexRevision:E?w.indexRevision+1:w.indexRevision,lastRepoCheckAt:b?x:w.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:k?Date.now():w.lastStatusChange}),e({directories:C})}else{const C=new Map(t().directories),w=C.get(n)??Nt();C.set(n,{...w,isGitRepo:!0,lastRepoCheckAt:b?x:w.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:w.lastStatusChange}),e({directories:C})}}catch(x){console.error("Failed to fetch git status:",x)}finally{if(!u&&yn(d,n)){const x=new Map(t().directories),b=x.get(n)??Nt();x.set(n,{...b,isLoadingStatus:!1}),e({directories:x})}}return g})();lo.set(a,f);try{return await f}finally{lo.get(a)===f&&lo.delete(a)}},moveStatusPathsOptimistically:(n,r,s)=>{const o=new Set(r.map(h=>h.trim()).filter(Boolean));if(o.size===0)return null;const{directories:i}=t(),a=i.get(n),l=a?.status??null;if(!a||!l)return l;let d=!1;const f=[];for(const h of l.files){if(!o.has(h.path)){f.push(h);continue}const m=s==="stage"?SO(h):CO(h);m!==h&&(d=!0),kO(m)?d=!0:f.push(m)}if(!d)return l;dh(t().runtimeKey,n);const u=new Map(i);return u.set(n,{...a,status:{...l,files:f,isClean:f.length===0},indexRevision:a.indexRevision+1,lastStatusChange:Date.now()}),e({directories:u}),l},restoreStatus:(n,r)=>{const{directories:s}=t(),o=s.get(n);if(!o)return;dh(t().runtimeKey,n);const i=new Map(s);i.set(n,{...o,status:r,indexRevision:o.indexRevision+1,lastStatusChange:Date.now()}),e({directories:i})},bumpIndexRevision:n=>{const{directories:r}=t(),s=r.get(n);if(!s)return;dh(t().runtimeKey,n);const o=new Map(r);o.set(n,{...s,indexRevision:s.indexRevision+1}),e({directories:o})},fetchBranches:async(n,r,s={})=>{const o=Y(),i=hr(o,n),a=$i.get(i);if(a)return a;const l=cs(n,"branches"),{silent:d=!1}=s,f=(async()=>{if(!d){const u=new Map(t().directories),h=u.get(n)??Nt();u.set(n,{...h,isLoadingBranches:!0}),e({directories:u})}try{const u=await r.getGitBranches(n);if(!yn(l,n))return;const h=new Map(t().directories),m=h.get(n)??Nt();h.set(n,{...m,branches:u,isLoadingBranches:!1,lastBranchesFetch:Date.now()}),e({directories:h}),gO(l.runtimeKey,n,u)}catch(u){if(console.error("Failed to fetch git branches:",u),!yn(l,n))return;const h=new Map(t().directories),m=h.get(n)??Nt();h.set(n,{...m,isLoadingBranches:!1}),e({directories:h})}})().finally(()=>{$i.get(i)===f&&$i.delete(i)});return $i.set(i,f),f},fetchLog:async(n,r,s,o={})=>{const{directories:i}=t(),a=i.get(n),l=s??a?.logMaxCount??25,d=Y(),f=EO(d,n,l),u=zi.get(f);if(u)return u;const h=cs(n,"log"),{silent:m=!1}=o,g=(async()=>{if(!m){const x=new Map(t().directories),b=x.get(n)??Nt();x.set(n,{...b,isLoadingLog:!0}),e({directories:x})}try{const x=await r.getGitLog(n,{maxCount:l});if(!yn(h,n))return;const b=new Map(t().directories),S=b.get(n)??Nt();b.set(n,{...S,log:x,isLoadingLog:!1,lastLogFetch:Date.now(),logMaxCount:l}),e({directories:b})}catch(x){if(console.error("Failed to fetch git log:",x),!yn(h,n))return;const b=new Map(t().directories),S=b.get(n)??Nt();b.set(n,{...S,isLoadingLog:!1}),e({directories:b})}})().finally(()=>{zi.get(f)===g&&zi.delete(f)});return zi.set(f,g),g},fetchRemotes:async(n,r,s={})=>{const o=r.getRemotes;if(typeof o!="function")return;const i=r.getRemoteUrl,a=Y(),l=hr(a,n),d=Ui.get(l);if(d)return d;const f=cs(n,"remotes"),{silent:u=!1}=s,h=(async()=>{if(!u){const m=new Map(t().directories),g=m.get(n)??Nt();m.set(n,{...g,isLoadingRemotes:!0}),e({directories:m})}try{const m=o(n),g=typeof i=="function"?i(n).then(v=>({ok:!0,value:v}),()=>({ok:!1,value:null})):Promise.resolve({ok:!0,value:null}),[x,b]=await Promise.all([m,g]);if(!yn(f,n))return;const S=new Map(t().directories),y=S.get(n)??Nt();S.set(n,{...y,remotes:x,remoteUrl:b.ok?b.value:y.remoteUrl,lastRemotesFetch:Date.now(),isLoadingRemotes:!1}),e({directories:S})}catch(m){if(console.error("Failed to fetch git remotes:",m),!yn(f,n))return;const g=new Map(t().directories),x=g.get(n)??Nt();g.set(n,{...x,isLoadingRemotes:!1}),e({directories:g})}})().finally(()=>{Ui.get(l)===h&&Ui.delete(l)});return Ui.set(l,h),h},ensureRemotes:async(n,r)=>{const s=t().directories.get(n),o=Date.now();s?.remotes!==null&&s?.remotes!==void 0&&o-(s?.lastRemotesFetch??0)<Ky||await t().fetchRemotes(n,r,{silent:s?.remotes!=null})},invalidateRemotes:n=>{const{directories:r}=t(),s=r.get(n);if(!s)return;const o=new Map(r);o.set(n,{...s,lastRemotesFetch:0}),e({directories:o})},fetchLogQuery:async(n,r,s,o={})=>{const{force:i=!1}=o,a=Xy(s),l=Y(),d=_O(l,n,a),f=Date.now(),u=t().directories.get(n)?.logQueryCache.get(a);if(!i&&u&&f-u.fetchedAt<cO)return u.log;const h=qi.get(d);if(h)return h;const m=cs(n,`log-query:${a}`),g=(async()=>{try{const x=await r.getGitLog(n,{maxCount:s.maxCount,from:s.from,to:s.to,all:s.all,file:s.file});if(!yn(m,n))return u?.log??null;const b=new Map(t().directories),S=b.get(n)??Nt(),y=new Map(S.logQueryCache);if(y.set(a,{log:x,fetchedAt:Date.now()}),y.size>lO){let v=null,C=Number.POSITIVE_INFINITY;for(const[w,I]of y)I.fetchedAt<C&&(C=I.fetchedAt,v=w);v!==null&&y.delete(v)}return b.set(n,{...S,logQueryCache:y}),e({directories:b}),x}catch(x){return console.error("Failed to fetch git log query:",x),u?.log??t().directories.get(n)?.logQueryCache.get(a)?.log??null}})().finally(()=>{qi.get(d)===g&&qi.delete(d)});return qi.set(d,g),g},getCachedLogQuery:(n,r)=>{const s=Xy(r);return t().directories.get(n)?.logQueryCache.get(s)?.log??null},fetchAll:async(n,r,s={})=>{const{directories:o}=t();let i=o.get(n);if(!i){i=Nt();const h=new Map(o);h.set(n,i),e({directories:h})}const{force:a=!1,silentIfCached:l=!1}=s,d=Date.now();await t().fetchStatus(n,r,{silent:l&&!!i?.status});const f=t().directories.get(n);if(!f?.isGitRepo)return;await t().fetchBranches(n,r);const u=d-(f.lastLogFetch||0);(a||u>nO||!f.log)&&await t().fetchLog(n,r)},getDiff:(n,r)=>t().directories.get(n)?.diffCache.get(r)??null,setDiff:(n,r,s,o)=>{if(o&&o!==t().runtimeKey||e4(s)>Md)return;const i=new Map(t().directories),a=i.get(n)??Nt(),l=new Map(a.diffCache);l.set(r,{...s,fetchedAt:Date.now()});const d=ev(l);i.set(n,{...a,diffCache:d}),e({directories:tv(i)})},clearDiffCache:(n,r)=>{tl(n),cs(n,"diff");const s=new Map(t().directories),o=s.get(n);if(!o||o.diffCache.size===0)return;const i=new Map(o.diffCache);if(r)for(const a of r)i.delete(a);else i.clear();i.size!==o.diffCache.size&&(s.set(n,{...o,diffCache:i}),e({directories:s}))},fetchAllDiffs:async(n,r)=>{const s=t().directories.get(n);if(!s?.status?.files||s.status.files.length===0)return;const o=s.status.files.map(i=>i.path).slice(0,Gy);await t().prefetchDiffs(n,r,o,{maxFiles:Gy})},prefetchDiffs:async(n,r,s,o={})=>{const i=cs(n,"diff"),a=t().directories.get(n);if(!a?.status?.files||a.status.files.length===0||s.length===0)return;const{maxFiles:l=dO}=o,d=new Set(a.status.files.map(k=>k.path)),f=a.status.diffStats,u=TO(n),h=[],m=new Set;for(const k of s){if(!k||m.has(k)||(m.add(k),!d.has(k))||a.diffCache.has(k)||u.has(k))continue;const _=f?.[k];_&&_.insertions+_.deletions>fO||h.push(k)}const g=h.slice(0,Math.max(1,l));if(g.length===0)return;const x=$l(n);if(typeof document<"u"&&document.hidden)return;g.forEach(k=>u.add(k));let b=0;const S=[],y=()=>{const k=b;return b+=1,k<g.length?g[k]:null},v=async k=>{const _=r.getGitFileDiff(n,{path:k}),M=new Promise((O,N)=>{setTimeout(()=>N(new Error(`Timed out after ${Zy}ms`)),Zy)}),L=await Promise.race([_,M]);return{path:k,diff:{original:L.original??"",modified:L.modified??"",isBinary:L.isBinary}}},C=async()=>{for(;;){if(x!==$l(n)||!yn(i,n))return;const k=y();if(!k)return;try{S.push(await v(k))}catch{}finally{u.delete(k)}}},w=Math.min(uO,g.length);if(await Promise.allSettled(Array.from({length:w},()=>C())),g.forEach(k=>u.delete(k)),x!==$l(n)||!yn(i,n))return;const I=new Map(t().directories),E=I.get(n);if(!E)return;const T=new Map(E.diffCache),A=Date.now();S.forEach(k=>{T.set(k.path,{...k.diff,fetchedAt:A})});const j=ev(T);I.set(n,{...E,diffCache:j}),e({directories:tv(I)})},setLogMaxCount:(n,r)=>{const s=new Map(t().directories),o=s.get(n)??Nt();s.set(n,{...o,logMaxCount:r}),e({directories:s})},ensureStatus:async(n,r)=>{const s=t().directories.get(n),o=Date.now();s?.status&&o-s.lastStatusFetch<sO||await t().fetchStatus(n,r,{silent:!!s?.status})},ensureAll:(n,r)=>{const s=hr(Y(),n),o=Wi.get(s);if(o)return o;const i=(async()=>{const a=t().directories.get(n),l=Date.now();(!a?.status||a.status.diffStats===void 0||l-(a?.lastStatusFetch??0)>=oO)&&await t().fetchStatus(n,r,{silent:!!a?.status});const f=t().directories.get(n);if(!f?.isGitRepo)return;const u=[];(!f.branches||l-f.lastBranchesFetch>=aO)&&u.push(t().fetchBranches(n,r,{silent:!!f.branches})),(!f.log||l-f.lastLogFetch>=iO)&&u.push(t().fetchLog(n,r,void 0,{silent:!!f.log})),(f.remotes==null||l-(f.lastRemotesFetch??0)>=Ky)&&u.push(t().fetchRemotes(n,r,{silent:f.remotes!=null})),u.length>0&&await Promise.all(u)})();return Wi.set(s,i),i.finally(()=>{Wi.get(s)===i&&Wi.delete(s)}),i},refresh:async(n,r={})=>{const{activeDirectory:s}=t();s&&await t().fetchAll(s,n,r)}}),{name:"git-store"})),AO=e=>vt(t=>e?t.directories.get(e)?.status??null:null),t4=e=>vt(t=>e?t.directories.get(e)?.branches??null:null),NO=e=>vt(t=>e?t.directories.get(e)?.log??null:null),LO=e=>vt(t=>e?t.directories.get(e)?.remotes??null:null),RO=e=>vt(t=>e?t.directories.get(e)?.remoteUrl??null:null),PO=e=>vt(t=>e?t.directories.get(e)?.isLoadingRemotes??!1:!1),ku=e=>vt(t=>e?t.directories.get(e)?.isGitRepo??null:null),DO=e=>vt(t=>e?t.directories.get(e)?.status?.current?.trim()??null:null),ov={current:new Map},OO=new Map,HO=(e=!0)=>vt(t=>{if(!e)return OO;const n=ov.current;let r=n.size===t.directories.size;if(r){for(const[o,i]of t.directories)if(n.get(o)!==(i.status?.current??null)){r=!1;break}}if(r)return n;const s=new Map;for(const[o,i]of t.directories)s.set(o,i.status?.current??null);return ov.current=s,s}),FO=e=>{const t=p.useRef(new Map);return vt(n=>{const r=t.current;let s=r.size===e.length;if(s)for(const i of e){const a=n.directories.get(i),l=r.get(i);if(!l||(a?.isGitRepo??null)!==l.isGitRepo||(a?.status?.current??null)!==l.branch){s=!1;break}}if(s)return r;const o=new Map;for(const i of e){const a=n.directories.get(i);o.set(i,{isGitRepo:a?.isGitRepo??null,branch:a?.status?.current??null})}return t.current=o,o})},BO=e=>vt(t=>e?t.directories.get(e)?.isLoadingStatus??!1:!1),VO=e=>vt(t=>e?t.directories.get(e)?.isLoadingLog??!1:!1),$O=e=>vt(t=>e?t.directories.get(e)?.isLoadingBranches??!1:!1),XJ=Object.freeze(Object.defineProperty({__proto__:null,useGitAllBranches:HO,useGitBranchLabel:DO,useGitBranches:t4,useGitLoadingBranches:$O,useGitLoadingLog:VO,useGitLoadingRemotes:PO,useGitLoadingStatus:BO,useGitLog:NO,useGitRemoteUrl:RO,useGitRemotes:LO,useGitRepoStatusMap:FO,useGitStatus:AO,useGitStore:vt,useIsGitRepo:ku},Symbol.toStringTag,{value:"Module"})),n4=p.createContext(null),JJ=({actions:e,children:t})=>c.jsx(n4.Provider,{value:e,children:t}),Ga=()=>p.useContext(n4),zO=/^[A-Za-z]:\/$/,R1=/^[A-Za-z]:\//,Wt=e=>{if(typeof e!="string")return"";const t=e.trim();if(!t)return"";const n=t.replace(/\\/g,"/"),r=n.startsWith("//");let s=n.replace(/\/+/g,"/");r&&!s.startsWith("//")&&(s=`/${s}`);const o=s==="/",i=zO.test(s);return!o&&!i&&(s=s.replace(/\/+$/,"")),s},UO=e=>{const t=Wt(e);return t.startsWith("/")||R1.test(t)},_d=e=>{const t=Wt(e);return R1.test(t)||t.startsWith("//")?t.toLowerCase():t},r4=e=>e.split("/").filter(Boolean),qO=(e,t)=>{const n=[...e];for(const r of r4(t))if(r!=="."){if(r===".."){n.length>0&&n.pop();continue}n.push(r)}return n},Za=(e,t)=>{const n=Wt(t);if(!n)return Wt(e);if(UO(n))return n;const r=Wt(e);if(!r)return n;const s=R1.test(r)?r.slice(0,2):"",o=r.startsWith("//"),i=r.startsWith("/")&&!o,a=s?r.slice(2):r,d=qO(r4(a),n).join("/");return s?d?`${s}/${d}`:`${s}/`:o?`//${d}`:i?`/${d}`:d},Mu=(e,t)=>{const n=Wt(e),r=Wt(t);if(!n||!r)return!1;const s=_d(n),o=_d(r);return s===o||s.startsWith(`${o}/`)},s4=(e,t)=>{const n=Wt(e),r=Wt(t);return n?r?_d(n)===_d(r)?".":Mu(n,r)?n.slice(r.length+1):n:n:""},uh=(e,t)=>{const n=Wt(e),r=Wt(t);if(n&&(!r||Mu(r,n))||!r)return n;const s=r.lastIndexOf("/");return s===0?"/":s<0?n||r:/^[A-Za-z]:\//.test(r)&&s===2?r.slice(0,3):r.slice(0,s)},WO=new Set(["edit","multiedit","write","apply_patch","create","file_write"]),P1=e=>"insertions"in e,Qs=e=>{if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.trunc(e))},KO=e=>{let t=0,n=0;for(const r of e.split(`
|
|
71
|
+
`))r.startsWith("+")&&!r.startsWith("+++")&&t++,r.startsWith("-")&&!r.startsWith("---")&&n++;return{added:t,removed:n}},QJ=e=>{const t=[],n=new Set;for(const r of e){if(r.type!=="tool"||!r.tool||!WO.has(r.tool))continue;const s=r.tool,o=r.messageId??r.messageID??"",i=r.state;if(i?.status&&i.status!=="completed")continue;const a=t.length,l=i?.metadata,d=Array.isArray(l?.files)?l.files:[];for(const f of d){if(!f||typeof f!="object")continue;const u=f,h=u.relativePath||u.filePath||"";!h||n.has(h)||(n.add(h),t.push({path:h,tool:s,partId:r.id,messageID:o,additions:Qs(u.additions)??void 0,deletions:Qs(u.deletions)??void 0,patch:typeof u.patch=="string"?u.patch:void 0}))}if(d.length===0&&l?.filediff&&typeof l.filediff=="object"){const f=l.filediff,u=typeof f.file=="string"?f.file:"";u&&!n.has(u)&&(n.add(u),t.push({path:u,tool:s,partId:r.id,messageID:o,additions:Qs(f.additions)??void 0,deletions:Qs(f.deletions)??void 0,patch:typeof f.patch=="string"?f.patch:void 0}))}if(d.length===0&&Array.isArray(l?.results))for(const f of l.results){if(!f||typeof f!="object")continue;const u=f.filediff;if(!u||typeof u!="object")continue;const h=typeof u.file=="string"?u.file:"";!h||n.has(h)||(n.add(h),t.push({path:h,tool:s,partId:r.id,messageID:o,additions:Qs(u.additions)??void 0,deletions:Qs(u.deletions)??void 0,patch:typeof u.patch=="string"?u.patch:void 0}))}if(t.length===a){const f=i?.input,u=typeof f?.filePath=="string"?f.filePath:typeof f?.file_path=="string"?f.file_path:typeof f?.path=="string"?f.path:void 0;u&&!n.has(u)&&(n.add(u),t.push({path:u,tool:s,partId:r.id,messageID:o}))}if(t.length===a){const f=typeof l?.patch=="string"?l.patch.trim():typeof l?.diff=="string"?l.diff.trim():"";if(f&&!n.has("Diff")){n.add("Diff");const u=KO(f);t.push({path:"Diff",tool:s,partId:r.id,messageID:o,additions:u.added,deletions:u.removed})}}}return t},o4=(e,t,n)=>{const r=[];for(const s of e){const o=s.index?.trim()??"",i=s.working_dir?.trim()??"",a=!!(o&&o!=="?"),l=!!(i||o==="?"),d=i||o;if(!d||d==="!")continue;const f=t?.[s.path];r.push({path:Za(n,s.path),relativePath:s.path,insertions:f?.insertions??0,deletions:f?.deletions??0,status:d,hasStagedChanges:a,hasWorkingChanges:l})}return r},GO=(e,t)=>s4(e,t),ZO=(e,t)=>{const n=P1(e)&&e.relativePath?e.relativePath:GO(e.path,t),r=n.split("/").pop()??n,s=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";return{fileName:r,dirPart:s}},YO=e=>P1(e)?{additions:e.insertions,deletions:e.deletions}:{additions:e.additions??0,deletions:e.deletions??0},XO=({files:e,currentDirectory:t,onOpenFile:n})=>c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 typography-ui-label font-medium text-muted-foreground",children:[c.jsx("span",{children:"Changed files"}),c.jsx("span",{className:"typography-meta tabular-nums",children:e.length})]}),c.jsx("div",{className:"max-h-[260px] overflow-y-auto",children:e.map((r,s)=>{const{fileName:o,dirPart:i}=ZO(r,t),a=YO(r);return c.jsxs("button",{type:"button",className:"relative flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none text-left hover:bg-interactive-hover",title:`Open ${r.path}`,onClick:()=>n(r),children:[c.jsx(pr,{filePath:r.path,className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 flex items-baseline overflow-hidden",title:r.path,children:i?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 truncate text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsxs("span",{className:"flex-shrink-0",children:[c.jsx("span",{className:"text-muted-foreground",children:"/"}),c.jsx("span",{className:"text-foreground",children:o})]})]}):c.jsx("span",{className:"truncate text-foreground",children:o})}),a.additions>0||a.deletions>0?c.jsxs("span",{className:"flex-shrink-0 inline-flex items-baseline gap-1 typography-micro tabular-nums",children:[a.additions>0?c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",a.additions]}):null,a.deletions>0?c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a.deletions]}):null]}):null]},`${r.path}:${s}`)})})]}),i4="w-max min-w-[280px] max-w-full rounded-xl p-1 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)] dark: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)] origin-[var(--transform-origin)]",a4={maxWidth:"calc(100cqw - 4ch)",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},c4=p.memo(({align:e="start"})=>{const[t,n]=p.useState(!1),r=p.useRef(null),s=Jn()??null,o=p.useContext($a),i=ku(s),a=vt(C=>s?C.directories.get(s)?.status??null:null),l=Ga(),d=re(C=>C.isMobile),{enabled:f}=mu(),u=d&&!f;p.useEffect(()=>{if(!t)return;const C=w=>{r.current&&!r.current.contains(w.target)&&n(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[t]);const h=p.useMemo(()=>!s||i!==!0||!a||a.isClean?[]:o4(a.files,a.diffStats,s),[i,a,s]),{totalAdded:m,totalRemoved:g}=p.useMemo(()=>{let C=0,w=0;for(const I of h)C+=I.insertions,w+=I.deletions;return{totalAdded:C,totalRemoved:w}},[h]);if(!s||i!==!0||h.length===0)return null;const x=C=>{if(!s||!P1(C))return;n(!1);const w=C.path;if(l){l.openChanges({diffPath:C.relativePath,staged:C.hasStagedChanges&&!C.hasWorkingChanges});return}const I=o?.editor;if(I){I.openFile(w);return}const E=re.getState(),T=C.hasStagedChanges&&!C.hasWorkingChanges;if(!E.isMobile){E.openContextDiff(s,C.relativePath,T);return}E.navigateToDiff(C.relativePath,T)},b=h.length,S=b===1?`${b} file`:`${b} files`,y=b===1?"1 change":`${b} changes`,v=c.jsxs(c.Fragment,{children:[c.jsx(V,{name:"git-branch",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),u?c.jsx("span",{className:"min-w-0 shrink-0 text-foreground typography-meta",children:y}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 shrink-0 text-foreground typography-meta",children:S}),c.jsx("span",{className:"status-row__changed-label min-w-0 typography-meta text-foreground truncate",children:"changed"})]}),c.jsxs("span",{className:"inline-flex shrink-0 items-baseline gap-1 typography-meta tabular-nums",children:[m>0?c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",m]}):null,g>0?c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",g]}):null]}),t?c.jsx(V,{name:"arrow-up-s",className:"h-3.5 w-3.5 shrink-0"}):c.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5 shrink-0"})]});return c.jsxs("div",{className:"relative",ref:r,children:[c.jsx("button",{type:"button",className:"flex min-w-0 max-w-full items-center gap-1 text-left text-muted-foreground",onClick:()=>n(C=>!C),"aria-expanded":t,children:v}),t&&c.jsx("div",{style:{...a4,maxWidth:"min(28rem, calc(100cqw - 4ch))"},className:R(i4,"absolute bottom-full mb-1 z-50",e==="end"?"right-0":"left-0","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:c.jsx(XO,{files:h,currentDirectory:s,onOpenFile:x})})]})});c4.displayName="PendingChangesBar";const JO=p.createContext("default"),Iu=()=>p.useContext(JO);let Bp=!1;const Vp=new Set,jd=()=>Bp,eQ=e=>{if(Bp!==e){Bp=e;for(const t of[...Vp])try{t()}catch{}}},QO=e=>(Vp.add(e),()=>{Vp.delete(e)}),l4=()=>p.useSyncExternalStore(QO,jd,jd);function eH({className:e,style:t,...n}){return c.jsx(Ds,{"data-slot":"command",style:{color:"var(--surface-elevated-foreground)",...t},className:R("flex h-full w-full flex-col overflow-hidden rounded-xl",e),...n})}const d4=H.forwardRef(({className:e,...t},n)=>c.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[c.jsx(V,{name:"search",className:"size-4 shrink-0 opacity-50"}),c.jsx(Ds.Input,{ref:n,"data-slot":"command-input",className:R("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));d4.displayName="CommandInput";function tH({className:e,children:t,scrollbarClassName:n,disableHorizontal:r,...s}){return c.jsx(Xn,{as:Ds.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:R("scroll-py-1 overflow-x-hidden h-full min-h-0",e),scrollbarClassName:n??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:r??!0,...s,children:t})}function nH({...e}){return c.jsx(Ds.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...e})}function rH({className:e,...t}){return c.jsx(Ds.Group,{"data-slot":"command-group",className:R("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]]:text-[length:var(--text-meta)] [&_[cmdk-group-heading]]:font-medium",e),...t})}function tQ({className:e,...t}){return c.jsx(Ds.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",e),...t})}function sH({className:e,...t}){return c.jsx(Ds.Item,{"data-slot":"command-item",className:R("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",e),...t})}function nQ({className:e,...t}){const n=o=>{const i=o.trim().toLowerCase();return i==="ctrl"||i==="control"?c.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?c.jsx(V,{name:"command",className:"size-3.5"}):i==="⇧"?c.jsx(V,{name:"arrow-up",className:"size-3.5"}):c.jsx("span",{className:"text-xs font-medium",children:o})},r=typeof t.children=="string"?t.children:"",s=r?r.split("+").map(o=>o.trim()).filter(Boolean):[];return c.jsx("span",{"data-slot":"command-shortcut",className:R("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",e),...t,children:s.length>0?s.map((o,i)=>c.jsxs(H.Fragment,{children:[i>0&&c.jsx("span",{className:"text-xs text-subtle-foreground",children:"+"}),n(o)]},`${o}-${i}`)):t.children})}const fh=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.code==="SESSION_BUSY"||typeof t.message=="string"&&t.message.includes("SESSION_BUSY")},rQ=e=>!!(e&&typeof e=="object"&&e.deferred===!0),sQ=e=>`${e} saved. It will apply when active sessions are idle.`,oQ=e=>`${e} could not be changed while a session is running. Try again when it finishes.`,oH=5e3,jn=new Map,Nr=new Map,Tr=new Map,ma=new Map,vo=(e,t)=>`${e}
|
|
72
|
+
${t?.trim()??""}`,Po=e=>{ma.set(e,(ma.get(e)??0)+1),Nr.delete(e)},iQ=e=>{const t=Y();if(typeof e=="string"&&e.trim().length>0){const r=vo(t,e);jn.delete(r),Po(r);return}const n=new Set([...jn.keys(),...Nr.keys(),...Tr.keys()]);for(const r of n)r.startsWith(`${t}
|
|
73
|
+
`)&&(jn.delete(r),Po(r))},hh=e=>{const t=new Set([...jn.keys(),...Nr.keys(),...Tr.keys()]);for(const n of t)n.startsWith(`${e}
|
|
74
|
+
`)&&(jn.delete(n),Po(n))},nl=e=>e.prompts.map(t=>({id:t.id,name:t.name,...typeof t.description=="string"?{description:t.description}:{},...typeof t.content=="string"?{content:t.content}:{},location:["global","project","package","path"].includes(t.location)?t.location:"path",editable:t.editable===!0})),zl=Et()(gr((e,t)=>({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null,setSelectedPrompt:n=>e({selectedPromptId:n}),setPromptDraft:n=>e({promptDraft:n}),resetForRuntimeSwitch:()=>{jn.clear(),Nr.clear(),Tr.clear(),ma.clear(),e({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null})},loadPrompts:async n=>{const r=Y(),s=typeof n=="string"&&n.trim().length>0?n.trim():void 0,o=vo(r,s),i=Date.now(),a=Tr.get(o);e({activeCacheKey:o,prompts:a??[],isLoading:!0});const l=jn.get(o)??0;if(l>0&&i-l<oH)return e({isLoading:!1}),!0;const d=Nr.get(o);if(d)return d;const f=ma.get(o)??0,u=(async()=>{try{const h=s?await Ie.listResources(s,{runtimeKey:r}):await Ie.listResources({runtimeKey:r});if(Y()!==r)return!1;if((ma.get(o)??0)!==f)return e(g=>g.activeCacheKey===o?{isLoading:!1}:g),!0;const m=nl(h);return Tr.set(o,m),jn.set(o,Date.now()),e(g=>g.activeCacheKey===o?{prompts:m,isLoading:!1,...g.selectedPromptId&&!m.some(x=>x.id===g.selectedPromptId)?{selectedPromptId:null}:{}}:g),!0}catch{return e(h=>h.activeCacheKey===o?{isLoading:!1}:h),!1}})();Nr.set(o,u);try{return await u}finally{Nr.get(o)===u&&Nr.delete(o)}},createPrompt:async(n,r,s)=>{const o=Y(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await Ie.createPromptTemplate({name:n,description:s.description,content:r,location:s.location},i,{runtimeKey:o});if(Y()!==o)return a.deferred===!0?"deferred":!0;const l=vo(o,i),d=nl(a);Po(l),Tr.set(l,d),hh(o),jn.set(l,Date.now());const f=d.find(u=>u.name===n&&u.location===s.location);return e(u=>u.activeCacheKey===l?{prompts:d,promptDraft:null,selectedPromptId:f?.id??null,isLoading:!1}:u),bl(s.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return fh(a)?"busy":!1}},updatePrompt:async(n,r,s)=>{const o=Y(),i=t().prompts.find(l=>l.id===n);if(!i||i.editable!==!0)return!1;const a=typeof s=="string"&&s.trim().length>0?s.trim():void 0;if((i.location==="project"||r.location==="project")&&!a)return!1;try{const l=await Ie.updatePromptTemplate(i.id,{...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{},...r.content!==void 0?{content:r.content}:{},...r.location!==void 0?{location:r.location}:{}},a,{runtimeKey:o});if(Y()!==o)return l.deferred===!0?"deferred":!0;const d=vo(o,a),f=nl(l);Po(d),Tr.set(d,f),hh(o),jn.set(d,Date.now());const u=f.find(h=>h.name===(r.name??i.name)&&h.location===(r.location??i.location));return e(h=>h.activeCacheKey===d?{prompts:f,selectedPromptId:u?.id??null,isLoading:!1}:h),bl(i.location==="global"||r.location==="global"?null:a),l.deferred===!0?"deferred":!0}catch(l){return fh(l)?"busy":!1}},deletePrompt:async(n,r)=>{const s=Y(),o=t().prompts.find(a=>a.id===n);if(!o||o.editable!==!0)return!1;const i=r?.trim()?r.trim():void 0;if(o.location==="project"&&!i)return!1;try{const a=await Ie.deletePromptTemplate(o.id,i,{runtimeKey:s});if(Y()!==s)return a.deferred===!0?"deferred":!0;const l=vo(s,i),d=nl(a);return Po(l),Tr.set(l,d),hh(s),jn.set(l,Date.now()),e(f=>f.activeCacheKey===l?{prompts:d,...f.selectedPromptId===n?{selectedPromptId:null}:{},isLoading:!1}:f),bl(o.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return fh(a)?"busy":!1}},getPromptById:n=>t().prompts.find(r=>r.id===n)}),{name:"prompt-templates-store"})),iH="pichamber.json",aH=".pichamber",cH=[".config","pichamber","projects"];function D1(){const e=zr();return e?.files?e.files:null}const lH=80,dH=4e3,uH=2e3,fH=300,hH=new Set(["macos","linux","windows"]),Do=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},La=(e,t)=>{const n=Do(e),r=t.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},u4=e=>La(La(e,aH),iH),Eu=()=>{const e="/api";return e.startsWith("/"),e},O1=async(e,t)=>{try{const n=await Rt(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return n.ok?{ok:!0,data:await n.json().catch(()=>null)}:{ok:!1,data:null}}catch{return{ok:!1,data:null}}},pH=async e=>{const t=D1();if(t?.createDirectory)try{if((await t.createDirectory(e))?.success)return!0}catch{}return!!(await O1(`${Eu()}/fs/mkdir`,{path:e})).ok},f4=async(e,t)=>{try{const n=await Rt(`${Eu()}/fs/read`,{query:{path:e,optional:"true",...t?{directory:t}:{}},cache:"no-store"});return n.ok?await n.text():null}catch{return null}},mH=async(e,t)=>{const n=D1();if(n?.writeFile)try{if((await n.writeFile(e,t))?.success)return!0}catch{}return!!(await O1(`${Eu()}/fs/write`,{path:e,content:t})).ok},h4=async()=>{const e=await dC();let t=e.home?Do(e.home):null;const n=e.pichamberDataDir?Do(e.pichamberDataDir):null;if(!t)try{const r=await uC();r&&r.trim().length>0&&(t=Do(r))}catch{}return{home:t,pichamberDataDir:n}},gH=async()=>(await h4()).home,yH=async()=>(await h4()).pichamberDataDir,p4=async()=>{const e=await yH();if(e)return La(e,"projects");const t=await gH();return t?cH.reduce((n,r)=>La(n,r),t):null},vH=e=>{const t=typeof e?.path=="string"?e.path.trim():"",n=t?Do(t):"";return n&&pm(n)||null},m4=async e=>{const t=await p4();if(!t)return null;const n=vH(e);return n?La(t,`${n}.json`):null},rl=(e,t)=>e.length<=t?e:e.slice(0,t),xH=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(typeof r!="string")continue;const s=r.trim().toLowerCase();!hH.has(s)||n.has(s)||(n.add(s),t.push(s))}return t},bH=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const s=r,o=typeof s.id=="string"?s.id.trim():"",i=rl(typeof s.name=="string"?s.name.trim():"",lH),a=rl(typeof s.command=="string"?s.command.trim():"",dH);if(!o||!i||!a||n.has(o))continue;n.add(o);const l=typeof s.icon=="string"?s.icon.trim():"",d=xH(s.platforms),f=s.autoOpenUrl===!0,u=typeof s.openUrl=="string"?s.openUrl.trim():"",h=rl(u,uH),m=typeof s.desktopOpenSshForward=="string"?s.desktopOpenSshForward.trim():"",g=rl(m,fH);t.push({id:o,name:i,command:a,icon:l||null,...f?{autoOpenUrl:!0}:{},...h?{openUrl:h}:{},...g?{desktopOpenSshForward:g}:{},...d.length>0?{platforms:d}:{}})}return t},g4=e=>{const t=bH(e?.actions),n=typeof e?.primaryActionId=="string"?e.primaryActionId.trim():"",r=n&&t.some(s=>s.id===n)?n:null;return{actions:t,primaryActionId:r}};async function H1(e){const t=typeof e?.path=="string"?e.path.trim():"";if(!t)return null;const n=await m4(e),r=async(a,l)=>{const d=await f4(a,l);return d===null?null:d},s=a=>{if(typeof a!="string")return null;const l=a.trim();if(!l)return null;try{const d=JSON.parse(l);return!d||typeof d!="object"?null:d}catch{return null}};if(n){const a=s(await r(n));if(a)return a}const o=u4(t),i=s(await r(o,t));if(!i)return null;try{await y4(e,i)&&await CH(t)}catch{}return i}async function y4(e,t){const n=typeof e?.path=="string"?e.path.trim():"";if(!n)return!1;const r=await p4(),s=await m4(e);if(!r||!s)return!1;try{if(!await pH(r))return!1;const i=await f4(s);let a={};if(typeof i=="string"&&i.trim())try{const f=JSON.parse(i);f&&typeof f=="object"&&!Array.isArray(f)&&(a=f)}catch{a={}}const l={};a.version!==void 0&&(l.version=a.version);const d=JSON.stringify({...a,...t,...l,projectPath:Do(n)},null,2);return await mH(s,d)}catch(o){return console.error("Failed to write pichamber config:",o),!1}}async function v4(e,t){const r={...await H1(e)||{},...t};return y4(e,r)}async function wH(e){const t=await H1(e);return P5(t?.draftStarters)}async function SH(e,t){return v4(e,{draftStarters:P5(t)})}async function aQ(e){const t=await H1(e);return g4({actions:t?.projectActions,primaryActionId:t?.projectActionsPrimaryId})}async function cQ(e,t){const n=g4({actions:t.actions,primaryActionId:t.primaryActionId});return v4(e,{projectActions:n.actions,projectActionsPrimaryId:n.primaryActionId??void 0})}async function CH(e){const t=u4(e),n=D1();if(n?.delete)try{await n.delete(t);return}catch{}try{await O1(`${Eu()}/fs/delete`,{path:t})}catch{}}const kH=[],Ei=(e,t)=>`${e}:${Hh(t)}`;function MH(){const e=re(N=>N.globalDraftStarters),t=zl(N=>N.prompts),n=zl(N=>N.activeCacheKey),r=zl(N=>N.loadPrompts),s=ct(N=>N.activeProjectId),o=ct(N=>N.projects),i=Jn(),a=p.useMemo(()=>{if(!s)return null;const N=o.find(D=>D.id===s);return N?.path?{id:N.id,path:N.path}:null},[s,o]),[l,d]=p.useState([]),f=p.useRef(new Set),[u,h]=p.useState(0);p.useEffect(()=>{let N=!1;if(!a){d([]);return}return wH(a).then(D=>{N||d(D)}).catch(()=>{N||d([])}),()=>{N=!0}},[a]),p.useEffect(()=>en(()=>{f.current.clear(),h(D=>D+1),d([])}),[]);const m=p.useCallback(()=>{i&&r(i)},[i,r]);p.useEffect(()=>{if(!i)return;let N=!1;const D=Y();return r(i).then(W=>{N||Y()===D&&W&&(f.current.add(i),h(z=>z+1))}),()=>{N=!0}},[i,r]);const g=vo(Y(),i),x=n===g,b=x?t:kH,S=p.useMemo(()=>fC(b),[b]),y=i?x&&f.current.has(i):!1,v=p.useCallback((N,D)=>{if(N.type==="text"){const z=hC[N.key];return z?{id:Ei(D,N),ref:N,group:D,label:z.label,icon:z.icon,insertText:z.text,promptName:""}:null}return S.get(N.name)?{id:Ei(D,N),ref:N,group:D,label:Qu(N.name),icon:Ju,insertText:`/${N.name} `,promptName:N.name}:y?null:{id:Ei(D,N),ref:N,group:D,label:Qu(N.name),icon:Ju,insertText:`/${N.name} `,promptName:N.name}},[S,y]),C=p.useMemo(()=>e??Mc,[e]),w=p.useMemo(()=>C.map(N=>v(N,"global")).filter(N=>N!==null),[C,v]),I=p.useMemo(()=>l.map(N=>v(N,"project")).filter(N=>N!==null),[l,v]),{global:E,project:T}=p.useMemo(()=>pC(I,w),[I,w]),A=p.useMemo(()=>{const N=new Set;for(const D of C)N.add(Hh(D));for(const D of l)N.add(Hh(D));return N},[C,l]),j=p.useMemo(()=>{const N=new Map;for(const D of b){if(D.editable!==!0||D.location!=="global"&&D.location!=="project")continue;const W=N.get(D.name),z=D.location==="project"?"project":"user",X={type:"prompt",name:D.name,label:Qu(D.name),icon:Ju,section:"prompt",scope:z};if(!W){N.set(D.name,X);continue}z==="project"&&W.scope!=="project"&&N.set(D.name,X)}return[...N.values()].filter(D=>!A.has(`${D.type}:${D.name}`))},[b,A]),k=p.useCallback(N=>{re.getState().setGlobalDraftStarters(N),$r({draftStarters:N})},[]),_=p.useCallback(N=>{d(N),a&&SH(a,N)},[a]),M=p.useCallback(N=>{if(N.type!=="prompt")return;const D={type:"prompt",name:N.name};if(N.scope==="project"){if(!a||l.some(W=>Ic(W,D)))return;_([...l,D])}else{const W=e??Mc;if(W.some(z=>Ic(z,D)))return;k([...W,D])}},[a,l,e,_,k]),L=p.useCallback((N,D)=>{N==="project"?_(l.filter(W=>!Ic(W,D))):k((e??Mc).filter(z=>!Ic(z,D)))},[l,e,_,k]),O=p.useCallback((N,D,W)=>{const z=N==="project"?l:e??Mc,X=z.findIndex(P=>Ei(N,P)===D),F=z.findIndex(P=>Ei(N,P)===W);if(X<0||F<0||X===F)return;const U=b8([...z],X,F);N==="project"?_(U):k(U)},[l,e,_,k]);return{global:E,project:T,pinnable:j,hasProject:!!a,ensureLoaded:m,addStarter:M,removeStarter:L,reorder:O}}const x4="__draft-starter-trash__",b4="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors",IH=[{key:"prompt",headingKey:"Prompts"}],EH=({item:e,onInsert:t,onRemove:n,hideRemove:r})=>{const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:l,isDragging:d}=Cm({id:e.id});return c.jsxs("div",{ref:i,style:{transform:km.Translate.toString(a),transition:l},className:R("group/chip relative",d&&"z-10 opacity-60"),children:[c.jsxs("button",{type:"button",...s,...o,onClick:()=>t(e),className:"group inline-flex touch-none select-none items-center gap-1.5 rounded-full border border-transparent px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-[var(--interactive-hover)] hover:text-foreground",children:[c.jsx(V,{name:e.icon,className:"h-3.5 w-3.5 shrink-0 opacity-70 transition-opacity group-hover:opacity-100"}),c.jsx("span",{className:"whitespace-nowrap",children:e.label})]}),r?null:c.jsx("button",{type:"button",onClick:f=>{f.stopPropagation(),n()},"aria-label":"Remove",title:"Remove",className:"absolute -right-1.5 -top-1.5 hidden h-4 w-4 items-center justify-center rounded-full border border-[var(--interactive-border)] bg-[var(--surface-elevated)] text-muted-foreground hover:text-foreground group-hover/chip:flex",children:c.jsx(V,{name:"close",className:"h-2.5 w-2.5"})})]})},iv=({items:e,onInsert:t,onRemove:n,hideRemove:r})=>c.jsx(Sm,{items:e.map(s=>s.id),strategy:S8,children:e.map(s=>c.jsx(EH,{item:s,onInsert:t,onRemove:()=>n(s),hideRemove:r},s.id))}),_H=()=>{const{currentTheme:e}=vr(),{setNodeRef:t,isOver:n}=C8({id:x4});return c.jsx("button",{type:"button",ref:t,"aria-label":"Remove",title:"Remove",className:R(b4,n?"border-destructive text-destructive":"text-muted-foreground"),style:{backgroundColor:e?.colors?.surface?.elevated,borderColor:n?void 0:e?.colors?.interactive?.border},children:c.jsx(V,{name:"delete-bin",className:"h-4 w-4"})})},jH=({pinnable:e,onPick:t,className:n})=>c.jsxs(eH,{className:R("min-h-0",n),children:[c.jsx(d4,{placeholder:"Search prompts…"}),c.jsxs(tH,{children:[c.jsx(nH,{children:"Nothing to add"}),IH.map(r=>{const s=e.filter(o=>o.section===r.key);return s.length===0?null:c.jsx(rH,{heading:r.headingKey,children:s.map(o=>c.jsx(sH,{value:`${o.section} ${o.label} ${o.name}`,onSelect:()=>t(o),children:c.jsx("span",{className:"truncate",children:o.label})},`${o.type}:${o.name}`))},r.key)})]})]}),TH=({pinnable:e,onOpen:t,onAdd:n})=>{const{currentTheme:r}=vr(),[s,o]=p.useState(!1);return c.jsxs(gu,{open:s,onOpenChange:i=>{o(i),i&&t()},children:[c.jsx(Cj,{asChild:!0,children:c.jsx("button",{type:"button","aria-label":"Add a starter",title:"Add a starter",className:R(b4,"text-muted-foreground hover:bg-[var(--interactive-hover)] hover:text-foreground"),style:{backgroundColor:r?.colors?.surface?.elevated,borderColor:r?.colors?.interactive?.border},children:c.jsx(V,{name:"add",className:"h-4 w-4"})})}),c.jsxs(yu,{className:"gap-0 overflow-hidden p-0 sm:max-w-sm",children:[c.jsx(vu,{className:"px-4 pb-2 pt-4 text-left",children:c.jsx(xu,{children:"Add a starter"})}),c.jsx(jH,{pinnable:e,onPick:i=>{n(i),o(!1)},className:"flex max-h-[60vh] flex-col"})]})]})},AH=({onInsert:e,className:t})=>{const{global:n,project:r,pinnable:s,ensureLoaded:o,addStarter:i,removeStarter:a,reorder:l}=MH(),{isMobile:d}=On(),[f,u]=p.useState(!1),h=xm(wa($5,{activationConstraint:{distance:8}}),wa(V5,{activationConstraint:{delay:200,tolerance:6}})),m=p.useCallback(S=>n.find(y=>y.id===S)??r.find(y=>y.id===S),[n,r]),g=()=>u(!0),x=()=>u(!1),b=S=>{u(!1);const{active:y,over:v}=S;if(!v)return;const C=String(y.id),w=m(C);if(!w)return;if(String(v.id)===x4){a(w.group,w.ref);return}const I=String(v.id);if(C===I)return;const E=m(I);E&&E.group===w.group&&l(w.group,C,I)};return c.jsx(bm,{sensors:h,collisionDetection:wm,measuring:{droppable:{strategy:w8.Always}},onDragStart:g,onDragCancel:x,onDragEnd:b,children:c.jsxs("div",{className:R("flex flex-wrap items-center justify-center gap-2",t),children:[n.length>0?c.jsx(iv,{items:n,onInsert:e,onRemove:S=>a("global",S.ref),hideRemove:d}):null,r.length>0?c.jsx(iv,{items:r,onInsert:e,onRemove:S=>a("project",S.ref),hideRemove:d}):null,d&&f?c.jsx(_H,{}):c.jsx(TH,{pinnable:s,onOpen:o,onAdd:i})]})})},w4=e=>re(n=>n.draftStartersVisible)?c.jsx(AH,{...e}):null,S4=()=>{const e=he(i=>i.currentSessionId),t=jw(),n=he(i=>i.newSessionDraft),r=ct(i=>i.activeProjectId),s=ct(i=>i.projects),o=nt(i=>i.currentDirectory);if(e){const i=t.find(a=>a.id===e);if(i?.directory)return i.directory}if(n?.open&&n.directoryOverride)return n.directoryOverride??void 0;if(r){const i=s.find(a=>a.id===r);if(i?.path)return i.path}return o??void 0},_i=new Map,NH=(e,t)=>`${e}
|
|
75
|
+
${t?.trim()??""}`;function C4(e){const t=e?.trim()?e.trim():void 0,n=p.useSyncExternalStore(sk,sf,sf),r=zl(m=>m.prompts.map(g=>`${g.id}:${g.name}:${g.location}`).join("|")),s=Hr(m=>m.skills.map(g=>`${g.id}:${g.name}:${g.scope}`).join("|")),[o,i]=p.useState(()=>{if(!t)return Mr();const m=m0(Y(),t);return m?[...Mr(),...m]:Mr()}),[a,l]=p.useState(!1),[d,f]=p.useState(0),u=p.useRef(void 0),h=p.useRef({promptSignature:"",skillSignature:""});return p.useEffect(()=>{h.current={promptSignature:r,skillSignature:s}},[r,s]),p.useEffect(()=>en(()=>{dk(),_i.clear(),u.current=void 0,i(Mr()),f(g=>g+1)}),[]),p.useEffect(()=>{const m=Y(),g=NH(m,t),x=`${g}
|
|
76
|
+
${n}`;if(!t){u.current=g,i(Mr());return}if(u.current!==g){u.current=g;const v=m0(m,t);i(v?[...Mr(),...v]:Mr())}const b=ik(m,t);if(b&&ak(b)){const v=b.promptSignature!==""&&b.promptSignature!==r,C=b.skillSignature!==""&&b.skillSignature!==s;if(!v&&!C){(b.promptSignature!==r||b.skillSignature!==s)&&lk(m,t,r,s),l(!1);return}}let S=!1;l(!0);const y=()=>{const v=_i.get(x);let C;if(v)C=v;else{const w=n,I=h.current.promptSignature,E=h.current.skillSignature,T={},A=(async()=>{try{const j=await Ie.listCommands(t,{runtimeKey:m});if(Y()!==m||sf()!==w)return null;const k=nk(j.commands);return ck(m,t,k,{promptSignature:I,skillSignature:E}),k}catch{return null}finally{_i.get(x)?.promise===T.promise&&_i.delete(x)}})();T.promise=A,C={promise:A,promptSignature:I,skillSignature:E},_i.set(x,C)}C.promise.then(w=>{if(!S&&Y()===m){if(w){i([...Mr(),...w]);const I=h.current,E=C.promptSignature!==""&&C.promptSignature!==I.promptSignature,T=C.skillSignature!==""&&C.skillSignature!==I.skillSignature;if(E||T){y();return}}l(!1)}}).catch(()=>{S||l(!1)})};return y(),()=>{S=!0}},[t,r,s,d,n]),{commands:o,isLoading:a}}const LH=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer"],RH=e=>typeof e=="string"&&LH.includes(e),PH=e=>{switch(e){case"concise":return"Keep replies short. Answer first, no preamble or recap of the question. Write like you're texting a colleague who already has the context — plain sentences, not headings or bullets. Reach for a list only when the content is genuinely a list; never use one to look organised.";case"detailed":return"Take the space you need to actually explain things. Walk through what's going on, why it matters, and where the real tradeoffs are. Prefer flowing prose over bullet points and headings — structure the answer with paragraphs and let the reasoning carry it. Lists are fine when something really is enumerable, but don't fragment a normal explanation into bullets.";case"mentor":return"Talk like a patient senior engineer pairing with someone less experienced. Explain the underlying idea before the answer, think out loud about how you'd approach it, and drop in a small concrete example when it actually helps. Keep it conversational — no lecture format, no checklists, no numbered steps unless the task literally is a sequence.";case"pushback":return"Don't agree automatically. If something I say sounds off — a wrong assumption, a flawed approach, a request that won't actually do what I think it will — push back first. Explain what you disagree with and why, and only proceed once I've responded. Disagreement is welcome; sycophancy is not. Don't soften it with 'you might want to consider' — just say it.";case"noFiller":return"Cut the filler. No 'Great question', no 'Certainly', no 'I'll help you with that', no restating what I just asked. No closing summary of what you did when the diff or output already shows it. No trailing 'let me know if you need anything else'. Open with the actual content and stop when you're done.";case"matchEnergy":return"Mirror the size and register of my message. A one-line question gets a one-line answer. A casual aside gets a casual reply, not a structured breakdown. If I write three words, don't respond with three paragraphs. Match the tone too — informal stays informal, technical stays technical. Don't inflate small asks into full essays.";case"warmPeer":return"Talk like a colleague, not an assistant. First person is fine and encouraged — 'I'd do this', 'I don't love that approach', 'that was sloppy of me'. Have actual opinions and share them. Push back when you disagree. Admit when you screwed up without grovelling. Skip the corporate helpfulness and performative politeness — just be a person."}},DH=({enabled:e,preset:t,customInstructions:n})=>e?t==="custom"?(typeof n=="string"?n.trim():"")||null:RH(t)?PH(t):null:null,k4=(e,t)=>{const n=e.reducer.bySession.get(t);return e.hydratedSessionIds.has(t)&&!e.sessionLoadErrorById.has(t)&&n!==void 0&&n.hasMoreBefore!==!0&&![...n.messages.values()].some(r=>r.role==="user")},OH=e=>e.newSessionDraftOpen||(e.sessionId!==null?k4(e.storeState,e.sessionId):!1),M4=e=>DH({enabled:e.responseStyleEnabled===!0,preset:e.responseStylePreset,customInstructions:e.responseStyleCustomInstructions});let ga=null,uo=null;const HH=e=>{ga={runtimeKey:Y(),value:M4(e)}};typeof window<"u"&&window.addEventListener("pichamber:settings-synced",e=>{HH(e.detail??{})});en(e=>{e.runtimeKey!==e.previousRuntimeKey&&(ga=null,uo=null)});const FH=async()=>{const e=Y();if(ga?.runtimeKey===e)return ga.value;if(uo?.runtimeKey===e)return uo.promise;const t=(async()=>{const n=await Rt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return null;const r=await n.json().catch(()=>null);if(!r||Y()!==e)return null;const s=M4(r);return ga={runtimeKey:e,value:s},s})();uo={runtimeKey:e,promise:t};try{return await t}finally{uo?.promise===t&&(uo=null)}},BH=async e=>{if(!OH({newSessionDraftOpen:e.newSessionDraftOpen,sessionId:e.sessionId,storeState:e.getStoreState()}))return null;const t=await FH().catch(()=>null);return!t||!e.newSessionDraftOpen&&e.sessionId!==null&&!k4(e.getStoreState(),e.sessionId)?null:t},av="<system-reminder>",cv="</system-reminder>",VH=e=>{const t=e.trim();return t?t.startsWith(av)&&t.endsWith(cv)?t:`${av}
|
|
77
|
+
${t}
|
|
78
|
+
${cv}`:""},lv=e=>e.includes("@")?"paste":"manual",$H=({value:e,cursorPosition:t,inputSource:n="manual",insertedText:r})=>{if(n==="paste"&&r?.includes("@"))return null;const s=e.substring(0,t),o=s.lastIndexOf("@");if(o===-1)return null;const i=o>0?s[o-1]:null,a=s.substring(o+1);return!(!i||/\s/.test(i))||a.includes(" ")||a.includes(`
|
|
79
|
+
`)?null:a},zH=/[\s()[\]{}<>"'`,.;:]/,UH=/^[`"'<([{]+/,qH=/[)\]},.;:!?`"'>]+$/,dv=/@([^\s]+)/g;function WH(e,t){return t<=0?!0:zH.test(e[t-1])}function KH(e){return e.trim().replace(UH,"").replace(qH,"")}function GH(e){if(!e||!e.includes("@"))return[];const t=[];dv.lastIndex=0;let n;for(;(n=dv.exec(e))!==null;){const r=n.index;if(!WH(e,r))continue;const s=n[1]??"",o=KH(s);if(!o)continue;const i=r+1+s.indexOf(o);t.push({start:r,end:i+o.length,raw:n[0],name:o})}return t}function ZH(e,t){return!e||e.includes("<")||e.includes(">")?null:t.knownAgentNames.has(e.toLowerCase())?"agent":YH(e,t.confirmedMentions)?"file":null}function YH(e,t){return e.includes("/")||e.includes("\\")||e.includes(".")||t.has(e)}const XH=(e,t)=>t<=0||/\s/.test(e[t-1]);function JH(e,t){if(!e.startsWith("/")||e.indexOf(" ")!==-1)return null;const r=e.indexOf(`
|
|
80
|
+
`),s=r===-1?e.length:r;return t>s?null:{kind:"command",query:e.substring(1,s)}}function QH(e,t,n,r){const s=e.substring(0,t),o=s.lastIndexOf(n);if(o===-1||!XH(s,o))return null;const i=s.substring(o+1);return i.includes(" ")||i.includes(`
|
|
81
|
+
`)?null:{kind:r,query:i}}function eF(e,t,n){return n.inputMode==="shell"?null:JH(e,t)??QH(e,t,"#","snippet")??tF(e,t,n)}function tF(e,t,n){const r=$H({value:e,cursorPosition:t,inputSource:n.inputSource,insertedText:n.insertedText});return r===null?null:{kind:"mention",query:r}}const nF=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),uv=new Set(["image","screenshot","screen-shot","clipboard","pasted-image","pastedimage","untitled","unknown","file","blob"]),rF={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/heic":"heic","image/heif":"heif","image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/svg+xml":"svg","image/tiff":"tiff","image/webp":"webp"},Rs=e=>e.trim().toLowerCase(),sF=e=>e.charCodeAt(0)<32||'<>:"/\\|?*[]'.includes(e),oF=e=>{const t=e.replace(/\\/g,"/").split("/").pop()??"";return Array.from(t).map(n=>sF(n)?"-":n).join("").replace(/\s+/g," ").replace(/-+/g,"-").trim()},iF=e=>{const t=e?.trim().toLowerCase()??"";return rF[t]??"png"},I4=e=>{const t=oF(e.name),n=iF(e.type),r=t.lastIndexOf(".");if(r>0&&r<t.length-1){const s=t.slice(r+1).toLowerCase();if(/^[a-z0-9]{1,10}$/.test(s))return{base:t.slice(0,r).trim()||"image",ext:s}}return{base:t.trim()||"image",ext:n}},aF=e=>{const{base:t}=I4({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(uv.has(n))return!0;const r=n.replace(/-\(\d+\)$/g,"");return r!==n&&uv.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},Oo=(e,t)=>`${e}.${t}`,cF=(e,t,n)=>{const r=Oo(e,t);if(!n.has(Rs(r)))return r;for(let s=2;s<Number.MAX_SAFE_INTEGER;s+=1){const o=Oo(`${e}-${s}`,t);if(!n.has(Rs(o)))return o}return Oo(`${e}-${Date.now()}`,t)},lF=(e,t)=>{for(let n=1;n<Number.MAX_SAFE_INTEGER;n+=1){const r=Oo(`image-${n}`,e);if(!Array.from(t).some(o=>o.startsWith(`image-${n}.`))&&!t.has(Rs(r)))return r}return Oo(`image-${Date.now()}`,e)},dF=(e,t)=>{const n=new Set(t.map(Rs));return e.map(r=>{const{base:s,ext:o}=I4(r),i=aF(Oo(s,o))?lF(o,n):cF(s,o,n);return n.add(Rs(i)),i})},uF=e=>e.map(t=>`[${t}]`).join(" "),fF=(e,t)=>{if(!e||!e.includes("[")||t.length===0)return[];const n=new Set(t.map(Rs)),r=[];let s=0;for(;s<e.length;){const o=e.indexOf("[",s);if(o===-1)break;const i=e.indexOf("]",o+1);if(i===-1)break;if(e[i+1]!=="("){const a=e.slice(o+1,i).trim();n.has(Rs(a))&&r.push({start:o,end:i+1})}s=i+1}return r},hF=e=>{switch(e){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return"shell";case"json":case"jsonc":case"json5":return"json";case"js":case"javascript":case"jsx":case"ts":case"typescript":case"tsx":return"javascript";case"html":case"heex":case"eex":case"leex":return"html";case"css":return"css";case"py":case"python":return"python";case"md":case"markdown":case"mdown":case"mkd":return"markdown";default:return null}},E4=e=>e.trim().toLowerCase(),$p=new Map,sl=new Map;let ol=null;const pF=async(e,t)=>{switch(e){case"javascript":{const{javascript:n}=await mt(async()=>{const{javascript:r}=await import("./vendor-codemirror-lang-javascript-Bx_FIyZF.js");return{javascript:r}},__vite__mapDeps([44,45,46,5,1,6,47]));switch(t){case"jsx":return n({jsx:!0}).language;case"ts":case"typescript":return n({typescript:!0}).language;case"tsx":return n({typescript:!0,jsx:!0}).language;default:return n().language}}case"json":{const{json:n}=await mt(async()=>{const{json:r}=await import("./vendor-codemirror-lang-json-DIvqf9Pb.js");return{json:r}},__vite__mapDeps([48,49,46,5,1,6]));return n().language}case"css":{const{css:n}=await mt(async()=>{const{css:r}=await import("./vendor-codemirror-lang-css-D1wpUg3Z.js");return{css:r}},__vite__mapDeps([50,51,46,5,1,6]));return n().language}case"html":{const{html:n}=await mt(async()=>{const{html:r}=await import("./vendor-codemirror-lang-html-DbL8oT9H.js");return{html:r}},__vite__mapDeps([52,53,46,5,1,6,50,51,44,45,47]));return n().language}case"markdown":{const{markdown:n}=await mt(async()=>{const{markdown:r}=await import("./vendor-codemirror-lang-markdown-v3yG2sbf.js");return{markdown:r}},__vite__mapDeps([54,5,1,6,47,55,52,53,46,50,51,44,45]));return n().language}case"python":{const{python:n}=await mt(async()=>{const{python:r}=await import("./vendor-codemirror-lang-python-b-JqEwQy.js");return{python:r}},__vite__mapDeps([56,57,46,5,1,6,47]));return n().language}case"shell":{if(ol)return ol;const{shell:n}=await mt(async()=>{const{shell:r}=await import("./shell-CjFT_Tl9.js");return{shell:r}},[]);return ol=k8.define(n),ol}}},_4=e=>e?$p.get(E4(e))??null:null,mF=e=>{const t=E4(e);if(!t)return Promise.resolve(null);const n=$p.get(t);if(n)return Promise.resolve(n);const r=sl.get(t);if(r)return r;const s=hF(t);if(!s)return Promise.resolve(null);const o=pF(s,t).then(i=>(i&&$p.set(t,i),sl.delete(t),i)).catch(()=>(sl.delete(t),null));return sl.set(t,o),o},gF={mentionFile:100,mentionAgent:100,mentionCommand:100,mentionSnippet:100,code:90,codeFence:90,path:85,link:80,linkUrl:78,heading:70,attention:60,strong:50,emphasis:50,blockquote:40,listMarker:35,marker:10},fv={mentionFile:"text-[var(--status-info)]",mentionAgent:"text-[var(--status-success)]",mentionCommand:"text-[var(--primary)]",mentionSnippet:"text-[var(--status-warning)]",code:"rounded-[3px] bg-[var(--surface-subtle)] text-[var(--markdown-inline-code)]",codeFence:"bg-[var(--surface-subtle)] text-[var(--markdown-inline-code)]",path:"text-[var(--status-info)]",link:"text-[var(--status-info)] underline",linkUrl:"text-muted-foreground",heading:"text-[var(--syntax-keyword)]",attention:"font-semibold text-[var(--status-warning)]",blockquote:"text-muted-foreground",listMarker:"text-[var(--syntax-keyword)]",marker:"text-muted-foreground",strong:"font-semibold",emphasis:"italic"},yF=new Set(["strong","emphasis"]),j4="text-foreground";function vF(e,t,n){const r=t>0?e[t-1]:"",s=e[t+n];return!s||/\s/.test(s)||e[t]==="_"&&/[\w]/.test(r)?!1:r===""||!/[\w]/.test(r)||e[t]==="*"}function xF(e,t,n){const r=e[t-1],s=e[t+n];return!(!r||/\s/.test(r)||e[t]==="_"&&s&&/[\w]/.test(s))}function bF(e,t){const n=e[t],r=/^(\*{1,3}|_{1,3})/.exec(e.slice(t))?.[1]??"";if(!r||!vF(e,t,r.length))return null;let s=t+r.length;for(;s<e.length;){const o=e.indexOf(r,s);if(o===-1)return null;if(e[o+r.length]===n){s=o+r.length+1;continue}if(xF(e,o,r.length))return{end:o+r.length,runLength:r.length};s=o+r.length}return null}function fo(e,t,n){let r=0;const s=e.length;for(;r<s;){const o=e[r];if(o==="`"){const i=/^`+/.exec(e.slice(r))?.[0]??"",a=e.indexOf(i,r+i.length);if(a!==-1){const l=a+i.length;n.push({start:t+r,end:t+l,style:"code"}),r=l;continue}}if(o==="["){const i=/^\[([^\]\n]*)\]\(([^)\n]*)\)/.exec(e.slice(r));if(i){const a=t+r,l=i[1].length,d=i[2].length,f=a+1,u=f+l,h=u+2,m=h+d,g=m+1;n.push({start:a,end:f,style:"marker"}),l>0&&n.push({start:f,end:u,style:"link"}),n.push({start:u,end:h,style:"marker"}),d>0&&n.push({start:h,end:m,style:"linkUrl"}),n.push({start:m,end:g,style:"marker"}),r+=i[0].length;continue}}if(o==="*"||o==="_"){const i=bF(e,r);if(i){const a=t+r+i.runLength,l=t+i.end-i.runLength;n.push({start:t+r,end:a,style:"marker"}),i.runLength>=2&&n.push({start:a,end:l,style:"strong"}),i.runLength!==2&&n.push({start:a,end:l,style:"emphasis"}),n.push({start:l,end:t+i.end,style:"marker"}),fo(e.slice(r+i.runLength,i.end-i.runLength),a,n),r=i.end;continue}}r+=1}}const wF=/^(\s*)(`{3,}|~{3,})\s*(\S*)/;function F1(e){const t=wF.exec(e);return t?{marker:t[2],lang:t[3]||""}:null}function T4(e,t){return new RegExp(`^\\s*\\${t[0]}{${t.length},}\\s*$`).test(e)}function SF(e){const t=[];if(!e)return t;let n=0,r=!1,s="";const o=e.split(`
|
|
82
|
+
`);for(let i=0;i<o.length;i+=1){const a=o[i],l=n,d=l+a.length;if(n=d+1,r){t.push({start:l,end:d,style:"codeFence"}),T4(a,s)&&(r=!1);continue}const f=F1(a);if(f){r=!0,s=f.marker,t.push({start:l,end:d,style:"codeFence"});continue}const u=/^(\s*)(!!!)(\s+)/.exec(a);if(u){const x=l+u[1].length,b=x+u[2].length;t.push({start:x,end:b,style:"marker"});const S=b+u[3].length;d>S&&(t.push({start:S,end:d,style:"attention"}),fo(a.slice(S-l),S,t));continue}const h=/^(\s*)(#{1,6})(\s+)/.exec(a);if(h){const x=l+h[1].length,b=x+h[2].length;t.push({start:x,end:b,style:"marker"});const S=b+h[3].length;d>S&&(t.push({start:S,end:d,style:"heading"}),fo(a.slice(S-l),S,t));continue}const m=/^(\s*)(>+)(\s?)/.exec(a);if(m){const x=l+m[1].length,b=x+m[2].length;t.push({start:x,end:b,style:"marker"});const S=b+m[3].length;d>S&&(t.push({start:S,end:d,style:"blockquote"}),fo(a.slice(S-l),S,t));continue}const g=/^(\s*)([-*+]|\d{1,9}[.)])(\s+)/.exec(a);if(g){const x=l+g[1].length,b=x+g[2].length;t.push({start:x,end:b,style:"listMarker"});const S=b+g[3].length;fo(a.slice(S-l),S,t);continue}fo(a,l,t)}return t}function CF(e,t){if(!e||t.length===0)return[];const n=e.length,r=new Set([0,n]);for(const d of t)d.start>0&&d.start<n&&r.add(d.start),d.end>0&&d.end<n&&r.add(d.end);const s=[...r].sort((d,f)=>d-f),o=t.map((d,f)=>({range:d,index:f})).filter(d=>d.range.end>d.range.start).sort((d,f)=>d.range.start-f.range.start),i=[],a=[];let l=0;for(let d=0;d<s.length-1;d+=1){const f=s[d],u=s[d+1];if(u<=f)continue;for(;l<o.length&&o[l].range.start<=f;)a.push(o[l]),l+=1;for(let v=a.length-1;v>=0;v-=1)a[v].range.end<=f&&a.splice(v,1);let h=null,m=-1,g=1/0;const x=[];for(const{range:v,index:C}of a){if(yF.has(v.style)){const I=v.className??fv[v.style];x.includes(I)||x.push(I);continue}const w=v.priority??gF[v.style];(w>m||w===m&&C<g)&&(m=w,g=C,h=v)}const b=h?h.className??fv[h.style]:j4,S=x.length>0?[b,...x].join(" "):b,y=i[i.length-1];y&&y.className===S&&y.end===f?y.end=u:i.push({start:f,end:u,className:S})}return i}const kF=j4;function MF(e){return e.map(t=>({start:t.start,end:t.end,style:t.kind==="file"?"mentionFile":"mentionAgent"}))}const ar="bg-[var(--surface-subtle)]",IF=91,EF=94,ph={keyword:8,function:7,type:6,string:5,number:5,variable:4,operator:3,comment:2},_F={keyword:`${ar} text-[var(--syntax-keyword)]`,string:`${ar} text-[var(--syntax-string)]`,number:`${ar} text-[var(--syntax-number)]`,comment:`${ar} text-[var(--syntax-comment)]`,function:`${ar} text-[var(--syntax-function)]`,type:`${ar} text-[var(--syntax-type)]`,variable:`${ar} text-[var(--syntax-variable)]`,operator:`${ar} text-[var(--syntax-operator)]`},jF=I8([{tag:[Pe.comment,Pe.lineComment,Pe.blockComment,Pe.docComment,Pe.meta],class:"comment"},{tag:[Pe.keyword,Pe.modifier,Pe.controlKeyword,Pe.operatorKeyword,Pe.definitionKeyword,Pe.moduleKeyword,Pe.self,Pe.null],class:"keyword"},{tag:[Pe.string,Pe.special(Pe.string),Pe.docString,Pe.character,Pe.regexp],class:"string"},{tag:[Pe.number,Pe.integer,Pe.float,Pe.bool,Pe.atom],class:"number"},{tag:[Pe.function(Pe.variableName),Pe.function(Pe.propertyName),Pe.macroName,Pe.standard(Pe.variableName)],class:"function"},{tag:[Pe.typeName,Pe.className,Pe.namespace,Pe.tagName],class:"type"},{tag:[Pe.variableName,Pe.propertyName,Pe.attributeName,Pe.labelName,Pe.definition(Pe.variableName)],class:"variable"},{tag:[Pe.operator,Pe.punctuation,Pe.bracket,Pe.derefOperator,Pe.separator],class:"operator"},{tag:[Pe.heading,Pe.heading1,Pe.heading2,Pe.heading3,Pe.heading4,Pe.heading5,Pe.heading6,Pe.strong],class:"keyword"},{tag:[Pe.emphasis,Pe.quote],class:"type"},{tag:[Pe.link,Pe.url],class:"function"},{tag:[Pe.monospace],class:"string"},{tag:[Pe.strikethrough],class:"comment"}]),TF=e=>{let t=null;for(const n of e.split(" ")){const r=n;ph[r]!==void 0&&(t===null||ph[r]>ph[t])&&(t=r)}return t?_F[t]:null},AF=2e4,NF=e=>e?_4(e):null;async function LF(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return!1;const t=new Set;for(const r of e.split(`
|
|
83
|
+
`)){const s=F1(r);s?.lang&&(_4(s.lang)||t.add(s.lang))}return t.size===0?!1:(await Promise.all([...t].map(r=>mF(r)))).some(r=>r!==null)}function RF(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return[];const t=[],n=e.split(`
|
|
84
|
+
`);let r=0;for(let s=0;s<n.length;s+=1){const o=n[s];r+=o.length+1;const i=F1(o);if(!i)continue;const a=NF(i.lang),l=r,d=[];let f=s+1,u=r;for(;f<n.length;f+=1){const m=n[f];if(T4(m,i.marker)){u+=m.length+1;break}d.push(m),u+=m.length+1}if(s=f,r=u,!a||d.length===0)continue;const h=d.join(`
|
|
85
|
+
`);if(h.trim()&&(t.push({start:l,end:l+h.length,style:"codeFence",className:`${ar} text-[var(--syntax-foreground)]`,priority:IF}),!(h.length>AF)))try{const m=a.parser.parse(h);M8(m,jF,(g,x,b)=>{const S=TF(b);S&&t.push({start:l+g,end:l+x,style:"codeFence",className:S,priority:EF})})}catch{}}return t}const hv=/~([^\s~]+)/g,PF=/[)\]},.;:!?`"'>]+$/,DF=/[\s()[\]{}<>"'`,;:]/;function OF(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z]/.test(e)}function HF(e){if(!e||!e.includes("~"))return[];const t=[];hv.lastIndex=0;let n;for(;(n=hv.exec(e))!==null;){const r=n.index,s=r>0?e[r-1]:"";if(s&&!DF.test(s))continue;const o=(n[1]??"").replace(PF,"");!o||!OF(o)||t.push({start:r,end:r+1+o.length,path:o})}return t}function FF(e){return HF(e).map(t=>({start:t.start,end:t.end,style:"path"}))}const BF="[A-Za-z0-9][A-Za-z0-9_-]*",VF="[A-Za-z0-9][^\\s/]*",$F={"/":new RegExp(`(^|\\s)\\/(${VF})`,"g"),"#":new RegExp(`(^|\\s)#(${BF})`,"g")};function zp(e,t){if(!e||!e.includes(t))return[];const n=$F[t],r=[];n.lastIndex=0;let s;for(;(s=n.exec(e))!==null;){const o=s[2],i=s.index+s[1].length;r.push({start:i,end:i+1+o.length,prefix:t,name:o})}return r}function Up(e,t,n="case-insensitive"){return t.size===0?[]:e.filter(r=>t.has(n==="exact"?r.name:r.name.toLowerCase()))}function zF(e,t,n,r="case-insensitive"){const s=new Set,o=[];for(const i of Up(zp(e,t),n,r))s.has(i.name)||(s.add(i.name),o.push(i.name));return o}function UF(e,t){const n=[];for(const r of GH(e)){const s=ZH(r.name,t);s&&n.push({start:r.start,end:r.end,kind:s})}return n}function qF(e,t){if(!e||t.inputMode==="shell")return[];const n=[...SF(e),...RF(e),...MF(UF(e,t)),...FF(e)];for(const r of Up(zp(e,"/"),t.knownSlashNames))n.push({start:r.start,end:r.end,style:"mentionCommand"});for(const r of Up(zp(e,"#"),t.knownSnippetTriggers))n.push({start:r.start,end:r.end,style:"mentionSnippet"});if(t.attachmentFilenames.length>0&&e.includes("["))for(const r of fF(e,[...t.attachmentFilenames]))n.push({...r,style:"mentionFile"});return n}const B1=Z5.define(),A4=Z5.define(),qp=Y5.define({create:()=>N4,update(e,t){for(const n of t.effects)if(n.is(B1))return n.value;return e}}),N4={inputMode:"normal",knownAgentNames:new Set,confirmedMentions:new Set,knownSlashNames:new Set,knownSnippetTriggers:new Set,attachmentFilenames:[]};function pv(e,t){const n=new _8;for(const r of CF(e,qF(e,t)))r.className!==kF&&n.add(r.start,r.end,j8.mark({class:r.className}));return n.finish()}const WF=Y5.define({create:e=>pv(e.doc.toString(),e.field(qp)),update(e,t){const n=t.effects.some(s=>s.is(B1)),r=t.effects.some(s=>s.is(A4));return!t.docChanged&&!n&&!r?e:pv(t.state.doc.toString(),t.state.field(qp))},provide:e=>bn.decorations.from(e)}),KF=E8.fromClass(class{generation=0;constructor(e){this.ensure(e)}update(e){e.docChanged&&this.ensure(e.view)}async ensure(e){const t=++this.generation,n=e.state.doc.toString();if(!n.includes("```")&&!n.includes("~~~"))return;let r=!1;try{r=await LF(n)}catch{return}t===this.generation&&r&&e.state.doc.toString()===n&&e.dispatch({effects:A4.of(void 0)})}});function GF(e=N4){return[qp.init(()=>e),WF,KF]}const ZF={"&":{backgroundColor:"transparent",color:"var(--surface-foreground)"},"&.cm-focused":{outline:"none"},".cm-content":{padding:"0",fontFamily:"inherit",fontSize:"inherit",lineHeight:"inherit",minHeight:"100%"},"&.cm-editor .cm-cursor, &.cm-editor .cm-dropCursor":{borderLeftColor:"var(--surface-foreground)",borderLeftWidth:"2px",marginLeft:"0",transform:"scaleY(1.15)",transformOrigin:"center"},".cm-line":{padding:"0"},".cm-scroller":{fontFamily:"inherit",fontSize:"inherit",lineHeight:"inherit",overflowX:"hidden"},".cm-placeholder":{color:"var(--surface-muted-foreground)"},"&.cm-editor .cm-selectionBackground, & .cm-selectionBackground":{background:"color-mix(in srgb, var(--interactive-selection) 45%, transparent)"},"&.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"color-mix(in srgb, var(--interactive-selection) 55%, transparent)"},"& ::selection":{background:"color-mix(in srgb, var(--primary) 25%, transparent)"}},YF=bn.theme(ZF),XF={"& .cm-content .cm-line ::selection, & .cm-content .cm-line::selection":{backgroundColor:"color-mix(in srgb, var(--primary) 25%, transparent) !important"},"&.cm-editor.oc-native-range .cm-content, &.cm-editor.oc-native-range .cm-content .cm-line":{caretColor:"var(--surface-foreground) !important"},"&.oc-native-range .cm-scroller > .cm-cursorLayer":{display:"none"},"& .cm-scroller > .cm-selectionLayer":{display:"none"}},JF=bn.theme(XF),QF=[JF,bn.editorAttributes.of(e=>e.state.selection.main.empty?null:{class:"oc-native-range"})];function eB(e,t){if(!e||e.state.readOnly||!e.contentDOM.isContentEditable||e.contentDOM.contains(t.target))return;t.preventDefault();const n=e.posAtCoords({x:t.clientX,y:t.clientY})??e.state.doc.length;e.focus(),e.dispatch({selection:{anchor:n}})}function tB(e){let t="";return e.changes.iterChanges((n,r,s,o,i)=>{t+=i.toString()}),t}function mv(e){return!!e.synthetic}const gv=new X5,yv=new X5,nB=p.forwardRef(function(t,n){const{value:r,languageContext:s,placeholder:o,editable:i=!0,spellCheck:a=!1,autoCorrect:l=!1,autoCapitalize:d="none",fillContainer:f=!1,maxLines:u=8,boundSelector:h,boundGapPx:m=0,className:g,contentClassName:x,commandComboboxExpanded:b,commandComboboxListboxId:S,commandComboboxActiveOptionId:y}=t,v=p.useRef(null),C=p.useRef(null),w=p.useRef(!1),I=p.useRef({element:null,role:null}),E=p.useRef(t),T=t.viewStore??null;T&&!T.handlers&&(T.handlers={current:t});const A=T?.handlers??E;A.current=t,p.useLayoutEffect(()=>{const k=v.current;if(!k)return;const _=T?.view;if(_){k.appendChild(_.dom),_.requestMeasure();const{anchor:N,head:D}=_.state.selection.main;return _.dispatch({selection:{anchor:N,head:D}}),C.current=_,()=>{_.dom.remove(),C.current=null}}const M=[{any:(N,D)=>(D.key==="Enter"&&mv(D)&&w.current&&Object.defineProperty(D,"shiftKey",{value:!0}),A.current.onKeyDown?.(D)??!1)}],L=new bn({state:T8.create({doc:A.current.value,extensions:[A8(),N8(),QF,bn.lineWrapping,L8.highest(t0.of(M)),t0.of([...R8,...P8]),GF(A.current.languageContext),gv.of(bn.editable.of(A.current.editable??!0)),yv.of(n0(A.current.placeholder??"")),YF,bn.updateListener.of(N=>{const D=A.current,W=xv(N.state);if(N.docChanged){const z=N.transactions.some(F=>F.isUserEvent("input.paste"));let X="";for(const F of N.transactions)X+=tB(F);D.onChange({value:N.state.doc.toString(),selection:W,fromPaste:z,insertedText:X})}else N.selectionSet&&D.onSelectionChange?.(W);(N.docChanged||N.heightChanged||N.geometryChanged)&&D.onVisualLineCount?.(vv(N.view))}),bn.domEventHandlers({focus:()=>(A.current.onFocus?.(),!1),blur:()=>(A.current.onBlur?.(),!1),paste:N=>(A.current.onPaste?.(N),!1)}),bn.contentAttributes.of({spellcheck:String(A.current.spellCheck??!1),autocorrect:A.current.autoCorrect?"on":"off",autocapitalize:A.current.autoCapitalize??"none",...A.current["aria-label"]?{"aria-label":A.current["aria-label"]}:{}})]}),parent:k});C.current=L,T&&(T.view=L);const O=N=>{N.key!=="Enter"||mv(N)||(w.current=N.shiftKey)};return L.contentDOM.addEventListener("keydown",O),()=>{if(C.current=null,T){L.dom.remove();return}L.destroy()}},[]),p.useEffect(()=>{const k=C.current;if(!k)return;const _=k.state.doc.toString();_!==r&&(k.dispatch({changes:{from:0,to:_.length,insert:r},selection:{anchor:r.length}}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{C.current===k&&(k.scrollDOM.scrollTop=k.scrollDOM.scrollHeight)})}))},[r]),p.useEffect(()=>{C.current?.dispatch({effects:B1.of(s)})},[s]),p.useEffect(()=>{C.current?.dispatch({effects:gv.reconfigure(bn.editable.of(i))})},[i]),p.useEffect(()=>{C.current?.dispatch({effects:yv.reconfigure(n0(o??""))})},[o]),p.useEffect(()=>{const k=C.current,_=v.current;if(!k||!_)return;if(f){k.scrollDOM.style.maxHeight="";return}const M=h?_.closest(h):null;let L=null;if(M)for(L=_;L.parentElement&&L.parentElement!==M;)L=L.parentElement;const O=()=>{const D=parseFloat(getComputedStyle(k.contentDOM).lineHeight||"");if(!Number.isFinite(D)||D<=0)return;let W=D*u;if(M&&L){const X=L.offsetHeight-k.scrollDOM.offsetHeight,F=M.clientHeight-X-m;F>0&&(W=Math.min(W,F))}const z=`${W}px`;k.scrollDOM.style.maxHeight!==z&&(k.scrollDOM.style.maxHeight=z)};if(O(),A.current.onVisualLineCount?.(vv(k)),typeof ResizeObserver>"u")return;const N=new ResizeObserver(O);return N.observe(_),L&&N.observe(L),M&&N.observe(M),()=>N.disconnect()},[m,h,f,u]),p.useEffect(()=>{const k=C.current;if(!k)return;const _=k.contentDOM;_.setAttribute("spellcheck",String(a)),_.setAttribute("autocorrect",l?"on":"off"),_.setAttribute("autocapitalize",d)},[d,l,a]),p.useLayoutEffect(()=>{const k=C.current;if(!k)return;const _=k.contentDOM;if(I.current.element!==_){const D=I.current;D.element&&D.element!==_&&(D.role===null?D.element.getAttribute("role")==="combobox"&&D.element.removeAttribute("role"):D.element.setAttribute("role",D.role),D.element.removeAttribute("aria-expanded"),D.element.removeAttribute("aria-controls"),D.element.removeAttribute("aria-activedescendant")),I.current={element:_,role:_.getAttribute("role")}}const M=I.current.role,L=()=>{M===null?_.getAttribute("role")==="combobox"&&_.removeAttribute("role"):_.getAttribute("role")!==M&&_.setAttribute("role",M)},O=()=>{_.removeAttribute("aria-expanded"),_.removeAttribute("aria-controls"),_.removeAttribute("aria-activedescendant"),L()};return!!(b&&S)&&S?(_.setAttribute("role","combobox"),_.setAttribute("aria-expanded","true"),_.setAttribute("aria-controls",S),y?_.setAttribute("aria-activedescendant",y):_.removeAttribute("aria-activedescendant"),O):(O(),O)},[b,S,y]);const j=p.useCallback(k=>{eB(C.current,k)},[]);return p.useImperativeHandle(n,()=>({focus(k){const _=C.current;_&&_.contentDOM.focus({preventScroll:k?.preventScroll})},blur(){C.current?.contentDOM.blur()},isFocused(){return C.current?.hasFocus??!1},getValue(){return C.current?.state.doc.toString()??""},getSelection(){const k=C.current;return k?xv(k.state):{start:0,end:0}},setSelection(k,_=k){const M=C.current;if(!M)return;const L=M.state.doc.length;M.dispatch({selection:{anchor:Math.min(Math.max(k,0),L),head:Math.min(Math.max(_,0),L)}})},selectAll(){const k=C.current;k&&k.dispatch({selection:{anchor:0,head:k.state.doc.length}})},insertText(k){const _=C.current;if(!_||!k)return;const{from:M,to:L}=_.state.selection.main;_.dispatch({changes:{from:M,to:L,insert:k},selection:{anchor:M+k.length},userEvent:"input.type"})},replaceRange(k,_,M,L){const O=C.current;O&&O.dispatch({changes:{from:k,to:_,insert:M},selection:{anchor:L??k+M.length},userEvent:"input.type"})},caretCoords(k){const _=C.current;if(!_)return null;const M=k??_.state.selection.main.head,L=_.coordsAtPos(M);return L?{top:L.top,bottom:L.bottom,left:L.left}:null},getScrollDOM(){return C.current?.scrollDOM??null}}),[]),c.jsx("div",{ref:v,"data-testid":t["data-testid"],"data-chat-input":"true",onMouseDown:j,className:R("composer-editor w-full","[&_.cm-editor]:h-full",f&&"flex min-h-0 flex-1 flex-col",g,x)})});function vv(e){const t=e.defaultLineHeight;return!Number.isFinite(t)||t<=0?1:Math.max(1,Math.round(e.contentHeight/t))}function xv(e){const t=e.selection.main;return{start:t.from,end:t.to}}function rB(){return{view:null,handlers:null}}function sB(e,t){const n=e?e.endsWith(`
|
|
86
|
+
|
|
87
|
+
`)?"":e.endsWith(`
|
|
88
|
+
`)?`
|
|
89
|
+
`:`
|
|
90
|
+
|
|
91
|
+
`:"",r=t.endsWith(`
|
|
92
|
+
|
|
93
|
+
`)?t:t.endsWith(`
|
|
94
|
+
`)?`${t}
|
|
95
|
+
`:`${t}
|
|
96
|
+
|
|
97
|
+
`;return`${e}${n}${r}`}function L4(e,t){const n=t.trim();if(!n)return e;if(!e)return`${n} `;const r=/[\s\n]$/.test(e)?"":" ";return`${e}${r}${n} `}function R4(e,t,n){if(!e)return e;const r=t.length>0&&!/\s$/.test(t)&&!/^\s/.test(e)&&!/[([{]$/.test(t),s=n.length>0&&!/\s$/.test(e)&&!/^\s/.test(n)&&!/^[\])}.,;:!?]/.test(n);return`${r?" ":""}${e}${s?" ":""}`}function oB(e,t){return e?`${e}${/\s$/.test(e)?"":" "}${t}`:t}const iB=/^(https?:\/\/|mailto:)\S+$/i;function aB(e,t){return iB.test(e)&&!/\s/.test(e)&&t.trim().length>0&&!t.includes("](")}const cB="application/x-pichamber-file-path",lB=["files","text/uri-list","codefiles",cB];function dB(e,t){try{return e.getData(t)}catch{return""}}function il(e){if(!e)return!1;if(e.files&&e.files.length>0)return!0;if(e.types){const t=Array.from(e.types).map(n=>n.toLowerCase());if(lB.some(n=>t.includes(n))||t.some(n=>n.includes("vnd.code.tree")))return!0}for(const t of bL){const n=dB(e,t);if(n&&vL(n).length>0)return!0}return!1}function uB(e){if(!e)return[];const t=Array.from(e.files||[]);return t.length>0?t:Array.from(e.items||[]).filter(n=>n.kind==="file").map(n=>n.getAsFile()).filter(n=>!!n)}function fB({enabled:e,composerRef:t,messageRef:n,cursorPosRef:r,confirmedMentionsRef:s,setMessage:o,addAttachedFile:i}){const[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=p.useRef(0),h=p.useCallback(y=>{if(!il(y.dataTransfer))return;y.preventDefault(),y.stopPropagation(),u.current++;const v=y.dataTransfer.types?.includes("application/x-pichamber-file-path")??!1;v!==d&&f(v),e&&!a&&l(!0)},[e,a,d]),m=p.useCallback(y=>{il(y.dataTransfer)&&(y.preventDefault(),y.stopPropagation(),y.dataTransfer.dropEffect="copy",e&&!a&&l(!0))},[e,a]),g=p.useCallback(y=>{y.preventDefault(),y.stopPropagation(),u.current--,u.current<=0&&(u.current=0,l(!1),f(!1))},[]),x=p.useCallback(()=>{u.current=0,l(!1),f(!1)},[]),b=p.useCallback(async y=>{if(u.current=0,!il(y.dataTransfer)||(y.preventDefault(),y.stopPropagation(),l(!1),!e))return;const C=y.dataTransfer.getData("application/x-pichamber-file-path");if(C&&C!=="."){s.current.add(C);const I=`@${C}`,E=t.current,T=n.current;if(E){const{start:A,end:j}=E.getSelection(),k=T.slice(0,A),_=T.slice(j),M=k.length>0&&!/\s$/.test(k),L=_.length>0&&!/^\s/.test(_),O=`${M?" ":""}${I}${L?" ":""}`;E.replaceRange(A,j,O),r.current=A+O.length,E.focus()}else o(A=>L4(A,I));return}const w=uB(y.dataTransfer);w.length>0&&((await Promise.all(w.map(async E=>{try{return await i(E)}catch(T){return console.error("File attach failed",T),!1}}))).some(Boolean)||Ce.error("Failed to attach file"))},[i,t,s,r,e,n,o]),S=p.useCallback(y=>{il(y.dataTransfer)&&y.preventDefault()},[]);return{isDragging:a,isInternalDrag:d,handleDragEnter:h,handleDragOver:m,handleDragLeave:g,handleDragEnd:x,handleDrop:b,handleDropCapture:S}}const hB=16e3,pB="pasted-text.txt";function mB(e){return e.length>hB}function bv(e){return new File([e],pB,{type:"text/plain"})}function gB({inputMode:e,enabled:t,composerRef:n,message:r,setMessage:s,insertTextAtSelection:o,updateAutocompleteState:i,markFileMentionPasteSuppression:a,attachedFiles:l,addAttachedFile:d}){const f=p.useRef(new Set);return p.useCallback(async u=>{const h=u.clipboardData;if(!h)return;const m={...u,clipboardData:h,preventDefault:()=>u.preventDefault()},g=m.clipboardData.getData("text"),x=mB(g);if(e==="normal"&&t&&!x){const j=n.current,k=j?.getSelection().start??-1,_=j?.getSelection().end??-1;if(j&&_>k){const M=g.trim(),L=r.slice(k,_);if(aB(M,L)){m.preventDefault();const O=`${r.slice(0,k)}[${L}](${M})${r.slice(_)}`,N=k+1+L.length+2+M.length+1;s(O),n.current?.setSelection(N,N),i(O,N,lv(M),M);return}}}const b=new Map;Array.from(m.clipboardData.files||[]).forEach(j=>{j.type.startsWith("image/")&&b.set(`${j.name}-${j.size}`,j)}),Array.from(m.clipboardData.items||[]).forEach(j=>{if(j.kind==="file"&&j.type.startsWith("image/")){const k=j.getAsFile();k&&b.set(`${k.name}-${k.size}`,k)}});const S=Array.from(b.values());if(x){if(!t){g.includes("@")&&a();return}if(m.preventDefault(),S.length===0){const j=bv(g);try{await d(j)||Ce.error("Failed to attach pasted text as file")}catch{Ce.error("Failed to attach pasted text as file")}return}}else{if(S.length===0){g.includes("@")&&a();return}if(!t){g.includes("@")&&a();return}m.preventDefault()}const y=dF(S,[...l.map(j=>j.filename),...f.current]),v=uF(y),C=n.current,w=C?.getSelection().start??r.length,I=C?.getSelection().end??r.length,E=R4(oB(x?"":g,v),r.slice(0,w),r.slice(I));o(E,lv(E));const T=x?(async()=>{try{await d(bv(g))||Ce.error("Failed to attach pasted text as file")}catch{Ce.error("Failed to attach pasted text as file")}})():null,A=S.map(async(j,k)=>{const _=y[k],M=nF(j,_);f.current.add(_);try{await d(M)}catch(L){console.error("Clipboard image attach failed",L),Ce.error(L instanceof Error?L.message:"Failed to attach image from clipboard")}finally{f.current.delete(_)}});await Promise.all(T?[T,...A]:A)},[d,l,n,t,e,o,a,r,s,i])}const yB=(e,t)=>{if(t.size===0)return[];const n=new Map;for(const a of t){const l=a.toLowerCase();n.has(l)||n.set(l,a)}const r=new Set;for(const a of n.keys())r.add(`skill:${a}`);const s=zF(e,"/",r,"case-insensitive"),o=new Set,i=[];for(const a of s){const l=a.slice(6),d=n.get(l.toLowerCase())??l,f=d.toLowerCase();o.has(f)||(o.add(f),i.push(d))}return i},vB=e=>e.length===0?null:`The user explicitly mentioned these skills in their message: ${e.map(n=>`/skill:${n}`).join(", ")}. Use the corresponding skill tool when it is relevant to accomplishing the user's request.`;function xB(e,t){let n="",r=[],s;const o=[],i=[],a=u=>{for(const h of t.collectSkillNames(u))i.includes(h)||i.push(h)},l=u=>{!s&&u&&(s=u)},d=u=>{const h=t.parseAgentMention(u);l(h.agentName);const m=t.extractFileMentions(h.text);return a(m.text),m};if(e.queued.forEach((u,h)=>{const m=d(u.content),g=[...t.sanitizeAttachments(u.attachments),...m.attachments];if(h===0){n=m.text,r=g;return}o.push({text:m.text,attachments:g})}),e.composerText!==null){const u=d(e.composerText.replace(/^\n+|\n+$/g,"")),h=[...t.sanitizeAttachments(e.composerAttachments),...u.attachments];e.queued.length===0?(n=u.text,r=h):o.push({text:u.text,attachments:h})}for(const u of e.syntheticTexts)o.push({text:u,synthetic:!0});const f=t.buildSkillInstruction(i);return f&&o.push({text:f,synthetic:!0}),{primaryText:n,primaryAttachments:r,additionalParts:o,agentMentionName:s,isEmpty:!n&&r.length===0&&o.length===0}}function wv(e){const t=e.trimStart();if(!t.startsWith("/"))return null;const n=t.slice(1),r=n.trim().split(/\s+/)[0]?.toLowerCase()??"";return r?{name:r,argument:n.slice(r.length).trim()}:null}const bB=["undo","redo","timeline","compact"];function P4(e){return bB.includes(e)}async function wB({command:e,currentSessionId:t,scrollToBottom:n,setTimelineDialogOpen:r,onCompactSession:s,onUndoSession:o,onRedoSession:i}){const{name:a,argument:l}=e;return P4(a)?a==="undo"&&t?(await o(t),n?.(),!0):a==="redo"&&t?(await i(t),n?.(),!0):a==="timeline"&&t?(r(!0),!0):a==="compact"?t?(await s(t,l.trim()||void 0),!0):(Ce.error("Open a session before compacting."),!0):!1:!1}function SB(e){const{enabled:t,openAutocomplete:n,message:r,editorRef:s,containerRef:o}=e,[i,a]=p.useState(null),l=p.useCallback(()=>{if(!t){a(null);return}if(n===null){a(null);return}const d=s.current,f=o.current;if(!d||!f)return;const u=d.caretCoords();if(!u)return;const h=f.getBoundingClientRect(),m=u.top-h.top,g=u.left-h.left,x=8,b=260,S=m-x,y=h.height-m-x,v=y>=b||y>=S?"below":"above",C=n==="mention"?520:450,w=Math.max(x,Math.min(g-24,h.width-C-x)),I=Math.max(120,Math.min(b,v==="below"?y:S));a({top:v==="below"?m+22:m-6,left:w,place:v,maxHeight:I})},[o,s,t,n]);return p.useLayoutEffect(()=>{l()},[l,r,n,t]),p.useEffect(()=>{if(!t)return;const d=()=>l();return window.addEventListener("resize",d),()=>{window.removeEventListener("resize",d)}},[t,l]),{position:i,update:l}}const _u=-1,Wp={index:_u,stashedDraft:""},Kp=e=>({state:e,text:null});function CB(e,t,n){if(t.length===0)return Kp(e);if(e.index===_u)return{state:{index:0,stashedDraft:n},text:t[0]};if(e.index>=t.length-1)return Kp(e);const r=e.index+1;return{state:{...e,index:r},text:t[r]}}function kB(e,t){if(e.index===_u)return Kp(e);if(e.index===0)return{state:Wp,text:e.stashedDraft};const n=e.index-1;return{state:{...e,index:n},text:t[n]}}function MB(e){const[t,n]=p.useState(Wp),r=p.useCallback(i=>{const a=CB(t,e,i);return a.text===null?null:(n(a.state),a.text)},[e,t]),s=p.useCallback(()=>{const i=kB(t,e);return i.text===null?null:(n(i.state),i.text)},[e,t]),o=p.useCallback(()=>n(Wp),[]);return{isBrowsing:t.index!==_u,older:r,newer:s,reset:o}}const IB=500;function Sv(e,t){return`${e}\0${[...t].sort().join("\0")}`}function EB(e){const{message:t,messageRef:n,setMessage:r,confirmedMentionsRef:s,identity:o,persistEnabled:i,initialDraft:a,onIdentityChange:l,onDraftRestored:d}=e,f=p.useRef(null),u=p.useRef(!1),h=p.useRef(new Map),m=p.useRef(a.identity),g=p.useRef({onIdentityChange:l,onDraftRestored:d});g.current={onIdentityChange:l,onDraftRestored:d},p.useEffect(()=>{m.current=o},[o]);const x=p.useCallback((v,C)=>{if(!v)return;const w=Jt(v),I=new Set;for(const T of s.current)C.includes(`@${T}`)&&I.add(T);s.current=I;const E=Sv(C,I);h.current.get(w)!==E&&(Ts(v,C,I),h.current.set(w,E))},[s]),b=p.useCallback(()=>{f.current&&(clearTimeout(f.current),f.current=null)},[]),S=p.useRef(!1);p.useEffect(()=>{if(!S.current&&(S.current=!0,!!a.text)){if(!i){r(""),Ts(a.identity,"",[]);return}requestAnimationFrame(()=>g.current.onDraftRestored?.())}},[i]);const y=p.useRef(a.identity);return p.useEffect(()=>{const v=y.current,C=v?Jt(v):null,w=o?Jt(o):null;if(C===w)return;if(y.current=o,g.current.onIdentityChange?.(),b(),u.current=!0,!i){r(""),s.current=new Set;return}x(v,n.current);const I=ru(o);r(I.text),s.current=I.confirmedMentions,I.text&&requestAnimationFrame(()=>g.current.onDraftRestored?.())},[b,s,o,n,i,x,r]),p.useEffect(()=>GM(v=>{const C=Jt(v);h.current.set(C,Sv("",[]));const w=m.current;!w||Jt(w)!==C||(b(),u.current=!0,n.current="",s.current=new Set,r(""))}),[b,s,n,r]),p.useEffect(()=>{if(!i){b(),x(o,"");return}if(u.current){u.current=!1;return}b();const v=t,C=o;return f.current=setTimeout(()=>{f.current=null,x(C,v)},IB),b},[b,o,t,i,x]),p.useEffect(()=>{const v=()=>{b(),i&&x(m.current,n.current)},C=()=>{document.visibilityState==="hidden"&&v()};return document.addEventListener("visibilitychange",C),document.addEventListener("freeze",v),window.addEventListener("pagehide",v),()=>{document.removeEventListener("visibilitychange",C),document.removeEventListener("freeze",v),window.removeEventListener("pagehide",v),v()}},[b,n,i,x]),{persistNow:x}}function _B(e,t,n){const s=e.substring(0,t).lastIndexOf("@");if(s!==-1){const a=e.substring(0,s)+`@${n} `+e.substring(t),l=s+n.length+2;return{newMessage:a,nextCursor:l}}const o=e.substring(0,t)+`@${n} `+e.substring(t),i=t+n.length+2;return{newMessage:o,nextCursor:i}}function Cv(e,t,n,r){const o=e.substring(0,t).lastIndexOf(n),i=o!==-1?o:t,a=`${e.substring(0,i)}${n}${r} ${e.substring(t)}`,l=i+r.length+2;return{newMessage:a,nextCursor:l}}function jB({composerRef:e,message:t,setMessage:n,updateAutocompleteState:r,closeAutocomplete:s,confirmedMentionsRef:o,toMentionPath:i}){const a=p.useCallback(u=>{const h=e.current?.getSelection().start||0,m=u.relativePath&&u.relativePath.trim().length>0?u.relativePath.trim():i(u.path)||u.name;o.current.add(m);const{newMessage:g,nextCursor:x}=_B(t,h,m);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(x),r(g,x)}),s(),e.current?.focus()},[s,e,o,t,n,i,r]),l=p.useCallback(u=>{const h=e.current?.getSelection().start??t.length,{newMessage:m,nextCursor:g}=Cv(t,h,"@",u);n(m),requestAnimationFrame(()=>{e.current&&e.current.setSelection(g),r(m,g)}),s(),e.current?.focus()},[s,e,t,n,r]),d=p.useCallback((u,h)=>{const m=e.current?.getSelection().start??t.length,{newMessage:g,nextCursor:x}=Cv(t,m,"#",h);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(x),r(g,x)}),s(),e.current?.focus()},[s,e,t,n,r]),f=p.useCallback(u=>{const h=u.invocationName??u.name;n(`/${h} `),s();const m=()=>{if(e.current){try{e.current.focus({preventScroll:!0})}catch{e.current.focus()}e.current.setSelection(e.current.getValue().length,e.current.getValue().length)}};requestAnimationFrame(()=>{m(),requestAnimationFrame(m)}),setTimeout(m,60)},[s,e,n]);return{handleFileSelect:a,handleAgentSelect:l,handleSnippetSelect:d,handleCommandSelect:f}}const TB=e=>{const t="nativeEvent"in e?e.nativeEvent:e;return t.isComposing||t.keyCode===229},AB={"`":["`","`"],"*":["*","*"],_:["_","_"],"~":["~","~"],"(":["(",")"],"[":["[","]"],"{":["{","}"],'"':['"','"'],"'":["'","'"]};function NB(e,t,n,r){if(n<=t)return null;const s=AB[r];if(!s)return null;const[o,i]=s,a=e.slice(t,n);return{next:`${e.slice(0,t)}${o}${a}${i}${e.slice(n)}`,caretStart:t+o.length,caretEnd:n+o.length}}function LB(e,t,n,r){if(r!=="`"||t!==n)return null;const s=e.slice(0,t);if(/(^|\n)``$/.test(s)){const o=e.slice(n),i=`${s}\`
|
|
98
|
+
|
|
99
|
+
\`\`\`${o}`,a=s.length+2;return{next:i,caret:a}}return null}function RB({inputMode:e,setInputMode:t,shellExcludeFromContext:n,setShellExcludeFromContext:r,message:s,setMessage:o,openAutocomplete:i,commandRef:a,snippetRef:l,mentionRef:d,composerRef:f,messageHistory:u,updateAutocompleteState:h,isMobile:m,hasContent:g,currentSessionId:x,sessionPhase:b,commandRunning:S=!1,followUpBehavior:y,handleSubmit:v,handleQueueMessage:C}){return p.useCallback(w=>{if(TB(w))return;if(e==="shell"&&w.key==="Escape"){w.preventDefault(),t("normal");return}if(e==="shell"&&w.key==="Backspace"&&s.length===0){w.preventDefault(),n&&r?r(!1):t("normal");return}if(i==="command"&&a.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),a.current.handleKeyDown(w.key);return}if(i==="snippet"&&l.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),l.current.handleKeyDown(w.key);return}if(i==="mention"&&d.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),d.current.handleKeyDown(w.key);return}const I=i!==null,E=f.current?.getSelection().start===0&&f.current?.getSelection().end===0,T=f.current?.getSelection().start===s.length&&f.current?.getSelection().end===s.length,A=!I&&(s.length===0||E),j=!I&&(s.length===0||T);if(e==="normal"&&!I&&!w.metaKey&&!w.ctrlKey&&!w.altKey){const k=f.current,_=k?.getSelection().start??-1,M=k?.getSelection().end??-1;if(k&&_>=0){const L=(D,W,z)=>{w.preventDefault(),o(D),f.current?.setSelection(W,z),h(D,z)},O=NB(s,_,M,w.key);if(O){L(O.next,O.caretStart,O.caretEnd);return}const N=LB(s,_,M,w.key);if(N){L(N.next,N.caret,N.caret);return}}}if(w.key==="ArrowUp"&&A){w.preventDefault();const k=u.older(s);k!==null&&(o(k),requestAnimationFrame(()=>f.current?.setSelection(0,0)));return}if(w.key==="ArrowDown"&&j){w.preventDefault();const k=u.newer();k!==null&&o(k);return}if(w.key==="Enter"&&!w.shiftKey&&(!m||w.ctrlKey||w.metaKey)){w.preventDefault();const k=w.ctrlKey||w.metaKey,_=e==="normal"&&g&&x&&b!=="idle";S&&_?C():y==="queue"?k||!_?v():C():k||!_?v():v({delivery:"steer"})}},[a,S,f,x,y,C,v,g,e,m,d,s,u,i,b,t,o,r,n,l,h])}const PB=e=>e.enabled&&e.draftOpen&&!!e.directory&&e.gitAvailable&&e.isGitRepository,DB=(e,t)=>{const n=(e??[]).filter(r=>r.length>0&&!r.startsWith("remotes/")).sort((r,s)=>r.localeCompare(s)).map(r=>({value:r,label:r}));return t&&!n.some(r=>r.value===t)&&n.push({value:t,label:t}),n};function OB(e){const t=ct(z=>z.projects),n=Qt(z=>z.projects),r=p.useMemo(()=>Ln(t,{projects:n}),[t,n]),s=nt(z=>z.homeDirectory),o=p.useMemo(()=>x3(t,r),[r,t]),i=ct(z=>z.activeProjectId),a=ct(z=>z.setActiveProjectIdOnly),l=he(z=>z.newSessionDraft),d=he(z=>z.currentSessionId),f=he(z=>z.currentSessionDirectory),u=he(z=>z.setNewSessionDraftTarget),h=!!l?.open,m=vt(z=>z.fetchBranches),{git:g}=qa(),x=p.useMemo(()=>{if(h){const X=Yt(l?.directoryOverride??null),F=l?.selectedProjectId?o.find(U=>U.ownerProjectId===l.selectedProjectId&&(!X||Yt(U.path)===X))??o.find(U=>U.id===l.selectedProjectId)??null:null;if(F)return F;if(X){const U=o.find(P=>Yt(P.path)===X)??null;if(U)return U}}else if(d){const X=Yt(f??null);if(X&&ZI(X,s)){const U=o.find(P=>P.ownerProjectId===fr)??null;if(U)return U}const F=Zn(t,r,f);if(F){const U=Yt(f??null);return o.find(P=>P.ownerProjectId===F.id&&Yt(P.path)===U)??o.find(P=>P.id===F.id)??null}}return(i?o.find(X=>X.id===i)??null:null)??o[0]??null},[i,r,f,d,s,h,l?.directoryOverride,l?.selectedProjectId,o,t]),b=p.useMemo(()=>Yt(x?.path??null),[x?.path]),S=p.useMemo(()=>h?Yt(l?.directoryOverride??null)??b:Yt(f??null)??b,[f,h,l?.directoryOverride,b]),y=x?t.find(z=>z.id===x.ownerProjectId)??null:null,v=Yt(y?.path??null),C=x?za(x):null;p.useEffect(()=>{if(!CL({enabled:e,isDraftOpen:h,activeProjectId:i,selectedProjectId:l?.selectedProjectId}))return;const z=o.find(X=>X.id===i);z&&u({projectId:z.id,directoryOverride:z.path,branchIntent:null,worktreeIntent:null})},[i,e,h,l?.selectedProjectId,o,u]);const w=ku(S),I=vt(z=>S&&z.directories.get(S)?.status?.current?.trim()||null),E=t4(h?S:null),[T,A]=p.useState(!1);p.useEffect(()=>{const z=S?vt.getState().directories.get(S)?.branches??null:null;if(!PB({enabled:e,draftOpen:h,directory:S,gitAvailable:!!g,isGitRepository:w===!0})){A(!1);return}if(!S||!g)return;let X=!1;return A(z===null),m(S,g).finally(()=>{X||A(!1)}),()=>{X=!0}},[e,m,h,g,w,S]);const j=E?.current?.trim()||I,k=h&&(l?.worktreeIntent?.startRef?.trim()||l?.branchIntent?.branch?.trim())||null,_=k??j,M=p.useMemo(()=>h?DB(E?.all,k):[],[k,h,E?.all]),L=_??(w===!0?"Detached HEAD":null),O=w===!0&&!!(L||M.length>0||T),N=p.useCallback(z=>{if(!h)return;const X=o.find(U=>U.id===z),F=Yt(X?.path??null);if(!(!X||!F)){if(X.ownerProjectId===fr){u({projectId:fr,directoryOverride:F,branchIntent:null,worktreeIntent:null});return}i!==X.ownerProjectId&&a(X.ownerProjectId),u({projectId:X.ownerProjectId,directoryOverride:F,branchIntent:null,worktreeIntent:null})}},[i,h,o,a,u]),D=p.useCallback(z=>{if(!h||!S)return;const X=z.trim();if(!(!X||X.startsWith("remotes/"))){if(l?.worktreeIntent&&v){u({branchIntent:null,worktreeIntent:{runtimeKey:Y(),projectRoot:v,sourceDirectory:S,startRef:X}});return}u({worktreeIntent:null,branchIntent:{runtimeKey:Y(),directory:S,branch:X}})}},[h,l?.worktreeIntent,S,v,u]),W=p.useCallback(z=>{if(!(!h||!S||!v||!_)){if(z){u({branchIntent:null,worktreeIntent:{runtimeKey:Y(),projectRoot:v,sourceDirectory:S,startRef:_}});return}u({worktreeIntent:null,branchIntent:_===j?null:{runtimeKey:Y(),directory:S,branch:_}})}},[j,h,_,S,v,u]);return{projects:o,selectedDraftProject:x,selectedDraftProjectPath:b,selectedDraftProjectRoot:v,draftProjectLabel:C,selectedDraftDirectory:S,selectedDraftBranchLabel:L,selectedBranchName:_,currentBranch:j,draftBranchItems:M,isDiscoveringDraftBranches:T,shouldShowDraftBranchSelector:O,worktreeMode:!!(h&&l?.worktreeIntent),handleDraftProjectChange:N,handleDraftBranchChange:D,handleWorktreeModeChange:W}}const HB=e=>{const t=ce(e.targetDirectory)??e.targetDirectory,r=(e.projectId?e.projects.find(i=>i.id===e.projectId)??null:null)??e.projects.reduce((i,a)=>{const l=ce(a.path);if(!l||t!==l&&!t.startsWith(`${l}/`))return i;const d=ce(i?.path??null);return!d||l.length>d.length?a:i},null),s=ce(r?.path??null),o=new Set([t]);if(!s)return o;o.add(s);for(const[i,a]of e.availableWorktreesByProject)if(ce(i)===s)for(const l of a??[]){const d=ce(l?.path??null);d&&o.add(d)}return o},FB=(e,t)=>{const n=new Set(e.map(r=>r.id));return t.some(r=>!n.has(r.id))},kv=(e,t)=>{const n=ct.getState(),r=Ln(n.projects,Qt.getState()),s=HB({targetDirectory:e,projectId:t,projects:n.projects,availableWorktreesByProject:r});return SE().filter(o=>s.has(o.directory)).sort((o,i)=>(o.title??"").localeCompare(i.title??"")||o.id.localeCompare(i.id))};function BB(e){const{activeRuntimeKey:t,intent:n,onReady:r}=e,{git:s}=qa(),o=vt(I=>I.fetchStatus),i=vt(I=>I.fetchBranches),a=vt(I=>I.clearDiffCache),[l,d]=p.useState(null),f=p.useRef(!1),u=p.useRef(0),h=p.useRef(null),m=p.useRef(r);m.current=r;const g=n?.runtimeKey??"",x=n?.directory??"",b=n?.branch??"";p.useEffect(()=>{u.current+=1,h.current=null,d(null)},[t,b,x,g]);const S=p.useCallback(I=>{s&&(a(I),Cu.requestGitRefresh({directory:I}),Promise.all([o(I,s,{silent:!0}),i(I,s)]))},[a,i,o,s]),y=p.useCallback((I,E)=>{const T={runtimeKey:E.runtimeKey,directory:E.directory,branch:E.branch};h.current=T,m.current(I,T)},[]),v=p.useCallback(async I=>{const E=I.intent;if(!(f.current||l)){if(!s){Ce.error("Git is not available for the selected runtime.");return}if(E.runtimeKey!==Y()){Ce.error("The runtime changed. Select the branch again before sending.");return}f.current=!0;try{const[T,A]=await Promise.all([s.getGitBranches(E.directory),s.getGitStatus(E.directory,{mode:"light"})]),j=he.getState().newSessionDraft.branchIntent;if(!da(E,j))return;if(!T.all.includes(E.branch)||E.branch.startsWith("remotes/")){Ce.error(`Local branch ${E.branch} no longer exists.`),i(E.directory,s);return}if(A.mergeInProgress||A.rebaseInProgress||A.attentionReason){const L=A.attentionReason??(A.rebaseInProgress?"rebase":"merge");Ce.error(`Finish or abort the ${L} before switching branches.`);return}const k=A.current?.trim()||T.current?.trim()||null;if(k===E.branch){y(I.continuation,E);return}const _=I.projectId?ct.getState().projects.find(L=>L.id===I.projectId)?.label?.trim():null,M=E.directory.split(/[\\/]/).filter(Boolean).pop()||E.directory;d({runtimeKey:E.runtimeKey,projectId:I.projectId??null,directory:E.directory,branch:E.branch,currentBranch:k,projectLabel:_||M,changedFileCount:A.files.length,activeSessions:kv(E.directory,I.projectId),phase:"ready",continuation:I.continuation})}catch(T){Ce.error(T instanceof Error?T.message:"Failed to inspect the selected branch.")}finally{f.current=!1}}},[i,s,l,y]),C=p.useCallback(()=>{u.current+=1,h.current=null,d(null)},[]),w=p.useCallback(async()=>{const I=l;if(!I||I.phase==="checking"||I.phase==="terminal-error"||!s)return;const E=u.current+1;u.current=E,d({...I,phase:"checking",activeSessionsChanged:!1,error:void 0});try{const T=he.getState().newSessionDraft;if(!T.open||!da(T.branchIntent,I))throw Object.assign(new Error("The draft target changed. Press Send again to review the branch."),{terminal:!0});if(I.runtimeKey!==Y())throw Object.assign(new Error("The runtime changed. Select the branch again before sending."),{terminal:!0});const A=kv(I.directory,I.projectId);if(FB(I.activeSessions,A)){d({...I,activeSessions:A,phase:"ready",activeSessionsChanged:!0,error:void 0});return}const j=await s.getGitBranches(I.directory);if(u.current!==E)return;const k=j.current?.trim()||null;if(k!==I.currentBranch&&k!==I.branch)throw Object.assign(new Error(`The current branch changed to ${k??"detached HEAD"}. Press Send again to review it.`),{terminal:!0});if(!j.all.includes(I.branch)||I.branch.startsWith("remotes/"))throw Object.assign(new Error(`Local branch ${I.branch} no longer exists.`),{terminal:!0});if(k!==I.branch&&(await s.checkoutBranch(I.directory,I.branch,{expectedCurrent:k,localOnly:!0})).currentBranch!==I.branch)throw Object.assign(new Error(`Git did not confirm checkout of ${I.branch}.`),{terminal:!0});if(u.current!==E)return;if(I.runtimeKey!==Y()){Ce.warning("The branch may have changed on the previous runtime. The message was not sent.");return}S(I.directory),d(null),y(I.continuation,I)}catch(T){if(u.current!==E)return;const A=T instanceof Error?T.message:"Failed to check out the selected branch.";let j;try{j=(await s.getGitBranches(I.directory)).current?.trim()||null}catch{j=void 0}if(u.current!==E)return;S(I.directory);const k=!!(T&&typeof T=="object"&&"terminal"in T)||T&&typeof T=="object"&&"code"in T&&T.code==="BRANCH_CHANGED"||j===I.branch||j===void 0,_=j===I.branch?`Git switched to ${I.branch}, but reported an error: ${A} Review the repository, then press Send again.`:A;d({...I,phase:k?"terminal-error":"retryable-error",error:_})}},[s,l,S,y]);return{dialogState:l,request:v,confirm:w,cancel:C,getReceipt:I=>da(I,h.current)?h.current:null,clearReceipt:()=>{h.current=null}}}function VB(e){const{taskId:t,intent:n}=e,{git:r}=qa(),s=Qt(f=>f.refreshProject),o=t??a3(n),a=ln(p.useCallback(f=>o?f.entries.get(o)??null:null,[o]))?.state??null,l=p.useCallback(async f=>{try{const u=await ln.getState().request({taskId:t??void 0,intent:f.intent,prompt:f.prompt,...f.failedSend?{failedSend:f.failedSend}:{},git:r??void 0,refreshProject:s});return f.intent.runtimeKey!==Y()?null:u}catch(u){return u instanceof Error&&u.message===Pl,null}},[r,s,t]),d=p.useCallback(f=>{const u=o?ln.getState().getEntryByKey(o):ln.getState().getEntry(f);return!u?.receipt||!f?null:sN(f,u.receipt)?u.receipt:null},[o]);return{state:a,request:l,getReceipt:d}}function $B(e){const{isMobile:t,editorRef:n,formRef:r,controlsPanelOpen:s,attachMenuOpen:o}=e,[i,a]=p.useState(!1),[l,d]=p.useState(!1),f=p.useRef(0),u=p.useRef(!1),h=p.useRef(null);p.useEffect(()=>()=>{h.current!==null&&window.clearTimeout(h.current)},[]),p.useEffect(()=>{if(!t||typeof document>"u")return;let v=document.getElementById("mobile-overlay-root");v||(v=document.createElement("div"),v.id="mobile-overlay-root",document.body.appendChild(v));const C=v,w=()=>d(C.childElementCount>0);w();const I=new MutationObserver(w);return I.observe(C,{childList:!0}),()=>I.disconnect()},[t]);const m=l||s||o,g=p.useRef(0),x=p.useRef(0);p.useEffect(()=>{if(!t||lr()||typeof window>"u"||!window.matchMedia?.("(display-mode: standalone)")?.matches)return;const v=()=>{g.current+=1},C=()=>{if(g.current=Math.max(0,g.current-1),!u.current||g.current>0)return;u.current=!1,x.current=Date.now()+600,n.current?.focus(),n.current?.isFocused()&&a(!0);const w=()=>{const I=n.current;I?.isFocused()&&(r.current??I.getScrollDOM())?.scrollIntoView({block:"end"})};window.setTimeout(w,300),window.setTimeout(w,650)};return window.addEventListener("oc:mobile-overlay-opened",v),window.addEventListener("oc:mobile-overlay-closed",C),()=>{window.removeEventListener("oc:mobile-overlay-opened",v),window.removeEventListener("oc:mobile-overlay-closed",C)}},[n,r,t]),p.useEffect(()=>{if(!t)return;if(m){(i||Date.now()-f.current<800)&&(u.current=!0);return}if(!u.current)return;const v=window.setTimeout(()=>{u.current=!1,n.current?.focus({preventScroll:lr()})},180);return()=>window.clearTimeout(v)},[n,i,t,m]),p.useEffect(()=>{if(!t||lr()||typeof document>"u")return;const v=document.documentElement;return i?v.classList.add("oc-browser-keyboard-open"):(v.classList.remove("oc-browser-keyboard-open"),window.matchMedia?.("(display-mode: standalone)")?.matches&&window.setTimeout(()=>{v.classList.contains("oc-browser-keyboard-open")||(window.scrollTo(0,0),document.body.scrollTop=0,v.scrollTop=0)},350)),()=>v.classList.remove("oc-browser-keyboard-open")},[i,t]);const b=p.useCallback(()=>{t&&(lr()&&$E(),h.current!==null&&(window.clearTimeout(h.current),h.current=null),a(!0))},[t]),S=p.useCallback(()=>{if(t){if(Date.now()<x.current){const v=n.current;if(v){v.focus(),window.setTimeout(()=>{Date.now()<x.current&&!v.isFocused()&&v.focus()},50);return}}if(f.current=Date.now(),lr()){ba.flushSync(()=>a(!1));return}h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{h.current=null,a(!1)},120)}},[n,t]),y=p.useCallback(()=>{u.current=!1},[]);return{focused:i,onEditorFocus:b,onEditorBlur:S,cancelOverlayCloseRestore:y}}function Mv(e){e.style.position="",e.style.left="",e.style.right="",e.style.width="",e.style.top="",e.style.height="",e.style.zIndex="",e.style.background=""}function zB(e){const{isMobile:t,isFullscreen:n,isDraftScreen:r,isFocused:s,formRef:o,editorRef:i}=e;p.useLayoutEffect(()=>{if(!t||!n||lr())return;const a=window.visualViewport,l=o.current,d=i.current;if(!a||!l)return;document.documentElement.classList.add("oc-browser-kb-fullscreen");const f=()=>{const u=Math.max(0,Math.floor(a.offsetTop)),h=document.documentElement.clientHeight;l.style.position="fixed",l.style.left="0",l.style.right="0",l.style.top=`${u}px`,l.style.height=`${Math.floor(Math.min(a.height,h-u))}px`,l.style.zIndex="40",l.style.background="var(--background)"};return f(),a.addEventListener("resize",f),a.addEventListener("scroll",f),window.addEventListener("resize",f),window.addEventListener("scroll",f,!0),()=>{a.removeEventListener("resize",f),a.removeEventListener("scroll",f),window.removeEventListener("resize",f),window.removeEventListener("scroll",f,!0),document.documentElement.classList.remove("oc-browser-kb-fullscreen"),Mv(l),requestAnimationFrame(()=>{d?.isFocused()&&d.getScrollDOM()?.scrollIntoView({block:"nearest"})})}},[i,o,n,t]),p.useLayoutEffect(()=>{if(!t||lr()||!r||n||!s)return;const a=window.visualViewport,l=o.current;if(!a||!l)return;const d=l.getBoundingClientRect();l.style.position="fixed",l.style.left=`${Math.floor(d.left)}px`,l.style.width=`${Math.floor(d.width)}px`,l.style.zIndex="40",l.style.background="var(--background)";let f=Number.NaN,u=0;const h=()=>{const m=document.documentElement.clientHeight,g=a.offsetTop+a.height,x=Math.max(0,Math.floor(Math.min(g,m)-l.offsetHeight));x!==f&&(f=x,l.style.top=`${x}px`),u=requestAnimationFrame(h)};return h(),()=>{cancelAnimationFrame(u),Mv(l)}},[o,r,s,n,t])}const UB=600*1e3,Iv=60*1e3,qB=[2e3,5e3,15e3],WB=200,qn=new Map,Td=new Set,D4=()=>{for(const e of Td)e()},KB=e=>(Td.add(e),()=>{Td.delete(e)});en(D4);const V1=e=>{const t=e?.trim();return t?t.length>1?t.replace(/[\\/]+$/,""):t:null},$1=e=>`${Y()}\0${e}`,mh=(e,t)=>{const n=qn.get(e);for(n?.url&&n.url!==t.url&&URL.revokeObjectURL(n.url),qn.delete(e),qn.set(e,t);qn.size>WB;){const[r,s]=qn.entries().next().value;s.url&&URL.revokeObjectURL(s.url),qn.delete(r)}D4()},GB=async e=>{const t=await Rt("/api/fs/project-icon",{query:{directory:e}});if(t.status===204)return null;if(!t.ok)throw new Error(`Project icon request failed (${t.status})`);const n=await t.blob();return n.size===0||!n.type.startsWith("image/")?null:URL.createObjectURL(n)},O4=(e,t,n=!1)=>{const r=qn.get(e);if(r&&(r.loading||!n&&r.expiresAt>Date.now()))return;const s=r?.failures??0;mh(e,{url:r?.url??null,expiresAt:0,loading:!0,failures:s}),GB(t).then(o=>{if(qn.get(e)?.loading!==!0){o&&URL.revokeObjectURL(o);return}mh(e,{url:o,expiresAt:Date.now()+(o?UB:Iv),loading:!1,failures:0})},()=>{const o=qn.get(e);if(o?.loading!==!0)return;const i=qB[s];mh(e,{url:o.url,expiresAt:Date.now()+(i??Iv),loading:!1,failures:s+1}),i!==void 0&&setTimeout(()=>{Td.size>0&&O4(e,t,!0)},i)})},ZB=e=>{const t=V1(e);return t?qn.get($1(t))?.url??null:null},YB=e=>{const t=V1(e);t&&O4($1(t),t)},XB=e=>{const t=p.useSyncExternalStore(KB,()=>ZB(e),()=>null),n=V1(e),r=n?$1(n):null;return p.useEffect(()=>{r&&YB(e)},[r,e]),t},gh=["var(--syntax-keyword)","var(--syntax-string)","var(--syntax-number)","var(--syntax-function)","var(--syntax-type)","var(--syntax-variable)","var(--primary)"],JB=e=>{const t=e.normalize("NFKC").match(/[\p{L}\p{N}]/u)?.[0];return t?t.toLocaleUpperCase():"?"},QB=e=>{let t=0;for(const n of e.normalize("NFKC").trim().toLowerCase())t=t*31+(n.codePointAt(0)??0)>>>0;return gh[t%gh.length]??gh[0]},eV=e=>({text:JB(e),color:QB(e)}),eo=16,tV=96,nV=.12,rV=.6,Ev=.1;function sV(e){let t=0,n=0,r=0;for(let s=0;s+3<e.length;s+=4){if(e[s+3]<tV)continue;t+=1;const o=wp({r:e[s],g:e[s+1],b:e[s+2]});o>nV&&(n+=1),o<rV&&(r+=1)}return t===0?"mixed":n/t<=Ev?"dark":r/t<=Ev?"light":"mixed"}const oV=400,ho=new Map;function iV(e){return ho.get(e)}function aV(e,t){const n=ho.get(t);if(n)return n;let r="mixed";try{const s=document.createElement("canvas");s.width=eo,s.height=eo;const o=s.getContext("2d",{willReadFrequently:!0});o&&(o.drawImage(e,0,0,eo,eo),r=sV(o.getImageData(0,0,eo,eo).data))}catch{r="mixed"}if(ho.set(t,r),ho.size>oV){const s=ho.keys().next().value;s!==void 0&&ho.delete(s)}return r}const _v=new Set,jv=new WeakMap,cV=e=>{const t=jv.get(e);if(t!==void 0)return t;const n=new Set;for(const s of e.byId.values()){if(s.archived||s.lifecycle!=="busy"&&s.lifecycle!=="retry")continue;const o=ce(s.directory);o&&n.add(o)}const r=[...n].sort().join(`
|
|
100
|
+
`);return jv.set(e,r),r},lV=(e,t,n)=>{if(!e)return _v;const r=Ln(t,{projects:n}),s=new Set;for(const o of e.split(`
|
|
101
|
+
`)){const i=Zn(t,r,o),a=ce(i?.path??null);a&&s.add(a)}return s.size>0?s:_v};let to=null;const dV=(e,t,n)=>{if(to&&to.liveDirectoriesKey===e&&to.projects===t&&to.worktreeProjects===n)return to.paths;const r=lV(e,t,n);return to={liveDirectoriesKey:e,projects:t,worktreeProjects:n,paths:r},r},uV=e=>cV(e.catalog),fV=e=>{const t=Be(uV,void 0,"catalog"),n=ct(o=>o.projects),r=Qt(o=>o.projects),s=ce(e??null);return!s||!t?!1:dV(t,n,r).has(s)};function hV({directory:e,label:t,className:n}){const r=XB(e),s=fV(e),[o,i]=p.useState(null),[a,l]=p.useState(null),d=s?void 0:"grayscale",f=r?a?.url===r?a.tone:iV(r):void 0;return r&&r!==o?c.jsx("img",{src:r,alt:"","aria-hidden":"true",draggable:!1,onError:()=>i(r),onLoad:u=>{f||l({url:r,tone:aV(u.currentTarget,r)})},"data-project-icon":"image","data-icon-tone":f&&f!=="mixed"?f:void 0,"data-agent-active":s?"":void 0,className:R("size-4 shrink-0 rounded-[25%] object-contain",d,n)}):c.jsx(pV,{label:t,active:s,className:R(d,n)})}function pV({label:e,active:t,className:n}){const r=p.useMemo(()=>eV(e),[e]);return c.jsx("span",{"aria-hidden":"true","data-project-icon":"mark","data-agent-active":t?"":void 0,className:R("inline-flex size-4 shrink-0 items-center justify-center overflow-hidden rounded-[25%]",n),style:{color:r.color,backgroundColor:`color-mix(in srgb, ${r.color} 20%, transparent)`},children:c.jsx("svg",{viewBox:"0 0 16 16",className:"size-full select-none",children:c.jsx("text",{x:"8",y:"11.7",textAnchor:"middle",fill:"currentColor",fontSize:"10.5",fontWeight:700,children:r.text})})})}const z1=(e,t)=>{const[n,r]=p.useState(e),s=p.useRef(null),o=p.useCallback(()=>{s.current!==null&&typeof window<"u"&&(window.clearTimeout(s.current),s.current=null)},[]);p.useEffect(()=>o,[o]);const i=p.useCallback(()=>{o(),r(e)},[o,e]),a=p.useCallback(l=>{o(),r(l),!(typeof window>"u")&&(s.current=window.setTimeout(()=>{r(e),s.current=null},t))},[o,t,e]);return{value:n,show:a,clear:i}},H4=20,mV=24,gV=(e,t)=>e.length<=t?e:`${e.slice(0,t-1)}…`;function Ad({project:e,maxCharacters:t}){const n=za(e),r=e.id==="__home__"||e.ownerProjectId==="__home__",s=e.kind==="worktree";return c.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:n,children:[s||r?c.jsx(V,{name:s?"git-branch":"home",className:"size-3.5 shrink-0 text-muted-foreground"}):c.jsx(hV,{directory:e.path,label:n,className:"size-3.5"}),s?c.jsx(l1,{value:n,showTitle:!1,className:"text-muted-foreground",style:t?{maxWidth:`${t}ch`}:void 0}):c.jsx("span",{className:"truncate text-muted-foreground",children:t?gV(n,t):n})]})}const Tv="h-7 min-w-0 w-fit max-w-[48vw] gap-1 border-transparent bg-transparent px-1.5 text-muted-foreground typography-meta font-normal hover:bg-transparent hover:text-foreground data-[popup-open]:bg-transparent [&_svg]:size-3.5 [&_svg]:opacity-70 sm:max-w-none",F4=({checked:e,onChange:t,showCheck:n=!0,chromeLess:r=!1,keepWidth:s=!1})=>c.jsxs(wt,{delayDuration:300,children:[c.jsx(St,{asChild:!0,children:c.jsxs(be,{variant:r?"ghost":"chip",size:"xs",className:R(s?"shrink-0":"min-w-0 max-w-[48vw] shrink sm:max-w-none",r&&"aria-pressed:bg-interactive-hover aria-pressed:text-foreground"),"aria-pressed":e,onClick:()=>t?.(!e),children:[c.jsx(V,{name:"git-branch",className:"size-3.5"}),c.jsx("span",{className:"truncate",children:"New worktree"}),e&&n?c.jsx(V,{name:"check",className:"size-3.5"}):null]})}),c.jsx(Ct,{side:"top",sideOffset:6,className:"max-w-72",children:"Starts from the selected branch's latest commit. Uncommitted changes are not copied."})]}),yV=({label:e,startFrom:t=!1})=>{const n=e??"Branch";return c.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:e??void 0,children:[c.jsx(V,{name:"git-branch",className:"size-3.5 shrink-0 text-muted-foreground"}),t&&e?c.jsx("span",{className:"shrink-0 text-subtle-foreground",children:"from"}):null,e?c.jsx(l1,{value:e,showTitle:!1}):c.jsx("span",{className:"truncate",children:n})]})};function vV({branchName:e}){const{value:t,show:n}=z1(!1,2e3),r=p.useCallback(async s=>{if(s.stopPropagation(),s.preventDefault(),!e)return;(await yr(e)).ok?n(!0):Ce.error("Failed to copy")},[e,n]);return e?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Copy branch name",onClick:s=>{r(s)},children:t?c.jsx(V,{name:"check",className:"size-3.5 text-[color:var(--status-success)]"}):c.jsx(V,{name:"file-copy",className:"size-3.5"})})}),c.jsx(Ct,{sideOffset:6,children:t?"Copied":"Copy branch name"})]}):null}function xV(e){const{projects:t,selectedProject:n,selectedBranchName:r,selectedBranchLabel:s,branchOptions:o,branchInteractive:i,branchLoading:a,showBranchSelector:l,showProjectSelector:d=!0,showWorktreeSelector:f=!1,worktreeMode:u=!1,endAccessory:h,onProjectChange:m,onBranchChange:g,onWorktreeModeChange:x,theme:b}=e;return c.jsxs("div",{className:"mb-3 flex min-w-0 w-full items-center justify-between gap-2 pl-2 pr-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[d?c.jsxs(xy,{value:n.id,onValueChange:m,children:[c.jsx(wy,{size:"sm",className:R(Tv,"shrink-0"),children:c.jsx(by,{children:c.jsx(Ad,{project:n,theme:b,maxCharacters:H4})})}),c.jsx(Sy,{className:"w-max min-w-48",children:t.map(S=>c.jsx(Cy,{value:S.id,className:S.kind==="worktree"?"max-w-[24rem] truncate pl-7":"max-w-[24rem] truncate",children:c.jsx(Ad,{project:S,theme:b})},S.id))})]}):null,l&&i?c.jsxs(xy,{value:r??void 0,onValueChange:g,disabled:!!(a&&o.length===0),children:[c.jsx(wy,{size:"sm",className:Tv,children:c.jsx(by,{children:c.jsx(yV,{label:s,startFrom:u})})}),c.jsx(Sy,{className:"w-max min-w-56",children:c.jsxs(ZR,{children:[c.jsx(YR,{children:a?"Loading branches...":"Local branches"}),o.map(S=>c.jsx(Cy,{value:S.value,className:"max-w-[28rem] truncate",children:S.label},S.value))]})})]}):null,f?c.jsx(F4,{checked:u,onChange:x,keepWidth:!0}):null]}),h?c.jsx("div",{className:"min-w-0 shrink-0",children:h}):null]})}function bV(e){const{selectedProject:t,selectedBranchName:n,selectedBranchLabel:r,branchInteractive:s,showBranchSelector:o,showProjectSelector:i=!0,showWorktreeSelector:a=!1,worktreeMode:l=!1,onWorktreeModeChange:d,endAccessory:f,theme:u,onOpenPicker:h}=e,m=r?c.jsx(l1,{value:r,showTitle:!1,style:{maxWidth:`${mV}ch`}}):c.jsx("span",{className:"truncate",children:"Branch"});return c.jsxs("div",{className:"mb-1.5 flex min-w-0 w-full flex-col gap-0.5 pl-2 pr-1",children:[a?c.jsx("div",{className:"flex w-full justify-end",children:c.jsx(F4,{checked:l,onChange:d,showCheck:!1,chromeLess:!0})}):null,c.jsxs("div",{className:"flex min-w-0 w-full items-center gap-x-1",children:[i?c.jsxs("button",{type:"button",className:"inline-flex h-7 min-w-0 max-w-[44%] shrink cursor-pointer items-center gap-1 rounded-lg px-1.5 typography-meta font-medium text-foreground/80 hover:bg-[var(--interactive-hover)]",onClick:()=>h("project"),children:[c.jsx(Ad,{project:t,theme:u,maxCharacters:H4}),c.jsx(V,{name:"arrow-down-s",className:"h-3 w-3 shrink-0 text-muted-foreground"})]}):null,o&&s?c.jsxs("button",{type:"button",className:`inline-flex h-7 min-w-0 cursor-pointer items-center gap-1 rounded-lg px-1.5 typography-meta font-medium text-foreground/80 hover:bg-[var(--interactive-hover)] ${i?"ml-auto max-w-[54%] shrink":"flex-1"}`,onClick:()=>h("branch"),title:r??void 0,children:[c.jsx(V,{name:"git-branch",className:"h-3 w-3 shrink-0 text-muted-foreground"}),l&&r?c.jsx("span",{className:"shrink-0 text-subtle-foreground",children:"from"}):null,m,c.jsx(V,{name:"arrow-down-s",className:"h-3 w-3 shrink-0 text-muted-foreground"})]}):o?c.jsxs("div",{className:`inline-flex h-7 min-w-0 items-center gap-1 px-1.5 typography-meta text-muted-foreground ${i?"ml-auto max-w-[54%] shrink":"min-w-0 flex-1"}`,title:r??void 0,children:[c.jsx(V,{name:"git-branch",className:"h-3 w-3 shrink-0"}),l&&r?c.jsx("span",{className:"shrink-0 text-subtle-foreground",children:"from"}):null,m,c.jsx(vV,{branchName:n})]}):null,!i&&f?c.jsx("div",{className:`min-w-0 shrink-0 ${o?"":"ml-auto"}`,children:f}):null]})]})}function wV(e){const{projects:t,selectedProject:n,selectedBranchName:r,branchOptions:s,branchInteractive:o,onProjectChange:i,onBranchChange:a,theme:l,openPicker:d,onOpenPickerChange:f,showProjectSelector:u=!0,showBranchSelector:h,query:m="",onQueryChange:g}=e,[x,b]=p.useState("");p.useEffect(()=>{d!=="project"&&b(""),d!=="branch"&&g?.("")},[g,d]);const S=p.useMemo(()=>{const v=x.trim().toLowerCase();return v?t.filter(C=>za(C).toLowerCase().includes(v)||C.path.toLowerCase().includes(v)):t},[x,t]),y=p.useMemo(()=>{const v=m.trim().toLowerCase();return v?s.filter(C=>C.label.toLowerCase().includes(v)):s},[s,m]);return c.jsxs(c.Fragment,{children:[c.jsx(Ta,{open:u&&d==="project",onClose:()=>f(null),title:"Project",children:c.jsxs("div",{className:"flex flex-col py-1",children:[t.length>5?c.jsx("div",{className:"px-3 pb-2 pt-1",children:c.jsx(Uo,{value:x,onChange:v=>b(v.target.value),placeholder:"Search projects...",className:"h-8 typography-meta",autoFocus:!0})}):null,c.jsx("div",{className:"max-h-[60vh] overflow-y-auto px-2",children:S.map(v=>{const C=v.id===n.id;return c.jsxs("button",{type:"button",onClick:()=>{i(v.id),f(null)},className:`flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-2 text-left typography-ui-label transition-colors hover:bg-[var(--interactive-hover)] ${v.kind==="worktree"?"pl-7 ":""}${C?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[c.jsx(Ad,{project:v,theme:l}),C?c.jsx(V,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},v.id)})})]})}),c.jsx(Ta,{open:o&&h&&d==="branch",onClose:()=>f(null),title:"Branch",children:c.jsxs("div",{className:"flex flex-col py-1",children:[s.length>5?c.jsx("div",{className:"px-3 pb-2 pt-1",children:c.jsx(Uo,{value:m,onChange:v=>g?.(v.target.value),placeholder:"Search branches...",className:"h-8 typography-meta",autoFocus:!0})}):null,c.jsx("div",{className:"max-h-[60vh] overflow-y-auto px-2",children:y.map(v=>{const C=v.value===r;return c.jsxs("button",{type:"button",onClick:()=>{a(v.value),f(null)},className:`flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-2 text-left typography-ui-label transition-colors hover:bg-[var(--interactive-hover)] ${C?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[c.jsx("span",{className:"truncate",children:v.label}),C?c.jsx(V,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},v.value)})})]})})]})}function SV(e){const{state:t,onCancel:n,onConfirm:r}=e,s=t?.phase==="checking",o=t?.phase==="terminal-error";return c.jsx(gu,{open:t!==null,onOpenChange:i=>{!i&&!s&&n()},children:c.jsxs(yu,{showCloseButton:!1,className:"max-w-md gap-5",children:[c.jsxs(vu,{children:[c.jsx(xu,{children:o?"Branch checkout needs attention":"Check out branch?"}),c.jsx(s1,{children:t?`PiChamber will check out "${t.branch}" in "${t.projectLabel}" before creating the session. This changes the files used by every session and terminal in this folder.`:""})]}),t?.activeSessions.length?c.jsxs("section",{"aria-live":"polite",className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[c.jsx("h3",{className:"typography-ui-label font-medium text-foreground",children:t.activeSessions.length===1?"Another session is active in this project":`${t.activeSessions.length} other sessions are active in this project`}),c.jsx("p",{className:"mt-1 typography-meta text-muted-foreground",children:"Switching branches may interrupt sessions using this folder or conflict with work in a related worktree."}),c.jsx("ul",{className:"mt-2 max-h-32 list-disc space-y-1 overflow-y-auto pl-5 typography-meta text-foreground",children:t.activeSessions.map(i=>c.jsx("li",{children:i.title??"Untitled session"},i.id))}),t.activeSessionsChanged?c.jsx("p",{className:"mt-2 typography-meta font-medium text-status-warning",children:"The active session list changed. Review it before continuing."}):null]}):null,t?.changedFileCount?c.jsx("p",{className:"typography-ui-label text-muted-foreground",children:t.changedFileCount===1?"This folder has 1 uncommitted file. Git may block the checkout if it conflicts.":`This folder has ${t.changedFileCount} uncommitted files. Git may block the checkout if they conflict.`}):null,t?.error?c.jsx("p",{role:"alert",className:"typography-ui-label text-status-error",children:t.error}):null,c.jsxs(Mj,{children:[c.jsx(be,{variant:"outline",onClick:n,disabled:s,children:o?"Close":"Cancel"}),o?null:c.jsx(be,{onClick:r,disabled:s,children:s?"Checking out...":t?.phase==="retryable-error"?"Try again":"Check out and send"})]})]})})}const U1=(e,t)=>{const[n,r]=p.useState(void 0);return p.useLayoutEffect(()=>{if(!t)return;const s=()=>{const o=e.current;if(!o)return;const i=o.closest("main");if(!i)return;const a=window.visualViewport?.offsetTop??0,l=Math.max(i.getBoundingClientRect().top,a),d=o.getBoundingClientRect().bottom-l-8,f=Math.max(120,Math.floor(d));r(u=>u===f?u:f)};return s(),window.addEventListener("resize",s),window.addEventListener("oc:keyboard-settled",s),window.visualViewport?.addEventListener("resize",s),window.visualViewport?.addEventListener("scroll",s),()=>{window.removeEventListener("resize",s),window.removeEventListener("oc:keyboard-settled",s),window.visualViewport?.removeEventListener("resize",s),window.visualViewport?.removeEventListener("scroll",s)}}),t?n:void 0},Kr=e=>e.invocationName??e.name;function Av(e,t){const n=Kr(e),r=Kr(t),s=e.searchAliases??[],o=[...s,...n===r&&e.name===t.name?[]:[t.name],...t.invocationName&&t.invocationName!==t.name&&t.invocationName!==n?[t.invocationName]:[],...t.description?[t.description]:[],...t.searchAliases??[]].filter((a,l,d)=>a!==e.description&&d.indexOf(a)===l);return o.length===s.length&&o.every((a,l)=>a===s[l])?e:{...e,searchAliases:o}}function CV(e,t,n,r=[]){const s=[],o=new Map,i=(a,l)=>{for(const d of a){const f=l(d),u=Kr(d),h=o.get(u);if(!h){o.set(u,{index:s.length,item:d,precedence:f}),s.push(d);continue}const m=f>h.precedence?Av(d,h.item):Av(h.item,d);s[h.index]=m,o.set(u,{index:h.index,item:m,precedence:Math.max(h.precedence,f)})}};return i(e,()=>4),i(t,a=>a.isBuiltIn?4:a.source==="extension"?3:a.isSkill?1:0),i(n,()=>2),i(r,()=>1),s}function Nv(e,t){switch(t){case"all":return!0;case"system":return!!e.isBuiltIn||e.source==="pichamber"||e.source==="system";case"skills":return!!e.isSkill||e.source==="skill";case"extensions":return e.source==="extension";case"prompts":return e.source==="prompt"}}function kV(e,t){return yo(e.name,t)||yo(Kr(e),t)||!!(e.description&&yo(e.description,t))||!!e.searchAliases?.some(n=>yo(n,t))}function MV(e,t,n){const r=t.trim(),s=r.toLowerCase(),i=[...r?e.filter(a=>Nv(a,n)&&kV(a,r)):e.filter(a=>Nv(a,n))];return i.sort((a,l)=>{const d=Kr(a).toLowerCase(),f=Kr(l).toLowerCase(),u=s.length>0&&d.startsWith(s),h=s.length>0&&f.startsWith(s);return u&&!h?-1:!u&&h?1:d.localeCompare(f)}),i}function IV(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function EV(e){return`command-listbox-${e.length>0?e:"commands"}`}function Gp(e,t){return`${e}-option-${t}`}function _V(e){if(!e.loading&&e.hasSelectedCommand)return Gp(e.listboxId,e.selectedIndex)}const Lv=e=>{if(e.source==="skill"||e.isSkill)return"Skill";if(e.source==="extension")return"Extension";if(e.source==="prompt")return"Prompt";if(e.source==="system"||e.source==="pichamber"||e.isBuiltIn)return"System";const t=[e.scope,e.agent].filter(n=>!!n);return t.length>0?t.join(" · "):null},jV=[{value:"all",label:"All"},{value:"system",label:"System"},{value:"prompts",label:"Prompts"},{value:"skills",label:"Skills"},{value:"extensions",label:"Extensions"}],B4=p.forwardRef(({searchQuery:e,onCommandSelect:t,onClose:n,style:r,onComboboxStateChange:s},o)=>{const i=he(N=>N.currentSessionId),l=Jm(i??"").length>0,d=!!i,f=re(N=>N.isMobile),[u,h]=p.useState("all"),m=Jn(),{commands:g,isLoading:x}=C4(m),[b,S]=p.useState([]),[y,v]=p.useState(!1),[C,w]=p.useState(0),I=p.useRef(0),E=p.useRef(!1),T=p.useRef([]),A=p.useRef(null),j=U1(A,f),k=p.useRef(!1),_=p.useRef(null),M=p.useRef(!1),L=p.useId(),O=p.useMemo(()=>EV(IV(L)),[L]);return p.useEffect(()=>{const N=D=>{const W=D.target;!W||!A.current||A.current.contains(W)||n()};return document.addEventListener("pointerdown",N,!0),()=>{document.removeEventListener("pointerdown",N,!0)}},[n]),p.useEffect(()=>{v(x);const N=g.filter(X=>X.source==="system").filter(X=>X.invocationName==="compact"?!0:d).map(X=>({id:X.id,name:X.name,invocationName:X.invocationName,source:"system",description:X.description,isBuiltIn:!0,...X.scope?{scope:X.scope}:{}})),D=g.filter(X=>X.source!=="system").map(X=>({id:X.id,name:X.name,invocationName:X.invocationName,source:X.source,description:X.description,...X.source==="skill"?{isSkill:!0}:{},...X.scope?{scope:X.scope}:{}})),W=CV(N,D.filter(X=>X.source==="extension"),D.filter(X=>X.source==="skill"),D.filter(X=>X.source==="prompt"));S(MV(W,e,f?"all":u))},[e,d,l,g,x,u,f]),p.useEffect(()=>{w(0)},[b]),p.useEffect(()=>{I.current=C},[C]),p.useEffect(()=>{s?.({listboxId:O,activeOptionId:_V({loading:y,hasSelectedCommand:!!b[C],selectedIndex:C,listboxId:O})})},[b,O,y,s,C]),p.useEffect(()=>{T.current[C]?.scrollIntoView({block:"nearest"})},[C]),p.useImperativeHandle(o,()=>({handleKeyDown:N=>{const D=b.length;if(N==="Escape"){n();return}if(D!==0){if(N==="ArrowDown"){E.current=!0,w(W=>(W+1)%D);return}if(N==="ArrowUp"){E.current=!0,w(W=>(W-1+D)%D);return}if(N==="Enter"||N==="Tab"){const W=(I.current%D+D)%D,z=b[W];z&&t(z)}}}}),[b,n,t]),f?c.jsx("div",{ref:A,className:"absolute bottom-full left-0 z-[100] mb-2 flex max-h-60 min-w-0 w-full max-w-[450px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-none",style:j!==void 0?{...r,maxHeight:j}:r,children:c.jsx(Xn,{role:"listbox",id:O,"aria-label":"Commands",preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:y?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(V,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):c.jsxs("div",{children:[b.map((N,D)=>{const W=D===C,z=Lv(N),X=Kr(N);return c.jsx("div",{id:Gp(O,D),ref:F=>{T.current[D]=F},role:"option","aria-selected":W,className:R("flex cursor-pointer items-center gap-2 rounded-lg px-3 py-1.5 typography-ui-label",W?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:F=>F.preventDefault(),onPointerDown:F=>{F.pointerType==="touch"&&(_.current={x:F.clientX,y:F.clientY},M.current=!1)},onPointerMove:F=>{if(F.pointerType!=="touch"||!_.current)return;const U=F.clientX-_.current.x,P=F.clientY-_.current.y;Math.hypot(U,P)>6&&(M.current=!0)},onPointerUp:F=>{if(F.pointerType!=="touch")return;const U=M.current;_.current=null,M.current=!1,!U&&(F.preventDefault(),F.stopPropagation(),k.current=!0,t(N))},onPointerCancel:()=>{_.current=null,M.current=!1},onClick:()=>{if(k.current){k.current=!1;return}t(N)},onMouseMove:()=>{E.current=!1,w(D)},children:c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono font-semibold",children:["/",X]}),z&&c.jsx("span",{className:"shrink-0 rounded border border-[var(--interactive-border)]/60 bg-[var(--surface-muted)] px-1.5 py-1 text-[10px] font-bold uppercase leading-none tracking-tight text-muted-foreground",children:z})]})},N.id)}),b.length===0&&c.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})})}):c.jsxs("div",{ref:A,className:"absolute bottom-full left-0 z-[100] flex max-h-80 min-w-0 w-full max-w-[520px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-lg",style:j!==void 0?{...r,maxHeight:j}:r,children:[c.jsx("div",{role:"group","aria-label":"Filter commands",className:"flex shrink-0 flex-wrap items-center gap-1 border-b border-border/60 px-2 py-1.5",children:jV.map(N=>c.jsx(be,{variant:"chip",size:"xs","aria-pressed":u===N.value,onMouseDown:D=>D.preventDefault(),onClick:()=>h(N.value),children:N.label},N.value))}),c.jsx(Xn,{role:"listbox",id:O,"aria-label":"Commands",preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:y?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(V,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):c.jsxs("div",{children:[b.map((N,D)=>{const W=D===C,z=Lv(N),X=Kr(N);return c.jsx("div",{id:Gp(O,D),ref:F=>{T.current[D]=F},role:"option","aria-selected":W,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",W?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:F=>F.preventDefault(),onPointerDown:F=>{F.pointerType==="touch"&&(_.current={x:F.clientX,y:F.clientY},M.current=!1)},onPointerMove:F=>{if(F.pointerType!=="touch"||!_.current)return;const U=F.clientX-_.current.x,P=F.clientY-_.current.y;Math.hypot(U,P)>6&&(M.current=!0)},onPointerUp:F=>{if(F.pointerType!=="touch")return;const U=M.current;_.current=null,M.current=!1,!U&&(F.preventDefault(),F.stopPropagation(),k.current=!0,t(N))},onPointerCancel:()=>{_.current=null,M.current=!1},onClick:()=>{if(k.current){k.current=!1;return}t(N)},onMouseMove:()=>{E.current=!1,w(D)},children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono typography-ui-label font-medium",children:["/",X]}),z&&c.jsx("span",{className:R("ml-auto max-w-[45%] shrink-0 truncate text-xs leading-4",W?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:z})]}),N.description&&c.jsx("div",{className:R("mt-1 truncate text-xs leading-5",W?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:N.description}),N.source==="skill"&&N.name!==X&&c.jsx("div",{className:R("mt-0.5 truncate text-xs leading-4",W?"text-interactive-selection-foreground/60":"text-subtle-foreground"),children:N.name})]})},N.id)}),b.length===0&&c.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),!f&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs leading-4 text-muted-foreground",children:"↑↓ Navigate · Enter Select · Esc Close"})]})});B4.displayName="CommandAutocomplete";const TV=(e,t=200)=>{const[n,r]=H.useState(e);return H.useEffect(()=>{const s=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(s)}},[e,t]),n},AV=p.forwardRef(({searchQuery:e,onFileSelect:t,onClose:n,style:r},s)=>{const o=S4()??"",i=ct(G=>G.activeProjectId),a=ct(p.useCallback(G=>G.projects.find(K=>K.id===i)?.path??null,[i])),l=p.useMemo(()=>{const G=a||o;return G?G.replace(/\\/g,"/").replace(/\/+$/,""):null},[a,o]),d=mC(p.useCallback(G=>l?G.byRoot[l]:void 0,[l])),f=gC(G=>G.searchFiles),u=TV(e,180),h=yC(),[m,g]=p.useState([]),[x,b]=p.useState([]),[S,y]=p.useState(!1),v=p.useRef(0),[C,w]=p.useState(0),I=p.useRef(0),[E,T]=p.useState(360),[A,j]=p.useState({}),[k,_]=p.useState({}),M=p.useRef([]),L=p.useRef([]),O=p.useRef([]),N=p.useRef(null),D=re(G=>G.isMobile),W=U1(N,D),z=(e??"").trim(),X=p.useMemo(()=>{if(!l||!d)return[];const G=[d.selectedPath,...d.openPaths.slice().reverse()].filter(oe=>typeof oe=="string"&&oe.length>0),K=new Set,se=z.toLowerCase();return G.filter(oe=>{if(K.has(oe))return!1;K.add(oe);const ue=oe.startsWith(`${l}/`)?oe.slice(l.length+1):oe;return se?ue.toLowerCase().includes(se):!0}).slice(0,6).map(oe=>{const ue=oe.replace(/\\/g,"/"),ye=ue.split("/").filter(Boolean).pop()||ue,we=ue.startsWith(`${l}/`)?ue.slice(l.length+1):ue;return{name:ye,path:ue,relativePath:we,extension:ye.includes(".")?ye.split(".").pop()?.toLowerCase():void 0}})},[z,l,d]),F=x,U=X,P=m;p.useEffect(()=>{const G=K=>{const se=K.target;!se||!N.current||N.current.contains(se)||n()};return document.addEventListener("pointerdown",G,!0),()=>{document.removeEventListener("pointerdown",G,!0)}},[n]),p.useEffect(()=>{if(!o){g([]);return}const K=(u??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!K){g([]);return}let se=!1;return v.current++,y(!0),f(o,K,80,{includeHidden:!0,respectGitignore:!h,type:"file"}).then(de=>{if(se)return;const oe=new Set(X.map(ue=>ue.path));g(de.filter(ue=>!oe.has(ue.path)).slice(0,15))}).catch(()=>{se||g([])}).finally(()=>{se||(v.current--,v.current<=0&&(v.current=0,y(!1)))}),()=>{se=!0,v.current=Math.max(0,v.current-1),v.current<=0&&y(!1)}},[o,u,X,f,h]),p.useEffect(()=>{if(!o){b([]);return}const K=(u??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!K){b([]);return}let se=!1;return v.current++,y(!0),f(o,K,20,{includeHidden:!0,respectGitignore:!h,type:"directory"}).then(de=>{se||b(de.slice(0,10))}).catch(()=>{se||b([])}).finally(()=>{se||(v.current--,v.current<=0&&(v.current=0,y(!1)))}),()=>{se=!0,v.current=Math.max(0,v.current-1),v.current<=0&&y(!1)}},[o,u,f,h]),p.useEffect(()=>{w(0),j({}),_({})},[P,F,U.length]),p.useEffect(()=>{I.current=C},[C]),p.useEffect(()=>{M.current[C]?.scrollIntoView({block:"nearest"})},[C]),p.useEffect(()=>{let G=null;const K=()=>{G!==null&&cancelAnimationFrame(G),G=requestAnimationFrame(()=>{const se={},de={};L.current.forEach((oe,ue)=>{if(!oe)return;const we=O.current[ue]?.offsetWidth??oe.scrollWidth,Me=Math.max(0,we-oe.clientWidth),He=Me>8;if(se[ue]=He,He){const Ae=Math.max(.6,Me/110);de[ue]=Ae}}),j(se),_(de)})};return K(),window.addEventListener("resize",K),()=>{G!==null&&cancelAnimationFrame(G),window.removeEventListener("resize",K)}},[P,F]),p.useEffect(()=>{const G=L.current[C];if(!G)return;const K=()=>{const de=G.clientWidth;de>0&&T(de)};if(K(),typeof ResizeObserver>"u")return;const se=new ResizeObserver(K);return se.observe(G),()=>{se.disconnect()}},[C]);const q=p.useCallback(G=>{t(G)},[t]);p.useImperativeHandle(s,()=>({handleKeyDown:G=>{if(G==="Escape"){n();return}const K=F.length+U.length+P.length;if(K!==0){if(G==="ArrowDown"){w(se=>(se+1)%K);return}if(G==="ArrowUp"){w(se=>(se-1+K)%K);return}if(G==="Enter"||G==="Tab"){const de=(I.current%K+K)%K;if(de<F.length){const ye=F[de];ye&&q(ye);return}const oe=de-F.length,ue=oe<U.length?U[oe]:P[oe-U.length];ue&&q(ue)}}}}),[P,F,U,n,q]);const B=G=>{switch(G.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return c.jsx(V,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-info)]"});case"json":return c.jsx(V,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-warning)]"});case"md":case"mdx":return c.jsx(V,{name:"file",className:"h-3.5 w-3.5 text-muted-foreground"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return c.jsx(V,{name:"file-image",className:"h-3.5 w-3.5 text-[var(--status-success)]"});default:return c.jsx(V,{name:"file-pdf",className:"h-3.5 w-3.5 text-muted-foreground"})}},ee=(G,K,se)=>{const de=G.relativePath||G.name,oe=e0(de,{maxLength:60}),ue=C===K,ye=A[K]??!1,we=k[K]??2.6;return c.jsxs("div",{ref:Me=>{M.current[K]=Me},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",ue&&"bg-interactive-selection"),onClick:()=>q(G),onMouseMove:()=>w(K),children:[B(G),c.jsxs("span",{ref:Me=>{L.current[K]=Me},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:ue?{"--file-mention-marquee-width":`${E}px`,"--file-mention-marquee-duration":`${we}s`}:void 0,"aria-label":de,children:[c.jsx("span",{ref:Me=>{O.current[K]=Me},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:de}),ye&&ue?c.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:de}):c.jsx("span",{className:"block truncate",children:oe})]})]},se)};return c.jsxs("div",{ref:N,className:"absolute z-[100] min-w-0 w-full max-w-[640px] max-h-64 bg-background border-2 border-border/60 rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",style:W!==void 0?{...r,maxHeight:W}:r,children:[c.jsx(Xn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-0",children:S?c.jsx("div",{className:"flex items-center justify-center py-4",children:c.jsx(V,{name:"refresh",className:"h-4 w-4 animate-spin text-muted-foreground"})}):c.jsxs("div",{className:"pb-2",children:[F.map((G,K)=>{const se=K,de=G.relativePath||G.name,oe=e0(de,{maxLength:60}),ue=C===se;return c.jsxs("div",{ref:ye=>{M.current[se]=ye},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",ue&&"bg-interactive-selection"),onClick:()=>q(G),onMouseMove:()=>w(se),children:[c.jsx(V,{name:"folder-3-fill",className:"h-3.5 w-3.5 text-primary/60"}),c.jsx("span",{className:"flex-1 min-w-0 truncate","aria-label":de,children:oe})]},`dir-${G.path}`)}),F.length>0&&(U.length>0||P.length>0)&&c.jsx("div",{className:"my-1 border-t border-border/60"}),U.map((G,K)=>ee(G,F.length+K,`recent-${G.path}`)),U.length>0&&P.length>0&&c.jsx("div",{className:"my-1 border-t border-border/60"}),P.map((G,K)=>ee(G,F.length+U.length+K,G.path)),P.length===0&&F.length===0&&U.length===0&&c.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No matches found"})]})}),!D&&c.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});function NV(e){const t=(e.description||e.content).replace(/\s+/g," ").trim();return t.length>140?`${t.slice(0,140).trimEnd()}…`:t}const V4=p.forwardRef(({searchQuery:e,onSnippetSelect:t,onClose:n,style:r},s)=>{const o=p.useRef(null),i=re(E=>E.isMobile),a=U1(o,i),[l,d]=p.useState(0),f=p.useRef(0),[u,h]=p.useState([]),m=p.useRef([]),g=Or(E=>E.snippets),x=Or(E=>E.loadSnippets),b=Jn(),S=Or(E=>E.setSnippetDraft),y=Or(E=>E.setSelectedSnippet),v=re(E=>E.setSettingsDialogOpen),C=re(E=>E.setSettingsPage);p.useEffect(()=>{x(b)},[x,b]),p.useEffect(()=>{const E=e.trim(),A=[...E.length?g.filter(j=>yo(j.name,E)||j.aliases.some(k=>yo(k,E))):g].sort((j,k)=>j.source==="project"&&k.source!=="project"?-1:j.source!=="project"&&k.source==="project"?1:j.name.localeCompare(k.name));h(A),d(A.length?1:0)},[e,g]),p.useEffect(()=>{f.current=l,m.current[l]?.scrollIntoView({block:"nearest"})},[l]),p.useEffect(()=>{const E=T=>{const A=T.target;A&&o.current&&!o.current.contains(A)&&n()};return document.addEventListener("pointerdown",E,!0),()=>document.removeEventListener("pointerdown",E,!0)},[n]);const w=p.useCallback(E=>{const T=e.trim(),A=E.aliases.includes(T)?T:E.name;t(E,A)},[t,e]),I=p.useCallback(()=>{const E=new Set(g.map(j=>j.name));let T="new-snippet",A=1;for(;E.has(T);)T=`new-snippet-${A++}`;S({name:T,scope:"global"}),y(null),C("snippets"),v(!0),n()},[n,y,v,C,S,g]);return p.useImperativeHandle(s,()=>({handleKeyDown:E=>{if(E==="Escape"){n();return}const T=u.length+1;if(E==="ArrowDown"){d(A=>(A+1)%T);return}if(E==="ArrowUp"){d(A=>(A-1+T)%T);return}if(E==="Enter"||E==="Tab"){if(f.current===0){I();return}const A=u[f.current-1];A&&w(A)}}}),[w,u,n,I]),c.jsxs("div",{ref:o,role:"listbox","aria-label":"Snippets","aria-activedescendant":l===0?"snippet-option-new":`snippet-option-${l}`,className:"absolute bottom-full left-0 z-[100] flex max-h-80 min-w-0 w-full max-w-[520px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-lg",style:a!==void 0?{...r,maxHeight:a}:r,children:[c.jsxs(Xn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:[c.jsx("div",{id:"snippet-option-new",ref:E=>{m.current[0]=E},role:"option","aria-selected":l===0,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",l===0?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:E=>E.preventDefault(),onClick:I,onMouseMove:()=>d(0),children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"typography-ui-label font-medium",children:"Create a new snippet"}),c.jsx("div",{className:R("mt-1 text-xs leading-5",l===0?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:"Save reusable text for the # picker"})]})}),u.length?u.map((E,T)=>{const A=T+1,j=A===l,k=E.source==="project"?"Project":"Global",_=NV(E);return c.jsx("div",{id:`snippet-option-${A}`,ref:M=>{m.current[A]=M},role:"option","aria-selected":j,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",j?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:M=>M.preventDefault(),onClick:()=>w(E),onMouseMove:()=>d(A),children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono typography-ui-label font-medium",children:["#",E.name]}),c.jsx("span",{className:R("ml-auto shrink-0 text-xs leading-4",j?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:k})]}),_?c.jsx("div",{className:R("mt-1 truncate text-xs leading-5",j?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:_}):null]})},`${E.source}:${E.id}`)}):c.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No snippets found"})]}),!i&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs leading-4 text-muted-foreground",children:"↑↓ Navigate · Enter Select · Esc Close"})]})});V4.displayName="SnippetAutocomplete";const LV={mention:520,command:520,snippet:520};function RV(e,t){if(t)return{left:`${t.left}px`,top:`${t.top}px`,bottom:"auto",width:`min(${LV[e]}px, calc(100% - ${t.left+8}px))`,maxHeight:`${t.maxHeight}px`,transform:t.place==="above"?"translateY(-100%)":void 0}}function PV(e){const{open:t,query:n,overlayPosition:r,onClose:s}=e;if(!t)return null;const o=RV(t,r);switch(t){case"command":return c.jsx(B4,{ref:e.commandRef,searchQuery:n,onCommandSelect:e.onCommandSelect,onClose:s,style:o,onComboboxStateChange:e.onCommandComboboxStateChange});case"snippet":return c.jsx(V4,{ref:e.snippetRef,searchQuery:n,onSnippetSelect:e.onSnippetSelect,onClose:s,style:o});case"mention":return c.jsx(AV,{ref:e.mentionRef,searchQuery:n,onFileSelect:e.onFileSelect,onClose:s,style:o})}}const Rv=Object.freeze({0:"var(--primary)",1:"var(--border)",2:"var(--primary)",3:"var(--border)",4:"var(--status-success)",5:"var(--status-error)",6:"var(--status-warning)",7:"var(--muted-foreground)",8:"var(--muted-foreground)",9:"var(--foreground)",10:"var(--muted-foreground)",11:"transparent",12:"var(--oc-scrollbar-thumb, var(--muted-foreground))",13:"var(--foreground)",14:"var(--foreground)",15:"var(--foreground)",16:"var(--muted-foreground)",17:"var(--tools-title)",18:"var(--tools-description)",19:"var(--markdown-heading1, var(--primary))",20:"var(--markdown-link, var(--primary))",21:"var(--muted-foreground)",22:"var(--markdown-inline-code, var(--syntax-string, var(--status-success)))",23:"var(--syntax-foreground, var(--foreground))",24:"var(--tools-border, var(--border))",25:"var(--markdown-blockquote, var(--muted-foreground))",26:"var(--markdown-blockquote-border, var(--border))",27:"var(--markdown-hr, var(--border))",28:"var(--markdown-list-marker, var(--primary))",29:"var(--tools-edit-added, var(--status-success))",30:"var(--tools-edit-removed, var(--status-error))",31:"var(--muted-foreground)",32:"var(--syntax-comment, var(--muted-foreground))",33:"var(--syntax-keyword, var(--primary))",34:"var(--syntax-function, var(--primary))",35:"var(--syntax-variable, var(--foreground))",36:"var(--syntax-string, var(--status-success))",37:"var(--syntax-number, var(--status-warning))",38:"var(--syntax-type, var(--status-info))",39:"var(--syntax-operator, var(--foreground))",40:"var(--syntax-punctuation, var(--muted-foreground))",41:"var(--muted-foreground)",42:"var(--muted-foreground)",43:"var(--muted-foreground)",44:"var(--muted-foreground)",45:"var(--muted-foreground)",46:"var(--muted-foreground)",47:"var(--muted-foreground)",48:"var(--primary)"}),Pv=Object.freeze({0:"var(--interactive-selection)",1:"var(--interactive-selection)",2:"var(--surface-elevated, var(--card))",3:"var(--surface-muted)",4:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",5:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",6:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))"}),Zp=Object.freeze({30:"var(--muted-foreground)",31:"var(--status-error)",32:"var(--status-success)",33:"var(--status-warning)",34:"var(--status-info)",35:"var(--primary)",36:"var(--status-info)",37:"var(--foreground)",90:"var(--muted-foreground)",91:"var(--status-error)",92:"var(--status-success)",93:"var(--status-warning)",94:"var(--status-info)",95:"var(--primary)",96:"var(--status-info)",97:"var(--foreground)"}),Dv=Object.freeze({40:"var(--muted)",41:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))",42:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",43:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",44:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",45:"var(--surface-elevated)",46:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",47:"var(--surface-elevated)",100:"var(--muted)",101:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))",102:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",103:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",104:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",105:"var(--surface-elevated)",106:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",107:"var(--surface-elevated)"});function Ov(e){if(e<0||e>255)return"var(--foreground)";if(e<16)return Zp[e<8?e+30:e-8+90]??"var(--foreground)";if(e>=232){const i=8+(e-232)*10;return`rgb(${i}, ${i}, ${i})`}const t=e-16,n=t%6,r=Math.floor(t/6)%6,s=Math.floor(t/36),o=[0,95,135,175,215,255];return`rgb(${o[s]}, ${o[r]}, ${o[n]})`}const DV=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|_[^\u0007\u001b]*(?:\u0007|\u001b\\)|[PX^_][^\u001b]*\u001b\\|[@-Z\\-_])/g;function $4(e){if(e)try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t.href:void 0}catch{return}}function Nn(e){return e.replace(DV,"")}function z4(e){return e.includes("\x1B")}function U4(e){if(!e)return[];if(!z4(e))return[{text:e}];const t=[],n={bold:!1,dim:!1,italic:!1,underline:!1,strikethrough:!1,inverse:!1},r=/\u001b(?:\[([0-?]*)[ -/]*([@-~])|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|_[^\u0007\u001b]*(?:\u0007|\u001b\\)|[PX^_][^\u001b]*\u001b\\|[@-Z\\-_])/g;let s=0,o;const i=a=>{if(!a)return;if(t.length>0){const d=t[t.length-1];if((d.fg??void 0)===n.fg&&(d.bg??void 0)===n.bg&&!!d.bold===n.bold&&!!d.dim===n.dim&&!!d.italic===n.italic&&!!d.underline===n.underline&&!!d.strikethrough===n.strikethrough&&!!d.inverse===n.inverse&&d.href===n.href){d.text+=a;return}}const l={text:a};n.fg&&(l.fg=n.fg),n.bg&&(l.bg=n.bg),n.bold&&(l.bold=!0),n.dim&&(l.dim=!0),n.italic&&(l.italic=!0),n.underline&&(l.underline=!0),n.strikethrough&&(l.strikethrough=!0),n.inverse&&(l.inverse=!0),n.href&&(l.href=n.href),t.push(l)};for(;(o=r.exec(e))!==null;){o.index>s&&i(e.slice(s,o.index)),s=r.lastIndex;const a=o[1],l=o[2];if(o[0].startsWith("\x1B]8;")){const d=o[0].slice(4).replace(/(?:\u0007|\u001b\\)$/,""),f=d.slice(d.indexOf(";")+1);n.href=f||void 0;continue}if(l==="m"&&(!a||/^[0-9;]*$/.test(a))){const d=(a||"0").split(";").map(u=>u===""?0:parseInt(u,10));let f=0;for(;f<d.length;){const u=d[f];if(Number.isNaN(u)||u===0)n.fg=void 0,n.bg=void 0,n.bold=!1,n.dim=!1,n.italic=!1,n.underline=!1,n.strikethrough=!1,n.inverse=!1,f+=1;else if(u===1)n.bold=!0,f+=1;else if(u===2)n.dim=!0,f+=1;else if(u===3)n.italic=!0,f+=1;else if(u===4)n.underline=!0,f+=1;else if(u===7)n.inverse=!0,f+=1;else if(u===9)n.strikethrough=!0,f+=1;else if(u===22)n.bold=!1,n.dim=!1,f+=1;else if(u===23)n.italic=!1,f+=1;else if(u===24)n.underline=!1,f+=1;else if(u===27)n.inverse=!1,f+=1;else if(u===29)n.strikethrough=!1,f+=1;else if(u>=30&&u<=37)n.fg=Zp[u],f+=1;else if(u===39)n.fg=void 0,f+=1;else if(u>=40&&u<=47)n.bg=Dv[u],f+=1;else if(u===49)n.bg=void 0,f+=1;else if(u>=90&&u<=97)n.fg=Zp[u],f+=1;else if(u>=100&&u<=107)n.bg=Dv[u],f+=1;else if(u===38){const h=d[f+1];if(h===5){const m=d[f+2];m!==void 0&&(n.fg=Ov(m)),f+=3}else if(h===2){const m=d[f+2],g=d[f+3],x=d[f+4];m!==void 0&&g!==void 0&&x!==void 0&&(m===1&&g===1&&x in Rv?n.fg=Rv[x]:n.fg=`rgb(${m}, ${g}, ${x})`),f+=5}else f+=1}else if(u===48){const h=d[f+1];if(h===5){const m=d[f+2];m!==void 0&&(n.bg=Ov(m)),f+=3}else if(h===2){const m=d[f+2],g=d[f+3],x=d[f+4];m!==void 0&&g!==void 0&&x!==void 0&&(m===1&&g===1&&x in Pv?n.bg=Pv[x]:n.bg=`rgb(${m}, ${g}, ${x})`),f+=5}else f+=1}else f+=1}}}return s<e.length&&i(e.slice(s)),t}const Nd=e=>{const t={};let n=!1,r=e.fg,s=e.bg;if(e.inverse){const o=r;r=s??"var(--surface-background, var(--background))",s=o??"var(--foreground)",n=!0}return r&&(t.color=r,n=!0),s&&(t.backgroundColor=s,n=!0),e.bold&&(t.fontWeight=600,n=!0),e.dim&&(t.opacity=.65,n=!0),e.italic&&(t.fontStyle="italic",n=!0),e.underline&&e.strikethrough?(t.textDecoration="underline line-through",n=!0):e.underline?(t.textDecoration="underline",n=!0):e.strikethrough&&(t.textDecoration="line-through",n=!0),n?t:void 0},q4=e=>e.mode==="overlay"&&!e.hidden&&e.frame?.visible!==!1&&!!e.frame?.layout,OV=/[\u2500-\u259f]/g,Hv=(e,t)=>{for(const n of e.frame?.lines??[]){const r=Nn(n).replace(OV," ").trim().split(/\s+/)[0]??"";if(/[\p{L}\p{N}]/u.test(r))return r.length>16?`${r.slice(0,15)}…`:r}return`Panel ${t+1}`},HV=(e,t)=>{const n=new Map;for(const o of e){if(!o.parentId)continue;const i=n.get(o.parentId)??[];i.push(o),n.set(o.parentId,i)}const r=new Map(t.map((o,i)=>[o,i])),s=[];for(const[o,i]of n){const a=[...i].sort((d,f)=>f.z-d.z),l=i.find(d=>d.focused)??a.find(d=>d.capturing)??a[0];i.sort((d,f)=>(r.get(d.surfaceId)??0)-(r.get(f.surfaceId)??0)),s.push({parentId:o,members:i,front:l})}return s},FV=new Map,BV=(e,t)=>{let n=null;const r=new Set(t.map(s=>s.parentId));for(const s of t){if(s.members.length<2||e.has(s.parentId))continue;const o=s.members[0]?.frame?.layout;n??=new Map(e),n.set(s.parentId,{row:o?.row??0,col:o?.col??0})}for(const s of e.keys())r.has(s)||(n??=new Map(e),n.delete(s));return n??e},VV=(e,t,n)=>{if(!(t>0))return e.top<n?"below":"above";const r=Math.max(0,Math.min(e.top,t-e.layoutHeight));return r>=n?"above":r+e.height+n<=t?"below":"inside"},W4=e=>Be(t=>{const n=e?t.reducer.bySession.get(e)?.extensionSurfaces:void 0;if(!n)return!1;for(const r of n.values())if(r.capturing&&q4(r))return!0;return!1},Object.is,e?`session:${e}`:"*",e??"");function $V(e){return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...e,children:[c.jsx("path",{d:"M208,56V200a8,8,0,0,1-8,8H56a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H200A8,8,0,0,1,208,56Z",opacity:"0.2"}),c.jsx("path",{d:"M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z"})]})}const zV=p.memo(function(t){const{isMobile:n,footerIconButtonClass:r,sendIconSizeClass:s,stopIconSizeClass:o,canSend:i,disabledReason:a,canAbort:l,hasContent:d,currentSessionId:f,newSessionDraftOpen:u,isSending:h=!1,isShellMode:m=!1,onPrimaryAction:g,onQueueMessage:x,onAbort:b}=t,S=i&&!!(f||u)&&!h,y=c.jsx("button",{type:n?"button":"submit",disabled:!i||!f&&!u||h,onClick:v=>{n&&(v.preventDefault(),g())},className:R(r,S?"rounded-full bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:bg-[var(--primary-hover)]":"opacity-30",m&&!h&&"w-auto gap-1 rounded-full px-2.5 typography-ui-label font-medium",h&&"animate-pulse"),"aria-label":h?"Creating session…":a||(m?"Run command":"Send message"),title:h?"Creating session…":a||(m?"Run command":void 0),children:h?c.jsx(V,{name:"loader-4",className:R(s,"animate-spin")}):m?c.jsxs(c.Fragment,{children:[c.jsx(V,{name:"play",className:"size-3.5"}),"Run"]}):c.jsx(V,{name:"send-plane-2",className:R(s,S&&"size-3.5")})});return l?c.jsxs("div",{className:"relative",children:[d?c.jsx("button",{type:"button",disabled:!f||!i,onClick:v=>{n&&v.preventDefault(),x()},className:R(r,"absolute z-20 bottom-full left-1/2 -translate-x-1/2 mb-1",f&&i?"text-primary hover:text-primary":"opacity-30"),"aria-label":a||"Add follow-up",title:a||void 0,children:c.jsx(V,{name:"send-plane-2",className:R(s,"-rotate-90")})}):null,c.jsx("button",{type:"button",onClick:b,className:R(r,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:c.jsx($V,{className:R(o)})})]}):y},(e,t)=>e.isMobile===t.isMobile&&e.footerIconButtonClass===t.footerIconButtonClass&&e.sendIconSizeClass===t.sendIconSizeClass&&e.stopIconSizeClass===t.stopIconSizeClass&&e.canSend===t.canSend&&e.disabledReason===t.disabledReason&&e.canAbort===t.canAbort&&e.hasContent===t.hasContent&&e.currentSessionId===t.currentSessionId&&e.newSessionDraftOpen===t.newSessionDraftOpen&&e.isSending===t.isSending&&e.isShellMode===t.isShellMode&&e.onPrimaryAction===t.onPrimaryAction&&e.onQueueMessage===t.onQueueMessage&&e.onAbort===t.onAbort),UV=p.memo(function(t){const{footerIconButtonClass:n,iconSizeClass:r,handlePickLocalFiles:s,onOpenSettings:o,isAttachmentDisabled:i,disabled:a=!1,onLinkGitHub:l}=t;return c.jsxs("div",{className:"flex items-center gap-x-1.5",children:[c.jsx("div",{className:"relative inline-flex",children:t.onOpenMobileSheet?c.jsx("button",{type:"button",className:n,onClick:t.onOpenMobileSheet,disabled:i,onMouseDown:d=>d.preventDefault(),onPointerDownCapture:d=>{d.pointerType==="touch"&&d.preventDefault()},title:"Add attachment","aria-label":"Add attachment",children:c.jsx(V,{name:"add-circle",className:R(r,"text-current")})}):c.jsxs(Fa,{onOpenChange:t.onMenuOpenChange,children:[c.jsx(Ba,{asChild:!0,children:c.jsx("button",{type:"button",className:n,title:"Add attachment","aria-label":"Add attachment",disabled:i,children:c.jsx(V,{name:"add-circle",className:R(r,"text-current")})})}),c.jsxs(Va,{align:"start",children:[c.jsxs(ur,{onSelect:()=>{requestAnimationFrame(s)},children:[c.jsx(V,{name:"attachment-2"}),"Attach files"]}),l?c.jsxs(ur,{onSelect:()=>{requestAnimationFrame(l)},children:[c.jsx(V,{name:"github"}),"Link issue / pull request"]}):null]})]})}),o?c.jsx("button",{type:"button",onClick:o,className:n,title:"Model and agent settings","aria-label":"Model and agent settings",disabled:a,children:c.jsx(V,{name:"ai-agent",className:R(r,"text-current")})}):null]})},(e,t)=>e.footerIconButtonClass===t.footerIconButtonClass&&e.iconSizeClass===t.iconSizeClass&&e.handlePickLocalFiles===t.handlePickLocalFiles&&e.onOpenSettings===t.onOpenSettings&&e.onMenuOpenChange===t.onMenuOpenChange&&e.onOpenMobileSheet===t.onOpenMobileSheet&&e.isAttachmentDisabled===t.isAttachmentDisabled&&e.disabled===t.disabled&&e.onLinkGitHub===t.onLinkGitHub);function qV(e){const{isMobile:t,isInline:n,alignToolsEnd:r,sessionId:s,newSessionDraftOpen:o,children:i,leadingExtra:a,trailingExtra:l,actionsOverride:d,footerPaddingClass:f,footerGapClass:u,footerIconButtonClass:h,iconSizeClass:m,sendIconSizeClass:g,stopIconSizeClass:x,canSend:b,disabledReason:S,canAbort:y,hasContent:v,isSending:C=!1,isShellMode:w=!1,isAttachmentDisabled:I,onOpenSettings:E,onPickLocalFiles:T,onLinkGitHub:A,onPrimaryAction:j,onQueueMessage:k,onAbort:_}=e,M=c.jsx(UV,{footerIconButtonClass:h,iconSizeClass:m,handlePickLocalFiles:T,onLinkGitHub:A,onOpenSettings:E,onOpenMobileSheet:t?T:void 0,disabled:C,isAttachmentDisabled:I}),L=d??c.jsx(zV,{isMobile:t,footerIconButtonClass:h,sendIconSizeClass:g,stopIconSizeClass:x,canSend:b,disabledReason:S,canAbort:y,hasContent:v,isSending:C,isShellMode:w,currentSessionId:s,newSessionDraftOpen:o,onPrimaryAction:j,onQueueMessage:k,onAbort:_});if(t)return c.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-transparent",children:[c.jsx("div",{className:"min-h-0 min-w-0 flex-1",children:i}),c.jsx("div",{className:R("flex-shrink-0",f,"flex items-center gap-x-1.5"),"data-chat-input-footer":"true",children:c.jsxs("div",{className:"flex w-full items-center justify-between gap-x-1.5",children:[c.jsxs("div",{className:"composer-mobile-actions flex min-w-0 items-center gap-x-2 overflow-x-auto pl-1","data-no-drawer-swipe":"true",children:[M,a?c.jsx("div",{className:R("w-max shrink-0",C&&"pointer-events-none opacity-60"),inert:C||void 0,children:a}):null]}),c.jsxs("div",{className:"flex min-w-0 shrink-0 items-center justify-end gap-x-1",children:[l,L]})]})})]});if(n){const O=r?"self-end":"self-center";return c.jsxs("div",{className:R("grid grid-cols-[auto_minmax(0,1fr)_auto] bg-transparent",f,u),"data-chat-input-footer":"true",children:[c.jsx("div",{className:R("flex min-w-0 items-center",u,O),children:M}),c.jsx("div",{className:"min-w-0",children:i}),c.jsxs("div",{className:R("flex min-w-0 items-center justify-end",u,O),children:[l,L]})]})}return c.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-transparent",children:[c.jsx("div",{className:"min-h-0 min-w-0 flex-1",children:i}),c.jsxs("div",{className:R("flex flex-shrink-0 items-center justify-between",f,u),"data-chat-input-footer":"true",children:[c.jsxs("div",{className:R("flex min-w-0 items-center",u),children:[M,a?c.jsx("div",{className:R("w-max min-w-0 shrink-0",C&&"pointer-events-none opacity-60"),inert:C||void 0,children:a}):null]}),c.jsxs("div",{className:R("flex flex-shrink-0 items-center",u),children:[l,L]})]})]})}const K4=p.memo(({sessionId:e})=>{const t=he(y=>y.restoreToMessage),n=he(y=>y.forkFromMessage),r=he(y=>y.handleSlashRedo),[s,o]=p.useState(null),[i,a]=p.useState(null),[l,d]=p.useState(!0),f=GI(e),u=f?.targetEntryId,h=p.useMemo(()=>f?f.abandoned.filter(y=>y.role==="user"):[],[f]),m="No text content",g=p.useMemo(()=>!f||h.length===0?[]:h.map(y=>({id:y.id,text:y.preview?.replace(/\s+/g," ").trim()||m})),[h,f,m]),x=g[0]?.id;p.useEffect(()=>{d(!0)},[u,x]);const b=p.useCallback(async y=>{if(!(!e||s)){o(y);try{const v=h.findIndex(w=>w.id===y),C=v>=0?h[v+1]:void 0;C?(await t(e,C.id),Ce.success("Restored messages through this point")):await r(e)}catch(v){Ce.error(v instanceof Error?v.message:"Failed to restore messages")}finally{o(null)}}},[h,r,t,s,e]),S=p.useCallback(async y=>{if(!(!e||i)){a(y);try{await n(e,y)}catch(v){Ce.error(v instanceof Error?v.message:"Failed to fork session")}finally{a(null)}}},[n,i,e]);return!e||g.length===0?null:c.jsx("div",{className:"pb-2 w-full px-1",children:c.jsxs("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm overflow-hidden",children:[c.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-[var(--interactive-hover)] transition-colors",onClick:()=>d(y=>!y),"aria-expanded":!l,children:[c.jsxs("span",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:["Reverted"," messages ",g.length]}),c.jsx(V,{name:"arrow-down-s",className:R("ml-auto h-4 w-4 text-muted-foreground transition-transform",!l&&"rotate-180"),"aria-hidden":"true"})]}),!l&&c.jsx("div",{className:"px-3 pb-3 flex flex-col gap-1.5 max-h-[10.5rem] overflow-y-auto",children:g.map(y=>c.jsxs("div",{className:"flex min-w-0 items-center gap-2 py-1",children:[c.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:y.text}),c.jsxs(be,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{S(y.id)},children:[i===y.id?c.jsx(V,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):c.jsx(V,{name:"git-branch",className:"h-3 w-3","aria-hidden":"true"}),"Fork"]}),c.jsxs(be,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{b(y.id)},children:[s===y.id?c.jsx(V,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):c.jsx(V,{name:"arrow-go-forward",className:"h-3 w-3","aria-hidden":"true"}),"Restore"]})]},y.id))})]})})});K4.displayName="RevertedMessageDock";const WV=({isInternalDrag:e,iconButtonBaseClass:t,iconSizeClass:n,radius:r,isAttachmentDisabled:s,onPickLocalFiles:o})=>c.jsx("div",{className:"absolute -inset-px z-50 flex items-center justify-center border border-border/80 bg-[var(--surface-subtle)]/90",style:{borderRadius:r},children:c.jsxs("div",{className:"text-center",children:[c.jsx("div",{className:"inline-flex justify-center",children:c.jsx("button",{type:"button",className:t,onClick:o,disabled:s,title:"Attach files","aria-label":"Attach files",children:c.jsx(V,{name:"attachment-2",className:R(n,"text-current")})})}),c.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:e?"Drop to insert as mention":"Drop files here to attach"})]})}),KV={type:"file",multiple:!0,accept:YM};function GV({inputRef:e,onChange:t}){return c.jsx("input",{ref:e,...KV,className:"hidden",onChange:t})}function ZV({available:e,disabled:t,className:n,iconClassName:r,onStart:s}){return e?c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:n,disabled:t,onClick:s,title:"Start dictation","aria-label":"Start dictation",children:c.jsx(V,{name:"mic",className:R("size-4",r)})}):null}const YV=48,Ld=2,XV=1,Fv=Ld+XV,yh=.08,Ho=512,JV=2,QV=(e,t)=>{e.values[e.cursor]=t,e.cursor=(e.cursor+1)%Ho,e.count=Math.min(Ho,e.count+1)},e$=(e,t)=>{const n=Math.min(e.count,t),r=(e.cursor-n+Ho)%Ho;return Array.from({length:n},(s,o)=>e.values[(r+o)%Ho])},Bv=(e,t,n,r,s)=>{const o=Math.max(1,Math.round(Ld*n.pixelRatio)),i=Math.max(1,n.height-Math.round(8*n.pixelRatio)),a=Math.max(Math.round(2*n.pixelRatio),Math.round(i*r)),l=Math.round((n.height-a)/2);e.globalAlpha=.35+r*.65,e.fillStyle=s,e.beginPath(),e.roundRect(t,l,o,a,o/2),e.fill(),e.globalAlpha=1};function t$({subscribeLevel:e}){const t=p.useRef(null),n=p.useRef(null),r=p.useRef(null),s=p.useRef(0),o=p.useRef(""),i=p.useRef({width:0,height:0,pixelRatio:1}),a=p.useRef({values:Array.from({length:Ho},()=>yh),cursor:0,count:0}),l=p.useCallback(()=>{const d=n.current,f=i.current;if(!d||f.width<=0||f.height<=0||!o.current)return;d.clearRect(0,0,f.width,f.height);const u=Math.max(1,Math.round(Fv*f.pixelRatio)),h=Math.ceil(f.width/u),m=e$(a.current,h),g=h-m.length;for(let x=0;x<h;x+=1){const b=x>=g?m[x-g]:yh,S=f.width-Math.round(Ld*f.pixelRatio)-(h-1-x)*u;Bv(d,S,f,b,o.current)}},[]);return p.useEffect(()=>{const d=t.current;if(!d)return;const f=d.getContext("2d",{alpha:!0});if(!f)return;n.current=f;const u=g=>{const x=Math.min(JV,Math.max(1,window.devicePixelRatio||1)),b={width:Math.max(1,Math.round(g*x)),height:Math.round(YV*x),pixelRatio:x},S=i.current;S.width===b.width&&S.height===b.height&&S.pixelRatio===b.pixelRatio||(i.current=b,d.width=b.width,d.height=b.height,o.current=getComputedStyle(d).color,l())},h=new ResizeObserver(g=>{const x=g[0]?.contentRect.width;typeof x=="number"&&x>0&&u(x)});h.observe(d);const m=new MutationObserver(()=>{o.current=getComputedStyle(d).color,l()});return m.observe(document.documentElement,{attributes:!0,attributeFilter:["class","style"]}),()=>{h.disconnect(),m.disconnect(),n.current=null}},[l]),p.useEffect(()=>{const d=()=>{r.current=null;const u=t.current,h=n.current,m=i.current;if(!u||!h||m.width<=0||!o.current)return;const g=Math.max(yh,s.current),x=Math.max(1,Math.round(Fv*m.pixelRatio));m.width>x&&(h.globalCompositeOperation="copy",h.drawImage(u,x,0,m.width-x,m.height,0,0,m.width-x,m.height),h.globalCompositeOperation="source-over"),h.clearRect(Math.max(0,m.width-x),0,x,m.height),Bv(h,m.width-Math.round(Ld*m.pixelRatio),m,g,o.current),QV(a.current,g)},f=e(u=>{s.current=u,r.current===null&&(r.current=requestAnimationFrame(d))});return()=>{f(),r.current!==null&&cancelAnimationFrame(r.current)}},[e]),c.jsx("canvas",{ref:t,className:"h-12 w-full text-primary","aria-hidden":"true"})}const n$=e=>`${Math.floor(e/60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`;function r$({state:e,elapsedSeconds:t,buttonClassName:n,iconClassName:r,isMobile:s,onCancel:o,onDone:i}){const a=e==="recording"||e==="reconnecting";return c.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s?null:c.jsxs("div",{className:"mr-1 flex items-center gap-2 typography-ui-compact text-muted-foreground",children:[a?c.jsx("span",{className:"size-2 rounded-full bg-[var(--status-error)]","aria-hidden":"true"}):null,c.jsx("span",{className:"tabular-nums",children:n$(t)})]}),c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:n,onClick:o,title:"Cancel dictation","aria-label":"Cancel dictation",children:c.jsx(V,{name:"close",className:R("size-4",r)})}),c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:R(n,"text-primary hover:text-primary"),onClick:i,disabled:!a,title:"Finish dictation","aria-label":"Finish dictation",children:c.jsx(V,{name:"check",className:R("size-4",r)})})]})}function s$({state:e,subscribeLevel:t}){const n=e==="recording"||e==="reconnecting",r=e==="requesting-permission"?"Requesting microphone access...":e==="reconnecting"?"Recording. Reconnecting to the server...":e==="transcribing"?"Transcribing...":"Recording";return c.jsx("div",{className:"flex h-[7rem] w-full items-center px-3 py-3",role:"group","aria-label":"Dictation recorder",children:c.jsxs("div",{className:"min-w-0 flex-1",children:[n?c.jsx(t$,{subscribeLevel:t}):c.jsx("div",{className:"flex h-12 items-center justify-center typography-ui-label text-muted-foreground",children:r}),c.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:r})]})})}const o$=3e4;let Yp=null,Ki=null;const lQ=()=>{Yp=null,Ki=null},i$=async e=>{const t=Y();if(!e?.fresh){const r=Yp;if(r&&r.key===t&&Date.now()<r.expiresAt)return r.status;const s=Ki;if(s&&s.key===t)return s.promise}const n=(async()=>{const r=await Rt("/api/stt/status");if(!r.ok)throw new Error("Could not load dictation settings");const s=await r.json();return!e?.fresh&&Y()===t&&(Yp={key:t,status:s,expiresAt:Date.now()+o$}),s})();e?.fresh||(Ki={key:t,promise:n});try{return await n}finally{Ki?.promise===n&&(Ki=null)}},a$=`
|
|
102
|
+
class PiChamberDictationProcessor extends AudioWorkletProcessor {
|
|
103
|
+
constructor() {
|
|
104
|
+
super();
|
|
105
|
+
this.outputRate = 16000;
|
|
106
|
+
this.step = sampleRate / this.outputRate;
|
|
107
|
+
this.position = 0;
|
|
108
|
+
this.source = [];
|
|
109
|
+
this.pending = [];
|
|
110
|
+
this.chunkSamples = 4000;
|
|
111
|
+
this.port.onmessage = (event) => {
|
|
112
|
+
if (event.data && event.data.type === 'flush') {
|
|
113
|
+
if (this.pending.length > 0) {
|
|
114
|
+
const samples = Int16Array.from(this.pending.splice(0));
|
|
115
|
+
this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
|
|
116
|
+
}
|
|
117
|
+
this.port.postMessage({ type: 'flushed' });
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
process(inputs) {
|
|
122
|
+
const input = inputs[0] && inputs[0][0];
|
|
123
|
+
if (!input || input.length === 0) return true;
|
|
124
|
+
let sum = 0;
|
|
125
|
+
for (let i = 0; i < input.length; i += 1) { this.source.push(input[i]); sum += input[i] * input[i]; }
|
|
126
|
+
this.port.postMessage({ type: 'level', value: Math.min(1, Math.sqrt(sum / input.length) * 3) });
|
|
127
|
+
while (this.position + 1 < this.source.length) {
|
|
128
|
+
const index = Math.floor(this.position);
|
|
129
|
+
const fraction = this.position - index;
|
|
130
|
+
const sample = this.source[index] + (this.source[index + 1] - this.source[index]) * fraction;
|
|
131
|
+
const clamped = Math.max(-1, Math.min(1, sample));
|
|
132
|
+
this.pending.push(clamped < 0 ? Math.round(clamped * 32768) : Math.round(clamped * 32767));
|
|
133
|
+
this.position += this.step;
|
|
134
|
+
}
|
|
135
|
+
const consumed = Math.floor(this.position);
|
|
136
|
+
if (consumed > 0) { this.source.splice(0, consumed); this.position -= consumed; }
|
|
137
|
+
while (this.pending.length >= this.chunkSamples) {
|
|
138
|
+
const samples = Int16Array.from(this.pending.splice(0, this.chunkSamples));
|
|
139
|
+
this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
|
|
140
|
+
}
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
registerProcessor('pichamber-dictation', PiChamberDictationProcessor);
|
|
145
|
+
`,c$=16e3,Vv=4e3,G4=()=>typeof window>"u"?null:window.AudioContext??window.webkitAudioContext??null,vh=e=>{try{e?.disconnect()}catch{}};class l${constructor(t){this.options=t}options;stream=null;context=null;source=null;processor=null;gain=null;listeners=new Set;pendingFallback=[];fallbackPosition=0;fallbackCarry=[];flushed=null;cancelled=!1;subscribeLevel(t){return this.listeners.add(t),()=>this.listeners.delete(t)}level(t){for(const n of this.listeners)n(t)}chunk(t){t.length&&this.options.onChunk(new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice())}async start(){if(this.stream)return;const t=G4();if(!t||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone recording is not supported");const n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});if(this.cancelled)throw n.getTracks().forEach(o=>o.stop()),new Error("Dictation cancelled");this.stream=n,this.options.onPermissionGranted?.();const r=new t;this.context=r,r.state==="suspended"&&await r.resume(),this.source=r.createMediaStreamSource(n),this.gain=r.createGain(),this.gain.gain.value=0;let s=null;if(r.audioWorklet&&typeof AudioWorkletNode<"u"){const o=URL.createObjectURL(new Blob([a$],{type:"text/javascript"}));try{await r.audioWorklet.addModule(o),s=new AudioWorkletNode(r,"pichamber-dictation",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1]})}catch{s=null}finally{URL.revokeObjectURL(o)}}if(s)s.port.onmessage=o=>{o.data.type==="level"?this.level(o.data.value??0):o.data.type==="chunk"&&o.data.buffer?this.chunk(new Int16Array(o.data.buffer)):o.data.type==="flushed"&&(this.flushed?.(),this.flushed=null)},this.processor=s;else{const o=r.createScriptProcessor(4096,1,1);o.onaudioprocess=i=>this.processFallback(i.inputBuffer.getChannelData(0),r.sampleRate),this.processor=o}this.source.connect(this.processor),this.processor.connect(this.gain),this.gain.connect(r.destination)}processFallback(t,n){let r=0;for(const a of t)r+=a*a;this.level(Math.min(1,Math.sqrt(r/Math.max(1,t.length))*3));const s=this.fallbackCarry.concat(Array.from(t)),o=n/c$;for(;this.fallbackPosition+1<s.length;){const a=Math.floor(this.fallbackPosition),l=this.fallbackPosition-a,d=s[a]+(s[a+1]-s[a])*l,f=Math.max(-1,Math.min(1,d));this.pendingFallback.push(f<0?Math.round(f*32768):Math.round(f*32767)),this.fallbackPosition+=o}const i=Math.floor(this.fallbackPosition);for(this.fallbackCarry=s.slice(i),this.fallbackPosition-=i;this.pendingFallback.length>=Vv;)this.chunk(Int16Array.from(this.pendingFallback.splice(0,Vv)))}async stop(){this.cancelled=!0;const t=this.processor;typeof AudioWorkletNode<"u"&&t instanceof AudioWorkletNode?await Promise.race([new Promise(n=>{this.flushed=n,t.port.postMessage({type:"flush"})}),new Promise(n=>window.setTimeout(n,100))]):this.pendingFallback.length&&this.chunk(Int16Array.from(this.pendingFallback.splice(0))),typeof ScriptProcessorNode<"u"&&t instanceof ScriptProcessorNode&&(t.onaudioprocess=null),vh(this.source),vh(t),vh(this.gain),this.stream?.getTracks().forEach(n=>n.stop()),await this.context?.close().catch(()=>{}),this.level(0),this.stream=null,this.context=null,this.source=null,this.processor=null,this.gain=null,this.pendingFallback=[],this.fallbackCarry=[],this.fallbackPosition=0,this.flushed=null}}const d$=()=>!!(G4()&&navigator.mediaDevices?.getUserMedia),xh=1,u$=300*16e3*2,$v=(e,t)=>{const n=new Uint8Array(4+t.byteLength);return new DataView(n.buffer).setUint32(0,e,!0),n.set(t,4),n},f$=()=>typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${crypto.getRandomValues(new Uint32Array(4)).join("-")}`;class h${constructor(t,n,r){this.providerConfigId=t,this.onState=n,this.onError=r}providerConfigId;onState;onError;recordingId=f$();socket=null;socketStarted=!1;chunks=[];audioBytes=0;finishing=!1;cancelled=!1;failures=0;generation=0;reconnectTimer=null;finishPromise=null;resolveFinish=null;rejectFinish=null;begin(){this.connect()}append(t){if(this.cancelled||this.finishing||!t.byteLength)return;if(this.audioBytes+t.byteLength>u$){this.fail(new Error("Recording reached the five minute limit"));return}const n=t.slice(),r=this.chunks.length;this.chunks.push(n),this.audioBytes+=n.byteLength,this.socketStarted&&this.socket?.readyState===xh&&this.socket.send($v(r,n))}finish(){return this.finishPromise?this.finishPromise:(this.finishing=!0,this.onState("transcribing"),this.finishPromise=new Promise((t,n)=>{this.resolveFinish=t,this.rejectFinish=n}),this.socketStarted?this.sendFinish():this.connect(),this.finishPromise)}cancel(){this.cancelled||(this.cancelled=!0,this.generation+=1,this.socket?.readyState===xh&&this.socketStarted&&this.socket.send(JSON.stringify({version:1,type:"cancel",recordingId:this.recordingId})),this.closeSocket(),this.clearAudio(),this.rejectFinish?.(new Error("Dictation cancelled")),this.rejectFinish=null,this.resolveFinish=null)}async connect(){if(this.cancelled||this.socket||this.reconnectTimer)return;const t=++this.generation;this.failures>0&&this.onState(this.finishing?"transcribing":"reconnecting");try{const n=await vC();if(this.cancelled||t!==this.generation)return;const r=xC(bC().websocket("/api/stt/ws",void 0,n));r.binaryType="arraybuffer",this.socket=r;let s=!1;r.onopen=()=>{s=!0,!(this.socket!==r||this.cancelled)&&r.send(JSON.stringify({version:1,type:"start",recordingId:this.recordingId,providerConfigId:this.providerConfigId}))},r.onmessage=o=>{if(typeof o.data!="string"||this.socket!==r)return;let i;try{i=JSON.parse(o.data)}catch{return}if(!(i.recordingId&&i.recordingId!==this.recordingId))if(i.type==="started"){this.failures=0,this.socketStarted=!0;const a=Number.isInteger(i.ackSequence)?i.ackSequence:-1;for(let l=a+1;l<this.chunks.length;l+=1)r.send($v(l,this.chunks[l]));this.finishing?this.sendFinish():this.onState("recording")}else if(i.type==="transcribing")this.onState("transcribing");else if(i.type==="final"){const a=String(i.text??"").trim();this.resolveFinish?.(a),this.resolveFinish=null,this.rejectFinish=null,this.clearAudio(),this.cancelled=!0,this.closeSocket()}else i.type==="error"&&this.fail(Object.assign(new Error(i.message||"Transcription failed"),{code:i.code}))},r.onerror=()=>{},r.onclose=()=>{this.socket===r&&(this.socket=null,this.socketStarted=!1,s||wC(n),this.cancelled||this.scheduleReconnect())}}catch(n){!this.cancelled&&t===this.generation&&(this.socket=null,this.scheduleReconnect(n instanceof Error?n:new Error(String(n))))}}sendFinish(){!this.socketStarted||this.socket?.readyState!==xh||this.socket.send(JSON.stringify({version:1,type:"finish",recordingId:this.recordingId,finalSequence:this.chunks.length-1}))}scheduleReconnect(t){this.failures+=1,this.onState(this.finishing?"transcribing":"reconnecting");const r=typeof document<"u"&&(document.visibilityState==="hidden"||navigator.onLine===!1)?3e4:Math.min(1e4,300*2**Math.min(this.failures,5));if(this.failures>=8){this.fail(t??new Error("Could not reconnect to the transcription server"));return}this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},r)}fail(t){this.cancelled||(this.cancelled=!0,this.onError(t),this.rejectFinish?.(t),this.resolveFinish=null,this.rejectFinish=null,this.closeSocket(),this.clearAudio())}closeSocket(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null;const t=this.socket;if(this.socket=null,this.socketStarted=!1,t){t.onclose=null,t.onmessage=null;try{t.close()}catch{}}}clearAudio(){this.chunks=[],this.audioBytes=0}}function p$(){const[e,t]=p.useState("idle"),[n,r]=p.useState(null),[s,o]=p.useState(!1),[i,a]=p.useState(0),l=p.useRef(null),d=p.useRef(null),f=p.useRef("local"),u=p.useRef(0),h=p.useRef(0),m=p.useCallback(async()=>{const v=await i$();f.current=v.config?.providerConfigId||"local",o(v.config?.enabled===!0&&d$())},[]);p.useEffect(()=>(m().catch(()=>{}),en(()=>{h.current+=1,d.current?.cancel(),l.current?.stop(),d.current=null,l.current=null,t("idle"),r(null),o(!1),m().catch(()=>{})})),[m]),p.useEffect(()=>{if(!u.current||e!=="recording"&&e!=="reconnecting")return;const v=()=>a(Math.min(300,Math.floor((Date.now()-u.current)/1e3)));v();const C=window.setInterval(v,250);return()=>window.clearInterval(C)},[e]);const g=p.useCallback(v=>{r(v.message),t("error"),l.current?.stop(),l.current=null},[]),x=p.useCallback(async()=>{if(!s||e==="requesting-permission"||e==="recording"||e==="reconnecting"||e==="transcribing")return;r(null),a(0),t("requesting-permission");const v=++h.current,C=new h$(f.current,I=>{h.current===v&&t(I)},I=>{h.current===v&&g(I)}),w=new l$({onChunk:I=>C.append(I),onPermissionGranted:()=>{h.current===v&&(u.current=Date.now(),t("recording"))}});d.current=C,l.current=w;try{await w.start(),C.begin()}catch(I){if(C.cancel(),await w.stop().catch(()=>{}),h.current!==v)return;d.current=null,l.current=null,u.current=0;const E=I instanceof Error?I:new Error(String(I));throw r(E.name==="NotAllowedError"?"Microphone access was denied":E.message),t("error"),E}},[s,e,g]),b=p.useCallback(async()=>{const v=d.current,C=l.current;if(!v||!C)throw new Error("No dictation recording is active");const w=h.current;t("transcribing");try{if(await C.stop(),h.current!==w||d.current!==v)throw new Error("Dictation cancelled");l.current=null;const I=await v.finish();if(h.current!==w)throw new Error("Dictation cancelled");return d.current=null,u.current=0,t("idle"),r(null),I}catch(I){const E=I instanceof Error?I:new Error(String(I));throw h.current===w&&(r(E.message),t("error")),E}},[]),S=p.useCallback(()=>{h.current+=1,d.current?.cancel(),d.current=null,l.current?.stop(),l.current=null,u.current=0,a(0),r(null),t("idle")},[]);p.useEffect(()=>S,[S]);const y=p.useCallback(v=>l.current?.subscribeLevel(v)??(()=>{}),[]);return{state:e,error:n,available:s,elapsedSeconds:i,start:x,finish:b,cancel:S,subscribeLevel:y}}const m$=Hs(()=>mt(()=>import("./GitHubLinkPicker-ELF_chia.js"),__vite__mapDeps([58,5,1,6,59,17,11,8,18,19,20,60,23,61,43,42])).then(e=>({default:e.GitHubLinkPicker}))),g$=Hs(()=>mt(()=>import("./ToolOutputDialog-aR4kcgKL.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),y$=5,v$=16,x$=4,b$=560,zv=p.memo(GD),w$=p.memo(J3),S$=e=>{const t=he.getState(),n=t.newSessionDraft?.open?t.newSessionDraft.directoryOverride:null,r=e?t.getDirectoryForSession(e)??t.currentSessionDirectory:n??nt.getState().currentDirectory;return Qo(Y(),r,e)},Z4=({onOpenSettings:e,scrollToBottom:t})=>{const n=p.useRef(null),r=p.useRef(null),s=p.useRef({text:"",confirmedMentions:new Set}),[o,i]=p.useState(()=>{const $=he.getState().currentSessionId,ae=S$($),Te=ru(ae);return r.current=ae,s.current=Te,Te.text&&(n.current=Te.text),Te.text}),a=p.useRef(s.current.confirmedMentions),[l,d]=p.useState("normal"),[f,u]=p.useState(!1);p.useEffect(()=>{l==="normal"&&u(!1)},[l]);const[h,m]=p.useState(null),[g,x]=p.useState(""),[b,S]=p.useState(null),y=p.useCallback(()=>m(null),[]);p.useEffect(()=>{h!=="command"&&S($=>$===null?$:null)},[h]);const v=h==="command"?b?.listboxId:void 0,C=!!v,[w,I]=p.useState(null),[E,T]=p.useState(null),[A,j]=p.useState(""),k=p.useRef(null),_=p.useRef(rB()).current;p.useEffect(()=>()=>{_.view?.destroy(),_.view=null},[_]);const M=p.useRef(null),L=p.useRef(0),O=p.useRef(null),N=p.useRef(!1),D=p.useRef(null),W=p.useRef(!1),z=p.useRef(null),X=p.useRef(null),F=p.useRef(null),U=p.useRef(o),P=p.useRef(r.current),q=p.useRef((...$)=>Promise.resolve(he.getState().sendMessage(...$))).current,B=he($=>$.currentSessionId),ee=W4(B);p.useEffect(()=>{ee&&y()},[ee,y]);const K=Be($=>B?$.sessionLoadErrorById.get(B)?.code??null:null,void 0,B?`session:${B}`:"chrome")==="SESSION_IN_USE",se=Be($=>{if(!B)return;const ae=$.reducer.bySession.get(B);if(!ae)return;const Te=ae.extensionEditorOps??(ae.extensionEditor?[ae.extensionEditor]:void 0);if(!(!Te||Te.length===0))return{sessionId:B,ops:Te}},($,ae)=>$===ae?!0:!$||!ae||$.sessionId!==ae.sessionId||$.ops.length!==ae.ops.length?!1:$.ops.every((Te,$e)=>Te.sequence===ae.ops[$e]?.sequence&&Te.text===ae.ops[$e]?.text&&Te.mode===ae.ops[$e]?.mode),B?`session:${B}`:"chrome"),de=p.useRef(new Map);p.useEffect(()=>{if(!B||!se||se.sessionId!==B)return;const{ops:$}=se;if(!$||$.length===0)return;const ae=de.current.get(B)??-1,Te=$.filter(Le=>Le.sequence>ae);if(Te.length===0)return;let $e=ae;for(const Le of Te)Le.sequence>$e&&($e=Le.sequence);let ze=-1;for(let Le=Te.length-1;Le>=0;Le--)if(Te[Le]?.mode!=="paste"){ze=Le;break}if(ze!==-1){const Le=Te[ze],Je=Te.slice(ze+1).map(hn=>hn.text).join(""),gt=Le.text+Je;a.current.clear(),i(gt),y()}else for(const Le of Te){const Je=k.current;Je?(Je.insertText(Le.text),Je.focus({preventScroll:!0})):i(gt=>gt+Le.text)}de.current.set(B,$e),qe().consumeExtensionEditor(B,$e)},[y,B,se]);const oe=nt($=>$.currentDirectory),ue=Jn()??oe,ye=he(p.useCallback($=>B?$.getDirectoryForSession(B):null,[B])),we=Y();NP({sessionId:B,directory:ye??ue,text:o}),p.useEffect(()=>(id(),Hr.getState().loadSkills(),en(()=>{id(),Hr.getState().loadSkills()})),[ue]);const Me=p.useMemo(()=>Qo(we,ye??ue,B),[we,ue,ye,B]),He=he($=>$.newSessionDraft),Ae=!!He?.open,Ge=he($=>$.sendingNewSessionDraftId),et=Lw(He,B,Ge);he($=>$.openNewSessionDraft);const Xe=he($=>$.abortPromptSessionId),te=he($=>$.clearAbortPrompt),Q=Ye($=>$.attachedFiles),me=Ye($=>$.addAttachedFile),Se=Ye($=>$.detachAttachedFiles),_e=Ye($=>$.consumePendingInputText),Fe=Ye($=>$.pendingStarterInsert),ht=Ye($=>$.pendingInputText),ge=Ye($=>$.pendingRevertText),Ze=Ye($=>$.consumePendingRevertText),Ve=Ye($=>$.consumePendingSyntheticParts),ie=he($=>$.acknowledgeSessionAbort),ke=p.useCallback($=>Qm($??B??""),[B]),ve=We($=>$.currentProviderId),xe=We($=>$.currentModelId),je=We($=>$.getModelMetadata);We($=>$.modelsMetadata),We($=>$.providers);const le=ve&&xe?je(ve,xe):void 0,J=We($=>$.currentVariant),ne=re($=>$.isMobile),fe=p$(),De=p.useRef({start:0,end:0}),Ue=p.useRef(null),st=fe.state==="requesting-permission"||fe.state==="recording"||fe.state==="reconnecting"||fe.state==="transcribing",Ke=Iu()==="mini-chat",_t=WE(),{enabled:fn}=mu(),Sn=ne&&!fn,Bs=re($=>$.setImagePreviewOpen),Vs=re($=>$.inputBarOffset),Hn=re($=>$.isExpandedInput),Ja=re($=>$.setExpandedInput),Ot=re($=>$.setTimelineDialogOpen),{git:tn}=qa(),{currentTheme:Yr}=vr(),ni=S4(),ri=ku(ue),xr=vt($=>ue?$.directories.get(ue)?.status??null:null),Qa=vt($=>$.ensureStatus),ec=vt($=>$.fetchStatus),tc=vt($=>$.clearDiffCache),[Fn,Xr]=p.useState(!1),Bn=p.useRef(async()=>{}),Pt=BB({activeRuntimeKey:we,intent:He?.branchIntent,onReady:$=>{Bn.current($)}}),br=VB({taskId:He?.id,intent:He?.worktreeIntent}),[Vt,Jr]=p.useState(!1),[si,Qr]=p.useState({open:!1,title:"",content:""}),[nc,Lu]=p.useState(!1);p.useEffect(()=>{si.open&&Lu(!0)},[si.open]);const $s=p.useRef({modelKey:`${ve??""}/${xe??""}`,modalitySignature:le?.modalities?.input?.slice().sort().join(",")??null,attachmentIds:new Set});p.useEffect(()=>{const $=`${ve??""}/${xe??""}`,ae=le?.modalities?.input,Te=ae?.slice().sort().join(",")??null,$e=$s.current,ze=$e.modelKey!==$,Le=$e.modalitySignature===null&&Te!==null,Je=ze||Le?Q:Q.filter(ut=>!$e.attachmentIds.has(ut.id));if($s.current={modelKey:$,modalitySignature:Te,attachmentIds:new Set(Q.map(ut=>ut.id))},!ae||Je.length===0)return;const gt=JM(Je,ae);if(gt.length===0)return;const hn=Array.from(new Set(gt.map(({modality:ut})=>ut))),pn={text:"Text",image:"Image",pdf:"PDF",audio:"Audio",video:"Video"},Ks=gt.map(({attachment:ut})=>ut.filename),qu=Ks.length>3?`${Ks.slice(0,3).join(", ")} (+${Ks.length-3})`:Ks.join(", ");Ce.warning(`${le.name??xe??""} does not support ${hn.map(ut=>pn[ut]).join(", ")} input required by ${qu}. You can still send the message, but these attachments may be ignored.`,{id:`attachment-modalities:${$}`})},[Q,xe,le,ve]);const Ru=p.useCallback($=>{$.image&&(Qr($),Bs(!0))},[Bs]),Pu=p.useCallback($=>{Qr(ae=>({...ae,open:$})),Bs($)},[Bs]);p.useEffect(()=>{!ue||!tn||Qa(ue,tn)},[ue,tn,Qa]),p.useEffect(()=>{if(!(!ue||!tn))return Cu.onGitRefreshHint($=>{Yt($.directory)===Yt(ue)&&($.paths?.length&&tc(ue,$.paths),ec(ue,tn,{silent:!0}))})},[tc,ue,tn,ec]);const Qn=!1,es=Hn&&ne,nn=es,[gg,oi]=p.useState(1),Vn=!ne&&!Ke,rc=!!(Ae&&Vn&&!nn),wr=!ne&&!nn&&!Vn,zs=ne||Vn?"1.5rem":"9999px",sc=ne||Vt;p.useEffect(()=>{const $=O.current;if(!$)return;const ae=$e=>{const ze=$e>0&&$e<b$;Jr(Le=>Le===ze?Le:ze)};if(ae($.clientWidth),typeof ResizeObserver>"u"){const $e=()=>ae($.clientWidth);return window.addEventListener("resize",$e),()=>window.removeEventListener("resize",$e)}const Te=new ResizeObserver($e=>{ae($e[0]?.contentRect.width??$.clientWidth)});return Te.observe($),()=>Te.disconnect()},[]);const oc=p.useMemo(()=>new Set,[]),{commands:ic}=C4(ue),ac=p.useMemo(()=>{const $=new Set;for(const ae of ic)$.add(ae.invocationName.toLowerCase());return $},[ic]),cc=Or($=>$.snippets),lc=Or($=>$.loadSnippets);p.useEffect(()=>{lc(ue)},[ue,lc]);const dc=p.useMemo(()=>{const $=new Set;for(const ae of cc){$.add(ae.name.toLowerCase());for(const Te of ae.aliases??[])$.add(Te.toLowerCase())}return $},[cc]),uc=p.useMemo(()=>Q.map($=>$.filename),[Q]),Z=p.useMemo(()=>({inputMode:l,knownAgentNames:oc,confirmedMentions:a.current,knownSlashNames:ac,knownSnippetTriggers:dc,attachmentFilenames:uc}),[uc,l,oc,ac,dc]),pe=p.useCallback($=>[...$??[]].map(ae=>({...ae,dataUrl:ae.source==="server"&&ae.serverPath?gL(ae.serverPath):ae.dataUrl})),[]),Re=p.useCallback($=>({sanitizedText:$,attachments:[]}),[]),Ne=p.useRef(null),lt=p.useRef(!1),ot=B?gm(B,ye??ue):null,dt=ft($=>$.followUpBehavior),Oe=ft($=>$.addToQueue),Qe=MB(c_(B??""));p.useEffect(()=>{U.current=o},[o]),p.useEffect(()=>{P.current=Me},[Me]);const{persistNow:kt}=EB({message:o,messageRef:U,setMessage:i,confirmedMentionsRef:a,identity:Me,persistEnabled:!0,initialDraft:{text:n.current??"",identity:r.current},onIdentityChange:()=>d("normal"),onDraftRestored:()=>k.current?.selectAll()});p.useEffect(()=>{const $=Me?Jt(Me):"";Ye.getState().activateAttachmentsDraft($)},[Me]);const jt=Ye($=>$.sentDraftClear);p.useEffect(()=>{if(!jt)return;const $=Me?Jt(Me):"";if(!$||jt.draftKey!==$)return;Ye.getState().consumeSentDraftClear(jt.nonce);const ae=k.current?.getValue()??U.current;II(jt,$,ae)&&(a.current.clear(),Qe.reset(),i(""))},[jt,Me,Qe]);const Cn=p.useRef(Ae);p.useEffect(()=>{!Cn.current&&Ae&&requestAnimationFrame(()=>{ne?k.current?.focus({preventScroll:!0}):k.current?.focus()}),Cn.current=Ae},[Ae,ne]);const{phase:rn}=f1();p.useEffect(()=>{if(ht!==null){const $=_e();$?.text&&($.mode==="append"?i(ae=>{const Te=$.text;return Te.trim()?sB(ae,Te):ae}):$.mode==="append-inline"?i(ae=>L4(ae,$.text)):i($.text),setTimeout(()=>{k.current?.focus()},0))}},[ht,_e]),p.useEffect(()=>{if(ge!==null){const $=Ze();$&&o.trim().length===0&&(i($),setTimeout(()=>{k.current?.focus()},0))}},[ge,Ze,o]);const Us=Ye($=>$.pendingWorktreeRestore),qs=Ye($=>$.consumePendingWorktreeRestore);p.useEffect(()=>{if(Us===null)return;const $=qs();if(!$)return;const ae=cN($,U.current??"");if(ae.ok)a.current=new Set($.confirmedMentions),U.current=$.prompt,i($.prompt),y(),setTimeout(()=>{k.current?.focus()},0);else{const Te=aN(ae,"pending-composer");Te&&Ce.error(Te.title,{description:Te.description})}},[Us,qs,y]);const er=o.trim().length>0||Q.length>0,ii=!!(ve&&xe),Sr=nh(Q),Cr=l4(),F9=(Cr?"Connection lost. Waiting to reconnect — your draft is kept.":null)??(ky(Q)?"Uploading attachments…":XR(Q)||Q.length>0&&!Sr?"Retry or remove failed attachments":null),yg=l==="shell"&&!!B&&!Ae,B9=er&&(ii||yg)&&Sr&&!Cr,$n=!!(br.state&&br.state.phase!=="failed")||et||K,Ws=!B&&!Ae||$n,fc=uu(B??""),V9=rn!=="idle"&&!fc,ai=p.useCallback(()=>{const $=k.current?.getValue()??o;return{message:$,hasContent:$.trim().length>0||Q.length>0}},[Q.length,o]),ci=p.useRef(!1),hc=p.useCallback(async()=>{if(jd()){Ce.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const $=ai();if(ci.current||!$.hasContent||!B||!ot||!nh(Q))return;ci.current=!0;let ae;try{ae=await ow(pe(Q))}catch{Ce.error("Attachment data could not be saved for the follow-up."),ci.current=!1;return}const Te=$.message.replace(/^\n+|\n+$/g,""),$e=B?Lt.getState().getSessionAgentSelection(B)??void 0:void 0;if(!Oe(ot,{content:Te,attachments:ae.length>0?ae:void 0,sendConfig:ve&&xe?{providerID:ve,modelID:xe,agent:$e,variant:J??void 0}:void 0})){ci.current=!1,Ce.error("Follow-up limit reached. Remove a pending message before adding another.");return}(k.current?.getValue()??U.current)===$.message&&i(""),ae.length>0&&Se(ae.map(Le=>Le.id)),ci.current=!1,ne||k.current?.focus()},[ai,B,ot,Q,pe,Oe,Se,ne,ve,xe,J]),$9=p.useCallback($=>{i($),setTimeout(()=>{k.current?.focus()},0)},[]),z9=p.useCallback($=>{Bn.current({queuedOnly:!0,queuedMessageId:$,delivery:"steer"})},[]),U9=($,ae)=>{const Te=$ instanceof Error?$.message:"";return Te.toLowerCase().includes("runtime changed")?"Message failed to send. Attachments restored.":Te||ae},vg=async $=>{if(jd()){Ce.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const ae=$?.queuedOnly??!1,Te=$?.queuedMessageId,$e=$?.delivery==="steer"?"steer":void 0,ze=ot;let Le=null;if(!(ae&&(!ze||!Te||(Le=ft.getState().claimQueuedMessage(ze,Te),!Le)))){try{if(!ae&&!nh(Q)){ky(Q)?Ce.info("Uploading attachments…"):Ce.error("Retry or remove failed attachments");return}const Je=$?.presetText!=null&&!ae?{message:$.presetText,hasContent:$.presetText.trim().length>0||Q.length>0}:ae?{message:"",hasContent:!1}:ai();if(!ae&&l==="shell"&&Q.length>0){Ce.error("Remove attachments to run a shell command.");return}if(ae){if(!B)return}else if(!Je.hasContent||!B&&!Ae)return;const gt=ae?Le?.sendConfig:void 0,hn=gt?.providerID??ve,pn=gt?.modelID??xe,Ks=gt?.agent,qu=ae?gt?.variant:J;if((!hn||!pn)&&!(yg&&!ae)){console.warn("Cannot send message: provider or model not selected"),Ce.error("Select a provider and model before sending a message.");return}const ut=he.getState().newSessionDraft,vc=!ze&&!ae&&!Te&&ut?.open===!0,xc=()=>he.getState().newSessionDraft.id===ut.id&&he.getState().currentSessionId===null,Wu=(l==="normal"?wv(Je.message):null)?.name==="compact",Og=!!(vc&&ut.worktreeIntent&&!Wu),ns=Og?new Set(a.current):null;let mn=null;if(vc){if(ut.id&&he.getState().sendingNewSessionDraftId===ut.id)return;if(he.getState().setSendingNewSessionDraftId(ut.id),Og){try{mn=await oN(Q)}catch{he.getState().sendingNewSessionDraftId===ut.id&&he.getState().setSendingNewSessionDraftId(null),Ce.error("Attachment data could not be saved for the worktree send.");return}U.current="",i(""),a.current.clear(),kt(Me,"")}await new Promise(rs=>{let Zt=!1;const on=()=>{Zt||(Zt=!0,rs())};typeof window<"u"&&typeof window.requestAnimationFrame=="function"&&window.requestAnimationFrame(()=>on()),setTimeout(()=>on(),50)})}try{const rs=!ze&&!$?.queuedOnly&&!$?.queuedMessageId&&ut?.open&&!Wu?ut.worktreeIntent:null;let Zt=br.getReceipt(rs);if(rs&&!Zt){const rt=br.request({intent:rs,prompt:Je.message,failedSend:{prompt:Je.message,confirmedMentions:ns?[...ns]:[],attachments:mn??[]}});if(mn&&mn.length>0&&Se(mn.map(It=>It.id)),Ce.info("Worktree queued",ut.id?{id:`worktree-queued:${ut.id}`}:void 0),he.getState().openNewSessionDraft(),re.getState().setActiveMainTab("chat"),Zt=await rt,!Zt){if((ut.id?ln.getState().getEntryByKey(ut.id):ln.getState().getEntry(rs))?.failedSend){Ce.error("Worktree creation failed",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}if(xc()){if(U.current=Je.message,a.current=ns??new Set,i(Je.message),Ts(Me,Je.message,ns??[]),mn){const bt=Ye.getState().restoreAttachmentsForRetry(mn);if(!bt.ok){const kn=_p({limit:bt.limit,currentCount:bt.currentCount,missingCount:bt.missingCount});Ce.error(kn.title,{description:kn.description})}}}else Ce.error("Worktree creation failed",{description:"Your prompt was not sent."});return}}const on=Zt?ut.id??a3(rs):null,kr=on?ln.getState().getEntryByKey(on)?.failedSend??null:null,bc=!ze&&!$?.queuedOnly&&!$?.queuedMessageId&&ut?.open&&!Wu?ut.branchIntent:null;if(bc&&!Pt.getReceipt(bc)){if(Pt.dialogState)return;await Pt.request({intent:bc,projectId:ut.selectedProjectId,continuation:$});return}const Ku=Pt.getReceipt(bc),Hg=ae&&ze&&Le?{target:ze,delivery:"steer",operationId:Le.id}:ze?{target:ze,...$e?{delivery:$e}:{}}:$e||Ku||Zt?{...$e?{delivery:$e}:{},...Ku?{branchCheckoutReceipt:Ku}:{},...Zt?{worktreeCreationReceipt:Zt,draftSnapshot:ut}:{}}:void 0,Fg=Ve(),gS=new Set(Hr.getState().skills.map(rt=>rt.name)),Gu=xB(ae&&Le?{queued:[{content:Le.content,attachments:Le.attachments}],composerText:null,composerAttachments:[],syntheticTexts:Fg?.map(rt=>rt.text)??[]}:{queued:[],composerText:Je.hasContent?Je.message:null,composerAttachments:iN(mn,Q),syntheticTexts:Fg?.map(rt=>rt.text)??[]},{parseAgentMention:rt=>({text:rt}),extractFileMentions:rt=>{const{sanitizedText:It,attachments:bt}=Re(rt);return{text:It,attachments:bt}},sanitizeAttachments:pe,collectSkillNames:rt=>yB(rt,gS),buildSkillInstruction:vB});let wc=Gu.primaryText;const{primaryAttachments:Bg,additionalParts:di}=Gu;if(Gu.isEmpty){!ae&&on&&kr&&Zt&&dN(on,kr,"Prompt was empty and was not sent.")&&Ce.error("Prompt was empty and was not sent.",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const Sc=()=>!Zt||xc();!ae&&Sc()&&(Qe.reset(),Ja(!1)),ne&&Sc()&&k.current?.blur();const Cc=l==="normal"?wv(wc):null;if(Cc&&await wB({command:Cc,currentSessionId:B,scrollToBottom:t,setTimelineDialogOpen:Ot,onUndoSession:async It=>{await he.getState().handleSlashUndo(It)},onRedoSession:async It=>{await he.getState().handleSlashRedo(It)},onCompactSession:async(It,bt)=>{try{await j_(),await T_(It,bt)}catch(kn){Ce.error(U9(kn,"Failed to compact session"))}}})){!ae&&on&&kr&&Zt&&uN(on,kr,mn,Q),Sc()&&(kt(Me,""),i(""),a.current.clear());return}let ui=!!(vc&&Cc&&!P4(Cc.name))?{...Hg,initialInputKind:"extension-command"}:Hg;const Vg=ze?.directory??ue,$g=await BH({newSessionDraftOpen:Ae,sessionId:ze?.sessionId??B,getStoreState:()=>qe().getState()});if($g&&di.push({text:VH($g),synthetic:!0}),l!=="shell")try{const rt=Or.getState().expandText;wc=rt(wc,Vg);for(const It of di)It.synthetic||(It.text=rt(It.text,Vg))}catch(rt){console.warn("[ChatInput] Failed to expand snippets, sending original text:",rt)}const yS=[...Bg,...di.flatMap(rt=>rt.attachments??[])],zg=c3(mn,Q);if(ae&&ze&&Le){const rt=ft.getState().markDeliveryAttempt(ze,Le.id,"steer");if(!rt?.streamEpoch){ft.getState().markSendUnconfirmed(ze,Le.id,"steer"),Ce.error("Follow-up status uncertain. Check status before retrying.");return}ui={...ui,streamEpoch:rt.streamEpoch}}!ae&&l==="shell"&&(ui={...ui,...f?{shellExcludeFromContext:!0}:{}});const vS=q(wc,hn??"",pn??"",Ks,Bg,void 0,di.length>0?di:void 0,qu,l,ui);Pt.clearReceipt(),typeof window>"u"?t?.():window.requestAnimationFrame(()=>{t?.()}),await vS.then(()=>{if(ae&&ze&&Le&&ft.getState().completeQueuedSend(ze,Le.id),!ae&&on&&kr&&ln.getState().markWorktreePromptSucceeded(on,kr),!ae&&zg.length>0&&Se(zg),!ae&&Sc()){const rt=Me?Jt(Me):"",It=P.current,bt=It?Jt(It):"",kn=k.current?.getValue()??U.current,kc=!kn||kn===Je.message;rt===bt?(kt(Me,kc?"":kn),kc&&(i(""),a.current.clear(),Qe.reset()),Ye.getState().publishSentDraftClear(rt,Je.message)):kt(Me,"")}}).catch(rt=>{if(ae&&ze&&Le){if(S3(rt)){ft.getState().markSendUnconfirmed(ze,Le.id,"steer"),console.warn("Follow-up send unconfirmed:",rt),Ce.error("Follow-up status uncertain. Check status before retrying.");return}ft.getState().markSendFailed(ze,Le.id)}const It=rt instanceof Error?rt.message:typeof rt=="string"?rt:String(rt??""),bt=It.toLowerCase();if(console.error("Message send failed:",It||rt),!ae&&on&&kr&&Zt){const Gs=It||"Prompt failed to send.";ln.getState().markWorktreePromptFailed(on,kr,Gs),Ce.error("Prompt failed to send",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const kn=k.current?.getValue()??U.current;if(xc()&&Je.message&&(!kn||kn===Je.message)&&(ns&&(a.current=ns),i(Je.message),Ts(Me,Je.message,ns??a.current)),xc()&&mn){const Gs=Ye.getState().restoreAttachmentsForRetry(mn);if(!Gs.ok){const Ug=_p({limit:Gs.limit,currentCount:Gs.currentCount,missingCount:Gs.missingCount});Ce.error(Ug.title,{description:Ug.description})}}const kc=bt.includes("timeout")||bt.includes("timed out")||bt.includes("may still be processing")||bt.includes("being processed")||bt.includes("failed to fetch")||bt.includes("networkerror")||bt.includes("network error")||bt.includes("gateway timeout")||bt==="failed to send message";if(bt.includes("payload too large")||bt.includes("413")||bt.includes("entity too large")){Ce.error("Attachments are too large to send. Please try reducing the number or size of images.");return}if(kc){yS.length>0&&Ce.error("Failed to send attachments. Try fewer files or smaller images.");return}if(bt.includes("runtime changed")){Ce.error("Message failed to send. Attachments remain available.");return}Ce.error(It||"Message failed to send. Attachments remain available.")})}finally{vc&&he.getState().sendingNewSessionDraftId===ut.id&&he.getState().setSendingNewSessionDraftId(null)}}finally{ae&&ze&&Le&&ft.getState().clearSending(ze,Le.id)}ne||k.current?.focus()}};Bn.current=vg;const xg=p.useCallback(()=>{const $=ai(),ae=l==="normal"&&$.hasContent&&B&&rn!=="idle";(dt==="queue"||fc)&&ae?hc():dt==="steer"&&ae?Bn.current({delivery:"steer"}):Bn.current()},[l,ai,B,rn,fc,dt,hc]),sn=p.useCallback(($,ae,Te="manual",$e)=>{const ze=eF($,ae,{inputMode:l,inputSource:Te,insertedText:$e});m(ze?.kind??null),x(ze?.query??"")},[l]),pc=p.useCallback($=>{const ae=()=>{try{k.current?.focus({preventScroll:!0})}catch{k.current?.focus()}k.current?.setSelection($)};requestAnimationFrame(()=>{ae(),requestAnimationFrame(ae)}),setTimeout(ae,60)},[]),Du=p.useCallback($=>{const ae=$.trim();if(!ae)return;const Te=`/${ae} `,$e=k.current,ze=$e?.getValue()??U.current??"",Le=ze.trim().length>0?`${Te}${ze.replace(/^\s+/,"")}`:Te,Je=Te.length;if($e)try{$e.replaceRange(0,ze.length,Le,Je)}catch{i(Le),requestAnimationFrame(()=>$e.setSelection(Je))}else i(Le);sn(Le,Je,"manual",Te),y(),pc(Je)},[y,pc,i,sn]),Ou=p.useCallback($=>{const ae=$.trim();if(!ae)return;const Te=k.current,$e=Te?.getValue()??U.current??"",ze=$e.trim().length>0,Le=ze?`${ae} ${$e.replace(/^\s+/,"")}`:ae,Je=ze?ae.length+1:ae.length;if(Te)try{Te.replaceRange(0,$e.length,Le,Je)}catch{i(Le),requestAnimationFrame(()=>Te.setSelection(Je))}else i(Le);sn(Le,Je,"manual"),y(),pc(Je)},[y,pc,i,sn]);p.useEffect(()=>{if(Fe==null)return;const $=Ye.getState().consumePendingStarterInsert();$&&("text"in $?Ou($.text):Du($.name))},[Fe,Du,Ou]);const q9=RB({inputMode:l,setInputMode:d,shellExcludeFromContext:f,setShellExcludeFromContext:u,message:o,setMessage:i,openAutocomplete:h,commandRef:X,snippetRef:F,mentionRef:z,composerRef:k,messageHistory:Qe,updateAutocompleteState:sn,isMobile:ne,hasContent:er,currentSessionId:B,sessionPhase:rn,commandRunning:!!fc,followUpBehavior:dt,handleSubmit:vg,handleQueueMessage:hc}),{update:W9}=SB({enabled:Qn,openAutocomplete:h,message:o,editorRef:k,containerRef:O}),mc=p.useCallback(()=>{Ne.current&&(clearTimeout(Ne.current),Ne.current=null),Xr(!0),Ne.current=setTimeout(()=>{Xr(!1),Ne.current=null},1800)},[]),K9=p.useCallback(()=>{te(),mc(),ke(B||void 0)},[ke,te,B,mc]),G9=p.useCallback(($,ae="manual")=>{if(!$)return;const Te=k.current;if(!Te){const gt=o+$;i(gt),sn(gt,gt.length,ae,$);return}const{start:$e,end:ze}=Te.getSelection(),Le=`${o.substring(0,$e)}${$}${o.substring(ze)}`,Je=$e+$.length;Te.insertText($),sn(Le,Je,ae,$)},[o,sn]),Z9=p.useCallback(()=>{const $=U.current.length;De.current=k.current?.getSelection()??{start:$,end:$},y(),fe.start().catch(()=>{})},[y,fe]),Y9=p.useCallback(()=>{fe.finish().then($=>{const ae=U.current,Te=De.current,$e=Math.min(Math.max(0,Te.start),ae.length),ze=Math.min(Math.max($e,Te.end),ae.length),Le=R4($.trim(),ae.slice(0,$e),ae.slice(ze));if(!Le)return;const Je=k.current;if(Je)Je.replaceRange($e,ze,Le,$e+Le.length),Je.focus({preventScroll:!0});else{const gt=`${ae.slice(0,$e)}${Le}${ae.slice(ze)}`;i(gt),sn(gt,$e+Le.length,"manual",Le)}}).catch(()=>{})},[fe,sn]);p.useEffect(()=>{fe.state!=="error"||!fe.error||Ue.current===fe.error||(Ue.current=fe.error,Ce.error(fe.error))},[fe.error,fe.state]);const Hu=p.useCallback(()=>{N.current=!1,D.current&&(clearTimeout(D.current),D.current=null)},[]),X9=p.useCallback(()=>{N.current=!0,D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{N.current=!1,D.current=null},700)},[]),J9=({value:$,selection:ae,fromPaste:Te,insertedText:$e})=>{const ze=Te?$e:"",Le=ze.includes("@")||N.current;N.current&&Hu();const Je=Le?"paste":"manual";if(l==="shell"&&!f&&$.startsWith("!")){const gt=$.slice(1),hn=Math.max(0,ae.start-1);u(!0),i(gt);const pn=k.current;pn&&pn.getValue()!==gt?pn.replaceRange(0,1,"",hn):requestAnimationFrame(()=>k.current?.setSelection(hn));return}if(l==="normal"&&$.startsWith("!")){const gt=$.slice(1),hn=Math.max(0,ae.start-1);d("shell"),i(gt),y();const pn=k.current;pn&&pn.getValue()!==gt?(pn.replaceRange(0,1,"",hn),y()):requestAnimationFrame(()=>k.current?.setSelection(hn));return}i($),sn($,ae.start,Je,ze)};p.useEffect(()=>()=>{Hu()},[Hu]);const Q9=gB({inputMode:l,enabled:!!(B||Ae),composerRef:k,message:o,setMessage:i,insertTextAtSelection:G9,updateAutocompleteState:sn,markFileMentionPasteSuppression:X9,attachedFiles:Q,addAttachedFile:me}),eS=p.useCallback($=>xL($,ni||""),[ni]),{handleFileSelect:tS,handleSnippetSelect:nS,handleCommandSelect:rS}=jB({composerRef:k,message:o,setMessage:i,updateAutocompleteState:sn,closeAutocomplete:y,confirmedMentionsRef:a,toMentionPath:eS});p.useEffect(()=>{B&&k.current&&!ne&&k.current.focus()},[B,ne]),p.useEffect(()=>{ne||I(null)},[ne]),p.useEffect(()=>{Xe&&Xe!==B&&te()},[Xe,B,te]),p.useEffect(()=>{W.current=!!(B||Ae)},[B,Ae]);const{isDragging:sS,isInternalDrag:oS,handleDragEnter:bg,handleDragOver:wg,handleDragLeave:iS,handleDragEnd:Sg,handleDrop:Cg,handleDropCapture:kg}=fB({enabled:!!(B||Ae),composerRef:k,messageRef:U,cursorPosRef:L,confirmedMentionsRef:a,setMessage:i,addAttachedFile:me}),Mg=p.useRef(null),Ig=p.useCallback(async $=>{const ae=Array.isArray($)?$:Array.from($),Te=await Promise.all(ae.map(async $e=>{try{return await me($e)}catch(ze){return console.error("File attach failed",ze),!1}}));ae.length>0&&!Te.some(Boolean)&&Ce.error("Failed to attach file")},[me]),Eg=p.useCallback(()=>{Ws||Mg.current?.click()},[Ws]),[_g,jg]=p.useState(!1),aS=p.useCallback(()=>{Ws||jg(!0)},[Ws]),cS=p.useCallback(async $=>{const ae=$.target.files;ae&&(await Ig(ae),$.target.value="")},[Ig]),lS="gap-x-1.5 gap-y-0",dS=!0,li=(Ae||!!B)&&!Ke,{projects:Tg,selectedDraftProject:ts,selectedDraftBranchLabel:Fu,selectedBranchName:Bu,draftBranchItems:Ag,isDiscoveringDraftBranches:Ng,shouldShowDraftBranchSelector:tr,worktreeMode:Vu,handleDraftProjectChange:Lg,handleDraftBranchChange:Rg,handleWorktreeModeChange:$u}=OB(li),Pg=!!(li&&ts&&(Ae||tr)),gc=p.useMemo(()=>Ke||ri!==!0||!xr||xr.isClean?!1:o4(xr.files,xr.diffStats,ue).length>0,[ue,xr,ri,Ke])?c.jsx(c4,{align:Pg?"end":"start"}):null,zu=$B({isMobile:ne,editorRef:k,formRef:M,controlsPanelOpen:!!w,attachMenuOpen:!1}),uS=zu.focused;p.useEffect(()=>{j("")},[E]),zB({isMobile:ne,isFullscreen:es,isDraftScreen:Ae,isFocused:uS,formRef:M,editorRef:k});const fS=ne?"pl-1.5 pr-3 pt-1.5 pb-3":wr?"px-1.5 py-1":"px-3 py-2",hS=ne?"h-8 w-8":"h-6 w-6",pS="h-4 w-4",mS=ne?"h-6 w-6":"h-5 w-5",yc="h-[18px] w-[18px]",Dg="flex cursor-pointer items-center justify-center text-foreground transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed",Uu=R(Dg,hS);return p.useEffect(()=>{const $=!!Xe&&Xe===B;!lt.current&&$&&!Fn&&(mc(),B&&ie(B)),lt.current=$},[Xe,ie,B,Fn,mc]),p.useEffect(()=>()=>{Ne.current&&(clearTimeout(Ne.current),Ne.current=null)},[]),c.jsxs(c.Fragment,{children:[c.jsxs("form",{ref:M,onSubmit:$=>{$.preventDefault(),xg()},className:R("relative w-full pt-0 pb-4",Qn,es&&"flex h-full min-h-0 flex-col pt-2",ne&&"bottom-safe-area oc-mobile-composer"),style:ne&&Vs>0?{marginBottom:`${Vs}px`}:void 0,children:[c.jsxs("div",{className:R("chat-input-column relative overflow-visible",nn&&"flex flex-1 min-h-0 flex-col"),children:[c.jsx(U3,{onEditMessage:$9,onSendMessage:z9}),c.jsx(K4,{sessionId:B,directory:ye??ue}),c.jsx(w$,{showAbortStatus:Fn,showAssistantStatus:!1,showTodos:dS,leftAccessory:Pg||Ae||!gc?null:gc}),!Sn&&li&&ts&&(Ae||tr)?c.jsx("div",{inert:$n||void 0,className:R($n&&"pointer-events-none opacity-60"),children:c.jsx(xV,{projects:Tg,selectedProject:ts,selectedBranchName:Bu,selectedBranchLabel:Fu,branchOptions:Ag,branchInteractive:Ae,branchLoading:Ng,showBranchSelector:tr&&Ae,showProjectSelector:Ae,showWorktreeSelector:Ae&&tr,worktreeMode:Vu,endAccessory:gc,onProjectChange:Lg,onBranchChange:Rg,onWorktreeModeChange:$u,theme:Yr})}):null,Sn&&li&&ts&&(Ae||tr)?c.jsx("div",{inert:$n||void 0,className:R($n&&"pointer-events-none opacity-60"),children:c.jsx(bV,{selectedProject:ts,selectedBranchName:Bu,selectedBranchLabel:Fu,branchInteractive:Ae,showBranchSelector:tr,showProjectSelector:Ae,showWorktreeSelector:Ae&&tr,worktreeMode:Vu,onWorktreeModeChange:$u,endAccessory:gc,theme:Yr,onOpenPicker:T})}):null,c.jsx("div",{className:R(!ne&&"contents",ne&&"relative",es&&"flex min-h-0 flex-1 flex-col"),children:c.jsx(c.Fragment,{children:c.jsxs("div",{className:R("flex flex-col relative overflow-visible",nn&&"flex-1 min-h-0",Vn&&!nn&&"min-h-[7rem]","border border-border/80","shadow-[0_4px_16px_-4px_rgb(0_0_0_/_0.12)]","focus-within:ring-1",l==="shell"?"focus-within:ring-[color:color-mix(in_srgb,var(--status-info)_45%,transparent)]":"focus-within:ring-primary/30"),style:{borderRadius:zs,backgroundColor:Yr?.colors?.surface?.subtle},ref:O,"data-composer-card":"true",onDropCapture:kg,onDragEnter:bg,onDragOver:wg,onDragLeave:iS,onDrop:Cg,onDragEnd:Sg,children:[sS&&c.jsx(WV,{isInternalDrag:oS,iconButtonBaseClass:Dg,iconSizeClass:yc,radius:zs,isAttachmentDisabled:Ws,onPickLocalFiles:Eg}),et&&c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-20 overflow-hidden",style:{borderRadius:zs},children:c.jsx("span",{className:"attachment-upload-shimmer absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r from-transparent via-foreground/10 to-transparent"})}),c.jsx(PV,{open:h,query:g,overlayPosition:null,commandRef:X,snippetRef:F,mentionRef:z,onCommandSelect:rS,onSnippetSelect:nS,onFileSelect:tS,onClose:y,onCommandComboboxStateChange:S}),c.jsx(qV,{isMobile:ne,isInline:wr,alignToolsEnd:gg>1,sessionId:B,directory:ye??ue,newSessionDraftOpen:Ae,messageLength:o.length,leadingExtra:l!=="shell"&&(Vn||ne)?c.jsx(zv,{keepLabels:!0,className:"w-max shrink-0",mobilePanel:ne?w:void 0,onMobilePanelChange:ne?I:void 0}):null,trailingExtra:st?null:c.jsx(ZV,{available:fe.available,disabled:!B&&!Ae||$n,className:Uu,iconClassName:yc,onStart:Z9}),actionsOverride:st?c.jsx(r$,{state:fe.state,elapsedSeconds:fe.elapsedSeconds,buttonClassName:Uu,iconClassName:yc,isMobile:ne,onCancel:fe.cancel,onDone:Y9}):void 0,radius:zs,footerPaddingClass:fS,footerGapClass:lS,footerIconButtonClass:Uu,iconSizeClass:yc,sendIconSizeClass:pS,stopIconSizeClass:mS,canSend:B9&&!$n,isSending:et,isShellMode:l==="shell",isAttachmentDisabled:Ws,disabledReason:F9,canAbort:V9,hasContent:!!er,onOpenSettings:e,onPickLocalFiles:Eg,onLinkGitHub:aS,onPrimaryAction:xg,onQueueMessage:hc,onAbort:K9,children:st?c.jsx(s$,{state:fe.state,subscribeLevel:fe.subscribeLevel}):c.jsxs("div",{className:R("overflow-hidden",nn&&"flex flex-1 min-h-0 flex-col"),children:[l==="shell"?c.jsxs("div",{className:R("flex items-center gap-1.5 typography-micro text-muted-foreground",wr?"px-1.5 pt-1":"px-3 pt-2"),"data-testid":"chat-input-shell-mode",children:[c.jsx(V,{name:"terminal-box",className:"size-3.5 shrink-0 text-foreground"}),c.jsx("span",{className:"font-medium text-foreground",children:"Shell"}),c.jsx("span",{className:"min-w-0 truncate",children:f?"Output not sent to the model":"Output sent to the model"}),!ne||_t?c.jsx("span",{className:"ml-auto shrink-0",children:"Esc to exit"}):c.jsx(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>{d("normal"),k.current?.focus()},className:"ml-auto h-6 shrink-0 px-2 typography-micro font-medium text-muted-foreground hover:text-foreground",children:"Exit shell"})]}):null,c.jsx("div",{className:"relative z-10",children:c.jsx($3,{onShowPopup:Ru,isInline:wr,isMobile:ne})}),c.jsx("div",{className:R("relative overflow-hidden",nn&&"flex flex-1 min-h-0 flex-col"),onDragEnter:bg,onDragOver:wg,onDropCapture:kg,onDrop:Cg,onDragEnd:Sg,children:c.jsx(nB,{ref:k,viewStore:_,"data-testid":"chat-input",value:o,languageContext:Z,onChange:J9,onKeyDown:$=>(q9($),$.defaultPrevented),onPaste:Q9,onSelectionChange:$=>{L.current=$.start,W9()},onVisualLineCount:$=>{oi(ae=>ae===$?ae:$)},onFocus:zu.onEditorFocus,onBlur:zu.onEditorBlur,placeholder:K?"Session is open elsewhere":B||Ae?l==="shell"?f?"Enter shell command...":"Enter shell command... (!! keeps it from the model)":rc?"Plan, build, / for skills, @ for context":sc?"Ask anything. @ files, / commands":"Ask anything. @ files, / commands, ! shell, # snippets":"Select or create a session to start chatting",editable:!!(B||Ae)&&!$n,autoCorrect:!1,autoCapitalize:"none",spellCheck:ne,fillContainer:nn,maxLines:ne?v$:y$,boundSelector:ne?"[data-composer-bound]":void 0,boundGapPx:x$,commandComboboxExpanded:C,commandComboboxListboxId:v,commandComboboxActiveOptionId:C?b?.activeOptionId:void 0,className:R("relative z-10",wr?"min-h-0 px-1.5 py-1.5":"min-h-[52px] px-3",nn?R("h-full min-h-0",ne?"py-2.5":"py-4"):ne?Q.length>0?"pt-1 pb-2.5":"py-2.5":wr?void 0:Q.length>0?"pt-1.5 pb-2":"pt-3 pb-2","typography-markdown md:typography-ui-label",l==="shell"&&"font-mono")})})]})})]})})}),Vn||ne||l==="shell"?null:c.jsx("div",{className:R("mt-1.5 flex w-full shrink-0 items-center pl-2",$n&&"pointer-events-none opacity-60"),inert:$n||void 0,children:c.jsx(zv,{className:"w-full min-w-0"})})]}),Ae&&!Qn&&!ne&&!Ke?c.jsx(w4,{onInsert:$=>$.ref.type==="text"?Ou($.insertText):Du($.promptName),className:"chat-input-column mt-3"}):null]}),nc?c.jsx(p.Suspense,{fallback:null,children:c.jsx(g$,{popup:si,onOpenChange:Pu,isMobile:ne})}):null,c.jsx(GV,{inputRef:Mg,onChange:cS}),c.jsx(SV,{state:Pt.dialogState,onCancel:Pt.cancel,onConfirm:()=>{Pt.confirm()}}),_g&&(ye??ue)?c.jsx(p.Suspense,{fallback:null,children:c.jsx(m$,{directory:ye??ue,open:_g,onClose:()=>jg(!1)})}):null,Sn&&li&&ts?c.jsx(wV,{projects:Tg,selectedProject:ts,selectedBranchName:Bu,selectedBranchLabel:Fu,branchOptions:Ag,branchInteractive:Ae,branchLoading:Ng,showBranchSelector:tr,showProjectSelector:Ae,showWorktreeSelector:Ae&&tr,worktreeMode:Vu,onProjectChange:Lg,onBranchChange:Rg,onWorktreeModeChange:$u,theme:Yr,openPicker:E,onOpenPickerChange:T,query:A,onQueryChange:j}):null]})};Z4.displayName="ChatInput";const ji=p.memo(Z4);function C$({label:e,className:t}){return c.jsx("span",{className:R("size-1.5 shrink-0 rounded-full bg-status-warning",t),"aria-label":e,title:e})}const k$=e=>e!=null&&e.count>0,dQ=e=>k$(e.pendingInput)?"needs-input":e.isStreaming?"working":!e.isStreaming&&!e.isActive&&e.unseenCount>0?"unread":null,M$=(e,t)=>{const n=e==="approval"?"Needs approval":"Needs input";return t>1?`${n} (${t} requests)`:n},uQ=e=>e===1?"A session needs input":`${e} sessions need input`,I$="underline decoration-dotted underline-offset-2 hover:decoration-solid",Y4=({segment:e,href:t,children:n})=>c.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:I$,style:Nd(e),children:n}),qt=H.memo(({text:e,className:t,style:n,links:r=!1})=>{if(e==null||e==="")return null;if(!z4(e))return t||n?c.jsx("span",{className:t,style:n,children:e}):c.jsx(c.Fragment,{children:e});const s=U4(e);return s.length===0?null:s.length===1&&!Nd(s[0])&&!(r&&s[0].href)?t||n?c.jsx("span",{className:t,style:n,children:s[0].text}):c.jsx(c.Fragment,{children:s[0].text}):c.jsx("span",{className:t,style:n,children:s.map((o,i)=>{const a=r?$4(o.href):void 0;if(a)return c.jsx(Y4,{segment:o,href:a,children:o.text},i);const l=Nd(o);return l?c.jsx("span",{style:l,children:o.text},i):c.jsx(H.Fragment,{children:o.text},i)})})});qt.displayName="AnsiText";const E$=(e,t,n)=>{if(n<=0)return null;switch(e){case"ArrowDown":return{kind:"highlight",index:(t+1)%n};case"ArrowUp":return{kind:"highlight",index:(t-1+n)%n};case"Home":return{kind:"highlight",index:0};case"End":return{kind:"highlight",index:n-1};case"Enter":case" ":return{kind:"submit",index:t};default:{if(e.length!==1||e<"1"||e>"9")return null;const r=Number(e)-1;return r<n?{kind:"submit",index:r}:null}}},_$=async(e,t,n)=>{try{await Ie.respondToExtensionDialog({requestId:t.requestId,...n},{runtimeKey:Y()}),qe().dismissExtensionDialog(e,t.requestId)}catch(r){if(r instanceof at&&r.code==="EXTENSION_DIALOG_NOT_PENDING"){qe().dismissExtensionDialog(e,t.requestId);return}throw r}},j$=()=>{requestAnimationFrame(()=>{document.querySelector('[data-slot="composer-editor"], .chat-input-column textarea, textarea')?.focus()})},T$=(e,t)=>{const[n,r]=H.useState(()=>typeof e!="number"||e<=0?null:Math.max(0,Math.ceil(e/1e3)));return H.useEffect(()=>{if(typeof e!="number"||e<=0){r(null);return}const s=Date.now();let o=null;const i=()=>{const a=Date.now()-s,l=Math.max(0,Math.ceil((e-a)/1e3));r(l),l<=0&&o!==null&&(clearInterval(o),o=null)};return i(),o=setInterval(i,1e3),()=>{o!==null&&clearInterval(o)}},[e,t]),n},A$=e=>e?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?e.value.trim().length>0:e.isContentEditable?(e.textContent??"").trim().length>0:!1:!1,N$=({request:e,onRespond:t,messageId:n,highlightedIndex:r,setHighlightedIndex:s})=>{const o=e.options??[];return c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsx("div",{className:"flex flex-col gap-1 max-h-60 overflow-y-auto",role:"listbox","aria-label":Nn(e.title),children:o.map((i,a)=>{const l=a===r,d=a<9?a+1:void 0;return c.jsxs("button",{type:"button",role:"option","aria-selected":l,tabIndex:l?0:-1,onMouseEnter:()=>s(a),onFocus:()=>s(a),onClick:()=>t({value:i}),className:R("flex w-full items-center justify-between rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors outline-none",l?"bg-interactive-selection text-interactive-selection-foreground font-medium":"text-foreground hover:bg-interactive-hover"),children:[c.jsx("span",{className:"truncate",children:c.jsx(qt,{text:i})}),d!==void 0&&c.jsx("span",{className:R("ml-2 shrink-0 font-mono text-xs opacity-70",l?"text-interactive-selection-foreground":"text-muted-foreground"),children:d})]},i)})})]})},L$=({request:e,onRespond:t,messageId:n})=>c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-3 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsxs("div",{className:"flex items-center justify-end gap-2",children:[c.jsx(be,{type:"button",variant:"outline",size:"sm",onClick:()=>t({confirmed:!1,cancelled:!0}),children:"No (N)"}),c.jsx(be,{type:"button",variant:"default",size:"sm",onClick:()=>t({confirmed:!0}),children:"Yes (Y)"})]})]}),R$=({request:e,onRespond:t,messageId:n})=>{const r=e.method==="editor",[s,o]=H.useState(r?e.prefill??"":""),i=()=>{t({value:s})};return c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),r?c.jsx("textarea",{autoFocus:!0,value:s,onChange:a=>o(a.target.value),placeholder:e.placeholder?Nn(e.placeholder):"","aria-label":Nn(e.title),rows:4,className:"w-full resize-y rounded-md border bg-transparent p-2 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing",onKeyDown:a=>{a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&(a.preventDefault(),i())}}):c.jsx("input",{autoFocus:!0,type:"text",value:s,onChange:a=>o(a.target.value),placeholder:e.placeholder?Nn(e.placeholder):"","aria-label":Nn(e.title),className:"w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing",onKeyDown:a=>{a.key==="Enter"&&(a.preventDefault(),i())}}),c.jsxs("div",{className:"mt-2.5 flex justify-end gap-2",children:[c.jsx(be,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),c.jsx(be,{type:"button",variant:"default",size:"sm",onClick:i,disabled:!r&&s.trim().length===0,children:"Submit"})]})]})},P$=({request:e,onRespond:t,messageId:n})=>{const r={};for(const u of e.fields??[])u.type==="checkbox"?r[u.id]=u.initial==="true"?"true":"false":u.initial!==void 0?r[u.id]=u.initial:u.type==="select"&&u.options?.[0]!==void 0?r[u.id]=u.options[0]:r[u.id]="";const[s,o]=H.useState(r),[i,a]=H.useState(!1),l=(e.fields??[]).filter(u=>u.required&&(s[u.id]??"").length===0),d=(e.fields??[]).filter(u=>{if(u.type!=="number")return!1;const h=s[u.id]??"";if(h.length===0)return!1;const m=Number(h);return!Number.isFinite(m)||"min"in u&&typeof u.min=="number"&&m<u.min||"max"in u&&typeof u.max=="number"&&m>u.max}),f=i&&(l.length>0||d.length>0);return c.jsxs("form",{onSubmit:u=>{u.preventDefault(),a(!0),!(l.length>0||d.length>0)&&t({values:{...s}})},children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsx("div",{className:"flex max-h-60 flex-col gap-2.5 overflow-y-auto",children:(e.fields??[]).map(u=>{const h=f&&u.required&&(s[u.id]??"").length===0,m=f&&d.some(y=>y.id===u.id),g=h||m,x=s[u.id]??"",b=y=>o(v=>({...v,[u.id]:y})),S="w-full rounded-md border bg-transparent p-1.5 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing";return u.type==="checkbox"?c.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[c.jsx("input",{type:"checkbox",checked:x==="true",onChange:y=>b(y.target.checked?"true":"false"),className:"size-4"}),c.jsx("span",{children:c.jsx(qt,{text:u.label})})]},u.id):c.jsxs("label",{className:"flex flex-col gap-1 text-sm",children:[c.jsxs("span",{className:"text-xs font-medium text-foreground",children:[c.jsx(qt,{text:u.label}),u.required&&c.jsx("span",{"aria-hidden":"true",className:"text-status-error",children:" *"})]}),u.type==="textarea"?c.jsx("textarea",{value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"",rows:2,"aria-invalid":g||void 0,className:S}):u.type==="number"?c.jsx("input",{type:"number",value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"",min:"min"in u&&typeof u.min=="number"?u.min:void 0,max:"max"in u&&typeof u.max=="number"?u.max:void 0,"aria-invalid":g||void 0,className:S}):u.type==="select"?c.jsx("select",{value:x,onChange:y=>b(y.target.value),"aria-invalid":g||void 0,className:S,children:(u.options??[]).map(y=>c.jsx("option",{value:y,children:y},y))}):c.jsx("input",{type:"text",value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"","aria-invalid":g||void 0,className:S})]},u.id)})}),f&&c.jsx("p",{role:"alert",className:"mt-2 text-xs text-status-error",children:l.length>0&&d.length>0?"Fill in all required fields and enter valid numbers within the allowed range before submitting.":d.length>0?"Enter valid numbers within the allowed range before submitting.":"Fill in all required fields before submitting."}),c.jsxs("div",{className:"mt-2.5 flex justify-end gap-2",children:[c.jsx(be,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),c.jsx(be,{type:"submit",variant:"default",size:"sm",children:"Submit"})]})]})},D$=3,O$=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(!r||!s||r.sessionId!==s.sessionId||r.directory!==s.directory||r.title!==s.title||r.pending.count!==s.pending.count||r.pending.kind!==s.pending.kind||r.pending.since!==s.pending.since)return!1}return!0},H$=e=>Be(t=>{const n=[];for(const r of qm(t.catalog)){if(e&&r.sessionId===e)continue;const s=t.catalog.byId.get(r.sessionId),o=s?n3(Ns(s),"Untitled session"):"Untitled session";n.push({sessionId:r.sessionId,directory:r.directory,pending:r.pending,title:o})}return n},O$,"catalog",e??""),F$=({sessions:e})=>{const t=he(s=>s.setCurrentSession),n=e.slice(0,D$),r=e.length-n.length;return c.jsxs("div",{role:"region","aria-label":"Other sessions need input",className:"overflow-hidden rounded-xl border border-border/80 bg-card p-1.5 shadow-md",children:[c.jsx("ul",{className:"flex flex-col",children:n.map(s=>{const o=M$(s.pending.kind,s.pending.count);return c.jsxs("li",{className:"flex min-h-[44px] items-center gap-2 px-2 py-1",children:[c.jsx(C$,{label:o}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-foreground",title:`${s.title} — ${o}`,children:s.title}),s.pending.count>1?c.jsx("span",{className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:`${s.pending.count} requests`}):null,c.jsx(be,{type:"button",variant:"outline",size:"sm",onClick:()=>{t(s.sessionId,s.directory)},"aria-label":`Open ${s.title}`,children:"Open"})]},s.sessionId)})}),r>0?c.jsx("p",{className:"px-2 pb-1 text-xs text-muted-foreground",children:`+${r} more`}):null]})},Uv=({sessionId:e})=>{const t=Be(y=>{const v=e??y.selectedSessionId,w=(v?y.reducer.bySession.get(v):void 0)?.extensionDialogs??[],I=w[0];if(I&&v)return{sessionId:v,request:I,queueLength:w.length};if(e!==void 0)return null;for(const[E,T]of y.reducer.bySession){const A=T.extensionDialogs,j=A[0];if(j)return{sessionId:E,request:j,queueLength:A.length}}return null},(y,v)=>y?.sessionId===v?.sessionId&&y?.request.requestId===v?.request.requestId&&y?.queueLength===v?.queueLength,"dialogs",e??""),n=he(y=>y.currentSessionId),s=H$(e??n??null),[o,i]=H.useState(!1),[a,l]=H.useState(!1),[d,f]=H.useState(0),u=H.useRef(!1),h=H.useRef(null),m=H.useId(),g=t?`${t.sessionId}\0${t.request.requestId}`:null;H.useEffect(()=>{u.current=!1,i(!1),l(!1),f(0),g!==null&&h.current&&!h.current.contains(document.activeElement)&&!A$(document.activeElement)&&h.current.focus()},[g]);const x=T$(t?.request.timeoutMs,t?.request.requestId),b=H.useCallback(y=>{!t||o||u.current||(u.current=!0,i(!0),l(!1),_$(t.sessionId,t.request,y).then(()=>{j$()}).catch(()=>{l(!0)}).finally(()=>{u.current=!1,i(!1)}))},[o,t]),S=y=>{if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),b({cancelled:!0});return}if(t){if(t.request.method==="confirm"){if(y.key==="y"||y.key==="Y"){y.preventDefault(),b({confirmed:!0});return}if(y.key==="n"||y.key==="N"){y.preventDefault(),b({confirmed:!1,cancelled:!0});return}}if(t.request.method==="select"){const v=t.request.options??[],C=E$(y.key,d,v.length);if(!C)return;const I=(y.target instanceof HTMLElement?y.target:null)?.getAttribute("role")==="option";if(C.kind==="highlight"){y.preventDefault(),f(C.index),I&&h.current?.querySelectorAll('[role="option"]')[C.index]?.focus();return}if((y.key==="Enter"||y.key===" ")&&!I&&y.target!==y.currentTarget)return;const T=v[C.index];if(T===void 0)return;y.preventDefault(),b({value:T})}}};return!t&&s.length===0?null:c.jsxs("div",{"data-extension-prompt-dock":!0,className:"chat-input-column relative mb-2 flex flex-col gap-2",children:[s.length>0?c.jsx(F$,{sessions:s}):null,t?c.jsxs("div",{ref:h,role:"dialog","aria-label":Nn(t.request.title),"aria-describedby":t.request.message?m:void 0,tabIndex:-1,onKeyDown:S,className:"relative z-40 overflow-hidden rounded-xl border border-border/80 bg-card p-3 shadow-md transition-[opacity,transform] duration-150 outline-none",children:[c.jsxs("div",{className:"mb-2.5 flex items-center justify-between gap-2 border-b border-border/40 pb-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx(V,{name:"plug-2",className:"size-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"truncate text-xs font-semibold uppercase tracking-wider text-foreground",children:c.jsx(qt,{text:t.request.title})})]}),c.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.queueLength>1&&c.jsxs("span",{className:"rounded-full bg-muted px-2 py-0.5 typography-micro font-medium text-muted-foreground",children:["1 of ",t.queueLength]}),x!==null&&c.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",title:`${x}s remaining`,children:[x,"s"]}),c.jsx(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>b({cancelled:!0}),className:"h-6 px-1.5 typography-micro text-muted-foreground hover:text-foreground","aria-label":"Dismiss extension dialog",children:"Dismiss (Esc)"})]})]}),c.jsxs("div",{className:o?"pointer-events-none opacity-60":void 0,"aria-busy":o||void 0,children:[t.request.method==="select"&&c.jsx(N$,{request:t.request,onRespond:b,messageId:m,highlightedIndex:d,setHighlightedIndex:f}),t.request.method==="confirm"&&c.jsx(L$,{request:t.request,onRespond:b,messageId:m}),(t.request.method==="input"||t.request.method==="editor")&&c.jsx(R$,{request:t.request,onRespond:b,messageId:m}),t.request.method==="form"&&c.jsx(P$,{request:t.request,onRespond:b,messageId:m})]}),a&&c.jsx("p",{role:"alert",className:"mt-2 text-xs text-status-error",children:"Could not send the response. Check your connection and try again."})]}):null]})},B$=e=>{const t=e.replace(/[-_]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e},V$=({sessionId:e,className:t})=>{const n=Be(d=>d.selectedSessionId),r=e??n,s=Be(d=>r?d.reducer.bySession.get(r)?.extensionWidgets:void 0,(d,f)=>d===f,r?`session:${r}`:"chrome"),o=H.useMemo(()=>[...s?.entries()??[]],[s]),[i,a]=H.useState({}),l=H.useCallback(d=>{a(f=>({...f,[d]:!f[d]}))},[]);return o.length===0?c.jsxs("div",{className:R("flex h-full flex-col items-center justify-center gap-1.5 p-6 text-center",t),"data-testid":"extensions-surface-empty",children:[c.jsx(V,{name:"plug-2","aria-hidden":"true",className:"size-6 text-subtle-foreground"}),c.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"No extension widgets yet"}),c.jsx("p",{className:"max-w-60 typography-micro text-muted-foreground",children:"Widgets that extensions set with ctx.ui.setWidget show up here."})]}):c.jsx("div",{className:R("flex h-full min-h-0 flex-col overflow-y-auto",t),"data-testid":"extensions-surface",children:c.jsx($$,{title:"Widgets",count:o.length,children:o.map(([d,f])=>c.jsx(z$,{title:B$(d),meta:f.placement==="belowEditor"?"below editor":"above editor",collapsed:!!i[d],onToggle:()=>l(d),testId:`extension-widget-${d}`,children:c.jsx("div",{className:"max-h-64 overflow-auto rounded-md bg-muted/40 px-2 py-1.5 font-mono typography-micro leading-relaxed text-foreground",children:f.lines.map((u,h)=>c.jsx("span",{className:"block whitespace-pre-wrap",children:c.jsx(qt,{text:u})},h))})},d))})})},$$=({title:e,count:t,children:n})=>c.jsxs("section",{"aria-label":e,className:"border-t border-border/60 first:border-t-0",children:[c.jsxs("p",{className:"flex items-center gap-1.5 px-3 pb-0.5 pt-1.5 typography-micro font-medium text-muted-foreground",children:[e,c.jsx("span",{className:"tabular-nums text-subtle-foreground",children:t})]}),c.jsx("div",{className:"flex flex-col p-1 pt-0.5",children:n})]}),z$=({title:e,meta:t,collapsed:n,onToggle:r,testId:s,children:o})=>c.jsxs("div",{"data-testid":s,children:[c.jsxs("button",{type:"button",onClick:r,"aria-expanded":!n,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-left hover:bg-interactive-hover",children:[c.jsx("span",{className:"inline-flex w-4 shrink-0 items-center justify-center",children:c.jsx(V,{name:n?"arrow-right-s":"arrow-down-s","aria-hidden":"true",className:"size-3.5 text-muted-foreground"})}),c.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:e,children:e}),t?c.jsx("span",{className:"shrink-0 whitespace-nowrap typography-micro text-muted-foreground",children:t}):null]}),!n&&c.jsx("div",{className:"pb-2 pl-8 pr-2 pt-0.5",children:o})]}),U$=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),qv=({sessionId:e})=>{const t=Be(u=>u.selectedSessionId),n=e??t,{isMobile:r}=On(),[s,o]=H.useState(!1),i=Be(u=>[...(n?u.reducer.bySession.get(n):void 0)?.extensionStatuses.entries()??[]],(u,h)=>U$(u.flat(),h.flat()),`session:${n??""}`),{widgetsCount:a,sessionDirectory:l}=Be(u=>{const h=n?u.reducer.bySession.get(n):void 0;return{widgetsCount:h?.extensionWidgets.size??0,sessionDirectory:h?.directory}},(u,h)=>u.widgetsCount===h.widgetsCount&&u.sessionDirectory===h.sessionDirectory,`session:${n??""}`);H.useEffect(()=>{a===0&&o(!1)},[a]);const d=a===0?"":a===1?"1 widget":`${a} widgets`,f=H.useCallback(()=>{if(r){o(h=>!h);return}const u=l||nt.getState().currentDirectory||"";re.getState().openContextSurface(u,"extensions")},[r,l]);return i.length===0&&!d?null:c.jsxs("div",{className:"chat-input-column flex flex-col gap-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 overflow-hidden rounded-full border border-border/40 bg-card px-3 py-1.5 shadow-sm transition-[opacity,transform] duration-150",children:[c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[c.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center rounded-full bg-interactive-hover text-muted-foreground",children:c.jsx(V,{name:"plug-2",className:"size-3"})}),i.length>0&&c.jsx("div",{className:"flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hidden touch-pan-x","data-no-drawer-swipe":"true",children:i.map(([u,h])=>c.jsx("span",{className:"inline-flex shrink-0 items-center whitespace-nowrap rounded-full border border-border/60 bg-muted/40 px-2 py-0.5 typography-micro font-medium text-foreground",children:c.jsx(qt,{text:h})},u))})]}),d&&c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:f,"aria-label":"Open extensions panel","aria-expanded":r?s:void 0,className:"shrink-0 gap-1 rounded-full border border-border/50 bg-muted/40 px-2 py-0.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground active:bg-interactive-active",children:[c.jsx(V,{name:"layout-right",className:"size-3"}),c.jsx("span",{children:d})]})]}),r&&s&&c.jsx("div",{className:"max-h-60 overflow-y-auto rounded-xl border border-border/80 bg-card p-2 shadow-md",children:c.jsx(V$,{sessionId:n,className:"h-auto"})})]})},q$=({sessionId:e})=>{const t=re(r=>r.commandTriggers),n=p.useCallback((r,s)=>{e&&qe().prompt(e,D5(r,s),"prompt").catch(()=>{})},[e]);return!e||t.length===0?null:c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-1.5 px-1",role:"toolbar","aria-label":"Command triggers",children:t.map(r=>c.jsx(be,{size:"xs",variant:"outline",disabled:!e,onClick:()=>n(r.command,r.args),title:r.combo?`${r.label} (${SC(r.combo)})`:r.label,children:r.label},r.id))})},W$=e=>[...e.key].length!==1?!1:e.getModifierState?.("AltGraph")===!0?!0:e.ctrlKey&&e.altKey&&!/^[a-z]$/i.test(e.key),K$={ArrowUp:"\x1B[A",ArrowDown:"\x1B[B",ArrowRight:"\x1B[C",ArrowLeft:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",Insert:"\x1B[2~",Delete:"\x1B[3~",PageUp:"\x1B[5~",PageDown:"\x1B[6~"},X4=e=>{const{key:t,ctrlKey:n,altKey:r,metaKey:s,shiftKey:o}=e;if(s)return null;if(W$(e))return t;if(t==="Enter")return!n&&!o?r?"\x1B\r":"\r":`\x1B[13;${1+(o?1:0)+(r?2:0)+(n?4:0)}u`;if(t==="Escape")return"\x1B";if(t==="Tab")return o?"\x1B[Z":" ";if(t==="Backspace")return r?"\x1B":"";const i=K$[t];if(i){if(!n&&!r&&!o)return i;const a=1+(o?1:0)+(r?2:0)+(n?4:0),l=i.at(-1);return l==="~"?i.replace("~",`;${a}~`):`\x1B[1;${a}${l}`}if([...t].length!==1)return null;if(n){const a=t.toLowerCase().charCodeAt(0);return a>=97&&a<=122?(r?"\x1B":"")+String.fromCharCode(a-96):t===" "||t==="@"?"\0":t==="["?"\x1B":t==="\\"?"":t==="]"?"":t==="_"||t==="-"?"":null}return r?`\x1B${t}`:t},Wv="\x1B[200~",Kv="\x1B[201~",G$=e=>{const t=e.split(Wv).join("").split(Kv).join("");return`${Wv}${t}${Kv}`},Z$=e=>{let n=e.action==="wheel-up"||e.action==="wheel-down"?e.action==="wheel-up"?64:65:Math.min(Math.max(e.button,0),2);e.action==="drag"&&(n+=32),e.shiftKey&&(n+=4),e.altKey&&(n+=8),e.ctrlKey&&(n+=16);const r=Math.max(0,Math.floor(e.col))+1,s=Math.max(0,Math.floor(e.row))+1;return`\x1B[<${n};${r};${s}${e.action==="release"?"m":"M"}`},Gv=(e,t)=>{const n=[...e],r=[...t];let s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s+=1;return"".repeat(n.length-s)+r.slice(s).join("").replace(/\r?\n/g,"\r")},Y$=256,q1=64*1024,ju=bb,Dn=new Map,W1=new Set,X$=(e,t)=>e!==void 0&&e.columns===t.columns&&e.screenColumns===t.screenColumns&&e.rows===t.rows,K1=e=>e instanceof at&&e.code==="EXTENSION_SURFACE_NOT_OPEN",Ya=()=>({runtimeKey:Y()}),J4=(e,t,n)=>{Ie.sendExtensionSurface("viewport",{sessionId:e,clientId:ju(),viewport:t,...n?{claim:!0}:{}},Ya()).catch(()=>{Dn.delete(e)})},J$=(e,t)=>{const n=W1.delete(e);!n&&X$(Dn.get(e),t)||(Dn.set(e,t),J4(e,t,n))},Q4=e=>{const t=Dn.get(e);t?J4(e,t,!0):W1.add(e)},Q$=e=>{Dn.delete(e),W1.delete(e)},Xp=new Map,ez=e=>{const t=[];let n=0;for(;e.length>0&&t.length<Y$;){const r=e[0];if(t.length>0&&n+r.length>q1)break;t.push(e.shift()),n+=r.length}return t},tz=async(e,t,n)=>{n.inFlight=!0;try{for(;n.pending.length>0;){const r=ez(n.pending);try{await Ie.sendExtensionSurface("input",{sessionId:e,surfaceId:t,clientId:ju(),...Dn.has(e)?{viewport:Dn.get(e)}:{},items:r},Ya())}catch(s){n.pending.length=0,K1(s)?qe().dropExtensionSurface(e,t):Ce.error("Keys did not reach the extension. Try again.")}}}finally{n.inFlight=!1,Xp.delete(`${e}\0${t}`)}},Ul=(e,t,n)=>{const r=n.filter(i=>i.length>0&&i.length<=q1);if(r.length===0)return;const s=`${e}\0${t}`;let o=Xp.get(s);o||(o={pending:[],inFlight:!1},Xp.set(s,o)),o.pending.push(...r),o.inFlight||tz(e,t,o)},Gi=new Set,nz=256,rz=e=>e.reason==="cancelled"&&!e.surface.parentId&&!Gi.has(`${e.sessionId}\0${e.surface.surfaceId}`),sz=async(e,t)=>{Gi.add(`${e}\0${t}`),Gi.size>nz&&Gi.delete(Gi.values().next().value);try{await Ie.sendExtensionSurface("close",{sessionId:e,surfaceId:t,clientId:ju(),...Dn.has(e)?{viewport:Dn.get(e)}:{}},Ya())}catch(n){if(K1(n)){qe().dropExtensionSurface(e,t);return}Ce.error("Could not close the extension surface. Try again.")}},Zv=async(e,t)=>{try{await Ie.sendExtensionSurface("focus",{sessionId:e,surfaceId:t,clientId:ju(),...Dn.has(e)?{viewport:Dn.get(e)}:{}},Ya())}catch(n){if(K1(n))return;Ce.error("Could not switch to that panel. Try again.")}},bh=new Set,oz=(e,t)=>{const n=`${e}\0${t}`;bh.has(n)||(bh.add(n),Ie.sendExtensionSurface("refresh",{sessionId:e,surfaceId:t},Ya()).catch(()=>{}).finally(()=>bh.delete(n)))},iz=[{label:"Esc",data:"\x1B"},{label:"Tab",data:" "},{label:"Left",data:"\x1B[D",icon:"arrow-left"},{label:"Up",data:"\x1B[A",icon:"arrow-up"},{label:"Down",data:"\x1B[B",icon:"arrow-down"},{label:"Right",data:"\x1B[C",icon:"arrow-right"},{label:"Enter",data:"\r"}],no=" ",e7=({sessionId:e,surfaceId:t,className:n})=>{const r=H.useRef(null),s=H.useRef(""),[o,i]=H.useState(!1),a=u=>{u&&Ul(e,t,[u])},l=()=>{s.current="";const u=r.current;u&&(u.value=no,u.setSelectionRange(no.length,no.length))},d=u=>{const h=u.currentTarget,m=u.nativeEvent.isComposing;if(!h.value.startsWith(no)){a(Gv(s.current,"")+(h.value===""?"":h.value)),l();return}const g=h.value.slice(no.length);a(Gv(s.current,g)),s.current=g,m||l()},f=u=>{if(u.nativeEvent.isComposing||u.key==="Unidentified"||[...u.key].length===1)return;const h=X4(u);h!==null&&(u.preventDefault(),a(h))};return c.jsxs("div",{role:"toolbar","aria-label":"Extension keys",className:R("relative flex items-center gap-0.5 overflow-x-auto",n),children:[iz.map(u=>c.jsx(be,{type:"button",variant:"outline",size:"xs",className:R("shrink-0 font-sans",u.icon?"h-7 w-6 px-0 has-[>svg]:px-0":"h-7 px-1.5"),"aria-label":u.icon?u.label:void 0,onPointerDown:h=>h.preventDefault(),onClick:()=>a(u.data),children:u.icon?c.jsx(V,{name:u.icon,className:"size-3.5"}):u.label},u.label)),c.jsx(be,{type:"button",variant:"chip",size:"xs",className:"ml-auto h-7 shrink-0 px-1.5 font-sans","aria-pressed":o,onPointerDown:u=>u.preventDefault(),onClick:()=>{o?r.current?.blur():r.current?.focus({preventScroll:!0})},children:"Keyboard"}),c.jsx("input",{ref:r,"aria-label":"Type to the extension",className:"pointer-events-none absolute left-0 top-0 size-px opacity-0",defaultValue:no,autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,enterKeyHint:"enter",onFocus:()=>{l(),i(!0)},onBlur:()=>i(!1),onInput:d,onCompositionEnd:l,onKeyDown:f})]})},az=.5,t7=(e,t)=>{const n=[1];return e.width>0&&t.width>0&&n.push(t.width/e.width),e.height&&t.height&&e.height>0&&t.height>0&&n.push(t.height/e.height),Math.max(az,Math.min(...n))},n7=(e,t,n=!0)=>{const[r,s]=H.useState({width:0,height:0,cell:0});return H.useEffect(()=>{const o=e.current;if(!o)return;const i=()=>{const l=o.clientWidth,d=o.clientHeight,f=(t.current?.getBoundingClientRect().width??0)/10;s(u=>u.width===l&&u.height===d&&u.cell===f?u:{width:l,height:d,cell:f})};i();const a=new ResizeObserver(i);return a.observe(o),()=>a.disconnect()},[e,t,n]),r},Ti=(e,t,n,r)=>({col:Math.min(Math.max(Math.floor((n-t.left)/Math.max(e.cellWidth,1)),0),Math.max(e.columns-1,0)),row:Math.min(Math.max(Math.floor((r-t.top)/e.lineHeight),0),Math.max(e.rows-1,0))}),Rd=5,cz=10,lz=(e,t,n,r)=>{const s=e.deltaMode===1?e.deltaY:e.deltaMode===2?e.deltaY*r:e.deltaY/n,o=t+s,i=Math.trunc(o);return{steps:Math.max(-Rd,Math.min(Rd,i)),rest:i===0?o:0}},wh={shiftKey:!1,altKey:!1,ctrlKey:!1},dz=e=>{const t=H.useRef(e);t.current=e;const n=H.useRef(null),r=H.useRef(0),s=(x,b,S,y)=>{t.current.send(Z$({action:x,button:b,...S,shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.ctrlKey}))},o=(x,b,S)=>{for(let y=0;y<Math.abs(x);y+=1)s(x<0?"wheel-up":"wheel-down",0,b,S)},i=()=>({columns:t.current.columns,rows:t.current.rows,cellWidth:t.current.measureCell(),lineHeight:t.current.lineHeight}),a=()=>t.current.rows===0||t.current.columns===0,l=x=>x.target instanceof Element&&x.target.closest("a[href]")!==null,d=x=>!x.shiftKey&&x.button<=2&&!a()&&!l(x),f=x=>{const b=t.current.ref.current;if(!b||n.current)return;if(x.pointerType==="touch"){if(a()||l(x))return;const w=b.getBoundingClientRect();n.current={kind:"touch",pointerId:x.pointerId,startX:x.clientX,startY:x.clientY,lastY:x.clientY,swiping:!1,rest:0,cell:Ti(i(),{left:w.left,top:w.top},x.clientX,x.clientY)};return}if(!d(x))return;const S=b.getBoundingClientRect(),y={left:S.left,top:S.top},v=i(),C=Ti(v,y,x.clientX,x.clientY);n.current={kind:"mouse",pointerId:x.pointerId,button:x.button,...C,grid:v,origin:y},b.setPointerCapture?.(x.pointerId),t.current.onPress?.(),s("press",x.button,C,x)},u=x=>{const b=n.current;if(!b||b.pointerId!==x.pointerId)return;if(b.kind==="touch"){if(!b.swiping){if(Math.hypot(x.clientX-b.startX,x.clientY-b.startY)<cz)return;if(t.current.nativeTouchScroll){n.current=null;return}b.swiping=!0}const y=b.rest+b.lastY-x.clientY;b.lastY=x.clientY;const v=Math.trunc(y/t.current.lineHeight);b.rest=y-v*t.current.lineHeight,o(Math.max(-Rd,Math.min(Rd,v)),b.cell,wh);return}const S=Ti(b.grid,b.origin,x.clientX,x.clientY);S.col===b.col&&S.row===b.row||(b.col=S.col,b.row=S.row,s("drag",b.button,S,x))},h=x=>{const b=n.current;if(!b||b.pointerId!==x.pointerId)return;if(n.current=null,b.kind==="touch"){if(x.type!=="pointerup"||b.swiping)return;t.current.onPress?.(),s("press",0,b.cell,wh),s("release",0,b.cell,wh);return}const S=x.type==="pointercancel"?b:Ti(b.grid,b.origin,x.clientX,x.clientY);s("release",b.button,{col:S.col,row:S.row},x)},m=x=>{d(x)&&x.preventDefault()},g=H.useRef({wheel:o,grid:i,empty:a});return g.current={wheel:o,grid:i,empty:a},H.useEffect(()=>{const x=e.ref.current;if(!x)return;const b=S=>{const{wheel:y,grid:v,empty:C}=g.current;if(S.shiftKey||S.deltaY===0||C())return;S.preventDefault();const{steps:w,rest:I}=lz(S,r.current,t.current.lineHeight,t.current.rows);if(r.current=I,w===0)return;const E=x.getBoundingClientRect();y(w,Ti(v(),{left:E.left,top:E.top},S.clientX,S.clientY),S)};return x.addEventListener("wheel",b,{passive:!1}),()=>x.removeEventListener("wheel",b)},[e.ref]),{onPointerDown:f,onPointerMove:u,onPointerUp:h,onPointerCancel:h,onMouseDown:m,touchAction:e.nativeTouchScroll?"pan-y":"none"}},uz="▀",fz="▄",hz="█",pz=/[▀▄█]/,mz=/^([▀▄█])\1*$/,gz=/([▀▄█])\1*|[^▀▄█]+/g,yz=e=>pz.test(e),r7=e=>mz.test(e),vz=e=>(e.match(gz)??[]).map(t=>({text:t,block:r7(t)})),Yv=(e,t,n)=>{const{color:r,backgroundColor:s,...o}=t??{},i=String(r??"var(--foreground)"),a=String(s??"transparent"),l=e[0];return{...o,display:"inline-block",width:`${e.length}ch`,height:n,verticalAlign:"top",color:"transparent",backgroundColor:l===hz?i:a,backgroundImage:l===uz?`linear-gradient(${i} 50%, ${a} 50%)`:l===fz?`linear-gradient(${a} 50%, ${i} 50%)`:"none"}},Ft=18,Ko=12,xz=24,s7=3,Go="font-mono text-[13px] leading-[18px] [font-variant-ligatures:none]",o7=[],i7=e=>Be(t=>e?t.reducer.bySession.get(e)?.extensionSurfaces:void 0,Object.is,e?`session:${e}`:"*",e??""),a7=e=>{const t=i7(e);return H.useMemo(()=>t?[...t.values()].sort((n,r)=>n.z-r.z):o7,[t])},bz=e=>Be(t=>{const n=t.reducer.bySession.get(e);return n?.lifecycle==="busy"&&!n.runningCommand||n?.lifecycle==="retry"},Object.is,`session:${e}`,e),al=e=>{document.querySelector(`[data-extension-surface="${CSS.escape(e)}"]`)?.focus({preventScroll:!0})},Jp=()=>{requestAnimationFrame(()=>{const e=document.activeElement;e&&e!==document.body&&!e.closest('[aria-hidden="true"]')||document.querySelector('[data-chat-input="true"] [contenteditable="true"], .chat-input-column textarea')?.focus()})},Sh=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null,c7=H.memo(({line:e,cells:t})=>{if(e==="")return" ";const n=t&&Sh?t:void 0;if(!n&&!yz(e))return c.jsx(qt,{text:e,links:!0});let r=0;return c.jsx(c.Fragment,{children:U4(e).map((s,o)=>{const i=Nd(s),a=$4(s.href);if(!a&&r7(s.text))return r+=s.text.length,c.jsx("span",{style:Yv(s.text,i,Ft),children:s.text},o);const l=[],d=f=>{for(const u of vz(f))l.push(u.block?c.jsx("span",{style:Yv(u.text,i,Ft),children:u.text},`block-${l.length}`):u.text)};if(!n||!Sh)d(s.text);else{let f="";for(const{segment:u}of Sh.segment(s.text)){const h=n[r++]??1;if(h===1){f+=u;continue}f&&d(f),f="",l.push(c.jsx("span",{className:"inline-block overflow-hidden text-center align-top",style:{width:`${h}ch`,height:Ft},children:h===0?null:u},r))}f&&d(f)}return a?c.jsx(Y4,{segment:s,href:a,children:l},o):c.jsx("span",{style:i,children:l},o)})})});c7.displayName="CellLine";const l7=({sessionId:e,surface:t,nativeTouchScroll:n=!1,scale:r=1,zoomSelf:s=!1})=>{const o=H.useRef(null),i=H.useRef(null),a=t.frame,l=t.capturing||t.focused,d=dz({ref:o,measureCell:()=>(i.current?.getBoundingClientRect().width??0)/10,columns:a?.columns??0,rows:a?.lines.length??0,lineHeight:Ft*r,nativeTouchScroll:n,send:h=>Ul(e,t.surfaceId,[h]),onPress:()=>{l&&o.current?.focus({preventScroll:!0})}});H.useEffect(()=>{!t.focused||!l||!o.current||o.current.contains(document.activeElement)||document.activeElement?.closest("[data-extension-tabs]")||o.current.focus({preventScroll:!0})},[t.focused,l]);const f=h=>{if(h.nativeEvent.isComposing)return;const m=h.metaKey||h.ctrlKey;if(m&&h.key.toLowerCase()==="c"&&(window.getSelection()?.toString()??"")!==""||m&&h.key.toLowerCase()==="v")return;const g=X4(h);g!==null&&(h.preventDefault(),h.stopPropagation(),Ul(e,t.surfaceId,[g]))},u=h=>{const m=h.clipboardData.getData("text/plain");if(!m)return;h.preventDefault();const g=G$(m);if(g.length>q1){Ce.error("That paste is too long for the extension (64 KB at most).");return}Ul(e,t.surfaceId,[g])};return c.jsxs("div",{ref:o,"data-extension-surface":t.surfaceId,role:"application","aria-label":`Extension: ${t.title}`,tabIndex:l?0:-1,onKeyDown:l?f:void 0,onPaste:l?u:void 0,onPointerDown:h=>{Q4(e),d.onPointerDown(h)},onPointerMove:d.onPointerMove,onPointerUp:d.onPointerUp,onPointerCancel:d.onPointerCancel,onMouseDown:d.onMouseDown,style:{touchAction:d.touchAction,...s&&r!==1?{zoom:r}:{}},className:R("relative whitespace-pre text-foreground outline-none",Go),children:[c.jsx("span",{ref:i,"aria-hidden":!0,className:"invisible absolute left-0 top-0",children:"0000000000"}),(a?.lines??[]).map((h,m)=>c.jsx("div",{style:{height:Ft},children:c.jsx(c7,{line:h,cells:a?.cells[m]})},m)),a?.cursor&&t.focused?c.jsx("span",{"aria-hidden":!0,className:"pointer-events-none absolute bg-foreground/70",style:{left:`${a.cursor.col}ch`,top:a.cursor.row*Ft+1,width:"1ch",height:Ft-2}}):null]})},G1=({sessionId:e,surface:t})=>c.jsx(be,{type:"button",variant:"ghost",size:"xs",className:"size-6 shrink-0 px-0 text-muted-foreground hover:text-foreground","aria-label":`Close ${t.title}`,title:"Close",onClick:()=>{sz(e,t.surfaceId)},children:c.jsx(V,{name:"close",className:"size-3.5"})}),wz=(e,t)=>{const n=t.filter(r=>r.stale).map(r=>r.surfaceId).join("\0");H.useEffect(()=>{if(n)for(const r of n.split("\0"))oz(e,r)},[e,n])},Sz=({sessionId:e})=>{const t=H.useRef(null),n=H.useRef(null),r=On().hasTouchOnlyPointer?s7:0;return H.useEffect(()=>{const s=t.current;if(!s)return;const o=s.closest("[data-composer-bound]"),i=()=>{const l=(n.current?.getBoundingClientRect().width??0)/10;!(l>0)||!o||J$(e,{columns:Math.floor(s.clientWidth/l),screenColumns:Math.floor((o.clientWidth-2*Ko)/l),rows:Math.max(1,Math.floor((o.clientHeight-2*Ko)/Ft)-r)})};Q$(e),i();const a=new ResizeObserver(i);return a.observe(s),o&&a.observe(o),()=>a.disconnect()},[e,r]),c.jsx("div",{"aria-hidden":!0,className:"chat-input-column pointer-events-none absolute inset-x-0 top-0 h-0 overflow-hidden",children:c.jsx("div",{className:"mx-px px-3",children:c.jsx("div",{ref:t,className:"relative w-full",children:c.jsx("span",{ref:n,className:R("invisible absolute",Go),children:"0000000000"})})})})},Cz=e=>{const[t,n]=H.useState(!1);return H.useEffect(()=>{const r=e.current;if(!r)return;const s=()=>n(r.scrollHeight>r.clientHeight+1);s();const o=new ResizeObserver(s);return o.observe(r),r.firstElementChild&&o.observe(r.firstElementChild),()=>o.disconnect()},[e]),t},kz=(e,t)=>{const[n,r]=H.useState(void 0);return H.useLayoutEffect(()=>{const s=e.current,o=t.current,i=s?.closest("[data-composer-bound]");if(!s||!o||!i)return;const a=()=>{const d=s.offsetHeight-o.offsetHeight,f=s.parentElement,u=f&&Number.parseFloat(getComputedStyle(f).paddingBottom)||0;r(Math.max(4*Ft,Math.floor(i.clientHeight-d-u-Ko)))};a();const l=new ResizeObserver(a);return l.observe(i),l.observe(s),()=>l.disconnect()},[e,t]),n},Mz=({sessionId:e,surface:t,below:n})=>{const r=bz(e),{hasTouchOnlyPointer:s}=On(),o=H.useRef(null),i=H.useRef(null),a=H.useRef(null),l=kz(o,i),d=Cz(i),f=n7(i,a),u=f.cell>0&&t.frame?t7({width:t.frame.columns*f.cell},{width:f.width-xz}):1;return c.jsx("div",{className:"chat-input-column pb-3",children:c.jsxs("div",{ref:o,role:"dialog","aria-label":`Extension: ${t.title}`,className:"pi-surface-rise overflow-hidden rounded-xl border border-border/80 bg-card shadow-md",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/40 px-3 py-1.5",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx(V,{name:"plug-2",className:"size-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"shrink-0 typography-ui-label font-medium text-foreground",children:t.title}),t.blocked?.message?c.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:t.blocked.message}):null,n>0?c.jsx("span",{className:"shrink-0 rounded-full bg-muted px-2 py-0.5 typography-micro text-muted-foreground",children:n===1?"1 more below":`${n} more below`}):null]}),c.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[r?c.jsxs(be,{type:"button",variant:"ghost",size:"xs",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>Qm(e),children:[c.jsx(V,{name:"stop",className:"size-3.5"}),"Stop"]}):null,c.jsx(G1,{sessionId:e,surface:t})]})]}),c.jsxs("div",{ref:i,className:"relative overflow-auto px-3 py-2",style:{maxHeight:l??"60vh"},children:[c.jsx(l7,{sessionId:e,surface:t,nativeTouchScroll:d,scale:u,zoomSelf:!0}),c.jsx("span",{ref:a,"aria-hidden":!0,className:R("invisible absolute left-0 top-0",Go),children:"0000000000"})]}),s&&t.capturing?c.jsx(e7,{sessionId:e,surfaceId:t.surfaceId,className:"border-t border-border/40 px-3 py-1.5"}):c.jsx("div",{className:"border-t border-border/40 px-3 py-1.5 typography-micro text-muted-foreground",children:"Keys go to the extension. Your draft is kept when it closes."})]})})},Iz=({sessionId:e,surfaces:t})=>{const n=uu(e)!==null;return t.length===0?null:c.jsx("div",{className:"chat-input-column mb-2 flex flex-col gap-1",children:t.map(r=>c.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg bg-[var(--surface-muted)] px-3 py-1",children:[c.jsxs("span",{className:"min-w-0 typography-meta text-muted-foreground [text-wrap:pretty]",children:[r.hidden?`${r.title} is hidden by the extension.`:`${r.title} is hidden because the screen is too narrow.`,n?" New messages wait until it closes.":null]}),c.jsx(G1,{sessionId:e,surface:r})]},r.surfaceId))})},Ez=e=>{H.useEffect(()=>{if(e)return qe().subscribeExtensionSurfaceDismissals(t=>{t.sessionId!==e||!rz(t)||Ce.info(`${t.surface.title} was closed on another device.`,{id:`extension-surface-closed:${t.surface.surfaceId}`})})},[e])},Xv=({sessionId:e,children:t})=>{Ez(e);const n=a7(e),r=n.filter(f=>f.mode==="inline"&&!f.hidden),s=r.at(-1)??null,o=n.filter(f=>f.mode==="overlay"&&!f.parentId&&(f.hidden||f.frame?.visible===!1)),[i,a]=H.useState(!1),[l,d]=H.useState({sessionId:e,hasTop:!!s});return(l.sessionId!==e||l.hasTop!==!!s)&&(d({sessionId:e,hasTop:!!s}),l.sessionId===e&&!s&&a(!0)),H.useEffect(()=>{i&&Jp()},[i]),wz(e??"",e?n:o7),c.jsxs(c.Fragment,{children:[e&&n.length>0?c.jsx(Sz,{sessionId:e}):null,e?c.jsx(Iz,{sessionId:e,surfaces:o}):null,e&&s?c.jsx(Mz,{sessionId:e,surface:s,below:r.length-1},s.surfaceId):null,c.jsx("div",{hidden:!!s,className:i&&!s?"pi-surface-fade":void 0,onAnimationEnd:f=>{f.target===f.currentTarget&&a(!1)},children:t})]})},Jv=8,_z=2,xo=5,jz=28-Ko,Z1="rounded-lg border border-border/80 bg-card shadow-md",d7=({sessionId:e,surface:t,scale:n})=>{const r=t.frame?.layout??{width:40,height:1};return c.jsx("div",{className:R(Z1,"max-w-full p-1"),style:n!==1?{zoom:n}:void 0,children:c.jsx("div",{className:"relative overflow-hidden",style:{width:`${r.width}ch`,maxWidth:"100%",height:r.height*Ft},children:c.jsx(l7,{sessionId:e,surface:t,scale:n})})})},u7=e=>({left:`max(0px, min(${e.col}ch, 100% - ${e.width}ch - ${2*xo}px))`,top:`max(0px, min(${e.row*Ft}px, 100% - ${e.height*Ft+2*xo}px))`,maxWidth:"100%"}),Tz=({sessionId:e,title:t,members:n,front:r,anchor:s,onPicked:o,scaleFor:i})=>{const a=r.frame?.layout??{width:40,height:1},l={row:s.row,col:s.col,width:a.width,height:a.height},d=n.length>1,f=Math.min(_z,n.length-1),u=l.row<3;return c.jsxs("div",{role:"group","aria-label":`${t} panels`,className:R("absolute isolate pointer-events-auto",Go),style:u7(l),children:[d?c.jsx("div",{role:"tablist","aria-label":`${t} panels`,"data-extension-tabs":!0,onKeyDown:h=>{const m=n.findIndex(x=>x.surfaceId===r.surfaceId),g=h.key==="ArrowRight"?(m+1)%n.length:h.key==="ArrowLeft"?(m-1+n.length)%n.length:h.key==="Home"?0:h.key==="End"?n.length-1:null;g!==null&&(h.preventDefault(),h.currentTarget.querySelectorAll('[role="tab"]')[g]?.focus(),g!==m&&Zv(e,n[g].surfaceId))},className:"absolute left-0 flex max-w-[calc(100vw-2rem)] items-center gap-1 overflow-x-auto rounded-md bg-card p-0.5 font-sans",style:u?{top:"calc(100% + 4px)"}:{bottom:`calc(100% + ${f*Jv+4}px)`},children:n.map((h,m)=>{const g=h.surfaceId===r.surfaceId;return c.jsx(be,{type:"button",variant:"chip",size:"xs",role:"tab","aria-selected":g,tabIndex:g?0:-1,className:R("shrink-0",g&&"bg-interactive-selection text-interactive-selection-foreground"),onMouseDown:x=>x.preventDefault(),onClick:()=>{o(),(!g||!h.focused)&&Zv(e,h.surfaceId)},children:Hv(h,m)},h.surfaceId)})}):null,Array.from({length:f},(h,m)=>{const g=m+1;return c.jsx("div",{"aria-hidden":!0,className:R("absolute inset-0",Z1),style:{zIndex:-g,transform:`translateY(-${g*Jv}px) scale(${1-g*.04})`,transformOrigin:"top center"}},g)}),c.jsx("div",{role:d?"tabpanel":"dialog","aria-label":`Extension: ${t}, ${Hv(r,n.indexOf(r))}`,className:"pi-surface-pop",children:c.jsx(d7,{sessionId:e,surface:r,scale:i(r)})},r.surfaceId)]})},Az=e=>{const[t,n]=H.useState(FV),r=BV(t,e);return r!==t&&n(r),r},Nz=e=>{const[t,n]=H.useState(e),[r,s]=H.useState([]);if(t!==e){const i=new Set(e.map(l=>l.surfaceId)),a=t.filter(l=>!i.has(l.surfaceId));n(e),(a.length>0||r.some(l=>i.has(l.surfaceId)))&&s([...r.filter(l=>!i.has(l.surfaceId)),...a])}const o=H.useCallback(i=>{s(a=>a.filter(l=>l.surfaceId!==i))},[]);return{leaving:r,finish:o}},Qv=({sessionId:e})=>{const t=i7(e),n=a7(e),r=H.useMemo(()=>n.filter(q4),[n]),s=H.useMemo(()=>HV(r,t?[...t.keys()]:[]),[r,t]),o=Az(s),i=H.useMemo(()=>s.flatMap(M=>{const L=o.get(M.parentId);return L?[{...M,anchor:L}]:[]}),[s,o]),a=H.useMemo(()=>new Set(i.flatMap(M=>M.members.map(L=>L.surfaceId))),[i]),{leaving:l,finish:d}=Nz(r),f=H.useRef(new Set),u=l.filter(M=>!f.current.has(M.surfaceId)),h=l.filter(M=>f.current.has(M.surfaceId)).map(M=>M.surfaceId).join("\0");H.useEffect(()=>{f.current=a},[a]),H.useEffect(()=>{if(h)for(const M of h.split("\0"))d(M)},[h,d]);const m=r.filter(M=>M.capturing).at(-1)?.surfaceId??null,g=H.useRef(!1);H.useEffect(()=>{m?g.current=!0:g.current&&(g.current=!1,Jp())},[m]);const x=(r.find(M=>M.capturing&&M.focused)??r.filter(M=>M.capturing).at(-1))?.surfaceId??null,b=H.useRef(null),{hasTouchOnlyPointer:S}=On(),y=H.useRef(null),v=H.useRef(null),C=n7(y,v,r.length>0||u.length>0),w=M=>{const L=M.frame?.layout;return!L||!(C.cell>0)?1:t7({width:L.width*C.cell+2*xo,height:L.height*Ft+2*xo},{width:C.width,height:C.height})};H.useEffect(()=>{const M=b.current,L=M?.closest("[data-composer-bound]");if(!x||!M||!L)return;const O=U=>U instanceof Element&&U.closest("[data-extension-prompt-dock]")!==null,N=()=>{O(document.activeElement)||document.activeElement?.closest("[data-extension-tabs]")||al(x)},D=requestAnimationFrame(N);let W=null;const z=()=>{W?.disconnect(),W=null},X=()=>{W||(W=new MutationObserver(()=>{const U=document.activeElement;U&&U!==document.body&&U.isConnected||(z(),N())}),W.observe(L,{childList:!0,subtree:!0}))},F=U=>{const P=U.target;if(!(P instanceof Node)||!L.contains(P)||M.contains(P)){z();return}if(O(P)){X();return}z(),N()};return O(document.activeElement)&&X(),document.addEventListener("focusin",F,!0),()=>{cancelAnimationFrame(D),z(),document.removeEventListener("focusin",F,!0)}},[x]);const I=x?null:r.find(M=>!M.capturing&&M.focused)?.surfaceId??null,E=H.useRef(null);if(H.useEffect(()=>{const M=E.current;E.current=I,!(I||!M)&&(document.activeElement?.getAttribute("data-extension-surface")===M&&document.activeElement.blur(),Jp())},[I]),H.useEffect(()=>{const M=b.current,L=M?.closest("[data-composer-bound]");if(!I||!M||!L)return;let O=!1;const N=W=>{W.target instanceof Node&&!M.contains(W.target)&&(O=!0)},D=W=>{const z=W.target;O||!(z instanceof Node)||!L.contains(z)||M.contains(z)||z instanceof Element&&z.closest("[data-extension-prompt-dock]")||al(I)};return document.addEventListener("pointerdown",N,!0),document.addEventListener("focusin",D,!0),()=>{document.removeEventListener("pointerdown",N,!0),document.removeEventListener("focusin",D,!0)}},[I]),!e||r.length===0&&u.length===0)return null;const T=r.filter(M=>M.capturing).at(-1)??null,A=x??I,j=S&&A!==null,k=C.height-(j?s7*Ft:0),_=[...r.map(M=>({surface:M,isLeaving:!1})),...u.map(M=>({surface:{...M,focused:!1,capturing:!1},isLeaving:!0}))];return c.jsxs("div",{ref:b,className:"pointer-events-none absolute inset-0 z-30",children:[T?c.jsx("div",{"aria-hidden":!0,className:"pi-surface-fade pointer-events-auto absolute inset-0 bg-background/60",onMouseDown:M=>{M.preventDefault(),Q4(e),x&&al(x)}}):null,c.jsx("div",{className:"absolute inset-0",style:{padding:Ko},children:c.jsxs("div",{ref:y,className:"relative h-full",children:[c.jsx("span",{ref:v,"aria-hidden":!0,className:R("invisible absolute left-0 top-0",Go),children:"0000000000"}),_.map(({surface:M,isLeaving:L})=>{const O=M.frame?.layout??{row:0,col:0,width:40,height:1};if(!L&&a.has(M.surfaceId)){const N=i.find(W=>W.members.includes(M));if(!N||N.members.some(W=>W.z>M.z))return null;const D=t?.get(N.parentId)?.title??M.title;return c.jsx(Tz,{sessionId:e,title:D,members:N.members,front:N.front,anchor:N.anchor,onPicked:()=>{x&&al(x)},scaleFor:w},`stack-${N.parentId}`)}return c.jsxs("div",{role:"dialog","aria-label":`Extension: ${M.title}`,"aria-hidden":L||void 0,className:R("absolute",Go,L?"pi-surface-out pointer-events-none":"pi-surface-pop pointer-events-auto"),style:u7(O),onAnimationEnd:L?N=>{N.target===N.currentTarget&&d(M.surfaceId)}:void 0,children:[M.parentId?null:c.jsxs("div",{className:R("absolute flex items-center gap-0.5 rounded-md bg-card pl-2 font-sans",{above:"right-0 -top-7",below:"right-0 -bottom-7",inside:"right-1 top-1 z-10 shadow-sm"}[VV({top:O.row*Ft,layoutHeight:O.height*Ft+2*xo,height:(O.height*Ft+2*xo)*w(M)},k,jz)]),children:[c.jsx("span",{className:"typography-micro text-muted-foreground",children:M.title}),c.jsx(G1,{sessionId:e,surface:M})]}),c.jsx(d7,{sessionId:e,surface:M,scale:w(M)})]},M.surfaceId)})]})}),j&&A?c.jsx("div",{className:"pointer-events-auto absolute inset-x-0 bottom-0 flex justify-center",style:{padding:Ko},children:c.jsx(e7,{sessionId:e,surfaceId:A,className:R(Z1,"max-w-full p-1")})}):null]})},Lz=({isNewSession:e=!1})=>{const{currentTheme:t}=vr(),n=t?.colors?.surface?.mutedForeground||"var(--muted-foreground)";return c.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[c.jsx(a1,{width:120,height:120,isAnimated:!e,className:e?"opacity-20":void 0}),e?c.jsx("span",{className:"text-body-md",style:{color:n},children:"Start a new chat"}):null]})},Rz=p.memo(Lz),Y1=2,f7=2,Pz=72,Dz=(e,t=Y1)=>t+Math.max(0,e),Oz=(e,t,n,r=Y1)=>{const s=Dz(n,r);return t<=s?!1:e<t-s},Hz=(e,t,n=Y1)=>Math.max(0,t-n-e),Fz=(e,t,n=f7)=>e+Math.max(0,Math.min(n,t)),Bz=({foldedCount:e,onLoadOlder:t,onLoadAll:n})=>{const r=Math.min(f7,e),s=e>r;return c.jsx("div",{className:"chat-message-column flex flex-col items-center py-4",children:c.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[c.jsxs(be,{type:"button",variant:"secondary",size:"sm",onClick:t,"aria-label":"Load older history",className:"gap-1.5 rounded-full px-3.5",children:[c.jsx(V,{name:"history",className:"size-3.5"}),"Load older history"]}),s?c.jsx(be,{type:"button",variant:"ghost",size:"sm",onClick:n,"aria-label":"Load all history",className:"rounded-full px-3.5 text-[var(--surface-mutedForeground)]",children:"Load all history"}):null]})})},Vz=p.memo(Bz),h7="The following tool was executed by the user",X1=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},$z=e=>{const t=e.info;return typeof t.parentID=="string"&&t.parentID.length>0?t.parentID:null},p7=e=>!e||X1(e)!=="user"?!1:e.parts.some(t=>{if(t?.type!=="text")return!1;const n=t.text;return t.synthetic===!0&&typeof n=="string"&&n.trim().startsWith(h7)}),m7=(e,t)=>{if(X1(e)!=="assistant")return{hide:!1,details:null};if(t&&$z(e)!==t)return{hide:!1,details:null};if(e.parts.length!==1)return{hide:!1,details:null};const n=e.parts[0];if(n?.type!=="tool")return{hide:!1,details:null};if((typeof n.tool=="string"?n.tool.toLowerCase():"")!=="bash")return{hide:!1,details:null};const s=typeof n.state?.input?.command=="string"?n.state.input.command:void 0,o=(typeof n.state?.output=="string"?n.state.output:void 0)??(typeof n.state?.metadata?.output=="string"?n.state.metadata.output:void 0),i=typeof n.state?.status=="string"?n.state.status:void 0;return{hide:!0,details:{command:s,output:o,status:i}}},zz=(e,t)=>{const n=e[t];if(!n)return null;const r=n.info.id;for(let s=t+1;s<e.length;s+=1){const o=e[s];if(X1(o)==="user")break;const{hide:i,details:a}=m7(o,r);if(i){const l=typeof a?.command=="string"?a.command.trim():"";return l.length>0?l:null}}return null},Ps=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},Uz=e=>e.info.error?.name==="SessionRetry",qz=e=>{const t=e.text;if(typeof t=="string")return t;const n=e.content;return typeof n=="string"?n:""},Wz=e=>{if(!e)return null;const t=e.info.id;return typeof t=="string"&&t.trim().length>0?t:null},Kz=e=>{const t=e.info.parentID;return typeof t=="string"&&t.trim().length>0?t:null},Gz=(e,t)=>{if(Ps(e)!=="system")return e;const r=Kz(e);return!r||!t.has(r)||e.info.clientRole==="assistant"?e:{...e,info:{...e.info,clientRole:"assistant"}}},Zz=e=>!e||Ps(e)!=="user"?!1:e.parts.some(t=>t?.type==="subtask"),Yz=e=>{const t=e,n=t.state?.metadata,r=(typeof n?.sessionID=="string"&&n.sessionID.trim().length>0?n.sessionID.trim():null)??(typeof n?.sessionId=="string"&&n.sessionId.trim().length>0?n.sessionId.trim():null);if(r)return r;const s=t.state?.output;if(typeof s=="string"){const o=s.match(/task_id\s*:\s*([^\s<"']+)/i);if(o?.[1])return o[1]}return null},Xz=e=>{if(Ps(e)!=="assistant")return{hide:!1,taskSessionId:null};if(e.parts.length!==1)return{hide:!1,taskSessionId:null};const t=e.parts[0];return t?.type!=="tool"?{hide:!1,taskSessionId:null}:(typeof t.tool=="string"?t.tool.toLowerCase():"")!=="task"?{hide:!1,taskSessionId:null}:{hide:!0,taskSessionId:Yz(e.parts[0])}},Jz=(e,t)=>{if(!t)return e;const n=e.parts.map(r=>{if(r?.type!=="subtask")return r;const s=r.taskSessionID;return typeof s=="string"&&s.trim().length>0?r:{...r,taskSessionID:t}});return{...e,parts:n}},Qz=(e,t)=>{const n=typeof t?.command=="string"?t.command.trim():"",r=typeof t?.output=="string"?t.output:"",s=typeof t?.status=="string"?t.status.trim():"",o=[];let i=!1;for(const a of e.parts){if(!i&&a?.type==="text"){const l=a.text;if(a.synthetic===!0&&typeof l=="string"&&l.trim().startsWith(h7)){o.push({type:"text",text:"/shell",shellAction:{...n?{command:n}:{},...r?{output:r}:{},...s?{status:s}:{}}}),i=!0;continue}}o.push(a)}return i||o.push({type:"text",text:"/shell",shellAction:{...n?{command:n}:{},...r?{output:r}:{},...s?{status:s}:{}}}),{...e,parts:o}},Ch=(e,t)=>t?e.userMessage.info.id===t?!0:e.assistantMessages.some(n=>n.info.id===t):!1,eU=40,tU=40,nU=(e,t)=>{const n=e.reduce((a,l)=>a+(l.kind==="tool"?1:0),0),r=Math.max(0,t),s=Math.max(0,n-r);if(s===0)return{activities:e,hiddenToolCount:0};let o=s,i=0;for(let a=0;a<e.length&&!(e[a]?.kind==="tool"&&(o-=1,i=a+1,o===0));a+=1);return{activities:e.slice(i),hiddenToolCount:s}},rU=(e,t,n,r)=>n&&!r&&e.length>t.length?e:t,J1=({text:e,isStreaming:t,identityKey:n,allowTextReplacement:r=!1})=>{const s=p.useRef(n),o=p.useRef(e);if(s.current!==n)return s.current=n,o.current=e,e;if(!t)return o.current=e,e;const i=rU(o.current,e,!0,r);return o.current=i,i},sU=e=>e.isStreaming?e.throttledTextContent:e.textContent,oU=e=>!e.isFinalized&&e.displayTextContent.trim().length===0?!1:e.displayTextContent.trim().length>0,iU=({part:e,messageId:t,streamPhase:n,onShowPopup:r,withinActivityRail:s=!1})=>{const o=e,i=typeof o.text=="string"?o.text:"",a=typeof o.content=="string"?o.content:"",l=typeof o.value=="string"?o.value:"",d=[i,a,l].reduce((y,v)=>v.length>y.length?v:y,""),h=n==="streaming"||n==="cooldown";_s("ui.assistant_text_part.render"),h&&_s("ui.assistant_text_part.render.streaming");const m=J1({text:d,isStreaming:h,identityKey:`${t}:${e.id??"text"}`}),g=sU({textContent:d,throttledTextContent:m,isStreaming:h});CC("ui.assistant_text_part.display_len",g.length);const x=o.time,b=!!(x&&typeof x.end<"u");return!(e.type==="text"||e.type==="reasoning")||!oU({displayTextContent:g,isFinalized:b})?null:c.jsx("div",{className:R("group/assistant-text relative w-full min-w-0 break-words",s?"py-1":"pt-3 pb-1"),"data-chat-activity-text":s?"true":void 0,"data-chat-assistant-text":"true",children:c.jsx(qo,{content:g,part:e,messageId:t,isAnimated:!1,isStreaming:h,variant:e.type==="reasoning"?"reasoning":"assistant",enableFileReferences:b,onShowPopup:r})},e.id||`${t}-text`)},g7=p.memo(iU),ex=300*1e3,Pd=({active:e,minDurationMs:t=300,className:n,children:r,style:s,title:o})=>{const i=p.useRef(e?Date.now():null),[a,l]=p.useState(e),d=p.useRef(null);e&&i.current===null&&(i.current=Date.now()),p.useEffect(()=>{if(e){if(d.current!==null&&(clearTimeout(d.current),d.current=null),i.current===null&&(i.current=Date.now()),Date.now()-i.current>=ex){l(!1),i.current=null;return}l(!0);return}if(!a){i.current=null;return}const u=i.current??Date.now(),h=Date.now()-u;if(h>=ex){l(!1),i.current=null;return}const m=Math.max(0,t-h);return d.current=setTimeout(()=>{l(!1),i.current=null,d.current=null},m),()=>{d.current!==null&&(clearTimeout(d.current),d.current=null)}},[e,t,a]);const f=p.useMemo(()=>{if(!a)return s;if(!s)return;const u={...s};return delete u.color,u},[a,s]);return c.jsxs("span",{className:R("transition-opacity duration-200",a&&"oc-shimmer-verb",n),style:f,title:o,children:[r,a&&typeof r=="string"?c.jsx(j3,{text:r}):null]})},aU="!text-[length:var(--text-markdown)] !leading-5 tracking-normal",Gr=R("typography-markdown font-medium",aU),Mt=R("typography-code font-mono","!text-[length:var(--text-code)] !leading-5 tracking-normal"),Qp={...kC.getCollapsedStyles(),padding:0,overflow:"visible"},tx={style:{background:"transparent",backgroundColor:"transparent"}},y7={color:"var(--status-error)"},v7={color:"var(--tools-icon)"},x7={color:"var(--status-error)"},ti={color:"color-mix(in srgb, var(--tools-title) 72%, var(--tools-description))"},fQ=`
|
|
146
|
+
[data-diff-header],
|
|
147
|
+
[data-diff] {
|
|
148
|
+
[data-separator] {
|
|
149
|
+
height: 24px !important;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
`,hQ={hunkLineCount:50,lineHeight:24,diffHeaderHeight:44,hunkSeparatorHeight:24,spacing:0},cU=e=>typeof e!="string"||e.trim().length===0?"":e.split(`
|
|
153
|
+
`).map(t=>t.replace(/^>\s?/,"").trimEnd()).filter(t=>t.trim().length>0).join(`
|
|
154
|
+
`).trim(),kh=80,lU=40,nx=4e3,dU=200,uU={duration:.2,ease:"easeOut"},b7=e=>e.replace(/<!--\s*-->/g,"").replace(/```[\w]*\n?([\s\S]*?)```/g,(t,n)=>n.trim()).replace(/`([^`]+)`/g,"$1").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/^>\s?/gm,"").replace(/^[-*_]{3,}\s*$/gm,"").trim(),w7=e=>{if(e.length<=kh)return e;const t=e.lastIndexOf(" ",kh),n=t>0?t:kh;return`${e.substring(0,n).trimEnd()}…`},fU=e=>{if(!e)return"";const t=b7(e).replace(/\s+/g," ").trim();return w7(t)},hU=e=>{const t=e.trimEnd();if(!t)return"";const n=t.lastIndexOf(`
|
|
155
|
+
`),r=n===-1?t:t.slice(n+1);return w7(b7(r).replace(/\s+/g," ").trim())},pU=e=>{let t=1,n=0;for(let s=e.length-1;s>=0;s-=1)if(e.charCodeAt(s)===10&&(t+=1,t>lU)){n=s+1;break}const r=n>0?e.slice(n):e;return r.length<=nx?r:r.slice(-nx)},mU=({text:e,variant:t,onContentChange:n,blockId:r,isStreaming:s=!1,actions:o,withinActivityRail:i=!1})=>{const[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=p.useRef(null),h=p.useRef(!0),m=p.useId(),g=p.useRef(s),x=p.useRef(null),b=p.useRef(null),S=p.useRef(!1),y=p.useRef(n);y.current=n;const v=p.useMemo(()=>s?hU(e):fU(e),[s,e]),C=a?"Collapse reasoning trace":"Expand reasoning trace",w=p.useCallback(()=>{f(!0),l(j=>!j),n?.("structural")},[n]),I=p.useCallback(j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),w())},[w]),E=p.useCallback(j=>{j.deltaY<0&&(h.current=!1)},[]),T=p.useCallback(j=>{const k=j.currentTarget;h.current=k.scrollHeight-k.scrollTop-k.clientHeight<=2},[]);if(p.useLayoutEffect(()=>{if(!s||!a){h.current=!0;return}const j=u.current;!j||!h.current||(j.scrollTop=j.scrollHeight)},[a,s,e]),p.useEffect(()=>{if(a){f(!0);return}if(!d)return;if(typeof window>"u"){f(!1);return}const j=window.setTimeout(()=>{f(!1)},dU);return()=>{window.clearTimeout(j)}},[a,d]),p.useLayoutEffect(()=>{const j=x.current;if(!j)return;if(b.current?.stop(),!S.current){S.current=!0,j.style.height=a?"auto":"0px",j.style.overflow=a?"visible":"hidden";return}j.style.overflow="hidden",a?j.style.height="0px":(j.style.height=`${j.scrollHeight}px`,y.current?.("animation"));const k=D8(j,{height:a?"auto":"0px"},uU);return b.current=k,k.finished.then(()=>{b.current===k&&(b.current=null,a?(j.style.overflow="visible",j.style.height="auto"):j.style.overflow="hidden")}).catch(()=>{}),()=>{k.stop(),b.current===k&&(b.current=null)}},[a]),p.useEffect(()=>()=>{b.current?.stop(),b.current=null},[]),!e||e.trim().length===0)return null;const A=c.jsxs(c.Fragment,{children:[c.jsx("div",{"data-message-text-export-source":"true",children:s?c.jsx("div",{className:"markdown-content markdown-reasoning w-full min-w-0 whitespace-pre-wrap break-words",children:pU(e)}):c.jsx(qo,{content:e,messageId:r,isAnimated:!1,isStreaming:!1,variant:"reasoning"})}),o?c.jsx("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5","data-message-actions":"true",children:c.jsx("div",{className:"flex items-center gap-1.5","data-message-action-group":"true",children:o})}):null]});return c.jsxs("div",{"data-reasoning-block-id":r,"data-message-text-export-root":"true",className:g.current?"oc-step-in":void 0,children:[c.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":a,"aria-controls":m,"aria-label":C,className:R("group/tool flex items-center gap-1.5 py-1 pr-2 pl-px cursor-pointer"),"data-chat-activity-row":"true",onClick:w,onKeyDown:I,children:[c.jsxs("div",{className:"flex h-5 items-center gap-1.5 flex-shrink-0",children:[c.jsxs("div",{className:"relative flex h-5 w-3.5 items-center justify-center",children:[c.jsx("div",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",a&&"opacity-0",!a&&"group-hover/tool:opacity-0"),style:{color:"var(--tools-icon)"},children:c.jsx(V,{name:"brain-ai-3",className:"h-3.5 w-3.5"})}),c.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",a&&"opacity-100",!a&&"opacity-0 group-hover/tool:opacity-100"),style:{color:"var(--tools-icon)"},children:a?c.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):c.jsx(V,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),c.jsx(Pd,{active:s,className:R("flex h-5 items-center typography-markdown font-medium text-[length:var(--text-markdown)] leading-none tracking-normal"),style:ti,title:t==="justification"?"Justification":"Thinking",children:t==="justification"?"Justification":"Thinking"})]}),!a&&v?c.jsx("span",{className:R("flex h-5 flex-1 items-center min-w-0 truncate typography-code font-mono text-[length:var(--text-code)] leading-none tracking-normal"),style:{color:"var(--tools-description)",opacity:.8},title:v,children:v}):null]}),d?c.jsx("div",{ref:x,id:m,"aria-hidden":!a,style:{height:a?"auto":"0px",overflow:a?"visible":"hidden",overflowAnchor:"none"},children:c.jsxs("div",{className:R("relative pt-0.5",i?"pl-0 pb-0":"ml-2 pl-3 pb-1"),style:{opacity:a?1:0,transform:a?"translateY(0)":"translateY(-4px)",transition:"opacity 180ms ease-out, transform 180ms ease-out"},children:[i?null:c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),c.jsx(Xn,{ref:u,as:"div",outerClassName:"oc-reasoning-scroll max-h-80 w-full min-w-0",className:"p-0",useScrollShadow:!0,scrollShadowSize:36,userIntentOnly:!0,onWheelCapture:s?E:void 0,onScroll:s?T:void 0,children:A})]})}):null]})},gU=p.memo(({part:e,onContentChange:t,messageId:n,streamPhase:r,withinActivityRail:s=!1})=>{const o=e,i=o.text||o.content||"",a=p.useMemo(()=>cU(i),[i]),l=o.time,f=(r===void 0||r!=="completed")&&o.streaming===!0&&typeof l?.end!="number",u=J1({text:a,isStreaming:f,identityKey:`${n}:${e.id??"reasoning"}`});return!u||u.trim().length===0?null:c.jsx(mU,{text:u,variant:"thinking",onContentChange:t,blockId:e.id||`${n}-reasoning`,time:l,isStreaming:f,withinActivityRail:s})}),rx=[{variant:"static",component:({children:e,className:t,...n})=>c.jsx("span",{...n,className:t,children:e})},{variant:"generate-effect",component:({children:e,className:t,...n})=>{if(e===null||typeof e>"u")return null;const r=typeof e=="string"?e:typeof e=="number"?String(e):Array.isArray(e)?e.map(s=>typeof s=="string"||typeof s=="number"?String(s):"").join(""):"";return r?c.jsx("span",{className:R("inline-block align-baseline",t),children:r.split("").map((s,o)=>H.createElement(Ec.span,{...n,key:s+String(o),className:R("inline-block whitespace-pre align-baseline"),initial:{opacity:0},animate:{opacity:1},transition:{ease:"easeOut",duration:.14,delay:Math.min(o*.0045,.14)}},s))}):null}},{variant:"glitch",component:({children:e,className:t,...n})=>c.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[c.jsx("span",{...n,className:R("invisible",t),children:e}),c.jsx("span",{...n,className:R("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}),c.jsx("span",{...n,className:R("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;const r=.25,s=.025,o=e.split("").map(i=>i===" "?" ":i);return c.jsxs(Ec.span,{...n,className:R("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",t),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[c.jsx("div",{children:o.map((i,a)=>c.jsx(Ec.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:r,ease:"easeInOut",delay:s*a},children:i},String(a)))}),c.jsx("div",{className:R("absolute inset-0"),children:o.map((i,a)=>c.jsx(Ec.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:r,ease:"easeInOut",delay:s*a},children:i},String(a)))})]})}},{variant:"shake",component:({children:e,className:t,...n})=>c.jsx("span",{...n,className:R("text-primary-muted hover:animate-text-shake",t),children:e})},{variant:"hover-decoration",component:({children:e,className:t,...n})=>c.jsx("div",{className:R("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:c.jsx("span",{...n,className:R("text-primary-muted",t),children:e})})}];function mr({variant:e="static",className:t,...n}){const s=rx.find(o=>o.variant===e)?.component||rx[0].component;return c.jsx(s,{...n,className:t})}const yU=600*1e3,em=new Map,vU=e=>{const t=Wt(e);if(!t)return;const n=em.get(t);if(n){if(n.expiresAt<=Date.now()){em.delete(t);return}return n.outsideFileGrant}},sx=(e,t,n)=>{const r=Wt(e);!r||!t||em.set(r,{outsideFileGrant:t,expiresAt:Date.now()+yU})},xU=async(e,t)=>{const n=Wt(e);if(!n||!t||Mu(n,t))return;const r=vU(n);if(r)return r;const s=await MC(n);if(!(!s.success||!s.path||!s.outsideFileGrant))return sx(s.path,s.outsideFileGrant),Wt(s.path)!==n&&sx(n,s.outsideFileGrant),s.outsideFileGrant},S7=(e,t)=>{const n=e.trim();if(n){if(Hr.getState().setSelectedSkill(n),re.getState().setSettingsPage("skills.installed"),t){t.openSettings("skills.installed");return}re.getState().setSettingsDialogOpen(!0)}},ox=e=>{if(!e)return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null},ix=e=>{const t=e?.state?.status;return typeof t=="string"?t:null},ax=e=>e?.state,cx=e=>e?.metadata,cl=e=>{const t=e?.time;return{start:typeof t?.start=="number"?t.start:null,end:typeof t?.end=="number"?t.end:null}},lx=e=>{const t=e;if(!t)return"";const n=typeof t.text=="string"?t.text:"",r=typeof t.content=="string"?t.content:"",s=typeof t.value=="string"?t.value:"";return[n,r,s].reduce((o,i)=>i.length>o.length?i:o,"")},Tu=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(r.type!==s.type)return!1;const o=ox(r),i=ox(s);if(o!==i)return!1;if(r.type==="tool"){if(ax(r)!==ax(s)||cx(r)!==cx(s)||ix(r)!==ix(s))return!1;const d=cl(r),f=cl(s);if(d.start!==f.start||d.end!==f.end)return!1;const u=r.tool,h=s.tool;if(u!==h)return!1;const m=r.output,g=s.output;if(m!==g)return!1;continue}const a=cl(r),l=cl(s);if(a.start!==l.start||a.end!==l.end)return!1;if(r.type==="file"){const d=r,f=s;if(d.filename!==f.filename||d.mime!==f.mime||d.url!==f.url||d.size!==f.size)return!1}if(r.type==="text"||r.type==="reasoning"){if(lx(r)!==lx(s))return!1;const d=r.shellAction,f=s.shellAction;if((d||f)&&(d?.command!==f?.command||d?.output!==f?.output||d?.status!==f?.status))return!1}}return!0},C7=(e,t)=>e===t?!0: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)&&e.render===t.render&&e.bashExecution===t.bashExecution,k7=(e,t)=>C7(e.info,t.info)&&e.info.error===t.info.error&&Tu(e.parts,t.parts),Dd=(e,t)=>e===t?!0:!e||!t?!1:C7(e.info,t.info),bU=(e,t)=>!e||!t?e===t:e.additions===t.additions&&e.deletions===t.deletions&&e.files===t.files,wU=(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){const r=e[n],s=t[n];if(r.file!==s.file||r.additions!==s.additions||r.deletions!==s.deletions)return!1}return!0},Q1=(e,t)=>e.id===t.id&&e.messageId===t.messageId&&e.kind===t.kind&&e.partIndex===t.partIndex&&e.endedAt===t.endedAt&&Tu([e.part],[t.part]),SU=(e,t,n)=>{let r=0,s=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.messageId!==n;)r+=1;for(;s<(t?.length??0)&&t?.[s]?.messageId!==n;)s+=1;const o=e?.[r],i=t?.[s];if(!o||!i)return o===i;if(!Q1(o,i))return!1;r+=1,s+=1}},CU=(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(!Q1(e.parts[n],t.parts[n]))return!1;return!0},dx=(e,t)=>!!e?.some(n=>n.anchorMessageId===t),kU=(e,t,n)=>{let r=0,s=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.anchorMessageId!==n;)r+=1;for(;s<(t?.length??0)&&t?.[s]?.anchorMessageId!==n;)s+=1;const o=e?.[r],i=t?.[s];if(!o||!i)return o===i;if(!CU(o,i))return!1;r+=1,s+=1}},M7=(e,t,n,r)=>{if(e===t)return!0;if(!e||!t)return e===t;if(r)return!0;if(e.turnId!==t.turnId||e.isFirstAssistantInTurn!==t.isFirstAssistantInTurn||e.isLastAssistantInTurn!==t.isLastAssistantInTurn||e.isLatestTurn!==t.isLatestTurn||e.isWorking!==t.isWorking||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;const o=e.activityOwnerMessageId===n||t.activityOwnerMessageId===n;if(o&&e.activityOwnerMessageId!==t.activityOwnerMessageId||!SU(e.activityParts,t.activityParts,n)||!kU(e.activityGroupSegments,t.activityGroupSegments,n))return!1;const i=dx(e.activityGroupSegments,n)||dx(t.activityGroupSegments,n);return!((o||i)&&!bU(e.diffStats,t.diffStats)||(o||i||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!wU(e.changedFiles,t.changedFiles))},Od=new Map,MU=e=>{const t=Od.get(e);if(t)return t;const n={subscribers:new Set,timerId:null};return Od.set(e,n),n},IU=(e,t)=>{const n=MU(e);return n.subscribers.add(t),t(Date.now()),n.timerId===null&&typeof window<"u"&&(n.timerId=window.setInterval(()=>{const r=Date.now();n.subscribers.forEach(s=>{s(r)})},e)),()=>{const r=Od.get(e);r&&(r.subscribers.delete(t),!(r.subscribers.size>0)&&(r.timerId!==null&&typeof window<"u"&&window.clearInterval(r.timerId),Od.delete(e)))}},I7=(e,t=250)=>{const[n,r]=p.useState(()=>Date.now());return p.useEffect(()=>{if(e)return IU(t,r)},[e,t]),n},ux=e=>typeof e!="string"?null:e.trim()||null,EU=e=>{const t=e.tool?.trim().toLowerCase(),n=e.state,r=n?.input&&typeof n.input=="object"?n.input:void 0;if(t==="skill")return ux(r?.name);if(t!=="read")return null;const s=n?.metadata?.pichamber;if(!s||typeof s!="object")return null;const o=s.skill;return!o||typeof o!="object"?null:ux(o.name)},Ra=e=>{const t="h-3.5 w-3.5 flex-shrink-0",n=e.toLowerCase();return n==="edit"||n==="multiedit"||n==="apply_patch"||n==="str_replace"||n==="str_replace_based_edit_tool"?c.jsx(V,{name:"pencil",className:t}):n==="write"||n==="create"||n==="file_write"?c.jsx(V,{name:"file-edit",className:t}):n==="read"||n==="view"||n==="file_read"||n==="cat"?c.jsx(V,{name:"file-text",className:t}):n==="bash"||n==="shell"||n==="cmd"||n==="terminal"?c.jsx(V,{name:"terminal-box",className:t}):n==="list"||n==="ls"||n==="dir"||n==="list_files"?c.jsx(V,{name:"folder-6",className:t}):n==="search"||n==="grep"||n==="find"||n==="ripgrep"?c.jsx(V,{name:"menu-search",className:t}):n==="glob"?c.jsx(V,{name:"file-search",className:t}):n==="fetch"||n==="curl"||n==="wget"||n==="webfetch"?c.jsx(V,{name:"global",className:t}):n==="web-search"||n==="websearch"||n==="search_web"||n==="codesearch"||n==="google"||n==="bing"||n==="duckduckgo"||n==="perplexity"?c.jsx(V,{name:"global",className:t}):n==="todowrite"||n==="todoread"?c.jsx(V,{name:"list-check-3",className:t}):n==="structuredoutput"||n==="structured_output"?c.jsx(V,{name:"list-check-2",className:t}):n==="skill"?c.jsx(V,{name:"book",className:t}):n==="task"?c.jsx(V,{name:"ai-agent",className:t}):n==="pichamber"?c.jsx(V,{name:"pichamber",className:t}):n==="question"?c.jsx(V,{name:"survey",className:t}):n==="lsp"?c.jsx(V,{name:"scan-2",className:t}):n==="plan_enter"?c.jsx(V,{name:"file-list-2",className:t}):n==="plan_exit"?c.jsx(V,{name:"task",className:t}):n.startsWith("git")?c.jsx(V,{name:"git-branch",className:t}):c.jsx(V,{name:"tools",className:t})},_U=({href:e})=>{const[t,n]=p.useState(!1),r=p.useMemo(()=>$T(e),[e]);return!r||t?null:c.jsx("span",{className:"inline-flex size-[18px] flex-shrink-0 items-center justify-center rounded border border-[var(--border)] bg-[var(--interactive-hover)]",children:c.jsx("img",{src:r,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",className:"size-3.5 rounded-sm",onError:()=>n(!0)})})},jU=e=>{if(e.kind!=="tool")return!1;const n=e.part.state?.status||void 0;return n==="completed"||n==="error"||n==="aborted"||n==="failed"||n==="timeout"||n==="cancelled"?!1:n==="running"||n==="pending"||n==="started"?!0:typeof e.endedAt!="number"},TU=e=>{const n=e.part.state?.time;return{start:typeof n?.start=="number"?n.start:void 0,end:typeof n?.end=="number"?n.end:e.endedAt}},AU=(e,t,n=Date.now())=>{const r=Math.max(0,(t??n)-e)/1e3;return`${(r<.05&&typeof t=="number"?.1:r).toFixed(1)}s`},NU=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=r?.filePath||r?.file_path||r?.path||s?.filePath||s?.file_path||s?.path;if(typeof o=="string"&&o.trim().length>0){const i=o.lastIndexOf("/");return i>=0?o.slice(i+1):o}return null},LU=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=r?.filePath||r?.file_path||r?.path||s?.filePath||s?.file_path||s?.path;return typeof o=="string"&&o.trim().length>0?o:null},RU=e=>{if(typeof e!="string")return null;const 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},Ai=e=>{if(e.length===0)return"0 tasks";let t=0,n=0;for(const s of e){if(!s||typeof s!="object")continue;const o=RU(s.status);o&&(o==="pending"&&(t+=1),o==="in_progress"&&(n+=1))}const r=t+n;return r===0?"0 tasks":`${r} ${r===1?"task":"tasks"}`},PU=e=>{const n=e.part.state,r=n?.input,s=n?.output;if(Array.isArray(r?.todos)){const o=Ai(r.todos);if(o)return o}if(Array.isArray(s)){const o=Ai(s);if(o)return o}if(s&&typeof s=="object"&&Array.isArray(s.todos)){const o=Ai(s.todos);if(o)return o}if(typeof s=="string"&&s.trim().length>0)try{const o=JSON.parse(s);if(Array.isArray(o)){const i=Ai(o);if(i)return i}if(o&&typeof o=="object"&&Array.isArray(o.todos)){const i=Ai(o.todos);if(i)return i}}catch{}return null},DU=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=(typeof r?.offset=="number"&&Number.isFinite(r.offset)?r.offset:void 0)??(typeof r?.line=="number"&&Number.isFinite(r.line)?r.line:void 0)??(typeof s?.offset=="number"&&Number.isFinite(s.offset)?s.offset:void 0)??(typeof s?.line=="number"&&Number.isFinite(s.line)?s.line:void 0);if(!(typeof o!="number"||o<=0))return Math.floor(o)},OU=(e,t=!0)=>{const n=e.lastIndexOf("/");if(n===-1)return c.jsx(mr,{variant:t?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-title)"},title:e,children:e});const r=e.slice(0,n),s=e.slice(n+1),o=r.startsWith("/"),i=o?r.slice(1):r;return c.jsxs("span",{className:R("min-w-0 inline-flex max-w-full flex-1 items-center overflow-hidden",Mt),title:e,children:[o?c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}):null,c.jsx("span",{className:"min-w-0 shrink truncate whitespace-nowrap",style:{color:"var(--tools-description)",direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}),c.jsx(mr,{variant:t?"generate-effect":"static",className:"flex-shrink-0",style:{color:"var(--tools-title)"},children:s})]})},HU=e=>{const t=e.part,n=t.tool?.toLowerCase()??"",r=t.state,s=r?.input,o=r?.metadata;if(n==="grep"||n==="search"||n==="find"||n==="ripgrep"){const i=s?.pattern;if(typeof i=="string"&&i.trim().length>0)return i.length>40?i.slice(0,40)+"...":i}if(n==="glob"){const i=s?.pattern;if(typeof i=="string"&&i.trim().length>0)return i.length>40?i.slice(0,40)+"...":i}if(n==="websearch"||n==="web-search"||n==="search_web"||n==="codesearch"||n==="perplexity"){const i=s?.query;if(typeof i=="string"&&i.trim().length>0)return i.length>50?i.slice(0,50)+"...":i}if(n==="skill"){const i=s?.name;if(typeof i=="string"&&i.trim().length>0)return i}if(n==="webfetch"||n==="fetch"||n==="curl"||n==="wget"){const i=typeof s?.url=="string"&&s.url||typeof s?.URL=="string"&&s.URL||typeof o?.url=="string"&&o.url||typeof o?.URL=="string"&&o.URL||"";if(typeof i=="string"&&i.trim().length>0)return i.trim()}return n==="todowrite"||n==="todoread"?PU(e):NU(e)},FU=({toolName:e,activity:t,animateTailText:n})=>{const r=p.useContext($a),s=Ga(),o=nt(A=>A.currentDirectory),i=jU(t),a=TU(t),l=typeof a.start=="number",d=I7(!!(l&&i&&typeof a.end!="number"),250),f=l?AU(a.start,a.end,d):null,u=HU(t),h=EU(t.part),m=e.toLowerCase(),g=m==="skill"||m==="read"&&h!==null,x=m==="read"&&!g,b=g?"skill":e,S=Ka(b).displayName,y=Ra(b),v=x?LU(t):null,C=x?DU(t):void 0,w=v?s4(v,o):null,I=p.useCallback((A,j)=>{const k=Za(o,A);if(!k)return;if(r?.editor){r.editor.openFile(k,j);return}if(s){const L=re.getState(),O=o||uh(o,k);j&&Number.isFinite(j)?L.openContextFileAtLine(O,k,Math.max(1,Math.trunc(j)),1):L.openContextFile(O,k),s.openFiles();return}if(!Mu(k,o)){xU(k,o).then(()=>{const L=re.getState(),O=o||uh(o,k);if(j&&Number.isFinite(j)){L.openContextFileAtLine(O,k,Math.max(1,Math.trunc(j)),1);return}L.openContextFile(O,k)});return}const _=re.getState(),M=uh(o,k);if(j&&Number.isFinite(j)){_.openContextFileAtLine(M,k,Math.max(1,Math.trunc(j)),1);return}_.openContextFile(M,k)},[o,s,r]),E=m==="grep"||m==="search"||m==="find"||m==="ripgrep"||m==="glob",T=m==="webfetch"||m==="fetch"||m==="curl"||m==="wget";return c.jsxs("div",{className:R("oc-static-tool-row flex w-full items-center gap-x-1.5 pr-2 pl-px py-1 min-w-0"),"data-chat-activity-row":"true",children:[c.jsx("div",{className:"inline-flex h-5 items-center flex-shrink-0",style:{color:"var(--tools-icon)"},children:y}),c.jsx(Pd,{active:i,minDurationMs:1e3,className:R(Gr,"inline-flex items-center flex-shrink-0"),style:ti,title:S,children:S}),x&&v&&w?c.jsxs("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),I(v,C)},className:R("inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left hover:text-[var(--status-info)] hover:opacity-90",Mt),style:{color:"var(--tools-description)"},title:C?`${w}:${C}`:w,children:[c.jsx(pr,{filePath:v,className:"h-3.5 w-3.5"}),OU(w,n)]}):null,E&&u!==null?c.jsx("span",{className:"inline-flex min-w-0 flex-1",children:c.jsxs(mr,{variant:n?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-description)"},title:u,children:['"',u,'"']})}):null,T&&u!==null?c.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:R("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",Mt),style:{color:"var(--status-info)"},title:u,children:[c.jsx(_U,{href:u}),c.jsx("span",{className:"min-w-0 truncate",children:u})]}):null,g&&h!==null?c.jsx("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),S7(h,s)},className:R("inline-flex !min-h-0 h-5 min-w-0 flex-1 items-center truncate whitespace-nowrap text-left hover:opacity-90",Mt),style:{color:"var(--tools-description)"},title:`Open ${h} in Settings`,"aria-label":`Open ${h} skill in Settings`,children:h}):null,!x&&!E&&!T&&!g&&u!==null?c.jsx(mr,{variant:n?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-description)"},children:u}):null,f?c.jsx("span",{className:R("flex-shrink-0 tabular-nums text-subtle-foreground",Mt),"aria-label":"Tool duration",children:f}):null]})},BU=(e,t)=>e.toolName===t.toolName&&e.animateTailText===t.animateTailText&&Q1(e.activity,t.activity),VU=p.memo(FU,BU),$U=e=>e.match(/<task\s+id="([^"]+)"(?:\s+[^>]*)?>/i)?.[1],pQ="diffs-container";(()=>{try{return!1}catch{return!1}})();const zU=/(?=^From [a-f0-9]+ .+$)/m,E7=/(?=^diff --git)/gm,mQ=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: (.*))?/m,gQ=new RegExp("(?<=\\n)"),UU=/^(---|\+\+\+)\s+([^\t\r\n]+)/,qU=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,WU=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,KU=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,yQ="header-prefix",vQ="header-filename-suffix",xQ="header-metadata",bQ="header-custom",wQ={dark:"pierre-dark",light:"pierre-light"},SQ="data-theme-css",CQ="data-unsafe-css",kQ="data-diffs-scrollbar-measure",MQ="--diffs-scrollbar-gutter-measured",IQ=1e5,GU={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8};({...GU});const EQ=Object.freeze({fromStart:0,fromEnd:0}),_Q={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},jQ={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0};function fx(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}const ZU=new TextEncoder,YU=new TextDecoder("utf-8",{ignoreBOM:!0}),XU=/[\uD800-\uDFFF]/,tm=1024;let bo=new Uint8Array(tm);function _7(){bo.length!==tm&&(bo=new Uint8Array(tm))}function Dt(e){if(e.length===0)return e;if(XU.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;bo.length<t&&(bo=new Uint8Array(t));const{written:n}=ZU.encodeInto(e,bo);return YU.decode(bo.subarray(0,n))}function JU(e,t,n){try{return QU(e,t,n)}finally{_7()}}function QU(e,t,n=!1){const r=cq(e),s=r?nq(e):rq(e);let o;const i=[];for(const a of s){if(r&&!E7.test(a)){if(o==null)o=Dt(a);else{if(n)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",a)}continue}else if(!r&&!sq(a)){if(o==null)o=Dt(a);else{if(n)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",a)}continue}const l=j7(a,{cacheKey:void 0,isGitDiff:r,throwOnError:n});l!=null&&i.push(l)}return{patchMetadata:o,files:i}}function TQ(e,t){try{return j7(e,t)}finally{_7()}}function j7(e,{cacheKey:t,isGitDiff:n=E7.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let i=0;const a=L7(e,"@@ ");let l;const d=r==null||s==null;let f=0,u=0;for(const h of a){const m=T7(h),g=m[0];if(g==null){if(o)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",h);continue}const x=N7(g);let b=0,S=0;if(x==null||l==null){if(l!=null){if(o)throw Error("parsePatchContent: Invalid hunk");console.error("parsePatchContent: Invalid hunk",h);continue}l={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:d,additionLines:!d&&r!=null&&s!=null?hx(s.contents):[],deletionLines:!d&&r!=null&&s!=null?hx(r.contents):[],cacheKey:gx(t)},l.additionLines.length===1&&s?.contents===""&&(l.additionLines.length=0),l.deletionLines.length===1&&r?.contents===""&&(l.deletionLines.length=0);for(const A of m){if(A.startsWith("diff --git")){const k=A.trim().match(WU),_=k?.[1]??k?.[2],M=k?.[3]??k?.[4];if(_==null||M==null){if(o)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",A);continue}l.name=Dt(M.trim()),_!==M&&(l.prevName=Dt(_.trim()));continue}const j=A.startsWith("---")||A.startsWith("+++")?A.match(n?qU:UU):null;if(j!=null){const[,k,_]=j;if(k==="---"&&_!=="/dev/null"){const M=Dt(_.trim());l.prevName=M,l.name=M}else k==="+++"&&_!=="/dev/null"&&(l.name=Dt(_.trim()))}else if(n){if(A.startsWith("new mode ")&&(l.mode=Dt(A.slice(8).trim())),A.startsWith("old mode ")&&(l.prevMode=Dt(A.slice(8).trim())),A.startsWith("new file mode")&&(l.type="new",l.mode=Dt(A.slice(13).trim())),A.startsWith("deleted file mode")&&(l.type="deleted",l.mode=Dt(A.slice(17).trim())),A.startsWith("similarity index")&&(A.startsWith("similarity index 100%")?l.type="rename-pure":l.type="rename-changed"),A.startsWith("index ")){const[,k,_,M]=A.trim().match(KU)??[];k!=null&&(l.prevObjectId=Dt(k)),_!=null&&(l.newObjectId=Dt(_)),M!=null&&(l.mode=Dt(M))}A.startsWith("rename from ")&&(l.prevName=Dt(A.slice(12).trim())),A.startsWith("rename to ")&&(l.name=Dt(A.slice(10).trim()))}}continue}let y,v;for(;m.length>0&&(m[m.length-1]===`
|
|
156
|
+
`||m[m.length-1]==="\r"||m[m.length-1]===`\r
|
|
157
|
+
`||m[m.length-1]==="");)m.pop();const{additionStart:C,deletionStart:w}=x;f=d?f:w-1,u=d?u:C-1;const I={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:x.additionCount,additionStart:C,additionLines:b,deletionCount:x.deletionCount,deletionStart:w,deletionLines:S,deletionLineIndex:f,additionLineIndex:u,hunkContent:[],hunkContext:gx(x.hunkContext),hunkSpecs:Dt(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let E=0,T=0;for(let A=1;A<m.length;A++){const j=m[A];if(E>=I.additionCount&&T>=I.deletionCount&&!j.startsWith("\\")){if(o&&oq(j)&&!iq(j))throw Error("parsePatchContent: hunk has more lines than expected");break}const k=j[0];if(k!=="+"&&k!=="-"&&k!==" "&&k!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${k}", full line: "${j}"`),console.error("processFile: invalid rawLine:",j);continue}const _=lq(k);if(_==="addition"){if(o&&E>=I.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const M=Mh(j);(y==null||y.type!=="change")&&(y=Ih("change",f,u),I.hunkContent.push(y)),u++,E++,d&&l.additionLines.push(M),y.additions++,b++,v="addition"}else if(_==="deletion"){if(o&&T>=I.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const M=Mh(j);(y==null||y.type!=="change")&&(y=Ih("change",f,u),I.hunkContent.push(y)),f++,T++,d&&l.deletionLines.push(M),y.deletions++,S++,v="deletion"}else if(_==="context"){if(o&&(T>=I.deletionCount||E>=I.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const M=Mh(j);(y==null||y.type!=="context")&&(y=Ih("context",f,u),I.hunkContent.push(y)),u++,f++,E++,T++,d&&(l.deletionLines.push(M),l.additionLines.push(M)),y.lines++,v="context"}else if(_==="metadata"&&y!=null){if(y.type==="context"?(I.noEOFCRAdditions=!0,I.noEOFCRDeletions=!0):v==="deletion"?I.noEOFCRDeletions=!0:v==="addition"&&(I.noEOFCRAdditions=!0),d&&(v==="addition"||v==="context")){const M=l.additionLines.length-1;M>=0&&(l.additionLines[M]=fx(l.additionLines[M]))}if(d&&(v==="deletion"||v==="context")){const M=l.deletionLines.length-1;M>=0&&(l.deletionLines[M]=fx(l.deletionLines[M]))}}}if(o&&(E!==I.additionCount||T!==I.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");I.additionLines=b,I.deletionLines=S,I.collapsedBefore=Math.max(I.additionStart-1-i,0),l.hunks.push(I),i=I.additionStart+I.additionCount-1;for(const A of I.hunkContent)A.type==="context"?(I.splitLineCount+=A.lines,I.unifiedLineCount+=A.lines):(I.splitLineCount+=Math.max(A.additions,A.deletions),I.unifiedLineCount+=A.deletions+A.additions);I.splitLineStart=l.splitLineCount+I.collapsedBefore,I.unifiedLineStart=l.unifiedLineCount+I.collapsedBefore,l.splitLineCount+=I.collapsedBefore+I.splitLineCount,l.unifiedLineCount+=I.collapsedBefore+I.unifiedLineCount}if(l!=null){if(o&&d&&!n&&l.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(l.hunks.length>0&&!d&&l.additionLines.length>0&&l.deletionLines.length>0){const h=l.hunks[l.hunks.length-1],m=h.additionStart+h.additionCount-1,g=l.additionLines.length,x=Math.max(g-m,0);l.splitLineCount+=x,l.unifiedLineCount+=x}return n||(l.prevName!=null&&l.name!==l.prevName?l.hunks.length>0?l.type="rename-changed":l.type="rename-pure":(r==null||r.contents==="")&&s!=null&&s.contents!==""?l.type="new":r!=null&&r.contents!==""&&(s==null||s.contents==="")&&(l.type="deleted")),l.type!=="rename-pure"&&l.type!=="rename-changed"&&(l.prevName=void 0),l}}function eq(e,t,n=!1){const r=[],s=tq(e)?e.split(zU):[e];for(const o of s)try{r.push(JU(o,t!=null?`${t}-${r.length}`:void 0,n))}catch(i){if(n)throw i;console.error(i)}return r}function tq(e){return e.startsWith("From ")||e.includes(`
|
|
158
|
+
From `)}function hx(e){const t=T7(e);for(let n=0;n<t.length;n++)t[n]=Dt(t[n]);return t}function T7(e){if(e.length===0)return[""];const t=[];let n=0;for(;;){const r=e.indexOf(`
|
|
159
|
+
`,n);if(r===-1)break;t.push(e.slice(n,r+1)),n=r+1}return n<e.length&&t.push(e.slice(n)),t}function nq(e){return L7(e,"diff --git")}function rq(e){if(e.length===0)return[""];const t=[];let n=0,r=0,s=0,o=0,i=!1;for(;r<e.length;){const a=nm(e,r);if(s<=0&&o<=0){if(A7(e,r)){r>n&&t.push(e.slice(n,r)),n=r,i=!0,r=nm(e,a);continue}if(i&&e.startsWith("@@ -",r)){const d=N7(e.slice(r,a));d!=null&&(s=d.deletionCount,o=d.additionCount)}r=a;continue}const l=e[r];if(l==="\\"){r=a;continue}l===" "?(s=Math.max(s-1,0),o=Math.max(o-1,0)):l==="-"?s=Math.max(s-1,0):l==="+"&&(o=Math.max(o-1,0)),r=a}return t.push(e.slice(n)),t}function sq(e){return A7(e,0)}function A7(e,t){const n=nm(e,t);return px(e,t,"---")&&px(e,n,"+++")}function px(e,t,n){if(!e.startsWith(n,t))return!1;const r=e[t+n.length];if(r!==" "&&r!==" ")return!1;for(let s=t+n.length+1;s<e.length;s++){const o=e[s];if(o===`
|
|
160
|
+
`||o==="\r")break;if(o!==" "&&o!==" ")return!0}return!1}function nm(e,t){const n=e.indexOf(`
|
|
161
|
+
`,t);return n===-1?e.length:n+1}function oq(e){const t=e[0];return t==="+"||t==="-"||t===" "}function iq(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){const n=e[t];if(n!==" "&&n!==" "&&n!==`
|
|
162
|
+
`&&n!=="\r")return!1}return!0}function N7(e){if(!e.startsWith("@@ -"))return;let t=4;const n=ll(e,t);if(n==null)return;const r=n.value;t=n.endIndex;let s=1;if(e[t]===","){const f=ll(e,t+1);if(f==null)return;s=f.value,t=f.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const o=ll(e,t);if(o==null)return;const i=o.value;t=o.endIndex;let a=1;if(e[t]===","){const f=ll(e,t+1);if(f==null)return;a=f.value,t=f.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let l;const d=t+3;return e[d]===" "&&(l=aq(e.slice(d+1))),{additionCount:a,additionStart:i,deletionCount:s,deletionStart:r,hunkContext:l}}function ll(e,t){let n=t,r=0;for(;n<e.length;n++){const s=e.charCodeAt(n)-48;if(s<0||s>9)break;r=r*10+s}if(n!==t)return{value:r,endIndex:n}}function aq(e){return e.endsWith(`\r
|
|
163
|
+
`)?e.slice(0,-2):e.endsWith(`
|
|
164
|
+
`)?e.slice(0,-1):e}function cq(e){return e.startsWith("diff --git")||e.includes(`
|
|
165
|
+
diff --git`)}function L7(e,t){if(e.length===0)return[""];const n=`
|
|
166
|
+
${t}`,r=e.startsWith(t)?0:mx(e,n,0);if(r===-1)return[e];const s=[];r>0&&s.push(e.slice(0,r));let o=r;for(;;){const i=mx(e,n,o+1);if(i===-1)break;s.push(e.slice(o,i)),o=i}return s.push(e.slice(o)),s}function mx(e,t,n){const r=e.indexOf(t,n);return r===-1?-1:r+1}function gx(e){return e==null?e:Dt(e)}function lq(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function Mh(e){const t=e.slice(1);return Dt(t===""?`
|
|
167
|
+
`:t)}function Ih(e,t,n){return e==="change"?{type:"change",additions:0,deletions:0,additionLineIndex:n,deletionLineIndex:t}:{type:"context",lines:0,additionLineIndex:n,deletionLineIndex:t}}const R7=/^\*\*\*\s+(?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)/m,Hd=/^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@/m,dq=/(?=^diff --git\s+)/gm,P7=/^diff --git\s+/m,uq=/(?=^---\s+\S)/gm,D7=/^---\s+\S/m,Zr=e=>typeof e=="object"&&e!==null,fq=e=>e.replace(/\r\n/g,`
|
|
168
|
+
`).replace(/\r/g,`
|
|
169
|
+
`).trim(),hq=e=>{let t=!1;return e.split(`
|
|
170
|
+
`).map(n=>{if(n.startsWith("@@"))return t=!0,n;if(t)return n;const r=n.match(/^\s*(---|\+\+\+)\s+(.+)$/);if(!r)return n;const s=r[1],o=r[2]??"";return o.trim()==="/dev/null"?`${s} /dev/null`:`${s} ${o.replace(/\\/g,"/")}`}).join(`
|
|
171
|
+
`)},pq=e=>{let t=!1;return e.split(`
|
|
172
|
+
`).map(n=>{if(n.startsWith("@@"))return t=!0,n;if(!t||n.startsWith("--- ")||n.startsWith("+++ ")||n.startsWith("diff --git"))return n;if(n.length===0)return" ";const r=n[0];return r===" "||r==="+"||r==="-"||r==="\\"?n:` ${n}`}).join(`
|
|
173
|
+
`)},yx=(e,t)=>t===1?e:`${e},${t}`,mq=e=>{const t=e.split(`
|
|
174
|
+
`),n=[...t];for(let r=0;r<t.length;r+=1){const o=(t[r]??"").match(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@(.*)$/);if(!o)continue;let i=0,a=0;for(let l=r+1;l<t.length;l+=1){const d=t[l]??"";if(d.startsWith("@@")||d.startsWith("--- ")||d.startsWith("diff --git"))break;if(!d.startsWith("\\")){if(d.startsWith("+")){a+=1;continue}if(d.startsWith("-")){i+=1;continue}i+=1,a+=1}}n[r]=`@@ -${yx(o[1]??"0",i)} +${yx(o[2]??"0",a)} @@${o[3]??""}`}return n.join(`
|
|
175
|
+
`)},O7=e=>mq(pq(hq(fq(e)))),Ut=e=>{if(typeof e=="string")return/\S/.test(e)?e:void 0;if(Zr(e)){const t=e.patch;if(typeof t=="string")return/\S/.test(t)?t:void 0}},Xa=e=>Zr(e)?typeof e.movePath=="string"?e.movePath:typeof e.filePath=="string"?e.filePath:typeof e.relativePath=="string"?e.relativePath:null:null,eg=(e,t,n)=>{if(e==="apply_patch"){const r=Array.isArray(n?.files)?n.files:[];for(const s of r)if(Zr(s)&&s.type!=="delete"){const o=Xa(s);if(o)return o}return null}if(e==="edit"||e==="multiedit"){const r=Zr(n?.filediff)?n.filediff:void 0;return r&&typeof r.file=="string"?r.file:typeof t?.filePath=="string"?t.filePath:typeof t?.file_path=="string"?t.file_path:typeof t?.path=="string"?t.path:null}return e==="write"?typeof t?.filePath=="string"?t.filePath:typeof t?.file_path=="string"?t.file_path:typeof t?.path=="string"?t.path:null:null},gq=(e,t,n)=>{if(e==="apply_patch"){const s=Array.isArray(n?.files)?n.files:[],o=new Set;for(const i of s){if(!Zr(i))continue;const a=Xa(i);a&&o.add(a),i.type==="move"&&typeof i.filePath=="string"&&o.add(i.filePath)}return[...o]}const r=eg(e,t,n);return r?[r]:[]},yq=e=>e==="edit"||e==="multiedit"||e==="apply_patch",vx=(e,t)=>{const n=Array.isArray(e.files)?e.files:[];if(!t){const r=n[0];return Zr(r)?r:void 0}return n.find(r=>Zr(r)&&(r.relativePath===t||r.filePath===t||r.movePath===t))},ya=e=>{if(!e)return;let t,n;for(const r of e.split(`
|
|
176
|
+
`)){const s=r.replace(/\r$/,""),o=s.match(/^@@\s+-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/);if(o){const i=Number.parseInt(o[1]??"",10);Number.isFinite(i)&&(t=Math.max(1,i),n??=t);continue}if(t!==void 0&&!(s.startsWith("+++")||s.startsWith("---")||s.startsWith("diff "))){if(s.startsWith("+"))return t;s.startsWith(" ")&&(t+=1)}}return n},xx=(e,t,n)=>{if(!t||!yq(e))return;if(n){const i=vx(t,n),a=Ut(i?.patch)??Ut(i?.diff);if(a){const l=ya(a);if(l!==void 0)return l}}const r=Ut(t.patch)??Ut(t.diff);if(r){const i=ya(r);if(i!==void 0)return i}const s=vx(t),o=Ut(s?.patch)??Ut(s?.diff);return o?ya(o):void 0},vq=e=>{const t=(e??"").trim().replace(/\t.*$/,"");return!t||t==="/dev/null"?"":t.replace(/^[ab]\//,"")},xq=e=>{const t=e.trim().replace(/\s+/g,"-");return t.length>0?t:"file"},bq=e=>{let t=!1;for(const n of e.split(`
|
|
177
|
+
`)){if(n.startsWith("@@")){if(!Hd.test(n))return!1;t=!0;continue}if(!t||n.length===0)continue;const r=n[0];if(r!==" "&&r!=="+"&&r!=="-"&&r!=="\\")return!1}return!0},Eh=e=>{const t=O7(e);if(!t||R7.test(t)||!Hd.test(t)||!bq(t))return null;try{const n=eq(t,void 0,!0);if(n.length!==1)return null;const r=n[0]?.files??[],s=r[0];return r.length!==1||!s||s.hunks.length===0?null:{patch:t,title:vq(s.name)}}catch{return null}},wq=e=>{const t=P7.test(e),n=D7.test(e);return!t&&!n?[]:e.split(t?dq:uq).map(r=>r.trim()).filter(r=>r.length>0)},bx=(e,t,n,r)=>{const s=O7(e);if(!s)return[];const o=Eh(s);if(o){const a=o.title?r(o.title):r(t);return[{id:`${n}-0`,title:a,patch:o.patch,renderMode:"diff"}]}const i=[];for(const a of wq(s)){const l=Eh(a),d=l?.title?r(l.title):r(t);if(!l){(Hd.test(a)||P7.test(a)||D7.test(a))&&i.push({id:`${n}-${i.length}`,title:d,patch:a,renderMode:"text"});continue}i.push({id:`${n}-${i.length}`,title:d,patch:l.patch,renderMode:"diff"})}if(i.length>0)return i;if(!R7.test(s)&&Hd.test(s)){const a=xq(t),l=Eh(`--- ${a}
|
|
178
|
+
+++ ${a}
|
|
179
|
+
${s}`);if(l)return[{id:`${n}-0`,title:r(t),patch:l.patch,renderMode:"diff"}]}return[{id:`${n}-0`,title:r(t),patch:s,renderMode:"text"}]},Sq=e=>{if(!Zr(e))return null;const t=Ut(e.patch)??Ut(e.diff);if(!t)return null;const n=typeof e.relativePath=="string"?e.relativePath:typeof e.filePath=="string"?e.filePath:"";return{filePath:Xa(e)??void 0,patch:t,title:n}},Cq=(e,t,n)=>{const s=(Array.isArray(e?.files)?e.files:[]).flatMap((i,a)=>{const l=Sq(i);return l?bx(l.patch,l.title||`File ${a+1}`,`file-${a}`,n).map(d=>({...d,filePath:l.filePath})):[]});return s.length>0?s:bx(typeof t=="string"?t:"","Diff","fallback",n)},kq=new Set(["read","skill"]),Fs=e=>{if(typeof e!="string")return"";const t=e.trim().toLowerCase();if(!t)return"";const n=t.replace(/:\d+$/,"");if(n.includes(".")){const r=n.split(".").filter(Boolean);return r[r.length-1]??n}return n},Mq=e=>!Iq(e),Iq=e=>kq.has(Fs(e)),Eq=(e,t,n)=>{if(typeof t=="string"&&t.trim().length>0)return t;const r=Fs(e)==="glob"?n?.pattern:void 0;return typeof r=="string"?r:""},_q=(e,t)=>{const n=t.replace(/\r\n/g,`
|
|
180
|
+
`);if(!n.trim())return;const r=(()=>{const a=(e??"").trim();return a?a.startsWith("/")?a.slice(1):a:"new-file"})(),s=n.split(`
|
|
181
|
+
`),o=s.length,i=s.map(a=>`+${a}`).join(`
|
|
182
|
+
`);return["--- /dev/null",`+++ b/${r}`,`@@ -0,0 +1,${o} @@`,i].join(`
|
|
183
|
+
`)},Fd=e=>{const t=e.trim().replace(/\\/g,"/").replace(/\/{2,}/g,"/");return!t||t==="/"?t:t.replace(/\/+$/,"")},Gn=(e,t)=>{const n=Fd(e),r=Fd(t);if(!n)return"";if(!r)return n;if(n===r)return".";const s=`${r}/`;return n.startsWith(s)?n.slice(s.length):n},jq=5,va=e=>typeof e=="object"&&e!==null,Tq=e=>{if(!va(e))return null;const t=typeof e.message=="string"?e.message.trim():"";if(!t)return null;const n=typeof e.severity=="number"&&Number.isFinite(e.severity)?Math.trunc(e.severity):void 0;if(n!==void 0&&n!==1)return null;const r=va(e.range)?e.range:void 0,s=r&&va(r.start)?r.start:void 0,o=typeof s?.line=="number"&&Number.isFinite(s.line)?Math.max(0,Math.trunc(s.line)):0,i=typeof s?.character=="number"&&Number.isFinite(s.character)?Math.max(0,Math.trunc(s.character)):0;return{message:t,line:o+1,character:i+1}},Aq=(e,t,n,r)=>{if(!["edit","multiedit","write","apply_patch"].includes(e))return null;const s=eg(e,t,n);if(!s||!n||!va(n.diagnostics))return null;const o=Fd(s),i=o.startsWith("/")?o:`${Fd(r)}/${o}`.replace(/\/+/g,"/"),a=n.diagnostics[o]??n.diagnostics[i];if(!Array.isArray(a))return null;const l=a.map(f=>Tq(f)).filter(f=>!!f);if(l.length===0)return null;const d=l.slice(0,jq);return{displayPath:o.startsWith("/")?Gn(o,r):o,diagnostics:d,remaining:Math.max(0,l.length-d.length)}},Nq=e=>{const t=e.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!t)return null;const n=[],r=t[1],s=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let o;for(;(o=s.exec(r))!==null;)n.push({question:o[1],answer:o[2]});return n.length>0?n:null},Lq=e=>{const t=Ut(e?.patch)??Ut(e?.diff);if(!t)return null;let n=0,r=0,s=0;for(let o=0;o<=t.length;o+=1){if(o<t.length&&t.charCodeAt(o)!==10)continue;const i=t.slice(s,o);i.startsWith("+")&&!i.startsWith("+++")&&n++,i.startsWith("-")&&!i.startsWith("---")&&r++,s=o+1}return n===0&&r===0?null:{added:n,removed:r}},Rq=e=>{if(!e?.content||typeof e.content!="string")return null;let t=1;for(let n=0;n<e.content.length;n+=1)e.content.charCodeAt(n)===10&&(t+=1);return t},H7=(e,t,n)=>{const r=t,s=r.metadata,o=r.input;if(e.tool==="apply_patch"){const i=Array.isArray(s?.files)?s?.files:[],a=i[0],l=a?.relativePath||a?.filePath;return i.length>1?null:typeof l=="string"?Gn(l,n):null}if((e.tool==="edit"||e.tool==="multiedit")&&o){const i=o?.filePath||o?.file_path||o?.path||s?.filePath||s?.file_path||s?.path;if(typeof i=="string")return Gn(i,n)}if(e.tool==="read"&&o){const i=o?.filePath||o?.file_path||o?.path||s?.filePath||s?.file_path||s?.path;if(typeof i=="string")return Gn(i,n)}if(e.tool&&["write","create","file_write"].includes(e.tool)&&o){const i=o?.filePath||o?.file_path||o?.path;if(typeof i=="string")return Gn(i,n)}if(e.tool==="lsp"&&o){const i=o?.filePath||o?.file_path||o?.path;if(typeof i=="string")return Gn(i,n)}return null},Pq=(e,t)=>{if(!e)return"";const n=typeof e.operation=="string"?e.operation:"lsp";if(n==="workspaceSymbol"){const l=typeof e.query=="string"&&e.query.trim().length>0?` "${e.query.trim()}"`:"";return`${n}${l}`}const r=typeof e.filePath=="string"?e.filePath:typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:"",s=r?Gn(r,t):"";if(n==="documentSymbol")return s?`${n} ${s}`:n;const o=typeof e.line=="number"&&Number.isFinite(e.line)?Math.trunc(e.line):void 0,i=typeof e.character=="number"&&Number.isFinite(e.character)?Math.trunc(e.character):void 0,a=o!==void 0&&i!==void 0?`:${o}:${i}`:"";return s?`${n} ${s}${a}`:n},Dq=(e,t,n)=>{const r=t,s=r.metadata,o=r.input,i=H7(e,t,n);if(i)return i;if(e.tool==="apply_patch"){const l=Array.isArray(s?.files)?s?.files:[];return l.length>1?`${l.length} files`:""}if(e.tool==="question"&&o?.questions&&Array.isArray(o.questions)){const l=o.questions.length;return`Asked ${l} question${l!==1?"s":""}`}if(e.tool==="bash"&&o?.command&&typeof o.command=="string")return o.command.split(`
|
|
184
|
+
`)[0].substring(0,100);if(e.tool==="task"&&o?.description&&typeof o.description=="string")return o.description.substring(0,80);if(e.tool==="lsp")return Pq(o,n);const a=o?.description||s?.description||"title"in t&&t.title||"";return Eq(e.tool,a,o)},F7=e=>{const t=e.state?.title;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.state?.input;if(n&&typeof n=="object"){const r=n.filePath??n.file_path??n.path;if(typeof r=="string"&&r.trim().length>0)return r.trim();const s=n.url;if(typeof s=="string"&&s.trim().length>0)return s.trim()}return""},Zo=e=>{const t=Fs(e.tool),n=e.state?.status??"",r=F7(e);return`${e.id??""}${t}${n}${r}`},Oq=({isTaskTool:e,isExpanded:t,isActive:n,hasFinalMetadataSummary:r,taskSessionId:s})=>e&&!!s&&!r&&(t||n),Yo=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},wx=e=>{if(!e||typeof e!="object")return;const t=e;return Yo(t.sessionID)??Yo(t.sessionId)},B7=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n=="string"){t.push({tool:"tool",state:{status:"completed",title:n}});continue}if(!n||typeof n!="object")continue;const r=n;t.push({id:typeof r.id=="string"?r.id:void 0,tool:typeof r.tool=="string"?r.tool:"tool",state:{status:typeof r.state?.status=="string"?r.state.status:typeof r.status=="string"?r.status:void 0,title:typeof r.state?.title=="string"?r.state.title:typeof r.title=="string"?r.title:void 0,input:r.state?.input&&typeof r.state.input=="object"?r.state.input:void 0}})}return t},V7=e=>{if(typeof e!="string"||e.trim().length===0)return{summaryEntries:[]};const t=e.match(/<task_metadata>\s*([\s\S]*?)\s*<\/task_metadata>/i);if(!t?.[1])return{summaryEntries:[]};try{const n=JSON.parse(t[1].trim());return{sessionId:Yo(n.sessionId)??Yo(n.sessionID),summaryEntries:B7(n.summary??n.entries??n.tools??n.calls)}}catch{return{summaryEntries:[]}}},Hq=e=>{if(typeof e!="string"||e.trim().length===0)return;const t=V7(e);if(t.sessionId)return t.sessionId;const n=e.match(/task_id\s*:\s*([^\s<"']+)/i),r=e.match(/session[_\s-]?id\s*:\s*([^\s<"']+)/i),s=n?.[1]??r?.[1];return Yo(s||$U(e))},Sx=new WeakMap,Fq=e=>e.type==="tool",Bq=e=>{const t=Sx.get(e);if(t)return t;const n=[];if(e.info.role==="assistant")for(const r of e.parts){if(!Fq(r))continue;const s=r.tool?.trim().toLowerCase();if(!s||s==="task"||s==="todowrite"||s==="todoread")continue;const o=r.state;n.push({id:r.id,tool:r.tool,state:{status:o?.status,title:o?.title,input:o?.input&&typeof o.input=="object"?o.input:void 0}})}return Sx.set(e,n),n},Vq=e=>{const t=[];for(const n of e)t.push(...Bq(n));return t},$q=e=>e.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Cx=e=>{if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.trunc(e));if(typeof e=="string"){const t=Number.parseInt(e,10);return Number.isFinite(t)?Math.max(0,t):null}return null},kx=(e,t)=>e===null?t:t===null?e:e+t,zq=e=>{const t=Array.isArray(e?.files)?e.files:[],n=new Map;for(const r of t){if(!r||typeof r!="object")continue;const s=r,o=typeof s.relativePath=="string"?s.relativePath:typeof s.filePath=="string"?s.filePath:"";if(!o)continue;const i=Cx(s.additions),a=Cx(s.deletions),l=n.get(o);if(l){l.added=kx(l.added,i),l.removed=kx(l.removed,a);continue}n.set(o,{file:s,path:o,name:o.split("/").pop()||o,added:i,removed:a})}return Array.from(n.values())},Uq=({animate:e=!0,metadata:t,onFileClick:n,openDiffLabel:r,showFileIcons:s=!0,textClassName:o})=>{const i=zq(t);return i.length<=1?null:c.jsx(c.Fragment,{children:i.map(a=>{const l=a.added!==null||a.removed!==null,d=c.jsxs(c.Fragment,{children:[s?c.jsx(pr,{filePath:a.path,className:"h-3.5 w-3.5"}):null,c.jsx(mr,{variant:e?"generate-effect":"static",className:R("min-w-0 max-w-full truncate",o),style:{color:"var(--tools-description)"},title:a.path,children:a.name}),l?c.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:[c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",a.added??0]}),c.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a.removed??0]})]}):null]}),f=n&&a.file.type!=="delete"&&Xa(a.file),u=`${r}: ${a.path}`;return f?c.jsx(be,{variant:"ghost",size:"xs",className:R("min-w-0 max-w-full gap-1 normal-case font-normal tracking-normal",o),"aria-label":u,title:u,onClick:h=>n(a.file,h),children:d},a.path):c.jsx("span",{className:R("inline-flex min-w-0 max-w-full items-center gap-1",o),style:{color:"var(--tools-description)"},children:d},a.path)})})},qq=({currentDirectory:e,editor:t,file:n})=>{const r=Xa(n);if(!r||n.type==="delete")return!1;const s=Ut(n.patch)??Ut(n.diff),o=s?ya(s):void 0,i=Za(e,r);return t.openFile(i,o),!0},$7=({children:e,animate:t,className:n})=>c.jsx("div",{className:R(t&&"oc-step-in",n),children:e}),tg=({children:e,maxHeightClass:t="max-h-[60vh]",className:n,outerClassName:r,disableHorizontal:s=!1,followKey:o})=>{const i=p.useRef(null),a=p.useRef(!0);return p.useLayoutEffect(()=>{const l=i.current;if(o===void 0){a.current=!0;return}!l||!a.current||(l.scrollTop=l.scrollHeight)},[o]),c.jsx("div",{className:R("w-full min-w-0 flex-none overflow-hidden",r),children:c.jsx(Su,{ref:i,"data-scrollable":"true",onWheelCapture:l=>{o!==void 0&&l.deltaY<0&&(a.current=!1)},onScroll:l=>{if(o===void 0)return;const d=l.currentTarget;a.current=d.scrollHeight-d.scrollTop-d.clientHeight<=2},className:R("tool-output-surface p-2 rounded-xl w-full min-w-0",t,s?"overflow-y-auto overflow-x-hidden":"overflow-auto",n),children:c.jsx("div",{className:"w-full min-w-0",children:e})})})},Mx=({path:e,grow:t=!0})=>{const n=e.lastIndexOf("/");if(n===-1)return c.jsx("span",{className:R("min-w-0 truncate typography-ui-label text-foreground",t&&"flex-1"),style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:e,children:e});const r=e.slice(0,n),s=e.slice(n+1),o=r.startsWith("/"),i=o?r.slice(1):r;return c.jsxs("span",{className:R("min-w-0 flex items-baseline overflow-hidden typography-ui-label",t&&"flex-1"),title:e,children:[o?c.jsx("span",{className:"flex-shrink-0 text-muted-foreground",children:"/"}):null,c.jsx("span",{className:"min-w-0 truncate text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsxs("span",{className:"flex-shrink-0",children:[c.jsx("span",{className:"text-muted-foreground",children:"/"}),c.jsx("span",{className:"text-foreground",children:s})]})]})},rm=({path:e,animate:t=!0,grow:n=!0,showFileIcons:r=!0})=>{const s=e.lastIndexOf("/");if(s===-1)return c.jsxs("span",{className:R("min-w-0 inline-flex items-center gap-1 overflow-hidden",n&&"flex-1"),title:e,children:[r?c.jsx(pr,{filePath:e,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsx(mr,{variant:t?"generate-effect":"static",className:R("min-w-0 truncate whitespace-nowrap",Mt,n&&"flex-1"),style:{color:"var(--tools-title)"},children:e})]});const o=e.slice(0,s),i=e.slice(s+1),a=o.startsWith("/"),l=a?o.slice(1):o;return c.jsxs("span",{className:R("min-w-0 inline-flex items-center gap-1 overflow-hidden",n&&"flex-1"),title:e,children:[r?c.jsx(pr,{filePath:e,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsxs("span",{className:R("min-w-0 inline-flex max-w-full items-baseline overflow-hidden",Mt,n&&"flex-1"),children:[a?c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}):null,c.jsx("span",{className:"min-w-0 shrink truncate whitespace-nowrap",style:{color:"var(--tools-description)",direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:l}),c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}),c.jsx(mr,{variant:t?"generate-effect":"static",className:"flex-shrink-0",style:{color:"var(--tools-title)"},children:i})]})]})},Wq=new Set(["read","view","file_read","cat","write","create","file_write","edit","multiedit","apply_patch"]),Kq=(e,t)=>{if(!Wq.has(e.toLowerCase()))return!1;const n=t.trim();if(!n||n==="Patch"||/^\d+\s+files$/.test(n))return!1;if(n.includes("/")||n.includes("\\"))return!0;const r=n.split(/[\\/]/).pop()||n;return r.startsWith(".")||r.includes(".")?!0:/^[A-Za-z0-9_-]+$/.test(r)},Gq=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(Zo(e[n])!==Zo(t[n]))return!1;return!0},z7=p.memo(({entry:e,isMobile:t,animateTailText:n})=>{const r=Fs(e.tool),s=r.length>0?r:"tool",o=F7(e),i=o.trim().length>0,a=e.state?.status,l=Ka(s).displayName;return c.jsx($7,{animate:n,children:c.jsxs("div",{className:R("flex gap-2 min-w-0 w-full",a==="error"&&t?"items-start":"items-center"),children:[c.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:Ra(s)}),c.jsx("span",{className:R(Gr,"text-foreground/80 flex-shrink-0"),style:ti,title:l,children:l}),i?a!=="error"&&Kq(s,o)?c.jsx(rm,{path:o,animate:n,showFileIcons:!0}):a==="error"?c.jsx("span",{className:R(Mt,"flex-1 min-w-0 text-[var(--status-error)]",t?"whitespace-normal break-words":"truncate"),children:o}):c.jsx(mr,{variant:n?"generate-effect":"static",className:R(Mt,"flex-1 min-w-0 truncate text-subtle-foreground"),style:{color:"var(--tools-description)"},title:o,children:o}):null]})})},(e,t)=>e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&Zo(e.entry)===Zo(t.entry));z7.displayName="TaskSummaryEntryRow";const U7=p.memo(({entries:e,isExpanded:t,isMobile:n,animateTailText:r})=>{const s=t?e:e.slice(-6),o=Math.max(0,e.length-s.length),i=e.length-s.length;return c.jsx(tg,{maxHeightClass:t?"max-h-[40vh]":"max-h-[min(17.5rem,45vh)]",disableHorizontal:!0,children:c.jsxs("div",{className:"w-full min-w-0 space-y-1","data-chat-task-entries-list":"true",children:[o>0?c.jsxs("div",{className:"typography-micro text-subtle-foreground",children:["+",o," more…"]}):null,s.map((a,l)=>{const d=t?l:i+l,f=a.id??`${Zo(a)}:${d}`;return c.jsx(z7,{entry:a,isMobile:n,animateTailText:r},f)})]})})},(e,t)=>e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&Gq(e.entries,t.entries));U7.displayName="TaskSummaryEntriesList";const Zq=({entries:e,isExpanded:t,isMobile:n,output:r,sessionId:s,onShowPopup:o,input:i,animateTailText:a=!0,isActive:l=!1})=>{const d=Jn(),f=he(S=>S.setCurrentSession),u=typeof r=="string"?$q(r):"",h=u.length>0,[m,g]=p.useState(!1),x=S=>{S.stopPropagation(),s&&d&&f(s,d)},b=typeof i?.subagent_type=="string"?i.subagent_type:"subagent";return e.length===0&&!h&&!s?c.jsx("div",{className:"oc-task-tool-summary relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",children:c.jsx("div",{className:"typography-meta text-subtle-foreground",children:l?"Waiting for subagent activity...":"No subagent session id on task metadata."})}):c.jsxs("div",{className:R("oc-task-tool-summary relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-[var(--tools-border)] before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:[e.length>0?c.jsx(U7,{entries:e,isExpanded:t,isMobile:n,animateTailText:a}):null,s&&c.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:S=>S.stopPropagation(),onClick:x,children:[c.jsx(V,{name:"external-link",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"typography-meta text-primary font-medium",children:`Open ${b.charAt(0).toUpperCase()+b.slice(1)} subtask`})]}),h?c.jsxs("div",{className:R("space-y-1",(e.length>0||s)&&"pt-1"),children:[c.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),g(y=>!y)},children:[m?c.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0"}):c.jsx(V,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?c.jsx(tg,{maxHeightClass:"max-h-[50vh]",children:c.jsx("div",{className:"w-full min-w-0",children:c.jsx(Wa,{content:u,variant:"tool",onShowPopup:o})})}):null]}):null]})},Yq=e=>{const t=e.colors.syntax.base,n=e.colors.syntax.tokens??{},r=e.colors.status;return{"--md-syntax-foreground":t.foreground,"--md-syntax-comment":t.comment,"--md-syntax-string":t.string,"--md-syntax-number":t.number,"--md-syntax-keyword":t.keyword,"--md-syntax-operator":t.operator,"--md-syntax-function":t.function,"--md-syntax-type":t.type,"--md-syntax-variable":t.variable,"--md-syntax-property":n.variableProperty??t.variable,"--md-syntax-inserted":r.success,"--md-syntax-deleted":r.error}},Xq="/assets/markdown-shiki.worker-BVA5NZBT.js";let zn,Jq=0;const Pa=new Map,sm=new Set,Ix=()=>{Pa.forEach(e=>e(null)),Pa.clear(),sm.clear(),zn?.terminate(),zn=void 0},Qq=()=>{if(zn)return zn;if(!(typeof window>"u"||typeof Worker>"u")){try{zn=new Worker(Xq,{type:"module"})}catch(e){console.error("Failed to create Shiki worker:",e);return}return zn.onmessage=e=>{const t=Pa.get(e.data.id);t&&(Pa.delete(e.data.id),t(e.data))},zn.onerror=Ix,zn.onmessageerror=Ix,zn.postMessage({type:"init"}),zn}},ng=e=>{const t=Qq();if(!t)return Promise.resolve(null);const n=++Jq;return new Promise(r=>{Pa.set(n,r),t.postMessage(e(n))})},eW=async(e,t)=>{const n=await ng(r=>({type:"highlight",id:r,code:e,lang:t}));return n?.type==="highlight"?n.html:null},AQ=async(e,t)=>{const n=await ng(r=>({type:"highlightLines",id:r,code:e,lang:t}));return n?.type==="highlightLines"?n.lines:null},NQ=async(e,t,n,r)=>{const s=!sm.has(n),o=await ng(i=>({type:"highlightTokens",id:i,code:e,lang:t,themeName:n,...s?{theme:r}:{}}));return o?.type==="highlightTokens"?(sm.add(n),o.lines):null},tW=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),nW=e=>e?Object.entries(e).map(([t,n])=>n==null?"":`${t.startsWith("--")?t:t.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`)}:${typeof n=="number"?`${n}px`:n};`).join(""):"",Ex=(e,t,n)=>{const r=e.querySelector("pre");r&&(r.style.margin="0",r.style.background="transparent",r.style.whiteSpace=t?"pre-wrap":"pre",t&&(r.style.wordBreak="break-word",r.style.overflowWrap="break-word"));const s=e.querySelector("code");if(s){const o=nW(n);o&&s.setAttribute("style",`${s.getAttribute("style")??""}${o}`)}},rW=e=>`<pre><code>${tW(e)}</code></pre>`,Bd=({code:e,language:t,className:n,style:r,codeStyle:s,wrap:o=!1})=>{const{currentTheme:i}=vr(),a=p.useRef(null),l=p.useMemo(()=>Yq(i),[i]);return p.useLayoutEffect(()=>{const d=a.current;d&&(d.innerHTML=rW(e),Ex(d,o,s))},[e,o,s]),p.useEffect(()=>{const d=a.current;if(!d)return;let f=!0;return eW(e,(t||"text").toLowerCase()).then(u=>{!f||!d||!u||(d.innerHTML=u,Ex(d,o,s))}),()=>{f=!1}},[e,t,o,s]),c.jsx("div",{ref:a,className:R("typography-code",n),style:{...l,...r}})},sW={maxDepth:50,maxNodes:1e5,initiallyExpandedDepth:2};function oW(e){return e===null?"null":Array.isArray(e)?"array":typeof e=="object"?"object":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":"null"}function iW(e){if(e.length===0)return"root";let t="root";for(const n of e)/^\d+$/.test(n)?t+=`[${n}]`:t+=`.${n}`;return t}let om=0;function q7(e,t,n,r,s){if(om>=s.maxNodes)return null;om++;const o=oW(e),i=iW(n),a=o==="object"||o==="array",l={id:i,key:t,value:e,type:o,depth:r,path:n,isExpandable:a};if(a&&r<s.maxDepth){const d=o==="array"?e.map((f,u)=>[String(u),f]):Object.entries(e);l.childCount=d.length,l.children=[];for(const[f,u]of d){const h=[...n,f],m=q7(u,f,h,r+1,s);m&&l.children.push(m)}}else a&&(l.childCount=o==="array"?e.length:Object.keys(e).length);return l}function aW(e,t){const n={...sW,...t};om=0;try{const r=e.trim();if(!r)return null;const s=JSON.parse(r);return q7(s,"root",[],0,n)}catch{return null}}function cW(e,t){if(!e)return[];const n=[];function r(s){const o=!t.has(s.id);if(n.push({node:s,isExpanded:o}),s.isExpandable&&o&&s.children)for(const i of s.children)r(i)}return r(e),n}function lW(e){if(!e)return[];const t=[];function n(r){if(r.isExpandable&&(t.push(r.id),r.children))for(const s of r.children)n(s)}return n(e),t}function dW(e,t){if(!e)return[];const n=[];function r(s){if(s.isExpandable&&s.depth>=t&&n.push(s.id),s.children)for(const o of s.children)r(o)}return r(e),n}const _x=["var(--syntax-key)","color-mix(in oklch, var(--syntax-key) 85%, var(--syntax-string))","color-mix(in oklch, var(--syntax-key) 70%, var(--syntax-number))","color-mix(in oklch, var(--syntax-key) 55%, var(--syntax-function))","color-mix(in oklch, var(--syntax-key) 40%, var(--syntax-type))","color-mix(in oklch, var(--syntax-key) 30%, var(--syntax-keyword))"];function uW(e){return _x[e%_x.length]}function fW(e){switch(e.type){case"string":return"var(--syntax-string)";case"number":return"var(--syntax-number)";case"boolean":return"var(--syntax-keyword)";case"null":return"var(--syntax-comment)";default:return"var(--surface-foreground)"}}function im(e){switch(e.type){case"string":{const t=e.value;return t.length>60?`"${t.slice(0,57)}..."`:`"${t}"`}case"number":case"boolean":return String(e.value);case"null":return"null";case"object":return`{${e.childCount??0} ${e.childCount===1?"item":"items"}}`;case"array":return`[${e.childCount??0}]`;default:return String(e.value)}}function hW(e){if(e.type==="object"){const t=e.children?.map(r=>r.key).slice(0,3)??[],n=(e.childCount??0)>3?", ...":"";return`{ ${t.map(r=>`"${r}": ...`).join(", ")}${n} }`}if(e.type==="array"){const t=e.childCount??0;return t<=3?`[${e.children?.map(r=>im(r)).join(", ")??""}]`:`[${t} items]`}return im(e)}const am=p.memo(({flatNode:e,onToggle:t,onCopyPath:n})=>{const{node:r,isExpanded:s}=e,o=r.depth*20,i=p.useCallback(()=>{t(r.id)},[t,r.id]),a=p.useCallback(u=>{n&&(u.preventDefault(),n(r.id))},[n,r.id]),l=uW(r.depth),d=fW(r),f=r.isExpandable&&r.children&&r.children.length>0;return c.jsxs("div",{className:"flex items-center py-0.5 px-2 hover:bg-[var(--surface-hover)] rounded-sm cursor-default font-mono text-xs leading-5 whitespace-nowrap",style:{paddingLeft:`${o+8}px`},onContextMenu:a,children:[f?c.jsx("button",{type:"button",onClick:i,className:"mr-1 flex h-4 w-4 shrink-0 items-center justify-center rounded-sm hover:bg-[var(--interactive-hover)] text-muted-foreground",children:s?c.jsx(V,{name:"arrow-down-s",className:"h-3 w-3"}):c.jsx(V,{name:"arrow-right-s",className:"h-3 w-3"})}):c.jsx("span",{className:"mr-1 w-4"}),r.key!=="root"&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"mr-1 font-semibold",style:{color:l},children:/^\d+$/.test(r.key)?r.key:`"${r.key}"`}),c.jsx("span",{className:"mr-1 text-[var(--surface-foreground)]",children:":"})]}),r.isExpandable?s?c.jsx("span",{className:"text-[var(--surface-foreground)]",children:r.type==="object"?"{":"["}):c.jsx("span",{style:{color:"var(--surface-mutedForeground)"},children:hW(r)}):c.jsx("span",{style:{color:d},children:im(r)})]})});am.displayName="JsonRow";const pW=200,mW=22,gW=p.forwardRef(function({data:t,className:n,maxHeight:r="100%",initiallyExpandedDepth:s=2,onCopyPath:o},i){const a=p.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]),l=p.useMemo(()=>a?aW(a):null,[a]),[d,f]=p.useState(()=>l?new Set(dW(l,s)):new Set),u=p.useMemo(()=>cW(l,d),[l,d]),h=u.length>pW,m=p.useRef(null),g=J5({count:u.length,enabled:h,getScrollElement:()=>m.current,estimateSize:()=>mW,overscan:20,getItemKey:y=>u[y]?.node.id??y}),x=p.useCallback(y=>{f(v=>{const C=new Set(v);return C.has(y)?C.delete(y):C.add(y),C})},[]),b=p.useCallback(()=>{f(new Set)},[]),S=p.useCallback(()=>{l&&f(new Set(lW(l)))},[l]);return p.useImperativeHandle(i,()=>({expandAll:b,collapseAll:S}),[b,S]),l?h?c.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:c.jsx("div",{style:{height:g.getTotalSize(),position:"relative"},children:g.getVirtualItems().map(y=>{const v=u[y.index];return v?c.jsx("div",{"data-index":y.index,ref:g.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${y.start}px)`},children:c.jsx(am,{flatNode:v,onToggle:x,onCopyPath:o})},v.node.id):null})})}):c.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:u.map(y=>c.jsx(am,{flatNode:y,onToggle:x,onCopyPath:o},y.node.id))}):null}),yW=({mode:e,onModeChange:t,className:n})=>{const r=p.useCallback(s=>{s.stopPropagation(),t(e==="side-by-side"?"unified":"side-by-side")},[e,t]);return c.jsx(be,{size:"sm",variant:"ghost",className:R("h-5 w-5 p-0 opacity-60 hover:opacity-100",n),onClick:r,title:e==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:e==="side-by-side"?c.jsx(V,{name:"align-justify",className:"h-3 w-3"}):c.jsx(V,{name:"layout-column",className:"h-3 w-3"})})},vW=e=>{let t=e.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return t=t.replace(/^\s*\d{5}\|\s?/gm,""),t.trim()},vn=(e,t="")=>{if(typeof e=="string")return e;if(e==null)return t;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{return JSON.stringify(e)}catch{return t}},xW=e=>e?e.includes("<diagnostics")||e.includes("<file_diagnostics>")||e.includes("LSP errors detected")||e.includes("This file has errors"):!1,bW=e=>e?e.replace(/\n{0,2}LSP errors detected[\s\S]*?<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,"").replace(/\n{0,2}This file has errors[\s\S]*?<\/file_diagnostics>/g,"").replace(/<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,"").replace(/<file_diagnostics>[\s\S]*?<\/file_diagnostics>/g,"").trim():"",jx=(e,t)=>!e||typeof e!="object"?String(e):lP(e,t||""),dl=e=>{if(typeof e=="string"){const t=e.trim();return t.length>0?t:void 0}if(e&&typeof e=="object"){const t=e.patch;if(typeof t=="string"){const n=t.trim();return n.length>0?n:void 0}}},wW=e=>{if(!e||typeof e!="object")return;const t=dl(e.patch)??dl(e.diff);if(t)return t;const n=Array.isArray(e.files)?e.files:[];for(const r of n){if(!r||typeof r!="object")continue;const s=dl(r.patch)??dl(r.diff);if(s)return s}},SW=e=>{if(!e||typeof e!="string")return{data:null,isJson:!1};const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return{data:null,isJson:!1};if(!t.endsWith("}")&&!t.endsWith("]"))return{data:null,isJson:!1};if(t.length<2)return{data:null,isJson:!1};try{const n=JSON.parse(t);return n!==null&&typeof n=="object"?{data:n,isJson:!0}:{data:null,isJson:!1}}catch{return{data:null,isJson:!1}}},W7=(e,t,n)=>{let r=vW(e);if((t==="edit"||t==="multiedit"||t==="write"||t==="apply_patch")&&xW(r)&&(r=bW(r)),(t==="edit"||t==="multiedit"||t==="apply_patch")&&r.trim().length===0){const s=wW(n);if(s)return s}return r},LQ=e=>{const n=e.match(/<type>(file|directory)<\/type>/i)?.[1]?.toLowerCase()??"unknown",i=(e.match(/<content>([\s\S]*?)<\/content>/i)?.[1]??e).replace(/\r\n/g,`
|
|
185
|
+
`).split(`
|
|
186
|
+
`),a=f=>/\(\s*File has more lines\..*offset.*\)/i.test(f.trim()),d=i.map(f=>{const u=f.trim(),h=u.startsWith("(")&&u.endsWith(")")||a(u);if(n!=="directory"){const m=f.match(/^(\d+):\s?(.*)$/);if(m){const g=m[2],x=g.trim(),b=x.startsWith("(")&&x.endsWith(")")||a(x);return{lineNumber:b?null:Number(m[1]),text:g,isInfo:b}}}return{lineNumber:null,text:f,isInfo:h}}).filter((f,u,h)=>{if(f.text.trim().length>0)return!0;const m=h[u-1],g=h[u+1],x=!!(m?.isInfo||g?.isInfo),b=f.lineNumber!==null;return!(x&&b)});return{type:n,lines:d}},RQ=(e,t)=>{try{const n=e.trim().split(`
|
|
187
|
+
`).filter(Boolean);if(n.length===0)return null;const r=[];return n.forEach(s=>{const o=s.match(/^(\s*)(.+)$/);if(o){const[,i,a]=o,l=Math.floor(i.length/2),d=!a.endsWith("/");r.push({name:a.replace(/\/$/,""),depth:l,isFile:d})}}),c.jsx("div",{className:R("w-full min-w-0 font-mono space-y-0.5",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Da.tool.popup,children:r.map((s,o)=>c.jsx("div",{className:"min-w-0",style:{paddingLeft:`${s.depth*20}px`},children:s.isFile?c.jsx("span",{className:"text-foreground block truncate",children:s.name}):c.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[s.name,"/"]})},o))})}catch{return null}},CW={backgroundColor:"var(--status-info)",opacity:.6},PQ=(e,t,n)=>{try{const r=e.trim().split(`
|
|
188
|
+
`).filter(Boolean);if(r.length===0)return null;const s={};return r.forEach(o=>{const i=o.match(/^(.+?):(\d+):(.*)$/)||o.match(/^(.+?):(.*)$/);if(i){const[,a,l,d]=i,f=d!==void 0?l:"",u=d!==void 0?d:l;s[a]||(s[a]=[]),s[a].push({lineNum:f,content:u})}}),c.jsxs("div",{className:R("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Da.tool.popup,children:[c.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," match",r.length!==1?"es":""]}),Object.entries(s).map(([o,i])=>c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:R("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:o}),c.jsx("div",{className:"pl-4 space-y-1",children:i.map((a,l)=>!a.lineNum&&!a.content?null:c.jsxs("div",{className:R("flex items-start gap-2 min-w-0",t?"typography-micro":"typography-code"),children:[c.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:CW}),c.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[a.lineNum&&c.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",a.lineNum,":"]}),c.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:a.content||" "})]})]},l))})]},o))]})}catch{return null}},kW={backgroundColor:"var(--status-info)",opacity:.6},DQ=(e,t,n)=>{try{const r=e.trim().split(`
|
|
189
|
+
`).filter(Boolean);if(r.length===0)return null;const s={};r.forEach(i=>{const a=i.lastIndexOf("/"),l=a>0?i.substring(0,a):"/",d=a>=0?i.substring(a+1):i;s[l]||(s[l]=[]),s[l].push(d)});const o=Object.keys(s).sort();return c.jsxs("div",{className:R("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Da.tool.popup,children:[c.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," file",r.length!==1?"s":""]}),o.map(i=>c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:R("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:[i,"/"]}),c.jsx("div",{className:R("pl-4 grid gap-1",t?"grid-cols-1":"grid-cols-2"),children:s[i].sort().map(a=>c.jsxs("div",{className:R("flex items-center gap-2 min-w-0",t?"typography-micro":"typography-code"),children:[c.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:kW}),c.jsx("span",{className:"text-foreground font-mono truncate",children:a})]},a))})]},i))]})}catch{return null}},MW=(e,t,n)=>{try{const r=JSON.parse(e);if(!Array.isArray(r))return null;const s=r.filter(a=>!!a&&typeof a=="object"&&typeof a.content=="string"&&typeof a.status=="string");if(s.length===0)return null;const o=s.reduce((a,l)=>{const d=l.status;return d in a&&a[d].push(l),a},{in_progress:[],pending:[],completed:[],cancelled:[]}),i=a=>{const l="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return c.jsx("div",{className:l,style:{backgroundColor:"var(--status-error)"}});case"medium":return c.jsx("div",{className:l,style:{backgroundColor:"var(--primary)"}});case"low":return c.jsx("div",{className:l,style:{backgroundColor:"var(--status-info)"}});default:return c.jsx("div",{className:l,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return c.jsxs("div",{className:R("space-y-3 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Da.tool.popup,children:[c.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[c.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:[t.total,": ",s.length]}),o.in_progress.length>0&&c.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:[t.inProgress,": ",o.in_progress.length]}),o.pending.length>0&&c.jsxs("span",{style:{color:"var(--muted-foreground)"},children:[t.pending,": ",o.pending.length]}),o.completed.length>0&&c.jsxs("span",{style:{color:"var(--status-success)"},children:[t.completed,": ",o.completed.length]}),o.cancelled.length>0&&c.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:[t.cancelled,": ",o.cancelled.length]})]}),o.in_progress.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),c.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:t.inProgress})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.in_progress.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[i(a.priority),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.pending.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),c.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:t.pending})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.pending.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[i(a.priority),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.completed.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(V,{name:"check",className:"w-3 h-3",style:{color:"var(--status-success)"}}),c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:t.completed})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.completed.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx(V,{name:"check",className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.cancelled.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"w-3 h-3 text-subtle-foreground",children:"×"}),c.jsx("span",{className:"typography-meta font-semibold text-subtle-foreground uppercase tracking-wide",children:t.cancelled})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.cancelled.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("span",{className:"w-3 h-3 text-subtle-foreground mt-0.5 flex-shrink-0",children:"×"}),c.jsx("span",{className:"typography-code text-subtle-foreground line-through flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]})]})}catch{return null}},OQ=(e,t)=>{try{return c.jsx("div",{className:R("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Da.tool.popup,children:c.jsx(Wa,{content:e,variant:"tool"})})}catch{return null}},IW=(e,t,n)=>cP(t,e,n),EW=new Set(["id","identifier","title","name"]),_W=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ul=e=>e.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").replace(/^./,t=>t.toUpperCase()),jW=e=>{const 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},TW=e=>{try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},Vd=p.memo(({value:e,label:t,depth:n})=>{if(Array.isArray(e)){const o=t?`${ul(t)} (${e.length})`:`(${e.length})`;return c.jsxs("details",{open:n<2,className:"group/json-summary",children:[c.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:[c.jsx(V,{name:"arrow-right-s",className:"h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90"}),c.jsx("span",{className:"min-w-0 truncate font-medium",children:o})]}),c.jsxs("div",{className:"relative ml-1 pl-3 pb-1",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)]"}),c.jsx("div",{className:"space-y-1",children:e.map((i,a)=>c.jsx(Vd,{value:i,depth:n+1},a))})]})]})}if(_W(e)){const o=jW(e),i=Object.entries(e).filter(([d])=>!EW.has(d)),a=t?`${ul(t)}${o?` · ${o}`:""}`:o,l=c.jsx("div",{className:"space-y-1",children:i.map(([d,f])=>c.jsx(Vd,{label:d,value:f,depth:n+1},d))});return!t&&n===0?c.jsxs("div",{className:"space-y-2",children:[o?c.jsx("div",{className:"typography-meta font-medium text-[var(--surface-foreground)]",children:o}):null,l]}):c.jsxs("details",{open:n<2,className:"group/json-summary",children:[c.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:[c.jsx(V,{name:"arrow-right-s",className:"h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90"}),c.jsx("span",{className:"min-w-0 truncate font-medium",children:a??(t?ul(t):"{}")})]}),c.jsxs("div",{className:"relative ml-1 pl-3 pb-1",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)]"}),l]})]})}const r=e===null?"null":typeof e=="boolean"?e?"true":"false":String(e),s=typeof e=="string"&&TW(e)?c.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[var(--status-info)] underline underline-offset-2 hover:opacity-80",title:e,children:e}):c.jsx("span",{className:R("min-w-0 break-words",e===null?"text-[var(--surface-mutedForeground)]":"text-[var(--surface-foreground)]"),children:r});return c.jsxs("div",{className:"grid grid-cols-[minmax(6rem,auto)_minmax(0,1fr)] gap-x-2 py-1 typography-meta",children:[t?c.jsx("span",{className:"truncate text-[var(--surface-mutedForeground)]",title:t,children:ul(t)}):c.jsx("span",{}),s]})});Vd.displayName="JsonSummaryValue";const $d=p.memo(({data:e})=>c.jsx("div",{className:"space-y-1",children:c.jsx(Vd,{value:e,depth:0})}));$d.displayName="JsonSummaryView";const K7=({diff:e})=>c.jsx("pre",{className:"m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg p-2 typography-code",style:{backgroundColor:"var(--syntax-base-background)",color:"var(--syntax-base-foreground)"},children:e}),G7=1e5,Tx=(e,t,n)=>{const r=Math.max(0,t-e.length+1),s=G7-n.syntheticCells,o=Math.min(r,s),i=Math.min(t,e.length+o-1);for(;e.length<=i;)e.push([]);return n.syntheticCells+=o,i},AW=(e,t,n,r,s)=>{const o=e[t],i=G7-s.syntheticCells,a=Math.min(n,o.length+i),l=Math.max(0,a-o.length);for(;o.length<a;)o.push(" ");return s.syntheticCells+=l,o[a]=r,a},Ax=e=>{if(!e.includes("\x1B")&&!e.includes("\r")&&!e.includes("\b"))return e;const t=[[]],n={syntheticCells:0};let r=0,s=0;for(let o=0;o<e.length;o+=1){const i=e[o];if(i===`
|
|
190
|
+
`){r+=1,s=0,t[r]??=[];continue}if(i==="\r"){s=0;continue}if(i==="\b"){s=Math.max(0,s-1);continue}if(i!=="\x1B"){s=AW(t,r,s,i,n)+1;continue}const a=e[o+1];if(a==="["){const l=o+2;let d=l;for(;d<e.length&&!/[\x40-\x7E]/.test(e[d]);)d+=1;if(d===e.length)break;const f=e[d],u=e.slice(l,d).split(";").map(m=>Number.parseInt(m,10)||0),h=u[0]||1;if(f==="A")r=Math.max(0,r-h);else if(f==="B")r=Tx(t,r+h,n);else if(f==="C")s+=h;else if(f==="D")s=Math.max(0,s-h);else if(f==="G")s=Math.max(0,h-1);else if(f==="H"||f==="f")r=Tx(t,Math.max(0,(u[0]||1)-1),n),s=Math.max(0,(u[1]||1)-1);else if(f==="K"){const m=t[r],g=u[0];if(g===1)for(let x=0;x<=s&&x<m.length;x+=1)m[x]=" ";else g===2?t[r]=[]:m.length=Math.min(m.length,s)}o=d;continue}if(a==="]"){const l=e.indexOf("\x07",o+2),d=e.indexOf("\x1B\\",o+2),f=l===-1?d:d===-1?l:Math.min(l,d);if(f===-1)break;o=e[f]==="\x07"?f:f+1;continue}o+=1}return t.map(o=>o.join("")).join(`
|
|
191
|
+
`)},NW=(e,t,n,r)=>{const s=e==="bash",o=s&&r!=="running";if(typeof t=="string")return o?Ax(t):t;if(s&&typeof n=="string"&&n.length>0)return o?Ax(n):n},LW=(e,t)=>t.startsWith(e)?t.slice(e.length):void 0,Z7=16,RW=(e,t=Z7)=>{if(t<=0||e.length===0)return e;let n=1;for(let r=e.length-1;r>=0;r-=1)if(e.charCodeAt(r)===10&&(n+=1,n>t))return e.slice(r+1);return e},PW=(e,t,n,r)=>t.tool==="bash"?"bash":IW(W7(e,t.tool||"",n),t.tool||"",r),DW=(e,t,n)=>t.tool==="bash"?e:W7(e,t.tool||"",n),OW=({output:e})=>{const t=p.useRef(null),n=p.useRef("");return p.useLayoutEffect(()=>{const r=t.current;if(!r)return;const s=r.firstChild,o=s instanceof globalThis.Text?s:document.createTextNode("");o!==s&&r.replaceChildren(o);const i=RW(e,Z7),a=LW(n.current,i);a===void 0?o.data=i:a.length>0&&o.appendData(a),n.current=i},[e]),c.jsx("pre",{ref:t,className:"m-0 whitespace-pre-wrap break-words",style:{...Qp,lineHeight:"round(var(--code-block-line-height), 1px)",overflowWrap:"break-word"}})},cm=({output:e,part:t,metadata:n,input:r,isStreaming:s=!1})=>{const o=DW(e,t,n),i=PW(e,t,n,r),a=p.useMemo(()=>SW(o),[o]),[l,d]=p.useState("summary"),[f,u]=p.useState(!1);p.useEffect(()=>{d("summary"),u(!1)},[o]);const h=p.useCallback((g,x)=>{x.stopPropagation(),d(g)},[]),m=p.useCallback(async g=>{if(g.stopPropagation(),!(await yr(o)).ok){Ce.error("Failed to copy output");return}u(!0),typeof window<"u"&&window.setTimeout(()=>u(!1),1200)},[o]);return t.tool==="bash"&&s?c.jsx("div",{className:"typography-code text-muted-foreground",children:c.jsx(OW,{output:o})}):a.isJson?c.jsxs("div",{className:"tool-output-surface relative p-2 rounded-xl w-full min-w-0",children:[c.jsxs("div",{className:"absolute right-2 top-2 z-10 flex items-center gap-1",children:[c.jsx(be,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="summary"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("summary",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show navigable JSON",title:"Show navigable JSON",children:c.jsx(V,{name:"list-unordered",className:"h-3.5 w-3.5"})}),c.jsx(be,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="formatted"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("formatted",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show formatted JSON",title:"Show formatted JSON",children:c.jsx(V,{name:"node-tree",className:"h-3.5 w-3.5"})}),c.jsx(be,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="raw"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("raw",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show raw JSON",title:"Show raw JSON",children:c.jsx(V,{name:"code-box",className:"h-3.5 w-3.5"})}),c.jsx(be,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-md bg-[var(--surface-elevated)]/80 text-muted-foreground hover:text-foreground",onClick:m,onPointerDown:g=>g.stopPropagation(),"aria-label":f?"Copied output":"Copy output",title:f?"Copied output":"Copy output",children:c.jsx(V,{name:f?"check":"file-copy",className:"h-3.5 w-3.5"})})]}),l==="summary"?c.jsx($d,{data:a.data}):l==="formatted"?c.jsx(gW,{data:a.data,initiallyExpandedDepth:1,maxHeight:"400px"}):c.jsx("div",{className:"typography-code pr-12 text-muted-foreground",children:c.jsx(Bd,{language:"json",code:o,style:Qp,codeStyle:tx.style,wrap:!0})})]}):c.jsx("div",{className:t.tool==="bash"?"typography-code text-muted-foreground":void 0,children:c.jsx(Bd,{language:i,code:o,style:Qp,codeStyle:tx.style,wrap:!0})})};cm.displayName="ToolScrollableTextOutput";const HW=Hs(()=>mt(()=>import("./ToolPartDiffPreview-B_wWmhtE.js"),__vite__mapDeps([82,5,1,6,77,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,78,79,80,81,25,17,11,18,19,20,43,42]))),Nx=({diff:e,diffViewMode:t})=>c.jsx(p.Suspense,{fallback:c.jsx(K7,{diff:e}),children:c.jsx(HW,{diff:e,diffViewMode:t})}),Y7=p.memo(({part:e,state:t,currentDirectory:n,isExpanded:r,onShowPopup:s})=>{const o=Ga(),[i,a]=p.useState("unified"),l=t,d=l.metadata,f=l.input,u=NW(e.tool||"",l.output,d?.output,t.status),h=typeof u=="string"&&u.length>0,m=typeof u=="string"?u:"",g=e.tool==="bash"&&t.status==="running",x=J1({text:m,isStreaming:g,identityKey:e.id,allowTextReplacement:g}),b=g?x:m,S=l.attachments,y=va(d?.filediff)?d.filediff:void 0,v=Ut(d?.patch)??Ut(d?.diff)??Ut(y?.patch)??Ut(y?.diff)??null,C=p.useMemo(()=>Cq(d,v??void 0,W=>Gn(W,n)),[n,v,d]),w=C.some(W=>W.renderMode==="diff"),I=e.tool==="pichamber"||e.tool==="apply_patch"||e.tool==="edit"||e.tool==="multiedit",E=p.useMemo(()=>Aq(e.tool||"",f,d,n),[n,f,d,e.tool]),T=p.useMemo(()=>!f||typeof f!="object"||Object.keys(f).length===0?"":"command"in f&&typeof f.command=="string"&&e.tool==="bash"?jx(f,e.tool):typeof f.content=="string"?f.content??"":jx(f,e.tool),[f,e.tool]),A=!I&&T.trim().length>0,j=e.tool==="write"||e.tool==="create"||e.tool==="file_write",k=e.tool==="todowrite"||e.tool==="todoread",_=p.useMemo(()=>Array.isArray(f?.todos)?JSON.stringify(f.todos):b,[f?.todos,b]),M=p.useMemo(()=>{if(!j||!A)return;const W=typeof f?.filePath=="string"?f.filePath:typeof f?.file_path=="string"?f.file_path:typeof f?.path=="string"?f.path:void 0;return _q(W,T)},[A,f?.filePath,f?.file_path,f?.path,T,j]);p.useEffect(()=>{a("unified")},[e.id]);const L=(W,z)=>c.jsx(tg,{maxHeightClass:z?.maxHeightClass,className:z?.className,disableHorizontal:z?.disableHorizontal,outerClassName:z?.outerClassName,followKey:z?.followKey,children:W}),O=()=>{const W=U=>Za(n,U.filePath??U.title),z=(U,P)=>{P.stopPropagation();const q=ya(U.patch),B=W(U);re.getState().openContextFileAtLine(n,B,q??1,1),o?.openFiles()},X=(U,P)=>{P.stopPropagation();const q=W(U),B=re.getState(),ee=Gn(q,n);if(B.isMobile){B.navigateToDiff(ee);return}B.openContextDiff(n,ee)},F=()=>E?c.jsxs("div",{className:"tool-output-surface rounded-xl border p-2 space-y-2",style:{borderColor:"var(--status-error-border)",backgroundColor:"var(--status-error-background)"},children:[c.jsx("div",{className:"typography-meta font-medium",style:{color:"var(--status-error)"},children:"LSP errors"}),c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"flex items-center gap-1 min-w-0",children:c.jsx(Mx,{path:E.displayPath,grow:!1})}),c.jsx("div",{className:"space-y-1",children:E.diagnostics.map((U,P)=>c.jsx("div",{className:"rounded-md border px-2 py-1",style:{borderColor:"var(--status-error-border)",backgroundColor:"var(--surface-elevated)"},children:c.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[c.jsxs("span",{className:"typography-micro shrink-0",style:{color:"var(--status-error)"},children:["[",U.line,":",U.character,"]"]}),c.jsx("span",{className:"typography-meta text-foreground whitespace-pre-wrap break-words",children:U.message})]})},`${E.displayPath}:${U.line}:${U.character}:${P}`))}),E.remaining>0?c.jsx("div",{className:"typography-micro text-muted-foreground",children:`+${E.remaining} more errors`}):null]})]}):null;if(e.tool==="question"){if(t.status==="completed"&&h){const P=Nq(b);if(P&&P.length>0)return L(c.jsx("div",{className:"space-y-2",children:P.map((q,B)=>c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground",children:q.question}),c.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:q.answer})]},B))}),{maxHeightClass:"max-h-[40vh]"})}if(t.status==="error"&&"error"in t)return c.jsxs("div",{children:[c.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),c.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:vn(t.error)})]});const U=f;return U?.questions&&Array.isArray(U.questions)&&U.questions.length>0?L(c.jsx("div",{className:"space-y-2",children:U.questions.map((P,q)=>c.jsxs("div",{className:"space-y-0.5",children:[P.header?c.jsx("div",{className:"typography-micro text-muted-foreground",children:vn(P.header)}):null,c.jsx("div",{className:"typography-meta text-foreground",children:vn(P.question)}),Array.isArray(P.options)&&P.options.length>0?c.jsx("div",{className:"flex flex-wrap gap-1 mt-0.5",children:P.options.map(B=>c.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-muted/30 border border-border/30 text-muted-foreground",children:vn(B.label)},vn(B.label)))}):null]},q))}),{maxHeightClass:"max-h-[40vh]"}):c.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(e.tool==="task"&&h)return L(c.jsx("div",{className:"w-full min-w-0",children:c.jsx(Wa,{content:vn(b),variant:"tool",onShowPopup:s})}));if((e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&(C.length>0||E))return L(c.jsxs("div",{className:"space-y-3",children:[C.map(U=>c.jsxs("div",{className:"w-full min-w-0",children:[c.jsxs("div",{className:"mb-1 flex min-w-0 items-center gap-1 px-2 py-1",children:[c.jsx("div",{className:"min-w-0 flex-1 typography-meta font-medium text-muted-foreground",children:c.jsx(Mx,{path:U.title})}),c.jsx(be,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:P=>z(U,P),"aria-label":"Open file at first change",title:"Open file at first change",children:c.jsx(V,{name:"file-edit",className:"h-3.5 w-3.5"})}),c.jsx(be,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:P=>X(U,P),"aria-label":"Open file diff",title:"Open file diff",children:c.jsx(V,{name:"git-pull-request",className:"h-3.5 w-3.5"})})]}),U.renderMode==="diff"?c.jsx(Nx,{diff:U.patch,diffViewMode:i}):c.jsx(K7,{diff:U.patch})]},U.id)),F()]}),{className:"p-1"});if(e.tool==="write"&&E)return L(c.jsx("div",{className:"space-y-3",children:F()}),{className:"p-1"});if(j)return null;if(h&&b.trim()){const U=c.jsx(cm,{output:vn(b),part:e,metadata:d,input:f,isStreaming:g});return L(U,{className:e.tool==="bash"?"p-1 rounded-none":"p-1",maxHeightClass:g?"max-h-64":e.tool==="bash"?"max-h-[46vh]":void 0,followKey:g?b:void 0})}return L(c.jsx("div",{className:"typography-meta text-subtle-foreground",children:"No output produced"}),{maxHeightClass:"max-h-60"})},N=b.trim().length>0,D=t.status==="completed"&&"output"in t||e.tool==="bash"&&N;if(k){if(t.status==="error"&&"error"in t)return c.jsxs("div",{className:"oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4",children:[c.jsx("div",{className:"typography-meta font-medium text-subtle-foreground mb-1",children:"Error:"}),c.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:t.error})]});const W=MW(_,{total:"Total",inProgress:"In progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},{unstyled:!0});return c.jsx("div",{className:"oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4",children:L(W??c.jsx(cm,{output:_,part:e,metadata:d,input:f}),{className:"p-2",maxHeightClass:"max-h-[46vh]"})})}return c.jsxs("div",{className:R("oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4"),children:[e.tool==="question"?O():c.jsxs(c.Fragment,{children:[A?c.jsx("div",{className:"my-1",children:L(e.tool==="bash"?c.jsx("pre",{className:"tool-input-text whitespace-pre-wrap break-words typography-code text-muted-foreground m-0 p-0",children:T}):j&&M?c.jsx(Nx,{diff:M,diffViewMode:i}):c.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-subtle-foreground",children:T}),{maxHeightClass:j&&M&&r?"max-h-[50vh]":"max-h-60",className:e.tool==="bash"?"tool-input-surface p-0 rounded-none":"tool-input-surface"})}):null,D&&c.jsxs("div",{children:[(e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&w?c.jsx("div",{className:"mb-1 flex items-center justify-end gap-2",children:c.jsx(yW,{mode:i,onModeChange:a,className:"h-5 w-5 p-0"})}):null,O()]}),t.status==="error"&&"error"in t&&c.jsxs("div",{children:[c.jsx("div",{className:"typography-meta font-medium text-subtle-foreground mb-1",children:"Error:"}),c.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:vn(t.error)})]})]}),Array.isArray(S)&&S.length>0&&t.status==="completed"?c.jsx(k1,{files:S,onShowPopup:s,compact:!0}):null]})});Y7.displayName="ToolExpandedContent";const ql=[];let xa;const X7=()=>{for(;ql.length>0;){const e=ql.pop();if(!e)break;if(e.active){e.fn(),xa=ql.length>0?window.requestAnimationFrame(X7):void 0;return}}xa=void 0},FW=e=>{if(typeof window>"u")return e(),()=>{};const t={active:!0,fn:e};return ql.push(t),xa===void 0&&(xa=window.requestAnimationFrame(()=>{xa=window.requestAnimationFrame(X7)})),()=>{t.active=!1}},Lx=e=>{const[t,n]=p.useState(e),r=p.useRef(!1);return p.useEffect(()=>{if(!e){r.current=!0,n(!1);return}if(!r.current){r.current=!0,n(!0);return}return FW(()=>{n(!0)})},[e]),t},BW=new Set(["bash","edit","write","apply_patch","patch"]),VW=(e,t,n=Date.now())=>{const s=Math.max(0,(t??n)-e)/1e3;return`${(s<.05&&t!==void 0?.1:s).toFixed(1)}s`},Rx=({start:e,end:t,active:n})=>{const r=I7(n,250);return c.jsx(c.Fragment,{children:VW(e,t,r)})},Px=(e,t)=>{if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},$W=(e,t)=>Px(e.call,t.call)&&Px(e.result,t.result),zW=p.memo(({call:e,result:t})=>{const n=Array.isArray(e)&&e.length>0,r=Array.isArray(t)&&t.length>0;return!n&&!r?null:c.jsxs("div",{className:R("my-1 ml-5 overflow-x-auto rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2","font-mono typography-code whitespace-pre max-h-80 overflow-y-auto"),"data-chat-tool-extension-render":"true",children:[n&&e.map((s,o)=>c.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:c.jsx(qt,{text:s})},`call-${o}`)),r&&t.map((s,o)=>c.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:c.jsx(qt,{text:s})},`res-${o}`))]})},$W),UW=({part:e,isExpanded:t,onToggle:n,isMobile:r,onContentChange:s,onShowPopup:o,animateTailText:i=!0})=>{const a=he(le=>le.currentSessionId),l=e.state?.deferredBody===!0,d=u_(a,e.id,t&&l),f=t&&d&&d.type==="tool"?d:e,u=f.state,h=u,m=h.metadata,g=h.input,x=Jn()??"",b=u?.render,S=!!(b&&(Array.isArray(b.call)&&b.call.length>0||Array.isArray(b.result)&&b.result.length>0||Array.isArray(b.resultExpanded)&&b.resultExpanded.length>0)),y=Fs(e.tool),v=y==="task",C=u?.status,w=C==="completed"||C==="error"||C==="aborted"||C==="failed"||C==="timeout"||C==="cancelled",I=C==="completed",E=C==="error"||C==="failed",[T,A]=p.useState(!w),j=p.useRef(e.id),k=p.useRef(!w);p.useEffect(()=>{j.current!==e.id&&(j.current=e.id,k.current=!w,A(!w))},[w,e.id]),p.useEffect(()=>{w||A(!0)},[w]),p.useEffect(()=>{if(!w){k.current=!0;return}if(!k.current)return;if(!I||!BW.has(y)){k.current=!1;return}if(!x)return;k.current=!1;const J=gq(y,g,m).map(ne=>Gn(ne,x));Cu.requestGitRefresh({directory:x,...J.length>0?{paths:J}:{}})},[x,g,w,I,m,y]);const _=w||v||S,M=p.useRef(s);M.current=s;const L=p.useRef(null);p.useLayoutEffect(()=>{if(v||S)return;const le=L.current;le&&(le.style.height=t?"auto":"0px",le.style.overflow=t?"visible":"hidden",_&&M.current?.("structural"))},[S,t,v,_]);const O=p.useRef(t);p.useEffect(()=>{const le=O.current!==t;O.current=t,!(!S||!t&&!le)&&M.current?.("structural")},[S,t,b?.call,b?.result,b?.resultExpanded]);const N=e.metadata,D=h.time,[W,z]=p.useState(()=>({start:typeof D?.start=="number"?D.start:void 0,end:typeof D?.end=="number"?D.end:void 0})),[X,F]=p.useState(void 0),[U,P]=p.useState(void 0);p.useEffect(()=>{z({}),F(void 0),P(void 0)},[e.id]),p.useEffect(()=>{w||typeof D?.start!="number"&&F(le=>le??Date.now())},[w,D?.start]),p.useEffect(()=>{z(le=>{const J={...le};let ne=!1;return typeof D?.start=="number"&&(typeof le.start!="number"||D.start<le.start)&&(J.start=D.start,ne=!0),typeof D?.end=="number"&&(typeof le.end!="number"||D.end>le.end)&&(J.end=D.end,ne=!0),ne?J:le})},[D?.end,D?.start]);const q=p.useMemo(()=>{const le=[W.start,D?.start].filter(J=>typeof J=="number");return le.length>0?Math.min(...le):X},[X,W.start,D?.start]),B=p.useMemo(()=>typeof h.output=="string"?h.output:void 0,[h.output]),ee=p.useMemo(()=>V7(B),[B]),G=p.useMemo(()=>{if(!v)return[];const le=m,J=B7(le?.summary??le?.entries??le?.tools??le?.calls);return J.length>0?J:ee.summaryEntries},[v,m,ee.summaryEntries]),K=w&&G.length>0,se=p.useMemo(()=>{if(!v)return;const le=wx(m);if(le)return le;const J=wx(N);return J||(ee.sessionId?ee.sessionId:Hq(B))},[v,m,ee.sessionId,N,B]);p.useEffect(()=>{if(typeof D?.end=="number"||typeof W.end=="number"){P(void 0);return}typeof q=="number"&&w&&P(le=>le??Date.now())},[q,w,W.end,D?.end]);const de=w?W.end??D?.end??U:void 0,oe=!w&&T,ue=w,ye=Oq({isTaskTool:v,isExpanded:t,isActive:oe,hasFinalMetadataSummary:K,taskSessionId:se})?se??"":"",we=fu(ye);p_(ye);const Me=p.useMemo(()=>!v||!se?[]:!Array.isArray(we)||we.length===0?[]:Vq(we),[we,v,se]),He=p.useMemo(()=>Me.length>0?Me:G,[Me,G]),Ae=p.useMemo(()=>He.map(Zo).join("\0"),[He]),Ge=p.useRef(null);p.useEffect(()=>{if(!v){Ge.current=null;return}const le=Ge.current;Ge.current=Ae,!(le===null||le===Ae||He.length===0)&&M.current?.("structural")},[v,He.length,Ae]);const et=p.useMemo(()=>y==="edit"||y==="multiedit"||y==="apply_patch"?Lq(m):null,[m,y]),Xe=p.useMemo(()=>y==="write"?Rq(g):null,[g,y]),te=y==="apply_patch"&&Array.isArray(m?.files)&&(m?.files).length>1,Q=y!==e.tool?{...e,tool:y}:e,me=u?H7(Q,u,x):void 0,Se=u?Dq(Q,u,x):void 0,_e=Ka(y||e.tool||"").displayName,Fe=p.useMemo(()=>{if(y==="bash"||y==="apply_patch"||y==="lsp"||me&&(y==="apply_patch"||y==="edit"||y==="multiedit"||y==="write"))return null;const le=h.title;if(typeof le=="string"&&le.trim().length>0)return le;const J=g?.description;return typeof J=="string"&&J.trim().length>0?J:null},[me,y,h,g]),ht=!!(Fe||Se||et||Xe),ge=p.useContext($a),Ze=(le,J)=>{ge?.editor&&(J.stopPropagation(),qq({currentDirectory:x,editor:ge.editor,file:le}))},Ve=le=>{if(v||S||!ge?.editor){n(e.id);return}let J,ne;if(y==="edit"||y==="multiedit")J=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path,typeof J=="string"&&(ne=xx(y,m,J));else if(y==="apply_patch")J=eg(y,g,m),typeof J=="string"&&(ne=xx(y,m,J));else if(["write","create","file_write"].includes(y))J=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path;else if(y==="lsp"){J=g?.filePath||g?.file_path||g?.path;const fe=g?.line;ne=typeof fe=="number"&&Number.isFinite(fe)?Math.trunc(fe):void 0}if(typeof J=="string"){le.stopPropagation();const fe=Za(x,J);ge.editor.openFile(fe,ne)}else n(e.id)},ie=le=>{le.key!=="Enter"&&le.key!==" "||(le.preventDefault(),Ve(le))},ke=!v&&E?y7:v7,ve=!v&&E?x7:ti,xe=Lx(v&&(He.length>0||oe||ue||!!se)),je=Lx(!v&&!S&&t);return!ue&&!oe&&!v?null:c.jsxs("div",{children:[c.jsxs("div",{className:R("group/tool flex w-full min-w-0 gap-x-1.5 rounded-md pr-2 pl-px py-1 transition-colors hover:bg-[var(--interactive-hover)]",te?"flex-wrap items-start cursor-pointer":"items-center cursor-pointer"),"data-chat-activity-row":"true",onClick:te?()=>n(e.id):Ve,onKeyDown:te?le=>{le.target===le.currentTarget&&(le.key!=="Enter"&&le.key!==" "||(le.preventDefault(),n(e.id)))}:ie,role:"button",tabIndex:0,children:[c.jsx("div",{className:R("flex min-w-0",te?"w-full flex-wrap items-center gap-x-2 gap-y-0.5":"flex-shrink-0 items-center gap-x-1.5"),children:te?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex h-5 flex-shrink-0 items-center gap-1.5",children:[c.jsxs("span",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[c.jsx("span",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",t?"opacity-0":"group-hover/tool:opacity-0"),style:ke,children:Ra(y||e.tool)}),c.jsx(V,{name:t?"arrow-down-s":"arrow-right-s",className:R("absolute inset-0 h-3.5 w-3.5 transition-opacity",t?"opacity-100":"opacity-0 group-hover/tool:opacity-100")})]}),c.jsx(Pd,{active:!!(oe&&!E),minDurationMs:300,className:R(Gr,"flex-shrink-0"),style:ve,children:_e})]}),c.jsx(Uq,{metadata:m,animate:i,showFileIcons:!0,textClassName:Mt,openDiffLabel:"Open file diff",onFileClick:ge?.editor?Ze:void 0}),typeof q=="number"?c.jsx("span",{className:R("ml-auto flex-shrink-0 tabular-nums text-subtle-foreground",Mt),"aria-label":"Tool duration",children:c.jsx(Rx,{start:q,end:typeof de=="number"?de:void 0,active:!!(oe&&typeof de!="number")})}):null]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"relative h-5 w-3.5 flex-shrink-0 cursor-pointer",onClick:le=>{le.stopPropagation(),n(e.id)},children:[c.jsx("div",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",t&&"opacity-0",!t&&"group-hover/tool:opacity-0"),style:ke,children:Ra(y||e.tool||"")}),c.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",t&&"opacity-100",!t&&"opacity-0 group-hover/tool:opacity-100"),children:t?c.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):c.jsx(V,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),c.jsx("div",{className:"flex min-w-0 flex-shrink-0 items-center gap-x-1.5",children:c.jsx(Pd,{active:!!(oe&&!E),minDurationMs:300,className:R(Gr,"flex-shrink-0"),style:ve,title:_e,children:_e})})]})}),!te&&ht?c.jsx("div",{className:R("flex min-w-0 flex-1 items-center",Mt),style:{color:"var(--tools-description)"},children:c.jsx("span",{className:R("inline-flex min-w-0 max-w-full items-center gap-1 overflow-hidden rounded-md bg-[var(--surface-subtle)] px-1.5 py-0.5",Mt),children:c.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-hidden",children:[Fe&&c.jsx("span",{className:R("min-w-0 truncate",Mt),style:{color:"var(--tools-description)",opacity:.8},title:Fe,children:Fe}),!Fe&&y==="lsp"&&me?c.jsx(rm,{path:me,animate:i,grow:!1,showFileIcons:!0}):null,!Fe&&y!=="lsp"&&Se&&(me&&Se===me?c.jsx(rm,{path:me,animate:i,grow:!1,showFileIcons:!0}):c.jsx(mr,{variant:i?"generate-effect":"static",className:R("min-w-0 truncate",Mt),style:{color:"var(--tools-description)"},title:Se,children:Se})),et&&c.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:[c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",et.added]}),c.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",et.removed]})]}),Xe&&c.jsx("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",Xe]})})]})})}):null,!te&&typeof q=="number"?c.jsx("span",{className:R("ml-auto flex-shrink-0 tabular-nums text-subtle-foreground",Mt),"aria-label":"Tool duration",children:c.jsx(Rx,{start:q,end:typeof de=="number"?de:void 0,active:!!(oe&&typeof de!="number")})}):null]}),S&&t?c.jsx(zW,{call:b?.call,result:b?.resultExpanded&&b.resultExpanded.length>0?b.resultExpanded:b?.result}):null,xe?c.jsx(Zq,{entries:He,isExpanded:t,isMobile:r,output:B,sessionId:se,onShowPopup:o,input:g,animateTailText:i,isActive:oe}):null,!v&&!S?c.jsx("div",{ref:L,"aria-hidden":!t,style:{height:t?"auto":"0px",overflow:t?"visible":"hidden",overflowAnchor:"none"},children:je?c.jsxs("div",{className:"relative ml-2 pl-3","data-chat-tool-indent":"true",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute left-0 top-px bottom-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),u?c.jsx(Y7,{part:f,state:u,currentDirectory:x,isExpanded:t,onShowPopup:o}):null]}):null}):null]})};class qW extends p.Component{state={hasError:!1};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:!1,error:void 0})}componentDidCatch(t){}render(){if(!this.state.hasError)return this.props.children;const t=this.state.error?.message;return c.jsxs("div",{className:"flex items-center gap-1.5 pr-2 pl-px py-1 min-w-0","data-chat-activity-row":"true",children:[c.jsx("div",{className:"h-3.5 w-3.5 flex-shrink-0",style:y7,children:Ra(this.props.toolName)}),c.jsx("span",{className:R(Gr,"flex-shrink-0"),style:x7,children:this.props.displayName}),t?c.jsxs("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:t,children:[this.props.errorLabel,": ",t]}):null]})}}const WW=e=>{const t=Fs(e.part.tool)||"tool",n=Ka(t).displayName;return c.jsx(qW,{displayName:n,errorLabel:"Error:",resetKey:e.part,toolName:t,children:c.jsx(UW,{...e})})},KW=p.memo(WW,(e,t)=>Tu([e.part],[t.part])&&e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.alwaysShowActions===t.alwaysShowActions&&e.onContentChange===t.onContentChange&&e.onShowPopup===t.onShowPopup&&e.animateTailText===t.animateTailText),J7=p.createContext(!1),Dx=({disabled:e,children:t})=>c.jsx(J7.Provider,{value:e,children:t}),rg=({children:e,className:t,skipAnimation:n,forceAnimation:r=!1,ignoreContextDisabled:s=!1,respectReducedMotion:o=!1})=>{const i=p.useContext(J7),a=o&&typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,l=!!n||!s&&i||a,d=r,f=p.useRef(null);f.current===null&&(f.current=d&&!l);const u=f.current,[h,m]=p.useState(!u);return p.useEffect(()=>{if(!u)return;let g=null;const x=()=>m(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?g=window.requestAnimationFrame(x):x(),()=>{g!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(g)}},[u]),u?c.jsx("div",{className:R("w-full transition-all duration-300 ease-out",h?"opacity-100 translate-y-0":"opacity-0 translate-y-2",t),children:e}):c.jsx(c.Fragment,{children:e})},GW=4e3,po=new Map,Q7=e=>{const t=po.get(e);return t?new Set(t):new Set},ZW=(e,t)=>{if(po.size>=GW&&!po.has(e)){const n=po.keys().next().value;typeof n=="string"&&po.delete(n)}po.set(e,new Set(t))},YW=e=>{const t=new Set,n=new Map;for(const r of e){const s=n.get(r.messageId)??new Set;s.add(r.id),n.set(r.messageId,s)}for(const[r,s]of n){const o=Q7(r);for(const i of s)o.has(i)&&t.add(i)}return t},XW=({messageId:e,ownerToolIds:t,nextValue:n,read:r,write:s})=>{const o=r(e);for(const i of t)n.has(i)?o.add(i):o.delete(i);s(e,o)};function JW({activities:e}){const t=re(g=>g.setImagePreviewOpen),n=p.useMemo(()=>e.filter(g=>g.kind==="tool"&&g.part.type==="tool"),[e]),r=p.useMemo(()=>{const g=new Map;for(const x of n)g.set(x.id,x.messageId);return g},[n]),s=p.useMemo(()=>{const g=new Map;for(const x of n){const b=g.get(x.messageId)??new Set;b.add(x.id),g.set(x.messageId,b)}return g},[n]),[o,i]=p.useState(()=>YW(n)),[a,l]=p.useState({open:!1,title:"",content:""}),d=o,f=p.useRef({ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d});f.current={ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d};const u=p.useCallback(g=>{const x=f.current,b=x.ownerByToolId.get(g);if(!b)return;const S=x.toolIdsByOwner.get(b)??new Set;i(y=>{const v=new Set(y);return v.has(g)?v.delete(g):v.add(g),XW({messageId:b,ownerToolIds:S,nextValue:v,read:Q7,write:ZW}),v})},[]),h=p.useCallback(g=>{(g.image||g.mermaid)&&(l(g),t(!0))},[t]),m=p.useCallback(g=>{l(x=>({...x,open:g})),t(g)},[t]);return{effectiveExpandedTools:d,popupContent:a,handleToggleTool:u,handleShowPopup:h,handlePopupChange:m}}const QW=Hs(()=>mt(()=>import("./ToolOutputDialog-aR4kcgKL.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),eK=e=>{const t=p.useRef(e),[n,r]=p.useState(e);return e&&(t.current=!0),p.useEffect(()=>{const s=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;let o;return e?s||typeof requestAnimationFrame!="function"?r(!0):o=requestAnimationFrame(()=>r(!0)):r(!1),()=>{o!==void 0&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(o)}},[e]),{isMounted:t.current,isVisible:n}},tK=({activity:e,isLiveTurn:t,activeStreamingMessageId:n,activeStreamingPhase:r})=>t&&n&&e.messageId===n?r??"streaming":"completed",e9=p.memo(({activity:e,animate:t,isExpanded:n,isMobile:r,onContentChange:s,onToggle:o,onShowPopup:i})=>{const a=Fs(e.part.tool),l=Mq(a)?c.jsx(KW,{part:e.part,isExpanded:n,onToggle:o,isMobile:r,alwaysShowActions:r,onContentChange:s,onShowPopup:i,animateTailText:t}):c.jsx(VU,{toolName:a,activity:e,animateTailText:t});return c.jsx(rg,{children:c.jsx($7,{animate:t,children:l})})},(e,t)=>e.activity.id===t.activity.id&&e.activity.messageId===t.activity.messageId&&e.activity.endedAt===t.activity.endedAt&&Tu([e.activity.part],[t.activity.part])&&e.animate===t.animate&&e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.onContentChange===t.onContentChange&&e.onToggle===t.onToggle&&e.onShowPopup===t.onShowPopup);e9.displayName="TurnToolActivityRow";const nK=({turn:e,isExpanded:t,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s,onContentChange:o})=>{const{isMobile:i}=On(),[a,l]=p.useState(eU),d=eK(t),f=p.useRef(o);f.current=o;const u=p.useCallback(T=>{f.current?.(T)},[]),h=e.activityParts,m=p.useMemo(()=>h.reduce((T,A)=>T+(A.kind==="tool"?1:0),0),[h]),g=p.useMemo(()=>nU(h,a),[h,a]),{effectiveExpandedTools:x,popupContent:b,handleToggleTool:S,handleShowPopup:y,handlePopupChange:v}=JW({activities:h}),C=p.useMemo(()=>h.filter(T=>T.kind==="tool").map(T=>T.id),[h]),w=p.useRef({turnId:e.turnId,committed:!1,knownToolIds:new Set,animatedToolIds:new Set});if(w.current.turnId!==e.turnId&&(w.current={turnId:e.turnId,committed:!1,knownToolIds:new Set,animatedToolIds:new Set}),n&&w.current.committed)for(const T of C)w.current.knownToolIds.has(T)||w.current.animatedToolIds.add(T);p.useEffect(()=>{const T=w.current;for(const A of C)T.knownToolIds.add(A);T.committed=!0},[C]);const I=p.useCallback(()=>{l(T=>Math.min(m,T+tU)),u("structural")},[u,m]),E=p.useCallback(T=>{const A=tK({activity:T,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s}),j=w.current.animatedToolIds.has(T.id);return T.kind==="reasoning"?c.jsx(gU,{part:T.part,messageId:T.messageId,streamPhase:A,onContentChange:u,withinActivityRail:!0},T.id):T.kind==="justification"?c.jsx(g7,{part:T.part,messageId:T.messageId,streamPhase:A,onContentChange:u,withinActivityRail:!0},T.id):T.part.type!=="tool"?null:c.jsx(e9,{activity:T,animate:j,isExpanded:x.has(T.id),isMobile:i,onContentChange:u,onToggle:S,onShowPopup:y},T.id)},[r,s,x,y,S,n,i,u]);return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"chat-message-column",children:c.jsx("div",{id:`turn-${e.turnId}-activity`,className:"relative min-w-0 pl-[18px]","data-turn-activity-rail":"true","data-turn-activity-expanded":t?"true":"false","aria-hidden":!t,children:d.isMounted?c.jsxs("div",{className:R("relative grid origin-top transition-[grid-template-rows,opacity,transform] duration-200 ease-out motion-reduce:transition-none motion-reduce:transform-none",d.isVisible?"grid-rows-[1fr] translate-y-0 opacity-100":"grid-rows-[0fr] -translate-y-1 opacity-0"),"data-turn-activity-panel":"true","data-turn-activity-visible":d.isVisible?"true":"false",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 -left-[18px] top-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),c.jsxs("div",{className:"relative min-h-0 overflow-hidden",children:[t&&g.hiddenToolCount>0?c.jsx(be,{type:"button",variant:"ghost",size:"xs",className:"-ml-1.5 mb-0.5 justify-start px-1.5 text-muted-foreground","aria-label":"Load earlier activity",onClick:I,children:"Load earlier activity"}):null,c.jsx("div",{className:"min-w-0 space-y-1","data-chat-activity-list":"true",children:g.activities.map(E)})]})]}):null})}),b.open?c.jsx(p.Suspense,{fallback:null,children:c.jsx(QW,{popup:b,onOpenChange:v,isMobile:i})}):null]})},rK=p.memo(nK),Wl=new Map,sK=(e,t)=>{const n=Wl.get(e);if(!n)return!1;let r=!1;for(const s of n)r=s(t)||r;return r},oK=(e,t)=>{const n=Wl.get(e)??new Set;return n.add(t),Wl.set(e,n),()=>{n.delete(t),n.size===0&&Wl.delete(e)}},iK=e=>e.filter(r=>r?.type==="text").map(r=>(r.text||r.content||"").trim()).filter(r=>r.length>0).join(`
|
|
192
|
+
`).replace(/\n\s*\n+/g,`
|
|
193
|
+
`),aK="Authentication failed for this provider. Please re-authenticate and retry.",cK=e=>{if(typeof e!="string")return!1;const 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;const n=t.includes("oauth"),r=t.includes("failed")||t.includes("invalid")||t.includes("expired");if(n&&r)return!0;const s=/\b401\b/.test(t),o=t.includes("auth")||t.includes("token")||t.includes("unauthorized");return s&&o},t9=e=>{const t=e?.error;if(!t)return;const n=typeof t.data?.message=="string"?t.data.message:void 0,r=typeof t.message=="string"?t.message:void 0,s=typeof t.name=="string"?t.name:void 0,o=n||r||s;if(o){if(s==="SessionRetry")return{text:`Retrying after an error:
|
|
194
|
+
\`${o}\``,variant:"info"};if(s==="SessionCompaction"){const i=t.data?.phase,a=t.data?.reason;if(i==="running")return{text:a==="threshold"?"Context is nearly full. Compacting automatically...":a==="overflow"?"Context limit reached. Compacting before retrying...":"Compacting session context...",variant:"info"};if(i==="retrying"){const d=typeof t.data?.attempt=="number"?t.data.attempt:void 0,f=typeof t.data?.maxAttempts=="number"?t.data.maxAttempts:void 0,u=d&&f?` (${d}/${f})`:"",h=typeof t.data?.message=="string"&&t.data.message.trim()?`
|
|
195
|
+
\`${t.data.message.trim()}\``:"";return{text:`Compaction failed temporarily. Retrying${u}...${h}`,variant:"info"}}if(i==="completed"){const d=typeof t.data?.tokensBefore=="number"?t.data.tokensBefore:void 0,f=typeof t.data?.estimatedTokensAfter=="number"?t.data.estimatedTokensAfter:void 0,u=d!==void 0&&f!==void 0?`
|
|
196
|
+
${d.toLocaleString()} → approximately ${f.toLocaleString()} tokens`:"",h=t.data?.willRetry===!0?`
|
|
197
|
+
Retrying the interrupted turn.`:"";return{text:`Session compacted${u}${h}`,variant:"info"}}return i==="aborted"?{text:"Compaction stopped.",variant:"info"}:{text:`Compaction failed.${typeof t.data?.message=="string"&&t.data.message.trim()?`
|
|
198
|
+
\`${t.data.message.trim()}\``:""}`,variant:"error"}}return cK(o)?{text:aK,variant:"error"}:o.trim().toLowerCase()==="aborted"?{text:"The running turn was stopped before the next message could be sent.",variant:"info"}:{text:`Failed to send message with error:
|
|
199
|
+
\`${o}\``,variant:"error"}}},lK=({isUser:e,displayParts:t,assistantErrorText:n})=>{if(e){const r=t.filter(a=>a.type==="text").map(a=>{const l=a.shellAction?.output;return typeof l=="string"?l.trim():""}).filter(a=>a.length>0);if(r.length>0)return r.join(`
|
|
200
|
+
|
|
201
|
+
`);const s=t.filter(a=>a.type==="text").map(a=>{const l=a.shellAction?.command;return typeof l=="string"?l.trim():""}).filter(a=>a.length>0);return s.length>0?s.join(`
|
|
202
|
+
`):t.filter(a=>a.type==="text").map(a=>(a.text||a.content||"").trim()).filter(a=>a.length>0).join(`
|
|
203
|
+
`).replace(/\n\s*\n+/g,`
|
|
204
|
+
`)}return n&&n.trim().length>0?n:iK(t)},n9=e=>e.type==="subtask",r9=e=>{const t=e;return t.type==="text"&&typeof t.shellAction=="object"&&t.shellAction!==null},dK=e=>!!(e&&typeof e=="object"&&typeof e.type=="string"),Au=e=>e.filter(dK),sg=e=>{const t=e,n=t.text;return typeof n=="string"?n:t.content||t.value||""},s9=e=>{if(e.type!=="text")return!1;const t=sg(e);return!t||t.trim().length===0},o9=e=>e.type==="text"?!s9(e):n9(e)||r9(e),og=e=>e.filter(t=>s9(t)?!1:t.type!=="compaction"),i9=(e,t,n)=>e.filter((r,s)=>{if(r.type==="tool"||r.type==="reasoning")return!1;if(r.type!=="text")return!0;const o=r.id??`${n}-part-${s}-${r.type}`;return!t.has(o)}),uK=(e,t)=>typeof t=="string"&&t.trim().length>0?!0:og(e).length>0,ig=(e,t={})=>{const{includeReasoning:n=!0}=t,r=Au(e),s=r.some(o=>!o.synthetic);return r.filter(o=>{const a=!!o.synthetic;return a&&o.type==="text"&&sg(o).includes("<system-reminder>")||a&&s||!n&&o.type==="reasoning"?!1:!(o.type==="patch")})},fK=(e,t)=>{const n=t9(e.info)?.text;if(typeof n=="string"&&n.trim().length>0)return!0;const r=ig(e.parts),s=i9(r,t,e.info.id);return og(s).length>0},_h=32,Ox=32,hK=({turnId:e,assistantMessages:t,renderMessage:n,deferEarlierMessages:r,activityPartIds:s})=>{const[o,i]=p.useState(_h),a=t[0],l=p.useMemo(()=>t.filter(y=>fK(y,s)),[s,t]),d=p.useMemo(()=>l.filter(y=>y!==a),[l,a]),f=r&&l.length>_h,u=f?Math.max(0,o-1):d.length,h=u>=d.length?d:d.slice(-u),m=d.length-h.length;p.useEffect(()=>{i(_h)},[e]),p.useEffect(()=>oK(e,y=>{if(a?.info.id===y)return!0;const v=d.findIndex(w=>w.info.id===y);if(v<0)return!1;const C=d.length-h.length;return!f||v>=C||i(w=>Math.max(w,d.length-v+1)),!0}),[d,a,f,e,h.length]);const g=p.useCallback(()=>{i(y=>Math.min(d.length+1,y+Ox))},[d.length]),x=p.useCallback(()=>{i(d.length+1)},[d.length]),b=p.useCallback(y=>c.jsx(pK,{message:y,renderMessage:n},y.info.id),[n]);if(!f||m===0)return c.jsxs("div",{className:"relative z-0",children:[a?b(a):null,d.map(b)]});const S=m>Ox;return c.jsxs("div",{className:"relative z-0",children:[a?b(a):null,c.jsxs("div",{className:"chat-message-column flex flex-wrap items-center justify-center gap-2 py-3",children:[c.jsxs(be,{type:"button",variant:"secondary",size:"sm",onClick:g,"aria-label":"Load earlier response",className:"gap-1.5 rounded-full px-3.5",children:[c.jsx(V,{name:"history",className:"size-3.5"}),"Load earlier response"]}),S?c.jsx(be,{type:"button",variant:"ghost",size:"sm",onClick:x,"aria-label":"Load full response",className:"rounded-full px-3.5 text-[var(--surface-mutedForeground)]",children:"Load full response"}):null]}),h.map(b)]})},pK=p.memo(function({message:t,renderMessage:n}){return n(t)},(e,t)=>e.message===t.message),mK=p.memo(hK),gK="GitHub issue context (JSON)",yK="GitHub pull request context (JSON)",Zi=e=>!e||typeof e!="object"?!1:!!e.synthetic,vK=e=>!Array.isArray(e)||e.length===0?!1:e.every(t=>Zi(t)),xK=e=>{if(!Array.isArray(e)||e.length===0)return[];const t=e.some(r=>!Zi(r)),n=r=>{if(!Zi(r)||r.type!=="text")return!1;const s=r.text;if(typeof s!="string")return!1;const o=s.trimStart();return o.startsWith(gK)||o.startsWith(yK)};return t&&e.some(s=>Zi(s))?e.filter(s=>!Zi(s)||n(s)):e},bK={activity:"idle",hasWorkingContext:!1,hasActiveTools:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,lifecyclePhase:null,statusText:null,isGenericStatus:!0,isWaitingForPermission:!1,canAbort:!1,compactionDeadline:null,activePartType:void 0,activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,retryInfo:null},wK=new Map,a9="\0",SK=new Set(["apply_patch","create","edit","file_write","multiedit","str_replace","str_replace_based_edit_tool","write"]),CK={read:"reading files",view:"reading files",file_read:"reading files",cat:"reading files",write:"editing files",create:"editing files",file_write:"editing files",edit:"editing files",multiedit:"editing files",apply_patch:"editing files",str_replace:"editing files",str_replace_based_edit_tool:"editing files",bash:"executing commands",shell:"executing commands",cmd:"executing commands",terminal:"executing commands",grep:"searching code",search:"searching code",find:"searching files",ripgrep:"searching code",glob:"searching files",list:"listing files",ls:"listing files",dir:"listing files",list_files:"listing files",task:"delegating work",subagent:"delegating work",webfetch:"fetching a URL",fetch:"fetching a URL",websearch:"searching the web",web_search:"searching the web",search_web:"searching the web",codesearch:"searching code",todowrite:"updating tasks",todoread:"reviewing tasks",skill:"loading a skill",question:"waiting for input",lsp:"inspecting code",structuredoutput:"formatting the response",structured_output:"formatting the response",pichamber:"working in PiChamber",plan_enter:"switching to planning",plan_exit:"switching to building"},Hx=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],c9=e=>{const t=e.trim().toLowerCase().replace(/:\d+$/,"");if(!t.includes("."))return t;const n=t.split(".").filter(Boolean);return n[n.length-1]??t},kK=e=>{const t=c9(e);return CK[t]??`using ${t.replaceAll("_"," ")}`},MK=e=>{let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)},IK=e=>Hx[MK(e)%Hx.length]??"working",Fx=(e,t,n)=>{for(let r=t.length-1;r>=0;r-=1){const s=t[r],o=s?e.get(s):void 0;if(o){if(o.type==="tool"&&(o.tool?.state==="running"||o.tool?.state==="pending")){const i=c9(o.tool.name);return{activePartType:SK.has(i)?"editing":"tool",activeToolName:i,statusText:kK(i),isGenericStatus:!1}}if(o.type==="thinking"&&o.streaming)return{activePartType:"reasoning",activeToolName:void 0,statusText:"thinking",isGenericStatus:!1};if(o.type==="text"&&o.streaming&&o.text.trim().length>0)return{activePartType:"text",activeToolName:void 0,statusText:"writing response",isGenericStatus:!1}}}return{activePartType:void 0,activeToolName:void 0,statusText:IK(n),isGenericStatus:!0}},EK=e=>[e.activePartType??"",e.activeToolName??"",e.statusText,e.isGenericStatus?"1":"0"].join(a9),_K=e=>{const[t,n,r="working",s]=e.split(a9);return{activePartType:t==="text"||t==="tool"||t==="reasoning"||t==="editing"?t:void 0,activeToolName:n||void 0,statusText:r,isGenericStatus:s==="1"}},jK=e=>{let t=null,n=null;for(let r=e.length-1;r>=0;r-=1){const s=e[r];if(s?.role!=="assistant")continue;const o=s;t=s.id,n=typeof o.parentID=="string"&&o.parentID.trim().length>0?o.parentID:null;break}if(!t||!n)return{assistantId:t,model:null};for(let r=e.length-1;r>=0;r-=1){const s=e[r];if(s?.role!=="user"||s.id!==n)continue;const o=s,i=typeof o.model?.providerID=="string"?o.model.providerID.trim():"",a=typeof o.model?.modelID=="string"?o.model.modelID.trim():"";return{assistantId:t,model:i&&a?{providerId:i,modelId:a}:null}}return{assistantId:t,model:null}};function l9(){const e=he(b=>b.currentSessionId);he(b=>b.currentSessionDirectory);const t=Jm(e??""),n=p.useMemo(()=>jK(t),[t]),r=n.assistantId,s=Be(p.useCallback(b=>{const S=`${e??""}:${r??""}`,y=e?b.reducer.bySession.get(e):void 0,v=Ma(y)??r,C=v?y?.partOrder.get(v)??[]:[],w=y?Fx(y.parts,C,S):Fx(wK,[],S);return EK(w)},[e,r]),void 0,e?`session:${e}`:"chrome"),o=he(p.useCallback(b=>e?b.sessionAbortFlags?.get(e)??null:null,[e])),{phase:i,isWorking:a}=f1(),l=du(e??""),d=l?.type==="retry"?l.attempt:void 0,f=l?.type==="retry"?l.next:void 0,u=p.useMemo(()=>_K(s),[s]),h=p.useMemo(()=>{const b=!!(o&&!o.acknowledged);return{wasAborted:b,abortActive:b}},[o]),m=p.useMemo(()=>{if(h.wasAborted)return{...bK,wasAborted:!0,abortActive:h.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1,retryInfo:null};const b=a,S=i==="busy",y=!1,v=i==="retry";let C="idle";b&&(u.activePartType==="tool"||u.activePartType==="editing"?C="tooling":C="streaming");const w=v?{attempt:d,next:f}:null;return{activity:C,hasWorkingContext:b,hasActiveTools:u.activePartType==="tool"||u.activePartType==="editing",isWorking:b,isStreaming:S,isCooldown:y,lifecyclePhase:S?"streaming":null,statusText:b?u.statusText:null,isGenericStatus:b?u.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:b,compactionDeadline:null,activePartType:b?u.activePartType:void 0,activeToolName:b?u.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,retryInfo:w}},[i,a,u,h,d,f]),g=p.useMemo(()=>({isActive:a&&u.activePartType==="text",characterCount:0}),[a,u.activePartType]),x=m;return{activeModel:n.model,forming:g,working:x}}const TK=({startedAt:e,completedAt:t,durationMs:n})=>typeof n=="number"&&Number.isFinite(n)&&n>=0?n:typeof e=="number"&&typeof t=="number"&&Number.isFinite(e)&&Number.isFinite(t)&&t>=e?t-e:null,AK=e=>{const t=Math.max(.1,e/1e3);if(t<60)return`${t.toFixed(1)}s`;const n=Math.floor(t/60),r=Math.round(t%60);return`${n}m ${r}s`},d9=p.memo(({isWorking:e,startedAt:t,statusText:n})=>{const r=he(h=>h.currentSessionId),s=Be(p.useCallback(h=>(r?h.reducer.bySession.get(r):void 0)?.extensionWorking,[r]),(h,m)=>h?.message===m?.message&&h?.visible===m?.visible,r?`session:${r}`:"chrome"),{activeModel:o,working:i}=l9(),a=Wb(r??""),l=We(h=>h.providers),d=p.useMemo(()=>{if(!o)return null;const h=l.find(m=>m.id===o.providerId);return _1(h,o.modelId)||null},[o,l]);if(s?.visible===!1)return null;const f=s?.message?Nn(s.message):n??i.statusText,u=s?.message||n?!1:i.isGenericStatus;return c.jsx(X3,{isWorking:e||i.isWorking,statusText:f,isGenericStatus:u,isWaitingForPermission:i.isWaitingForPermission,retryInfo:i.retryInfo,modelName:d,providerId:o?.providerId??null,startedAt:n?t??a??null:a??t??null})});d9.displayName="LiveTurnStatus";const NK=({turnId:e,isLiveTurn:t,isWorking:n,isAwaitingRecovery:r=!1,hasActivity:s,isActivityExpanded:o,onToggleActivity:i,startedAt:a,completedAt:l,durationMs:d,liveStatusText:f,wasSteered:u})=>{const h=TK({startedAt:a,completedAt:l,durationMs:d}),m=!t&&r,g=t?"Agent working":m?"Reconnecting · last seen working":h!==null?`Worked for ${AK(h)}${u?" · Steered":""}`:s?"Agent activity":null,x=`turn-${e}-activity`;return c.jsx("div",{className:"chat-message-column mb-1","data-turn-working-header":"true","data-turn-working":t&&n?"true":"false",children:c.jsxs("div",{className:"flex min-h-6 items-center gap-1 py-0.5",children:[c.jsx("div",{className:"flex min-w-0 items-center overflow-hidden",children:t?c.jsx(d9,{isWorking:n,startedAt:a,statusText:f}):g?c.jsx("span",{className:"typography-markdown inline-flex min-w-0 items-center leading-5 text-muted-foreground",role:"status","aria-label":g,...m?{"data-turn-reconnecting":"true"}:{"data-agent-worked-row":"true"},children:g}):null}),s?c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:R("h-6 w-6 shrink-0 rounded-md p-0 text-muted-foreground","hover:bg-interactive-hover hover:text-foreground"),"aria-expanded":o,"aria-controls":x,"aria-label":o?"Collapse activity":"Expand activity","data-turn-activity-toggle":"true",onClick:i,children:c.jsx(V,{name:"arrow-right-s",className:R("size-4 transition-transform duration-200 ease-out motion-reduce:transition-none",o&&"rotate-90"),"aria-hidden":"true"})}):null]})})},LK=p.memo(NK),RK=({isExpanded:e,userToggled:t,wasAutoCollapsed:n,hasActivity:r,showWorkingStatus:s,hasFinalText:o,previousHadFinalText:i,hasNewActivity:a})=>r?s&&o&&!i?{isExpanded:!1,wasAutoCollapsed:!0,resetUserToggle:t}:t?{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1}:a&&n?{isExpanded:!0,wasAutoCollapsed:!1,resetUserToggle:!1}:s&&!o&&!e?{isExpanded:!0,wasAutoCollapsed:n,resetUserToggle:!1}:s&&o&&e?{isExpanded:!1,wasAutoCollapsed:!0,resetUserToggle:!1}:{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1}:{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1},PK=p.memo(function({userMessage:t,renderMessage:n}){return n(t)},(e,t)=>e.userMessage===t.userMessage),DK=e=>{const t=e.summary.sourcePartId;return!t||!e.summary.text||e.summary.text.trim().length===0?!1:!e.activityParts.some(n=>n.id===t&&n.kind==="justification")},OK=({turn:e,renderMessage:t,deferEarlierAssistantMessages:n,showWorkingStatus:r=!1,isAwaitingRecovery:s=!1,activeStreamingMessageId:o=null,activeStreamingPhase:i=null,onActivityContentChange:a})=>{const l=p.useMemo(()=>e.activityParts.length>0,[e.activityParts]),d=p.useMemo(()=>DK(e),[e]),[f,u]=p.useState(()=>r&&l&&!d),h=p.useRef(!1),m=p.useRef(!1),g=p.useRef(e.activityParts.length),x=p.useRef(d);p.useLayoutEffect(()=>{const v=g.current,C=x.current,w=e.activityParts.length>v;g.current=e.activityParts.length,x.current=d;const I=RK({isExpanded:f,userToggled:h.current,wasAutoCollapsed:m.current,hasActivity:l,showWorkingStatus:r,hasFinalText:d,previousHadFinalText:C,hasNewActivity:w});m.current=I.wasAutoCollapsed,I.resetUserToggle&&(h.current=!1),I.isExpanded!==f&&u(I.isExpanded)},[l,d,f,r,e.activityParts.length]);const b=p.useCallback(()=>{h.current=!0,u(v=>!v),a?.("structural")},[a]),S=e.assistantMessages.length>0||r||s,y=p.useMemo(()=>new Set(e.activityParts.map(v=>v.id)),[e.activityParts]);return c.jsxs("section",{className:"relative w-full",id:`turn-${e.turnId}`,"data-turn-id":e.turnId,"data-scroll-spy-id":e.turnId,children:[c.jsx(PK,{userMessage:e.userMessage,renderMessage:t}),e.notices.length>0?e.notices.map(v=>c.jsx(p.Fragment,{children:t(v)},v.info.id)):null,S?c.jsx(LK,{turnId:e.turnId,isLiveTurn:r,isWorking:r,isAwaitingRecovery:s,hasActivity:l,isActivityExpanded:f,onToggleActivity:b,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,liveStatusText:e.isSteering?"Steering agent":void 0,wasSteered:e.stream.settledReason==="steered"}):null,l?c.jsx(rK,{turn:e,isExpanded:f,isLiveTurn:r,activeStreamingMessageId:o,activeStreamingPhase:i,onContentChange:a},e.turnId):null,c.jsx(mK,{turnId:e.turnId,assistantMessages:e.assistantMessages,renderMessage:t,deferEarlierMessages:n,activityPartIds:y})]})},HK=p.memo(OK),lm="#pichamber-skill:",dm="#pichamber-agent:",FK=e=>`${lm}${encodeURIComponent(e)}`,BK=e=>`${dm}${encodeURIComponent(e)}`,VK=e=>{if(!e?.startsWith(lm))return null;try{return decodeURIComponent(e.slice(lm.length))}catch{return null}},HQ=e=>{if(!e?.startsWith(dm))return null;try{return decodeURIComponent(e.slice(dm.length))}catch{return null}},$K=/(^|\s)\/skill:([A-Za-z0-9][A-Za-z0-9_-]*)/g,zK=/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g,UK=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),u9=(e,t)=>e.split(zK).map((n,r)=>r%2===1?n:t(n)).join(""),qK=e=>u9(e,t=>t.replace(/ *\n/g,`
|
|
205
|
+
`)),WK=({textContent:e,agentMention:t,skillNames:n})=>{let r=u9(e,UK);if(t?.token&&r.includes(t.token)){const s=`[${t.token}](${BK(t.name)})`;r=r.replace(t.token,s)}return r=r.replace($K,(s,o,i)=>n.has(i)?`${o}[/skill:${i}](${FK(i)})`:s),qK(r)},KK=({part:e,messageId:t,agentMention:n})=>{const r=e,s=r.text,i=typeof s=="string"?s:r.content||r.value||"",[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=Hr(w=>w.skills),h=Ga(),m=!a,g=p.useRef(null),x=p.useMemo(()=>new Map(u.map(w=>[w.name,w])),[u]),b=p.useCallback(w=>{x.has(w)&&S7(w,h)},[h,x]),S=p.useCallback(w=>{if(typeof window>"u")return!1;const I=window.getSelection();if(!I||I.isCollapsed||I.rangeCount===0)return!1;const E=I.getRangeAt(0);return w.contains(E.startContainer)||w.contains(E.endContainer)},[]);p.useEffect(()=>{const w=g.current;if(!w)return;const I=()=>{a||f(w.scrollHeight>w.clientHeight)};I();const E=new ResizeObserver(I);return E.observe(w),()=>E.disconnect()},[i,a]);const y=p.useCallback(w=>{const I=w.target,T=I?.closest("[data-skill-name]")?.dataset.skillName??VK(I?.closest("a[href]")?.getAttribute("href"));if(T){w.preventDefault(),w.stopPropagation(),b(T);return}const A=g.current;A&&(S(A)||!a&&d&&l(!0))},[S,a,d,b]),v=p.useCallback(w=>{w.stopPropagation(),l(!1)},[]),C=p.useMemo(()=>WK({textContent:i,agentMention:n,skillNames:new Set(x.keys())}),[n,x,i]);return!i||i.trim().length===0?null:c.jsxs("div",{className:"relative",children:[a&&c.jsx("button",{type:"button",onClick:v,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":"Collapse user message",children:c.jsx(V,{name:"arrow-up-s",className:"h-3.5 w-3.5"})}),c.jsx("div",{className:R("break-words font-sans typography-markdown-body",a&&"pb-3",m&&"line-clamp-2",d&&!a&&"cursor-pointer"),ref:g,onClick:y,children:c.jsx(Wa,{content:C,className:R("[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",m&&["[&_.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]]:!inline","[&_[data-md-code-line-number]]:hidden","[&_[data-md-code-line-break]]:!inline"]),disableLinkSafety:!0,enableFileReferences:!1})})]},e.id||`${t}-user-text`)},GK=p.memo(KK),ZK="application/vnd.github.issue-link",YK="application/vnd.github.pull-request-link",f9=e=>e.mime===ZK?"issue":e.mime===YK?"pr":null,h9=e=>!e||!Number.isFinite(e)||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,XK=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},JK=e=>{if(!e)return"Unnamed file";const n=e.replace(/\\/g,"/").split("/");return n[n.length-1]||e},um=e=>f9(e)!==null&&typeof e.filename=="string"&&e.filename.trim().length>0?e.filename.trim():JK(e.filename||e.url),p9=H.memo(({files:e,onShowPopup:t,className:n})=>{const[r,s]=H.useState(!1),[o,i]=H.useState(null),a=H.useRef(null),l=H.useMemo(()=>e.filter(b=>b.type==="file"&&(b.filename||b.mime||b.url)),[e]),d=l.length,f=H.useCallback(()=>{const b=a.current?.closest('[data-slot="dialog-content"], [role="dialog"]');i(b||null)},[]),u=H.useCallback(b=>{re.getState().navigateToDiagram(b),s(!1)},[]);if(d===0)return null;const h=l[0],m=um(h),g=h9(h.size),x=d===1?`${m}${g?` (${g})`:""}`:`${d} attachments`;return c.jsxs(U5,{open:r,onOpenChange:s,children:[c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(q5,{render:c.jsxs("button",{ref:a,type:"button",className:R("inline-flex items-center gap-1.5 rounded-md px-1.5 py-1 text-xs font-medium","text-subtle-foreground hover:text-foreground transition-colors cursor-pointer select-none",n),"aria-label":`View ${d} attachment${d!==1?"s":""}`,onPointerDownCapture:f,onFocusCapture:f,children:[c.jsx(V,{name:"attachment-2",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"truncate max-w-[200px]",children:x}),c.jsx(V,{name:r?"arrow-up-s":"arrow-down-s",className:"h-3.5 w-3.5 shrink-0 opacity-60"})]})})}),c.jsx(Ct,{side:"top",children:d===1?`Attachment: ${m}`:`View ${d} attachments`})]}),c.jsx(W5,{container:o||void 0,children:c.jsx(K5,{side:"top",align:"end",sideOffset:6,collisionPadding:8,children:c.jsxs(G5,{style:a4,className:R(i4,"w-84 max-h-96 overflow-y-auto p-3 space-y-3 transition-all duration-150 ease-out scrollbar-thin","data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95"),children:[c.jsx("div",{className:"flex items-center justify-between border-b border-border/30 pb-2",children:c.jsxs("span",{className:"text-xs font-semibold text-foreground flex items-center gap-1.5",children:[c.jsx(V,{name:"attachment-2",className:"h-3.5 w-3.5 text-muted-foreground"}),"Attachments (",d,")"]})}),c.jsx("div",{className:"space-y-3 divide-y divide-border/20",children:l.map((b,S)=>{const y=b.url||`${um(b)}-${S}`;return c.jsx(QK,{file:b,onShowPopup:t,onNavigateToDiagram:u},y)})})]})})})]})}),QK=H.memo(function({file:t,onShowPopup:n,onNavigateToDiagram:r}){const s=um(t),o=XK(s),i=h9(t.size),l=!!(t.mime?.startsWith("image/")&&t.url),d=f9(t),f=t.source,u=typeof f?.type=="string"?f.type:void 0,h=f&&typeof f.path=="string"?f.path:void 0,m=u==="file"&&h?h:t.url||"",g=m&&R3(m),x=H.useCallback(()=>{n&&t.url&&n({open:!0,title:s,content:"",image:{url:t.url,mimeType:t.mime,filename:s,size:t.size}})},[n,t.url,t.mime,t.size,s]),b=H.useCallback(v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),x())},[x]),S=c.jsxs("div",{className:"flex items-start gap-2.5",children:[c.jsx(pr,{filePath:s,extension:o,className:"size-5 shrink-0 mt-0.5"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"text-xs font-medium text-foreground truncate",title:s,children:s}),c.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:[o.toUpperCase()||"FILE",t.mime,i].filter(Boolean).join(" · ")})]}),d&&t.url?c.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),ja(t.url||"")},className:"shrink-0 p-1 text-muted-foreground hover:text-foreground rounded hover:bg-muted/40 transition-colors",title:"Open on GitHub","aria-label":"Open on GitHub",children:c.jsx(V,{name:"github",className:"h-4 w-4"})}):g?c.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),r(m)},className:"shrink-0 p-1 text-muted-foreground hover:text-foreground rounded hover:bg-muted/40 transition-colors",title:"Open in diagram view","aria-label":"Open in diagram view",children:c.jsx(V,{name:"external-link",className:"h-4 w-4"})}):null]});if(!l||!t.url)return c.jsx("div",{className:"pt-3 first:pt-0 space-y-2",children:S});const y=t.url;return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx("div",{role:"button",tabIndex:0,"aria-label":`Preview ${s}`,onClick:x,onKeyDown:b,className:"pt-3 first:pt-0 space-y-2 cursor-pointer rounded-lg",children:S})}),c.jsx(Ct,{side:"left",className:R(D3),children:c.jsx(O3,{imageUrl:y,filename:s,metaLine:[o.toUpperCase(),i].filter(Boolean).join(" · ")})})]})});p9.displayName="UserMessageAttachments";const m9=e=>{if(e==="12h")return!0;if(e==="24h")return!1},eG=(e,t,n={})=>{const r=e instanceof Date?e:new Date(e);return Number.isFinite(r.getTime())?r.toLocaleTimeString("en-US",{hour:n.hour??"numeric",minute:"2-digit",second:n.precision==="second"?"2-digit":void 0,hour12:m9(t)}):n.fallback??""},FQ=(e,t,n)=>{const r=e instanceof Date?e:new Date(e);return Number.isFinite(r.getTime())?r.toLocaleString("en-US",{...n,hour12:n.hour?m9(t):n.hour12}):""},g9=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),tG=(e,t)=>{const n=new Date(t);return n.setDate(t.getDate()-1),g9(e,n)},nG=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),y9=(e,t)=>{if(!nG(e))return"";const n=new Date(e),r=new Date,s=eG(n,t),o="en-US";if(g9(n,r))return s;if(tG(n,r))return`Yesterday ${s}`;const i=n.toLocaleString(o,{month:"short"}),a=n.getDate(),l=`${i} ${a}`;return n.getFullYear()===r.getFullYear()?`${l}, ${s}`:`${l}, ${n.getFullYear()}, ${s}`},rG=e=>{const[t,n]=p.useState(()=>{if(!e)return!1;const r=qe().getState().reducer.bySession.get(e);return r?.lifecycle==="busy"||r?.lifecycle==="retry"});return p.useEffect(()=>{if(!e){n(!1);return}const r=()=>{const s=qe().getState().reducer.bySession.get(e);n(s?.lifecycle==="busy"||s?.lifecycle==="retry")};return r(),qe().subscribe(r,`session:${e}`)},[e]),t},sG=e=>e.includes(":")?e.split(":")[0]??e:e,zd=(e,t,n)=>{const r=he(d=>d.revertToMessage),s=he(d=>d.forkFromMessage),o=rG(t),[i,a]=p.useState(!1);return{run:p.useCallback(async()=>{if(!t||!n||i||o)return;const d=sG(n);a(!0);try{e==="revert"?(await r(t,d),Ce.success("Reverted — conversation rewound. Files on disk were not changed.")):(await s(t,d),Ce.success("Forked — new session created from this message."))}catch(f){const u=e==="revert"?"Failed to revert conversation":"Failed to fork session";Ce.error(f instanceof Error?f.message:u)}finally{a(!1)}},[i,s,o,e,n,r,t]),busy:i,disabled:i||o||!t||!n}},ag=p.memo(({sessionId:e,messageId:t,size:n="user",isLatestMessage:r=!1})=>{const{run:s,busy:o,disabled:i}=zd("revert",e,t),a=p.useCallback(f=>{f.stopPropagation(),f.preventDefault(),s()},[s]),l=n==="user"?"h-6 w-6":"h-8 w-8",d=n==="user"?"h-3 w-3":"h-3.5 w-3.5";return r?null:c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon",disabled:i,"aria-label":"Revert conversation to here",className:R(l,"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",i&&"opacity-50"),onPointerDown:f=>f.stopPropagation(),onClick:a,children:o?c.jsx(V,{name:"loader-4",className:R(d,"animate-spin"),"aria-hidden":"true"}):c.jsx(V,{name:"history",className:d,"aria-hidden":"true"})})}),c.jsx(Ct,{sideOffset:6,children:"Revert to here"})]})});ag.displayName="MessageRevertAction";const cg=p.memo(({sessionId:e,messageId:t,size:n="user"})=>{const{run:r,busy:s,disabled:o}=zd("fork",e,t),i=p.useCallback(d=>{d.stopPropagation(),d.preventDefault(),r()},[r]),a=n==="user"?"h-6 w-6":"h-8 w-8",l=n==="user"?"h-3 w-3":"h-3.5 w-3.5";return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon",disabled:o,"aria-label":"Fork conversation from here",className:R(a,"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",o&&"opacity-50"),onPointerDown:d=>d.stopPropagation(),onClick:i,children:s?c.jsx(V,{name:"loader-4",className:R(l,"animate-spin"),"aria-hidden":"true"}):c.jsx(V,{name:"git-branch",className:l,"aria-hidden":"true"})})}),c.jsx(Ct,{sideOffset:6,children:"Fork to new session"})]})});cg.displayName="MessageForkAction";const lg=p.memo(({sessionId:e,messageId:t,showRevert:n,onSaveImage:r,saveImageDisabled:s=!1,size:o="user"})=>{const i=zd("revert",e,t),a=zd("fork",e,t),l=p.useRef(null),d=i.busy||a.busy;return c.jsxs(Fa,{children:[c.jsx(Ba,{asChild:!0,children:c.jsx(be,{ref:l,type:"button",variant:"ghost",size:"icon","aria-label":"More message actions",className:R(o==="user"?"h-6 w-6":"h-8 w-8","text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50"),onPointerDown:f=>f.stopPropagation(),children:d?c.jsx(V,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):c.jsx(V,{name:"more-fill",className:"h-3.5 w-3.5","aria-hidden":"true"})})}),c.jsxs(Va,{align:"end",className:"min-w-44",children:[n?c.jsx(ur,{disabled:i.disabled,onSelect:()=>{i.run()},children:"Revert to here"}):null,c.jsx(ur,{disabled:a.disabled,onSelect:()=>{a.run()},children:"Fork to new session"}),r?c.jsx(ur,{disabled:s,onSelect:()=>{l.current&&r(l.current)},children:"Save as image"}):null]})]})});lg.displayName="MessageMoreActions";const oG=e=>{if(!e||typeof e!="object")return null;const t=typeof e.providerID=="string"?e.providerID.trim():"",n=typeof e.modelID=="string"?e.modelID.trim():"";return!t||!n?null:`${t}/${n}`},iG=({part:e})=>{const[t,n]=p.useState(!1),r=Jn(),s=he(m=>m.setCurrentSession),o=Ga(),i=typeof e.description=="string"?e.description.trim():"",a=typeof e.command=="string"?e.command.trim():"",l=typeof e.agent=="string"?e.agent.trim():"",d=typeof e.prompt=="string"?e.prompt.trim():"",f=typeof e.taskSessionID=="string"?e.taskSessionID.trim():"",u=oG(e.model),h=p.useCallback(()=>{!r||!f||(s(f,r),o?.closeDrawers?.())},[r,f,s,o]);return c.jsxs("div",{className:"mt-2",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Delegated task"}),a?c.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 typography-micro leading-none bg-foreground/5 text-muted-foreground",children:["/",a]}):null,l?c.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 typography-micro leading-none bg-foreground/5 text-muted-foreground",children:["@",l]}):null,u?c.jsx("span",{className:"inline-flex h-5 items-center rounded px-1.5 typography-micro leading-none bg-foreground/5 text-muted-foreground",children:u}):null]}),i?c.jsx("div",{className:"typography-ui-label text-foreground mt-1.5",children:i}):null,d?c.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>n(m=>!m),children:t?"Hide prompt":"Show prompt"}),t?c.jsx("pre",{className:"typography-meta mt-1.5 overflow-x-auto whitespace-pre-wrap break-words text-foreground/85","data-no-drawer-swipe":"true",children:d}):null]}):null,f?c.jsx("div",{className:"mt-1.5",children:c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:h,children:"Open subtask session"})}):null]})},Bx={background:"transparent",backgroundColor:"transparent"},aG=({part:e})=>{const t=typeof e.shellAction?.output=="string"?e.shellAction.output:"",[n,r]=p.useState(!0),{value:s,show:o}=z1(!1,2e3),i=typeof e.shellAction?.command=="string"?e.shellAction.command.trim():"",a=typeof e.shellAction?.status=="string"?e.shellAction.status.trim().toLowerCase():"",l=t.trim().length>0,d=p.useCallback(async()=>{!l||!(await yr(t)).ok||o(!0)},[l,t,o]);return c.jsxs("div",{className:"mt-2",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Shell command"}),a?c.jsx("span",{className:R("inline-flex h-5 items-center rounded px-1.5 typography-micro leading-none",a==="error"?"bg-[var(--status-error-background)] text-[var(--status-error)]":"bg-foreground/5 text-muted-foreground"),children:a}):null]}),i?c.jsx("div",{className:"typography-meta mt-1.5 overflow-x-auto font-mono","data-no-drawer-swipe":"true",children:c.jsx(Bd,{language:"bash",code:i,codeStyle:Bx,wrap:!0})}):null,l?c.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[c.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>r(f=>!f),children:n?"Hide output":"Show output"}),c.jsx("button",{type:"button",className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:()=>{d()},"aria-label":s?"Copied":"Copy output",title:s?"Copied":"Copy output",children:s?c.jsx(V,{name:"check",className:"h-3.5 w-3.5"}):c.jsx(V,{name:"file-copy",className:"h-3.5 w-3.5"})})]}),n?c.jsx("div",{className:"typography-meta mt-1.5 max-h-56 overflow-auto font-mono text-foreground/85",children:c.jsx(Bd,{language:"bash",code:t,codeStyle:Bx,wrap:!0})}):null]}):null]})},cG={contain:"layout",transform:"translateZ(0)"},lG=p.memo(function({sessionId:t,messageId:n,parts:r,messageCreatedAt:s,isLatestMessage:o=!1,isMobile:i,alwaysShowActions:a=i,hasTouchInput:l,hasTextContent:d,onCopyMessage:f,copiedMessage:u,onShowPopup:h,agentMention:m,userActionsMode:g="inline"}){const x=re(z=>z.timeFormatPreference),[b,S]=p.useState(!1),y=p.useRef(null),v=p.useMemo(()=>r.filter(o9),[r]),C=p.useMemo(()=>r.filter(z=>z.type==="file"&&!!(z.filename||z.mime||z.url)),[r]),w=m?.token;let I=!1;const E=!!f,T=!!u,A=!!(l??i),j=!!d,k=g!=="external-actions",_=g!=="external-content",M=p.useCallback(()=>{y.current!==null&&typeof window<"u"&&(window.clearTimeout(y.current),y.current=null)},[]),L=p.useCallback(()=>{!A||!E||!j||typeof window>"u"||(M(),S(!0),y.current=window.setTimeout(()=>{S(!1),y.current=null},1800))},[E,M,j,A]);p.useEffect(()=>{j||(S(!1),M())},[M,j]);const O=p.useCallback(z=>{!f||!j||(z.stopPropagation(),z.preventDefault(),f(),A&&L())},[j,A,f,L]),N=p.useMemo(()=>{if(typeof s!="number"||s<=0)return null;const z=y9(s,x);return z.length>0?z:null},[s,x]),D=i||a,W=_?c.jsx("div",{className:R("group/user-actions",D?g==="inline"?"mt-2 mb-1 flex items-center justify-end":"flex min-h-11 items-start justify-end pt-0":g==="inline"?"absolute top-full left-0 right-0 z-10 pt-5":"flex min-h-8 items-start justify-end pt-2"),children:c.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-3 gap-y-1",children:[c.jsxs("div",{className:R("flex items-center justify-start gap-1.5",g==="inline"?"translate-x-5":"translate-x-0",a?"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"),children:[N?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("span",{className:"mr-1 flex items-center gap-1 typography-meta tabular-nums text-subtle-foreground","aria-label":`Message time: ${N}`,children:[c.jsx(V,{name:"time",className:"size-3"}),c.jsx("span",{className:"message-footer__label",children:N})]})}),c.jsx(Ct,{children:N})]}):null,!A&&!o?c.jsx(ag,{sessionId:t??null,messageId:n,size:"assistant"}):null,A?null:c.jsx(cg,{sessionId:t??null,messageId:n,size:"assistant"}),E&&j&&c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon","data-visible":b||T?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:z=>z.stopPropagation(),onClick:O,onFocus:()=>S(!0),onBlur:()=>{T||S(!1)},children:T?c.jsx(V,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):c.jsx(V,{name:"file-copy",className:"h-3.5 w-3.5"})})}),c.jsx(Ct,{sideOffset:6,children:"Copy message"})]}),A?c.jsx(lg,{sessionId:t??null,messageId:n,showRevert:!o,size:"assistant"}):null]}),C.length>0?c.jsx(p9,{files:C,onShowPopup:h}):null]})}):null;return k?c.jsxs("div",{className:"relative w-full group/message",style:cG,onTouchStart:A&&E&&j?L:void 0,children:[c.jsx("div",{className:R("leading-relaxed text-foreground text-base overflow-x-hidden","overflow-y-hidden"),style:void 0,children:v.map((z,X)=>{if(n9(z))return c.jsx(p.Fragment,{children:c.jsx(iG,{part:z})},z.id??`user-subtask-${X}`);if(r9(z))return c.jsx(p.Fragment,{children:c.jsx(aG,{part:z})},z.id??`user-shell-${X}`);let F;return m&&w&&!I&&sg(z).includes(w)&&(F=m,I=!0),c.jsx(p.Fragment,{children:c.jsx(GK,{part:z,messageId:n,isMobile:i,agentMention:F})},z.id??`user-text-${X}`)})}),W]}):c.jsx(c.Fragment,{children:W})}),Vx=8,dG=280,uG=({containerRef:e})=>{const[t,n]=p.useState({x:0,y:0,show:!1}),[r,s]=p.useState(""),[o,i]=p.useState(""),a=p.useRef(!1),[l,d]=p.useState(!1),f=p.useRef(null),u=p.useRef(dG),h=p.useRef(null),m=p.useRef(null),g=p.useRef(null),x=p.useRef(!1),b=he(j=>j.createSession),S=Ye(j=>j.setPendingInputText),y=re(j=>j.isMobile);p.useEffect(()=>{x.current=t.show},[t.show]),p.useEffect(()=>()=>{m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),g.current!==null&&(window.clearTimeout(g.current),g.current=null)},[]);const v=p.useCallback(()=>{h.current=null,x.current&&(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),d(!1),n(j=>({...j,show:!1})),s(""),i(""),x.current=!1)},[]),C=p.useCallback(j=>{if(typeof window>"u")return j;const k=window.innerWidth,M=u.current/2,L=Vx+M,O=k-Vx-M;return L>O?k/2:Math.min(Math.max(j,L),O)},[]),w=p.useCallback(()=>{if(!h.current)return;const{plainText:j,markdownText:k,rect:_}=h.current,M=!t.show,L=y?_.left+_.width/2:C(_.left+_.width/2),O=_.top-10;s(j),i(k),n({x:L,y:O,show:!0}),x.current=!0,M&&(d(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{d(!1),m.current=null}))},[C,y,t.show]);p.useLayoutEffect(()=>{if(!t.show||y||!f.current)return;const j=f.current.offsetWidth;!Number.isFinite(j)||j<=0||j===u.current||(u.current=j,n(k=>({...k,x:C(k.x)})))},[C,y,t.show]),p.useEffect(()=>{if(!t.show||y)return;const j=()=>{n(k=>({...k,x:C(k.x)}))};return window.addEventListener("resize",j),()=>{window.removeEventListener("resize",j)}},[C,y,t.show]);const I=p.useCallback(()=>{const j=window.getSelection(),k=e.current;if(!j||!k){a.current||v();return}const _=wn(j.toString());if(!_){a.current||v();return}const M=j.getRangeAt(0);if(!k.contains(M.commonAncestorContainer)){a.current||v();return}const L=M.getBoundingClientRect();h.current={plainText:_,markdownText:g3(M,_),rect:L},a.current||w()},[e,v,w]);p.useEffect(()=>{const j=e.current;if(!j)return;const k=()=>{a.current=!0,v()},_=()=>{a.current=!1,h.current&&(g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{g.current=null;const L=window.getSelection();L&&L.toString().trim()?w():v()},10))};document.addEventListener("selectionchange",I),j.addEventListener("mousedown",k),document.addEventListener("mouseup",_);const M=L=>{f.current&&!f.current.contains(L.target)&&!window.getSelection()?.toString().trim()&&v()};return document.addEventListener("mousedown",M),()=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null),document.removeEventListener("selectionchange",I),j.removeEventListener("mousedown",k),document.removeEventListener("mouseup",_),document.removeEventListener("mousedown",M)}},[e,I,v,w]);const E=p.useCallback(()=>{if(!o)return;const j=v1(o);S(j,"append"),v(),window.getSelection()?.removeAllRanges(),queueMicrotask(()=>{To()})},[o,S,v]),T=p.useCallback(async()=>{if(!r)return;await b(void 0,null,null)&&S(r,"replace"),v(),window.getSelection()?.removeAllRanges()},[r,b,S,v]),A=p.useCallback(async()=>{if(!r)return;const j=await yr(r);j.ok||console.error("Failed to copy:",j.error),v(),window.getSelection()?.removeAllRanges()},[r,v]);return t.show?y?ba.createPortal(c.jsx("div",{ref:f,className:R("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:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs("button",{onClick:E,className:R("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:"Add to current chat",type:"button",children:[c.jsx(V,{name:"add",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"Add to chat"})]}),c.jsxs("button",{onClick:T,className:R("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:"Create new session with selection",type:"button",children:[c.jsx(V,{name:"chat-new",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"New session"})]}),c.jsxs("button",{onClick:A,className:R("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:"Copy",type:"button",children:[c.jsx(V,{name:"file-copy",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"Copy"})]})]})}),document.body):ba.createPortal(c.jsx("div",{ref:f,className:"fixed z-50",style:{left:t.x,top:t.y,transform:"translate(-50%, -100%)"},children:c.jsxs("div",{className:R("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:[c.jsxs("button",{onClick:E,className:R("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:"Add to current chat",type:"button",children:[c.jsx(V,{name:"add",className:"h-4 w-4"}),c.jsx("span",{className:"whitespace-nowrap",children:"Add to chat"})]}),c.jsx("div",{className:"w-px h-4 bg-[var(--interactive-border)]"}),c.jsxs("button",{onClick:T,className:R("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:"Create new session with selection",type:"button",children:[c.jsx(V,{name:"chat-new",className:"h-4 w-4"}),c.jsx("span",{className:"whitespace-nowrap",children:"New session"})]})]})}),document.body):null},fl=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function fG(e){if(!e||e==="build")return fl[0];let t=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);t=(t<<5)-t+s,t=t&t}const n=1+Math.abs(t)%(fl.length-1);return fl[n]}const hG=p.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,onShareImage:r,sessionId:s,messageId:o,isLatestMessage:i=!1})=>{const a=Iu(),[l,d]=p.useState(!1),{value:f,show:u,clear:h}=z1(!1,2e3),[m,g]=p.useState(!1),x=p.useRef(null),b=!!n,S=p.useCallback(()=>{x.current!==null&&typeof window<"u"&&(window.clearTimeout(x.current),x.current=null)},[]);p.useEffect(()=>S,[S]),p.useEffect(()=>{(!e||!b)&&(d(!1),S(),h())},[b,S,h,e]);const y=p.useCallback(()=>{!t||!b||!e||typeof window>"u"||(S(),d(!0),x.current=window.setTimeout(()=>{d(!1),x.current=null},1800))},[b,S,e,t]),v=p.useCallback(async E=>{!n||!e||(E.stopPropagation(),E.preventDefault(),await n()===!1)||(u(!0),t&&y())},[e,t,n,y,u]),C=p.useCallback(async E=>{if(!(m||!e)){g(!0);try{const A=E.closest("[data-message-text-export-root]")?.querySelector("[data-message-text-export-source]")??null;await r(A)}finally{g(!1)}}},[e,m,r]),w=p.useCallback(async E=>{E.stopPropagation(),E.preventDefault(),await C(E.currentTarget)},[C]),I=t&&!!(s&&o);return c.jsxs(c.Fragment,{children:[!I&&s&&o&&!i?c.jsx(ag,{sessionId:s,messageId:o,size:"assistant"},"message-revert"):null,!I&&s&&o?c.jsx(cg,{sessionId:s,messageId:o,size:"assistant"},"message-fork"):null,n&&c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon","data-visible":l||f?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!e&&"opacity-50"),disabled:!e,"aria-label":"Copy message text","aria-hidden":!e,onPointerDown:E=>E.stopPropagation(),onClick:E=>{v(E)},onFocus:()=>{e&&d(!0)},onBlur:()=>{f||d(!1)},children:f?c.jsx(V,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):c.jsx(V,{name:"file-copy",className:"h-3.5 w-3.5"})})}),c.jsx(Ct,{sideOffset:6,children:"Copy answer"})]},"message-copy"),I&&o?c.jsx(lg,{sessionId:s,messageId:o,showRevert:!i,size:"assistant",onSaveImage:a!=="mini-chat"?E=>{C(E)}:void 0,saveImageDisabled:m||!e},"message-more"):null,!I&&a!=="mini-chat"?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",size:"icon",variant:"ghost",disabled:m||!e,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",(!e||m)&&"opacity-50"),onPointerDown:E=>E.stopPropagation(),onClick:E=>{w(E)},children:m?c.jsx(V,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx(V,{name:"image-download",className:"h-4 w-4"})})}),c.jsx(Ct,{sideOffset:6,children:m?"Saving image...":"Save as image"})]},"message-share"):null]})});async function pG(e,t){const n=t;if(!n)return;let r=null;try{const{toPng:s}=await mt(async()=>{const{toPng:y}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{toPng:y}},[]),o=n,i=window.getComputedStyle(o),l=window.getComputedStyle(document.documentElement).getPropertyValue("--surface-background").trim()||i.backgroundColor||window.getComputedStyle(document.body).backgroundColor,d=24;r=document.createElement("div"),r.setAttribute("data-message-image-export","true"),r.style.cssText=`
|
|
206
|
+
padding: ${d}px;
|
|
207
|
+
background-color: ${l};
|
|
208
|
+
display: inline-block;
|
|
209
|
+
`;const f=o.cloneNode(!0);f.style.cssText=`
|
|
210
|
+
${i.cssText}
|
|
211
|
+
transform: none;
|
|
212
|
+
contain: none;
|
|
213
|
+
`,f.querySelectorAll('[data-message-actions="true"]').forEach(y=>{y.style.display="none"}),f.querySelectorAll('[data-message-action-group="true"]').forEach(y=>{y.style.display="none"});const m=f.querySelectorAll('[aria-label^="Message time:"]'),g=new Set;m.forEach(y=>{const C=y.getAttribute("aria-label")?.replace("Message time:","").trim();if(!C||y.textContent?.includes(C))return;const w=document.createElement("span");w.style.marginLeft="4px",w.textContent=C,y.appendChild(w);const E=y.parentElement?.parentElement;!E||g.has(E)||(E.style.justifyContent="flex-start",g.add(E))}),r.appendChild(f),document.body.appendChild(r);const x=await s(r,{quality:1,pixelRatio:2,backgroundColor:l}),b=`message-${e}.png`,S=await F8({filename:b,mimeType:"image/png",data:x});S==="downloaded"?Ce.success("Image saved"):S==="shared"&&Ce.success("Image shared")}catch(s){console.error("Failed to generate image:",s),Ce.error("Failed to generate image")}finally{r&&r.parentNode&&r.parentNode.removeChild(r)}}function mG({visibleParts:e,isMessageCompleted:t,messageFinish:n,messageCompletedAt:r,messageCreatedAt:s,turnGroupingContext:o,errorMessage:i,isMobile:a,isMiniChatSurface:l,timeFormatPreference:d}){const f=p.useMemo(()=>e.filter(v=>v.type==="text"),[e]),u=p.useMemo(()=>{if(a||l)return null;for(const v of f){const C=v.text;if(typeof C!="string"||C.length===0)continue;const w=WT(C)[0];if(w)return w.includes("0.0.0.0")?w.replace("0.0.0.0","127.0.0.1"):w}return null},[f,a,l]),h=o?.isLastAssistantInTurn??!1,m=!!o?.isWorking,g=p.useRef(m),x=g.current&&!m;p.useEffect(()=>{g.current=m},[m]);const b=n==="stop"||t&&!i,S=!t,y=p.useMemo(()=>{const v=typeof r=="number"&&r>0?r:typeof s=="number"&&s>0?s:null;if(v===null)return null;const C=y9(v,d);return C.length>0?C:null},[r,s,d]);return{messagePreviewUrl:u,isLastAssistantInTurn:h,isTurnWorking:m,shouldAnimateTurnFooter:x,hasStopFinish:b,awaitingMessageCompletion:S,footerTimestamp:y}}const gG={contain:"layout",transform:"translateZ(0)"},yG={containerType:"inline-size",containerName:"message-footer"},vG=p.memo(({sessionId:e,messageId:t,parts:n,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,isLatestMessage:a=!1,isMobile:l,alwaysShowActions:d,hasTouchInput:f,onShowPopup:u,streamPhase:h,onContentChange:m,hasTextContent:g=!1,onCopyMessage:x,turnGroupingContext:b,errorMessage:S,errorVariant:y="error",footerProviderID:v,footerModelName:C,footerAgentName:w,footerVariant:I,isDarkTheme:E=!1})=>{const T=Iu(),A=p.useRef(null),j=p.useRef(null),k=!!(f??l),_=!!(d??l),{src:M,onError:L,hasLogo:O}=M1(v??null),N=p.useMemo(()=>og(n),[n]),D=T==="mini-chat",W=he(te=>te.currentSessionId),z=he(te=>te.getDirectoryForSession),X=Jn(),F=re(te=>te.timeFormatPreference),U=re(te=>te.openContextPreview),{messagePreviewUrl:P,isLastAssistantInTurn:q,isTurnWorking:B,shouldAnimateTurnFooter:ee,hasStopFinish:G,awaitingMessageCompletion:K,footerTimestamp:se}=mG({visibleParts:N,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,turnGroupingContext:b,errorMessage:S,isMobile:l,isMiniChatSurface:D,timeFormatPreference:F}),de=G?"completed":h,oe=!!g&&!K,ue=p.useCallback(async te=>{const Q=te??j.current??A.current;await pG(t,Q)},[t]),ye=!!S,we=y==="info"?"information":"error-warning",Me=q&&(g||!!S)&&!B,He=p.useMemo(()=>c.jsx(hG,{hasCopyableText:oe,isTouchContext:k,onCopyMessage:x,onShareImage:ue,sessionId:e,messageId:t,isLatestMessage:a}),[ue,oe,a,k,t,x,e]),Ae=p.useMemo(()=>{const te=[];let Q=0;for(;Q<N.length;){const me=N[Q];if(me.type!=="text"){Q++;continue}te.push(c.jsx("div",{ref:j,"data-message-text-export-source":"true",children:c.jsx(g7,{part:me,sessionId:e,messageId:t,streamPhase:de,onContentChange:m,onShowPopup:u})},`assistant-text-${t}-${Q}`)),Q++}return te},[t,e,m,u,de,N]),Ge="typography-meta text-muted-foreground tabular-nums flex items-center gap-1",et=!D&&!l,Xe=c.jsx(c.Fragment,{children:et&&P?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Open preview",onPointerDown:te=>te.stopPropagation(),onClick:()=>{const te=X??(W?z(W):null);te&&U(te,P)},children:c.jsx(V,{name:"global",className:"h-4 w-4"})})}),c.jsx(Ct,{sideOffset:6,children:"Open preview"})]}):null});return c.jsxs("div",{ref:A,"data-message-text-export-root":"true",className:R("relative w-full group/message"),style:gG,children:[c.jsx(uG,{containerRef:A}),c.jsxs("div",{children:[c.jsxs("div",{className:"message-content-text space-y-2 leading-relaxed overflow-hidden text-foreground [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Ae,ye&&c.jsx(rg,{children:c.jsx("div",{className:R("group/assistant-text relative mt-3 p-3 rounded-lg border break-words max-w-full",y==="info"?"bg-[var(--status-info-background)] border-[var(--status-info-border)]":"bg-[var(--status-error-background)] border-[var(--status-error-border)]"),children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(V,{name:we,className:R("h-4 w-4 shrink-0",y==="info"?"text-[var(--status-info)]":"text-[var(--status-error)]")}),c.jsx("div",{className:"min-w-0 flex-1 break-words",children:c.jsx(Wa,{content:S??"",onShowPopup:u,className:"[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",enableFileReferences:!1})})]})})},"assistant-error")]}),c.jsx(k1,{files:n,onShowPopup:u}),Me&&c.jsxs("div",{className:R("mt-2 mb-1 flex flex-wrap items-center justify-start gap-x-3 gap-y-1.5",ee&&"message-footer-enter"),style:yG,children:[c.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1 typography-meta text-muted-foreground",children:[C?c.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[O&&M?c.jsx("img",{src:M,alt:"",className:"h-3.5 w-3.5 flex-shrink-0",style:{filter:E?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:L}):c.jsx(V,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0",style:{color:`var(${fG(w).var})`}}),c.jsx("span",{className:"truncate",children:C})]}):null,I&&!["default","none"].includes(I.toLowerCase())?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx(V,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"message-footer__label",children:I[0].toLowerCase()+I.slice(1)})]}):null,w?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx(V,{name:"ai-agent",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"message-footer__label",children:w})]}):null,se?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("span",{className:R(Ge,"message-footer__timestamp"),"aria-label":`Message time: ${se}`,children:[c.jsx(V,{name:"time",className:"h-3.5 w-3.5"}),c.jsx("span",{className:"message-footer__label",children:se})]})}),c.jsx(Ct,{children:se})]}):null]}),c.jsxs("div",{className:R("flex items-center gap-1.5",_||k?void 0:"pointer-events-none opacity-0 transition-opacity duration-150 focus-within:pointer-events-auto focus-within:opacity-100 group-hover/message:pointer-events-auto group-hover/message:opacity-100"),"data-message-action-group":"true",children:[He,Xe]})]})]})]})}),jh=p.memo(({isUser:e,...t})=>e?c.jsx(lG,{sessionId:t.sessionId,messageId:t.messageId,parts:t.parts,messageCreatedAt:t.messageCreatedAt,isMobile:t.isMobile,alwaysShowActions:t.alwaysShowActions,hasTouchInput:t.hasTouchInput,hasTextContent:t.hasTextContent,onCopyMessage:t.onCopyMessage,copiedMessage:t.copiedMessage,onShowPopup:t.onShowPopup,agentMention:t.agentMention,userActionsMode:t.userActionsMode}):c.jsx(vG,{...t})),Ud=e=>{const 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}},v9="GitHub issue context (JSON)",x9="GitHub pull request context (JSON)",$x=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,zx=(e,t)=>{const n=e.trimStart();if(!n.startsWith(t))return null;const r=n.indexOf("{");if(r<0)return null;try{return JSON.parse(n.slice(r))}catch{return null}},xG=e=>{const t=zx(e,v9);if(t){const r=t.issue,s=r?.number,o=r?.title,i=r?.url;return!$x(s)||typeof o!="string"||typeof i!="string"?null:{type:"file",mime:"application/vnd.github.issue-link",filename:`Issue #${s}: ${o}`,url:i}}const n=zx(e,x9);if(n){const r=n.pr,s=r?.number,o=r?.title,i=r?.url;return!$x(s)||typeof o!="string"||typeof i!="string"?null:{type:"file",mime:"application/vnd.github.pull-request-link",filename:`PR #${s}: ${o}`,url:i}}return null},bG=e=>!!e.trim().startsWith("The following tool was executed by the user"),dg=e=>e.filter(t=>{if(!(t.synthetic===!0))return!0;if(t.type!=="text")return!1;const r=t.text;if(typeof r!="string")return!1;const s=r.trimStart();return bG(r)||s.startsWith(v9)||s.startsWith(x9)}).map(t=>{const n=t;if(n.type==="compaction")return{type:"text",text:"/compact"};if(n.type==="text"){const r=typeof n.text=="string"?n.text.trim():"";if(n.synthetic===!0){const o=xG(r);if(o)return o}if(r.startsWith("The following tool was executed by the user"))return{type:"text",text:"/shell"}}return t}),Ux=new WeakMap,b9=e=>{if(!e||!Ud(e.info).isUser)return!1;const t=Ux.get(e.parts);if(t!==void 0)return t;const n=dg(Au(e.parts)),r=ig(n,{includeReasoning:!0}).length===0;return Ux.set(e.parts,r),r};function Th(e){const[t,n]=p.useState(e);return p.useEffect(()=>{e!=null&&n(e)},[e]),e??t}const xn=(e,t)=>{if(typeof e=="object"&&e!==null)return e[t]},hs=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},qx=e=>{const t=xn(e,"model"),n=typeof t=="object"&&t!==null?t:null;return{providerId:hs(xn(e,"providerID"))??hs(n?.providerID)??hs(n?.providerId),modelId:hs(xn(e,"modelID"))??hs(n?.modelID)??hs(n?.modelId)}};function wG({message:e,previousMessage:t,isUser:n,sessionId:r,isInActiveTurn:s,turnGroupingContext:o}){const i=We(_=>_.providers),a=Lt(_=>_.getAgentModelForSession),l=Lt(_=>_.getSessionModelSelection),d=Lt(O8(_=>s&&r?_.sessionAgentSelections.get(r)??null:null)),f=p.useMemo(()=>{if(n||!t)return null;const _=xn(t.info,"clientRole"),M=xn(t.info,"role");if((typeof _=="string"?_:typeof M=="string"?M:void 0)!=="user")return null;const O=xn(t.info,"mode"),N=xn(t.info,"agent"),D=qx(t.info),W=xn(t.info,"variant"),z=typeof O=="string"&&O.trim().length>0?O:typeof N=="string"&&N.trim().length>0?N:void 0,X=D.providerId,F=D.modelId,U=typeof W=="string"&&W.trim().length>0?W:void 0;return!z&&!X&&!F&&!U?null:{agentName:z,providerId:X,modelId:F,variant:U}},[n,t]),u=p.useMemo(()=>{if(n)return;const _=xn(e.info,"mode");if(typeof _=="string"&&_.trim().length>0)return _;const M=xn(e.info,"agent");if(typeof M=="string"&&M.trim().length>0)return M;if(f?.agentName)return f.agentName;if(r)return d??void 0},[n,e.info,f,r,d]),h=n?{providerId:void 0,modelId:void 0}:qx(e.info),m=h.providerId??null,g=h.modelId??null,x=p.useMemo(()=>{if(n||!r)return null;if(f?.providerId&&f?.modelId)return{providerId:f.providerId,modelId:f.modelId};if(u){const M=a(r,u);if(M?.providerId&&M?.modelId)return M}const _=l(r);return _?.providerId&&_?.modelId?_:null},[n,r,u,f,a,l]),b=p.useMemo(()=>n?null:typeof m=="string"&&m.trim().length>0?m:x?.providerId??null,[n,m,x]),S=p.useMemo(()=>n?null:typeof g=="string"&&g.trim().length>0?g:x?.modelId??null,[n,g,x]),y=p.useMemo(()=>{if(n)return;const _=b&&i.length>0?i.find(M=>M.id===b):void 0;return _1(_,S)||void 0},[n,b,S,i]),v=p.useMemo(()=>{if(n||!b||!S)return!1;const _=i.find(O=>O.id===b);if(!_?.models||!Array.isArray(_.models))return!1;const L=_.models.find(O=>O.id===S)?.variants;return!!(L&&Object.keys(L).length>0)},[n,S,b,i]),C=Th(u),w=Th(b??void 0),I=Th(y),E=C??void 0,T=w??null,A=I??void 0,j=n?void 0:hs(xn(e.info,"variant"))??o?.userMessageVariant??f?.variant;return{headerAgentName:E,headerProviderID:T,headerModelName:A,headerVariant:n?void 0:v?j??"Default":j}}class Cs{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Cs.instance||(Cs.instance=new Cs),Cs.instance}recordSessionStart(t){this.sessionStartTimes.set(t,Date.now())}getSessionStartTime(t){return this.sessionStartTimes.get(t)}shouldAnimateMessage(t,n){if(t.role!=="assistant"||this.seenMessageIds.has(t.id))return!1;const r=t.time?.created;if(typeof r!="number"||!Number.isFinite(r))return this.seenMessageIds.add(t.id),!1;const s=this.sessionStartTimes.get(n);if(!s)return this.seenMessageIds.add(t.id),this.messageCreationTimes.set(t.id,r),!1;const o=r>s-5e3;return this.seenMessageIds.add(t.id),this.messageCreationTimes.set(t.id,r),o}clearSession(t){this.sessionStartTimes.delete(t)}hasSessionTiming(t){return this.sessionStartTimes.has(t)}hasBeenAnimated(t){return this.seenMessageIds.has(t)}markMessageAsAnimated(t,n){this.seenMessageIds.add(t),this.messageCreationTimes.set(t,n)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function SG({message:e,isUser:t,sessionId:n,streamPhase:r,assistantTextParts:s,shouldCoordinateRendering:o,animationHandlers:i,messageContainerRef:a}){const l=p.useMemo(()=>t||!n?!1:Cs.getInstance().shouldAnimateMessage(e.info,n),[e.info,t,n]),d=i??null,f=p.useRef(!1),u=p.useRef(!1),h=p.useRef(!1),m=p.useRef(!1),g=p.useRef(!1);p.useEffect(()=>{f.current=!1,u.current=!1,h.current=!1,m.current=!1,g.current=!1},[e.info.id]);const x=!!xn(e.info,"animationSettled"),b=r==="streaming"||r==="cooldown";b&&(g.current=!0);const S=l&&!x&&!b&&!g.current,y=!t&&l&&s.length>0&&!o;p.useEffect(()=>{if(d?.onStreamingCandidate){if(!y){u.current&&(d?.onReservationCancelled&&d.onReservationCancelled(),u.current=!1);return}m.current||(m.current=!0,d.onStreamingCandidate(),u.current=!0)}},[d,y]),p.useEffect(()=>{d?.onAnimationStart&&S&&(h.current||(d.onAnimationStart(),h.current=!0))},[d,S]),p.useEffect(()=>{if(t)return;const v=d?.onAnimatedHeightChange;if(!v||!(S||y))return;const w=a.current;if(!w)return;if(typeof window>"u"||typeof ResizeObserver>"u"){v(w.getBoundingClientRect().height);return}let I=null;const E=A=>{if(typeof window>"u"){v(A);return}I!==null&&window.cancelAnimationFrame(I),I=window.requestAnimationFrame(()=>{v(A)})},T=new ResizeObserver(A=>{const j=A[0];j&&E(j.contentRect.height)});return T.observe(w),E(w.getBoundingClientRect().height),()=>{I!==null&&(window.cancelAnimationFrame(I),I=null),T.disconnect()}},[S,t,d,y,a])}function CG(){const e=re(o=>o.setImagePreviewOpen),[t,n]=p.useState({open:!1,title:"",content:""}),r=p.useCallback(o=>{(o.image||o.mermaid)&&(n(o),e(!0))},[e]),s=p.useCallback(o=>{n(i=>({...i,open:o})),e(o)},[e]);return{popupContent:t,handleShowPopup:r,handlePopupChange:s}}const kG=Hs(()=>mt(()=>import("./ToolOutputDialog-aR4kcgKL.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),MG=({message:e,previousMessage:t,nextMessage:n,onContentChange:r,animationHandlers:s,turnGroupingContext:o,isInActiveTurn:i=!1,activeStreamingPhase:a=null,animateUserOnMount:l=!1,onUserAnimationConsumed:d})=>{const{isMobile:f,isTablet:u,hasTouchInput:h}=On(),m=f||u,{currentTheme:g}=vr(),x=p.useRef(null);_s("ui.chat_message.render"),i&&_s("ui.chat_message.render.streaming");const[b,S]=p.useState(!1),v=p.useMemo(()=>Ud(e.info),[e.info]).isUser,C=e.info.sessionID,{headerAgentName:w,headerProviderID:I,headerModelName:E,headerVariant:T}=wG({message:e,previousMessage:t,isUser:v,sessionId:C,isInActiveTurn:i,turnGroupingContext:o}),A=p.useMemo(()=>{const _e=Au(e.parts);return v?dg(_e):_e},[v,e.parts]),j=p.useMemo(()=>{const _e=e.info.time;return typeof _e?.completed=="number"?_e.completed:null},[e.info.time]),k=p.useMemo(()=>{const _e=e.info.time;return typeof _e?.created=="number"?_e.created:null},[e.info.time]),_=p.useMemo(()=>v?!0:!!(j&&j>0),[v,j]),M=p.useMemo(()=>{const _e=e.info.finish;return typeof _e=="string"?_e:void 0},[e.info]),L=p.useMemo(()=>ig(A,{includeReasoning:!0}),[A]),O=p.useMemo(()=>{const _e=new Set;for(const Fe of o?.activityParts??[])_e.add(Fe.id);return _e},[o?.activityParts]),N=p.useMemo(()=>v?L:i9(L,O,e.info.id),[O,v,e.info.id,L]),D=v&&N.some(o9),W=p.useMemo(()=>v?[]:N.filter(_e=>_e.type==="text"),[N,v]),z=p.useMemo(()=>v?[]:L.filter(_e=>_e.type==="tool"),[v,L]),{popupContent:X,handleShowPopup:F,handlePopupChange:U}=CG(),P=p.useMemo(()=>{if(!v)return;const _e=A.find(Ze=>Ze.type==="agent");if(!_e)return;const Fe=_e,ht=typeof Fe.name=="string"?Fe.name:void 0;if(!ht)return;const ge=Fe.source&&typeof Fe.source.value=="string"&&Fe.source.value.trim().length>0?Fe.source.value:`@${ht}`;return{name:ht,token:ge}},[v,A]),q=v&&N.length===0,B=!_&&typeof M!="string",ee=p.useMemo(()=>v?!1:W.length===0||z.length===0?B:!0,[W.length,z.length,B,v]),G=g?.metadata.variant,K=p.useMemo(()=>G?G==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[G]),se=p.useMemo(()=>n?Ud(n.info):null,[n]),de=!!o,oe=o?.isLastAssistantInTurn??!1,ue=p.useMemo(()=>!v&&b9(n),[v,n]),ye=p.useMemo(()=>v?!1:de?!oe:se?!se.isUser&&se.role==="assistant":!1,[de,oe,v,se]),we=p.useMemo(()=>_?"completed":i?a??"streaming":"completed",[a,i,_]);SG({message:e,isUser:v,sessionId:C,streamPhase:we,assistantTextParts:W,shouldCoordinateRendering:ee,animationHandlers:s,messageContainerRef:x}),p.useEffect(()=>{!v||!l||d?.(e.info.id)},[l,v,e.info.id,d]);const Me=p.useMemo(()=>{if(!v)return t9(e.info)},[v,e.info]),He=Me?.text,Ae=Me?.variant,Ge=p.useMemo(()=>lK({isUser:v,displayParts:N,assistantErrorText:He}),[He,N,v]),et=Ge.length>0,Xe=p.useMemo(()=>v?!1:!uK(N,He),[He,N,v]),te=p.useCallback(async()=>{let _e;if(v)_e=await yr(Ge);else{const{renderMarkdownSync:Fe}=await mt(async()=>{const{renderMarkdownSync:ht}=await import("./markdownCore-D5jiabKe.js").then(ge=>ge.m);return{renderMarkdownSync:ht}},__vite__mapDeps([21,8,22,23,24]));_e=await B_(Ge,Fe(Ge))}return _e.ok?(v&&(S(!0),setTimeout(()=>S(!1),2e3)),!0):!1},[v,Ge]);if(q||Xe)return null;const Q="pt-0",me="var(--radius-xl)",Se={sessionId:e.info.sessionID,messageId:e.info.id,parts:N,isUser:v,isMessageCompleted:_,messageFinish:M,messageCreatedAt:k??void 0,isMobile:f,alwaysShowActions:m,hasTouchInput:h,onShowPopup:F,streamPhase:we,onContentChange:r,hasTextContent:et,onCopyMessage:te,copiedMessage:b,agentMention:P,errorMessage:He,errorVariant:Ae,isLatestMessage:!n};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:R("group w-full",v?f?"pt-2":"pt-4":Q,v?f?"pb-0":"pb-2":ye||ue?"pb-0":"pb-2"),id:`message-${e.info.id}`,"data-message-id":e.info.id,ref:x,children:c.jsx("div",{className:"chat-message-column relative",children:v?N.length===0?null:c.jsx(rg,{forceAnimation:!0,skipAnimation:!l,ignoreContextDisabled:!0,respectReducedMotion:!0,children:c.jsx("div",{className:R("relative flex justify-end",f?void 0:"group/user-shell"),children:c.jsxs("div",{className:"flex max-w-[85%] flex-col items-end",children:[D?c.jsx("div",{style:{backgroundColor:"var(--chat-user-message-bg)",borderRadius:me,borderBottomRightRadius:"var(--radius-sm)"},className:R("shadow-none border border-primary/5",f?"px-3 py-2":"px-5 py-3",!f&&"pb-4"),children:c.jsx(jh,{...Se,userActionsMode:"external-content"})}):null,c.jsx(jh,{...Se,userActionsMode:"external-actions"})]})})}):c.jsx("div",{className:"relative",children:c.jsx(jh,{sessionId:e.info.sessionID,messageId:e.info.id,parts:N,isUser:v,isMessageCompleted:_,isLatestMessage:!n,messageFinish:M,messageCompletedAt:j??void 0,messageCreatedAt:k??void 0,isMobile:f,alwaysShowActions:m,hasTouchInput:h,onShowPopup:F,streamPhase:we,onContentChange:r,hasTextContent:et,onCopyMessage:te,copiedMessage:b,agentMention:P,turnGroupingContext:o,errorMessage:He,errorVariant:Ae,footerProviderID:I,footerModelName:E,footerAgentName:w,footerVariant:T,isDarkTheme:K})})})}),c.jsx(p.Suspense,{fallback:null,children:c.jsx(kG,{popup:X,onOpenChange:U,isMobile:f})})]})},IG=p.memo(MG,(e,t)=>k7({info:e.message.info,parts:e.message.parts},{info:t.message.info,parts:t.message.parts})&&Dd(e.previousMessage?{info:e.previousMessage.info,parts:e.previousMessage.parts}:void 0,t.previousMessage?{info:t.previousMessage.info,parts:t.previousMessage.parts}:void 0)&&Dd(e.nextMessage?{info:e.nextMessage.info,parts:e.nextMessage.parts}:void 0,t.nextMessage?{info:t.nextMessage.info,parts:t.nextMessage.parts}:void 0)&&e.isInActiveTurn===t.isInActiveTurn&&e.activeStreamingPhase===t.activeStreamingPhase&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&M7(e.turnGroupingContext,t.turnGroupingContext,e.message.info.id,Ud(e.message.info).isUser)),Wx={info:"bg-status-info/15 text-status-info",success:"bg-status-success/15 text-status-success",warning:"bg-status-warning/15 text-status-warning",error:"bg-status-error/15 text-status-error",neutral:"bg-interactive-hover text-muted-foreground"},EG=e=>typeof e=="string"&&e.length>0&&e in zw,_G=({action:e,variant:t,sessionId:n})=>{const[r,s]=H.useState(!1),[o,i]=H.useState(!1),[a,l]=H.useState(!1),[d,f]=H.useState(""),u=H.useCallback(async b=>{if(!(!n||r)){s(!0);try{await qe().prompt(n,D5(e.command,b),"prompt")}finally{s(!1)}}},[n,r,e.command]),h=H.useCallback(async()=>{if(e.promptForArgs){l(!0),f("");return}await u(e.args)},[e,u]),m=H.useCallback(async()=>{if(!(!n||r||e.disabled)){if(e.confirm){i(!0);return}await h()}},[n,r,e,h]);if(!n)return null;const g=r||e.loading===!0,x=EG(e.icon)?c.jsx(V,{name:e.icon,className:"size-3.5"}):null;return o?c.jsxs("div",{role:"alertdialog","aria-label":e.confirm,className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[c.jsx("span",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:e.confirm}),c.jsx(be,{type:"button",size:"xs",variant:"default",onClick:()=>{i(!1),h()},children:"Continue"}),c.jsx(be,{type:"button",size:"xs",variant:"ghost",onClick:()=>i(!1),children:"Cancel"})]}):a?c.jsxs("form",{className:"flex min-w-0 flex-wrap items-center gap-1.5",onSubmit:b=>{b.preventDefault(),l(!1),u(d)},children:[c.jsx("input",{autoFocus:!0,value:d,onChange:b=>f(b.target.value),placeholder:e.promptForArgs?.placeholder??"","aria-label":e.promptForArgs?.label??e.label,className:"h-6 min-w-0 flex-1 rounded-md border bg-transparent px-2 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focus sm:w-40 sm:flex-none",onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),l(!1))}}),c.jsx(be,{type:"submit",size:"xs",variant:"default",disabled:r,children:"Run"}),c.jsx(be,{type:"button",size:"xs",variant:"ghost",onClick:()=>l(!1),children:"Cancel"})]}):c.jsxs(be,{size:"xs",variant:t,onClick:()=>{m()},disabled:g||e.disabled,"aria-label":e.label,children:[g?c.jsx("span",{"aria-hidden":"true",className:"size-3.5 shrink-0 animate-spin rounded-full border border-current border-t-transparent"}):x,e.label]})},jG=({label:e,value:t,max:n})=>{const r=Math.min(Math.max(t,0),n),s=Math.round(r/n*100);return c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:e??""}),c.jsxs("span",{className:"tabular-nums text-muted-foreground",children:[s,"%"]})]}),c.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-interactive-hover",role:"progressbar","aria-valuenow":s,"aria-valuemin":0,"aria-valuemax":100,"aria-label":e??"Progress",children:c.jsx("div",{className:"h-full rounded-full bg-primary transition-[width] duration-300",style:{width:`${s}%`}})})]})},TG=({body:e,messageId:t,text:n})=>{const[r,s]=H.useState(!1),o=typeof n=="string"&&n.trim().length>0;return c.jsxs("div",{className:"flex flex-col gap-1.5",children:[o&&c.jsx(qo,{messageId:t,content:n,className:"text-sm text-foreground"}),e&&e!==n&&c.jsxs("div",{children:[c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>s(i=>!i),"aria-expanded":r,className:"h-5 gap-1 px-1.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx(V,{name:r?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:"Details"})]}),r&&c.jsx("pre",{className:"mt-1.5 max-h-64 overflow-auto rounded-md border border-border/40 bg-muted/40 p-2 font-mono text-xs leading-relaxed whitespace-pre-wrap text-muted-foreground",children:c.jsx("code",{children:e})})]})]})},AG=({sessionId:e,messageId:t,customType:n,text:r,data:s,details:o,className:i})=>{const a=H.useMemo(()=>cb({customType:n,data:s,details:o,text:r}),[n,s,o,r]),l=a.kind==="ui"?a.descriptor.title:a.title,d=a.kind==="ui"?a.descriptor.actions:void 0,f=a.kind==="ui"?a.descriptor.component:void 0,u=()=>{if(!f)return c.jsx(TG,{body:a.kind==="fallback"?a.body:"",messageId:t,text:r});switch(f.component){case"markdown":return c.jsx(qo,{messageId:t,content:f.body,className:"text-sm"});case"kv":return c.jsx("dl",{className:"grid grid-cols-[minmax(6rem,auto)_1fr] gap-x-3 gap-y-1.5 text-sm",children:f.rows.map(h=>c.jsxs(H.Fragment,{children:[c.jsx("dt",{className:"truncate text-muted-foreground",children:h.label}),c.jsx("dd",{className:R("break-words",Wx[h.tone??"neutral"]?.split(" ")[1]),children:h.value})]},`${h.label}:${h.value}`))});case"list":return c.jsx("ul",{className:"flex flex-col gap-1.5 text-sm",children:f.items.map(h=>c.jsxs("li",{className:"flex items-baseline gap-2",children:[c.jsx("span",{className:"size-1.5 shrink-0 translate-y-[-1px] rounded-full bg-interactive-hover"}),c.jsx("span",{className:"font-medium",children:h.label}),h.value&&c.jsx("span",{className:"text-muted-foreground",children:h.value})]},`${h.label}:${h.value}`))});case"table":return c.jsx("div",{className:"overflow-x-auto",children:c.jsxs("table",{className:"w-full border-collapse text-sm",children:[c.jsx("thead",{children:c.jsx("tr",{children:f.columns.map(h=>c.jsx("th",{className:"border-b px-2 py-1.5 text-left font-medium text-muted-foreground",children:h},h))})}),c.jsx("tbody",{children:f.rows.map((h,m)=>c.jsx("tr",{children:h.map((g,x)=>c.jsx("td",{className:"border-b px-2 py-1.5 break-words",children:g},x))},m))})]})});case"progress":{const h=f.max??100;return c.jsx(jG,{label:f.label,value:f.value,max:h>0?h:100})}case"badges":return c.jsx("div",{className:"flex flex-wrap gap-1.5",children:f.items.map(h=>c.jsx("span",{className:R("rounded-full px-2 py-0.5 text-xs font-medium",Wx[h.tone??"neutral"]),children:h.label},h.label))});case"code":return c.jsx("pre",{className:"max-h-80 overflow-auto rounded-md border border-border/40 bg-muted/40 p-2 font-mono text-xs leading-relaxed",children:c.jsx("code",{children:f.code})});default:return null}};return c.jsxs("div",{className:R("my-1 flex flex-col gap-2 rounded-xl border border-border/60 bg-card p-3 text-card-foreground shadow-sm",i),"data-extension-ui":t,children:[(l!==void 0||d!==void 0)&&c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l!==void 0&&c.jsx("div",{className:"flex min-w-0 items-center gap-1.5",children:c.jsx("span",{className:"text-xs font-medium tracking-wide text-muted-foreground uppercase",children:l})}),d!==void 0&&c.jsx("div",{className:"flex shrink-0 flex-wrap gap-1.5",children:d.map(h=>c.jsx(_G,{action:h,variant:h.variant??"outline",sessionId:e},`${h.command}:${h.label}`))})]}),u()]})},NG=({messageId:e,customType:t,text:n,data:r,details:s,render:o,className:i})=>{const[a,l]=H.useState(!1),[d,f]=H.useState(!1),[u,h]=H.useState(!1),m=s!==void 0?s:r,g=m!=null,x=typeof n=="string"&&n.trim().length>0,b=t||"extension",S=Array.isArray(o?.message)&&o.message.length>0?o.message:void 0,y=Array.isArray(o?.messageExpanded)&&o.messageExpanded.length>0?o.messageExpanded:void 0,v=d&&y?y:S,C=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:{color:"var(--tools-icon)"},children:c.jsx(V,{name:"plug-2",className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Gr,"shrink-0"),style:ti,children:"Extension"}),c.jsx("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:b,children:b})]});return c.jsxs("div",{className:R("py-1",i),"data-extension-ui":e,children:[g&&!S?c.jsxs("button",{type:"button",onClick:()=>l(w=>!w),"aria-expanded":a,"aria-label":a?`Hide ${b} details`:`Show ${b} details`,className:"group/extension-note flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2 text-left",children:[C,c.jsx(V,{name:"arrow-right-s","aria-hidden":"true",className:R("size-3.5 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] duration-150 group-hover/extension-note:opacity-100 group-focus-visible/extension-note:opacity-100",a&&"rotate-90 opacity-100")})]}):c.jsx("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:C}),g&&a&&!S&&c.jsxs("div",{className:"relative mb-1 ml-2 pl-3",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px bg-[var(--tools-border)]"}),c.jsx("div",{className:"max-h-80 overflow-auto",children:c.jsx($d,{data:m})})]}),v&&c.jsx("div",{className:"my-1 max-h-80 overflow-x-auto overflow-y-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-code","data-extension-message-render":"true",children:v.map((w,I)=>c.jsx("div",{className:"min-h-[1.25em] leading-relaxed",children:c.jsx(qt,{text:w})},I))}),S&&y&&c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>f(w=>!w),"aria-expanded":d,className:"h-5 gap-1 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx(V,{name:d?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:d?"Show less":"Show more"})]}),S&&(x||g)&&c.jsxs("div",{children:[c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>h(w=>!w),"aria-expanded":u,className:"h-5 gap-1 px-1.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx(V,{name:u?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:"Raw message"})]}),u&&c.jsxs("div",{className:"relative mb-1 ml-2 pl-3",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px bg-[var(--tools-border)]"}),x&&c.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:c.jsx(qo,{messageId:e,content:n,variant:"assistant"})}),g&&c.jsx("div",{className:"max-h-80 overflow-auto",children:c.jsx($d,{data:m})})]})]}),!S&&x&&c.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:c.jsx(qo,{messageId:e,content:n,variant:"assistant"})})]})},Kx=12,Gx={info:{label:"Notice",icon:"information"},warning:{label:"Warning",icon:"alert"},error:{label:"Error",icon:"error-warning"}},LG=({messageId:e,level:t,message:n,className:r})=>{const[s,o]=H.useState(!1),i=Gx[t]??Gx.info,a=typeof n=="string"&&n.trim().length>0?n:"Extension notification",l=a.split(`
|
|
214
|
+
`),d=H.useMemo(()=>AN(a),[a]),f=he(S=>S.currentSessionDirectory),u=re(S=>S.isMobile),h=d.filter(S=>Tp(S)==="external"||!u&&!!f),m=l.length>Kx,g=!m||s?l:l.slice(0,Kx),x=t==="error"?{color:"var(--status-error)"}:t==="warning"?{color:"var(--status-warning)"}:{color:"var(--tools-icon)"},b=t==="error"?{color:"var(--status-error)"}:t==="warning"?{color:"var(--status-warning)"}:ti;return c.jsxs("div",{className:R("py-1",r),"data-extension-notice":e,children:[c.jsxs("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:x,children:c.jsx(V,{name:i.icon,className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Gr,"shrink-0"),style:b,children:i.label}),c.jsx("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:"Extension notice",children:"Extension"})]}),c.jsx("div",{className:"my-1 max-h-80 overflow-x-auto overflow-y-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-code","data-extension-notice-body":"true",children:g.map((S,y)=>c.jsx("div",{className:"min-h-[1.25em] leading-relaxed w-max min-w-full",children:c.jsx(qt,{text:S})},y))}),h.length>0&&c.jsx("div",{className:"flex min-w-0 flex-wrap gap-1",children:h.map(S=>c.jsx(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>LN(Tp(S),S,f??""),title:S,className:"h-5 min-w-0 max-w-full px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:c.jsxs("span",{className:"truncate",children:["Open ",_N(S)]})},S))}),m&&c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>o(S=>!S),"aria-expanded":s,"aria-label":s?"Show less of the extension notice":"Show more of the extension notice",className:"h-5 gap-1 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx(V,{name:s?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:s?"Show less":"Show more"})]})]})},RG=e=>{if(e.kind==="recorded"){const{details:s}=e,o=typeof s.exitCode=="number"?s.exitCode:void 0;return{command:s.command,output:s.output,running:!1,status:s.cancelled?{text:"Cancelled",tone:"muted"}:o!==void 0&&o!==0?{text:`Exit code ${o}`,tone:"error"}:null,excludeFromContext:s.excludeFromContext===!0,truncated:s.truncated===!0,fullOutputPath:s.fullOutputPath}}const{execution:t}=e,n=typeof t.exitCode=="number"?t.exitCode:void 0,r=t.phase==="completed"||t.phase==="cancelled";return{command:t.command,output:t.output??"",running:t.phase==="running",status:t.phase==="running"?{text:"Running",tone:"muted"}:t.phase==="failed"?{text:"Failed",tone:"error"}:t.phase==="cancelled"?{text:"Cancelled",tone:"muted"}:n!==void 0&&n!==0?{text:`Exit code ${n}`,tone:"error"}:null,excludeFromContext:t.excludeFromContext===!0,truncated:t.truncated===!0,fullOutputPath:t.fullOutputPath,note:t.phase==="failed"?t.error:r?"Added to the conversation when the current response ends.":void 0}},PG=8,DG=({messageId:e,sessionId:t,state:n,className:r})=>{const s=RG(n),[o,i]=H.useState(!1),a=!!s.fullOutputPath&&xt()&&Jo(),l=H.useRef(null),d=H.useRef(!0),f=H.useCallback(()=>{const h=l.current;h&&(d.current=h.scrollHeight-h.scrollTop-h.clientHeight<=PG)},[]);H.useLayoutEffect(()=>{const h=l.current;!h||!d.current||(h.scrollTop=h.scrollHeight)},[s.output]);const u=H.useCallback(()=>{!t||o||(i(!0),Nw(t).catch(h=>{Ce.error(h instanceof Error&&h.message?h.message:"Failed to stop the command")}).finally(()=>i(!1)))},[t,o]);return c.jsxs("div",{className:R("py-1",r),"data-bash-execution":e,children:[c.jsxs("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:v7,children:c.jsx(V,{name:"terminal-box",className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Gr,"shrink-0 font-normal"),style:{color:"var(--tools-description)"},children:"Shell"}),c.jsx("span",{className:R(Mt,"min-w-0 truncate text-foreground"),title:s.command,children:s.command}),s.status?s.status.tone==="error"?c.jsx("span",{className:"shrink-0 rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-1.5 typography-micro font-medium text-[var(--status-error)]",children:s.status.text}):c.jsx("span",{className:"shrink-0 typography-micro",style:{color:"var(--tools-description)"},children:s.status.text}):null,s.truncated?c.jsx("span",{className:"shrink-0 rounded border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] px-1.5 typography-micro font-medium text-[var(--status-warning)]",children:"Output truncated"}):null,s.excludeFromContext?c.jsx("span",{className:"shrink-0 rounded border border-[var(--status-info-border)] bg-[var(--status-info-background)] px-1.5 typography-micro font-medium text-[var(--status-info)]",children:"Not sent to the model"}):null,s.running&&t?c.jsx(be,{type:"button",variant:"ghost",size:"xs",onClick:u,disabled:o,"aria-label":"Stop the shell command",className:"ml-auto h-5 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:"Stop"}):null]}),s.truncated?c.jsx("p",{className:"mt-1 typography-micro text-muted-foreground text-pretty",children:a?c.jsxs(c.Fragment,{children:["Earlier output was cut; the full output is in ",c.jsx("span",{className:"font-mono break-all select-text text-foreground",children:s.fullOutputPath})]}):"Earlier output was discarded. Only the last 50 KB is kept."}):null,s.output.length>0?c.jsx("pre",{ref:l,onScroll:f,className:"my-1 max-h-80 overflow-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-code leading-relaxed","data-no-drawer-swipe":"true",children:s.output}):null,s.note?c.jsx("p",{className:"typography-micro text-pretty",style:{color:n.kind==="live"&&n.execution.phase==="failed"?"var(--status-error)":"var(--tools-description)"},children:s.note}):null]})},ug="pichamber.notice",OG=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},Zx=new WeakMap,Yx=(e,t)=>{const n=Zx.get(e);if(n&&n.sessionId===t)return n.entry;const r=HG(e,t);return Zx.set(e,{sessionId:t,entry:r}),r},HG=(e,t)=>({info:{id:`notice:${e.id}`,sessionID:t,role:"extension",customType:ug,text:e.message,noticeLevel:e.level,time:{created:e.createdAt,completed:e.createdAt}},parts:[]}),FG=(e,t,n)=>{if(!n||t.length===0)return e;const r=[...t].sort((i,a)=>i.createdAt-a.createdAt),s=[];let o=0;for(const i of e){const a=OG(i);for(;o<r.length&&(a===void 0||r[o].createdAt<=a);)s.push(Yx(r[o],n)),o+=1;s.push(i)}for(;o<r.length;)s.push(Yx(r[o],n)),o+=1;return s},fg=p.memo(({message:e,previousMessage:t,nextMessage:n,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:l,animationHandlers:d,scrollToBottom:f})=>{const u=e.info;if(u.role==="extension"&&u.customType===ug){const h=u.noticeLevel,m=h==="warning"||h==="error"?h:"info";return c.jsx("div",{className:"chat-message-column",children:c.jsx(LG,{messageId:e.info.id,level:m,message:typeof u.text=="string"?u.text:""})})}if(u.role==="extension"&&u.customType===Kl){const h=u.bashExecution,m=u.details;if(h||m&&typeof m.command=="string"&&typeof m.output=="string")return c.jsx("div",{className:"chat-message-column",children:c.jsx(DG,{messageId:e.info.id,sessionId:u.sessionID,state:h?{kind:"live",execution:h}:{kind:"recorded",details:m}})})}if(u.role==="extension"){const h=cb({customType:u.customType,data:u.data,details:u.details,text:typeof u.text=="string"?u.text:void 0});return c.jsx("div",{className:"chat-message-column",children:h.kind==="ui"?c.jsx(AG,{sessionId:u.sessionID,messageId:e.info.id,customType:u.customType,text:typeof u.text=="string"?u.text:void 0,data:u.data,details:u.details}):c.jsx(NG,{messageId:e.info.id,customType:u.customType,text:typeof u.text=="string"?u.text:void 0,data:u.data,details:u.details,render:u.render})})}return c.jsx(IG,{message:e,previousMessage:t,nextMessage:n,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:l,animationHandlers:d,scrollToBottom:f,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o})},(e,t)=>{const n=e.turnGroupingContext,r=t.turnGroupingContext;return k7(e.message,t.message)&&Dd(e.previousMessage,t.previousMessage)&&Dd(e.nextMessage,t.nextMessage)&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&e.onContentChange===t.onContentChange&&e.scrollToBottom===t.scrollToBottom&&M7(n,r,e.message.info.id,Ps(e.message)==="user")&&e.isInActiveTurn===t.isInActiveTurn&&e.activeStreamingPhase===t.activeStreamingPhase&&e.animationHandlers?.onChunk===t.animationHandlers?.onChunk&&e.animationHandlers?.onComplete===t.animationHandlers?.onComplete&&e.animationHandlers?.onStreamingCandidate===t.animationHandlers?.onStreamingCandidate&&e.animationHandlers?.onAnimationStart===t.animationHandlers?.onAnimationStart&&e.animationHandlers?.onReservationCancelled===t.animationHandlers?.onReservationCancelled&&e.animationHandlers?.onAnimatedHeightChange===t.animationHandlers?.onAnimatedHeightChange});fg.displayName="MessageRow";const w9=p.memo(({turn:e,isLastTurn:t,nextEntryFirstMessage:n,sessionIsWorking:r,sessionAwaitingRecovery:s=!1,awaitingPromptEcho:o=!1,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})=>{const m=p.useMemo(()=>{const _=[e.userMessage,...e.assistantMessages],M=new Map;return _.forEach((L,O)=>{M.set(L.info.id,O)}),{ordered:_,lookup:M}},[e.assistantMessages,e.userMessage]),g=p.useMemo(()=>BN({activeStreamingMessageId:u,assistantMessages:e.assistantMessages}),[u,e.assistantMessages]),x=e.assistantMessages,b=p.useMemo(()=>{const _=new Map;return x.forEach((M,L)=>{_.set(M.info.id,L)}),_},[x]),S=p.useMemo(()=>Ch(e,g),[e,g]),y=Ch(e,u),v=t&&s,C=p.useMemo(()=>S&&g?g:x[0]?.info.id,[g,S,x]),w=e.activityParts,I=e.activitySegments,E=p.useMemo(()=>{const _=new Map;for(const M of w){const L=_.get(M.messageId)??[];L.push(M),_.set(M.messageId,L)}return _},[w]),T=p.useMemo(()=>{const _=e.userMessage.info.time?.created,M=e.userMessage.info,L=M?.model?.variant??M?.variant,O=typeof L=="string"&&L.trim().length>0?L:void 0;return{turnId:e.turnId,summaryBody:e.summaryText,activityParts:w,activityGroupSegments:I,headerMessageId:e.headerMessageId,hasTools:e.hasTools,hasReasoning:e.hasReasoning,diffStats:e.diffStats,changedFiles:e.changedFiles,userMessageCreatedAt:typeof _=="number"?_:void 0,userMessageVariant:O}},[e.changedFiles,e.diffStats,e.hasReasoning,e.hasTools,e.headerMessageId,e.summaryText,e.turnId,e.userMessage.info,w,I]),A=p.useCallback(_=>{const L=Ps(_)==="user",O=m.lookup.get(_.info.id),N=b.get(_.info.id)??-1,D=N>=0,W=N===0,z=N===x.length-1,F=!!C&&_.info.id===C||W||z,U=E.get(_.info.id)??[],P=L?void 0:D?W?e.userMessage:void 0:typeof O=="number"&&O>0?m.ordered[O-1]:void 0,q=D&&z?n:void 0,B=D?{turnId:e.turnId,activityOwnerMessageId:C,isFirstAssistantInTurn:W,isLastAssistantInTurn:z,isLatestTurn:t,isWorking:UN({messageId:_.info.id,activeStreamingMessageId:u,isRetrying:Uz(_),isAwaitingRecovery:v&&z}),hasTools:e.hasTools,hasReasoning:e.hasReasoning,...F?{summaryBody:T.summaryBody,activityParts:T.activityParts,activityGroupSegments:T.activityGroupSegments,headerMessageId:T.headerMessageId,diffStats:T.diffStats,changedFiles:T.changedFiles,userMessageCreatedAt:T.userMessageCreatedAt,userMessageVariant:T.userMessageVariant}:{activityParts:U}}:void 0;return c.jsx(fg,{message:_,previousMessage:P,nextMessage:q,turnGroupingContext:B,isInActiveTurn:!!g&&_.info.id===g,activeStreamingPhase:_.info.id===g?h:null,animateUserOnMount:d(_),onUserAnimationConsumed:f,onContentChange:i,animationHandlers:a(_.info.id),scrollToBottom:l},_.info.id)},[a,t,n,m.lookup,m.ordered,i,l,e.hasReasoning,e.hasTools,e.turnId,e.userMessage,T,g,u,h,x,b,C,E,v,d,f]),j=!Ch(e,u),k=zN({isLastTurn:t,sessionIsWorking:r,turnIsInActiveStream:e.stream.isStreaming&&y,activeStreamingMessageId:u,isSteering:e.isSteering,awaitingPromptEcho:o});return c.jsx(HK,{turn:e,renderMessage:A,deferEarlierAssistantMessages:j,showWorkingStatus:k,isAwaitingRecovery:v&&!k,activeStreamingMessageId:u,activeStreamingPhase:h,onActivityContentChange:i})});w9.displayName="TurnBlock";const S9=p.memo(({message:e,previousMessage:t,nextMessage:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,shouldAnimateUserMessage:i,onUserAnimationConsumed:a,activeStreamingMessageId:l,activeStreamingPhase:d})=>c.jsx(fg,{message:e,previousMessage:t,nextMessage:n,isInActiveTurn:!!l&&e.info.id===l,activeStreamingPhase:e.info.id===l?d:null,animateUserOnMount:i(e),onUserAnimationConsumed:a,onContentChange:r,animationHandlers:s(e.info.id),scrollToBottom:o}));S9.displayName="UngroupedMessageRow";const BG=new Set(["task"]),VG=e=>typeof e=="string"&&BG.has(e.toLowerCase()),$G=e=>{const t=e.state?.time?.end;if(typeof t=="number")return t;const n=e.time?.end;return typeof n=="number"?n:void 0},Xx=e=>{const t=e.text;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.content;if(typeof n=="string"&&n.trim().length>0)return n},zG=e=>{const t=e.info.finish;return typeof t=="string"?t:void 0},UG=e=>e.info.summary===!0,qG=(e,t,n,r)=>({id:n.id??`${t}-part-${r}-${n.type}`,turnId:e,messageId:t,part:n,partIndex:r,endedAt:$G(n)}),WG=e=>{const t=[];let n=!1,r=!1;e.assistantMessages.forEach(g=>{g.parts.forEach(x=>{if(x.type==="tool"){n=!0;return}x.type==="reasoning"&&Xx(x)&&(r=!0)})});const s=new Map,o=[],i=e.summarySourceMessageId?e.assistantMessages.findIndex(g=>g.info.id===e.summarySourceMessageId):-1,a=i>=0&&e.summarySourcePartId?e.assistantMessages[i]?.parts.findIndex((g,x)=>(g.id??`${e.assistantMessages[i]?.info.id}-part-${x}-${g.type}`)===e.summarySourcePartId)??-1:-1,l=e.assistantMessages.some(g=>g.parts.some(x=>x.type==="tool"||x.type==="reasoning")),d=new Map;let f=null;e.assistantMessages.forEach((g,x)=>{const b=zG(g),S=g.parts.some(v=>v.type==="tool"),y=UG(g);g.parts.forEach((v,C)=>{const w=v.type==="tool",I=v.type==="reasoning"||v.type==="text"?Xx(v):void 0,E=v.id??`${g.info.id}-part-${C}-${v.type}`,T=w?v.tool:void 0,A=w&&VG(T);if(A){const O=E;s.has(O)||(s.set(O,g.info.id),o.push(O)),f=O}const j=v.type==="text"&&typeof I=="string"&&(b==="stop"||typeof b!="string")&&e.summarySourceMessageId===g.info.id&&e.summarySourcePartId===E,k=i>=0&&(x<i||x===i&&a>=0&&C<a);let _=null;if(w?_="tool":v.type==="reasoning"?I&&(_="reasoning"):e.showTextJustificationActivity&&v.type==="text"&&I&&(y||!j&&(S||typeof b=="string"&&b!=="stop"||l||k))&&(_="justification"),!_)return;const M={...qG(e.turnId,g.info.id,v,C),kind:_};if(t.push(M),_==="tool"&&A)return;const L=d.get(f)??[];L.push(M),d.set(f,L)})});const u=[],h=g=>{if(g.length===0)return;const x=new Map;g.forEach(S=>{x.set(S.messageId,(x.get(S.messageId)??0)+1)});let b;for(const S of e.assistantMessages)(x.get(S.info.id)??0)>0&&!b&&(b=S.info.id);return b};return[null,...o].forEach(g=>{const x=d.get(g)??[];if(x.length===0)return;const b=g===null?h(x):s.get(g);b&&u.push({id:`${e.turnId}:${b}:${g??"start"}`,anchorMessageId:b,afterToolPartId:g,parts:x})}),{activityParts:t,activitySegments:u,hasTools:n,hasReasoning:r}},KG=e=>{const t=new Map,n=new Map,r=new Map,s=new Set;e.forEach(a=>{t.set(a.turnId,a);const l=a.assistantMessages[0]?.info.id,d=a.assistantMessages[a.assistantMessages.length-1]?.info.id;n.set(a.userMessageId,a.turnId),s.add(a.userMessageId),r.set(a.userMessageId,{turnId:a.turnId,messageId:a.userMessageId,userMessageId:a.userMessageId,isUserMessage:!0,isAssistantMessage:!1,isFirstAssistantInTurn:!1,isLastAssistantInTurn:!1,headerMessageId:a.headerMessageId}),a.assistantMessageIds.forEach(f=>{n.set(f,a.turnId),s.add(f),r.set(f,{turnId:a.turnId,messageId:f,userMessageId:a.userMessageId,isUserMessage:!1,isAssistantMessage:!0,isFirstAssistantInTurn:f===l,isLastAssistantInTurn:f===d,headerMessageId:a.headerMessageId})}),(a.notices??[]).forEach(f=>{n.set(f.info.id,a.turnId),s.add(f.info.id),r.set(f.info.id,{turnId:a.turnId,messageId:f.info.id,userMessageId:a.userMessageId,isUserMessage:!1,isAssistantMessage:!1,isFirstAssistantInTurn:!1,isLastAssistantInTurn:!1,headerMessageId:a.headerMessageId})})});const o=e.length>0?e[e.length-1]:null,i=new Set;return o&&(i.add(o.userMessageId),o.assistantMessageIds.forEach(a=>{i.add(a)}),(o.notices??[]).forEach(a=>{i.add(a.info.id)})),{turns:e,indexes:{turnById:t,messageToTurnId:n,messageMetaById:r},lastTurnId:o?.turnId??null,lastTurnMessageIds:i,ungroupedMessageIds:new Set}},GG=e=>{const t=e.text;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.content;if(typeof n=="string"&&n.trim().length>0)return n},ZG=e=>e.info.summary===!0,Jx=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!ZG(r)&&!(t&&r.info.finish!=="stop"))for(let s=r.parts.length-1;s>=0;s-=1){const o=r.parts[s];if(!o||o.type!=="text")continue;const i=GG(o);if(i)return{text:i,sourceMessageId:r.info.id,sourcePartId:o.id??`${r.info.id}-part-${s}-text`}}}},YG=e=>Jx(e,!0)??Jx(e,!1)??{},XG=e=>{const n=e.info.summary?.diffs;if(!Array.isArray(n)||n.length===0)return;let r=0,s=0,o=0;if(n.forEach(i=>{if(!i)return;const a=typeof i.additions=="number"?i.additions:0,l=typeof i.deletions=="number"?i.deletions:0;(a!==0||l!==0)&&(o+=1),r+=a,s+=l}),o!==0)return{additions:r,deletions:s,files:o}},fm=[],Yi=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},C9=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},k9=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},JG=e=>{const t=e.info.time?.completed;return typeof t=="number"?t:void 0},QG=e=>{const t=e.info?.summary?.body;return typeof t!="string"?void 0:t.trim().length>0?t:void 0},M9=e=>{const t=e.info;return t.role==="extension"&&t.customType===ug},eZ=(e,t)=>{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},Ah=(e,t)=>{const n=Yi(e);return{messageId:e.info.id,role:n,parentMessageId:C9(e),message:e,order:t}},tZ=(e,t)=>{const n=k9(e);let r,s=!1;t.forEach(i=>{const a=JG(i);typeof a=="number"?r=Math.max(r??0,a):s=!0});const o=typeof n=="number"&&typeof r=="number"&&r>=n?r-n:void 0;return{isStreaming:s,isRetrying:t.length>1,startedAt:n,completedAt:r,durationMs:o}},nZ={previousProjection:null,showTextJustificationActivity:!1,mergeHiddenUserTurns:void 0},rZ=(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},sZ=(e,t)=>e.userMessage===t.userMessage&&e.headerMessageId===t.headerMessageId&&rZ(e.assistantMessages,t.assistantMessages),Qx=(e,t)=>{e.summary=YG(e.assistantMessages),e.summaryText=e.summary.text??QG(e.userMessage),e.diffStats=XG(e.userMessage),e.changedFiles=void 0;const n=WG({turnId:e.turnId,assistantMessages:e.assistantMessages,summarySourceMessageId:e.summary.sourceMessageId,summarySourcePartId:e.summary.sourcePartId,showTextJustificationActivity:t.showTextJustificationActivity});return e.activityParts=n.activityParts,e.activitySegments=n.activitySegments,e.hasTools=n.hasTools,e.hasReasoning=n.hasReasoning,e.stream=tZ(e.userMessage,e.assistantMessages),e.startedAt=e.stream.startedAt,e.completedAt=e.stream.completedAt,e.durationMs=e.stream.durationMs,e},oZ=e=>{let t=!1;const n=[...e];for(let r=1;r<e.length;r+=1){const s=n[r-1],o=n[r],i=o.startedAt;if(!s.stream.isStreaming||typeof i!="number")continue;const a=s.startedAt,l=typeof a=="number"&&i>=a?i-a:void 0;n[r-1]={...s,stream:{...s.stream,isStreaming:!1,completedAt:i,durationMs:l,settledReason:"steered"},completedAt:i,durationMs:l},n[r]=o.isSteering?o:{...o,isSteering:!0},t=!0}return t?n:e},iZ=(e,t)=>{const n=t.previousProjection;if(!n||n.turns.length===0||e.length===0)return e.map(i=>Qx(i,t));let r=n.turns.length===e.length,s=!1;const o=e.map((i,a)=>{const l=n.indexes.turnById.get(i.turnId);return l&&sZ(l,i)?(s=!0,n.turns[a]!==l&&(r=!1),l):(r=!1,Qx(i,t))});return r&&s?n.turns:o},aZ=(e,t,n)=>{if(n.size===0&&e.every(a=>a.notices.length===0))return e;const r=new Map;e.forEach(a=>r.set(a.turnId,a));const s=new Map;t.forEach(a=>{if(!M9(a))return;const l=n.get(a.info.id);if(!l)return;const d=r.get(l);if(!d)return;if(d.completedAt!==void 0){const u=k9(a);if(u===void 0||u>d.completedAt)return}const f=s.get(l);f?f.push(a):s.set(l,[a])});let o=!1;const i=e.map(a=>{const l=s.get(a.turnId),d=a.notices??fm;return l?eZ(d,l)?a:(o=!0,{...a,notices:l}):d.length===0?a:(o=!0,{...a,notices:fm})});return o?i:e},I9=(e,t)=>{const n={...nZ,...t},r=[],s=new Map,o=new Set,i=n.mergeHiddenUserTurns;e.forEach((h,m)=>{if(Yi(h)!=="user")return;const x=r[r.length-1];if(i&&x&&b9(h)){s.set(h.info.id,x),x.messages.push(Ah(h,m)),o.add(h.info.id);return}const S={turnId:h.info.id,isSteering:!1,userMessageId:h.info.id,userMessage:h,notices:fm,headerMessageId:void 0,messages:[Ah(h,m)],assistantMessageIds:[],assistantMessages:[],activityParts:[],activitySegments:[],summary:{},summaryText:void 0,hasTools:!1,hasReasoning:!1,diffStats:void 0,changedFiles:void 0,stream:{isStreaming:!1,isRetrying:!1}};r.push(S),s.set(S.userMessageId,S),o.add(h.info.id)}),e.forEach((h,m)=>{if(Yi(h)!=="assistant")return;const x=C9(h),b=x?s.get(x):void 0;b&&(b.assistantMessages.push(h),b.assistantMessageIds.push(h.info.id),b.messages.push(Ah(h,m)),b.headerMessageId||(b.headerMessageId=h.info.id),o.add(h.info.id))});const a=new Map;{let h=null;e.forEach(m=>{if(Yi(m)==="user"){h=s.get(m.info.id)??null;return}M9(m)&&h&&a.set(m.info.id,h.turnId)})}const l=oZ(iZ(r,n)),d=aZ(l,e,a);d.forEach(h=>{h.notices.length!==0&&h.notices.forEach(m=>o.add(m.info.id))});const f=KG(d),u=new Set;return e.forEach(h=>{Yi(h)!=="assistant"&&(o.has(h.info.id)||u.add(h.info.id))}),{...f,ungroupedMessageIds:u}},cZ=30,lZ=4,Lr=new Map,e5=new WeakMap;let t5=1;const dZ=()=>un()?lZ:cZ,Nh=e=>{const t=e5.get(e);if(t!==void 0)return t;const n=t5;return t5+=1,e5.set(e,n),n},uZ=e=>e.map(t=>{const n=Nh(t.info),r=Nh(t.parts),s=t.parts.map(o=>Nh(o)).join(",");return`${n}:${r}:${s}`}).join(";"),fZ=(e,t,n,r)=>{const s=t.length>0?t[t.length-1]:void 0,o=s?.info?.id??"",i=s?.parts?.length??0;return[e,t.length,o,i,uZ(t),n?"1":"0",r].join("|")},hZ=e=>{const t=Lr.get(e);return t&&(Lr.delete(e),Lr.set(e,t)),t},pZ=(e,t)=>{Lr.delete(e);const n=dZ();for(;Lr.size>=n;){const r=Lr.keys().next().value;if(typeof r!="string")break;Lr.delete(r)}Lr.set(e,t)},mZ=(e,t)=>{const n=p.useRef(null),r=p.useRef([]),s=p.useRef(void 0),o=p.useRef(t.sessionKey),i=p.useRef(t.showTextJustificationActivity);(o.current!==t.sessionKey||i.current!==t.showTextJustificationActivity)&&(o.current=t.sessionKey,i.current=t.showTextJustificationActivity,n.current=null,r.current=[],s.current=void 0),p.useEffect(()=>{n.current=null,r.current=[],s.current=void 0},[t.sessionKey,t.showTextJustificationActivity]);const a=p.useMemo(()=>{const f=t.sessionKey??"",u=fZ(f,e,t.showTextJustificationActivity,"merge"),h=hZ(u);return h?(n.current=h,h):vl("ui.turns.projection_ms",()=>{const m=I9(e,{previousProjection:n.current,showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:!0});return n.current=m,pZ(u,m),m})},[e,t.showTextJustificationActivity,t.sessionKey]),l=p.useMemo(()=>{const f=a.turns.length<=1?[]:a.turns.slice(0,-1),u=r.current;if(u.length===f.length){let h=!0;for(let m=0;m<f.length;m+=1)if(u[m]!==f[m]){h=!1;break}if(h)return u}return r.current=f,f},[a.turns]),d=p.useMemo(()=>{const f=a.turns.length===0?void 0:a.turns[a.turns.length-1];return s.current===f?s.current:(s.current=f,f)},[a.turns]);return{projection:a,staticTurns:l,streamingTurn:d}},gZ=1.5,yZ=({hasMoreBefore:e,beforeCursor:t,resolveScrollContainer:n,loadOlder:r,onBeforeLoad:s,onLoadError:o})=>{p.useEffect(()=>{if(!e||!t)return;const i=n();if(!i)return;let a=!1,l,d=!0;const f=()=>{if(a||!e)return;const u=i.scrollTop<i.clientHeight*gZ,h=i.scrollHeight<=i.clientHeight+1;!u&&!h||(a=!0,s(),r().then(m=>{d&&(a=!1,m&&(l=window.setTimeout(f,0)))}).catch(()=>{d&&(a=!1,o())}))};return i.addEventListener("scroll",f,{passive:!0}),f(),()=>{d=!1,l!==void 0&&window.clearTimeout(l),i.removeEventListener("scroll",f)}},[t,e,r,s,o,n])},n5=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},r5=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},vZ=(e,t,n)=>{if(!t||!n)return e;const r={name:"SessionCompaction",message:n.message,data:{...n}},s=n.completedAt??n.startedAt;let o=-1;for(let f=e.length-1;f>=0;f-=1){const u=r5(e[f]);if(!(s!==void 0&&u!==void 0&&u>s)&&n5(e[f])==="user"){o=f;break}}if(o<0)return e;let i=-1;for(let f=o+1;f<e.length;f+=1){const u=r5(e[f]);if(s!==void 0&&u!==void 0&&u>s)break;n5(e[f])==="assistant"&&(i=f)}if(i>=0)return e.map((f,u)=>u===i?{...f,info:{...f.info,error:r}}:f);const a=s??0,l={info:{id:`synthetic_compaction_notice_${t}`,sessionID:t,role:"assistant",parentID:e[o].info.id,time:{created:a,completed:a},finish:"stop",error:r},parts:[]},d=e.slice();return d.splice(o+1,0,l),d},s5=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},xZ=(e,t)=>{if(!t.sessionId)return e;const n={name:"SessionRetry",message:t.message,data:{message:t.message}};let r=-1;for(let d=e.length-1;d>=0;d-=1)if(s5(e[d])==="user"){r=d;break}if(r<0)return e;let s=-1;for(let d=e.length-1;d>r;d-=1)if(s5(e[d])==="assistant"){s=d;break}if(s>=0)return e.map((d,f)=>f!==s?d:{...d,info:{...d.info,error:n}});const o=typeof t.confirmedAt=="number"?t.confirmedAt:t.fallbackTimestamp,a={info:{id:`synthetic_retry_notice_${t.sessionId}`,sessionID:t.sessionId,role:"assistant",parentID:e[r].info.id,time:{created:o,completed:o},finish:"stop",error:n},parts:[]},l=e.slice();return l.splice(r+1,0,a),l},o5=new WeakMap,bZ=(e,t)=>{const n=o5.get(e);if(n&&n.sessionId===t)return n.entry;const r={info:{id:`bash:${e.id}`,sessionID:t,role:"extension",customType:Kl,bashExecution:e,time:{created:e.startedAt,...e.completedAt?{completed:e.completedAt}:{}}},parts:[]};return o5.set(e,{sessionId:t,entry:r}),r},wZ=(e,t,n)=>!n||t.length===0?e:[...e,...t.map(r=>bZ(r,n))],i5=[],SZ=({staticTurns:e,messages:t,ungroupedMessageIds:n,lastTurnId:r,tailUserMessageId:s})=>{const o=e.map(h=>({kind:"turn",key:`turn:${h.turnId}`,turn:h,isLastTurn:h.turnId===r}));if(n.size===0)return{entries:o,trailing:i5};const i=new Map;o.forEach(h=>{i.set(h.turn.userMessage.info.id,h)});const a=t[t.length-1],l=!s&&a&&n.has(a.info.id)?a.info.id:void 0,d=[],f=[];let u=!1;return t.forEach((h,m)=>{if(s&&h.info.id===s){u=!0;return}const g=i.get(h.info.id);if(g){d.push(g);return}!n.has(h.info.id)||h.info.id===l||(u?f:d).push({kind:"ungrouped",key:`msg:${h.info.id}`,message:h,previousMessage:m>0?t[m-1]:void 0,nextMessage:m<t.length-1?t[m+1]:void 0})}),{entries:d,trailing:f.length>0?f:i5}},E9=e=>e.parts.some(t=>t?.type==="compaction"),CZ=e=>{if(!E9(e))return e;let t=!1;const n=e.parts.map(o=>o?.type!=="compaction"?o:(t=!0,{type:"text",text:"/compact"})),s=e.info.clientRole!=="user";return!t&&!s?e:{...e,info:s?{...e.info,clientRole:"user"}:e.info,parts:t?n:e.parts}},kZ=e=>{const t=Au(e.parts);return t.length===e.parts.length?e:{...e,parts:t}},a5=new WeakMap,_9=e=>{const t=a5.get(e);if(t)return t;const n=kZ(e),r=CZ(n),s=xK(r.parts),o=s===r.parts?r:{...r,parts:s};return a5.set(e,o),o},c5=(e,t,n)=>e.info.id!==t||e.parts===n?e:_9({...e,parts:n}),MZ=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(!r||!s||r.id!==s.id||r.type!==s.type||r.type!=="text"&&r!==s)return!1}return!0},l5=(e,t)=>{if(e.messages.length===0)return e.messages;const n=new Map(t.map(o=>[o.info.id,o]));let r=!1;const s=e.messages.map(o=>{const i=n.get(o.messageId);return!i||i===o.message?o:(r=!0,{...o,message:i})});return r?s:e.messages},IZ=(e,t)=>{const n=t.activeStreamingMessageId;if(!n)return e;if(e.kind==="ungrouped"){const g=c5(e.message,n,t.liveParts);return g===e.message?e:{...e,message:g}}let r=!1;const s=e.turn.assistantMessages.map(g=>{const x=c5(g,n,t.liveParts);return x!==g&&(r=!0),x});if(!r)return e;const o=e.turn.assistantMessages.find(g=>g.info.id===n),i=s.find(g=>g.info.id===n);if(!!(o&&i&&MZ(o.parts,i.parts)))return{...e,turn:{...e.turn,assistantMessages:s,messages:l5(e.turn,s)}};const l=new Map(s.map(g=>[g.info.id,g])),f=[...e.turn.messages.length>0?e.turn.messages.slice().sort((g,x)=>g.order-x.order).map(g=>l.get(g.messageId)??g.message):[e.turn.userMessage,...s],...e.turn.notices],h=I9(f,{showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:t.mergeHiddenUserTurns}).turns[0],m=h?h.notices.length>0||e.turn.notices.length>0?{...h,notices:e.turn.notices}:h:{...e.turn,assistantMessages:s,assistantMessageIds:s.map(g=>g.info.id),messages:l5(e.turn,s)};return{...e,turn:m}},d5=e=>!!(e&&e.clientHeight>0),EZ=5,_Z=[],jZ=new Set,TZ=16,AZ=(e,t)=>e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r]),NZ=320,LZ=8,RZ=16,PZ=()=>un()?RZ:LZ,DZ=30,OZ=180,HZ=5,FZ=120,BZ=1200,VZ=80,$Z=160,u5=1500,zZ=1.5,UZ=90,qZ=(e,t)=>{if(e.length===0||t.length<=e.length||e[e.length-1]?.key!==t[t.length-1]?.key)return!1;const n=e[0]?.key;return t.findIndex(s=>s.key===n)>0},ms=new Map,WZ=32,mo=new Map,f5=e=>mo.get(e)??0,KZ=(e,t)=>{if(mo.size>=WZ&&!mo.has(e)){const n=mo.keys().next().value;typeof n=="string"&&mo.delete(n)}mo.set(e,t)},GZ=(e,t)=>{const n=ms.get(e);if(n){if(AZ(n.keys,t))return n.items;ms.delete(e)}},ZZ=(e,t,n)=>{if(!(!n||t.length===0))for(ms.delete(e),ms.set(e,{keys:t.slice(),items:n.takeSnapshot()});ms.size>TZ;){const r=ms.keys().next().value;if(typeof r!="string")break;ms.delete(r)}},hl=e=>{const t=p.useRef(e);return p.useEffect(()=>{t.current=e},[e]),p.useCallback((...n)=>t.current(...n),[])},Nu=p.memo(({entry:e,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,sessionIsWorking:s,sessionAwaitingRecovery:o=!1,awaitingPromptEcho:i=!1,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f,onLoadOlderHistory:u,onLoadAllHistory:h})=>(_s("ui.message_list_entry.render"),e.kind==="ungrouped"?c.jsx(S9,{message:e.message,previousMessage:e.previousMessage,nextMessage:e.nextMessage,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f}):e.kind==="history-gate"?c.jsx(Vz,{foldedCount:e.turns.length,onLoadOlder:()=>u?.(e.turns.length),onLoadAll:()=>h?.(e.turns.length)}):c.jsx(w9,{turn:e.turn,isLastTurn:e.isLastTurn,nextEntryFirstMessage:e.nextEntryFirstMessage,sessionIsWorking:s,sessionAwaitingRecovery:o,awaitingPromptEcho:i,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r})));Nu.displayName="MessageListEntry";const j9=p.memo(({entries:e,engine:t,contentRef:n,scrollRef:r,registerTanstackVirtualizer:s,virtualizerKey:o,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,onLoadOlderHistory:u,onLoadAllHistory:h})=>{const m=t==="tanstack",g=p.useRef(!1),x=p.useRef(0),b=p.useRef(null),S=m&&un();p.useEffect(()=>{if(!S)return;const D=r?.current;if(!D)return;const W=()=>{g.current=!0},z=()=>{g.current=!1},X=()=>{x.current=performance.now()};return D.addEventListener("touchstart",W,{passive:!0}),D.addEventListener("touchend",z,{passive:!0}),D.addEventListener("touchcancel",z,{passive:!0}),D.addEventListener("scroll",X,{passive:!0}),()=>{D.removeEventListener("touchstart",W),D.removeEventListener("touchend",z),D.removeEventListener("touchcancel",z),D.removeEventListener("scroll",X)}},[S,r]);const y=p.useCallback(()=>g.current||performance.now()-x.current<$Z,[]),v=p.useCallback(()=>{const D=r?.current;return D?D.scrollTop<D.clientHeight*zZ:!0},[r]),[C,w]=p.useState(e);let I=C;e!==C?S&&qZ(C,e)&&y()&&!v()&&(b.current===null||performance.now()-b.current<u5)?b.current===null&&(b.current=performance.now()):(b.current=null,w(e),I=e):b.current!==null&&(b.current=null);const[,E]=p.useReducer(D=>D+1,0);p.useEffect(()=>{if(!S)return;const D=window.setInterval(()=>{if(b.current===null)return;const W=performance.now()-b.current>=u5;(!y()||v()||W)&&E()},UZ);return()=>window.clearInterval(D)},[S,y,v]);const T=p.useRef(I);T.current=I;const[A]=p.useState(()=>m?GZ(o,e.map(D=>D.key)):void 0),j=p.useRef(null),k=p.useRef(NZ),[_,M]=p.useState(null);p.useLayoutEffect(()=>{if(!m){M(F=>F===null?F:null);return}let D,W=0;const z=()=>{const F=r?.current??null;return d5(F)?(M(U=>U===F?U:F),!0):!1};if(z())return;const X=r?.current;return X?(D=new ResizeObserver(()=>{z()&&D?.disconnect()}),D.observe(X)):typeof window<"u"&&(W=window.requestAnimationFrame(()=>{if(z())return;const F=r?.current;F&&(D=new ResizeObserver(()=>{z()&&D?.disconnect()}),D.observe(F))})),()=>{W&&window.cancelAnimationFrame(W),D?.disconnect()}},[m,r,o]);const L=m&&d5(_),O=J5({count:I.length,enabled:L,getScrollElement:()=>_,estimateSize:D=>T.current[D]?.kind==="history-gate"?Pz:k.current,overscan:PZ(),scrollToFn:(D,W,z)=>{const X=j.current;X&&(X.style.height=`${z.getTotalSize()}px`),H8(D,W,z)},getItemKey:D=>T.current[D]?.key??`index:${D}`,anchorTo:"end",initialOffset:()=>Number.MAX_SAFE_INTEGER,initialMeasurementsCache:A});O.shouldAdjustScrollPositionOnItemSizeChange=(D,W,z)=>{if(z.isAtEnd(VZ))return!1;const X=z.range?.startIndex;return X!==void 0&&D.index<X},p.useEffect(()=>{if(!m)return;const D=O.itemSizeCache;if(D.size>=HZ){let W=0;for(const z of D.values())W+=z;k.current=Math.min(BZ,Math.max(FZ,Math.round(W/D.size)))}}),p.useEffect(()=>{if(L)return s?.(O),()=>{ZZ(o,T.current.map(D=>D.key),O),s?.(null)}},[L,s,O,o]);const N=p.useCallback(D=>c.jsx(Nu,{entry:D,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,sessionIsWorking:!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:null,activeStreamingPhase:null,onLoadOlderHistory:u,onLoadAllHistory:h},D.key),[a,h,u,i,f,l,d]);if(t==="none"||t==="tanstack"&&!L)return c.jsx("div",{ref:n,className:"relative w-full",children:I.map(D=>c.jsx("div",{"data-turn-entry":D.key,children:N(D)},D.key))});if(t==="tanstack"){const D=O.getVirtualItems(),W=D[0]?.start??0;return c.jsx("div",{ref:j,className:"relative w-full",style:{height:O.getTotalSize()},children:c.jsx("div",{style:{paddingTop:`${W}px`},children:D.map(z=>{const X=I[z.index];return X?c.jsx("div",{"data-index":z.index,ref:O.measureElement,"data-turn-entry":X.key,children:N(X)},X.key):null})})})}return null});j9.displayName="StaticHistoryList";const T9=({entry:e,sessionId:t,directory:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a=!1,awaitingPromptEcho:l=!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})=>{const m=t_(t,u??"",n),g=p.useMemo(()=>IZ(e,{activeStreamingMessageId:u,liveParts:m,showTextJustificationActivity:!0,mergeHiddenUserTurns:!0}),[u,e,m]);return c.jsx(Nu,{entry:g,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a,awaitingPromptEcho:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})};T9.displayName="StreamingTailContent";const A9=p.forwardRef(({sessionKey:e,messages:t,sessionIsWorking:n=!1,sessionAwaitingRecovery:r=!1,awaitingPromptEcho:s=!1,activeStreamingMessageId:o=null,activeStreamingPhase:i=null,retryOverlay:a=null,compactionOverlay:l=null,onMessageContentChange:d,getAnimationHandlers:f,scrollToBottom:u,scrollRef:h,directory:m},g)=>{IC("react.message_list_render"),_s("ui.message_list.render");const{hasMoreBefore:x,beforeCursor:b,loadOlder:S}=h_(e),y=_w(e),v=r_(e),[C,w]=p.useState(()=>f5(e)),I=p.useRef(null),E=p.useRef(null),T=p.useCallback(()=>{const ie=h?.current;if(!ie)return null;const ke=ie.getBoundingClientRect(),ve=Array.from(ie.querySelectorAll("[data-message-id]")).find(xe=>xe.getBoundingClientRect().bottom>ke.top+1);return{top:ie.scrollTop,height:ie.scrollHeight,anchor:ve?.dataset.messageId?{messageId:ve.dataset.messageId,offsetTop:ve.getBoundingClientRect().top-ke.top}:null}},[h]),A=p.useCallback(ie=>{w(ke=>{const ve=typeof ie=="function"?ie(ke):ie;return KZ(e,ve),ve})},[e]),j=p.useCallback(ie=>{I.current=T(),A(ke=>Fz(ke,ie))},[T,A]),k=p.useCallback(ie=>{I.current=T(),A(ke=>ke+ie)},[T,A]),_=p.useCallback((ie,ke,ve)=>{const xe=ke.findIndex(je=>je.turnId===ie);xe<0||(E.current=ie,A(je=>Math.max(je,Hz(xe,ve))))},[A]);p.useLayoutEffect(()=>{w(f5(e)),E.current=null},[e]);const M=p.useRef({sessionKey:void 0,previousOrder:[],animatedIds:new Set}),L=hl(f),O=hl(()=>{u?.()}),N=p.useMemo(()=>vl("ui.message_list.base_display_ms",()=>{const ie=new Set,ke=new Map,ve=[];for(const le of t){const J=le.info?.id;typeof J=="string"&&ke.set(J,le)}for(let le=0;le<t.length;le+=1){const J=t[le],ne=J.info?.id;if(typeof ne=="string"){if(ie.has(ne))continue;ie.add(ne)}ve.push(_9(typeof ne=="string"?ke.get(ne)??J:J))}const xe=[],je=new Set;for(let le=0;le<ve.length;le+=1){const J=ve[le],ne=Gz(J,je);(E9(J)||J.parts.some(De=>De.type==="text"&&qz(De).trim()==="/compact"))&&je.add(J.info.id);const fe=xe.length>0?xe[xe.length-1]:void 0;if(Zz(fe)){const De=Xz(ne);if(De.hide){xe[xe.length-1]=Jz(fe,De.taskSessionId);continue}}if(p7(fe)){const De=m7(ne,Wz(fe));if(De.hide){xe[xe.length-1]=Qz(fe,De.details);continue}}xe.push(ne)}return xe}),[t]),D=p.useRef(null),W=p.useCallback(()=>h?.current?h.current:typeof document>"u"?null:document.querySelector('[data-scrollbar="chat"]'),[h]),z=p.useCallback(()=>{I.current=T()},[T]),X=p.useCallback(()=>{I.current=null},[]);yZ({hasMoreBefore:x,beforeCursor:b,resolveScrollContainer:W,loadOlder:S,onBeforeLoad:z,onLoadError:X});const F=p.useMemo(()=>vl("ui.message_list.retry_overlay_ms",()=>{const ie=xZ(N,{sessionId:a?.sessionId??null,message:a?.message??"Quota limit reached. Retrying automatically.",confirmedAt:a?.confirmedAt,fallbackTimestamp:a?.fallbackTimestamp??0}),ke=vZ(ie,l?.sessionId??null,l?.compaction??null),ve=FG(ke,y,e);return wZ(ve,v,e)}),[N,l,a,v,y,e]),{projection:U,staticTurns:P,streamingTurn:q}=mZ(F,{sessionKey:e,showTextJustificationActivity:!0}),B=U.ungroupedMessageIds.size>0,ee=B?F:_Z,G=B?U.ungroupedMessageIds:jZ,K=q?.userMessage.info.id,{entries:se,trailing:de}=p.useMemo(()=>vl("ui.message_list.render_entries_ms",()=>SZ({staticTurns:P,messages:ee,ungroupedMessageIds:G,lastTurnId:U.lastTurnId,tailUserMessageId:K})),[U.lastTurnId,ee,G,P,K]),oe=p.useMemo(()=>{if(q)return{kind:"turn",key:`turn:${q.turnId}`,turn:q,isLastTurn:q.turnId===U.lastTurnId};if(U.ungroupedMessageIds.size===0)return;const ie=F[F.length-1];if(!(!ie||!U.ungroupedMessageIds.has(ie.info.id)))return{kind:"ungrouped",key:`msg:${ie.info.id}`,message:ie,previousMessage:F.length>1?F[F.length-2]:void 0,nextMessage:void 0}},[F,U.lastTurnId,U.ungroupedMessageIds,q]);oe&&_s("ui.message_list.render.streaming");const ue=oe?oe.kind==="turn"?oe.turn.userMessage:oe.message:void 0,ye=p.useMemo(()=>{const ie=se.map((le,J)=>{if(le.kind!=="turn")return le;const ne=J<se.length-1?(()=>{const fe=se[J+1];return fe&&fe.kind==="turn"?fe.turn.userMessage:fe?.kind==="ungrouped"?fe.message:void 0})():ue;return ne?{...le,nextEntryFirstMessage:ne}:le});let ke=0;for(const le of ie)le.kind==="turn"&&(ke+=1);let ve=-1;const xe=[],je=[];for(const le of ie){if(le.kind!=="turn"){je.push(le);continue}if(ve+=1,Oz(ve,ke,C)){xe.push(le.turn);continue}je.push(le)}return xe.length===0?je:[{kind:"history-gate",key:"history-gate",turns:xe},...je]},[C,se,ue]);p.useLayoutEffect(()=>{const ie=I.current;if(ie){I.current=null;const je=h?.current;if(je){const le=ie.anchor?.messageId?je.querySelector(`[data-message-id="${ie.anchor.messageId}"]`):null;if(le&&ie.anchor){const J=je.getBoundingClientRect(),ne=le.getBoundingClientRect().top-J.top-ie.anchor.offsetTop;ne!==0&&(je.scrollTop+=ne)}else{const J=je.scrollHeight-ie.height;J>0?je.scrollTop=ie.top+J:je.scrollTop=ie.top}}}const ke=E.current;if(!ke)return;E.current=null,W()?.querySelector(`[data-turn-id="${ke}"]`)?.scrollIntoView({block:"start"})},[ye,W,h]);const we=un()||ye.length>=EZ,Me=we?"tanstack":"none",He=p.useRef(null),Ae=p.useCallback(ie=>{He.current=ie},[]),Ge=p.useMemo(()=>{const ie=oe?[...ye,oe]:ye;return de.length>0?[...ie,...de]:ie},[ye,oe,de]),et=hl(ie=>{d(ie)}),Xe=hl(ie=>{d(ie)}),te=p.useMemo(()=>t.filter(ie=>Ps(ie)==="user").map(ie=>ie.info.id),[t]);{const ie=M.current;ie.sessionKey!==e&&(ie.sessionKey=e,ie.previousOrder=te,ie.animatedIds=new Set);const ke=ie.previousOrder;if(te.length>ke.length&&ke.every((xe,je)=>te[je]===xe)&&xE(e))for(let xe=ke.length;xe<te.length;xe+=1){const je=te[xe];if(je&&!ie.animatedIds.has(je)){if(!bE(e))break;ie.animatedIds.add(je)}}ie.previousOrder=te}const Q=p.useCallback(ie=>Ps(ie)!=="user"?!1:M.current.animatedIds.has(ie.info.id),[]),me=p.useCallback(ie=>{M.current.animatedIds.delete(ie)},[]),Se=p.useMemo(()=>{const ie=new Map;return Ge.forEach((ke,ve)=>{if(ke.kind==="ungrouped"){ie.set(ke.message.info.id,ve);return}if(ke.kind==="history-gate"){ke.turns.forEach(xe=>{ie.set(xe.userMessage.info.id,ve),xe.assistantMessages.forEach(je=>{ie.set(je.info.id,ve)})});return}ie.set(ke.turn.userMessage.info.id,ve),ke.turn.assistantMessages.forEach(xe=>{ie.set(xe.info.id,ve)})}),ie},[Ge]),_e=p.useMemo(()=>{const ie=new Map;return Ge.forEach((ke,ve)=>{ke.kind==="turn"&&ie.set(ke.turn.turnId,ve),ke.kind==="history-gate"&&ke.turns.forEach(xe=>{ie.set(xe.turnId,ve)})}),ie},[Ge]),Fe=p.useCallback(ie=>{const ke=W();return ke?ke.querySelector(`[data-message-id="${ie}"]`):null},[W]),ht=p.useCallback(ie=>{if(ie<0||ie>=ye.length||!we)return!1;const ke=He.current;return ke?(ke.scrollToIndex(ie,{align:"start",behavior:"auto"}),!0):!1},[ye.length,we]),ge=p.useCallback((ie,ke="auto")=>{const ve=W();if(!ve)return!1;const xe=Fe(ie);if(!xe)return!1;const je=ve.getBoundingClientRect(),ne=xe.getBoundingClientRect().top-je.top+ve.scrollTop-50;return ve.scrollTo({top:ne,behavior:ke}),!0},[Fe,W]),Ze=p.useCallback((ie,ke,ve)=>{if(typeof window>"u")return!1;let xe=0;const je=()=>{sK(ie,ke),!ge(ke,ve)&&(xe+=1,xe<60&&window.requestAnimationFrame(je))};return window.requestAnimationFrame(je),!0},[ge]);return p.useEffect(()=>{if(!g)return;const ie={scrollToTurnId:(ve,xe)=>{const je=ye.find(Ue=>Ue.kind==="history-gate");if(je?.kind==="history-gate"){const Ue=ye.reduce((st,Ee)=>Ee.kind==="turn"?st+1:st,0);_(ve,je.turns,je.turns.length+Ue)}const le=xe?.behavior??"auto",J=_e.get(ve);if(J===void 0)return!1;const ne=W();if(!ne)return!1;const fe=ne.querySelector(`[data-turn-id="${ve}"]`);return fe?(fe.scrollIntoView({behavior:le,block:"start"}),!0):oe!==void 0&&J>=ye.length?!1:ht(J)},scrollToMessageId:(ve,xe)=>{const je=xe?.behavior??"auto",le=Se.get(ve);if(le===void 0)return!1;const J=Ge[le];if(J?.kind==="history-gate"){const De=J.turns.find(Ue=>Ue.userMessage.info.id===ve||Ue.assistantMessages.some(st=>st.info.id===ve));if(De){const Ue=ye.reduce((st,Ee)=>Ee.kind==="turn"?st+1:st,0);_(De.turnId,J.turns,J.turns.length+Ue)}}if(ge(ve,je))return!0;oe!==void 0&&le>=ye.length||ht(le);const fe=U.indexes.messageToTurnId.get(ve);return fe?Ze(fe,ve,je):!1},holdViewportAnchor:ve=>{const xe=W();if(!xe||typeof window>"u")return;let je=0,le=0,J=!1;const ne=()=>{J=!0,xe.removeEventListener("touchstart",ne),xe.removeEventListener("wheel",ne)};xe.addEventListener("touchstart",ne,{passive:!0}),xe.addEventListener("wheel",ne,{passive:!0});const fe=()=>{if(J)return;const De=Fe(ve.messageId);if(De){const Ue=De.getBoundingClientRect().top-xe.getBoundingClientRect().top-ve.offsetTop;Math.abs(Ue)>.5?(xe.scrollTop+=Ue,le=0):le+=1}if(je+=1,le>=DZ||je>=OZ){xe.removeEventListener("touchstart",ne),xe.removeEventListener("wheel",ne);return}window.requestAnimationFrame(fe)};window.requestAnimationFrame(fe)},isHistoryVirtualized:()=>we,captureViewportAnchor:()=>{const ve=W();if(!ve)return null;const xe=ve.getBoundingClientRect(),le=Array.from(ve.querySelectorAll("[data-message-id]")).find(ne=>ne.getBoundingClientRect().bottom>xe.top+1);if(!le)return null;const J=le.dataset.messageId;return J?{messageId:J,offsetTop:le.getBoundingClientRect().top-xe.top}:null},restoreViewportAnchor:ve=>{const xe=W();if(!xe||!Se.has(ve.messageId))return!1;const je=()=>{const le=Fe(ve.messageId);if(!le)return!1;const J=xe.getBoundingClientRect(),fe=le.getBoundingClientRect().top-J.top-ve.offsetTop;return fe!==0&&(xe.scrollTop+=fe),!0};if(!je()){const le=Se.get(ve.messageId);if(typeof le=="number"&&le<ye.length)return ht(le)}return je()},scrollToBottom:()=>{if(we&&ye.length>0&&He.current){He.current.scrollToEnd();return}const ve=W();ve&&(ve.scrollTop=ve.scrollHeight+4096)}};if(typeof g=="function")return g(ie),()=>{g(null)};const ke=g;return ke.current=ie,()=>{ke.current=null}},[Ge,Fe,ye,Se,U.indexes.messageToTurnId,W,_,Ze,ht,ge,we,oe,_e,g]),c.jsx("div",{children:c.jsx(Dx,{disabled:!1,children:c.jsxs("div",{className:"relative w-full",children:[c.jsx(Dx,{disabled:we,children:c.jsx(j9,{entries:ye,engine:Me,contentRef:D,scrollRef:h,registerTanstackVirtualizer:Ae,virtualizerKey:e,onMessageContentChange:et,getAnimationHandlers:L,scrollToBottom:O,shouldAnimateUserMessage:Q,onUserAnimationConsumed:me,onLoadOlderHistory:j,onLoadAllHistory:k},e)}),oe?c.jsx(T9,{entry:oe,sessionId:e??null,directory:m,onMessageContentChange:Xe,getAnimationHandlers:L,scrollToBottom:O,sessionIsWorking:n,sessionAwaitingRecovery:r,awaitingPromptEcho:s,shouldAnimateUserMessage:Q,onUserAnimationConsumed:me,activeStreamingMessageId:o,activeStreamingPhase:i}):null,de.map(ie=>c.jsx(Nu,{entry:ie,onMessageContentChange:Xe,getAnimationHandlers:L,scrollToBottom:O,sessionIsWorking:n,shouldAnimateUserMessage:Q,onUserAnimationConsumed:me},ie.key))]})})})});A9.displayName="MessageList";const YZ=p.memo(A9),XZ=({visible:e,onClick:t})=>c.jsx("div",{className:R("absolute bottom-full left-1/2 -translate-x-1/2 mb-2 transition-all duration-150",e?"opacity-100 translate-y-0 scale-100 pointer-events-auto":"opacity-0 translate-y-2 scale-95 pointer-events-none"),children:c.jsx(be,{variant:"outline",size:"sm",onClick:t,className:"size-8 rounded-full [corner-shape:round] p-0 shadow-none bg-background/95 hover:bg-interactive-hover","aria-label":"Scroll to bottom",children:c.jsx(V,{name:"arrow-down",className:"h-4 w-4"})})}),JZ=p.memo(XZ),QZ=.1,eY=40,tY=2,h5=1500,p5=2,N9=350,nY=300,rY=600,sY=8e3,Xi=()=>typeof performance<"u"?performance.now():Date.now(),oY=(e,t)=>{if(e)return eY;const n=t?.clientHeight??0;return n<=0?96:Math.max(48,n*QZ)},L9=e=>e.scrollHeight-e.scrollTop-e.clientHeight,Ni=e=>e.scrollHeight-e.clientHeight>1,m5=(e,t)=>L9(e)<=oY(t,e),iY=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return!1;switch(e.key){case"ArrowUp":case"PageUp":case"Home":return!0;default:return!1}},aY=(e,t)=>{if(!(t instanceof Element))return null;const n=t.closest("[data-scrollable]");return!n||n===e||!(n instanceof HTMLElement)?null:n},g5=(e,t)=>{const n=aY(e,t);return n?n.scrollTop>0:!1},cY=100,lY=48,dY=.1,uY=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=Math.max(lY,e.clientHeight*dY),fY=(e,t)=>{if(e.length===0)return;let n=0,r=e.length-1,s=0;for(;n<=r;){const o=n+r>>1,i=e[o]?.top;if(i===void 0)break;if(i<=t){s=o,n=o+1;continue}r=o-1}return e[s]?.id},hY=e=>{const t=e.raf??requestAnimationFrame,n=e.caf??cancelAnimationFrame,r=e.ResizeObserver??globalThis.ResizeObserver,s=e.MutationObserver??globalThis.MutationObserver;let o,i,a,l,d,f,u=!0;const h=new Map;let m=[];const g=()=>{l===void 0&&(l=t(()=>{l=void 0,b()}))},x=()=>{const T=o;if(!T){m=[],u=!1;return}const A=T.getBoundingClientRect().top;m=[...h].map(([j,k])=>({id:j,top:k.getBoundingClientRect().top-A+T.scrollTop})),m.sort((j,k)=>j.top-k.top),u=!1},b=()=>{const T=o;if(!T)return;u&&x();const A=uY(T)?m[m.length-1]?.id:fY(m,T.scrollTop+cY);!A||A===f||(f=A,e.onActive(A))},S=()=>{const T=o;if(T){if(clearTimeout(d),d=void 0,i?.disconnect(),i=void 0,r){i=new r(()=>{clearTimeout(d),d=setTimeout(()=>{u=!0,g()},100)}),i.observe(T);for(const A of h.values())i.observe(A)}if(a?.disconnect(),a=void 0,s){a=new s(()=>{u=!0,g()});const A={subtree:!0,childList:!0};r||(A.characterData=!0,A.characterDataOldValue=!1),a.observe(T,A)}u=!0,g()}},y=T=>{o!==T&&(o=T,f=void 0,S())},v=(T,A)=>{const j=h.get(A);j&&j!==T&&i?.unobserve(j),h.set(A,T),i&&i.observe(T),u=!0,g()},C=T=>{const A=h.get(T);A&&(i?.unobserve(A),h.delete(T),u=!0,g())},w=()=>{u=!0,g()},I=()=>{for(const T of h.values())i?.unobserve(T);h.clear(),m=[],f=void 0,u=!0};return{setContainer:y,register:v,unregister:C,onScroll:g,markDirty:w,clear:I,destroy:()=>{l!==void 0&&n(l),l=void 0,clearTimeout(d),d=void 0,I(),i?.disconnect(),a?.disconnect(),i=void 0,a=void 0,o=void 0},getActiveId:()=>f}};function pY(e,t){p.useEffect(()=>{if(!t)return;const n=e;if(!n)return;let r=null;const s=hY({onActive:u=>{u!==r&&(r=u,t(u))}});s.setContainer(n);const o=new Map,i=u=>{const h=u.dataset.turnId;return h?(o.set(h,u),s.register(u,h),!0):!1},a=u=>{const h=u.dataset.turnId;return!h||o.get(h)!==u?!1:(o.delete(h),s.unregister(h),!0)},l=u=>{if(!(u instanceof HTMLElement))return[];const h=[];return u.matches("[data-turn-id]")&&h.push(u),u.querySelectorAll("[data-turn-id]").forEach(m=>h.push(m)),h};n.querySelectorAll("[data-turn-id]").forEach(i),s.markDirty();const d=new MutationObserver(u=>{let h=!1;u.forEach(m=>{m.removedNodes.forEach(g=>{l(g).forEach(x=>{a(x)&&(h=!0)})}),m.addedNodes.forEach(g=>{l(g).forEach(x=>{i(x)&&(h=!0)})})}),h&&s.markDirty()});d.observe(n,{subtree:!0,childList:!0});const f=()=>s.onScroll();return n.addEventListener("scroll",f,{passive:!0}),()=>{n.removeEventListener("scroll",f),d.disconnect(),s.destroy()}},[e,t])}function mY({containerEl:e,handleScrollEvent:t,releaseFromUserIntent:n,scrollRef:r,stateRef:s,canScroll:o,scrollToBottomNow:i,updateOverflowAndButton:a,keyboardAnimRef:l,animationGuardUntilRef:d,lastScrollTopRef:f}){p.useEffect(()=>{const u=e;if(!u)return;f.current=u.scrollTop;const h=v=>{v.deltaY>=0||g5(u,v.target)||n()};let m=null;const g=v=>{const C=v.touches.item(0);m=C?C.clientY:null},x=v=>{const C=v.touches.item(0);if(!C){m=null;return}const w=m;m=C.clientY,!(w===null||C.clientY-w<=tY)&&(g5(u,v.target)||n())},b=()=>{m=null},S=v=>{iY(v)&&n()},y=v=>{const C=v.target;C instanceof Element&&C.closest("[data-overlay-scrollbar-thumb]")&&n()};return u.addEventListener("scroll",t,{passive:!0}),u.addEventListener("wheel",h,{passive:!0}),u.addEventListener("touchstart",g,{passive:!0}),u.addEventListener("touchmove",x,{passive:!0}),u.addEventListener("touchend",b,{passive:!0}),u.addEventListener("touchcancel",b,{passive:!0}),u.addEventListener("keydown",S),typeof window<"u"&&window.addEventListener("pointerdown",y,!0),()=>{u.removeEventListener("scroll",t),u.removeEventListener("wheel",h),u.removeEventListener("touchstart",g),u.removeEventListener("touchmove",x),u.removeEventListener("touchend",b),u.removeEventListener("touchcancel",b),u.removeEventListener("keydown",S),typeof window<"u"&&window.removeEventListener("pointerdown",y,!0)}},[e,t,f,n]),p.useEffect(()=>{if(typeof window>"u")return;const u=m=>{const g=m.detail;g&&(l.current=!0,d.current=Xi()+g.durationMs+N9)},h=()=>{l.current=!1;const m=r.current;if(!m){a();return}s.current==="following"&&o(m)&&i("auto"),a()};return window.addEventListener("oc:keyboard-anim",u),window.addEventListener("oc:keyboard-settled",h),()=>{window.removeEventListener("oc:keyboard-anim",u),window.removeEventListener("oc:keyboard-settled",h),l.current=!1}},[d,o,l,r,i,s,a])}const gY=({currentSessionId:e,currentSessionKey:t,sessionMessageCount:n,latestTailEntryId:r=null,sessionIsWorking:s,isMobile:o,onActiveTurnChange:i})=>{const a=p.useRef(null),[l,d]=p.useState(null),f=p.useRef(null),[u,h]=p.useState("following"),[m,g]=p.useState(!1),[x,b]=p.useState(!1),[S,y]=p.useState(!1),v=p.useRef("following"),C=p.useRef(o);C.current=o;const w=p.useRef(s);w.current=s;const I=p.useRef(!1),E=p.useRef(null),T=p.useRef(t);T.current=t;const A=p.useRef(null),j=p.useRef(null),k=p.useRef(null),_=p.useRef(0),M=p.useRef(!1),L=p.useRef(0),O=p.useRef(!1),N=p.useRef(null),D=p.useRef(null),W=p.useRef(0),z=p.useRef(null);p.useLayoutEffect(()=>{a.current!==f.current&&(f.current=a.current,d(a.current))});const X=p.useCallback(()=>w.current||I.current,[]),F=p.useCallback(Q=>{v.current!==Q&&(v.current=Q,h(Q))},[]),U=p.useCallback(Q=>{j.current={top:Math.max(0,Q.scrollHeight-Q.clientHeight),time:Xi()},k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{j.current=null,k.current=null},h5)},[]),P=p.useCallback(Q=>{const me=j.current;return me?Xi()-me.time>h5?(j.current=null,!1):Math.abs(Q.scrollTop-me.top)<p5:!1},[]),q=p.useCallback(()=>Xi()<_.current,[]),B=p.useCallback(()=>{O.current=!1,N.current&&(clearTimeout(N.current),N.current=null),D.current&&(clearTimeout(D.current),D.current=null)},[]),ee=p.useCallback(()=>{N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{N.current=null,B()},rY)},[B]),G=p.useCallback(()=>{const Q=a.current;Q&&(O.current=!0,W.current=Q.scrollHeight,ee(),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,B()},sY))},[ee,B]),K=p.useCallback(()=>{const Q=a.current;if(!Q){g(!1),b(!1);return}const me=Ni(Q);if(g(me),!me){b(!1);return}const Se=v.current==="released"&&!m5(Q,C.current);b(Se)},[]),se=p.useCallback(Q=>{const me=a.current;if(!me)return;U(me);const Se=me.scrollHeight+4096;if(Q==="smooth"){me.scrollTo({top:Se,behavior:Q});return}me.scrollTop=Se},[U]),de=p.useCallback((Q,me="auto")=>{const Se=a.current;!Q&&!X()||(Q&&v.current!=="following"&&F("following"),Se&&(!Q&&v.current!=="following"||se(Q?me:"auto")))},[X,se,F]),oe=p.useCallback(()=>{const Q=a.current;if(Q){if(!Ni(Q)){F("following");return}v.current!=="released"&&(F("released"),K())}},[F,K]),ue=p.useCallback((Q="instant")=>{de(!0,Q==="smooth"?"smooth":"auto")},[de]),ye=p.useCallback(()=>{de(!0)},[de]),we=p.useCallback(()=>{F("released"),K()},[F,K]),Me=p.useCallback(()=>{B(),oe()},[B,oe]),He=p.useCallback(async()=>{const Q=T.current;return Q?a.current?(z.current=null,F("following"),de(!0),G(),K(),!1):(z.current=Q,F("following"),!1):!1},[G,de,F,K]);p.useEffect(()=>{!e||!t||t===A.current||(A.current=t,Cs.getInstance().recordSessionStart(e),j.current=null,z.current&&z.current!==t&&(z.current=null))},[e,t]),p.useEffect(()=>{if(I.current=!1,E.current&&(clearTimeout(E.current),E.current=null),s){v.current==="following"&&de(!0);return}I.current=!0,E.current=setTimeout(()=>{I.current=!1,E.current=null},nY)},[s,de]),p.useEffect(()=>{y(u==="following"&&s)},[u,s]),p.useLayoutEffect(()=>{l&&z.current&&z.current===t&&He()},[l,t,He]);const Ae=p.useCallback(()=>{const Q=a.current;if(!Q)return;const me=L.current;L.current=Q.scrollTop;const Se=Q.scrollTop>me+.5;if(K(),!Ni(Q)){F("following");return}if(m5(Q,C.current)){const _e=L9(Q)<=p5;(Se||v.current==="following"||_e)&&F("following");return}if(v.current==="following"&&(P(Q)||q())){de(!1);return}Me()},[q,P,Me,de,F,K]);mY({containerEl:l,handleScrollEvent:Ae,releaseFromUserIntent:Me,scrollRef:a,stateRef:v,canScroll:Ni,scrollToBottomNow:se,updateOverflowAndButton:K,keyboardAnimRef:M,animationGuardUntilRef:_,lastScrollTopRef:L}),p.useEffect(()=>{const Q=l;if(!Q||typeof ResizeObserver>"u")return;const me=new ResizeObserver(()=>{if(M.current){K();return}const _e=a.current;if(_e&&!Ni(_e)){F("following"),K();return}if(K(),O.current&&_e){const Fe=_e.scrollHeight>W.current+1;W.current=_e.scrollHeight,de(!0),Fe&&ee();return}X()&&v.current==="following"&&de(!1)});me.observe(Q);const Se=Q.firstElementChild;return Se instanceof Element&&me.observe(Se),()=>me.disconnect()},[ee,l,X,de,F,K]),p.useEffect(()=>{K()},[n,K]);const Ge=p.useRef(null);p.useEffect(()=>{const Q=Ge.current;Ge.current={key:t,count:n,tailId:r},!(!Q||!t||Q.key!==t||!(n>Q.count||r!==null&&r!==Q.tailId))&&(w.current||v.current!=="following"||(de(!0),G()))},[G,t,r,de,n]);const et=p.useCallback(Q=>{if(Q==="animation"&&(_.current=Xi()+N9),K(),O.current){de(!0),ee();return}v.current==="following"&&de(!1)},[ee,de,K]),Xe=p.useRef(new Map),te=p.useCallback(Q=>{const me=Xe.current.get(Q);if(me)return me;const Se=()=>{v.current==="following"&&de(!1)},_e={onChunk:Se,onComplete:()=>{K()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:Se,onReservationCancelled:()=>{}};return Xe.current.set(Q,_e),_e},[de,K]);return p.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),E.current&&(clearTimeout(E.current),E.current=null),B()},[B]),pY(l,i),{scrollRef:a,state:u,isPinned:u==="following",isOverflowing:m,isFollowingProgrammatically:S,showScrollButton:x,notifyContentChange:et,getAnimationHandlers:te,goToBottom:ue,scrollToBottomOnSend:ye,releaseAutoFollow:we,restoreSnapshot:He}},hg=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},pg=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},y5=e=>{if(!e)return null;const t=hg(e),n=typeof e.info?.id=="string"?e.info.id:"",r=pg(e)??"";return`${n}::${t}::${r}`},yY=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}),vY=(e,t,n)=>{if(!e||!t)return null;if(t.length===n.length){let f=-1;for(let u=0;u<n.length;u+=1)if(t[u]!==n[u]){if(f!==-1)return null;f=u}return f===-1?e:f!==n.length-1?null:y5(t[f])===y5(n[f])?e:null}if(n.length!==t.length+1)return null;for(let f=0;f<t.length;f+=1)if(t[f]!==n[f])return null;const r=n[n.length-1];if(!r)return null;const s=hg(r),o=r.info.id,i=yY(e);if(s==="user"){const f=i.turnIds.length;return i.turnIds.push(o),i.turnMessageStartIndexes.push(n.length-1),i.turnIndexById.set(o,f),i.messageToTurnId.set(o,o),i.messageToTurnIndex.set(o,f),i.turnCount=i.turnIds.length,i}if(s!=="assistant"){const f=i.turnIds.length-1;if(f<0)return null;const u=i.turnIds[f];return u?(i.messageToTurnId.set(o,u),i.messageToTurnIndex.set(o,f),i):null}const a=pg(r);if(!a)return i;const l=i.turnIndexById.get(a);if(typeof l!="number"||l<0)return null;const d=i.turnIds[l];return d?(i.messageToTurnId.set(o,d),i.messageToTurnIndex.set(o,l),i):null},xY=e=>{const t=[],n=[],r=new Map,s=new Map,o=new Map,i=new Map;let a=-1;return e.forEach((l,d)=>{const f=hg(l),u=l.info.id;if(f==="user"){a=t.length,t.push(u),n.push(d),r.set(u,a),i.set(u,a),s.set(u,u),o.set(u,a);return}if(f!=="assistant"){if(a>=0){const x=t[a];x&&(s.set(u,x),o.set(u,a))}return}const h=pg(l);if(!h)return;const m=i.get(h);if(typeof m!="number"||m<0)return;const g=t[m];g&&(s.set(u,g),o.set(u,m))}),{turnIds:t,turnMessageStartIndexes:n,turnIndexById:r,messageToTurnId:s,messageToTurnIndex:o,turnCount:t.length}},bY=30,wY=1200,SY=1.5,CY=e=>Math.max(wY,e*SY),kY=4,MY=30,IY=250,EY=2e3,_Y=2500,go=new Map,jY=()=>un()?kY:bY,TY=e=>un()?e.length<=MY:!0,v5=(e,t)=>{if(go.delete(e),!TY(t.messages))return;const n=jY();for(;go.size>=n;){const r=go.keys().next().value;if(typeof r!="string")break;go.delete(r)}go.set(e,t)},AY=e=>!e.sessionId||!e.isPinned||!e.canLoadEarlier||e.isLoadingOlder||e.pendingRevealWork?!1:e.scrollHeight<=e.clientHeight+1,x5=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),NY=20,LY=4,b5=(e,t)=>{const n=e.style.overflow;if(e.style.overflow="hidden",e.scrollTop=t,e.scrollHeight,e.style.overflow=n,e.scrollTop=t,typeof window>"u")return;let r=!1,s=0;const o=()=>{r=!0};e.addEventListener("touchstart",o,{passive:!0,once:!0});const i=()=>{r||(e.scrollTop<t-LY&&(e.scrollTop=t),s+=1,s<NY?window.requestAnimationFrame(i):e.removeEventListener("touchstart",o))};window.requestAnimationFrame(i)},w5=(e,t,n)=>!e||!t||t===e?!1:n.some(r=>r.info.id===e);function RY({sessionKey:e,timelineIdentityRef:t,scrollRef:n,messageListRef:r,renderedMessages:s,isPinnedRef:o,goToBottom:i,captureViewportAnchor:a,restoreViewportAnchor:l}){const d=p.useRef(null),f=p.useRef(null);return p.useLayoutEffect(()=>{d.current=null,f.current=null},[e]),p.useLayoutEffect(()=>{const u=n.current;if(!u)return;let h=d.current;const m=f.current,g=s[0]?.info?.id??null,x=s[s.length-1]?.info?.id??null,b=m?x5({previousOldestId:m.oldestId,previousNewestId:m.newestId,currentOldestId:g,currentNewestId:x})||w5(m.oldestId,g,s):!1;h&&h.identity!==t.current&&(d.current=null,h=null);const S=h?x5({previousOldestId:h.oldestId,previousNewestId:h.newestId,currentOldestId:g,currentNewestId:x})||w5(h.oldestId,g,s):!1,y=b||S,v=!!(h&&(b||S)),C=()=>{f.current={oldestId:g,newestId:x,scrollHeight:u.scrollHeight}},w=()=>{const E=d.current;E&&(d.current={...E,height:u.scrollHeight,top:u.scrollTop,anchor:a(),oldestId:g,newestId:x})};if(o.current){y?(d.current=null,i("instant")):h&&w(),C();return}const I=r.current?.isHistoryVirtualized()??!1;if(h&&v){if(d.current=null,I){!h.historyVirtualized&&h.anchor&&l(h.anchor),C();return}const E=u.scrollHeight-h.height,T=()=>E<=0?!1:(u.scrollTop=h.top+E,!0);if(un()&&E>0){b5(u,h.top+E),C();return}h.anchor&&l(h.anchor)||T()}else if(b&&m&&!I){const E=u.scrollHeight-m.scrollHeight;if(E>0){const T=u.scrollTop+E;un()?b5(u,T):u.scrollTop=T}}else h&&w();C()},[a,r,s,n,l,i,o,t]),{prePrependScrollRef:d}}const PY=({sessionId:e,sessionKey:t,messages:n,historyMeta:r,scrollRef:s,messageListRef:o,loadMoreMessages:i,goToBottom:a,releaseAutoFollow:l,isPinned:d,showScrollButton:f})=>{const u=p.useRef(null),h=p.useRef(null),m=p.useRef(null),g=p.useMemo(()=>{const te=t??"";m.current!==t&&(m.current=t,u.current=null,h.current=null);const Q=te?go.get(te):void 0;if(Q&&Q.messages===n)return v5(te,Q),u.current=Q.model,h.current=n,Q.model;const Se=vY(u.current,h.current,n)??xY(n);return u.current=Se,h.current=n,te&&n.length>0&&v5(te,{messages:n,model:Se}),Se},[n,t]),[x,b]=p.useState(!1),[S,y]=p.useState(!1),[v,C]=p.useState(null),w=p.useRef(g),I=p.useRef(d),E=p.useRef(x),T=p.useRef(S),A=p.useRef(e),j=p.useRef({key:t});j.current.key!==t&&(j.current={key:t});const k=p.useRef(n),_=p.useRef(r),M=p.useRef(null),L=p.useRef([]),O=p.useRef(null),N=p.useRef(null),D=p.useRef(!1),W=p.useRef(null),z=p.useMemo(()=>{const te=Iy().HISTORICAL_MESSAGES,Q=!1,me=r?!r.complete:n.length>=te,Se=!!r?.loading;return{hasBufferedTurns:Q,hasMoreAboveTurns:me,historyLoading:Se,canLoadEarlier:me}},[r,n.length]),X=p.useRef(z);w.current=g,I.current=d,E.current=x,T.current=S,X.current=z,A.current=e,k.current=n,_.current=r;const F=p.useCallback(()=>{D.current=!0,W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null)},[]),U=p.useCallback(()=>{if(typeof window>"u"){D.current=!1;return}W.current!==null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{W.current=null,D.current=!1},EY)},[]);p.useLayoutEffect(()=>{if(M.current===t)return;W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null),D.current=!1,M.current=t;const te=O.current;te&&te.identity!==j.current&&(O.current=null,te.resolve(!1)),b(!1),y(!1),N.current=null,C(null)},[t]),p.useLayoutEffect(()=>{if(!d)return;const te=g.turnIds[g.turnIds.length-1];te&&C(Q=>Q===te?Q:te)},[d,g.turnIds]);const P=p.useCallback(()=>{const te=L.current;te.length!==0&&(L.current=[],te.forEach(Q=>Q()))},[]),q=p.useCallback(()=>new Promise(te=>{if(typeof window>"u"){te();return}let Q=!1;const me=()=>{Q||(Q=!0,window.clearTimeout(Se),te())};L.current.push(me);const Se=window.setTimeout(me,IY)}),[]),B=p.useCallback(te=>{const Q=O.current;Q&&(O.current=null,Q.resolve(te))},[]),ee=p.useCallback(()=>{const te=O.current;if(!te)return;if(te.identity!==j.current){B(!1);return}if(te.kind==="turn"?o.current?.scrollToTurnId(te.id,{behavior:te.behavior})??!1:o.current?.scrollToMessageId(te.id,{behavior:te.behavior})??!1){te.turnId&&(N.current={turnId:te.turnId,expiresAt:Date.now()+_Y},C(te.turnId)),B(!0);return}typeof(te.kind==="turn"?w.current.turnIndexById.get(te.id):w.current.messageToTurnIndex.get(te.id))=="number"&&B(!1)},[o,B]);p.useEffect(()=>()=>{W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null),P(),B(!1)},[P,B]);const G=n;p.useLayoutEffect(()=>{P(),ee()},[ee,G,P]);const K=p.useCallback(()=>o.current?.captureViewportAnchor()??null,[o]),se=p.useCallback(te=>o.current?.restoreViewportAnchor(te)??!1,[o]),{prePrependScrollRef:de}=RY({sessionKey:t,timelineIdentityRef:j,scrollRef:s,messageListRef:o,renderedMessages:G,isPinnedRef:I,goToBottom:a,captureViewportAnchor:K,restoreViewportAnchor:se}),oe=p.useCallback(async()=>!1,[]),ue=p.useCallback(async te=>{if(!A.current||!j.current.key||E.current||!X.current.hasMoreAboveTurns)return!1;const Q=A.current,me=j.current;if(!Q||!me.key)return!1;const Se=()=>{de.current?.identity===me&&(de.current=null)},_e=s.current,Fe=k.current,ht=Fe.length,ge=Fe[0]?.info?.id??null,Ze=_.current?.limit??Iy().HISTORICAL_MESSAGES;te.preserveViewport&&_e&&(de.current={identity:me,height:_e.scrollHeight,top:_e.scrollTop,anchor:K(),historyVirtualized:o.current?.isHistoryVirtualized()??!1,oldestId:ge,newestId:Fe[Fe.length-1]?.info?.id??null}),F(),b(!0);try{let Ve=ht,ie=ge,ke=Ze;const ve=w.current.turnCount;for(;;){if(await i(Q,"up"),j.current!==me||(await q(),j.current!==me))return Se(),!1;const xe=k.current,je=xe.length,le=xe[0]?.info?.id??null,J=_.current?.limit??ke,ne=je>Ve||typeof ie=="string"&&typeof le=="string"&&ie!==le||J>ke;if(w.current.turnCount-ve>0)return!0;if(!ne)return Se(),!1;if(!X.current.hasMoreAboveTurns)return!0;Ve=je,ie=le,ke=J}}catch(Ve){throw Se(),Ve}finally{j.current===me&&(b(!1),U())}},[F,K,i,o,de,s,U,q]),ye=p.useCallback(async te=>{const Q=j.current;F(),te?.userInitiated&&l();try{await ue({preserveViewport:!0})}finally{j.current===Q&&U()}},[F,ue,l,U]),we=p.useCallback(()=>{if(un())return;const te=s.current;te&&(I.current||te.scrollTop>=CY(te.clientHeight)||X.current.canLoadEarlier&&(E.current||T.current||ye({userInitiated:!0})))},[ye,s]),Me=p.useCallback(()=>{if(un()||D.current)return;const te=s.current;te&&AY({sessionId:A.current,isPinned:I.current,canLoadEarlier:X.current.canLoadEarlier,isLoadingOlder:E.current,pendingRevealWork:T.current,scrollHeight:te.scrollHeight,clientHeight:te.clientHeight})&&ye()},[ye,s]);p.useEffect(()=>{if(typeof window>"u")return;const te=window.requestAnimationFrame(()=>{Me()});return()=>window.cancelAnimationFrame(te)},[z.canLoadEarlier,x,d,Me,S,G.length,t]),p.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const te=s.current;if(!te)return;let Q=null;const me=()=>{Q===null&&(Q=window.requestAnimationFrame(()=>{Q=null,Me()}))},Se=new ResizeObserver(me);Se.observe(te);const _e=te.firstElementChild;return _e instanceof Element&&Se.observe(_e),me(),()=>{Q!==null&&window.cancelAnimationFrame(Q),Se.disconnect()}},[Me,s,t]);const He=p.useCallback(async(te,Q)=>{if(!te||!A.current||!j.current.key)return!1;const me=j.current;l(),y(!0);try{return j.current!==me||typeof w.current.turnIndexById.get(te)!="number"?!1:!!await new Promise(Fe=>{O.current={identity:me,kind:"turn",id:te,behavior:Q?.behavior??"auto",turnId:te,resolve:Fe},ee()})}finally{j.current===me&&y(!1)}},[ee,l]),Ae=p.useCallback(async(te,Q)=>{if(!te||!A.current||!j.current.key)return!1;const me=j.current;l(),y(!0);try{if(j.current!==me)return!1;const Se=w.current.messageToTurnId.get(te);return typeof w.current.messageToTurnIndex.get(te)!="number"?!1:!!await new Promise(ht=>{O.current={identity:me,kind:"message",id:te,behavior:Q?.behavior??"auto",turnId:Se??null,resolve:ht},ee()})}finally{j.current===me&&y(!1)}},[ee,l]),Ge=p.useCallback(async()=>{y(!1),b(!1),a("smooth")},[a]),et=p.useCallback(async()=>{y(!1),b(!1),a("instant")},[a]),Xe=p.useCallback(te=>{const Q=N.current;if(Q){if(te!==Q.turnId&&Date.now()<Q.expiresAt)return;N.current=null}C(te)},[]);return{turnIds:g.turnIds,turnStart:0,renderedMessages:G,historySignals:z,isLoadingOlder:x,pendingRevealWork:S,activeTurnId:v,showScrollToBottom:f&&!S,turnWindowModel:g,loadEarlier:ye,revealBufferedTurns:oe,resumeToBottom:Ge,resumeToBottomInstant:et,scrollToTurn:He,scrollToMessage:Ae,handleHistoryScroll:we,captureViewportAnchor:K,restoreViewportAnchor:se,handleActiveTurnChange:Xe}};function hm(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
215
|
+
`)}function R9(e,t=80){const r=hm(e).replace(/\n/g," ");return r.length>t?`${r.slice(0,t)}…`:r}const DY=({open:e,onOpenChange:t,onScrollToMessage:n,onScrollByTurnOffset:r,onResumeToLatest:s,canLoadEarlier:o=!1,isLoadingEarlier:i=!1,onLoadEarlier:a,onRevert:l,onFork:d})=>{const{isMobile:f}=On(),u=he(q=>q.currentSessionId),[h,m]=p.useState(0);p.useEffect(()=>{if(!u){m(0);return}const q=()=>{try{const{getPiSessionStore:B}=require("@/apps/pi-session-store");m(B().getState().reducer.bySession.get(u)?.sessionTreeRevision??0)}catch{m(0)}};q();try{const{getPiSessionStore:B}=require("@/apps/pi-session-store");return B().subscribe(q,`session:${u}`)}catch{return}},[u]);const[g,x]=p.useState(new Map),b=p.useRef(null);p.useEffect(()=>{if(!e||!u)return;b.current!==u&&(b.current=u,x(new Map));let q=!1;return(async()=>{try{const{getPiSessionStore:B}=require("@/apps/pi-session-store"),ee=await B().tree(u);if(q)return;const G=new Map,K=se=>{se.label&&G.set(se.entryId,se.label);for(const de of se.children)K(de)};for(const se of ee.nodes)K(se);x(G)}catch{}})(),()=>{q=!0}},[u,e,h]);const[S,y]=p.useState(!1);p.useEffect(()=>{if(!u){y(!1);return}const q=()=>{try{const{getPiSessionStore:B}=require("@/apps/pi-session-store"),ee=B().getState().reducer.bySession.get(u);y(ee?.lifecycle==="busy"||ee?.lifecycle==="retry")}catch{y(!1)}};q();try{const{getPiSessionStore:B}=require("@/apps/pi-session-store");return B().subscribe(q,`session:${u}`)}catch{return}},[u]);const v=fu(u??""),[C,w]=p.useState(""),[I,E]=p.useState(0),T=p.useRef([]),A=p.useRef(null),j=p.useRef(null),k=p.useRef(!1),_=p.useRef(e),M=p.useCallback(q=>new Date(q).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),[]),L=p.useCallback(q=>new Date(q).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),[]),O=p.useMemo(()=>v.filter(q=>q.info.role==="user").map(q=>({message:q})),[v]),N=p.useMemo(()=>{const q=C.trim();if(!q)return O;const B=q.toLowerCase();return O.filter(({message:ee})=>hm(ee.parts).toLowerCase().includes(B))},[O,C]);p.useEffect(()=>{k.current||E(C.trim()?0:Math.max(0,N.length-1))},[N,C]),p.useEffect(()=>{T.current=T.current.slice(0,N.length)},[N.length]),p.useEffect(()=>{k.current||T.current[I]?.scrollIntoView({block:"nearest"})},[I]),p.useEffect(()=>{!k.current||j.current||i||(k.current=!1)},[N.length,i]),p.useLayoutEffect(()=>{const q=_.current;if(_.current=e,!e||q||k.current||C.trim())return;const B=A.current;B&&(B.scrollTop=B.scrollHeight)},[e,C]),p.useLayoutEffect(()=>{const q=j.current,B=A.current;if(!q||!B||i)return;j.current=null;const ee=T.current.find(K=>K?.dataset.timelineMessageId===q.messageId);if(!ee)return;const G=ee.getBoundingClientRect().top-B.getBoundingClientRect().top;B.scrollTop+=G-q.top},[N.length,i]);const D=p.useCallback(()=>{const q=A.current;if(q){const B=q.getBoundingClientRect().top,ee=T.current.find(G=>G?G.getBoundingClientRect().bottom>=B:!1);ee?.dataset.timelineMessageId&&(j.current={messageId:ee.dataset.timelineMessageId,top:ee.getBoundingClientRect().top-B})}k.current=!0,a?.()},[a]),W=p.useCallback(async q=>{await n?.(q)!==!1&&t(!1)},[t,n]),z=p.useCallback(q=>{const B=N.length;if(B!==0){if(q.key==="ArrowDown"){q.preventDefault(),E(ee=>(ee+1)%B);return}if(q.key==="ArrowUp"){q.preventDefault(),E(ee=>(ee-1+B)%B);return}if(q.key==="Enter"){q.preventDefault();const ee=(I%B+B)%B,G=N[ee];G&&W(G.message.info.id)}}},[N,W,I]),X=p.useCallback(async()=>{const q=N.length;if(q===0||!l||S)return;const B=(I%q+q)%q,ee=N[B];if(ee)try{await l(ee.message.info.id),t(!1)}catch(G){Ce.error(G instanceof Error?G.message:"Failed to revert")}},[N,S,l,t,I]),F=p.useCallback(async()=>{const q=N.length;if(q===0||!d||S)return;const B=(I%q+q)%q,ee=N[B];if(ee)try{await d(ee.message.info.id),t(!1)}catch(G){Ce.error(G instanceof Error?G.message:"Failed to fork")}},[N,S,d,t,I]),U=p.useCallback(q=>{const B=N.length;if(B!==0){if(q.key==="ArrowDown"){q.preventDefault(),E(ee=>(ee+1)%B);return}if(q.key==="ArrowUp"){q.preventDefault(),E(ee=>(ee-1+B)%B);return}if(q.key==="Enter"){q.preventDefault();const ee=(I%B+B)%B,G=N[ee];G&&W(G.message.info.id)}}},[N,W,I]);if(p.useEffect(()=>{if(!e||f)return;const q=window.setTimeout(()=>A.current?.focus(),100);return()=>window.clearTimeout(q)},[e,f]),!u)return null;const P=N[(I%Math.max(1,N.length)+Math.max(1,N.length))%Math.max(1,N.length)]?.message??null;return c.jsx(gu,{open:e,onOpenChange:t,children:c.jsxs(yu,{className:R("flex flex-col",f?"max-w-full max-h-[85vh] rounded-t-2xl mt-auto":"max-w-2xl max-h-[70vh]"),children:[c.jsxs(vu,{children:[c.jsxs(xu,{className:"flex items-center gap-2",children:[c.jsx(V,{name:"time",className:"h-5 w-5"}),"Conversation timeline"]}),c.jsx(s1,{children:f?"Tap a message, then Revert or Fork":"Arrow keys to move • Enter to jump"})]}),!f&&c.jsxs("div",{className:"relative mt-2",children:[c.jsx(V,{name:"search",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(Uo,{placeholder:"Search messages...",value:C,onChange:q=>w(q.target.value),onKeyDown:z,className:"pl-9 w-full"})]}),o&&a&&c.jsx("div",{className:"flex justify-center py-1",children:c.jsxs(be,{type:"button",variant:"link",size:"sm",onClick:D,disabled:i,className:"h-auto px-1 py-0 text-muted-foreground hover:text-foreground",children:[i&&c.jsx(V,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),c.jsx("div",{ref:A,tabIndex:0,onKeyDown:U,className:"flex-1 overflow-y-auto outline-none focus-visible:ring-1 focus-visible:ring-ring rounded","aria-label":"Message list",children:N.length===0?c.jsx("div",{className:"text-center text-muted-foreground py-8",children:C?"No messages found":"No messages in this session yet"}):N.map(({message:q},B)=>{const ee=R9(q.parts),G=q.info.time?.created??0,K=M(G),se=N[B-1],de=se?M(se.message.info.time?.created??0):null,oe=K!==de,ue=L(G),ye=B===I,we=g.get(q.info.id),Me=C.trim()?HY(hm(q.parts),C):null;return c.jsxs(p.Fragment,{children:[oe&&c.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-3 bg-background/95 py-2 backdrop-blur-sm",children:[c.jsx("div",{className:"h-px flex-1 bg-border/60"}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:K}),c.jsx("div",{className:"h-px flex-1 bg-border/60"})]}),c.jsxs("div",{ref:He=>{T.current[B]=He},"data-timeline-message-id":q.info.id,className:R("group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",ye&&"bg-interactive-selection text-interactive-selection-foreground"),onClick:()=>{W(q.info.id)},onMouseEnter:()=>E(B),children:[c.jsx("span",{className:R("typography-meta w-16 flex-shrink-0 text-right tabular-nums",ye?"text-interactive-selection-foreground/70":"text-muted-foreground"),children:ue}),we&&c.jsx("span",{className:"max-w-40 shrink-0 truncate rounded-full border border-border/60 bg-muted/40 px-2 py-0.5 typography-micro text-muted-foreground",children:we}),c.jsxs("p",{className:R("flex-1 min-w-0 typography-small truncate",ye?"text-interactive-selection-foreground":"text-foreground"),children:[Me??(ee||"[No text content]"),!Me&&ee&&ee.length>=80&&"…"]})]})]},q.info.id)})}),P&&c.jsxs("div",{className:R("flex gap-2 mt-3",f?"flex-col":"flex-row"),children:[c.jsxs(be,{type:"button",variant:f?"default":"outline",size:f?"default":"sm",className:R(f&&"w-full justify-center h-11 text-base"),disabled:S,onClick:()=>{X()},children:[c.jsx(V,{name:"history",className:"h-4 w-4"}),"Revert"]}),c.jsxs(be,{type:"button",variant:"outline",size:f?"default":"sm",className:R(f&&"w-full justify-center h-11 text-base"),disabled:S,onClick:()=>{F()},children:[c.jsx(V,{name:"git-branch",className:"h-4 w-4"}),"Fork"]})]})]})})},OY=e=>e.open?c.jsx(DY,{...e}):null;function HY(e,t,n=30){const r=e.toLowerCase(),s=t.toLowerCase(),o=r.indexOf(s);if(o===-1)return null;const i=Math.max(0,o-n),a=Math.min(e.length,o+t.length+n);return`${i>0?"…":""}${e.slice(i,a).replace(/\n/g," ")}${a<e.length?"…":""}`}const FY=e=>{const t=e.startsWith("#")?e.slice(1):e;if(!t)return null;const n=t.match(/^turn-(.+)$/);if(n?.[1])return{kind:"turn",id:n[1]};const r=t.match(/^message-(.+)$/);return r?.[1]?{kind:"message",id:r[1]}:null},BY=(e,t,n)=>{if(n===0)return{kind:"noop"};if(e.length===0)return{kind:"noop"};const r=t?e.indexOf(t):e.length-1,o=(r>=0?r:e.length-1)+n;if(o>=e.length)return{kind:"resume"};const i=Math.max(0,o),a=e[i];return a?{kind:"turn",turnId:a}:{kind:"noop"}},pl=e=>{if(typeof window>"u")return;const t=e?`#${e}`:"",n=`${window.location.pathname}${window.location.search}${t}`;window.history.replaceState(window.history.state,"",n)},VY=({sessionId:e,turnIds:t,activeTurnId:n,scrollToTurn:r,scrollToMessage:s,resumeToBottom:o})=>{const i=p.useRef(t),a=p.useRef(n);p.useEffect(()=>{i.current=t},[t]),p.useEffect(()=>{a.current=n},[n]);const l=p.useCallback(async(h,m)=>h?(m?.updateHash!==!1&&pl(`turn-${h}`),r(h,{behavior:m?.behavior})):!1,[r]),d=p.useCallback(async(h,m)=>h?(m?.updateHash!==!1&&pl(`message-${h}`),s(h,{behavior:m?.behavior})):!1,[s]),f=p.useCallback(async(h,m)=>{const g=i.current,x=BY(g,a.current,h);if(x.kind==="noop")return h===0;if(x.kind==="resume"){if(m?.resumePastEnd===!1){const b=g[g.length-1];return b?l(b,{behavior:"auto"}):!1}return pl(null),o(),!0}return l(x.turnId,{behavior:"auto"})},[o,l]),u=p.useCallback(()=>{pl(null),o()},[o]);return p.useEffect(()=>{if(!e||typeof window>"u")return;const h=()=>{const m=FY(window.location.hash);if(m){if(m.kind==="turn"){l(m.id,{behavior:"auto",updateHash:!1});return}d(m.id,{behavior:"auto",updateHash:!1})}};return h(),window.addEventListener("hashchange",h),()=>{window.removeEventListener("hashchange",h)}},[e,d,l,t.length]),{scrollToTurnId:l,scrollToMessageId:d,scrollByTurnOffset:f,resumeToLatest:u}},$Y=[],zY={type:"idle"},S5="pichamber:chat-force-scroll-bottom",UY="Quota limit reached. Retrying automatically.",qY={overflowAnchor:"none",overscrollBehavior:"contain",overscrollBehaviorY:"contain","--scroll-shadow-top-size":"16px"},P9=e=>e?"relative":"relative z-10",Lh=(e,t=!1)=>R(P9(t),"flex flex-col gap-2 bg-background",e?"flex-1 min-h-0":"shrink-0"),WY=["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(","),KY=e=>e instanceof HTMLElement,mg=e=>KY(e)?!!e.closest(WY):!1,GY=(e,t)=>typeof document>"u"||!e||e===document.body||e===document.documentElement||mg(e)?!0:!t?.contains(e),ZY=()=>{const{isCommandPaletteOpen:e,isHelpDialogOpen:t,isImagePreviewOpen:n,isSessionSwitcherOpen:r,isSettingsDialogOpen:s}=re.getState();return e||t||n||r||s},YY=(e,t)=>{if(!t)return e;const n=e.indexOf(t);return n===-1?e:c.jsxs(c.Fragment,{children:[e.slice(0,n),c.jsx("span",{className:"font-medium",children:t}),e.slice(n+t.length)]})},C5=()=>{const e=he(n=>n.newSessionDraft.selectedProjectId??null),t=ct(p.useCallback(n=>kL({selectedProjectId:e,activeProjectId:n.activeProjectId,projects:n.projects}),[e]));return c.jsxs("div",{className:"oc-draft-center flex min-h-0 flex-1 flex-col items-center justify-center px-6 text-center",children:[c.jsx("h1",{className:"text-balance text-3xl font-normal tracking-tight text-foreground",children:YY(t?`What are we working on in ${t}?`:"What are we working on?",t)}),c.jsx(w4,{onInsert:n=>{n.ref.type==="text"?Ye.getState().requestStarterTextInsert(n.insertText):Ye.getState().requestStarterInsert(n.promptName)},className:"oc-draft-starters mt-8 max-w-md"})]})},D9=p.memo(()=>{const e=he(l=>l.currentSessionId),t=he(p.useCallback(l=>e?l.sessionAbortFlags?.get(e)??null:null,[e])),{activeModel:n,working:r}=l9(),s=Wb(e??""),o=We(l=>l.providers),i=p.useMemo(()=>{if(!n)return null;const l=o.length>0?o.find(d=>d.id===n.providerId):void 0;return _1(l,n.modelId)||null},[n,o]),a=!!(t&&!t.acknowledged);return c.jsx(J3,{isWorking:r.isWorking,statusText:r.statusText,isGenericStatus:r.isGenericStatus,isWaitingForPermission:r.isWaitingForPermission,wasAborted:a||r.wasAborted,abortActive:a||r.abortActive,retryInfo:r.retryInfo,showAssistantStatus:!0,showTodos:!1,modelName:i,providerId:n?.providerId??null,turnStartedAt:s})});D9.displayName="StatusRowContainer";const XY=160,Rh=28,JY=12,Li=6,QY=8,Ri=30,Pi=12,k5=18,eX=80,ml=4,tX=10,nX=14,rX=20,an=54,M5=4,sX=8,I5=2,oX=160,iX=(e,t)=>e.map(n=>{const r=t.get(n)??[];return{turnId:n,preview:R9(r,XY)}}),aX=[1,.6,.35,.15],cX=(e,t,n)=>{const r=n?nX:tX;if(t===null)return r;const s=Math.abs(e-t),o=aX[s]??0;return Math.round(r+(rX-r)*o)};function lX({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:s,isLoadingOlder:o,onLoadEarlier:i}){const a=re(J=>J.isPromptNavigatorPanelOpen),l=re(J=>J.setPromptNavigatorPanelOpen),d=p.useRef(null),f=p.useRef(null),[u,h]=p.useState(null),[m,g]=p.useState(0),[x,b]=p.useState(!1),[S,y]=p.useState(Li);p.useEffect(()=>{const J=f.current?.parentElement;if(!J||typeof ResizeObserver>"u")return;const ne=()=>{const Ue=J.querySelector(".chat-message-column");if(!Ue){b(!1),y(Li);return}const st=J.getBoundingClientRect(),Ee=Ue.getBoundingClientRect(),Ke=st.right-Ee.right-QY-Rh;if(Ke<=Li){y(Li);const _t=st.right-Li-Rh;b(Ee.right>_t);return}y(Ke),b(!1)};ne();const fe=new ResizeObserver(ne);fe.observe(J);const De=J.querySelector(".chat-message-column");return De&&fe.observe(De),()=>fe.disconnect()},[e.length]);const v=p.useMemo(()=>iX(e,t),[t,e]),C=Math.min(v.length,Ri),w=Math.max(0,v.length-C),I=Math.min(m,w),E=I+C,T=I>0,A=E<v.length,j="[No text content]",k="Current prompt",_="Load more prompts",M=p.useMemo(()=>n?v.findIndex(J=>J.turnId===n):-1,[n,v]),L=p.useRef(I);L.current=I;const O=p.useRef(v.length);O.current=v.length;const N=p.useRef(null),D=p.useRef(null),W=p.useRef(0),z=p.useCallback(J=>{g(ne=>{const fe=O.current,De=Math.min(fe,Ri),Ue=Math.max(0,fe-De),st=Math.min(ne,Ue);return J<st?J:J>=st+De?Math.min(Ue,J-De+1):st})},[]),X=p.useRef(v[0]?.turnId),F=p.useRef(v.length);p.useLayoutEffect(()=>{const J=X.current,ne=F.current,fe=v.length-ne;fe>0&&ne>0&&J&&v[0]?.turnId!==J&&(g(De=>De+fe),h(De=>De===null?null:De+fe)),X.current=v[0]?.turnId,F.current=v.length},[v]),p.useEffect(()=>{if(u!==null)return;const J=M>=0?M:v.length-1;g(()=>{const ne=O.current,fe=Math.min(ne,Ri),De=Math.max(0,ne-fe);return Math.max(0,Math.min(De,J-Math.floor(fe/2)))})},[M,u,v.length]);const U=p.useCallback(J=>{const ne=d.current;if(!ne)return null;const fe=ne.getBoundingClientRect(),De=Math.floor((J-fe.top)/Pi),Ue=Math.min(O.current,Ri);return Ue===0?null:Math.max(0,Math.min(Ue-1,De))},[]),P=p.useCallback(()=>{W.current=0,D.current!==null&&(window.clearInterval(D.current),D.current=null)},[]),q=p.useCallback(()=>{const J=W.current;if(J===0){P();return}const ne=O.current,fe=Math.min(ne,Ri),De=Math.max(0,ne-fe),Ue=Math.min(L.current,De),st=Math.max(0,Math.min(De,Ue+J));if(st===Ue){P();return}L.current=st,g(st);const Ee=N.current;if(Ee!==null){const Ke=U(Ee);Ke!==null&&h(Math.min(ne-1,st+Ke))}},[U,P]),B=p.useCallback(J=>{const ne=d.current;if(!ne)return;const fe=ne.getBoundingClientRect(),De=J-fe.top;let Ue=0;if(De<=k5&&T?Ue=-1:De>=fe.height-k5&&A&&(Ue=1),W.current=Ue,Ue===0){P();return}D.current===null&&(D.current=window.setInterval(q,eX))},[q,T,A,P]);p.useEffect(()=>()=>{D.current!==null&&window.clearInterval(D.current)},[]);const ee=p.useRef(null),G=p.useCallback(()=>{ee.current!==null&&(window.clearTimeout(ee.current),ee.current=null)},[]),K=p.useCallback(()=>{G(),ee.current=window.setTimeout(()=>{ee.current=null,h(null)},oX)},[G]);p.useEffect(()=>()=>{ee.current!==null&&window.clearTimeout(ee.current)},[]);const se=p.useCallback(J=>{G(),N.current=J.clientY;const ne=U(J.clientY);ne!==null&&h(Math.min(O.current-1,L.current+ne)),B(J.clientY)},[G,U,B]),de=p.useCallback(()=>{N.current=null,P(),K()},[K,P]),oe=p.useCallback(()=>{l(!1)},[l]),ue=p.useCallback(J=>{if(J===null)return;const ne=v[J];ne&&(r(ne.turnId),P(),h(null),oe(),d.current?.blur())},[oe,r,v,P]),ye=p.useCallback(J=>{const ne=U(J.clientY);ne!==null&&ue(Math.min(v.length-1,L.current+ne))},[ue,v.length,U]);p.useEffect(()=>{if(!a)return;const J=d.current;!J||J===document.activeElement||(J.focus(),h(ne=>{if(ne!==null)return ne;const fe=M>=0?M:v.length-1;return z(fe),fe}))},[M,z,a,v.length]),p.useEffect(()=>()=>{l(!1)},[l]);const we=p.useCallback(J=>{if(v.length===0)return;const ne=u??(M>=0?M:v.length-1),fe=De=>{const Ue=Math.max(0,Math.min(v.length-1,De));z(Ue),h(Ue)};if(J.key==="ArrowUp"||J.key==="ArrowDown"){J.preventDefault(),fe(ne+(J.key==="ArrowUp"?-1:1));return}if(J.key==="Home"){J.preventDefault(),fe(0);return}if(J.key==="End"){J.preventDefault(),fe(v.length-1);return}if(J.key==="Enter"||J.key===" "){J.preventDefault(),ue(ne);return}J.key==="Escape"&&(J.preventDefault(),h(null),oe(),d.current?.blur())},[M,oe,z,ue,u,v]),Me=p.useCallback(()=>{P(),h(null),oe()},[oe,P]),He=p.useRef(null),Ae=p.useRef(u);Ae.current=u;const Ge=u!==null,et=p.useRef(0);p.useEffect(()=>{const J=He.current;if(!J)return;const ne=fe=>{fe.preventDefault(),fe.stopPropagation(),et.current+=fe.deltaY;const De=Math.trunc(et.current/an);if(De===0)return;et.current-=De*an;const Ue=Ae.current;if(Ue===null)return;const st=Math.max(0,Math.min(O.current-1,Ue+De));st!==Ue&&(z(st),h(st))};return J.addEventListener("wheel",ne,{passive:!1}),()=>J.removeEventListener("wheel",ne)},[z,Ge]);const Xe=u!==null?v[u]:void 0,te=Math.min(v.length,sX),Q=te*an,me=v.length*an-Q,Se=J=>Math.max(0,Math.min(me,J)),_e=p.useRef(null);let Fe=0;if(u===null)_e.current=null;else if(_e.current===null)Fe=Se(u*an-(Q-an)/2),_e.current=Fe;else{let J=_e.current;const ne=(u-I5)*an,fe=(u+1+I5)*an-Q;J>ne?J=ne:J<fe&&(J=fe),Fe=Se(J),_e.current=Fe}const ht=Math.floor(Fe/an),ge=Math.max(0,ht-ml),Ze=Math.min(v.length,ht+te+ml),Ve=Fe>0,ie=Fe<me,ke=Ve||ie?`linear-gradient(to bottom, ${Ve?"transparent, black 10%":"black"}, ${ie?"black 90%, transparent":"black"})`:void 0,ve=Math.max(0,I-ml),xe=Math.min(v.length,E+ml),je=v.slice(ve,xe),le=T||A?`linear-gradient(to bottom, ${T?"transparent, black 14%":"black"}, ${A?"black 86%, transparent":"black"})`:void 0;return v.length===0?null:c.jsx("nav",{ref:f,"aria-label":"Prompt navigation",className:"pointer-events-none absolute top-1/2 z-20 -translate-y-1/2",style:{right:`${S}px`},children:c.jsxs("div",{className:"pointer-events-auto flex flex-col items-end",children:[s?c.jsx("button",{type:"button",tabIndex:-1,className:R("-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)]",o?"cursor-wait opacity-70":void 0),"aria-label":_,title:_,disabled:o,onClick:J=>{J.stopPropagation(),o||i()},children:o?c.jsx(V,{name:"loader-4",className:"size-3.5 animate-spin"}):c.jsx(V,{name:"arrow-up-s",className:"size-3.5"})}):null,c.jsxs("div",{ref:d,role:"listbox",tabIndex:-1,"aria-activedescendant":Xe?`prompt-rail-tick-${Xe.turnId}`:void 0,className:"relative cursor-pointer outline-none",style:{width:`${x?JY:Rh}px`,height:`${C*Pi}px`},onMouseMove:se,onMouseLeave:de,onClick:ye,onKeyDown:we,onBlur:Me,children:[c.jsx("div",{className:"absolute inset-0 overflow-hidden",style:le?{maskImage:le,WebkitMaskImage:le}:void 0,children:c.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-300 ease-out",style:{transform:`translateY(-${I*Pi}px)`},children:je.map((J,ne)=>{const fe=ve+ne,De=J.turnId===n,Ue=u===fe,st=cX(fe,u,De);return c.jsx("div",{id:`prompt-rail-tick-${J.turnId}`,role:"option","aria-selected":Ue,"aria-current":De?"true":void 0,"aria-label":J.preview.trim()||j,className:"pointer-events-none absolute right-1 flex items-center justify-end",style:{top:`${fe*Pi}px`,height:`${Pi}px`},children:c.jsx("span",{"aria-hidden":"true",className:R("block h-0.5 rounded-full transition-all duration-200 ease-out",De?"bg-[var(--surface-foreground)]":Ue?"bg-[var(--surface-foreground)]/80":"bg-[var(--surface-foreground)]/30"),style:{width:`${st}px`}})},J.turnId)})},v[0]?.turnId)}),Xe&&u!==null?c.jsx("div",{ref:He,className:R("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:G,onMouseLeave:K,onMouseMove:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),children:c.jsx("div",{className:"relative overflow-hidden",style:{height:`${te*an}px`,maskImage:ke,WebkitMaskImage:ke},children:c.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-200 ease-out",style:{height:`${v.length*an}px`,transform:`translateY(-${Fe}px)`},children:v.slice(ge,Ze).map((J,ne)=>{const fe=ge+ne,De=J.turnId===n,Ue=u===fe;return c.jsx("div",{role:"option","aria-selected":Ue,"aria-current":De?"true":void 0,title:De?k:void 0,className:"absolute inset-x-0 cursor-pointer px-1.5",style:{top:`${fe*an+M5}px`,height:`${an-M5*2}px`},onMouseMove:()=>{G(),Ae.current!==fe&&(z(fe),h(fe))},onClick:()=>ue(fe),children:c.jsx("div",{className:R("flex h-full items-center rounded-lg border px-2 transition-colors",De?"border-transparent bg-[var(--interactive-selection)]":Ue?"border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]":"border-[var(--interactive-border)]/40"),children:c.jsx("span",{className:R("min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] typography-meta",De?"text-[var(--interactive-selectionForeground)]":"text-[var(--surface-mutedForeground)]"),children:J.preview.trim()||j})})},J.turnId)})})})}):null]})]})})}const O9=p.memo(({currentSessionId:e,currentSessionKey:t,isDesktopExpandedInput:n,isMobile:r,directory:s,scrollRef:o,messageListRef:i,pendingRevealWork:a,renderedMessages:l,isLoadingOlder:d,sessionIsWorking:f,sessionAwaitingRecovery:u,awaitingPromptEcho:h,streamingMessageId:m,activeStreamingPhase:g,retryOverlay:x,compactionOverlay:b,handleMessageContentChange:S,getAnimationHandlers:y,handleHistoryScroll:v,scrollToBottom:C,isProgrammaticFollowActive:w,showLoadOlderButton:I,onLoadOlder:E,turnIds:T,activeTurnId:A,onSelectTurn:j,showPromptNavigator:k,canLoadEarlierPrompts:_,isLoadingOlderPrompts:M,onLoadEarlierPrompts:L})=>{const O=p.useRef(new Map),N=p.useRef(new WeakMap),D=p.useRef(new Map),W=p.useRef(e);W.current!==e&&(W.current=e,D.current.clear());const z=p.useMemo(()=>{const P=new Map;for(let B=0;B<l.length;B+=1){const ee=l[B];if(ee.info.role!=="user")continue;if(p7(ee)){const K=zz(l,B)??"",se=D.current.get(ee.info.id);if(se&&se.command===K)P.set(ee.info.id,se.parts);else{const de=[{type:"text",text:K?`$ ${K}`:"/shell"}];D.current.set(ee.info.id,{command:K,parts:de}),P.set(ee.info.id,de)}continue}if(vK(ee.parts))continue;let G=N.current.get(ee.parts);G||(G=dg(ee.parts),N.current.set(ee.parts,G)),G.length!==0&&P.set(ee.info.id,G)}const q=O.current;if(q.size===P.size){let B=!0;for(const[ee,G]of P)if(q.get(ee)!==G){B=!1;break}if(B)return q}return O.current=P,P},[l]),X=p.useMemo(()=>T.filter(P=>z.has(P)),[z,T]),F=p.useMemo(()=>{if(!A||z.has(A))return A;const P=T.indexOf(A);for(let q=P-1;q>=0;q-=1){const B=T[q];if(z.has(B))return B}return null},[A,z,T]),U=p.useCallback(P=>{P.defaultPrevented||mg(P.target)||typeof window<"u"&&window.getSelection()?.type==="Range"||o.current?.focus({preventScroll:!0})},[o]);return c.jsx("div",{className:R("relative min-h-0",n?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":n,children:c.jsxs("div",{className:"absolute inset-0",children:[c.jsx(Su,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:o,style:qY,observeMutations:!1,size:24,hideTopShadow:!1,tabIndex:0,onClick:U,onScroll:v,"data-scroll-shadow":"true","data-scrollbar":"chat",children:c.jsxs("div",{className:"relative z-0 min-h-full",children:[I&&c.jsx("div",{className:"flex justify-center pt-3 pb-1",children:c.jsxs(be,{variant:"secondary",size:"sm",onClick:E,disabled:d,children:[d&&c.jsx(V,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),c.jsx(YZ,{ref:i,sessionKey:e,disableStaging:a,messages:l,sessionIsWorking:f,sessionAwaitingRecovery:u,awaitingPromptEcho:h,activeStreamingMessageId:m,activeStreamingPhase:g,retryOverlay:x,compactionOverlay:b,onMessageContentChange:S,getAnimationHandlers:y,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:s},t),T.length===0&&f?c.jsx("div",{className:"mb-3",children:c.jsx(D9,{})}):T.length===0&&u?c.jsx("div",{className:"chat-message-column mb-3",children:c.jsx("span",{className:"typography-markdown leading-5 text-muted-foreground",role:"status","data-turn-reconnecting":"true",children:"Reconnecting · last seen working"})}):null,c.jsx("div",{className:"flex-shrink-0",style:{height:r?"calc(40px + var(--oc-safe-area-bottom, 0px))":"calc(10vh + var(--oc-safe-area-bottom, 0px))"},"aria-hidden":"true"})]})}),c.jsx(t3,{containerRef:o,suppressVisibility:w,userIntentOnly:!0,observeMutations:!1}),k&&X.length>=2?c.jsx(lX,{turnIds:X,previewsByTurnId:z,activeTurnId:F,onSelectTurn:j,canLoadEarlier:_,isLoadingOlder:M,onLoadEarlier:L}):null]})})},(e,t)=>e.currentSessionId===t.currentSessionId&&e.currentSessionKey===t.currentSessionKey&&e.isDesktopExpandedInput===t.isDesktopExpandedInput&&e.isMobile===t.isMobile&&e.directory===t.directory&&e.scrollRef===t.scrollRef&&e.messageListRef===t.messageListRef&&e.pendingRevealWork===t.pendingRevealWork&&e.renderedMessages===t.renderedMessages&&e.isLoadingOlder===t.isLoadingOlder&&e.sessionIsWorking===t.sessionIsWorking&&e.sessionAwaitingRecovery===t.sessionAwaitingRecovery&&e.awaitingPromptEcho===t.awaitingPromptEcho&&e.streamingMessageId===t.streamingMessageId&&e.activeStreamingPhase===t.activeStreamingPhase&&e.retryOverlay===t.retryOverlay&&e.compactionOverlay===t.compactionOverlay&&e.handleMessageContentChange===t.handleMessageContentChange&&e.getAnimationHandlers===t.getAnimationHandlers&&e.handleHistoryScroll===t.handleHistoryScroll&&e.scrollToBottom===t.scrollToBottom&&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);O9.displayName="ChatViewport";const dX={isWorking:!1,isAwaitingRecovery:!1},BQ=({active:e=!0,autoOpenDraft:t=!0})=>{const n=he(Ee=>Ee.currentSessionId),r=he(Ee=>Ee.currentSessionDirectory),s=he(Ee=>Ee.openNewSessionDraft),o=he(Ee=>Ee.newSessionDraft),i=he(Ee=>Ee.sendingNewSessionDraftId),a=Lw(o,n,i),l=W3(),d=i_(),f=r??d,u=n?JSON.stringify([Y(),f,n]):null,h=p.useCallback(Ee=>l.ensureSessionRenderable(Ee),[l]),m=p.useCallback(async()=>{},[]),g=re(Ee=>Ee.isExpandedInput),x=re(Ee=>Ee.isTimelineDialogOpen),b=re(Ee=>Ee.setTimelineDialogOpen),S=Ew(),y=l4(),v=l_(n??""),w=S==="ready"&&!y?v:null,I=w?"streaming":null,E=f_(n??""),T=Tw(n??""),A=fu(n??""),j=W4(n),k=n?A:$Y,_=_w(n??""),M=a_(n??""),[L]=p.useState(TA);p.useEffect(()=>{if(!(!e||!u||!T||k.length===0))return L.schedule(u,k.length)},[e,u,L,T,k.length]);const O=du(n??"")??zY,N=uu(n??""),D=p.useMemo(()=>{if(!n)return dX;const Ee=O.type??"idle",Ke=k[k.length-1]?.info,_t=typeof Ke?.finish=="string"?Ke.finish:void 0,fn=!!(Ke&&Ke.role==="assistant"&&typeof Ke.time?.completed!="number"&&_t!=="stop"&&_t!=="error");return $N({connection:S,transportUncertain:y,authoritativeWorking:Ee==="busy"&&!N||Ee==="retry",hasPendingAssistant:fn,hasRetainedStream:!!v})},[S,n,v,N,k,O.type,y]),W=D.isWorking,z=D.isAwaitingRecovery,X=s_(n??""),F=W||X,U=d_(n??""),P=p.useMemo(()=>{if(!n||O.type!=="retry")return null;const Ee=typeof O.message=="string"?(O.message??"").trim():"";return{sessionId:n,message:Ee||UY,confirmedAt:O.confirmedAt}},[n,O]),q=n_(n??""),B=p.useMemo(()=>n&&q?{sessionId:n,compaction:q}:null,[q,n]),[ee,G]=p.useState(0),K=p.useRef(null);p.useEffect(()=>{if(!P||typeof P.confirmedAt=="number"){K.current=null,G(0);return}K.current!==P.sessionId&&(K.current=P.sessionId,G(Date.now()))},[P]);const se=p.useMemo(()=>P?{...P,fallbackTimestamp:ee}:null,[P,ee]),de=p.useMemo(()=>n?{limit:k.length,complete:M.complete||!M.cursor,loading:M.status==="loading"}:null,[n,M.complete,M.cursor,M.status,k.length]),{isMobile:oe}=On(),ue=Iu(),ye=!!o?.open,we=oe&&g,Me=oe||ue==="mini-chat",He=p.useRef(null);p.useEffect(()=>{xw().sessionId||t&&!n&&!ye&&s({automatic:!0})},[t,n,ye,s]);const Ae=p.useRef(()=>{}),Ge=p.useCallback(Ee=>{Ae.current(Ee)},[]),{scrollRef:et,notifyContentChange:Xe,getAnimationHandlers:te,goToBottom:Q,scrollToBottomOnSend:me,releaseAutoFollow:Se,restoreSnapshot:_e,isPinned:Fe,isFollowingProgrammatically:ht,showScrollButton:ge}=gY({currentSessionId:n,currentSessionKey:u,sessionMessageCount:E,latestTailEntryId:_.at(-1)?.id??null,sessionIsWorking:F,isMobile:oe,onActiveTurnChange:Ge}),Ve=PY({sessionId:n,sessionKey:u,messages:k,historyMeta:de,scrollRef:et,messageListRef:He,loadMoreMessages:m,goToBottom:Q,releaseAutoFollow:Se,isPinned:Fe,showScrollButton:ge}),ie=p.useCallback(()=>{Q("instant")},[Q]),ke=un()&&Ve.historySignals.canLoadEarlier,ve=Ve.loadEarlier,xe=p.useCallback(()=>{ve({userInitiated:!0})},[ve]);p.useEffect(()=>{Ae.current=Ve.handleActiveTurnChange},[Ve.handleActiveTurnChange]);const je=VY({sessionId:n,turnIds:Ve.turnIds,activeTurnId:Ve.activeTurnId,scrollToTurn:Ve.scrollToTurn,scrollToMessage:Ve.scrollToMessage,resumeToBottom:Ve.resumeToBottomInstant}),le=p.useCallback(Ee=>{je.scrollToTurnId(Ee,{behavior:"smooth"})},[je]),J=Ve.historySignals.canLoadEarlier,ne=!oe&&!we&&Ve.turnIds.length>=2;p.useEffect(()=>{ne||re.getState().setPromptNavigatorPanelOpen(!1)},[ne]),p.useEffect(()=>{if(typeof window>"u"||!n)return;const Ee=Ke=>{const _t=Ke;_t.detail?.sessionId&&_t.detail.sessionId!==n||Q("instant")};return window.addEventListener(S5,Ee),()=>{window.removeEventListener(S5,Ee)}},[n,Q]),p.useEffect(()=>{if(typeof window>"u"||!n||we)return;const Ee=Ke=>{if(Ke.defaultPrevented||Ke.isComposing||Ke.key!=="ArrowUp"&&Ke.key!=="ArrowDown"||Ke.altKey||Ke.ctrlKey||Ke.metaKey||Ke.shiftKey)return;const{activeMainTab:_t}=re.getState();if(_t!=="chat"||ZY())return;const fn=et.current;if(GY(document.activeElement,fn)||mg(Ke.target))return;Ke.preventDefault();const Sn=Ke.key==="ArrowUp"?-1:1;je.scrollByTurnOffset(Sn,{resumePastEnd:!1})};return window.addEventListener("keydown",Ee),()=>{window.removeEventListener("keydown",Ee)}},[n,we,je,et]),p.useLayoutEffect(()=>{const Ee=et.current;if(!Ee)return;const Ke=()=>{Ee.style.setProperty("--chat-scroll-height",`${Ee.clientHeight}px`)};Ke();let _t=0;const fn=()=>{_t||(_t=requestAnimationFrame(()=>{_t=0,Ke()}))};if(typeof ResizeObserver>"u")return window.addEventListener("resize",fn),()=>{_t&&cancelAnimationFrame(_t),window.removeEventListener("resize",fn)};const Sn=new ResizeObserver(fn);return Sn.observe(Ee),()=>{_t&&cancelAnimationFrame(_t),Sn.disconnect()}},[n,we,et]);const fe=p.useRef(null),Ue=!!n&&(!!n&&!T||M.status==="loading"),st=p.useCallback(()=>{!e||!n||l.ensureSessionRenderable(n)},[e,n,l]);return p.useEffect(()=>{if(!e||!n||fe.current===u)return;const Ee=typeof window<"u"&&window.location.hash.length>0;if(fe.current=u,Ee){Se();return}const Ke=()=>{_e()};typeof window>"u"?Ke():window.requestAnimationFrame(Ke)},[e,n,u,Se,_e]),p.useEffect(()=>{!e||!n||T||h(n)},[e,n,h,T]),!n&&!ye?t?c.jsx("div",{className:"flex h-full flex-col bg-background"}):c.jsx("div",{className:"flex flex-col h-full bg-background",children:c.jsx(Rz,{isNewSession:!0})}):!n&&ye?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[Me&&!we?c.jsx(C5,{}):null,c.jsx("div",{className:R("relative z-10 flex min-h-0",we?"flex-1 bg-background":Me?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:c.jsx(ji,{scrollToBottom:me})})]}):n?Ue?M.status==="error"?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center px-6",children:c.jsxs("div",{className:"max-w-sm text-center",children:[c.jsx("div",{className:"mx-auto mb-3 flex size-9 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--status-error)_10%,transparent)] text-[var(--status-error)]",children:c.jsx(V,{name:"error-warning",className:"size-4"})}),c.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:M.errorCode==="SESSION_IN_USE"?"Session is open elsewhere":"Session could not be loaded"}),c.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:M.errorCode==="SESSION_IN_USE"?"Another PiChamber instance is using this session. Close it there, then try again.":"Check the connection and try loading this session again."}),c.jsx(be,{variant:"outline",size:"sm",className:"mt-4",onClick:st,children:"Try again"})]})}),c.jsx("div",{className:Lh(!1),children:c.jsx(ji,{scrollToBottom:me})})]}):c.jsxs("div",{"data-composer-bound":!0,className:"relative flex flex-col h-full bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx("div",{className:R("relative min-h-0 flex items-center justify-center",we?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":we,children:c.jsxs("div",{className:"flex flex-col items-center gap-3",children:[c.jsx(a1,{width:120,height:120,isAnimated:!0}),a?c.jsx("p",{role:"status",className:"typography-meta animate-pulse text-muted-foreground",children:"Creating session…"}):null]})}),c.jsx("div",{className:Lh(we),children:c.jsx(ji,{scrollToBottom:me})})]}):k.length===0&&_.length===0&&!W&&!z?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[Me&&!we?c.jsx(C5,{}):null,c.jsx("div",{className:R(P9(j),"flex min-h-0",we?"flex-1 bg-background":Me?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:c.jsxs("div",{className:"flex w-full min-w-0 flex-col gap-2",children:[c.jsx(Uv,{sessionId:n}),c.jsx(qv,{sessionId:n}),c.jsx(Xv,{sessionId:n,children:c.jsx(ji,{scrollToBottom:me})})]})}),c.jsx(Qv,{sessionId:n},n)]}):c.jsxs("div",{"data-composer-bound":!0,className:"relative flex min-w-0 flex-1 flex-col h-full bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx(O9,{currentSessionId:n,currentSessionKey:u??n,isDesktopExpandedInput:we,isMobile:oe,directory:f,scrollRef:et,messageListRef:He,pendingRevealWork:Ve.pendingRevealWork,renderedMessages:Ve.renderedMessages,isLoadingOlder:Ve.isLoadingOlder,sessionIsWorking:W,sessionAwaitingRecovery:z,awaitingPromptEcho:U,streamingMessageId:w,activeStreamingPhase:I,retryOverlay:se,compactionOverlay:B,handleMessageContentChange:Xe,getAnimationHandlers:te,handleHistoryScroll:Ve.handleHistoryScroll,scrollToBottom:ie,isProgrammaticFollowActive:ht,showLoadOlderButton:ke,onLoadOlder:xe,turnIds:Ve.turnIds,activeTurnId:Ve.activeTurnId,onSelectTurn:le,showPromptNavigator:ne,canLoadEarlierPrompts:J,isLoadingOlderPrompts:Ve.isLoadingOlder,onLoadEarlierPrompts:xe}),c.jsxs("div",{className:Lh(we,j),children:[!we&&k.length>0&&c.jsx(JZ,{visible:Ve.showScrollToBottom,onClick:je.resumeToLatest}),c.jsx(q$,{sessionId:n}),c.jsx(Uv,{sessionId:n}),c.jsx(qv,{sessionId:n}),c.jsx(Xv,{sessionId:n,children:c.jsx(ji,{scrollToBottom:me})})]}),c.jsx(Qv,{sessionId:n},n),c.jsx(OY,{open:x,onOpenChange:b,onScrollToMessage:Ve.scrollToMessage,onScrollByTurnOffset:je.scrollByTurnOffset,onResumeToLatest:ie,canLoadEarlier:Ve.historySignals.canLoadEarlier,isLoadingEarlier:Ve.isLoadingOlder,onLoadEarlier:xe,onRevert:async Ee=>{if(!n)return;const Ke=Ee.includes(":")?Ee.split(":")[0]??Ee:Ee;await he.getState().revertToMessage(n,Ke)},onFork:async Ee=>{if(!n)return;const Ke=Ee.includes(":")?Ee.split(":")[0]??Ee:Ee;await he.getState().forkFromMessage(n,Ke)}})]}):null},uX=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(100,Math.round(e))),fX=e=>e>=90?"critical":e>=75?"warn":"safe",VQ=({percentage:e,size:t=18,stroke:n=3,className:r})=>{const s=uX(e),o=fX(e),i=o==="critical"?"var(--status-error)":o==="warn"?"var(--status-warning)":"var(--status-success)",a=(t-n)/2,l=2*Math.PI*a;return c.jsxs("svg",{viewBox:`0 0 ${t} ${t}`,className:r??"size-[18px] -rotate-90",role:"progressbar","aria-valuenow":Math.round(s),"aria-valuemin":0,"aria-valuemax":100,children:[c.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",stroke:"var(--interactive-border)",strokeWidth:n}),c.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",stroke:i,strokeWidth:n,strokeLinecap:"round",strokeDasharray:l,strokeDashoffset:l*(1-s/100),className:"transition-[stroke-dashoffset,stroke] duration-300"})]})},hX=()=>{const e=re(n=>n.uiFont),t=re(n=>n.monoFont);return{uiFont:e,monoFont:t}},$Q=p.memo(function({visible:t}){const[n,r]=p.useState(!1);if(H.useEffect(()=>{if(!t)return;let o=!1;dr("desktop_get_current_window_state").then(a=>{o||r(!!a?.maximized)}).catch(()=>{});const i=a=>{const l=a.detail;r(!!l?.maximized)};return window.addEventListener("pichamber:window-maximized-changed",i),()=>{o=!0,window.removeEventListener("pichamber:window-maximized-changed",i)}},[t]),!t)return null;const s="app-region-no-drag inline-flex h-12 w-11 items-center justify-center text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary";return c.jsxs("div",{className:"app-region-no-drag ml-1 flex h-12 shrink-0 items-center","aria-label":"Window controls",children:[c.jsx("button",{type:"button",className:s,onClick:()=>{dr("desktop_minimize_current_window")},title:"Minimize window","aria-label":"Minimize window",children:c.jsx(V,{name:"subtract",className:"h-4 w-4"})}),c.jsx("button",{type:"button",className:s,onClick:()=>{dr("desktop_toggle_current_window_maximized").then(o=>r(!!o?.maximized)).catch(()=>{})},title:n?"Restore window":"Maximize window","aria-label":n?"Restore window":"Maximize window",children:c.jsx(V,{name:n?"fullscreen-exit":"checkbox-blank",className:"h-3.5 w-3.5"})}),c.jsx("button",{type:"button",className:R(s,"hover:bg-status-error hover:text-status-error-foreground"),onClick:()=>{dr("desktop_close_current_window")},title:"Close window","aria-label":"Close window",children:c.jsx(V,{name:"close",className:"h-4 w-4"})})]})}),E5=new Set,Ph=new Map,pX=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace("%40","@").replace("%2F","/")}/files/${e.filePrefix}-latin-${t}-normal.woff2`,mX=(e,t)=>{const n=`${e.family}:${t}`;if(E5.has(n))return Promise.resolve();const r=Ph.get(n);if(r)return r;if(typeof document>"u"||typeof FontFace>"u"||!document.fonts)return Promise.resolve();const s=new FontFace(e.family,`url(${pX(e,t)}) format('woff2')`,{style:"normal",weight:String(t),display:"swap"});document.fonts.add(s);const o=s.load().then(()=>{E5.add(n)}).catch(i=>{document.fonts.delete(s),console.warn(`Failed to load font: ${e.family} ${t}`,i)}).finally(()=>{Ph.delete(n)});return Ph.set(n,o),o},H9=e=>e?Promise.all(e.weights.map(t=>mX(e,t))).then(()=>{}):Promise.resolve(),gX=e=>H9(Fh[e]?.source),yX=e=>H9(Bh[e]?.source);function zQ(){const{uiFont:e,monoFont:t}=hX();p.useEffect(()=>{if(typeof document>"u")return;const n=document.documentElement,r=Fh[e]?.stack??Fh[EC].stack,s=Bh[t]?.stack??Bh[_C].stack;gX(e),yX(t),n.style.setProperty("--font-sans",r),n.style.setProperty("--font-heading",r),n.style.setProperty("--font-family-sans",r),n.style.setProperty("--font-mono",s),n.style.setProperty("--font-family-mono",s),n.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=r)},[e,t])}export{wJ as $,Ua as A,be as B,h1 as C,HJ as D,bJ as E,GN as F,mu as G,iJ as H,V as I,WE as J,t1 as K,JJ as L,hX as M,gX as N,We as O,a1 as P,l4 as Q,eQ as R,sT as S,KX as T,GX as U,hp as V,ON as W,HE as X,zQ as Y,gy as Z,YX as _,ct as a,Fa as a$,AJ as a0,_J as a1,jJ as a2,TJ as a3,gA as a4,UJ as a5,SJ as a6,CJ as a7,lJ as a8,pu as a9,Ta as aA,vu as aB,Mj as aC,ln as aD,EJ as aE,WX as aF,qX as aG,xw as aH,Be as aI,$X as aJ,LJ as aK,RJ as aL,_N as aM,LN as aN,NN as aO,Xn as aP,Wa as aQ,wt as aR,St as aS,Ct as aT,QT as aU,eA as aV,tA as aW,nA as aX,BQ as aY,aQ as aZ,cQ as a_,rJ as aa,vJ as ab,sJ as ac,cJ as ad,aJ as ae,UX as af,Ma as ag,yr as ah,wE as ai,Km as aj,N_ as ak,P_ as al,yw as am,zX as an,tJ as ao,Ym as ap,Dr as aq,Ow as ar,On as as,D2 as at,l1 as au,gu as av,yu as aw,xu as ax,s1 as ay,Cu as az,Rm as b,$Q as b$,Ba as b0,Va as b1,Uo as b2,MD as b3,E1 as b4,Wo as b5,KR as b6,kD as b7,Lb as b8,e_ as b9,QX as bA,VJ as bB,$J as bC,Rj as bD,DO as bE,ku as bF,k$ as bG,zJ as bH,uQ as bI,b3 as bJ,VX as bK,TV as bL,HO as bM,Qt as bN,Ln as bO,u3 as bP,FX as bQ,Ga as bR,FO as bS,Fj as bT,vr as bU,pT as bV,za as bW,oJ as bX,TX as bY,W3 as bZ,AX as b_,fu as ba,Lt as bb,VQ as bc,MJ as bd,lN as be,kJ as bf,aN as bg,IJ as bh,cd as bi,vt as bj,ZI as bk,ep as bl,QN as bm,Bm as bn,HX as bo,Iw as bp,DX as bq,o1 as br,Lj as bs,Pj as bt,hV as bu,ur as bv,BJ as bw,ZL as bx,YL as by,No as bz,Ca as c,ZN as c$,Or as c0,zl as c1,dk as c2,Hr as c3,OX as c4,LX as c5,Ye as c6,lQ as c7,Vj as c8,Bj as c9,Im as cA,Xd as cB,Ht as cC,R6 as cD,gb as cE,iQ as cF,wH as cG,SH as cH,pR as cI,eG as cJ,i$ as cK,Wb as cL,RX as cM,I7 as cN,NJ as cO,Hw as cP,pr as cQ,AO as cR,z1 as cS,jw as cT,Ud as cU,Bd as cV,Hs as cW,qf as cX,V$ as cY,OJ as cZ,DJ as c_,Wj as ca,xy as cb,wy as cc,by as cd,Sy as ce,Cy as cf,rQ as cg,sQ as ch,fh as ci,oQ as cj,Rl as ck,Yw as cl,mJ as cm,MT as cn,H2 as co,F2 as cp,Df as cq,gJ as cr,yJ as cs,FQ as ct,DT as cu,aT as cv,iT as cw,hT as cx,pJ as cy,M1 as cz,OM as d,Hj as d$,KN as d0,eH as d1,d4 as d2,tH as d3,nH as d4,rH as d5,sH as d6,nQ as d7,GJ as d8,KJ as d9,VK as dA,eW as dB,NQ as dC,Su as dD,R3 as dE,L3 as dF,rP as dG,uJ as dH,fJ as dI,hJ as dJ,vU as dK,YJ as dL,_Q as dM,jQ as dN,bQ as dO,yQ as dP,vQ as dQ,xQ as dR,pQ as dS,gW as dT,CQ as dU,kQ as dV,MQ as dW,SQ as dX,tQ as dY,t4 as dZ,Oj as d_,WJ as da,ZJ as db,JO as dc,uX as dd,fX as de,Jm as df,To as dg,tL as dh,AR as di,wQ as dj,GU as dk,fx as dl,xJ as dm,$T as dn,UT as dp,UO as dq,Wt as dr,PJ as ds,Mu as dt,xU as du,uh as dv,Za as dw,Yq as dx,rg as dy,HQ as dz,JT as e,t3 as e0,NO as e1,LO as e2,RO as e3,BO as e4,VO as e5,JN as e6,TQ as e7,gQ as e8,EQ as e9,IQ as ea,Zn as eb,dJ as ec,AQ as ed,fQ as ee,hQ as ef,LQ as eg,yW as eh,jx as ei,MW as ej,RQ as ek,PQ as el,DQ as em,OQ as en,SW as eo,eq as ep,K7 as eq,mQ as er,I9 as es,QJ as et,NX as eu,BX as ev,nJ as ew,FJ as ex,qJ as ey,XJ as ez,ZX as f,qe as g,he as h,XX as i,BM as j,JX as k,Ns as l,dQ as m,M$ as n,ja as o,PX as p,C$ as q,n1 as r,Zj as s,Ce as t,tu as u,n3 as v,eJ as w,zo as x,Jn as y,qa as z};
|