@calmabacus/pi-web 1.2.8 → 1.2.9

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 (267) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +13 -11
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/required-server-files.js +1 -1
  5. package/.next/required-server-files.json +1 -1
  6. package/.next/routes-manifest.json +14 -0
  7. package/.next/server/app/_global-error/page.js +2 -2
  8. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/server/app/_global-error.html +1 -1
  10. package/.next/server/app/_global-error.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/server/app/_not-found/page.js +1 -1
  15. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  16. package/.next/server/app/_not-found.html +1 -1
  17. package/.next/server/app/_not-found.rsc +4 -4
  18. package/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
  19. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
  20. package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
  21. package/.next/server/app/api/agent/[id]/bash-output/route.js +1 -1
  22. package/.next/server/app/api/agent/[id]/events/route.js +1 -1
  23. package/.next/server/app/api/agent/[id]/lease/route.js +1 -1
  24. package/.next/server/app/api/agent/[id]/route.js +1 -1
  25. package/.next/server/app/api/agent/new/route.js +1 -1
  26. package/.next/server/app/api/agent/running/route.js +1 -1
  27. package/.next/server/app/api/app-update/route.js +1 -1
  28. package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
  29. package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
  30. package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
  31. package/.next/server/app/api/auth/providers/route.js +1 -1
  32. package/.next/server/app/api/cwd/browse/route.js +1 -1
  33. package/.next/server/app/api/cwd/validate/route.js +1 -1
  34. package/.next/server/app/api/default-cwd/route.js +1 -1
  35. package/.next/server/app/api/file-index/route.js +1 -1
  36. package/.next/server/app/api/files/[...path]/route.js +1 -1
  37. package/.next/server/app/api/git/diff/route.js +2 -2
  38. package/.next/server/app/api/git/status/route.js +1 -1
  39. package/.next/server/app/api/home/route.js +1 -1
  40. package/.next/server/app/api/image-generation/route.js +1 -1
  41. package/.next/server/app/api/image-generation/settings/connections/route.js +1 -1
  42. package/.next/server/app/api/image-generation/settings/route.js +1 -1
  43. package/.next/server/app/api/models/route.js +1 -1
  44. package/.next/server/app/api/models-config/catalog/route.js +1 -1
  45. package/.next/server/app/api/models-config/discover/route.js +1 -1
  46. package/.next/server/app/api/models-config/picker/route.js +1 -1
  47. package/.next/server/app/api/models-config/route.js +1 -1
  48. package/.next/server/app/api/models-config/runtime/route.js +1 -1
  49. package/.next/server/app/api/models-config/test/route.js +1 -1
  50. package/.next/server/app/api/plugins/check/route.js +1 -1
  51. package/.next/server/app/api/plugins/route.js +1 -1
  52. package/.next/server/app/api/project-overrides/route.js +1 -0
  53. package/.next/server/app/api/project-overrides/route.js.nft.json +1 -0
  54. package/.next/server/app/api/project-overrides/route_client-reference-manifest.js +1 -0
  55. package/.next/server/app/api/project-trust/route.js +1 -1
  56. package/.next/server/app/api/projects/route.js +1 -1
  57. package/.next/server/app/api/push/config/route.js +1 -1
  58. package/.next/server/app/api/push/subscribe/route.js +1 -1
  59. package/.next/server/app/api/sessions/[id]/auto-name/route.js +2 -2
  60. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  61. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
  62. package/.next/server/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route.js +1 -1
  63. package/.next/server/app/api/sessions/[id]/export/route.js +2 -2
  64. package/.next/server/app/api/sessions/[id]/outline/route.js +1 -1
  65. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  66. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  67. package/.next/server/app/api/sessions/[id]/subagent-usage/route.js +1 -0
  68. package/.next/server/app/api/sessions/[id]/subagent-usage/route.js.nft.json +1 -0
  69. package/.next/server/app/api/sessions/[id]/subagent-usage/route_client-reference-manifest.js +1 -0
  70. package/.next/server/app/api/sessions/route.js +1 -1
  71. package/.next/server/app/api/sessions/search/route.js +1 -1
  72. package/.next/server/app/api/skills/check/route.js +1 -1
  73. package/.next/server/app/api/skills/check/route.js.nft.json +1 -1
  74. package/.next/server/app/api/skills/install/route.js +1 -1
  75. package/.next/server/app/api/skills/route.js +2 -2
  76. package/.next/server/app/api/skills/route.js.nft.json +1 -1
  77. package/.next/server/app/api/skills/search/route.js +1 -1
  78. package/.next/server/app/api/skills/update/route.js +1 -1
  79. package/.next/server/app/api/skills/update/route.js.nft.json +1 -1
  80. package/.next/server/app/api/subagents/[id]/route.js +1 -1
  81. package/.next/server/app/api/subagents/profiles/route.js +1 -1
  82. package/.next/server/app/api/subagents/settings/route.js +1 -1
  83. package/.next/server/app/api/terminal/[id]/events/route.js +1 -1
  84. package/.next/server/app/api/terminal/[id]/route.js +1 -1
  85. package/.next/server/app/api/terminal/route.js +1 -1
  86. package/.next/server/app/api/tools/settings/route.js +1 -1
  87. package/.next/server/app/api/usage/route.js +1 -1
  88. package/.next/server/app/api/web-auth/route.js +1 -1
  89. package/.next/server/app/api/worktrees/route.js +1 -1
  90. package/.next/server/app/index.html +1 -1
  91. package/.next/server/app/index.rsc +7 -7
  92. package/.next/server/app/index.segments/__PAGE__.segment.rsc +7 -7
  93. package/.next/server/app/index.segments/_full.segment.rsc +7 -7
  94. package/.next/server/app/index.segments/_tree.segment.rsc +4 -4
  95. package/.next/server/app/login/page.js +2 -2
  96. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  97. package/.next/server/app/login.html +1 -1
  98. package/.next/server/app/login.rsc +5 -5
  99. package/.next/server/app/login.segments/_full.segment.rsc +5 -5
  100. package/.next/server/app/login.segments/_tree.segment.rsc +3 -3
  101. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +5 -5
  102. package/.next/server/app/manifest.webmanifest/route.js +2 -2
  103. package/.next/server/app/page.js +23 -22
  104. package/.next/server/app/page_client-reference-manifest.js +1 -1
  105. package/.next/server/app-paths-manifest.json +13 -11
  106. package/.next/server/chunks/2243.js +1 -1
  107. package/.next/server/chunks/402.js +3 -2
  108. package/.next/server/chunks/4020.js +1 -0
  109. package/.next/server/chunks/6429.js +8 -6
  110. package/.next/server/chunks/7147.js +1 -1
  111. package/.next/server/middleware-build-manifest.js +1 -1
  112. package/.next/server/middleware.js +4 -4
  113. package/.next/server/pages/404.html +1 -1
  114. package/.next/server/pages/500.html +1 -1
  115. package/.next/static/6f_3UIpNmHjU9Xn8SsAAi/_buildManifest.js +1 -0
  116. package/.next/static/chunks/2981-5abf1fdfdb963718.js +1 -0
  117. package/.next/static/chunks/app/_global-error/page-be5d61c3d2d00f10.js +1 -0
  118. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-be5d61c3d2d00f10.js +1 -0
  119. package/.next/static/chunks/app/api/agent/[id]/events/route-be5d61c3d2d00f10.js +1 -0
  120. package/.next/static/chunks/app/api/agent/[id]/lease/route-be5d61c3d2d00f10.js +1 -0
  121. package/.next/static/chunks/app/api/agent/[id]/route-be5d61c3d2d00f10.js +1 -0
  122. package/.next/static/chunks/app/api/agent/new/route-be5d61c3d2d00f10.js +1 -0
  123. package/.next/static/chunks/app/api/agent/running/route-be5d61c3d2d00f10.js +1 -0
  124. package/.next/static/chunks/app/api/app-update/route-be5d61c3d2d00f10.js +1 -0
  125. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-be5d61c3d2d00f10.js +1 -0
  126. package/.next/static/chunks/app/api/auth/login/[provider]/route-be5d61c3d2d00f10.js +1 -0
  127. package/.next/static/chunks/app/api/auth/logout/[provider]/route-be5d61c3d2d00f10.js +1 -0
  128. package/.next/static/chunks/app/api/auth/providers/route-be5d61c3d2d00f10.js +1 -0
  129. package/.next/static/chunks/app/api/cwd/browse/route-be5d61c3d2d00f10.js +1 -0
  130. package/.next/static/chunks/app/api/cwd/validate/route-be5d61c3d2d00f10.js +1 -0
  131. package/.next/static/chunks/app/api/default-cwd/route-be5d61c3d2d00f10.js +1 -0
  132. package/.next/static/chunks/app/api/file-index/route-be5d61c3d2d00f10.js +1 -0
  133. package/.next/static/chunks/app/api/files/[...path]/route-be5d61c3d2d00f10.js +1 -0
  134. package/.next/static/chunks/app/api/git/diff/route-be5d61c3d2d00f10.js +1 -0
  135. package/.next/static/chunks/app/api/git/status/route-be5d61c3d2d00f10.js +1 -0
  136. package/.next/static/chunks/app/api/home/route-be5d61c3d2d00f10.js +1 -0
  137. package/.next/static/chunks/app/api/image-generation/route-be5d61c3d2d00f10.js +1 -0
  138. package/.next/static/chunks/app/api/image-generation/settings/connections/route-be5d61c3d2d00f10.js +1 -0
  139. package/.next/static/chunks/app/api/image-generation/settings/route-be5d61c3d2d00f10.js +1 -0
  140. package/.next/static/chunks/app/api/models/route-be5d61c3d2d00f10.js +1 -0
  141. package/.next/static/chunks/app/api/models-config/catalog/route-be5d61c3d2d00f10.js +1 -0
  142. package/.next/static/chunks/app/api/models-config/discover/route-be5d61c3d2d00f10.js +1 -0
  143. package/.next/static/chunks/app/api/models-config/picker/route-be5d61c3d2d00f10.js +1 -0
  144. package/.next/static/chunks/app/api/models-config/route-be5d61c3d2d00f10.js +1 -0
  145. package/.next/static/chunks/app/api/models-config/runtime/route-be5d61c3d2d00f10.js +1 -0
  146. package/.next/static/chunks/app/api/models-config/test/route-be5d61c3d2d00f10.js +1 -0
  147. package/.next/static/chunks/app/api/plugins/check/route-be5d61c3d2d00f10.js +1 -0
  148. package/.next/static/chunks/app/api/plugins/route-be5d61c3d2d00f10.js +1 -0
  149. package/.next/static/chunks/app/api/project-overrides/route-be5d61c3d2d00f10.js +1 -0
  150. package/.next/static/chunks/app/api/project-trust/route-be5d61c3d2d00f10.js +1 -0
  151. package/.next/static/chunks/app/api/projects/route-be5d61c3d2d00f10.js +1 -0
  152. package/.next/static/chunks/app/api/push/config/route-be5d61c3d2d00f10.js +1 -0
  153. package/.next/static/chunks/app/api/push/subscribe/route-be5d61c3d2d00f10.js +1 -0
  154. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-be5d61c3d2d00f10.js +1 -0
  155. package/.next/static/chunks/app/api/sessions/[id]/context/route-be5d61c3d2d00f10.js +1 -0
  156. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-be5d61c3d2d00f10.js +1 -0
  157. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route-be5d61c3d2d00f10.js +1 -0
  158. package/.next/static/chunks/app/api/sessions/[id]/export/route-be5d61c3d2d00f10.js +1 -0
  159. package/.next/static/chunks/app/api/sessions/[id]/outline/route-be5d61c3d2d00f10.js +1 -0
  160. package/.next/static/chunks/app/api/sessions/[id]/route-be5d61c3d2d00f10.js +1 -0
  161. package/.next/static/chunks/app/api/sessions/[id]/state/route-be5d61c3d2d00f10.js +1 -0
  162. package/.next/static/chunks/app/api/sessions/[id]/subagent-usage/route-be5d61c3d2d00f10.js +1 -0
  163. package/.next/static/chunks/app/api/sessions/route-be5d61c3d2d00f10.js +1 -0
  164. package/.next/static/chunks/app/api/sessions/search/route-be5d61c3d2d00f10.js +1 -0
  165. package/.next/static/chunks/app/api/skills/check/route-be5d61c3d2d00f10.js +1 -0
  166. package/.next/static/chunks/app/api/skills/install/route-be5d61c3d2d00f10.js +1 -0
  167. package/.next/static/chunks/app/api/skills/route-be5d61c3d2d00f10.js +1 -0
  168. package/.next/static/chunks/app/api/skills/search/route-be5d61c3d2d00f10.js +1 -0
  169. package/.next/static/chunks/app/api/skills/update/route-be5d61c3d2d00f10.js +1 -0
  170. package/.next/static/chunks/app/api/subagents/[id]/route-be5d61c3d2d00f10.js +1 -0
  171. package/.next/static/chunks/app/api/subagents/profiles/route-be5d61c3d2d00f10.js +1 -0
  172. package/.next/static/chunks/app/api/subagents/settings/route-be5d61c3d2d00f10.js +1 -0
  173. package/.next/static/chunks/app/api/terminal/[id]/events/route-be5d61c3d2d00f10.js +1 -0
  174. package/.next/static/chunks/app/api/terminal/[id]/route-be5d61c3d2d00f10.js +1 -0
  175. package/.next/static/chunks/app/api/terminal/route-be5d61c3d2d00f10.js +1 -0
  176. package/.next/static/chunks/app/api/tools/settings/route-be5d61c3d2d00f10.js +1 -0
  177. package/.next/static/chunks/app/api/usage/route-be5d61c3d2d00f10.js +1 -0
  178. package/.next/static/chunks/app/api/web-auth/route-be5d61c3d2d00f10.js +1 -0
  179. package/.next/static/chunks/app/api/worktrees/route-be5d61c3d2d00f10.js +1 -0
  180. package/.next/static/chunks/app/{layout-abd03353f2b87156.js → layout-2c4104276f105978.js} +1 -1
  181. package/.next/static/chunks/app/manifest.webmanifest/route-be5d61c3d2d00f10.js +1 -0
  182. package/.next/static/chunks/app/page-8a658c191630cbd4.js +213 -0
  183. package/.next/static/chunks/next/dist/client/components/builtin/app-error-be5d61c3d2d00f10.js +1 -0
  184. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-be5d61c3d2d00f10.js +1 -0
  185. package/.next/static/chunks/next/dist/client/components/builtin/not-found-be5d61c3d2d00f10.js +1 -0
  186. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-be5d61c3d2d00f10.js +1 -0
  187. package/.next/static/css/{f6c5c5c31909d266.css → 90f551ecf6f7f552.css} +1 -1
  188. package/.next/static/css/{1a6a041bd877a737.css → cdd9ca136f3e707d.css} +1 -1
  189. package/.next/static/css/eae95890104af950.css +1 -0
  190. package/.next/trace +9 -42
  191. package/.next/trace-build +1 -1
  192. package/.next/types/app/api/project-overrides/route.ts +353 -0
  193. package/.next/types/app/api/sessions/[id]/subagent-usage/route.ts +353 -0
  194. package/.next/types/routes.d.ts +3 -1
  195. package/.next/types/validator.ts +18 -0
  196. package/package.json +1 -1
  197. package/.next/static/JdASme3vlmmcq3bfLK3dJ/_buildManifest.js +0 -1
  198. package/.next/static/chunks/2981-3cdf8a2b6a7acda7.js +0 -1
  199. package/.next/static/chunks/app/_global-error/page-65c0cd7526c36b6b.js +0 -1
  200. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-65c0cd7526c36b6b.js +0 -1
  201. package/.next/static/chunks/app/api/agent/[id]/events/route-65c0cd7526c36b6b.js +0 -1
  202. package/.next/static/chunks/app/api/agent/[id]/lease/route-65c0cd7526c36b6b.js +0 -1
  203. package/.next/static/chunks/app/api/agent/[id]/route-65c0cd7526c36b6b.js +0 -1
  204. package/.next/static/chunks/app/api/agent/new/route-65c0cd7526c36b6b.js +0 -1
  205. package/.next/static/chunks/app/api/agent/running/route-65c0cd7526c36b6b.js +0 -1
  206. package/.next/static/chunks/app/api/app-update/route-65c0cd7526c36b6b.js +0 -1
  207. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-65c0cd7526c36b6b.js +0 -1
  208. package/.next/static/chunks/app/api/auth/login/[provider]/route-65c0cd7526c36b6b.js +0 -1
  209. package/.next/static/chunks/app/api/auth/logout/[provider]/route-65c0cd7526c36b6b.js +0 -1
  210. package/.next/static/chunks/app/api/auth/providers/route-65c0cd7526c36b6b.js +0 -1
  211. package/.next/static/chunks/app/api/cwd/browse/route-65c0cd7526c36b6b.js +0 -1
  212. package/.next/static/chunks/app/api/cwd/validate/route-65c0cd7526c36b6b.js +0 -1
  213. package/.next/static/chunks/app/api/default-cwd/route-65c0cd7526c36b6b.js +0 -1
  214. package/.next/static/chunks/app/api/file-index/route-65c0cd7526c36b6b.js +0 -1
  215. package/.next/static/chunks/app/api/files/[...path]/route-65c0cd7526c36b6b.js +0 -1
  216. package/.next/static/chunks/app/api/git/diff/route-65c0cd7526c36b6b.js +0 -1
  217. package/.next/static/chunks/app/api/git/status/route-65c0cd7526c36b6b.js +0 -1
  218. package/.next/static/chunks/app/api/home/route-65c0cd7526c36b6b.js +0 -1
  219. package/.next/static/chunks/app/api/image-generation/route-65c0cd7526c36b6b.js +0 -1
  220. package/.next/static/chunks/app/api/image-generation/settings/connections/route-65c0cd7526c36b6b.js +0 -1
  221. package/.next/static/chunks/app/api/image-generation/settings/route-65c0cd7526c36b6b.js +0 -1
  222. package/.next/static/chunks/app/api/models/route-65c0cd7526c36b6b.js +0 -1
  223. package/.next/static/chunks/app/api/models-config/catalog/route-65c0cd7526c36b6b.js +0 -1
  224. package/.next/static/chunks/app/api/models-config/discover/route-65c0cd7526c36b6b.js +0 -1
  225. package/.next/static/chunks/app/api/models-config/picker/route-65c0cd7526c36b6b.js +0 -1
  226. package/.next/static/chunks/app/api/models-config/route-65c0cd7526c36b6b.js +0 -1
  227. package/.next/static/chunks/app/api/models-config/runtime/route-65c0cd7526c36b6b.js +0 -1
  228. package/.next/static/chunks/app/api/models-config/test/route-65c0cd7526c36b6b.js +0 -1
  229. package/.next/static/chunks/app/api/plugins/check/route-65c0cd7526c36b6b.js +0 -1
  230. package/.next/static/chunks/app/api/plugins/route-65c0cd7526c36b6b.js +0 -1
  231. package/.next/static/chunks/app/api/project-trust/route-65c0cd7526c36b6b.js +0 -1
  232. package/.next/static/chunks/app/api/projects/route-65c0cd7526c36b6b.js +0 -1
  233. package/.next/static/chunks/app/api/push/config/route-65c0cd7526c36b6b.js +0 -1
  234. package/.next/static/chunks/app/api/push/subscribe/route-65c0cd7526c36b6b.js +0 -1
  235. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-65c0cd7526c36b6b.js +0 -1
  236. package/.next/static/chunks/app/api/sessions/[id]/context/route-65c0cd7526c36b6b.js +0 -1
  237. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-65c0cd7526c36b6b.js +0 -1
  238. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route-65c0cd7526c36b6b.js +0 -1
  239. package/.next/static/chunks/app/api/sessions/[id]/export/route-65c0cd7526c36b6b.js +0 -1
  240. package/.next/static/chunks/app/api/sessions/[id]/outline/route-65c0cd7526c36b6b.js +0 -1
  241. package/.next/static/chunks/app/api/sessions/[id]/route-65c0cd7526c36b6b.js +0 -1
  242. package/.next/static/chunks/app/api/sessions/[id]/state/route-65c0cd7526c36b6b.js +0 -1
  243. package/.next/static/chunks/app/api/sessions/route-65c0cd7526c36b6b.js +0 -1
  244. package/.next/static/chunks/app/api/sessions/search/route-65c0cd7526c36b6b.js +0 -1
  245. package/.next/static/chunks/app/api/skills/check/route-65c0cd7526c36b6b.js +0 -1
  246. package/.next/static/chunks/app/api/skills/install/route-65c0cd7526c36b6b.js +0 -1
  247. package/.next/static/chunks/app/api/skills/route-65c0cd7526c36b6b.js +0 -1
  248. package/.next/static/chunks/app/api/skills/search/route-65c0cd7526c36b6b.js +0 -1
  249. package/.next/static/chunks/app/api/skills/update/route-65c0cd7526c36b6b.js +0 -1
  250. package/.next/static/chunks/app/api/subagents/[id]/route-65c0cd7526c36b6b.js +0 -1
  251. package/.next/static/chunks/app/api/subagents/profiles/route-65c0cd7526c36b6b.js +0 -1
  252. package/.next/static/chunks/app/api/subagents/settings/route-65c0cd7526c36b6b.js +0 -1
  253. package/.next/static/chunks/app/api/terminal/[id]/events/route-65c0cd7526c36b6b.js +0 -1
  254. package/.next/static/chunks/app/api/terminal/[id]/route-65c0cd7526c36b6b.js +0 -1
  255. package/.next/static/chunks/app/api/terminal/route-65c0cd7526c36b6b.js +0 -1
  256. package/.next/static/chunks/app/api/tools/settings/route-65c0cd7526c36b6b.js +0 -1
  257. package/.next/static/chunks/app/api/usage/route-65c0cd7526c36b6b.js +0 -1
  258. package/.next/static/chunks/app/api/web-auth/route-65c0cd7526c36b6b.js +0 -1
  259. package/.next/static/chunks/app/api/worktrees/route-65c0cd7526c36b6b.js +0 -1
  260. package/.next/static/chunks/app/manifest.webmanifest/route-65c0cd7526c36b6b.js +0 -1
  261. package/.next/static/chunks/app/page-3c870fe5f7505e28.js +0 -212
  262. package/.next/static/chunks/next/dist/client/components/builtin/app-error-65c0cd7526c36b6b.js +0 -1
  263. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-65c0cd7526c36b6b.js +0 -1
  264. package/.next/static/chunks/next/dist/client/components/builtin/not-found-65c0cd7526c36b6b.js +0 -1
  265. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-65c0cd7526c36b6b.js +0 -1
  266. package/.next/static/css/b121d2362092b3ab.css +0 -1
  267. /package/.next/static/{JdASme3vlmmcq3bfLK3dJ → 6f_3UIpNmHjU9Xn8SsAAi}/_ssgManifest.js +0 -0
@@ -1,212 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{9669:(e,t,n)=>{Promise.resolve().then(n.bind(n,14530)),Promise.resolve().then(n.bind(n,32981))},14530:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>o6});var r=n(95155),i=n(12115),s=n(73321);function a(e){let t=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,s=r.id,a=null;for(;;){if(n.has(s)){a=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(r.relation?.kind!=="subagent"){a=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,a)}return n}(e),n=new Map;for(let t of e)t.relation?.kind!=="subagent"&&n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(r.relation?.kind!=="subagent")continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}let l="pi-web:file-explorer:open";function o(){try{return window.localStorage}catch{return null}}function d(e,t=o()){if(t)try{t.setItem(l,String(e))}catch{}}let c=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function u(e){let t=e.match(c);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}function h(e,t){let n=e.slice(0,t),r=n.charCodeAt(n.length-1);return r>=55296&&r<=56319?n.slice(0,-1):n}function p(e){var t;return e.name?e.name:h((t=e.firstMessage)?h(u(t)??t,500):"",50)||e.id.slice(0,12)}function m(e){return e.projectKey??e.projectRoot??e.cwd}function g(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=m(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(([e,{root:t}])=>({key:e,root:t}))}function f(e,t){return e.filter(e=>m(e)===t)}let x="pi-sidebar-single-project",v="pi-sidebar-single-project-changed";function y(){return"true"===window.localStorage.getItem(x)}var b=n(2730),w=n(32981);function j(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function k(e){return j(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function S(e){let t=j(e).replace(/\/+$/,"");return t.split("/").pop()??t}function C(e){let t=j(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function N(e,t){if(!t)return e;let n=j(e),r=j(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function E(e,t){return`${j(e).replace(/\/$/,"")}/${t}`}var M=n(47650);async function I(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function L(){return(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function T(){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function $({onCancel:e,onSelect:t,initialPath:n,busy:s=!1,error:a}){let{t:l}=(0,w.s)(),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(""),[h,p]=(0,i.useState)(null),[m,g]=(0,i.useState)(n??""),[f,x]=(0,i.useState)([]),[v,y]=(0,i.useState)(null),[b,j]=(0,i.useState)(null),[k,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),j(null);try{let t=await I(e),n=t.path??e??"/";u(n),p(t.parentPath??null),g(n),x(t.directories??[]),y(t.drives??null)}catch(e){j(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{d(document.body),C(n||void 0)},[n,C]);let N=m.trim()!==c,E=!!c&&!N&&!s,R=!!h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,M.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||s||e()},onKeyDown:t=>{"Escape"!==t.key||s||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:600,fontSize:14},children:l("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:s,title:l("i18n.close"),"aria-label":l("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:s?"default":"pointer",opacity:s?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(h??void 0),disabled:k||!R,title:l("directoryPicker.goToParent"),"aria-label":l("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:R?"pointer":"default",opacity:R?1:.45},children:(0,r.jsx)("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,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:l("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),j(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:k||!m.trim(),title:l("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:k||!m.trim()?"default":"pointer",opacity:k||!m.trim()?.6:1},children:l("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[k?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==v?(0,r.jsx)(r.Fragment,{children:v.length>0?v.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsx)(T,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):f.length>0?f.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsx)(L,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noSubdirectories")}),(b||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"var(--danger)",fontSize:11},children:b??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:s,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:s?"default":"pointer",fontSize:12},children:l("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!E,title:l(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--primary)",color:"var(--primary-contrast)",fontSize:12,opacity:E?1:.6,cursor:E?"pointer":"default"},children:l(s?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}function R(e){return Math.round(264/e)/10}function W({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon":`url(/icons/catppuccin/latte/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function P({size:e=14,open:t=!1}){return(0,r.jsx)(W,{name:t?"_folder_open":"_folder",size:e})}function z({size:e=14}){return(0,r.jsx)(W,{name:"_file",size:e})}let D={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function A(e,t=14){let n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(W,{name:i,size:t});let s=D[n.split(".").pop()??""];return s?(0,r.jsx)(W,{name:s,size:t}):(0,r.jsx)(z,{size:t})}function F({open:e}){return(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:e?"rotate(90deg)":"none",transition:"transform 0.15s",display:"block",flexShrink:0},children:(0,r.jsx)("polyline",{points:"9 6 15 12 9 18"})})}async function B(e){let t=k(e),n=await fetch(`/api/files/${t}?type=list`);if(!n.ok){let e=`Failed to load files (HTTP ${n.status})`;try{let t=await n.json();t.error&&(e=t.error)}catch{}throw Error(e)}return((await n.json()).entries??[]).map(t=>({name:t.name,fullPath:E(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}))}async function O(e){let t=new URLSearchParams({cwd:e}),n=await fetch(`/api/git/status?${t.toString()}`);if(!n.ok)throw Error(`Failed to load Git status (HTTP ${n.status})`);return n.json()}let H={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},U={modified:"var(--warning)",added:"var(--success)",deleted:"var(--danger)",renamed:"var(--accent)",untracked:"var(--success)",conflict:"var(--danger)"};function _({status:e,t}){return(0,r.jsx)("span",{title:t(H[e.status]),"aria-label":t(H[e.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:U[e.status],fontSize:11},children:e.code})}function q({size:e=12}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(e),strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function K({onClick:e,title:t}){return(0,r.jsx)("button",{type:"button",onClick:e,title:t,"aria-label":t,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-muted)",cursor:"pointer"},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="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}function V({node:e,depth:t,cwd:n,onOpenFile:s,onAtMention:a,expandedPaths:l,onToggleExpanded:o,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p}){let m=l.has(e.fullPath),g=c.has(e.fullPath),f=j(e.fullPath),x=u.get(f),v=e.isDir&&(void 0!==x||h.has(f)),[y,b]=(0,i.useState)(e.children??[]),[w,S]=(0,i.useState)(e.loaded??!1),[C,E]=(0,i.useState)(!1),[M,I]=(0,i.useState)(null),[L,T]=(0,i.useState)(!1),$=(0,i.useCallback)(async(t=!1)=>{if(!w||t){E(!0),I(null);try{let t=await B(e.fullPath);b(t),S(!0)}catch(e){I(e instanceof Error?e.message:String(e))}finally{E(!1)}}},[w,e.fullPath]);(0,i.useEffect)(()=>{void 0!==d&&m&&w&&$(!0)},[d]);let R=(0,i.useCallback)(()=>{if(e.isDir){let t=!m;o(e.fullPath,t)}else s(e.fullPath,e.name,{cwd:n})},[n,e.isDir,e.fullPath,e.name,m,s,o]);return(0,i.useEffect)(()=>{m&&!w&&$()},[$,w,m]),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:R,onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:4+14*t,paddingRight:8,height:26,boxSizing:"border-box",cursor:"pointer",background:L?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[e.isDir?(0,r.jsx)("span",{className:"sidebar-section-gutter",style:{paddingLeft:9,boxSizing:"border-box"},children:(0,r.jsx)(F,{open:m})}):(0,r.jsx)("span",{className:"sidebar-section-gutter",style:{color:L?"var(--text)":"var(--text-muted)"},children:A(e.name,13)}),(0,r.jsx)("span",{style:{fontSize:12,color:L?"var(--text)":"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:e.fullPath,children:e.name}),g&&(0,r.jsx)("span",{title:p("files.newlyUploaded"),"aria-label":p("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"var(--accent)"}})}),!L&&!e.isDir&&x&&(0,r.jsx)(_,{status:x,t:p}),!L&&v&&(0,r.jsx)("span",{title:p("files.containsChangedFiles"),"aria-label":p("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"var(--warning)"}})}),C&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"3",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),L&&(a||!e.isDir)&&(0,r.jsxs)("span",{style:{position:"absolute",right:4,top:0,height:"100%",display:"flex",alignItems:"center",gap:2,paddingLeft:4,background:"var(--bg-hover)",borderRadius:4},children:[a&&(0,r.jsx)("button",{type:"button",className:"file-row-action",onClick:t=>{t.stopPropagation(),a(N(e.fullPath,n),e.isDir,n)},title:p("files.insertPath"),"aria-label":p("files.insertPath"),children:(0,r.jsx)(q,{size:13})}),!e.isDir&&(0,r.jsx)("a",{href:`/api/files/${k(e.fullPath)}?type=download`,download:!0,className:"file-row-action",onClick:e=>e.stopPropagation(),title:p("files.download"),"aria-label":p("files.download"),children:(0,r.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,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]})]}),e.isDir&&m&&(0,r.jsxs)("div",{children:[y.map(e=>(0,r.jsx)(V,{node:e,depth:t+1,cwd:n,onOpenFile:s,onAtMention:a,expandedPaths:l,onToggleExpanded:o,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p},e.fullPath)),0===y.length&&w&&(0,r.jsx)("div",{style:{paddingLeft:4+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),M&&(0,r.jsx)("button",{type:"button",onClick:()=>void $(!0),title:M,style:{marginLeft:2+(t+1)*14,height:22,padding:0,border:0,background:"none",color:"var(--danger)",cursor:"pointer",fontSize:11},children:p("files.loadFailedRetry")})]})]})}function J({status:e,cwd:t,onOpenFile:n,t:s}){let[a,l]=(0,i.useState)(!1),o=S(e.filePath),d=N(e.filePath,t);return(0,r.jsxs)("div",{onClick:()=>n(e.filePath,o,{modeHint:"diff",cwd:t}),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:26,boxSizing:"border-box",cursor:"pointer",background:a?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)(_,{status:e,t:s}),(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",color:a?"var(--text)":"var(--text-muted)"},children:A(o,13)}),(0,r.jsx)("span",{style:{fontSize:12,color:a?"var(--text)":"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:d})]})}let Y=(0,i.forwardRef)(function({cwd:e,onOpenFile:t,refreshKey:n,onAtMention:s,onAtMentions:a,onUploadBusyChange:l,changesCollapsed:o,onChangesCountChange:d,fileSearchOpen:c=!1,onFileSearchOpenChange:u},h){let{t:p}=(0,w.s)(),[m,g]=(0,i.useState)([]),[f,x]=(0,i.useState)(!0),[v,y]=(0,i.useState)(null),[b,S]=(0,i.useState)(new Set),[M,I]=(0,i.useState)(0),[L,T]=(0,i.useState)(new Set),[$,R]=(0,i.useState)([]),[W,P]=(0,i.useState)({additions:0,deletions:0}),[z,D]=(0,i.useState)(null),[A,F]=(0,i.useState)(null),[H,_]=(0,i.useState)("idle"),[Y,Z]=(0,i.useState)(0),[X,G]=(0,i.useState)(null),[Q,ee]=(0,i.useState)(null),[et,en]=(0,i.useState)(null),[er,ei]=(0,i.useState)(""),[es,ea]=(0,i.useState)([]),[el,eo]=(0,i.useState)(!1),[ed,ec]=(0,i.useState)(!1),[eu,eh]=(0,i.useState)(new Set),ep=(0,i.useRef)(null),em=(0,i.useRef)(null),eg=(0,i.useRef)(null),ef=(0,i.useRef)(null),ex=`${n??0}:${M}`,ev="idle"!==H,ey=er.trim().length>0;(0,i.useEffect)(()=>{if(!c)return;let t=er.trim();if(!t){ea([]),eo(!1),ec(!1);return}let n=new AbortController;eo(!0),ec(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(e)}&q=${encodeURIComponent(t)}&kind=file&version=${encodeURIComponent(ex)}`,{signal:n.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>ea((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{n.signal.aborted||(ea([]),ec(!0))}).finally(()=>{n.signal.aborted||eo(!1)})},150);return()=>{clearTimeout(r),n.abort()}},[e,c,ex,er]),(0,i.useEffect)(()=>{c&&ep.current?.focus()},[c]),(0,i.useEffect)(()=>{if(0===es.length)return;let t=new Set;for(let n of es){let r=n.split("/"),i="";for(let n=0;n<r.length-1;n++)i=i?`${i}/${r[n]}`:r[n],t.add(E(e,i))}eh(e=>{let n=!1,r=new Set(e);for(let e of t)r.has(e)||(r.add(e),n=!0);return n?r:e})},[e,es]);let eb=(0,i.useMemo)(()=>{let t=n=>({name:n.name,fullPath:E(e,n.path),isDir:n.isDir,size:0,children:n.children.map(t),loaded:!0});return(function(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t})(es).map(t)},[e,es]),ew=(0,i.useMemo)(()=>new Map($.map(e=>[j(e.filePath),e])),[$]),ej=(0,i.useMemo)(()=>{let t=new Set,n=j(e).replace(/\/$/,"");for(let e of $){let r=C(j(e.filePath));for(;(r===n||r.startsWith(`${n}/`))&&(t.add(r),r!==n);){let e=C(r);if(e===r)break;r=e}}return t},[e,$]),ek=(0,i.useCallback)((e,t)=>{S(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),eS=(0,i.useCallback)(t=>{let n=t.uploaded??[];ee({uploaded:n,skipped:t.skipped??[],errors:t.errors??[]}),n.length>0&&(T(new Set(n.map(t=>E(e,t)))),I(e=>e+1))},[e]),eC=(0,i.useCallback)(async(t,n)=>{en(null),G(null),Z(0),_("uploading");try{let{status:r,data:i}=await new Promise((r,i)=>{let s=new FormData;t.forEach(e=>s.append("files",e,e.name));let a=new XMLHttpRequest;a.open("POST",`/api/files/${k(e)}?type=upload&conflict=${n}`),a.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&Z(Math.round(e.loaded/e.total*100))},a.onerror=()=>i(Error("Network error while uploading files")),a.onabort=()=>i(Error("Upload cancelled")),a.onload=()=>{let e={};try{e=JSON.parse(a.responseText)}catch{a.responseText&&(e.error=a.responseText)}r({status:a.status,data:e})},a.send(s)});if(409===r&&i.conflicts?.length)return void en({files:t,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);Z(100),eS(i)}catch(e){G(e instanceof Error?e.message:String(e))}finally{_("idle")}},[eS,e]),eN=(0,i.useCallback)(async t=>{if(0!==t.length&&!ev){ee(null),T(new Set),en(null),G(null),Z(0),_("checking");try{let n=await fetch(`/api/files/${k(e)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:t.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void en({files:t,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await eC(t,"error")}catch(e){G(e instanceof Error?e.message:String(e))}finally{_("idle")}}},[e,eC,ev]),eE=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eN(t)},[eN]);(0,i.useImperativeHandle)(h,()=>({openUploadPicker(){ev||ef.current?.click()}}),[ev]),(0,i.useEffect)(()=>{l?.(ev)},[l,ev]),(0,i.useEffect)(()=>()=>l?.(!1),[l]),(0,i.useEffect)(()=>{let t=em.current!==e;em.current=e,t&&(S(new Set),T(new Set),ee(null),en(null),G(null)),x(t),y(null);let n=!1;return B(e).then(e=>{n||g(e)}).catch(e=>{n||y(e instanceof Error?e.message:String(e))}).finally(()=>{n||x(!1)}),()=>{n=!0}},[e,n,M]),(0,i.useEffect)(()=>{let t=!1;return eg.current!==e&&(D(null),R([]),P({additions:0,deletions:0})),F(null),O(e).then(n=>{t||(R(n.isGitRepository?n.files:[]),P(n.isGitRepository?{additions:n.additions,deletions:n.deletions}:{additions:0,deletions:0}),eg.current=e,D(e))}).catch(e=>{t||F(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e,n,M]),(0,i.useEffect)(()=>{d?.(z===e?$.length:0)},[e,$,z,d]);let eM=ev||null!==et||null!==X||null!==Q,eI=(0,i.useCallback)(()=>{Q&&0!==Q.uploaded.length&&a?.(Q.uploaded.map(t=>N(E(e,t),e)),e)},[e,a,Q]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},children:[(0,r.jsx)("input",{ref:ef,type:"file",multiple:!0,hidden:!0,onChange:eE}),eM&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ev&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===H?p("files.checking"):p("files.uploading",{progress:Y}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===H?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===H&&(0,r.jsxs)("span",{style:{fontSize:11},children:[Y,"%"]})]}),"uploading"===H&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${Y}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),et&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, var(--warning) 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, var(--warning) 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:p("files.conflictSummary",{count:et.conflicts.length,countSuffix:1===et.conflicts.length?"":"s",files:et.conflicts.join(", ")})}),et.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:11,color:"var(--warning)",lineHeight:1.35,overflowWrap:"anywhere"},children:p("files.cannotReplace",{files:et.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void eC(et.files,"overwrite"),style:{height:22,padding:"0 7px",border:"1px solid var(--danger)",borderRadius:4,background:"transparent",color:"var(--danger)",cursor:"pointer",fontSize:11},children:p("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void eC(et.files,"skip"),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:11},children:p("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>en(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:p("files.cancel")})]})]}),X&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"var(--danger)"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:X}),(0,r.jsx)(K,{onClick:()=>G(null),title:p("files.dismissError")})]}),Q&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[Q.uploaded.length>0&&(0,r.jsxs)("span",{title:`${Q.uploaded.length} uploaded`,"aria-label":`${Q.uploaded.length} uploaded`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--success)"},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:Q.uploaded.length})]}),Q.skipped.length>0&&(0,r.jsxs)("span",{title:`${Q.skipped.length} skipped`,"aria-label":`${Q.skipped.length} skipped`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:Q.skipped.length})]}),Q.errors.length>0&&(0,r.jsxs)("span",{title:`${Q.errors.length} failed`,"aria-label":`${Q.errors.length} failed`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--danger)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:Q.errors.length})]})]}),Q.uploaded.length>0&&a&&(0,r.jsxs)("button",{type:"button",onClick:eI,title:1===Q.uploaded.length?p("files.addUploadedFile"):p("files.addAllUploadedFiles"),"aria-label":1===Q.uploaded.length?p("files.addUploadedFile"):p("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,whiteSpace:"nowrap"},children:[(0,r.jsx)(q,{}),p("files.mention")]}),(0,r.jsx)(K,{onClick:()=>ee(null),title:p("files.dismissUploadResults")})]}),Q.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:11,color:"var(--danger)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),c&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:ep,className:"file-search-input",value:er,onChange:e=>ei(e.target.value),onKeyDown:e=>{"Escape"===e.key&&u?.(!1)},placeholder:p("sidebar.searchFilesPlaceholder"),"aria-label":p("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit",fontSize:12}}),er&&(0,r.jsx)("button",{type:"button",onClick:()=>ei(""),title:p("sidebar.clearSearch"),"aria-label":p("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",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,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),ey&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[el&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:11,color:"var(--text-dim)"},children:p("sidebar.searchingFiles")}),!el&&ed&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:11,color:"var(--danger)"},children:p("i18n.networkError")}),!el&&!ed&&0===es.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:11,color:"var(--text-dim)"},children:p("sidebar.noMatchingFiles")}),!el&&!ed&&es.length>0&&(0,r.jsx)("div",{children:eb.map(n=>(0,r.jsx)(V,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:s,expandedPaths:eu,onToggleExpanded:(e,t)=>{eh(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:L,gitStatusByPath:ew,changedDirectoryPaths:ej,t:p},`${er}:${n.fullPath}`))})]})]}),A&&(0,r.jsx)("div",{role:"alert",title:A,style:{padding:"6px 12px",fontSize:11,color:"var(--danger)"},children:p("files.gitStatusFailed")}),!o&&z===e&&$.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":p("files.changeStats",{count:$.length,additions:W.additions,deletions:W.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:p("files.changedCount",{count:$.length})}),(0,r.jsxs)("span",{style:{color:U.added,fontVariantNumeric:"tabular-nums"},children:["+",W.additions]}),(0,r.jsxs)("span",{style:{color:U.deleted,fontVariantNumeric:"tabular-nums"},children:["-",W.deletions]})]}),$.map(n=>(0,r.jsx)(J,{status:n,cwd:e,onOpenFile:t,t:p},n.filePath))]}),(o||z!==e||0===$.length)&&(!c||!ey)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[f?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."}):v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--danger)"},children:v}):m.map(n=>(0,r.jsx)(V,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:s,expandedPaths:b,onToggleExpanded:ek,refreshToken:ex,highlightedPaths:L,gitStatusByPath:ew,changedDirectoryPaths:ej,t:p},n.fullPath)),!f&&!v&&0===m.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:p("files.noFiles")})]})]})});function Z({open:e,query:t,refreshKey:n,children:s,selectedSessionId:a,onSelectSession:l}){let{t:o,locale:d}=(0,w.s)(),[c,u]=(0,i.useState)({query:""}),h=t.trim(),p=c.query===h?c.response:void 0,m=c.query===h&&c.failed;return(0,i.useEffect)(()=>{if(!e||!h)return;let t=new AbortController;u({query:h});let n=setTimeout(async()=>{try{let e=await fetch(`/api/sessions/search?${new URLSearchParams({q:h})}`,{signal:t.signal});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await e.json();t.signal.aborted||u({query:h,response:n})}catch{t.signal.aborted||u({query:h,failed:!0})}},300);return()=>{clearTimeout(n),t.abort()}},[e,h,n]),e&&h?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!p&&!m,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:m?o("sidebar.sessionSearchFailed"):p?0===p.results.length?o("sidebar.sessionSearchEmpty"):o("sidebar.sessionSearchCount",{count:p.results.length}):o("sidebar.sessionSearching")}),p?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:o("sidebar.sessionSearchPartial")}),p?.results.map(({session:e,entryId:t,blockIndex:n,before:i,match:s,after:o})=>(0,r.jsxs)("button",{type:"button",onClick:()=>l(e,t,n),"aria-current":e.id===a?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${e.id===a?"bg-bg-selected":""}`,children:[(0,r.jsx)("span",{className:"block truncate text-xs text-text",children:e.name||e.firstMessage}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[11px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:e.cwd,children:e.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,b.fw)(e.modified,d)})]}),(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[i,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:s}),o]})]},e.id))]}):s}function X({size:e=14,title:t,ariaLabel:n,className:i,style:s}){let a=e<=10?4:5;return(0,r.jsxs)("span",{className:`live-pulse-beacon${i?` ${i}`:""}`,title:t,"aria-label":n,style:{width:e,height:e,...s},children:[(0,r.jsx)("span",{className:"live-pulse-beacon-halo",style:{width:a,height:a},"aria-hidden":"true"}),(0,r.jsx)("span",{className:"live-pulse-beacon-core",style:{width:a,height:a},"aria-hidden":"true"})]})}function G({size:e=13,className:t,style:n}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(e),strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:t,style:{flexShrink:0,...n},children:[(0,r.jsx)("rect",{x:"2",y:"8",width:"14",height:"14",rx:"2"}),(0,r.jsx)("path",{d:"M8 2h12a2 2 0 0 1 2 2v12"})]})}function Q({onClick:e,title:t,disabled:n,skipHover:i,color:s,background:a="none",marginRight:l,ariaPressed:o,className:d,children:c}){return(0,r.jsx)("button",{onClick:e,disabled:n,title:t,"aria-label":t,"aria-pressed":o,className:d,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,marginRight:l,background:a,border:"none",color:s,cursor:n?"default":"pointer",borderRadius:4,flexShrink:0,opacity:n?.6:1,transition:"color 0.3s, background 0.3s"},onMouseEnter:e=>{n||i||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||i||(e.currentTarget.style.color=s,e.currentTarget.style.background=a)},children:c})}function ee({open:e}){return(0,r.jsx)("span",{className:"sidebar-section-gutter workspace-folder-icon",children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e?(0,r.jsx)("path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-1.94V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}):(0,r.jsx)("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})})})}let et="pi-web:unread-session-ids",en="pi-web:last-custom-cwd",er="pi-web:workspace-expansion";function ei(){try{let e=window.localStorage.getItem(er);if(!e)return null;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):null}catch{return null}}function es(){try{return window.localStorage.getItem(en)??""}catch{return""}}function ea(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function el({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function eo({selectedSessionId:e,onSelectSession:t,onOpenSessionInNewTab:n,onNewSession:s,initialSessionId:c,skipInitialProjectSelection:u,refreshKey:h,onSessionDeleted:p,selectedCwd:x,onCwdChange:b,onOpenFile:j,onOpenTerminal:k,explorerRefreshKey:C,onExplorerRefresh:N,onAtMention:E,onAtMentions:M,onBackgroundTaskDone:I,onRunningSessionIdsChange:L,onSessionsChange:T,pinnedCwds:R,onTogglePinnedCwd:W,onHomeDirChange:P,onWorktreeInfoChange:z}){let D,A,F,B,{t:O}=(0,w.s)(),[H,U]=(0,i.useState)([]),[_,q]=(0,i.useState)([]),[K,V]=(0,i.useState)(null),J=(0,i.useRef)(null),G=(0,i.useRef)(0),[ed,ec]=(0,i.useState)(!0),[eh,ep]=(0,i.useState)(null),[em,eg]=(0,i.useState)(null),[ef,ex]=(0,i.useState)(""),[ev,ey]=(0,i.useState)(!1),[eb,ew]=(0,i.useState)(""),[ej,ek]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(es),[eN,eE]=(0,i.useState)(null),[eM,eI]=(0,i.useState)(!1),[eL,eT]=(0,i.useState)(null),e$=(0,i.useRef)(null),[eR,eW]=(0,i.useState)(null),[eP,ez]=(0,i.useState)(!1),[eD,eA]=(0,i.useState)(!1),[eF,eB]=(0,i.useState)(""),[eO,eH]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(!1),[eq,eK]=(0,i.useState)(null),[eV,eJ]=(0,i.useState)(null),eY=(0,i.useRef)(null),eZ=(0,i.useRef)(null),[eX,eG]=(0,i.useState)(!0),[eQ,e0]=(0,i.useState)(!0),[e1,e2]=(0,i.useState)(!0),[e4,e8]=(0,i.useState)(ei),[e3,e6]=(0,i.useState)({}),[e5,e7]=(0,i.useState)(0),[e9,te]=(0,i.useState)(!1),[tt,tn]=(0,i.useState)(!1),[tr,ti]=(0,i.useState)(!1),[ts,ta]=(0,i.useState)(""),tl=tr&&!!ts.trim(),[to,td]=(0,i.useState)(0),[tc,tu]=(0,i.useState)(!0),[th,tp]=(0,i.useState)(()=>new Set),[tm,tg]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(et);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),tf=(0,i.useRef)(new Set),tx=(0,i.useRef)(new Set),tv=(0,i.useRef)(new Set),ty=(0,i.useRef)(!1),tb=(0,i.useRef)(null),tw=(0,i.useRef)(null),[tj,tk]=(0,i.useState)(0),[tS,tC]=(0,i.useState)(0),[tN,tE]=(0,i.useState)(null),[tM,tI]=(0,i.useState)(null),[tL,tT]=(0,i.useState)(null),[t$,tR]=(0,i.useState)(null),tW=t$?.key??null,[tP,tz]=(0,i.useState)(null),[tD,tA]=(0,i.useState)(null),tF=(0,i.useRef)(null),tB=(0,i.useRef)(null),tO=(0,i.useRef)(!1),tH=(0,i.useRef)(null),tU=(0,i.useCallback)(e=>{tI(null),tT(null);let t=e.currentTarget.scrollTop;null==tH.current&&(tH.current=requestAnimationFrame(()=>{tH.current=null,tC(t)}))},[]);(0,i.useEffect)(()=>{if(!tM&&!tL&&!t$)return;let e=e=>{let t=e.target;t?.closest(".project-context-menu")||(tI(null),tT(null),tR(null))},t=e=>{"Escape"===e.key&&(tI(null),tT(null),tR(null))};return window.addEventListener("pointerdown",e,!0),window.addEventListener("keydown",t),()=>{window.removeEventListener("pointerdown",e,!0),window.removeEventListener("keydown",t)}},[tM,tL,t$]);let t_=(0,i.useCallback)((e,t,n)=>{if(n.target?.closest(".workspace-row-action"))return;let r=n.touches[0];tB.current={x:r.clientX,y:r.clientY},tO.current=!1,tF.current=setTimeout(()=>{tO.current=!0,tT({key:e,cwd:t,x:r.clientX,y:r.clientY}),navigator.vibrate?.(15)},400)},[]),tq=(0,i.useCallback)(e=>{if(!tB.current||!tF.current)return;let t=e.touches[0];(Math.abs(t.clientX-tB.current.x)>10||Math.abs(t.clientY-tB.current.y)>10)&&(clearTimeout(tF.current),tF.current=null)},[]),tK=(0,i.useCallback)(()=>{tF.current&&clearTimeout(tF.current),tF.current=null,tB.current=null},[]);(0,i.useLayoutEffect)(()=>{let e=tw.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)tk(t.contentRect.height)});return t.observe(e),tk(e.clientHeight),tC(e.scrollTop),()=>t.disconnect()},[tl]);let tV=(0,i.useCallback)(async(e=!1,t=!1)=>{let n=++G.current;try{e&&ec(!0);let r=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(n!==G.current)return;J.current=i.sessionListVersion,V(i.sessionListVersion),U(i.sessions),q(i.pinnedSessionIds),ty.current||(tx.current=new Set(i.completionNotificationSuppressedSessionIds??[]),tp(new Set(i.runningSessionIds??[])));let s=new Set(i.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));tg(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>s.has(e)));return t.size===e.size?e:t}),ep(null)}catch(e){n===G.current&&ep(String(e))}finally{n===G.current&&ec(!1)}},[]),tJ=(0,i.useCallback)(async e=>{let t=!_.includes(e);q(n=>t?[...n,e]:n.filter(t=>t!==e));try{await fetch(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({pinned:t})})}finally{tV()}},[tV,_]),tY=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tY.current;tY.current=!0,tV(e,!e)},[tV,h]),(0,i.useEffect)(()=>{eG(function(e=o()){if(!e)return!0;try{return"false"!==e.getItem(l)}catch{return!0}}())},[]),(0,i.useEffect)(()=>{try{0===tm.size?window.localStorage.removeItem(et):window.localStorage.setItem(et,JSON.stringify([...tm]))}catch{}},[tm]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(!t.ok)return;let r=await t.json();if(e||n!==s)return;ty.current=!0,tx.current=new Set(r.completionNotificationSuppressedSessionIds??[]),tp(new Set(r.runningSessionIds??[])),r.sessionListVersion!==J.current&&await tV()}catch{}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[tV]),(0,i.useEffect)(()=>{L?.(th)},[L,th]),(0,i.useEffect)(()=>{T?.(H)},[H,T]),(0,i.useEffect)(()=>{let t=tf.current,n=[...t].filter(t=>!th.has(t)&&t!==e),r=new Set(H.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),i=n.filter(e=>!tv.current.has(e)&&!r.has(e)),s=[...th].filter(e=>!t.has(e));(i.length>0||s.length>0)&&tg(e=>{let t=new Set(e);return th.forEach(e=>t.delete(e)),i.forEach(e=>t.add(e)),t});let a=s.some(e=>!H.some(t=>t.id===e));(n.length>0||a)&&tV(!1,!0),i.length>0&&I?.(i),tf.current=th,tv.current=new Set([...th].filter(e=>tx.current.has(e)||r.has(e)))},[th,e,H,tV,I]),(0,i.useEffect)(()=>{e&&tg(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{void 0!==C&&e7(e=>e+1)},[C]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&ex(e.home)}).catch(()=>{})},[]),(0,i.useEffect)(()=>{ef&&P?.(ef)},[ef,P]);let tZ=(0,i.useRef)(!1),tX=(0,i.useCallback)((e,t)=>({root:e,key:t}),[]),tG=(0,i.useCallback)(e=>{if(!e)return null;if(eL?.cwd===e)return tX(eL.root,eL.key);if(eR&&eR.forCwd===e||eR?.worktrees.some(t=>t.path===e))return tX(eR.projectRoot,eR.projectKey);let t=H.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return t?tX(t.projectRoot??t.cwd,m(t)):tX(e,e)},[eL,eR,H,tX]),tQ=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tG(em),t=tQ.current;(t?.cwd!==em||t.key!==(e?.key??null))&&(tQ.current={cwd:em,key:e?.key??null},b?.(em,e?.root??null,e?.key??null))},[em,b,tG]);let t0=(0,i.useRef)(null);(0,i.useEffect)(()=>{x&&x!==t0.current&&(t0.current=x,eg(x))},[x]);let[t1,t2]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!em){eW(null),eJ(null);return}let e=!1;return eJ(em),fetch(`/api/worktrees?cwd=${encodeURIComponent(em)}`).then(e=>e.json()).then(t=>{if(!e){if(eJ(null),t.error||!t.projectRoot)return void eW(null);eW({forCwd:em,projectRoot:t.projectRoot,projectKey:t.projectKey??t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,currentWorktreePath:t.currentWorktreePath??null,worktrees:t.worktrees??[]})}}).catch(()=>{e||(eJ(null),eW(null))}),()=>{e=!0}},[em,t1,h]),(0,i.useEffect)(()=>{if(z){if(!eR?.isGit)return void z(null);z({forCwd:eR.forCwd,projectRoot:eR.projectRoot,currentWorktreePath:eR.currentWorktreePath,worktrees:eR.worktrees})}},[eR,z]),(0,i.useEffect)(()=>{if(0!==H.length&&!u&&null===em){if(c&&!tZ.current){tZ.current=!0;let e=H.find(e=>e.id===c);if(e){eg(e.cwd),t(e,!0);return}}let e=g(H);e.length>0&&eg(e[0].root)}},[H,em,c,u,t]);let t4=eR?eR.worktrees.find(e=>e.path===em)??(eR.forCwd===em&&eR.currentWorktreePath?eR.worktrees.find(e=>e.path===eR.currentWorktreePath):void 0)??eR.worktrees.find(e=>e.isMain):void 0,t8=t4?.path??null,t3=(0,i.useCallback)(async e=>{let t=(e??eS).trim();if(t&&!eM){eI(!0),eE(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await e.json().catch(()=>({}));if(!e.ok||r.error||!r.cwd||!r.projectRoot||!r.projectKey)return void eE(r.error??`HTTP ${e.status}`);eT({cwd:r.cwd,root:r.projectRoot,key:r.projectKey});var n=r.cwd;try{window.localStorage.setItem(en,n)}catch{}eC(r.cwd),R.includes(r.projectRoot)||W(r.projectRoot),e8(e=>new Set([...e??[],r.projectKey])),eg(r.cwd),ek(!1),ey(!1)}catch(e){eE(e instanceof Error?e.message:String(e))}finally{eI(!1)}}},[eS,eM,W,R]),t6=(0,i.useCallback)(()=>{ek(!0),eE(null),ey(!1)},[]),t5=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&(R.includes(t.cwd)||W(t.cwd),e8(e=>new Set([...e??[],t.cwd])),eg(t.cwd),ek(!1),eE(null),ey(!1))}catch{}},[W,R]),t7=(0,i.useCallback)(async()=>{let e=eF.trim();if(e&&!eU&&eR){e_(!0),eH(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eR.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eH(n.error??`HTTP ${t.status}`);eA(!1),eB(""),ez(!1),eW(t=>t?{...t,forCwd:n.path,currentWorktreePath:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),eg(n.path),t2(e=>e+1)}catch(e){eH(e instanceof Error?e.message:String(e))}finally{e_(!1)}}},[eF,eU,eR]),t9=(0,i.useCallback)(async(e,t)=>{if(eR&&!eU){e_(!0),eH(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eR.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void eK(e);eH(r.error??`HTTP ${n.status}`);return}eK(null),t8===e&&eg(eR.projectRoot),t2(e=>e+1)}catch(e){eH(e instanceof Error?e.message:String(e))}finally{e_(!1)}}},[eR,eU,t8]);(0,i.useEffect)(()=>{let e=e=>{e$.current&&!e$.current.contains(e.target)&&ey(!1),eY.current&&!eY.current.contains(e.target)&&(ez(!1),eA(!1),eB(""),eH(null),eK(null),ew(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let ne=(0,i.useCallback)((e,n,r)=>{U(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e8(t=>{let n=new Set(t??[]);return n.add(m(e)),n});let i=tG(em)?.key;(function(e){let t=e.sessionCwd;if(!t)return!1;let n=e.selectedCwd;if(!n)return!0;if(t===n)return!1;if(e.sessionProjectKey&&e.selectedProjectKey&&e.sessionProjectKey!==e.selectedProjectKey)return!0;let r=e.worktrees;if(!r?.length)return!0;let i=e=>r.find(t=>t.path===e)?.path??null,s=i(t);return!!s&&s!==(i(n)??n)})({sessionCwd:e.cwd,selectedCwd:em,sessionProjectKey:m(e),selectedProjectKey:i,worktrees:eR?.worktrees})&&eg(e.cwd),t(e,!1,n,r)},[t,tG,em,eR]),nt=(0,i.useCallback)(e=>{let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;s?.(t,e)},[s]),[nn,nr]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=()=>nr(y());return e(),window.addEventListener(v,e),()=>window.removeEventListener(v,e)},[]);let ni=(0,i.useMemo)(()=>g(H),[H]),ns=!em&&!ed&&!eh&&0===ni.length,na=(0,i.useMemo)(()=>tG(em),[tG,em]),nl=(0,i.useMemo)(()=>{let e=[],t=new Set,n=n=>{!n||t.has(n.key)||(t.add(n.key),e.push(n))},r=new Set(ni.map(e=>e.key));return R.forEach(e=>{let t=tG(e);t&&!r.has(t.key)&&n(t)}),ni.forEach(n),n(na),e},[R,tG,ni,na]),no=(0,i.useMemo)(()=>{let t;return e?t=na?.key:1===nl.length&&(t=nl[0]?.key),new Set(t?[t]:[])},[na?.key,e,nl]);(0,i.useEffect)(()=>{null===e4&&0!==nl.length&&e8(no)},[no,e4,nl.length]),(0,i.useEffect)(()=>{null!==e4&&function(e){try{window.localStorage.setItem(er,JSON.stringify([...e]))}catch{}}(e4)},[e4]);let nd=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=m(i);if(!e)continue;let s=r.get(e);s||(s={running:0,unread:0},r.set(e,s)),t.has(i.id)&&s.running++,n.has(i.id)&&s.unread++}return r})(H,th,tm),[H,th,tm]),nc=(0,i.useMemo)(()=>{let e=0,t=0;for(let[n,r]of nd)n!==na?.key&&(e+=r.running,t+=r.unread);return{running:e,unread:t}},[nd,na?.key]),nu=(0,i.useCallback)(async e=>{tR(null),tA(null),tz(e.key);try{let t=await fetch("/api/projects",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key})}),n=await t.json().catch(()=>({}));if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);for(let t of R)tG(t)?.key===e.key&&W(t);for(let t of(na?.key===e.key&&eg(nl.find(t=>t.key!==e.key)?.root??null),n.deletedSessionIds??[]))p?.(t);tV()}catch(e){tA(e instanceof Error?e.message:String(e))}finally{tz(null)}},[tV,p,W,R,tG,na?.key,nl]),nh=!!(eR?.isGit&&eR.isTopLevel&&em&&na?.key===eR.projectKey),np=(0,i.useMemo)(()=>{let t=[],n=e4??no;for(let r of nn?nl.filter(e=>e.key===(na??nl[0])?.key):nl){let i=a(f(H,r.key)).filter(e=>!_.includes(e.root.id));if(t.push({kind:"workspace",project:r,cwd:i[0]?.root.cwd??r.root}),nn||n.has(r.key)){let n=nn?1/0:e3[r.key]??6,s=i.slice(0,n),a=i.find(t=>t.root.id===e||t.subagents.some(t=>t.id===e));a&&!s.includes(a)&&(s=[...s.slice(0,Math.max(0,n-1)),a]),t.push(...s.map(e=>({kind:"session",family:e})));let l=i.length-s.length;l>0&&t.push({kind:"showMore",projectKey:r.key,remaining:l})}}return t},[H,no,e4,_,na,e,nn,nl,e3]),nm=(0,i.useMemo)(()=>a(H).filter(e=>_.includes(e.root.id)),[H,_]),ng=function(e,t,n,r=-1){let i=Math.ceil((n||600)/26)+16,s=Math.max(0,Math.min(Math.floor(t/26)-8,e-i)),a=Math.min(e,s+i),l=Array.from({length:a-s},(e,t)=>s+t);return r>=0&&r<s&&l.unshift(r),r>=a&&r<e&&l.push(r),l}(np.length,tS,tj,np.findIndex(e=>"session"===e.kind&&e.family.root.id===tN)),nf=nh&&eR?(A=(D=eR.worktrees.length>=8)&&eb.trim()?eR.worktrees.filter(e=>(e.branch??ea(e.path,ef)).toLowerCase().includes(eb.trim().toLowerCase())):eR.worktrees,F=t4?t4.branch??ea(t4.path,ef):"…",(0,r.jsxs)("div",{ref:eY,className:"workspace-worktree-switcher",style:{minWidth:48,maxWidth:"60%",flex:"0 10000 auto"},children:[(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),ez(e=>!e),ey(!1)},onTouchStart:e=>e.stopPropagation(),title:t4?O("sidebar.switchWorktreeTitle",{path:t4.path}):O("sidebar.switchWorktree"),"aria-expanded":eP,"aria-haspopup":"listbox",style:{display:"flex",alignItems:"center",gap:4,height:22,maxWidth:"100%",minWidth:0,padding:"0 4px",background:eP?"var(--bg-hover)":"none",border:"none",borderRadius:4,cursor:"pointer",fontSize:11,lineHeight:1.3,color:"var(--text-dim)",textAlign:"left",overflow:"hidden",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{eP||(e.currentTarget.style.background="none"),e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,fontSize:11},children:F})]}),eP&&(0,r.jsxs)("div",{role:"menu",className:"menu-surface",style:{position:"absolute",top:"calc(100% + 4px)",left:2,right:2,zIndex:100},children:[D&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,height:28,padding:"0 8px",marginBottom:4,borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{className:"sidebar-dropdown-filter-input",value:eb,onChange:e=>ew(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(ew(""),ez(!1))},placeholder:O("sidebar.filterWorktrees"),autoFocus:!0,style:{flex:1,minWidth:0,fontSize:12,fontFamily:"inherit",padding:"2px 0",border:"none",outline:"none",background:"transparent",color:"var(--text)"}}),eb&&(0,r.jsx)("button",{type:"button",onClick:()=>ew(""),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,padding:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},title:O("chat.clear"),children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto",scrollbarWidth:"none"},children:[A.map(e=>{let t=e.path===t8;return eq===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,height:28,padding:"0 4px 0 8px",borderRadius:4,background:"color-mix(in srgb, var(--danger) 7%, transparent)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:O("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void t9(e.path,!0),disabled:eU,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:4,color:"#fff",fontSize:11,cursor:"pointer",flexShrink:0},children:O("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eK(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:O("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":t,onClick:()=>{eg(e.path),ez(!1),eH(null),ew("")},title:e.path,style:{flex:1},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(el,{text:e.branch??ea(e.path,ef),style:{flex:1}}),e.isMain&&(e.branch??"").toLowerCase()!==O("sidebar.main").toLowerCase()&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:O("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void t9(e.path,!1),disabled:eU,title:O("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",borderRadius:4,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--danger)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),D&&0===A.length&&eb.trim()&&(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:O("sidebar.noMatchingWorktrees")})]}),eD?(0,r.jsxs)("div",{style:{marginTop:4,padding:"6px 4px 2px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("input",{ref:eZ,className:"sidebar-dropdown-filter-input",value:eF,onChange:e=>{eB(e.target.value),eH(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t7()),"Escape"===e.key&&(eA(!1),eB(""),eH(null))},placeholder:O("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:4,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void t7(),disabled:eU||!eF.trim(),style:{flex:1,padding:"4px 0",background:"var(--primary)",border:"none",borderRadius:4,color:"var(--primary-contrast)",fontSize:11,cursor:eU||!eF.trim()?"not-allowed":"pointer",opacity:eU||!eF.trim()?.65:1},children:eU?O("sidebar.creating"):O("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eA(!1),eB(""),eH(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:O("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:e=>{e.stopPropagation(),eA(!0),eH(null),setTimeout(()=>eZ.current?.focus(),0)},title:O("sidebar.createWorktreeTitle"),style:{marginTop:4,borderTop:"1px solid var(--border)",borderRadius:"0 0 4px 4px"},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:O("sidebar.newWorktree")})]}),eO&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eO})]})]})):null,nx=(t,i=!1)=>{let s=[t.root,...t.subagents],a=t.latestModified===t.root.modified?t.root:{...t.root,modified:t.latestModified},l=_.includes(t.root.id);return(0,r.jsx)("div",{onFocus:()=>tE(t.root.id),onBlur:()=>tE(null),children:(0,r.jsx)(eu,{session:a,indent:14,isSelected:s.some(t=>t.id===e),isRunning:s.some(e=>th.has(e.id)),isUnread:s.some(e=>tm.has(e.id)),menuAt:tM?.id===t.root.id?tM:null,onOpenMenu:(e,n)=>{tT(null),tI({id:t.root.id,x:e,y:n})},onCloseMenu:()=>tI(null),onClick:()=>ne(t.root),onRenamed:tV,onOpenInNewTab:n?()=>n(t.root):void 0,isPinned:l,projectHint:i?ea(t.root.projectRoot??t.root.cwd,ef):void 0,onTogglePin:()=>void tJ(t.root.id),onDeleted:e=>{p?.(e),tV()}})})};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[ej&&(0,r.jsx)($,{initialPath:eS,busy:eM,error:eN,onCancel:()=>{ek(!1),eE(null)},onSelect:e=>void t3(e)}),tL&&(B=!!nd.get(tL.key)?.running,(0,r.jsxs)("div",{role:"menu",className:"project-context-menu menu-surface",style:{left:Math.min(tL.x+2,window.innerWidth-168),top:Math.min(tL.y+2,window.innerHeight-76)},children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{tT(null),eg(tL.cwd),eG(!0),d(!0)},children:[(0,r.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,r.jsx)("path",{d:"M4 5h4"}),(0,r.jsx)("path",{d:"M10 5h10"}),(0,r.jsx)("path",{d:"M4 12h4"}),(0,r.jsx)("path",{d:"M10 12h10"}),(0,r.jsx)("path",{d:"M4 19h4"}),(0,r.jsx)("path",{d:"M10 19h10"})]}),O("files.explorer")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",className:"is-danger",disabled:B||tP===tL.key,title:O(B?"sidebar.deleteProjectSessionsRunning":"sidebar.deleteProjectSessions"),onClick:()=>{tR({key:tL.key,x:tL.x,y:tL.y}),tT(null)},children:[(0,r.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,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),O("sidebar.deleteSessions")]})]})),nm.length>0&&(0,r.jsxs)("div",{style:{flexShrink:0,borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{className:"sidebar-section-row",children:(0,r.jsx)("button",{type:"button",onClick:()=>e2(e=>!e),className:"sidebar-section-label","aria-expanded":e1,children:(0,r.jsx)("span",{children:O("sidebar.pinned")})})}),e1&&(0,r.jsx)("div",{style:{padding:"0 4px"},children:nm.map(e=>(0,r.jsx)("div",{children:nx(e,!0)},e.root.id))})]}),(0,r.jsxs)("div",{ref:e$,className:"sidebar-section-row",style:{position:"relative"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>e0(e=>!e),className:"sidebar-section-label",children:(0,r.jsx)("span",{children:O("sidebar.projects")})}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[eQ&&!nn&&nl.filter(e=>(e4??no).has(e.key)).length>=2&&(0,r.jsx)(Q,{onClick:()=>e8(new Set),title:O("sidebar.collapseAll"),color:"var(--text-muted)",children:(0,r.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,r.jsx)("polyline",{points:"7 20 12 15 17 20"}),(0,r.jsx)("polyline",{points:"7 4 12 9 17 4"})]})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[nn&&(nc.running>0||nc.unread>0)&&(0,r.jsx)("span",{role:"status",title:O("sidebar.otherProjectActivity"),"aria-label":`${O("sidebar.otherProjectActivity")} (${nc.running+nc.unread})`,style:{display:"inline-flex",alignItems:"center"},children:nc.running>0?(0,r.jsx)(X,{size:11}):(0,r.jsx)("span",{style:{color:"var(--success)",fontSize:10},children:nc.unread})}),(0,r.jsx)(Q,{onClick:()=>{ey(e=>!e),ez(!1)},title:O(nn?"sidebar.switchProject":"sidebar.addProject"),ariaPressed:ev,color:ev?"var(--accent)":"var(--text-muted)",background:ev?"var(--bg-selected)":"none",children:nn?(0,r.jsx)("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,r.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})}):(0,r.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,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),(0,r.jsx)(Q,{onClick:()=>{ti(e=>{let t=!e;return t&&e0(!0),t}),ez(!1),ey(!1)},title:O("sidebar.toggleSessionSearch"),ariaPressed:tr,color:tr?"var(--accent)":"var(--text-muted)",background:tr?"var(--bg-selected)":"none",children:(0,r.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,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})})]}),ev&&(0,r.jsxs)("div",{role:"menu",className:"menu-surface",style:{position:"absolute",top:"calc(100% + 4px)",left:6,right:6,zIndex:100},children:[nn&&(0,r.jsx)("div",{style:{maxHeight:"min(50vh, 380px)",overflowY:"auto",scrollbarWidth:"none",marginBottom:4,paddingBottom:4,borderBottom:"1px solid var(--border)"},children:nl.map(e=>{let t=e.key===na?.key,n=nd.get(e.key);return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":t,onClick:()=>{eg(e.root),ey(!1)},title:e.root,style:{flex:1},children:[(0,r.jsx)(el,{text:ea(e.root,ef),style:{flex:1}}),n?.running?(0,r.jsx)(X,{size:11}):null,n?.unread?(0,r.jsx)("span",{style:{color:"var(--success)",fontSize:10},children:n.unread}):null]}),H.some(t=>m(t)===e.key)&&(0,r.jsx)(Q,{onClick:t=>{ey(!1),tR({key:e.key,x:t.clientX,y:t.clientY})},disabled:!!n?.running||tP===e.key,title:O(n?.running?"sidebar.deleteProjectSessionsRunning":"sidebar.deleteProjectSessions"),color:"var(--text-muted)",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.key)})}),(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:e=>{e.stopPropagation(),t5()},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:(0,r.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,r.jsx)("span",{children:O("sidebar.useDefaultDirectory")})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:e=>{e.stopPropagation(),t6()},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:O("sidebar.customPath")})]})]})]}),tr&&eQ&&(0,r.jsx)("div",{style:{padding:"4px 8px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:ts,maxLength:200,"aria-label":O("sidebar.searchSessions"),placeholder:O("sidebar.searchSessions"),onChange:e=>ta(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),ta(""))},className:"block h-[29px] w-full min-w-0 rounded-[4px] border border-border bg-bg px-[10px] text-xs text-text focus:outline-2 focus:outline-accent"})}),t$&&(()=>{let e=nl.find(e=>e.key===t$.key);if(!e)return null;let t=f(H,e.key).length;return(0,r.jsx)("div",{className:"project-context-menu menu-surface",style:{left:Math.min(t$.x+2,window.innerWidth-232),top:Math.min(t$.y+2,window.innerHeight-148)},children:(0,r.jsxs)("div",{role:"alertdialog","aria-labelledby":"delete-project-title","aria-describedby":"delete-project-detail",className:"project-confirm",children:[(0,r.jsx)("div",{id:"delete-project-title",children:O("sidebar.deleteProjectSessionsConfirm",{count:t})}),(0,r.jsx)("div",{id:"delete-project-detail",children:O("sidebar.deleteProjectSessionsDetail",{count:t})}),(0,r.jsxs)("div",{className:"project-confirm-actions",children:[(0,r.jsx)("button",{type:"button",autoFocus:!0,onClick:()=>tR(null),children:O("sidebar.cancel")}),(0,r.jsx)("button",{type:"button",className:"is-danger",onClick:()=>void nu(e),children:O("sidebar.delete")})]})]})})})(),(0,r.jsx)(Z,{open:tr&&eQ,query:ts,refreshKey:K,selectedSessionId:e,onSelectSession:ne,children:eQ&&(0,r.jsxs)("div",{ref:tw,onScroll:tU,style:{flex:eX&&(x||em)?"1 1 0":"1 1 auto",overflowY:"auto",scrollbarGutter:"stable",padding:"0",minHeight:80},children:[eh&&(0,r.jsx)("div",{style:{padding:"12px 14px",color:"var(--danger)",fontSize:12},children:eh}),tD&&(0,r.jsx)("div",{role:"alert",onClick:()=>tA(null),style:{padding:"6px 14px",color:"var(--danger)",fontSize:12,cursor:"pointer"},children:O("sidebar.deleteProjectSessionsFailed",{error:tD})}),!ed&&!eh&&!ns&&0===nl.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:O("sidebar.noSessions")}),np.length>0&&(0,r.jsx)("div",{style:{position:"relative",height:26*np.length},children:ng.map(e=>{let t=np[e];if("workspace"===t.kind){let n=(e4??no).has(t.project.key),i=t.project.key===na?.key,s=nd.get(t.project.key),a=i&&em?em:t.cwd,l=tW===t.project.key;return(0,r.jsxs)("div",{className:"workspace-list-row","data-active":i?"true":"false","data-pending-delete":l?"true":void 0,"data-expanded":!nn&&n?"true":void 0,onTouchStart:e=>t_(t.project.key,a,e),onTouchMove:tq,onTouchEnd:tK,onTouchCancel:tK,onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),tO.current||tT({key:t.project.key,cwd:a,x:e.clientX,y:e.clientY})},style:{position:"absolute",top:26*e,left:4,right:4,height:26,display:"flex",alignItems:"center",WebkitTouchCallout:"none",userSelect:"none"},children:[(0,r.jsxs)("button",{type:"button","aria-current":i?"page":void 0,"aria-expanded":nn?ev:n,onMouseDown:nn?e=>e.stopPropagation():void 0,onClick:()=>{if(tO.current){tO.current=!1;return}if(nn){ey(e=>!e),ez(!1);return}n&&e6(e=>{if(!(t.project.key in e))return e;let n={...e};return delete n[t.project.key],n}),e8(e=>{let n=new Set(e??no);return n.has(t.project.key)?n.delete(t.project.key):n.add(t.project.key),n})},title:t.project.root,style:{display:"flex",alignItems:"center",gap:4,flex:"1 1 auto",minWidth:0,height:"100%",padding:"0 4px",border:"none",background:"none",color:"inherit",cursor:"pointer",textAlign:"left",fontSize:12},children:[(0,r.jsx)(ee,{open:nn?ev:n}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:S(t.project.root)}),s?.running?(0,r.jsx)("span",{role:"status","aria-label":`${O("sidebar.agentRunning")} (${s.running})`,children:(0,r.jsx)(X,{size:11})}):null,s?.unread?(0,r.jsx)("span",{"aria-label":`${O("sidebar.newSessionActivity")} (${s.unread})`,style:{color:"var(--success)",fontSize:10},children:s.unread}):null]}),i?nf:null,(0,r.jsxs)("span",{className:"workspace-row-action",children:[(0,r.jsx)(Q,{onClick:()=>{eg(a),eG(!0),d(!0)},title:O("sidebar.openProjectExplorer",{path:a}),color:"var(--text-muted)",className:"workspace-explorer",children:(0,r.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,r.jsx)("path",{d:"M4 5h4"}),(0,r.jsx)("path",{d:"M10 5h10"}),(0,r.jsx)("path",{d:"M4 12h4"}),(0,r.jsx)("path",{d:"M10 12h10"}),(0,r.jsx)("path",{d:"M4 19h4"}),(0,r.jsx)("path",{d:"M10 19h10"})]})}),(0,r.jsx)(Q,{onClick:()=>{tO.current=!1,eg(a),e8(e=>new Set([...e??no,t.project.key])),nt(a)},title:O("sidebar.newSessionTitle",{path:a}),color:"var(--text-muted)",className:"workspace-new-session",marginRight:6,children:(0,r.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,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]},`workspace:${t.project.key}`)}return"showMore"===t.kind?(0,r.jsxs)("button",{type:"button",className:"workspace-show-more-button","aria-label":O("sidebar.showMoreSessionsLabel",{count:t.remaining}),onClick:()=>e6(e=>({...e,[t.projectKey]:(e[t.projectKey]??6)+Math.min(20,t.remaining)})),style:{position:"absolute",top:26*e,left:4,right:4,height:26},children:[(0,r.jsx)("span",{children:O("sidebar.showMoreSessions")}),(0,r.jsx)("span",{className:"workspace-show-more-count",children:t.remaining})]},`more:${t.projectKey}`):(0,r.jsx)("div",{style:{position:"absolute",top:26*e,left:4,right:4},children:nx(t.family)},t.family.root.id)})})]})}),(x||em)&&(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:eX?"1 1 0":"0 0 auto",minHeight:0,overflow:"hidden"},children:[(0,r.jsxs)("div",{className:"sidebar-section-row",children:[(0,r.jsx)("button",{onClick:()=>eG(e=>{let t=!e;return d(t),t}),className:"sidebar-section-label",children:(0,r.jsx)("span",{children:O("files.explorer")})}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[k&&(0,r.jsx)(Q,{onClick:()=>k(em??x),title:O("terminal.open"),color:"var(--text-muted)",children:(0,r.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,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),eX&&to>0&&(0,r.jsx)(Q,{onClick:()=>tu(e=>!e),title:O("sidebar.changedFiles",{count:to}),ariaPressed:!tc,color:tc?"var(--text-muted)":"var(--accent)",background:tc?"none":"var(--bg-selected)",children:(0,r.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,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6"}),(0,r.jsx)("path",{d:"M15 12h6"})]})}),eX&&(0,r.jsx)(Q,{onClick:()=>{tn(e=>!e)},title:O("sidebar.searchFiles"),ariaPressed:tt,color:tt?"var(--accent)":"var(--text-muted)",background:tt?"var(--bg-selected)":"none",children:(0,r.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,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}),eX&&(0,r.jsx)(Q,{onClick:()=>tb.current?.openUploadPicker(),disabled:e9,title:O("sidebar.uploadFilesTitle"),color:"var(--text-muted)",children:(0,r.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,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}),(0,r.jsx)(Q,{onClick:()=>{N?N():e7(e=>e+1)},title:O("sidebar.refreshExplorer"),color:"var(--text-muted)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]}),eX&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden",scrollbarGutter:"stable"},children:(0,r.jsx)(Y,{ref:tb,cwd:em??x,onOpenFile:j??(()=>{}),refreshKey:e5,onAtMention:E,onAtMentions:M,onUploadBusyChange:te,changesCollapsed:tc,onChangesCountChange:td,fileSearchOpen:tt,onFileSearchOpenChange:tn})})]})]})}function ed(){let{t:e}=(0,w.s)();return(0,r.jsx)(X,{size:14,title:e("sidebar.agentRunning"),ariaLabel:e("sidebar.agentRunning")})}function ec(){let{t:e}=(0,w.s)();return(0,r.jsx)("span",{title:e("sidebar.newSessionActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"5",fill:"var(--success)"}),(0,r.jsx)("path",{d:"M3.6 6.2l1.6 1.6 3.2-3.4",stroke:"#ffffff",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})}function eu({session:e,isSelected:t,isRunning:n,isUnread:s,menuAt:a=null,onOpenMenu:l,onCloseMenu:o,onClick:d,onRenamed:c,onOpenInNewTab:h,isPinned:m=!1,onTogglePin:g,projectHint:f,onDeleted:x,indent:v=0,depth:y=0,hasChildren:j=!1,collapsed:k=!1,onToggleCollapse:S}){let{locale:C,t:N}=(0,w.s)(),[E,M]=(0,i.useState)(!1),[I,L]=(0,i.useState)(!1),[T,$]=(0,i.useState)(""),[R,W]=(0,i.useState)(!1),[P,z]=(0,i.useState)(!1),D=(0,i.useRef)(null),A=(0,i.useRef)(null),F=(0,i.useRef)(null),B=(0,i.useRef)(!1),O=(0,i.useCallback)(t=>{if(R||I||e.transient)return;let n=t.touches[0];F.current={x:n.clientX,y:n.clientY},B.current=!1,A.current=setTimeout(()=>{B.current=!0,window.getSelection()?.removeAllRanges();try{navigator.vibrate?.(15)}catch{}l?.(n.clientX,n.clientY)},400)},[R,l,I,e.transient]),H=(0,i.useCallback)(e=>{if(!F.current||!A.current)return;let t=e.touches[0],n=Math.abs(t.clientX-F.current.x),r=Math.abs(t.clientY-F.current.y);(n>10||r>10)&&(clearTimeout(A.current),A.current=null)},[]),U=(0,i.useCallback)(()=>{A.current&&(clearTimeout(A.current),A.current=null)},[]);(0,i.useEffect)(()=>{if(I){let e=requestAnimationFrame(()=>D.current?.select());return()=>cancelAnimationFrame(e)}},[I]);let _=u(e.firstMessage)??e.firstMessage,q=p(e),K=(0,i.useCallback)(t=>{t?.stopPropagation(),e.transient||($(p(e)),L(!0))},[e]),V=(0,i.useCallback)(async()=>{let t=T.trim();if(L(!1),T!==q&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[T,e.id,e.name,c,q]),J=(0,i.useCallback)(async()=>{if(!e.transient){W(!1),z(!0);try{let t=await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"});if(!t.ok)throw Error(`HTTP ${t.status}`);x?.(e.id)}catch{z(!1)}}},[e.id,e.transient,x]),Y=(0,i.useCallback)(e=>{e.stopPropagation(),J()},[J]),Z=(0,i.useCallback)(e=>{e.stopPropagation(),W(!1)},[]),X=(0,i.useCallback)(t=>{t.preventDefault(),t.stopPropagation(),B.current||e.transient||!function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)}({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{c?.()}})&&l?.(t.clientX,t.clientY)},[l,c,e.cwd,e.id,e.name,e.path,e.transient]),Q=e=>()=>{o?.(),e()};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"session-list-row",onClick:e=>{if(B.current){B.current=!1,e.preventDefault(),e.stopPropagation();return}R||I||d()},onDoubleClick:()=>{R||I||e.transient||h?.()},onTouchStart:O,onTouchMove:H,onTouchEnd:U,onTouchCancel:U,onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1!==e.button||!h||R||I||(e.preventDefault(),e.stopPropagation(),h())},onContextMenu:R||I?void 0:X,onMouseEnter:()=>M(!0),onMouseLeave:()=>{M(!1)},style:{height:26,position:"relative",display:"flex",alignItems:"center",paddingLeft:14+v+14*y,paddingRight:8,cursor:R||I?"default":"pointer",background:R?"color-mix(in srgb, var(--danger) 6%, transparent)":t?"var(--bg-selected)":E?"var(--bg-hover)":"transparent",borderRadius:4,transition:"background 0.1s",opacity:P?.5:1,gap:6,overflow:"hidden",userSelect:"none",WebkitUserSelect:"none",WebkitTouchCallout:"none"},children:R?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:N("sidebar.deleteSession",{title:q.slice(0,22)+(q.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:Y,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:24,padding:"0 8px",background:"var(--danger)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:12,whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),N("sidebar.delete")]}),(0,r.jsx)("button",{onClick:Z,style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:12,whiteSpace:"nowrap"},children:N("sidebar.cancel")})]})]}):I?(0,r.jsx)("input",{ref:D,value:T,onChange:e=>$(e.target.value),onBlur:V,onKeyDown:e=>{"Enter"===e.key&&V(),"Escape"===e.key&&L(!1)},autoFocus:!0,className:"session-rename-input",style:{flex:1,minWidth:0,fontSize:12,fontFamily:"inherit",lineHeight:1.4,padding:"1px 6px",border:"1px solid var(--accent)",borderRadius:4,outline:"none",background:"var(--bg)",color:"var(--text)",height:24,boxSizing:"border-box"}}):(0,r.jsxs)(r.Fragment,{children:[g&&!e.transient&&(0,r.jsx)("button",{type:"button",className:`session-row-pin${m?" is-pinned":""}`,onClick:e=>{e.stopPropagation(),g()},onDoubleClick:e=>e.stopPropagation(),title:N(m?"sidebar.unpinSession":"sidebar.pinSession"),"aria-label":N(m?"sidebar.unpinSession":"sidebar.pinSession"),"aria-pressed":m,style:{position:"absolute",left:v+14*y-10,top:3,display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,background:"transparent",border:"none",borderRadius:4,color:t||E?"var(--text)":"var(--text-muted)",cursor:"pointer"},children:(0,r.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,r.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"22"}),(0,r.jsx)("path",{d:"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"})]})}),y>0&&(0,r.jsx)(G,{size:13,style:{color:"var(--accent)"}}),(0,r.jsx)("button",{type:"button","aria-current":t?"page":void 0,style:{flex:1,minWidth:0,padding:0,border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:5,minWidth:0,fontSize:12,lineHeight:1.4,color:t||E?"var(--text)":"var(--text-muted)"},title:(e.name||_||e.id)+(f?`
2
- ${f}`:""),children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:q})})}),e.isWorktree&&e.branch&&(0,r.jsxs)("span",{title:`Worktree: ${e.branch}
3
- ${e.cwd}`,style:{display:"flex",alignItems:"center",gap:3,maxWidth:82,color:"var(--text-dim)",flexShrink:1,fontSize:10,lineHeight:1.3},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e.branch})]}),j&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),S?.()},title:N(k?"sidebar.expandSubagents":"sidebar.collapseSubagents"),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:k?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("div",{className:"session-row-meta",style:{display:"flex",alignItems:"center",justifyContent:"flex-end",flexShrink:0,color:"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:n?(0,r.jsx)(ed,{}):s?(0,r.jsx)(ec,{}):(0,r.jsx)("span",{title:e.modified,children:(0,b.wA)(e.modified,C)})}),!e.transient&&(0,r.jsx)("div",{className:"session-row-actions",style:{display:"flex",alignItems:"center",gap:2,position:"absolute",right:6,top:0,height:"100%",background:t?"var(--bg-selected)":E?"var(--bg-hover)":"var(--bg-panel)",paddingLeft:4,borderRadius:4},children:h&&(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),h()},title:N("chatTabs.openInNewTab",{defaultValue:"在新标签页打开"}),"aria-label":N("chatTabs.openInNewTab",{defaultValue:"在新标签页打开"}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,background:"transparent",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=t?"var(--bg-hover)":"var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.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,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),(0,r.jsx)("polyline",{points:"15 3 21 3 21 9"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})})]})}),a&&(0,r.jsxs)("div",{role:"menu",className:"project-context-menu menu-surface",style:{left:Math.min(a.x+2,window.innerWidth-168),top:Math.min(a.y+2,window.innerHeight-128)},children:[h&&(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:Q(h),children:[(0,r.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,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),(0,r.jsx)("polyline",{points:"15 3 21 3 21 9"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),N("chatTabs.openInNewTab")]}),g&&(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:Q(g),children:[(0,r.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,r.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"22"}),(0,r.jsx)("path",{d:"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"})]}),N(m?"sidebar.unpinSession":"sidebar.pinSession")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:Q(K),children:[(0,r.jsx)("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,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),N("sidebar.rename")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",className:"is-danger",onClick:Q(()=>W(!0)),children:[(0,r.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,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),N("sidebar.delete")]})]})]})}function eh({src:e,alt:t="",children:n,className:s,style:a}){let{t:l}=(0,w.s)(),[o,d]=(0,i.useState)(!1),c=(0,i.useRef)(null),u=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!o)return;let e=u.current;if(!e)return;let t=c.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),h.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[o]);let p=()=>{u.current?.open&&u.current.close(),d(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:c,type:"button",className:s,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...a},onClick:()=>d(!0),"aria-label":l("chat.previewImage"),"aria-haspopup":"dialog","aria-expanded":o,title:l("chat.previewImage"),children:n}),o&&(0,r.jsxs)("dialog",{ref:u,className:"image-preview-dialog","aria-label":l("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),p()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),p())},onClick:p,children:[(0,r.jsx)("img",{className:"image-preview-image",src:e,alt:t}),(0,r.jsx)("button",{ref:h,type:"button",className:"image-preview-close",onClick:p,"aria-label":l("chat.close"),title:l("chat.close"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}let ep="pi-image-result",em=[{model:"gpt-image-2.5-flare",label:"Flare"},{model:"gpt-image-2.5-sunburst",label:"Sunburst"},{model:"grok-imagine-image-2.0",label:"Grok"}],eg=["1:1","16:9","9:16","4:3","3:4","3:2","2:3"];function ef(e,t){let n=Math.abs(e),r=Math.abs(t);for(;r;){let e=n%r;n=r,r=e}return`${e/n}:${t/n}`}let ex=/@"([^"]+)"|@([^\s"]+)/g,ev=/\.(?:png|jpe?g|webp)$/i;function ey(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eb(e){if(!ey(e)||![ep,"pi-web:image"].includes(e.type)||1!==e.version)return null;let t=e.type===ep;return!("string"!=typeof e.path||!e.path||t&&(!e.path.startsWith(".pi/generated-images/")||e.path.split(/[\\/]/).includes("..")))&&"string"==typeof e.mimeType&&e.mimeType.startsWith("image/")&&"string"==typeof e.prompt&&e.prompt&&"string"==typeof e.connection&&e.connection&&(void 0===e.label||"string"==typeof e.label&&e.label)&&"string"==typeof e.model&&e.model&&"number"==typeof e.width&&Number.isSafeInteger(e.width)&&!(e.width<=0)&&"number"==typeof e.height&&Number.isSafeInteger(e.height)&&!(e.height<=0)&&(void 0===e.size||"string"==typeof e.size)&&(void 0===e.resolution||"string"==typeof e.resolution)&&(void 0===e.quality||"string"==typeof e.quality)&&(void 0===e.source||"string"==typeof e.source)?{...e,type:ep}:null}function ew(e,t,n){if("generate_image"!==e)return null;let r=eb(n);return r?r.source?"edit":"generate":ey(t)&&!0===t.new_image?"generate":ey(t)&&("string"==typeof t.target&&t.target||!0===t.use_last_attachment)?"edit":null}function ej(e,t){return`/api/files/${k(e)}?type=${t}`}function ek(e,t){return e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?e:t?E(t,e):e}function eS({path:e,cwd:t,onRemove:n}){let{t:i}=(0,w.s)(),s=ej(ek(e,t),"read");return(0,r.jsxs)("span",{className:"relative inline-block shrink-0 overflow-hidden rounded-md border border-border align-middle",style:{width:56,height:56},children:[(0,r.jsx)("img",{src:s,alt:"",className:"block h-full w-full object-cover"}),n?(0,r.jsx)("button",{type:"button",onClick:n,className:"absolute right-0.5 top-0.5 flex h-4 w-4 items-center justify-center rounded-full border-0 bg-black/55 text-white","aria-label":i("i18n.close"),children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}):null]})}function eC(e,t){return{aspectRatio:`${e} / ${t}`,width:`min(100%, calc(28rem * ${e/t}))`}}function eN({value:e,cwd:t,onEdit:n,onMention:s,showPrompt:a=!1,createdAt:l}){let o,d,c,u,{t:h,locale:p}=(0,w.s)(),m=eb(e),[g,f]=(0,i.useState)(!1);if(!m)return null;let x=ek(m.path,t),v=ej(x,"read"),y=(c=[(o=function(e,t){if(e<=0||t<=0)return ef(e,t);let n=e/t,r=eg[0],i=1/0;for(let e of eg){let[t,s]=e.split(":").map(Number),a=Math.abs(n-t/s)/(t/s);a<i&&(r=e,i=a)}return i<=.03?r:ef(e,t)}(m.width,m.height),d=`${m.width}\u00d7${m.height}`,o===`${m.width}:${m.height}`?d:`${o}(${d})`)],m.resolution&&c.push(m.resolution.toUpperCase()),(u="low"===m.quality?h("image.qualityLow"):"medium"===m.quality?h("image.qualityMedium"):"high"===m.quality?h("image.qualityHigh"):"auto"===m.quality?h("image.qualityAuto"):m.quality)&&c.push(u),c.join(" \xb7 ")),b=[m.label?m.label:m.model.includes("sunburst")?"Sunburst":m.model.includes("flare")?"Flare":m.model.includes("grok-imagine")?"Grok":m.model.includes("flash-image")?"Banana 2":m.model,l?function(e,t){let n=new Date(e),r=new Date,i=n.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit",hour12:!1});if(n.getFullYear()===r.getFullYear()&&n.getMonth()===r.getMonth()&&n.getDate()===r.getDate())return i;let s=n.toLocaleDateString(t,{month:"short",day:"numeric",year:n.getFullYear()!==r.getFullYear()?"numeric":void 0});return`${s} ${i}`}(l,p):void 0].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("article",{className:"mb-3 mt-2 w-fit max-w-full",children:[(0,r.jsxs)("div",{className:"relative max-w-full overflow-hidden rounded-[10px] border border-border/80 bg-bg-panel",style:eC(m.width,m.height),children:[g?(0,r.jsx)("div",{className:"flex h-full min-h-28 items-center justify-center px-4 text-xs text-text-muted",children:h("chat.imagePreviewUnavailable")}):(0,r.jsx)(eh,{src:v,alt:m.prompt,className:"block h-full w-full",children:(0,r.jsx)("img",{src:v,alt:m.prompt,loading:"lazy",onError:()=>f(!0),className:"block h-full w-full object-cover"})}),(0,r.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 flex justify-end p-2",children:(0,r.jsxs)("div",{className:"pointer-events-auto flex items-center rounded-full bg-black/50 p-0.5 text-white backdrop-blur-sm",children:[n?(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),n(m)},title:h("image.edit"),className:"h-7 rounded-full px-2.5 text-[11px] tracking-wide text-white/95 hover:bg-white/15",children:h("image.edit")}):null,n?(0,r.jsx)("span",{className:"mx-0.5 h-3 w-px bg-white/25","aria-hidden":"true"}):null,s?(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),s(m.path)},title:h("image.quote"),"aria-label":h("image.quote"),className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-white/95 hover:bg-white/15",children:(0,r.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,r.jsx)("path",{d:"M9 17 4 12l5-5"}),(0,r.jsx)("path",{d:"M20 18v-2a4 4 0 0 0-4-4H4"})]})}):null,(0,r.jsx)("a",{href:ej(x,"download"),download:!0,title:h("i18n.downloadFile"),"aria-label":h("i18n.downloadFile"),onClick:e=>e.stopPropagation(),className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-white/95 hover:bg-white/15",children:(0,r.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,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m7 10 5 5 5-5M12 15V3"})]})})]})})]}),a&&m.prompt?(0,r.jsx)("p",{className:"mt-1.5 line-clamp-3 text-[12px] leading-snug text-text-muted",title:m.prompt,children:m.prompt}):null,y||b?(0,r.jsxs)("div",{className:`${a&&m.prompt?"mt-1":"mt-1.5"} max-w-full text-[11px] leading-snug tracking-wide text-text-muted`,title:m.model,children:[y,y&&b?" \xb7 ":null,b]}):null]})}function eE({prompt:e,size:t,width:n,height:i,previewUrl:s}){let{t:a}=(0,w.s)(),{w:l,h:o}=function(e,t){if(e&&"auto"!==e){let t=/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(e.trim());if(t)return{w:Number(t[1]),h:Number(t[2])};let n=/^(\d+)x(\d+)$/.exec(e.trim());if(n)return{w:Number(n[1]),h:Number(n[2])}}return t?.width&&t.height?{w:t.width,h:t.height}:{w:1,h:1}}(t,{width:n,height:i});return(0,r.jsxs)("article",{className:"mb-3 mt-2 w-fit max-w-full",children:[(0,r.jsxs)("div",{role:"status","aria-label":a("image.generating"),className:"relative max-w-full overflow-hidden rounded-[10px] border border-border/80 bg-bg-panel",style:eC(l,o),children:[s?(0,r.jsx)("img",{src:s,alt:"",className:"absolute inset-0 h-full w-full object-cover opacity-35"}):null,(0,r.jsx)("div",{className:"image-pending-sheen","aria-hidden":"true"})]}),e?(0,r.jsx)("p",{className:"mt-1.5 line-clamp-3 text-[12px] leading-snug text-text-muted",children:e}):null]})}let eM=["off","minimal","low","medium","high","xhigh","max"],eI=RegExp(`:(${eM.join("|")})$`),eL=new Map;function eT(e){return`pi-chat-draft:${encodeURIComponent(e)}`}function e$(){try{return window.sessionStorage}catch{return null}}function eR(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function eW(e){return!e.value&&0===e.images.length}function eP(e){let t=eL.get(e)??function(e){try{let t=e$()?.getItem(eT(e));if(!t)return null;let n=JSON.parse(t);if("string"!=typeof n.value||!Array.isArray(n.images)||!n.images.every(e=>"string"==typeof e?.data&&"string"==typeof e?.mimeType))return null;return eR(n)}catch{return null}}(e);return t&&!eL.has(e)&&eL.set(e,t),t?eR(t):null}function ez(e,t){if(eW(t))return eD(e),!0;let n=eR(t);eL.set(e,n);let r=e$();if(!r)return!1;try{return r.setItem(eT(e),JSON.stringify(n)),!0}catch{return r.removeItem(eT(e)),!1}}function eD(e){eL.delete(e);try{e$()?.removeItem(eT(e))}catch{}}function eA(e,t){return e.trim()?t.trim()?`${e}
4
-
5
- ${t}`:e:t}function eF(e){return{data:e.data,mimeType:e.mimeType}}function eB(e,t,n,r){return{value:eA(e,n),images:[...t??[],...r].map(eF)}}function eO(e,t,n){if(e===t)return n?eR(n):eP(t);let r=eP(e),i=n&&!eW(n)?eR(n):r??(n?eR(n):null),s=eP(t);if(eD(e),!i)return s;let a=s?eB(s.value,s.images,i.value,i.images):i;return ez(t,a),eR(a)}function eH(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function eU(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function e_(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function eq(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function eK({active:e,size:t=13,className:n,style:i}){return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"2.4 2.4 19.2 19.2",fill:"none",stroke:"currentColor",strokeWidth:.8*R(t),strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:n,style:{flexShrink:0,color:e?"var(--accent)":"currentColor",display:"block",...i},children:[(0,r.jsx)("path",{d:"M9.5 4a3.5 3.5 0 0 0-3.5 3.5c0 .34.05.67.14.98A4 4 0 0 0 4 12c0 1.9 1.3 3.5 3.1 3.9A3.5 3.5 0 0 0 10.5 19h1"}),(0,r.jsx)("path",{d:"M14.5 4a3.5 3.5 0 0 1 3.5 3.5c0 .34-.05.67-.14.98A4 4 0 0 1 20 12c0 1.9-1.3 3.5-3.1 3.9A3.5 3.5 0 0 1 13.5 19h-1"}),(0,r.jsx)("path",{d:"M12 4v16"})]})}let eV="(max-width: 640px)",eJ=e=>(function(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)})(eV,e),eY=()=>!!window.matchMedia&&window.matchMedia(eV).matches;function eZ(){return!1}function eX(){return(0,i.useSyncExternalStore)(eJ,eY,eZ)}let eG="pi-chat-content-width",eQ="pi-chat-content-font-size",e0={width:820,fontSize:14},e1=null,e2=new Set;function e4(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function e8(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function e3(e){try{return window.localStorage.getItem(e)}catch{return null}}function e6({width:e,fontSize:t}){"u">typeof document&&(document.documentElement.style.setProperty("--chat-content-max-width",`${e}px`),document.documentElement.style.setProperty("--chat-content-font-size",`${t}px`))}function e5(){return e1||e6(e1={width:e4(e3(eG)),fontSize:e8(e3(eQ))}),e1}function e7(e){return e2.add(e),()=>{e2.delete(e)}}function e9(e,t){let n="width"===e?e4(t):e8(t);e6(e1={...e5(),[e]:n});try{window.localStorage.setItem("width"===e?eG:eQ,String(n))}catch{}e2.forEach(e=>e())}let te=e=>e9("width",e),tt=e=>e9("fontSize",e);function tn(){return{...(0,i.useSyncExternalStore)(e7,e5,()=>e0),setWidth:te,setFontSize:tt}}var tr=n(14755);function ti(e,t){if(null==e||Number.isNaN(e))return"?";if(e<=0)return"0";if(e<1e3)return String(e);if(e>=1e6){let t=Math.round(e/1e6*100)/100;return`${t}M`}let n=e/1e3;if(n<10){let e=Math.round(10*n)/10;return`${e}k`}return`${Math.round(n).toLocaleString(t)}k`}let ts="pi-shift-enter-to-send";function ta(){try{return"true"===window.localStorage.getItem(ts)}catch{return!1}}let tl=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function to(e,t){return tl.compare(e.name||e.modelId,t.name||t.modelId)||tl.compare(e.provider,t.provider)||tl.compare(e.modelId,t.modelId)}function td({options:e,value:t,onChange:n,onClear:s,emptyLabel:a,selectedLabel:l,disabled:o=!1,busy:d=!1,isAutoSelection:c=!1,ariaLabel:u,variant:h="toolbar",placement:p="up"}){let m,g,f,x,v,y,b,w,j,k=(0,i.useRef)(null),S=(0,i.useRef)(null),C=(0,i.useRef)(null),N=(0,i.useId)(),[E,M]=(0,i.useState)(!1),[I,L]=(0,i.useState)(-1),[T,$]=(0,i.useState)(null),R=o||d,W=(0,i.useMemo)(()=>[...e].sort(to),[e]),P=[];for(let e of W){let t=P.find(t=>t.provider===e.provider);t?t.options.push(e):P.push({provider:e.provider,options:[e]})}let z=l??(t?W.find(e=>e.modelId===t.modelId&&e.provider===t.provider)?.name??t.modelId:a??(W.length>0?"Select model":"No models")),D=(0,i.useMemo)(()=>s?[null,...W]:W,[s,W]),A=D.findIndex(e=>null!==e?e.modelId===t?.modelId&&e.provider===t?.provider:!t),F=I>=0&&D.length?Math.min(I,D.length-1):-1,B=F>=0?`${N}-option-${F}`:void 0,O=(0,i.useCallback)(()=>{let e=S.current?.getBoundingClientRect();e&&$({top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width})},[]);(0,i.useEffect)(()=>{let e=e=>{k.current&&!k.current.contains(e.target)&&C.current&&!C.current.contains(e.target)&&M(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{R&&M(!1)},[R]),(0,i.useEffect)(()=>{if(!E)return;O();let e=window.visualViewport;return window.addEventListener("scroll",O,!0),window.addEventListener("resize",O),e?.addEventListener("scroll",O),e?.addEventListener("resize",O),()=>{window.removeEventListener("scroll",O,!0),window.removeEventListener("resize",O),e?.removeEventListener("scroll",O),e?.removeEventListener("resize",O)}},[E,O]),(0,i.useEffect)(()=>{E||L(-1)},[E]),(0,i.useEffect)(()=>{if(!E)return;let e=B??(A>=0?`${N}-option-${A}`:void 0);e&&document.getElementById(e)?.scrollIntoView({block:"nearest"})},[E,B,A,N]);let H="field"===h?{display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,height:34,padding:"0 9px",overflow:"hidden",border:"1px solid var(--border)",borderRadius:4,background:R?"var(--bg-panel)":"var(--bg)",color:R?"var(--text-dim)":"var(--text)",cursor:R?"default":"pointer",fontSize:12,textAlign:"left"}:{},U=e=>{let r=e.modelId===t?.modelId&&e.provider===t?.provider;M(!1),(!r||c)&&n(e.provider,e.modelId)};return(0,r.jsxs)("div",{ref:k,className:`model-selector is-${h}${R?" is-disabled":""}`,style:{position:"relative",width:"field"===h?"100%":void 0,minWidth:0,display:"toolbar"===h?"flex":void 0,alignItems:"toolbar"===h?"center":void 0},onKeyDown:e=>{"Escape"===e.key&&E&&(e.preventDefault(),e.stopPropagation(),M(!1))},children:[(0,r.jsxs)("button",{ref:S,type:"button",role:"combobox","aria-label":u,"aria-haspopup":"listbox","aria-controls":N,"aria-activedescendant":E?B:void 0,"aria-expanded":E,onKeyDown:e=>{if("Escape"===e.key&&E){e.preventDefault(),M(!1);return}if("ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),!E){O(),L(A>=0?A:0),M(!0);return}let t="ArrowDown"===e.key?1:-1;L(e=>D.length?e<0?A>=0?A:t>0?0:D.length-1:(e+t+D.length)%D.length:0);return}if(E&&D.length){if("Home"===e.key||"End"===e.key)e.preventDefault(),L("Home"===e.key?0:D.length-1);else if("Enter"===e.key||" "===e.key){e.preventDefault();let t=D[F];null===t?(M(!1),s?.()):t&&U(t)}}},"aria-busy":d||void 0,disabled:R,title:d?"Switching model":R?z:W.length>0||s?"Change model":"No available models",className:"toolbar"===h?"composer-btn model-selector-trigger":void 0,style:H,onClick:()=>{O(),M(e=>!e)},onMouseEnter:"field"!==h||R?void 0:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:"field"!==h||R?void 0:e=>{e.currentTarget.style.background="var(--bg)"},children:[d?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",display:"block",flexShrink:0,transform:"translateY(-1px)"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):"field"===h?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}):null,(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1.25},children:z}),"field"===h&&(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),E&&T&&(m=window.visualViewport?.height??window.innerHeight,g=window.visualViewport?.width??window.innerWidth,f=T.top-8,x=m-T.bottom-8,y=Math.max(120,Math.min((v="up"===p||f>x)?f:x,.6*m)),b=v?{bottom:m-T.top+6}:{top:T.bottom+6},j={left:w=Math.max(8,T.left),width:"max-content",minWidth:T.width,maxWidth:g-w-8},(0,r.jsx)("div",{ref:C,id:N,role:"listbox","aria-label":u,"aria-activedescendant":B,className:"menu-surface is-scrolling",style:{position:"fixed",...b,...j,zIndex:500,display:"flex",flexDirection:"column",maxHeight:y,overflow:"hidden"},children:(0,r.jsxs)("div",{className:"menu-surface-scroll",children:[s&&(0,r.jsx)(tc,{id:`${N}-option-0`,active:!t,highlighted:0===F,label:a??"Default",onActive:()=>L(0),onClick:()=>{M(!1),s()}}),0===P.length?(0,r.jsx)("div",{style:{padding:"7px 8px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:"No available models"}):P.map(e=>(0,r.jsxs)("div",{className:"menu-surface-group",children:[P.length>1&&(0,r.jsx)("div",{className:"menu-surface-label",children:e.provider}),e.options.map(e=>(0,r.jsx)(tc,{id:`${N}-option-${D.indexOf(e)}`,active:e.modelId===t?.modelId&&e.provider===t?.provider,highlighted:F===D.indexOf(e),label:e.name,onActive:()=>L(D.indexOf(e)),onClick:()=>U(e)},`${e.provider}:${e.modelId}`))]},e.provider))]})}))]})}function tc({id:e,active:t,highlighted:n,label:i,onActive:s,onClick:a}){return(0,r.jsxs)("button",{id:e,type:"button",role:"option","aria-selected":t,"data-active":n||void 0,onClick:a,onMouseEnter:s,children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,visibility:t?"visible":"hidden"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}),(0,r.jsx)("span",{title:i,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:i})]})}let tu=["configured","chat-only","read-only","default","full"],th={configured:tr.Q8,"chat-only":"none","read-only":"read-only",default:"default",full:"full"},tp=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function tm(e,t){let n=null,r=()=>{n=null,t(function(e,t,n=8){return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let s=e.parentElement,a=s?.parentElement,l="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&l?.observe(s),a&&l?.observe(a);let o=window.visualViewport;return o?.addEventListener("resize",i),o?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{l?.disconnect(),o?.removeEventListener("resize",i),o?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let tg=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"},{name:"bug",description:"chat.commandBug",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"}];function tf(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return tg.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}function tx(e,t){return`${t.map(e=>eq(e,!1)).join("")}${e.trim()}`.trim()}let tv=["builtin","extension","prompt","skill"],ty={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},tb={builtin:0,extension:1,prompt:2,skill:3};function tw(e,t,n){let r=e.name.toLowerCase(),i=tj(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function tj(e,t){return"builtin"===e.source?t(e.description):e.description??""}function tk(e,t){requestAnimationFrame(()=>{let n=e.current;n&&(n.focus(),n.setSelectionRange(t,t))})}let tS={name:"<session-title>",session:"[session-id]",clone:"[new-title]"};function tC(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function tN(e){let t=()=>{var t;return t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})};if(!(e.size>1048576&&"image/gif"!==e.type)||"function"!=typeof createImageBitmap)return t();let n=await createImageBitmap(e).catch(()=>null);if(!n)return t();try{let r=Math.min(1,1024/Math.max(n.width,n.height)),i=document.createElement("canvas");i.width=Math.max(1,Math.round(n.width*r)),i.height=Math.max(1,Math.round(n.height*r));let s=i.getContext("2d");if(!s)return t();s.fillStyle="#fff",s.fillRect(0,0,i.width,i.height),s.drawImage(n,0,0,i.width,i.height);let a=i.toDataURL("image/jpeg",.85).split(",")[1];return a&&a.length<4*Math.ceil(e.size/3)?{data:a,mimeType:"image/jpeg"}:t()}catch{return t()}finally{n.close()}}function tE(e){return{data:e.data,mimeType:e.mimeType}}function tM(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function tI(e){return(e??[]).map(tM)}function tL(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}let tT=()=>()=>{};function t$({kind:e,text:t,action:n}){return(0,r.jsxs)("div",{className:"chat-input-queue-row",title:t,children:[(0,r.jsx)("span",{className:"chat-input-queue-kind",children:e}),(0,r.jsx)("span",{className:"chat-input-queue-text",children:t}),n]})}function tR({tone:e,title:t,body:n,onClose:i}){let s="error"===e?"var(--danger)":"var(--warning)";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid color-mix(in srgb, ${s} 30%, transparent)`,borderRadius:4,background:`color-mix(in srgb, ${s} 7%, transparent)`,color:s,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]}),i&&(0,r.jsx)("button",{type:"button",onClick:i,"aria-label":"Dismiss",style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:12,lineHeight:1},children:"\xd7"})]})}function tW({error:e}){let{t}=(0,w.s)();return e?(0,r.jsx)(tR,{tone:"error",title:t("chat.modelError"),body:e}):null}function tP({warnings:e}){let{t}=(0,w.s)();return e&&0!==e.length?(0,r.jsx)(tR,{tone:"warning",title:t(e.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:e.join("\n")}):null}let tz=(0,i.forwardRef)(function({onSend:e,onOpenImageGeneration:t,onAbort:n,onSteer:s,onFollowUp:a,isStreaming:l,disabled:o=!1,model:d,isAutoModelSelection:c,modelNames:u,modelList:h,modelError:p,modelScopeWarnings:m,onModelChange:g,modelSwitching:f,onCompact:x,onAbortCompaction:v,isCompacting:y,compactError:b,compactResult:j,toolPreset:k,onToolPresetChange:S,contextUsage:C,cacheHitRate:N,onOpenSessionStats:E,thinkingLevel:M,onThinkingLevelChange:I,availableThinkingLevels:L,thinkingLevelMap:T,retryInfo:$,queuedMessages:R,inputHistory:W=[],onRecallQueue:z,slashCommands:D,slashCommandsLoading:F,onLoadSlashCommands:B,onBuiltinCommand:O,onAudioUnlock:H,onPromptWithStreamingBehavior:U,draftKey:_,onDraftChange:q,draftPersistenceWarning:K=!1,cwd:V,compact:J=!1},Y){let Z,X,G,Q,ee,et,{t:en}=(0,w.s)(),{fontSize:er}=tn(),ei=eX(),es=(0,i.useSyncExternalStore)(tT,ta,()=>!1),[ea,el]=(0,i.useState)(!1),eo=(0,i.useId)(),[ed,ec]=(0,i.useState)(()=>_?eP(_)?.value??"":""),[eu,eh]=(0,i.useState)("root"),[ep,em]=(0,i.useState)(!1),[eg,ef]=(0,i.useState)(!1),[ex,ev]=(0,i.useState)(!1),[ey,eb]=(0,i.useState)(!1),[ew,ej]=(0,i.useState)(!1),[ek,eC]=(0,i.useState)([]),eN=(0,i.useRef)([]);eN.current=ek;let[eE,eI]=(0,i.useState)(()=>_?tI(eP(_)?.images):[]),eL=ed.trimStart(),eT=0===eE.length&&eL.startsWith("!"),e$=eT&&eL.startsWith("!!"),[eR,eW]=(0,i.useState)(!1),[eF,eq]=(0,i.useState)(null),[eV,eJ]=(0,i.useState)(0),[eY,eZ]=(0,i.useState)(null),[eG,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(null),[e8,e3]=(0,i.useState)(0),[e6,e5]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[ts,tl]=(0,i.useState)(0),to=(0,i.useRef)(null),[tc,tM]=(0,i.useState)(!1),[tz,tD]=(0,i.useState)(null),[tA,tF]=(0,i.useState)(!1),[tB,tO]=(0,i.useState)(null),[tH,tU]=(0,i.useState)(null),t_=V&&tH?.cwd===V?tH.values:{},tq=(0,i.useRef)(null),tK=(0,i.useRef)(null),tV=(0,i.useRef)(null),tJ=(0,i.useRef)(null),tY=(0,i.useRef)(null),tZ=(0,i.useRef)(null),tX=(0,i.useRef)(null),tG=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(!1),t1=(0,i.useRef)(0),t2=(0,i.useRef)(!1),t4=(0,i.useRef)(null),t8=(0,i.useRef)([]),t3=(0,i.useRef)(null),t6=(0,i.useRef)([]),t5=(0,i.useRef)(!1),t7=(0,i.useRef)([]),t9=(0,i.useRef)(null),ne=(0,i.useRef)(null),nt=(0,i.useRef)(0),nn=(0,i.useRef)(_),nr=(0,i.useRef)(ed),ni=(0,i.useRef)(eE),ns=(0,i.useRef)(0);nr.current=ed,ni.current=eE,(0,i.useImperativeHandle)(Y,()=>({insertIfEmpty(e){let t=tq.current;(t?t.value:ed).trim()||(nr.current=e,ec(e),eQ(null),requestAnimationFrame(()=>{t&&t.focus()}))},replaceMessage(e){var t,n,r;let i=tq.current;if(t=i?i.value:ed,n=ni.current.length,r=ns.current,t.trim()||0!==n||0!==r)return;let s="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),a=tI("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return!function(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}(r)?[]:[r]}));nr.current=s,ni.current=a,ec(s),eQ(null),tt(!1),eI(e=>(e.forEach(tL),a)),requestAnimationFrame(()=>{i&&i.focus()})},prependText(e){if(!e.trim())return;let t=tq.current,n=[e,t?t.value:ed].filter(e=>e.trim()).join("\n\n");nr.current=n,ec(n),eQ(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length))})},rekeyDraft(e,t){if(e===t)return;if(nn.current!==e)return void eO(e,t);let n={value:nr.current,images:ni.current.map(tE)},r=eO(e,t,n)??{value:"",images:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType);if(nn.current=t,i)return;let s=tI(r.images);nr.current=r.value,ni.current=s,ec(r.value),eI(e=>(e.forEach(tL),s)),eQ(null),tt(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=nn.current,i=n??r,s=i===r,a=!s&&i?eP(i):null,l=eB(e,t,s?nr.current:a?.value??"",s?ni.current.map(tE):a?.images??[]);if(i&&ez(i,l),!s)return;let o=tI(l.images);nr.current=l.value,ni.current=o,ec(t=>{let n=eA(e,t);return nr.current=n,n}),eQ(null),tt(!1),eI(e=>(e.forEach(tL),ni.current=o,o)),requestAnimationFrame(()=>{let e=tq.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))})},insertText(e){let t=tq.current;if(!t)return void ec(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),s=t.value.slice(r),a=i.length>0&&!i.endsWith(" ")?" ":"",l=i+a+e+s;nr.current=l,ec(l),eQ(null),requestAnimationFrame(()=>{if(!t)return;let r=n+a.length+e.length;t.setSelectionRange(r,r),t.focus()})},addImages(e){na(e)},mentionImage(e){eC(t=>t.includes(e)?t:[...t,e]),requestAnimationFrame(()=>tq.current?.focus())},removeAttachedImage(e){let t=ni.current.findIndex(t=>t.data===e);t>=0&&nl(t)}}));let na=(0,i.useCallback)(async e=>{if(J)return;let t=Math.max(0,10-ni.current.length-ns.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(!n.length)return;let r=nt.current;ns.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await tN(e),previewUrl:URL.createObjectURL(e)})));eI(t=>{if(r!==nt.current)return e.forEach(tL),t;let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(tL);let i=[...t,...n];return ni.current=i,i})}finally{ns.current-=n.length}},[J]),nl=(0,i.useCallback)(e=>{eI(t=>{let n=[...t],[r]=n.splice(e,1);return r&&tL(r),ni.current=n,n})},[]),no=(0,i.useCallback)(()=>{ni.current=[],eI(e=>(e.forEach(tL),[]))},[]),nd=(0,i.useCallback)(()=>{nt.current+=1,to.current=null,nr.current="",ec(""),eQ(null),tt(!1),_&&eD(_),nn.current&&nn.current!==_&&eD(nn.current),no(),eN.current=[],eC([])},[no,_]);(0,i.useEffect)(()=>{_&&nn.current===_&&(tM(!ez(_,{value:ed,images:eE.map(tE)})),q?.(_,ed,eE.length))},[eE,_,q,ed]),(0,i.useEffect)(()=>{let e=nn.current;if(e===_)return;e&&ez(e,{value:nr.current,images:ni.current.map(tE)});let t=_?eP(_):null;nn.current=_;let n=t?.value??"",r=tI(t?.images);nt.current+=1,nr.current=n,ni.current=r,ec(n),eQ(null),tt(!1),eI(e=>(e.forEach(tL),r)),_&&q?.(_,n,r.length)},[_,q]);let nc=(0,i.useCallback)(()=>{let e=tq.current;if(!e)return;let t=e.parentElement;t&&(t.style.minHeight=`${t.offsetHeight}px`),e.style.overflowY="hidden",e.style.height="auto";let n=e.value?e.scrollHeight:0;n&&(e.style.height=`${Math.min(n,200)}px`),n>200&&(e.style.overflowY="auto"),t&&(t.style.minHeight="")},[]);(0,i.useLayoutEffect)(nc,[ed,er,nc]),(0,i.useEffect)(()=>{let e=tq.current;if(!e)return;let t=-1,n=new ResizeObserver(([e])=>{e.contentRect.width!==t&&(t=e.contentRect.width,nc())});return n.observe(e),()=>n.disconnect()},[nc]),(0,i.useEffect)(()=>()=>{nt.current+=1,ni.current.forEach(tL)},[]);let nu=(0,i.useCallback)(async e=>{if(eE.length||!e.startsWith("/")||!O)return!1;if(t5.current)return!0;t5.current=!0,e5(!0);try{var t,n;let r=await O(e);if(!r.handled)return!1;return r.error||(t=nr.current,n=ni.current.length,0!==n||t.trim()!==e)||nd(),!0}finally{t5.current=!1,e5(!1)}},[eE.length,nd,O]),nh=(0,i.useCallback)(async()=>{if(o)return;let t=ed.trim();if(eE.length>10)return;let n=tx(t,ek);if(!n&&!eE.length||(H?.(),(!l||tf(t))&&await nu(t)||l))return;let r=eE.length?eE:void 0;nd(),e(n,r)},[o,ed,eE,ek,l,nu,e,nd,H]),np=!J&&ed.startsWith("/")&&!/\s/.test(ed.slice(1))?ed.slice(1).toLowerCase():null,nm=null===np?[]:[...l?tg.filter(e=>e.availableWhileStreaming):tg,...D??[]].filter(e=>{let t=e.name.toLowerCase(),n=tj(e,en).toLowerCase();return t.includes(np)||n.includes(np)}).sort((e,t)=>{let n=tw(e,np,en)-tw(t,np,en);return 0!==n?n:tb[e.source]-tb[t.source]||tp.compare(e.name,t.name)}),{commands:ng,groups:nf}=(Z=0,{commands:(X=tv.map(e=>{let t=nm.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!tC(e,t_)),...t.filter(e=>tC(e,t_))]:t;return{source:e,items:n.map(e=>({command:e,index:Z++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:X}),nx=(()=>{if(J)return null;let e=eF??ed.length,t=ed.slice(0,e);if(t.includes("\n"))return null;let n=/^\/([^\s]+)\s(.*)$/.exec(t);return n&&tS[n[1]]?{command:n[1],signature:tS[n[1]],hasArgument:n[2].trim().length>0}:null})(),nv=1===nm.length?en(np?"chat.match":"chat.command"):en(np?"chat.matches":"chat.commands",{count:nm.length}),ny=!!ed.trim(),nb=eE.length>10,nw=!nb&&(ny||eE.length>0||ek.length>0),nj=!o&&!nb&&(ny||eE.length>0||ek.length>0),nk=eE.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(d,h)&&!e7;(0,i.useEffect)(()=>{0===eE.length&&e9(!1)},[eE.length]);let nS=(0,i.useCallback)((e,t)=>{if(!V)return void eQ(null);let n=t??e.length;eQ(eH(e.slice(0,n)))},[V]),nC=eG?.query??null,nN=i.useMemo(()=>null!==nC&&tz&&tz.cwd===V?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:e_(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:e_(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||eU(e.entry.path)-eU(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tz.entries,nC):[],[nC,tz,V]),nE=!!(nC&&tz?.clientTruncated&&tz.cwd===V);(0,i.useEffect)(()=>{if(!nE||!V||!nC)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(V)}&q=${encodeURIComponent(nC)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tO({cwd:V,query:nC,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nE,nC,V]);let nM=nE&&null!==tB&&tB.cwd===V&&tB.query===nC,nI=nM?tB.matches:nN,nL=null===eG?null:`${eG.start}:${+!!eG.quoted}:${eG.query}`;(0,i.useEffect)(()=>{if(null===nL){e1(!1),e3(0);return}e1(!0),e3(0)},[nL]);let nT=null!==eG;(0,i.useEffect)(()=>{if(!nT||!V)return;let e=t9.current;e&&e.cwd===V&&Date.now()-e.fetchedAt<1e4||ne.current===V||(ne.current=V,tF(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(V)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tD({cwd:V,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>eU(e.path)-eU(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),clientTruncated:!!e.clientTruncated,serverHardTruncated:!!e.serverHardTruncated}),t9.current={cwd:V,fetchedAt:Date.now()}}).catch(()=>{t9.current=null}).finally(()=>{ne.current=null,tF(!1)}))},[nT,V]);let n$=(0,i.useCallback)(e=>{if(!eG)return;let t=tq.current,n=t?.selectionStart??ed.length,r=ed.slice(0,eG.start),i=ed.slice(n);eG.quoted&&i.startsWith('"')&&(i=i.slice(1));let s=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eG.quoted),a=r+s.text+i,l=r.length+s.cursorOffset;nr.current=a,ec(a),eq(l),eQ(eH(a.slice(0,l))),tk(tq,l)},[eG,ed]);(0,i.useEffect)(()=>{e8>=nI.length&&e3(Math.max(0,nI.length-1))},[nI.length,e8]),(0,i.useEffect)(()=>{t6.current.length=nI.length},[nI.length]),(0,i.useEffect)(()=>{e0&&t6.current[e8]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e8,e0]),(0,i.useEffect)(()=>{ts>=W.length&&tl(Math.max(0,W.length-1))},[W.length,ts]),(0,i.useEffect)(()=>{t7.current.length=W.length},[W.length]),(0,i.useEffect)(()=>{te&&t7.current[ts]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ts,te]);let nR=(0,i.useCallback)(()=>{let e=to.current;to.current=null,e&&(nr.current=e.text,ec(e.text)),tt(!1)},[]),nW=(0,i.useCallback)(e=>{to.current=null,nr.current=e,ec(e),eq(e.length),tt(!1),tl(0),eQ(null),tk(tq,e.length)},[]),nP=(0,i.useCallback)(e=>{let t=`/${e.name} `;nr.current=t,ec(t),eq(t.length),eW(!1),eJ(0),tk(tq,t.length)},[]),nz=(0,i.useCallback)(e=>{let t=ed.trim();if(eE.length>10)return;let n=tx(t,ek);if(!n&&!eE.length)return;if(H?.(),!eE.length&&O&&tf(t))return void nu(t);let r=eE.length?eE:void 0;if(t.startsWith("/")&&U){nd(),U(t,"steer"===e?"steer":"followUp",r);return}nd(),"steer"===e&&s?s(n,r):"followup"===e&&a&&a(n,r)},[ed,eE,ek,O,U,s,a,nd,H,nu]),nD=(0,i.useCallback)(e=>{let t=e.nativeEvent,r=!ei&&ta(),i="Enter"===e.key&&e.shiftKey===r&&(!ei||e.ctrlKey||e.metaKey),o=Date.now()-t1.current<100,d=t0.current||t.isComposing||229===t.keyCode;if(i&&(d||o)){o&&e.preventDefault();return}if(te&&!d){if("ArrowDown"===e.key){e.preventDefault(),tl(e=>Math.min(Math.max(0,W.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tl(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),nR();return}if(("Tab"===e.key||i)&&W[ts]){e.preventDefault(),nW(W[ts]);return}}if(eR&&null!==np&&!d){if("ArrowDown"===e.key){e.preventDefault(),eJ(e=>0===ng.length?0:(e+1)%ng.length);return}if("ArrowUp"===e.key){e.preventDefault(),eJ(e=>0===ng.length?0:(e-1+ng.length)%ng.length);return}if("Escape"===e.key){e.preventDefault(),eW(!1);return}let t=ng[eV];if("Tab"===e.key&&t){e.preventDefault(),nP(t);return}if(i&&t)return void((e.preventDefault(),l&&("builtin"!==t.source||!0!==t.availableWhileStreaming)||"builtin"!==t.source||ed.trim()!==`/${t.name}`)?nP(t):(eW(!1),nh()))}if(e0&&null!==eG&&!d){if("ArrowDown"===e.key){e.preventDefault(),e3(e=>0===nI.length?0:(e+1)%nI.length);return}if("ArrowUp"===e.key){e.preventDefault(),e3(e=>0===nI.length?0:(e-1+nI.length)%nI.length);return}if("Escape"===e.key){e.preventDefault(),e1(!1);return}if(("Tab"===e.key||i)&&nI[e8]){e.preventDefault(),n$(nI[e8]);return}}if("ArrowUp"===e.key&&!ed&&!d&&!l&&W.length>0){e.preventDefault(),eW(!1),e1(!1),to.current={text:ed},tl(W.length-1),tt(!0);return}if("Escape"===e.key&&(ex||ey||ep||ew)){e.preventDefault(),ev(!1),eb(!1),ej(!1),eh("root"),em(!1);return}if("Escape"===e.key&&!d&&l&&n){e.preventDefault(),n();return}i&&(e.preventDefault(),l&&(s||a)?nz(e.altKey&&a||!s?"followup":"steer"):(l&&nw&&!tf(ed.trim())&&el(!0),nh()))},[ei,l,nw,s,a,n,ex,ey,ew,ep,eR,np,ng,eV,nP,nz,nh,e0,eG,nI,e8,n$,te,W,ts,nW,nR,ed]),nA=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!J&&t.length){e.preventDefault(),na(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:a,occurrence:l}of t){if(!s||!a)continue;let t=0;for(let n=0;n<=l&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let o=s.replace(/([\\[\]])/g,"\\$1"),d=a.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${o}](${d})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let a=e.currentTarget,l=a.selectionStart,o=a.value.slice(0,l)+s+a.value.slice(a.selectionEnd);e.preventDefault(),nr.current=o,ec(o),tt(!1),nS(o,l+s.length),requestAnimationFrame(()=>{a.focus(),a.setSelectionRange(l+s.length,l+s.length)})},[J,na,nS]);(0,i.useEffect)(()=>{if(null===np){eW(!1),eJ(0),t2.current=!1;return}eW(!0),eJ(0),!t2.current&&B&&(t2.current=!0,Promise.resolve(B()).catch(()=>{t2.current=!1}))},[np,B]),(0,i.useEffect)(()=>{if(!eR||!V)return;let e=!1;return tU({cwd:V,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(V)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tU({cwd:V,values:n})}).catch(()=>{e||tU({cwd:V,values:{}})}),()=>{e=!0}},[eR,V]),(0,i.useEffect)(()=>{eV>=ng.length&&eJ(Math.max(0,ng.length-1))},[ng.length,eV]),(0,i.useEffect)(()=>{t8.current.length=ng.length},[ng.length]),(0,i.useEffect)(()=>{eR&&t8.current[eV]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eV,eR]),(0,i.useLayoutEffect)(()=>{if(!eR||null===np)return void eZ(null);let e=t4.current;if(e)return tm(e,e=>{eZ(t=>t===e?t:e)})},[eR,np]),(0,i.useLayoutEffect)(()=>{if(!e0||null===eG)return void e4(null);let e=t3.current;if(e)return tm(e,e=>{e4(t=>t===e?t:e)})},[e0,eG]);let nF=h&&h.length>0?h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(u??{}).map(([e,t])=>({provider:d?.provider??"unknown",modelId:e,name:t})),nB=j?Math.max(0,j.tokensBefore-j.estimatedTokensAfter):0,nO=j?`${j.reason&&"manual"!==j.reason?`${j.reason[0].toUpperCase()}${j.reason.slice(1)} `:en("chat.compacted")} ${ti(j.tokensBefore)} -> ${ti(j.estimatedTokensAfter)} tokens (${en("chat.tokensSaved",{saved:ti(nB)})})`:null,nH=M?T?.[M]??M:"…",nU=Object.entries(th).find(([,e])=>e===(k??tr.Q8))?.[0]??"configured",n_="chat-only"===nU?en("chat.chatOnly"):nU,nq="configured"!==nU,nK=!!(S||x);(0,i.useEffect)(()=>{let e=e=>{let t=e.target;tK.current&&!tK.current.contains(t)&&em(!1),tV.current&&!tV.current.contains(t)&&ev(!1),tJ.current&&!tJ.current.contains(t)&&(eb(!1),eh("root")),tY.current&&!tY.current.contains(t)&&ej(!1),tX.current&&!tX.current.contains(t)&&ef(!1),!t4.current||t4.current.contains(t)||tq.current?.contains(t)||eW(!1),!t3.current||t3.current.contains(t)||tq.current?.contains(t)||e1(!1),!tG.current||tG.current.contains(t)||tq.current?.contains(t)||nR()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[nR]);let nV=C&&C.contextWindow>0?C.percent??(null!==C.tokens?C.tokens/C.contextWindow*100:null):null,nJ=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"chat-input-menu-chevron",children:(0,r.jsx)("path",{d:"M4 2.5 6.5 5 4 7.5"})}),nY=e=>(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"chat-input-menu-check",style:{visibility:e?"visible":"hidden"},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}),nZ=e=>{"Escape"===e.key&&(e.stopPropagation(),ev(!1),eb(!1),eh("root"),em(!1),ej(!1),tq.current?.focus())},nX=(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 19V5m-7 7 7-7 7 7"})}),nG=(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24","aria-hidden":"true",children:(0,r.jsx)("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2",fill:"currentColor"})}),nQ=ei?"Ctrl/Cmd+":es?"Shift+":"",n0=ei?["Control+","Meta+"]:[es?"Shift+":""],n1=n0.map(e=>`${e}Enter`).join(" "),n2=n0.map(e=>`${e}Alt+Enter`).join(" "),n4=R?.steering??[],n8=R?.followUp??[],n3=n4.length+n8.length,n6=z?(0,r.jsx)("button",{type:"button",className:"chat-input-queue-recall",onClick:z,title:en("chat.recallTitle"),"aria-label":en("chat.recall"),children:(0,r.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,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}):null,n5=l&&!!(s||a)&&nw,n7=n5&&!!(s&&a),n9=l?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"composer-btn is-icon chat-input-queue-action","aria-label":en("chat.stop"),title:en("chat.stopAgent"),inert:!n5||void 0,onClick:n,children:nG}),(0,r.jsxs)("div",{ref:tY,className:"chat-input-popover-anchor",children:[(0,r.jsx)("button",{type:"button",className:"composer-send","aria-label":n5?n7?en("chat.send"):s?en("chat.steer"):en("chat.followUp"):en("chat.stop"),title:n5?n7?`${en("chat.sendOptions")} (${nQ}Enter: steer \xb7 ${nQ}Alt+Enter: follow-up)`:`${s?en("chat.steerHint"):en("chat.followUpHint")} (${nQ}Enter)`:`${en("chat.stopAgent")} (Esc)`,"aria-keyshortcuts":n5?n1:"Escape","aria-haspopup":n7?"menu":void 0,"aria-expanded":n7?ew:void 0,onClick:n5?n7?()=>ej(e=>!e):()=>nz(s?"steer":"followup"):n,onKeyDown:n7?nZ:void 0,children:n5?nX:nG}),ew&&n7&&(0,r.jsxs)("div",{role:"menu",className:"chat-input-menu menu-surface",style:{right:0,minWidth:180},onKeyDown:nZ,children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",title:en("chat.steerHint"),"aria-keyshortcuts":n1,onClick:()=>{ej(!1),nz("steer")},children:[(0,r.jsx)("span",{children:"steer"}),!ei&&(0,r.jsxs)("span",{className:"chat-input-menu-note",children:[nQ,"Enter"]})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",title:en("chat.followUpHint"),"aria-keyshortcuts":n2,onClick:()=>{ej(!1),nz("followup")},children:[(0,r.jsx)("span",{children:"follow-up"}),!ei&&(0,r.jsxs)("span",{className:"chat-input-menu-note",children:[nQ,"Alt+Enter"]})]})]})]})]}):(0,r.jsx)("button",{type:"button",className:"composer-send","aria-label":en("chat.send"),title:nb?en("chat.tooManyImagesTitle"):en("chat.send"),onClick:nh,disabled:!nj,children:nX});(0,i.useEffect)(()=>{if(!l){el(!1),ej(!1);return}em(!1),eh("root"),ev(!1),eb(!1)},[l]);let re=`${eo}-history`,rt=`${eo}-slash`,rn=`${eo}-files`,rr=te&&W.length>0?re:eR&&null!==np?rt:e0&&null!==eG?rn:void 0,ri=rr===re&&void 0!==W[ts]?`${re}-${ts}`:rr===rt&&ng[eV]?`${rt}-${eV}`:rr===rn&&nI[e8]?`${rn}-${e8}`:void 0;return(0,r.jsxs)("fieldset",{disabled:e6,"aria-busy":e6,className:J?"chat-input is-compact":"chat-input",style:{flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:J?0:"0 16px 8px",paddingRight:16*!J,opacity:e6?.5:1,transition:"opacity 0.15s"},children:[!J&&(0,r.jsx)("input",{ref:tQ,type:"file",accept:"image/*",multiple:!0,disabled:o,style:{display:"none"},onChange:e=>{na(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{style:{maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(tW,{error:p}),(0,r.jsx)(tP,{warnings:m}),nb&&(0,r.jsx)(tR,{tone:"error",title:en("chat.tooManyImagesTitle"),body:en("chat.tooManyImagesBody",{count:eE.length,max:10})}),nk&&(G=h?.find(e=>e.provider===d?.provider&&e.id===d?.modelId),(0,r.jsx)(tR,{tone:"warning",title:en("chat.imageNotSupportedTitle"),body:en("chat.imageNotSupportedBody",{model:G?.name||d?.modelId||""}),onClose:()=>e9(!0)})),$&&(0,r.jsxs)("div",{className:"chat-input-feedback chat-input-feedback-warning",children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),en("chat.retrying",{attempt:$.attempt,max:$.maxAttempts}),$.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",$.errorMessage]})]}),nO&&(0,r.jsxs)("div",{className:"chat-input-feedback chat-input-feedback-success",children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nO]}),b&&(0,r.jsx)("div",{role:"alert",className:"chat-input-feedback chat-input-feedback-error chat-input-feedback-detail",style:{whiteSpace:"pre-wrap"},children:b}),ea&&l&&(0,r.jsx)("div",{role:"status",className:"chat-input-feedback chat-input-feedback-warning",children:en("chat.sendHeldWhileBusy")}),(tc||K)&&(0,r.jsx)("div",{role:"status",className:"chat-input-feedback chat-input-feedback-warning chat-input-feedback-draft",children:en("chat.draftPageOnly")}),(0,r.jsxs)("div",{ref:tZ,style:{position:"relative",minWidth:0},children:[nx&&!eR&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,bottom:"calc(100% + 6px)",zIndex:119,height:24,display:"inline-flex",alignItems:"center",gap:6,padding:"0 8px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 2px 8px rgba(0,0,0,0.06)",fontFamily:"var(--font-mono)",fontSize:11,lineHeight:1,color:"var(--text-dim)",opacity:nx.hasArgument?.45:1,pointerEvents:"none"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:"Usage:"}),(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["/",nx.command]}),(0,r.jsx)("span",{children:nx.signature})]}),te&&W.length>0&&(0,r.jsxs)("div",{ref:tG,className:"popover-surface",style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:en("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.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,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{id:re,role:"listbox",style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:W.map((e,t)=>{let n=t===ts;return(0,r.jsxs)("button",{ref:e=>{t7.current[t]=e},type:"button",id:`${re}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),nW(e)},onMouseEnter:()=>tl(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontVariantNumeric:"tabular-nums",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eR&&null!==np&&(0,r.jsxs)("div",{ref:t4,className:"popover-surface",style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eY?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eY}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:F?en("chat.loadingCommands"):en("chat.slashCommands",{label:nv})}),(0,r.jsx)("span",{children:en("chat.tabEnter")})]}),(0,r.jsx)("div",{id:rt,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:6},children:F||0!==nm.length?nf.map(e=>(0,r.jsxs)("section",{style:{marginBottom:8},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-6,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 8px 3px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,letterSpacing:"0.04em",textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:en(ty[e.source])}),(0,r.jsx)("span",{style:{fontVariantNumeric:"tabular-nums"},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:1},children:e.items.map(({command:e,index:t})=>{let n=t===eV,i=tC(e,t_);return(0,r.jsxs)("button",{ref:e=>{t8.current[t]=e},type:"button",id:`${rt}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),nP(e)},onMouseEnter:()=>eJ(t),style:{width:"100%",minWidth:0,height:30,display:"flex",alignItems:"center",gap:12,padding:"0 8px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"none",color:i?"var(--text-dim)":"var(--text)",cursor:"pointer",textAlign:"left",transition:"background 0.08s ease"},children:[(0,r.jsxs)("span",{style:{flexShrink:0,fontSize:12,whiteSpace:"nowrap",color:n?"var(--text)":i?"var(--text-dim)":"var(--text)"},children:[function(e,t){if(!t)return`/${e}`;let n=e.toLocaleLowerCase().indexOf(t.toLocaleLowerCase());return n<0?`/${e}`:(0,r.jsxs)(r.Fragment,{children:[`/${e.slice(0,n)}`,(0,r.jsx)("span",{style:{color:"var(--accent)"},children:e.slice(n,n+t.length)}),e.slice(n+t.length)]})}(e.name,np),"builtin"===e.source&&tS[e.name]&&(0,r.jsx)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11,fontWeight:400},children:tS[e.name]}),i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:en("chat.dormant")})]}),(0,r.jsx)("span",{style:{flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:12},children:tj(e,en)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"4px 8px",fontSize:12,color:"var(--text-dim)"},children:en("chat.noCommands")})})]}),e0&&null!==eG&&(Q=tA&&(!tz||tz.cwd!==V),ee=1===nI.length?en("chat.match"):en("chat.matches",{count:nI.length}),et=tz?.serverHardTruncated?en("chat.serverIndexTruncated"):tz?.clientTruncated&&!nM?eG.query?en("chat.searchingAll"):en("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:t3,className:"popover-surface",style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===e2?"min(48vh, 400px)":`min(48vh, 400px, ${e2}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:Q?en("chat.loadingFiles"):en("chat.files",{label:ee,hint:et})}),(0,r.jsx)("span",{children:en("chat.tabEnter")})]}),(0,r.jsx)("div",{id:rn,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:Q||0!==nI.length?nI.map((e,t)=>{let n=t===e8,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{t6.current[t]=e},type:"button",id:`${rn}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),n$(e)},onMouseEnter:()=>e3(t),style:{width:"100%",height:30,display:"flex",alignItems:"center",gap:8,padding:"0 8px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12,transition:"background 0.08s ease"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(P,{size:13}):A(i,13)}),(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text)",whiteSpace:"nowrap"},children:[function(e,t){if(!t)return e;let n=e.toLocaleLowerCase().indexOf(t.toLocaleLowerCase());return n<0?e:(0,r.jsxs)(r.Fragment,{children:[e.slice(0,n),(0,r.jsx)("mark",{style:{padding:0,color:"var(--accent)",background:"transparent"},children:e.slice(n,n+t.length)}),e.slice(n+t.length)]})}(i,eG?.query??null),e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]}),s&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},children:s})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:nE&&!nM?en("chat.searching"):en("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-input-composer${eT?" is-bash-mode":""}${eT&&e$?" is-bash-excluded":""}`,children:[n3>0&&(0,r.jsxs)("div",{className:"chat-input-queue",role:"status","aria-label":en("chat.queued",{count:n3}),children:[n3>1&&(0,r.jsxs)("div",{className:"chat-input-queue-row",children:[(0,r.jsxs)("span",{className:"chat-input-queue-count",children:["queued \xb7 ",n3]}),n6]}),n4.map((e,t)=>(0,r.jsx)(t$,{kind:"steer",text:e,action:1===n3?n6:void 0},`steer-${t}`)),n8.map((e,t)=>(0,r.jsx)(t$,{kind:"follow-up",text:e,action:1===n3?n6:void 0},`followup-${t}`))]}),(eE.length>0||ek.length>0)&&(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginBottom:6,flexWrap:"wrap"},children:[ek.map(e=>(0,r.jsx)(eS,{path:e,cwd:V??void 0,onRemove:()=>eC(t=>t.filter(t=>t!==e))},e)),eE.map((e,t)=>(0,r.jsxs)("div",{className:"chat-input-image-preview",children:[(0,r.jsx)("img",{src:e.previewUrl,alt:""}),(0,r.jsx)("button",{type:"button",className:"chat-input-image-remove",onClick:()=>nl(t),title:en("i18n.close"),"aria-label":en("i18n.close"),children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},t))]}),eT&&(0,r.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"2px 6px",borderRadius:4,background:e$?"color-mix(in srgb, var(--text-dim) 12%, transparent)":"color-mix(in srgb, var(--accent) 12%, transparent)",color:e$?"var(--text-muted)":"var(--accent)",fontSize:11,flexShrink:0,alignSelf:"flex-start",userSelect:"none"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}),(0,r.jsx)("span",{style:{lineHeight:1},children:e$?"Local":"Shell"})]}),(0,r.jsxs)("div",{className:"chat-input-field-row",children:[(0,r.jsx)("textarea",{ref:tq,className:"chat-input-textarea",role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-expanded":!!rr,"aria-controls":rr,"aria-activedescendant":ri,"aria-label":J?en("chat.quoteQuestion"):en("chat.message"),disabled:o,placeholder:o?en("agentSwitcher.status.queued"):void 0,value:ed,onChange:e=>{nr.current=e.target.value,ec(e.target.value),eq(e.target.selectionStart),to.current=null,tt(!1),el(!1),nS(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;eq(t.selectionStart),nS(t.value,t.selectionStart)},onKeyDown:nD,onCompositionStart:()=>{t0.current=!0},onCompositionEnd:e=>{t0.current=!1,t1.current=Date.now();let t=e.currentTarget;eq(t.selectionStart),nS(t.value,t.selectionStart)},onPaste:nA,rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.5,padding:J?0:"2px 0 1px",fontFamily:eT?"var(--font-mono)":"var(--font-chat)",minHeight:J?96:24,maxHeight:200}}),(0,r.jsx)("div",{className:`chat-input-actions${n5?" is-queueing":""}`,children:n9})]}),!J&&(0,r.jsxs)("div",{className:"chat-input-dock",children:[(0,r.jsxs)("div",{ref:tV,className:"chat-input-popover-anchor",children:[(0,r.jsx)("button",{type:"button",className:"composer-btn is-icon",disabled:o,"data-active":eE.length>0||void 0,onClick:()=>{t?(eb(!1),em(!1),ev(e=>!e)):tQ.current?.click()},title:t?`${en("chat.attachImage")} / ${en("image.title")}`:en("chat.attachImage"),"aria-label":t?`${en("chat.attachImage")} / ${en("image.title")}`:en("chat.attachImage"),"aria-expanded":t?ex:void 0,"aria-haspopup":t?"menu":void 0,children:(0,r.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,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),ex&&t&&(0,r.jsxs)("div",{role:"menu",className:"chat-input-menu menu-surface",style:{left:0},onKeyDown:nZ,children:[(0,r.jsx)("button",{type:"button",role:"menuitem",onClick:()=>{ev(!1),tQ.current?.click()},children:en("chat.attachImage")}),(0,r.jsx)("button",{type:"button",role:"menuitem",onClick:()=>{ev(!1);let[e]=1===ni.current.length?ni.current:[];t(e?tE(e):void 0)},children:en("image.title")})]})]}),(nF.length>0||d||p)&&g&&(0,r.jsx)(td,{options:nF,value:d,onChange:g,disabled:l,busy:f,isAutoSelection:c}),I&&(0,r.jsxs)("div",{ref:tK,className:"chat-input-popover-anchor",children:[(0,r.jsxs)("button",{type:"button",className:"composer-btn",onClick:()=>{eb(!1),ev(!1),em(e=>!e)},disabled:l,title:en("chat.changeReasoning",{level:nH}),"aria-label":en("chat.changeReasoningLabel"),"aria-haspopup":"menu","aria-expanded":ep,children:[(0,r.jsx)(eK,{size:13}),(0,r.jsx)("span",{children:nH})]}),ep&&(0,r.jsx)("div",{role:"menu",className:"chat-input-menu menu-surface",style:{left:0},onKeyDown:nZ,children:eM.filter(e=>!L||L.includes(e)).map(e=>{let t=M===e,n=T?.[e],i=null!=n&&n!==e?n:e;return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":t,onClick:()=>{em(!1),t||I(e)},children:[nY(t),(0,r.jsx)("span",{children:i})]},e)})})]}),(0,r.jsx)("div",{className:"chat-input-dock-spacer"}),(()=>{if(!C||null===nV)return null;let e=C.contextWindow,t=C.tokens,n=nV>=85,i=nV>=70&&!n,s=null!==t?Math.max(0,e-t):null,a=[`${en("chat.contextUsage")}: ${null!==t?ti(t):"?"} / ${ti(e)} (${nV.toFixed(1)}%)`,null!==s?`${en("chat.contextRemaining")}: ${ti(s)}`:null,null!=N?`${en("session.cacheHitRate")}: ${N.toFixed(1)}%`:null,n?en("chat.contextHighWarning"):null].filter(Boolean).join("\n");return(0,r.jsxs)("button",{ref:tX,type:"button",className:`composer-btn chat-input-context${n?" is-high":i?" is-warning":""}`,"aria-pressed":E?eg:void 0,onClick:()=>{ef(e=>!e),E?.()},title:a,"aria-label":a,"data-top-panel-trigger":E?"session":void 0,"aria-controls":E?"workspace-top-panel":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",style:{transform:"rotate(-90deg)"},children:[(0,r.jsx)("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"1.4",opacity:"0.3"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"6",pathLength:"100",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeDasharray:`${Math.min(100,Math.round(nV))} 100`})]}),(0,r.jsxs)("span",{children:[null!==t?ti(t):"?","/",ti(e)]}),null!=N&&(0,r.jsxs)("span",{className:"chat-input-context-cache",children:["cache ",N.toFixed(0),"%"]})]})})(),nK&&(0,r.jsxs)("div",{ref:tJ,className:"chat-input-popover-anchor",children:[(0,r.jsxs)("button",{type:"button",className:`composer-btn${nq&&S?" is-flagged":" is-icon"}`,"aria-label":en("chat.moreControls"),"aria-haspopup":"menu","aria-expanded":ey,title:nq&&S?`${en("chat.changeToolPreset")}: ${n_}`:en("chat.moreControls"),onClick:()=>{ev(!1),em(!1),eh("root"),eb(e=>!e)},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M4 7h9M17 7h3M4 17h3M11 17h9"}),(0,r.jsx)("circle",{cx:"15",cy:"7",r:"2"}),(0,r.jsx)("circle",{cx:"9",cy:"17",r:"2"})]}),nq&&S&&(0,r.jsx)("span",{className:"composer-tools-label",children:nU})]}),ey&&(0,r.jsx)("div",{role:"menu",className:"chat-input-menu menu-surface",style:{right:0,minWidth:180},onKeyDown:nZ,children:"root"!==eu?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",className:"chat-input-menu-back",onClick:()=>eh("root"),children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 2.5 3.5 5 6 7.5"})}),(0,r.jsx)("span",{children:eu})]}),"tools"===eu&&S&&tu.map(e=>{let t=th[e],n=(k??tr.Q8)===t;return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eb(!1),n||S(t)},children:[nY(n),(0,r.jsx)("span",{children:e})]},e)}),"compact"===eu&&x&&(0,r.jsxs)("button",{type:"button",role:"menuitem",disabled:l,onClick:()=>{eb(!1),x()},children:[nY(!1),(0,r.jsx)("span",{children:en("chat.compactConfirm")})]})]}):(0,r.jsxs)(r.Fragment,{children:[S&&(0,r.jsxs)("button",{type:"button",role:"menuitem","aria-haspopup":"menu",disabled:l,onClick:()=>eh("tools"),children:[(0,r.jsx)("span",{children:"tools"}),(0,r.jsx)("span",{className:"chat-input-menu-note",children:nU}),nJ]}),x&&(y?(0,r.jsx)("button",{type:"button",role:"menuitem",onClick:()=>{eb(!1),v?.()},children:(0,r.jsx)("span",{children:en("chat.stopCompaction")})}):(0,r.jsxs)("button",{type:"button",role:"menuitem","aria-haspopup":"menu",disabled:l,onClick:()=>eh("compact"),children:[(0,r.jsx)("span",{children:"compact"}),null!==nV&&(0,r.jsxs)("span",{className:"chat-input-menu-note",children:[Math.round(nV),"%"]}),nJ]}))]})})]})]})]})]}),eT&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e$?"var(--text-muted)":"var(--accent)",marginTop:4},children:[en("chat.shell")," \xb7 ",e$?en("chat.outputLocal"):en("chat.outputModel")]})]})]})});function tD(e,t,n,r){let i=e?.capabilities[t];if(r&&i?.includes(r))return r;let s=e?.defaults?.[n];return s&&i?.includes(s)?s:i?.includes("auto")?"auto":i?.[0]??""}function tA({value:e,label:t,onChange:n,children:i}){return(0,r.jsxs)("label",{className:"relative inline-flex flex-none items-center",children:[(0,r.jsx)("select",{"aria-label":t,value:e,onChange:e=>n(e.target.value),className:"image-generation-select appearance-none bg-transparent py-1 pl-1.5 pr-5 text-[12px] text-text-muted outline-none hover:text-text focus:text-text",children:i}),(0,r.jsx)("svg",{className:"pointer-events-none absolute right-0.5 top-1/2 -translate-y-1/2 text-text-dim",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})]})}function tF({config:e,edit:t,editPreviewUrl:n,initialSourceImage:s,onClose:a,onSubmit:l}){let{t:o}=(0,w.s)(),d=(0,i.useRef)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),[h,p]=(0,i.useState)(""),m=e.connections.filter(e=>!0===e.capabilities.editing),[g,f]=(0,i.useState)(()=>t||!m.length?void 0:s),x=!!(t||g),v=x?m:e.connections,[y,b]=(0,i.useState)(()=>t?.connection&&e.connections.some(e=>e.id===t.connection)?t.connection:e.defaultConnection);(0,i.useEffect)(()=>{v.some(e=>e.id===y)||b(v.some(t=>t.id===e.defaultConnection)?e.defaultConnection:v[0]?.id??"")},[e.defaultConnection,v,y]);let j=v.find(e=>e.id===y)??v[0],k=!t&&m.length>0,S=e=>{let t=Array.from(e).find(e=>e.type.startsWith("image/"));return!!t&&(tN(t).then(f,e=>console.error("Failed to read source image:",e)),!0)},[C,N]=(0,i.useState)(()=>tD(j,"sizes","size",t?.size)),[E,M]=(0,i.useState)(()=>tD(j,"resolutions","resolution",t?.resolution)),[I,L]=(0,i.useState)(()=>tD(j,"qualities","quality",t?.quality)),T=j?.capabilities.sizes??[],$=j?.capabilities.resolutions??[],R=j?.capabilities.qualities??[],W=v.length>1,P=t?n:g?`data:${g.mimeType};base64,${g.data}`:void 0;(0,i.useLayoutEffect)(()=>{let e=c.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`)},[h]),(0,i.useEffect)(()=>{let e=document.activeElement;return window.matchMedia("(max-width: 640px)").matches||c.current?.focus(),()=>{e?.isConnected&&e.focus()}},[]),(0,i.useEffect)(()=>{let e=t&&j?.id===t.connection?t:void 0;N(tD(j,"sizes","size",e?.size)),M(tD(j,"resolutions","resolution",e?.resolution)),L(tD(j,"qualities","quality",e?.quality))},[j,t]);let z=()=>{if(!h.trim()||!j)return;let e={prompt:h.trim(),connection:j.id,...C?{size:C}:{},...E?{resolution:E}:{},...I?{quality:I}:{},...t?{target:t.path}:g?{}:{new_image:!0}};a(),l(e,t?void 0:g)};return(0,r.jsx)("div",{role:"presentation",className:"fixed inset-0 z-[1100] flex items-end justify-center bg-black/40 p-0 sm:items-center sm:p-4",onClick:e=>{e.target===e.currentTarget&&a()},children:(0,r.jsxs)("div",{ref:d,role:"dialog","aria-modal":"true","aria-labelledby":"image-generation-title",tabIndex:-1,onDragOver:e=>{k&&e.dataTransfer.types.includes("Files")&&e.preventDefault()},onDrop:e=>{k&&S(e.dataTransfer.files)&&e.preventDefault()},className:"flex max-h-[min(92dvh,100%)] w-full max-w-full flex-col overflow-hidden rounded-t-[16px] border border-border/80 bg-bg-panel shadow-2xl sm:max-h-[calc(100dvh-2rem)] sm:w-[480px] sm:rounded-[12px]",onKeyDown:e=>{if("Escape"===e.key){e.preventDefault(),a();return}if((e.metaKey||e.ctrlKey)&&"Enter"===e.key){e.preventDefault(),z();return}if("Tab"!==e.key)return;let t=Array.from(d.current?.querySelectorAll("button:not(:disabled), textarea:not(:disabled), select:not(:disabled), input:not(:disabled)")??[]).filter(e=>null!==e.offsetParent);if(!t.length)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n.focus())},children:[(0,r.jsx)("div",{className:"flex justify-center pt-2 sm:hidden","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-1 w-10 rounded-full bg-border"})}),(0,r.jsxs)("header",{className:"flex h-10 shrink-0 items-center px-4 sm:h-11",children:[(0,r.jsx)("h2",{id:"image-generation-title",className:"text-[14px] font-semibold text-text",children:x?o("image.editTitle"):o("image.title")}),(0,r.jsx)("button",{type:"button",onClick:a,className:"ml-auto inline-flex h-7 w-7 items-center justify-center rounded-md border-0 bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",title:o("trust.cancel"),"aria-label":o("trust.cancel"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:P?"flex flex-col gap-3 sm:flex-row sm:items-start":void 0,children:[P?(0,r.jsxs)("div",{className:"relative overflow-hidden rounded-[10px] sm:shrink-0",children:[(0,r.jsx)("img",{src:P,alt:t?.prompt??o("image.editSource"),className:"block h-auto w-full sm:h-28 sm:w-auto sm:max-w-[7.5rem]"}),t?null:(0,r.jsx)("button",{type:"button",onClick:()=>f(void 0),className:"absolute right-1 top-1 inline-flex h-6 w-6 items-center justify-center rounded-full border-0 bg-black/60 text-white hover:bg-black/80",title:o("image.removeSource"),"aria-label":o("image.removeSource"),children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]}):null,(0,r.jsx)("textarea",{ref:c,id:"image-prompt",rows:2,value:h,maxLength:32e3,"aria-label":o("image.prompt"),onChange:e=>p(e.target.value),onPaste:e=>{k&&S(e.clipboardData.files)&&e.preventDefault()},placeholder:x?o("image.editPromptPlaceholder"):o("image.promptPlaceholder"),className:`image-generation-prompt w-full resize-none rounded-[10px] border-0 bg-bg px-3 py-2.5 leading-[1.5] text-text outline-none ring-1 ring-inset ring-transparent placeholder:text-text-dim focus:ring-accent/50 ${P?"sm:min-h-28 sm:flex-1":""}`,style:{fontFamily:"var(--font-chat)",fontSize:"var(--chat-content-font-size, 14px)"}})]})}),(0,r.jsxs)("footer",{className:"flex shrink-0 items-center gap-2 px-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-3",children:[(0,r.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-x-1 gap-y-0.5",children:[k&&!g?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",onClick:()=>u.current?.click(),className:"inline-flex h-7 w-7 flex-none items-center justify-center rounded-md border-0 bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",title:o("image.addSource"),"aria-label":o("image.addSource"),children:(0,r.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,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(0,r.jsx)("input",{ref:u,type:"file",accept:"image/*",hidden:!0,onChange:e=>{S(e.target.files??[]),e.target.value=""}})]}):null,W?(0,r.jsx)(tA,{value:y,label:o("image.connection"),onChange:b,children:e.connections.map(e=>(0,r.jsx)("option",{value:e.id,children:e.label},e.id))}):null,T.length?(0,r.jsx)(tA,{value:C,label:o("image.aspect"),onChange:N,children:T.map(e=>{let t,n,i;return(0,r.jsx)("option",{value:e,children:"auto"===(t="auto"===(i=e.trim())?"auto":(n=function(e){let t=/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(e.trim())??/^(\d+)x(\d+)$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]);return!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0?null:{width:n,height:r}}(i))?n.width===n.height?"square":n.width>n.height?"landscape":"portrait":null)?o("image.aspectAuto"):"square"===t?`${o("image.aspectSquare")} ${e}`:"portrait"===t?`${o("image.aspectPortrait")} ${e}`:"landscape"===t?`${o("image.aspectLandscape")} ${e}`:e},e)})}):null,$.length?(0,r.jsx)(tA,{value:E,label:o("image.resolution"),onChange:M,children:$.map(e=>(0,r.jsx)("option",{value:e,children:e.toUpperCase()},e))}):null,R.length?(0,r.jsx)(tA,{value:I,label:o("image.quality"),onChange:L,children:R.map(e=>(0,r.jsx)("option",{value:e,children:"auto"===e?o("image.qualityAuto"):"low"===e?o("image.qualityLow"):"medium"===e?o("image.qualityMedium"):"high"===e?o("image.qualityHigh"):e},e))}):null]}),(0,r.jsx)("button",{type:"button",disabled:!h.trim(),onClick:z,className:"h-8 shrink-0 rounded-md border-0 bg-[var(--primary)] px-3 text-[12px] text-[var(--primary-contrast)] disabled:cursor-not-allowed disabled:opacity-50",children:x?o("image.edit"):o("image.generate")})]})]})})}let tB=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,tO=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,tH=/\x1B_pi:c\x07/g;function tU(e){return e.replace(tH,"").replace(tB,"")}function t_(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(tO);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function tq(e,t){let n=t_(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function tK(e){return t_(e)[0]?.char}let tV={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},tJ={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function tY(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}function tZ(e){return"custom"===e.role&&"pi-web:subagent-notification"===e.customType}function tX(e){return tY(e)||tZ(e)}function tG(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function tQ(e,t={}){return(e.content??[]).filter(e=>!tG(e,t)&&!function(e,t={}){return"text"===e.type&&!t.isStreaming&&""===e.text.trim()}(e,t))}function t0(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function t1(e,t={}){return"image"===e.type||"text"===e.type&&(t.isStreaming?e.text.length>0:e.text.trim().length>0)}function t2(e,t={}){let n=tQ(e,t),r=n.findLastIndex(e=>!t1(e,t));return -1===r?{answerBlocks:n,processBlocks:[]}:{processBlocks:n.slice(0,r+1),answerBlocks:n.slice(r+1)}}function t4(e,t={}){return t2(e,t).answerBlocks.some(e=>t1(e,t))}function t8(e){return e.filter(e=>"toolCall"===e.type).length}function t3(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),n.omitError&&("error"===r.stopReason&&(r.stopReason="stop"),r.errorMessage=void 0),r}function t6(e,t={}){let n=function(e,t={}){let{processBlocks:n,answerBlocks:r}=t2(e,t),i=[],s=[];for(let e of n)"text"===e.type&&e.text.trim().length>400?s.push(e):i.push(e);return{answerBlocks:[...s,...r],processBlocks:i}}(e,t),r=t4(e,t),i=!!t0(e,t),s=n.answerBlocks.length>0?t3(e,n.answerBlocks,{omitError:!r}):null;return{processMessage:tQ({...e,content:n.processBlocks},t).length>0||i&&!r?t3(e,n.processBlocks,{omitUsage:!!s&&!t.isStreaming,omitError:r}):null,answerMessage:s}}let t5=/^\*\*\* (Add|Update|Delete) File: (.+)$/,t7=/^\*\*\* Move to: (.+)$/;function t9(){return{lineNo:null,text:"",type:"empty"}}function ne(e){if(!e.includes("*** Begin Patch"))return null;let t=[],n=null,r=!1,i=[],s=[],a=()=>{if(!n){i=[],s=[];return}let e=Math.max(i.length,s.length);for(let t=0;t<e;t+=1){let e=i[t]?{lineNo:i[t].lineNo,text:i[t].text,type:"removed"}:t9(),r=s[t]?{lineNo:s[t].lineNo,text:s[t].text,type:"added"}:t9();n.rows.push({type:"line",left:e,right:r})}i=[],s=[]};for(let l of e.split(/\r?\n/)){if(l.startsWith("*** Begin Patch")||l.startsWith("*** End Patch")){a(),r=!1;continue}let e=l.match(t5);if(e){a(),r=!1;let i=e[1].toLowerCase();n={path:e[2].trim(),operation:i,rows:[]},t.push(n);continue}if(!n)continue;let o=l.match(t7);if(o){n.moveTo=o[1].trim();continue}if(l.startsWith("@@")){a(),r=!0,n.rows.push({type:"hunk",text:l});continue}if(l.startsWith("*** "))return null;if(""===l){a();continue}if(!r&&"update"===n.operation)continue;let d=l[0]??"",c=l.slice(1);"+"===d?s.push({lineNo:null,text:c}):"-"===d?i.push({lineNo:null,text:c}):" "===d&&(a(),n.rows.push({type:"line",left:{lineNo:null,text:c,type:"context"},right:{lineNo:null,text:c,type:"context"}}))}return a(),t.length>0?t:null}function nt(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function nn(e){try{return decodeURIComponent(e)}catch{return e}}function nr(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function ni(e){let t=nr(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){s.length>0&&".."!==s[s.length-1]?s.pop():i||n||r||s.push(e);continue}s.push(e)}let a=s.join("/");return n?a:r?`//${a}`:i?`/${a}`:a}function ns(e,t){if(!e)return null;let n=e.split("#",1)[0].split("?",1)[0].trim();if(!n)return null;let r=null,i=nn(n),s=i.startsWith("\\\\"),a=nr(i),l=a.toLowerCase();if(l.startsWith("/api/")||l.startsWith("/_next/")||!s&&a.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(a)&&!l.startsWith("file:")&&!/^[a-zA-Z]:\//.test(a))return null;if(l.startsWith("file:"))r=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=nn(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(n);else if(/^[a-zA-Z]:\//.test(a))r=a;else if(a.startsWith("/"))r=a;else t&&!(a.startsWith("#")||a.startsWith("?"))&&(a.startsWith("./")||a.startsWith("../")||a.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(a))&&(r=`${nr(t).replace(/\/+$/,"")}/${a}`);return r?ni(r).replace(/:\d+(?::\d+)?$/,""):null}function na(e){if(!e)return null;let t=e.split("#",2)[1];if(!t)return null;let n=new URLSearchParams(t).get("page");if(null===n||!/^\d+$/.test(n))return null;let r=Number(n);return Number.isSafeInteger(r)&&r>0?r:null}function nl(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function no(e){let t=e.toLowerCase();return"apply_patch"===t||t.endsWith(".apply_patch")||t.endsWith("/apply_patch")||t.endsWith("_apply_patch")}function nd(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
6
-
7
- ${r}
8
-
9
- ${n}`}function nc(e,t,n=50){let r=Math.max(0,e),i=Math.min(Math.max(0,t),Math.max(0,r-Math.min(n,r))),s=r-i;return{startIndex:Math.max(0,s-n),endIndex:s}}function nu(e,t,n,r=8){return e+t>=n-r}class nh extends Error{constructor(e,t){super(t),this.name="OutlineLocateError",this.reason=e}}function np(e,t){return e.entry.id===t||!!e.compressedEntryIds?.includes(t)}function nm(e,t){if(!e)return null;let n=new Map,r=[];for(let t=e.length-1;t>=0;t--)n.set(e[t],null),r.push(e[t]);for(;r.length>0;){let e=r.pop();if(np(e,t)){let t=[],r=e;for(;r;)t.push(r),r=n.get(r)??null;return t.reverse(),t}let i=e.children;if(i&&0!==i.length)for(let t=i.length-1;t>=0;t--)n.set(i[t],e),r.push(i[t])}return null}async function ng(e,t,n,r){let i=t,s=new Set;for(;;){if(r.throwIfAborted(),i.entryIds.includes(e))return;let t=i.oldestEntryId;if(!i.hasMore||!t)throw new nh("exhausted","Question is no longer in this branch. Refresh the outline and try again.");if(s.has(t))throw new nh("stalled","History did not advance. Please try again.");s.add(t);let a=await n(t);if(r.throwIfAborted(),!a)throw new nh("load_failed","Could not load this question. Please try again.");if(a.entryIds.includes(e))return;if(a.oldestEntryId===t||null!==a.oldestEntryId&&s.has(a.oldestEntryId))throw new nh("stalled","History did not advance. Please try again.");i=a}}function nf(e,t){return t.aborted||e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&"AbortError"===e.name}var nx=n(32316),nv=n(88374),ny=n(5924),nb=n(94764),nw=n(63835),nj=n(23135),nk=n(54152),nS=n(84678),nC=n(98164);let nN={...nb.j,attributes:{...nb.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...nb.j.protocols,href:[...nb.j.protocols?.href??[],"file"]},strip:[...nb.j.strip||[],"iframe","object","style","form"]};function nE(e){return/^file:/i.test(e)?e:(0,nx.Lv)(e)}let nM=/(?<![\\`])`((?:[^`\n]|\\`)+?)(?<![\\`])`(?!`)/g;function nI(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,a=null,l=new Map,o=new Set;for(let e=0;e<n.length;e++){var d,c;let t=n[e];if(a){r.push(t),RegExp(`</${a}\\s*>`,"i").test(t)&&(a=null);continue}let u=t.match(/^ {0,3}(`{3,}|~{3,})/);if(u){let e=u[1][0],n=u[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let h=t.match(/<(code|pre|script|style)\b/i);if(h){let e=h[1].toLowerCase(),n=t.slice((h.index??0)+h[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(a=e),s=0,r.push(t);continue}if(""===t.trim()||/^(?: {4}|\t)/.test(t)&&!/^[ \t]*\$\$/.test(t)||o.has(e)){s=0,r.push(t);continue}if(s||(t=t.replace(nM,(e,t)=>{let n=t.replace(/\\`/g,"`");if(n===t)return e;let r="`".repeat(Math.max(...n.match(/`+/g)?.map(e=>e.length)??[0])+1);return`${r}${n}${r}`})),s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let p=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let m=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(m){let e=m[2].trim();if(d=e,/\\[A-Za-z]+/.test(d)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(d)){r.push(`${m[1]}$$`,`${m[1]}${e}`,`${m[1]}$$`);continue}}let g=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(g){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${g[1]}$$`,...n.slice(e+1,t).map(e=>nR(e,g[1])),`${g[1]}$$`),e=t;continue}}let f=t.match(/^([ \t]*)\$\$(.+)\$\$[ \t]*$/);if(f){let e=f[2].trim();if(e){r.push(`${f[1]}$$`,`${f[1]}${e}`,`${f[1]}$$`);continue}}let x=t.match(/^([ \t]*)\$\$(.+)$/);if(x){let i=x[1],s=x[2].trimEnd();if(s&&!s.includes("$$")){let a=nL(n,e+1,i,l);if(a){r.push(`${i}$$`,`${i}${s}`);for(let t=e+1;t<a.index;t++)r.push(nR(n[t],i));a.content&&r.push(`${i}${a.content}`),r.push(`${i}$$`),e=a.index;continue}r.push(nT(t));continue}}let v=t.match(/^([ \t]*)\$\$\s*$/);if(v){let i=v[1],s=nL(n,e+1,i,l);if(s&&(s.glued||""!==i)){r.push(`${i}$$`);for(let t=e+1;t<s.index;t++)r.push(nR(n[t],i));s.content&&r.push(`${i}${s.content}`),r.push(`${i}$$`),e=s.index;continue}if(s){o.add(s.index),r.push(t);continue}r.push(nT(t));continue}r.push((c=t,/^\s{0,3}\[[^\]]+\]:/.test(c)||/]\s*\(/.test(c)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(c)||/\b(?:https?|file|mailto):/i.test(c)||/\b[A-Za-z]:\\/.test(c)?c:c.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function nL(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,a;let t=e[i];if(function(e,t){if(""===t)return/^ {0,3}\$\$\s*$/.test(e);let n=n$(e,t);return null!==n&&/^\$\$\s*$/.test(n)}(t,n))return{index:i,content:"",glued:!1};if(s=t,/^ {0,3}(`{3,}|~{3,})/.test(s)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(s)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(s)||/^ {0,3}>/.test(s)||/<(code|pre|script|style)\b/i.test(s)||(a=t,/^[ \t]*\$\$(?:\S|[ \t]+\S)/.test(a)))return r.set(n,i),null;let l=function(e,t){let n=n$(e,t);if(null===n)return null;let r=n.match(/^(.+?)\$\$\s*$/);if(!r)return null;let i=r[1].trimEnd();return i&&!i.includes("$$")?i:null}(t,n);if(null!==l)return{index:i,content:l,glued:!0}}return r.set(n,e.length),null}function nT(e){return e.replace(/^([ \t]*)\$\$/,(e,t)=>`${t}\\$\\$`)}function n$(e,t){if(e.startsWith(t))return e.slice(t.length);let n=e.match(/^[ \t]*/)?.[0]??"";return t&&n.length<t.length?e.slice(n.length):null}function nR(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let nW={singleTilde:!1},nP=[[nk.A,["yaml"]],[nS.A,nW],nC.A,nj.A],nz=[[nk.A,["yaml"]],[nS.A,nW],nC.A,nj.A],nD=[ny.A,[nw.A,nN],[nv.A,{throwOnError:!1,strict:!1}]],nA=[ny.A,[nw.A,nN],[nv.A,{throwOnError:!1,strict:!1}]];var nF=n(7644);let nB="pi-theme",nO="pi-theme-palette",nH=["light","dark","auto"],nU={preference:"auto",theme:"light",palette:"default"},n_=new Set,nq=null,nK=!1;function nV(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function nJ(e){try{return localStorage.getItem(e)}catch{return null}}function nY(e,t){try{localStorage.setItem(e,t)}catch{}}function nZ(e){return"auto"===e?nV():e}let nX={default:{light:"#f5f5f5",dark:"#242424"},claude:{light:"#fafaf4",dark:"#111111"}};function nG(e,t){if("u"<typeof document)return;let n=document.documentElement;n.classList.toggle("dark","dark"===t),"default"===e?delete n.dataset.theme:n.dataset.theme=e,function(e,t){if("u"<typeof document)return;let n=nX[e][t],r=document.querySelectorAll('meta[name="theme-color"]');if(0===r.length){let e=document.createElement("meta");e.name="theme-color",e.content=n,document.head.appendChild(e);return}for(let e of r)e.removeAttribute("media"),e.content=n}(e,t)}function nQ(){let e;if(nq)return nq;let t="light"===(e=nJ(nB))||"dark"===e?e:"auto",n="claude"===nJ(nO)?"claude":"default",r=nZ(t);return nG(n,r),nq={preference:t,theme:r,palette:n}}function n0(e,t){nG(e.palette,e.theme),t&&(nY(nB,e.preference),nY(nO,e.palette)),nq=e,n_.forEach(e=>e())}function n1(){let e=nQ();if("auto"!==e.preference)return;let t=nV();t!==e.theme&&n0({...e,theme:t},!1)}function n2(e){return n_.add(e),nQ(),nK||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",n1),window.addEventListener("focus",n1),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&n1()}),nK=!0),n1(),()=>{n_.delete(e)}}function n4(){return nQ()}function n8(){return nU}function n3(){let e=(0,i.useSyncExternalStore)(n2,n4,n8),t=(0,i.useCallback)((e,t)=>{if(nQ().preference===e)return;let n=nZ(e),r=()=>{n0({...nQ(),preference:e,theme:n},!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,a=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(a,window.innerHeight-a));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${a}px)`,`circle(${l}px at ${s}px ${a}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),n=(0,i.useCallback)(e=>{let t=nQ();t.palette!==e&&n0({...t,palette:e},!0)},[]),r=(0,i.useCallback)(e=>{var n;let r;t((n=nQ().preference,r=nH.indexOf(n),nH[(r+1)%nH.length]),e)},[t]);return{theme:e.theme,preference:e.preference,palette:e.palette,setThemePreference:t,setThemePalette:n,toggleTheme:r,isDark:"dark"===e.theme}}let n6={comment:"#7d7b73",prolog:"#7d7b73",doctype:"#7d7b73",cdata:"#7d7b73",punctuation:"#3d3d3a",operator:"#3d3d3a",function:"#3d3d3a",string:"#5b7a3a",inserted:"#5b7a3a",keyword:"#a8472a",atrule:"#a8472a",tag:"#a8472a",selector:"#a8472a",".language-autohotkey .token.keyword":"#a8472a",number:"#946010",boolean:"#946010",constant:"#946010",symbol:"#946010",variable:"#946010",url:"#946010","attr-name":"#946010",".language-json .token.boolean":"#946010",".language-json .token.number":"#946010","class-name":"#2e6e66",property:"#2e6e66","attr-value":"#5b7a3a",".language-json .token.property":"#2e6e66",'code[class*="language-css"]':"#2e6e66",regex:"#b53333",entity:"#b53333",deleted:"#b53333",".language-autohotkey .token.tag":"#b53333"},n5=Object.fromEntries(Object.entries(nF.vs).map(([e,t])=>e in n6?[e,{...t,color:n6[e]}]:e.includes("::selection")||e.includes("::-moz-selection")?[e,{background:"#f0dcd3"}]:"#393A34"===t.color?[e,{...t,color:"#3d3d3a"}]:[e,t])),n7={"#d4d4d4":"#dedcd4","#9cdcfe":"#dedcd4","#569cd6":"#e08a6d","#c586c0":"#e08a6d","#db4c69":"#e08a6d","#ce9178":"#b3c78f","#b5cea8":"#e0b36a","#d7ba7d":"#e0b36a","#dcdcaa":"#e6d3a3","#4ec9b0":"#7fb8ad","#d16969":"#e86b6b","#6a9955":"#8d8b85","#808080":"#8d8b85","#1e1e1e":"#1a1a19","#264f78":"#5a3a2e"},n9=Object.fromEntries(Object.entries(nF.xJ).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,"string"==typeof t?t.replace(/#[0-9a-f]{6}\b/gi,e=>n7[e.toLowerCase()]??e):t]))])),re={background:"#fdfdf7",primaryColor:"#efefe9",primaryTextColor:"#141413",primaryBorderColor:"#b9b9b3",secondaryColor:"#f4e6df",tertiaryColor:"#f6f6f0",lineColor:"#73736d",noteBkgColor:"#f7efe0",noteBorderColor:"#d9c7a3"},rt={darkMode:!0,background:"#151515",primaryColor:"#262625",primaryTextColor:"#f8f7f4",primaryBorderColor:"#4a4947",secondaryColor:"#3a2b25",tertiaryColor:"#1f1f1e",lineColor:"#8d8b85",edgeLabelBackground:"#151515",textColor:"#f8f7f4",noteBkgColor:"#33291c",noteBorderColor:"#6b5a3a",noteTextColor:"#f8f7f4"};function rn(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()}}var rr=n(65063);function ri({code:e,isStreaming:t,defaultPreview:s=!1}){let{isDark:a,palette:l}=n3(),o="claude"===l,{t:d}=(0,w.s)(),[c,u]=(0,i.useState)(s),[h,p]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),f=(0,i.useRef)(null),x=`${l}-${a?"dark":"light"}
10
- ${e}`,v=c&&!t;(0,i.useEffect)(()=>{if(!v)return;let t=!1;return p({key:x,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(988),n.e(9425),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,...o?{theme:"base",themeVariables:a?rt:re}:{theme:a?"dark":"default"}}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,s=await r.render(i,e);t||p({key:x,status:"ready",svg:s.svg})})().catch(()=>{t||p({key:x,status:"error"})}),()=>{t=!0}},[e,x,o,a,v]);let y=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),disabled:t,title:t?d("i18n.previewAfterStreaming"):v?d("i18n.showMermaidSource"):d("i18n.previewMermaid"),className:["markdown-code-action",v?"is-active":""].filter(Boolean).join(" "),children:v?d("i18n.source"):d("i18n.preview")}),[t,v,d]);if(!v)return(0,r.jsx)(ra,{code:e,lang:"mermaid",headerAction:y,isStreaming:t});let b=h?.key===x&&"error"===h.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:d("i18n.invalidMermaid")}):h?.key!==x||"ready"!==h.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":d("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!m&&(0,r.jsx)("button",{ref:f,type:"button",className:"mermaid-block mermaid-preview-button",title:d("i18n.openMermaidViewer"),"aria-label":d("i18n.openMermaidViewer"),onClick:()=>g(!0),dangerouslySetInnerHTML:{__html:h.svg}}),m&&(0,r.jsx)(rs,{svg:h.svg,onClose:()=>g(!1)})]});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[h?.key===x&&"ready"===h.status&&(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${d("i18n.downloadFile")} (SVG)`,"aria-label":`${d("i18n.downloadFile")} (SVG)`,onClick:()=>{let e,t,n,r=f.current?.querySelector("svg");r&&(e=new XMLSerializer().serializeToString(r),t=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),(n=document.createElement("a")).href=t,n.download="mermaid-diagram.svg",n.click(),setTimeout(()=>URL.revokeObjectURL(t),0))},children:"SVG"}),y]})]}),b]})}function rs({svg:e,onClose:t}){let{t:n}=(0,w.s)(),s=(0,i.useRef)(null),[a,l]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:s,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.max(.5,e-.25)),disabled:a<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*a),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.min(3,e+.25)),disabled:a>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>l(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("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,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*a}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let ra=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:s}){let{isDark:a,palette:l}=n3(),{t:o}=(0,w.s)(),[d,c]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsxs)("button",{type:"button",onClick:()=>{rn(e).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",title:o(d?"i18n.copied":"i18n.copy"),"aria-label":o(d?"i18n.copied":"i18n.copy"),children:[d?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,r.jsx)("span",{children:o(d?"i18n.copied":"i18n.copy")})]})]})]}),s?(0,r.jsx)("pre",{style:{margin:0,padding:"6px 10px",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.54,overflowX:"auto",border:"none",borderRadius:0,background:"transparent",backgroundColor:"transparent"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(rr.A,{language:t||"text",style:"claude"===l?a?n9:n5:a?nF.xJ:nF.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",paddingRight:"0.8em",userSelect:"none"},customStyle:{margin:0,padding:"6px 10px",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.54,borderRadius:0,border:"none",boxShadow:"none",background:"transparent",backgroundColor:"transparent",overflowX:"auto"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function rl({children:e,className:t,isStreaming:n,cwd:s,onOpenFile:a}){let l=(0,i.useMemo)(()=>nI(e),[e]),o=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let s=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===s?(0,r.jsx)(ri,{code:a.replace(/\n$/,""),isStreaming:n,defaultPreview:!0}):(0,r.jsx)(ra,{code:a.replace(/\n$/,""),lang:s,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=a?ns(e,s):null;if(!i||!a)return(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t});let l=na(e);return(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(!nt(e))return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),a(i,l??void 0))},children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?ns(e,s):null,a=i?`/api/files/${k(i)}?type=read`:e;return(0,r.jsx)("img",{src:a,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[s,n,a]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(nx.oz,{remarkPlugins:nP,rehypePlugins:nD,urlTransform:a?nE:void 0,components:o,children:l})})}function ro({toolName:e,isError:t,size:n=12}){if(t)return(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]});let i=e.toLowerCase();return i.includes("bash")||i.includes("sh")||i.includes("terminal")||i.includes("powershell")||i.includes("command")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 15 10 9 4 3"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"20",y2:"17"})]}):"read"===i||i.includes("read_file")||i.includes("view")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,r.jsx)("line",{x1:"9",y1:"13",x2:"15",y2:"13"}),(0,r.jsx)("line",{x1:"9",y1:"17",x2:"13",y2:"17"})]}):i.includes("write")||i.includes("edit")||i.includes("patch")||i.includes("apply")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),(0,r.jsx)("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}):i.includes("todo")||i.includes("task")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"5",width:"6",height:"6",rx:"1"}),(0,r.jsx)("path",{d:"m3 17 2 2 4-4"}),(0,r.jsx)("path",{d:"M13 6h8"}),(0,r.jsx)("path",{d:"M13 12h8"}),(0,r.jsx)("path",{d:"M13 18h8"})]}):i.includes("agent")||i.includes("subagent")?(0,r.jsx)(G,{size:n,className:"shrink-0",style:{display:"block"}}):i.includes("search")||i.includes("fetch")||i.includes("web")||i.includes("browser")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}):(0,r.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:(0,r.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"})})}let rd=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,rc=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function ru(e){let t,n=[],r=null,i=0,s=0,a=0,l=0,o=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){o=[],d=[];return}let e=Math.max(o.length,d.length);for(let t=0;t<e;t++){let e=o[t]?{lineNo:o[t].lineNo,text:o[t].text,type:"removed"}:c(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();r.rows.push({type:"line",left:e,right:n})}o=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(a>0||l>0)){if(c.startsWith("--- ")){u(),t=rh(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:rh(c.slice(4)),rows:[]},n.push(r);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),s=Number(e[3]),a=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let h=c[0],p=c.slice(1);" "===h?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:p,type:"context"},right:{lineNo:s++,text:p,type:"context"}}),a>0&&a--,l>0&&l--):"-"===h?(o.push({lineNo:i++,text:p}),a>0&&a--):"+"===h?(d.push({lineNo:s++,text:p}),l>0&&l--):""!==c&&(u(),r.rows.push({type:"hunk",text:c}))}u();let h=n.filter(e=>e.rows.some(e=>"line"===e.type));return h.length>0?h:null}function rh(e){return e.split(" ")[0].trim()}let rp="pi-thinking-expanded",rm="pi-thinking-expanded-changed";function rg(){return"true"===window.localStorage.getItem(rp)}function rf({files:e,onOpenFile:t}){let{t:n}=(0,w.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=S(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:5,padding:"2.5px 7px",minHeight:22,fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1,color:"var(--text-muted)",background:"color-mix(in srgb, var(--bg-subtle) 65%, var(--bg))",border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",borderRadius:5,cursor:"pointer",transition:"background 0.12s ease, color 0.12s ease"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--bg-subtle) 65%, var(--bg))",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:A(i,12)}),(0,r.jsx)("span",{style:{lineHeight:1},children:i})]},e)})})}let rx=new Map;function rv({children:e,className:t,...n}){let{t:s}=(0,w.s)(),[a,l]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(rl,{className:t,...n,children:e});if(!a){var o;return(0,r.jsxs)("button",{onClick:()=>l(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",s("i18n.largeMessageReveal",{size:(o=e.length)>=1e6?`${(o/1e6).toFixed(1)} MB`:o>=1e3?`${Math.round(o/1e3)} KB`:`${o} B`})]})}return(0,r.jsx)("div",{className:t,style:{maxHeight:420,overflow:"auto",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:e})})}function ry(e,t){if("number"!=typeof e||"number"!=typeof t)return;let n=Math.round((t-e)/1e3);return n>0?n:void 0}function rb(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let s=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${s} ${i}`}let rw=(0,i.memo)(function({message:e,modelName:t,isStreaming:n,toolResults:i,cwd:s,onOpenFile:a,onOpenSession:l,entryId:o,searchBlock:d,onFork:c,forking:u,onNavigate:h,prevAssistantEntryId:p,onEditContent:m,isTurnEnd:g,sessionId:f,writtenFiles:x,isProcess:v,runningToolIds:y}){return"user"===e.role?(0,r.jsx)(rS,{message:e,cwd:s,onOpenFile:a,entryId:o,onFork:c,forking:u,onNavigate:h,prevAssistantEntryId:p,onEditContent:m}):"assistant"===e.role?(0,r.jsx)(rC,{message:e,modelName:t,isStreaming:n,toolResults:i,cwd:s,onOpenFile:a,onOpenSession:l,isTurnEnd:g,sessionId:f,entryId:o,searchBlock:d,writtenFiles:x,isProcess:v,runningToolIds:y}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(rO,{message:e}):tZ(e)?(0,r.jsx)(r_,{message:e,cwd:s,onOpenFile:a}):(0,r.jsx)(rq,{message:e,cwd:s,onOpenFile:a}):"bashExecution"===e.role?(0,r.jsx)(rY,{message:e,sessionId:f}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onOpenSession===t.onOpenSession&&e.entryId===t.entryId&&e.searchBlock===t.searchBlock&&e.onFork===t.onFork&&e.forking===t.forking&&e.onNavigate===t.onNavigate&&e.prevAssistantEntryId===t.prevAssistantEntryId&&e.onEditContent===t.onEditContent&&e.isTurnEnd===t.isTurnEnd&&e.modelName===t.modelName&&e.writtenFiles===t.writtenFiles&&e.sessionId===t.sessionId&&e.isProcess===t.isProcess);function rj({text:e,cwd:t,onOpenFile:n}){let i=function(e){let t=[],n=0;for(let r of e.matchAll(ex)){let i=function(e){let t=(e[1]??e[2]??"").replace(/[),.;]+$/,"");if(!(!ev.test(t)||t.split(/[\\/]/).includes("..")))return t}(r),s=r.index??0;i&&(s>n&&t.push({type:"text",value:e.slice(n,s)}),t.push({type:"mention",path:i}),n=s+r[0].length)}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t.length?t:[{type:"text",value:e}]}(e),s=i.filter(e=>"mention"===e.type),a=i.filter(e=>"text"===e.type).map(e=>e.value).join("").trim();return s.length?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!a},children:s.map(e=>(0,r.jsx)(eS,{path:e.path,cwd:t},e.path))}),a?(0,r.jsx)(rv,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:a}):null]}):(0,r.jsx)(rv,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:e})}let rk=/^\[Image(?:: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by \d+\.\d{2} to map to original image\.| converted from \S+ to \S+\.)\]$/;function rS({message:e,cwd:t,onOpenFile:n,entryId:s,onFork:a,forking:l,onNavigate:o,prevAssistantEntryId:d,onEditContent:c}){let{t:h}=(0,w.s)(),[p,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),y=function(e){let t=e.split("\n"),n=t.length;for(;n>0&&(""===t[n-1].trim()||rk.test(t[n-1].trim()));)n-=1;return t.slice(0,n).join("\n")}("string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")),b="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),j=u(y),k=j?.search(/\s/)??-1,S=j?-1===k?j:j.slice(0,k):"",C=j&&-1!==k?j.slice(k+1):"",N=rb(e.timestamp),E=!!s&&!!a,M=j??y,I=j?function(e,t){if("string"==typeof e.content)return{...e,content:t};let n=[],r=!1;for(let i of e.content){if("text"!==i.type){n.push(i);continue}r||(n.push({...i,text:t}),r=!0)}return r||n.unshift({type:"text",text:t}),{...e,content:n}}(e,j):e,L=b.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!y},children:b.map((e,t)=>{let n=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,r.jsx)(eh,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:8,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t)})}),T=!!d&&!!o;return(0,r.jsxs)("div",{style:{marginBottom:10,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"min(85%, 680px)"},children:(0,r.jsx)("div",{style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid var(--user-border, var(--border))",borderRadius:6,padding:"6px 11px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.58,color:"var(--text)",wordBreak:"break-word",maxHeight:480,overflowY:"auto"},children:j?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[L,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>v(e=>!e),title:h(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S}),(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),C&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.58,whiteSpace:"pre-wrap",wordBreak:"break-word",flex:"1 0 auto",width:"max-content",maxWidth:"100%"},children:C})]}),x&&(0,r.jsx)(rl,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:y})]}):(0,r.jsxs)(r.Fragment,{children:[L,y&&(0,r.jsx)(rj,{text:y,cwd:t,onOpenFile:n})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:2},children:[(0,r.jsx)("div",{className:"message-action-group",style:{opacity:+!!p,pointerEvents:p?"auto":"none"},children:(0,r.jsx)("button",{type:"button",className:"message-action-button","data-copied":g?"true":void 0,onClick:()=>{rn(M).then(()=>{f(!0),setTimeout(()=>f(!1),1500)})},title:h(g?"i18n.copied":"i18n.copyMessage"),"aria-label":h(g?"i18n.copied":"i18n.copy"),children:g?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})}),(E||T)&&(0,r.jsxs)("div",{className:"message-action-group",style:{opacity:p||l?1:0,pointerEvents:p||l?"auto":"none"},children:[T&&(0,r.jsx)("button",{type:"button",className:"message-action-button",onClick:()=>{o(d),c?.(I)},title:h("i18n.editFromHereTitle"),"aria-label":h("i18n.editFromHere"),children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]})}),E&&(0,r.jsx)("button",{type:"button",className:"message-action-button",onClick:()=>{a(s)},disabled:l,title:h(l?"i18n.creatingSession":"i18n.newSessionTitle"),"aria-label":h(l?"i18n.creating":"i18n.newSession"),children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),N&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums",userSelect:"none"},children:N})]})]})}function rC({message:e,modelName:t,isStreaming:n,toolResults:s,cwd:a,onOpenFile:l,onOpenSession:o,isTurnEnd:d,sessionId:c,entryId:u,searchBlock:h,writtenFiles:p,isProcess:m,runningToolIds:g}){let{t:f}=(0,w.s)(),[x,v]=(0,i.useState)(!1),y=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!tG(e,{isStreaming:n})),[e.content,n]),b=(0,i.useMemo)(()=>y.map(({block:e})=>e),[y]),j=e.completedAt??e.timestamp,k=(0,i.useMemo)(()=>{let t=new Map;if(!s||void 0===j)return t;for(let n of e.content){if("toolCall"!==n.type)continue;let e=s.get(n.toolCallId),r=ry(j,e?.timestamp);void 0!==r&&t.set(n.toolCallId,r)}return t},[e.content,s,j]),S=t0(e,{isStreaming:n}),C=function(e,t={}){return!t.isStreaming&&"length"===e.stopReason}(e,{isStreaming:n}),N=b.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),E=d&&!n?rb(e.timestamp):null,M=d&&!n&&(t||e.model)||null,I=d&&!n&&!!(M||N||E);return 0!==b.length||n||S||C?(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":u,style:{marginBottom:d?16:8},children:[(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:y.map(({block:t,originalIndex:i},d)=>{let p="thinking"===t.type?t:null,m=p?p.startedAt??e.timestamp:void 0,f=p?ry(m,p.endedAt??e.completedAt):void 0,x=!!(n&&p&&d===y.length-1&&void 0===f&&"number"==typeof m);return(0,r.jsx)(rM,{block:t,searchTarget:t===h,toolResults:s,isStreaming:n,streamingDuration:f,startTime:"toolCall"===t.type?j:m,live:x||"toolCall"===t.type&&!!g?.has(t.toolCallId),toolCallDurations:k,cwd:a,onOpenFile:l,onOpenSession:o,sessionId:c,entryId:u,blockIndex:i},`${u??"stream"}-${i}`)})}),S&&(m?(0,r.jsx)("div",{style:{marginTop:4*(b.length>0)},children:(0,r.jsx)(rN,{error:S})}):(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(b.length>0),padding:"7px 10px",border:"1px solid color-mix(in srgb, var(--danger) 30%, transparent)",borderRadius:6,background:"color-mix(in srgb, var(--danger) 7%, transparent)",color:"var(--danger)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",S]})),C&&(0,r.jsx)("div",{role:"status",style:{marginTop:8*(b.length>0),padding:"7px 10px",border:"1px solid color-mix(in srgb, var(--warning) 35%, transparent)",borderRadius:6,background:"color-mix(in srgb, var(--warning) 8%, transparent)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:f("chat.truncatedByOutputLimit")}),p&&p.length>0&&(0,r.jsx)(rf,{files:p,onOpenFile:l}),I&&(0,r.jsxs)("div",{"data-answer-footer":!0,style:{display:"flex",alignItems:"center",gap:6,marginTop:2},children:[M&&(0,r.jsx)("div",{"data-answer-model":!0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-ui)"},children:M}),(N||E)&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginLeft:"auto",flexShrink:0},children:[N&&(0,r.jsx)("button",{type:"button",className:"answer-copy-button message-action-button","data-copied":x?"true":void 0,onClick:()=>{rn(N).then(()=>{v(!0),setTimeout(()=>v(!1),1500)})},title:f(x?"i18n.copied":"i18n.copyMessage"),"aria-label":f(x?"i18n.copied":"i18n.copy"),children:x?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),E&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,fontVariantNumeric:"tabular-nums",userSelect:"none"},children:E})]})]})]}):null}function rN({error:e}){let{t}=(0,w.s)(),[n,s]=(0,i.useState)(!1),a=(0,i.useId)(),l=(0,i.useMemo)(()=>{let t=e.replace(/^(Error:\s*)+/i,"").trim();return t.split("\n")[0]||t},[e]);return(0,r.jsxs)("div",{"data-step-card":"",style:{borderRadius:6,overflow:"hidden",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",border:"1px solid color-mix(in srgb, var(--danger) 35%, transparent)",background:"color-mix(in srgb, var(--danger) 5%, transparent)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:(0,r.jsxs)("button",{type:"button","aria-expanded":n,"data-step-trigger":"","aria-controls":a,title:t(n?"chat.collapseProcess":"chat.expandProcess"),onClick:()=>s(e=>!e),style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"3px 8px",minHeight:24,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"var(--danger)",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),(0,r.jsx)("span",{style:{color:"var(--danger)",fontSize:11,lineHeight:1.35,flexShrink:0},children:t("chat.modelError")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0,lineHeight:1.35},children:l}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,display:"block",transform:n?"rotate(180deg)":"none",transition:"transform 0.15s, opacity 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),n&&(0,r.jsxs)("div",{id:a,style:{padding:"8px 10px",background:"var(--bg)",borderTop:"1px solid color-mix(in srgb, var(--danger) 20%, transparent)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,color:"var(--danger)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",e]})]})}function rE({seconds:e,startTime:t,live:n}){let{t:s}=(0,w.s)(),[a,l]=(0,i.useState)(Date.now);(0,i.useEffect)(()=>{if(!n)return;let e=setInterval(()=>l(Date.now()),500);return()=>clearInterval(e)},[n]);let o=n&&void 0!==t?Math.max(0,Math.round((a-t)/1e3)):e;if(void 0===o)return null;let d=void 0!==t?s("chat.stepStartedAt",{time:new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):void 0;return(0,r.jsx)("span",{title:d,style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums",lineHeight:1.35},children:(0,b.a3)(o,s)})}function rM({block:e,searchTarget:t,toolResults:n,isStreaming:i,streamingDuration:s,startTime:a,live:l,toolCallDurations:o,cwd:d,onOpenFile:c,onOpenSession:u,sessionId:h,entryId:p,blockIndex:m}){if("text"===e.type){let n=e.text;return i||n&&""!==n.trim()?(0,r.jsx)("div",{"data-message-text":!0,"data-search-target":t||void 0,children:(0,r.jsx)(rI,{block:e,isStreaming:i,cwd:d,onOpenFile:c})}):null}if("image"===e.type){let n=rJ(e);return n?(0,r.jsx)("div",{"data-search-target":t||void 0,style:{margin:"8px 0"},children:(0,r.jsx)(eh,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})})}):null}if("thinking"===e.type)return(0,r.jsx)(rL,{block:e,duration:s,startTime:a,live:l,sessionId:h,entryId:p,blockIndex:m});if("toolCall"===e.type){let t=n?.get(e.toolCallId),i=o?.get(e.toolCallId);return(0,r.jsx)(rT,{block:e,result:t,duration:i,startTime:a,live:l,onOpenSession:u})}return null}function rI({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(rv,{className:"markdown-assistant-message",isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rL({block:e,duration:t,startTime:n,live:s,sessionId:a,entryId:l,blockIndex:o}){var d;let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(rg),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),[x,v]=(0,i.useState)(null),y=(0,i.useRef)(c);y.current=c;let b=(d=e.thinking,d.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>h(rg());return window.addEventListener(rm,e),()=>window.removeEventListener(rm,e)},[]),(0,i.useEffect)(()=>{if(!u||!e.deferred||null!==p)return;if(!a||!l)return void v(y.current("i18n.thinkingUnavailable"));let t=!1;return f(!0),v(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=rx.get(r);if(i)return rx.delete(r),rx.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw rx.delete(r),e});if(rx.set(r,s),rx.size>100){let e=rx.keys().next().value;e&&rx.delete(e)}return s})(a,l,o).then(e=>{t||(m(e),f(!1))}).catch(e=>{t||(v(e instanceof Error?e.message:String(e)),f(!1))}),()=>{t=!0}},[u,e.deferred,p,a,l,o]),(0,r.jsxs)("div",{"data-step-card":"",style:{borderRadius:6,overflow:"hidden",border:"1px solid var(--border)",background:"var(--bg-subtle)",transition:"border-color 0.15s ease"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:(0,r.jsxs)("button",{type:"button","aria-expanded":u,"data-step-trigger":"","aria-label":`${c("i18n.thinking")}${b?`: ${b}`:""}`,title:c("i18n.thinking"),onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"3px 8px",minHeight:24,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0},children:(0,r.jsx)(eK,{active:u,size:12})}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-ui)",fontSize:11,lineHeight:1.35,flexShrink:0},children:c("i18n.thinking")}),!u&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-ui)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0,lineHeight:1.35},children:b?(0,r.jsx)(nx.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:b}):"..."}),u&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsx)(rE,{seconds:t,startTime:n,live:s}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,display:"block",transform:u?"rotate(180deg)":"none",transition:"transform 0.15s, opacity 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),u&&(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",fontFamily:"var(--font-ui)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,color:x?"var(--danger)":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:g?c("i18n.loadingThinking"):x??(e.deferred?p:e.thinking)})]})}function rT({block:e,result:t,duration:n,startTime:s,live:a,onOpenSession:l}){var o,d;let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(!1),p=(d=e).rawInput??JSON.stringify(d.input,null,2),m=void 0!==e.rawInput,g=nl(e.toolName),f=no(e.toolName),x=f?"string"==typeof e.input?.patch?e.input.patch:function(e){if(!e)return;let t=/"patch"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(e);if(!t)return;let n=t[1];if(!n.endsWith("\\")||n.endsWith("\\\\"))try{return JSON.parse(`"${n}"`)}catch{return}}(e.rawInput):void 0,v=ew(e.toolName,e.input,t?.details),y="edit"===v?c("image.edit"):"generate"===v?c("image.generate"):e.toolName,b=t&&!t.isError?function(e){var t;let n=e.details;if(!("object"==typeof(t=n)&&null!==t&&!Array.isArray(t)))return null;let r="string"==typeof n.patch?n.patch:null;if(r)return{text:r};let i="string"==typeof n.diff?n.diff:null;return i?{text:i}:null}(t):null,j=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,k=rV(t?.content??[]),S=null!==j&&("(no output)"===j.trim()||""===j.trim()),C=t?.isError??!1,N=(o=t?.details)&&"object"==typeof o&&"pi-web-subagent"===o.kind&&"string"==typeof o.sessionId?t.details:null;return(0,r.jsxs)("div",{"data-step-card":"",style:{borderRadius:6,overflow:"hidden",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",border:C?"1px solid color-mix(in srgb, var(--danger) 45%, transparent)":"1px solid var(--border)",background:C?"color-mix(in srgb, var(--danger) 5%, transparent)":"var(--bg-subtle)",transition:"border-color 0.15s ease"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":u,"data-step-trigger":"",onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"3px 8px",minHeight:24,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:C?"var(--danger)":void 0},children:(0,r.jsx)(ro,{toolName:e.toolName,isError:C,size:12})}),(0,r.jsx)("span",{style:{color:C?"var(--danger)":"var(--text)",fontSize:11,lineHeight:1.35,flexShrink:0},children:y}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0,lineHeight:1.35},children:m?c("chat.generatingToolInput"):function(e){let t=e.input;if(!t||"object"!=typeof t)return"";let n=Object.keys(t);return 0===n.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[n[0]]).slice(0,120)}(e)}),(0,r.jsx)(rE,{seconds:n,startTime:s,live:a}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,display:"block",transform:u?"rotate(180deg)":"none",transition:"transform 0.15s, opacity 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),N&&l&&(0,r.jsx)("button",{type:"button",onClick:()=>l(N.sessionId),title:c("subagent.open"),"aria-label":c("subagent.open"),style:{width:30,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})})]}),u&&(m||!g)&&!f&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg)",borderTop:C?"1px solid color-mix(in srgb, var(--danger) 25%, transparent)":"1px solid color-mix(in srgb, var(--border) 80%, transparent)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:p}),u&&f&&void 0!==x&&(0,r.jsx)("div",{style:{borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",background:"var(--bg)"},children:(0,r.jsx)(rP,{patch:x})}),u&&f&&void 0===x&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg)",borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:c("chat.generatingToolInput")}),u&&t&&!(f&&void 0!==x)&&(b?(0,r.jsx)(rR,{diff:b}):(0,r.jsx)(rB,{text:j??"",images:k,isEmpty:S,isError:C})),!u&&k.length>0&&(0,r.jsx)("div",{style:{padding:"6px 10px 8px",borderTop:C?"1px solid color-mix(in srgb, var(--danger) 25%, transparent)":"1px solid color-mix(in srgb, var(--border) 80%, transparent)",background:"var(--bg)"},children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:(0,r.jsx)(r$,{images:k,thumbnails:!0})})})]})}function r$({images:e,thumbnails:t=!1}){return(0,r.jsx)(r.Fragment,{children:e.map((e,n)=>{let i=rJ(e);return i?(0,r.jsx)(eh,{src:i,style:{maxWidth:"100%"},children:(0,r.jsx)("img",{src:i,alt:"",loading:"lazy",style:{display:"block",borderRadius:6,objectFit:"contain",border:"1px solid var(--border)",...t?{maxWidth:220,maxHeight:150}:{maxWidth:"min(100%, 720px)",maxHeight:520}}})},`${i}-${n}`):null})})}function rR({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid color-mix(in srgb, var(--success) 15%, transparent)",background:"var(--bg)"},children:(0,r.jsx)(rW,{text:e.text})})}function rW({text:e}){let t=(0,i.useMemo)(()=>ru(e),[e]);return t?(0,r.jsx)(rz,{files:t}):(0,r.jsx)(rF,{text:e})}function rP({patch:e}){let t=(0,i.useMemo)(()=>ne(e),[e]);return t?(0,r.jsx)(rz,{files:t.map(e=>({oldPath:"add"===e.operation?void 0:e.path,newPath:"delete"===e.operation?void 0:e.moveTo??e.path,rows:e.rows}))}):(0,r.jsx)(rF,{text:e})}function rz({files:e}){let{t}=(0,w.s)(),n=e.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:e.map((e,i)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===i?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[n&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(rD,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(rD,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(rA,{cell:e.left,side:"left"}),(0,r.jsx)(rA,{cell:e.right,side:"right"})]},t))})]},i))})}function rD({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function rA({cell:e,side:t}){let n="added"===e.type?"color-mix(in srgb, var(--success) 12%, transparent)":"removed"===e.type?"color-mix(in srgb, var(--danger) 13%, transparent)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:s,userSelect:"none",flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function rF({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{style:{maxHeight:520,overflowY:"auto",overflowX:"hidden",fontFamily:"var(--font-mono)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"color-mix(in srgb, var(--success) 12%, transparent)":"removed"===n?"color-mix(in srgb, var(--danger) 13%, transparent)":"hunk"===n?"color-mix(in srgb, var(--accent) 12%, transparent)":"transparent",borderLeft:"added"===n?"3px solid var(--success)":"removed"===n?"3px solid var(--danger)":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"var(--success)":"removed"===n?"var(--danger)":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function rB({text:e,images:t,isEmpty:n,isError:i}){let{t:s}=(0,w.s)(),a=!n||0===t.length;return(0,r.jsxs)("div",{style:{borderTop:`1px solid ${i?"color-mix(in srgb, var(--danger) 30%, transparent)":"color-mix(in srgb, var(--success) 15%, transparent)"}`,background:i?"color-mix(in srgb, var(--danger) 4%, transparent)":"var(--bg-subtle)"},children:[t.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",padding:"10px",background:"var(--bg)"},children:(0,r.jsx)(r$,{images:t})}),a&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:i?"var(--danger)":n?"var(--text-dim)":"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:n?s("i18n.noOutput"):e})]})}function rO({message:e}){let{t}=(0,w.s)(),n=rK(e.content),s=(0,i.useMemo)(()=>{let e,t,r,i,s;return e=[],t=[],r=n.match(rc),i=r?.[1]??"",s=r?.index===void 0?n:n.slice(0,r.index),i.replace(rd,(n,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):t.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:t}},[n]),a=rb(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontSize:11},children:"compaction"}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:11},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",fontWeight:600,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:t("i18n.compactionDescription")}),s.body?(0,r.jsx)(rl,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(rH,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})]})})}function rH({readFiles:e,modifiedFiles:t}){let{t:n}=(0,w.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(rU,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(rU,{title:n("i18n.readFiles"),files:e})]})}function rU({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function r_({message:e,cwd:t,onOpenFile:n}){let{t:s}=(0,w.s)(),[a,l]=(0,i.useState)(!1),o=(e.details?.sessionIds??[]).length||1,d=1===o?s("subagent.notificationSingle"):s("subagent.notificationMany",{count:o}),c=rK(e.content);return(0,r.jsxs)("div",{"data-step-card":"",style:{overflow:"hidden",borderRadius:4},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":a,"data-step-trigger":"",title:d,onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:24,padding:"3px 8px",border:"none",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{width:14,height:14,display:"grid",placeItems:"center",flexShrink:0},children:(0,r.jsx)(G,{size:12})}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:d}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,transform:a?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),a&&c&&(0,r.jsx)("div",{style:{padding:"7px 10px 8px 28px",borderTop:"1px solid color-mix(in srgb, var(--border) 65%, transparent)",color:"var(--text-muted)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.48},children:(0,r.jsx)(rv,{className:"markdown-subagent-notification",cwd:t,onOpenFile:n,children:c})})]})}function rq({message:e,cwd:t,onOpenFile:n}){let s,{t:a}=(0,w.s)(),l=!1===e.display,[o,d]=(0,i.useState)(!l),[c,u]=(0,i.useState)(!1),[h,p]=(0,i.useState)(!1),m=rK(e.content),g=rV(e.content),f=void 0!==e.details,x=f?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",v=e.customType||"extension",y=rb(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:l?"var(--bg-subtle)":"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:11},children:v}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:a("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:11},children:y})]}),o?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!m},children:g.map((e,t)=>{let n=rJ(e);return n?(0,r.jsx)(eh,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t):null})}),m?(0,r.jsx)(rl,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:m}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:a("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>d(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?(s=m.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"Show extension message":a("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[m||x?(0,r.jsx)("button",{onClick:()=>{rn(m||x).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:a(h?"i18n.copied":"i18n.copy")}):null,(f||l)&&(0,r.jsx)("button",{onClick:()=>{l?d(e=>!e):u(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:a(l?o?"i18n.collapse":"i18n.expand":c?"i18n.hideDetails":"i18n.showDetails")})]}),f&&(l&&o||!l&&c)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:x})]})})}function rK(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rV(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function rJ(e){return 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}`:""}function rY({message:e,sessionId:t}){let[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(null),c=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,h=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,p=e.truncated&&h&&null===n,m=n??e.output;async function g(){if(h){l(!0),d(null);try{let e=await fetch(h),t=await e.json();t.success?s(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{l(!1)}}}let f=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:f,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:f,content:m?[{type:"text",text:m}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(rT,{block:x,result:v}),e.truncated&&h&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[p&&(0,r.jsx)("button",{onClick:g,disabled:a,style:{background:"none",border:"none",color:"var(--accent)",cursor:a?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:a?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${h}&download=1`,style:{marginLeft:10*!!p,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),o&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",o,")"]})]})]})}function rZ(e,t){let n=new Set(e),r=new Map,i=t.find(e=>n.has(e)),s=void 0===i?e.length:e.indexOf(i),a=e[s-1]??null;for(let e of t)n.has(e)&&(a=e),null!==a&&r.set(e,a);for(let t of e)r.set(t,t);return r}function rX(e,t,n){return n-t>0&&e+t>=n-8?1/0:e+48}function rG(e,t){if(!e.length)return null;let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;e[i].top<=t?n=i+1:r=i}return e[Math.max(0,n-1)].userId}var rQ=n(88576),r0=n.n(rQ);function r1({items:e,activeEntryId:t,onJumpToEntry:n,label:s,left:a,top:l,maxHeight:o=360,width:d=310}){var c,u;let h,p,m,{t:g}=(0,w.s)(),f=(0,i.useRef)(null),x=(0,i.useRef)(null),[v,y]=(0,i.useState)(!1),[b,j]=(0,i.useState)(0),[k,S]=(0,i.useState)(0),[C,N]=(0,i.useState)(null),E=(0,i.useRef)(0),M=(0,i.useRef)(null),I=(0,i.useRef)(!1),L=(0,i.useRef)(null),T=(0,i.useRef)(null),$=(0,i.useRef)(null),R=(0,i.useId)(),W=e.findIndex(e=>e.entryId===t),P={start:h=Math.max(0,Math.min(W-Math.floor(7.5),(c=e.length)-15)),end:Math.min(c,h+15)},z=Math.min(28*e.length,o-28*(C?.state==="error")),{start:D,end:A}=(u=e.length,p=Math.min(z,28*u),{start:Math.max(0,Math.floor((m=Math.max(0,Math.min(b,28*u-p)))/28)-1),end:Math.min(u,Math.ceil((m+p)/28)+1)});(0,i.useEffect)(()=>()=>{E.current++,L.current&&clearTimeout(L.current),T.current&&clearTimeout(T.current),$.current&&clearTimeout($.current)},[]);let F=(0,i.useCallback)(()=>{L.current&&clearTimeout(L.current),T.current&&clearTimeout(T.current),$.current&&clearTimeout($.current),M.current=null,y(!1)},[]),B=(0,i.useCallback)(()=>{T.current&&(clearTimeout(T.current),T.current=null),v||(L.current=setTimeout(()=>{y(!0)},100))},[v]),O=(0,i.useCallback)(e=>{L.current&&(clearTimeout(L.current),L.current=null);let t=document.activeElement;t instanceof HTMLElement&&e.currentTarget.contains(t)&&t.matches(":focus-visible")||(T.current=setTimeout(()=>{F()},150))},[F]);async function H(e){let t=++E.current;N({entryId:e,state:"loading"});try{await n(e),E.current===t&&(N(null),$.current&&clearTimeout($.current),$.current=setTimeout(()=>{F()},160))}catch(n){if(E.current!==t)return;if(n&&"object"==typeof n&&"name"in n&&"AbortError"===n.name)return void N(null);N({entryId:e,state:"error",message:n instanceof Error?n.message:String(n)})}}function U(t){let n=Math.max(0,Math.min(e.length-1,t));M.current=n,S(n);let r=x.current;if(r){var i;let e;i=r.scrollTop,r.scrollTop=(e=28*n)<i?e:e+28>i+z?e+28-z:i,j(r.scrollTop);let t=r.querySelector(`[data-outline-index="${n}"]`);t&&(M.current=null,t.focus({preventScroll:!0}))}y(!0)}return((0,i.useLayoutEffect)(()=>{if(!v){I.current=!1;return}let e=x.current;if(e){if(!I.current){let t=Math.max(0,W);e.scrollTop=Math.max(0,(t+.5)*28-z/2),S(t),I.current=!0}j(e.scrollTop)}},[v,W,z]),(0,i.useLayoutEffect)(()=>{if(!v||null===M.current)return;let e=x.current?.querySelector(`[data-outline-index="${M.current}"]`);e&&(M.current=null,e.focus({preventScroll:!0}))}),e.length)?(0,r.jsxs)("div",{className:r0().minimap,style:{left:a,top:l},onMouseEnter:B,onMouseLeave:O,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||F()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),F(),f.current?.focus({preventScroll:!0}))},children:[(0,r.jsx)("button",{ref:f,type:"button",className:r0().trigger,style:{height:Math.min(o,Math.max(20,(P.end-P.start)*8+6))},"aria-label":s,"aria-expanded":v,"aria-controls":v?R:void 0,"aria-busy":C?.state==="loading"||void 0,onClick:e=>{0===e.detail?U(Math.max(0,W)):(L.current&&clearTimeout(L.current),T.current&&clearTimeout(T.current),y(e=>!e))},onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),U(Math.max(0,W)))},children:e.slice(P.start,P.end).map((e,n)=>(0,r.jsx)("span",{className:r0().marker,"data-marker-index":P.start+n,"data-active":t===e.entryId?"true":void 0,"aria-hidden":"true"},e.entryId))}),v&&(0,r.jsx)("div",{className:r0().panel,style:{width:d},children:(0,r.jsxs)("nav",{id:R,className:r0().menu,"aria-label":s,children:[(0,r.jsx)("div",{ref:x,className:r0().list,style:{height:z},onScroll:e=>j(e.currentTarget.scrollTop),children:(0,r.jsx)("div",{className:r0().track,style:{height:28*e.length},children:e.slice(D,A).map((n,i)=>{let s=D+i;return(0,r.jsx)("button",{type:"button",className:r0().row,style:{top:28*s},"data-outline-index":s,"aria-current":t===n.entryId?"location":void 0,"aria-label":n.preview,tabIndex:s===(k>=D&&k<A?k:D)?0:-1,onFocus:()=>S(s),onKeyDown:t=>{let n={ArrowDown:s+1,ArrowUp:s-1,Home:0,End:e.length-1,PageDown:s+Math.max(1,Math.floor(z/28)),PageUp:s-Math.max(1,Math.floor(z/28))};t.key in n&&(t.preventDefault(),U(n[t.key]))},onClick:()=>{H(n.entryId)},children:(0,r.jsx)("span",{className:r0().rowText,children:n.preview})},n.entryId)})})}),C?.state==="error"&&(0,r.jsxs)("div",{className:r0().status,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{children:`${g("chatMinimap.jumpFailed")||"跳转失败:"}${C.message||"请重试"}`}),(0,r.jsx)("button",{type:"button",onClick:()=>{H(C.entryId)},children:g("chatMinimap.retry")||"重试"})]})]})})]}):null}function r2({items:e,scrollContainer:t,contentContainer:n,loadedEntryIds:s,onJumpToEntry:a,label:l}){let[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),h=(0,i.useMemo)(()=>rZ(e.map(e=>e.entryId),s),[e,s]);return((0,i.useEffect)(()=>{let r=t.current,i=n.current;if(!r||!i)return;let s=0,a=!0,l=[],o=[],c=new ResizeObserver(()=>m()),p=()=>{s||(s=requestAnimationFrame(g))},m=()=>{a=!0,p()};function g(){if(s=0,a){a=!1;let t=r.getBoundingClientRect(),n=Math.max(0,t.top),s=Math.min(window.innerHeight,t.bottom),d=Math.min(window.innerWidth,t.right),p=Math.max(0,Math.min(360,s-n-16)),m={left:d-26,top:(n+s-Math.min(p,Math.max(20,8*Math.min(15,e.length)+6)))/2,maxHeight:p,width:Math.max(0,Math.min(310,d-Math.max(0,t.left)-36))};u(e=>e&&e.left===m.left&&e.top===m.top&&e.maxHeight===p&&e.width===m.width?e:m);let g=Array.from(i.children).filter(e=>e instanceof HTMLElement&&e.hasAttribute("data-entry-id"));l=g.flatMap(e=>{let n=h.get(e.dataset.entryId);return n?[{userId:n,top:e.getBoundingClientRect().top-t.top-r.clientTop+r.scrollTop}]:[]}).sort((e,t)=>e.top-t.top);let f=new Set(g),x=new Set(o);for(let e of o)f.has(e)||c.unobserve(e);for(let e of g)x.has(e)||c.observe(e);o=g}d(rG(l,rX(r.scrollTop,r.clientHeight,r.scrollHeight)))}c.observe(r),c.observe(i);let f=new MutationObserver(m);f.observe(i,{subtree:!0,childList:!0,characterData:!0,attributes:!0}),r.addEventListener("scroll",p,{passive:!0}),window.addEventListener("resize",m);let x=e=>{e.target!==r&&e.target instanceof Node&&e.target.contains(r)&&m()};return window.addEventListener("scroll",x,!0),p(),()=>{cancelAnimationFrame(s),c.disconnect(),f.disconnect(),r.removeEventListener("scroll",p),window.removeEventListener("resize",m),window.removeEventListener("scroll",x,!0)}},[e.length,h,t,n]),!c||c.maxHeight<52||c.width<80)?null:(0,M.createPortal)((0,r.jsx)(r1,{items:e,activeEntryId:o,onJumpToEntry:a,label:l,...c}),document.body)}let r4=[];function r8(e,t,n){let r=JSON.stringify([e,t]),[s,a]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return;let n=new AbortController,i=new URLSearchParams;t&&i.set("leafId",t);let s=i.toString();return fetch(`/api/sessions/${encodeURIComponent(e)}/outline${s?`?${s}`:""}`,{signal:n.signal}).then(async e=>e.ok?e.json():{items:[]}).then(e=>{n.signal.aborted||a({key:r,items:e.items??[]})}).catch(()=>{n.signal.aborted||a({key:r,items:[]})}),()=>n.abort()},[e,t,n,r]),e&&s?.key===r)?s.items:r4}function r3({sessionId:e,leafId:t,outlineRevision:n,...i}){let{t:s}=(0,w.s)(),a=r8(e,t,n);return e&&a.length?(0,r.jsx)(r2,{...i,items:a,label:s("chatMinimap.userOutline")},JSON.stringify([e,t])):null}function r6({sessionId:e,leafId:t,outlineRevision:n,scrollContainer:r,contentContainer:s,loadedEntryIds:a,onJumpToEntry:l,onChange:o}){let d=r8(e,t,n);return(0,i.useEffect)(()=>{o?.({items:d,scrollContainer:r,contentContainer:s,loadedEntryIds:a,onJumpToEntry:l})},[d,r,s,a,l,o]),(0,i.useEffect)(()=>()=>{o?.(null)},[o]),null}function r5({view:e,onClose:t}){let{t:n}=(0,w.s)(),{items:s,scrollContainer:a,contentContainer:l,loadedEntryIds:o,onJumpToEntry:d}=e,[c,u]=(0,i.useState)(()=>s[s.length-1]?.entryId??null),h=(0,i.useRef)(null),p=(0,i.useRef)(null);return(0,i.useLayoutEffect)(()=>{if(!s.length||!a?.current||!l?.current)return;let e=a.current,t=l.current,n=rZ(s.map(e=>e.entryId),o??[]),r=e.getBoundingClientRect(),i=[];for(let s of t.querySelectorAll("[data-entry-id]")){let t=n.get(s.dataset.entryId??"");t&&i.push({userId:t,top:s.getBoundingClientRect().top-r.top-e.clientTop+e.scrollTop})}i.sort((e,t)=>e.top-t.top),u(rG(i,rX(e.scrollTop,e.clientHeight,e.scrollHeight))??s[s.length-1]?.entryId??null)},[s,o,a,l]),(0,i.useLayoutEffect)(()=>{let e=h.current,t=p.current;if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();n.top<r.top?t.scrollTop+=n.top-r.top:n.bottom>r.bottom&&(t.scrollTop+=n.bottom-r.bottom)},[c]),(0,r.jsx)("div",{ref:p,className:"overflow-y-auto overscroll-contain border-b border-[var(--border)] py-1.5",style:{maxHeight:"inherit"},children:0===s.length?(0,r.jsx)("div",{style:{padding:"12px 16px",color:"var(--text-muted)",fontSize:12},children:n("chatMinimap.empty")}):s.map((e,n)=>{let i=c===e.entryId;return(0,r.jsxs)("button",{ref:i?h:void 0,type:"button",className:"mobile-outline-row","aria-current":i?"location":void 0,onClick:()=>{t(),d(e.entryId)},children:[(0,r.jsx)("span",{className:`w-5 shrink-0 text-right tabular-nums text-[12px] leading-[18px] select-none ${i?"text-[var(--accent)]":"text-[var(--text-dim)]"}`,"aria-hidden":"true",children:n+1}),(0,r.jsx)("span",{className:"flex-1 min-w-0 line-clamp-2 text-[12px] leading-[18px]",style:{hangingPunctuation:"first"},children:e.preview})]},e.entryId)})})}var r7=n(42790);function r9({text:e}){let t=(0,i.useMemo)(()=>new r7.v().ansi_to_html(e),[e]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:t}})}let ie="/icons/icon-192.png";function it(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function ir(e){let t;if("u"<typeof Notification)return()=>{};e(Notification.permission);let n="u"<typeof navigator?void 0:navigator.permissions;if(!n?.query)return()=>{};let r=!1;return n.query({name:"notifications"}).then(n=>{r||(t=n,n.onchange=()=>e(Notification.permission))}).catch(()=>{}),()=>{r=!0,t&&(t.onchange=null)}}function ii(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}async function is(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,icon:ie,badge:ie,...e.tag?{tag:e.tag,renotify:!0}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}function ia(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function il(e,t={}){if("assistant"!==e.role)return e;let n=e.content;if(!Array.isArray(n))return e;let r=n.map(e=>(function(e,t={}){if(!ia(e)||"toolCall"!==e.type)return null;let n={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},r=t.includeStreamingRawInput?function(e){if("string"==typeof e.rawInput)return e.rawInput;if("string"==typeof e.partialJson)return e.partialJson;if("string"==typeof e.partialArgs)return e.partialArgs;let t=ia(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=ia(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}let io=new Map,id=new Map,ic="pi-web:models:",iu=new Set(["set_model","set_thinking_level"]);class ih extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function ip(e){return e instanceof ih&&"prompt_rejected"===e.code&&!1===e.accepted}async function im(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new ih(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return iu.has(t.type)&&io.clear(),r.data}let ig=["off","minimal","low","medium","high","xhigh","max"];function ix(e,t){if(!e?.length||e.includes(t))return t;let n=ig.indexOf(t);if(-1===n)return e[0];for(let t=n+1;t<ig.length;t++)if(e.includes(ig[t]))return ig[t];for(let t=n-1;t>=0;t--)if(e.includes(ig[t]))return ig[t];return e[0]}let iv="pi-tool-preset";function iy(){try{return window.localStorage}catch{return null}}function ib(e,t){t&&(e.tokens.input+=t.input??0,e.tokens.output+=t.output??0,e.tokens.cacheRead+=t.cacheRead??0,e.tokens.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost?.total??0,e.costs.input+=t.cost?.input??0,e.costs.output+=t.cost?.output??0,e.costs.cacheRead+=t.cost?.cacheRead??0,e.costs.cacheWrite+=t.cost?.cacheWrite??0)}function iw(e){let t={userMessages:0,assistantMessages:0,toolCalls:0,toolResults:0,totalMessages:0,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,costs:{input:0,output:0,cacheRead:0,cacheWrite:0}};for(let n of e)"custom"!==n.role&&(t.totalMessages+=1,"user"===n.role?t.userMessages+=1:"toolResult"===n.role?(t.toolResults+=1,ib(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),ib(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function ij(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function ik(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(ij).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class iS extends Error{constructor(e,t){super(t??("ready_timeout"===e?"Timed out starting the agent session. Please try again.":"Failed to connect to the agent event stream. Please try again.")),this.status=e,this.name="AgentEventConnectionError"}}class iC{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.epoch=0}close(){this.epoch+=1,this.stopRetrying(),this.current&&this.discard(this.current,new iS("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof iS?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}reconnect(e){return this.ensureConnected(e,!0)}async ensureConnected(e,t=!1){let n=this.epoch,r=t;for(;;){if(this.epoch!==n)throw new iS("closed");let t=this.current;if(!t||t.sessionId!==e||r)r=!1,t=this.open(e);else if(t.attempt.ready&&1===t.source.readyState)return;try{await t.attempt.promise}catch(r){if(this.epoch!==n)throw r;if(this.current!==t&&this.current?.sessionId===e)continue;throw r}if(this.epoch!==n)throw new iS("closed");if(this.current!==t){if(this.current?.sessionId===e)continue;throw new iS("closed")}if(1===t.source.readyState)return;this.discard(t,new iS("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new iS("closed"));try{t=this.options.createSource(e)}catch(e){throw new iS("closed",e instanceof Error?e.message:String(e))}let i=!1,s=new Promise((e,t)=>{n=e,r=t}),a=setTimeout(()=>{this.fail(o,new iS("ready_timeout"))},this.options.readinessTimeoutMs),l={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(a),n())},fail(e){i||(i=!0,clearTimeout(a),r(e))}},o={sessionId:e,source:t,attempt:l};return this.current=o,t.onmessage=e=>{let t;if(this.current===o){try{t=JSON.parse(e.data)}catch{return}if("connected"===t.type)l.ready=!0,l.succeed(),this.stopRetrying();else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(o,new iS("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(o,new iS("closed"))},o}fail(e,t){this.current===e&&(this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function iN(e){var t;return("message_start"===e.type||"message_end"===e.type)&&"object"==typeof(t=e.message)&&null!==t&&!Array.isArray(t)&&"system"===e.message.role}let iE={isStreaming:!1,streamingMessage:null};function iM(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],s=n(i[t]);return s?(i[t]=s,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function iI(e,t){switch(t.type){case"text_start":return iM(e,t.contentIndex,()=>({type:"text",text:""}));case"text_delta":return iM(e,t.contentIndex,e=>e?.type==="text"?{...e,text:e.text+t.delta}:null);case"text_end":return iM(e,t.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:t.content}));case"thinking_start":{let n=Date.now(),r=e.streamingMessage;if(!r)return e;let i=[...r.content];for(let e=0;e<i.length;e++){let r=i[e];e!==t.contentIndex&&r?.type==="thinking"&&"number"!=typeof r.endedAt&&(i[e]={...r,endedAt:n})}return i[t.contentIndex]={type:"thinking",thinking:"",startedAt:n},{isStreaming:!0,streamingMessage:{...r,content:i}}}case"thinking_delta":return iM(e,t.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+t.delta,startedAt:e.startedAt??Date.now()}:null);case"thinking_end":return iM(e,t.contentIndex,e=>({...e?.type==="thinking"?e:{startedAt:Date.now()},type:"thinking",thinking:t.content,endedAt:Date.now()}));case"toolcall_start":return iM(e,t.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:t.id??e.toolCallId,toolName:t.toolName??e.toolName,rawInput:""}:"string"!=typeof t.toolName?null:{type:"toolCall",toolCallId:t.id??"",toolName:t.toolName,input:{},rawInput:""});case"toolcall_delta":return iM(e,t.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:t.id||e.toolCallId,toolName:t.toolName||e.toolName,rawInput:(e.rawInput??"")+t.delta}:null);case"toolcall_end":return iM(e,t.contentIndex,()=>({type:"toolCall",toolCallId:t.toolCall.id,toolName:t.toolCall.name,input:t.toolCall.arguments}));default:return e}}function iL(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=il(t.message,{includeStreamingRawInput:!0});if("assistant"!==n.role)return e;let r="number"==typeof n.timestamp?n.timestamp:Date.now(),i=e.streamingMessage,s=n.content.map((e,t)=>{if("thinking"!==e.type)return e;let n=i?.content[t],s=e.startedAt??(n?.type==="thinking"?n.startedAt:void 0)??r,a=e.endedAt??(n?.type==="thinking"?n.endedAt:void 0);return e.startedAt===s&&e.endedAt===a?e:{...e,startedAt:s,..."number"==typeof a?{endedAt:a}:{}}});return{isStreaming:!0,streamingMessage:{...n,timestamp:r,content:s}}}case"delta":return iI(e,t.event);case"deltas":return t.events.reduce(iI,e);case"end":return iE;default:return e}}class iT{begin(e){this.inFlight.add(e)}cancel(e){this.cancelled.add(e)}markDispatched(e){this.dispatched.add(e)}isCancelled(e){return this.cancelled.has(e)}wasDispatched(e){return this.dispatched.has(e)}isInFlight(e){return this.inFlight.has(e)}shouldAbandonUnsent(e){return this.isCancelled(e)&&!this.wasDispatched(e)}forget(e){this.cancelled.delete(e),this.dispatched.delete(e),this.inFlight.delete(e)}constructor(){this.cancelled=new Set,this.dispatched=new Set,this.inFlight=new Set}}function i$(e,t,n,r){return e===t&&"string"==typeof n&&n.length>0&&n===r}async function iR(e){let{gate:t,runId:n}=e;t.begin(n);let r=()=>!(!t.isCancelled(n)||t.wasDispatched(n))&&(e.abandonUnsent(),!0),i=null,s=!1;try{if(r()||(i=await e.prepare(),r()))return{status:"abandoned"};if(!i)throw Error("No active session for the prompt");if(s=!0,t.markDispatched(n),e.onDispatched?.(),await e.send(i),!t.isCancelled(n))return{status:"sent",sessionId:i};if(e.promptPending()&&i$(n,e.currentRunId(),i,e.currentSessionId()))return await e.abort(i),{status:"aborted",sessionId:i};return{status:"stale"}}catch(r){if(!t.isCancelled(n))return{status:"failed",sessionId:i,error:r,requestStarted:s};if(!s)return e.abandonUnsent(),{status:"abandoned"};if(e.promptPending()&&i$(n,e.currentRunId(),i,e.currentSessionId()))return{status:"cancelled_after_dispatch",sessionId:i};return{status:"stale"}}finally{t.forget(n)}}async function iW(e){let t=null,n=!1;try{if(t=await e.prepare(),e.abortRequested())return e.restoreUnsent(),{status:"restored_unsent"};if(!t)throw Error("Unable to create a session for the shell command");return n=!0,await e.send(t),await e.loadResults(t),e.abortRequested()?{status:"cancelled_after_dispatch",sessionId:t}:{status:"completed",sessionId:t}}catch(r){if(!e.abortRequested())throw r;if(!n)return e.restoreUnsent(),{status:"restored_unsent"};if(t)try{await e.loadResults(t)}catch{}return{status:"cancelled_after_dispatch",sessionId:t}}}function iP(e){return(e??[]).map(e=>"string"==typeof e?{text:e,images:[]}:{text:"string"==typeof e.text?e.text:"",images:Array.isArray(e.images)?e.images.flatMap(e=>{let t=e&&"object"==typeof e&&"string"==typeof e.data&&0!==e.data.length&&"string"==typeof e.mimeType&&e.mimeType.startsWith("image/")?{data:e.data,mimeType:e.mimeType}:null;return t?[t]:[]}):[]})}function iz(e){return"string"==typeof e?e:e?.text??""}function iD(e){return{steering:(e?.steering??[]).map(iz),followUp:(e?.followUp??[]).map(iz)}}function iA(e,t){return e===t||null!==e&&null!==t&&e.tokens===t.tokens&&e.percent===t.percent&&e.contextWindow===t.contextWindow?e:t}let iF=[2e3,5e3,1e4];function iB(e){return new Promise(t=>setTimeout(t,e))}function iO(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function iH(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:iO(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iO(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=iO(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function iU(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function i_(e){if(!e?.defaultModel)return null;let t=e.modelList?.find(t=>t.id===e.defaultModel?.modelId&&t.provider===e.defaultModel?.provider);return t?{provider:t.provider,modelId:t.id}:null}function iq(e,t){if(!e||!t)return null;let n=e.thinkingLevelPins?.[`${t.provider}/${t.modelId}`];return n||(e.defaultThinkingLevel?ix(e.thinkingLevels?.[`${t.provider}:${t.modelId}`],e.defaultThinkingLevel):null)}function iK({embedded:e,title:t,subtitle:n,closeLabel:i="Close",onClose:s,children:a,width:l=900,height:o="78vh"}){let d=e?void 0:{"--config-panel-width":`${l}px`,"--config-panel-height":o};return(0,r.jsx)("div",{role:e?void 0:"dialog","aria-modal":e?void 0:"true","aria-label":t,className:`config-panel-root ${e?"is-embedded":"is-modal"}`,onClick:t=>{e||t.target!==t.currentTarget||s()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:d,children:[!e&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:t}),n&&(0,r.jsx)("span",{className:"config-panel-subtitle",title:n,children:n}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:s,title:i,"aria-label":i,children:"\xd7"})]}),a]})})}function iV({label:e,children:t,style:n}){return(0,r.jsxs)("div",{className:"config-field",style:n,children:[(0,r.jsx)("span",{className:"config-field-label",children:e}),t]})}function iJ({children:e}){return(0,r.jsx)("div",{className:"config-empty-state",children:e})}function iY({label:e}){return(0,r.jsx)("p",{role:"status",className:"settings-loading",children:(0,r.jsx)("span",{children:e})})}function iZ({status:e,children:t}){return(0,r.jsxs)("footer",{className:"config-footer",children:[(0,r.jsx)("div",{className:"config-footer-status",children:e}),(0,r.jsx)("div",{className:"config-footer-actions",children:t})]})}function iX({title:e,action:t,children:n}){return(0,r.jsxs)("section",{className:"settings-group",children:[(e||t)&&(0,r.jsxs)("div",{className:"settings-group-header",children:[e&&(0,r.jsx)("h3",{className:"settings-group-title",children:e}),t]}),(0,r.jsx)("div",{className:"settings-group-rows",children:n})]})}function iG({label:e,description:t,htmlFor:n,stacked:i=!1,title:s,children:a}){return(0,r.jsxs)("div",{className:`settings-row${i?" is-stacked":""}`,title:s,children:[(0,r.jsxs)("div",{className:"settings-row-copy",children:[n?(0,r.jsx)("label",{htmlFor:n,className:"settings-row-label",children:e}):(0,r.jsx)("span",{className:"settings-row-label",children:e}),t&&(0,r.jsx)("p",{className:"settings-row-description",children:t})]}),a&&(0,r.jsx)("div",{className:"settings-row-control",children:a})]})}function iQ({label:e,description:t,muted:n=!1,title:i,onOpen:s,children:a}){return(0,r.jsxs)("div",{className:"settings-row is-link",children:[(0,r.jsxs)("button",{type:"button",className:"settings-row-copy settings-row-open",title:i,onClick:s,children:[(0,r.jsx)("span",{className:`settings-row-label${n?" is-dim":""}`,children:e}),t&&(0,r.jsx)("span",{className:"settings-row-description is-clamped",children:t})]}),a&&(0,r.jsx)("div",{className:"settings-row-control",children:a})]})}function i0({label:e,onClick:t}){return(0,r.jsxs)("button",{type:"button","data-settings-back":!0,className:"settings-back-link",onClick:t,children:[(0,r.jsx)("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,r.jsx)("path",{d:"m15 18-6-6 6-6"})}),e]})}function i1({value:e,onChange:t,placeholder:n}){return(0,r.jsxs)("label",{className:"settings-search-field",children:[(0,r.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,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{type:"search",value:e,onChange:e=>t(e.target.value),placeholder:n,"aria-label":n})]})}function i2({label:e,count:t}){return(0,r.jsxs)(r.Fragment,{children:[e,(0,r.jsx)("span",{className:"settings-group-count",children:t})]})}function i4({title:e,meta:t,description:n,children:i}){return(0,r.jsxs)("div",{className:"settings-detail-page",children:[(0,r.jsxs)("header",{className:"settings-detail-header",children:[(0,r.jsx)("h2",{className:"settings-detail-title",children:e}),t&&(0,r.jsx)("div",{className:"settings-detail-meta",children:t}),n&&(0,r.jsx)("p",{className:"settings-detail-description",children:n})]}),i]})}function i8({label:e,options:t,value:n,onChange:i,disabled:s=!1}){return(0,r.jsx)("div",{role:"radiogroup","aria-label":e,className:"settings-segmented",children:t.map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":n===e.value,className:"settings-segmented-option",disabled:s||e.disabled,title:e.title,onClick:()=>i(e.value),children:e.label},e.value))})}function i3({children:e}){return(0,r.jsx)("dl",{className:"settings-properties",children:e})}function i6({label:e,children:t}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:t})]})}function i5({variant:e="secondary",size:t="default",className:n,children:i,...s}){return(0,r.jsx)("button",{type:"button",...s,className:["config-button",`config-button-${e}`,`config-button-${t}`,n].filter(Boolean).join(" "),children:i})}function i7({checked:e,disabled:t=!1,loading:n=!1,label:i,onChange:s}){let a=t||n;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":e,"aria-busy":n||void 0,"aria-label":i,title:i,disabled:a,className:`config-switch${n?" is-loading":""}`,onClick:()=>s(!e),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function i9({tone:e,title:t}){return(0,r.jsx)("span",{role:"img","aria-label":t,title:t,className:`config-status-dot is-${e}`})}function se({showCurrentVersion:e=!1}){let{t}=(0,w.s)(),[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)("idle"),[h,p]=(0,i.useState)(null),m=(0,i.useRef)(!1),g=n?.currentVersion;(0,i.useEffect)(()=>{let e;if("waiting"!==c||!g)return;let t=new AbortController,n=!1,r=setTimeout(()=>{n=!0,t.abort(),clearTimeout(e),u("timeout")},18e4),i=async()=>{try{let e=await fetch("/api/app-update?status=1",{cache:"no-store",signal:t.signal});if(e.ok){let t=await e.json();if(!n&&t.currentVersion&&t.currentVersion!==g){n=!0,clearTimeout(r),window.location.reload();return}}}catch{}n||(e=setTimeout(()=>{i()},2e3))};return i(),()=>{n=!0,t.abort(),clearTimeout(r),clearTimeout(e)}},[c,g]);let f=async()=>{if(!m.current&&window.confirm(t("appUpdate.confirm"))){m.current=!0,p(null),u("requesting");try{let e=await fetch("/api/app-update",{method:"POST"});if(202!==e.status){let n=await e.json().catch(()=>null);throw Error(n?.error||t("appUpdate.failed"))}u("waiting")}catch(e){p(e instanceof Error?e.message:t("appUpdate.failed")),u("idle"),m.current=!1}}},x=(0,i.useCallback)(async(e,t)=>{try{let n=await fetch(e?"/api/app-update?force=1":"/api/app-update",{cache:"no-store",signal:t});if(!n.ok)throw Error(`HTTP ${n.status}`);s(await n.json()),l(!1)}catch{t?.aborted||l(!0)}},[]);(0,i.useEffect)(()=>{let e=new AbortController;x(!1,e.signal);let t=()=>{"visible"===document.visibilityState&&x(!1,e.signal)};return document.addEventListener("visibilitychange",t),()=>{e.abort(),document.removeEventListener("visibilitychange",t)}},[x]);let v=async()=>{d(!0),l(!1),await x(!0),d(!1)},y=n?.updateAvailable&&n.latestVersion&&n.releaseUrl;if(!e&&!y)return null;let b=t("appUpdate.releaseNotes",{version:n?.latestVersion??""}),j=t("appUpdate.updateAndRestart"),k=y&&n?(0,r.jsxs)("a",{className:"app-update-link",href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:b,"aria-label":b,children:["v",n.latestVersion]}):null,S="requesting"===c||"waiting"===c,C=y&&n?.canUpdate?(0,r.jsx)("button",{type:"button",className:"app-update-action",disabled:"idle"!==c,title:S?t("appUpdate.waiting"):j,"aria-label":S?t("appUpdate.waiting"):j,onClick:()=>{f()},children:t(S?"appUpdate.updating":"appUpdate.update")}):null,N=a||n?.releaseUrl?(0,r.jsx)("button",{type:"button",className:"app-update-icon",disabled:o||"idle"!==c,onClick:()=>{v()},title:t("appUpdate.checkNow"),"aria-label":t("appUpdate.checkNow"),children:(0,r.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,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3-6.7L21 8"}),(0,r.jsx)("path",{d:"M21 3v5h-5"})]})}):null,E=e&&y&&!n?.canUpdate||h||"timeout"===c?(0,r.jsxs)("div",{className:"app-update-detail popover-surface",children:[e&&y&&!n?.canUpdate&&(n?.manualCommand?(0,r.jsxs)("p",{children:[t("appUpdate.manualCommand")," ",(0,r.jsx)("code",{children:n.manualCommand})]}):(0,r.jsx)("p",{children:t("appUpdate.manualUpdate")})),h&&(0,r.jsx)("p",{role:"alert",children:h}),"timeout"===c&&(0,r.jsxs)("div",{role:"alert",children:[(0,r.jsx)("p",{children:t("appUpdate.timeout")}),(0,r.jsx)("p",{children:(0,r.jsx)("code",{children:"npm install -g @calmabacus/pi-web@latest"})}),(0,r.jsxs)("p",{children:[t("appUpdate.thenStart")," ",(0,r.jsx)("code",{children:"pi-web"})]})]})]}):null;if(!e)return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"app-update-home",children:[k,C]}),E]});let M=t(!o&&(n||a)?a?"appUpdate.checkFailed":n?.releaseUrl?"appUpdate.upToDate":"appUpdate.checkDisabled":"appUpdate.checking");return(0,r.jsx)(r.Fragment,{children:(0,r.jsx)(iG,{label:t("settings.version"),children:(0,r.jsxs)("span",{className:"app-update-line",children:[(0,r.jsx)("span",{className:"app-update-current",children:t("appUpdate.currentVersion",{version:n?.currentVersion??"1.2.8"??"dev"})}),y?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{"aria-hidden":"true",children:"→"}),k,C]}):(0,r.jsx)("span",{role:"status",className:"app-update-status",children:M}),N,E]})})})}function st(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}function sn({label:e}){return(0,r.jsx)("div",{role:"status","aria-label":e,className:"flex h-[28px] items-center",style:{marginBottom:8},children:(0,r.jsx)(X,{size:12})})}function sr({cwd:e,onChange:t,recentPaths:n,pinnedPaths:s,homeDir:a,worktreeInfo:l}){let{t:o}=(0,w.s)(),d=(0,i.useRef)(null),[c,u]=(0,i.useState)(!1),[h,p]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(!1),[v,y]=(0,i.useState)(null),b=[...s.filter(e=>!n.includes(e)),...n],j=l&&(l.forCwd===e||l.projectRoot===e||l.currentWorktreePath===e||l.worktrees.some(t=>t.path===e))?l:null;(0,i.useEffect)(()=>{if(!c&&!h)return;let e=e=>{d.current?.contains(e.target)||(u(!1),p(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[c,h]);let k=j?.worktrees??[],S=k.find(t=>t.path===e||t.path===j?.currentWorktreePath)??k.find(e=>e.isMain),C=S?.branch??null,N=j?.projectRoot??e,E=a&&N.startsWith(a)?`~${N.slice(a.length)}`:N,M=()=>{u(!1),p(!1)},I=n=>{n===e?M():(x(!0),t(n).then(M).finally(()=>x(!1)))};return(0,r.jsxs)("div",{ref:d,style:{position:"relative",marginTop:10,maxWidth:"100%",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",title:o("chat.changeWorkingDirectory"),"aria-label":`${o("chat.changeWorkingDirectory")}: ${N}`,"aria-expanded":c,onClick:()=>{u(e=>!e),p(!1)},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},style:{maxWidth:"min(80vw, 360px)",border:"none",background:"none",color:"var(--text-muted)",fontSize:12,lineHeight:1.4,padding:0,cursor:"pointer"},children:(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"center"},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:E})})}),C&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{color:"var(--text-dim)",fontSize:12,userSelect:"none"},children:"|"}),(0,r.jsx)("button",{type:"button",title:S?.path,"aria-label":`${o("sidebar.switchWorktree")}: ${C}`,"aria-expanded":h,onClick:()=>{p(e=>!e),u(!1)},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},style:{maxWidth:220,border:"none",background:"none",color:"var(--text-muted)",fontSize:12,lineHeight:1.4,padding:0,cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C})]}),c&&(0,r.jsxs)("div",{role:"listbox","aria-label":o("chat.changeWorkingDirectory"),className:"menu-surface",style:{position:"absolute",top:"calc(100% + 6px)",left:"50%",transform:"translateX(-50%)",width:"max-content",minWidth:200,maxWidth:"min(90vw, 260px)",zIndex:50},children:[(0,r.jsx)("div",{style:{maxHeight:280,overflowY:"auto",scrollbarWidth:"none"},children:b.map(t=>{let n=t===e||!!(j?.projectRoot&&t===j.projectRoot);return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,disabled:f,onClick:()=>I(t),title:t,children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a&&t.startsWith(a)?`~${t.slice(a.length)}`:t})]},t)})}),(0,r.jsx)("button",{type:"button",role:"option","aria-selected":!1,onClick:()=>{u(!1),g(!0),y(null)},style:{marginTop:4,borderTop:"1px solid var(--border)",borderRadius:"0 0 4px 4px"},children:o("sidebar.customPath")})]}),h&&k.length>0&&(0,r.jsx)("div",{role:"listbox","aria-label":o("sidebar.switchWorktree"),className:"menu-surface",style:{position:"absolute",top:"calc(100% + 6px)",left:"50%",transform:"translateX(-50%)",width:"max-content",minWidth:180,maxWidth:"min(90vw, 260px)",zIndex:50},children:(0,r.jsx)("div",{style:{maxHeight:280,overflowY:"auto",scrollbarWidth:"none"},children:k.map(t=>{let n=t.path===e||t.path===j?.currentWorktreePath;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":!!n,disabled:f,onClick:()=>I(t.path),title:t.path,children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.branch??t.path}),t.isMain&&(t.branch??"").toLowerCase()!==o("sidebar.main").toLowerCase()&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:o("sidebar.main")})]},t.path)})})}),m&&(0,r.jsx)($,{initialPath:e,busy:f,error:v,onCancel:()=>{g(!1),y(null)},onSelect:e=>{x(!0),y(null),t(e).then(()=>g(!1),e=>y(e instanceof Error?e.message:String(e))).finally(()=>x(!1))}})]})}function si(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&t4(r))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}function ss(e){return e?.content.at(-1)}function sa(e,t,n,r,i=!1){if(!e)return!1;if(r?.kind==="running_tools")return!0;let s=ss(n);return!!t&&(s?.type==="thinking"||s?.type==="toolCall")||!i}function sl(e,t,n){if(!e)return null;let r=ew(e,t);return"edit"===r?n("image.edit"):"generate"===r?n("image.generate"):null}function so(e,t,n){if(t?.kind==="running_tools"){let e=t.tools[t.tools.length-1]?.name??null;return sl(e,void 0,n)??e}let r=ss(e);return r?.type==="thinking"?n("chat.thinking"):r?.type==="toolCall"?sl(r.toolName,r.input,n)??r.toolName??null:null}function sd(e,t,n,r){return t?(e&&(n.current=e),n.current??r):(n.current=null,null)}function sc(e,t){if("number"==typeof e&&"number"==typeof t&&Number.isFinite(e)&&Number.isFinite(t)&&!(t<=e))return Math.max(1,Math.round((t-e)/1e3))}function su({startTime:e,t}){let[n,s]=(0,i.useState)(()=>Math.max(0,Math.round((Date.now()-e)/1e3)));return(0,i.useEffect)(()=>{let t=setInterval(()=>{s(Math.max(0,Math.round((Date.now()-e)/1e3)))},500);return()=>clearInterval(t)},[e]),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--accent)",fontVariantNumeric:"tabular-nums",flexShrink:0},children:(0,b.a3)(n,t)})}function sh({messageCount:e,toolCallCount:t,durationSeconds:n,startTime:s,defaultExpanded:a=!1,reveal:l=!1,isMobile:o=!1,activeStepSummary:d=null,isStreaming:c=!1,children:u,t:h}){let[p,m]=(0,i.useState)(a),g=(0,i.useRef)(null),f=(0,i.useRef)(!1),x=(0,i.useRef)(!1);(0,i.useLayoutEffect)(()=>{x.current||m(a)},[a]);let v=p||l,y=h(1===t?"chat.step":"chat.steps"),w=void 0!==n&&n>0?(0,b.a3)(n,h):null,j=w?t>0?h("chat.workedForSteps",{duration:w,count:t,steps:y}):h("chat.workedFor",{duration:w}):t>0?`${t} ${y}`:h("chat.processDetails");return(0,i.useLayoutEffect)(()=>{if(!v){f.current=!1;return}let e=g.current;!e||f.current||e.scrollHeight<=e.clientHeight+1||(e.scrollTop=e.scrollHeight)},[v,e,t]),(0,r.jsxs)("div",{style:{marginBottom:v?8:2},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":v,onClick:()=>{x.current=!0,m(e=>!e)},className:"process-details-summary",style:{display:"inline-flex",alignItems:"center",gap:5,maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontFamily:"var(--font-ui)",fontWeight:400,textAlign:"left",transition:"color 0.12s ease"},title:h(v?"chat.collapseProcess":"chat.expandProcess"),children:[c?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(X,{size:12}),s&&(0,r.jsx)(su,{startTime:s,t:h}),(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,minWidth:0,fontSize:11,color:"var(--accent)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"\xb7"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d||h("chat.thinking")})]})]}):(0,r.jsx)("span",{"data-summary-label":"",style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:400,color:"inherit",lineHeight:1.35,transition:"color 0.12s ease"},children:j}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block",transform:v?"rotate(90deg)":"none",transition:"transform 0.15s ease"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"3.5 2 6.5 5 3.5 8"})})]}),v&&(0,r.jsx)("div",{ref:g,onScroll:()=>{let e=g.current;e&&(f.current=!(e.scrollTop+e.clientHeight>=e.scrollHeight-20))},className:"process-details-list",style:{display:"flex",flexDirection:"column",gap:1,margin:"0 -8px",padding:"2px 8px 4px",maxHeight:o?220:280,overflowY:"auto",overflowX:"hidden",overscrollBehavior:"contain",overflowAnchor:"none"},children:u})]})}function sp({session:e,searchTarget:t,onSearchTargetHandled:s,initialScrollPosition:a,onScrollPositionChange:l,sessionRunning:o,newSessionCwd:d,newSessionDraftKey:c,onDraftChange:u,onKeepTabOpen:h,onNewSessionCwdChange:p,recentProjectPaths:m=[],pinnedCwds:g=[],homeDir:f="",worktreeInfo:x=null,draftPersistenceWarning:v=!1,onAgentEnd:y,onAttentionNeeded:b,onSessionCreated:j,onSessionForked:S,modelsRefreshKey:C,chatInputRef:N,isFocusedPane:I=!1,isVisiblePane:L=I,onBranchDataChange:T,onSystemPromptChange:$,onSystemToolsChange:R,onSystemInfoLoaderChange:W,onOutlineViewChange:P,onSessionStatsChange:z,onSessionStatsPanelOpen:D,onContextUsageChange:A,onOpenFile:F,onOpenSession:B,onAskInNewChat:O,quoteSelectionEnabled:H=!1,initialPrompt:U,onInitialPromptConsumed:_,soundEnabled:q=!0,playDoneSound:K=()=>{},unlockAudio:V}){var J;let Y,{t:Z}=(0,w.s)(),X=eX(),G=e?.relation?.kind!=="subagent",Q=(0,i.useRef)(K);Q.current=K;let ee=(0,i.useRef)(q);ee.current=q;let et=(0,i.useRef)(e);et.current=e;let en=(0,i.useRef)(null),er=(0,i.useCallback)(e=>{let t=en.current;en.current=e,N&&(e?N.current=e:N.current===t&&(N.current=null))},[N]),ei=(0,i.useRef)(null),es=(0,i.useCallback)(()=>{G&&ee.current&&Q.current(),y?.(et.current)},[G,y]),ea=(0,i.useCallback)(e=>{b?.(e,et.current)},[b]),el=(0,i.useCallback)(e=>{S?.(e,et.current?.id??null)},[S]),eo=(0,i.useCallback)((e,t)=>{F?.(e,et.current?.id??null,t)},[F]),ed=(0,i.useCallback)(()=>{let e=et.current?.id;e&&h?.(e)},[h]),ec=(0,i.useCallback)(e=>{en.current?.replaceMessage(e)},[]),eu=(0,i.useRef)(t?null:a??null),[eh,em]=(0,i.useState)(()=>{let e=eu.current;return e&&!e.atBottom?e:null}),[eg,ef]=(0,i.useState)(!1),{data:ex,loading:ev,error:ey,messages:ew,activeToolResults:ej,entryIds:ek,historyCursor:eS,hasEarlierMessages:eC,streamState:eM,agentRunning:eI,directImageRunning:eL,bashRunning:eT,pendingBash:e$,modelNames:eR,modelList:eW,modelError:eD,modelScopeWarnings:eA,modelThinkingLevels:eF,modelThinkingLevelMaps:eH,toolPreset:eU,thinkingLevel:e_,retryInfo:eq,contextUsage:eK,forkingEntryId:eV,isCompacting:eJ,compactError:eY,compactResult:eZ,displayModel:eG,modelSwitching:eQ,sessionStats:e0,slashCommands:e1,slashCommandsLoading:e2,queuedMessages:e4,notices:e8,extensionDialog:e3,extensionCustomUi:e6,respondToExtensionUi:e5,sendExtensionCustomInput:e7,addNotice:e9,setNoticePaused:te,isAutoModelSelection:tt,agentPhase:tn,isNew:ti,sessionIdRef:ts,scrollContainerRef:ta,isNearBottomRef:tl,handleSend:to,handleDirectImageGeneration:td,abortDirectImageGeneration:tc,handleAbort:tu,handleFork:th,handleNavigate:tp,handleModelChange:tm,handleCompact:tg,handleSteer:tf,handleFollowUp:tx,handlePromptWithStreamingBehavior:tv,handleAbortCompaction:ty,handleRecallQueue:tb,handleBuiltinSlashCommand:tw,handleToolPresetChange:tj,handleThinkingLevelChange:tk,loadSlashCommands:tS,loadContext:tC,activeLeafId:tN,scrollToBottom:tE,scrollToMessage:tM}=function(e){let{session:t,sessionRunning:r,newSessionCwd:s,newSessionDraftKey:a,onAgentEnd:l,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,onBranchDataChange:h,onSystemPromptChange:p,onSystemToolsChange:m,onSystemInfoLoaderChange:g,onSessionStatsPanelOpen:f,isVisiblePane:x=!1}=e,v=null===t&&null!==s,y=s??t?.cwd??"",b=y?`/api/models?cwd=${encodeURIComponent(y)}`:"/api/models",w=io.get(b)?.data??("u"<typeof localStorage?void 0:function(e){try{let t=localStorage.getItem(ic+e);return t?JSON.parse(t):void 0}catch{return}}(b)),j=v?i_(w):null,k=iq(w,j),[S,C]=(0,i.useState)(null),[N,E]=(0,i.useState)(!v),[M,I]=(0,i.useState)(null),[L,T]=(0,i.useState)(null),[$,R]=(0,i.useState)([]),[W,P]=(0,i.useState)(new Map),[z,D]=(0,i.useState)([]),[A,F]=(0,i.useState)(null),[B,O]=(0,i.useState)(!1),H=(0,i.useRef)({messages:$,entryIds:z,oldestEntryId:A,hasMore:B});H.current={messages:$,entryIds:z,oldestEntryId:A,hasMore:B};let[U,_]=(0,i.useReducer)(iL,iE),q=(0,i.useRef)(U);q.current=U;let[K,V]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),[Z,X]=(0,i.useState)(null),[G,Q]=(0,i.useState)(!1),ee=(0,i.useRef)(!1),et=(0,i.useRef)(null),en=(0,i.useRef)(!1),[er,ei]=(0,i.useState)(()=>w?.models??{}),[es,ea]=(0,i.useState)(()=>w?.modelList??[]),[el,eo]=(0,i.useState)(()=>w?.modelError??null),[ed,ec]=(0,i.useState)(()=>w?.modelScopeWarnings??[]),[eu,eh]=(0,i.useState)(()=>w?.thinkingLevels??{}),[ep,em]=(0,i.useState)(()=>w?.thinkingLevelMaps??{}),[eg,ef]=(0,i.useState)(()=>w?.thinkingLevelPins??{}),[ex,ev]=(0,i.useState)(()=>w?.defaultThinkingLevel),[ey,eb]=(0,i.useState)(null),[ew,ej]=(0,i.useState)(j),[ek,eS]=(0,i.useState)(tr.Q8),[eC,eN]=(0,i.useState)(k),[eE,eM]=(0,i.useState)(null),[eI,eL]=(0,i.useState)(null),[eT,e$]=(0,i.useState)(null),[eR,eW]=(0,i.useState)(null),[eD,eA]=(0,i.useState)(null),[eF,eH]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(!1),[eq,eK]=(0,i.useState)(!1),[eV,eJ]=(0,i.useState)(!0),[eY,eZ]=(0,i.useState)(null),[eX,eG]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)([]),[e4,e8]=(0,i.useState)(!1),[e3,e6]=(0,i.useReducer)(iH,{visible:[],pending:[]}),[e5,e7]=(0,i.useState)(null),[e9,te]=(0,i.useState)(null),[tt,tn]=(0,i.useState)(null),[ti,ts]=(0,i.useState)({steering:[],followUp:[]}),ta=(0,i.useRef)(null),tl=(0,i.useRef)(null),to=(0,i.useRef)(0),td=(0,i.useRef)(!1),tc=(0,i.useRef)(!1),tu=(0,i.useRef)(t?.id??null),th=(0,i.useRef)(t?.id??null),tp=(0,i.useRef)(!!r),tm=(0,i.useRef)(x),tg=(0,i.useRef)(!1),tf=(0,i.useRef)(!1),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(-1),ty=(0,i.useRef)(!1),tb=(0,i.useRef)(!1),tw=(0,i.useRef)(0),tj=(0,i.useRef)(null),tk=(0,i.useRef)(!!e.deferInitialScroll),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(!e.deferInitialScroll),tN=(0,i.useRef)(0),tE=(0,i.useRef)(null),tM=(0,i.useRef)([]),tI=(0,i.useRef)(void 0),tL=(0,i.useRef)(null),tT=(0,i.useRef)(null),t$=(0,i.useRef)(!1),tR=(0,i.useRef)(null),tW=(0,i.useRef)(null),tP=(0,i.useRef)(0),tz=(0,i.useRef)(new iT),tD=(0,i.useRef)(null),tA=(0,i.useRef)(!1),tF=(0,i.useRef)(null),tB=(0,i.useRef)(0),tO=(0,i.useRef)(!1),tH=(0,i.useRef)(u),tU=(0,i.useRef)(new Map),t_=(0,i.useRef)(!0);th.current=t?.id??null,tp.current=!!r,tm.current=x,ta.current||(ta.current=new iC({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tj.current?.(e),shouldMaintain:e=>t_.current&&tu.current===e&&(tm.current||tg.current||td.current||th.current===e&&tp.current),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tq=e.setToolPreset??eS,tK=t?.id;(0,i.useLayoutEffect)(()=>{(tK||v&&!tu.current)&&tq(function(e=iy()){if(!e)return tr.Q8;try{let t=e.getItem(iv);return(0,tr.sn)(t)?t:tr.Q8}catch{return tr.Q8}}())},[tK,v,tq]);let tV=(0,i.useCallback)((e="instant")=>{let t=tL.current;t&&(tC.current=!0,t.scrollTo({top:Math.max(0,t.scrollHeight-t.clientHeight),behavior:e}),tN.current=t.scrollTop)},[]),tJ=eD??S?.context.model??eF??null,tY=v?ey??ew:tJ,tZ=t?.id??a??void 0,tX=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tU.current.get(t);if(!e)break;t=e}return t},[]),tG=(0,i.useCallback)((t,n,r)=>{let i=n?.map(({data:e,mimeType:t})=>({data:e,mimeType:t})),s=tX(r);if(!t_.current&&!t$.current&&r===a)return;let l=e.chatInputRef?.current;if(l)l.restoreSubmission(t,i,s);else{let e,n;s&&(n=eB(t,i,(e=eP(s)??{value:"",images:[]}).value,e.images),ez(s,n))}},[a,e.chatInputRef,tX]),tQ=(0,i.useMemo)(()=>{if(e5)return{...e5,totalActiveMs:S?.totalActiveMs,...eI?{contextUsage:eI}:{}};let e=S?.stats,n=function(e,t,n){let r=iw(n);if(!e)return r;let i=iw(t),s=(e,t)=>Math.max(0,e-t),a={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return a.total=a.input+a.output+a.cacheRead+a.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:a,cost:e.cost+s(r.cost,i.cost),costs:{input:e.costs.input+s(r.costs.input,i.costs.input),output:e.costs.output+s(r.costs.output,i.costs.output),cacheRead:e.costs.cacheRead+s(r.costs.cacheRead,i.costs.cacheRead),cacheWrite:e.costs.cacheWrite+s(r.costs.cacheWrite,i.costs.cacheWrite)}}}(e,S?.context.messages??[],$);return 0!==n.tokens.total||0!==$.length||e?{sessionFile:S?.filePath||void 0,sessionId:tu.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:S?.totalActiveMs,...eI?{contextUsage:eI}:{}}:null},[$,e5,eI,S?.context.messages,S?.filePath,S?.totalActiveMs,S?.stats,t?.id,t?.name]),t0=(0,i.useCallback)(async(e,t=!1,n=!1)=>{let r=!1,i=tB.current;try{t&&E(!0);let s=new URLSearchParams({deferThinking:"1",deferMedia:"1"});n&&s.set("force","1");let a=await fetch(`/api/sessions/${encodeURIComponent(e)}?${s}`);if(404===a.status)return t&&(C(null),T(null),R([]),D([]),F(null),O(!1),eL(null),I(null)),null;if(!a.ok)throw Error(`HTTP ${a.status}`);let l=await a.json();if(tu.current!==e)return null;if(tB.current!==i)return r=!0,t&&E(!1),null;let o={messages:l.context.messages,entryIds:l.context.entryIds??[],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore},d=t?o:function(e,t){if(0===e.entryIds.length||0===t.entryIds.length)return t;let n=new Set(t.entryIds),r=e.entryIds.findIndex(e=>n.has(e));return r<=0?t:{messages:[...e.messages.slice(0,r),...t.messages],entryIds:[...e.entryIds.slice(0,r),...t.entryIds],oldestEntryId:e.oldestEntryId??e.entryIds[0]??t.oldestEntryId,hasMore:e.hasMore}}(H.current,o);if(C({...l,context:{...l.context,...d}}),T(l.leafId),R(d.messages),D(d.entryIds),F(d.oldestEntryId),O(d.hasMore),tc.current=void 0!==l.toolNames,tq(void 0!==l.toolNames?(0,tr.YO)(l.toolNames):tr.Q8),eA(e=>tO.current?e:null),I(null),l.context.thinkingLevel&&eN(l.context.thinkingLevel),void 0!==l.contextUsage&&eL(l.contextUsage??null),r=!0,t&&E(!1),!n)return null;try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(tu.current!==e)return null;let r=n.state;return r?(void 0!==r.contextUsage&&eL(r.contextUsage??null),void 0!==r.systemPrompt&&e$(r.systemPrompt??null),r.thinkingLevel&&eN(r.thinkingLevel),void 0!==r.queuedMessages&&ts(iD(r.queuedMessages))):n.running||ts({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return I(String(e)),null}finally{t&&!r&&E(!1)}},[tq]),t1=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,a=await fetch(s,{signal:r?.signal});if(!a.ok)throw Error(`HTTP ${a.status}`);let l=await a.json();if(tu.current!==e||r?.signal?.aborted||!t_.current)return;return F(l.context.oldestEntryId),O(l.context.hasMore),C(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...l.context.messages,...t.context.messages],entryIds:[...l.context.entryIds,...t.context.entryIds],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore}:l.context;return{...t,context:r}}),n?(R(e=>[...l.context.messages,...e]),D(e=>[...l.context.entryIds,...e])):(R(l.context.messages),D(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),t2=(0,i.useCallback)(async e=>{try{let t=await im(e,{type:"get_tools"});if(!t||!t_.current||tu.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tq(tc.current?r(t):tr.Q8),m?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[m,tq]),t4=(0,i.useCallback)((t=0,n="(no messages)")=>{let r=tu.current;if(v&&s&&r&&!t$.current&&(t$.current=!0,a)){if(a!==r){tU.current.set(a,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(a,r):eO(a,r)}d?.({id:r,path:"",cwd:s,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},a)}},[v,s,a,d,e.chatInputRef]),t8=(0,i.useCallback)(e=>{e instanceof iS||console.error("Failed to maintain the agent event stream:",e)},[]),t3=(0,i.useCallback)(async()=>{if(tu.current||!v||!s)return tu.current;if(tT.current)return tT.current;let e=(async()=>{let e=tR.current,t=tW.current;e&&eH(e);let n=(0,tr.xG)(ek);tc.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:s,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!r.ok)throw Error(`HTTP ${r.status}`);(e||t)&&io.clear();let i=await r.json(),a=i.sessionId;return tu.current=a,tm.current&&ta.current?.ensureConnected(a).catch(t8),void 0!==i.contextUsage&&eL(i.contextUsage??null),i.model&&tR.current===e&&(eH(i.model),e||ej(i.model)),i.thinkingLevel&&tW.current===t&&eN(i.thinkingLevel),a})();tT.current=e;try{return await e}finally{tT.current=null}},[t8,v,s,ek]),t6=(0,i.useCallback)(async()=>{let e=tu.current??await t3();if(!e)return;let[t]=await Promise.all([im(e,{type:"get_state"}),t2(e)]);t_.current&&tu.current===e&&e$(t.systemPrompt??"")},[t3,t2]),t5=(0,i.useCallback)(async()=>{let e=tu.current??await t3();if(!e)return e2([]),[];e8(!0);try{let t=await im(e,{type:"get_commands"}),n=t?.commands??[];return e2(n),n}catch(e){return console.error("Failed to load slash commands:",e),e2([]),[]}finally{e8(!1)}},[t3]),t7=(0,i.useCallback)(()=>{to.current+=1,td.current=!1,tl.current&&(clearTimeout(tl.current),tl.current=null)},[]),t9=(0,i.useCallback)(()=>{ta.current?.close()},[]),ne=(0,i.useCallback)(e=>ta.current.ensureConnected(e),[]),nt=(0,i.useCallback)(e=>{ta.current.maintain(e)},[]),nn=(0,i.useCallback)(e=>{ta.current?.reconnect(e).catch(t8)},[t8]);(0,i.useEffect)(()=>{if(t?.id&&r)return nt(t.id),()=>{tu.current!==t.id||tg.current||td.current||tm.current||th.current===t.id&&tp.current||ta.current?.close()}},[nt,t?.id,r]),(0,i.useEffect)(()=>{if(!x){tg.current||tp.current||td.current||t9();return}let e=t?.id??tu.current??null;e&&(t7(),ta.current?.ensureConnected(e).catch(t8))},[t7,t9,t8,x,t?.id]);let nr=(0,i.useCallback)(async(e,t)=>{let n=tu.current;if(te(t=>t?.id===e.id?null:t),n)try{await im(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),ni=(0,i.useCallback)(async(e,t)=>{let n=tu.current;if(n)try{await im(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),ns=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e6({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),na=(0,i.useCallback)(t=>{switch(ii(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":te(t);break;case"notify":ns({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tn(e=>t.closed?e?.id===t.id?null:e:t)}},[ns,o,e.chatInputRef]),nl=(0,i.useCallback)(()=>{null!==tE.current&&(cancelAnimationFrame(tE.current),tE.current=null);let e=tM.current;0!==e.length&&(tM.current=[],_({type:"deltas",events:e}))},[]),no=(0,i.useCallback)(e=>{tM.current.push(e),null===tE.current&&(tE.current=requestAnimationFrame(()=>{tE.current=null,nl()}))},[nl]),nd=(0,i.useCallback)(()=>{nl();let e=tg.current;return tg.current=!1,V(!1),e0(null),eM(null),P(new Map),_({type:"end"}),e},[nl]),nc=(0,i.useCallback)(e=>tv.current!==e&&(tv.current=e,l?.(),!0),[l]),nh=(0,i.useCallback)(e=>{if(tm.current&&tu.current===e)return void t7();t7(),td.current=!0;let t=to.current,n=async()=>{if(t===to.current&&tu.current===e&&td.current)try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==to.current||tu.current!==e||!td.current)return;let s=i.state;if(i.running&&s&&(s.isStreaming||s.isPromptRunning)){td.current=!1,tl.current=null,tf.current=!!s?.isStreaming,tx.current=!!s?.isPromptRunning,tg.current=!0,V(!0),e0(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&s?.isCompacting){eK(!0),tl.current=setTimeout(()=>void n(),600);return}td.current=!1,tl.current=null,t9()}catch{if(t!==to.current||tu.current!==e||!td.current)return;tl.current=setTimeout(()=>void n(),600)}};tl.current=setTimeout(()=>void n(),3e4)},[t7,t9]),np=(0,i.useCallback)(async(e=tu.current,t=tP.current)=>{if(tP.current===t)try{e&&await t0(e)}finally{if(tP.current!==t)return;let n=tx.current,r=tf.current;tx.current=!1,tf.current=!1,tF.current=null;let i=nd();n?nc(t):r&&i&&l?.(),e&&nh(e)}},[t0,nc,l,nh,nd]),nm=(0,i.useCallback)(async(e,t)=>{await iB(800);let n=Date.now();for(;tg.current&&Date.now()-n<2e4;){if(void 0!==t&&tP.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await np(e,t)}}catch{}await iB(600)}},[np]),ng=(0,i.useCallback)(async e=>{let t=tw.current+1;for(tw.current=t;ty.current&&tw.current===t&&tu.current===e;){await iB(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await t0(e),tw.current!==t||tu.current!==e)return;ty.current=!1,Y(!1),X(null);return}catch{}}},[t0]),nf=(0,i.useCallback)(async e=>{if(!tg.current||tu.current!==e)return;let t=tP.current;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let r=await n.json();if(tu.current!==e||tP.current!==t)return;let i=r.state;if(eK(i?.isCompacting??!1),ts(iD(i?.queuedMessages)),"boolean"==typeof i?.autoCompactionEnabled&&eJ(i.autoCompactionEnabled),i?.contextUsage!==void 0&&eL(e=>iA(e,i.contextUsage??null)),r.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting)){tf.current=!!i.isStreaming,tx.current=!!i.isPromptRunning;return}if(!tg.current)return;i&&void 0!==i.systemPrompt&&e$(i.systemPrompt??null),await np(e,t)}catch{}},[np]);(0,i.useEffect)(()=>{if(!K)return;let e=()=>{let e=tu.current;e&&nf(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[K,nf]),(0,i.useEffect)(()=>{let e=()=>{let e=tu.current;if(e&&"hidden"!==document.visibilityState){if(tm.current)return void nn(e);(tg.current||td.current||th.current===e&&tp.current)&&nt(e)}},t=()=>{"visible"===document.visibilityState&&e()};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener("pageshow",e)}},[nt,nn]),(0,i.useEffect)(()=>{tg.current=K},[K]),tj.current=(0,i.useCallback)(e=>{switch("message_update"!==e.type&&nl(),e.type){case"connected":{let t=tu.current;t&&t0(t),_({type:!0===e.isStreaming?"resume":"end"}),!0===e.isStreaming&&(t7(),tf.current=!0,tg.current=!0,V(!0),e0({kind:"waiting_model"}));break}case"agent_start":t7(),tf.current=!0,tg.current=!0,V(!0),e0({kind:"waiting_model"}),_({type:"start"});break;case"agent_end":if(!tg.current)break;e0(null),eM(null),_({type:"end"}),tu.current&&(t0(tu.current),fetch(`/api/agent/${encodeURIComponent(tu.current)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eL(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&e$(e.state.systemPrompt??null),ts(iD(e.state?.queuedMessages))}).catch(()=>{}));break;case"agent_settled":{let e=tf.current;if(tf.current=!1,!e||tx.current)break;let t=tu.current,n=nd();eK(!1),t&&(t0(t),nh(t)),n&&l?.();break}case"prompt_done":{let e=tP.current,t=tx.current;tx.current=!1,tF.current=null;let n=nc(e);if(!t&&!n)break;let r=tu.current;r&&t0(r),!tf.current&&(nd(),r&&nh(r))}break;case"prompt_error":ns({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":ns({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tg.current||iN(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(_({type:"snapshot",message:t}),t.content.length>0&&e0(null)):t&&e0(null)}else{let t=e.assistantMessageEvent;t&&(no(t),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&e0(null))}break;case"message_end":{if(!tg.current||iN(e))break;let t=e.message;if(t&&(tB.current+=1),t&&"user"===t.role){let e=il(t),n=ik(e),r=tF.current;tF.current=null,R(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&ik(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let e=il(t);if("assistant"===e.role){let t=function(e){if("assistant"!==e.role||"aborted"===e.stopReason||"error"===e.stopReason)return null;let t=e.usage;if(!t)return null;let n=t.totalTokens,r=n&&n>0?n:t.input+t.output+t.cacheRead+t.cacheWrite;return r>0?r:null}(e);null!==t&&eL(e=>{let n=e?.contextWindow??0;return n<=0?e:iA(e,{tokens:t,contextWindow:n,percent:t/n*100})});let n=Date.now(),r=function(e,t,n){if(!t)return e;let r=!1,i=e.content.map((e,i)=>{if("thinking"!==e.type)return e;let s=t.content[i],a=(s?.type==="thinking"?s.startedAt:void 0)??e.startedAt??t.timestamp,l=(s?.type==="thinking"?s.endedAt:void 0)??e.endedAt??n;return e.startedAt===a&&e.endedAt===l?e:(r=!0,{...e,..."number"==typeof a?{startedAt:a}:{},..."number"==typeof l?{endedAt:l}:{}})});return r?{...e,content:i}:e}({...e,completedAt:n},q.current.streamingMessage,n);R(e=>[...e,r])}else"system"!==e.role&&R(t=>[...t,e])}_({type:"end"}),e0({kind:"waiting_model"});break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName;e0(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n)&&Array.isArray(i)&&P(e=>{let s=new Map(e);return s.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),s}),e0(e=>{let r=e?.kind==="running_tools"?e.tools:[],i=r.find(e=>e.id===t),s=n||i?.name||"tool";return i?.name===s?e:{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),{id:t,name:s}]}});break}case"tool_execution_end":{let t=e.toolCallId;P(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),e0(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":ts({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eM({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eM(null);break;case"auto_compaction_start":case"compaction_start":eK(!0),eZ(null),eG(null);break;case"auto_compaction_end":case"compaction_end":eK(!1),e.errorMessage?(eZ(e.errorMessage),eG(null)):!e.aborted&&(eG(iU(e.result,e.reason??"auto")),tu.current&&t0(tu.current));break;case"extension_ui_request":na(e);break;case"extension_ui_closed":te(t=>t?.id===e.id?null:t)}},[ns,t7,nl,na,t0,nc,l,no,nh,nd]);let nx=(0,i.useCallback)(async(e,n)=>{let r=e.trim();if(!r&&!n?.length)return;if(tg.current||ty.current)return void tG(e,n,tZ);let i=!n?.length&&r.startsWith("/");if(!n?.length&&r.startsWith("!")){let t=r.startsWith("!!"),i=(t?r.slice(2):r.slice(1)).trim();return i?void await tI.current?.(i,t):void tG(e,n,tZ)}let a=tP.current+1;t7(),tx.current=!0;let l=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),o={role:"user",content:l?.length?[...e.trim()?[{type:"text",text:e}]:[],...l]:e,timestamp:Date.now()};R(e=>[...e,o]),tB.current+=1,tF.current=ik(o),tP.current=a,tg.current=!0,V(!0),e0(i?{kind:"running_command"}:{kind:"waiting_model"}),_({type:"start"}),tS.current=!0,tD.current={runId:a,message:e,images:n,userMsg:o};let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=!1;tz.current.begin(a);let u=async e=>{try{await im(e,{type:"abort"})}catch(e){ns({type:"error",message:e instanceof Error?e.message:String(e)})}},h=await iR({gate:tz.current,runId:a,currentRunId:()=>tP.current,currentSessionId:()=>tu.current,promptPending:()=>tx.current,abandonUnsent:()=>{tD.current?.runId===a&&(tD.current=null,tx.current=!1,R(e=>{let t=e.lastIndexOf(o);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tG(e,n,tZ),tF.current=null,tP.current===a&&(tg.current=!1,V(!1),e0(null),_({type:"end"})))},onDispatched:()=>{tD.current?.runId===a&&(tD.current=null)},abort:u,prepare:async()=>{if(v&&s){let e=tu.current??await tT.current;if(tz.current.isCancelled(a))return null;let t=e??await t3();if(tz.current.isCancelled(a))return null;if(!t)throw Error("Unable to create a session for the prompt");if(ey&&(eH(ey),e)){let e=await im(t,{type:"set_model",provider:ey.provider,modelId:ey.modelId});if(e?.thinkingLevel&&eN(e.thinkingLevel),tz.current.isCancelled(a))return null}return(await ne(t),tz.current.isCancelled(a))?null:t}if(t)return(await ne(t.id),tz.current.isCancelled(a))?null:t.id;throw Error("No active session for the prompt")},send:async t=>{let n=await im(t,{type:"prompt",message:e,...d?.length?{images:d}:{}});c=n?.subagentAction==="steered"||n?.subagentAction==="resumed"}});if("abandoned"!==h.status&&"aborted"!==h.status&&"stale"!==h.status){if("cancelled_after_dispatch"===h.status)return void nm(h.sessionId,a);if("failed"===h.status){let t=h.error,r=h.sessionId,i=h.requestStarted;return(console.error("Failed to send message:",t),!(!i||ip(t))&&r)?void nm(r,a):(tx.current=!1,tD.current?.runId===a&&(tD.current=null),R(e=>{let t=e.lastIndexOf(o);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),ns({type:"error",message:t instanceof Error?t.message:String(t)}),tG(e,n,tZ),tF.current=null,r)?void nf(r):(tg.current=!1,t9(),V(!1),e0(null),void _({type:"end"}))}if(v&&s&&t4(1,e),c&&h.sessionId){tx.current=!1,nm(h.sessionId,a);return}i&&h.sessionId&&nm(h.sessionId,a)}},[v,s,ey,t,t3,ne,t4,nm,ns,t7,t9,tZ,nf,tG]),nv=(0,i.useCallback)(async(e,n)=>{if(tg.current||ty.current||ee.current)throw Error("Cannot generate an image while the session is busy");let r=crypto.randomUUID();ee.current=!0,et.current=r,en.current=!1,Q(!0);try{let i=t?.id??(v&&s?await t3():null);if(!i)throw Error("No active session for image generation");if(en.current)throw new DOMException("Image generation cancelled","AbortError");let a=await im(i,{type:"generate_image_direct",requestId:r,arguments:e,...n?{sourceImage:n}:{}});return await t0(i),v&&s&&t4(1,e.prompt),a}finally{et.current===r&&(ee.current=!1,et.current=null,en.current=!1,Q(!1))}},[t3,v,t0,s,t4,t?.id]),ny=(0,i.useCallback)(async()=>{en.current=!0;let e=tu.current,t=et.current;e&&t&&await im(e,{type:"abort_image_generation",requestId:t})},[]);tI.current=(0,i.useCallback)(async(e,n)=>{if(tg.current||ty.current)return;let r=`${n?"!!":"!"}${e}`;tA.current=!1,ty.current=!0,X({command:e,excludeFromContext:n}),Y(!0);try{let i=await iW({abortRequested:()=>tA.current,prepare:async()=>tu.current??t?.id??await t3(),send:async t=>{await im(t,{type:"bash",command:e,excludeFromContext:n})},loadResults:async e=>{tu.current===e&&await t0(e)},restoreUnsent:()=>tG(r,void 0,tZ)});("completed"===i.status||"cancelled_after_dispatch"===i.status)&&t4(1,r)}catch(e){console.error("Failed to execute shell command:",e),ns({type:"error",message:e instanceof Error?e.message:String(e)}),tG(r,void 0,tZ)}finally{ty.current=!1,X(null),Y(!1)}},[ns,tZ,t3,t0,t4,tG,t]);let nb=(0,i.useCallback)(async()=>{var e;let n=tP.current,r=tu.current,i=async e=>{if(r&&!tb.current){tb.current=!0;try{await im(r,{type:e})}catch(e){console.error("Failed to abort:",e),ns({type:"error",message:e instanceof Error?e.message:String(e)})}finally{tb.current=!1}}};if(ty.current){tA.current=!0,await i("abort_bash");return}let s=tD.current;(tz.current.isInFlight(n)||s?.runId===n)&&tz.current.cancel(n);let a=!!(s&&s.runId===n&&tz.current.shouldAbandonUnsent(n));if(a&&s){tD.current=null,tx.current=!1,R(e=>{let t=e.lastIndexOf(s.userMsg);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tG(s.message,s.images,tZ),tF.current=null,tg.current=!1,V(!1),e0(null),_({type:"end"});return}let l=(e={bashRunning:!1,hasSessionId:!!r,localUnsent:a,agentRunning:tg.current||tx.current}).bashRunning?e.hasSessionId?"abort_bash":"none":!e.agentRunning||e.localUnsent?"none":e.hasSessionId?"abort":"none";t?.relation?.kind==="subagent"&&"queued"===t.relation.status&&r?await i("abort"):"none"!==l&&r&&await i("abort_bash"===l?"abort_bash":"abort")},[ns,tZ,tG,t]),nw=(0,i.useCallback)(async e=>{if(ty.current)return;let t=tu.current;if(t){eW(e);try{let{cancelled:n,newSessionId:r}=await im(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e)}finally{eW(null)}}},[c]),nj=(0,i.useCallback)(async e=>{if(ty.current)return;let t=tu.current;t&&(im(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),T(e),await t1(t,e))},[t1]),nk=(0,i.useCallback)(async e=>{if(ty.current)return;T(e);let t=tu.current;t&&(await t1(t,e),e&&im(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[t1]),nS=(0,i.useCallback)(async(e,t)=>{if(v){let n={provider:e,modelId:t};tR.current=n,eb(n),eH(n);let r=tu.current??await tT.current;if(!r){let r=tW.current;eN(r?ix(eu[`${e}:${t}`],r):iq({models:{},thinkingLevels:eu,thinkingLevelPins:eg,defaultThinkingLevel:ex},n));return}try{let n=await im(r,{type:"set_model",provider:e,modelId:t});n?.thinkingLevel&&eN(n.thinkingLevel)}catch(e){console.error("Failed to set model:",e)}return}let n=tu.current;if(n&&!tO.current){tO.current=!0,eA({provider:e,modelId:t}),e_(!0);try{await im(n,{type:"set_model",provider:e,modelId:t}),tO.current=!1,await t0(n)}catch(e){console.error("Failed to set model:",e),tO.current=!1,eA(eD),ns({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await t0(n)}finally{tO.current=!1,e_(!1)}}},[ns,eD,v,t0,ex,eg,eu,eb]),nC=(0,i.useCallback)(async()=>{let e=tu.current;if(e&&!eq){eK(!0),eZ(null),eG(null);try{let t=await im(e,{type:"compact"});eG(iU(t,"manual")),await t0(e,!0)}catch(e){eZ(e instanceof Error?e.message:String(e)),eG(null)}finally{eK(!1)}}},[eq,t0]),nN=(0,i.useCallback)(async(e,t=!1,n)=>{let r;try{r=await function(e,t,n={}){let r=io.get(e);if(!n.force&&r&&r.loadedAt+6e4>Date.now())return Promise.resolve(r.data);let i=id.get(e);if(i&&(!n.force||i.forced&&i.refreshToken===n.refreshToken))return i.promise;let s=(i?i.promise.catch(()=>void 0):Promise.resolve()).then(t).then(t=>{if(t.modelError&&(t.modelList?.length??0)===0)throw Error(t.modelError);for(io.delete(e),io.set(e,{data:t,loadedAt:Date.now()}),"u">typeof localStorage&&function(e,t){try{localStorage.setItem(ic+e,JSON.stringify(t))}catch{}}(e,t);io.size>32;){let e=io.keys().next().value;if(void 0===e)break;io.delete(e)}return t}).finally(()=>{id.get(e)?.promise===s&&id.delete(e)});return id.set(e,{promise:s,forced:!0===n.force,...void 0!==n.refreshToken?{refreshToken:n.refreshToken}:{}}),s}(b,async()=>{let e=await fetch(b);if(!e.ok){let t="";try{let n=await e.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(t=n.error)}catch{}throw Error(t||`Failed to load models (HTTP ${e.status})`)}return e.json()},{force:t,refreshToken:n}),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||eo(t instanceof Error?t.message:String(t)),t}if(ei(r.models),eo(r.modelError??null),ec(r.modelScopeWarnings??[]),eh(r.thinkingLevels??{}),em(r.thinkingLevelMaps??{}),ef(r.thinkingLevelPins??{}),ev(r.defaultThinkingLevel),ea(r.modelList??[]),v&&!tu.current){let e=i_(r);ej(e),null===tW.current&&eN(iq(r,tR.current??e))}},[v,b]),nE=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),s=tu.current??await t3(),a=e=>(e.handled&&(e.error?ns({type:"error",message:e.error}):"openSessionStats"!==e.action&&ns({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!s||eq)return a({handled:!0,error:"No active session to compact"});eK(!0),eZ(null),eG(null);let e=await im(s,{type:"compact",...i?{customInstructions:i}:{}});return eG(iU(e,"manual")),await t0(s,!0)&&t4(),a({handled:!0,message:"Compacted context"})}case"reload":if(!s)return a({handled:!0,error:"No active session to reload"});return await im(s,{type:"reload"}),await Promise.all([t0(s,!1,!0),t2(s),t5(),nN(void 0,!0)]),a({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return a({handled:!0,error:"No active session to name"});if(!i)return a({handled:!0,error:"Usage: /name <name>"});return await im(s,{type:"set_session_name",name:i}),await t0(s)&&t4(),a({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!s)return a({handled:!0,error:"No active session"});let e=await im(s,{type:"get_session_stats"});return e&&e7(e),f?.(),a({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return a({handled:!0,error:"No active session"});let e=await im(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return a({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),a({handled:!0,message:"Copied last assistant message"})}case"auto-compact":{if(!s)return a({handled:!0,error:"No active session"});let e=await im(s,{type:"get_state"}),t=!("boolean"!=typeof e?.autoCompactionEnabled||e.autoCompactionEnabled);return await im(s,{type:"set_auto_compaction",enabled:t}),eJ(t),a({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"clone":{if(!s)return a({handled:!0,error:"No active session to clone"});if(tg.current||ty.current)return a({handled:!0,error:"Cannot clone while the session is running"});let e=await im(s,{type:"clone",leafId:L});if(e?.cancelled||!e?.newSessionId)return a({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=a({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}case"bug":{if(!s)return a({handled:!0,error:"No active session to report"});if(tg.current||ty.current)return a({handled:!0,error:"Cannot report a bug while the session is running"});let e=await im(s,{type:"bug_report",...i?{hint:i}:{}});if(!e)return a({handled:!0,error:"Bug report failed"});return a({handled:!0,message:"upload"===e.delivery?`Bug report uploaded. Report ID: ${e.id}`:`Upload failed (${e.error??"unknown error"}); exported to ${e.path}`})}default:return{handled:!1}}}catch(e){return a({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eK(!1)}},[L,ns,t3,eq,nN,t0,t5,t2,t4,c,f]),nM=(0,i.useCallback)(async(e,t,n)=>{let r=tu.current;if(!r){tG(e,n,tZ),ns({type:"error",message:"No active session for the queued message"});return}let i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await im(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),ip(t)&&tG(e,n,tZ),ns({type:"error",message:t instanceof Error?t.message:String(t)})}},[ns,tZ,tG]),nI=(0,i.useCallback)(async(e,t)=>{await nM(e,"steer",t)},[nM]),nL=(0,i.useCallback)(async(e,t,n)=>{await nM(e,t,n)},[nM]),nT=(0,i.useCallback)(async(e,t)=>{await nM(e,"followUp",t)},[nM]),n$=(0,i.useCallback)(async()=>{let e=tu.current;if(e)try{await im(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nR=(0,i.useCallback)(async()=>{let e=tu.current;if(e)try{let t=await im(e,{type:"clear_queue"});ts({steering:[],followUp:[]});let n=[...iP(t?.steering),...iP(t?.followUp)];if(0===n.length)return;tG(n.map(e=>e.text).filter(Boolean).join("\n\n"),n.flatMap(e=>e.images).map(e=>({...e,previewUrl:""})),tZ)}catch(e){console.error("Failed to recall queued messages:",e),ns({type:"error",message:e instanceof Error?e.message:"Failed to recall queued messages"})}},[ns,tZ,tG]),nW=(0,i.useCallback)(async e=>{eN(e),v&&!tu.current&&(tW.current=e);let t=tu.current??await tT.current;if(t)try{await im(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[v]),nP=(0,i.useCallback)(async e=>{let t=(0,tr.xG)(e);!function(e,t=iy()){if(t)try{t.setItem(iv,e)}catch{}}(e),tq(e);let n=tu.current??await tT.current;if(!n){tc.current=void 0!==t;return}try{let e=await im(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tc.current=void 0!==t;let r=e?.sessionId??n,i=e?.recreated===!0;r!==n&&(t7(),t9(),tu.current=r),e2([]),tm.current&&(i||r!==n)&&nn(r);let[s]=await Promise.all([im(r,{type:"get_state"}),t2(r)]);t_.current&&tu.current===r&&e$(s.systemPrompt??"")}catch(e){console.error("Failed to set tools:",e)}},[t7,t9,t2,nn,tq]),nz=(0,i.useCallback)((e,t=16)=>{let n=tL.current;n&&(tk.current=!0,tS.current=!1,tC.current=!1,n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tN.current=n.scrollTop)},[]),nD=(0,i.useCallback)(()=>{let e=tL.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tg.current,s=tC.current,a=function(e,t,n,r,i,s=96){return!!nu(n,r,i)||!(n<t)&&(!!(!e&&n>t&&nu(n,r,i,s))||e)}(s,tN.current,t,n,r,i?96:8);tC.current=a,tN.current=t,!s&&a&&i&&tV("instant")}},[tV]);(0,i.useEffect)(()=>(t_.current=!0,t&&(tu.current=t.id,t0(t.id,!0,!0).then(e=>{e?.running&&(t2(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tf.current=!!e.state.isStreaming,tx.current=!!e.state.isPromptRunning,tg.current=!0,V(!0),e0(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),_({type:"resume"}),nt(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nm(t.id)),e.state?.isBashRunning&&(ty.current=!0,Y(!0),ng(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eK(e.state.isCompacting),"boolean"==typeof e.state.autoCompactionEnabled&&eJ(e.state.autoCompactionEnabled),void 0!==e.state.contextUsage&&eL(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&e$(e.state.systemPrompt??null),e.state.thinkingLevel&&eN(e.state.thinkingLevel),void 0!==e.state.queuedMessages&&ts(iD(e.state.queuedMessages)))})),()=>{t_.current=!1,null!==tE.current&&cancelAnimationFrame(tE.current),tE.current=null,tM.current=[],tw.current+=1,t7(),t9()}),[]),(0,i.useEffect)(()=>{p?.(eT)},[eT,p]),(0,i.useEffect)(()=>(g?.(t6),()=>g?.(null)),[t6,g]),(0,i.useEffect)(()=>{h&&h(S?.tree??[],L,nk)},[S?.tree,L,nk,h]),(0,i.useEffect)(()=>{let e=tL.current;if(e)return tN.current=e.scrollTop,e.addEventListener("scroll",nD,{passive:!0}),()=>{e.removeEventListener("scroll",nD)}},[$.length,N,nD]),(0,i.useLayoutEffect)(()=>{$.length>0&&(tS.current?(tS.current=!1,tk.current=!0,tV("instant")):tk.current?tC.current&&tV("instant"):(tk.current=!0,tV("instant")))},[$.length,K,tV,U.streamingMessage]),(0,i.useEffect)(()=>{let e=new AbortController,t=tH.current!==u;return tH.current=u,(async()=>{for(let n=0;;n++)try{await nN(e.signal,t,u);return}catch(t){if(e.signal.aborted||t instanceof DOMException&&"AbortError"===t.name||n>=iF.length||(await iB(iF[n]),e.signal.aborted))return}})(),()=>e.abort()},[nN,u]),(0,i.useEffect)(()=>{if(!eX)return;let e=setTimeout(()=>eG(null),6e3);return()=>clearTimeout(e)},[eX]);let[nA,nF]=(0,i.useState)(null),nB=(0,i.useRef)(5e3),nO=(0,i.useRef)(null),nH=(0,i.useRef)(null);return(0,i.useEffect)(()=>{if(0===e3.visible.length){nH.current=null;return}let e=e3.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e6({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=e3.visible[0];if(!t||(nH.current!==t.id&&(nH.current=t.id,nB.current=5e3),e3.visible.some(e=>e.id===nA)))return;nO.current=Date.now();let n=setTimeout(()=>{e6({type:"mark_oldest_exiting"})},nB.current);return()=>{clearTimeout(n),null!==nO.current&&(nB.current=Math.max(0,nB.current-(Date.now()-nO.current)),nO.current=null)}},[e3.visible,nA]),(0,i.useEffect)(()=>{e7(null)},[$.length,eI?.tokens,eI?.percent,eI?.contextWindow]),{data:S,loading:N,error:M,activeLeafId:L,messages:$,activeToolResults:W,entryIds:z,historyCursor:A,hasEarlierMessages:B,streamState:U,agentRunning:K,directImageRunning:G,modelNames:er,modelList:es,modelError:el,modelScopeWarnings:ed,modelThinkingLevels:eu,modelThinkingLevelMaps:ep,newSessionModel:ey,toolPreset:ek,thinkingLevel:eC,retryInfo:eE,contextUsage:eI,systemPrompt:eT,forkingEntryId:eR,isCompacting:eq,autoCompactionEnabled:eV,compactError:eY,compactResult:eX,currentModel:tJ,displayModel:tY,modelSwitching:eU,sessionStats:tQ,slashCommands:e1,slashCommandsLoading:e4,queuedMessages:ti,notices:e3.visible,extensionDialog:e9,extensionCustomUi:tt,respondToExtensionUi:nr,sendExtensionCustomInput:ni,isAutoModelSelection:v&&null===ey,agentPhase:eQ,isNew:v,sessionIdRef:tu,scrollContainerRef:tL,initialScrollDoneRef:tk,isNearBottomRef:tC,handleSend:nx,handleDirectImageGeneration:nv,abortDirectImageGeneration:ny,handleAbort:nb,handleFork:nw,handleNavigate:nj,handleModelChange:nS,handleCompact:nC,handleSteer:nI,handleFollowUp:nT,handlePromptWithStreamingBehavior:nL,handleAbortCompaction:n$,handleRecallQueue:nR,handleBuiltinSlashCommand:nE,addNotice:ns,setNoticePaused:nF,handleToolPresetChange:nP,handleThinkingLevelChange:nW,loadTools:t2,loadSlashCommands:t5,setActiveLeafId:T,setData:C,setMessages:R,loadContext:t1,scrollToBottom:tV,scrollToMessage:nz,dispatch:_,setAgentRunning:V,setForkingEntryId:eW,bashRunning:J,pendingBash:Z,handleAgentEventRef:tj}}({session:e,sessionRunning:o,newSessionCwd:d,newSessionDraftKey:c,onAgentEnd:es,onAttentionNeeded:ea,onSessionCreated:j,onSessionForked:el,modelsRefreshKey:C,chatInputRef:en,onBranchDataChange:T,onSystemPromptChange:$,onSystemToolsChange:R,onSystemInfoLoaderChange:W,onSessionStatsPanelOpen:D,deferInitialScroll:!!eh,isVisiblePane:L}),tI=eI||eL||eT,tL=(0,i.useCallback)(()=>eL?tc():tu(),[tc,eL,tu]),tT=(0,i.useRef)(null),t$=e0?e0.tokens.input+e0.tokens.cacheRead+e0.tokens.cacheWrite:0,tR=e0&&t$>0?e0.tokens.cacheRead/t$*100:null,[tW,tP]=(0,i.useState)(null),tD=ti&&0===ew.length&&!eM.isStreaming&&!tI&&null===tW,[tA,tB]=(0,i.useState)(!1),[tO,tH]=(0,i.useState)(null),[tU,t_]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(null),[tV,tJ]=(0,i.useState)(void 0),[tG,t1]=(0,i.useState)(0),[t2,t4]=(0,i.useState)(null),[t3,t5]=(0,i.useState)(!1),[t7,t9]=(0,i.useState)(!1),[nt,nn]=(0,i.useState)(null),nr=(0,i.useRef)(null),ns=(0,i.useRef)(null),na=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/image-generation",{signal:e.signal}).then(async e=>{let t=await e.json();e.ok&&t.available&&t.config?.connections.length?tH(t.config):(tH(null),t_(!1),tK(null))}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load image generation config:",e)}),()=>e.abort()},[tG,C]);let nx=(0,i.useCallback)(async(t,n)=>{ed();let r=null;for(let e=ew.length-1;e>=0;e--){let t=eb(ew[e].details);if(t){r=t;break}}let i=e?.cwd??d,s=t.target,a=s&&(s.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(s)?s:i?E(i,s):s);tP({prompt:t.prompt,size:t.size,width:n?void 0:r?.width,height:n?void 0:r?.height,previewUrl:n?`data:${n.mimeType};base64,${n.data}`:a?`/api/files/${k(a)}?type=read`:void 0});try{await td(t,n),n&&en.current?.removeAttachedImage(n.data)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;e9({type:"error",message:e instanceof Error?e.message:String(e)})}finally{tP(null)}},[e9,td,ed,ew,d,e?.cwd]),nv=(0,i.useCallback)(async e=>{let t=await tw(e);return!("error"in t)&&/^\/reload(?:\s|$)/.test(e.trim())&&t1(e=>e+1),t},[tw]),ny=(0,i.useCallback)(()=>{t4(null),t5(!1),nn(null)},[]);(0,i.useEffect)(()=>{H||ny()},[H,ny]);let nb=(0,i.useCallback)(e=>{let t=na.current;if(t&&!(null!=e&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>4)||!H||t3)return;let n=window.getSelection(),r=n?.rangeCount?n.getRangeAt(0):null,i=n$.current;if(!n||n.isCollapsed||!r||!i||!i.contains(r.commonAncestorContainer))return void t4(null);let s=n.toString().trim();if(!s)return void t4(null);let a=r.getBoundingClientRect(),l=[r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?r.commonAncestorContainer:r.commonAncestorContainer.parentElement,r.startContainer.nodeType===Node.ELEMENT_NODE?r.startContainer:r.startContainer.parentElement,r.endContainer.nodeType===Node.ELEMENT_NODE?r.endContainer:r.endContainer.parentElement].map(e=>e?.closest('[data-message-role="assistant"]')?.dataset.entryId).find(e=>!!e);t4({text:s,top:Math.min(window.innerHeight-44,a.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,a.left+a.width/2)),sourceEntryId:l})},[H,t3]);(0,i.useEffect)(()=>{t3&&t2&&ns.current?.insertIfEmpty(nd(t2.text,Z("chat.quoteIntro"),Z("chat.quoteQuestion")))},[t3,t2,Z]),(0,i.useLayoutEffect)(()=>{let e=nr.current;if(!e||!t2)return;let t=window.visualViewport,n=()=>{let n=e.getBoundingClientRect(),r=t?.offsetTop??0,i=t?.offsetLeft??0;e.style.top=`${Math.max(r+8,Math.min(t2.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(t2.left-n.width/2,i+(t?.width??window.innerWidth)-n.width-8))}px`};n();let r=new ResizeObserver(n);return r.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[t2,t3,nt]),(0,i.useEffect)(()=>{if(!t2)return;let e=e=>{if(t3||nr.current?.contains(e.target))return;na.current={x:e.clientX,y:e.clientY};let t=()=>{document.removeEventListener("pointerup",t),document.removeEventListener("pointercancel",t),queueMicrotask(()=>{na.current=null})};document.addEventListener("pointerup",t),document.addEventListener("pointercancel",t),ny()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),t7||ny())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[t2,t3,t7,ny]);let nw=(0,i.useCallback)(()=>{t2&&(en.current?.insertText(nd(t2.text,Z("chat.quoteIntro"),Z("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),ny())},[t2,ny,Z]),nj=(0,i.useCallback)(async t=>{let n=ts.current??e?.id;if(!t7&&t.trim()&&t2?.sourceEntryId&&n&&O){t9(!0),nn(null),V?.();try{await O(t,n,t2.sourceEntryId),ny()}catch(e){ns.current?.restoreSubmission(t),nn(e instanceof Error?e.message:String(e))}finally{t9(!1)}}},[O,t2,t7,e?.id,ts,ny,V]),nk=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(ev||ey||!U||nk.current)return;let t=ts.current??e?.id;t&&(nk.current=!0,_?.(t),ed(),to(U))},[U,ev,ey,to,_,ed,e?.id,ts]),(0,i.useEffect)(()=>{G&&e3&&ei.current!==e3.id&&(ei.current=e3.id,Q.current())},[G,e3]);let[nS,nC]=(0,i.useState)(0),[nN,nE]=(0,i.useState)(50),nM=(0,i.useRef)(null),nI=(0,i.useRef)(null),nL=(0,i.useRef)({startIndex:0,endIndex:0,totalCount:0}),nT=(0,i.useRef)(null),n$=(0,i.useRef)(null),nR=(0,i.useRef)(null),nW=(0,i.useRef)(!1),nP=(0,i.useRef)(null),[nz,nD]=(0,i.useState)(null),nA=(0,i.useRef)(!1),nF=(0,i.useRef)(tN),nB=(0,i.useRef)(eh);nB.current=eh;let[nO,nH]=(0,i.useState)(null),nU=ew[ek.indexOf(nO?.entryId??"")],n_=nU?.role==="assistant"?nO?.blockIndex===void 0?nU.content.find(e=>"text"===e.type):nU.content[nO.blockIndex]:void 0,nq=(0,i.useRef)({entryIds:ek,historyCursor:eS,hasEarlierMessages:eC});nq.current={entryIds:ek,historyCursor:eS,hasEarlierMessages:eC},(0,i.useLayoutEffect)(()=>{let t=e?.id,n=ta.current,r=n$.current;if(t&&l&&n&&r)return()=>{if(nB.current)return;if(nu(n.scrollTop,n.clientHeight,n.scrollHeight))return void l(t,{atBottom:!0});let e=n.getBoundingClientRect().top,i=st(Array.from(r.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),e);i&&l(t,{atBottom:!1,...i,oldestEntryId:nq.current.historyCursor})}},[ev,l,ta,e?.id]),(0,i.useEffect)(()=>{t&&em(null)},[t]);let nK=(0,i.useCallback)(async(e,t,n)=>{do await new Promise(e=>requestAnimationFrame(()=>e())),n.throwIfAborted();while(nW.current);nW.current=!0;try{let r=nq.current;await ng(e,{entryIds:r.entryIds,oldestEntryId:r.historyCursor,hasMore:r.hasEarlierMessages},e=>tC(t,tN,e,{signal:n}),n)}finally{nW.current=!1}},[tN,tC]),nV=(0,i.useRef)(nK);nV.current=nK;let nJ=(0,i.useCallback)(()=>{let e=nL.current;nC(e.totalCount-e.endIndex),nE(50)},[]);(0,i.useEffect)(()=>{let n=e?.id;if(!eh||!n||ev||t||nA.current)return;nA.current=!0,nP.current?.abort();let r=new AbortController;nP.current=r,nD(null),nH(null);let i=()=>{ef(!1),em(null)};return(async()=>{try{if(await nV.current(eh.anchorEntryId,n,r.signal),r.signal.aborted)return void i();ef(!0)}catch(e){if(nf(e,r.signal))return void i();tE("instant"),em(null)}})(),()=>{r.abort(),nP.current===r&&(nP.current=null),em(null),ef(!1)}},[ev,eh,tE,t,e?.id]),(0,i.useLayoutEffect)(()=>{let e=n$.current;if(!eh||!e||t)return;let n=e.querySelector(`[data-entry-id="${CSS.escape(eh.anchorEntryId)}"]`);if(n){nJ(),tM(n,eh.anchorOffset),em(null);return}eg&&(tE("instant"),em(null))},[ek,nJ,eh,eg,tE,tM,t,nN,nS]),(0,i.useEffect)(()=>{if(!t||ev)return;nP.current?.abort();let e=new AbortController;nP.current=e,nD(null),nH(null);let n=t.sessionId;return(async()=>{try{if(await nV.current(t.entryId,n,e.signal),e.signal.aborted)return;nR.current=null,nH(t)}catch(n){if(nf(n,e.signal))return;e9({type:"warning",message:"other_branch"===(n instanceof nh&&"exhausted"===n.reason?function(e,t,n){if(!t||!n)return"not_found";let r=nm(t,n);return!r||r.some(t=>np(t,e))?"not_found":nm(t,e)?"other_branch":"not_found"}(t.entryId,ex?.tree,tN):"not_found")?Z("chat.locateOtherBranch"):n instanceof nh&&"stalled"===n.reason?Z("chat.locateHistoryStalled"):n instanceof nh&&"load_failed"===n.reason?Z("chat.locateLoadFailed"):Z("chat.locateNotFound")}),s?.(t)}})(),()=>{e.abort(),nP.current===e&&(nP.current=null)}},[tN,e9,ex?.tree,ev,s,t,Z]),(0,i.useLayoutEffect)(()=>{var e;let n=nO?`[data-entry-id="${CSS.escape(nO.entryId)}"]`:null,r=n?ta.current?.querySelector(nU?.role==="user"?n:`${n} [data-search-target]`)??ta.current?.querySelector(n):null,i=(e={pending:nO??null,searchTarget:t??null,elementFound:!!r}).pending?e.pending!==e.searchTarget?"clear-stale":e.elementFound?"commit":"retry":"ignore";"ignore"===i||"retry"===i||("clear-stale"===i?nH(null):r&&nO&&(nJ(),tM(r),r.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500}),nH(null),s?.(nO)))},[ek,nJ,ew.length,nN,nO,t,nU,ta,tM,s,nS]),(0,i.useEffect)(()=>{nC(0),nE(50)},[e?.id]),(0,i.useEffect)(()=>{let e=ta.current;e&&(tI||eM.isStreaming)&&nu(e.scrollTop,e.clientHeight,e.scrollHeight)&&nC(0)},[tI,eM.isStreaming,ta]),(0,i.useEffect)(()=>{let e=ta.current;if(!e)return void tB(!1);let t=()=>{let t=e.scrollHeight-e.scrollTop-e.clientHeight;tB(nS>0||t>160)},n=()=>{t(),nP.current||nS>0||nu(e.scrollTop,e.clientHeight,e.scrollHeight)&&(nC(0),nE(50))};t();let r=new ResizeObserver(()=>{tl.current&&tE("instant"),t()});return r.observe(e),n$.current&&r.observe(n$.current),e.addEventListener("scroll",n,{passive:!0}),()=>{r.disconnect(),e.removeEventListener("scroll",n)}},[tD,tl,ev,ta,tE,e?.id,nS]);let nY=(0,i.useCallback)(()=>{if(nW.current||nP.current)return;let t=ta.current;if(nL.current.startIndex>0){let e=n$.current;if(e&&t){let n=t.getBoundingClientRect().top;nT.current=st(Array.from(e.children).flatMap((e,t)=>{if(!(e instanceof HTMLElement))return[];let n=e.dataset.entryId||e.dataset.slotIndex||`slot-${t}`,r=e.getBoundingClientRect();return[{entryId:n,top:r.top,bottom:r.bottom}]}),n)}nC(e=>e+25),nE(50);return}if(!eC||!eS)return;let n=e?.id??ts.current;n&&(nW.current=!0,t&&(nR.current=t.scrollHeight-t.scrollTop),tC(n,tN,eS).finally(()=>{nW.current=!1}))},[eS,eC,e,tN,tC,ts,ta]);(0,i.useEffect)(()=>{let e=nM.current,t=ta.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nY()},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nY,ta]),(0,i.useEffect)(()=>{let e=nI.current,t=ta.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&!nP.current&&nC(e=>Math.max(0,e-25))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nS,ta]),(0,i.useLayoutEffect)(()=>{let e=nT.current,t=n$.current;if(!e||!t)return;let n=Array.from(t.children).find((t,n)=>t instanceof HTMLElement&&(t.dataset.entryId||t.dataset.slotIndex||`slot-${n}`)===e.anchorEntryId);n instanceof HTMLElement&&tM(n,e.anchorOffset),nT.current=null},[nS,tM]),(0,i.useEffect)(()=>{if(null==nR.current)return;let e=ta.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nR.current),nR.current=null}},[ew.length,ta]);let nZ=e0?[e0.sessionId,e0.sessionFile??"",e0.sessionName??"",e0.userMessages,e0.assistantMessages,e0.toolCalls,e0.toolResults,e0.totalMessages,e0.tokens.input,e0.tokens.output,e0.tokens.cacheRead,e0.tokens.cacheWrite,e0.tokens.total,e0.cost??0,e0.totalActiveMs??0,e0.contextUsage?.percent??"null",e0.contextUsage?.contextWindow??"",e0.contextUsage?.tokens??"null"].join("|"):null,nX=(0,i.useRef)(e0);nX.current=e0,(0,i.useEffect)(()=>{ev||z?.(nX.current)},[ev,nZ,z]),(0,i.useEffect)(()=>()=>{z?.(null)},[z]);let nG=eK?`${eK.percent??"null"}|${eK.contextWindow}|${eK.tokens??"null"}`:null,nQ=(0,i.useRef)(eK);nQ.current=eK,(0,i.useEffect)(()=>{ev||A?.(nQ.current)},[nG,ev,A]),(0,i.useEffect)(()=>()=>{A?.(null)},[A]);let{isDragOver:n0,handleDragEnter:n1,handleDragOver:n2,handleDragLeave:n4,handleDrop:n8}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&(e.preventDefault(),r.current+=1,n(!0))},[]),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:a,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{en.current?.addImages(e)},[])),n3=e?.cwd??d??void 0,n6=(0,i.useMemo)(()=>ew.filter(e=>tX(e)||"assistant"===e.role||"toolResult"===e.role&&!e.isError&&eb(e.details)),[ew]),n5=(0,i.useMemo)(()=>{let e=new Map(ej);for(let t of ew)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ej,ew]),n7=(0,i.useMemo)(()=>new Set(tn?.kind==="running_tools"?tn.tools.map(e=>e.id):[]),[tn]),n9=(0,i.useMemo)(()=>ew.map(e=>"assistant"===e.role?t6(e):null),[ew]),re=(0,i.useMemo)(()=>{let e=new Map;for(let t=0;t<ew.length;){let n=tX(ew[t])?t:-1,r=n>=0?t+1:t;for(;r<ew.length&&!tX(ew[r]);)r+=1;let i=si(ew,n,r);if(i>=0&&n9[i]?.answerMessage){let t=[];for(let e=n+1;e<=i;e+=1){let n=ew[e];n?.role==="assistant"&&t.push(...n.content)}e.set(i,function(e,t,n){let r=new Set,i=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||nl(e)||no(e)}(s.toolName))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let e of function(e){let t=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(e);if(t)return[t];let n="string"==typeof e?.patch?e.patch:null;return n?function(e){let t=ne(e);if(!t)return[];let n=[];for(let e of t){let t=e.moveTo??e.path;t&&!n.includes(t)&&n.push(t)}return n}(n):[]}(s.input)){let t=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),a=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(s),o=s.startsWith("//");if(l||o)n=s;else if(s.startsWith("/")){let e=a?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??a?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!a)return null;n=`${a}/${s}`}return ni(n)}(e,n);t&&(r.has(t)||(r.add(t),i.push({filePath:t})))}}return i}(t,n5,n3))}t=r}return e},[n9,n3,ew,n5]),rt=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ew.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;if("string"==typeof e.content){let t=e.content.trim();return t.length>0?t:null}let t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim();return t.length>0?t:null}(ew[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ew]),rn=(J=n6.length,(Y=(0,i.useRef)([])).current=Array(J).fill(null).map((e,t)=>Y.current[t]??null),Y),rr=(0,i.useMemo)(()=>{for(let e=ew.length-1;e>=0;e--)if(ew[e]?.role==="user")return ek[e]??"";return""},[ek,ew]);(0,i.useEffect)(()=>{let e=nF.current;nF.current=tN,null!==e&&e!==tN&&(nP.current?.abort(),nB.current&&(em(null),ef(!1)))},[tN]),(0,i.useEffect)(()=>()=>{nP.current?.abort()},[e?.id]);let ri=(0,i.useCallback)(async t=>{let n=e?.id??ts.current;if(!n)return;nP.current?.abort();let r=new AbortController;nP.current=r,nD(null),nH(null);try{nR.current=null,nT.current=null,await nK(t,n,r.signal),r.signal.throwIfAborted(),await new Promise((e,n)=>{r.signal.addEventListener("abort",()=>n(r.signal.reason),{once:!0}),nD({entryId:t,signal:r.signal,resolve:e})})}catch(e){if(nf(e,r.signal))return;e9({type:"warning",message:e instanceof nh&&"stalled"===e.reason?Z("chat.locateHistoryStalled"):e instanceof nh&&"load_failed"===e.reason?Z("chat.locateLoadFailed"):Z("chat.locateNotFound")})}finally{nD(e=>e?.signal===r.signal?null:e),nP.current===r&&(nP.current=null)}},[e9,nK,e?.id,ts,Z]);(0,i.useLayoutEffect)(()=>{if(!nz||nz.signal.aborted)return;let e=n$.current?.querySelector(`[data-entry-id="${CSS.escape(nz.entryId)}"]`);e&&(nJ(),tM(e),nz.resolve())},[nz,ek,nJ,ew.length,nN,nS,tM]);let rs=!!eM.streamingMessage?.content.length,ra=(0,i.useMemo)(()=>{let e=-1;for(let t=ew.length-1;t>=0;t--)if(tX(ew[t])){e=t;break}let t=e>=0&&tZ(ew[e])?e:e+1;for(let e=t;e<ew.length;e++){let t=ew[e];if("custom"===t.role||"assistant"===t.role&&(tQ(t).length>0||t0(t)))return!0}return!1},[ew]),rl=eM.streamingMessage?.role==="assistant"?eM.streamingMessage:null,ro=rl?t6(rl,{isStreaming:!0}):{processMessage:null,answerMessage:null},rd=(0,i.useRef)(I);(0,i.useLayoutEffect)(()=>{let e=rd.current;rd.current=I,!e&&I&&tI&&!tA&&tE("instant")},[I,tI,tA,tE]);let rc=eG?eF[`${eG.provider}:${eG.modelId}`]??null:null,ru=eG?eH[`${eG.provider}:${eG.modelId}`]??null:null,rh=(0,i.useCallback)(async(e,t)=>{ed(),nP.current?.abort(),nD(null),nH(null),nC(0),nE(50),await to(e,t)},[to,ed]),rp=(0,i.useCallback)(e=>(ed(),th(e)),[th,ed]),rm=(0,i.useCallback)((e,t)=>(ed(),tf(e,t)),[tf,ed]),rg=(0,i.useCallback)((e,t)=>(ed(),tx(e,t)),[tx,ed]),rf=(0,i.useCallback)((e,t,n)=>(ed(),tv(e,t,n)),[tv,ed]),rx=!ti&&ev,rv=e?.relation?.kind==="subagent"&&"queued"===e.relation.status,ry=(0,r.jsx)(tz,{ref:er,onSend:rh,onOpenImageGeneration:!tO||rx||tI||rv?void 0:e=>{tK(null),tJ(e),t1(e=>e+1),t_(!0)},onAbort:tL,onSteer:eI?rm:void 0,onFollowUp:eI?rg:void 0,onPromptWithStreamingBehavior:eI?rf:void 0,isStreaming:tI||rv,disabled:rv,model:rx?null:eG,isAutoModelSelection:!rx&&tt,modelNames:eR,modelList:eW,modelError:rx?null:eD,modelScopeWarnings:rx?[]:eA,onModelChange:rx||rv?void 0:tm,modelSwitching:eQ,onCompact:!rv&&(e||ti)?tg:void 0,onAbortCompaction:ty,isCompacting:eJ,compactError:eY,compactResult:eZ,contextUsage:rx?null:eK,cacheHitRate:tR,onOpenSessionStats:D,toolPreset:eU,onToolPresetChange:!rv&&(e||ti)?tj:void 0,thinkingLevel:rx?void 0:e_??void 0,onThinkingLevelChange:rx||rv?void 0:e||ti?tk:void 0,availableThinkingLevels:rc,thinkingLevelMap:ru,retryInfo:eq,queuedMessages:e4,inputHistory:rt,onRecallQueue:tb,slashCommands:e1,slashCommandsLoading:e2,onLoadSlashCommands:tS,onBuiltinCommand:nv,onAudioUnlock:V,draftKey:e?.id??c??void 0,onDraftChange:u,draftPersistenceWarning:v,cwd:e?.cwd??d});return ev?(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[(0,r.jsx)("div",{className:"relative flex min-h-0 min-w-0 flex-1 items-center justify-center",children:(0,r.jsx)("div",{className:"text-sm text-text-muted",children:Z("chat.loadingSession")})}),(0,r.jsx)("div",{className:"relative shrink-0",children:ry})]}):ey?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ey}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:n1,onDragOver:n2,onDragLeave:n4,onDrop:n8,children:[n0&&(0,r.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-[color-mix(in_srgb,var(--accent)_6%,transparent)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[color-mix(in_srgb,var(--accent)_50%,transparent)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.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_color-mix(in_srgb,var(--accent)_18%,transparent)]",children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"color-mix(in srgb, var(--accent) 8%, transparent)",stroke:"color-mix(in srgb, var(--accent) 50%, transparent)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"color-mix(in srgb, var(--accent) 16%, transparent)",stroke:"color-mix(in srgb, var(--accent) 40%, transparent)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"color-mix(in srgb, var(--accent) 22%, transparent)",stroke:"color-mix(in srgb, var(--accent) 55%, transparent)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"color-mix(in srgb, var(--accent) 45%, transparent)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,r.jsx)("div",{className:"notice-shelf-wrapper",style:{position:"absolute",top:12,left:0,right:0,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(sg,{notices:e8,floating:!0,onPauseChange:te})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[tU&&tO&&(0,r.jsx)(tF,{config:tO,edit:tq,initialSourceImage:tV,editPreviewUrl:tq?`/api/files/${k(tq.path.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(tq.path)?tq.path:n3?E(n3,tq.path):tq.path)}?type=read`:void 0,onClose:()=>{t_(!1),tK(null)},onSubmit:nx}),e3&&(0,r.jsx)(sf,{request:e3,onRespond:e5},e3.id),e6&&(0,r.jsx)(sx,{request:e6,onInput:e7},e6.id),!tD&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:ta,className:"min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",style:{overflowAnchor:"none",overscrollBehaviorY:"contain",visibility:eh?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:n$,onPointerUp:nb,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var n,i;let s=-1;for(let e=ew.length-1;e>=0;e--)if(tX(ew[e])){s=e;break}let a=new Map,l=0;ew.forEach((e,t)=>{let n=("toolResult"!==e.role||e.isError)&&("custom"!==e.role||e.customType!==ep)?null:eb(e.details);(tX(e)||"assistant"===e.role||n)&&a.set(t,l++)});let o=(t,n={})=>{var i,s;let l,o,d,c=n.messageOverride??ew[t],u="user"===c.role&&t>0&&"assistant"===ew[t-1].role?ek[t-1]:void 0,h=("toolResult"!==c.role||c.isError)&&("custom"!==c.role||c.customType!==ep)?null:eb(c.details),p=tX(c)||"assistant"===c.role||!!h,m=a.get(t),g=n.keyPrefix??"message",f=ek[t]??t,x=h?(0,r.jsx)(eN,{value:h,cwd:n3,onEdit:tO&&!tI&&tO.connections.some(e=>e.id===h.connection&&!0===e.capabilities.editing)?e=>{tK(e),t1(e=>e+1),t_(!0)}:void 0,onMention:tO?e=>{en.current?.mentionImage(e)}:void 0,showPrompt:"custom"===c.role,createdAt:c.timestamp},`${g}-image-${f}`):(0,r.jsx)(rw,{message:c,modelName:n.isTurnEnd&&"assistant"===c.role?(i=c.provider??"",s=c.model??"",l=i.toLowerCase(),o=s.toLowerCase(),d=Object.entries(eR??{}).flatMap(([e,t])=>{let n=e.indexOf(":");return n>0&&e.slice(0,n).toLowerCase()===l?[{id:e.slice(n+1).toLowerCase(),name:t}]:[]}),d.find(e=>e.id===o)?.name??d.find(e=>o.endsWith(`/${e.id}`))?.name??Object.entries(eR??{}).find(([e])=>e.toLowerCase()===o)?.[1]??(i&&s?`${i}/${s}`:s)):void 0,toolResults:n5,cwd:n3,onOpenFile:eo,onOpenSession:B,entryId:ek[t],searchBlock:ek[t]===nO?.entryId?n_:void 0,onFork:tI||ti?void 0:rp,forking:eV===ek[t],onNavigate:tI?void 0:tp,prevAssistantEntryId:tI?void 0:u,onEditContent:ec,isTurnEnd:n.isTurnEnd,sessionId:e?.id??ts.current??void 0,writtenFiles:n.writtenFiles,isProcess:n.isProcess,runningToolIds:"assistant"===c.role&&c.content.some(e=>"toolCall"===e.type&&n7.has(e.toolCallId))?n7:void 0},`${g}-view-${f}`);return p?(0,r.jsx)("div",{"data-entry-id":ek[t],"data-slot-index":`msg-${t}`,ref:!1===n.attachRef||void 0===m?void 0:e=>{rn.current[m]=e},children:x},`${g}-${f}`):x},d=(n={outline:nz?{entryId:nz.entryId,aborted:nz.signal.aborted}:null,search:nO?{entryId:nO.entryId,matchesTarget:nO===t}:null,restore:eh?{entryId:eh.anchorEntryId}:null}).outline&&!n.outline.aborted?n.outline.entryId:n.search&&n.search.matchesTarget?n.search.entryId:n.restore?n.restore.entryId:null,c=[],u=-1,h=e=>{var t,n;t=u,n=c.length,u=d&&e.includes(d)?n:t},p=0;for(let e=0;e<ew.length;){let t,n,i,l=tX(ew[e]),u=tY(ew[e]),m=l?e:-1,g=m>=0&&tZ(ew[m]),f=l?e+1:e;for(;f<ew.length&&!tX(ew[f]);)f+=1;let x=l?m:e,v=g?m:m+1,y=si(ew,m,f),b=(tI||eM.isStreaming)&&f===ew.length&&m===s;if(b&&(p=f-x),-1===y&&!g){for(let e=x;e<f;e++)h([ek[e]]),c.push(o(e));if(b&&ro.processMessage){h([]);let e=sa(!0,eM.isStreaming,rl,tn,!!ro.answerMessage),t=m>=0&&"number"==typeof ew[m]?.timestamp&&Number.isFinite(ew[m].timestamp)?ew[m].timestamp:ro.processMessage.timestamp,n=sc(t,ro.processMessage.completedAt);c.push((0,r.jsx)("div",{children:(0,r.jsx)(sh,{messageCount:1,toolCallCount:t8(ro.processMessage.content??[]),durationSeconds:n,startTime:t,defaultExpanded:!0,isMobile:X,activeStepSummary:sd(so(ro.processMessage,tn,Z),e,tT,Z("chat.thinking")),isStreaming:e,t:Z,children:(0,r.jsx)(rw,{message:ro.processMessage,isStreaming:!0,isProcess:!0,toolResults:n5,cwd:n3,onOpenFile:eo,onOpenSession:B},"streaming-process-view")})},`process-group-${ek[x]??x}`))}e=f;continue}u&&(h([ek[m]]),c.push(o(m)));let w=n9[y],j=w?.answerMessage??null,k=y>=0?y:f-1,S=[],C=[],N=[],E=0,M=!1;for(let e=v;e<=k;e++){let r=ew[e];if("number"==typeof r.timestamp&&Number.isFinite(r.timestamp)&&(n=void 0===n?r.timestamp:Math.min(n,r.timestamp),i=void 0===i?r.timestamp:Math.max(i,r.timestamp)),"assistant"===r.role&&"number"==typeof r.completedAt&&Number.isFinite(r.completedAt)&&(i=void 0===i?r.completedAt:Math.max(i,r.completedAt)),"custom"===r.role){t??=a.get(e),M||=!!(d&&d===ek[e]),ek[e]&&C.push(ek[e]),S.push(o(e,{attachRef:!1,keyPrefix:"process",isProcess:!0}));continue}if("assistant"!==r.role)continue;let s=n9[e];e!==y&&s?.answerMessage&&N.push({idx:e,message:s.answerMessage});let l=s?.processMessage;if(!l)continue;let c=tQ(l),u=!!t0(l);(0!==c.length||u)&&(t??=a.get(e),E+=t8(c),M||=!!(d&&ek[e]===d&&(!n_||nO?.entryId!==d||c.includes(n_))),ek[e]&&C.push(ek[e]),S.push(o(e,{attachRef:!1,keyPrefix:"process",messageOverride:l,isTurnEnd:!1,isProcess:!0})))}b&&ro.processMessage&&(E+=t8(ro.processMessage.content??[]),S.push((0,r.jsx)(rw,{message:ro.processMessage,isStreaming:!0,isProcess:!0,toolResults:n5,cwd:n3,onOpenFile:eo,onOpenSession:B},"streaming-process-view")));let I=!!(j||ro.answerMessage),L=sa(b,eM.isStreaming,rl,tn,I),T=sd(so(rl,tn,Z),L,tT,Z("chat.thinking")),$=m>=0&&"number"==typeof ew[m]?.timestamp&&Number.isFinite(ew[m].timestamp)?ew[m].timestamp:n,R=sc($??n,i);S.length>0&&(h(C),c.push((0,r.jsx)("div",{"data-entry-id":ek[v],ref:void 0===t?void 0:e=>{rn.current[t]=e},children:(0,r.jsx)(sh,{messageCount:S.length,toolCallCount:E,durationSeconds:R,startTime:$??n,defaultExpanded:!j&&f===ew.length,reveal:M,isMobile:X,activeStepSummary:T,isStreaming:L,t:Z,children:S})},`process-group-${ek[x]??x}`)));for(let e=x;e<=k;e++){let t=ew[e];"toolResult"===t.role&&!t.isError&&eb(t.details)&&(h([ek[e]]),c.push(o(e)))}for(let e of N)h([ek[e.idx]]),c.push(o(e.idx,{keyPrefix:"promoted",messageOverride:e.message}));if(j&&(h([ek[y]]),c.push(o(y,{isTurnEnd:!0,messageOverride:j,writtenFiles:re.get(y)}))),y>=0)for(let e=y+1;e<f;e++)h([ek[e]]),c.push(o(e));e=f}let m=Math.max(nN,50+p),{startIndex:g,endIndex:f}=u>=0?nc(i=c.length,i-Math.max(0,u-5)-50):nc(c.length,nS,m);nL.current={startIndex:g,endIndex:f,totalCount:c.length};let x=g>0||eC;return(0,r.jsxs)(r.Fragment,{children:[x&&(0,r.jsx)("button",{type:"button",ref:nM,onClick:nY,className:"w-full cursor-pointer py-3 text-center text-xs text-text-muted transition-colors hover:text-text focus-visible:outline-2 focus-visible:outline-accent",children:Z("chat.loadEarlier")}),c.slice(g,f),f<c.length&&(0,r.jsx)("div",{ref:nI,className:"py-3 text-center text-xs text-text-muted"})]})})(),eM.isStreaming&&ro.answerMessage&&(0,r.jsx)(rw,{message:ro.answerMessage,isStreaming:!0,cwd:n3,onOpenFile:eo,onOpenSession:B}),eI&&!rs&&!ra&&(0,r.jsx)(sn,{label:Z("chat.agentWorking")}),eT&&!e$&&(0,r.jsx)(sn,{label:Z("chat.agentWorking")}),e$&&(0,r.jsx)(rw,{message:{role:"bashExecution",command:e$.command,output:"",excludeFromContext:e$.excludeFromContext},sessionId:e?.id??ts.current??void 0,onOpenSession:B}),tW&&(0,r.jsx)(eE,{prompt:tW.prompt,size:tW.size,width:tW.width,height:tW.height,previewUrl:tW.previewUrl})]})})}),tA&&!eh&&(0,r.jsx)("button",{type:"button",onClick:()=>{nP.current?.abort(),nD(null),nH(null),nC(0),nE(50),requestAnimationFrame(()=>tE("smooth"))},className:"absolute bottom-3 right-5 z-30 inline-flex h-7 w-7 items-center justify-center rounded-[4px] border border-[var(--border)] bg-[var(--bg)] text-[var(--text-muted)] transition-colors hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:outline-2 focus-visible:outline-[var(--accent)]",title:Z("chat.scrollToBottom"),"aria-label":Z("chat.scrollToBottom"),children:(0,r.jsx)("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,r.jsx)("path",{d:"m7 10 5 5 5-5"})})}),X&&L&&(0,r.jsx)(r6,{sessionId:e?.id??ts.current,leafId:tN,outlineRevision:rr,scrollContainer:ta,contentContainer:n$,loadedEntryIds:ek,onJumpToEntry:ri,onChange:P}),!L||X||eh?null:(0,r.jsx)(r3,{sessionId:e?.id??ts.current,leafId:tN,outlineRevision:rr,scrollContainer:ta,contentContainer:n$,loadedEntryIds:ek,onJumpToEntry:ri})]})]}),H&&t2&&(0,M.createPortal)((0,r.jsx)("div",{ref:nr,role:t3?"dialog":"toolbar","aria-label":Z(t3?"chat.newQuoteChat":"chat.askSelection"),className:"popover-surface",style:{position:"fixed",top:t2.top,left:t2.left,zIndex:130,display:"flex",flexWrap:"wrap",gap:2,width:t3?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:t3?12:2},children:t3?(0,r.jsxs)("fieldset",{disabled:t7,"aria-busy":t7,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:Z("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:Z("i18n.close"),"aria-label":Z("i18n.close"),disabled:t7,onClick:ny,style:{border:"none"},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(tz,{ref:ns,compact:!0,onSend:nj,onAbort:ny,isStreaming:!1}),nt&&(0,r.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:12,overflowWrap:"anywhere"},children:nt})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"inline-flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-[4px] border-0 bg-transparent px-2 text-[11px] text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:outline-2 focus-visible:outline-[var(--accent)]",title:Z("chat.askInCurrent"),"aria-label":Z("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:nw,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:"@"}),(0,r.jsx)("span",{children:Z("chat.askInCurrent")})]}),O&&t2.sourceEntryId&&!tI&&(0,r.jsxs)("button",{type:"button",className:"inline-flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-[4px] border-0 bg-transparent px-2 text-[11px] text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:outline-2 focus-visible:outline-[var(--accent)]",title:Z("chat.askInNewChat"),"aria-label":Z("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{t5(!0),window.getSelection()?.removeAllRanges()},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12M18 9a9 9 0 0 1-9 9"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"})]}),(0,r.jsx)("span",{children:Z("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative shrink-0",children:[tD&&(0,r.jsxs)("div",{className:"empty-hero-anchor mx-auto mb-6 select-none text-center",style:{maxWidth:"var(--chat-content-max-width, 820px)",padding:"0 16px"},children:[(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 82 32",width:"82",height:"32",fill:"currentColor",role:"img","aria-label":"Pi Web",style:{color:"var(--text)",display:"block",margin:"0 auto"},children:(0,r.jsx)("path",{d:"M0 0H24V16H16V8H0ZM0 8H8V16H16V24H8V32H0ZM24 16H32V32H24ZM44 16H46V26H44ZM46 26H48V32H46ZM48 22H50V26H48ZM50 26H52V32H50ZM52 16H54V26H52ZM60 16H68V18H60ZM58 18H60V30H58ZM60 22H66V24H60ZM60 30H68V32H60ZM72 16H80V18H74V22H80V24H74V30H80V32H72ZM80 18H82V22H80ZM80 24H82V30H80Z"})}),(0,r.jsx)(se,{}),d&&p&&(0,r.jsx)(sr,{cwd:d,onChange:p,recentPaths:m,pinnedPaths:g,homeDir:f,worktreeInfo:x})]}),ry]}),tD&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function sm({type:e}){return"success"===e?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})}):"error"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"var(--danger)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),(0,r.jsx)("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}):"warning"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"var(--warning)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function sg({notices:e,floating:t=!1,onPauseChange:n}){return 0===e.length?null:(0,r.jsx)("div",{className:"notice-shelf-root",style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!t},children:e.map((i,s)=>(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>n?.(i.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||n?.(null)},onFocus:()=>n?.(i.id),onBlur:e=>{e.currentTarget.matches(":hover")||n?.(null)},style:{display:"flex",alignItems:"flex-start",gap:8,minHeight:34,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(s!==e.length-1),overflow:"hidden",borderRadius:8,border:"1px solid var(--border)",background:"color-mix(in srgb, var(--bg) 95%, var(--bg-panel))",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",color:"var(--text)",width:"fit-content",maxWidth:"min(100%, 540px)",boxShadow:t?"0 4px 16px -2px rgba(0, 0, 0, 0.12), 0 2px 6px -1px rgba(0, 0, 0, 0.06)":"0 2px 8px -2px rgba(0, 0, 0, 0.08)",fontSize:12,lineHeight:1.45,transformOrigin:"top right",animation:i.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"8px 12px"},children:[(0,r.jsx)(sm,{type:i.type}),(0,r.jsx)("span",{tabIndex:0,style:{minWidth:0,maxWidth:"100%",maxHeight:480,overflowY:"auto",whiteSpace:"pre-line",wordBreak:"break-word"},children:i.message})]},i.id))})}function sf({request:e,onRespond:t}){let{t:n}=(0,w.s)(),[s,a]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(()=>Date.now()),u=(0,i.useCallback)(e=>e?.focus(),[]),h=function(e){if("select"===e.method&&e.options.length>0)return e.options[0];if("confirm"===e.method){let t=e.message.split("\n").find(e=>e.trim());return t?.trim()}}(e),p=void 0===e.expiresAt?null:Math.max(0,Math.ceil((e.expiresAt-d)/1e3));(0,i.useEffect)(()=>{if(void 0===e.expiresAt)return;let t=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(t)},[e.expiresAt]);let m=null!==p&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionExpiresIn",{seconds:p})}),g=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:s})};return(0,r.jsx)("div",{onKeyDown:n=>{"Escape"!==n.key||n.nativeEvent.isComposing||(n.preventDefault(),n.stopPropagation(),t(e,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:l?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:l?(0,r.jsxs)("button",{type:"button",onClick:()=>o(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--accent)",flexShrink:0},children:n("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:e.title}),h&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:h}),m,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:n("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog","aria-label":e.title,style:{pointerEvents:"auto",width:"min(560px, 100%)",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:600},children:e.title}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontVariantNumeric:"tabular-nums"},children:[(0,r.jsx)("span",{children:n("chat.extensionRequest")}),m]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>o(!0),"aria-expanded":!0,title:n("chat.extensionCollapse"),"aria-label":n("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===e.method&&(0,r.jsx)(rl,{children:e.message}),"select"===e.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:e.options.map((n,i)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":n,ref:0===i?u:void 0,onClick:()=>t(e,{value:n}),onKeyDown:r=>{("Enter"===r.key||" "===r.key)&&(r.preventDefault(),t(e,{value:n}))},style:{width:"100%",padding:"9px 10px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12,overflowWrap:"anywhere"},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(rl,{children:n})})},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:s,placeholder:e.placeholder,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||g()},style:{width:"100%",padding:"9px 10px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:12}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:s,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&g()},style:{width:"100%",minHeight:220,padding:10,borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===e.method||"select"===e.method&&0===e.options.length,onClick:()=>t(e,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:n("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:g,style:{padding:"6px 10px",borderRadius:4,border:"1px solid var(--primary)",background:"var(--primary)",color:"var(--primary-contrast)",cursor:"pointer"},children:n("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:g,style:{padding:"6px 10px",borderRadius:4,border:"1px solid var(--primary)",background:"var(--primary)",color:"var(--primary-contrast)",cursor:"pointer"},children:n("chat.submit")}):null]})]})})}function sx({request:e,onInput:t}){let{t:n}=(0,w.s)(),s=(0,i.useRef)(null),a=(0,i.useRef)(!1),[l,o]=(0,i.useState)(!1),d=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(tH,""),i=tU(e).trimEnd();if(t.test(i))continue;let s=e,a=tK(s);("│"===a||"┃"===a)&&" "===tK(s=tq(s,0))&&(s=tq(s,0));let l=function(e){let t=t_(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),o=l>=0?t_(s)[l]?.char:void 0;("│"===o||"┃"===o)&&(s=tq(s,l)),n.push(function(e){let t=e;for(;;){let e=t_(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===tU(n[0]).trim();)n.shift();for(;n.length>0&&""===tU(n[n.length-1]).trim();)n.pop();return n.length?n:e}(e.lines),c=d.find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{l||s.current?.focus()},[l]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:l?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:l?(0,r.jsxs)("button",{type:"button",onClick:()=>o(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--accent)",flexShrink:0},children:n("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n("chat.extensionPanel")}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:c}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:n("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||s.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:s,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=tJ[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":tV[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:n=>{a.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:600},children:n("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("button",{type:"button",onClick:()=>o(!0),"aria-expanded":!0,title:n("chat.extensionCollapse"),"aria-label":n("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(r9,{text:d.join("\n")})})]})})}function sv({tabs:e,activeTabId:t,splitTabId:n=null,activePane:s="primary",runningSessionIds:a,onSelectTab:l,onCloseTab:o,onPinTab:d,onNewTab:c,onToggleSplit:u,onClosePane:h,canSplit:p=!0,isSecondaryPane:m=!1,unifiedHeader:g=!1,isMobile:f=!1}){let{t:x}=(0,w.s)(),[v,y]=(0,i.useState)(null),[b,j]=(0,i.useState)(!1),[k,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)({top:0,left:0,width:320}),E=(0,i.useRef)(null),I=(0,i.useRef)(null),L=(0,i.useRef)(null),T=(0,i.useRef)(null);(0,i.useEffect)(()=>{E.current&&E.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),(0,i.useEffect)(()=>{let e=I.current;if(!e)return;let t=()=>j(e.scrollWidth>e.clientWidth+1);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[e]),(0,i.useEffect)(()=>{if(!k)return;let e=e=>{let t=e.composedPath();T.current&&t.includes(T.current)||L.current&&t.includes(L.current)||S(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),S(!1),L.current?.focus())},n=()=>S(!1);return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),window.addEventListener("resize",n),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0),window.removeEventListener("resize",n)}},[k]),(0,i.useEffect)(()=>{b||S(!1)},[b]);let $=!!(n&&!f),R=e=>{let t=e?Array.from(document.querySelectorAll("[data-chat-tab-id]")).find(t=>t.dataset.chatTabId===e):null,n=E.current??document.querySelector('[data-chat-tab="true"][tabindex="0"]'),r=Array.from(document.querySelectorAll(".chat-input-textarea")).find(e=>e.getClientRects().length>0);(t??n??r)?.focus()};return(0,r.jsxs)("div",{role:"tablist","aria-label":x("chatTabs.label",{defaultValue:"对话标签"}),style:{display:"flex",alignItems:"stretch",background:g?"transparent":"var(--bg-panel)",boxShadow:g?void 0:"inset 0 -1px 0 var(--border)",height:"var(--workspace-header-height, 30px)",minHeight:"var(--workspace-header-height, 30px)",maxHeight:"var(--workspace-header-height, 30px)",width:g?"auto":"100%",maxWidth:"100%",minWidth:0,flex:g?"0 1 auto":"0 0 auto",flexShrink:0,overflow:"hidden",position:"relative"},children:[(0,r.jsx)("div",{ref:I,onWheel:e=>{e.deltaY&&!e.deltaX&&(e.currentTarget.scrollLeft+=e.deltaY)},style:{display:"flex",alignItems:"stretch",flex:"0 1 auto",minWidth:0,overflowX:"auto",overflowY:"hidden",scrollbarWidth:"none",WebkitOverflowScrolling:"touch",touchAction:"pan-x",overscrollBehaviorX:"contain"},children:e.map((i,c)=>{let u=i.id===t,h=i.id===n,p=u||h,m=u&&"primary"===s||h&&"secondary"===s,b="session"===i.kind&&!!(i.session&&a?.has(i.session.id));return(0,r.jsxs)("div",{"data-chat-tab":"true","data-chat-tab-id":i.id,ref:u?E:void 0,role:"tab","aria-label":i.dirty?`${i.title}, ${x("chatTabs.unsentDraft")}`:i.title,"aria-selected":p,tabIndex:m||!t&&0===c?0:-1,onClick:()=>l(i.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1===e.button&&(e.preventDefault(),e.stopPropagation(),o(i.id))},onDoubleClick:()=>d?.(i.id),onKeyDown:t=>{if(t.target===t.currentTarget){if("Enter"===t.key||" "===t.key)t.preventDefault(),l(i.id);else if(["ArrowLeft","ArrowRight"].includes(t.key)){t.preventDefault();let n=(c+("ArrowRight"===t.key?1:-1)+e.length)%e.length;l(e[n].id),t.currentTarget.parentElement?.children[n]?.focus()}else if("Delete"===t.key){if(t.preventDefault(),!1===o(i.id))return;requestAnimationFrame(()=>{R()})}}},style:{display:"flex",alignItems:"center",gap:f?4:6,height:"100%",paddingLeft:f?8:10,paddingRight:f?p?4:8:4,borderRight:f&&c===e.length-1&&!p?"none":"1px solid var(--border)",background:p?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:p?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:f?130:200,minWidth:f?70:84,flexShrink:0,userSelect:"none",WebkitUserSelect:"none",touchAction:"pan-x",position:"relative",transition:"background 0.12s, color 0.12s",boxShadow:[m&&"inset 0 2px 0 var(--accent)",p&&0===c&&g&&"inset 1px 0 0 var(--border)",!p&&"inset 0 -1px 0 var(--border)"].filter(Boolean).join(", ")||void 0},title:i.preview?`${i.title} \xb7 ${x("chatTabs.previewTabHint",{defaultValue:"预览标签,双击固定"})}`:i.title,children:[(b||"draft"===i.kind)&&(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:b?"var(--accent)":p?"var(--text)":"var(--text-dim)"},children:b?(0,r.jsx)(X,{size:12,ariaLabel:"Running"}):(0,r.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,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,textDecoration:i.preview?"underline dotted":void 0,textDecorationColor:"var(--text-dim)",textUnderlineOffset:5,paddingBlock:5},children:i.title}),"draft"===i.kind&&i.dirty&&(0,r.jsx)("span",{title:x("chatTabs.unsentDraft"),"aria-hidden":"true",style:{width:5,height:5,borderRadius:"50%",background:"var(--accent)",flexShrink:0}}),(!f||p)&&(0,r.jsx)("button",{type:"button",tabIndex:-1,className:"file-tab-close",onMouseDown:e=>{0===e.button&&e.preventDefault()},onClick:e=>{e.stopPropagation(),y(null),o(i.id)},onDoubleClick:e=>e.stopPropagation(),onMouseEnter:()=>y(i.id),onMouseLeave:()=>y(null),onBlur:()=>y(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:f?22:20,height:f?22:20,background:v===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:3,color:v===i.id?"var(--text)":"var(--text-muted)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:x("chatTabs.closeTab",{defaultValue:"关闭标签"}),"aria-label":`${x("chatTabs.closeTab",{defaultValue:"关闭标签"})}: ${i.title}`,children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},i.id)})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,alignSelf:"stretch"},children:[b&&!f&&(0,r.jsx)("button",{ref:L,type:"button",onClick:()=>{if(k)return void S(!1);let e=L.current.getBoundingClientRect(),t=Math.min(320,window.innerWidth-16);N({top:e.bottom+4,left:Math.max(8,Math.min(e.right-t,window.innerWidth-t-8)),width:t}),S(!0)},"aria-expanded":k,title:x("chatTabs.allTabs"),"aria-label":x("chatTabs.allTabs"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",padding:0,border:"none",background:k?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 6h13M8 12h13M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01M3 12h.01M3 18h.01"})]})}),(0,r.jsx)("button",{type:"button",onClick:c,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:x("chatTabs.newTab",{defaultValue:"新建对话标签"}),"aria-label":x("chatTabs.newTab",{defaultValue:"新建对话标签"}),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="transparent"},children:(0,r.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,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),!m&&p&&!f&&u&&(0,r.jsx)("button",{type:"button",onClick:u,"aria-pressed":$,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:$?"var(--bg-selected)":"transparent",border:"none",color:$?"var(--accent)":"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:$?x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):x("chatTabs.splitView",{defaultValue:"向右分屏"}),"aria-label":$?x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):x("chatTabs.splitView",{defaultValue:"向右分屏"}),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="transparent")},children:(0,r.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,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]})}),m&&h&&(0,r.jsx)("button",{type:"button",onClick:h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}),"aria-label":x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}),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="transparent"},children:(0,r.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,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),k&&(0,M.createPortal)((0,r.jsx)("div",{ref:T,role:"dialog","aria-label":x("chatTabs.allTabs"),className:"popover-surface",style:{position:"fixed",top:C.top,left:C.left,width:C.width,zIndex:700,padding:4},children:(0,r.jsx)("div",{style:{maxHeight:"min(50vh, 360px)",overflowY:"auto",scrollbarWidth:"none"},children:e.map((e,i)=>{let s=e.id===t||e.id===n,d="session"===e.kind&&!!(e.session&&a?.has(e.session.id));return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",minWidth:0,background:s?"var(--bg-selected)":"transparent",borderRadius:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{S(!1),l(e.id),requestAnimationFrame(()=>R(e.id))},style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,height:28,padding:"0 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12},children:[d?(0,r.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:12,height:12,flexShrink:0},children:(0,r.jsx)(X,{size:10})}):(0,r.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",flexShrink:0,background:e.dirty?"var(--accent)":"transparent"}}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title})]}),(0,r.jsx)("button",{type:"button","data-tab-menu-close":e.id,onClick:()=>{!1!==o(e.id)&&requestAnimationFrame(()=>{let e=I.current;if(e&&e.scrollWidth>e.clientWidth+1){let e=T.current?.querySelectorAll("[data-tab-menu-close]"),t=e?.[Math.min(i,e.length-1)];if(t)return void t.focus()}S(!1),R()})},title:`${x("chatTabs.closeTab")}: ${e.title}`,"aria-label":`${x("chatTabs.closeTab")}: ${e.title}`,style:{width:28,height:28,padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M2 2l6 6M8 2 2 8"})})})]},e.id)})})}),document.body)]})}function sy(e,t){let n=e.split(/\r?\n/).find(e=>e.trim())?.trim();if(!n)return t;let r=Array.from(n);return r.length<=48?n:`${r.slice(0,47).join("")}…`}function sb(e){return e.pane??"primary"}function sw(e,t){return e.filter(e=>sb(e)===t)}function sj(e,t,n="primary"){let r=e.findIndex(e=>e.id===t.id),i=p(t);if(r>=0){let n=[...e];return n[r]={...n[r],session:t,title:i,projectKey:t.projectKey??t.cwd},{tabs:n,tabId:t.id}}let s=e.findIndex(e=>!0===e.preview&&sb(e)===n);if(s>=0){let r=[...e];return r[s]={id:t.id,kind:"session",title:i,session:t,newSessionCwd:null,newSessionDraftKey:null,projectKey:t.projectKey??t.cwd,preview:!0,pane:n},{tabs:r,tabId:t.id}}return{tabs:[...e,{id:t.id,kind:"session",title:i,session:t,newSessionCwd:null,newSessionDraftKey:null,projectKey:t.projectKey??t.cwd,preview:!0,pane:n}],tabId:t.id}}function sk(e,t){let n=e.findIndex(e=>e.id===t);if(-1===n||!0!==e[n].preview)return e;let r=[...e];return r[n]={...r[n],preview:!1},r}function sS(e,t){let n=[...sw(e,"primary"),...sw(e,"secondary")],r=n.find(e=>e.id===t&&e.preview)??n.find(e=>e.preview);return n.map(e=>({...e,pane:"primary",preview:!0===e.preview?e.id===r?.id:e.preview}))}function sC(e,t,n="primary"){let r=e.findIndex(e=>e.id===t.id),i=p(t);if(r>=0){let n=[...e];return n[r]={...n[r],session:t,title:i,projectKey:t.projectKey??t.cwd,preview:!1},{tabs:n,tabId:t.id}}return{tabs:[...e,{id:t.id,kind:"session",title:i,session:t,newSessionCwd:null,newSessionDraftKey:null,projectKey:t.projectKey??t.cwd,pane:n}],tabId:t.id}}function sN(e,t,n,r="新会话",i="primary"){let s=`draft:${n}`;return e.find(e=>e.id===s)?{tabs:e,tabId:s}:{tabs:[...e,{id:s,kind:"draft",title:r,session:null,newSessionCwd:t,newSessionDraftKey:n,projectKey:t,dirty:!1,pane:i}],tabId:s}}function sE(e,t,n,r=null){let i=e.findIndex(e=>e.id===t);if(-1===i)return{tabs:e,nextActiveTabId:n,nextSplitTabId:r};let s=e.filter(e=>e.id!==t),a=sb(e[i]),l=sw(e,a),o=sw(s,a),d=o[Math.min(l.findIndex(e=>e.id===t),o.length-1)]?.id??null,c=t===n?d:n,u=t===r?d:r;if(r&&0===o.length){let e="primary"===a?u:c;return{tabs:sS(s,e),nextActiveTabId:e,nextSplitTabId:null}}return{tabs:s,nextActiveTabId:c,nextSplitTabId:u}}var sM=n(50640);let sI={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},sL={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},sT={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function s$(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function sR(e){return null!==(sI[s$(e)]??null)}function sW(e){return null!==(sL[s$(e)]??null)}function sP(e){return null!==(sT[s$(e)]??null)}function sz(e){let t;return null!==("pdf"===(t=s$(e))||"docx"===t?t:null)}let sD=new Set(["md","mdx","markdown","html","htm"]);var sA=n(73620);let sF=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function sB(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}function sO(e,t){if(e[t]?.level!==3)return -1;for(let n=t-1;n>=0;n--)if(e[n].level<3)return n;return -1}let sH=/^ {0,3}(`{3,}|~{3,})/,sU=/^ {0,3}(#{1,3})[ \t]+(.+?)[ \t]*#*[ \t]*$/,s_=["tags","categories","keywords","tag","category"];function sq({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,s=s_.find(t=>Array.isArray(e[t])),a=s?e[s].map(sB).filter(Boolean):[],l=n.filter(([e])=>e!==s&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),a.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:a.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=sB(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}function sK({items:e,scrollRoot:t}){let{t:n}=(0,w.s)(),s=(0,i.useId)(),a=(0,i.useRef)(null),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(()=>new Set),u=e.length>20;if((0,i.useEffect)(()=>{o(!1),c(new Set)},[e]),(0,i.useEffect)(()=>{if(!l)return;let e=e=>{a.current?.contains(e.target)||o(!1)},t=e=>{"Escape"===e.key&&o(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[l]),0===e.length)return null;let h=e.map(()=>!1);if(u)for(let t=0;t<e.length;t++){let n=sO(e,t);n>=0&&(h[n]=!0)}return(0,r.jsxs)("div",{ref:a,className:"file-outline",children:[(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button","aria-expanded":l,"aria-haspopup":"menu","aria-controls":s,"aria-label":n("i18n.outline"),title:n("i18n.outline"),onClick:()=>o(e=>!e),style:{background:l?"var(--bg-selected)":"transparent",color:l?"var(--text)":"var(--text-muted)"},children:(0,r.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,r.jsx)("path",{d:"M8 6h13"}),(0,r.jsx)("path",{d:"M8 12h13"}),(0,r.jsx)("path",{d:"M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01"}),(0,r.jsx)("path",{d:"M3 12h.01"}),(0,r.jsx)("path",{d:"M3 18h.01"})]})}),l&&(0,r.jsx)("div",{className:`popover-surface file-outline-menu${u?" is-collapsible":""}`,id:s,role:"menu",children:e.map((n,i)=>{if(u&&3===n.level){let t=sO(e,i);if(t>=0&&!d.has(t))return null}return(0,r.jsxs)("div",{className:"file-outline-item","data-level":n.level,children:[h[i]?(0,r.jsx)("button",{type:"button",className:"file-outline-fold","aria-expanded":d.has(i),"aria-label":n.text,onClick:()=>{c(e=>{let t=new Set(e);return t.has(i)?t.delete(i):t.add(i),t})},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}):null,(0,r.jsx)("button",{type:"button",role:"menuitem",className:"file-outline-jump",title:n.text,onClick:()=>{!function(e,t,n){let r=t[n];if(!e||!r)return;let i=t.slice(0,n).filter(e=>e.text===r.text).length,s=0;for(let t of e.querySelectorAll(".markdown-file-preview :is(h1, h2, h3)"))if(t.textContent?.replace(/\s+/g," ").trim()===r.text){if(s===i)return void t.scrollIntoView({block:"start",inline:"nearest"});s++}}(t.current,e,i),o(!1)},children:n.text})]},`${n.level}-${i}-${n.text}`)})})]})}function sV(e,t,n){var r;return r=n??(sD.has(s$(e))?"preview":void 0),t?.displayMode??r??"source"}let sJ={fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.6},sY={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:1.6,userSelect:"none",flexShrink:0,verticalAlign:"top"};function sZ(){return(0,r.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,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function sX(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function sG(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=sX(n.startContainer),i=sX(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),a=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(a))return null;if(s<a){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((i=e).dataset.lineNumber))}}}return s>a?null:{startLine:s,endLine:a}}function sQ({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,s)=>{let a=e.children??[],l=a[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?a[0]:null,c=o?a.slice(1):a;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":s+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,sM.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${s}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,sM.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${s}-${r}`}))})]},`source-line-${s}`)})}function s0(e,t,n,r={}){let i=k(e),s=new URLSearchParams({type:t});for(let[e,t]of(n&&s.set("sessionId",n),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${i}?${s.toString()}`}function s1({filePath:e,sourceSessionId:t}){let{t:n}=(0,w.s)();return(0,r.jsx)("a",{href:s0(e,"download",t),download:S(e),title:n("i18n.downloadFile"),"aria-label":n("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.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,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function s2(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function s4({patch:e}){let{t}=(0,w.s)(),n=(0,i.useMemo)(()=>{let t;return(t=ru(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[{type:"hunk",text:e.text}];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[]},[e]),s=e.split(/\r?\n/).filter(e=>/^(?:similarity index|dissimilarity index|rename from|rename to|copy from|copy to|old mode|new mode|new file mode|deleted file mode|Binary files|Submodule )/.test(e));return s.length>0||n.some(e=>"added"===e.type||"removed"===e.type)?(0,r.jsxs)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...sJ},children:[s.map((e,t)=>(0,r.jsx)("div",{style:{padding:"2px 12px",color:"var(--text-muted)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:e},`${t}:${e}`)),n.map((e,t)=>{if("hunk"===e.type)return(0,r.jsx)("div",{style:{padding:"2px 12px",color:"var(--accent)",background:"var(--bg-panel)",borderBlock:"1px solid var(--border)"},children:e.text},`hunk-${t}`);let n="added"===e.type?"color-mix(in srgb, var(--success) 12%, transparent)":"removed"===e.type?"color-mix(in srgb, var(--danger) 14%, transparent)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid var(--success)":"removed"===e.type?"3px solid var(--danger)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{...sY,width:40,minWidth:40,paddingInline:6},children:e.oldLineNo}),(0,r.jsx)("span",{style:{...sY,width:40,minWidth:40,paddingInline:6},children:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)})]}):(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)"},children:t("i18n.noChanges")})}function s8({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:s=!0}){let{t:a}=(0,w.s)(),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),m(null),f(null),o(!1)},[e,n]),(0,i.useEffect)(()=>{if(o(!1),x.current&&(x.current.close(),x.current=null),!s)return;let t=!0,r=!1,i=new EventSource(s0(e,"watch",n));x.current=i,i.addEventListener("connected",()=>{var i;let s;o(!0),i=r,s=++v.current,fetch(s0(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&s===v.current){if(e.error)return void f(e.error);"number"==typeof e.size&&h(e.size),m(null),f(null),i&&c(e=>e+1)}}).catch(e=>{t&&s===v.current&&f(String(e))}),r=!0}),i.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),f(null),c(e=>e+1)});let a=()=>{o(!1)};return i.addEventListener("error",a),i.onerror=a,()=>{t=!1,i.close(),x.current===i&&(x.current=null)}},[e,n,s]);let b=s0(e,"read",n,d?{v:d}:void 0),j=null!=u?s2(u):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{title:e,children:N(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),j&&(0,r.jsx)("span",{children:j}),(0,r.jsxs)("span",{title:a(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"var(--success)":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"var(--success)":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px var(--success)":"none"}}),l?"live":"static"]}),(0,r.jsx)(s1,{filePath:e,sourceSessionId:n})]}),(0,r.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:g?(0,r.jsx)("div",{style:{color:"var(--danger)",fontSize:12},children:g}):(0,r.jsx)("img",{src:b,alt:e,onLoad:e=>{let t=e.currentTarget;m({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>f("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function s3(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}function s6({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:s=!0}){let{t:a}=(0,w.s)(),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),m(null),f(null),o(!1)},[e,n]),(0,i.useEffect)(()=>{if(o(!1),x.current&&(x.current.close(),x.current=null),!s)return;let t=!0,r=!1,i=new EventSource(s0(e,"watch",n));x.current=i,i.addEventListener("connected",()=>{var i;let s;o(!0),i=r,s=++v.current,fetch(s0(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&s===v.current){if(e.error)return void f(e.error);"number"==typeof e.size&&h(e.size),m(null),f(null),i&&c(e=>e+1)}}).catch(e=>{t&&s===v.current&&f(String(e))}),r=!0}),i.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),f(null),c(e=>e+1)});let a=()=>{o(!1)};return i.addEventListener("error",a),i.onerror=a,()=>{t=!1,i.close(),x.current===i&&(x.current=null)}},[e,n,s]);let b=s0(e,"read",n,d?{v:d}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{title:e,children:N(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"audio"}),null!=p&&(0,r.jsx)("span",{children:s3(p)}),null!=u&&(0,r.jsx)("span",{children:s2(u)}),(0,r.jsxs)("span",{title:a(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"var(--success)":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"var(--success)":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px var(--success)":"none"}}),l?"live":"static"]}),(0,r.jsx)(s1,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,r.jsx)("div",{style:{color:"var(--danger)",fontSize:12,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:b,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>f("Failed to load audio"),style:{width:"100%"}},b)]})})]})}function s5({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:s=!0}){let{t:a}=(0,w.s)(),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),m(null),f(null),o(!1)},[e,n]),(0,i.useEffect)(()=>{if(o(!1),x.current&&(x.current.close(),x.current=null),!s)return;let t=!0,r=!1,i=new EventSource(s0(e,"watch",n));x.current=i,i.addEventListener("connected",()=>{var i;let s;o(!0),i=r,s=++v.current,fetch(s0(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&s===v.current){if(e.error)return void f(e.error);"number"==typeof e.size&&h(e.size),m(null),f(null),i&&c(e=>e+1)}}).catch(e=>{t&&s===v.current&&f(String(e))}),r=!0}),i.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),f(null),c(e=>e+1)});let a=()=>{o(!1)};return i.addEventListener("error",a),i.onerror=a,()=>{t=!1,i.close(),x.current===i&&(x.current=null)}},[e,n,s]);let b=s0(e,"read",n,d?{v:d}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{title:e,children:N(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"video"}),null!=p&&(0,r.jsx)("span",{children:s3(p)}),null!=u&&(0,r.jsx)("span",{children:s2(u)}),(0,r.jsxs)("span",{title:a(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"var(--success)":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"var(--success)":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px var(--success)":"none"}}),l?"live":"static"]}),(0,r.jsx)(s1,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[g&&(0,r.jsx)("div",{style:{color:"var(--danger)",fontSize:12,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:b,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>f("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},b)]})})]})}function s7({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:s=!0,pdfPage:a}){let{t:l}=(0,w.s)(),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[h,p]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),f=(0,i.useRef)(null),x=(0,i.useRef)(0),v=s$(e),y="pdf"===v,b=y?s0(e,"read",n,c?{v:c}:void 0)+(a?`#page=${a}`:""):s0(e,"preview",n,c?{v:c}:void 0);return(0,i.useEffect)(()=>{u(0),p(null),g(null),d(!1);let t=!0,r=++x.current;return fetch(s0(e,"meta",n)).then(e=>e.json()).then(e=>{t&&r===x.current&&(e.error&&g(e.error),"number"==typeof e.size&&(p(e.size),!y&&e.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(e=>{t&&r===x.current&&g(String(e))}),()=>{t=!1}},[e,y,n]),(0,i.useEffect)(()=>{if(d(!1),f.current&&(f.current.close(),f.current=null),!s)return;let t=!0,r=!1,i=new EventSource(s0(e,"watch",n));f.current=i,i.addEventListener("connected",()=>{var i;let s;d(!0),i=r,s=++x.current,fetch(s0(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&s===x.current){if(e.error)return void g(e.error);if("number"==typeof e.size&&(p(e.size),!y&&e.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null),i&&u(e=>e+1)}}).catch(e=>{t&&s===x.current&&g(String(e))}),r=!0}),i.addEventListener("change",e=>{x.current+=1;try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(p(t.size),!y&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),u(e=>e+1)});let a=()=>{d(!1)};return i.addEventListener("error",a),i.onerror=a,()=>{t=!1,i.close(),f.current===i&&(f.current=null)}},[e,y,n,s]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:N(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===v?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:s2(h)}),(0,r.jsx)(s1,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:l(o?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:o?"var(--success)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:o?"var(--success)":"var(--border)",display:"inline-block",boxShadow:o?"0 0 4px var(--success)":"none"}}),o?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:m?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"var(--danger)",fontSize:12,textAlign:"center"},children:m}):(0,r.jsx)("iframe",{src:b,sandbox:y?void 0:"allow-same-origin",title:l("i18n.previewFile",{file:S(e)}),style:{width:"100%",height:"100%",border:"none",background:y?"var(--bg)":"#eef1f5"}},b)})]})}function s9({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:l,initialDisplayMode:o,initialState:d,onStateChange:c,watchEnabled:u=!0,pdfPage:h}){let p="diff"===sV(e,d,o);return!p&&sR(e)?(0,r.jsx)(s8,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&sW(e)?(0,r.jsx)(s6,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&sP(e)?(0,r.jsx)(s5,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&sz(e)?(0,r.jsx)(s7,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u,pdfPage:h}):(0,r.jsx)(ae,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:l,initialDisplayMode:o,initialState:d,onStateChange:c,watchEnabled:u})}function ae({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:s,onMentionLines:a,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d,initialState:c,onStateChange:u,watchEnabled:h=!0}){let{isDark:p,palette:m}=n3(),{t:g}=(0,w.s)(),[f,x]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[b,j]=(0,i.useState)(!1),[k,S]=(0,i.useState)(!1),[E,M]=(0,i.useState)(null),[I,L]=(0,i.useState)(!0),[T,$]=(0,i.useState)(!1),[R,W]=(0,i.useState)(null),P=sV(e,c,d),z="diff"===P&&(sR(e)||sW(e)||sP(e)||sz(e)),D=c?.wrapLines??!1,A=c?.scrollByMode?.[P],F=A?.scrollTop??c?.scrollTop??0,B=A?.scrollLeft??c?.scrollLeft??0,O=c?.loadedBytes??0,[H,U]=(0,i.useState)(P),[_,q]=(0,i.useState)(D),[K,V]=(0,i.useState)(!1),J=(0,i.useRef)(null),Y=(0,i.useRef)(0),Z=(0,i.useRef)(null),X=(0,i.useRef)(0),G=(0,i.useRef)(null),Q=(0,i.useRef)(!1),ee=(0,i.useRef)(0),et=(0,i.useRef)(null),en=(0,i.useRef)(!1),er=(0,i.useRef)(!0),ei=(0,i.useRef)({displayMode:P,wrapLines:D,scrollTop:F,scrollLeft:B,loadedBytes:O,scrollByMode:{...c?.scrollByMode}}),es=(0,i.useRef)(u),[ea,el]=(0,i.useState)(null);es.current=u;let eo=(0,i.useCallback)(e=>{ei.current.displayMode=e,U(e)},[]),ed=(0,i.useCallback)(()=>{q(e=>{let t=!e;return ei.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>()=>{es.current?.({...ei.current})},[]);let ec=(0,i.useCallback)(async(e,t=0)=>{let r=++Y.current,i=async t=>(await fetch(s0(e,"read",n,{offset:t||void 0}))).json();try{let e=t,n=await i(e);if(r!==Y.current||e&&"Invalid text preview offset"===n.error&&(e=0,n=await i(0),r!==Y.current))return null;if(n.error)return W(n.error),null;if(e&&(Z.current!==n.version||X.current!==e)){if(e=0,n=await i(0),r!==Y.current)return null;if(n.error)return W(n.error),null}return W(null),Z.current=n.version,X.current=n.nextOffset,ei.current.loadedBytes=n.nextOffset,x(t=>e&&t?{...n,content:t.content+n.content}:n),n}catch(e){if(r!==Y.current)return null;return W(String(e)),null}},[n]),eu=(0,i.useCallback)(async(e,t)=>{let n=await ec(e);for(;n?.truncated&&n.nextOffset<t;)n=await ec(e,n.nextOffset);return n},[ec]),eh=4194304*!!sD.has(s$(e)),ep=(0,i.useCallback)(async e=>{let n=++ee.current;if(j(!0),M(null),!t){y(null),j(!1),S(!0);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(n!==ee.current)return;i.ok||M(s.error??`Failed to load diff (HTTP ${i.status})`),y(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch(e){n===ee.current&&(y(null),M(e instanceof Error?e.message:String(e)))}finally{n===ee.current&&(j(!1),S(!0))}},[t]);(0,i.useEffect)(()=>{let t=!0;if(L(!0),W(null),x(null),y(null),S(!1),M(null),V(!1),Z.current=null,X.current=0,Q.current=!1,z)return L(!1),G.current=null,()=>{t=!1,Y.current+=1};let n=eu(e,Math.max(O,eh));return G.current=n,n.finally(()=>{G.current===n&&(G.current=null),t&&L(!1)}),()=>{t=!1,Y.current+=1}},[eh,e,eu,O,z,n]),(0,i.useEffect)(()=>{if(V(!1),J.current&&(J.current.close(),J.current=null),!h)return;let t=new EventSource(s0(e,"watch",n));J.current=t,t.addEventListener("connected",n=>{V(!0);let r=Q.current;if(Q.current=!0,r&&ep(e),z)return;let i=(()=>{try{return JSON.parse(n.data).version??null}catch{return null}})();(G.current??Promise.resolve()).then(()=>{J.current===t&&i!==Z.current&&(eu(e,Math.max(ei.current.loadedBytes??0,eh)),ep(e))})}),t.addEventListener("change",()=>{z||eu(e,Math.max(ei.current.loadedBytes??0,eh)),ep(e)});let r=()=>{V(!1)};return t.addEventListener("error",r),t.onerror=r,()=>{t.close(),J.current===t&&(J.current=null)}},[eh,e,ep,eu,z,n,h]),(0,i.useEffect)(()=>{ep(e)},[ep,e,o]);let em=v?.supported===!0&&"string"==typeof v.patch,eg=em&&"deleted"===v.status;(0,i.useEffect)(()=>{k&&!em&&"diff"===H&&eo("source")},[H,k,em,eo]),(0,i.useEffect)(()=>{"diff"===P&&em&&!en.current&&(en.current=!0,eo("diff"))},[P,em,eo]);let ef=(0,i.useMemo)(()=>f?.language==="markdown"?nI(f.content):"",[f]),ex=(0,i.useMemo)(()=>f?.language==="markdown"?function(e){let t=function(e){let t=sF.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,sA.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(f.content):null,[f]),ev=(0,i.useMemo)(()=>(function(e){let t=[],n=null;for(let r of e.split(/\r?\n/)){let e=sH.exec(r);if(e){let t=e[1][0],r=e[1].length;n?n.ch===t&&r>=n.n&&(n=null):n={ch:t,n:r};continue}if(n)continue;let i=sU.exec(r);if(!i)continue;let s=i[2].replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[*_`]/g,"").trim();s&&t.push({level:i[1].length,text:s})}return t})(ex?.rest??""),[ex]),ey=f?.content??"",eb=(0,i.useMemo)(()=>ey.split("\n"),[ey]),ew=f?.language??"text",ej="html"===ew,ek="markdown"===ew,eS=!f?.truncated&&(ej||ek),eC=eg?"diff":"preview"!==H||eS?H:"source",eN=(eb.length>1e3||(f?.size??0)>131072)&&!("diff"===eC&&em)&&!("preview"===eC&&eS),eE=!eN&&!("diff"===eC&&em)&&!("preview"===eC&&eS),eM=(0,i.useMemo)(()=>eE?(0,r.jsx)(rr.A,{className:_?"file-source-view is-wrapped":"file-source-view",language:"text"===ew?"plaintext":ew,style:"claude"===m?p?n9:n5:p?nF.xJ:nF.vs,showLineNumbers:!0,lineNumberStyle:{...sY},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...sJ,width:_?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:_?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(sQ,{...e,wrapLines:_}),wrapLongLines:_,children:ey}):null,[p,ew,m,eE,ey,_]),eI=(0,i.useMemo)(()=>eN?eb.map((e,t)=>(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:sY,children:t+1}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:_?"anywhere":"normal",whiteSpace:_?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[eb,eN,_]);(0,i.useEffect)(()=>{let e=()=>{let e=et.current;el(t=>{let n=a&&"source"===H&&e?sG(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),a&&"source"===H)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[f?.content,H,a]);let eL=(0,i.useCallback)(n=>{a&&n&&a(N(e,t),n.startLine,n.endLine,t)},[t,e,a]);if((0,i.useEffect)(()=>{if(!a||"source"!==H)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=et.current,r=n?sG(n,window.getSelection()):null;r&&(e.preventDefault(),eL(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[H,eL,a]),(0,i.useEffect)(()=>{if(!er.current||I||R&&!eg||"diff"===P&&!k||"diff"===P&&em&&"diff"!==H)return;let e=et.current;e&&(e.scrollTop=ei.current.scrollTop,e.scrollLeft=ei.current.scrollLeft,er.current=!1)},[f?.content,H,R,k,em,eg,I,P]),(0,i.useLayoutEffect)(()=>{if(er.current)return;let e=et.current;if(!e)return;let t=ei.current.scrollByMode?.[eC];e.scrollTop=t?.scrollTop??0,e.scrollLeft=t?.scrollLeft??0},[eC]),I||"diff"===P&&b&&!k)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:12},children:g("i18n.loading")});if("diff"===P&&k&&E)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"var(--danger)",fontSize:12,textAlign:"center"},children:E});if(R&&!("diff"===eC&&em))return(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",gap:8,color:"var(--danger)",fontSize:12},children:[R,"Binary file, preview not available"===R&&(0,r.jsx)(s1,{filePath:e,sourceSessionId:n})]});if(!f&&!("diff"===eC&&em))return null;let eT=C(e),e$=!f||eg?["diff"]:["source",...eS?["preview"]:[],...em?["diff"]:[]],eR=eg?g("files.deleted"):f?`${ew} \xb7 ${eb.length} lines \xb7 ${s2(f.size)}`:g("i18n.diff");return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",title:e,children:N(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eR,children:eR}),f&&!eg&&(0,r.jsx)("span",{title:K?g("i18n.liveSync"):g("i18n.notWatching"),"aria-label":K?g("i18n.liveSync"):g("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:K?"var(--success)":"var(--border)",boxShadow:K?"0 0 4px var(--success)":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[e$.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":g("i18n.fileViewMode"),children:e$.map(e=>{let t=eC===e;return(0,r.jsx)("button",{type:"button",onClick:()=>eo(e),title:"diff"===e?g("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:"source"===e?g("i18n.source"):"preview"===e?g("i18n.preview"):g("i18n.diff")},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[ek&&"preview"===eC&&(0,r.jsx)(sK,{items:ev,scrollRoot:et}),(l||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{ea&&a?eL(ea):l?.(N(e,t),!1,t)},title:ea&&a?`${g("i18n.mentionSelectedLines")} (L${ea.startLine}${ea.startLine!==ea.endLine?`-L${ea.endLine}`:""})`:g("files.insertPath"),"aria-label":g("files.mention"),disabled:!l&&!a,className:"file-viewer-icon-button",children:(0,r.jsx)(sZ,{})}),"source"===eC&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:ed,title:_?g("i18n.disableWrap"):g("i18n.enableWrap"),"aria-label":_?g("i18n.disableWrap"):g("i18n.enableWrap"),"aria-pressed":_,className:"file-viewer-icon-button",style:{background:_?"var(--bg-selected)":"transparent",color:_?"var(--text)":"var(--text-muted)"},children:(0,r.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,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!eg&&(0,r.jsx)(s1,{filePath:e,sourceSessionId:n})]})]}),f?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",children:[(0,r.jsxs)("span",{children:[s2(f.nextOffset)," / ",s2(f.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:T,onClick:()=>{$(!0),ec(e,f.nextOffset).finally(()=>$(!1))},children:T?g("i18n.loading"):g("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:et,className:"file-viewer-content",onScroll:e=>{let t={scrollTop:e.currentTarget.scrollTop,scrollLeft:e.currentTarget.scrollLeft};ei.current.scrollTop=t.scrollTop,ei.current.scrollLeft=t.scrollLeft,ei.current.scrollByMode={...ei.current.scrollByMode,[eC]:t}},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:f?.truncated?48:void 0},children:"diff"===eC&&em?(0,r.jsx)(s4,{patch:v.patch}):ej&&"preview"===eC?(0,r.jsx)("iframe",{srcDoc:ey,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:g("i18n.htmlPreview")}):ek&&"preview"===eC?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ex?.data&&(0,r.jsx)(sq,{data:ex.data}),(0,r.jsx)(nx.oz,{remarkPlugins:nz,rehypePlugins:nA,urlTransform:s?nE:void 0,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,r.jsx)(ri,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(ra,{code:s.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:["markdown-inline-code",e].filter(Boolean).join(" "),...n,children:t})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})}),pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){if(delete n.node,e?.startsWith("#"))return(0,r.jsx)("a",{href:e,...n,onClick:t=>{t.preventDefault();let n=decodeURIComponent(e.slice(1)),r=t.currentTarget.closest(".markdown-file-preview"),i=[...r?.querySelectorAll("h1, h2, h3, h4, h5, h6")??[]],s=r?.querySelector(`[id="user-content-${CSS.escape(n)}"]`)??i[function(e,t){let n=new Map;for(let r=0;r<e.length;r++){let i=e[r].trim().toLowerCase().replace(/[^\p{L}\p{M}\p{N}\p{Pc}\- ]/gu,"").replace(/ /g,"-"),s=n.get(i)??0;if(n.set(i,s+1),(s?`${i}-${s}`:i)===t)return r}return -1}(i.map(e=>e.textContent??""),n)];s?.scrollIntoView({block:"start",inline:"nearest"})},children:t});let i=s?ns(e,eT):null;return i&&s?(0,r.jsx)("a",{href:e,...n,onClick:t=>{nt(t)&&(t.preventDefault(),s(i,na(e)??void 0))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...i}){delete i.node;let s="string"==typeof e?ns(e,eT):null,a=s?s0(s,"read",n):e;return(0,r.jsx)("img",{src:a,alt:t??"",loading:"lazy",...i})}},children:ef})]}):eN?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:_?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...sJ},children:eI}):eM})]})}function at(e,t){if(t<=0)return"";let n=Math.max(0,e.length-1-t);return e.slice(n,-1).join("/")||e[0]||""}function an(e,t){return t?`${e} \xb7 ${t}`:e}function ar(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}function ai({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:s}){let{t:a}=(0,w.s)(),[l,o]=(0,i.useState)(null),d=(0,i.useRef)(null),c=(0,i.useRef)(!1),u=(0,i.useMemo)(()=>(function(e){let t=new Map,n=new Map;for(let t of e){let e=function(e){let t=e.label?.trim();return t||S(e.path)||e.path}(t),r=n.get(e);r?r.push(t):n.set(e,[t])}for(let[e,r]of n){if(1===r.length){t.set(r[0].id,e);continue}let n=r.map(e=>(function(e){let t=j(e).replace(/\/+$/,"");return t?/^[a-zA-Z]:$/.test(t)?[t]:t.split("/").filter((e,t)=>e.length>0||0===t):[]})(e.path)),i=n.map(e=>Math.max(0,e.length-1)),s=r.map(()=>0),a=!0;for(;a;){a=!1;let t=r.map((t,r)=>an(e,at(n[r],s[r]))),l=ar(t);for(let e=0;e<r.length;e+=1)!((l.get(t[e])??0)<=1)&&(s[e]>=i[e]||(s[e]+=1,a=!0))}let l=r.map((t,r)=>an(e,at(n[r],s[r]))),o=ar(l);r.forEach((n,r)=>{t.set(n.id,(o.get(l[r])??0)>1?e:l[r])})}return t})(e.map(e=>({id:e.id,path:e.filePath,label:e.label}))),[e]);return(0,i.useEffect)(()=>{d.current?.scrollIntoView({block:"nearest",inline:"nearest"}),c.current&&(c.current=!1,d.current?.focus())},[t,e]),(0,r.jsx)("div",{role:"tablist",style:{display:"flex",alignItems:"stretch",background:"var(--bg-panel)",boxShadow:"inset 0 -1px 0 var(--border)",overflowX:"auto",flexShrink:0,height:"100%"},children:e.map(i=>{let h=i.id===t,p=u.get(i.id)??i.label;return(0,r.jsxs)("div",{ref:h?d:null,role:"tab","aria-label":"terminal"===i.kind?a("terminal.tabLabel",{name:p}):p,"aria-selected":h,tabIndex:h||!t&&e[0].id===i.id?0:-1,onKeyDown:t=>{if(t.target===t.currentTarget){if("Enter"===t.key||" "===t.key)t.preventDefault(),n(i.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(t.key)){t.preventDefault();let r=e.findIndex(e=>e.id===i.id),s="Home"===t.key?0:"End"===t.key?e.length-1:(r+("ArrowRight"===t.key?1:-1)+e.length)%e.length;n(e[s].id),t.currentTarget.parentElement?.children[s]?.focus()}}},onClick:()=>n(i.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1===e.button&&(e.preventDefault(),e.stopPropagation(),i.closing||s(i.id))},style:{display:"flex",alignItems:"center",gap:6,height:"100%",paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:h?"var(--bg)":"var(--bg-panel)",boxShadow:h?"inset 0 2px 0 var(--accent)":"inset 0 -1px 0 var(--border)",cursor:"pointer",fontSize:12,color:h?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center"},children:"terminal"===i.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):A(i.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,lineHeight:1.3},title:i.filePath,children:p}),(0,r.jsx)("button",{type:"button",className:"file-tab-close",disabled:i.closing,onClick:e=>{e.stopPropagation(),o(null),c.current=!0,s(i.id)},onMouseEnter:()=>o(i.id),onMouseLeave:()=>o(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,background:l===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:l===i.id?"var(--text)":"var(--text-muted)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:a("terminal"===i.kind?"terminal.close":"i18n.close"),"aria-label":`${a("terminal"===i.kind?"terminal.close":"i18n.close")} ${p}`,children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},i.id)})})}function as(e,t){let n=e.findIndex(e=>e.id===t);if(-1===n)return null;let r=e.filter(e=>e.id!==t);return r[Math.min(n,r.length-1)]?.id??null}let aa=["sarasa","claude"],al="pi-font-scheme",ao=new Set;function ad(){try{let e=localStorage.getItem(al);return aa.includes(e)?e:"sarasa"}catch{return"sarasa"}}function ac(e){let t=document.documentElement;"sarasa"===e?delete t.dataset.font:t.dataset.font=e;try{localStorage.setItem(al,e)}catch{}ao.forEach(e=>e())}function au(e){return ao.add(e),()=>{ao.delete(e)}}let ah=new Map,ap=new Map;function am(e){return ah.get(e)}function ag(e){let t=ap.get(e);return t||(t=fetch(e,{cache:"no-store"}).then(async t=>{let n={ok:t.ok,status:t.status,data:await t.json()};return ah.set(e,n),n}).finally(()=>ap.delete(e)),ap.set(e,t)),t}let af=e=>`cwd=${encodeURIComponent(e)}`,ax="/api/web-auth",av="/api/tools/settings",ay="/api/models-config",ab=e=>`/api/auth/providers${e?`?${af(e)}`:""}`,aw=e=>`/api/models-config/runtime?${af(e)}`,aj=e=>`/api/models-config/picker?${af(e)}`,ak=e=>`/api/subagents/profiles?${af(e)}`,aS="/api/subagents/settings",aC=e=>`/api/models?${af(e)}`,aN="/api/image-generation/settings",aE=e=>`/api/skills?${af(e)}`,aM=e=>`/api/plugins?${af(e)}`,aI="/api/usage";function aL(e){for(let t of e?[ay,ab(e),aw(e),aj(e),ax,av,aS,ak(e),aC(e),aN,aE(e),aM(e),aI]:[ay,ab(e),ax,av,aS,aN,aI])ah.has(t)||ag(t).catch(()=>{})}function aT(){for(let e of ah.keys())ag(e).catch(()=>{})}let a$=["general","models","agents","images","skills","plugins","usage"],aR="pi-web:settings-navigation",aW=new Set(["skills","agents","plugins"]);function aP(){try{return window.localStorage}catch{return null}}function az(e){let t=e.getItem(aR);if(!t)return{};try{let e=JSON.parse(t);if(null===e||"object"!=typeof e||Array.isArray(e))return{};return{section:"string"==typeof e.section?e.section:void 0,selections:null===e.selections||"object"!=typeof e.selections||Array.isArray(e.selections)?void 0:e.selections}}catch{return{}}}function aD(e,t=aP()){if(t)try{let n=az(t);n.section=e,t.setItem(aR,JSON.stringify(n))}catch{}}let aA="pi-auto-session-title";function aF(){try{return"false"!==window.localStorage.getItem(aA)}catch{return!0}}let aB=["input","output","cacheRead","cacheWrite"];function aO(e){return{input:e?.input===void 0?"":String(e.input),output:e?.output===void 0?"":String(e.output),cacheRead:e?.cacheRead===void 0?"":String(e.cacheRead),cacheWrite:e?.cacheWrite===void 0?"":String(e.cacheWrite)}}function aH(e){if(!aU(e))return;let t=e=>{if(!e.trim())return 0;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0},n=t(e.input),r=t(e.output),i=t(e.cacheRead),s=t(e.cacheWrite);if(void 0!==n&&void 0!==r&&void 0!==i&&void 0!==s)return{input:n,output:r,cacheRead:i,cacheWrite:s}}function aU(e){return aB.some(t=>""!==e[t].trim())}let a_=["name","reasoning","thinkingLevelMap","input","contextWindow","maxTokens","cost","headers","compat"];function aq(e,t){return`${e}/${t}`}function aK(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function aV(e,t){let n=aK(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function aJ(e){let t=e.trim(),n=t.match(eI),r=n?t.slice(0,-n[0].length):t,i=n?.[1];if(!r||/[*?\[]/.test(r))return null;let s=r.indexOf("/");return s===r.length-1?null:s<=0?{id:r,...i?{pin:i}:{},ref:r}:{provider:r.slice(0,s),id:r.slice(s+1),...i?{pin:i}:{},ref:r}}function aY(e,t){let n=t.trim();return aK(e).filter(e=>e!==n)}function aZ(e){let t=aK(e);return t.length>0&&t.every(e=>null!==aJ(e))}let aX={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function aG({id:e,size:t}){let n=aX[e];if(n)return(0,r.jsx)("svg",{"aria-hidden":"true",width:t,height:t,viewBox:"0 0 24 24",fill:n.color?void 0:"currentColor",style:{flexShrink:0},children:(0,r.jsx)("use",{href:`/provider-icons.svg#${n.symbol}`})});let i=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*t)),fontWeight:600,lineHeight:1},children:i})}function aQ({value:e,onChange:t,placeholder:n,mono:i,disabled:s,id:a}){return(0,r.jsx)("input",{id:a,className:`models-input${i?" is-mono":""}`,value:e,onChange:e=>t(e.target.value),placeholder:n,disabled:s})}function a0({value:e,onChange:t,placeholder:n,mono:s,onKeyDown:a}){let[l,o]=(0,i.useState)(!1),{t:d}=(0,w.s)();return(0,i.useEffect)(()=>{e||o(!1)},[e]),(0,r.jsxs)("div",{className:"models-secret",children:[(0,r.jsx)("input",{type:l?"text":"password",className:`models-input${s?" is-mono":""}`,value:e,onChange:e=>t(e.target.value),onKeyDown:a,placeholder:n,autoComplete:"off",spellCheck:!1}),(0,r.jsx)("button",{type:"button",className:"models-secret-toggle",onClick:()=>o(e=>!e),"aria-label":d(l?"i18n.hideDetails":"i18n.showDetails"),title:d(l?"i18n.hideDetails":"i18n.showDetails"),children:l?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.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,r.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,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function a1({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",className:"models-input",value:e,onChange:e=>t(e.target.value),placeholder:n})}function a2({value:e,onChange:t,options:n,required:i}){let{t:s}=(0,w.s)();return(0,r.jsxs)("select",{className:"models-input",value:e,onChange:e=>t(e.target.value),children:[!i&&(0,r.jsx)("option",{value:"",children:s("models.useDefault")}),n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function a4({label:e,description:t,checked:n,onChange:i}){return(0,r.jsx)(iG,{label:e,description:t,children:(0,r.jsx)(i7,{checked:n,label:e,onChange:i})})}function a8({title:e,hint:t,actions:n}){return(0,r.jsxs)("div",{className:"models-section-header",children:[(0,r.jsxs)("div",{className:"models-section-heading",children:[(0,r.jsx)("h3",{className:"settings-group-title",children:e}),t&&(0,r.jsx)("p",{className:"settings-row-description",children:t})]}),n&&(0,r.jsx)("span",{className:"models-form-actions",children:n})]})}function a3({children:e}){return(0,r.jsx)("span",{className:"models-hint",children:e})}function a6({tone:e="info",children:t,action:n}){return(0,r.jsxs)("div",{className:`models-notice is-${e}`,role:"danger"===e?"alert":"status",children:[(0,r.jsx)("div",{className:"models-notice-body",children:t}),n]})}function a5({headers:e,onChange:t}){let{t:n}=(0,w.s)(),[s,a]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),l=(0,i.useRef)(s.length),o=e=>{a(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},d=(e,t)=>{o(s.map(n=>n.id===e?{...n,...t}:n))};return(0,r.jsxs)("div",{className:"models-header-list",children:[s.map(e=>(0,r.jsxs)("div",{className:"models-header-row",children:[(0,r.jsx)("input",{className:"models-input is-mono",value:e.name,onChange:t=>d(e.id,{name:t.target.value}),placeholder:"Header-Name"}),(0,r.jsx)("input",{className:"models-input is-mono",value:e.value,onChange:t=>d(e.id,{value:t.target.value}),placeholder:"value"}),(0,r.jsx)("button",{type:"button",className:"models-icon-button is-danger",onClick:()=>{var t;return t=e.id,void o(s.filter(e=>e.id!==t))},"aria-label":n("i18n.remove"),title:n("i18n.remove"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.id)),(0,r.jsx)(i5,{size:"small",className:"models-self-start",onClick:()=>a(e=>[...e,{id:l.current++,name:"",value:""}]),children:n("models.addHeader")})]})}function a7({value:e,onChange:t}){let{t:n}=(0,w.s)(),i=e??{},s=(e,n)=>{let r={...i};"omit"===n?delete r[e]:r[e]=n,t(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{className:"models-thinking-map",children:eM.map(e=>{let t=i[e],a=e in i?null===t?"null":"string":"omit",l="string"==typeof t?t:"";return(0,r.jsxs)("div",{className:`models-thinking-row is-${a}`,children:[(0,r.jsx)("span",{className:"models-thinking-level",children:e}),(0,r.jsxs)("div",{className:"models-segmented",role:"radiogroup","aria-label":e,children:[(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"omit"===a,onClick:()=>s(e,"omit"),children:n("models.levelDefault")}),(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"null"===a,className:"is-danger",onClick:()=>s(e,null),children:n("models.levelDisabled")}),(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"string"===a,onClick:()=>s(e,l||e),children:n("models.levelCustom")})]}),(0,r.jsx)("input",{className:"models-input is-mono models-thinking-input",value:l,onChange:t=>s(e,t.target.value),onFocus:()=>{"string"!==a&&s(e,l||e)},placeholder:e,maxLength:10,"aria-label":`${e} ${n("models.levelCustom")}`})]},e)})})}function a9({title:e,description:t,width:n=560,onClose:i,children:s,footer:a,header:l}){return(0,r.jsx)("div",{className:"models-dialog-backdrop",onClick:e=>{e.target===e.currentTarget&&i()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),i())},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":e,className:"models-dialog",style:{width:n},children:[l??(0,r.jsxs)("div",{className:"models-dialog-header",children:[(0,r.jsx)("strong",{children:e}),t&&(0,r.jsx)("span",{children:t})]}),(0,r.jsx)("div",{className:"models-dialog-body",children:s}),a&&(0,r.jsx)("div",{className:"models-dialog-footer",children:a})]})})}function le(e,t){return window.confirm(e("models.disconnectConfirm",{name:t}))}function lt({tone:e,children:t}){return(0,r.jsxs)("span",{className:`models-status is-${e}`,children:[(0,r.jsx)("span",{className:"models-status-dot","aria-hidden":"true"}),t]})}function ln({provider:e,onRefresh:t,cwd:n}){let[s,a]=(0,i.useState)({phase:"idle"}),{t:l}=(0,w.s)(),[o,d]=(0,i.useState)(""),c=(0,i.useRef)(null),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>u.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{a({phase:"idle"}),d(""),c.current?.close(),c.current=null},[e.id]),(0,i.useEffect)(()=>()=>{c.current?.close()},[]);let h=(0,i.useCallback)(()=>{c.current?.close(),a({phase:"connecting"}),d("");let r=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}${n?`?cwd=${encodeURIComponent(n)}`:""}`);c.current=r,r.onmessage=e=>{let n=JSON.parse(e.data);"auth"===n.type?(a({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),window.open(n.url,"_blank","noopener,noreferrer")):"device_code"===n.type?(a({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?a({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?a({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?a({phase:"progress",message:n.message}):"success"===n.type?(r.close(),a({phase:"success"}),t()):"error"===n.type?(r.close(),a({phase:"error",message:n.message})):"cancelled"===n.type&&(r.close(),a({phase:"idle"}))},r.onerror=()=>{r.close(),a(e=>"success"===e.phase?e:{phase:"error",message:l("models.loginConnectionLost")})}},[e.id,t,n,l]),p=(0,i.useCallback)(async()=>{le(l,e.name)&&(await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n})}),a({phase:"idle"}),t())},[e.id,e.name,t,l,n]),m=(0,i.useCallback)(async(t,n,r)=>{a({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));a({phase:"error",message:e.error??`HTTP ${r.status}`});return}d("")}catch(e){a({phase:"error",message:e instanceof Error?e.message:String(e)})}},[e.id]),g=(e,t)=>{t.trim()&&m(e,t.trim(),l("models.loginVerifying"))},f="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{className:"models-auth",children:[(0,r.jsxs)("div",{className:"models-auth-row",children:[(0,r.jsxs)("div",{className:"models-auth-copy",children:[(0,r.jsx)("strong",{children:l("models.oauthTitle")}),(0,r.jsx)(lt,{tone:e.loggedIn?"success":"muted",children:e.loggedIn?l("i18n.connected"):l("i18n.notConnected")})]}),(0,r.jsx)("div",{className:"models-auth-actions",children:f?(0,r.jsx)(i5,{size:"small",onClick:()=>{c.current?.close(),a({phase:"idle"})},children:l("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[e.loggedIn&&(0,r.jsx)(i5,{size:"small",variant:"ghost",className:"models-danger-ghost",onClick:p,children:l("i18n.disconnect")}),(0,r.jsx)(i5,{size:"small",variant:e.loggedIn?"secondary":"primary",onClick:h,children:e.loggedIn?l("i18n.relogin"):l("i18n.login")})]})})]}),"idle"===s.phase&&!e.loggedIn&&(0,r.jsx)("p",{className:"models-muted",children:l("models.oauthConnectHint",{name:e.name})}),"connecting"===s.phase&&(0,r.jsx)("p",{className:"models-muted",children:l("i18n.openingBrowser")}),"select"===s.phase&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:s.message}),(0,r.jsx)("div",{className:"models-auth-options",children:s.options.map(e=>(0,r.jsx)(i5,{className:"models-auth-option",onClick:()=>void m(s.token,e.id,l("models.loginContinuing")),children:e.label},e.id))})]}),("auth"===s.phase||"prompt"===s.phase)&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:"auth"===s.phase?l("models.oauthPasteRedirect"):s.message}),"auth"===s.phase&&(0,r.jsxs)("p",{className:"models-hint",children:[l("models.oauthBrowserNotOpened")," ",(0,r.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"models-link",children:l("models.oauthOpenLoginPage")})]}),(0,r.jsxs)("div",{className:"models-inline-form",children:[(0,r.jsx)("input",{ref:u,className:"models-input is-mono",value:o,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&g(s.token,o)},placeholder:"auth"===s.phase?"http://localhost:1455/auth/callback?code=…":s.placeholder??l("models.enterValue")}),(0,r.jsx)(i5,{variant:"primary",size:"small",onClick:()=>g(s.token,o),disabled:!o.trim(),children:l("i18n.submit")})]})]}),"device_code"===s.phase&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:l("models.deviceCodeHint")}),(0,r.jsx)("div",{className:"models-device-code",children:s.userCode}),(0,r.jsxs)("p",{className:"models-hint",children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",className:"models-link",children:s.verificationUri}),s.expiresInSeconds?` \xb7 ${l("models.deviceCodeExpires",{minutes:Math.ceil(s.expiresInSeconds/60)})}`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{className:"models-muted",children:s.message}),"success"===s.phase&&(0,r.jsx)(a6,{tone:"success",children:l("i18n.connectedSuccessfully")}),"error"===s.phase&&(0,r.jsx)(a6,{tone:"danger",children:s.message})]})}function lr({provider:e,onRefresh:t,cwd:n}){let[s,a]=(0,i.useState)(""),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(!1),{t:g}=(0,w.s)();(0,i.useEffect)(()=>{a(""),h(null),m(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(s.trim()){o(!0),h(null),m(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:s.trim(),cwd:n})}),i=await r.json();!r.ok||i.error?h(i.error??`HTTP ${r.status}`):(a(""),m(!0),setTimeout(()=>m(!1),2e3),t())}catch(e){h(String(e))}finally{o(!1)}}},[s,e.id,t,n]),x=(0,i.useCallback)(async()=>{if(le(g,e.displayName)){c(!0),h(null);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n})}),i=await r.json();!r.ok||i.error?h(i.error??`HTTP ${r.status}`):t()}catch(e){h(String(e))}finally{c(!1)}}},[e.id,e.displayName,t,g,n]);return(0,r.jsxs)("div",{className:"models-auth",children:[(0,r.jsxs)("div",{className:"models-auth-row",children:[(0,r.jsxs)("div",{className:"models-auth-copy",children:[(0,r.jsx)("strong",{children:g("models.apiKeyTitle")}),(0,r.jsx)(lt,{tone:e.configured?"success":"muted",children:e.configured?g("i18n.configured"):g("i18n.notConfigured")})]}),e.configured&&(0,r.jsx)("div",{className:"models-auth-actions",children:(0,r.jsx)(i5,{size:"small",variant:"ghost",className:"models-danger-ghost",onClick:x,disabled:d,children:d?g("i18n.removing"):g("i18n.disconnect")})})]}),(0,r.jsxs)("div",{className:"models-inline-form",children:[(0,r.jsx)(a0,{value:s,onChange:a,onKeyDown:e=>{"Enter"===e.key&&s.trim()&&f()},placeholder:e.configured?g("models.replaceKeyPlaceholder"):"sk-…",mono:!0}),(0,r.jsx)(i5,{variant:"primary",size:"small",onClick:f,disabled:l||!s.trim()||p,className:p?"is-success":void 0,children:p?g("i18n.saved"):l?g("i18n.saving"):e.configured?g("models.updateKey"):g("models.saveKey")})]}),u&&(0,r.jsx)(a6,{tone:"danger",children:u})]})}let li=/^[a-z0-9][a-z0-9._-]*$/;function ls(){let e=(0,i.useRef)(null);return(0,i.useEffect)(()=>{setTimeout(()=>e.current?.focus(),30)},[]),e}function la({oauthProviders:e,apiKeyProviders:t,existingIds:n,onSelectOAuth:s,onSelectApiKey:a,onAddCustom:l,onClose:o}){let[d,c]=(0,i.useState)(""),[u,h]=(0,i.useState)(!1),[p,m]=(0,i.useState)(""),{t:g}=(0,w.s)(),f=ls(),x=d.trim().toLowerCase(),v=e.filter(e=>!e.loggedIn&&(!x||e.name.toLowerCase().includes(x))),y=t.filter(e=>!e.configured&&(!x||e.displayName.toLowerCase().includes(x)||e.id.toLowerCase().includes(x))),b=!x||"custom".includes(x)||"openai-compatible".includes(x)||"anthropic-compatible".includes(x),j=v.length+y.length+ +!!b,k=p.trim(),S=li.test(k)&&!n.has(k),C=(e,t,n,i,s)=>(0,r.jsxs)("button",{type:"button",className:"models-card",onClick:s,children:[(0,r.jsxs)("span",{className:"models-card-copy",children:[(0,r.jsx)("strong",{children:t}),(0,r.jsx)("span",{children:n})]}),i]},e);return(0,r.jsx)(a9,{title:g("models.addProviderTitle"),width:820,onClose:o,header:(0,r.jsxs)("div",{className:"models-dialog-search",children:[(0,r.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,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:f,value:d,onChange:e=>c(e.target.value),placeholder:g("i18n.searchProviders"),"aria-label":g("i18n.searchProviders")})]}),children:0===j?(0,r.jsx)("p",{className:"models-empty",children:g("i18n.noProviders")}):(0,r.jsxs)("div",{className:"models-card-grid",children:[b&&(0,r.jsx)("div",{className:"models-card-group",children:g("i18n.custom")}),b&&!u&&C("custom",g("models.customCompatible"),g("i18n.customEndpoint"),(0,r.jsx)("span",{className:"models-card-plus","aria-hidden":"true",children:"+"}),()=>h(!0)),b&&u&&(0,r.jsxs)("form",{className:"models-custom-form",onSubmit:e=>{e.preventDefault(),S&&(l(k),o())},children:[(0,r.jsx)("label",{htmlFor:"custom-provider-id",className:"config-field-label",children:g("models.providerId")}),(0,r.jsx)("input",{id:"custom-provider-id",autoFocus:!0,className:"models-input is-mono",value:p,onChange:e=>m(e.target.value),placeholder:"my-provider","aria-describedby":"custom-provider-id-hint"}),(0,r.jsx)("span",{id:"custom-provider-id-hint",children:(0,r.jsx)(a3,{children:n.has(k)?g("models.providerIdTaken"):g("models.providerIdFormat")})}),(0,r.jsxs)("div",{className:"models-form-actions",children:[(0,r.jsx)(i5,{size:"small",onClick:()=>h(!1),children:g("i18n.cancel")}),(0,r.jsx)(i5,{size:"small",type:"submit",variant:"primary",disabled:!S,children:g("models.createProvider")})]})]}),v.length>0&&(0,r.jsx)("div",{className:"models-card-group",children:g("i18n.subscriptions")}),v.map(e=>C(e.id,e.name,g("models.kindOAuth"),(0,r.jsx)(aG,{id:e.id,size:28}),()=>{s(e.id),o()})),y.length>0&&(0,r.jsx)("div",{className:"models-card-group",children:g("models.kindApiKey")}),y.map(e=>C(e.id,e.displayName,g("models.modelCount",{count:e.modelCount}),(0,r.jsx)(aG,{id:e.id,size:28}),()=>{a(e.id),o()}))]})})}function ll({catalog:e,listedRefs:t,mode:n,providerLabel:s,saving:a,error:l,onClose:o,onApply:d}){let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(""),[p,m]=(0,i.useState)(new Set),g=ls(),f=u.trim().toLocaleLowerCase(),x=e.filter(e=>!f||e.id.toLocaleLowerCase().includes(f)||e.name?.toLocaleLowerCase().includes(f)),v=e=>t.has(aq(e.provider,e.id)),y=new Map;for(let e of x){let t=y.get(e.provider)??[];t.push(e),y.set(e.provider,t)}return(0,r.jsxs)(a9,{title:c("models.pickModels"),description:"replace"===n?c("models.pickReplaceHint"):c("models.pickAddHint"),onClose:o,footer:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"models-hint",children:c("models.pickSelected",{count:p.size})}),(0,r.jsxs)("span",{className:"models-form-actions",children:[(0,r.jsx)(i5,{onClick:o,children:c("i18n.cancel")}),(0,r.jsx)(i5,{variant:"primary",disabled:0===p.size||a,onClick:()=>d([...p]),children:c("models.pickApply",{count:p.size})})]})]}),children:[(0,r.jsx)("input",{ref:g,className:"models-input",value:u,onChange:e=>h(e.target.value),placeholder:c("models.pickFilterPlaceholder"),"aria-label":c("models.pickFilter")}),!x.some(e=>!v(e))&&(0,r.jsx)("p",{className:"models-empty",children:c("models.noExtraModels")}),[...y.entries()].map(([e,t])=>{let n=t.filter(e=>!v(e)).map(e=>aq(e.provider,e.id)),i=n.length>0&&n.every(e=>p.has(e));return(0,r.jsxs)("section",{className:"models-picker-group",children:[(0,r.jsxs)("label",{className:"models-picker-head",children:[(0,r.jsx)("input",{type:"checkbox",checked:i,disabled:0===n.length,onChange:()=>m(e=>{let t=new Set(e);for(let e of n)i?t.delete(e):t.add(e);return t})}),(0,r.jsx)(aG,{id:e,size:12}),(0,r.jsx)("span",{children:s(e)}),(0,r.jsx)("span",{className:"models-count",children:t.length})]}),t.map(e=>{let t=aq(e.provider,e.id),n=v(e);return(0,r.jsxs)("label",{className:`models-row${n?" is-disabled":""}`,children:[(0,r.jsx)("input",{type:"checkbox",checked:n||p.has(t),disabled:n,onChange:()=>m(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})}),(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsx)("span",{className:"models-row-title",children:e.name||e.id}),e.name&&e.name!==e.id&&(0,r.jsx)("code",{className:"models-row-sub",children:e.id})]}),n&&(0,r.jsx)("span",{className:"models-tag",children:c("models.alreadyInChat")})]},t)})]},e)}),l&&(0,r.jsx)(a6,{tone:"danger",children:l})]})}let lo=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function ld(e){return{id:e.id,name:e.name,api:e.api,reasoning:e.reasoning,thinkingLevelMap:e.thinkingLevelMap,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens,cost:e.cost,headers:e.headers,compat:e.compat}}function lc({providerId:e,provider:t,builtIn:n,namePlaceholder:i,onChange:s}){let{t:a}=(0,w.s)(),l=(e,n)=>s({...t,[e]:n});return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsxs)(iV,{label:a("models.displayName"),children:[(0,r.jsx)(aQ,{value:t.name??"",onChange:e=>l("name",e.trim()||void 0),placeholder:i}),(0,r.jsx)(a3,{children:a("models.providerIdHint",{id:e})})]}),(0,r.jsx)(iV,{label:a("models.apiProtocol"),children:n?(0,r.jsx)(a2,{value:t.api??"",onChange:e=>l("api",e||void 0),options:lo}):(0,r.jsx)(a2,{value:t.api??"openai-completions",onChange:e=>l("api",e),options:lo,required:!0})})]}),(0,r.jsx)(iV,{label:a("models.baseUrl"),children:(0,r.jsx)(aQ,{value:t.baseUrl??"",onChange:e=>l("baseUrl",e||void 0),placeholder:n?a("models.builtInDefault"):"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(iV,{label:a("models.apiKeyTitle"),children:[(0,r.jsx)(a0,{value:t.apiKey??"",onChange:e=>l("apiKey",e||void 0),placeholder:a(n?"models.builtInKeyPlaceholder":"models.endpointKeyPlaceholder"),mono:!0}),(0,r.jsx)(a3,{children:a("models.endpointKeyHint")})]}),(0,r.jsxs)(iV,{label:a("models.headers"),children:[(0,r.jsx)(a5,{headers:t.headers,onChange:e=>l("headers",e)}),(0,r.jsx)(a3,{children:a("models.providerHeadersHelp")})]})]})}function lu({providerId:e,provider:t,onAddModels:n,onClose:s}){let{t:a}=(0,w.s)(),[l,o]=(0,i.useState)({phase:"idle"}),[d,c]=(0,i.useState)(""),[u,h]=(0,i.useState)([]),p=(0,i.useRef)(0),m=(0,i.useRef)(null),g=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim())return;let n=++p.current;o({phase:"loading"}),h([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await r.json();if(n!==p.current)return;if(!r.ok||i.error||!i.models)return void o({phase:"error",message:i.error??`HTTP ${r.status}`});o({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==p.current)return;o({phase:"error",message:e instanceof Error?e.message:String(e)})}},[e,t]);(0,i.useEffect)(()=>{g()},[e,t.baseUrl,t.api,t.apiKey]);let f=new Set((t.models??[]).map(e=>e.id)),x="success"===l.phase?l.models:[],v=d.trim().toLocaleLowerCase(),y=x.filter(e=>!v||e.id.toLocaleLowerCase().includes(v)||e.name?.toLocaleLowerCase().includes(v)),b=y.slice(0,300),j=b.filter(e=>!f.has(e.id)).map(e=>e.id),k=u.filter(e=>!f.has(e)).length,S=j.length>0&&j.every(e=>u.includes(e)),C=!S&&j.some(e=>u.includes(e));return(0,i.useEffect)(()=>{m.current&&(m.current.indeterminate=C)},[C]),(0,r.jsxs)("div",{className:"models-discovery",children:[(0,r.jsxs)("div",{className:"models-discovery-header",children:[(0,r.jsx)("strong",{children:a("models.discoveryTitle")}),(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:s,children:a("i18n.close")})]}),"loading"===l.phase&&(0,r.jsx)("p",{className:"models-muted",children:a("models.discoveryFetching")}),"error"===l.phase&&(0,r.jsx)(a6,{tone:"danger",action:(0,r.jsx)(i5,{size:"small",onClick:()=>void g(),children:a("models.retry")}),children:l.message}),"success"===l.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"models-input",value:d,onChange:e=>c(e.target.value),placeholder:a("models.discoveryFilterPlaceholder",{count:l.models.length}),"aria-label":a("models.discoveryFilter")}),(0,r.jsxs)("div",{className:"models-list models-discovery-list",children:[(0,r.jsxs)("label",{className:"models-row models-discovery-all",children:[(0,r.jsx)("input",{ref:m,type:"checkbox",checked:S,disabled:0===j.length,onChange:()=>{let e=new Set(j);h(t=>S?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...j])))}}),a("models.discoverySelectShown")]}),0===b.length?(0,r.jsx)("div",{className:"models-row models-muted",children:a("models.discoveryNoMatches")}):b.map(e=>{let t=f.has(e.id);return(0,r.jsxs)("label",{className:`models-row${t?" is-disabled":""}`,children:[(0,r.jsx)("input",{type:"checkbox",checked:u.includes(e.id)||t,disabled:t,onChange:()=>{var t;return t=e.id,void h(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])}}),(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsx)("span",{className:"models-row-title",children:e.name??e.id}),e.name&&(0,r.jsx)("code",{className:"models-row-sub",children:e.id})]}),t&&(0,r.jsx)("span",{className:"models-tag",children:a("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{className:"models-discovery-footer",children:[(0,r.jsx)("span",{className:"models-hint",title:l.endpoint,children:y.length>b.length?a("models.discoveryShowing",{shown:b.length,total:y.length}):a("models.discoveryFetched",{count:l.models.length})}),(0,r.jsx)(i5,{size:"small",variant:"primary",onClick:()=>{if("success"!==l.phase)return;let e=new Set(u),t=l.models.filter(t=>e.has(t.id)&&!f.has(t.id));0!==t.length&&(n(t),h([]))},disabled:0===k,children:k?a("models.discoveryAddSelectedCount",{count:k}):a("models.discoveryAddSelected")})]})]})]})}let lh={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lp(e){return e.compat?.thinkingFormat==="deepseek"}function lm({providerName:e,provider:t,model:n,onChange:s,onDelete:a,lockId:l=!1,cwd:o=null,shadowsBuiltIn:d=!1}){let[c,u]=(0,i.useState)({phase:"idle"}),{t:h}=(0,w.s)(),[p,m]=(0,i.useState)({phase:"idle"}),[g,f]=(0,i.useState)(!1),[x,v]=(0,i.useState)(()=>aO(n.cost)),y=(0,i.useRef)(x),[b,j]=(0,i.useState)(!1),k=(0,i.useRef)(0),S=(0,i.useRef)(null),C=(0,i.useRef)(n.cost),N=(e,t)=>s({...n,[e]:t}),E=(()=>{if("idle"===c.phase||"testing"===c.phase)return null;let e=[void 0!==c.latencyMs?`${c.latencyMs}ms`:null,void 0!==c.status?`HTTP ${c.status}`:null].filter(Boolean);return"success"===c.phase?[h("i18n.connected"),...e,c.responseText||null].filter(Boolean).join(" \xb7 "):[h("i18n.failed"),...e,c.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{u({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{k.current+=1,m({phase:"idle"}),S.current=null},[e,t.baseUrl,n.id]);let M=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==c.phase){u({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n,cwd:o??void 0})}),i=await r.json();if(!r.ok||!i.ok)return void u({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});u({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){u({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,c.phase,o]),I=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===p.phase)return;let i=++k.current;m({phase:"loading"});try{let a=new URLSearchParams({q:r,provider:e,limit:"50"});o&&a.set("cwd",o),t.baseUrl?.trim()&&a.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${a}`),d=await l.json();if(i!==k.current)return;if(!l.ok||d.error||!d.recommendation)return void m({phase:"error",message:d.error??`HTTP ${l.status}`});let c=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let a=aH(aO(i));s>0&&a&&(n.cost={...i,...a},r+=s)}return{model:n,appliedCount:r}}(n,d.recommendation.preset);c.appliedCount>0&&(S.current=n,s(c.model)),f(!1),m({phase:"success",recommendation:d.recommendation,appliedCount:c.appliedCount})}catch(e){if(i!==k.current)return;m({phase:"error",message:e instanceof Error?e.message:String(e)})}},[p.phase,n,s,t.baseUrl,e,o]),L=(()=>{if("success"!==p.phase)return null;let{recommendation:t,appliedCount:n}=p,r=n>0?h("models.catalogFilled",{count:n}):h("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?h("models.catalogNoExactMatch"):h("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?h("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?h("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):h("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),T="error"===p.phase?p.message:L,$="error"===p.phase?"danger":"success"===p.phase&&"unreliable"===p.recommendation.price.status?"warning":"info",R=[{key:"input",label:h("models.costInput")},{key:"output",label:h("models.costOutput")},{key:"cacheRead",label:h("models.costCacheRead")},{key:"cacheWrite",label:h("models.costCacheWrite")}],W=new Set(Object.keys(n.compat??{})),P=0;lp(n)&&(P+=1,W.delete("thinkingFormat"),W.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(n.compat??{},"supportsDeveloperRole")&&(P+=1,W.delete("supportsDeveloperRole")),P+=W.size;let z=[n.api?`API: ${n.api}`:null,Object.keys(n.headers??{}).length?h("models.headersSummary",{count:Object.keys(n.headers??{}).length}):null,P?h("models.compatSummary",{count:P}):null,Object.keys(n.thinkingLevelMap??{}).length?h("models.thinkingSummary",{count:Object.keys(n.thinkingLevelMap??{}).length}):null].filter(e=>!!e),D=z.length?z.join(" \xb7 "):h("models.providerDefaults");return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)("header",{className:"settings-detail-header",children:[(0,r.jsx)("h2",{className:"settings-detail-title",children:n.name||n.id||h("models.untitledModel")}),(0,r.jsx)("div",{className:"settings-detail-meta",children:(0,r.jsx)("span",{className:"config-scope-tag",children:l?h("models.kindOverride"):h("models.kindDefinition")})})]}),d&&a&&(0,r.jsx)(a6,{tone:"warning",action:(0,r.jsx)(i5,{size:"small",onClick:a,children:h("models.restoreBuiltIn")}),children:h("models.replacesBuiltInHint")}),E&&(0,r.jsx)(a6,{tone:"success"===c.phase?"success":"danger",children:(0,r.jsx)("span",{className:"models-ellipsis",title:E,children:E})}),(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsx)(iV,{label:h("models.modelId"),children:(0,r.jsx)(aQ,{value:n.id,onChange:e=>N("id",e),placeholder:"model-id",mono:!0,disabled:l})}),(0,r.jsx)(iV,{label:h("models.displayName"),children:(0,r.jsx)(aQ,{value:n.name??"",onChange:e=>N("name",e||void 0),placeholder:n.id||h("models.displayName")})})]}),(0,r.jsxs)("div",{className:"models-switch-list",children:[(0,r.jsx)(iG,{label:h("models.catalogFill"),description:(0,r.jsxs)(r.Fragment,{children:[h("models.catalogFillDescription")," ",(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",className:"settings-link",children:"models.dev ↗"})]}),children:(0,r.jsx)(i5,{size:"small",onClick:()=>void I(),disabled:!n.id.trim()||"loading"===p.phase,children:"loading"===p.phase?h("models.catalogFilling"):h("models.catalogFillAction")})}),(0,r.jsx)(iG,{label:h("i18n.testConnection"),description:h("models.testDescription"),children:(0,r.jsx)(i5,{size:"small",onClick:M,disabled:!n.id.trim()||"testing"===c.phase,children:"testing"===c.phase?h("i18n.checking"):h("models.testAction")})})]}),T&&(0,r.jsx)(a6,{tone:$,action:S.current&&(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:()=>{let e=S.current;e&&(S.current=null,s(e),m({phase:"idle"}))},children:h("models.catalogUndo")}),children:(0,r.jsx)("span",{className:"models-ellipsis",title:T,children:T})}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(a8,{title:h("models.capabilities")}),(0,r.jsxs)("div",{className:"models-switch-list",children:[(0,r.jsx)(a4,{label:h("models.reasoning"),description:h("models.reasoningDescription"),checked:n.reasoning??!1,onChange:e=>N("reasoning",e||void 0)}),(0,r.jsx)(a4,{label:h("models.imageInput"),description:h("models.imageInputDescription"),checked:n.input?.includes("image")??!1,onChange:e=>N("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(a8,{title:h("models.modelSpecs")}),(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsx)(iV,{label:h("models.contextWindow"),children:(0,r.jsx)(a1,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>N("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(iV,{label:h("models.maxOutputTokens"),children:(0,r.jsx)(a1,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>N("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{className:"models-section-header",children:[(0,r.jsx)("span",{className:"config-field-label",children:h("models.costPerMillion")}),(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:()=>{if(g)return void f(!1);C.current=n.cost;let e=aO(n.cost);y.current=e,v(e),f(!0)},"aria-expanded":g,children:g?h("models.finishEditingCosts"):h("models.editCosts")})]}),g?(0,r.jsxs)("div",{className:"models-cost-grid",children:[R.map(({key:e,label:t})=>(0,r.jsx)(iV,{label:t,children:(0,r.jsx)(a1,{value:x[e],onChange:t=>{let r,i,a;return i=aH(r={...y.current,[e]:t}),a={...n},void(y.current=r,v(r),i?(a.cost={...C.current??{},...i},C.current=a.cost):delete a.cost,s(a))},placeholder:"0"})},e)),aU(x)&&!aH(x)&&(0,r.jsx)("p",{"aria-live":"polite",className:"models-hint is-warning models-grid-full",children:h("models.costAllRequired")})]}):(0,r.jsx)("div",{className:"models-cost-grid",children:R.map(({key:e,label:t})=>{let i;return(0,r.jsxs)("div",{className:"models-cost-cell",children:[(0,r.jsx)("span",{className:"models-hint",children:t}),(0,r.jsx)("span",{className:`models-cost-value${n.cost?.[e]===void 0?" is-missing":""}`,children:void 0===(i=n.cost?.[e])?h("models.notProvided"):`$${String(i)}`})]},e)})})]}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsxs)("button",{type:"button",className:"models-disclosure",onClick:()=>j(e=>!e),"aria-expanded":b,"aria-controls":"model-advanced-settings",children:[(0,r.jsxs)("span",{className:"models-disclosure-copy",children:[(0,r.jsx)("strong",{children:h("models.advancedSettings")}),(0,r.jsx)("span",{children:D})]}),(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"models-disclosure-chevron",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),b&&(0,r.jsxs)("div",{id:"model-advanced-settings",className:"models-form",children:[!l&&(0,r.jsx)(iV,{label:h("models.apiOverride"),children:(0,r.jsx)(a2,{value:n.api??"",onChange:e=>N("api",e||void 0),options:lo})}),(0,r.jsxs)(iV,{label:h("models.headers"),children:[(0,r.jsx)(a5,{headers:n.headers,onChange:e=>N("headers",e)}),(0,r.jsx)(a3,{children:h("models.headersHelp")})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(a8,{title:h("models.compatibility")}),(0,r.jsxs)("div",{className:"models-switch-list",children:[(0,r.jsx)(a4,{label:h("models.deepSeekThinkingCompat"),checked:lp(n),onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...lh}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(a4,{label:h("models.developerRole"),checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>s({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})})]}),(0,r.jsx)(a8,{title:h("models.thinkingLevelMap"),actions:n.thinkingLevelMap&&(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:()=>N("thinkingLevelMap",void 0),children:h("models.clearAll")})}),(0,r.jsx)(a7,{value:n.thinkingLevelMap,onChange:e=>N("thinkingLevelMap",e)})]})]})]}),a&&(0,r.jsx)(iX,{children:(0,r.jsx)(iG,{label:h("models.deleteDefinition"),description:h("models.deleteDefinitionDescription"),children:(0,r.jsx)(i5,{size:"small",variant:"danger",onClick:a,children:h("i18n.delete")})})})]})}function lg({onClose:e,embedded:t=!1,cwd:n=null,onModelsChanged:s,onDirtyChange:a}){var l;let o,d,{t:c}=(0,w.s)(),[u,h]=(0,i.useState)({providers:{}}),[p,m]=(0,i.useState)({providers:{}}),[g,f]=(0,i.useState)(!0),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,E]=(0,i.useState)({provider:null}),[M,I]=(0,i.useState)([]),[L,T]=(0,i.useState)([]),[$,R]=(0,i.useState)(!1),[W,P]=(0,i.useState)(null),[z,D]=(0,i.useState)(null),[A,F]=(0,i.useState)([]),[B,O]=(0,i.useState)(new Set),[H,U]=(0,i.useState)(null),[_,q]=(0,i.useState)(!1),[K,V]=(0,i.useState)(null),[J,Y]=(0,i.useState)(null),[Z,X]=(0,i.useState)(null),[G,Q]=(0,i.useState)({}),ee=(0,i.useRef)(!1),et=(0,i.useCallback)(e=>{if(b(e.error??null),ee.current)return;let t=e.providers?e:{...e,providers:{}};h(t),m(t)},[]),en=(0,i.useCallback)(e=>{Array.isArray(e.oauthProviders)&&I(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&T(e.apiKeyProviders)},[]),er=(0,i.useCallback)(e=>{Array.isArray(e.catalog)&&F(e.catalog),Array.isArray(e.builtIn)&&O(new Set(e.builtIn)),X(e.modelError??null)},[]),ei=(0,i.useCallback)(({ok:e,data:t})=>{e&&!t.error&&t.source?(V(null),U(t)):V(t.error??c("models.scopeError"))},[c]),es=(0,i.useCallback)(()=>ag(ab(n)).then(e=>en(e.data)).catch(()=>{}),[n,en]),ea=(0,i.useCallback)(()=>n?ag(aw(n)).then(e=>er(e.data)).catch(()=>{}):void F([]),[n,er]),el=(0,i.useCallback)(()=>n?ag(aj(n)).then(ei).catch(()=>V(c("models.scopeError"))):void U(null),[n,c,ei]);(0,i.useEffect)(()=>{if(!J)return;let e=setTimeout(()=>Y(null),4e3);return()=>clearTimeout(e)},[J]);let eo=(0,i.useCallback)(()=>{es(),ea(),el()},[es,ea,el]);(0,i.useLayoutEffect)(()=>{let e=!1,t=am(ay),r=am(ab(n)),i=n?am(aw(n)):void 0,s=n?am(aj(n)):void 0;return t&&r&&(!n||i&&s)&&(et(t.data),en(r.data),i&&er(i.data),s&&ei(s),f(!1)),Promise.all([ag(ay).then(e=>et(e.data)).catch(e=>b(String(e))),es(),ea(),el()]).finally(()=>{e||f(!1)}),()=>{e=!0}},[n,et,en,er,ei,es,ea,el]);let ed=JSON.stringify(u)!==JSON.stringify(p);(0,i.useEffect)(()=>{ee.current=ed,a?.(ed)},[ed,a]),(0,i.useEffect)(()=>{if(!ed)return;let e=e=>e.preventDefault();return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[ed]);let ec=(0,i.useCallback)((e,t)=>{E({provider:e,...t?{model:t}:{}})},[]),eu=(0,i.useCallback)(e=>{h(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),ec(e)},[ec]),eh=(0,i.useCallback)((e,t)=>{h(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),ep=(0,i.useCallback)(e=>{h(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),ec(null)},[ec]),em=(0,i.useCallback)(e=>{let t=u.providers?.[e]?.models?.length??0;h(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),ec(e,{kind:"definition",index:t})},[u.providers,ec]),eg=(0,i.useCallback)((e,t)=>{h(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],s=new Set(i.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),ef=(0,i.useCallback)((e,t,n)=>{h(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),ex=(0,i.useCallback)((e,t,n)=>{let r=function(e,t){let n={};for(let i of a_){let s=t[i];if(void 0!==s){var r;r=e[i],JSON.stringify(s)!==JSON.stringify(r)&&(n[i]=s)}}return Object.keys(n).length>0?n:void 0}(ld(t),{...n,id:t.id});h(n=>{var i,s;let a,l=n.providers?.[e]??{},o={...l},d=(i=l.modelOverrides,s=t.id,a={...i??{}},delete a[s],r&&(a[s]=r),Object.keys(a).length>0?a:void 0);return d?o.modelOverrides=d:delete o.modelOverrides,{...n,providers:{...n.providers??{},[e]:o}}})},[]),ev=(0,i.useCallback)((e,t)=>{h(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),ec(e)},[ec]),ey=(0,i.useCallback)(async()=>{if(!n)return null;let e=await fetch(`/api/models-config/picker?cwd=${encodeURIComponent(n)}`),t=await e.json();return e.ok&&!t.error&&t.source?t:null},[n]),eb=(0,i.useRef)(0),ew=(0,i.useCallback)(async()=>{let e=++eb.current,t=await ey();return t&&e===eb.current&&U(t),t},[ey]),ej=(0,i.useRef)(Promise.resolve()),ek=(0,i.useCallback)(e=>{if(!n)return Promise.resolve(!1);let t=ej.current.then(async()=>{let t=await ey();if(!t)return V(c("models.scopeError")),!1;if(t.readOnly)return!1;let r=e(t);if(0===r.length)return V(c("models.keepOneModel")),!1;q(!0),V(null),Y(null);try{let e=await fetch("/api/models-config/picker",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,patterns:r})}),t=await e.json();if(!e.ok||t.error||!t.source)return V("untrusted"===t.code?c("models.scopeReadOnly"):t.error??c("models.scopeError")),!1;return U(t),s?.(),!0}catch{return V(c("models.scopeError")),!1}finally{q(!1)}});return ej.current=t.catch(()=>!1),t},[n,ey,s,c]),eS=(0,i.useCallback)(()=>{n&&H&&D("none"===H.source?"replace":"add")},[n,H]),eC=(0,i.useCallback)(async e=>{let t=!!H&&!aZ(H?.patterns??[]);await ek(t=>(function(e){let t=aK(e.patterns);if(aZ(t)){let n,r;return r=(n=e.ref.trim()).slice(n.indexOf("/")+1),aK(t).filter(e=>{let t=aJ(e);return null===t||t.ref!==n&&(void 0!==t.provider||t.id!==r)})}return e.visible.filter(t=>t!==e.ref).map(t=>`${t}${e.pins[t]?`:${e.pins[t]}`:""}`)})({patterns:t.patterns,visible:t.visible.map(e=>aq(e.provider,e.id)),pins:t.pins,ref:e}))&&t&&Y(c("models.listWritten"))},[ek,H,c]),eN=(0,i.useCallback)(async()=>{v(!0),k(null),C(!1);try{var e;let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),n=await t.json();if(!t.ok||n.error)return void k(n.error??`HTTP ${t.status}`);m(u),C(!0),setTimeout(()=>C(!1),2e3),ea();let r=H?.defined,i=await ew(),a=r&&i?(e={patterns:r.length?H?.patterns??[]:[],before:new Set(r),after:new Set(i.defined)},aK(e.patterns).filter(t=>{let n=aJ(t);return null!==n&&void 0!==n.provider&&e.before.has(n.ref)&&!e.after.has(n.ref)})):[];a.length>0&&await ek(e=>e.patterns.filter(e=>!a.includes(e)))&&Y(c("models.removedWithDefinition",{count:a.length})),s?.()}catch(e){k(String(e))}finally{v(!1)}},[u,ew,s,ea,ek,H,c]),eE=[y,Z].filter(Boolean).map(e=>String(e).split("\n")[0]).join(" \xb7 ")||null,eM=H?.visible??[],eI=new Set(eM.map(e=>aq(e.provider,e.id))),eL=new Set(A.map(e=>aq(e.provider,e.id))),eT=H?(o=new Set((l={patterns:H.patterns,visible:[...eI]}).visible),d=new Set(l.visible.map(e=>e.slice(e.indexOf("/")+1))),aK(l.patterns).filter(e=>{let t=aJ(e);return null!==t&&(t.provider?!o.has(t.ref):!d.has(t.id))})).filter(e=>!(H.ambiguous??[]).includes(e)):[],e$=new Set([...M.filter(e=>e.loggedIn).map(e=>e.id),...L.filter(e=>e.configured).map(e=>e.id)]),eR=N.provider,eW=[],eP=e=>{e&&!eW.includes(e)&&eW.push(e)};M.filter(e=>e.loggedIn).forEach(e=>eP(e.id)),L.filter(e=>e.configured).forEach(e=>eP(e.id)),Object.keys(u.providers??{}).forEach(eP),A.forEach(e=>eP(e.provider)),eM.forEach(e=>eP(e.provider)),eP(eR);let ez=eW.map(e=>{let t=M.find(t=>t.id===e),n=L.find(t=>t.id===e),r=u.providers?.[e],i=A.filter(t=>t.provider===e);return{id:e,label:r?.name??t?.name??n?.displayName??e,...t?{oauth:t}:{},...n?{apiKey:n}:{},...r?{json:r}:{},models:i,connected:e$.has(e)||i.length>0}}),eD=e=>eM.filter(t=>t.provider===e).length,eA=()=>n?H?(0,r.jsxs)(r.Fragment,{children:[H.readOnly&&(0,r.jsx)(a6,{tone:"warning",children:c("models.scopeReadOnly")}),J&&(0,r.jsx)(a6,{tone:"info",children:J}),K&&(0,r.jsx)(a6,{tone:"danger",children:K}),eT.length>0&&(0,r.jsx)(lf,{title:c("models.unavailable",{count:eT.length}),hint:c("models.unavailableHint"),entries:eT,readOnly:!!H.readOnly,onRemove:e=>void ek(t=>aY(t.patterns,e))}),(H.ambiguous?.length??0)>0&&(0,r.jsx)(lf,{title:c("models.ambiguous",{count:H.ambiguous?.length??0}),hint:c("models.ambiguousHint"),entries:H.ambiguous??[],readOnly:!!H.readOnly,onRemove:e=>void ek(t=>aY(t.patterns,e))})]}):K?(0,r.jsx)(a6,{tone:"danger",children:K}):null:(0,r.jsx)(a6,{children:c("models.scopeNoCwd")}),eF=e=>{let t=e.json,i=!!(e.oauth||e.apiKey),s=e.apiKey&&(!e.oauth||e.apiKey.configured||!e.oauth.loggedIn),a=t?.models??[],l=!!(t&&(t.name&&""!==t.name.trim()||t.api||t.baseUrl&&""!==t.baseUrl.trim()||t.apiKey&&""!==t.apiKey.trim()||t.headers&&Object.keys(t.headers).length>0)),o=G[e.id]??l,d=[...e.models.map(e=>{let t=a.findIndex(t=>t.id===e.id);return{id:e.id,name:e.name,ref:t>=0?{kind:"definition",index:t}:{kind:"runtime",id:e.id},usable:!0,definition:t>=0}}),...a.map((e,t)=>({model:e,index:t})).filter(({model:t})=>!eL.has(`${e.id}/${t.id}`)).map(({model:e,index:t})=>({id:e.id,name:e.name,ref:{kind:"definition",index:t},usable:!1,definition:!0}))],u=t&&(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(a8,{title:i?c("models.sectionEndpointOverride"):c("models.sectionEndpoint"),hint:i?c("models.sectionOverrideHint"):void 0,actions:i?(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:()=>Q(t=>({...t,[e.id]:!o})),children:o?c("i18n.collapse"):c("i18n.expand")}):void 0}),(!i||o)&&(0,r.jsx)(lc,{providerId:e.id,provider:t,builtIn:i,namePlaceholder:e.oauth?.name??e.apiKey?.displayName??e.id,onChange:t=>eh(e.id,t)},e.id)]}),h=e.oauth?.loggedIn?c("models.kindOAuth"):e.apiKey?.configured?c("models.kindApiKey"):null;return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)("header",{className:"settings-detail-header",children:[(0,r.jsxs)("h2",{className:"settings-detail-title models-provider-label",children:[(0,r.jsx)(aG,{id:e.id,size:16}),e.label]}),(0,r.jsxs)("div",{className:"settings-detail-meta",children:[h&&(0,r.jsx)("span",{className:"config-scope-tag",children:h}),e.oauth&&!e.apiKey&&!e.oauth.loggedIn&&(0,r.jsx)("span",{className:"config-scope-tag",children:c("models.kindOAuth")}),t&&(0,r.jsx)("span",{className:"config-scope-tag",children:i?c("models.kindOverridden"):c("models.kindCustom")})]})]}),(e.oauth||s)&&(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(a8,{title:c("models.sectionConnection")}),e.oauth&&(0,r.jsx)(ln,{provider:e.oauth,onRefresh:eo,cwd:n},e.oauth.id),s&&e.apiKey&&(0,r.jsx)(lr,{provider:e.apiKey,onRefresh:eo,cwd:n},`${e.apiKey.id}-key`)]}),!i&&u,(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(a8,{title:(0,r.jsx)(i2,{label:c("models.sectionModelsTitle"),count:d.length}),hint:n&&H?c("models.chatSwitchHint"):void 0,actions:(t||i)&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i5,{size:"small",disabled:!t?.baseUrl?.trim(),title:t?.baseUrl?.trim()?void 0:c("models.discoveryNeedsBaseUrl"),onClick:()=>P(e.id),children:c("models.discoveryFetch")}),(0,r.jsx)(i5,{size:"small",onClick:()=>em(e.id),children:c("models.newModel")})]})}),t&&W===e.id&&(0,r.jsx)(lu,{providerId:e.id,provider:t,onAddModels:t=>eg(e.id,t),onClose:()=>P(null)}),0===d.length?(0,r.jsx)("p",{className:"models-empty",children:t?c("models.noDefinitions"):c("models.connectToSeeModels")}):(0,r.jsx)("div",{className:"models-list",children:d.map(t=>{let s,a,l,o,d=aq(e.id,t.id);return(0,r.jsxs)("div",{className:"models-row",children:[(s=t.name&&t.name!==t.id?t.name:t.id||c("models.untitledModel"),a=t.name&&t.name!==t.id?t.id:void 0,l=(0,r.jsxs)(r.Fragment,{children:[t.definition&&B.has(d)?(0,r.jsx)("span",{className:"models-tag is-warning",title:c("models.replacesBuiltInHint"),children:c("models.replacesBuiltIn")}):i&&t.definition&&(0,r.jsx)("span",{className:"models-tag",children:c("models.kindDefinition")}),!t.usable&&(0,r.jsx)("span",{className:"models-tag is-warning",children:c("models.notUsable")}),H?.pins[d]&&(0,r.jsx)("span",{className:"models-tag",children:c("models.thinkingPin",{level:H.pins[d]})})]}),o=()=>ec(e.id,t.ref),(0,r.jsxs)("button",{type:"button",className:"models-row-main models-row-button",title:c("models.editParams"),onClick:o,children:[(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsxs)("span",{className:"models-row-title-line",children:[(0,r.jsx)("span",{className:"models-row-title",children:s}),l]}),a&&(0,r.jsx)("code",{className:"models-row-sub",children:a})]}),(0,r.jsx)("svg",{className:"models-row-chevron",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]})),t.id&&((e,t)=>{if(!n||!H)return null;let i=eI.has(e);return(0,r.jsx)("span",{className:"models-row-switch",children:(0,r.jsx)(i7,{checked:i,disabled:H.readOnly||!t&&!i,loading:_,label:c("models.showInChat"),onChange:t=>{t?ek(t=>aV(t.patterns,e)):eC(e)}})})})(d,t.usable)]},`${t.ref.kind}:${t.id}:${"definition"===t.ref.kind?t.ref.index:""}`)})})]}),i&&u,t&&(0,r.jsx)(iX,{children:(0,r.jsx)(iG,{label:i?c("models.deleteOverride"):c("models.deleteEndpoint"),description:i?c("models.deleteOverrideDescription"):c("models.deleteEndpointDescription"),children:(0,r.jsx)(i5,{size:"small",variant:"danger",onClick:()=>{ep(e.id),i&&ec(e.id)},children:i?c("i18n.remove"):c("i18n.delete")})})})]})};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(iK,{embedded:t,title:c("common.models"),closeLabel:c("i18n.close"),onClose:e,children:[(0,r.jsx)("div",{className:"models-body settings-scroll",children:(0,r.jsx)("div",{className:"settings-page",children:g?(0,r.jsx)(iY,{label:c("i18n.loading")}):(()=>{let e=ez.find(e=>e.id===eR),t=e?N.model:void 0;if(e)return(0,r.jsxs)(r.Fragment,{children:[!t&&(0,r.jsx)(i0,{label:c("common.models"),onClick:()=>ec(null)}),eA(),t?((e,t)=>{let i=(0,r.jsxs)("button",{type:"button","data-settings-back":!0,className:"models-breadcrumb",onClick:()=>ec(e.id),children:[(0,r.jsx)("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,r.jsx)("path",{d:"m15 18-6-6 6-6"})}),(0,r.jsx)(aG,{id:e.id,size:13}),e.label]});if("runtime"===t.kind){var s;let a=A.find(n=>n.provider===e.id&&n.id===t.id);if(!a)return null;let l=u.providers?.[e.id]??{},o=l.modelOverrides?.[a.id],d=(s=ld(a),o?{...s,...o,id:s.id,cost:o.cost?{...s.cost,...o.cost}:s.cost}:{...s,id:s.id});return(0,r.jsxs)(r.Fragment,{children:[i,(0,r.jsx)(lm,{providerName:e.id,provider:l,model:d,lockId:!0,cwd:n,onChange:t=>ex(e.id,a,t)},`${e.id}-${t.id}`)]})}let a=u.providers?.[e.id],l=a?.models?.[t.index];return a&&l?(0,r.jsxs)(r.Fragment,{children:[i,(0,r.jsx)(lm,{providerName:e.id,provider:a,model:l,cwd:n,onChange:n=>ef(e.id,t.index,n),onDelete:()=>ev(e.id,t.index),shadowsBuiltIn:B.has(`${e.id}/${l.id}`)},`${e.id}-${t.index}`)]}):null})(e,t)??eF(e):eF(e)]});let i=ez.filter(e=>e.connected),s=ez.filter(e=>!e.connected),a=e=>{let t;return(0,r.jsx)(iQ,{label:(0,r.jsxs)("span",{className:"models-provider-label",children:[(0,r.jsx)(aG,{id:e.id,size:13}),e.label,(t=e.id,JSON.stringify(u.providers?.[t]??null)!==JSON.stringify(p.providers?.[t]??null)&&(0,r.jsx)("span",{className:"models-dirty-dot",title:c("models.unsavedProvider")}))]}),description:e.oauth?.loggedIn?c("models.kindOAuth"):e.apiKey?.configured?c("models.kindApiKey"):e.json?c("models.kindCustom"):c("models.notConnected"),muted:!e.connected,onOpen:()=>ec(e.id),children:H&&e.models.length>0&&(0,r.jsx)("span",{className:"settings-row-status",title:c("models.inChatCount",{count:eD(e.id),total:e.models.length}),children:c("models.inChatShort",{count:eD(e.id),total:e.models.length})})},e.id)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"settings-toolbar",children:[(0,r.jsx)("span",{className:"settings-toolbar-summary",children:c("models.summary",{count:eM.length})}),(0,r.jsx)("span",{className:"settings-toolbar-spacer"}),(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:()=>eS(),disabled:!n||!H||H.readOnly,children:c("models.pickChatModels")}),(0,r.jsx)(i5,{size:"small",onClick:()=>R(!0),children:c("models.addProvider")})]}),eA(),0===ez.length?(0,r.jsx)(iJ,{children:c("models.noProviders")}):(0,r.jsxs)(r.Fragment,{children:[i.length>0&&(0,r.jsx)(iX,{title:(0,r.jsx)(i2,{label:c("models.groupConnected"),count:i.length}),children:i.map(a)}),s.length>0&&(0,r.jsx)(iX,{title:(0,r.jsx)(i2,{label:c("models.groupNotConnected"),count:s.length}),children:s.map(a)})]})]})})()},g?"loading":JSON.stringify(N))}),(ed||x||S||j||eE)&&(0,r.jsxs)(iZ,{status:j||eE?(0,r.jsx)("span",{className:"models-footer-status is-danger",title:eE??void 0,children:j||eE}):ed?(0,r.jsxs)("span",{className:"models-footer-status",children:[(0,r.jsx)("span",{className:"models-dirty-dot"}),c("models.unsavedChanges")]}):null,children:[!t&&(0,r.jsx)(i5,{onClick:e,children:c("i18n.cancel")}),ed&&!x&&(0,r.jsx)(i5,{onClick:()=>{h(p),k(null),!N.provider||p.providers?.[N.provider]||A.some(e=>e.provider===N.provider)?N.provider&&ec(N.provider):ec(null)},children:c("models.discardChanges")}),(ed||x||S)&&(0,r.jsxs)(i5,{variant:"primary",onClick:eN,disabled:x||S,className:S?"is-success":void 0,children:[S&&(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:S?c("i18n.saved"):x?c("i18n.saving"):c("models.saveModelsJson")})]})]})]}),$&&(0,r.jsx)(la,{oauthProviders:M,apiKeyProviders:L,existingIds:new Set([...Object.keys(u.providers??{}),...M.map(e=>e.id),...L.map(e=>e.id),...A.map(e=>e.provider)]),onSelectOAuth:e=>ec(e),onSelectApiKey:e=>ec(e),onAddCustom:eu,onClose:()=>R(!1)}),z&&(0,r.jsx)(ll,{catalog:A,listedRefs:"replace"===z?new Set:eI,mode:z,providerLabel:e=>ez.find(t=>t.id===e)?.label??e,saving:_,error:K,onClose:()=>D(null),onApply:e=>{D(null),ek(t=>"replace"===z?e:e.reduce((e,t)=>aV(e,t),t.patterns))}})]})}function lf({title:e,hint:t,entries:n,readOnly:i,onRemove:s}){let{t:a}=(0,w.s)();return(0,r.jsxs)(a6,{tone:"warning",children:[(0,r.jsx)("strong",{children:e}),(0,r.jsx)("span",{className:"models-notice-hint",children:t}),(0,r.jsx)("div",{className:"models-notice-list",children:n.map(e=>(0,r.jsxs)("div",{className:"models-notice-entry",children:[(0,r.jsx)("code",{children:aJ(e)?.id??e}),!i&&(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:()=>s(e),children:a("models.removeFromChat")})]},e))})]})}function lx(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lv(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function ly(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function lb(e){return e?e.slice(0,8):"unknown"}function lw({skill:e,cwd:t,onToggle:n,toggling:i,saveError:s,updateStatus:a,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u,onDelete:h,deleting:p,deleteError:m}){let{t:g}=(0,w.s)(),f=lv(e),x=!e.disableModelInvocation,v=a?.state==="update-available",y=l?g("i18n.checking"):a&&!v?"up-to-date"===a.state?g("i18n.upToDate"):"unsupported"===a.state?g("i18n.automaticChecksUnavailable"):a.message||g("i18n.checkFailed"):null;return(0,r.jsxs)(i4,{title:e.name,meta:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`config-scope-tag${"project"===f?" is-project":""}`,children:f}),(0,r.jsx)("span",{className:"config-detail-path",title:e.filePath,children:function(e){if("project"===f&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return lx(e)}(e.filePath)})]}),description:e.description,children:[(0,r.jsxs)(iX,{children:[(0,r.jsx)(iG,{label:g("skills.modelInvocation"),description:g(x?"skills.modelInvocationOn":"i18n.hiddenButInvocable"),children:(0,r.jsx)(i7,{checked:x,loading:i,label:g("skills.modelInvocation"),onChange:()=>n(e)})}),s&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:s}),e.install&&(0,r.jsx)(iG,{label:g("i18n.version"),description:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:lb(a?.currentVersion??e.install.versionHash)}),v&&(0,r.jsxs)(r.Fragment,{children:[" → ",(0,r.jsx)("span",{className:"is-accent",children:lb(a.latestVersion)})]}),y&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{className:a?.state==="error"?"is-error":void 0,children:y})]})]}),children:v?(0,r.jsx)(i5,{variant:"primary",size:"small",onClick:u,disabled:o||l,children:g(o?"i18n.updating":"i18n.update")}):e.install.canCheckForUpdates&&(0,r.jsx)(i5,{size:"small",onClick:c,disabled:l||o,children:g("i18n.check")})}),d&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:d}),e.install?.skillsShUrl&&(0,r.jsx)(iG,{label:g("skills.source"),children:(0,r.jsxs)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,className:"settings-link",children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),(0,r.jsxs)(iX,{children:[(0,r.jsx)(iG,{label:g("skills.deleteTitle"),description:g(e.removable?"skills.deleteDescription":"skills.notRemovable"),children:e.removable&&(0,r.jsx)(i5,{variant:"danger",size:"small",onClick:h,disabled:p,children:g("i18n.delete")})}),m&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:m})]})]})}function lj({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:s}){let{t:a}=(0,w.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,h]=(0,i.useState)(!1),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(new Set),[j,k]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),m(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);c(n.results??[]),0===(n.results??[]).length&&m(a("skills.noResults"))}catch(e){m(String(e))}finally{h(!1)}}},[a]),N=(0,i.useCallback)(async t=>{f(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:j,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);b(e=>new Set(e).add(`${j}:${t}`)),s()}catch(e){v(String(e))}finally{f(null)}},[s,j,e]),E="global"===j?"~/.pi/agent/skills/":`${lx(e)}/.pi/skills/`;return(0,r.jsxs)(i4,{title:a("i18n.addSkill"),description:(0,r.jsxs)(r.Fragment,{children:[a("skills.addDescription")," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",className:"settings-link",children:"skills.sh ↗"})]}),children:[(0,r.jsxs)(iX,{children:[(0,r.jsxs)("div",{className:"settings-search",children:[(0,r.jsx)("input",{ref:S,className:"settings-search-input",value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(l)},placeholder:a("i18n.skillSearchPlaceholder"),"aria-label":a("i18n.skillSearchPlaceholder")}),(0,r.jsx)(i5,{variant:"primary",onClick:()=>C(l),disabled:u||!l.trim(),children:u?a("i18n.searching"):a("i18n.search")})]}),(0,r.jsx)(iG,{label:a("skills.installTo"),description:E,children:(0,r.jsx)(i8,{label:a("skills.installTo"),value:j,onChange:k,options:[{value:"global",label:a("skills.scope.global")},{value:"project",label:a("skills.scope.project"),disabled:!n,title:n?void 0:a("trust.projectScopeUnavailable")}]})}),p&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:p}),x&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:x})]}),d.length>0&&(0,r.jsx)(iX,{title:`${a("skills.results")} \xb7 ${d.length}`,children:d.map(e=>{let n=t[j].has(e.package)||y.has(`${j}:${e.package}`),i=g===e.package,s=e.package.indexOf("@"),l=s>-1?e.package.slice(0,s):e.package,o=s>-1?e.package.slice(s+1):null;return(0,r.jsx)(iG,{label:o??l,description:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:l})," \xb7 ",e.installs,e.url&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",className:"settings-link",children:"skills.sh ↗"})]})]}),children:n?(0,r.jsxs)("span",{className:"settings-row-status is-success",children:["✓ ",a("i18n.installed")]}):(0,r.jsx)(i5,{size:"small",onClick:()=>void N(e.package),disabled:null!==g,children:i?a("i18n.installing"):a("i18n.install")})},e.package)})})]})}function lk({cwd:e,onClose:t,embedded:n=!1}){let{t:s}=(0,w.s)(),[a]=(0,i.useState)(()=>{let t=am(aE(e));return t?.ok&&!t.data.error?t.data:null}),[l,o]=(0,i.useState)(a?.skills??[]),[d,c]=(0,i.useState)(!a),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(new Set),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)("list"),[j,k]=(0,i.useState)(""),[S,C]=(0,i.useState)({}),[N,E]=(0,i.useState)(new Set),[M,I]=(0,i.useState)(!1),[L,T]=(0,i.useState)(null),[$,R]=(0,i.useState)(null),[W,P]=(0,i.useState)(a?.projectResourcesLoaded??!0),[z,D]=(0,i.useState)(null),[A,F]=(0,i.useState)(null),B=(0,i.useCallback)(async()=>{h(null);try{let t=await ag(aE(e)),n=t.data;if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];return o(r),P(n.projectResourcesLoaded??!0),r}catch(e){return h(String(e)),[]}finally{c(!1)}},[e]);(0,i.useEffect)(()=>{C({}),R(null),B()},[e]);let O=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(ly).filter(e=>!!e);if(0!==n.length){R(null),E(e=>new Set([...e,...n])),t||I(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);C(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){R(e instanceof Error?e.message:String(e))}finally{E(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||I(!1)}}},[e,l]),H=(0,i.useCallback)(async t=>{if(!t.install)return;let n=ly(t);T(n),R(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await B();let s=i.skill?.install?.versionHash;C(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){R(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,B]),U=(0,i.useCallback)(async t=>{let n=!t.disableModelInvocation;f(e=>new Set(e).add(t.filePath)),v(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath,disableModelInvocation:n})}),i=await r.json();if(!r.ok||i.error)return void v(i.error??`HTTP ${r.status}`);o(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:n}:e))}catch(e){v(String(e))}finally{f(e=>{let n=new Set(e);return n.delete(t.filePath),n})}},[e]),_=(0,i.useCallback)(async t=>{let n=[s("skills.deleteConfirm",{path:lx(t.filePath)}),t.install?s("skills.deleteViaSkillsSh"):null,s("skills.deleteReloadHint")].filter(Boolean).join("\n\n");if(window.confirm(n)){D(t.filePath),F(null);try{let n=await fetch("/api/skills",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath})}),r=await n.json();if(!n.ok||!r.success)throw Error(r.error??`HTTP ${n.status}`);m(null),b("list"),await B()}catch(e){F(e instanceof Error?e.message:String(e))}finally{D(null)}}},[e,B,s]),q=l.find(e=>e.filePath===p)??null,K=()=>{b("list"),F(null)},V=Object.values(S).filter(e=>"update-available"===e.state).length,J=j.trim().toLowerCase(),Y=J?l.filter(e=>`${e.name} ${e.description}`.toLowerCase().includes(J)):l,Z=["project","global","path"].map(e=>({label:s(`skills.group.${e}`),matches:t=>lv(t)===e})).map(({label:e,matches:t})=>{var n;return{label:e,skills:[...(n=Y.filter(t)).filter(e=>!e.disableModelInvocation),...n.filter(e=>e.disableModelInvocation)]}}).filter(e=>e.skills.length>0);return(0,r.jsx)(iK,{embedded:n,title:s("common.skills"),subtitle:lx(e),closeLabel:s("i18n.close"),onClose:t,children:(0,r.jsx)("div",{className:"settings-scroll",children:(0,r.jsx)("div",{className:"settings-page",children:"add"===y?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i0,{label:s("common.skills"),onClick:K}),(0,r.jsx)(lj,{cwd:e,projectResourcesLoaded:W,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{B()}})]}):"detail"===y&&q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i0,{label:s("common.skills"),onClick:K}),(0,r.jsx)(lw,{skill:q,cwd:e,onToggle:U,toggling:g.has(q.filePath),saveError:x,updateStatus:ly(q)?S[ly(q)]:void 0,checkingUpdate:!!ly(q)&&N.has(ly(q)),updating:L===ly(q),updateError:$,onCheckUpdate:()=>void O(q),onUpdate:()=>void H(q),onDelete:()=>void _(q),deleting:z===q.filePath,deleteError:A},q.filePath)]}):(0,r.jsxs)(r.Fragment,{children:[!W&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-warning",children:s("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{className:"settings-toolbar",children:[(0,r.jsx)(i1,{value:j,onChange:k,placeholder:s("skills.filterPlaceholder")}),(0,r.jsx)("span",{className:"settings-toolbar-spacer"}),l.some(e=>!!e.install)&&(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:()=>void O(),disabled:M||null!==L,children:M?s("i18n.checking"):V>0?`${s("i18n.checkUpdates")} \xb7 ${V}`:s("i18n.checkUpdates")}),(0,r.jsx)(i5,{size:"small",onClick:()=>b("add"),children:s("i18n.addSkill")})]}),(x||$)&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:x||$}),d?(0,r.jsx)(iY,{label:s("i18n.loading")}):u?(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:u}):0===Z.length?(0,r.jsx)("p",{className:"settings-row-message",children:J?s("skills.noResults"):s("i18n.noSkills")}):Z.map(e=>(0,r.jsx)(iX,{title:(0,r.jsx)(i2,{label:e.label,count:e.skills.length}),children:e.skills.map(e=>{let t=ly(e),n=!!t&&S[t]?.state==="update-available";return(0,r.jsxs)(iQ,{label:(0,r.jsxs)(r.Fragment,{children:[e.name,e.install?.skillsShUrl&&(0,r.jsx)("span",{className:"settings-row-tag",children:"skills.sh"})]}),description:e.description,muted:e.disableModelInvocation,title:e.filePath,onOpen:()=>{m(e.filePath),F(null),b("detail")},children:[n&&(0,r.jsx)("span",{className:"settings-row-status is-accent",children:s("i18n.updateAvailable")}),(0,r.jsx)(i7,{checked:!e.disableModelInvocation,loading:g.has(e.filePath),label:s("skills.modelInvocation"),onChange:()=>void U(e)})]},e.filePath)})},e.label))]})},d?"loading":y)})})}let lS={builtin:0,global:1,workspace:2,project:3};function lC(e,t){let n=t.toLowerCase();return e.filter(e=>e.name.toLowerCase()===n).sort((e,t)=>lS[t.scope]-lS[e.scope])}let lN=["read","bash","edit","write","grep","find","ls"],lE=["",...eM],lM={name:"custom-agent",displayName:"Custom agent",description:"",systemPrompt:"",tools:["read","bash","edit","write","grep","find","ls"],loadSkills:!1,loadExtensions:!1,inheritContext:!1,runInBackground:!0,enabled:!0};function lI(e){return{name:e.name,displayName:e.displayName,description:e.description,systemPrompt:e.systemPrompt,tools:[...e.tools],loadSkills:e.loadSkills,loadExtensions:e.loadExtensions,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.maxTurns?{maxTurns:e.maxTurns}:{},inheritContext:e.inheritContext,runInBackground:e.runInBackground,enabled:e.enabled}}function lL(e){return"builtin"!==e}function lT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l$(e,t){if(!e.filePath)return null;if(("project"===e.scope||"workspace"===e.scope)&&e.filePath.startsWith(t)){let n=e.filePath.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return lT(e.filePath)}function lR({label:e,children:t}){return(0,r.jsx)(iV,{label:e,children:t})}function lW({checked:e,disabled:t,label:n,onChange:i}){return(0,r.jsxs)("label",{className:"settings-checkbox",children:[(0,r.jsx)("input",{type:"checkbox",checked:e,disabled:t,onChange:e=>i(e.target.checked)}),n]})}function lP({cwd:e,sessionId:t=null,onClose:n,onReloaded:s,embedded:a=!1}){let{t:l}=(0,w.s)(),[o]=(0,i.useState)(()=>{let t=e=>e?.ok&&!e.data.error?e.data:void 0,n=t(am(aS));return{profiles:t(am(ak(e)))?.profiles,settings:"boolean"==typeof n?.enabled?n:void 0,models:t(am(aC(e)))?.modelList}}),[d,c]=(0,i.useState)(o.profiles??[]),[u,h]=(0,i.useState)(o.models??[]),[p,m]=(0,i.useState)(!o.models),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)("list"),[j,k]=(0,i.useState)(lM),[S,C]=(0,i.useState)("view"),[N,E]=(0,i.useState)("project"),[M,I]=(0,i.useState)(!o.profiles),[L,T]=(0,i.useState)(!1),[$,R]=(0,i.useState)(!1),[W,P]=(0,i.useState)(!1),[z,D]=(0,i.useState)(null),[A,F]=(0,i.useState)(o.settings?.enabled??!0),[B,O]=(0,i.useState)(o.settings?.maxConcurrent??10),[H,U]=(0,i.useState)(!o.settings),[_,q]=(0,i.useState)(!1),[K,V]=(0,i.useState)(null),[J,Y]=(0,i.useState)(!1),[Z,X]=(0,i.useState)(!1),G=(0,i.useMemo)(()=>x?lC(d,x):[],[d,x]),Q=G[0]??null,ee=G.slice(1),et=Q?.disableStub?ee[0]??Q:Q,en=(0,i.useMemo)(()=>[...new Set(d.map(e=>e.name.toLowerCase()))].map(e=>{let[t,n]=lC(d,e),r=t.disableStub?n??t:t;return{name:e,top:t,label:r.displayName,description:r.description}}).sort((e,t)=>e.label.localeCompare(t.label)),[d]),er=(0,i.useMemo)(()=>u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[u]),ei=(0,i.useCallback)((e,t)=>{if(v(t),D(null),!t)return;let[n,r]=lC(e,t);if(!n)return;k(lI(n.disableStub?r??n:n));let i=lL(n.scope)&&!n.disableStub&&!n.configurationError;C(i?"edit":"view"),i&&E(n.scope)},[]),es=(0,i.useCallback)(async()=>{let t=await ag(ak(e)),n=t.data;if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.profiles??[];return c(r),r},[e]),ea=(0,i.useCallback)(async e=>{D(null);try{let t=await es();e&&ei(t,e.toLowerCase())}catch(e){D(e instanceof Error?e.message:String(e))}finally{I(!1)}},[es,ei]);(0,i.useEffect)(()=>{ea()},[ea]),(0,i.useEffect)(()=>{let e=new AbortController;return V(null),(async()=>{try{let t=await ag(aS);if(e.signal.aborted)return;let n=t.data;if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);F(n.enabled),"number"==typeof n.maxConcurrent&&O(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;V(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||U(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{let t=new AbortController;return f(null),(async()=>{try{let n=await ag(aC(e));if(t.signal.aborted)return;let r=n.data;if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);h(r.modelList??[]),f(r.modelError??null)}catch(e){if(t.signal.aborted)return;f(e instanceof Error?e.message:String(e))}finally{t.signal.aborted||m(!1)}})(),()=>t.abort()},[e]);let el=async e=>{await ea(e),Y(!!t)},eo=async()=>{if("create"===S&&en.some(e=>e.name===j.name.trim().toLowerCase()))return void D(l("agents.nameExists",{name:j.name.trim()}));T(!0),D(null),R(!1);try{let t=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:N,profile:j})}),n=await t.json();if(!t.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${t.status}`);await el(n.profile.name),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){D(e instanceof Error?e.message:String(e))}finally{T(!1)}},ed=async()=>{if(!Q||!et||!lL(Q.scope))return;let t=ee[0],n=t?l("agents.restoreConfirm",{name:et.displayName,scope:l(`agents.scope.${t.scope}`)}):l("agents.deleteConfirm",{name:et.displayName});if(window.confirm(n)){T(!0),D(null);try{let n=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:Q.scope,name:Q.name})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);await el(t?Q.name:void 0),t||b("list")}catch(e){D(e instanceof Error?e.message:String(e))}finally{T(!1)}}},ec="create"===S||"customize"===S,eu="view"!==S,eh=!eu||L||W,ep=ec?N:Q?.scope,em=ec?"global"===N?`~/.pi/agent/agents/${j.name||"..."}.md`:`./.pi/agents/${j.name||"..."}.md`:Q?l$(Q,e)??l("agents.builtinPath"):"",eg=ec?em:Q?.filePath??em,ef=!j.model||u.some(e=>`${e.provider}/${e.id}`===j.model),ex=(()=>{if(!j.model)return null;let e=j.model.indexOf("/");return e<0?{provider:"",modelId:j.model}:{provider:j.model.slice(0,e),modelId:j.model.slice(e+1)}})(),ev=(e,t)=>{k(n=>({...n,[e]:t}))},ey=async(n,r)=>{P(!0),D(null);try{let i=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,name:n,enabled:r})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await es(),n===x&&ev("enabled",r),Y(!!t)}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(!1)}},eb=async e=>{ec?ev("enabled",e):Q&&await ey(Q.name,e)},ew=async e=>{q(!0),V(null);try{let n=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${n.status}`);F(r.enabled),Y(!!t)}catch(e){V(e instanceof Error?e.message:String(e))}finally{q(!1)}},ej=async e=>{O(e),V(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);O(n.maxConcurrent)}catch(e){V(e instanceof Error?e.message:String(e))}},ek=async()=>{if(t){X(!0),V(null);try{await im(t,{type:"reload"}),Y(!1),s?.()}catch(e){V(e instanceof Error?e.message:String(e))}finally{X(!1)}}},eS="create"===S?l("agents.new"):j.displayName||j.name,eC=!ec&&Q?[...Q.disableStub?[l("agents.stubNote")]:[],...ee.map(t=>"builtin"===t.scope?l("agents.overridesBuiltin"):l("agents.shadows",{scope:l(`agents.scope.${t.scope}`),path:l$(t,e)??""}))]:[],eN=ec?j.enabled:!!Q?.enabled,eE=!ec&&Q&&lL(Q.scope)&&!Q.disableStub;return(0,r.jsxs)(iK,{embedded:a,title:l("common.agents"),subtitle:lT(e),closeLabel:l("agents.close"),onClose:n,children:[J&&t&&(0,r.jsxs)("div",{className:"agents-feature-setting is-notice",children:[(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:l("agents.reloadRequired")}),(0,r.jsx)(i5,{size:"small",onClick:()=>void ek(),disabled:Z||_,children:Z?l("agents.reloading"):l("agents.reloadSession")})]}),(0,r.jsx)("div",{className:"settings-scroll",children:(0,r.jsx)("div",{className:"settings-page",children:"list"===y?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(iX,{children:[(0,r.jsx)(iG,{label:l("agents.builtInTitle"),description:l("agents.builtInDescription"),children:(0,r.jsx)(i7,{checked:A,disabled:H||Z,loading:_,label:l("agents.builtInTitle"),onChange:e=>void ew(e)})}),(0,r.jsx)(iG,{label:l("agents.maxConcurrent"),description:l("agents.maxConcurrentDescription"),children:(0,r.jsx)("input",{"aria-label":l("agents.maxConcurrent"),className:"settings-inline-input agents-number-input",type:"number",min:1,max:32,value:B,disabled:H||_,onChange:e=>O(Number(e.target.value)),onBlur:()=>void ej(B)})}),K&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:K})]}),(0,r.jsxs)(iX,{title:(0,r.jsx)(i2,{label:l("agents.profiles"),count:en.length}),action:(0,r.jsx)(i5,{size:"small",onClick:()=>{let e="custom-agent",t=2;for(;en.some(t=>t.name===e);)e=`custom-agent-${t++}`;v(null),k({...lM,name:e,displayName:e}),C("create"),E("project"),D(null),b("detail")},children:l("agents.new")}),children:[z&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:z}),M?(0,r.jsx)(iY,{label:l("agents.loading")}):en.map(({name:e,top:t,label:n,description:i})=>(0,r.jsx)(iQ,{label:(0,r.jsxs)(r.Fragment,{children:[n,(0,r.jsx)("span",{className:"settings-row-tag",children:l(`agents.scope.${t.scope}`)})]}),description:i,muted:!t.enabled,title:t.filePath,onOpen:()=>{ei(d,e),b("detail")},children:(0,r.jsx)(i7,{checked:t.enabled,disabled:W||!!t.configurationError,label:t.enabled?l("agents.disable"):l("agents.enable"),onChange:e=>void ey(t.name,e)})},e))]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i0,{label:l("common.agents"),onClick:()=>{b("list"),D(null)}}),Q||"create"===S?(0,r.jsxs)(i4,{title:eS,meta:(0,r.jsxs)(r.Fragment,{children:[ep&&(0,r.jsx)("span",{className:`config-scope-tag${"project"===ep?" is-project":""}`,children:l(`agents.scope.${ep}`)}),"builtin"!==ep&&(0,r.jsx)("span",{title:eg,className:"config-detail-path",children:em})]}),description:eC.length>0&&(0,r.jsx)("span",{className:"agents-source-note",children:eC.map(e=>(0,r.jsx)("span",{children:e},e))}),children:[(0,r.jsxs)(iX,{children:[(0,r.jsx)(iG,{label:l("agents.enabled"),description:l("agents.enabledDescription"),children:(0,r.jsx)(i7,{checked:eN,disabled:L||W||!ec&&!!Q?.configurationError,label:eN?l("agents.disable"):l("agents.enable"),onChange:e=>void eb(e)})}),Q?.scope==="builtin"&&"view"===S&&(0,r.jsx)(iG,{label:l("agents.customize"),description:l("agents.customizeDescription"),children:(0,r.jsx)(i5,{size:"small",onClick:()=>{et&&(k(lI(et)),C("customize"),E("project"),D(null))},disabled:L||W,children:l("agents.customize")})}),ec&&(0,r.jsx)(iG,{label:l("agents.saveScope"),description:l("agents.saveScopeDescription"),children:(0,r.jsx)("div",{role:"radiogroup","aria-label":l("agents.saveScope"),className:"settings-segmented",children:["global","project"].map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":N===e,className:"settings-segmented-option",onClick:()=>E(e),disabled:L,children:l(`agents.scope.${e}`)},e))})})]}),(0,r.jsx)(iX,{title:l("agents.profile"),children:(0,r.jsxs)("div",{className:"settings-form",children:[(0,r.jsxs)("div",{className:"settings-form-pair",children:[(0,r.jsx)(lR,{label:l("agents.name"),children:"create"===S?(0,r.jsx)("input",{"aria-label":l("agents.name"),value:j.name,disabled:eh,onChange:e=>ev("name",e.target.value)}):(0,r.jsx)("code",{className:"settings-form-value",children:j.name})}),(0,r.jsx)(lR,{label:l("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":l("agents.displayName"),value:j.displayName,disabled:eh,onChange:e=>ev("displayName",e.target.value)})})]}),(0,r.jsx)(lR,{label:l("agents.description"),children:(0,r.jsx)("input",{"aria-label":l("agents.description"),value:j.description,disabled:eh,onChange:e=>ev("description",e.target.value)})}),(0,r.jsx)(lR,{label:l("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":l("agents.prompt"),value:j.systemPrompt,disabled:eh,onChange:e=>ev("systemPrompt",e.target.value)})})]})}),(0,r.jsx)(iX,{title:l("agents.capabilities"),children:(0,r.jsxs)("div",{className:"settings-form",children:[(0,r.jsx)(lR,{label:l("agents.tools"),children:(0,r.jsx)("div",{className:"settings-checkbox-grid",children:lN.map(e=>(0,r.jsx)(lW,{label:e,disabled:eh,checked:j.tools.includes(e),onChange:t=>ev("tools",t?[...j.tools,e]:j.tools.filter(t=>t!==e))},e))})}),(0,r.jsx)(lR,{label:l("agents.resources"),children:(0,r.jsxs)("div",{className:"settings-checkbox-grid",children:[(0,r.jsx)(lW,{label:l("agents.loadSkills"),disabled:eh,checked:j.loadSkills,onChange:e=>ev("loadSkills",e)}),(0,r.jsx)(lW,{label:l("agents.loadExtensions"),disabled:eh,checked:j.loadExtensions,onChange:e=>ev("loadExtensions",e)})]})})]})}),(0,r.jsx)(iX,{title:l("agents.runtime"),children:(0,r.jsxs)("div",{className:"settings-form",children:[(0,r.jsxs)("div",{className:"settings-form-triple",children:[(0,r.jsxs)(lR,{label:l("agents.model"),children:[(0,r.jsx)(td,{options:er,value:ex,onChange:(e,t)=>ev("model",`${e}/${t}`),onClear:()=>ev("model",void 0),emptyLabel:p?l("agents.modelsLoading"):l("agents.inherit"),selectedLabel:j.model&&!ef?l("agents.modelUnavailable",{model:j.model}):void 0,disabled:eh||p||0===u.length&&!j.model,ariaLabel:l("agents.model"),variant:"field",placement:"auto"}),g&&(0,r.jsx)("span",{className:"settings-row-message is-error",children:g})]}),(0,r.jsx)(lR,{label:l("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":l("agents.thinking"),value:j.thinking??"",disabled:eh,onChange:e=>ev("thinking",e.target.value||void 0),children:lE.map(e=>(0,r.jsx)("option",{value:e,children:e||l("agents.inherit")},e||"default"))})}),(0,r.jsx)(lR,{label:l("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":l("agents.maxTurns"),type:"number",min:1,value:j.maxTurns??"",disabled:eh,onChange:e=>ev("maxTurns",e.target.value?Number(e.target.value):void 0)})})]}),(0,r.jsxs)("div",{className:"settings-checkbox-grid",children:[(0,r.jsx)(lW,{label:l("agents.inheritContext"),disabled:eh,checked:j.inheritContext,onChange:e=>ev("inheritContext",e)}),(0,r.jsx)(lW,{label:l("agents.background"),disabled:eh,checked:j.runInBackground,onChange:e=>ev("runInBackground",e)})]})]})}),et&&!ec&&(0,r.jsxs)(iX,{children:[(0,r.jsx)(iG,{label:l("agents.duplicate"),description:l("agents.duplicateDescription"),children:(0,r.jsx)(i5,{size:"small",onClick:()=>{if(!et)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,s=2;for(;n.has(i.toLowerCase());)i=`${r}-${s++}`;return i}(et.name,d);v(null),k({...lI(et),name:e,displayName:l("agents.copyName",{name:et.displayName}),enabled:!0}),C("create"),E("project"),D(null)},disabled:L||W,children:l("agents.duplicate")})}),eE&&(0,r.jsx)(iG,{label:ee[0]?l("agents.restore",{scope:l(`agents.scope.${ee[0].scope}`)}):l("agents.deleteTitle"),description:ee[0]?l("agents.restoreDescription"):l("agents.deleteDescription"),children:(0,r.jsx)(i5,{variant:"danger",size:"small",onClick:()=>void ed(),disabled:L||W,children:ee[0]?l("agents.restore",{scope:l(`agents.scope.${ee[0].scope}`)}):l("agents.delete")})})]})]}):(0,r.jsx)(iJ,{children:l("agents.empty")})]})},M?"loading":y)}),"detail"===y&&eu&&(0,r.jsx)(iZ,{status:z&&(0,r.jsx)("span",{role:"alert",className:"settings-row-message is-error",children:z}),children:(0,r.jsxs)(i5,{variant:"primary",onClick:()=>void eo(),disabled:L||$||W||!j.name.trim(),className:$?"is-success":void 0,children:[$&&(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:$?l("i18n.saved"):L?l("agents.saving"):l("agents.save")})]})})]})}function lz(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lD(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function lA(e){return`${e.scope}\0${e.source}`}function lF(e){return`extension\0${e.path}`}function lB(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t(1===e.counts.extensions?"i18n.extensionShortOne":"i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t(1===e.counts.skills?"i18n.skillShortOne":"i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t(1===e.counts.prompts?"i18n.promptShortOne":"i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t(1===e.counts.themes?"i18n.themeShortOne":"i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function lO({pkg:e}){let{t}=(0,w.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)(iX,{title:t("i18n.resolvedResources"),children:(0,r.jsx)("p",{className:"settings-row-message",children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")})}):n.map(e=>(0,r.jsx)(iX,{title:`${e.label} \xb7 ${e.resources.length}`,children:e.resources.map(e=>(0,r.jsx)(iG,{title:e.path,label:e.name,description:e.relativePath},`${e.kind}:${e.path}`))},e.kind))}function lH({scope:e}){return(0,r.jsx)("span",{className:`config-scope-tag${"project"===e?" is-project":""}`,children:e})}function lU({cwd:e,source:t,scope:n,projectResourcesLoaded:s,busy:a,actionError:l,onSourceChange:o,onScopeChange:d,onInstall:c}){let{t:u}=(0,w.s)(),h=(0,i.useRef)(null);return(0,i.useEffect)(()=>{h.current?.focus()},[]),(0,r.jsxs)(i4,{title:u("i18n.addPlugin"),description:(0,r.jsxs)(r.Fragment,{children:[u("plugins.addDescription")," ",(0,r.jsx)("a",{href:"https://pi.dev/packages",target:"_blank",rel:"noopener noreferrer",className:"settings-link",children:"pi.dev/packages ↗"})]}),children:[(0,r.jsxs)(iX,{children:[(0,r.jsxs)("div",{className:"settings-search",children:[(0,r.jsx)("input",{id:"plugin-source",ref:h,className:"settings-search-input is-mono","aria-label":u("plugins.source"),value:t,onChange:e=>o(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=lD(t);n!==t&&(e.preventDefault(),o(n))},onBlur:e=>o(lD(e.currentTarget.value)),placeholder:"npm:@scope/package",onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!a&&c()}}),(0,r.jsx)(i5,{variant:"primary",onClick:c,disabled:a||!t.trim(),children:u(a?"i18n.installing":"i18n.install")})]}),(0,r.jsx)(iG,{label:u("skills.installTo"),description:"project"===n?`${lz(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}",children:(0,r.jsx)(i8,{label:u("skills.installTo"),value:n,onChange:d,options:[{value:"global",label:u("skills.scope.global")},{value:"project",label:u("skills.scope.project"),disabled:!s,title:s?void 0:u("trust.projectScopeUnavailable")}]})}),l&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error is-pre",children:l})]}),(0,r.jsx)(iX,{title:u("plugins.examples"),children:(0,r.jsx)("div",{className:"settings-examples",children:["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"].map(e=>(0,r.jsx)("button",{type:"button",className:"settings-example",onClick:()=>o(e),children:e},e))})})]})}function l_({pkg:e,busyKey:t,actionError:n,actionMessage:i,sessionId:s,updateStatus:a,checkingUpdate:l,updateError:o,onAction:d,onCheckUpdate:c,onReloadSession:u}){let h,{t:p}=(0,w.s)(),m=lA(e),g=t?.endsWith(m)??!1,f="reload"===t,x=!e.disabled,v=e.canCheckForUpdates,y=a?.state==="update-available",b=v&&(l||a&&!y)?l?p("i18n.checking"):a?.state==="up-to-date"?p("i18n.upToDate"):a?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):a?.message||p("i18n.checkFailed"):null;return(0,r.jsxs)(i4,{title:e.packageName??e.source,meta:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lH,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{className:"config-scope-tag",children:p("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{className:"config-scope-tag is-warning",children:p("i18n.filtered")}),(0,r.jsx)("span",{className:"config-detail-path",title:e.source,children:e.source})]}),children:[(0,r.jsxs)(iX,{children:[(0,r.jsx)(iG,{label:p("plugins.enabled"),description:p("plugins.enabledDescription"),children:(0,r.jsx)(i7,{checked:x,loading:g||f,onChange:()=>d(e.disabled?"enable":"disable",e),label:p(e.disabled?"i18n.enablePackage":"i18n.disablePackage")})}),(0,r.jsx)(iG,{label:p("i18n.version"),description:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(h=[],e.version&&h.push(p("i18n.installedVersion",{version:e.version})),e.configuredVersion&&h.push(p("i18n.configuredVersion",{version:e.configuredVersion})),h.length?h.join(" \xb7 "):p("i18n.unknown"))}),y&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{className:"is-accent",title:a.displayName,children:p("i18n.updateAvailable")})]}),b&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{className:a?.state==="error"?"is-error":void 0,children:b})]})]}),children:(0,r.jsx)(i5,{size:"small",variant:y?"primary":void 0,onClick:y||!v?()=>d("update",e):c,disabled:g||f||l,children:p(t===`update:${m}`?"i18n.updating":l?"i18n.checking":y||!v?"i18n.update":"i18n.check")})}),o&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:o}),(0,r.jsx)(iG,{label:p("i18n.reloadSession"),description:p(s?"plugins.reloadDescription":"i18n.openSessionToReload"),children:(0,r.jsx)(i5,{size:"small",onClick:u,disabled:!s||f||g,children:p(f?"i18n.reloading":"plugins.reload")})}),i&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-success",children:i}),n&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:n})]}),(0,r.jsx)(iX,{title:p("settings.details"),children:(0,r.jsxs)(i3,{children:[(0,r.jsx)(i6,{label:p("i18n.status"),children:(0,r.jsx)("span",{className:`settings-status is-${e.status}`,children:e.status})}),(0,r.jsx)(i6,{label:p("i18n.resources"),children:lB(e,p)}),(0,r.jsx)(i6,{label:p("i18n.installedPath"),children:e.installedPath?lz(e.installedPath):(0,r.jsx)("span",{className:"is-error",children:p("i18n.notFound")})})]})}),(0,r.jsx)(lO,{pkg:e}),(0,r.jsx)(iX,{children:(0,r.jsx)(iG,{label:p("plugins.removeTitle"),description:p("plugins.removeDescription"),children:(0,r.jsx)(i5,{variant:"danger",size:"small",onClick:()=>d("remove",e),disabled:g||f,children:p(t===`remove:${m}`?"i18n.removing":"i18n.remove")})})})]})}function lq({extension:e}){let{t}=(0,w.s)(),n=e.enabled?"loaded":"disabled";return(0,r.jsx)(i4,{title:e.name,meta:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lH,{scope:e.scope}),(0,r.jsx)("span",{className:"config-detail-path",title:e.path,children:lz(e.path)})]}),children:(0,r.jsx)(iX,{title:t("settings.details"),children:(0,r.jsxs)(i3,{children:[(0,r.jsx)(i6,{label:t("i18n.status"),children:(0,r.jsx)("span",{className:`settings-status is-${n}`,children:n})}),(0,r.jsx)(i6,{label:t("i18n.installedPath"),children:lz(e.path)})]})})})}function lK({cwd:e,sessionId:t,onClose:n,onReloaded:s,embedded:a=!1}){let{t:l}=(0,w.s)(),[o,d]=(0,i.useState)(()=>{let t=am(aM(e));return t?.ok&&!t.data.error?t.data:null}),[c,u]=(0,i.useState)(!0),[h,p]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)("list"),[v,y]=(0,i.useState)(""),[b,j]=(0,i.useState)("global"),[k,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[E,M]=(0,i.useState)(null),[I,L]=(0,i.useState)({}),[T,$]=(0,i.useState)(new Set),[R,W]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[D,A]=(0,i.useState)(!1),F=(0,i.useMemo)(()=>o?.packages??[],[o?.packages]),B=(0,i.useMemo)(()=>o?.standaloneExtensions??[],[o?.standaloneExtensions]),O=F.find(e=>lA(e)===m)??null,H=B.find(e=>lF(e)===m)??null,U=o?.projectResourcesLoaded??!0,_=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:F.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[F]),q=(0,i.useCallback)(async()=>{u(!0),p(null);try{let t=await ag(aM(e)),n=t.data;if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);d(n)}catch(e){p(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,i.useEffect)(()=>{L({}),z(null),q()},[e]);let K=(0,i.useCallback)(async t=>{let n=(t?[t]:F.filter(e=>e.canCheckForUpdates)).map(lA);if(0!==n.length){z(null),$(e=>new Set([...e,...n])),t||W(!0);try{let n=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,source:t?.source,scope:t?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);L(e=>{let t={...e};for(let e of r.updates??[])t[lA(e)]=e;return t})}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||W(!1)}}},[e,F]),V=(0,i.useCallback)(async()=>{A(!0),N(null),M(null),z(null);try{let n=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);d(r),L({}),M(l("i18n.packagesUpdated")),t&&M(`${l("i18n.packagesUpdated")} ${l("agents.reloadRequired")}`)}catch(e){N(e instanceof Error?e.message:String(e))}finally{A(!1)}},[e,t,l]),J=(0,i.useCallback)(async(t,n)=>{let r=lA(n);S(`${t}:${r}`),N(null),M(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);d(s),"remove"===t?(g(null),x("list"),M("Package removed."),L(e=>{let t={...e};return delete t[r],t})):(M({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t]),"update"===t&&L(e=>{let t={...e};return delete t[r],t}))}catch(e){N(e instanceof Error?e.message:String(e))}finally{S(null)}},[e]),Y=(0,i.useCallback)(async()=>{let t=lD(v).trim();if(!t)return;y(t);let n=`${b}\0${t}`;S(`install:${n}`),N(null),M(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:b,cwd:e})}),l=await a.json();if(!a.ok||l.error)throw Error(l.error??`HTTP ${a.status}`);d(l);let o=(r=l.packages,s=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===b&&e.source===i)??r.find(e=>e.scope===b&&e.source===`npm:${s}`)??r.find(e=>e.scope===b&&e.source.endsWith(i)));g(o?lA(o):n),x("detail"),y(""),M("Package installed.")}catch(e){N(e instanceof Error?e.message:String(e))}finally{S(null)}},[e,b,v]),Z=(0,i.useCallback)(async()=>{if(t){S("reload"),N(null),M(null);try{await im(t,{type:"reload"}),s?.(),await q(),M("Session reloaded.")}catch(e){N(e instanceof Error?e.message:String(e))}finally{S(null)}}},[q,s,t]),X=k?.startsWith("install:")??!1,G=Object.values(I).filter(e=>"update-available"===e.state).length,Q=F.some(e=>e.canCheckForUpdates),ee=c||null!==k||T.size>0||D,et=()=>{x("list"),N(null),M(null)},en=e=>{g(e),N(null),M(null),x("detail")};return(0,r.jsx)(iK,{embedded:a,title:l("common.plugins"),subtitle:lz(e),closeLabel:l("i18n.close"),onClose:n,children:(0,r.jsx)("div",{className:"settings-scroll",children:(0,r.jsx)("div",{className:"settings-page",children:"add"===f?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i0,{label:l("common.plugins"),onClick:et}),(0,r.jsx)(lU,{cwd:e,source:v,scope:b,projectResourcesLoaded:U,busy:X,actionError:C,onSourceChange:y,onScopeChange:j,onInstall:Y})]}):"detail"===f&&(H||O)?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i0,{label:l("common.plugins"),onClick:et}),H?(0,r.jsx)(lq,{extension:H}):O&&(0,r.jsx)(l_,{pkg:O,busyKey:k,actionError:C,actionMessage:E,sessionId:t,updateStatus:I[lA(O)],checkingUpdate:T.has(lA(O)),updateError:P,onAction:J,onCheckUpdate:()=>void K(O),onReloadSession:Z},lA(O))]}):(0,r.jsxs)(r.Fragment,{children:[!U&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-warning",children:l("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{className:"settings-toolbar",children:[o&&(0,r.jsx)("span",{className:"settings-toolbar-summary",children:l("plugins.summary",{count:F.length,enabled:F.filter(e=>!e.disabled).length})}),(0,r.jsx)("span",{className:"settings-toolbar-spacer"}),(0,r.jsx)(i5,{size:"small",variant:"ghost",onClick:()=>void q(),disabled:ee,children:l("i18n.refresh")}),Q&&(0,r.jsx)(i5,{size:"small",variant:G>0?"primary":"ghost",onClick:()=>void(G>0?V():K()),disabled:ee,title:G>0?l("i18n.updateAllPluginsHint"):void 0,children:D?l("i18n.updating"):R?l("i18n.checking"):G>0?`${l("i18n.updateAllPlugins")} \xb7 ${G}`:l("i18n.checkUpdates")}),(0,r.jsx)(i5,{size:"small",onClick:()=>{N(null),x("add")},children:l("i18n.addPlugin")})]}),o?.diagnostics.length?(0,r.jsx)("p",{className:`settings-row-message ${o.diagnostics.some(e=>"error"===e.type)?"is-error":"is-warning"}`,title:o.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),children:l("plugins.diagnostics",{count:o.diagnostics.length})}):null,E&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-success",children:E}),(C||P)&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error is-pre",children:C||P}),c&&!o?(0,r.jsx)(iY,{label:l("i18n.loading")}):h?(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:h}):0===F.length&&0===B.length?(0,r.jsx)("p",{className:"settings-row-message",children:l("plugins.empty")}):(0,r.jsxs)(r.Fragment,{children:[_.map(e=>(0,r.jsx)(iX,{title:(0,r.jsx)(i2,{label:l(`skills.group.${e.scope}`),count:e.packages.length}),children:e.packages.map(e=>{let t=lA(e),n=k?.endsWith(t)??!1;return(0,r.jsxs)(iQ,{label:e.packageName??e.source,description:(0,r.jsxs)(r.Fragment,{children:[lz(e.source)," \xb7 ",lB(e,l)]}),muted:e.disabled,title:e.source,onOpen:()=>en(t),children:[("installed"===e.status||"missing"===e.status)&&(0,r.jsx)(i9,{tone:"missing"===e.status?"danger":"warning",title:e.status}),I[t]?.state==="update-available"&&(0,r.jsx)("span",{className:"settings-row-status is-accent",children:l("i18n.updateAvailable")}),(0,r.jsx)(i7,{checked:!e.disabled,loading:n,disabled:"reload"===k,label:e.disabled?l("i18n.enablePackage"):l("i18n.disablePackage"),onChange:()=>void J(e.disabled?"enable":"disable",e)})]},t)})},e.scope)),B.length>0&&(0,r.jsx)(iX,{title:(0,r.jsx)(i2,{label:l("i18n.extensions"),count:B.length}),children:B.map(e=>(0,r.jsx)(iQ,{label:e.name,description:lz(e.path),muted:!e.enabled,title:e.path,onOpen:()=>en(lF(e))},lF(e)))})]})]})},c&&!o?"loading":f)})})}let lV=new Set(["openai-codex","antigravity","xai"]);function lJ({sessionId:e=null,onReloaded:t}){let{t:n}=(0,w.s)(),[s,a]=(0,i.useState)(()=>{let e=am(aN);return e?.ok&&!e.data.error?lY(e.data):null}),[l,o]=(0,i.useState)(null===s),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(!1),[p,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(null);(0,i.useEffect)(()=>{let e=new AbortController;return f(null),(async()=>{try{let t=await ag(aN);if(e.signal.aborted)return;let n=t.data;if(!t.ok||n.error||"boolean"!=typeof n.enabled||!Array.isArray(n.connections))throw Error(n.error??`HTTP ${t.status}`);let r=lY(n);a(r)}catch(e){e instanceof DOMException&&"AbortError"===e.name||f(e instanceof Error?e.message:String(e))}finally{e.signal.aborted||o(!1)}})(),()=>e.abort()},[]);let j=async t=>{let n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled||!Array.isArray(n.connections))throw Error(n.error??`HTTP ${t.status}`);a(lY(n)),m(!!e)},k=async e=>{c(!0),f(null);try{let t=await fetch("/api/image-generation/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});await j(t)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}},S=async()=>{if(!y||!y.label.trim())return void b(null);c(!0),f(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:y.id,label:y.label.trim()})});await j(e),b(null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}},C=async()=>{if(x){c(!0),f(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"edit"===x.mode?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify("edit"===x.mode?{id:x.id,label:x.label,provider:x.provider,model:x.model}:{label:x.label,provider:x.provider,model:x.model})});await j(e),v(null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}}},N=async e=>{if(window.confirm(n("agents.deleteConfirm",{name:e.label}))){c(!0),f(null);try{let t=await fetch("/api/image-generation/settings/connections",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e.id})});await j(t),x?.mode==="edit"&&x.id===e.id&&v(null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}}},E=async()=>{if(e){h(!0),f(null);try{await im(e,{type:"reload"}),m(!1),t?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}}},M=s?.connections.filter(e=>"custom"!==e.kind)??[],I=s?.connections.filter(e=>"custom"===e.kind)??[],L=s?.providers??[],T=x?.mode==="edit"?I.find(e=>e.id===x.id):void 0,$=x&&(0,r.jsxs)("form",{className:"settings-inline-form",onSubmit:e=>{e.preventDefault(),C()},children:[(0,r.jsxs)("label",{className:"settings-field",children:[(0,r.jsx)("span",{children:n("settings.imagesLabel")}),(0,r.jsx)("input",{value:x.label,onChange:e=>v({...x,label:e.target.value}),required:!0})]}),(0,r.jsxs)("label",{className:"settings-field",children:[(0,r.jsx)("span",{children:n("settings.imagesProvider")}),(0,r.jsx)("select",{value:x.provider,onChange:e=>v({...x,provider:e.target.value}),required:!0,children:L.map(e=>(0,r.jsx)("option",{value:e.id,children:e.name===e.id?e.id:`${e.name} (${e.id})`},e.id))})]}),(0,r.jsxs)("label",{className:"settings-field",children:[(0,r.jsx)("span",{children:n("settings.imagesModel")}),(0,r.jsx)(lG,{value:x.model,t:n,onChange:e=>{let t=em.find(t=>t.model===e);v({...x,model:e,..."create"===x.mode&&!x.label.trim()&&t?{label:t.label}:{}})}},"edit"===x.mode?x.id:"create")]}),(0,r.jsxs)("div",{className:"settings-inline-form-actions",children:[T&&(0,r.jsx)(i5,{type:"button",size:"small",variant:"ghost",className:"is-danger-text is-pushed-left",disabled:d,onClick:()=>void N(T),children:n("agents.delete")}),(0,r.jsx)(i5,{type:"button",size:"small",disabled:d,onClick:()=>v(null),children:n("trust.cancel")}),(0,r.jsx)(i5,{type:"submit",variant:"primary",size:"small",disabled:d||!x.label.trim()||!x.provider||!x.model.trim(),children:d?n("agents.saving"):n("agents.save")})]})]});return l&&!s?(0,r.jsx)("div",{className:"settings-page",children:(0,r.jsx)(iY,{label:n("i18n.loading")})},"loading"):(0,r.jsxs)("div",{className:"settings-page",children:[(0,r.jsxs)(iX,{children:[(0,r.jsxs)(iG,{label:n("settings.imagesEnabled"),description:n("settings.imagesDescription"),children:[p&&e&&(0,r.jsx)(i5,{size:"small",onClick:()=>void E(),disabled:u||d,children:u?n("agents.reloading"):n("agents.reloadSession")}),(0,r.jsx)(i7,{checked:s?.enabled===!0,disabled:l||u||!s,loading:d&&!x&&!y,label:n("settings.imagesEnabled"),onChange:e=>void k({enabled:e})})]}),s?.enabled&&s.connections.some(e=>e.enabled)&&(0,r.jsx)(iG,{label:n("settings.imagesDefault"),description:n("settings.imagesDefaultDescription"),children:(0,r.jsx)("select",{className:"settings-select",value:s.defaultConnection,disabled:l||d||u,onChange:e=>void k({default:e.target.value}),children:s.connections.filter(e=>e.enabled).map(e=>(0,r.jsxs)("option",{value:e.id,disabled:!e.signedIn,children:[e.label,e.signedIn?"":` (${n("settings.imagesSignedOut")})`]},e.id))})}),p&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-warning",children:n("agents.reloadRequired")}),g&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:g})]}),s?.enabled&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(iX,{title:(0,r.jsx)(i2,{label:n("settings.imagesBuiltin"),count:M.length}),children:M.map(e=>(0,r.jsx)(lZ,{connection:e,disabled:l||u||d,unsignedLabel:n("settings.imagesSignedOut"),onChange:t=>void k({connections:{[e.id]:{enabled:t}}}),renaming:y?.id===e.id,renameValue:y?.id===e.id?y.label:e.label,onRenameChange:t=>b({id:e.id,label:t}),onRenameSubmit:()=>void S(),onRenameCancel:()=>b(null),onEdit:()=>{v(null),b({id:e.id,label:e.label})},editLabel:n("i18n.rename")},e.id))}),(0,r.jsxs)(iX,{title:(0,r.jsx)(i2,{label:n("settings.imagesCustom"),count:I.length}),action:L.length>0&&!x&&(0,r.jsx)(i5,{size:"small",disabled:l||u||d,onClick:()=>{b(null),v({mode:"create",label:"",provider:L.find(e=>!lV.has(e.id))?.id??L[0]?.id??"",model:""})},children:n("settings.imagesAddConnection")}),children:[0===L.length&&(0,r.jsx)("p",{className:"settings-row-message",children:n("settings.imagesNoProviders")}),I.map(e=>(0,r.jsx)(i.Fragment,{children:x?.mode==="edit"&&x.id===e.id?$:(0,r.jsx)(lZ,{connection:e,disabled:l||u||d,unsignedLabel:n("settings.imagesNotConfigured"),detail:e.model,onChange:t=>void k({connections:{[e.id]:{enabled:t}}}),onEdit:()=>{b(null),v({mode:"edit",id:e.id,label:e.label,provider:e.provider,model:e.model})},editLabel:n("image.edit")})},e.id)),x?.mode==="create"&&$]})]})]},"ready")}function lY(e){return{enabled:!0===e.enabled,defaultConnection:e.defaultConnection??"",connections:(e.connections??[]).map(e=>({...e,model:e.model??"",kind:"custom"===e.kind?"custom":"builtin"})),providers:(e.providers??[]).filter(e=>!!(e&&"string"==typeof e.id&&e.id))}}function lZ({connection:e,disabled:t,unsignedLabel:n,detail:s,onChange:a,onEdit:l,editLabel:o,renaming:d=!1,renameValue:c,onRenameChange:u,onRenameSubmit:h,onRenameCancel:p}){let m=(0,i.useRef)(!1),g=!e.signedIn&&!e.enabled,f=d?(0,r.jsx)("input",{className:"settings-inline-input",value:c,autoFocus:!0,"aria-label":o,onChange:e=>u?.(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),m.current=!0,h?.()),"Escape"===e.key&&(e.preventDefault(),m.current=!0,p?.())},onBlur:()=>{if(m.current){m.current=!1;return}h?.()}}):(0,r.jsx)("span",{className:e.signedIn?void 0:"is-dim",children:e.label});return(0,r.jsxs)(iG,{label:f,description:e.signedIn?s:n,children:[(0,r.jsx)("span",{className:"settings-row-hover-actions",children:l&&!d?(0,r.jsx)(i5,{size:"small",variant:"ghost",disabled:t,onClick:l,children:o}):null}),(0,r.jsx)(i7,{checked:e.enabled,disabled:t||g,label:e.label,onChange:a})]})}let lX="__other__";function lG({value:e,onChange:t,t:n}){let s=em.some(t=>t.model===e),[a,l]=(0,i.useState)(!s),o=a||!s?lX:e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("select",{value:o,onChange:e=>{let n=e.target.value;n===lX?l(!0):(l(!1),t(n))},children:[em.map(e=>(0,r.jsxs)("option",{value:e.model,children:[e.label," \xb7 ",e.model]},e.model)),(0,r.jsx)("option",{value:lX,children:n("settings.imagesOtherModel")})]}),o===lX?(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),required:!0}):null]})}let lQ=e=>String(e).padStart(2,"0"),l0=e=>`${e.getFullYear()}-${lQ(e.getMonth()+1)}-${lQ(e.getDate())}`,l1=e=>{let[t,n,r]=e.split("-").map(Number);return new Date(t,n-1,r??1)},l2=(e,t)=>new Date(e.getFullYear(),e.getMonth(),e.getDate()+t);function l4(){return{cost:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,messages:0,unpriced:0}}function l8(e,t){e.cost+=t.cost,e.tokens+=t.input+t.output+t.cacheRead+t.cacheWrite,e.input+=t.input,e.output+=t.output,e.cacheRead+=t.cacheRead,e.cacheWrite+=t.cacheWrite,e.messages+=t.messages,e.unpriced+=t.unpriced}function l3(e){let t=l4();for(let n of e)l8(t,n);return t}function l6(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i||n.set(e,i={key:e,records:[],...l4()}),i.records.push(r),l8(i,r)}return[...n.values()].sort((e,t)=>t.cost-e.cost||t.tokens-e.tokens)}function l5(e,t){return"all"===e?null:l0(l2(t,1-Number.parseInt(e,10)))}function l7(e,t){if("day"===t)return e;if("month"===t)return e.slice(0,7);let n=l1(e);return l0(l2(n,-((n.getDay()+6)%7)))}function l9(e,t,n){let r=[],i=l1(l7(e,n)),s=l7(t,n);for(;;){let e="month"===n?l0(i).slice(0,7):l0(i);if(e>s)return r;r.push(e),i="day"===n?l2(i,1):"week"===n?l2(i,7):new Date(i.getFullYear(),i.getMonth()+1,1)}}function oe(e,t,n,r){return"month"===t?n.month(e):"week"===t?r("usage.weekOf",{date:n.shortDay(e)}):n.day(e)}function ot(){let e,{t,locale:n}=(0,w.s)(),s=(0,i.useMemo)(()=>{let e=e=>new Intl.NumberFormat(n,{style:"currency",currency:"USD",currencyDisplay:"narrowSymbol",minimumFractionDigits:e,maximumFractionDigits:e}),t=e(1),r=e(2),i=new Intl.NumberFormat(n,{notation:"compact",minimumFractionDigits:1,maximumFractionDigits:1}),s=new Intl.NumberFormat(n),a=new Intl.NumberFormat(n,{style:"percent",minimumFractionDigits:1,maximumFractionDigits:1}),l=new Intl.DateTimeFormat(n,{year:"numeric",month:"short",day:"numeric"}),o=new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}),d=new Intl.DateTimeFormat(n,{year:"numeric",month:"short"}),c=new Intl.DateTimeFormat(n,{month:"short"}),u=new Intl.DateTimeFormat(n,{weekday:"narrow"}),h=new Intl.DateTimeFormat(n,{weekday:"long"});return{cost:e=>e>0&&e<.05?`<${t.format(.1)}`:t.format(e),unitCost:e=>r.format(e),tokens:e=>{let t=i.format(e);return/\d$/.test(t)?s.format(Math.round(e)):t},count:e=>s.format(e),percent:e=>a.format(e),share:e=>e>0&&e<.001?`<${a.format(.001)}`:a.format(e),day:e=>l.format(l1(e)),shortDay:e=>o.format(l1(e)),month:e=>d.format(l1(e)),monthName:e=>c.format(e),weekday:e=>u.format(e),weekdayLong:e=>h.format(e)}},[n]),[a,l]=(0,i.useState)(()=>{let e=am(aI);return e?.ok?e.data:null}),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)("overview"),[h,p]=(0,i.useState)("30d");(0,i.useEffect)(()=>{let e,t=!1,n=()=>{ag(aI).then(r=>{if(!t){if(!r.ok||r.data.error)throw Error(r.data.error??`HTTP ${r.status}`);l(r.data),d(null),r.data.scan&&(e=setTimeout(n,1e3))}}).catch(e=>{t||d(e instanceof Error?e.message:String(e))})};return n(),()=>{t=!0,clearTimeout(e)}},[]);let m=(0,i.useMemo)(()=>{let e=new Date;return e.setHours(0,0,0,0),e},[]),g=(0,i.useMemo)(()=>a?.records??[],[a]),f=(0,i.useMemo)(()=>{let e=l5(h,m);return e?g.filter(t=>t.day>=e):g},[g,h,m]);if(!a)return(0,r.jsx)("div",{className:"settings-page",children:o?(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:o}):(0,r.jsx)(iY,{label:t("i18n.loading")})});let x=a.scan,v=[{value:"overview",label:t("usage.overview")},{value:"models",label:t("common.models")},{value:"projects",label:t("usage.projects")},{value:"timeline",label:t("usage.timeline")},{value:"activity",label:t("usage.activity")}],y=[{value:"7d",label:t("usage.days",{count:7})},{value:"30d",label:t("usage.days",{count:30})},{value:"90d",label:t("usage.days",{count:90})},{value:"all",label:t("usage.rangeAll")}];return e=0===g.length?x?null:(0,r.jsx)(iJ,{children:t("usage.empty")}):"activity"===c?(0,r.jsx)(oc,{records:g,today:m,scanning:!!x,format:s,t:t}):0===f.length?(0,r.jsx)(iJ,{children:t("usage.emptyRange")}):"overview"===c?(0,r.jsx)(oi,{records:f,range:h,today:m,format:s,t:t},h):"models"===c?(0,r.jsx)(oo,{groups:l6(f,e=>e.model),nameLabel:t("usage.model"),limit:10,format:s,t:t}):"projects"===c?(0,r.jsx)(oo,{groups:l6(f,e=>e.project),nameLabel:t("usage.project"),name:e=>e?e.split(/[\\/]/).filter(Boolean).pop()??e:t("usage.unknownProject"),limit:10,format:s,t:t}):(0,r.jsx)(od,{records:f,format:s,t:t}),(0,r.jsxs)("div",{className:"settings-page usage-page",children:[o&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:o}),x&&(0,r.jsxs)("p",{role:"status",className:"usage-scan",children:[(0,r.jsx)("span",{children:t("usage.scanning",{done:s.count(x.done),total:s.count(x.total)})}),(0,r.jsx)("span",{className:"usage-scan-track","aria-hidden":"true",children:(0,r.jsx)("span",{style:{width:`${x.total?x.done/x.total*100:0}%`}})})]}),(0,r.jsxs)("div",{className:"usage-toolbar",children:[(0,r.jsx)(i8,{label:t("settings.usage"),options:v,value:c,onChange:u}),"activity"!==c&&(0,r.jsx)(i8,{label:t("usage.range"),options:y,value:h,onChange:p})]}),e]})}function on({items:e}){return(0,r.jsx)("dl",{className:"usage-stats",children:e.map(e=>(0,r.jsxs)("div",{className:"usage-stat",children:[(0,r.jsx)("dt",{children:e.label}),(0,r.jsx)("dd",{className:"usage-stat-value",title:e.value,children:e.value}),e.detail&&(0,r.jsx)("dd",{className:"usage-stat-detail",children:e.detail})]},e.label))})}function or({points:e,selected:t,onSelect:n,start:i,end:s,peakLabel:a}){let l=Math.max(...e.map(e=>e.value),0);return(0,r.jsxs)("div",{className:"usage-chart",children:[(0,r.jsx)("span",{className:"usage-chart-peak",children:a}),(0,r.jsx)("div",{className:"usage-bars",style:{"--usage-bar-count":e.length},children:e.map(e=>(0,r.jsx)("button",{type:"button",className:"usage-bar",style:{"--usage-bar":l>0?`${e.value/l*100}%`:"0%"},title:e.title,"aria-label":e.title,"aria-pressed":t===e.key,"data-dimmed":t&&t!==e.key?"":void 0,onClick:()=>n(e.key)},e.key))}),(0,r.jsxs)("div",{className:"usage-chart-axis",children:[(0,r.jsx)("span",{children:i}),(0,r.jsx)("span",{children:s})]})]})}function oi({records:e,range:t,today:n,format:s,t:a}){let[l,o]=(0,i.useState)(null),d=l3(e),c=new Set(e.map(e=>e.day)).size,u=l5(t,n)??e.reduce((e,t)=>t.day<e?t.day:e,e[0].day),h=l0(n),p=l9(u,h,"day").length>120?"week":"day",m=new Map(l6(e,e=>l7(e.day,p)).map(e=>[e.key,e])),g=l9(u,h,p),f=Math.max(...g.map(e=>m.get(e)?.cost??0)),x=g.map(e=>{let t=m.get(e);return{key:e,value:t?.cost??0,title:a("usage.cell",{date:oe(e,p,s,a),cost:s.cost(t?.cost??0),tokens:s.tokens(t?.tokens??0)})}}),v=l?m.get(l)?.records??[]:e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(on,{items:[{label:a("usage.totalCost"),value:s.cost(d.cost)},{label:a("usage.totalTokens"),value:s.tokens(d.tokens),detail:a("usage.cacheShare",{share:s.percent(d.cacheRead/Math.max(d.tokens,1))})},{label:a("usage.messages"),value:s.count(d.messages)},{label:a("usage.avgPerDay"),value:s.cost(d.cost/Math.max(c,1)),detail:a("usage.activeDaysDetail",{count:c})}]}),(0,r.jsx)(iX,{title:"day"===p?a("usage.dailyCost"):a("usage.weeklyCost"),children:(0,r.jsx)(or,{points:x,selected:l,onSelect:e=>o(t=>t===e?null:e),start:oe(g[0],p,s,a),end:oe(g[g.length-1],p,s,a),peakLabel:a("usage.peak",{cost:s.cost(f)})})}),(0,r.jsx)(iX,{title:l?oe(l,p,s,a):a("usage.topModels"),action:l&&(0,r.jsx)("button",{type:"button",className:"usage-link",onClick:()=>o(null),children:a("usage.clearSelection")}),children:(0,r.jsx)(oo,{groups:l6(v,e=>e.model),nameLabel:a("usage.model"),limit:5,format:s,t:a},l??"")})]})}let os=e=>{let t=e.input+e.cacheWrite;return t>0?e.cacheRead/t:null},oa=e=>e.tokens>0?e.cost/e.tokens*1e6:null,ol={input:e=>e.input,output:e=>e.output,cacheRead:e=>e.cacheRead,cacheWrite:e=>e.cacheWrite,cacheRatio:os,tokens:e=>e.tokens,cost:e=>e.cost,costPerMillion:oa};function oo({groups:e,nameLabel:t,name:n=e=>e||"—",limit:s=1/0,defaultSort:a={key:"cost",desc:!0},detail:l,format:o,t:d}){let[c,u]=(0,i.useState)(a),[h,p]=(0,i.useState)(!1),[m,g]=(0,i.useState)(new Set),f=e.reduce((e,t)=>e+t.cost,0),x=e.reduce((e,t)=>e+t.tokens,0),v=eX()&&"tokens"===c.key,y=[...e].sort((e,t)=>{let n="name"===c.key?e.key.localeCompare(t.key,void 0,{numeric:!0}):(ol[c.key](e)??-1)-(ol[c.key](t)??-1);return c.desc?-n:n}),b=h?y:y.slice(0,s),w=e.length-s,j=e=>g(t=>{let n=new Set(t);return n.delete(e)||n.add(e),n}),k=[{sort:"input",label:d("usage.input"),width:64,secondary:!0,cell:e=>o.tokens(e.input)},{sort:"output",label:d("usage.output"),width:64,secondary:!0,cell:e=>o.tokens(e.output)},{sort:"cacheRead",label:d("usage.cacheRead"),width:68,secondary:!0,cell:e=>o.tokens(e.cacheRead)},{sort:"cacheWrite",label:d("usage.cacheWrite"),width:68,secondary:!0,cell:e=>o.tokens(e.cacheWrite)},{sort:"cacheRatio",label:d("usage.cacheRatio"),hint:d("usage.cacheRatioHint"),width:64,secondary:!0,cell:e=>{let t=os(e);return null===t?"—":`${t.toFixed(1)}\xd7`}},{sort:"tokens",label:d("usage.tokensColumn"),width:68,cell:e=>o.tokens(e.tokens)},{sort:"cost",label:d("usage.cost"),width:68,strong:!0,cell:e=>o.cost(e.cost)},{sort:"costPerMillion",label:d("usage.costPerMillion"),hint:d("usage.costPerMillionHint"),width:56,secondary:!0,cell:e=>{let t=oa(e);return null===t?"—":o.unitCost(t)}},{label:d("usage.tokenShare"),width:64,secondary:!0,cell:e=>x>0?o.share(e.tokens/x):"—"},{label:v?d("usage.tokenShare"):d("usage.costShare"),width:56,cell:e=>v?x>0?o.share(e.tokens/x):"—":f>0?o.share(e.cost/f):"—"}],S=k.length+1,C=(e,t)=>(0,r.jsx)("button",{type:"button",className:"usage-sort",onClick:()=>u(t=>({key:e,desc:t.key===e?!t.desc:"name"!==e})),children:t}),N=e=>e&&c.key===e?c.desc?"descending":"ascending":void 0;return(0,r.jsx)("div",{className:"usage-table-scroll",children:(0,r.jsxs)("table",{className:"usage-table",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{"aria-sort":N("name"),children:C("name",t)}),k.map((e,t)=>(0,r.jsx)("th",{className:e.secondary?"is-secondary":void 0,style:{width:e.width},title:e.hint,"aria-sort":N(e.sort),children:e.sort?C(e.sort,e.label):e.label},t))]})}),(0,r.jsxs)("tbody",{children:[b.map(e=>{let t=m.has(e.key);return(0,r.jsxs)(i.Fragment,{children:[(0,r.jsxs)("tr",{className:l?"usage-period-row":void 0,onClick:l?()=>j(e.key):void 0,children:[(0,r.jsxs)("td",{className:"usage-table-name",title:e.key,children:[l?(0,r.jsxs)("button",{type:"button",className:"usage-disclosure","aria-expanded":t,onClick:t=>{t.stopPropagation(),j(e.key)},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})}),(0,r.jsx)("span",{children:n(e.key)})]}):(0,r.jsx)("span",{children:n(e.key)}),e.unpriced>0&&(0,r.jsx)("span",{className:"usage-badge",title:d("usage.unpricedNote",{count:e.unpriced}),children:d("usage.unpriced")})]}),k.map((t,n)=>(0,r.jsx)("td",{className:[t.secondary&&"is-secondary",t.strong&&"is-strong"].filter(Boolean).join(" ")||void 0,children:t.cell(e)},n))]}),l&&t&&(0,r.jsx)("tr",{className:"usage-period-detail",children:(0,r.jsx)("td",{colSpan:S,children:l(e)})})]},e.key)}),w>0&&(0,r.jsx)("tr",{className:"usage-table-more",children:(0,r.jsx)("td",{colSpan:S,children:(0,r.jsx)("button",{type:"button",className:"usage-link",onClick:()=>p(!h),children:h?d("usage.showFewer"):d("usage.showMore",{count:w})})})})]})]})})}function od({records:e,format:t,t:n}){let[s,a]=(0,i.useState)("day"),l=[{value:"day",label:n("usage.grainDay")},{value:"week",label:n("usage.grainWeek")},{value:"month",label:n("usage.grainMonth")}];return(0,r.jsx)(iX,{action:(0,r.jsx)(i8,{label:n("usage.timeline"),options:l,value:s,onChange:a}),children:(0,r.jsx)(oo,{groups:l6(e,e=>l7(e.day,s)),nameLabel:n("usage.period"),name:e=>oe(e,s,t,n),defaultSort:{key:"name",desc:!0},detail:e=>(0,r.jsx)(oo,{groups:l6(e.records,e=>e.model),nameLabel:n("usage.model"),limit:8,format:t,t:n}),format:t,t:n},s)})}function oc({records:e,today:t,scanning:n,format:s,t:a}){let[l,o]=(0,i.useState)(null),d=(0,i.useRef)(null),c=(0,i.useMemo)(()=>{let n,r,i=l2(t,-((t.getDay()+6)%7)-364),a=e.filter(e=>e.day>=l0(i)),l=new Map(l6(a,e=>e.day).map(e=>[e.key,e])),o=(n=[...l.values()].map(e=>e.cost).filter(e=>e>0).sort((e,t)=>e-t),r=[.25,.5,.75].map(e=>n[Math.floor(e*(n.length-1))]??0),e=>e<=0?0:1+r.filter(t=>e>t).length),d=Array.from({length:371},(e,n)=>{let r=l2(i,7*Math.floor(n/7)+n%7);return{key:l0(r),date:r,future:r>t}}),c=[];for(let e=1;e<53;e+=1){let t=d[7*e].date;t.getMonth()!==d[(e-1)*7].date.getMonth()&&c.push({column:e,label:s.monthName(t)})}let u=l6(e,e=>e.day),h=u.reduce((e,t)=>!e||t.cost>e.cost?t:e,null);return{cells:d,months:c,days:l,level:o,yearCost:a.reduce((e,t)=>e+t.cost,0),streak:function(e,t){let n=0,r=0,i=null;for(let t of[...e].sort())n=Math.max(n,r=i&&l0(l2(l1(i),1))===t?r+1:1),i=t;let s=e.has(l0(t))?t:l2(t,-1),a=0;for(;e.has(l0(s));)a+=1,s=l2(s,-1);return{current:a,longest:n}}(new Set(u.map(e=>e.key)),t),activeDays:u.length,peak:h,topModel:l6(e,e=>e.model)[0],weekdays:[0,2,4].map(e=>({row:e,label:s.weekday(l2(i,e))}))}},[e,t,s]);(0,i.useLayoutEffect)(()=>{let e=d.current;e&&(e.scrollLeft=e.scrollWidth)},[c]);let u=l?c.days.get(l):void 0;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(on,{items:[{label:a("usage.activeDays"),value:a("usage.days",{count:c.activeDays})},{label:a("usage.streak"),value:a("usage.days",{count:c.streak.current}),detail:a("usage.longest",{count:c.streak.longest})},{label:a("usage.peakDay"),value:c.peak?s.cost(c.peak.cost):"—",detail:c.peak&&s.day(c.peak.key)},{label:a("usage.topModel"),value:c.topModel?.key??"—",detail:c.topModel&&s.cost(c.topModel.cost)}]}),(0,r.jsxs)(iX,{title:a("usage.dailyCost"),action:(0,r.jsxs)("span",{className:"usage-legend","aria-hidden":"true",children:[a("usage.less"),[0,1,2,3,4].map(e=>(0,r.jsx)("span",{className:"usage-cell","data-level":e},e)),a("usage.more")]}),children:[(0,r.jsx)("div",{ref:d,className:"usage-heatmap-scroll",children:(0,r.jsxs)("div",{className:"usage-heatmap",style:{"--usage-weeks":53},children:[c.months.map(e=>(0,r.jsx)("span",{className:"usage-month",style:{gridColumn:e.column+2},children:e.label},e.column)),c.weekdays.map(e=>(0,r.jsx)("span",{className:"usage-weekday",style:{gridRow:e.row+2},children:e.label},e.row)),c.cells.map((e,t)=>{let n=c.days.get(e.key),i={gridColumn:Math.floor(t/7)+2,gridRow:t%7+2};if(e.future)return(0,r.jsx)("span",{className:"usage-cell","data-future":"",style:i},e.key);let d=a("usage.cell",{date:s.day(e.key),cost:s.cost(n?.cost??0),tokens:s.tokens(n?.tokens??0)});return(0,r.jsx)("button",{type:"button",className:"usage-cell","data-level":c.level(n?.cost??0),"aria-pressed":l===e.key,disabled:!n,style:i,title:d,"aria-label":d,onClick:()=>o(t=>t===e.key?null:e.key)},e.key)})]})}),(0,r.jsx)("p",{className:"usage-caption",children:a("usage.yearSummary",{cost:s.cost(c.yearCost),days:c.days.size})})]}),u&&(0,r.jsx)(iX,{title:s.day(u.key),action:(0,r.jsx)("button",{type:"button",className:"usage-link",onClick:()=>o(null),children:a("usage.clearSelection")}),children:(0,r.jsx)(oo,{groups:l6(u.records,e=>e.model),nameLabel:a("usage.model"),limit:8,format:s,t:a},u.key)}),(0,r.jsx)(og,{records:e,scanning:n,format:s,t:a})]})}let ou=[{key:"morning",from:5,to:11},{key:"daytime",from:12,to:16},{key:"evening",from:17,to:21},{key:"night",from:22,to:4}],oh=e=>ou.findIndex(t=>t.from<=t.to?e>=t.from&&e<=t.to:e>=t.from||e<=t.to),op=(e,t)=>`${String(e).padStart(2,"0")}:${t}`;function om({rows:e,percent:t}){let n=e.reduce((e,t)=>e+t.value,0),i=Math.max(...e.map(e=>e.value),0);return(0,r.jsx)("div",{className:"usage-share-rows",children:e.map(e=>(0,r.jsxs)("div",{className:"usage-share-row","data-top":e.value===i&&i>0?"":void 0,children:[(0,r.jsx)("span",{className:"usage-share-label",children:e.label}),void 0!==e.span&&(0,r.jsx)("span",{className:"usage-share-span",children:e.span}),(0,r.jsx)("span",{className:"usage-share-track","aria-hidden":"true",children:(0,r.jsx)("span",{style:{width:`${i>0?e.value/i*100:0}%`}})}),(0,r.jsx)("span",{className:"usage-share-value",children:n>0?t(e.value/n):"—"})]},e.key))})}function og({records:e,scanning:t,format:n,t:i}){let s=e.filter(e=>null!==e.hour);if(0===s.length)return null;let a=e=>e.input+e.output+e.cacheRead+e.cacheWrite,l=[0,0,0,0],o=[0,0,0,0,0,0,0],d=l6(s,e=>String(e.hour));for(let e of s)l[oh(e.hour)]+=a(e),o[(l1(e.day).getDay()+6)%7]+=a(e);let c=d.reduce((e,t)=>t.tokens>e.tokens?t:e),u=Number(c.key),h=l3(s),p=new Set(s.map(e=>`${e.day} ${e.hour}`)).size,m=s.map(e=>e.day).sort(),g=new Date(2024,0,1);return(0,r.jsxs)(iX,{title:i("usage.hourProfile"),children:[(0,r.jsx)("p",{className:"usage-caption usage-profile-summary",children:i("usage.profileSummary",{from:n.day(m[0]),to:n.day(m[m.length-1]),hours:n.count(p),tokens:n.tokens(h.tokens),cost:n.cost(h.cost)})}),t&&(0,r.jsx)("p",{className:"usage-caption",children:i("usage.hourCalculating")}),(0,r.jsxs)("div",{className:"usage-profile",children:[(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"usage-subtitle",children:i("usage.whenYouWork")}),(0,r.jsx)(om,{percent:n.percent,rows:ou.map((e,t)=>({key:e.key,label:i(`usage.part.${e.key}`),span:`${op(e.from,"00")}–${op(e.to,"59")}`,value:l[t]}))})]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"usage-subtitle",children:i("usage.byWeekday")}),(0,r.jsx)(om,{percent:n.percent,rows:o.map((e,t)=>({key:String(t),label:n.weekdayLong(l2(g,t)),value:e}))})]})]}),(0,r.jsx)("p",{className:"usage-caption",children:i("usage.peakHour",{span:`${op(u,"00")}–${op(u,"59")}`,tokens:n.tokens(c.tokens),cost:n.cost(c.cost)})})]})}let of=null;async function ox(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(of)return of;let t=(async()=>{try{let t=await fetch("/api/push/config");if(!t.ok)return!1;let{publicKey:n}=await t.json();if(!n)return!1;let r=await navigator.serviceWorker.ready,i=await r.pushManager.getSubscription();return i||(i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){let t="=".repeat((4-e.length%4)%4),n=atob((e+t).replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}(n)})),(await fetch("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscription:i.toJSON(),locale:e})})).ok}catch{return of=null,!1}})();return of=t,t.then(e=>{e||of!==t||(of=null)}),t}let ov={general:(0,r.jsx)("path",{d:"M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6"}),models:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1"}),(0,r.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 14h3M1 9h3M1 14h3"})]}),images:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("circle",{cx:"9",cy:"9",r:"2"}),(0,r.jsx)("path",{d:"m21 15-3.09-3.09a2 2 0 0 0-2.82 0L6 21"})]}),skills:(0,r.jsx)("path",{d:"M2 4h6a4 4 0 0 1 4 4v13a3 3 0 0 0-3-3H2zM22 4h-6a4 4 0 0 0-4 4v13a3 3 0 0 1 3-3h7z"}),plugins:(0,r.jsx)("path",{d:"M12 22v-5M9 8V2M15 8V2M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8z"}),usage:(0,r.jsx)("path",{d:"M3 3v16a2 2 0 0 0 2 2h16M18 17V9M13 17V5M8 17v-3"})};function oy({section:e}){return"agents"===e?(0,r.jsx)(G,{size:15}):(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"settings-nav-icon",children:ov[e]})}function ob({preference:e}){return"light"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",className:"settings-theme-icon",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.42 1.42M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.42-1.41M17.66 6.34l1.41-1.41"})]}):"dark"===e?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"settings-theme-icon",children:(0,r.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"settings-theme-icon",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M8 21h8M12 17v4"})]})}function ow({sessionId:e,onSessionReloaded:t,quoteSelectionEnabled:n,onQuoteSelectionChange:s,soundEnabled:a,onSoundToggle:l}){let{locale:o,setLocale:d,supportedLocales:c,t:u}=(0,w.s)(),{preference:h,setThemePreference:p,palette:m,setThemePalette:g}=n3(),{scheme:f,setFontScheme:b}={scheme:(0,i.useSyncExternalStore)(au,ad,()=>"sarasa"),setFontScheme:ac},{width:j,setWidth:k,fontSize:S,setFontSize:C}=tn(),[N,E]=(0,i.useState)(()=>{let e=am(av);return e?.ok&&!e.data.error?e.data:null}),[M,I]=(0,i.useState)(!1),[L,T]=(0,i.useState)(null),[$,R]=(0,i.useState)(!1),[W,P]=(0,i.useState)(!0),[z,D]=(0,i.useState)(!1),[A,F]=(0,i.useState)(!1),[B,O]=(0,i.useState)(null),[H,U]=(0,i.useState)(!1),[_,q]=(0,i.useState)(null),[K,V]=(0,i.useState)(()=>am(ax)?.data.enabled===!0),[J,Y]=(0,i.useState)(!1),[Z,X]=(0,i.useState)("");(0,i.useEffect)(()=>{R(rg()),P(aF()),D(y()),F(ta())},[]),(0,i.useEffect)(()=>{ag(ax).then(e=>V(e.ok&&!0===e.data.enabled)).catch(()=>{})},[]),(0,i.useEffect)(()=>ir(O),[]);let G=[{id:"light",label:u("settings.themeLight")},{id:"dark",label:u("settings.themeDark")},{id:"auto",label:u("settings.themeSystem")}],Q=[{id:"default",label:u("settings.paletteDefault")},{id:"claude",label:u("settings.paletteClaude")}],ee=[{id:"sarasa",label:u("settings.fontSchemeSarasa")},{id:"claude",label:u("settings.fontSchemeClaude")}];(0,i.useEffect)(()=>{let e=!1;return ag(av).then(async t=>{let n=t.data;if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||E(n)}).catch(t=>{e||T(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let et=async n=>{I(!0),T(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);E(i),e&&(await im(e,{type:"reload"}),t())}catch(e){T(e instanceof Error?e.message:String(e))}finally{I(!1)}},en=async()=>{if(!H){U(!0),q(null);try{if(!("Notification"in window))throw Error("unsupported or not permitted");let e="default"===Notification.permission?await Notification.requestPermission():Notification.permission;if("granted"!==e||!await ox(o))throw Error("unsupported or not permitted");q({kind:"ok",message:u("settings.pushRegistered")})}catch(e){q({kind:"error",message:`${u("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{U(!1)}}},er=async()=>{Y(!0),X("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{X(u("auth.logoutFailed"))}finally{Y(!1)}},ei=(0,r.jsx)("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,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})}),es=(e,t,n,i)=>(0,r.jsx)(iG,{label:e,description:t,children:(0,r.jsx)(i7,{checked:n,label:e,onChange:i})}),ea=(e,t,n,i,s,a,l,o)=>(0,r.jsxs)("div",{className:"settings-range",children:[(0,r.jsx)("input",{id:e,type:"range",min:n,max:i,step:s,value:t,onChange:e=>o(Number(e.target.value))}),(0,r.jsxs)("output",{htmlFor:e,children:[t,"px"]}),(0,r.jsx)(i5,{variant:"ghost",size:"small",className:"settings-chat-reset",title:l,"aria-label":l,disabled:t===a,onClick:()=>o(a),children:ei})]});return(0,r.jsxs)("div",{className:"settings-page",children:[(0,r.jsxs)(iX,{title:u("settings.appearance"),children:[(0,r.jsx)(iG,{label:u("settings.theme"),stacked:!0,children:(0,r.jsx)("div",{role:"radiogroup","aria-label":u("settings.theme"),className:"settings-segmented",children:G.map(e=>(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":h===e.id,onClick:()=>p(e.id),className:"settings-segmented-option",children:[(0,r.jsx)(ob,{preference:e.id}),(0,r.jsx)("span",{className:"settings-segmented-label",children:e.label})]},e.id))})}),(0,r.jsx)(iG,{label:u("settings.palette"),stacked:!0,children:(0,r.jsx)("div",{role:"radiogroup","aria-label":u("settings.palette"),className:"settings-segmented",children:Q.map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":m===e.id,onClick:()=>g(e.id),className:"settings-segmented-option",children:(0,r.jsx)("span",{className:"settings-segmented-label",children:e.label})},e.id))})}),(0,r.jsx)(iG,{label:u("settings.fontScheme"),stacked:!0,children:(0,r.jsx)("div",{role:"radiogroup","aria-label":u("settings.fontScheme"),className:"settings-segmented",children:ee.map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":f===e.id,onClick:()=>b(e.id),className:"settings-segmented-option",children:(0,r.jsx)("span",{className:"settings-segmented-label",children:e.label})},e.id))})}),(0,r.jsx)(iG,{label:u("common.language"),stacked:!0,children:(0,r.jsx)("div",{role:"radiogroup","aria-label":u("common.language"),className:"settings-segmented",children:c.map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":o===e.id,onClick:()=>d(e.id),className:"settings-segmented-option",children:(0,r.jsx)("span",{className:"settings-segmented-label",children:e.label})},e.id))})}),(0,r.jsx)(iG,{label:u("settings.chatContentWidth"),description:u("settings.chatContentWidthDescription"),htmlFor:"settings-chat-content-width",stacked:!0,children:ea("settings-chat-content-width",j,820,2e3,10,820,u("settings.resetChatContentWidth"),k)}),(0,r.jsx)(iG,{label:u("settings.chatContentFontSize"),description:u("settings.chatContentFontSizeDescription"),htmlFor:"settings-chat-content-font-size",stacked:!0,children:ea("settings-chat-content-font-size",S,12,24,1,14,u("settings.resetChatContentFontSize"),C)}),es(u("settings.thinkingExpandedDefault"),u("settings.thinkingExpandedDefaultDescription"),$,e=>{window.localStorage.setItem(rp,String(e)),window.dispatchEvent(new Event(rm)),R(e)})]}),(0,r.jsxs)(iX,{title:u("settings.chat"),children:[es(u("settings.shiftEnterToSend"),u("settings.shiftEnterToSendDescription"),A,e=>{window.localStorage.setItem(ts,String(e)),F(e)}),es(u("settings.autoSessionTitle"),u("settings.autoSessionTitleDescription"),W,e=>{window.localStorage.setItem(aA,String(e)),P(e)}),es(u("settings.quoteSelection"),u("settings.quoteSelectionDescription"),n,s),es(u("settings.sidebarSingleProject"),u("settings.sidebarSingleProjectDescription"),z,e=>{window.localStorage.setItem(x,String(e)),window.dispatchEvent(new Event(v)),D(e)}),N?.isWindows&&(0,r.jsx)(iG,{label:u("settings.usePowerShell"),description:u("settings.shellToolDescription"),children:(0,r.jsx)(i7,{checked:N.powerShellEnabled,loading:M,label:u("settings.usePowerShell"),onChange:e=>void et(e)})}),L&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:L})]}),(0,r.jsxs)(iX,{title:u("settings.notifications"),children:[es(u("settings.completionSound"),u("settings.completionSoundDescription"),a,l),B&&(0,r.jsx)(iG,{label:u("settings.browserNotifications"),description:u("settings.browserNotificationsDescription"),children:"granted"===B?(0,r.jsx)("span",{className:"settings-row-status",children:u("settings.browserNotificationsOn")}):"denied"===B?(0,r.jsx)("span",{className:"settings-row-status",children:u("settings.browserNotificationsBlocked")}):(0,r.jsx)(i5,{size:"small",onClick:()=>void Notification.requestPermission().then(O),children:u("settings.browserNotificationsEnable")})}),(0,r.jsx)(iG,{label:u("settings.pushPermission"),description:u("settings.pushPermissionDescription"),children:(0,r.jsx)(i5,{size:"small",disabled:H,onClick:()=>void en(),children:H?u("settings.pushRegisterLoading"):u("settings.pushRegister")})}),_&&(0,r.jsx)("p",{role:"status",className:`settings-row-message ${"ok"===_.kind?"is-success":"is-error"}`,children:_.message})]}),(0,r.jsxs)(iX,{title:u("settings.about"),children:[(0,r.jsx)(se,{showCurrentVersion:!0}),K&&(0,r.jsx)(iG,{label:u("auth.logOut"),description:u("settings.logOutDescription"),children:(0,r.jsx)(i5,{size:"small",variant:"danger",disabled:J,onClick:()=>void er(),children:J?u("auth.loggingOut"):u("auth.logOut")})}),Z&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:Z})]})]})}function oj({cwd:e,sessionId:t,initialSection:n,onClose:s,onSessionReloaded:a,onModelsChanged:l,quoteSelectionEnabled:o,onQuoteSelectionChange:d,soundEnabled:c,onSoundToggle:u}){let{t:h}=(0,w.s)(),[p,m]=(0,i.useState)(n),[g,f]=(0,i.useState)("nav"),[x,v]=(0,i.useState)(()=>new Set([p])),y=[{label:h("settings.title"),sections:[{id:"general",label:h("settings.general"),requiresProject:!1},{id:"usage",label:h("settings.usage"),requiresProject:!1}]},{label:h("settings.navAgent"),sections:[{id:"models",label:h("common.models"),requiresProject:!1},{id:"agents",label:h("common.agents"),requiresProject:!0},{id:"images",label:h("settings.images"),requiresProject:!1},{id:"skills",label:h("common.skills"),requiresProject:!0},{id:"plugins",label:h("common.plugins"),requiresProject:!0}]}],b=y.flatMap(e=>e.sections),j=(0,i.useRef)(!1),k=(0,i.useCallback)(e=>{j.current=e},[]),S=(0,i.useCallback)(()=>{(!j.current||window.confirm(h("models.discardConfirm")))&&s()},[s,h]);(0,i.useEffect)(()=>aD(n),[n]),(0,i.useEffect)(()=>aL(e),[e]),(0,i.useEffect)(()=>aT,[]),(0,i.useEffect)(()=>{let e=e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),S())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[S]),(0,i.useEffect)(()=>{e||"skills"!==p&&"agents"!==p&&"plugins"!==p||(m("general"),v(e=>new Set(e).add("general")),aD("general"))},[e,p]);let C=b.find(e=>e.id===p)?.label,N=(0,i.useRef)(null),E=(e,t)=>x.has(e)?(0,r.jsx)("div",{hidden:p!==e,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{role:"dialog","aria-modal":"true","aria-label":h("settings.title"),onClick:e=>{e.target===e.currentTarget&&S()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface","data-pane":g,children:[(0,r.jsxs)("nav",{"aria-label":h("settings.title"),className:"settings-nav",children:[(0,r.jsx)("strong",{className:"settings-nav-title",children:h("settings.title")}),y.map(t=>(0,r.jsxs)("div",{role:"group","aria-label":t.label,className:"settings-nav-group",children:[(0,r.jsx)("span",{className:"settings-nav-group-label",children:t.label}),t.sections.map(t=>{let n=t.requiresProject&&!e;return(0,r.jsxs)("button",{type:"button",className:"settings-nav-item",disabled:n,title:n?h("settings.projectRequired"):void 0,"aria-current":p===t.id?"page":void 0,onClick:()=>{var e;return e=t.id,void(v(t=>new Set(t).add(e)),m(e),aD(e),f("section"))},children:[(0,r.jsx)(oy,{section:t.id}),(0,r.jsx)("span",{className:"settings-nav-label",children:t.label}),(0,r.jsx)("svg",{className:"settings-nav-chevron",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]},t.id)})]},t.label))]}),(0,r.jsxs)("div",{className:"settings-dialog-content",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("button",{type:"button",className:"settings-nav-back",onClick:()=>{let e=N.current?.querySelector(".settings-section-host:not([hidden]) [data-settings-back]");e?e.click():f("nav")},"aria-label":h("i18n.back"),children:(0,r.jsx)("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,r.jsx)("path",{d:"m15 18-6-6 6-6"})})}),(0,r.jsx)("strong",{className:"settings-dialog-title",children:C})]}),(0,r.jsxs)("main",{ref:N,className:"settings-dialog-main",children:[E("general",(0,r.jsx)(ow,{sessionId:t,onSessionReloaded:a,quoteSelectionEnabled:o,onQuoteSelectionChange:d,soundEnabled:c,onSoundToggle:u})),E("models",(0,r.jsx)(lg,{embedded:!0,onClose:S,cwd:e,onModelsChanged:l,onDirtyChange:k})),e&&E("agents",(0,r.jsx)(lP,{embedded:!0,cwd:e,sessionId:t,onClose:s,onReloaded:a},e)),E("images",(0,r.jsx)(lJ,{sessionId:t,onReloaded:a})),e&&E("skills",(0,r.jsx)(lk,{embedded:!0,cwd:e,onClose:s},e)),e&&E("plugins",(0,r.jsx)(lK,{embedded:!0,cwd:e,sessionId:t,onClose:s,onReloaded:a},e)),E("usage",(0,r.jsx)(ot,{}))]})]}),(0,r.jsx)("button",{type:"button",onClick:S,title:h("i18n.close"),"aria-label":h("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]})})}function ok({cwd:e,busy:t,error:n,onCancel:s,onConfirm:a}){let{t:l}=(0,w.s)(),o=(0,i.useRef)(null),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;return d.current?.focus(),()=>{e?.isConnected?e.focus():document.querySelector('[data-dialog-focus-fallback="true"]')?.focus()}},[]),(0,i.useEffect)(()=>{t&&o.current?.focus()},[t]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||s()},children:(0,r.jsxs)("div",{ref:o,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title",tabIndex:-1,onKeyDown:e=>{if("Escape"===e.key&&!t){e.preventDefault(),s();return}if("Tab"!==e.key)return;let n=Array.from(o.current?.querySelectorAll("button:not(:disabled)")??[]);if(0===n.length){e.preventDefault(),o.current?.focus();return}let r=n[0],i=n[n.length-1];e.shiftKey&&(document.activeElement===r||document.activeElement===o.current)?(e.preventDefault(),i.focus()):e.shiftKey||document.activeElement!==i||(e.preventDefault(),r.focus())},style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"var(--warning)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:l("trust.dialogTitle")}),(0,r.jsx)("div",{style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:l("trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),n&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:12,lineHeight:1.5},children:n})]})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:d,type:"button",onClick:s,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"transparent",color:"var(--text-muted)",cursor:t?"not-allowed":"pointer",fontSize:12},children:l("trust.cancel")}),(0,r.jsx)("button",{type:"button",onClick:a,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--primary)",borderRadius:5,background:"var(--primary)",color:"var(--primary-contrast)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontSize:12},children:l(t?"trust.trusting":"trust.trustProject")})]})]})})}function oS(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function oC(e){let t=e,n=t.branchPreview,r=oS(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&oS(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function oN(e){if(e.length>1)return e;if(0===e.length)return[];let t=oC(e[0]).node;return t.children.length>1?t.children:[]}function oE(e){if(e.length>1)return!0;let t=[...e];for(;t.length>0;){let e=t.pop();if(e.children.length>1)return!0;for(let n of e.children)t.push(n)}return!1}function oM({node:e,activePathIds:t,depth:n,isLast:i,parentLines:s,onSelect:a}){let{node:l,skipped:o,branchPreview:d,labelEntry:c}=oC(e),u=t.has(l.entry.id),h=t.has(e.entry.id)||t.has(l.entry.id),p=d?.text??function(e){if("message"===e.type&&oS(e)){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(c),m=d?d.role??null:oS(c)?c.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>a(l.entry.id),children:[s.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:10,color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"color-mix(in srgb, var(--accent) 8%, transparent)":"var(--bg-hover)",border:`1px solid ${"user"===m?"color-mix(in srgb, var(--accent) 20%, transparent)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),o>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",o]}),(0,r.jsx)("span",{style:{fontSize:11,color:u?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:p})]}),l.children.map((e,o)=>(0,r.jsx)(oM,{node:e,activePathIds:t,depth:n+1,isLast:o===l.children.length-1,parentLines:[...s,!i],onSelect:a},e.entry.id))]})}function oI({tree:e,activeLeafId:t,onLeafChange:n,hasSession:s}){let{t:a}=(0,w.s)(),l=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(e,t),[e,t]),o=oN(e),d=s?oE(e)&&0!==o.length?null:a("i18n.noBranches"):a("i18n.noActiveSession");return d?(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)"},children:d}):(0,r.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:o.map((e,t)=>(0,r.jsx)(oM,{node:e,activePathIds:l,depth:0,isLast:t===o.length-1,parentLines:[],onSelect:n},e.entry.id))})}function oL({tree:e,activeLeafId:t,onLeafChange:n,inline:s,open:a,onToggle:l,hasSession:o,compact:d,disabled:c=!1}){let{t:u}=(0,w.s)(),[h,p]=(0,i.useState)(!1),m=void 0!==a?a:h,g=o?oE(e)?null:u("i18n.noBranches"):u("i18n.noActiveSession"),f=oN(e),x=!g&&f.length>0,v=c||!x,y=(0,r.jsxs)("svg",{width:d?13:12,height:d?13:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(d?13:12),strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),b=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:m?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return s?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:(0,r.jsxs)("button",{className:"workspace-header-action",disabled:v,onClick:()=>{v||(l?l():p(e=>!e))},style:{display:"flex",alignItems:"center",justifyContent:d?"center":void 0,gap:6*!d,height:"100%",width:d?30:void 0,padding:d?0:"0 12px",background:m?"var(--bg-selected)":"none",border:"none",cursor:v?"not-allowed":"pointer",color:v?"var(--text-dim)":m?"var(--text)":"var(--text-muted)",opacity:v?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{v||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{v||(e.currentTarget.style.color=m?"var(--text)":"var(--text-muted)",e.currentTarget.style.background=m?"var(--bg-selected)":"none")},title:v?u("i18n.noBranches",{defaultValue:"没有分支"}):u("i18n.branches"),"aria-label":u("i18n.branches"),"aria-pressed":m,"data-top-panel-trigger":"branches",children:[y,!d&&(0,r.jsx)("span",{style:{lineHeight:1},children:u("i18n.branches")})]})}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>p(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:[y,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:u("i18n.branches")}),b]}),m&&(0,r.jsx)("div",{className:"branch-dropdown",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:(0,r.jsx)(oI,{tree:e,activeLeafId:t,onLeafChange:n,hasSession:o})})]})}function oT({mobile:e,disabled:t,menuOpen:n,exporting:s=!1,error:a,labels:l,onViewFullHistory:o,onExportMarkdown:d,onMenuOpenChange:c}){let u=(0,i.useRef)(null),[h,p]=(0,i.useState)(null);(0,i.useLayoutEffect)(()=>{if(!n)return void p(null);let e=()=>{let e=u.current?.getBoundingClientRect();e&&p({top:e.bottom,left:e.left})};e();let t=e=>{u.current?.contains(e.target)||c(!1)},r=e=>{"Escape"===e.key&&c(!1)};return window.addEventListener("resize",e),document.addEventListener("pointerdown",t,!0),document.addEventListener("keydown",r,!0),()=>{window.removeEventListener("resize",e),document.removeEventListener("pointerdown",t,!0),document.removeEventListener("keydown",r,!0)}},[n,c]);let m=t?"var(--text-dim)":"var(--text-muted)",g=(e,r)=>{t||(e.currentTarget.style.color=r||n?"var(--text)":"var(--text-muted)")};return(0,r.jsxs)("div",{ref:u,style:{display:"flex",alignItems:"stretch",height:"100%",position:"relative"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{t||c(!n)},disabled:t,title:t?l.unsaved:l.menu,"aria-label":l.menu,"aria-haspopup":"menu","aria-expanded":n,"data-active":n||void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":m,cursor:t?"not-allowed":"pointer",opacity:t?.45:1,flexShrink:0,transition:"color 0.1s, background 0.1s, opacity 0.1s, box-shadow 0.1s"},onMouseEnter:e=>g(e,!0),onMouseLeave:e=>g(e,!1),className:"workspace-header-action","data-mobile-toolbar-action":e?"history":void 0,children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:n?"var(--text)":m,flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),n&&!t&&h&&(0,r.jsxs)("div",{role:"menu","aria-label":l.menu,className:"menu-surface",style:{position:"fixed",top:h.top+2,left:Math.max(8,Math.min(h.left,window.innerWidth-210)),minWidth:195,zIndex:520},children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{c(!1),o()},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}),(0,r.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l.full})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",title:l.exportMarkdownTitle,disabled:s,onClick:()=>{d()},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),(0,r.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l.exportMarkdown}),s&&(0,r.jsxs)("svg",{className:"animate-spin",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",style:{marginLeft:6,flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round"})]})]}),a&&(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:11,color:"var(--danger)",lineHeight:1.35},children:a})]})]})}function o$({loading:e,prompt:t,translate:n}){return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":n("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:t?(0,r.jsx)("div",{className:"system-prompt-text",children:t}):(0,r.jsx)("div",{className:"system-prompt-empty",children:n(""===t?"system.empty":e?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
11
- .system-prompt-panel {
12
- display: flex;
13
- height: min(600px, 75dvh);
14
- min-height: 220px;
15
- flex-direction: column;
16
- background: var(--bg-panel);
17
- border-bottom: 1px solid var(--border);
18
- }
19
- .system-prompt-scroll {
20
- min-height: 0;
21
- flex: 1;
22
- overflow: auto;
23
- padding: 12px 16px;
24
- }
25
- .system-prompt-text {
26
- color: var(--text-muted);
27
- font-family: var(--font-mono);
28
- font-size: 12px;
29
- line-height: 1.6;
30
- overflow-wrap: anywhere;
31
- white-space: pre-wrap;
32
- }
33
- .system-prompt-empty {
34
- padding: 10px 0;
35
- color: var(--text-muted);
36
- font-size: 12px;
37
- }
38
- `})]})}function oR(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function oW({children:e}){return(0,r.jsx)("div",{className:"tool-definitions-empty",children:e})}function oP({loading:e,tools:t,translate:n}){let s=(0,i.useMemo)(()=>t?.filter(e=>e.active)??null,[t]),[a,l]=(0,i.useState)(null);(0,i.useEffect)(()=>{l(e=>s?.some(t=>t.name===e)?e:s?.[0]?.name??null)},[s]);let o=s?.find(e=>e.name===a)??s?.[0]??null,d=o?function(e){if(!e||!e.properties||"object"!=typeof e.properties)return[];let t=e.properties,n=new Set(Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[]);return Object.entries(t).map(([e,t])=>{let r=t&&"object"==typeof t?t:{};return{name:e,type:function e(t){let n=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:null;if(n)return n.map(t=>t&&"object"==typeof t?e(t):"unknown").filter((e,t,n)=>n.indexOf(e)===t).join(" | ");if(void 0!==t.const)return oR(t.const);if(Array.isArray(t.enum)&&t.enum.length>0&&void 0===t.type)return[...new Set(t.enum.map(e=>null===e?"null":typeof e))].join(" | ");let r=t.type,i=Array.isArray(r)?r.filter(e=>"string"==typeof e).join(" | "):"string"==typeof r?r:"string"==typeof t.$ref?t.$ref.split("/").pop()??"object":"unknown";if("array"===i){let n=t.items,r=n&&"object"==typeof n?e(n):"unknown";return`${r}[]`}return i}(r),description:"string"==typeof r.description?r.description:void 0,required:n.has(e),allowedValues:Array.isArray(r.enum)?r.enum.map(oR).join(", "):void 0,defaultValue:void 0===r.default?void 0:oR(r.default)}})}(o.parameters):[];return(0,r.jsxs)("div",{className:"tool-definitions-panel",children:[(0,r.jsx)("nav",{className:"tool-definitions-sidebar","aria-label":n("tools.title"),children:(0,r.jsx)("div",{className:"tool-definitions-list",children:s&&s.length>0?s.map(e=>{let t=e.name===o?.name;return(0,r.jsx)("button",{type:"button",className:`tool-definitions-item${t?" selected":""}`,"aria-pressed":t,onClick:()=>l(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):s?(0,r.jsx)(oW,{children:n("tools.noTools")}):(0,r.jsx)(oW,{children:e?n("tools.loading"):n("tools.load")})})}),(0,r.jsx)("section",{className:"tool-definition-detail","aria-label":n("tools.details"),children:o?(0,r.jsxs)("div",{className:"tool-definition-scroll",children:[o.description&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:n("tools.description")}),(0,r.jsx)("div",{className:"tool-definition-description",children:o.description})]}),(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsxs)("div",{className:"tool-definition-section-label",children:[(0,r.jsx)("span",{children:n("tools.parameters")}),(0,r.jsx)("span",{children:n("tools.parameterCount",{count:d.length})})]}),d.length>0?(0,r.jsx)("div",{className:"tool-definition-fields",children:d.map(e=>(0,r.jsxs)("div",{className:"tool-definition-field",children:[(0,r.jsxs)("div",{className:"tool-definition-field-name",children:[(0,r.jsx)("code",{children:e.name}),(0,r.jsx)("span",{className:e.required?"required":void 0,children:n(e.required?"tools.required":"tools.optional")})]}),(0,r.jsxs)("div",{className:"tool-definition-field-value",children:[(0,r.jsx)("code",{className:"tool-definition-type",children:e.type}),e.description&&(0,r.jsx)("div",{children:e.description}),e.allowedValues&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[n("tools.allowedValues"),": ",(0,r.jsx)("code",{children:e.allowedValues})]}),void 0!==e.defaultValue&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[n("tools.defaultValue"),": ",(0,r.jsx)("code",{children:e.defaultValue})]})]})]},e.name))}):(0,r.jsx)("div",{className:"tool-definition-no-parameters",children:n("tools.noParameters")})]}),o.promptGuidelines&&o.promptGuidelines.length>0&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:n("tools.guidelines")}),(0,r.jsx)("ul",{className:"tool-definition-guidelines",children:o.promptGuidelines.map((e,t)=>(0,r.jsx)("li",{children:e},`${o.name}:${t}`))})]})]}):(0,r.jsx)(oW,{children:s?n("tools.noTools"):e?n("tools.loading"):n("tools.load")})}),(0,r.jsx)("style",{children:`
39
- .tool-definitions-panel {
40
- display: grid;
41
- grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
42
- height: min(600px, 75dvh);
43
- min-height: 240px;
44
- overflow: hidden;
45
- background: var(--bg-panel);
46
- border-bottom: 1px solid var(--border);
47
- }
48
- .tool-definitions-sidebar,
49
- .tool-definition-detail {
50
- display: flex;
51
- min-width: 0;
52
- min-height: 0;
53
- flex-direction: column;
54
- }
55
- .tool-definitions-sidebar {
56
- border-right: 1px solid var(--border);
57
- background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
58
- }
59
- .tool-definitions-list,
60
- .tool-definition-scroll {
61
- min-height: 0;
62
- flex: 1;
63
- overflow: auto;
64
- }
65
- .tool-definitions-item {
66
- display: flex;
67
- width: 100%;
68
- min-height: 38px;
69
- align-items: center;
70
- padding: 8px 12px;
71
- border: none;
72
- border-bottom: 1px solid var(--border);
73
- background: transparent;
74
- color: var(--text-muted);
75
- cursor: pointer;
76
- text-align: left;
77
- }
78
- .tool-definitions-item:hover {
79
- background: var(--bg-hover);
80
- color: var(--text);
81
- }
82
- .tool-definitions-item.selected {
83
- background: var(--bg-selected);
84
- box-shadow: inset 2px 0 0 var(--accent);
85
- color: var(--text);
86
- }
87
- .tool-definitions-item code {
88
- max-width: 100%;
89
- color: inherit;
90
- font-size: 11px;
91
- font-weight: 600;
92
- overflow-wrap: anywhere;
93
- }
94
- .tool-definition-scroll {
95
- padding: 14px 16px 20px;
96
- }
97
- .tool-definition-section + .tool-definition-section {
98
- margin-top: 18px;
99
- }
100
- .tool-definition-section-label {
101
- display: flex;
102
- align-items: center;
103
- justify-content: space-between;
104
- gap: 8px;
105
- margin-bottom: 7px;
106
- color: var(--text-dim);
107
- font-size: 11px;
108
- font-weight: 600;
109
- }
110
- .tool-definition-section-label > span:last-child {
111
- font-weight: 400;
112
- white-space: nowrap;
113
- }
114
- .tool-definition-description {
115
- color: var(--text-muted);
116
- font-size: 12px;
117
- line-height: 1.55;
118
- overflow-wrap: anywhere;
119
- white-space: pre-wrap;
120
- }
121
- .tool-definition-fields {
122
- border-top: 1px solid var(--border);
123
- }
124
- .tool-definition-field {
125
- display: grid;
126
- grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
127
- gap: 12px;
128
- padding: 9px 0;
129
- border-bottom: 1px solid var(--border);
130
- font-size: 11px;
131
- line-height: 1.45;
132
- }
133
- .tool-definition-field-name {
134
- display: flex;
135
- min-width: 0;
136
- flex-direction: column;
137
- gap: 3px;
138
- color: var(--text);
139
- }
140
- .tool-definition-field-name code {
141
- overflow-wrap: anywhere;
142
- }
143
- .tool-definition-field-name span {
144
- color: var(--text-dim);
145
- font-size: 10px;
146
- }
147
- .tool-definition-field-name span.required {
148
- color: var(--accent);
149
- }
150
- .tool-definition-field-value {
151
- min-width: 0;
152
- color: var(--text-muted);
153
- overflow-wrap: anywhere;
154
- }
155
- .tool-definition-type {
156
- display: block;
157
- margin-bottom: 3px;
158
- color: var(--text);
159
- }
160
- .tool-definition-meta {
161
- margin-top: 4px;
162
- color: var(--text-dim);
163
- }
164
- .tool-definition-meta code {
165
- color: var(--text-muted);
166
- }
167
- .tool-definition-no-parameters {
168
- padding: 2px 0 10px;
169
- color: var(--text-dim);
170
- font-size: 11px;
171
- }
172
- .tool-definition-guidelines {
173
- margin: 0;
174
- padding-left: 18px;
175
- color: var(--text-muted);
176
- font-size: 11px;
177
- line-height: 1.5;
178
- }
179
- .tool-definitions-empty {
180
- padding: 14px 12px;
181
- color: var(--text-muted);
182
- font-size: 12px;
183
- overflow-wrap: anywhere;
184
- }
185
- @media (max-width: 640px) {
186
- .tool-definitions-panel {
187
- grid-template-columns: 112px minmax(0, 1fr);
188
- }
189
- .tool-definitions-item {
190
- padding: 8px 10px;
191
- }
192
- .tool-definition-scroll {
193
- padding: 12px;
194
- }
195
- .tool-definition-field {
196
- grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
197
- gap: 9px;
198
- }
199
- }
200
- `})]})}function oz(e){return e.name||e.firstMessage||e.id.slice(0,12)}function oD(e,t){return t?"running":e.relation?.kind==="subagent"?e.relation.status:"completed"}function oA(e){return"running"===e||"starting"===e?0:"queued"===e?1:2}function oF({status:e}){return"running"===e||"starting"===e?(0,r.jsx)(X,{size:13}):"failed"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m9 9 6 6M15 9l-6 6"})]}):"queued"===e?(0,r.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,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}):"aborted"===e||"interrupted"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M9 9h6v6H9z"})]}):(0,r.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,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m8 12 3 3 5-6"})]})}function oB({session:e,main:t,selected:n,running:i,onSelect:s,onOpenInNewTab:a}){let{locale:l,t:o}=(0,w.s)(),d=e.relation?.kind==="subagent"?e.relation:null,c=oD(e,i),u=t?o("agentSwitcher.main"):d?.description||oz(e),h=t?oz(e):`${d?.profile??o("agentSwitcher.subagent")} \xb7 ${function(e,t){let n=new Date(e).getTime();if(!Number.isFinite(n))return"";let r=Math.round((n-Date.now())/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(r))return i.format(r,"second");let s=Math.round(r/60);if(60>Math.abs(s))return i.format(s,"minute");let a=Math.round(s/60);return 24>Math.abs(a)?i.format(a,"hour"):i.format(Math.round(a/24),"day")}(e.modified,l)}`;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,onClick:s,onAuxClick:e=>{1===e.button&&a&&(e.preventDefault(),a())},style:{width:"100%",minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",borderBottom:"1px solid var(--border)",borderLeft:n?"2px solid var(--accent)":"2px solid transparent",background:n?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="transparent")},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:t?"var(--text-muted)":"var(--accent)"},children:t?(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"M3 9h18"})]}):(0,r.jsx)(G,{size:16})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},title:u,children:u}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:h,children:h})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:t&&!i?"var(--text-dim)":"running"===c||"starting"===c?"var(--accent)":"completed"===c?"var(--success)":"failed"===c?"var(--danger)":"aborted"===c?"var(--warning)":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:t&&!i?n?o("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oF,{status:c}),(0,r.jsx)("span",{children:o(`agentSwitcher.status.${c}`)})]})})]})}function oO({rootSession:e,subagents:t,selectedSessionId:n,runningSessionIds:s,onSelectSession:a,onOpenInNewTab:l}){let{t:o}=(0,w.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useMemo)(()=>[...t].sort((e,t)=>{let n=oA(oD(e,s.has(e.id)))-oA(oD(t,s.has(t.id)));return 0!==n?n:t.modified.localeCompare(e.modified)}),[s,t]),h=d.trim().toLowerCase(),p=h?u.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null;return[t?.description,t?.profile,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes(h))}):u,m=t.filter(e=>s.has(e.id)).length;return(0,r.jsx)("div",{role:"listbox","aria-label":o("agentSwitcher.title"),className:"popover-surface",style:{overflow:"hidden"},children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("strong",{style:{fontSize:12,fontWeight:600},children:o("agentSwitcher.title")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("agentSwitcher.count",{count:t.length})}),m>0&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--accent)",fontSize:11},children:o("agentSwitcher.runningCount",{count:m})})]}),t.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",className:"agent-switcher-search-input",value:d,onChange:e=>c(e.target.value),placeholder:o("agentSwitcher.search"),"aria-label":o("agentSwitcher.search"),style:{width:"100%",height:32,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(58dvh, 480px)",overflowY:"auto"},children:[(0,r.jsx)(oB,{session:e,main:!0,selected:e.id===n,running:s.has(e.id),onSelect:()=>a(e),onOpenInNewTab:l?()=>l(e):void 0}),p.map(e=>(0,r.jsx)(oB,{session:e,selected:e.id===n,running:s.has(e.id),onSelect:()=>a(e),onOpenInNewTab:l?()=>l(e):void 0},e.id)),0===p.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:o("agentSwitcher.noMatches")})]})]})})}var oH=n(63606),oU=n(8422);async function o_(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(15e3)}),r=await n.json().catch(()=>{throw Error(`Terminal request failed (HTTP ${n.status}): server returned an empty or invalid JSON response. Check the pi-web server log.`)});if(!r||"object"!=typeof r)throw Error(`Terminal request failed (HTTP ${n.status}): invalid JSON response. Check the pi-web server log.`);if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);return r}function oq({tab:e,active:t,onRestart:n,onClosed:s,onCloseError:a}){let{t:l}=(0,w.s)(),{id:o,cwd:d,restored:c}=e,u=(0,i.useRef)(null),h=(0,i.useRef)(null),p=(0,i.useRef)(Promise.resolve()),m=(0,i.useRef)(null),g=(0,i.useRef)({onClosed:s,onCloseError:a});g.current={onClosed:s,onCloseError:a};let[f,x]=(0,i.useState)("connecting"),[v,y]=(0,i.useState)(null),[b,j]=(0,i.useState)(null),[k,S]=(0,i.useState)(0);return(0,i.useEffect)(()=>{var e;let t,n,r,i,s,a=u.current;if(!a)return;let l=!1,g=null,f=!1,v=!1,b=!1;x("connecting"),y(null),j(null);let w=new oU.B({cursorBlink:!0,fontFamily:getComputedStyle(a).getPropertyValue("--font-mono").trim()||"monospace",fontSize:13,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:{background:"#111318",foreground:"#d7dce5",cursor:"#60a5fa",selectionBackground:"#365b8a",black:"#1d222b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#e5e7eb",brightBlack:"#6b7280",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"}});h.current=w;let S=new oH.Y;w.loadAddon(S),w.open(a),w.attachCustomKeyEventHandler(e=>{if("keydown"!==e.type)return!0;let t=e.key.toLowerCase();return!((e.ctrlKey||e.metaKey)&&"v"===t||(e.ctrlKey||e.metaKey)&&"c"===t&&w.hasSelection())});let C=(e=e=>{l||(b=!0,w.options.disableStdin=!0,y(e.message),x("error"))},n=Promise.resolve(),r=!1,i=null,s=t=>{r||(n=n.then(async()=>{r||(t===i&&(i=null),await o_(`/api/terminal/${encodeURIComponent(o)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))}).catch(t=>{r=!0,e(t)}))},{write(e){if(!r)for(let t of e.match(/[\s\S]{1,32768}/gu)??[])i&&i.data.length+t.length<=65536?i.data+=t:s(i={type:"input",data:t})},resize(e,t){i=null,s({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});m.current=C;let N=w.onData(e=>{!f||v||b||C.write(e)}),E=()=>{a.offsetWidth&&a.offsetHeight&&S.fit()},M=w.onResize(({cols:e,rows:t})=>{!f||v||b||C.resize(e,t)}),I=new ResizeObserver(E);I.observe(a);let L=()=>{l||v||!navigator.onLine||(g?.close(),(g=new EventSource(`/api/terminal/${encodeURIComponent(o)}/events${void 0===t?"":`?after=${t}`}`)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){if(n.reset)w.reset();else if(void 0!==t&&n.offset<=t)return;w.write(n.data),t=n.offset}else v=!0,f=!1,w.options.disableStdin=!0,g?.close(),j("exit"===n.type?n.exitCode:null),x("exited")},g.onopen=()=>{f=!0,!b&&(w.options.disableStdin=!1,x("ready"),E(),C.resize(w.cols,w.rows),a.offsetWidth&&a.offsetHeight&&w.focus())},g.onerror=()=>{l||v||(f=!1,w.options.disableStdin=!0,x(g?.readyState===EventSource.CLOSED?"error":"connecting"))})};p.current=(async()=>{E(),c||k>0?await o_(`/api/terminal/${encodeURIComponent(o)}`):await o_("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,cwd:d,cols:w.cols,rows:w.rows})}),L()})().catch(e=>{l||(y(e.message),x("error"))});let T=()=>{f=!1,w.options.disableStdin=!0,g?.close(),v||b||x("connecting")},$=e=>{e.persisted&&L()};return window.addEventListener("pagehide",T),window.addEventListener("pageshow",$),window.addEventListener("offline",T),window.addEventListener("online",L),()=>{l=!0,g?.close(),C.stop(),I.disconnect(),N.dispose(),M.dispose(),window.removeEventListener("pagehide",T),window.removeEventListener("pageshow",$),window.removeEventListener("offline",T),window.removeEventListener("online",L),w.dispose(),h.current=null}},[o,d,c,k]),(0,i.useEffect)(()=>{t&&h.current?.focus()},[t]),(0,i.useEffect)(()=>{if(!e.closing)return;let t=!1;return h.current&&(h.current.options.disableStdin=!0),(async()=>{await p.current,await m.current?.stop(),await o_(`/api/terminal/${encodeURIComponent(o)}`,{method:"DELETE",keepalive:!0}),t||g.current.onClosed()})().catch(e=>{t||(y(e.message),x("error"),g.current.onCloseError())}),()=>{t=!0}},[o,e.closing]),(0,r.jsxs)("section",{className:"terminal-panel","aria-label":l("terminal.title"),children:[(0,r.jsxs)("header",{className:"terminal-panel-header",children:[(0,r.jsxs)("div",{className:"terminal-panel-path",children:[(0,r.jsx)("span",{className:`terminal-status-dot is-${f}`,title:l(`terminal.${f}`)}),(0,r.jsx)("span",{title:d,children:d})]}),"error"===f&&(0,r.jsx)("button",{type:"button",onClick:()=>S(e=>e+1),disabled:!!e.closing,title:l("terminal.reconnect"),"aria-label":l("terminal.reconnect"),children:(0,r.jsx)("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,r.jsx)("path",{d:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})})}),(0,r.jsx)("button",{type:"button",onClick:n,disabled:!!e.closing,title:l("terminal.restart"),"aria-label":l("terminal.restart"),children:(0,r.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,r.jsx)("path",{d:"M20 11a8 8 0 1 0-2.34 5.66"}),(0,r.jsx)("polyline",{points:"20 4 20 11 13 11"})]})})]}),(0,r.jsxs)("div",{children:[v&&(0,r.jsx)("div",{className:"terminal-panel-error",role:"alert",children:v}),"exited"===f&&(0,r.jsx)("div",{className:"terminal-panel-exit",role:"status",children:null===b?l("terminal.exited"):l("terminal.exitCode",{code:b})})]}),(0,r.jsx)("div",{className:"terminal-xterm",children:(0,r.jsx)("div",{ref:u,className:"terminal-xterm-host"})})]})}let oK="pi-web:terminal-tabs";function oV(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function oJ(e){return Math.round(Math.min(200*Math.sqrt(Math.max(e,1)/260),360))}function oY(e,t,n){let r=Number.isFinite(e)?e:t,i=Math.max(t,n);return Math.round(Math.max(t,Math.min(i,r)))}function oZ(e){return{min:Math.max(.2,280/e),max:Math.min(.8,(e-12-280)/e)}}function oX(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function oG(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:s,getMaxWidth:a,growthDirection:l,maxWidth:o,minWidth:d,storageKey:c,widthRef:u}=e,h=(0,i.useRef)(null),p=(0,i.useRef)(null),m=(0,i.useRef)(!1),[g,f]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1);(0,i.useEffect)(()=>{b(!0)},[]);let w=(0,i.useCallback)(()=>Math.min(o,Math.max(d,a())),[a,o,d]),j=(0,i.useCallback)(e=>oY(e,d,w()),[w,d]),k=(0,i.useCallback)(e=>{u.current=e,h.current?.style.setProperty(n,`${e}px`)},[n,u]),S=(0,i.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,i=j(e),s=i!==u.current;return k(i),f(i),r&&(s||n)&&oX(c,i),i},[k,j,c,u]),C=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),N=(0,i.useCallback)(e=>{let t=p.current;if(t&&t.pointerId===e){p.current=null,C(t),v(!1),S(u.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[S,C,u]),E=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=p.current;t&&N(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),p.current={pointerId:e.pointerId,startX:e.clientX,startWidth:u.current,target:n,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",v(!0)},[N,u]),M=(0,i.useCallback)(e=>{let t=p.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void N(e.pointerId);e.preventDefault();let n="right"===l?1:-1,r=j(t.startWidth+(e.clientX-t.startX)*n);k(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[k,j,N,l]),I=(0,i.useCallback)(e=>{N(e.pointerId)},[N]),L=(0,i.useCallback)(e=>{N(e.pointerId)},[N]),T=(0,i.useCallback)(e=>{N(e.pointerId)},[N]),$=(0,i.useCallback)(()=>{S(s?.()??r,{forcePersist:!0})},[S,r,s]),R=(0,i.useCallback)(()=>{S(u.current)},[S,u]),W=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===l?"ArrowRight":"ArrowLeft",r="right"===l?"ArrowLeft":"ArrowRight";e.key===n?(e.preventDefault(),S(u.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),S(u.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),S(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),S(w(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),$())},[S,w,l,d,$,u]);return(0,i.useLayoutEffect)(()=>{if(m.current)return;m.current=!0;let e=h.current,t=e?.style.transition??"";e&&(e.style.transition="none");let n=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(c),i=S(n??s?.()??r,{persist:!1});null!==n&&n!==i&&oX(c,i),e&&(e.offsetWidth,e.style.transition=t)},[S,r,s,c]),(0,i.useEffect)(()=>{if(!m.current)return;S(u.current);let e=()=>{S(u.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[S,u]),(0,i.useEffect)(()=>{if(!x)return;let e=()=>{let e=p.current;e&&N(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[N,x]),(0,i.useEffect)(()=>()=>{let e=p.current;e&&(p.current=null,C(e))},[C]),{isResizing:x,panelRef:h,reclampWidth:R,resetWidth:$,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":y?w():o,"aria-valuemin":d,"aria-valuenow":g,"aria-valuetext":`${g} px`,onDoubleClick:$,onKeyDown:W,onLostPointerCapture:T,onPointerCancel:L,onPointerDown:E,onPointerMove:M,onPointerUp:I,role:"separator",tabIndex:0},width:g}}let oQ="pi-web:pinned-cwds";function o0(){try{return window.localStorage}catch{return null}}function o1(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if("string"!=typeof n)continue;let e=n.trim();!e||t.includes(e)||t.push(e)}return t}function o2(e,t,n){return t&&n?j(t).replace(/\/$/,"")===j(n).replace(/\/$/,"")||e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?e:E(t,e):e}let o4="pi-chat-draft-tabs";function o8(e){return`parked-new:${e}`}function o3(){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.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-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 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.73V4a2 2 0 0 0-2-2z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function o6(){let e,t=(0,s.useRouter)(),n=(0,s.useSearchParams)(),[l]=(0,i.useState)(()=>{let e;return{requestedCwd:e=n.get("cwd")?.trim()||null,sessionId:e?null:n.get("session")}}),{locale:o,t:d}=(0,w.s)(),c=eX();(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{let r;n=null,!function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let i=.01>Math.abs(r-1);return e&&i&&t-n>1}({hasFocusedEditable:(r=document.activeElement)instanceof HTMLElement&&(r.isContentEditable||"INPUT"===r.tagName||"SELECT"===r.tagName||"TEXTAREA"===r.tagName),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.removeProperty("--app-viewport-height"):t.style.setProperty("--app-viewport-height",`${e.height}px`);let i=0!==window.scrollX||0!==window.scrollY,s=.01>Math.abs(e.scale-1);i&&s&&window.scrollTo(0,0)},i=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return i(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("focusin",i),window.addEventListener("focusout",i),window.addEventListener("pageshow",i),()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("focusin",i),window.removeEventListener("focusout",i),window.removeEventListener("pageshow",i),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]),n3(),(0,i.useEffect)(()=>ir(e=>{"granted"===e&&ox(o)}),[o]);let{soundEnabled:u,onSoundToggle:h,playDoneSound:f,unlockAudio:x,soundEnabledRef:v}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),s=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),a=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=s();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[s]);return{soundEnabled:e,onSoundToggle:(0,i.useCallback)(()=>{let e=!n.current;e&&a(!0),n.current=e,localStorage.setItem("pi-sound-enabled",String(e)),t(e)},[a]),playDoneSound:(0,i.useCallback)(()=>{if(!n.current)return;let e=s();if(!e)return;let t=()=>{try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),s=e.createGain();i.connect(s),s.connect(e.destination),i.type="sine",i.frequency.value=n;let a=t+.18*r;s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.18,a+.02),s.gain.exponentialRampToValueAtTime(.001,a+.45),i.start(a),i.stop(a+.45)})}catch{}};"suspended"===e.state?e.resume().then(t).catch(()=>{}):t()},[s]),unlockAudio:a,soundEnabledRef:n}}(),[y,b]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{b("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let j=(0,i.useCallback)(e=>{b(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),k=(0,i.useRef)(new Set),C=(0,i.useCallback)(e=>{if(!v.current)return;let t=new Set(eg.current.filter(e=>"session"===e.kind&&e.session).map(e=>e.session.id));(!e||!(e.length>0)||e.some(e=>!t.has(e)))&&f()},[f,v]),[N,E]=(0,i.useState)(null),[M,I]=(0,i.useState)([]),L=(0,i.useCallback)(e=>{I(e)},[]),T=(0,i.useMemo)(()=>g(M).map(e=>e.root),[M]),[$,W]=(0,i.useState)(()=>(function(e=o0()){if(!e)return[];try{let t=e.getItem(oQ);if(!t)return[];return o1(JSON.parse(t))}catch{return[]}})()),P=(0,i.useCallback)(e=>{W(t=>{let n,r=(n=e.trim())?t.includes(n)?t.filter(e=>e!==n):[...t,n]:o1(t);return!function(e,t=o0()){if(t)try{t.setItem(oQ,JSON.stringify(o1(e)))}catch{}}(r),r})},[]),[z,D]=(0,i.useState)(""),[A,F]=(0,i.useState)(null),B=(0,i.useMemo)(()=>N?[...M.filter(e=>e.id!==N.id),N]:M,[N,M]),O=(0,i.useMemo)(()=>{var e;return(e=N?.id)?a(B).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[N?.id,B]),H=!!O?.subagents.length,[U,_]=(0,i.useState)(()=>new Set),q=(0,i.useCallback)(e=>{_(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),[K,V]=(0,i.useState)(null),[J,Y]=(0,i.useState)("initial"),Z=(0,i.useRef)(null),[X,Q]=(0,i.useState)(()=>l.requestedCwd?"validating":"idle"),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(0),[ei,es]=(0,i.useState)(0),ea=(0,i.useRef)(new Map),el=(0,i.useCallback)((e,t)=>{ea.current.set(e,t)},[]),[ed,ec]=(0,i.useState)([]),[eu,eh]=(0,i.useState)(!1),[ep,em]=(0,i.useState)(!1),eg=(0,i.useRef)([]);eg.current=ed;let[ef,ex]=(0,i.useState)(null),ev=(0,i.useRef)(null);ev.current=ef;let[ey,eb]=(0,i.useState)(null),ew=(0,i.useRef)(null);ew.current=ey;let[ej,ek]=(0,i.useState)("primary"),eS=(0,i.useRef)("primary");eS.current=ej;let eC=(0,i.useRef)(!1),[eN,eE]=(0,i.useState)(.5),eM=(0,i.useRef)(null),eI=(0,i.useRef)(!1),[eL,eT]=(0,i.useState)(600);e=(0,i.useMemo)(()=>0===ed.length?N?.id?[N.id]:[]:ed.flatMap(e=>"session"===e.kind&&e.session?[e.session.id]:[]),[ed,N?.id]).join(","),(0,i.useEffect)(()=>{if(!e)return;let t=e.split(","),n=!1,r=()=>{if(!n)for(let e of t)fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store"}).catch(()=>{})};r();let i=setInterval(r,3e4),s=()=>{"visible"===document.visibilityState&&r()};return document.addEventListener("visibilitychange",s),()=>{n=!0,clearInterval(i),document.removeEventListener("visibilitychange",s)}},[e]);let e$=(0,i.useCallback)((e,t,n)=>{let r=!!(t.trim()||n>0),i=sy(t,d("i18n.newSession"));ec(t=>{let n=!1,s=t.map(t=>"draft"!==t.kind||t.newSessionDraftKey!==e||t.dirty===r&&t.title===i?t:(n=!0,{...t,dirty:r,title:i}));return n?s:t})},[d]);(0,i.useEffect)(()=>{try{let e=window.sessionStorage.getItem(o4),t=(e?JSON.parse(e):[]).flatMap(e=>{if("string"!=typeof e?.draftKey||"string"!=typeof e?.title)return[];let t=eP(e.draftKey);return t?[{id:`draft:${e.draftKey}`,kind:"draft",title:sy(t.value,e.title),session:null,newSessionCwd:"string"==typeof e.cwd?e.cwd:null,newSessionDraftKey:e.draftKey,projectKey:"string"==typeof e.cwd?e.cwd:null,dirty:!0}]:[]});if(t.length>0&&(ec(e=>[...e,...t.filter(t=>!e.some(e=>e.id===t.id))]),!l.sessionId&&!l.requestedCwd)){let e=t[0];ex(t=>t??e.id),E(null),V(e.newSessionCwd),Z.current=e.newSessionDraftKey}}catch{}eh(!0)},[l.requestedCwd,l.sessionId]),(0,i.useEffect)(()=>{if(!eu)return;let e=ed.flatMap(e=>"draft"===e.kind&&e.dirty&&e.newSessionDraftKey?[{draftKey:e.newSessionDraftKey,cwd:e.newSessionCwd,title:e.title}]:[]);if(0===e.length){try{window.sessionStorage.removeItem(o4)}catch{}em(!1);return}try{window.sessionStorage.setItem(o4,JSON.stringify(e)),em(!1)}catch{em(!0)}},[ed,eu]);let[eR,eW]=(0,i.useState)(null),ez=(0,i.useCallback)(e=>{eW(t=>t===e?null:t)},[]),[eA,eF]=(0,i.useState)(0),[eB,eH]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(0),[eK,eV]=(0,i.useState)(null),[eJ,eY]=(0,i.useState)(!1),[eZ,eG]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)(!0),[e4,e8]=(0,i.useState)(!1),[e3,e6]=(0,i.useState)(!1),[e5,e7]=(0,i.useState)(!1),e9=(0,i.useRef)(260),te=(0,i.useRef)(560),tt=(0,i.useCallback)(()=>oY(.42*window.innerWidth,360,640),[]),tn=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let i=t<960;return Math.min(480,t-(i?320:420)-(!i&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:e4,rightPanelWidth:te.current}),[e4]),tr=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:n,sidebarWidth:r}=e;return t<960?1200:Math.min(1200,t-420-(n?r:0))})({viewportWidth:window.innerWidth,sidebarOpen:e1,sidebarWidth:e9.current}),[e1]),ts=oG({ariaLabel:d("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:tn,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:e9}),ta=oG({ariaLabel:d("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:tt,getMaxWidth:tr,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:te}),tl=ts.reclampWidth,to=ta.reclampWidth;(0,i.useEffect)(()=>{c&&e2(!1)},[c]),(0,i.useEffect)(()=>{e7(!0)},[]),(0,i.useEffect)(()=>{e4&&(tl(),to())},[to,tl,e4]),(0,i.useEffect)(()=>{if(!e4)return void e6(!1);let e=ta.panelRef.current,t=!1,n=()=>{t||(t=!0,e6(!0))};if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return void n();let r=t=>{t.target===e&&("width"===t.propertyName||"min-width"===t.propertyName||"transform"===t.propertyName)&&n()};e?.addEventListener("transitionend",r);let i=window.setTimeout(n,oJ(te.current)+80);return()=>{e?.removeEventListener("transitionend",r),window.clearTimeout(i)}},[e4,ta.panelRef]);let td=(0,i.useRef)(null),[tc,tu]=(0,i.useState)(null),th=(0,i.useCallback)(e=>{tu(t=>t?.sessionId===e?null:t)},[]),tp=(0,i.useRef)(null),[tm,tg]=(0,i.useState)([]),[tf,tx]=(0,i.useState)(null),[tv,ty]=(0,i.useState)(!1),[tb,tw]=(0,i.useState)(!1),[tj,tk]=(0,i.useState)(null),tS=(0,i.useRef)(null),tC=oE(tm),tN=(0,i.useRef)(new Map),tE=(0,i.useRef)(new Map),tM=(0,i.useRef)(new Map),tI=(0,i.useCallback)((e,t,n)=>{tZ.current&&tM.current.set(tZ.current,{tree:e,activeLeafId:t}),tg(e),tx(t),tS.current=n},[]),tL=(0,i.useCallback)(e=>{tS.current?.(e)},[]),[tT,t$]=(0,i.useState)(null),[tR,tW]=(0,i.useState)(null),[tP,tz]=(0,i.useState)(!1),tD=(0,i.useRef)(null),tA=(0,i.useRef)(0),tF=(0,i.useRef)(null),tB=(0,i.useRef)(null),tO=(0,i.useRef)(null),tH=(0,i.useRef)(null),tU=(0,i.useRef)(null),t_=(0,i.useRef)(null),tq=(0,i.useCallback)(e=>{t$(e),tz(!1)},[]),tK=(0,i.useCallback)(e=>{tW(e)},[]),tV=(0,i.useCallback)(e=>{tA.current+=1,tD.current=e,tz(!1)},[]),[tJ,tY]=(0,i.useState)(null),tZ=(0,i.useRef)(N?.id??null);tZ.current=N?.id??null;let tX=(0,i.useCallback)(e=>{null!==e&&(e.sessionId&&tN.current.set(e.sessionId,e),tY(e))},[]),[tG,tQ]=(0,i.useState)(null),t0=(0,i.useRef)(null),t1=(0,i.useCallback)((e,t)=>{rn(t).then(()=>{t0.current&&clearTimeout(t0.current),tQ(e),t0.current=setTimeout(()=>tQ(null),1400)})},[]);(0,i.useEffect)(()=>()=>{t0.current&&clearTimeout(t0.current)},[]);let[t2,t4]=(0,i.useState)(null),t8=(0,i.useCallback)(e=>{null!==e&&(tZ.current&&tE.current.set(tZ.current,e),t4(e))},[]),t3=(0,i.useCallback)(e=>{tY(tN.current.get(e)??null),t4(tE.current.get(e)??null);let t=tM.current.get(e);tg(t?.tree??[]),tx(t?.activeLeafId??null)},[]);(0,i.useEffect)(()=>{if(!N){tY(null),t4(null);return}t3(N.id)},[N,t3]);let[t6,t5]=(0,i.useState)(null),[t7,t9]=(0,i.useState)(null),[ne,nt]=(0,i.useState)(null),nn=(0,i.useCallback)((e=!1)=>{t5(null),e&&t6&&requestAnimationFrame(()=>{let e=document.querySelector(`[data-top-panel-trigger="${t6}"]`)??tB.current;e?.focus()})},[t6]);(0,i.useEffect)(()=>{tC||t5(e=>"branches"===e?null:e)},[tC]),(0,i.useEffect)(()=>{H||t5(e=>"agents"===e?null:e)},[H]);let nr=(0,i.useCallback)(e=>{t9(e),e||t5(e=>"outline"===e?null:e)},[]),ni=(0,i.useCallback)(e=>{c&&e2(!1),t5(t=>t===e?null:e)},[c]),ns=(0,i.useCallback)(e=>{let t=t6!==e;if(ni(e),!t||tP||"system"===e&&null!==tT||"tools"===e&&null!==tR)return;let n=tD.current;if(!n)return;let r=++tA.current;tz(!0),n().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tA.current===r&&tz(!1)})},[t6,tP,tT,tR,ni]),na=(0,i.useCallback)(()=>{c&&e2(!1),t5(e=>"session"===e?null:"session")},[c]),nl=(0,i.useCallback)(()=>{c&&t5(null),e2(e=>!e)},[c]),no=(0,i.useCallback)(()=>{e2(!1),requestAnimationFrame(()=>tB.current?.focus())},[]);(0,i.useEffect)(()=>{if(!c||!e1||!e5)return;let e=requestAnimationFrame(()=>{let e=ts.panelRef.current;e?.querySelector('[aria-current="page"], button:not(:disabled)')?.focus()}),t=e=>{"Escape"===e.key&&(e.preventDefault(),no())};return document.addEventListener("keydown",t),()=>{cancelAnimationFrame(e),document.removeEventListener("keydown",t)}},[no,c,e5,e1,ts.panelRef]);let nd=(0,i.useCallback)(()=>{c&&(e2(!1),t5(null)),e8(e=>!e)},[c]),nc=(0,i.useCallback)((e=!1)=>{e8(!1),e&&requestAnimationFrame(()=>tO.current?.focus())},[]);(0,i.useEffect)(()=>{if(!e4)return;let e=requestAnimationFrame(()=>{(c||!(window.innerWidth>=960))&&ta.panelRef.current?.querySelector('[role="tab"][aria-selected="true"]')?.focus()}),t=e=>{"Escape"===e.key&&(c||!(window.innerWidth>=960))&&(e.preventDefault(),e.stopPropagation(),nc(!0))};return document.addEventListener("keydown",t,!0),()=>{cancelAnimationFrame(e),document.removeEventListener("keydown",t,!0)}},[nc,c,e4,ta.panelRef]),(0,i.useEffect)(()=>{ty(!1),tk(null)},[c,N?.id,J]),(0,i.useEffect)(()=>{t6&&ty(!1)},[t6]),(0,i.useLayoutEffect)(()=>{if(!t6||!tp.current)return;let e=()=>{let e=tp.current.getBoundingClientRect();if("agents"===t6){let t=tU.current??tH.current,n=Math.min(420,window.innerWidth-16);if(t){let e=t.getBoundingClientRect(),r=Math.max(8,Math.min(e.right-n,window.innerWidth-n-8));nt({top:e.bottom+4,left:r,width:n});return}let r=Math.max(8,Math.min(e.right-n-8,window.innerWidth-n-8));nt({top:e.bottom+4,left:r,width:n});return}nt({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tp.current),window.addEventListener("resize",e),()=>{t.disconnect(),window.removeEventListener("resize",e)}},[t6,c]),(0,i.useEffect)(()=>{if(!t6||"language"===t6)return;let e=e=>{let t=e.target;!t||t_.current?.contains(t)||t instanceof Element&&t.closest("[data-top-panel-trigger]")||nn()},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),nn(!0))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[t6,nn]);let[nu,nh]=(0,i.useState)([]),[np,nm]=(0,i.useState)(null),[ng,nf]=(0,i.useState)([]),[nx,nv]=(0,i.useState)(!1),ny=(0,i.useMemo)(()=>[...nu,...ng.map(e=>({id:e.id,label:S(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing}))],[nu,ng]);(0,i.useEffect)(()=>{try{let e=function(e){try{let t=JSON.parse(e??"null"),n=[];for(let e of Array.isArray(t?.tabs)?t.tabs:[])e&&"string"==typeof e.id&&/^[a-f0-9]{32}$/.test(e.id)&&"string"==typeof e.cwd&&e.cwd.trim()&&!n.some(t=>t.id===e.id||t.cwd===e.cwd)&&n.push({id:e.id,cwd:e.cwd,restored:!0});return{tabs:n,activeId:n.some(e=>e.id===t.activeId)?t.activeId:null,open:t?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(oK));nf(e.tabs),e.activeId&&(nm(e.activeId),e8(e.open))}catch{}nv(!0)},[]),(0,i.useEffect)(()=>{if(nx)try{window.sessionStorage.setItem(oK,JSON.stringify({tabs:ng.map(({id:e,cwd:t})=>({id:e,cwd:t})),activeId:np,open:e4}))}catch{}},[ng,np,e4,nx]);let nb=(0,i.useCallback)((e,t,n)=>{nh(r=>(function(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let s=[...e];return s[i]={...s[i],viewerState:r},s})(r,e,t,n))},[]),[nw,nj]=(0,i.useState)(null),nk=(0,i.useCallback)(()=>{let e=eC.current&&"secondary"===eS.current?ew.current:ev.current,t=eg.current.find(t=>t.id===e);return t?.kind==="session"?t.session?.cwd??null:t?.kind==="draft"?t.newSessionCwd:N?.cwd??K??nw},[nw,K,N?.cwd]),nS=(0,i.useCallback)((e,t,n)=>{let r=o2(e,n,nk());td.current?.insertText(eq(r,t)),c&&(e8(!1),e2(!1))},[nk,c]),nC=(0,i.useCallback)((e,t)=>{let n=nk(),r=e.map(e=>o2(e,t,n)).map(e=>eq(e,!1)).join("");r&&td.current?.insertText(r),c&&(e8(!1),e2(!1))},[nk,c]),nN=(0,i.useCallback)((e,t,n,r)=>{let i,s,a,l,o,d,u,h=o2(e,r,nk());td.current?.insertText((s=(i=e=>Number.isFinite(e)&&Number.isInteger(e)&&e>=1?e:1)(t),l=Math.min(s,a=i(n)),o=Math.max(s,a),d=h.includes(" ")?`@"${h}"`:`@${h}`,u=l===o?`:${l}`:`:${l}-${o}`,`${d}${u} `)),c&&(e8(!1),e2(!1))},[nk,c]),nE=l.sessionId,nM=(0,i.useRef)(null),nI=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=l.requestedCwd;if(!e)return;let t=new AbortController;return Q("validating"),et(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async t=>{let n=await t.json().catch(()=>({}));if(!t.ok||!n.cwd)throw Error(n.error??`HTTP ${t.status}`);nI.current=!0;let r=`initial:${e}`;Y(r),Z.current=`new:${r}:${n.cwd}`,V(n.cwd),Q("ready")}).catch(e=>{t.signal.aborted||(et(e instanceof Error?e.message:String(e)),Q("error"))}),()=>t.abort()},[l]);let nL=(0,i.useCallback)((e,n,r)=>{let i=K??nw;if(nj(e),!e)return;let s=r??n??e,a=nM.current??(N?m(N):null);if(nM.current=s,nI.current){nI.current=!1;return}if(i===e&&a!==s||void 0!==eg&&eg.current?.length>0||a===s&&(null!==N||i===e))return;let l=Z.current;l&&i&&eO(l,o8(i));let o="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,d=`new:${o}:${e}`;eO(o8(e),d),Y(o),Z.current=d,E(null),V(t=>t&&t!==e?null:t),es(e=>e+1),tg([]),tx(null),t$(null),tW(null),tz(!1),t5(null),a!==s&&(nh([]),(!np||np.startsWith("file:"))&&(nm(null),e8(!1))),t.replace(window.location.pathname,{scroll:!1})},[nw,np,K,t,N]),nT=(0,i.useCallback)((e,n=!1,r,i,s=!1,a=!1)=>{var l,o;let d,u;eW(r?{sessionId:e.id,entryId:r,blockIndex:i}:null);let h=Z.current,g=K??(null===N?nw:null);if(h&&g&&!eg.current.some(e=>e.id===`draft:${h}`)&&eO(h,o8(g)),Z.current=null,e.projectKey&&(nM.current=e.projectKey),!n&&N){let t=m(N)===m(e);if(N.id===e.id&&t){s&&ec(t=>sk(t,e.id)),c&&e2(!1);return}}V(null),"function"==typeof t3&&t3(e.id),E(e);let f=eC.current?eS.current:"primary",x=(l=eg.current,o=e.id,"secondary"===(u=(d=l.find(e=>e.id===o))?sb(d):f)?{splitChatTabId:o,pane:u}:{activeChatTabId:o,pane:u});ec(t=>!a||n||s?(n||s?sC(t,e,f):sj(t,e,f)).tabs:function(e,t,n,r="primary"){let i=e.findIndex(e=>e.id===n.id),s=p(n);if(i>=0){let t=[...e];return t[i]={...t[i],session:n,title:s,projectKey:n.projectKey??n.cwd},{tabs:t,tabId:n.id}}let a=t?e.findIndex(e=>e.id===t):-1,l=a>=0?e[a]:void 0;if(!l||"session"!==l.kind)return sj(e,n,r);let o=[...e];return o[a]={...l,id:n.id,title:s,session:n,newSessionCwd:null,newSessionDraftKey:null,projectKey:n.projectKey??n.cwd,mountKey:void 0},{tabs:o,tabId:n.id}}(t,"secondary"===f?ew.current:ev.current,e,f).tabs),void 0!==x.activeChatTabId&&ex(x.activeChatTabId),void 0!==x.splitChatTabId&&eb(x.splitChatTabId),ek(x.pane),es(e=>e+1),tg([]),tx(null),tS.current=null,t$(null),tW(null),tz(!1),c&&!n&&e2(!1),n&&(nI.current=!0),n||t.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nw,t,c,K,N,t3]),n$=(0,i.useCallback)((e,n)=>{let r=`new:${e}:${n}`;eO(o8(n),r),Z.current=r,Y(e),E(null),V(n);{let e=eC.current&&"secondary"===eS.current,t=`draft:${r}`;ec(t=>sN(t,n,r,d("i18n.newSession"),e?"secondary":"primary").tabs),e?eb(t):ex(t)}es(e=>e+1),tg([]),tx(null),t$(null),tW(null),tz(!1),t5(null),c&&e2(!1),t.replace(window.location.pathname,{scroll:!1})},[t,c,d]),nR=(0,i.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&(E(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t),ec(t=>t.map(t=>t.id===e&&"session"===t.kind?{...t,title:p(n),session:{...t.session,...n}}:t)))}).catch(()=>{})},[]),nW=(0,i.useCallback)(e=>{nT(e,!1,void 0,void 0,!0)},[nT]),nP=(0,i.useCallback)(e=>{nT(e,!1,void 0,void 0,!1,!0)},[nT]),nz=(0,i.useCallback)(async e=>{try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||!n.info)throw Error(n.error??`HTTP ${t.status}`);nW(n.info)}catch(e){console.error("[pi-web] failed to open session:",e instanceof Error?e.message:e)}},[nW]),nD=(0,i.useCallback)((e,n)=>{er(e=>e+1),ec(t=>{var r;let i,{tabs:s,newTabId:a}=(r=`draft:${n}`,i=p(e),{tabs:t.map(t=>t.id===r?{...t,id:e.id,kind:"session",title:i,session:e,newSessionCwd:null,newSessionDraftKey:null,projectKey:e.projectKey??e.cwd,mountKey:t.mountKey??t.id}:t),newTabId:e.id});return ex(e=>e===`draft:${n}`?a:e),eb(e=>e===`draft:${n}`?a:e),s}),Z.current===n&&(Z.current=null,V(null),E(e),nR(e.id),t.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[t,nR]),nA=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&is({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&nW(e)}})},[nW]),nF=(0,i.useCallback)((e,t)=>{er(e=>e+1),E(n=>n?.id===e?{...n,name:t}:n),ec(n=>n.map(n=>n.id===e&&"session"===n.kind?{...n,title:t,session:n.session?{...n.session,name:t}:n.session}:n)),tY(n=>n?.sessionId===e?{...n,sessionName:t}:n)},[]),nB=(0,i.useRef)(void 0),nO=(0,i.useRef)(new Set),nH=(0,i.useCallback)(e=>{er(e=>e+1),eF(e=>e+1),N&&nR(N.id);let t=e??N;if(aF()&&t&&t.id&&!t.name&&t.relation?.kind!=="subagent"&&!nO.current.has(t.id)){let e=t.id;setTimeout(()=>{nB.current?.({sessionId:e})},350)}t?.relation?.kind==="subagent"||it()&&nA({targetSession:t,title:t?.name??d("i18n.sessionComplete"),body:d("i18n.taskFinished"),tag:t?`pi-session-complete:${t.id}`:"pi-session-complete"})},[nA,nR,N,d]),nU=(0,i.useCallback)((e,t)=>{var n;t?.relation?.kind!=="subagent"&&it()&&(n=k.current,!(!ii(e)||n.has(e.id))&&(n.add(e.id),1)&&nA({targetSession:t,title:d("i18n.attentionNeeded"),body:"custom"===e.method?d("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[nA,d]);nB.current=(0,i.useCallback)(async e=>{let t=e?.sessionId;if(t&&!nO.current.has(t)){nO.current.add(t);try{let e=await fetch(`/api/sessions/${encodeURIComponent(t)}/auto-name`,{method:"POST"}),n=await e.json().catch(()=>({}));if(!e.ok||!n.title)throw Error(n.error||`HTTP ${e.status}`);nF(t,n.title.trim())}catch(e){console.warn("[pi-web] silent auto-name failed:",e instanceof Error?e.message:e)}finally{nO.current.delete(t)}}},[nF]);let n_=(0,i.useCallback)(()=>{eF(e=>e+1)},[]),nq=(0,i.useCallback)((e,n)=>{let r=eg.current.find(e=>e.id===(n??N?.id)),i=n?r?.session:N,s=eC.current&&r?sb(r):"primary",a={...i??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1},l=!n||tZ.current===n;er(e=>e+1),ec(e=>sC(e,a,s).tabs),nR(e),l&&(Z.current=null,es(e=>e+1),V(null),E(a),"secondary"===s?eb(e):ex(e),ek(s),t.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1}))},[nR,t,N]),nK=(0,i.useCallback)(async(e,t,n)=>{ec(e=>sk(e,t));let r=await im(t,{type:"fork_branch",entryId:n});if(!r?.newSessionId)throw Error(d("chat.quoteForkFailed"));tu({sessionId:r.newSessionId,text:e}),nq(r.newSessionId,t)},[nq,d]),nV=(0,i.useCallback)(e=>{er(e=>e+1),ec(n=>{if(!n.some(t=>t.id===e))return n;let{tabs:r,nextActiveTabId:i,nextSplitTabId:s}=sE(n,e,ev.current??"",ew.current);if(0===r.length){let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=nw?`new:${e}:${nw}`:`draft:${e}`,r=sN([],nw??null,n,d("i18n.newSession"));return ex(r.tabId),eb(null),ek("primary"),E(null),V(nw??null),t.replace(window.location.pathname,{scroll:!1}),r.tabs}ex(i),eb(s),s||"secondary"!==eS.current||ek("primary");let a="secondary"===eS.current&&s?s:i,l=r.find(e=>e.id===a);return l?.kind==="session"&&l.session?(E(l.session),V(null),t.replace(`?session=${encodeURIComponent(l.session.id)}`,{scroll:!1})):l?.kind==="draft"&&(E(null),V(l.newSessionCwd),t.replace(window.location.pathname,{scroll:!1})),r}),tZ.current===e&&(tg([]),tx(null),t$(null),tW(null),tz(!1),t5(null))},[nw,t,d]),nJ=(0,i.useCallback)(e=>{let t=eM.current;if(!t)return;let n=t.getBoundingClientRect();if(n.width<=0)return;let r=oZ(n.width);eE(Math.max(r.min,Math.min(r.max,(e-n.left)/n.width)))},[]),nY=(0,i.useCallback)(e=>{e.preventDefault(),eI.current=!0,e.currentTarget.setPointerCapture(e.pointerId),nJ(e.clientX)},[nJ]),nZ=(0,i.useCallback)(e=>{eI.current&&nJ(e.clientX)},[nJ]),nX=(0,i.useCallback)(()=>{eI.current=!1},[]),nG=(0,i.useCallback)(e=>{let t=oZ(eL);if("ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault();let n="ArrowLeft"===e.key?-1:1;eE(e=>Math.max(t.min,Math.min(t.max,e+.05*n)))}else("Home"===e.key||"End"===e.key)&&(e.preventDefault(),eE("Home"===e.key?t.min:t.max))},[eL]),nQ=(0,i.useMemo)(()=>sw(ed,"primary"),[ed]),n0=(0,i.useMemo)(()=>sw(ed,"secondary"),[ed]),n1=(0,i.useMemo)(()=>nQ.find(e=>e.id===ef)??nQ[0]??null,[nQ,ef]),n2=(0,i.useMemo)(()=>ey?ed.find(e=>e.id===ey)??null:null,[ed,ey]),n4=!c&&eL>=600,n8=!!(n4&&ey&&n2&&ef!==ey);eC.current=n8;let n6=!n8||"primary"===ej,n5=(0,i.useCallback)((e,n)=>{if(ek(n),"session"===e.kind&&e.session){Z.current=null,tZ.current!==e.session.id&&(tS.current=null,t3(e.session.id),t$(null),tW(null),tz(!1),t5(null)),E(e.session),V(null),t.replace(`?session=${encodeURIComponent(e.session.id)}`,{scroll:!1});return}Z.current=e.newSessionDraftKey,E(null),V(e.newSessionCwd),tY(null),t4(null),tg([]),tx(null),tS.current=null,t$(null),tW(null),tz(!1),t5(null),t.replace(window.location.pathname,{scroll:!1})},[t,t3]),n7=(0,i.useCallback)(e=>{let t="secondary"===e?n2:n1;t&&n5(t,e)},[n5,n1,n2]);(0,i.useLayoutEffect)(()=>{let e=eM.current;if(!e)return;let t=e=>{if(eT(e),e<600)return;let t=oZ(e);eE(e=>Math.max(t.min,Math.min(t.max,e)))};t(e.getBoundingClientRect().width);let n=new ResizeObserver(([e])=>t(e.contentRect.width));return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>{if(!ey||n4)return;let e="secondary"===ej?n2:n1;(ec(t=>sS(t,e?.id??null)),eb(null),e)?(ex(e.id),n5(e,"primary")):ek("primary")},[ej,n4,n5,n1,n2,ey]);let n9=(0,i.useCallback)(e=>{let t=ed.find(t=>t.id===e);t&&(ex(e),n5(t,"primary"))},[ed,n5]),re=(0,i.useCallback)(e=>{let t=ed.find(t=>t.id===e);t&&(eb(e),n5(t,"secondary"))},[ed,n5]),rt=(0,i.useCallback)(e=>{let t=ed.find(t=>t.id===e);if(!t)return;let n=n8?sb(t):"primary";"secondary"===n?eb(e):ex(e),n5(t,n)},[ed,n5,n8]),rr=(0,i.useCallback)(e=>{let n=eg.current.find(t=>t.id===e);if(n?.kind==="draft"&&n.newSessionDraftKey){let e=eP(n.newSessionDraftKey);if((n.dirty||e&&(e.value.trim()||e.images.length>0))&&!window.confirm(d("chatTabs.discardDraft")))return!1;eD(n.newSessionDraftKey)}return ec(n=>{let{tabs:r,nextActiveTabId:i,nextSplitTabId:s}=sE(n,e,ef??"",ey);if(0===r.length){let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=`new:${e}:${nw??""}`;eO(o8(nw??""),n),Z.current=n,Y(e);let r=sN([],nw,n,d("i18n.newSession"));return ex(r.tabId),eb(null),ek("primary"),E(null),V(nw),t.replace(window.location.pathname,{scroll:!1}),r.tabs}ex(i),eb(s),s||"secondary"!==ej||ek("primary");let a="secondary"===ej&&s?s:i,l=r.find(e=>e.id===a)??r.find(e=>e.id===i);return l?.kind==="session"&&l.session?(E(l.session),V(null),t.replace(`?session=${encodeURIComponent(l.session.id)}`,{scroll:!1})):l?.kind==="draft"&&(E(null),V(l.newSessionCwd),t.replace(window.location.pathname,{scroll:!1})),r}),!0},[ej,ef,nw,t,ey,d]),ri=(0,i.useCallback)(e=>{var n;let r=n8&&("secondary"===e||"primary"!==e&&"secondary"===ej),i=((n=r?n2:n1)?"session"===n.kind?n.session?.cwd??null:n.newSessionCwd:null)??nw,s="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,a=`new:${s}:${i??""}`;eO(o8(i??""),a),Z.current=a,Y(s);let{tabs:l,tabId:o}=sN(ed,i,a,d("i18n.newSession"),r?"secondary":"primary");ec(l),r?(eb(o),ek("secondary")):(ex(o),ek("primary")),E(null),V(i),t.replace(window.location.pathname,{scroll:!1})},[ej,nw,ed,n8,n1,t,n2,d]),rs=(0,i.useCallback)(async(e,t)=>{let n=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await n.json();if(!n.ok||!r.cwd)throw Error(r.error??`HTTP ${n.status}`);let i=r.cwd;e&&ec(t=>t.map(t=>"draft"===t.kind&&t.newSessionDraftKey===e?{...t,newSessionCwd:i,projectKey:i}:t)),e&&Z.current!==e||V(i),nj(i)},[]),ra=(0,i.useCallback)(()=>{if(ey){let e="secondary"===ej?n2:n1;ec(t=>sS(t,e?.id??null)),eb(null),ek("primary"),e&&(ex(e.id),n5(e,"primary"))}else if(n4){let e=ed.findIndex(e=>e.id===ef),n=ed[e+1]??ed[e-1];if(n)ec(e=>e.map(e=>e.id===n.id?{...e,pane:"secondary"}:e)),eb(n.id),ek("secondary"),"session"===n.kind&&n.session?(E(n.session),V(null),t.replace(`?session=${encodeURIComponent(n.session.id)}`,{scroll:!1})):"draft"===n.kind&&(E(null),V(n.newSessionCwd),t.replace(window.location.pathname,{scroll:!1}));else{let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=`new:${e}:${nw??""}`;eO(o8(nw??""),n),Z.current=n,Y(e);let{tabs:r,tabId:i}=sN(ed,nw,n,d("i18n.newSession"),"secondary");ec(r),eb(i),ek("secondary"),E(null),V(nw),t.replace(window.location.pathname,{scroll:!1})}}},[ej,ef,nw,n4,ed,n5,n1,t,n2,ey,d]),rl=(0,i.useCallback)(()=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e8(!0)))},[]),ro=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=`file:${e}`;nh(a=>(function(e,t){let n=e.find(e=>e.id===t.tabId);if(!n)return[...e,{id:t.tabId,label:t.fileName,filePath:t.filePath,cwd:t.cwd,sourceSessionId:t.sourceSessionId,initialDisplayMode:t.modeHint,...void 0!==t.page?{pdfPage:t.page}:{},viewerState:t.modeHint?{displayMode:t.modeHint,wrapLines:!1,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId),i=!!(t.cwd&&n.cwd!==t.cwd),s=(t.page??void 0)!==n.pdfPage;return r||i||t.modeHint||s?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e};return r&&(n.sourceSessionId=t.sourceSessionId),i&&(n.cwd=t.cwd),s&&(n.pdfPage=t.page,n.viewerRevision=(e.viewerRevision??0)+1),t.modeHint?(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines??!1,scrollTop:0,scrollLeft:0,loadedBytes:e.viewerState?.loadedBytes,scrollByMode:{...e.viewerState?.scrollByMode,diff:{scrollTop:0,scrollLeft:0}}},n.viewerRevision=(e.viewerRevision??0)+1):(r||i)&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(a,{fileName:t,filePath:e,cwd:n?.cwd??nw??void 0,modeHint:i,sourceSessionId:r,...n?.page!==void 0?{page:n.page}:{},tabId:s})),nm(s),rl(),c&&e2(!1)},[nw,c,rl]),rd=(0,i.useCallback)((e,t,n)=>{let r=t?eg.current.find(e=>e.id===t)?.session?.cwd:void 0;ro(e,S(e),{sourceSessionId:t,cwd:r,...void 0!==n?{page:n}:{}})},[ro]),rc=(0,i.useCallback)(e=>{let t=ng.find(t=>t.cwd===e),n=t??oV(e);t||nf(e=>[...e,n]),nm(n.id),rl(),c&&e2(!1)},[ng,c,rl]),ru=(0,i.useCallback)(e=>{if(ng.some(t=>t.id===e))return void nf(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));let t=as(ny,e);nh(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===ng.length&&e8(!1),n}),nm(n=>n!==e?n:t)},[ny,ng]),rh=(0,i.useCallback)(()=>{N&&window.open(`/api/sessions/${encodeURIComponent(N.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[N]);(0,i.useEffect)(()=>{if(N)ec(e=>e.some(e=>e.id===N.id)?e:sC(e,N).tabs),ex(e=>e??N.id);else if(K){let e=Z.current??J;ec(t=>{let n=`draft:${e}`;return t.some(e=>e.id===n)?t:sN(t,K,e,d("i18n.newSession")).tabs}),ex(e=>e??`draft:${Z.current??J}`)}},[K,J,N,d]);let rp=(0,i.useCallback)(e=>{ec(t=>sk(t,e))},[]),rm=(e,t,n,i,s,a)=>{let l=e?U.has(e.id):!!(N&&U.has(N.id));return(0,r.jsx)(sp,{session:e,searchTarget:i&&eR?.sessionId===e?.id?eR:null,onSearchTargetHandled:ez,initialScrollPosition:e?ea.current.get(e.id)??null:null,onScrollPositionChange:el,sessionRunning:l,newSessionCwd:t,newSessionDraftKey:n,onDraftChange:e$,onKeepTabOpen:rp,onNewSessionCwdChange:!e&&t?e=>rs(n,e):void 0,recentProjectPaths:T,pinnedCwds:$,homeDir:z,worktreeInfo:A,draftPersistenceWarning:ep,onAgentEnd:nH,onAttentionNeeded:nU,onSessionCreated:nD,onSessionForked:nq,modelsRefreshKey:eU,chatInputRef:i?td:void 0,isFocusedPane:i,isVisiblePane:a,onBranchDataChange:i?tI:void 0,onSystemPromptChange:i?tq:void 0,onSystemToolsChange:i?tK:void 0,onSystemInfoLoaderChange:i?tV:void 0,onOutlineViewChange:i?nr:void 0,onSessionStatsChange:i?tX:void 0,onSessionStatsPanelOpen:na,onContextUsageChange:i?t8:void 0,onOpenFile:rd,onOpenSession:nz,onAskInNewChat:nK,quoteSelectionEnabled:y,initialPrompt:tc?.sessionId===e?.id?tc?.text:void 0,onInitialPromptConsumed:th,soundEnabled:u,playDoneSound:f,unlockAudio:x},s??ei)},rg=(0,i.useCallback)(e=>{e&&t5(null),ty(e),e||tk(null)},[]),rf=(0,i.useCallback)(async()=>{if(N){tk(null),tw(!0);try{let e=new URLSearchParams({format:"md"});tf&&e.set("leafId",tf),e.set("tz",String(-new Date().getTimezoneOffset()));let t=await fetch(`/api/sessions/${encodeURIComponent(N.id)}/export?${e}`);if(!t.ok){let e=await t.json().catch(()=>null);tk(e?.error==="empty"?d("history.exportEmpty"):d("history.exportFailed"));return}let n=await t.blob(),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=function(e){if(!e)return null;let t=/filename\*=UTF-8''([^;]+)/i.exec(e);if(t?.[1])try{return decodeURIComponent(t[1])}catch{return t[1]}return/filename="([^"]+)"/i.exec(e)?.[1]??null}(t.headers.get("Content-Disposition"))??"session.md",document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(r),ty(!1)}catch{tk(d("history.exportFailed"))}finally{tw(!1)}}},[tf,N,d]),rx=K??(null===N&&nw?nw:null),rv=null===N&&rx?`new:${J}:${rx}`:null,ry=n8&&"secondary"===ej?n2:n1,rb=ry?.kind==="draft"?ry.newSessionDraftKey:0===ed.length?rv:null;(0,i.useLayoutEffect)(()=>{Z.current=rb},[rb]);let rw=null!==N||null!==rx,rj=!!(N&&tJ?.sessionId===N.id),rk=N?.cwd??rx;(0,i.useEffect)(()=>{if(eV(null),eY(!1),e0(null),!rk)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rk)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eV(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[rk]);let rS=(0,i.useCallback)(async()=>{if(rk&&!eZ){eG(!0),e0(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rk})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eV(t),eY(!1),e_(e=>e+1),es(e=>e+1)}catch(e){e0(e instanceof Error?e.message:String(e))}finally{eG(!1)}}},[eZ,rk]),rC=nu.find(e=>e.id===np)??null,rN=nw?S(nw)||nw:null,rE=rN?`${rN} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==rE&&(document.title=rE)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rE]);let rM=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(eo,{selectedSessionId:N?.id??null,onSelectSession:nT,onOpenSessionInNewTab:nW,onNewSession:n$,initialSessionId:nE,skipInitialProjectSelection:null!==l.requestedCwd,refreshKey:en,onSessionDeleted:nV,selectedCwd:nw??N?.cwd??K??null,onCwdChange:nL,onOpenFile:ro,onOpenTerminal:rc,explorerRefreshKey:eA,onExplorerRefresh:n_,onAtMention:nS,onAtMentions:nC,onBackgroundTaskDone:C,onRunningSessionIdsChange:q,onSessionsChange:L,pinnedCwds:$,onTogglePinnedCwd:P,onHomeDirChange:D,onWorktreeInfoChange:F}),(0,r.jsx)("div",{className:"sidebar-footer",children:(0,r.jsxs)("button",{type:"button",onClick:()=>eH(function(e,t=aP()){if(!t)return"general";try{let n=az(t).section;if(!("string"==typeof n&&a$.includes(n)))return"general";return aW.has(n)&&!e?"general":n}catch{return"general"}}(rk)),onPointerEnter:()=>aL(rk),onFocus:()=>aL(rk),title:d("common.settings"),"aria-label":d("common.settings"),className:"sidebar-footer-item",children:[(0,r.jsx)("span",{className:"sidebar-section-gutter",children:(0,r.jsx)(o3,{})}),(0,r.jsx)("span",{children:d("common.settings")})]})})]}),rI=e=>rw&&eK?.requiresTrust&&!eK.trusted?(0,r.jsxs)("button",{type:"button",onClick:()=>{e0(null),eY(!0)},title:d("trust.resourcesNotLoaded"),"aria-label":d("trust.resourcesNotLoaded"),style:{display:"flex",alignItems:"center",justifyContent:e?"flex-start":"center",gap:6,width:e?"100%":void 0,minHeight:e?32:void 0,height:e?void 0:"100%",padding:e?"6px 12px":"0 12px",background:e?"color-mix(in srgb, var(--warning) 8%, var(--bg-panel))":"none",border:"none",borderRight:e?"none":"1px solid var(--border)",borderBottom:e?"1px solid var(--border)":"none",color:"var(--warning)",cursor:"pointer",flexShrink:0,fontSize:11,lineHeight:e?1.35:void 0,textAlign:"left"},className:e?void 0:"workspace-header-action","data-mobile-trust-banner":e?"true":void 0,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),(0,r.jsx)("span",{children:d("trust.resourcesNotLoaded")})]}):null,rL=(e,t)=>{let n=t?.sessionTools??!0;return(e||rw)&&(e||n||H)?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[H&&N?.relation?.kind==="subagent"&&(0,r.jsx)("button",{type:"button",onClick:()=>nP(O.root),title:d("agentSwitcher.backToMain"),"aria-label":d("agentSwitcher.backToMain"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},className:"workspace-header-action",children:(0,r.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,r.jsx)("path",{d:"M19 12H5"}),(0,r.jsx)("path",{d:"m12 19-7-7 7-7"})]})}),H&&(0,r.jsxs)("button",{ref:e?void 0:tH,type:"button",onClick:e=>{tU.current=e.currentTarget,ni("agents")},title:d("agentSwitcher.title"),"aria-label":d("agentSwitcher.title"),"aria-pressed":"agents"===t6,"aria-expanded":"agents"===t6,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"agents",style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"agents"===t6?"var(--bg-selected)":"none",border:"none",color:"agents"===t6?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},className:"workspace-header-action","data-mobile-toolbar-action":e?"agents":void 0,children:[(0,r.jsx)(G,{size:13}),(0,r.jsx)("span",{"aria-hidden":"true",style:{position:"absolute",top:2,right:2,minWidth:13,height:13,padding:"0 3px",display:"grid",placeItems:"center",borderRadius:4,background:"var(--bg-selected)",color:"var(--accent)",fontSize:10,lineHeight:1,fontVariantNumeric:"tabular-nums"},children:O.subagents.length})]}),n&&(e?tC&&(0,r.jsx)("button",{type:"button",onClick:()=>ni("branches"),title:d("i18n.branches"),"aria-label":d("i18n.branches"),"aria-pressed":"branches"===t6,"data-top-panel-trigger":"branches",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"branches"===t6?"var(--bg-selected)":"none",border:"none",color:"branches"===t6?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},className:"workspace-header-action","data-mobile-toolbar-action":"branches",children:(0,r.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,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}):(0,r.jsx)(oL,{tree:tm,activeLeafId:tf,onLeafChange:tL,inline:!0,compact:!0,open:"branches"===t6,onToggle:()=>ni("branches"),disabled:!tC,hasSession:!0})),n&&(0,r.jsx)(oT,{mobile:e,disabled:!N,menuOpen:tv,exporting:tb,error:tj,labels:{full:d("history.full"),unsaved:d("history.unsaved"),menu:d("history.menu"),exportMarkdown:d("history.exportMarkdown"),exportMarkdownTitle:d("history.exportMarkdownTitle")},onMenuOpenChange:e=>{rg(e)},onViewFullHistory:()=>{rh()},onExportMarkdown:()=>{rf()}}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:tF,type:"button",onClick:()=>ns("system"),disabled:e&&!rw,title:d("system.prompt"),"aria-label":d("system.prompt"),"aria-pressed":"system"===t6,"aria-expanded":"system"===t6,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"system",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"system"===t6?"var(--bg-selected)":"none",border:"none",cursor:e&&!rw?"not-allowed":"pointer",color:"system"===t6?"var(--text)":"var(--text-muted)",opacity:e&&!rw?.45:1,transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rw)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===t6?"var(--text)":"var(--text-muted)"},className:"workspace-header-action","data-mobile-toolbar-action":e?"system":void 0,children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,r.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,r.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>ns("tools"),disabled:e&&!rw,title:d("tools.title"),"aria-label":d("tools.title"),"aria-pressed":"tools"===t6,"aria-expanded":"tools"===t6,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"tools",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"tools"===t6?"var(--bg-selected)":"none",border:"none",cursor:e&&!rw?"not-allowed":"pointer",color:"tools"===t6?"var(--text)":"var(--text-muted)",opacity:e&&!rw?.45:1,transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rw)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===t6?"var(--text)":"var(--text-muted)"},className:"workspace-header-action","data-mobile-toolbar-action":e?"tools":void 0,children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z"})})}),n&&e&&(0,r.jsx)("button",{type:"button",onClick:()=>ni("outline"),title:d("chatMinimap.userOutline")||"Outline","aria-label":d("chatMinimap.userOutline")||"Outline","aria-pressed":"outline"===t6,"aria-expanded":"outline"===t6,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"outline",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"outline"===t6?"var(--bg-selected)":"none",border:"none",color:"outline"===t6?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="outline"===t6?"var(--text)":"var(--text-muted)"},className:"workspace-header-action","data-mobile-toolbar-action":"outline",children:(0,r.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,r.jsx)("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),(0,r.jsx)("line",{x1:"4",y1:"12",x2:"14",y2:"12"}),(0,r.jsx)("line",{x1:"4",y1:"18",x2:"17",y2:"18"})]})})]})]}):null},rT=N?p(N):d("i18n.newSession"),r$=e=>{if(!e&&(!rw||!rj))return null;let t=t2??tJ?.contextUsage;if(!tJ&&(!e||!t))return null;let n=tJ?.tokens,i=tJ?.cost??0,s=i>=.01?`$${i.toFixed(2)}`:i>0?"<$0.01":"$0.00",a=(n?.cacheRead??0)+(n?.cacheWrite??0)+(n?.input??0),l=a>0?(n?.cacheRead??0)/a*100:null,c=[];if(n&&(c.push(`in: ${n.input.toLocaleString(o)}`),c.push(`out: ${n.output.toLocaleString(o)}`),c.push(`cache read: ${n.cacheRead.toLocaleString(o)}`),c.push(`cache write: ${n.cacheWrite.toLocaleString(o)}`),null!==l&&c.push(`${d("session.cacheHitRate")}: ${l.toFixed(1)}%`),i>0&&c.push(`cost: $${i.toFixed(4)}`)),t?.contextWindow){let e=t.percent;c.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${t.contextWindow.toLocaleString()} tokens`)}let u=c.join(" | ");return(0,r.jsx)("button",{type:"button",onClick:()=>ni("session"),disabled:!rw,title:u||d("session.title"),"aria-label":u||d("session.title"),"aria-pressed":"session"===t6,"aria-expanded":"session"===t6,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"session",className:"workspace-header-action","data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:"auto",display:"flex",alignItems:"center",justifyContent:"flex-end",minWidth:0,gap:e?8:10,paddingLeft:e?6:8,paddingRight:e?6:8,height:"100%",overflow:"hidden",background:"session"===t6?"var(--bg-selected)":"none",border:"none",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:rw?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{rw&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===t6?"var(--text)":"var(--text-muted)"},children:s&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text-muted)",fontWeight:400,flexShrink:0,lineHeight:1},children:s})})},rR=e=>(0,r.jsx)("button",{ref:tO,type:"button",onClick:nd,"aria-controls":"file-panel","aria-expanded":e4,title:e4?d("files.hidePanel"):d("files.showPanel"),"aria-label":e4?d("files.hidePanel"):d("files.showPanel"),className:"workspace-header-action","data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:tJ||t2?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:e4?(0,r.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,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})});return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("style",{children:`
201
- @media (max-width: 640px) {
202
- .sidebar-overlay-backdrop.sidebar-mobile-pending {
203
- opacity: 0 !important;
204
- pointer-events: none !important;
205
- }
206
- .sidebar-container.sidebar-mobile-pending.sidebar-open {
207
- transform: translateX(calc(-100% - env(safe-area-inset-left)));
208
- box-shadow: none;
209
- }
210
- }
211
- `}),(0,r.jsxs)("div",{style:{display:"flex",width:"100%",height:"var(--app-viewport-height, 100dvh)",paddingLeft:"env(safe-area-inset-left)",paddingRight:"env(safe-area-inset-right)",overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{className:`sidebar-overlay-backdrop${e5?"":" sidebar-mobile-pending"}`,"aria-hidden":"true",onClick:no,style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!e1,pointerEvents:e1?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:ts.panelRef,id:"session-sidebar",role:"navigation","aria-label":"Pi Web","aria-hidden":!!c&&!e1||void 0,inert:!!c&&!e1||void 0,className:`sidebar-container${e1?" sidebar-open":" sidebar-closed"}${e5?"":" sidebar-mobile-pending"}${ts.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${ts.width}px`,"--panel-transition":`${oJ(ts.width)}ms`,background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,paddingTop:"env(safe-area-inset-top)",paddingBottom:"env(safe-area-inset-bottom)",zIndex:200},children:rM}),e1&&(0,r.jsx)("div",{...ts.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${ts.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${d("layout.resizeSidebar")}: ${d("layout.resizeHint")}`}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tp,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{className:"workspace-header",style:{position:"relative"},children:[(0,r.jsx)("button",{ref:tB,"data-dialog-focus-fallback":"true",className:"workspace-header-action",onClick:nl,title:e1?d("sidebar.hide"):d("sidebar.show"),"aria-label":e1?d("sidebar.hide"):d("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:e1?(0,r.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,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),c&&(0,r.jsxs)("div",{"data-mobile-toolbar":"true",style:{display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[rL(!0),r$(!0),rR(!0)]}),!c&&(0,r.jsxs)(r.Fragment,{children:[!n8&&rw&&ed.length>0&&(0,r.jsx)("div",{style:{flex:"0 1 auto",minWidth:0,height:"100%",overflow:"hidden",display:"flex",alignItems:"stretch"},children:(0,r.jsx)(sv,{tabs:ed,activeTabId:ef??"",activePane:"primary",runningSessionIds:U,onSelectTab:rt,onCloseTab:rr,onPinTab:rp,onNewTab:ri,onToggleSplit:ra,canSplit:n4,unifiedHeader:!0})}),e1||!rw||ed.length>0?null:(0,r.jsx)("button",{type:"button",onClick:()=>ni("session"),title:rT,"aria-label":rT,"aria-pressed":"session"===t6,"aria-expanded":"session"===t6,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"session",className:"workspace-header-action","data-collapsed-session-title":"true",style:{display:"flex",alignItems:"center",minWidth:0,flex:1,height:"100%",padding:"0 12px",border:"none",borderRight:"1px solid var(--border)",background:"session"===t6?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:rT})}),(0,r.jsxs)("div",{"data-desktop-header-actions":"true",style:{marginLeft:"auto",display:"flex",alignItems:"stretch",height:"100%",flexShrink:0},children:[rI(!1),r$(!1),rL(!1,{sessionTools:rj})]})]}),!c&&rR(!1),t6&&ne&&(0,r.jsxs)("div",{ref:t_,id:"workspace-top-panel",role:"region","aria-label":"agents"===t6?d("agentSwitcher.title"):"system"===t6?d("system.prompt"):"tools"===t6?d("tools.title"):"outline"===t6?d("chatMinimap.userOutline"):"branches"===t6?d("i18n.branches"):d("session.title"),style:{position:"fixed",top:ne.top,left:ne.left,width:ne.width,maxHeight:`calc(100dvh - ${ne.top}px - 16px)`,overflowY:"agents"===t6?"visible":"auto",zIndex:520},children:["agents"===t6&&O&&N&&(0,r.jsx)(oO,{rootSession:O.root,subagents:O.subagents,selectedSessionId:N.id,runningSessionIds:U,onSelectSession:nP,onOpenInNewTab:nW}),("system"===t6||"tools"===t6||"session"===t6||"outline"===t6||"branches"===t6)&&(0,r.jsxs)("div",{className:"session-sheet-pop",style:{maxHeight:"inherit",overflowY:"auto"},children:["system"===t6&&(0,r.jsx)(o$,{loading:tP,prompt:tT,translate:d}),"tools"===t6&&(0,r.jsx)(oP,{loading:tP,tools:tR,translate:d}),"branches"===t6&&(0,r.jsx)("div",{style:{borderBottom:"1px solid var(--border)"},children:(0,r.jsx)(oI,{tree:tm,activeLeafId:tf,onLeafChange:tL,hasSession:rw})}),"outline"===t6&&(0,r.jsx)(r5,{view:t7??{items:[],onJumpToEntry:async()=>{}},onClose:nn}),"session"===t6&&(0,r.jsx)("div",{className:"session-info-popover",style:{position:"relative",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",boxShadow:"0 8px 24px rgba(0,0,0,0.08)",padding:c?"12px 14px 14px":"14px 20px 16px"},children:tJ?(()=>{let e=tJ.totalActiveMs??0,t={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},n=(e,n,i="copy")=>{let s=tG===e;return(0,r.jsx)("button",{type:"button",className:"session-copy-btn","data-copied":s||void 0,title:s?d("session.copied"):`${d(t[e])}
212
- ${n}`,"aria-label":d(t[e]),onClick:()=>t1(e,n),style:{color:s?"var(--accent)":void 0},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:R(13),strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s?(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"}):"file"===i?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 3 14 8 19 8"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})})},s=e=>(0,r.jsx)("div",{className:"session-stats-label",children:e}),a=(e,t=!1)=>(0,r.jsx)("div",{className:"session-stats-num",style:t?{color:"var(--text)"}:void 0,children:e}),l=(e,t,n)=>(0,r.jsxs)("section",{className:"session-stats-section",children:[(0,r.jsxs)("div",{className:"session-stats-heading",children:[(0,r.jsx)("span",{children:e}),t]}),n]}),c=t2??tJ.contextUsage,u=c?.percent??(c?.tokens!==null&&c?.contextWindow?c.tokens/c.contextWindow*100:null),h=null!==u?Math.min(100,Math.max(0,u)):0,p=null!==u&&u>=85,m=null!==u&&u>=70&&u<85,g=c?.tokens!==null&&c?.contextWindow?Math.max(0,c.contextWindow-c.tokens):null,f=c?.contextWindow?l(d("session.activeContext"),null!==u&&(0,r.jsxs)("span",{style:{fontWeight:400,color:p?"var(--danger)":m?"color-mix(in srgb, var(--warning) 95%, transparent)":"var(--text)"},children:[u.toFixed(1),"%"]}),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{height:4,borderRadius:2,background:"var(--border)",overflow:"hidden",margin:"2px 0 10px"},children:(0,r.jsx)("div",{style:{width:`${h}%`,height:"100%",background:p?"var(--danger)":m?"var(--warning)":"var(--accent)",borderRadius:2,transition:"width 0.3s ease"}})}),(0,r.jsxs)("div",{className:"session-stats-table",children:[null!==c.tokens&&(0,r.jsxs)(r.Fragment,{children:[s(d("session.contextUsed")),a(ti(c.tokens,o),!0)]}),null!==g&&(0,r.jsxs)(r.Fragment,{children:[s(d("session.contextRemaining")),a(ti(g,o))]}),s(d("session.contextWindow")),a(ti(c.contextWindow,o))]}),p&&(0,r.jsx)("div",{className:"session-stats-note",style:{color:"var(--danger)"},children:d("chat.contextHighWarning")})]})):null,{tokens:x,costs:v}=tJ,y=x.cacheRead+x.cacheWrite,b=y+x.input>0?`${(x.cacheRead/(y+x.input)*100).toFixed(1)}%`:null,w=!!v&&v.input+v.output+v.cacheRead+v.cacheWrite>0,j=tJ.cost>0,k=e=>e>0&&e<.01?"<$0.01":`$${e.toFixed(2)}`,S=[[d("session.input"),x.input,v?.input],[d("session.output"),x.output,v?.output],[d("session.cacheRead"),x.cacheRead,v?.cacheRead],[d("session.cacheWrite"),x.cacheWrite,v?.cacheWrite]],C=l(d("session.cumulativeTokens"),null,(0,r.jsx)(r.Fragment,{children:(0,r.jsxs)("div",{className:"session-stats-table",style:j?{gridTemplateColumns:"1fr max-content max-content"}:void 0,children:[S.map(([e,t,n])=>(0,r.jsxs)(i.Fragment,{children:[s(e),a(ti(t,o)),j&&a(w&&void 0!==n?k(n):"")]},e)),(0,r.jsx)("div",{className:"session-stats-rule"}),s(d("session.total")),a(ti(x.total,o),!0),j&&a(k(tJ.cost),!0),j&&x.total>0&&(0,r.jsxs)(r.Fragment,{children:[s(d("session.avgPrice")),(0,r.jsxs)("div",{className:"session-stats-num",style:{gridColumn:"2 / -1"},children:["$",(tJ.cost/x.total*1e6).toFixed(2),"/M"]})]}),b&&(0,r.jsxs)(r.Fragment,{children:[s(d("session.cacheHitRate")),(0,r.jsx)("div",{className:"session-stats-num",style:{gridColumn:"2 / -1"},children:b})]})]})})),E=N?z&&N.cwd.startsWith(z)?`~${N.cwd.slice(z.length)}`:N.cwd:null,M=(e,t,...n)=>(0,r.jsxs)("div",{className:"session-stats-text",children:[(0,r.jsx)("span",{title:t,className:"session-stats-ellipsis",children:e}),n]}),I=l(d("session.infoSection"),null,(0,r.jsxs)("div",{className:"session-stats-table",style:{gridTemplateColumns:"max-content minmax(0, 1fr)"},children:[tJ.sessionName&&(0,r.jsxs)(r.Fragment,{children:[s(d("session.name")),M((0,r.jsx)("span",{style:{color:"var(--text)"},children:tJ.sessionName}),tJ.sessionName)]}),N&&E&&(0,r.jsxs)(r.Fragment,{children:[s(d("session.directory")),(0,r.jsxs)("div",{className:"session-stats-text",children:[(0,r.jsx)("span",{title:N.cwd,className:"session-stats-ellipsis",style:{direction:"rtl",textAlign:"left"},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:E})}),n(N.isWorktree?"gitWorktree":"projectDir",N.cwd)]})]}),N?.branch&&(0,r.jsxs)(r.Fragment,{children:[s(d("session.branch")),M(N.branch,N.branch)]}),s(d("session.id")),M(tJ.sessionId?`${tJ.sessionId.slice(0,8)}…${tJ.sessionId.slice(-6)}`:"?",tJ.sessionId,tJ.sessionId?(0,r.jsx)(i.Fragment,{children:n("id",tJ.sessionId)},"i"):null,tJ.sessionFile?(0,r.jsx)(i.Fragment,{children:n("file",tJ.sessionFile,"file")},"f"):null),(0,r.jsx)("div",{className:"session-stats-rule"}),s(d("session.messages")),(0,r.jsxs)("div",{style:{color:"var(--text-muted)"},children:[tJ.userMessages," ",d("session.user").toLowerCase()," \xb7 ",tJ.assistantMessages," ",d("session.assistant").toLowerCase()," \xb7 ",(0,r.jsxs)("span",{style:{whiteSpace:"nowrap"},children:[tJ.toolCalls," ",d("session.toolCalls").toLowerCase()]})]}),e>0&&(0,r.jsxs)(r.Fragment,{children:[s(d("session.activeTime")),M((e=>{if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`})(e))]})]}));return(0,r.jsxs)("div",{className:"session-stats-grid",children:[f,C,I]})})():(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:d("session.load")})})]})]})]}),c&&rw&&ed.length>1&&(0,r.jsx)("div",{"data-mobile-chat-tabs":"true",style:{boxShadow:"inset 0 -1px 0 var(--border)",background:"var(--bg-panel)",height:"var(--workspace-header-height, 30px)",minHeight:"var(--workspace-header-height, 30px)",width:"100%",maxWidth:"100%",minWidth:0,overflow:"hidden",display:"flex",alignItems:"stretch"},children:(0,r.jsx)(sv,{tabs:ed,activeTabId:ef??"",activePane:"primary",runningSessionIds:U,onSelectTab:rt,onCloseTab:rr,onPinTab:rp,onNewTab:ri,canSplit:!1,isMobile:!0})}),c&&rI(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative",display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{ref:eM,style:{flex:1,overflow:"hidden",position:"relative",display:"grid",minHeight:0,gridTemplateColumns:n8?`${100*eN}% 0 minmax(0, 1fr)`:"minmax(0, 1fr)",gridTemplateRows:n8?"auto minmax(0, 1fr)":"minmax(0, 1fr)"},children:rw?(0,r.jsxs)(r.Fragment,{children:[n8&&(0,r.jsx)("div",{style:{gridColumn:1,gridRow:1,minWidth:0,overflow:"hidden"},onPointerDownCapture:()=>n7("primary"),children:(0,r.jsx)(sv,{tabs:nQ,activeTabId:ef??"",activePane:"primary"===ej?"primary":"secondary",runningSessionIds:U,onSelectTab:n9,onCloseTab:rr,onPinTab:rp,onNewTab:()=>ri("primary"),onToggleSplit:ra,canSplit:!1})}),ed.length>0?ed.map(e=>{let t=n8?sb(e):"primary",n=e.id===("secondary"===t?ey:ef),i="secondary"===t?"secondary"===ej:n6,s=e.mountKey??e.id;return(0,r.jsx)("div",{"data-chat-pane":t,onPointerDownCapture:()=>{n&&n8&&n7(t)},style:{gridColumn:"secondary"===t?3:1,gridRow:n8?2:1,display:n?"flex":"none",flexDirection:"column",minWidth:0,minHeight:0,overflow:"hidden",position:"relative",borderLeft:"secondary"===t?"1px solid var(--border)":void 0},children:rm("session"===e.kind?e.session:null,"draft"===e.kind?e.newSessionCwd:null,"draft"===e.kind?e.newSessionDraftKey:null,n&&i,s,n)},s)}):(0,r.jsx)("div",{style:{gridColumn:1,gridRow:n8?2:1,minHeight:0,display:"flex",flexDirection:"column"},children:rm(N,rx,rv,n6,void 0,!0)}),n8&&(0,r.jsx)("div",{className:"split-chat-resize-handle",style:{gridColumn:2,gridRow:"1 / 3"},role:"separator","aria-orientation":"vertical","aria-valuemin":Math.round(100*oZ(eL).min),"aria-valuemax":Math.round(100*oZ(eL).max),"aria-valuenow":Math.round(100*eN),tabIndex:0,title:d("chatTabs.splitView",{defaultValue:"调整分屏大小"}),onPointerDown:nY,onPointerMove:nZ,onPointerUp:nX,onPointerCancel:nX,onKeyDown:nG,onDoubleClick:()=>eE(.5)}),n8&&n2&&(0,r.jsx)("div",{style:{gridColumn:3,gridRow:1,minWidth:0,overflow:"hidden",borderLeft:"1px solid var(--border)"},onPointerDownCapture:()=>n7("secondary"),children:(0,r.jsx)(sv,{tabs:n0,activeTabId:ey??"",activePane:"secondary"===ej?"primary":"secondary",runningSessionIds:U,onSelectTab:re,onCloseTab:rr,onPinTab:rp,onNewTab:()=>ri("secondary"),onClosePane:ra,isSecondaryPane:!0})})]}):"validating"===X?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:d("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontSize:12},children:l.requestedCwd})]}):"error"===X?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--danger)"},children:d("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontSize:12},children:l.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:ee})]}):null})})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${e4?" is-open":""}`,onClick:()=>nc(!0)}),e4&&(0,r.jsx)("div",{...ta.separatorProps,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${ta.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${d("layout.resizeFilePanel")}: ${d("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:ta.panelRef,id:"file-panel","aria-hidden":!e4,inert:!e4||void 0,className:`right-panel-container${e4?" right-panel-open":" right-panel-closed"}${ta.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${ta.width}px`,"--panel-transition":`${oJ(ta.width)}ms`,display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{className:"workspace-header",style:{background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,height:"100%",overflow:"hidden"},children:(0,r.jsx)(ai,{tabs:ny,activeTabId:np??"",onSelectTab:nm,onCloseTab:ru})}),(0,r.jsx)("button",{type:"button",onClick:()=>nc(!0),className:"workspace-header-action right-panel-header-close","aria-controls":"file-panel",title:d("files.hidePanel"),"aria-label":d("files.hidePanel"),style:{alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:(0,r.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,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})})]}),(0,r.jsxs)("div",{className:"file-preview-pane",style:{flex:1,minHeight:0,overflow:"hidden",paddingBottom:"env(safe-area-inset-bottom)"},children:[rC?.filePath?(0,r.jsx)(s9,{filePath:rC.filePath,cwd:rC.cwd??nw??void 0,sourceSessionId:rC.sourceSessionId,gitRefreshKey:eA,initialDisplayMode:rC.initialDisplayMode,initialState:rC.viewerState,watchEnabled:e3,pdfPage:rC.pdfPage,onStateChange:e=>nb(rC.id,rC.viewerRevision??0,e),onMentionLines:e4?nN:void 0,onAtMention:nS,onOpenFile:(e,t)=>ro(e,S(e),{sourceSessionId:rC.sourceSessionId,cwd:rC.cwd,page:t})},`${rC.id}:${rC.viewerRevision??0}`):ng.some(e=>e.id===np)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:d("files.noneOpen")}),ng.map(e=>(0,r.jsx)("div",{hidden:e.id!==np,style:{width:"100%",height:"100%"},children:(0,r.jsx)(oq,{tab:e,active:e4&&e.id===np,onRestart:()=>nf(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n,r;return t="restart"===e.closing?oV(e.cwd):null,n=ng.filter(t=>t.id!==e.id),r=as(ny,e.id),void(nf(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nm(n=>n!==e.id?n:t?.id??r),!t&&!n.length&&!nu.length&&e8(!1))},onCloseError:()=>nf(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),eB&&(0,r.jsx)(oj,{cwd:rk,sessionId:N?.id??null,initialSection:eB,quoteSelectionEnabled:y,onQuoteSelectionChange:j,soundEnabled:u,onSoundToggle:h,onClose:()=>{eH(null),e_(e=>e+1)},onSessionReloaded:()=>es(e=>e+1),onModelsChanged:()=>e_(e=>e+1)}),eJ&&rk&&(0,r.jsx)(ok,{cwd:rk,busy:eZ,error:eQ,onCancel:()=>{eZ||eY(!1)},onConfirm:()=>void rS()})]})}},14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>p,getPresetFromTools:()=>h,sn:()=>u,xG:()=>s});let r="configured",i=[r,"none","read-only","default","full"];function s(e){if(e!==r)return"none"===e?[...a]:"read-only"===e?[...l]:"full"===e?[...d]:[...o]}let a=[],l=["read","grep","find","ls"],o=["read","bash","edit","write"],d=["bash","read","edit","write","grep","find","ls"],c=new Set([...d,"powershell"]);function u(e){return"string"==typeof e&&i.includes(e)}function h(e){return p(e.filter(e=>e.active).map(e=>e.name))}function p(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>c.has(e)).sort().join(",");return t===[...l].sort().join(",")?"read-only":t===[...o].sort().join(",")?"default":t===[...d].sort().join(",")?"full":"default"}},88576:e=>{e.exports={minimap:"ChatMinimap_minimap__gDaeY",trigger:"ChatMinimap_trigger__Wb5KU",marker:"ChatMinimap_marker__NEjJc",panel:"ChatMinimap_panel__bAkor",menu:"ChatMinimap_menu__7Cur1",minimapFadeIn:"ChatMinimap_minimapFadeIn__XXu75",list:"ChatMinimap_list__g9HUb",track:"ChatMinimap_track__ZlbIX",row:"ChatMinimap_row__LGVWw",rowText:"ChatMinimap_rowText__bagDa",status:"ChatMinimap_status__U2inN"}}},e=>{e.O(0,[7523,7330,3888,5931,2981,8441,3794,7358],()=>e(e.s=9669)),_N_E=e.O()}]);