@seqyuan/annovibe 0.8.12 → 0.8.14

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 (205) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +8 -5
  3. package/.next/build-manifest.json +3 -3
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/react-loadable-manifest.json +6 -6
  6. package/.next/required-server-files.js +1 -1
  7. package/.next/required-server-files.json +1 -1
  8. package/.next/routes-manifest.json +18 -0
  9. package/.next/server/app/_global-error/page.js +3 -3
  10. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  11. package/.next/server/app/_global-error.html +1 -1
  12. package/.next/server/app/_global-error.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  16. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  17. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  18. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  19. package/.next/server/app/_not-found/page.js +2 -2
  20. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  21. package/.next/server/app/_not-found.html +1 -1
  22. package/.next/server/app/_not-found.rsc +2 -2
  23. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  24. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  25. package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  26. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  27. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  28. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  29. package/.next/server/app/api/agent/[id]/events/route.js +2 -2
  30. package/.next/server/app/api/agent/[id]/route.js +1 -1
  31. package/.next/server/app/api/agent/new/route.js +1 -1
  32. package/.next/server/app/api/auth/all-providers/route.js +1 -1
  33. package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
  34. package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
  35. package/.next/server/app/api/auth/login/route.js +1 -1
  36. package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
  37. package/.next/server/app/api/auth/providers/route.js +1 -1
  38. package/.next/server/app/api/auth/status/route.js +1 -1
  39. package/.next/server/app/api/default-cwd/route.js +1 -1
  40. package/.next/server/app/api/files/[...path]/route.js +2 -2
  41. package/.next/server/app/api/harness/route.js +1 -1
  42. package/.next/server/app/api/home/route.js +1 -1
  43. package/.next/server/app/api/internal/runtime/route.js +1 -0
  44. package/.next/server/app/api/internal/runtime/route.js.nft.json +1 -0
  45. package/.next/server/app/api/internal/runtime/route_client-reference-manifest.js +1 -0
  46. package/.next/server/app/api/models/route.js +1 -1
  47. package/.next/server/app/api/models-config/discover/route.js +1 -1
  48. package/.next/server/app/api/models-config/route.js +1 -1
  49. package/.next/server/app/api/models-config/test/route.js +1 -1
  50. package/.next/server/app/api/plot-kernels/route.js +1 -1
  51. package/.next/server/app/api/plot-kernels/status/route.js +1 -1
  52. package/.next/server/app/api/plot-kernels/stop/route.js +1 -1
  53. package/.next/server/app/api/projects/browse/route.js +1 -0
  54. package/.next/server/app/api/projects/browse/route.js.nft.json +1 -0
  55. package/.next/server/app/api/projects/browse/route_client-reference-manifest.js +1 -0
  56. package/.next/server/app/api/projects/route.js +3 -0
  57. package/.next/server/app/api/projects/route.js.nft.json +1 -0
  58. package/.next/server/app/api/projects/route_client-reference-manifest.js +1 -0
  59. package/.next/server/app/api/reports/[id]/route.js +7 -4
  60. package/.next/server/app/api/search/route.js +2 -2
  61. package/.next/server/app/api/sessions/[id]/context/route.js +2 -2
  62. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  63. package/.next/server/app/api/sessions/new/route.js +1 -1
  64. package/.next/server/app/api/sessions/route.js +2 -2
  65. package/.next/server/app/api/settings/route.js +1 -1
  66. package/.next/server/app/api/skills/install/route.js +1 -1
  67. package/.next/server/app/api/skills/route.js +2 -2
  68. package/.next/server/app/api/skills/search/route.js +1 -1
  69. package/.next/server/app/api/soul/route.js +1 -1
  70. package/.next/server/app/api/version/route.js +1 -1
  71. package/.next/server/app/favicon.ico/route.js +1 -1
  72. package/.next/server/app/index.html +1 -1
  73. package/.next/server/app/index.rsc +3 -3
  74. package/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  75. package/.next/server/app/index.segments/_full.segment.rsc +3 -3
  76. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  77. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  78. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  79. package/.next/server/app/login/page.js +2 -2
  80. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  81. package/.next/server/app/login.html +1 -1
  82. package/.next/server/app/login.rsc +2 -2
  83. package/.next/server/app/login.segments/_full.segment.rsc +2 -2
  84. package/.next/server/app/login.segments/_head.segment.rsc +1 -1
  85. package/.next/server/app/login.segments/_index.segment.rsc +2 -2
  86. package/.next/server/app/login.segments/_tree.segment.rsc +2 -2
  87. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +1 -1
  88. package/.next/server/app/login.segments/login.segment.rsc +1 -1
  89. package/.next/server/app/page.js +13 -13
  90. package/.next/server/app/page.js.nft.json +1 -1
  91. package/.next/server/app/page_client-reference-manifest.js +1 -1
  92. package/.next/server/app-paths-manifest.json +8 -5
  93. package/.next/server/chunks/1688.js +45 -0
  94. package/.next/server/chunks/7601.js +54 -12
  95. package/.next/server/chunks/static/media/pdf.worker.min.c476e1a0.mjs +6 -0
  96. package/.next/server/middleware-build-manifest.js +1 -1
  97. package/.next/server/middleware-react-loadable-manifest.js +1 -1
  98. package/.next/server/pages/404.html +1 -1
  99. package/.next/server/pages/500.html +1 -1
  100. package/.next/server/server-reference-manifest.json +1 -1
  101. package/.next/static/QvZYZknhDLA2wQJwpT60o/_buildManifest.js +1 -0
  102. package/.next/static/chunks/51fb665c.9f0b013f33bf4f6d.js +45 -0
  103. package/.next/static/chunks/8771-3e14b6810486df1f.js +1 -0
  104. package/.next/static/chunks/app/_global-error/page-7222ee8be0d45596.js +1 -0
  105. package/.next/static/chunks/app/api/agent/[id]/events/route-7222ee8be0d45596.js +1 -0
  106. package/.next/static/chunks/app/api/agent/[id]/route-7222ee8be0d45596.js +1 -0
  107. package/.next/static/chunks/app/api/agent/new/route-7222ee8be0d45596.js +1 -0
  108. package/.next/static/chunks/app/api/auth/all-providers/route-7222ee8be0d45596.js +1 -0
  109. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-7222ee8be0d45596.js +1 -0
  110. package/.next/static/chunks/app/api/auth/login/[provider]/route-7222ee8be0d45596.js +1 -0
  111. package/.next/static/chunks/app/api/auth/login/route-7222ee8be0d45596.js +1 -0
  112. package/.next/static/chunks/app/api/auth/logout/[provider]/route-7222ee8be0d45596.js +1 -0
  113. package/.next/static/chunks/app/api/auth/providers/route-7222ee8be0d45596.js +1 -0
  114. package/.next/static/chunks/app/api/auth/status/route-7222ee8be0d45596.js +1 -0
  115. package/.next/static/chunks/app/api/default-cwd/route-7222ee8be0d45596.js +1 -0
  116. package/.next/static/chunks/app/api/files/[...path]/route-7222ee8be0d45596.js +1 -0
  117. package/.next/static/chunks/app/api/harness/route-7222ee8be0d45596.js +1 -0
  118. package/.next/static/chunks/app/api/home/route-7222ee8be0d45596.js +1 -0
  119. package/.next/static/chunks/app/api/internal/runtime/route-7222ee8be0d45596.js +1 -0
  120. package/.next/static/chunks/app/api/models/route-7222ee8be0d45596.js +1 -0
  121. package/.next/static/chunks/app/api/models-config/discover/route-7222ee8be0d45596.js +1 -0
  122. package/.next/static/chunks/app/api/models-config/route-7222ee8be0d45596.js +1 -0
  123. package/.next/static/chunks/app/api/models-config/test/route-7222ee8be0d45596.js +1 -0
  124. package/.next/static/chunks/app/api/plot-kernels/route-7222ee8be0d45596.js +1 -0
  125. package/.next/static/chunks/app/api/plot-kernels/status/route-7222ee8be0d45596.js +1 -0
  126. package/.next/static/chunks/app/api/plot-kernels/stop/route-7222ee8be0d45596.js +1 -0
  127. package/.next/static/chunks/app/api/projects/browse/route-7222ee8be0d45596.js +1 -0
  128. package/.next/static/chunks/app/api/projects/route-7222ee8be0d45596.js +1 -0
  129. package/.next/static/chunks/app/api/reports/[id]/route-7222ee8be0d45596.js +1 -0
  130. package/.next/static/chunks/app/api/search/route-7222ee8be0d45596.js +1 -0
  131. package/.next/static/chunks/app/api/sessions/[id]/context/route-7222ee8be0d45596.js +1 -0
  132. package/.next/static/chunks/app/api/sessions/[id]/route-7222ee8be0d45596.js +1 -0
  133. package/.next/static/chunks/app/api/sessions/new/route-7222ee8be0d45596.js +1 -0
  134. package/.next/static/chunks/app/api/sessions/route-7222ee8be0d45596.js +1 -0
  135. package/.next/static/chunks/app/api/settings/route-7222ee8be0d45596.js +1 -0
  136. package/.next/static/chunks/app/api/skills/install/route-7222ee8be0d45596.js +1 -0
  137. package/.next/static/chunks/app/api/skills/route-7222ee8be0d45596.js +1 -0
  138. package/.next/static/chunks/app/api/skills/search/route-7222ee8be0d45596.js +1 -0
  139. package/.next/static/chunks/app/api/soul/route-7222ee8be0d45596.js +1 -0
  140. package/.next/static/chunks/app/api/version/route-7222ee8be0d45596.js +1 -0
  141. package/.next/static/chunks/app/page-e0ad11ee7003214a.js +270 -0
  142. package/.next/static/chunks/next/dist/client/components/builtin/app-error-7222ee8be0d45596.js +1 -0
  143. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-7222ee8be0d45596.js +1 -0
  144. package/.next/static/chunks/next/dist/client/components/builtin/not-found-7222ee8be0d45596.js +1 -0
  145. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-7222ee8be0d45596.js +1 -0
  146. package/.next/static/chunks/{webpack-5e677f60fa366b60.js → webpack-c223a77d0c5e1b9e.js} +1 -1
  147. package/.next/static/css/8026433d69e690e2.css +3 -0
  148. package/.next/static/media/pdf.worker.min.29aaf158.mjs +6 -0
  149. package/.next/trace +75 -74
  150. package/.next/trace-build +1 -1
  151. package/.next/types/app/api/internal/runtime/route.ts +351 -0
  152. package/.next/types/app/api/projects/browse/route.ts +351 -0
  153. package/.next/types/app/api/projects/route.ts +351 -0
  154. package/.next/types/routes.d.ts +4 -1
  155. package/.next/types/validator.ts +27 -0
  156. package/README.md +2 -0
  157. package/bin/pi-web.js +293 -16
  158. package/package.json +1 -1
  159. package/.next/server/chunks/7270.js +0 -45
  160. package/.next/server/chunks/static/media/pdf.worker.min.9df6854a.mjs +0 -6
  161. package/.next/static/chunks/7355-29eaa714eb390050.js +0 -1
  162. package/.next/static/chunks/9b0008ae.2918095672924572.js +0 -45
  163. package/.next/static/chunks/app/_global-error/page-3edd3886076a73cb.js +0 -1
  164. package/.next/static/chunks/app/api/agent/[id]/events/route-3edd3886076a73cb.js +0 -1
  165. package/.next/static/chunks/app/api/agent/[id]/route-3edd3886076a73cb.js +0 -1
  166. package/.next/static/chunks/app/api/agent/new/route-3edd3886076a73cb.js +0 -1
  167. package/.next/static/chunks/app/api/auth/all-providers/route-3edd3886076a73cb.js +0 -1
  168. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-3edd3886076a73cb.js +0 -1
  169. package/.next/static/chunks/app/api/auth/login/[provider]/route-3edd3886076a73cb.js +0 -1
  170. package/.next/static/chunks/app/api/auth/login/route-3edd3886076a73cb.js +0 -1
  171. package/.next/static/chunks/app/api/auth/logout/[provider]/route-3edd3886076a73cb.js +0 -1
  172. package/.next/static/chunks/app/api/auth/providers/route-3edd3886076a73cb.js +0 -1
  173. package/.next/static/chunks/app/api/auth/status/route-3edd3886076a73cb.js +0 -1
  174. package/.next/static/chunks/app/api/default-cwd/route-3edd3886076a73cb.js +0 -1
  175. package/.next/static/chunks/app/api/files/[...path]/route-3edd3886076a73cb.js +0 -1
  176. package/.next/static/chunks/app/api/harness/route-3edd3886076a73cb.js +0 -1
  177. package/.next/static/chunks/app/api/home/route-3edd3886076a73cb.js +0 -1
  178. package/.next/static/chunks/app/api/models/route-3edd3886076a73cb.js +0 -1
  179. package/.next/static/chunks/app/api/models-config/discover/route-3edd3886076a73cb.js +0 -1
  180. package/.next/static/chunks/app/api/models-config/route-3edd3886076a73cb.js +0 -1
  181. package/.next/static/chunks/app/api/models-config/test/route-3edd3886076a73cb.js +0 -1
  182. package/.next/static/chunks/app/api/plot-kernels/route-3edd3886076a73cb.js +0 -1
  183. package/.next/static/chunks/app/api/plot-kernels/status/route-3edd3886076a73cb.js +0 -1
  184. package/.next/static/chunks/app/api/plot-kernels/stop/route-3edd3886076a73cb.js +0 -1
  185. package/.next/static/chunks/app/api/reports/[id]/route-3edd3886076a73cb.js +0 -1
  186. package/.next/static/chunks/app/api/search/route-3edd3886076a73cb.js +0 -1
  187. package/.next/static/chunks/app/api/sessions/[id]/context/route-3edd3886076a73cb.js +0 -1
  188. package/.next/static/chunks/app/api/sessions/[id]/route-3edd3886076a73cb.js +0 -1
  189. package/.next/static/chunks/app/api/sessions/new/route-3edd3886076a73cb.js +0 -1
  190. package/.next/static/chunks/app/api/sessions/route-3edd3886076a73cb.js +0 -1
  191. package/.next/static/chunks/app/api/settings/route-3edd3886076a73cb.js +0 -1
  192. package/.next/static/chunks/app/api/skills/install/route-3edd3886076a73cb.js +0 -1
  193. package/.next/static/chunks/app/api/skills/route-3edd3886076a73cb.js +0 -1
  194. package/.next/static/chunks/app/api/skills/search/route-3edd3886076a73cb.js +0 -1
  195. package/.next/static/chunks/app/api/soul/route-3edd3886076a73cb.js +0 -1
  196. package/.next/static/chunks/app/api/version/route-3edd3886076a73cb.js +0 -1
  197. package/.next/static/chunks/app/page-dc03bbb33a1d438c.js +0 -270
  198. package/.next/static/chunks/next/dist/client/components/builtin/app-error-3edd3886076a73cb.js +0 -1
  199. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-3edd3886076a73cb.js +0 -1
  200. package/.next/static/chunks/next/dist/client/components/builtin/not-found-3edd3886076a73cb.js +0 -1
  201. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-3edd3886076a73cb.js +0 -1
  202. package/.next/static/css/d830cdea1c9a03c6.css +0 -3
  203. package/.next/static/ixA4-CDguO8ne_SD2W8sd/_buildManifest.js +0 -1
  204. package/.next/static/media/pdf.worker.min.5f98222a.mjs +0 -6
  205. /package/.next/static/{ixA4-CDguO8ne_SD2W8sd → QvZYZknhDLA2wQJwpT60o}/_ssgManifest.js +0 -0
