@pi-chamber/web 0.8.2 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +22 -6
  2. package/bin/cli.js +16 -3
  3. package/bin/cli.test.js +62 -0
  4. package/bin/lib/DOCUMENTATION.md +6 -6
  5. package/bin/lib/cli-args.js +26 -7
  6. package/bin/lib/cli-lifecycle.js +3 -0
  7. package/bin/lib/cli-paths.js +6 -0
  8. package/bin/lib/cli-process.js +1 -0
  9. package/bin/lib/cli-tunnel-profiles.js +15 -10
  10. package/bin/lib/commands-connect-url.js +9 -1
  11. package/bin/lib/commands-lifecycle.js +14 -0
  12. package/bin/lib/commands-logs.js +24 -5
  13. package/bin/lib/commands-serve.js +176 -4
  14. package/bin/lib/commands-tunnel.js +35 -0
  15. package/bin/lib/commands-update.js +107 -39
  16. package/bin/lib/commands-update.test.js +97 -1
  17. package/dist/assets/{DiagramEditor-DerMrS6m.js → DiagramEditor-DoEOH0hY.js} +1 -1
  18. package/dist/assets/{DiagramView-DdipXAq8.js → DiagramView-y9Ystuhv.js} +1 -1
  19. package/dist/assets/DiffView-ScM4XoqZ.js +18 -0
  20. package/dist/assets/{FilesView-BXp0yc0j.js → FilesView-CjkhMFqJ.js} +3 -3
  21. package/dist/assets/GitView-Bqi6H8I-.js +8 -0
  22. package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
  23. package/dist/assets/{MarkdownRendererImpl-DNZQgQua.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
  24. package/dist/assets/{PatchDiff-B_NFEIX7.js → PatchDiff-ClnfJJ2J.js} +1 -1
  25. package/dist/assets/{SessionSwitcherContent-Q4P2TGBr.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
  26. package/dist/assets/{SessionSwitcherDropdown-Cgw2mQIO.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
  27. package/dist/assets/{SessionUnreadDot-BxtTkvHB.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
  28. package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
  29. package/dist/assets/{SettingsWindow-BEjHL1ET.js → SettingsWindow-Cy9tmnMg.js} +1 -1
  30. package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
  31. package/dist/assets/{ToolPartDiffPreview-ClV785zX.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
  32. package/dist/assets/{VirtualizedFileDiff-DrxkW2WQ.js → VirtualizedFileDiff-DJNcTQNp.js} +4 -4
  33. package/dist/assets/{collapsible-CR3-hRMy.js → collapsible-DxgVLhi9.js} +1 -1
  34. package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
  35. package/dist/assets/{contextFileOpenGuard-BRc5Z0g-.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
  36. package/dist/assets/gitStatusPredicates-CIFSGjJs.js +134 -0
  37. package/dist/assets/index-D2C3q2xD.js +8 -0
  38. package/dist/assets/index-DNoEeZ2U.css +1 -0
  39. package/dist/assets/{index-CMfiVUIr.js → index-DmNPBaSo.js} +1 -1
  40. package/dist/assets/{isDiffPlainText-MmBA1REG.js → isDiffPlainText-CrvpUauF.js} +1 -1
  41. package/dist/assets/{isFilePlainText-bQAPxqO9.js → isFilePlainText-CKvhS32g.js} +1 -1
  42. package/dist/assets/{main-zZrKd3hZ.js → main-BFv8slLp.js} +2 -2
  43. package/dist/assets/main-CjM7g4Gq.js +135 -0
  44. package/dist/assets/{markdownCore-B9jXCPry.js → markdownCore-DKrraAqT.js} +1 -1
  45. package/dist/assets/{miniChat-Di2oVS5o.js → miniChat-hQnLS5mt.js} +2 -2
  46. package/dist/assets/{mobile-VU_G_SgX.js → mobile-DuXOBGs_.js} +2 -2
  47. package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
  48. package/dist/assets/renderMobileApp-DofX2wjB.js +11 -0
  49. package/dist/assets/runtimeEndpointReset-BZeYg6eN.js +54 -0
  50. package/dist/assets/{runtimeSurface-CBaS2Ank.js → runtimeSurface-C7CBxDbh.js} +1 -1
  51. package/dist/assets/{useAppFontEffects-8ZU-TTIW.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
  52. package/dist/assets/{useFilesViewSearch-COow9O9x.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
  53. package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
  54. package/dist/assets/{useSwitcherItems-DOQqhi-e.js → useSwitcherItems-BEoW7LlC.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-language-data-B_0wrsbo.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
  56. package/dist/assets/{vendor-dnd-kit-core-CP8ck10N.js → vendor-dnd-kit-core-C9qcAm_1.js} +1 -1
  57. package/dist/assets/{vendor-dnd-kit-sortable-B-Icjoj4.js → vendor-dnd-kit-sortable-D8ozj8M-.js} +1 -1
  58. package/dist/assets/vendor-xterm-addon-fit-DX4qG4td.js +1 -0
  59. package/dist/assets/vendor-xterm-xterm-CrXqRur4.js +16 -0
  60. package/dist/assets/vendor-xterm-xterm-DDGTF8rc.css +1 -0
  61. package/dist/assets/{web-components-C9ENH49P.js → web-components-Dy-Tz_LJ.js} +3 -3
  62. package/dist/index.html +4 -4
  63. package/dist/mini-chat.html +3 -3
  64. package/dist/mobile.html +3 -3
  65. package/package.json +3 -4
  66. package/server/index.js +26 -7
  67. package/server/lib/client-auth/pairing.js +13 -2
  68. package/server/lib/client-auth/remote-clients.js +13 -2
  69. package/server/lib/fs/DOCUMENTATION.md +3 -1
  70. package/server/lib/fs/routes.test.js +74 -0
  71. package/server/lib/git/DOCUMENTATION.md +1 -1
  72. package/server/lib/git/identity-storage.js +10 -1
  73. package/server/lib/package-manager.js +1 -1
  74. package/server/lib/package-manager.test.js +11 -0
  75. package/server/lib/pi/archive-store.js +3 -2
  76. package/server/lib/pi/model-config-store.js +6 -2
  77. package/server/lib/pi/routes.js +11 -2
  78. package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
  79. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  80. package/server/lib/pi/session-daemon/session-daemon.js +226 -40
  81. package/server/lib/pi/session-daemon/session-daemon.test.js +207 -0
  82. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  83. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  84. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  85. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  86. package/server/lib/pi/session-folders-store.js +20 -2
  87. package/server/lib/pi/session-folders-store.test.js +17 -0
  88. package/server/lib/pi/settings-store.js +3 -2
  89. package/server/lib/pi/snippets-store.js +4 -1
  90. package/server/lib/pi/ui-settings-store.js +3 -2
  91. package/server/lib/server/cross-process-lock.js +112 -0
  92. package/server/lib/server/cross-process-lock.test.js +70 -0
  93. package/server/lib/server/server-profile.js +110 -0
  94. package/server/lib/server/server-profile.test.js +58 -0
  95. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  96. package/server/lib/server/tunnel-service.js +8 -1
  97. package/server/lib/stt/DOCUMENTATION.md +1 -1
  98. package/server/lib/stt/config-store.js +3 -2
  99. package/server/lib/terminal/DOCUMENTATION.md +3 -3
  100. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  101. package/server/lib/ui-auth/ui-auth.js +9 -2
  102. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  103. package/dist/assets/DiffView-Gh9wjthp.js +0 -18
  104. package/dist/assets/GitView-BmNCkkoC.js +0 -8
  105. package/dist/assets/JsonTreeView-CxXRXXzk.js +0 -1
  106. package/dist/assets/SettingsView-CFzxRzUq.js +0 -2
  107. package/dist/assets/ToolOutputDialog-C_7vJLEq.js +0 -8
  108. package/dist/assets/computeVirtualFileMetrics-D0mQcleY.js +0 -3
  109. package/dist/assets/gitStatusPredicates-DBGDfr1K.js +0 -134
  110. package/dist/assets/index-CzO3ooje.css +0 -1
  111. package/dist/assets/index-ivrh3jfy.js +0 -8
  112. package/dist/assets/main-BoVfUG73.js +0 -135
  113. package/dist/assets/renderElectronMiniChatApp-Bi1927c8.js +0 -2
  114. package/dist/assets/renderMobileApp-D9mxhuaM.js +0 -11
  115. package/dist/assets/runtimeEndpointReset-DImT35Ug.js +0 -54
  116. package/dist/assets/usePushVisibilityBeacon-zYd3ppNh.js +0 -10
  117. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
@@ -1,135 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-Gh9wjthp.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-ivrh3jfy.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-CzO3ooje.css","assets/useAppFontEffects-8ZU-TTIW.js","assets/vendor-base-ui-vkqQ2P9o.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-CBaS2Ank.js","assets/vendor-dnd-kit-core-CP8ck10N.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-B-Icjoj4.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-B_0wrsbo.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-DYppkHEk.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/gitStatusPredicates-DBGDfr1K.js","assets/web-components-C9ENH49P.js","assets/computeVirtualFileMetrics-D0mQcleY.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.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/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.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/VirtualizedFileDiff-DrxkW2WQ.js","assets/isDiffPlainText-MmBA1REG.js","assets/vendor-diff-C3JhlQdm.js","assets/runtimeEndpointReset-DImT35Ug.js","assets/SessionUnreadDot-BxtTkvHB.js","assets/permissionStore-iKN1K2_x.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/contextFileOpenGuard-BRc5Z0g-.js","assets/FilesView-BXp0yc0j.js","assets/DiagramEditor-DerMrS6m.js","assets/vendor-react-drawio-BYDptOsj.js","assets/useFilesViewSearch-COow9O9x.js","assets/JsonTreeView-CxXRXXzk.js","assets/Virtualizer-BSHVMKgK.js","assets/isFilePlainText-bQAPxqO9.js","assets/vendor-codemirror-search-BV44140v.js","assets/vendor-replit-codemirror-vim-CGHHNQxC.js","assets/GitView-BmNCkkoC.js","assets/collapsible-CR3-hRMy.js","assets/DiagramView-DdipXAq8.js","assets/SettingsView-CFzxRzUq.js","assets/vendor-qrcode-B0KNSajT.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/SettingsWindow-BEjHL1ET.js"])))=>i.map(i=>d[i]);
2
- import{R as s,j as e,r as Ce,e as _n}from"./vendor-react-B5Z1Mdn3.js";import"./vendor-katex-CNckGUMB.js";import{u as Y,c as ge,r as tt,j as Zt,J as An,H as en,U as tn,w as In,G as Ln,O as On,W as Ee,P as $n,Q as Wn,L as Te,M as Fn,X as Bn,Y as zn,Z as Et,_ as Ve,f as Un,d as Hn,l as Vn,b as Kn,A as Xn,$ as nn,m as rn,a0 as Yn,a1 as Gn,a2 as qn,a3 as Jn,s as Qn,p as sn,o as Zn}from"./index-ivrh3jfy.js";import{_ as Re}from"./vendor-vite-runtime-DD1OZmLC.js";import{f as er,C as tr,a as nr,b as rr,c as sr,d as or,S as ar,T as on,D as ir,g as lr,h as cr,i as dr,j as ur,k as hr,l as pr,H as Rt,m as Tt,A as Dt,n as Mt,o as mr,r as fr,p as gr,F as xr,W as wr}from"./runtimeEndpointReset-DImT35Ug.js";import{$ as Ne,bv as st,k as Se,t as ve,bw as yr,U as le,I as B,aw as nt,bx as an,b6 as pt,D as br,E as Oe,F as $e,a as vr,G as We,b as jr,af as mt,bm as Sr,bn as Cr,j as ft,aB as Ge,bb as ln,bg as _t,ao as kr,aQ as gt,aR as xt,bi as wt,bj as yt,bk as bt,bl as Nr,aN as Pr,br as Er,N as Rr,bd as cn,L as Ie,by as Ke,bz as dn,bA as un,aT as Tr,bB as ut,bC as Dr,bD as Me,ba as hn,bE as Mr,bF as vt,bG as _r,b9 as jt,Q as pn,Y as Ar,bH as Ir,bI as Lr,bJ as At,u as Or,d as $r,e as Wr,bK as Fr,c as It,s as Br,r as ot,be as zr,bL as Ur,f as Hr,bM as Vr,bN as Kr,bO as Xr,bP as Yr,bQ as Ue,bR as He,bS as Gr,a1 as qr,a0 as Jr,a3 as Qr,_ as Zr,bT as es,a2 as ts,a4 as ns,a5 as rs,a8 as ss,a9 as os}from"./useAppFontEffects-8ZU-TTIW.js";import{v as mn,g as fn}from"./contextFileOpenGuard-BRc5Z0g-.js";import{g as gn,l as as,e as is,f as ls,h as cs,u as ds}from"./useFilesViewSearch-COow9O9x.js";import{g as xn}from"./SessionUnreadDot-BxtTkvHB.js";import{c as us,d as Lt,T as hs,M as ps,D as ms,e as fs}from"./vendor-dnd-kit-core-CP8ck10N.js";import{a as gs,S as xs,v as ws,u as ys}from"./vendor-dnd-kit-sortable-B-Icjoj4.js";import{C as bs}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import{u as Ot,a as qe,m as $t}from"./vendor-framer-motion-CfplGuM0.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./permissionStore-iKN1K2_x.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-CBaS2Ank.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-B_0wrsbo.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-DYppkHEk.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";const Wt=280,Ft=280,Bt=500,vs=({isOpen:t,isMobile:n,children:r,className:a,topBar:o})=>{const f=Y(w=>w.sidebarWidth),x=Y(w=>w.setSidebarWidth),[d,h]=s.useState(!1),m=s.useRef(0),y=s.useRef(f||Wt),u=s.useRef(null),l=s.useRef(null),R=s.useRef(null),c=s.useCallback(w=>Math.min(Bt,Math.max(Ft,w)),[]),j=s.useCallback(w=>{const C=R.current;C&&(C.style.width=`${w}px`,C.style.minWidth=`${w}px`,C.style.maxWidth=`${w}px`,C.style.setProperty("--oc-left-sidebar-width",`${w}px`))},[]);s.useEffect(()=>{n&&d&&h(!1)},[n,d]),s.useEffect(()=>{d||(u.current=null,l.current=null)},[d]);const v=er(t);if(n)return null;const P=Math.min(Bt,Math.max(Ft,f||Wt)),E=v.layoutVisible?P:0,I=w=>{if(t){try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}l.current=w.pointerId,h(!0),m.current=w.clientX,y.current=E,u.current=E,j(E),w.preventDefault()}},J=w=>{if(n||!d||l.current!==w.pointerId)return;const C=w.clientX-m.current,U=c(y.current+C);u.current!==U&&(u.current=U,j(U))},Q=w=>{if(l.current!==w.pointerId||n)return;try{w.currentTarget.releasePointerCapture(w.pointerId)}catch{}const C=c(u.current??E);l.current=null,u.current=null,h(!1),x(C)},Z=d?u.current??E:E,F=d?Z:E;return e.jsxs("aside",{ref:R,className:ge("relative flex h-full overflow-hidden motion-reduce:transition-none","bg-sidebar",a),style:{width:`${F}px`,minWidth:`${F}px`,maxWidth:`${F}px`,"--oc-left-sidebar-width":`${d?Z:P}px`,overflowX:"clip",transform:d||v.slidIn?"translateX(0)":"translateX(-100%)",transition:d?"none":v.transition},"aria-hidden":!t||F===0,children:[t&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-30 shadow-[inset_-2px_0_10px_-2px_rgb(0_0_0_/_0.06)]","aria-hidden":"true"}),t&&e.jsx("div",{className:ge("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",d&&"bg-[var(--interactive-border)]"),onPointerDown:I,onPointerMove:J,onPointerUp:Q,onPointerCancel:Q,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:ge("relative z-10 flex h-full shrink-0 flex-col",d&&"pointer-events-none",!t&&"pointer-events-none select-none"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[o,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(Ne,{children:r})})]})]})},js=t=>{if(!t||typeof t!="object")return!1;const n=t;return typeof n.x=="number"&&typeof n.y=="number"},zt=t=>!t||typeof t!="object"?!1:Object.values(t).every(n=>typeof n=="string"),Be=t=>{if(!t||typeof t!="object")return!1;const n=t,r=n.bounds;return typeof n.tag=="string"&&typeof n.text=="string"&&typeof n.selector=="string"&&typeof n.path=="string"&&!!r&&typeof r?.x=="number"&&typeof r?.y=="number"&&typeof r?.width=="number"&&typeof r?.height=="number"&&js(n.center)&&zt(n.attributes)&&zt(n.computedStyle)&&Array.isArray(n.ancestry)},St=({pageUrl:t,viewport:n,devicePixelRatio:r,target:a,screenshotAttached:o,intro:f})=>{const x=a.text.trim(),d=Object.entries(a.attributes).map(([R,c])=>`${R}="${c}"`).join(" "),h=a.computedStyle,m=a.bounds,y=a.center,u=f.replace(/[.:]+$/g,""),l=a.ancestry.map(R=>R.selectorPart).join(" > ");return[`${u}:`,`Page: ${t||"preview"}`,`Viewport: ${n.width}x${n.height}, DPR ${r}`,`Screenshot: ${o?"attached":"not attached"}`,`Element: ${a.tag}`,x?`Text: ${x}`:null,`- Selector: ${a.selector}`,`- Path: ${a.path}`,l?`- Ancestry: ${l}`:null,d?`- Attributes: ${d}`:null,`- Bounds: x=${Math.round(m.x)}, y=${Math.round(m.y)}, width=${Math.round(m.width)}, height=${Math.round(m.height)}`,`- Center: x=${Math.round(y.x)}, y=${Math.round(y.y)}`,`Styles: display=${h.display}; position=${h.position}; font=${h.fontWeight} ${h.fontSize} / ${h.lineHeight} ${h.fontFamily}; color=${h.color}; background=${h.backgroundColor}; z-index=${h.zIndex}`].filter(R=>typeof R=="string").join(`
3
- `)},Pe=new Map,Ss=3e4,Ct=t=>{const n=Pe.get(t);return n?n.expiresAt-Date.now()<=Ss?(Pe.delete(t),null):n:null},Cs=t=>{try{return new URL(t).origin}catch{return t}},ze="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",at=new Map;function wn(t){const n="#ffffff",r=t.defaultView??window;try{const a=t.body?r.getComputedStyle(t.body).backgroundColor:"";if(a&&a!=="rgba(0, 0, 0, 0)"&&a!=="transparent")return a;const o=r.getComputedStyle(t.documentElement).backgroundColor;if(o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent")return o}catch{}return n}const yn=t=>new Promise((n,r)=>{const a=new FileReader;a.onloadend=()=>n(typeof a.result=="string"?a.result:ze),a.onerror=()=>r(a.error??new Error("Failed to read image blob")),a.readAsDataURL(t)}),ks=async(t,n=.82)=>{const r=await new Promise(a=>t.toBlob(a,"image/jpeg",n));return r&&(await yn(r)).split(",",2)[1]||""},it=async(t,n)=>{try{const r=await fetch(t,{credentials:n});return r.ok?await yn(await r.blob()):null}catch{return null}},Ns=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const n=t.origin,r=Ct(n);if(r)return`${r.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const a=at.get(n),o=a??(async()=>{try{const x=await tt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!x.ok)return Pe.delete(n),null;const d=await x.json(),h=typeof d.proxyBasePath=="string"?d.proxyBasePath:"",m=typeof d.expiresAt=="number"?d.expiresAt:0;if(!h)return Pe.delete(n),null;const y={proxyBasePath:h,expiresAt:m};return Pe.set(n,y),y}catch{return Pe.delete(n),null}finally{at.delete(n)}})();a||at.set(n,o);const f=await o;return f?`${f.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},bn=async(t,n)=>{if(!t||t.startsWith("data:"))return t;try{const r=new URL(t,n.baseURI);if(r.origin===window.location.origin||r.protocol!=="http:"&&r.protocol!=="https:")return await it(r.toString(),"include")??ze;const a=await Ns(r),o=a?await it(a,"include"):null;return o||(await it(r.toString(),"omit")??ze)}catch{return ze}},Ps=async(t,n)=>{if(!t||t==="none"||!t.includes("url("))return t;const r=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let a=t;for(const o of r){const f=o[2]||"";if(!f||f.startsWith("data:"))continue;const x=await bn(f,n);a=a.replace(o[0],`url("${x}")`)}return a},Ut=t=>t.complete?Promise.resolve():new Promise(n=>{t.addEventListener("load",()=>n(),{once:!0}),t.addEventListener("error",()=>n(),{once:!0})}),vn=t=>{const n=t.style.cssText;return()=>{t.style.cssText=n}},Es=t=>{const n=Number.parseFloat(t.lineHeight);if(Number.isFinite(n)&&n>0)return n;const r=Number.parseFloat(t.fontSize);return Number.isFinite(r)&&r>0?r*1.2:16},Rs=(t,n,r)=>{const a=[],o=t.defaultView??window,x=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const d of x){const h=d.textContent?.replace(/\s+/g," ").trim()??"";if(!h||!h.includes(" "))continue;const m=d.getBoundingClientRect();if(m.width<=0||m.height<=0||m.right<0||m.bottom<0||m.left>n||m.top>r)continue;const y=o.getComputedStyle(d);if(y.display==="none"||y.visibility==="hidden"||Number(y.opacity)===0)continue;const u=y.getPropertyValue("text-wrap"),l=y.getPropertyValue("text-wrap-mode"),R=y.whiteSpace.includes("nowrap")||u==="nowrap"||l==="nowrap",c=m.height<=Es(y)*1.7;!R&&(!c||m.width>n*.72)||(a.push(vn(d)),d.style.whiteSpace="nowrap",d.style.overflowWrap="normal",d.style.wordBreak="normal",d.style.setProperty("text-wrap","nowrap"),d.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let d=a.length-1;d>=0;d-=1)a[d]?.()}},Ts=(t,n,r,a)=>{const o=[],f=t.defaultView??window,x=f.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,d=f.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,h=Array.from(t.querySelectorAll("*")).filter(m=>{const y=f.getComputedStyle(m);if(y.position!=="fixed"||y.display==="none"||y.visibility==="hidden"||Number(y.opacity)===0)return!1;const u=m.getBoundingClientRect();return u.width>0&&u.height>0&&u.right>=0&&u.bottom>=0&&u.left<=n&&u.top<=r}).filter((m,y,u)=>!u.some((l,R)=>R<y&&l.contains(m)));for(const m of h){const y=m.getBoundingClientRect(),u=f.getComputedStyle(m),l=Math.ceil(y.width)+8,R=Math.ceil(y.height)+2;a?.add(m),o.push(vn(m)),m.style.position="absolute",m.style.top=`${y.top+d}px`,m.style.left=`${y.left+x}px`,m.style.right="auto",m.style.bottom="auto",m.style.width=`${l}px`,m.style.minWidth=`${l}px`,m.style.height=`${R}px`,m.style.minHeight=`${R}px`,m.style.margin="0",m.style.boxSizing="border-box",m.style.transform="none",u.zIndex!=="auto"&&(m.style.zIndex=u.zIndex)}return()=>{for(let m=o.length-1;m>=0;m-=1)o[m]?.()}},jn=async(t,n,r,a={})=>{const o=[],f=t.defaultView??window,x=u=>{if(u===t.documentElement||u===t.body)return!0;try{const l=u.getBoundingClientRect();return l.width>0&&l.height>0&&l.right>=0&&l.bottom>=0&&l.left<=n&&l.top<=r}catch{return!1}};if(a.applyLayoutWorkarounds){const u=new WeakSet;o.push(Ts(t,n,r,u)),o.push(Rs(t,n,r))}const d=new Map;for(const u of Array.from(t.images))d.set(u,u.currentSrc||u.src||u.getAttribute("src")||"");const h=Array.from(t.querySelectorAll("picture"));for(const u of h){const l=Array.from(u.querySelectorAll("source"));if(l.length===0)continue;const R=l.map(c=>({source:c,srcset:c.getAttribute("srcset"),sizes:c.getAttribute("sizes")}));o.push(()=>{for(const c of R)c.srcset===null?c.source.removeAttribute("srcset"):c.source.setAttribute("srcset",c.srcset),c.sizes===null?c.source.removeAttribute("sizes"):c.source.setAttribute("sizes",c.sizes)});for(const c of l)c.removeAttribute("srcset"),c.removeAttribute("sizes")}const m=Array.from(t.images).filter(u=>x(u));await Promise.all(m.map(async u=>{const l=d.get(u)||u.currentSrc||u.src||u.getAttribute("src")||"";if(!l)return;await Ut(u);const R=await bn(l,t),c={src:u.getAttribute("src"),srcset:u.getAttribute("srcset"),sizes:u.getAttribute("sizes")};o.push(()=>{c.src===null?u.removeAttribute("src"):u.setAttribute("src",c.src),c.srcset===null?u.removeAttribute("srcset"):u.setAttribute("srcset",c.srcset),c.sizes===null?u.removeAttribute("sizes"):u.setAttribute("sizes",c.sizes)}),u.removeAttribute("srcset"),u.removeAttribute("sizes"),u.setAttribute("src",R||ze),await Ut(u)}));const y=Array.from(t.querySelectorAll("*")).filter(x);return await Promise.all(y.map(async u=>{const l=f.getComputedStyle(u).backgroundImage;if(!l||l==="none"||!l.includes("url("))return;const R=await Ps(l,t);if(R===l)return;const c=u.style.backgroundImage;o.push(()=>{u.style.backgroundImage=c}),u.style.backgroundImage=R})),()=>{for(let u=o.length-1;u>=0;u-=1)try{o[u]?.()}catch{}}},Ds=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},Qe=(...t)=>{Ds()&&console.info("[preview-capture]",...t)},Sn=(t,n=8)=>{const r=[];try{const a=t.querySelectorAll("*");for(const o of a){const f=o.scrollTop||0,x=o.scrollLeft||0;if(f<=0&&x<=0)continue;const d=o.tagName.toLowerCase(),h=o.id?`#${o.id}`:"",m=typeof o.className=="string"&&o.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(r.push({selector:`${d}${h}${m}`,scrollTop:f,scrollLeft:x,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),r.length>=n)break}}catch{}return r},Xe="data-oc-fixed-pin",Ms=(t,n,r)=>{if(n<=0&&r<=0)return()=>{};const a=t.defaultView;if(!a)return()=>{};const o=[],f=[];try{for(const x of t.querySelectorAll("*")){if(a.getComputedStyle(x).position!=="fixed")continue;const d=x.getBoundingClientRect();if(!(d.width>0&&d.height>0))continue;x.setAttribute(Xe,JSON.stringify({top:d.top+r,left:d.left+n,width:d.width,height:d.height})),o.push(x);const h=x.tagName.toLowerCase(),m=typeof x.className=="string"&&x.className?`.${x.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";f.push({selector:`${h}${m}`,top:Math.round(d.top),left:Math.round(d.left),width:Math.round(d.width),height:Math.round(d.height)})}}catch{}return Qe("tagged fixed elements",f),()=>{for(const x of o)try{x.removeAttribute(Xe)}catch{}}},_s={name:"oc-fixed-pin",afterClone(t){const n=t?.clone;if(!(!n||typeof n.querySelectorAll!="function"))for(const r of n.querySelectorAll(`[${Xe}]`)){let a;try{a=JSON.parse(r.getAttribute(Xe)||"")}catch{continue}r.style.setProperty("position","absolute","important"),r.style.setProperty("top",`${a.top}px`,"important"),r.style.setProperty("left",`${a.left}px`,"important"),r.style.setProperty("right","auto","important"),r.style.setProperty("bottom","auto","important"),r.style.setProperty("width",`${a.width}px`,"important"),r.style.setProperty("height",`${a.height}px`,"important"),r.removeAttribute(Xe)}}},Fe="data-oc-scroll-pin",As=t=>{const n=[],r=Sn(t,64);try{const f=t.documentElement,x=t.body;for(const d of t.querySelectorAll("*")){const h=d.scrollTop||0,m=d.scrollLeft||0;if(h<=0&&m<=0)continue;const y=d!==f&&d!==x;y&&d.setAttribute(Fe,JSON.stringify({top:h,left:m})),n.push({el:d,top:h,left:m,tagged:y})}}catch{}return{reapply:()=>{for(const f of n)try{f.el.scrollHeight,f.el.scrollTop!==f.top&&(f.el.scrollTop=f.top),f.el.scrollLeft!==f.left&&(f.el.scrollLeft=f.left)}catch{}},cleanup:()=>{for(const f of n)if(f.tagged)try{f.el.removeAttribute(Fe)}catch{}},snapshot:r}},Is={name:"oc-nested-scroll",afterClone(t){const n=t?.clone;if(!n||typeof n.querySelectorAll!="function")return;const r=n.ownerDocument;if(r)for(const a of n.querySelectorAll(`[${Fe}]`)){let o;try{o=JSON.parse(a.getAttribute(Fe)||"")}catch{a.removeAttribute(Fe);continue}const f=`translate(${-o.left}px, ${-o.top}px)`,x=a.children.length===1&&a.firstElementChild instanceof HTMLElement&&a.firstElementChild.style.willChange==="transform"?a.firstElementChild:null;if(x)x.style.transform=f;else{a.style.overflow="hidden";const d=r.createElement("div");for(d.style.transform=f,d.style.willChange="transform",d.style.display="inline-block",d.style.width="100%";a.firstChild;)d.appendChild(a.firstChild);a.appendChild(d)}a.removeAttribute(Fe)}}},Cn=async(t,n)=>{if(typeof window<"u")try{const r=t.getBoundingClientRect(),a=await Zt("desktop_capture_page_rect",{x:r.left,y:r.top,width:r.width,height:r.height});if(!a)throw new Error("Desktop screenshot capture is not available");const o=new Image;await new Promise((c,j)=>{o.onload=()=>c(),o.onerror=()=>j(new Error("Failed to load desktop preview screenshot")),o.src=`data:${a.mime};base64,${a.base64}`});const f=Math.max(1,o.naturalWidth||a.width||Math.floor(r.width)),x=Math.max(1,o.naturalHeight||a.height||Math.floor(r.height)),h=Math.min(1,1200/f),m=document.createElement("canvas");m.width=Math.floor(f*h),m.height=Math.floor(x*h);const y=m.getContext("2d");if(!y)return null;y.scale(h,h),y.drawImage(o,0,0,f,x);const u=f/Math.max(1,r.width),l=x/Math.max(1,r.height);y.fillStyle="rgba(37, 99, 235, 0.28)",y.strokeStyle="rgb(37, 99, 235)",y.lineWidth=Math.max(2,2*u),y.fillRect(n.bounds.x*u,n.bounds.y*l,n.bounds.width*u,n.bounds.height*l),y.strokeRect(n.bounds.x*u,n.bounds.y*l,n.bounds.width*u,n.bounds.height*l);const R=await new Promise(c=>m.toBlob(c,"image/jpeg",.82));return R?new File([R],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(r){return console.warn("[preview] failed to capture annotation screenshot:",r),null}return await Os(t,n)},kt=async(t,n,r,a,o,f)=>{if(!t)return null;try{const x=new Image;await new Promise((v,P)=>{x.onload=()=>v(),x.onerror=()=>P(new Error("Failed to load desktop browser screenshot")),x.src=`data:image/jpeg;base64,${t}`});const d=Math.max(1,x.naturalWidth||n),h=Math.max(1,x.naturalHeight||r),y=Math.min(1,1200/d),u=document.createElement("canvas");u.width=Math.floor(d*y),u.height=Math.floor(h*y);const l=u.getContext("2d");if(!l)return null;l.scale(y,y),l.drawImage(x,0,0,d,h);const R=d/Math.max(1,a||d),c=h/Math.max(1,o||h);l.fillStyle="rgba(37, 99, 235, 0.14)",l.strokeStyle="rgb(37, 99, 235)",l.lineWidth=Math.max(2,2*R),l.fillRect(f.bounds.x*R,f.bounds.y*c,f.bounds.width*R,f.bounds.height*c),l.strokeRect(f.bounds.x*R,f.bounds.y*c,f.bounds.width*R,f.bounds.height*c);const j=await new Promise(v=>u.toBlob(v,"image/jpeg",.82));return j?new File([j],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}};async function Ls(t,n){try{const r=t.contentWindow,a=t.contentDocument??r?.document,o=a?.documentElement;if(!r||!a||!o)return null;const f=t.getBoundingClientRect(),x=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||f.width)),d=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||f.height)),h=a.body,m=a.scrollingElement instanceof HTMLElement?a.scrollingElement:null,y=r.scrollX||0,u=r.scrollY||0,l=r.pageXOffset||0,R=r.pageYOffset||0,c=r.visualViewport?.pageLeft||r.visualViewport?.offsetLeft||0,j=r.visualViewport?.pageTop||r.visualViewport?.offsetTop||0,v=o.scrollLeft||0,P=o.scrollTop||0,E=h?.scrollLeft||0,I=h?.scrollTop||0,J=m?.scrollLeft||0,Q=m?.scrollTop||0,Z=Math.max(y,l,c,v,E,J),F=Math.max(u,R,j,P,I,Q);Qe("scroll sources",{windowScrollX:y,windowScrollY:u,pageScrollX:l,pageScrollY:R,visualViewportScrollX:c,visualViewportScrollY:j,rootScrollX:v,rootScrollY:P,bodyScrollX:E,bodyScrollY:I,scrollingElementScrollX:J,scrollingElementScrollY:Q,scrollingElementTag:m?.tagName?.toLowerCase()??null,resolvedScrollX:Z,resolvedScrollY:F,nestedScrolledElements:Sn(a)});const w=Math.max(x,o.scrollWidth||0,h?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),C=Math.max(d,o.scrollHeight||0,h?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),U=Math.min(2,Math.max(1,window.devicePixelRatio||1)),G=o.style.scrollBehavior,L=h?.style.scrollBehavior??"";o.style.scrollBehavior="auto",h&&(h.style.scrollBehavior="auto");const O=As(a);Qe("nested scroll snapshot",O.snapshot);let q=()=>{},N=()=>{};try{await a.fonts?.ready.catch(()=>{}),q=await jn(a,x,d,{applyLayoutWorkarounds:!1}),r.scrollTo(Z,F),N=Ms(a,Z,F),O.reapply();const{snapdom:H}=await Re(async()=>{const{snapdom:g}=await import("./vendor-zumer-snapdom-Btyu_Xi2.js");return{snapdom:g}},[]),k={backgroundColor:wn(a),cache:"disabled",dpr:U,embedFonts:!0,fast:!1,height:C,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[_s,Is],quality:.82,width:w},V=await(await H(o,k)).toCanvas();if(!V.width||!V.height)return null;const A=V.width/Math.max(1,w),X=V.height/Math.max(1,C),se=Math.min(V.width,Math.max(1,Math.round(x*A))),ie=Math.min(V.height,Math.max(1,Math.round(d*X))),he=Math.max(0,V.width-se),ye=Math.max(0,V.height-ie),pe=Math.min(he,Math.max(0,Math.round(Z*A))),xe=Math.min(ye,Math.max(0,Math.round(F*X)));Qe("capture geometry",{viewportWidth:x,viewportHeight:d,captureWidth:w,captureHeight:C,canvasWidth:V.width,canvasHeight:V.height,xScale:A,yScale:X,sourceX:pe,sourceY:xe,sourceWidth:se,sourceHeight:ie});const ce=a.createElement("canvas");ce.width=se,ce.height=ie;const M=ce.getContext("2d");if(!M)return null;M.drawImage(V,pe,xe,se,ie,0,0,se,ie);const $=await ks(ce,.82);return $?await kt($,x,d,x,d,n):null}finally{N(),O.cleanup(),q(),r.scrollTo(Z,F),O.reapply(),o.style.scrollBehavior=G,h&&(h.style.scrollBehavior=L)}}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",r),null}}async function Os(t,n){const r=await Ls(t,n);if(r)return r;try{const a=t.contentWindow,o=t.contentDocument??a?.document,f=o?.documentElement;if(!a||!o||!f)return null;const x=t.getBoundingClientRect(),d=Math.max(1,Math.ceil(a.innerWidth||t.clientWidth||x.width)),h=Math.max(1,Math.ceil(a.innerHeight||t.clientHeight||x.height)),m=a.scrollX||o.documentElement.scrollLeft||o.body?.scrollLeft||0,y=a.scrollY||o.documentElement.scrollTop||o.body?.scrollTop||0,u=o.body,l=Math.max(h,f.scrollHeight||0,u?.scrollHeight||0),R=Math.min(2,Math.max(1,window.devicePixelRatio||1)),c=f.style.scrollBehavior,j=u?.style.scrollBehavior??"";f.style.scrollBehavior="auto",u&&(u.style.scrollBehavior="auto");let v="",P=()=>{};try{await o.fonts?.ready.catch(()=>{}),P=await jn(o,d,h,{applyLayoutWorkarounds:!0}),a.scrollTo(m,y);const{getFontEmbedCSS:I,toJpeg:J}=await Re(async()=>{const{getFontEmbedCSS:Z,toJpeg:F}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:Z,toJpeg:F}},[]),Q=await I(f).catch(()=>"");v=await J(f,{quality:.82,pixelRatio:R,width:d,height:h,backgroundColor:wn(o),imagePlaceholder:ze,fontEmbedCSS:Q||void 0,style:{transform:`translate(${-m}px, ${-y}px)`,transformOrigin:"top left",minWidth:`${d}px`,minHeight:`${l}px`},cacheBust:!0})}finally{P(),a.scrollTo(m,y),f.style.scrollBehavior=c,u&&(u.style.scrollBehavior=j)}const E=v.split(",",2)[1]||"";return E?await kt(E,d,h,d,h,n):null}catch(a){return console.warn("[preview] failed to capture iframe DOM screenshot:",a),null}}const Ht=200,$s=(t,n)=>n==="all"?!0:n==="errors"?t.level==="error"||t.level==="runtime"||t.level==="resource":n==="warnings"?t.level==="warn":t.level==="log"||t.level==="info"||t.level==="debug",rt=t=>{const n=st.getState();n.setPendingSyntheticParts([...n.pendingSyntheticParts??[],{text:t,synthetic:!0}])},kn=async t=>{const n=await t.json().catch(()=>({}));if(!t.ok)return{ok:!1,message:typeof n.error=="string"?n.error:`HTTP ${t.status}`};const r=typeof n.proxyBasePath=="string"?n.proxyBasePath:"",a=typeof n.previewToken=="string"?n.previewToken:"";return!r||!a?{ok:!1,message:"Could not start preview proxy."}:{ok:!0,target:{proxyBasePath:r,previewToken:a,expiresAt:typeof n.expiresAt=="number"?n.expiresAt:0}}},Nn=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Vt=(t,n,r)=>{t.postMessage(r,Nn(n))},Ws=t=>{if(!t)return t;try{const n=new URL(t);return n.searchParams.delete("oc_preview_token"),n.searchParams.delete("oc_client_token"),n.searchParams.delete("oc_url_token"),n.toString()}catch{return t}},Kt=t=>{if(!t)return t;try{const n=new URL(t);return n.searchParams.delete("ocPreview"),n.searchParams.delete("oc_preview_token"),n.searchParams.delete("oc_client_token"),n.searchParams.delete("oc_url_token"),n.toString()}catch{return t}};function Pn(t){const[n,r]=s.useState("");return s.useEffect(()=>{if(!t){r("");return}let a=!1;return r(""),An(en()).then(o=>{!a&&o&&r(t)}).catch(()=>{}),()=>{a=!0}},[t]),n}const En=`new Promise((resolve) => {
4
- const existing = document.getElementById('__pichamber_desktop_browser_overlay');
5
- if (existing) existing.remove();
6
- if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
7
- try { window.__pichamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
8
- }
9
- const overlay = document.createElement('div');
10
- overlay.id = '__pichamber_desktop_browser_overlay';
11
- overlay.style.cssText = 'position:fixed;z-index:2147483647;pointer-events:none;border:2px solid #60a5fa;background:rgba(96,165,250,.24);border-radius:3px;display:none;box-sizing:border-box;';
12
- document.documentElement.appendChild(overlay);
13
- const cssEscape = (value) => {
14
- try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
15
- };
16
- const selectorPart = (element) => {
17
- const tag = element.tagName.toLowerCase();
18
- if (element.id) return tag + '#' + cssEscape(element.id);
19
- const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
20
- return tag + className;
21
- };
22
- const metadata = (element) => {
23
- const rect = element.getBoundingClientRect();
24
- const style = getComputedStyle(element);
25
- const ancestry = [];
26
- let current = element;
27
- while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
28
- ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
29
- current = current.parentElement;
30
- }
31
- const attrs = {};
32
- for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
33
- const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
34
- return {
35
- frame: 'top',
36
- tag: element.tagName.toLowerCase(),
37
- text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
38
- selector: element.id ? '#' + cssEscape(element.id) : path,
39
- path,
40
- bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
41
- center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
42
- attributes: attrs,
43
- computedStyle: { display: style.display, position: style.position, fontWeight: style.fontWeight, fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily, color: style.color, backgroundColor: style.backgroundColor, zIndex: style.zIndex },
44
- ancestry,
45
- };
46
- };
47
- const move = (event) => {
48
- const element = document.elementFromPoint(event.clientX, event.clientY);
49
- if (!element || element === overlay || element === document.documentElement || element === document.body) return;
50
- const rect = element.getBoundingClientRect();
51
- overlay.style.display = 'block';
52
- overlay.style.left = rect.left + 'px';
53
- overlay.style.top = rect.top + 'px';
54
- overlay.style.width = rect.width + 'px';
55
- overlay.style.height = rect.height + 'px';
56
- };
57
- const cleanup = () => {
58
- window.removeEventListener('mousemove', move, true);
59
- window.removeEventListener('click', click, true);
60
- window.removeEventListener('keydown', keydown, true);
61
- if (window.__pichamberDesktopBrowserCancelInspect === cancel) {
62
- delete window.__pichamberDesktopBrowserCancelInspect;
63
- }
64
- };
65
- const cancel = () => {
66
- cleanup();
67
- overlay.remove();
68
- resolve(null);
69
- };
70
- const click = (event) => {
71
- event.preventDefault();
72
- event.stopPropagation();
73
- const element = document.elementFromPoint(event.clientX, event.clientY);
74
- const result = element ? metadata(element) : null;
75
- cleanup();
76
- overlay.remove();
77
- resolve(result);
78
- };
79
- const keydown = (event) => {
80
- if (event.key !== 'Escape') return;
81
- cancel();
82
- };
83
- window.__pichamberDesktopBrowserCancelInspect = cancel;
84
- window.addEventListener('mousemove', move, true);
85
- window.addEventListener('click', click, true);
86
- window.addEventListener('keydown', keydown, true);
87
- });`,Ze=`(() => {
88
- if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
89
- window.__pichamberDesktopBrowserCancelInspect();
90
- return;
91
- }
92
- const overlay = document.getElementById('__pichamber_desktop_browser_overlay');
93
- if (overlay) overlay.remove();
94
- })()`,Fs=`(() => {
95
- if (window.__pichamberSameWebviewNavigationInstalled) return;
96
- window.__pichamberSameWebviewNavigationInstalled = true;
97
-
98
- const navigate = (rawUrl) => {
99
- if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
100
- try {
101
- const url = new URL(rawUrl, window.location.href);
102
- if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
103
- window.location.assign(url.href);
104
- return true;
105
- } catch (_error) {
106
- return false;
107
- }
108
- };
109
-
110
- const originalOpen = window.open.bind(window);
111
- window.open = (url, target, features) => {
112
- if (navigate(url)) return null;
113
- return originalOpen(url, target, features);
114
- };
115
-
116
- document.addEventListener('click', (event) => {
117
- if (event.defaultPrevented) return;
118
- const target = event.target;
119
- if (!(target instanceof Element)) return;
120
- const anchor = target.closest('a[target="_blank"][href]');
121
- if (!(anchor instanceof HTMLAnchorElement)) return;
122
- if (!navigate(anchor.href)) return;
123
- event.preventDefault();
124
- event.stopPropagation();
125
- }, true);
126
- })()`,Ye=t=>{const n=t.trim();if(!n)return"about:blank";try{const r=new URL(n.includes("://")?n:`https://${n}`);return r.protocol!=="http:"&&r.protocol!=="https:"?"about:blank":r.toString()}catch{return"about:blank"}},Xt=async(t,n)=>{const r=t.contentWindow;if(!r)throw new Error("Iframe window is not available");const o=r.eval.call(r,n);return await Promise.resolve(o)},Bs=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,zs=({initialUrl:t,directory:n,tabID:r})=>{const a=s.useRef(null),o=Y(M=>M.setContextPanelTabTargetPath),f=Ye(t),x=f!=="about:blank"?f:"",[d,h]=s.useState(x),[m,y]=s.useState(x),[u,l]=s.useState(x),[R,c]=s.useState(()=>x?[x]:[]),[j,v]=s.useState(()=>x?0:-1),[P,E]=s.useReducer(M=>M+1,0),[I,J]=s.useState(!!x),[Q,Z]=s.useState(!1),[F,w]=s.useState(null),[C,U]=s.useState({status:"idle"}),G=Se(M=>M.currentSessionId),L=Se(M=>M.newSessionDraft?.open),O=st(M=>M.addAttachedFile),q=s.useCallback(M=>{!M||M==="about:blank"||!n||!r||o(n,r,M)},[n,r,o]),N=s.useCallback((M,$)=>{const g=Ye(M),D=g!=="about:blank"?g:"";y(D),h(D),$?.inFrame?J(!1):(l(D),J(!!D)),q(D),c(K=>{if(!D)return v(-1),[];if($?.replaceHistory)return K;const ae=j>=0?K.slice(0,j+1):[];if(ae[ae.length-1]===D)return v(ae.length-1),ae;const me=[...ae,D];return v(me.length-1),me})},[j,q]),H=s.useCallback(M=>{const $=R[M];$&&(v(M),y($),l($),h($),J(!0),q($))},[R,q]),k=s.useCallback(()=>{if(m){J(!0);try{a.current?.contentWindow?.location.reload()}catch{E()}}},[m]);s.useEffect(()=>{if(!u){U({status:"idle"});return}const M=Cs(u),$=Ct(M);if($?.previewToken){U({status:"ready",proxyBasePath:$.proxyBasePath,previewToken:$.previewToken,expiresAt:$.expiresAt});return}$&&Pe.delete(M);let g=!1;return U({status:"loading"}),J(!0),(async()=>{try{const D=await tt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:u,allowExternal:!0})}),K=await kn(D);if(!K.ok){g||U({status:"error",message:K.message});return}Pe.set(M,K.target),g||U({status:"ready",...K.target})}catch(D){if(!g){const K=D instanceof Error?D.message:String(D);U({status:"error",message:K})}}})(),()=>{g=!0}},[u]);const _=u&&C.status==="ready"?`${C.proxyBasePath}|${C.previewToken||""}|${P}`:"",V=Pn(_),A=s.useMemo(()=>{if(V!==_||!u||C.status!=="ready")return"";try{const M=new URL(u),$=M.pathname||"/",g=new URLSearchParams(M.search);g.delete("oc_url_token"),g.delete("oc_client_token"),g.set("ocPreview",String(P)),g.set("oc_preview_token",C.previewToken||"");const D=g.toString();return tn().authenticatedAsset(`${C.proxyBasePath}${$}${D?`?${D}`:""}${M.hash}`)}catch{return""}},[u,C,_,P,V]),X=A||(C.status==="error"?u:""),se=s.useCallback(M=>{if(!M||!u||C.status!=="ready")return"";try{const $=new URL(M,window.location.origin),g=C.proxyBasePath.endsWith("/")?C.proxyBasePath.slice(0,-1):C.proxyBasePath;if($.origin!==window.location.origin||!$.pathname.startsWith(g))return"";const D=$.pathname.slice(g.length)||"/",K=new URL(u).origin;return Kt(new URL(`${D}${$.search}${$.hash}`,K).toString())}catch{return""}},[u,C]),ie=s.useCallback(M=>{if(!M||!u||C.status!=="ready")return"";try{const $=new URL(M,window.location.origin),g=new URL(u).origin;if($.origin!==window.location.origin||g===window.location.origin)return"";const D=C.proxyBasePath.endsWith("/")?C.proxyBasePath.slice(0,-1):C.proxyBasePath;return $.pathname.startsWith(D)?"":Kt(new URL(`${$.pathname}${$.search}${$.hash}`,g).toString())}catch{return""}},[u,C]),he=s.useCallback(M=>{const $=a.current?.contentWindow;$&&$.postMessage({source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:M},window.location.origin)},[]),ye=s.useCallback(async M=>{if(!(G??(L?"draft":null))){ve.error("Open a chat session before attaching preview annotations");return}const g=a.current,D=g?.contentWindow,K=g?.getBoundingClientRect(),ae={width:Number.isFinite(D?.innerWidth)?D?.innerWidth??K?.width??0:K?.width??0,height:Number.isFinite(D?.innerHeight)?D?.innerHeight??K?.height??0:K?.height??0},de=g?await Cn(g,M):null,me=!!de;de&&await O(de),rt(St({pageUrl:m,viewport:ae,devicePixelRatio:window.devicePixelRatio||1,target:M,screenshotAttached:me,intro:me?"This is a selected DOM element from the in-app preview. A screenshot of the visible preview area with the selected element highlighted is attached.":"This is a selected DOM element from the in-app preview."})),ve.success("Preview annotation attached to chat")},[O,G,m,L]),pe=s.useCallback(()=>{const M=a.current;w(null),he(!1),M&&Xt(M,Ze).catch(()=>{})},[he]);s.useEffect(()=>{if(!Q)return;const M=$=>{$.key==="Escape"&&($.preventDefault(),$.stopImmediatePropagation(),Z(!1),pe())};return window.addEventListener("keydown",M,!0),()=>window.removeEventListener("keydown",M,!0)},[pe,Q]),s.useEffect(()=>()=>pe(),[pe]),s.useEffect(()=>{const M=$=>{if($.source!==a.current?.contentWindow)return;const g=$.data;if(!(!g||g.source!=="pichamber-preview-bridge"||g.version!==1)){if(g.type==="ready"){const D=typeof g.url=="string"?g.url:"",K=se(D);K&&K!==m&&N(K,{inFrame:!0});return}if(g.type==="hover"){w(Be(g.target)?g.target:null);return}if(g.type==="select"&&Be(g.target)){w(null),Z(!1),he(!1),ye(g.target);return}if(g.type==="navigate-preview"){const D=typeof g.url=="string"?g.url:"",K=ie(D);if(K){N(K);return}D&&N(D)}}};return window.addEventListener("message",M),()=>window.removeEventListener("message",M)},[N,ye,m,se,ie,he]);const xe=s.useCallback(()=>{const M=a.current;if(!(!M||!m)){if(Q){Z(!1),pe();return}if(A){w(null),Z(!0),he(!0);return}Z(!0),(async()=>{try{const $=await Xt(M,En);if(Z(!1),!$||!Be($))return;await ye($)}catch{Z(!1),ve.error("This page cannot be inspected from the browser panel.")}})()}},[ye,pe,m,Q,he,A]),ce=s.useCallback(()=>{try{const M=a.current?.contentWindow?.location.href||"",$=ie(M);if($){N($,{inFrame:!0});return}}catch{}J(!1),Q&&A&&he(!0)},[N,ie,Q,he,A]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:j<=0,onClick:()=>H(j-1),children:e.jsx(B,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:j<0||j>=R.length-1,onClick:()=>H(j+1),children:e.jsx(B,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:k,children:e.jsx(B,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:M=>{M.preventDefault(),N(d)},children:e.jsx("input",{value:d,onChange:M=>h(M.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),e.jsx(le,{type:"button",variant:Q?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:xe,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(B,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:()=>{nt(m)},children:e.jsx(B,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[X?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("iframe",{ref:a,src:X,title:"Web browser",className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:ce},`${r}:${P}`),Q&&F?e.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:F.bounds.x,top:F.bounds.y,width:F.bounds.width,height:F.bounds.height},children:e.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[F.tag,F.text?` · ${F.text}`:""]})}):null]}):e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[e.jsx(an,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground",children:"Enter an address above to start browsing the web"}),e.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:"Pages opened here run with full access to PiChamber — needed for inspect and screenshots. Only open sites you trust: a malicious page could read your data or act on your behalf."})]}),I?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Us=({initialUrl:t,directory:n,tabID:r})=>{const a=s.useRef(null),o=Y(w=>w.setContextPanelTabTargetPath),f=Ye(t),x=f!=="about:blank"?f:"",d=s.useRef(Ye(t)),[h,m]=s.useState(x),[y,u]=s.useState(x),[l,R]=s.useState(!1),[c,j]=s.useState(!0),v=s.useRef(null),P=c,E=s.useCallback(w=>{!w||w==="about:blank"||!n||!r||o(n,r,w)},[n,r,o]),I=Se(w=>w.currentSessionId),J=Se(w=>w.newSessionDraft?.open),Q=st(w=>w.addAttachedFile);s.useEffect(()=>{const w=a.current;if(!w)return;const C=()=>{try{const N=w.getURL();N&&N!=="about:blank"&&(u(N),m(N),E(N))}catch{}},U=N=>{const H=N.detail;typeof H?.url=="string"&&H.url&&(u(H.url),m(H.url),E(H.url))},G=()=>{v.current&&clearTimeout(v.current),v.current=setTimeout(()=>j(!0),200)},L=()=>{v.current&&clearTimeout(v.current),j(!1),C()},O=N=>{const H=N.detail;if(H?.disposition==="new-window"||H?.disposition==="foreground-tab"||H?.disposition==="background-tab"){N.preventDefault();const k=a.current;typeof k?.loadURL=="function"&&H.url&&k.loadURL(H.url)}},q=()=>{try{w.executeJavaScript?.(Fs,!0).catch(()=>{})}catch{}};w.addEventListener("did-navigate",U),w.addEventListener("did-navigate-in-page",U),w.addEventListener("did-start-loading",G),w.addEventListener("did-stop-loading",L),w.addEventListener("new-window",O),w.addEventListener("dom-ready",q);try{w.isLoading()||(j(!1),C())}catch{}return q(),()=>{v.current&&clearTimeout(v.current),w.removeEventListener("did-navigate",U),w.removeEventListener("did-navigate-in-page",U),w.removeEventListener("did-start-loading",G),w.removeEventListener("did-stop-loading",L),w.removeEventListener("new-window",O),w.removeEventListener("dom-ready",q)}},[E]),s.useEffect(()=>{const w=setTimeout(()=>j(!1),3e4);return()=>clearTimeout(w)},[]),s.useEffect(()=>{if(!l)return;const w=C=>{if(C.key!=="Escape")return;C.preventDefault(),C.stopImmediatePropagation(),R(!1);const U=a.current;try{U?.executeJavaScript?.(Ze).catch(()=>{})}catch{}};return window.addEventListener("keydown",w,!0),()=>window.removeEventListener("keydown",w,!0)},[l]),s.useEffect(()=>{const w=a.current;return()=>{try{const C=w?.getURL?.();C&&C!=="about:blank"&&o(n,r,C)}catch{}try{w?.executeJavaScript?.(Ze).catch(()=>{})}catch{}}},[n,r,o]);const Z=s.useCallback(w=>{const C=a.current;if(typeof C?.loadURL!="function")return;const U=Ye(w);try{C.loadURL(U)}catch{}},[]),F=s.useCallback(()=>{const w=a.current;if(w){if(l){R(!1);try{w.executeJavaScript?.(Ze).catch(()=>{})}catch{}return}R(!0),w.executeJavaScript?.(En,!0).then(async C=>{if(R(!1),!C||!Be(C))return;if(!(I??(J?"draft":null))){ve.error("Open a chat session before attaching preview annotations");return}const G=typeof w.getWebContentsId=="function"?w.getWebContentsId():null;if(G==null)return;const L=await yr("desktop_browser_capture_page",{webContentsId:G}),O=await w.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),q=Number.isFinite(O?.width)?O.width:L.width,N=Number.isFinite(O?.height)?O.height:L.height,H=await kt(L.base64,L.width,L.height,q,N,C),k=!!H;H&&await Q(H),rt(St({pageUrl:y,viewport:{width:q,height:N},devicePixelRatio:window.devicePixelRatio||1,target:C,screenshotAttached:k,intro:"This is a selected DOM element from the in-app preview. A screenshot of the visible preview area with the selected element highlighted is attached."})),ve.success("Preview annotation attached to chat")}).catch(()=>R(!1))}},[Q,I,y,l,J]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{a.current?.goBack?.()}catch{}},children:e.jsx(B,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{a.current?.goForward?.()}catch{}},children:e.jsx(B,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{a.current?.reload?.()}catch{}},children:e.jsx(B,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:w=>{w.preventDefault(),Z(h)},children:e.jsx("input",{value:h,onChange:w=>m(w.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),e.jsx(le,{type:"button",variant:l?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:F,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(B,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{nt(y)},children:e.jsx(B,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[e.jsx("webview",{ref:a,src:d.current,partition:"persist:pichamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!y||y==="about:blank")&&!c?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[e.jsx(an,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,P?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Hs=t=>{const n=Bs()?Us:zs;return e.jsx(n,{...t})},Vs=8,De=new Map,Nt=t=>JSON.stringify([In(),t]),Yt=t=>{const n=Nt(t),r=De.get(n);return r?(r.touchedAt=Date.now(),De.delete(n),De.set(n,r),r):null},lt=t=>{const n=Nt(t),r=De.get(n);if(r)return r.touchedAt=Date.now(),r;if(De.size>=Vs){const o=De.keys().next().value;o!==void 0&&De.delete(o)}const a={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return De.set(n,a),a},Ks=t=>{De.delete(Nt(t))},Rn=(t,n)=>e.jsx(pt,{filePath:t,extension:n}),Xs=({status:t})=>{const n={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"}[t];return e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:n}})},Ys=({node:t,root:n,isExpanded:r,isActive:a,isBrowserClient:o,status:f,badge:x,permissions:d,downloadFile:h,onSelect:m,onToggle:y,onRevealPath:u,onOpenDialog:l})=>{const R=t.type==="directory",{canRename:c,canCreateFile:j,canCreateFolder:v,canDelete:P,canReveal:E}=d,I=!R&&!!h,J=E&&!o,Q=c||j||v||P||I||J,[Z,F]=s.useState(!1),[w,C]=s.useState(!1),U=s.useCallback(N=>{Q&&(N?.preventDefault(),C(!0))},[Q]),G=s.useCallback(()=>{R?y(t.path):m(t)},[R,t,m,y]),L=s.useCallback(N=>{N.stopPropagation(),C(!1),F(!0)},[]),O=({Item:N,Separator:H})=>e.jsxs(e.Fragment,{children:[c&&e.jsxs(N,{onClick:k=>{k.stopPropagation(),l("rename",t)},children:[e.jsx(B,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(N,{onClick:k=>{k.stopPropagation(),mt(t.path).then(_=>{if(_.ok){ve.success("Path copied");return}ve.error("Copy failed")})},children:[e.jsx(B,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy Path"]}),!R&&h&&e.jsxs(N,{onClick:k=>{k.stopPropagation(),h(t.path).catch(_=>{console.error("Download failed:",_),ve.error("Operation failed")})},children:[e.jsx(B,{name:"download",className:"mr-2 h-4 w-4"})," ",o?"Download":"Save"]}),J&&e.jsxs(N,{onClick:k=>{k.stopPropagation(),u(t.path)},children:[e.jsx(B,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",Ln()]}),R&&(j||v)&&e.jsxs(e.Fragment,{children:[e.jsx(H,{}),j&&e.jsxs(N,{onClick:k=>{k.stopPropagation(),l("createFile",t)},children:[e.jsx(B,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New File"]}),v&&e.jsxs(N,{onClick:k=>{k.stopPropagation(),l("createFolder",t)},children:[e.jsx(B,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New Folder"]})]}),P&&e.jsxs(e.Fragment,{children:[e.jsx(H,{}),e.jsxs(N,{onClick:k=>{k.stopPropagation(),l("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(B,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),q=s.useCallback(N=>{const H=gn(n,t.path);H&&(N.dataTransfer.setData("application/x-pichamber-file-path",H),N.dataTransfer.effectAllowed="copy")},[t.path,n]);return e.jsxs(tr,{open:w,onOpenChange:C,children:[e.jsxs(nr,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:U}),children:[e.jsxs("button",{type:"button",onClick:G,onContextMenu:U,draggable:!0,onDragStart:q,className:ge("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40","cursor-grab active:cursor-grabbing"),children:[R?r?e.jsx(B,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(B,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):Rn(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!R&&f&&e.jsx(Xs,{status:f}),R&&x&&e.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[x.modified>0&&e.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",x.modified]}),x.added>0&&e.jsxs("span",{className:"text-[var(--status-success)]",children:["+",x.added]})]})]}),Q&&e.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:e.jsxs(br,{open:Z,onOpenChange:F,children:[e.jsxs(Oe,{children:[e.jsx($e,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(vr,{asChild:!0,children:e.jsx(le,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:L,title:"File menu","aria-label":"File menu",children:e.jsx(B,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx(We,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(jr,{align:"end",side:"bottom",onCloseAutoFocus:()=>F(!1),children:O({Item:Sr,Separator:Cr})})]})})]}),e.jsx(rr,{className:"min-w-[180px]",children:O({Item:sr,Separator:or})})]})},Gs=(t,n)=>t.node===n.node&&t.root===n.root&&t.isExpanded===n.isExpanded&&t.isActive===n.isActive&&t.isBrowserClient===n.isBrowserClient&&t.status===n.status&&t.badge===n.badge&&t.permissions===n.permissions&&t.downloadFile===n.downloadFile&&t.onSelect===n.onSelect&&t.onToggle===n.onToggle&&t.onRevealPath===n.onRevealPath&&t.onOpenDialog===n.onOpenDialog,qs=s.memo(Ys,Gs),Js=()=>{const{files:t,runtime:n}=ft(),r=On(n.platform),a=Ge()??"",o=Ee(a.trim()),f=$n(),x=Wn(),d=Y(i=>i.openContextFile),h=ln(a),[m,y]=s.useState(""),u=s.useRef(null),{results:l,searching:R}=as({directory:a,query:m,chrome:"desktop",showHidden:f,showGitignored:x}),[c,j]=s.useState({}),[v,P]=s.useState({}),E=s.useRef(new Set),I=s.useRef(new Set),J=s.useRef(null);s.useEffect(()=>{if(!o){j({}),P({}),E.current=new Set;return}const i=Yt(o);i?(j({...i.childrenByDir}),P({...i.loadErrorsByDir}),E.current=new Set(i.loadedDirs)):(j({}),P({}),E.current=new Set)},[o]),s.useEffect(()=>{if(!o)return;const i=lt(o);i.childrenByDir=c},[o,c]),s.useEffect(()=>{if(!o)return;const i=lt(o);i.loadErrorsByDir=v},[o,v]),s.useEffect(()=>{if(!o)return;const i=lt(o);i.loadedDirs=new Set(E.current)},[o,c,v]),s.useEffect(()=>()=>{if(!o)return;const i=Yt(o);i&&i.loadedDirs.size===0&&Object.keys(i.childrenByDir).length===0&&Ks(o)},[o]);const Q=s.useMemo(()=>[],[]),Z=s.useMemo(()=>[],[]),F=Te(i=>o?i.byRoot[o]?.expandedPaths??Q:Q),w=Te(i=>o?i.byRoot[o]?.selectedPath??null:null),C=Te(i=>i.setSelectedPath),U=Te(i=>i.addOpenPath),G=Te(i=>i.removeOpenPathsByPrefix),L=Te(i=>i.toggleExpandedPath),O=Te(i=>i.collapseAllExpandedPaths),q=Y(i=>o?i.contextPanelByDirectory[o]?.tabs??Z:Z),N=s.useMemo(()=>new Set(q.map(i=>i.mode==="file"?i.targetPath:null).filter(i=>typeof i=="string"&&i.length>0).map(i=>Ee(i))),[q]),H=s.useCallback(i=>{t.revealPath&&t.revealPath(i).catch(()=>{ve.error("Failed to reveal path")})},[t]),k=s.useCallback((i,T)=>{const ee=T.filter(z=>z&&typeof z.name=="string"&&z.name.length>0).filter(z=>f||!z.name.startsWith(".")).filter(z=>x||!is(z.name)).map(z=>{const ue=z.name,te=Ee(z.path||""),we=te?ls(te)?te:Ee(`${i}/${te}`):Ee(`${i}/${ue}`),be=z.isDirectory?"directory":"file",Le=be==="file"&&ue.includes(".")?ue.split(".").pop()?.toLowerCase():void 0;return{name:ue,path:we,type:be,extension:Le}});return cs(ee)},[x,f]),_=s.useCallback(async(i,T)=>{const ee=Ee(i.trim());if(!ee||E.current.has(ee)||I.current.has(ee))return;I.current=new Set(I.current),I.current.add(ee);const z=t.listDirectory?t.listDirectory(ee).then(ue=>ue.entries.map(te=>({name:te.name,path:te.path,isDirectory:te.isDirectory}))):Fn(ee).then(ue=>ue.map(te=>({name:te.name,path:te.path,isDirectory:te.isDirectory})));try{const ue=await z;if(T?.())return;const te=k(ee,ue);E.current=new Set(E.current),E.current.add(ee),P(we=>{if(!we[ee])return we;const be={...we};return delete be[ee],be}),j(we=>({...we,[ee]:te}))}catch(ue){if(T?.())return;const te=ue instanceof Error?ue.message:String(ue??"");console.error("Failed to load sidebar directory:",ue),P(we=>({...we,[ee]:te}))}finally{I.current=new Set(I.current),I.current.delete(ee)}},[t,k]),V=s.useCallback(async()=>{if(!o)return;J.current?.abort();const i=new AbortController;J.current=i;try{const ee=(Te.getState().byRoot[o]?.expandedPaths??[]).map(te=>Ee(te)).filter(te=>!!te&&te!==o&&te.startsWith(`${o}/`)),z=[o,...ee];E.current=new Set(E.current);for(const te of z)E.current.delete(te);P(te=>{if(Object.keys(te).length===0)return te;const we={...te};let be=!1;for(const Le of z)Le in we&&(delete we[Le],be=!0);return be?we:te});const ue=()=>i.signal.aborted;await _(o,ue);for(let te=0;te<ee.length&&!i.signal.aborted;te+=3){const we=ee.slice(te,te+3);await Promise.all(we.map(be=>_(be,ue)))}}catch(T){if(i.signal.aborted)return;console.error("Failed to refresh sidebar tree:",T)}finally{J.current===i&&(J.current=null)}},[_,o]),A=s.useCallback(async i=>{if(!i){await V();return}const T=Ee(i);E.current=new Set(E.current),E.current.delete(T),I.current=new Set(I.current),I.current.delete(T),await _(T)},[_,V]),X=s.useCallback(()=>{o&&C(o,null)},[o,C]),{operation:se,target:ie,inputValue:he,setInputValue:ye,submitting:pe,inputRef:xe,open:ce,close:M,submit:$,capabilities:{canCreateFile:g,canCreateFolder:D,canRename:K,canDelete:ae}}=ds({files:t,root:o,selectedPath:w??"",refreshDirectory:A,removeOpenPathsByPrefix:G,clearSelectedPath:X}),de=!!t.revealPath,me=s.useMemo(()=>({canRename:K,canCreateFile:g,canCreateFolder:D,canDelete:ae,canReveal:de}),[K,g,D,ae,de]);s.useEffect(()=>{o&&(J.current?.abort(),E.current=new Set,I.current=new Set,P({}),j(i=>Object.keys(i).length===0?i:{}),_(o))},[_,o,f,x]),s.useEffect(()=>{if(!o||F.length===0)return;const i=F.map(z=>Ee(z)).filter(z=>!!z&&z!==o&&z.startsWith(`${o}/`)&&!E.current.has(z)&&!I.current.has(z)).sort((z,ue)=>z.split("/").length-ue.split("/").length);if(i.length===0)return;let T=!1;const ee=()=>T;return(async()=>{for(let z=0;z<i.length&&!T;z+=3){const ue=i.slice(z,z+3);await Promise.all(ue.map(te=>_(te,ee)))}})(),()=>{T=!0}},[F,_,o]);const fe=s.useMemo(()=>{const i=new Map;if(!h?.files)return i;for(const T of h.files)T.index==="A"||T.working_dir==="?"?i.set(T.path,"git-added"):T.index==="D"?i.set(T.path,"git-deleted"):(T.index==="M"||T.working_dir==="M")&&i.set(T.path,"git-modified");return i},[h]),je=s.useMemo(()=>{const i=new Map;if(!h?.files||!o)return i;for(const T of h.files){const ee=T.index==="M"||T.working_dir==="M",z=T.index==="A"||T.working_dir==="?";if(!ee&&!z)continue;const ue=T.path.split("/");if(ue.length<=1)continue;let te=o;for(let we=0;we<ue.length-1;we++){te=`${te}/${ue[we]}`;let be=i.get(te);be||(be={modified:0,added:0},i.set(te,be)),ee&&be.modified++,z&&be.added++}}return i},[h,o]),b=s.useCallback(i=>{if(N.has(i))return"open";if(fe.size===0)return null;const T=i.startsWith(o+"/")?i.slice(o.length+1):i;return fe.get(T)??null},[N,fe,o]),S=s.useCallback(i=>{if(je.size===0)return null;const T=je.get(i);return T&&T.modified+T.added>0?T:null},[je]),ne=s.useCallback(async i=>{if(!o)return;const T=await mn(t,i.path,{directory:o});if(!T.ok){ve.error(fn(T.reason));return}C(o,i.path),U(o,i.path),d(o,i.path)},[U,t,d,o,C]),re=s.useCallback(async i=>{const T=Ee(i);o&&(L(o,T),E.current.has(T)||await _(T))},[_,o,L]);function oe(i,T){const ee=c[i]??[];return ee.map((z,ue)=>{const te=z.type==="directory",we=te&&F.includes(z.path),be=w===z.path,Le=ue===ee.length-1;return e.jsxs("li",{className:"relative",children:[T>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Le&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),e.jsx(qs,{node:z,root:o,isExpanded:we,isActive:be,isBrowserClient:r,status:te?void 0:b(z.path),badge:te?S(z.path):void 0,permissions:me,downloadFile:t.downloadFile,onSelect:ne,onToggle:re,onRevealPath:H,onOpenDialog:ce}),te&&we&&e.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[v[z.path]?e.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:v[z.path],children:v[z.path]}),e.jsxs(le,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{A(z.path)},children:[e.jsx(B,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,oe(z.path,T+1)]})]},z.path)})}const W=!!(o&&c[o]),p=o?v[o]:null;return e.jsxs("section",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col gap-2 border-b border-border/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[g&&e.jsxs(Oe,{children:[e.jsx($e,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(le,{variant:"ghost",size:"sm",onClick:()=>ce("createFile",{path:a,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:e.jsx(B,{name:"file-add",className:"h-4 w-4"})})})}),e.jsx(We,{side:"bottom",sideOffset:6,children:"New File"})]}),D&&e.jsxs(Oe,{children:[e.jsx($e,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(le,{variant:"ghost",size:"sm",onClick:()=>ce("createFolder",{path:a,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:e.jsx(B,{name:"folder-add",className:"h-4 w-4"})})})}),e.jsx(We,{side:"bottom",sideOffset:6,children:"New Folder"})]}),e.jsxs(Oe,{children:[e.jsx($e,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(le,{variant:"ghost",size:"sm",onClick:()=>{V()},className:"h-8 w-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:e.jsx(B,{name:"refresh",className:"h-4 w-4"})})})}),e.jsx(We,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(Oe,{children:[e.jsx($e,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(le,{variant:"ghost",size:"sm",onClick:()=>{o&&O(o)},className:"h-8 w-8 p-0 flex-shrink-0",title:"Collapse all folders","aria-label":"Collapse all folders",children:e.jsx(B,{name:"collapse-vertical",className:"h-4 w-4"})})})}),e.jsx(We,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]}),e.jsxs("div",{className:"relative min-w-0",children:[e.jsx(B,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(_t,{ref:u,value:m,onChange:i=>y(i.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),m.trim().length>0?e.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{y(""),u.current?.focus()},children:e.jsx(B,{name:"close",className:"h-4 w-4"})}):null]})]}),e.jsx(kr,{outerClassName:"flex-1 min-h-0",className:"p-2",children:e.jsx("ul",{className:"flex flex-col",children:R?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(B,{name:"loader-4",className:"h-4 w-4 animate-spin"}),"Searching..."]}):l.length>0?l.map(i=>{const T=w===i.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>ne(i),draggable:!0,onDragStart:ee=>{const z=i.relativePath||gn(o??"",i.path);!z||z==="."||(ee.dataTransfer.setData("application/x-pichamber-file-path",z),ee.dataTransfer.effectAllowed="copy")},className:ge("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors cursor-grab active:cursor-grabbing",T?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:i.path,children:[Rn(i.path,i.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:i.relativePath??i.path})]})},i.path)}):p?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:p}),e.jsxs(le,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{V()},children:[e.jsx(B,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):W&&o?oe(o,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(gt,{open:!!se,onOpenChange:i=>!i&&M(),children:e.jsxs(xt,{children:[e.jsxs(wt,{children:[e.jsxs(yt,{children:[se==="createFile"&&"Create File",se==="createFolder"&&"Create Folder",se==="rename"&&"Rename",se==="delete"&&"Delete"]}),e.jsxs(bt,{children:[se==="createFile"&&`Create a new file in ${ie?.path??"root"}`,se==="createFolder"&&`Create a new folder in ${ie?.path??"root"}`,se==="rename"&&`Rename ${ie?.name??""}`,se==="delete"&&`Are you sure you want to delete ${ie?.name??""}? This action cannot be undone.`]})]}),se!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(_t,{ref:xe,value:he,onChange:i=>ye(i.target.value),placeholder:se==="rename"?"New name":"Name",onKeyDown:i=>{i.key==="Enter"&&$()},autoFocus:!0})}),e.jsxs(Nr,{children:[e.jsx(le,{variant:"outline",onClick:M,disabled:pe,children:"Cancel"}),e.jsx(le,{variant:se==="delete"?"destructive":"default",onClick:()=>{$()},disabled:pe||se!=="delete"&&!he.trim(),children:pe?e.jsx(B,{name:"loader-4",className:"size-4 animate-spin"}):se==="delete"?"Delete":"Confirm"})]})]})})]})},Qs=200,Zs=480,eo=({visible:t})=>{const n=Y(v=>v.contextEditorTreeWidth),r=Y(v=>v.setContextEditorTreeWidth),[a,o]=s.useState(!1),f=s.useRef(0),x=s.useRef(n),d=s.useRef(null),h=s.useRef(null),m=s.useRef(null),y=s.useCallback(v=>Math.min(Zs,Math.max(Qs,Math.round(v))),[]),u=s.useCallback(v=>{const P=m.current;P&&(P.style.width=`${v}px`,P.style.setProperty("--oc-editor-tree-width",`${v}px`))},[]),l=v=>{if(t){try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}h.current=v.pointerId,o(!0),f.current=v.clientX,x.current=n,d.current=n,v.preventDefault()}},R=v=>{if(!a||h.current!==v.pointerId)return;const P=f.current-v.clientX,E=y(x.current+P);d.current!==E&&(d.current=E,u(E))},c=v=>{if(h.current!==v.pointerId)return;try{v.currentTarget.releasePointerCapture(v.pointerId)}catch{}const P=y(d.current??n);h.current=null,d.current=null,o(!1),r(P)},j=t?n:0;return e.jsxs("div",{ref:m,className:ge("relative h-full flex-shrink-0 overflow-hidden border-l border-border bg-background will-change-[width] motion-reduce:transition-none",!t&&"border-l-0"),style:{width:`${a?d.current??j:j}px`,"--oc-editor-tree-width":`${a?d.current??n:n}px`,overflowX:"clip",transitionProperty:a?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t,children:[t&&e.jsx("div",{className:ge("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",a&&"bg-[var(--interactive-border)]"),onPointerDown:l,onPointerMove:R,onPointerUp:c,onPointerCancel:c,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:ge("relative z-10 h-full shrink-0 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",a&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-editor-tree-width)"},"aria-hidden":!t,children:e.jsx(Js,{})})]})},to="x-pichamber-preview-target-error",no=t=>{const n=t.get(to);return n==="missing"||n==="expired"||n==="invalid-token"?n:null},ro=(t,n)=>no(t)?n?"stop-retrying":"retry-registration":"none",so=({rawUrl:t,onNavigate:n})=>{const{currentTheme:r}=Pr(),[a,o]=s.useReducer(S=>S+1,0),[f,x]=s.useReducer(S=>S+1,0),[d,h]=s.useState({status:"idle"}),m=s.useRef(null),y=s.useRef(1),[u,l]=s.useState(!1),[R,c]=s.useState(!1),[j,v]=s.useState("all"),[P,E]=s.useState([]),[I,J]=s.useState(!1),[Q,Z]=s.useState(null),F=Se(S=>S.currentSessionId),w=Se(S=>S.newSessionDraft?.open),C=Ge(),U=st(S=>S.addAttachedFile);let G=null;try{G=t?new URL(t):null}catch{G=null}const L=G?G.hostname==="localhost"||G.hostname==="127.0.0.1"||G.hostname==="::1"||G.hostname==="[::1]"||G.hostname==="0.0.0.0":!1,O=G?G.hostname==="0.0.0.0"?new URL(G.toString().replace("0.0.0.0","127.0.0.1")):G:null,q=O?O.toString():"",N=q?`${en()||"same-origin"}|${q}`:"",H=r.metadata.variant;s.useEffect(()=>{if(!q||!L){h({status:"idle"});return}const S=Ct(N);if(S?.previewToken){h({status:"ready",proxyBasePath:S.proxyBasePath,previewToken:S.previewToken,expiresAt:S.expiresAt});return}S&&Pe.delete(N);let ne=!1;return h({status:"loading"}),(async()=>{try{const re=await tt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:q})}),oe=await kn(re);if(!oe.ok){Pe.delete(N),ne||h({status:"error",message:oe.message});return}Pe.set(N,oe.target),ne||h({status:"ready",...oe.target})}catch(re){if(Pe.delete(N),!ne){const oe=re instanceof Error?re.message:String(re);h({status:"error",message:oe})}}})(),()=>{ne=!0}},[L,N,f,q]);const k=O&&(O.protocol==="http:"||O.protocol==="https:")?O.toString():"",_=L&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${a}`:"",V=Pn(_),A=L&&d.status==="ready"&&O&&V===_?(()=>{const S=O.pathname||"/",ne=new URLSearchParams(O.search);ne.delete("oc_url_token"),ne.delete("oc_client_token"),ne.set("ocPreview",String(a)),ne.set("oc_preview_token",d.previewToken||"");const re=ne.toString(),oe=O.hash||"";return tn().authenticatedAsset(`${d.proxyBasePath}${S}${re?`?${re}`:""}${oe}`)})():"",X=L?A:k,se=L?Ws(A):k,ie=L&&(d.status==="loading"||d.status==="idle"||V!==_),he=L&&d.status==="error",ye=s.useCallback(S=>{if(!(F??(w?"draft":null))||!C){ve.error("Open a chat session before attaching preview annotations");return}const re=t||X||"",oe=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},W=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let p=!1;try{const i=m.current,T=i?await Cn(i,S):null;T&&(await U(T),p=!0)}catch{p=!1}rt(St({pageUrl:re,viewport:oe,devicePixelRatio:W,target:S,screenshotAttached:p,intro:"This is a selected DOM element from the in-app preview."})),ve.success("Preview annotation attached to chat")})()},[U,F,C,X,w,t]);s.useEffect(()=>{l(!1),E([]),c(!1),v("all"),J(!1),Z(null),y.current=1},[X]),s.useEffect(()=>{const S=m.current?.contentWindow;!u||!S||Vt(S,A,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:I})},[u,I,A]),s.useEffect(()=>{const S=m.current?.contentWindow;!u||!S||Vt(S,A,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:H})},[u,H,A]),s.useEffect(()=>{if(!I||typeof window>"u")return;const S=ne=>{ne.key==="Escape"&&(ne.preventDefault(),ne.stopImmediatePropagation(),J(!1))};return window.addEventListener("keydown",S,!0),()=>window.removeEventListener("keydown",S,!0)},[I]),s.useEffect(()=>{if(!L||typeof window>"u")return;const S=oe=>{if(typeof oe=="string")return oe;if(oe==null)return"";try{return JSON.stringify(oe)}catch{return String(oe)}},ne=oe=>{const W=y.current;y.current+=1,E(p=>{const i=[...p,{...oe,id:W}];return i.length>Ht?i.slice(i.length-Ht):i})},re=oe=>{if(oe.source!==m.current?.contentWindow)return;const W=oe.data;if(!(!W||W.source!=="pichamber-preview-bridge"||W.version!==1)){if(W.type==="ready"){l(!0);return}if(W.type==="console"){const p=W.level==="error"||W.level==="warn"||W.level==="info"||W.level==="debug"?W.level:"log",i=Array.isArray(W.args)?W.args.map(S).filter(Boolean):[];ne({level:p,message:i.join(" "),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="runtime-error"){const p=S(W.filename),i=typeof W.line=="number"?W.line:null,T=typeof W.column=="number"?W.column:null,ee=p?`${p}${i!==null?`:${i}${T!==null?`:${T}`:""}`:""}`:"",z=S(W.stack);ne({level:"runtime",message:S(W.message)||"Runtime error",details:[ee,z].filter(Boolean).join(`
127
- `),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="resource-error"){const p=S(W.tag)||"resource",i=S(W.url);ne({level:"resource",message:i?`${p}: ${i}`:p,details:S(W.outerHTML),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="hover"){Z(Be(W.target)?W.target:null);return}if(W.type==="select"&&Be(W.target)){Z(W.target),J(!1),ye(W.target);return}if(W.type==="navigate-preview"){const p=typeof W.url=="string"?W.url:"",i=W.navigation==="external"?"external":"proxy";if(p&&i==="external"){nt(p);return}p&&n(p)}}};return window.addEventListener("message",re),()=>{window.removeEventListener("message",re)}},[ye,L,n]);const pe=P.filter(S=>S.level==="error"||S.level==="runtime"||S.level==="resource").length,xe=P.filter(S=>$s(S,j)),ce=s.useCallback(()=>{const S=[`Preview URL: ${t||X||""}`,`Events: ${P.length}`,""].join(`
128
- `),ne=P.map(re=>{const oe=new Date(re.ts).toISOString(),W=re.details?`
129
- ${re.details}`:"";return`[${oe}] [${re.level}] ${re.message}${W}`}).join(`
130
- `);mt(`${S}${ne}`).then(re=>{re.ok?ve.success("Preview console copied"):ve.error("Failed to copy preview console")})},[P,X,t]),M=s.useCallback(()=>{if(!(F??(w?"draft":null))||!C){ve.error("Open a chat session before attaching preview logs");return}const ne=[`Preview URL: ${t||X||""}`,`Events: ${P.length}`,""].join(`
131
- `),re=P.map(oe=>{const W=new Date(oe.ts).toISOString(),p=oe.details?`
132
- ${oe.details}`:"";return`[${W}] [${oe.level}] ${oe.message}${p}`}).join(`
133
- `);rt(`These are browser console logs from the dev server running for this project.
134
-
135
- ${ne}${re}`),ve.success("Preview console attached to chat")},[P,F,C,X,w,t]),[$,g]=s.useState("unknown"),D=s.useRef(0),K=s.useRef(0),ae=s.useRef(""),de=s.useRef(""),me=15e3;s.useEffect(()=>{if(!A){g("unknown"),ae.current="",D.current=0,K.current=0;return}let S=!1,ne=null;ae.current!==N&&(ae.current=N,D.current=Date.now(),K.current=0);const re=oe=>{ne=setTimeout(()=>{S||o()},oe)};return g("unknown"),(async()=>{const W=await(async()=>{try{return await tt(A,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(S)return;if(!W){g("unreachable"),re(5e3);return}const p=ro(W.headers,de.current===N);if(p!=="none"){if(Pe.delete(N),p==="retry-registration")de.current=N,h({status:"loading"}),x();else{const ee=await W.json().catch(()=>({}));if(S)return;const z=typeof ee?.error=="string"?ee.error:`HTTP ${W.status}`;h({status:"error",message:z})}return}if(W.status!==502){de.current="",g("reachable");return}const i=D.current||Date.now();if(Date.now()-i<me){g("starting"),K.current+=1;const ee=K.current,z=Math.min(2e3,250*Math.pow(2,Math.min(4,ee)));re(z);return}g("unreachable"),re(5e3)})(),()=>{S=!0,ne&&clearTimeout(ne)}},[N,A,a]);const fe=L&&d.status==="ready"&&($==="unknown"||$==="starting"),je=L&&d.status==="ready"&&$==="unreachable",b=s.useCallback(S=>{if(!L||d.status!=="ready"||typeof window>"u")return;const ne=S.currentTarget.contentWindow;if(ne)try{const re=ne.location,oe=Nn(A);if(re.origin!==oe||re.pathname.startsWith(d.proxyBasePath))return;const W=`${d.proxyBasePath}${re.pathname}${re.search}${re.hash}`;ne.location.replace(W)}catch{}},[L,A,d]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:se||t,children:se||t||"No preview URL"}),e.jsx(le,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>o(),title:"Reload preview","aria-label":"Reload preview",disabled:!X,children:e.jsx(B,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(le,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{k&&nt(k)},title:"Open in browser","aria-label":"Open in browser",disabled:!k,children:e.jsx(B,{name:"external-link",className:"h-3.5 w-3.5"})}),L?e.jsx(le,{type:"button",size:"sm",variant:I?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>J(S=>!S),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!u,children:e.jsx(B,{name:"cursor",className:"h-3.5 w-3.5"})}):null,L?e.jsxs(le,{type:"button",size:"sm",variant:R?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>c(S=>!S),title:u?"Open preview console":"Waiting for preview console","aria-label":u?"Open preview console":"Waiting for preview console",disabled:!u&&P.length===0,children:[e.jsx(B,{name:"terminal-box",className:"h-3.5 w-3.5"}),pe>0?e.jsx("span",{className:"typography-micro text-status-error",children:pe}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[fe?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[e.jsx("div",{children:"Starting dev server..."}),e.jsx("div",{className:"text-xs opacity-70",children:"Waiting for the server to accept connections."})]}):je?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[e.jsx("div",{children:"Dev server is not responding."}),e.jsx("div",{className:"text-xs opacity-70",children:"Make sure your dev server is still running, then retry."}),e.jsx(le,{type:"button",size:"sm",variant:"outline",onClick:()=>o(),children:"Retry"})]}):X&&(!L||$==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:m,src:X,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:H},onLoad:b,sandbox:L?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${X}:${a}`),I&&Q?e.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:Q.bounds.x,top:Q.bounds.y,width:Q.bounds.width,height:Q.bounds.height},children:e.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[Q.tag,Q.text?` · ${Q.text}`:""]})}):null]}):ie?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Connecting preview proxy..."}):he?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[e.jsx("div",{children:"Could not start preview proxy."}),d.status==="error"?e.jsx("div",{className:"text-center text-xs opacity-70",children:d.message}):null]}):e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Preview needs a valid http(s) URL."}),R?e.jsxs("div",{className:"absolute inset-x-3 bottom-3 z-10 max-h-[45%] overflow-hidden rounded-xl border border-border/70 bg-[var(--surface-elevated)] shadow-lg",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Preview console"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(le,{type:"button",size:"xs",variant:"ghost",onClick:M,disabled:P.length===0,children:"Attach"}),e.jsx(le,{type:"button",size:"xs",variant:"ghost",onClick:ce,disabled:P.length===0,children:"Copy"}),e.jsx(le,{type:"button",size:"xs",variant:"ghost",onClick:()=>E([]),disabled:P.length===0,children:"Clear"})]})]}),e.jsx("div",{className:"flex items-center gap-1 border-b border-border/30 px-3 py-1.5",children:["all","errors","warnings","logs"].map(S=>e.jsx(le,{type:"button",size:"xs",variant:j===S?"secondary":"ghost",onClick:()=>v(S),children:S==="all"?"All":S==="errors"?"Errors":S==="warnings"?"Warnings":"Logs"},S))}),e.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:P.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No preview console events yet."}):xe.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No events match this filter."}):xe.map(S=>e.jsx("div",{className:"border-b border-border/30 px-2 py-1 last:border-b-0",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:ge("shrink-0 uppercase",S.level==="error"||S.level==="runtime"||S.level==="resource"?"text-status-error":S.level==="warn"?"text-status-warning":"text-muted-foreground"),children:S.level}),e.jsx("span",{className:"min-w-0 break-words text-foreground",children:S.message})]})},S.id))})]}):null]})]})},Pt=t=>t,ht=t=>{const n=Pt(t).type;return typeof n=="string"?n:""},oo=t=>{const n=Pt(t).tool;return typeof n=="string"?n:""},ao=t=>{const n=Pt(t).text;return typeof n=="string"?n:""},io=t=>{const n=ht(t);return n==="tool"?oo(t).trim().toLowerCase()||"tool":n||"unknown"},lo=t=>{if(t.length===0)return"";const n=[];for(const r of t){const a=io(r);n.includes(a)||n.push(a)}return n.join(" + ")},co=t=>t.replace(/\s+/g," ").trim(),uo=t=>{for(const r of t)if(ht(r)==="text"){const a=co(ao(r));if(a.length===0)continue;return a}const n=t.filter(r=>ht(r)!=="text").length;return n===0?"":`${n} attachment${n===1?"":"s"}`},ho=(t,n,r)=>`${r(t)} / ${r(n)}`,po=t=>{if(t==="12h")return!0;if(t==="24h")return!1},mo=(t,n)=>{if(!t||!Number.isFinite(t))return"-";const r=po(n);return new Date(t).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:r===!1?"2-digit":"numeric",minute:"2-digit",...r===void 0?{}:{hour12:r}})},fo={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},et={user:0,assistant:0,tool:0,other:0},go=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,ct=t=>ut(t),xo=(...t)=>{for(const n of t)if(typeof n=="string"&&n.trim().length>0)return n;return""},ke=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((n,r)=>n+ke(r),0):t&&typeof t=="object"?Object.values(t).reduce((n,r)=>n+ke(r),0):0,wo=(t,n)=>{const r=t,a=typeof r.type=="string"?r.type:"";if(a==="reasoning")return{...et,assistant:ke(r.text)+ke(r.content)};const o=xo(r.text,r.content,r.value,r.source?.value,r.source?.text?.value);return a==="tool"||n==="tool"?{user:0,assistant:0,tool:ke(r.input)+ke(r.output)+ke(r.error)+ke(r.call?.input)+ke(r.call?.output)+ke(r.call?.error)+ke(r.raw)+Math.round(ke(r.metadata)*.25)+Math.round(ke(r.state)*.1),other:0}:n==="user"?{user:o.length,assistant:0,tool:0,other:0}:n==="assistant"?{user:0,assistant:o.length,tool:0,other:0}:{user:0,assistant:0,tool:0,other:o.length}},Gt=(t,n)=>({user:t.user+n.user,assistant:t.assistant+n.assistant,tool:t.tool+n.tool,other:t.other+n.other}),yo=t=>{const n=Ke(t.info);return n.isUser?"user":n.role==="assistant"?"assistant":n.role==="tool"?"tool":"other"},bo=(t,n)=>{if(t.length===0)return{...et};const r=t.reduce((a,o)=>{const f=yo(o);let x={...et};for(const d of o.parts)x=Gt(x,wo(d,f));return Gt(a,x)},{...et});return r.user+=n.length,{user:Math.ceil(r.user/4),assistant:Math.ceil(r.assistant/4),tool:Math.ceil(r.tool/4),other:Math.ceil(r.other/4)}},_e=t=>t.toLocaleString("en-US"),vo=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),jo=(t,n)=>!t||!Number.isFinite(t)?"-":Dr(t,n,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),So=(t,n,r)=>{const a=t.find(f=>f.id===n),o=a?.models?.find(f=>f.id===r);return{providerName:a?.name||n||"-",modelName:o?.name||r||"-",contextLimit:typeof o?.limit?.context=="number"?o.limit.context:null}},Co=()=>{const t=Y(c=>c.timeFormatPreference),[n,r]=s.useState({}),{value:a,show:o,clear:f}=Er(null,2e3),x=Se(c=>c.currentSessionId),d=Se(c=>c.currentSessionDirectory),h=Rr(),m=cn(x??""),y=Ie(c=>c.providers);s.useEffect(()=>{r(c=>Object.keys(c).length>0?{}:c),f()},[f,d,x]);const u=s.useCallback(async(c,j)=>{(await mt(j)).ok?o(c):f()},[f,o]),l=s.useMemo(()=>{const c=x?h.find(A=>A.id===x)??null:null,j=m.filter(A=>Ke(A.info).role==="assistant"),v=m.filter(A=>Ke(A.info).isUser);let P=null;for(let A=j.length-1;A>=0;A-=1){const X=j[A];if(ct(X).total>0){P=X;break}}const E=P?ct(P):fo,I=P?.info?.usage,J=dn({input:E.input,cache:{read:E.cacheRead,write:E.cacheWrite}}),Q=j.reduce((A,X)=>{const se=go(X.info.cost);return A+se},0),Z=P?.info?.model??null,F=So(y,Z?.providerID||"",Z?.modelID||""),w=F.contextLimit,C=I?un(I):E.total,U=w&&w>0?Math.min(999,C/w*100):0,G=[...m].reverse().find(A=>Ke(A.info).isUser&&typeof A.info.system=="string")?.info?.system||"",L=bo(m,G),O=L.user,q=L.assistant,N=L.tool,H=I?0:Math.max(0,E.input-O-q-N),k=O+q+N+H,_=m[0]?.info?.time?.created,V=m.length>0?m[m.length-1]?.info?.time?.created:null;return{sessionTitle:xn(c),messagesCount:m.length,userMessagesCount:v.length,assistantMessagesCount:j.length,createdAt:c?.time?.created??_??null,lastActivityAt:V??c?.time?.created??null,providerModel:F,tokenBreakdown:E,usagePercent:U,cacheHitRate:J,totalAssistantCost:Q,contextLimit:w,contextWindowTokens:C,hasUsage:I!==void 0,breakdown:{user:O,assistant:q,tool:N,other:H},breakdownTotal:k}},[x,y,m,h]);if(!x)return e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:"Open a session to inspect context."});const R=[{key:"user",label:"User",value:l.breakdown.user,color:"var(--status-success)"},{key:"assistant",label:"Assistant",value:l.breakdown.assistant,color:"var(--primary-base)"},{key:"tool",label:"Tool Calls",value:l.breakdown.tool,color:"var(--status-warning)"},...l.hasUsage?[]:[{key:"other",label:"Other",value:l.breakdown.other,color:"var(--surface-muted-foreground)"}]];return e.jsx("div",{className:"h-full overflow-y-auto bg-background",children:e.jsxs("div",{className:"mx-auto w-full max-w-[52rem] px-5 py-6",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:l.sessionTitle}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 typography-micro text-muted-foreground/70",children:[e.jsxs("span",{children:[l.providerModel.providerName," / ",l.providerModel.modelName]}),l.createdAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:jo(l.createdAt,t)})]})]})]}),e.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Context"}),e.jsxs("span",{className:"typography-micro tabular-nums text-muted-foreground/70",children:[_e(l.contextWindowTokens),l.contextLimit?` / ${_e(l.contextLimit)}`:""]})]}),e.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:l.usagePercent>0&&e.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,l.usagePercent)}%`,backgroundColor:l.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}})}),e.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:`${l.usagePercent.toFixed(1)}% used`})]}),e.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:[{label:"Messages",value:_e(l.messagesCount)},{label:"User",value:_e(l.userMessagesCount)},{label:"Assistant",value:_e(l.assistantMessagesCount)},{label:"Cost",value:vo(l.totalAssistantCost)}].map(c=>e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 px-3 py-2.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:c.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:c.value})]},c.label))}),e.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:"Last Assistant Message"}),e.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:"Input",value:l.tokenBreakdown.input,format:"count"},{label:"Output",value:l.tokenBreakdown.output,format:"count"},{label:"Reasoning",value:l.tokenBreakdown.reasoning,format:"count"},{label:"Cache Read",value:l.tokenBreakdown.cacheRead,format:"count"},{label:"Cache Write",value:l.tokenBreakdown.cacheWrite,format:"count"},{label:"Cache Hit",value:l.cacheHitRate.hasInput?l.cacheHitRate.percent:null,format:"percent"}].map(c=>e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:c.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:c.value!==null&&c.value!==void 0?c.format==="percent"?`${c.value.toFixed(1)}%`:_e(c.value):"—"})]},c.label))})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:R.map(c=>c.value<=0||l.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${c.value/l.breakdownTotal*100}%`,backgroundColor:c.color}},c.key))}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:R.map(c=>{const j=l.breakdownTotal>0?c.value/l.breakdownTotal*100:0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:c.color}}),e.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[c.label," ",e.jsxs("span",{className:"tabular-nums",children:[j.toFixed(0),"%"]})]})]},c.key)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Raw Messages"}),e.jsx("div",{className:"mt-2.5 space-y-1",children:[...m].reverse().map(c=>{const v=Ke(c.info).role,P=v==="assistant",E=v==="user",I=n[c.info.id]===!0,J=a===c.info.id,Q=c.info.time?.created??null,Z=lo(c.parts),F=P?ct({info:c.info,parts:c.parts}):null,w=E?uo(c.parts):"",C=mo(Q,t),U=Z||"—",G=F?ho(F.input,F.output,_e):"",L=v||"unknown",O=Z?`${L}: ${Z}`:L,q=I?JSON.stringify({info:c.info,parts:c.parts},null,2):"";return e.jsxs("div",{className:"overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:[e.jsx("button",{type:"button",className:"w-full cursor-pointer px-3 py-1.5 text-left hover:bg-[var(--interactive-hover)]","aria-expanded":I,onClick:()=>{r(N=>({...N,[c.info.id]:N[c.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:P?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[E?e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",w]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:P?U:O}),P&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:G})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:C})]})}),I&&e.jsx("div",{className:"border-t border-[var(--surface-subtle)] p-0",children:e.jsxs("div",{className:"group relative max-h-[26rem] w-full overflow-auto bg-[var(--surface-background)]",children:[e.jsx("div",{className:"absolute top-1 right-2 z-10 opacity-0 transition-opacity group-hover:opacity-100",children:e.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",onClick:N=>{N.stopPropagation(),u(c.info.id,q)},"aria-label":J?"Copied":"Copy JSON",title:J?"Copied":"Copy",children:J?e.jsx(B,{name:"check",className:"size-3.5"}):e.jsx(B,{name:"file-copy",className:"size-3.5"})})}),e.jsx(Tr,{language:"json",code:q,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},c.info.id)})})]})]})})},ko=Me(()=>Re(()=>import("./DiffView-Gh9wjthp.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117])).then(t=>({default:t.DiffView}))),No=Me(()=>Re(()=>import("./FilesView-BXp0yc0j.js"),__vite__mapDeps([118,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,115,116,99,100,84,85,86,87,88,89,90,91,92,93,94,95,96,97,119,120,111,112,113,114,121,122,81,82,83,98,101,102,103,104,105,106,107,123,124,125,126])).then(t=>({default:t.FilesView}))),Po=Me(()=>Re(()=>import("./GitView-BmNCkkoC.js"),__vite__mapDeps([127,24,1,2,9,4,3,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,114,128,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,115,116])).then(t=>({default:t.GitView}))),Eo=380,Ro=1400,Tn=600,To=100,Do=24,qt=t=>Number.isFinite(t)?Math.min(Ro,Math.max(Eo,Math.round(t))):Tn,Mo=t=>{const n=t?.parentElement?.clientWidth;return!n||n<=0?null:n},_o=(t,n)=>{if(!t)return"";const r=t.replace(/\\/g,"/"),a=n.replace(/\\/g,"/").replace(/\/+$/,"");return a&&r.startsWith(a+"/")?r.slice(a.length+1):r},Dn=(t,n=null)=>t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?vt(n).label:t==="terminal"?"Terminal":"Context",Ao=t=>{if(!t)return null;const n=t.replace(/\\/g,"/").trim();if(!n)return null;const r=n.split("/").filter(Boolean);return r.length===0?n:r[r.length-1]||null},Io=(t,n=null)=>{if(t.label)return t.label;if(t.mode==="file")return Ao(t.targetPath)||"Files";if(t.mode==="preview"){const r=t.targetPath;if(r)try{const a=new URL(r);return a.host||a.hostname||"Preview"}catch{}return"Preview"}return t.mode==="diff"?"Changes":Dn(t.mode,n)},Jt=(t,n=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(pt,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return e.jsx(ir,{className:"h-3.5 w-3.5"});if(t.mode==="git")return e.jsx(B,{name:vt(n).icon,className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(B,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(B,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(B,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(B,{name:"global",className:"h-3.5 w-3.5"})},Lo=(t,n)=>t.length<=n?t:`${t.slice(0,n-3)}...`,Oo=()=>{const t=Ge()??"",n=s.useMemo(()=>Ee(t),[t]),r=Y(b=>n?b.contextPanelByDirectory[n]:void 0),a=Y(b=>b.closeContextPanel),o=Y(b=>b.closeContextPanelTab),f=Y(b=>b.openContextPanelTab),x=Y(b=>b.toggleContextPanelExpanded),d=Y(b=>b.setContextPanelWidth),h=Y(b=>b.setActiveContextPanelTab),m=Y(b=>b.reorderContextPanelTabs),y=Te(b=>b.setSelectedPath),u=Y(b=>b.openContextPreview),l=Y(b=>b.contextEditorTreeVisible),R=Y(b=>b.toggleContextEditorTree),c=s.useMemo(()=>r?.tabs??[],[r?.tabs]),j=c.find(b=>b.id===r?.activeTabId)??c[c.length-1]??null,v=!!(r?.isOpen&&j),P=!!(v&&r?.expanded),[E,I]=s.useState(null),J=r?.width,Q=_r,Z=E??(typeof window<"u"?window.innerWidth:Tn*2),F=qt(J??Math.round(Q*Z)),w=hn(n||null),[C,U]=s.useState(!1),G=s.useRef(0),L=s.useRef(F),O=s.useRef(null),q=s.useRef(null),N=s.useRef(null),H=s.useRef(!1);s.useLayoutEffect(()=>{const b=N.current?.parentElement;if(!b||typeof ResizeObserver>"u")return;const S=new ResizeObserver(()=>{I(b.clientWidth||null)});return S.observe(b),I(b.clientWidth||null),()=>S.disconnect()},[]),s.useEffect(()=>{if(!v||H.current){H.current=v;return}const b=window.requestAnimationFrame(()=>{N.current?.focus({preventScroll:!0})});return H.current=!0,()=>window.cancelAnimationFrame(b)},[v]);const k=s.useRef(null),_=s.useRef(null),V=s.useCallback(()=>{_.current=null;const b=N.current,S=O.current;!b||S===null||b.style.setProperty("--oc-context-panel-width",`${S}px`)},[]);s.useEffect(()=>()=>{_.current!==null&&clearTimeout(_.current)},[]);const A=s.useCallback(b=>{const S=qt(b),ne=k.current;return ne===null?S:Math.min(S,Math.max(1,ne))},[]),X=s.useCallback(b=>{!v||P||!n||(q.current=b.pointerId,U(!0),G.current=b.clientX,L.current=F,O.current=F,k.current=Mo(N.current),document.documentElement.style.cursor="col-resize",b.preventDefault())},[n,P,v,F]),se=s.useCallback(()=>{const b=A(O.current??F);O.current=null,k.current=null,_.current!==null&&(clearTimeout(_.current),_.current=null),document.documentElement.style.cursor="",n&&d(n,b),U(!1),q.current=null},[A,n,d,F]);s.useEffect(()=>{if(!C)return;const b=re=>{if(q.current!==re.pointerId)return;const oe=G.current-re.clientX,W=A(L.current+oe);O.current!==W&&(O.current=W,_.current===null&&(_.current=setTimeout(V,To)))},S=re=>{q.current===re.pointerId&&se()},ne=()=>{se()};return window.addEventListener("pointermove",b),window.addEventListener("pointerup",S),window.addEventListener("pointercancel",S),window.addEventListener("blur",ne),()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",S),window.removeEventListener("pointercancel",S),window.removeEventListener("blur",ne)}},[V,A,se,C]),s.useEffect(()=>{C||(O.current=null,document.documentElement.style.cursor="")},[C]);const ie=s.useCallback(()=>{n&&a(n)},[a,n]),he=s.useCallback(()=>{n&&x(n)},[n,x]),ye=s.useCallback(b=>{b.key==="Escape"&&(Mr(b.target)||(b.preventDefault(),b.stopPropagation(),ie()))},[ie]);s.useEffect(()=>{if(!(!n||!j)&&j.mode==="file"&&j.targetPath){y(n,j.targetPath,{allowOutsideRoot:!0});return}},[j,n,y]);const pe=s.useCallback(b=>{!n||j?.mode!=="diff"||f(n,{mode:"diff",targetPath:j.targetPath,stagedDiff:b==="staged",diffScope:b})},[j,n,f]),xe=j?.mode==="file"||j?.mode==="preview",ce=s.useMemo(()=>j?c.filter(b=>b.mode===j.mode):[],[j,c]),M=s.useMemo(()=>ce.map(b=>{const S=Io(b,w),ne=Lo(S,Do),re=_o(b.targetPath,t);return{id:b.id,label:ne,icon:Jt(b,w),title:re?`${S}: ${re}`:S,closeLabel:`Close ${ne} tab`}}),[ce,t,w]),$=j?.mode==="context"?e.jsx(Co,{}):j?.mode==="git"?e.jsx(s.Suspense,{fallback:null,children:e.jsx(Po,{isActive:v})}):j?.mode==="preview"?e.jsx(so,{rawUrl:j.targetPath??"",onNavigate:b=>u(t,b)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(B,{name:"global",className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"Preview"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Use Project Actions or a terminal Preview button to open a preview."})]}),g=s.useMemo(()=>c.filter(b=>b.mode==="browser"),[c]),D=s.useMemo(()=>c.filter(b=>b.mode==="diff"),[c]),K=s.useMemo(()=>c.some(b=>b.mode==="terminal"),[c]),ae=s.useMemo(()=>c.some(b=>b.mode==="file"),[c]),de=s.useMemo(()=>c.some(b=>b.mode==="file"&&b.targetPath),[c]),me=j?.mode==="file",fe=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[xe?e.jsx(ar,{items:M,activeId:j?.id??null,onSelect:b=>{n&&h(n,b)},onClose:b=>{n&&o(n,b)},onReorder:(b,S)=>{n&&m(n,b,S)},layoutMode:"scrollable",variant:"default"}):e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[j?Jt(j,w):null,e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:j?Dn(j.mode,w):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[me?e.jsx(le,{type:"button",variant:"ghost",size:"sm",onClick:R,className:"h-7 w-7 p-0",title:"Toggle file tree","aria-label":"Toggle file tree","aria-pressed":l,children:e.jsx(B,{name:"layout-right",className:"h-3.5 w-3.5"})}):null,e.jsx(le,{type:"button",variant:"ghost",size:"sm",onClick:he,className:"h-7 w-7 p-0",title:P?"Collapse panel":"Expand panel","aria-label":P?"Collapse panel":"Expand panel",children:P?e.jsx(B,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):e.jsx(B,{name:"fullscreen",className:"h-3.5 w-3.5"})}),e.jsx(le,{type:"button",variant:"ghost",size:"sm",onClick:ie,className:"h-7 w-7 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(B,{name:"close",className:"h-3.5 w-3.5"})})]})]}),je=v?P?{"--oc-context-panel-width":E!==null?`${E}px`:"100%",width:E!==null?`${E}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${F}px`}:{"--oc-context-panel-width":`${F}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:N,"data-context-panel":"true",tabIndex:-1,inert:!v||void 0,className:ge("flex min-h-0 flex-col overflow-hidden bg-background",P?"absolute inset-y-0 right-0 z-20 min-w-0":"relative h-full flex-shrink-0",!v&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:ye,style:je,children:[v&&!P&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),v&&e.jsx("div",{"aria-hidden":"true",className:"absolute right-0 top-0 z-40 h-full w-px bg-border"}),!P&&e.jsx("div",{className:ge("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",C&&"bg-[var(--interactive-border)]"),onPointerDown:X,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:ge("relative z-10 flex h-full min-h-0 shrink-0 flex-col duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none","transition-[width,opacity]",!v&&"pointer-events-none select-none opacity-0"),style:{width:P?E!==null?`${E}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!v,children:[fe,e.jsxs("div",{className:ge("relative min-h-0 flex-1 overflow-hidden",C&&"pointer-events-none"),children:[ae?e.jsxs("div",{className:ge("absolute inset-0 flex",me?"flex":"hidden"),children:[e.jsx("div",{className:"h-full min-w-0 flex-1",children:de?e.jsx(s.Suspense,{fallback:null,children:e.jsx(No,{mode:"editor-only"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(B,{name:"file-code",className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"No file open"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Pick a file from the tree to start editing."})]})}),e.jsx(eo,{visible:l})]}):null,g.map(b=>e.jsx("div",{className:ge("absolute inset-0",j?.id!==b.id&&"hidden"),children:e.jsx(Hs,{initialUrl:b.targetPath??"",directory:n,tabID:b.id})},b.id)),v?D.filter(b=>j?.id===b.id).map(b=>e.jsx("div",{className:"absolute inset-0",children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(ko,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:b.diffScope??(b.stagedDiff?"staged":"working"),onDiffScopeChange:pe,targetFilePath:b.targetPath,flushContent:!0})})},b.id)):null,K?e.jsx("div",{className:ge("absolute inset-0",j?.mode==="terminal"?"block":"hidden"),children:e.jsx(on,{visible:v&&j?.mode==="terminal"})}):null,v&&!me&&j?.mode!=="browser"&&j?.mode!=="diff"&&j?.mode!=="terminal"?$:null]})]})]})},$o=150,Wo=500,Fo=[],Ae=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t),Je=(t,n)=>{if(!t||typeof t!="object")return;const r=t[n];return typeof r=="number"&&Number.isFinite(r)?r:void 0},Bo=t=>t>99?"99+":String(t),zo=t=>t>=90?"text-[var(--status-error)]":t>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",Uo=({surface:t,isActive:n,showActivityDot:r,label:a,description:o,badgeCount:f,badgeAriaLabel:x,badgeDescription:d,orderNumber:h,showOrderNumber:m,onSelect:y,chartPercentage:u,chartDetails:l})=>{const{attributes:R,listeners:c,setNodeRef:j,transform:v,transition:P,isDragging:E}=ys({id:t.id}),I=f!=null&&f>0?Bo(f):null;return e.jsx("div",{ref:j,style:{transform:bs.Translate.toString(v),transition:P},className:ge("relative",E&&"z-10 opacity-70"),children:e.jsxs(Oe,{delayDuration:$o,children:[e.jsx($e,{asChild:!0,children:e.jsxs("button",{type:"button",...R,...c,onClick:()=>y(t),"aria-label":x??a,"aria-pressed":n,className:ge("flex h-9 w-9 touch-none select-none items-center justify-center rounded-md transition-colors",n?"text-primary":"text-muted-foreground hover:text-foreground"),children:[t.id==="context"&&typeof u=="number"?e.jsx(At,{percentage:u,className:"size-[18px] -rotate-90"}):e.jsx(B,{name:t.icon,className:"h-[18px] w-[18px]"}),m&&h!=null?e.jsx("span",{"aria-hidden":"true",className:"absolute right-0 top-0 flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-muted px-1 text-[0.625rem] font-medium leading-none text-muted-foreground",children:h===10?"0":h}):I?e.jsx("span",{"aria-hidden":"true",className:"absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[0.625rem] font-semibold leading-none",style:{backgroundColor:"var(--status-info-background)",color:"var(--status-info)"},children:I}):r?e.jsx("span",{"aria-hidden":"true",className:"absolute right-1 top-1 h-1.5 w-1.5 rounded-full bg-[var(--status-info)]"}):null]})}),e.jsx(We,{side:"left",sideOffset:8,className:t.id==="context"&&l?"p-0 border-0 bg-transparent shadow-none":void 0,children:t.id==="context"&&l?e.jsx("div",{className:"w-[300px] overflow-hidden rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[e.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:e.jsx(At,{percentage:l.percentage,className:"size-[18px] -rotate-90"})}),e.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:a}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:l.hasData?e.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[e.jsxs("span",{className:ge("font-semibold",zo(l.percentage)),children:[l.percentage.toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:`${Ae(l.totalTokens)}/${Ae(l.contextLimit)}`})]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:"No data yet"})})]}),l.hasData?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ae(l.totalTokens)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ae(l.contextLimit)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ae(l.outputLimit)})]}),typeof l.cacheRead=="number"&&typeof l.cacheWrite=="number"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ae(l.cacheRead)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ae(l.cacheWrite)})]})]}):null,typeof l.cacheHitPercent=="number"?e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache hit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:`${l.cacheHitPercent.toFixed(1)}%`})]}):null]}):e.jsx("div",{className:"px-2.5 py-2 typography-micro text-muted-foreground",children:o})]})}):e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:a}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:o}),d?e.jsx("span",{className:"typography-micro text-muted-foreground",children:d}):null]})})]})})},Ho=()=>{const t=Ge(),n=t?Bn(t):"",r=Y(g=>n?g.contextPanelByDirectory[n]:void 0),a=Y(g=>g.contextRailOrder),o=Y(g=>g.setContextRailOrder),f=Y(g=>g.openContextSurface),x=Y(g=>g.shortcutOverrides),{screenWidth:d}=jt(),{git:h}=ft(),m=ln(n||null),y=hn(n||null),u=pn(g=>g.ensureStatus);s.useEffect(()=>{n&&u(n,h)},[n,u,h]);const l=s.useMemo(()=>zn("switch_context_surface",x),[x]),[R,c]=s.useState(!1);s.useEffect(()=>{const g=new Set;let D=null,K=!1;const ae=b=>b.length===1&&b>="0"&&b<="9",de=()=>{Et(l,g)?!K&&D===null&&(D=setTimeout(()=>c(!0),Wo)):(K=!1,D!==null&&(clearTimeout(D),D=null),c(!1))},me=b=>{if(g.add(b.key.toLowerCase()),ae(b.key)&&Et(l,g)){K=!0,D!==null&&(clearTimeout(D),D=null),c(!1);return}de()},fe=b=>{g.delete(b.key.toLowerCase()),de()},je=()=>{g.clear(),K=!1,D!==null&&(clearTimeout(D),D=null),c(!1)};return window.addEventListener("keydown",me,!0),window.addEventListener("keyup",fe,!0),window.addEventListener("blur",je),()=>{window.removeEventListener("keydown",me,!0),window.removeEventListener("keyup",fe,!0),window.removeEventListener("blur",je),D!==null&&clearTimeout(D)}},[l]);const j=us(Lt(ps,{activationConstraint:{distance:8}}),Lt(hs,{activationConstraint:{delay:200,tolerance:6}})),v=r?.tabs??Fo,P=v.find(g=>g.id===r?.activeTabId)??null,E=r?.isOpen?P?.mode??null:null,I=m?.files.length??0,J=Se(g=>g.currentSessionId),Q=Se(g=>!!g.newSessionDraft?.open),Z=Ie(g=>g.providers),F=Ie(g=>g.currentProviderId),w=Ie(g=>g.currentModelId),C=Ie(g=>g.getCurrentModel()),U=Ie(g=>g.getModelMetadata);Ie(g=>g.modelsMetadata.size);const G=Ar(s.useCallback(g=>J?g.sessionModelSelections.get(J)??null:null,[J])),L=cn(J??""),O=s.useMemo(()=>{for(let g=L.length-1;g>=0;g-=1){const D=L[g];if(D?.info.role==="assistant")try{if(ut(D).total>0)return D}catch{continue}}return null},[L]),N=s.useMemo(()=>{for(let g=L.length-1;g>=0;g-=1){const D=L[g]?.info;if(D.role!=="user")continue;const K=D.model,ae=K?.providerID??K?.providerId,de=K?.modelID??K?.modelId;if(typeof ae=="string"&&ae.trim()&&typeof de=="string"&&de.trim())return{providerID:ae,modelID:de}}return null},[L])??(()=>{const g=O?.info.model,D=g?.providerID??g?.providerId,K=g?.modelID??g?.modelId;return D&&K?{providerID:D,modelID:K}:null})()??(G?{providerID:G.providerId,modelID:G.modelId}:null)??(F&&w?{providerID:F,modelID:w}:null),k=(N?Z.find(g=>g.id===N.providerID):void 0)?.models.find(g=>g.id===N?.modelID),_=N?U(N.providerID,N.modelID):void 0,V=Je(k?.limit,"context")??_?.limit?.context??Je(C?.limit,"context")??0,A=Je(k?.limit,"output")??_?.limit?.output??Je(C?.limit,"output")??0,X=O?(()=>{try{return ut(O)}catch{return null}})():null,se=O?.info?.usage,ie=se?un(se):X?.total??0,he=!Q&&ie>0&&V>0?Math.min(ie/V*100,999):0,ye=he,pe=X?dn({input:X.input,cache:{read:X.cacheRead,write:X.cacheWrite}}):null,xe=pe?.hasInput?pe.percent:null,ce=s.useMemo(()=>{const g=!!O&&ie>0&&V>0;return{percentage:he,totalTokens:ie,contextLimit:V,outputLimit:A,cacheRead:X?.cacheRead??null,cacheWrite:X?.cacheWrite??null,cacheHitPercent:xe,hasData:g}},[X,xe,V,O,A,he,ie]),M=s.useMemo(()=>Ir({railOrder:a,tabs:v}),[a,d,v]),$=s.useCallback(g=>{const{active:D,over:K}=g;if(!K||D.id===K.id)return;const ae=Lr(Y.getState().contextRailOrder).map(fe=>fe.id),de=ae.indexOf(D.id),me=ae.indexOf(K.id);de===-1||me===-1||o(gs(ae,de,me))},[o]);return n?e.jsx("nav",{"aria-label":"Panel surfaces",className:"flex h-full w-11 flex-shrink-0 flex-col items-center gap-1 bg-background py-2",children:e.jsx(ms,{sensors:j,collisionDetection:fs,onDragEnd:$,children:e.jsx(xs,{items:M.map(g=>g.id),strategy:ws,children:M.map((g,D)=>{const K=g.id==="git"?vt(y):null,ae=K?{...g,...K}:g,de=ae.label,me=g.id==="git"&&y===!0?I:0,fe=me>0?me:null,je=g.id==="context";return e.jsx(Uo,{surface:ae,isActive:E===g.mode,showActivityDot:!1,label:de,description:ae.description,badgeCount:fe,badgeAriaLabel:fe!==null?fe===1?`${de}, ${fe} changed file`:`${de}, ${fe} changed files`:null,badgeDescription:fe!==null?fe===1?`${fe} changed file`:`${fe} changed files`:null,chartPercentage:je?ye:void 0,chartDetails:je?ce:void 0,orderNumber:D+1,showOrderNumber:R,onSelect:b=>f(n,b.mode)},g.id)})})})}):null},Vo=(t,n)=>!t||n.length===0?"":JSON.stringify([t,n]),Ko=(t,n,r,a)=>!r||a!==r||t.length===0?[]:Ve(t,n,o=>o.name,{limit:10,threshold:.4}),Xo=new Set,dt=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),r=n.startsWith("//");let a=n.replace(/\/+/g,"/");r&&!a.startsWith("//")&&(a=`/${a}`);const o=a==="/",f=/^[A-Za-z]:\/$/.test(a);return!o&&!f&&(a=a.replace(/\/+$/,"")),a},Yo=()=>{const t=Y(p=>p.isCommandPaletteOpen),n=Y(p=>p.setCommandPaletteOpen),r=Y(p=>p.setActiveMainTab),a=Y(p=>p.setSettingsDialogOpen),o=Y(p=>p.setSettingsPage),f=Y(p=>p.setSessionSwitcherOpen),x=Y(p=>p.toggleSidebar),d=Y(p=>p.openContextOverview),h=Y(p=>p.openContextSurface),m=Y(p=>p.openContextFile),y=Y(p=>p.shortcutOverrides),u=Se(p=>p.openNewSessionDraft),l=Se(p=>p.setCurrentSession),R=Or({archived:!1}),c=$r(s.useCallback(p=>t?p.ids:Xo,[t])),j=Wr(s.useCallback(p=>t?p.rankById:Fr,[t])),v=Un(p=>p.currentDirectory),P=It(p=>p.getActiveProject()),E=It(p=>p.projects),I=Ge(),J=Hn(p=>p.searchFiles),{files:Q,git:Z}=ft(),F=pn(p=>p.ensureStatus),{isMobile:w}=jt(),C=s.useMemo(()=>I?dt(I):null,[I]),[U,G]=s.useState(""),O=Br(U,200).trim(),q=U.trim();s.useEffect(()=>{t&&G("")},[t]),s.useEffect(()=>{if(!t||!Z)return;const p=setTimeout(()=>{const i=new Set;for(const T of R){const ee=ot(T);!ee||i.has(ee)||(i.add(ee),F(ee,Z))}},0);return()=>clearTimeout(p)},[t,R,Z,F]);const N=s.useCallback(()=>n(!1),[n]),H=s.useCallback(p=>()=>{N(),p()},[N]),k=s.useMemo(()=>{const p=[{id:"new-session",title:"New Session",icon:e.jsx(B,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New Session",onSelect:H(()=>{r("chat"),f(!1),u()})},{id:"add-project",title:"Add Project",icon:e.jsx(B,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add Project",onSelect:H(()=>{zr.requestDirectoryDialog()})},{id:"toggle-sidebar",title:w?"Show Session Switcher":"Toggle Sidebar",icon:e.jsx(B,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:w?"Show Session Switcher":"Toggle Sidebar",onSelect:H(()=>{if(w){const{isSessionSwitcherOpen:i}=Y.getState();f(!i)}else x()})},{id:"toggle-terminal",title:"Toggle Terminal",icon:e.jsx(B,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle Terminal",onSelect:H(()=>{v&&h(v,"terminal")})},{id:"context-usage",title:"Show Context Usage",icon:e.jsx(B,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show Context Usage",onSelect:H(()=>{v&&d(v)})},{id:"open-settings",title:"Open Settings...",icon:e.jsx(B,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open Settings...",onSelect:H(()=>a(!0))}];return Vn()&&p.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat Window",icon:e.jsx(B,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat Window",onSelect:H(()=>{Zt("desktop_open_draft_mini_chat_window",{directory:dt(v||P?.path||""),projectId:P?.id??null}).catch(i=>{console.warn("[command-palette] failed to open draft mini chat window",i)})})}),p},[H,w,r,f,u,x,h,v,d,a,P?.id,P?.path]),_=s.useMemo(()=>{const p=Kn();return{isWeb:!p&&Xn(),isDesktop:p,isMobile:w}},[w]),V=s.useMemo(()=>lr.filter(p=>p.slug!=="home").filter(p=>p.isAvailable?p.isAvailable(_):!0).map(p=>{const i=cr(p.slug)??"settings-3",T=(p.keywords??[]).join(" ");return{id:`settings:${p.slug}`,title:p.title,icon:e.jsx(B,{name:i,className:"mr-2 h-4 w-4"}),searchText:`${p.title} ${p.group} ${T}`,onSelect:H(()=>{o(p.slug),a(!0)})}}),[_,H,o,a]),A=s.useMemo(()=>Ur(R,c,j),[R,c,j]),X=Hr(),se=s.useCallback((p,i)=>i&&X.get(i)?.trim()||null,[X]),[ie,he]=s.useState([]),[ye,pe]=s.useState(""),xe=Vo(C,O);s.useEffect(()=>{if(!t){he([]),pe("");return}if(!xe){he([]),pe("");return}if(!C){he([]),pe("");return}let p=!1;return J(C,O,10,{type:"file"}).then(i=>{p||(he(i.map(T=>({path:dt(T.path),name:T.name,relativePath:T.relativePath}))),pe(xe))}).catch(()=>{p||(he([]),pe(xe))}),()=>{p=!0}},[t,C,O,xe,J]);const ce=q.length>0,M=s.useMemo(()=>ce?Ve(k,q,p=>p.searchText,{limit:7,noFuzzy:!0}):k.map(p=>({item:p,score:0})),[k,q,ce]),$=s.useMemo(()=>ce?Ve(V,q,p=>p.searchText,{limit:7,noFuzzy:!0}):[],[V,q,ce]),g=s.useMemo(()=>ce?Ve(A,q,p=>p.title||"",{limit:7,threshold:.2}):A.slice(0,5).map(p=>({item:p,score:0})),[A,q,ce]),D=s.useMemo(()=>t?Ko(ie,O,xe,ye):[],[t,ie,ye,xe,O]),K=t&&xe.length>0&&ye!==xe,ae=s.useMemo(()=>{if(!ce)return[];const p=E.map(i=>({...i,displayName:i.label||i.path.split("/").pop()||i.path,searchText:`${i.label||""} ${i.path}`}));return Ve(p,q,i=>i.searchText,{limit:7,threshold:.4})},[E,q,ce]),de=M.map(p=>p.item),me=$.map(p=>p.item),fe=g.map(p=>p.item),je=ce?D.map(p=>p.item):[],b=ce?ae.map(p=>p.item):[],S=s.useMemo(()=>{if(!ce)return["commands","sessions"];const p=T=>T.length?T[0].score:1/0,i=[{key:"commands",score:p(M)},{key:"settings",score:p($)},{key:"sessions",score:p(g)},{key:"files",score:p(D)},{key:"projects",score:p(ae)}];return i.sort((T,ee)=>T.score-ee.score),i.map(T=>T.key)},[ce,M,$,g,D,ae]),ne=s.useCallback(p=>{N(),l(p.id,ot(p))},[N,l]),re=s.useCallback(async p=>{if(!C)return;const i=await mn(Q,p,{directory:C});if(!i.ok){ve.error(fn(i.reason));return}m(C,p),N()},[C,Q,m,N]),oe=s.useCallback((p,i)=>{N(),u({selectedProjectId:p,directoryOverride:i})},[N,u]),W=s.useCallback(p=>nn(rn(p,y)),[y]);return e.jsxs(gt,{open:t,onOpenChange:n,children:[e.jsxs(wt,{className:"sr-only",children:[e.jsx(yt,{children:"Command Palette"}),e.jsx(bt,{children:"Search files, sessions, and commands."})]}),e.jsx(xt,{className:"overflow-hidden p-0",showCloseButton:!0,children:e.jsxs(Vr,{shouldFilter:!1,className:"[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta",children:[e.jsx(Kr,{value:U,onValueChange:G,placeholder:"Search files, sessions, commands..."}),e.jsxs(Xr,{children:[e.jsx(Yr,{children:"No results found."}),S.map(p=>p==="commands"&&de.length>0?e.jsx(Ue,{children:de.map(i=>e.jsxs(He,{value:i.id,onSelect:i.onSelect,children:[i.icon,e.jsx("span",{children:i.title}),i.shortcutId?e.jsx(Gr,{children:W(i.shortcutId)}):null]},i.id))},"commands"):p==="settings"&&me.length>0?e.jsx(Ue,{children:me.map(i=>e.jsxs(He,{value:i.id,onSelect:i.onSelect,children:[i.icon,e.jsx("span",{children:i.title})]},i.id))},"settings"):p==="sessions"&&fe.length>0?e.jsx(Ue,{children:fe.map(i=>{const T=xn(i),ee=ot(i),z=se(i.id,ee);return e.jsxs(He,{value:`session:${i.id}`,onSelect:()=>ne(i),children:[e.jsx(B,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:T}),z?e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[e.jsx(B,{name:"git-branch",className:"h-3 w-3"}),e.jsx("span",{className:"truncate max-w-[160px]",children:z})]}):null]},i.id)})},"sessions"):p==="files"&&je.length>0?e.jsx(Ue,{children:je.map(i=>{const T=Yn(i.relativePath||i.name,{maxLength:80});return e.jsxs(He,{value:`file:${i.path}`,onSelect:()=>{re(i.path)},children:[e.jsx(pt,{filePath:i.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":i.relativePath,children:T})]},`file:${i.path}`)})},"files"):p==="projects"&&b.length>0?e.jsx(Ue,{children:b.map(i=>{const T=i.displayName;return e.jsxs(He,{value:`project:${i.id}`,onSelect:()=>oe(i.id,i.path),children:[e.jsx(B,{name:"folder",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:T}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:i.path})]},`project:${i.id}`)})},"projects"):null),K?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]})})]})},Go=(t,n,r)=>qn(t)?nn(rn(t,r)):n,qo=()=>{const t=Y(f=>f.isHelpDialogOpen),n=Y(f=>f.setHelpDialogOpen),r=Y(f=>f.shortcutOverrides),a=Gn(),o=[{categoryKey:"Navigation & Commands",items:[{id:"open_command_palette",descriptionKey:"Open Command Palette",icon:"command",keys:""},{id:"open_help",descriptionKey:"Show Keyboard Shortcuts (this dialog)",icon:"question",keys:""},{id:"toggle_sidebar",descriptionKey:"Toggle Session Sidebar",icon:"layout-left",keys:""},{id:"add_selection_to_chat",descriptionKey:"Add Selection to Chat",icon:"add",keys:""},{id:"open_model_selector",descriptionKey:"Open Model Selector",icon:"ai-generate-2",keys:""},{keys:["↑↓"],descriptionKey:"Navigate Models (in picker)",icon:"ai-generate-2"},{keys:["←→"],descriptionKey:"Adjust Thinking Mode (in picker, when supported)",icon:"brain-ai-3"},{id:"cycle_thinking_variant",descriptionKey:"Cycle thinking (global shortcut)",icon:"brain-ai-3",keys:""},{keys:[`Shift + Alt + ${a} + N`],descriptionKey:"New Window (desktop only)",icon:"window"}]},{categoryKey:"Session Management",items:[{id:"new_chat",descriptionKey:"Create New Session",icon:"add",keys:""},{id:"focus_input",descriptionKey:"Focus Chat Input",icon:"text",keys:""},{id:"cycle_session_folder",descriptionKey:"Cycle session folder",icon:"folder-open",keys:""},{id:"cycle_draft_folder",descriptionKey:"Cycle draft folder",icon:"folder-3",keys:""},{id:"open_timeline_dialog",descriptionKey:"Open conversation timeline",icon:"history",keys:""},{id:"abort_run",descriptionKey:"Abort active run (double press)",icon:"close-circle",keys:""}]},{categoryKey:"Panels",items:[{id:"open_right_sidebar",descriptionKey:"Open right sidebar",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{keys:[`${a} + 1...0`],descriptionKey:"Switch Context Panel Surface (number key)",icon:"layout-right"}]},{categoryKey:"Interface",items:[{id:"cycle_theme",descriptionKey:"Cycle Theme (Light → Dark → System)",icon:"palette",keys:""},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"Open Settings",icon:"settings-3",keys:""}]}];return e.jsx(gt,{open:t,onOpenChange:n,children:e.jsxs(xt,{className:"w-[92vw] max-w-[1120px] h-[84vh] max-h-[900px] flex flex-col overflow-hidden",children:[e.jsxs(wt,{children:[e.jsxs(yt,{className:"flex items-center gap-2",children:[e.jsx(B,{name:"command",className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(bt,{children:"Use these keyboard shortcuts to navigate PiChamber efficiently"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:e.jsx("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-x-10",children:o.map(f=>e.jsxs("div",{className:"min-w-0 break-inside-avoid",children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:f.categoryKey}),e.jsx("div",{className:"space-y-1",children:f.items.map(x=>{const d=x.id?Go(x.id,Array.isArray(x.keys)?x.keys[0]:x.keys,r):Array.isArray(x.keys)?x.keys:x.keys.split(" / ");return e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[x.icon&&e.jsx(B,{name:x.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:x.descriptionKey})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(d)?d:[d]).map((h,m)=>e.jsxs(s.Fragment,{children:[m>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:h})]},`${h}-${m}`))})]},x.id||x.descriptionKey)})})]},f.categoryKey))})})]})})},Jo=s.createContext(null),Qo=({children:t,value:n})=>e.jsx(Jo.Provider,{value:n,children:t}),Qt=Me(()=>Re(()=>import("./GitView-BmNCkkoC.js"),__vite__mapDeps([127,24,1,2,9,4,3,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,114,128,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,115,116])).then(t=>({default:t.GitView}))),Zo=Me(()=>Re(()=>import("./DiffView-Gh9wjthp.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117])).then(t=>({default:t.DiffView}))),ea=Me(()=>Re(()=>import("./FilesView-BXp0yc0j.js"),__vite__mapDeps([118,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,115,116,99,100,84,85,86,87,88,89,90,91,92,93,94,95,96,97,119,120,111,112,113,114,121,122,81,82,83,98,101,102,103,104,105,106,107,123,124,125,126])).then(t=>({default:t.FilesView}))),ta=Me(()=>Re(()=>import("./DiagramView-DdipXAq8.js"),__vite__mapDeps([129,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,119,120])).then(t=>({default:t.DiagramView}))),na=Me(()=>Re(()=>import("./SettingsView-CFzxRzUq.js").then(t=>t.a),__vite__mapDeps([130,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,114,131,132,128])).then(t=>({default:t.SettingsView}))),ra=Me(()=>Re(()=>import("./SettingsWindow-BEjHL1ET.js"),__vite__mapDeps([133,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,130,111,112,113,114,131,132,128])).then(t=>({default:t.SettingsWindow}))),sa=()=>{const t=Y(k=>k.isSidebarOpen),n=Y(k=>k.activeMainTab),r=Y(k=>k.setIsMobile),a=Y(k=>k.isSessionSwitcherOpen),o=Y(k=>k.isSettingsDialogOpen),f=Y(k=>k.setSettingsDialogOpen),[x,d]=s.useState(!1);s.useEffect(()=>{o&&d(!0)},[o]),s.useEffect(()=>{const k=()=>Y.getState().closeMainSurfaces(),_=Se.subscribe((A,X)=>{const se=!!A.currentSessionId&&A.currentSessionId!==X.currentSessionId,ie=!!A.newSessionDraft?.open&&A.newSessionDraft!==X.newSessionDraft;(se||ie)&&k()}),V=Y.subscribe((A,X)=>{A.activeMainTab!==X.activeMainTab&&k()});return()=>{_(),V()}},[]);const{isMobile:h}=jt(),m=s.useRef(!1),[y,u]=s.useState(!1),[l,R]=s.useState(!1),[c,j]=s.useState(!1),[v,P]=s.useState(!1),E=s.useCallback(k=>{u(k),Y.getState().setSessionSwitcherOpen(k)},[]),I=s.useRef(typeof window>"u"?0:window.innerWidth),J=s.useRef(null),Q=s.useRef(!1),Z=s.useRef(!1),F=s.useRef(!1),w=s.useRef(null),C=s.useRef(null),U=Ot(-I.current),G=Ce.useRef(0),L=Ot(I.current),O=Ce.useRef(0);Ce.useEffect(()=>{h&&(G.current=window.innerWidth,O.current=window.innerWidth)},[h]),Ce.useEffect(()=>{if(!h)return;const k=()=>{const _=window.innerWidth;G.current=_,O.current=_,y||U.get()<-10&&U.set(-_),l||L.get()>10&&L.set(_)};return window.addEventListener("resize",k),window.addEventListener("orientationchange",k),()=>{window.removeEventListener("resize",k),window.removeEventListener("orientationchange",k)}},[h,U,L,y,l]),Ce.useEffect(()=>{if(!h){j(!1);return}y&&j(!0);const k=G.current||I.current||(typeof window<"u"?window.innerWidth:0),_=qe(U,y?0:-k,{type:"spring",stiffness:400,damping:35,mass:.8});return w.current=_,()=>_.stop()},[y,h,U]),Ce.useEffect(()=>{if(!h){P(!1);return}l&&P(!0);const k=O.current||I.current||(typeof window<"u"?window.innerWidth:0),_=qe(L,l?0:k,{type:"spring",stiffness:400,damping:35,mass:.8});return C.current=_,()=>_.stop()},[h,l,L]),Ce.useEffect(()=>{if(h)return U.on("change",k=>{const _=G.current||I.current,V=y||k>-_+.5;j(A=>A===V?A:V)})},[h,U,y]),Ce.useEffect(()=>{if(h)return L.on("change",k=>{const _=O.current||I.current,V=l||k<_-.5;P(A=>A===V?A:V)})},[h,l,L]),Ce.useEffect(()=>{h&&!a&&y&&E(!1)},[a,h,y,E]),Ce.useEffect(()=>{if(!h){m.current=!1;return}m.current||(m.current=!0,E(!1),R(!1))},[h,E]),Ce.useEffect(()=>{if(!h||n!=="chat"||y||l||o)return;let k=!1,_;const V=A=>{_=window.setTimeout(()=>{if(k)return;const X=Se.getState(),se=Y.getState();if(!(se.activeMainTab!=="chat"||se.isSettingsDialogOpen||X.currentSessionId||X.newSessionDraft?.open)){if(X.isLoading){V(250);return}X.openNewSessionDraft({automatic:!0})}},A)};return V(500),()=>{k=!0,_!==void 0&&window.clearTimeout(_)}},[n,h,o,y,l]),Ce.useEffect(()=>{!h||!o||(E(!1),R(!1))},[h,o,E]),s.useEffect(()=>{Y.getState().isMobile!==h&&r(h)},[h,r]);const q=s.useCallback(()=>{y&&E(!1),R(!l)},[y,l,E]);dr(J,{enabled:h,leftOpen:y,rightOpen:l,leftWidth:()=>G.current||I.current||(typeof window<"u"?window.innerWidth:0),rightWidth:()=>O.current||I.current||(typeof window<"u"?window.innerWidth:0),onLeftProgress:k=>{const _=G.current||I.current||(typeof window<"u"?window.innerWidth:0);U.set(_*(k-1))},onRightProgress:k=>{const _=O.current||I.current||(typeof window<"u"?window.innerWidth:0);L.set(_*(1-k))},onLeftOpen:()=>{l&&R(!1),E(!0)},onLeftClose:()=>E(!1),onRightOpen:()=>{y&&E(!1),R(!0)},onRightClose:()=>R(!1),onDragStart:k=>{Q.current=!0,k==="left"?(Z.current=y,w.current?.stop(),c||j(!0)):(F.current=l,C.current?.stop(),v||P(!0))},onDragEnd:(k,_)=>{if(Q.current=!1,k==="left"&&typeof _=="boolean"){const V=Z.current;if(_===V){const A=G.current||I.current||(typeof window<"u"?window.innerWidth:0),X=qe(U,V?0:-A,{type:"spring",stiffness:400,damping:35,mass:.8});w.current=X}}if(k==="right"&&typeof _=="boolean"){const V=F.current;if(_===V){const A=O.current||I.current||(typeof window<"u"?window.innerWidth:0),X=qe(L,V?0:A,{type:"spring",stiffness:400,damping:35,mass:.8});C.current=X}}}});const N=s.useMemo(()=>{if(!h&&n!=="terminal"&&n!=="diagram"||h&&n==="git"&&(l||v))return null;switch(n){case"git":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Qt,{isActive:!0})});case"diff":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Zo,{})});case"terminal":return e.jsx(on,{});case"files":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(ea,{})});case"diagram":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(ta,{})});default:return null}},[n,h,v,l]),H=n==="chat";return e.jsxs(ur,{children:[e.jsx(hr,{}),e.jsxs("div",{"data-page-scroll-lock":"true",className:ge("main-content-safe-area",h?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(Yo,{}),e.jsx(qo,{}),e.jsx(pr,{}),h?e.jsxs(Qo,{value:{leftDrawerOpen:y,rightDrawerOpen:l,toggleLeftDrawer:()=>{const k=!y;l&&R(!1),E(k)},toggleRightDrawer:q,leftDrawerX:U,rightDrawerX:L,leftDrawerWidth:G,rightDrawerWidth:O,setMobileLeftDrawerOpen:E,setRightSidebarOpen:R},children:[!o&&e.jsx(Rt,{onToggleLeftDrawer:()=>{const k=!y;l&&R(!1),E(k)},onToggleRightDrawer:()=>{q()},leftDrawerOpen:y,rightDrawerOpen:l}),e.jsx("div",{"data-page-scroll-lock":"true",className:ge("flex flex-1 overflow-hidden relative",o&&"hidden"),children:e.jsxs("main",{ref:J,className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:[e.jsx("div",{className:ge("absolute inset-0",!H&&"invisible"),children:e.jsx(Ne,{children:e.jsx(Tt,{active:H&&!o})})}),N&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ne,{children:N})}),e.jsx(Ne,{children:e.jsx(Dt,{})}),e.jsx($t.div,{className:ge("absolute inset-0 z-20 bg-sidebar",!c&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:U},"aria-hidden":!y,children:e.jsx(Ne,{children:e.jsx(Mt,{mobileVariant:!0,isVisible:c})})}),e.jsx($t.div,{className:ge("absolute inset-0 z-20 bg-sidebar",!v&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:L},"aria-hidden":!l,children:e.jsx(Ne,{children:l||v?e.jsx(s.Suspense,{fallback:null,children:e.jsx(Qt,{isActive:l})}):null})})]})}),o&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:e.jsx(Ne,{children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(na,{onClose:()=>f(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(mr,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(vs,{isOpen:t,isMobile:h,children:e.jsx(Mt,{isVisible:t})}),e.jsxs("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden bg-background","data-page-scroll-lock":"true",children:[e.jsx(Rt,{}),e.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden bg-background","data-page-scroll-lock":"true",children:[e.jsx("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden border-t border-border bg-background","data-page-scroll-lock":"true",children:e.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden","data-page-scroll-lock":"true",children:e.jsxs("div",{className:"relative flex flex-1 min-h-0 min-w-0 overflow-hidden","data-page-scroll-lock":"true","data-chat-area":"true",children:[e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[e.jsx("div",{className:ge("absolute inset-0",!H&&"invisible"),children:e.jsx(Ne,{children:e.jsx(Tt,{active:H&&!o})})}),N&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ne,{children:N})}),e.jsx(Ne,{children:e.jsx(Dt,{})})]}),e.jsx(Oo,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(Ne,{children:e.jsx(Ho,{})})})]})]})]}),x?e.jsx(s.Suspense,{fallback:null,children:e.jsx(ra,{open:o,onOpenChange:f})}):null]})]})]})},oa=()=>(Zr(),gr(),e.jsxs(xr,{children:[e.jsx(es,{embeddedBackgroundWorkEnabled:!0}),e.jsx(ts,{}),e.jsx(sa,{}),e.jsx(wr,{}),e.jsx(ns,{}),e.jsx(rs,{})]}));function aa({apis:t}){const n=t??sn(),[r,a]=s.useState(0);return s.useEffect(()=>Jn(o=>{o.runtimeKey!==o.previousRuntimeKey&&(fr(o),a(f=>f+1))}),[]),s.useEffect(()=>{Qn()},[r]),s.useEffect(()=>{n&&Zn(n)},[n]),n?e.jsx(Ne,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(qr,{apis:n,children:e.jsx(Jr,{children:e.jsx(Qr,{children:e.jsx(oa,{})})},r)})})}):e.jsx(Ne,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const Mn=document.getElementById("root");if(!Mn)throw new Error("Root element not found");_n.createRoot(Mn).render(e.jsx(Ce.StrictMode,{children:e.jsx(ss,{children:e.jsx(os,{children:e.jsx(aa,{apis:sn()??void 0})})})}));
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SessionSwitcherDropdown-Cgw2mQIO.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/useAppFontEffects-8ZU-TTIW.js","assets/vendor-zustand-GVb4H8HE.js","assets/index-ivrh3jfy.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-CzO3ooje.css","assets/vendor-base-ui-vkqQ2P9o.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-CBaS2Ank.js","assets/vendor-dnd-kit-core-CP8ck10N.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-B-Icjoj4.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-B_0wrsbo.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-DYppkHEk.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js"])))=>i.map(i=>d[i]);
2
- import{j as e,R as a,r as pe,e as we}from"./vendor-react-B5Z1Mdn3.js";import"./vendor-katex-CNckGUMB.js";import{c as V,f as J,h as ve,j as Y,u as oe,k as z,l as je,m as be,o as le,p as Se,q as Ie,s as Ce}from"./index-ivrh3jfy.js";import{u as Ne,a as Pe,s as De,b as Me,c as ke}from"./usePushVisibilityBeacon-zYd3ppNh.js";import{C as Ee,I as K,M as _e,E as Le,F as Oe,G as Ae,H as Te,J as Re,k as S,K as Be,c as ie,L as w,N as ae,O as Fe,j as ze,Q as Ue,R as $e,S as We,W as de,U as ue,V as me,X as He,Y as Ge,t as Ve,Z as Ke,_ as Je,$ as qe,a0 as Qe,a1 as Xe,a2 as Ye,a3 as Ze,a4 as et,a5 as tt,a6 as rt,a7 as st,a8 as nt,a9 as ot}from"./useAppFontEffects-8ZU-TTIW.js";import{_ as it}from"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-CBaS2Ank.js";import"./vendor-dnd-kit-core-CP8ck10N.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-B-Icjoj4.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-B_0wrsbo.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-DYppkHEk.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-CfplGuM0.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";const at=({mode:t,children:s})=>e.jsx(Ee.Provider,{value:t,children:s}),ct=Te,lt=Re,dt=({totalTokens:t,percentage:s,colorPercentage:n,contextLimit:c,outputLimit:i,size:m="default",isMobile:l=!1,hideIcon:M=!1,showPercentIcon:L=!1,className:h,valueClassName:p,percentIconClassName:k,onClick:N,pressed:E=!1,cacheRead:g,cacheWrite:I,cacheHitPercent:v})=>{const[P,j]=a.useState(!1),_=typeof n=="number"?n:s,o=ct(s)??0,y=lt(_),x=y==="critical"?"var(--status-error)":y==="warn"?"var(--status-warning)":"var(--status-success)",d=b=>b>=1e6?`${(b/1e6).toFixed(1)}M`:b>=1e3?`${(b/1e3).toFixed(1)}K`:b.toFixed(1).replace(/\.0$/,""),U=b=>b>=90?"text-status-error":b>=75?"text-status-warning":"text-status-success",f=20,$=3,W=(f-$)/2,q=2*Math.PI*W,ce=q*(1-o/100),H=typeof i=="number"?Math.max(i,0):0,O=typeof g=="number"&&typeof I=="number",Q=O?Math.max(0,g):0,Z=O?Math.max(0,I):0,R=typeof v=="number"&&Number.isFinite(v),T=[`Used tokens: ${d(t)}`,`Context limit: ${d(c)}`,`Output limit: ${d(H)}`,...O?[`Cache read: ${d(Q)}`,`Cache write: ${d(Z)}`]:[],...R?[`Cache hit: ${v.toFixed(1)}%`]:[],`${Math.min(s,999).toFixed(1)}% used`],A=!l&&typeof N=="function",B=e.jsxs(e.Fragment,{children:[!l&&!M&&e.jsx(K,{name:"donut-chart",className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:V("font-medium inline-flex items-center gap-1.5",p),children:L?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{viewBox:`0 0 ${f} ${f}`,className:V("h-3.5 w-3.5 -rotate-90",k),role:"progressbar","aria-valuenow":Math.round(o),"aria-valuemin":0,"aria-valuemax":100,children:[e.jsx("circle",{cx:f/2,cy:f/2,r:W,fill:"none",stroke:"var(--interactive-border)",strokeWidth:$}),e.jsx("circle",{cx:f/2,cy:f/2,r:W,fill:"none",stroke:x,strokeWidth:$,strokeLinecap:"round",strokeDasharray:q,strokeDashoffset:ce,className:"transition-[stroke-dashoffset,stroke] duration-300"})]}),e.jsxs("span",{className:"text-foreground",children:[Math.min(s,999).toFixed(1),"%"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:U(_),children:Math.min(s,999).toFixed(1)}),"%"]})})]}),C=V("app-region-no-drag flex items-center gap-1.5 select-none",m==="compact"?"typography-micro":"typography-meta",A?V("rounded-md px-2 py-1.5 text-foreground transition-colors","hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"):"text-muted-foreground/60",h),D=A?e.jsx("button",{type:"button",className:C,"aria-label":"Context usage","aria-pressed":E,onClick:N,children:B}):e.jsx("div",{className:C,"aria-label":"Context usage",onClick:l?()=>j(!0):void 0,children:B});return l?e.jsxs(e.Fragment,{children:[D,e.jsx(_e,{open:P,onClose:()=>j(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:d(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:d(c)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:d(H)})]}),O?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:d(Q)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:d(Z)})]})]}):null,R?e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache hit"}),e.jsxs("span",{className:"typography-meta text-foreground font-medium",children:[v.toFixed(1),"%"]})]}):null,e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:V("typography-meta font-semibold",U(_)),children:[Math.min(s,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:D}),e.jsx(Ae,{children:e.jsx("div",{className:"space-y-0.5",children:T.map(b=>e.jsx("p",{className:"typography-micro leading-tight",children:b},b))})})]})},ut=a.lazy(()=>it(()=>import("./SessionSwitcherDropdown-Cgw2mQIO.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79])).then(t=>({default:t.SessionSwitcherDropdown}))),mt=t=>{const s=typeof t=="string"?t.trim():"";if(!s)return"";const n=typeof window<"u"?window.__PICHAMBER_HOME__:"";if(n&&s===n)return"~";if(n&&s.startsWith(`${n}/`))return`~/${s.slice(n.length+1)}`;const c=s.split("/").filter(Boolean);return c.length<=3?s:`.../${c.slice(-3).join("/")}`},re=t=>{const s=typeof t=="string"?t.trim():"";if(!s)return"";const n=s.replace(/\\/g,"/");return n==="/"?"/":n.replace(/\/+$/,"")},pt=({mode:t})=>{const s=S(r=>r.currentSessionId),n=S(r=>!!r.newSessionDraft?.open),c=S(r=>r.newSessionDraft?.selectedProjectId??null),i=J(r=>r.currentDirectory),m=ie(r=>r.projects),l=ie(r=>r.getActiveProject()),M=w(r=>r.getCurrentModel),L=w(r=>r.providers),h=ae(),p=Fe(s??""),k=ze(),N=Ue(r=>r.ensureStatus),E=S(r=>r.newSessionDraft?.open?re(r.newSessionDraft.directoryOverride??""):""),[g,I]=a.useState(!1),v=typeof window<"u"?window.__PICHAMBER_MACOS_MAJOR__??0:0,P=Number.isFinite(v)&&v>0,{usesFramelessChrome:j,side:_}=$e(),o=P?v>=26?"h-12":v<=15?"h-14":"":"",y=a.useMemo(()=>s?h.find(r=>r.id===s)??null:null,[s,h]);a.useEffect(()=>{ve()&&Y("desktop_get_window_pinned").then(r=>{typeof r?.pinned=="boolean"&&I(r.pinned)})},[]);const x=y?.title?.trim()||(n||t==="draft"?"New session":"Session"),d=re(y?.directory??null),U=re(i),f=d||E||U,$=mt(f);a.useEffect(()=>{f&&N(f,k.git).catch(()=>{})},[N,f,k.git]);const W=a.useMemo(()=>{const r=f;return r?m.map(u=>({...u,normalizedPath:re(u.path)})).filter(u=>u.normalizedPath&&(u.normalizedPath===r||r.startsWith(`${u.normalizedPath}/`))).sort((u,G)=>G.path.length-u.path.length)[0]??null:null},[f,m]),q=a.useMemo(()=>{const r=W??l;if(!r)return $||"PiChamber";const u=r.label?.trim();return u||(r.path.split(/[\\/]/).filter(Boolean).at(-1)??r.path)},[l,$,W]),H=We(f||null),O=H&&H!=="HEAD"?H:null,Q=M(),Z=a.useMemo(()=>{for(let r=p.length-1;r>=0;r-=1){const u=p[r];if(u.role!=="assistant"||typeof u.providerID!="string"||typeof u.modelID!="string")continue;const te=L.find(X=>X.id===u.providerID)?.models.find(X=>X.id===u.modelID);if(te)return te}},[p,L]),R=Q?.limit?Q:Z,T=R&&typeof R.limit=="object"&&R.limit!==null?R.limit:null,A=T&&typeof T.context=="number"?T.context:0,B=T&&typeof T.output=="number"?T.output:0,C=a.useMemo(()=>{if(!s||p.length===0)return null;let r,u;for(let se=p.length-1;se>=0;se-=1){const ne=p[se];if(ne.role!=="assistant")continue;const F=ne.tokens;if(!F)continue;if(F.input+F.output+F.reasoning+(F.cache?.read??0)+(F.cache?.write??0)>0){r=F,u=ne.id;break}}if(!r)return null;const G=r.input+r.output+r.reasoning+(r.cache?.read??0)+(r.cache?.write??0),te=A>0?A:2e5,X=A>0?Math.round(G/A*100):0,ye=B>0?Math.round(r.output/B*100):void 0;return{totalTokens:G,percentage:X,contextLimit:A||0,outputLimit:B||void 0,normalizedOutput:ye,thresholdLimit:te,lastMessageId:u}},[A,s,p,B]),[D,b]=a.useState(null),fe={WebkitAppRegion:"drag"},ee={WebkitAppRegion:"no-drag"};a.useEffect(()=>{if(!s){b(r=>r===null?r:null);return}if(C&&C.totalTokens>0){b(r=>r&&r.totalTokens===C.totalTokens&&r.percentage===C.percentage&&r.contextLimit===C.contextLimit&&(r.outputLimit??0)===(C.outputLimit??0)&&(r.normalizedOutput??0)===(C.normalizedOutput??0)&&r.thresholdLimit===C.thresholdLimit&&r.lastMessageId===C.lastMessageId?r:C);return}b(r=>r===null?r:null)},[C,s]);const he=D&&D.contextLimit>0?Math.min(999,D.totalTokens/D.contextLimit*100):0,xe=a.useCallback(()=>{const r=!g;I(r),Y("desktop_set_window_pinned",{pinned:r}).catch(()=>{I(!r)})},[g]),ge=a.useCallback(()=>{const r=s?{sessionId:s,directory:y?.directory??i??""}:{mode:"draft",directory:f||i||"",projectId:c};Y("desktop_focus_main_window",r).then(u=>u?.focused===!0?Y("desktop_close_current_window"):null)},[i,s,c,f,y]);return e.jsxs("header",{className:V("flex items-center gap-3 bg-background pr-3",P?"pl-[5.5rem]":"pl-3",j?"h-12":o||"min-h-14"),style:fe,children:[j&&_==="left"?e.jsx(de,{visible:!0,position:"left"}):null,e.jsx(pe.Suspense,{fallback:e.jsxs("button",{type:"button","aria-label":"Open session switcher",style:ee,className:"flex min-w-0 max-w-full flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[e.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:x}),e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[e.jsx("span",{className:"truncate",children:q}),O?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[e.jsx(K,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:O})]}):null]})]}),children:e.jsx(ut,{children:e.jsxs("button",{type:"button","aria-label":"Open session switcher",style:ee,className:"flex min-w-0 max-w-full flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[e.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:x}),e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[e.jsx("span",{className:"truncate",children:q}),O?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[e.jsx(K,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:O})]}):null]})]})})}),e.jsx("div",{className:"min-w-0 flex-1"}),D&&D.totalTokens>0?e.jsx(dt,{totalTokens:D.totalTokens,percentage:he,colorPercentage:D.percentage,contextLimit:D.contextLimit,outputLimit:D.outputLimit??0,className:"h-9 shrink-0 pl-1 pr-1 typography-ui-label",valueClassName:"font-semibold leading-none",hideIcon:!0,showPercentIcon:!0,percentIconClassName:"h-4.5 w-4.5"}):null,e.jsx(ue,{type:"button",variant:"ghost",size:"icon",onClick:xe,"aria-label":g?"Unpin Mini Chat window":"Pin Mini Chat window",title:g?"Unpin window":"Pin above other windows",style:ee,children:g?e.jsx(K,{name:"pushpin-2-fill",className:"h-4 w-4"}):e.jsx(K,{name:"pushpin-2",className:"h-4 w-4"})}),e.jsx(ue,{type:"button",variant:"ghost",size:"icon",onClick:ge,"aria-label":"Open session in main window",title:"Open in main window",style:ee,children:e.jsx(K,{name:"external-link",className:"h-4 w-4"})}),e.jsx(de,{visible:j&&_==="right",position:"right"})]})},ft=({mode:t,autoOpenDraft:s=!1,unavailable:n=!1})=>{const c=S(i=>i.currentSessionId);return e.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background text-foreground",children:[e.jsx(pt,{mode:t}),e.jsx("main",{className:"min-h-0 flex-1",children:n?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center typography-ui-label text-muted-foreground",children:e.jsxs("div",{className:"max-w-sm rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-3",children:[e.jsx("div",{className:"font-medium text-foreground",children:"Session unavailable"}),e.jsx("div",{className:"mt-1 typography-small text-muted-foreground",children:"This session could not be loaded. It may have been deleted, archived, or opened from a different project context."})]})}):e.jsx(at,{mode:"mini-chat",children:e.jsx(Be,{autoOpenDraft:s},c??"no-session")})})]})},ht=()=>{const t=oe(i=>i.shortcutOverrides),s=J(i=>i.currentDirectory),n=ie(i=>i.getActiveProject()),c=S(i=>i.openNewSessionDraft);a.useEffect(()=>{const i=l=>be(l,t),m=l=>{if(z(l,i("focus_input"))){l.preventDefault(),me();return}if(je()&&z(l,i("new_mini_chat"))){l.preventDefault(),Y("desktop_open_draft_mini_chat_window",{directory:s||n?.path||"",projectId:n?.id??null})?.catch(h=>{console.warn("[mini-chat-shortcuts] failed to open draft mini chat window",h)});return}if(z(l,i("new_chat"))){l.preventDefault(),c({selectedProjectId:n?.id??null,directoryOverride:s||n?.path||null,preserveDirectoryOverride:!!(s||n?.path)}),me();return}if(z(l,i("open_model_selector"))){l.preventDefault();const{isModelSelectorOpen:h,setModelSelectorOpen:p}=oe.getState();p(!h);return}if(z(l,i("cycle_thinking_variant"))){if(w.getState().getCurrentModelVariants().length===0)return;l.preventDefault(),He(1).then(k=>{const N=S.getState().currentSessionId,E=w.getState().currentAgentName,g=w.getState().currentProviderId,I=w.getState().currentModelId;N&&E&&g&&I&&Ge.getState().saveAgentModelVariantForSession(N,E,g,I,k)}).catch(()=>{Ve.error("Couldn't update thinking")});return}const M=z(l,i("cycle_favorite_model_forward")),L=z(l,i("cycle_favorite_model_backward"));if(M||L){const{favoriteModels:h,addRecentModel:p}=oe.getState();if(h.length===0)return;l.preventDefault();const{currentProviderId:k,currentModelId:N,setProvider:E,setModel:g}=w.getState(),I=h.findIndex(j=>j.providerID===k&&j.modelID===N),P=h[(I+(M?1:-1)+h.length)%h.length];E(P.providerID),g(P.modelID),p(P.providerID,P.modelID)}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[n?.id,n?.path,s,c,t])},xt="pichamber:mini-chat-presence",gt=()=>{const t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams,s=t.get("mode")==="session"?"session":"draft",n=t.get("sessionId")?.trim()||null,c=t.get("directory")?.trim()||null,i=t.get("projectId")?.trim()||null;return{mode:s,sessionId:n,directory:c,projectId:i}},yt=({config:t})=>{const s=ae(),n=J(o=>o.currentDirectory),c=J(o=>o.setDirectory),i=S(o=>o.currentSessionId),m=S(o=>!!o.newSessionDraft?.open),l=S(o=>o.newSessionDraft?.open?o.newSessionDraft.bootstrapPendingDirectory??o.newSessionDraft.directoryOverride??"":""),M=S(o=>o.setCurrentSession),L=S(o=>o.openNewSessionDraft),h=w(o=>o.initializeApp),p=w(o=>o.isInitialized),k=w(o=>o.isConnected),N=w(o=>o.loadProviders),E=w(o=>o.loadAgents),g=w(o=>o.providers.length),I=w(o=>o.agents.length),v=st();a.useEffect(()=>{h()},[h]),a.useEffect(()=>{if(p)return;let o=!0,y=0;const x=window.setInterval(()=>{if(o){if(y+=1,y>10){window.clearInterval(x);return}w.getState().isInitialized||w.getState().initializeApp()}},1e3);return()=>{o=!1,window.clearInterval(x)}},[p]);const P=a.useRef(!1);a.useEffect(()=>{if(!P.current&&t.mode==="session"&&t.directory){if(n===t.directory){P.current=!0;return}c(t.directory,{showOverlay:!1}),P.current=!0}},[t.directory,t.mode,n,c]),a.useEffect(()=>{t.mode!=="draft"||!m||i||!l||n===l||c(l,{showOverlay:!1})},[t.mode,n,i,l,m,c]),a.useEffect(()=>{k&&(g===0&&N({source:"electronMiniChat:recovery"}),I===0&&E({source:"electronMiniChat:recovery"}))},[I,k,E,N,g]);const j=a.useRef(!1);a.useEffect(()=>{if(j.current||t.mode!=="session"||!t.sessionId)return;if(i===t.sessionId){j.current=!0;return}if(i){j.current=!0;return}const o=s.find(x=>x.id===t.sessionId);if(!o){v.ensureSessionRenderable(t.sessionId);return}const y=o.directory??t.directory;M(t.sessionId,y),j.current=!0},[t,i,s,M,v]),a.useEffect(()=>{const o=y=>{const x=y.detail,d=typeof x?.sessionId=="string"?x.sessionId.trim():"";if(!d||S.getState().currentSessionId===d)return;const U=typeof x?.directory=="string"&&x.directory.trim().length>0?x.directory.trim():s.find(f=>f.id===d)?.directory??null;v.ensureSessionRenderable(d),M(d,U),j.current=!0};return window.addEventListener("pichamber:open-session",o),()=>window.removeEventListener("pichamber:open-session",o)},[s,M,v]),a.useEffect(()=>{t.mode!=="draft"||m||i||L({selectedProjectId:t.projectId,directoryOverride:t.directory,preserveDirectoryOverride:!!t.directory})},[t,i,m,L]);const _=a.useRef(!1);return a.useEffect(()=>{if(_.current||!p)return;const o=()=>{if(_.current)return;_.current=!0;const d=typeof document<"u"?document.getElementById("initial-loading"):null;d&&(d.classList.add("fade-out"),window.setTimeout(()=>d.remove(),300))},y=t.mode==="session"?i===t.sessionId:m,x=window.setTimeout(o,y?100:1500);return()=>window.clearTimeout(x)},[p,t.mode,t.sessionId,i,m]),null},wt=()=>{const t=S(n=>n.currentSessionId),s=J(n=>n.currentDirectory);return a.useEffect(()=>{if(!t||!s||typeof BroadcastChannel>"u")return;const n=new BroadcastChannel(xt),c=l=>{n.postMessage({type:"mini-chat-session-presence",sessionId:t,directory:s,viewed:l})};c(!0);const i=window.setInterval(()=>c(!0),5e3),m=()=>c(!1);return window.addEventListener("beforeunload",m),()=>{window.clearInterval(i),window.removeEventListener("beforeunload",m),c(!1),n.close()}},[s,t]),null},vt=t=>{const s=ae(),n=S(m=>m.currentSessionId),[c,i]=a.useState(!1);return a.useEffect(()=>{if(t.mode!=="session"||!t.sessionId||n===t.sessionId){i(!1);return}if(s.some(l=>l.id===t.sessionId)){i(!1);return}const m=window.setTimeout(()=>i(!0),5e3);return()=>window.clearTimeout(m)},[t.mode,t.sessionId,n,s]),c};function jt({apis:t}){const s=a.useMemo(()=>gt(),[]),n=J(c=>c.currentDirectory);return a.useEffect(()=>{const c=n||s.directory;c&&Ke().focusProject(c,null)},[s.directory,n]),a.useEffect(()=>(le(t),()=>le(null)),[t]),Je(),ht(),Ne({enabled:!0}),e.jsx(qe,{children:e.jsx(Qe,{directory:n||s.directory,children:e.jsxs(Xe,{apis:t,children:[e.jsx(Ye,{}),e.jsx(Ze,{delayDuration:300,skipDelayDuration:150,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(bt,{config:s}),e.jsx(et,{}),e.jsx(tt,{})]})})]})})})}const bt=({config:t})=>{const s=vt(t);return e.jsxs(e.Fragment,{children:[e.jsx(yt,{config:t}),e.jsx(wt,{}),e.jsx(rt,{embeddedBackgroundWorkEnabled:!0}),e.jsx(ft,{mode:t.mode,autoOpenDraft:t.mode==="draft",unavailable:s})]})},St=()=>{Ie().then(()=>{Promise.all([Ce(),Pe()]).catch(t=>{console.error("[mini-chat-main] settings init failed:",t)}),De(),Me(),ke()}).catch(t=>{console.error("[mini-chat-main] appearance init failed:",t)})};function Xr(t){const s=t??Se();if(!s)throw new Error("Runtime APIs not registered");St();const n=document.getElementById("root");if(!n)throw new Error("Root element not found");we.createRoot(n).render(e.jsx(pe.StrictMode,{children:e.jsx(nt,{children:e.jsx(ot,{children:e.jsx(jt,{apis:s})})})}))}export{Xr as renderElectronMiniChatApp};