@oscharko-dev/keiko 0.2.4 → 0.2.6

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 (256) hide show
  1. package/dist/ui/csp-hashes.json +21 -20
  2. package/dist/ui/static/404.html +1 -1
  3. package/dist/ui/static/__next.__PAGE__.txt +4 -4
  4. package/dist/ui/static/__next._full.txt +11 -12
  5. package/dist/ui/static/__next._head.txt +4 -4
  6. package/dist/ui/static/__next._index.txt +4 -4
  7. package/dist/ui/static/__next._tree.txt +2 -3
  8. package/dist/ui/static/_next/static/chunks/141a63f7.b221c9ae6bf65aa1.js +1 -0
  9. package/dist/ui/static/_next/static/chunks/{29d1969dncoef.js → 1562.a7c2497354300cf6.js} +1 -1
  10. package/dist/ui/static/_next/static/chunks/1587.561c8a85eac6595a.js +1 -0
  11. package/dist/ui/static/_next/static/chunks/1688.1b48974d4820565a.js +1 -0
  12. package/dist/ui/static/_next/static/chunks/1814a212.7fd52f5815687000.js +368 -0
  13. package/dist/ui/static/_next/static/chunks/1968-bbcb89b9ce3eb26b.js +32 -0
  14. package/dist/ui/static/_next/static/chunks/1994.32d7f1649e15081f.js +1 -0
  15. package/dist/ui/static/_next/static/chunks/2063.443bb736720d0976.js +1 -0
  16. package/dist/ui/static/_next/static/chunks/2107.c1ff3a39fd003d88.js +1 -0
  17. package/dist/ui/static/_next/static/chunks/2238.1c80c539dd21caff.js +3 -0
  18. package/dist/ui/static/_next/static/chunks/3170.2539679cfc72865c.js +679 -0
  19. package/dist/ui/static/_next/static/chunks/3181.7d593f9e0f846c96.js +1 -0
  20. package/dist/ui/static/_next/static/chunks/3294.024505d0744fef2a.js +1 -0
  21. package/dist/ui/static/_next/static/chunks/3740.84a20b2730a97a3a.js +1 -0
  22. package/dist/ui/static/_next/static/chunks/3868.3ebf6f39d31a4cce.js +1 -0
  23. package/dist/ui/static/_next/static/chunks/3883.f8e3dc3fea7fdbe1.js +1 -0
  24. package/dist/ui/static/_next/static/chunks/3968.55fa02cd74fb96b3.js +1 -0
  25. package/dist/ui/static/_next/static/chunks/4444.46b9cfb85257a381.js +1 -0
  26. package/dist/ui/static/_next/static/chunks/4621-88a84538a70dcf6d.js +98 -0
  27. package/dist/ui/static/_next/static/chunks/{0i37w6dtch5bm.js → 4690.6bc5c7d6c119aa54.js} +1 -1
  28. package/dist/ui/static/_next/static/chunks/4905.e5c0de0e634d5b31.js +1 -0
  29. package/dist/ui/static/_next/static/chunks/{0r1eh0425nsf8.js → 5272.bca1ad25a75d8d0a.js} +1 -1
  30. package/dist/ui/static/_next/static/chunks/5730.56d7cdb98dbdc486.js +1 -0
  31. package/dist/ui/static/_next/static/chunks/6028.c73575c441d46324.js +1 -0
  32. package/dist/ui/static/_next/static/chunks/{1pxydolx3s42k.js → 6774.52093bc8b0ffabc8.js} +1 -1
  33. package/dist/ui/static/_next/static/chunks/6808.64f635d2f411e8a8.js +1 -0
  34. package/dist/ui/static/_next/static/chunks/6bb8c0f0.ef92cd6e0332751d.js +1005 -0
  35. package/dist/ui/static/_next/static/chunks/7301.0c053ca1f6a524e6.js +1 -0
  36. package/dist/ui/static/_next/static/chunks/7573.103bcab7ad9ec4f4.js +1 -0
  37. package/dist/ui/static/_next/static/chunks/7732.a6e5df401d584efd.js +1 -0
  38. package/dist/ui/static/_next/static/chunks/7f819917.631f7e51d345e84c.js +1 -0
  39. package/dist/ui/static/_next/static/chunks/8556.4f751fdef390f050.js +1 -0
  40. package/dist/ui/static/_next/static/chunks/8776.140362f8c6f4d7f1.js +3 -0
  41. package/dist/ui/static/_next/static/chunks/87c73c54-014124adcece3495.js +1 -0
  42. package/dist/ui/static/_next/static/chunks/8835-d642f66c1962fa68.js +1 -0
  43. package/dist/ui/static/_next/static/chunks/8948.d928ebd17b05f4df.js +1 -0
  44. package/dist/ui/static/_next/static/chunks/9211-06ff5a834d85f608.js +3 -0
  45. package/dist/ui/static/_next/static/chunks/9385.4cf1f094775e2625.js +1 -0
  46. package/dist/ui/static/_next/static/chunks/{1qlzx0yicfamw.js → 9580.c45199468eff0333.js} +1 -1
  47. package/dist/ui/static/_next/static/chunks/960-fc53cb72c81db8c2.js +1 -0
  48. package/dist/ui/static/_next/static/chunks/9682.d5b8d9ce8cb80519.js +1 -0
  49. package/dist/ui/static/_next/static/chunks/9834.a4b101bcdd6d6a02.js +7 -0
  50. package/dist/ui/static/_next/static/chunks/9976.5970067ee5af21ee.js +1 -0
  51. package/dist/ui/static/_next/static/chunks/app/_global-error/page-7bf8bd93aa11e337.js +1 -0
  52. package/dist/ui/static/_next/static/chunks/app/_not-found/page-f21e3f25e28a4fe0.js +1 -0
  53. package/dist/ui/static/_next/static/chunks/app/launch/page-e1218f7643eb0a6e.js +1 -0
  54. package/dist/ui/static/_next/static/chunks/app/layout-b771eb1e519fd8e1.js +1 -0
  55. package/dist/ui/static/_next/static/chunks/app/local-knowledge/capsule/page-97eb36a77e8d4e78.js +1 -0
  56. package/dist/ui/static/_next/static/chunks/app/local-knowledge/page-d8f34047a97108ae.js +1 -0
  57. package/dist/ui/static/_next/static/chunks/app/memoriaviva/consolidation/page-7bf8bd93aa11e337.js +1 -0
  58. package/dist/ui/static/_next/static/chunks/app/memoriaviva/detail/page-7bf8bd93aa11e337.js +1 -0
  59. package/dist/ui/static/_next/static/chunks/app/memoriaviva/page-7bf8bd93aa11e337.js +1 -0
  60. package/dist/ui/static/_next/static/chunks/app/memoriaviva/review-queue/page-7bf8bd93aa11e337.js +1 -0
  61. package/dist/ui/static/_next/static/chunks/app/page-919e12de0b674447.js +1 -0
  62. package/dist/ui/static/_next/static/chunks/ebdf2699.65a70a76e20e9c97.js +1 -0
  63. package/dist/ui/static/_next/static/chunks/framework-2da6d53e02270a60.js +1 -0
  64. package/dist/ui/static/_next/static/chunks/main-3c13180c1c50c526.js +5 -0
  65. package/dist/ui/static/_next/static/chunks/main-app-f9e2c4e6329295bb.js +1 -0
  66. package/dist/ui/static/_next/static/chunks/next/dist/client/components/builtin/app-error-7bf8bd93aa11e337.js +1 -0
  67. package/dist/ui/static/_next/static/chunks/next/dist/client/components/builtin/forbidden-7bf8bd93aa11e337.js +1 -0
  68. package/dist/ui/static/_next/static/chunks/next/dist/client/components/builtin/global-error-af3824b7b26275df.js +1 -0
  69. package/dist/ui/static/_next/static/chunks/next/dist/client/components/builtin/not-found-7bf8bd93aa11e337.js +1 -0
  70. package/dist/ui/static/_next/static/chunks/next/dist/client/components/builtin/unauthorized-7bf8bd93aa11e337.js +1 -0
  71. package/dist/ui/static/_next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  72. package/dist/ui/static/_next/static/chunks/webpack-284633a353ab8ff4.js +1 -0
  73. package/dist/ui/static/_next/static/css/0fcf744e25b17e8a.css +3 -0
  74. package/dist/ui/static/_next/static/css/1ab47b3e78ccc975.css +3 -0
  75. package/dist/ui/static/_next/static/css/29c9f45818b0ee66.css +1 -0
  76. package/dist/ui/static/_next/static/css/5adfb34e72f5c7db.css +1 -0
  77. package/dist/ui/static/_next/static/oUkwnS6PllEZCcS8tUuTR/_buildManifest.js +1 -0
  78. package/dist/ui/static/_next/static/{3yZ69dbD6hxn3rKeTd62L → oUkwnS6PllEZCcS8tUuTR}/_ssgManifest.js +1 -1
  79. package/dist/ui/static/_not-found/__next._full.txt +9 -9
  80. package/dist/ui/static/_not-found/__next._head.txt +4 -4
  81. package/dist/ui/static/_not-found/__next._index.txt +4 -4
  82. package/dist/ui/static/_not-found/__next._not-found.__PAGE__.txt +2 -2
  83. package/dist/ui/static/_not-found/__next._not-found.txt +3 -3
  84. package/dist/ui/static/_not-found/__next._tree.txt +2 -2
  85. package/dist/ui/static/_not-found.html +1 -1
  86. package/dist/ui/static/_not-found.txt +9 -9
  87. package/dist/ui/static/apple-touch-icon.png +0 -0
  88. package/dist/ui/static/favicon.ico +0 -0
  89. package/dist/ui/static/favicon.svg +1 -1
  90. package/dist/ui/static/icon-192-maskable.png +0 -0
  91. package/dist/ui/static/icon-192.png +0 -0
  92. package/dist/ui/static/icon-512-maskable.png +0 -0
  93. package/dist/ui/static/icon-512.png +0 -0
  94. package/dist/ui/static/index.html +1 -1
  95. package/dist/ui/static/index.txt +11 -12
  96. package/dist/ui/static/launch/__next._full.txt +11 -12
  97. package/dist/ui/static/launch/__next._head.txt +4 -4
  98. package/dist/ui/static/launch/__next._index.txt +4 -4
  99. package/dist/ui/static/launch/__next._tree.txt +2 -3
  100. package/dist/ui/static/launch/__next.launch.__PAGE__.txt +4 -4
  101. package/dist/ui/static/launch/__next.launch.txt +3 -3
  102. package/dist/ui/static/launch.html +1 -1
  103. package/dist/ui/static/launch.txt +11 -12
  104. package/dist/ui/static/local-knowledge/__next._full.txt +11 -12
  105. package/dist/ui/static/local-knowledge/__next._head.txt +4 -4
  106. package/dist/ui/static/local-knowledge/__next._index.txt +4 -4
  107. package/dist/ui/static/local-knowledge/__next._tree.txt +2 -3
  108. package/dist/ui/static/local-knowledge/__next.local-knowledge.__PAGE__.txt +4 -4
  109. package/dist/ui/static/local-knowledge/__next.local-knowledge.txt +3 -3
  110. package/dist/ui/static/local-knowledge/capsule/__next._full.txt +10 -10
  111. package/dist/ui/static/local-knowledge/capsule/__next._head.txt +4 -4
  112. package/dist/ui/static/local-knowledge/capsule/__next._index.txt +4 -4
  113. package/dist/ui/static/local-knowledge/capsule/__next._tree.txt +2 -2
  114. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.__PAGE__.txt +3 -3
  115. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.txt +3 -3
  116. package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.txt +3 -3
  117. package/dist/ui/static/local-knowledge/capsule.html +1 -1
  118. package/dist/ui/static/local-knowledge/capsule.txt +10 -10
  119. package/dist/ui/static/local-knowledge.html +1 -1
  120. package/dist/ui/static/local-knowledge.txt +11 -12
  121. package/dist/ui/static/memoriaviva/__next._full.txt +9 -9
  122. package/dist/ui/static/memoriaviva/__next._head.txt +4 -4
  123. package/dist/ui/static/memoriaviva/__next._index.txt +4 -4
  124. package/dist/ui/static/memoriaviva/__next._tree.txt +2 -2
  125. package/dist/ui/static/memoriaviva/__next.memoriaviva.__PAGE__.txt +2 -2
  126. package/dist/ui/static/memoriaviva/__next.memoriaviva.txt +3 -3
  127. package/dist/ui/static/memoriaviva/consolidation/__next._full.txt +9 -9
  128. package/dist/ui/static/memoriaviva/consolidation/__next._head.txt +4 -4
  129. package/dist/ui/static/memoriaviva/consolidation/__next._index.txt +4 -4
  130. package/dist/ui/static/memoriaviva/consolidation/__next._tree.txt +2 -2
  131. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.__PAGE__.txt +2 -2
  132. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.txt +3 -3
  133. package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.txt +3 -3
  134. package/dist/ui/static/memoriaviva/consolidation.html +1 -1
  135. package/dist/ui/static/memoriaviva/consolidation.txt +9 -9
  136. package/dist/ui/static/memoriaviva/detail/__next._full.txt +9 -9
  137. package/dist/ui/static/memoriaviva/detail/__next._head.txt +4 -4
  138. package/dist/ui/static/memoriaviva/detail/__next._index.txt +4 -4
  139. package/dist/ui/static/memoriaviva/detail/__next._tree.txt +2 -2
  140. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.__PAGE__.txt +2 -2
  141. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.txt +3 -3
  142. package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.txt +3 -3
  143. package/dist/ui/static/memoriaviva/detail.html +1 -1
  144. package/dist/ui/static/memoriaviva/detail.txt +9 -9
  145. package/dist/ui/static/memoriaviva/review-queue/__next._full.txt +9 -9
  146. package/dist/ui/static/memoriaviva/review-queue/__next._head.txt +4 -4
  147. package/dist/ui/static/memoriaviva/review-queue/__next._index.txt +4 -4
  148. package/dist/ui/static/memoriaviva/review-queue/__next._tree.txt +2 -2
  149. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.__PAGE__.txt +2 -2
  150. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.txt +3 -3
  151. package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.txt +3 -3
  152. package/dist/ui/static/memoriaviva/review-queue.html +1 -1
  153. package/dist/ui/static/memoriaviva/review-queue.txt +9 -9
  154. package/dist/ui/static/memoriaviva.html +1 -1
  155. package/dist/ui/static/memoriaviva.txt +9 -9
  156. package/dist/ui/static/sw.js +1 -211
  157. package/node_modules/@oscharko-dev/keiko-cli/dist/.tsbuildinfo +1 -1
  158. package/node_modules/@oscharko-dev/keiko-cli/package.json +14 -14
  159. package/node_modules/@oscharko-dev/keiko-contracts/dist/.tsbuildinfo +1 -1
  160. package/node_modules/@oscharko-dev/keiko-contracts/dist/index.d.ts +1 -1
  161. package/node_modules/@oscharko-dev/keiko-contracts/dist/index.js +1 -1
  162. package/node_modules/@oscharko-dev/keiko-contracts/package.json +1 -1
  163. package/node_modules/@oscharko-dev/keiko-evaluations/dist/.tsbuildinfo +1 -1
  164. package/node_modules/@oscharko-dev/keiko-evaluations/package.json +9 -9
  165. package/node_modules/@oscharko-dev/keiko-evidence/dist/.tsbuildinfo +1 -1
  166. package/node_modules/@oscharko-dev/keiko-evidence/package.json +4 -4
  167. package/node_modules/@oscharko-dev/keiko-harness/dist/.tsbuildinfo +1 -1
  168. package/node_modules/@oscharko-dev/keiko-harness/package.json +6 -6
  169. package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/.tsbuildinfo +1 -1
  170. package/node_modules/@oscharko-dev/keiko-local-knowledge/package.json +5 -5
  171. package/node_modules/@oscharko-dev/keiko-memory-capture/package.json +3 -3
  172. package/node_modules/@oscharko-dev/keiko-memory-consolidation/package.json +3 -3
  173. package/node_modules/@oscharko-dev/keiko-memory-governance/package.json +3 -3
  174. package/node_modules/@oscharko-dev/keiko-memory-retrieval/package.json +3 -3
  175. package/node_modules/@oscharko-dev/keiko-memory-vault/dist/.tsbuildinfo +1 -1
  176. package/node_modules/@oscharko-dev/keiko-memory-vault/package.json +3 -3
  177. package/node_modules/@oscharko-dev/keiko-model-gateway/dist/.tsbuildinfo +1 -1
  178. package/node_modules/@oscharko-dev/keiko-model-gateway/package.json +3 -3
  179. package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/.tsbuildinfo +1 -1
  180. package/node_modules/@oscharko-dev/keiko-quality-intelligence/package.json +3 -3
  181. package/node_modules/@oscharko-dev/keiko-sandbox/dist/.tsbuildinfo +1 -1
  182. package/node_modules/@oscharko-dev/keiko-sandbox/package.json +2 -2
  183. package/node_modules/@oscharko-dev/keiko-sdk/dist/.tsbuildinfo +1 -1
  184. package/node_modules/@oscharko-dev/keiko-sdk/package.json +9 -9
  185. package/node_modules/@oscharko-dev/keiko-security/dist/.tsbuildinfo +1 -1
  186. package/node_modules/@oscharko-dev/keiko-security/package.json +2 -2
  187. package/node_modules/@oscharko-dev/keiko-server/dist/.tsbuildinfo +1 -1
  188. package/node_modules/@oscharko-dev/keiko-server/package.json +19 -19
  189. package/node_modules/@oscharko-dev/keiko-tools/dist/.tsbuildinfo +1 -1
  190. package/node_modules/@oscharko-dev/keiko-tools/package.json +5 -5
  191. package/node_modules/@oscharko-dev/keiko-verification/dist/.tsbuildinfo +1 -1
  192. package/node_modules/@oscharko-dev/keiko-verification/package.json +5 -5
  193. package/node_modules/@oscharko-dev/keiko-workflows/dist/.tsbuildinfo +1 -1
  194. package/node_modules/@oscharko-dev/keiko-workflows/package.json +10 -10
  195. package/node_modules/@oscharko-dev/keiko-workspace/dist/.tsbuildinfo +1 -1
  196. package/node_modules/@oscharko-dev/keiko-workspace/package.json +3 -3
  197. package/package.json +24 -22
  198. package/dist/ui/static/_next/static/3yZ69dbD6hxn3rKeTd62L/_buildManifest.js +0 -11
  199. package/dist/ui/static/_next/static/3yZ69dbD6hxn3rKeTd62L/_clientMiddlewareManifest.js +0 -1
  200. package/dist/ui/static/_next/static/chunks/02x_fenv7_zew.js +0 -1
  201. package/dist/ui/static/_next/static/chunks/04v1kck7tfha5.js +0 -3
  202. package/dist/ui/static/_next/static/chunks/05-c3ty_6dwfk.js +0 -1
  203. package/dist/ui/static/_next/static/chunks/0cz1d0mv5g_q7.js +0 -1
  204. package/dist/ui/static/_next/static/chunks/0f5n_cgpnc_up.js +0 -1
  205. package/dist/ui/static/_next/static/chunks/0f8vu_oqmv33v.js +0 -1
  206. package/dist/ui/static/_next/static/chunks/0oj6iz8mnbx8s.js +0 -2
  207. package/dist/ui/static/_next/static/chunks/0plguvqu88z22.css +0 -1
  208. package/dist/ui/static/_next/static/chunks/0rfgnninook6m.js +0 -7
  209. package/dist/ui/static/_next/static/chunks/0rpy-4z62fhgt.js +0 -1
  210. package/dist/ui/static/_next/static/chunks/1008yamfukit7.js +0 -1
  211. package/dist/ui/static/_next/static/chunks/118gmc8yis71o.js +0 -1
  212. package/dist/ui/static/_next/static/chunks/14mrh2-p_w84d.js +0 -1
  213. package/dist/ui/static/_next/static/chunks/14pxq1l54d91b.js +0 -100
  214. package/dist/ui/static/_next/static/chunks/1bch0lzf2jhte.js +0 -1
  215. package/dist/ui/static/_next/static/chunks/1g9ftam8b7m8q.js +0 -1
  216. package/dist/ui/static/_next/static/chunks/1hu0-yn7a2hl7.js +0 -1
  217. package/dist/ui/static/_next/static/chunks/1jb065bgx6s74.js +0 -1
  218. package/dist/ui/static/_next/static/chunks/1ranrsmqde7a3.js +0 -1
  219. package/dist/ui/static/_next/static/chunks/1x1yfevmu5rb2.js +0 -1
  220. package/dist/ui/static/_next/static/chunks/20foqqrxh746m.js +0 -1
  221. package/dist/ui/static/_next/static/chunks/29350453epqhl.js +0 -678
  222. package/dist/ui/static/_next/static/chunks/2brgey_3-j__0.css +0 -78
  223. package/dist/ui/static/_next/static/chunks/2f07lv5x0j18r.js +0 -31
  224. package/dist/ui/static/_next/static/chunks/2hyzx1ec3gusp.js +0 -5
  225. package/dist/ui/static/_next/static/chunks/2kk_6twoug205.js +0 -1
  226. package/dist/ui/static/_next/static/chunks/2m8gr4lszkhce.js +0 -1
  227. package/dist/ui/static/_next/static/chunks/2ow5x0jmgs6c3.js +0 -1
  228. package/dist/ui/static/_next/static/chunks/2udnn0cidn7rd.js +0 -1372
  229. package/dist/ui/static/_next/static/chunks/2xt20mg9l3s14.js +0 -1
  230. package/dist/ui/static/_next/static/chunks/332o8ksd43271.css +0 -2
  231. package/dist/ui/static/_next/static/chunks/3ikgvfgh2w2mv.js +0 -1
  232. package/dist/ui/static/_next/static/chunks/3l7lvskoqfema.js +0 -1
  233. package/dist/ui/static/_next/static/chunks/3m8_lgj6p8ik3.js +0 -1
  234. package/dist/ui/static/_next/static/chunks/3peubv2924kx4.js +0 -1
  235. package/dist/ui/static/_next/static/chunks/3rcxnxkqe56aj.js +0 -1
  236. package/dist/ui/static/_next/static/chunks/3s4w0yl_p2lcg.css +0 -11
  237. package/dist/ui/static/_next/static/chunks/3wdv1n7vcw9cc.js +0 -3
  238. package/dist/ui/static/_next/static/chunks/3xvtkd60q8trh.js +0 -1
  239. package/dist/ui/static/_next/static/chunks/3zd9_bzzf89g-.js +0 -1
  240. package/dist/ui/static/_next/static/chunks/403o25d1h_c-n.js +0 -1
  241. package/dist/ui/static/_next/static/chunks/40jvaobgkjymu.js +0 -1
  242. package/dist/ui/static/_next/static/chunks/40zvqgo8jkl9z.css +0 -7
  243. package/dist/ui/static/_next/static/chunks/43ils02xq1hm1.js +0 -2
  244. package/dist/ui/static/_next/static/chunks/turbopack-06ieh9kn4227g.js +0 -1
  245. package/dist/ui/static/_next/static/chunks/turbopack-1g6b_g7qh0ywi.js +0 -1
  246. package/dist/ui/static/_next/static/chunks/turbopack-2kouhzbnsra9l.js +0 -1
  247. package/dist/ui/static/_next/static/chunks/turbopack-2t_ks90iyjtkj.js +0 -1
  248. package/dist/ui/static/_next/static/chunks/turbopack-3isq3ty8v6x-q.js +0 -1
  249. package/dist/ui/static/_next/static/chunks/turbopack-410ydpmcadyki.js +0 -1
  250. package/dist/ui/static/_next/static/chunks/turbopack-worker-2gqdcwp7k90ea.js +0 -1
  251. package/dist/ui/static/_next/static/media/css.worker.2tg30ell0fh1e.js +0 -8
  252. package/dist/ui/static/_next/static/media/editor.worker.2da6bfstu5_et.js +0 -11
  253. package/dist/ui/static/_next/static/media/html.worker.3rfboyno_oqe1.js +0 -8
  254. package/dist/ui/static/_next/static/media/json.worker.3z5byn_3-su6-.js +0 -8
  255. package/dist/ui/static/_next/static/media/ts.worker.0i3svvld44ebg.js +0 -14
  256. /package/dist/ui/static/_next/static/media/{codicon.3bppog5b8ye-1.ttf → codicon.5b7d6fac.ttf} +0 -0
@@ -1,100 +0,0 @@
1
- (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,88143,(e,t,n)=>{"use strict";function a({widthInt:e,heightInt:t,blurWidth:n,blurHeight:l,blurDataURL:i,objectFit:r}){let s=n?40*n:e,o=l?40*l:t,c=s&&o?`viewBox='0 0 ${s} ${o}'`:"";return`%3Csvg xmlns='http://www.w3.org/2000/svg' ${c}%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='${c?"none":"contain"===r?"xMidYMid":"cover"===r?"xMidYMid slice":"none"}' style='filter: url(%23b);' href='${i}'/%3E%3C/svg%3E`}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getImageBlurSvg",{enumerable:!0,get:function(){return a}})},87690,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var a={VALID_LOADERS:function(){return i},imageConfigDefault:function(){return r}};for(var l in a)Object.defineProperty(n,l,{enumerable:!0,get:a[l]});let i=["default","imgix","cloudinary","akamai","custom"],r={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:14400,formats:["image/webp"],maximumDiskCacheSize:void 0,maximumRedirects:3,maximumResponseBody:5e7,dangerouslyAllowLocalIP:!1,dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"attachment",localPatterns:void 0,remotePatterns:[],qualities:[75],unoptimized:!1,customCacheHandler:!1}},8927,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getImgProps",{enumerable:!0,get:function(){return c}}),e.r(33525);let a=e.r(43369),l=e.r(88143),i=e.r(87690),r=["-moz-initial","fill","none","scale-down",void 0];function s(e){return void 0!==e.default}function o(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function c({src:e,sizes:t,unoptimized:n=!1,priority:d=!1,preload:u=!1,loading:p,className:m,quality:h,width:f,height:g,fill:v=!1,style:b,overrideSrc:x,onLoad:y,onLoadingComplete:w,placeholder:j="empty",blurDataURL:k,fetchPriority:N,decoding:S="async",layout:C,objectFit:I,objectPosition:E,lazyBoundary:R,lazyRoot:$,...A},T){var L;let P,M,D,{imgConf:q,showAltText:F,blurComplete:O,defaultLoader:z}=T,K=q||i.imageConfigDefault;if("allSizes"in K)P=K;else{let e=[...K.deviceSizes,...K.imageSizes].sort((e,t)=>e-t),t=K.deviceSizes.sort((e,t)=>e-t),n=K.qualities?.sort((e,t)=>e-t);P={...K,allSizes:e,deviceSizes:t,qualities:n}}if(void 0===z)throw Object.defineProperty(Error("images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config"),"__NEXT_ERROR_CODE",{value:"E163",enumerable:!1,configurable:!0});let B=A.loader||z;delete A.loader,delete A.srcSet;let _="__next_img_default"in B;if(_){if("custom"===P.loader)throw Object.defineProperty(Error(`Image with src "${e}" is missing "loader" prop.
2
- Read more: https://nextjs.org/docs/messages/next-image-missing-loader`),"__NEXT_ERROR_CODE",{value:"E252",enumerable:!1,configurable:!0})}else{let e=B;B=t=>{let{config:n,...a}=t;return e(a)}}if(C){"fill"===C&&(v=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[C];e&&(b={...b,...e});let n={responsive:"100vw",fill:"100vw"}[C];n&&!t&&(t=n)}let U="",W=o(f),V=o(g);if((L=e)&&"object"==typeof L&&(s(L)||void 0!==L.src)){let t=s(e)?e.default:e;if(!t.src)throw Object.defineProperty(Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ${JSON.stringify(t)}`),"__NEXT_ERROR_CODE",{value:"E460",enumerable:!1,configurable:!0});if(!t.height||!t.width)throw Object.defineProperty(Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ${JSON.stringify(t)}`),"__NEXT_ERROR_CODE",{value:"E48",enumerable:!1,configurable:!0});if(M=t.blurWidth,D=t.blurHeight,k=k||t.blurDataURL,U=t.src,!v)if(W||V){if(W&&!V){let e=W/t.width;V=Math.round(t.height*e)}else if(!W&&V){let e=V/t.height;W=Math.round(t.width*e)}}else W=t.width,V=t.height}let H=!d&&!u&&("lazy"===p||void 0===p);(!(e="string"==typeof e?e:U)||e.startsWith("data:")||e.startsWith("blob:"))&&(n=!0,H=!1),P.unoptimized&&(n=!0),_&&!P.dangerouslyAllowSVG&&e.split("?",1)[0].endsWith(".svg")&&(n=!0);let Y=o(h),G=Object.assign(v?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:I,objectPosition:E}:{},F?{}:{color:"transparent"},b),J=O||"empty"===j?null:"blur"===j?`url("data:image/svg+xml;charset=utf-8,${(0,l.getImageBlurSvg)({widthInt:W,heightInt:V,blurWidth:M,blurHeight:D,blurDataURL:k||"",objectFit:G.objectFit})}")`:`url("${j}")`,X=r.includes(G.objectFit)?"fill"===G.objectFit?"100% 100%":"cover":G.objectFit,Q=J?{backgroundSize:X,backgroundPosition:G.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:J}:{},Z=function({config:e,src:t,unoptimized:n,width:l,quality:i,sizes:r,loader:s}){if(n){if(t.startsWith("/")&&!t.startsWith("//")){let e=(0,a.getDeploymentId)();if(e){let n=t.indexOf("?");if(-1!==n){let a=new URLSearchParams(t.slice(n+1));a.get("dpl")||(a.append("dpl",e),t=t.slice(0,n)+"?"+a.toString())}else t+=`?dpl=${e}`}}return{src:t,srcSet:void 0,sizes:void 0}}let{widths:o,kind:c}=function({deviceSizes:e,allSizes:t},n,a){if(a){let n=/(^|\s)(1?\d?\d)vw/g,l=[];for(let e;e=n.exec(a);)l.push(parseInt(e[2]));if(l.length){let n=.01*Math.min(...l);return{widths:t.filter(t=>t>=e[0]*n),kind:"w"}}return{widths:t,kind:"w"}}return"number"!=typeof n?{widths:e,kind:"w"}:{widths:[...new Set([n,2*n].map(e=>t.find(t=>t>=e)||t[t.length-1]))],kind:"x"}}(e,l,r),d=o.length-1;return{sizes:r||"w"!==c?r:"100vw",srcSet:o.map((n,a)=>`${s({config:e,src:t,quality:i,width:n})} ${"w"===c?n:a+1}${c}`).join(", "),src:s({config:e,src:t,quality:i,width:o[d]})}}({config:P,src:e,unoptimized:n,width:W,quality:Y,sizes:t,loader:B}),ee=H?"lazy":p;return{props:{...A,loading:ee,fetchPriority:N,width:W,height:V,decoding:S,className:m,style:{...G,...Q},sizes:Z.sizes,srcSet:Z.srcSet,src:x||Z.src},meta:{unoptimized:n,preload:u||d,placeholder:j,fill:v}}}},98879,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return s}});let a=e.r(71645),l="u"<typeof window,i=l?()=>{}:a.useLayoutEffect,r=l?()=>{}:a.useEffect;function s(e){let{headManager:t,reduceComponentsToState:n}=e;function s(){if(t&&t.mountedInstances){let e=a.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(n(e))}}return l&&(t?.mountedInstances?.add(e.children),s()),i(()=>(t?.mountedInstances?.add(e.children),()=>{t?.mountedInstances?.delete(e.children)})),i(()=>(t&&(t._pendingUpdate=s),()=>{t&&(t._pendingUpdate=s)})),r(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},25633,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var a={default:function(){return f},defaultHead:function(){return u}};for(var l in a)Object.defineProperty(n,l,{enumerable:!0,get:a[l]});let i=e.r(55682),r=e.r(90809),s=e.r(43476),o=r._(e.r(71645)),c=i._(e.r(98879)),d=e.r(42732);function u(){return[(0,s.jsx)("meta",{charSet:"utf-8"},"charset"),(0,s.jsx)("meta",{name:"viewport",content:"width=device-width"},"viewport")]}function p(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}e.r(33525);let m=["name","httpEquiv","charSet","itemProp"];function h(e){let t,n,a,l;return e.reduce(p,[]).reverse().concat(u().reverse()).filter((t=new Set,n=new Set,a=new Set,l={},e=>{let i=!0,r=!1;if(e.key&&"number"!=typeof e.key&&e.key.indexOf("$")>0){r=!0;let n=e.key.slice(e.key.indexOf("$")+1);t.has(n)?i=!1:t.add(n)}switch(e.type){case"title":case"base":n.has(e.type)?i=!1:n.add(e.type);break;case"meta":for(let t=0,n=m.length;t<n;t++){let n=m[t];if(e.props.hasOwnProperty(n))if("charSet"===n)a.has(n)?i=!1:a.add(n);else{let t=e.props[n],a=l[n]||new Set;("name"!==n||!r)&&a.has(t)?i=!1:(a.add(t),l[n]=a)}}}return i})).reverse().map((e,t)=>{let n=e.key||t;return o.default.cloneElement(e,{key:n})})}let f=function({children:e}){let t=(0,o.useContext)(d.HeadManagerContext);return(0,s.jsx)(c.default,{reduceComponentsToState:h,headManager:t,children:e})};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),t.exports=n.default)},18556,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"ImageConfigContext",{enumerable:!0,get:function(){return i}});let a=e.r(55682)._(e.r(71645)),l=e.r(87690),i=a.default.createContext(l.imageConfigDefault)},65856,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"RouterContext",{enumerable:!0,get:function(){return a}});let a=e.r(55682)._(e.r(71645)).default.createContext(null)},70965,(e,t,n)=>{"use strict";function a(e,t){let n=e||75;return t?.qualities?.length?t.qualities.reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e,t.qualities[0]):n}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"findClosestQuality",{enumerable:!0,get:function(){return a}})},1948,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return r}});let a=e.r(70965),l=e.r(43369);function i({config:e,src:t,width:n,quality:r}){let s=(0,l.getDeploymentId)();if(t.startsWith("/")&&!t.startsWith("//")){let e=t.indexOf("?");if(-1!==e){let n=new URLSearchParams(t.slice(e+1)),a=n.get("dpl");if(a){s=a,n.delete("dpl");let l=n.toString();t=t.slice(0,e)+(l?"?"+l:"")}}}if(t.startsWith("/")&&t.includes("?")&&e.localPatterns?.length===1&&"**"===e.localPatterns[0].pathname&&""===e.localPatterns[0].search)throw Object.defineProperty(Error(`Image with src "${t}" is using a query string which is not configured in images.localPatterns.
3
- Read more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`),"__NEXT_ERROR_CODE",{value:"E871",enumerable:!1,configurable:!0});let o=(0,a.findClosestQuality)(r,e);return`${e.path}?url=${encodeURIComponent(t)}&w=${n}&q=${o}${t.startsWith("/")&&s?`&dpl=${s}`:""}`}i.__next_img_default=!0;let r=i},5500,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"Image",{enumerable:!0,get:function(){return y}});let a=e.r(55682),l=e.r(90809),i=e.r(43476),r=l._(e.r(71645)),s=a._(e.r(74080)),o=a._(e.r(25633)),c=e.r(8927),d=e.r(87690),u=e.r(18556);e.r(33525);let p=e.r(65856),m=a._(e.r(1948)),h=e.r(18581),f={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[32,48,64,96,128,256,384],qualities:[75],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!0};function g(e,t,n,a,l,i,r){let s=e?.src;e&&e["data-loaded-src"]!==s&&(e["data-loaded-src"]=s,("decode"in e?e.decode():Promise.resolve()).catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&l(!0),n?.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let a=!1,l=!1;n.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>a,isPropagationStopped:()=>l,persist:()=>{},preventDefault:()=>{a=!0,t.preventDefault()},stopPropagation:()=>{l=!0,t.stopPropagation()}})}a?.current&&a.current(e)}}))}function v(e){return r.use?{fetchPriority:e}:{fetchpriority:e}}"u"<typeof window&&(globalThis.__NEXT_IMAGE_IMPORTED=!0);let b=(0,r.forwardRef)(({src:e,srcSet:t,sizes:n,height:a,width:l,decoding:s,className:o,style:c,fetchPriority:d,placeholder:u,loading:p,unoptimized:m,fill:f,onLoadRef:b,onLoadingCompleteRef:x,setBlurComplete:y,setShowAltText:w,sizesInput:j,onLoad:k,onError:N,...S},C)=>{let I=(0,r.useCallback)(e=>{e&&(N&&(e.src=e.src),e.complete&&g(e,u,b,x,y,m,j))},[e,u,b,x,y,N,m,j]),E=(0,h.useMergedRef)(C,I);return(0,i.jsx)("img",{...S,...v(d),loading:p,width:l,height:a,decoding:s,"data-nimg":f?"fill":"1",className:o,style:c,sizes:n,srcSet:t,src:e,ref:E,onLoad:e=>{g(e.currentTarget,u,b,x,y,m,j)},onError:e=>{w(!0),"empty"!==u&&y(!0),N&&N(e)}})});function x({isAppRouter:e,imgAttributes:t}){let n={as:"image",imageSrcSet:t.srcSet,imageSizes:t.sizes,crossOrigin:t.crossOrigin,referrerPolicy:t.referrerPolicy,...v(t.fetchPriority)};return e&&s.default.preload?(s.default.preload(t.src,n),null):(0,i.jsx)(o.default,{children:(0,i.jsx)("link",{rel:"preload",href:t.srcSet?void 0:t.src,...n},"__nimg-"+t.src+t.srcSet+t.sizes)})}let y=(0,r.forwardRef)((e,t)=>{let n=(0,r.useContext)(p.RouterContext),a=(0,r.useContext)(u.ImageConfigContext),l=(0,r.useMemo)(()=>{let e=f||a||d.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),n=e.deviceSizes.sort((e,t)=>e-t),l=e.qualities?.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:n,qualities:l,localPatterns:"u"<typeof window?a?.localPatterns:e.localPatterns}},[a]),{onLoad:s,onLoadingComplete:o}=e,h=(0,r.useRef)(s);(0,r.useEffect)(()=>{h.current=s},[s]);let g=(0,r.useRef)(o);(0,r.useEffect)(()=>{g.current=o},[o]);let[v,y]=(0,r.useState)(!1),[w,j]=(0,r.useState)(!1),{props:k,meta:N}=(0,c.getImgProps)(e,{defaultLoader:m.default,imgConf:l,blurComplete:v,showAltText:w});return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(b,{...k,unoptimized:N.unoptimized,placeholder:N.placeholder,fill:N.fill,onLoadRef:h,onLoadingCompleteRef:g,setBlurComplete:y,setShowAltText:j,sizesInput:e.sizes,ref:t}),N.preload?(0,i.jsx)(x,{isAppRouter:!n,imgAttributes:k}):null]})});("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),t.exports=n.default)},94909,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var a={default:function(){return d},getImageProps:function(){return c}};for(var l in a)Object.defineProperty(n,l,{enumerable:!0,get:a[l]});let i=e.r(55682),r=e.r(8927),s=e.r(5500),o=i._(e.r(1948));function c(e){let{props:t}=(0,r.getImgProps)(e,{defaultLoader:o.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[32,48,64,96,128,256,384],qualities:[75],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!0}});for(let[e,n]of Object.entries(t))void 0===n&&delete t[e];return{props:t}}let d=s.Image},57688,(e,t,n)=>{t.exports=e.r(94909)},89199,e=>{"use strict";let t;var n=e.i(43476),a=e.i(71645);let l=(0,a.createContext)(null);function i({value:e,children:t}){return(0,n.jsx)(l.Provider,{value:e,children:t})}function r(){let e=(0,a.useContext)(l);if(null===e)throw Error("useChatSessionContext must be used inside ChatSessionProvider");return e}function s(){return(0,a.useContext)(l)}let o=[{id:"read",action:"Read files",scope:"workspace",decision:"allow"},{id:"write",action:"Write files",scope:"src/** · docs/**",decision:"allow"},{id:"write-prod",action:"Write files",scope:"prod/** · infra/**",decision:"deny"},{id:"command",action:"Run commands",scope:"test · build · lint",decision:"allow"},{id:"command-danger",action:"Run commands",scope:"deploy · rm · db",decision:"ask"},{id:"network",action:"Network / fetch",scope:"allowlist",decision:"ask"},{id:"pr",action:"Open pull request",scope:"feature branches",decision:"allow"},{id:"mail",action:"Mail / calendar",scope:"any",decision:"ask"}],c={calendar:!0,mail:!1,jira:!0,docs:!0},d="keiko.twin.mode",u="keiko.twin.persona",p="keiko.twin.policy",m="keiko.twin.bridges",h=(0,a.createContext)(null);function f(e,t){try{let n=window.localStorage.getItem(e);if(null===n)return t;let a=JSON.parse(n);return null==a?t:a}catch{return t}}function g(e,t){try{window.localStorage.setItem(e,t)}catch{}}function v(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function b({children:e}){let[t,l]=(0,a.useState)("manual"),[i,r]=(0,a.useState)("Developer"),[s,x]=(0,a.useState)(o),[y,w]=(0,a.useState)(c),[j,k]=(0,a.useState)(!1);(0,a.useEffect)(()=>{l(function(){try{let e=window.localStorage.getItem(d);return"manual"===e||"autonomous"===e?e:"manual"}catch{return"manual"}}()),r(function(){try{let e=window.localStorage.getItem(u);if("Developer"===e||"Product Owner"===e||"Designer"===e)return e;return"Developer"}catch{return"Developer"}}()),x(f(p,o)),w(f(m,c));try{window.localStorage.removeItem("keiko.twin.memory")}catch{}k(!0)},[]),(0,a.useEffect)(()=>{j&&g(d,t)},[t,j]),(0,a.useEffect)(()=>{j&&g(u,i)},[i,j]),(0,a.useEffect)(()=>{j&&v(p,s)},[s,j]),(0,a.useEffect)(()=>{j&&v(m,y)},[y,j]);let N=(0,a.useCallback)((e,t)=>{let n;return n=e=>s.find(t=>t.id===e)?.decision??null,"write"===e?"high"===t?n("write-prod")??"deny":n("write")??"allow":"command"===e?"high"===t?n("command-danger")??"ask":n("command")??"allow":"git"===e?n("pr")??"allow":"mail"===e?n("mail")??"ask":"network"===e?n("network")??"ask":"ask"},[s]),S=(0,a.useMemo)(()=>({mode:t,setMode:l,persona:i,setPersona:r,policy:s,setPolicy:x,bridges:y,setBridges:w,decide:N}),[t,i,s,y,N]);return(0,n.jsx)(h.Provider,{value:S,children:e})}function x(){let e=(0,a.useContext)(h);if(null===e)throw Error("useTwin must be used inside <TwinProvider>");return e}let y=(0,a.createContext)({wins:[],active:null,winCount:0});var w=e.i(76055),j=e.i(17161);let k={w:150,h:110},N={w:290,h:190},S={chat:{title:"Chat",icon:"newChat",accent:!0,desc:"Talk to Keiko",w:480,h:480,min:{w:300,h:260},config:[{key:"title",label:"Title",type:"text",def:"New chat",optional:!0,placeholder:"Name this conversation"}]},chatHistory:{title:"Chat History",icon:"archive",desc:"Manage conversations",w:380,h:560,min:{w:300,h:320},tiny:{w:260,h:220},tool:!0,singleton:!0},memoria:{title:"MemoriaViva",icon:"brain",desc:"Review governed memory",w:680,h:600,min:{w:420,h:360},tiny:{w:300,h:220},tool:!0,singleton:!0},files:{title:"Files",icon:"files",accent:!0,desc:"Browse a folder",w:290,h:340,tiny:{w:200,h:150},config:[{key:"root",label:"Folder",type:"directory",def:""}]},editor:{title:"Editor",icon:"editor",desc:"Open a folder or file",w:920,h:620,min:{w:620,h:380},config:[{key:"root",label:"Folder",type:"directory",def:"",optional:!0,placeholder:"/absolute/folder/path"},{key:"file",label:"File path",type:"text",def:"",optional:!0,placeholder:"optional relative file path"}]},browser:{title:"Browser",icon:"browser",desc:"Open a URL",w:460,h:340,config:[{key:"url",label:"URL",type:"text",def:"",optional:!0,placeholder:"https://…"}]},terminal:{title:"Terminal",icon:"terminal",accent:!0,desc:"Run commands",w:460,h:250,tiny:{w:250,h:140},config:[{key:"projectPath",label:"Project path",type:"text",def:""},{key:"cwd",label:"Working directory",type:"directory",def:""}]},review:{title:"Review",icon:"review",desc:"Review a proposed diff",w:520,h:420,config:[{key:"runId",label:"Run ID",type:"text",def:"",optional:!0,placeholder:"e.g. r-2026-06-01-…"}]},agents:{title:"Agents",icon:"agents",desc:"Choose a coding agent",w:520,h:560,tiny:{w:250,h:140},cta:"Start agent",config:[]},integ:{title:"Integrations",icon:"plugins",desc:"Connect apps",w:320,h:300,config:[{key:"provider",label:"Provider",type:"select",options:["GitHub","Linear","Slack","Sentry"],def:"GitHub"}]},keiko:{title:"Keiko",icon:"spark",desc:"Keiko twin",w:344,h:520,tool:!0,singleton:!0},settings:{title:"Settings",icon:"settings",desc:"Preferences",w:470,h:560,tool:!0,singleton:!0},project:{title:"Project",icon:"folder",desc:"Project tree",w:304,h:440,tool:!0,singleton:!0},search:{title:"Search",icon:"search",desc:"Search the workspace",w:320,h:500,tool:!0,singleton:!0},plugins:{title:"Plugins",icon:"plugins",desc:"Plugins & tools",w:320,h:470,tool:!0,singleton:!0},automations:{title:"Automations",icon:"automations",desc:"Workflow automations",w:320,h:300,tool:!0,singleton:!0},mobile:{title:"Keiko Mobile",icon:"mobile",desc:"Mobile companion",w:300,h:380,tool:!0,singleton:!0},inspector:{title:"Inspector",icon:"layers",desc:"Inspect the workspace",w:290,h:440,tool:!0,singleton:!0},activity:{title:"Activity",icon:"activity",desc:"Activity timeline",w:322,h:460,tool:!0,singleton:!0},notifications:{title:"Notifications",icon:"bell",desc:"Review alerts & updates",w:300,h:360,tool:!0,singleton:!0},resources:{title:"Resources",icon:"cube",desc:"System resources",w:300,h:320,tool:!0,singleton:!0},connector:{title:"Knowledge Connector",icon:"server",accent:!0,desc:"Pick a Local Knowledge connector",w:320,h:380,min:{w:220,h:180},config:[],cta:"Select connector"},localKnowledge:{title:"Local Knowledge",icon:"localKnowledge",accent:!0,desc:"Manage knowledge capsules",w:720,h:560,min:{w:360,h:320},tiny:{w:300,h:220},tool:!0,singleton:!0},quality:{title:"Quality Intelligence",icon:"check",accent:!0,desc:"Design & review test cases",w:384,h:580,min:{w:300,h:320},tiny:{w:260,h:200},tool:!0,singleton:!0},promptEnhancer:{title:"Prompt Enhancer",icon:"spark",accent:!0,desc:"Turn a raw prompt into a governed, reviewable Enhanced Prompt",w:460,h:620,min:{w:340,h:360},tiny:{w:280,h:220},tool:!0,singleton:!0},qiRun:{title:"QI Run",icon:"check",desc:"Generated test cases",w:760,h:660,min:{w:320,h:280},tiny:{w:280,h:200},config:[{key:"runId",label:"Run ID",type:"text",def:""}]},relationships:{title:"Relationships",icon:"branch",accent:!0,desc:"Inspect the relationship graph",w:760,h:600,min:{w:360,h:320},tiny:{w:300,h:220},tool:!0,singleton:!0},figma:{title:"Figma Snapshot",icon:"layers",accent:!0,desc:"Manage Figma snapshots",w:420,h:540,min:{w:320,h:360},tiny:{w:280,h:240},tool:!0,singleton:!0},figmaView:{title:"Figma View",icon:"layers",accent:!0,desc:"Inspect a scoped Figma screen view",w:360,h:360,min:{w:300,h:260},tiny:{w:260,h:200}},figmaJson:{title:"Figma JSON",icon:"file",accent:!0,desc:"Inspect scoped Figma Screen-IR JSON",w:520,h:540,min:{w:340,h:300},tiny:{w:280,h:220}},figmaImage:{title:"Figma Image",icon:"file",accent:!0,desc:"Inspect a scoped Figma screen render",w:560,h:420,min:{w:300,h:240},tiny:{w:240,h:180}}},C=new Map;function I(e,t){C.set(e,t)}let E=(t={},Object.keys(S).forEach(e=>{var n;let a,l;t[e]=(a={title:(n=S[e]).title,icon:n.icon,desc:n.desc,w:n.w,h:n.h,min:n.min??k,tiny:n.tiny??N,render:(t,n)=>{let a=C.get(e);return void 0!==a?a(t,n):null}},l={},!0===n.accent&&(l.accent=!0),!0===n.tool&&(l.tool=!0),!0===n.singleton&&(l.singleton=!0),void 0!==n.config&&(l.config=n.config),void 0!==n.cta&&(l.cta=n.cta),{...a,...l})}),t),R={agents:["files","terminal","plugins","review","browser","agents","keiko"],chat:["files","browser","plugins","keiko","connector"],files:["agents","chat","quality","editor"],editor:["files","connector"],terminal:["agents"],plugins:["agents","chat"],review:["agents"],browser:["agents","chat"],keiko:["agents","chat"],connector:["chat","quality","editor"],quality:["files","connector","figma","figmaView","figmaJson","figmaImage"],figma:["quality"],figmaView:["quality"],figmaJson:["quality"],figmaImage:["quality"]};function $(e,t){return void 0!==e&&void 0!==t&&e!==t&&((R[e]??[]).includes(t)||(R[t]??[]).includes(e))}function A(e,t){let n="files"===e.type?e:"files"===t.type?t:null,a=null===n?null:n===e?t:e;if(null!==n&&null!==a&&("chat"===a.type||"agents"===a.type||"quality"===a.type||"editor"===a.type)){let e=function(e){if(void 0===e)return null;let t=e.resolvedRoot;if("string"==typeof t&&t.length>0)return t;let n=e.root;return"string"==typeof n&&n.length>0?n:null}(n.cfg);return null===e?"no folder selected":`uses ${function(e,t){let n=e?.activeFilePath;if("string"==typeof n&&n.length>0)return n.split(/[/\\]/u).filter(Boolean).pop()??n;let a=e?.activeDirectoryPath;return"string"==typeof a&&a.length>0?`${a.split(/[/\\]/u).filter(Boolean).pop()??a}/`:`${t.split(/[/\\]/u).filter(Boolean).pop()??t}/`}(n.cfg,e)}`}let l=[e.type,t.type];if(l.includes("connector"))return"uses knowledge";if(l.includes("figmaJson"))return"uses JSON";if(l.includes("figmaImage"))return"uses image";if(l.includes("figmaView"))return"uses view";if(l.includes("figma")){let n="figma"===e.type?e:"figma"===t.type?t:null,a=n?.cfg?.selectedScreenName;return"string"==typeof a&&a.trim().length>0?"uses view":"uses snapshot"}return l.includes("keiko")?"governed by":"agents"===l[0]&&"agents"===l[1]?"delegates":l.includes("terminal")?"runs in":l.includes("plugins")?"uses tools":l.includes("review")?"reviews":l.includes("browser")?"browses":"connected"}function T(e){return{left:{x:e.x,y:e.y,w:e.w/2,h:e.h},right:{x:e.x+e.w/2,y:e.y,w:e.w/2,h:e.h},maxi:{x:e.x,y:e.y,w:e.w,h:e.h},tl:{x:e.x,y:e.y,w:e.w/2,h:e.h/2},tr:{x:e.x+e.w/2,y:e.y,w:e.w/2,h:e.h/2},bl:{x:e.x,y:e.y+e.h/2,w:e.w/2,h:e.h/2},br:{x:e.x+e.w/2,y:e.y+e.h/2,w:e.w/2,h:e.h/2}}}function L(e,t){if(void 0===t)return null;let n=e=>{let n=t[e];return"string"==typeof n&&n.length>0?n:null};switch(e){case"files":return n("root");case"browser":return n("url");case"editor":{let e=n("file"),t=n("root");return null!==e&&null!==t?`${e} — ${t}`:e}case"terminal":return n("cwd");case"review":{let e=n("base"),t=n("head");return null!==e&&null!==t?`${e} → ${t}`:null}case"agents":return n("role");case"chat":{let e=n("title");return null!==e&&"New chat"!==e?e:null}case"figma":case"figmaView":return n("selectedScreenName");case"figmaJson":return n("selectedScreenName")??n("screenId");default:return null}}function P({winCount:e,windows:t,windowPaletteOpen:l,onToggleWindowPalette:i,onSelectWindow:r,onCloseWindowPalette:s,statusRef:o}){let c=(0,a.useRef)(null),[d,u]=(0,a.useState)("version loading"),p=`${String(e)} ${1===e?"window":"windows"}`,m=[...t].sort((e,t)=>t.z-e.z);return(0,a.useEffect)(()=>{let e=!1;return async function(){try{let t=await (0,w.fetchHealth)();e||u(t.version)}catch{e||u("version unavailable")}}(),()=>{e=!0}},[]),(0,a.useEffect)(()=>{if(!l)return;if(0===e)return void s();let t=e=>{let t=e.target;t instanceof Node&&null!==c.current&&!c.current.contains(t)&&s()},n=e=>{"Escape"===e.key&&s()};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",n),()=>{document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",n)}},[s,e,l]),(0,n.jsxs)("footer",{ref:o,className:"footer mono",tabIndex:-1,"aria-label":"Workspace status","aria-live":"polite",children:[(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"ft-brand","aria-label":`Keiko version ${d}`,children:["Keiko | ",d]}),(0,n.jsxs)("span",{className:"ft-window-wrap",ref:c,children:[(0,n.jsxs)("button",{type:"button",className:"ft-seg ft-accent ft-window-trigger ui-tip","aria-atomic":"true","aria-expanded":l,"aria-controls":"footer-window-palette",disabled:0===e,"data-tip":"Open windows",onClick:i,children:[(0,n.jsx)(j.Icons.tile,{size:13})," ",p]}),l&&e>0?(0,n.jsxs)("div",{id:"footer-window-palette",className:"ft-window-palette",role:"menu","aria-label":"Open windows",children:[(0,n.jsx)("div",{className:"ft-window-palette-head",children:"Open windows"}),(0,n.jsx)("div",{className:"ft-window-list",children:m.map(e=>{let t=E[e.type],a=j.Icons[t.icon],l=L(e.type,e.cfg),i=!0===e.minimized?"Minimized":e.max?"Fullscreen":"Visible",s=!0===e.minimized?"Restore":"Focus";return(0,n.jsxs)("button",{type:"button",className:"ft-window-card",role:"menuitem","data-minimized":!0===e.minimized?"true":"false","aria-label":`${s} ${t.title} window${null!==l?` - ${l}`:""}`,onClick:()=>r(e.id),children:[(0,n.jsx)("span",{className:"ft-window-icon",style:{color:!0===t.accent?"var(--accent)":void 0},children:(0,n.jsx)(a,{size:14})}),(0,n.jsxs)("span",{className:"ft-window-copy",children:[(0,n.jsx)("span",{className:"ft-window-title",children:t.title}),(0,n.jsx)("span",{className:"ft-window-sub",title:l??i,children:l??i})]}),(0,n.jsx)("span",{className:"ft-window-state",children:i})]},e.id)})})]}):null]})]})}function M({openPalette:e,openCommandPalette:t,onTileAll:a,onSplitFront:l,onCascade:i}){return(0,n.jsxs)("header",{className:"header",children:[(0,n.jsxs)("div",{className:"hd-brand",children:[(0,n.jsx)("img",{className:"hd-logo",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsx)("span",{className:"hd-wordmark",children:"Keiko"})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("div",{className:"hd-tools",children:[(0,n.jsx)("button",{type:"button",className:"hd-tool ui-tip",onClick:a,"data-tip":"Tile all windows","aria-label":"Tile all windows",children:(0,n.jsx)(j.Icons.tile,{size:16})}),(0,n.jsx)("button",{type:"button",className:"hd-tool ui-tip",onClick:l,"data-tip":"Split front windows","aria-label":"Split front windows",children:(0,n.jsx)(j.Icons.split,{size:16})}),(0,n.jsx)("button",{type:"button",className:"hd-tool ui-tip",onClick:i,"data-tip":"Cascade windows","aria-label":"Cascade windows",children:(0,n.jsx)(j.Icons.cascade,{size:16})})]})]})}let D=[{id:"chatHistory",icon:"archive",label:"Chat History"}];function q({tool:e,active:t,onClick:a}){let l=j.Icons[e.icon];return(0,n.jsx)("button",{type:"button",className:"rail-btn","data-active":t?"true":"false","data-side":"left","aria-label":e.label,"aria-pressed":t,"data-tip":e.label,onClick:a,children:void 0!==e.img?(0,n.jsx)("img",{className:"rail-img",src:e.img,alt:""}):(0,n.jsx)(l,{size:19})})}function F({openTools:e,onTool:t,onNewChat:a,theme:l,onToggleTheme:i}){return(0,n.jsxs)("nav",{className:"rail rail-left","aria-label":"Primary workspace navigation",children:[(0,n.jsx)("button",{type:"button",className:"rail-new",onClick:a,"data-side":"left","aria-label":"New chat","data-tip":"New chat",children:(0,n.jsx)(j.Icons.newChat,{size:18})}),(0,n.jsx)("div",{className:"rail-div"}),(0,n.jsx)("div",{className:"rail-group",children:D.map(a=>(0,n.jsx)(q,{tool:a,active:e.has(a.id),onClick:()=>t(a.id)},a.id))}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("div",{className:"rail-group",children:[(0,n.jsx)("button",{type:"button",className:"rail-btn","data-active":e.has("memoria")?"true":"false","data-side":"left","aria-label":"MemoriaViva","aria-pressed":e.has("memoria"),"data-tip":"MemoriaViva",onClick:()=>t("memoria"),children:(0,n.jsx)(j.Icons.brain,{size:19})}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":e.has("quality")?"true":"false","aria-label":"Quality Intelligence","aria-pressed":e.has("quality"),"data-tip":"Quality Intelligence",onClick:()=>t("quality"),children:(0,n.jsx)(j.Icons.check,{size:19})}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":e.has("promptEnhancer")?"true":"false","aria-label":"Prompt Enhancer","aria-pressed":e.has("promptEnhancer"),"data-tip":"Prompt Enhancer",onClick:()=>t("promptEnhancer"),children:(0,n.jsx)(j.Icons.spark,{size:19})}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":e.has("localKnowledge")?"true":"false","aria-label":"Local Knowledge","aria-pressed":e.has("localKnowledge"),"data-tip":"Local Knowledge",onClick:()=>t("localKnowledge"),children:(0,n.jsx)(j.Icons.localKnowledge,{size:19})}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":e.has("figma")?"true":"false","aria-label":"Figma Snapshot","aria-pressed":e.has("figma"),"data-tip":"Figma Snapshot",onClick:()=>t("figma"),children:(0,n.jsx)(j.Icons.layers,{size:19})})]}),(0,n.jsx)("div",{className:"rail-div"}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","aria-label":"light"===l?"Dark mode":"Light mode","aria-pressed":"light"===l,"data-tip":"light"===l?"Dark mode":"Light mode",onClick:i,children:"light"===l?(0,n.jsx)(j.Icons.moon,{size:19}):(0,n.jsx)(j.Icons.sun,{size:19})}),(0,n.jsx)("button",{type:"button",className:"rail-btn","data-side":"left","data-active":e.has("settings")?"true":"false","aria-label":"Settings","aria-pressed":e.has("settings"),"data-tip":"Settings",onClick:()=>t("settings"),children:(0,n.jsx)(j.Icons.settings,{size:19})})]})}function O(e){return(0,n.jsx)("aside",{className:"rail rail-right","aria-label":"Workspace utilities",children:(0,n.jsx)("span",{className:"spacer"})})}function z(e){return e.toFixed(2)}function K({onNewWindow:e}){let t=(0,a.useId)(),l=`ewb-${t.replace(/:/gu,"")}`,i=(0,a.useRef)(null),r=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=e=>{i.current?.setAttribute("d",function(e){let t=[];for(let n=0;n<150;n++){let a=n/150*Math.PI*2,l=1+.07*(.55*Math.sin(3*a+e)+.32*Math.sin(5*a-.8*e+1.7)+.22*Math.sin(2*a+.5*e+.4));t.push([140+127.44000000000001*l*Math.cos(a),140+118*l*Math.sin(a)])}let n=`M${z(t[0]?.[0]??140)} ${z(t[0]?.[1]??140)} `;for(let e=0;e<t.length;e++){let a=t[(e-1+t.length)%t.length],l=t[e],i=t[(e+1)%t.length],r=t[(e+2)%t.length],s=l[0]+(i[0]-a[0])/6,o=l[1]+(i[1]-a[1])/6,c=i[0]-(r[0]-l[0])/6,d=i[1]-(r[1]-l[1])/6;n+=`C${z(s)} ${z(o)} ${z(c)} ${z(d)} ${z(i[0])} ${z(i[1])} `}return`${n}Z`}(e))};if(e(.7),"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||"function"!=typeof window.requestAnimationFrame)return;let t=0,n=()=>{0!==t&&(window.cancelAnimationFrame(t),t=0)},a=n=>{e(85e-5*n),t=window.requestAnimationFrame(a)},l=()=>{0===t&&!0!==document.hidden&&(t=window.requestAnimationFrame(a))},r=()=>{!0===document.hidden?n():l()};return l(),document.addEventListener("visibilitychange",r),window.addEventListener("blur",n),window.addEventListener("focus",l),()=>{n(),document.removeEventListener("visibilitychange",r),window.removeEventListener("blur",n),window.removeEventListener("focus",l)}},[]);let s=(0,a.useCallback)(()=>{let t=r.current;null!==t&&(t.classList.remove("is-pulse"),t.getBoundingClientRect(),t.classList.add("is-pulse")),e()},[e]);return(0,n.jsx)("button",{type:"button",className:"empty-workspace-blob","aria-label":"Open a new window",onClick:s,children:(0,n.jsxs)("svg",{width:"320",height:"320",viewBox:"0 0 280 280","aria-hidden":"true",children:[(0,n.jsx)("defs",{children:(0,n.jsxs)("mask",{id:l,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"280",height:"280",children:[(0,n.jsx)("rect",{x:"0",y:"0",width:"280",height:"280",fill:"#fff"}),(0,n.jsx)("g",{transform:"translate(107,64) scale(0.080625)",children:(0,n.jsx)("g",{transform:"translate(1024 0) scale(-1 1)",children:(0,n.jsx)("g",{transform:"translate(1024,1024) scale(-0.1,-0.1)",fill:"#000",children:(0,n.jsx)("path",{d:"M3465 8223 c-144 -8 -314 -52 -408 -105 -69 -39 -146 -99 -146 -113 0 -5 30 -24 68 -42 146 -70 323 -229 377 -340 25 -49 29 -70 29 -138 -1 -72 -5 -88 -39 -160 -36 -75 -54 -95 -265 -305 -134 -132 -270 -279 -331 -355 -339 -425 -552 -896 -626 -1390 -25 -165 -25 -549 0 -720 92 -645 368 -1196 826 -1655 322 -324 710 -562 1145 -704 389 -126 793 -172 1155 -130 235 27 377 63 579 149 205 87 268 86 423 -7 102 -62 231 -115 335 -138 247 -56 562 -26 794 74 92 40 244 136 232 146 -4 3 -26 12 -48 19 -86 28 -246 116 -385 211 -162 112 -284 182 -357 207 l-48 17 40 15 c185 70 436 223 595 363 438 386 695 1014 678 1663 l-3 120 -50 -70 c-64 -90 -248 -280 -350 -362 -171 -136 -366 -255 -645 -391 -288 -140 -442 -243 -590 -391 -136 -137 -247 -316 -325 -526 -47 -127 -114 -262 -160 -326 -79 -107 -237 -224 -384 -283 -136 -55 -355 -96 -514 -96 -274 0 -548 71 -832 215 -242 123 -375 216 -553 389 -175 171 -287 332 -361 517 -44 114 -63 216 -63 359 0 152 17 233 74 350 35 70 59 102 136 179 l95 94 21 -29 c55 -75 219 -277 277 -338 171 -183 337 -256 582 -256 56 0 126 -3 155 -7 53 -6 54 -7 76 -57 30 -66 97 -128 172 -156 151 -57 318 11 395 160 33 62 34 193 3 261 -30 64 -88 125 -148 157 -44 23 -63 27 -141 27 -78 0 -97 -4 -140 -27 -58 -30 -131 -105 -141 -142 -6 -25 -8 -26 -93 -26 -47 0 -131 5 -186 10 -87 8 -111 15 -182 51 -45 22 -109 66 -143 96 -59 53 -326 361 -319 367 14 11 179 47 241 52 102 9 177 -7 318 -66 158 -66 243 -89 357 -99 157 -12 413 5 582 40 l93 19 44 -39 c59 -52 135 -75 228 -69 117 8 212 72 262 176 23 47 28 71 28 138 0 70 -4 89 -29 138 -55 110 -145 167 -270 174 -65 3 -91 0 -137 -18 -107 -40 -183 -140 -195 -257 l-6 -52 -51 -11 c-104 -23 -285 -41 -411 -42 -149 -1 -211 12 -402 88 -186 74 -256 88 -403 81 -193 -8 -377 -70 -546 -182 -342 -228 -485 -611 -399 -1064 30 -157 119 -388 209 -541 20 -35 35 -64 33 -66 -8 -8 -111 108 -190 214 -154 206 -278 489 -324 737 -28 154 -25 492 6 635 46 216 133 391 256 514 82 82 161 128 271 156 152 39 300 23 529 -57 217 -76 308 -101 410 -114 137 -17 284 -7 426 30 272 70 414 145 809 425 217 153 399 238 610 283 64 14 129 18 265 18 197 0 269 -9 615 -76 461 -89 843 -149 952 -149 41 0 41 0 23 -20 -28 -31 -169 -119 -254 -158 -167 -77 -388 -145 -716 -222 -399 -93 -508 -128 -608 -194 -102 -68 -160 -160 -217 -346 -35 -115 -102 -286 -149 -378 -85 -168 -227 -341 -377 -458 -105 -82 -115 -107 -69 -162 29 -34 65 -44 109 -29 86 29 261 181 371 322 126 162 201 309 295 581 61 176 90 232 145 283 62 57 163 93 470 165 439 104 640 169 863 278 206 100 368 240 434 375 32 67 33 71 33 198 -1 120 -3 138 -34 229 -98 294 -319 655 -573 936 -381 421 -968 723 -1618 834 -448 76 -767 83 -1169 25 -80 -12 -165 -19 -190 -17 -26 3 -90 26 -146 53 -343 162 -576 233 -842 255 -114 9 -141 10 -248 3z m2926 -1227 c164 -27 346 -102 485 -202 181 -129 354 -348 354 -448 0 -64 -75 -126 -154 -126 -60 0 -63 4 -52 70 8 50 7 65 -9 100 -29 64 -74 93 -151 98 -54 4 -70 1 -107 -21 -42 -25 -61 -52 -91 -129 -25 -64 -55 -73 -246 -73 -121 0 -187 5 -248 18 -318 70 -556 242 -556 402 0 218 388 374 775 311z m-2249 -611 c119 -21 208 -50 321 -106 114 -56 177 -100 266 -184 67 -63 157 -173 148 -181 -2 -3 -61 18 -130 45 -131 52 -298 100 -427 122 -113 20 -367 17 -470 -4 -502 -106 -885 -433 -1160 -992 -70 -142 -160 -379 -160 -424 0 -9 -5 -23 -11 -31 -13 -19 -5 316 10 410 80 482 295 846 661 1117 145 107 350 197 522 228 100 18 326 18 430 0z m1485 -1456 c95 -36 119 -159 42 -223 -78 -66 -209 -1 -209 104 0 60 33 100 99 121 36 10 36 10 68 -2z m-591 -822 c29 -26 37 -42 40 -77 6 -54 -9 -86 -55 -117 -41 -28 -70 -29 -119 -4 -44 22 -62 55 -62 112 0 51 13 75 53 99 50 31 101 26 143 -13z"})})})}),(0,n.jsx)("text",{x:"140",y:"172",textAnchor:"middle",fill:"#000",fontFamily:"var(--font-ui)",fontSize:"16",fontWeight:"700",children:"Empty workspace"}),(0,n.jsx)("text",{x:"140",y:"191",textAnchor:"middle",fill:"#000",fontFamily:"var(--font-ui)",fontSize:"11",fontWeight:"400",children:"Open a window to start working"})]})}),(0,n.jsx)("g",{ref:r,className:"empty-workspace-blob__group",children:(0,n.jsx)("path",{ref:i,className:"empty-workspace-blob__fill",mask:`url(#${l})`})})]})})}function B(e){return 0===e.button&&!(0===e.button&&e.ctrlKey)}function _(e){return e instanceof Element&&null!==e.closest("button,input,textarea,select,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='dialog'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab'],.dlg-overlay,.mc-dialog-backdrop,.cmdk-overlay,.window,.ws-zoom,.ws-fab,.empty-workspace-blob,.conn-badge")}function U(){return!("u"<typeof document)&&"true"===document.documentElement.getAttribute("data-keiko-modal-open")}let W=0,V="",H="";function Y(){if("u"<typeof document)return()=>void 0;let e=document.body;0===W&&(V=e.style.cursor,H=e.style.userSelect,e.style.cursor="grabbing",e.style.userSelect="none"),W+=1;let t=!1;return()=>{t||(t=!0,0===(W=Math.max(0,W-1))&&(e.style.cursor=V,e.style.userSelect=H))}}let G="keiko.wallpaper.enabled",J="keiko.wallpaper.opacity",X="keiko.workspace.background.brightness",Q="keiko.workspace.grid.strength",Z="keiko.frame.border.strength",ee="keiko.frame.inner.glow.strength",et="keiko:wallpaper-enabled",en="keiko:wallpaper-opacity",ea="keiko:workspace-background-brightness",el="keiko:workspace-grid-strength",ei="keiko:frame-border-strength",er="keiko:frame-inner-glow-strength";function es(e){return Number.isFinite(e)?Math.max(0,Math.min(100,e)):0}function eo(){try{if("function"!=typeof window.localStorage?.getItem)return!1;return"true"===window.localStorage.getItem(G)}catch{return!1}}function ec(){try{if("function"!=typeof window.localStorage?.getItem)return 100;let e=window.localStorage.getItem(J);if(null===e)return 100;return es(Number.parseInt(e,10))}catch{return 100}}function ed(){try{if("function"!=typeof window.localStorage?.getItem)return 0;let e=window.localStorage.getItem(X);if(null===e)return 0;return es(Number.parseInt(e,10))}catch{return 0}}function eu(){try{if("function"!=typeof window.localStorage?.getItem)return 28;let e=window.localStorage.getItem(Q);if(null===e)return 28;return es(Number.parseInt(e,10))}catch{return 28}}function ep(){try{if("function"!=typeof window.localStorage?.getItem)return 42;let e=window.localStorage.getItem(Z);if(null===e)return 42;return es(Number.parseInt(e,10))}catch{return 42}}function em(){try{if("function"!=typeof window.localStorage?.getItem)return 0;let e=window.localStorage.getItem(ee);if(null===e)return 0;return es(Number.parseInt(e,10))}catch{return 0}}function eh(e){"u">typeof document&&document.documentElement.style.setProperty("--workspace-bg-brightness",`${es(e)}%`)}function ef(e){"u">typeof document&&document.documentElement.style.setProperty("--workspace-grid-strength",`${es(e)}%`)}function eg(e){"u">typeof document&&document.documentElement.style.setProperty("--frame-border-strength",`${es(e)}%`)}function ev(e){"u">typeof document&&document.documentElement.style.setProperty("--frame-inner-glow-strength",`${es(e)}%`)}let eb=`
4
- attribute vec2 aPos;
5
- void main(){ gl_Position = vec4(aPos, 0.0, 1.0); }
6
- `,ex=`
7
- precision highp float;
8
- uniform vec2 uRes;
9
- uniform float uTime;
10
- uniform float uLight; // 1 = light theme, 0 = dark; WebGL default 0 keeps failure mode dark
11
- uniform vec2 uRip[4]; // ripple origins (0..1, y up)
12
- uniform float uRipT[4]; // seconds since each ripple fired (large = inactive)
13
-
14
- float hash(vec2 p){
15
- p = fract(p * vec2(123.34, 456.21));
16
- p += dot(p, p + 45.32);
17
- return fract(p.x * p.y);
18
- }
19
- float vnoise(vec2 p){
20
- vec2 i = floor(p), f = fract(p);
21
- vec2 u = f * f * (3.0 - 2.0 * f);
22
- float a = hash(i), b = hash(i + vec2(1.,0.));
23
- float c = hash(i + vec2(0.,1.)), d = hash(i + vec2(1.,1.));
24
- return mix(mix(a,b,u.x), mix(c,d,u.x), u.y);
25
- }
26
- float fbm(vec2 p){
27
- float v = 0.0, a = 0.5;
28
- mat2 m = mat2(1.6, 1.2, -1.2, 1.6);
29
- for(int i = 0; i < 5; i++){ v += a * vnoise(p); p = m * p; a *= 0.5; }
30
- return v;
31
- }
32
-
33
- void main(){
34
- vec2 uv = gl_FragCoord.xy / uRes.xy;
35
- float aspect = uRes.x / uRes.y;
36
- vec2 p = vec2(uv.x * aspect, uv.y);
37
-
38
- float t = uTime * 0.06;
39
-
40
- // --- click ripples ---------------------------------------------------
41
- float rip = 0.0;
42
- for(int i = 0; i < 4; i++){
43
- float age = uRipT[i];
44
- if(age < 2.4){
45
- vec2 rc = vec2(uRip[i].x * aspect, uRip[i].y);
46
- float d = distance(p, rc);
47
- float ring = sin(d * 15.0 - age * 9.0);
48
- float env = exp(-d * 3.6) * exp(-age * 2.1);
49
- rip += ring * env;
50
- }
51
- }
52
-
53
- // --- liquid domain warp ---------------------------------------------
54
- vec2 warp = vec2(
55
- fbm(p * 2.1 + vec2(0.0, t)),
56
- fbm(p * 2.1 + vec2(t, 4.7))
57
- );
58
- warp += rip * 0.07;
59
-
60
- float f = fbm(p * 2.4 + warp * 1.7 + vec2(t * 0.6, 0.0));
61
-
62
- // --- chrome banding (sharp metallic streaks) ------------------------
63
- float bands = abs(sin((f * 4.0 + warp.x * 2.0) * 3.14159 + t * 1.4));
64
- float chrome = pow(bands, 2.6);
65
-
66
- // --- palette (brand) -------------------------------------------------
67
- vec3 baseD = vec3(0.072, 0.085, 0.079); // warm near-black ~ --bg
68
- vec3 metalD = vec3(0.205, 0.230, 0.216); // chrome mid grey
69
- vec3 baseL = vec3(0.930, 0.942, 0.935); // near-white
70
- vec3 metalL = vec3(0.795, 0.835, 0.812); // soft grey
71
- vec3 green = vec3(0.306, 0.729, 0.529); // #4EBA87
72
-
73
- vec3 base = mix(baseD, baseL, uLight);
74
- vec3 metal = mix(metalD, metalL, uLight);
75
-
76
- vec3 col = mix(base, metal, chrome * 0.85);
77
-
78
- // orca-green sheen on the brightest specular ridges
79
- float spec = smoothstep(0.80, 1.0, bands);
80
- col += green * spec * mix(0.16, 0.085, uLight);
81
-
82
- // ripple highlight
83
- vec3 ripCol = mix(vec3(1.0), green, uLight);
84
- col += ripCol * max(rip, 0.0) * 0.032;
85
-
86
- // keep it dezent — pull back toward base
87
- col = mix(base, col, 0.84);
88
-
89
- gl_FragColor = vec4(col, 1.0);
90
- }
91
- `;function ey(e,t,n){let a=e.createShader(t);return null===a?null:(e.shaderSource(a,n),e.compileShader(a),e.getShaderParameter(a,e.COMPILE_STATUS))?a:(e.deleteShader(a),null)}function ew(){let e=(0,a.useRef)(null),[t,l]=(0,a.useState)(eo);return(0,a.useEffect)(()=>{eh(ed()),ef(eu()),eg(ep()),ev(em());let e=e=>{let t=e.detail;eh("number"==typeof t?t:ed())},t=e=>{let t=e.detail;ef("number"==typeof t?t:eu())},n=e=>{let t=e.detail;eg("number"==typeof t?t:ep())},a=e=>{let t=e.detail;ev("number"==typeof t?t:em())};return window.addEventListener(ea,e),window.addEventListener(el,t),window.addEventListener(ei,n),window.addEventListener(er,a),()=>{window.removeEventListener(ea,e),window.removeEventListener(el,t),window.removeEventListener(ei,n),window.removeEventListener(er,a)}},[]),(0,a.useEffect)(()=>{let e=e=>{let t=e.detail;l("boolean"==typeof t?t:eo())},t=e=>{(null===e.key||e.key===G)&&l(eo())};return window.addEventListener(et,e),window.addEventListener("storage",t),()=>{window.removeEventListener(et,e),window.removeEventListener("storage",t)}},[]),(0,a.useEffect)(()=>{let n;if(!t)return;let a=e.current;if(null===a)return;let l=a.parentElement;if(null===l)return;let i=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>{i.matches?(n?.(),n=void 0):void 0===n&&(n=function(e,t){t.style.opacity=String(ec()/100);let n=e=>{let n=e.detail,a="number"==typeof n?n:ec();t.style.opacity=String(es(a)/100)};window.addEventListener(en,n);let a=null;try{a=t.getContext("webgl",{antialias:!1,alpha:!1,premultipliedAlpha:!1,depth:!1})}catch{a=null}if(null===a)return()=>{window.removeEventListener(en,n)};let l=ey(a,a.VERTEX_SHADER,eb),i=ey(a,a.FRAGMENT_SHADER,ex);if(null===l||null===i)return()=>{window.removeEventListener(en,n)};let r=a.createProgram();if(null===r||(a.attachShader(r,l),a.attachShader(r,i),a.linkProgram(r),!a.getProgramParameter(r,a.LINK_STATUS)))return()=>{window.removeEventListener(en,n)};a.useProgram(r);let s=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,s),a.bufferData(a.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),a.STATIC_DRAW);let o=a.getAttribLocation(r,"aPos");a.enableVertexAttribArray(o),a.vertexAttribPointer(o,2,a.FLOAT,!1,0,0);let c=a.getUniformLocation(r,"uRes"),d=a.getUniformLocation(r,"uTime"),u=a.getUniformLocation(r,"uLight"),p=a.getUniformLocation(r,"uRip"),m=a.getUniformLocation(r,"uRipT"),h=1,f=1,g=Math.min(window.devicePixelRatio??1,1.5),v=new Float32Array(8),b=[,,,,].fill(-1/0),x=0;function y(){let n=e.getBoundingClientRect();h=Math.max(1,Math.round(n.width)),f=Math.max(1,Math.round(n.height)),t.width=Math.round(h*g),t.height=Math.round(f*g),t.style.width=`${String(h)}px`,t.style.height=`${String(f)}px`,null!==a&&a.viewport(0,0,t.width,t.height)}y();let w="u">typeof ResizeObserver?new ResizeObserver(y):null;null!==w?w.observe(e):window.addEventListener("resize",y);let j=t=>{let n=e.getBoundingClientRect(),a=(t.clientX-n.left)/Math.max(1,n.width),l=1-(t.clientY-n.top)/Math.max(1,n.height);a<0||a>1||l<0||l>1||(v[2*x]=a,v[2*x+1]=l,b[x]=performance.now(),x=(x+1)%4)};e.addEventListener("pointerdown",j);let k=performance.now(),N=0,S=!0,C=new Float32Array(4);function I(){if(!S)return;let e=performance.now();for(let t=0;t<4;t++)C[t]=(e-(b[t]??-1/0))/1e3;let n=+("light"===document.documentElement.dataset.theme);null!==a&&(a.uniform2f(c,t.width,t.height),a.uniform1f(d,(e-k)/1e3),a.uniform1f(u,n),a.uniform2fv(p,v),a.uniform1fv(m,C),a.drawArrays(a.TRIANGLES,0,3)),N=requestAnimationFrame(I)}N=requestAnimationFrame(I);let E=()=>{document.hidden?(S=!1,cancelAnimationFrame(N)):S||(S=!0,N=requestAnimationFrame(I))};return document.addEventListener("visibilitychange",E),()=>{S=!1,cancelAnimationFrame(N),document.removeEventListener("visibilitychange",E),window.removeEventListener(en,n),e.removeEventListener("pointerdown",j),null!==w?w.disconnect():window.removeEventListener("resize",y),null!==a&&(a.deleteBuffer(s),a.deleteProgram(r),a.deleteShader(l),a.deleteShader(i))}}(l,a))};return r(),i.addEventListener("change",r),()=>{i.removeEventListener("change",r),n?.()}},[t]),t?(0,n.jsx)("canvas",{ref:e,className:"ws-shader","aria-hidden":"true"}):null}let ej=new Set(["files","connector","browser","plugins","agents","quality"]);function ek(e,t){return e>=4||t>=8192}function eN({pathId:e,intensity:t}){let a="heavy"===t?3:1,l="heavy"===t?1.1:2.2;return(0,n.jsx)(n.Fragment,{children:Array.from({length:a},(i,r)=>(0,n.jsx)("circle",{className:"conn-particle",r:"heavy"===t?3:2.4,"aria-hidden":"true",children:(0,n.jsx)("animateMotion",{dur:`${String(l)}s`,repeatCount:"indefinite",begin:`${String(l/a*r)}s`,rotate:"auto",keyPoints:"0;1",keyTimes:"0;1",calcMode:"linear",children:(0,n.jsx)("mpath",{href:`#${e}`})})},r))})}function eS({wins:e,conns:t,connecting:l,api:i}){let r=s(),o=function(){let[e,t]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)");t(e.matches);let n=e=>t(e.matches);return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]),e}(),{armedId:c,arm:d,disarm:u}=function(){let[e,t]=(0,a.useState)(null);return(0,a.useEffect)(()=>{if(null===e)return;let n=setTimeout(()=>t(null),3e3);return()=>clearTimeout(n)},[e]),{armedId:e,arm:e=>t(e),disarm:()=>t(null)}}(),{flowing:p,intensity:m}=function(e,t){let[n,l]=(0,a.useState)("light"),[i,r]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{if(void 0===t)return;l(function(e){switch(e.groundingKind){case"connected-context":return ek(e.contextPack.usage.filesRead,e.contextPack.usage.excerptBytes)?"heavy":"light";case"hybrid":return ek(e.contextPack.folder.usage.filesRead,e.contextPack.folder.usage.excerptBytes)||e.contextPack.knowledge.referencesUsed>=4?"heavy":"light";case"local-knowledge":return e.contextPack.referencesUsed>=4?"heavy":"light";default:return"light"}}(t)),r(!0);let e=setTimeout(()=>r(!1),2500);return()=>clearTimeout(e)},[t]),{flowing:e||i,intensity:n}}(r?.sending===!0,r?.latestGrounded),h=function(e,t){let n=new Map(e.map(e=>[e.id,e])),a=[];for(let e of t){let t=n.get(e.a),l=n.get(e.b);if(void 0===t||void 0===l)continue;let i=function(e,t){let n,a,l,i,r={x:e.x+e.w/2,y:e.y+e.h/2},s={x:t.x+t.w/2,y:t.y+t.h/2},o=s.x-r.x,c=s.y-r.y;if(Math.abs(o)>=Math.abs(c)){n=o>=0?{x:e.x+e.w,y:r.y}:{x:e.x,y:r.y};let c=Math.max(40,Math.abs((a=o>=0?{x:t.x,y:s.y}:{x:t.x+t.w,y:s.y}).x-n.x)/2),d=o>=0?1:-1;l={x:n.x+d*c,y:n.y},i={x:a.x-d*c,y:a.y}}else{n=c>=0?{x:r.x,y:e.y+e.h}:{x:r.x,y:e.y};let o=Math.max(40,Math.abs((a=c>=0?{x:s.x,y:t.y}:{x:s.x,y:t.y+t.h}).y-n.y)/2),d=c>=0?1:-1;l={x:n.x,y:n.y+d*o},i={x:a.x,y:a.y-d*o}}let d={x:(n.x+3*l.x+3*i.x+a.x)/8,y:(n.y+3*l.y+3*i.y+a.y)/8};return{d:`M${String(n.x)},${String(n.y)} C${String(l.x)},${String(l.y)} ${String(i.x)},${String(i.y)} ${String(a.x)},${String(a.y)}`,mid:d}}(t,l);a.push({c:e,d:i.d,mid:i.mid,label:A(t,l),dataChannel:function(e,t){let n=[e.type,t.type].includes("chat"),a="chat"===e.type?ej.has(t.type):ej.has(e.type);return n&&a}(t,l)})}return a}(e,t),f=null!==l?function(e,t){let n=t.find(t=>t.id===e.from);if(void 0===n)return null;let a={x:n.x+n.w/2,y:n.y+n.h/2},l=e.x-a.x,i=e.y-a.y,r=Math.abs(l)>=Math.abs(i),s=r?{x:l>=0?n.x+n.w:n.x,y:a.y}:{x:a.x,y:i>=0?n.y+n.h:n.y},o=Math.max(40,Math.abs(r?l:i)/2),c=r?{x:s.x+(l>=0?o:-o),y:s.y}:{x:s.x,y:s.y+(i>=0?o:-o)},d=e.x,u=e.y;return{d:`M${String(s.x)},${String(s.y)} C${String(c.x)},${String(c.y)} ${String(d)},${String(u)} ${String(d)},${String(u)}`,ex:d,ey:u}}(l,e):null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"conn-layer",children:(0,n.jsxs)("svg",{className:"conn-svg",viewBox:"-10000 -10000 20000 20000",preserveAspectRatio:"xMidYMid meet",children:[h.map(e=>{let t=p&&e.dataChannel,a=`conn-path-${e.c.id}`;return(0,n.jsxs)("g",{children:[(0,n.jsx)("path",{id:a,className:"conn-path",d:e.d,"data-active":t?"true":void 0,"data-intensity":t?m:void 0,"data-reduced-motion":t&&o?"true":void 0}),t&&!o?(0,n.jsx)(eN,{pathId:a,intensity:m}):null]},e.c.id)}),null!==f?(0,n.jsx)("path",{className:"conn-path conn-temp",d:f.d}):null,null!==f?(0,n.jsx)("circle",{className:"conn-dot",cx:f.ex,cy:f.ey,r:"5"}):null]})}),(0,n.jsx)("div",{className:"conn-badge-layer",children:h.map(t=>{let a,l=p&&t.dataChannel;if(!function(e,t,n=!1){let a,l=(a=Math.min(240,Math.max(40,7.2*e.label.length))+(44+18*!!n),{left:e.mid.x-a/2,right:e.mid.x+a/2,top:e.mid.y-13,bottom:e.mid.y+13});return!t.some(e=>{var t;return!0!==e.minimized&&(t={left:e.x,top:e.y,right:e.x+e.w,bottom:e.y+e.h},l.left<t.right&&l.right>t.left&&l.top<t.bottom&&l.bottom>t.top)})}(t,e,l))return null;let r=c===t.c.id,s=(a=[`Connection: ${t.label}`],void 0!==t.c.boundRoot&&a.push(`Root: ${t.c.boundRoot}`),void 0!==t.c.boundScopeKind&&a.push(`Scope: ${t.c.boundScopeKind}`),void 0!==t.c.boundRelativePath&&t.c.boundRelativePath.length>0&&a.push(`Path: ${t.c.boundRelativePath}`),void 0!==t.c.boundConnectorKind&&void 0!==t.c.boundConnectorId&&a.push(`Knowledge: ${t.c.boundConnectorKind} ${t.c.boundConnectorId}`),a.join("\n"));return(0,n.jsxs)("button",{type:"button",className:"conn-badge","data-active":l?"true":void 0,"data-intensity":l?m:void 0,"data-armed":r?"true":void 0,style:{left:t.mid.x,top:t.mid.y},onClick:()=>{r?(u(),i.removeConn(t.c.id)):d(t.c.id)},onBlur:()=>{r&&u()},title:r?`Click again to remove: ${t.label}
92
-
93
- ${s}`:`${s}
94
-
95
- Click once to arm removal.`,"aria-label":r?`Confirm removal of connection: ${t.label}. Activate again to remove.`:l?`${t.label} — ${m} data exchange in progress. Activate to remove connection.`:`Remove connection: ${t.label}`,children:[(0,n.jsx)(j.Icons.git,{size:11})," ",(0,n.jsx)("span",{children:r?"Remove?":t.label}),l&&!r?(0,n.jsx)("span",{className:"conn-flow-tag","aria-hidden":"true",children:"heavy"===m?"⇶":"→"}):null]},t.c.id)})})]})}let eC=["n","s","e","w","ne","nw","se","sw"],eI=["t","r","b","l"];function eE({icon:e,label:t}){let a=j.Icons[e];return(0,n.jsxs)("div",{className:"too-small",children:[(0,n.jsx)("div",{className:"ts-ico",children:(0,n.jsx)(a,{size:28})}),(0,n.jsxs)("div",{className:"ts-title",children:["Too small to show ",t]}),(0,n.jsx)("div",{className:"ts-sub",children:"Enlarge the window or zoom its content out"}),(0,n.jsx)("div",{className:"ts-arrow","aria-hidden":"true",children:(0,n.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 22 22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M8 8l8 8M16 11v5h-5"})})})]})}function eR({win:e,top:t,connState:l,view:i,api:r,wsRef:s}){var o;let c=E[e.type],d=void 0!==(o=e.type)&&((R[o]??[]).length>0||Object.values(R).some(e=>e.includes(o))),u=j.Icons[c.icon],[p,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),f=(0,a.useRef)(null),g=e.zoom??1,v="chat"===e.type||"agents"===e.type||"quality"===e.type||"editor"===e.type,b="agents"===e.type||"quality"===e.type||"editor"===e.type,x="quality"===e.type||"editor"===e.type,y=v?r.linkedFilesRoot(e.id):null,w=b?r.linkedFilesContext(e.id)?.activeFilePath:void 0,k="quality"===e.type?r.linkedAllFilesRoots(e.id):null!==y?[y]:[],N=x?r.linkedConnectorCapsuleIds(e.id):[],S=x?r.linkedConnectorCapsuleSetIds(e.id):[],C="quality"===e.type?r.linkedFigmaSnapshotRunIds(e.id):[],I="quality"===e.type?r.linkedFigmaSnapshotSources?.(e.id):void 0,$="quality"===e.type?r.linkedImageSources?.(e.id):void 0,A=e.w/g,T=e.h/g,P=(0,a.useCallback)(t=>{r.update(e.id,{cfg:{...e.cfg,...t}})},[r,e.cfg,e.id]),M=(0,a.useCallback)((e,t)=>r.add(e,t),[r]),{mode:D,node:q}=function(e,t,a,l,i,r,s,o,c,d,u,p,m,h,f){let g=E[t];if("chat"===t){let t=a<520,n=a<430;return{mode:n?"mini":"full",node:g.render(i,{windowId:e,mini:n,minimalChat:a<360||l<320,compact:a<640,controlsNarrow:t,barCompact:a<520,workflowCompact:t,linkedRoot:r,linkedFilePath:s,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:p,linkedImageSources:m,updateCfg:h,openWindow:f})}}return a<g.tiny.w||l<g.tiny.h?{mode:"tiny",node:(0,n.jsx)(eE,{icon:g.icon,label:g.title})}:{mode:"full",node:g.render(i,{windowId:e,linkedRoot:r,linkedFilePath:s,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:p,linkedImageSources:m,updateCfg:h,openWindow:f})}}(e.id,e.type,A,T,e.cfg,y,w,k,N,S,C,I,$,P,M),F=(0,a.useCallback)(t=>r.update(e.id,{zoom:Math.max(.5,Math.min(2,Math.round(10*t)/10))}),[r,e.id]);(0,a.useEffect)(()=>{var t,n;if(t=e.type,n=e.cfg,"figmaView"!==t||"string"!=typeof n.selectedScreenIdsJson||!(n.selectedScreenIdsJson.length>0)||e.max||"full"!==D)return;let a=h.current;if(null===a)return;let l=null,i=()=>{l=null;let t=a.scrollHeight-a.clientHeight;if(t<=8)return;let n=Math.ceil(e.h+t);n<=e.h+8||r.update(e.id,{h:n})},s=()=>{null===l&&(l="function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(i):window.setTimeout(i,0))};s();let o="u">typeof ResizeObserver?new ResizeObserver(s):null;o?.observe(a);let c=a.firstElementChild;return null!==c&&o?.observe(c),()=>{null!==l&&("function"==typeof window.cancelAnimationFrame?window.cancelAnimationFrame(l):window.clearTimeout(l)),o?.disconnect()}},[r,D,e.cfg,e.h,e.id,e.max,e.type]),(0,a.useEffect)(()=>()=>{f.current?.(),f.current=null},[]);let O=(0,a.useCallback)(t=>{t instanceof Element&&null!==t.closest("button,input,textarea,select,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab']")?window.setTimeout(()=>r.focus(e.id),0):r.focus(e.id)},[r,e.id]),z=(0,a.useCallback)(t=>{var n,a,o,c;let d,u,p,h,f;if(!(B(c=t)||1===c.button)||"valid"===l)return;t.preventDefault(),O(t.target);let g=s.current;if(null===g)return;let v=(n=g.getBoundingClientRect(),{z:d=i.zoom,vpx0:-i.x/d,vpy0:-i.y/d,vpw:n.width/d,vph:n.height/d,toWX:e=>(e-n.left-i.x)/d,toWY:e=>(e-n.top-i.y)/d}),b=e.max,x=b?e.prev?.w??480:e.w,y=b?e.prev?.h??360:e.h,w=b?x/2:v.toWX(t.clientX)-e.x,j=b?18:v.toWY(t.clientY)-e.y;b&&r.update(e.id,{max:!1,w:x,h:y}),m(!0),a={winId:e.id,offX:w,offY:j,W:x},o=()=>m(!1),u=30/v.z,p=e=>{let t,n,l,i,s=v.toWX(e.clientX),o=v.toWY(e.clientY),c=s-a.offX,d=o-a.offY;c=Math.max(v.vpx0-(a.W-120),Math.min(v.vpx0+v.vpw-120,c)),d=Math.max(v.vpy0,Math.min(v.vpy0+v.vph-38,d)),r.setSnap((t=s-v.vpx0<u,n=v.vpx0+v.vpw-s<u,l=o-v.vpy0<u,i=v.vpy0+v.vph-o<u,l&&t?"tl":l&&n?"tr":i&&t?"bl":i&&n?"br":t?"left":n?"right":l?"maxi":null)),r.update(a.winId,{x:c,y:d})},h=()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),r.commitSnap(a.winId),f(),o?.()},f=Y(),window.addEventListener("pointermove",p),window.addEventListener("pointerup",h),window.addEventListener("pointercancel",h)},[r,e.id,e.x,e.y,e.w,e.h,e.max,e.prev,i,s,l,O]),K=(0,a.useCallback)(t=>n=>{if(!B(n))return;n.preventDefault(),n.stopPropagation(),f.current?.(),f.current=null,r.focus(e.id);let a={x:e.x,y:e.y,w:e.w,h:e.h},l=a,s=n.clientX,o=n.clientY,c=i.zoom,d=document.body.style.cursor,u=!0,p=()=>{u&&(u=!1,window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),window.removeEventListener("blur",m),document.body.style.cursor=d,f.current===p&&(f.current=null))},m=()=>{p()},h=n=>{var i;if(!u)return;if(0===n.buttons)return void p();let d=function(e,t,n,a,l){let{x:i,y:r,w:s,h:o}=e;t.includes("e")&&(s=e.w+n),t.includes("s")&&(o=e.h+a),t.includes("w")&&(s=e.w-n,i=e.x+n),t.includes("n")&&(o=e.h-a,r=e.y+a);let c=E[l].min,d=c.w>0?c.w:240,u=c.h>0?c.h:150;return s<d&&(t.includes("w")&&(i-=d-s),s=d),o<u&&(t.includes("n")&&(r-=u-o),o=u),{x:i,y:r,w:s,h:o}}(a,t,(n.clientX-s)/c,(n.clientY-o)/c,e.type);((i=l).x!==d.x||i.y!==d.y||i.w!==d.w||i.h!==d.h)&&(l=d,r.update(e.id,{...d,max:!1}))};document.body.style.cursor="n"===t||"s"===t?"ns-resize":"e"===t||"w"===t?"ew-resize":"ne"===t||"sw"===t?"nesw-resize":"nwse-resize",window.addEventListener("pointermove",h),window.addEventListener("pointerup",m),window.addEventListener("pointercancel",m),window.addEventListener("blur",m),f.current=p},[r,e.id,e.x,e.y,e.w,e.h,e.type,i.zoom]),_=(0,a.useCallback)((t,n)=>{let a=t.getBoundingClientRect();r.startConnect(e.id,{clientX:"clientX"in n?n.clientX:a.left+a.width/2,clientY:"clientY"in n?n.clientY:a.top+a.height/2,preventDefault:()=>n.preventDefault(),stopPropagation:()=>n.stopPropagation()})},[r,e.id]),U=(0,a.useCallback)(e=>{B(e)&&(e.preventDefault(),e.stopPropagation(),_(e.currentTarget,e))},[_]),W=(0,a.useCallback)(t=>{if("Enter"===t.key||" "===t.key||"Spacebar"===t.key){if("valid"===l)return void r.confirmConnect(e.id,{preventDefault:()=>t.preventDefault(),stopPropagation:()=>t.stopPropagation()});t.preventDefault(),t.stopPropagation(),_(t.currentTarget,t)}},[_,l,r,e.id]),V=(0,a.useCallback)(()=>{r.close(e.id),requestAnimationFrame(()=>{let e=document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab");e?.focus({preventScroll:!0})})},[r,e.id]),H=(0,a.useCallback)(()=>{r.minimize(e.id),requestAnimationFrame(()=>{let e=document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab");e?.focus({preventScroll:!0})})},[r,e.id]),G="full"===D?L(e.type,e.cfg):null,J="full"===D&&A>=340,X="tiny"===D?{}:{zoom:g},Q={left:e.x,top:e.y,width:e.w,height:e.h,zIndex:e.z};return(0,n.jsxs)("section",{className:"window","aria-label":null!==G?`${c.title} — ${G}`:c.title,"aria-roledescription":"window","data-top":t?"true":"false","data-max":e.max?"true":"false","data-conn":l??void 0,"data-dragging":p?"true":void 0,"data-window-id":e.id,style:Q,tabIndex:-1,onPointerDown:t=>{"valid"===l&&r.confirmConnect(e.id,t),O(t.target)},onFocusCapture:()=>{t||window.setTimeout(()=>r.focus(e.id),0)},children:[(0,n.jsxs)("header",{className:"win-head",onPointerDown:z,onDoubleClick:t=>{(function(e){let t=e.target;if(t instanceof Element&&null!==t.closest("button,[role='button']"))return!1;let n=e.currentTarget.getBoundingClientRect(),a=Math.min(210,n.width/2);return e.clientX<n.right-a})(t)&&r.maximize(e.id)},children:[(0,n.jsx)("span",{className:"win-ico",style:{color:!0===c.accent?"var(--accent)":"var(--fg-muted)"},children:(0,n.jsx)(u,{size:14})}),(0,n.jsx)("span",{className:"win-title",children:c.title}),null!==G?(0,n.jsx)("span",{className:"win-sub mono",title:G,children:(0,n.jsx)("span",{className:"win-sub-text",children:G})}):null,(0,n.jsx)("span",{className:"spacer"}),J?(0,n.jsxs)("div",{className:"win-zoom",children:[(0,n.jsx)("button",{type:"button",className:"win-zbtn ui-tip","data-tip":"Zoom content out","aria-label":`Zoom ${c.title} content out`,disabled:g<=.5,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>F(g-.1),children:(0,n.jsx)(j.Icons.zoomOut,{size:13})}),(0,n.jsxs)("button",{type:"button",className:"win-zpct ui-tip","data-tip":"Reset content zoom to 100%","aria-label":`${String(Math.round(100*g))}% — reset ${c.title} content zoom`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>r.update(e.id,{zoom:1}),children:[Math.round(100*g),"%"]}),(0,n.jsx)("button",{type:"button",className:"win-zbtn ui-tip","data-tip":"Zoom content in","aria-label":`Zoom ${c.title} content in`,disabled:g>=2,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>F(g+.1),children:(0,n.jsx)(j.Icons.zoomIn,{size:13})})]}):null,(0,n.jsxs)("div",{className:"win-traffic",role:"group","aria-label":`${c.title} window controls`,children:[(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-minimize ui-tip","data-tip":"Minimize","aria-label":`Minimize ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:H,children:(0,n.jsx)(j.Icons.minimize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-maximize ui-tip","data-tip":e.max?"Restore":"Full screen","aria-label":e.max?`Restore ${c.title} window`:`Full screen ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>r.maximize(e.id),children:e.max?(0,n.jsx)(j.Icons.restore,{size:17}):(0,n.jsx)(j.Icons.maximize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-close ui-tip","data-tip":"Close","aria-label":`Close ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:V,children:(0,n.jsx)(j.Icons.close,{size:17})})]})]}),(0,n.jsx)("div",{ref:h,className:"win-body","data-mode":D,style:X,children:q}),e.max?null:eC.map(e=>(0,n.jsx)("div",{className:`wz wz-${e}`,onPointerDown:K(e)},e)),!e.max&&d?eI.map(e=>(0,n.jsx)("button",{type:"button",className:`win-port wp-${e}`,title:"Click to connect to another window","aria-label":`Connect ${c.title} from ${"t"===e?"top":"r"===e?"right":"b"===e?"bottom":"left"} edge`,onPointerDown:U,onKeyDown:W},`p${e}`)):null]})}let e$=[/\bsk-[A-Za-z0-9_-]{20,}\b/,/\bAKIA[0-9A-Z]{16}\b/,/\bgh[pousr]_[A-Za-z0-9]{36,}\b/,/\bxox[abporsu]-[A-Za-z0-9-]{10,}\b/,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/-----BEGIN [A-Z ]*PRIVATE KEY-----/],eA=/\b(?:\d[ -]?){13,19}\b/g;e.i(47167);let eT={chat:{lifecycle:["draft","streaming","final","archived"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"durable.ui"},chatHistory:{lifecycle:["live","archived"],trustBoundary:["ui"],authority:"user-confirm",persistence:"durable.ui"},memoria:{lifecycle:["live","needs-review","archived"],trustBoundary:["ui","memory"],authority:"user-confirm",persistence:"memory-reference"},files:{lifecycle:["connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},connector:{lifecycle:["connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},localKnowledge:{lifecycle:["idle","connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs","model"],authority:"user-confirm",persistence:"durable.ui"},editor:{lifecycle:["viewing","editing","unsaved","saved","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},browser:{lifecycle:["idle","live","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"transient"},terminal:{lifecycle:["idle","running","blocked","cancelled","error"],trustBoundary:["ui","tool"],authority:"user-confirm",persistence:"transient"},review:{lifecycle:["proposed","needs-review","applied","reverted","archived"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},agents:{lifecycle:["proposed","running","blocked","needs-review","verified","cancelled"],trustBoundary:["ui","model","tool","evidence"],authority:"user-confirm",persistence:"durable.ui"},integ:{lifecycle:["idle","connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"durable.config"},keiko:{lifecycle:["live"],trustBoundary:["ui","memory"],authority:"user",persistence:"memory-reference"},settings:{lifecycle:["viewing","editing","saved"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},project:{lifecycle:["none","connecting","connected","disconnected"],trustBoundary:["ui","fs"],authority:"user",persistence:"durable.config"},search:{lifecycle:["idle","searching","results","error"],trustBoundary:["ui","fs"],authority:"read-only",persistence:"transient"},plugins:{lifecycle:["idle","installed","disabled","enabled"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},automations:{lifecycle:["idle","enabled","disabled"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},mobile:{lifecycle:["paired","unpaired","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"durable.config"},inspector:{lifecycle:["empty","focused"],trustBoundary:["ui"],authority:"ui-only",persistence:"transient"},activity:{lifecycle:["live","archived"],trustBoundary:["ui"],authority:"read-only",persistence:"transient"},notifications:{lifecycle:["unread","read","dismissed"],trustBoundary:["ui"],authority:"ui-only",persistence:"transient"},resources:{lifecycle:["live"],trustBoundary:["ui"],authority:"read-only",persistence:"transient"},quality:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"evidence-reference"},promptEnhancer:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"transient"},qiRun:{lifecycle:["running","final","needs-review","verified","failed","cancelled"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"evidence-reference"},relationships:{lifecycle:["idle","live","degraded","blocked","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"durable.ui"},figma:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","evidence","network"],authority:"user-confirm",persistence:"evidence-reference"},figmaView:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},figmaJson:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},figmaImage:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence","model"],authority:"user-confirm",persistence:"evidence-reference"}},eL=["apikey","accesskey","clientsecret","credential","password","privatekey","secret","token"],eP=["api_key=","apikey=","client_secret=","clientsecret=","credential=","authorization:","password=","secret=","token="],eM=[".env",".env.local",".env.development",".env.test",".env.production"],eD={chat:["chatId"],editor:["openFiles","layoutJson"],files:["activeFilePath","activeDirectoryPath","resolvedRoot"],figma:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaView:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaJson:["snapshotRunId","screenId","selectedScreenIdsJson","selectedScreenName"],figmaImage:["snapshotRunId","screenId","selectedScreenName","imageSrc"]};function eq(e){return"number"==typeof e&&Number.isFinite(e)}function eF(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eO(e){let t=e.trim();if(0===t.length)return!1;let n=t.toLowerCase();return function(e){for(let t of e$)if(t.test(e))return!0;for(let t of e.matchAll(eA)){let e=t[0].replaceAll(/[ -]/g,"");if(e.length>=13&&e.length<=19&&function(e){let t=0,n=!1;for(let a=e.length-1;a>=0;a-=1){let l=Number(e[a]);n&&(l*=2)>9&&(l-=9),t+=l,n=!n}return t%10==0}(e))return!0}return!1}(t)||function(e){let t="bearer ",n=e.toLowerCase().indexOf(t);if(-1===n)return!1;let a=0;for(let l=n+t.length;l<e.length&&0!==(e[l]??"").trim().length;l+=1)a+=1;return a>=8}(t)||function(e){if(!e.includes("://"))return!1;try{let t=new URL(e);return t.username.length>0||t.password.length>0}catch{return!1}}(t)||eP.some(e=>n.includes(e))||function(e){let t=e.toLowerCase().replaceAll("\\","/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e]??"",a=t[e+1]??"";if(eM.includes(n)||".npmrc"===n||"credentials.json"===n||".aws"===n&&"credentials"===a||".ssh"===n&&a.startsWith("id_"))return!0}return!1}(t)}function ez(e){if(0===e.length||e.length>256||e.startsWith(".")||e.trim()!==e||eO(e))return!1;for(let t of e)if(!function(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||46===t||95===t||45===t}(t))return!1;return!0}function eK(e){if(0===e.length||e.length>256||e.trim()!==e||eO(e))return!1;for(let t of e){let e=t.charCodeAt(0),n=e>=48&&e<=57,a=e>=65&&e<=90,l=e>=97&&e<=122,i=46===e||58===e||95===e||45===e;if(!n&&!a&&!l&&!i)return!1}return!0}function eB(e){if(!Array.isArray(e)||0===e.length)return;let t=[];for(let n of e){if("string"!=typeof n)return;let e=n.trim().replace(/\\/gu,"/").replace(/^\/+/u,"");if(!(0===e.length||e.length>512||eO(e)||t.includes(e))&&(t.push(e),t.length>=64))break}return t.length>0?t:void 0}function e_(e){let t=[];for(let n of e){let e=function(e){var t;if(!eF(e)||!("string"==typeof(t=e.type)&&t in E))return null;let n=e.type;if("transient"===eT[n].persistence||"string"!=typeof e.id||!eq(e.x)||!eq(e.y)||!eq(e.w)||!eq(e.h)||!eq(e.z)||"boolean"!=typeof e.max)return null;let a={id:e.id,type:n,x:e.x,y:e.y,w:e.w,h:e.h,z:e.z,cfg:function(e,t){if(!eF(t)||"durable.config"===eT[e].persistence)return{};let n=new Set([...(E[e].config??[]).map(e=>e.key),...eD[e]??[]]),a={};for(let[l,i]of Object.entries(t)){if(!n.has(l))continue;let t=function(e,t,n){let a;if("editor"===e&&"openFiles"===t)return eB(n);if("editor"===e&&"layoutJson"===t)return function(e){let t;if("string"!=typeof e||0===e.length)return;try{t=JSON.parse(e)}catch{return}if("object"!=typeof t||null===t||Array.isArray(t))return;let n=t;if(2===n.schemaVersion||2===n.version){let e=eF(n.panes)?n.panes:{},t={};for(let[n,a]of Object.entries(e)){if(!eF(a))continue;let e="string"==typeof a.activeFile?a.activeFile.trim():"",l=eB(a.openFiles),i=eB(a.tabOrder)??l;if(void 0===l&&0===e.length)continue;let r=l??eB([e]);void 0!==r&&(t[n.slice(0,48)]={id:n.slice(0,48),activeFile:e.length>0?e.replace(/\\/gu,"/").replace(/^\/+/u,""):r[0],openFiles:r,tabOrder:i??r})}let a=new Set(Object.keys(t)),l=e=>{if(!eF(e))return null;if("pane"===e.type&&"string"==typeof e.paneId&&a.has(e.paneId))return{type:"pane",paneId:e.paneId};if("split"===e.type){let t=l(e.first),n=l(e.second);if(null===t||null===n)return null;let a="number"==typeof e.ratio&&Number.isFinite(e.ratio)?Math.min(85,Math.max(15,Math.round(e.ratio))):50;return{type:"split",id:"string"==typeof e.id?e.id.slice(0,48):"split-1",direction:"column"===e.direction?"column":"row",ratio:a,first:t,second:n}}return null},i=l(n.tree),r=Object.keys(t)[0];if(null===i||void 0===r)return;let s="string"==typeof n.activePaneId&&a.has(n.activePaneId)?n.activePaneId:r,o="number"==typeof n.sidebarWidth&&Number.isFinite(n.sidebarWidth)?Math.min(440,Math.max(180,Math.round(n.sidebarWidth))):260;return JSON.stringify({schemaVersion:2,root:"string"==typeof n.root?n.root:"",activePaneId:s,tree:i,panes:t,sidebarWidth:o,sidebarCollapsed:!0===n.sidebarCollapsed})}let a=Array.isArray(n.panes)?n.panes.slice(0,2):[],l=[];for(let[e,t]of a.entries()){if("object"!=typeof t||null===t||Array.isArray(t))return;let n="string"==typeof t.file?t.file.trim():"",a=eB(t.openFiles);if(n.length>512||eO(n))continue;let i=a??(n.length>0?eB([n]):void 0);void 0!==i&&l.push({id:"string"==typeof t.id&&t.id.trim().length>0?t.id.trim().slice(0,32):`pane-${e+1}`,file:n.length>0?n.replace(/\\/gu,"/").replace(/^\/+/u,""):i[0],openFiles:i})}if(0===l.length)return;let i="column"===n.direction?"column":"row",r="number"==typeof n.splitRatio&&Number.isFinite(n.splitRatio)?Math.min(75,Math.max(25,Math.round(n.splitRatio))):50,s="number"==typeof n.sidebarWidth&&Number.isFinite(n.sidebarWidth)?Math.min(440,Math.max(180,Math.round(n.sidebarWidth))):260,o="string"==typeof n.activePaneId&&l.some(e=>e.id===n.activePaneId)?n.activePaneId:l[0].id;return JSON.stringify({version:1,panes:l,activePaneId:o,direction:i,splitRatio:r,sidebarWidth:s,sidebarCollapsed:!0===n.sidebarCollapsed})}(n);if("figma"===e||"figmaView"===e||"figmaJson"===e||"figmaImage"===e)return function(e,t){if("string"==typeof t){if("snapshotRunId"===e)return ez(t)?t:void 0;if("screenId"===e)return eK(t)?t:void 0;if("imageSrc"===e)return/^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(t)?t:void 0;if("selectedScreenIdsJson"===e){let e;try{e=JSON.parse(t)}catch{return}if(!Array.isArray(e)||0===e.length||e.length>16)return;let n=[];for(let t of e){if("string"!=typeof t)return;let e=t.trim();if(!eK(e))return;n.push(e)}return JSON.stringify(n)}if("selectedScreenName"===e){if(t.length>256||eO(t))return;return t}}}(t,n);if("string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||(a=function(e){let t="";for(let n of e.toLowerCase())(n>="a"&&n<="z"||n>="0"&&n<="9")&&(t+=n);return t}(t),eL.some(e=>a.includes(e))))return;if("string"!=typeof n)return n;let l=eT[e].persistence;return"evidence-reference"===l?ez(n)?n:void 0:eO(n)?"durable.ui"===l?"[REDACTED]":void 0:n}(e,l,i);void 0!==t&&(a[l]=t)}return a}(n,e.cfg),max:e.max},l=function(e){if(eF(e)&&eq(e.x)&&eq(e.y)&&eq(e.w)&&eq(e.h))return{x:e.x,y:e.y,w:e.w,h:e.h}}(e.prev);return{...a,...!0===e.minimized?{minimized:!0}:{},...void 0!==l?{prev:l}:{},...eq(e.zoom)?{zoom:e.zoom}:{}}}(n);null!==e&&t.push("figma"!==e.type||void 0===function(e){let t=e.selectedScreenIdsJson;if("string"==typeof t)try{let e=JSON.parse(t);if(!Array.isArray(e))return;let n=e[0];return"string"==typeof n&&n.length>0?n:void 0}catch{return}}(e.cfg)?e:{...e,type:"figmaView",cfg:{...e.cfg}})}let n=t.filter(e=>"figma"===e.type);if(n.length<=1)return t;let a=n.reduce((e,t)=>t.z>e.z?t:e);return t.filter(e=>"figma"!==e.type||e.id===a.id)}function eU(e,t){let n=new Set(t.map(e=>e.id)),a=[];for(let t of e){if("string"!=typeof t.id||"string"!=typeof t.a||"string"!=typeof t.b||!n.has(t.a)||!n.has(t.b))continue;let e="string"==typeof t.boundRoot&&t.boundRoot.length>0,l="workspace-root"===t.boundScopeKind||"directory"===t.boundScopeKind||"files"===t.boundScopeKind,i="string"==typeof t.boundRelativePath&&t.boundRelativePath.length>0,r="string"==typeof t.boundChatWindowId&&t.boundChatWindowId.length>0&&n.has(t.boundChatWindowId),s=("capsule"===t.boundConnectorKind||"capsule-set"===t.boundConnectorKind)&&"string"==typeof t.boundConnectorId&&t.boundConnectorId.length>0;a.push({id:t.id,a:t.a,b:t.b,...r?{boundChatWindowId:t.boundChatWindowId}:{},...e?{boundRoot:t.boundRoot}:{},...l?{boundScopeKind:t.boundScopeKind}:{},...i?{boundRelativePath:t.boundRelativePath}:{},...s?{boundConnectorKind:t.boundConnectorKind,boundConnectorId:t.boundConnectorId}:{}})}return a}function eW(e,t,n,a,l){return{x:e.x+Math.max(16,Math.min(l+26*a,e.w-t-16)),y:e.y+Math.max(16,Math.min(l+26*a,e.h-n-16))}}function eV(e){let{prev:t,...n}=e;return n}function eH(e,t,n){return e.some(e=>e.a===t&&e.b===n||e.a===n&&e.b===t)}function eY(e,t){return e?.type==="chat"?e.id:t?.type==="chat"?t.id:null}function eG(e){return e.length>0&&(e.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(e))}function eJ(e){return/^[A-Za-z]:[/\\]?$/u.test(e)?e.replace(/\\/gu,"/"):e.replace(/\\/gu,"/").replace(/\/+$/u,"")}function eX(e){if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,a="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;return null!==a&&eG(a)?a:null}function eQ(e){return e.replace(/\\/gu,"/").replace(/^\/+/u,"").replace(/\/+$/u,"")}function eZ(e,t){return void 0!==e.root&&void 0!==t.root&&eJ(e.root)===eJ(t.root)&&e.kind===t.kind&&e.relativePaths.length===t.relativePaths.length&&e.relativePaths.every((e,n)=>eQ(e)===eQ(t.relativePaths[n]??""))}function e0(e,t,n){let a="files"===e.type?e:"files"===t.type?t:null,l="chat"===e.type?e:"chat"===t.type?t:null;if(null===a||null===l)return null;let i=eX(a);if(null===i)return null;let r=a.cfg.activeFilePath;if("string"==typeof r&&r.length>0)return{kind:"files",relativePaths:[eQ(r)],root:eJ(i),connectedAtMs:n};let s=a.cfg.activeDirectoryPath;return"string"==typeof s&&s.length>0?{kind:"directory",relativePaths:[eQ(s)],root:eJ(i),connectedAtMs:n}:{kind:"workspace-root",relativePaths:[],root:eJ(i),connectedAtMs:n}}function e1(e){if("string"!=typeof e.boundRoot||0===e.boundRoot.length)return null;let t=Date.now();return"directory"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"directory",relativePaths:[eQ(e.boundRelativePath)],root:eJ(e.boundRoot),connectedAtMs:t}:"files"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"files",relativePaths:[eQ(e.boundRelativePath)],root:eJ(e.boundRoot),connectedAtMs:t}:{kind:"workspace-root",relativePaths:[],root:eJ(e.boundRoot),connectedAtMs:t}}function e2(e){return Math.max(e.maxConnectedSources,e.maxLocalKnowledgeSources)}function e4(e,t){return e.filter(e=>!eZ(e,t))}function e3(e){return e.connectedScopes??(void 0!==e.connectedScope?[e.connectedScope]:[])}function e6(e){return e.localKnowledgeScopes??(void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[])}function e5(e){return"capsule"===e.kind?`capsule:${e.capsuleId}`:`set:${e.capsuleSetId}`}function e8(e){return"string"!=typeof e.boundConnectorId||0===e.boundConnectorId.length?null:"capsule"===e.boundConnectorKind?{kind:"capsule",capsuleId:e.boundConnectorId,connectedAtMs:0}:"capsule-set"===e.boundConnectorKind?{kind:"capsule-set",capsuleSetId:e.boundConnectorId,connectedAtMs:0}:null}function e7(e,t){let n="connector"===e.type?e:"connector"===t.type?t:null,a="chat"===e.type?e:"chat"===t.type?t:null;if(null===n||null===a)return null;let l=n.cfg.selectedKind,i=n.cfg.selectedId;if("string"!=typeof l||"string"!=typeof i)return null;let r=i.trim();return 0===r.length?null:"capsule"===l?{kind:"capsule",capsuleId:r,connectedAtMs:Date.now()}:"capsule-set"===l?{kind:"capsule-set",capsuleSetId:r,connectedAtMs:Date.now()}:null}let e9="keiko.workspace.v4",te="keiko.conns.v1",tt="keiko.view";function tn(){try{let e=window.localStorage.getItem(tt);if(null===e)return{zoom:1,x:0,y:0};let t=JSON.parse(e);if("object"==typeof t&&null!==t&&"zoom"in t&&"number"==typeof t.zoom)return{zoom:t.zoom,x:"number"==typeof t.x?t.x:0,y:"number"==typeof t.y?t.y:0}}catch{}return{zoom:1,x:0,y:0}}function ta(e){return Math.max(.3,Math.min(2.5,e))}function tl(e){return Math.max(.5,Math.min(2,Math.round(10*e)/10))}function ti(e){let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}function tr(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function ts(e){let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:2===e.deltaMode?800:1;return{x:e.deltaX*t,y:e.deltaY*t}}let to={Equal:"=",NumpadAdd:"+",Minus:"-",NumpadSubtract:"-",Digit0:"0",Numpad0:"0"},tc="application/x-keiko-local-knowledge-connector",td="keiko:local-knowledge-connector-drop";function tu(e){if(!Array.from(e.types).includes(tc))return null;try{let t=JSON.parse(e.getData(tc));if("object"!=typeof t||null===t||"capsule"!==t.kind||"string"!=typeof t.id||0===t.id.trim().length)return null;let n="string"==typeof t.label?t.label.trim():"",a="string"==typeof t.lifecycleState?t.lifecycleState.trim():"";return{kind:"capsule",id:t.id.trim(),...n.length>0?{label:n}:{},...a.length>0?{lifecycleState:a}:{}}}catch{return null}}let tp="application/x-keiko-figma-view",tm="keiko:figma-view-drop";function th(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tf(e){if(!Array.from(e.types).includes(tp))return null;try{let t=JSON.parse(e.getData(tp));if("object"!=typeof t||null===t)return null;let n=th(t.snapshotRunId),a=th(t.screenId),l=th(t.name);if(null===n||null===a||null===l)return null;return{snapshotRunId:n,screenId:a,name:l}}catch{return null}}let tg="application/x-keiko-figma-json",tv="keiko:figma-json-drop";function tb(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tx(e){if(!Array.from(e.types).includes(tg))return null;try{let t=JSON.parse(e.getData(tg));if("object"!=typeof t||null===t)return null;let n=tb(t.snapshotRunId),a=tb(t.screenId),l=tb(t.name);if(null===n||null===a||null===l)return null;let i=tb(t.sourceWindowId);return{snapshotRunId:n,screenId:a,name:l,...null!==i?{sourceWindowId:i}:{}}}catch{return null}}let ty="application/x-keiko-figma-image",tw="keiko:figma-image-drop";function tj(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tk(e){if(!Array.from(e.types).includes(ty))return null;try{let t=JSON.parse(e.getData(ty));if("object"!=typeof t||null===t)return null;let n=tj(t.snapshotRunId),a=tj(t.screenId),l=tj(t.name),i=tj(t.imageSrc);if(null===n||null===a||null===l||null===i||!/^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(i))return null;let r=tj(t.sourceWindowId);return{snapshotRunId:n,screenId:a,name:l,imageSrc:i,...null!==r?{sourceWindowId:r}:{}}}catch{return null}}let tN={w:260,h:220},tS={w:360,h:360},tC={w:520,h:540},tI={w:560,h:420};function tE({clientX:e,clientY:t,rect:n,view:a,size:l=tN}){return{x:Math.round((e-n.left-a.x)/a.zoom-l.w/2),y:Math.round((t-n.top-a.y)/a.zoom-28)}}function tR(e,t){let n=e+t;return e<1&&n>1||e>1&&n<1?1:n}function t$(e,t,n){t.preventDefault();let a=t.currentTarget;a.setPointerCapture?.(t.pointerId);let l=t.clientX,i=t.clientY,r=Y();n(!0);let s=t=>{e(t.clientX-l,t.clientY-i),l=t.clientX,i=t.clientY},o=()=>{window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),n(!1),a.hasPointerCapture?.(t.pointerId)===!0&&a.releasePointerCapture?.(t.pointerId),r()};window.addEventListener("pointermove",s),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o)}function tA({wins:e,connecting:t,conns:l}){let[i,r]=(0,a.useState)(""),s=(0,a.useRef)(null),o=(0,a.useRef)(l.length);return(0,a.useEffect)(()=>{let n=s.current;s.current=t;let a=o.current;if(o.current=l.length,null===n&&null!==t){let n=e?.find(e=>e.id===t.from),a=void 0!==n?E[n.type].title:"window";r(`Connecting from ${a} — select a highlighted window, press Escape to cancel`);return}if(null!==n&&null===t)if(l.length>a){let t=l[l.length-1],n=void 0!==t?e?.find(e=>e.id===t.a):void 0,a=void 0!==t?e?.find(e=>e.id===t.b):void 0;r(void 0!==n&&void 0!==a?`Connected: ${A(n,a)}`:"Connected")}else r("Connection cancelled")},[t,l,e]),(0,n.jsx)("div",{className:"sr-only","aria-live":"polite",children:i})}function tT({ws:e,wsRef:t,openPalette:l,palette:i}){let{wins:r,view:s,snapPrev:o,conns:c,connecting:d,api:u}=e,[p,m]=(0,a.useState)(!1),[h,f]=(0,a.useState)(!1),g=(0,a.useRef)(!1),v=(0,a.useMemo)(()=>null===r?null:r.filter(e=>!0!==e.minimized),[r]),b=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}(v),x=null!==d&&null!==v?v.find(e=>e.id===d.from)??null:null;(0,a.useEffect)(()=>{let e=e=>{g.current=e,f(e)},t=t=>{var n;!("Space"!==t.code||(n=t.target)instanceof Element&&null!==n.closest("input,textarea,select,button,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='dialog'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab']"))&&(t.preventDefault(),g.current||e(!0))},n=t=>{"Space"===t.code&&e(!1)},a=()=>{e(!1)};return window.addEventListener("keydown",t),window.addEventListener("keyup",n),window.addEventListener("blur",a),()=>{window.removeEventListener("keydown",t),window.removeEventListener("keyup",n),window.removeEventListener("blur",a)}},[]);let y=(0,a.useMemo)(()=>({backgroundSize:`${String(22*s.zoom)}px ${String(22*s.zoom)}px`,backgroundPosition:`${String(s.x)}px ${String(s.y)}px`}),[s]),w=(0,a.useMemo)(()=>({transform:`translate(${String(s.x/s.zoom)}px, ${String(s.y/s.zoom)}px)`,transformOrigin:"0 0",zoom:s.zoom}),[s]),k=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("connector",{presentation:"node",selectedKind:e.kind,selectedId:e.id,...void 0!==e.label?{selectedLabel:e.label}:{},...void 0!==e.lifecycleState?{selectedState:e.lifecycleState}:{}});null!==l&&u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s}),...tN})},[u,s]),N=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaView",{snapshotRunId:e.snapshotRunId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});null!==l&&u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tS}),...tS})},[u,s]),S=(0,a.useCallback)(e=>{if(null===r)return[];let t=new Map(r.map(e=>[e.id,e])),n=[];for(let a of c){let l=a.a===e?a.b:a.b===e?a.a:null;if(null===l)continue;let i=t.get(l);i?.type==="quality"&&n.push({connId:a.id,qualityId:i.id})}return n},[c,r]),C=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaJson",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});if(null===l||(u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tC}),...tC}),void 0===e.sourceWindowId))return;let i=S(e.sourceWindowId);if(0!==i.length){for(let e of i)u.removeConn(e.connId);window.setTimeout(()=>{for(let e of i)u.connect(l,e.qualityId)},0)}},[u,S,s]),I=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaImage",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenName:e.name,imageSrc:e.imageSrc});if(null===l||(u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tI}),...tI}),void 0===e.sourceWindowId))return;let i=S(e.sourceWindowId);if(0!==i.length){for(let e of i)u.removeConn(e.connId);window.setTimeout(()=>{for(let e of i)u.connect(l,e.qualityId)},0)}},[u,S,s]);(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"capsule"===t.kind&&"string"==typeof t.id}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||k(i,a,l,n)};return window.addEventListener(td,e),()=>{window.removeEventListener(td,e)}},[k,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||N(i,a,l,n)};return window.addEventListener(tm,e),()=>{window.removeEventListener(tm,e)}},[N,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name&&(void 0===t.sourceWindowId||"string"==typeof t.sourceWindowId)}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||C(i,a,l,n)};return window.addEventListener(tv,e),()=>{window.removeEventListener(tv,e)}},[C,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name&&"string"==typeof t.imageSrc&&(void 0===t.sourceWindowId||"string"==typeof t.sourceWindowId)}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||I(i,a,l,n)};return window.addEventListener(tw,e),()=>{window.removeEventListener(tw,e)}},[I,t]);let E=null!==r&&0===r.length,R=r?.some(e=>e.max)??!1;return(0,n.jsxs)("main",{className:"workspace",ref:t,"aria-label":"Workspace surface",tabIndex:0,"data-window-maxed":R?"true":void 0,"data-canvas-overlays-hidden":R?"true":"false","data-connecting":null!==d?"true":void 0,"data-panning":p?"true":void 0,"data-hand-tool":h?"true":void 0,onPointerDownCapture:e=>{var t;if(U())return;if(g.current&&B(e)&&null===d&&!((t=e.target)instanceof Element&&null!==t.closest("input, textarea, select, [contenteditable='true'], [contenteditable='']"))&&!_(e.target)){t$(u.panBy,e,m),e.stopPropagation();return}if(0!==e.button||null===d||null===x||null===v)return;let n=function(e){if(!(e instanceof Element))return;let t=e.closest(".window[data-window-id]");return t?.dataset.windowId}(e.target);if(void 0===n||n===x.id)return;let a=v.find(e=>e.id===n);void 0!==a&&$(x.type,a.type)&&u.confirmConnect(a.id,e)},onPointerDown:e=>{if(!(U()||_(e.target))){var t;if(null!==d){B(e)&&u.cancelConnect();return}(B(t=e)||1===t.button)&&t$(u.panBy,e,m)}},onKeyDown:e=>{if(e.target!==e.currentTarget)return;let t=e.shiftKey?192:48;switch(e.key){case"ArrowLeft":u.panBy(t,0);break;case"ArrowRight":u.panBy(-t,0);break;case"ArrowUp":u.panBy(0,t);break;case"ArrowDown":u.panBy(0,-t);break;default:return}e.preventDefault()},onDragOver:e=>{(null!==tu(e.dataTransfer)||null!==tf(e.dataTransfer)||null!==tx(e.dataTransfer)||null!==tk(e.dataTransfer))&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:e=>{let t=tu(e.dataTransfer),n=tf(e.dataTransfer),a=tx(e.dataTransfer),l=tk(e.dataTransfer);if(null===t&&null===n&&null===a&&null===l)return;e.preventDefault(),e.stopPropagation();let i=e.currentTarget.getBoundingClientRect();null!==t?k(t,e.clientX,e.clientY,i):null!==n?N(n,e.clientX,e.clientY,i):null!==a?C(a,e.clientX,e.clientY,i):null!==l&&I(l,e.clientX,e.clientY,i)},children:[(0,n.jsx)(ew,{}),(0,n.jsx)("div",{className:"ws-grid",style:y,"aria-hidden":"true"}),(0,n.jsx)(tA,{wins:v,connecting:d,conns:c}),null!==d?(0,n.jsx)("div",{className:"ws-connect-hint","aria-hidden":"true",children:"Click a highlighted window to connect — Esc to cancel"}):null,E?(0,n.jsx)("div",{className:"ws-empty",children:(0,n.jsx)(K,{onNewWindow:l})}):null,(0,n.jsxs)("div",{className:"ws-scene",style:w,children:[null!==o?(0,n.jsx)("div",{className:"snap-ghost",style:{left:o.x,top:o.y,width:o.w,height:o.h}}):null,null!==v?(0,n.jsx)(eS,{wins:v,conns:c,connecting:d,api:u}):null,null!==v?v.map(e=>(0,n.jsx)(eR,{win:e,top:null!==b&&e.id===b.id,connState:null===x?null:e.id===x.id?"source":$(x.type,e.type)?"valid":"invalid",view:s,api:u,wsRef:t},e.id)):null]}),(0,n.jsxs)("div",{className:"ws-zoom",children:[(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-start",onClick:()=>u.zoomTo(tR(s.zoom,-.2)),disabled:s.zoom<=.3,"aria-label":"Zoom out","data-tip":"Zoom out",children:(0,n.jsx)(j.Icons.zoomOut,{size:15})}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-start",onClick:u.fitView,disabled:null===v||0===v.length,"aria-label":"Fit workspace to windows","data-tip":"Fit workspace to windows",children:(0,n.jsx)(j.Icons.expand,{size:15})}),(0,n.jsxs)("button",{type:"button",className:"ws-zoom-pct mono ui-tip",onClick:u.resetView,"aria-label":`${String(Math.round(100*s.zoom))}% — reset`,"data-tip":"Reset",children:[Math.round(100*s.zoom),"%"]}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-end",onClick:()=>u.zoomTo(tR(s.zoom,.2)),disabled:s.zoom>=2.5,"aria-label":"Zoom in","data-tip":"Zoom in",children:(0,n.jsx)(j.Icons.zoomIn,{size:15})})]}),(0,n.jsx)("button",{type:"button",className:"ws-fab ui-tip cmp-tip-end",onPointerDown:e=>e.stopPropagation(),onClick:l,"aria-label":"New window","data-tip":"New window",children:(0,n.jsx)(j.Icons.add,{size:20})}),R?null:i??null]})}function tL({commands:e,onClose:t}){let[l,i]=(0,a.useState)(""),[r,s]=(0,a.useState)(0),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(null);(0,a.useEffect)(()=>(c.current=document.activeElement,()=>{c.current?.focus?.()}),[]),(0,a.useEffect)(()=>{o.current?.focus()},[]);let u=(0,a.useMemo)(()=>{let t=l.toLowerCase();return e.filter(e=>`${e.label} ${e.group??""}`.toLowerCase().includes(t))},[e,l]);(0,a.useEffect)(()=>{s(0)},[l]),(0,a.useEffect)(()=>{document.getElementById(`cmdk-row-${String(r)}`)?.scrollIntoView?.({block:"nearest"})},[r,u]);let p=e=>{void 0!==e&&(e.run(),t())};return(0,n.jsx)("div",{className:"cmdk-overlay",onPointerDown:t,children:(0,n.jsxs)("div",{ref:d,className:"cmdk",role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title","aria-describedby":"cmdk-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Tab"===e.key){let t=Array.from(d.current?.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])")??[]);if(t.length>0){let n=t[0],a=t[t.length-1];if(e.shiftKey&&document.activeElement===n){e.preventDefault(),a.focus();return}if(!e.shiftKey&&document.activeElement===a){e.preventDefault(),n.focus();return}}}if("ArrowDown"===e.key){e.preventDefault(),s(e=>Math.min(u.length-1,e+1));return}if("ArrowUp"===e.key){e.preventDefault(),s(e=>Math.max(0,e-1));return}if("Enter"===e.key){e.preventDefault(),p(u[r]);return}"Escape"===e.key&&t()},children:[(0,n.jsx)("h2",{id:"cmdk-title",className:"sr-only",children:"Command palette"}),(0,n.jsx)("p",{id:"cmdk-desc",className:"sr-only",children:"Search commands and press Enter to run the selected action."}),(0,n.jsxs)("div",{className:"cmdk-input",children:[(0,n.jsx)(j.Icons.search,{size:16}),(0,n.jsx)("input",{ref:o,role:"combobox","aria-expanded":"true","aria-controls":"cmdk-list","aria-activedescendant":u.length>0?`cmdk-row-${String(r)}`:void 0,"aria-label":"Command query",placeholder:"Type a command…",value:l,onChange:e=>i(e.target.value)}),(0,n.jsx)("span",{className:"kbd",children:"esc"})]}),(0,n.jsx)("div",{className:"sr-only",role:"status",children:0===u.length?"No matching commands":`${String(u.length)} command${1===u.length?"":"s"}`}),(0,n.jsxs)("div",{id:"cmdk-list",role:"listbox",className:"cmdk-list",children:[0===u.length&&(0,n.jsx)("div",{className:"cmdk-empty",children:"No matching commands"}),u.map((e,t)=>{var a;let l;return(0,n.jsxs)("div",{role:"option",id:`cmdk-row-${String(t)}`,"aria-selected":t===r,className:"cmdk-row","data-sel":t===r,tabIndex:-1,onMouseEnter:()=>s(t),onClick:()=>p(e),children:[(0,n.jsx)("span",{className:"cmdk-ico",children:(a=e.icon,l=j.Icons[a]??j.Icons.spark,(0,n.jsx)(l,{size:16}))}),(0,n.jsx)("span",{className:"cmdk-label",children:e.label}),(0,n.jsx)("span",{className:"spacer"}),void 0!==e.shortcut&&(0,n.jsx)("span",{className:"kbd",children:e.shortcut}),void 0!==e.group&&(0,n.jsx)("span",{className:"cmdk-group mono",children:e.group})]},e.id)})]})]})})}var tP=e.i(74080);function tM(e){return Array.from(new Set(e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)))}function tD({onCancel:e,preserveExisting:t=!1,storedApiKeyHeaderName:l,storedModels:i=[]}){let r=(0,a.useRef)(null),s=(0,a.useRef)(null),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(void 0),[u,p]=(0,a.useState)(""),[m,h]=(0,a.useState)(""),[f,g]=(0,a.useState)(""),[v,b]=(0,a.useState)(""),[x,y]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)(""),[I,E]=(0,a.useState)(!1),[R,$]=(0,a.useState)(),[A,T]=(0,a.useState)(),[L,P]=(0,a.useState)();async function M(e){if(e.preventDefault(),!I){var n;E(!0),$(void 0),T(void 0),P(void 0),r.current?.focus();try{let e,a=tM(x);if(function(e){try{return new URL(e.trim()).hostname.endsWith(".services.ai.azure.com")}catch{return!1}}(u)&&0===a.length){$("Azure AI Foundry requires deployment names. Paste the names from the Deployments tab."),E(!1);return}try{e=function(e){let t=e.trim();if(""===t)return;let n=Number(t);if(!Number.isInteger(n)||n<=0)throw Error("Request timeout must be a positive integer in milliseconds.");return n}(v)}catch(e){$(e instanceof Error?e.message:"Request timeout is invalid."),E(!1);return}let l=tM(k),i=!t||""!==u.trim()||""!==m.trim()||""!==f.trim()||a.length>0||l.length>0,r=i||void 0!==e,s=""!==S.trim(),o=await (0,w.setupGateway)({baseUrl:""===u.trim()?void 0:u.trim(),apiKey:""===m.trim()?void 0:m.trim(),apiKeyHeaderName:""===f.trim()?void 0:f.trim(),...void 0===e?{}:{timeoutMs:e},deploymentNames:a,preserveExisting:t,...0===l.length?{}:{imageInputModelIds:l},...""===S.trim()?{}:{figmaAccessToken:S.trim()}}),c=o.testedModelIds.length,p=(n=o.skippedModelIds??[],0===n.length?"":` Could not verify deployment${1===n.length?"":"s"}: ${n.join(", ")}.`);E(!1),s&&!r?P("Verified Figma access token. Reloading Keiko…"):s&&!i?P("Updated model gateway settings and verified Figma access token. Reloading Keiko…"):s||i?s?P(`Verified ${String(c)} workflow chat model${1===c?"":"s"} and Figma access token. Reloading Keiko…${p}`):P(`Verified ${String(c)} workflow chat model${1===c?"":"s"}. Reloading Keiko…${p}`):P("Updated model gateway settings. Reloading Keiko…"),d.current=window.setTimeout(()=>window.location.reload(),0===(o.skippedModelIds??[]).length?800:1800)}catch(t){let e=t instanceof w.ApiError?{message:t.message,code:t.code}:t instanceof Error?{message:t.message}:{message:"The gateway could not be configured."};$(e.message),T(e.code),E(!1)}}}(0,a.useEffect)(()=>{let e=document.documentElement,n=Number(e.dataset.keikoModalOpenCount??"0");e.dataset.keikoModalOpenCount=String(n+1),e.setAttribute("data-keiko-modal-open","true");let a=Number(e.dataset.keikoGatewaySetupOpenCount??"0");return e.dataset.keikoGatewaySetupOpenCount=String(a+1),e.setAttribute("data-keiko-gateway-setup-open","true"),c.current=document.activeElement,t?o.current?.focus():s.current?.focus(),()=>{void 0!==d.current&&window.clearTimeout(d.current);let t=Math.max(0,Number(e.dataset.keikoModalOpenCount??"1")-1);0===t?(delete e.dataset.keikoModalOpenCount,e.removeAttribute("data-keiko-modal-open")):e.dataset.keikoModalOpenCount=String(t);let n=Math.max(0,Number(e.dataset.keikoGatewaySetupOpenCount??"1")-1);0===n?(delete e.dataset.keikoGatewaySetupOpenCount,e.removeAttribute("data-keiko-gateway-setup-open")):e.dataset.keikoGatewaySetupOpenCount=String(n),c.current?.focus?.()}},[t]),(0,a.useEffect)(()=>{let t=r.current;if(null===t)return;let n=n=>{if("Escape"===n.key){if(I||void 0!==L||void 0===e)return;n.preventDefault(),e();return}if("Tab"!==n.key)return;let a=Array.from(t.querySelectorAll("button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),summary,[tabindex]:not([tabindex='-1'])"));if(0===a.length)return;let l=a[0],i=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),i.focus()):n.shiftKey||document.activeElement!==i||(n.preventDefault(),l.focus())};return t.addEventListener("keydown",n),()=>t.removeEventListener("keydown",n)},[I,e,L]),(0,a.useEffect)(()=>{void 0===R||I||(t&&""===u.trim()&&""===m.trim()?o.current?.focus():s.current?.focus())},[m,u,I,R,t]);let D=tM(x),q=tM(k),F=!t,O=""!==u.trim()||""!==m.trim()||""!==f.trim()||""!==v.trim()||D.length>0||q.length>0,z=""!==S.trim(),K=!I&&void 0===L&&(F?""!==u.trim()&&""!==m.trim():O||z),B=i.map(e=>e.id),_=B.slice(0,6),U=Math.max(0,B.length-_.length),W=(0,n.jsxs)("div",{className:"gw-grid",children:[(0,n.jsxs)("label",{className:"gw-field gw-span-2",children:[(0,n.jsxs)("span",{children:["Base URL ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",value:u,placeholder:t?"Only enter a value to replace the stored gateway URL":"https://llm-gateway.example.com/v1",autoComplete:"off",disabled:I||void 0!==L,ref:s,onChange:e=>p(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API token ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:m,placeholder:t?"Only enter a value to replace the stored token":"Paste your API token",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>h(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API key header ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",value:f,placeholder:t?"Leave blank to keep stored header":"Authorization",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>g(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Request timeout (ms) ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",inputMode:"numeric",value:v,placeholder:t?"Leave blank to keep stored timeout":"30000",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>b(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsx)("span",{children:"Deployment names for Azure"}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:x,placeholder:"Paste deployment names, one per line",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>y(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Image-input models ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:k,placeholder:"Paste image-capable model names, one per line",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>N(e.target.value)})]})]}),V=(0,n.jsx)("div",{className:"gw-setup-backdrop",role:"presentation",children:(0,n.jsx)("div",{ref:r,className:"gw-setup",role:"dialog","aria-modal":"true","aria-labelledby":"gw-setup-title","aria-describedby":"gw-setup-desc",tabIndex:-1,children:(0,n.jsxs)("form",{className:"gw-form",onSubmit:e=>void M(e),children:[(0,n.jsxs)("div",{className:"gw-head",children:[(0,n.jsxs)("div",{className:"gw-setup-badge",children:[(0,n.jsx)(j.Icons.cube,{size:18}),t?"Credential update":"Model gateway setup"]}),(0,n.jsx)("h1",{id:"gw-setup-title",children:t?"Update Keiko credentials":"Connect Keiko to your internal LLMs"}),(0,n.jsx)("p",{id:"gw-setup-desc",children:t?"Leave stored gateway fields blank to keep the current value. Keiko never returns existing secrets to the browser.":"Keiko needs the internal gateway URL and API token before chat and agent workflows can run. The token is tested once and stored only on this machine."})]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-model-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-model-section-title",children:"Model gateway"}),(0,n.jsx)("p",{children:t?"Blank gateway fields keep the stored value.":"Base URL and API token are required."})]})}),t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"gw-current","aria-label":"Stored model gateway credentials",children:[(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"Gateway URL"}),(0,n.jsx)("strong",{children:"Stored"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API token"}),(0,n.jsx)("strong",{className:"mono",children:"••••••••••••"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API key header"}),(0,n.jsx)("strong",{className:"mono",children:l??"authorization"})]}),(0,n.jsxs)("div",{className:"gw-current-models",children:[(0,n.jsx)("span",{children:"Configured models"}),(0,n.jsxs)("div",{className:"gw-model-chips",children:[0===_.length?(0,n.jsx)("strong",{children:"Stored"}):_.map(e=>(0,n.jsx)("strong",{className:"mono",children:e},e)),U>0?(0,n.jsxs)("strong",{children:["+",U.toString()]}):null]})]})]}),(0,n.jsxs)("details",{className:"gw-replace",children:[(0,n.jsx)("summary",{children:"Replace model gateway settings"}),W]})]}):W]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-figma-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-figma-section-title",children:"Figma Snapshot"}),(0,n.jsx)("p",{children:"Optional connector credential."})]})}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Figma access token ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:S,placeholder:t?"Stored Figma token is kept when blank":"Paste a read-only Figma PAT when needed",autoComplete:"off",disabled:I||void 0!==L,ref:o,onChange:e=>C(e.target.value)})]})]}),(0,n.jsx)("div",{className:"gw-note",children:"Stored secrets stay local and are never returned to the browser. Supported API-key headers: Authorization, X-Litellm-Key, X-Api-Key, api-key."}),void 0!==R?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[R,void 0!==A?(0,n.jsx)("div",{className:"gw-error-code mono",children:A}):null]}):null,void 0!==L?(0,n.jsx)("div",{className:"gw-success",role:"status",children:L}):null,I?(0,n.jsx)("div",{className:"gw-pending",role:"status",children:"Testing credentials…"}):null,(0,n.jsx)("span",{id:"gw-submit-requirements",className:"visually-hidden",children:t?"Enter at least one field to update. Blank stored gateway fields keep their current value.":"Base URL and API token are required. The Figma access token is optional."}),(0,n.jsxs)("div",{className:"gw-actions",children:[void 0!==e?(0,n.jsx)("button",{className:"gw-cancel",type:"button",disabled:I||void 0!==L,onClick:e,children:"Cancel"}):null,(0,n.jsx)("button",{className:"gw-submit",type:"submit",disabled:!K,"aria-busy":I,"aria-describedby":"gw-submit-requirements",children:I?"Testing credentials…":"Test & save"})]})]})})});return"u"<typeof document?V:(0,tP.createPortal)(V,document.body)}function tq(e){return e.findIndex(e=>!0!==e.disabled)}function tF(e,t,n){if(0===e.length)return -1;let a=t;for(let t=0;t<e.length;t+=1)if(a=(a+n+e.length)%e.length,e[a]?.disabled!==!0)return a;return -1}function tO({active:e,index:t,onCommit:l,onOptionKeyDown:i,option:r,setOptionRef:s}){let o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(null),[u,p]=(0,a.useState)(null),m=()=>{null!==d.current&&(clearTimeout(d.current),d.current=null),p(null)},h=()=>{null!==d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{let e=c.current,t=o.current;if(null===e||null===t||e.scrollWidth<=e.clientWidth)return;let n=t.getBoundingClientRect(),a=Math.min(520,window.innerWidth-32),l=n.right+8+a<=window.innerWidth-16?"top-left":"top-right";p({left:"top-left"===l?n.right+8:n.left-8,placement:l,top:n.top-6})},1500)};return(0,a.useEffect)(()=>m,[]),(0,n.jsxs)("button",{ref:e=>{o.current=e,s(t,e)},"aria-selected":e,className:`ksel-option${e?" ksel-option-active":""}`,"data-disabled":!0===r.disabled?"true":void 0,disabled:r.disabled,onBlur:m,onClick:()=>l(r),onFocus:h,onKeyDown:e=>i(e,t),onPointerEnter:h,onPointerLeave:m,role:"option",type:"button",children:[(0,n.jsxs)("span",{className:"ksel-option-copy",children:[(0,n.jsx)("span",{className:"ksel-option-label",ref:c,children:r.label}),void 0!==r.description?(0,n.jsx)("span",{className:"ksel-option-desc",children:r.description}):null]}),void 0!==r.badge?(0,n.jsx)("span",{className:"ksel-option-badge",children:r.badge}):null,null!==u?(0,tP.createPortal)((0,n.jsx)("div",{className:"ksel-overflow-tooltip","data-placement":u.placement,role:"tooltip",style:{left:`${u.left.toString()}px`,top:`${u.top.toString()}px`},children:r.label}),document.body):null]})}function tz({value:e,sections:t,onValueChange:l,disabled:i=!1,placeholder:r="Select an option",ariaLabel:s,ariaDescribedBy:o,ariaLabelledBy:c,triggerClassName:d,menuClassName:u,menuTitle:p,menuCountLabel:m,showMenuHeader:h=!0,leadingVisual:f,mono:g=!1,showChevron:v=!0,menuMinWidth:b,attached:x=!0,triggerStyle:y,autoFocus:w=!1}){let j=(0,a.useRef)(null),k=(0,a.useRef)(null),N=(0,a.useRef)([]),S=(0,a.useId)(),[C,I]=(0,a.useState)(!1),[E,R]=(0,a.useState)(-1),[$,A]=(0,a.useState)(null),[T,L]=(0,a.useState)(!1),P=(0,a.useMemo)(()=>t.flatMap((e,t)=>e.options.map((n,a)=>({...n,key:`${e.label??"section"}-${t.toString()}-${n.value}-${a.toString()}`,sectionLabel:e.label}))),[t]),M=P.findIndex(t=>t.value===e),D=-1===M?null:P[M],q=D?.label??r,F=D?.description??null,O=()=>{I(!1),R(-1)},z=e=>{if(i||0===P.length)return;let t=void 0!==e&&P[e]?.disabled!==!0?e:M>=0&&P[M]?.disabled!==!0?M:tq(P);I(!0),R(t)};function K(e){e.disabled||(l(e.value),O(),j.current?.focus())}function B(e,t){if("Escape"===e.key){e.preventDefault(),O(),j.current?.focus();return}if("Tab"===e.key)return void O();if("ArrowDown"===e.key){e.preventDefault(),R(tF(P,t,1));return}if("ArrowUp"===e.key){e.preventDefault(),R(tF(P,t,-1));return}if("Home"===e.key){e.preventDefault(),R(tq(P));return}if("End"===e.key){e.preventDefault(),R(tF(P,0,-1));return}if("Enter"===e.key||" "===e.key){e.preventDefault();let n=P[t];void 0!==n&&K(n)}}(0,a.useEffect)(()=>{if(!C)return;let e=e=>{let t=e.target;null!==j.current&&t instanceof Node&&j.current.contains(t)||null!==k.current&&t instanceof Node&&k.current.contains(t)||O()},t=()=>O();return window.addEventListener("pointerdown",e,!0),window.addEventListener("blur",t),()=>{window.removeEventListener("pointerdown",e,!0),window.removeEventListener("blur",t)}},[C]),(0,a.useLayoutEffect)(()=>{if(!C||null===j.current)return;let e=()=>{let e=j.current?.getBoundingClientRect();if(void 0===e)return;let t=Math.min(void 0!==b&&e.width<Math.min(b,96)?b:e.width,window.innerWidth-32),n=x&&1>Math.abs(t-e.width),a=n?-1:6,l=window.innerHeight-e.bottom-16,i=e.top-16,r=l<Math.max(96,2*e.height)&&i>l;L(r);let s=r?i:l,o=50*!!h+2,c=Math.max(e.height,Math.min(Math.max(e.height,s-o),380)),d=c+o,u=window.getComputedStyle(j.current);A({left:Math.min(Math.max(16,e.left),window.innerWidth-t-16),width:t,top:r?Math.max(16,e.top-d-a):Math.min(e.bottom+a,window.innerHeight-16-d),optionHeight:Math.max(28,Math.min(e.height,30)),maxHeight:c,openUp:r,attached:n,fontFamily:u.fontFamily,fontSize:u.fontSize,fontWeight:u.fontWeight,letterSpacing:u.letterSpacing,lineHeight:u.lineHeight})};return e(),window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0)}},[C,x,b,h]),(0,a.useLayoutEffect)(()=>{if(!C||null===$||!$.openUp||null===j.current||null===k.current)return;let e=j.current.getBoundingClientRect(),t=k.current.getBoundingClientRect();if(t.height<=0)return;let n=$.attached?-1:6,a=Math.max(16,e.top-t.height-n);.5>Math.abs(a-$.top)||A(e=>null===e?e:{...e,top:a})},[C,$]),(0,a.useEffect)(()=>{C&&!(E<0)&&(N.current[E]?.focus(),N.current[E]?.scrollIntoView({block:"nearest"}))},[C,E]),(0,a.useEffect)(()=>{if(!C)return;let e=e=>{if("Escape"===e.key){O(),j.current?.focus();return}if(1===e.key.length&&!e.metaKey&&!e.ctrlKey&&!e.altKey){var t;if((t=e.target)instanceof HTMLElement&&("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName||t.isContentEditable))return;let n=e.key.toLowerCase(),a=E>=0?E:M>=0?M:0;for(let e=1;e<=P.length;e+=1){let t=(a+e)%P.length,l=P[t];if(void 0!==l&&!0!==l.disabled&&l.label.toLowerCase().startsWith(n)){R(t);break}}}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[C,E,P,M]);let _=["ksel-trigger",g?"mono":"",d??"",C?"ksel-trigger-open":"",C&&$?.attached===!0?T?"ksel-trigger-open-up":"ksel-trigger-open-down":"",i?"ksel-trigger-disabled":""].filter(e=>e.length>0).join(" "),U=C&&null!==$?(0,tP.createPortal)((0,n.jsxs)("div",{ref:k,className:["ksel-menu",$.attached?"ksel-menu-attached":"",$.openUp?"ksel-menu-open-up":"ksel-menu-open-down",u??""].filter(e=>e.length>0).join(" "),style:{left:`${$.left.toString()}px`,top:`${$.top.toString()}px`,width:`${$.width.toString()}px`,"--ksel-option-height":`${$.optionHeight.toString()}px`,fontFamily:$.fontFamily,fontSize:$.fontSize,fontWeight:$.fontWeight,letterSpacing:$.letterSpacing,lineHeight:$.lineHeight},children:[h?(0,n.jsxs)("div",{className:"ksel-menu-head",children:[(0,n.jsx)("div",{className:"ksel-menu-title",children:p??s??r}),(0,n.jsx)("div",{className:"ksel-menu-note",children:m??`${P.length.toString()} options`})]}):null,(0,n.jsx)("div",{className:"ksel-menu-scroll",role:"listbox",id:S,style:{maxHeight:`${$.maxHeight.toString()}px`},children:t.map((e,t)=>(0,n.jsxs)("div",{className:"ksel-section",children:[void 0!==e.label?(0,n.jsx)("div",{className:"ksel-section-label",children:e.label}):null,e.options.map(t=>{let a=P.findIndex(n=>n.value===t.value&&n.sectionLabel===e.label),l=a===M,i=P[a];return void 0===i?null:(0,n.jsx)(tO,{active:l,index:a,onCommit:K,onOptionKeyDown:B,option:i,setOptionRef:(e,t)=>{N.current[e]=t}},`${e.label??"section"}-${t.value}`)})]},`${e.label??"section"}-${t.toString()}`))})]}),document.body):null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:j,"aria-controls":S,"aria-describedby":o,"aria-expanded":C,"aria-haspopup":"listbox","aria-label":s,"aria-labelledby":c,autoFocus:w,className:_,disabled:i,onClick:()=>{C?O():z()},onKeyDown:function(e){if(!i){if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault(),z(M>=0?M:tq(P));return}("Enter"===e.key||" "===e.key)&&(e.preventDefault(),C?O():z())}},role:"combobox",style:y,type:"button",children:[void 0!==f?(0,n.jsx)("span",{className:"ksel-trigger-leading",children:f}):null,(0,n.jsxs)("span",{className:"ksel-trigger-copy",children:[(0,n.jsx)("span",{className:"ksel-trigger-label",children:q}),null!==F?(0,n.jsx)("span",{className:"ksel-trigger-desc",children:F}):null]}),v?(0,n.jsx)("span",{"aria-hidden":"true",className:`ksel-trigger-caret${C?" ksel-trigger-caret-open":""}`,children:(0,n.jsx)("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",children:(0,n.jsx)("path",{d:"M2.25 4.5 6 8.25 9.75 4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}):null]}),U]})}let tK=[["ask","Ask every action"],["full","Full access"]];function tB({cfg:e,set:t}){let a=!1!==e.keikoMode,l="full"===e.access?"full":"ask",i=a?"No rights by default. You approve while manual; Keiko governs per policy when autonomous.":"full"===l?"Legacy: agent acts without prompts.":"Legacy: you approve each privileged action.";return(0,n.jsxs)("div",{className:"permctl",children:[(0,n.jsxs)("button",{type:"button",className:"perm-toggle","data-on":a,"aria-pressed":a,onClick:()=>t("keikoMode",!a),children:[(0,n.jsx)("img",{className:"perm-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsxs)("span",{className:"perm-tt",children:[(0,n.jsx)("span",{className:"perm-name",children:"Keiko-Mode"}),(0,n.jsx)("span",{className:"perm-desc",children:"Zero standing rights · Keiko governs"})]}),(0,n.jsx)("span",{className:"perm-sw"+(a?" on":""),children:(0,n.jsx)("span",{})})]}),!a&&(0,n.jsx)("div",{className:"perm-legacy",children:tK.map(([e,a])=>(0,n.jsx)("button",{type:"button",className:"perm-opt","data-on":l===e,"aria-pressed":l===e,onClick:()=>t("access",e),children:a},e))}),(0,n.jsx)("div",{className:"perm-note",children:i})]})}function t_(e){return"chat"===e.kind&&e.toolCalling&&e.structuredOutput}function tU(e){if(e instanceof w.ApiError){if("BAD_ROOT"===e.code)return"Enter an absolute folder path.";if("DENIED"===e.code)return"That location is excluded."}return e instanceof Error?e.message:"Unable to read directories."}function tW({value:e,projectId:t,selectProjectRoot:l=!1,onSelect:i,onClose:r}){let[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(e),[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(null),f=t??e.trim(),g=(0,a.useCallback)(async e=>{if(0===f.length){o(null),h("Enter an absolute folder path.");return}p(!0),h(null);try{let t=await (0,w.fetchFilesDirectories)(f,e);o(t),d(t.path)}catch(e){h(tU(e))}finally{p(!1)}},[f]);return(0,a.useEffect)(()=>{g(e.length>0?e:void 0)},[]),(0,n.jsxs)("div",{className:"dir-picker",role:"group","aria-label":"Directory picker",children:[(0,n.jsxs)("div",{className:"dir-top",children:[(0,n.jsx)("input",{className:"dlg-input mono dir-path",value:c,"aria-label":"Folder path",placeholder:"/absolute/folder/path",onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),g(c))}}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dir-go",onClick:()=>void g(c),children:"Go"})]}),null!==s?(0,n.jsx)("div",{className:"dir-roots",children:s.roots.map(e=>(0,n.jsx)("button",{type:"button",className:"dir-chip",onClick:()=>void g(e.path),children:e.label},`${e.label}:${e.path}`))}):null,(0,n.jsxs)("div",{className:"dir-list",children:[s?.parent!==null&&s?.parent!==void 0?(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(s.parent??void 0),children:[(0,n.jsx)(j.Icons.back,{size:14}),(0,n.jsx)("span",{children:"Parent directory"})]}):null,s?.entries.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(e.path),children:[(0,n.jsx)(j.Icons.folder,{size:14}),(0,n.jsx)("span",{children:e.name})]},e.path)),u?(0,n.jsx)("div",{className:"dir-note",role:"status",children:"Loading directories…"}):null,u||null===s||0!==s.entries.length?null:(0,n.jsx)("div",{className:"dir-note",children:"No child directories."}),null!==m?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:m}):null]}),(0,n.jsxs)("div",{className:"dir-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:r,children:"Close"}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{null!==s&&(i(l?s.roots[0]?.path??s.path:s.path),r())},disabled:null===s,children:"Use directory"})]})]})}let tV=[{id:"unit-test-generation",label:"Unit Test Agent",scope:"Source file"},{id:"bug-investigation",label:"Bugfix Agent",scope:"Bug report"}];function tH(e){return e.filter(e=>e.available).map(e=>e.path)}function tY(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)}function tG(e){let t=tJ(e.trim()).replace(/\/+$/u,""),n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function tJ(e){return e.replaceAll("\\","/")}function tX(e,t){let n=tJ(t.trim());if(0===n.length)return"";let a=tJ(e.trim()).replace(/\/+$/u,"");if(0===a.length)return n;if(n===a)return".";let l=`${a}/`;return n.startsWith(l)?n.slice(l.length):n}function tQ({root:e,value:t,onSelect:l,onClose:i}){let r=tX(e,t),[s,o]=(0,a.useState)(tG(r)),[c,d]=(0,a.useState)(r),[u,p]=(0,a.useState)([]),[m,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(0===e.trim().length){p([]),h(!1),g(!1),b("Select a repository first.");return}let t=!1;return g(!0),b(null),(0,w.fetchFilesTree)(e.trim(),s).then(e=>{t||(p(e.entries),h(e.truncated))}).catch(e=>{t||(p([]),h(!1),b(tU(e)))}).finally(()=>{t||g(!1)}),()=>{t=!0}},[s,e]);let x=u.filter(e=>"directory"===e.kind),y=u.filter(e=>"directory"!==e.kind);return(0,n.jsxs)("div",{className:"file-picker",role:"group","aria-label":"File picker",children:[(0,n.jsx)("div",{className:"file-picker-head",children:(0,n.jsx)("span",{className:"file-picker-path mono",children:0===s.length?"Repository root":s})}),(0,n.jsxs)("div",{className:"dir-list file-picker-list",children:[s.length>0?(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>o(tG(s)),children:[(0,n.jsx)(j.Icons.back,{size:14}),(0,n.jsx)("span",{children:"Parent folder"})]}):null,x.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row file-picker-row",disabled:!e.readable,onClick:()=>o(e.path),title:e.path,children:[(0,n.jsx)(j.Icons.folder,{size:14}),(0,n.jsx)("span",{children:e.name})]},e.path)),y.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row file-picker-row","data-selected":c===e.path?"true":void 0,disabled:!e.readable,"aria-pressed":c===e.path,onClick:()=>d(e.path),title:e.path,children:[(0,n.jsx)(j.Icons.file,{size:14}),(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"file-picker-meta mono",children:function(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}(e.sizeBytes)})]},e.path)),f?(0,n.jsx)("div",{className:"dir-note",role:"status",children:"Loading files…"}):null,f||null!==v||0!==u.length?null:(0,n.jsx)("div",{className:"dir-note",children:"No files in this folder."}),m?(0,n.jsxs)("div",{className:"dir-note file-picker-warning",role:"status",children:["Showing only the first ",u.length.toString()," entries."]}):null,null!==v?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:v}):null]}),(0,n.jsxs)("div",{className:"dir-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:i,children:"Close"}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{0!==c.trim().length&&(l(tX(e,c)),i())},disabled:0===c.trim().length,children:"Use file"})]})]})}function tZ({filesContext:e,firstRef:t,directoryField:l,setDirectoryField:i,setDialogError:r,onConfirm:s}){let[o,c]=(0,a.useState)("unit-test-generation"),[d,u]=(0,a.useState)(e?.root??""),[p,m]=(0,a.useState)(""),[h,f]=(0,a.useState)([]),[g,v]=(0,a.useState)([]),[b,x]=(0,a.useState)(()=>{var t,n;let a;return t=e?.root??"",{verifyTargetFiles:a=null===(n=e?.activeFilePath??null)?"":tX(t,n),explainFilePath:a,explainQuestion:"",unitFilePath:a,bugDescription:"",bugFailingOutput:"",bugStackTrace:"",bugTargetFiles:a}}),[y,k]=(0,a.useState)(!0),[N,S]=(0,a.useState)(!1),[C,I]=(0,a.useState)(!1),E=d.trim(),R=null!==e&&e.root===E&&void 0!==e.activeFilePath?e.activeFilePath:null,$=E.length>0&&g.includes(E),A=0===E.length?"Repository is required.":0===p.length?"No compatible model is available.":"explain-plan"===o&&0===b.explainFilePath.trim().length?"Explain plan requires a file path.":"unit-test-generation"===o&&0===b.unitFilePath.trim().length?"Unit Test Agent requires a source file.":"bug-investigation"===o&&0===b.bugDescription.trim().length?"Bugfix Agent requires an observed behavior.":null,T=null===A&&$&&!C&&!y,L=tV.find(e=>e.id===o)??tV[0],P="unit-test-generation"===o?"Start Unit Test Agent":"Start Bugfix Agent";(0,a.useEffect)(()=>{let e=!1;return k(!0),r(null),Promise.all([(0,w.fetchModels)(),(0,w.fetchProjects)()]).then(([t,n])=>{if(e)return;let a=t.models.filter(t_);f(a),m(e=>e||(a[0]?.id??"")),v(tH(n.projects))}).catch(t=>{e||r(tU(t))}).finally(()=>{e||k(!1)}),()=>{e=!0}},[r]);let M=e=>{x(t=>({...t,...e}))};(0,a.useEffect)(()=>{if(null===R)return;let e=tX(E,R);x(t=>{let n={};return 0===t.verifyTargetFiles.trim().length&&(n.verifyTargetFiles=e),0===t.explainFilePath.trim().length&&(n.explainFilePath=e),0===t.unitFilePath.trim().length&&(n.unitFilePath=e),0===t.bugTargetFiles.trim().length&&(n.bugTargetFiles=e),0===Object.keys(n).length?t:{...t,...n}})},[R,E]);let D=async()=>{v(tH((await (0,w.fetchProjects)()).projects))},q=async()=>{if(0!==E.length){S(!0),r(null);try{await (0,w.createProject)({path:E}),await D()}catch(e){r(tU(e))}finally{S(!1)}}},F=async()=>{if(!T)return void r(A??"Repository is not registered.");I(!0),r(null);let t=function(e,t,n,a){if("verify"===e){let e=tY(a.verifyTargetFiles).map(e=>tX(t,e));return{taskType:"verify",modelId:n,input:{workspaceRoot:t,...e.length>0?{targetFiles:e}:{}}}}return"explain-plan"===e?{taskType:"explain-plan",modelId:n,input:{workspaceRoot:t,filePath:tX(t,a.explainFilePath),...a.explainQuestion.trim().length>0?{question:a.explainQuestion.trim()}:{}}}:"unit-test-generation"===e?{workflowId:"unit-test-generation",modelId:n,input:{workspaceRoot:t,target:{kind:"file",filePath:tX(t,a.unitFilePath)}}}:{workflowId:"bug-investigation",modelId:n,input:{workspaceRoot:t,report:{...a.bugDescription.trim().length>0?{description:a.bugDescription.trim()}:{},...a.bugFailingOutput.trim().length>0?{failingOutput:a.bugFailingOutput.trim()}:{},...a.bugStackTrace.trim().length>0?{stackTrace:a.bugStackTrace.trim()}:{},...tY(a.bugTargetFiles).length>0?{targetFiles:tY(a.bugTargetFiles).map(e=>tX(t,e))}:{}}}}}(o,E,p,b);try{let n=await (0,w.startRun)(t);s({workflow:o,model:p,runId:n.runId,fingerprint:n.fingerprint,workspaceRoot:E,inputJson:JSON.stringify(t.input),...null!==e&&e.root===E?{__connectFilesId:e.id}:{}})}catch(e){e instanceof w.ApiError&&"WORKSPACE_NOT_REGISTERED"===e.code?(await D().catch(()=>void 0),r("Repository is not registered.")):r(tU(e))}finally{I(!1)}};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"dlg-agent-grid",children:[(0,n.jsxs)("div",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Agent"}),(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input",value:o,ariaLabel:"Agent",autoFocus:!0,menuTitle:"Agent",menuCountLabel:`${tV.length.toString()} agents`,sections:[{options:tV.map(e=>({value:e.id,label:e.label}))}],onValueChange:e=>{let t=tV.find(t=>t.id===e);void 0!==t&&c(t.id)}})})]}),(0,n.jsxs)("div",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Model"}),(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input mono",value:p,ariaLabel:"Model",disabled:0===h.length,menuTitle:"Model",mono:!0,sections:[{options:h.map(e=>({value:e.id,label:e.id}))}],onValueChange:m})})]})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Repository"}),(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{className:"dlg-input mono",value:d,placeholder:"/absolute/repository/path",onClick:()=>i("agentWorkspace"),onChange:e=>u(e.target.value)}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>i("agentWorkspace"),children:"Browse"})]}),"agentWorkspace"===l?(0,n.jsx)(tW,{value:d,projectId:$?E:void 0,onSelect:u,onClose:()=>i(null)}):null]}),E.length>0&&!$?(0,n.jsxs)("div",{className:"dlg-agent-warning",children:[(0,n.jsx)("span",{children:"Repository is not registered."}),(0,n.jsx)("button",{type:"button",className:"dlg-btn",disabled:N,onClick:()=>void q(),children:N?"Registering…":"Register repository"})]}):null,null!==R?(0,n.jsxs)("button",{type:"button",className:"dlg-current-file",onClick:()=>{if(null===R)return;let e=tX(E,R);"unit-test-generation"===o?M({unitFilePath:e}):M({bugTargetFiles:e})},title:R,children:[(0,n.jsx)(j.Icons.files,{size:13})," Use current file ",(0,n.jsx)("span",{className:"mono",children:R})]}):null,(0,n.jsxs)("div",{className:"dlg-agent-task",children:[(0,n.jsxs)("div",{className:"dlg-agent-task-head",children:[(0,n.jsx)("span",{className:"dlg-agent-task-title",children:L.label}),(0,n.jsx)("span",{className:"dlg-agent-task-scope",children:L.scope})]}),"unit-test-generation"===o?(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Source file"}),(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{className:"dlg-input mono",placeholder:"src/file.ts",value:b.unitFilePath,onChange:e=>M({unitFilePath:e.target.value}),onBlur:e=>M({unitFilePath:tX(E,e.target.value)})}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn","aria-label":"Browse source file",onClick:()=>i("unitSourceFile"),children:"Browse"})]}),"unitSourceFile"===l?(0,n.jsx)(tQ,{root:E,value:b.unitFilePath,onSelect:e=>M({unitFilePath:e}),onClose:()=>i(null)}):null]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Observed behavior"}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea",rows:2,placeholder:"Describe the observed bug.",value:b.bugDescription,onChange:e=>M({bugDescription:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Failing output ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:b.bugFailingOutput,onChange:e=>M({bugFailingOutput:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Stack trace ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:b.bugStackTrace,onChange:e=>M({bugStackTrace:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Related files ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,placeholder:"src/file.ts, src/other.ts",value:b.bugTargetFiles,onChange:e=>M({bugTargetFiles:e.target.value}),onBlur:e=>M({bugTargetFiles:tY(e.target.value).map(e=>tX(E,e)).join(", ")})})]})]})]}),(0,n.jsxs)("div",{className:"dlg-agent-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",disabled:!T,"aria-busy":C,"aria-describedby":T||C?void 0:"agent-start-validation",onClick:()=>void F(),children:C?"Starting…":P}),y?(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:"Loading models and projects…"}):null,y||null===A?null:(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:A})]})]})}function t0({type:e,types:t,filesContext:l=null,onConfirm:i,onClose:r}){let s=t[e],o=s.config??[],[c,d]=(0,a.useState)(()=>(function(e){let t={};for(let n of e)t[n.key]=n.def??"";return t})(o)),[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),v=(0,a.useRef)(null),b=(0,a.useRef)(null),x=(0,a.useRef)(null);(0,a.useEffect)(()=>(x.current=document.activeElement,()=>{let e=x.current;null!==e&&e.isConnected?e.focus():requestAnimationFrame(()=>{(document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab")??document.body).focus({preventScroll:!0})})}),[]),(0,a.useEffect)(()=>{let e=requestAnimationFrame(()=>{p(!0),(v.current??b.current)?.focus()});return()=>cancelAnimationFrame(e)},[]),(0,a.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e)}},[r]),(0,a.useEffect)(()=>{if("files"!==e&&"editor"!==e)return;let t=!1,n=c.root;if("string"!=typeof n||!(n.length>0))return h(null),(0,w.fetchProjects)().then(e=>{let n=tH(e.projects)[0];t||void 0===n||d(e=>({...e,root:n}))}).catch(e=>{t||h(tU(e))}),()=>{t=!0}},[c.root,e]);let y=(e,t)=>d(n=>({...n,[e]:t})),k=()=>{"agents"!==e&&i(c)},N=j.Icons[s.icon],S=s.cta??`Open ${s.title}`;return(0,n.jsx)("div",{className:"dlg-overlay"+(u?" in":""),onPointerDown:r,children:(0,n.jsxs)("div",{ref:b,className:"agents"===e?"dlg dlg-agents":"dlg",role:"dialog","aria-modal":"true","aria-labelledby":"new-window-title","aria-describedby":"new-window-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{let t,n;if("Escape"===e.key)return void r();if("Enter"===e.key&&(e.metaKey||e.ctrlKey))return void k();if("Enter"===e.key){let t=e.target instanceof HTMLElement?e.target.tagName:"";("INPUT"===t||"SELECT"===t)&&(e.preventDefault(),k());return}if("Tab"!==e.key)return;let a=(t=e.currentTarget.querySelectorAll("button,input,select,textarea"),n=[],t.forEach(e=>{e.hasAttribute("disabled")||(null!==e.offsetParent||"BUTTON"===e.tagName)&&n.push(e)}),n);if(0===a.length)return;let l=a[0],i=a[a.length-1];e.shiftKey&&document.activeElement===l?(e.preventDefault(),i.focus()):e.shiftKey||document.activeElement!==i||(e.preventDefault(),l.focus())},children:[(0,n.jsxs)("div",{className:"dlg-head",children:[(0,n.jsx)("span",{className:"dlg-ico",children:(0,n.jsx)(N,{size:20})}),(0,n.jsxs)("div",{className:"dlg-htext",children:[(0,n.jsxs)("span",{id:"new-window-title",className:"dlg-title",children:["New ",s.title," window"]}),(0,n.jsx)("span",{id:"new-window-desc",className:"dlg-sub",children:s.desc})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:r,"aria-label":"Cancel",title:"Cancel",children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsxs)("div",{className:"dlg-body",children:["agents"===e?(0,n.jsx)(tZ,{filesContext:l,firstRef:e=>{v.current=e},directoryField:f,setDirectoryField:g,setDialogError:h,onConfirm:i}):0===o.length&&(0,n.jsxs)("div",{className:"dlg-empty",children:["Add a new ",s.title," window to your workspace."]}),"agents"!==e&&o.map((e,t)=>(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:[e.label,!0===e.optional&&(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),function(e,t,a,l,i){if("perm"===e.type)return(0,n.jsx)(tB,{cfg:t,set:a});let r=t[e.key],s="string"==typeof r?r:void 0===r?"":String(r);if("select"===e.type){let t=e.options??[];return(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input mono",value:s,disabled:0===t.length,autoFocus:null!==l,menuTitle:e.label,mono:!0,sections:[{options:t.map(t=>({value:t,label:`${e.prefix??""}${t}`}))}],onValueChange:t=>a(e.key,t)})})}return"textarea"===e.type?(0,n.jsx)("textarea",{ref:l??void 0,className:"dlg-input dlg-textarea",rows:3,placeholder:e.placeholder??"",value:s,onChange:t=>a(e.key,t.target.value)}):"directory"===e.type?(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{ref:l??void 0,className:"dlg-input mono",placeholder:e.placeholder??e.label,value:s,onClick:()=>i(e.key),onChange:t=>a(e.key,t.target.value)}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>i(e.key),children:"Browse"})]}):(0,n.jsx)("input",{ref:l??void 0,className:"dlg-input mono",placeholder:e.placeholder??e.label,value:s,onChange:t=>a(e.key,t.target.value)})}(e,c,y,0===t?e=>{v.current=e}:null,g),"directory"===e.type&&f===e.key?(0,n.jsx)(tW,{value:"string"==typeof c[e.key]?c[e.key]:"",selectProjectRoot:"root"===e.key,onSelect:t=>y(e.key,t),onClose:()=>g(null)}):null]},e.key)),null!==m?(0,n.jsx)("div",{className:"dlg-error",role:"alert",children:m}):null]}),(0,n.jsxs)("div",{className:"dlg-foot",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:r,children:"Cancel"}),"agents"!==e?(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:k,children:S}):null]})]})})}function t1({types:e,order:t,onAdd:l,onClose:i}){let r=t.length<=4?2:3,s=(0,a.useRef)(null),o=(0,a.useRef)(null),[c,d]=(0,a.useState)(0);return(0,a.useEffect)(()=>{o.current=document.activeElement;let e=s.current?.querySelector(".pal-card");return e?.focus(),()=>{let e=document.activeElement;(null===e||e===document.body)&&o.current?.focus?.()}},[]),(0,a.useEffect)(()=>{let e=e=>{null!==s.current&&e.target instanceof Node&&!s.current.contains(e.target)&&i()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[i]),(0,n.jsxs)("div",{ref:s,className:"palette",role:"dialog","aria-labelledby":"palette-title","aria-describedby":"palette-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Escape"===e.key){e.preventDefault(),i();return}if(!(e.target instanceof HTMLElement)||!e.target.classList.contains("pal-card"))return;let t=Array.from(s.current?.querySelectorAll(".pal-card")??[]),n=function(e,t,n,a){let l;if(0===n)return null;if("Home"===e)return 0;if("End"===e)return n-1;if("ArrowRight"===e)l=1;else if("ArrowLeft"===e)l=-1;else if("ArrowDown"===e)l=a;else{if("ArrowUp"!==e)return null;l=-a}return Math.max(0,Math.min(n-1,t+l))}(e.key,t.indexOf(e.target),t.length,r);null!==n&&(e.preventDefault(),d(n),t[n]?.focus())},onBlur:e=>{e.relatedTarget instanceof Node&&s.current?.contains(e.relatedTarget)!==!0&&i()},"data-columns":r,children:[(0,n.jsxs)("div",{className:"palette-head",children:[(0,n.jsx)("span",{className:"palette-badge",children:(0,n.jsx)(j.Icons.add,{size:17})}),(0,n.jsxs)("div",{className:"palette-htext",children:[(0,n.jsx)("span",{id:"palette-title",className:"palette-title",children:"New window"}),(0,n.jsx)("span",{id:"palette-desc",className:"palette-sub",children:"Pick a card to add to your workspace"})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:i,"aria-label":"Close",title:"Close",children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsx)("div",{className:"palette-grid",children:t.map((t,a)=>{let i=e[t],r=j.Icons[i.icon];return(0,n.jsxs)("button",{type:"button",className:"pal-card pal-main",tabIndex:a===c?0:-1,onFocus:()=>d(a),onClick:()=>l(t),children:[(0,n.jsx)("span",{className:"pal-ico",children:(0,n.jsx)(r,{size:18})}),(0,n.jsx)("span",{className:"pal-name",children:i.title}),(0,n.jsx)("span",{className:"pal-desc",children:i.desc}),(0,n.jsx)("span",{className:"pal-add","aria-hidden":"true",children:(0,n.jsx)(j.Icons.plus,{size:15})})]},t)})})]})}async function t2(e){try{let t=await e.json();return{code:t.error.code,message:t.error.message}}catch{return{code:"INTERNAL",message:`HTTP ${e.status.toString()}`}}}async function t4(e,t){let n,a,l=(t?.method??"GET").toUpperCase(),i=t?.body,r=await fetch(e,{...t,headers:(n={Accept:"application/json"},((a="GET"!==l&&"HEAD"!==l)||null!=i)&&(n["Content-Type"]="application/json"),a&&(n["X-Keiko-CSRF"]="1"),n)});if(!r.ok){let{code:e,message:t}=await t2(r);throw new w.ApiError(e,t,r.status)}return r.json()}async function t3(e={},t=t4){let n=new URLSearchParams;void 0!==e.scope&&e.scope.length>0&&n.set("scope",e.scope.join(",")),void 0!==e.type&&e.type.length>0&&n.set("type",e.type.join(",")),void 0!==e.status&&e.status.length>0&&n.set("status",e.status.join(",")),void 0!==e.sensitivity&&e.sensitivity.length>0&&n.set("sensitivity",e.sensitivity.join(",")),void 0!==e.limit&&n.set("limit",e.limit.toString()),void 0!==e.offset&&n.set("offset",e.offset.toString());let a=n.toString();return t(`/api/memory${a.length>0?`?${a}`:""}`)}async function t6(e=t4){return e("/api/memory/review-queue")}async function t5(e,t=t4){return t("/api/memory/consolidation/jobs",{method:"POST",body:JSON.stringify({settings:e})})}async function t8(e,t=t4){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}`)}async function t7(e,t=t4){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST",body:"{}"})}async function t9(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}`)}async function ne(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}async function nt(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}/pin`,{method:"POST",body:"{}"})}async function nn(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}/unpin`,{method:"POST",body:"{}"})}async function na(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/archive`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}async function nl(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/forget`,{method:"POST",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function ni(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function nr(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/correct`,{method:"POST",body:JSON.stringify({body:t})})}async function ns(e,t=t4){return t(`/api/memory/proposals/${encodeURIComponent(e)}/accept`,{method:"POST",body:"{}"})}async function no(e,t,n=t4){return n(`/api/memory/proposals/${encodeURIComponent(e)}/reject`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}let nc=[{workflowId:"unit-test-generation",label:"Generate unit tests",description:"Drafts a reviewable unit-test patch for a target file. Dry-run only from chat — apply from the workflow view.",prompt:"Target file (workspace-relative)",placeholder:"src/example.ts",buildInput:(e,t)=>({workspaceRoot:e,target:{kind:"file",filePath:t.trim()}})},{workflowId:"bug-investigation",label:"Investigate bug",description:"Investigates a reported issue and proposes a root-cause hypothesis. Dry-run only from chat.",prompt:"Describe the bug",placeholder:"The login button does nothing when the form is empty…",buildInput:(e,t)=>({workspaceRoot:e,report:{description:t.trim()}})}];function nd(e){return nc.find(t=>t.workflowId===e)}let nu=new Set(["completed","dry-run","fix-applied","fix-proposed","investigation-only"]);function np(e){return e.length>200?e.slice(0,200):e}function nm(e){if(null!==e&&"object"==typeof e)return e}function nh(){return"Investigation complete; root cause documented."}function nf(e){let t=e.workflowId;return"unit-test-generation"===t||"unit-tests"===t?"unit-tests":"bug-investigation"===t?"bug":"verify"===e.taskType?"verify":"explain-plan"===e.taskType?"explain":"other"}function ng(e){return void 0===e||!Number.isFinite(e)||e<=0?0:Math.floor(e)}function nv(e){return"u">typeof TextEncoder?new TextEncoder().encode(e).length:e.length}function nb(e){let t=ng(e.modelContextWindow),n=ng(e.modelMaxOutputTokens),a=Math.max(0,t-n),l=nv(e.userDraftText),i=function(e){let t=0;for(let n of e)t+=nv(n.role),t+=nv(n.content);return t}(e.conversationHistory),r=function(e){if(void 0===e)return 0;let t=0;for(let n of e)t+=ng(n.extractedBytes);return t}(e.documentContext),s=ng(e.repoContextPackBytes),o=ng(e.knowledgeCapsuleBytes),c=ng(e.memoryContextBytes),d=l+i+r+s+o+c,u=Math.ceil(d/4),p=function(e,t){if(t<=0)return"exceeded";let n=e/t;return n>.95?"exceeded":n>.75?"high":n>.5?"moderate":"low"}(u,a);return{approximateBytes:d,approximateTokens:u,contextWindowTokens:t,reservedOutputTokens:n,availableInputTokens:a,pressure:p,breakdown:{draftBytes:l,historyBytes:i,documentBytes:r,repoContextBytes:s,knowledgeBytes:o,memoryBytes:c}}}function nx(e){return"chat"===e.kind}let ny={embedding:"embedding-only","ocr-vision":"ocr-vision-only"},nw=[/\bsk-[A-Za-z0-9_-]{12,}\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/gi,/\bgho_[A-Za-z0-9_]{12,}\b/g,/\bghp_[A-Za-z0-9_]{12,}\b/g],nj=/\s+\(([A-Z][A-Z0-9_/-]{2,})\)\s*$/;function nk(e){let t=e;for(let e of nw)t=t.replace(e,"[REDACTED]");return t.replace(/\bBearer\s+\[REDACTED\]/gi,"[REDACTED]")}function nN(e,t){return"BAD_REQUEST"===t&&e.toLowerCase().includes("too broad")&&e.toLowerCase().includes("connected")}function nS(e){return"CLARIFICATION_NEEDED"===e}function nC(e,t,n){return"GATEWAY_TIMEOUT"===t&&(0===e.length||e===t)?"The model gateway timed out before the model returned a response.":e.length>0?e:n}function nI(e,t){return nS(t)?"Keiko braucht mehr Kontext":nN(e,t)?"Narrow the connected-source question":"GATEWAY_TIMEOUT"===t?"Model gateway timed out":"PAYLOAD_TOO_LARGE"===t?"Request is too large":"NO_MODEL"===t?"No model is available":void 0!==t?"Request failed":"Something went wrong"}function nE(e,t){return nS(t)?"Nenne eine konkrete Datei, einen Identifier, eine Fehlermeldung oder eine exakte Phrase.":nN(e,t)?"Ask about a specific file, folder, symbol, identifier, or exact phrase. For broad questions over large project folders, narrow the Files scope first.":"GATEWAY_TIMEOUT"===t?"Retry the request. If it repeats, choose a smaller prompt or another configured model, then check the gateway base URL, proxy, and model deployment availability in Settings.":"PAYLOAD_TOO_LARGE"===t?"Reduce the selected scope or remove large attachments before retrying.":void 0}function nR(e,t){if(e instanceof w.ApiError){let n=nC(nk(e.message.trim()),e.code,t);return`${n} (${e.code})`}return e instanceof Error&&e.message.trim().length>0?nk(e.message.trim()):t}let n$="\n…[truncated]",nA=["text/"],nT=new Set(["application/json","application/x-yaml","application/yaml"]),nL=new TextEncoder;function nP(e){return nL.encode(e).length}function nM(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}let nD=`${String(256)} KB`;function nq(e){return`"${e}" won't be sent — the ${nD} attachment limit was already used by earlier files.`}async function nF(e,t){var n,a;let l,i,r,s,o;if(e.remainingAggregate<=0)return nq(nM(t.name));try{l=await t.file.text()}catch{return n=nM(t.name),`Couldn't read "${n}" — it will be skipped. Your message will be sent without it.`}let c=Math.min(65536,Math.max(e.remainingAggregate-nP(n$),0));if(c<=0)return nq(nM(t.name));let{entry:d,consumed:u}=(r=(i=nP(a=l)>c)?function(e,t){if(t<=0)return"";if(nP(e)<=t)return e;let n=0,a="";for(let l of e){let e=n+nP(l);if(e>t)break;n=e,a+=l}return a}(a,c):a,s=nP(r),o=i?nP(n$):0,{entry:{id:t.id,displayName:nM(t.name),mimeType:t.mimeType,sizeBytes:t.sizeBytes,extractedBytes:s,truncated:i,truncationMarker:i?n$:void 0,text:r},consumed:s+o});if(0===d.text.length)return 0===l.length?void 0:nq(nM(t.name));e.entries.push(d),e.remainingAggregate-=u}async function nO(e){let t=e.filter(e=>{var t;return t=e.mimeType,!!nA.some(e=>t.startsWith(e))||nT.has(t)}),n=t.slice(0,16),a={entries:[],remainingAggregate:262144},l=[];for(let e of n){let t=await nF(a,e);void 0!==t&&l.push(t)}for(let e of t.slice(16)){var i;l.push((i=nM(e.name),`"${i}" won't be sent — only the first ${String(16)} documents are included.`))}return{entries:a.entries,failures:l}}let nz=["text/"],nK=new Set(["application/pdf","application/json","application/x-yaml","application/yaml"]),nB="New chat",n_="keiko:chat-upsert",nU="keiko:chat-delete",nW=["completed","failed","cancelled"];function nV(e){return"idle"!==e&&!nW.includes(e)}let nH="The conversation context exceeded the model's window. Clear history or pick a larger-context model.",nY="The model request completed, but the provider did not return any answer text. Retry once; if it happens again, check the selected model deployment in Settings.",nG=new Set(["CONVERSATION_OVERSIZED_CONTEXT","GATEWAY_CONTEXT_OVERFLOW"]),nJ=["context length","context_length_exceeded","max_tokens","too many tokens"],nX=["empty assistant response","empty grounded answer","without assistant content"];function nQ(e){return void 0!==e&&e.contextWindowTokens>0&&"exceeded"===e.pressure}function nZ(e){let t;return function(e){if(e instanceof w.ApiError&&nG.has(e.code))return!0;let t=e instanceof Error?e.message.toLowerCase():"";return 0!==t.length&&nJ.some(e=>t.includes(e))}(e)?nH:0!==(t=e instanceof Error?e.message.toLowerCase():"").length&&nX.some(e=>t.includes(e))?e instanceof w.ApiError?`${nY} (${e.code})`:nY:nR(e,"Something went wrong. Try again.")}function n0(e){return[...e].sort((e,t)=>t.updatedAt-e.updatedAt)}function n1(e){window.dispatchEvent(new CustomEvent(n_,{detail:e}))}function n2(e){return e.find(nx)?.id}function n4(e,t){return void 0!==e&&t.some(t=>t.id===e&&nx(t))?e:n2(t)}function n3(e){return void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0||void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0}let n6={projects:[],chats:[],messages:[],models:[],activeProject:void 0,activeChat:void 0,selectedModel:void 0};function n5(e,t){if(0===t.length)return Array.from(e);let n=new Map(t.map(e=>[e.id,e])),a=e.map(e=>n.get(e.id)??e),l=new Set(e.map(e=>e.id));for(let e of t)l.has(e.id)||a.push(e);return a}async function n8(e){let t=(await (0,w.fetchModels)()).models.filter(nx),n=n2(t),a=[...(await (0,w.fetchProjects)().catch(()=>({projects:[]}))).projects].sort((e,t)=>e.favorite!==t.favorite?e.favorite?-1:1:e.lastOpenedAt!==t.lastOpenedAt?t.lastOpenedAt-e.lastOpenedAt:e.path.localeCompare(t.path)),l=a.find(e=>e.available)??a[0];if(void 0!==l){let e=n0((await (0,w.fetchChats)(l.path).catch(()=>({chats:[]}))).chats),n=e[0];if(void 0!==n){let i=await (0,w.fetchChatMessages)(n.id,l.path),r=n4(n.selectedModel,t);return{models:t,selectedModel:r,projects:Array.from(a),activeProject:l,chats:e,activeChat:n,messages:Array.from(i.messages)}}}if(void 0===n||!e)return{models:t,selectedModel:n,projects:Array.from(a),activeProject:l,chats:[],activeChat:void 0,messages:[]};let i={modelId:n,title:nB};l?.available===!0&&(i.projectPath=l.path);let r=await (0,w.createDesktopChat)(i);return n1(r.chat),{models:t,selectedModel:r.chat.selectedModel,projects:Array.from(r.projects),activeProject:r.project,chats:n0(r.chats),activeChat:r.chat,messages:Array.from(r.messages)}}function n7(e={}){let t=e.autoCreate??!0,[n,l]=(0,a.useState)(n6),[i,r]=(0,a.useState)(""),[s,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)("idle"),u=nV(c),p=(0,a.useRef)("idle"),m=(0,a.useRef)(null),[h,f]=(0,a.useState)(),[g,v]=(0,a.useState)(),[b,x]=(0,a.useState)(),[y,j]=(0,a.useState)(!0),[k,N]=(0,a.useState)(1200),S=(0,a.useRef)(!0),C=(0,a.useRef)(void 0),I=(0,a.useRef)(new Set),E=(0,a.useRef)(0),R=(0,a.useRef)([]),[$,A]=(0,a.useState)([]),[T,L]=(0,a.useState)([]),P=(0,a.useCallback)(async e=>{var t;let a;if(0===e.size)return{ok:!1,reason:"empty"};if(e.size>8388608)return{ok:!1,reason:"oversized"};let l=(t=e.type).startsWith("image/")?"image":nz.some(e=>t.startsWith(e))||nK.has(t)?"document":"unsupported-type";if("unsupported-type"===l)return{ok:!1,reason:"unsupported-type"};let i=n.models.find(e=>e.id===n.selectedModel);if(void 0!==i&&("image"===l&&!i.supportsImageInput||"document"===l&&!i.supportsDocumentInput))return{ok:!1,reason:"text-only-model"};if("image"===l)try{a=await new Promise((t,n)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=()=>n(Error("FileReader error")),a.readAsDataURL(e)})}catch{return{ok:!1,reason:"unsupported-type"}}let r={id:crypto.randomUUID(),kind:l,name:e.name,mimeType:e.type,sizeBytes:e.size,previewDataUrl:a,file:e};return A(e=>[...e,r]),{ok:!0}},[n.models,n.selectedModel]),M=(0,a.useCallback)(e=>{A(t=>t.filter(t=>t.id!==e))},[]),D=(0,a.useCallback)(()=>{A([])},[]),q=(0,a.useCallback)(async()=>{let e=$.filter(e=>"document"===e.kind&&void 0!==e.file).map(e=>({id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,file:e.file}));if(0===e.length)return{entries:[],disclosures:[]};let{entries:t,failures:n}=await nO(e);n.length>0&&f(n.join(" "));let a=t.map(e=>({id:e.id,displayName:e.displayName,truncated:e.truncated}));return{entries:t,disclosures:a}},[$]),F=(0,a.useCallback)(()=>{x(void 0)},[]),O=(0,a.useCallback)((e,t)=>({enabled:y,budgetTokens:k,context:{userId:"local-operator",workspaceId:t.path,projectId:t.path,conversationId:e.id}}),[k,y]),z=(0,a.useCallback)(async e=>{await ns(e),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),K=(0,a.useCallback)(async e=>{await no(e),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),B=(0,a.useCallback)(async e=>{await nl(e,"user-initiated forget from Conversation Center"),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"forget"!==t.kind||t.memoryId!==e)})},[]),_=(0,a.useCallback)(e=>{p.current=e,d(e)},[]),U=(0,a.useCallback)(async(e,t,n,a)=>{let i=n.runId;if(void 0===i)return void I.current.delete(a);let r={...void 0===n.workflowId?{}:{workflowId:n.workflowId},...void 0===n.taskType?{}:{taskType:n.taskType}};try{for(let a=0;a<120;a+=1){let s;if(!S.current||C.current!==e.id)return;try{let e=await (0,w.fetchRunReport)(i),t=function(e,t){let n=nm(e);if(void 0===n)return{kind:"unknown"};let a=function(e){let t=e.status;if("string"==typeof t)return t}(n),l=nf(t);return"running"===a?{kind:"running"}:"cancelled"===a?{kind:"terminal",summary:{workflowStatus:"cancelled",shortResult:"Run cancelled."}}:"failed"===a||"rejected"===a?{kind:"terminal",summary:{workflowStatus:"failed",shortResult:np(function(e){let t,n,a=(t=nm(e.failure),n=t?.message,"string"==typeof n&&n.length>0?n:void 0);return void 0!==a?np(`Run failed: ${a}.`):"Run failed."}(n))}}:void 0!==a&&nu.has(a)?{kind:"terminal",summary:{workflowStatus:"completed",shortResult:np(function(e,t){if("unit-tests"===t)return function(e){let t,n=e.addedTestFiles;if(Array.isArray(n)){let e=0,a=!1;for(let t of n){let n=nm(t),l=n?.estimatedTestCount;"number"==typeof l&&Number.isFinite(l)&&(e+=l,a=!0)}a&&(t=e)}let a=Array.isArray(n)?n.length:0;return a>0&&void 0!==t?`Generated ${String(a)} test files; ${String(t)} tests proposed.`:a>0?`Generated ${String(a)} test files.`:"Completed."}(e);if("bug"===t)return nh();if("verify"===t){let t,n;return t=nm(e.verificationSummary),n=t?.results,Array.isArray(n)&&n.length>0?`Verification passed: ${String(n.length)} classifications.`:"Verification passed."}if("explain"===t){let t=e.dryRunPreview;if("string"==typeof t&&t.length>0){let e=t.split("\n").filter(e=>e.trim().length>0);if(e.length>0)return`Plan generated; ${String(e.length)} steps.`}return"Plan generated."}return"Completed."}(n,l))}}:{kind:"unknown"}}(e.report,r);"terminal"===t.kind&&(s=t.summary)}catch(e){if(!(e instanceof w.ApiError)||404!==e.status)return;try{let e=await (0,w.fetchEvidenceManifest)(i),t=function(e,t){let n=nm(e),a=void 0===n?void 0:nm(n.run),l=void 0===a?void 0:a.outcome,i=nf(t);return"cancelled"===l?{workflowStatus:"cancelled",shortResult:"Run cancelled."}:"failed"===l||"limit-exceeded"===l?{workflowStatus:"failed",shortResult:"Run failed."}:"completed"===l?{workflowStatus:"completed",shortResult:np("bug"===i?nh():"verify"===i?"Verification passed.":"explain"===i?"Plan generated.":"unit-tests"===i?"Generated tests.":"Completed.")}:{workflowStatus:"completed",shortResult:"Completed."}}(e.manifest,r);s={workflowStatus:"failed"===t.workflowStatus||"cancelled"===t.workflowStatus?t.workflowStatus:"completed",shortResult:t.shortResult}}catch{}}if(void 0!==s){let a=await (0,w.patchChatMessage)(n.id,e.id,t,s);if(!S.current||C.current!==e.id)return;l(t=>t.activeChat?.id!==e.id?t:{...t,messages:t.messages.map(e=>e.id===n.id?a.message:e)});return}a<119&&await new Promise(e=>{globalThis.setTimeout(e,1e3)})}}finally{I.current.delete(a)}},[]);(0,a.useEffect)(()=>{C.current=n.activeChat?.id},[n.activeChat?.id]),(0,a.useEffect)(()=>{R.current=n.models},[n.models]),(0,a.useEffect)(()=>{let e=!1;return async function(){o(!0),f(void 0);try{let n=await n8(t);e||l(e=>({...e,...n}))}catch(t){e||f(nZ(t))}finally{e||o(!1)}}(),()=>{e=!0}},[t]),(0,a.useEffect)(()=>{let e=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.id&&"string"==typeof t.projectPath&&"string"==typeof t.title&&"string"==typeof t.selectedModel&&l(e=>({...e,chats:n0([t,...e.chats.filter(e=>e.id!==t.id)]),activeChat:e.activeChat?.id===t.id?t:e.activeChat,selectedModel:e.activeChat?.id===t.id?n4(t.selectedModel,e.models):e.selectedModel}))},t=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.chatId&&l(e=>({...e,chats:e.chats.filter(e=>e.id!==t.chatId),activeChat:e.activeChat?.id===t.chatId?void 0:e.activeChat,messages:e.activeChat?.id===t.chatId?[]:e.messages}))};return window.addEventListener(n_,e),window.addEventListener(nU,t),()=>{window.removeEventListener(n_,e),window.removeEventListener(nU,t)}},[]),(0,a.useEffect)(()=>(S.current=!0,()=>{S.current=!1,m.current?.abort()}),[]),(0,a.useEffect)(()=>{let e=n.activeChat,t=n.activeProject;if(void 0!==e&&void 0!==t)for(let a of n.messages){if("system"!==a.role||"string"!=typeof a.runId||void 0!==a.workflowStatus&&"pending"!==a.workflowStatus&&"running"!==a.workflowStatus)continue;let n=a.runId;if(void 0===n)continue;let l=`${a.id}:${n}`;I.current.has(l)||(I.current.add(l),U(e,t.path,a,l))}},[n.activeChat,n.activeProject,n.messages,U]);let W=(0,a.useCallback)(e=>{let t;f(void 0),l(n=>(t={selectedModel:n.selectedModel,activeChat:n.activeChat,chats:n.chats},{...n,selectedModel:e,activeChat:void 0===n.activeChat?n.activeChat:{...n.activeChat,selectedModel:e},chats:n.chats.map(t=>void 0!==n.activeChat&&t.id===n.activeChat.id?{...t,selectedModel:e}:t)})),A(t=>t.filter(t=>{let n;return void 0===(n=R.current.find(t=>t.id===e))||("image"===t.kind?n.supportsImageInput:n.supportsDocumentInput)}));let n=C.current;if(void 0===n)return;let a=E.current+1;E.current=a,(0,w.updateChat)(n,{selectedModel:e}).then(e=>{E.current!==a||C.current===e.chat.id&&(n1(e.chat),l(t=>({...t,selectedModel:e.chat.selectedModel,activeChat:t.activeChat?.id===e.chat.id?e.chat:t.activeChat,chats:t.chats.map(t=>t.id===e.chat.id?e.chat:t)})))}).catch(e=>{if(E.current===a&&C.current===n&&(f(nZ(e)),void 0!==t)){let e=t;l(t=>({...t,selectedModel:t.activeChat?.id===n?e.selectedModel:t.selectedModel,activeChat:t.activeChat?.id===n?e.activeChat:t.activeChat,chats:t.chats.map(t=>{if(t.id!==n)return t;let a=e.chats.find(e=>e.id===n);return void 0!==a?{...t,selectedModel:a.selectedModel}:t})}))}})},[]),V=(0,a.useCallback)(async(e,t)=>{let a=n4(n.selectedModel,n.models);if(void 0===a)return void f("No conversation-eligible model is configured. Connect a gateway in Settings.");f(void 0);try{let i=t?.trim(),r={modelId:a,title:void 0!==i&&i.length>0?i:nB},s=e?.path??n.activeProject?.path;void 0!==s&&(r.projectPath=s);let o=await (0,w.createDesktopChat)(r);return C.current=o.chat.id,n1(o.chat),l({projects:Array.from(o.projects),chats:n0(o.chats),messages:Array.from(o.messages),models:n.models,activeProject:o.project,activeChat:o.chat,selectedModel:o.chat.selectedModel}),o.chat}catch(e){f(nZ(e));return}},[n.selectedModel,n.activeProject,n.models]),H=(0,a.useCallback)(async e=>{f(void 0),l(t=>({...t,activeProject:e}));try{let t=await (0,w.fetchChats)(e.path),a=n0(t.chats),i=a[0];if(void 0===i)return void await V(e);let r=await (0,w.fetchChatMessages)(i.id,e.path);C.current=i.id;let s=n4(i.selectedModel,n.models);l(e=>({...e,chats:a,activeChat:i,selectedModel:s,messages:Array.from(r.messages)})),x(void 0)}catch(e){f(nZ(e))}},[V,n.models]),Y=(0,a.useCallback)(async e=>{f(void 0),m.current?.abort(),m.current=null,C.current=e.id,v(void 0),x(void 0),L([]);try{let t=await (0,w.fetchChatMessages)(e.id,e.projectPath),a=n4(e.selectedModel,n.models);l(n=>{let l=n.projects.find(t=>t.path===e.projectPath);return{...n,activeProject:l,activeChat:e,selectedModel:a,messages:Array.from(t.messages)}})}catch(e){f(nZ(e))}},[n.models]),G=(0,a.useCallback)(async e=>{let t=e.trim();if(0!==t.length){f(void 0);try{let e=await (0,w.createProject)({path:t}),n=await (0,w.fetchProjects)();l(e=>({...e,projects:Array.from(n.projects)})),await V(e.project)}catch(e){f(nZ(e))}}},[V]),J=(0,a.useCallback)(e=>{l(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[]),X=(0,a.useCallback)((e,t,n)=>{let a=!1;return{onToken:t=>{a||(_("streaming"),a=!0),l(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,content:n.content+t}:n)}))},onDone:a=>{l(n=>({...n,activeChat:a.chat,chats:n0([a.chat,...n.chats.filter(e=>e.id!==a.chat.id)]),messages:[...n.messages.filter(n=>n.id!==t&&n.id!==e),...Array.from(a.messages)]})),n1(a.chat),void 0!==a.memory&&x(a.memory),n("completed")},onError:({code:t,message:a})=>{f(nZ(new w.ApiError(t,a,0))),J(e),n("failed")},onCancelled:()=>{J(e),n("cancelled")}}},[J,_]),Q=(0,a.useCallback)((e,t,n,a,i,r,s)=>{let o=`stream-${String(Date.now())}`;l(t=>({...t,messages:[...t.messages,{id:o,chatId:e.id,role:"assistant",content:"",timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0}]}));let c={chatId:e.id,projectPath:t.path,content:n,modelId:i,memory:O(e,t),...s.length>0?{documentContext:s}:{}};return new Promise((e,t)=>{let n=X(o,a,e);(0,w.sendDesktopChatStream)(c,r,n).catch(n=>{J(o),n instanceof w.StreamingUnavailableError?t(n):n instanceof DOMException&&"AbortError"===n.name?e("cancelled"):(f(nZ(n)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),e("failed"))})})},[O,X,J]),Z=(0,a.useCallback)(async(e,t,n,a,i,r,s)=>{try{_("contacting");let o=await (0,w.sendDesktopChat)({chatId:e.id,projectPath:t.path,content:n,modelId:i,memory:O(e,t),...s.length>0?{documentContext:s}:{}},r);if(r.aborted)return"cancelled";return l(e=>({...e,activeChat:o.chat,chats:n0([o.chat,...e.chats.filter(e=>e.id!==o.chat.id)]),messages:[...e.messages.filter(e=>e.id!==a),...Array.from(o.messages)]})),n1(o.chat),x(o.memory),"completed"}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return"cancelled";f(nZ(n));try{let n=await (0,w.fetchChatMessages)(e.id,t.path);l(e=>({...e,messages:Array.from(n.messages)}))}catch{l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)}))}return"failed"}},[O,_]),ee=(0,a.useCallback)(async(e,t,a,l,i,r,s)=>{if(n.models.find(e=>e.id===i)?.streaming!==!0)return Z(e,t,a,l,i,r,s);_("contacting");try{return await Q(e,t,a,l,i,r,s)}catch(e){if(!(e instanceof w.StreamingUnavailableError))throw e}return Z(e,t,a,l,i,r,s)},[n.models,Z,Q,_]),et=(0,a.useCallback)(async(e,t,n,a,i,r)=>{v(void 0);try{_("contacting");let t=await (0,w.askGrounded)({chatId:e.id,content:n,modelId:i},r);if(C.current!==e.id)return"completed";if(r.aborted)return"cancelled";v(t),x(void 0);let[a,s]=await Promise.all([(0,w.fetchChatMessages)(e.id,e.projectPath),(0,w.fetchChats)(e.projectPath)]),o=s.chats.find(t=>t.id===e.id);return l(e=>({...e,messages:Array.from(a.messages),chats:n0(s.chats),activeChat:o??e.activeChat})),void 0!==o&&n1(o),"completed"}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return"cancelled";return f(nZ(e)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),"failed"}},[_]),en=(0,a.useCallback)(()=>{nV(p.current)&&(m.current?.abort(),m.current=null,_("cancelled"))},[_]),ea=(0,a.useCallback)(async()=>{if(nV(p.current))return;let e=i.trim(),t=n.activeChat,a=n.activeProject,s=n4(n.selectedModel,n.models);if(0===e.length||void 0===t||void 0===a||void 0===s)return;if(nQ(nb({modelContextWindow:n.models.find(e=>e.id===s)?.contextWindow??0,modelMaxOutputTokens:n.models.find(e=>e.id===s)?.maxOutputTokens??0,userDraftText:e,conversationHistory:n.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}))})))return void f(nH);if(n3(t)&&$.length>0)return void f("Attachments are not supported for grounded chats. Remove the attachment or switch to a non-grounded chat.");let o={id:`local-${String(Date.now())}`,chatId:t.id,role:"user",content:e,timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0};_("queued"),r(""),f(void 0),l(e=>({...e,messages:[...e.messages,o]}));let c=new AbortController;m.current=c,x(void 0);try{let n=n3(t),{entries:l,disclosures:i}=n?{entries:[],disclosures:[]}:await q(),r=n?await et(t,a,e,o.id,s,c.signal):await ee(t,a,e,o.id,s,c.signal,l);"cancelled"===p.current||_(r),"completed"===r&&(D(),L(i))}finally{m.current=null}},[i,n.activeChat,n.activeProject,n.selectedModel,n.models,n.messages,$,et,ee,q,D,_]),el=(0,a.useCallback)(()=>{v(void 0),x(void 0),l(e=>({...e,messages:[]}))},[]),ei=(0,a.useMemo)(()=>{let e=n.models.find(e=>e.id===n.selectedModel);if(void 0===e)return;let t=n.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content})),a=0,l=0;void 0!==g&&(("connected-context"===g.groundingKind||"hybrid"===g.groundingKind)&&(a=("hybrid"===g.groundingKind?g.contextPack.folder:g.contextPack).usage.excerptBytes),("local-knowledge"===g.groundingKind||"hybrid"===g.groundingKind)&&(l=4*("hybrid"===g.groundingKind?g.contextPack.knowledge:g.contextPack).referenceBudget));let r=y&&void 0!==b&&b.context.enabled?b.context.text.length:0;return nb({modelContextWindow:e.contextWindow,modelMaxOutputTokens:e.maxOutputTokens,userDraftText:i,conversationHistory:t,repoContextPackBytes:a,knowledgeCapsuleBytes:l,memoryContextBytes:r})},[n.models,n.selectedModel,n.messages,i,g,b,y]),er=(0,a.useCallback)(async e=>{if(nV(p.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};let t=e.text.trim();if(0===t.length)return{ok:!1,reason:"missing-input"};let a=n.activeChat,i=n.activeProject;if(void 0===a||void 0===i)return{ok:!1,reason:"missing-chat"};let r=n.models.find(t=>t.id===e.modelId);if(void 0===r||!t_(r))return{ok:!1,reason:"not-workflow-eligible"};let s=nd(e.workflowId);if(void 0===s)return{ok:!1,reason:"unknown-workflow"};let o=Date.now(),c=s.buildInput(i.path,t);try{let n=await (0,w.startChatRun)({chatId:a.id,projectPath:i.path,run:{workflowId:e.workflowId,input:c,modelId:e.modelId},user:{content:t,timestamp:o},summary:{content:`Launched: ${s.label}`,timestamp:o+1}});return l(e=>({...e,messages:n5(e.messages,n.messages)})),{ok:!0,runId:n.run.runId}}catch(t){let e=nZ(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat,n.activeProject,n.models]),es=(0,a.useCallback)(async e=>{if(nV(p.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};if(void 0===n.activeChat)return{ok:!1,reason:"missing-chat"};if(0===e.modelId.trim().length)return{ok:!1,reason:"missing-model"};try{let t=await (0,w.startGroundedWorkflowHandoff)({assistantMessageId:e.assistantMessageId,chatId:n.activeChat.id,modelId:e.modelId,workflowKind:e.workflowKind,input:e.input,editablePaths:e.editablePaths,...void 0===e.expectedChecks?{}:{expectedChecks:e.expectedChecks},...void 0===e.unknowns?{}:{unknowns:e.unknowns},requestedAtMs:Date.now()});return l(e=>({...e,messages:n5(e.messages,t.messages)})),{ok:!0,runId:t.run.runId}}catch(t){let e=nZ(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat]),eo=(0,a.useCallback)(e=>{n1(e),l(t=>({...t,chats:t.chats.map(t=>t.id===e.id?e:t),activeChat:t.activeChat?.id===e.id?e:t.activeChat}))},[]),ec=(0,a.useCallback)(()=>{f(void 0)},[]);return{projects:n.projects,chats:n.chats,messages:n.messages,models:n.models,activeProject:n.activeProject,activeChat:n.activeChat,selectedModel:n.selectedModel,noEligibleModels:!s&&void 0===n4(n.selectedModel,n.models),draft:i,loading:s,sending:u,sendStatus:c,error:h,clearError:ec,setDraft:r,setSelectedModel:W,openNewChat:V,openProject:H,openChat:Y,addProject:G,sendMessage:ea,cancelSend:en,replaceChat:eo,latestGrounded:g,cancelGrounded:en,pendingAttachments:$,addPendingAttachment:P,removePendingAttachment:M,clearPendingAttachments:D,lastSentDocuments:T,budget:ei,memoryEnabled:y,setMemoryEnabled:j,memoryBudgetTokens:k,setMemoryBudgetTokens:N,latestMemory:b,clearLatestMemory:F,acceptMemoryCandidate:z,rejectMemoryCandidate:K,forgetMemoryAction:B,clearHistory:el,launchWorkflowFromConversation:er,launchGroundedWorkflowHandoff:es}}let n9="keiko.theme",ae="dark";var at=e.i(26428);let an=["agent","capsule","capsule-set","chat","connector","data-source","evidence-run","mcp-tool","memory","patch-proposal","skill","tool","workflow-run","workspace-path"],aa=["capsule","capsule-set","chat","evidence-run","memory","patch-proposal","tool","workflow-run","workspace-path"],al=["reads-context","proposes-patch","uses-tool","starts-workflow","produces-evidence","references-document","depends-on"],ai=["draft","active","archived","superseded","revoked","blocked","stale"],ar={"reads-context":{id:"reads-context",displayName:"reads context",semantics:"A consumer endpoint reads the contextual content of the target at a specific point in time.",validSourceKinds:["workflow-run","chat"],validTargetKinds:["memory","capsule","capsule-set","evidence-run","workspace-path","connector","data-source"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"proposes-patch":{id:"proposes-patch",displayName:"proposes patch",semantics:"A workflow run proposes a patch against one or more workspace paths. The relationship records the proposal; diff content stays in the harness PatchProposedEvent.",validSourceKinds:["workflow-run"],validTargetKinds:["workspace-path","patch-proposal"],cardinality:"1:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"fs"},"uses-tool":{id:"uses-tool",displayName:"uses tool",semantics:"A workflow run uses a registered tool. Per-call arguments and results remain in the harness ToolCallRequest / ToolCallResult envelopes.",validSourceKinds:["workflow-run"],validTargetKinds:["tool","mcp-tool"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"tool"},"starts-workflow":{id:"starts-workflow",displayName:"starts workflow",semantics:"A chat or a parent workflow run initiates a workflow run. The relationship records the origin; run identity belongs to the workflow ledger.",validSourceKinds:["chat","workflow-run"],validTargetKinds:["workflow-run"],cardinality:"1:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"produces-evidence":{id:"produces-evidence",displayName:"produces evidence",semantics:"A workflow run produces exactly one durable evidence-run record. If a run produces no evidence, no relationship is recorded.",validSourceKinds:["workflow-run"],validTargetKinds:["evidence-run"],cardinality:"1:1",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"produces",ownerPackage:"@oscharko-dev/keiko-evidence",trustBoundary:"evidence"},"references-document":{id:"references-document",displayName:"references document",semantics:"A chat or workflow run holds a structural pointer to a document (workspace file or local-knowledge capsule). Distinct from reads-context: a reference is structural, a read is an event.",validSourceKinds:["chat","workflow-run"],validTargetKinds:["workspace-path","capsule","capsule-set"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!1,reconnectable:!0,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"depends-on":{id:"depends-on",displayName:"depends on",semantics:"A capsule, capsule-set, workflow run, or memory depends on another. Used by impact analysis (#542). Self-loops and direct two-edge cycles are forbidden at validation time; transitive cycle detection is deferred to impact traversal.",validSourceKinds:["capsule","capsule-set","workflow-run","memory"],validTargetKinds:["capsule","capsule-set","workflow-run","memory","evidence-run","workspace-path"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!1,reconnectable:!0,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-contracts",trustBoundary:"per-endpoint"}},as=["prompt","documentcontent","filecontent","toolstdout","toolstderr","secret","credential","apikey","password","token"],ao="Unable to reach the local backend. Check that the Keiko server is running (keiko ui).";class ac extends Error{code;status;reasons;constructor(e,t,n,a=[]){super(t),this.name="RelationshipApiError",this.code=e,this.status=n,this.reasons=a}}async function ad(e){let t;try{t=await e.json()}catch{throw new ac("relationship/parse-error","Response is not valid JSON.",e.status)}if(!e.ok){let n=t,a=n.error??n,l="string"==typeof a.code?a.code:"relationship/unknown-error",i="string"==typeof a.message?a.message:"An unknown error occurred.",r=Array.isArray(n.reasons)?n.reasons:[];throw new ac(l,i,e.status,r)}return t}function au(e){let t={"Content-Type":"application/json","X-Keiko-CSRF":"1"};return void 0!==e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),void 0!==e.ifMatch&&(t["If-Match"]=e.ifMatch),t}async function ap(e){let t={schemaVersion:"1",proposal:{type:e.type,source:{kind:e.source.kind,id:e.source.id},target:{kind:e.target.kind,id:e.target.id},...void 0!==e.summary?{summary:e.summary}:{}}},n=await fetch("/api/relationships/validate",{method:"POST",headers:au({}),body:JSON.stringify(t)});return{decision:(await ad(n)).decision}}async function am(e,t){let n={schemaVersion:"1",proposal:{type:e.type,source:{kind:e.source.kind,id:e.source.id},target:{kind:e.target.kind,id:e.target.id},...void 0!==e.summary?{summary:e.summary}:{}}},a=await fetch("/api/relationships",{method:"POST",headers:au({idempotencyKey:t}),body:JSON.stringify(n)}),l=await ad(a);return{relationship:l.relationship,etag:l.etag}}async function ah(e){let t=new URLSearchParams;void 0!==e.lifecycle&&t.set("lifecycle",e.lifecycle),void 0!==e.type&&t.set("type",e.type),void 0!==e.sourceKind&&t.set("sourceKind",e.sourceKind),void 0!==e.targetKind&&t.set("targetKind",e.targetKind),void 0!==e.sourceId&&t.set("sourceId",e.sourceId),void 0!==e.targetId&&t.set("targetId",e.targetId),void 0!==e.limit&&t.set("limit",String(e.limit)),void 0!==e.cursor&&t.set("cursor",e.cursor);let n=await fetch(`/api/relationships?${t.toString()}`),a=await ad(n);return{entries:a.entries,truncated:a.truncated,nextCursor:a.nextCursor}}async function af(e){let t=await fetch(`/api/relationships/${encodeURIComponent(e)}`);return(await ad(t)).relationship}async function ag(e,t,n,a){let l=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"PATCH",headers:au({idempotencyKey:a,ifMatch:n}),body:JSON.stringify({schemaVersion:"1",...t})}),i=await ad(l);return{relationship:i.relationship,etag:i.etag}}async function av(e,t,n){let a=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"DELETE",headers:au({idempotencyKey:n,ifMatch:t})});return(await ad(a)).relationship}async function ab(e,t={}){let n=new URLSearchParams;void 0!==t.direction&&n.set("direction",t.direction),void 0!==t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),void 0!==t.maxNodes&&n.set("maxNodes",String(t.maxNodes)),void 0!==t.maxRelationships&&n.set("maxRelationships",String(t.maxRelationships));let a=await fetch(`/api/relationships/${encodeURIComponent(e)}/dependencies?${n.toString()}`);return(await ad(a)).report}async function ax(e){return ad(await fetch(`/api/relationships/${encodeURIComponent(e)}/explain`))}async function ay(){return ad(await fetch("/api/relationships/health"))}let aw=[{key:"t",mod:["cmd"]},{key:"t",mod:["ctrl"]},{key:"r",mod:["cmd"]},{key:"r",mod:["ctrl"]},{key:"n",mod:["cmd","shift"]},{key:"n",mod:["ctrl","shift"]},{key:"w",mod:["cmd"]},{key:"w",mod:["ctrl"]}];function aj(e){switch(e.kind){case"ui.window.move":return"Move window";case"ui.window.resize":return"Resize window";case"ui.window.zorder":return"Reorder window";case"ui.window.close":return"Close window";case"ui.window.open":return"Open window";case"ui.workspace.pan":return"Pan workspace";case"ui.workspace.zoom":return"Zoom workspace";case"ui.workspace.fit":return"Fit workspace to view";case"ui.panel.toggle":return`Toggle ${e.panel} panel`;case"ui.selection.change":return"Change selection";case"ui.tab.switch":return"Switch tab"}}function ak(e){let t=[...e.mod].sort();return`${t.join("+")}|${e.key.toLowerCase()}`}let aN={undoStack:[],redoStack:[]};class aS extends Error{conflicts;constructor(e){super(`Workspace keyboard shortcut conflicts detected: ${e.map(e=>`${ak(e.chord)} (${e.commandIds.join(", ")})`).join("; ")}`),this.name="WorkspaceShortcutConflictError",this.conflicts=e}}class aC extends Error{reserved;constructor(e){super(`Workspace keyboard shortcut bindings refused: ${e.map(e=>`${e.commandId} → ${ak(e.chord)}`).join("; ")} are browser-reserved`),this.name="WorkspaceShortcutReservedError",this.reserved=e}}let aI=[{commandId:"undo",chord:{key:"z",mod:["cmd"]}},{commandId:"redo",chord:{key:"z",mod:["cmd","shift"]}},{commandId:"focus-status",chord:{key:"s",mod:["alt"]}}];var aE=e.i(57688);let aR="cmp-budget-exceeded-alert",a$={low:"Low",moderate:"Moderate",high:"High",exceeded:"Exceeded"},aA={low:"cmp-budget-badge cmp-budget-badge-low",moderate:"cmp-budget-badge cmp-budget-badge-moderate",high:"cmp-budget-badge cmp-budget-badge-high",exceeded:"cmp-budget-badge cmp-budget-badge-exceeded"},aT="Token counts are approximate. Actual model usage may vary.";function aL(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function aP({budget:e,onClearHistory:t,disabled:l,compact:i=!1}){let[r,s]=(0,a.useState)(!1),[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(null);if((0,a.useEffect)(()=>{r&&d.current?.focus()},[r]),void 0===e)return null;let p=e.contextWindowTokens>0,m=aL(e.approximateTokens),h=aL(e.contextWindowTokens),f=e.pressure,g=p&&"exceeded"===f;return(0,n.jsxs)("div",{className:"cmp-budget","data-pressure":p?f:"unknown",children:[(0,n.jsxs)("div",{className:"cmp-budget-row",children:[(0,n.jsx)("span",{className:"cmp-budget-count",children:p?i?`Context: ${m} / ${h}`:`Approximate context: ${m} / ${h} tokens`:i?`Context: ${m}`:`Approximate context: ${m} tokens`}),p?(0,n.jsx)("span",{className:aA[f],"aria-label":`Context pressure: ${a$[f]}`,children:a$[f]}):null,(0,n.jsx)("span",{className:"cmp-budget-info",role:"img",tabIndex:0,"aria-label":aT,"data-tip":aT,children:"i"}),r?(0,n.jsxs)("span",{className:"cmp-budget-confirm",children:[(0,n.jsx)("span",{className:"cmp-budget-confirm-label",id:"cmp-budget-confirm-label",children:"Clear history?"}),(0,n.jsx)("button",{type:"button",ref:d,className:"cmp-budget-clear","aria-describedby":"cmp-budget-confirm-label",onClick:function(){t(),s(!1),c(!0),requestAnimationFrame(()=>u.current?.focus())},children:"Clear"}),(0,n.jsx)("button",{type:"button",className:"cmp-budget-clear",onClick:function(){s(!1),requestAnimationFrame(()=>u.current?.focus())},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button",ref:u,className:"cmp-budget-clear","aria-label":"Clear conversation history for next prompt",onClick:()=>{c(!1),s(!0)},disabled:!0===l,children:i?"Clear":"Clear history"}),o?(0,n.jsx)("span",{role:"status",className:"cmp-budget-cleared",children:"History cleared for the next prompt — messages remain saved."}):null]}),g?(0,n.jsx)("div",{id:aR,role:"alert",className:"cmp-budget-alert gw-error",children:"Context exceeds the selected model's window. Clear history or pick a model with a larger context."}):null]})}function aM({notice:e,className:t="ui-error-notice",id:l,onDismiss:i}){let r=`${e.title}
96
- ${e.message}
97
- ${e.code??""}
98
- ${e.remediation??""}`,[s,o]=(0,a.useState)();return s===r?null:(0,n.jsxs)("div",{id:l,className:t,role:"alert","aria-live":"assertive",children:[(0,n.jsxs)("div",{className:"ui-error-notice-title-row",children:[(0,n.jsx)("div",{className:"ui-error-notice-title",children:e.title}),(0,n.jsx)("button",{type:"button",className:"ui-error-notice-close","aria-label":"Dismiss error",title:"Dismiss error",onClick:()=>{o(r),i?.()},children:(0,n.jsx)(j.Icons.close,{size:14})})]}),(0,n.jsx)("div",{className:"ui-error-notice-message",children:e.message}),void 0!==e.remediation?(0,n.jsx)("div",{className:"ui-error-notice-remediation",children:e.remediation}):null,void 0!==e.code?(0,n.jsx)("div",{className:"ui-error-notice-code mono",children:e.code}):null]})}function aD({error:e,fallback:t,className:a,id:l,onDismiss:i}){return(0,n.jsx)(aM,{id:l,className:a,notice:function(e,t){var n;let a;if(e instanceof w.ApiError){let n=nC(nk(e.message.trim()),e.code,t);return{title:nI(n,e.code),message:n,code:e.code,remediation:nE(n,e.code)}}let l=(n=nk(("string"==typeof e?e.trim():e instanceof Error?e.message.trim():"")||t),null===(a=nj.exec(n))?{message:n,code:void 0}:{message:n.slice(0,a.index).trim(),code:a[1]});return{title:nI(l.message,l.code),message:l.message,code:l.code,remediation:nE(l.message,l.code)}}(e,t),onDismiss:i})}var aq=e.i(83449);function aF(e){return Number.isFinite(e)?String(e):"—"}function aO(e,t){return Number.isFinite(e)?t(e):"—"}function az(e){return e.toLocaleString("en-US")}function aK(e){return e.replaceAll("-"," ")}function aB({label:e,value:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("dt",{className:"grounded-context-pack-dt",children:e}),(0,n.jsx)("dd",{className:"grounded-context-pack-dd",children:t})]})}function a_({contextPack:e}){let{usage:t,budget:a}=e,l=function(e){if("workspace-root"===e.scopeKind)return"workspace root";let t=e.scopeId.slice(-8);return`${aK(e.scopeKind)} (${t})`}(e),i="files"===e.scopeKind?`Scope: ${String(e.fileCount)} file${1===e.fileCount?"":"s"} in ${l}`:`Scope: ${l}`;return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Context inspection summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:i}),(0,n.jsxs)("dl",{className:"grounded-context-pack-dl",children:[(0,n.jsx)(aB,{label:"Searched",value:`${String(t.searchCalls)} / ${aF(a.searchCallsMax)} searches`}),(0,n.jsx)(aB,{label:"Read",value:`${String(t.filesRead)} / ${aF(a.filesReadMax)} files`}),(0,n.jsx)(aB,{label:"Bytes",value:`${(0,aq.formatBytes)(t.excerptBytes)} / ${aO(a.excerptBytesMax,aq.formatBytes)}`}),(0,n.jsx)(aB,{label:"Input",value:`${az(t.modelInputTokens)} / ${aO(a.modelInputTokensMax,az)} tokens`}),(0,n.jsx)(aB,{label:"Output",value:`${az(t.modelOutputTokens)} / ${aO(a.modelOutputTokensMax,az)} tokens`}),(0,n.jsx)(aB,{label:"Rerank",value:`${String(t.rerankCalls)} / ${aF(a.rerankCallsMax)} calls`}),(0,n.jsx)(aB,{label:"Time",value:`${(0,aq.formatMs)(e.elapsedMs)} / ${aO(a.elapsedMsMax,aq.formatMs)}`}),(0,n.jsx)(aB,{label:"Query",value:aK(e.queryKind)})]})]})}function aU({score:e}){return(0,n.jsxs)("span",{className:"grounded-citation-score",children:[(0,n.jsx)("span",{className:"sr-only",children:"relevance "}),e.toFixed(2)]})}function aW({citation:e}){let t=e.documentFormat?.toUpperCase();return(0,n.jsxs)("span",{className:"grounded-citation",title:function(e){let t=`relevance ${e.score.toFixed(2)}`,n=void 0===e.documentFormat?"Evidence citation":`${e.documentFormat.toUpperCase()} document evidence (extracted text)`;if(void 0===e.lineRange)return`${n} in ${e.scopePath} — ${t}`;let a=void 0===e.documentFormat?`at lines ${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`:`at extracted span ${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`;return`${n} in ${e.scopePath} ${a} — ${t}`}(e),children:[void 0===t?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"grounded-citation-doc-badge",children:t}),(0,n.jsx)("span",{className:"sr-only",children:" document evidence extracted text "})]}),(0,n.jsx)("span",{className:"grounded-citation-range",children:void 0===e.lineRange?e.scopePath:`${e.scopePath}:${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`}),(0,n.jsx)(aU,{score:e.score})]})}function aV(e){let t=new Set,n=[];for(let a of e)t.has(a.stableId)||(t.add(a.stableId),n.push(a));return n}function aH({total:e,expanded:t,onToggle:a}){return e<=8?null:(0,n.jsx)("button",{type:"button",className:"grounded-citations-more","aria-expanded":t,onClick:a,children:t?"Show fewer sources":`Show all ${String(e)} sources`})}function aY({citations:e}){let[t,l]=(0,a.useState)(!1);if(0===e.length)return null;let i=aV([...e].sort((e,t)=>t.score-e.score)),r=t?i:i.slice(0,8);return(0,n.jsxs)("div",{className:"grounded-citations-wrap",children:[(0,n.jsx)("span",{className:"grounded-citations-label",children:"Evidence"}),(0,n.jsx)("ul",{className:"grounded-citations","aria-label":"Evidence citations",children:r.map(e=>(0,n.jsx)("li",{className:"grounded-citations-item",children:(0,n.jsx)(aW,{citation:e})},e.stableId))}),(0,n.jsx)(aH,{total:i.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function aG({citations:e}){let[t,l]=(0,a.useState)(!1);if(0===e.length)return null;let i=aV([...e].sort((e,t)=>t.score-e.score)),r=t?i:i.slice(0,8);return(0,n.jsxs)("div",{className:"grounded-citations-wrap",children:[(0,n.jsx)("span",{className:"grounded-citations-label",children:"Knowledge citations"}),(0,n.jsx)("ul",{className:"grounded-citations","aria-label":"Knowledge citations",children:r.map(e=>(0,n.jsx)("li",{className:"grounded-citations-item",children:(0,n.jsxs)("span",{className:"grounded-citation",title:void 0===e.source?`${e.label} — relevance ${e.score.toFixed(2)}`:`${e.source} \xb7 ${e.label} — relevance ${e.score.toFixed(2)}`,children:[(0,n.jsx)("span",{children:void 0===e.source?`${e.marker} ${e.label}`:`${e.marker} ${e.source} \xb7 ${e.label}`}),(0,n.jsx)(aU,{score:e.score})]})},e.stableId))}),(0,n.jsx)(aH,{total:i.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function aJ({markers:e}){if(0===e.length)return null;let t=Array.from(new Set(e.map(e=>aK(e.kind)))).join(", ");return(0,n.jsxs)("div",{className:"grounded-uncertainty",role:"note",children:[(0,n.jsx)("div",{children:`Uncertainty (${String(e.length)} markers — ${t})`}),(0,n.jsx)("ul",{className:"grounded-uncertainty-list",children:e.map((e,t)=>(0,n.jsx)("li",{children:`${aK(e.kind)}: ${e.claim}`},`${e.kind}-${String(t)}`))})]})}function aX({omittedCount:e,omittedCounts:t}){if(e<=0)return null;let a=Object.entries(t).filter(([,e])=>e>0).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${aK(e)}: ${String(t)}`).join(", "),l=a.length>0?` (${a})`:"";return(0,n.jsx)("div",{className:"grounded-meta",children:`Not used: ${String(e)} excerpt${1===e?"":"s"}${l}`})}let aQ=[{reason:"size-exceeded",label:"larger than 2 MB"},{reason:"binary",label:"binary or an unsupported format"},{reason:"tool-unavailable",label:"unreadable"},{reason:"unsupported-format",label:"an unsupported document format"},{reason:"no-text-layer",label:"a scanned document with no text layer"},{reason:"malformed-document",label:"a malformed document"},{reason:"encrypted-document",label:"a password-protected document"}];function aZ({omittedCounts:e}){let t=aQ.map(({reason:t,label:n})=>({label:n,count:e[t]})).filter(e=>e.count>0),a=t.reduce((e,t)=>e+t.count,0);if(a<=0)return null;let l=t.map(e=>`${String(e.count)} ${e.label}`).join(", "),i=e.binary>0||e["unsupported-format"]>0||e["no-text-layer"]>0||e["malformed-document"]>0||e["encrypted-document"]>0;return(0,n.jsxs)("div",{className:"grounded-coverage-notice",role:"note",children:[(0,n.jsx)("span",{className:"grounded-coverage-notice-title",children:"Partial coverage"}),(0,n.jsx)("span",{children:`This answer reflects only the searchable files in the connected scope — ${String(a)} ${1===a?"file":"files"} ${1===a?"was":"were"} not searched (${l}). It does not cover the entire folder.`}),i?(0,n.jsx)("span",{children:"Repository Search reads text, code, and small DOCX, XLSX, and text-layer PDF documents. Larger, scanned, encrypted, or other document formats remain available through Local Knowledge."}):null]})}function a0({runId:e,runIds:t}){let a=Array.from(new Set([...void 0===e?[]:[e],...t??[]]));return 0===a.length?null:(0,n.jsx)("div",{className:"grounded-meta",children:a.map((e,t)=>(0,n.jsxs)("a",{className:"sm-link",href:`/api/evidence/${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",children:[1===a.length?"View connected-context audit evidence":`View connected-context audit evidence ${String(t+1)}`," ",(0,n.jsx)("span",{className:"sr-only",children:"(opens in new tab)"})]},e))})}function a1({contextPack:e}){return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Knowledge scope summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:`Knowledge scope: ${e.scopeLabel}`}),(0,n.jsxs)("dl",{className:"grounded-context-pack-dl",children:[(0,n.jsx)(aB,{label:"Mode",value:aK(e.scopeKind)}),(0,n.jsx)(aB,{label:"Capsules",value:String(e.capsuleCount)}),(0,n.jsx)(aB,{label:"Sources",value:String(e.sourceCount)}),(0,n.jsx)(aB,{label:"Citations",value:String(e.citationCount)}),(0,n.jsx)(aB,{label:"Context budget",value:`${String(e.referencesUsed)} / ${String(e.referenceBudget)} references`})]})]})}function a2({contextPack:e}){return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Hybrid source summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:`Hybrid: ${String(e.folderSourceCount)} folder source${1===e.folderSourceCount?"":"s"} + ${String(e.connectorSourceCount)} connector source${1===e.connectorSourceCount?"":"s"}`}),(0,n.jsx)(a_,{contextPack:e.folder}),(0,n.jsx)(a1,{contextPack:e.knowledge})]})}function a4({answer:e,busy:t}){return void 0===e?t?(0,n.jsx)("div",{className:"grounded-meta",role:"status","aria-live":"polite","aria-busy":"true",children:"Searching connected sources and asking Keiko…"}):null:"local-knowledge"===e.groundingKind?(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(aG,{citations:e.citations}),(0,n.jsx)(aJ,{markers:e.uncertainty}),(0,n.jsx)(a1,{contextPack:e.contextPack})]}):"hybrid"===e.groundingKind?(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(aZ,{omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(aY,{citations:e.citations}),(0,n.jsx)(aG,{citations:e.knowledgeCitations}),(0,n.jsx)(aJ,{markers:e.uncertainty}),(0,n.jsx)(aX,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(a0,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(a2,{contextPack:e.contextPack})]}):(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(aZ,{omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(aY,{citations:e.citations}),(0,n.jsx)(aJ,{markers:e.uncertainty}),(0,n.jsx)(aX,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(a0,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(a_,{contextPack:e.contextPack})]})}function a3({label:e,disabled:t=!1,onStepUp:a,onStepDown:l}){let i=`Increase ${e}`,r=`Decrease ${e}`;return(0,n.jsxs)("span",{className:"number-control-stepper",children:[(0,n.jsx)("button",{type:"button",className:"number-control-stepper-button number-control-stepper-up","aria-label":i,disabled:t,onPointerDown:e=>{e.preventDefault()},onClick:e=>{e.stopPropagation(),a()}}),(0,n.jsx)("button",{type:"button",className:"number-control-stepper-button number-control-stepper-down","aria-label":r,disabled:t,onPointerDown:e=>{e.preventDefault()},onClick:e=>{e.stopPropagation(),l()}})]})}var a6=a;let a5=["<script","</script","<iframe","</iframe","<object","</object","<embed","</embed","<style","</style","<svg","</svg","<form","</form","<meta","<link","<base"],a8=[" ","\n"," ","'",'"'];function a7(e){let t=function(e){let t=e.toLowerCase().replaceAll("\0",""),n="";for(let e=0;e<t.length;e++){let a=t[e]??"";if("<"===a){for(n+="<";e+1<t.length&&(" "===t[e+1]||" "===t[e+1]||"\n"===t[e+1]||"\r"===t[e+1]);)e++;continue}n+=a}return n}(e);for(let e of a5)if(t.includes(e))return!0;let n=0;for(;n<t.length-4;){let e=t[n];if(a8.includes(e)&&"o"===t[n+1]&&"n"===t[n+2]){let e=n+3;for(;e<t.length&&/[a-z]/.test(t[e]??"");)e++;if(e<t.length&&"="===t[e])return!0}n++}return!1}function a9(e,t,n,a){a>n&&e.push({kind:"text",text:t.slice(n,a)})}function le(e){return void 0!==e&&/[A-Za-z0-9]/.test(e)}let lt=new Set([" "," ","\n","<",">",'"']),ln=new Set([".",",",")","]","!","?"]);function la(e,t=0){if(t>=16)return e.length>0?[{kind:"text",text:e}]:[];let n=[],a=0,l=0;for(;a<e.length;){let i=function(e,t,n,a){if("`"!==t[n])return -1;let l=t.indexOf("`",n+1);return -1===l?-1:(a9(e,t,a,n),e.push({kind:"inline-code",text:t.slice(n+1,l)}),l+1)}(n,e,a,l);if(-1!==i||-1!==(i=function(e,t,n,a,l){let i=t[n],r=t[n+1];if(n+1>=t.length||("*"!==i||"*"!==r)&&("_"!==i||"_"!==r))return -1;let s=t.indexOf(i+r,n+2);if(-1===s)return -1;a9(e,t,a,n);let o=t.slice(n+2,s);return e.push({kind:"strong",children:la(o,l+1)}),s+2}(n,e,a,l,t))||-1!==(i=function(e,t,n,a,l){let i=t[n];if("*"!==i&&"_"!==i||"_"===i&&le(t[n-1])&&le(t[n+1])||t[n+1]===i||n>0&&t[n-1]===i)return -1;let r=function(e,t,n){for(let a=n;a<e.length;a++)if(e[a]===t&&e[a-1]!==t&&(a+1>=e.length||e[a+1]!==t))return a;return -1}(t,i,n+1);return -1===r||"_"===i&&le(t[r-1])&&le(t[r+1])?-1:(a9(e,t,a,n),e.push({kind:"em",children:la(t.slice(n+1,r),l+1)}),r+1)}(n,e,a,l,t))||-1!==(i=function(e,t,n,a){let l;if("["!==t[n])return -1;let i=t.indexOf("]",n+1);if(-1===i||"("!==t[i+1])return -1;let r=t.indexOf(")",i+2);if(-1===r)return -1;let s=t.slice(n+1,i),o=t.slice(i+2,r);return a9(e,t,a,n),((l=o.trim().toLowerCase()).startsWith("http://")||l.startsWith("https://"))&&!a7(s)&&!a7(o)?e.push({kind:"link",text:s,href:o}):e.push({kind:"text",text:`[${s}](${o})`}),r+1}(n,e,a,l))||-1!==(i=function(e,t,n,a){if("h"!==t[n])return -1;let l="https://"===t.slice(n,n+8),i="http://"===t.slice(n,n+7);if(!l&&!i)return -1;let r=function(e,t){let n=t;for(;n<e.length&&!lt.has(e[n]??"");)n++;for(;n>t&&ln.has(e[n-1]??"");)n--;return n}(t,n);if(r-n<=(l?8:7))return -1;let s=t.slice(n,r);return a9(e,t,a,n),e.push({kind:"link",text:s,href:s}),r}(n,e,a,l))){l=i,a=i;continue}a++}return a9(n,e,l,e.length),n}function ll(e){let t=e.trim(),n=t.startsWith(":"),a=t.endsWith(":");return n&&a?"center":a?"right":n?"left":void 0}function li(e){let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|")}function lr(e){let t=/^( *)([*+\-]) (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[3]??""}:{match:!1}}function ls(e){let t=/^( *)\d+\. (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[2]??""}:{match:!1}}function lo(e){return e.includes("|")}function lc(e){let t=e.trim();return/^(-{3,}|\*{3,}|_{3,})$/.test(t)}function ld(e,t){let n=[],a=t?ls:lr;for(;e.i<e.lines.length;){let t=e.lines[e.i]??"",l=a(t);if(l.match)n.push({text:l.text,indent:l.indent}),e.i++;else if(""===t.trim())break;else break}return function e(t,n,a){let l=n?"ol":"ul",i=[],r=0;for(;r<t.length;){let l=t[r];if(void 0===l){r++;continue}let s=l.indent,o=[];for(r++;r<t.length;){let e=t[r];if(void 0===e||e.indent<=s)break;o.push(e),r++}let c=[...la(l.text)];o.length>0&&a<16?c.push(e(o,n,a+1)):o.length>0&&c.push({kind:"text",text:o.map(e=>e.text).join("\n")}),i.push({kind:"li",children:c})}return{kind:l,children:i}}(n,t,e.depth)}function lu({text:e}){let[t,a]=(0,a6.useState)(!1),[l,i]=(0,a6.useState)(""),r=(0,a6.useCallback)(()=>{"u"<typeof navigator||navigator.clipboard?.writeText===void 0?i("Copy unavailable: the clipboard requires a secure (HTTPS) connection."):navigator.clipboard.writeText(e).then(()=>{a(!0),i("Code copied"),setTimeout(()=>{a(!1),i("")},1500)},()=>{})},[e]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"sm-code-copy","aria-label":t?"Copied":"Copy code block",title:t?"Copied":"Copy code block","data-copied":t?"true":"false",onClick:r,children:t?"Copied":"Copy"}),(0,n.jsx)("span",{role:"status",className:"sr-only",children:l})]})}let lp={1:"h3",2:"h4",3:"h5",4:"h6",5:"h6",6:"h6"},lm={1:"sm-h sm-h1",2:"sm-h sm-h2",3:"sm-h sm-h3",4:"sm-h sm-h4",5:"sm-h sm-h5",6:"sm-h sm-h6"};function lh(e,t){return void 0===e.children?null:e.children.map((e,n)=>lf(e,t+"-"+String(n)))}function lf(e,t){let a=function(e,t){switch(e.kind){case"paragraph":return(0,n.jsx)("p",{className:"sm-p",children:lh(e,t)},t);case"heading":{let a=e.level??1,l=lp[a],i=lm[a];return(0,n.jsx)(l,{className:i,children:lh(e,t)},t)}case"blockquote":return(0,n.jsx)("blockquote",{className:"sm-blockquote",children:lh(e,t)},t);case"hr":return(0,n.jsx)("hr",{className:"sm-hr"},t);case"code-block":{let a=e.language,l=e.text??"",i=void 0!==a?`lang-${a}`:void 0;return(0,n.jsxs)("div",{className:"sm-code-block-frame",children:[(0,n.jsxs)("div",{className:"sm-code-block-header",children:[(0,n.jsx)("span",{className:"sm-code-lang",children:a??"text"}),(0,n.jsx)(lu,{text:l})]}),(0,n.jsx)("pre",{className:"sm-pre",children:(0,n.jsx)("code",{className:i,children:l})})]},t)}default:return null}}(e,t);if(null!==a)return a;let l=function(e,t){switch(e.kind){case"ul":return(0,n.jsx)("ul",{className:"sm-ul",children:lh(e,t)},t);case"ol":return(0,n.jsx)("ol",{className:"sm-ol",children:lh(e,t)},t);case"li":return(0,n.jsx)("li",{className:"sm-li",children:lh(e,t)},t);default:return null}}(e,t);if(null!==l)return l;let i=function(e,t){let a=void 0!==e.align?{textAlign:e.align}:void 0;switch(e.kind){case"table":return(0,n.jsx)("div",{className:"sm-table-wrapper",children:(0,n.jsx)("table",{className:"sm-table",children:lh(e,t)})},t);case"thead":return(0,n.jsx)("thead",{children:lh(e,t)},t);case"tbody":return(0,n.jsx)("tbody",{children:lh(e,t)},t);case"tr":return(0,n.jsx)("tr",{children:lh(e,t)},t);case"th":return(0,n.jsx)("th",{style:a,children:lh(e,t)},t);case"td":return(0,n.jsx)("td",{style:a,children:lh(e,t)},t);default:return null}}(e,t);if(null!==i)return i;let r=function(e,t){switch(e.kind){case"text":return(0,n.jsx)("span",{children:e.text},t);case"inline-code":return(0,n.jsx)("code",{className:"sm-inline-code",children:e.text},t);case"link":return(0,n.jsxs)("a",{href:e.href,className:"sm-link",rel:"noopener noreferrer",target:"_blank",children:[e.text,(0,n.jsx)("span",{className:"sr-only",children:" (opens in new tab)"})]},t);case"strong":return(0,n.jsx)("strong",{children:lh(e,t)},t);case"em":return(0,n.jsx)("em",{children:lh(e,t)},t);default:return null}}(e,t);return null!==r?r:null}function lg({source:e}){let t=function e(t,n){let a=[],l={lines:t.split("\n"),i:0,depth:n};for(;l.i<l.lines.length;)!function(t,n){let a=t.lines[t.i]??"";if(""===a.trim())return t.i++;if(function(e,t,n){let a=/^(`{3,}|~{3,})(\S*)/.exec(t.trim());if(null===a)return!1;let l=a[1]??"```",i=a[2],r=void 0!==i&&i.length>0?i:void 0;return n.push(function(e,t,n){let a=[];for(e.i++;e.i<e.lines.length;){let n=e.lines[e.i]??"",l=/^(`{3,}|~{3,})\s*$/.exec(n.trim());if(null!==l){let n=l[1]??"";if(n.startsWith(t[0]??"")&&n.length>=t.length){e.i++;break}}a.push(n),e.i++}let l={kind:"code-block",text:a.join("\n")};return void 0!==n?{...l,language:n}:l}(e,l,r)),!0}(t,a,n)||function(e,t,n){let a=/^(#{1,6}) (.+)$/.exec(t.trim());if(null===a)return!1;let l=Math.min((a[1]??"").length,6),i=a[2]??"";return n.push({kind:"heading",level:l,children:la(i)}),e.i++,!0}(t,a,n))return;if(lc(a)){n.push({kind:"hr"}),t.i++;return}if(a.trimStart().startsWith("> ")||">"===a.trim())return n.push(function(t){let n=[];for(;t.i<t.lines.length;){let e=t.lines[t.i]??"";if(e.trimStart().startsWith("> ")||">"===e.trim())n.push(e.replace(/^( *)> ?/,"")),t.i++;else break}let a=n.join("\n");return t.depth>=16?{kind:"blockquote",children:[{kind:"paragraph",children:[{kind:"text",text:a}]}]}:{kind:"blockquote",children:[...e(a,t.depth+1)]}}(t));if(lo(a.trim())&&function(e){if(0===e.length)return!1;for(let t of e){let e=t.trim().replace(/^:/,"").replace(/:$/,"");if(!/^-+$/.test(e))return!1}return!0}(li(t.lines[t.i+1]??""))&&(n.push(function(e,t){let n,a;e.i++;let l=e.lines[e.i]??"",i=[];for(e.i++;e.i<e.lines.length;){let t=e.lines[e.i]??"";if(""===t.trim()||!lo(t.trim()))break;i.push(t),e.i++}return n=li(t),a=li(l).map(ll),{kind:"table",children:[{kind:"thead",children:[{kind:"tr",children:n.map((e,t)=>{var n;let l;return n=a[t],l={kind:"th",children:la(e.trim())},void 0!==n?{...l,align:n}:l})}]},{kind:"tbody",children:i.map(e=>({kind:"tr",children:li(e).map((e,t)=>{var n;let l;return n=a[t],l={kind:"td",children:la(e.trim())},void 0!==n?{...l,align:n}:l})}))}]}}(t,a)),1)||(lr(a).match?(n.push(ld(t,!1)),!0):!!ls(a).match&&(n.push(ld(t,!0)),!0)))return;let l=function(e){let t=[];for(;e.i<e.lines.length;){let n=e.lines[e.i]??"";if(function(e){let t=e.trim();return!!(""===t||/^#{1,6} /.test(t)||e.trimStart().startsWith("> ")||/^(`{3,}|~{3,})/.test(t))||!!lr(e).match||!!ls(e).match||lc(e)}(n))break;t.push(n),e.i++}return 0===t.length?null:{kind:"paragraph",children:la(t.join(" "))}}(t);null!==l&&n.push(l)}(l,a);return a}(e,0);return(0,n.jsx)("div",{className:"sm-root",children:t.map((e,t)=>lf(e,String(t)))})}class lv extends a6.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?(0,n.jsx)("div",{className:"sm-root sm-fallback","data-markdown-fallback":"true",children:this.props.source}):(0,n.jsx)(lg,{source:this.props.source})}}function lb({attachment:e,onRemove:t}){var a;let l=`Remove attachment ${e.name}`,i=function(e,t=32){if(e.length<=t)return e;let n=e.lastIndexOf(".");if(n>0&&e.length-n<=8){let a=e.slice(n);return`${e.slice(0,t-a.length-1)}…${a}`}return`${e.slice(0,t-1)}…`}(e.name);return(0,n.jsxs)("div",{className:"attach-chip",role:"listitem",children:["image"===e.kind&&void 0!==e.previewDataUrl?(0,n.jsx)("img",{src:e.previewDataUrl,alt:"",className:"attach-chip-thumb",width:40,height:40}):(0,n.jsx)("span",{className:"attach-chip-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.file,{size:16})}),(0,n.jsx)("span",{className:"attach-chip-name",title:e.name,children:i}),(0,n.jsx)("span",{className:"attach-chip-size",children:(a=e.sizeBytes)<1024?`${String(a)} B`:a<1048576?`${(a/1024).toFixed(1)} KB`:`${(a/1048576).toFixed(1)} MiB`}),(0,n.jsx)("button",{type:"button",className:"attach-chip-remove","aria-label":l,onClick:()=>t(e.id),children:(0,n.jsx)(j.Icons.close,{size:12})})]})}function lx({attachments:e,onRemove:t}){return 0===e.length?null:(0,n.jsx)("div",{className:"attach-strip",role:"list","aria-label":"Pending attachments",children:e.map(e=>(0,n.jsx)(lb,{attachment:e,onRemove:t},e.id))})}function ly({enabled:e,onFiles:t}){let[l,i]=(0,a.useState)(!1),[r,s]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(!e)return;let t=0,n=e=>{Array.from(e.dataTransfer?.types??[]).includes("Files")&&(t+=1,s(!0))},a=()=>{0===(t=Math.max(0,t-1))&&s(!1)},l=()=>{t=0,s(!1)};return window.addEventListener("dragenter",n),window.addEventListener("dragleave",a),window.addEventListener("drop",l),window.addEventListener("dragend",l),()=>{window.removeEventListener("dragenter",n),window.removeEventListener("dragleave",a),window.removeEventListener("drop",l),window.removeEventListener("dragend",l)}},[e]);let o=(0,a.useCallback)(t=>{e&&(t.preventDefault(),i(!0))},[e]),c=(0,a.useCallback)(()=>{i(!1)},[]),d=(0,a.useCallback)(n=>{if(n.preventDefault(),i(!1),!e)return;let a=Array.from(n.dataTransfer.files);a.length>0&&t(a)},[e,t]);return e?(0,n.jsx)("div",{className:"attach-drop-zone","data-dragover":l?"true":void 0,"data-active":r?"true":"false","aria-hidden":"true",onDragOver:o,onDragLeave:c,onDrop:d,children:(0,n.jsx)("span",{className:"attach-drop-hint",children:"Drop files here to attach"})}):null}let lw="cmp-attach-disabled-hint";function lj({model:e,onFiles:t,anyModelSupportsAttachments:l=!0}){let i=(0,a.useRef)(null),r=void 0!==e&&(e.supportsImageInput||e.supportsDocumentInput),s=function(e){if(void 0===e)return"";let t=[];return e.supportsImageInput&&t.push("image/*"),e.supportsDocumentInput&&t.push(".pdf,.txt,.md,.csv,.json,.yaml,.yml"),t.join(",")}(e),o=(0,a.useCallback)(()=>{r&&i.current?.click()},[r]),c=(0,a.useCallback)(()=>{let e=Array.from(i.current?.files??[]);e.length>0&&(t(e),null!==i.current&&(i.current.value=""))},[t]);return(0,n.jsxs)(n.Fragment,{children:[r?null:(0,n.jsx)("span",{id:lw,className:"sr-only",children:l?"The selected model does not support image or document input. Choose a different model to attach files.":"The selected model does not support image or document input. No configured model currently supports attachments."}),(0,n.jsx)("input",{ref:i,type:"file",multiple:!0,accept:s,className:"sr-only",tabIndex:-1,"aria-hidden":"true",onChange:c}),(0,n.jsx)("button",{type:"button",className:"cmp-icon cmp-tip-start","aria-label":"Attach file","aria-disabled":r?void 0:"true","aria-describedby":r?void 0:lw,"data-tip":r?"Attach file":"Attachments not supported",onClick:o,children:(0,n.jsx)(j.Icons.files,{size:16})})]})}function lk({reason:e,mimeType:t}){return void 0===e?null:(0,n.jsx)("div",{role:"alert",className:"attach-rejection-alert",children:function(e,t){switch(e){case"text-only-model":return"The selected model can't accept this attachment type. Choose a model that supports images or documents.";case"unsupported-type":return`Unsupported file type${void 0!==t&&t.length>0?`: ${t}`:""}. Supported types: images (image/*), PDF, plain text, markdown, JSON, YAML.`;case"oversized":return"File is larger than the 8 MiB limit. Choose a smaller file or summarize the content as text.";case"empty":return"Empty file. Add a file with content to attach."}}(e,t)})}function lN({documents:e}){if(0===e.length)return null;let t=e.some(e=>e.truncated);return(0,n.jsxs)("div",{role:"note",className:"sent-docs-note","aria-label":"Documents included as context",children:[(0,n.jsx)("span",{className:"sent-docs-note-label",children:1===e.length?"Document included as context:":"Documents included as context:"}),(0,n.jsx)("ul",{className:"sent-docs-note-list",children:e.map(e=>(0,n.jsxs)("li",{className:"sent-docs-note-item",children:[e.displayName,e.truncated?(0,n.jsx)("span",{className:"sent-docs-note-trunc",children:" (truncated)"}):null]},e.id))}),t?(0,n.jsx)("span",{className:"sent-docs-note-hint",children:"Some document text was truncated to fit the context limit."}):null]})}function lS({selectedModel:e,compact:t=!1,launch:l}){let[i,r]=(0,a.useState)(!1),s=(0,a.useRef)(null);return void 0!==e&&t_(e)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:s,type:"button",className:`cmp-mode${t?" cmp-mode-compact":" cmp-pill-standard"} ui-tip`,"aria-label":"Launch workflow","aria-haspopup":"dialog","data-tip":t?"Launch workflow":void 0,onClick:()=>r(!0),children:[(0,n.jsx)(j.Icons.spark,{size:t?16:14,style:{color:"var(--accent)"}}),t?(0,n.jsx)("span",{className:"sr-only",children:"Launch workflow"}):"Launch workflow",t?null:(0,n.jsx)(j.Icons.chevron,{size:12})]}),i?(0,n.jsx)(lI,{modelId:e.id,launch:l,onClose:()=>{r(!1),s.current?.focus()}}):null]}):null}function lC(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))}function lI({modelId:e,launch:t,onClose:l}){let i=(0,a.useId)(),r=(0,a.useId)(),[s,o]=(0,a.useState)(),[c,d]=(0,a.useState)(""),[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(),f=(0,a.useRef)(null),g=void 0===s?void 0:nd(s);async function v(){if(void 0===g||0===c.trim().length)return;p(!0),h(void 0);let n=await t({workflowId:g.workflowId,modelId:e,text:c});(p(!1),n.ok)?l():h(function(e){if(void 0!==e.message&&e.message.length>0)return e.message;switch(e.reason){case"not-workflow-eligible":return"The selected model does not support workflow runs. Pick a model with tool calling and structured output.";case"unknown-workflow":return"That workflow is no longer available.";case"missing-chat":return"Open or create a chat first, then launch the workflow.";case"missing-input":return"Provide an input before launching the workflow.";case"request-failed":return"Could not launch the workflow. Try again, or check the gateway logs.";default:return"Could not launch the workflow."}}(n))}(0,a.useEffect)(()=>{f.current?.focus()},[s]),(0,a.useEffect)(()=>{function e(e){if("Escape"===e.key)return void l();if("Tab"!==e.key)return;let t=f.current;if(null===t)return;let n=lC(t);if(0===n.length){e.preventDefault(),t.focus();return}let a=n[0],i=n[n.length-1],r=document.activeElement;e.shiftKey&&(r===a||r===t)?(e.preventDefault(),i?.focus()):e.shiftKey||r!==i||(e.preventDefault(),a?.focus())}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[l]);let b=(0,n.jsx)("div",{ref:f,role:"dialog","aria-modal":"true","aria-labelledby":i,tabIndex:-1,className:"wf-dialog-overlay",children:(0,n.jsxs)("div",{className:"wf-dialog",children:[(0,n.jsx)("h2",{id:i,className:"wf-dialog-title",children:"Launch workflow"}),void 0===g?(0,n.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available workflows",children:nc.map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>o(e.workflowId),children:[(0,n.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,n.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowId))}):(0,n.jsxs)("div",{className:"wf-dialog-form",children:[(0,n.jsx)("p",{className:"wf-dialog-form-desc",children:g.description}),(0,n.jsx)("label",{className:"wf-dialog-field",htmlFor:r,children:g.prompt}),(0,n.jsx)("textarea",{id:r,className:"wf-dialog-input mono",rows:3,placeholder:g.placeholder,value:c,onChange:e=>d(e.target.value)}),void 0!==m?(0,n.jsx)("div",{role:"alert",className:"wf-dialog-error",children:m}):null,(0,n.jsxs)("div",{className:"wf-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>o(void 0),children:"Back"}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:u||0===c.trim().length,onClick:()=>{v()},children:u?"Launching…":"Launch"})]})]}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close launch workflow",onClick:l,children:(0,n.jsx)(j.Icons.close,{size:14})})]})});return"u"<typeof document?b:(0,tP.createPortal)(b,document.body)}let lE=[{workflowKind:"unit-test-generation",label:"Generate unit tests",description:"Use the grounded evidence as read-only context and propose in-scope test changes."},{workflowKind:"bug-investigation",label:"Investigate bug",description:"Investigate a bug against the grounded evidence and keep writes inside approved paths."},{workflowKind:"verification",label:"Run verification",description:"Run verification against the grounded workspace context without granting write access."}],lR=["verify","lint","typecheck","tests","manual"];function l$(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(e=>e.length>0)}function lA({answer:e,modelId:t,busy:l,launch:i}){let[r,s]=(0,a.useState)(!1),o=(0,a.useRef)(null),c=(0,a.useId)();if(void 0===e||"connected-context"!==e.groundingKind||void 0===t||e.citations.some(e=>void 0!==e.source))return null;let d=!0===l;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:o,type:"button",className:"cmp-mode ui-tip","data-tip":"Launch grounded workflow","aria-haspopup":"dialog","aria-disabled":d||void 0,"aria-describedby":d?c:void 0,onClick:()=>{d||s(!0)},children:[(0,n.jsx)(j.Icons.spark,{size:14,style:{color:"var(--accent)"}})," Launch grounded workflow",(0,n.jsx)(j.Icons.chevron,{size:12})]}),d?(0,n.jsx)("span",{className:"sr-only",id:c,children:"A run is in progress. Wait for it to complete before launching another grounded workflow."}):null,r?(0,n.jsx)(lT,{answer:e,modelId:t,launch:i,onClose:()=>{s(!1),o.current?.focus()}}):null]})}function lT({answer:e,modelId:t,launch:l,onClose:i}){let r=(0,a.useId)(),s=(0,a.useRef)(null),[o,c]=(0,a.useState)(),[d,u]=(0,a.useState)("file"),[p,m]=(0,a.useState)(""),[h,f]=(0,a.useState)(""),[g,v]=(0,a.useState)(""),[b,x]=(0,a.useState)(""),[y,w]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)([]),[I,E]=(0,a.useState)(!1),[R,$]=(0,a.useState)();async function A(){if(void 0===o)return;let n=function(e,t,n,a,l,i){if("unit-test-generation"===e){if("changedFiles"===t){let e=l$(n);return 0===e.length?{ok:!1,message:"Provide at least one changed file."}:{ok:!0,input:{target:{kind:"changedFiles",filePaths:e}}}}let e=n.trim();return 0===e.length?{ok:!1,message:"module"===t?"Provide a module directory.":"Provide a target file."}:"module"===t?{ok:!0,input:{target:{kind:"module",moduleDir:e}}}:{ok:!0,input:{target:{kind:"file",filePath:e}}}}if("bug-investigation"===e){let e=l$(l),t=a.trim();return 0===t.length&&0===e.length?{ok:!1,message:"Provide at least a bug description or one suspected target file."}:{ok:!0,input:{report:{...0===t.length?{}:{description:t},...0===e.length?{}:{targetFiles:e}}}}}let r=l$(i);return{ok:!0,input:0===r.length?{}:{targetFiles:r}}}(o,d,p,h,g,b);if(!n.ok)return void $(n.message);if(0===S.length)return void $("Select at least one expected check.");E(!0),$(void 0);let a=await l({assistantMessageId:e.assistantMessageId,modelId:t,workflowKind:o,input:n.input,editablePaths:l$(y),expectedChecks:S,unknowns:l$(k)});(E(!1),a.ok)?i():$(function(e){if(e.ok)return"";if(void 0!==e.message&&e.message.length>0)return e.message;switch(e.reason){case"missing-chat":return"Open a chat with the grounded answer you want to hand off.";case"missing-model":return"Pick a model before launching the grounded workflow.";default:return"Could not launch the grounded workflow."}}(a))}(0,a.useEffect)(()=>{s.current?.focus()},[o]),(0,a.useEffect)(()=>{void 0!==o&&C("unit-test-generation"===o?["tests"]:["verify"])},[o]),(0,a.useEffect)(()=>{function e(e){if("Escape"===e.key)return void i();if("Tab"!==e.key)return;let t=s.current;if(null===t)return;let n=lC(t);if(0===n.length){e.preventDefault(),t.focus();return}let a=n[0],l=n[n.length-1],r=document.activeElement;e.shiftKey&&(r===a||r===t)?(e.preventDefault(),l?.focus()):e.shiftKey||r!==l||(e.preventDefault(),a?.focus())}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[i]);let T=lE.find(e=>e.workflowKind===o),L=(0,n.jsx)("div",{ref:s,role:"dialog","aria-modal":"true","aria-labelledby":r,tabIndex:-1,className:"wf-dialog-overlay",children:(0,n.jsxs)("div",{className:"wf-dialog",children:[(0,n.jsx)("h2",{id:r,className:"wf-dialog-title",children:"Grounded workflow handoff"}),void 0===T?(0,n.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available grounded workflows",children:lE.map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>c(e.workflowKind),children:[(0,n.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,n.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowKind))}):(0,n.jsxs)("div",{className:"wf-dialog-form",children:[(0,n.jsx)("p",{className:"wf-dialog-form-desc",children:T.description}),"unit-test-generation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"wf-dialog-field",children:[(0,n.jsx)("span",{children:"Target mode"}),(0,n.jsx)(tz,{triggerClassName:"wf-dialog-input mono",value:d,ariaLabel:"Target mode",menuTitle:"Target mode",mono:!0,sections:[{options:[{value:"file",label:"File"},{value:"module",label:"Module"},{value:"changedFiles",label:"Changed files"}]}],onValueChange:e=>u(e)})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["module"===d?"Module directory":"changedFiles"===d?"Changed files (one per line)":"Target file",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:"changedFiles"===d?3:2,value:p,onChange:e=>m(e.target.value),placeholder:"module"===d?"src/components":"changedFiles"===d?"src/a.ts\nsrc/b.ts":"src/example.ts"})]})]}):null,"bug-investigation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Bug description",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:h,onChange:e=>f(e.target.value),placeholder:"Describe the failing behavior or regression."})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Suspected target files (one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:g,onChange:e=>v(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]})]}):null,"verification"===o?(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Target files (optional, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:b,onChange:e=>x(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]}):null,(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Editable paths (explicit, workspace-relative, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:y,onChange:e=>w(e.target.value),placeholder:"src/example.test.ts"})]}),(0,n.jsxs)("fieldset",{className:"wf-dialog-field",style:{border:0,padding:0,margin:0},children:[(0,n.jsx)("legend",{children:"Expected checks"}),(0,n.jsx)("div",{className:"wf-dialog-form",style:{gap:8},children:lR.map(e=>(0,n.jsxs)("label",{className:"c-check",children:[(0,n.jsx)("input",{type:"checkbox",checked:S.includes(e),onChange:()=>{C(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])}}),(0,n.jsx)("span",{className:"bx","aria-hidden":"true",children:(0,n.jsx)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M5 12.5 L10 17.5 L19 6.5"})})}),(0,n.jsx)("span",{children:e})]},e))})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Unknowns (optional, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:k,onChange:e=>N(e.target.value),placeholder:"Need confirmation on public API behavior"})]}),void 0!==R?(0,n.jsx)("div",{role:"alert",className:"wf-dialog-error",children:R}):null,(0,n.jsxs)("div",{className:"wf-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>c(void 0),children:"Back"}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:I,onClick:()=>{A()},children:I?"Launching…":"Launch"})]})]}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close grounded workflow handoff",onClick:i,children:(0,n.jsx)(j.Icons.close,{size:14})})]})});return"u"<typeof document?L:(0,tP.createPortal)(L,document.body)}function lL(e){return"system"===e.role&&"string"==typeof e.runId}function lP({message:e,onOpenResult:t}){let l=e.workflowStatus??"queued",i=e.workflowId??e.taskType??"workflow",r=void 0===e.runId?"":e.runId.slice(0,8),s=void 0===e.runId?void 0:`/api/evidence/${encodeURIComponent(e.runId)}`,[o,c]=(0,a.useState)(""),d=(0,a.useRef)(l);return(0,a.useEffect)(()=>{d.current!==l&&(d.current=l,c(`Workflow ${i}: ${l}`))},[l,i]),(0,n.jsxs)("article",{className:"run-summary-card","data-testid":"run-summary-card","data-status":l,"aria-label":`Workflow run ${i} — ${l}`,children:[(0,n.jsxs)("header",{className:"run-summary-card-head",children:[(0,n.jsx)(j.Icons.spark,{size:14,style:{color:"var(--accent)"}}),(0,n.jsx)("span",{className:"run-summary-card-workflow mono",children:i}),(0,n.jsx)("span",{className:"run-summary-card-status","data-status":l,children:l})]}),(0,n.jsxs)("div",{className:"run-summary-card-body",children:[(0,n.jsx)("p",{className:"run-summary-card-line",children:e.content}),void 0!==e.shortResult&&e.shortResult.length>0?(0,n.jsx)("p",{className:"run-summary-card-result",children:e.shortResult}):null,void 0!==e.runId?(0,n.jsxs)("p",{className:"run-summary-card-meta mono",children:["run"," ",(0,n.jsx)("span",{className:"run-summary-card-runshort","data-runid":e.runId,title:e.runId,children:r})]}):null,void 0!==e.runId?(0,n.jsxs)("div",{className:"run-summary-card-actions","aria-label":"Workflow result actions",children:[void 0!==t?(0,n.jsx)("button",{type:"button",className:"run-summary-card-action",onClick:()=>t(e),children:"Open result"}):null,void 0!==s?(0,n.jsx)("a",{className:"run-summary-card-action run-summary-card-action-secondary",href:s,target:"_blank",rel:"noreferrer",children:"Evidence"}):null]}):null]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"run-summary-card-sr",children:o})]})}function lM({on:e,onChange:t,label:a}){return(0,n.jsx)("button",{type:"button",role:"switch","aria-checked":e,"aria-label":a,className:`auto-toggle${e?" on":""}`,onClick:()=>{t(!e)},children:(0,n.jsx)("span",{})})}var lD=e.i(61593);let lq="cmp-no-model-alert",lF="cmp-send-hint",lO="cmp-loading-status",lz="Ask Keiko...",lK=/\s*[[【[]\d+[\]】]]/g;function lB({content:e}){let[t,l]=(0,a.useState)(!1),[i,r]=(0,a.useState)(""),s=(0,a.useCallback)(()=>{"u"<typeof navigator||navigator.clipboard?.writeText===void 0?r("Copy unavailable: the clipboard requires a secure (HTTPS) connection."):navigator.clipboard.writeText(e.replace(lK,"")).then(()=>{l(!0),r("Message copied"),setTimeout(()=>{l(!1),r("")},1500)},()=>{})},[e]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"chat-msg-copy ui-tip","aria-label":t?"Copied":"Copy message","data-tip":t?"Copied":"Copy message","data-copied":t?"true":"false",onClick:s,children:t?"Copied":"Copy"}),(0,n.jsx)("span",{role:"status",className:"sr-only",children:i})]})}function l_({message:e,onOpenRunResult:t,streaming:a=!1}){let l,i;if(lL(e))return(0,n.jsx)(lP,{message:e,onOpenResult:t});let r="user"===e.role;return(0,n.jsx)("article",{className:"chat-msg","data-role":e.role,children:(0,n.jsxs)("div",{className:"chat-msg-bubble",children:[r?(0,n.jsx)("div",{className:"chat-msg-role",children:"You"}):(0,n.jsx)(lU,{}),r?e.content:(0,n.jsx)(lv,{source:e.content}),a&&!r?(0,n.jsx)("span",{className:"ai-stream-cursor","aria-hidden":"true"}):null,(0,n.jsxs)("div",{className:"chat-msg-foot",children:[(0,n.jsx)("div",{className:"chat-msg-time",title:new Date(e.timestamp).toLocaleString(),children:(i=(l=new Date(e.timestamp)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),l.toDateString()===new Date().toDateString()?i:`${l.toLocaleDateString([],{month:"short",day:"numeric"})}, ${i}`)}),r?null:(0,n.jsx)(lB,{content:e.content})]})]})})}function lU({pulsing:e=!1}){return(0,n.jsx)("div",{className:"chat-msg-brand","data-pulsing":e?"true":"false",role:"img","aria-label":"Keiko logo",children:(0,n.jsx)(aE.default,{src:"/assets/keiko-logo.svg",width:22,height:22,alt:"","aria-hidden":"true"})})}function lW(){return(0,n.jsx)("article",{className:"chat-msg","data-role":"assistant",children:(0,n.jsxs)("div",{className:"chat-msg-bubble",children:[(0,n.jsx)(lU,{pulsing:!0}),(0,n.jsxs)("span",{className:"chat-typing",role:"img","aria-label":"Keiko is responding",children:[(0,n.jsx)("i",{}),(0,n.jsx)("i",{}),(0,n.jsx)("i",{})]})]})})}function lV({session:e,ready:t,selectedModelCapability:a,onAttachFiles:l,compact:i=!1,controlsNarrow:r=!1,barCompact:s=!1,workflowCompact:o=!1,budgetExceeded:c}){let{models:d,selectedModel:u,setSelectedModel:p,draft:m,noEligibleModels:h,loading:f,sending:g,cancelSend:v,launchWorkflowFromConversation:b}=e,x=h||c||!t,y=0===m.trim().length,w=h?lq:void 0,k=h?lq:c?aR:f?lO:y?lF:void 0,N=f||h?"":u??"",S=f?"Loading models…":h?"No conversation-eligible model":"Change model";return(0,n.jsxs)("div",{className:`cmp-bar${s?" cmp-bar-compact":""}`,children:[(0,n.jsxs)("div",{className:"cmp-bar-main",children:[(0,n.jsx)(lj,{model:a,onFiles:l,anyModelSupportsAttachments:d.some(e=>e.supportsImageInput||e.supportsDocumentInput)}),(0,n.jsx)(lS,{selectedModel:a,compact:o,launch:b}),(0,n.jsx)("div",{className:`cmp-model mono ui-tip${r?" cmp-model-compact":" cmp-pill-standard"}`,"data-tip":r?S:void 0,children:(0,n.jsx)(tz,{triggerClassName:"cmp-model-select",value:N,ariaLabel:"Models",ariaDescribedBy:w,disabled:f,placeholder:f?"Loading models…":h?"No conversation-eligible model":"Models",leadingVisual:(0,n.jsx)(j.Icons.cube,{size:r?16:13,style:{color:"var(--accent)"}}),menuTitle:"Models",menuClassName:"cmp-model-menu",menuMinWidth:r?118:280,mono:!0,sections:[{options:f?[{value:"",label:"Loading models…",disabled:!0}]:h?[{value:"",label:"No conversation-eligible model",disabled:!0}]:d.filter(e=>"chat"===e.kind).map(e=>({value:e.id,label:e.id}))}],onValueChange:e=>{h||f||p(e)}})}),null]}),k===lF?(0,n.jsx)("span",{id:lF,className:"sr-only",children:"Type a message to send"}):null,g?(0,n.jsx)("button",{type:"button",className:"cmp-send cmp-send-cancel cmp-tip-end","data-on":!0,"aria-label":"Cancel response","data-tip":"Cancel response",onClick:v,children:(0,n.jsx)(j.Icons.close,{size:16})}):(0,n.jsx)("button",{type:x?"button":"submit",className:"cmp-send cmp-tip-end","data-on":!x,"data-tip":h?"No model available":c?"Context too large":f?"Connecting to gateway":"Send message","aria-disabled":x,"aria-describedby":k,"aria-label":"Send message",children:(0,n.jsx)(j.Icons.arrowUp,{size:16})})]})}function lH(){return(0,n.jsx)("div",{id:lq,role:"alert",className:"gw-error cmp-no-model",children:"No conversation-eligible model is configured. Connect a gateway in Settings to enable chat."})}function lY(){return(0,n.jsxs)("div",{id:lO,role:"status",className:"cmp-loading-status",children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),"Connecting to your gateway…"]})}function lG({status:e}){let t=function(e){switch(e){case"idle":case"completed":case"failed":return"";case"queued":return"Submitting your message…";case"contacting":return"Contacting model…";case"streaming":return"Receiving response…";case"cancelled":return"Response cancelled."}}(e);return(0,n.jsx)("div",{role:"status","aria-live":"polite","data-send-status":e,className:"cmp-send-status",children:0===t.length?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),t]})})}function lJ({session:e,ready:t,placeholder:l,minimal:i=!1,compact:r=!1,controlsNarrow:s=!1,barCompact:o=!1,workflowCompact:c=!1}){let{draft:d,loading:u,sending:p,sendStatus:m,setDraft:h,sendMessage:f,models:g,selectedModel:v,pendingAttachments:b,addPendingAttachment:x,removePendingAttachment:y,budget:w,clearHistory:j}=e,k=nQ(w),N=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=N.current;null!==e&&(e.style.height="auto",e.style.height=`${String(Math.min(e.scrollHeight,220))}px`)},[d]);let[S,C]=(0,a.useState)(),[I,E]=(0,a.useState)(),R=g.find(e=>e.id===v),$=void 0!==R&&(R.supportsImageInput||R.supportsDocumentInput),A=(0,a.useCallback)(async e=>{let t,n;for(let a of e){let e=await x(a);e.ok||void 0!==t||(t=e.reason,n=a.type)}C(t),E(n)},[x]);return(0,n.jsxs)("div",{className:`cmp-box${r?" cmp-box-compact":""}`,children:[(0,n.jsxs)("div",{className:"cmp-input-stack",children:[(0,n.jsx)(ly,{enabled:$,onFiles:A}),(0,n.jsx)("textarea",{className:"cmp-input",ref:N,rows:2,value:d,"aria-label":"Chat message",placeholder:l,onChange:e=>h(e.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&("Enter"!==e.key||e.shiftKey||(e.preventDefault(),f()))}}),(0,n.jsx)(lx,{attachments:b,onRemove:y}),(0,n.jsx)(lk,{reason:S,mimeType:I}),(0,n.jsx)(lG,{status:m})]}),(0,n.jsxs)("div",{className:"cmp-footer-row",children:[i?null:(0,n.jsx)(aP,{budget:w,onClearHistory:j,disabled:p||u,compact:r}),(0,n.jsx)(lV,{session:e,ready:t,selectedModelCapability:R,onAttachFiles:A,compact:r,controlsNarrow:s,barCompact:o,workflowCompact:c,budgetExceeded:k})]})]})}function lX({minimal:e=!1}){return e?(0,n.jsx)("div",{className:"chatw-empty chatw-empty-minimal",role:"note","aria-label":"Conversation ready",children:(0,n.jsx)("h2",{className:"chatw-empty-headline",children:"How can I help you today?"})}):(0,n.jsx)("div",{className:"chatw-empty",children:(0,n.jsx)("h2",{className:"chatw-empty-headline",children:"How can I help you today?"})})}function lQ(){return(0,n.jsxs)("div",{className:"chatw-empty-no-chat",children:[(0,n.jsx)("div",{className:"chatw-empty-no-chat-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.spark,{size:20})}),(0,n.jsx)("p",{className:"chatw-empty-no-chat-label",children:"Pick or start a chat"}),(0,n.jsx)("p",{className:"chatw-empty-no-chat-hint",children:"Select a conversation from the project sidebar, or create a new one to get started."})]})}function lZ(e){return(void 0!==e.connectedScopes?e.connectedScopes.length:+(void 0!==e.connectedScope))+(void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes.length:+(void 0!==e.localKnowledgeScope))}function l0(e){if(lZ(e)>1)return"multi";let t=e.localKnowledgeScopes?.[0]??e.localKnowledgeScope;return t?.kind==="capsule"?`capsule:${t.capsuleId}`:t?.kind==="capsule-set"?`capsule-set:${t.capsuleSetId}`:l2(e)?"files":"none"}function l1(e){return void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes:void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[]}function l2(e){return void 0!==e&&(void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0)}function l4(e){return l2(e)||void 0!==e&&(void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0)}function l3(e){return nR(e,"Unable to update knowledge scope.")}function l6({chat:e,onChatChanged:t,catalog:l,connected:i}){let{capsules:r,capsuleSets:s,loadError:o}=l,[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(null);async function m(n){d(!0),p(null);try{if("none"===n){let n=lZ(e);if(n>0&&!window.confirm(`This will disconnect ${String(n)} grounding ${1===n?"source":"sources"}. Continue?`))return;let a=await (0,w.updateChat)(e.id,{connectedScopes:null,localKnowledgeScopes:null});t(a.chat);return}if("files"===n){let n=await (0,w.updateChat)(e.id,{localKnowledgeScopes:null});t(n.chat);return}if(n.startsWith("capsule-set:")){let a={kind:"capsule-set",capsuleSetId:n.slice(12),connectedAtMs:Date.now()},l=l1(e),i=l.some(e=>"capsule-set"===e.kind&&e.capsuleSetId===a.capsuleSetId)?l:[...l,a],r=await (0,w.updateChat)(e.id,{localKnowledgeScopes:i});t(r.chat);return}if(n.startsWith("capsule:")){let a={kind:"capsule",capsuleId:n.slice(8),connectedAtMs:Date.now()},l=l1(e),i=l.some(e=>"capsule"===e.kind&&e.capsuleId===a.capsuleId)?l:[...l,a],r=await (0,w.updateChat)(e.id,{localKnowledgeScopes:i});t(r.chat)}}catch(e){p(l3(e))}finally{d(!1)}}let h=l0(e),f=function(e,t){let n=t.map(e=>({value:`capsule:${e.id}`,label:`Knowledge capsule: ${e.displayName}`})),a=l0(e);if(!a.startsWith("capsule:")||n.some(e=>e.value===a))return n;let l=a.slice(8);return[...n,{value:a,label:`Knowledge capsule: ${l} (unavailable)`}]}(e,r),g=function(e,t){let n=t.map(e=>({value:`capsule-set:${e.id}`,label:`Capsule set: ${e.displayName}`})),a=l0(e);if(!a.startsWith("capsule-set:")||n.some(e=>e.value===a))return n;let l=a.slice(12);return[...n,{value:a,label:`Capsule set: ${l} (unavailable)`}]}(e,s),v=u??o;return(0,n.jsxs)("div",{className:"scope-grounding","data-connected":i?"true":"false",children:[(0,n.jsx)("span",{className:"scope-grounding-label mono",children:"Grounding"}),(0,n.jsx)(tz,{triggerClassName:"scope-grounding-select",value:h,disabled:c,ariaLabel:"Grounding mode",menuTitle:"Strategy",sections:[{options:[{value:"none",label:"Model only"},{value:"files",label:"Live Files context",disabled:!l2(e)},..."multi"===h?[{value:"multi",label:"Multiple sources",disabled:!0}]:[],...f.map(e=>({value:e.value,label:e.label})),...g.map(e=>({value:e.value,label:e.label}))]}],onValueChange:e=>{m(e)}}),null!==v?(0,n.jsx)("span",{role:"alert",className:"scope-connect-error",children:v}):null]})}function l5({chat:e,onChatChanged:t}){let l=function(){let[e,t]=(0,a.useState)([]),[n,l]=(0,a.useState)([]),[i,r]=(0,a.useState)(null);return(0,a.useEffect)(()=>{let e=!1;return async function(){try{let[n,a]=await Promise.allSettled([(0,lD.fetchCapsules)(),(0,lD.fetchCapsuleSets)()]);if("fulfilled"!==n.status)throw n.reason;if(e)return;t(n.value.capsules.filter(e=>"ready"===e.lifecycleState)),"fulfilled"===a.status?l(a.value.capsuleSets):(l([]),r(l3(a.reason)))}catch(t){e||r(l3(t))}}(),()=>{e=!0}},[]),{capsules:e,capsuleSets:n,loadError:i}}(),i=l4(e);return(0,n.jsx)("div",{className:"chat-scope-header","data-grounded":i?"true":"false",children:(0,n.jsx)(l6,{chat:e,onChatChanged:t,catalog:l,connected:i})})}function l8({chat:e,answer:t,busy:a,selectedModelId:l,launchGroundedWorkflowHandoff:i}){return void 0!==e&&l4(e)&&(void 0!==t||a)?(0,n.jsxs)("div",{className:"chatw-grounded",children:[(0,n.jsx)(a4,{answer:t,busy:a}),(0,n.jsx)(lA,{answer:t,modelId:l,busy:a,launch:i})]}):null}function l7({action:e,acceptCandidate:t,rejectCandidate:l,forgetMemoryAction:i,onActionSettled:r}){let[s,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(),[u,p]=(0,a.useState)(!1),m=(0,a.useCallback)((e,t,n)=>{s||(o(!0),d(void 0),e().then(()=>{r(t)}).catch(e=>{d(e instanceof Error?e.message:n)}).finally(()=>o(!1)))},[s,r]);if("candidate"===e.kind)return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:e.scopeLabel}),(0,n.jsx)("span",{children:e.requiresApproval?"Approval required":"Proposed memory"})]}),(0,n.jsx)("p",{children:e.body}),(0,n.jsxs)("div",{className:"chat-memory-action-buttons",children:[(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:()=>{m(()=>t(e.proposalId),"MemoriaViva proposal accepted.","Unable to accept memory.")},children:"Accept"}),(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:()=>{m(()=>l(e.proposalId),"MemoriaViva proposal rejected.","Unable to reject memory.")},children:"Reject"})]}),void 0!==c?(0,n.jsx)(aD,{error:c,fallback:"Unable to update memory.",onDismiss:()=>d(void 0)}):null]});if("update"===e.kind)return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:"MemoriaViva update detected"}),(0,n.jsx)("span",{children:e.memoryId})]}),(0,n.jsx)("p",{children:void 0!==e.bodyPatch?`Suggested update: ${e.bodyPatch}`:"Suggested update."})]});if("forget"===e.kind){let t=()=>{m(()=>i(e.memoryId).then(()=>p(!1)),"MemoriaViva forget action completed.","Unable to forget memory.")};return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:"MemoriaViva forget detected"}),(0,n.jsx)("span",{children:e.requiresConfirmation?"Confirmation required":e.memoryId})]}),(0,n.jsx)("p",{children:`Matched memory ${e.memoryId} for a forget operation.`}),(0,n.jsx)("div",{className:"chat-memory-action-buttons",children:e.requiresConfirmation?u?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:t,children:"Forget permanently"}),(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:()=>{s||(d(void 0),p(!1))},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:()=>{s||(d(void 0),p(!0))},children:"Review forget"}):(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:t,children:"Forget"})}),void 0!==c?(0,n.jsx)(aD,{error:c,fallback:"Unable to update memory.",onDismiss:()=>d(void 0)}):null]})}return"rejected"===e.kind?(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsx)("div",{className:"chat-memory-action-head",children:(0,n.jsx)("strong",{children:"Memory proposal declined"})}),(0,n.jsx)("p",{children:""!==e.reason?e.reason:"No reason provided"})]}):(0,n.jsx)("article",{className:"chat-memory-action",children:(0,n.jsx)("div",{className:"chat-memory-action-head",children:(0,n.jsx)("strong",{children:"MemoriaViva action not created"})})})}function l9({memoryEnabled:e,setMemoryEnabled:t,memoryBudgetTokens:l,setMemoryBudgetTokens:i,latestMemory:r,acceptCandidate:s,rejectCandidate:o,forgetMemoryAction:c,compact:d=!1}){let[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(""),f=(0,a.useId)(),g=`${f}-chat-memory-disclosure`,v=(0,a.useRef)(null),b=(0,a.useCallback)(e=>{h(e),v.current?.focus()},[]),x=r?.context.memories.length??0,y=x>0?`${String(x)} memories included`:"No memories included",w=e=>{i(Math.max(0,l+e))},k=(0,n.jsxs)("label",{className:"chat-memory-budget",children:[(0,n.jsx)("span",{children:"Budget (tokens)"}),(0,n.jsxs)("span",{className:"number-control number-control-pill",children:[(0,n.jsx)("input",{type:"number",className:"number-control-input",min:0,step:100,value:l,onChange:e=>i(Math.max(0,Number(e.target.value)||0)),onWheel:e=>{0===e.deltaY||(e.preventDefault(),w(100*(e.deltaY<0?1:-1)))}}),(0,n.jsx)(a3,{label:"memory budget",onStepUp:()=>w(100),onStepDown:()=>w(-100)})]})]});return(0,n.jsxs)("section",{className:"chat-memory-panel","aria-label":"Conversation memory",children:[(0,n.jsxs)("div",{className:"chat-memory-panel-head",children:[(0,n.jsxs)("div",{className:"chat-memory-toggle",children:[(0,n.jsx)(lM,{on:e,onChange:t,label:"Enable MemoriaViva for the next request"}),(0,n.jsxs)("span",{children:["MemoriaViva ",e?"on":"off"]})]}),d?null:k,(0,n.jsx)("button",{ref:v,type:"button",className:`chip${d?" chip-icon chat-memory-disclosure-toggle ui-tip cmp-tip-end":""}`,"aria-expanded":u,"aria-controls":g,"aria-label":y,"data-tip":d?y:void 0,onClick:()=>p(e=>!e),children:d?(0,n.jsx)(j.Icons.brainSlash,{size:16,style:{color:"var(--accent)"}}):y})]}),u?(0,n.jsxs)("div",{id:g,className:"chat-memory-disclosure",children:[(0,n.jsx)("p",{className:"chat-memory-summary",children:void 0===r?"MemoriaViva disclosure appears after the next response.":r.context.enabled?`Used ${String(r.context.budget.used)} of ${String(r.context.budget.tokens)} MemoriaViva tokens.`:"MemoriaViva was disabled for the last request."}),r?.context.memories.map(e=>(0,n.jsxs)("article",{className:"chat-memory-item",children:[(0,n.jsxs)("div",{className:"chat-memory-item-head",children:[(0,n.jsx)("strong",{children:e.memoryId}),(0,n.jsx)("span",{children:e.inclusionReason})]}),(0,n.jsx)("p",{children:e.bodyExcerpt}),(0,n.jsxs)("dl",{className:"chat-memory-meta","aria-label":`Provenance for ${e.memoryId}`,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Source"}),(0,n.jsx)("dd",{children:e.sourceKind})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Sensitivity"}),(0,n.jsx)("dd",{children:e.sensitivity})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Status"}),(0,n.jsx)("dd",{children:e.status})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Confidence"}),(0,n.jsx)("dd",{children:`${String(Math.round(100*e.confidence))}%`})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Captured"}),(0,n.jsx)("dd",{children:new Date(e.capturedAt).toISOString().slice(0,10)})]})]}),void 0!==e.captureRationale?(0,n.jsx)("p",{className:"chat-memory-rationale",children:e.captureRationale}):null]},e.memoryId)),r?.actions.map(e=>(0,n.jsx)(l7,{action:e,acceptCandidate:s,rejectCandidate:o,forgetMemoryAction:c,onActionSettled:b},"candidate"===e.kind?e.proposalId:"rejected"===e.kind?e.reason:e.memoryId)),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:m})]}):null]})}function ie({mini:e=!1,minimalChat:t=!1,compact:l=!1,controlsNarrow:i=!1,barCompact:s=!1,workflowCompact:o=!1,onOpenRunResult:c}){let d=r(),{messages:u,draft:p,loading:m,sending:h,sendStatus:f,error:g,noEligibleModels:v,selectedModel:b,sendMessage:x,cancelGrounded:y,activeChat:w,replaceChat:j,latestGrounded:k,latestMemory:N,lastSentDocuments:S,memoryEnabled:C,setMemoryEnabled:I,memoryBudgetTokens:E,setMemoryBudgetTokens:R,acceptMemoryCandidate:$,rejectMemoryCandidate:A,launchGroundedWorkflowHandoff:T,forgetMemoryAction:L}=d,P=p.trim().length>0&&!h&&!m&&!v,M=u.filter(e=>"user"===e.role||"assistant"===e.role&&e.content.length>0||lL(e)),D=(0,a.useRef)(null),q=(0,a.useRef)(!0),F=(0,a.useRef)(!1),O=M.length>0?M[M.length-1]:void 0,z=void 0===O?"":O.content,K=l||e,B=i||e||t||o,_=s||t,U=o||e||t;return(0,a.useEffect)(()=>{h&&!F.current&&(q.current=!0),F.current=h;let e=D.current;null!==e&&q.current&&(e.scrollTop=e.scrollHeight)},[M.length,h,z]),(0,n.jsxs)("div",{className:`chatw${K?" chatw-compact":""}${t?" chatw-minimal":""}`,children:[void 0!==w?(0,n.jsx)(l5,{chat:w,onChatChanged:j}):null,void 0!==w?(0,n.jsx)(l9,{memoryEnabled:C,setMemoryEnabled:I,memoryBudgetTokens:E,setMemoryBudgetTokens:R,latestMemory:N,acceptCandidate:$,rejectCandidate:A,forgetMemoryAction:L,compact:K||t}):null,v?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(lH,{})}):null,m?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(lY,{})}):null,(0,n.jsx)("div",{className:"chatw-scroll",ref:D,role:"log","aria-label":"Conversation",tabIndex:0,onScroll:e=>{let t=e.currentTarget;q.current=t.scrollHeight-t.scrollTop-t.clientHeight<64},children:0===M.length?void 0!==w?(0,n.jsx)(lX,{minimal:t}):(0,n.jsx)(lQ,{}):(0,n.jsxs)("div",{className:"chatw-log",children:[M.map((e,t)=>(0,n.jsx)(l_,{message:e,onOpenRunResult:c,streaming:"streaming"===f&&t===M.length-1&&"assistant"===e.role},e.id)),h&&"streaming"!==f?(0,n.jsxs)("div",{className:"chatw-typing-row",children:[(0,n.jsx)(lW,{}),l4(w)?(0,n.jsx)("button",{type:"button",className:"grounded-cancel-btn","aria-label":"Cancel grounded request",onClick:y,children:"Cancel"}):null]}):null,(0,n.jsx)(l8,{chat:w,answer:k,busy:h,selectedModelId:b,launchGroundedWorkflowHandoff:T}),(0,n.jsx)(lN,{documents:S})]})}),M.length>0?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:`composer${K?" composer-chat-compact":""}`,onSubmit:e=>{e.preventDefault(),x()},children:[(0,n.jsx)(lJ,{session:d,ready:P,placeholder:lz,minimal:t,compact:K,controlsNarrow:B,barCompact:_,workflowCompact:U}),void 0!==g?(0,n.jsx)(aD,{error:g,fallback:"Could not send message.",onDismiss:d.clearError}):null]})}):null,0===M.length&&void 0!==w?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:`composer${K?" composer-chat-compact":""}`,onSubmit:e=>{e.preventDefault(),x()},children:[(0,n.jsx)(lJ,{session:d,ready:P,placeholder:m?"Connecting to your gateway…":lz,minimal:t,compact:K,controlsNarrow:B,barCompact:_,workflowCompact:U}),void 0!==g?(0,n.jsx)(aD,{error:g,fallback:"Could not send message.",onDismiss:d.clearError}):null]})}):null,0===M.length&&void 0!==g&&void 0===w?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(aD,{error:g,fallback:"Could not load chat.",onDismiss:d.clearError})}):null]})}let it=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function ia(e){return Array.from(e.querySelectorAll("button[role='treeitem']"))}function il({project:e,activeProjectPath:t,chats:l,activeChatId:i,onProject:r,onChat:s,treeRef:o}){let c=t===e.path,[d,u]=(0,a.useState)(c),p=e.available?"Available":"Unavailable";return(0,a.useEffect)(()=>{c&&u(!0)},[c]),(0,n.jsxs)("div",{className:"proj",children:[(0,n.jsxs)("button",{className:"proj-head",type:"button",role:"treeitem","aria-level":1,"aria-expanded":d,"aria-selected":c,"data-active":c?"true":"false","aria-current":c?"true":void 0,"aria-label":`${e.name} (${p})`,tabIndex:c?0:-1,onClick:()=>{u(e=>!e),r(e),null!==o.current&&ia(o.current).forEach(e=>{e.tabIndex=-1})},children:[(0,n.jsx)("span",{className:"proj-caret","data-open":d,"aria-hidden":"true",children:(0,n.jsx)(j.Icons.chevronR,{size:13})}),(0,n.jsx)(j.Icons.folder,{size:15,"aria-hidden":"true"}),(0,n.jsx)("span",{className:"proj-name",children:e.name}),(0,n.jsx)("span",{className:"chat-time",children:p})]}),d&&(0,n.jsx)("div",{className:"proj-chats",role:"group","aria-label":e.name,children:c?0===l.length?(0,n.jsx)("div",{className:"proj-empty",children:"No chats"}):l.map(e=>(0,n.jsxs)("button",{type:"button",role:"treeitem","aria-level":2,"aria-selected":i===e.id,className:"chat-row","data-active":i===e.id,tabIndex:-1,onClick:()=>{s(e)},children:[(0,n.jsx)("span",{className:"chat-title",children:e.title}),void 0!==e.branchLabel?(0,n.jsx)("span",{className:"chat-meta mono",children:e.branchLabel}):null]},e.id)):(0,n.jsx)("div",{className:"proj-empty",children:"Select project to load chats"})})]})}function ii(){let e=r(),t=(0,a.useRef)(null);return(0,n.jsxs)("div",{className:"tw-scroll",children:[(0,n.jsx)("div",{className:"sb-section",children:(0,n.jsx)("span",{className:"sb-section-label",children:"Projects"})}),0===e.projects.length?(0,n.jsx)("div",{className:"proj-empty",children:"No registered projects"}):(0,n.jsx)("div",{className:"proj-tree",role:"tree","aria-label":"Projects",tabIndex:-1,ref:t,onKeyDown:e=>{it.has(e.key)&&null!==t.current&&function(e,t){let n=ia(t),a=e.target;if(!(a instanceof HTMLElement))return;let l=a.closest("button[role='treeitem']");if(null===l)return;let i=n.indexOf(l);if(i<0)return;e.preventDefault();let r=e.key;if("ArrowDown"===r)n[i+1]?.focus();else if("ArrowUp"===r)n[i-1]?.focus();else if("Home"===r)n[0]?.focus();else if("End"===r)n[n.length-1]?.focus();else if("ArrowRight"===r)"false"===l.getAttribute("aria-expanded")?l.click():"true"===l.getAttribute("aria-expanded")&&n[i+1]?.focus();else if("ArrowLeft"===r)if("true"===l.getAttribute("aria-expanded"))l.click();else{let e=Number(l.getAttribute("aria-level")??"1");for(let t=i-1;t>=0;t-=1)if(Number(n[t]?.getAttribute("aria-level")??"1")<e){n[t]?.focus();break}}}(e,t.current)},children:e.projects.map(a=>(0,n.jsx)(il,{project:a,activeProjectPath:e.activeProject?.path,chats:e.activeProject?.path===a.path?e.chats:[],activeChatId:e.activeChat?.id,treeRef:t,onProject:t=>{e.openProject(t)},onChat:t=>{e.openChat(t)}},a.path))})]})}function ir({openChatWindow:e}){let t=r(),[l,i]=(0,a.useState)(""),[s,o]=(0,a.useState)("active"),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(""),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(null),k=(0,a.useRef)(null),N=(0,a.useId)(),S=(0,a.useId)(),C=(0,a.useId)(),I=(0,a.useId)(),E=(0,a.useMemo)(()=>t.chats.filter(e=>"closed"!==e.status).length,[t.chats]),R=t.chats.length-E,$=(0,a.useMemo)(()=>[...t.chats].sort((e,t)=>t.updatedAt-e.updatedAt).filter(e=>"deleted"===s?"closed"===e.status:"closed"!==e.status).filter(e=>{let t;return 0===(t=l.trim().toLowerCase()).length||e.title.toLowerCase().includes(t)||e.selectedModel.toLowerCase().includes(t)||(e.branchLabel?.toLowerCase().includes(t)??!1)}),[l,t.chats,s]);(0,a.useEffect)(()=>{null!==c&&k.current?.focus({preventScroll:!0})},[c]);let A=async()=>{b(null);let n=await t.openNewChat(void 0,"New chat");void 0!==n&&e(n)},T=e=>{d(e.id),p(e.title),h(null),b(null),y(null)},L=async e=>{let n=u.trim();if(0===n.length){y("Title cannot be empty."),k.current?.focus({preventScroll:!0});return}if(n===e.title){d(null),y(null);return}g(e.id),b(null),y(null);try{let a=await (0,w.updateChat)(e.id,{title:n});t.replaceChat(a.chat),d(null)}catch{b("Rename failed.")}finally{g(null)}},P=async e=>{g(e.id),b(null);try{let n=await (0,w.updateChat)(e.id,{status:"closed"});t.replaceChat(n.chat),h(null)}catch(t){let e=t instanceof Error?t.message:"Request failed.";b(`Delete failed: ${e}`)}finally{g(null)}},M=async e=>{g(e.id),b(null);try{let n=await (0,w.updateChat)(e.id,{status:"open"});t.replaceChat(n.chat),h(null)}catch(t){let e=t instanceof Error?t.message:"Request failed.";b(`Restore failed: ${e}`)}finally{g(null)}};return(0,n.jsxs)("div",{className:"chat-history",children:[(0,n.jsxs)("div",{className:"chat-history-head",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"chat-history-kicker",children:"Conversations"}),(0,n.jsx)("h2",{children:"Chat History"})]}),(0,n.jsxs)("button",{type:"button",className:"lk-btn lk-btn-primary",onClick:()=>void A(),children:[(0,n.jsx)(j.Icons.newChat,{size:15}),"New"]})]}),(0,n.jsxs)("label",{className:"chat-history-search",children:[(0,n.jsx)(j.Icons.search,{size:15}),(0,n.jsx)("input",{value:l,onChange:e=>i(e.target.value),placeholder:"Search","aria-label":"Search chat history"})]}),(0,n.jsxs)("div",{className:"chat-history-tabs",role:"tablist","aria-label":"Conversation state",children:[(0,n.jsxs)("button",{type:"button",id:N,role:"tab","aria-selected":"active"===s,"aria-controls":C,className:"chat-history-tab",onClick:()=>{o("active"),h(null)},children:["Active ",(0,n.jsx)("span",{children:E})]}),(0,n.jsxs)("button",{type:"button",id:S,role:"tab","aria-selected":"deleted"===s,"aria-controls":C,className:"chat-history-tab",onClick:()=>{o("deleted"),h(null)},children:["Deleted ",(0,n.jsx)("span",{children:R})]})]}),null!==v?(0,n.jsx)("div",{className:"lk-alert",role:"alert",children:v}):null,(0,n.jsx)("div",{id:C,className:"chat-history-list",role:"tabpanel","aria-labelledby":"active"===s?N:S,children:0===$.length?(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-title",children:"No conversations"})}):$.map(t=>{var a;let l=e3(t).length+e6(t).length,i=c===t.id,r=m===t.id,s=f===t.id,o="closed"===t.status;return(0,n.jsxs)("article",{className:"chat-history-row","data-chat-id":t.id,"data-state":o?"deleted":"active",children:[(0,n.jsx)("div",{className:"chat-history-row-main",children:i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{ref:k,className:"chat-history-title-input",value:u,"aria-invalid":null!==x,"aria-describedby":null!==x?I:void 0,onChange:e=>{p(e.target.value),null!==x&&y(null)},onKeyDown:e=>{"Enter"===e.key&&L(t),"Escape"===e.key&&(d(null),y(null))}}),null!==x?(0,n.jsx)("span",{id:I,className:"chat-history-rename-error",role:"alert",children:x}):null]}):(0,n.jsxs)("button",{type:"button",className:"chat-history-open",disabled:o,onClick:()=>e(t),children:[(0,n.jsx)("span",{className:"chat-history-title",children:t.title}),(0,n.jsxs)("span",{className:"chat-history-meta",children:[(a=t.updatedAt,new Intl.DateTimeFormat(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(a)))," / ",t.selectedModel,l>0?` / ${String(l)} sources`:""]})]})}),(0,n.jsx)("div",{className:"chat-history-actions",children:i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary",disabled:s,onClick:()=>void L(t),children:"Save"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:s,onClick:()=>{d(null),y(null)},children:"Cancel"})]}):r?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",disabled:s,onClick:()=>void P(t),children:"Delete"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:s,onClick:()=>h(null),children:"Cancel"})]}):o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:"lk-btn lk-btn-primary",disabled:s,onClick:()=>void M(t),children:[(0,n.jsx)(j.Icons.restore,{size:14}),"Restore"]}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>T(t),children:"Rename"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>T(t),children:"Rename"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>{h(t.id),d(null)},children:"Delete"})]})})]},t.id)})})]})}function is(){let e=s(),t=e?.activeProject?.name??"No project selected",l=(0,a.useId)();return(0,n.jsxs)("div",{className:"srch",children:[(0,n.jsxs)("div",{className:"srch-box",children:[(0,n.jsx)(j.Icons.search,{size:15,"aria-hidden":"true"}),(0,n.jsx)("input",{type:"search","aria-label":"Search files and symbols","aria-describedby":l,placeholder:"Search files & symbols…",disabled:!0})]}),(0,n.jsxs)("div",{className:"tw-label srch-label",children:[t," ",(0,n.jsx)("span",{className:"srch-meta mono",children:"workspace search"})]}),(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsxs)("div",{className:"rb-placeholder",style:{height:150},children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)("span",{className:"rb-ph-label mono",children:"search"})]}),(0,n.jsx)("div",{id:l,className:"rb-foot mono",style:{marginTop:14},children:"Search across workspace files & symbols — coming soon."})]})]})}let io=[{value:"auto",label:"Auto (recommended)"},{value:"fast",label:"Fast"},{value:"precise",label:"Precise"},{value:"research",label:"Research"},{value:"creative",label:"Creative"},{value:"technical",label:"Technical"},{value:"safety-critical",label:"Safety-critical"},{value:"agentic",label:"Agentic"}],ic=[{value:"clarify",label:"Ask clarifying questions"},{value:"assume",label:"State explicit assumptions"}],id="__none__";function iu({items:e,empty:t}){return 0===e.length?void 0===t?null:(0,n.jsx)("p",{className:"pe-empty",children:t}):(0,n.jsx)("ul",{className:"pe-list",children:e.map((e,t)=>(0,n.jsx)("li",{children:e},`${String(t)}:${e.slice(0,24)}`))})}function ip({title:e,children:t}){return(0,n.jsxs)("section",{className:"pe-section","aria-label":e,children:[(0,n.jsx)("h4",{className:"pe-section-title",children:e}),t]})}function im({routing:e}){let t="available"===e.availability?"ok":"unavailable"===e.availability?"warn":"muted",a="available"===e.availability?`Model ready: ${e.resolvedModelId??""}`:"unavailable"===e.availability?"Selected model unavailable — enhancement still completed deterministically":"No downstream model selected — enhancement is provider-neutral";return(0,n.jsx)("p",{className:`pe-routing pe-routing-${t}`,"data-testid":"pe-model-routing",role:"status","aria-live":"polite",children:a})}function ih({safety:e}){let t=e.requiresHumanReview;return(0,n.jsxs)(ip,{title:"Safety",children:[(0,n.jsxs)("p",{className:"pe-safety-summary","data-testid":"pe-safety-decision",children:["Decision: ",(0,n.jsx)("strong",{children:e.decision})," · verification: ",e.verificationStatus," ·"," ","human review: ",(0,n.jsx)("strong",{children:t?"required":"not required"})]}),t?(0,n.jsx)("p",{className:"pe-safety-warning",role:"alert",children:"This prompt requires human review before any downstream use."}):null,e.findings.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"pe-subhead",children:"Safety findings"}),(0,n.jsx)("ul",{className:"pe-list","data-testid":"pe-safety-findings",children:e.findings.map(e=>(0,n.jsxs)("li",{children:[(0,n.jsx)("span",{className:`pe-sev pe-sev-${e.severity}`,children:e.severity})," ",e.detail]},`${e.ruleId}:${e.code}`))})]}):null,e.leastPrivilege.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"pe-subhead",children:"Least-privilege constraints"}),(0,n.jsx)(iu,{items:[...e.leastPrivilege]})]}):null]})}function ig({plan:e,readiness:t}){let a="ready"===t.status?"Grounding readiness: connected context available":"unavailable"===t.status?`Grounding readiness: unavailable${void 0===t.notice?"":` — ${t.notice}`}`:"Grounding readiness: not required";return(0,n.jsxs)(ip,{title:"Grounding plan",children:[(0,n.jsx)("p",{className:`pe-grounding-readiness pe-grounding-readiness-${t.status}`,"data-testid":"pe-grounding-readiness",role:"unavailable"===t.status?"alert":"status","aria-live":"polite",children:a}),(0,n.jsxs)("p",{className:"pe-grounding-meta",children:["Strategy: ",(0,n.jsx)("strong",{children:e.strategy})," · ",e.required?"required":"optional"," · citations: ",e.citation.discipline," (",e.citation.granularity,")"]}),e.sourcePriority.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"pe-subhead",children:"Source priority"}),(0,n.jsx)("ol",{className:"pe-list",children:e.sourcePriority.map(e=>(0,n.jsxs)("li",{children:[e.source,e.required?" (required)":""]},e.source))})]}):null,(0,n.jsx)(iu,{items:[...e.directives]})]})}function iv({evidence:e,fingerprint:t}){return(0,n.jsxs)("p",{className:"pe-evidence","data-testid":"pe-evidence",children:["Evidence fingerprint: ",t.slice(0,16),"…","recorded"===e.status&&void 0!==e.runId?(0,n.jsxs)(n.Fragment,{children:[" ","Manifest:"," ",(0,n.jsx)("a",{href:e.manifestUrl??"#",target:"_blank",rel:"noreferrer","aria-label":`Prompt enhancement evidence manifest ${e.runId}`,children:e.runId})]}):" Manifest not recorded."]})}function ib({candidates:e}){return(0,n.jsx)(ip,{title:"Candidate scorecards",children:(0,n.jsx)("div",{className:"c-tablewrap",children:(0,n.jsx)("div",{className:"c-tablescroll",children:(0,n.jsxs)("table",{className:"c-table pe-scorecards","data-testid":"pe-scorecards",children:[(0,n.jsx)("thead",{children:(0,n.jsxs)("tr",{children:[(0,n.jsx)("th",{scope:"col",children:"Profile"}),(0,n.jsx)("th",{scope:"col",className:"num",children:"Score"}),(0,n.jsx)("th",{scope:"col",className:"num",children:"Tokens"}),(0,n.jsx)("th",{scope:"col",children:"Winner"})]})}),(0,n.jsx)("tbody",{children:e.scorecards.map(t=>{let a=t.candidateId===e.winnerCandidateId;return(0,n.jsxs)("tr",{className:a?"pe-winner":void 0,children:[(0,n.jsx)("th",{scope:"row",children:t.profile}),(0,n.jsx)("td",{className:"num",children:t.aggregateScore.toFixed(3)}),(0,n.jsx)("td",{className:"num",children:t.estimatedTokens}),(0,n.jsx)("td",{children:a?"★":""})]},t.candidateId)})})]})})})})}function ix({result:e}){let t=e.enhancedPrompt,a=e.analysis.missingContext.map(e=>"assumption"===e.kind?e.statement:e.question);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ip,{title:"Role",children:(0,n.jsx)("p",{children:t.role})}),(0,n.jsx)(ip,{title:"Objective",children:(0,n.jsx)("p",{children:t.goal})}),(0,n.jsx)(ip,{title:"Context",children:(0,n.jsx)(iu,{items:[...t.context],empty:"No additional context."})}),(0,n.jsx)(ip,{title:e.analysis.missingContext.some(e=>"assumption"===e.kind)?"Assumptions":"Clarification questions",children:(0,n.jsx)(iu,{items:a,empty:"No clarifications or assumptions needed."})}),(0,n.jsx)(ip,{title:"Steps",children:(0,n.jsx)(iu,{items:[...t.taskDecomposition]})}),(0,n.jsx)(ip,{title:"Constraints",children:(0,n.jsx)(iu,{items:[...t.constraints]})}),(0,n.jsxs)(ip,{title:"Output schema",children:[(0,n.jsxs)("p",{children:["Format: ",(0,n.jsx)("strong",{children:t.outputSchema.format}),t.outputSchema.structured?" · structured":""]}),(0,n.jsx)(iu,{items:[...t.outputSchema.hints]})]}),(0,n.jsx)(ip,{title:"Quality criteria",children:(0,n.jsx)(iu,{items:[...t.qualityCriteria]})}),(0,n.jsx)(ip,{title:"Uncertainty handling",children:(0,n.jsx)(iu,{items:[...t.uncertaintyHandling]})}),(0,n.jsx)(ip,{title:"Safety rules",children:(0,n.jsx)(iu,{items:[...t.safetyRules]})})]})}function iy({enhanceImpl:e=w.enhancePrompt,fetchModelsImpl:t=w.fetchModels}={}){let[l,i]=(0,a.useState)(""),[r,s]=(0,a.useState)("auto"),[o,c]=(0,a.useState)("clarify"),[d,u]=(0,a.useState)(id),[p,m]=(0,a.useState)([]),[h,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(!1),[b,x]=(0,a.useState)(null),[y,j]=(0,a.useState)(!1),[k,N]=(0,a.useState)(null),S=(0,a.useRef)(null),C=(0,a.useId)(),I=(0,a.useId)();(0,a.useEffect)(()=>{let e=!1;return t().then(t=>{e||m(t.models.filter(e=>"chat"===e.kind))}).catch(()=>{}),()=>{e=!0}},[t]),(0,a.useEffect)(()=>()=>{S.current?.abort()},[]);let E=(0,a.useCallback)(async()=>{let t=l.trim();if(0===t.length)return void x("Enter a prompt draft to enhance.");S.current?.abort();let n=new AbortController;S.current=n,v(!0),x(null),j(!1),N(null);let a={text:t,missingInformationStrategy:"assume"===o?"assume":"clarify",..."auto"===r?{}:{profilePreference:r},...d===id?{}:{modelId:d}};try{let t=await e(a,n.signal);n.signal.aborted||f(t)}catch(e){n.signal.aborted||x(e instanceof w.ApiError?`${e.message} (${e.code})`:e instanceof Error&&"AbortError"===e.name?"Request cancelled.":"Prompt enhancement failed. Please try again.")}finally{n.signal.aborted||v(!1)}},[l,o,r,d,e]),R=(0,a.useCallback)(async()=>{if(null===h)return;let e=navigator.clipboard?.writeText;if(void 0===e)return void x("Clipboard is not available in this browser.");try{await e.call(navigator.clipboard,h.renderedPrompt),j(!0),N("Rendered prompt copied to clipboard.")}catch{x("Could not copy to the clipboard.")}},[h]),$=[{options:[{value:id,label:"Deterministic only (no model)"},...p.map(e=>({value:e.id,label:e.id}))]}];return(0,n.jsxs)("div",{className:"pe-panel","data-testid":"prompt-enhancer-panel",children:[(0,n.jsx)("h3",{className:"pe-title",children:"Prompt Enhancer"}),(0,n.jsx)("p",{className:"pe-intro",children:"Turn a raw prompt into a governed, structured Enhanced Prompt. The result is for review and copy/export — it is never executed from here."}),(0,n.jsxs)("div",{className:"pe-form",children:[(0,n.jsx)("label",{className:"pe-label",htmlFor:C,children:"Raw prompt"}),(0,n.jsx)("textarea",{id:C,className:"pe-draft",value:l,onChange:e=>{i(e.target.value)},rows:5,placeholder:"Describe the task you want a strong prompt for…","aria-describedby":null===b?void 0:I}),(0,n.jsxs)("div",{className:"pe-controls",children:[(0,n.jsxs)("div",{className:"pe-control",children:[(0,n.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Profile"}),(0,n.jsx)(tz,{value:r,ariaLabel:"Profile",onValueChange:s,sections:[{options:io.map(e=>({...e}))}]})]}),(0,n.jsxs)("div",{className:"pe-control",children:[(0,n.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Missing information"}),(0,n.jsx)(tz,{value:o,ariaLabel:"Missing information",onValueChange:c,sections:[{options:ic.map(e=>({...e}))}]})]}),(0,n.jsxs)("div",{className:"pe-control",children:[(0,n.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Readiness model"}),(0,n.jsx)(tz,{value:d,ariaLabel:"Readiness model",onValueChange:u,sections:$})]})]}),(0,n.jsx)("button",{type:"button",className:"pe-enhance",onClick:()=>{E()},disabled:g||0===l.trim().length,children:g?"Enhancing…":"Enhance prompt"}),g?(0,n.jsx)("p",{className:"pe-status",role:"status","aria-live":"polite",children:"Enhancing prompt…"}):null]}),null!==b?(0,n.jsx)("p",{className:"pe-error",role:"alert",id:I,children:b}):null,null!==h?(0,n.jsxs)("div",{className:"pe-result","data-testid":"pe-result",children:[(0,n.jsx)(im,{routing:h.modelRouting}),(0,n.jsxs)("p",{className:"pe-analysis",children:["Task: ",(0,n.jsx)("strong",{children:h.analysis.taskClass})," · domain: ",h.analysis.domain," · criticality: ",h.analysis.criticality]}),(0,n.jsx)(ih,{safety:h.safety}),(0,n.jsx)(ix,{result:h}),(0,n.jsx)(ig,{plan:h.enhancedPrompt.groundingPlan,readiness:h.groundingReadiness}),(0,n.jsx)(ib,{candidates:h.candidates}),(0,n.jsxs)(ip,{title:"Rendered prompt",children:[(0,n.jsx)("pre",{className:"pe-rendered","aria-label":"Rendered prompt text",children:h.renderedPrompt}),(0,n.jsx)("div",{className:"pe-actions",children:(0,n.jsx)("button",{type:"button",className:"pe-copy",onClick:()=>{R()},children:"Copy rendered prompt"})}),y&&null!==k?(0,n.jsx)("p",{className:"pe-status",role:"status","aria-live":"polite",children:k}):null]}),(0,n.jsx)(iv,{evidence:h.evidence,fingerprint:h.inputFingerprintSha256})]}):null]})}let iw=[{name:"Context7",img:"upstash",desc:"Up-to-date library docs",on:!0},{name:"Sequential Thinking",icon:"layers",desc:"Step-by-step reasoning",on:!0},{name:"Filesystem",icon:"files",desc:"Local file access",on:!0},{name:"GitHub",img:"github",desc:"Repos · PRs · issues",on:!0},{name:"Playwright",img:"playwright",desc:"Browser automation",on:!1},{name:"Brave Search",img:"brave",desc:"Web search",on:!1},{name:"MemoriaViva",icon:"cube",desc:"Knowledge graph",on:!0}],ij=[{name:"GitHub",img:"github",on:!0},{name:"Linear",img:"linear",on:!0},{name:"PostgreSQL",img:"postgresql",on:!0},{name:"Sentry",img:"sentry",on:!1},{name:"Slack",img:"slack",on:!1},{name:"Notion",img:"notion",on:!1}];function ik({img:e,icon:t,glyph:a}){if(void 0!==e)return(0,n.jsx)("img",{className:"pl-img",src:`/assets/icons/${e}.svg`,width:"20",height:"20",alt:""});if(void 0!==t){let e=j.Icons[t];return(0,n.jsx)("span",{className:"pl-line",children:(0,n.jsx)(e,{size:18})})}return(0,n.jsx)("span",{className:"mono pl-glyph",children:a})}function iN(){let[e,t]=(0,a.useState)(iw.map(e=>e.on)),l=e.filter(Boolean).length;return(0,n.jsxs)("div",{className:"plg",children:[(0,n.jsxs)("div",{className:"plg-sec",children:[(0,n.jsx)("span",{className:"plg-sec-t",children:"MCP Servers"}),(0,n.jsxs)("span",{className:"plg-sec-c mono",children:[l,"/",iw.length," active"]})]}),iw.map((a,l)=>{let i=e[l]??!1;return(0,n.jsxs)("div",{className:"plg-row",children:[(0,n.jsx)("span",{className:"plg-ico",children:(0,n.jsx)(ik,{img:a.img,icon:a.icon})}),(0,n.jsxs)("span",{className:"plg-text",children:[(0,n.jsx)("span",{className:"plg-name",children:a.name}),(0,n.jsx)("span",{className:"plg-desc",children:a.desc})]}),(0,n.jsx)("button",{className:`plg-dot${i?" on":""}`,title:i?"Running":"Stopped","aria-label":`${a.name}: ${i?"running":"stopped"}`,onClick:()=>{t(e=>{let t=[...e];return t[l]=!t[l],t})}})]},a.name)}),(0,n.jsx)("div",{className:"plg-sec plg-sec2",children:(0,n.jsx)("span",{className:"plg-sec-t",children:"Connectors"})}),ij.map(e=>(0,n.jsxs)("button",{className:"plg-row plg-conn","data-on":e.on,children:[(0,n.jsx)("span",{className:"plg-ico",children:(0,n.jsx)(ik,{img:e.img})}),(0,n.jsxs)("span",{className:"plg-text",children:[(0,n.jsx)("span",{className:"plg-name",children:e.name}),(0,n.jsx)("span",{className:"plg-desc",children:e.on?"Connected":"Not connected"})]}),e.on?(0,n.jsx)("span",{className:"integ-on",children:(0,n.jsx)(j.Icons.check,{size:13})}):(0,n.jsx)("span",{className:"integ-add",children:(0,n.jsx)(j.Icons.plus,{size:14})})]},e.name))]})}let iS=[{id:"nightly-review",name:"Nightly review",when:"02:00 daily",defaultOn:!0},{id:"on-push-lint",name:"On push → lint",when:"git push",defaultOn:!0},{id:"weekly-digest",name:"Weekly digest",when:"Mon 09:00",defaultOn:!1}],iC="keiko.automations.v1",iI=Object.fromEntries(iS.map(e=>[e.id,e.defaultOn]));function iE(){try{let e=localStorage.getItem(iC);if(null===e)return{...iI};let t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))return{...iI};let n={...iI};for(let[e,a]of Object.entries(t))e in iI&&"boolean"==typeof a&&(n[e]=a);return n}catch{return{...iI}}}function iR(){let[e,t]=(0,a.useState)(iE);return(0,n.jsx)("div",{className:"tw-list",children:iS.map(a=>{let l=e[a.id]??a.defaultOn;return(0,n.jsxs)("div",{className:"auto-row",children:[(0,n.jsx)("span",{className:"dot",style:{background:l?"var(--accent)":"var(--fg-faint)"}}),(0,n.jsxs)("span",{className:"auto-text",children:[(0,n.jsx)("span",{className:"auto-name",children:a.name}),(0,n.jsx)("span",{className:"auto-when mono",children:a.when})]}),(0,n.jsx)(lM,{on:l,onChange:()=>{var e;e=a.id,t(t=>{let n={...t,[e]:!t[e]};try{localStorage.setItem(iC,JSON.stringify(n))}catch{}return n})},label:a.name})]},a.id)})})}function i$(){return(0,n.jsxs)("div",{className:"tw-pad mob",children:[(0,n.jsxs)("div",{className:"mob-qr",children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)(j.Icons.mobile,{size:28,style:{position:"relative",color:"var(--fg-dim)"}})]}),(0,n.jsx)("div",{className:"mob-title",children:"Keiko Mobile"}),(0,n.jsx)("div",{className:"mob-sub",children:"Scan to continue this workspace on your phone."})]})}function iA(){var e;let t,{wins:l,active:i,winCount:r}=(0,a.useContext)(y),s=null!==i?E[i.type]:null,o=null!==i?Object.entries(i.cfg).filter(([,e])=>""!==e&&null!=e):[];return(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsx)("div",{className:"rb-section-label",style:{marginTop:0},children:"Active window"}),null!==i&&null!==s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"insp-top",children:[(0,n.jsx)("span",{className:"insp-ico",style:{color:!0===s.accent?"var(--accent)":"var(--fg-muted)"},children:(e=s.icon,t=j.Icons[e],(0,n.jsx)(t,{size:16}))}),(0,n.jsx)("span",{className:"insp-title",children:s.title})]}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Size"}),(0,n.jsxs)("span",{className:"rb-row-v mono",children:[Math.round(i.w)," × ",Math.round(i.h)]})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Position"}),(0,n.jsxs)("span",{className:"rb-row-v mono",children:[Math.round(i.x),", ",Math.round(i.y)]})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"State"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:i.max?"maximized":"floating"})]})]}),o.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"rb-section-label",children:"Configuration"}),(0,n.jsx)("div",{className:"rb-rows",children:o.map(([e,t])=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:e}),(0,n.jsx)("span",{className:"rb-row-v mono",children:String(t).slice(0,20)||"—"})]},e))})]}),(0,n.jsx)("div",{className:"rb-section-label insp-governance",children:"Governance"}),(0,n.jsxs)("div",{className:"rb-rows insp-governance","data-testid":"insp-governance",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Authority"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eT[i.type].authority})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Persistence"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eT[i.type].persistence})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Trust"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eT[i.type].trustBoundary.join(", ")})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Lifecycle"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eT[i.type].lifecycle.join(" → ")})]})]})]}):(0,n.jsx)("div",{className:"insp-empty",children:"No window focused"}),(0,n.jsx)("div",{className:"rb-section-label",children:"Workspace"}),(0,n.jsx)("div",{className:"rb-rows",children:(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Open windows"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:r})]})})]})}let iT=[{t:"Agent finished build-board",time:"2m",c:"var(--accent)"},{t:"diff-review ready to merge",time:"9m",c:"var(--info)"},{t:"lint-pass queued",time:"14m",c:"var(--fg-faint)"}];function iL(){return(0,n.jsx)("ul",{className:"tw-list",children:iT.map((e,t)=>(0,n.jsxs)("li",{className:"nt-row",children:[(0,n.jsx)("span",{className:"dot",style:{background:e.c,marginTop:6},"aria-hidden":"true"}),(0,n.jsxs)("span",{className:"nt-text",children:[(0,n.jsx)("span",{className:"nt-title",children:e.t}),(0,n.jsxs)("span",{className:"nt-time mono",children:[e.time," ago"]})]})]},t))})}function iP(){return(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsxs)("div",{className:"rb-placeholder",style:{height:150},children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)("span",{className:"rb-ph-label mono",children:"resources"})]}),(0,n.jsx)("div",{className:"rb-foot mono",style:{marginTop:14},children:"Shared assets & references — coming soon."})]})}let iM="keiko-activity",iD={step:"var(--fg-dim)",approval:"var(--warn)",approved:"var(--accent)",rejected:"var(--danger)",stopped:"var(--danger)",open:"var(--info)","twin-approved":"var(--accent)","twin-denied":"var(--danger)"};function iq(){let e=function(){let[,e]=(0,a.useState)(0);return(0,a.useEffect)(()=>{let t=()=>{e(e=>e+1)};return window.addEventListener(iM,t),()=>{window.removeEventListener(iM,t)}},[]),window.__keikoActivity??[]}();return(0,n.jsxs)("div",{className:"tl",role:"log","aria-label":"Activity timeline",children:[0===e.length&&(0,n.jsxs)("div",{className:"tl-empty",children:["No activity yet.",(0,n.jsx)("br",{}),"Start an agent to see its actions stream here."]}),e.map((e,t)=>(0,n.jsxs)("div",{className:"tl-row",children:[(0,n.jsx)("span",{className:"tl-dot","aria-hidden":"true",style:{background:iD[e.type]??"var(--fg-faint)"}}),(0,n.jsxs)("div",{className:"tl-body",children:[(0,n.jsx)("span",{className:"visually-hidden",children:e.type}),(0,n.jsx)("span",{className:"tl-text",children:e.text}),(0,n.jsxs)("span",{className:"tl-meta mono",children:[e.agent??"workspace"," · ",new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})]})]})]},t))]})}function iF({name:e,icon:t}){let a,l=t??("dockerfile"===(a=e.toLowerCase())||a.includes("docker-compose")||a.endsWith(".dockerignore")?"docker":a.endsWith(".json")?"json":a.endsWith(".yml")||a.endsWith(".yaml")?"yaml":a.endsWith(".md")?"markdown":a.endsWith(".properties")||a.endsWith(".env")||a.startsWith(".env.")?"properties":a.endsWith(".java")?"java":a.endsWith(".tsx")?"react":a.endsWith(".ts")?"typescript":a.endsWith(".jsx")||a.endsWith(".js")||a.endsWith(".mjs")||a.endsWith(".cjs")?"javascript":a.endsWith(".py")?"python":a.endsWith(".go")?"go":a.endsWith(".rs")?"rust":a.endsWith(".gradle")?"gradle":a.endsWith(".sql")?"postgresql":a.endsWith(".html")?"html5":a.endsWith(".css")?"css3":a.endsWith(".graphql")||a.endsWith(".gql")?"graphql":a.endsWith(".png")||a.endsWith(".jpg")||a.endsWith(".jpeg")||a.endsWith(".gif")||a.endsWith(".webp")||a.endsWith(".svg")?"image":null);return null!==l?(0,n.jsx)("img",{className:"fi-img",src:`/assets/icons/${l}.svg`,width:"15",height:"15",alt:""}):(0,n.jsx)("span",{className:"fi-fallback",children:(0,n.jsx)(j.Icons.file,{size:14})})}let iO={jsx:"js",js:"js",mjs:"js",ts:"ts",tsx:"ts",java:"java",kt:"kotlin",kts:"kotlin",py:"py",rb:"py",go:"go",rs:"rust",json:"json",yml:"yaml",yaml:"yaml",md:"md",markdown:"md",html:"html",xml:"html",css:"css",sql:"sql",sh:"sh",bash:"sh",cob:"cobol",cbl:"cobol",gradle:"js",graphql:"graphql",gql:"graphql",properties:"props",toml:"props",env:"props",dockerfile:"docker"};function iz(e){let t=e.toLowerCase();if(".env"===t||t.startsWith(".env."))return"props";if("dockerfile"===t||t.startsWith("dockerfile"))return"docker";if(t.includes("docker-compose"))return"yaml";let n=t.split("."),a=n.length>1?n[n.length-1]:void 0;return void 0===a?"code":iO[a]??"code"}let iK=new Set("const let var function return if else for while do switch case break continue import from export default class extends implements interface enum new async await yield of in typeof instanceof this super public private protected static final readonly void int long double float boolean char byte short val fun object data override companion package def pass lambda try catch except finally throw throws raise with as not and or is null nil None True False true false undefined struct impl trait pub use mod match where select insert update delete create table from join on group by order limit FROM RUN CMD ENV COPY WORKDIR EXPOSE ENTRYPOINT AS".split(" "));function iB(e){let t=[];return e.split(/(`[^`]+`|\*\*[^*]+\*\*)/).forEach(e=>{""!==e&&(e.startsWith("`")?t.push(["str",e]):e.startsWith("**")?t.push(["type",e]):t.push(["id",e]))}),t.length>0?t:[["id",e]]}function i_(e,t){if("md"===t)return e.split("\n").map(e=>{if(/^#{1,6}\s/.test(e))return[["head",e]];if(/^\s*```/.test(e))return[["com",e]];let t=/^(\s*)([-*+]|\d+\.)(\s)/.exec(e);return null!==t?[["ws",t[1]??""],["key",t[2]??""],["ws",t[3]??""],...iB(e.slice(t[0].length))]:iB(e)});if("json"===t)return e.split("\n").map(e=>{let t=[],n=0;for(;n<e.length;){let a=e.slice(n),l=/^"(?:[^"\\]|\\.)*"/.exec(a);if(null!==l){let a=e.slice(n+l[0].length),i=/^\s*:/.test(a);t.push([i?"key2":"str",l[0]]),n+=l[0].length;continue}let i=/^-?\d[\d.eE+\-]*/.exec(a);if(null!==i){t.push(["num",i[0]]),n+=i[0].length;continue}let r=/^(true|false|null)\b/.exec(a);if(null!==r){t.push(["lit",r[0]]),n+=r[0].length;continue}let s=/^\s+/.exec(a);if(null!==s){t.push(["ws",s[0]]),n+=s[0].length;continue}t.push(["punct",a.charAt(0)]),n+=1}return t});let n="py"===t||"sh"===t||"yaml"===t||"props"===t||"docker"===t?{line:"#",block:null}:"sql"===t?{line:"--",block:["/*","*/"]}:"cobol"===t?{line:"*>",block:null}:"html"===t?{line:null,block:["<!--","-->"]}:{line:"//",block:["/*","*/"]},a={inBlock:!1},l=[];for(let t of e.split("\n"))l.push(function(e,t,n){let a=[],l=0;if(t.inBlock&&null!==n.block){let i=e.indexOf(n.block[1]);if(-1===i)return a.push(["com",e]),a;a.push(["com",e.slice(0,i+n.block[1].length)]),l=i+n.block[1].length,t.inBlock=!1}for(;l<e.length;){let i=e.slice(l);if(null!==n.line&&i.startsWith(n.line)){a.push(["com",i]);break}if(null!==n.block&&i.startsWith(n.block[0])){let r=e.indexOf(n.block[1],l+n.block[0].length);if(-1===r){a.push(["com",i]),t.inBlock=!0;break}a.push(["com",e.slice(l,r+n.block[1].length)]),l=r+n.block[1].length;continue}let r=/^(?:"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?)/.exec(i);if(null!==r&&r[0].length>1){a.push(["str",r[0]]),l+=r[0].length;continue}if(/^\d/.test(i)){let e=/^\d[\w.]*/.exec(i),t=e?.[0]??i.charAt(0);a.push(["num",t]),l+=t.length;continue}let s=/^[@A-Za-z_$][\w$]*/.exec(i);if(null!==s){let t=s[0],n="id";iK.has(t)||iK.has(t.toLowerCase())?n="key":t.startsWith("@")||/^[A-Z]/.test(t)?n="type":"("===e.charAt(l+t.length)&&(n="fn"),a.push([n,t]),l+=t.length;continue}let o=/^\s+/.exec(i);if(null!==o){a.push(["ws",o[0]]),l+=o[0].length;continue}let c=/^[^\w\s$@"']+/.exec(i);if(null!==c){a.push(["punct",c[0]]),l+=c[0].length;continue}a.push(["id",i.charAt(0)]),l+=1}return a}(t,a,n));return l}let iU={docx:"DOCX",xlsx:"XLSX",pdf:"PDF"};function iW(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}function iV(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function iH({label:e,value:t}){return(0,n.jsxs)("div",{className:"fpv-meta-row",children:[(0,n.jsx)("span",{children:e}),(0,n.jsx)("strong",{children:t})]})}function iY({root:e,path:t,onClose:l,onOpenInEditor:i}){let[r,s]=(0,a.useState)(null),[o,c]=(0,a.useState)(!0),[d,u]=(0,a.useState)(null),[p,m]=(0,a.useState)(0),h=(0,a.useRef)(null);(0,a.useEffect)(()=>{h.current?.focus({preventScroll:!0})},[]),(0,a.useEffect)(()=>{let n=!1;return c(!0),u(null),s(null),(0,w.fetchFilesPreview)(e,t).then(e=>{n||s(e)}).catch(e=>{n||u(e instanceof w.ApiError&&"DENIED"===e.code?{message:"This file is excluded from the read surface for safety (matches a deny pattern such as .env, *.pem, node_modules, .git, …).",denied:!0}:e instanceof Error?{message:/^HTTP \d+$/.test(e.message)?"The file could not be loaded. Try again.":e.message,denied:!1}:{message:"Unable to read this file.",denied:!1})}).finally(()=>{n||c(!1)}),()=>{n=!0}},[t,e,p]);let f=d?.denied===!0,g=null!==r?"text"===r.kind?r.extension??"text":"image"===r.kind?r.mime:r.extension??"binary":f?"denied":null!==d?"error":"loading",v=f?"Hidden file":r?.name??(null!==d?"Preview unavailable":"Loading preview"),b=r?.kind==="text"&&r.content.length<=2e5,x=void 0!==i&&r?.kind==="text"&&!r.truncated,y=r?.kind==="text"?b?i_(r.content,iz(r.name)):r.content.split("\n").map(e=>[["id",e]]):[];return(0,n.jsxs)("div",{className:"fpv",onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),l())},children:[(0,n.jsxs)("div",{className:"fpv-bar",children:[(0,n.jsx)("button",{className:"fpv-back",type:"button",ref:h,onClick:l,title:"Back to files","aria-label":"Back to files",children:(0,n.jsx)(j.Icons.back,{size:15})}),(0,n.jsx)(iF,{name:f||null===r?"":r.name}),(0,n.jsx)("span",{className:"fpv-name",title:v,children:v}),(0,n.jsx)("span",{className:"fpv-lang mono",children:g}),(0,n.jsx)("span",{className:"spacer"}),x?(0,n.jsx)("button",{className:"fpv-back",type:"button",onClick:()=>i(e,t),title:"Open in editor","aria-label":"Open in editor",children:(0,n.jsx)(j.Icons.editor,{size:15})}):null,(0,n.jsx)("button",{className:"fpv-back",type:"button",onClick:l,title:"Close preview","aria-label":"Close preview",children:(0,n.jsx)(j.Icons.close,{size:15})})]}),o?(0,n.jsx)("div",{className:"fpv-state",role:"status",children:"Loading preview…"}):null,null!==d?(0,n.jsxs)("div",{className:"fpv-state fpv-error",role:"alert",children:[(0,n.jsx)("span",{children:d.message}),d.denied?null:(0,n.jsx)("button",{type:"button",className:"fpv-retry",onClick:()=>m(e=>e+1),children:"Retry"})]}):null,r?.kind==="text"?(0,n.jsxs)(n.Fragment,{children:[r.truncated?(0,n.jsxs)("div",{className:"fpv-banner",children:["Preview truncated at ",iW(r.maxBytes),". Larger files can't be shown in full here."]}):null,b?null:(0,n.jsx)("div",{className:"fpv-banner",children:"Syntax highlighting disabled for large previews."}),(0,n.jsx)("div",{className:"fpv-code mono",tabIndex:0,role:"region","aria-label":`File preview: ${r.name}`,style:{"--fpv-gutter-w":`max(44px, calc(${String(String(y.length).length)}ch + 16px))`},children:y.map((e,t)=>(0,n.jsxs)("div",{className:"fpv-line",children:[(0,n.jsx)("span",{className:"fpv-num",children:t+1}),(0,n.jsx)("span",{className:"fpv-src",children:e.map((e,t)=>(0,n.jsx)("span",{className:`hl-${e[0]}`,children:e[1]},t))})]},t))})]}):null,r?.kind==="image"?(0,n.jsxs)("div",{className:"fpv-image-pane",children:[(0,n.jsx)("div",{className:"fpv-image-card",children:(0,n.jsx)("img",{className:"fpv-image",src:r.dataUrl,alt:r.name})}),(0,n.jsxs)("div",{className:"fpv-meta",children:[(0,n.jsx)(iH,{label:"Type",value:r.mime}),(0,n.jsx)(iH,{label:"Size",value:iW(r.sizeBytes)}),(0,n.jsx)(iH,{label:"Modified",value:iV(r.modifiedAt)})]})]}):null,r?.kind==="binary"?(0,n.jsx)("div",{className:"fpv-meta-pane",children:(0,n.jsxs)("div",{className:"fpv-meta-card",children:[(0,n.jsx)(iF,{name:r.name}),(0,n.jsx)("h3",{children:r.name}),(0,n.jsx)("p",{children:function(e){if("too_large"===e.reason)return`Preview disabled because this file exceeds ${iW(e.maxBytes??0)}.`;let t=iU[function(e){let t=e.extension?.trim().toLowerCase();if(void 0!==t&&t.length>0)return t;let n=e.name.lastIndexOf(".");return n>=0?e.name.slice(n+1).trim().toLowerCase():""}(e)];if(void 0!==t)return`${t} files up to 2 MB are searchable in Repository Search via bounded text extraction when explicitly connected to a chat. Encrypted, scanned, or larger documents are not extracted — use Local Knowledge for those. No inline preview is available for this format here.`;return"No safe text or image preview is available for this file type."}(r)}),(0,n.jsxs)("div",{className:"fpv-meta",children:[(0,n.jsx)(iH,{label:"Type",value:r.mime}),(0,n.jsx)(iH,{label:"Extension",value:r.extension??"none"}),(0,n.jsx)(iH,{label:"Size",value:iW(r.sizeBytes)}),(0,n.jsx)(iH,{label:"Modified",value:iV(r.modifiedAt)})]})]})}):null]})}function iG(e){let t=e.replace(/[/\\]+$/,""),n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return n<0?null:0===n?"/":/^[A-Za-z]:$/.test(t.slice(0,n))?`${t.slice(0,n)}\\`:t.slice(0,n)}function iJ(e){return 8+18*e}let iX=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function iQ({root:e,activeFilePath:t,openFilesDirectly:l=!1,onActiveFileChange:i,onRootChange:r,onOpenFile:s}){let o=e?.trim(),c=void 0!==o&&o.length>0?o:null,[d,u]=(0,a.useState)(null),p=c??d??"",[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(""),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(null),[k,N]=(0,a.useState)({}),[S,C]=(0,a.useState)(()=>new Set([""])),[I,E]=(0,a.useState)(0),R=(0,a.useRef)(i);R.current=i;let $=(0,a.useRef)(null),A=(0,a.useRef)(null),T=(0,a.useId)();(0,a.useEffect)(()=>{if(null!==v)return;let e=A.current;if(null===e)return;A.current=null;let t=$.current?.querySelector(`.tr-file[data-path="${"u">typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"]`);(t??$.current)?.focus({preventScroll:!0})},[v]),(0,a.useEffect)(()=>{if(null!==c)return;let e=!1;return(0,w.fetchProjects)().then(t=>{e||u(t.projects.find(e=>e.available)?.path??null)}).catch(()=>{e||u(null)}),()=>{e=!0}},[c]);let L=(0,a.useCallback)(async e=>{if(0===p.length)return void N(t=>({...t,[e]:{entries:[],truncated:!1,loading:!1,error:null,notice:"no-root"}}));N(t=>({...t,[e]:{entries:t[e]?.entries??[],truncated:t[e]?.truncated??!1,loading:!0,error:null,notice:null}}));try{let t=await (0,w.fetchFilesTree)(p,e);""===e&&(h(t.root),R.current?.(null,t.root,null),y(null)),N(n=>({...n,[e]:{entries:t.entries,truncated:t.truncated,loading:!1,error:null,notice:null}}))}catch(t){N(n=>({...n,[e]:{entries:n[e]?.entries??[],truncated:n[e]?.truncated??!1,loading:!1,error:t instanceof Error?t.message:"Unable to read this folder.",notice:null}}))}},[p]);(0,a.useEffect)(()=>{b(null),y(null),R.current?.(null,null,null),h(null),C(new Set([""])),N({}),L("")},[p,L,I]);let P=function(e,t){if(null===t||0===t.length)return e;let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return`${e.replace(/[/\\]+$/u,"")}${n}${t.replace(/\//gu,n)}`}(m??(p.length>0?p:""),x);(0,a.useEffect)(()=>{g(P)},[P]);let M=(0,a.useCallback)(e=>{let t=e.trim();void 0===r||0===t.length||t!==P&&r(t)},[r,P]),D=(0,a.useCallback)(e=>{b(null),y(e),R.current?.(null,m??p,e),null!==e&&void 0===k[e]&&L(e)},[p,k,L,m]),q=(0,a.useCallback)(()=>{if(null!==x)return void D(function(e){let t=e.replace(/\/+$/u,""),n=t.lastIndexOf("/");if(n<0)return null;let a=t.slice(0,n);return a.length>0?a:null}(x));let e=iG(m??p);null!==e&&M(e)},[p,x,D,M,m]),F=(e,a,i=k[e])=>(0,n.jsxs)("div",{className:"tr-dir",role:0===a?void 0:"group",children:[i?.loading===!0?(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iJ(a)+18},children:"Loading…"}):null,i?.notice==="no-root"?(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iJ(a)+18},children:void 0!==r?"No folder is open yet. Enter a folder path above and press Open.":"No registered project is available."}):null,i?.error!==null&&i?.error!==void 0?(0,n.jsxs)("div",{className:"files-error",role:"alert",style:{marginLeft:iJ(a)},children:[(0,n.jsx)("span",{children:i.error}),(0,n.jsx)("button",{type:"button",className:"files-retry",onClick:()=>{L(e)},children:"Retry"})]}):null,i?.truncated===!0?(0,n.jsxs)("div",{className:"files-note files-warning",role:"status",style:{paddingLeft:iJ(a)+18},children:["Showing only the first ",i.entries.length," entries — this folder contains more."]}):null,i?.entries.map(e=>((e,a)=>{let i=iJ(a),r=S.has(e.path),o="This link can't be opened from this folder.";if("directory"===e.kind){let t=k[e.path];return(0,n.jsxs)("div",{className:"tr-row-wrap",children:[(0,n.jsxs)("div",{className:"tr-dir-line",style:{paddingLeft:i},children:[(0,n.jsx)("button",{className:"tr-caret-btn",type:"button",tabIndex:-1,disabled:!e.readable,"aria-label":`${r?"Collapse":"Expand"} folder: ${e.name}`,onClick:()=>(e=>{if(!e.readable)return;let t=S.has(e.path);C(t=>{let n=new Set(t);return n.has(e.path)?n.delete(e.path):n.add(e.path),n}),t||void 0!==k[e.path]||L(e.path)})(e),title:e.readable?`${r?"Collapse":"Expand"} ${e.path}`:o,children:(0,n.jsx)("span",{className:"tr-caret","data-open":r,children:(0,n.jsx)(j.Icons.chevronR,{size:11})})}),(0,n.jsxs)("button",{className:"tr-row tr-dir-enter",role:"treeitem","aria-level":a+1,"aria-selected":x===e.path,"data-active":x===e.path,"data-readable":e.readable,"data-path":e.path,type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:T,"aria-expanded":r,onClick:()=>{e.readable&&D(e.path)},title:e.readable?e.path:o,children:[(0,n.jsx)("span",{className:"fi-fallback",style:{color:"var(--accent)"},children:(0,n.jsx)(j.Icons.folder,{size:14})}),(0,n.jsx)("span",{className:"tr-name tr-folder",children:e.name}),e.symlink?(0,n.jsx)("span",{className:"tr-badge",children:"link"}):null]})]}),r?F(e.path,a+1,t):null]},e.path)}let c=v??t??null;return(0,n.jsxs)("button",{className:"tr-row tr-file",role:"treeitem","aria-level":a+1,"aria-selected":c===e.path,"data-active":c===e.path,"data-readable":e.readable,"data-path":e.path,style:{paddingLeft:i},type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:T,onClick:()=>{if(!e.readable)return;let t=m??p;if(l&&void 0!==s){R.current?.(e.path,t),s(t,e.path);return}b(e.path),R.current?.(e.path,t)},title:e.readable?e.path:o,children:[(0,n.jsx)("span",{className:"tr-caret tr-caret-ghost","aria-hidden":"true",children:(0,n.jsx)(j.Icons.chevronR,{size:11})}),(0,n.jsx)(iF,{name:e.name}),(0,n.jsx)("span",{className:"tr-name",children:e.name}),e.symlink?(0,n.jsx)("span",{className:"tr-badge",children:"link"}):null,(0,n.jsx)("span",{className:"tr-meta mono",children:function(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}(e.sizeBytes)})]},e.path)})(e,a)),void 0===i||i.loading||null!==i.error||null!==i.notice||0!==i.entries.length?null:(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iJ(a)+18},children:"Empty folder."})]});return null!==v?(0,n.jsx)(iY,{root:m??p,path:v,onOpenInEditor:s,onClose:()=>{A.current=v,b(null),R.current?.(null,m??p)}}):(0,n.jsxs)("div",{className:"files",ref:$,tabIndex:-1,children:[void 0!==r?(0,n.jsxs)("form",{className:"files-root-bar",role:"group","aria-label":"Folder root",onSubmit:e=>{e.preventDefault(),M(f)},children:[(0,n.jsx)("button",{type:"button",className:"files-root-up",onClick:q,disabled:null===x&&null===iG(m??p),title:"Open parent folder","aria-label":"Open parent folder",children:(0,n.jsx)(j.Icons.arrowUp,{size:13})}),(0,n.jsx)("input",{type:"text",className:"files-root-input mono","aria-label":"Folder path — open any folder on this machine",placeholder:"/path/to/any/folder",spellCheck:!1,value:f,onChange:e=>g(e.target.value)}),(0,n.jsx)("button",{type:"submit",className:"files-root-open",title:"Open this folder",children:"Open"})]}):null,(0,n.jsx)("button",{className:"files-refresh",type:"button",onClick:()=>E(e=>e+1),title:"Refresh folder","aria-label":"Refresh folder",children:(0,n.jsx)(j.Icons.reset,{size:13})}),(0,n.jsx)("span",{id:T,className:"visually-hidden",children:"This link can't be opened from this folder."}),(0,n.jsx)("div",{className:"tr files-tree",role:"tree","aria-label":"Files",tabIndex:-1,onKeyDown:e=>{if(!iX.has(e.key))return;let t=e.target,n=t instanceof HTMLElement?t.closest("button.tr-row"):null;if(null===n)return;let a=Array.from(e.currentTarget.querySelectorAll("button.tr-row")),l=a.indexOf(n);l<0||(e.preventDefault(),function(e,t,n){let a=e[t];if(void 0===a)return;let l=a.closest(".tr-row-wrap")?.querySelector("button.tr-caret-btn");if("ArrowDown"===n)e[t+1]?.focus();else if("ArrowUp"===n)e[t-1]?.focus();else if("Home"===n)e[0]?.focus();else if("End"===n)e[e.length-1]?.focus();else if("ArrowRight"===n){let n=a.getAttribute("aria-expanded");"false"===n?l?.click():"true"===n&&e[t+1]?.focus()}else"ArrowLeft"===n&&("true"===a.getAttribute("aria-expanded")?l?.click():function(e,t){let n=Number(e[t]?.getAttribute("aria-level")??"1");for(let a=t-1;a>=0;a-=1)if(Number(e[a]?.getAttribute("aria-level")??"1")<n)return void e[a]?.focus()}(e,t))}(a,l,e.key))},children:F(x??"",0)})]})}var iZ=e.i(70703);function i0(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function i1(e,t,n){return Math.min(n,Math.max(t,e))}function i2(e){return i1(Math.round(e),15,85)}function i4(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)"string"==typeof n&&n.length>0&&!t.includes(n)&&t.push(n);return t}function i3(e,t,n){let a=[],l=e=>{e.length>0&&!a.includes(e)&&a.push(e)};for(let e of n??[])l(e);for(let e of t)l(e);return l(e),a}function i6(e,t,n){let a=i3(t,n);return{id:e,openFiles:a,activeFile:t.length>0?t:a[0]??"",tabOrder:a}}function i5(e,t){if(!i0(e))return null;let n="string"==typeof e.id&&e.id.length>0?e.id:t,a="string"==typeof e.activeFile?e.activeFile:"string"==typeof e.file?e.file:"",l=i6(n,a,i3(a,i4(e.openFiles),i4(e.tabOrder)));return l.openFiles.length>0||l.activeFile.length>0?l:null}function i8(e){return"column"===e?"column":"row"}function i7(e,t=[]){return"pane"===e.type?t.push(e.paneId):(i7(e.first,t),i7(e.second,t)),t}function i9(e,t){return"number"==typeof e.sidebarWidth&&Number.isFinite(e.sidebarWidth)?i1(e.sidebarWidth,t.minSidebarWidth,t.maxSidebarWidth):t.defaultSidebarWidth}function re(e,t,n){return"string"==typeof e.activePaneId&&void 0!==t[e.activePaneId]?e.activePaneId:n}function rt(e){return JSON.stringify({schemaVersion:2,root:e.root,activePaneId:e.activePaneId,tree:e.tree,panes:e.panes,sidebarWidth:Math.round(e.sidebarWidth),sidebarCollapsed:e.sidebarCollapsed})}function rn(e){return i7(e.tree)}function ra(e){return rn(e).map(t=>e.panes[t]).filter(e=>void 0!==e)}function rl(e){return e.panes[e.activePaneId]??ra(e)[0]??i6("pane-1","",[])}function ri(e,t,n){let a=e.panes[t];return void 0===a?e:{...e,panes:{...e.panes,[t]:n(a)}}}function rr(e,t){return e.filter(e=>e!==t)}function rs(e,t,n){let a=rr(e,t),l=void 0===n?a.length:i1(n,0,a.length);return[...a.slice(0,l),t,...a.slice(l)]}function ro(e,t,n){let a=i3(n,t);return{...e,openFiles:a,tabOrder:a,activeFile:n.length>0?n:a[0]??""}}function rc(e,t,n,a,l){let i=e.panes[t];if(void 0===i)return e;let r=a??i.activeFile;if(0===r.length)return e;let s=function(e){let t=Object.keys(e.panes).length+1;for(;void 0!==e.panes[`pane-${String(t)}`];)t+=1;return`pane-${String(t)}`}(e),o=i6(s,r,[r]),c={type:"split",id:function(e){let t=new Set,n=e=>{"split"===e.type&&(t.add(e.id),n(e.first),n(e.second))};n(e);let a=t.size+1;for(;t.has(`split-${String(a)}`);)a+=1;return`split-${String(a)}`}(e.tree),direction:n,ratio:50,first:{type:"pane",paneId:l?s:t},second:{type:"pane",paneId:l?t:s}};return{...e,activePaneId:s,tree:function e(t,n,a){return"pane"===t.type?t.paneId===n?a:t:{...t,first:e(t.first,n,a),second:e(t.second,n,a)}}(e.tree,t,c),panes:{...e.panes,[s]:o}}}function rd(e,t){if(void 0===e.panes[t]||rn(e).length<=1)return e;let n=function e(t,n){if("pane"===t.type)return t.paneId===n?null:t;let a=e(t.first,n),l=e(t.second,n);return null===a?l:null===l?a:{...t,first:a,second:l}}(e.tree,t);if(null===n)return e;let a={};for(let[n,l]of Object.entries(e.panes))n!==t&&(a[n]=l);let l=e.activePaneId===t?i7(n)[0]??e.activePaneId:e.activePaneId;return{...e,tree:n,panes:a,activePaneId:l}}function ru(e,t,n){let a=e.panes[t];if(!a?.openFiles.includes(n))return e;let l=a.tabOrder.indexOf(n),i=rr(a.openFiles,n);if(0===i.length)return rn(e).length>1?rd(e,t):ri(e,t,e=>ro(e,[],""));let r=a.activeFile===n?i[l]??i[l-1]??i[0]??"":a.activeFile;return ri(e,t,e=>ro(e,i,r))}function rp(e,t,n,a,l){if(t===n)return ri(e,n,e=>ro(e,rs(e.tabOrder,a,l),a));let i=e.panes[t],r=e.panes[n];if(void 0===i||void 0===r||!i.openFiles.includes(a))return e;let s=ru(e,t,a);return void 0===s.panes[n]?s:{...s=ri(s,n,e=>ro(e,rs(e.tabOrder,a,l),a)),activePaneId:n}}let rm=new Set(["open-file","select-file","close-tab","reorder-tab"]),rh=new Set(["close-pane","move-tab","drop-tab","split-pane"]);function rf(e,t){if(rm.has(t.type)){switch(t.type){case"open-file":return ri(e,t.paneId,e=>ro(e,i3(t.file,e.openFiles),t.file));case"select-file":return ri({...e,activePaneId:t.paneId},t.paneId,e=>e.openFiles.includes(t.file)?ro(e,e.openFiles,t.file):e);case"close-tab":return ru(e,t.paneId,t.file);case"reorder-tab":return ri(e,t.paneId,e=>e.openFiles.includes(t.file)?ro(e,rs(e.tabOrder,t.file,t.targetIndex),t.file):e)}return}return rh.has(t.type)?function(e,t){switch(t.type){case"close-pane":return rd(e,t.paneId);case"move-tab":return rp(e,t.fromPaneId,t.toPaneId,t.file,t.targetIndex);case"drop-tab":var n;return"center"===(n=t.intent).zone?rp(e,n.fromPaneId,n.toPaneId,n.file,n.targetIndex):rc(rp(e,n.fromPaneId,n.fromPaneId,n.file),n.toPaneId,"top"===n.zone||"bottom"===n.zone?"column":"row",n.file,"top"===n.zone||"left"===n.zone);case"split-pane":return rc(e,t.paneId,t.direction,t.file,!1)}}(e,t):function(e,t){switch(t.type){case"set-active-pane":return void 0===e.panes[t.paneId]?e:{...e,activePaneId:t.paneId};case"resize-split":return{...e,tree:function e(t,n,a){return"pane"===t.type?t:{...t,ratio:t.id===n?i2(a):t.ratio,first:e(t.first,n,a),second:e(t.second,n,a)}}(e.tree,t.splitId,t.ratio)};case"set-sidebar":return{...e,sidebarWidth:t.width??e.sidebarWidth,sidebarCollapsed:t.collapsed??e.sidebarCollapsed};case"replace-root":let n;return n=i6("pane-1","",[]),{schemaVersion:2,root:t.root,activePaneId:n.id,tree:{type:"pane",paneId:n.id},panes:{[n.id]:n},sidebarWidth:t.sidebarWidth??e.sidebarWidth,sidebarCollapsed:!1}}}(e,t)}function rg(e){let t=[];for(let n of ra(e))for(let e of n.openFiles)e.length>0&&!t.includes(e)&&t.push(e);return t}let rv=(0,iZ.default)(()=>e.A(37337),{loadableGenerated:{modules:[65890]},ssr:!1,loading:()=>(0,n.jsx)("div",{className:"ed-host-loading","aria-hidden":"true"})});function rb(e,t,n){return Math.min(n,Math.max(t,e))}function rx(e){return e.trim().replace(/\\/gu,"/").replace(/\/+$/u,"")}function ry(e,t){let n=t?.trim()??"";if(0===e.trim().length||0===n.length)return n;let a=rx(e),l=rx(n),i=a.toLowerCase(),r=l.toLowerCase();return r===i?"":r.startsWith(`${i}/`)?l.slice(a.length+1).replace(/^\/+/u,""):n}function rw(e,t,n){let a=[],l=t=>{let n=ry(e,t);0===n.length||a.includes(n)||a.push(n)};for(let e of n??[])l(e);return l(t),a}function rj(e,t){let n={};for(let[a,l]of Object.entries(t.panes))n[a]=function(e,t){let n=rw(e,t.activeFile,t.openFiles),a=ry(e,t.activeFile)||n[0]||"",l=rw(e,a,t.tabOrder);return{...t,openFiles:n,activeFile:a,tabOrder:l.length>0?l:n}}(e,l);return{...t,root:e,panes:n}}function rk(e){return rj(e.root,function(e){let t=function(e){if(void 0!==e.layoutJson&&e.layoutJson.trim().length>0)try{let t=JSON.parse(e.layoutJson);if(i0(t)){let n=t.schemaVersion??t.version,a=2===n||"2"===n?function(e,t,n){let a=function(e){if(!i0(e))return{};let t={};for(let[n,a]of Object.entries(e)){let e=i5(a,n);null!==e&&(t[e.id]=e)}return t}(t.panes),l=Object.keys(a)[0];if(void 0===l)return null;let i=function e(t,n){return i0(t)?("pane"===t.type&&"string"==typeof t.paneId&&void 0!==n[t.paneId]?{type:"pane",paneId:t.paneId}:null)??function(t,n){if("split"!==t.type)return null;let a=e(t.first,n),l=e(t.second,n);if(null===a||null===l)return null;let i="string"==typeof t.id&&t.id.length>0?t.id:"split-1",r="number"==typeof t.ratio&&Number.isFinite(t.ratio)?t.ratio:50;return{type:"split",id:i,direction:i8(t.direction),ratio:i2(r),first:a,second:l}}(t,n):null}(t.tree,a)??{type:"pane",paneId:l},r=function(e,t){let n={};for(let a of new Set(i7(e))){let e=t[a];void 0!==e&&(n[a]=e)}return n}(i,a);return{schemaVersion:2,root:e,activePaneId:re(t,r,i7(i)[0]??l),tree:i,panes:r,sidebarWidth:i9(t,n),sidebarCollapsed:!0===t.sidebarCollapsed}}(e.root,t,e):function(e,t,n){var a;let l=Array.isArray(a=t.panes)?a.map((e,t)=>i5(e,`pane-${String(t+1)}`)).filter(e=>null!==e):[];if(0===l.length)return null;let i={};for(let e of l)i[e.id]=e;let r=l[0];if(void 0===r)return null;let s=function(e,t,n){if(void 0===t)return{type:"pane",paneId:e.id};let a="number"==typeof n.splitRatio&&Number.isFinite(n.splitRatio)?i2(n.splitRatio):50;return{type:"split",id:"split-1",direction:i8(n.direction),ratio:a,first:{type:"pane",paneId:e.id},second:{type:"pane",paneId:t.id}}}(r,l[1],t);return{schemaVersion:2,root:e,activePaneId:re(t,i,r.id),tree:s,panes:i,sidebarWidth:i9(t,n),sidebarCollapsed:!0===t.sidebarCollapsed}}(e.root,t,e);if(null!==a)return a}}catch{}return null}(e);if(null!==t)return t;let n=i6("pane-1",e.file.length>0?e.file:e.openFiles[0]??"",e.openFiles);return{schemaVersion:2,root:e.root,activePaneId:n.id,tree:{type:"pane",paneId:n.id},panes:{[n.id]:n},sidebarWidth:e.defaultSidebarWidth,sidebarCollapsed:!1}}({root:e.root,file:e.file,openFiles:e.openFiles,layoutJson:e.layoutJson,defaultSidebarWidth:260,minSidebarWidth:180,maxSidebarWidth:440}))}function rN(e){let t=new Set;for(let n of Object.values(e))for(let e of Object.keys(n))t.add(e);return[...t]}function rS(e){let t="editor-dirty-close-title",l=(0,a.useRef)(null);return(0,a.useEffect)(()=>{l.current?.focus()},[]),(0,a.useEffect)(()=>{let t=t=>{"Escape"!==t.key||e.pending.saving||e.onCancel()};return document.addEventListener("keydown",t),()=>{document.removeEventListener("keydown",t)}},[e]),(0,n.jsx)("div",{className:"ed-dialog-backdrop",role:"presentation",children:(0,n.jsxs)("div",{className:"ed-dirty-dialog",ref:l,role:"dialog","aria-modal":"true","aria-labelledby":t,tabIndex:-1,children:[(0,n.jsx)("h2",{id:t,children:"Unsaved editor changes"}),(0,n.jsx)("p",{children:"Choose how to handle these files before continuing."}),(0,n.jsx)("ul",{children:e.pending.dirtyFiles.map(e=>(0,n.jsx)("li",{children:e},e))}),void 0!==e.pending.error?(0,n.jsx)("p",{role:"alert",children:e.pending.error}):null,(0,n.jsxs)("div",{className:"ed-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"ed-save",onClick:e.onSave,disabled:e.pending.saving,children:e.pending.saving?"Saving...":"Save"}),(0,n.jsx)("button",{type:"button",className:"ed-reload",onClick:e.onDiscard,disabled:e.pending.saving,children:"Discard"}),(0,n.jsx)("button",{type:"button",className:"ed-icon-action",onClick:e.onCancel,disabled:e.pending.saving,children:"Cancel"})]})]})})}function rC({root:e,file:t,openFiles:l,layoutJson:i,onWorkspaceChange:r,...s}){let o=e?.trim()??"",c=ry(o,t),d=rw(o,c,l),u=rk({root:o,file:c,openFiles:d,layoutJson:i}),[p,m]=(0,a.useState)(o),[h,f]=(0,a.useState)(u),[g,v]=(0,a.useState)({}),[b,x]=(0,a.useState)(null),[y,w]=(0,a.useState)(null),[k,N]=(0,a.useState)(null),S=(0,a.useRef)(0),C=(0,a.useRef)(new Map),I=(0,a.useRef)(e?.trim()??""),E=(0,a.useRef)(null),R=(0,a.useCallback)((e,t)=>{var n;let a=rl(t);return{root:e,file:a.activeFile.length>0?a.activeFile:void 0,openFiles:(n=rg(t)).length>0?n:void 0,layoutJson:rt(t)}},[]),$=(0,a.useCallback)((e,t=p)=>{let n=rj(t,e);f(n),t.length>0&&r?.(R(t,n))},[R,r,p]);(0,a.useEffect)(()=>{let n=e?.trim()??"",a=ry(n,t),s=rw(n,a,l),o=rk({root:n,file:a,openFiles:s,layoutJson:i}),c=rl(o),d=rg(o),u=I.current!==n;if(I.current=n,m(n),f(o),u&&v({}),0===n.length||void 0===r)return;let p=(t?.trim()??"")!==c.activeFile,h=void 0===l?0!==d.length:!(l.length===d.length&&l.every((e,t)=>e===d[t])),g=i!==rt(o);(p||h||g)&&r(R(n,o))},[R,l,t,i,r,e]);let A=(0,a.useMemo)(()=>rN(g),[g]),T=rl(h),L=T.activeFile;(0,a.useEffect)(()=>{if(0===A.length)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}},[A.length]);let P=(0,a.useCallback)((e,t,n)=>{v(a=>{let l=a[e]??{};if(n)return!0===l[t]?a:{...a,[e]:{...l,[t]:!0}};if(!0!==l[t])return a;let{[t]:i,...r}=l;return{...a,[e]:r}})},[]),M=(0,a.useCallback)((e,t)=>{S.current+=1;let n=S.current;return $(rf(h,{type:"select-file",paneId:e,file:t})),N({id:n,paneId:e,file:t}),new Promise(e=>{C.current.set(n,e)})},[$,h]),D=(0,a.useCallback)((e,t,n,a)=>{let l=C.current.get(e);C.current.delete(e),k?.id===e&&N(null),a&&P(t,n,!1),l?.(a)},[P,k?.id]),q=(0,a.useCallback)(e=>{var t,n;let a,l=new Set(rN(g)),i="root-change"===e.reason||"window-close"===e.reason?e.files.filter(e=>l.has(e)):(t=e.paneId,n=e.files,a=g[t]??{},n.filter(e=>!0===a[e]));return 0===i.length?(e.apply(),!0):(x({intent:function(e){let t=[];for(let n of e.files)n.length>0&&!t.includes(n)&&t.push(n);return{paneId:e.paneId,files:t,reason:e.reason}}({paneId:e.paneId,files:i,reason:e.reason}),apply:e.apply,dirtyFiles:i,saving:!1}),!1)},[g]),F=(0,a.useCallback)(()=>{null===b||b.saving||(x({...b,saving:!0,error:void 0}),(async()=>{for(let e of b.dirtyFiles){let t=Object.entries(g).find(([,t])=>!0===t[e])?.[0]??b.intent.paneId;if(!await M(t,e))return void x({...b,saving:!1,error:"Save failed. The close action was not applied."})}b.apply(),x(null)})())},[g,b,M]),O=(0,a.useCallback)(()=>{if(null!==b&&!b.saving){for(let e of b.dirtyFiles)for(let[t,n]of Object.entries(g))!0===n[e]&&P(t,e,!1);b.apply(),x(null)}},[g,P,b]),z=(0,a.useCallback)(()=>{b?.saving!==!0&&x(null)},[b?.saving]),K=(0,a.useCallback)(e=>{let t=e.trim();0===t.length||q({paneId:rn(h)[0]??h.activePaneId,files:A,reason:"root-change",apply:()=>{let e=rf(h,{type:"replace-root",root:t,sidebarWidth:h.sidebarWidth});m(t),v({}),$(e,t)}})},[$,A,h,q]),B=(0,a.useCallback)((e,t)=>{let n=e.trim(),a=ry(n,t);if(0===n.length||0===a.length)return;let l=rf(h,{type:"open-file",paneId:T.id,file:a});m(n),$(l,n)},[$,T.id,h]),_=(0,a.useCallback)((e,t)=>{0!==p.length&&0!==t.length&&$(rf(h,{type:"select-file",paneId:e,file:t}))},[$,h,p]),U=(0,a.useCallback)(async(e,t)=>q({paneId:e,files:[t],reason:"tab-close",apply:()=>{P(e,t,!1),$(rf(h,{type:"close-tab",paneId:e,file:t}))}}),[$,h,P,q]),W=(0,a.useCallback)((e,t)=>{$(rf(h,{type:"split-pane",paneId:e,direction:t}))},[$,h]),V=(0,a.useCallback)(e=>{let t=h.panes[e];void 0!==t&&q({paneId:e,files:t.openFiles,reason:"pane-close",apply:()=>{v(t=>{let{[e]:n,...a}=t;return a}),$(rf(h,{type:"close-pane",paneId:e}))}})},[$,h,q]),H=(0,a.useCallback)(()=>{$(rf(h,{type:"set-sidebar",collapsed:!h.sidebarCollapsed}))},[$,h]),Y=(0,a.useCallback)(e=>{null===E.current||$(rf(h,{type:"set-sidebar",width:rb(e-E.current.getBoundingClientRect().left,180,440),collapsed:!1}))},[$,h]),G=(0,a.useCallback)(e=>{1===e.buttons&&Y(e.clientX)},[Y]),J=(0,a.useCallback)((e,t,n,a)=>{let l="row"===e.direction?(n-t.left)/t.width*100:(a-t.top)/t.height*100;$(rf(h,{type:"resize-split",splitId:e.id,ratio:rb(l,15,85)}))},[$,h]),X=(0,a.useCallback)(e=>{e.preventDefault();let t=e=>Y(e.clientX),n=()=>{window.removeEventListener("mousemove",t),window.removeEventListener("mouseup",n)};window.addEventListener("mousemove",t),window.addEventListener("mouseup",n,{once:!0})},[Y]),Q=(0,a.useCallback)((e,t)=>{t.preventDefault();let n=t.currentTarget.parentElement;if(null===n)return;let a=t=>J(e,n.getBoundingClientRect(),t.clientX,t.clientY),l=()=>{window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l)};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l,{once:!0})},[J]),Z=(0,a.useCallback)(e=>{e.currentTarget.setPointerCapture(e.pointerId)},[]),ee=(0,a.useCallback)(e=>{e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},[]),et=(0,a.useCallback)((e,t,n)=>{if(!n.altKey)return;let a=h.panes[e];if(void 0!==a&&("ArrowLeft"===n.key||"ArrowRight"===n.key)){n.preventDefault();let l=rn(h);if(n.shiftKey){let a=l.indexOf(e),i="ArrowLeft"===n.key?l[a-1]:l[a+1];void 0!==i&&$(rf(h,{type:"move-tab",fromPaneId:e,toPaneId:i,file:t}));return}let i=a.tabOrder.indexOf(t);$(rf(h,{type:"reorder-tab",paneId:e,file:t,targetIndex:"ArrowLeft"===n.key?i-1:i+1}))}},[$,h]),en=(0,a.useCallback)((e,t,n)=>{n.preventDefault(),null!==y&&($(rf(h,{type:"drop-tab",intent:{fromPaneId:y.paneId,toPaneId:e,file:y.file,zone:t}})),w(null))},[$,y,h]);if(0===p.length)return(0,n.jsx)(rv,{...s});let ea=e=>{if("pane"===e.type){let t,a,l=h.panes[e.paneId];return void 0===l?null:(t=ra(h).map(e=>({paneId:e.id,activeFile:e.activeFile.length>0?e.activeFile:null,openFiles:e.openFiles})),a={...s,root:p,...l.activeFile.length>0?{file:l.activeFile}:{},openFiles:l.openFiles,dirtyFiles:A,windowId:`${s.windowId??"editor"}-${l.id}`,paneId:l.id,layoutPanes:t,activePaneId:h.activePaneId,onSelectOpenFile:e=>_(l.id,e),onCloseOpenFile:e=>U(l.id,e),onDirtyChange:(e,t)=>P(l.id,e,t),toolbarExtras:(0,n.jsxs)("span",{className:"ed-pane-actions","aria-label":"Editor split controls",children:[(0,n.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Split ${l.activeFile||"editor"} right`,title:"Split right",onClick:()=>W(l.id,"row"),children:(0,n.jsx)(j.Icons.split,{size:14})}),(0,n.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Split ${l.activeFile||"editor"} down`,title:"Split down",onClick:()=>W(l.id,"column"),children:(0,n.jsx)(j.Icons.tile,{size:14})}),rn(h).length>1?(0,n.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Close split ${l.activeFile||"editor"}`,title:"Close split",onClick:()=>V(l.id),children:(0,n.jsx)(j.Icons.close,{size:14})}):null]}),externalSaveRequest:null!==k&&k.paneId===l.id?k:void 0,onExternalSaveComplete:D},(0,n.jsxs)("section",{className:"ed-pane","data-active":l.id===h.activePaneId?"true":"false","data-dragging":null===y?"false":"true",children:[(0,n.jsx)("div",{className:"ed-pane-drop-zones","aria-hidden":"true",children:["left","right","top","bottom","center"].map(e=>(0,n.jsx)("button",{type:"button",className:`ed-pane-drop-zone ${e}`,tabIndex:-1,"aria-label":`Drop tab ${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>en(l.id,e,t)},e))}),(0,n.jsx)(rv,{...a,renderTabHandle:(e,t,n)=>({draggable:!0,onDragStart:t=>{t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e),w({paneId:l.id,file:e})},onDragEnd:()=>w(null),onKeyDown:t=>et(l.id,e,t),"data-active":t?"true":"false","data-dirty":n?"true":"false"})})]},l.id))}return(0,n.jsxs)("div",{className:`ed-panes ${e.direction}`,"data-split-id":e.id,style:{"--ed-split-ratio":`${String(e.ratio)}%`},children:[ea(e.first),(0,n.jsx)("button",{type:"button",className:"ed-pane-resizer","aria-label":"Resize editor split",title:"Resize editor split",onPointerDown:Z,onPointerMove:t=>{if(1!==t.buttons)return;let n=t.currentTarget.parentElement;null!==n&&J(e,n.getBoundingClientRect(),t.clientX,t.clientY)},onPointerUp:ee,onPointerCancel:ee,onMouseDown:t=>Q(e,t)}),ea(e.second)]})},el=1===rn(h).length;return(0,n.jsxs)("div",{className:`editor-workspace${h.sidebarCollapsed?" sidebar-collapsed":""}`,ref:E,style:{"--ed-sidebar-width":`${String(h.sidebarWidth)}px`},children:[h.sidebarCollapsed?(0,n.jsx)("button",{type:"button",className:"ed-sidebar-restore","aria-label":"Show project tree",title:"Show project tree",onClick:H,children:(0,n.jsx)(j.Icons.sidebar,{size:15})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("aside",{className:"ed-sidebar","aria-label":"Editor files",children:[(0,n.jsx)("div",{className:"ed-sidebar-chrome",children:(0,n.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":"Hide project tree",title:"Hide project tree",onClick:H,children:(0,n.jsx)(j.Icons.sidebar,{size:14})})}),(0,n.jsx)(iQ,{root:p,activeFilePath:L.length>0?L:void 0,openFilesDirectly:!0,onRootChange:K,onOpenFile:B})]}),(0,n.jsx)("button",{type:"button",className:"ed-sidebar-resizer","aria-label":"Resize project tree",title:"Resize project tree",onPointerDown:Z,onPointerMove:G,onPointerUp:ee,onPointerCancel:ee,onMouseDown:X})]}),(0,n.jsx)("div",{className:"ed-main",children:(0,n.jsx)("div",{className:`ed-panes ed-panes-root${el?" single":""}`,children:ea(h.tree)})}),null!==b?(0,n.jsx)(rS,{pending:b,onSave:F,onDiscard:O,onCancel:z}):null]})}async function rI(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}if(204!==l.status)return l.json()}async function rE(e){return rI(`/api/browser/status?port=${encodeURIComponent(String(e))}`)}async function rR(e){return rI("/api/browser/sessions",{method:"POST",body:JSON.stringify({port:e})})}async function r$(e){await rI(`/api/browser/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}async function rA(e,t){return rI(`/api/browser/sessions/${encodeURIComponent(e)}/navigate`,{method:"POST",body:JSON.stringify({url:t})})}async function rT(e){return rI(`/api/browser/sessions/${encodeURIComponent(e)}/screenshot`,{method:"POST",body:JSON.stringify({})})}async function rL(e,t){return rI(`/api/browser/sessions/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify({captureSeq:t})})}async function rP(e){return rI(`/api/browser/sessions/${encodeURIComponent(e)}/content`,{method:"POST",body:JSON.stringify({})})}function rM(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function rD(e){let t=e.cdpPort??9222,l=e.url??"http://localhost:5173",[i,r]=(0,a.useState)(String(t)),[s,o]=(0,a.useState)(l),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[m,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)([]),[w,j]=(0,a.useState)(null),[k,N]=(0,a.useState)(null),[S,C]=(0,a.useState)(null),I=(0,a.useRef)(null),E=(0,a.useCallback)(()=>{b(null)},[]),R=(0,a.useCallback)(e=>{y(t=>{let n=[...t,e];return n.length>50?n.slice(n.length-50):n}),"navigated"===e.kind&&"string"==typeof e.payload.originOnly&&C(e.payload.originOnly),"error"===e.kind&&b({code:"string"==typeof e.payload.code?e.payload.code:"INTERNAL",message:"string"==typeof e.payload.message?e.payload.message:"Error."})},[]);(0,a.useEffect)(()=>{var e;if(null===c){I.current?.close(),I.current=null;return}let t=new EventSource((e=c.sessionId,`/api/browser/sessions/${encodeURIComponent(e)}/events`));for(let e of["session-opened","navigated","screenshot-captured","page-content-captured","session-closed","trust-warning","error"])t.addEventListener(`browser:${e}`,e=>{try{let t=JSON.parse(e.data);R(t)}catch{}});return I.current=t,()=>{t.close(),I.current=null}},[c,R]);let $=(0,a.useCallback)(async()=>{E(),h(!0);try{let e=Number.parseInt(i,10),t=await rE(e);p(t)}catch(e){b(rM(e))}finally{h(!1)}},[i,E]),A=(0,a.useCallback)(async()=>{E(),h(!0);try{let e=Number.parseInt(i,10),t=await rR(e);d(t),y([]),N(null),C(null)}catch(e){b(rM(e))}finally{h(!1)}},[i,E]),T=(0,a.useCallback)(async()=>{if(null!==c){E(),h(!0);try{await r$(c.sessionId),d(null),j(null),N(null),C(null)}catch(e){b(rM(e))}finally{h(!1)}}},[c,E]),L=(0,a.useCallback)(async()=>{if(null!==c){E(),h(!0);try{let e=await rA(c.sessionId,s);C(e.originOnly)}catch(e){b(rM(e))}finally{h(!1)}}},[c,s,E]),P=(0,a.useCallback)(async()=>{if(null!==c){E(),h(!0);try{let e=await rT(c.sessionId);e.persisted||j({seq:e.seq,dataBase64:e.dataBase64})}catch(e){b(rM(e))}finally{h(!1)}}},[c,E]),M=(0,a.useCallback)(async()=>{if(null!==c&&null!==w){E(),h(!0);try{let e=await rL(c.sessionId,w.seq);e.persisted&&N(e.path),j(null)}catch(e){b(rM(e))}finally{h(!1)}}},[c,w,E]),D=(0,a.useCallback)(async()=>{if(null!==c){E(),h(!0);try{await rP(c.sessionId)}catch(e){b(rM(e))}finally{h(!1)}}},[c,E]),q=(0,a.useMemo)(()=>m||null!==c,[m,c]),F=(0,a.useMemo)(()=>m||null===c,[m,c]),O=m||null!==c,z=m||null===w,K=m&&null!==f?f:null!==w?"Screenshot ready (dry-run) — press Apply to persist.":null!==k?`Persisted as ${k}.`:null!==S?`Current origin: ${S}`:null!==u&&null===c?`Reachable: ${u.reachable?"yes":"no"}`:"";return(0,n.jsxs)("div",{className:"browser",children:[(0,n.jsxs)("div",{className:"bw-bar",children:[(0,n.jsx)("span",{className:"bw-dot",style:{background:null===c?"var(--line-strong)":"var(--ok)"},"aria-hidden":"true"}),(0,n.jsxs)("label",{className:"bw-field",children:[(0,n.jsx)("span",{className:"bw-field-label",children:"Port"}),(0,n.jsx)("input",{type:"text",inputMode:"numeric",className:"bw-input",value:i,onChange:e=>r(e.target.value),disabled:null!==c||m})]}),(0,n.jsxs)("label",{className:"bw-field bw-field-url",children:[(0,n.jsx)("span",{className:"bw-field-label",children:"URL"}),(0,n.jsx)("input",{type:"url",className:"bw-input bw-input-url",value:s,onChange:e=>o(e.target.value),disabled:m})]})]}),(0,n.jsxs)("div",{className:"bw-actions",role:"group","aria-label":"Browser actions",children:[(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{O||(g("Checking Chrome…"),$())},"aria-disabled":O,children:"Check"}),(0,n.jsx)("button",{type:"button",className:"bw-btn bw-btn-primary",onClick:()=>{q||(g("Opening session…"),A())},"aria-disabled":q,children:"Open session"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Navigating…"),L())},"aria-disabled":F,children:"Navigate"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing screenshot…"),P())},"aria-disabled":F,children:"Screenshot"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{z||(g("Applying screenshot…"),M())},"aria-disabled":z,children:"Apply"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing HTML…"),D())},"aria-disabled":F,children:"Capture HTML"}),(0,n.jsx)("button",{type:"button",className:"bw-btn bw-btn-danger",onClick:()=>{F||(g("Closing session…"),T())},"aria-disabled":F,children:"Close"})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:K}),m&&null!==f?(0,n.jsx)("p",{className:"bw-status",children:f}):null,null!==u&&null===c?(0,n.jsxs)("p",{className:"bw-status",children:["Reachable: ",u.reachable?"yes":"no",null===u.browserVersion?"":` — ${u.browserVersion}`]}):null,null!==S?(0,n.jsxs)("p",{className:"bw-status",children:["Current origin: ",(0,n.jsx)("span",{className:"mono",children:S})]}):null,null!==w?(0,n.jsx)("p",{className:"bw-status",children:"Screenshot ready (dry-run) — press Apply to persist."}):null,null!==k?(0,n.jsxs)("p",{className:"bw-status",children:["Persisted as ",(0,n.jsx)("span",{className:"mono",children:k}),"."]}):null,null!==v?(0,n.jsxs)("div",{className:"bw-error",role:"alert",children:[v.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",v.code,")"]})]}):null,(0,n.jsx)("div",{className:"bw-view",children:null!==w?(0,n.jsx)("img",{className:"bw-screenshot",src:`data:image/png;base64,${w.dataBase64}`,alt:"Pending screenshot preview"}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"ph-stripes","aria-hidden":"true"}),(0,n.jsx)("div",{className:"bw-overlay mono",children:null===c?"No session — choose a port and press Open session":"Session open — use Screenshot to capture a preview"})]})}),(0,n.jsx)("div",{className:"bw-log",role:"log","aria-label":"Browser event log",children:(0,n.jsx)("ul",{className:"bw-log-list",children:x.slice(-10).reverse().map((e,t)=>(0,n.jsxs)("li",{className:"bw-log-item",children:[(0,n.jsx)("span",{className:"bw-log-kind",children:function(e){switch(e){case"session-opened":return"session opened";case"navigated":return"navigated";case"screenshot-captured":return"screenshot captured";case"page-content-captured":return"content captured";case"session-closed":return"session closed";case"trust-warning":return"trust warning";case"error":return"error"}}(e.kind)}),(0,n.jsx)("span",{className:"bw-log-detail mono",children:function(e){let t=e.payload;if("navigated"===e.kind){let e="string"==typeof t.originOnly?t.originOnly:"",n="number"==typeof t.httpStatus?` (${String(t.httpStatus)})`:"";return`${e}${n}`}return"screenshot-captured"===e.kind?!0===t.persisted?"persisted":"dry-run":"page-content-captured"===e.kind?"number"==typeof t.byteLength?`${String(t.byteLength)} bytes`:"":"error"===e.kind||"trust-warning"===e.kind?"string"==typeof t.message?t.message:"string"==typeof t.warning?t.warning:"":""}(e)})]},`${String(e.kind)}-${String(t)}`))})})]})}async function rq(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}if(204!==l.status)return l.json()}async function rF(){return rq("/api/terminal/policy")}async function rO(e,t){let n=new URLSearchParams;return n.set("projectId",e),void 0!==t&&t.length>0&&n.set("path",t),rq(`/api/terminal/directories?${n.toString()}`)}async function rz(e){return rq("/api/terminal/executions",{method:"POST",body:JSON.stringify(e)})}async function rK(e){await rq(`/api/terminal/executions/${encodeURIComponent(e)}`,{method:"DELETE"})}function rB(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function r_(e){let[t,l]=(0,a.useState)(null),[i,r]=(0,a.useState)(""),[s,o]=(0,a.useState)(""),[c,d]=(0,a.useState)(e.cwd??""),[u,p]=(0,a.useState)(e.projectPath??""),[m,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(null),[w,j]=(0,a.useState)([]),k=(0,a.useRef)(null),N=(0,a.useRef)(!1),S=(0,a.useRef)(null),[C,I]=(0,a.useState)([]);(0,a.useEffect)(()=>{let e=!1;return rF().then(t=>{e||(l(t),r(e=>e.length>0?e:t.commands[0]??""))}).catch(t=>{e||y(rB(t))}),()=>{e=!0}},[]),(0,a.useEffect)(()=>{if(0===u.length)return void I([]);let e=!1;return rO(u,c.length>0?c:void 0).then(t=>{e||I(t.entries)}).catch(()=>{e||I([])}),()=>{e=!0}},[u,c]),(0,a.useEffect)(()=>{let e=new EventSource("/api/terminal/events");k.current=e;let t=e=>{try{let t=JSON.parse(e.data);if("execution-started"===t.kind&&N.current){let e=t.payload;"string"==typeof e.requestId&&e.requestId===S.current&&g(e=>null!==e?e:t.executionId)}if("execution-completed"===t.kind||"execution-failed"===t.kind||"execution-cancelled"===t.kind){let e=t.payload;"string"==typeof e.requestId&&e.requestId===S.current&&g(e=>null===e||e!==t.executionId?e:null)}j(e=>{let n=[t,...e];return n.length>30?n.slice(0,30):n})}catch{}};for(let n of["execution-started","execution-completed","execution-failed","execution-cancelled"])e.addEventListener(`terminal:${n}`,t);return()=>{e.close(),k.current=null}},[]);let E=(0,a.useCallback)(async e=>{let t;if(e.preventDefault(),m)return;y(null),b(null),g(null);let n="function"==typeof crypto.randomUUID?crypto.randomUUID():`terminal-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;S.current=n;let a=0===(t=s.trim()).length?[]:t.split(/\s+/);N.current=!0,h(!0);try{let e={projectId:u,command:i,args:a,...c.length>0?{cwd:c}:{},requestId:n},t=await rz(e);b(t)}catch(e){y(rB(e))}finally{N.current=!1,h(!1),S.current=null,g(null)}},[s,i,c,u,m]),R=(0,a.useCallback)(async()=>{if(null!==f)try{await rK(f)}catch(e){y(rB(e))}},[f]),$=(0,a.useMemo)(()=>t?.limits??null,[t]),A=(0,a.useRef)(null),T=(0,a.useRef)(!1);return(0,a.useEffect)(()=>{T.current&&!m&&document.activeElement===document.body&&A.current?.focus(),T.current=m},[m]),(0,n.jsxs)("div",{className:"terminal",children:[(0,n.jsxs)("form",{className:"tm-form",onSubmit:e=>void E(e),children:[(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Project path"}),(0,n.jsx)("input",{type:"text",value:u,onChange:e=>p(e.target.value),placeholder:"/absolute/path/to/project",required:!0})]}),(0,n.jsxs)("div",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Command"}),(0,n.jsx)(tz,{value:i,ariaLabel:"Command",disabled:null===t,menuTitle:"Allowed commands",mono:!0,sections:[{options:t?.commands.map(e=>({value:e,label:e}))??[]}],onValueChange:r})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Args (space-separated)"}),(0,n.jsx)("input",{type:"text",value:s,onChange:e=>o(e.target.value),placeholder:"e.g. -la src"})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Working directory (optional)"}),(0,n.jsx)("input",{type:"text",value:c,onChange:e=>d(e.target.value),placeholder:"(project root)",list:"tm-cwd-suggestions"}),(0,n.jsx)("datalist",{id:"tm-cwd-suggestions",children:C.map(e=>(0,n.jsx)("option",{value:e.path},e.path))})]}),(0,n.jsxs)("div",{className:"tm-actions",children:[(0,n.jsx)("button",{type:"submit",className:"tm-action","data-primary":"true",ref:A,disabled:null===t,"aria-disabled":m||null===t,children:m?"Running…":"Run"}),m?(0,n.jsx)("button",{type:"button",className:"tm-action","aria-disabled":null===f,onClick:()=>void R(),children:"Cancel"}):null]}),null!==$?(0,n.jsxs)("p",{className:"tm-limits",children:["Limits: ",(0,aq.formatBytes)($.maxOutputBytes)," output ·"," ",(0,aq.formatMs)($.defaultTimeoutMs)," timeout"]}):null]}),null!==x?(0,n.jsxs)("div",{className:"tm-error",role:"alert",children:[(0,n.jsxs)("span",{className:"tm-error-text",children:[x.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",x.code,")"]})]}),(0,n.jsx)("button",{type:"button",className:"tm-error-dismiss","aria-label":"Dismiss error",onClick:()=>y(null),children:"✕"})]}):null,(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==v?`Command finished: exit ${String(v.exitCode)}, ${String(v.durationMs)} ms${v.truncated?", output truncated":""}${v.timedOut?", timed out":""}`:""}),null!==v?(0,n.jsxs)("div",{className:"tm-result",children:[(0,n.jsxs)("div",{className:"tm-badges",children:[(0,n.jsxs)("span",{className:0===v.exitCode?"tm-badge tm-badge-ok":"tm-badge tm-badge-fail",children:["exit ",String(v.exitCode)]}),(0,n.jsxs)("span",{className:"tm-badge",children:[v.durationMs," ms"]}),v.truncated?(0,n.jsx)("span",{className:"tm-badge tm-badge-warn",children:"truncated"}):null,v.timedOut?(0,n.jsx)("span",{className:"tm-badge tm-badge-warn",children:"timed out"}):null]}),v.stdout.length>0?(0,n.jsx)("pre",{className:"tm-stdout",children:v.stdout}):null,v.stderr.length>0?(0,n.jsx)("pre",{className:"tm-stderr",children:v.stderr}):null]}):null,(0,n.jsx)("ul",{className:"tm-events",role:"log","aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false","aria-label":"Recent terminal events",children:w.map((e,t)=>{var a;let l;return(0,n.jsxs)("li",{className:"tm-event",children:[(0,n.jsx)("span",{className:"tm-event-kind",children:function(e){switch(e){case"execution-started":return"started";case"execution-completed":return"completed";case"execution-failed":return"failed";case"execution-cancelled":return"cancelled"}}(e.kind)}),(0,n.jsx)("span",{className:"tm-event-detail",children:(l=(a=e).payload,"execution-completed"===a.kind?["number"==typeof l.exitCode||null===l.exitCode?`exit ${String(l.exitCode)}`:"","number"==typeof l.durationMs?`${String(l.durationMs)}ms`:""].filter(Boolean).join(" · "):"execution-failed"===a.kind?"string"==typeof l.code?l.code:"":"execution-started"===a.kind&&"string"==typeof l.command?l.command:"")})]},`${e.executionId}-${String(t)}-${e.kind}`)})})]})}function rU(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function rW(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function rV(e){return("dry-run"===e.status||"fix-proposed"===e.status)&&void 0!==e.proposedDiff&&void 0===e.appliedAt}function rH(e){return void 0!==e.proposedDiff&&""!==e.proposedDiff}function rY({href:e,hasManifest:t,error:a}){return t?(0,n.jsx)("a",{className:"rv-evidence-link",href:e,target:"_blank",rel:"noopener noreferrer",children:"Evidence"}):null!==a?(0,n.jsxs)("span",{className:"rv-evidence-link rv-evidence-error",role:"alert",children:["Evidence error: ",a.message]}):(0,n.jsx)("button",{type:"button",className:"rv-evidence-link rv-evidence-disabled",disabled:!0,children:"Evidence"})}function rG({tokens:e}){return(0,n.jsx)(n.Fragment,{children:e.map((e,t)=>(0,n.jsx)("span",{className:`hl-${e[0]}`,children:e[1]},t))})}function rJ({line:e,lang:t}){let a,l="add"===e.kind?"+":"del"===e.kind?"−":"ctx"===e.kind?"·":"",i="ctx"===e.kind?"":` rv-${e.kind}`;if("meta"!==e.kind&&"code"!==t){let l=i_(e.text,iz(t))[0]??[];a=(0,n.jsx)(rG,{tokens:l})}else a=e.text;return(0,n.jsxs)("div",{className:`rv-line${i}`,children:[(0,n.jsx)("span",{className:"rv-sr-only",children:{add:"Added line",del:"Deleted line",ctx:"Context line",meta:"Diff metadata"}[e.kind]}),(0,n.jsx)("span",{className:"rv-num-old rv-num",children:e.oldLine??""}),(0,n.jsx)("span",{className:"rv-num-new rv-num",children:e.newLine??""}),(0,n.jsx)("span",{className:"rv-gutter","aria-hidden":"true",children:l}),(0,n.jsx)("code",{className:"rv-src",children:a})]})}function rX({hunk:e,lang:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"rv-hunk mono","aria-label":`Hunk header ${e.header}`,children:[(0,n.jsx)("span",{className:"rv-sr-only",children:"Hunk header"}),e.header]}),e.lines.map((e,a)=>(0,n.jsx)(rJ,{line:e,lang:t},a))]})}function rQ({file:e,index:t,changedFiles:a,sectionRef:l}){let i=a.find(t=>t.path===e.path),r=e.path.includes(".")?e.path.split(".").pop()??"code":"code";return(0,n.jsxs)("section",{id:`rv-file-${t}`,"aria-labelledby":`rv-file-${t}-h`,ref:l,children:[(0,n.jsxs)("h3",{id:`rv-file-${t}-h`,className:"rv-file mono",children:[(0,n.jsx)("span",{className:"rv-path",children:e.path}),void 0!==e.oldPath&&(0,n.jsxs)("span",{className:"rv-oldpath",children:[" (was ",e.oldPath,")"]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"rv-stat add",children:["+",e.addedLines]}),(0,n.jsxs)("span",{className:"rv-stat del",children:["−",e.removedLines]}),i?.elevatedReview===!0&&(0,n.jsx)("span",{className:"rv-elevated","aria-label":"Elevated review",children:"!"})]}),(0,n.jsx)("div",{className:"rv-code mono",children:e.hunks.map((e,t)=>(0,n.jsx)(rX,{hunk:e,lang:r},t))})]})}function rZ({runId:e,onRunIdSubmit:t}){let[l,i]=(0,a.useState)(null),[r,s]=(0,a.useState)(!1),[o,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!1),[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(null),[y,j]=(0,a.useState)(""),[k,N]=(0,a.useState)(!1),S=(0,a.useRef)(null);(0,a.useEffect)(()=>()=>{null!==S.current&&window.clearTimeout(S.current)},[]),(0,a.useEffect)(()=>{if(void 0===e||""===e)return;let t=!1;return u(!0),m(null),i(null),s(!1),c(null),x(null),Promise.allSettled([(0,w.fetchRunReport)(e),(0,w.fetchEvidenceManifest)(e)]).then(([e,n])=>{if(!t){if("fulfilled"===n.status)s(!0),c(null);else{let e=rW(n.reason);s(!1),c("NOT_FOUND"===e.code?null:e)}if("fulfilled"===e.status){i(e.value.report),u(!1);return}m(rW(e.reason)),u(!1)}}),()=>{t=!0}},[e]);let C=`/api/evidence/${encodeURIComponent(e??"")}`,I=(0,a.useMemo)(()=>l?.proposedDiff!==void 0?function(e){let t=new TextEncoder,n=t.encode(e).byteLength;if(0===e.length)return{files:[],truncated:!1,totalBytes:0};let a=e,l=!1;if(n>524288){l=!0;let n=t.encode(e),i=new TextDecoder().decode(n.slice(0,524288)),r=i.lastIndexOf("\n");a=-1===r?i:i.slice(0,r+1)}let i=a.split("\n"),r=i.length>0&&""===i[i.length-1]?i.slice(0,-1):i,s=[],o=null,c=null,d=0,u=0,p=()=>{null!==o&&null!==c&&o.hunks.push(c),c=null},m=()=>{p(),null!==o&&(s.length<400?s.push(o):l=!0),o=null},h=0;for(;h<r.length;){let e=r[h]??"";if(e.startsWith("diff --git ")){m();let t=/^diff --git a\/(.+?) b\/(.+)$/.exec(e);if(null!==t&&void 0!==t[1]&&void 0!==t[2]){let e=t[1],n=t[2],a=rU(`b/${n}`),l=rU(`a/${e}`),i={path:a,hunks:[],addedLines:0,removedLines:0};l!==a&&(i.oldPath=l),o=i}h++;continue}if(null!==c){if(e.startsWith("+")){let t={kind:"add",oldLine:null,newLine:u,text:e.slice(1)};c.lines.push(t),null!==o&&o.addedLines++,u++,h++;continue}if(e.startsWith("-")){let t={kind:"del",oldLine:d,newLine:null,text:e.slice(1)};c.lines.push(t),null!==o&&o.removedLines++,d++,h++;continue}if(e.startsWith("\\ ")){let t={kind:"meta",oldLine:null,newLine:null,text:e};c.lines.push(t),h++;continue}if(e.startsWith(" ")||""===e){let t={kind:"ctx",oldLine:d,newLine:u,text:e.startsWith(" ")?e.slice(1):e};c.lines.push(t),d++,u++,h++;continue}}if(e.startsWith("--- ")){let t=e.slice(4);if("/dev/null"!==t&&null===o)m(),o={path:rU(t),hunks:[],addedLines:0,removedLines:0};else if("/dev/null"!==t&&null!==o){let e=rU(t);e!==o.path&&(o.oldPath=e)}h++;continue}if(e.startsWith("+++ ")){let t=e.slice(4);"/dev/null"!==t&&null!==o?o.path=rU(t):"/dev/null"!==t&&(m(),o={path:rU(t),hunks:[],addedLines:0,removedLines:0}),h++;continue}if(e.startsWith("@@ ")){null===o&&(o={path:"(unknown)",hunks:[],addedLines:0,removedLines:0}),p();let t=function(e){let t=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);return null===t||void 0===t[1]||void 0===t[2]?null:{oldStart:parseInt(t[1],10),newStart:parseInt(t[2],10)}}(e);d=t?.oldStart??1,u=t?.newStart??1,c={header:e,lines:[]},h++;continue}h++}return m(),{files:s,truncated:l,totalBytes:n}}(l.proposedDiff):null,[l?.proposedDiff]),E=l?.changedFiles??[],R=(0,a.useMemo)(()=>({added:I?.files.reduce((e,t)=>e+t.addedLines,0)??0,removed:I?.files.reduce((e,t)=>e+t.removedLines,0)??0}),[I]),$=null!==I&&I.files.length>0?Math.min(b??0,I.files.length-1):null,A=null!==$?I?.files[$]:void 0,T=l?.status==="running";return void 0===e||""===e?(0,n.jsxs)("section",{className:"review rv-empty","aria-label":"Diff review",children:[(0,n.jsx)("h2",{className:"rv-empty-h",children:"Review"}),void 0!==t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"rv-empty-p",children:"Paste a run ID below to load a proposed diff."}),(0,n.jsxs)("form",{className:"rv-empty-form",onSubmit:e=>{e.preventDefault();let n=y.trim();0!==n.length&&t(n)},children:[(0,n.jsx)("label",{className:"rv-empty-label",htmlFor:"rv-runid-input",children:"Run ID"}),(0,n.jsx)("input",{id:"rv-runid-input",className:"rv-runid-input mono",type:"text",value:y,onChange:e=>j(e.target.value),placeholder:"e.g. 7f3a9c12…"}),(0,n.jsx)("button",{type:"submit",className:"arun-btn",children:"Load run"})]})]}):(0,n.jsx)("p",{className:"rv-empty-p",children:"Enter a run ID in the window configuration to load a proposed diff."})]}):(0,n.jsxs)("section",{className:"review","aria-label":"Diff review",children:[d&&(0,n.jsxs)("div",{className:"rv-loading",role:"status","aria-busy":"true","aria-label":"Loading diff",children:[(0,n.jsx)("div",{className:"rv-skel"}),(0,n.jsx)("div",{className:"rv-skel rv-skel-sm"})]}),!d&&null!==p&&(0,n.jsxs)("div",{role:"alert",className:"rv-error",children:["NOT_FOUND"===p.code?"No run with that ID was found.":(0,n.jsxs)(n.Fragment,{children:[p.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",p.code,")"]})]}),(r||null!==o)&&(0,n.jsx)("span",{className:"rv-error-evidence",children:(0,n.jsx)(rY,{href:C,hasManifest:r,error:o})})]}),(0,n.jsx)("p",{role:"status","aria-live":"polite",className:!d&&null===p&&null!==l&&T?"rv-no-diff":"sr-only",children:!d&&null===p&&null!==l&&T?"Run is still running. The proposed diff will appear when the run completes.":""}),!d&&null===p&&null!==l&&!T&&!rH(l)&&(0,n.jsx)("p",{className:"rv-no-diff",children:"This run has no proposed diff to review."}),!d&&null===p&&null!==l&&rH(l)&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"rv-header",children:[(0,n.jsx)("span",{className:"rv-status mono",children:(0,aq.runStatusLabel)(l.status)}),void 0!==l.modelId&&(0,n.jsx)("span",{className:"rv-model mono",children:l.modelId}),(0,n.jsxs)("span",{className:"rv-counts mono",children:[null!==I&&`${I.files.length} file${1!==I.files.length?"s":""}`," ",(0,n.jsxs)("span",{className:"rv-stat add",children:["+",R.added]})," ",(0,n.jsxs)("span",{className:"rv-stat del",children:["−",R.removed]})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)(rY,{href:C,hasManifest:r,error:o})]}),null!==I&&I.files.length>0&&null!==$&&void 0!==A&&(0,n.jsxs)("div",{className:"rv-layout",children:[(0,n.jsx)("nav",{className:"rv-filelist","aria-label":"Changed files",children:(0,n.jsx)("ul",{children:I.files.map((e,t)=>{let a=E.find(t=>t.path===e.path),l=$===t;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"rv-filerow",title:e.path,"aria-pressed":l,"aria-controls":l?`rv-file-${t}`:void 0,onClick:()=>{x(t)},children:[(0,n.jsx)("span",{className:"rv-filerow-path mono",children:function(e){if(e.length<=40)return e;let t=e.split("/");return t.length<=2?e:`…/${t.slice(-2).join("/")}`}(e.path)}),(0,n.jsxs)("span",{className:"rv-stat add",children:["+",e.addedLines]}),(0,n.jsxs)("span",{className:"rv-stat del",children:["−",e.removedLines]}),a?.elevatedReview===!0&&(0,n.jsx)("span",{className:"rv-elevated","aria-label":"Elevated review",children:"!"})]})},e.path)})})}),(0,n.jsxs)("div",{className:"rv-body",children:[(0,n.jsx)(rQ,{file:A,index:$,changedFiles:E,sectionRef:()=>void 0},A.path),I.truncated&&(0,n.jsxs)("p",{role:"note",className:"rv-truncated",children:["Diff truncated at 512 KB. Open the"," ",r?(0,n.jsx)("a",{href:C,target:"_blank",rel:"noopener noreferrer",children:"evidence manifest"}):"evidence manifest"," ","for the full record."]})]})]}),(0,n.jsxs)("div",{className:"rv-controls",children:[(0,n.jsx)("span",{role:"status","aria-live":"polite",className:"rv-apply-status",children:h?"Applying…":void 0!==l.appliedAt?"Applied":""}),null!==g&&(0,n.jsx)("span",{role:"alert",className:"rv-apply-error",children:g.message}),void 0!==l.appliedAt?(0,n.jsx)("span",{className:"rv-final mono",children:"Applied"}):rV(l)?(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":h,onClick:()=>{if(!h){if(!k){N(!0),null!==S.current&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{N(!1),S.current=null},6e3);return}null!==S.current&&(window.clearTimeout(S.current),S.current=null),N(!1),void 0!==e&&null!==l&&rV(l)&&!h&&(f(!0),v(null),(0,w.applyRun)(e).then(e=>{i(e.report),f(!1)}).catch(e=>{v(rW(e)),f(!1)}))}},children:h?"Applying…":k?`Confirm apply (${(I?.files.length??0).toString()} file${I?.files.length===1?"":"s"})`:"Apply"}):null]})]})]})}let r0=["run:started","state:transition","model:call:started","model:call:completed","model:call:failed","tool:call:started","tool:call:completed","tool:call:failed","reasoning:trace","patch:proposed","verification:result","run:completed","run:cancelled","run:failed","command:executed","sandbox:configured","patch:applied","browser:session-opened","browser:navigated","browser:screenshot-captured","browser:page-content-captured","browser:session-closed","browser:trust-warning","browser:error","workflow:started","conventions:detected","context:selected","workflow:model:call:started","workflow:model:call:completed","patch:validated","workflow:patch:applied","workflow:verification:result","workflow:completed","workflow:failed","bug:started","bug:failure:parsed","bug:context:selected","bug:model:call:started","bug:model:call:completed","bug:rootcause:proposed","bug:patch:validated","bug:patch:applied","bug:verification:result","bug:completed","bug:failed","ready"],r1=new Set(["run:completed","run:cancelled","run:failed","workflow:completed","workflow:failed","bug:completed","bug:failed"]),r2=new Set(["completed","dry-run","rejected","cancelled","failed","fix-applied","fix-proposed","investigation-only"]),r4={verify:"Verify","explain-plan":"Explain plan","unit-test-generation":"Generate unit tests","bug-investigation":"Investigate bug"};function r3(e,t){return void 0===t||0===t.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:e}),(0,n.jsx)("pre",{children:t})]})}let r6={high:"High",medium:"Medium",low:"Low — verify"};function r5({level:e}){return(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Confidence"}),(0,n.jsxs)("span",{className:"ai-conf","data-level":e,children:[(0,n.jsxs)("span",{className:"track","aria-hidden":"true",children:[(0,n.jsx)("i",{}),(0,n.jsx)("i",{}),(0,n.jsx)("i",{})]}),(0,n.jsx)("span",{className:"lbl",children:r6[e]})]})]})}function r8({cfg:e={},linkedRoot:t=null,linkedFilePath:l}){var i,r;let s,o=e.runId??null,c="verify"===(i=e.workflow)||"explain-plan"===i||"unit-test-generation"===i||"bug-investigation"===i?i:null,d=e.model??"",u=function(e){if(void 0===e||0===e.length)return null;try{let t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?null:t}catch{return null}}(e.inputJson),p=function(e){let[t,n]=(0,a.useState)([]),[l,i]=(0,a.useState)("connecting"),[r,s]=(0,a.useState)(null),o=(0,a.useRef)(-1);return(0,a.useEffect)(()=>{if(null===e)return;n([]),i("connecting"),s(null),o.current=-1;let t=null,a=!1,l=`/api/runs/${encodeURIComponent(e)}/events`;(t=new EventSource(o.current>=0?`${l}?lastEventId=${o.current.toString()}`:l)).onopen=()=>{a||(i("live"),s(null))},t.onerror=()=>{a||(i("error"),s("Stream disconnected. Attempting to reconnect…"))};let r=e=>{let l;if(!a){try{l=JSON.parse(e.data)}catch{return}o.current=l.seq,n(e=>[...e,l]),r1.has(l.type)&&(i("terminal"),t?.close())}};for(let e of r0)t.addEventListener(e,r);return()=>{a=!0,t?.close()}},[e]),{events:t,status:l,error:r}}(o),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(!1),[k,N]=(0,a.useState)(null),[S,C]=(0,a.useState)(null),[I,E]=(0,a.useState)(!1),R=(0,a.useRef)(null),$=(0,a.useRef)(null),A=(0,a.useCallback)(async()=>{if(null!==o){b(null);try{let e=await (0,w.fetchRunReport)(o);h(e.report),g(null)}catch(e){if(e instanceof w.ApiError&&404===e.status){try{let e=await (0,w.fetchEvidenceManifest)(o);g(e.manifest),h(null)}catch(e){b(e instanceof Error?e.message:"Unable to load evidence.")}return}b(e instanceof Error?e.message:"Unable to load run report.")}}},[o]);(0,a.useEffect)(()=>{A()},[A]),(0,a.useEffect)(()=>{"terminal"===p.status&&A()},[A,p.status]),(0,a.useEffect)(()=>{let e=!1;if(0!==d.length)return(0,w.fetchModels)().then(t=>{e||C(t.models.find(e=>e.id===d)?.costClass??null)}).catch(()=>{e||C(null)}),()=>{e=!0}},[d]);let T=(0,a.useMemo)(()=>(function(e,t){let n=t?.usage?.promptTokens??0,a=t?.usage?.completionTokens??0,l=t?.usage?.latencyMs??0,i=+(t?.usage!==void 0);if(i>0)return{promptTokens:n,completionTokens:a,latencyMs:l,requestCount:i};for(let t of e){let e=function(e){if("model:call:completed"===e.type)return{promptTokens:e.usage.promptTokens,completionTokens:e.usage.completionTokens,latencyMs:e.usage.latencyMs,requestCount:1};let t=e.promptTokens,n=e.completionTokens,a=e.latencyMs;return"number"==typeof t&&"number"==typeof n&&"number"==typeof a?{promptTokens:t,completionTokens:n,latencyMs:a,requestCount:1}:null}(t);null!==e&&(n+=e.promptTokens,a+=e.completionTokens,l+=e.latencyMs,i+=e.requestCount)}return{promptTokens:n,completionTokens:a,latencyMs:l,requestCount:i}})(p.events,m),[p.events,m]),L=m?.durationMs??f?.run.durationMs??(p.events.length>0?Math.max(0,Date.now()-Number(new Date(p.events[0]?.ts??Date.now()))):0),P=null!==m?m.status:null!==f?f.run.outcome:"loading",M=null!==m?(0,aq.runStatusLabel)(m.status):null!==f?(0,aq.outcomeLabel)(f.run.outcome):"Loading…",D=null!==m&&r2.has(m.status),q=null!==m&&void 0!==m.proposedDiff&&void 0===m.appliedAt&&("unit-test-generation"===c&&"dry-run"===m.status||"bug-investigation"===c&&"fix-proposed"===m.status),F=!D&&m?.status==="running",O=function(e){if(void 0===e||0===e.length)return 0;let t=e.match(/^diff --git /gm);if(null!==t)return t.length;let n=e.match(/^\+\+\+ /gm);return null===n?0:n.length}(m?.proposedDiff),z=x||"connecting"===p.status||m?.status==="running"||null===m&&null===f&&null===v,K=(0,a.useRef)(!1);(0,a.useEffect)(()=>{K.current&&!F&&document.activeElement===document.body&&$.current?.focus(),K.current=F},[F]),(0,a.useEffect)(()=>()=>{null!==R.current&&window.clearTimeout(R.current)},[]);let B=async()=>{if(null!==o){b(null);try{await (0,w.cancelRun)(o),await A()}catch(e){b(e instanceof Error?e.message:"Unable to cancel run.")}}},_=async()=>{if(null!==o&&q&&!x){y(!0),N(null);try{let e=await (0,w.applyRun)(o);h(e.report)}catch(e){N(e instanceof Error?e.message:"Unable to apply run.")}finally{y(!1)}}};return null===o||null===c?(0,n.jsxs)("div",{className:"arun arun-empty",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Agent run is not configured."}),(0,n.jsx)("p",{children:"Open a new Agent window from the launcher to start a workflow."})]}):(0,n.jsxs)("div",{className:"arun arun-real","aria-busy":z?"true":void 0,children:[(0,n.jsxs)("div",{className:"arun-head",children:[(0,n.jsx)("span",{className:"arun-role",children:r4[c]}),d.length>0?(0,n.jsx)("span",{className:"ag-model mono",children:d}):null,null!==S?(0,n.jsx)("span",{className:"arun-gov",title:"Model cost class",children:(0,aq.costClassLabel)(S)}):null,(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"arun-status",children:[(0,n.jsx)("span",{className:"dot","data-live":m?.status==="running","data-status":P}),M]})]}),(0,n.jsxs)("div",{className:"arun-summary",role:"status","aria-live":"polite",children:[(0,n.jsx)("strong",{children:function(e,t,n){if(null===t&&null===n)return"Loading run state…";let a=null===e?"Agent run":r4[e];return t?.status==="running"?`${a} is running.`:t?.status==="dry-run"?`${a} produced a reviewable dry-run.`:t?.status==="fix-proposed"?`${a} proposed a fix.`:t?.status==="fix-applied"?`${a} applied changes.`:t?.status==="investigation-only"?`${a} completed without a patch.`:t?.status==="failed"||t?.status==="rejected"?`${a} failed.`:t?.status==="cancelled"?`${a} was cancelled.`:null!==t?`${a} completed.`:n?.patch?.redactedDiff!==void 0?`${a} evidence loaded with a reviewable diff.`:`${a} evidence loaded: ${n?.run.outcome??"unknown"}.`}(c,m,f)}),(0,n.jsxs)("span",{className:"mono",title:o,children:["run ",o.slice(0,8)]})]}),(0,n.jsxs)("div",{className:"arun-meters",children:[(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Elapsed"}),(0,n.jsx)("span",{className:"arun-mv mono",children:(0,aq.formatMs)(L)})]}),(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Usage"}),(0,n.jsx)("span",{className:"arun-mv mono",children:0===T.requestCount?"No model usage":`${(0,aq.formatTokens)(T.promptTokens+T.completionTokens)} tok`})]}),(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Latency"}),(0,n.jsx)("span",{className:"arun-mv mono",children:0===T.requestCount?"—":(0,aq.formatMs)(T.latencyMs)})]})]}),(0,n.jsxs)("div",{className:"arun-perms",children:[(0,n.jsxs)("span",{className:"arun-perm","data-on":null!==t,title:null!==t?t:e.workspaceRoot??void 0,children:[(0,n.jsx)(j.Icons.files,{size:11}),(0,n.jsx)("span",{className:"arun-perm-path",children:null!==t?t:e.workspaceRoot??"no workspace"})]}),void 0!==l?(0,n.jsxs)("span",{className:"arun-perm","data-on":!0,title:l,children:[(0,n.jsx)(j.Icons.files,{size:11}),(0,n.jsx)("span",{className:"arun-perm-path",children:l})]}):null]}),null!==u?(0,n.jsxs)("details",{className:"arun-input",children:[(0,n.jsx)("summary",{children:"Run input"}),(0,n.jsx)("pre",{children:JSON.stringify(u,null,2)})]}):null,(0,n.jsxs)("div",{className:"arun-log",role:"log","aria-live":"polite","aria-label":"Run events","aria-busy":z?"true":void 0,children:["error"===p.status&&null!==p.error?(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:p.error})]}):null,0===p.events.length?"error"===p.status?null:(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:"connecting"===p.status?"Connecting to run events…":"Waiting for run events…"})]}):p.events.slice().reverse().slice(0,50).map(e=>{let t;return(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.spark,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:function(e){switch(e.type){case"ready":return"SSE stream ready";case"run:started":return`Started ${e.taskType}`;case"run:completed":return"Run completed";case"run:failed":return`Run failed: ${e.failure.message}`;case"run:cancelled":return"Run cancelled";case"state:transition":return`${e.from} -> ${e.to}${void 0===e.reason?"":`: ${e.reason}`}`;case"model:call:started":return`Model call started (${(0,aq.formatBytes)(e.contextBytes)})`;case"model:call:completed":return`Model call completed (${(0,aq.formatTokens)(e.usage.promptTokens+e.usage.completionTokens)} tokens)`;case"model:call:failed":return`Model call failed: ${e.message}`;case"patch:proposed":return`Patch proposed (${(0,aq.formatBytes)(e.patchBytes)})`;case"verification:result":return`Verification ${e.passed?"passed":"failed"}: ${e.detail}`;case"workflow:started":return"Unit-test workflow started";case"workflow:model:call:completed":return`Unit-test model call completed (${(0,aq.formatTokens)(e.promptTokens+e.completionTokens)} tokens)`;case"workflow:verification:result":return`Unit-test verification ${e.overallStatus}`;case"workflow:completed":return`Unit-test workflow ${e.status}`;case"workflow:failed":return`Unit-test workflow failed: ${e.message}`;case"bug:started":return"Bug investigation started";case"bug:model:call:completed":return`Bug model call completed (${(0,aq.formatTokens)(e.promptTokens+e.completionTokens)} tokens)`;case"bug:rootcause:proposed":return`Root cause proposed${e.hasPatch?" with patch":""}`;case"bug:verification:result":return`Bug verification ${e.overallStatus}`;case"bug:completed":return`Bug investigation ${e.status}`;case"bug:failed":return`Bug investigation failed: ${e.message}`;default:return e.type}}(e)}),(0,n.jsx)("span",{className:"arun-log-t mono",children:Number.isFinite(t="number"==typeof e.ts?e.ts:Date.parse(e.ts))?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""})]},`${e.runId}:${e.seq}:${e.type}`)})]}),null!==m?(0,n.jsxs)("div",{className:"arun-results",children:[void 0===m.report?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Report"}),(0,n.jsx)("pre",{children:m.report})]}),void 0===m.overallStatus||void 0===m.results?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Status"}),(0,n.jsx)("strong",{children:m.overallStatus})]}),m.results.slice(0,8).map(e=>(0,n.jsxs)("div",{className:"arun-check-row",children:[(0,n.jsx)("span",{children:e.kind}),(0,n.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),r3("Failure",m.failureReason),r3("Covered behavior",m.coveredBehavior),r3("Known gaps",m.knownGaps),r3("Verification note",m.verificationSkipReason),function(e){let t=e.hypothesis;if(void 0===t)return null;let a=[["Root cause",t.rootCause],["Regression test",t.regressionTestStrategy],["Uncertainty",t.uncertainty]].filter(e=>"string"==typeof e[1]&&e[1].length>0),l="string"==typeof t.confidence?t.confidence:"",i="low"===l||"medium"===l||"high"===l?l:void 0,r=l.length>0&&void 0===i?l:void 0;return 0===a.length&&void 0===i&&void 0===r?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Hypothesis"}),a.map(([e,t])=>(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:e}),(0,n.jsx)("strong",{children:t})]},e)),void 0!==r?(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Confidence"}),(0,n.jsx)("strong",{children:r})]}):null,void 0!==i?(0,n.jsx)(r5,{level:i}):null]})}(m),void 0===(r=m.nextActions)||0===r.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Next actions"}),r.map(e=>(0,n.jsx)("div",{className:"arun-check-row",children:(0,n.jsx)("span",{children:e})},e))]}),void 0!==m.dryRunPreview?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Dry-run preview"}),(0,n.jsx)("pre",{children:m.dryRunPreview})]}):null,void 0!==m.proposedDiff?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Proposed diff"}),(0,n.jsx)("pre",{children:m.proposedDiff})]}):null,void 0===(s=m.verificationSummary)?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Status"}),(0,n.jsx)("strong",{children:s.overallStatus})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Duration"}),(0,n.jsx)("strong",{children:(0,aq.formatMs)(s.durationMs)})]}),s.results.slice(0,5).map(e=>(0,n.jsxs)("div",{className:"arun-check-row",children:[(0,n.jsx)("span",{children:e.kind}),(0,n.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),void 0!==m.applyReport?(0,n.jsxs)("div",{className:"arun-result-card arun-applied",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Applied"}),(0,n.jsx)("pre",{children:JSON.stringify(m.applyReport,null,2)})]}):null]}):null!==f?(0,n.jsxs)("div",{className:"arun-results",children:[(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Evidence"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Outcome"}),(0,n.jsx)("strong",{children:f.run.outcome})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Duration"}),(0,n.jsx)("strong",{children:(0,aq.formatMs)(f.run.durationMs)})]}),void 0!==f.patch?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Changed files"}),(0,n.jsx)("strong",{children:f.patch.changedFiles.toString()})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Patch size"}),(0,n.jsx)("strong",{children:(0,aq.formatBytes)(f.patch.patchBytes)})]})]}):null]}),f.patch?.redactedDiff!==void 0?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Proposed diff"}),(0,n.jsx)("pre",{children:f.patch.redactedDiff})]}):null]}):null,null!==v?(0,n.jsx)("div",{className:"arun-error",role:"alert",children:v}):null,null!==k?(0,n.jsx)("div",{className:"arun-error",role:"alert",children:k}):null,(0,n.jsxs)("div",{className:"arun-controls",children:[(0,n.jsx)("a",{className:"arun-btn ghost",href:`/api/evidence/${encodeURIComponent(o)}`,target:"_blank",rel:"noreferrer",ref:$,children:"Evidence"}),q?(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":x,onClick:()=>{if(!x){if(!I){E(!0),null!==R.current&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{E(!1),R.current=null},6e3);return}null!==R.current&&(window.clearTimeout(R.current),R.current=null),E(!1),_()}},children:x?"Applying…":I?`Confirm apply (${O.toString()} file${1===O?"":"s"})`:"Apply"}):m?.appliedAt!==void 0?(0,n.jsx)("span",{className:"arun-final mono",children:"Applied"}):null,F?(0,n.jsx)("button",{type:"button",className:"arun-btn danger",onClick:()=>void B(),children:"Cancel"}):null]})]})}let r7=[{name:"Messaging",desc:"Catch up on threads",glyph:"#"},{name:"GitHub",desc:"PRs, code & CI",glyph:"{ }"},{name:"Linear",desc:"Track issues",glyph:"⊿"},{name:"Slack",desc:"Team channels",glyph:"≡"},{name:"Sentry",desc:"Error tracking",glyph:"◎"}];function r9(){return(0,n.jsx)("ul",{className:"integ","aria-label":"Integrations",children:r7.map(e=>(0,n.jsxs)("li",{className:"integ-row",children:[(0,n.jsx)("span",{className:"integ-glyph mono",children:e.glyph}),(0,n.jsxs)("span",{className:"integ-text",children:[(0,n.jsx)("span",{className:"integ-name",children:e.name}),(0,n.jsx)("span",{className:"integ-desc",children:e.desc})]}),(0,n.jsx)("span",{className:"integ-status",children:"Not connected — coming soon"})]},e.name))})}let se={allow:["Allow","var(--accent)"],ask:["Ask","var(--warn)"],deny:["Deny","var(--danger)"]},st={allow:"ask",ask:"deny",deny:"allow"},sn=[{id:1,label:"Write src/windows.jsx",kind:"write",risk:"low",expect:"allow"},{id:2,label:"Overwrite prod/secrets.env",kind:"write",risk:"high",expect:"deny"},{id:3,label:"Run `npm test`",kind:"command",risk:"low",expect:"allow"},{id:4,label:"Run `kubectl apply` → prod",kind:"command",risk:"high",expect:"ask"},{id:5,label:"Open pull request #142",kind:"git",risk:"low",expect:"allow"},{id:6,label:"Email the customer",kind:"mail",risk:"low",expect:"ask"}],sa=[["Developer","Codes, reviews diffs, runs tests, opens PRs"],["Product Owner","Searches docs, drafts Jira tickets, plans releases"],["Designer","Explores UI options, reviews flows, writes specs"]],sl=[["calendar","Calendar","automations"],["mail","Mail","bell"],["jira","Jira","review"],["docs","Docs","files"]];function si({policy:e,setPolicy:t}){return(0,n.jsxs)("div",{className:"pol",children:[(0,n.jsx)("div",{className:"pol-hint",children:"Rights an agent inherits when Keiko governs. Tap a decision to cycle through Allow → Ask → Deny."}),e.map(e=>{let a=se[e.decision];return(0,n.jsxs)("div",{className:"pol-row",children:[(0,n.jsxs)("div",{className:"pol-text",children:[(0,n.jsx)("span",{className:"pol-action",children:e.action}),(0,n.jsx)("span",{className:"pol-scope mono",children:e.scope})]}),(0,n.jsx)("button",{type:"button",className:"pol-dec",style:{color:a[1],borderColor:a[1]},onClick:()=>{let n;return n=e.id,t(e=>e.map(e=>e.id===n?{...e,decision:st[e.decision]}:e))},children:a[0]})]},e.id)})]})}function sr({decide:e}){let[t,l]=(0,a.useState)(!1),i=sn.map(t=>{let n=e(t.kind,t.risk);return{...t,actual:n,pass:n===t.expect}}),r=i.filter(e=>e.pass).length;return(0,n.jsxs)("div",{className:"evl",children:[(0,n.jsxs)("div",{className:"evl-head",children:[(0,n.jsxs)("button",{type:"button",className:"evl-run",onClick:()=>l(!0),children:[(0,n.jsx)(j.Icons.spark,{size:13})," Run evaluation"]}),t&&(0,n.jsxs)("span",{className:"evl-score"+(r===i.length?" ok":""),children:[r,"/",i.length," passed"]})]}),(0,n.jsx)("div",{className:"evl-hint",children:"Mock scenarios against your policy before going autonomous."}),i.map(e=>(0,n.jsxs)("div",{className:"evl-row","data-state":t?e.pass?"pass":"fail":"idle",children:[(0,n.jsx)("span",{className:"evl-ico",children:t?e.pass?(0,n.jsx)(j.Icons.check,{size:13}):(0,n.jsx)(j.Icons.close,{size:13}):(0,n.jsx)("span",{className:"evl-dot"})}),(0,n.jsx)("span",{className:"evl-label",children:e.label}),t&&(0,n.jsx)("span",{className:"evl-res mono",style:{color:se[e.actual][1]},children:se[e.actual][0]})]},e.id))]})}function ss({bridges:e,setBridges:t}){return(0,n.jsxs)("div",{className:"brg",children:[(0,n.jsx)("div",{className:"evl-hint",children:"What your twin can reach on your behalf."}),sl.map(([a,l,i])=>{let r=j.Icons[i],s=e[a];return(0,n.jsxs)("button",{type:"button",className:"brg-row","data-on":s,"aria-pressed":s,onClick:()=>t(e=>({...e,[a]:!e[a]})),children:[(0,n.jsx)("span",{className:"brg-ico",children:(0,n.jsx)(r,{size:16})}),(0,n.jsx)("span",{className:"brg-name",children:l}),(0,n.jsx)("span",{className:"brg-tg"+(s?" on":""),children:(0,n.jsx)("span",{})})]},a)})]})}function so({persona:e,setPersona:t}){return(0,n.jsxs)("div",{className:"prs",children:[(0,n.jsx)("div",{className:"evl-hint",children:"Keiko adapts behaviour & tools to who is at the wheel."}),sa.map(([a,l])=>(0,n.jsxs)("button",{type:"button",className:"prs-row","data-on":e===a,"aria-pressed":e===a,onClick:()=>t(a),children:[(0,n.jsx)("span",{className:"prs-dot"}),(0,n.jsxs)("span",{className:"prs-text",children:[(0,n.jsx)("span",{className:"prs-name",children:a}),(0,n.jsx)("span",{className:"prs-desc",children:l})]}),e===a&&(0,n.jsx)(j.Icons.check,{size:14,style:{color:"var(--accent)"}})]},a))]})}let sc=[["policy","Policy"],["eval","EVAL"],["bridges","Connections"],["persona","Persona"]];function sd(){let e=x(),[t,l]=(0,a.useState)("policy");return(0,n.jsxs)("div",{className:"twin",children:[(0,n.jsxs)("div",{className:"twin-hero",children:[(0,n.jsx)("img",{className:"twin-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsxs)("div",{className:"twin-id",children:[(0,n.jsx)("span",{className:"twin-name",children:"Keiko — Digital Twin"}),(0,n.jsxs)("span",{className:"twin-sub mono",children:["mirroring · ",e.persona]})]}),(0,n.jsx)("span",{className:"twin-mode "+("autonomous"===e.mode?"on":""),children:"autonomous"===e.mode?"Autonomous":"Manual"})]}),(0,n.jsx)("div",{className:"twin-tabs",children:sc.map(([e,a])=>(0,n.jsx)("button",{type:"button",className:"twin-tab","data-on":t===e,onClick:()=>l(e),children:a},e))}),(0,n.jsxs)("div",{className:"twin-body",children:["policy"===t&&(0,n.jsx)(si,{policy:e.policy,setPolicy:e.setPolicy}),"eval"===t&&(0,n.jsx)(sr,{decide:e.decide}),"bridges"===t&&(0,n.jsx)(ss,{bridges:e.bridges,setBridges:e.setBridges}),"persona"===t&&(0,n.jsx)(so,{persona:e.persona,setPersona:e.setPersona})]})]})}function su(e){return"embedding-only"===e?"Embedding model — not selectable for text conversation":"ocr-vision-only"===e?"OCR/vision-only — not selectable for text conversation":"Not a chat model — not selectable for text conversation"}function sp(){return"Available for embeddings; not shown in the chat model picker"}function sm({model:e}){let t=function(e){if("chat"!==e.kind)return ny[e.kind]}(e);return void 0===t?(0,n.jsx)("span",{className:"ml-elig ml-elig-ok","data-testid":"conv-elig-ok",role:"status","aria-label":"Model eligibility: eligible for conversation",children:"Conversation-eligible"}):"embedding-only"===t?(0,n.jsx)("span",{className:"ml-elig ml-elig-embed","data-testid":"embedding-elig-ok",role:"status","aria-label":"Model eligibility: "+sp(),title:sp(),children:"Embedding-ready"}):(0,n.jsxs)("span",{className:"ml-elig ml-elig-no","data-testid":"conv-elig-no",role:"status","aria-label":"Model eligibility: "+su(t),title:su(t),children:["Not selectable — ","ocr-vision-only"===t?"OCR/vision-only":"not a chat model"]})}function sh({model:e}){var t;let a=nx(e),l="embedding"===e.kind;return(0,n.jsxs)("div",{className:"ml-row",children:[(0,n.jsx)("span",{className:"ml-ico",children:(0,n.jsx)(j.Icons.cube,{size:16})}),(0,n.jsxs)("div",{className:"ml-info",children:[(0,n.jsxs)("div",{className:"ml-top",children:[(0,n.jsx)("span",{className:"ml-name",children:e.id}),(0,n.jsx)("span",{className:"ml-type mono",children:"ocr-vision"===(t=e.kind)?"OCR":t}),(0,n.jsx)(sm,{model:e})]}),(0,n.jsxs)("div",{className:"ml-url mono",children:["tools ",e.toolCalling?"yes":"no"," · structured"," ",e.structuredOutput?"yes":"no"," · ",e.costClass,"/",e.latencyClass]})]}),(0,n.jsx)("span",{className:"ml-status "+(a||l?"connected":"ineligible"),title:a?"conversation-eligible":l?"available for embeddings":"not selectable for conversation","aria-hidden":"true"})]})}function sf(){let[e,t]=(0,a.useState)(eo),[l,i]=(0,a.useState)(ec),[r,s]=(0,a.useState)(ed),[o,c]=(0,a.useState)(eu),[d,u]=(0,a.useState)(ep),[p,m]=(0,a.useState)(em);(0,a.useEffect)(()=>{try{window.localStorage.setItem(G,e?"true":"false")}catch{}window.dispatchEvent(new CustomEvent(et,{detail:e}))},[e]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(J,String(l))}catch{}window.dispatchEvent(new CustomEvent(en,{detail:l}))},[l]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(X,String(r))}catch{}eh(r),window.dispatchEvent(new CustomEvent(ea,{detail:r}))},[r]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(Q,String(o))}catch{}ef(o),window.dispatchEvent(new CustomEvent(el,{detail:o}))},[o]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(Z,String(d))}catch{}eg(d),window.dispatchEvent(new CustomEvent(ei,{detail:d}))},[d]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(ee,String(p))}catch{}ev(p),window.dispatchEvent(new CustomEvent(er,{detail:p}))},[p]);let h={"--p":`${String(l)}%`},f={"--p":`${String(r)}%`},g={"--p":`${String(o)}%`},v={"--p":`${String(d)}%`},b={"--p":`${String(p)}%`};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"set-sec-h",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"set-sec-t",children:"Workspace wallpaper"}),(0,n.jsx)("div",{className:"set-sec-d",children:"Liquid Chrome — a subtle metallic flow behind the grid that reacts to your cursor and clicks. Turn it off to stop the WebGL animation completely."})]})}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"gpref-label",children:"Liquid wallpaper"}),(0,n.jsx)("div",{className:"gpref-help",children:e?"Running":"Stopped"})]}),(0,n.jsx)(lM,{on:e,onChange:t,label:"Liquid wallpaper"})]}),(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"wp-op",children:"Wallpaper opacity"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[l,"%"]})]}),(0,n.jsx)("input",{id:"wp-op",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:l,disabled:!e,onChange:e=>i(Number.parseInt(e.target.value,10)),style:h,"aria-label":"Wallpaper opacity"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Off"}),(0,n.jsx)("span",{children:"Full"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"ws-bg-bright",children:"Workspace background brightness"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[r,"%"]})]}),(0,n.jsx)("input",{id:"ws-bg-bright",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:r,onChange:e=>s(Number.parseInt(e.target.value,10)),style:f,"aria-label":"Workspace background brightness"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Base"}),(0,n.jsx)("span",{children:"Lighter"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"ws-grid-strength",children:"Workspace grid strength"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[o,"%"]})]}),(0,n.jsx)("input",{id:"ws-grid-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:o,onChange:e=>c(Number.parseInt(e.target.value,10)),style:g,"aria-label":"Workspace grid strength"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Subtle"}),(0,n.jsx)("span",{children:"Strong"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"frame-border-strength",children:"Workspace border strength"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[d,"%"]})]}),(0,n.jsx)("input",{id:"frame-border-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:d,onChange:e=>u(Number.parseInt(e.target.value,10)),style:v,"aria-label":"Workspace border strength"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Subtle"}),(0,n.jsx)("span",{children:"Strong"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"frame-inner-glow-strength",children:"Workspace inner glow"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[p,"%"]})]}),(0,n.jsx)("input",{id:"frame-inner-glow-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:p,onChange:e=>m(Number.parseInt(e.target.value,10)),style:b,"aria-label":"Workspace inner glow"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Off"}),(0,n.jsx)("span",{children:"Strong"})]})]})]})}function sg(){let[e,t]=(0,a.useState)("models"),[l,i]=(0,a.useState)([]),[r,s]=(0,a.useState)(null),[o,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(!0),[p,m]=(0,a.useState)(),[h,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(0);(0,a.useEffect)(()=>{let e=!1;return async function(){u(!0),m(void 0);try{let[t,n]=await Promise.all([(0,w.fetchConfig)(),(0,w.fetchModels)()]);if(e)return;s(t.config),c(t.configPresent),i(n.models)}catch(t){if(e)return;m(function(e){let t="Could not load gateway settings — the local Keiko backend did not respond.";if(!(e instanceof Error))return t;let n=e.message.trim();return 0===n.length||/^HTTP \d+$/u.test(n)||"Failed to fetch"===n||"Load failed"===n||"NetworkError when attempting to fetch a resource."===n?t:n}(t))}finally{e||u(!1)}}(),()=>{e=!0}},[g]);let b=l.filter(nx).length,x=l.length>0,y=o?x?0===b?"Gateway connected, but none of the discovered models can be used for conversation. Add a chat-capable deployment.":"Keiko can use the configured gateway models for chat and agent workflows.":"The gateway is configured, but no conversation-capable models are currently available.":"Enter the gateway base URL and API token before using chat or agent workflows.",k=o?"connected":"untested";return(0,n.jsxs)("div",{className:"set",children:[(0,n.jsxs)("div",{className:"set-hero",children:[(0,n.jsx)(j.Icons.settings,{size:18}),(0,n.jsx)("span",{className:"set-title",children:"Settings"}),(0,n.jsxs)("span",{className:"set-onprem",title:"Runs inside your network",children:[(0,n.jsx)("span",{className:"dot",style:{background:"var(--accent)"}})," Self-hosted"]})]}),(0,n.jsx)("div",{className:"set-tabs",children:["models","general","security"].map(a=>(0,n.jsx)("button",{type:"button",className:"set-tab","data-on":e===a,"aria-pressed":e===a,onPointerDown:()=>t(a),onClick:()=>t(a),children:"models"===a?"Models":"general"===a?"General":"Security"},a))}),(0,n.jsxs)("div",{className:"set-body",children:["models"===e&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"set-sec-h",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"set-sec-t",children:"Model gateway"}),(0,n.jsx)("div",{className:"set-sec-d",children:"Credentials are stored locally by the Keiko loopback server; secrets are never returned to the browser."})]}),(0,n.jsxs)("button",{type:"button",className:"set-add",onClick:()=>f(!0),children:[(0,n.jsx)(j.Icons.plus,{size:14}),o?"Update credentials":"Connect gateway"]})]}),(0,n.jsxs)("div",{className:"ml-row",children:[(0,n.jsx)("span",{className:"ml-ico",children:(0,n.jsx)(j.Icons.cube,{size:16})}),(0,n.jsxs)("div",{className:"ml-info",children:[(0,n.jsxs)("div",{className:"ml-top",children:[(0,n.jsx)("span",{className:"ml-name",children:o?x?"Gateway connected":"Gateway configured":"Gateway setup required"}),(0,n.jsxs)("span",{className:"ml-type mono",children:[l.length.toString()," models"]}),(0,n.jsxs)("span",{className:"ml-type mono",children:[b.toString()," chat"]})]}),(0,n.jsx)("div",{className:"ml-url mono",children:y})]}),(0,n.jsx)("span",{className:"ml-status "+k,title:o?"gateway configured":"setup required","aria-hidden":"true"})]}),void 0!==p?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[p,(0,n.jsx)("button",{type:"button",className:"gw-error-retry",onClick:()=>v(e=>e+1),children:"Retry"})]}):null,d?(0,n.jsx)("div",{className:"set-placeholder",role:"status",children:"Loading gateway models…"}):0===l.length?(0,n.jsx)("div",{className:"set-placeholder",role:"status",children:o?"No conversation-capable models are currently available. Review the gateway configuration or discovered model set.":"No models are configured yet. Connect the gateway to load configured model capabilities."}):(0,n.jsx)("div",{className:"set-list",children:l.map(e=>(0,n.jsx)(sh,{model:e},e.id))}),h?(0,n.jsx)(tD,{onCancel:()=>f(!1),preserveExisting:o,storedApiKeyHeaderName:r?.providers[0]?.credentialHeaderName,storedModels:l}):null]}),"general"===e&&(0,n.jsx)(sf,{}),"security"===e&&(0,n.jsx)("div",{className:"set-placeholder",children:"SSO · audit log · data residency — coming soon."})]})]})}function sv(e){return e instanceof w.ApiError?`${e.message} (${e.code})`:e instanceof Error?e.message:"Failed to load connectors."}function sb(){return(0,n.jsx)("div",{className:"connector-picker-status",role:"status","aria-live":"polite",children:"Loading connectors…"})}function sx({message:e,onRetry:t}){return(0,n.jsxs)("div",{className:"connector-picker-error",role:"alert",children:[(0,n.jsx)("p",{children:e}),(0,n.jsx)("button",{type:"button",className:"connector-picker-retry",onClick:t,children:"Try again"})]})}function sy({onManageConnectors:e}){return(0,n.jsx)("div",{className:"connector-picker-empty",children:(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary connector-picker-create-link",onClick:e,children:"Create a connector"})})}function sw({capsules:e,capsuleSets:t,selectedKind:a,selectedId:l}){let i=function(e,t,n,a){if(void 0===n||void 0===a||0===a.length)return null;if("capsule"===n){let t=e.find(e=>e.id===a);return void 0!==t?t.displayName:`Capsule ${a}`}if("capsule-set"===n){let e=t.find(e=>e.id===a);return void 0!==e?e.displayName:`Set ${a}`}return null}(e,t,a,l);return null===i?null:(0,n.jsxs)("div",{className:"connector-picker-selected",role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"●"}),(0,n.jsx)("span",{children:i})]})}function sj({selectedId:e,selectedLabel:t,selectedState:a,onManageConnectors:l}){let i=void 0!==t&&t.trim().length>0?t.trim():`Capsule ${e}`;return(0,n.jsxs)("div",{className:"connector-node","data-testid":"knowledge-connector-node",children:[(0,n.jsx)("div",{className:"connector-node-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.server,{size:42})}),(0,n.jsxs)("div",{className:"connector-node-copy",children:[(0,n.jsx)("p",{className:"connector-node-kicker",children:function(e){switch(e){case"ready":return"Indexed";case"draft":return"Draft";case"indexing":return"Indexing";case"stale":return"Stale";case"error":return"Failed";default:return"Local Knowledge"}}(a)}),(0,n.jsx)("h2",{className:"connector-node-title",title:i,children:i}),(0,n.jsx)("p",{className:"connector-node-id mono",title:e,children:e})]}),(0,n.jsx)("button",{type:"button",className:"connector-node-manage",onClick:l,children:"Manage"})]})}function sk({selectedKind:e,selectedId:t,selectedLabel:l,selectedState:i,presentation:r,onSelect:s,onManageConnectors:o=()=>void 0}){let[c,d]=(0,a.useState)([]),[u,p]=(0,a.useState)([]),[m,h]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(0),w="node"===r&&"capsule"===e&&void 0!==t&&t.length>0;if((0,a.useEffect)(()=>{if(w)return;let e=!1;return async function(){h(!0),g(null),b(!1);try{let[t,n]=await Promise.allSettled([(0,lD.fetchCapsules)(),(0,lD.fetchCapsuleSets)()]);if(e)return;"fulfilled"===t.status?d(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):g(sv(t.reason)),"fulfilled"===n.status?p(n.value.capsuleSets):b(!0)}catch(t){e||g(sv(t))}finally{e||h(!1)}}(),()=>{e=!0}},[w,x]),w)return(0,n.jsx)(sj,{selectedId:t,selectedLabel:l,selectedState:i,onManageConnectors:o});if(m)return(0,n.jsx)(sb,{});if(null!==f)return(0,n.jsx)(sx,{message:f,onRetry:()=>{y(e=>e+1)}});let j=c.length>0,k=u.length>0;if(!j&&!k)return(0,n.jsx)(sy,{onManageConnectors:o});let N=void 0!==e&&void 0!==t&&t.length>0?`${e}:${t}`:"";return(0,n.jsxs)("div",{className:"connector-picker",children:[(0,n.jsx)(sw,{capsules:c,capsuleSets:u,selectedKind:e,selectedId:t}),(0,n.jsx)("div",{className:"connector-picker-label",children:"Select a connector"}),(0,n.jsx)(tz,{triggerClassName:"connector-picker-select",value:N,ariaLabel:"Select a connector",placeholder:"— choose a connector —",menuTitle:"Available connectors",sections:[...j?[{label:"Capsules",options:c.map(e=>({value:`capsule:${e.id}`,label:`${e.displayName} (${function(e){switch(e){case"ready":return"Ready";case"indexing":return"Indexing…";case"error":return"Failed";default:return e}}(e.lifecycleState)})`}))}]:[],...k?[{label:"Capsule sets",options:u.map(e=>({value:`capsule-set:${e.id}`,label:`${e.displayName} (${String(e.capsuleCount)} capsules)`}))}]:[]],onValueChange:e=>{!function(e){if(""===e)return;let t=e.indexOf(":");if(-1===t)return;let n=e.slice(0,t),a=e.slice(t+1);0!==a.length&&s({selectedKind:n,selectedId:a})}(e)}}),v?(0,n.jsx)("p",{className:"connector-picker-notice",role:"status",children:"Capsule sets could not be loaded."}):null,(0,n.jsx)("div",{className:"connector-picker-footer",children:(0,n.jsx)("button",{type:"button",className:"connector-picker-create-link",onClick:o,children:"Create or manage connectors"})})]})}async function sN(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}return l.json()}async function sS(e,t={}){return sN("/api/figma/snapshots",{method:"POST",...void 0!==t.signal?{signal:t.signal}:{},body:JSON.stringify({boardLink:e,...!0===t.acknowledgeReadOnly?{acknowledgeReadOnly:!0}:{},...!0===t.isResnapshot?{isResnapshot:!0}:{},...void 0!==t.version?{version:t.version}:{}})})}async function sC(e,t){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}`,{...void 0!==t?{signal:t}:{}})}async function sI(e={}){let t=new URLSearchParams;void 0!==e.fileKey&&t.set("fileKey",e.fileKey),void 0!==e.nodeId&&t.set("nodeId",e.nodeId),void 0!==e.limit&&t.set("limit",String(e.limit));let n=t.size>0?`?${t.toString()}`:"";return(await sN(`/api/figma/snapshots${n}`,{...void 0!==e.signal?{signal:e.signal}:{}})).snapshots}async function sE(e,t,n){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}`,{method:"PATCH",...void 0!==n?{signal:n}:{},body:JSON.stringify({displayName:t})})}async function sR(e,t){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}`,{method:"DELETE",...void 0!==t?{signal:t}:{}})}function s$(e,t){return`/api/figma/snapshots/${encodeURIComponent(e)}/screens/${encodeURIComponent(String(t))}/image`}async function sA(e,t,n){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}/screens/${encodeURIComponent(t)}/json`,{...void 0!==n?{signal:n}:{}})}async function sT(e,t){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}/code`,{method:"POST",...void 0!==t?{signal:t}:{},body:JSON.stringify({})})}async function sL(){return sN("/api/figma/token",{method:"DELETE",body:JSON.stringify({})})}let sP=/"(?:\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})|[^"\\])*"\s*:?|[-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|\b(?:true|false|null)\b|[{}\[\],:]/gu;function sM(e){return 0===e.length?0:"u">typeof TextEncoder?new TextEncoder().encode(e).byteLength:e.length}function sD({text:e,className:t}){let a=function(e){let t=[],n=0;for(let a of e.matchAll(sP)){let l=a[0],i=a.index;i>n&&t.push(e.slice(n,i)),t.push({kind:l.startsWith('"')?l.endsWith(":")?"key":"string":"true"===l||"false"===l?"boolean":"null"===l?"null":/^-?\d/u.test(l)?"number":"punctuation",text:l}),n=i+l.length}return n<e.length&&t.push(e.slice(n)),t}(e);return(0,n.jsx)("pre",{className:t,children:(0,n.jsx)("code",{children:a.map((e,t)=>"string"==typeof e?e:(0,n.jsx)("span",{className:`json-token-${e.kind}`,children:e.text},`${e.kind}-${t.toString()}`))})})}let sq=[];function sF(e){try{let t=new URL(e.trim()),n=t.hostname.toLowerCase();if("https:"!==t.protocol||"figma.com"!==n&&"www.figma.com"!==n||!/^\/(design|file)\//u.test(t.pathname))return!1;let a=t.searchParams.get("node-id");return null!==a&&a.length>0}catch{return!1}}function sO(e){let t=new URL(`https://www.figma.com/design/${e.fileKey}/board`);return t.searchParams.set("node-id",e.nodeId),void 0!==e.version&&e.version.length>0&&t.searchParams.set("version",e.version),t.toString()}function sz(e){return e.displayName??`Snapshot ${(0,aq.formatDate)(e.fetchedAt)}`}function sK(e){return void 0===e||0===e.length?"Latest":e}function sB(e){return e.length<=16?e:`${e.slice(0,12)}…`}function s_(e){return e.management??{}}function sU(e,t){return{runId:e.runId,...void 0!==t.displayName?{displayName:t.displayName}:{},management:s_(t),fileKey:e.fileKey,nodeId:e.nodeId,version:e.version,fetchedAt:e.fetchedAt,screenCount:e.screenCount,skippedCount:e.skippedCount,...void 0!==e.structuralOnlyCount?{structuralOnlyCount:e.structuralOnlyCount}:{},reductionHint:e.reductionHint,integrityHash:e.integrityHash}}let sW=new Set(["FIGMA_PROXY_EGRESS_FAILED","FIGMA_PROXY_UNREACHABLE","FIGMA_PROXY_AUTH_REQUIRED","FIGMA_PROXY_BLOCKED_BY_POLICY"]),sV=new Set(["FIGMA_TLS_CA_FAILURE"]),sH=new Set(["FIGMA_NETWORK_UNREACHABLE","FIGMA_EGRESS_TIMEOUT","FIGMA_EGRESS_FAILED"]);function sY(e){return e instanceof w.ApiError?"FIGMA_UPSTREAM_UNAVAILABLE"===e.code?{title:"Figma is currently unavailable",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"Retry later — no snapshot was stored.",assertive:!0}:sW.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"Check the configured proxy, NO_PROXY rules, and CA bundle, then retry. No snapshot was stored.",assertive:!0}:sV.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"A TLS certificate verification failure blocked the request. Check the CA bundle configuration, then retry. No snapshot was stored.",assertive:!0}:sH.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"The outbound network request to Figma failed. Check DNS resolution and network connectivity, then retry. No snapshot was stored.",assertive:!0}:{title:"Figma snapshot failed",detail:e.message}:e instanceof Error?{title:"Figma snapshot failed",detail:e.message}:{title:"Figma snapshot failed",detail:"An unexpected error occurred."}}function sG(e){let t=sY(e);return void 0===t.status?t.detail:`${t.detail} (${t.status})`}function sJ(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window")}function sX(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tm,{detail:n}))}function sQ(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tv,{detail:n}))}function sZ(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tw,{detail:n}))}function s0({index:e,screenId:t,name:l,irSummary:i,imageSrc:r,imageByteLength:s,structuralReason:o,onAddSource:c,isSourceSelected:d=!1,dragPayload:u}){let p=(0,a.useRef)(null),m=(0,a.useRef)(!1),h=(0,a.useRef)(!1),f=void 0!==u&&void 0!==c&&!d,g=d?`${l} preview is already the active scoped source`:`Drag screen ${l} to the workspace, or click to add it as a Quality Intelligence source`,v=void 0!==r?(0,n.jsx)(aE.default,{className:"figma-snapshot-screen-image",src:r,alt:`Captured preview for ${l}`,loading:"lazy",width:72,height:54,unoptimized:!0}):(0,n.jsxs)("div",{className:"figma-snapshot-screen-image figma-snapshot-screen-placeholder","aria-label":`Structural data only for ${l}`,role:"img",children:[(0,n.jsx)(j.Icons.layers,{className:"figma-snapshot-screen-frame-icon","aria-hidden":"true"}),(0,n.jsx)("span",{className:"figma-snapshot-screen-placeholder-label",children:"IR"})]});return(0,n.jsxs)("article",{className:"figma-snapshot-screen-card","aria-label":`Screen ${String(e+1)}: ${l}`,children:[void 0!==c?(0,n.jsx)("button",{type:"button",className:"figma-snapshot-screen-preview-btn",onClick:e=>{if(h.current){h.current=!1,e.preventDefault(),e.stopPropagation();return}c?.()},disabled:d,"aria-disabled":d?"true":void 0,"aria-label":g,draggable:f,onDragStart:e=>{f&&(e.dataTransfer.effectAllowed="copy",e.dataTransfer.setData(tp,JSON.stringify(u)),e.dataTransfer.setData("text/plain",l))},onDragEnd:e=>{f&&sJ(e.clientX,e.clientY)&&sX(u,e)},onPointerDown:e=>{f&&0===e.button&&(m.current=!1,p.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{let t=p.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault()},onPointerUp:e=>{let t=p.current;if(null===t||t.pointerId!==e.pointerId)return;p.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(m.current=!0),n>=6&&void 0!==u&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),h.current=!0,sX(u,e))},onPointerCancel:e=>{let t=p.current;null!==t&&t.pointerId===e.pointerId&&(p.current=null,e.currentTarget.releasePointerCapture(e.pointerId))},onMouseDown:e=>{if(!f||0!==e.button||void 0===u)return;let t=e.clientX,n=e.clientY,a=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault()},l=e=>{if(window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l),m.current){m.current=!1;return}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),h.current=!0,sX(u,e))};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l)},children:v}):v,(0,n.jsxs)("div",{className:"figma-snapshot-screen-meta",children:[(0,n.jsx)("h3",{className:"figma-snapshot-screen-name",title:l,children:l}),(0,n.jsx)("p",{className:"figma-snapshot-screen-summary",children:i}),(0,n.jsx)("p",{className:"figma-snapshot-screen-size",children:void 0!==s?(0,aq.formatBytes)(s):`Structural IR only${void 0!==o?` (${o})`:""}`}),(0,n.jsx)("p",{className:"figma-snapshot-screen-id",children:t}),void 0!==c?(0,n.jsx)("div",{className:"figma-snapshot-screen-actions",children:(0,n.jsx)("button",{type:"button",className:"figma-snapshot-screen-source-btn",onClick:c,disabled:d,"aria-disabled":d?"true":void 0,"aria-label":d?`${l} is already the active scoped source`:`Add screen ${l} to the workspace as a Quality Intelligence source`,children:d?"Source active":"Add to workspace"})}):null]})]})}function s1({name:e,screenId:t,irSummary:l,imageSrc:i,imageByteLength:r,structuralReason:s,snapshotRunId:o,capturedAt:c,imageDragPayload:d}){let u=(0,a.useRef)(null),p=(0,a.useRef)(!1),m=void 0!==i&&void 0!==d,h=void 0!==i?(0,n.jsx)(aE.default,{className:"figma-view-preview-image",src:i,alt:`Captured preview for ${e}`,loading:"eager",width:360,height:240,draggable:!1,unoptimized:!0}):(0,n.jsxs)("div",{className:"figma-view-preview-image figma-view-preview-placeholder","aria-label":`Structural data only for ${e}`,role:"img",children:[(0,n.jsx)(j.Icons.layers,{className:"figma-view-preview-icon","aria-hidden":"true"}),(0,n.jsx)("span",{children:"Structural IR"})]});return(0,n.jsxs)("article",{className:"figma-view-source-card","aria-label":`Figma view source: ${e}`,children:[m?(0,n.jsx)("button",{type:"button",className:"figma-view-preview figma-view-preview-drag-surface",draggable:!0,onDragStart:e=>{m&&(e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setData(ty,JSON.stringify(d)),e.dataTransfer.setData("text/plain",`${d.name}.png`))},onDragEnd:e=>{m&&sJ(e.clientX,e.clientY)&&sZ(d,e)},onKeyDown:e=>{if(!m||"Enter"!==e.key&&" "!==e.key)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();sZ(d,{clientX:t.right+24,clientY:t.top+t.height/2})},onPointerDown:e=>{m&&0===e.button&&(p.current=!1,u.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{let t=u.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault()},onPointerUp:e=>{let t=u.current;if(null===t||t.pointerId!==e.pointerId)return;u.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(p.current=!0),n>=6&&m&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),sZ(d,e))},onPointerCancel:e=>{let t=u.current;null!==t&&t.pointerId===e.pointerId&&(u.current=null,e.currentTarget.releasePointerCapture(e.pointerId))},onMouseDown:e=>{if(!m||0!==e.button)return;let t=e.clientX,n=e.clientY,a=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault()},l=e=>{if(window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l),p.current){p.current=!1;return}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),sZ(d,e))};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l)},"aria-label":`Create a standalone image source for ${e}`,title:`Drag image for ${e} to the workspace`,children:h}):(0,n.jsx)("div",{className:"figma-view-preview",children:h}),(0,n.jsxs)("div",{className:"figma-view-source-meta",children:[(0,n.jsx)("p",{className:"figma-view-source-kicker",children:"QI view source"}),(0,n.jsx)("h2",{className:"figma-view-source-title",title:e,children:e}),(0,n.jsx)("p",{className:"figma-view-source-summary",children:l}),(0,n.jsxs)("dl",{className:"figma-view-source-facts",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Screen"}),(0,n.jsx)("dd",{children:t})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Snapshot"}),(0,n.jsx)("dd",{children:o})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Captured"}),(0,n.jsx)("dd",{children:c})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Preview"}),(0,n.jsx)("dd",{children:void 0!==r?(0,aq.formatBytes)(r):`Structural IR${void 0!==s?` (${s})`:""}`})]})]})]})]})}function s2({sourceWindowId:e,snapshotRunId:t,selectedScreenIds:l=sq,selectedScreenName:i,openScreenSource:r,updateCfg:s,triggerImpl:o=sS,loadImpl:c=sC,listImpl:d=sI,updateMetadataImpl:u=sE,deleteImpl:p=sR,loadScreenJsonImpl:m=sA,codegenImpl:h=sT,revokeImpl:f=sL}){let g,v,b,x,y=(0,a.useId)(),k=(0,a.useId)(),N=(0,a.useId)(),S=(0,a.useId)(),[C,I]=(0,a.useState)(""),[E,R]=(0,a.useState)("idle"),[$,A]=(0,a.useState)(null),[T,L]=(0,a.useState)(null),[P,M]=(0,a.useState)(null),[D,q]=(0,a.useState)(null),[F,O]=(0,a.useState)(0),[z,K]=(0,a.useState)("recent"),[B,_]=(0,a.useState)([]),[U,W]=(0,a.useState)([]),[V,H]=(0,a.useState)(!1),[Y,G]=(0,a.useState)(!1),[J,X]=(0,a.useState)(null),[Q,Z]=(0,a.useState)(null),[ee,et]=(0,a.useState)(null),[en,ea]=(0,a.useState)(""),[el,ei]=(0,a.useState)(null),[er,es]=(0,a.useState)(null),[eo,ec]=(0,a.useState)(null),[ed,eu]=(0,a.useState)(null),[ep,em]=(0,a.useState)(!1),[eh,ef]=(0,a.useState)(!1),eg=(0,a.useRef)(null),ev=(0,a.useRef)(null),eb=(0,a.useRef)(null),ex=(0,a.useRef)(null),ey=(0,a.useRef)(null),ew=(0,a.useRef)(null),ej=(0,a.useRef)(null),ek=(0,a.useRef)(null),eN=(0,a.useRef)(!1),eS=(0,a.useCallback)(()=>{ef(!0)},[]),[eC,eI]=(0,a.useState)("idle"),[eE,eR]=(0,a.useState)(null),[e$,eA]=(0,a.useState)(null),[eT,eL]=(0,a.useState)("idle"),[eP,eM]=(0,a.useState)(null),[eD,eq]=(0,a.useState)(null),[eF,eO]=(0,a.useState)(null),[ez,eK]=(0,a.useState)(!1),[eB,e_]=(0,a.useState)(null),[eU,eW]=(0,a.useState)(null),eV=(0,a.useRef)(null),eH=(0,a.useRef)(null),[eY,eG]=(0,a.useState)(24),eJ=l.join("\0"),eX=sF(C),eQ=function(e){let t=e.trim();if(0===t.length||sF(t))return null;try{let e=new URL(t),n=e.hostname.toLowerCase();if("https:"===e.protocol&&("figma.com"===n||"www.figma.com"===n)&&/^\/(design|file)\//u.test(e.pathname))return"Add a node-id by selecting a frame or section in Figma and copying its link (Copy link to selection)."}catch{}return"This doesn't look like a Figma board link. Use a figma.com design/file link that includes a node-id parameter."}(C),eZ=(0,a.useMemo)(()=>null!==$?{fileKey:$.fileKey,nodeId:$.nodeId}:function(e){try{let t=new URL(e.trim()),n=t.hostname.toLowerCase();if("https:"!==t.protocol||"figma.com"!==n&&"www.figma.com"!==n)return null;let[,a,l]=t.pathname.split("/");if("design"!==a&&"file"!==a||void 0===l||0===l.length)return null;let i=t.searchParams.get("node-id");if(null===i||0===i.length)return null;return{fileKey:l,nodeId:i}}catch{return null}}(C),[C,$]),e0=eZ?.fileKey,e1=eZ?.nodeId,e2="building"===E,e4="loading"===E,e3=e2||e4,e6=e2&&null!==D?(v=Math.floor((g=Math.max(0,Math.floor(F/1e3)))/3600),b=Math.floor(g%3600/60),x=g%60,v>0?`${String(v)}h ${String(b)}m ${String(x)}s`:b>0?`${String(b)}m ${String(x)}s`:`${String(x)}s`):null,e5=(0,a.useMemo)(()=>new Set(l),[l]),e8=l.length>0,e7=e8&&void 0!==t&&t.length>0,e9=(0,a.useMemo)(()=>{if(null===$)return[];let e=new Set($.screens.map(e=>e.screenId)),t=[...$.screens.map((e,t)=>({kind:"rendered",screen:e,imageIndex:t})),...($.structuralScreens??[]).filter(t=>!e.has(t.screenId)).map(e=>({kind:"structural",screen:e}))];return e8?t.filter(e=>e5.has(e.screen.screenId)):t},[e8,e5,$]),te=1===l.length?l[0]:void 0,tt=(0,a.useMemo)(()=>null===eP?"":JSON.stringify(eP,null,2),[eP]),tn=(0,a.useMemo)(()=>sM(tt),[tt]),ta=($?.screens.length??0)+($?.structuralScreens?.length??0),tl=null===$?{}:s_($);(0,a.useEffect)(()=>{eh&&"error"===E&&eg.current?.focus()},[eh,E]),(0,a.useEffect)(()=>{ez&&eV.current?.focus()},[ez]),(0,a.useEffect)(()=>{if(!e2||null===D)return;O(Date.now()-D);let e=window.setInterval(()=>{O(Date.now()-D)},1e3);return()=>{window.clearInterval(e)}},[e2,D]),(0,a.useEffect)(()=>()=>{ev.current?.abort(),eb.current?.abort(),ex.current?.abort(),ey.current?.abort(),ew.current?.abort()},[]),(0,a.useEffect)(()=>{null===eZ&&"board"===z&&K("recent")},[eZ,z]);let ti=(0,a.useCallback)(()=>{ey.current?.abort();let e=new AbortController;if(ey.current=e,G(!0),Z(null),d({limit:12,signal:e.signal}).then(e=>{W(e)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(W([]),Z(sG(e)))}).finally(()=>{ey.current===e&&G(!1)}),void 0===e0||void 0===e1){_([]),X(null),H(!1);return}H(!0),X(null),d({fileKey:e0,nodeId:e1,limit:12,signal:e.signal}).then(e=>{_(e)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(_([]),X(sG(e)))}).finally(()=>{ey.current===e&&H(!1)})},[e0,e1,d]);(0,a.useEffect)(()=>{ti()},[ti,$?.runId]);let tr=(0,a.useCallback)(e=>{if(0===e.length||e3)return;ev.current?.abort();let n=new AbortController;ev.current=n,R("loading"),L(null),M(null),eI("idle"),eR(null),eA(null),eL("idle"),eM(null),eq(null),eO(null),c(e,n.signal).then(e=>{A(e),I(sO(e)),s({snapshotRunId:e.runId}),R("done")}).catch(n=>{n instanceof DOMException&&"AbortError"===n.name||(n instanceof w.ApiError&&"FIGMA_SNAPSHOT_NOT_FOUND"===n.code?(t===e&&s({snapshotRunId:void 0}),L({...sY(n),detail:t===e?`${n.message} The stored run ID has been cleared.`:n.message})):L(sY(n)),R("error"))})},[e3,c,t,s]);(0,a.useEffect)(()=>{e7&&void 0!==t&&0!==t.length&&null===$&&"idle"===E&&tr(t)},[E,e7,tr,t,$]);let ts=(0,a.useCallback)(async(e,t)=>{ev.current?.abort(),eb.current?.abort(),ex.current?.abort(),eb.current=null,ex.current=null;let n=new AbortController;ev.current=n,ej.current={link:e,isResnapshot:t},R("building"),L(null),M(null),q(Date.now()),O(0),eI("idle"),eR(null),eL("idle"),eM(null),eq(null),eO(null);try{let a=await o(e,{acknowledgeReadOnly:ep,isResnapshot:t,signal:n.signal});A(a),I(sO(a)),s({snapshotRunId:a.runId}),R("done"),q(null),O(0),ej.current=null}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return;if(q(null),O(0),n instanceof w.ApiError&&"FIGMA_CONSENT_REQUIRED"===n.code){let e=sY(n);L({...e,detail:`${e.detail} Tick the acknowledgement checkbox below, then snapshot again.`}),eS()}else n instanceof w.ApiError&&"FIGMA_BUILD_TIMEOUT"===n.code?(M({link:e,isResnapshot:t}),L({title:"Figma snapshot is still running",detail:"This window stopped waiting for the snapshot result. The server may still finish the build in the background.",status:`HTTP ${n.status.toString()}`,remediation:"Reconnect to the same board to keep waiting, or close this window and return later."})):L(sY(n));R("error"),ej.current=null}},[o,s,ep,eS]),to=(0,a.useCallback)(e=>{if(e.preventDefault(),eX&&!e3){if(!ep){L({title:"Figma snapshot failed",detail:"Tick the read-only acknowledgement checkbox below, then snapshot again."}),R("error"),eS();return}ts(C,!1)}},[C,e3,ep,eX,ts,eS]),tc=(0,a.useCallback)(()=>{e3||null!==$&&ts(sO($),!0)},[e3,ts,$]),td=(0,a.useCallback)(()=>{ev.current?.abort(),ev.current=null,q(null),O(0),null!==ej.current&&M(ej.current),ej.current=null,R("idle"),L(null)},[]),tu=(0,a.useCallback)(()=>{e3||null===P||ts(P.link,P.isResnapshot)},[e3,P,ts]),tp=(0,a.useCallback)(()=>{let e=$?.runId??t;if(void 0===e||0===e.length||"generating"===eC)return;let n=new AbortController;eb.current=n,eI("generating"),eA(null),h(e,n.signal).then(e=>{eR(e),eI("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?eI("idle"):(eA(sG(e)),eI("error"))}).finally(()=>{eb.current===n&&(eb.current=null)})},[h,eC,t,$]),tm=(0,a.useCallback)(()=>{let e=$?.runId??t;if(void 0===e||0===e.length||void 0===te||"loading"===eT)return;ex.current?.abort();let n=new AbortController;ex.current=n,eL("loading"),eq(null),eO(null),m(e,te,n.signal).then(e=>{eM(e),eL("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?eL("idle"):(eM(null),eq(sG(e)),eL("error"))}).finally(()=>{ex.current===n&&(ex.current=null)})},[te,m,eT,t,$?.runId]),th=(0,a.useCallback)(()=>{if(0!==tt.length){if(void 0===navigator.clipboard)return void eO("Clipboard unavailable");navigator.clipboard.writeText(tt).then(()=>{eO("Copied")}).catch(()=>{eO("Copy failed")})}},[tt]),tf=(0,a.useMemo)(()=>{let n=eP?.runId??$?.runId??t,a=eP?.screen.screenId??te,l=eP?.screen.name??i??a;return void 0===n||0===n.length||void 0===a||0===a.length||void 0===l||0===l.length?null:{snapshotRunId:n,screenId:a,name:l,...void 0!==e?{sourceWindowId:e}:{}}},[te,eP?.runId,eP?.screen.name,eP?.screen.screenId,i,t,e,$?.runId]),tv=(0,a.useCallback)(e=>{null!==tf&&(e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setData(tg,JSON.stringify(tf)),e.dataTransfer.setData("text/plain",`${tf.name}.json`))},[tf]),tb=(0,a.useCallback)(e=>{null!==tf&&sJ(e.clientX,e.clientY)&&sQ(tf,e)},[tf]),tx=(0,a.useCallback)(e=>{if(null===tf||"Enter"!==e.key&&" "!==e.key)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();sQ(tf,{clientX:t.right+24,clientY:t.top+t.height/2})},[tf]),ty=(0,a.useCallback)(e=>{null!==tf&&0===e.button&&(eN.current=!1,ek.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId))},[tf]),tw=(0,a.useCallback)(e=>{let t=ek.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault()},[]),tj=(0,a.useCallback)(e=>{let t=ek.current;if(null===t||t.pointerId!==e.pointerId)return;ek.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(eN.current=!0),n>=6&&null!==tf&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),sQ(tf,e))},[tf]),tk=(0,a.useCallback)(e=>{let t=ek.current;null!==t&&t.pointerId===e.pointerId&&(ek.current=null,e.currentTarget.releasePointerCapture(e.pointerId))},[]),tN=(0,a.useCallback)(e=>{if(null===tf||0!==e.button)return;let t=e.clientX,n=e.clientY,a=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault()},l=e=>{if(window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l),eN.current){eN.current=!1;return}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),sQ(tf,e))};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l)},[tf]),tS=(0,a.useCallback)(()=>{eb.current?.abort(),eb.current=null,eI("idle"),eA(null)},[]),tC=(0,a.useCallback)(()=>{void 0===t||0===t.length||e3||tr(t)},[e3,tr,t]);(0,a.useEffect)(()=>{eG(24)},[eJ,$?.runId]),(0,a.useEffect)(()=>{ex.current?.abort(),ex.current=null,eL("idle"),eM(null),eq(null),eO(null)},[eJ,t]);let tI=(0,a.useCallback)(()=>{eK(!1),eW(null),e_(null),f().then(e=>{e_(e.message),requestAnimationFrame(()=>eH.current?.focus())}).catch(e=>{eW(sG(e)),requestAnimationFrame(()=>eH.current?.focus())})},[f]),tE=(0,a.useCallback)(()=>{eK(!1),requestAnimationFrame(()=>eH.current?.focus())},[]),tR=(0,a.useCallback)(e=>{et(e.runId),ea(e.displayName??""),ei(null),es(null),eu(null)},[]),t$=(0,a.useCallback)(()=>{et(null),ea("")},[]),tA=(0,a.useCallback)(e=>{if(null!==eo)return;ew.current?.abort();let t=new AbortController;ew.current=t,ec(e),eu(null);let n=en.trim();u(e,0===n.length?null:n,t.signal).then(t=>{$?.runId===e&&A(t),_(n=>n.map(n=>n.runId===e?sU(n,t):n)),W(n=>n.map(n=>n.runId===e?sU(n,t):n)),et(null),ea("")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||eu(sG(e))}).finally(()=>{ew.current===t&&(ew.current=null),ec(null)})},[en,eo,$?.runId,u]),tT=(0,a.useCallback)(e=>{ei(t=>t===e?null:e),et(null),es(null),eu(null)},[]),tL=(0,a.useCallback)(e=>{es(e),et(null),ei(null),eu(null)},[]),tP=(0,a.useCallback)(e=>{if(null!==eo)return;ew.current?.abort();let n=new AbortController;ew.current=n,ec(e),eu(null),p(e,n.signal).then(n=>{_(t=>t.filter(t=>t.runId!==e)),W(t=>t.filter(t=>t.runId!==e)),es(null),et(null),ei(null),$?.runId===e&&(A(null),R("idle"),eI("idle"),eR(null),eL("idle"),eM(null)),($?.runId===e||t===e)&&s({snapshotRunId:void 0})}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||eu(sG(e))}).finally(()=>{ew.current===n&&(ew.current=null),ec(null)})},[p,eo,t,$?.runId,s]),tM=void 0!==t&&t.length>0&&null===$&&("idle"===E||"loading"===E||"error"===E),tD=(e,a,l,i,r,s)=>a?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status",children:"Loading snapshots…"}):null!==l?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status figma-snapshot-dashboard-status-error",children:l}):0===e.length?(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-empty",children:[(0,n.jsx)("p",{className:"figma-snapshot-dashboard-empty-title",children:i}),(0,n.jsx)("p",{className:"figma-snapshot-dashboard-empty-detail",children:r})]}):(0,n.jsx)("div",{className:"figma-snapshot-dashboard-list",role:"list",children:e.map(e=>{let a=$?.runId===e.runId,l=sz(e),i=s_(e),r=eo===e.runId,o=el===e.runId,c=ee===e.runId,d=er===e.runId;return(0,n.jsxs)("article",{className:"figma-snapshot-dashboard-item",role:"listitem","aria-current":a?"true":void 0,"aria-busy":e4&&t===e.runId?"true":void 0,children:[(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-item-head",children:[(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-item-title-block",children:[(0,n.jsx)("h3",{className:"figma-snapshot-dashboard-item-title",title:l,children:l}),(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-date",children:(0,aq.formatDate)(e.fetchedAt)})]}),a&&(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-badge",children:"Current"}),(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-item-actions",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-load",onClick:()=>{tr(e.runId)},disabled:e3,"aria-disabled":e3?"true":void 0,"aria-label":`Load snapshot ${l}`,children:"Load"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn",onClick:()=>tR(e),disabled:r,"aria-label":`Rename snapshot ${l}`,title:"Rename",children:(0,n.jsx)(j.Icons.edit,{"aria-hidden":"true"})}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn",onClick:()=>tT(e.runId),"aria-expanded":o,"aria-label":`${o?"Hide":"Show"} metadata for snapshot ${l}`,title:"Metadata",children:(0,n.jsx)(j.Icons.info,{"aria-hidden":"true"})}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn figma-snapshot-dashboard-icon-btn-danger",onClick:()=>tL(e.runId),disabled:r,"aria-label":`Delete snapshot ${l}`,title:"Delete",children:(0,n.jsx)(j.Icons.trash,{"aria-hidden":"true"})})]})]}),(0,n.jsx)("p",{className:"figma-snapshot-dashboard-item-hint",children:e.reductionHint}),(0,n.jsxs)("p",{className:"figma-snapshot-dashboard-item-meta",children:[e.screenCount.toString()," screen",1!==e.screenCount?"s":"",e.skippedCount>0?`, ${e.skippedCount.toString()} skipped`:", no skipped renders"]}),s&&(0,n.jsxs)("p",{className:"figma-snapshot-dashboard-item-scope",children:[e.fileKey," · ",e.nodeId]}),c?(0,n.jsxs)("form",{className:"figma-snapshot-dashboard-rename",onSubmit:t=>{t.preventDefault(),tA(e.runId)},children:[(0,n.jsx)("input",{type:"text",className:"figma-snapshot-dashboard-rename-input",value:en,onChange:e=>ea(e.target.value),maxLength:120,disabled:r,"aria-label":`Snapshot name for ${l}`,placeholder:"Snapshot name"}),(0,n.jsx)("button",{type:"submit",className:"figma-snapshot-dashboard-rename-save",disabled:r,"aria-busy":r,children:"Save"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-rename-cancel",onClick:t$,disabled:r,children:"Cancel"})]}):null,d?(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-delete-confirm",children:[(0,n.jsx)("span",{children:"Delete this snapshot?"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-delete-confirm-btn",onClick:()=>tP(e.runId),disabled:r,"aria-busy":r,children:"Delete"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-delete-cancel-btn",onClick:()=>es(null),disabled:r,children:"Cancel"})]}):null,o?(0,n.jsxs)("dl",{className:"figma-snapshot-dashboard-details",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Run"}),(0,n.jsx)("dd",{children:e.runId})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Version"}),(0,n.jsx)("dd",{children:sK(e.version)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Integrity"}),(0,n.jsx)("dd",{title:e.integrityHash,children:sB(e.integrityHash)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Structural"}),(0,n.jsx)("dd",{children:(e.structuralOnlyCount??0).toString()})]}),void 0!==i.updatedAt?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Name updated"}),(0,n.jsx)("dd",{children:(0,aq.formatDate)(i.updatedAt)})]}):null]}):null]},e.runId)})});if(e7){let a=i??l.join(", "),r=void 0!==te&&($?.runId??t)!==void 0&&"loading"!==eT;return(0,n.jsxs)("section",{className:"figma-snapshot-window figma-view-window","aria-label":`Figma view source ${a}`,children:[(0,n.jsxs)("div",{className:"figma-view-source-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-view-source-eyebrow",children:"Figma view"}),(0,n.jsx)("h1",{className:"figma-view-source-heading",title:a,children:a})]}),(0,n.jsxs)("div",{className:"figma-view-source-actions",children:[(0,n.jsx)("span",{className:"figma-view-source-badge",children:"QI source"}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-btn",onClick:tm,disabled:!r,"aria-disabled":r?void 0:"true","aria-busy":"loading"===eT?"true":void 0,children:"loading"===eT?"Loading JSON…":"Inspect JSON"})]})]}),(0,n.jsxs)("div",{id:k,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[e4&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Loading view preview…"}),"error"===E&&null!==T&&(0,n.jsx)("p",{className:"figma-snapshot-error",children:T.detail}),"done"===E&&null!==$&&(0,n.jsxs)("p",{className:"sr-only",children:["Figma view loaded — ",a,"."]})]}),null===$?(0,n.jsxs)("div",{className:"figma-view-source-empty",children:[(0,n.jsx)("p",{className:"figma-view-source-empty-title",children:e4?"Loading the selected view…":"Selected view preview not loaded."}),!e4&&(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tC,children:"Load view"})]}):e9.length>0?e9.map(t=>{let a="rendered"===t.kind?s$($.runId,t.imageIndex):void 0,l=void 0===a?void 0:{snapshotRunId:$.runId,screenId:t.screen.screenId,name:t.screen.name,imageSrc:a,...void 0!==e?{sourceWindowId:e}:{}};return(0,n.jsx)(s1,{name:t.screen.name,screenId:t.screen.screenId,irSummary:t.screen.irSummary,imageSrc:a,imageByteLength:"rendered"===t.kind?t.screen.imageByteLength:void 0,structuralReason:"structural"===t.kind?t.screen.reason:void 0,snapshotRunId:$.runId,capturedAt:(0,aq.formatDate)($.fetchedAt),imageDragPayload:l},t.screen.screenId)}):(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:"The selected screen is not present in this stored snapshot."})}),"error"===eT&&null!==eD?(0,n.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:eD}):null,"done"===eT&&null!==eP?(0,n.jsxs)("section",{className:"figma-view-json-inspector","aria-label":`Scoped JSON for ${eP.screen.name}`,children:[(0,n.jsxs)("div",{className:"figma-view-json-inspector-header",children:[(0,n.jsxs)("div",{className:"figma-view-json-drag-surface",role:"button",tabIndex:null!==tf?0:-1,draggable:!1,onDragStart:tv,onDragEnd:tb,onKeyDown:tx,onPointerDown:ty,onPointerMove:tw,onPointerUp:tj,onPointerCancel:tk,onMouseDown:tN,"aria-label":`Create a standalone JSON source for ${eP.screen.name}`,"aria-disabled":null===tf?"true":void 0,title:`Drag JSON for ${eP.screen.name} to the workspace`,children:[(0,n.jsx)("p",{className:"figma-view-json-kicker",children:"Stored Screen-IR JSON"}),(0,n.jsx)("h2",{className:"figma-view-json-title",children:eP.screen.screenId}),(0,n.jsxs)("p",{className:"figma-view-json-meta",children:[eP.screen.kind," · ",(0,aq.formatBytes)(tn)," ·"," ",eP.relatedLinks.length.toString()," related link",1!==eP.relatedLinks.length?"s":""]})]}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-copy-btn",onClick:th,children:"Copy JSON"})]}),null!==eF?(0,n.jsx)("p",{className:"figma-view-json-copy-status",role:"status",children:eF}):null,(0,n.jsx)(sD,{text:tt,className:"figma-view-json-code"})]}):null]})}return(0,n.jsxs)("section",{className:"figma-snapshot-window","aria-label":"Figma Snapshot",children:[(0,n.jsxs)("form",{className:"figma-snapshot-form",onSubmit:to,noValidate:!0,children:[(0,n.jsx)("label",{className:"figma-snapshot-label",htmlFor:y,children:"Board link"}),(0,n.jsxs)("div",{className:"figma-snapshot-input-row",children:[(0,n.jsx)("input",{id:y,type:"url",className:"figma-snapshot-input",placeholder:"https://www.figma.com/design/…?node-id=…",value:C,onChange:e=>{I(e.target.value),null!==T&&L(null),"error"===E&&R("idle"),null!==P&&M(null),eh&&ef(!1)},"aria-describedby":null!==eQ?`${N} ${k}`:k,"aria-invalid":null!==eQ?"true":void 0,readOnly:e3,autoComplete:"off",spellCheck:!1}),(0,n.jsx)("button",{type:"submit",className:"figma-snapshot-trigger-btn",disabled:!eX&&!e3,"aria-disabled":!eX||e3?"true":void 0,"aria-busy":e2,children:e2?"Building…":"Snapshot"})]}),null!==eQ&&(0,n.jsx)("p",{id:N,className:"figma-snapshot-link-error",role:"alert",children:eQ}),(0,n.jsxs)("label",{className:"figma-snapshot-consent",children:[(0,n.jsx)("input",{type:"checkbox",className:"figma-snapshot-consent-checkbox",ref:eg,checked:ep,"aria-invalid":eh?"true":void 0,onChange:e=>{em(e.target.checked),null!==T&&L(null),"error"===E&&R("idle"),ef(!1)},disabled:e2}),(0,n.jsxs)("span",{children:["I acknowledge the configured Figma PAT is read-only and least-privilege (",(0,n.jsx)("code",{children:"file_content:read"}),")."," ",(0,n.jsx)("span",{className:"figma-snapshot-consent-required",children:"Required before the first snapshot of a board."})]})]}),(0,n.jsx)("p",{className:"figma-snapshot-hint",children:"Paste a Figma board link with a node-id param (section or frame anchor). The access token is resolved server-side — it never reaches this page."})]}),"error"===E&&null!==T&&!0===T.assertive&&(0,n.jsxs)("div",{className:"figma-snapshot-error-card",role:"alert","aria-labelledby":`${k}-error-title`,children:[(0,n.jsx)("p",{id:`${k}-error-title`,className:"figma-snapshot-error-title",children:T.title}),(0,n.jsx)("p",{className:"figma-snapshot-error-detail",children:T.detail}),void 0!==T.status&&(0,n.jsx)("p",{className:"figma-snapshot-error-status",children:T.status}),void 0!==T.remediation&&(0,n.jsx)("p",{className:"figma-snapshot-error-remediation",children:T.remediation})]}),(0,n.jsxs)("div",{id:k,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[e2&&(0,n.jsxs)("p",{className:"figma-snapshot-progress",children:["Building snapshot — fetching screens from Figma…"," ",null!==e6?`${e6} elapsed.`:""," Large boards can take several minutes."]}),e4&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Loading stored snapshot…"}),"done"===E&&null!==$&&(0,n.jsxs)("p",{className:"sr-only",children:["Snapshot complete — ",$.reductionHint,"."]}),"done"===eC&&null!==eE&&(0,n.jsxs)("p",{className:"sr-only",children:["Code generated — ",String(eE.fileCount)," file",1!==eE.fileCount?"s":""," ready for review."]}),"idle"===E&&(0,n.jsx)("p",{className:"sr-only","aria-live":"polite"}),"error"===E&&null!==T&&!0!==T.assertive&&(0,n.jsx)("p",{className:"figma-snapshot-error",children:T.detail})]}),e2&&(0,n.jsxs)("div",{className:"figma-snapshot-cancel-row",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-cancel-btn",onClick:td,children:"Cancel"}),(0,n.jsx)("p",{className:"figma-snapshot-cancel-note",role:"status","aria-live":"polite",children:"Cancelling stops this window from waiting — the server-side build continues on demand."})]}),null!==P&&!e3&&(0,n.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,n.jsx)("p",{className:"figma-snapshot-stored-text",children:"This window is no longer waiting. The server may still be building the snapshot in the background. You can close this window safely."}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tu,children:"Reconnect build"})]}),"idle"===E&&null===$&&null===P&&!tM&&(0,n.jsxs)("div",{className:"figma-snapshot-empty",children:[(0,n.jsx)("p",{className:"figma-snapshot-empty-title",children:"Capture screens from a Figma board"}),(0,n.jsxs)("ol",{className:"figma-snapshot-empty-steps",children:[(0,n.jsx)("li",{children:"In Figma, select the frame or section you want to capture."}),(0,n.jsx)("li",{children:"Copy its link (Copy link to selection) — it contains the node-id."}),(0,n.jsx)("li",{children:"Paste it above, acknowledge the read-only scope, then take the snapshot."})]}),(0,n.jsx)("p",{className:"figma-snapshot-empty-note",children:"The snapshot stores the captured screens and their structure as immutable evidence — connect this window to Quality Intelligence to ground generated tests in the design. Requires a Figma access token configured on the server."})]}),tM&&(0,n.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,n.jsx)("p",{className:"figma-snapshot-stored-text",children:"A stored snapshot is available."}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tC,"aria-disabled":e4?"true":void 0,"aria-busy":e4,children:e4?"Loading…":"Load snapshot"})]}),(0,n.jsxs)("section",{className:"figma-snapshot-dashboard","aria-label":"Snapshot dashboard",children:[(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-snapshot-dashboard-eyebrow",children:"Snapshot dashboard"}),(0,n.jsx)("h2",{className:"figma-snapshot-dashboard-title",children:"Stored snapshots"})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-refresh",onClick:ti,children:"Refresh"})]}),(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-tabs",role:"tablist","aria-label":"Snapshot views",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"board"===z,"aria-controls":`${S}-board-panel`,id:`${S}-board-tab`,onClick:()=>{null!==eZ&&K("board")},disabled:null===eZ,children:"This board"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"recent"===z,"aria-controls":`${S}-recent-panel`,id:`${S}-recent-tab`,onClick:()=>{K("recent")},children:"Recent"})]}),null!==ed?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status figma-snapshot-dashboard-status-error",role:"alert",children:ed}):null,"board"===z?(0,n.jsx)("div",{id:`${S}-board-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${S}-board-tab`,children:null===eZ?tD([],!1,null,"No board selected yet","Paste a valid Figma board link or load a stored snapshot to see this board's history.",!1):tD(B,V,J,"No snapshots stored for this board","Take the first snapshot for this board to make it available here.",!1)}):(0,n.jsx)("div",{id:`${S}-recent-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${S}-recent-tab`,children:tD(U,Y,Q,"No snapshots stored yet","Stored Figma snapshots will appear here once the first board capture completes.",!0)})]}),null!==$&&(0,n.jsxs)("div",{className:"figma-snapshot-result",children:[(0,n.jsxs)("div",{className:"figma-snapshot-reduction",children:[(0,n.jsxs)("div",{className:"figma-snapshot-result-head",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:"figma-snapshot-result-title",title:sz($),children:sz($)}),(0,n.jsx)("p",{className:"figma-snapshot-result-run",children:$.runId})]}),(0,n.jsx)("span",{className:"figma-snapshot-result-hash",title:$.integrityHash,children:sB($.integrityHash)})]}),(0,n.jsx)("p",{className:"figma-snapshot-reduction-hint",children:$.reductionHint}),(0,n.jsxs)("p",{className:"figma-snapshot-captured-at",children:["Captured ",(0,aq.formatDate)($.fetchedAt)]}),(0,n.jsxs)("dl",{className:"figma-snapshot-result-metadata",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"File"}),(0,n.jsx)("dd",{children:$.fileKey})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Node"}),(0,n.jsx)("dd",{children:$.nodeId})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Version"}),(0,n.jsx)("dd",{children:sK($.version)})]}),void 0!==tl.updatedAt?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Name updated"}),(0,n.jsx)("dd",{children:(0,aq.formatDate)(tl.updatedAt)})]}):null]}),e8&&(0,n.jsxs)("p",{className:"figma-snapshot-scope-note",children:["QI source scope: ",i??l.join(", ")]}),$.skippedCount>0&&(0,n.jsxs)("p",{className:"figma-snapshot-skipped-notice",children:[String($.skippedCount)," screen",1!==$.skippedCount?"s":""," could not be rendered and were skipped."]})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-resnapshot-btn",onClick:tc,"aria-disabled":e3?"true":void 0,"aria-busy":e2,"aria-label":"Re-snapshot this board",children:e2?"Building…":"Re-snapshot"}),(0,n.jsxs)("div",{className:"figma-snapshot-codegen",children:[(0,n.jsxs)("div",{className:"figma-snapshot-codegen-actions",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-codegen-btn",onClick:tp,"aria-disabled":"generating"===eC?"true":void 0,"aria-busy":"generating"===eC,children:"generating"===eC?"Generating code…":"Generate code"}),"generating"===eC&&(0,n.jsx)("button",{type:"button",className:"figma-snapshot-codegen-cancel-btn",onClick:tS,children:"Cancel"})]}),"error"===eC&&null!==e$&&(0,n.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:e$}),"done"===eC&&null!==eE&&(0,n.jsxs)("div",{className:"figma-snapshot-code-result",children:[(0,n.jsxs)("p",{className:"figma-snapshot-code-summary",children:[String(eE.fileCount)," reviewable file",1!==eE.fileCount?"s":""," (",String(eE.screenCount)," screen",1!==eE.screenCount?"s":"",","," ",eE.adapterName,") — proposal only, never auto-applied."]}),eE.files.map(e=>(0,n.jsxs)("details",{className:"figma-snapshot-code-file",children:[(0,n.jsx)("summary",{className:"figma-snapshot-code-file-path",children:e.path}),(0,n.jsx)("pre",{className:"figma-snapshot-code-file-contents",children:(0,n.jsx)("code",{children:e.contents})})]},e.path))]})]}),(0,n.jsxs)("details",{className:"figma-snapshot-scopes",children:[(0,n.jsx)("summary",{className:"figma-snapshot-scopes-summary",children:"Required Figma PAT scopes"}),(0,n.jsx)("ul",{className:"figma-snapshot-scopes-list",children:(0,n.jsxs)("li",{children:[(0,n.jsx)("code",{children:"file_content:read"})," — read design file structure, node metadata, and rendered images"]})}),(0,n.jsxs)("p",{className:"figma-snapshot-scopes-note",children:["The token is read server-side from the vault, Keiko config, or"," ",(0,n.jsx)("code",{children:"FIGMA_ACCESS_TOKEN"})," environment variable. This window never holds or transmits the token."]}),(0,n.jsxs)("div",{className:"figma-snapshot-revoke-row",children:[ez?(0,n.jsxs)("span",{className:"figma-snapshot-revoke-confirm",children:[(0,n.jsx)("span",{className:"figma-snapshot-revoke-confirm-label",children:"Really revoke the stored token?"}),(0,n.jsx)("button",{ref:eV,type:"button",className:"figma-snapshot-revoke-confirm-btn",onClick:tI,children:"Yes, revoke"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-revoke-cancel-btn",onClick:tE,children:"Cancel"})]}):(0,n.jsx)("button",{ref:eH,type:"button",className:"figma-snapshot-revoke-btn",onClick:()=>{eK(!0),e_(null),eW(null)},children:"Revoke stored token"}),(0,n.jsx)("p",{className:"figma-snapshot-revoke-status",role:"status","aria-live":"polite","aria-atomic":"true",children:eB??eU??""})]})]}),e9.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("section",{className:"figma-snapshot-gallery","aria-label":e8?`${String(e9.length)} selected screen${1!==e9.length?"s":""}`:`${String(ta)} captured and structural screen${1!==ta?"s":""}`,children:e9.slice(0,eY).map((e,t)=>{let a=void 0===r?void 0:()=>r({snapshotRunId:$.runId,screenId:e.screen.screenId,name:e.screen.name}),l={snapshotRunId:$.runId,screenId:e.screen.screenId,name:e.screen.name};return"rendered"===e.kind?(0,n.jsx)(s0,{index:t,screenId:e.screen.screenId,name:e.screen.name,irSummary:e.screen.irSummary,imageSrc:s$($.runId,e.imageIndex),imageByteLength:e.screen.imageByteLength,onAddSource:a,isSourceSelected:e5.has(e.screen.screenId),dragPayload:l},e.screen.screenId):(0,n.jsx)(s0,{index:t,screenId:e.screen.screenId,name:e.screen.name,irSummary:e.screen.irSummary,structuralReason:e.screen.reason,onAddSource:a,isSourceSelected:e5.has(e.screen.screenId),dragPayload:l},e.screen.screenId)})}),eY<e9.length?(0,n.jsx)("button",{type:"button",className:"figma-snapshot-gallery-more",onClick:()=>eG(e=>Math.min(e+24,e9.length)),children:"Show more screens"}):null]}):(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:e8?"The selected screen is not present in this stored snapshot.":"No screens were captured from this board section."})})]})]})}function s4({snapshotRunId:e,screenId:t,screenName:l,loadScreenJsonImpl:i=sA}){let r,s=(0,a.useRef)(null),[o,c]=(0,a.useState)("idle"),[d,u]=(0,a.useState)(null),[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)(null),g=void 0!==(r=l?.trim())&&r.length>0?r:t?.trim()??"Selected Figma view",v=(0,a.useMemo)(()=>null===d?"":JSON.stringify(d,null,2),[d]),b=(0,a.useMemo)(()=>sM(v),[v]),x=(0,a.useCallback)(()=>{if(void 0===e||0===e.trim().length||void 0===t||0===t.trim().length){u(null),c("error"),m("Missing Figma JSON source reference.");return}s.current?.abort();let n=new AbortController;s.current=n,c("loading"),m(null),f(null),i(e,t,n.signal).then(e=>{u(e),c("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(u(null),m(e instanceof Error?e.message:"Failed to load Figma JSON."),c("error"))}).finally(()=>{s.current===n&&(s.current=null)})},[i,t,e]);(0,a.useEffect)(()=>(x(),()=>{s.current?.abort(),s.current=null}),[x]);let y=(0,a.useCallback)(()=>{if(0!==v.length){if(void 0===navigator.clipboard)return void f("Clipboard unavailable");navigator.clipboard.writeText(v).then(()=>f("Copied")).catch(()=>f("Copy failed"))}},[v]);return(0,n.jsxs)("section",{className:"figma-json-window","aria-label":`Figma JSON source ${g}`,children:[(0,n.jsxs)("header",{className:"figma-json-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-json-eyebrow",children:"Figma JSON"}),(0,n.jsx)("h1",{className:"figma-json-heading",title:g,children:g}),(0,n.jsx)("p",{className:"figma-json-meta",children:null!==d?`${d.screen.kind} \xb7 ${(0,aq.formatBytes)(b)} \xb7 captured ${(0,aq.formatDate)(d.fetchedAt)}`:t})]}),(0,n.jsxs)("div",{className:"figma-json-actions",children:[(0,n.jsx)("span",{className:"figma-view-source-badge",children:"QI source"}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-copy-btn",onClick:y,disabled:0===v.length,"aria-disabled":0===v.length?"true":void 0,children:"Copy JSON"})]})]}),"loading"===o?(0,n.jsx)("p",{className:"figma-json-status",role:"status",children:"Loading JSON…"}):null,"error"===o&&null!==p?(0,n.jsxs)("div",{className:"figma-json-error",role:"alert",children:[(0,n.jsx)("p",{children:p}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:x,children:"Retry"})]}):null,null!==h?(0,n.jsx)("p",{className:"figma-view-json-copy-status",role:"status",children:h}):null,"done"===o&&v.length>0?(0,n.jsx)(sD,{text:v,className:"figma-json-code"}):null]})}function s3({imageSrc:e,screenName:t}){let a,l=void 0!==(a=t?.trim())&&a.length>0?a:"Figma image source";return void 0===e||0===e.trim().length?(0,n.jsx)("section",{className:"figma-image-window","aria-label":l,children:(0,n.jsx)("div",{className:"figma-image-missing",role:"alert",children:"Image preview is unavailable."})}):(0,n.jsx)("section",{className:"figma-image-window","aria-label":l,children:(0,n.jsx)(aE.default,{className:"figma-image-preview",src:e,alt:l,width:720,height:480,unoptimized:!0,priority:!0})})}async function s6(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}return l.json()}async function s5(){return s6("/api/quality-intelligence/runs")}async function s8(e){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`)}async function s7(e){let t="QI_RUN_FAILED",n=`HTTP ${e.status.toString()}`;try{let a=await e.json();t=a.error?.code??t,n=a.error?.message??n}catch{}return new w.ApiError(t,n,e.status)}async function s9(e,t,n){let a=await fetch("/api/quality-intelligence/runs",{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json","X-Keiko-CSRF":"1"},body:JSON.stringify(e),signal:t}),l=a.headers.get("content-type")??"";if(!a.ok||!l.includes("text/event-stream"))throw await s7(a);let i=a.body;if(null===i)throw new w.ApiError("QI_NO_STREAM","The server did not return a progress stream.",a.status);let r=i.getReader(),s=new TextDecoder,o="";try{for(;!t.aborted;){let e=await r.read();if(e.done)break;let t=(o+=s.decode(e.value,{stream:!0})).split("\n");for(let e of(o=t.pop()??"",t)){let t=e.trim();if(t.startsWith("data:"))try{n(JSON.parse(t.slice(5).trim()))}catch{}}}}finally{await r.cancel().catch(()=>{}),r.releaseLock()}}async function oe(e){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`,{method:"DELETE"})}async function ot(e,t,n,a){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({action:t,...void 0!==n?{candidateId:n}:{},...void 0!==a?{reviewerLabel:a}:{}})})}async function on(e,t,n,a){return(await s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/edit`,{method:"POST",body:JSON.stringify({candidateId:t,edited:n,...void 0!==a?{editorLabel:a}:{}})})).candidate}async function oa(e,t){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/re-check`,{method:"POST",body:JSON.stringify({sources:t})})}async function ol(e,t){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/regenerate-stale`,{method:"POST",body:JSON.stringify({sources:t})})}async function oi(e,t,n){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/export`,{method:"POST",body:JSON.stringify({adapter:t,dryRun:n?.dryRun??!1,approvedOnly:n?.approvedOnly??!1})})}async function or(e,t){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/traceability`,{method:"POST",body:JSON.stringify({format:t})})}var os=e.i(68336);let oo={open:"Open",approved:"Approved","changes-requested":"Changes requested",rejected:"Rejected",withdrawn:"Withdrawn"},oc={open:"qi-review-open",approved:"qi-review-approved","changes-requested":"qi-review-changes",rejected:"qi-review-rejected",withdrawn:"qi-review-withdrawn"};function od({state:e}){return(0,n.jsxs)("span",{className:`qi-review-badge ${oc[e]}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"Review: "}),oo[e]]})}function ou(e){if(e instanceof w.ApiError){var t,n;return t=e.code,n=e.message,`${n} (${t})`}return e instanceof Error?e.message:"An unexpected error occurred."}function op(e){try{return new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}catch{return e}}let om={running:"Running",succeeded:"Succeeded",failed:"Failed",cancelled:"Cancelled"},oh={running:"qi-badge-running",succeeded:"qi-badge-succeeded",failed:"qi-badge-failed",cancelled:"qi-badge-cancelled"};function of(e){return"running"===e||"succeeded"===e||"failed"===e||"cancelled"===e}function og({status:e}){let t=of(e)?om[e]:e,a=of(e)?oh[e]:"qi-badge-default";return(0,n.jsx)("span",{className:`qi-badge ${a}`,children:t})}let ov={critical:"qi-sev-critical",high:"qi-sev-high",medium:"qi-sev-medium",low:"qi-sev-low"};function ob({severity:e}){let t="critical"===e||"high"===e||"medium"===e||"low"===e?ov[e]:"qi-sev-low";return(0,n.jsxs)("span",{className:`qi-sev ${t}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"Severity: "}),e]})}function ox({score:e}){if(null===e)return(0,n.jsxs)("span",{className:"qi-badge qi-badge-default","data-testid":"qi-quality-badge",children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"—"}),(0,n.jsx)("span",{className:"sr-only",children:"Quality score not available"})]});let t=Math.round(e);return(0,n.jsxs)("span",{className:`qi-badge ${t>=90?"qi-quality-high":t>=70?"qi-quality-mid":"qi-quality-low"}`,"data-testid":"qi-quality-badge",children:[t.toString(),(0,n.jsx)("span",{className:"sr-only",children:" out of 100"})]})}function oy({flag:e}){return(0,n.jsxs)("div",{role:"note","aria-label":`Weak test flagged by the quality judge: ${e.rationale}`,className:"qi-weak-flag","data-testid":"qi-weak-flag",children:[(0,n.jsxs)("span",{className:"qi-weak-flag-badge",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-weak-flag-icon",children:"⚠"}),"Weak test"]}),(0,n.jsx)("p",{className:"qi-weak-flag-reason",children:e.rationale})]})}let ow={verifiability:"Verifiability",atomicity:"Atomicity",determinism:"Determinism","ac-fidelity":"AC fidelity"};function oj({verdict:e}){let t=Math.round(e.score),a="strong"===e.verdict?"Strong":"Weak";return(0,n.jsxs)("div",{role:"note","aria-label":`Quality judge verdict: ${a}, ${t.toString()} out of 100. ${e.overallRationale}`,className:"qi-cand-block","data-testid":"qi-quality-verdict",children:[(0,n.jsx)("p",{className:"qi-cand-block-label",children:"Quality verdict"}),(0,n.jsxs)("p",{children:[a," - ",t.toString(),"/100"]}),(0,n.jsx)("ul",{className:"qi-cand-list","aria-label":"Quality dimensions",children:e.dimensions.map(e=>(0,n.jsxs)("li",{children:[ow[e.name]??e.name," ",Math.round(e.score).toString(),": ",e.rationale]},e.name))})]})}function ok({height:e=20,width:t="100%"}){return(0,n.jsx)("div",{"aria-hidden":"true",className:"qi-skeleton",style:{height:e,width:t}})}function oN(){return(0,n.jsx)("div",{"data-testid":"qi-loading-state","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 0"},children:[1,2,3].map(e=>(0,n.jsxs)("div",{className:"qi-skeleton-row",children:[(0,n.jsx)(ok,{height:14,width:"60%"}),(0,n.jsx)(ok,{height:12,width:"40%"})]},e))})}function oS({message:e,onRetry:t}){return(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert","data-testid":"qi-error-state",children:[e,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:t,children:"Retry"})]})}let oC="connectedSourcesJson";function oI(e,t){let n=e[t];return"string"==typeof n?n:void 0}function oE(e,t){return"string"==typeof e[t]}function oR(e){if(!("object"==typeof e&&null!==e&&!Array.isArray(e))||!oE(e,"label"))return!1;switch(e.kind){case"file":case"workspace":return oE(e,"path");case"capsule":return oE(e,"capsuleId");case"capsule-set":return oE(e,"capsuleSetId");case"figma-snapshot":let t;return oE(e,"snapshotRunId")&&(void 0===(t=e.screenIds)||Array.isArray(t)&&t.length>0&&t.every(e=>"string"==typeof e&&e.trim().length>0));case"image":return"figma-snapshot-screen"===e.sourceKind&&oE(e,"snapshotRunId")&&oE(e,"screenId");default:return!1}}function o$(e){return e.length>0?{[oC]:JSON.stringify(e)}:{}}function oA(e){let t=e.split(/[\\/]/u).filter(e=>e.length>0);return t.length>0?t[t.length-1]??e:e}function oT(e){return e.replaceAll("\\","/")}function oL(e){if(/^[A-Za-z]:[/\\]?$/u.test(e))return e.replaceAll("\\","/");if(/^\/\/[^/]+\/[^/]+$/u.test(oT(e)))return oT(e);let t=oT(e).replace(/\/+$/u,"");return 0===t.length&&e.length>0?"/":t}function oP(e){let t=e.connectedRoot??null,n=function(e,t){let n=t?.trim()??"";if(0===n.length)return null;if(n.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(n)||n.startsWith("\\\\")||n.startsWith("//"))return n;let a=e?.trim()??"";if(0===a.length)return null;let l=oL(a),i=oT(n).replace(/^\/+/u,""),r=l.endsWith("/")?"":"/";return`${l}${r}${i}`}(t,e.connectedFilePath??null),a=null!==t?oL(t):null,l=(void 0!==e.connectedRoots&&null!==e.connectedRoots&&e.connectedRoots.length>0?e.connectedRoots:null!==t?[t]:[]).map(oL),i=null!==n?l.filter(e=>e!==a):l,r=[];for(let e of(null!==n&&r.push({kind:"file",label:oA(n),path:n}),i))r.push({kind:"workspace",label:oA(e),path:e});for(let t of e.connectedCapsuleIds??[])r.push({kind:"capsule",label:t,capsuleId:t});for(let t of e.connectedCapsuleSetIds??[])r.push({kind:"capsule-set",label:t,capsuleSetId:t});for(let t of void 0!==e.connectedFigmaSnapshotSources?e.connectedFigmaSnapshotSources:(e.connectedFigmaSnapshotRunIds??[]).map(e=>({kind:"figma-snapshot",label:e,snapshotRunId:e})))r.push(t);for(let t of e.connectedImageSources??[])r.push(t);let s=new Set,o=[];for(let e of r){if(o.length>=16)break;let t=function(e){switch(e.kind){case"file":case"workspace":return`${e.kind}:${e.path}`;case"capsule":return`capsule:${e.capsuleId}`;case"capsule-set":return`capsule-set:${e.capsuleSetId}`;case"figma-snapshot":{let t=e.screenIds,n=void 0===t||0===t.length?"*":[...new Set(t.map(e=>e.trim()).filter(e=>e.length>0))].sort().join(",");return`figma-snapshot:${e.snapshotRunId}:${n}`}case"image":return`image:${e.sourceKind}:${e.snapshotRunId}:${e.screenId}`}}(e);s.has(t)||(s.add(t),o.push(e))}return o}let oM=[{id:"regression-default",label:"Regression (default)"},{id:"banking-default",label:"Banking"},{id:"insurance-default",label:"Insurance"}],oD=[{id:"requirements",label:"Requirements",hint:"Paste text"},{id:"workspace",label:"Folder",hint:"Browse local"},{id:"file",label:"File",hint:"Browse local"},{id:"capsule",label:"Capsule",hint:"Local Knowledge"},{id:"capsule-set",label:"Capsule set",hint:"Local Knowledge"}];function oq({kind:e}){return"requirements"===e?(0,n.jsx)(j.Icons.review,{size:15}):"workspace"===e?(0,n.jsx)(j.Icons.folder,{size:15}):"file"===e?(0,n.jsx)(j.Icons.file,{size:15}):"capsule-set"===e?(0,n.jsx)(j.Icons.layers,{size:15}):(0,n.jsx)("svg",{"aria-hidden":"true",className:"qi-source-kind-icon-svg",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{d:"M12 3.8 19 7.7v8.6L12 20.2 5 16.3V7.7z"})})}let oF={phase:"Starting…",stageName:null,candidates:0,findings:0,atomCount:null,droppedSourceCount:0,skippedSources:[]},oO="Der Lauf wurde nicht erfolgreich abgeschlossen. Passe die Quelle an und versuche es erneut.";function oz(e){switch(e.code){case"QI_IMAGE_DESCRIPTION_UNAVAILABLE":return`${e.label} (image was readable, but the image model produced no usable description)`;case"QI_IMAGE_UNAVAILABLE":return`${e.label} (stored image could not be found or read)`;case"QI_FIGMA_SNAPSHOT_UNAVAILABLE":return`${e.label} (stored Figma snapshot could not be found or read)`;case"QI_SOURCE_EMPTY":return`${e.label} (source produced no usable evidence)`;case"QI_SOURCE_DENIED":return`${e.label} (source is in a protected location)`;case"QI_SOURCE_TOO_LARGE":return`${e.label} (source is too large for this run)`;case"QI_SOURCE_UNSUPPORTED":return`${e.label} (source format is not supported)`;case"QI_WORKSPACE_NOT_FOUND":return`${e.label} (workspace path could not be read)`;case"QI_CAPSULE_UNAVAILABLE":return`${e.label} (knowledge source is unavailable)`;default:return`${e.label} (could not be read)`}}function oK(e){switch(e.kind){case"file":return"File";case"workspace":return"Folder";case"capsule":return"Capsule";case"capsule-set":return"Capsule set";case"figma-snapshot":return e.label.startsWith("JSON ·")?"Figma JSON":"Figma snapshot";case"image":return"Image"}}function oB(e){switch(e.kind){case"file":case"workspace":return e.path;case"capsule":return e.capsuleId;case"capsule-set":return e.capsuleSetId;case"figma-snapshot":return void 0!==e.screenIds&&e.screenIds.length>0?`${e.snapshotRunId}#${e.screenIds.join(",")}`:e.snapshotRunId;case"image":return`${e.snapshotRunId}#${e.screenId}`}}function o_({onRunCompleted:e,startImpl:t=s9,fetchCapsulesImpl:l=lD.fetchCapsules,fetchCapsuleSetsImpl:i=lD.fetchCapsuleSets,fetchProjectsImpl:r=w.fetchProjects,fetchFilesTreeImpl:s=w.fetchFilesTree,connectedRoot:o=null,connectedFilePath:c=null,connectedRoots:d,connectedCapsuleIds:u,connectedCapsuleSetIds:p,connectedFigmaSnapshotRunIds:m,connectedFigmaSnapshotSources:h,connectedImageSources:f}){let[g,v]=(0,a.useState)(""),[b,x]=(0,a.useState)("requirements"),[y,j]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)(""),[I,E]=(0,a.useState)(""),[R,$]=(0,a.useState)(!1),[A,T]=(0,a.useState)([]),[L,P]=(0,a.useState)([]),[M,D]=(0,a.useState)(!1),[q,F]=(0,a.useState)(null),[O,z]=(0,a.useState)("regression-default"),[K,B]=(0,a.useState)(""),[_,U]=(0,a.useState)(!1),[W,V]=(0,a.useState)(oF),[H,Y]=(0,a.useState)(null),[G,J]=(0,a.useState)(null),X=(0,a.useRef)(null),Q=(0,a.useRef)(null),Z=(0,a.useRef)(null),ee=(0,a.useRef)(!1),et=oP({connectedRoot:o,connectedFilePath:c,connectedRoots:d,connectedCapsuleIds:u,connectedCapsuleSetIds:p,connectedFigmaSnapshotRunIds:m,connectedFigmaSnapshotSources:h,connectedImageSources:f}),en=et.length>0,ea=A.find(e=>e.id===S),el=L.find(e=>e.id===I),ei=k.trim().length>0,er="requirements"===b?y.trim().length>0:"workspace"===b||"file"===b?ei:"capsule"===b?S.trim().length>0:I.trim().length>0,es="requirements"===b?0===y.trim().length:("workspace"===b||"file"===b)&&!ei,eo=er||es&&en,ec=K.trim(),ed=0===ec.length?void 0:/^\d+$/u.test(ec)?Number(ec):NaN,eu=void 0===ed||Number.isSafeInteger(ed)&&Number.isFinite(ed),ep=e=>{let t=Number.parseInt(K.trim(),10);B(String(Math.max(0,(Number.isFinite(t)?t:0)+e))),Y(null)},em=!eo||!eu,eh=(0,a.useId)(),ef=(0,a.useId)(),eg=(0,a.useId)(),ev=(0,a.useId)(),eb=(0,a.useId)(),ex=eo?eu?void 0:ef:eh,ey="workspace"===b||"file"===b?b:null,ew=(0,a.useCallback)(e=>{x(e),$(!1),Y(null),F(null)},[]),ej=(0,a.useCallback)((e,t)=>{_||0!==e.button||ew(t)},[ew,_]),ek=(0,a.useCallback)(e=>{if(_)return;let t="ArrowRight"===e.key||"ArrowDown"===e.key?1:"ArrowLeft"===e.key||"ArrowUp"===e.key?-1:0;if(0===t)return;e.preventDefault();let n=oD.length,a=(Math.max(0,oD.findIndex(e=>e.id===b))+t+n)%n,l=oD[a];void 0!==l&&(ew(l.id),e.currentTarget.parentElement?.querySelectorAll('[role="radio"]')[a]?.focus())},[ew,_,b]),eN=(0,a.useCallback)(e=>{var t,n,a;"event"===e.type&&("stage:failed"===e.kind||"run:failed"===e.kind)&&"string"==typeof e.reasonSummary&&(Z.current=e.reasonSummary),"done"===e.type&&("succeeded"===e.status?(Q.current=e.runId,!0===e.degraded&&J(function(e){let t="Die Modellgenerierung ist fehlgeschlagen — Keiko hat deterministische Baseline-Testfälle aus der Evidenz erstellt. Diese sind nicht modellgestützt; prüfe das Modell-Gateway und starte den Lauf für modellgestützte Testfälle erneut.";if(null==e||0===e.trim().length)return t;if("qi-error: UnparseableModelOutputError"===e)return`${t} (Modellausgabe nicht als JSON parsebar)`;if("qi-error: QI_PROMPT_TOO_LARGE"===e)return`${t} (Quellkontext f\xfcr das Modell zu gro\xdf)`;let n=e.startsWith("qi-error: ")?e.slice(10):e.startsWith("qi-safe-error: ")?e.slice(15):e;return`${t} (${n})`}(e.reasonSummary??null))):"failed"===e.status&&Y(null==(t=e.reasonSummary??Z.current)||0===t.trim().length?oO:"qi-run-error"===t?"Die Modellgenerierung ist fehlgeschlagen, bevor nutzbare Testfälle zurückgegeben wurden. Versuche es mit einer kleineren Quelle oder prüfe das ausgewählte Modell-Gateway.":"qi-error: UnparseableModelOutputError"===t?"Das Modell hat eine Ausgabe geliefert, die nicht zu Testfällen geparst werden konnte. Versuche es erneut oder nutze ein Modell mit strukturierter JSON-Ausgabe.":"qi-error: QI_PROMPT_TOO_LARGE"===t?"Der zusammengestellte Quellkontext ist für das Modell zu groß. Reduziere die Quelle und versuche es erneut.":t.startsWith("qi-error: ")?`${oO} (${t.slice(10)})`:t.startsWith("qi-safe-error: ")?`${oO} (${t.slice(15)})`:`${oO} (${t})`)),"error"===e.type&&Y((n=e.code,a=e.message,`${a} (${n})`)),V(t=>(function(e,t){if("accepted"===t.type)return{...e,phase:"Ingested sources",atomCount:t.atomCount,droppedSourceCount:t.droppedSourceCount??0,skippedSources:t.skippedSources??[]};if("event"===t.type){let n="candidate:proposed"===t.kind?e.candidates+1:e.candidates,a="finding:recorded"===t.kind?e.findings+1:e.findings,l=t.stageName??e.stageName;return{...e,phase:t.kind,stageName:l,candidates:n,findings:a}}return e})(t,e))},[]),eS="capsule"===b||"capsule-set"===b;(0,a.useEffect)(()=>{if(!eS)return;let e=!1;return async function(){D(!0),F(null);try{let[t,n]=await Promise.allSettled([l(),i()]);if(e)return;"fulfilled"===t.status?T(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):(T([]),"capsule"===b&&F(ou(t.reason))),"fulfilled"===n.status?P(n.value.capsuleSets):(P([]),"capsule-set"===b&&F(ou(n.reason)))}finally{e||D(!1)}}(),()=>{e=!0}},[l,i,eS,b]),(0,a.useEffect)(()=>{if("capsule"===b){let e=A.some(e=>e.id===S)?S:A[0]?.id??"";e!==S&&C(e)}if("capsule-set"===b){let e=L.some(e=>e.id===I)?I:L[0]?.id??"";e!==I&&E(e)}},[S,I,L,A,b]);let eC=(0,a.useCallback)(()=>{let e=g.trim();return"requirements"===b&&y.trim().length>0?[{kind:"requirements",label:e||"Requirements",text:y}]:"workspace"===b&&k.trim().length>0?[{kind:"workspace",label:e||"Folder",path:k.trim()}]:"file"===b&&k.trim().length>0?[{kind:"file",label:e||"File",path:k.trim()}]:"capsule"===b&&S.trim().length>0?[{kind:"capsule",label:e||ea?.displayName||"Knowledge capsule",capsuleId:S.trim()}]:"capsule-set"===b&&I.trim().length>0?[{kind:"capsule-set",label:e||el?.displayName||"Capsule set",capsuleSetId:I.trim()}]:null},[S,I,g,k,ea,el,b,y]),eI=(0,a.useCallback)(async()=>{if(!eo||_||!eu||ee.current)return;ee.current=!0,U(!0),Y(null),J(null),V(oF),Q.current=null,Z.current=null;let n=new AbortController;X.current=n;let a=eC()??et,l={sources:a,profileId:O,...void 0!==ed?{seed:ed}:{}};try{await t(l,n.signal,eN);let i=Q.current;null!==i&&e?.(i,a.filter(e=>"requirements"!==e.kind))}catch(e){n.signal.aborted||Y(ou(e))}finally{U(!1),X.current=null,ee.current=!1}},[eo,O,_,et,eC,eN,e,ed,eu,t]),eE=(0,a.useCallback)(()=>{X.current?.abort()},[]),eR=W.droppedSourceCount>0?`${W.droppedSourceCount.toString()} source${1!==W.droppedSourceCount?"s":""} over the 16-source limit ${1!==W.droppedSourceCount?"were":"was"} not included.`:null,e$=function(e){if(0===e.length)return null;let t=e.length.toString(),n=1!==e.length?"sources were":"source was";return`${t} connected ${n} skipped: ${e.map(oz).join(", ")}.`}(W.skippedSources),eA=[eR,e$].filter(e=>null!==e).join(" ");return(0,n.jsxs)("section",{className:"qi-launcher","aria-label":"Start a Quality Intelligence run",children:[(0,n.jsx)("header",{className:"qi-col-header",children:(0,n.jsx)("h2",{className:"qi-col-title",children:"New run"})}),(0,n.jsxs)("div",{className:"qi-launcher-body",children:[1===et.length&&void 0!==et[0]?(0,n.jsxs)("div",{className:"qi-connected-source","data-testid":"qi-connected-source",children:[(0,n.jsxs)("span",{className:"qi-connected-kind",children:["Connected ",oK(et[0]).toLowerCase()]}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:oB(et[0]),children:oB(et[0])}),(0,n.jsx)("span",{className:"qi-connected-hint",children:er?"Manual input below overrides the connected source for this run.":`Generate uses the connected ${oK(et[0]).toLowerCase()}.`})]}):et.length>1?(0,n.jsxs)("div",{className:"qi-connected-source","data-testid":"qi-connected-source",children:[(0,n.jsxs)("span",{className:"qi-connected-kind",children:["Connected sources (",et.length.toString(),")"]}),(0,n.jsx)("ul",{className:"qi-connected-roots","aria-label":"Connected sources",children:et.map(e=>(0,n.jsxs)("li",{className:"qi-connected-root-item",children:[(0,n.jsx)("span",{className:"qi-connected-root-name",children:oK(e)}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:oB(e),children:oB(e)})]},`${e.kind}:${oB(e)}`))}),(0,n.jsx)("span",{className:"qi-connected-hint",children:er?"Manual input below overrides the connected sources for this run.":"Generate uses all connected sources."})]}):null,(0,n.jsxs)("div",{className:"qi-launcher-row",children:[(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Source label"}),(0,n.jsx)("input",{type:"text",className:"qi-input",value:g,placeholder:"e.g. Funds Transfer — acceptance criteria",disabled:_,"aria-describedby":en&&!er?eg:void 0,onChange:e=>{v(e.target.value)}}),en&&!er?(0,n.jsx)("span",{className:"qi-field-hint",id:eg,children:"Applies to manual input only — connected sources use their own labels."}):null]}),(0,n.jsxs)("div",{className:"qi-field qi-field-kind",children:[(0,n.jsx)("span",{className:"qi-field-label",id:ev,children:"Source type"}),(0,n.jsx)("div",{className:"qi-source-kind-grid",role:"radiogroup","aria-labelledby":ev,"aria-disabled":_||void 0,children:oD.map(e=>(0,n.jsxs)("button",{type:"button",className:"qi-source-kind-option",role:"radio","aria-label":e.label,"data-tip":e.label,"aria-checked":b===e.id,tabIndex:b===e.id?0:-1,disabled:_,onPointerDown:t=>{ej(t,e.id)},onClick:()=>ew(e.id),onKeyDown:ek,children:[(0,n.jsx)("span",{className:"qi-source-kind-label",children:e.label}),(0,n.jsx)("span",{className:"qi-source-kind-icon","aria-hidden":"true",children:(0,n.jsx)(oq,{kind:e.id})})]},e.id))})]})]}),function(){if("requirements"===b)return(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Requirements"}),(0,n.jsx)("textarea",{className:"qi-textarea",value:y,rows:6,placeholder:"Paste requirements or acceptance criteria, one statement per line.",disabled:_,onChange:e=>{j(e.target.value)}})]});if("workspace"===b||"file"===b){let e="file"===b;return(0,n.jsxs)("div",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",id:eb,children:e?"File path":"Folder path"}),(0,n.jsxs)("div",{className:"qi-path-picker",children:[(0,n.jsx)("div",{className:"qi-path-value qi-monospace",role:"textbox","aria-readonly":"true","aria-labelledby":eb,title:k,"data-empty":0===k.trim().length?"true":void 0,children:k.trim().length>0?k:e?"Choose a local file…":"Choose a local folder…"}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-browse-btn",disabled:_,onClick:()=>$(!0),children:"Browse"})]})]})}let e="capsule"===b,t=e?A:L;return(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:e?"Knowledge capsule":"Capsule set"}),(0,n.jsxs)("select",{className:"qi-select",value:e?S:I,disabled:_||M||null!==q||0===t.length,onChange:t=>{e?C(t.target.value):E(t.target.value)},children:[M?(0,n.jsx)("option",{value:"",children:"Loading connectors..."}):null,M||0!==t.length?null:(0,n.jsx)("option",{value:"",children:e?"No ready capsules":"No capsule sets"}),e?A.map(e=>(0,n.jsx)("option",{value:e.id,children:e.displayName},e.id)):L.map(e=>(0,n.jsx)("option",{value:e.id,children:`${e.displayName} (${String(e.capsuleCount)} capsules)`},e.id))]})]})}(),null!==q?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-connector-error",children:q}):null,(0,n.jsxs)("div",{className:"qi-launcher-controls",children:[(0,n.jsxs)("div",{className:"qi-field qi-field-inline qi-policy-profile-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Policy profile"}),(0,n.jsx)(tz,{triggerClassName:"qi-select",value:O,ariaLabel:"Policy profile",disabled:_,menuTitle:"Policy",menuClassName:"qi-policy-profile-menu",sections:[{options:oM.map(e=>({value:e.id,label:e.label}))}],onValueChange:z})]}),(0,n.jsxs)("label",{className:"qi-field qi-field-inline",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Seed (optional)"}),(0,n.jsxs)("span",{className:"number-control qi-number-control",children:[(0,n.jsx)("input",{type:"number",min:0,step:1,className:"qi-input number-control-input",value:K,placeholder:"e.g. 42",disabled:_,"aria-invalid":!eu||void 0,"aria-describedby":eu?void 0:ef,onChange:e=>{B(e.target.value),Y(null)},onWheel:e=>{_||0===e.deltaY||(e.preventDefault(),ep(e.deltaY<0?1:-1))}}),(0,n.jsx)(a3,{label:"seed",disabled:_,onStepUp:()=>ep(1),onStepDown:()=>ep(-1)})]}),eu?null:(0,n.jsx)("span",{className:"qi-field-error",id:ef,children:"Seed must be a non-negative integer."})]}),(0,n.jsx)("button",{type:"button",className:_?"qi-btn qi-btn-secondary":"qi-btn qi-btn-primary","aria-disabled":!_&&em||void 0,"aria-describedby":_?void 0:ex,onClick:()=>{_?eE():em||eI()},children:_?"Cancel":"Generate test cases"}),_||eo?null:(0,n.jsx)("span",{className:"qi-generate-hint",id:eh,children:"Add requirements text, a folder path, a file path, select a capsule, select a capsule set, or connect a source to generate."})]}),_?(0,n.jsxs)("div",{className:"qi-progress","data-testid":"qi-launch-progress","aria-hidden":"true",children:[(0,n.jsx)("span",{className:"qi-progress-spinner","aria-hidden":"true"}),(0,n.jsxs)("span",{className:"qi-progress-text",children:[null!==W.stageName?`Stage: ${W.stageName} \xb7 `:"",W.candidates.toString()," test case",1!==W.candidates?"s":"",W.findings>0?` \xb7 ${W.findings.toString()} finding${1!==W.findings?"s":""}`:""]})]}):null,(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"qi-launch-progress-sr",children:function(e,t){if(!e)return"";if(null===t.stageName&&0===t.candidates&&0===t.findings)return"Generating test cases…";let n=null!==t.stageName?`Stage: ${t.stageName}. `:"",a=`${t.candidates.toString()} test case${1!==t.candidates?"s":""}`,l=t.findings>0?`, ${t.findings.toString()} finding${1!==t.findings?"s":""}`:"";return`${n}${a}${l}`}(_,W)}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:eA}),null!==eR||null!==e$?(0,n.jsxs)("div",{className:"qi-coverage-notice","data-testid":"qi-coverage-notice",children:[null!==eR?(0,n.jsx)("p",{className:"qi-coverage-line",children:eR}):null,null!==e$?(0,n.jsx)("p",{className:"qi-coverage-line",children:e$}):null]}):null,null!==G?(0,n.jsx)("p",{className:"qi-degraded-notice",role:"status","data-testid":"qi-launch-degraded",children:G}):null,null!==H?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-launch-error",children:H}):null]}),R&&null!==ey?(0,n.jsx)(os.LocalFileBrowserDialog,{mode:"file"===ey?"file":"folder",title:`Choose ${"file"===ey?"file":"folder"} source`,description:"Browse a registered local project or enter an absolute folder root.",initialRootPath:"file"===ey?(0,os.dirname)(k):k,fetchProjectsImpl:r,fetchFilesTreeImpl:s,onCancel:()=>$(!1),onApply:e=>{N("file"===ey?(0,os.displayLocalPath)(e.rootPath,e.files[0]??null):e.folderPath),$(!1),Y(null)}}):null]})}function oU({run:e,onOpen:t,onDelete:l,deleting:i}){var r;let s=e.totals.candidates,[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(null),p=(0,a.useRef)(null);(0,a.useEffect)(()=>{o&&u.current?.focus()},[o]);let m=(0,a.useCallback)(()=>{c(!1),requestAnimationFrame(()=>{d.current?.focus()})},[]),h=(0,a.useCallback)(e=>{"Escape"===e.key&&(e.preventDefault(),m())},[m]),f=(0,a.useCallback)(()=>{i||l(e.id)},[i,l,e.id]);return(0,n.jsxs)("li",{style:{display:"flex",alignItems:"stretch"},children:[(0,n.jsxs)("button",{type:"button",className:"qi-run-item",style:{flex:1},onClick:()=>{t(e.id,[])},"aria-label":`Open run ${e.id} — ${of(r=e.status)?om[r]:r}, ${op(e.requestedAt)}, ${s.toString()} test case${1!==s?"s":""}, review ${oo[e.reviewState]}`,title:`Open run ${e.id}`,children:[(0,n.jsx)("span",{className:"qi-run-title",children:op(e.requestedAt)}),(0,n.jsx)(og,{status:e.status}),(0,n.jsx)(od,{state:e.reviewState}),(0,n.jsxs)("span",{className:"qi-run-id",children:[e.id.slice(0,16),"…"]}),(0,n.jsxs)("span",{className:"qi-run-totals",children:[e.totals.candidates.toString()," test case",1!==e.totals.candidates?"s":""]})]}),o?(0,n.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":`Confirm deleting run ${op(e.requestedAt)}`,style:{display:"flex",alignItems:"center",gap:4,padding:"0 6px",flexShrink:0},children:[(0,n.jsx)("button",{ref:p,type:"button",className:"qi-btn qi-btn-reject",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-label":`Confirm delete of run ${op(e.requestedAt)}`,"aria-busy":i||void 0,"aria-disabled":i||void 0,onClick:f,onKeyDown:h,children:i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"Deleting…"}),(0,n.jsx)("span",{className:"sr-only",children:"Deleting run, please wait"})]}):"Confirm delete"}),(0,n.jsx)("button",{ref:u,type:"button",className:"qi-btn qi-btn-secondary",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-disabled":i||void 0,onClick:()=>{i||m()},onKeyDown:h,children:"Cancel"})]}):(0,n.jsx)("button",{ref:d,type:"button",className:"qi-btn qi-btn-reject",style:{alignSelf:"center",minWidth:0,padding:"4px 10px",fontSize:12,margin:"0 6px 0 0",flexShrink:0},"aria-label":`Delete run ${op(e.requestedAt)}`,onClick:()=>{c(!0)},children:"Delete"})]})}function oW({openRun:e,connectedRoot:t=null,connectedFilePath:l=null,connectedRoots:i,connectedCapsuleIds:r,connectedCapsuleSetIds:s,connectedFigmaSnapshotRunIds:o,connectedFigmaSnapshotSources:c,connectedImageSources:d,fetchRunsImpl:u=s5,deleteImpl:p=oe}){let[m,h]=(0,a.useState)([]),[f,g]=(0,a.useState)(0),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(!0),[w,j]=(0,a.useState)(null),[k,N]=(0,a.useState)(25),[S,C]=(0,a.useState)(null),[I,E]=(0,a.useState)(""),R=(0,a.useCallback)(async()=>{y(!0),j(null);try{let e=await u();h(e.runs),g(e.totalRunIds),b(e.truncated)}catch(e){j(ou(e))}finally{y(!1)}},[u]);(0,a.useEffect)(()=>{R()},[R]);let $=(0,a.useCallback)((t,n)=>{R(),e(t,n)},[R,e]),A=(0,a.useCallback)(async e=>{if(null===S){C(e),j(null);try{await p(e),E("Run deleted."),await R()}catch(e){j(ou(e))}finally{C(null)}}},[S,p,R]);return(0,n.jsxs)("div",{className:"qi-hub",children:[(0,n.jsx)(o_,{onRunCompleted:$,connectedRoot:t,connectedFilePath:l,connectedRoots:i,connectedCapsuleIds:r,connectedCapsuleSetIds:s,connectedFigmaSnapshotRunIds:o,connectedFigmaSnapshotSources:c,connectedImageSources:d}),(0,n.jsxs)("section",{className:"qi-hub-runs","aria-label":"Quality Intelligence runs",children:[(0,n.jsxs)("header",{className:"qi-col-header",children:[(0,n.jsx)("h2",{className:"qi-col-title",children:"Runs"}),x||null!==w?null:(0,n.jsx)("span",{className:"qi-col-count",children:f.toString()})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:x?"Loading runs…":null===w?`Run list loaded: ${m.length.toString()} run${1===m.length?"":"s"}${v?` of ${f.toString()}`:""}.`:""}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:I}),(0,n.jsx)("div",{className:"qi-col-body","aria-busy":x,children:x?(0,n.jsx)(oN,{}):null!==w?(0,n.jsx)(oS,{message:w,onRetry:()=>{R()}}):0===m.length?(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No runs yet"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"Start a run above — generated test cases open as cards on your workspace."})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:"qi-run-list","aria-label":"Run list",children:m.slice(0,k).map(t=>(0,n.jsx)(oU,{run:t,onOpen:e,onDelete:e=>{A(e)},deleting:S===t.id},t.id))}),k<m.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{N(e=>e+25)},children:["Show more runs (",(m.length-k).toString()," remaining)"]}):null,v?(0,n.jsx)("p",{className:"qi-runs-truncated","data-testid":"qi-runs-truncated",children:`Showing ${m.length.toString()} of ${f.toString()} runs.`}):null]})})]})]})}e.s(["QUALITY_INTELLIGENCE_SCHEMA_VERSION",0,"1"],73859),e.i(73859);let oV=["..","/","\\"],oH=(e,t)=>"string"!=typeof e?{ok:!1,reason:`${t} must be a string`}:0===e.length?{ok:!1,reason:`${t} must not be empty`}:0===e.trim().length?{ok:!1,reason:`${t} must not be whitespace-only`}:e!==e.trim()?{ok:!1,reason:`${t} must not have leading or trailing whitespace`}:e.length>256?{ok:!1,reason:`${t} exceeds max length ${String(256)}`}:e.normalize("NFKC")!==e?{ok:!1,reason:`${t} must be NFKC-normalised`}:(e=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31||127===n||n>=128&&n<=159)return!0}return!1})(e)?{ok:!1,reason:`${t} contains control characters`}:oV.some(t=>e.includes(t))?{ok:!1,reason:`${t} contains forbidden path fragment`}:{ok:!0},oY=(e,t)=>{let n=oH(e,t);if(!n.ok)throw TypeError(`Invalid ${t}: ${n.reason}`);return e},oG=e=>1564===e||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8294&&e<=8297||65279===e,oJ=e=>!!(/[a-z][a-z0-9+.-]*:\/\//iu.test(e)||/AKIA[0-9A-Z]{12,}/u.test(e)||/(?:ghp_|gho_|github_pat_)[A-Za-z0-9_]{20,}/u.test(e)||/xox[baprs]-[A-Za-z0-9-]{10,}/u.test(e)||/sk-[A-Za-z0-9]{16,}/u.test(e)||/\bBearer\s+\S/u.test(e)||/-----BEGIN [A-Z ]*PRIVATE KEY-----/u.test(e)||/^(?:\/|[A-Za-z]:[\\/]|\\\\)/u.test(e)||(e=>{for(let t of e)if(oG(t.codePointAt(0)??0))return!0;return!1})(e)),oX=e=>Number.isFinite(e)&&e>=0&&e<=1,oQ=Object.freeze({critical:0,high:1,medium:2,low:3}),oZ=new Set(["jira-issues","qtest","xray","polarion","alm","quality-center"]),o0=["verifiability","atomicity","determinism","ac-fidelity"],o1=Object.freeze({type:"object",additionalProperties:!1,required:["dimensions","overallRationale"],properties:{dimensions:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","score","rationale"],properties:{name:{type:"string",enum:[...o0]},score:{type:"integer",minimum:0,maximum:100},rationale:{type:"string"}}}},overallRationale:{type:"string"}}});e.s(["QUALITY_INTELLIGENCE_AUDIT_MANIFEST_SCHEMA_VERSION",0,1,"QUALITY_INTELLIGENCE_COVERAGE_KINDS",0,["derived","asserted","manual"],"QUALITY_INTELLIGENCE_EVENT_SCHEMA_VERSION",0,1,"QUALITY_INTELLIGENCE_EVIDENCE_ATOM_KINDS",0,["requirement","design-fragment","code-fragment","document-excerpt","human-statement"],"QUALITY_INTELLIGENCE_EXPORT_ADAPTERS",0,["jira-issues","qtest","xray","polarion","alm","csv","json","spreadsheet-safe-csv","markdown","plain-text","quality-center"],"QUALITY_INTELLIGENCE_HANDOFF_PROMPTED_ACTIONS",0,["design-tests","validate-tests","review-coverage","request-export"],"QUALITY_INTELLIGENCE_LIFECYCLE_STATUSES",0,["draft","finalised","archived"],"QUALITY_INTELLIGENCE_PLANNER_KINDS",0,["scripted","model-routed"],"QUALITY_INTELLIGENCE_PRIORITIES",0,["P0","P1","P2","P3"],"QUALITY_INTELLIGENCE_REDACTION_STATUSES",0,["redacted","not-required"],"QUALITY_INTELLIGENCE_REVIEWER_KINDS",0,["human-author","human-reviewer","judge"],"QUALITY_INTELLIGENCE_REVIEW_STATES",0,["open","approved","changes-requested","rejected","withdrawn"],"QUALITY_INTELLIGENCE_RISK_CLASSES",0,["safety","compliance","regression","functional","visual"],"QUALITY_INTELLIGENCE_RUN_EVENT_KINDS",0,["run:queued","run:started","stage:started","stage:completed","stage:failed","candidate:proposed","finding:recorded","review:requested","review:completed","run:succeeded","run:failed","run:cancelled"],"QUALITY_INTELLIGENCE_SCHEMA_VERSION",0,"1","QUALITY_INTELLIGENCE_SEVERITIES",0,["critical","high","medium","low"],"QUALITY_INTELLIGENCE_SEVERITY_RANK",0,oQ,"QUALITY_INTELLIGENCE_SOURCE_KINDS",0,["repository-context","local-knowledge-capsule","figma-evidence","human-context","connector-document"],"QUALITY_INTELLIGENCE_TEST_CASE_STATUSES",0,["proposed","accepted","rejected","needs-review"],"QUALITY_INTELLIGENCE_TMS_ADAPTERS",0,oZ,"QUALITY_INTELLIGENCE_VALIDATION_FINDING_KINDS",0,["logic-defect","faithfulness-defect","semantic-defect","mutation-defect","policy-violation","manual-rejection","coverage-gap","test-quality"],"TEST_QUALITY_JUDGE_RESPONSE_SCHEMA",0,o1,"TEST_QUALITY_RUBRIC_DIMENSIONS",0,o0,"asQualityIntelligenceAuditSummaryId",0,e=>oY(e,"QualityIntelligenceAuditSummaryId"),"asQualityIntelligenceCoverageMapId",0,e=>oY(e,"QualityIntelligenceCoverageMapId"),"asQualityIntelligenceEvidenceAtomId",0,e=>oY(e,"QualityIntelligenceEvidenceAtomId"),"asQualityIntelligenceExportBundleId",0,e=>oY(e,"QualityIntelligenceExportBundleId"),"asQualityIntelligenceReviewRecordId",0,e=>oY(e,"QualityIntelligenceReviewRecordId"),"asQualityIntelligenceRunId",0,e=>oY(e,"QualityIntelligenceRunId"),"asQualityIntelligenceSourceEnvelopeId",0,e=>oY(e,"QualityIntelligenceSourceEnvelopeId"),"asQualityIntelligenceTestCaseId",0,e=>oY(e,"QualityIntelligenceTestCaseId"),"asQualityIntelligenceValidationFindingId",0,e=>oY(e,"QualityIntelligenceValidationFindingId"),"assertCoverageMapInvariant",0,e=>{for(let t=0;t<e.mappings.length;t+=1){let n=e.mappings[t];if(void 0===n)throw RangeError(`Coverage map mapping[${String(t)}] is missing`);if(!oX(n.confidence))throw RangeError(`Coverage map mapping[${String(t)}] has out-of-range confidence ${String(n.confidence)}`);if(0===n.candidateIds.length)throw RangeError(`Coverage map mapping[${String(t)}] must reference at least one candidate`)}},"assertExportBundleInvariant",0,e=>{if(!/^[0-9a-f]{64}$/u.test(e.integrityHashSha256Hex))throw Error(`Export bundle integrity hash must be a lowercase sha256 hex string (id=${e.id})`);if(oZ.has(e.targetAdapter)&&!e.redactionAttested)throw Error(`Export bundle targeting TMS adapter "${e.targetAdapter}" requires redactionAttested === true (id=${e.id})`)},"assertQualityIntelligenceNever",0,e=>{throw TypeError(`Unexpected Quality Intelligence discriminant: ${JSON.stringify(e)}`)},"assertRunEventSequenceMonotonic",0,e=>{let t=-1;for(let n=0;n<e.length;n+=1){let a=e[n];if(void 0===a)throw RangeError(`Run event[${String(n)}] is missing`);if(!Number.isInteger(a.sequence)||a.sequence<0)throw RangeError(`Run event[${String(n)}] has invalid sequence ${String(a.sequence)}`);if(a.sequence<=t)throw RangeError(`Run event[${String(n)}] sequence ${String(a.sequence)} is not strictly greater than previous ${String(t)}`);t=a.sequence}},"hasCanonicalSha256Hash",0,e=>/^[0-9a-f]{64}$/u.test(e.canonicalHashSha256Hex),"looksLikeBrowserSafeSourceEnvelope",0,e=>{let{displayLabel:t,provenance:n,localRef:a}=e;return!(0===t.length||t.length>256||/^[A-Za-z0-9+/]{40,}={0,2}$/u.test(t)||!/^[0-9a-f]{64}$/u.test(n.integrityHashSha256Hex)||oJ(t)||oJ(a)||oJ(n.origin)||"connector-document"===e.kind&&oJ(e.adapterId))},"validateQualityIntelligenceIdString",0,oH],47425);var o2=e.i(47425),o2=o2;let o4=o2.QUALITY_INTELLIGENCE_PRIORITIES,o3=o2.QUALITY_INTELLIGENCE_RISK_CLASSES,o6=e=>e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),o5=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function o8(e,t){let n=o6(t.preconditions),a=o6(t.steps),l=o6(t.expectedResults),i=t.tags.split(",").map(e=>e.trim()).filter(e=>e.length>0);return{...t.title!==e.title?{title:t.title}:{},...!o5(n,e.preconditions)?{preconditions:n}:{},...!o5(a,e.steps)?{steps:a}:{},...!o5(l,e.expectedResults)?{expectedResults:l}:{},...t.priority!==e.priority?{priority:t.priority}:{},...t.riskClass!==e.riskClass?{riskClass:t.riskClass}:{},...!o5(i,e.tags)?{tags:i}:{}}}function o7({id:e,label:t,value:a,disabled:l=!1,onChange:i}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label",children:t}),(0,n.jsx)("textarea",{id:e,className:"qi-edit-textarea",value:a,rows:3,disabled:l,onChange:e=>{i(e.target.value)}})]})}function o9({id:e,label:t,value:a,disabled:l=!1,required:i=!1,onChange:r}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label","data-required":i?"true":void 0,children:t}),(0,n.jsx)("input",{id:e,className:"qi-edit-input",value:a,disabled:l,required:i,"aria-required":i?"true":void 0,onChange:e=>{r(e.target.value)}})]})}function ce({id:e,label:t,value:a,options:l,disabled:i=!1,onChange:r}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label",children:t}),(0,n.jsx)("select",{id:e,className:"qi-edit-select",value:a,disabled:i,onChange:e=>{r(e.target.value)},children:l.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]})}function ct({onCancel:e,saving:t}){return(0,n.jsxs)("div",{className:"qi-edit-actions",children:[(0,n.jsx)("button",{type:"submit",className:"qi-btn qi-btn-approve qi-edit-save","aria-disabled":t||void 0,children:"Save"}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-edit-cancel","aria-disabled":t||void 0,onClick:()=>{t||e()},children:"Cancel"})]})}function cn({candidate:e,onSave:t,onCancel:l}){let[i,r]=(0,a.useState)(()=>({title:e.title,preconditions:e.preconditions.join("\n"),steps:e.steps.join("\n"),expectedResults:e.expectedResults.join("\n"),priority:e.priority,riskClass:e.riskClass,tags:e.tags.join(", ")})),[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(!1),m=(0,a.useRef)(null),h=(e,t)=>{o(null),p(!1),r(n=>({...n,[e]:t}))},f=(0,a.useCallback)(()=>{c||(!(Object.keys(o8(e,i)).length>0)||u?l():p(!0))},[e,u,l,c,i]);(0,a.useEffect)(()=>{let e=e=>{if("Escape"!==e.key||c)return;let t=m.current;null!==t&&t.contains(document.activeElement)&&f()};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[f,c]),(0,a.useEffect)(()=>{m.current?.querySelector("input.qi-edit-input")?.focus()},[]);let g=`qi-edit-${e.id}`,v=async()=>{if(!c){d(!0),o(null);try{await t(o8(e,i))}catch(e){o(ou(e))}finally{d(!1)}}};return(0,n.jsxs)("form",{ref:m,className:"qi-edit-form","aria-label":`Edit ${e.title}`,"aria-busy":c,onSubmit:e=>{e.preventDefault(),v()},children:[(0,n.jsxs)("div",{className:"qi-edit-head",children:[(0,n.jsxs)("div",{className:"qi-edit-head-copy",children:[(0,n.jsx)("p",{className:"qi-edit-eyebrow",children:"Edit test case"}),(0,n.jsx)("h3",{className:"qi-edit-heading",children:e.title})]}),(0,n.jsx)(ct,{onCancel:f,saving:c})]}),null!==s?(0,n.jsx)("p",{className:"qi-edit-error",role:"alert","aria-live":"assertive",children:s}):null,(0,n.jsx)("p",{className:"qi-edit-discard-note",role:"status","aria-live":"polite",children:u?"Unsaved changes — press Escape or activate Cancel again to discard them.":""}),(0,n.jsxs)("div",{className:"qi-edit-layout",children:[(0,n.jsxs)("div",{className:"qi-edit-main",children:[(0,n.jsx)(o9,{id:`${g}-title`,label:"Title",value:i.title,disabled:c,required:!0,onChange:e=>{h("title",e)}}),(0,n.jsx)(o7,{id:`${g}-preconditions`,label:"Preconditions (one per line)",value:i.preconditions,disabled:c,onChange:e=>{h("preconditions",e)}}),(0,n.jsx)(o7,{id:`${g}-steps`,label:"Steps (one per line)",value:i.steps,disabled:c,onChange:e=>{h("steps",e)}}),(0,n.jsx)(o7,{id:`${g}-expected`,label:"Expected results (one per line)",value:i.expectedResults,disabled:c,onChange:e=>{h("expectedResults",e)}})]}),(0,n.jsxs)("div",{className:"qi-edit-side",children:[(0,n.jsx)(ce,{id:`${g}-priority`,label:"Priority",value:i.priority,options:o4,disabled:c,onChange:e=>{h("priority",e)}}),(0,n.jsx)(ce,{id:`${g}-risk`,label:"Risk class",value:i.riskClass,options:o3,disabled:c,onChange:e=>{h("riskClass",e)}}),(0,n.jsx)(o9,{id:`${g}-tags`,label:"Tags (comma-separated)",value:i.tags,disabled:c,onChange:e=>{h("tags",e)}})]})]})]})}let ca=new Set(["approved","rejected","withdrawn"]);function cl({items:e,label:t}){return 0===e.length?null:(0,n.jsxs)("div",{className:"qi-cand-block",children:[(0,n.jsx)("p",{className:"qi-cand-block-label",children:t}),(0,n.jsx)("ol",{className:"qi-cand-list","aria-label":t,children:e.map((e,a)=>(0,n.jsx)("li",{children:e},`${t}-${String(a)}`))})]})}function ci({candidate:e}){return(0,n.jsxs)("dl",{className:"qi-cand-meta","aria-label":"Test case metadata",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Steps"}),(0,n.jsx)("dd",{children:e.steps.length.toString()})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Expected"}),(0,n.jsx)("dd",{children:e.expectedResults.length.toString()})]}),void 0!==e.qualityVerdict?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Quality"}),(0,n.jsx)("dd",{children:Math.round(e.qualityVerdict.score).toString()})]}):null]})}function cr({title:e,children:t}){return(0,n.jsxs)("details",{className:"qi-cand-accordion",children:[(0,n.jsx)("summary",{className:"qi-cand-accordion-summary",children:(0,n.jsx)("span",{children:e})}),(0,n.jsx)("div",{className:"qi-cand-accordion-body",children:t})]})}function cs({candidate:e}){return(0,n.jsxs)(cr,{title:"Scenario",children:[(0,n.jsx)(cl,{items:e.preconditions,label:"Preconditions"}),(0,n.jsx)(cl,{items:e.steps,label:"Steps"}),(0,n.jsx)(cl,{items:e.expectedResults,label:"Expected results"})]})}function co({candidate:e}){return 0===e.tags.length&&void 0===e.qualityVerdict&&void 0===e.weakTestFlag?null:(0,n.jsxs)(cr,{title:"Evidence",children:[void 0!==e.weakTestFlag?(0,n.jsx)(oy,{flag:e.weakTestFlag}):null,void 0!==e.qualityVerdict?(0,n.jsx)(oj,{verdict:e.qualityVerdict}):null,e.tags.length>0?(0,n.jsx)("ul",{className:"qi-cand-tags","aria-label":"Tags",children:e.tags.map(e=>(0,n.jsx)("li",{className:"qi-cand-tag",children:e},e))}):null]})}function cc({className:e,label:t,pressed:a,disabled:l,describedBy:i,onActivate:r}){return(0,n.jsx)("button",{type:"button",className:e,...void 0!==a?{"aria-pressed":a}:{},"aria-disabled":l||void 0,"aria-describedby":l?i:void 0,onClick:()=>{l||r()},children:t})}function cd({candidateId:e,state:t,onReview:l,disabled:i=!1,describedBy:r,pendingReview:s}){let o=null!=s,c=t=>o&&s.candidateId===e&&s.action===t,d=ca.has(t),u=(0,a.useId)(),p=d?u:r;return(0,n.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":"Review decision",children:[d?(0,n.jsx)("p",{id:u,className:"qi-cand-governance-note",role:"note",children:"This review decision is final — reopen to change it."}):null,(0,n.jsx)(cc,{className:"qi-btn qi-btn-approve",label:c("approve")?"Saving…":"Approve",pressed:"approved"===t,disabled:i||o||d,describedBy:p,onActivate:()=>{l(e,"approve")}}),(0,n.jsx)(cc,{className:"qi-btn qi-btn-reject",label:c("reject")?"Saving…":"Reject",pressed:"rejected"===t,disabled:i||o||d,describedBy:p,onActivate:()=>{l(e,"reject")}}),(0,n.jsx)(cc,{className:"qi-btn qi-btn-secondary",label:c("request-changes")?"Saving…":"Request changes",pressed:"changes-requested"===t,disabled:i||o||d,describedBy:p,onActivate:()=>{l(e,"request-changes")}}),d?(0,n.jsx)(cc,{className:"qi-btn qi-btn-secondary",label:c("reopen")?"Saving…":"Reopen",disabled:i||o,describedBy:i?r:void 0,onActivate:()=>{l(e,"reopen")}}):null]})}function cu({candidate:e,onReview:t,onStartEdit:l,actionsDisabled:i=!1,actionsDisabledReason:r,describedBy:s,editButtonRef:o,pendingReview:c}){let d=(0,a.useId)(),u=i&&void 0!==r?[s,d].filter(Boolean).join(" "):s;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"qi-cand-header",children:[(0,n.jsx)("div",{className:"qi-cand-title-wrap",children:(0,n.jsx)("h3",{className:"qi-cand-title",children:e.title})}),(0,n.jsxs)("div",{className:"qi-cand-status",children:[(0,n.jsxs)("div",{className:"qi-cand-badges",children:[(0,n.jsx)("span",{className:"qi-cand-risk",children:e.riskClass}),"open"!==e.reviewState?(0,n.jsx)(od,{state:e.reviewState}):null]}),(0,n.jsx)(ci,{candidate:e})]})]}),(0,n.jsxs)("div",{className:"qi-cand-accordion-stack",children:[(0,n.jsx)(cs,{candidate:e}),(0,n.jsx)(co,{candidate:e})]}),(0,n.jsxs)("div",{className:"qi-cand-actions-row",children:[i&&void 0!==r?(0,n.jsx)("p",{id:d,className:"qi-cand-action-note",role:"note",children:r}):null,(0,n.jsxs)("div",{className:"qi-cand-action-buttons",children:[void 0!==l?(0,n.jsx)("button",{ref:o,type:"button",className:"qi-btn qi-btn-secondary qi-cand-edit","aria-disabled":i||void 0,"aria-describedby":i?u:void 0,onClick:()=>{i||l()},children:"Edit"}):null,void 0!==t?(0,n.jsx)(cd,{candidateId:e.id,state:e.reviewState,onReview:t,disabled:i,describedBy:u,pendingReview:c}):null]})]})]})}function cp({candidate:e,onReview:t,onEdit:l,actionsDisabled:i=!1,actionsDisabledReason:r,describedBy:s,pendingReview:o}){let[c,d]=(0,a.useState)(!1),u=(0,a.useRef)(null),p=(0,a.useRef)(!1);(0,a.useEffect)(()=>{p.current&&!c&&u.current?.focus(),p.current=c},[c]);let m=async t=>{void 0!==l&&await l(e.id,t),d(!1)};return(0,n.jsx)("li",{className:c?"qi-cand-card qi-cand-card-editing":"qi-cand-card",children:c&&void 0!==l?(0,n.jsx)(cn,{candidate:e,onSave:m,onCancel:()=>{d(!1)}}):(0,n.jsx)(cu,{candidate:e,onReview:t,actionsDisabled:i,actionsDisabledReason:r,describedBy:s,pendingReview:o,editButtonRef:u,onStartEdit:void 0!==l?()=>{d(!0)}:void 0})})}function cm({candidates:e,onReview:t,onEdit:l,actionsDisabled:i=!1,actionsDisabledReason:r,pendingReview:s}){let[o,c]=(0,a.useState)(25),d=(0,a.useId)(),u=i&&void 0!==r;if(0===e.length)return(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No test cases"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"This run produced no generated test cases."})]});let p=[...e].sort((e,t)=>!!e.tags.includes("source:deterministic-baseline")-!!t.tags.includes("source:deterministic-baseline")).slice(0,o);return(0,n.jsxs)("div",{className:"qi-cand-pane",children:[u?(0,n.jsx)("p",{id:d,className:"qi-cand-governance-note",role:"note",children:r}):null,(0,n.jsx)("ul",{className:"qi-cand-cards","aria-label":"Test case list",children:p.map(e=>(0,n.jsx)(cp,{candidate:e,onReview:t,onEdit:l,actionsDisabled:i,actionsDisabledReason:r,describedBy:u?d:void 0,pendingReview:s},e.id))}),o<e.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-cand-more",onClick:()=>{c(e=>e+25)},children:["Show more test cases (",(e.length-o).toString()," remaining)"]}):null]})}function ch(e){return 0===e?"No drift — every test is current.":`${e.toString()} ${1===e?"test is":"tests are"} stale — source changed since this run.`}function cf(e){let t=e.regeneratedCount,n=e.preservedCount;return`Regenerated ${t.toString()} ${1===t?"test":"tests"} as a new run (${n.toString()} ${1===n?"test":"tests"} preserved).`}function cg({staleCount:e}){return 0===e?(0,n.jsxs)("p",{className:"qi-drift-fresh","data-testid":"qi-drift-fresh",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-drift-icon-ok",children:"✓"}),ch(0)]}):(0,n.jsxs)("p",{className:"qi-drift-stale","data-testid":"qi-drift-stale",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-drift-icon-warn",children:"⚠"}),ch(e)]})}function cv({runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:i=oa,regenerateImpl:r=ol}){let[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),u=null!==c,[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)(null),g=(0,a.useRef)(null),v=(0,a.useRef)(null),b=(0,a.useCallback)(()=>{u||(async()=>{d("check"),m(null),f(null);try{o(await i(e,t))}catch(e){m(ou(e))}finally{d(null)}})()},[u,i,e,t]),x=(0,a.useCallback)(()=>{u||(async()=>{d("regenerate"),m(null);try{let n=await r(e,t);document.activeElement===v.current&&g.current?.focus(),f(n),o(null),l?.(n)}catch(e){m(ou(e))}finally{d(null)}})()},[u,r,e,t,l]);return(0,n.jsxs)("section",{className:"qi-drift-panel","aria-label":"Drift detection",children:[(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==h?cf(h):null!==s?ch(s.staleCount):""}),(0,n.jsxs)("div",{className:"qi-drift-head",children:[(0,n.jsx)("h3",{className:"qi-col-subtitle",children:"Living tests"}),(0,n.jsx)("button",{type:"button",ref:g,className:"qi-btn qi-btn-secondary",onClick:b,"aria-disabled":u||void 0,"data-testid":"qi-drift-recheck",children:"check"===c?"Checking…":"Re-check drift"})]}),null!==p?(0,n.jsx)("p",{className:"lk-alert",role:"alert",children:p}):null,null!==s?(0,n.jsx)(cg,{staleCount:s.staleCount}):null,null!==s&&s.staleCount>0&&null===h?(0,n.jsx)("button",{type:"button",ref:v,className:"qi-btn qi-btn-approve",onClick:x,"aria-disabled":u||void 0,"data-testid":"qi-drift-regenerate",children:"regenerate"===c?"Regenerating…":`Regenerate ${s.staleCount.toString()} stale ${1===s.staleCount?"test":"tests"}`}):null,null!==h?(0,n.jsx)("p",{className:"qi-drift-regenerated","data-testid":"qi-drift-regenerated",children:cf(h)}):null]})}let cb={"traceability-csv":"csv","traceability-markdown":"markdown"},cx=[{id:"csv",label:"CSV",tms:!1},{id:"json",label:"JSON",tms:!1},{id:"spreadsheet-safe-csv",label:"Spreadsheet-safe CSV",tms:!1},{id:"markdown",label:"Markdown",tms:!1},{id:"plain-text",label:"Plain text",tms:!1},{id:"pdf",label:"PDF",tms:!1},{id:"zip-bundle",label:"ZIP bundle (all formats)",tms:!1},{id:"traceability-csv",label:"Traceability matrix (CSV)",tms:!1},{id:"traceability-markdown",label:"Traceability matrix (Markdown)",tms:!1},{id:"jira-issues",label:"Jira (preview)",tms:!0},{id:"qtest",label:"qTest (preview)",tms:!0},{id:"xray",label:"Xray (preview)",tms:!0},{id:"polarion",label:"Polarion (preview)",tms:!0},{id:"quality-center",label:"Quality Center (preview)",tms:!0}];function cy(e,t,n,a){let l=new Blob(["base64"===a?function(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(n):n],{type:t}),i=URL.createObjectURL(l),r=document.createElement("a");r.href=i,r.download=e,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>{URL.revokeObjectURL(i)},250)}function cw({runId:e,exportImpl:t=oi,traceabilityImpl:l=or}){let[i,r]=(0,a.useState)("csv"),[s,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),v=cx.find(e=>e.id===i),b=v?.tms??!1,x=(0,a.useCallback)(async()=>{let n=cb[i];if(void 0!==n){let t=await l(e,n);cy(t.filename,t.contentType,t.body),h(t.filename);return}let a=await t(e,i,{dryRun:b,approvedOnly:f});a.dryRun?p(`${a.candidateCount.toString()} test case${1===a.candidateCount?"":"s"} \xb7 ${a.byteLen.toString()} bytes
99
-
100
- ${a.preview}`):(cy(a.filename,a.contentType,a.body,a.encoding),h(a.filename))},[e,i,b,f,t,l]),y=(0,a.useCallback)(async()=>{o(!0),d(null),p(null),h(null);try{await x()}catch(e){d(ou(e))}finally{o(!1)}},[x]);return(0,n.jsxs)("div",{className:"qi-export","data-testid":"qi-export-bar",children:[(0,n.jsxs)("div",{className:"qi-export-head",children:[(0,n.jsxs)("div",{className:"qi-export-copy",children:[(0,n.jsx)("p",{className:"qi-export-title",children:"Export"}),b?null:(0,n.jsx)("p",{className:"qi-export-hint",role:"note","data-testid":"qi-export-scope-notice",children:f?"Exports approved test cases only.":"Exports all test cases, including unapproved."})]}),b?null:(0,n.jsxs)("label",{className:"qi-export-approved-label",children:[(0,n.jsx)("input",{type:"checkbox",className:"qi-checkbox",checked:f,disabled:s,onChange:e=>{g(e.target.checked)},"data-testid":"qi-export-approved-only"}),(0,n.jsx)("span",{children:"Approved only"})]})]}),(0,n.jsxs)("div",{className:"qi-export-controls",children:[(0,n.jsxs)("div",{className:"qi-field qi-export-format",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Format"}),(0,n.jsx)(tz,{triggerClassName:"qi-select",value:i,ariaLabel:"Export",disabled:s,ariaDescribedBy:b?"qi-export-connector-hint":void 0,menuTitle:"Export",sections:[{options:cx.map(e=>({value:e.id,label:e.label}))}],onValueChange:e=>{r(e),p(null),d(null),h(null)}})]}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-primary qi-export-action",disabled:s,onClick:()=>{y()},children:s?"Exporting…":b?"Preview":"Download"})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==m?`Downloaded ${m}`:null!==u?"Export preview ready below.":""}),b?(0,n.jsx)("p",{id:"qi-export-connector-hint",className:"qi-export-hint",role:"note","data-testid":"qi-export-connector-hint",children:v?.id==="quality-center"?"Quality Center is preview-only. Configure a connector to enable live export.":"External target — preview only. Configure a connector to enable live export."}):null,null!==m?(0,n.jsx)("p",{className:"qi-export-success","data-testid":"qi-export-success",children:`Downloaded ${m}`}):null,null!==u?(0,n.jsx)("pre",{className:"qi-export-preview",role:"region","aria-label":"Export preview",tabIndex:0,"data-testid":"qi-export-preview",children:u}):null,null!==c?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-export-error",children:c}):null]})}let cj="keiko.qi.reviewerLabel",ck="Set a reviewer label to review or edit candidates.";function cN({detail:e}){return(0,n.jsxs)("dl",{className:"qi-run-summary","aria-label":"Run summary",children:[(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Status"}),(0,n.jsx)("dd",{children:(0,n.jsx)(og,{status:e.status})})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Test cases"}),(0,n.jsx)("dd",{children:e.totals.candidates.toString()})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Findings"}),(0,n.jsx)("dd",{children:e.totals.findings.toString()})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Quality"}),(0,n.jsx)("dd",{children:(0,n.jsx)(ox,{score:e.qualityScore})})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Review"}),(0,n.jsx)("dd",{className:"qi-run-summary-review",children:oo[e.reviewState]})]}),(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Requested"}),(0,n.jsx)("dd",{children:op(e.requestedAt)})]}),null!==e.completedAt?(0,n.jsxs)("div",{className:"qi-run-summary-item",children:[(0,n.jsx)("dt",{children:"Completed"}),(0,n.jsx)("dd",{children:op(e.completedAt)})]}):null]})}let cS={"logic-defect":"Logic defect","faithfulness-defect":"Faithfulness defect","semantic-defect":"Semantic defect","mutation-defect":"Mutation defect","policy-violation":"Policy violation","manual-rejection":"Manual rejection","coverage-gap":"Coverage gap","test-quality":"Test quality"};function cC({detail:e}){let[t,l]=(0,a.useState)(20),i=e.findingRefs.length;if(0===i)return null;let r=e.findingRefs.slice(0,t);return(0,n.jsxs)("section",{className:"qi-run-findings","aria-label":"Findings",children:[(0,n.jsxs)("h3",{className:"qi-col-subtitle",children:["Findings",(0,n.jsx)("span",{className:"qi-col-count",children:i.toString()})]}),(0,n.jsx)("ul",{className:"qi-finding-list","aria-label":"Findings list",children:r.map(e=>(0,n.jsxs)("li",{className:"qi-finding-item",children:[(0,n.jsxs)("div",{className:"qi-finding-header",children:[(0,n.jsx)("span",{className:"qi-finding-kind",children:cS[e.kind]??e.kind}),(0,n.jsx)(ob,{severity:e.severity})]}),(0,n.jsx)("p",{className:"qi-finding-summary",children:e.summaryRedacted})]},e.id))}),t<i?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{l(e=>e+20)},children:["Show more findings (",(i-t).toString()," remaining)"]}):null]})}let cI={covered:"Covered","weakly-covered":"Weakly covered",uncovered:"Uncovered"},cE={covered:"qi-cov-covered","weakly-covered":"qi-cov-weak",uncovered:"qi-cov-uncovered"},cR={uncovered:0,"weakly-covered":1,covered:2};function c$({detail:e}){let[t,l]=(0,a.useState)(20),{total:i,coveredCount:r,gaps:s}=(0,a.useMemo)(()=>{let t=e.coverageByAtom;return{total:t.length,coveredCount:t.filter(e=>"covered"===e.status).length,gaps:t.filter(e=>"covered"!==e.status).sort((e,t)=>cR[e.status]-cR[t.status])}},[e.coverageByAtom]);if(0===i)return null;let o=s.slice(0,t);return(0,n.jsxs)("section",{className:"qi-coverage-panel","aria-label":"Coverage",children:[(0,n.jsxs)("h3",{className:"qi-col-subtitle",children:["Coverage",(0,n.jsxs)("span",{className:"qi-badge qi-badge-default","aria-label":`Coverage: ${e.coveragePercentage.toFixed(0)} percent, ${r.toString()} of ${i.toString()} requirements covered`,"data-testid":"qi-coverage-pct",children:[e.coveragePercentage.toFixed(0),"%"]})]}),(0,n.jsx)("p",{className:"qi-coverage-summary","data-testid":"qi-coverage-summary",children:`${r.toString()} of ${i.toString()} requirements covered \xb7 ${s.length.toString()} gap${1===s.length?"":"s"}`}),s.length>0?(0,n.jsxs)("section",{className:"qi-coverage-gaps","aria-label":"Gap radar",children:[(0,n.jsx)("h4",{className:"qi-col-subtitle",children:`Gap radar (${s.length.toString()})`}),(0,n.jsx)("ul",{className:"qi-coverage-gap-list","aria-label":"Uncovered and weakly covered atoms",children:o.map(e=>{let t=cI[e.status],a=cE[e.status],l=e.requirementExcerptRedacted;return(0,n.jsxs)("li",{className:"qi-coverage-gap-item","aria-label":void 0===l?`Atom ${e.atomId}: ${t}`:`Requirement "${l}" (atom ${e.atomId}): ${t}`,children:[(0,n.jsxs)("span",{className:"qi-coverage-gap-req",children:[void 0===l?null:(0,n.jsx)("span",{className:"qi-coverage-gap-text","data-testid":"qi-coverage-gap-text",children:l}),(0,n.jsx)("span",{className:"qi-coverage-atom-id qi-monospace",children:e.atomId})]}),(0,n.jsx)("span",{className:`qi-badge ${a}`,"aria-hidden":"true",children:t}),(0,n.jsx)("span",{className:"qi-sr-only",children:t})]},e.atomId)})}),t<s.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{l(e=>e+20)},children:["Show more gaps (",(s.length-t).toString()," remaining)"]}):null]}):null]})}function cA({detail:e}){let t=(0,a.useId)();return e.drift.reCheckSupported?(0,n.jsxs)("section",{className:"qi-drift-panel","aria-label":"Drift detection",children:[(0,n.jsxs)("div",{className:"qi-drift-head",children:[(0,n.jsx)("h3",{className:"qi-col-subtitle",children:"Living tests"}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary","aria-disabled":"true","aria-describedby":t,"data-testid":"qi-drift-recheck-unavailable",onClick:e=>{e.preventDefault()},children:"Re-check drift"})]}),(0,n.jsx)("p",{id:t,className:"qi-drift-note","data-testid":"qi-drift-unavailable",children:"Drift fingerprints are recorded for this run, but this card has no current source handle. Reopen it from the connected source or start a new run from the current source."})]}):null}function cT({runId:e,connectedSources:t,onRegenerated:l,fetchDetailImpl:i=s8,reviewImpl:r=ot,editImpl:s=on,reCheckImpl:o,regenerateImpl:c}){let[d,u]=(0,a.useState)(null),[p,m]=(0,a.useState)(!0),[h,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(null),[y,w]=(0,a.useState)(""),[j,k]=(0,a.useState)(!1),N=(0,a.useId)(),S=(0,a.useId)(),[C,I]=(0,a.useState)(""),E=(0,a.useRef)(0),R=(0,a.useRef)(0),$=(0,a.useCallback)(async()=>{let t=R.current+1;R.current=t,m(!0),f(null);try{let n=await i(e);R.current===t&&u(n)}catch(e){R.current===t&&f(ou(e))}finally{R.current===t&&m(!1)}},[i,e]);(0,a.useEffect)(()=>{$()},[$]),(0,a.useEffect)(()=>{w(function(){try{return window.localStorage.getItem(cj)??""}catch{return""}}()),k(!0)},[]),(0,a.useEffect)(()=>{if(j)try{window.localStorage.setItem(cj,y)}catch{}},[y,j]);let A=y.trim(),T=A.length>0,L=(0,a.useCallback)((t,n)=>{T&&null===b&&(x({candidateId:t,action:n}),(async()=>{v(null);try{await r(e,n,t,A),await $();let a=oo["approve"===n?"approved":"reject"===n?"rejected":"request-changes"===n?"changes-requested":"open"],l=d?.candidates.find(e=>e.id===t)?.title??t;E.current+=1,I(`Candidate "${l}" marked ${a}. (${E.current.toString()})`)}catch(e){v(ou(e))}finally{x(null)}})())},[T,b,r,e,A,$,d]),P=(0,a.useCallback)(async(t,n)=>{if(!T)throw Error(ck);await s(e,t,n,A),await $()},[s,T,e,A,$]);return(0,n.jsxs)("div",{className:"qi-run-card","data-testid":"qi-run-card",children:[(0,n.jsx)("header",{className:"qi-run-card-head",children:(0,n.jsx)("span",{className:"qi-run-id qi-monospace",title:e,role:"heading","aria-level":2,"aria-label":`Quality Intelligence run ${e}`,children:e})}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:p?"Loading run…":null===h&&null!==d?`Run loaded: ${d.totals.candidates.toString()} test case${1===d.totals.candidates?"":"s"}.`:""}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"qi-review-announce",children:C}),(0,n.jsx)("div",{className:"qi-run-card-body","aria-busy":p,children:p&&null===d?(0,n.jsx)(oN,{}):null!==h?(0,n.jsx)(oS,{message:h,onRetry:()=>void $()}):null===d?(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:"Run not found."})}):(0,n.jsxs)(n.Fragment,{children:[null!==g?(0,n.jsxs)("div",{className:"lk-alert qi-action-error",role:"alert","data-testid":"qi-action-error",children:[g,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{v(null)},children:"Dismiss"})]}):null,(0,n.jsxs)("section",{className:"qi-run-governance","aria-label":"Review governance",children:[(0,n.jsxs)("label",{className:"qi-field",htmlFor:`qi-reviewer-label-${e}`,children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Reviewer label"}),(0,n.jsx)("input",{id:`qi-reviewer-label-${e}`,className:"qi-input qi-run-governance-input",value:y,placeholder:"Required for review and edit actions","aria-invalid":!T,"aria-describedby":T?N:`${N} ${S}`,onChange:e=>{w(e.target.value)}})]}),(0,n.jsx)("p",{id:N,className:"qi-run-governance-help",children:"Used for QI review and edit audit entries."}),(0,n.jsx)("p",{id:S,className:"qi-run-governance-warning",role:"status","aria-live":"polite",children:T?"":ck})]}),(0,n.jsx)(cN,{detail:d}),(0,n.jsx)(cC,{detail:d}),(0,n.jsx)(c$,{detail:d}),void 0!==t&&t.length>0?(0,n.jsx)(cv,{runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:o,regenerateImpl:c}):(0,n.jsx)(cA,{detail:d}),(0,n.jsxs)("section",{className:"qi-run-cases","aria-label":"Generated test cases",children:[(0,n.jsxs)("div",{className:"qi-run-cases-head",children:[(0,n.jsxs)("h3",{className:"qi-col-subtitle",children:["Test cases",(0,n.jsx)("span",{className:"qi-col-count",children:d.candidates.length.toString()})]}),d.candidates.length>0?(0,n.jsx)(cw,{runId:e}):null]}),(0,n.jsx)(cm,{candidates:d.candidates,onReview:L,pendingReview:b,onEdit:P,actionsDisabled:!T,actionsDisabledReason:ck})]})]})})]})}let cL={inactive:{label:"Inactive",ariaDescription:"No recent activity for this relationship.",iconShape:"hollow-circle",textColor:"var(--fg-muted)",bgColor:"var(--inset)",animated:!1},queued:{label:"Queued",ariaDescription:"A workflow run referencing this relationship is queued.",iconShape:"clock",textColor:"var(--fg-muted)",bgColor:"var(--inset)",animated:!1},active:{label:"Active",ariaDescription:"A model call referencing this relationship is in progress.",iconShape:"filled-circle",textColor:"var(--accent)",bgColor:"var(--accent-dim)",borderColor:"var(--accent-line)",animated:!1},processing:{label:"Processing",ariaDescription:"A tool or command referencing this relationship is executing.",iconShape:"spinning-circle",textColor:"var(--accent)",bgColor:"var(--accent-dim)",borderColor:"var(--accent-line)",animated:!0},completed:{label:"Completed",ariaDescription:"The most recent run referencing this relationship completed successfully.",iconShape:"check",textColor:"var(--accent)",bgColor:"var(--accent-dim)",animated:!1},failed:{label:"Failed",ariaDescription:"The most recent run referencing this relationship failed.",iconShape:"triangle-exclamation",textColor:"var(--danger)",bgColor:"color-mix(in oklch, var(--danger) 12%, var(--card))",animated:!1},blocked:{label:"Blocked",ariaDescription:"The validator denied a recent proposal referencing this relationship; see the inspector for the reason.",iconShape:"filled-square",textColor:"var(--warn)",bgColor:"color-mix(in oklch, var(--warn) 12%, var(--card))",animated:!1},degraded:{label:"Degraded",ariaDescription:"The health check flagged at least one endpoint of this relationship as not currently live.",iconShape:"broken-line",textColor:"var(--warn)",bgColor:"color-mix(in oklch, var(--warn) 8%, var(--card))",animated:!1},"high-throughput":{label:"High throughput",ariaDescription:"More than fifty events referenced this relationship in the last sixty seconds.",iconShape:"stacked-lines",textColor:"var(--accent)",bgColor:"var(--accent-dim)",animated:!1}};function cP({shape:e,color:t,animated:a,highContrast:l}){let i=["rb-edge-badge-icon",a?"rb-edge-badge-icon--processing":"",l?"rb-edge-badge-icon--high-contrast":""].filter(e=>e.length>0).join(" "),r=l?2:1.5,s={width:12,height:12,viewBox:"0 0 12 12","aria-hidden":!0,fill:"currentColor",className:i,style:{color:t}};switch(e){case"hollow-circle":return(0,n.jsx)("svg",{...s,children:(0,n.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:r})});case"clock":return(0,n.jsxs)("svg",{...s,children:[(0,n.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:r}),(0,n.jsx)("path",{d:"M6 3v3l2 1",stroke:"currentColor",strokeWidth:r,strokeLinecap:"round",fill:"none"})]});case"filled-circle":return(0,n.jsx)("svg",{...s,children:(0,n.jsx)("circle",{cx:"6",cy:"6",r:"5"})});case"spinning-circle":return(0,n.jsx)("svg",{...s,children:(0,n.jsx)("circle",{cx:"6",cy:"6",r:"4.5",fill:"none",stroke:"currentColor",strokeWidth:r,strokeDasharray:"8 4"})});case"check":return(0,n.jsx)("svg",{...s,children:(0,n.jsx)("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:l?2.2:1.8,strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"triangle-exclamation":return(0,n.jsxs)("svg",{...s,children:[(0,n.jsx)("path",{d:"M6 1 L11 10 L1 10 Z",fill:"currentColor"}),(0,n.jsx)("path",{d:"M6 5v2.5",stroke:"var(--card)",strokeWidth:r,strokeLinecap:"round",fill:"none"}),(0,n.jsx)("circle",{cx:"6",cy:"9",r:"0.7",fill:"var(--card)"})]});case"filled-square":return(0,n.jsx)("svg",{...s,children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"9",height:"9",rx:"1.5"})});case"broken-line":return(0,n.jsx)("svg",{...s,children:(0,n.jsx)("path",{d:"M1 6h2.5l1.5-2 2 4 1.5-2H11",stroke:"currentColor",strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"stacked-lines":return(0,n.jsxs)("svg",{...s,children:[(0,n.jsx)("rect",{x:"2",y:"2.5",width:"8",height:"1.5",rx:"0.75"}),(0,n.jsx)("rect",{x:"2",y:"5.25",width:"8",height:"1.5",rx:"0.75"}),(0,n.jsx)("rect",{x:"2",y:"8",width:"8",height:"1.5",rx:"0.75"})]})}}function cM({state:e}){let t={width:10,height:10,viewBox:"0 0 10 10","aria-hidden":!0,fill:"currentColor"};switch(e){case"draft":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("circle",{cx:"5",cy:"5",r:"4",fill:"none",stroke:"currentColor",strokeWidth:"1.5"})});case"active":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("circle",{cx:"5",cy:"5",r:"4.5"})});case"archived":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1"})});case"superseded":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("path",{d:"M2 5h6M6 3l2 2-2 2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})});case"revoked":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("path",{d:"M2 2l6 6M8 2L2 8",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",fill:"none"})});case"blocked":return(0,n.jsxs)("svg",{...t,children:[(0,n.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1"}),(0,n.jsx)("path",{d:"M5 3v3",stroke:"var(--card)",strokeWidth:"1.5",strokeLinecap:"round",fill:"none"}),(0,n.jsx)("circle",{cx:"5",cy:"7.5",r:"0.6",fill:"var(--card)"})]});case"stale":return(0,n.jsx)("svg",{...t,children:(0,n.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1",fill:"none",stroke:"currentColor",strokeWidth:"1.5"})})}}function cD({type:e,lifecycle:t,activity:l,throughputCount:i,animateOverride:r=!0,highContrast:s,onClick:o,className:c=""}){let[d,u]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(void 0!==s)return;let e=window.matchMedia("(prefers-contrast: more)"),t=e=>{u(e)};t(e.matches);let n=e=>{t(e.matches)};return e.addEventListener("change",n),()=>{e.removeEventListener("change",n)}},[s]);let p=cL[l]??cL.inactive,m=ar[e],h=s??d,f="high-throughput"===l&&void 0!==i?`${p.label} (${String(i)})`:p.label,g=`${m.displayName} — ${p.ariaDescription}`,v=p.animated&&r,b=h?{color:p.textColor,background:"var(--card)",border:`1px solid ${p.textColor}`}:{color:p.textColor,background:p.bgColor,border:void 0!==p.borderColor?`1px solid ${p.borderColor}`:void 0};return(0,n.jsx)("span",{role:"status","aria-live":"polite","aria-atomic":"true",className:`rb-edge-badge ${c}`.trim(),"data-activity-state":l,"data-high-contrast":h?"true":void 0,children:void 0!==o?(0,n.jsxs)("button",{type:"button",className:"rb-edge-badge-btn",style:b,"aria-label":g,onClick:o,children:[(0,n.jsx)("span",{"aria-hidden":"true",children:(0,n.jsx)(cP,{shape:p.iconShape,color:p.textColor,animated:v,highContrast:h})}),(0,n.jsx)("span",{className:"visually-hidden",children:p.ariaDescription}),(0,n.jsx)("span",{"aria-hidden":"true",className:"rb-edge-badge-label",children:f}),(0,n.jsx)("span",{className:"rb-edge-badge-type",children:m.displayName}),(0,n.jsx)(cM,{state:t})]}):(0,n.jsxs)("span",{className:"rb-edge-badge-static",style:b,"aria-label":g,children:[(0,n.jsx)("span",{"aria-hidden":"true",children:(0,n.jsx)(cP,{shape:p.iconShape,color:p.textColor,animated:v,highContrast:h})}),(0,n.jsx)("span",{className:"visually-hidden",children:p.ariaDescription}),(0,n.jsx)("span",{"aria-hidden":"true",className:"rb-edge-badge-label",children:f}),(0,n.jsx)("span",{className:"rb-edge-badge-type",children:m.displayName}),(0,n.jsx)(cM,{state:t})]})})}let cq="keiko.relationships.density",cF={minimal:5,standard:25,dense:512};function cO(){try{let e=window.localStorage.getItem(cq);if("minimal"===e||"standard"===e||"dense"===e)return e}catch{}return"minimal"}function cz(e,t){return void 0===e||0===e.length?[]:e.split(",").map(e=>e.trim()).filter(e=>t.includes(e))}function cK(e){return{types:cz(e.relType,al),lifecycles:cz(e.relLifecycle,ai),activities:cz(e.relActivity,["inactive","queued","active","processing","completed","failed","blocked","degraded","high-throughput"]),srcKinds:cz(e.relSrcKind,an),tgtKinds:cz(e.relTgtKind,an)}}let cB={"high-throughput":0,processing:1,active:2,blocked:3,failed:4,degraded:5,queued:6,completed:7,inactive:8};function c_(e,t,n){return n.get(e)??function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive"}}(t)}function cU({filters:e,selectedId:t,onSelect:l,onFilterChange:i,activityMap:r=new Map,throughputMap:s=new Map,animateBadges:o=!0,highContrast:c=!1}){let[d,u]=(0,a.useState)(()=>{let t=e.relDensity;return"minimal"===t||"standard"===t||"dense"===t?t:cO()}),[p,m]=(0,a.useState)(!1),[h,f]=(0,a.useState)([]),[g,v]=(0,a.useState)(!1),[b,x]=(0,a.useState)(null),[y,w]=(0,a.useState)(!1),j=(0,a.useRef)(null),k=(0,a.useRef)(null),[N,S]=(0,a.useState)(e.relType??""),C=(0,a.useRef)(null),I=(0,a.useCallback)(e=>{u(e),i({relDensity:e});try{window.localStorage.setItem(cq,e)}catch{}},[i]);(0,a.useEffect)(()=>{let t=e.relDensity;"minimal"===t||"standard"===t||"dense"===t?u(t):u(cO())},[e.relDensity]),(0,a.useEffect)(()=>{S(e.relType??"")},[e.relType]);let E=(0,a.useCallback)(async()=>{x(null),v(!0);try{let t=cK(e),n=1===t.lifecycles.length?t.lifecycles[0]:"active",a=1===t.types.length?t.types[0]:void 0,l=1===t.srcKinds.length?t.srcKinds[0]:void 0,i=1===t.tgtKinds.length?t.tgtKinds[0]:void 0,r=await ah({lifecycle:n,type:a,sourceKind:l,targetKind:i,limit:cF[d]});f(r.entries),w(r.truncated)}catch(e){x(e instanceof ac?e.message:ao)}finally{v(!1)}},[e,d]);(0,a.useEffect)(()=>{E()},[E]),(0,a.useEffect)(()=>{let e=j.current;if(null!==e)return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t);function t(e){if(!("u"<typeof document)&&null!==document.querySelector('[role="dialog"][aria-modal="true"]'))return;let t=e.target;t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t instanceof HTMLElement&&t.isContentEditable||("f"===e.key||"F"===e.key?(e.preventDefault(),m(e=>!e)):"Escape"===e.key?m(!1):"/"===e.key&&(e.preventDefault(),k.current?.focus()))}},[]);let R=(0,a.useCallback)(e=>{let t=e.target.value;S(t),null!==C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{i({relType:t.length>0?t:void 0})},250)},[i]),$=(0,a.useMemo)(()=>{let t=cK(e),n=(e.relType??"").split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),a=0===n.length?h:h.filter(e=>n.some(t=>e.type.toLowerCase().includes(t)));return(0===t.activities.length?a:a.filter(e=>t.activities.includes(c_(e.id,e.lifecycle,r)))).slice(0,cF[d])},[r,d,e,h]),A=$.slice(0,25),T=$.slice(25),L=T.length,P=L>0?function(e,t){let n=new Map;for(let a of e){let e=c_(a.id,a.lifecycle,t);n.set(e,(n.get(e)??0)+1)}return Array.from(n.entries()).sort((e,t)=>t[1]!==e[1]?t[1]-e[1]:(cB[e[0]]??Number.MAX_SAFE_INTEGER)-(cB[t[0]]??Number.MAX_SAFE_INTEGER)).map(([e,t])=>{let n;return n=1===t?"relationship":"relationships","high-throughput"===e?`${t} high-throughput ${n}`:`${t} ${e} ${n}`}).join(", ")}(T,r):"",M=y?`Showing first ${String($.length)} relationships — more available.`:`Showing ${String($.length)} relationship${1!==$.length?"s":""}.`,D=(e.relType??"").trim().length>0||(e.relActivity??"").trim().length>0||(e.relSrcKind??"").trim().length>0||(e.relTgtKind??"").trim().length>0||(e.relLifecycle??"").trim().length>0&&"active"!==e.relLifecycle,q=cz(e.relLifecycle,ai),F=1===q.length?q[0]??"active":"active";return(0,n.jsxs)("div",{ref:j,className:"tw-pad","data-testid":"relationship-list-panel","data-relationship-focus":p?"true":void 0,children:[(0,n.jsxs)("div",{role:"group","aria-label":"Relationship density",style:{display:"flex",flexWrap:"wrap",gap:"var(--space-2)",marginBottom:8},children:[["minimal","standard","dense"].map(e=>(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-pressed":d===e,onClick:()=>I(e),style:{textTransform:"capitalize",minWidth:24,minHeight:24},children:e},e)),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-pressed":p,onClick:()=>m(e=>!e),title:"Toggle focus mode (F)","aria-label":`Focus mode: ${p?"on":"off"}`,style:{minWidth:24,minHeight:24},children:"Focus"})]}),(0,n.jsxs)("div",{style:{marginBottom:8},children:[(0,n.jsx)("label",{htmlFor:"rel-type-filter",className:"rb-row-k",style:{display:"block",marginBottom:2,fontSize:11,fontWeight:600},children:"Filter by type (press / to focus)"}),(0,n.jsx)("input",{id:"rel-type-filter",ref:k,type:"text",list:"rel-type-filter-options",value:N,onChange:R,placeholder:"e.g. reads-context","aria-label":"Filter relationships by type",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:9,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:13}}),(0,n.jsx)("datalist",{id:"rel-type-filter-options",children:al.map(e=>(0,n.jsx)("option",{value:e},e))})]}),(0,n.jsxs)("div",{style:{marginBottom:8},children:[(0,n.jsx)("label",{htmlFor:"rel-lifecycle-filter",className:"rb-row-k",style:{display:"block",marginBottom:2,fontSize:11,fontWeight:600},children:"Lifecycle"}),(0,n.jsx)("select",{id:"rel-lifecycle-filter",value:F,onChange:e=>i({relLifecycle:e.target.value}),"aria-label":"Filter relationships by lifecycle",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:9,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:13},children:ai.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsx)("div",{"aria-live":"polite","aria-atomic":"true",className:"visually-hidden",children:M}),y&&(0,n.jsx)("div",{"data-testid":"list-truncation-note",style:{fontSize:11,color:"var(--fg-muted)",marginBottom:6},children:M}),null!==b&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:b}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void E(),children:"Retry"})]}),g&&0===h.length&&(0,n.jsx)("div",{role:"status",className:"insp-empty",children:"Loading…"}),(!g||h.length>0)&&null===b&&0===$.length&&(0,n.jsx)("div",{className:"insp-empty","data-testid":"list-empty",children:D?"No relationships match the current filter.":'No active relationships yet. Create one with "+ New relationship", or connect a source — connections appear here automatically.'}),$.length>0&&(0,n.jsxs)("div",{role:"list","aria-label":"Relationships","aria-busy":g||void 0,style:{display:"flex",flexDirection:"column",gap:"var(--space-1)",opacity:g?.6:1,transition:"opacity 0.15s ease"},children:[A.map(e=>{let a=e.id===t,i=c_(e.id,e.lifecycle,r),d=p&&a,u=p&&!a;return(0,n.jsx)("div",{role:"listitem",style:{opacity:u?.4:1},children:(0,n.jsxs)("button",{type:"button","aria-pressed":a,"aria-label":`${e.type} relationship from ${e.source.kind} ${e.source.id} to ${e.target.kind} ${e.target.id}, lifecycle: ${e.lifecycle}`,title:`${e.source.id} → ${e.target.id}`,onClick:()=>l(e.id),onKeyDown:t=>{var n;return n=e.id,void(("Enter"===t.key||" "===t.key)&&(t.preventDefault(),l(n)))},"data-incident":d?"true":void 0,className:"rel-row",children:[(0,n.jsx)(cD,{type:e.type,lifecycle:e.lifecycle,activity:i,throughputCount:s.get(e.id),animateOverride:o,highContrast:c}),(0,n.jsxs)("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column"},children:[(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--fg)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.source.kind," → ",e.target.kind]}),(0,n.jsx)("span",{style:{fontSize:10.5,color:"var(--fg-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.summary??`${e.source.id} → ${e.target.id}`})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--fg-muted)",whiteSpace:"nowrap"},children:e.lifecycle})]})},e.id)}),L>0&&(0,n.jsxs)("div",{role:"listitem","aria-live":"polite",style:{fontSize:12,color:"var(--fg-muted)",padding:"4px 6px"},"data-testid":"animation-cap-aggregate",children:["+",String(L)," more: ",P]})]})]})}function cW(){return(0,n.jsx)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)",borderLeft:"2px solid var(--warn)",paddingLeft:8},children:"The walk hit a bound before the graph was fully traversed; more objects may be affected than shown."})}function cV({title:e,help:t,report:a,onSelectRelationship:l}){if(null===a)return(0,n.jsxs)("section",{style:{marginBottom:12},children:[(0,n.jsx)("div",{className:"rb-section-label",role:"heading","aria-level":4,children:e}),(0,n.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)",margin:0},children:"Loading…"})]});let i=a.endpoints.slice(1),r=a.relationships,s=i.slice(0,50),o=r.slice(0,50);return(0,n.jsxs)("section",{style:{marginBottom:12},"aria-label":e,children:[(0,n.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":4,children:[e,(0,n.jsx)("span",{className:"rb-count","aria-hidden":"true",children:i.length})]}),(0,n.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:t}),0===i.length?(0,n.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)",margin:0},children:"No further objects are affected in this direction."}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:s.map(e=>(0,n.jsx)("li",{className:"rb-row",style:{fontSize:12},children:(0,n.jsx)("span",{className:"mono",children:`${e.kind}: ${e.id}`})},`${e.kind}:${e.id}`))}),i.length>s.length&&(0,n.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)"},children:["Showing the first ",String(50)," of ",String(i.length)," ","objects."]}),r.length>0&&(0,n.jsxs)("details",{style:{marginTop:6},children:[(0,n.jsxs)("summary",{style:{fontSize:11,color:"var(--fg-muted)",cursor:"pointer"},children:[String(r.length)," relationship",1===r.length?"":"s"," on the path"]}),(0,n.jsx)("ul",{style:{listStyle:"none",margin:"4px 0 0",padding:0},children:o.map(e=>(0,n.jsx)("li",{style:{marginBottom:2},children:(0,n.jsxs)("button",{type:"button",className:"arun-btn ghost",onClick:()=>l(e.id),"aria-label":`Inspect ${e.type} relationship from ${e.source.kind} ${e.source.id} to ${e.target.kind} ${e.target.id}`,style:{display:"flex",width:"100%",gap:"var(--space-3)",alignItems:"center",textAlign:"left",fontSize:12},children:[(0,n.jsx)("span",{className:"mono",children:e.type}),(0,n.jsxs)("span",{style:{color:"var(--fg-muted)"},children:[e.source.id," → ",e.target.id]})]})},e.id))})]})]}),a.truncated&&(0,n.jsx)(cW,{})]})}function cH({outgoing:e,incoming:t,onSelectRelationship:a}){return(0,n.jsxs)("div",{style:{marginTop:8,padding:"8px 10px",border:"1px solid var(--line)",borderRadius:8,background:"var(--inset)"},"aria-label":"Bounded impact analysis",children:[(0,n.jsx)(cV,{title:"Downstream impact",help:"Objects this relationship's target leads to. Deleting or revoking here may affect them.",report:e,onSelectRelationship:a}),(0,n.jsx)(cV,{title:"Upstream impact",help:"Objects that depend on this relationship's source.",report:t,onSelectRelationship:a})]})}let cY={draft:{bg:"var(--inset)",fg:"var(--fg-muted)"},active:{bg:"var(--accent-dim)",fg:"var(--accent)"},archived:{bg:"var(--inset)",fg:"var(--fg-dim)"},superseded:{bg:"var(--inset)",fg:"var(--fg-dim)"},revoked:{bg:"color-mix(in oklch, var(--danger) 14%, var(--card))",fg:"var(--danger)"},blocked:{bg:"color-mix(in oklch, var(--warn) 12%, var(--card))",fg:"var(--warn)"},stale:{bg:"var(--inset)",fg:"var(--fg-faint)"}},cG={draft:"Proposed but not yet validated or awaiting an upstream gate.",active:"Validated and committed. Both endpoints are currently live.",archived:"Preserved for audit but no longer participates in queries by default.",superseded:"Replaced by a newer relationship of the same type.",revoked:"Rejected after proposal or retracted after acceptance. Terminal state.",blocked:"Cannot transition to active because the validator returned a denial reason.",stale:"At least one endpoint is tombstoned, retired, or unavailable."};function cJ({lines:e=3}){return(0,n.jsx)("div",{className:"rb-rows","aria-hidden":"true",children:Array.from({length:e},(e,t)=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",style:{background:"var(--inset)",borderRadius:3,width:"40%",display:"block",height:12}}),(0,n.jsx)("span",{className:"rb-row-v",style:{background:"var(--inset)",borderRadius:3,width:"55%",display:"block",height:12}})]},t))})}function cX({children:e,style:t}){return(0,n.jsx)("div",{className:"rb-section-label",role:"heading","aria-level":3,style:t,children:e})}function cQ({rel:e}){let t=ar[e.type],a=`${e.source.kind} ${e.type} ${e.target.kind}`;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"insp-top",children:[(0,n.jsx)("span",{className:"chip",style:{fontSize:11},children:e.type}),(0,n.jsx)("span",{className:"insp-title",children:a})]}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Semantics"}),(0,n.jsx)("span",{className:"rb-row-v",children:t.semantics})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Cardinality"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:t.cardinality})]})]})]})}function cZ({label:e,kind:t,id:a}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(cX,{children:[e," endpoint"]}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Kind"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:t})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Reference"}),(0,n.jsx)("span",{className:"rb-row-v mono","aria-label":`Reference id: ${a}`,children:a})]})]})]})}function c0({lifecycle:e}){let t=`lifecycle-desc-${e}`,a=cY[e]??cY.draft;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{children:"Lifecycle status"}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"State"}),(0,n.jsx)("span",{className:"rb-row-v",children:(0,n.jsx)("span",{className:"chip",style:{background:a.bg,color:a.fg},"aria-describedby":t,children:e})})]}),(0,n.jsx)("div",{className:"rb-row",children:(0,n.jsx)("span",{id:t,className:"rb-row-v",style:{color:"var(--fg-muted)",fontSize:12},children:cG[e]})})]})]})}function c1({type:e,lifecycle:t,activity:a,throughputCount:l,animateBadges:i,highContrast:r,transitions:s,densityMode:o}){let c=s.slice(0,"minimal"===o?3:5);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{children:"Activity"}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Current state"}),(0,n.jsx)("span",{className:"rb-row-v",children:(0,n.jsx)(cD,{type:e,lifecycle:t,activity:a,throughputCount:l,animateOverride:i,highContrast:r})})]}),c.length>0&&(0,n.jsxs)("div",{className:"rb-row",style:{flexDirection:"column",gap:"var(--space-2)",alignItems:"flex-start"},children:[(0,n.jsx)("span",{className:"rb-row-k",style:{marginBottom:4},children:"Recent transitions"}),c.map((e,t)=>(0,n.jsxs)("div",{style:{fontSize:12,color:"var(--fg-muted)",display:"flex",gap:"var(--space-4)"},children:[(0,n.jsxs)("span",{className:"mono",children:[e.from," → ",e.to]}),(0,n.jsx)("time",{dateTime:new Date(e.occurredAt).toISOString(),style:{color:"var(--fg-faint)"},children:new Date(e.occurredAt).toLocaleString()})]},t))]})]})]})}function c2(){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{children:"Authority status"}),(0,n.jsx)("div",{className:"rb-rows",children:(0,n.jsx)("div",{className:"rb-row","data-testid":"authority-disclaimer",children:(0,n.jsx)("span",{className:"rb-row-v",style:{color:"var(--fg-muted)",fontStyle:"italic"},children:"Relationship: governance only. No model/tool/file/workflow authority granted."})})})]})}function c4({auditRows:e,loading:t,error:a,onRetry:l,onLoadMore:i,hasMore:r}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{children:"Audit history"}),t&&(0,n.jsx)(cJ,{lines:3}),null!==a&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:a}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:l,children:"Retry"})]}),!t&&null===a&&0===e.length&&(0,n.jsx)("div",{className:"rb-rows",children:(0,n.jsx)("div",{className:"rb-row",children:(0,n.jsx)("span",{className:"rb-row-v",style:{color:"var(--fg-muted)"},children:"No audit events for this relationship yet."})})}),!t&&e.length>0&&(0,n.jsxs)("div",{className:"rb-rows",children:[e.map((e,t)=>(0,n.jsxs)("div",{className:"rb-row",style:{flexDirection:"column",alignItems:"flex-start",gap:"var(--space-1)"},children:[(0,n.jsxs)("span",{className:"rb-row-k mono",style:{fontSize:11},children:[e.from," → ",e.to]}),(0,n.jsx)("time",{dateTime:new Date(e.occurredAt).toISOString(),style:{color:"var(--fg-faint)",fontSize:11},children:new Date(e.occurredAt).toLocaleString()})]},t)),r&&(0,n.jsx)("div",{className:"rb-row",children:(0,n.jsx)("button",{type:"button",className:"rb-row-v",style:{color:"var(--accent)",fontSize:12,background:"none",border:"none",padding:0,cursor:"pointer",minHeight:24,minWidth:24},onClick:i,"aria-label":"Load more audit events",children:"Load more"})})]})]})}function c3({rel:e}){let t,a=(t=[],"evidence-run"===e.source.kind&&t.push(e.source.id),"evidence-run"===e.target.kind&&t.push(e.target.id),t);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{children:"Evidence references"}),0===a.length?(0,n.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)",margin:"0 0 4px"},"data-testid":"evidence-empty",children:"No evidence references for this relationship."}):(0,n.jsx)("div",{className:"rb-rows",children:a.map(e=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Evidence run"}),(0,n.jsx)("span",{className:"rb-row-v mono","aria-label":`Evidence run reference ${e}`,title:e,children:e})]},e))})]})}function c6({relationshipId:e,forwardCount:t,reverseCount:a,outgoing:l,incoming:i,expanded:r,onToggle:s,onSelectRelationship:o}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{children:"Impact summary"}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Forward dependencies"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:null===t?"—":String(t)})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Reverse dependencies"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:null===a?"—":String(a)})]}),(0,n.jsx)("div",{className:"rb-row",children:(0,n.jsx)("button",{type:"button",className:"arun-btn",onClick:s,"aria-expanded":r,"aria-controls":"rb-impact-detail","aria-label":r?`Hide impact for relationship ${e}`:`View impact for relationship ${e}`,"data-testid":"view-impact-btn",children:r?"Hide impact":"View impact"})})]}),r&&(0,n.jsx)("div",{id:"rb-impact-detail",children:(0,n.jsx)(cH,{outgoing:l,incoming:i,onSelectRelationship:o})})]})}function c5({codes:e,messages:t,deniedAt:a}){return 0===e.length?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{children:"Denial reason"}),(0,n.jsxs)("div",{className:"lk-alert",role:"status","aria-live":"polite","data-testid":"denial-section",children:[e.map((a,l)=>(0,n.jsxs)("div",{style:{marginBottom:8*(l<e.length-1)},children:[(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg-muted)",marginBottom:2},children:a}),(0,n.jsx)("div",{style:{fontSize:13,color:"var(--fg)"},children:t[l]??a})]},a)),void 0!==a&&(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--fg-faint)",marginTop:6},children:["Denied at ",(0,n.jsx)("time",{dateTime:a,children:a})]})]})]})}function c8(e){return null==e||0===e.length?null:{codes:e.map(e=>e.code),messages:e.map(e=>e.message)}}function c7({rel:e,onReconnect:t,onArchive:a,onRevoke:l,onViewImpact:i,onViewEvidence:r,mutating:s}){let o=e.lifecycle,c="blocked"===o,d="active"===o,u="active"===o||"blocked"===o||"archived"===o,p="active"===o;return(0,n.jsxs)("div",{style:{display:"flex",gap:"var(--space-3)",flexWrap:"wrap",marginTop:8},children:[(0,n.jsx)("button",{type:"button",className:`arun-btn${c?" primary":""}`,"aria-disabled":!c||s,"aria-label":"Reconnect — only available for blocked relationships",title:c?"Reconnect this relationship":"Only blocked relationships can be reconnected.",disabled:!c||s,onClick:c?t:void 0,children:"Reconnect"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!d||s,"aria-label":"Archive — only available for active relationships",title:d?"Archive this relationship":"Only active relationships can be archived.",disabled:!d||s,onClick:d?a:void 0,children:"Archive"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!u||s,"aria-label":"Revoke relationship",title:u?"Revoke this relationship":"Already revoked or superseded.",disabled:!u||s,onClick:u?l:void 0,style:{color:u?"var(--danger)":void 0},children:"Revoke"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":!p,"aria-label":"View impact analysis",title:p?"Toggle the impact analysis card":"Impact analysis is unavailable in this state.",disabled:!p,onClick:p?i:void 0,children:"View impact"}),(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-label":"View evidence references",title:"Jump to the evidence references section",onClick:r,children:"View evidence"})]})}function c9({relationshipId:e,densityMode:t="minimal",onClearFocus:l,onViewImpact:i,activityMap:r=new Map,throughputMap:s=new Map,animateBadges:o=!0,highContrast:c=!1}){let[d,u]=(0,a.useState)(null),[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(!1),[y,w]=(0,a.useState)(null),[j,k]=(0,a.useState)(null),[N,S]=(0,a.useState)(null),[C,I]=(0,a.useState)(null),[E,R]=(0,a.useState)(!1),$=null===N?null:N.relationships.length,A=null===C?null:C.relationships.length,[T,L]=(0,a.useState)(!1),P=(0,a.useRef)(null),M=(0,a.useRef)(0),D=(0,a.useCallback)(async e=>{let t=++M.current;v(null),f(!0),k(null),S(null),I(null),R(!1);let n=setTimeout(()=>{M.current===t&&L(!0)},500);P.current=n;try{let[n,a]=await Promise.all([af(e),ax(e)]);if(M.current!==t)return;u(n),m(a);try{let[n,a]=await Promise.all([ab(e,{direction:"outgoing",maxDepth:3,maxRelationships:512}),ab(e,{direction:"incoming",maxDepth:3,maxRelationships:512})]);if(M.current!==t)return;S(n),I(a)}catch{}}catch(e){if(M.current!==t)return;v(e instanceof ac?e.message:ao)}finally{P.current===n?(clearTimeout(n),P.current=null):clearTimeout(n),M.current===t&&(f(!1),L(!1))}},[]);(0,a.useEffect)(()=>{if(null===e){M.current+=1,null!==P.current&&(clearTimeout(P.current),P.current=null),u(null),m(null),v(null),k(null),L(!1),f(!1);return}return D(e),()=>{null!==P.current&&(clearTimeout(P.current),P.current=null)}},[e,D]);let q=(0,a.useCallback)(async e=>{if(null!==d){x(!0),w(null),k(null);try{let t=crypto.randomUUID(),{relationship:n}=await ag(d.id,{transition:{to:e}},String(d.etag),t);u(n),m(null),await D(d.id)}catch(e){w(e instanceof ac?e.message:"Mutation failed. Please retry."),k(e instanceof ac?c8(e.reasons):null)}finally{x(!1)}}},[d,D]),F=(0,a.useCallback)(()=>void q("draft"),[q]),O=(0,a.useCallback)(()=>void q("archived"),[q]),z=(0,a.useCallback)(async()=>{if(null!==d&&window.confirm(`Revoke relationship "${d.type}"? This cannot be undone.`)){x(!0),w(null),k(null);try{let e=crypto.randomUUID(),t=await av(d.id,String(d.etag),e);u(t)}catch(e){w(e instanceof ac?e.message:"Revoke failed. Please retry."),k(e instanceof ac?c8(e.reasons):null)}finally{x(!1)}}},[d]),K=(0,a.useCallback)(()=>{R(e=>!e)},[]),B=(0,a.useCallback)(e=>{i?.(e)},[i]),_=(0,a.useRef)(null),U=(0,a.useCallback)(()=>{_.current?.scrollIntoView?.({block:"start"})},[]);if(null===e)return(0,n.jsxs)("div",{className:"tw-pad","data-testid":"relationship-inspector-panel",children:[(0,n.jsx)(cX,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)("div",{className:"insp-empty","data-testid":"inspector-empty",children:"Select a relationship from the list to inspect it."}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--fg-muted)",marginTop:4},children:"If the list is empty, use “+ New relationship” in the toolbar to create one."})]});let W=c8(p?.decision.reasons)??j,V=null!==W&&(d?.lifecycle==="blocked"||d?.lifecycle==="revoked"||null!==j),H=null!==d?r.get(d.id)??function(e){switch(e){case"blocked":return"blocked";case"stale":return"degraded";default:return"inactive"}}(d.lifecycle):"inactive",Y=null!==d?s.get(d.id):void 0;return(0,n.jsxs)("div",{className:"tw-pad","aria-busy":h,"data-testid":"relationship-inspector-panel",children:[null!==g&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:g}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void D(e),children:"Retry"})]}),null!==y&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert","aria-live":"assertive",children:[(0,n.jsx)("span",{children:y}),(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>w(null),children:"Dismiss"})]}),h&&T&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)(cJ,{lines:4}),(0,n.jsx)(cJ,{lines:3})]}),!h&&null===g&&null===d&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)("div",{className:"insp-empty","data-testid":"inspector-not-found",children:"This relationship is no longer available."}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--fg-muted)",marginTop:4},children:"It may have been deleted, retired by retention, or it never existed in this workspace."}),void 0!==l&&(0,n.jsx)("button",{type:"button",className:"arun-btn",style:{marginTop:8},onClick:l,children:"Clear focus"})]}),!h&&null!==d&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cX,{style:{marginTop:0},children:"Relationship"}),(0,n.jsx)(cQ,{rel:d}),(0,n.jsx)(cZ,{label:"Source",kind:d.source.kind,id:d.source.id}),(0,n.jsx)(cZ,{label:"Target",kind:d.target.kind,id:d.target.id}),(0,n.jsx)(c0,{lifecycle:d.lifecycle}),(0,n.jsx)(c1,{type:d.type,lifecycle:d.lifecycle,activity:H,throughputCount:Y,animateBadges:o,highContrast:c,transitions:p?.lifecycle??[],densityMode:t}),(0,n.jsx)(c2,{}),(0,n.jsx)(c4,{auditRows:p?.lifecycle??[],loading:!1,error:null,onRetry:()=>void D(e),onLoadMore:()=>{},hasMore:!1}),(0,n.jsx)("div",{ref:_,children:(0,n.jsx)(c3,{rel:d})}),(0,n.jsx)(c6,{relationshipId:d.id,forwardCount:$,reverseCount:A,outgoing:N,incoming:C,expanded:E,onToggle:K,onSelectRelationship:B}),V&&null!==W&&(0,n.jsx)(c5,{codes:W.codes,messages:W.messages}),(0,n.jsx)(c7,{rel:d,onReconnect:F,onArchive:O,onRevoke:()=>void z(),onViewImpact:K,onViewEvidence:U,mutating:b})]})]})}let de=new Set(["kind","id","state","timestamp","count"]);function dt(e){return`${e.kind}: ${e.id}`}function dn({category:e}){return(0,n.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)",borderLeft:"2px solid var(--warn)",paddingLeft:8},children:["More ",e," exist than the bounded query returned. Resolve the listed items, then re-run the health check."]})}function da({category:e,onSelectRelationship:t}){if(0===e.items.length)return null;let a=e.items.slice(0,50),l=e.items.length-a.length;return(0,n.jsxs)("section",{"aria-label":`${e.label} (${String(e.items.length)})`,style:{marginBottom:14},children:[(0,n.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":3,children:[e.label,(0,n.jsx)("span",{className:"rb-count","aria-hidden":"true",children:e.items.length})]}),(0,n.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:e.help}),(0,n.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:a.map(e=>(0,n.jsx)("li",{style:{marginBottom:2},children:(0,n.jsxs)("button",{type:"button",className:"arun-btn ghost",onClick:()=>t(e.id),"aria-label":`Inspect ${e.type} relationship from ${dt(e.source)} to ${dt(e.target)}, lifecycle ${e.lifecycle}`,style:{display:"flex",width:"100%",gap:6,alignItems:"center",textAlign:"left",fontSize:12},children:[(0,n.jsx)("span",{className:"mono",style:{color:"var(--fg)"},children:e.type}),(0,n.jsxs)("span",{style:{color:"var(--fg-muted)"},children:[dt(e.source)," → ",dt(e.target)]}),(0,n.jsx)("span",{className:"mono",style:{marginLeft:"auto",color:"var(--fg-muted)"},children:e.lifecycle})]})},e.id))}),l>0&&(0,n.jsxs)("p",{role:"note",style:{margin:"4px 0 0",fontSize:11,color:"var(--fg-muted)"},children:["Showing the first ",String(50)," of ",String(e.items.length),"."]}),e.truncated&&(0,n.jsx)(dn,{category:e.label.toLowerCase()})]})}function dl({findings:e}){if(0===e.orphanedEndpoints.length)return null;let t=e.orphanedEndpoints.slice(0,50);return(0,n.jsxs)("section",{"aria-label":`Orphaned endpoints (${String(e.orphanedEndpoints.length)})`,style:{marginBottom:14},children:[(0,n.jsxs)("div",{className:"rb-section-label",role:"heading","aria-level":3,children:["Orphaned endpoints",(0,n.jsx)("span",{className:"rb-count","aria-hidden":"true",children:e.orphanedEndpoints.length})]}),(0,n.jsx)("p",{style:{margin:"0 0 6px",fontSize:11,color:"var(--fg-muted)"},children:"Endpoints that participate in no live relationship."}),(0,n.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0},children:t.map(e=>(0,n.jsx)("li",{className:"rb-row",style:{fontSize:12},children:(0,n.jsx)("span",{className:"mono",children:dt(e)})},`${e.kind}:${e.id}`))}),e.orphanedEndpointsTruncated&&(0,n.jsx)(dn,{category:"orphaned endpoints"})]})}function di({onSelectRelationship:e}){var t,l;let[i,r]=(0,a.useState)(null),[s,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),u=(0,a.useCallback)(async()=>{o(!0),d(null);try{let e=await ay();r(e)}catch(e){d(e instanceof ac?e.message:"Could not load the graph health check.")}finally{o(!1)}},[]);return(0,a.useEffect)(()=>{u()},[u]),(0,n.jsxs)("div",{style:{padding:12,height:"100%",overflowY:"auto"},"aria-busy":s,children:[(0,n.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[(0,n.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--fg)",flexGrow:1},children:"Graph health"}),(0,n.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>void u(),"aria-label":"Re-run the graph health check",style:{minHeight:24},children:"Refresh"})]}),s&&(0,n.jsx)("p",{style:{fontSize:12,color:"var(--fg-muted)"},"aria-live":"polite",children:"Running health check…"}),null!==c&&(0,n.jsxs)("div",{className:"lk-alert",role:"alert",children:[c,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>void u(),children:"Retry"})]}),!s&&null===c&&null!==i&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("p",{style:{fontSize:11,color:"var(--fg-faint)",margin:"0 0 10px"},children:["Checked at"," ",(0,n.jsx)("time",{dateTime:new Date(i.checkedAt).toISOString(),children:new Date(i.checkedAt).toLocaleString()}),"."]}),(0,n.jsx)("div",{className:"rb-rows",style:{marginBottom:14},children:ai.filter(e=>(i.totals[e]??0)>0).map(e=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:e}),(0,n.jsx)("span",{className:"rb-row-v mono",children:String(i.totals[e]??0)})]},e))}),0===(t=i.findings).orphanedEndpoints.length+t.staleRelationships.length+t.blockedRelationships.length+t.failedRelationships.length+t.invalidReferences.length+t.cycleParticipants.length?(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"Healthy"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"No relationship-graph defects were found."})]}):(0,n.jsxs)(n.Fragment,{children:[[{key:"invalid",label:"Invalid references",help:"An endpoint no longer resolves to a live workspace object.",items:(l=i.findings).invalidReferences,truncated:l.invalidReferencesTruncated},{key:"blocked",label:"Blocked",help:"A policy or endpoint state is blocking this relationship.",items:l.blockedRelationships,truncated:l.blockedRelationshipsTruncated},{key:"failed",label:"Failed (revoked)",help:"The relationship reached the revoked terminal state.",items:l.failedRelationships,truncated:l.failedRelationshipsTruncated},{key:"cycle",label:"Cycle participants",help:"These relationships take part in a dependency cycle.",items:l.cycleParticipants,truncated:l.cycleScanTruncated},{key:"stale",label:"Stale",help:"A health check flagged at least one endpoint as not currently live.",items:l.staleRelationships,truncated:l.staleRelationshipsTruncated}].map(t=>(0,n.jsx)(da,{category:t,onSelectRelationship:e},t.key)),(0,n.jsx)(dl,{findings:i.findings})]})]})]})}let dr={draft:["draft","active","archived","superseded","revoked","blocked","stale"],active:["active","archived","superseded","revoked","stale"],archived:["archived","superseded","revoked","stale"],superseded:["superseded","stale"],revoked:["revoked"],blocked:["blocked","draft","active","archived","revoked","stale"],stale:["stale","active","archived","superseded","revoked"]};function ds(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dc(e){return"string"==typeof e&&e.length>0}function dd(e,t,n){return void 0===n?{code:e,message:t}:{code:e,field:n,message:t}}function du(e,t,n){return ds(e)?dc(e.kind)?dc(e.id)?!!dc(e.workspaceId)||(n.push(dd("denied/schema-version-unsupported",`${t}.workspaceId must be a non-empty string`,`${t}.workspaceId`)),!1):(n.push(dd("denied/schema-version-unsupported",`${t}.id must be a non-empty string`,`${t}.id`)),!1):(n.push(dd("denied/schema-version-unsupported",`${t}.kind must be a non-empty string`,`${t}.kind`)),!1):(n.push(dd("denied/schema-version-unsupported",`${t} must be an object`,t)),!1)}function dp(e,t,n){dc(e[t])||n.push(dd("denied/schema-version-unsupported",`${t} must be a non-empty string`,t))}function dm(e,t){let n=e.kind;return an.includes(n)?null:dd("denied/schema-version-unsupported",`${t}.kind is not a known object kind`,`${t}.kind`)}function dh(e,t,n){"missing"===t?n.push(dd("source"===e?"denied/non-existent-source":"denied/non-existent-target",`${e} endpoint does not exist`,e)):"tombstoned"===t?n.push(dd("denied/endpoint-tombstoned",`${e} endpoint has been tombstoned`,e)):"retired"===t?n.push(dd("denied/endpoint-retired",`${e} endpoint has been retired`,e)):"unavailable"===t&&n.push(dd("denied/endpoint-unavailable",`${e} endpoint is unavailable`,e))}function df(e,t){let n=e.kind;return aa.includes(n)?null:dd("denied/object-kind-not-yet-supported",`${t}.kind "${n}" is reserved for a future release`,`${t}.kind`)}function dg(){return{type:"reads-context",sourceKind:"workflow-run",sourceId:"",targetKind:"memory",targetId:"",summary:""}}let dv=new Set(["denied/path-not-contained","denied/cross-workspace","denied/payload-content-not-permitted"]);function db(e){return e?.codes.some(e=>dv.has(e))===!0}function dx({onClose:e}){let[t,l]=(0,a.useState)(dg),[i,r]=(0,a.useState)([]),[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(!1),m=(0,a.useRef)(null),h="rel-create-dialog-title",f="rel-create-dialog-desc",g=(0,a.useCallback)(e=>{let t=m.current;if(null===t)return;let n=Array.from(t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(e=>!e.hasAttribute("disabled")),a=n[0],l=n[n.length-1];"Tab"===e.key&&(e.shiftKey?document.activeElement===a&&(e.preventDefault(),l?.focus()):document.activeElement===l&&(e.preventDefault(),a?.focus()))},[]),v=(0,a.useCallback)(t=>{"Escape"===t.key&&e(null)},[e]);(0,a.useEffect)(()=>{let e=m.current;if(null!==e)return e.addEventListener("keydown",g),e.addEventListener("keydown",v),()=>{e.removeEventListener("keydown",g),e.removeEventListener("keydown",v)}},[g,v]),(0,a.useEffect)(()=>{if(0===t.sourceId.length||0===t.targetId.length)return void r([]);let e=function(e){let t=function(e){var t;if(!ds(e))return{errors:[dd("denied/schema-version-unsupported","relationship must be an object")]};let n=[];dp(e,"id",n),dp(e,"workspaceId",n),dp(e,"createdAt",n),dp(e,"updatedAt",n),(!("number"==typeof(t=e.etag)&&Number.isInteger(t)&&Number.isFinite(t))||e.etag<0)&&n.push(dd("denied/schema-version-unsupported","etag must be a non-negative finite integer","etag"));let a=du(e.source,"source",n),l=du(e.target,"target",n);return!(n.length>0)&&a&&l?{errors:[],value:{record:e,source:e.source,target:e.target}}:{errors:n}}(e);if(!t.value)return{ok:!1,errors:t.errors};let{record:n,source:a,target:l}=t.value,i=function(e,t,n){let a,l,i="1"!==e.schemaVersion?dd("denied/schema-version-unsupported",'schemaVersion must be the literal "1"',"schemaVersion"):null;if(i)return[i];let r=dc(a=e.type)?al.includes(a)?null:dd("denied/schema-version-unsupported","type is not a known relationship type","type"):dd("denied/schema-version-unsupported","type must be a non-empty string","type");if(r)return[r];let s=dm(t,"source"),o=dm(n,"target");if(null!==s||null!==o){let e=[];return null!==s&&e.push(s),null!==o&&e.push(o),e}let c=dc(l=e.lifecycleState)?ai.includes(l)?null:dd("denied/schema-version-unsupported","lifecycleState is not a known lifecycle state","lifecycleState"):dd("denied/schema-version-unsupported","lifecycleState must be a non-empty string","lifecycleState");return c?[c]:null}(n,a,l);if(i)return{ok:!1,errors:i};let r=function(e){if(!e?.endpointResolver)return null;let t=[];return"missing"===e.endpointResolver.source&&dh("source",e.endpointResolver.source,t),"missing"===e.endpointResolver.target&&dh("target",e.endpointResolver.target,t),t}(void 0);if(null!==r&&r.length>0)return{ok:!1,errors:r};let s=function(e,t,n,a){var l,i,r,s,o;let c,d,u,p,m,h,f=[],g=e.type,v=e.lifecycleState,b=df(t,"source");b&&f.push(b);let x=df(n,"target");x&&f.push(x),null===b&&null===x&&(l=t.kind,i=n.kind,"denied/source-kind-not-allowed"===(d=(c=ar[g]).validSourceKinds.includes(l)?c.validTargetKinds.includes(i)?null:"denied/target-kind-not-allowed":"denied/source-kind-not-allowed")?f.push(dd("denied/source-kind-not-allowed",`source.kind "${t.kind}" is not permitted for type "${g}"`,"source.kind")):"denied/target-kind-not-allowed"===d&&f.push(dd("denied/target-kind-not-allowed",`target.kind "${n.kind}" is not permitted for type "${g}"`,"target.kind")));let y=(u=a?.cardinalityCounts)?"produces-evidence"===g&&"number"==typeof u.producesEvidenceForSource&&u.producesEvidenceForSource>=1?dd("denied/cardinality-exceeded","produces-evidence already exists for this source workflow-run"):"starts-workflow"===g&&"number"==typeof u.startsWorkflowForTarget&&u.startsWorkflowForTarget>=1?dd("denied/cardinality-exceeded","starts-workflow already exists for this target workflow-run"):null:null;y&&f.push(y),(p=t.kind===n.kind&&t.id===n.id?dd("denied/cycle-forbidden","source and target refer to the same endpoint"):null)&&f.push(p),(m="depends-on"===g&&a?.dependsOnReverseEdgeExists===!0?dd("denied/cycle-forbidden","depends-on reverse edge already exists for this endpoint pair"):null)&&f.push(m);let w=(r=e.workspaceId,t.workspaceId!==r||n.workspaceId!==r?dd("denied/cross-workspace","source and target must be in the relationship's workspace"):null);w&&f.push(w);let j=void 0===(h=a?.previousLifecycleState)||dr[h].includes(v)?null:dd("denied/lifecycle-illegal-transition",`transition from ${h} to ${v} is not permitted`,"lifecycleState");for(let t of(j&&f.push(j),s=a,o=f,s?.endpointResolver&&("missing"!==s.endpointResolver.source&&dh("source",s.endpointResolver.source,o),"missing"!==s.endpointResolver.target&&dh("target",s.endpointResolver.target,o)),function(e){let t=[];if(void 0===e.metadata||null===e.metadata)return t;if(!ds(e.metadata))return t.push(dd("denied/payload-content-not-permitted","metadata must be an object when set","metadata")),t;for(let n of Object.keys(e.metadata)){let e=n.toLowerCase().replace(/[^a-z0-9]/g,"");for(let a of as)if(e.includes(a)){t.push(dd("denied/payload-content-not-permitted","metadata may not carry endpoint content",`metadata.${n}`));break}}return t}(e)))f.push(t);return f}(n,a,l,void 0);return s.length>0?{ok:!1,errors:s}:{ok:!0,value:n}}({id:"candidate",schemaVersion:"1",workspaceId:"preview",source:{kind:t.sourceKind,id:t.sourceId,workspaceId:"preview"},target:{kind:t.targetKind,id:t.targetId,workspaceId:"preview"},type:t.type,lifecycleState:"active",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),etag:0});e.ok?r([]):r(e.errors.map(e=>e.message))},[t]);let b=(0,a.useRef)(null),x=(0,a.useRef)(0);(0,a.useEffect)(()=>{x.current+=1;let e=x.current;return(null!==b.current&&clearTimeout(b.current),0===t.sourceId.length||0===t.targetId.length||i.length>0)?void p(!1):(b.current=setTimeout(async()=>{p(!0);try{if(await ap({type:t.type,source:{kind:t.sourceKind,id:t.sourceId},target:{kind:t.targetKind,id:t.targetId},summary:t.summary.length>0?t.summary:void 0}),e!==x.current)return;o(e=>db(e)?e:null)}catch(t){if(e!==x.current)return;t instanceof ac&&t.reasons.length>0?o({source:"preview",codes:t.reasons.map(e=>e.code),messages:t.reasons.map(e=>e.message)}):o(null)}finally{e===x.current&&p(!1)}},250),()=>{null!==b.current&&clearTimeout(b.current)})},[t,i]),(0,a.useEffect)(()=>{o(e=>e?.source!=="submit"||db(e)?e:null)},[t]);let y=t.sourceId.trim().length>0&&t.targetId.trim().length>0&&0===i.length&&null===s&&!c,w=(0,a.useCallback)(async()=>{if(y){d(!0),o(null);try{let n=crypto.randomUUID(),{relationship:a}=await am({type:t.type,source:{kind:t.sourceKind,id:t.sourceId},target:{kind:t.targetKind,id:t.targetId},summary:t.summary.length>0?t.summary:void 0},n);e(a)}catch(e){e instanceof ac?e.reasons.length>0?o({source:"submit",codes:e.reasons.map(e=>e.code),messages:e.reasons.map(e=>e.message)}):o({source:"submit",codes:[e.code],messages:[e.message]}):o({source:"submit",codes:["relationship/network-error"],messages:[ao]})}finally{d(!1)}}},[y,t,e]),k=(0,a.useCallback)(e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&w()},[w]),N=ar[t.type],S=db(s),C=[i.length>0?"rel-create-client-hints":null,null!==s?"rel-create-server-denial":null].filter(e=>null!==e),I=(0,n.jsx)("div",{className:"cmdk-overlay",onPointerDown:()=>e(null),"data-testid":"rel-create-overlay",children:(0,n.jsxs)("div",{ref:m,role:"dialog","aria-modal":"true","aria-labelledby":h,"aria-describedby":f,className:"cmdk",style:{maxWidth:480,width:"100%"},onPointerDown:e=>e.stopPropagation(),onKeyDown:k,"data-testid":"rel-create-dialog",children:[(0,n.jsxs)("div",{className:"cmdk-input",style:{borderBottom:"1px solid var(--line)"},children:[(0,n.jsx)("span",{id:h,style:{fontWeight:600,fontSize:14,color:"var(--fg)"},children:"Create relationship"}),(0,n.jsx)("span",{id:f,className:"visually-hidden",children:"Create a new relationship between two workspace endpoints."}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:()=>e(null),"aria-label":"Close",title:"Close",style:{marginLeft:"auto"},children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsxs)("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:"rel-type",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Type"}),(0,n.jsx)(tz,{value:t.type,ariaLabel:"Relationship type",autoFocus:!0,menuTitle:"Relationship type",triggerStyle:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:13},sections:[{options:al.map(e=>({value:e,label:ar[e].displayName}))}],onValueChange:e=>l(t=>({...t,type:e}))}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--fg-muted)",marginTop:3},children:N.semantics})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:"var(--space-3)"},children:[(0,n.jsxs)("div",{style:{flex:"0 0 140px"},children:[(0,n.jsx)("label",{htmlFor:"rel-src-kind",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Source kind"}),(0,n.jsx)("select",{id:"rel-src-kind",value:t.sourceKind,onChange:e=>l(t=>({...t,sourceKind:e.target.value})),style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12},"aria-label":"Source endpoint kind",children:aa.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsxs)("div",{style:{flex:1},children:[(0,n.jsx)("label",{htmlFor:"rel-src-id",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Source ID"}),(0,n.jsx)("input",{id:"rel-src-id",type:"text",value:t.sourceId,onChange:e=>l(t=>({...t,sourceId:e.target.value})),placeholder:"endpoint id",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12},"aria-label":"Source endpoint ID","aria-describedby":"rel-src-kind"})]})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:"var(--space-3)"},children:[(0,n.jsxs)("div",{style:{flex:"0 0 140px"},children:[(0,n.jsx)("label",{htmlFor:"rel-tgt-kind",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Target kind"}),(0,n.jsx)("select",{id:"rel-tgt-kind",value:t.targetKind,onChange:e=>l(t=>({...t,targetKind:e.target.value})),style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12},"aria-label":"Target endpoint kind",children:aa.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsxs)("div",{style:{flex:1},children:[(0,n.jsx)("label",{htmlFor:"rel-tgt-id",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Target ID"}),(0,n.jsx)("input",{id:"rel-tgt-id",type:"text",value:t.targetId,onChange:e=>l(t=>({...t,targetId:e.target.value})),placeholder:"endpoint id",style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12},"aria-label":"Target endpoint ID","aria-describedby":"rel-tgt-kind"})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:"rel-summary",style:{fontSize:12,color:"var(--fg-muted)",display:"block",marginBottom:3},children:"Summary (optional, ≤240 chars)"}),(0,n.jsx)("textarea",{id:"rel-summary",value:t.summary,maxLength:240,rows:2,onChange:e=>l(t=>({...t,summary:e.target.value})),style:{width:"100%",background:"var(--inset)",border:"1px solid var(--line)",borderRadius:4,padding:"4px 8px",minHeight:24,color:"var(--fg)",fontSize:12,resize:"vertical"},"aria-label":"Relationship summary"})]}),i.length>0&&(0,n.jsx)("div",{id:"rel-create-client-hints",className:"lk-alert",role:"status","aria-live":"polite","data-testid":"client-validation-hints",children:i.map((e,t)=>(0,n.jsx)("div",{style:{fontSize:12},children:e},t))}),u&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--fg-muted)"},"aria-live":"polite",children:"Validating…"}),null!==s&&(0,n.jsxs)("div",{id:"rel-create-server-denial",className:"lk-alert",role:"alert","aria-live":"assertive","data-testid":"server-denial-banner",children:[s.codes.map((e,t)=>(0,n.jsxs)("div",{style:{marginBottom:6*(t<s.codes.length-1)},children:[(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--fg-muted)",marginBottom:2},children:e}),(0,n.jsx)("div",{style:{fontSize:13,color:"var(--fg)"},children:s.messages[t]??e})]},e)),S&&(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>o(null),style:{marginTop:6},children:"Dismiss"})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:"var(--space-4)",justifyContent:"flex-end",marginTop:4},children:[(0,n.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>e(null),style:{minWidth:24,minHeight:24},children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:`arun-btn${y?" primary":""}`,"aria-disabled":!y,"aria-describedby":C.length>0?C.join(" "):void 0,onClick:()=>void w(),"aria-busy":c,style:{minWidth:24,minHeight:24},children:c?"Creating…":"Create"})]})]})]})});return"u"<typeof document?I:(0,tP.createPortal)(I,document.body)}let dy={};function dw(){let{activityMap:e,throughputMap:t,animate:l}=function(){let e=(0,a.useRef)(new Map),t=(0,a.useRef)("u"<typeof document||"visible"===document.visibilityState),[n,l]=(0,a.useState)(new Map),[i,r]=(0,a.useState)(new Map),s=(0,a.useRef)(new Map),o=(0,a.useRef)(new Map),[c,d]=(0,a.useState)(()=>window.matchMedia("(prefers-reduced-motion: reduce)").matches),[u,p]=(0,a.useState)(!1),m=(0,a.useCallback)(()=>{p(!0)},[]),h=(0,a.useCallback)((t,n)=>{let a=new Map(s.current),i=new Set,c=new Set,d=!1;for(let[l,r]of a){let s=t-(e.current.get(l)??0);s>=6e4&&"inactive"!==r&&(a.set(l,"inactive"),c.add(l),d=!0),!n&&s>=12e4&&(a.delete(l),i.add(l),c.add(l),d=!0)}if(a.size>512)for(let t of Array.from(a.keys()).sort((t,n)=>{let l=a.get(t),i=a.get(n);return"inactive"===l&&"inactive"!==i?-1:"inactive"!==l&&"inactive"===i?1:(e.current.get(t)??0)-(e.current.get(n)??0)}).slice(0,a.size-512))a.delete(t),i.add(t),c.add(t),d=!0;if(d&&(s.current=a,l(a)),i.size>0)for(let t of i)e.current.delete(t);if(c.size>0){let e=!1,t=new Map(o.current);for(let n of c)t.delete(n)&&(e=!0);e&&(o.current=t,r(t))}},[]);(0,a.useEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)"),t=e=>{d(e.matches)};return e.addEventListener("change",t),()=>{e.removeEventListener("change",t)}},[]);let f=(0,a.useCallback)(n=>{if(!t.current)return;let a=Date.now();a-(e.current.get(n.id)??0)<2e3||(e.current.set(n.id,a),l(e=>{let t=new Map(e);return t.set(n.id,n.state),s.current=t,t}),"high-throughput"===n.state&&void 0!==n.count?r(e=>{let t=new Map(e);return t.set(n.id,n.count),o.current=t,t}):r(e=>{if(!e.has(n.id))return e;let t=new Map(e);return t.delete(n.id),o.current=t,t}))},[]);return(0,a.useEffect)(()=>{let e=setInterval(()=>{t.current&&h(Date.now(),!1)},15e3);return()=>{clearInterval(e)}},[h]),(0,a.useEffect)(()=>{if("u"<typeof document)return;let e=()=>{t.current="visible"===document.visibilityState,t.current&&h(Date.now(),!0)};return t.current="visible"===document.visibilityState,document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[h]),(0,a.useEffect)(()=>{let e=!1,n=null,a=null;function l(e){let t;try{t=JSON.parse(e)}catch{return}let n=function(e){var t;if(null===e||"object"!=typeof e||function e(t){if(null===t||"object"!=typeof t)return!1;for(let n of Object.keys(t))if(function(e){let t=e.toLowerCase();return as.some(e=>t.includes(e))}(n)||e(t[n]))return!0;return!1}(e))return null;let n={};for(let t of de)Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=e[t]);return"string"!=typeof n.id||0===n.id.length?null:"inactive"!==(t=n.state)&&"queued"!==t&&"active"!==t&&"processing"!==t&&"completed"!==t&&"failed"!==t&&"blocked"!==t&&"degraded"!==t&&"high-throughput"!==t||"number"!=typeof n.timestamp?null:{kind:"string"==typeof n.kind?n.kind:"relationship:activity",id:n.id,state:n.state,timestamp:n.timestamp,count:"number"==typeof n.count?n.count:void 0}}(t);null!==n&&f(n)}function i(){null!==a&&(clearTimeout(a),a=null)}function r(){n?.close(),n=null}function s(){!e&&null===a&&t.current&&(a=setTimeout(()=>{a=null,o()},5e3))}function o(){if(!e&&t.current){try{n=new EventSource("/api/relationships/events")}catch{s();return}n.addEventListener("relationship:activity",e=>{l(e.data)}),n.onmessage=e=>{l(e.data)},n.onerror=()=>{e||(r(),s())}}}o();let c=()=>{if(t.current="visible"===document.visibilityState,!t.current){i(),r();return}h(Date.now(),!0),null===n&&o()};return document.addEventListener("visibilitychange",c),()=>{e=!0,document.removeEventListener("visibilitychange",c),i(),r()}},[void 0,f,h]),{activityMap:n,throughputMap:i,animate:!c&&!u,disable:m}}(),[i,r]=(0,a.useState)(!1),[s,o]=(0,a.useState)(dy),c=s.relFocus,d=s.relDensity??"minimal",[u,p]=(0,a.useState)(!1),m=(0,a.useRef)(null),h=(0,a.useRef)(!1),f=(0,a.useRef)(null),[g,v]=(0,a.useState)(!1),b=(0,a.useCallback)(e=>{o(t=>{let n={...t,...e},a={};for(let[e,t]of Object.entries(n))void 0!==t&&""!==t&&(a[e]=t);return a})},[]),x=(0,a.useCallback)(e=>{b({relFocus:e})},[b]),y=(0,a.useCallback)(()=>{b({relFocus:void 0})},[b]),w=(0,a.useCallback)(e=>{b({relFocus:e})},[b]),j=(0,a.useCallback)(e=>{h.current=!0,p(!1),null!==e&&b({relFocus:e.id})},[b]);return(0,a.useEffect)(()=>{!u&&h.current&&(h.current=!1,m.current?.focus())},[u]),(0,a.useEffect)(()=>{let e=window.matchMedia("(prefers-contrast: more)"),t=e=>{r(e)};t(e.matches);let n=e=>{t(e.matches)};return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]),(0,a.useEffect)(()=>{let e=f.current;if(null===e)return;let t=e=>{let t=e.target;if(!("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName||t.isContentEditable)&&"Escape"===e.key){if(u||null!==document.querySelector('[role="dialog"][aria-modal="true"]'))return;y()}};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[u,y]),(0,n.jsxs)(n.Fragment,{children:[u&&(0,n.jsx)(dx,{onClose:j}),(0,n.jsxs)("div",{ref:f,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",background:"var(--bg)"},children:[(0,n.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--line)",flexShrink:0},children:[(0,n.jsx)("button",{type:"button",className:"arun-btn",onClick:()=>v(e=>!e),"aria-pressed":g,"aria-label":"Toggle the graph health view",style:{flex:"0 0 auto",minHeight:24,marginRight:"auto"},children:g?"Hide health":"Graph health"}),(0,n.jsx)("button",{ref:m,type:"button",className:"arun-btn primary",onClick:()=>p(!0),"aria-label":"Create new relationship",style:{flex:"0 0 auto",minWidth:24,minHeight:24},children:"+ New relationship"})]}),(0,n.jsxs)("div",{style:{display:"flex",flex:1,overflow:"hidden"},children:[(0,n.jsx)("div",{style:{flex:"0 0 280px",borderRight:"1px solid var(--line)",overflowY:"auto"},children:(0,n.jsx)(cU,{filters:s,selectedId:c,onSelect:x,onFilterChange:b,activityMap:e,throughputMap:t,animateBadges:l,highContrast:i})}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:g?(0,n.jsx)(di,{onSelectRelationship:e=>{v(!1),x(e)}}):(0,n.jsx)(c9,{relationshipId:c??null,densityMode:d,onClearFocus:y,onViewImpact:w,activityMap:e,throughputMap:t,animateBadges:l,highContrast:i})})]})]})]})}var dj=e.i(22016);let dk={NOT_FOUND:"The memory could not be found. It may have been deleted.",BAD_REQUEST:"The request was rejected as invalid. Adjust the input and try again.",CONFLICT:"The memory changed in the meantime. Reload the page and try again.",GOVERNANCE_ERROR:"Governance rules blocked this action.",MEMORY_ERROR:"The memory store reported an error. Retry, or check the server log.",MEMORY_UNAVAILABLE:"The memory store is currently unavailable. Retry in a moment.",PAYLOAD_TOO_LARGE:"The submitted content is too large. Shorten it and try again.",INTERNAL:"Something went wrong on the server. Retry, or check the server log."};function dN(e){if(e instanceof w.ApiError){let t=dk[e.code];return void 0!==t?`${t} (${e.code})`:e.message.trim().length>0?`${e.message} (${e.code})`:`Something went wrong. Retry, or check the server log. (${e.code})`}return e instanceof Error&&e.message.trim().length>0?e.message:"An unexpected error occurred."}let dS={jaccardThreshold:.85,staleConfidenceThreshold:.3,maxAgeMs:7776e6,maxClustersPerRun:100,maxRecordsPerRun:1e3};function dC(e,t){return`${e.toString()} ${1===e?t:`${t}s`}`}function dI(e){return"completed"===e||"failed"===e||"canceled"===e||"skipped"===e}function dE(e){return void 0===e?"—":new Date(e).toLocaleString()}function dR({id:e,onOpenDetail:t}){return void 0!==t?(0,n.jsx)("button",{type:"button",className:"mc-id-link mc-link-button",title:e,onClick:()=>t(e),children:e}):(0,n.jsx)(dj.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e)}`,className:"mc-id-link",title:e,children:e})}function d$({ids:e,onOpenDetail:t}){return(0,n.jsx)(n.Fragment,{children:e.map((e,l)=>(0,n.jsxs)(a.Fragment,{children:[l>0?", ":null,(0,n.jsx)(dR,{id:e,onOpenDetail:t})]},`${l.toString()}:${e}`))})}function dA({item:e,onOpenDetail:t}){return void 0===e.proposedAction?(0,n.jsx)(n.Fragment,{children:"No automatic action proposed."}):"merge"===e.proposedAction.kind?(0,n.jsxs)(n.Fragment,{children:["Merge into ",(0,n.jsx)(dR,{id:e.proposedAction.winner,onOpenDetail:t}),"; replace ",(0,n.jsx)(d$,{ids:e.proposedAction.losers,onOpenDetail:t}),"."]}):(0,n.jsxs)(n.Fragment,{children:["Supersede ",(0,n.jsx)(dR,{id:e.proposedAction.older,onOpenDetail:t})," with"," ",(0,n.jsx)(dR,{id:e.proposedAction.newer,onOpenDetail:t}),"."]})}function dT({flag:e,onOpenDetail:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(dR,{id:e.memoryId,onOpenDetail:t})," — ",e.reason]})}function dL({label:e,name:t,value:l,min:i,max:r,step:s,help:o,disabled:c=!1,onChange:d}){let u=(0,a.useId)(),p=e=>{var n;let a=s??1,o=Number.isFinite(l)?l:i??0,c=Math.min(function(e){let[,t=""]=e.toString().split(".");return t.length}(a)+2,8);d(t,(n=Number((o+e*a).toFixed(c)),void 0!==i&&n<i?i:void 0!==r&&n>r?r:n))};return(0,n.jsxs)("div",{style:{display:"grid",gap:"var(--space-3)"},children:[(0,n.jsxs)("label",{style:{display:"grid",gap:"var(--space-3)"},children:[(0,n.jsx)("span",{className:"mc-dialog-label",children:e}),(0,n.jsxs)("span",{className:"number-control",children:[(0,n.jsx)("input",{type:"number",inputMode:"decimal",className:"mc-dialog-input number-control-input",name:t,value:Number.isFinite(l)?l:"",min:i,max:r,step:s,disabled:c,"aria-describedby":u,onChange:e=>{d(t,Number(e.target.value))},onWheel:e=>{c||0===e.deltaY||(e.preventDefault(),p(e.deltaY<0?1:-1))}}),(0,n.jsx)(a3,{label:e.toLowerCase(),disabled:c,onStepUp:()=>p(1),onStepDown:()=>p(-1)})]})]}),(0,n.jsx)("span",{id:u,style:{color:"var(--fg-muted)",fontSize:12},children:o})]})}function dP({startJobImpl:e=t5,fetchJobImpl:t=t8,cancelJobImpl:l=t7,pollIntervalMs:i=2e3,onBack:r,onOpenDetail:s}){var o;let[c,d]=(0,a.useState)(dS),[u,p]=(0,a.useState)(null),[m,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(null),[w,j]=(0,a.useState)(null),k=u?.job??null,N=null!==k&&!dI(k.state),S=(0,a.useMemo)(()=>{if(null===k)return null;let e=k.result;return{reviewCount:e?.reviewItems.length??0,staleCount:e?.staleFlags.length??0,edgeCount:e?.edgesProposed.length??0}},[k]),C=(0,a.useCallback)((e,t)=>{d(n=>({...n,[e]:t}))},[]),I=(0,a.useCallback)(async e=>{g(!0);try{let n=await t(e);p(n.job),j(null)}catch(e){j(dN(e))}finally{g(!1)}},[t]);(0,a.useEffect)(()=>{if(null===k||dI(k.state))return;let e=window.setInterval(()=>{I(k.id)},i);return()=>{window.clearInterval(e)}},[k,i,I]);let E=(0,a.useCallback)(async t=>{if(t.preventDefault(),!m&&!N){h(!0),y(null),j(null);try{let t=await e(c);p(t.job)}catch(e){y(dN(e))}finally{h(!1)}}},[c,e,m,N]),R=(0,a.useCallback)(async()=>{if(null!==k&&!v){b(!0),j(null);try{let e=await l(k.id);p(e.job)}catch(e){j(dN(e))}finally{b(!1)}}},[k,l,v]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header mc-consolidation-header",children:[(0,n.jsxs)("div",{className:"mc-consolidation-heading",style:{display:"grid",gap:"var(--space-2)"},children:[(0,n.jsx)("h1",{className:"lk-title",children:"MemoriaViva Consolidation"}),(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"Start a bounded consolidation job, inspect its output, and cancel it while it is still queued or running."})]}),void 0!==r?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg","aria-label":"Back to MemoriaViva",onClick:r,children:"Back"}):(0,n.jsx)(dj.default,{href:"/memoriaviva",className:"lk-btn lk-btn-ghost lk-btn-lg","aria-label":"Back to MemoriaViva",children:"Back"})]}),(0,n.jsxs)("div",{className:"mc-consolidation-scroll",children:[(0,n.jsx)("section",{"aria-label":"Consolidation settings",style:{display:"grid",gap:16,padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:(0,n.jsxs)("form",{onSubmit:E,style:{display:"grid",gap:16},children:[(0,n.jsxs)("div",{style:{display:"grid",gap:"var(--space-5)",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))"},children:[(0,n.jsx)(dL,{label:"Jaccard threshold",name:"jaccardThreshold",value:c.jaccardThreshold,min:0,max:1,step:.01,disabled:m||N,help:"Similarity floor for near-duplicate detection.",onChange:C}),(0,n.jsx)(dL,{label:"Stale confidence threshold",name:"staleConfidenceThreshold",value:c.staleConfidenceThreshold,min:0,max:1,step:.01,disabled:m||N,help:"Memories at or below this confidence are flagged stale.",onChange:C}),(0,n.jsx)(dL,{label:"Max age (days)",name:"maxAgeMs",value:c.maxAgeMs/864e5,min:0,step:1,disabled:m||N,help:"Memories older than this are checked for staleness.",onChange:(e,t)=>{C(e,864e5*t)}}),(0,n.jsx)(dL,{label:"Max clusters per run",name:"maxClustersPerRun",value:c.maxClustersPerRun,min:0,max:1e3,step:1,disabled:m||N,help:"Hard bound on duplicate clusters inspected in one run.",onChange:C}),(0,n.jsx)(dL,{label:"Max records per run",name:"maxRecordsPerRun",value:c.maxRecordsPerRun,min:0,max:1e3,step:1,disabled:m||N,help:"Hard bound on accepted records admitted to one scan.",onChange:C})]}),null!==x?(0,n.jsx)("div",{role:"alert",className:"lk-alert",children:x}):null,(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"var(--space-5)"},children:[(0,n.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary","aria-disabled":m||N,"aria-busy":m,children:m?"Starting…":"Start consolidation"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null===k||f,"aria-busy":f,onClick:()=>{null===k||f||I(k.id)},children:f?"Refreshing…":"Refresh status"}),N?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":v,"aria-busy":v,onClick:()=>{R()},children:v?"Canceling…":"Cancel job"}):null]})]})}),(0,n.jsx)("section",{"aria-label":"Consolidation job status",style:{display:"grid",gap:16,padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:null===k?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No consolidation job started yet."}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{display:"grid",gap:"var(--space-5)",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))"},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"State"}),(0,n.jsx)("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{fontWeight:700,textTransform:"capitalize"},children:k.state})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Job ID"}),(0,n.jsx)("div",{style:{wordBreak:"break-all"},children:k.id})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Started"}),(0,n.jsx)("div",{children:dE(k.startedAt)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Completed"}),(0,n.jsx)("div",{children:dE(k.completedAt)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Clusters inspected"}),(0,n.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:k.result?.clustersInspected??0})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Elapsed"}),(0,n.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:(o=k.result?.elapsedMs??0)<1e3?`${o.toString()} ms`:`${(o/1e3).toFixed(1)} s`})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Records inspected"}),(0,n.jsxs)("div",{style:{fontVariantNumeric:"tabular-nums"},children:[k.result?.recordsInspected??0,k.result?.truncated===!0?" (truncated)":""]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--fg-muted)",fontSize:12},children:"Memories loaded"}),(0,n.jsx)("div",{style:{fontVariantNumeric:"tabular-nums"},children:u?.memoryCount??0})]})]}),null!==w?(0,n.jsx)("div",{role:"alert",className:"lk-alert",children:w}):null,void 0!==k.error&&k.error.length>0?(0,n.jsx)("div",{role:"alert",className:"lk-alert",children:k.error}):null,null!==S?(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"var(--space-5)"},children:[(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:dC(S.reviewCount,"review item")}),(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:dC(S.staleCount,"stale flag")}),(0,n.jsx)("span",{className:"mc-badge mc-badge-default",children:dC(S.edgeCount,"proposed edge")})]}):null]})}),k?.result!==void 0?(0,n.jsxs)("section",{"aria-label":"Consolidation results","aria-live":"polite","aria-atomic":"false",style:{display:"grid",gap:16,gridTemplateColumns:"repeat(auto-fit, minmax(280px, 1fr))"},children:[(0,n.jsxs)("article",{style:{display:"grid",gap:"var(--space-5)",padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,n.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Review items"}),0===k.result.reviewItems.length?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No review items returned."}):(0,n.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:"var(--space-5)"},children:k.result.reviewItems.map(e=>(0,n.jsxs)("li",{style:{display:"grid",gap:"var(--space-2)"},children:[(0,n.jsx)("strong",{style:{textTransform:"capitalize"},children:e.reason.replaceAll("-"," ")}),(0,n.jsx)("span",{children:(0,n.jsx)(d$,{ids:e.relatedMemoryIds,onOpenDetail:s})}),(0,n.jsx)("span",{style:{color:"var(--fg-muted)"},children:(0,n.jsx)(dA,{item:e,onOpenDetail:s})})]},e.id))})]}),(0,n.jsxs)("article",{style:{display:"grid",gap:"var(--space-5)",padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,n.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Stale flags"}),0===k.result.staleFlags.length?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No stale flags returned."}):(0,n.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:"var(--space-5)"},children:k.result.staleFlags.map(e=>(0,n.jsx)("li",{children:(0,n.jsx)(dT,{flag:e,onOpenDetail:s})},`${e.memoryId}:${e.reason}`))})]}),(0,n.jsxs)("article",{style:{display:"grid",gap:"var(--space-5)",padding:16,border:"1px solid var(--line)",borderRadius:14,background:"var(--card)"},children:[(0,n.jsx)("h2",{className:"lk-section-head",style:{margin:0},children:"Proposed edges"}),0===k.result.edgesProposed.length?(0,n.jsx)("p",{style:{margin:0,color:"var(--fg-muted)"},children:"No edges proposed."}):(0,n.jsx)("ul",{style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:"var(--space-5)"},children:k.result.edgesProposed.map(e=>(0,n.jsxs)("li",{style:{display:"grid",gap:"var(--space-2)"},children:[(0,n.jsx)("strong",{children:e.kind}),(0,n.jsxs)("span",{children:[(0,n.jsx)(dR,{id:e.fromMemoryId,onOpenDetail:s})," →"," ",(0,n.jsx)(dR,{id:e.toMemoryId,onOpenDetail:s})]}),void 0!==e.provenanceSummary?(0,n.jsx)("span",{style:{color:"var(--fg-muted)"},children:e.provenanceSummary}):null]},e.id))})]})]}):null]})]})}let dM=["user","workspace","project","workflow","global"],dD=["episodic","semantic-fact","procedural","preference","correction","decision","negative","pinned"],dq=["public","confidential","restricted"],dF=["proposed","accepted","rejected","superseded","archived","forgotten","conflicted","expired"],dO={user:"User",workspace:"Workspace",project:"Project",workflow:"Workflow",global:"Global"},dz={episodic:"Episodic","semantic-fact":"Fact",procedural:"Procedural",preference:"Preference",correction:"Correction",decision:"Decision",negative:"Negative",pinned:"Pinned"},dK={proposed:"Proposed",accepted:"Accepted",rejected:"Rejected",superseded:"Superseded",archived:"Archived",forgotten:"Forgotten",conflicted:"Conflicted",expired:"Expired"},dB={public:"Public",confidential:"Confidential",restricted:"Restricted"};function d_(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function dU({label:e,items:t,labels:a,active:l,onToggle:i}){return(0,n.jsxs)("div",{className:"mc-filter-row",role:"group","aria-label":`Filter by ${e}`,children:[(0,n.jsx)("span",{className:"mc-filter-label",children:e}),(0,n.jsx)("div",{className:"mc-filter-chips",children:t.map(e=>{let t=l.includes(e);return(0,n.jsx)("button",{type:"button",className:"mc-chip","data-active":String(t),"aria-pressed":t,onClick:()=>{i(e)},children:a[e]},e)})})]})}function dW({filters:e,onChange:t}){return(0,n.jsxs)("section",{className:"mc-filters","aria-label":"Memory filters",children:[(0,n.jsx)(dU,{label:"Scope",items:dM,labels:dO,active:e.scope,onToggle:n=>{t({...e,scope:d_(e.scope,n)})}}),(0,n.jsx)(dU,{label:"Type",items:dD,labels:dz,active:e.type,onToggle:n=>{t({...e,type:d_(e.type,n)})}}),(0,n.jsx)(dU,{label:"Status",items:dF,labels:dK,active:e.status,onToggle:n=>{t({...e,status:d_(e.status,n)})}}),(0,n.jsx)(dU,{label:"Sensitivity",items:dq,labels:dB,active:e.sensitivity,onToggle:n=>{t({...e,sensitivity:d_(e.sensitivity,n)})}})]})}let dV={public:"Public",confidential:"Confidential",restricted:"Restricted"};function dH({record:e,mode:t="edit",onSave:l,onClose:i,editMemoryImpl:r=ne,correctMemoryImpl:s=nr}){let[o,c]=(0,a.useState)(e.body),[d,u]=(0,a.useState)(e.tags.join(", ")),[p,m]=(0,a.useState)(e.provenance.sensitivity),[h,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(!1),y=(0,a.useRef)(null),w=(0,a.useRef)(null),j=(0,a.useRef)(null),k=(0,a.useRef)(null),N=(0,a.useId)(),S=(0,a.useId)(),C="correct"===t;(0,a.useEffect)(()=>(k.current=document.activeElement instanceof HTMLElement?document.activeElement:null,y.current?.focus(),()=>{k.current?.focus()}),[]);let I=(0,a.useCallback)(e=>{if("Escape"===e.key)return void i();if("Tab"!==e.key)return;let t=j.current?.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])');if(void 0===t||0===t.length){e.preventDefault(),j.current?.focus();return}let n=t[0],a=t[t.length-1];if(void 0===n||void 0===a){e.preventDefault(),j.current?.focus();return}let l=document.activeElement;e.shiftKey||l!==a?e.shiftKey&&l===n&&(e.preventDefault(),a.focus()):(e.preventDefault(),n.focus())},[i]),E=(0,a.useCallback)(e=>{e.target===w.current&&i()},[i]),R=(0,a.useCallback)(async()=>{let t=o.trim();if(0===t.length){v("Body cannot be empty."),x(!0),y.current?.focus();return}let n=d.split(",").map(e=>e.trim()).filter(e=>e.length>0);f(!0),v(null);try{if(C){let n=await s(e.id,t);l(n.correction)}else{let a=await r(e.id,{body:t,tags:n,sensitivity:p});l(a.memory)}}catch(e){v(dN(e))}finally{f(!1)}},[o,d,p,e.id,C,s,r,l]);return(0,n.jsx)("div",{ref:w,className:"mc-dialog-backdrop",role:"presentation",onClick:E,children:(0,n.jsxs)("div",{ref:j,role:"dialog","aria-modal":"true","aria-labelledby":N,tabIndex:-1,className:"mc-dialog",onKeyDown:I,children:[(0,n.jsx)("h2",{id:N,className:"mc-dialog-title",children:C?"Correct memory":"Edit memory"}),(0,n.jsxs)("div",{className:"mc-dialog-field",children:[(0,n.jsx)("label",{htmlFor:"edit-body",className:"mc-dialog-label",children:C?"Corrected body":"Body"}),(0,n.jsx)("textarea",{id:"edit-body",ref:y,className:"mc-dialog-textarea",value:o,rows:5,onChange:e=>{c(e.target.value),b&&(x(!1),v(null))},disabled:h,"aria-required":"true","aria-invalid":b?"true":void 0,"aria-describedby":b?S:void 0})]}),C?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"mc-dialog-field",children:[(0,n.jsxs)("label",{htmlFor:"edit-tags",className:"mc-dialog-label",children:["Tags ",(0,n.jsx)("span",{className:"mc-dialog-hint",children:"(comma-separated)"})]}),(0,n.jsx)("input",{id:"edit-tags",type:"text",className:"mc-dialog-input",value:d,onChange:e=>{u(e.target.value)},disabled:h})]}),(0,n.jsxs)("div",{className:"mc-dialog-field",children:[(0,n.jsx)("label",{htmlFor:"edit-sensitivity",className:"mc-dialog-label",children:"Sensitivity"}),(0,n.jsx)("select",{id:"edit-sensitivity",className:"mc-dialog-select",value:p,onChange:e=>{m(e.target.value)},disabled:h,children:dq.map(e=>(0,n.jsx)("option",{value:e,children:dV[e]},e))})]})]}),null!==g?(0,n.jsx)("p",{id:S,role:"alert",className:"mc-dialog-error",children:g}):null,(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:i,disabled:h,children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary",onClick:()=>{R()},disabled:h,"aria-busy":h,children:h?C?"Submitting…":"Saving…":C?"Submit correction":"Save"})]})]})})}function dY({record:e,mode:t="forget",onComplete:l,onClose:i,forgetMemoryImpl:r=nl,deleteMemoryImpl:s=ni}){let[o,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(null),p=(0,a.useRef)(null),m=(0,a.useRef)(null),h=(0,a.useRef)(null),f=(0,a.useRef)(null),g="delete"===t;(0,a.useEffect)(()=>(f.current=document.activeElement instanceof HTMLElement?document.activeElement:null,p.current?.focus(),()=>{f.current?.focus()}),[]);let v=(0,a.useCallback)(e=>{if("Escape"===e.key)return void i();if("Tab"!==e.key)return;let t=h.current?.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])');if(void 0===t||0===t.length){e.preventDefault(),h.current?.focus();return}let n=t[0],a=t[t.length-1];if(void 0===n||void 0===a){e.preventDefault(),h.current?.focus();return}let l=document.activeElement;e.shiftKey||l!==a?e.shiftKey&&l===n&&(e.preventDefault(),a.focus()):(e.preventDefault(),n.focus())},[i]),b=(0,a.useCallback)(e=>{e.target===m.current&&i()},[i]),x=(0,a.useCallback)(async()=>{c(!0),u(null);try{g?await s(e.id,"user-initiated delete from MemoriaViva"):await r(e.id,"user-initiated forget from MemoriaViva"),l()}catch(e){u(dN(e)),c(!1)}},[s,r,g,l,e.id]);return(0,n.jsx)("div",{ref:m,className:"mc-dialog-backdrop",role:"presentation",onClick:b,children:(0,n.jsxs)("div",{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":"forget-dialog-title","aria-describedby":"forget-dialog-desc",tabIndex:-1,className:"mc-dialog",onKeyDown:v,children:[(0,n.jsx)("h2",{id:"forget-dialog-title",className:"mc-dialog-title",children:g?"Delete this memory?":"Forget this memory?"}),(0,n.jsx)("p",{id:"forget-dialog-desc",className:"mc-dialog-body",children:(0,n.jsxs)(n.Fragment,{children:["This action is ",(0,n.jsx)("strong",{children:"permanent"}),". The memory will be removed and a tombstone audit record will be created. You cannot undo this."]})}),(0,n.jsx)("blockquote",{className:"mc-dialog-quote","aria-label":"Memory content to be removed",children:e.body.length>120?`${e.body.slice(0,120)}…`:e.body}),null!==d?(0,n.jsx)("p",{role:"alert",className:"mc-dialog-error",children:d}):null,(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{ref:p,type:"button",className:"lk-btn lk-btn-ghost",onClick:i,disabled:o,children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",onClick:()=>{x()},disabled:o,"aria-busy":o,children:o?g?"Deleting…":"Forgetting…":g?"Delete permanently":"Forget permanently"})]})]})})}function dG({record:e,onRecordChange:t,acceptImpl:l=ns,rejectImpl:i=no,pinImpl:r=nt,unpinImpl:s=nn,archiveImpl:o=na,deleteImpl:c=ni,correctImpl:d=nr}){let[u,p]=(0,a.useState)(null),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(!1),[w,j]=(0,a.useState)(!1),[k,N]=(0,a.useState)(!1),S=(0,a.useCallback)(async(e,t)=>{if(null===u){p(e),h(null),g(null);try{await t()}catch(e){h(dN(e))}finally{p(null)}}},[u]),C=(0,a.useCallback)(()=>{S("accept",async()=>{t((await l(e.id)).memory)})},[l,t,e.id,S]),I=(0,a.useCallback)(()=>{S("reject",async()=>{t((await i(e.id,"rejected by user in MemoriaViva")).memory)})},[t,e.id,i,S]),E=(0,a.useCallback)(()=>{S("pin",async()=>{t((await r(e.id)).memory)})},[t,r,e.id,S]),R=(0,a.useCallback)(()=>{S("unpin",async()=>{t((await s(e.id)).memory)})},[t,e.id,S,s]),$=(0,a.useCallback)(()=>{S("archive",async()=>{t((await o(e.id,"archived by user in MemoriaViva")).memory)})},[o,t,e.id,S]),A=(0,a.useCallback)(e=>{y(!1),g(`Correction submitted for review: ${e.body}`)},[]),T="proposed"===e.status,L="accepted"===e.status||"superseded"===e.status||"conflicted"===e.status||"expired"===e.status,P="forgotten"===e.status;return(0,n.jsxs)("div",{className:"mc-actions",role:"group","aria-label":"Memory actions",children:[T?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary","aria-disabled":null!==u,"aria-busy":"accept"===u,onClick:C,"aria-label":"Approve this memory proposal",children:"accept"===u?"Approving…":"Approve"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"reject"===u,onClick:I,"aria-label":"Reject this memory proposal",children:"reject"===u?"Rejecting…":"Reject"})]}):null,P?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,onClick:()=>{null===u&&(h(null),g(null),b(!0))},"aria-label":"Edit memory body, tags, or sensitivity",children:"Edit"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,onClick:()=>{null===u&&(h(null),g(null),y(!0))},"aria-label":"Create a correction proposal for this memory",children:"Correct"})]}),P?null:e.pinned?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"unpin"===u,onClick:R,"aria-label":"Unpin this memory",children:"unpin"===u?"Unpinning…":"Unpin"}):(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"pin"===u,onClick:E,"aria-label":"Pin this memory for priority retrieval",children:"pin"===u?"Pinning…":"Pin"}),L?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==u,"aria-busy":"archive"===u,onClick:$,"aria-label":"Archive this memory",children:"archive"===u?"Archiving…":"Archive"}):null,P?null:(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger","aria-disabled":null!==u,onClick:()=>{null===u&&(h(null),g(null),j(!0))},"aria-label":"Forget this memory permanently",children:"Forget"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger","aria-disabled":null!==u,onClick:()=>{null===u&&(h(null),g(null),N(!0))},"aria-label":"Delete this memory record",children:"Delete"}),null!==m?(0,n.jsx)("p",{role:"alert","aria-live":"assertive",className:"mc-action-error",children:m}):null,null!==f?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"mc-action-notice",children:f}):null,v?(0,n.jsx)(dH,{record:e,onSave:e=>{b(!1),t(e)},onClose:()=>{b(!1)}}):null,x?(0,n.jsx)(dH,{mode:"correct",record:e,correctMemoryImpl:d,onSave:A,onClose:()=>{y(!1)}}):null,w?(0,n.jsx)(dY,{record:e,onComplete:()=>{j(!1),t(null)},onClose:()=>{j(!1)}}):null,k?(0,n.jsx)(dY,{mode:"delete",record:e,deleteMemoryImpl:c,onComplete:()=>{N(!1),t(null)},onClose:()=>{N(!1)}}):null]})}function dJ(e){return new Date(e).toLocaleString()}function dX({label:e,value:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("dt",{className:"mc-meta-label",children:e}),(0,n.jsx)("dd",{className:"mc-meta-value",children:t})]})}function dQ({provenance:e}){return(0,n.jsxs)("section",{"aria-label":"Provenance",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Provenance"}),(0,n.jsxs)("dl",{className:"mc-meta",children:[(0,n.jsx)(dX,{label:"Source kind",value:e.sourceKind}),(0,n.jsx)(dX,{label:"Captured at",value:dJ(e.capturedAt)}),(0,n.jsx)(dX,{label:"Confidence",value:`${(100*e.confidence).toFixed(0)}%`}),(0,n.jsx)(dX,{label:"Sensitivity",value:e.sensitivity}),void 0!==e.captureRationale?(0,n.jsx)(dX,{label:"Rationale",value:e.captureRationale}):null,void 0!==e.modelIdentity?(0,n.jsx)(dX,{label:"Model",value:`${e.modelIdentity.provider} / ${e.modelIdentity.modelId}`}):null]})]})}function dZ({validity:e}){return(0,n.jsxs)("section",{"aria-label":"Validity",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Validity"}),(0,n.jsxs)("dl",{className:"mc-meta",children:[(0,n.jsx)(dX,{label:"Valid from",value:dJ(e.validFrom)}),(0,n.jsx)(dX,{label:"Valid until",value:void 0!==e.validUntil?dJ(e.validUntil):"No expiry"})]})]})}function d0({tags:e}){return 0===e.length?(0,n.jsx)("span",{className:"mc-meta-empty",children:"No tags"}):(0,n.jsx)("ul",{className:"mc-tags","aria-label":"Tags",children:e.map(e=>(0,n.jsx)("li",{className:"mc-tag",children:e},e))})}function d1({onBack:e,controlRef:t,children:a="Back to MemoriaViva"}){return void 0!==e?(0,n.jsx)("button",{ref:t,type:"button",className:"mc-back-link lk-btn lk-btn-ghost",onClick:e,children:a}):(0,n.jsx)(dj.default,{ref:t,href:"/memoriaviva",className:"mc-back-link lk-btn lk-btn-ghost","aria-label":"Back to MemoriaViva",children:a})}function d2({record:e,onBack:t}){return(0,n.jsxs)("header",{className:"mc-detail-header",children:[(0,n.jsxs)("div",{className:"mc-detail-title-row",children:[(0,n.jsxs)("h1",{className:"lk-title",style:{flex:1},children:[dz[e.type]," memory"]}),(0,n.jsx)("span",{className:`mc-badge mc-badge-${e.status}`,children:e.status}),e.pinned?(0,n.jsx)("span",{"aria-label":"Pinned",className:"mc-badge mc-badge-pinned",children:"Pinned"}):null]}),(0,n.jsx)(d1,{onBack:t,children:"Back"})]})}function d4({id:e,fetchMemoryImpl:t=t9,onBack:l}){let[i,r]=(0,a.useState)(null),[s,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!1),m=(0,a.useRef)(null),h=(0,a.useCallback)(e=>{m.current=e},[]),f=(0,a.useCallback)(e=>{null===e&&p(!0),r(e)},[]);(0,a.useEffect)(()=>{u&&null===i&&m.current?.focus()},[u,i]);let g=(0,a.useCallback)(async()=>{o(!0),d(null);try{let n=await t(e);r(n.memory)}catch(e){d(dN(e))}finally{o(!1)}},[e,t]);return((0,a.useEffect)(()=>{g()},[g]),s)?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading memory…"}):null!==c?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[c,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{g()},children:"Retry"})]}),(0,n.jsx)("p",{children:(0,n.jsx)(d1,{onBack:l})})]}):null===i?(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:u?"Memory removed":"Memory not found"}),(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-empty-body",children:u?"The memory was forgotten or deleted and is no longer available.":"This memory may have been deleted. Open a memory from the list instead."}),(0,n.jsx)("p",{children:(0,n.jsx)(d1,{onBack:l,controlRef:h})})]})}):(0,n.jsxs)("article",{"aria-label":`Memory record: ${i.body.slice(0,60)}`,className:"mc-detail",children:[(0,n.jsx)(d2,{record:i,onBack:l}),(0,n.jsxs)("section",{"aria-label":"Memory body",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Content"}),(0,n.jsx)("p",{className:"mc-body-text",children:i.body})]}),(0,n.jsxs)("section",{"aria-label":"Details",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Details"}),(0,n.jsxs)("dl",{className:"mc-meta",children:[(0,n.jsx)(dX,{label:"ID",value:(0,n.jsx)("code",{className:"mc-code",children:i.id})}),(0,n.jsx)(dX,{label:"Scope",value:function(e){switch(e.kind){case"user":return`user:${e.userId}`;case"workspace":return`workspace:${e.workspaceId}`;case"project":return`project:${e.projectId}`;case"workflow":return`workflow:${e.workflowDefinitionId}`;case"global":return"global";default:return"unknown"}}(i.scope)}),(0,n.jsx)(dX,{label:"Type",value:dz[i.type]}),(0,n.jsx)(dX,{label:"Created",value:dJ(i.createdAt)}),(0,n.jsx)(dX,{label:"Updated",value:dJ(i.updatedAt)}),void 0!==i.staleReason?(0,n.jsx)(dX,{label:"Stale reason",value:(0,n.jsx)("em",{children:i.staleReason})}):null]})]}),(0,n.jsx)(dQ,{provenance:i.provenance}),(0,n.jsx)(dZ,{validity:i.validity}),(0,n.jsxs)("section",{"aria-label":"Tags",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Tags"}),(0,n.jsx)(d0,{tags:i.tags})]}),(0,n.jsxs)("section",{"aria-label":"Actions",className:"mc-section",children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Actions"}),(0,n.jsx)(dG,{record:i,onRecordChange:f})]})]})}var d3=e.i(18566);let d6={proposed:"mc-badge-proposed",accepted:"mc-badge-accepted",conflicted:"mc-badge-conflicted",rejected:"mc-badge-rejected",archived:"mc-badge-archived",forgotten:"mc-badge-forgotten",superseded:"mc-badge-superseded",expired:"mc-badge-expired"};function d5({status:e}){let t=d6[e]??"mc-badge-default";return(0,n.jsx)("span",{className:`mc-badge ${t}`,children:e})}function d8({record:e,onOpenDetail:t}){var a;let l=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"mc-row-main",children:[(0,n.jsx)("span",{className:"mc-row-body",title:e.body,children:e.body}),(0,n.jsxs)("div",{className:"mc-row-meta",children:[(0,n.jsx)("span",{className:"mc-row-type",children:dz[e.type]}),(0,n.jsx)("span",{className:"mc-row-scope",children:dO[e.scope.kind]}),(0,n.jsxs)("span",{className:"mc-row-source",children:["Source ",e.provenance.sourceKind]}),(0,n.jsx)("span",{className:"mc-row-confidence",children:(a=e.provenance.confidence,`${(100*a).toFixed(0)}% confidence`)}),(0,n.jsxs)("span",{className:"mc-row-sensitivity",children:["Sensitivity ",e.provenance.sensitivity]}),e.pinned?(0,n.jsx)("span",{className:"mc-badge mc-badge-pinned",children:"Pinned"}):null]})]}),(0,n.jsx)(d5,{status:e.status})]});return(0,n.jsx)("li",{children:void 0!==t?(0,n.jsx)("button",{type:"button",className:"mc-row mc-row-button",onClick:()=>t(e.id),children:l}):(0,n.jsx)(dj.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e.id)}`,className:"mc-row",children:l})})}function d7({hasFilters:e}){return(0,n.jsx)("div",{"data-testid":"memory-empty-state",className:"lk-empty",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No memories found"}),(0,n.jsx)("p",{className:"lk-empty-body",children:e?"Try removing some filters to see more memories.":"Memories will appear here once the system captures them from your conversations and workflows."})]})})}function d9({filters:e,onFilterChange:t,fetchMemoriesImpl:l=t3,onOpenDetail:i,onOpenConsolidation:r,onOpenReviewQueue:s,policyEnabled:o,onPolicyEnabledChange:c,showWorkspaceBackLink:d=!0}){let[u,p]=(0,a.useState)([]),[m,h]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(!0),x=o??v,y=e.scope.length>0||e.type.length>0||e.status.length>0||e.sensitivity.length>0,w=(0,a.useCallback)(async e=>{h(!0),g(null);try{let t=await l(e);p(t.memories)}catch(e){g(dN(e))}finally{h(!1)}},[l]);return(0,a.useEffect)(()=>{w(e)},[e,w]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header",children:[(0,n.jsx)("h1",{className:"lk-title",children:"MemoriaViva"}),(0,n.jsxs)("div",{className:"mc-view-actions",children:[(0,n.jsxs)("div",{className:"mc-policy-switch",children:[(0,n.jsx)(lM,{on:x,onChange:c??b,label:"Enable MemoriaViva policy"}),(0,n.jsxs)("span",{children:["Policy ",x?"on":"off"]})]}),d?(0,n.jsx)(dj.default,{href:"/",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to Workspace"}):null,void 0!==r?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg",onClick:r,children:"Consolidation"}):(0,n.jsx)(dj.default,{href:"/memoriaviva/consolidation",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Consolidation"}),void 0!==s?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg mc-queue-link",onClick:s,children:"Review queue"}):(0,n.jsx)(dj.default,{href:"/memoriaviva/review-queue",className:"lk-btn lk-btn-ghost lk-btn-lg mc-queue-link",children:"Review queue"})]})]}),(0,n.jsx)(dW,{filters:e,onChange:t}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:m||null!==f?null:`${u.length.toString()} ${1===u.length?"memory":"memories"} found`}),(0,n.jsx)("section",{"aria-label":"Memory records","aria-busy":m,style:{flex:1,minHeight:0,overflowY:"auto"},children:m&&0===u.length?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading memories…"}):null!==f?(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[f,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{w(e)},children:"Retry"})]}):0===u.length?(0,n.jsx)(d7,{hasFilters:y}):(0,n.jsx)("ul",{"aria-label":"Memory list",style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:4,opacity:m?.6:1,transition:"opacity 0.15s ease"},children:u.map(e=>(0,n.jsx)(d8,{record:e,onOpenDetail:i},e.id))})})]})}function ue({record:e,busyAction:t,rowError:a,onAccept:l,onReject:i,onArchive:r,onOpenDetail:s}){let o=`memory-review-body-${e.id}`,c=`View details for memory ${e.id}: ${e.body.slice(0,80)}`,d=void 0!==e.staleReason||"expired"===e.status;return(0,n.jsx)("li",{"data-review-row-id":e.id,children:(0,n.jsxs)("article",{className:"mc-review-row",children:[(0,n.jsxs)("div",{className:"mc-review-body",children:[(0,n.jsx)("p",{id:o,className:"mc-row-body",children:e.body}),(0,n.jsxs)("div",{className:"mc-row-meta",children:[(0,n.jsx)("span",{className:"mc-row-type",children:dz[e.type]}),(0,n.jsx)("span",{className:"mc-row-scope",children:dO[e.scope.kind]}),(0,n.jsx)("span",{className:`mc-badge mc-badge-${e.status}`,children:e.status}),d?(0,n.jsxs)("span",{className:"mc-row-stale",children:["Stale",void 0!==e.staleReason?`: ${e.staleReason}`:""]}):null,void 0!==s?(0,n.jsx)("button",{type:"button",className:"mc-row-detail-link mc-link-button","aria-label":c,onClick:()=>s(e.id),children:"View details"}):(0,n.jsx)(dj.default,{href:`/memoriaviva/detail?id=${encodeURIComponent(e.id)}`,className:"mc-row-detail-link","aria-label":c,children:"View details"})]}),null!==a?(0,n.jsx)("p",{role:"alert",className:"mc-action-error",children:a}):null]}),(0,n.jsx)("div",{className:"mc-review-actions",role:"group","aria-labelledby":o,children:"proposed"===e.status?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary","aria-disabled":null!==t,"aria-busy":"accept"===t,onClick:()=>{null===t&&l(e)},children:"accept"===t?"Approving…":"Approve"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==t,"aria-busy":"reject"===t,onClick:()=>{null===t&&i(e)},children:"reject"===t?"Rejecting…":"Reject"})]}):"conflicted"===e.status?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==t,"aria-busy":"reject"===t,onClick:()=>{null===t&&i(e)},children:"reject"===t?"Rejecting…":"Reject conflict"}):(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost","aria-disabled":null!==t,"aria-busy":"archive"===t,onClick:()=>{null===t&&r(e)},children:"archive"===t?"Archiving…":"Archive stale"})})]})})}function ut({fetchQueueImpl:e=t6,acceptImpl:t=ns,rejectImpl:l=no,archiveImpl:i=na,onBack:r,onOpenDetail:s}){let[o,c]=(0,a.useState)([]),[d,u]=(0,a.useState)(!0),[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)({}),[g,v]=(0,a.useState)({}),[b,x]=(0,a.useState)(""),y=(0,a.useRef)(null),w=(0,a.useRef)(null),j=(0,a.useRef)(null),k=(0,a.useCallback)(async()=>{u(!0),m(null);try{let t=await e();c(t.memories),f({}),v({})}catch(e){m(dN(e))}finally{u(!1)}},[e]);(0,a.useEffect)(()=>{k()},[k]);let N=(0,a.useCallback)(e=>{f(t=>{let n={...t};return delete n[e],n}),v(t=>{let n={...t};return delete n[e],n})},[]),S=(0,a.useCallback)(e=>{let t=o.findIndex(t=>t.id===e),n=o[t+1]??o[t-1];j.current=void 0!==n?n.id:"",c(t=>t.filter(t=>t.id!==e)),N(e)},[o,N]);(0,a.useEffect)(()=>{let e=j.current;if(null===e)return;j.current=null;let t=""===e?null:y.current?.querySelector(`[data-review-row-id="${CSS.escape(e)}"]`)??null,n=null===t?null:t.querySelector("button");null!==n?n.focus():w.current?.focus()},[o]);let C=(0,a.useCallback)(async(e,n)=>{let a=e.id;f(e=>({...e,[a]:n})),v(e=>{let t={...e};return delete t[a],t});try{"accept"===n?await t(a):"archive"===n?await i(a,"archived stale memory from review queue"):await l(a,"conflicted"===e.status?"rejected conflict from review queue":"rejected from review queue"),S(a),x("accept"===n?"Memory approved":"archive"===n?"Memory archived":"Memory rejected")}catch(e){v(t=>({...t,[a]:dN(e)})),f(e=>{let t={...e};return delete t[a],t})}},[t,i,l,S]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header mc-review-header",children:[(0,n.jsx)("h1",{className:"lk-title",tabIndex:-1,ref:w,children:"Review queue"}),(0,n.jsxs)("span",{role:"status","aria-live":"polite",className:"mc-badge-count",children:[o.length.toString()," awaiting review"]}),void 0!==r?(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg","aria-label":"Back to MemoriaViva",onClick:r,children:"Back"}):(0,n.jsx)(dj.default,{href:"/memoriaviva",className:"lk-btn lk-btn-ghost lk-btn-lg","aria-label":"Back to MemoriaViva",children:"Back"})]}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:b}),(0,n.jsx)("section",{"aria-label":"Memories awaiting review","aria-busy":d,style:{flex:1,minHeight:0,overflowY:"auto"},children:d?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading review queue…"}):null!==p?(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[p,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:()=>{k()},children:"Retry"})]}):0===o.length?(0,n.jsx)("div",{"data-testid":"review-queue-empty",className:"lk-empty",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"Queue is clear"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"No memories are waiting for review. Proposed, conflicted, and stale memories appear here."})]})}):(0,n.jsx)("ul",{ref:y,"aria-label":"Review queue",style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:8},children:o.map(e=>(0,n.jsx)(ue,{record:e,busyAction:h[e.id]??null,rowError:g[e.id]??null,onAccept:e=>{C(e,"accept")},onReject:e=>{C(e,"reject")},onArchive:e=>{C(e,"archive")},onOpenDetail:s},e.id))})})]})}let un={scope:[],type:[],status:[],sensitivity:[]};function ua(){let[e,t]=(0,a.useState)({kind:"list"}),[l,i]=(0,a.useState)(un),[r,s]=(0,a.useState)(!0),o=(0,a.useCallback)(()=>{t({kind:"list"})},[]),c=(0,a.useCallback)(e=>{t({kind:"detail",id:e})},[]);return(0,n.jsx)("div",{className:"memoria-window",children:"list"===e.kind?(0,n.jsx)(d9,{filters:l,onFilterChange:i,onOpenDetail:c,onOpenConsolidation:()=>t({kind:"consolidation"}),onOpenReviewQueue:()=>t({kind:"reviewQueue"}),policyEnabled:r,onPolicyEnabledChange:s,showWorkspaceBackLink:!1}):"detail"===e.kind?(0,n.jsx)(d4,{id:e.id,onBack:o}):"consolidation"===e.kind?(0,n.jsx)(dP,{onBack:o,onOpenDetail:c}):(0,n.jsx)(ut,{onBack:o,onOpenDetail:c})})}var ul=e.i(8245),ui=e.i(96688),ur=e.i(61774);function us(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])"))}function uo({capsule:e,checked:t,disabled:a,onToggle:l}){return(0,n.jsx)("li",{className:"lk-compose-member",children:(0,n.jsxs)("label",{className:"lk-compose-member-label",children:[(0,n.jsx)("input",{type:"checkbox",checked:t,disabled:a,onChange:()=>l(e.id)}),(0,n.jsx)("span",{className:"lk-compose-member-name",title:e.displayName,children:e.displayName}),(0,n.jsx)("span",{className:"lk-badge","data-state":e.lifecycleState,children:ui.STATUS_LABELS[e.lifecycleState]})]})})}function uc({capsules:e,onCancel:t,onCreated:l,createImpl:i=lD.createCapsuleSet}){let r,s=(0,a.useId)(),o=(0,a.useId)(),c=(0,a.useId)(),d=(0,a.useRef)(null),[u,p]=(0,a.useState)(""),[m,h]=(0,a.useState)(new Set),[f,g]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null);function x(e){h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),null!==v&&b(null)}async function y(e){var t;e.preventDefault();let n=(t=m.size,0===u.trim().length?"Set name is required.":0===t?"Select at least one capsule to combine.":t>16?"A set can hold at most 16 capsules.":null);if(null!==n)return void b(n);g(!0),b(null);try{await i({displayName:u.trim(),capsuleIds:[...m]}),l()}catch(e){b((0,ur.formatError)(e))}finally{g(!1)}}(0,ul.useModalInteractionLock)(),(0,a.useEffect)(()=>{let e=document.activeElement,t=d.current;return null!==t&&us(t)[0]?.focus(),()=>e?.focus?.()},[d]),(0,a.useEffect)(()=>{let e=d.current;if(null!==e)return e.addEventListener("keydown",n),()=>e.removeEventListener("keydown",n);function n(n){if("Escape"===n.key&&!f){n.preventDefault(),t();return}if("Tab"!==n.key)return;let a=us(e);if(0===a.length)return void n.preventDefault();let l=a[0],i=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),i?.focus()):n.shiftKey||document.activeElement!==i||(n.preventDefault(),l?.focus())}},[d,f,t]),r=(0,a.useRef)(!1),(0,a.useEffect)(()=>{let e=d.current;null!==e&&(f?(r.current=!0,e.focus()):r.current&&(r.current=!1,us(e)[0]?.focus()))},[d,f]);let w="Set name is required."===v,j="Select at least one capsule to combine."===v;return(0,tP.createPortal)((0,n.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,n.jsxs)("div",{ref:d,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":s,tabIndex:-1,children:[(0,n.jsx)("h2",{id:s,className:"mc-dialog-title",children:"Combine capsules into a set"}),(0,n.jsxs)("form",{onSubmit:e=>void y(e),children:[(0,n.jsxs)("label",{className:"mc-dialog-field",htmlFor:o,children:[(0,n.jsx)("span",{className:"mc-dialog-label",children:"Set name"}),(0,n.jsx)("input",{id:o,className:"mc-dialog-input",value:u,disabled:f,autoComplete:"off","aria-invalid":w,"aria-describedby":w?c:void 0,onChange:e=>{p(e.target.value),null!==v&&b(null)}})]}),(0,n.jsxs)("fieldset",{className:"lk-compose-fieldset",disabled:f,"aria-invalid":j,"aria-describedby":j?c:void 0,children:[(0,n.jsxs)("legend",{className:"mc-dialog-label",children:["Capsules (",m.size.toString(),"/","16",")"]}),0===e.length?(0,n.jsx)("p",{className:"lkd-empty-note",children:"No capsules available to combine."}):(0,n.jsx)("ul",{className:"lk-compose-member-list","aria-label":"Selectable capsules",children:e.map(e=>(0,n.jsx)(uo,{capsule:e,checked:m.has(e.id),disabled:f,onToggle:x},e.id))})]}),null!==v?(0,n.jsx)("div",{id:c,role:"alert","aria-live":"assertive",className:"mc-dialog-error",children:v}):null,(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:f,onClick:t,children:"Cancel"}),(0,n.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary",disabled:f,"aria-busy":f,children:f?"Combining…":"Combine"})]})]})]})}),document.body)}var ud=e.i(80010);function uu({message:e,onRetry:t,onDismiss:a}){return(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert",children:[e,void 0!==t?(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":"Retry loading capsules",className:"lk-alert-retry",children:"Retry"}):null,void 0!==a?(0,n.jsx)("button",{type:"button",onClick:a,"aria-label":"Dismiss error message",className:"lk-alert-retry",children:"Dismiss"}):null]})}function up(e){return Array.from(e.querySelectorAll("button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex='-1'])"))}function um({busy:e,error:t,onCancel:l,onSubmit:i}){let r=(0,a.useId)(),s=(0,a.useId)(),o=(0,a.useId)(),c=(0,a.useId)(),d=(0,a.useRef)(null),u=(0,a.useRef)(null),p=(0,a.useRef)(null),[m,h]=(0,a.useState)(""),[f,g]=(0,a.useState)(null);(0,ul.useModalInteractionLock)(),(0,a.useEffect)(()=>(p.current=document.activeElement,u.current?.focus(),()=>{p.current?.focus?.()}),[]),(0,a.useEffect)(()=>{let t=d.current;if(null===t)return;let n=n=>{if("Escape"===n.key&&!e){n.preventDefault(),l();return}if("Tab"!==n.key)return;let a=up(t);if(0===a.length)return void n.preventDefault();let i=a[0],r=a[a.length-1];n.shiftKey&&document.activeElement===i?(n.preventDefault(),r?.focus()):n.shiftKey||document.activeElement!==r||(n.preventDefault(),i?.focus())};return t.addEventListener("keydown",n),()=>t.removeEventListener("keydown",n)},[e,l]);let v=(0,a.useRef)(!1);async function b(e){e.preventDefault();let t=m.trim();0===t.length?g("Capsule display name is required."):(g(null),await i(t))}(0,a.useEffect)(()=>{let t=d.current;null!==t&&(e?(v.current=!0,t.focus()):v.current&&(v.current=!1,up(t)[0]?.focus()))},[e]);let x=f??t;return(0,tP.createPortal)((0,n.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,n.jsxs)("div",{ref:d,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":r,"aria-describedby":s,tabIndex:-1,children:[(0,n.jsx)("h2",{id:r,className:"mc-dialog-title",children:"Create capsule"}),(0,n.jsx)("p",{id:s,className:"mc-dialog-body",children:"Name the capsule. After creating it, connect a source and start indexing from the capsule page."}),(0,n.jsxs)("form",{onSubmit:e=>void b(e),children:[(0,n.jsxs)("label",{className:"mc-dialog-field",htmlFor:o,children:[(0,n.jsx)("span",{className:"mc-dialog-label",children:"Capsule display name"}),(0,n.jsx)("input",{id:o,ref:u,className:"mc-dialog-input",value:m,disabled:e,autoComplete:"off","aria-invalid":null!==x,"aria-describedby":null!==x?c:void 0,onChange:e=>{h(e.target.value),null!==f&&g(null)}})]}),null!==x?(0,n.jsx)("div",{id:c,role:"alert","aria-live":"assertive",className:"mc-dialog-error",children:x}):null,(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:e,onClick:l,children:"Cancel"}),(0,n.jsx)("button",{type:"submit",className:"lk-btn lk-btn-primary",disabled:e,children:e?"Creating…":"Create capsule"})]})]})]})}),document.body)}function uh({capsuleName:e,onCancel:t,onConfirm:l}){let i=(0,a.useId)(),r=(0,a.useId)(),s=(0,a.useRef)(null);return(0,ul.useModalInteractionLock)(),(0,a.useEffect)(()=>{let e=document.activeElement,t=s.current;return null!==t&&up(t)[0]?.focus(),()=>e?.focus?.()},[]),(0,a.useEffect)(()=>{let e=s.current;if(null===e)return;let n=n=>{if("Escape"===n.key){n.preventDefault(),t();return}if("Tab"!==n.key)return;let a=up(e);if(0===a.length)return void n.preventDefault();let l=a[0],i=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),i?.focus()):n.shiftKey||document.activeElement!==i||(n.preventDefault(),l?.focus())};return e.addEventListener("keydown",n),()=>e.removeEventListener("keydown",n)},[t]),(0,tP.createPortal)((0,n.jsx)("div",{className:"mc-dialog-backdrop",role:"presentation",children:(0,n.jsxs)("div",{ref:s,className:"mc-dialog",role:"dialog","aria-modal":"true","aria-labelledby":i,"aria-describedby":r,tabIndex:-1,children:[(0,n.jsx)("h2",{id:i,className:"mc-dialog-title",children:"Disconnect capsule"}),(0,n.jsxs)("p",{id:r,className:"mc-dialog-body",children:['Disconnect "',e,'"? The capsule keeps its index, but the source link is removed.']}),(0,n.jsxs)("div",{className:"mc-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:t,children:"Cancel"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",onClick:l,children:"Disconnect"})]})]})}),document.body)}function uf({state:e}){return(0,n.jsx)("span",{className:"lk-badge","data-state":e,children:ui.STATUS_LABELS[e]})}function ug({capsule:e,busy:t,busyKind:l,onStart:i,onCancel:r}){let{id:s,displayName:o,lifecycleState:c,sourceCount:d}=e,u=(0,a.useId)();if("indexing"===c)return(0,n.jsx)("button",{type:"button",disabled:t,"aria-busy":"cancel"===l,"aria-label":`Cancel indexing for capsule ${o}`,onClick:()=>{r(s)},className:"lk-btn lk-btn-ghost",children:"cancel"===l?"Cancelling…":"Cancel"});let p=d>0;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",disabled:t,"aria-disabled":!p||void 0,"aria-busy":"index"===l,"aria-label":`Start indexing capsule ${o}`,"aria-describedby":p?void 0:u,title:p?void 0:"Attach a source before indexing this capsule.",onClick:()=>{p&&i(s)},className:"lk-btn lk-btn-primary",children:"index"===l?"Indexing…":"Index"}),p?null:(0,n.jsx)("span",{id:u,className:"visually-hidden",children:"Attach a source before indexing."})]})}function uv({capsule:e,busy:t,busyKind:a,onStart:l,onCancel:i,onDisconnect:r,onHealth:s,onAddToWorkspace:o}){let{id:c,displayName:d}=e;return(0,n.jsxs)("div",{role:"group","aria-label":`Actions for capsule ${d}`,className:"lk-capsule-actions",children:[(0,n.jsx)(ug,{capsule:e,busy:t,busyKind:a,onStart:l,onCancel:i}),(0,n.jsx)("button",{type:"button",disabled:t,"aria-label":`Add capsule ${d} to workspace`,onClick:()=>{o(c)},className:"lk-btn lk-btn-ghost",children:"Add to workspace"}),(0,n.jsx)("button",{type:"button",disabled:t,"aria-label":`Open details for capsule ${d}`,onClick:()=>{s(c)},className:"lk-btn lk-btn-ghost",children:"Details"}),(0,n.jsx)("button",{type:"button",disabled:t,"aria-busy":"disconnect"===a,"aria-label":`Disconnect capsule ${d}`,onClick:()=>{r(c)},className:"lk-btn lk-btn-danger",children:"disconnect"===a?"Disconnecting…":"Disconnect"})]})}function ub(e){return e instanceof Element&&null!==e.closest(".lk-capsule-actions,a,input,select,textarea")}function ux(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window")}function uy(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(td,{detail:n}))}function uw({capsule:e,busy:t,busyKind:l,onStart:i,onCancel:r,onDisconnect:s,onHealth:o,onAddToWorkspace:c}){let[d,u]=(0,a.useState)(null),p=(0,a.useRef)(!1),m=(0,a.useRef)(!1),h={kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},f=e=>{m.current||(m.current=!0,uy(h,e),window.setTimeout(()=>{m.current=!1},250))},g=(t,n)=>{p.current=!0;let a=!1,l=l=>{let i=l.clientX-t,r=l.clientY-n;!a&&6>Math.hypot(i,r)||(a=!0,document.body.style.cursor="grabbing",u({x:l.clientX,y:l.clientY,label:e.displayName,state:e.lifecycleState}))},i=e=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",i),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",i),p.current=!1,document.body.style.cursor="",u(null),a&&ux(e.clientX,e.clientY)&&f(e)};window.addEventListener("pointermove",l),window.addEventListener("pointerup",i),window.addEventListener("mousemove",l),window.addEventListener("mouseup",i)};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("article",{"aria-label":`Capsule: ${e.displayName}`,className:"lk-capsule-row",children:[(0,n.jsxs)("button",{type:"button",className:"lk-capsule-drag-handle","aria-label":`Drag capsule ${e.displayName} to workspace`,title:"Drag to the workspace to create a connector card",onPointerDown:e=>{ub(e.target)||B(e)&&(e.preventDefault(),e.stopPropagation(),g(e.clientX,e.clientY))},onMouseDown:e=>{p.current||ub(e.target)||B(e)&&(e.preventDefault(),e.stopPropagation(),g(e.clientX,e.clientY))},onDragStart:t=>{ub(t.target)?t.preventDefault():(t.dataTransfer.effectAllowed="copy",t.dataTransfer.setData(tc,JSON.stringify(h)),t.dataTransfer.setData("text/plain",e.displayName))},onDragEnd:e=>{ux(e.clientX,e.clientY)&&f(e)},draggable:!0,children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"lk-capsule-icon",children:"⬡"}),(0,n.jsxs)("span",{className:"lk-capsule-info",children:[(0,n.jsx)("span",{className:"lk-capsule-name",title:e.displayName,children:e.displayName}),(0,n.jsx)(uf,{state:e.lifecycleState})]})]}),(0,n.jsx)(uv,{capsule:e,busy:t,busyKind:l,onStart:i,onCancel:r,onDisconnect:s,onHealth:o,onAddToWorkspace:c})]}),null!==d?(0,tP.createPortal)((0,n.jsxs)("div",{className:"lk-connector-drag-ghost",style:{left:d.x+14,top:d.y+14},"aria-hidden":"true",children:[(0,n.jsx)("span",{className:"lk-connector-drag-ghost-icon",children:"▣"}),(0,n.jsxs)("span",{className:"lk-connector-drag-ghost-copy",children:[(0,n.jsx)("span",{children:d.label}),(0,n.jsx)("small",{children:ui.STATUS_LABELS[d.state]})]})]}),document.body):null]})}function uj({creating:e,onCreateCapsule:t}){return(0,n.jsxs)("div",{"data-testid":"empty-state",className:"lk-empty",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"lk-empty-icon",children:"⬡"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No capsules yet"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"Create a capsule to start indexing your local knowledge sources."})]}),(0,n.jsx)("button",{type:"button",disabled:e,"aria-label":"Create your first knowledge capsule",onClick:t,className:"lk-btn lk-btn-primary lk-btn-xl",children:e?"Creating…":"Create your first capsule"})]})}function uk({capsules:e,isLoading:t,creating:a,actionBusy:l,actionKind:i,onCreateCapsule:r,onStartIndexing:s,onCancelIndexing:o,onDisconnect:c,onOpenHealth:d}){return t?(0,n.jsx)("p",{role:"status","aria-live":"polite",className:"lk-loading",children:"Loading capsules…"}):0===e.length?(0,n.jsx)(uj,{creating:a,onCreateCapsule:r}):(0,n.jsx)("ul",{"aria-label":"Knowledge capsule list",style:{display:"flex",flexDirection:"column",gap:8,listStyle:"none",padding:0,margin:0},children:e.map(e=>(0,n.jsx)("li",{style:{display:"block"},children:(0,n.jsx)(uw,{capsule:e,busy:l===e.id,busyKind:l===e.id?i:null,onStart:s,onCancel:o,onDisconnect:c,onHealth:d,onAddToWorkspace:()=>{let t=function(){let e=document.querySelector("main.workspace");if(!(e instanceof HTMLElement))return null;let t=e.getBoundingClientRect();return 0===t.width||0===t.height?null:{clientX:Math.round(t.left+t.width/2),clientY:Math.round(t.top+t.height/2)}}();null!==t&&uy({kind:"capsule",id:e.id,label:e.displayName,lifecycleState:e.lifecycleState},t)}})},e.id))})}function uN({creating:e,createDialogOpen:t,combineDialogOpen:l,combineDisabled:i,showBackToWorkspace:r,loadStatus:s,loadError:o,actionError:c,createError:d,reload:u,onCreateCapsule:p,onCombineCapsules:m,onDismissCreateError:h,onDismissActionError:f}){let g=(0,a.useId)();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("header",{className:"lk-header",children:[(0,n.jsx)("h1",{className:"lk-title",children:"Local Knowledge Connector"}),(0,n.jsxs)("div",{className:"lk-header-actions",children:[r?(0,n.jsx)(dj.default,{href:"/",className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Back to Workspace"}):null,(0,n.jsx)("button",{type:"button","aria-disabled":i,"aria-describedby":i?g:void 0,"aria-label":"Combine capsules into a set","aria-haspopup":"dialog","aria-expanded":l,title:i?"Create capsules first, then combine them into a set.":void 0,onClick:()=>{i||m()},className:"lk-btn lk-btn-ghost lk-btn-lg",children:"Combine capsules"}),i?(0,n.jsx)("span",{id:g,className:"visually-hidden",children:"Create capsules first, then combine them into a set."}):null,(0,n.jsx)("button",{type:"button",disabled:e,"aria-label":"Create a new knowledge capsule","aria-haspopup":"dialog","aria-expanded":t,onClick:p,className:"lk-btn lk-btn-primary lk-btn-lg",children:e?"Creating…":"Create capsule"})]})]}),"error"===s&&null!==o?(0,n.jsx)(uu,{message:o,onRetry:u}):null,null===d||t?null:(0,n.jsx)(uu,{message:d,onDismiss:h}),null!==c?(0,n.jsx)(uu,{message:c,onDismiss:f}):null]})}function uS(e){let t,l,{onOpenCapsule:i,showBackToWorkspace:r=!0}=e,[s,o]=(0,a.useState)(null),c=(0,a.useCallback)(e=>{void 0!==i?i(e):o(e)},[i]),{capsules:d,loadStatus:u,loadError:p,actionBusy:m,actionKind:h,actionError:f,creating:g,createError:v,reload:b,clearCreateError:x,clearActionError:y,handleStartIndexing:w,handleCancelIndexing:j,handleDisconnect:k,handleOpenHealth:N,handleCreateCapsule:S}=function(e){let{fetchCapsulesImpl:t=lD.fetchCapsules,createCapsuleImpl:n=lD.createCapsule,startIndexingImpl:l=lD.startIndexing,cancelIndexingImpl:i=lD.cancelIndexing,disconnectCapsuleImpl:r=lD.disconnectCapsule,onOpenCapsule:s}=e,{capsules:o,loadStatus:c,loadError:d,reload:u}=function(e){let[t,n]=(0,a.useState)([]),[l,i]=(0,a.useState)("loading"),[r,s]=(0,a.useState)(null),o=(0,a.useCallback)(async()=>{i("loading"),s(null);try{let t=await e();n(t.capsules),i("ready")}catch(e){s((0,ur.formatError)(e)),i("error")}},[e]);return(0,a.useEffect)(()=>{o()},[o]),{capsules:t,loadStatus:l,loadError:r,reload:function(){o()}}}(t),{actionBusy:p,actionKind:m,actionError:h,clearActionError:f,handleStartIndexing:g,handleCancelIndexing:v,handleDisconnect:b,handleOpenHealth:x}=function(e,t,n,l,i){let r=(0,d3.useRouter)(),[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null);async function m(t,n,a){o(t),d(n),p(null);try{await a(),e()}catch(e){p((0,ur.formatError)(e))}finally{o(null),d(null)}}return{actionBusy:s,actionKind:c,actionError:u,clearActionError:function(){p(null)},handleStartIndexing:function(e){m(e,"index",()=>t(e))},handleCancelIndexing:function(e){m(e,"cancel",()=>n(e))},handleDisconnect:function(e){m(e,"disconnect",()=>l(e))},handleOpenHealth:function(e){void 0!==i?i(e):r.push(`/local-knowledge/capsule?capsuleId=${encodeURIComponent(e)}`)}}}(u,l,i,r,s),{creating:y,createError:w,clearCreateError:j,handleCreateCapsule:k}=function(e,t){let[n,l]=(0,a.useState)(!1),[i,r]=(0,a.useState)(null);return{creating:n,createError:i,clearCreateError:function(){r(null)},handleCreateCapsule:async function n(n){l(!0),r(null);try{await e({displayName:n}),t()}catch(e){r((0,ur.formatError)(e))}finally{l(!1)}}}}(n,u);return{capsules:o,loadStatus:c,loadError:d,actionBusy:p,actionKind:m,actionError:h,creating:y,createError:w,reload:u,clearCreateError:j,clearActionError:f,handleStartIndexing:g,handleCancelIndexing:v,handleDisconnect:b,handleOpenHealth:x,handleCreateCapsule:k}}({...e,onOpenCapsule:c}),C="loading"===u,[I,E]=(0,a.useState)(!1),[R,$]=(0,a.useState)(!1),[A,T]=(0,a.useState)(null);async function L(e){try{await S(e),E(!1)}catch{}}return null!==s&&void 0===i?(0,n.jsxs)("div",{className:"lk-page",children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost lk-btn-lg lk-back-inline",onClick:()=>{o(null),b()},children:"Back to capsules"}),(0,n.jsx)(ud.CapsuleDetail,{capsuleId:s,onDeleted:()=>{o(null),b()}})]}):(0,n.jsxs)("div",{className:"lk-page",children:[(0,n.jsx)(uN,{creating:g,createDialogOpen:I,combineDialogOpen:R,combineDisabled:C||0===d.length,showBackToWorkspace:r,loadStatus:u,loadError:p,actionError:f,createError:v,reload:b,onCreateCapsule:()=>E(!0),onCombineCapsules:()=>$(!0),onDismissCreateError:x,onDismissActionError:y}),(0,n.jsx)("p",{role:"status",className:"visually-hidden",children:C||null!==p?null:(t=d.filter(e=>"indexing"===e.lifecycleState).length,l=`${d.length.toString()} capsule${1===d.length?"":"s"}`,t>0?`${l}, ${t.toString()} indexing`:l)}),(0,n.jsxs)("section",{"aria-label":"Knowledge capsules","aria-busy":C,style:{flex:1,minHeight:0,overflowY:"auto"},children:[(0,n.jsx)("h2",{className:"lk-section-head",children:"Knowledge Capsules"}),(0,n.jsx)(uk,{capsules:d,isLoading:C,creating:g,actionBusy:m,actionKind:h,onCreateCapsule:()=>E(!0),onStartIndexing:w,onCancelIndexing:j,onDisconnect:e=>T(d.find(t=>t.id===e)??null),onOpenHealth:N})]}),I?(0,n.jsx)(um,{busy:g,error:v,onCancel:()=>{E(!1),x()},onSubmit:L}):null,R?(0,n.jsx)(uc,{capsules:d,onCancel:()=>$(!1),onCreated:function(){$(!1),b()}}):null,null!==A?(0,n.jsx)(uh,{capsuleName:A.displayName,onCancel:()=>T(null),onConfirm:()=>{k(A.id),T(null)}}):null]})}function uC(e,t){let n=e[t];return"string"==typeof n?n:void 0}function uI(e,t){let n=uC(e,t);if(void 0===n||0===n.trim().length)return[];try{let e=JSON.parse(n);if(!Array.isArray(e))return[];return e.filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim())}catch{return[]}}function uE({cfg:e,ctx:t}){let l=n7({autoCreate:!1}),r=(0,a.useRef)(!1),s=uC(e,"chatId"),o=uC(e,"title"),{updateCfg:c}=t,{activeChat:d,activeProject:u,chats:p,loading:m,openChat:h,openNewChat:f}=l,g=void 0!==d&&"closed"!==d.status?d:void 0;(0,a.useEffect)(()=>{if(!m){if(void 0!==s){if(g?.id===s)return;let e=p.find(e=>e.id===s&&"closed"!==e.status);void 0!==e&&h(e);return}r.current||(r.current=!0,f(void 0,o).then(e=>{void 0!==e&&c({chatId:e.id,title:e.title})}).finally(()=>{r.current=!1}))}},[s,g?.id,p,m,h,f,o,c]),(0,a.useEffect)(()=>{m||void 0===s||g?.id!==s||g.title!==o&&c({title:g.title})},[g?.id,g?.title,s,m,o,c]);let v=void 0!==s&&!l.loading&&g?.id!==s&&!l.chats.some(e=>e.id===s&&"closed"!==e.status),b=l.loading||void 0!==s&&g?.id!==s,x=(0,a.useCallback)(e=>{if(void 0===e.runId)return;let n={runId:e.runId},a=e.workflowId??e.taskType;void 0!==a&&(n.workflow=a),u?.path!==void 0&&(n.workspaceRoot=u.path),t.openWindow("agents",n)},[u?.path,t]);return(0,n.jsx)(i,{value:l,children:v?(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"Chat not found"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"This conversation was deleted or is no longer available."})]}):b?(0,n.jsx)("div",{className:"lk-loading",children:"Opening chat..."}):(0,n.jsx)(ie,{mini:!0===t.mini,minimalChat:!0===t.minimalChat,compact:!0===t.compact,controlsNarrow:!0===t.controlsNarrow,barCompact:!0===t.barCompact,workflowCompact:!0===t.workflowCompact,linkedRoot:t.linkedRoot,onOpenRunResult:x})})}I("chat",(e,t)=>(0,n.jsx)(uE,{cfg:e,ctx:t})),I("chatHistory",(e,t)=>(0,n.jsx)(ir,{openChatWindow:e=>{t.openWindow("chat",{chatId:e.id,title:e.title})}})),I("project",()=>(0,n.jsx)(ii,{})),I("promptEnhancer",()=>(0,n.jsx)(iy,{})),I("search",()=>(0,n.jsx)(is,{})),I("plugins",()=>(0,n.jsx)(iN,{})),I("automations",()=>(0,n.jsx)(iR,{})),I("mobile",()=>(0,n.jsx)(i$,{})),I("inspector",()=>(0,n.jsx)(iA,{})),I("notifications",()=>(0,n.jsx)(iL,{})),I("resources",()=>(0,n.jsx)(iP,{})),I("activity",()=>(0,n.jsx)(iq,{})),I("keiko",()=>(0,n.jsx)(sd,{})),I("settings",()=>(0,n.jsx)(sg,{})),I("localKnowledge",()=>(0,n.jsx)(uS,{showBackToWorkspace:!1})),I("quality",(e,t)=>(0,n.jsx)(oW,{openRun:(e,n)=>{let a=void 0!==n?{[oC]:JSON.stringify(n.filter(oR))}:o$(oP({connectedFilePath:t.linkedFilePath??null,connectedRoot:t.linkedRoot,connectedRoots:t.linkedRoots,connectedCapsuleIds:t.linkedCapsuleIds,connectedCapsuleSetIds:t.linkedCapsuleSetIds,connectedFigmaSnapshotRunIds:t.linkedFigmaSnapshotRunIds,connectedFigmaSnapshotSources:t.linkedFigmaSnapshotSources,connectedImageSources:t.linkedImageSources}));t.openWindow("qiRun",{runId:e,...a})},connectedRoot:t.linkedRoot,connectedFilePath:t.linkedFilePath??null,connectedRoots:t.linkedRoots,connectedCapsuleIds:t.linkedCapsuleIds,connectedCapsuleSetIds:t.linkedCapsuleSetIds,connectedFigmaSnapshotRunIds:t.linkedFigmaSnapshotRunIds,connectedFigmaSnapshotSources:t.linkedFigmaSnapshotSources,connectedImageSources:t.linkedImageSources})),I("qiRun",(e,t)=>{let a=uC(e,"runId");if(void 0===a||""===a)return(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:"Open a run from the Quality Intelligence hub."})});let l=function(e){let t=oI(e,oC);if(void 0!==t&&t.length>0){let e=function(e){try{let t=JSON.parse(e);if(!Array.isArray(t)||!t.every(oR))return null;return t}catch{return null}}(t);if(null!==e)return e}return oP({connectedFilePath:oI(e,"connectedFilePath")??null,connectedRoot:oI(e,"connectedRoot")??null})}(e),i=o$(l);return(0,n.jsx)(cT,{runId:a,connectedSources:l,onRegenerated:e=>{t.openWindow("qiRun",{runId:e.runId,...i})}})}),I("relationships",()=>(0,n.jsx)(dw,{})),I("files",(e,t)=>{let a=uC(e,"root"),l=(e,n,a)=>{let l={activeFilePath:e??void 0,resolvedRoot:n??void 0};void 0!==a&&(l.activeDirectoryPath=a??void 0),t.updateCfg(l)},i=e=>{t.updateCfg({root:e,activeFilePath:void 0,activeDirectoryPath:void 0,resolvedRoot:void 0})},r=(e,n)=>{t.openWindow("editor",{root:e,file:n,openFiles:[n]})};return void 0!==a?(0,n.jsx)(iQ,{root:a,onActiveFileChange:l,onRootChange:i,onOpenFile:r}):(0,n.jsx)(iQ,{onActiveFileChange:l,onRootChange:i,onOpenFile:r})}),I("editor",(e,t)=>{let a=uC(e,"root"),l=uC(e,"file"),i=function(e,t){let n=e[t];if(!Array.isArray(n))return;let a=n.filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim());return a.length>0?a:void 0}(e,"openFiles"),r=uC(e,"layoutJson"),s={};return void 0!==a&&(s.root=a),void 0!==l&&(s.file=l),void 0!==i&&(s.openFiles=i),void 0!==r&&(s.layoutJson=r),s.linkedRoot=t.linkedRoot,s.linkedFilePath=t.linkedFilePath,s.linkedCapsuleIds=t.linkedCapsuleIds,s.linkedCapsuleSetIds=t.linkedCapsuleSetIds,s.windowId=t.windowId,s.onWorkspaceChange=e=>{t.updateCfg(e)},(0,n.jsx)(rC,{...s})}),I("browser",e=>{let t=uC(e,"url");return void 0!==t&&""!==t?(0,n.jsx)(rD,{url:t}):(0,n.jsx)(rD,{})}),I("terminal",e=>{let t=uC(e,"cwd"),a=uC(e,"projectPath"),l={};return void 0!==t&&(l.cwd=t),void 0!==a&&(l.projectPath=a),(0,n.jsx)(r_,{...l})}),I("review",(e,t)=>{let a=uC(e,"runId"),l=e=>{t.updateCfg({runId:e})};return void 0!==a&&""!==a?(0,n.jsx)(rZ,{runId:a,onRunIdSubmit:l}):(0,n.jsx)(rZ,{onRunIdSubmit:l})}),I("agents",(e,t)=>{var a;let l,i,r,s,o,c,d,u,p,m,h;return(0,n.jsx)(r8,{cfg:(r={},void 0!==(s=uC(a=e,"workflow"))&&(r.workflow=s),void 0!==(o=uC(a,"model"))&&(r.model=o),void 0!==(c=uC(a,"runId"))&&(r.runId=c),void 0!==(d=uC(a,"fingerprint"))&&(r.fingerprint=d),void 0!==(u=uC(a,"workspaceRoot"))&&(r.workspaceRoot=u),void 0!==(p=uC(a,"inputJson"))&&(r.inputJson=p),void 0!==(m="boolean"==typeof(l=a.keikoMode)?l:void 0)&&(r.keikoMode=m),void 0!==(h="ask"===(i=a.access)||"full"===i?i:void 0)&&(r.access=h),r),linkedRoot:t.linkedRoot,linkedFilePath:t.linkedFilePath})}),I("memoria",()=>(0,n.jsx)(ua,{})),I("integ",()=>(0,n.jsx)(r9,{})),I("figma",(e,t)=>{let a=uC(e,"snapshotRunId"),l=uI(e,"selectedScreenIdsJson"),i=uC(e,"selectedScreenName");return(0,n.jsx)(s2,{sourceWindowId:t.windowId,snapshotRunId:a,selectedScreenIds:l,selectedScreenName:i,openScreenSource:({snapshotRunId:e,screenId:n,name:a})=>{t.openWindow("figmaView",{snapshotRunId:e,selectedScreenIdsJson:JSON.stringify([n]),selectedScreenName:a})},updateCfg:e=>{t.updateCfg(e)}})}),I("figmaView",(e,t)=>{let a=uC(e,"snapshotRunId"),l=uI(e,"selectedScreenIdsJson"),i=uC(e,"selectedScreenName");return(0,n.jsx)(s2,{sourceWindowId:t.windowId,snapshotRunId:a,selectedScreenIds:l,selectedScreenName:i,updateCfg:e=>{t.updateCfg(e)}})}),I("figmaJson",e=>{let t=uC(e,"snapshotRunId"),a=uC(e,"screenId"),l=uC(e,"selectedScreenName");return(0,n.jsx)(s4,{snapshotRunId:t,screenId:a,screenName:l})}),I("figmaImage",e=>{let t=uC(e,"imageSrc"),a=uC(e,"selectedScreenName");return(0,n.jsx)(s3,{imageSrc:t,screenName:a})}),I("connector",(e,t)=>{let a=uC(e,"presentation"),l=uC(e,"selectedKind"),i=uC(e,"selectedId"),r=uC(e,"selectedLabel"),s=uC(e,"selectedState");return(0,n.jsx)(sk,{presentation:a,selectedKind:l,selectedId:i,selectedLabel:r,selectedState:s,onSelect:e=>{t.updateCfg(e)},onManageConnectors:()=>{t.openWindow("localKnowledge")}})});let uR={supported:{heading:"Install Keiko",body:"Keep Keiko in your app shelf for fast access.",install:"Install Keiko"},"ios-add-to-home":{heading:"Install Keiko",body:'On iOS Safari, tap Share, then "Add to Home Screen".',install:null}};function u$(){let{available:e,triggerInstall:t}=function(){let[e,t]=(0,a.useState)(!1),n=(0,a.useRef)(null);return(0,a.useEffect)(()=>{let e=e=>{e.preventDefault(),function(e){if("function"!=typeof e.prompt)return!1;let t=e.userChoice;return"object"==typeof t&&null!==t&&"function"==typeof t.then}(e)&&(n.current=e,t(!0))},a=()=>{localStorage.setItem("keiko.pwa.installed","true"),n.current=null,t(!1)};return window.addEventListener("beforeinstallprompt",e,{passive:!1}),window.addEventListener("appinstalled",a),()=>{window.removeEventListener("beforeinstallprompt",e),window.removeEventListener("appinstalled",a)}},[]),{available:e,triggerInstall:(0,a.useCallback)(async()=>{let e=n.current;if(null===e)return;await e.prompt();let{outcome:a}=await e.userChoice;"accepted"===a&&localStorage.setItem("keiko.pwa.installed","true"),n.current=null,t(!1)},[])}}(),[l,i]=(0,a.useState)(!1),[r]=(0,a.useState)(()=>{let e;return"u">typeof navigator?(e=navigator.userAgent.toLowerCase()).includes("crios/")?"manual":e.includes("chrome/")&&!e.includes("mobile")||e.includes("edg/")||e.includes("chromium/")?"supported":e.includes("firefox/")?"manual":e.includes("safari/")&&(e.includes("iphone")||e.includes("ipad")||e.includes("ipod"))?"ios-add-to-home":(e.includes("safari/")&&e.includes("macintosh"),"manual"):"manual"}),s=(0,a.useRef)(null),o=(0,a.useCallback)(()=>{localStorage.setItem("keiko.pwa.dismissed",new Date().toISOString()),i(!0)},[]),c=(0,a.useCallback)(async()=>{await t()},[t]),d=(0,a.useCallback)(e=>{"Escape"!==e.key||e.defaultPrevented||o()},[o]);if(l||window.matchMedia("(display-mode: standalone)").matches||"true"===localStorage.getItem("keiko.pwa.installed")||function(){let e=localStorage.getItem("keiko.pwa.dismissed");if(null===e)return!1;let t=Date.parse(e);return!!Number.isNaN(t)||Date.now()-t<2592e6}()||"supported"===r&&!e||"supported"!==r&&"ios-add-to-home"!==r)return null;let u=uR[r];return(0,n.jsx)("aside",{className:"install-banner",role:"region","aria-label":"Install Keiko",onKeyDown:d,children:(0,n.jsxs)("div",{className:"install-banner-body",children:[(0,n.jsxs)("div",{className:"install-banner-text",children:[(0,n.jsx)("span",{className:"install-banner-heading",children:u.heading}),(0,n.jsx)("span",{className:"install-banner-desc",children:u.body})]}),(0,n.jsxs)("div",{className:"install-banner-actions",children:[null!==u.install&&(0,n.jsx)("button",{ref:s,type:"button",className:"install-banner-btn-install",onClick:()=>void c(),children:u.install}),(0,n.jsx)("button",{type:"button",className:"install-banner-btn-dismiss",onClick:o,children:"Not now"})]})]})})}let uA="keiko.service-worker-update-reload-pending",uT=!1;function uL(){uT||function(){try{if("true"!==window.sessionStorage.getItem(uA))return!1;return window.sessionStorage.removeItem(uA),!0}catch{return!0}}()&&(uT=!0,window.location.reload())}function uP(e){let t=e.waiting;if(null!==t){try{window.sessionStorage.setItem(uA,"true")}catch{}try{t.postMessage({type:"KEIKO_ACTIVATE_WAITING_SERVICE_WORKER"})}catch{try{window.sessionStorage.removeItem(uA)}catch{}}}}function uM(e){return null===e||void 0===e.root?null:[e.root.replace(/\\/gu,"/").replace(/\/+$/u,""),e.kind,...e.relativePaths.map(e=>e.replace(/\\/gu,"/").replace(/^\/+|\/+$/gu,""))].join("\0")}function uD(e){return e.trim().replace(/\\/gu,"/").replace(/\/+$/u,"")}function uq(e,t){let n=uD(e),a=uD(t);if(0===a.length)return"";if(0===n.length)return/^\/+$/u.test(e.trim().replace(/\\/gu,"/"))?a.replace(/^\/+/u,""):"";let l=n.toLowerCase(),i=a.toLowerCase();return i===l?"":i.startsWith(`${l}/`)?a.slice(n.length+1).replace(/^\/+/u,""):null}let uF=["chat","connector","files","editor","agents"],uO=["chatHistory","memoria","settings","automations","mobile","inspector","activity","notifications","resources","localKnowledge","figma","quality","promptEnhancer","relationships"];function uz(){var e,t,l;let r,{theme:s,toggle:o}=function(){let[e,t]=(0,a.useState)(ae),[n,l]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{t(function(){try{let e=window.localStorage.getItem(n9);return"light"===e||"dark"===e?e:ae}catch{return ae}}()),l(!0)},[]),(0,a.useEffect)(()=>{if(n){"u">typeof document&&(document.documentElement.dataset.theme=e);try{window.localStorage.setItem(n9,e)}catch{}}},[e,n]),{theme:e,toggle:(0,a.useCallback)(()=>{t(e=>"light"===e?"dark":"light")},[])}}(),c=x(),d=n7({autoCreate:!1}),u=(0,a.useRef)(null),p=(0,a.useRef)(null),[m,h]=(0,a.useState)(at.DEFAULT_GROUNDING_LIMITS);(0,a.useEffect)(()=>{(0,w.fetchConfig)().then(e=>h(e.effectiveGroundingLimits)).catch(()=>void 0)},[]);let[f,g]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(null===f)return;let e=window.setTimeout(()=>g(null),1e4);return()=>window.clearTimeout(e)},[f]);let v=(0,a.useCallback)((e,t)=>(g(`Source limit reached — this chat already has ${String(e)} of ${String(t)} connected sources. Disconnect a source before connecting another.`),!1),[]),b=(0,a.useCallback)(e=>(g(e),!1),[]),j=(0,a.useCallback)(e=>{let t=function(e){if(e?.type!=="chat")return;let t=e.cfg.chatId;return"string"==typeof t&&t.length>0?t:void 0}(p.current?.find(t=>t.id===e));if(void 0===t)return;let n=d.chats.find(e=>e.id===t)??(d.activeChat?.id===t?d.activeChat:void 0);return n?.status==="closed"?void 0:n},[d.activeChat,d.chats]),k=(0,a.useCallback)(async(e,t,n=null)=>{var a;let l=j(e);if(void 0===l)return b("Open a ready chat window before connecting a source.");let i=null===n?e3(l):e4(e3(l),n),r=e6(l);if(i.some(e=>eZ(e,t))){if(null!==n){let e=await (0,w.updateChatConnectedScopes)(l.id,i.length>0?i:null);d.replaceChat(e.chat)}return!0}let s=e2(m);if(i.length+r.length>=s)return v(i.length+r.length,s);let o={...t,connectedAtMs:Date.now()},c=function(e,t,n=16){if(void 0===t.root)return null;let a=eJ(t.root);if(!eG(a))return null;let l=t.relativePaths.map(eQ),i={kind:t.kind,relativePaths:l,root:a,connectedAtMs:t.connectedAtMs};return e.some(e=>eZ(e,i))||e.length>=n?e:[...e,i]}(i,o,m.maxConnectedSources);if(null===c)return b("Choose a local folder before connecting it to chat.");if(c===i)return v(i.length+r.length,s);try{let e=await (0,w.updateChatConnectedScopes)(l.id,c);d.replaceChat(e.chat),g(null);let t=function(e){if(void 0===e.root)return null;let t=e.relativePaths[0]?.replace(/\\/gu,"/").replace(/^\/+/u,"");if(void 0===t||0===t.length)return e.root;let n=e.root.replace(/\\/gu,"/").replace(/\/+$/u,"");return`${n}/${t}`}(o);return null!==t&&(a=l.id,0!==a.length&&0!==t.length&&am({type:"reads-context",source:{kind:"chat",id:a},target:{kind:"workspace-path",id:t}},function(e,t){let n=0x811c9dc5,a=`${e}|${t}`;for(let e=0;e<a.length;e+=1)n=Math.imul(n^a.charCodeAt(e),0x1000193);return`rc-${(n>>>0).toString(36)}-${(65535&a.length).toString(36)}`}(a,t)).catch(e=>{})),!0}catch{return b("Keiko could not connect that source. Check that it is still available and try again.")}},[j,d,m,v,b]),N=function(e,t={}){var n,l,i,r,s,o,c,d,u;let[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(!1),[b,x]=(0,a.useState)([]),[y,w]=(0,a.useState)(null),[j,k]=(0,a.useState)(tn),N=(0,a.useRef)(3),S=(0,a.useRef)(null),C=(0,a.useRef)([]);C.current=p??[];let I=(0,a.useRef)([]);I.current=b;let R=(0,a.useRef)(null);R.current=y;let A=(0,a.useRef)(null),L=(0,a.useRef)(()=>void 0),{viewRef:P,worldVP:M,zoomTo:D,fitView:q,resetView:F,panBy:O,rect:z}=function({wsRef:e,view:t,winsRef:n,setView:l,setWins:i}){let r=(0,a.useRef)(t);r.current=t;let s=(0,a.useRef)(null),o=(0,a.useRef)(null);(0,a.useEffect)(()=>{tr(tt,t)},[t]),(0,a.useEffect)(()=>()=>{null!==o.current&&"function"==typeof window.cancelAnimationFrame&&window.cancelAnimationFrame(o.current)},[]);let c=(0,a.useCallback)(e=>{let t=s.current??r.current,n="function"==typeof e?e(t):e;if(r.current=n,s.current=n,"function"!=typeof window.requestAnimationFrame||"function"!=typeof window.cancelAnimationFrame){s.current=null,l(n);return}null===o.current&&(o.current=window.requestAnimationFrame(()=>{o.current=null;let e=s.current;s.current=null,null!==e&&l(e)}))},[l]);(0,a.useEffect)(()=>{let t=e.current;if(null===t)return;let n=e=>{if(e.metaKey||e.ctrlKey){var n;e.preventDefault();let a=(n=e.target)instanceof Element?n.closest(".window[data-window-id]")?.dataset.windowId??null:null;if(null!==a)return void i(t=>null===t?t:t.map(t=>{var n,l;let i,r;return t.id===a?(n=t,l=e.deltaY,(r=tl((i=n.zoom??1)*Math.exp(-(.0015*l))))===i?n:{...n,zoom:r}):t}));let l=t.getBoundingClientRect(),s=r.current,o=ts(e),d=ta(s.zoom*Math.exp(-(.0015*o.y))),u=(e.clientX-l.left-s.x)/s.zoom,p=(e.clientY-l.top-s.y)/s.zoom;return void c({zoom:d,x:e.clientX-l.left-u*d,y:e.clientY-l.top-p*d})}let a=e.target;if(a instanceof Element&&null!==a.closest(".window"))return;e.preventDefault();let l=ts(e);c(e=>({...e,x:e.x-l.x,y:e.y-l.y}))};return t.addEventListener("wheel",n,{passive:!1}),()=>{t.removeEventListener("wheel",n)}},[e,i,c]);let d=(0,a.useCallback)(()=>null===e.current?null:e.current.getBoundingClientRect(),[e]),u=(0,a.useCallback)(()=>{let e=d();if(null===e)return null;let t=r.current;return{x:-t.x/t.zoom,y:-t.y/t.zoom,w:e.width/t.zoom,h:e.height/t.zoom}},[d]),p=(0,a.useCallback)(e=>{let t=d();if(null===t)return;let n=r.current,a=t.width/2,l=t.height/2,i=(a-n.x)/n.zoom,s=(l-n.y)/n.zoom,o=ta(e);c({zoom:o,x:a-i*o,y:l-s*o})},[d,c]),m=(0,a.useCallback)(()=>{let e=d();null!==e&&c(function(e,t){let n=e.filter(e=>!0!==e.minimized);if(0===n.length)return{zoom:1,x:0,y:0};let a=1/0,l=1/0,i=-1/0,r=-1/0;for(let e of n)a=Math.min(a,e.x),l=Math.min(l,e.y),i=Math.max(i,e.x+e.w),r=Math.max(r,e.y+e.h);let s=Math.max(1,i-a),o=Math.max(1,r-l),c=ta(Math.min(1,Math.max(1,t.width-144)/s,Math.max(1,t.height-144)/o)),d=a+s/2,u=l+o/2;return{zoom:c,x:Math.round(t.width/2-d*c),y:Math.round(t.height/2-u*c)}}(n.current,e))},[d,n,c]);return{viewRef:r,worldVP:u,zoomTo:p,fitView:m,resetView:(0,a.useCallback)(()=>c({zoom:1,x:0,y:0}),[c]),panBy:(0,a.useCallback)((e,t)=>c(n=>({...n,x:n.x+e,y:n.y+t})),[c]),rect:d}}({wsRef:e,view:j,winsRef:C,setView:k,setWins:m});!function({wsRef:e,setWins:t,setConns:n,zc:l}){(0,a.useLayoutEffect)(()=>{let a=e.current;if(null===a)return;a.getBoundingClientRect();let i=null;try{i=function(e){if(null===e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t)||0===t.length)return null;let n=e_(t);return n.length>0?n:null}catch{return null}}(window.localStorage.getItem(e9))}catch{i=null}null===i&&(i=[]),l.current=0===i.length?1:Math.max(1,...i.map(e=>e.z)),t(i);try{n(function(e,t){if(null===e)return[];try{let n=JSON.parse(e);if(!Array.isArray(n))return[];return eU(n,t)}catch{return[]}}(window.localStorage.getItem(te),i))}catch{}},[e,t,n,l])}({wsRef:e,setWins:m,setConns:x,zc:N}),(0,a.useEffect)(()=>{null!==p&&tr(te,eU(b,p))},[b,p]),(0,a.useEffect)(()=>{null!==p&&x(e=>{let t=e.filter(e=>void 0!==p.find(t=>t.id===e.a)&&void 0!==p.find(t=>t.id===e.b));return t.length===e.length?e:t})},[p,x]),(0,a.useEffect)(()=>{null!==p&&tr(e9,e_(p))},[p]),function({setWins:e,rect:t,cancelConnectRef:n}){(0,a.useEffect)(()=>{let a=a=>{var l,i;if("Escape"===a.key)return void n.current();if(null!==(l=document.activeElement)&&("INPUT"===l.tagName||"TEXTAREA"===l.tagName||"SELECT"===l.tagName))return;let r=to[a.code];if((a.metaKey||a.ctrlKey)&&a.altKey&&void 0!==r){a.preventDefault(),e(e=>{var t;if(null===e||0===e.length)return e;let n=ti(e);if(null===n)return e;let a=(t=n.zoom??1,"0"===r?1:"-"===r||"_"===r?tl(t-.1):tl(t+.1));return e.map(e=>e.id===n.id?{...e,zoom:a}:e)});return}if(!/^Arrow/.test(a.key))return;let s=a.metaKey||a.ctrlKey,o=a.altKey;if(!s&&!o)return;a.preventDefault();let c=t();null!==c&&(i={key:a.key,shift:a.shiftKey},e(e=>{let t,n,a,l,r,s,d;if(null===e||0===e.length)return e;let u=ti(e);if(null===u)return e;let p=o?(t=i.shift?1:16,n=u.w,a=u.h,"ArrowRight"===i.key?n+=t:"ArrowLeft"===i.key?n-=t:"ArrowDown"===i.key?a+=t:"ArrowUp"===i.key&&(a-=t),n=Math.max((l=E[u.type].min).w,Math.min(c.width,n)),a=Math.max(l.h,Math.min(c.height,a)),{x:u.x,y:u.y,w:n,h:a}):(r=i.shift?1:16,s=u.x,d=u.y,"ArrowRight"===i.key?s+=r:"ArrowLeft"===i.key?s-=r:"ArrowDown"===i.key?d+=r:"ArrowUp"===i.key&&(d-=r),{x:s=Math.max(-(u.w-120),Math.min(c.width-120,s)),y:d=Math.max(0,Math.min(c.height-38,d)),w:u.w,h:u.h});return e.map(e=>e.id===u.id?{...e,...p,max:!1}:e)}))};return window.addEventListener("keydown",a),()=>{window.removeEventListener("keydown",a)}},[e,t,n])}({setWins:m,rect:z,cancelConnectRef:L}),function({wsRef:e,viewRef:t,setWins:n}){(0,a.useEffect)(()=>{let a=e.current;if(null===a||"u"<typeof ResizeObserver)return;let l=new ResizeObserver(()=>{let e=a.getBoundingClientRect(),l=t.current,i={x:-l.x/l.zoom,y:-l.y/l.zoom,w:e.width/l.zoom,h:e.height/l.zoom};n(e=>null===e?e:e.map(e=>(function(e,t){if(e.max)return{...e,x:t.x,y:t.y,w:t.w,h:t.h};if(t.w<520||t.h<420){let n=t.x+8,a=t.y+8;return n===e.x&&a===e.y?e:{...e,x:n,y:a}}let n=Math.max(t.x-(e.w-120),Math.min(t.x+t.w-120,e.x)),a=Math.max(t.y,Math.min(t.y+t.h-38,e.y));return n===e.x&&a===e.y?e:{...e,x:n,y:a}})(e,i)))});return l.observe(a),()=>{l.disconnect()}},[e,t,n])}({wsRef:e,viewRef:P,setWins:m});let{update:K,focus:B,close:_,minimize:U,restore:W,maximize:V,add:H,toggleTool:Y}={update:(l=(n={setWins:m,zc:N,worldVP:M}).setWins,(e,t)=>l(n=>{if(null===n)return n;let a=!1,l=n.map(n=>{if(n.id!==e)return n;for(let[e,l]of Object.entries(t))if(n[e]!==l)return a=!0,{...n,...t};return n});return a?l:n})),focus:(i=n.setWins,r=n.zc,e=>i(t=>null===t?t:t.map(t=>t.id===e?{...t,z:++r.current}:t))),close:(s=n.setWins,e=>s(t=>null===t?t:t.filter(t=>t.id!==e))),minimize:(o=n.setWins,e=>o(t=>null===t?t:t.map(t=>t.id===e?{...t,minimized:!0}:t))),restore:(c=n.setWins,d=n.zc,e=>c(t=>null===t?t:t.map(t=>t.id===e?{...t,minimized:!1,z:++d.current}:t))),maximize:function(e){let{setWins:t,zc:n,worldVP:a}=e;return e=>t(t=>{if(null===t)return t;let l=a();return null===l?t:t.map(t=>{if(t.id!==e)return t;if(t.max){var a;let e,i,r,s=t.prev??(a=t.type,i=Math.min((e=E[a]).w,Math.max(e.min.w,l.w-32)),r=Math.min(e.h,Math.max(e.min.h,l.h-32)),{x:l.x+Math.max(16,Math.round((l.w-i)/2)),y:l.y+Math.max(16,Math.round((l.h-r)/2)),w:i,h:r}),{prev:o,...c}=t;return{...c,x:s.x,y:s.y,w:s.w,h:s.h,max:!1,z:++n.current}}return{...t,max:!0,prev:{x:t.x,y:t.y,w:t.w,h:t.h},x:l.x,y:l.y,w:l.w,h:l.h,z:++n.current}})})}(n),add:function(e){let{setWins:t,zc:n,worldVP:a}=e;return(e,l)=>{let i=E[e],r="figma"===e&&"string"==typeof l?.selectedScreenIdsJson&&l.selectedScreenIdsJson.length>0,s=r?360:i.w,o=r?360:i.h,c=r?Math.max(i.min.w,300):i.min.w,d=r?Math.max(i.min.h,260):i.min.h,u=null;return t(t=>{let r=a();if(null===r)return t;let p=t??[];if(!0===i.singleton){let t=p.find(t=>t.type===e);if(void 0!==t)return u=t.id,p.map(e=>e.id===t.id?{...e,minimized:!1,z:++n.current}:e)}let m="qiRun"===e?l?.runId:void 0;if("string"==typeof m&&m.length>0){let e=p.find(e=>"qiRun"===e.type&&e.cfg.runId===m);if(void 0!==e)return u=e.id,p.map(t=>t.id===e.id?{...t,cfg:void 0===l?t.cfg:{...t.cfg,...l},minimized:!1,z:++n.current}:t)}let h="chat"===e?l?.chatId:void 0;if("string"==typeof h&&h.length>0){let e=p.find(e=>"chat"===e.type&&e.cfg.chatId===h);if(void 0!==e)return u=e.id,p.map(t=>t.id===e.id?{...t,minimized:!1,z:++n.current}:t)}let{x:f,y:g}=eW(r,s,o,p.length,40),v=!0===i.singleton?e:`${e}-${Date.now().toString(36)}`;return u=v,[...p,{id:v,type:e,x:f,y:g,w:Math.max(s,c),h:Math.max(o,d),z:++n.current,cfg:l??{},max:!1,zoom:1}]}),u}}(n),toggleTool:function(e){let{setWins:t,zc:n,worldVP:a}=e;return e=>{let l=E[e];t(t=>{let i=a();if(null===i)return t;let r=t??[],s=r.find(t=>t.type===e);if(void 0!==s&&!0===s.minimized)return r.map(e=>e.id===s.id?{...e,minimized:!1,z:++n.current}:e);if(void 0!==s)return r.filter(t=>t.type!==e);let{x:o,y:c}=eW(i,l.w,l.h,r.length,28);return[...r,{id:e,type:e,x:o,y:c,w:l.w,h:l.h,z:++n.current,cfg:{},max:!1,zoom:1}]})}}(n)},{tileAll:G,splitFront:J,cascade:X}={tileAll:function({setWins:e,worldVP:t}){return()=>e(e=>{if(null===e||0===e.length)return e;let n=t();if(null===n)return e;let a=e.length,l=Math.ceil(Math.sqrt(a)),i=Math.ceil(a/l),r=(n.w-12*(l+1))/l,s=(n.h-12*(i+1))/i;return e.map((e,t)=>{let a=Math.floor(t/l);return{...eV(e),max:!1,minimized:!1,x:n.x+12+t%l*(r+12),y:n.y+12+a*(s+12),w:r,h:s}})})}(u={setWins:m,worldVP:M}),splitFront:function({setWins:e,worldVP:t}){return()=>e(e=>{if(null===e||0===e.length)return e;let n=t();if(null===n)return e;let a=[...e].filter(e=>!0!==e.minimized).sort((e,t)=>t.z-e.z).slice(0,2).map(e=>e.id);return e.map(e=>{let t=a.indexOf(e.id);return 0===t?{...eV(e),max:!1,minimized:!1,x:n.x,y:n.y,w:n.w/2,h:n.h}:1===t?{...eV(e),max:!1,minimized:!1,x:n.x+n.w/2,y:n.y,w:n.w/2,h:n.h}:e})})}(u),cascade:function({setWins:e,worldVP:t}){return()=>e(e=>{if(null===e)return e;let n=t();return null===n?e:e.map((e,t)=>({...eV(e),max:!1,minimized:!1,x:n.x+24+30*t,y:n.y+24+30*t,w:Math.min(560,n.w-80),h:Math.min(420,n.h-80),z:t+1}))})}(u)},{setSnap:Q,commitSnap:Z}=function({setSnapPrev:e,snapZone:t,worldVP:n,update:a}){return{setSnap:a=>{if(t.current=a,null===a)return void e(null);let l=n();null!==l&&e(T(l)[a])},commitSnap:l=>{let i=t.current;if(t.current=null,e(null),null===i)return;let r=n();if(null===r)return;let s={...T(r)[i],max:"maxi"===i};"maxi"===i&&(s.prev={x:r.x+40,y:r.y+40,w:480,h:360}),a(l,s)}}}({setSnapPrev:f,snapZone:S,worldVP:M,update:K}),{startConnect:ee,confirmConnect:et,cancelConnect:en,removeConn:ea,connect:el,linkedFilesRoot:ei,linkedFilesContext:er,linkedAllFilesRoots:es,linkedConnectorCapsuleIds:eo,linkedConnectorCapsuleSetIds:ec,linkedFigmaSnapshotRunIds:ed,linkedFigmaSnapshotSources:eu,linkedImageSources:ep,currentFilesContext:em}=function(e){let{wsRef:t,viewRef:n,winsRef:a,connsRef:l,connectingRef:i,connectCleanupRef:r,focus:s,setConns:o,setConnecting:c,onScopeBind:d,onScopeUnbind:u,onConnectorBind:p,onConnectorUnbind:m}=e,h=()=>{null!==r.current&&(r.current(),r.current=null),i.current=null,c(null)},f=e=>{if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,a="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;if(null===a||!eG(a))return null;let l=e.cfg.activeFilePath;return{id:e.id,root:a,..."string"==typeof l&&l.length>0?{activeFilePath:l}:{}}},g=e=>{let t=[];for(let n of l.current){let l=n.a===e?n.b:n.b===e?n.a:null;if(null===l)continue;let i=a.current.find(e=>e.id===l);void 0!==i&&"files"===i.type&&t.push(i)}if(0===t.length)return null;let n=[...t].sort((e,t)=>t.z-e.z),i=n.find(e=>{let t=e.cfg.activeFilePath;return"string"==typeof t&&t.length>0})??n[0];return void 0===i?null:f(i)},v=(e,t)=>{let n=new Set,i=[];for(let r of l.current){if(i.length>=16)break;let l=r.a===e?r.b:r.b===e?r.a:null;if(null===l)continue;let s=a.current.find(e=>e.id===l);if(void 0===s||"connector"!==s.type||s.cfg.selectedKind!==t)continue;let o=s.cfg.selectedId;"string"==typeof o&&0!==o.trim().length&&(n.has(o)||(n.add(o),i.push(o)))}return i},b=e=>{let t=(e=>{if("string"!=typeof e||0===e.trim().length)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>"string"==typeof e&&""!==e.trim()).map(e=>e.trim());return[...new Set(n)].sort()}catch{return[]}})(e.cfg.selectedScreenIdsJson);if(t.length>0)return t;let n=e.cfg.screenId;return"string"==typeof n&&n.trim().length>0?[n.trim()]:[]};return{startConnect:(e,a)=>{if(a.preventDefault(),a.stopPropagation(),null!==i.current&&i.current.from===e)return void h();let l=t.current;if(null===l)return;let s=l.getBoundingClientRect(),o=n.current,d=e=>(e-s.left-o.x)/o.zoom,u=e=>(e-s.top-o.y)/o.zoom;null!==r.current&&(r.current(),r.current=null);let p={from:e,x:d(a.clientX),y:u(a.clientY)};i.current=p,c(p);let m=t=>{let n={from:e,x:d(t.clientX),y:u(t.clientY)};i.current=n,c(n)};window.addEventListener("pointermove",m),r.current=()=>{window.removeEventListener("pointermove",m)}},confirmConnect:(e,t)=>{t.preventDefault(),t.stopPropagation();let n=i.current;if(null===n)return;let l=a.current,r=l.find(e=>e.id===n.from),c=l.find(t=>t.id===e);if(void 0!==r&&void 0!==c&&$(r.type,c.type)){let t,l=e0(r,c,Date.now()),i=null===l?e7(r,c):null,u=null!==l||null!==i?eY(r,c):null;try{t=null!==l&&null!==u?d?.(u,l)??!0:null===i||null!==u&&(p?.(u,i)??!0)}catch{t=!1}Promise.resolve(t).then(t=>{!t||a.current.some(e=>e.id===n.from)&&a.current.some(t=>t.id===e)&&(o(t=>eH(t,n.from,e)?t:[...t,{id:`${n.from}~${e}`,a:n.from,b:e,...null!==u?{boundChatWindowId:u}:{},...null!==l?{boundRoot:l.root,boundScopeKind:l.kind,boundRelativePath:l.relativePaths[0]}:{},...null!==i?"capsule"===i.kind?{boundConnectorKind:"capsule",boundConnectorId:i.capsuleId}:{boundConnectorKind:"capsule-set",boundConnectorId:i.capsuleSetId}:{}}]),s(e))}).catch(()=>void 0)}h()},cancelConnect:h,removeConn:e=>{let t=l.current.find(t=>t.id===e);if(o(t=>t.filter(t=>t.id!==e)),void 0===t)return;let n=a.current,i=n.find(e=>e.id===t.a),r=n.find(e=>e.id===t.b),s=void 0!==i&&void 0!==r,c=t.boundChatWindowId??(s?eY(i,r):null),d=e1(t)??(s?e0(i,r,Date.now()):null);null!==d&&null!==c&&u?.(c,d);let p=e8(t)??(s?e7(i,r):null);null!==p&&null!==c&&m?.(c,p)},connect:(e,t)=>{let n=a.current,l=n.find(t=>t.id===e),i=n.find(e=>e.id===t);void 0!==l&&void 0!==i&&$(l.type,i.type)&&o(n=>eH(n,e,t)?n:[...n,{id:`${e}~${t}`,a:e,b:t}])},linkedFilesRoot:e=>g(e)?.root??null,linkedFilesContext:g,linkedAllFilesRoots:e=>{let t=new Set,n=[];for(let i of l.current){if(n.length>=16)break;let l=i.a===e?i.b:i.b===e?i.a:null;if(null===l)continue;let r=a.current.find(e=>e.id===l);if(void 0===r)continue;let s=eX(r);null===s||t.has(s)||(t.add(s),n.push(s))}return n},linkedConnectorCapsuleIds:e=>v(e,"capsule"),linkedConnectorCapsuleSetIds:e=>v(e,"capsule-set"),linkedFigmaSnapshotRunIds:e=>{let t=new Set,n=[];for(let i of l.current){if(n.length>=16)break;let l=i.a===e?i.b:i.b===e?i.a:null;if(null===l)continue;let r=a.current.find(e=>e.id===l);if(void 0===r||"figma"!==r.type)continue;let s=r.cfg.snapshotRunId;"string"==typeof s&&0!==s.trim().length&&(t.has(s)||(t.add(s),n.push(s)))}return n},linkedFigmaSnapshotSources:e=>{let t=new Set,n=[];for(let i of l.current){if(n.length>=16)break;let l=i.a===e?i.b:i.b===e?i.a:null;if(null===l)continue;let r=a.current.find(e=>e.id===l);if(void 0===r||"figma"!==r.type&&"figmaView"!==r.type&&"figmaJson"!==r.type)continue;let s=r.cfg.snapshotRunId;if("string"!=typeof s||0===s.trim().length)continue;let o=r.cfg.selectedScreenIdsJson,c=r.cfg.selectedScreenName,d=b(r);if(("figmaJson"===r.type||"figmaView"===r.type||void 0!==o||"string"==typeof c&&c.trim().length>0)&&0===d.length)continue;let u=`${s}:${d.join(",")||"*"}`;if(t.has(u))continue;t.add(u);let p=d.length>0&&"string"==typeof c&&c.trim().length>0?"figmaJson"===r.type?`JSON \xb7 ${c}`:c:s;n.push({kind:"figma-snapshot",label:p,snapshotRunId:s,...d.length>0?{screenIds:d}:{}})}return n},linkedImageSources:e=>{let t=new Set,n=[];for(let i of l.current){if(n.length>=16)break;let l=i.a===e?i.b:i.b===e?i.a:null;if(null===l)continue;let r=a.current.find(e=>e.id===l);if(void 0===r||"figmaImage"!==r.type)continue;let s=r.cfg.snapshotRunId,o=r.cfg.screenId;if("string"!=typeof s||0===s.trim().length||"string"!=typeof o||0===o.trim().length)continue;let c=`${s}:${o}`;if(t.has(c))continue;t.add(c);let d=r.cfg.selectedScreenName,u="string"==typeof d&&d.trim().length>0?`Image \xb7 ${d}`:`Image \xb7 ${o}`;n.push({kind:"image",label:u,sourceKind:"figma-snapshot-screen",snapshotRunId:s,screenId:o})}return n},currentFilesContext:()=>{let e=a.current.map(e=>f(e)).filter(e=>null!==e);if(1===e.length)return e[0]??null;let t=[...a.current].filter(e=>"files"===e.type).sort((e,t)=>t.z-e.z)[0];return void 0===t?null:f(t)}}}({wsRef:e,viewRef:P,winsRef:C,connsRef:I,connectingRef:R,connectCleanupRef:A,focus:B,setConns:x,setConnecting:w,onScopeBind:t.onScopeBind,onScopeUnbind:t.onScopeUnbind,onConnectorBind:t.onConnectorBind,onConnectorUnbind:t.onConnectorUnbind});return L.current=en,(0,a.useEffect)(()=>()=>{null!==A.current&&(A.current(),A.current=null)},[]),{wins:p,snapPrev:h,palOpen:g,setPalOpen:v,conns:b,connecting:y,view:j,api:{add:H,toggleTool:Y,focus:B,close:e=>{let n=C.current.find(t=>t.id===e);if(void 0!==n)for(let a of I.current){let l=a.a===e?a.b:a.b===e?a.a:null;if(null===l)continue;let i=C.current.find(e=>e.id===l);if(void 0===i)continue;let r=a.boundChatWindowId??("chat"===n.type?n.id:"chat"===i.type?i.id:null),s=e1(a)??e0(n,i,Date.now());null!==s&&null!==r&&t.onScopeUnbind?.(r,s);let o=e8(a)??e7(n,i);null!==o&&null!==r&&t.onConnectorUnbind?.(r,o)}_(e)},minimize:U,restore:W,maximize:V,update:K,setSnap:Q,commitSnap:Z,tileAll:G,splitFront:J,cascade:X,startConnect:ee,confirmConnect:et,cancelConnect:en,removeConn:ea,updateConnBoundScope:(e,t)=>{x(n=>n.map(n=>n.id===e?{...n,boundScopeKind:t.kind,...void 0!==t.root?{boundRoot:t.root}:{},...void 0!==t.relativePaths[0]?{boundRelativePath:t.relativePaths[0]}:{}}:n))},connect:el,linkedFilesRoot:ei,linkedFilesContext:er,linkedAllFilesRoots:es,linkedConnectorCapsuleIds:eo,linkedConnectorCapsuleSetIds:ec,linkedFigmaSnapshotRunIds:ed,linkedFigmaSnapshotSources:eu,linkedImageSources:ep,currentFilesContext:em,zoomTo:D,fitView:q,resetView:F,panBy:O,rect:z}}}(u,{onScopeBind:(0,a.useCallback)(async(e,t)=>k(e,t),[k]),onScopeUnbind:(0,a.useCallback)((e,t)=>{let n=j(e);if(void 0===n)return;let a=e4(e3(n),t);(0,w.updateChatConnectedScopes)(n.id,a.length>0?a:null).then(e=>{d.replaceChat(e.chat)}).catch(e=>{console.warn("[keiko] connected-scope unbind failed",e)})},[j,d]),onConnectorBind:(0,a.useCallback)(async(e,t)=>{var n;let a,l,i=j(e);if(void 0===i)return b("Open a ready chat window before connecting a source.");let r=e6(i),s=e3(i);if(a=e5(t),r.some(e=>e5(e)===a))return!0;let o=e2(m);if(s.length+r.length>=o)return v(s.length+r.length,o);let c=(n=m.maxLocalKnowledgeSources,l=e5(t),r.some(e=>e5(e)===l)||r.length>=n?r:[...r,t]);if(c===r)return v(s.length+r.length,o);try{let e=await (0,w.updateChatLocalKnowledgeScopes)(i.id,c);return d.replaceChat(e.chat),g(null),!0}catch{return b("Keiko could not connect that knowledge source. Check that it is still available and try again.")}},[j,d,m,v,b]),onConnectorUnbind:(0,a.useCallback)((e,t)=>{var n;let a=j(e);if(void 0===a)return;let l="capsule"===t.kind?`capsule:${t.capsuleId}`:`set:${t.capsuleSetId}`,i=(n=e6(a),n.filter(e=>e5(e)!==l));(0,w.updateChatLocalKnowledgeScopes)(a.id,i.length>0?i:null).then(e=>{d.replaceChat(e.chat)}).catch(()=>void 0)},[j,d])});p.current=N.wins,(0,a.useEffect)(()=>{if(null!==N.wins)for(let e of N.conns){let t=N.wins.find(t=>t.id===e.a),n=N.wins.find(t=>t.id===e.b);if(void 0===t||void 0===n)continue;let a=e.boundChatWindowId??("chat"===t.type?t.id:"chat"===n.type?n.id:null);if(null===a)continue;let l=e0(t,n,Date.now());if(null===l)continue;let i=e1(e);uM(i)!==uM(l)&&k(a,l,i).then(t=>{t&&N.api.updateConnBoundScope(e.id,l)})}},[k,N.api,N.conns,N.wins]);let[S,C]=(0,a.useState)(!1),[I,R]=(0,a.useState)(null),[A,L]=(0,a.useState)(!1),[D,q]=(0,a.useState)(!1),z=N.wins?.length??0,K=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}(N.wins),B=(0,a.useMemo)(()=>(function(e){if(null===e)return new Set;let t=new Set;for(let n of e)!0===E[n.type].tool&&t.add(n.type);return t})(N.wins),[N.wins]),_=(0,a.useMemo)(()=>({wins:N.wins??[],active:K,winCount:z}),[N.wins,K,z]),U=(0,a.useCallback)(()=>C(!0),[]),W=(0,a.useCallback)(()=>C(!1),[]),V=(0,a.useCallback)(()=>q(e=>!e),[]),H=(0,a.useCallback)(()=>q(!1),[]),Y=(0,a.useCallback)(e=>{N.api.restore(e),q(!1)},[N.api]),G=(0,a.useCallback)(e=>{C(!1),R(e)},[]),J=(0,a.useCallback)(e=>{if(R(null),null===I)return;let{__connectFilesId:t,...n}="editor"===I?function(e){let t="string"==typeof e.root?e.root.trim():"",n="string"==typeof e.file?e.file.trim():"";if(0===t.length)return e;let a=uq(t,n),l={...e,root:t},i=function(e,t,n){let a=[],l=t=>{let n=function(e,t){let n=t.trim();if(0===n.length)return"";let a=uq(e,n);return null!==a?a:n.startsWith("/")||n.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(n)?null:n.replace(/\\/gu,"/").replace(/^\/+/u,"")}(e,t);null===n||0===n.length||a.includes(n)||a.push(n)};if(Array.isArray(t))for(let e of t)"string"==typeof e&&l(e);return n.length>0&&l(n),a}(t,e.openFiles,null!==a?a:n);return null===a?n.length>0&&(l.file=n):a.length>0?l.file=a:delete l.file,i.length>0?l.openFiles=i:delete l.openFiles,l}(e):e,a=N.api.add(I,n);"agents"===I&&null!==a&&"string"==typeof t&&t.length>0&&N.api.connect(a,t),null!==a&&requestAnimationFrame(()=>{let e=document.querySelector(`[data-window-id="${a}"]`);null===e||(e.querySelector("textarea, input, select, button, [tabindex]")??e).focus()})},[I,N.api]),X=(0,a.useCallback)(()=>R(null),[]),Q=(0,a.useCallback)(()=>L(!1),[]),Z=(0,a.useCallback)(()=>L(!0),[]),ee=(0,a.useRef)(null),et=(0,a.useCallback)(e=>{ee.current=e},[]),en=function(e){let{apply:t}=e,n=e.limit??100,[l,i]=(0,a.useState)(aN),r=(0,a.useRef)(t);r.current=t;let s=(0,a.useRef)(l);s.current=l;let o=(0,a.useCallback)(e=>{i(t=>{let a=[...t.undoStack,e];return{undoStack:a.length>n?a.slice(a.length-n):a,redoStack:[]}})},[n]),c=(0,a.useCallback)(()=>{let e=s.current;if(0===e.undoStack.length)return;let t=e.undoStack[e.undoStack.length-1],n=function(e){switch(e.kind){case"ui.window.move":case"ui.window.resize":case"ui.window.zorder":case"ui.workspace.pan":case"ui.workspace.zoom":case"ui.workspace.fit":case"ui.panel.toggle":case"ui.selection.change":case"ui.tab.switch":return{...e,before:e.after,after:e.before};case"ui.window.close":return{...e,kind:"ui.window.open"};case"ui.window.open":return{...e,kind:"ui.window.close"}}}(t);i({undoStack:e.undoStack.slice(0,-1),redoStack:[...e.redoStack,t]}),r.current(n)},[]),d=(0,a.useCallback)(()=>{let e=s.current;if(0===e.redoStack.length)return;let t=e.redoStack[e.redoStack.length-1];i({undoStack:[...e.undoStack,t],redoStack:e.redoStack.slice(0,-1)}),r.current(t)},[]),u=(0,a.useCallback)(()=>{i(aN)},[]);return(0,a.useMemo)(()=>{let e=l.undoStack[l.undoStack.length-1],t=l.redoStack[l.redoStack.length-1];return{canUndo:l.undoStack.length>0,canRedo:l.redoStack.length>0,undoLabel:void 0!==e?aj(e):null,redoLabel:void 0!==t?aj(t):null,push:o,undo:c,redo:d,clear:u}},[l,o,c,d,u])}({apply:(0,a.useCallback)(e=>{var t;return t=N.api,void("ui.panel.toggle"===e.kind&&e.panel in E&&t.toggleTool(e.panel))},[N.api])}),ea=(0,a.useCallback)(e=>{if(!(e in E))return;let t=B.has(e);N.api.toggleTool(e),en.push({kind:"ui.panel.toggle",panel:e,before:t,after:!t})},[N.api,B,en]),el=(0,a.useCallback)(()=>G("chat"),[G]),ei=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(ei.current||null===N.wins)return;ei.current=!0;let e=window.location.pathname.replace(/\/+$/u,""),t="/relationships"===e?"relationships":"/local-knowledge"===e?"localKnowledge":null;null!==t&&(N.wins.some(e=>e.type===t)||ea(t),window.history.replaceState(null,"","/"))},[N.wins,ea]),function(e){let{bindings:t,dispatch:n}=e,l=e.platform??function(){if("u"<typeof navigator)return"other";let e=navigator.platform||"";return/Mac|iPhone|iPad|iPod/i.test(e)?"mac":"other"}(),i=(0,a.useRef)(n);i.current=n;let r=(0,a.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=ak(n.chord),a=t.get(e);void 0!==a?a.push(n.commandId):t.set(e,[n.commandId])}let n=[];for(let[,a]of t)if(a.length>1){let t=e.find(e=>a.includes(e.commandId));void 0!==t&&n.push({chord:t.chord,commandIds:a})}return n})(t),[t]),s=(0,a.useMemo)(()=>t.filter(e=>(function(e){for(let t of aw)if(ak(e)===ak(t))return!0;return!1})(e.chord)),[t]);if(r.length>0)throw new aS(r);if(s.length>0)throw new aC(s);(0,a.useEffect)(()=>{function e(e){if(!function(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}(e.target)){for(let n of t)if(function(e,t,n){if(!(e.key.toLowerCase()===t.key.toLowerCase()||t.mod.includes("alt")&&/^[a-z]$/i.test(t.key)&&e.code===`Key${t.key.toUpperCase()}`))return!1;let a=function(e,t){let n=new Set;for(let a of e)"cmd"===a?n.add("mac"===t?"meta":"ctrl"):"ctrl"===a?n.add("ctrl"):"alt"===a?n.add("alt"):"shift"===a&&n.add("shift");return n}(t.mod,n);return e.metaKey===a.has("meta")&&e.ctrlKey===a.has("ctrl")&&e.altKey===a.has("alt")&&e.shiftKey===a.has("shift")}(e,n.chord,l)){e.preventDefault(),i.current(n.commandId);return}}}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t,l]),(0,a.useMemo)(()=>({bindings:t,conflicts:r,reserved:s}),[t,r,s])}({bindings:aI,dispatch:(0,a.useCallback)(e=>{"undo"===e?en.undo():"redo"===e?en.redo():"focus-status"===e&&ee.current?.focus()},[en])}),(0,a.useEffect)(()=>{let e=document.documentElement,t=()=>{e.setAttribute("data-input-modality","pointer")},n=t=>{t.metaKey||t.ctrlKey||t.altKey||"Tab"===t.key&&e.setAttribute("data-input-modality","keyboard")};return e.setAttribute("data-input-modality","pointer"),window.addEventListener("pointerdown",t,!0),window.addEventListener("mousedown",t,!0),window.addEventListener("keydown",n,!0),()=>{window.removeEventListener("pointerdown",t,!0),window.removeEventListener("mousedown",t,!0),window.removeEventListener("keydown",n,!0),e.removeAttribute("data-input-modality")}},[]);let er=(0,a.useMemo)(()=>(function(e,t,n,a,l,i){let r=[];for(let e of uF){let t=E[e];r.push({id:`new-${e}`,label:`New ${t.title}`,group:"Create",icon:t.icon,run:()=>n(e)})}for(let e of uO){let n=E[e];r.push({id:`open-${e}`,label:`Open ${n.title}`,group:"Tools",icon:n.icon,run:()=>t(e)})}return r.push({id:"tile",label:"Tile all windows",group:"Layout",icon:"tile",run:e.tileAll}),r.push({id:"split",label:"Split front windows",group:"Layout",icon:"split",run:e.splitFront}),r.push({id:"cascade",label:"Cascade windows",group:"Layout",icon:"cascade",run:e.cascade}),r.push({id:"theme",label:"Toggle light / dark theme",group:"View",icon:"light"===a?"moon":"sun",run:l}),r.push({id:"undo",label:null!==i.undoLabel?`Undo: ${i.undoLabel}`:"Undo (window and panel changes only)",group:"Edit",icon:"back",shortcut:"⌘Z",run:i.undo}),r.push({id:"redo",label:null!==i.redoLabel?`Redo: ${i.redoLabel}`:"Redo (window and panel changes only)",group:"Edit",icon:"fwd",shortcut:"⇧⌘Z",run:i.redo}),r})(N.api,ea,G,s,o,en),[N.api,ea,G,s,o,en]),es=!d.loading&&void 0===d.error&&0===d.models.length,eo=(e=d.activeProject?.name,d.loading?"Loading project…":void 0!==e&&e.trim().length>0?e:"No project selected"),ec=void 0!==d.activeProject,ed=d.activeProject?.available===!0,eu=(t={loading:d.loading,error:d.error,hasProject:ec,projectAvailable:ed,noEligibleModels:d.noEligibleModels}).loading?"Loading shell…":void 0!==t.error?"Shell error":t.hasProject?t.projectAvailable?t.noEligibleModels?"Gateway setup required":"Ready":"Project unavailable":"No project selected",ep=0===(r=(N.wins??[]).filter(e=>"review"===e.type)).length?"No review open":r.some(e=>"string"==typeof e.cfg.runId&&e.cfg.runId.length>0)?"Evidence ready":"Review window open",em=void 0!==(l=d.activeChat?.branchLabel)&&l.trim().length>0?l:"No branch selected",eh=S?(0,n.jsx)(t1,{types:E,order:uF,onAdd:G,onClose:W}):null;return(0,n.jsx)(i,{value:d,children:(0,n.jsx)(y.Provider,{value:_,children:(0,n.jsxs)("div",{className:"app",children:[(0,n.jsx)("a",{className:"skip-link",href:"#main",children:"Skip to content"}),(0,n.jsx)("h1",{className:"visually-hidden",children:"Keiko workspace"}),(0,n.jsx)(M,{openPalette:U,openCommandPalette:Z,onTileAll:N.api.tileAll,onSplitFront:N.api.splitFront,onCascade:N.api.cascade}),(0,n.jsxs)("div",{className:"mid",children:[es?null:(0,n.jsx)(F,{openTools:B,onTool:ea,onNewChat:el,theme:s,onToggleTheme:o}),(0,n.jsxs)("div",{className:"stage",id:"main",tabIndex:-1,children:[(0,n.jsx)(tT,{ws:N,wsRef:u,openPalette:U,palette:eh}),null!==f&&(0,n.jsxs)("div",{className:"source-limit-alert",role:"alert",children:[(0,n.jsx)("span",{children:f}),(0,n.jsx)("button",{type:"button",className:"source-limit-alert-dismiss","aria-label":"Dismiss source connection notice",onClick:()=>g(null),children:"×"})]})]}),es?null:(0,n.jsx)(O,{openTools:B,onTool:ea})]}),(0,n.jsx)(P,{winCount:z,windows:N.wins??[],windowPaletteOpen:D,onToggleWindowPalette:V,onSelectWindow:Y,onCloseWindowPalette:H,mode:c.mode,selectedModel:d.selectedModel,projectName:eo,branchLabel:em,shellStatusLabel:eu,evidenceStatusLabel:ep,statusRef:et}),null!==I&&(0,n.jsx)(t0,{type:I,types:E,filesContext:N.api.currentFilesContext(),onConfirm:J,onClose:X}),A&&(0,n.jsx)(tL,{commands:er,onClose:Q}),es?(0,n.jsx)(tD,{}):null,(0,n.jsx)(u$,{})]})})})}function uK(){let[e,t]=(0,a.useState)(!1);return((0,a.useEffect)(()=>{try{window.sessionStorage.removeItem("keiko.app-boot-recovery-reload-count")}catch{}t(!0)},[]),(0,a.useEffect)(()=>{!function(){if(!("u">typeof navigator&&"serviceWorker"in navigator))return;let e=navigator.serviceWorker;try{e.register("/sw.js",{scope:"/"}).then(t=>{e.addEventListener("controllerchange",uL),null!==e.controller&&uP(t),t.addEventListener("updatefound",()=>{let n;n=t.installing,null!==n&&n.addEventListener("statechange",()=>{"installed"!==n.state||null!==e.controller&&uP(t)})})}).catch(e=>{})}catch{}}()},[]),e)?(0,n.jsx)(b,{children:(0,n.jsx)(uz,{})}):(0,n.jsx)("div",{className:"app","aria-hidden":"true",children:(0,n.jsx)("div",{className:"app-boot",children:(0,n.jsx)("img",{className:"app-boot-logo",src:"/assets/keiko-logo.svg",alt:""})})})}e.s(["KeikoDesktop",0,function(){return(0,n.jsx)(uK,{})}],89199)}]);