@@ -1,270 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{46760:(e,t,r)=>{"use strict";r.d(t,{AppShell:()=>nl});var n=r(95155),i=r(12115),o=r(73321);let l="var(--text-dim)";function s({size:e=14,open:t=!1}){return t?(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:[(0,n.jsx)("path",{d:"M1 4.5A1 1 0 0 1 2 3.5H5.5L7 5h7.5v1H1V4.5Z",fill:l}),(0,n.jsx)("path",{d:"M1 6h14.5L14 13H2L1 6Z",stroke:l,strokeWidth:"1",fill:l,fillOpacity:"0.12"})]}):(0,n.jsx)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:(0,n.jsx)("path",{d:"M1 4.5A1 1 0 0 1 2 3.5H5.5L7 5H14a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V4.5Z",stroke:l,strokeWidth:"1",fill:l,fillOpacity:"0.1"})})}function a({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:[(0,n.jsx)("path",{d:"M3 2h7l3 3v9H3V2Z",stroke:l,strokeWidth:"1",fill:l,fillOpacity:"0.08"}),(0,n.jsx)("path",{d:"M10 2v3h3",stroke:l,strokeWidth:"1",fill:"none",strokeLinejoin:"round"})]})}function d({label:e,size:t=14}){let r=t/14;return(0,n.jsxs)("svg",{width:t,height:t,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:l,strokeWidth:"0.9",fill:l,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:l,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("text",{x:"7",y:"9.5",textAnchor:"middle",fontSize:3.4*r,fontFamily:"var(--font-mono), monospace",fontWeight:"600",fill:l,letterSpacing:"0",children:e})]})}function c({size:e=14}){return(0,n.jsx)(d,{label:"TS",size:e})}function u({size:e=14}){return(0,n.jsx)(d,{label:"TSX",size:e})}function p({size:e=14}){return(0,n.jsx)(d,{label:"JS",size:e})}function h({size:e=14}){return(0,n.jsx)(d,{label:"JSX",size:e})}function x({size:e=14}){return(0,n.jsx)(d,{label:"PY",size:e})}function g({size:e=14}){return(0,n.jsx)(d,{label:"{}",size:e})}function f({size:e=14}){return(0,n.jsx)(d,{label:"CSS",size:e})}function v({size:e=14}){return(0,n.jsx)(d,{label:"SC",size:e})}function m({size:e=14}){return(0,n.jsx)(d,{label:"HTM",size:e})}function y({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:l,strokeWidth:"0.9",fill:l,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:l,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M3.5 9.5V7l1.5 1.5L6.5 7v2.5",stroke:l,strokeWidth:"0.9",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),(0,n.jsx)("path",{d:"M8 7v2.5M7 9l1 1.5 1-1.5",stroke:l,strokeWidth:"0.9",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function b({size:e=14}){return(0,n.jsx)(d,{label:"YML",size:e})}function j({size:e=14}){return(0,n.jsx)(d,{label:"TOM",size:e})}function k({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:l,strokeWidth:"0.9",fill:l,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:l,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M4 7.5l2 1.5-2 1.5",stroke:l,strokeWidth:"0.95",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),(0,n.jsx)("path",{d:"M7.5 10.5h2.5",stroke:l,strokeWidth:"0.95",strokeLinecap:"round"})]})}function w({size:e=14}){return(0,n.jsx)(d,{label:"RS",size:e})}function S({size:e=14}){return(0,n.jsx)(d,{label:"GO",size:e})}function C({size:e=14}){return(0,n.jsx)(d,{label:"SQL",size:e})}function T({size:e=14}){return(0,n.jsx)(d,{label:"GQL",size:e})}function z({size:e=14}){return(0,n.jsx)(d,{label:"TF",size:e})}function L({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:l,strokeWidth:"0.9",fill:l,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:l,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("rect",{x:"3.5",y:"6.5",width:"2",height:"1.5",rx:"0.3",stroke:l,strokeWidth:"0.8"}),(0,n.jsx)("rect",{x:"6",y:"6.5",width:"2",height:"1.5",rx:"0.3",stroke:l,strokeWidth:"0.8"}),(0,n.jsx)("rect",{x:"3.5",y:"8.5",width:"2",height:"1.5",rx:"0.3",stroke:l,strokeWidth:"0.8"})]})}function I({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:l,strokeWidth:"0.9",fill:l,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:l,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("circle",{cx:"5.5",cy:"8.5",r:"1.5",stroke:l,strokeWidth:"0.9"}),(0,n.jsx)("path",{d:"M7 8.5h2.5M8.5 8.5v1.5",stroke:l,strokeWidth:"0.9",strokeLinecap:"round"})]})}function M({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:l,strokeWidth:"0.9",fill:l,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:l,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("circle",{cx:"5",cy:"6.5",r:"1",stroke:l,strokeWidth:"0.85"}),(0,n.jsx)("circle",{cx:"9",cy:"6.5",r:"1",stroke:l,strokeWidth:"0.85"}),(0,n.jsx)("circle",{cx:"5",cy:"10",r:"1",stroke:l,strokeWidth:"0.85"}),(0,n.jsx)("path",{d:"M5 7.5V9",stroke:l,strokeWidth:"0.85",strokeLinecap:"round"}),(0,n.jsx)("path",{d:"M9 7.5v.5a2 2 0 0 1-2 2H6",stroke:l,strokeWidth:"0.85",strokeLinecap:"round",fill:"none"})]})}function R({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:l,strokeWidth:"0.9",fill:l,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:l,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("rect",{x:"4.5",y:"8.5",width:"5",height:"3",rx:"0.6",stroke:l,strokeWidth:"0.9"}),(0,n.jsx)("path",{d:"M5.5 8.5V7.5a1.5 1.5 0 0 1 3 0v1",stroke:l,strokeWidth:"0.9",strokeLinecap:"round",fill:"none"})]})}function W({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:l,strokeWidth:"0.9",fill:l,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:l,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("circle",{cx:"7",cy:"8.5",r:"1.3",stroke:l,strokeWidth:"0.9"}),(0,n.jsx)("path",{d:"M7 6.5v.7M7 10.3v.7M5 8.5h.7M8.3 8.5H9M5.5 6.9l.5.5M8.5 9.6l-.5-.5M5.5 10.1l.5-.5M8.5 7.4l-.5.5",stroke:l,strokeWidth:"0.8",strokeLinecap:"round"})]})}function E(e,t=14){let r=e.toLowerCase(),i=r.split(".").pop()??"";if("dockerfile"===r||r.startsWith("dockerfile."))return(0,n.jsx)(L,{size:t});if(".env"===r||r.startsWith(".env."))return(0,n.jsx)(I,{size:t});if(".gitignore"===r||".gitattributes"===r||".gitmodules"===r)return(0,n.jsx)(M,{size:t});if("package-lock.json"===r||"yarn.lock"===r||"bun.lock"===r||"pnpm-lock.yaml"===r||"cargo.lock"===r)return(0,n.jsx)(R,{size:t});if(r.endsWith(".config.ts")||r.endsWith(".config.js")||r.endsWith(".config.mjs")||r.endsWith(".config.cjs")||[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(r))return(0,n.jsx)(W,{size:t});switch(i){case"ts":return(0,n.jsx)(c,{size:t});case"tsx":return(0,n.jsx)(u,{size:t});case"js":case"mjs":case"cjs":return(0,n.jsx)(p,{size:t});case"jsx":return(0,n.jsx)(h,{size:t});case"py":return(0,n.jsx)(x,{size:t});case"json":case"jsonl":return(0,n.jsx)(g,{size:t});case"css":case"less":return(0,n.jsx)(f,{size:t});case"scss":return(0,n.jsx)(v,{size:t});case"html":case"htm":return(0,n.jsx)(m,{size:t});case"md":case"mdx":return(0,n.jsx)(y,{size:t});case"yaml":case"yml":return(0,n.jsx)(b,{size:t});case"toml":return(0,n.jsx)(j,{size:t});case"sh":case"bash":case"zsh":case"fish":return(0,n.jsx)(k,{size:t});case"rs":return(0,n.jsx)(w,{size:t});case"go":return(0,n.jsx)(S,{size:t});case"sql":return(0,n.jsx)(C,{size:t});case"graphql":case"gql":return(0,n.jsx)(T,{size:t});case"tf":case"hcl":return(0,n.jsx)(z,{size:t});case"lock":return(0,n.jsx)(R,{size:t});default:return(0,n.jsx)(a,{size:t})}}function $(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function B(e){return $(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function N(e){let t=$(e).replace(/\/+$/,"");return t.split("/").pop()??t}function P(e,t){if(!t)return e;let r=$(e),n=$(t).replace(/\/$/,"");return r.startsWith(n+"/")?r.slice(n.length+1):e}async function A(e){let t=B(e),r=await fetch(`/api/files/${t}?type=list`);return r.ok?((await r.json()).entries??[]).map(t=>{var r;return{name:t.name,fullPath:(r=t.name,`${$(e).replace(/\/$/,"")}/${r}`),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}}):[]}function D(e,t){let r=t.trim().toLowerCase();return!!(!r||e.name.toLowerCase().includes(r))||(e.children??[]).some(e=>D(e,r))}function H(e){return!!Array.from(e.types).includes("Files")||Array.from(e.items).some(e=>"file"===e.kind)}function O(e){return Array.from(e.files).filter(e=>!!e.name)}function F(e,t){return e===t?".":P(e,t)}function U({node:e,depth:t,cwd:r,onOpenFile:o,onAtMention:l,expandedPaths:a,onToggleExpanded:d,onUploadFiles:c,uploadTargetPath:u,refreshKey:p,searchQuery:h}){let x=!!h?.trim(),g=x?e.isDir:a.has(e.fullPath),[f,v]=(0,i.useState)(e.children??[]),[m,y]=(0,i.useState)(e.loaded??!1),[b,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),T=e.isDir&&(S||u===e.fullPath),z=x?f.filter(e=>D(e,h??"")):f,L=(0,i.useCallback)(async(t=!1)=>{if(!m||t){j(!0);try{let t=await A(e.fullPath);v(t),y(!0)}catch{}finally{j(!1)}}},[m,e.fullPath]),I=(0,i.useRef)(m);(0,i.useEffect)(()=>{I.current=m}),(0,i.useEffect)(()=>{g&&m&&L(!0)},[p]);let M=(0,i.useCallback)(()=>{if(e.isDir){let t=!g;d(e.fullPath,t),t&&!m&&L()}else o(e.fullPath,e.name)},[e.isDir,e.fullPath,e.name,m,g,L,o,d]),R=(0,i.useCallback)(t=>{e.isDir&&H(t.dataTransfer)&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect="copy",C(!0))},[e.isDir]),W=(0,i.useCallback)(t=>{e.isDir&&H(t.dataTransfer)&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect="copy")},[e.isDir]),$=(0,i.useCallback)(t=>{if(!e.isDir)return;let r=t.relatedTarget;r instanceof Node&&t.currentTarget.contains(r)||C(!1)},[e.isDir]),B=(0,i.useCallback)(t=>{if(!e.isDir||!H(t.dataTransfer))return;t.preventDefault(),t.stopPropagation(),C(!1);let r=O(t.dataTransfer);r.length>0&&(c(r,e.fullPath),g||d(e.fullPath,!0),m||L())},[L,m,e.fullPath,e.isDir,d,c,g]);return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{onClick:M,onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),onDragEnter:R,onDragOver:W,onDragLeave:$,onDrop:B,style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*t,paddingRight:8,height:24,cursor:"pointer",background:T?"rgba(37,99,235,0.14)":k?"var(--bg-hover)":"transparent",outline:T?"1px solid rgba(37,99,235,0.42)":"none",outlineOffset:-1,borderRadius:4,userSelect:"none",transition:"background 0.12s, outline-color 0.12s"},children:[e.isDir&&(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:g?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,n.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!e.isDir&&(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,n.jsx)(s,{size:14,open:g}):E(e.name,14)}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:e.fullPath,children:e.name}),b&&(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,n.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),l&&k&&(0,n.jsxs)("button",{onClick:t=>{t.stopPropagation(),l(P(e.fullPath,r))},title:"Insert path into chat",style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,n.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]}),"mention"]})]}),e.isDir&&g&&(0,n.jsxs)("div",{children:[z.map(e=>(0,n.jsx)(U,{node:e,depth:t+1,cwd:r,onOpenFile:o,onAtMention:l,expandedPaths:a,onToggleExpanded:d,onUploadFiles:c,uploadTargetPath:u,refreshKey:p,searchQuery:h},e.fullPath)),0===z.length&&m&&!x&&(0,n.jsx)("div",{style:{paddingLeft:8+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"})]})]})}function _({cwd:e,onOpenFile:t,refreshKey:r,onAtMention:o,searchQuery:l="",onSearchChange:s}){let[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[x,g]=(0,i.useState)(new Set),[f,v]=(0,i.useState)(!1),[m,y]=(0,i.useState)(null),[b,j]=(0,i.useState)(null),k=(0,i.useRef)(null),w=(0,i.useRef)(null),S=(0,i.useRef)(0),C=(0,i.useCallback)((e,t)=>(u(t),h(null),A(e).then(e=>d(e)).catch(e=>h(String(e))).finally(()=>u(!1))),[]),T=(0,i.useCallback)((e,t)=>{g(r=>{let n=new Set(r);return t?n.add(e):n.delete(e),n})},[]);(0,i.useEffect)(()=>{let t=k.current!==e;k.current=e,t&&g(new Set),C(e,t)},[e,r,C]),(0,i.useEffect)(()=>()=>{w.current&&clearTimeout(w.current)},[]);let z=(0,i.useCallback)(()=>{C(e,0===a.length)},[e,a.length,C]),L=(0,i.useCallback)(()=>{w.current&&clearTimeout(w.current),w.current=setTimeout(()=>j(null),5e3)},[]),I=(0,i.useCallback)((t,r)=>{if(0===t.length)return;S.current=0,v(!1),w.current&&clearTimeout(w.current);let n=t.reduce((e,t)=>e+t.size,0),i=F(r,e);y(r),j({phase:"uploading",targetPath:r,fileCount:t.length,loaded:0,total:n,message:`Uploading ${t.length} file${1===t.length?"":"s"} to ${i}`});let o=new FormData;t.forEach(e=>o.append("files",e,e.name));let l=new XMLHttpRequest,s=B(r);l.open("POST",`/api/files/${s}?type=upload`),l.upload.onprogress=e=>{e.lengthComputable&&j(t=>t?{...t,loaded:e.loaded,total:e.total}:t)},l.onload=()=>{y(null);let e={};try{e=JSON.parse(l.responseText)}catch{e={}}if(l.status>=200&&l.status<300){let o=e.uploaded??[],l=e.failed??[],s=[...o.filter(e=>e.name!==e.originalName).slice(0,3).map(e=>`${e.originalName} saved as ${e.name}`),...l.slice(0,3).map(e=>`${e.name}: ${e.error}`)];j({phase:l.length>0?"warning":"success",targetPath:r,fileCount:t.length,loaded:n,total:n,message:l.length>0?`Uploaded ${o.length}, ${l.length} failed`:`Uploaded ${o.length} file${1===o.length?"":"s"} to ${i}`,details:s}),z(),L()}else{let i=e.error??`Upload failed (HTTP ${l.status})`;j({phase:(l.status,"error"),targetPath:r,fileCount:t.length,loaded:0,total:n,message:i,details:403===l.status?["Check directory write permission or project access."]:void 0}),L()}},l.onerror=()=>{y(null),j({phase:"error",targetPath:r,fileCount:t.length,loaded:0,total:n,message:"Upload failed due to a network error"}),L()},l.onabort=()=>{y(null),j({phase:"error",targetPath:r,fileCount:t.length,loaded:0,total:n,message:"Upload canceled"}),L()},l.send(o)},[e,z,L]),M=(0,i.useCallback)(e=>{H(e.dataTransfer)&&(e.preventDefault(),S.current+=1,v(!0))},[]),R=(0,i.useCallback)(e=>{H(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]),W=(0,i.useCallback)(()=>{S.current-=1,S.current<=0&&(S.current=0,v(!1))},[]),E=(0,i.useCallback)(t=>{if(!H(t.dataTransfer))return;t.preventDefault(),S.current=0,v(!1);let r=O(t.dataTransfer);r.length>0&&I(r,e)},[e,I]),$=l.trim()?a.filter(e=>D(e,l)):a,N=l.trim().length>0;return c?(0,n.jsx)(V,{cwd:e,isDraggingFiles:f,uploadState:b,onDragEnter:M,onDragOver:R,onDragLeave:W,onDrop:E,children:(0,n.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."})}):p?(0,n.jsx)(V,{cwd:e,isDraggingFiles:f,uploadState:b,onDragEnter:M,onDragOver:R,onDragLeave:W,onDrop:E,children:(0,n.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:p})}):(0,n.jsx)(V,{cwd:e,isDraggingFiles:f,uploadState:b,onDragEnter:M,onDragOver:R,onDragLeave:W,onDrop:E,children:(0,n.jsxs)("div",{style:{padding:"2px 4px"},children:[$.map(i=>(0,n.jsx)(U,{node:i,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:x,onToggleExpanded:T,onUploadFiles:I,uploadTargetPath:m,refreshKey:r,searchQuery:l},i.fullPath)),0===$.length&&(0,n.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:N?"No matching files":"No files found"})]})})}function V({cwd:e,isDraggingFiles:t,uploadState:r,onDragEnter:i,onDragOver:o,onDragLeave:l,onDrop:s,children:a}){let d=r&&r.total>0?Math.max(0,Math.min(100,Math.round(r.loaded/r.total*100))):r?.phase==="uploading"?8:100,c=r?.phase==="success"?"#22c55e":r?.phase==="warning"?"#f59e0b":r?.phase==="error"?"#ef4444":"var(--accent)";return(0,n.jsxs)("div",{onDragEnter:i,onDragOver:o,onDragLeave:l,onDrop:s,style:{position:"relative",display:"flex",flexDirection:"column",minHeight:"100%",outline:t?"1px solid rgba(37,99,235,0.45)":"none",outlineOffset:-1,background:t?"rgba(37,99,235,0.04)":void 0,transition:"background 0.12s, outline-color 0.12s"},children:[(0,n.jsx)("div",{style:{flex:1,minHeight:0},children:a}),t&&(0,n.jsx)("div",{style:{pointerEvents:"none",position:"absolute",inset:6,top:42,border:"1px dashed rgba(37,99,235,0.62)",borderRadius:8,background:"rgba(37,99,235,0.07)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2},children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontSize:12,boxShadow:"0 8px 24px rgba(0,0,0,0.16)"},children:[(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,n.jsx)("polyline",{points:"17 8 12 3 7 8"}),(0,n.jsx)("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),"Drop to upload into ",F(e,e)]})}),r&&(0,n.jsxs)("div",{style:{margin:"6px",padding:"7px 8px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",boxShadow:"0 8px 24px rgba(0,0,0,0.12)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0},children:[(0,n.jsx)("span",{style:{width:8,height:8,borderRadius:999,background:c,flexShrink:0}}),(0,n.jsx)("span",{title:r.message,style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11,fontWeight:600},children:r.message}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,flexShrink:0},children:"uploading"===r.phase?`${d}%`:function(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],r=e,n=0;for(;r>=1024&&n<t.length-1;)r/=1024,n+=1;return`${r>=10||0===n?Math.round(r):r.toFixed(1)} ${t[n]}`}(r.total)})]}),(0,n.jsx)("div",{style:{marginTop:6,height:3,borderRadius:999,background:"var(--bg)",overflow:"hidden"},children:(0,n.jsx)("div",{style:{width:`${d}%`,height:"100%",borderRadius:999,background:c,transition:"width 0.15s ease"}})}),r.details&&r.details.length>0&&(0,n.jsx)("div",{style:{marginTop:5,display:"grid",gap:2},children:r.details.map(e=>(0,n.jsx)("div",{title:e,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:e},e))})]})]})}function J(e,t){let r=t&&e.startsWith(t)?"~"+e.slice(t.length):e,n=r.includes("/")?"/":"\\",i=r.split(n).filter(Boolean);return i.length<=2?r:"..."+n+i.slice(-2).join(n)}function K(e){let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function q({open:e,cwd:t,homeDir:r,onClose:o,onSelectSession:l}){let[s,a]=(0,i.useState)(""),[d,c]=(0,i.useState)("current"),[u,p]=(0,i.useState)([]),[h,x]=(0,i.useState)(!1),[g,f]=(0,i.useState)(null),[v,m]=(0,i.useState)(!1),y=(0,i.useRef)(null);if((0,i.useEffect)(()=>{e&&(c(t?"current":"all"),setTimeout(()=>y.current?.focus(),0))},[e,t]),(0,i.useEffect)(()=>{if(!e)return;let t=e=>{"Escape"===e.key&&o()};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[e,o]),(0,i.useEffect)(()=>{if(!e)return;let r=s.trim();if(r.length<2){p([]),x(!1),f(null),m(!1);return}let n=new AbortController,i=setTimeout(async()=>{x(!0),f(null);try{let e=new URLSearchParams({q:r,scope:d});t&&e.set("cwd",t);let i=await fetch(`/api/search?${e.toString()}`,{signal:n.signal});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();if(o.error)throw Error(o.error);p(o.results??[]),m(o.truncated??!1)}catch(e){"AbortError"!==e.name&&f(String(e))}finally{x(!1)}},180);return()=>{clearTimeout(i),n.abort()}},[e,s,d,t]),!e)return null;let b=s.trim(),j=u.reduce((e,t)=>e+t.matches.length,0);return(0,n.jsx)("div",{role:"dialog","aria-modal":"true","aria-label":"Search conversation history",style:{position:"fixed",inset:0,zIndex:500,display:"flex",alignItems:"flex-start",justifyContent:"center",padding:"8vh 16px 16px",background:"rgba(0,0,0,0.28)"},onMouseDown:e=>{e.target===e.currentTarget&&o()},children:(0,n.jsxs)("div",{style:{width:"min(760px, 100%)",maxHeight:"78vh",display:"flex",flexDirection:"column",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 16px 48px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:12,borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:8,padding:"0 10px"},children:[(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"4.5"}),(0,n.jsx)("path",{d:"M10.5 10.5 13.5 13.5"})]}),(0,n.jsx)("input",{ref:y,value:s,onChange:e=>a(e.target.value),placeholder:"Search conversation history...",style:{flex:1,minWidth:0,height:38,background:"transparent",border:"none",outline:"none",color:"var(--text)",fontSize:14}})]}),(0,n.jsx)("button",{type:"button",onClick:o,title:"Close",style:{width:34,height:34,display:"inline-flex",alignItems:"center",justifyContent:"center",background:"none",border:"none",borderRadius:7,color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:[(0,n.jsx)("path",{d:"M4 4 12 12"}),(0,n.jsx)("path",{d:"M12 4 4 12"})]})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:10},children:[(0,n.jsx)("div",{style:{display:"inline-flex",padding:2,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7},children:[{value:"current",label:"Current project",disabled:!t},{value:"all",label:"All history",disabled:!1}].map(e=>(0,n.jsx)("button",{type:"button",disabled:e.disabled,onClick:()=>c(e.value),style:{height:24,padding:"0 9px",background:d===e.value?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:e.disabled?"var(--text-dim)":d===e.value?"var(--text)":"var(--text-muted)",cursor:e.disabled?"not-allowed":"pointer",fontSize:11,fontWeight:500},children:e.label},e.value))}),(0,n.jsx)("div",{style:{flex:1,minWidth:0,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"current"===d&&t?J(t,r):"Searching every saved session"})]})]}),(0,n.jsxs)("div",{style:{flex:1,overflowY:"auto",minHeight:180},children:[b.length<2&&(0,n.jsx)("div",{style:{padding:28,textAlign:"center",color:"var(--text-muted)",fontSize:13},children:"Type at least 2 characters to search saved conversations."}),b.length>=2&&h&&0===u.length&&(0,n.jsx)("div",{style:{padding:28,textAlign:"center",color:"var(--text-muted)",fontSize:13},children:"Searching..."}),g&&(0,n.jsx)("div",{style:{padding:18,color:"#ef4444",fontSize:13},children:g}),b.length>=2&&!h&&!g&&0===u.length&&(0,n.jsx)("div",{style:{padding:28,textAlign:"center",color:"var(--text-muted)",fontSize:13},children:"No matching conversations found."}),u.map(e=>(0,n.jsxs)("div",{style:{borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{l(e.session),o()},style:{width:"100%",display:"flex",alignItems:"center",gap:10,padding:"10px 12px",background:"var(--bg-panel)",border:"none",borderBottom:"1px solid var(--border)",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:600},children:e.session.name||e.session.firstMessage||"(no messages)"}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:11},children:K(e.session.modified)})]}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J(e.session.cwd,r)})]}),e.matchCount>e.matches.length&&(0,n.jsxs)("span",{style:{flexShrink:0,color:"var(--text-muted)",fontSize:11},children:[e.matchCount," matches"]})]}),e.matches.map(t=>(0,n.jsxs)("button",{type:"button",onClick:()=>{l(e.session),o()},style:{width:"100%",padding:"9px 14px 9px 28px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:3},children:[(0,n.jsx)("span",{style:{minWidth:54,color:"user"===t.role?"var(--accent)":"var(--text-dim)",fontSize:11,fontWeight:600,textTransform:"capitalize"},children:t.role}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:K(t.timestamp)})]}),(0,n.jsx)("div",{style:{fontSize:12,lineHeight:1.45,color:"var(--text-muted)"},children:function(e,t){let r=t.trim();if(!r)return e;let i=e.toLowerCase().indexOf(r.toLowerCase());return i<0?e:(0,n.jsxs)(n.Fragment,{children:[e.slice(0,i),(0,n.jsx)("mark",{style:{background:"rgba(37,99,235,0.16)",color:"var(--text)",borderRadius:3,padding:"0 2px"},children:e.slice(i,i+r.length)}),e.slice(i+r.length)]})}(t.snippet,b)})]},t.entryId))]},e.session.id))]}),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",padding:"8px 12px",borderTop:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11},children:[(0,n.jsx)("span",{children:j>0?`${j}${v?"+":""} results`:"Esc to close"}),h&&u.length>0&&(0,n.jsx)("span",{children:"Updating..."})]})]})})}let Y="AnnoVibe",G="annovibe:sidebar:collapsed-projects",Z="annovibe:sidebar:collapsed-projects:init-v1";function X(e){window.localStorage.setItem(G,JSON.stringify([...e]))}function Q(e){let t=new Date(e),r=new Date().getTime()-t.getTime(),n=Math.floor(r/6e4),i=Math.floor(r/36e5),o=Math.floor(r/864e5);return n<1?"just now":n<60?`${n}m ago`:i<24?`${i}h ago`:o<7?`${o}d ago`:t.toLocaleDateString()}function ee(e){let t=new Map;for(let r of e){if(!r.cwd)continue;let e=t.get(r.cwd);(!e||r.modified>e)&&t.set(r.cwd,r.modified)}return[...t.entries()].sort((e,t)=>t[1].localeCompare(e[1])).slice(0,5).map(([e])=>e)}function et(e,t){let r=t&&e.startsWith(t)?"~"+e.slice(t.length):e,n=r.includes("/")?"/":"\\",i=r.split(n).filter(Boolean);return i.length<=2?r:"…/"+i.slice(-2).join(n)}let er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function en(){let[e,t]=(0,i.useState)(!1),[r,o]=(0,i.useState)(!1),l=(0,i.useRef)(null),s=function(e,t){let[r,n]=(0,i.useState)(e),o=(0,i.useRef)(null),l=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void n(e);l.current=0;let r=4*e.length,i=()=>{l.current+=1;let t=Math.floor(l.current/r*e.length);n(e.split("").map((e,r)=>" "===e?" ":r<t?e:er[Math.floor(Math.random()*er.length)]).join("")),l.current<r?o.current=requestAnimationFrame(i):n(e)};return o.current=requestAnimationFrame(i),()=>{o.current&&cancelAnimationFrame(o.current)}},[e,t]),r}(e?"v0.8.12":Y,r),a=(0,i.useCallback)(e=>{t(e),o(!0),setTimeout(()=>o(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{l.current&&clearTimeout(l.current);let t=!e;a(t),t&&(l.current=setTimeout(()=>a(!1),3e3))},[e,a]);return(0,i.useEffect)(()=>()=>{l.current&&clearTimeout(l.current)},[]),(0,n.jsx)("button",{onClick:d,style:{background:"none",border:"none",padding:0,cursor:"default",fontWeight:700,fontSize:15,letterSpacing:"-0.01em",color:e?"var(--accent)":"var(--text)",fontFamily:"var(--font-mono)",minWidth:"9ch"},children:s})}function ei({selectedSessionId:e,onSelectSession:t,onNewSession:r,initialSessionId:o,onInitialRestoreDone:l,refreshKey:s,onSessionDeleted:a,selectedCwd:d,onCwdChange:c,onOpenFile:u,explorerRefreshKey:p,onAtMention:h,projectPlotMemory:x}){let[g,f]=(0,i.useState)([]),[v,m]=(0,i.useState)(!0),[y,b]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(""),[C,T]=(0,i.useState)(!1),[z,L]=(0,i.useState)(!1),[I,M]=(0,i.useState)(""),[R,W]=(0,i.useState)(!1),[E,$]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(G)??window.localStorage.getItem("pidex:sidebar:collapsed-projects");return e?new Set(JSON.parse(e)):new Set}catch{return new Set}})()),[B,N]=(0,i.useState)(()=>new Set),P=(0,i.useRef)(!1),A=(0,i.useRef)(!1),D=(0,i.useRef)(!1),H=(0,i.useRef)(null),O=(0,i.useRef)(null),[F,U]=(0,i.useState)(!0),[V,J]=(0,i.useState)(0),[K,Y]=(0,i.useState)(""),Q=(0,i.useCallback)(async(e=!1)=>{try{e&&m(!0);let t=await fetch("/api/sessions");if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();f(r.sessions),b(null)}catch(e){b(String(e))}finally{e&&m(!1)}},[]),er=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!er.current;er.current=!0,Q(e)},[Q,s]),(0,i.useEffect)(()=>{void 0!==p&&J(e=>e+1)},[p]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&S(e.home)}).catch(()=>{})},[]);let es=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(A.current){A.current=!1;return}if(D.current){D.current=!1;return}c?.(j)},[j,c]),(0,i.useEffect)(()=>{if(0!==g.length&&null===j){if(o&&!es.current){es.current=!0;let e=g.find(e=>e.id===o);if(e){k(e.cwd),t(e,!0);return}l?.()}let e=ee(g);e.length>0&&k(e[0])}},[g,j,o,t,l]);let ea=(0,i.useCallback)(()=>{let e=I.trim();e&&k(e),L(!1),M(""),T(!1)},[I]),ed=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&(k(t.cwd),T(!1))}catch{}},[]);(0,i.useEffect)(()=>{let e=e=>{O.current&&!O.current.contains(e.target)&&(T(!1),L(!1),M(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let ec=d??j,eu=(0,i.useCallback)(e=>{if(!e)return void T(!0);let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;r?.(t,e)},[r]),ep=(0,i.useCallback)(()=>{eu(ec)},[eu,ec]),eh=ee(g),ex=(0,i.useMemo)(()=>(function(e,t,r){let n=new Map;for(let t of e){let e=t.cwd||"";n.has(e)||n.set(e,[]),n.get(e).push(t)}t&&!n.has(t)&&n.set(t,[]);let i=[...n.entries()].map(([e,t])=>{let n=[...t].sort((e,t)=>t.modified.localeCompare(e.modified));return{cwd:e,displayName:function(e,t){if(!e)return"No Project";let r=e.replace(/[\\/]+$/,""),n=r.includes("/")?"/":"\\";return r.split(n).filter(Boolean).pop()||et(e,t)}(e,r),sessions:n,modified:n[0]?.modified??"",synthetic:0===n.length}});return i.sort((e,r)=>t&&e.cwd===t?-1:t&&r.cwd===t?1:e.modified!==r.modified?r.modified.localeCompare(e.modified):e.displayName.localeCompare(r.displayName)),i})(g,ec,w),[g,ec,w]);(0,i.useEffect)(()=>{ec&&$(e=>{if(!e.has(ec))return e;let t=new Set(e);return t.delete(ec),X(t),t})},[ec]),(0,i.useEffect)(()=>{if(!ec||P.current||ex.length<=1||(P.current=!0,window.localStorage.getItem(Z)||window.localStorage.getItem("pidex:sidebar:collapsed-projects:init-v1")))return;let e=new Set;for(let t of ex)t.cwd!==ec&&e.add(t.cwd);$(e),X(e),window.localStorage.setItem(Z,"1")},[ex,ec]);let eg=(0,i.useCallback)(e=>{D.current=!0,k(e),c?.(e),$(t=>{let r=new Set(t);return r.delete(e),X(r),r})},[c]),ef=(0,i.useCallback)((e,r=!1)=>{e.cwd!==ec&&(A.current=!0,k(e.cwd)),$(t=>{if(!t.has(e.cwd))return t;let r=new Set(t);return r.delete(e.cwd),X(r),r}),t(e,r)},[t,ec]),ev=(0,i.useCallback)(e=>{$(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),X(r),r})},[]),em=(0,i.useCallback)(e=>{N(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"12px 10px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,n.jsx)(en,{}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsxs)("button",{onClick:ep,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,background:"var(--bg-hover)",border:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",height:32,paddingLeft:10,paddingRight:12,borderRadius:7,fontSize:12,fontWeight:500,letterSpacing:"-0.01em",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:ec?`New session in ${ec}`:"Select a project first",onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,n.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]}),"New"]}),(0,n.jsx)("button",{onClick:()=>W(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:"Search conversations",onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"4.4"}),(0,n.jsx)("path",{d:"M10.4 10.4 13.2 13.2"})]})})]})]}),(0,n.jsxs)("div",{ref:O,style:{position:"relative"},children:[(0,n.jsxs)("div",{style:{marginBottom:5,display:"flex",alignItems:"center",justifyContent:"space-between",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase"},children:[(0,n.jsx)("span",{children:"Project"}),(0,n.jsxs)("span",{children:[ex.length," dirs"]})]}),(0,n.jsx)("button",{onClick:()=>T(e=>!e),style:{width:"100%",display:"flex",alignItems:"center",padding:"6px 10px",background:ec?"var(--bg-hover)":"rgba(37,99,235,0.06)",border:ec?"1px solid var(--border)":"1px solid rgba(37,99,235,0.4)",borderRadius:7,cursor:"pointer",fontSize:12,color:"var(--text)",textAlign:"left",transition:"border-color 0.15s, background 0.15s"},children:(0,n.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11,color:ec?"var(--text)":"var(--text-dim)"},title:ec??"",children:ec?et(ec,w):o&&!es.current?"":"Open project…"})}),C&&(0,n.jsxs)("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[eh.map(e=>(0,n.jsxs)("button",{onClick:()=>{eg(e),L(!1),M(""),T(!1)},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:e===ec?"var(--bg-selected)":"none",border:"none",borderBottom:"1px solid var(--border)",color:e===ec?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:[e===ec&&(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}),e!==ec&&(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:et(e,w)})]},e)),!z&&(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),ed()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",borderTop:eh.length>0?"1px solid var(--border)":"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("path",{d:"M1 3A1 1 0 0 1 2 2H4L5 3.5H8.5a.5.5 0 0 1 .5.5v4a.5.5 0 0 1-.5.5h-7A.5.5 0 0 1 1 8V3Z"})}),(0,n.jsx)("span",{children:"Use default directory"})]}),z?(0,n.jsxs)("div",{style:{padding:"6px 8px",borderTop:eh.length>0?"none":void 0},children:[(0,n.jsx)("input",{ref:H,value:I,onChange:e=>M(e.target.value),onKeyDown:e=>{"Enter"===e.key&&ea(),"Escape"===e.key&&(L(!1),M(""))},placeholder:"/path/to/project",style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,n.jsx)("button",{onClick:ea,style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"#fff",fontSize:11,fontWeight:600,cursor:"pointer"},children:"Open"}),(0,n.jsx)("button",{onClick:()=>{L(!1),M("")},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:"Cancel"})]})]}):(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),L(!0),setTimeout(()=>H.current?.focus(),0)},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,n.jsx)("span",{children:"Open project path…"})]})]})]})]}),(0,n.jsx)(q,{open:R,cwd:ec,homeDir:w,onClose:()=>W(!1),onSelectSession:e=>{ef(e)}}),(0,n.jsxs)("div",{style:{flex:F&&ec?"1 1 0":"1 1 auto",overflowY:"auto",padding:"6px 8px 8px",minHeight:120},children:[v&&(0,n.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:"Loading..."}),y&&(0,n.jsx)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:y}),!v&&!y&&0===ex.length&&(0,n.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:"No projects found"}),!v&&!y&&ex.map(t=>{let r=E.has(t.cwd),i=t.cwd===ec,o=B.has(t.cwd),l=function(e){let t=new Map;for(let r of e)t.set(r.id,{session:r,children:[]});let r=new Map;for(let t of e)t.parentSessionId&&r.set(t.id,t.parentSessionId);let n=[];for(let e of t.values()){let i=function(e){let n=r.get(e),i=new Set;for(;n&&!i.has(n);){if(i.add(n),t.has(n))return n;n=r.get(n)}return null}(e.session.id);i?t.get(i).children.push(e):n.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(n),n}(t.sessions),s=l.length,d=l;if(s>10&&!o){d=l.slice(0,10);let t=l.find(t=>(function e(t,r){return!!r&&(t.session.id===r||t.children.some(t=>e(t,r)))})(t,e));t&&!d.includes(t)&&(d=[...d,t])}let c=s-d.length;return(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)(eo,{group:t,homeDir:w,plotMemoryBytes:x?.[t.cwd]??0,isCurrent:i,isCollapsed:r,onToggle:()=>ev(t.cwd),onSelect:()=>eg(t.cwd),onNewSession:e=>{e.stopPropagation(),eg(t.cwd),eu(t.cwd)}}),!r&&(0,n.jsxs)("div",{style:{marginTop:2,overflow:"hidden",borderRadius:7},children:[0===t.sessions.length?(0,n.jsx)("button",{type:"button",onClick:()=>{eg(t.cwd),eu(t.cwd)},style:{width:"100%",padding:"10px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:"Start a new session in this project"}):d.map(t=>(0,n.jsx)(el,{node:t,selectedSessionId:e,onSelectSession:ef,onRenamed:Q,onSessionDeleted:e=>{a?.(e),Q()},depth:0},t.session.id)),(o||c>0)&&s>10&&(0,n.jsx)("button",{type:"button",onClick:()=>em(t.cwd),style:{width:"100%",padding:"6px 10px",background:"transparent",border:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11,textAlign:"center"},children:o?"Show less":`Show ${Math.max(0,c)} more`})]})]},t.cwd||"__no_project")})]}),ec&&(0,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:F?"1 1 0":"0 0 auto",minHeight:0,overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,gap:0,padding:"2px 4px"},children:[(0,n.jsxs)("button",{onClick:()=>U(e=>!e),style:{display:"flex",alignItems:"center",gap:6,padding:"6px 6px 6px 6px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase",textAlign:"left",flexShrink:0},children:[(0,n.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:F?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},children:(0,n.jsx)("polyline",{points:"3 2 7 5 3 8"})}),"Explorer"]}),(0,n.jsxs)("div",{style:{position:"relative",flex:1,minWidth:0},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"4.4"}),(0,n.jsx)("path",{d:"M10.4 10.4 13.2 13.2"})]}),(0,n.jsx)("input",{value:K,onChange:e=>Y(e.target.value),placeholder:"Filter files...",style:{width:"100%",height:28,boxSizing:"border-box",padding:"0 26px 0 26px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}}),K&&(0,n.jsx)("button",{type:"button",onClick:()=>Y(""),title:"Clear filter",style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",width:20,height:20,display:"flex",alignItems:"center",justifyContent:"center",border:"none",borderRadius:4,background:"transparent",color:"var(--text-dim)",cursor:"pointer",padding:0},children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,n.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]})]}),F&&(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,n.jsx)(_,{cwd:ec,onOpenFile:u??(()=>{}),refreshKey:V,onAtMention:h,searchQuery:K,onSearchChange:Y})})]})]})}function eo({group:e,homeDir:t,plotMemoryBytes:r,isCurrent:o,isCollapsed:l,onToggle:s,onSelect:a,onNewSession:d}){let[c,u]=(0,i.useState)(!1),p=!Number.isFinite(r)||r<=0?"":`${(r/1024/1024/1024).toFixed(1)}G`,h=(0,i.useCallback)(()=>{o?s():a()},[o,a,s]);return(0,n.jsxs)("div",{role:"button",tabIndex:0,onClick:h,onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),h())},onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{width:"100%",minHeight:42,display:"flex",alignItems:"center",gap:7,padding:"7px 8px",background:o?"var(--bg-selected)":c?"var(--bg-hover)":"transparent",border:"none",borderLeft:o?"2px solid var(--accent)":"2px solid transparent",borderRadius:7,color:"var(--text)",cursor:"pointer",textAlign:"left",overflow:"hidden",transition:"background 0.12s"},title:e.cwd,children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:l?"none":"rotate(90deg)",transition:"transform 0.15s",color:"var(--text-dim)",flexShrink:0},children:(0,n.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:o?"var(--accent)":"var(--text-dim)",flexShrink:0},children:(0,n.jsx)("path",{d:"M3 6.5A2.5 2.5 0 0 1 5.5 4H10l2 2.5h6.5A2.5 2.5 0 0 1 21 9v8.5A2.5 2.5 0 0 1 18.5 20h-13A2.5 2.5 0 0 1 3 17.5v-11Z"})}),(0,n.jsxs)("span",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("span",{style:{display:"block",color:"var(--text)",fontSize:12,fontWeight:o?600:500,lineHeight:1.25,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,n.jsxs)("span",{style:{display:"block",marginTop:2,color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)",lineHeight:1.25,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.sessions.length," chats",p?` \xb7 ${p} plot`:""," \xb7 ",e.modified?Q(e.modified):et(e.cwd,t)]})]}),(0,n.jsx)("span",{style:{minWidth:18,height:18,padding:"0 5px",display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:999,background:o?"rgba(37,99,235,0.12)":"var(--bg-hover)",color:o?"var(--accent)":"var(--text-dim)",fontSize:10,fontWeight:600,flexShrink:0},children:e.sessions.length}),(0,n.jsx)("button",{type:"button",onClick:d,disabled:!e.cwd,"aria-label":"New session in this project",title:e.cwd?"New session in this project":"Select a project path first",style:{width:24,height:24,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:6,border:"none",padding:0,color:e.cwd&&c?"var(--accent)":"var(--text-dim)",background:c&&e.cwd?"var(--bg)":"transparent",opacity:c||o?1:0,pointerEvents:e.cwd&&(c||o)?"auto":"none",cursor:e.cwd?"pointer":"default",flexShrink:0,transition:"opacity 0.12s, color 0.12s, background 0.12s"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,n.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})})]})}function el({node:e,selectedSessionId:t,onSelectSession:r,onRenamed:o,onSessionDeleted:l,depth:s}){let[a,d]=(0,i.useState)(!1),c=e.children.length>0;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{position:"relative"},children:[s>0&&(0,n.jsx)("div",{style:{position:"absolute",left:12*s+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,n.jsx)(es,{session:e.session,isSelected:e.session.id===t,onClick:()=>r(e.session),onRenamed:o,onDeleted:e=>l?.(e),depth:s,hasChildren:c,collapsed:a,onToggleCollapse:()=>d(e=>!e)})]}),c&&!a&&(0,n.jsx)("div",{children:e.children.map(e=>(0,n.jsx)(el,{node:e,selectedSessionId:t,onSelectSession:r,onRenamed:o,onSessionDeleted:l,depth:s+1},e.session.id))})]})}function es({session:e,isSelected:t,onClick:r,onRenamed:o,onDeleted:l,depth:s=0,hasChildren:a=!1,collapsed:d=!1,onToggleCollapse:c}){let[u,p]=(0,i.useState)(!1),[h,x]=(0,i.useState)(!1),[g,f]=(0,i.useState)(""),[v,m]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1),j=(0,i.useRef)(null),k=e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12),w=(0,i.useCallback)(t=>{t.stopPropagation(),f(e.name??""),x(!0),setTimeout(()=>j.current?.select(),0)},[e.name]),S=(0,i.useCallback)(async()=>{let t=g.trim();if(x(!1),t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),o?.()}catch{}},[g,e.id,e.name,o]),C=(0,i.useCallback)(e=>{e.stopPropagation(),m(!0)},[]),T=(0,i.useCallback)(async t=>{t.stopPropagation(),m(!1),b(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),l?.(e.id)}catch{b(!1)}},[e.id,l]),z=(0,i.useCallback)(e=>{e.stopPropagation(),m(!1)},[]);return(0,n.jsx)("div",{onClick:v||h?void 0:r,onMouseEnter:()=>p(!0),onMouseLeave:()=>{p(!1)},style:{height:54,display:"flex",alignItems:"center",paddingLeft:s>0?12*s+14:14,paddingRight:8,cursor:v||h?"default":"pointer",background:v?"rgba(239,68,68,0.06)":t?"var(--bg-selected)":u?"var(--bg-hover)":"transparent",borderLeft:v?"2px solid #ef4444":t?"2px solid var(--accent)":"2px solid transparent",transition:"background 0.1s",opacity:y?.5:1,gap:6,overflow:"hidden"},children:v?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["Delete ",(0,n.jsxs)("span",{style:{fontWeight:600},children:["“",k.slice(0,22),k.length>22?"…":"","”"]}),"?"]}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,n.jsxs)("button",{onClick:T,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"#ef4444",border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),"Delete"]}),(0,n.jsx)("button",{onClick:z,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:"Cancel"})]})]}):h?(0,n.jsx)("input",{ref:j,value:g,onChange:e=>f(e.target.value),onBlur:S,onKeyDown:e=>{"Enter"===e.key&&S(),"Escape"===e.key&&x(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,n.jsxs)(n.Fragment,{children:[s>0&&(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:t?500:400,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},title:k,children:k}),(0,n.jsxs)("div",{style:{marginTop:2,display:"flex",gap:8,color:"var(--text-dim)",fontSize:11},children:[(0,n.jsx)("span",{title:e.modified,children:Q(e.modified)}),(0,n.jsxs)("span",{children:[e.messageCount," msgs"]})]})]}),a&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),c?.()},title:d?"Expand forks":"Collapse forks",style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:d?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),u&&(0,n.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,n.jsx)("button",{onClick:w,title:"Rename",style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,n.jsx)("button",{onClick:C,title:"Delete",style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let ea=new Set;function ed(e){return ea.add(e),()=>{ea.delete(e)}}function ec(){return"u"<typeof document?"light":document.documentElement.classList.contains("dark")?"dark":"light"}function eu(){return"light"}function ep(){let e=(0,i.useSyncExternalStore)(ed,ec,eu);return{theme:e,toggleTheme:(0,i.useCallback)(e=>{let t="dark"===ec()?"light":"dark",r=()=>{"dark"===t?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark");try{localStorage.setItem("pi-theme",t)}catch{}ea.forEach(e=>e())},n=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||n)return void r();let i=e?.x??window.innerWidth/2,o=e?.y??window.innerHeight/2,l=Math.hypot(Math.max(i,window.innerWidth-i),Math.max(o,window.innerHeight-o));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${i}px ${o}px)`,`circle(${l}px at ${i}px ${o}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),isDark:"dark"===e}}function eh(e){let t,r=[],n=/`{1,3}show-widget`{0,3}\s*(?:\n\s*`{3}(?:json|html)?\s*)?\n?/g,i=0,o=!1;for(;null!==(t=n.exec(e));){o=!0;let l=e.slice(i,t.index).trim();l&&r.push({type:"text",content:l});let s=t.index+t[0].length,a=e.indexOf("```",s),d=e.indexOf("{",s);if(-1!==d&&d<=s+200&&(-1===a||d<a)){let t=function(e,t){let r=0,n=!1,i=!1;for(let o=t;o<e.length;o++){let t=e[o];if(i){i=!1;continue}if("\\"===t&&n){i=!0;continue}if('"'===t){n=!n;continue}if(!n&&("{"===t&&r++,"}"===t)&&0==--r)return o}return -1}(e,d);if(-1===t){let t=function(e){try{let t=ex(e);if(t)return t}catch{}let t=e.indexOf('"widget_code"');if(-1===t)return null;let r=e.indexOf(":",t+13);if(-1===r)return null;let n=e.indexOf('"',r+1);if(-1===n)return null;let i=e.slice(n+1);(i=i.replace(/"\s*\}\s*$/,"")).endsWith("\\")&&(i=i.slice(0,-1));let o=e.match(/"title"\s*:\s*"([^"]*?)"/)?.[1],l=eg(i.replace(/\\\\/g,"\0BACKSLASH\0").replace(/\\n/g,"\n").replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\"/g,'"').replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/\x00BACKSLASH\x00/g,"\\"));return l.code.trim()?{title:o,code:l.code,showOverlay:l.truncated}:null}(e.slice(d));t&&r.push({type:"widget",...t,partial:!0}),i=e.length;break}let o=ex(e.slice(d,t+1).trim());o&&r.push({type:"widget",...o});let l=t+1,s=e.slice(l,l+16).match(/^\s*\n?`{1,3}\s*/);s&&(l+=s[0].length),i=l,n.lastIndex=l;continue}if(-1!==a){let t=e.slice(s,a).trim(),o=ex(t);o?r.push({type:"widget",...o}):t&&r.push({type:"text",content:t}),n.lastIndex=i=a+3}else{let t=ex(e.slice(s).trim());if(t){let e=eg(t.code);r.push({type:"widget",title:t.title,code:e.code,partial:!0,showOverlay:e.truncated})}i=e.length;break}}let l=e.slice(i).trim();return l&&r.push({type:"text",content:l}),!o&&0===r.length&&e.trim()&&r.push({type:"text",content:e}),r}function ex(e){if(e.startsWith("{")){if(!e.endsWith("}"))return null;try{let t=JSON.parse(e),r=t.widget_code??t.code;if(r)return{title:t.title,code:r}}catch{return null}}return/<(!DOCTYPE|html|svg|canvas|script|style|div)/i.test(e)?{code:e}:null}function eg(e){let t=e.lastIndexOf("<script");if(-1===t)return{code:e,truncated:!1};let r=e.slice(t);return/<script[\s\S]*?<\/script>/i.test(r)?{code:e,truncated:!1}:{code:e.slice(0,t).trim(),truncated:!0}}let ef=/<(iframe|object|embed|meta|link|base|form)[\s>][\s\S]*?<\/\1>/gi,ev=/<(iframe|object|embed|meta|link|base)\b[^>]*\/?>/gi;function em(e){return e.replace(ef,"").replace(ev,"")}let ey=["--bg","--bg-panel","--bg-hover","--bg-selected","--border","--text","--text-muted","--text-dim","--accent","--accent-hover"];function eb(){if("u"<typeof document)return{};let e=getComputedStyle(document.documentElement),t={};for(let r of ey){let n=e.getPropertyValue(r).trim();n&&(t[r]=n)}return t}let ej=["--bg","--bg-panel","--bg-hover","--bg-selected","--border","--text","--text-muted","--text-dim","--accent","--accent-hover"];async function ek(e){if(navigator.clipboard?.writeText)return void await navigator.clipboard.writeText(e);let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.inset="0",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();let r=document.execCommand("copy");if(document.body.removeChild(t),!r)throw Error("Clipboard copy failed.")}async function ew(e){let t=await eS(e.code);if(t)return t;if(e.capture)return function(e){if(!e.html)throw Error("The widget did not provide capturable HTML.");let t=ez({width:e.bodyWidth||640,height:e.bodyHeight||360}),r=function(e){let t=document.createElement("template");t.innerHTML=em(e.html||"");let r=document.createElement("div");for(let n of(r.appendChild(t.content.cloneNode(!0)),Array.from(r.querySelectorAll("img[data-canvas-export]")))){let t=Number(n.getAttribute("data-canvas-export")),r=Number.isFinite(t)?e.canvases?.[t]:null;if(!r?.dataUrl){n.remove();continue}n.setAttribute("src",r.dataUrl),n.setAttribute("width",String(r.width)),n.setAttribute("height",String(r.height)),n.setAttribute("style",function(e,t){let r=new Map;for(let t of(e||"").split(";")){let[e,...n]=t.split(":");e?.trim()&&n.length>0&&r.set(e.trim(),n.join(":").trim())}for(let[e,n]of Object.entries(t))r.set(e,n);return Array.from(r.entries()).map(([e,t])=>e+":"+t).join(";")}(n.getAttribute("style"),{width:r.width+"px",height:r.height+"px",display:"block"}))}return eC(r),Array.from(r.childNodes).map(e=>new XMLSerializer().serializeToString(e)).join("")}(e);if(!r.trim())throw Error("The widget capture was empty.");let n=[e.styles||"","#__widget_export_root{"+function(){if("u"<typeof document)return"";let e=getComputedStyle(document.documentElement);return ej.map(t=>{let r=e.getPropertyValue(t).trim();return r?t+":"+r+";":""}).join("")}()+'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;font-size:14px;line-height:1.6;color:var(--text,#1a1a1a);background:transparent;}',"#__widget_export_root *{box-sizing:border-box;}\n#__widget_export_root svg{max-width:100%;height:auto;display:block;}"].join("\n");return eI(eM('<svg xmlns="http://www.w3.org/2000/svg" width="'+t.width+'" height="'+t.height+'" viewBox="0 0 '+t.width+" "+t.height+'"><defs><style><![CDATA['+n.replace(/\]\]>/g,"]]]]><![CDATA[>")+']]></style></defs><foreignObject x="0" y="0" width="100%" height="100%">'+('<div xmlns="http://www.w3.org/1999/xhtml" id="__widget_export_root" style="width:'+t.width+"px;min-height:")+t.height+'px;overflow:visible;">'+r+"</div></foreignObject></svg>"),t.width,t.height)}(e.capture);throw Error("PNG export needs a rendered widget capture.")}async function eS(e){var t;let r,n,i,o,l=function(e){let t=em(e).trim();if(!/^<\s*(style|svg)\b/i.test(t))return null;let r=new DOMParser().parseFromString(t,"text/html"),n=Array.from(r.body.children),i=n.filter(e=>"svg"===e.tagName.toLowerCase()),o=n.filter(e=>"style"!==e.tagName.toLowerCase());if(1!==i.length||1!==o.length)return null;let l=i[0].cloneNode(!0),s=Array.from(r.body.querySelectorAll("style")).map(e=>e.textContent||"").join("\n").trim();if(s){let e=document.createElementNS("http://www.w3.org/2000/svg","style");e.textContent=s,l.insertBefore(e,l.firstChild)}return l}(e);if(!l)return null;eC(l),l.setAttribute("xmlns","http://www.w3.org/2000/svg");let s=ez((r=function(e){if(!e)return null;let t=e.trim().split(/[\s,]+/).map(Number);return 4!==t.length||t.some(e=>!Number.isFinite(e))||t[2]<=0||t[3]<=0?null:{width:t[2],height:t[3]}}((t=l).getAttribute("viewBox")),n=eT(t.getAttribute("width"))??r?.width??640,i=r?r.height/r.width:.5625,o=eT(t.getAttribute("height"))??r?.height??n*i,{width:n,height:o}));return l.setAttribute("width",String(s.width)),l.setAttribute("height",String(s.height)),l.getAttribute("viewBox")||l.setAttribute("viewBox","0 0 "+s.width+" "+s.height),eI(eM(new XMLSerializer().serializeToString(l)),s.width,s.height)}function eC(e){for(let t of Array.from(e.querySelectorAll("script, iframe, object, embed, meta, link, base, form")))t.remove();for(let t of[e,...Array.from(e.querySelectorAll("*"))])for(let e of Array.from(t.attributes)){let r=e.name.toLowerCase(),n=e.value.trim();if(r.startsWith("on")){t.removeAttribute(e.name);continue}("href"===r||"src"===r||r.endsWith(":href"))&&/^\s*(javascript|data:text\/html)/i.test(n)&&t.removeAttribute(e.name)}}function eT(e){if(!e||e.includes("%"))return null;let t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?t:null}function ez(e){let t=eL(Math.ceil(e.width||640),240,2e3),r=eL(Math.ceil(e.height||360),80,4e3),n=t*r;if(n>8e6){let e=Math.sqrt(8e6/n);t=Math.max(240,Math.floor(t*e)),r=Math.max(80,Math.floor(r*e))}return{width:t,height:r}}function eL(e,t,r){return Math.min(Math.max(e,t),r)}function eI(e,t,r){return new Promise((n,i)=>{let o=new Image,l=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"}));o.onload=()=>{URL.revokeObjectURL(l);try{let e=document.createElement("canvas"),l=Math.min(window.devicePixelRatio||1,2);e.width=Math.ceil(t*l),e.height=Math.ceil(r*l),e.style.width=t+"px",e.style.height=r+"px";let s=e.getContext("2d");if(!s)throw Error("Canvas is not available.");s.scale(l,l),s.drawImage(o,0,0,t,r),e.toBlob(e=>{e?n(e):i(Error("Canvas export returned no image."))},"image/png")}catch(e){i(e instanceof Error?e:Error("PNG export failed."))}},o.onerror=()=>{URL.revokeObjectURL(l),i(Error("The browser could not render this widget as PNG."))},o.src=l})}function eM(e){if("u"<typeof document)return e;let t=getComputedStyle(document.documentElement);return e.replace(/var\(\s*(--[a-zA-Z0-9_-]+)(?:\s*,\s*([^)]+))?\)/g,(e,r,n)=>t.getPropertyValue(r).trim()||n?.trim()||"#000")}let eR=/cdnjs\.cloudflare\.com|cdn\.jsdelivr\.net|unpkg\.com|esm\.sh/,eW=new Map;function eE(e){return e.slice(0,200)}function e$({code:e,isStreaming:t,title:r,showOverlay:o,onSendMessage:l}){let{isDark:s}=ep(),a=(0,i.useRef)(null),d=(0,i.useRef)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),p=(0,i.useRef)(""),[h,x]=(0,i.useState)(!1),[g,f]=(0,i.useState)(()=>eW.get(eE(e))??0),[v,m]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1),[j,k]=(0,i.useState)(null),[w,S]=(0,i.useState)(!1),[C,T]=(0,i.useState)(!1),z=(0,i.useRef)(""),L=(0,i.useRef)((eW.get(eE(e))??0)>0),I=(0,i.useRef)(!1),M=(0,i.useRef)(s),R=(0,i.useMemo)(()=>eR.test(e),[e]),W=(0,i.useMemo)(()=>{let e;return function(e="",t=!1){return`<!DOCTYPE html>
2
- <html class="${t?"dark":""}">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width,initial-scale=1">
6
- <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://unpkg.com https://esm.sh; style-src 'unsafe-inline'; img-src * data: blob:; font-src * data:; connect-src 'none'">
7
- <style>
8
- ${e}
9
- </style>
10
- </head>
11
- <body>
12
- <div id="__root" style="height:fit-content;"></div>
13
- <script>
14
- (function() {
15
- var root = document.getElementById("__root");
16
- var timer = null;
17
- var first = true;
18
- var lastHeight = 0;
19
-
20
- function notifyReady() {
21
- parent.postMessage({ type: "widget:ready" }, "*");
22
- }
23
-
24
- function reportHeight() {
25
- if (timer) clearTimeout(timer);
26
- timer = setTimeout(function() {
27
- var rect = root.getBoundingClientRect();
28
- var h = Math.ceil(Math.max(rect.height, document.body.scrollHeight, document.documentElement.scrollHeight));
29
- if (h > 0 && h !== lastHeight) {
30
- lastHeight = h;
31
- parent.postMessage({ type: "widget:resize", height: h, first: first }, "*");
32
- }
33
- first = false;
34
- }, 60);
35
- }
36
-
37
- function handleUpdate(html) {
38
- root.innerHTML = html;
39
- reportHeight();
40
- }
41
-
42
- function handleFinalize(html) {
43
- var tmp = document.createElement("div");
44
- tmp.innerHTML = html;
45
- var nodes = tmp.querySelectorAll("script");
46
- var scripts = [];
47
- for (var i = 0; i < nodes.length; i++) {
48
- var item = { src: nodes[i].src || "", text: nodes[i].textContent || "", attrs: [] };
49
- for (var j = 0; j < nodes[i].attributes.length; j++) {
50
- var attr = nodes[i].attributes[j];
51
- if (attr.name !== "src" && attr.name !== "onload") item.attrs.push({ name: attr.name, value: attr.value });
52
- }
53
- scripts.push(item);
54
- nodes[i].remove();
55
- }
56
- var visualHtml = tmp.innerHTML;
57
- if (root.innerHTML !== visualHtml) root.innerHTML = visualHtml;
58
-
59
- var cdnScripts = scripts.filter(function(s) { return !!s.src; });
60
- var inlineScripts = scripts.filter(function(s) { return !s.src && s.text; });
61
- function appendInline() {
62
- for (var k = 0; k < inlineScripts.length; k++) {
63
- var s = document.createElement("script");
64
- s.textContent = inlineScripts[k].text;
65
- for (var a = 0; a < inlineScripts[k].attrs.length; a++) {
66
- s.setAttribute(inlineScripts[k].attrs[a].name, inlineScripts[k].attrs[a].value);
67
- }
68
- root.appendChild(s);
69
- }
70
- reportHeight();
71
- setTimeout(function() { parent.postMessage({ type: "widget:scriptsReady" }, "*"); }, 50);
72
- }
73
- if (cdnScripts.length === 0) {
74
- appendInline();
75
- } else {
76
- var pending = cdnScripts.length;
77
- function done() { pending--; if (pending <= 0) appendInline(); }
78
- for (var c = 0; c < cdnScripts.length; c++) {
79
- var n = document.createElement("script");
80
- n.src = cdnScripts[c].src;
81
- n.onload = done;
82
- n.onerror = done;
83
- for (var d = 0; d < cdnScripts[c].attrs.length; d++) {
84
- n.setAttribute(cdnScripts[c].attrs[d].name, cdnScripts[c].attrs[d].value);
85
- }
86
- root.appendChild(n);
87
- }
88
- }
89
- reportHeight();
90
- setTimeout(reportHeight, 150);
91
- setTimeout(reportHeight, 600);
92
- }
93
-
94
- function handleTheme(vars) {
95
- Object.entries(vars || {}).forEach(function(_a) {
96
- var key = _a[0], val = _a[1];
97
- document.documentElement.style.setProperty(key, val);
98
- });
99
- if (typeof arguments[1] === "boolean") {
100
- document.documentElement.className = arguments[1] ? "dark" : "";
101
- }
102
- reportHeight();
103
- }
104
-
105
- function captureRenderedWidget(requestId) {
106
- try {
107
- var html = root.innerHTML;
108
- var styles = "";
109
- var styleEls = document.querySelectorAll("style");
110
- for (var si = 0; si < styleEls.length; si++) {
111
- styles += styleEls[si].textContent || "";
112
- }
113
-
114
- var canvases = document.querySelectorAll("canvas");
115
- var snapshots = [];
116
- var placeholders = [];
117
- var hidden = [];
118
- for (var ci = 0; ci < canvases.length; ci++) {
119
- try {
120
- var canvas = canvases[ci];
121
- var placeholder = document.createElement("img");
122
- placeholder.setAttribute("data-canvas-export", String(ci));
123
- placeholder.style.cssText = "width:" + canvas.offsetWidth + "px;height:" + canvas.offsetHeight + "px;display:block;";
124
- canvas.parentNode.insertBefore(placeholder, canvas);
125
- placeholders.push(placeholder);
126
- hidden.push({ node: canvas, display: canvas.style.display });
127
- canvas.style.display = "none";
128
- snapshots.push({
129
- dataUrl: canvas.toDataURL("image/png"),
130
- width: canvas.offsetWidth,
131
- height: canvas.offsetHeight,
132
- });
133
- } catch (_err) {
134
- snapshots.push(null);
135
- }
136
- }
137
-
138
- html = root.innerHTML;
139
-
140
- for (var pi = 0; pi < placeholders.length; pi++) {
141
- placeholders[pi].remove();
142
- }
143
- for (var hi = 0; hi < hidden.length; hi++) {
144
- hidden[hi].node.style.display = hidden[hi].display;
145
- }
146
-
147
- parent.postMessage({
148
- type: "widget:captured",
149
- requestId: requestId,
150
- html: html,
151
- styles: styles,
152
- canvases: snapshots,
153
- bodyWidth: document.body.scrollWidth,
154
- bodyHeight: document.body.scrollHeight,
155
- }, "*");
156
- } catch (_err) {
157
- parent.postMessage({ type: "widget:captured", requestId: requestId, html: null }, "*");
158
- }
159
- }
160
-
161
- var ro = new ResizeObserver(reportHeight);
162
- ro.observe(root);
163
-
164
- window.addEventListener("message", function(e) {
165
- if (!e.data || typeof e.data.type !== "string") return;
166
- switch (e.data.type) {
167
- case "widget:update": handleUpdate(e.data.html || ""); break;
168
- case "widget:finalize": handleFinalize(e.data.html || ""); break;
169
- case "widget:theme": handleTheme(e.data.vars, e.data.isDark); break;
170
- case "widget:capture": captureRenderedWidget(e.data.requestId); break;
171
- case "widget:crossFilter":
172
- window.dispatchEvent(new CustomEvent("widget-filter", { detail: e.data.payload }));
173
- break;
174
- }
175
- });
176
-
177
- document.addEventListener("click", function(e) {
178
- var a = e.target && e.target.closest ? e.target.closest("a[href]") : null;
179
- if (!a) return;
180
- var href = a.getAttribute("href");
181
- if (!href || href.charAt(0) === "#") return;
182
- e.preventDefault();
183
- parent.postMessage({ type: "widget:link", href: href }, "*");
184
- });
185
-
186
- window.__widgetSendMessage = function(text) {
187
- if (typeof text === "string" && text.length <= 500) {
188
- parent.postMessage({ type: "widget:sendMessage", text: text }, "*");
189
- }
190
- };
191
-
192
- window.__widgetPublish = function(topic, data) {
193
- if (typeof topic === "string") {
194
- parent.postMessage({ type: "widget:publish", topic: topic, data: data }, "*");
195
- }
196
- };
197
-
198
- notifyReady();
199
- })();
200
- </script>
201
- </body>
202
- </html>`}((e=Object.entries({"--bg":"#ffffff","--bg-panel":"#f5f5f5","--bg-hover":"#eeeeee","--bg-selected":"#e8e8e8","--border":"#e0e0e0","--text":"#1a1a1a","--text-muted":"#6b7280","--text-dim":"#9ca3af","--accent":"#2563eb","--accent-hover":"#1d4ed8",..."u"<typeof document?{}:eb(),"--font-mono":"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"}).map(([e,t])=>` ${e}: ${t};`).join("\n"),`
203
- :root {
204
- ${e}
205
- }
206
- .dark { color-scheme: dark; }
207
- body {
208
- --color-background-primary: var(--bg, #fff);
209
- --color-background-secondary: var(--bg-panel, #f5f5f5);
210
- --color-background-tertiary: var(--bg-hover, #eee);
211
- --color-text-primary: var(--text, #1a1a1a);
212
- --color-text-secondary: var(--text-muted, #6b7280);
213
- --color-text-tertiary: var(--text-dim, #9ca3af);
214
- --color-border-tertiary: var(--border, #e0e0e0);
215
- --color-border-secondary: var(--border, #e0e0e0);
216
- --color-border-primary: var(--accent, #2563eb);
217
- --font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
218
- --border-radius-md: 8px;
219
- --border-radius-lg: 12px;
220
- margin: 0;
221
- padding: 0;
222
- font-family: var(--font-sans);
223
- font-size: 14px;
224
- line-height: 1.6;
225
- color: var(--color-text-primary);
226
- background: transparent;
227
- }
228
- * { box-sizing: border-box; }
229
- svg { max-width: 100%; height: auto; display: block; }
230
- a { color: var(--accent, #2563eb); }
231
- button, input, select, textarea { font: inherit; }
232
- button {
233
- border: 1px solid var(--color-border-tertiary);
234
- border-radius: var(--border-radius-md);
235
- background: var(--color-background-secondary);
236
- color: var(--color-text-primary);
237
- padding: 5px 10px;
238
- cursor: pointer;
239
- }
240
- button:hover { background: var(--color-background-tertiary); }
241
- input[type="range"] { accent-color: var(--accent, #2563eb); }
242
- `),M.current)},[]);(0,i.useEffect)(()=>{function t(t){if(t.data&&"string"==typeof t.data.type&&(!a.current||t.source===a.current.contentWindow))switch(t.data.type){case"widget:ready":x(!0);break;case"widget:captured":{let e=String(t.data.requestId??""),r=u.current.get(e);if(!r)break;clearTimeout(r.timeout),u.current.delete(e),r.resolve({html:"string"==typeof t.data.html?t.data.html:null,styles:"string"==typeof t.data.styles?t.data.styles:"",canvases:Array.isArray(t.data.canvases)?t.data.canvases:[],bodyWidth:"number"==typeof t.data.bodyWidth?t.data.bodyWidth:void 0,bodyHeight:"number"==typeof t.data.bodyHeight?t.data.bodyHeight:void 0});break}case"widget:resize":if("number"==typeof t.data.height&&t.data.height>0){let r=Math.min(t.data.height+2,2e3),n=eE(e);if(I.current){f(e=>{let t=Math.max(e,r);return eW.set(n,t),t});break}if(eW.set(n,r),L.current)f(r);else{L.current=!0;let e=a.current;e&&(e.style.transition="none",e.offsetHeight),f(r),requestAnimationFrame(()=>{e&&(e.style.transition="height 0.2s ease-out")})}}break;case"widget:link":{let e=String(t.data.href??"");e&&!/^\s*(javascript|data)\s*:/i.test(e)&&window.open(e,"_blank","noopener,noreferrer");break}case"widget:sendMessage":{let e=String(t.data.text??"");e&&e.length<=500&&l?.(e);break}case"widget:publish":window.dispatchEvent(new CustomEvent("widget-cross-publish",{detail:{topic:t.data.topic,data:t.data.data,sourceIframe:a.current}}))}}return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e,l]),(0,i.useEffect)(()=>{let e=u.current;return()=>{for(let t of(c.current&&clearTimeout(c.current),e.values()))clearTimeout(t.timeout),t.reject(Error("Widget renderer unmounted."));e.clear()}},[]),(0,i.useEffect)(()=>{function e(e){let t=e.detail;a.current?.contentWindow&&t?.sourceIframe!==a.current&&a.current.contentWindow.postMessage({type:"widget:crossFilter",payload:{topic:t?.topic,data:t?.data}},"*")}return window.addEventListener("widget-cross-publish",e),()=>window.removeEventListener("widget-cross-publish",e)},[]);let E=(0,i.useCallback)(e=>{let t=a.current;t?.contentWindow&&e!==p.current&&(p.current=e,t.contentWindow.postMessage({type:"widget:update",html:e},"*"))},[]);(0,i.useEffect)(()=>{if(!t||!h)return;let r=em(e).replace(/\s+on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>"']*)/gi,"").replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<script\b[^>]*\/?>/gi,"").replace(/\s+(href|src|action)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']*))/gi,(e,t,r,n,i)=>{let o=(r??n??i??"").trim();return/^\s*(javascript|data)\s*:/i.test(o)?"":e});return d.current&&clearTimeout(d.current),d.current=setTimeout(()=>E(r),120),()=>{d.current&&clearTimeout(d.current)}},[e,t,h,E]),(0,i.useEffect)(()=>{if(t||!h||z.current===e)return;let r=em(e),n=a.current;if(!n?.contentWindow)return;z.current=e,p.current=r,I.current=!0,T(!1),n.contentWindow.postMessage({type:"widget:finalize",html:r},"*");let i=setTimeout(()=>{I.current=!1,T(!0)},450);return()=>clearTimeout(i)},[t,h,e]),(0,i.useEffect)(()=>{if(!h)return;let e=()=>{a.current?.contentWindow?.postMessage({type:"widget:theme",vars:eb(),isDark:s},"*")};e();let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>t.disconnect()},[h,s]),(0,i.useEffect)(()=>{if(!y)return;let e=document.body.style.overflow;document.body.style.overflow="hidden";let t=e=>{"Escape"===e.key&&b(!1)};return window.addEventListener("keydown",t),()=>{document.body.style.overflow=e,window.removeEventListener("keydown",t)}},[y]);let $=(0,i.useCallback)(e=>{c.current&&clearTimeout(c.current),k(e),c.current=setTimeout(()=>k(null),1800)},[]),B=(0,i.useCallback)(()=>{let e=a.current?.contentWindow;return e?new Promise((t,r)=>{let n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,i=setTimeout(()=>{u.current.delete(n),r(Error("Timed out waiting for widget capture."))},2500);u.current.set(n,{resolve:t,reject:r,timeout:i}),e.postMessage({type:"widget:capture",requestId:n},"*")}):Promise.reject(Error("Widget iframe is not ready."))},[]),N=(0,i.useCallback)(async()=>{try{let t;await ek((t={widget_code:e},r?.trim()&&(t.title=r.trim()),"```show-widget\n"+JSON.stringify(t,null,2)+"\n```")),$("Copied source")}catch{$("Copy failed")}},[e,r,$]),P=(0,i.useCallback)(async()=>{try{await ek(e),$("Copied HTML/SVG")}catch{$("Copy failed")}},[e,$]),A=(0,i.useCallback)(async()=>{if(!t&&!w){S(!0),$("Exporting PNG...");try{var n,i;let t,o,l;try{t=await ew({code:e})}catch{let r=await B();t=await ew({code:e,capture:r})}n=t,i=`${((r||"widget").trim()||"widget").replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"widget"}.png`,o=URL.createObjectURL(n),(l=document.createElement("a")).href=o,l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o),$("Downloaded PNG")}catch(e){console.warn("[WidgetRenderer] PNG export failed:",e),$("PNG export unavailable")}finally{S(!1)}}},[e,r,t,w,B,$]),D=o||R&&!t&&h&&!C,H={width:24,height:22,padding:0,background:"var(--bg-hover)",color:"var(--text-dim)",border:"1px solid var(--border)",borderRadius:3,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},O={...H,width:48,fontSize:10,whiteSpace:"nowrap"};return(0,n.jsxs)("div",{className:"widget-frame",style:{position:y?"fixed":"relative",inset:y?12:void 0,zIndex:y?1e3:void 0,marginTop:4*!y,marginBottom:4*!y,borderRadius:y?8:6,background:y?"var(--bg)":void 0,boxShadow:y?"0 24px 80px rgba(0, 0, 0, 0.35)":void 0,display:y?"flex":void 0,flexDirection:y?"column":void 0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 10px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderBottom:"none",borderRadius:`${y?8:6}px ${y?8:6}px 0 0`,fontSize:11,color:"var(--text-dim)",minHeight:26,flexShrink:0},children:[(0,n.jsx)("span",{style:{fontWeight:600,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r||"Widget"}),t&&(0,n.jsx)("span",{style:{fontSize:10,color:"var(--accent)",animation:"pulse 1.5s infinite",flexShrink:0},children:"streaming…"}),j&&(0,n.jsx)("span",{"aria-live":"polite",style:{marginLeft:"auto",fontSize:10,color:"var(--text-muted)",flexShrink:0},children:j}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,marginLeft:j?0:"auto",flexShrink:0},children:[(0,n.jsx)("button",{onClick:N,title:"Copy show-widget source","aria-label":"Copy show-widget source",style:H,children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"16 18 22 12 16 6"}),(0,n.jsx)("polyline",{points:"8 6 2 12 8 18"})]})}),(0,n.jsx)("button",{onClick:P,title:"Copy widget HTML/SVG","aria-label":"Copy widget HTML/SVG",style:H,children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),(0,n.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),(0,n.jsx)("button",{onClick:A,disabled:t||w,title:t?"PNG export is available after streaming finishes":"Export widget as PNG","aria-label":"Export widget as PNG",style:{...H,...t||w?{opacity:.45,cursor:"not-allowed"}:null},children:w?(0,n.jsx)("span",{style:{fontSize:9},children:"..."}):(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,n.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,n.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})}),(0,n.jsx)("button",{onClick:()=>b(e=>!e),title:y?"Exit full screen":"View full screen","aria-label":y?"Exit full screen":"View full screen",style:H,children:y?(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,n.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,n.jsx)("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),(0,n.jsx)("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"15 3 21 3 21 9"}),(0,n.jsx)("polyline",{points:"9 21 3 21 3 15"}),(0,n.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),(0,n.jsx)("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),(0,n.jsx)("button",{onClick:()=>m(e=>!e),title:v?"Show widget preview":"Show widget code",style:O,children:v?"Preview":"Code"})]})]}),v&&(0,n.jsx)("pre",{style:{margin:0,padding:"8px 10px",fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text-muted)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"0 0 6px 6px",overflow:"auto",maxHeight:y?"none":400,flex:y?1:void 0,whiteSpace:"pre-wrap"},children:e}),(0,n.jsx)("iframe",{ref:a,sandbox:"allow-scripts",srcDoc:W,title:r||"Widget",onLoad:()=>x(!0),style:{width:"100%",height:y?"calc(100vh - 50px)":g,minHeight:g>0?void 0:80,border:"1px solid var(--border)",borderRadius:`0 0 ${y?8:6}px ${y?8:6}px`,display:v?"none":"block",overflow:"hidden",background:"transparent",flex:y?1:void 0,transition:L.current?"height 0.2s ease-out":"none"}}),D&&!v&&(0,n.jsx)("div",{className:"widget-shimmer",style:{position:"absolute",inset:0,top:26,pointerEvents:"none",borderRadius:"0 0 6px 6px"}})]})}var eB=r(63143),eN=r(32957),eP=r(59893);function eA({chart:e}){let{isDark:t}=ep(),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(null),d=(0,i.useRef)(`mermaid-${Math.random().toString(36).slice(2)}`);return((0,i.useEffect)(()=>{let n=!1,i=e.trim();return(l(null),a(null),i)?(Promise.all([r.e(2941),r.e(2995),r.e(3308)]).then(r.bind(r,43328)).then(({default:e})=>(e.initialize({startOnLoad:!1,securityLevel:"strict",theme:t?"dark":"default"}),e.render(`${d.current}-${Date.now()}`,i))).then(e=>{n||l(e.svg)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}):void a("Empty Mermaid diagram")},[e,t]),s)?(0,n.jsxs)("div",{className:"mermaid-diagram mermaid-diagram-error",children:[(0,n.jsx)("div",{className:"mermaid-diagram-error-title",children:"Mermaid render failed"}),(0,n.jsx)("div",{className:"mermaid-diagram-error-message",children:s}),(0,n.jsx)("pre",{children:e})]}):(0,n.jsx)("div",{className:"mermaid-diagram",children:o?(0,n.jsx)("div",{className:"mermaid-diagram-canvas",dangerouslySetInnerHTML:{__html:o}}):(0,n.jsx)("div",{className:"mermaid-diagram-loading",children:"Rendering diagram..."})})}var eD=r(7644);let eH={light:eD.vs,dark:eD.xJ},eO={light:eD.vs,dark:eD.bM};function eF(e,t="default"){let r=function(e="default"){return"compact"===e?eO:eH}(t);return e?r.dark:r.light}function eU(e){return/^[a-z][a-z\d+.-]*:/i.test(e)||e.startsWith("//")}function e_(e){let t=$(e),r=t.startsWith("/"),n=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){n.length>0&&".."!==n[n.length-1]?n.pop():r||n.push(e);continue}n.push(e)}return`${r?"/":""}${n.join("/")}`}function eV(e,t){let r,n,i;if(!e||!t||t.startsWith("#")||eU(t))return null;let o=(r=/^([^?#]*)(.*)$/.exec(t),r?.[1]??t);if(!o)return null;let l=function(e){try{return decodeURI(e)}catch{return e}}(o);return l.startsWith("/")?e_(l):e_(`${(i=(n=$(e)).lastIndexOf("/"))>=0?n.slice(0,i):""}/${l}`)}function eJ(e){return`/api/files/${B(e)}?type=read`}function eK({code:e,language:t,variant:r}){let{isDark:o}=ep(),[l,s]=(0,i.useState)(!1);return(0,n.jsxs)("div",{className:`markdown-code-block markdown-code-block-${r}`,style:{position:"relative",marginTop:"file"===r?12:4,marginBottom:"file"===r?12:4,borderRadius:6,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{padding:"3px 10px",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,n.jsx)("span",{children:t||"text"}),(0,n.jsx)("button",{onClick:()=>{(function(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}})(e).then(()=>{s(!0),setTimeout(()=>s(!1),1500)})},style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:l?"copied":"copy"})]}),(0,n.jsx)(eP.A,{language:t||"text",style:eF(o),showLineNumbers:"chat"===r,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal"},customStyle:{margin:0,padding:"file"===r?"12px 16px":"10px 12px",fontSize:"file"===r?13:12.5,lineHeight:1.6,borderRadius:0,background:"var(--bg)"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})}function eq({content:e,className:t="markdown-body",style:r,codeBlockVariant:i="chat",baseFilePath:o,onOpenLocalFile:l,onWidgetSendMessage:s,renderVisualCodeBlocks:a=!1}){return(0,n.jsx)("div",{className:t,style:r,children:(0,n.jsx)(eB.oz,{remarkPlugins:[eN.A],components:{code({className:e,children:t,node:r,...o}){let l,d,c,u=e?.replace(/^language-/,"").trim()??"",p=String(t),h=p.replace(/\n$/,""),x=e?.includes("language-")||p.includes("\n");if(x&&("mermaid"===(l=u.trim().toLowerCase())||"mmd"===l))return(0,n.jsx)(eA,{chart:h});if(x&&"show-widget"===u.trim().toLowerCase()){let e,t=(e=eh(`\`\`\`show-widget
243
- ${h}
244
- \`\`\``).find(e=>"widget"===e.type),e?.type==="widget"?{title:e.title,code:e.code}:null);if(t)return(0,n.jsx)(e$,{code:t.code,isStreaming:!1,title:t.title,onSendMessage:s})}return x&&a&&(d=u.trim().toLowerCase(),(c=h.trim())&&("svg"===d||"xml"===d&&/^<svg[\s>]/i.test(c)?/^<svg[\s>]/i.test(c):!("html"!==d||/<!doctype|<html[\s>]|<head[\s>]|<body[\s>]/i.test(c))&&/^<(style|svg|div|section|article|main|figure|canvas)\b/i.test(c)))?(0,n.jsx)(e$,{code:h,isStreaming:!1,title:`${u||"visual"} preview`,onSendMessage:s}):x?(0,n.jsx)(eK,{code:h,language:u,variant:i}):(0,n.jsx)("code",{style:{background:"var(--bg-selected)",padding:"1px 4px",borderRadius:3,fontFamily:"var(--font-mono)",fontSize:"0.9em"},...o,children:t})},pre:({children:e})=>(0,n.jsx)(n.Fragment,{children:e}),a({href:e,children:t,node:r,...i}){let s=eV(o,e),a=!!s,d=!!e&&eU(e);return(0,n.jsx)("a",{...i,href:a?eJ(s):e,target:d?"_blank":void 0,rel:d?"noreferrer":void 0,onClick:e=>{s&&l&&(e.preventDefault(),l(s,N(s)))},title:a?s:i.title,children:t})},img({src:e,alt:t,node:r,...i}){let l="string"==typeof e?e:void 0,s=eV(o,l),a=s?eJ(s):l;return(0,n.jsx)("img",{...i,src:a,alt:t??"",loading:"lazy",title:s??i.title})}},children:e})})}let eY=/```(?:analysis-report-update|report-update)\s*\n([\s\S]*?)```/gi;function eG(e){if(!e)return null;let t=new Date(e),r=new Date,n=t.getFullYear()===r.getFullYear()&&t.getMonth()===r.getMonth()&&t.getDate()===r.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(n)return i;let o=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==r.getFullYear()?"numeric":void 0});return`${o} ${i}`}function eZ(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}function eX({message:e,isStreaming:t,toolResults:r,modelNames:i,entryId:o,onFork:l,forking:s,onNavigate:a,prevAssistantEntryId:d,onEditContent:c,onSendMessage:u,showTimestamp:p,prevTimestamp:h,renderVisualCodeBlocks:x}){return"user"===e.role?(0,n.jsx)(eQ,{message:e,entryId:o,onFork:l,forking:s,onNavigate:a,prevAssistantEntryId:d,onEditContent:c}):"assistant"===e.role?(0,n.jsx)(e0,{message:e,isStreaming:t,toolResults:r,modelNames:i,onSendMessage:u,showTimestamp:p,prevTimestamp:h,renderVisualCodeBlocks:x}):"toolResult"===e.role?null:"custom"===e.role?(0,n.jsx)(e9,{message:e,showTimestamp:p}):null}function eQ({message:e,entryId:t,onFork:r,forking:o,onNavigate:l,prevAssistantEntryId:s,onEditContent:a}){let[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),x="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),g=eG(e.timestamp),f=!!t&&!!r,v=!!s&&!!l;return(0,n.jsxs)("div",{style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,n.jsxs)("div",{style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid rgba(59,130,246,0.2)",borderRadius:12,padding:"8px 12px",fontSize:14,lineHeight:1.6,color:"var(--text)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[x.length>0&&(0,n.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!h},children:x.map((e,t)=>{let r=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,n.jsx)("img",{src:r,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid rgba(59,130,246,0.15)"}},t)})}),h]})}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,n.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!d,pointerEvents:d?"auto":"none",transition:"opacity 0.12s"},children:(0,n.jsxs)("button",{onClick:()=>{eZ(h).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},title:"Copy message",style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:u?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{u||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{u||(e.currentTarget.style.color="var(--text-dim)")},children:[u?(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,n.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),u?"Copied":"Copy"]})}),(f||v)&&(0,n.jsxs)("div",{style:{display:"flex",gap:3,opacity:d||o?1:0,pointerEvents:d||o?"auto":"none",transition:"opacity 0.12s"},children:[v&&(0,n.jsxs)("button",{onClick:()=>{l(s),a?.(h)},title:"Edit from here — branches within this session",style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,n.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),"Edit from here"]}),f&&(0,n.jsxs)("button",{onClick:()=>{r(t)},disabled:o,title:o?"Creating new session…":"New session — creates an independent copy from here",style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:o?"var(--accent)":"var(--text-dim)",cursor:o?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{o||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),o?"Creating…":"New session"]})]}),g&&(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:g})]})]})}function e0({message:e,isStreaming:t,toolResults:r,modelNames:o,onSendMessage:l,showTimestamp:s,prevTimestamp:a,renderVisualCodeBlocks:d}){var c;let u,p=s?eG(e.timestamp):null,h=e.content??[],[x,g]=(0,i.useState)(!1),[f,v]=(0,i.useState)(!1),m=(0,i.useRef)(null),[y,b]=(0,i.useState)(null),j=(0,i.useRef)(h);j.current=h;let k=(0,i.useRef)(new Map),[w,S]=(0,i.useState)(new Map),C=(0,i.useMemo)(()=>{if(!e.timestamp||!a)return;let t=Math.round((e.timestamp-a)/1e3);return t>0?t:void 0},[e.timestamp,a]),T=(0,i.useMemo)(()=>{let t=new Map;if(!r||!e.timestamp)return t;for(let[n,i]of r)if(i.timestamp&&e.timestamp){let r=Math.round((i.timestamp-e.timestamp)/1e3);r>0&&t.set(n,r)}return t},[r,e.timestamp]),z=h.filter(e=>"text"===e.type).map(e=>e.text).join("\n");return(0,i.useEffect)(()=>{if(!t){let e=Date.now();S(t=>{let r=new Map(t);for(let[t,n]of k.current)r.has(t)||r.set(t,Math.round((e-n)/1e3));return r}),m.current=null,b(null);return}let e=setInterval(()=>{let e=j.current,t=Date.now();e.forEach((e,r)=>{k.current.has(r)||k.current.set(r,t)}),S(r=>{let n=!1,i=new Map(r);for(let r=0;r<e.length-1;r++)if(!i.has(r)&&k.current.has(r)){let e=k.current.get(r),o=k.current.get(r+1)??t;i.set(r,Math.round((o-e)/1e3)),n=!0}return n?i:r});let r=0;for(let t of e)"text"===t.type?r+=t.text?.length??0:"thinking"===t.type?r+=t.thinking?.length??0:"toolCall"===t.type&&(r+=JSON.stringify(t.input??{}).length);if(0===r)return;null===m.current&&(m.current=t);let n=(t-m.current)/1e3;n>.5&&b(r/4/n)},300);return()=>clearInterval(e)},[t]),(0,n.jsxs)("div",{style:{marginBottom:16},onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),children:[(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:4,display:"flex",alignItems:"center",gap:6},children:[e.provider&&(0,n.jsx)("span",{children:o?.[`${e.provider}:${e.model}`]??o?.[e.model]??e.model}),t&&(()=>{let e,t=0;for(let e of h)"text"===e.type?t+=e.text?.length??0:"thinking"===e.type?t+=e.thinking?.length??0:"toolCall"===e.type&&(t+=JSON.stringify(e.input??{}).length);let r=Math.round(t/4);return(0,n.jsx)(n.Fragment,{children:r>0&&(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:"var(--text)"},title:"预估 token 数(流式接收中)",children:[(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},children:[(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,n.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),r]}),null!==y&&(e=y>=50?"#53b3cb":y>=30?"#9bc53d":y>=15?"#f9c22e":"#e01a4f",(0,n.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",borderRadius:4,background:e,color:"#fff",fontSize:11,fontWeight:400},children:[y.toFixed(1)," t/s"]}))]})})})()]}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:h.map((e,i)=>(0,n.jsx)(e1,{block:e,toolResults:r,isStreaming:t,streamingDuration:w.get(i)??("thinking"===e.type?C:void 0),toolCallDurations:T,onSendMessage:l,renderVisualCodeBlocks:d},i))}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[e.usage&&!t&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:(c=e.usage,u=[],c.input&&u.push(`${c.input.toLocaleString()} in`),c.output&&u.push(`${c.output.toLocaleString()} out`),c.cacheRead&&u.push(`${c.cacheRead.toLocaleString()} cache`),c.cost?.total&&u.push(`$${c.cost.total.toFixed(4)}`),u.join(" \xb7 "))}),z&&!t&&(0,n.jsxs)("button",{onClick:()=>{eZ(z).then(()=>{v(!0),setTimeout(()=>v(!1),1500)})},title:"Copy message",style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:f?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{f||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{f||(e.currentTarget.style.color="var(--text-dim)")},children:[f?(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,n.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),f?"Copied":"Copy"]}),p&&!t&&(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:p})]})]})}function e1({block:e,toolResults:t,isStreaming:r,streamingDuration:i,toolCallDurations:o,onSendMessage:l,renderVisualCodeBlocks:s}){if("text"===e.type)return(0,n.jsx)(e2,{block:e,isStreaming:r,onSendMessage:l,renderVisualCodeBlocks:s});if("thinking"===e.type)return(0,n.jsx)(e3,{block:e,duration:i});if("toolCall"===e.type){let r=t?.get(e.toolCallId),i=o?.get(e.toolCallId);return(0,n.jsx)(e8,{block:e,result:r,duration:i})}return null}function e2({block:e,isStreaming:t,onSendMessage:r,renderVisualCodeBlocks:i}){var o;let l=e.text.replace(eY,"").replace(/\n{3,}/g,"\n\n").trim(),s=eh(l),a=s.some(e=>"widget"===e.type),d=(o=e.text,eY.lastIndex=0,eY.test(o));if(!a){if(d&&!l.trim())return(0,n.jsx)(e4,{isStreaming:t});if(t&&/`{1,3}show-widget/.test(l)){let e=s.filter(e=>"text"===e.type).map(e=>e.content).join("\n\n");return(0,n.jsxs)(n.Fragment,{children:[e&&(0,n.jsx)(e5,{text:e,onSendMessage:r,renderVisualCodeBlocks:i}),(0,n.jsx)(e6,{})]})}return(0,n.jsx)(e5,{text:l,onSendMessage:r,renderVisualCodeBlocks:i})}return(0,n.jsx)(n.Fragment,{children:s.map((e,t)=>"text"===e.type?(0,n.jsx)(e5,{text:e.content,onSendMessage:r,renderVisualCodeBlocks:i},t):(0,n.jsx)(e$,{code:e.code,isStreaming:!!e.partial,title:e.title,showOverlay:e.showOverlay,onSendMessage:r},t))})}function e4({isStreaming:e}){return(0,n.jsx)("div",{style:{border:"1px solid var(--border)",borderRadius:6,padding:"8px 10px",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:e?"Updating analysis report...":"Analysis report updated"})}function e5({text:e,onSendMessage:t,renderVisualCodeBlocks:r}){return(0,n.jsx)(eq,{content:e,onWidgetSendMessage:t,renderVisualCodeBlocks:r})}function e6(){return(0,n.jsx)("div",{style:{position:"relative",height:88,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden",background:"var(--bg-panel)"},children:(0,n.jsx)("div",{className:"widget-shimmer",style:{position:"absolute",inset:0}})})}function e3({block:e,duration:t}){let[r,o]=(0,i.useState)(!1);return(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:6,overflow:"hidden",fontSize:13},children:[(0,n.jsxs)("button",{onClick:()=>o(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"6px 10px",background:"var(--bg-panel)",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:[(0,n.jsx)("span",{children:"Thinking"}),void 0!==t&&(0,n.jsxs)("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:[t,"s"]})]}),r&&(0,n.jsx)("div",{style:{padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",background:"var(--bg-panel)",borderTop:"1px solid var(--border)"},children:e.thinking})]})}function e8({block:e,result:t,duration:r}){let[o,l]=(0,i.useState)(!1),s=JSON.stringify(e.input,null,2),a=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,d=null!==a&&("(no output)"===a.trim()||""===a.trim()),c=t?.isError??!1;return(0,n.jsxs)("div",{style:{borderRadius:7,overflow:"hidden",fontSize:12,border:c?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:c?"rgba(248,113,113,0.05)":"rgba(34,197,94,0.04)"},children:[(0,n.jsxs)("button",{onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,n.jsx)("span",{style:{color:c?"#f87171":"#16a34a",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:e.toolName}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:function(e){let t=e.input;if(!t||"object"!=typeof t)return"";let r=Object.keys(t);return 0===r.length?"":"command"in t?String(t.command).slice(0,120):"path"in t?String(t.path).slice(0,120):"file_path"in t?String(t.file_path).slice(0,120):"pattern"in t?String(t.pattern).slice(0,120):"query"in t?String(t.query).slice(0,120):String(t[r[0]]).slice(0,120)}(e)}),void 0!==r&&(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[r,"s"]}),(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:o?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),o&&(0,n.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:c?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:s}),o&&t&&(0,n.jsx)(e7,{text:a??"",isEmpty:d,isError:c})]})}function e7({text:e,isEmpty:t,isError:r}){return(0,n.jsx)("div",{style:{borderTop:`1px solid ${r?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`,background:r?"rgba(248,113,113,0.04)":"var(--bg-subtle)"},children:(0,n.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:r?"#f87171":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?"(no output)":e})})}function e9({message:e,showTimestamp:t}){if(!e.display)return null;let r=t?eG(e.timestamp):null,i="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),o="subagent-notify"===e.customType,l=i.match(/^Background task (completed|failed|paused):\s*\*\*(.+?)\*\*/),s=l?"completed"===l[1]?"✅":"failed"===l[1]?"❌":"⏸":o?"\uD83E\uDD16":"ℹ";return(0,n.jsxs)("div",{style:{marginBottom:12},children:[(0,n.jsx)("div",{style:{padding:"8px 14px",borderRadius:8,border:`1px solid ${o?"rgba(99,102,241,0.25)":"var(--border)"}`,background:o?"rgba(99,102,241,0.05)":"var(--bg-panel)",fontSize:13,lineHeight:1.6,color:"var(--text-muted)"},children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[(0,n.jsx)("span",{style:{flexShrink:0,fontSize:14},children:s}),(0,n.jsx)("div",{style:{flex:1,minWidth:0},children:(0,n.jsx)(eq,{content:i,style:{fontSize:13}})})]})}),(r||l)&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[l&&(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:l[2]}),r&&(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:r})]})]})}let te=["off","default","full","plot"],tt={off:"none",default:"default",full:"full",plot:"full-plot"},tr=["auto","off","minimal","low","medium","high","xhigh"],tn={auto:"沿用 pi 默认设置",off:"关闭推理",minimal:"最少推理",low:"低强度推理",medium:"中等推理",high:"高强度推理",xhigh:"最高强度推理"};function ti({doc:e,onRemove:t}){var r;let i=e.fileName.split(".").pop()?.toLowerCase()??"",o=function(e){switch(e){case"pdf":return{emoji:"\uD83D\uDCC4",color:"#ef4444"};case"docx":case"doc":return{emoji:"\uD83D\uDCDD",color:"#3b82f6"};case"xlsx":case"xls":return{emoji:"\uD83D\uDCCA",color:"#22c55e"};case"pptx":case"ppt":return{emoji:"\uD83D\uDCFD",color:"#f97316"};default:return{emoji:"\uD83D\uDCCE",color:"var(--text-muted)"}}}(i),l=(r=e.size)<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(1)} KB`:`${(r/1048576).toFixed(1)} MB`;return(0,n.jsxs)("div",{style:{position:"relative",display:"flex",alignItems:"center",gap:6,padding:"5px 10px 5px 7px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,maxWidth:200},title:e.fileName,children:[(0,n.jsx)("span",{style:{color:o.color,fontSize:14,flexShrink:0},children:o.emoji}),(0,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1.3},children:e.fileName}),(0,n.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",lineHeight:1.3},children:[i.toUpperCase()," \xb7 ",l,e.extractionError?" \xb7 no text":e.truncated?" \xb7 truncated":e.extractedText?" \xb7 text":""]})]}),(0,n.jsx)("button",{onClick:t,style:{flexShrink:0,width:14,height:14,borderRadius:"50%",background:"var(--bg-hover)",border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:(0,n.jsxs)("svg",{width:"7",height:"7",viewBox:"0 0 7 7",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"1",y1:"1",x2:"6",y2:"6"}),(0,n.jsx)("line",{x1:"6",y1:"1",x2:"1",y2:"6"})]})})]})}function to(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&apos;/g,"'")}async function tl(e){let t=await Promise.all([r.e(2084),r.e(2619)]).then(r.bind(r,66898));t.GlobalWorkerOptions.workerSrc=new r.U(r(9924)).toString();let n=await t.getDocument({data:e.slice(0)}).promise,i=[];for(let e=1;e<=n.numPages;e+=1){let t=await n.getPage(e),r=(await t.getTextContent()).items.map(e=>"str"in e?e.str:"").filter(Boolean).join(" ");r.trim()&&i.push(`Page ${e}
245
- ${r}`)}return i.join("\n\n")}async function ts(e){let t=(await Promise.all([r.e(2619),r.e(4453)]).then(r.t.bind(r,54453,23))).default,n=await t.loadAsync(e),i=["word/document.xml",...Object.keys(n.files).filter(e=>/^word\/(footnotes|endnotes|comments)\.xml$/i.test(e)).sort()],o=[];for(let e of i){let t=n.file(e);if(!t)continue;let r=[...(await t.async("string")).replace(/<w:(br|cr)[^>]*\/>/g,"\n").replace(/<\/w:p>/g,"\n").matchAll(/<w:t[^>]*>([\s\S]*?)<\/w:t>/g)];o.push(...r.map(e=>to(e[1])))}return o.join("").replace(/[ \t]+\n/g,"\n")}async function ta(e){let t=await Promise.all([r.e(3524),r.e(8436)]).then(r.bind(r,15967)),n=t.read(e,{type:"array"});return n.SheetNames.map(e=>{let r=n.Sheets[e],i=t.utils.sheet_to_csv(r);return`Sheet: ${e}
246
- ${i}`}).join("\n\n")}async function td(e){let t=(await Promise.all([r.e(2619),r.e(4453)]).then(r.t.bind(r,54453,23))).default,n=await t.loadAsync(e),i=Object.keys(n.files).map(e=>({name:e,match:/^ppt\/slides\/slide(\d+)\.xml$/i.exec(e)})).filter(e=>null!==e.match).sort((e,t)=>Number(e.match[1])-Number(t.match[1])),o=[];for(let{name:e,match:t}of i){let r=[...(await n.file(e).async("string")).matchAll(/<a:t[^>]*>([\s\S]*?)<\/a:t>/g)].map(e=>to(e[1]).trim()).filter(Boolean);r.length&&o.push(`Slide ${t[1]}
247
- ${r.join("\n")}`)}return o.join("\n\n")}async function tc(e,t){let r=e.name.split(".").pop()?.toLowerCase()??"";try{let n,i="";if(e.type.startsWith("text/")||["csv","tsv","md","txt","json","xml"].includes(r))i=new TextDecoder("utf-8").decode(t);else if("pdf"===r||"application/pdf"===e.type)i=await tl(t);else if("docx"===r)i=await ts(t);else if("xlsx"===r)i=await ta(t);else{if("pptx"!==r)return{extractionError:"Text extraction is not supported for this file type"};i=await td(t)}let{text:o,truncated:l}=(n=i.replace(/\r\n/g,"\n").replace(/\n{4,}/g,"\n\n\n").trim()).length<=6e4?{text:n,truncated:!1}:{text:`${n.slice(0,6e4)}
248
-
249
- [truncated after 60000 characters]`,truncated:!0};if(!o)return{extractionError:"No extractable text found"};return{extractedText:o,truncated:l}}catch(e){return{extractionError:e instanceof Error?e.message:String(e)}}}let tu=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:r,onFollowUp:o,isStreaming:l,model:s,modelNames:a,modelList:d,onModelChange:c,onCompact:u,onAbortCompaction:p,isCompacting:h,compactError:x,toolPreset:g,onToolPresetChange:f,thinkingLevel:v,onThinkingLevelChange:m,availableThinkingLevels:y,thinkingLevelMap:b,retryInfo:j,soundEnabled:k,onSoundToggle:w},S){let C,T,z,[L,I]=(0,i.useState)(""),[M,R]=(0,i.useState)(!1),[W,E]=(0,i.useState)(null),[$,B]=(0,i.useState)(!1),[N,P]=(0,i.useState)(!1),[A,D]=(0,i.useState)([]),[H,O]=(0,i.useState)([]),F=(0,i.useRef)(null),U=(0,i.useRef)(null),_=(0,i.useRef)(null),V=(0,i.useRef)(null),J=(0,i.useRef)(null),K=(0,i.useRef)(null),q=(0,i.useRef)(null);(0,i.useImperativeHandle)(S,()=>({insertIfEmpty(e){let t=F.current;(t?t.value:L).trim()||(I(e),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},insertText(e){let t=F.current;if(!t)return void I(t=>t+(t?" ":"")+e);let r=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length,i=t.value.slice(0,r),o=t.value.slice(n),l=i.length>0&&!i.endsWith(" ")?" ":"";I(i+l+e+o),requestAnimationFrame(()=>{if(!t)return;let n=r+l.length+e.length;t.setSelectionRange(n,n),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addImages(e){Y(e)},addFiles(e){G(e)}}));let Y=(0,i.useCallback)(async e=>{let t=e.filter(e=>e.type.startsWith("image/"));if(!t.length)return;let r=await Promise.all(t.map(e=>new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{t({data:n.result.split(",")[1],mimeType:e.type,previewUrl:URL.createObjectURL(e)})},n.onerror=r,n.readAsDataURL(e)})));D(e=>[...e,...r])},[]),G=(0,i.useCallback)(async e=>{let t=e.filter(e=>e.type.startsWith("image/")),r=e.filter(e=>!e.type.startsWith("image/"));if(t.length&&Y(t),r.length){let e=await Promise.all(r.map(e=>new Promise((t,r)=>{let n=new FileReader;n.onload=async()=>{let r=n.result,i=await tc(e,r);t({data:r,fileName:e.name,mimeType:e.type||"application/octet-stream",size:e.size,...i})},n.onerror=r,n.readAsArrayBuffer(e)})));O(t=>[...t,...e])}},[Y]),Z=(0,i.useCallback)(e=>{D(t=>{let r=[...t];return URL.revokeObjectURL(r[e].previewUrl),r.splice(e,1),r})},[]),X=(0,i.useCallback)(e=>{O(t=>{let r=[...t];return r.splice(e,1),r})},[]),Q=(0,i.useCallback)(()=>{D(e=>(e.forEach(e=>URL.revokeObjectURL(e.previewUrl)),[])),O([])},[]),ee=(0,i.useCallback)(()=>{let t=L.trim();(t||A.length||H.length)&&!l&&(e(t,A.length?A:void 0,H.length?H:void 0),I(""),Q(),F.current&&(F.current.style.height="auto"))},[L,A,H,l,e,Q]),et=(0,i.useCallback)(e=>{let t=L.trim();if(!t&&!A.length&&!H.length)return;let n=A.length?A:void 0,i=H.length?H:void 0;"steer"===e&&r?r(t,n,i):"followup"===e&&o&&o(t,n,i),I(""),Q(),F.current&&(F.current.style.height="auto")},[L,A,H,r,o,Q]),er=(0,i.useCallback)(e=>{"Enter"!==e.key||e.shiftKey||e.nativeEvent.isComposing||(e.preventDefault(),l&&(r||o)?et(r?"steer":"followup"):ee())},[l,r,o,et,ee]),en=(0,i.useCallback)(()=>{let e=F.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),ei=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>"file"===e.kind&&(e.type.startsWith("image/")||e.type.includes("pdf")||e.type.includes("officedocument")||e.type.includes("msword")||e.type.includes("ms-")));t.length&&(e.preventDefault(),G(t.map(e=>e.getAsFile()).filter(e=>null!==e)))},[G]),eo=d&&d.length>0?d.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(a??{}).map(([e,t])=>({provider:s?.provider??"unknown",modelId:e,name:t})),el=[];for(let e of eo){let t=el.find(t=>t.provider===e.provider);t?t.options.push(e):el.push({provider:e.provider,options:[e]})}let es=s?eo.find(e=>e.modelId===s.modelId&&e.provider===s.provider)?.name??s.modelId:eo.length>0?eo[0].name:null;return(0,i.useEffect)(()=>{let e=e=>{U.current&&!U.current.contains(e.target)&&_.current&&!_.current.contains(e.target)&&R(!1),V.current&&!V.current.contains(e.target)&&B(!1),J.current&&!J.current.contains(e.target)&&P(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,n.jsxs)("div",{style:{flexShrink:0,background:"transparent",padding:"0 16px 8px",paddingRight:52},children:[(0,n.jsx)("input",{ref:K,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:e=>{Y(Array.from(e.target.files??[])),e.target.value=""}}),(0,n.jsx)("input",{ref:q,type:"file",accept:".pdf,.docx,.xlsx,.pptx,.doc,.xls,.ppt,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.presentation",multiple:!0,style:{display:"none"},onChange:e=>{G(Array.from(e.target.files??[])),e.target.value=""}}),(0,n.jsxs)("div",{style:{maxWidth:820,margin:"0 auto"},children:[j&&(0,n.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]}),"Retrying (",j.attempt,"/",j.maxAttempts,")…",j.errorMessage&&(0,n.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",j.errorMessage]})]}),(A.length>0||H.length>0)&&(0,n.jsxs)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap",alignItems:"flex-end"},children:[A.map((e,t)=>(0,n.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,n.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}}),(0,n.jsx)("button",{onClick:()=>Z(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,n.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`img-${t}`)),H.map((e,t)=>(0,n.jsx)(ti,{doc:e,onRemove:()=>X(t)},`doc-${t}`))]}),(0,n.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${l&&(r||o)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14,padding:"10px 10px 10px 14px",boxShadow:"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,n.jsx)("textarea",{ref:F,value:L,onChange:e=>I(e.target.value),onKeyDown:er,onInput:en,onPaste:ei,placeholder:l&&(r||o)?"Steer 立即注入 / Follow-up 排队…":l?"Agent is running…":"Message…",rows:1,style:{flex:1,background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),l?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[r&&(0,n.jsxs)("button",{onClick:()=>et("steer"),disabled:!L.trim()&&!A.length&&!H.length,title:"打断 Agent 当前运行,立即注入消息",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:L.trim()||A.length||H.length?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:L.trim()||A.length||H.length?"rgba(180,130,0,1)":"var(--text-dim)",cursor:L.trim()||A.length||H.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),"Steer"]}),o&&(0,n.jsxs)("button",{onClick:()=>et("followup"),disabled:!L.trim()&&!A.length&&!H.length,title:"在 Agent 完成后排队发送",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:L.trim()||A.length||H.length?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:L.trim()||A.length||H.length?"rgba(99,102,241,1)":"var(--text-dim)",cursor:L.trim()||A.length||H.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,n.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,n.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),"Follow-up"]})]}):(0,n.jsxs)("button",{onClick:ee,disabled:!L.trim()&&!A.length&&!H.length,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:L.trim()||A.length||H.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:L.trim()||A.length||H.length?"#fff":"var(--text-dim)",cursor:L.trim()||A.length||H.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:L.trim()||A.length||H.length?"0 1px 3px rgba(37,99,235,0.25)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,n.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),"Send"]})]}),(0,n.jsxs)("div",{style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("div",{style:{flex:"0 0 auto",display:"flex",alignItems:"center",gap:2},children:[(0,n.jsx)("button",{onClick:()=>K.current?.click(),disabled:l,title:"Attach image (right-click for document)",style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:A.length||H.length?"var(--accent)":"var(--text-muted)",cursor:l?"not-allowed":"pointer",opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=A.length||H.length?"var(--accent)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=A.length||H.length?"var(--accent)":"var(--text-muted)"},onContextMenu:e=>{e.preventDefault(),q.current?.click()},children:(0,n.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}),eo.length>0&&es&&c&&(0,n.jsxs)("div",{ref:U,style:{position:"relative"},children:[(0,n.jsxs)("button",{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();E({top:t.top,left:t.left,width:t.width}),R(e=>!e)},disabled:l,style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",height:32,maxWidth:220,overflow:"hidden",background:M?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=M?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:es})]}),M&&W&&(T=(C=window.visualViewport?.height??window.innerHeight)-W.top+6,z=Math.max(120,Math.min(W.top-8,.6*C)),(0,n.jsx)("div",{ref:_,style:{position:"fixed",bottom:T,left:W.left,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",width:"max-content",minWidth:W.width,maxHeight:z,overflowY:"auto"},children:el.map((e,t)=>(0,n.jsxs)("div",{children:[el.length>1&&(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>{let t=e.modelId===s?.modelId&&e.provider===s?.provider;return(0,n.jsxs)("button",{onClick:()=>{R(!1),t||c(e.provider,e.modelId)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),e.name]},`${e.provider}:${e.modelId}`)})]},e.provider))}))]})]}),(0,n.jsx)("div",{style:{flex:1}}),(0,n.jsxs)("div",{style:{flex:"0 0 auto",display:"flex",alignItems:"center",gap:2,marginLeft:"auto"},children:[!l&&m&&(0,n.jsxs)("div",{ref:J,style:{position:"relative"},children:[(0,n.jsxs)("button",{onClick:()=>!l&&P(e=>!e),disabled:l,title:"切换推理强度",style:{display:"flex",alignItems:"center",gap:5,padding:"8px 12px",height:32,background:N?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=N?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,n.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,n.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(0,n.jsx)("span",{children:(()=>{let e=v??"auto";if("auto"===e||!b)return e;let t=b[e];return null!=t?t:e})()})]}),N&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:tr.filter(e=>!y||"auto"===e||y.includes(e)).map(e=>{let t=(v??"auto")===e,r=tn[e],i="auto"!==e&&b?b[e]:void 0,o=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,n.jsxs)("button",{onClick:()=>{P(!1),t||m(e)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsxs)("span",{style:{flex:1},children:[o,l&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:r})]},e)})})]}),!l&&f&&(0,n.jsxs)("div",{ref:V,style:{position:"relative"},children:[(0,n.jsxs)("button",{onClick:()=>!l&&B(e=>!e),disabled:l,title:"切换工具预设",style:{display:"flex",alignItems:"center",gap:5,padding:"8px 12px",height:32,background:$?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=$?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,n.jsx)("span",{children:Object.entries(tt).find(([,e])=>e===(g??"default"))?.[0]??"default"})]}),$&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:te.map(e=>{let t=tt[e],r=(g??"default")===t,i="off"===e?"无工具,纯聊天":"default"===e?"4 项内置工具":"plot"===e?"全工具 + 绘图":"全部内置工具";return(0,n.jsxs)("button",{onClick:()=>{B(!1),r||f(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1},children:e}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!l&&u&&(0,n.jsxs)("div",{style:{position:"relative"},children:[x&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,background:"#1f2937",color:"#f87171",fontSize:11,padding:"4px 8px",borderRadius:5,whiteSpace:"nowrap",pointerEvents:"none",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",zIndex:50},children:x}),(0,n.jsx)("button",{onClick:h?p:u,disabled:l&&!h,style:{display:"flex",alignItems:"center",gap:5,padding:"8px 12px",height:32,background:h?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:h?"#ef4444":"var(--text-muted)",cursor:l&&!h?"not-allowed":"pointer",fontSize:12,opacity:l&&!h?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!l||h)&&(e.currentTarget.style.background=h?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=h?"#ef4444":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=h?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=h?"#ef4444":"var(--text-muted)"},title:h?"停止压缩":"压缩上下文",children:h?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),"Compacting…"]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,n.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,n.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,n.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),"Compact"]})})]}),l&&(0,n.jsxs)("button",{onClick:t,title:"停止 Agent",style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),"Stop"]}),void 0!==w&&(0,n.jsx)("button",{onClick:w,title:k?"关闭完成提示音":"开启完成提示音",style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:k?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:k?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=k?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=k?"1":"0.55"},children:k?(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,n.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,n.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})})]})]})]})]})});function tp(e){return"user"===e.role?{bg:"rgba(37,99,235,0.18)",border:"rgba(37,99,235,0.7)"}:{bg:"rgba(107,114,128,0.12)",border:"rgba(107,114,128,0.5)"}}function th({messages:e,streamingMessage:t,scrollContainer:r,messageRefs:o}){let[l,s]=(0,i.useState)(0),[a,d]=(0,i.useState)(1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)([]),[x,g]=(0,i.useState)(!1),[f,v]=(0,i.useState)(null),m=(0,i.useRef)(!1),y=(0,i.useRef)(null),b=(0,i.useMemo)(()=>t?[...e,t]:e,[e,t]),j=(0,i.useRef)(b);j.current=b;let k=(0,i.useRef)(null);k.current=()=>{let e=r.current;if(!e)return;let t=e.scrollHeight,n=e.clientHeight,i=t-n;u(i>20),i<=0?(s(0),d(1)):(s(e.scrollTop/i),d(n/t));let l=o.current,a=[],c=0,p=j.current;for(let r=0;r<p.length;r++){let n=p[r];if("user"!==n.role&&"assistant"!==n.role)continue;let i=l?.[c];if(c++,("user"===n.role||"assistant"===n.role&&(n.content??[]).some(e=>"text"===e.type))&&i&&t>0){let r=i.getBoundingClientRect(),o=e.getBoundingClientRect(),l=r.top-o.top+e.scrollTop,s=r.height;a.push({topRatio:l/t,heightRatio:s/t,msg:n,index:a.length})}}h(a)};let w=(0,i.useCallback)(()=>k.current(),[]);(0,i.useEffect)(()=>{let e=r.current;if(!e)return;e.addEventListener("scroll",w,{passive:!0});let t=new ResizeObserver(w);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),w(),()=>{e.removeEventListener("scroll",w),t.disconnect()}},[r,w]),(0,i.useEffect)(()=>{let e=setTimeout(w,50);return()=>clearTimeout(e)},[e.length,w]);let S=(0,i.useCallback)(e=>{let t=r.current;if(!t)return;let n=t.scrollHeight-t.clientHeight;n<=0||(t.scrollTop=Math.max(0,Math.min(1-a,e))/(1-a)*n)},[r,a]),C=(0,i.useCallback)(e=>{if(!c)return;m.current=!0;let t=e.currentTarget.getBoundingClientRect(),r=(e.clientY-t.top)/t.height,n=r-l*(1-a),i=n>=0&&n<=a?n:a/2;S(r-i);let o=e=>{m.current&&S((e.clientY-t.top)/t.height-i)},s=()=>{m.current=!1,window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",s)};window.addEventListener("mousemove",o),window.addEventListener("mouseup",s)},[c,a,l,S]),T=y.current?.clientHeight??600,z=(0,i.useMemo)(()=>{if(!x||0===p.length)return[];let e=p.map(e=>Math.round(e.topRatio*T-11));for(let t=0;t<10;t++){for(let t=1;t<e.length;t++){let r=e[t-1]+22+2;e[t]<r&&(e[t]=r)}for(let t=e.length-2;t>=0;t--){let r=e[t+1]-22-2;e[t]>r&&(e[t]=r)}}for(let t=0;t<e.length;t++)e[t]=Math.max(0,Math.min(T-22,e[t]));return e},[x,p,T]);if(!c)return null;let L=l*(1-a)*100,I=100*a,M=null!==f&&p.length>0?p.reduce((e,t)=>Math.abs(t.topRatio-f)<Math.abs(p[e].topRatio-f)?t.index:e,0):null;return(0,n.jsxs)("div",{ref:y,onMouseDown:C,onMouseEnter:()=>g(!0),onMouseLeave:()=>{g(!1),v(null)},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();v((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"default",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[(0,n.jsx)("div",{style:{position:"absolute",left:0,right:0,top:`${L}%`,height:`${I}%`,background:"rgba(100,100,100,0.1)",borderTop:"1px solid rgba(100,100,100,0.2)",borderBottom:"1px solid rgba(100,100,100,0.2)",pointerEvents:"none",zIndex:1}}),p.map(e=>{let t=tp(e.msg),r=x&&M===e.index,i="user"===e.msg.role,o=100*e.topRatio;return(0,n.jsx)("div",{style:{position:"absolute",top:`${o}%`,transform:"translateY(-50%)",left:0,right:0,height:"12px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",zIndex:2},children:(0,n.jsx)("div",{style:{width:i?8:6,height:i?8:6,borderRadius:i?2:"50%",background:t.bg,border:`1.5px solid ${t.border}`,flexShrink:0,transition:"transform 0.1s",transform:r?"scale(1.6)":"scale(1)"}})},e.index)}),(0,n.jsx)("div",{style:{position:"absolute",left:"50%",top:0,bottom:0,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),x&&p.map((e,t)=>{let r=function(e){if("user"===e.role){let t=e.content;return"string"==typeof t?t.slice(0,200):Array.isArray(t)?t.filter(e=>"text"===e.type&&e.text).map(e=>e.text).join("\n").slice(0,200):""}if("assistant"===e.role){let t=e.content??[],r=t.filter(e=>"text"===e.type).map(e=>e.text).join(" ");if(r)return r.slice(0,200);let n=t.filter(e=>"toolCall"===e.type).map(e=>e.toolName);if(n.length)return n.join(", ")}return""}(e.msg),i=tp(e.msg),o=M===e.index;return r&&0!==z.length?(0,n.jsx)("div",{style:{position:"absolute",top:z[t],right:"100%",marginRight:6,background:"var(--bg)",borderTop:`1px solid ${o?i.border:"var(--border)"}`,borderRight:`1px solid ${o?i.border:"var(--border)"}`,borderBottom:`1px solid ${o?i.border:"var(--border)"}`,borderLeft:`2px solid ${i.border}`,borderRadius:4,padding:"2px 7px",width:200,zIndex:100,pointerEvents:"none",opacity:o?1:.45,transition:"top 0.1s, opacity 0.1s"},children:(0,n.jsx)("div",{style:{fontSize:11,color:o?"var(--text)":"var(--text-muted)",lineHeight:1.4,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:r})},e.index):null})]})}function tx(e){let t=new Map;for(let r of e){if("custom"===r.role&&"subagent-notify"===r.customType&&"string"==typeof r.content){let e=r.content.match(/^Background task (completed|failed|paused):\s*\*\*(.+?)\*\*(?:\s+\((.+?)\))?/);if(e){let n=`bg-${e[2]}-${r.timestamp??""}`;t.set(n,{id:n,agent:e[2],status:e[1],task:e[3],summary:r.content.split("\n").slice(3).join("\n").trim()||void 0,timestamp:r.timestamp})}}if("assistant"===r.role){let e=r.content;if(!e)continue;for(let n of e)if("toolCall"===n.type&&"subagent"===n.toolName&&n.input){let e=n.input,i=e.agent??(e.chain?"chain":e.tasks?"parallel":e.action??"subagent"),o="string"==typeof e.task?e.task:void 0,l=n.toolCallId??`sub-${i}-${r.timestamp??Date.now()}`;t.set(l,{id:l,agent:i,status:"running",task:o,timestamp:r.timestamp})}}if("toolResult"===r.role&&r.toolCallId&&t.has(r.toolCallId)){let e=t.get(r.toolCallId);e.status=r.isError?"failed":"completed",e.summary=(r.content?.filter(e=>"text"===e.type).map(e=>e.text??"").join("\n")??"").slice(0,200)||void 0}}return Array.from(t.values()).sort((e,t)=>(t.timestamp??0)-(e.timestamp??0))}function tg({messages:e,runs:t}){let r=(0,i.useMemo)(()=>tx(e??[]),[e]),o=t??r,l=o.filter(e=>"running"===e.status),s=o.filter(e=>"running"!==e.status);return 0===o.length?null:(0,n.jsxs)("div",{style:{height:"100%",overflow:"auto",padding:12},children:[l.length>0&&(0,n.jsxs)("div",{style:{marginBottom:16},children:[(0,n.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",marginBottom:8,textTransform:"uppercase",letterSpacing:"0.05em"},children:["Active (",l.length,")"]}),l.map(e=>(0,n.jsxs)("div",{style:{padding:"8px 12px",borderRadius:6,border:"1px solid rgba(99,102,241,0.2)",background:"rgba(99,102,241,0.04)",marginBottom:6,fontSize:12},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:8,height:8,borderRadius:"50%",background:"#818cf8",display:"inline-block",animation:"pulse 1.5s infinite",flexShrink:0}}),(0,n.jsx)("span",{style:{fontWeight:600,color:"var(--text)"},children:e.agent}),(0,n.jsx)("span",{style:{color:"var(--accent)",fontSize:10,fontWeight:600},children:"running"})]}),e.task&&(0,n.jsx)("div",{style:{marginTop:4,color:"var(--text-muted)",fontSize:11,lineHeight:1.4},children:e.task.length>120?e.task.slice(0,120)+"…":e.task})]},e.id))]}),s.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",marginBottom:8,textTransform:"uppercase",letterSpacing:"0.05em"},children:["Completed (",s.length,")"]}),s.map(e=>(0,n.jsxs)("div",{style:{padding:"6px 12px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",marginBottom:4,fontSize:12},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{fontSize:12,flexShrink:0},children:"completed"===e.status?"✅":"failed"===e.status?"❌":"⏸"}),(0,n.jsx)("span",{style:{fontWeight:600,color:"var(--text)"},children:e.agent}),(0,n.jsx)("span",{style:{color:"completed"===e.status?"#22c55e":"failed"===e.status?"#ef4444":"var(--text-dim)",fontSize:10,fontWeight:600},children:e.status})]}),e.summary&&(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:11,lineHeight:1.4,maxHeight:60,overflow:"hidden"},children:e.summary})]},e.id))]})]})}function tf(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let r=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input})??e);return{...e,content:r}}async function tv(e,t){let r=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);return n.data}function tm(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}let ty=["image/","application/pdf","application/vnd.openxmlformats-officedocument","application/msword","application/vnd.ms-"];function tb(e){return ty.some(t=>e.type.startsWith(t))}let tj=["annotate and analyze.","vibe code bioinformatics.","turn data into figures.","inspect your project.","build a reproducible report.","run R/Python plots.","summarize that paper.","review the pipeline.","compare markers.","draft methods.","find the next analysis step."];function tk({phrases:e}){let[t,r]=(0,i.useState)(()=>Math.floor(Math.random()*e.length)),[o,l]=(0,i.useState)(""),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!0);return(0,i.useEffect)(()=>{let e=setInterval(()=>c(e=>!e),530);return()=>clearInterval(e)},[]),(0,i.useEffect)(()=>{let n,i=e[t];if(s||o!==i)if(s&&""===o)a(!1),r(t=>(t+1)%e.length);else{let e=s?i.slice(0,o.length-1):i.slice(0,o.length+1);n=setTimeout(()=>l(e),s?28:55)}else n=setTimeout(()=>a(!0),1800);return()=>clearTimeout(n)},[o,s,t,e]),(0,n.jsxs)("span",{style:{color:"var(--text-muted)",fontWeight:400},children:[o,(0,n.jsx)("span",{style:{opacity:+!!d,color:"var(--accent)",marginLeft:1},children:"▍"})]})}function tw({session:e,newSessionCwd:t,onAgentEnd:o,onSessionCreated:l,onSessionForked:s,modelsRefreshKey:a,chatInputRef:d,onBranchDataChange:c,onSystemPromptChange:u,onSessionStatsChange:p,onContextUsageChange:h,onReportUpdated:x,generativeUI:g}){var f;let v,{loading:m,error:y,messages:b,entryIds:j,streamState:k,agentRunning:w,modelNames:S,modelList:C,modelThinkingLevels:T,modelThinkingLevelMaps:z,toolPreset:L,thinkingLevel:I,retryInfo:M,contextUsage:R,forkingEntryId:W,isCompacting:E,compactError:$,displayModel:B,sessionStats:N,agentPhase:P,isNew:A,messagesEndRef:D,scrollContainerRef:H,lastUserMsgRef:O,handleSend:F,handleAbort:U,handleFork:_,handleNavigate:V,handleModelChange:J,handleCompact:K,handleSteer:q,handleFollowUp:G,handleAbortCompaction:Z,handleToolPresetChange:X,handleThinkingLevelChange:Q,handleAgentEventRef:ee}=function(e){let{session:t,newSessionCwd:n,onAgentEnd:o,onSessionCreated:l,onSessionForked:s,modelsRefreshKey:a,onBranchDataChange:d,onSystemPromptChange:c}=e,u=null===t&&null!==n,[p,h]=(0,i.useState)(null),[x,g]=(0,i.useState)(!u),[f,v]=(0,i.useState)(null),[m,y]=(0,i.useState)(null),[b,j]=(0,i.useState)([]),[k,w]=(0,i.useState)([]),[S,C]=(0,i.useReducer)(tm,{isStreaming:!1,streamingMessage:null}),[T,z]=(0,i.useState)(!1),[L,I]=(0,i.useState)({}),[M,R]=(0,i.useState)([]),[W,E]=(0,i.useState)({}),[$,B]=(0,i.useState)({}),[N,P]=(0,i.useState)(null),[A,D]=(0,i.useState)("default"),[H,O]=(0,i.useState)("auto"),[F,U]=(0,i.useState)(null),[_,V]=(0,i.useState)(null),[J,K]=(0,i.useState)(null),[q,Y]=(0,i.useState)(null),[G,Z]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(!1),[er,en]=(0,i.useState)(null),[ei,eo]=(0,i.useState)(null),el=(0,i.useRef)(null),es=(0,i.useRef)(t?.id??null),ea=(0,i.useRef)(!1),ed=(0,i.useRef)(null),ec=(0,i.useRef)(!1),eu=(0,i.useRef)(null),ep=(0,i.useRef)(!1),eh=(0,i.useRef)(null),ex=(0,i.useRef)(null),eg=e.setNewSessionModel??P,ef=e.setToolPreset??D,ev=G??p?.context.model??X??null,em=u?N:ev,ey=(0,i.useCallback)(e=>e?.length?e.map((e,t)=>{let r=`Attachment ${t+1}: ${e.fileName} (${e.mimeType||"application/octet-stream"}, ${e.size} bytes)`;if(e.extractedText){let t=e.truncated?"\n[The extracted text was truncated before sending.]":"";return`${r}
250
- ${t}
251
- ${e.extractedText}`.trim()}return`${r}
252
- [Text extraction unavailable: ${e.extractionError??"unsupported file type"}]`}).join("\n\n---\n\n"):"",[]),eb=(()=>{let e={input:0,output:0,cacheRead:0,cacheWrite:0},t=0;for(let r of b){if("assistant"!==r.role)continue;let n=r.usage;n&&(e.input+=n.input??0,e.output+=n.output??0,e.cacheRead+=n.cacheRead??0,e.cacheWrite+=n.cacheWrite??0,t+=n.cost?.total??0)}return e.input+e.output+e.cacheRead+e.cacheWrite>0?{tokens:e,cost:t}:null})(),ej=(0,i.useCallback)(async(e,t=!1,r=!1)=>{try{t&&g(!0);let n=r?`/api/sessions/${encodeURIComponent(e)}?includeState`:`/api/sessions/${encodeURIComponent(e)}`,i=await fetch(n);if(404===i.status)return t&&(h(null),y(null),j([]),v(null)),null;if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();return h(o),y(o.leafId),j(o.context.messages),w(o.context.entryIds??[]),Z(null),v(null),!o.agentState?.state?.thinkingLevel&&o.context.thinkingLevel&&"off"!==o.context.thinkingLevel&&O(o.context.thinkingLevel),o.agentState??null}catch(e){return v(String(e)),null}finally{t&&g(!1)}},[]),ek=(0,i.useCallback)(async(e,t)=>{try{let r=t?`/api/sessions/${encodeURIComponent(e)}/context?leafId=${encodeURIComponent(t)}`:`/api/sessions/${encodeURIComponent(e)}/context`,n=await fetch(r);if(!n.ok)throw Error(`HTTP ${n.status}`);let i=await n.json();j(i.context.messages),w(i.context.entryIds??[])}catch(e){console.error("Failed to load context:",e)}},[]),ew=(0,i.useCallback)(async e=>{try{let t=await tv(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await r.e(8451).then(r.bind(r,48451));ef(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ef]),eS=(0,i.useCallback)(e=>{el.current&&(el.current.close(),el.current=null);let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);el.current=t,t.onmessage=e=>{try{let t=JSON.parse(e.data);ed.current?.(t)}catch{}},t.onerror=()=>{el.current===t&&ea.current&&(t.close(),el.current=null,setTimeout(()=>{ea.current&&eS(e)},1e3))}},[]);(0,i.useEffect)(()=>{ea.current=T},[T]),ed.current=(0,i.useCallback)(e=>{switch(e.type){case"agent_start":z(!0),eo({kind:"waiting_model"}),C({type:"start"});break;case"agent_end":z(!1),eo(null),U(null),C({type:"end"}),es.current&&(ej(es.current),fetch(`/api/agent/${encodeURIComponent(es.current)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&V(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&K(e.state.systemPrompt??null)}).catch(()=>{})),o?.();break;case"message_start":case"message_update":{let t=e.message;t&&C({type:"update",message:tf(t)}),eo(null);break}case"message_end":{let t=e.message;t&&j(e=>[...e,tf(t)]),C({type:"reset"}),eo({kind:"waiting_model"});break}case"tool_execution_start":{let t=e.toolCallId,r=e.toolName;eo(e=>{let n=e?.kind==="running_tools"?[...e.tools]:[];return n.some(e=>e.id===t)||n.push({id:t,name:r}),{kind:"running_tools",tools:n}});break}case"tool_execution_end":{let t=e.toolCallId;eo(e=>{if(e?.kind!=="running_tools")return e;let r=e.tools.filter(e=>e.id!==t);return 0===r.length?{kind:"waiting_model"}:{kind:"running_tools",tools:r}});break}case"auto_retry_start":U({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":U(null);break;case"auto_compaction_start":case"compaction_start":et(!0),en(null);break;case"auto_compaction_end":case"compaction_end":et(!1),e.errorMessage?en(e.errorMessage):!e.aborted&&es.current&&ej(es.current)}},[ej,o]);let eC=(0,i.useCallback)(async(e,i,o)=>{if(!e.trim()&&!i?.length&&!o?.length||T)return;let s=ey(o),a=e.trim()?s?`${e}
253
-
254
- Attached document text:
255
-
256
- ${s}`:e:s?`Attached document text:
257
-
258
- ${s}`:"",d=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),c={role:"user",content:d?.length?[...a.trim()?[{type:"text",text:a}]:[],...d]:a,timestamp:Date.now()};j(e=>[...e,c]),z(!0),eo({kind:"waiting_model"}),C({type:"start"}),ep.current=!0;let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{if(u&&n){N&&Q(N);let{PRESET_NONE:t,PRESET_DEFAULT:i,PRESET_FULL:o,PRESET_FULL_PLOT:s}=await r.e(8451).then(r.bind(r,48451)),d="none"===A?t:"default"===A?i:"full-plot"===A?s:o,c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,type:"prompt",message:a,toolNames:d,...p?.length?{images:p}:{},...N?{provider:N.provider,modelId:N.modelId}:{},..."auto"!==H?{thinkingLevel:H}:{}})});if(!c.ok)throw Error(`HTTP ${c.status}`);let u=(await c.json()).sessionId;es.current=u,eS(u),l?.({id:u,path:"",cwd:n,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:1,firstMessage:e})}else t&&(eS(t.id),await tv(t.id,{type:"prompt",message:a,...p?.length?{images:p}:{}}))}catch(e){console.error("Failed to send message:",e),z(!1),eo(null),C({type:"end"})}},[u,n,N,A,H,t,T,eS,l,ey]),eT=(0,i.useCallback)(async()=>{let e=es.current;if(e)try{await tv(e,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),ez=(0,i.useCallback)(async e=>{let t=es.current;if(t){Y(e);try{let{cancelled:r,newSessionId:n}=await tv(t,{type:"fork",entryId:e})??{};!r&&n&&s?.(n)}catch(e){console.error("Fork failed:",e)}finally{Y(null)}}},[s]),eL=(0,i.useCallback)(async e=>{let t=es.current;t&&(tv(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),y(e),await ek(t,e))},[ek]),eI=(0,i.useCallback)(async e=>{y(e);let t=es.current;t&&(await ek(t,e),e&&tv(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[ek]),eM=(0,i.useCallback)(async(e,t)=>{if(u)return void eg({provider:e,modelId:t});let r=es.current;if(r)try{await tv(r,{type:"set_model",provider:e,modelId:t}),Z({provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}},[u,eg]),eR=(0,i.useCallback)(async()=>{let e=es.current;if(e&&!ee){et(!0),en(null);try{await tv(e,{type:"compact"}),await ej(e,!0)}catch(e){en(e instanceof Error?e.message:String(e))}finally{et(!1)}}},[ee,ej]),eW=(0,i.useCallback)(async(e,t,r)=>{let n=es.current;if(!n)return;let i=ey(r),o=e.trim()?i?`${e}
259
-
260
- Attached document text:
261
-
262
- ${i}`:e:i?`Attached document text:
263
-
264
- ${i}`:"";j(e=>[...e,{role:"user",content:`[steer] ${o}`,timestamp:Date.now()}]);let l=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await tv(n,{type:"steer",message:o,...l?.length?{images:l}:{}})}catch(e){console.error("Failed to steer:",e)}},[ey]),eE=(0,i.useCallback)(async(e,t,r)=>{let n=es.current;if(!n)return;let i=ey(r),o=e.trim()?i?`${e}
265
-
266
- Attached document text:
267
-
268
- ${i}`:e:i?`Attached document text:
269
-
270
- ${i}`:"";j(e=>[...e,{role:"user",content:o,timestamp:Date.now()}]);let l=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await tv(n,{type:"follow_up",message:o,...l?.length?{images:l}:{}})}catch(e){console.error("Failed to follow up:",e)}},[ey]),e$=(0,i.useCallback)(async()=>{let e=es.current;if(e)try{await tv(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),eB=(0,i.useCallback)(async e=>{if(O(e),"auto"===e)return;let t=es.current;if(t)try{await tv(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),eN=(0,i.useCallback)(async e=>{let{PRESET_NONE:t,PRESET_DEFAULT:n,PRESET_FULL:i,PRESET_FULL_PLOT:o}=await r.e(8451).then(r.bind(r,48451));ef(e);let l=es.current;if(l)try{await tv(l,{type:"set_tools",toolNames:"none"===e?t:"default"===e?n:"full-plot"===e?o:i})}catch(e){console.error("Failed to set tools:",e)}},[ef]),eP=(0,i.useCallback)((e="smooth")=>{eh.current?.scrollIntoView({behavior:e})},[]),eA=(0,i.useCallback)(()=>{let e=ex.current,t=eu.current;if(!e||!t)return;let r=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop;e.scrollTo({top:r-16,behavior:"smooth"})},[]);return(0,i.useEffect)(()=>(t&&(es.current=t.id,ej(t.id,!0,!0).then(e=>{e?.running&&(ew(t.id),z(!0),eo({kind:"waiting_model"}),C({type:"start"}),eS(t.id)),e?.state&&(void 0!==e.state.isCompacting&&et(e.state.isCompacting),void 0!==e.state.contextUsage&&V(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&K(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&O(e.state.thinkingLevel??"auto"))})),()=>{el.current?.close(),el.current=null}),[]),(0,i.useEffect)(()=>{c?.(J)},[J,c]),(0,i.useEffect)(()=>{d&&d(p?.tree??[],m,eI)},[p?.tree,m,eI,d]),(0,i.useEffect)(()=>{b.length>0&&(ep.current?(ep.current=!1,ec.current=!0,eA()):ec.current?ea.current||eP("smooth"):(ec.current=!0,eP("instant")))},[b.length,T,eP,eA]),(0,i.useEffect)(()=>{fetch("/api/models").then(e=>e.json()).then(e=>{if(I(e.models),e.thinkingLevels&&E(e.thinkingLevels),e.thinkingLevelMaps&&B(e.thinkingLevelMaps),e.modelList&&(R(e.modelList),u&&e.modelList.length>0)){let t=e.defaultModel,r=t&&e.modelList.find(e=>e.id===t.modelId&&e.provider===t.provider);eg(r?{provider:r.provider,modelId:r.id}:{provider:e.modelList[0].provider,modelId:e.modelList[0].id})}}).catch(()=>{})},[u,a,eg]),(0,i.useEffect)(()=>{if(!er)return;let e=setTimeout(()=>en(null),3e3);return()=>clearTimeout(e)},[er]),{data:p,loading:x,error:f,activeLeafId:m,messages:b,entryIds:k,streamState:S,agentRunning:T,modelNames:L,modelList:M,modelThinkingLevels:W,modelThinkingLevelMaps:$,newSessionModel:N,toolPreset:A,thinkingLevel:H,retryInfo:F,contextUsage:_,systemPrompt:J,forkingEntryId:q,isCompacting:ee,compactError:er,currentModel:ev,displayModel:em,sessionStats:eb,agentPhase:ei,isNew:u,sessionIdRef:es,eventSourceRef:el,messagesEndRef:eh,scrollContainerRef:ex,lastUserMsgRef:eu,pendingScrollToUserRef:ep,initialScrollDoneRef:ec,handleSend:eC,handleAbort:eT,handleFork:ez,handleNavigate:eL,handleModelChange:eM,handleCompact:eR,handleSteer:eW,handleFollowUp:eE,handleAbortCompaction:e$,handleToolPresetChange:eN,handleThinkingLevelChange:eB,loadTools:ew,setActiveLeafId:y,setData:h,setMessages:j,dispatch:C,setAgentRunning:z,setForkingEntryId:Y,handleAgentEventRef:ed}}({session:e,newSessionCwd:t,onAgentEnd:o,onSessionCreated:l,onSessionForked:s,modelsRefreshKey:a,onBranchDataChange:c,onSystemPromptChange:u}),{soundEnabled:et,onSoundToggle:er,playDoneSound:en}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{r.current=e},[e]),{soundEnabled:e,onSoundToggle:(0,i.useCallback)(()=>{t(e=>{let t=!e;return localStorage.setItem("pi-sound-enabled",String(t)),t})},[]),playDoneSound:(0,i.useCallback)(()=>{if(r.current)try{let e=new AudioContext,t=e.currentTime;[523.25,659.25].forEach((r,n)=>{let i=e.createOscillator(),o=e.createGain();i.connect(o),o.connect(e.destination),i.type="sine",i.frequency.value=r;let l=t+.18*n;o.gain.setValueAtTime(0,l),o.gain.linearRampToValueAtTime(.18,l+.02),o.gain.exponentialRampToValueAtTime(.001,l+.45),i.start(l),i.stop(l+.45)}),setTimeout(()=>e.close(),1200)}catch{}},[]),soundEnabledRef:r}}(),ei=(0,i.useRef)(en);ei.current=en;let eo=(0,i.useRef)(et);eo.current=et;let el=ee.current;(0,i.useEffect)(()=>{ee.current=e=>{"agent_end"===e.type&&eo.current&&ei.current(),el?.(e)}},[el,ee]);let es=N?`${N.tokens.input}|${N.tokens.output}|${N.tokens.cacheRead}|${N.tokens.cacheWrite}|${N.cost??0}`:null,ea=(0,i.useRef)(N);ea.current=N,(0,i.useEffect)(()=>{p?.(ea.current)},[es,p]),(0,i.useEffect)(()=>()=>{p?.(null)},[p]);let ed=R?`${R.percent??"null"}|${R.contextWindow}|${R.tokens??"null"}`:null,ec=(0,i.useRef)(R);ec.current=R,(0,i.useEffect)(()=>{h?.(ec.current)},[ed,h]),(0,i.useEffect)(()=>()=>{h?.(null)},[h]);let{isDragOver:eu,handleDragEnter:ep,handleDragOver:eh,handleDragLeave:ex,handleDrop:eg}=function(e){let[t,r]=(0,i.useState)(!1),n=(0,i.useRef)(0),o=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(tb)&&(e.preventDefault(),n.current+=1,r(!0))},[]),l=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(tb)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:o,handleDragOver:l,handleDragLeave:(0,i.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,r(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),n.current=0,r(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{d?.current?.addFiles(e)},[d])),[ef,ev]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!A)return;let e=!1;return fetch("/api/version").then(e=>e.ok?e.json():null).then(t=>{!e&&t?.updateAvailable&&ev(t)}).catch(()=>{}),()=>{e=!0}},[A]);let em=(f=b.filter(e=>"user"===e.role||"assistant"===e.role).length,(v=(0,i.useRef)([])).current=Array(f).fill(null).map((e,t)=>v.current[t]??null),v),ey=(0,i.useRef)(new Set);(0,i.useEffect)(()=>{ey.current.clear()},[e?.id]),(0,i.useEffect)(()=>{if(e?.id)for(let t of b.flatMap(e=>"assistant"!==e.role?[]:(Array.isArray(e.content)?e.content:[]).flatMap(e=>"text"!==e.type?[]:function(e){let t=[];for(let r of e.matchAll(eY)){let e=r[0],n=function(e){try{var t,r;let n=JSON.parse(e);if("object"!=typeof n||null===n||Array.isArray(n))return null;return{section:"string"==typeof n.section?n.section:void 0,action:(t=n.action,"replace"===t?"replace":"append"===t?"append":void 0),status:(r=n.status,"draft"===r||"verified"===r||"outdated"===r||"needs_review"===r?r:"needs review"===r?"needs_review":void 0),markdown:"string"==typeof n.markdown?n.markdown:void 0,sources:Array.isArray(n.sources)?n.sources:void 0,invalidates:Array.isArray(n.invalidates)?n.invalidates.filter(e=>"string"==typeof e):void 0,note:"string"==typeof n.note?n.note:void 0}}catch{return null}}(r[1]?.trim()??"");n&&t.push({update:n,raw:e})}return t}(e.text)))){let r=`${e.id}:${t.raw}`;ey.current.has(r)||(ey.current.add(r),fetch(`/api/reports/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"apply_update",update:t.update,updateKey:t.raw})}).then(e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);x?.()}).catch(()=>{ey.current.delete(r)}))}},[b,x,e?.id]);let eb=A&&0===b.length&&!k.isStreaming&&!w,[ej,ek]=(0,i.useState)(!1),ew=tx(b),eS=ew.filter(e=>"running"===e.status).length;(0,i.useEffect)(()=>{0===ew.length&&ej&&ek(!1)},[ew.length,ej]);let eC=B?T[`${B.provider}:${B.modelId}`]??null:null,eT=B?z[`${B.provider}:${B.modelId}`]??null:null,ez=(0,n.jsx)(tu,{ref:d,onSend:F,onAbort:U,onSteer:w?q:void 0,onFollowUp:w?G:void 0,isStreaming:w,model:B,modelNames:S,modelList:C,onModelChange:J,onCompact:e||A?K:void 0,onAbortCompaction:Z,isCompacting:E,compactError:$,toolPreset:L,onToolPresetChange:e||A?X:void 0,thinkingLevel:I,onThinkingLevelChange:e||A?Q:void 0,availableThinkingLevels:eC,thinkingLevelMap:eT,retryInfo:M,soundEnabled:et,onSoundToggle:er}),eL=(0,i.useCallback)(e=>{w?d?.current?.insertText(e):F(e)},[w,d,F]);return m?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:"Loading session..."}):y?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:y}):(0,n.jsxs)("div",{className:"relative flex h-full flex-col overflow-hidden",onDragEnter:ep,onDragOver:eh,onDragLeave:ex,onDrop:eg,children:[eu&&(0,n.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,n.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,n.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,n.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,n.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,n.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,n.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,n.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,n.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,n.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,n.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,n.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,n.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,n.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),eb?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto px-4 py-8",children:(0,n.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,n.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0,flex:1,lineHeight:1.4},children:[(0,n.jsx)("span",{style:{fontSize:23,color:"var(--text)",fontWeight:750,letterSpacing:0},children:Y}),(0,n.jsx)("span",{style:{fontSize:14,minWidth:0,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:(0,n.jsx)(tk,{phrases:tj})})]}),(0,n.jsx)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"flex-end",minHeight:22},children:ef?.updateAvailable?(0,n.jsxs)("span",{title:`Latest ${ef.latest??""}`,style:{fontSize:11,color:"var(--accent)",whiteSpace:"nowrap"},children:["Update: ",(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)"},children:ef.updateCommand})]}):(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:["v","0.8.12"]})})]}),ez]})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"relative flex flex-1 overflow-hidden",children:[(0,n.jsx)("div",{ref:H,className:"flex-1 overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,n.jsxs)("div",{className:"mx-auto max-w-[820px] px-4",children:[(()=>{let e=new Map;for(let t of b)"toolResult"===t.role&&e.set(t.toolCallId,t);let t=-1;for(let e=b.length-1;e>=0;e--)if("user"===b[e].role){t=e;break}let r=0;return b.map((i,o)=>{let l="user"===i.role&&o>0&&"assistant"===b[o-1].role?j[o-1]:void 0,s="user"===i.role||"assistant"===i.role,a=s?r++:-1,c=!1;if("assistant"===i.role){c=!0;for(let e=o+1;e<b.length;e++){let t=b[e].role;if("user"===t)break;if("assistant"===t){c=!1;break}}c&&k.isStreaming&&o===b.length-1&&(c=!1)}let u=(0,n.jsx)(eX,{message:i,toolResults:e,modelNames:S,entryId:j[o],onFork:w||A||0===o&&"user"===i.role?void 0:_,forking:W===j[o],onNavigate:w?void 0:V,prevAssistantEntryId:w?void 0:l,onEditContent:e=>d?.current?.insertIfEmpty(e),onSendMessage:eL,showTimestamp:c,prevTimestamp:o>0?b[o-1].timestamp:void 0,renderVisualCodeBlocks:!!g},o);return s?(0,n.jsx)("div",{ref:e=>{em.current[a]=e,o===t&&(O.current=e)},children:u},o):u})})(),k.isStreaming&&k.streamingMessage&&(0,n.jsx)(eX,{message:k.streamingMessage,isStreaming:!0,modelNames:S,onSendMessage:eL,renderVisualCodeBlocks:!!g}),w&&!k.streamingMessage&&(0,n.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,n.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e){if(e?.kind==="running_tools"){let t=e.tools.map(e=>e.name);return 0===t.length?"Running tool...":1===t.length?`Running ${t[0]}...`:t.length<=3?`Running ${t.join(", ")}...`:`Running ${t.slice(0,2).join(", ")} (+${t.length-2})...`}return e?.kind==="waiting_model"?"Waiting for model...":"Thinking..."}(P)})}),w&&(0,n.jsx)("div",{style:{height:H.current?H.current.clientHeight:"80vh"}}),(0,n.jsx)("div",{ref:D})]})}),(0,n.jsx)(th,{messages:b,streamingMessage:k.streamingMessage,scrollContainer:H,messageRefs:em}),ew.length>0&&(0,n.jsxs)("button",{onClick:()=>ek(e=>!e),title:ej?"Hide subagent runs":"Show subagent runs",style:{position:"absolute",right:ej?260:40,top:8,minWidth:28,height:28,display:"flex",alignItems:"center",justifyContent:"center",gap:6,padding:eS>0||ew.length>1?"0 8px":0,background:ej?"var(--bg-selected)":"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:ej?"var(--accent)":"var(--text-dim)",cursor:"pointer",zIndex:30,fontSize:12,transition:"right 0.2s ease, background 0.12s"},onMouseEnter:e=>{ej||(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{ej||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),(0,n.jsx)("circle",{cx:"9",cy:"7",r:"4"}),(0,n.jsx)("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),(0,n.jsx)("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),(eS>0||ew.length>1)&&(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,fontSize:10,fontWeight:700,color:eS>0?"var(--accent)":"var(--text-dim)"},children:[eS>0&&(0,n.jsxs)("span",{children:[eS," active"]}),(0,n.jsx)("span",{children:ew.length})]})]}),ej&&ew.length>0&&(0,n.jsxs)("div",{style:{position:"absolute",right:48,top:4,bottom:4,width:250,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"-2px 0 12px rgba(0,0,0,0.08)",zIndex:25,overflow:"hidden"},children:[(0,n.jsx)("div",{style:{padding:"6px 12px",fontSize:11,fontWeight:600,color:"var(--text-dim)",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Subagents"}),(0,n.jsx)(tg,{runs:ew})]})]}),(0,n.jsx)("div",{className:"relative",children:ez})]})]})}function tS({fileName:e,pageInfo:t,onZoomIn:r,onZoomOut:i,zoom:o,extra:l}){return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0,minHeight:32},children:[e&&(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:300},title:e,children:e}),(0,n.jsx)("span",{style:{marginLeft:"auto"}}),t&&(0,n.jsx)("span",{children:t}),void 0!==o&&i&&r&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,n.jsx)("button",{onClick:i,title:"Zoom out",style:tC,children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:(0,n.jsx)("line",{x1:"2",y1:"5",x2:"8",y2:"5"})})}),(0,n.jsxs)("span",{style:{minWidth:36,textAlign:"center",fontVariantNumeric:"tabular-nums"},children:[Math.round(100*o),"%"]}),(0,n.jsx)("button",{onClick:r,title:"Zoom in",style:tC,children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"2",x2:"5",y2:"8"}),(0,n.jsx)("line",{x1:"2",y1:"5",x2:"8",y2:"5"})]})})]}),l]})}let tC={display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer"},tT=null;function tz({arrayBuffer:e,fileName:t}){let o=(0,i.useRef)(null),[l,s]=(0,i.useState)(!0),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(1),[x,g]=(0,i.useState)(1),f=(0,i.useRef)(x);f.current=x;let v=(0,i.useRef)(null),m=(0,i.useRef)(null),y=(0,i.useCallback)(async e=>{if(!tT||!v.current)return;let t=v.current;if(!(e<1)&&!(e>t.numPages)){m.current&&(m.current.cancel(),m.current=null);try{let r=await t.getPage(e),n=r.getViewport({scale:f.current*(window.devicePixelRatio||1)}),i=o.current;if(!i)return;let l=i.querySelector("canvas");if(l||((l=document.createElement("canvas")).style.display="block",l.style.margin="0 auto",i.innerHTML="",i.appendChild(l)),l.width=n.width,l.height=n.height,l.style.width=`${n.width/(window.devicePixelRatio||1)}px`,l.style.height=`${n.height/(window.devicePixelRatio||1)}px`,!l.getContext("2d"))return;let s=r.render({canvas:l,viewport:n});m.current=s,await s.promise,m.current=null}catch(e){"RenderingCancelledException"!==e.name&&console.error("PDF render error:",e)}}},[]);return(0,i.useEffect)(()=>{let t=!1;return async function(){s(!0),d(null);try{tT||((tT=await Promise.all([r.e(2084),r.e(2619)]).then(r.bind(r,66898))).GlobalWorkerOptions.workerSrc=new r.U(r(9924)).toString());let n=await tT.getDocument({data:e}).promise;if(t)return;v.current=n,u(n.numPages),h(1),s(!1)}catch(e){t||(d(String(e)),s(!1))}}(),()=>{t=!0,m.current&&(m.current.cancel(),m.current=null)}},[e]),(0,i.useEffect)(()=>{!l&&c>0&&y(p)},[l,p,c,y]),(0,i.useEffect)(()=>{!l&&c>0&&y(p)},[x]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(tS,{fileName:t,pageInfo:c>0?`Page ${p} / ${c}`:void 0,zoom:x,onZoomIn:()=>g(e=>Math.min(e+.25,3)),onZoomOut:()=>g(e=>Math.max(e-.25,.25)),extra:c>1&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,n.jsx)("button",{onClick:()=>h(e=>Math.max(e-1,1)),disabled:p<=1,style:{...tL,opacity:p<=1?.4:1},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:(0,n.jsx)("polyline",{points:"6 2 3 5 6 8"})})}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",minWidth:28,textAlign:"center"},children:[p,"/",c]}),(0,n.jsx)("button",{onClick:()=>h(e=>Math.min(e+1,c)),disabled:p>=c,style:{...tL,opacity:p>=c?.4:1},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:(0,n.jsx)("polyline",{points:"4 2 7 5 4 8"})})})]})}),(0,n.jsxs)("div",{style:{flex:1,overflow:"auto",background:"#525659",display:"flex",justifyContent:"center",padding:16},children:[l&&(0,n.jsx)("div",{style:{color:"#ccc",fontSize:13,display:"flex",alignItems:"center",gap:6,alignSelf:"flex-start",marginTop:40},children:"Loading PDF..."}),a&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,alignSelf:"flex-start",marginTop:40},children:a}),(0,n.jsx)("div",{ref:o,style:{visibility:l?"hidden":"visible"}})]})]})}let tL={display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer"};function tI({arrayBuffer:e,fileName:t}){let o=(0,i.useRef)(null),[l,s]=(0,i.useState)(!0),[a,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{let t=!1;return async function(){s(!0),d(null);try{let{renderAsync:n}=await Promise.all([r.e(2619),r.e(4453),r.e(2274)]).then(r.bind(r,52274)),i=o.current;if(!i||t)return;i.innerHTML="",await n(e,i,void 0,{className:"docx-preview",inWrapper:!0,ignoreWidth:!1,ignoreHeight:!1,ignoreFonts:!1,breakPages:!0,ignoreLastRenderedPageBreak:!1,experimental:!1,trimXmlDeclaration:!0,useBase64URL:!1,renderChanges:!1,renderHeaders:!0,renderFooters:!0,renderFootnotes:!0,renderEndnotes:!0}),t||s(!1)}catch(e){t||(console.error("DOCX render error:",e),d(String(e)),s(!1))}}(),()=>{t=!0}},[e]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(tS,{fileName:t}),(0,n.jsxs)("div",{style:{flex:1,overflow:"auto",background:"#e8e8e8",padding:"24px 0"},children:[l&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,padding:"40px 16px",textAlign:"center"},children:"Loading document..."}),a&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,padding:"40px 16px",textAlign:"center"},children:a}),(0,n.jsx)("div",{ref:o,style:{maxWidth:816,margin:"0 auto",background:"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.12)",minHeight:100,visibility:l?"hidden":"visible"},className:"docx-preview-container"})]})]})}function tM({arrayBuffer:e,fileName:t}){let[o,l]=(0,i.useState)(!0),[s,a]=(0,i.useState)(null),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(0),h=(0,i.useRef)(null),[x,g]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{let t=!1;return async function(){l(!0),a(null);try{let n=await Promise.all([r.e(3524),r.e(8436)]).then(r.bind(r,15967)),i=n.read(e,{type:"array"}),o=i.SheetNames.map(e=>{let t=i.Sheets[e],r=n.utils.sheet_to_html(t,{editable:!1});return{name:e,html:r}});t||(c(o),p(0),l(!1))}catch(e){t||(console.error("XLSX parse error:",e),a(String(e)),l(!1))}}(),()=>{t=!0}},[e]),(0,i.useEffect)(()=>{let e=h.current;if(!e)return;let t=e.querySelector("table");if(!t)return;let r=()=>{g(t.querySelectorAll("colgroup col, thead tr:first-child th, tbody tr:first-child td").length>8)};r();let n=new ResizeObserver(r);return n.observe(e),()=>n.disconnect()},[u,d]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(tS,{fileName:t,extra:d.length>1&&(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:2},children:d.map((e,t)=>(0,n.jsx)("button",{onClick:()=>p(t),style:{padding:"2px 10px",fontSize:11,border:"1px solid var(--border)",borderBottom:t===u?"2px solid var(--accent)":"1px solid var(--border)",borderRadius:"4px 4px 0 0",background:t===u?"var(--bg-selected)":"none",color:t===u?"var(--text)":"var(--text-muted)",cursor:"pointer",fontWeight:t===u?600:400,transition:"background 0.12s"},onMouseEnter:e=>{t!==u&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t!==u&&(e.currentTarget.style.background="none")},children:e.name},t))})}),(0,n.jsxs)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)"},children:[o&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,padding:"40px 16px",textAlign:"center"},children:"Loading spreadsheet..."}),s&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,padding:"40px 16px",textAlign:"center"},children:s}),!o&&!s&&d.length>0&&(0,n.jsx)("div",{ref:h,style:{padding:"0 16px 16px",overflow:x?"auto":"visible"},dangerouslySetInnerHTML:{__html:d[u]?.html??""},className:"xlsx-preview"})]})]})}function tR({arrayBuffer:e,fileName:t}){let[o,l]=(0,i.useState)(!0),[s,a]=(0,i.useState)(null),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(0);(0,i.useEffect)(()=>{let t=!1;return async function(){l(!0),a(null);try{let n=(await Promise.all([r.e(2619),r.e(4453)]).then(r.t.bind(r,54453,23))).default,i=await n.loadAsync(e),o=[];i.forEach(e=>{let t=/^ppt\/slides\/slide(\d+)\.xml$/i.exec(e);t&&o.push({name:e,index:parseInt(t[1],10)})}),o.sort((e,t)=>e.index-t.index);let s=[];for(let e of o){let r;if(t)return;let n=await i.file(e.name).async("string"),o=/<a:t[^>]*>([^<]*)<\/a:t>/g,l=[];for(;null!==(r=o.exec(n));){let e=r[1].trim();e&&l.push(e)}s.push({index:e.index,texts:l})}t||(c(s),l(!1))}catch(e){t||(console.error("PPTX parse error:",e),a(String(e)),l(!1))}}(),()=>{t=!0}},[e]);let h=d[u],x=d.length;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(tS,{fileName:t,pageInfo:x>0?`Slide ${u+1} / ${x}`:void 0,extra:x>1&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,n.jsx)("button",{onClick:()=>p(e=>Math.max(e-1,0)),disabled:u<=0,style:{...tW,opacity:u<=0?.4:1},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:(0,n.jsx)("polyline",{points:"6 2 3 5 6 8"})})}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",minWidth:28,textAlign:"center"},children:[u+1,"/",x]}),(0,n.jsx)("button",{onClick:()=>p(e=>Math.min(e+1,x-1)),disabled:u>=x-1,style:{...tW,opacity:u>=x-1?.4:1},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:(0,n.jsx)("polyline",{points:"4 2 7 5 4 8"})})})]})}),(0,n.jsxs)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",justifyContent:"center",alignItems:"flex-start",padding:24},children:[o&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,padding:"40px 16px",textAlign:"center"},children:"Loading presentation..."}),s&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,padding:"40px 16px",textAlign:"center"},children:s}),!o&&!s&&h&&(0,n.jsxs)("div",{style:{width:"100%",maxWidth:800},children:[(0,n.jsxs)("div",{style:{background:"#fff",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.08)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"8px 16px",background:"var(--bg)",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:["Slide ",h.index]}),(0,n.jsx)("div",{style:{padding:"24px 32px 40px",minHeight:200},children:0===h.texts.length?(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontStyle:"italic",fontSize:13},children:"(No text content)"}):(0,n.jsx)("ul",{style:{margin:0,padding:0,listStyle:"none"},children:h.texts.map((e,t)=>(0,n.jsx)("li",{style:{padding:"4px 0",fontSize:14,lineHeight:1.6,color:"var(--text)",borderBottom:t<h.texts.length-1?"1px solid var(--bg-panel)":"none"},children:e},t))})})]}),x>1&&(0,n.jsxs)("div",{style:{marginTop:24},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",marginBottom:8},children:"All slides"}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:8},children:d.map((e,t)=>(0,n.jsxs)("button",{onClick:()=>p(t),style:{padding:"10px 12px",background:t===u?"var(--bg-selected)":"var(--bg)",border:t===u?"2px solid var(--accent)":"1px solid var(--border)",borderRadius:6,cursor:"pointer",textAlign:"left",fontSize:11,color:"var(--text-muted)",transition:"border-color 0.12s, background 0.12s"},onMouseEnter:e=>{t!==u&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t!==u&&(e.currentTarget.style.background="var(--bg)")},children:[(0,n.jsxs)("div",{style:{fontWeight:600,marginBottom:2,color:"var(--text)"},children:["Slide ",e.index]}),(0,n.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.texts[0]||"(empty)"})]},e.index))})]})]})]})]})}let tW={display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer"};var tE=r(27071),t$=r(89561),tB=r(82228),tN=r(46732),tP=r(74059),tA=r(13307),tD=r(53689),tH=r(14097),tO=r(25460),tF=r(20144),tU=r(82774),t_=r(62733),tV=r(77482),tJ=r(55135),tK=r(11209),tq=r(88198),tY=r(4238),tG=r(44542);function tZ({initialContent:e,language:t,isDark:r,onChange:o,onSave:l}){let s=(0,i.useRef)(null),a=(0,i.useRef)(null),d=(0,i.useRef)(o),c=(0,i.useRef)(l);return d.current=o,c.current=l,(0,i.useEffect)(()=>{let n=s.current;if(!n)return;let i=function(e){switch(e){case"javascript":case"typescript":return(0,tA.Q2)({typescript:"typescript"===e});case"python":return(0,tD.Hg)();case"sql":return(0,tH.ll)();case"json":return(0,tO.Pq)();case"html":return(0,tF.qy)();case"css":case"scss":case"less":return(0,tU.AH)();case"markdown":return(0,t_.wD)();case"xml":case"yaml":case"toml":return(0,tV._n)();case"rust":return(0,tJ.T)();case"go":return(0,tK.go)();case"java":return(0,tq.J)();default:return null}}(t),o=l?t$.w4.of([{key:"Mod-s",run:()=>(c.current?.(),!0),preventDefault:!0}]):[],u=tE.$t.create({doc:e,extensions:[(0,t$.$K)(),(0,t$.dz)(),(0,tB.b6)(),(0,tN.y9)(tN.Zt),t$.w4.of([...tB.pw,...tB.cL,...tG.OO,...tY.Eo]),o,(0,tG.yU)(),...r?[tP.bM]:[],...i?[i]:[],t$.Lz.updateListener.of(e=>{e.docChanged&&d.current?.(e.state.doc.toString())}),t$.Lz.theme({"&":{height:"100%",fontSize:"13px"},".cm-scroller":{overflow:"auto",fontFamily:"var(--font-mono)"},".cm-content":{padding:"8px 0"},".cm-gutters":{borderRight:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-dim)"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground":{background:r?"#3a3d4e":"#b4d5fe"}})]}),p=new t$.Lz({state:u,parent:n});return a.current=p,()=>{p.destroy(),a.current=null}},[t,r]),(0,i.useEffect)(()=>{let t=a.current;t&&t.state.doc.toString()!==e&&t.dispatch({changes:{from:0,to:t.state.doc.length,insert:e}})},[e]),(0,n.jsx)("div",{ref:s,style:{height:"100%",overflow:"hidden"}})}function tX({dir:e}){return(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:"asc"===e?(0,n.jsx)("polyline",{points:"2 6 5 3 8 6"}):(0,n.jsx)("polyline",{points:"2 4 5 7 8 4"})})}function tQ(e,t,r){let n=new Blob([e],{type:r}),i=URL.createObjectURL(n),o=document.createElement("a");o.href=i,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),setTimeout(()=>URL.revokeObjectURL(i),1e3)}function t0({content:e,delimiter:t,fileName:r="table"}){let[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)("asc"),{header:d,rows:c}=(0,i.useMemo)(()=>(function(e,t){let r=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),n=[],i=[],o="",l=!1;for(let e=0;e<r.length;e+=1){let s=r[e];if('"'===s){l&&'"'===r[e+1]?(o+='"',e+=1):l=!l;continue}if(s===t&&!l){i.push(o),o="";continue}if("\n"===s&&!l){i.push(o),i.some(e=>e.length>0)&&n.push(i),i=[],o="";continue}o+=s}i.push(o),i.some(e=>e.length>0)&&n.push(i);let s=n[0]??[],a=s.length;return{header:s,rows:n.slice(1).map(e=>{let t=[...e];for(;t.length<a;)t.push("");return t.slice(0,a)})}})(e,t),[e,t]),u=(0,i.useMemo)(()=>{if(null===o)return c;let e=[...c];return e.sort((e,t)=>{let r=e[o]??"",n=t[o]??"",i=Number(r),l=Number(n),a=""===r||""===n||Number.isNaN(i)||Number.isNaN(l)?r.localeCompare(n):i-l;return"asc"===s?a:-a}),e},[c,s,o]);return 0===d.length&&0===c.length?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:"No tabular data to display"}):(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"8px 12px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:[c.length," rows, ",d.length," columns"]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("button",{onClick:()=>{tQ(e,r," "===t?"text/tab-separated-values;charset=utf-8":"text/csv;charset=utf-8")},style:{padding:"2px 8px",fontSize:11,cursor:"pointer",background:"var(--bg-hover)",color:"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5},children:["Export "," "===t?"TSV":"CSV"]}),(0,n.jsx)("button",{onClick:()=>{tQ(JSON.stringify(u.map(e=>Object.fromEntries(d.map((t,r)=>[t||`column_${r+1}`,e[r]??""]))),null,2),r.replace(/\.[^.]+$/,"")+".json","application/json;charset=utf-8")},style:{padding:"2px 8px",fontSize:11,cursor:"pointer",background:"var(--bg-hover)",color:"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5},children:"Export JSON"})]})]}),(0,n.jsx)("div",{style:{minHeight:0,flex:1,overflow:"auto",background:"var(--bg)"},children:(0,n.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",tableLayout:"fixed",fontSize:12},children:[(0,n.jsx)("thead",{style:{position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)"},children:(0,n.jsx)("tr",{children:d.map((e,t)=>(0,n.jsx)("th",{onClick:()=>{o===t?a(e=>"asc"===e?"desc":"asc"):(l(t),a("asc"))},title:e,style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",textAlign:"left",color:"var(--text-muted)",fontWeight:600,cursor:"pointer",userSelect:"none",fontSize:11,whiteSpace:"nowrap"},children:(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6,minWidth:0},children:[(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:e||`column_${t+1}`}),o===t&&(0,n.jsx)("span",{style:{color:"var(--accent)",display:"inline-flex",flexShrink:0},children:(0,n.jsx)(tX,{dir:s})})]})},`${e}-${t}`))})}),(0,n.jsx)("tbody",{children:u.map((e,t)=>(0,n.jsx)("tr",{style:{borderBottom:"1px solid rgba(127,127,127,0.14)",background:t%2==1?"var(--bg-subtle)":"transparent"},children:d.map((r,i)=>(0,n.jsx)("td",{title:e[i]??"",style:{padding:"6px 10px",color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:0},children:e[i]??""},`${r}-${t}-${i}`))},t))})]})})]})}let t1=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"]),t2=new Set(["mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","webm"]),t4=new Set(["pdf","docx","xlsx","pptx","doc","xls","ppt"]);function t5(e){let t=N(e).toLowerCase().split(".").pop()??"";return"csv"===t?",":"tsv"===t?" ":null}function t6(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function t3({oldContent:e,newContent:t}){let r=function(e,t){let r=e.length,n=t.length,i=r+n,o=Array(2*i+1).fill(0),l=[];for(let s=0;s<=i;s++){l.push([...o]);for(let a=-s;a<=s;a+=2){let d,c=(d=a===-s||a!==s&&o[a-1+i]<o[a+1+i]?o[a+1+i]:o[a-1+i]+1)-a;for(;d<r&&c<n&&e[d]===t[c];)d++,c++;if(o[a+i]=d,d>=r&&c>=n){let o=[],a=r,d=n;for(let r=s;r>0;r--){let n,s=l[r-1],c=a-d;n=c===-r||c!==r&&s[c-1+i]<s[c+1+i]?c+1:c-1;let u=s[n+i],p=u-n;for(;a>u&&d>p;)a--,d--,o.unshift({type:"unchanged",text:e[a],lineNo:a+1});r>0&&(a>u?(a--,o.unshift({type:"removed",text:e[a],lineNo:a+1})):(d--,o.unshift({type:"added",text:t[d],lineNo:d+1})))}for(;a>0&&d>0;)a--,d--,o.unshift({type:"unchanged",text:e[a],lineNo:a+1});return o}}}return[...e.map((e,t)=>({type:"removed",text:e,lineNo:t+1})),...t.map((e,t)=>({type:"added",text:e,lineNo:t+1}))]}(e.split("\n"),t.split("\n"));if(!r.some(e=>"unchanged"!==e.type))return(0,n.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"No changes"});let i=new Set(r.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),o=new Set;for(let e of i)for(let t=Math.max(0,e-3);t<=Math.min(r.length-1,e+3);t++)o.add(t);let l=[],s=0;for(;s<r.length;)if(o.has(s)){let e=[];for(;s<r.length&&o.has(s);)e.push(r[s]),s++;l.push({hidden:!1,lines:e})}else{let e=0;for(;s<r.length&&!o.has(s);)e++,s++;l.push({hidden:!0,count:e})}let a=[],d=1;for(let e of r)"removed"===e.type?a.push(0):a.push(d++);let c=0;return(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},children:l.map((e,t)=>{if(e.hidden){let r=(0,n.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);return c+=e.count,r}let r=e.lines.map((e,t)=>{let r=a[c+t],i="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",o="added"===e.type?"+":"removed"===e.type?"-":" ",l="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",background:i,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,n.jsx)("span",{style:{minWidth:44,padding:"0 8px 0 16px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",fontSize:11,lineHeight:1.6,borderRight:"1px solid var(--border)",background:"var(--bg-panel)",flexShrink:0},children:"removed"===e.type?e.lineNo:r||""}),(0,n.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:l,userSelect:"none",flexShrink:0,fontWeight:600},children:o}),(0,n.jsx)("span",{style:{flex:1,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)",overflowX:"auto"},children:e.text||"\xa0"})]},t)});return c+=e.lines.length,(0,n.jsx)("div",{children:r},t)})})}function t8({filePath:e,cwd:t}){let[r,o]=(0,i.useState)(!1),[l,s]=(0,i.useState)(0),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),x=(0,i.useRef)(null),g=N(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{s(0),d(null),u(null),h(null),o(!1),x.current&&(x.current.close(),x.current=null);let t=B(e),r=new EventSource(`/api/files/${t}?type=watch`);return x.current=r,r.addEventListener("connected",()=>o(!0)),r.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}s(e=>e+1)}),r.addEventListener("error",()=>o(!1)),r.onerror=()=>o(!1),()=>{r.close(),x.current=null}},[e]);let f=B(e),v=`/api/files/${f}?type=read${l?`&v=${l}`:""}`,m=null!=a?t6(a):null;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:P(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:g||"image"}),c&&(0,n.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),m&&(0,n.jsx)("span",{children:m}),(0,n.jsxs)("span",{title:r?"Live sync active":"Not watching",style:{display:"flex",alignItems:"center",gap:4,color:r?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:r?"#4ade80":"var(--border)",display:"inline-block",boxShadow:r?"0 0 4px #4ade80":"none"}}),r?"live":"static"]})]}),(0,n.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:p?(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13},children:p}):(0,n.jsx)("img",{src:v,alt:e,onLoad:e=>{let t=e.currentTarget;u({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>h("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function t7({filePath:e,cwd:t}){let[r,o]=(0,i.useState)(!1),[l,s]=(0,i.useState)(0),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),x=(0,i.useRef)(null),g=N(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{s(0),d(null),u(null),h(null),o(!1),x.current&&(x.current.close(),x.current=null);let t=B(e),r=new EventSource(`/api/files/${t}?type=watch`);return x.current=r,r.addEventListener("connected",()=>o(!0)),r.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}u(null),h(null),s(e=>e+1)}),r.addEventListener("error",()=>o(!1)),r.onerror=()=>o(!1),()=>{r.close(),x.current=null}},[e]);let f=B(e),v=`/api/files/${f}?type=read${l?`&v=${l}`:""}`;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:P(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:g||"audio"}),null!=c&&(0,n.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),r=Math.floor(t/60);return`${r}:${String(t%60).padStart(2,"0")}`}(c)}),null!=a&&(0,n.jsx)("span",{children:t6(a)}),(0,n.jsxs)("span",{title:r?"Live sync active":"Not watching",style:{display:"flex",alignItems:"center",gap:4,color:r?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:r?"#4ade80":"var(--border)",display:"inline-block",boxShadow:r?"0 0 4px #4ade80":"none"}}),r?"live":"static"]})]}),(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,n.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[p&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:p}),(0,n.jsx)("audio",{controls:!0,preload:"metadata",src:v,onLoadedMetadata:e=>u(e.currentTarget.duration),onError:()=>h("Failed to load audio"),style:{width:"100%"}},v)]})})]})}function t9({filePath:e,cwd:t,onOpenFile:r}){let i,o,l;return(i=N(e).toLowerCase().split(".").pop()??"",t1.has(i))?(0,n.jsx)(t8,{filePath:e,cwd:t}):(o=N(e).toLowerCase().split(".").pop()??"",t2.has(o))?(0,n.jsx)(t7,{filePath:e,cwd:t}):(l=N(e).toLowerCase().split(".").pop()??"",t4.has(l))?(0,n.jsx)(re,{filePath:e,cwd:t}):(0,n.jsx)(rt,{filePath:e,cwd:t,onOpenFile:r})}function re({filePath:e,cwd:t}){let r,[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(0),h="pdf"===(r=N(e).toLowerCase().split(".").pop()??"")?"pdf":"docx"===r||"doc"===r?"docx":"xlsx"===r||"xls"===r?"xlsx":"pptx"===r||"ppt"===r?"pptx":"other",x=N(e).toLowerCase().split(".").pop()??"",g=(0,i.useCallback)(async e=>{try{let t=B(e),r=p.current?`&v=${p.current}`:"",n=await fetch(`/api/files/${t}?type=read${r}`);if(!n.ok){let e=await n.json().catch(()=>({error:String(n.status)}));c(e.error??`HTTP ${n.status}`);return}let i=await n.arrayBuffer();l(i),c(null)}catch(e){c(String(e))}},[]);if((0,i.useEffect)(()=>{a(!0),c(null),l(null),p.current=0,u.current&&(u.current.close(),u.current=null),g(e).finally(()=>a(!1));let t=B(e),r=new EventSource(`/api/files/${t}?type=watch`);return u.current=r,r.addEventListener("connected",()=>{}),r.addEventListener("change",()=>{p.current+=1,g(e)}),r.addEventListener("error",()=>{}),r.onerror=()=>{},()=>{r.close(),u.current=null}},[e,g]),s&&!o)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:"Loading..."});if(d&&!o)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:d});if(!o)return null;let f=P(e,t);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:["pdf"===h&&(0,n.jsx)(tz,{arrayBuffer:o,fileName:f}),"docx"===h&&(0,n.jsx)(tI,{arrayBuffer:o,fileName:f}),"xlsx"===h&&(0,n.jsx)(tM,{arrayBuffer:o,fileName:f}),"pptx"===h&&(0,n.jsx)(tR,{arrayBuffer:o,fileName:f}),"other"===h&&(0,n.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:["Unsupported document format: .",x]})]})}function rt({filePath:e,cwd:t,onOpenFile:r}){let{isDark:o}=ep(),[l,s]=(0,i.useState)(null),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[x,g]=(0,i.useState)(null),[f,v]=(0,i.useState)(!1),[m,y]=(0,i.useState)("source"),[b,j]=(0,i.useState)(!1),[k,w]=(0,i.useState)(!1),[S,C]=(0,i.useState)(0),[T,z]=(0,i.useState)(!1),[L,I]=(0,i.useState)(""),[M,R]=(0,i.useState)(!1),[W,E]=(0,i.useState)(!1),[$,A]=(0,i.useState)(!1),[D,H]=(0,i.useState)(null),O=(0,i.useRef)(null),F=(0,i.useRef)(!1);F.current=T,(0,i.useRef)(null).current=l;let U=(0,i.useCallback)((e,t=!1)=>{let r=B(e);return fetch(`/api/files/${r}?type=read`).then(e=>e.json()).then(e=>e.error?(h(e.error),null):(t?(s(t=>(t&&d(t.content),e)),C(e=>e+1)):s(e),h(null),e)).catch(e=>(h(String(e)),null))},[]);(0,i.useEffect)(()=>{u(!0),h(null),s(null),d(null),v(!1),y("source"),j(!1),C(0),w(!1),O.current&&(O.current.close(),O.current=null),U(e).then(t=>{(t?.language==="markdown"||t5(e))&&v(!0)}).finally(()=>u(!1));let t=B(e),r=new EventSource(`/api/files/${t}?type=watch`);return O.current=r,r.addEventListener("connected",()=>{w(!0)}),r.addEventListener("change",()=>{F.current?E(!0):U(e,!0)}),r.addEventListener("error",()=>{w(!1)}),r.onerror=()=>{w(!1)},()=>{r.close(),O.current=null}},[e,U]);let _=(0,i.useCallback)(()=>{l&&(z(!0),I(l.content),H(l.mtime??null),A(!1),g(null),E(!1),v(!1),y("source"))},[l]),V=(0,i.useCallback)(async(t=!1)=>{let r=B(e);R(!0),A(!1),g(null);try{let n=await fetch(`/api/files/${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:L,...t||!D?{}:{baseMtime:D}})});if(409===n.status){let e=await n.json().catch(()=>({error:"File changed on disk since it was opened"}));throw A(!0),E(!0),Error(e.error??"File changed on disk since it was opened")}if(!n.ok){let e=await n.json().catch(()=>({error:String(n.status)}));throw Error(e.error??`HTTP ${n.status}`)}let i=await U(e,!0);H(i?.mtime??null),z(!1),E(!1),A(!1)}catch(e){g(e instanceof Error?e.message:String(e))}finally{R(!1)}},[e,L,D,U]),J=(0,i.useCallback)(()=>{z(!1),E(!1),A(!1),g(null),H(null)},[]),K=(0,i.useCallback)(async()=>{let t=await U(e,!0);t&&(I(t.content),H(t.mtime??null),E(!1),A(!1),g(null),h(null))},[U,e]);if(c)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:"Loading..."});if(p)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:p});if(!l)return null;let q="html"===l.language,Y="markdown"===l.language,G=t5(e),Z=null!==G,X=l.content.split("\n"),Q=null!==a&&a!==l.content;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:P(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:l.language}),"source"===m&&(0,n.jsxs)("span",{children:[X.length," lines"]}),(0,n.jsx)("span",{children:t6(l.size)}),(0,n.jsxs)("span",{title:k?"Live sync active":"Not watching",style:{display:"flex",alignItems:"center",gap:4,color:k?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:k?"#4ade80":"var(--border)",display:"inline-block",boxShadow:k?"0 0 4px #4ade80":"none"}}),k?"live":"static"]}),T?(0,n.jsxs)(n.Fragment,{children:[(W||$||x)&&(0,n.jsxs)("span",{title:"File changed on disk while editing",style:{padding:"2px 8px",fontSize:11,background:"rgba(234,179,8,0.1)",color:"#b8860b",border:"1px solid rgba(234,179,8,0.3)",borderRadius:5,display:"flex",alignItems:"center",gap:4},children:[(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,n.jsx)("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),(0,n.jsx)("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),x??"External change",(W||$)&&(0,n.jsx)("button",{onClick:K,style:{marginLeft:4,padding:"1px 6px",fontSize:10,cursor:"pointer",background:"rgba(234,179,8,0.2)",color:"#b8860b",border:"1px solid rgba(234,179,8,0.3)",borderRadius:3,fontWeight:600},children:"Reload"}),$&&(0,n.jsx)("button",{onClick:()=>void V(!0),disabled:M,style:{marginLeft:4,padding:"1px 6px",fontSize:10,cursor:M?"not-allowed":"pointer",background:"rgba(239,68,68,0.12)",color:"#ef4444",border:"1px solid rgba(239,68,68,0.3)",borderRadius:3,fontWeight:600},children:"Overwrite"})]}),(0,n.jsx)("button",{onClick:()=>void V(),disabled:M,title:"Save file (Ctrl+S)",style:{padding:"2px 10px",fontSize:11,cursor:M?"not-allowed":"pointer",background:"var(--accent)",color:"#fff",border:"1px solid var(--accent)",borderRadius:5,fontWeight:600,opacity:M?.6:1},children:M?"Saving…":"Save"}),(0,n.jsx)("button",{onClick:J,title:"Cancel editing",style:{padding:"2px 10px",fontSize:11,cursor:"pointer",background:"var(--bg-hover)",color:"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5,fontWeight:600},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.1)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.3)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:"Cancel"})]}):(0,n.jsx)("button",{onClick:_,title:"Edit file",style:{padding:"2px 10px",fontSize:11,cursor:"pointer",background:"var(--bg-hover)",color:"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5,fontWeight:600},onMouseEnter:e=>{e.currentTarget.style.background="var(--accent)",e.currentTarget.style.color="#fff",e.currentTarget.style.borderColor="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:"Edit"}),Q&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>y("source"),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:"source"===m?"var(--bg-selected)":"var(--bg-hover)",color:"source"===m?"var(--text)":"var(--text-muted)",fontWeight:"source"===m?600:400},children:"Source"}),(0,n.jsxs)("button",{onClick:()=>y("diff"),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:"diff"===m?"var(--bg-selected)":"var(--bg-hover)",color:"diff"===m?"var(--text)":"var(--text-muted)",fontWeight:"diff"===m?600:400},children:["Diff ",S>0&&(0,n.jsxs)("span",{style:{color:"#4ade80",marginLeft:2},children:["+",S]})]})]}),"source"===m&&!f&&(0,n.jsx)("button",{onClick:()=>j(e=>!e),title:b?"Disable word wrap":"Enable word wrap",style:{padding:"2px 8px",fontSize:11,cursor:"pointer",background:b?"var(--bg-selected)":"var(--bg-hover)",color:b?"var(--text)":"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5,fontWeight:b?600:400},children:"wrap"}),q&&"source"===m&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>v(!1),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:f?"var(--bg-hover)":"var(--bg-selected)",color:f?"var(--text-muted)":"var(--text)",fontWeight:f?400:600},children:"Code"}),(0,n.jsx)("button",{onClick:()=>v(!0),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:f?"var(--bg-selected)":"var(--bg-hover)",color:f?"var(--text)":"var(--text-muted)",fontWeight:f?600:400},children:"Preview"})]}),Y&&"source"===m&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>v(!0),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:f?"var(--bg-selected)":"var(--bg-hover)",color:f?"var(--text)":"var(--text-muted)",fontWeight:f?600:400},children:"Preview"}),(0,n.jsx)("button",{onClick:()=>v(!1),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:f?"var(--bg-hover)":"var(--bg-selected)",color:f?"var(--text-muted)":"var(--text)",fontWeight:f?400:600},children:T?"Edit":"Raw"})]}),Z&&"source"===m&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>v(!0),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:f?"var(--bg-selected)":"var(--bg-hover)",color:f?"var(--text)":"var(--text-muted)",fontWeight:f?600:400},children:"Table"}),(0,n.jsx)("button",{onClick:()=>v(!1),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:f?"var(--bg-hover)":"var(--bg-selected)",color:f?"var(--text-muted)":"var(--text)",fontWeight:f?400:600},children:"Raw"})]})]}),(0,n.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:T&&!(Y&&f)?(0,n.jsx)(tZ,{initialContent:L,language:l.language,isDark:o,onChange:I,onSave:()=>void V()}):T&&Y&&f?(0,n.jsx)(eq,{content:L,className:"markdown-body markdown-file-preview",codeBlockVariant:"file",baseFilePath:e,onOpenLocalFile:r,style:{padding:"28px 36px",maxWidth:920,margin:"0 auto"}}):"diff"===m&&Q?(0,n.jsx)(t3,{oldContent:a,newContent:l.content,language:l.language}):q&&f?(0,n.jsx)("iframe",{srcDoc:l.content,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:"HTML preview"}):Y&&f?(0,n.jsx)(eq,{content:l.content,className:"markdown-body markdown-file-preview",codeBlockVariant:"file",baseFilePath:e,onOpenLocalFile:r,style:{padding:"28px 36px",maxWidth:920,margin:"0 auto"}}):Z&&f&&G?(0,n.jsx)(t0,{content:l.content,delimiter:G,fileName:N(e)}):(0,n.jsx)(eP.A,{language:"text"===l.language||"csv"===l.language||"tsv"===l.language?"plaintext":l.language,style:eF(o),showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",minWidth:"3em",paddingRight:"1em"},customStyle:{margin:0,padding:"12px 0",background:"var(--bg)",fontSize:13,lineHeight:1.6,fontFamily:"var(--font-mono)",minHeight:"100%"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},wrapLongLines:b,children:l.content})})]})}let rr={__soul__:{apiPath:"/api/soul",title:"soul.md"},__harness__:{apiPath:"/api/harness",title:"harness.md"}};function rn({filePath:e}){let t=rr[e],{isDark:r}=ep(),[o,l]=(0,i.useState)(""),[s,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{t&&(a(!0),fetch(t.apiPath).then(e=>e.json()).then(e=>l(e.content??"")).catch(e=>c(String(e))).finally(()=>a(!1)))},[t]);let g=(0,i.useCallback)(async()=>{if(t){p(!0);try{await fetch(t.apiPath,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})}),x(!0),setTimeout(()=>x(!1),2e3)}catch(e){c(String(e))}finally{p(!1)}}},[t,o]);return t?s?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:"Loading…"}):d?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:d}):(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:600,color:"var(--text)"},children:t.title}),(0,n.jsx)("span",{style:{marginLeft:"auto",fontSize:10,color:"var(--text-dim)"},children:"Global"}),h&&(0,n.jsx)("span",{style:{color:"#4ade80",fontWeight:600,animation:"saved-pop 0.3s ease"},children:"✓ Saved"}),(0,n.jsx)("button",{onClick:g,disabled:u,title:"Save (Ctrl+S)",style:{padding:"2px 10px",fontSize:11,cursor:u?"not-allowed":"pointer",background:"var(--accent)",color:"#fff",border:"1px solid var(--accent)",borderRadius:5,fontWeight:600,opacity:u?.6:1},children:u?"Saving…":"Save"})]}),(0,n.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,n.jsx)(tZ,{initialContent:o,language:"markdown",isDark:r,onChange:l,onSave:g})})]}):null}function ri(e){return"verified"===e?"#16a34a":"outdated"===e?"#ef4444":"needs_review"===e?"rgba(234,179,8,0.95)":"var(--text-dim)"}function ro({sessionId:e,cwd:t,refreshKey:r=0,onOpenFile:o}){let[l,s]=(0,i.useState)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[x,g]=(0,i.useState)("preview");(0,i.useEffect)(()=>{if(!e){s(null),h(null);return}let t=!1;return d(!0),h(null),fetch(`/api/reports/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():e.json().then(t=>Promise.reject(Error(t.error??`HTTP ${e.status}`)))).then(e=>{t||s(e.report)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||d(!1)}),()=>{t=!0}},[e,r]);let f=(0,i.useCallback)(()=>{e&&(u(!0),h(null),fetch(`/api/reports/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"generate"})}).then(e=>e.ok?e.json():e.json().then(t=>Promise.reject(Error(t.error??`HTTP ${e.status}`)))).then(e=>{s(e.report),g("preview")}).catch(e=>h(e instanceof Error?e.message:String(e))).finally(()=>u(!1)))},[e]),v=(0,i.useMemo)(()=>{if(t)return`${t.replace(/\/+$/,"")}/analysis_report.md`},[t]),m=(0,i.useMemo)(()=>l?.sections.filter(e=>e.markdown.trim())??[],[l]);return e?(0,n.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"8px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0},children:[["preview","sections","changes","source"].map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>g(e),style:{height:28,padding:"0 9px",border:"1px solid var(--border)",borderRadius:7,background:x===e?"var(--bg-selected)":"var(--bg-panel)",color:x===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,textTransform:"capitalize"},children:e},e)),(0,n.jsx)("div",{style:{flex:1}}),(0,n.jsx)("button",{type:"button",onClick:f,disabled:c,title:"Refresh analysis report from this session",style:{height:28,padding:"0 10px",border:"1px solid rgba(37,99,235,0.45)",borderRadius:7,background:"var(--bg-selected)",color:"var(--accent)",cursor:c?"default":"pointer",fontSize:11,fontWeight:600,opacity:c?.65:1},children:c?"Updating...":"Update"})]}),p&&(0,n.jsx)("div",{style:{padding:"8px 12px",color:"#ef4444",fontSize:12,borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.08)"},children:p}),a?(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:12},children:"Loading report..."}):l?(0,n.jsxs)("div",{style:{flex:1,overflow:"auto"},children:["preview"===x&&(0,n.jsx)(eq,{content:l.markdown,className:"markdown-body markdown-file-preview",style:{padding:"22px 26px 40px",maxWidth:860,margin:"0 auto"},codeBlockVariant:"file",baseFilePath:v,onOpenLocalFile:o}),"sections"===x&&(0,n.jsx)("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:m.map(e=>{var t;return(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"9px 11px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)",flex:1},children:e.title}),(0,n.jsx)("span",{style:{fontSize:10,color:ri(e.status),border:`1px solid ${ri(e.status)}`,borderRadius:999,padding:"2px 7px"},children:"needs_review"===(t=e.status)?"Needs review":t.slice(0,1).toUpperCase()+t.slice(1)})]}),(0,n.jsx)("div",{style:{padding:"9px 11px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:e.markdown.replace(/[#*_`>|-]/g," ").replace(/\s+/g," ").trim()||"No curated content yet."})]},e.id)})}),"changes"===x&&(0,n.jsx)("div",{style:{padding:14},children:0===l.changes.length?(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontSize:12},children:"No report changes yet."}):l.changes.map(e=>(0,n.jsxs)("div",{style:{padding:"10px 0",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)",marginBottom:4},children:e.title}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:6},children:new Date(e.timestamp).toLocaleString()}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.detail})]},e.id))}),"source"===x&&(0,n.jsx)("pre",{style:{margin:0,padding:18,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,color:"var(--text-muted)"},children:l.markdown})]}):(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:"No report available."})]}):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:"Select or start a session to build an analysis report."})}function rl(){document.body.style.cursor="",document.body.style.userSelect=""}function rs({side:e,onResize:t,onResizeStart:r,onResizeEnd:o,ariaLabel:l}){let s=(0,i.useRef)(null),a=(0,i.useRef)(!1),d=(0,i.useRef)(0),[c,u]=(0,i.useState)(!1),p=(0,i.useCallback)(e=>{if(!a.current)return;a.current=!1,u(!1);let t=s.current;t&&void 0!==e&&t.hasPointerCapture(e)&&t.releasePointerCapture(e),rl(),o?.()},[o]),h=(0,i.useCallback)(e=>{0===e.button&&e.isPrimary&&(e.preventDefault(),a.current=!0,d.current=e.clientX,u(!0),r?.(),e.currentTarget.setPointerCapture(e.pointerId),document.body.style.cursor="col-resize",document.body.style.userSelect="none")},[r]),x=(0,i.useCallback)(e=>{if(!a.current)return;e.preventDefault();let r=e.clientX-d.current;d.current=e.clientX,t(r)},[t]),g=(0,i.useCallback)(e=>{e.preventDefault(),p(e.pointerId)},[p]),f=(0,i.useCallback)(e=>{p(e.pointerId)},[p]);return(0,i.useEffect)(()=>()=>{a.current&&(a.current=!1,rl(),o?.())},[o]),(0,n.jsx)("div",{ref:s,role:"separator","aria-label":l??"Resize panel","aria-orientation":"vertical",className:`resize-handle${c?" resize-handle-dragging":""}`,"data-side":e,onPointerDown:h,onPointerMove:x,onPointerUp:g,onPointerCancel:f,style:{alignSelf:"stretch",cursor:"col-resize",display:"flex",flexShrink:0,justifyContent:"center",marginLeft:-5,marginRight:-5,position:"relative",touchAction:"none",width:10,zIndex:250},children:(0,n.jsx)("div",{className:"resize-handle-line"})})}function ra({tabs:e,activeTabId:t,onSelectTab:r,onCloseTab:o}){let[l,s]=(0,i.useState)(null);return(0,n.jsx)("div",{style:{display:"flex",alignItems:"flex-end",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t,a=!1!==e.closable;return(0,n.jsxs)("div",{onClick:()=>r(e.id),style:{display:"flex",alignItems:"center",gap:6,height:36,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:i?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:i?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,n.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:"report"===e.icon?(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,n.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,n.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,n.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}):E(e.filePath??e.label,13)}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},title:e.filePath??e.label,children:e.label}),a&&(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),o(e.id)},onMouseEnter:()=>s(e.id),onMouseLeave:()=>s(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:16,height:16,background:l===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:3,color:l===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:"Close",children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,n.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}function rd(e){let t=e,r=0;for(;1===t.children.length;)t=t.children[0],r++;return{node:t,skipped:r}}function rc({node:e,activePathIds:t,depth:r,isLast:i,parentLines:o,onSelect:l}){let{node:s,skipped:a}=rd(e),d=t.has(s.entry.id),c=t.has(e.entry.id)||t.has(s.entry.id),u=function(e){if("message"===e.type&&"message"in e){let t=e.message,r=t.content,n="";if("string"==typeof r?n=r:Array.isArray(r)&&(n=r.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),n.length>40&&(n=n.slice(0,40)+"…"),n)return n;if("assistant"===t.role)return"[assistant]"}return e.type}(s.entry),p="message"===s.entry.type&&"message"in s.entry?s.entry.message.role:null;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>l(s.entry.id),children:[o.map((e,t)=>(0,n.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,n.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,n.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,n.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,n.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,n.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:d?"var(--accent)":c?"var(--text-muted)":"var(--border)",border:d?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),p&&(0,n.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===p?"var(--accent)":"var(--text-dim)",background:"user"===p?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===p?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===p?"U":"A"}),a>0&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",a]}),(0,n.jsx)("span",{style:{fontSize:11,color:d?"var(--text)":c?"var(--text-muted)":"var(--text-dim)",fontWeight:d?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:u})]}),s.children.map((e,a)=>(0,n.jsx)(rc,{node:e,activePathIds:t,depth:r+1,isLast:a===s.children.length-1,parentLines:[...o,!i],onSelect:l},e.entry.id))]})}function ru({tree:e,activeLeafId:t,onLeafChange:r,inline:o,containerRef:l,open:s,onToggle:a,hasSession:d}){let[c,u]=(0,i.useState)(!1),p=void 0!==s?s:c,h=(0,i.useRef)(null),[x,g]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!p||!o)return;let e=l?.current??h.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();g({top:t.bottom,left:t.left,width:t.width})};t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[p,o,l]);let f=(0,i.useMemo)(()=>t?new Set(function e(r,n){for(let i of r){let r=[...n,i.entry.id];if(i.entry.id===t)return r;let o=e(i.children,r);if(o)return o}return null}(e,[])??[]):new Set,[e,t]),v=(0,i.useCallback)(e=>{r(e)},[r]),m=d?!function e(t){for(let r of t)if(r.children.length>1||e(r.children))return!0;return!1}(e)?"This session has no branches":null:"No active session",y=e.length>0?rd(e[0]):null,b=y?.node??null,j=!m&&b&&b.children.length>1,k=(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:j?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),w=(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:p?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return o?(0,n.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,n.jsxs)("button",{ref:h,onClick:()=>a?a():u(e=>!e),style:{display:"flex",alignItems:"center",gap:6,height:28,padding:"0 9px",background:p?"var(--bg-selected)":"var(--bg-panel)",border:`1px solid ${p?"rgba(37,99,235,0.45)":"var(--border)"}`,borderRadius:7,cursor:"pointer",color:p?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, border-color 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=p?"var(--text)":"var(--text-muted)",e.currentTarget.style.background=p?"var(--bg-selected)":"var(--bg-panel)"},children:[k,(0,n.jsx)("span",{children:"Branches"})]}),p&&x&&(0,n.jsx)("div",{style:{position:"fixed",top:x.top,left:x.left,width:x.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:j&&b?(0,n.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:b.children.map((e,t)=>(0,n.jsx)(rc,{node:e,activePathIds:f,depth:0,isLast:t===b.children.length-1,parentLines:[],onSelect:v},e.entry.id))}):(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:m})})]}):(0,n.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,n.jsxs)("button",{onClick:()=>u(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[k,(0,n.jsx)("span",{style:{color:"var(--text-muted)"},children:"Branches"}),w]}),p&&(0,n.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:j&&b?(0,n.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:b.children.map((e,t)=>(0,n.jsx)(rc,{node:e,activePathIds:f,depth:0,isLast:t===b.children.length-1,parentLines:[],onSelect:v},e.entry.id))}):(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:m??"This session has no branches"})})]})}function rp(e,t="0 0 24 24"){let r=({size:r=24,style:i})=>(0,n.jsx)("svg",{width:r,height:r,viewBox:t,fill:"none",style:i,children:e});return r.displayName="ProviderIcon",r}let rh=rp((0,n.jsx)("path",{d:"M17.5 3H6.5L3 21h4l1.2-6h7.6l1.2 6h4L17.5 3zm-2.3 9H8.8L12 5.5 15.2 12z",fill:"currentColor"})),rx=rp((0,n.jsx)("path",{d:"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5",stroke:"currentColor",strokeWidth:"1.5",strokeLinejoin:"round"})),rg=rp((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z",fill:"#4285F4"}),(0,n.jsx)("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"#34A853"}),(0,n.jsx)("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"#FBBC05"}),(0,n.jsx)("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"#EA4335"})]})),rf=rp((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"3",fill:"#4D6BFE"}),(0,n.jsx)("text",{x:"12",y:"16",textAnchor:"middle",fill:"white",fontSize:"10",fontWeight:"bold",fontFamily:"sans-serif",children:"DS"})]})),rv=rp((0,n.jsx)("path",{d:"M4 4h16v16H4z",fill:"#F55036"}),"0 0 24 24"),rm=rp((0,n.jsx)("path",{d:"M4 4h5v5H4zm5.5 0h5v5h-5zM15 4h5v5h-5zM4 9.5h5v5H4zm5.5 5.5h5v5h-5zM15 9.5h5v5h-5z",fill:"#FA6F00"})),ry=rp((0,n.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),"0 0 24 24"),rb=rp((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"3",fill:"#00D4AA"}),(0,n.jsx)("text",{x:"12",y:"16",textAnchor:"middle",fill:"white",fontSize:"9",fontWeight:"bold",fontFamily:"sans-serif",children:"MM"})]})),rj=rp((0,n.jsx)("circle",{cx:"12",cy:"12",r:"10",fill:"#FF5722"}),"0 0 24 24"),rk=rp((0,n.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 5h2v3h-2V7zm0 4h2v2h-2v-2zm3 5H7v-2h7v2z",fill:"#FFD21E"})),rw=rp((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"3",fill:"#E84026"}),(0,n.jsx)("text",{x:"12",y:"16",textAnchor:"middle",fill:"white",fontSize:"9",fontWeight:"bold",fontFamily:"sans-serif",children:"CB"})]})),rS=rp((0,n.jsx)("path",{d:"M12 2l9 5v10l-9 5-9-5V7l9-5z",stroke:"currentColor",strokeWidth:"1.5",fill:"none"})),rC=rp((0,n.jsx)("path",{d:"M4 4l8 8 8-8M4 20l8-8 8 8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})),rT=rp((0,n.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 5l4 3-4 3V7z",fill:"#F38020"})),rz={anthropic:{Icon:rh,hasColor:!1},openai:{Icon:rx,hasColor:!1},"openai-codex":{Icon:rx,hasColor:!1},google:{Icon:rg,hasColor:!0},"google-vertex":{Icon:rg,hasColor:!0},deepseek:{Icon:rf,hasColor:!0},groq:{Icon:rv,hasColor:!1},mistral:{Icon:rm,hasColor:!0},moonshotai:{Icon:ry,hasColor:!1},"moonshotai-cn":{Icon:ry,hasColor:!1},moonshot:{Icon:ry,hasColor:!1},minimax:{Icon:rb,hasColor:!0},"minimax-cn":{Icon:rb,hasColor:!0},fireworks:{Icon:rj,hasColor:!0},huggingface:{Icon:rk,hasColor:!0},cerebras:{Icon:rw,hasColor:!0},openrouter:{Icon:rS,hasColor:!1},xai:{Icon:rC,hasColor:!1},"cloudflare-ai-gateway":{Icon:rT,hasColor:!0},"cloudflare-workers-ai":{Icon:rT,hasColor:!0},"vercel-ai-gateway":{Icon:rp((0,n.jsx)("path",{d:"M12 2L22 20H2L12 2z",fill:"currentColor"})),hasColor:!1},"github-copilot":{Icon:rp((0,n.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),"0 0 24 24"),hasColor:!1},"amazon-bedrock":{Icon:rp((0,n.jsx)("path",{d:"M3 15h2l1-3h2l1 3h2V9H9v3L8 9H6l-1 3V9H3v6zm9 0h2v-2h2v-2h-2V9h-2v2h-2v2h2v2z",fill:"#FF9900"})),hasColor:!0},"azure-openai-responses":{Icon:rp((0,n.jsx)("path",{d:"M12 2L3 18h5l4-6 4 6h5L12 2z",fill:"#0078D4"})),hasColor:!0},"kimi-coding":{Icon:rp((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"3",fill:"#6C5CE7"}),(0,n.jsx)("text",{x:"12",y:"16",textAnchor:"middle",fill:"white",fontSize:"10",fontWeight:"bold",fontFamily:"sans-serif",children:"Ki"})]})),hasColor:!0},qwen:{Icon:rp((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"3",fill:"#615CED"}),(0,n.jsx)("text",{x:"12",y:"16",textAnchor:"middle",fill:"white",fontSize:"9",fontWeight:"bold",fontFamily:"sans-serif",children:"QW"})]})),hasColor:!0},zai:{Icon:rp((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"3",fill:"#3859FF"}),(0,n.jsx)("text",{x:"12",y:"16",textAnchor:"middle",fill:"white",fontSize:"9",fontWeight:"bold",fontFamily:"sans-serif",children:"ZP"})]})),hasColor:!0},cohere:{Icon:rp((0,n.jsx)("path",{d:"M4 8h16v2H4zm0 4h12v2H4zm0 4h8v2H4z",fill:"#3059B1"})),hasColor:!0},perplexity:{Icon:rp((0,n.jsx)("path",{d:"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5",stroke:"#1DB954",strokeWidth:"1.5",fill:"none",strokeLinejoin:"round"})),hasColor:!0},together:{Icon:rp((0,n.jsx)("circle",{cx:"12",cy:"12",r:"10",fill:"#0F6CBD"}),"0 0 24 24"),hasColor:!0},grok:{Icon:rp((0,n.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),"0 0 24 24"),hasColor:!1}},rL=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function rI({label:e,children:t}){return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let rM={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function rR({value:e,onChange:t,placeholder:r,mono:i}){return(0,n.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:r,style:{...rM,fontFamily:i?"var(--font-mono)":"inherit"}})}function rW({value:e,onChange:t,placeholder:r,mono:o,onKeyDown:l,autoComplete:s="off",spellCheck:a=!1,style:d}){let[c,u]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,n.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,n.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:l,placeholder:r,style:{...rM,paddingRight:34,fontFamily:o?"var(--font-mono)":"inherit"},autoComplete:s,spellCheck:a}),(0,n.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":c?"Hide API key":"Show API key",title:c?"Hide API key":"Show API key",style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:c?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,n.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,n.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,n.jsx)("path",{d:"M1 1l22 22"})]}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function rE({value:e,onChange:t,placeholder:r}){return(0,n.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:r,style:rM})}function r$({value:e,onChange:t,options:r,required:i}){return(0,n.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...rM,color:e?"var(--text)":"var(--text-dim)"},children:[!i&&(0,n.jsx)("option",{value:"",children:"— inherit / none —"}),r.map(e=>(0,n.jsx)("option",{value:e,children:e},e))]})}function rB({label:e,checked:t,onChange:r}){return(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,n.jsx)("input",{type:"checkbox",checked:t,onChange:e=>r(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function rN({children:e}){return(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function rP({name:e,provider:t,onChange:r,onRename:o,onDelete:l}){let[s,a]=(0,i.useState)(e);(0,i.useEffect)(()=>a(e),[e]);let d=(e,n)=>r({...t,[e]:n});return(0,i.useEffect)(()=>{t.api||r({...t,api:"openai-completions"})},[t.api]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(rN,{children:"Provider"}),(0,n.jsx)("button",{onClick:l,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:"Delete"})]}),(0,n.jsxs)(rI,{label:"Provider name",children:[(0,n.jsx)(rR,{value:s,onChange:a,placeholder:"provider-name",mono:!0}),s!==e&&s.trim()&&(0,n.jsx)("button",{onClick:()=>o(s.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:"Rename"})]}),(0,n.jsx)(rI,{label:"Base URL",children:(0,n.jsx)(rR,{value:t.baseUrl??"",onChange:e=>d("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,n.jsxs)(rI,{label:"API Key",children:[(0,n.jsx)(rW,{value:t.apiKey??"",onChange:e=>d("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,n.jsx)(rI,{label:"API",children:(0,n.jsx)(r$,{value:t.api??"openai-completions",onChange:e=>d("api",e),options:rL,required:!0})})]})}let rA=["off","minimal","low","medium","high","xhigh"],rD={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c"};function rH({value:e,onChange:t}){let r=e??{},i=(e,n)=>{let i={...r};"omit"===n?delete i[e]:i[e]=n,t(Object.keys(i).length?i:void 0)};return(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:rA.map(e=>{let t=r[e],o=e in r?null===t?"null":"string":"omit",l="string"==typeof t?t:"",s=rD[e],a={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--accent)",color:"#fff",fontWeight:600};return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:s,flexShrink:0,opacity:"null"===o?.3:1}}),(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===o?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===o?"line-through":"none"},children:e})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,n.jsx)("button",{onClick:()=>i(e,"omit"),style:{...a,..."omit"===o?d:{}},children:"Default"}),(0,n.jsx)("button",{onClick:()=>i(e,null),style:{...a,borderLeft:"1px solid var(--border)",..."null"===o?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===o?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,n.jsx)("button",{onClick:()=>i(e,l||e),style:{...a,..."string"===o?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,n.jsx)("input",{value:l,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==o&&i(e,l||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===o?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===o?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let rO={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function rF({providerName:e,provider:t,model:r,onChange:o,onDelete:l}){let[s,a]=(0,i.useState)({phase:"idle"}),d=(e,t)=>o({...r,[e]:t}),c=(()=>{if("idle"===s.phase)return null;if("testing"===s.phase)return"Testing model connection...";let e=[void 0!==s.latencyMs?`${s.latencyMs}ms`:null,void 0!==s.status?`HTTP ${s.status}`:null].filter(Boolean);return"success"===s.phase?["Connected",...e,s.responseText||null].filter(Boolean).join(" \xb7 "):["Failed",...e,s.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{a({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,r.id,r.api]);let u=(0,i.useCallback)(async()=>{if(r.id.trim()&&"testing"!==s.phase){a({phase:"testing"});try{let n=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:r})}),i=await n.json();if(!n.ok||!i.ok)return void a({phase:"error",message:i.error??`HTTP ${n.status}`,latencyMs:i.latencyMs,status:i.status});a({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){a({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[r,t,e,s.phase]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(rN,{children:"Model"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[c&&(0,n.jsx)("span",{title:c,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===s.phase?"#fecaca":"success"===s.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===s.phase?"#fee2e2":"success"===s.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:c}),(0,n.jsxs)("button",{onClick:u,disabled:!r.id.trim()||"testing"===s.phase,title:"Test model connection",style:{height:24,padding:"0 8px",background:"success"===s.phase?"#16a34a":"none",border:`1px solid ${"success"===s.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===s.phase?"#fff":r.id.trim()&&"testing"!==s.phase?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"testing"!==s.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===s.phase&&(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===s.phase?"Testing…":"success"===s.phase?"OK":"Test"]}),(0,n.jsx)("button",{onClick:l,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:"Remove"})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(rI,{label:"ID *",children:(0,n.jsx)(rR,{value:r.id,onChange:e=>d("id",e),placeholder:"model-id",mono:!0})}),(0,n.jsx)(rI,{label:"Name",children:(0,n.jsx)(rR,{value:r.name??"",onChange:e=>d("name",e||void 0),placeholder:"Display name"})})]}),(0,n.jsx)(rI,{label:"API override",children:(0,n.jsx)(r$,{value:r.api??"",onChange:e=>d("api",e||void 0),options:rL})}),(0,n.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,n.jsx)(rB,{label:"Reasoning / thinking",checked:r.reasoning??!1,onChange:e=>d("reasoning",e||void 0)}),(0,n.jsx)(rB,{label:"Image input",checked:r.input?.includes("image")??!1,onChange:e=>d("input",e?["text","image"]:void 0)})]}),r.reasoning&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rB,{label:"DeepSeek thinking compat",checked:r.compat?.thinkingFormat==="deepseek",onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...rO}};if(!e.compat)return e;let r={...e.compat};return delete r.thinkingFormat,delete r.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(r).length?r:void 0}}(r,e))}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,n.jsx)(rN,{children:"Thinking level map"}),r.thinkingLevelMap&&(0,n.jsx)("button",{onClick:()=>d("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,n.jsx)(rH,{value:r.thinkingLevelMap,onChange:e=>d("thinkingLevelMap",e)})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(rI,{label:"Context window (tokens)",children:(0,n.jsx)(rE,{value:void 0!==r.contextWindow?String(r.contextWindow):"",onChange:e=>d("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,n.jsx)(rI,{label:"Max output tokens",children:(0,n.jsx)(rE,{value:void 0!==r.maxTokens?String(r.maxTokens):"",onChange:e=>d("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(rN,{children:"Cost (per million tokens)"}),(0,n.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,n.jsx)(rI,{label:e,children:(0,n.jsx)(rE,{value:r.cost?.[e]!==void 0?String(r.cost[e]):"",onChange:t=>{let n;return n=parseFloat(t),void o({...r,cost:{...r.cost??{},[e]:isNaN(n)?void 0:n}})},placeholder:"0"})},e))})]})]})}function rU({provider:e,onRefresh:t}){let[r,o]=(0,i.useState)({phase:"idle"}),[l,s]=(0,i.useState)(""),a=(0,i.useRef)(null),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===r.phase||"prompt"===r.phase)&&setTimeout(()=>d.current?.focus(),50)},[r.phase]),(0,i.useEffect)(()=>{o({phase:"idle"}),s(""),a.current?.close(),a.current=null},[e.id]),(0,i.useEffect)(()=>()=>{a.current?.close()},[]);let c=(0,i.useCallback)(()=>{a.current?.close(),o({phase:"connecting"}),s("");let r=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);a.current=r,r.onmessage=e=>{let n=JSON.parse(e.data);"auth"===n.type?(o({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),window.open(n.url,"_blank","noopener,noreferrer")):"device_code"===n.type?(o({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),window.open(n.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===n.type?o({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?o({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?o({phase:"progress",message:n.message}):"success"===n.type?(r.close(),o({phase:"success"}),t()):"error"===n.type?(r.close(),o({phase:"error",message:n.message})):"cancelled"===n.type&&(r.close(),o({phase:"idle"}))},r.onerror=()=>{r.close(),o(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,t]),u=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),o({phase:"idle"}),t()},[e.id,t]),p=(0,i.useCallback)(async(t,r)=>{if(r.trim()){o({phase:"progress",message:"Verifying…"});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:r.trim()})});if(!n.ok){let e=await n.json().catch(()=>({}));o({phase:"error",message:e.error??`Server error ${n.status}`});return}s("")}catch(e){o({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[e.id]),h=(0,i.useCallback)(async(t,r)=>{o({phase:"progress",message:"Continuing…"});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:r})});if(!n.ok){let e=await n.json().catch(()=>({}));o({phase:"error",message:e.error??`Server error ${n.status}`})}}catch(e){o({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id]),x="connecting"===r.phase||"progress"===r.phase||"auth"===r.phase||"device_code"===r.phase||"prompt"===r.phase||"select"===r.phase;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(rN,{children:"Subscription"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:e.loggedIn?"connected":"not connected"})]})]}),(0,n.jsxs)("div",{style:{minHeight:48},children:["idle"===r.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===r.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:"Opening browser…"}),"select"===r.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:r.message}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.options.map(e=>(0,n.jsx)("button",{onClick:()=>h(r.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===r.phase||"prompt"===r.phase)&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===r.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":r.message}),"auth"===r.phase&&(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,n.jsx)("a",{href:r.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{ref:d,value:l,onChange:e=>s(e.target.value),onKeyDown:e=>{"Enter"===e.key&&p(r.token,l)},placeholder:"auth"===r.phase?"http://localhost:1455/auth/callback?code=…":r.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,n.jsx)("button",{onClick:()=>p(r.token,l),disabled:!l.trim(),style:{padding:"6px 12px",background:l.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:l.trim()?"#fff":"var(--text-dim)",cursor:l.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:"Submit"})]})]}),"device_code"===r.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,n.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:r.userCode}),(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,n.jsx)("a",{href:r.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:r.verificationUri}),r.expiresInSeconds?` Expires in ${Math.ceil(r.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===r.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:r.message}),"success"===r.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:"Connected successfully."}),"error"===r.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:r.message})]}),(0,n.jsx)("div",{style:{display:"flex",gap:8},children:x?(0,n.jsx)("button",{onClick:()=>{a.current?.close(),o({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:"Cancel"}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{onClick:c,style:{padding:"5px 14px",background:"var(--accent)",border:"none",borderRadius:5,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600},children:e.loggedIn?"Re-login":"Login"}),e.loggedIn&&(0,n.jsx)("button",{onClick:u,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:"Disconnect"})]})})]})}function r_({provider:e,onRefresh:t}){let[r,o]=(0,i.useState)(""),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1);(0,i.useEffect)(()=>{o(""),u(null),h(!1)},[e.id]);let x=(0,i.useCallback)(async()=>{if(r.trim()){s(!0),u(null),h(!1);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r.trim()})}),i=await n.json();!n.ok||i.error?u(i.error??`HTTP ${n.status}`):(o(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{s(!1)}}},[r,e.id,t]),g=(0,i.useCallback)(async()=>{d(!0),u(null);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),n=await r.json();!r.ok||n.error?u(n.error??`HTTP ${r.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(rN,{children:"API Key"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:e.configured?"configured":"not configured"})]})]}),(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,n.jsx)(rI,{label:"API Key",children:(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)(rW,{value:r,onChange:o,onKeyDown:e=>{"Enter"===e.key&&r.trim()&&x()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,n.jsxs)("button",{onClick:x,disabled:l||!r.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":r.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:r.trim()||p?"#fff":"var(--text-dim)",cursor:l||!r.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),p?"Saved":l?"Saving…":"Save"]})]})}),c&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),e.configured&&(0,n.jsx)("button",{onClick:g,disabled:a,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:a?"not-allowed":"pointer",fontSize:12},children:a?"Removing…":"Disconnect"})]})}function rV({id:e,size:t}){let r=rz[e];return r?r.hasColor?(0,n.jsx)(r.Icon,{size:t}):(0,n.jsx)(r.Icon,{size:t,style:{color:"var(--text-muted)"}}):null}function rJ({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:r,onSelectApiKey:o,onAddCustom:l,onDiscover:s,onClose:a}){let[d,c]=(0,i.useState)(""),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=d.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),x=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),g=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),f=!p||"discover".includes(p)||"base url".includes(p)||"model import".includes(p),v=h.length+x.length+ +!!g+ +!!f,m={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},children:(0,n.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,n.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,n.jsx)("input",{ref:u,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Escape"===e.key&&a()},placeholder:"Search providers…",style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===v?(0,n.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:"No providers match"}):(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[g&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"Custom"}),g&&(0,n.jsxs)("button",{onClick:()=>{l(),a()},style:m,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Custom endpoint format"})]}),(0,n.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),f&&(0,n.jsxs)("button",{onClick:()=>{s(),a()},style:m,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"Discover models from Base URL"}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OpenAI-compatible / Ollama catalog"})]}),(0,n.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)"},children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,n.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})})]}),h.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"Subscriptions"}),h.map(e=>(0,n.jsxs)("button",{onClick:()=>{r(e.id),a()},style:m,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,n.jsx)(rV,{id:e.id,size:28})]},e.id)),x.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),x.map(e=>(0,n.jsxs)("button",{onClick:()=>{o(e.id),a()},style:m,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,n.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,n.jsx)(rV,{id:e.id,size:28})]},e.id))]})})]})})}function rK({existingProviders:e,onImport:t,onClose:r}){let[o,l]=(0,i.useState)(""),[s,a]=(0,i.useState)(""),[d,c]=(0,i.useState)("custom-provider"),[u,p]=(0,i.useState)(new Set),[h,x]=(0,i.useState)({phase:"idle"}),g=(0,i.useCallback)(async()=>{let e=o.trim();if(e&&"loading"!==h.phase){x({phase:"loading"});try{let t=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:e,apiKey:s,provider:d,enrich:!1})}),r=await t.json();if(!t.ok||!r.ok||!r.models||!r.piModels||!r.endpoint)return void x({phase:"error",message:r.error??`HTTP ${t.status}`});x({phase:"success",endpoint:r.endpoint,models:r.models,piModels:r.piModels}),p(new Set(r.piModels.map(e=>e.id)))}catch(e){x({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[s,o,d,h.phase]),f="success"===h.phase?h:null,v=u.size,m=!!(f&&d.trim()&&v>0);return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&r()},children:(0,n.jsxs)("div",{style:{width:880,maxWidth:"calc(100vw - 32px)",height:"min(78vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:"Discover models"}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:2},children:"Fetch model catalog from a Base URL and import selected models."})]}),(0,n.jsx)("button",{onClick:r,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{padding:16,borderBottom:"1px solid var(--border)",display:"grid",gridTemplateColumns:"1.4fr 1fr 0.9fr auto",gap:10,alignItems:"end",flexShrink:0},children:[(0,n.jsx)(rI,{label:"Base URL",children:(0,n.jsx)(rR,{value:o,onChange:l,placeholder:"https://api.example.com",mono:!0})}),(0,n.jsx)(rI,{label:"API Key",children:(0,n.jsx)(rW,{value:s,onChange:a,placeholder:"optional for local providers",mono:!0})}),(0,n.jsx)(rI,{label:"Provider name",children:(0,n.jsx)(rR,{value:d,onChange:c,placeholder:"provider-name",mono:!0})}),(0,n.jsx)("button",{onClick:g,disabled:!o.trim()||"loading"===h.phase,style:{height:31,padding:"0 14px",background:o.trim()&&"loading"!==h.phase?"var(--accent)":"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:o.trim()&&"loading"!==h.phase?"#fff":"var(--text-dim)",cursor:o.trim()&&"loading"!==h.phase?"pointer":"not-allowed",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:"loading"===h.phase?"Fetching...":"Fetch models"})]}),(0,n.jsxs)("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:["idle"===h.phase&&(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:"Enter a Base URL to discover available models."}),"loading"===h.phase&&(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:"Fetching model catalog..."}),"error"===h.phase&&(0,n.jsx)("div",{style:{padding:18,color:"#f87171",fontSize:12,lineHeight:1.6},children:h.message}),f&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 16px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f.piModels.length," models from ",f.endpoint]}),(0,n.jsx)("button",{onClick:()=>{if(f){if(u.size===f.piModels.length)return void p(new Set);p(new Set(f.piModels.map(e=>e.id)))}},style:{padding:"2px 8px",fontSize:11,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer"},children:u.size===f.piModels.length?"Clear":"Select all"})]}),(0,n.jsx)("div",{style:{flex:1,overflow:"auto"},children:f.piModels.map((e,t)=>{let r=f.models[t],i=u.has(e.id);return(0,n.jsxs)("label",{style:{display:"grid",gridTemplateColumns:"24px minmax(0, 1fr) 90px 90px 90px",gap:10,alignItems:"center",padding:"8px 16px",borderBottom:"1px solid rgba(127,127,127,0.12)",background:i?"var(--bg-subtle)":"transparent",cursor:"pointer"},children:[(0,n.jsx)("input",{type:"checkbox",checked:i,onChange:()=>{var t;return t=e.id,void p(e=>{let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r})},style:{width:14,height:14,accentColor:"var(--accent)"}}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.id}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r?.ownedBy??"unknown"})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:e.contextWindow}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:e.maxTokens}),(0,n.jsx)("span",{style:{fontSize:10,color:e.reasoning?"var(--accent)":"var(--text-dim)"},children:e.reasoning?"reasoning":""})]},e.id)})})]})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"10px 16px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:[v," selected"]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,n.jsx)("button",{onClick:r,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:"Cancel"}),(0,n.jsx)("button",{onClick:()=>{if(!f||!m)return;let n=o.trim().replace(/\/+$/,""),i=s.trim(),l=Object.entries(e).find(([,e])=>(e.baseUrl??"").replace(/\/+$/,"")===n&&(e.apiKey??"")===i),a=l?.[0]??d.trim(),c=e[a],p=new Map((c?.models??[]).map(e=>[e.id,e])),h=0;for(let e of f.piModels)u.has(e.id)&&!p.has(e.id)&&(p.set(e.id,e),h+=1);t(a,{...c??{},baseUrl:n,api:c?.api??"openai-completions",...i?{apiKey:i}:{},models:Array.from(p.values())},h),r()},disabled:!m,style:{padding:"6px 16px",background:m?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:6,color:m?"#fff":"var(--text-dim)",cursor:m?"pointer":"not-allowed",fontSize:13,fontWeight:600},children:"Import selected"})]})]})]})})}function rq({onClose:e,embedded:t=!1}){let[r,o]=(0,i.useState)({providers:{}}),[l,s]=(0,i.useState)(!0),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[x,g]=(0,i.useState)(!1),[f,v]=(0,i.useState)(null),[m,y]=(0,i.useState)([]),[b,j]=(0,i.useState)([]),[k,w]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),T=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>y(e.providers)).catch(()=>{})},[]),z=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>j(e.providers)).catch(()=>{})},[]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};o(t);let r=Object.keys(t.providers??{});r.length>0&&v({type:"provider",name:r[0]})}).catch(()=>o({providers:{}})).finally(()=>s(!1)),T(),z()},[T,z]);let L=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;r.providers?.[e];)e=`new-provider-${t++}`;o(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),v({type:"provider",name:e})},[r.providers]),I=(0,i.useCallback)((e,t)=>{o(r=>({...r,providers:{...r.providers??{},[e]:t}}))},[]),M=(0,i.useCallback)((e,t)=>{o(r=>{let n=Object.entries(r.providers??{}),i=n.findIndex(([t])=>t===e);return -1===i?r:(n[i]=[t,n[i][1]],{...r,providers:Object.fromEntries(n)})}),v(r=>r?"provider"===r.type&&r.name===e?{type:"provider",name:t}:"model"===r.type&&r.providerName===e?{...r,providerName:t}:r:r)},[]),R=(0,i.useCallback)(e=>{o(t=>{let r={...t.providers??{}};return delete r[e],{...t,providers:r}}),o(e=>{let t=Object.keys(e.providers??{});return v(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),W=(0,i.useCallback)(e=>{o(t=>{let r=t.providers?.[e]??{},n=[...r.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...r,models:n}}}}),o(t=>{let r=(t.providers?.[e]?.models?.length??1)-1;return v({type:"model",providerName:e,index:r}),t})},[]),E=(0,i.useCallback)((e,t,r)=>{o(n=>{let i=n.providers?.[e]??{},o=[...i.models??[]];return o[t]=r,{...n,providers:{...n.providers??{},[e]:{...i,models:o}}}})},[]),$=(0,i.useCallback)((e,t)=>{o(r=>{let n=r.providers?.[e]??{},i=[...n.models??[]];return i.splice(t,1),{...r,providers:{...r.providers??{},[e]:{...n,models:i.length?i:void 0}}}}),v({type:"provider",name:e})},[]),B=(0,i.useCallback)((e,t,r)=>{o(r=>({...r,providers:{...r.providers??{},[e]:t}})),v({type:"provider",name:e}),g(!1),u(null),h(`${r} model${1===r?"":"s"} imported. Click Save to write models.json.`)},[]),N=(0,i.useCallback)(async()=>{d(!0),u(null),h(null),g(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),t=await e.json();!e.ok||t.error?u(t.error??`HTTP ${e.status}`):(g(!0),setTimeout(()=>g(!1),2e3))}catch(e){u(String(e))}finally{d(!1)}},[r]),P=Object.entries(r.providers??{}),A=m.filter(e=>e.loggedIn),D=b.filter(e=>e.configured),H=(()=>{if(!f)return null;if("oauth"===f.type){let e=m.find(e=>e.id===f.providerId);return e?(0,n.jsx)(rU,{provider:e,onRefresh:T},e.id):null}if("apikey"===f.type){let e=b.find(e=>e.id===f.providerId);return e?(0,n.jsx)(r_,{provider:e,onRefresh:z},e.id):null}if("provider"===f.type){let e=r.providers?.[f.name];return e?(0,n.jsx)(rP,{name:f.name,provider:e,onChange:e=>I(f.name,e),onRename:e=>M(f.name,e),onDelete:()=>R(f.name)},f.name):null}let e=r.providers?.[f.providerName],t=e?.models?.[f.index];return t?(0,n.jsx)(rF,{providerName:f.providerName,provider:e,model:t,onChange:e=>E(f.providerName,f.index,e),onDelete:()=>$(f.providerName,f.index)},`${f.providerName}-${f.index}`):null})();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:t?{height:"100%",minHeight:0,display:"flex",alignItems:"stretch",justifyContent:"stretch"}:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:r=>{t||r.target!==r.currentTarget||e()},children:(0,n.jsxs)("div",{style:{width:t?"100%":860,height:t?"100%":"78vh",background:"var(--bg)",border:t?"none":"1px solid var(--border)",borderRadius:10*!t,display:"flex",flexDirection:"column",boxShadow:t?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[!t&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:"Models"}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.pi/agent/models.json"})]}),(0,n.jsx)("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:210,borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[A.map(e=>{let t=f?.type==="oauth"&&f.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>v({type:"oauth",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(rV,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),D.map(e=>{let t=f?.type==="apikey"&&f.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>v({type:"apikey",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(rV,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(A.length>0||D.length>0)&&P.length>0&&(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),l?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading…"}):P.map(([e,t])=>{let r=f?.type==="provider"&&f.name===e,i=t.models??[];return(0,n.jsxs)("div",{style:{marginBottom:2},children:[(0,n.jsxs)("div",{onClick:()=>v({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:r?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,r)=>{let i=f?.type==="model"&&f.providerName===e&&f.index===r;return(0,n.jsxs)("div",{onClick:()=>v({type:"model",providerName:e,index:r}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||"new model"}),t.reasoning&&(0,n.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},r)}),(0,n.jsx)("div",{onClick:t=>{t.stopPropagation(),W(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsx)("span",{style:{fontSize:11},children:"+ model"})})]},e)})]}),(0,n.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,n.jsx)("button",{onClick:()=>w(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:"+ Add provider"})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:l?null:H??(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:"Select a provider or model"})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[c?(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:c}):p?(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flex:1},children:p}):null,(0,n.jsx)("button",{onClick:e,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:"Cancel"}),(0,n.jsxs)("button",{onClick:N,disabled:a||x,style:{position:"relative",padding:"6px 16px",minWidth:92,background:x?"#16a34a":a?"var(--bg-panel)":"var(--accent)",border:"none",borderRadius:6,color:x?"#fff":a?"var(--text-muted)":"#fff",cursor:a||x?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:x?"saved-pop 0.45s ease":void 0},children:[x&&(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,n.jsx)("span",{children:x?"Saved":a?"Saving…":"Save"})]})]})]})}),k&&(0,n.jsx)(rJ,{oauthProviders:m,apiKeyProviders:b,onSelectOAuth:e=>v({type:"oauth",providerId:e}),onSelectApiKey:e=>v({type:"apikey",providerId:e}),onAddCustom:L,onDiscover:()=>C(!0),onClose:()=>w(!1)}),S&&(0,n.jsx)(rK,{existingProviders:r.providers??{},onImport:B,onClose:()=>C(!1)})]})}function rY(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function rG(e){let t=e.sourceInfo?.source,r=e.sourceInfo?.scope;return"user"===r||"user"===t?"global":"project"===r||"project"===t?"project":"path"}function rZ({enabled:e,loading:t,onToggle:r}){return(0,n.jsx)("button",{onClick:r,disabled:t,title:e?"Visible in model prompt — click to disable":"Hidden from model prompt — click to enable",style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function rX({skill:e,cwd:t,onToggle:r,toggling:i,saveError:o}){let l=rG(e),s=!e.disableModelInvocation;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===l?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===l?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:l}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===l&&e.startsWith(t)){let r=e.slice(t.length).replace(/^[/\\]/,"");return`./${r}`}return rY(e)}(e.filePath)}),(0,n.jsx)(rZ,{enabled:s,loading:i,onToggle:()=>r(e)}),o&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flexShrink:0},children:o})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,n.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function rQ({cwd:e,onInstalled:t}){let[r,o]=(0,i.useState)(""),[l,s]=(0,i.useState)([]),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[x,g]=(0,i.useState)(null),[f,v]=(0,i.useState)(new Set),[m,y]=(0,i.useState)("global"),b=(0,i.useRef)(null);(0,i.useEffect)(()=>{b.current?.focus()},[]);let j=(0,i.useCallback)(async e=>{if(e.trim()){d(!0),u(null),s([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),r=await t.json();if(r.error)return void u(r.error);s(r.results??[]),0===(r.results??[]).length&&u("No skills found")}catch(e){u(String(e))}finally{d(!1)}}},[]),k=(0,i.useCallback)(async r=>{h(r),g(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:r,scope:m,cwd:e})}),i=await n.json();if(!n.ok||i.error)return void g(i.error??`HTTP ${n.status}`);v(e=>new Set(e).add(r)),t()}catch(e){g(String(e))}finally{h(null)}},[t,m,e]),w="global"===m?"~/.pi/agent/skills/":`${rY(e)}/.pi/agent/skills/`;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:"Add Skill"}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,n.jsx)("input",{ref:b,value:r,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&j(r)},placeholder:"e.g. react, testing, deploy",style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,n.jsx)("button",{onClick:()=>j(r),disabled:a||!r.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--accent)",color:"#fff",cursor:a||!r.trim()?"not-allowed":"pointer",opacity:a||!r.trim()?.5:1,flexShrink:0},children:a?"Searching…":"Search"})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,n.jsx)("button",{onClick:()=>y(e),style:{padding:"3px 10px",border:"none",cursor:"pointer",background:m===e?"var(--bg-selected)":"none",color:m===e?"var(--text)":"var(--text-dim)",fontWeight:m===e?600:400,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",w]})]}),c&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:c}),x&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),l.length>0?(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:l.map(e=>{let t=f.has(e.package),r=p===e.package,i=e.package.indexOf("@"),o=i>-1?e.package.slice(0,i):e.package,l=i>-1?e.package.slice(i+1):null;return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??o}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,n.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,n.jsx)("button",{onClick:()=>!t&&!r&&k(e.package),disabled:t||r||null!==p,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:t||r||null!==p?"not-allowed":"pointer",background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":r?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:t?"✓ Installed":r?"Installing…":"Install"})]},e.package)})}):!c&&!a&&(0,n.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,n.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function r0({cwd:e,onClose:t,embedded:r=!1}){let[o,l]=(0,i.useState)([]),[s,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,x]=(0,i.useState)(new Set),[g,f]=(0,i.useState)(null),[v,m]=(0,i.useState)(!1),y=(0,i.useCallback)(()=>{a(!0),c(null),fetch(`/api/skills?cwd=${encodeURIComponent(e)}`).then(e=>e.json()).then(e=>{if(e.error)return void c(e.error);let t=e.skills??[];l(t),t.length>0&&!u&&p(t[0].filePath)}).catch(e=>c(String(e))).finally(()=>a(!1))},[e,u]);(0,i.useEffect)(()=>{y()},[e]);let b=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),f(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),n=await r.json();if(!r.ok||n.error)return void f(n.error??`HTTP ${r.status}`);l(r=>r.map(r=>r.filePath===e.filePath?{...r,disableModelInvocation:t}:r))}catch(e){f(String(e))}finally{x(t=>{let r=new Set(t);return r.delete(e.filePath),r})}},[]),j=o.find(e=>e.filePath===u)??null;return(0,n.jsx)("div",{style:r?{height:"100%",minHeight:0,display:"flex",alignItems:"stretch",justifyContent:"stretch"}:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{r||e.target!==e.currentTarget||t()},children:(0,n.jsxs)("div",{style:{width:r?"100%":860,height:r?"100%":"78vh",background:"var(--bg)",border:r?"none":"1px solid var(--border)",borderRadius:10*!r,display:"flex",flexDirection:"column",boxShadow:r?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[!r&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:"Skills"}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:rY(e)})]}),(0,n.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:210,borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:s?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading…"}):d?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:d}):0===o.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No skills found"}):(()=>{let e=[];for(let t of["project","global","path"]){let r=o.filter(e=>rG(e)===t);r.length>0&&e.push({label:t,skills:r})}return e.map(({label:e,skills:t})=>(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),t.map(e=>{let t=!v&&u===e.filePath,r=e.disableModelInvocation;return(0,n.jsxs)("div",{onClick:()=>{p(e.filePath),m(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:r?"var(--border)":"var(--accent)",boxShadow:r?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:t?600:400,color:r?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.filePath)})]},e))})()}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{onClick:()=>m(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:v?"var(--bg-selected)":"none",color:v?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{v||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{v||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),"Add skill"]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:v?(0,n.jsx)(rQ,{cwd:e,onInstalled:()=>{y()}}):s?null:j?(0,n.jsx)(rX,{skill:j,cwd:e,onToggle:b,toggling:h.has(j.filePath),saveError:g},j.filePath):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:"Select a skill"})})]}),(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:"Close"})})]})})}let r1=[{label:"30m",value:18e5},{label:"2h",value:72e5},{label:"6h",value:216e5},{label:"24h",value:864e5},{label:"48h",value:1728e5},{label:"Never",value:0}];function r2(e){return e?e.replace(/^\/(?:Users|home)\/[^/]+/,"~"):""}function r4(e){if(e<=0)return"never";let t=e/60/1e3;if(t<60)return`${Math.round(t)}m`;let r=t/60;return Number.isInteger(r)?`${r}h`:`${r.toFixed(1)}h`}function r5(e){return{id:"",language:e,displayName:"",command:"python"===e?"python3":"R",argsText:JSON.stringify("python"===e?["-u"]:["--slave","--vanilla"]),envText:"{}"}}function r6(e){return{id:e.id,language:e.language,displayName:e.displayName,command:e.command,argsText:JSON.stringify(e.args),envText:JSON.stringify(e.env,null,2)}}let r3={height:30,padding:"0 11px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,whiteSpace:"nowrap"},r8={width:"100%",minWidth:0,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)"};function r7({label:e,children:t}){return(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}function r9({cwd:e}){let[t,r]=(0,i.useState)("python"),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,x]=(0,i.useState)(null),[g,f]=(0,i.useState)([]),[v,m]=(0,i.useState)(null),[y,b]=(0,i.useState)("view"),[j,k]=(0,i.useState)(()=>r5("python")),[w,S]=(0,i.useState)(1728e5),[C,T]=(0,i.useState)(!1),z=(0,i.useCallback)(async()=>{a(!0),p(null);try{let r=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/plot-kernels${r}`),i=await n.json();if(!n.ok||i.error)throw Error(i.error??`HTTP ${n.status}`);l(i),f([]),x(null),m(e=>{if(e&&i.kernels.some(t=>t.id===e))return e;let r=i.kernels.find(e=>e.language===t&&e.isEffective);return r?.id??i.kernels.find(e=>e.language===t)?.id??null})}catch(e){p(e instanceof Error?e.message:String(e))}finally{a(!1)}},[e,t]);(0,i.useEffect)(()=>{z()},[z]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/settings").then(e=>e.ok?e.json():Promise.reject(Error(`HTTP ${e.status}`))).then(t=>{e||"number"!=typeof t.settings?.plotIdleTimeoutMs||S(t.settings.plotIdleTimeoutMs)}).catch(()=>{}),()=>{e=!0}},[]);let L=(0,i.useMemo)(()=>(o?.kernels??[]).filter(e=>e.language===t),[t,o?.kernels]),I=L.find(e=>e.id===v)??null;(0,i.useEffect)(()=>{if("new"===y)return void k(r5(t));let e=I??L.find(e=>e.isEffective)??L[0]??null;e?(v!==e.id&&m(e.id),k(r6(e)),b("view")):(m(null),k(r5(t)),b("new"))},[t,o?.kernels]);let M=(0,i.useCallback)(async(t,r)=>{c(r),p(null),x(null),f([]);try{let r=await fetch("/api/plot-kernels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,...t})}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);return l(n),f(n.errors??[]),n}catch(e){return p(e instanceof Error?e.message:String(e)),null}finally{c(null)}},[e]),R=(0,i.useCallback)(async e=>{let t=await M({action:"scan",..."all"===e?{}:{language:e}},"scan");t&&x(`Scan added ${t.added?.length??0} kernel${(t.added?.length??0)===1?"":"s"}${t.skipped?`, skipped ${t.skipped} existing`:""}.`)},[M]),W=(0,i.useCallback)(async e=>{await M({action:"select",language:e.language,kernelId:e.id},"select")&&x(`Selected ${e.displayName} for this project.`)},[M]),E=(0,i.useCallback)(async e=>{await M({action:"setDefault",language:e.language,kernelId:e.id},"default")&&x(`Set ${e.displayName} as global default.`)},[M]),$=(0,i.useCallback)(async()=>{let e=j.id.trim();if(!e)return void p("Kernel ID is required");try{let t=function(e){let t=JSON.parse(e.argsText||"[]"),r=JSON.parse(e.envText||"{}");if(!Array.isArray(t))throw Error("Args must be a JSON array");if(!r||"object"!=typeof r||Array.isArray(r))throw Error("Env must be a JSON object");return{language:e.language,command:e.command.trim(),displayName:e.displayName.trim(),args:t.map(e=>String(e)),env:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,String(t)]))}}(j);if(!t.command)throw Error("Command is required");if(!await M({action:"new"===y?"add":"edit",kernelId:e,kernel:t},"save"))return;m(e),b("view"),x("new"===y?"Kernel added.":"Kernel saved.")}catch(e){p(e instanceof Error?e.message:String(e))}},[j,y,M]),B=(0,i.useCallback)(async e=>{let r=await M({action:"delete",kernelId:e.id},"delete");if(!r)return;let n=r.kernels.find(e=>e.language===t&&e.isEffective)??r.kernels.find(e=>e.language===t)??null;m(n?.id??null),b(n?"view":"new"),x("Kernel deleted.")},[t,M]),N=()=>{b("new"),m(null),k(r5(t)),p(null),x(null)},P=(0,i.useCallback)(async e=>{S(e),T(!0),p(null);try{let t=await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({settings:{plotIdleTimeoutMs:e}})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);"number"==typeof r.settings?.plotIdleTimeoutMs&&(S(r.settings.plotIdleTimeoutMs),x(`Plot idle timeout set to ${r4(r.settings.plotIdleTimeoutMs)}.`))}catch(e){S(w),p(e instanceof Error?e.message:String(e))}finally{T(!1)}},[w]);return(0,n.jsxs)("div",{style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)",flexWrap:"wrap"},children:[(0,n.jsx)("div",{style:{display:"flex",padding:2,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)"},children:["python","r"].map(e=>{let i=t===e;return(0,n.jsx)("button",{type:"button",onClick:()=>r(e),style:{height:26,padding:"0 12px",border:"none",borderRadius:5,background:i?"var(--bg)":"transparent",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:i?600:500},children:"python"===e?"Python":"R"},e)})}),(0,n.jsxs)("button",{type:"button",onClick:()=>void R(t),disabled:!!d,style:{...r3,opacity:d?.55:1},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M21 12a9 9 0 0 1-15.3 6.4"}),(0,n.jsx)("path",{d:"M3 12A9 9 0 0 1 18.3 5.6"}),(0,n.jsx)("path",{d:"M18 2v4h4"}),(0,n.jsx)("path",{d:"M6 22v-4H2"})]}),"scan"===d?"Scanning...":`Scan ${"python"===t?"Python":"R"}`]}),(0,n.jsx)("button",{type:"button",onClick:()=>void R("all"),disabled:!!d,style:{...r3,opacity:d?.55:1},children:"Scan all"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginLeft:"auto"},children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:"Idle"}),(0,n.jsx)("div",{style:{display:"flex",padding:2,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)"},children:r1.map(e=>{let t=w===e.value;return(0,n.jsx)("button",{type:"button",onClick:()=>{t||P(e.value)},disabled:C,title:`Close inactive plot kernels after ${r4(e.value)}`,style:{height:24,padding:"0 8px",border:"none",borderRadius:5,background:t?"var(--bg)":"transparent",color:t?"var(--accent)":"var(--text-muted)",cursor:C?"default":"pointer",fontSize:11,fontWeight:t?700:500,opacity:C?.65:1},children:e.label},e.label)})})]}),(0,n.jsxs)("button",{type:"button",onClick:N,style:{...r3,marginLeft:"auto",color:"var(--accent)"},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),"Add kernel"]})]}),(u||h||g.length>0)&&(0,n.jsxs)("div",{style:{flexShrink:0,padding:"8px 16px",borderBottom:"1px solid var(--border)",fontSize:12,lineHeight:1.5},children:[u&&(0,n.jsx)("div",{style:{color:"#f87171"},children:u}),h&&(0,n.jsx)("div",{style:{color:"var(--text-muted)"},children:h}),g.map(e=>(0,n.jsx)("div",{style:{color:"rgba(234,179,8,0.95)"},children:e},e))]}),(0,n.jsxs)("div",{style:{flex:1,minHeight:0,display:"flex",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:290,flexShrink:0,borderRight:"1px solid var(--border)",background:"var(--bg-panel)",display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,n.jsxs)("div",{children:["Global: ",(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)",wordBreak:"break-all"},children:r2(o?.paths.global??"")})]}),e&&(0,n.jsxs)("div",{children:["Project: ",(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)",wordBreak:"break-all"},children:r2(o?.paths.project??"")})]}),!e&&(0,n.jsx)("div",{children:"Project selection requires an active cwd."})]}),(0,n.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"8px 6px"},children:s?(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--text-muted)",fontSize:12},children:"Loading..."}):0===L.length?(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--text-dim)",fontSize:12},children:"No kernels found"}):L.map(e=>{let t=v===e.id&&"new"!==y;return(0,n.jsxs)("button",{type:"button",onClick:()=>{m(e.id),b("view"),k(r6(e)),p(null),x(null)},style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"8px 9px",border:"none",borderRadius:6,background:t?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="transparent")},children:[(0,n.jsx)("span",{style:{width:8,height:8,borderRadius:"50%",background:e.isEffective?"var(--accent)":"var(--border)",flexShrink:0}}),(0,n.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("span",{style:{display:"block",color:"var(--text)",fontSize:12,fontWeight:t?600:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,n.jsx)("span",{style:{display:"block",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.id})]}),(e.isProjectSelected||e.isDefault)&&(0,n.jsxs)("span",{style:{flexShrink:0,display:"flex",gap:3},children:[e.isProjectSelected&&(0,n.jsx)("span",{title:"Project selected",style:{fontSize:9,color:"var(--accent)",border:"1px solid rgba(37,99,235,0.35)",borderRadius:4,padding:"1px 4px"},children:"P"}),e.isDefault&&(0,n.jsx)("span",{title:"Global default",style:{fontSize:9,color:"var(--text-muted)",border:"1px solid var(--border)",borderRadius:4,padding:"1px 4px"},children:"D"})]})]},e.id)})}),(0,n.jsxs)("div",{style:{padding:"8px 10px",borderTop:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11},children:["Last scan: ",function(e){if(!e)return"never";let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}(o?.scanCache?.lastScan)]})]}),(0,n.jsx)("div",{style:{flex:1,minWidth:0,minHeight:0,overflowY:"auto",padding:18},children:"view"===y&&I?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16,maxWidth:760},children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,n.jsx)("h3",{style:{margin:0,color:"var(--text)",fontSize:15,lineHeight:1.3},children:I.displayName}),I.isEffective&&(0,n.jsx)("span",{style:{fontSize:10,color:"var(--accent)",border:"1px solid rgba(37,99,235,0.35)",borderRadius:4,padding:"1px 5px"},children:"active"})]}),(0,n.jsx)("div",{style:{marginTop:5,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:I.id})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:12},children:[(0,n.jsx)(r7,{label:"Command",children:(0,n.jsx)("input",{readOnly:!0,value:I.command,style:{...r8,color:"var(--text-muted)"}})}),(0,n.jsx)(r7,{label:"Args",children:(0,n.jsx)("input",{readOnly:!0,value:JSON.stringify(I.args),style:{...r8,color:"var(--text-muted)"}})})]}),(0,n.jsx)(r7,{label:"Environment",children:(0,n.jsx)("textarea",{readOnly:!0,value:JSON.stringify(I.env,null,2),rows:5,style:{...r8,resize:"vertical",color:"var(--text-muted)"}})}),(0,n.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>e&&void W(I),disabled:!e||"select"===d,style:{...r3,background:e?"var(--accent)":"var(--bg-panel)",color:e?"#fff":"var(--text-dim)",opacity:"select"===d?.6:1},children:"Use for project"}),(0,n.jsx)("button",{type:"button",onClick:()=>void E(I),disabled:"default"===d,style:{...r3,opacity:"default"===d?.6:1},children:"Set default"}),(0,n.jsx)("button",{type:"button",onClick:()=>{b("edit"),m(I.id),k(r6(I)),p(null),x(null)},style:r3,children:"Edit"}),!I.id.startsWith("default-")&&(0,n.jsx)("button",{type:"button",onClick:()=>void B(I),disabled:"delete"===d,style:{...r3,color:"#f87171",opacity:"delete"===d?.6:1},children:"Delete"})]})]}):(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14,maxWidth:760},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[(0,n.jsx)("h3",{style:{margin:0,color:"var(--text)",fontSize:15},children:"new"===y?"Add Kernel":"Edit Kernel"}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:"python"===t?"Python":"R"})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:12},children:[(0,n.jsx)(r7,{label:"Kernel ID",children:(0,n.jsx)("input",{value:j.id,readOnly:"edit"===y,onChange:e=>k(t=>({...t,id:e.target.value})),placeholder:"python"===t?"my-python":"my-r",style:{...r8,color:"edit"===y?"var(--text-muted)":"var(--text)"}})}),(0,n.jsx)(r7,{label:"Display name",children:(0,n.jsx)("input",{value:j.displayName,onChange:e=>k(t=>({...t,displayName:e.target.value})),placeholder:"python"===t?"Python 3 (Project)":"R (Project)",style:r8})})]}),(0,n.jsx)(r7,{label:"Command",children:(0,n.jsx)("input",{value:j.command,onChange:e=>k(t=>({...t,command:e.target.value})),placeholder:"/usr/bin/python3",style:r8})}),(0,n.jsx)(r7,{label:"Args JSON",children:(0,n.jsx)("input",{value:j.argsText,onChange:e=>k(t=>({...t,argsText:e.target.value})),style:r8})}),(0,n.jsx)(r7,{label:"Env JSON",children:(0,n.jsx)("textarea",{value:j.envText,onChange:e=>k(t=>({...t,envText:e.target.value})),rows:6,style:{...r8,resize:"vertical"}})}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void $(),disabled:"save"===d,style:{...r3,background:"var(--accent)",borderColor:"var(--accent)",color:"#fff",opacity:"save"===d?.6:1},children:"save"===d?"Saving...":"Save"}),(0,n.jsx)("button",{type:"button",onClick:()=>{let e=I??L.find(e=>e.isEffective)??L[0]??null;e?(m(e.id),k(r6(e)),b("view")):N(),p(null)},style:r3,children:"Cancel"})]})]})})]})]})}function ne({checked:e,onChange:t}){return(0,n.jsx)("button",{type:"button",onClick:t,"aria-pressed":e,style:{width:44,height:24,borderRadius:999,border:"none",padding:0,cursor:"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",flexShrink:0},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?23:3,width:18,height:18,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function nt(){return(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.51a2 2 0 0 1 1-1.72l.15-.1a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function nr(e){return"models"===e?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"})]}):"skills"===e?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M12 2L2 7l10 5 10-5-10-5z"}),(0,n.jsx)("path",{d:"M2 17l10 5 10-5"}),(0,n.jsx)("path",{d:"M2 12l10 5 10-5"})]}):"generative-ui"===e?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1.5"}),(0,n.jsx)("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1.5"}),(0,n.jsx)("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1.5"}),(0,n.jsx)("path",{d:"M16 17h5"}),(0,n.jsx)("path",{d:"M18.5 14.5v5"})]}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M3 3v18h18"}),(0,n.jsx)("path",{d:"m19 9-5 5-4-4-3 3"}),(0,n.jsx)("path",{d:"M14 9h5v5"})]})}function nn({cwd:e,generativeUI:t,initialTab:r="models",onGenerativeUIToggle:o,onClose:l,onModelsChanged:s}){let[a,d]=(0,i.useState)(r);(0,i.useEffect)(()=>{d(r)},[r]),(0,i.useEffect)(()=>{let e=e=>{"Escape"===e.key&&l()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[l]);let c=[{id:"models",label:"Models",description:"~/.pi/agent/models.json",icon:nr("models")},{id:"skills",label:"Skills",description:e?"Project and global skills":"Select a project first",disabled:!e,icon:nr("skills")},{id:"generative-ui",label:"Generative UI",description:t?"Enabled":"Disabled",icon:nr("generative-ui")},{id:"plot-kernels",label:"Plot Kernels",description:e?"Python / R runtime":"Global kernels only",icon:nr("plot-kernels")}],u=c.find(e=>e.id===a)??c[0];return(0,n.jsx)("div",{className:"settings-dialog-backdrop",onClick:e=>{e.target===e.currentTarget&&l()},children:(0,n.jsxs)("div",{className:"settings-dialog-shell",children:[(0,n.jsxs)("div",{className:"settings-dialog-header",children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minWidth:0},children:[(0,n.jsx)("span",{style:{color:"var(--text-muted)",display:"flex",alignItems:"center",justifyContent:"center"},children:(0,n.jsx)(nt,{})}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:15,fontWeight:700,color:"var(--text)",lineHeight:1.25},children:"Settings"}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u.label})]})]}),(0,n.jsx)("button",{type:"button",onClick:l,title:"Close settings","aria-label":"Close settings",style:{width:30,height:30,border:"none",borderRadius:6,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:"x"})]}),(0,n.jsxs)("div",{className:"settings-dialog-body",children:[(0,n.jsx)("div",{className:"settings-dialog-tabs",children:c.map(e=>{let t=a===e.id;return(0,n.jsxs)("button",{type:"button",disabled:e.disabled,onClick:()=>d(e.id),className:"settings-dialog-tab",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)",opacity:e.disabled?.45:1,cursor:e.disabled?"not-allowed":"pointer"},onMouseEnter:r=>{t||e.disabled||(r.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="transparent")},children:[(0,n.jsx)("span",{style:{flexShrink:0,color:t?"var(--accent)":"currentColor",display:"flex"},children:e.icon}),(0,n.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("span",{style:{display:"block",fontSize:12,fontWeight:t?700:600,lineHeight:1.25},children:e.label}),(0,n.jsx)("span",{style:{display:"block",marginTop:2,fontSize:10,color:"var(--text-dim)",lineHeight:1.25,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.description})]})]},e.id)})}),(0,n.jsxs)("div",{className:"settings-dialog-panel",children:["models"===a&&(0,n.jsx)(rq,{embedded:!0,onClose:()=>{s?.(),l()}}),"skills"===a&&e&&(0,n.jsx)(r0,{cwd:e,embedded:!0,onClose:l}),"generative-ui"===a&&(0,n.jsx)("div",{style:{height:"100%",overflowY:"auto",padding:20},children:(0,n.jsxs)("div",{style:{maxWidth:720,display:"flex",flexDirection:"column",gap:18},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:18,padding:16,border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)",lineHeight:1.35},children:"Generative UI"}),(0,n.jsx)("div",{style:{marginTop:5,fontSize:12,color:"var(--text-muted)",lineHeight:1.55},children:"Render structured widgets and safe visual code blocks directly in chat when the assistant produces UI content."})]}),(0,n.jsx)(ne,{checked:t,onChange:o})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:12},children:[(0,n.jsxs)("div",{style:{padding:14,border:"1px solid var(--border)",borderRadius:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)",marginBottom:5},children:"When enabled"}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:"The agent prompt favors compact visual artifacts for icons, forms, dashboards, and small interactive UI when useful."})]}),(0,n.jsxs)("div",{style:{padding:14,border:"1px solid var(--border)",borderRadius:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)",marginBottom:5},children:"Fallback rendering"}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:"Assistant SVG and safe HTML code blocks can be previewed instead of appearing only as source text."})]})]})]})}),"plot-kernels"===a&&(0,n.jsx)(r9,{cwd:e})]})]})]})})}function ni({initialWidth:e,minWidth:t,maxWidth:r,storageKey:n,direction:o="right"}){let[l,s]=(0,i.useState)(e),[a,d]=(0,i.useState)(!1),c=(0,i.useRef)(e),u=(0,i.useCallback)(e=>{let i=Math.max(t,Math.min(r,e));s(i),c.current=i,document.documentElement.style.setProperty(n,`${i}px`)},[t,r,n]);(0,i.useEffect)(()=>{try{let e=localStorage.getItem(n);if(e){let n=parseInt(e,10);if(!isNaN(n)&&n>=t&&n<=r)return void u(n)}}catch{}u(c.current)},[n,t,r,u]);let p=(0,i.useCallback)(()=>{d(!0)},[]),h=(0,i.useCallback)(e=>{let t="left"===o?-1:1;u(c.current+e*t)},[u,o]);return{beginResize:p,endResize:(0,i.useCallback)(()=>{d(!1);try{localStorage.setItem(n,String(c.current))}catch{}},[n]),isResizing:a,resizeBy:h,width:l,widthRef:c}}function no(e){return!Number.isFinite(e)||e<=0?"0.0G":`${(e/1024/1024/1024).toFixed(1)}G`}function nl(){let e=(0,o.useRouter)(),t=(0,o.useSearchParams)(),{isDark:r,toggleTheme:l}=ep(),[s,a]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(0),[h,x]=(0,i.useState)(0),[g,f]=(0,i.useState)(0),[v,m]=(0,i.useState)(0),[y,b]=(0,i.useState)(!1),[j,k]=(0,i.useState)("models"),[w,S]=(0,i.useState)({generativeUI:!0,plotIdleTimeoutMs:1728e5}),[C,T]=(0,i.useState)(!0),z=ni({initialWidth:260,minWidth:180,maxWidth:500,storageKey:"--pi-sidebar-width"}),L=ni({initialWidth:500,minWidth:300,maxWidth:1200,storageKey:"--pi-right-panel-width",direction:"left"}),I=(0,i.useRef)(null),M=(0,i.useRef)(null),[R,W]=(0,i.useState)([]),[E,$]=(0,i.useState)(null),B=(0,i.useRef)(null),N=(0,i.useCallback)((e,t,r)=>{W(e),$(t),B.current=r},[]),P=(0,i.useCallback)(e=>{B.current?.(e)},[]),[A,D]=(0,i.useState)(null),H=(0,i.useRef)(null),[O,F]=(0,i.useState)(!1),[U,_]=(0,i.useState)(""),V=(0,i.useRef)(null),J=(0,i.useRef)(!1),K=(0,i.useCallback)(e=>{D(e)},[]);(0,i.useEffect)(()=>{F(!1)},[s?.id]);let q=(0,i.useCallback)(e=>e?e.name||e.firstMessage.slice(0,80)||e.id.slice(0,12):"",[]),Y=(0,i.useCallback)(()=>{s&&(J.current=!1,_(s.name||q(s)),F(!0),setTimeout(()=>V.current?.select(),0))},[q,s]),G=(0,i.useCallback)(async()=>{if(J.current){J.current=!1,F(!1);return}if(!s)return void F(!1);let e=U.trim(),t=q(s);if(F(!1),e!==(s.name??"")&&(s.name||e!==t))try{(await fetch(`/api/sessions/${encodeURIComponent(s.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})})).ok&&(a(t=>t&&t.id===s.id?{...t,name:e}:t),p(e=>e+1))}catch{}},[q,s,U]),Z=(0,i.useCallback)(e=>{"Enter"===e.key?(e.preventDefault(),G()):"Escape"===e.key&&(J.current=!0,F(!1))},[G]);(0,i.useEffect)(()=>{let e=!1;return fetch("/api/settings").then(e=>e.ok?e.json():null).then(t=>{e||S(e=>({generativeUI:"boolean"==typeof t?.settings?.generativeUI?t.settings.generativeUI:e.generativeUI,plotIdleTimeoutMs:"number"==typeof t?.settings?.plotIdleTimeoutMs?t.settings.plotIdleTimeoutMs:e.plotIdleTimeoutMs}))}).catch(()=>{}),()=>{e=!0}},[]);let X=(0,i.useCallback)(()=>{let e=!w.generativeUI;S(t=>({...t,generativeUI:e})),fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({settings:{generativeUI:e}})}).then(e=>e.ok?e.json():Promise.reject(Error(`HTTP ${e.status}`))).then(e=>{S(t=>({...t,..."boolean"==typeof e.settings?.generativeUI?{generativeUI:e.settings.generativeUI}:{},..."number"==typeof e.settings?.plotIdleTimeoutMs?{plotIdleTimeoutMs:e.settings.plotIdleTimeoutMs}:{}}))}).catch(()=>S(e=>({...e,generativeUI:!e.generativeUI})))},[w.generativeUI]),[Q,ee]=(0,i.useState)(null),et=(0,i.useCallback)(e=>{ee(e)},[]),[er,en]=(0,i.useState)(null),eo=(0,i.useCallback)(e=>{en(e)},[]),[el,es]=(0,i.useState)(null),[ea,ed]=(0,i.useState)(null),ec=(0,i.useCallback)(e=>{es(t=>t===e?null:e)},[]);(0,i.useEffect)(()=>{if(!el||!M.current)return;let e=()=>{let e=M.current.getBoundingClientRect();ed({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(M.current),()=>t.disconnect()},[el]);let[eu,eh]=(0,i.useState)([]),[ex,eg]=(0,i.useState)("report"),[ef,ev]=(0,i.useState)(!1),[em,ey]=(0,i.useState)(0),eb=(0,i.useCallback)(e=>{I.current?.insertText("`"+e+"`")},[]),[ej]=(0,i.useState)(()=>t.get("session")),[ek,ew]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(()=>!t.get("session")),eT=(0,i.useRef)(!1),ez=(0,i.useCallback)(t=>{ew(t),t&&!eT.current&&(a(e=>e&&e.cwd!==t?null:e),c(e=>e&&e!==t?null:e),x(e=>e+1),f(e=>e+1),W([]),$(null),D(null),es(null),e.replace("/",{scroll:!1}))},[e]),eL=(0,i.useCallback)((t,r=!1)=>{c(null),ew(t.cwd),a(t),x(e=>e+1),D(null),eC(!0),r&&(eT.current=!0,setTimeout(()=>{eT.current=!1},0)),r||e.replace(`?session=${encodeURIComponent(t.id)}`,{scroll:!1})},[e]),eI=(0,i.useCallback)((t,r)=>{a(null),c(r),ew(r),x(e=>e+1),W([]),$(null),D(null),es(null),e.replace("/",{scroll:!1})},[e]),eM=(0,i.useCallback)(t=>{c(null),ew(t.cwd),a(t),p(e=>e+1),e.replace(`?session=${encodeURIComponent(t.id)}`,{scroll:!1})},[e]),eR=(0,i.useCallback)(()=>{p(e=>e+1),f(e=>e+1)},[]),eW=(0,i.useCallback)(t=>{p(e=>e+1),x(e=>e+1),c(null),a(e=>({...e??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:t})),e.replace(`?session=${encodeURIComponent(t)}`,{scroll:!1})},[e]),eE=(0,i.useCallback)(()=>{eC(!0)},[]),e$=(0,i.useCallback)(t=>{if(p(e=>e+1),s?.id===t){let t=s.cwd;a(null),c(t??null),x(e=>e+1),W([]),$(null),D(null),es(null),e.replace("/",{scroll:!1})}},[s,e]),eB=(0,i.useCallback)((e,t)=>{let r=`file:${e}`;eh(n=>n.find(e=>e.id===r)?n:[...n,{id:r,label:t,filePath:e}]),eg(r),ev(!0)},[]),eN=(0,i.useCallback)(e=>{"report"!==e&&(eh(t=>t.filter(t=>t.id!==e)),eg(t=>{if(t!==e)return t;let r=eu.filter(t=>t.id!==e);return r.length>0?r[r.length-1].id:"report"}))},[eu]),eP=d??(null===s&&ek?ek:null),eA=null!==s||null!==eP,eD=eS&&!eA,eH=[{id:"report",label:"Report",closable:!1,icon:"report"},...eu],eO=eu.find(e=>e.id===ex)??null,eF=s?q(s):eP?"New chat":"No session",eU=s?.cwd??eP??ek??"",e_=eU?eU.replace(/\/+$/,"").split(/[\\/]/).filter(Boolean).pop()||eU:"",eV=ek??s?.cwd??d??null,eJ=(0,i.useCallback)((e="models")=>{k(e),b(!0)},[]),[eK,eq]=(0,i.useState)(null),[eY,eG]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)(null),eQ=`${s?.id??""}|${eV??""}`,e0=eK?.totalBytes??0,e1=eK?.currentSessionBytes??0,e2=eK?.projects??{},e4=(0,i.useCallback)(async()=>{let e=new URLSearchParams;eV&&e.set("cwd",eV),s?.id&&e.set("sessionId",s.id);try{let t=await fetch(`/api/plot-kernels/status${e.toString()?`?${e}`:""}`),r=await t.json();if(!t.ok||!("totalBytes"in r)||!("kernels"in r))throw Error(r.error??`HTTP ${t.status}`);eq(r),eG(null)}catch(e){eG(e instanceof Error?e.message:String(e))}},[s?.id,eV]);(0,i.useEffect)(()=>{let e=!1,t=async()=>{await e4(),e||(r=window.setTimeout(t,"plot"===el?3e3:8e3))},r=window.setTimeout(t,0);return()=>{e=!0,window.clearTimeout(r)}},[el,e4,eQ]);let e5=(0,i.useCallback)(async()=>{if(s?.id&&!eZ){eX("all"),eG(null);try{let e=await fetch("/api/plot-kernels/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:s.id})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);window.setTimeout(()=>{e4()},600)}catch(e){eG(e instanceof Error?e.message:String(e))}finally{eX(null)}}},[e4,eZ,s?.id]),e6=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ei,{selectedSessionId:s?.id??null,onSelectSession:eL,onNewSession:eI,initialSessionId:ej,onInitialRestoreDone:eE,refreshKey:u,onSessionDeleted:e$,selectedCwd:s?.cwd??d??ek??null,onCwdChange:ez,onOpenFile:eB,explorerRefreshKey:g,onAtMention:eb,projectPlotMemory:e2}),(0,n.jsx)("div",{style:{padding:"8px",flexShrink:0},children:(0,n.jsxs)("button",{type:"button",onClick:()=>eJ("models"),title:"Settings",style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,height:34,padding:"0 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0},children:[(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.51a2 2 0 0 1 1-1.72l.15-.1a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"})]}),(0,n.jsx)("span",{children:"Settings"})]}),(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:5,color:w.generativeUI?"var(--accent)":"var(--text-dim)",fontSize:10},children:["UI ",w.generativeUI?"on":"off"]})]})})]});return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{display:"flex",height:"100dvh",overflow:"hidden",background:"var(--bg)"},children:[(0,n.jsx)("div",{className:"sidebar-overlay-backdrop",onClick:()=>T(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!C,pointerEvents:C?"auto":"none",transition:"opacity 0.25s ease"}}),(0,n.jsx)("div",{className:`sidebar-container${C?" sidebar-open":" sidebar-closed"}`,style:{background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,zIndex:200,width:C?z.width:0,minWidth:C?z.width:0,transition:C||z.isResizing?"none":void 0},children:e6}),C&&(0,n.jsx)(rs,{side:"right",ariaLabel:"Resize sidebar",onResizeStart:z.beginResize,onResize:z.resizeBy,onResizeEnd:z.endResize}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,n.jsxs)("div",{ref:M,style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,borderBottom:"1px solid var(--border)",height:48,padding:"0 8px",background:"var(--bg)"},children:[(0,n.jsx)("button",{onClick:()=>T(e=>!e),title:C?"Hide sidebar":"Show sidebar",style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-panel)"},children:C?(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,n.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]}):(0,n.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,n.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,n.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{minWidth:0,display:"flex",alignItems:"center",gap:6},children:O&&s?(0,n.jsx)("input",{ref:V,value:U,onChange:e=>_(e.target.value),onKeyDown:Z,onBlur:()=>void G(),style:{width:"min(360px, 34vw)",height:28,boxSizing:"border-box",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",padding:"0 8px",fontSize:13,fontWeight:500,outline:"none"}}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{title:eF,style:{minWidth:0,maxWidth:"min(420px, 36vw)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:eA?"var(--text)":"var(--text-muted)",fontSize:14,fontWeight:600,lineHeight:1.2},children:eF}),s&&(0,n.jsx)("button",{type:"button",onClick:Y,title:"Rename session",style:{width:22,height:22,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="transparent"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M12 20h9"}),(0,n.jsx)("path",{d:"M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"})]})})]})}),e_&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12,flexShrink:0},children:"/"}),(0,n.jsx)("span",{title:eU||e_,style:{minWidth:0,maxWidth:"min(280px, 24vw)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontSize:12,lineHeight:1.2},children:e_})]})]}),eA&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,height:28,flexShrink:0},children:[(0,n.jsx)(ru,{tree:R,activeLeafId:E,onLeafChange:P,inline:!0,containerRef:M,open:"branches"===el,onToggle:()=>ec("branches"),hasSession:!!s}),(0,n.jsxs)("button",{ref:H,onClick:()=>ec("system"),style:{display:"flex",alignItems:"center",gap:6,height:28,padding:"0 9px",background:"system"===el?"var(--bg-selected)":"var(--bg-panel)",border:`1px solid ${"system"===el?"rgba(37,99,235,0.45)":"var(--border)"}`,borderRadius:7,cursor:"pointer",color:"system"===el?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="system"===el?"var(--text)":"var(--text-muted)",e.currentTarget.style.background="system"===el?"var(--bg-selected)":"var(--bg-panel)"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:A?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,n.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,n.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,n.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),(0,n.jsx)("span",{children:"System"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>ec("plot"),title:`Plot kernels: ${no(e0)}`,style:{display:"flex",alignItems:"center",gap:6,height:28,padding:"0 9px",background:"plot"===el?"var(--bg-selected)":e0>0?"rgba(37,99,235,0.08)":"var(--bg-panel)",border:`1px solid ${"plot"===el||e0>0?"rgba(37,99,235,0.45)":"var(--border)"}`,borderRadius:7,cursor:"pointer",color:e0>0?"var(--accent)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s",fontVariantNumeric:"tabular-nums"},onMouseEnter:e=>{e.currentTarget.style.color=e0>0?"var(--accent)":"var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=e0>0?"var(--accent)":"var(--text-muted)",e.currentTarget.style.background="plot"===el?"var(--bg-selected)":e0>0?"rgba(37,99,235,0.08)":"var(--bg-panel)"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M4 19V5"}),(0,n.jsx)("path",{d:"M4 19h16"}),(0,n.jsx)("path",{d:"m7 16 3-5 4 3 4-7"})]}),(0,n.jsx)("span",{children:"Plot"}),e0>0&&(0,n.jsx)("span",{children:no(e0)})]})]}),eA&&(Q||er)&&(()=>{let e=Q?.tokens,t=Q?.cost??0,r=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),i=t>0?t>=.01?`$${t.toFixed(2)}`:"<$0.01":null,o="var(--text-muted)",l=null;if(er?.contextWindow){let e=er.percent;null!==e&&e>90?o="#ef4444":null!==e&&e>70&&(o="rgba(234,179,8,0.95)"),l=null!==e?`${e.toFixed(0)}% / ${r(er.contextWindow)}`:`? / ${r(er.contextWindow)}`}let s=[];if(e&&(s.push(`in: ${e.input.toLocaleString()}`),s.push(`out: ${e.output.toLocaleString()}`),s.push(`cache read: ${e.cacheRead.toLocaleString()}`),s.push(`cache write: ${e.cacheWrite.toLocaleString()}`),t>0&&s.push(`cost: $${t.toFixed(4)}`)),er?.contextWindow){let e=er.percent;s.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${er.contextWindow.toLocaleString()} tokens`)}let a=s.join(" | ");return(0,n.jsxs)("div",{title:a,style:{display:"flex",alignItems:"center",gap:10,padding:"0 8px",height:28,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:"default",fontVariantNumeric:"tabular-nums"},children:[e&&e.input>0&&(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,n.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),r(e.input)]}),e&&e.output>0&&(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,n.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),r(e.output)]}),e&&e.cacheRead>0&&(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M8.5 5a3.5 3.5 0 1 1-1-2.45"}),(0,n.jsx)("polyline",{points:"6.5 1.5 8.5 2.5 7.5 4.5"})]}),r(e.cacheRead)]}),i&&(0,n.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text)",fontWeight:500},children:i}),l&&(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:o},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M1 9 L1 5 Q1 1 5 1 Q9 1 9 5 L9 9"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"9",y2:"9"})]}),l]})]})})(),(0,n.jsx)("button",{type:"button",onClick:X,title:`生成式 UI: ${w.generativeUI?"on":"off"}`,style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:28,padding:0,background:w.generativeUI?"var(--bg-selected)":"var(--bg-panel)",border:`1px solid ${w.generativeUI?"rgba(37,99,235,0.45)":"var(--border)"}`,borderRadius:7,color:w.generativeUI?"var(--accent)":"var(--text-muted)",cursor:"pointer",transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color=w.generativeUI?"var(--accent)":"var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=w.generativeUI?"var(--accent)":"var(--text-muted)",e.currentTarget.style.background=w.generativeUI?"var(--bg-selected)":"var(--bg-panel)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1.5"}),(0,n.jsx)("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1.5"}),(0,n.jsx)("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1.5"}),(0,n.jsx)("path",{d:"M16 17h5"}),(0,n.jsx)("path",{d:"M18.5 14.5v5"})]})}),(0,n.jsx)("button",{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();l({x:t.left+t.width/2,y:t.top+t.height/2})},title:r?"Switch to light mode":"Switch to dark mode","aria-label":r?"Switch to light mode":"Switch to dark mode","aria-pressed":r,style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:28,padding:0,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-panel)"},children:r?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"5"}),(0,n.jsx)("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),(0,n.jsx)("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),(0,n.jsx)("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),(0,n.jsx)("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),(0,n.jsx)("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),(0,n.jsx)("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),(0,n.jsx)("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),(0,n.jsx)("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]}):(0,n.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}),(0,n.jsx)("button",{onClick:()=>ev(e=>!e),title:ef?"Hide report panel":"Show report panel",style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:28,padding:0,background:ef?"var(--bg-selected)":"var(--bg-panel)",border:`1px solid ${ef?"rgba(37,99,235,0.45)":"var(--border)"}`,borderRadius:7,color:ef?"var(--accent)":"var(--text-muted)",cursor:"pointer",transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color=ef?"var(--accent)":"var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=ef?"var(--accent)":"var(--text-muted)",e.currentTarget.style.background=ef?"var(--bg-selected)":"var(--bg-panel)"},children:(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,n.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})}),el&&ea&&(0,n.jsxs)("div",{style:{position:"fixed",top:ea.top,left:ea.left,width:ea.width,zIndex:500},children:["system"===el&&(0,n.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:A?(0,n.jsx)("div",{style:{maxHeight:"min(600px, 75vh)",overflowY:"auto",padding:"12px 16px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",fontFamily:"var(--font-mono)"},children:A}):""===A?(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"System prompt is empty (tools are disabled)"}):(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"Send a message to load the system prompt"})}),"plot"===el&&(0,n.jsxs)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16,flexWrap:"wrap"},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:"Plot Kernels"}),(0,n.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.45},children:["Total memory ",no(e0),e1>0?` \xb7 current chat ${no(e1)}`:""," \xb7 ","idle timeout ",function(e){if(e<=0)return"never";let t=e/60/60/1e3;return t>=24&&Number.isInteger(t/24)?`${t/24}d`:Number.isInteger(t)?`${t}h`:`${Math.round(e/60/1e3)}m`}(w.plotIdleTimeoutMs)]})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>eJ("plot-kernels"),style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:"Settings"}),(0,n.jsx)("button",{type:"button",onClick:()=>void e5(),disabled:!s?.id||!!eZ,style:{height:28,padding:"0 10px",border:"1px solid rgba(248,113,113,0.45)",borderRadius:6,background:"var(--bg)",color:s?.id?"#f87171":"var(--text-dim)",cursor:s?.id&&!eZ?"pointer":"not-allowed",fontSize:12,opacity:eZ?.65:1},children:"all"===eZ?"Releasing...":"Release current chat"})]})]}),eY&&(0,n.jsx)("div",{style:{marginTop:10,color:"#f87171",fontSize:12,lineHeight:1.45},children:eY}),(0,n.jsx)("div",{style:{marginTop:12,display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:10},children:["python","r"].map(e=>{let t=(eK?.kernels??[]).filter(t=>t.language===e),r=t.reduce((e,t)=>e+t.rssBytes,0);return(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg)",padding:10,minWidth:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:650,color:"var(--text)"},children:"python"===e?"Python":"R"}),(0,n.jsx)("div",{style:{fontSize:12,color:r>0?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:no(r)})]}),(0,n.jsx)("div",{style:{marginTop:6,color:"var(--text-dim)",fontSize:11,lineHeight:1.45},children:t.length>0?`${t.length} process${1===t.length?"":"es"}`:"No warm kernel detected"}),t.length>0&&(0,n.jsx)("div",{style:{marginTop:7,display:"flex",flexDirection:"column",gap:4},children:t.slice(0,3).map(e=>(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,n.jsxs)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["pid ",e.pid]}),(0,n.jsx)("span",{style:{flexShrink:0},children:no(e.rssBytes)})]},`${e.pid}:${e.language}`))})]},e)})}),(0,n.jsx)("div",{style:{marginTop:9,color:"var(--text-dim)",fontSize:11,lineHeight:1.45},children:"Memory is estimated from OS processes; per-variable memory will appear after warmplot exposes kernel object telemetry."})]})]})]}),(0,n.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:eA?(0,n.jsx)(tw,{session:s,newSessionCwd:eP,onAgentEnd:eR,onSessionCreated:eM,onSessionForked:eW,modelsRefreshKey:v,chatInputRef:I,onBranchDataChange:N,onSystemPromptChange:K,onSessionStatsChange:et,onContextUsageChange:eo,onReportUpdated:()=>ey(e=>e+1),generativeUI:w.generativeUI},h):eD?ek?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:"Select a session from the sidebar"}):(0,n.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,n.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,n.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,n.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:"Get Started"}),(0,n.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),"Select a project directory from the sidebar",(0,n.jsx)("br",{}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),"Add models via the ",(0,n.jsx)("strong",{style:{color:"var(--text)"},children:"Models"})," button at the bottom"]})]})]}):null})]}),ef&&(0,n.jsx)(rs,{side:"left",ariaLabel:"Resize right panel",onResizeStart:L.beginResize,onResize:L.resizeBy,onResizeEnd:L.endResize}),(0,n.jsxs)("div",{className:`right-panel-container${ef?" right-panel-open":" right-panel-closed"}`,style:{display:ef?"flex":"none",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,width:L.width,minWidth:L.width,transition:L.isResizing?"none":void 0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",height:36},children:[(0,n.jsxs)("button",{type:"button",className:"right-panel-back-button",onClick:()=>ev(!1),title:"Back to chat","aria-label":"Back to chat",style:{height:36,padding:"0 10px",border:"none",borderRight:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,alignItems:"center",gap:6,flexShrink:0},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"19",y1:"12",x2:"5",y2:"12"}),(0,n.jsx)("polyline",{points:"12 19 5 12 12 5"})]}),(0,n.jsx)("span",{children:"Chat"})]}),(0,n.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,n.jsx)(ra,{tabs:eH,activeTabId:ex,onSelectTab:eg,onCloseTab:eN})})]}),(0,n.jsx)("div",{style:{flex:1,overflow:"hidden"},children:"report"===ex?(0,n.jsx)(ro,{sessionId:s?.id??null,cwd:s?.cwd??ek??void 0,refreshKey:em,onOpenFile:eB}):eO?.filePath?eO.filePath.startsWith("__")?(0,n.jsx)(rn,{filePath:eO.filePath}):(0,n.jsx)(t9,{filePath:eO.filePath,cwd:ek??void 0,onOpenFile:eB}):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:"No file open"})})]})]}),y&&(0,n.jsx)(nn,{cwd:eV,generativeUI:w.generativeUI,initialTab:j,onGenerativeUIToggle:X,onModelsChanged:()=>m(e=>e+1),onClose:()=>{b(!1),m(e=>e+1)}})]})}},51564:(e,t,r)=>{Promise.resolve().then(r.bind(r,46760))}},e=>{e.O(0,[6079,7355,8441,3794,7358],()=>e(e.s=51564)),_N_E=e.O()}]);