@jingyi0605/codingns 0.8.5 → 0.9.0

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 (439) hide show
  1. package/bin/codingns.mjs +7 -156
  2. package/dist/public/assets/AdaptiveButlerPage-B17QiMyT.js +2 -0
  3. package/dist/public/assets/{App-BOHBGFOd.js → App-CFBwDUNA.js} +6 -6
  4. package/dist/public/assets/{BootstrapPage-BxHQT4nA.js → BootstrapPage-W5wU3BPh.js} +1 -1
  5. package/dist/public/assets/{ConversationPage-DWFsF6BB.js → ConversationPage-DQLX1bUh.js} +6 -6
  6. package/dist/public/assets/{DesktopDetachPreviewPage-DOgEjYEf.js → DesktopDetachPreviewPage-DTPeuAW-.js} +1 -1
  7. package/dist/public/assets/DesktopModal-6ii53_Y9.js +1 -0
  8. package/dist/public/assets/DesktopWindowPage-D0blSuKd.js +2 -0
  9. package/dist/public/assets/FileContextPanel-BrKO8Xt6.js +1 -0
  10. package/dist/public/assets/GitSidebar-BdwiDtOr.js +6 -0
  11. package/dist/public/assets/MobileCreateSessionSheet-Cx_dBiBb.js +1 -0
  12. package/dist/public/assets/MobileSheet-opTWyRe1.js +1 -0
  13. package/dist/public/assets/{MobileTopHeaderFrame-lcp2GscV.js → MobileTopHeaderFrame-BbNON3Y4.js} +1 -1
  14. package/dist/public/assets/MobileWorkspaceSwitcherHeader-BZEzPeMj.js +1 -0
  15. package/dist/public/assets/{PluginAccessOverview-DGcKAMQl.js → PluginAccessOverview-mQDmAljp.js} +1 -1
  16. package/dist/public/assets/PluginContainerPage-CcxUJpM4.js +1 -0
  17. package/dist/public/assets/{PluginDetailPage-CAJ7LFpD.js → PluginDetailPage-D5--ACIt.js} +1 -1
  18. package/dist/public/assets/{PluginsListPage-BxZG1NyT.js → PluginsListPage-D_oJxYXT.js} +1 -1
  19. package/dist/public/assets/{RelayConnectEntryPage-CfNO_TIl.js → RelayConnectEntryPage-DROxpnkv.js} +1 -1
  20. package/dist/public/assets/{ServerSettingsModal-by36Z_5k.js → ServerSettingsModal-CUUOPqSe.js} +1 -1
  21. package/dist/public/assets/SessionIndexPage-C2Jxh6Gp.js +1 -0
  22. package/dist/public/assets/SettingsPage-BlAZCHsy.js +2 -0
  23. package/dist/public/assets/{TerminalManagerPanel-NVZRxxmH.js → TerminalManagerPanel-CjzbiWjl.js} +1 -1
  24. package/dist/public/assets/{TerminalPage-C4LNoPBp.js → TerminalPage-CwWyFDj8.js} +2 -2
  25. package/dist/public/assets/TerminalRuntimeFallbackModal-CSVVbO8r.js +1 -0
  26. package/dist/public/assets/{ToolFilesPage-47zbdgTW.js → ToolFilesPage-QBEY8oCf.js} +1 -1
  27. package/dist/public/assets/{ToolGitPage-Fuk_b_jg.js → ToolGitPage-BKoZ2l9v.js} +1 -1
  28. package/dist/public/assets/{ToolProcessesPage-sWSMWD-9.js → ToolProcessesPage-BOH0ib4G.js} +1 -1
  29. package/dist/public/assets/{ToolsHomePage-R1mZlbZi.js → ToolsHomePage-BcMZ3BCQ.js} +1 -1
  30. package/dist/public/assets/{WorkbenchLandingPage-CqmiFH2u.js → WorkbenchLandingPage-B5zoppEl.js} +1 -1
  31. package/dist/public/assets/WorkbenchLayout-BksVkkFF.css +1 -0
  32. package/dist/public/assets/WorkbenchLayout-CikJBS62.js +1019 -0
  33. package/dist/public/assets/{WorkbenchModal-C7qoQElW.js → WorkbenchModal-NGmPgqaE.js} +1 -1
  34. package/dist/public/assets/WorkbenchShellRoute-BbbSOiZw.js +1 -0
  35. package/dist/public/assets/WorkbenchShellRoute-DT3VMjWD.css +1 -0
  36. package/dist/public/assets/WorkspaceDebugDetailPage-CVivdPx5.js +1 -0
  37. package/dist/public/assets/{WorkspaceDetailPage-BPsrFffw.js → WorkspaceDetailPage-DgOSjscR.js} +1 -1
  38. package/dist/public/assets/{WorkspaceHomePage-KAtqZOAb.js → WorkspaceHomePage-HPa7M_Vh.js} +1 -1
  39. package/dist/public/assets/{client-runtime-manager-wmCJZKYd.js → client-runtime-manager-DXbI9K1K.js} +1 -1
  40. package/dist/public/assets/index-BxJPQpFM.css +1 -0
  41. package/dist/public/assets/index-CeXGOT_T.js +50 -0
  42. package/dist/public/assets/{login-direct-candidate-resolver-BOAgTuUf.js → login-direct-candidate-resolver-DkKyFtQJ.js} +1 -1
  43. package/dist/public/assets/{plugin-permission-copy-Cq99cnzV.js → plugin-permission-copy-CzN269Bk.js} +1 -1
  44. package/dist/public/assets/{plugins-api-BQTV5DOp.js → plugins-api-Bv9DHpLF.js} +1 -1
  45. package/dist/public/assets/{preferences-service-DJxbEEeg.js → preferences-service-D2ISL2Zz.js} +1 -1
  46. package/dist/public/assets/{relay-entry-D-LfvdiX.js → relay-entry-Bg0OisQy.js} +1 -1
  47. package/dist/public/assets/{terminal-runtime-meta-BJmy8dyK.js → terminal-runtime-meta-C8t-CIDF.js} +1 -1
  48. package/dist/public/assets/{useRegisteredDebugTemplates-DQAWVdCo.js → useRegisteredDebugTemplates-Bol3NVfN.js} +1 -1
  49. package/dist/public/assets/{workbench-navigation-MEzCSmsK.js → workbench-navigation-B7IjRQd8.js} +1 -1
  50. package/dist/public/index.html +2 -2
  51. package/dist/server/middlewares/auth-guard.js +10 -5
  52. package/dist/server/middlewares/auth-guard.js.map +1 -1
  53. package/dist/server/modules/affairs-indexer/contracts/src/errors/app-error.d.ts +11 -0
  54. package/dist/server/modules/affairs-indexer/contracts/src/errors/app-error.js +22 -0
  55. package/dist/server/modules/affairs-indexer/contracts/src/errors/app-error.js.map +1 -0
  56. package/dist/server/modules/affairs-indexer/contracts/src/errors/error-codes.d.ts +23 -0
  57. package/dist/server/modules/affairs-indexer/contracts/src/errors/error-codes.js +23 -0
  58. package/dist/server/modules/affairs-indexer/contracts/src/errors/error-codes.js.map +1 -0
  59. package/dist/server/modules/affairs-indexer/contracts/src/index.d.ts +4 -0
  60. package/dist/server/modules/affairs-indexer/contracts/src/index.js +5 -0
  61. package/dist/server/modules/affairs-indexer/contracts/src/index.js.map +1 -0
  62. package/dist/server/modules/affairs-indexer/contracts/src/types/cli-command-context.d.ts +7 -0
  63. package/dist/server/modules/affairs-indexer/contracts/src/types/cli-command-context.js +2 -0
  64. package/dist/server/modules/affairs-indexer/contracts/src/types/cli-command-context.js.map +1 -0
  65. package/dist/server/modules/affairs-indexer/contracts/src/types/runtime-config.d.ts +16 -0
  66. package/dist/server/modules/affairs-indexer/contracts/src/types/runtime-config.js +2 -0
  67. package/dist/server/modules/affairs-indexer/contracts/src/types/runtime-config.js.map +1 -0
  68. package/dist/server/modules/affairs-indexer/core/src/config/load-runtime-config.d.ts +10 -0
  69. package/dist/server/modules/affairs-indexer/core/src/config/load-runtime-config.js +215 -0
  70. package/dist/server/modules/affairs-indexer/core/src/config/load-runtime-config.js.map +1 -0
  71. package/dist/server/modules/affairs-indexer/core/src/index.d.ts +31 -0
  72. package/dist/server/modules/affairs-indexer/core/src/index.js +32 -0
  73. package/dist/server/modules/affairs-indexer/core/src/index.js.map +1 -0
  74. package/dist/server/modules/affairs-indexer/core/src/logging/structured-logger.d.ts +20 -0
  75. package/dist/server/modules/affairs-indexer/core/src/logging/structured-logger.js +47 -0
  76. package/dist/server/modules/affairs-indexer/core/src/logging/structured-logger.js.map +1 -0
  77. package/dist/server/modules/affairs-indexer/core/src/parser/base-complex-parser-adapter.d.ts +17 -0
  78. package/dist/server/modules/affairs-indexer/core/src/parser/base-complex-parser-adapter.js +63 -0
  79. package/dist/server/modules/affairs-indexer/core/src/parser/base-complex-parser-adapter.js.map +1 -0
  80. package/dist/server/modules/affairs-indexer/core/src/parser/complex-document-skip-adapter.d.ts +12 -0
  81. package/dist/server/modules/affairs-indexer/core/src/parser/complex-document-skip-adapter.js +42 -0
  82. package/dist/server/modules/affairs-indexer/core/src/parser/complex-document-skip-adapter.js.map +1 -0
  83. package/dist/server/modules/affairs-indexer/core/src/parser/csv-parser-adapter.d.ts +7 -0
  84. package/dist/server/modules/affairs-indexer/core/src/parser/csv-parser-adapter.js +107 -0
  85. package/dist/server/modules/affairs-indexer/core/src/parser/csv-parser-adapter.js.map +1 -0
  86. package/dist/server/modules/affairs-indexer/core/src/parser/document-parser.d.ts +19 -0
  87. package/dist/server/modules/affairs-indexer/core/src/parser/document-parser.js +37 -0
  88. package/dist/server/modules/affairs-indexer/core/src/parser/document-parser.js.map +1 -0
  89. package/dist/server/modules/affairs-indexer/core/src/parser/docx-parser-adapter.d.ts +7 -0
  90. package/dist/server/modules/affairs-indexer/core/src/parser/docx-parser-adapter.js +123 -0
  91. package/dist/server/modules/affairs-indexer/core/src/parser/docx-parser-adapter.js.map +1 -0
  92. package/dist/server/modules/affairs-indexer/core/src/parser/openxml-utils.d.ts +8 -0
  93. package/dist/server/modules/affairs-indexer/core/src/parser/openxml-utils.js +111 -0
  94. package/dist/server/modules/affairs-indexer/core/src/parser/openxml-utils.js.map +1 -0
  95. package/dist/server/modules/affairs-indexer/core/src/parser/parser-adapter.d.ts +42 -0
  96. package/dist/server/modules/affairs-indexer/core/src/parser/parser-adapter.js +2 -0
  97. package/dist/server/modules/affairs-indexer/core/src/parser/parser-adapter.js.map +1 -0
  98. package/dist/server/modules/affairs-indexer/core/src/parser/parser-capability-registry.d.ts +18 -0
  99. package/dist/server/modules/affairs-indexer/core/src/parser/parser-capability-registry.js +91 -0
  100. package/dist/server/modules/affairs-indexer/core/src/parser/parser-capability-registry.js.map +1 -0
  101. package/dist/server/modules/affairs-indexer/core/src/parser/parser-router.d.ts +18 -0
  102. package/dist/server/modules/affairs-indexer/core/src/parser/parser-router.js +59 -0
  103. package/dist/server/modules/affairs-indexer/core/src/parser/parser-router.js.map +1 -0
  104. package/dist/server/modules/affairs-indexer/core/src/parser/parser-skip-repository.d.ts +48 -0
  105. package/dist/server/modules/affairs-indexer/core/src/parser/parser-skip-repository.js +193 -0
  106. package/dist/server/modules/affairs-indexer/core/src/parser/parser-skip-repository.js.map +1 -0
  107. package/dist/server/modules/affairs-indexer/core/src/parser/pdf-parser-adapter.d.ts +7 -0
  108. package/dist/server/modules/affairs-indexer/core/src/parser/pdf-parser-adapter.js +371 -0
  109. package/dist/server/modules/affairs-indexer/core/src/parser/pdf-parser-adapter.js.map +1 -0
  110. package/dist/server/modules/affairs-indexer/core/src/parser/plain-text-parser-adapter.d.ts +10 -0
  111. package/dist/server/modules/affairs-indexer/core/src/parser/plain-text-parser-adapter.js +55 -0
  112. package/dist/server/modules/affairs-indexer/core/src/parser/plain-text-parser-adapter.js.map +1 -0
  113. package/dist/server/modules/affairs-indexer/core/src/parser/plain-text-parser.d.ts +9 -0
  114. package/dist/server/modules/affairs-indexer/core/src/parser/plain-text-parser.js +2 -0
  115. package/dist/server/modules/affairs-indexer/core/src/parser/plain-text-parser.js.map +1 -0
  116. package/dist/server/modules/affairs-indexer/core/src/parser/pptx-parser-adapter.d.ts +7 -0
  117. package/dist/server/modules/affairs-indexer/core/src/parser/pptx-parser-adapter.js +130 -0
  118. package/dist/server/modules/affairs-indexer/core/src/parser/pptx-parser-adapter.js.map +1 -0
  119. package/dist/server/modules/affairs-indexer/core/src/parser/xlsx-parser-adapter.d.ts +7 -0
  120. package/dist/server/modules/affairs-indexer/core/src/parser/xlsx-parser-adapter.js +228 -0
  121. package/dist/server/modules/affairs-indexer/core/src/parser/xlsx-parser-adapter.js.map +1 -0
  122. package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-repository.d.ts +205 -0
  123. package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-repository.js +1471 -0
  124. package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-repository.js.map +1 -0
  125. package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-write-repository.d.ts +161 -0
  126. package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-write-repository.js +1350 -0
  127. package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-write-repository.js.map +1 -0
  128. package/dist/server/modules/affairs-indexer/core/src/scanner/file-scanner.d.ts +32 -0
  129. package/dist/server/modules/affairs-indexer/core/src/scanner/file-scanner.js +208 -0
  130. package/dist/server/modules/affairs-indexer/core/src/scanner/file-scanner.js.map +1 -0
  131. package/dist/server/modules/affairs-indexer/core/src/services/dirty/dirty-scope-resolver.d.ts +30 -0
  132. package/dist/server/modules/affairs-indexer/core/src/services/dirty/dirty-scope-resolver.js +66 -0
  133. package/dist/server/modules/affairs-indexer/core/src/services/dirty/dirty-scope-resolver.js.map +1 -0
  134. package/dist/server/modules/affairs-indexer/core/src/services/export/export-builder.d.ts +33 -0
  135. package/dist/server/modules/affairs-indexer/core/src/services/export/export-builder.js +705 -0
  136. package/dist/server/modules/affairs-indexer/core/src/services/export/export-builder.js.map +1 -0
  137. package/dist/server/modules/affairs-indexer/core/src/services/indexer/allowed-extensions-diff-service.d.ts +80 -0
  138. package/dist/server/modules/affairs-indexer/core/src/services/indexer/allowed-extensions-diff-service.js +193 -0
  139. package/dist/server/modules/affairs-indexer/core/src/services/indexer/allowed-extensions-diff-service.js.map +1 -0
  140. package/dist/server/modules/affairs-indexer/core/src/services/indexer/text-indexer.d.ts +77 -0
  141. package/dist/server/modules/affairs-indexer/core/src/services/indexer/text-indexer.js +467 -0
  142. package/dist/server/modules/affairs-indexer/core/src/services/indexer/text-indexer.js.map +1 -0
  143. package/dist/server/modules/affairs-indexer/core/src/services/mcp/mcp-stdio-server.d.ts +17 -0
  144. package/dist/server/modules/affairs-indexer/core/src/services/mcp/mcp-stdio-server.js +264 -0
  145. package/dist/server/modules/affairs-indexer/core/src/services/mcp/mcp-stdio-server.js.map +1 -0
  146. package/dist/server/modules/affairs-indexer/core/src/services/search/offline-search-service.d.ts +11 -0
  147. package/dist/server/modules/affairs-indexer/core/src/services/search/offline-search-service.js +76 -0
  148. package/dist/server/modules/affairs-indexer/core/src/services/search/offline-search-service.js.map +1 -0
  149. package/dist/server/modules/affairs-indexer/core/src/services/search/search-index-builder.d.ts +26 -0
  150. package/dist/server/modules/affairs-indexer/core/src/services/search/search-index-builder.js +305 -0
  151. package/dist/server/modules/affairs-indexer/core/src/services/search/search-index-builder.js.map +1 -0
  152. package/dist/server/modules/affairs-indexer/core/src/services/tagging/tag-recompute-service.d.ts +53 -0
  153. package/dist/server/modules/affairs-indexer/core/src/services/tagging/tag-recompute-service.js +566 -0
  154. package/dist/server/modules/affairs-indexer/core/src/services/tagging/tag-recompute-service.js.map +1 -0
  155. package/dist/server/modules/affairs-indexer/core/src/services/watch/watch-service.d.ts +47 -0
  156. package/dist/server/modules/affairs-indexer/core/src/services/watch/watch-service.js +227 -0
  157. package/dist/server/modules/affairs-indexer/core/src/services/watch/watch-service.js.map +1 -0
  158. package/dist/server/modules/affairs-indexer/core/src/sqlite/catalog-schema.d.ts +5 -0
  159. package/dist/server/modules/affairs-indexer/core/src/sqlite/catalog-schema.js +245 -0
  160. package/dist/server/modules/affairs-indexer/core/src/sqlite/catalog-schema.js.map +1 -0
  161. package/dist/server/modules/affairs-indexer/core/src/sqlite/detect-catalog-schema.d.ts +14 -0
  162. package/dist/server/modules/affairs-indexer/core/src/sqlite/detect-catalog-schema.js +87 -0
  163. package/dist/server/modules/affairs-indexer/core/src/sqlite/detect-catalog-schema.js.map +1 -0
  164. package/dist/server/modules/affairs-indexer/core/src/sqlite/init-catalog.d.ts +13 -0
  165. package/dist/server/modules/affairs-indexer/core/src/sqlite/init-catalog.js +16 -0
  166. package/dist/server/modules/affairs-indexer/core/src/sqlite/init-catalog.js.map +1 -0
  167. package/dist/server/modules/affairs-indexer/core/src/sqlite/migration-runner.d.ts +22 -0
  168. package/dist/server/modules/affairs-indexer/core/src/sqlite/migration-runner.js +430 -0
  169. package/dist/server/modules/affairs-indexer/core/src/sqlite/migration-runner.js.map +1 -0
  170. package/dist/server/modules/affairs-indexer/core/src/sqlite/open-database.d.ts +9 -0
  171. package/dist/server/modules/affairs-indexer/core/src/sqlite/open-database.js +19 -0
  172. package/dist/server/modules/affairs-indexer/core/src/sqlite/open-database.js.map +1 -0
  173. package/dist/server/modules/affairs-indexer/core/src/tagging/simple-tag-inference.d.ts +21 -0
  174. package/dist/server/modules/affairs-indexer/core/src/tagging/simple-tag-inference.js +94 -0
  175. package/dist/server/modules/affairs-indexer/core/src/tagging/simple-tag-inference.js.map +1 -0
  176. package/dist/server/modules/affairs-indexer/core/src/utils/abort.d.ts +2 -0
  177. package/dist/server/modules/affairs-indexer/core/src/utils/abort.js +13 -0
  178. package/dist/server/modules/affairs-indexer/core/src/utils/abort.js.map +1 -0
  179. package/dist/server/modules/affairs-indexer/core/src/utils/file-streaming.d.ts +9 -0
  180. package/dist/server/modules/affairs-indexer/core/src/utils/file-streaming.js +64 -0
  181. package/dist/server/modules/affairs-indexer/core/src/utils/file-streaming.js.map +1 -0
  182. package/dist/server/modules/affairs-indexer/core/src/utils/root-command-lock.d.ts +10 -0
  183. package/dist/server/modules/affairs-indexer/core/src/utils/root-command-lock.js +230 -0
  184. package/dist/server/modules/affairs-indexer/core/src/utils/root-command-lock.js.map +1 -0
  185. package/dist/server/modules/affairs-indexer/core/src/utils/rss-log.d.ts +2 -0
  186. package/dist/server/modules/affairs-indexer/core/src/utils/rss-log.js +19 -0
  187. package/dist/server/modules/affairs-indexer/core/src/utils/rss-log.js.map +1 -0
  188. package/dist/server/modules/affairs-indexer/internal-command-runner.d.ts +31 -0
  189. package/dist/server/modules/affairs-indexer/internal-command-runner.js +643 -0
  190. package/dist/server/modules/affairs-indexer/internal-command-runner.js.map +1 -0
  191. package/dist/server/modules/assistant-capability/assistant-capability-controller.d.ts +0 -49
  192. package/dist/server/modules/assistant-capability/assistant-capability-controller.js +10 -56
  193. package/dist/server/modules/assistant-capability/assistant-capability-controller.js.map +1 -1
  194. package/dist/server/modules/assistant-capability/assistant-capability-service.d.ts +2 -46
  195. package/dist/server/modules/assistant-capability/assistant-capability-service.js +15 -158
  196. package/dist/server/modules/assistant-capability/assistant-capability-service.js.map +1 -1
  197. package/dist/server/modules/browser-runtime/opencli-bridge-browser-executor.d.ts +4 -2
  198. package/dist/server/modules/browser-runtime/opencli-bridge-browser-executor.js +62 -21
  199. package/dist/server/modules/browser-runtime/opencli-bridge-browser-executor.js.map +1 -1
  200. package/dist/server/modules/butler/butler-control-session-service.d.ts +3 -4
  201. package/dist/server/modules/butler/butler-control-session-service.js +39 -62
  202. package/dist/server/modules/butler/butler-control-session-service.js.map +1 -1
  203. package/dist/server/modules/butler/butler-controller.d.ts +11 -3
  204. package/dist/server/modules/butler/butler-controller.js +19 -4
  205. package/dist/server/modules/butler/butler-controller.js.map +1 -1
  206. package/dist/server/modules/butler/butler-follow-up-service.js.map +1 -1
  207. package/dist/server/modules/butler/butler-profile-service.d.ts +1 -1
  208. package/dist/server/modules/butler/butler-profile-service.js +34 -63
  209. package/dist/server/modules/butler/butler-profile-service.js.map +1 -1
  210. package/dist/server/modules/butler/butler-project-service.d.ts +1 -3
  211. package/dist/server/modules/butler/butler-project-service.js +1 -7
  212. package/dist/server/modules/butler/butler-project-service.js.map +1 -1
  213. package/dist/server/modules/butler/butler-session-service.d.ts +1 -0
  214. package/dist/server/modules/butler/butler-session-service.js +109 -0
  215. package/dist/server/modules/butler/butler-session-service.js.map +1 -1
  216. package/dist/server/modules/butler/butler-session-summary-service.js +0 -2
  217. package/dist/server/modules/butler/butler-session-summary-service.js.map +1 -1
  218. package/dist/server/modules/butler/butler-workspace-context.d.ts +5 -1
  219. package/dist/server/modules/butler/butler-workspace-context.js +21 -12
  220. package/dist/server/modules/butler/butler-workspace-context.js.map +1 -1
  221. package/dist/server/modules/file/file-content-service.d.ts +11 -0
  222. package/dist/server/modules/file/file-content-service.js +55 -0
  223. package/dist/server/modules/file/file-content-service.js.map +1 -1
  224. package/dist/server/modules/file/file-controller.d.ts +26 -1
  225. package/dist/server/modules/file/file-controller.js +59 -4
  226. package/dist/server/modules/file/file-controller.js.map +1 -1
  227. package/dist/server/modules/file/file-preview-link-service.d.ts +1 -0
  228. package/dist/server/modules/file/file-preview-link-service.js +25 -0
  229. package/dist/server/modules/file/file-preview-link-service.js.map +1 -1
  230. package/dist/server/modules/file/file-preview-service.js +15 -4
  231. package/dist/server/modules/file/file-preview-service.js.map +1 -1
  232. package/dist/server/modules/file/file-preview-types.d.ts +9 -1
  233. package/dist/server/modules/file/file-preview-types.js +8 -1
  234. package/dist/server/modules/file/file-preview-types.js.map +1 -1
  235. package/dist/server/modules/file/recent-modified-file-service.d.ts +15 -0
  236. package/dist/server/modules/file/recent-modified-file-service.js +102 -0
  237. package/dist/server/modules/file/recent-modified-file-service.js.map +1 -0
  238. package/dist/server/modules/file/runtime/codingns-workspace-bridge.js +6 -0
  239. package/dist/server/modules/file/workspace-file-bridge-service.d.ts +11 -0
  240. package/dist/server/modules/file/workspace-file-bridge-service.js +19 -0
  241. package/dist/server/modules/file/workspace-file-bridge-service.js.map +1 -1
  242. package/dist/server/modules/file/workspace-index-apply-service.d.ts +25 -0
  243. package/dist/server/modules/file/workspace-index-apply-service.js +42 -0
  244. package/dist/server/modules/file/workspace-index-apply-service.js.map +1 -0
  245. package/dist/server/modules/office/office-controller.d.ts +15 -1
  246. package/dist/server/modules/office/office-controller.js +26 -1
  247. package/dist/server/modules/office/office-controller.js.map +1 -1
  248. package/dist/server/modules/office/onlyoffice-integration-service.d.ts +78 -0
  249. package/dist/server/modules/office/onlyoffice-integration-service.js +610 -0
  250. package/dist/server/modules/office/onlyoffice-integration-service.js.map +1 -0
  251. package/dist/server/modules/plugins/plugin-file-gateway-service.d.ts +12 -0
  252. package/dist/server/modules/plugins/plugin-file-gateway-service.js +13 -0
  253. package/dist/server/modules/plugins/plugin-file-gateway-service.js.map +1 -1
  254. package/dist/server/modules/preferences/profile-service.d.ts +1 -0
  255. package/dist/server/modules/preferences/profile-service.js +27 -3
  256. package/dist/server/modules/preferences/profile-service.js.map +1 -1
  257. package/dist/server/modules/sessions/codex-app-server-helper-process.js +0 -8
  258. package/dist/server/modules/sessions/codex-app-server-helper-process.js.map +1 -1
  259. package/dist/server/modules/sessions/session-controller.d.ts +1 -0
  260. package/dist/server/modules/sessions/session-controller.js +3 -0
  261. package/dist/server/modules/sessions/session-controller.js.map +1 -1
  262. package/dist/server/modules/sessions/session-history-service.d.ts +2 -0
  263. package/dist/server/modules/sessions/session-history-service.js +78 -3
  264. package/dist/server/modules/sessions/session-history-service.js.map +1 -1
  265. package/dist/server/modules/sessions/session-live-runtime-service.d.ts +1 -0
  266. package/dist/server/modules/sessions/session-live-runtime-service.js +4 -0
  267. package/dist/server/modules/sessions/session-live-runtime-service.js.map +1 -1
  268. package/dist/server/modules/sessions/session-permission-request-service.js +0 -4
  269. package/dist/server/modules/sessions/session-permission-request-service.js.map +1 -1
  270. package/dist/server/modules/sessions/workspace-session-instruction-watch-service.d.ts +23 -0
  271. package/dist/server/modules/sessions/workspace-session-instruction-watch-service.js +122 -0
  272. package/dist/server/modules/sessions/workspace-session-instruction-watch-service.js.map +1 -0
  273. package/dist/server/modules/sessions/workspace-session-runtime-context-service.d.ts +15 -0
  274. package/dist/server/modules/sessions/workspace-session-runtime-context-service.js +93 -10
  275. package/dist/server/modules/sessions/workspace-session-runtime-context-service.js.map +1 -1
  276. package/dist/server/modules/skills/builtin-skills/codingns-assistant/SKILL.md +6 -7
  277. package/dist/server/modules/skills/builtin-skills/codingns-assistant/references/cli-workflow.md +2 -3
  278. package/dist/server/modules/system/host-resource-controller.d.ts +7 -0
  279. package/dist/server/modules/system/host-resource-controller.js +12 -0
  280. package/dist/server/modules/system/host-resource-controller.js.map +1 -0
  281. package/dist/server/modules/system/host-resource-service.d.ts +54 -0
  282. package/dist/server/modules/system/host-resource-service.js +162 -0
  283. package/dist/server/modules/system/host-resource-service.js.map +1 -0
  284. package/dist/server/modules/tasks/observability-service.d.ts +12 -2
  285. package/dist/server/modules/tasks/observability-service.js +13 -1
  286. package/dist/server/modules/tasks/observability-service.js.map +1 -1
  287. package/dist/server/modules/tasks/task-helper-client.d.ts +36 -2
  288. package/dist/server/modules/tasks/task-helper-client.js +201 -19
  289. package/dist/server/modules/tasks/task-helper-client.js.map +1 -1
  290. package/dist/server/modules/tasks/task-helper-pool.d.ts +37 -0
  291. package/dist/server/modules/tasks/task-helper-pool.js +173 -0
  292. package/dist/server/modules/tasks/task-helper-pool.js.map +1 -0
  293. package/dist/server/modules/tasks/task-helper-process-handlers.d.ts +27 -0
  294. package/dist/server/modules/tasks/task-helper-process-handlers.js +25 -1
  295. package/dist/server/modules/tasks/task-helper-process-handlers.js.map +1 -1
  296. package/dist/server/modules/tasks/task-helper-process.js +75 -26
  297. package/dist/server/modules/tasks/task-helper-process.js.map +1 -1
  298. package/dist/server/modules/tasks/task-helper-scheduling.d.ts +11 -0
  299. package/dist/server/modules/tasks/task-helper-scheduling.js +43 -0
  300. package/dist/server/modules/tasks/task-helper-scheduling.js.map +1 -0
  301. package/dist/server/modules/tasks/task-lane-executors.js +19 -3
  302. package/dist/server/modules/tasks/task-lane-executors.js.map +1 -1
  303. package/dist/server/modules/tasks/task-manager.d.ts +1 -0
  304. package/dist/server/modules/tasks/task-manager.js +3 -0
  305. package/dist/server/modules/tasks/task-manager.js.map +1 -1
  306. package/dist/server/modules/tasks/task-registry.d.ts +1 -0
  307. package/dist/server/modules/tasks/task-registry.js +3 -0
  308. package/dist/server/modules/tasks/task-registry.js.map +1 -1
  309. package/dist/server/modules/tasks/task-scheduler.d.ts +6 -0
  310. package/dist/server/modules/tasks/task-scheduler.js +162 -7
  311. package/dist/server/modules/tasks/task-scheduler.js.map +1 -1
  312. package/dist/server/modules/tasks/task-types.d.ts +28 -3
  313. package/dist/server/modules/tasks/task-types.js +14 -2
  314. package/dist/server/modules/tasks/task-types.js.map +1 -1
  315. package/dist/server/modules/workbench/affairs-assistant-session-snapshot-service.d.ts +68 -0
  316. package/dist/server/modules/workbench/affairs-assistant-session-snapshot-service.js +286 -0
  317. package/dist/server/modules/workbench/affairs-assistant-session-snapshot-service.js.map +1 -0
  318. package/dist/server/modules/workbench/workbench-controller.js +11 -1
  319. package/dist/server/modules/workbench/workbench-controller.js.map +1 -1
  320. package/dist/server/modules/workbench/workbench-service.d.ts +9 -2
  321. package/dist/server/modules/workbench/workbench-service.js +58 -18
  322. package/dist/server/modules/workbench/workbench-service.js.map +1 -1
  323. package/dist/server/modules/workspace/affairs-library-controller.d.ts +117 -0
  324. package/dist/server/modules/workspace/affairs-library-controller.js +164 -0
  325. package/dist/server/modules/workspace/affairs-library-controller.js.map +1 -0
  326. package/dist/server/modules/workspace/affairs-library-debug-log.d.ts +23 -0
  327. package/dist/server/modules/workspace/affairs-library-debug-log.js +107 -0
  328. package/dist/server/modules/workspace/affairs-library-debug-log.js.map +1 -0
  329. package/dist/server/modules/workspace/affairs-library-dirty-watch-service.d.ts +52 -0
  330. package/dist/server/modules/workspace/affairs-library-dirty-watch-service.js +555 -0
  331. package/dist/server/modules/workspace/affairs-library-dirty-watch-service.js.map +1 -0
  332. package/dist/server/modules/workspace/affairs-library-preview-link-service.d.ts +24 -0
  333. package/dist/server/modules/workspace/affairs-library-preview-link-service.js +157 -0
  334. package/dist/server/modules/workspace/affairs-library-preview-link-service.js.map +1 -0
  335. package/dist/server/modules/workspace/affairs-library-refresh-contract.d.ts +56 -0
  336. package/dist/server/modules/workspace/affairs-library-refresh-contract.js +48 -0
  337. package/dist/server/modules/workspace/affairs-library-refresh-contract.js.map +1 -0
  338. package/dist/server/modules/workspace/affairs-library-service.d.ts +344 -0
  339. package/dist/server/modules/workspace/affairs-library-service.js +3755 -0
  340. package/dist/server/modules/workspace/affairs-library-service.js.map +1 -0
  341. package/dist/server/modules/workspace/affairs-lightweight-session-controller.d.ts +78 -0
  342. package/dist/server/modules/workspace/affairs-lightweight-session-controller.js +146 -0
  343. package/dist/server/modules/workspace/affairs-lightweight-session-controller.js.map +1 -0
  344. package/dist/server/modules/workspace/affairs-lightweight-session-service.d.ts +133 -0
  345. package/dist/server/modules/workspace/affairs-lightweight-session-service.js +1447 -0
  346. package/dist/server/modules/workspace/affairs-lightweight-session-service.js.map +1 -0
  347. package/dist/server/modules/workspace/affairs-tag-controller.d.ts +107 -0
  348. package/dist/server/modules/workspace/affairs-tag-controller.js +97 -0
  349. package/dist/server/modules/workspace/affairs-tag-controller.js.map +1 -0
  350. package/dist/server/modules/workspace/affairs-tag-service.d.ts +153 -0
  351. package/dist/server/modules/workspace/affairs-tag-service.js +680 -0
  352. package/dist/server/modules/workspace/affairs-tag-service.js.map +1 -0
  353. package/dist/server/modules/workspace/workspace-controller.d.ts +2 -1
  354. package/dist/server/modules/workspace/workspace-controller.js +8 -2
  355. package/dist/server/modules/workspace/workspace-controller.js.map +1 -1
  356. package/dist/server/modules/workspace/workspace-service.js +60 -9
  357. package/dist/server/modules/workspace/workspace-service.js.map +1 -1
  358. package/dist/server/routes/affairs.d.ts +3 -0
  359. package/dist/server/routes/affairs.js +7 -0
  360. package/dist/server/routes/affairs.js.map +1 -0
  361. package/dist/server/routes/assistant.js +0 -5
  362. package/dist/server/routes/assistant.js.map +1 -1
  363. package/dist/server/routes/files.js +5 -0
  364. package/dist/server/routes/files.js.map +1 -1
  365. package/dist/server/routes/office.js +4 -0
  366. package/dist/server/routes/office.js.map +1 -1
  367. package/dist/server/routes/system.d.ts +2 -1
  368. package/dist/server/routes/system.js +2 -1
  369. package/dist/server/routes/system.js.map +1 -1
  370. package/dist/server/routes/workspaces.d.ts +4 -1
  371. package/dist/server/routes/workspaces.js +46 -1
  372. package/dist/server/routes/workspaces.js.map +1 -1
  373. package/dist/server/server/create-server.d.ts +6 -2
  374. package/dist/server/server/create-server.js +113 -32
  375. package/dist/server/server/create-server.js.map +1 -1
  376. package/dist/server/shared/http/error-handler.js +10 -0
  377. package/dist/server/shared/http/error-handler.js.map +1 -1
  378. package/dist/server/storage/repositories/affairs-assistant-session-snapshot-repository.d.ts +10 -0
  379. package/dist/server/storage/repositories/affairs-assistant-session-snapshot-repository.js +47 -0
  380. package/dist/server/storage/repositories/affairs-assistant-session-snapshot-repository.js.map +1 -0
  381. package/dist/server/storage/repositories/butler-profile-repository.js +7 -3
  382. package/dist/server/storage/repositories/butler-profile-repository.js.map +1 -1
  383. package/dist/server/storage/repositories/office-onlyoffice-setting-repository.d.ts +19 -0
  384. package/dist/server/storage/repositories/office-onlyoffice-setting-repository.js +55 -0
  385. package/dist/server/storage/repositories/office-onlyoffice-setting-repository.js.map +1 -0
  386. package/dist/server/storage/repositories/session-index-repository.js +9 -2
  387. package/dist/server/storage/repositories/session-index-repository.js.map +1 -1
  388. package/dist/server/storage/repositories/user-affairs-library-setting-repository.d.ts +10 -0
  389. package/dist/server/storage/repositories/user-affairs-library-setting-repository.js +69 -0
  390. package/dist/server/storage/repositories/user-affairs-library-setting-repository.js.map +1 -0
  391. package/dist/server/storage/repositories/user-preference-profile-repository.js +6 -3
  392. package/dist/server/storage/repositories/user-preference-profile-repository.js.map +1 -1
  393. package/dist/server/storage/repositories/workspace-navigation-state-repository.d.ts +3 -0
  394. package/dist/server/storage/repositories/workspace-navigation-state-repository.js +47 -4
  395. package/dist/server/storage/repositories/workspace-navigation-state-repository.js.map +1 -1
  396. package/dist/server/storage/sqlite/client.js +230 -123
  397. package/dist/server/storage/sqlite/client.js.map +1 -1
  398. package/dist/server/storage/sqlite/schema.sql +48 -25
  399. package/dist/server/types/domain.d.ts +27 -20
  400. package/dist/server/ws/workbench-ws-hub.js +2 -2
  401. package/dist/server/ws/workbench-ws-hub.js.map +1 -1
  402. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-permissions.js +0 -2
  403. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-permissions.js.map +1 -1
  404. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.js +0 -6
  405. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.js.map +1 -1
  406. package/package.json +1 -1
  407. package/dist/public/assets/AdaptiveButlerPage-B153lk5H.css +0 -1
  408. package/dist/public/assets/AdaptiveButlerPage-CJw8Ae62.js +0 -3
  409. package/dist/public/assets/DesktopModal-D_A8sgQU.js +0 -1
  410. package/dist/public/assets/DesktopWindowPage-DK7L7osV.js +0 -2
  411. package/dist/public/assets/FileContextPanel-BdCoubcJ.js +0 -1
  412. package/dist/public/assets/GitSidebar-BeZ0hj7A.js +0 -6
  413. package/dist/public/assets/MobileCreateSessionSheet-DfLMVu8q.js +0 -1
  414. package/dist/public/assets/MobileSheet-5kZ-w-gU.js +0 -1
  415. package/dist/public/assets/MobileWorkspaceSwitcherHeader-C6JMiOq_.js +0 -1
  416. package/dist/public/assets/PluginContainerPage-BlY-xJDh.js +0 -1
  417. package/dist/public/assets/SessionIndexPage-DkBp9Mqz.js +0 -1
  418. package/dist/public/assets/SettingsPage-C-ASmJAG.js +0 -2
  419. package/dist/public/assets/TerminalRuntimeFallbackModal-Bzum5nZ0.js +0 -1
  420. package/dist/public/assets/WorkbenchLayout-OFi6CWgH.js +0 -244
  421. package/dist/public/assets/WorkbenchShellRoute-B4XB8SwG.css +0 -1
  422. package/dist/public/assets/WorkbenchShellRoute-BAQe_E0O.js +0 -1
  423. package/dist/public/assets/WorkspaceDebugDetailPage-DhKa6e9y.js +0 -1
  424. package/dist/public/assets/file-tree-icon-Mg1DiBRX.js +0 -590
  425. package/dist/public/assets/index-C4t-vvqk.css +0 -1
  426. package/dist/public/assets/index-CL97fwWB.js +0 -42
  427. package/dist/public/assets/realtime-client-CLafKzzJ.js +0 -1
  428. package/dist/server/modules/butler/assistant-sandbox-cleanup-scheduler.d.ts +0 -32
  429. package/dist/server/modules/butler/assistant-sandbox-cleanup-scheduler.js +0 -93
  430. package/dist/server/modules/butler/assistant-sandbox-cleanup-scheduler.js.map +0 -1
  431. package/dist/server/modules/butler/assistant-sandbox-service.d.ts +0 -69
  432. package/dist/server/modules/butler/assistant-sandbox-service.js +0 -399
  433. package/dist/server/modules/butler/assistant-sandbox-service.js.map +0 -1
  434. package/dist/server/modules/channels/wechat-claw-client.d.ts +0 -51
  435. package/dist/server/modules/channels/wechat-claw-client.js +0 -245
  436. package/dist/server/modules/channels/wechat-claw-client.js.map +0 -1
  437. package/dist/server/storage/repositories/assistant-sandbox-workspace-repository.d.ts +0 -18
  438. package/dist/server/storage/repositories/assistant-sandbox-workspace-repository.js +0 -191
  439. package/dist/server/storage/repositories/assistant-sandbox-workspace-repository.js.map +0 -1
@@ -0,0 +1,1019 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FileContextPanel-BrKO8Xt6.js","assets/index-CeXGOT_T.js","assets/index-BxJPQpFM.css","assets/App-CFBwDUNA.js","assets/App-CcDXqFl1.css","assets/workbench-navigation-B7IjRQd8.js","assets/WorkbenchModal-NGmPgqaE.js","assets/DesktopModal-6ii53_Y9.js","assets/window-BVUB8gMK.js","assets/event-DvH9tcej.js","assets/relay-entry-Bg0OisQy.js","assets/MobileSheet-opTWyRe1.js","assets/GitSidebar-BdwiDtOr.js","assets/TerminalManagerPanel-CjzbiWjl.js","assets/terminal-runtime-meta-C8t-CIDF.js","assets/TerminalRuntimeFallbackModal-CSVVbO8r.js"])))=>i.map(i=>d[i]);
2
+ var iT=Object.defineProperty;var aT=(e,t,n)=>t in e?iT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ht=(e,t,n)=>aT(e,typeof t!="symbol"?t+"":t,n);import{C as ae,A as rr,b as d,U as Lk,t as a,j as s,e as Fr,m as fa,L as jl,V as Fu,H as Dk,w as iu,g as Ok,D as Fk,E as Br,p as _u,F as Rr,W as oT,X as lT,Y as _k,i as Bk,Z as eh,f as Bu,$ as cT,h as au,a0 as uT,l as Wk,n as dT,z as fT,y as hT,d as Ga,a1 as mT,a2 as pT,u as gT,G as Cd,a as Vp,T as Kp,a3 as bT,a4 as $k,a5 as yT,a6 as xT,a7 as kT,a8 as wT,a9 as vT,aa as ou,ab as ST,_ as bm}from"./index-CeXGOT_T.js";import{e as Hn,t as Kt,h as Wu,u as Nl,f as Vn,g as Bs,i as ha,v as CT,w as jT,j as NT,p as TT,O as jd}from"./App-CFBwDUNA.js";import{c as Mi,d as zk,j as Jn,A as Wi,B as rs,J as Jl,C as $i,k as Ot,M as Es,O as Xo,a as Yr,g as Hk,l as IT,b as ua,z as Uk,w as AT,Q as qk,f as Vk,D as Fs,i as Kk,h as Gk,e as Fi,R as Yk,S as Jk,L as RT,o as PT,T as MT,p as ET,y as Co,I as Ea,F as LT,r as DT,U as OT,u as FT,s as _T}from"./workbench-navigation-B7IjRQd8.js";import{t as Ba,P as lu,g as Xk}from"./window-BVUB8gMK.js";import{R as BT,_ as Gp,a as Yp,C as Qk,i as Wt}from"./event-DvH9tcej.js";import{M as Zk,D as Qr}from"./DesktopModal-6ii53_Y9.js";import{W as ln}from"./WorkbenchModal-NGmPgqaE.js";import{r as WT,b as $T}from"./relay-entry-Bg0OisQy.js";import{M as zi}from"./MobileSheet-opTWyRe1.js";function th(){return ae.request("/api/workspaces")}async function zT(e){const t=new Headers;e!=null&&e.refresh&&t.set("X-CodingNS-Workbench-Refresh","true"),e!=null&&e.awaitDiscovery&&t.set("X-CodingNS-Workbench-Await-Discovery","true");try{return await ae.request("/api/workbench",{headers:t})}catch(n){if(!(n instanceof rr)||n.status!==404)throw n;const r=await th();return{items:await Promise.all(r.items.map(async o=>({workspace:o,sessions:(await c0(o.id)).items})))}}}function HT(e){return ae.request("/api/workspaces/import",{method:"POST",body:JSON.stringify(e)})}function UT(e){return ae.request("/api/workspaces/clone",{method:"POST",body:JSON.stringify(e)})}function qT(e){return ae.request(`/api/workspaces/${encodeURIComponent(e)}`,{method:"DELETE"})}function fV(e){return ae.request("/api/debug-targets/analyze",{method:"POST",body:JSON.stringify(e)})}function hV(e,t){return ae.request(`/api/debug-targets/${encodeURIComponent(e)}/launch-plan`,{method:"POST",body:JSON.stringify({})})}function mV(){return ae.request("/api/framework-compatibility-matrix")}function VT(e){return ae.request("/api/workspaces/reorder",{method:"PUT",body:JSON.stringify(e)})}function ew(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/navigation-state`,{method:"PUT",body:JSON.stringify(t)})}function tw(){return ae.request("/api/affairs/library-binding")}function nw(e){return ae.request("/api/affairs/library-binding",{method:"PUT",body:JSON.stringify(e)})}function sw(e){return ae.request("/api/affairs/library-enabled",{method:"PUT",body:JSON.stringify(e)})}function Zi(e){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-snapshot`)}function Xl(e){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-config`)}function KT(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-config`,{method:"PUT",body:JSON.stringify(t)})}function jo(e,t){var r,i,o;const n=new URLSearchParams;if(n.set("browseMode",t.browseMode),(r=t.selectedFolderPath)!=null&&r.trim()&&n.set("selectedFolderPath",t.selectedFolderPath.trim()),(i=t.selectedTagPath)!=null&&i.trim()&&n.set("selectedTagPath",t.selectedTagPath.trim()),Array.isArray(t.selectedTagPaths)){const l=t.selectedTagPaths.map(c=>c.trim()).filter(c=>c.length>0);l.length>0&&n.set("selectedTagPaths",l.join(","))}return(o=t.selectedFavoriteId)!=null&&o.trim()&&n.set("selectedFavoriteId",t.selectedFavoriteId.trim()),typeof t.offset=="number"&&n.set("offset",String(t.offset)),typeof t.limit=="number"&&n.set("limit",String(t.limit)),ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-documents?${n.toString()}`)}function GT(e,t){var i;const n=new URLSearchParams;(i=t==null?void 0:t.path)!=null&&i.trim()&&n.set("path",t.path.trim()),n.set("limit",String(t.limit));const r=n.toString();return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-files${r?`?${r}`:""}`)}function $u(e,t){return ym(e,t)}function ym(e,t,n){const r=new URLSearchParams({path:t});return(n==null?void 0:n.officeDisplayMode)==="reading"&&r.set("displayMode","reading"),ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-preview?${r.toString()}`)}function YT(e,t){const n=new URLSearchParams({path:t});return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-download?${n.toString()}`)}function Wa(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-ops`,{method:"POST",body:JSON.stringify(t)})}function Jp(e,t={}){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/library-refresh`,{method:"POST",body:JSON.stringify(t)})}function JT(e){return ae.request("/api/affairs/library-favorites",{method:"PUT",body:JSON.stringify(e)})}function XT(e,t){const n=new URLSearchParams,r=n.toString()?`?${n.toString()}`:"";return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/tags${r}`)}function QT(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/tags`,{method:"POST",body:JSON.stringify(t)})}function ZT(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/tags/${encodeURIComponent(t)}`)}function e0(e,t,n){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/tags/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)})}function t0(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/tags/${encodeURIComponent(t)}`,{method:"DELETE"})}function n0(e){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/tags/recovery/recompute`,{method:"POST"})}function nh(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/documents/${encodeURIComponent(t)}/tag-details`)}function s0(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/documents/${encodeURIComponent(t)}/tag-task`)}function r0(e,t,n){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/documents/${encodeURIComponent(t)}/tags`,{method:"PUT",body:JSON.stringify(n)})}function i0(e,t,n){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/documents/${encodeURIComponent(t)}/tags`,{method:"PUT",body:JSON.stringify(n)})}function sh(e,t){const n=new URLSearchParams({folderPath:t});return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/folders/tag-details?${n.toString()}`)}function Xp(e){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/tags/recovery/status`)}function a0(e,t){const n=new URLSearchParams({folderPath:t});return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/folders/tag-task?${n.toString()}`)}function o0(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/folders/tags`,{method:"PUT",body:JSON.stringify(t)})}function l0(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/folders/tags`,{method:"PUT",body:JSON.stringify(t)})}function rw(e){const t=new URLSearchParams;return e!=null&&e.trim()&&t.set("path",e.trim()),ae.request(`/api/workspaces/browse${t.size>0?`?${t.toString()}`:""}`)}function iw(e){return ae.request("/api/workspaces/directories",{method:"POST",body:JSON.stringify(e)})}function c0(e){return ae.request(`/api/sessions?workspaceId=${encodeURIComponent(e)}`)}function pV(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}`)}function gV(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}/changed-files`)}function Qp(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}/seen`,{method:"POST"})}function xm(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/title`,{method:"PATCH",body:JSON.stringify({title:t})})}function cu(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/archive`,{method:"PATCH",body:JSON.stringify({archived:t})})}function aw(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/favorite`,{method:"PATCH",body:JSON.stringify({favorite:t})})}function rh(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function u0(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/parallel-groups`,{method:"POST",body:JSON.stringify(t)})}function d0(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/parallel-groups`,{method:"POST",body:JSON.stringify(t)})}function bV(e){return ae.request(`/api/parallel-groups/${encodeURIComponent(e)}`)}function f0(e,t){return ae.request(`/api/parallel-groups/${encodeURIComponent(e)}/members`,{method:"POST",body:JSON.stringify(t)})}function yV(e){return ae.request(`/api/session-isolated-workspaces/${encodeURIComponent(e)}/promote`,{method:"POST"})}function h0(e){return ae.request("/api/worktrees",{method:"POST",body:JSON.stringify(e)})}function m0(e){return ae.request(`/api/worktrees/${encodeURIComponent(e)}/merge-preview`,{method:"POST"})}function p0(e){return ae.request(`/api/worktrees/${encodeURIComponent(e)}/merge-into-parent`,{method:"POST"})}function g0(e,t){return ae.request(`/api/worktrees/${encodeURIComponent(e)}/cleanup`,{method:"POST",body:JSON.stringify(t??{})})}function xV(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}/capabilities`)}function ow(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}/permission-requests`)}function b0(){return ae.request("/api/preferences/quick-phrases")}function y0(e){return ae.request("/api/preferences/quick-phrases",{method:"PUT",body:JSON.stringify({items:e})})}function no(e,t,n){var i;const r=new URLSearchParams;return t!=null&&t.trim()&&r.set("workspaceId",t.trim()),(n==null?void 0:n.providerConfigMode)==="cc-switch-preset"&&((i=n.providerPresetId)!=null&&i.trim())&&(r.set("providerConfigMode","cc-switch-preset"),r.set("providerPresetId",n.providerPresetId.trim())),ae.request(`/api/providers/${encodeURIComponent(e)}/capabilities${r.size>0?`?${r.toString()}`:""}`)}async function x0(){return(await ae.request("/api/providers/catalog")).items}async function k0(){return(await ae.request("/api/providers/catalog/refresh",{method:"POST"})).items}async function w0(e,t){return(await ae.request(`/api/providers/catalog/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({enabled:t})})).item}async function km(e,t){const n=await Promise.allSettled(e.map(async i=>[i,await no(i,t)])),r=[];for(const i of n){if(i.status!=="fulfilled")continue;const[o,l]=i.value;r.push([o,l])}return Object.fromEntries(r)}function uu(e,t,n,r="forward"){const i=new URLSearchParams;return t&&i.set("cursor",t),i.set("limit",String(n)),i.set("direction",r),ae.request(`/api/sessions/${encodeURIComponent(e)}/messages?${i.toString()}`)}function lw(e,t){return ae.requestBlob(`/api/sessions/${encodeURIComponent(e)}/attachments/${encodeURIComponent(t)}/content`)}function kV(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify(t)})}function wV(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/forks`,{method:"POST",body:JSON.stringify(t)})}function vV(e){return ae.request("/api/sessions/start-live",{method:"POST",body:JSON.stringify(e)})}function v0(e){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions`)}function S0(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/${encodeURIComponent(t)}`)}function cw(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/${encodeURIComponent(t)}/messages`)}function Zp(e,t,n){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/${encodeURIComponent(t)}/seen`,{method:"POST",body:JSON.stringify(n?{seenAt:n}:{})})}function C0(e,t,n){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/${encodeURIComponent(t)}/title`,{method:"PATCH",body:JSON.stringify({title:n})})}function eg(e,t,n){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/${encodeURIComponent(t)}/archive`,{method:"PATCH",body:JSON.stringify({archived:n})})}function j0(e,t,n){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/${encodeURIComponent(t)}/favorite`,{method:"PATCH",body:JSON.stringify({favorite:n})})}function N0(e,t){return ae.request(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/${encodeURIComponent(t)}`,{method:"DELETE"})}async function T0(e,t,n){const r=await ae.requestRaw(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/stream`,{method:"POST",body:JSON.stringify(t)});return uw(r,n)}async function I0(e,t,n,r){const i=await ae.requestRaw(`/api/workspaces/${encodeURIComponent(e)}/affairs/lightweight-sessions/${encodeURIComponent(t)}/messages/stream`,{method:"POST",body:JSON.stringify(n)});return uw(i,r)}function SV(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/messages/live`,{method:"POST",body:JSON.stringify(t)})}function CV(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}/queue`)}function jV(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/queue`,{method:"POST",body:JSON.stringify(t)})}function NV(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/queue/${encodeURIComponent(t)}`,{method:"DELETE"})}function TV(e,t){return ae.request(`/api/sessions/${encodeURIComponent(e)}/queue/${encodeURIComponent(t)}/steer`,{method:"POST"})}function A0(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}/runtime`)}function R0(e){return ae.request(`/api/sessions/${encodeURIComponent(e)}/interrupt`,{method:"POST"})}function P0(e,t,n){return ae.request(`/api/sessions/${encodeURIComponent(e)}/permission-requests/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify(n)})}async function uw(e,t){var c;const n=(c=e.body)==null?void 0:c.getReader();if(!n)throw new rr(0,{detail:"轻量会话流式响应为空",error_code:"INVALID_RESPONSE"});const r=new TextDecoder;let i="",o=null;const l=async u=>{const f=u.trim();if(!f)return;let h;try{h=JSON.parse(f)}catch(m){const g=m instanceof Error?`:${m.message}`:"";throw new rr(0,{detail:`轻量会话流式响应不是合法 JSON${g}`,error_code:"INVALID_RESPONSE"})}if(h.type==="error")throw new rr(502,{detail:h.detail,error_code:h.errorCode});h.type==="completed"&&(o=h.result),await t(h)};for(;;){const u=await n.read();i+=r.decode(u.value??new Uint8Array,{stream:!u.done});let f=i.indexOf(`
3
+ `);for(;f>=0;){const h=i.slice(0,f);i=i.slice(f+1),await l(h),f=i.indexOf(`
4
+ `)}if(u.done)break}if(i.trim()&&await l(i),!o)throw new rr(0,{detail:"轻量会话流式响应提前结束,缺少 completed 事件",error_code:"INVALID_RESPONSE"});return o}const qc="codingns.workspace.session-display-sort-mode",Vc="codingns.file-panel.show-system-files",wm="codingns.notification.preferences",wa={notifyOnPermissionRequest:!0,notifyOnSessionCompleted:!0,notifyOnSessionFailed:!0};function so(){return typeof window<"u"&&typeof window.localStorage<"u"}function M0(e){return e==="createdAt"||e==="updatedAt"||e==="title"}function tg(){if(!so())return"createdAt";const e=window.localStorage.getItem(qc);return M0(e)?e:"createdAt"}function ng(){return so()?window.localStorage.getItem(Vc)==="1":!1}function Nd(e){return typeof e=="boolean"}function sg(){if(!so())return wa;const e=window.localStorage.getItem(wm);if(!e)return wa;try{const t=JSON.parse(e);return{notifyOnPermissionRequest:Nd(t.notifyOnPermissionRequest)?t.notifyOnPermissionRequest:wa.notifyOnPermissionRequest,notifyOnSessionCompleted:Nd(t.notifyOnSessionCompleted)?t.notifyOnSessionCompleted:wa.notifyOnSessionCompleted,notifyOnSessionFailed:Nd(t.notifyOnSessionFailed)?t.notifyOnSessionFailed:wa.notifyOnSessionFailed}}catch{return wa}}function rg(e,t){return e.notifyOnPermissionRequest===t.notifyOnPermissionRequest&&e.notifyOnSessionCompleted===t.notifyOnSessionCompleted&&e.notifyOnSessionFailed===t.notifyOnSessionFailed}function E0(e){so()&&window.localStorage.setItem(wm,JSON.stringify(e))}class L0{constructor(){ht(this,"state",{sessionDisplaySortMode:tg(),showSystemFiles:ng(),notificationPreferences:sg()});ht(this,"listeners",new Set);ht(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));ht(this,"getState",()=>this.state);ht(this,"handleStorage",t=>{if(t.key!==null&&t.key!==qc&&t.key!==Vc&&t.key!==wm)return;const n=tg(),r=ng(),i=sg(),o=this.state.sessionDisplaySortMode===n,l=this.state.showSystemFiles===r,c=rg(this.state.notificationPreferences,i);o&&l&&c||(this.state={sessionDisplaySortMode:n,showSystemFiles:r,notificationPreferences:i},this.emit())});typeof window<"u"&&window.addEventListener("storage",this.handleStorage)}setSessionDisplaySortMode(t){so()&&(t==="createdAt"?window.localStorage.removeItem(qc):window.localStorage.setItem(qc,t)),this.state.sessionDisplaySortMode!==t&&(this.state={...this.state,sessionDisplaySortMode:t},this.emit())}setShowSystemFiles(t){so()&&(t?window.localStorage.setItem(Vc,"1"):window.localStorage.removeItem(Vc)),this.state.showSystemFiles!==t&&(this.state={...this.state,showSystemFiles:t},this.emit())}setNotificationPreferences(t){const n={...this.state.notificationPreferences,...t};rg(this.state.notificationPreferences,n)||(E0(n),this.state={...this.state,notificationPreferences:n},this.emit())}emit(){for(const t of this.listeners)t()}}const ig=new L0;function Ql(e){return d.useSyncExternalStore(ig.subscribe,()=>e(ig.getState()))}const D0="codingns.debug.perf",O0="codingns.debug.sessionMessageDedup",F0="codingns.debug.timelineScroll",_0="codingns.debug.conversationTimeline";function B0(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(D0)==="1"}catch{return!1}}function Xt(e,t){if(!B0()||typeof performance>"u")return;const n=Math.round(performance.now());if(t&&Object.keys(t).length>0){console.info(`[perf-ui] ${e} ${n}ms`,t);return}console.info(`[perf-ui] ${e} ${n}ms`)}function W0(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(O0)==="1"}catch{return!1}}function Hi(e,t){if(!W0()||typeof performance>"u")return;const n=Math.round(performance.now()),r={scope:e,timestampMs:n,...t??{}};try{const i=window,o=i.__CODINGNS_SESSION_MESSAGE_DEDUP_DEBUG__??[];o.push(r),o.length>300&&o.splice(0,o.length-300),i.__CODINGNS_SESSION_MESSAGE_DEDUP_DEBUG__=o}catch{}if(t&&Object.keys(t).length>0){console.info(`[session-dedup] ${e} ${n}ms`,t);return}console.info(`[session-dedup] ${e} ${n}ms`)}function $0(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(_0)==="1"}catch{return!1}}function z0(e,t){if(!$0()||typeof performance>"u")return;const n=Math.round(performance.now()),r={scope:e,timestampMs:n,...t??{}};try{const i=window;i.__CODINGNS_CONVERSATION_TIMELINE_DEBUG_CLEARED__!==!0&&(i.__CODINGNS_OPENCODE_ORDER_DEBUG__=[],i.__CODINGNS_SESSION_MESSAGE_DEDUP_DEBUG__=[],i.__CODINGNS_TIMELINE_SCROLL_DEBUG__=[],i.__CODINGNS_CONVERSATION_TIMELINE_DEBUG__=[],i.__CODINGNS_CONVERSATION_TIMELINE_DEBUG_CLEARED__=!0);const o=i.__CODINGNS_CONVERSATION_TIMELINE_DEBUG__??[];o.push(r),o.length>400&&o.splice(0,o.length-400),i.__CODINGNS_CONVERSATION_TIMELINE_DEBUG__=o}catch{}if(t&&Object.keys(t).length>0){console.info(`[conversation-timeline] ${e} ${n}ms`,t);return}console.info(`[conversation-timeline] ${e} ${n}ms`)}function ih(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(F0)==="1"}catch{return!1}}function H0(e,t){if(!ih()||typeof performance>"u")return;const n=Math.round(performance.now()),r={scope:e,timestampMs:n,...t??{}};try{const i=window,o=i.__CODINGNS_TIMELINE_SCROLL_DEBUG__??[];o.push(r),o.length>300&&o.splice(0,o.length-300),i.__CODINGNS_TIMELINE_SCROLL_DEBUG__=o}catch{}if(t&&Object.keys(t).length>0){console.info(`[timeline-scroll] ${e} ${n}ms`,t);return}console.info(`[timeline-scroll] ${e} ${n}ms`)}function dw(e){return ae.request(`/api/office/artifacts/${encodeURIComponent(e)}/preview-link`)}function fw(e,t){return ae.request(`/api/office/tasks/${encodeURIComponent(e)}/files/${encodeURIComponent(t)}/preview-link`)}function U0(e,t){const n=new URLSearchParams({workspaceId:e});return t&&n.set("path",t),ae.request(`/api/files/tree?${n.toString()}`)}function q0(e,t,n,r){return ae.request("/api/files/content",{method:"PUT",body:JSON.stringify({workspaceId:e,path:t,content:n,expectedVersion:r??void 0})})}function IV(e){return ae.request("/api/files/ops",{method:"POST",body:JSON.stringify(e)})}function AV(e){return ae.request("/api/files/upload",{method:"POST",body:JSON.stringify(e)})}function RV(e,t){const n=new URLSearchParams({workspaceId:e,path:t});return ae.request(`/api/files/download?${n.toString()}`)}function V0(e,t,n=1,r=20){const i=new URLSearchParams({workspaceId:e,keyword:t,page:String(n),pageSize:String(r)});return ae.request(`/api/files/search?${i.toString()}`)}function K0(e,t){var r;const n=new URLSearchParams({workspaceId:e,limit:String((t==null?void 0:t.limit)??10)});return(r=t==null?void 0:t.keyword)!=null&&r.trim()&&n.set("keyword",t.keyword.trim()),ae.request(`/api/files/recent-modified?${n.toString()}`)}function vm(e,t,n){const r=new URLSearchParams({workspaceId:e,path:t});return(n==null?void 0:n.officeDisplayMode)==="reading"&&r.set("displayMode","reading"),ae.request(`/api/files/preview?${r.toString()}`)}function zu(e,t){const n=new URLSearchParams({workspaceId:e,path:t});return ae.request(`/api/files/preview-link?${n.toString()}`)}function PV(e){return ae.request(`/api/git/status?workspaceId=${encodeURIComponent(e)}`)}function MV(e){return ae.request("/api/git/init",{method:"POST",body:JSON.stringify({workspaceId:e})})}function EV(e,t,n){const r=new URLSearchParams({workspaceId:e,path:t,staged:String(n)});return ae.request(`/api/git/diff?${r.toString()}`)}function LV(e,t){return ae.request("/api/git/stage",{method:"POST",body:JSON.stringify({workspaceId:e,targets:t})})}function DV(e,t){return ae.request("/api/git/unstage",{method:"POST",body:JSON.stringify({workspaceId:e,targets:t})})}function OV(e,t){return ae.request("/api/git/discard",{method:"POST",body:JSON.stringify({workspaceId:e,targets:t})})}function FV(e,t){return ae.request("/api/git/commit/draft",{method:"POST",body:JSON.stringify({workspaceId:e,mode:t})})}function _V(e,t){return ae.request("/api/git/commit",{method:"POST",body:JSON.stringify({workspaceId:e,draft:t})})}function BV(e){return ae.request("/api/git/commit/undo",{method:"POST",body:JSON.stringify({workspaceId:e})})}function WV(e,t=5,n=null){const r=new URLSearchParams({workspaceId:e,limit:String(t)});return n&&r.set("cursor",n),ae.request(`/api/git/history?${r.toString()}`)}function $V(e,t){const n=new URLSearchParams({workspaceId:e,commitHash:t});return ae.request(`/api/git/commit-detail?${n.toString()}`)}function G0(e){return ae.request(`/api/git/branches?workspaceId=${encodeURIComponent(e)}`)}function Y0(e){return ae.request(`/api/git/tags?workspaceId=${encodeURIComponent(e)}`)}function zV(e,t,n){return ae.request("/api/git/branches/switch",{method:"POST",body:JSON.stringify({workspaceId:e,branchName:t,create:n})})}function HV(e,t,n,r,i){return ae.request("/api/git/remote/sync",{method:"POST",body:JSON.stringify({workspaceId:e,action:t,...n?{remote:n}:{},...r?{auth:r}:{},...i?{remember:i}:{}})})}function UV(e){return ae.request(`/api/git/remotes?workspaceId=${encodeURIComponent(e)}`)}const J0={files:{kind:"files",label:"文件",defaultFocusOwner:"file-context-panel"},git:{kind:"git",label:"Git",defaultFocusOwner:"git-sidebar"},processes:{kind:"processes",label:"调试",defaultFocusOwner:"terminal-manager-panel"},terminals:{kind:"terminals",label:"终端",defaultFocusOwner:"terminal-page"},affairs:{kind:"affairs",label:"事务",defaultFocusOwner:"affairs-workbench"},code:{kind:"code",label:"代码",defaultFocusOwner:"code-workbench"}};function hw(e){return{...e,bounds:{...e.bounds},payload:{...e.payload}}}function mw(e,t,n){t&&(e.windows.registerDescriptor(t),n?e.windows.markWindowOpen(t.windowId):e.windows.markWindowClosed(t.windowId))}function X0(e){return J0[e]}function pw(e,t){return`${e}-${t}`}function gw(e){return e.trim().replace(/\\/g,"/")}function ag(e){return encodeURIComponent(e).replace(/%/g,"_").replace(/\./g,"_")}function Q0(e,t){const n=e.trim(),r=gw(t);return`file-preview-${ag(n)}-${ag(r)}`}async function fo(e,t,n){const r=n.workspaceId.trim(),i=X0(t);if(!e.isDesktop||!e.bridge.supported)return{ok:!1,errorCode:"PLATFORM_NOT_SUPPORTED",detail:"当前运行环境不支持桌面外部窗口。"};if(!r)return{ok:!1,errorCode:"WINDOW_WORKSPACE_REQUIRED",detail:`${i.label}外部窗口必须绑定工作区。`};const o=pw(t,r),l=e.windows.getDescriptor(o),c=l?hw(l):null,u=e.windows.isWindowOpen(o),f=Lk({windowId:o,kind:t,workspaceId:r,workspaceName:n.workspaceName??(c==null?void 0:c.workspaceName)??null,sessionId:n.sessionId??(c==null?void 0:c.sessionId)??null,mode:"external",bounds:c==null?void 0:c.bounds,focusOwner:n.focusOwner??i.defaultFocusOwner,payload:{routePath:n.routePath??(c==null?void 0:c.payload.routePath)??null}});e.windows.registerDescriptor(f);const h=await e.bridge.createWindow(f);return h.ok?(e.windows.markWindowOpen(o),{ok:!0,value:f}):(c?mw(e,c,u):e.windows.removeWindow(o),{ok:!1,errorCode:h.errorCode,detail:h.detail})}async function Z0(e,t,n){const r=n.workspaceId.trim(),i=gw(n.filePath);if(!e.isDesktop||!e.bridge.supported)return{ok:!1,errorCode:"PLATFORM_NOT_SUPPORTED",detail:"当前运行环境不支持桌面外部窗口。"};if(!r)return{ok:!1,errorCode:"WINDOW_WORKSPACE_REQUIRED",detail:"文件预览外部窗口必须绑定工作区。"};if(!i)return{ok:!1,errorCode:"WINDOW_FILE_REQUIRED",detail:"文件预览外部窗口必须指定文件。"};const o=Q0(r,i),l=e.windows.getDescriptor(o),c=l?hw(l):null,u=e.windows.isWindowOpen(o),f=Lk({windowId:o,kind:t,workspaceId:r,workspaceName:n.workspaceName??(c==null?void 0:c.workspaceName)??null,sessionId:n.sessionId??(c==null?void 0:c.sessionId)??null,mode:"external",bounds:n.bounds??(c==null?void 0:c.bounds)??{width:1120,height:760,minWidth:720,minHeight:480},focusOwner:n.focusOwner??"file-preview-window",payload:{filePath:i}});e.windows.registerDescriptor(f);const h=await e.bridge.createWindow(f);return h.ok?(e.windows.markWindowOpen(o),{ok:!0,value:f}):(c?mw(e,c,u):e.windows.removeWindow(o),{ok:!1,errorCode:h.errorCode,detail:h.detail})}function qV(e){return pw("terminals",e)}function eI(e,t){return fo(e,"files",t)}function tI(e,t){return fo(e,"git",t)}function nI(e,t){return fo(e,"processes",t)}function VV(e,t){return fo(e,"terminals",t)}function sI(e,t){return fo(e,"affairs",t)}function rI(e,t){return fo(e,"code",t)}function KV(e,t){return Z0(e,"file-preview",t)}var Kc,Gc;function bw(e){var t;if("items"in e)e.items=(t=e.items)===null||t===void 0?void 0:t.map(n=>"rid"in n?n:bw(n));else if("action"in e&&e.action){const n=new Qk;return n.onmessage=e.action,delete e.action,{...e,handler:n}}return e}async function ho(e,t){const n=new Qk;if(t&&typeof t=="object"&&("action"in t&&t.action&&(n.onmessage=t.action,delete t.action),"item"in t&&t.item&&typeof t.item=="object"&&"About"in t.item&&t.item.About&&typeof t.item.About=="object"&&"icon"in t.item.About&&t.item.About.icon&&(t.item.About.icon=Ba(t.item.About.icon)),"icon"in t&&t.icon&&(t.icon=Ba(t.icon)),"items"in t&&t.items)){let r=function(i){var o;return"rid"in i?[i.rid,i.kind]:("item"in i&&typeof i.item=="object"&&(!((o=i.item.About)===null||o===void 0)&&o.icon)&&(i.item.About.icon=Ba(i.item.About.icon)),"icon"in i&&i.icon&&(i.icon=Ba(i.icon)),"items"in i&&i.items&&(i.items=i.items.map(r)),bw(i))};t.items=t.items.map(r)}return Wt("plugin:menu|new",{kind:e,options:t,handler:n})}class mo extends BT{get id(){return Gp(this,Kc,"f")}get kind(){return Gp(this,Gc,"f")}constructor(t,n,r){super(t),Kc.set(this,void 0),Gc.set(this,void 0),Yp(this,Kc,n),Yp(this,Gc,r)}}Kc=new WeakMap,Gc=new WeakMap;class Sm extends mo{constructor(t,n){super(t,n,"MenuItem")}static async new(t){return ho("MenuItem",t).then(([n,r])=>new Sm(n,r))}async text(){return Wt("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(t){return Wt("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:t})}async isEnabled(){return Wt("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(t){return Wt("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:t})}async setAccelerator(t){return Wt("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:t})}}class Cm extends mo{constructor(t,n){super(t,n,"Check")}static async new(t){return ho("Check",t).then(([n,r])=>new Cm(n,r))}async text(){return Wt("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(t){return Wt("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:t})}async isEnabled(){return Wt("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(t){return Wt("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:t})}async setAccelerator(t){return Wt("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:t})}async isChecked(){return Wt("plugin:menu|is_checked",{rid:this.rid})}async setChecked(t){return Wt("plugin:menu|set_checked",{rid:this.rid,checked:t})}}var og;(function(e){e.Add="Add",e.Advanced="Advanced",e.Bluetooth="Bluetooth",e.Bookmarks="Bookmarks",e.Caution="Caution",e.ColorPanel="ColorPanel",e.ColumnView="ColumnView",e.Computer="Computer",e.EnterFullScreen="EnterFullScreen",e.Everyone="Everyone",e.ExitFullScreen="ExitFullScreen",e.FlowView="FlowView",e.Folder="Folder",e.FolderBurnable="FolderBurnable",e.FolderSmart="FolderSmart",e.FollowLinkFreestanding="FollowLinkFreestanding",e.FontPanel="FontPanel",e.GoLeft="GoLeft",e.GoRight="GoRight",e.Home="Home",e.IChatTheater="IChatTheater",e.IconView="IconView",e.Info="Info",e.InvalidDataFreestanding="InvalidDataFreestanding",e.LeftFacingTriangle="LeftFacingTriangle",e.ListView="ListView",e.LockLocked="LockLocked",e.LockUnlocked="LockUnlocked",e.MenuMixedState="MenuMixedState",e.MenuOnState="MenuOnState",e.MobileMe="MobileMe",e.MultipleDocuments="MultipleDocuments",e.Network="Network",e.Path="Path",e.PreferencesGeneral="PreferencesGeneral",e.QuickLook="QuickLook",e.RefreshFreestanding="RefreshFreestanding",e.Refresh="Refresh",e.Remove="Remove",e.RevealFreestanding="RevealFreestanding",e.RightFacingTriangle="RightFacingTriangle",e.Share="Share",e.Slideshow="Slideshow",e.SmartBadge="SmartBadge",e.StatusAvailable="StatusAvailable",e.StatusNone="StatusNone",e.StatusPartiallyAvailable="StatusPartiallyAvailable",e.StatusUnavailable="StatusUnavailable",e.StopProgressFreestanding="StopProgressFreestanding",e.StopProgress="StopProgress",e.TrashEmpty="TrashEmpty",e.TrashFull="TrashFull",e.User="User",e.UserAccounts="UserAccounts",e.UserGroup="UserGroup",e.UserGuest="UserGuest"})(og||(og={}));class jm extends mo{constructor(t,n){super(t,n,"Icon")}static async new(t){return ho("Icon",t).then(([n,r])=>new jm(n,r))}async text(){return Wt("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(t){return Wt("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:t})}async isEnabled(){return Wt("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(t){return Wt("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:t})}async setAccelerator(t){return Wt("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:t})}async setIcon(t){return Wt("plugin:menu|set_icon",{rid:this.rid,kind:this.kind,icon:Ba(t)})}}class Nm extends mo{constructor(t,n){super(t,n,"Predefined")}static async new(t){return ho("Predefined",t).then(([n,r])=>new Nm(n,r))}async text(){return Wt("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(t){return Wt("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:t})}}function Ya([e,t,n]){switch(n){case"Submenu":return new Hu(e,t);case"Predefined":return new Nm(e,t);case"Check":return new Cm(e,t);case"Icon":return new jm(e,t);case"MenuItem":default:return new Sm(e,t)}}class Hu extends mo{constructor(t,n){super(t,n,"Submenu")}static async new(t){return ho("Submenu",t).then(([n,r])=>new Hu(n,r))}async text(){return Wt("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(t){return Wt("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:t})}async isEnabled(){return Wt("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(t){return Wt("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:t})}async append(t){return Wt("plugin:menu|append",{rid:this.rid,kind:this.kind,items:(Array.isArray(t)?t:[t]).map(n=>"rid"in n?[n.rid,n.kind]:n)})}async prepend(t){return Wt("plugin:menu|prepend",{rid:this.rid,kind:this.kind,items:(Array.isArray(t)?t:[t]).map(n=>"rid"in n?[n.rid,n.kind]:n)})}async insert(t,n){return Wt("plugin:menu|insert",{rid:this.rid,kind:this.kind,items:(Array.isArray(t)?t:[t]).map(r=>"rid"in r?[r.rid,r.kind]:r),position:n})}async remove(t){return Wt("plugin:menu|remove",{rid:this.rid,kind:this.kind,item:[t.rid,t.kind]})}async removeAt(t){return Wt("plugin:menu|remove_at",{rid:this.rid,kind:this.kind,position:t}).then(Ya)}async items(){return Wt("plugin:menu|items",{rid:this.rid,kind:this.kind}).then(t=>t.map(Ya))}async get(t){return Wt("plugin:menu|get",{rid:this.rid,kind:this.kind,id:t}).then(n=>n?Ya(n):null)}async popup(t,n){var r;return Wt("plugin:menu|popup",{rid:this.rid,kind:this.kind,window:(r=n==null?void 0:n.label)!==null&&r!==void 0?r:null,at:t instanceof lu?t:t?new lu(t):null})}async setAsWindowsMenuForNSApp(){return Wt("plugin:menu|set_as_windows_menu_for_nsapp",{rid:this.rid})}async setAsHelpMenuForNSApp(){return Wt("plugin:menu|set_as_help_menu_for_nsapp",{rid:this.rid})}async setIcon(t){return Wt("plugin:menu|set_icon",{rid:this.rid,kind:this.kind,icon:Ba(t)})}}class $a extends mo{constructor(t,n){super(t,n,"Menu")}static async new(t){return ho("Menu",t).then(([n,r])=>new $a(n,r))}static async default(){return Wt("plugin:menu|create_default").then(([t,n])=>new $a(t,n))}async append(t){return Wt("plugin:menu|append",{rid:this.rid,kind:this.kind,items:(Array.isArray(t)?t:[t]).map(n=>"rid"in n?[n.rid,n.kind]:n)})}async prepend(t){return Wt("plugin:menu|prepend",{rid:this.rid,kind:this.kind,items:(Array.isArray(t)?t:[t]).map(n=>"rid"in n?[n.rid,n.kind]:n)})}async insert(t,n){return Wt("plugin:menu|insert",{rid:this.rid,kind:this.kind,items:(Array.isArray(t)?t:[t]).map(r=>"rid"in r?[r.rid,r.kind]:r),position:n})}async remove(t){return Wt("plugin:menu|remove",{rid:this.rid,kind:this.kind,item:[t.rid,t.kind]})}async removeAt(t){return Wt("plugin:menu|remove_at",{rid:this.rid,kind:this.kind,position:t}).then(Ya)}async items(){return Wt("plugin:menu|items",{rid:this.rid,kind:this.kind}).then(t=>t.map(Ya))}async get(t){return Wt("plugin:menu|get",{rid:this.rid,kind:this.kind,id:t}).then(n=>n?Ya(n):null)}async popup(t,n){var r;return Wt("plugin:menu|popup",{rid:this.rid,kind:this.kind,window:(r=n==null?void 0:n.label)!==null&&r!==void 0?r:null,at:t instanceof lu?t:t?new lu(t):null})}async setAsAppMenu(){return Wt("plugin:menu|set_as_app_menu",{rid:this.rid}).then(t=>t?new $a(t[0],t[1]):null)}async setAsWindowMenu(t){var n;return Wt("plugin:menu|set_as_window_menu",{rid:this.rid,window:(n=t==null?void 0:t.label)!==null&&n!==void 0?n:null}).then(r=>r?new $a(r[0],r[1]):null)}}async function dl(e){if(e.length===0)return;await(await $a.new({items:await Promise.all(e.map(n=>yw(n)))})).popup(void 0,Xk())}async function yw(e){return"items"in e?Hu.new({id:e.id,text:e.label,enabled:!e.disabled,items:await Promise.all(e.items.map(t=>yw(t)))}):{id:e.id,text:e.label,enabled:!e.disabled,accelerator:e.accelerator,action:()=>{e.onSelect()}}}function Tl(){return Hn().haptics}const iI="mobile.tools.last-primary-tool";function xw(){if(typeof window>"u")return"files";try{return window.localStorage.getItem(iI)==="git"?"git":"files"}catch{return"files"}}function Tm(e){var r;const t=[{pattern:"/workspaces/:workspaceId/tools/processes",routeKind:"processes"},{pattern:"/workspaces/:workspaceId/tools/files",routeKind:"files"},{pattern:"/workspaces/:workspaceId/tools/git",routeKind:"git"},{pattern:"/workspaces/:workspaceId/tools",routeKind:"home"}];for(const i of t){const o=Kt(i.pattern,e),l=((r=o==null?void 0:o.params.workspaceId)==null?void 0:r.trim())??null;if(l)return{workspaceId:l,routeKind:i.routeKind,legacy:!1}}const n=[{pattern:"/tools/processes",routeKind:"processes"},{pattern:"/tools/files",routeKind:"files"},{pattern:"/tools/git",routeKind:"git"},{pattern:"/tools",routeKind:"home"}];for(const i of n)if(Kt(i.pattern,e))return{workspaceId:null,routeKind:i.routeKind,legacy:!0};return null}function aI(e,t){const n=Tm(e);if((n==null?void 0:n.routeKind)==="git")return"git";if((n==null?void 0:n.routeKind)==="files")return"files";const r=new URLSearchParams(t).get("tab");return r==="git"?"git":r==="files"?"files":xw()}function Im(e,t){const n=Tm(e);return(n==null?void 0:n.routeKind)==="processes"&&n.workspaceId?Mi(n.workspaceId):n!=null&&n.workspaceId?zk(n.workspaceId,aI(e,t)):n!=null&&n.legacy?xw()==="git"?"/tools?tab=git":"/tools?tab=files":null}function Am({activeEntry:e,presentation:t,pathname:n,search:r,moreButtonLabel:i}){if(t==="conversation-focus"||e!=="butler")return null;const o=Tm(n);return o?o.routeKind==="processes"?{title:a("shell.terminalManagerEntry"),showBackButton:!0,showMoreButton:!1,moreButtonLabel:i}:(o.routeKind==="home"||o.routeKind==="files"||o.routeKind==="git",null):null}const kw=d.createContext({composerPortalTarget:null});function Rm({composerPortalTarget:e,children:t}){return s.jsx(kw.Provider,{value:{composerPortalTarget:e},children:t})}function GV(){return d.useContext(kw)}function Pm(e,t,n){const[r,i]=d.useState(void 0);return d.useEffect(()=>{const o=e.current,l=t.current;if(!n||!o||!l){i(void 0),o&&o.style.removeProperty("--mobile-conversation-tabbar-height");return}const c=o,u=l;function f(){if(!e.current||!u.isConnected)return;const m=`${Math.round(u.getBoundingClientRect().height)}px`;c.style.setProperty("--mobile-conversation-tabbar-height",m),i(m)}f();const h=typeof ResizeObserver<"u"?new ResizeObserver(f):null;return h==null||h.observe(u),window.addEventListener("resize",f),()=>{h==null||h.disconnect(),window.removeEventListener("resize",f),c.style.removeProperty("--mobile-conversation-tabbar-height")}},[n,e,t]),r}const oI=3e3,Zl=10,lg=84,cg=.36;function Mm({enabled:e,rootRef:t,suspended:n=!1,resetKey:r}){const i=d.useRef(null),o=d.useRef(null),l=d.useRef("visible"),c=d.useRef(1),[u,f]=d.useState("visible"),[h,m]=d.useState(1);d.useEffect(()=>{l.current=u},[u]),d.useEffect(()=>{c.current=h},[h]);function g(){ea(i),i.current=window.setTimeout(()=>{p()},oI)}function p(){f("hidden"),m(0)}function b(){f("visible"),m(1),g()}d.useEffect(()=>{if(ea(i),!e){ea(i),f("visible"),m(1);return}if(n){f("hidden"),m(0);return}return b(),()=>{ea(i)}},[e,r,n]),d.useEffect(()=>()=>{ea(i)},[]),d.useEffect(()=>{if(!e||n){o.current=null;return}const x=t.current;if(!x)return;function k(z){if(z.touches.length!==1){o.current=null;return}const L=z.touches[0],R=fg(z.target);if(!L||!R){o.current=null;return}o.current={surface:R,startX:L.clientX,startY:L.clientY,pointerType:"touch",initialState:l.current==="visible"?"visible":"hidden",touchId:L.identifier,dragging:!1,latestProgress:c.current},l.current==="visible"&&ea(i)}function C(z){const L=o.current;if(!L||L.pointerType!=="touch")return;const R=Td(z.touches,L.touchId);if(!R)return;const K=R.clientX-L.startX,E=R.clientY-L.startY;if(L.surface==="conversation"){if(Math.abs(E)<=Zl||Math.abs(E)<=Math.abs(K))return;o.current=null,L.initialState==="visible"&&p();return}const D=L.initialState==="hidden"?-E:E;D<=Zl&&!L.dragging||(mg(z),L.dragging=!0,L.latestProgress=ug(L.initialState,D),f("dragging"),m(L.latestProgress))}function j(z){const L=o.current;if(!(!L||L.pointerType!=="touch"||!Td(z.changedTouches,L.touchId))){if(o.current=null,!L.dragging){L.initialState==="visible"&&g();return}dg(L.initialState,L.latestProgress,b,f,m)}}function H(z){const L=o.current;if(!(!L||L.pointerType!=="touch"||!Td(z.changedTouches,L.touchId))){if(o.current=null,!L.dragging){L.initialState==="visible"&&g();return}if(L.initialState==="visible"){b();return}f("hidden"),m(0)}}function _(z){if(z.pointerType!=="touch")return;const L=fg(z.target);if(!L){o.current=null;return}if(o.current={surface:L,startX:z.clientX,startY:z.clientY,pointerType:"pointer",initialState:l.current==="visible"?"visible":"hidden",pointerId:z.pointerId,captureTarget:z.target instanceof Element?z.target:null,dragging:!1,latestProgress:c.current},z.target instanceof Element)try{z.target.setPointerCapture(z.pointerId)}catch{}l.current==="visible"&&ea(i)}function T(z){const L=o.current;if(!L||L.pointerType!=="pointer")return;const R=z.clientX-L.startX,K=z.clientY-L.startY;if(L.surface==="conversation"){if(Math.abs(K)<=Zl||Math.abs(K)<=Math.abs(R))return;o.current=null,L.initialState==="visible"&&p();return}const E=L.initialState==="hidden"?-K:K;E<=Zl&&!L.dragging||(mg(z),L.dragging=!0,L.latestProgress=ug(L.initialState,E),f("dragging"),m(L.latestProgress))}function P(z){const L=o.current;if(!(!L||L.pointerType!=="pointer"||L.pointerId!==z.pointerId)){if(o.current=null,lI(L),!L.dragging){L.initialState==="visible"&&g();return}dg(L.initialState,L.latestProgress,b,f,m)}}return x.addEventListener("touchstart",k,{passive:!0}),x.addEventListener("pointerdown",_,{passive:!0}),window.addEventListener("touchmove",C,{passive:!1}),window.addEventListener("touchend",j),window.addEventListener("touchcancel",H),window.addEventListener("pointermove",T,{passive:!1}),window.addEventListener("pointerup",P),window.addEventListener("pointercancel",P),()=>{x.removeEventListener("touchstart",k),x.removeEventListener("pointerdown",_),window.removeEventListener("touchmove",C),window.removeEventListener("touchend",j),window.removeEventListener("touchcancel",H),window.removeEventListener("pointermove",T),window.removeEventListener("pointerup",P),window.removeEventListener("pointercancel",P)}},[e,t,n]);const y=e&&!n?h:e?0:1;return{state:n&&e?"hidden":u,progress:y,isOpen:y>.01}}function ea(e){e.current!==null&&(window.clearTimeout(e.current),e.current=null)}function ug(e,t){return hg(e==="hidden"?t/lg:1-t/lg,0,1)}function dg(e,t,n,r,i){if(e==="hidden"){if(t>=cg){n();return}r("hidden"),i(0);return}if(t<=1-cg){r("hidden"),i(0);return}n()}function lI(e){if(!(e.pointerType!=="pointer"||typeof e.pointerId!="number"||!(e.captureTarget instanceof Element)))try{e.captureTarget.hasPointerCapture(e.pointerId)&&e.captureTarget.releasePointerCapture(e.pointerId)}catch{}}function Td(e,t){if(typeof t!="number")return e[0]??null;for(let n=0;n<e.length;n+=1){const r=e[n];if((r==null?void 0:r.identifier)===t)return r}return null}function fg(e){return e instanceof Element?e.closest(".composer-panel")?"composer":e.closest(".message-list, .message-timeline, .mobile-conversation-main, .conversation-page-shell, .mobile-butler-main-stage, .mobile-butler-chat-body, .mobile-butler-page-shell")?"conversation":null:null}function hg(e,t,n){return Math.min(Math.max(e,t),n)}function mg(e){e.cancelable&&e.preventDefault()}function Il({viewportClass:e,activeEntry:t,hasNavigationPanel:n,hasAuxiliaryPanel:r,preferCompactLayout:i=!1}){return i||e==="compact"?"compact":e==="expanded"&&n&&r?"expanded":t==="butler"&&r?"medium-auxiliary":n?"medium-navigation":r?"medium-auxiliary":"compact"}function Uu(e){return!e.isNativeMobile||e.viewportClass==="expanded"||typeof window>"u"?!1:window.innerHeight>window.innerWidth}function ww(e){return e==="medium-navigation"||e==="expanded"}function vw(e){return e==="medium-auxiliary"||e==="expanded"}function Em({viewportClass:e,activeEntry:t,hasNavigationPanel:n,hasAuxiliaryPanel:r,preferCompactLayout:i=!1,children:o,navigationPanel:l,auxiliaryPanel:c}){const u=Il({viewportClass:e,activeEntry:t,hasNavigationPanel:n,hasAuxiliaryPanel:r,preferCompactLayout:i}),f=ww(u)&&l,h=vw(u)&&c;return s.jsxs("div",{className:"mobile-adaptive-pane-layout","data-pane-layout":u,children:[f?s.jsx("aside",{className:"workbench-nav surface-card mobile-adaptive-pane-panel mobile-adaptive-pane-panel-navigation",children:l}):null,s.jsx("div",{className:"mobile-adaptive-pane-main",children:o}),h?s.jsx("aside",{className:"workbench-auxiliary surface-card mobile-adaptive-pane-panel mobile-adaptive-pane-panel-auxiliary",children:c}):null]})}function cI({activeEntry:e,presentation:t="default",children:n,navigationPanel:r,auxiliaryPanel:i,onNavigateWorkspaces:o,onNavigateTerminals:l,onNavigateSessions:c,onNavigateButler:u,onNavigateToolProcesses:f,onNavigateSettings:h}){const m=Hn(),g=Tl(),p=Wu(),b=Nl(),y=d.useRef(null),x=d.useRef(null),[k,C]=d.useState(null),j=t==="conversation-focus",H=Uu({isNativeMobile:m.isNativeMobile,viewportClass:m.viewportClass}),_=Mm({enabled:j,rootRef:y,resetKey:`${p.pathname}${p.search}`}),T=Il({viewportClass:m.viewportClass,activeEntry:e,hasNavigationPanel:!!r,hasAuxiliaryPanel:!!i,preferCompactLayout:H}),P=Am({activeEntry:e,presentation:t,pathname:p.pathname,search:p.search,moreButtonLabel:a("shell.androidMoreAction")}),z=[{key:"workspaces",label:a("shell.mobileWorkspacesEntry"),icon:s.jsx(fI,{}),onClick:o},{key:"sessions",label:a("shell.mobileSessionsEntry"),icon:s.jsx(hI,{}),onClick:c},{key:"terminals",label:a("shell.mobileButlerEntry"),icon:s.jsx(pI,{}),onClick:u},{key:"butler",label:a("shell.mobileTerminalsEntry"),icon:s.jsx(mI,{}),onClick:l},{key:"settings",label:a("shell.mobileSettingsEntry"),icon:s.jsx(gI,{}),onClick:h}],L=j?{"--mobile-conversation-tabbar-progress":_.progress.toFixed(4)}:void 0;Pm(y,x,j);function R(){const E=Im(p.pathname,p.search);if(!E){l();return}b(E,{replace:!0})}const K=s.jsx("nav",{ref:x,className:"android-workbench-bottom-nav","aria-label":a("shell.title"),children:z.map(E=>s.jsxs("button",{type:"button",className:"android-workbench-bottom-nav-item","data-active":E.key===e,"aria-current":E.key===e?"page":void 0,onClick:()=>{E.key!==e&&g.trigger("selection"),E.onClick()},children:[s.jsx("span",{className:"android-workbench-bottom-nav-icon","aria-hidden":"true",children:E.icon}),s.jsx("span",{className:"android-workbench-bottom-nav-label",children:E.label})]},E.key))});return s.jsx(Rm,{composerPortalTarget:j?k:null,children:s.jsxs("div",{ref:y,className:"android-workbench-shell","data-active-entry":e,"data-mobile-presentation":t,"data-pane-layout":T,"data-tabbar-open":j?_.isOpen:!0,"data-conversation-tabbar-state":j?_.state:"default",style:L,children:[P?s.jsxs("header",{className:"android-workbench-topbar","data-header-kind":"tools",children:[s.jsxs("div",{className:"android-workbench-topbar-leading",children:[P.showBackButton?s.jsx("button",{type:"button",className:"android-workbench-icon-button","aria-label":a("common.back"),onClick:R,children:s.jsx(uI,{})}):null,s.jsx("div",{className:"android-workbench-topbar-copy",children:s.jsx("h1",{children:P.title})})]}),s.jsx("div",{className:"android-workbench-topbar-actions",children:P.showMoreButton?s.jsx("button",{type:"button",className:"android-workbench-icon-button","aria-label":P.moreButtonLabel,onClick:f,children:s.jsx(dI,{})}):null})]}):null,s.jsx("div",{className:"android-workbench-content",children:s.jsx(Em,{viewportClass:m.viewportClass,activeEntry:e,hasNavigationPanel:!!r,hasAuxiliaryPanel:!!i,preferCompactLayout:H,navigationPanel:r,auxiliaryPanel:i,children:n})}),j?s.jsxs("div",{className:"mobile-conversation-bottom-layer",children:[s.jsx("div",{ref:C,className:"mobile-conversation-bottom-layer-composer-slot"}),s.jsx("div",{className:"mobile-conversation-bottom-layer-tabbar-shell",children:K})]}):K]})})}function uI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"m15 18-6-6 6-6"}),s.jsx("path",{d:"M21 12H9"})]})}function dI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"5",r:"1.8"}),s.jsx("circle",{cx:"12",cy:"12",r:"1.8"}),s.jsx("circle",{cx:"12",cy:"19",r:"1.8"})]})}function fI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}),s.jsx("path",{d:"M8 13h8"})]})}function hI(){return s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function mI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2.5"}),s.jsx("path",{d:"m7.5 9 3 3-3 3"}),s.jsx("path",{d:"M12.5 15H17"})]})}function pI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("rect",{x:"5",y:"7",width:"14",height:"10",rx:"3"}),s.jsx("path",{d:"M9 7V5a3 3 0 0 1 6 0v2"}),s.jsx("circle",{cx:"10",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"14",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M10 15c.6.5 1.2.8 2 .8s1.4-.3 2-.8"})]})}function gI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82L4.21 7.1a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 8.92 4a1.65 1.65 0 0 0 1-1.51V2.4a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9c0 .66.39 1.25 1 1.51h.09a2 2 0 0 1 0 4h-.09c-.61.26-1 .85-1 1.49z"})]})}const bI=120,Wo={viewportHeight:null,keyboardInset:0,keyboardOpen:!1};function ah(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function yI(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable||e.closest("[contenteditable='true']"))return!0;if(e instanceof HTMLTextAreaElement)return!e.readOnly&&!e.disabled;if(e instanceof HTMLInputElement){if(e.readOnly||e.disabled)return!1;const t=(e.type||"text").toLowerCase();return!["button","checkbox","color","file","hidden","image","radio","range","reset","submit"].includes(t)}return!1}function xI(){var t;if(typeof window>"u")return 0;const e=[window.innerHeight,typeof document<"u"?(t=document.documentElement)==null?void 0:t.clientHeight:0].filter(ah);return e.length>0?Math.max(...e):0}function pg(){if(typeof window>"u")return Wo;const e=window.visualViewport,t=xI(),n=(e==null?void 0:e.height)??t,r=ah(n)?Math.round(n):null,i=ah(e==null?void 0:e.offsetTop)?(e==null?void 0:e.offsetTop)??0:0,o=r===null?0:Math.max(0,Math.round(t-r-i));return{viewportHeight:r,keyboardInset:o,keyboardOpen:yI(typeof document<"u"?document.activeElement:null)&&o>=bI}}function Id(e,t){if(typeof document>"u")return;[document.documentElement,document.body].filter(r=>r instanceof HTMLElement).forEach(r=>{if(!e){delete r.dataset.mobileKeyboardOpen,delete r.dataset.mobileViewportBound,r.style.removeProperty("--mobile-shell-viewport-height"),r.style.removeProperty("--mobile-shell-keyboard-inset");return}r.dataset.mobileKeyboardOpen=String(t.keyboardOpen),r.dataset.mobileViewportBound="true",t.viewportHeight===null?r.style.removeProperty("--mobile-shell-viewport-height"):r.style.setProperty("--mobile-shell-viewport-height",`${t.viewportHeight}px`),r.style.setProperty("--mobile-shell-keyboard-inset",`${t.keyboardInset}px`)})}function kI(e){const[t,n]=d.useState(()=>e?pg():Wo),r=d.useRef(null);return d.useEffect(()=>{if(!e){n(Wo),Id(!1,Wo);return}function i(){n(pg())}function o(){r.current!==null&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>{r.current=null,i()},0)}i();const l=window.visualViewport;return window.addEventListener("resize",i),window.addEventListener("orientationchange",i),l==null||l.addEventListener("resize",i),l==null||l.addEventListener("scroll",i),document.addEventListener("focusin",i),document.addEventListener("focusout",o),()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null),window.removeEventListener("resize",i),window.removeEventListener("orientationchange",i),l==null||l.removeEventListener("resize",i),l==null||l.removeEventListener("scroll",i),document.removeEventListener("focusin",i),document.removeEventListener("focusout",o),Id(!1,Wo)}},[e]),d.useEffect(()=>{Id(e,t)},[e,t]),t}function wI({activeEntry:e,presentation:t="default",children:n,navigationPanel:r,auxiliaryPanel:i,onNavigateWorkspaces:o,onNavigateTerminals:l,onNavigateSessions:c,onNavigateButler:u,onNavigateToolProcesses:f,onNavigateSettings:h}){const m=Hn(),g=Tl(),p=Wu(),b=Nl(),y=d.useRef(null),x=d.useRef(null),[k,C]=d.useState(null),j=t==="conversation-focus",H=Uu({isNativeMobile:m.isNativeMobile,viewportClass:m.viewportClass}),_=Mm({enabled:j,rootRef:y,resetKey:`${p.pathname}${p.search}`}),T=Il({viewportClass:m.viewportClass,activeEntry:e,hasNavigationPanel:!!r,hasAuxiliaryPanel:!!i,preferCompactLayout:H}),P=Am({activeEntry:e,presentation:t,pathname:p.pathname,search:p.search,moreButtonLabel:a("shell.iosMoreAction")}),z=[{key:"workspaces",label:a("shell.mobileWorkspacesEntry"),icon:s.jsx(CI,{}),onClick:o},{key:"sessions",label:a("shell.mobileSessionsEntry"),icon:s.jsx(jI,{}),onClick:c},{key:"terminals",label:a("shell.mobileButlerEntry"),icon:s.jsx(TI,{}),onClick:u},{key:"butler",label:a("shell.mobileTerminalsEntry"),icon:s.jsx(NI,{}),onClick:l},{key:"settings",label:a("shell.mobileSettingsEntry"),icon:s.jsx(II,{}),onClick:h}],L=j?{"--mobile-conversation-tabbar-progress":_.progress.toFixed(4)}:void 0;Pm(y,x,j);function R(){const E=Im(p.pathname,p.search);if(!E){l();return}b(E,{replace:!0})}const K=s.jsx("nav",{ref:x,className:"ios-workbench-tabbar","aria-label":a("shell.title"),children:z.map(E=>s.jsxs("button",{type:"button",className:"ios-workbench-tabbar-item","data-active":E.key===e,"aria-current":E.key===e?"page":void 0,onClick:()=>{E.key!==e&&g.trigger("selection"),E.onClick()},children:[s.jsx("span",{className:"ios-workbench-tabbar-icon","aria-hidden":"true",children:E.icon}),s.jsx("span",{className:"ios-workbench-tabbar-label",children:E.label})]},E.key))});return s.jsx(Rm,{composerPortalTarget:j?k:null,children:s.jsxs("div",{ref:y,className:"ios-workbench-shell","data-active-entry":e,"data-mobile-presentation":t,"data-pane-layout":T,"data-tabbar-open":j?_.isOpen:!0,"data-conversation-tabbar-state":j?_.state:"default",style:L,children:[P?s.jsxs("header",{className:"ios-workbench-nav","data-header-kind":"tools",children:[s.jsx("div",{className:"ios-workbench-nav-leading",children:P.showBackButton?s.jsxs("button",{type:"button",className:"ios-workbench-back-button","aria-label":a("common.back"),onClick:R,children:[s.jsx(vI,{}),s.jsx("span",{children:a("common.back")})]}):null}),s.jsx("div",{className:"ios-workbench-nav-copy",children:s.jsx("h1",{children:P.title})}),s.jsx("div",{className:"ios-workbench-nav-actions",children:P.showMoreButton?s.jsx("button",{type:"button",className:"ios-workbench-icon-button","aria-label":P.moreButtonLabel,onClick:f,children:s.jsx(SI,{})}):null})]}):null,s.jsx("div",{className:"ios-workbench-content",children:s.jsx(Em,{viewportClass:m.viewportClass,activeEntry:e,hasNavigationPanel:!!r,hasAuxiliaryPanel:!!i,preferCompactLayout:H,navigationPanel:r,auxiliaryPanel:i,children:n})}),j?s.jsxs("div",{className:"mobile-conversation-bottom-layer",children:[s.jsx("div",{ref:C,className:"mobile-conversation-bottom-layer-composer-slot"}),s.jsx("div",{className:"mobile-conversation-bottom-layer-tabbar-shell",children:K})]}):K]})})}function vI(){return s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",children:s.jsx("path",{d:"m15 18-6-6 6-6"})})}function SI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"5",r:"1.8"}),s.jsx("circle",{cx:"12",cy:"12",r:"1.8"}),s.jsx("circle",{cx:"12",cy:"19",r:"1.8"})]})}function CI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",children:[s.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}),s.jsx("path",{d:"M8 13h8"})]})}function jI(){return s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function NI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2.5"}),s.jsx("path",{d:"m7.5 9 3 3-3 3"}),s.jsx("path",{d:"M12.5 15H17"})]})}function TI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",children:[s.jsx("rect",{x:"5",y:"7",width:"14",height:"10",rx:"3"}),s.jsx("path",{d:"M9 7V5a3 3 0 0 1 6 0v2"}),s.jsx("circle",{cx:"10",cy:"12",r:".95",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"14",cy:"12",r:".95",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M10 15c.6.5 1.2.8 2 .8s1.4-.3 2-.8"})]})}function II(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82L4.21 7.1a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 8.92 4a1.65 1.65 0 0 0 1-1.51V2.4a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9c0 .66.39 1.25 1 1.51h.09a2 2 0 0 1 0 4h-.09c-.61.26-1 .85-1 1.49z"})]})}function AI(e){const t=Hn();return t.platform==="ios"?s.jsx(wI,{...e}):t.platform==="android"?s.jsx(cI,{...e}):s.jsx(RI,{...e})}function RI({activeEntry:e,presentation:t="default",children:n,navigationPanel:r,auxiliaryPanel:i,onNavigateWorkspaces:o,onNavigateTerminals:l,onNavigateSessions:c,onNavigateButler:u,onNavigateToolProcesses:f,onNavigateSettings:h}){const m=Hn(),g=Tl(),p=Wu(),b=Nl(),y=d.useRef(null),x=d.useRef(null),[k,C]=d.useState(null),j=kI(m.platform==="web"),H=m.platform==="web"&&j.keyboardOpen,_=t==="conversation-focus",T=Uu({isNativeMobile:m.isNativeMobile,viewportClass:m.viewportClass}),P=Mm({enabled:_,rootRef:y,suspended:H,resetKey:`${p.pathname}${p.search}`}),z=Il({viewportClass:m.viewportClass,activeEntry:e,hasNavigationPanel:!!r,hasAuxiliaryPanel:!!i,preferCompactLayout:T}),L=Am({activeEntry:e,presentation:t,pathname:p.pathname,search:p.search,moreButtonLabel:a("shell.iosMoreAction")}),R=[{key:"workspaces",label:a("shell.mobileWorkspacesEntry"),icon:s.jsx(EI,{}),onClick:o},{key:"sessions",label:a("shell.mobileSessionsEntry"),icon:s.jsx(LI,{}),onClick:c},{key:"terminals",label:a("shell.mobileButlerEntry"),icon:s.jsx(OI,{}),onClick:u},{key:"butler",label:a("shell.mobileTerminalsEntry"),icon:s.jsx(DI,{}),onClick:l},{key:"settings",label:a("shell.mobileSettingsEntry"),icon:s.jsx(FI,{}),onClick:h}],K=_?{"--mobile-conversation-tabbar-progress":P.progress.toFixed(4)}:void 0;Pm(y,x,_);function E(){const te=Im(p.pathname,p.search);if(!te){l();return}b(te,{replace:!0})}const D=s.jsx("nav",{ref:x,className:"mobile-workbench-tabbar","aria-label":a("shell.title"),hidden:H,children:R.map(te=>s.jsxs("button",{type:"button",className:"mobile-workbench-tabbar-item","data-active":te.key===e,"aria-current":te.key===e?"page":void 0,onClick:()=>{te.key!==e&&g.trigger("selection"),te.onClick()},children:[s.jsx("span",{className:"mobile-workbench-tabbar-icon","aria-hidden":"true",children:te.icon}),s.jsx("span",{className:"mobile-workbench-tabbar-label",children:te.label})]},te.key))});return s.jsx(Rm,{composerPortalTarget:_?k:null,children:s.jsxs("div",{ref:y,className:"mobile-workbench-shell","data-active-entry":e,"data-mobile-presentation":t,"data-mobile-runtime":m.platform,"data-mobile-keyboard-open":H,"data-pane-layout":z,"data-tabbar-open":H?!1:_?P.isOpen:!0,"data-conversation-tabbar-state":_?P.state:"default",style:K,children:[L?s.jsxs("header",{className:"mobile-workbench-header","data-header-kind":"tools",children:[s.jsxs("div",{className:"mobile-workbench-header-leading",children:[L.showBackButton?s.jsx("button",{type:"button",className:"mobile-workbench-header-button","aria-label":a("common.back"),onClick:E,children:s.jsx(PI,{})}):null,s.jsx("div",{className:"mobile-workbench-header-copy",children:s.jsx("h1",{children:L.title})})]}),s.jsx("div",{className:"mobile-workbench-header-actions",children:L.showMoreButton?s.jsx("button",{type:"button",className:"mobile-workbench-header-button mobile-tools-more-button","aria-label":L.moreButtonLabel,onClick:f,children:s.jsx(MI,{})}):null})]}):null,s.jsx("div",{className:"mobile-workbench-content",children:s.jsx(Em,{viewportClass:m.viewportClass,activeEntry:e,hasNavigationPanel:!!r,hasAuxiliaryPanel:!!i,preferCompactLayout:T,navigationPanel:r,auxiliaryPanel:i,children:n})}),_?s.jsxs("div",{className:"mobile-conversation-bottom-layer",children:[s.jsx("div",{ref:C,className:"mobile-conversation-bottom-layer-composer-slot"}),s.jsx("div",{className:"mobile-conversation-bottom-layer-tabbar-shell",children:D})]}):D]})})}function PI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("path",{d:"m15 18-6-6 6-6"}),s.jsx("path",{d:"M21 12H9"})]})}function MI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"5",r:"1.8"}),s.jsx("circle",{cx:"12",cy:"12",r:"1.8"}),s.jsx("circle",{cx:"12",cy:"19",r:"1.8"})]})}function EI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}),s.jsx("path",{d:"M8 13h8"})]})}function LI(){return s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function DI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2.5"}),s.jsx("path",{d:"m7.5 9 3 3-3 3"}),s.jsx("path",{d:"M12.5 15H17"})]})}function OI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("rect",{x:"5",y:"7",width:"14",height:"10",rx:"3"}),s.jsx("path",{d:"M9 7V5a3 3 0 0 1 6 0v2"}),s.jsx("circle",{cx:"10",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"14",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M10 15c.6.5 1.2.8 2 .8s1.4-.3 2-.8"})]})}function FI(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82L4.21 7.1a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 8.92 4a1.65 1.65 0 0 0 1-1.51V2.4a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9c0 .66.39 1.25 1 1.51h.09a2 2 0 0 1 0 4h-.09c-.61.26-1 .85-1 1.49z"})]})}class Sw{constructor(t){ht(this,"maxAttempts");ht(this,"baseDelayMs");ht(this,"reconnectAttempts",0);ht(this,"reconnectTimer",null);ht(this,"disposed",!1);this.options=t,this.maxAttempts=t.maxAttempts??4,this.baseDelayMs=t.baseDelayMs??300}start(){this.options.onReconnect(!1)}markConnected(){this.reconnectAttempts=0,this.options.onStateChange("connected")}markTransientFailure(){this.disposed||this.reconnectAttempts>0||this.options.onStateChange("reconnecting")}markDisconnected(){if(this.disposed)return;if(!Fr.getState().autoReconnect){this.options.onStateChange("reconnect_failed");return}if(this.reconnectAttempts+=1,this.reconnectAttempts>this.maxAttempts){this.options.onStateChange("reconnect_failed");return}this.options.onStateChange("reconnecting");const t=this.baseDelayMs*this.reconnectAttempts;this.reconnectTimer=window.setTimeout(()=>{this.options.onReconnect(!0)},t)}reconnectNow(){this.reconnectAttempts=0,this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.options.onReconnect(!0)}close(){this.disposed=!0,this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.options.onStateChange("closed")}}class _I{constructor(t){ht(this,"socket",null);ht(this,"disposed",!1);ht(this,"authRecoveryInFlight",!1);ht(this,"pendingRefresh",!1);ht(this,"workbenchKnownRevision");ht(this,"lastWorkbenchSnapshot",null);ht(this,"fileTreeSubscription",null);ht(this,"gitSubscription",null);ht(this,"terminalManagerSubscription",null);ht(this,"workspaceManagementSubscription",null);ht(this,"pendingFileTreeRefresh",null);ht(this,"pendingGitRefresh",null);ht(this,"pendingTerminalManagerRefresh",null);ht(this,"pendingWorkspaceManagementRefresh",null);ht(this,"fileTreeRevisionByPath",new Map);ht(this,"gitRevisionByWorkspaceId",new Map);ht(this,"terminalManagerRevisionByWorkspaceId",new Map);ht(this,"workspaceManagementRevisionByWorkspaceId",new Map);ht(this,"fileTreeListeners",new Set);ht(this,"gitListeners",new Set);ht(this,"terminalManagerListeners",new Set);ht(this,"workspaceManagementListeners",new Set);ht(this,"workbenchSubscribeStartedAtMs",null);ht(this,"workbenchRefreshStartedAtMs",null);ht(this,"connectionManager");this.options=t,this.workbenchKnownRevision=null,this.connectionManager=new Sw({onReconnect:n=>{this.connect(n)},onStateChange:t.onConnectionChange})}start(){this.connectionManager.start()}requestRefresh(){const t=this.socket;if(!gg(t)){this.pendingRefresh=!0;return}this.workbenchRefreshStartedAtMs=performance.now(),t.send(JSON.stringify({type:"workbench.refresh",knownRevision:this.workbenchKnownRevision??void 0})),Xt("workbench.refresh.sent",{knownRevision:this.workbenchKnownRevision}),this.pendingRefresh=!1}setWorkbenchKnownRevision(t){this.workbenchKnownRevision=Ir(t)}primeWorkbenchSnapshot(t){if(!t||!Array.isArray(t.items)){this.lastWorkbenchSnapshot=null,this.workbenchKnownRevision=null;return}this.lastWorkbenchSnapshot=t,this.workbenchKnownRevision=Ir(t.revision)??null}subscribeFileTree(t,n,r){this.fileTreeSubscription={workspaceId:t,paths:bg(n),knownRevisionByPath:Ad(r==null?void 0:r.knownRevisionByPath)},this.sendWhenReady({type:"fileTree.subscribe",workspaceId:t,paths:this.fileTreeSubscription.paths,knownRevisions:Rd(t,this.fileTreeSubscription.paths,this.fileTreeSubscription.knownRevisionByPath,this.fileTreeRevisionByPath)})}requestFileTreeRefresh(t,n,r){const i=bg(n),o={type:"fileTree.refresh",workspaceId:t,paths:i,knownRevisions:Rd(t,i,Ad(r==null?void 0:r.knownRevisionByPath),this.fileTreeRevisionByPath)};this.sendWhenReady(o)?this.pendingFileTreeRefresh=null:this.pendingFileTreeRefresh={workspaceId:t,paths:i,knownRevisionByPath:Ad(r==null?void 0:r.knownRevisionByPath)}}subscribeGit(t,n){this.gitSubscription={workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)},this.sendWhenReady({type:"git.subscribe",workspaceId:t,knownRevision:this.gitSubscription.knownRevision??this.gitRevisionByWorkspaceId.get(t)})}requestGitRefresh(t,n){const r={type:"git.refresh",workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)??this.gitRevisionByWorkspaceId.get(t)};this.sendWhenReady(r)?this.pendingGitRefresh=null:this.pendingGitRefresh={workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)}}subscribeTerminalManager(t,n){this.terminalManagerSubscription={workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)},this.sendWhenReady({type:"terminalManager.subscribe",workspaceId:t,knownRevision:this.terminalManagerSubscription.knownRevision??this.terminalManagerRevisionByWorkspaceId.get(t)})}requestTerminalManagerRefresh(t,n){const r={type:"terminalManager.refresh",workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)??this.terminalManagerRevisionByWorkspaceId.get(t)};this.sendWhenReady(r)?this.pendingTerminalManagerRefresh=null:this.pendingTerminalManagerRefresh={workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)}}subscribeWorkspaceManagement(t,n){this.workspaceManagementSubscription={workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)},this.sendWhenReady({type:"workspaceManagement.subscribe",workspaceId:t,knownRevision:this.workspaceManagementSubscription.knownRevision??this.workspaceManagementRevisionByWorkspaceId.get(t)})}requestWorkspaceManagementRefresh(t,n){const r={type:"workspaceManagement.refresh",workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)??this.workspaceManagementRevisionByWorkspaceId.get(t)};this.sendWhenReady(r)?this.pendingWorkspaceManagementRefresh=null:this.pendingWorkspaceManagementRefresh={workspaceId:t,knownRevision:Ir(n==null?void 0:n.knownRevision)}}addFileTreeSnapshotListener(t){return this.fileTreeListeners.add(t),()=>{this.fileTreeListeners.delete(t)}}addGitSnapshotListener(t){return this.gitListeners.add(t),()=>{this.gitListeners.delete(t)}}addTerminalManagerSnapshotListener(t){return this.terminalManagerListeners.add(t),()=>{this.terminalManagerListeners.delete(t)}}addWorkspaceManagementSnapshotListener(t){return this.workspaceManagementListeners.add(t),()=>{this.workspaceManagementListeners.delete(t)}}close(){var t;this.disposed=!0,this.connectionManager.close(),(t=this.socket)==null||t.close(),this.socket=null}connect(t){var u;if(this.disposed)return;t&&this.socket&&(this.socket.close(),this.socket=null);const n=(u=fa.getState().session)==null?void 0:u.accessToken;if(!n){this.options.onUnauthorized();return}const r=jl(),i=Fu(r),o=i.baseUrl,l=`${Dk("/ws",o)}?access_token=${encodeURIComponent(n)}`,c=i.transport.createWebSocket({path:"/ws",baseUrl:o,url:l});this.socket=c,c.addEventListener("open",()=>{this.workbenchSubscribeStartedAtMs=performance.now(),c.send(JSON.stringify({type:"workbench.subscribe",knownRevision:this.workbenchKnownRevision??void 0})),Xt("workbench.subscribe.sent",{knownRevision:this.workbenchKnownRevision,baseUrl:o}),this.pendingRefresh&&this.requestRefresh(),this.fileTreeSubscription&&c.send(JSON.stringify({type:"fileTree.subscribe",workspaceId:this.fileTreeSubscription.workspaceId,paths:this.fileTreeSubscription.paths,knownRevisions:Rd(this.fileTreeSubscription.workspaceId,this.fileTreeSubscription.paths,this.fileTreeSubscription.knownRevisionByPath,this.fileTreeRevisionByPath)})),this.pendingFileTreeRefresh&&this.requestFileTreeRefresh(this.pendingFileTreeRefresh.workspaceId,this.pendingFileTreeRefresh.paths,{knownRevisionByPath:this.pendingFileTreeRefresh.knownRevisionByPath}),this.gitSubscription&&c.send(JSON.stringify({type:"git.subscribe",workspaceId:this.gitSubscription.workspaceId,knownRevision:this.gitSubscription.knownRevision??this.gitRevisionByWorkspaceId.get(this.gitSubscription.workspaceId)})),this.pendingGitRefresh&&this.requestGitRefresh(this.pendingGitRefresh.workspaceId,{knownRevision:this.pendingGitRefresh.knownRevision}),this.terminalManagerSubscription&&c.send(JSON.stringify({type:"terminalManager.subscribe",workspaceId:this.terminalManagerSubscription.workspaceId,knownRevision:this.terminalManagerSubscription.knownRevision??this.terminalManagerRevisionByWorkspaceId.get(this.terminalManagerSubscription.workspaceId)})),this.pendingTerminalManagerRefresh&&this.requestTerminalManagerRefresh(this.pendingTerminalManagerRefresh.workspaceId,{knownRevision:this.pendingTerminalManagerRefresh.knownRevision}),this.workspaceManagementSubscription&&c.send(JSON.stringify({type:"workspaceManagement.subscribe",workspaceId:this.workspaceManagementSubscription.workspaceId,knownRevision:this.workspaceManagementSubscription.knownRevision??this.workspaceManagementRevisionByWorkspaceId.get(this.workspaceManagementSubscription.workspaceId)})),this.pendingWorkspaceManagementRefresh&&this.requestWorkspaceManagementRefresh(this.pendingWorkspaceManagementRefresh.workspaceId,{knownRevision:this.pendingWorkspaceManagementRefresh.knownRevision})}),c.addEventListener("message",f=>{var m,g,p,b,y,x,k,C,j,H;if(!(f instanceof MessageEvent)||typeof f.data!="string")return;const h=JSON.parse(f.data);if(h.type==="system.connected"){this.connectionManager.markConnected();return}if(h.type==="session.error"){h.error_code==="UNAUTHORIZED"&&this.handleUnauthorized();return}if(h.type==="workbench.snapshot"&&(Xt("workbench.snapshot.received",{unchanged:h.unchanged,revision:h.revision,workspaceCount:((m=h.snapshot)==null?void 0:m.items.length)??0,sessionCount:h.snapshot?$I(h.snapshot):0,subscribeDurationMs:ec(this.workbenchSubscribeStartedAtMs),refreshDurationMs:ec(this.workbenchRefreshStartedAtMs)}),this.workbenchRefreshStartedAtMs=null),h.type==="workbench.delta"){Xt("workbench.delta.received",{baseRevision:h.baseRevision,revision:h.revision,changedWorkspaceCount:h.changedItems.length,removedWorkspaceCount:h.removedWorkspaceIds.length,subscribeDurationMs:ec(this.workbenchSubscribeStartedAtMs),refreshDurationMs:ec(this.workbenchRefreshStartedAtMs)}),this.workbenchRefreshStartedAtMs=null;const _=WI(this.lastWorkbenchSnapshot,h);if(!_){Xt("workbench.delta.mismatch",{currentRevision:((g=this.lastWorkbenchSnapshot)==null?void 0:g.revision)??null,baseRevision:h.baseRevision,revision:h.revision}),this.workbenchKnownRevision=null,this.lastWorkbenchSnapshot=null,this.connectionManager.reconnectNow();return}this.lastWorkbenchSnapshot=_,this.workbenchKnownRevision=h.revision,this.options.onSnapshot(_);return}if(h.type==="fileTree.snapshot"){const _=h.snapshot;if(_)_.revision=h.revision,this.fileTreeRevisionByPath.set(oh(_.workspaceId,_.path),h.revision);else if(h.unchanged&&this.fileTreeSubscription)for(const T of this.fileTreeSubscription.paths)this.fileTreeRevisionByPath.set(oh(this.fileTreeSubscription.workspaceId,T),h.revision);if(!_)return;(b=(p=this.options).onFileTreeSnapshot)==null||b.call(p,_),this.fileTreeListeners.forEach(T=>T(_));return}if(h.type==="git.snapshot"){const _=h.snapshot;if(_?(_.revision=h.revision,this.gitRevisionByWorkspaceId.set(_.workspaceId,h.revision)):h.unchanged&&this.gitSubscription&&this.gitRevisionByWorkspaceId.set(this.gitSubscription.workspaceId,h.revision),!_)return;(x=(y=this.options).onGitSnapshot)==null||x.call(y,_),this.gitListeners.forEach(T=>T(_));return}if(h.type==="terminalManager.snapshot"){const _=h.snapshot;if(_?(_.revision=h.revision,this.terminalManagerRevisionByWorkspaceId.set(_.workspaceId,h.revision)):h.unchanged&&this.terminalManagerSubscription&&this.terminalManagerRevisionByWorkspaceId.set(this.terminalManagerSubscription.workspaceId,h.revision),!_)return;(C=(k=this.options).onTerminalManagerSnapshot)==null||C.call(k,_),this.terminalManagerListeners.forEach(T=>T(_));return}if(h.type==="workspaceManagement.snapshot"){const _=h.snapshot;if(_?(_.revision=h.revision,this.workspaceManagementRevisionByWorkspaceId.set(_.workspaceId,h.revision)):h.unchanged&&this.workspaceManagementSubscription&&this.workspaceManagementRevisionByWorkspaceId.set(this.workspaceManagementSubscription.workspaceId,h.revision),!_)return;(H=(j=this.options).onWorkspaceManagementSnapshot)==null||H.call(j,_),this.workspaceManagementListeners.forEach(T=>T(_));return}h.type==="workbench.snapshot"&&h.snapshot&&BI(h.snapshot)?(h.snapshot.revision=h.revision,this.lastWorkbenchSnapshot=h.snapshot,this.workbenchKnownRevision=h.revision,this.options.onSnapshot(h.snapshot)):h.type==="workbench.snapshot"&&h.unchanged&&(this.workbenchKnownRevision=h.revision,this.lastWorkbenchSnapshot&&(this.lastWorkbenchSnapshot={...this.lastWorkbenchSnapshot,revision:h.revision}))}),c.addEventListener("close",()=>{this.disposed||this.socket!==c||this.connectionManager.markDisconnected()}),c.addEventListener("error",()=>{this.disposed||this.socket!==c||this.connectionManager.markTransientFailure()})}handleUnauthorized(){if(this.authRecoveryInFlight||this.disposed)return;this.authRecoveryInFlight=!0;const t=this.socket;this.socket=null,t==null||t.close(),fa.refresh().then(n=>{if(this.authRecoveryInFlight=!1,!this.disposed){if(n.status==="refreshed"){this.connectionManager.reconnectNow();return}if(n.status==="deferred"){this.connectionManager.markDisconnected();return}this.options.onUnauthorized()}})}sendWhenReady(t){const n=this.socket;return gg(n)?(n.send(JSON.stringify(t)),!0):!1}}function gg(e){return e!==null&&e.readyState===1}function BI(e){return typeof e!="object"||e===null?!1:Array.isArray(e.items)}function bg(e){const t=new Set;for(const n of e??[""])t.add(n.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,""));return[...t]}function Ir(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function WI(e,t){if(!e||e.revision!==t.baseRevision)return null;const n=new Map(e.items.map(i=>[i.workspace.id,i]));for(const i of t.removedWorkspaceIds)n.delete(i);for(const i of t.changedItems)n.set(i.workspace.id,i);const r=[];for(const i of t.orderedWorkspaceIds){const o=n.get(i);if(!o)return null;r.push(o)}return{revision:t.revision,items:r}}function Ad(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,""),Ir(n)]).filter(t=>t[1]!==null)):{}}function Rd(e,t,n,r){const i=t.map(o=>{const l=o.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");return[l,n[l]??r.get(oh(e,l))??null]}).filter(o=>!!o[1]);if(i.length!==0)return Object.fromEntries(i)}function oh(e,t){return`${e}::${t}`}function $I(e){return e.items.reduce((t,n)=>t+n.sessions.length+Cw(n.childWorktrees??[]),0)}function Cw(e){return e.reduce((t,n)=>{if(typeof n!="object"||n===null)return t;const r=n,i=Array.isArray(r.sessions)?r.sessions.length:0,o=Array.isArray(r.children)?Cw(r.children):0;return t+i+o},0)}function ec(e){return e===null||typeof performance>"u"?null:Math.round(performance.now()-e)}const yg=6,zI=["button","a","input","textarea","select","summary","[role='button']","[role='link']","[role='tab']","[role='menuitem']","[contenteditable='true']","[data-window-drag='ignore']"].join(", ");function HI(e){return e instanceof HTMLElement?!e.closest(zI):!0}function lh(e,t,n){return e.isDesktop&&e.ui.osFamily==="macos"&&t===0&&HI(n)}function jw(e){return e.isDesktop&&e.ui.osFamily==="macos"&&e.ui.prefersOverlayTitlebar}function Lm(e){return jw(e)?"":void 0}function UI(e){if(!lh(e.platform,e.button,e.target)||typeof window>"u")return;const t=e.clientX,n=e.clientY;let r=!0;const i=()=>{r&&(r=!1,window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",l),window.removeEventListener("blur",c))},o=u=>{Math.abs(u.clientX-t)<yg&&Math.abs(u.clientY-n)<yg||(i(),qI())},l=()=>{i()},c=()=>{i()};window.addEventListener("mousemove",o),window.addEventListener("mouseup",l),window.addEventListener("blur",c)}async function qI(){typeof window>"u"||typeof window.__TAURI_INTERNALS__>"u"||await Xk().startDragging()}const du=.78,VI=1;function KI(){return typeof window<"u"&&typeof window.__TAURI_INTERNALS__<"u"}function Nw(e,t,n,r){const i=Math.hypot(n-e,r-t),o=Math.min(1,i/120);return du+(VI-du)*o}function _i(e){return Math.round(Number.isFinite(e)?e:0)}function GI(e){if(!KI())return null;const t=_i(e.x),n=_i(e.y);let r=!1,i=Promise.resolve();const o=(c,u)=>(i=i.then(async()=>{await window.__TAURI_INTERNALS__.invoke(c,u)}).catch(()=>{}),i),l=async()=>{r||(r=!0,await o("close_detach_preview"))};return o("show_detach_preview",{title:e.title,x:t,y:n,scale:du}),{updatePosition(c,u){if(r)return;const f=_i(c),h=_i(u);o("update_detach_preview_position",{x:f,y:h,scale:Nw(t,n,f,h)})},complete(){return l()},cancel(){return l()}}}function YI(e){if(typeof document>"u")return null;const t=_i(e.x),n=_i(e.y),r=document.createElement("div");r.className="desktop-window-detach-animation",r.setAttribute("aria-hidden","true"),r.dataset.state="preview",r.style.left=`${t}px`,r.style.top=`${n}px`,r.style.setProperty("--detach-preview-scale",du.toFixed(3));const i=document.createElement("div");i.className="desktop-window-detach-animation-bar";const o=document.createElement("strong");o.className="desktop-window-detach-animation-title",o.textContent=e.title;const l=document.createElement("div");l.className="desktop-window-detach-animation-body",i.append(o),r.append(i,l),document.body.append(r);let c=!1;const u=()=>{c||(c=!0,r.remove())};return{updatePosition(f,h){if(c)return;const m=_i(f),g=_i(h),p=Nw(t,n,m,g);r.style.left=`${m}px`,r.style.top=`${g}px`,r.style.setProperty("--detach-preview-scale",p.toFixed(3))},async complete(){u()},async cancel(){u()}}}function xg(e){return GI(e)??YI(e)}async function ch(){return await ae.request("/api/skills/overview")}async function JI(e){var n;const t=new URLSearchParams;return t.set("workspaceId",e.workspaceId),(n=e.sessionId)!=null&&n.trim()&&t.set("sessionId",e.sessionId.trim()),await ae.request(`/api/skills/workspace-session-mcp-status?${t.toString()}`)}async function XI(e){await ae.request("/api/skills",{method:"POST",body:JSON.stringify(e)})}async function QI(e){await ae.request("/api/skills/import",{method:"POST",body:JSON.stringify(e)})}async function ZI(e){await ae.request("/api/skills/sync",{method:"POST",body:JSON.stringify(e)})}function kg(e){if(e.executionBackend==="opencli_bridge"||e.executionBackend==="playwright")return e.executionBackend;try{return JSON.parse(e.inputJson).executionBackend==="opencli_bridge"?"opencli_bridge":"playwright"}catch{return"playwright"}}async function wg(e="active"){const t=new URLSearchParams({status:e});return(await ae.request(`/api/office/document-templates?${t.toString()}`)).items}async function vg(e={}){var i;const t=new URLSearchParams;(i=e.workspaceId)!=null&&i.trim()&&t.set("workspaceId",e.workspaceId.trim());const n=t.size>0?`?${t.toString()}`:"";return(await ae.request(`/api/office/browser/profiles${n}`)).items}async function e1(e){return await ae.request("/api/office/browser/profiles",{method:"POST",body:JSON.stringify(e)})}async function t1(e,t){return await ae.request(`/api/office/browser/profiles/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}async function n1(e){return await ae.request(`/api/office/browser/profiles/${encodeURIComponent(e)}`,{method:"DELETE"})}async function s1(e){return await ae.request("/api/office/document-templates/import-file",{method:"POST",body:JSON.stringify(e)})}async function tc(e){var i;const t=new URLSearchParams;(i=e.workspaceId)!=null&&i.trim()&&t.set("workspaceId",e.workspaceId.trim()),e.taskType&&t.set("taskType",e.taskType),e.status&&t.set("status",e.status),e.riskLevel&&t.set("riskLevel",e.riskLevel),typeof e.limit=="number"&&Number.isFinite(e.limit)&&t.set("limit",String(Math.trunc(e.limit)));const n=t.size>0?`?${t.toString()}`:"";return(await ae.request(`/api/office/tasks${n}`)).items}async function Pd(e){return await ae.request(`/api/office/tasks/${encodeURIComponent(e)}`)}async function r1(e){return await ae.request(`/api/office/browser/tasks/${encodeURIComponent(e)}/execute`,{method:"POST"})}async function uh(e){return(await ae.request(`/api/office/browser/tasks/${encodeURIComponent(e)}/execution`)).task}async function Sg(){return await ae.request("/api/office/browser/bridge-status")}async function Cg(){return await ae.request("/api/office/onlyoffice/settings")}async function i1(e){return await ae.request("/api/office/onlyoffice/settings",{method:"PUT",body:JSON.stringify(e)})}async function nc(){return await ae.request("/api/office/onlyoffice/status")}async function a1(e){return await ae.request(`/api/office/browser/tasks/${encodeURIComponent(e)}/execution/cancel`,{method:"POST"})}async function o1(e,t){await ae.request(`/api/office/approvals/${encodeURIComponent(e)}/reply`,{method:"POST",body:JSON.stringify(t)})}async function jg(e){var i;const t=new URLSearchParams;(i=e.workspaceId)!=null&&i.trim()&&t.set("workspaceId",e.workspaceId.trim()),e.kind&&t.set("kind",e.kind),e.status&&t.set("status",e.status);const n=t.size>0?`?${t.toString()}`:"";return(await ae.request(`/api/office/ops/targets${n}`)).items}async function l1(e){return await ae.request("/api/office/ops/targets",{method:"POST",body:JSON.stringify(e)})}async function c1(e,t){return await ae.request(`/api/office/ops/targets/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}const dh=new Set;let ui={items:null,loading:!1,requested:!1},Di=null;function u1(){dh.forEach(e=>e())}function da(e){ui=e,u1()}function d1(e){return dh.add(e),()=>{dh.delete(e)}}function Ng(){return ui}function f1(e=!1){if(!e){if(ui.items)return Promise.resolve(ui.items);if(Di)return Di}return da({...ui,loading:!0,requested:!0}),Di=x0().then(t=>(da({items:t,loading:!1,requested:!0}),t)).catch(()=>(da({...ui,items:null,loading:!1,requested:!0}),null)).finally(()=>{Di=null}),Di}function YV(){return da({...ui,loading:!0,requested:!0}),Di=k0().then(e=>(da({items:e,loading:!1,requested:!0}),e)).catch(()=>(da({...ui,loading:!1,requested:!0}),null)).finally(()=>{Di=null}),Di}function h1(e){const t=ui.items??[],n=m1(t,e);da({items:n,loading:!1,requested:!0})}async function JV(e,t){const n=await w0(e,t);return h1(n),n}function Tw(e=!0){const t=d.useSyncExternalStore(d1,Ng,Ng);return d.useEffect(()=>{e&&f1()},[e]),t}function m1(e,t){const n=e.slice(),r=n.findIndex(i=>i.provider===t.provider);return r>=0?(n[r]=t,n):(n.push(t),n)}async function p1(){return await ae.request("/api/opencli/catalog")}async function Tg(){return await ae.request("/api/opencli/check",{method:"POST"})}async function g1(e){return await ae.request("/api/opencli/config",{method:"POST",body:JSON.stringify(e)})}const Md="all",Ed="status";function b1({toolbarMode:e="internal",onToolbarStateChange:t}={}){var We,Ce,ke,we;const n=iu(se=>{var ce;return((ce=se.session)==null?void 0:ce.accessToken)??null}),[r,i]=d.useState(null),[o,l]=d.useState(!1),[c,u]=d.useState(!1),[f,h]=d.useState(!1),[m,g]=d.useState(!1),[p,b]=d.useState([]),[y,x]=d.useState(null),[k,C]=d.useState(null),[j,H]=d.useState(Md),[_,T]=d.useState(null),[P,z]=d.useState(!1),[L,R]=d.useState(""),[K,E]=d.useState(Ed);d.useEffect(()=>{let se=!0;if(!n){i(null),g(!1),b([]),C(null),x(null),l(!1),H(Md),T(null),z(!1),R(""),E(Ed);return}return(async()=>{l(!0),C(null),x(null);try{const Y=await Tg();if(!se)return;M(Y)}catch(Y){if(!se)return;const Te=rc(Y);try{const pe=await p1();if(!se)return;M(pe),C(Te)}catch(pe){if(!se)return;C(rc(pe))}}finally{se&&l(!1)}})(),()=>{se=!1}},[n]);const D=d.useMemo(()=>new Set(p),[p]),te=d.useMemo(()=>k1((r==null?void 0:r.entries)??[]),[r==null?void 0:r.entries]),V=d.useMemo(()=>C1(),[]);d.useEffect(()=>{te.some(se=>se.id===j)||H(Md)},[j,te]);const ee=d.useMemo(()=>((r==null?void 0:r.siteGroups)??[]).filter(se=>se.commands.some(ce=>Ig(ce,j,D))),[j,r==null?void 0:r.siteGroups,D]),U=d.useMemo(()=>_?ee.find(se=>se.site===_)??null:null,[_,ee]);d.useEffect(()=>{_&&!U&&T(null)},[_,U]),d.useEffect(()=>{R(""),E(Ed)},[_]);const he=d.useMemo(()=>{if(!U)return[];const se=L.trim().toLowerCase();return U.commands.filter(ce=>Ig(ce,j,D)&&v1(ce,se)).sort((ce,Y)=>S1(ce,Y,{sortId:K,selectedCommandIdSet:D}))},[j,U,L,K,D]),X=!!(r&&(r.provider.enabled!==m||r.entries.some(se=>se.enabled!==D.has(se.commandId)))),I=d.useMemo(()=>({draftEnabled:m,enableDisabled:o||c||f,refreshDisabled:!n||o||c||f,detailDisabled:!r||o,saveDisabled:!n||o||c||f||!r||!X,refreshing:c,saving:f,onEnabledChange:de,onRefresh:()=>{xe()},onShowDetails:()=>z(!0),onSave:()=>{le()}}),[n,r,p,m,X,o,c,f]);d.useEffect(()=>{t==null||t(I)},[t,I]),d.useEffect(()=>()=>{t==null||t(null)},[t]);async function xe(){if(n){u(!0),C(null),x(null);try{const se=await Tg();M(se),x(M1(se.refreshState,se.runtimeAvailability))}catch(se){C(rc(se))}finally{u(!1)}}}async function le(){if(n){h(!0),C(null),x(null);try{const se=await g1({enabled:m,enabledCommandIds:p});M(se),x(E1(se))}catch(se){C(rc(se))}finally{h(!1)}}}function M(se){i(se),g(se.provider.enabled),b(se.entries.filter(ce=>ce.enabled).map(ce=>ce.commandId).sort((ce,Y)=>ce.localeCompare(Y))),C(null)}function de(se){g(se)}function Ne(se,ce){const Y=se.commands.map(Te=>Te.commandId);b(Te=>{const pe=new Set(Te);for(const fe of Y)ce?pe.add(fe):pe.delete(fe);return[...pe].sort((fe,W)=>fe.localeCompare(W))})}function ye(se,ce){b(Y=>{const Te=new Set(Y);return ce?Te.add(se):Te.delete(se),[...Te].sort((pe,fe)=>pe.localeCompare(fe))})}const Be=(r==null?void 0:r.summary)??{catalogCount:0,browserDependentCount:0,installState:"not_installed"};return s.jsxs("section",{className:"settings-opencli-panel settings-skill-section",children:[e==="internal"?s.jsx(y1,{state:I,className:"settings-opencli-inline-toolbar"}):null,s.jsxs("div",{className:"settings-skill-summary-grid",children:[s.jsx(sc,{label:a("settings.opencliSummaryInstallState"),value:Pg(Be.installState)}),s.jsx(sc,{label:a("settings.opencliSummaryCatalogCount"),value:String(Be.catalogCount)}),s.jsx(sc,{label:a("settings.opencliSummaryEnabledCount"),value:String(p.length)}),s.jsx(sc,{label:a("settings.opencliSummaryBrowserCount"),value:String(Be.browserDependentCount)})]}),y?s.jsx("p",{className:"settings-release-status",children:y}):null,k?s.jsx("p",{className:"settings-release-status",children:k}):null,o?s.jsx("div",{className:"settings-skill-empty",children:a("settings.opencliLoading")}):r!=null&&r.siteGroups.length?s.jsxs("section",{className:"settings-opencli-catalog-section settings-skill-section",children:[s.jsx("div",{className:"settings-model-tabs settings-opencli-filter-tabs",role:"tablist","aria-label":a("settings.opencliFilterTabsLabel"),children:te.map(se=>{const ce=j===se.id;return s.jsx("button",{type:"button",role:"tab",className:"settings-model-tab","aria-selected":ce,"data-active":ce?"true":"false",onClick:()=>H(se.id),children:se.label},se.id)})}),ee.length>0?s.jsx("div",{className:"settings-opencli-site-grid",children:ee.map(se=>{const ce=w1(se,D),Y=j1(se.commands),Te=Rg(se,{maxDescriptions:2}),pe=Rg(se),fe=Aw(se.site),W=_===se.site;return s.jsxs("div",{className:"settings-opencli-site-card","data-selected":W?"true":"false",children:[s.jsxs("div",{className:"settings-opencli-site-card-head",children:[s.jsx("div",{className:"settings-opencli-site-card-visual",style:fe.style,children:s.jsx("span",{children:fe.label})}),s.jsxs("div",{className:"settings-opencli-site-card-body",children:[s.jsxs("div",{className:"settings-opencli-site-card-topline",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:se.site}),s.jsxs("div",{className:"settings-opencli-site-card-actions",children:[s.jsx("button",{className:"ghost-button settings-opencli-site-detail-button",type:"button",onClick:()=>T(se.site),children:a("settings.opencliSiteViewAction")}),s.jsxs("label",{className:"settings-opencli-checkbox settings-opencli-site-toggle",children:[s.jsx("input",{"aria-label":a("settings.opencliSiteToggleLabel",{site:se.site}),type:"checkbox",checked:ce.allSelected,disabled:c||f,ref:Me=>{Me&&(Me.indeterminate=ce.partialSelected)},onChange:Me=>Ne(se,Me.target.checked)}),s.jsx("span",{children:a("settings.opencliSiteEnableAction")})]})]})]}),s.jsx("p",{className:"settings-opencli-site-card-description",title:pe,children:Te})]})]}),s.jsx("div",{className:"settings-opencli-site-card-summary",children:s.jsx("div",{className:"settings-opencli-site-card-tag-rows",children:s.jsx("div",{className:"settings-skill-tags settings-opencli-site-card-tag-row settings-opencli-site-card-type-row",children:(Y.length>0?Y:["unknown"]).slice(0,2).map(Me=>s.jsx("span",{className:"settings-skill-tag settings-opencli-strategy-tag","data-strategy":Mw(Me),children:Rw(Me)},`${se.site}:${Me}`))})})})]},se.site)})}):s.jsx("div",{className:"settings-skill-empty",children:a("settings.opencliFilteredEmpty")})]}):s.jsx("div",{className:"settings-skill-empty",children:L1(r)}),s.jsx(ln,{open:P,title:a("settings.opencliDetailTitle"),className:"settings-opencli-detail-modal",onClose:()=>z(!1),children:r?s.jsxs(s.Fragment,{children:[s.jsx(Jn,{heading:a("settings.opencliDetailStatusHeading"),actions:s.jsxs("div",{className:"settings-opencli-detail-tags",children:[s.jsx(Jl,{children:Pg(r.provider.installState)}),s.jsx(Jl,{children:I1(r.provider.healthState)}),s.jsx(Jl,{children:R1(((We=r.activeRuntimeProfile)==null?void 0:We.status)??null)})]}),children:s.jsxs(Wi,{compact:!0,className:"settings-opencli-detail-list",children:[s.jsx(rs,{label:a("settings.opencliEnabledStateLabel"),trailing:s.jsx("span",{className:"settings-opencli-detail-value",children:m?a("settings.opencliEnabledStateOn"):a("settings.opencliEnabledStateOff")})}),s.jsx(rs,{label:a("settings.opencliSummaryCatalogCount"),trailing:s.jsx("span",{className:"settings-opencli-detail-value",children:String(Be.catalogCount)})}),s.jsx(rs,{label:a("settings.opencliSummaryEnabledCount"),trailing:s.jsx("span",{className:"settings-opencli-detail-value",children:String(p.length)})}),s.jsx(rs,{label:a("settings.opencliSummaryBrowserCount"),trailing:s.jsx("span",{className:"settings-opencli-detail-value",children:String(Be.browserDependentCount)})}),s.jsx(rs,{label:a("settings.opencliVersionLabel"),trailing:s.jsx("span",{className:"settings-opencli-detail-value",children:r.provider.version??"-"})}),s.jsx(rs,{label:a("settings.opencliCatalogSourceLabel"),trailing:s.jsx("span",{className:"settings-opencli-detail-value",children:A1(r.effectiveCatalogSource??null)})}),s.jsx(rs,{label:a("settings.opencliLastCheckedLabel"),trailing:s.jsx("span",{className:"settings-opencli-detail-value",children:Mg(r.provider.lastCheckedAt)})}),s.jsx(rs,{label:a("settings.opencliCatalogRefreshedLabel"),trailing:s.jsx("span",{className:"settings-opencli-detail-value",children:Mg(r.provider.catalogRefreshedAt)})}),s.jsx(rs,{label:a("settings.opencliInstallPathLabel"),description:r.provider.installPath??"-"}),s.jsx(rs,{label:a("settings.opencliDetailRuntimeIdLabel"),description:r.provider.activeRuntimeId??"-"}),s.jsx(rs,{label:a("settings.opencliDetailRuntimeRootLabel"),description:((Ce=r.activeRuntimeProfile)==null?void 0:Ce.runtimeRootPath)??"-"})]})}),r.provider.lastErrorDetail||(ke=r.activeRuntimeProfile)!=null&&ke.lastErrorDetail?s.jsx(Jn,{tone:"danger",heading:a("settings.opencliDetailErrorHeading"),children:s.jsxs("div",{className:"settings-opencli-detail-errors",children:[r.provider.lastErrorDetail?s.jsx("p",{className:"settings-skill-entry-meta",children:r.provider.lastErrorDetail}):null,(we=r.activeRuntimeProfile)!=null&&we.lastErrorDetail?s.jsx("p",{className:"settings-skill-entry-meta",children:r.activeRuntimeProfile.lastErrorDetail}):null]})}):null]}):null}),s.jsx(ln,{open:U!==null,title:U?a("settings.opencliSiteDetailTitle",{site:U.site}):a("settings.opencliCommandModalFallbackTitle"),description:U?a("settings.opencliSiteDetailDescription",{count:he.length,total:U.totalCount}):void 0,className:"settings-opencli-command-modal",onClose:()=>T(null),children:U?s.jsxs("section",{className:"settings-skill-section",children:[s.jsx(Jn,{heading:a("settings.opencliSiteDescriptionHeading"),children:s.jsx("div",{className:"settings-opencli-site-detail-copy",children:Iw(U.commands).map(se=>s.jsx("p",{className:"settings-opencli-site-detail-description",children:se},se))})}),s.jsx(Jn,{heading:a("settings.opencliCommandSearchLabel"),actions:s.jsx(Jl,{children:a("settings.opencliCommandResultCount",{count:he.length})}),children:s.jsxs("div",{className:"settings-opencli-command-tools",children:[s.jsxs("label",{className:"settings-opencli-command-search",htmlFor:"opencli-command-search",children:[s.jsx("span",{className:"settings-opencli-command-search-label",children:a("settings.opencliCommandSearchLabel")}),s.jsx("input",{id:"opencli-command-search",className:"settings-text-input",type:"search",value:L,placeholder:a("settings.opencliCommandSearchPlaceholder"),onChange:se=>R(se.target.value)})]}),s.jsxs("div",{className:"settings-opencli-command-sort",children:[s.jsx("span",{className:"settings-opencli-command-search-label",children:a("settings.opencliCommandSortLabel")}),s.jsx("div",{className:"settings-opencli-command-sort-tabs",role:"tablist","aria-label":a("settings.opencliCommandSortLabel"),children:V.map(se=>{const ce=K===se.id;return s.jsx("button",{type:"button",role:"tab",className:"settings-model-tab settings-opencli-command-sort-button","aria-selected":ce,"data-active":ce?"true":"false",onClick:()=>E(se.id),children:se.label},se.id)})})]})]})}),he.length>0?s.jsx("div",{className:"settings-opencli-command-grid",children:he.map(se=>s.jsx(x1,{command:se,checked:D.has(se.commandId),disabled:c||f,onToggle:ye},se.commandId))}):s.jsx($i,{compact:!0,title:a("settings.opencliCommandModalEmpty")})]}):null})]})}function y1({state:e,className:t}){return s.jsxs("div",{className:`settings-opencli-toolbar${t?` ${t}`:""}`,children:[s.jsxs("label",{className:"settings-opencli-checkbox settings-opencli-toolbar-toggle",children:[s.jsx("input",{"aria-label":a("settings.opencliProviderToggleLabel"),type:"checkbox",checked:e.draftEnabled,disabled:e.enableDisabled,onChange:n=>e.onEnabledChange(n.target.checked)}),s.jsx("span",{children:a("settings.opencliEnableAction")})]}),s.jsx("button",{className:"secondary-button",type:"button",disabled:e.refreshDisabled,onClick:e.onRefresh,children:e.refreshing?a("common.loading"):a("settings.opencliRefreshAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:e.detailDisabled,onClick:e.onShowDetails,children:a("settings.opencliDetailAction")}),s.jsx("button",{className:"primary-button",type:"button",disabled:e.saveDisabled,onClick:e.onSave,children:e.saving?a("common.loading"):a("settings.opencliSaveAction")})]})}function x1({command:e,checked:t,disabled:n,onToggle:r}){const i=Aw(e.commandId);return s.jsxs("div",{className:"settings-opencli-command-card",children:[s.jsxs("div",{className:"settings-opencli-command-card-head",children:[s.jsx("div",{className:"settings-opencli-command-badge",style:i.style,children:s.jsx("span",{children:e.name.slice(0,1).toUpperCase()})}),s.jsxs("div",{className:"settings-opencli-command-card-main",children:[s.jsxs("label",{className:"settings-opencli-checkbox",children:[s.jsx("input",{"aria-label":a("settings.opencliCommandToggleLabel",{commandId:e.commandId}),type:"checkbox",checked:t,disabled:n,onChange:o=>r(e.commandId,o.target.checked)}),s.jsx("span",{children:e.commandId})]}),s.jsx("p",{className:"settings-skill-entry-meta",children:e.description||a("settings.opencliCommandDescriptionEmpty")})]})]}),s.jsxs("div",{className:"settings-skill-tags",children:[s.jsx("span",{className:"settings-skill-tag settings-opencli-strategy-tag","data-strategy":Mw(e.strategy),children:P1(e.strategy)}),e.browser?s.jsx("span",{className:"settings-skill-tag","data-status":"failed",children:a("settings.opencliBrowserTag")}):s.jsx("span",{className:"settings-skill-tag","data-status":"synced",children:a("settings.opencliHttpTag")})]})]})}function sc({label:e,value:t}){return s.jsxs("div",{className:"settings-skill-summary-card",children:[s.jsx("span",{children:e}),s.jsx("strong",{children:t})]})}function k1(e){const t=Array.from(new Set(e.map(n=>n.strategy.trim()).filter(n=>n.length>0&&n!=="unknown"))).sort((n,r)=>n.localeCompare(r));return[{id:"all",label:a("settings.opencliFilterAll")},{id:"enabled",label:a("settings.opencliFilterEnabled")},{id:"browser",label:a("settings.opencliFilterBrowser")},{id:"direct",label:a("settings.opencliFilterDirect")},...t.map(n=>({id:`strategy:${n}`,label:a("settings.opencliFilterStrategy",{strategy:Rw(n)})}))]}function Ig(e,t,n){switch(t){case"all":return!0;case"enabled":return n.has(e.commandId);case"browser":return e.browser;case"direct":return!e.browser;default:return t.startsWith("strategy:")?e.strategy===t.slice(9):!0}}function w1(e,t){const n=e.commands.filter(r=>t.has(r.commandId)).length;return{selectedCount:n,allSelected:n>0&&n===e.commands.length,partialSelected:n>0&&n<e.commands.length}}function v1(e,t){return t?[e.commandId,e.name,e.description,e.strategy].join(`
5
+ `).toLowerCase().includes(t):!0}function S1(e,t,n){const r=Ag(e,n)-Ag(t,n);if(r!==0)return r;const i=e.name.localeCompare(t.name);return i!==0?i:e.commandId.localeCompare(t.commandId)}function Ag(e,t){const n=t.selectedCommandIdSet.has(e.commandId)?0:1,r=e.browser?1:0;switch(t.sortId){case"browser":return(e.browser?0:2)+n;case"name":return 0;case"status":default:return n*2+r}}function C1(){return[{id:"status",label:a("settings.opencliCommandSortStatus")},{id:"browser",label:a("settings.opencliCommandSortBrowser")},{id:"name",label:a("settings.opencliCommandSortName")}]}function Iw(e){return Array.from(new Set(e.map(t=>t.description.trim()).filter(t=>t.length>0)))}function Rg(e,t={}){const n=Iw(e.commands);if(n.length===0)return a("settings.opencliSiteDescriptionEmpty");const r=t.maxDescriptions??n.length;return n.slice(0,r).join(" · ")}function j1(e){return Array.from(new Set(e.map(t=>t.strategy.trim()).filter(t=>t.length>0&&t!=="unknown"))).sort((t,n)=>t.localeCompare(n))}function Aw(e){const t=D1[e.toLowerCase()];if(t)return{label:t.label,style:{background:t.background}};const n=Eg[Math.abs(T1(e))%Eg.length];return{label:N1(e),style:{background:`linear-gradient(135deg, ${n[0]} 0%, ${n[1]} 100%)`}}}function N1(e){const t=e.split(/[^a-z0-9]+/i).map(r=>r.trim()).filter(r=>r.length>0);if(t.length>=2)return`${t[0][0]??""}${t[1][0]??""}`.toUpperCase();const n=t[0]??e;return n.slice(0,Math.min(2,n.length)).toUpperCase()}function T1(e){let t=0;for(const n of e)t=(t<<5)-t+n.charCodeAt(0),t|=0;return t}function rc(e){return e instanceof rr?e.message||a("settings.opencliLoadFailed"):e instanceof Error?e.message:a("settings.opencliLoadFailed")}function Pg(e){switch(e){case"installed":return a("settings.opencliInstallInstalled");case"broken":return a("settings.opencliInstallBroken");default:return a("settings.opencliInstallMissing")}}function I1(e){switch(e){case"ready":return a("settings.opencliHealthReady");case"bridge_missing":return a("settings.opencliHealthBridgeMissing");case"binary_ready":return a("settings.opencliHealthBinaryReady");case"runtime_build_failed":return a("settings.opencliHealthRuntimeBuildFailed");default:return a("settings.opencliHealthUnknown")}}function A1(e){switch(e){case"manifest":return a("settings.opencliCatalogSourceManifest");case"cli_list":return a("settings.opencliCatalogSourceCliList");case"local_manifest":return a("settings.opencliCatalogSourceLocalManifest");case"cache":return a("settings.opencliCatalogSourceCache");default:return"-"}}function R1(e){switch(e){case"ready":return a("settings.opencliRuntimeReady");case"failed":return a("settings.opencliRuntimeFailed");case"pending":return a("settings.opencliRuntimePending");case"stale":return a("settings.opencliRuntimeStale");default:return a("settings.opencliRuntimeIdle")}}function P1(e){return a("settings.opencliStrategyLabel",{strategy:Pw(e)})}function Rw(e){return a("settings.opencliStrategyShortLabel",{strategy:Pw(e)})}function Pw(e){switch(Ew(e)){case"cookie":return a("settings.opencliStrategyCookie");case"header":return a("settings.opencliStrategyHeader");case"intercept":return a("settings.opencliStrategyIntercept");case"local":return a("settings.opencliStrategyLocal");case"public":return a("settings.opencliStrategyPublic");case"ui":return a("settings.opencliStrategyUi");default:return a("settings.opencliStrategyUnknown")}}function Mw(e){return Ew(e)}function Ew(e){const t=e.trim().toLowerCase();return t.length>0?t:"unknown"}function M1(e,t){return e==="cache_retained"?a("settings.opencliRefreshCacheRetained"):e==="unavailable"?a("settings.opencliRefreshUnavailable"):t==="ready"?a("settings.opencliRefreshReady"):a("settings.opencliRefreshDone")}function E1(e){return e.runtimeAvailability==="ready"?a("settings.opencliSaveReady"):e.provider.enabled?a("settings.opencliSaveEnabled"):a("settings.opencliSaveDisabled")}function L1(e){return e?e.provider.installState!=="installed"?a("settings.opencliEmptyNotInstalled"):a("settings.opencliEmpty"):a("settings.opencliEmpty")}function Mg(e){if(!e)return"-";const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toLocaleString()}const Eg=[["#2563eb","#0ea5e9"],["#0f766e","#14b8a6"],["#7c3aed","#6366f1"],["#ea580c","#f59e0b"],["#be123c","#f43f5e"],["#1d4ed8","#38bdf8"]],D1={github:{label:"GH",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"},hackernews:{label:"HN",background:"linear-gradient(135deg, #f97316 0%, #fb923c 100%)"},twitter:{label:"TW",background:"linear-gradient(135deg, #2563eb 0%, #38bdf8 100%)"},x:{label:"X",background:"linear-gradient(135deg, #111827 0%, #6b7280 100%)"},reddit:{label:"RD",background:"linear-gradient(135deg, #f97316 0%, #ef4444 100%)"}},O1=[{id:"skills"},{id:"office"},{id:"ops"},{id:"opencli"}];function F1({triggerClassName:e="secondary-button",triggerLabel:t,triggerLeading:n,workspaceId:r=null,sessionId:i=null,initialTab:o="skills",triggerMode:l="panel"}){var Mt;const c=iu(A=>{var ie;return((ie=A.session)==null?void 0:ie.accessToken)??null}),u=iu(A=>{var ie;return((ie=A.session)==null?void 0:ie.user)??null}),f=d.useRef(null),h=d.useRef(null),[m,g]=d.useState(null),[p,b]=d.useState([]),[y,x]=d.useState([]),[k,C]=d.useState([]),[j,H]=d.useState({}),[_,T]=d.useState(null),[P,z]=d.useState(null),[L,R]=d.useState(null),[K,E]=d.useState([]),[D,te]=d.useState([]),[V,ee]=d.useState([]),[U,he]=d.useState(null),[X,I]=d.useState(null),[xe,le]=d.useState(null),[M,de]=d.useState(null),[Ne,ye]=d.useState(null),[Be,We]=d.useState(!1),[Ce,ke]=d.useState(null),[we,se]=d.useState(null),[ce,Y]=d.useState(null),[Te,pe]=d.useState(!1),[fe,W]=d.useState(!1),[Me,je]=d.useState(!1),[Q,ge]=d.useState(!1),[Oe,$e]=d.useState(!1),[Ve,G]=d.useState(!1),[ve,_e]=d.useState(!1),[nt,et]=d.useState(!1),[ot,jt]=d.useState(!1),[Ft,bt]=d.useState(!1),[_t,xt]=d.useState(!1),[rt,It]=d.useState(null),[$t,pt]=d.useState(!1),Ie=(rt==null?void 0:rt.simplified)??null,[kt,St]=d.useState(null),[vt,Ct]=d.useState("file"),[J,Ue]=d.useState("workspace"),[ze,st]=d.useState(""),[q,re]=d.useState(()=>No("workspace")),[ue,Re]=d.useState(o),[Se,Ke]=d.useState(null),[De,He]=d.useState("all"),[lt,wt]=d.useState("ssh_host"),[it,Ze]=d.useState({enabled:!1,serverUrl:"",publicBaseUrl:"",callbackBaseUrl:"",userDisplayName:"",userAvatarUrl:"",jwtSecret:"",clearJwtSecret:!1}),[Ht,gt]=d.useState({fileName:"",fileContentBase64:""}),[Nt,dt]=d.useState({displayName:"",engine:"chrome",mode:"persistent",ownershipScope:r!=null&&r.trim()?"workspace":"user",cdpEndpoint:""}),[ft,en]=d.useState({targetId:null,displayName:"",environment:"",host:"",port:"22",username:"",privateKeyPath:"",knownHostsPath:"",jumpHost:"",workspacePath:"",credentialRef:"",strictHostKeyChecking:"accept-new",status:"active"}),cn=d.useId(),Cn=Tw(Te&&!!c).items??[],Bt=d.useMemo(()=>oA(Cn),[Cn]),is=d.useMemo(()=>new Map(K.map(A=>[A.id,A])),[K]),Ws=d.useMemo(()=>!Ft||!(r!=null&&r.trim())?y:y.filter(A=>A.workspaceId===r),[y,Ft,r]),fn=d.useMemo(()=>xe?k.filter(A=>A.targetRefId===xe.id):[],[k,xe]);d.useEffect(()=>{P&&Ze(lc(P))},[P]),d.useEffect(()=>{let A=!0;if(!Te&&!Q)return;if(!c){g(null),se(null),Y(null),We(!1);return}return(async()=>{We(!0);try{const[tt,Pt,zt,pn,Os,Tn,Qs,Pn,on]=await Promise.all([ch(),wg("active"),vg(),tc({taskType:"browser",limit:100}),Cg(),nc(),th(),tc({workspaceId:r,taskType:"ops",limit:20}),jg({workspaceId:r,kind:"ssh_host"})]);if(!A)return;const Sn=await qg(pn),gn=await Sg().catch(()=>null);g(tt),b(Pt),x(zt),C(pn),T(gn),H(Sn),z(Os),R(Tn),E(Qs.items),te(Pn),ee(on),le(null),de(null),ye(null),se(null)}catch(tt){if(!A)return;se(fs(tt))}finally{A&&We(!1)}})(),()=>{A=!1}},[c,Te,Q,r]);async function mt(){const[A,ie,tt,Pt,zt,pn,Os,Tn,Qs]=await Promise.all([ch(),wg("active"),vg(),tc({taskType:"browser",limit:100}),Cg(),nc(),th(),tc({workspaceId:r,taskType:"ops",status:De==="all"?void 0:De,limit:20}),jg({workspaceId:r,kind:lt==="all"?void 0:lt})]),Pn=await qg(Pt),on=await Sg().catch(()=>null);g(A),b(ie),x(tt),C(Pt),T(on),H(Pn),z(zt),R(pn),E(Os.items),te(Tn),ee(Qs),se(null)}async function O(){if(c){ke("refresh"),se(null),Y(null);try{await mt(),Y(a("settings.skillRefreshSuccess"))}catch(A){se(fs(A))}finally{ke(null)}}}async function Ae(){if(c){ke("onlyoffice-save"),se(null),Y(null);try{const A=await i1({enabled:it.enabled,serverUrl:it.serverUrl,publicBaseUrl:it.publicBaseUrl,callbackBaseUrl:it.callbackBaseUrl,userDisplayName:it.userDisplayName,userAvatarUrl:it.userAvatarUrl,jwtSecret:it.jwtSecret,clearJwtSecret:it.clearJwtSecret}),ie=await nc();z(A),R(ie),Ze(tt=>({...tt,jwtSecret:"",clearJwtSecret:!1})),Y(a("settings.skillOnlyOfficeSaveSuccess"))}catch(A){se(fs(A))}finally{ke(null)}}}async function Xe(){if(c){ke("onlyoffice-check"),se(null),Y(null);try{const A=await nc();R(A),Y(a("settings.skillOnlyOfficeCheckSuccess"))}catch(A){se(fs(A))}finally{ke(null)}}}async function Qt(){if(c){ke("office-template-submit"),se(null),Y(null);try{await s1({fileName:Ht.fileName,fileContentBase64:Ht.fileContentBase64}),gt(oc()),je(!1),Y(a("settings.skillOfficeTemplateImported")),await mt()}catch(A){se(fs(A))}finally{ke(null)}}}async function Un(){if(c){ke("browser-profile-submit"),se(null),Y(null);try{await e1({workspaceId:r,displayName:Nt.displayName.trim()||null,engine:Nt.engine,mode:Nt.mode,ownershipScope:Nt.ownershipScope,cdpEndpoint:Nt.mode==="cdp_attached"&&Nt.cdpEndpoint.trim()||null}),dt(ac(r)),$e(!1),Y(a("settings.skillOfficeBrowserProfileCreated")),await mt()}catch(A){se(fs(A))}finally{ke(null)}}}async function as(A){var tt;if(!c)return;const ie=A.ownershipScope==="user"?"workspace":"user";if(ie==="workspace"&&!((tt=A.workspaceId)!=null&&tt.trim())){se(a("settings.skillOfficeBrowserProfileWorkspaceRequired"));return}ke(`browser-profile-scope:${A.id}`),se(null),Y(null);try{await t1(A.id,{ownershipScope:ie}),await mt(),Y(ie==="user"?a("settings.skillOfficeBrowserProfileCrossWorkspaceEnabled"):a("settings.skillOfficeBrowserProfileWorkspaceOnlyEnabled"))}catch(Pt){se(fs(Pt))}finally{ke(null)}}function tn(A){he(A),G(!0),se(null)}function sn(A){I(A),_e(!0),se(null)}async function At(){if(!c)return;const A=X;if(A){ke(`browser-profile-delete:${A.id}`),se(null),Y(null);try{await n1(A.id),(xe==null?void 0:xe.id)===A.id&&(jt(!1),le(null),de(null)),(U==null?void 0:U.id)===A.id&&(G(!1),he(null)),_e(!1),I(null),await mt(),Y(a("settings.skillOfficeBrowserProfileDeleted"))}catch(ie){se(fs(ie))}finally{ke(null)}}}async function Gt(A){if(c){ke(`browser-profile-tasks:${A.id}`),se(null);try{le(A),de(null),jt(!0)}catch(ie){se(fs(ie))}finally{ke(null)}}}async function Zn(A){if(c){ke(`browser-task-detail:${A}`),se(null);try{const[ie,tt]=await Promise.all([Pd(A),uh(A)]);de(ie),H(Pt=>({...Pt,[A]:tt}))}catch(ie){se(fs(ie))}finally{ke(null)}}}async function es(A){if(c){ke(`browser-task-execute:${A}`),se(null),Y(null);try{await r1(A),await Nn(A),Y(a("settings.skillOfficeBrowserInstanceStarted"))}catch(ie){se(fs(ie))}finally{ke(null)}}}async function os(A){if(c){ke(`browser-task-cancel:${A}`),se(null),Y(null);try{await a1(A),await Nn(A),Y(a("settings.skillOfficeBrowserInstanceCancelled"))}catch(ie){se(fs(ie))}finally{ke(null)}}}async function ut(A){if(c){ke(`ops-task-detail:${A}`),se(null);try{const ie=await Pd(A);ye(ie)}catch(ie){se(fs(ie))}finally{ke(null)}}}async function Ds(A,ie){if(c){ke(`ops-approval:${A}:${ie}`),se(null);try{if(await o1(A,{status:ie,decisionNote:ie==="approved"?a("settings.skillOpsApprovalApproveNote"):a("settings.skillOpsApprovalRejectNote")}),Ne){const tt=await Pd(Ne.task.id);ye(tt)}await mt(),Y(ie==="approved"?a("settings.skillOpsApprovalApproved"):a("settings.skillOpsApprovalRejected"))}catch(tt){se(fs(tt))}finally{ke(null)}}}async function cr(){if(c){ke("ops-target-submit"),se(null),Y(null);try{const A={workspaceId:r,kind:"ssh_host",displayName:ft.displayName.trim(),environment:ft.environment.trim()||null,credentialRef:ft.credentialRef.trim()||null,status:ft.status,config:{host:ft.host.trim(),port:Number.parseInt(ft.port,10)||22,username:ft.username.trim(),privateKeyPath:ft.privateKeyPath.trim()||void 0,knownHostsPath:ft.knownHostsPath.trim()||void 0,jumpHost:ft.jumpHost.trim()||void 0,workspacePath:ft.workspacePath.trim()||void 0,strictHostKeyChecking:ft.strictHostKeyChecking}};ft.targetId?(await c1(ft.targetId,A),Y(a("settings.skillOpsTargetUpdated"))):(await l1(A),Y(a("settings.skillOpsTargetCreated"))),en(ic()),et(!1),await mt()}catch(A){se(fs(A))}finally{ke(null)}}}async function jn(){if(!(!c||!(r!=null&&r.trim()))){xt(!0),pt(!0),se(null);try{const A=await JI({workspaceId:r,sessionId:i});It(A)}catch(A){se(fs(A)),It(null)}finally{pt(!1)}}}function an(A){const ie=Lw(A.configJson);en({targetId:A.id,displayName:A.displayName,environment:A.environment??"",host:Ei(ie.host),port:Dw(ie.port,22),username:Ei(ie.username),privateKeyPath:Ei(ie.privateKeyPath),knownHostsPath:Ei(ie.knownHostsPath),jumpHost:Ei(ie.jumpHost),workspacePath:Ei(ie.workspacePath),credentialRef:A.credentialRef??"",strictHostKeyChecking:q1(ie.strictHostKeyChecking),status:A.status}),et(!0)}function hs(){en(ic())}async function ur(A){var tt;const ie=((tt=A.target.files)==null?void 0:tt[0])??null;if(A.target.value="",!!ie){se(null),Y(null);try{gt({fileName:ie.name,fileContentBase64:await CA(ie)})}catch(Pt){se(fs(Pt))}}}function ts(){gt(oc()),je(!0),se(null)}function Dn(){Ze(lc(P)),ge(!0),se(null)}function Kn(){dt(ac(r)),$e(!0),se(null)}function Rn(){en(ic()),et(!0),se(null)}async function Nn(A){const ie=await uh(A);H(tt=>({...tt,[A]:ie}))}async function ks(A){if(c){ke(Lg(A)),se(null),Y(null);try{await QI({targetCli:A.targetCli,directoryPath:A.directoryPath,expectedContentHash:A.contentHash}),await mt(),Y(a("settings.skillImportSuccess",{name:A.name,target:yr(A.targetCli)}))}catch(ie){se(fs(ie))}finally{ke(null)}}}async function xn(A){if(!c)return;const ie=A.bindings.filter(tt=>tt.enabled).map(tt=>tt.targetCli).filter(tt=>Vs(tt,Bt));if(ie.length===0){se(pA(A.bindings));return}ke(Dg(A.skill.id)),se(null),Y(null);try{await ZI({skillId:A.skill.id,targetCli:ie}),await mt(),Y(a("settings.skillSyncSuccess",{name:A.skill.name}))}catch(tt){se(fs(tt))}finally{ke(null)}}async function $s(A){var tt;const ie=((tt=A.target.files)==null?void 0:tt[0])??null;if(A.target.value="",!!ie){se(null),Y(null);try{const Pt=await SA(ie),zt=Bw(ie.name,Pt);St(zt),re(No(J,Bt))}catch(Pt){se(fs(Pt))}}}async function Vt(){const A=Hg({sourceMode:vt,fileDraft:kt,pastedMarkdown:ze});if(!c)return;if(!A){se(vt==="paste"?a("settings.skillPasteEmpty"):a("settings.skillUploadEmpty"));return}const ie=A.directoryName;if(!ie){se(a("settings.skillUploadDirectoryInvalid"));return}const tt=fu(J).filter(Pt=>q[Pt]).filter(Pt=>Vs(Pt,Bt)).map(Pt=>Pt);if(tt.length===0){se(gA(J,Bt));return}ke("upload"),se(null),Y(null);try{await XI({markdownContent:A.rawContent,scope:J,fileName:A.fileName,directoryName:ie,targetCli:tt}),await mt(),Y(a("settings.skillUploadSuccess",{name:ie})),ls(J),W(!1)}catch(Pt){se(fs(Pt))}finally{ke(null)}}function nn(A){Ue(A),re(No(A,Bt))}function ns(A){Ct(A),St(null),st(""),re(No(J,Bt)),se(null)}function ss(A){Vs(A,Bt)&&re(ie=>({...ie,[A]:!ie[A]}))}function Ts(){W(!0),se(null),ls(J)}function Xs(){W(!1),se(null),ls(J)}function ls(A){St(null),st(""),Ct("file"),re(No(A,Bt))}const zs=(m==null?void 0:m.summary)??{managedSkillCount:0,managedEntryCount:0},ms=xA((m==null?void 0:m.assistantRuntimeSkills)??[],(m==null?void 0:m.conflictedEntries)??[],(m==null?void 0:m.diagnostics)??[]),ps=((m==null?void 0:m.conflictedEntries)??[]).filter(A=>!_w(A,(m==null?void 0:m.diagnostics)??[])),ws=((m==null?void 0:m.diagnostics)??[]).filter(A=>!Al(A)),On=Hg({sourceMode:vt,fileDraft:kt,pastedMarkdown:ze}),vs=t??a("settings.skillManageAction"),Ss=ue==="skills",Wn=ue==="office",Gn=ue==="ops",cs=ue==="opencli",Rt=l==="onlyoffice",Yn=Te||Q;return s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:e,type:"button","data-open":Yn?"true":"false","aria-haspopup":"dialog","aria-expanded":Yn,onClick:()=>{if(se(null),Y(null),Re(o),Rt){ge(!0);return}pe(!0)},children:[n,s.jsx("span",{children:vs})]}),s.jsxs(ln,{open:Te,title:a("settings.skillConfigModalTitle"),hideHeader:!0,className:"settings-skill-modal",onClose:()=>{Re(o),pe(!1)},children:[s.jsxs("div",{className:"settings-skill-modal-topbar",children:[s.jsxs("div",{className:"settings-skill-modal-topbar-main",children:[s.jsx("div",{className:"settings-model-tabs settings-skill-tabs",role:"tablist","aria-label":a("settings.skillConfigTabsLabel"),children:O1.map(A=>{const ie=ue===A.id,tt=`${cn}-${A.id}-tab`,Pt=`${cn}-${A.id}-panel`;return s.jsx("button",{id:tt,type:"button",role:"tab",className:"settings-model-tab","aria-selected":ie,"aria-controls":Pt,"data-active":ie?"true":"false",onClick:()=>Re(A.id),children:U1(A.id)},A.id)})}),Ss?s.jsxs("div",{className:"settings-skill-modal-actions settings-skill-page-toolbar",children:[s.jsx("button",{className:"secondary-button",type:"button",disabled:!c||Be||Ce!==null,onClick:Ts,children:a("settings.skillCreateAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:!c||Be||Ce!==null,onClick:()=>{O()},children:Ce==="refresh"?a("common.loading"):a("settings.skillRefresh")})]}):null,Wn?s.jsxs("div",{className:"settings-skill-modal-actions settings-skill-page-toolbar",children:[s.jsxs("div",{className:"settings-skill-toolbar-status",role:"status",title:_?a("settings.skillOfficeBrowserBridgeSummaryDetail",{provider:_.provider,status:$g(_),detail:_.detail??a("settings.skillOfficeBrowserBridgeDetailReady")}):a("settings.skillOfficeBrowserBridgeAvailabilityUnknown"),children:[s.jsx("span",{className:"settings-skill-toolbar-status-dot","data-status":eA(_),"aria-hidden":"true"}),s.jsx("span",{className:"settings-skill-toolbar-status-label",children:a("settings.skillOfficeBrowserBridgeSummaryLabel")}),s.jsx("strong",{className:"settings-skill-toolbar-status-value",children:$g(_)})]}),s.jsx("button",{className:"secondary-button",type:"button",disabled:!c||Be||Ce!==null,onClick:ts,children:a("settings.skillOfficeTemplateOpenCreateAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:!c||Be||Ce!==null,onClick:Kn,children:a("settings.skillOfficeBrowserProfileOpenCreateAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:!c||Be||Ce!==null,onClick:()=>{O()},children:Ce==="refresh"?a("common.loading"):a("settings.skillRefresh")})]}):null,Gn?s.jsxs("div",{className:"settings-skill-modal-actions settings-skill-page-toolbar",children:[s.jsx("button",{className:"secondary-button",type:"button",disabled:!c||Be||Ce!==null,onClick:Rn,children:a("settings.skillOpsTargetOpenCreateAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:!c||Be||Ce!==null,onClick:()=>{O()},children:Ce==="refresh"?a("common.loading"):a("settings.skillRefresh")})]}):null,cs&&Se?s.jsxs("div",{className:"settings-skill-modal-actions settings-skill-page-toolbar settings-opencli-toolbar",children:[s.jsxs("label",{className:"settings-opencli-checkbox settings-opencli-toolbar-toggle",children:[s.jsx("input",{"aria-label":a("settings.opencliProviderToggleLabel"),type:"checkbox",checked:Se.draftEnabled,disabled:Se.enableDisabled,onChange:A=>Se.onEnabledChange(A.target.checked)}),s.jsx("span",{children:a("settings.opencliEnableAction")})]}),s.jsx("button",{className:"secondary-button",type:"button",disabled:Se.refreshDisabled,onClick:Se.onRefresh,children:Se.refreshing?a("common.loading"):a("settings.opencliRefreshAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:Se.detailDisabled,onClick:Se.onShowDetails,children:a("settings.opencliDetailAction")}),s.jsx("button",{className:"primary-button",type:"button",disabled:Se.saveDisabled,onClick:Se.onSave,children:Se.saving?a("common.loading"):a("settings.opencliSaveAction")})]}):null]}),s.jsx(Zk,{onClick:()=>{Re("skills"),pe(!1)}})]}),Ss?s.jsxs("div",{id:`${cn}-skills-panel`,role:"tabpanel","aria-labelledby":`${cn}-skills-tab`,className:"settings-skill-panel",children:[s.jsxs("section",{className:"settings-skill-summary-block",children:[s.jsxs("div",{className:"settings-skill-summary-grid",children:[s.jsx(nr,{label:a("settings.skillSummaryManagedSkills"),value:String(zs.managedSkillCount)}),s.jsx(nr,{label:a("settings.skillSummaryManagedEntries"),value:String(zs.managedEntryCount)}),s.jsx(nr,{label:a("settings.skillSummaryConflictedEntries"),value:String(ps.length)}),s.jsx(nr,{label:a("settings.skillSummaryDiagnostics"),value:String(ws.length)})]}),s.jsx("div",{className:"settings-release-meta",children:s.jsxs("span",{children:[a("settings.skillScannedAt"),": ",Be?a("common.loading"):yA(m==null?void 0:m.scannedAt)]})}),ce?s.jsx("p",{className:"settings-release-status",children:ce}):null,we?s.jsx("p",{className:"settings-release-status",children:we}):null]}),s.jsx(Ur,{title:a("settings.skillManagedListTitle"),emptyText:a("settings.skillManagedEmpty"),items:(m==null?void 0:m.managedSkills)??[],renderItem:A=>{const ie=Dg(A.skill.id);return s.jsxs("div",{className:"settings-skill-entry",children:[s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:A.skill.name}),s.jsx("p",{className:"settings-skill-entry-meta",children:fA(A.bindings)}),s.jsx("div",{className:"settings-skill-tags",children:A.bindings.map(tt=>s.jsx("span",{className:"settings-skill-tag","data-status":uA(tt,Bt),children:dA(tt,Bt)},`${A.skill.id}-${tt.targetCli}`))})]}),s.jsx("div",{className:"settings-skill-entry-actions",children:s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null||!cA(A.bindings,Bt),onClick:()=>{xn(A)},children:Ce===ie?a("common.loading"):a("settings.skillSyncAction")})})]},A.skill.id)}}),s.jsx(Ur,{title:a("settings.skillUnmanagedListTitle"),emptyText:a("settings.skillUnmanagedEmpty"),items:(m==null?void 0:m.unmanagedEntries)??[],renderItem:A=>{const ie=Lg(A);return s.jsxs("div",{className:"settings-skill-entry",children:[s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:A.name}),s.jsx("p",{className:"settings-skill-entry-meta",children:hA(A,Bt)}),Vs(A.targetCli,Bt)?null:s.jsx("div",{className:"settings-skill-tags",children:s.jsx("span",{className:"settings-skill-tag","data-status":"failed",children:a("settings.skillTargetDisabledTag")})})]}),s.jsx("div",{className:"settings-skill-entry-actions",children:s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null||!Vs(A.targetCli,Bt),onClick:()=>{ks(A)},children:Ce===ie?a("common.loading"):a("settings.skillImportAction")})})]},`${A.targetCli}:${A.directoryPath}`)}}),s.jsx(Ur,{title:a("settings.skillAssistantRuntimeListTitle"),description:a("settings.skillAssistantRuntimeListDescription"),emptyText:a("settings.skillAssistantRuntimeEmpty"),items:ms,renderItem:A=>s.jsxs("div",{className:"settings-skill-entry",children:[s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:A.name}),s.jsx("p",{className:"settings-skill-entry-meta",children:a("settings.skillAssistantRuntimeItemDescription")}),s.jsxs("p",{className:"settings-skill-entry-meta",children:[a("settings.skillAssistantRuntimeUsedBy"),": ",Fw(A.usedByTargetCli)]}),s.jsxs("div",{className:"settings-skill-tags",children:[s.jsx("span",{className:"settings-skill-tag","data-status":"assistant-runtime",children:kA(A.usageTag)}),A.usedByTargetCli.map(ie=>s.jsx("span",{className:"settings-skill-tag","data-status":Vs(ie,Bt)?"synced":"failed",children:Vs(ie,Bt)?yr(ie):`${yr(ie)} · ${a("settings.skillTargetDisabledTag")}`},`${A.directoryName}:${ie}`))]})]}),A.directoryName==="codingns-workspace-session"?s.jsx("div",{className:"settings-skill-entry-actions",children:s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null||!(r!=null&&r.trim()),onClick:()=>{jn()},children:a("settings.skillWorkspaceSessionMcpStatusAction")})}):null]},`${A.directoryName}:${A.sourcePath}`)}),s.jsx(Ur,{title:a("settings.skillConflictedListTitle"),emptyText:a("settings.skillConflictedEmpty"),items:ps,renderItem:A=>{const ie=wA(A,(m==null?void 0:m.diagnostics)??[]);return s.jsx("div",{className:"settings-skill-entry",children:s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:A.name}),s.jsx("p",{className:"settings-skill-entry-meta",children:mA(A,Bt)}),ie.length>0?s.jsx("div",{className:"settings-skill-tags",children:ie.map(tt=>s.jsx("span",{className:"settings-skill-tag","data-status":tt.status,children:tt.label},tt.key))}):null]})},`${A.targetCli}:${A.directoryPath}`)}}),s.jsx(Ur,{title:a("settings.skillDiagnosticsTitle"),emptyText:a("settings.skillDiagnosticsEmpty"),items:ws,renderItem:A=>{const ie=vA(A),tt=bA(A);return s.jsx("div",{className:"settings-skill-entry",children:s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:tt.title}),s.jsx("p",{className:"settings-skill-entry-meta",children:tt.detail}),ie.length>0?s.jsx("div",{className:"settings-skill-tags",children:ie.map(Pt=>s.jsx("span",{className:"settings-skill-tag","data-status":Pt.status,children:Pt.label},Pt.key))}):null]})},`${A.targetCli}:${A.code}:${A.directoryPath??A.rootDir}`)}})]}):null,Wn?s.jsxs("div",{id:`${cn}-office-panel`,role:"tabpanel","aria-labelledby":`${cn}-office-tab`,className:"settings-skill-panel",children:[s.jsxs("section",{className:"settings-skill-summary-block",children:[s.jsxs("div",{className:"settings-skill-summary-grid",children:[s.jsx(nr,{label:a("settings.skillOfficeTemplateCount"),value:String(p.length)}),s.jsx(nr,{label:a("settings.skillOfficeBrowserProfileCount"),value:String(Ws.length)}),s.jsx(nr,{label:a("settings.skillOfficeBrowserTaskCount"),value:String(k.length)}),s.jsx(nr,{label:a("settings.skillOnlyOfficeStatusLabel"),value:Ld(L)}),s.jsx(nr,{label:a("settings.skillOfficeWorkspaceScope"),value:r!=null&&r.trim()?a("settings.skillOfficeScoped"):a("settings.skillOfficeGlobal")})]}),ce?s.jsx("p",{className:"settings-release-status",children:ce}):null,we?s.jsx("p",{className:"settings-release-status",children:we}):null]}),s.jsx(Ur,{title:a("settings.skillOnlyOfficeSectionTitle"),description:a("settings.skillOnlyOfficeSectionDescription"),emptyText:a("settings.skillOnlyOfficeSectionEmpty"),items:[L??null],renderItem:()=>{var A;return s.jsxs("div",{className:"settings-skill-entry",children:[s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:a("settings.skillOnlyOfficeSectionTitle")}),s.jsx("p",{className:"settings-skill-entry-meta",children:(L==null?void 0:L.summary)??a("settings.skillOnlyOfficeStatusUnknown")}),s.jsxs("div",{className:"settings-skill-tags",children:[s.jsx("span",{className:"settings-skill-tag","data-status":Q1(L==null?void 0:L.state),children:Ld(L)}),s.jsx("span",{className:"settings-skill-tag","data-status":P!=null&&P.enabled?"synced":"pending",children:P!=null&&P.enabled?a("settings.skillOnlyOfficeEnabledLabel"):a("settings.skillOnlyOfficeStatusDisabled")})]}),(A=L==null?void 0:L.checks)!=null&&A.length?s.jsx("div",{className:"settings-skill-tags",children:L.checks.map(ie=>s.jsx("span",{className:"settings-skill-tag","data-status":Wg(ie.status),title:ie.detail,children:`${ie.label} · ${Bg(ie.status)}`},ie.key))}):null]}),s.jsx("div",{className:"settings-skill-entry-actions",children:s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{Dn()},children:a("settings.skillOnlyOfficeOpenSettingsAction")})})]})}}),s.jsx(Ur,{title:a("settings.skillOfficeTemplateListTitle"),description:a("settings.skillOfficeTemplateListDescription"),emptyText:a("settings.skillOfficeTemplateEmpty"),items:p,renderItem:A=>s.jsxs("div",{className:"settings-skill-entry",children:[s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:A.displayName}),s.jsx("p",{className:"settings-skill-entry-meta",children:a("settings.skillOfficeTemplateListMeta",{key:A.templateKey,version:A.templateVersion})}),s.jsxs("div",{className:"settings-skill-tags",children:[s.jsx("span",{className:"settings-skill-tag","data-status":"synced",children:A.engine}),s.jsx("span",{className:"settings-skill-tag","data-status":A.status==="active"?"synced":"failed",children:A.status})]})]}),s.jsx("div",{className:"settings-skill-entry-actions",children:s.jsx("span",{className:"settings-skill-entry-meta",children:A.templateSourcePath??"-"})})]},A.id)}),s.jsx(Ur,{title:a("settings.skillOfficeBrowserProfileListTitle"),description:a("settings.skillOfficeBrowserProfileListDescription"),emptyText:a("settings.skillOfficeBrowserProfileEmpty"),headerExtra:s.jsxs("label",{className:"settings-skill-inline-toggle",children:[s.jsx("input",{type:"checkbox",checked:Ft,disabled:!(r!=null&&r.trim()),onChange:A=>bt(A.target.checked)}),s.jsx("span",{children:a("settings.skillOfficeBrowserProfileOnlyCurrentWorkspace")})]}),items:Ws,renderItem:A=>s.jsxs("div",{className:"settings-skill-entry settings-browser-profile-entry",children:[s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:A.displayName}),s.jsx("p",{className:"settings-skill-entry-meta",children:a("settings.skillOfficeBrowserProfileListMeta",{engine:Og(A.engine),mode:V1(A.mode),scope:K1(A.ownershipScope)})}),s.jsxs("div",{className:"settings-skill-tags",children:[s.jsx("span",{className:"settings-skill-tag","data-status":"synced",children:Og(A.engine)}),s.jsx("span",{className:"settings-skill-tag","data-status":Y1(A.status),children:G1(A.status)}),s.jsx("span",{className:"settings-skill-tag","data-status":"pending",children:a("settings.skillOfficeBrowserProfileWorkspaceTag",{workspaceName:Fg(A.workspaceId,is)})}),A.ownershipScope==="user"?s.jsx("span",{className:"settings-skill-tag","data-status":"synced",children:a("settings.skillOfficeBrowserProfileCrossWorkspaceTag")}):null,A.cdpEndpoint?s.jsx("span",{className:"settings-skill-tag","data-status":"pending",children:a("settings.skillOfficeBrowserProfileCdpEndpointTag")}):null]}),s.jsx("p",{className:"settings-skill-entry-meta settings-skill-path",children:A.userDataDir??A.cdpEndpoint??a("settings.skillOfficeBrowserProfileUserDataDirLabel")})]}),s.jsxs("div",{className:"settings-skill-entry-actions settings-browser-profile-entry-actions",children:[s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{tn(A)},children:a("settings.skillOfficeBrowserProfileOptionAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{Gt(A)},children:Ce===`browser-profile-tasks:${A.id}`?a("common.loading"):a("settings.skillOfficeBrowserProfileTaskAction")}),s.jsx("button",{className:"settings-button-danger",type:"button",disabled:Be||Ce!==null,onClick:()=>{sn(A)},children:a("settings.skillOfficeBrowserProfileDeleteAction")})]})]},A.id)})]}):null,Gn?s.jsxs("div",{id:`${cn}-ops-panel`,role:"tabpanel","aria-labelledby":`${cn}-ops-tab`,className:"settings-skill-panel",children:[s.jsxs("section",{className:"settings-skill-summary-block",children:[s.jsxs("div",{className:"settings-skill-summary-grid",children:[s.jsx(nr,{label:a("settings.skillOpsTaskCount"),value:String(D.length)}),s.jsx(nr,{label:a("settings.skillOpsTargetCount"),value:String(V.length)}),s.jsx(nr,{label:a("settings.skillOpsWorkspaceScope"),value:r!=null&&r.trim()?a("settings.skillOfficeScoped"):a("settings.skillOfficeGlobal")})]}),ce?s.jsx("p",{className:"settings-release-status",children:ce}):null,we?s.jsx("p",{className:"settings-release-status",children:we}):null]}),s.jsx(Ur,{title:a("settings.skillOpsTaskListTitle"),description:a("settings.skillOpsTaskListDescription"),emptyText:a("settings.skillOpsTaskEmpty"),items:D,renderItem:A=>s.jsxs("div",{className:"settings-skill-entry",children:[s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:A.title}),s.jsx("p",{className:"settings-skill-entry-meta",children:a("settings.skillOpsTaskListMeta",{status:A.status,risk:A.riskLevel})}),s.jsxs("div",{className:"settings-skill-tags",children:[s.jsx("span",{className:"settings-skill-tag","data-status":"synced",children:A.connectorId}),s.jsx("span",{className:"settings-skill-tag","data-status":zg(A.status),children:A.status})]}),(Ne==null?void 0:Ne.task.id)===A.id?s.jsx("div",{className:"settings-skill-tags",children:Ne.approvals.map(ie=>s.jsx("span",{className:"settings-skill-tag","data-status":ie.status==="pending"?"pending":ie.status==="approved"?"synced":"failed",children:ie.status},ie.id))}):null]}),s.jsxs("div",{className:"settings-skill-entry-actions",children:[s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{ut(A.id)},children:Ce===`ops-task-detail:${A.id}`?a("common.loading"):a("settings.skillOpsTaskDetailAction")}),(Ne==null?void 0:Ne.task.id)===A.id?Ne.approvals.filter(ie=>ie.status==="pending").map(ie=>s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{Ds(ie.id,"approved")},children:Ce===`ops-approval:${ie.id}:approved`?a("common.loading"):a("settings.skillOpsApprovalApproveAction")},ie.id)):null]})]},A.id)}),s.jsx(Ur,{title:a("settings.skillOpsTargetListTitle"),description:a("settings.skillOpsTargetListDescription"),emptyText:a("settings.skillOpsTargetEmpty"),items:V,renderItem:A=>s.jsxs("div",{className:"settings-skill-entry",children:[s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:A.displayName}),s.jsx("p",{className:"settings-skill-entry-meta",children:iA(A)}),s.jsxs("div",{className:"settings-skill-tags",children:[s.jsx("span",{className:"settings-skill-tag","data-status":"synced",children:A.kind}),s.jsx("span",{className:"settings-skill-tag","data-status":A.status==="active"?"synced":"failed",children:A.status})]})]}),s.jsx("div",{className:"settings-skill-entry-actions",children:s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>an(A),children:a("settings.skillOpsTargetEditAction")})})]},A.id)})]}):null,cs?s.jsx("div",{id:`${cn}-opencli-panel`,role:"tabpanel","aria-labelledby":`${cn}-opencli-tab`,className:"settings-skill-panel",children:s.jsx(b1,{toolbarMode:"external",onToolbarStateChange:Ke})}):null]}),s.jsxs(ln,{open:Q,title:a("settings.skillOnlyOfficeModalTitle"),description:a("settings.skillOnlyOfficeModalDescription"),className:"settings-skill-create-modal",onClose:()=>{ge(!1),Ze(lc(P))},children:[s.jsx(Jn,{heading:a("settings.skillOnlyOfficeStatusLabel"),children:s.jsx("div",{className:"settings-skill-entry",children:s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:Ld(L)}),s.jsx("p",{className:"settings-skill-entry-meta",children:(L==null?void 0:L.summary)??a("settings.skillOnlyOfficeStatusUnknown")}),(Mt=L==null?void 0:L.checks)!=null&&Mt.length?s.jsx("div",{className:"settings-skill-tags",children:L.checks.map(A=>s.jsx("span",{className:"settings-skill-tag","data-status":Wg(A.status),title:A.detail,children:`${A.label} · ${Bg(A.status)}`},A.key))}):null]})})}),s.jsxs(Jn,{heading:a("settings.skillOnlyOfficeSectionTitle"),children:[s.jsx(Ot,{label:a("settings.skillOnlyOfficeEnabledLabel"),children:s.jsxs("label",{className:"settings-skill-inline-toggle",children:[s.jsx("input",{type:"checkbox",checked:it.enabled,onChange:A=>{Ze(ie=>({...ie,enabled:A.target.checked}))}}),s.jsx("span",{children:a("settings.skillOnlyOfficeEnabledLabel")})]})}),s.jsx(Ot,{label:a("settings.skillOnlyOfficeServerUrlLabel"),htmlFor:"onlyoffice-server-url",children:s.jsx("input",{id:"onlyoffice-server-url",className:"settings-text-input",value:it.serverUrl,onChange:A=>{Ze(ie=>({...ie,serverUrl:A.target.value}))},placeholder:a("settings.skillOnlyOfficeServerUrlPlaceholder")})}),s.jsx(Ot,{label:a("settings.skillOnlyOfficePublicBaseUrlLabel"),htmlFor:"onlyoffice-public-base-url",children:s.jsx("input",{id:"onlyoffice-public-base-url",className:"settings-text-input",value:it.publicBaseUrl,onChange:A=>{Ze(ie=>({...ie,publicBaseUrl:A.target.value}))},placeholder:a("settings.skillOnlyOfficePublicBaseUrlPlaceholder")})}),s.jsx(Ot,{label:a("settings.skillOnlyOfficeCallbackBaseUrlLabel"),htmlFor:"onlyoffice-callback-base-url",children:s.jsx("input",{id:"onlyoffice-callback-base-url",className:"settings-text-input",value:it.callbackBaseUrl,onChange:A=>{Ze(ie=>({...ie,callbackBaseUrl:A.target.value}))},placeholder:a("settings.skillOnlyOfficeCallbackBaseUrlPlaceholder")})}),s.jsx(Ot,{label:a("settings.skillOnlyOfficeUserDisplayNameLabel"),description:a("settings.skillOnlyOfficeUserDisplayNameDescription",{username:(u==null?void 0:u.username)??"-"}),htmlFor:"onlyoffice-user-display-name",children:s.jsx("input",{id:"onlyoffice-user-display-name",className:"settings-text-input",value:it.userDisplayName,onChange:A=>{Ze(ie=>({...ie,userDisplayName:A.target.value}))},placeholder:a("settings.skillOnlyOfficeUserDisplayNamePlaceholder")})}),s.jsx(Ot,{label:a("settings.skillOnlyOfficeUserAvatarUrlLabel"),description:a("settings.skillOnlyOfficeUserAvatarUrlDescription"),htmlFor:"onlyoffice-user-avatar-url",children:s.jsx("input",{id:"onlyoffice-user-avatar-url",className:"settings-text-input",value:it.userAvatarUrl,onChange:A=>{Ze(ie=>({...ie,userAvatarUrl:A.target.value}))},placeholder:a("settings.skillOnlyOfficeUserAvatarUrlPlaceholder")})}),s.jsx(Ot,{label:a("settings.skillOnlyOfficeJwtSecretLabel"),htmlFor:"onlyoffice-jwt-secret",children:s.jsx("input",{id:"onlyoffice-jwt-secret",className:"settings-text-input",value:it.jwtSecret,onChange:A=>{Ze(ie=>({...ie,jwtSecret:A.target.value,clearJwtSecret:!1}))},placeholder:P!=null&&P.jwtSecretConfigured?a("settings.skillOnlyOfficeJwtSecretKeepPlaceholder"):a("settings.skillOnlyOfficeJwtSecretPlaceholder")})}),P!=null&&P.jwtSecretConfigured?s.jsx(Ot,{label:a("settings.skillOnlyOfficeClearJwtSecretLabel"),children:s.jsxs("label",{className:"settings-skill-inline-toggle",children:[s.jsx("input",{type:"checkbox",checked:it.clearJwtSecret,onChange:A=>{Ze(ie=>({...ie,clearJwtSecret:A.target.checked}))}}),s.jsx("span",{children:a("settings.skillOnlyOfficeClearJwtSecretLabel")})]})}):null,ce?s.jsx("p",{className:"settings-release-status",children:ce}):null,we?s.jsx("p",{className:"settings-release-status",children:we}):null,s.jsxs(Es,{children:[s.jsx("button",{className:"secondary-button",type:"button",onClick:()=>{ge(!1),Ze(lc(P))},children:a("common.cancel")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{Xe()},children:Ce==="onlyoffice-check"?a("common.loading"):a("settings.skillOnlyOfficeCheckAction")}),s.jsx("button",{className:"primary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{Ae()},children:Ce==="onlyoffice-save"?a("common.loading"):a("settings.skillOnlyOfficeSaveAction")})]})]})]}),s.jsx(ln,{open:Me,title:a("settings.skillOfficeTemplateModalTitle"),description:a("settings.skillOfficeTemplateModalDescription"),className:"settings-skill-create-modal",onClose:()=>{je(!1),gt(oc())},children:s.jsxs(Jn,{heading:a("settings.skillOfficeTemplateFormTitle"),children:[s.jsx("input",{ref:h,type:"file",accept:".domt,.doct,application/octet-stream",className:"settings-skill-upload-input",onChange:A=>{ur(A)}}),s.jsx(Ot,{label:a("settings.skillOfficeTemplateUploadLabel"),description:a("settings.skillOfficeTemplateUploadDescription"),children:s.jsx("div",{className:"settings-skill-create-toolbar",children:s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{var A;return(A=h.current)==null?void 0:A.click()},children:a("settings.skillOfficeTemplatePickAction")})})}),Ht.fileName?s.jsx("div",{className:"settings-skill-entry",children:s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:Ht.fileName}),s.jsx("p",{className:"settings-skill-entry-meta",children:a("settings.skillOfficeTemplateAutoDetectHint")})]})}):null,s.jsxs(Es,{children:[s.jsx("button",{className:"secondary-button",type:"button",onClick:()=>{je(!1),gt(oc())},children:a("common.cancel")}),s.jsx("button",{className:"primary-button",type:"button",disabled:!Ht.fileName||Be||Ce!==null,onClick:()=>{Qt()},children:Ce==="office-template-submit"?a("common.loading"):a("settings.skillOfficeTemplateSaveAction")})]})]})}),s.jsx(ln,{open:Oe,title:a("settings.skillOfficeBrowserProfileModalTitle"),description:a("settings.skillOfficeBrowserProfileModalDescription"),className:"settings-skill-create-modal",onClose:()=>{$e(!1),dt(ac(r))},children:s.jsxs(Jn,{heading:a("settings.skillOfficeBrowserProfileFormTitle"),children:[s.jsx(Ot,{label:a("settings.skillOfficeBrowserProfileNameLabel"),htmlFor:"browser-profile-name",children:s.jsx("input",{id:"browser-profile-name",className:"settings-text-input",value:Nt.displayName,onChange:A=>dt(ie=>({...ie,displayName:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOfficeBrowserProfileEngineLabel"),htmlFor:"browser-profile-engine",children:s.jsxs("select",{id:"browser-profile-engine",className:"settings-select",value:Nt.engine,onChange:A=>dt(ie=>({...ie,engine:A.target.value})),children:[s.jsx("option",{value:"chrome",children:a("settings.skillOfficeBrowserProfileEngineChrome")}),s.jsx("option",{value:"edge",children:a("settings.skillOfficeBrowserProfileEngineEdge")})]})}),s.jsx(Ot,{label:a("settings.skillOfficeBrowserProfileModeLabel"),htmlFor:"browser-profile-mode",children:s.jsxs("select",{id:"browser-profile-mode",className:"settings-select",value:Nt.mode,onChange:A=>dt(ie=>({...ie,mode:A.target.value})),children:[s.jsx("option",{value:"persistent",children:a("settings.skillOfficeBrowserProfileModePersistent")}),s.jsx("option",{value:"cdp_attached",children:a("settings.skillOfficeBrowserProfileModeCdpAttached")})]})}),s.jsx(Ot,{label:a("settings.skillOfficeBrowserProfileScopeLabel"),htmlFor:"browser-profile-scope",children:s.jsxs("select",{id:"browser-profile-scope",className:"settings-select",value:Nt.ownershipScope,onChange:A=>dt(ie=>({...ie,ownershipScope:A.target.value})),children:[s.jsx("option",{value:"user",children:a("settings.skillOfficeBrowserProfileScopeUser")}),s.jsx("option",{value:"workspace",children:a("settings.skillOfficeBrowserProfileScopeWorkspace")}),s.jsx("option",{value:"target",children:a("settings.skillOfficeBrowserProfileScopeTarget")})]})}),Nt.mode==="cdp_attached"?s.jsx(Ot,{label:a("settings.skillOfficeBrowserProfileCdpEndpointLabel"),description:a("settings.skillOfficeBrowserProfileCdpEndpointDescription"),htmlFor:"browser-profile-cdp-endpoint",children:s.jsx("input",{id:"browser-profile-cdp-endpoint",className:"settings-text-input",value:Nt.cdpEndpoint,onChange:A=>dt(ie=>({...ie,cdpEndpoint:A.target.value}))})}):null,s.jsxs(Es,{children:[s.jsx("button",{className:"secondary-button",type:"button",onClick:()=>{$e(!1),dt(ac(r))},children:a("common.cancel")}),s.jsx("button",{className:"primary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{Un()},children:Ce==="browser-profile-submit"?a("common.loading"):a("settings.skillOfficeBrowserProfileSaveAction")})]})]})}),s.jsx(ln,{open:ot,title:a("settings.skillOfficeBrowserProfileTaskModalTitle",{profileName:(xe==null?void 0:xe.displayName)??"-"}),description:a("settings.skillOfficeBrowserProfileTaskModalDescription"),className:"settings-skill-detail-modal",onClose:()=>{jt(!1),le(null),de(null)},children:s.jsx(Jn,{heading:a("settings.skillOfficeBrowserProfileTaskListTitle"),description:xe?a("settings.skillOfficeBrowserProfileTaskListDescription",{workspaceName:Fg(xe.workspaceId,is)}):void 0,children:fn.length===0?s.jsx($i,{title:a("settings.skillOfficeBrowserProfileTaskEmpty"),compact:!0}):s.jsx(Wi,{children:fn.map(A=>{const ie=j[A.id]??null,tt=(M==null?void 0:M.task.id)===A.id;return s.jsxs(rs,{className:"settings-browser-task-list-item",label:A.title,description:a("settings.skillOfficeBrowserInstanceListMeta",{profileName:(xe==null?void 0:xe.displayName)??"-",status:_g(ie,A.status),risk:A.riskLevel}),trailing:s.jsxs("div",{className:"settings-skill-entry-actions settings-browser-task-list-item-actions",children:[s.jsx("span",{className:"settings-skill-entry-meta",children:rA(A.createdAt)}),s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{Zn(A.id)},children:Ce===`browser-task-detail:${A.id}`?a("common.loading"):a("settings.skillOfficeBrowserInstanceDetailAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null||!nA(A.status),onClick:()=>{es(A.id)},children:Ce===`browser-task-execute:${A.id}`?a("common.loading"):a("settings.skillOfficeBrowserInstanceExecuteAction")}),s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null||!sA(ie),onClick:()=>{os(A.id)},children:Ce===`browser-task-cancel:${A.id}`?a("common.loading"):a("settings.skillOfficeBrowserInstanceCancelAction")})]}),children:[s.jsxs("div",{className:"settings-skill-tags",children:[s.jsx("span",{className:"settings-skill-tag","data-status":zg(A.status),children:A.status}),s.jsx("span",{className:"settings-skill-tag","data-status":Z1(kg(A)),children:X1(kg(A))}),s.jsx("span",{className:"settings-skill-tag","data-status":tA(ie),children:_g(ie,A.status)})]}),tt?s.jsxs("div",{className:"settings-skill-entry-meta",children:[s.jsx("p",{children:ie?a("settings.skillOfficeBrowserInstanceSnapshotMeta",{status:Ow(ie.status),attempt:ie.attempt,startedAt:Ug(ie.startedAt),finishedAt:Ug(ie.finishedAt)}):a("settings.skillOfficeBrowserInstanceSnapshotPending")}),M.steps.map(Pt=>s.jsxs("p",{children:[Pt.title," · ",Pt.status]},Pt.id))]}):null]},A.id)})})})}),s.jsx(ln,{open:Ve,title:a("settings.skillOfficeBrowserProfileOptionsModalTitle",{profileName:(U==null?void 0:U.displayName)??"-"}),description:a("settings.skillOfficeBrowserProfileOptionsModalDescription"),className:"settings-skill-create-modal",onClose:()=>{G(!1),he(null)},children:s.jsxs(Jn,{heading:a("settings.skillOfficeBrowserProfileOptionsSectionTitle"),children:[s.jsx(Ot,{label:a("settings.skillOfficeBrowserProfileCrossWorkspaceFieldLabel"),description:a("settings.skillOfficeBrowserProfileCrossWorkspaceFieldDescription"),children:s.jsx("div",{className:"settings-skill-entry-actions settings-browser-profile-entry-actions",children:s.jsx("button",{className:"secondary-button",type:"button",disabled:!U||Be||Ce!==null||!J1(U),onClick:()=>{U&&as(U)},children:U&&Ce===`browser-profile-scope:${U.id}`?a("common.loading"):(U==null?void 0:U.ownershipScope)==="user"?a("settings.skillOfficeBrowserProfileSetWorkspaceOnlyAction"):a("settings.skillOfficeBrowserProfileAllowCrossWorkspaceAction")})})}),s.jsx(Es,{children:s.jsx("button",{className:"secondary-button",type:"button",onClick:()=>{G(!1),he(null)},children:a("common.close")})})]})}),s.jsx(ln,{open:ve,title:a("settings.skillOfficeBrowserProfileDeleteModalTitle"),description:a("settings.skillOfficeBrowserProfileDeleteModalDescription"),className:"settings-skill-create-modal",onClose:()=>{_e(!1),I(null)},children:s.jsxs(Jn,{heading:(X==null?void 0:X.displayName)??"-",children:[s.jsx("p",{className:"settings-skill-entry-meta",children:a("settings.skillOfficeBrowserProfileDeleteModalWarning")}),s.jsxs(Es,{children:[s.jsx("button",{className:"secondary-button",type:"button",onClick:()=>{_e(!1),I(null)},children:a("common.cancel")}),s.jsx("button",{className:"settings-button-danger",type:"button",disabled:!X||Be||Ce!==null,onClick:()=>{At()},children:X&&Ce===`browser-profile-delete:${X.id}`?a("common.loading"):a("settings.skillOfficeBrowserProfileDeleteConfirmAction")})]})]})}),s.jsx(ln,{open:nt,title:a("settings.skillOpsTargetModalTitle"),description:a("settings.skillOpsTargetModalDescription"),className:"settings-skill-create-modal",onClose:()=>{et(!1),en(ic())},children:s.jsxs(Jn,{heading:a("settings.skillOpsTargetFormTitle"),description:a("settings.skillOpsTargetFormDescription"),children:[s.jsx("p",{className:"settings-skill-entry-meta",children:a("settings.skillOpsPasswordNotice")}),s.jsx(Ot,{label:a("settings.skillOpsTargetNameLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.displayName,onChange:A=>en(ie=>({...ie,displayName:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetEnvironmentLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.environment,onChange:A=>en(ie=>({...ie,environment:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetHostLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.host,onChange:A=>en(ie=>({...ie,host:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetPortLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.port,onChange:A=>en(ie=>({...ie,port:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetUsernameLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.username,onChange:A=>en(ie=>({...ie,username:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetPrivateKeyPathLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.privateKeyPath,onChange:A=>en(ie=>({...ie,privateKeyPath:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetKnownHostsPathLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.knownHostsPath,onChange:A=>en(ie=>({...ie,knownHostsPath:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetJumpHostLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.jumpHost,onChange:A=>en(ie=>({...ie,jumpHost:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetWorkspacePathLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.workspacePath,onChange:A=>en(ie=>({...ie,workspacePath:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetCredentialRefLabel"),children:s.jsx("input",{className:"settings-text-input",value:ft.credentialRef,onChange:A=>en(ie=>({...ie,credentialRef:A.target.value}))})}),s.jsx(Ot,{label:a("settings.skillOpsTargetHostKeyPolicyLabel"),children:s.jsxs("select",{className:"settings-select",value:ft.strictHostKeyChecking,onChange:A=>en(ie=>({...ie,strictHostKeyChecking:A.target.value})),children:[s.jsx("option",{value:"accept-new",children:"accept-new"}),s.jsx("option",{value:"yes",children:"yes"}),s.jsx("option",{value:"no",children:"no"})]})}),s.jsxs(Es,{children:[s.jsx("button",{className:"secondary-button",type:"button",onClick:hs,children:a("settings.skillOpsTargetResetAction")}),s.jsx("button",{className:"primary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{cr()},children:Ce==="ops-target-submit"?a("common.loading"):a("settings.skillOpsTargetSaveAction")})]})]})}),s.jsxs(ln,{open:_t,title:a("settings.skillWorkspaceSessionMcpModalTitle"),description:a("settings.skillWorkspaceSessionMcpModalDescription"),className:"settings-skill-create-modal",onClose:()=>{xt(!1),It(null)},children:[s.jsx(Jn,{heading:a("settings.skillWorkspaceSessionMcpRuntimeTitle"),description:a("settings.skillWorkspaceSessionMcpRuntimeDescription"),children:$t?s.jsx("div",{className:"settings-skill-empty",children:a("settings.skillWorkspaceSessionMcpLoading")}):rt?s.jsxs("div",{className:"settings-skill-entry-list",children:[s.jsxs("div",{className:"settings-skill-summary-grid",children:[s.jsx(nr,{label:a("settings.skillWorkspaceSessionMcpOverallLabel"),value:(Ie==null?void 0:Ie.overallState)==="ready"?a("settings.skillWorkspaceSessionMcpStateReady"):(Ie==null?void 0:Ie.overallState)==="partial"?a("settings.skillWorkspaceSessionMcpStatePartial"):a("settings.skillWorkspaceSessionMcpStateMissing")}),s.jsx(nr,{label:a("settings.skillWorkspaceSessionMcpCurrentSessionLabel"),value:Ie!=null&&Ie.currentSessionReady?a("settings.skillWorkspaceSessionMcpStateReady"):a("settings.skillWorkspaceSessionMcpStateMissing")}),s.jsx(nr,{label:a("settings.skillWorkspaceSessionMcpCodexLabel"),value:(Ie==null?void 0:Ie.codexState)==="ready"?a("settings.skillWorkspaceSessionMcpStateReady"):(Ie==null?void 0:Ie.codexState)==="partial"?a("settings.skillWorkspaceSessionMcpStatePartial"):a("settings.skillWorkspaceSessionMcpStateMissing")})]}),s.jsxs(Wi,{children:[s.jsx(rs,{label:a("settings.skillWorkspaceSessionMcpRuntimeTitle"),description:(Ie==null?void 0:Ie.currentSessionDetail)??a("settings.skillWorkspaceSessionMcpValueMissing"),trailing:To(Ie!=null&&Ie.currentSessionReady?"ready":"missing")}),s.jsx(rs,{label:"Codex",description:(Ie==null?void 0:Ie.codexDetail)??a("settings.skillWorkspaceSessionMcpValueMissing"),trailing:To((Ie==null?void 0:Ie.codexState)??"missing")}),s.jsx(rs,{label:a("settings.skillWorkspaceSessionMcpGlobalCodingnsLabel"),description:(Ie==null?void 0:Ie.globalCodingnsDetail)??a("settings.skillWorkspaceSessionMcpValueMissing"),trailing:To((Ie==null?void 0:Ie.globalCodingnsState)??"missing")})]})]}):s.jsx($i,{title:a("settings.skillWorkspaceSessionMcpEmptyTitle"),description:we??a("settings.skillWorkspaceSessionMcpEmptyDescription"),compact:!0})}),s.jsx(Jn,{heading:a("settings.skillWorkspaceSessionMcpCommandTitle"),description:a("settings.skillWorkspaceSessionMcpCommandDescription"),children:rt?s.jsxs(Wi,{children:[s.jsx(rs,{label:a("settings.skillWorkspaceSessionMcpBrowserBridgeLabel"),description:a("settings.skillWorkspaceSessionMcpBrowserBridgeDetail"),trailing:To("ready")}),s.jsx(rs,{label:a("settings.skillWorkspaceSessionMcpRecommendedPathLabel"),description:(Ie==null?void 0:Ie.recommendedPath)??a("settings.skillWorkspaceSessionMcpValueMissing"),trailing:To("ready")})]}):null}),s.jsx(Es,{children:s.jsx("button",{className:"secondary-button",type:"button",disabled:!(r!=null&&r.trim())||$t,onClick:()=>{jn()},children:$t?a("common.loading"):a("settings.skillWorkspaceSessionMcpRefreshAction")})})]}),s.jsx(ln,{open:fe,title:a("settings.skillCreateModalTitle"),description:a("settings.skillCreateModalDescription"),className:"settings-skill-create-modal",onClose:Xs,children:s.jsxs("section",{className:"settings-skill-section",children:[s.jsx("h3",{className:"settings-skill-section-title",children:a("settings.skillUploadSectionTitle")}),s.jsx("p",{className:"settings-skill-section-description",children:a("settings.skillUploadSectionDescription")}),s.jsxs("div",{className:"settings-skill-create-panel",children:[s.jsx("input",{ref:f,type:"file",accept:".md,text/markdown,text/plain",className:"settings-skill-upload-input",onChange:A=>{$s(A)}}),s.jsx("div",{className:"settings-model-tabs",role:"tablist","aria-label":a("settings.skillCreateSourceTabsLabel"),children:$1.map(A=>{const ie=vt===A;return s.jsx("button",{type:"button",role:"tab",className:"settings-model-tab","aria-selected":ie,"data-active":ie?"true":"false",onClick:()=>ns(A),children:H1(A)},A)})}),s.jsx("div",{className:"settings-skill-upload-targets",role:"radiogroup","aria-label":a("settings.skillUploadScopeLabel"),children:W1.map(A=>s.jsxs("label",{className:"settings-skill-upload-target","data-selected":J===A?"true":"false",children:[s.jsx("input",{type:"radio",name:"skill-upload-scope",checked:J===A,onChange:()=>nn(A)}),s.jsx("span",{children:z1(A)})]},A))}),vt==="file"?s.jsx("div",{className:"settings-skill-create-toolbar",children:s.jsx("button",{className:"secondary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{var A;(A=f.current)==null||A.click()},children:a("settings.skillUploadPickAction")})}):s.jsxs("label",{className:"settings-skill-upload-field",children:[s.jsx("span",{children:a("settings.skillPasteLabel")}),s.jsx("textarea",{className:"settings-skill-create-textarea",value:ze,onChange:A=>st(A.target.value),placeholder:a("settings.skillPastePlaceholder")})]}),On?s.jsx("div",{className:"settings-skill-entry",children:s.jsxs("div",{className:"settings-skill-entry-main",children:[s.jsx("strong",{className:"settings-skill-entry-title",children:On.previewTitle}),s.jsxs("p",{className:"settings-skill-entry-meta",children:[a("settings.skillUploadPickedFile"),": ",On.fileName]})]})}):s.jsx("div",{className:"settings-skill-empty",children:vt==="paste"?a("settings.skillPasteEmpty"):a("settings.skillUploadEmpty")}),s.jsxs("div",{className:"settings-skill-upload-field",children:[s.jsx("span",{children:a("settings.skillUploadTargetsLabel")}),s.jsx("div",{className:"settings-skill-upload-targets",children:fu(J).map(A=>s.jsxs("label",{className:"settings-skill-upload-target","data-selected":q[A]?"true":"false",children:[s.jsx("input",{type:"checkbox",checked:q[A],disabled:!Vs(A,Bt),onChange:()=>ss(A)}),s.jsx("span",{children:Vs(A,Bt)?yr(A):`${yr(A)} · ${a("settings.skillTargetDisabledTag")}`})]},A))})]}),On!=null&&On.notes.length?s.jsx("div",{className:"settings-skill-tags",children:On.notes.map((A,ie)=>s.jsx("span",{className:"settings-skill-tag","data-status":"pending",children:A},`${On.fileName}:${ie}`))}):null,we?s.jsx("p",{className:"settings-release-status",children:we}):null,s.jsx("div",{className:"settings-skill-create-actions",children:s.jsx("button",{className:"primary-button",type:"button",disabled:Be||Ce!==null,onClick:()=>{Vt()},children:Ce==="upload"?a("common.loading"):a("settings.skillCreateSubmitAction")})})]})]})})]})}function Ur({title:e,description:t,headerExtra:n,emptyText:r,items:i,renderItem:o}){return s.jsxs("section",{className:"settings-skill-section",children:[s.jsxs("div",{className:"settings-skill-section-header",children:[s.jsx("h3",{className:"settings-skill-section-title",children:e}),n?s.jsx("div",{className:"settings-skill-section-extra",children:n}):null]}),t?s.jsx("p",{className:"settings-skill-section-description",children:t}):null,i.length>0?s.jsx("div",{className:"settings-skill-entry-list",children:i.map((l,c)=>s.jsx(d.Fragment,{children:o(l)},c))}):s.jsx("div",{className:"settings-skill-empty",children:r})]})}function nr({label:e,value:t}){return s.jsxs("div",{className:"settings-skill-summary-card",children:[s.jsx("span",{children:e}),s.jsx("strong",{children:t})]})}function Lg(e){return`import:${e.targetCli}:${e.directoryPath}`}function Dg(e){return`sync:${e}`}const _1=["codex","claude-code","gemini","opencode"],B1=["codex","claude-code"],W1=["workspace","assistant"],$1=["file","paste"];function fs(e){return e instanceof rr?e.message||a("settings.skillLoadFailed"):e instanceof Error?e.message:a("settings.skillLoadFailed")}function yr(e){switch(e){case"claude-code":return a("settings.skillTargetClaudeCode");case"gemini":return a("settings.skillTargetGemini");case"opencode":return a("settings.skillTargetOpenCode");default:return a("settings.skillTargetCodex")}}function z1(e){return e==="assistant"?a("settings.skillUploadScopeAssistant"):a("settings.skillUploadScopeWorkspace")}function H1(e){return e==="paste"?a("settings.skillCreateSourcePaste"):a("settings.skillCreateSourceFile")}function U1(e){switch(e){case"office":return a("settings.skillConfigTabOffice");case"ops":return a("settings.skillConfigTabOps");case"opencli":return a("settings.skillConfigTabOpenCli");default:return a("settings.skillConfigTabSkills")}}function No(e,t={}){const r=fu(e).filter(i=>Vs(i,t))[0]??null;return{codex:r==="codex","claude-code":r==="claude-code",gemini:r==="gemini",opencode:r==="opencode"}}function fu(e){return e==="assistant"?B1:_1}function ic(){return{targetId:null,displayName:"",environment:"",host:"",port:"22",username:"",privateKeyPath:"",knownHostsPath:"",jumpHost:"",workspacePath:"",credentialRef:"",strictHostKeyChecking:"accept-new",status:"active"}}function ac(e){return{displayName:"",engine:"chrome",mode:"persistent",ownershipScope:e!=null&&e.trim()?"workspace":"user",cdpEndpoint:""}}function oc(){return{fileName:"",fileContentBase64:""}}function lc(e){return{enabled:(e==null?void 0:e.enabled)??!1,serverUrl:(e==null?void 0:e.serverUrl)??"",publicBaseUrl:(e==null?void 0:e.publicBaseUrl)??"",callbackBaseUrl:(e==null?void 0:e.callbackBaseUrl)??"",userDisplayName:(e==null?void 0:e.userDisplayName)??"",userAvatarUrl:(e==null?void 0:e.userAvatarUrl)??"",jwtSecret:"",clearJwtSecret:!1}}function Lw(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Ei(e){return typeof e=="string"?e:""}function Dw(e,t){return typeof e=="number"&&Number.isFinite(e)?String(e):String(t)}function q1(e){return e==="yes"||e==="no"||e==="accept-new"?e:"accept-new"}function Og(e){return e==="edge"?a("settings.skillOfficeBrowserProfileEngineEdge"):a("settings.skillOfficeBrowserProfileEngineChrome")}function V1(e){return e==="cdp_attached"?a("settings.skillOfficeBrowserProfileModeCdpAttached"):a("settings.skillOfficeBrowserProfileModePersistent")}function K1(e){switch(e){case"workspace":return a("settings.skillOfficeBrowserProfileScopeWorkspace");case"target":return a("settings.skillOfficeBrowserProfileScopeTarget");default:return a("settings.skillOfficeBrowserProfileScopeUser")}}function G1(e){switch(e){case"locked":return a("settings.skillOfficeBrowserProfileStatusLocked");case"archived":return a("settings.skillOfficeBrowserProfileStatusArchived");case"error":return a("settings.skillOfficeBrowserProfileStatusError");default:return a("settings.skillOfficeBrowserProfileStatusActive")}}function Y1(e){switch(e){case"locked":return"pending";case"archived":case"error":return"failed";default:return"synced"}}function Fg(e,t){var n;return e!=null&&e.trim()?((n=t.get(e))==null?void 0:n.name)??a("settings.skillOfficeBrowserProfileWorkspaceUnknown"):a("settings.skillOfficeBrowserProfileWorkspaceUnbound")}function J1(e){var t;return e.ownershipScope==="user"?!!((t=e.workspaceId)!=null&&t.trim()):!0}function _g(e,t){return e?Ow(e.status):t==="succeeded"?a("settings.skillOfficeBrowserInstanceExecutionSucceeded"):t==="failed"?a("settings.skillOfficeBrowserInstanceExecutionFailed"):t==="cancelled"?a("settings.skillOfficeBrowserInstanceExecutionCancelled"):a("settings.skillOfficeBrowserInstanceExecutionIdle")}function Ow(e){switch(e){case"queued":return a("settings.skillOfficeBrowserInstanceExecutionQueued");case"running":return a("settings.skillOfficeBrowserInstanceExecutionRunning");case"succeeded":return a("settings.skillOfficeBrowserInstanceExecutionSucceeded");case"failed":return a("settings.skillOfficeBrowserInstanceExecutionFailed");case"cancelled":return a("settings.skillOfficeBrowserInstanceExecutionCancelled");default:return a("settings.skillOfficeBrowserInstanceExecutionTimeout")}}function X1(e){return e==="opencli_bridge"?a("settings.skillOfficeBrowserExecutionBackendOpenCliBridge"):a("settings.skillOfficeBrowserExecutionBackendPlaywright")}function Ld(e){switch(e==null?void 0:e.state){case"ready":return a("settings.skillOnlyOfficeStatusReady");case"warning":return a("settings.skillOnlyOfficeStatusWarning");case"error":return a("settings.skillOnlyOfficeStatusError");case"misconfigured":return a("settings.skillOnlyOfficeStatusMisconfigured");case"disabled":return a("settings.skillOnlyOfficeStatusDisabled");default:return a("settings.skillOnlyOfficeStatusUnknown")}}function Bg(e){switch(e){case"pass":return a("settings.skillOnlyOfficeCheckPass");case"warn":return a("settings.skillOnlyOfficeCheckWarn");case"fail":return a("settings.skillOnlyOfficeCheckFail");case"skip":default:return a("settings.skillOnlyOfficeCheckSkip")}}function Wg(e){switch(e){case"pass":return"synced";case"warn":return"pending";case"fail":return"failed";case"skip":default:return"assistant-runtime"}}function Q1(e){switch(e){case"ready":return"synced";case"error":return"failed";case"warning":case"misconfigured":return"pending";case"disabled":default:return"assistant-runtime"}}function Z1(e){return e==="opencli_bridge"?"pending":"synced"}function $g(e){if(!e)return a("settings.skillOfficeBrowserBridgeAvailabilityUnknown");switch(e.availability){case"ready":return a("settings.skillOfficeBrowserBridgeAvailabilityReady");case"daemon_missing":return a("settings.skillOfficeBrowserBridgeAvailabilityDaemonMissing");case"extension_missing":return a("settings.skillOfficeBrowserBridgeAvailabilityExtensionMissing");default:return a("settings.skillOfficeBrowserBridgeAvailabilityUnavailable")}}function eA(e){if(!e)return"conflicted";switch(e.availability){case"ready":return"synced";case"daemon_missing":case"extension_missing":return"pending";default:return"failed"}}function tA(e){if(!e)return"conflicted";switch(e.status){case"queued":case"running":return"pending";case"succeeded":return"synced";case"failed":case"cancelled":case"timeout":return"failed";default:return"conflicted"}}function nA(e){return e==="ready"||e==="failed"}function sA(e){return(e==null?void 0:e.status)==="queued"||(e==null?void 0:e.status)==="running"}function rA(e){return new Date(e).toLocaleString("zh-CN",{hour12:!1})}function zg(e){return e==="ready"||e==="running"||e==="succeeded"?"synced":e==="pending_approval"||e==="waiting_external"||e==="paused"?"pending":e==="failed"||e==="cancelled"||e==="rolled_back"?"failed":"conflicted"}function iA(e){var l;const t=Lw(e.configJson),n=Ei(t.host),r=Ei(t.username),i=Dw(t.port,22);return[(l=e.environment)==null?void 0:l.trim(),`${r}@${n}:${i}`].filter(c=>c&&c.trim().length>0).join(" · ")}function To(e){const t=e==="ready"?"synced":e==="partial"?"pending":"failed",n=e==="ready"?a("settings.skillWorkspaceSessionMcpStateReady"):e==="partial"?a("settings.skillWorkspaceSessionMcpStatePartial"):a("settings.skillWorkspaceSessionMcpStateMissing");return s.jsx("span",{className:"settings-skill-tag","data-status":t,children:n})}function Hg({sourceMode:e,fileDraft:t,pastedMarkdown:n}){return e==="file"?t:n.trim()?Bw(jA(n),n):null}function aA(e){switch(e){case"conflicted":return a("settings.skillBindingConflicted");case"failed":return a("settings.skillBindingFailed");case"pending":return a("settings.skillBindingPending");default:return a("settings.skillBindingSynced")}}function oA(e){const t={};for(const n of e){const r=lA(n.provider);r&&(t[r]=n)}return t}function lA(e){switch(e){case"claude-code":return"claude-code";case"codex":return"codex";case"gemini":return"gemini";case"opencode":return"opencode";default:return null}}function Vs(e,t){var n;return((n=t[e])==null?void 0:n.enabled)!==!1}function cA(e,t){return e.some(n=>n.enabled&&Vs(n.targetCli,t))}function uA(e,t){return Vs(e.targetCli,t)?e.syncStatus:"failed"}function dA(e,t){return Vs(e.targetCli,t)?`${yr(e.targetCli)} · ${aA(e.syncStatus)}`:`${yr(e.targetCli)} · ${a("settings.skillTargetDisabledTag")}`}function Fw(e){return e.map(yr).join(" / ")}function fA(e){const t=e.filter(n=>n.enabled);return t.length===0?a("settings.skillManagedItemNoTarget"):a("settings.skillManagedItemDescription",{targets:Fw(t.map(n=>n.targetCli))})}function hA(e,t){return Vs(e.targetCli,t)?a("settings.skillUnmanagedItemDescription",{target:yr(e.targetCli)}):a("settings.skillUnmanagedItemDisabledDescription",{target:yr(e.targetCli)})}function mA(e,t){return Vs(e.targetCli,t)?a("settings.skillConflictedItemDescription",{target:yr(e.targetCli)}):a("settings.skillConflictedItemDisabledDescription",{target:yr(e.targetCli)})}function pA(e,t){return e.some(r=>r.enabled)?a("settings.skillSyncTargetDisabled"):a("settings.skillSyncTargetMissing")}function gA(e,t){return fu(e).some(r=>Vs(r,t))?a("settings.skillUploadTargetRequired"):a("settings.skillUploadTargetDisabled")}function bA(e){const t=yr(e.targetCli);switch(e.code){case"SKILL_TARGET_ROOT_MISSING":return{title:a("settings.skillDiagnosticTargetMissingTitle",{target:t}),detail:a("settings.skillDiagnosticTargetMissingDetail",{target:t})};case"SKILL_TARGET_ROOT_INVALID":case"SKILL_TARGET_STAT_FAILED":case"SKILL_TARGET_READ_FAILED":return{title:a("settings.skillDiagnosticReadFailedTitle",{target:t}),detail:a("settings.skillDiagnosticReadFailedDetail",{target:t})};case"SKILL_TARGET_SKILL_MISSING":return{title:a("settings.skillDiagnosticSyncMissingTitle",{target:t}),detail:a("settings.skillDiagnosticSyncMissingDetail",{target:t})};default:return{title:a("settings.skillDiagnosticGenericTitle",{target:t}),detail:a("settings.skillDiagnosticGenericDetail",{target:t})}}}function yA(e){if(!e)return"-";const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toLocaleString()}function Ug(e){return e===null?"-":new Date(e).toLocaleString()}async function qg(e){const t=await Promise.all(e.map(async n=>[n.id,await uh(n.id)]));return Object.fromEntries(t)}function xA(e,t,n){if(e.length>0)return e.map(i=>({name:i.name,directoryName:i.directoryName,sourcePath:i.sourcePath,usedByTargetCli:i.usedByTargetCli,usageTag:Dd(i.directoryName)}));const r=new Map;for(const i of t)_w(i,n)&&r.set(Vg(i.targetCli,i.directoryPath),{name:i.name,directoryName:i.directoryName,sourcePath:i.directoryPath,usedByTargetCli:[i.targetCli],usageTag:Dd(i.directoryName)});for(const i of n){if(!Al(i))continue;const o=i.directoryPath??i.rootDir,l=Vg(i.targetCli,o);r.has(l)||r.set(l,{name:i.directoryName??"codingns-assistant",directoryName:i.directoryName??"codingns-assistant",sourcePath:o,usedByTargetCli:[i.targetCli],usageTag:Dd(i.directoryName??"codingns-assistant")})}return[...r.values()]}function Vg(e,t){return`${e}:${t}`}function _w(e,t){return t.some(n=>Al(n)&&n.targetCli===e.targetCli&&n.directoryPath===e.directoryPath&&n.directoryName===e.directoryName)}function Al(e){return e.code==="SKILL_RESERVED_FOR_ASSISTANT_RUNTIME"}function Dd(e){return e==="codingns-workspace-session"?"workspace-session":"assistant-only"}function kA(e){return e==="workspace-session"?a("settings.skillTagWorkspaceSessionOnly"):a("settings.skillTagAssistantOnly")}function wA(e,t){return t.find(r=>Al(r)&&r.targetCli===e.targetCli&&r.directoryName===e.directoryName&&r.directoryPath===e.directoryPath)?[{key:`assistant-runtime:${e.targetCli}:${e.directoryPath}`,label:a("settings.skillTagAssistantOnly"),status:"assistant-runtime"}]:[]}function vA(e){return Al(e)?[{key:`assistant-runtime:${e.targetCli}:${e.directoryPath??e.rootDir}`,label:a("settings.skillTagAssistantOnly"),status:"assistant-runtime"}]:[]}function Bw(e,t){const n=[],r=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
6
+ `).trim();if(!r)throw new Error(a("settings.skillUploadContentEmpty"));r!==t.trim()&&n.push(a("settings.skillUploadNormalizedNote"));const i=Ww(r),o=fh(e)??fh(i)??"";return o||n.push(a("settings.skillUploadDirectoryRequiredNote")),i||n.push(a("settings.skillUploadHeadingNote")),{fileName:e,rawContent:r,directoryName:o,previewTitle:i||NA(o||"skill"),notes:n}}async function SA(e){if(typeof e.text=="function")return await e.text();if(typeof FileReader>"u")throw new Error(a("settings.skillUploadReadFailed"));return await new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>{n(r.error??new Error(a("settings.skillUploadReadFailed")))},r.onload=()=>{if(typeof r.result=="string"){t(r.result);return}n(new Error(a("settings.skillUploadReadFailed")))},r.readAsText(e)})}async function CA(e){if(typeof e.arrayBuffer=="function"){const t=await e.arrayBuffer();return Kg(new Uint8Array(t))}if(typeof FileReader>"u")throw new Error(a("settings.skillUploadReadFailed"));return await new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>{n(r.error??new Error(a("settings.skillUploadReadFailed")))},r.onload=()=>{if(r.result instanceof ArrayBuffer){t(Kg(new Uint8Array(r.result)));return}n(new Error(a("settings.skillUploadReadFailed")))},r.readAsArrayBuffer(e)})}function Kg(e){let t="";return e.forEach(n=>{t+=String.fromCharCode(n)}),btoa(t)}function fh(e){const r=(e.replace(/\\/g,"/").split("/").pop()??e).replace(/\.[A-Za-z0-9]+$/,"").trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-._]+|[-._]+$/g,"").toLowerCase();return r.length>0?r:null}function jA(e){const t=fh(Ww(e));return t?`${t}.md`:"pasted-skill.md"}function Ww(e){var t,n;return((n=(t=e.match(/^#\s+(.+)$/m))==null?void 0:t[1])==null?void 0:n.trim())??""}function NA(e){return e.split(/[._-]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")||e}const TA="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAF+0lEQVRYha2XbXBUZxXHf+e5u4SkCZjg0NIWnQLJLgRF5UWnL75MP9gMjqPT2eyC0qlMiYxOUAR206LOyhiSTVscp52O0xamWgu7WTp0qLUz6kht6Qed1L7M5GUTsAoDTRSIJJos2b33+GFfWMJuNqmcT/c595z/+d3nOc+9zxXKWE9Li7tm0fjyqmT6H0t/Fp8sFz9XM+UCauouH8Rx+ifmWWdP7Q0sLRbT98g3lySC/mcSQd+GGwrQt2vzx1G2ZEa6KJ3S1mJxlpOKIDyEmEM3FGCk5vw5YCw3FmFbb9hXfV2gcm/26vINBfhS+LU0qgcKXB9xT1hbr6kdDhtgcYaDxHSNwVBg92Ao0DMY8n97zgAAZnK8U2AoX1D0++rzWfkC44k6wAVghP7C3EQo8Iiijyq61oEDiV2bPjojwKk234pEsPnh/lDgzpyv/olXrwi6qyDsjsQy2ZQXmJdefPWWvp0v3uZ/CLQ9NxZINpxJj84IYDvmOUT2G/T1DD0CUB/pflnhd1eT5Mcnwl90Adi23JzPl9TbAEN7fF9AeapQW5AOicftGQFEOJ+9tEDbB9v8x99r21wLYBlnJ5AGUKhfklz8QEbY3J71nVnZceziUPAbtzvGxAB3wdPH6yPRx6cXvw4gbbm/B5zIO5SvVKjdMxAMrKvviPcpHMyLqvyoN+ybh7AUwIi+M9TaVOGI/SJwc4Fsf6rS2SqgxQBkukPDYTM40RdCZB/Z5gKmEGmzjStq2alBoDqbvF2hEWgF9oEuAvlugdx/Deaz9ZEjvcWKFwXIWaLNv14cDqmwugDvFRVOi8qOrOMdhT6BzQhvoNxzjbjItxo6o8+VqjEjAMBQa1OFXbXwh4KGuLqmDleXToHzwG1FpLs9kah/uvf98IPz08nkSuZbp+vDL4zNCJAHaQt82lH9JfCJ2cQrTFjq8hiZGrfVtQGcDQhrFNYAywELuFw15SwRgN6dvrrahcnkreGXJ0pCtDZVOFULwsCerEBJExhVGAY8FH/Z2cBvPJHY1ySx13cbaXMaqACSwCVRLqlhVNBRVTOm4lxCOSdqPkB0FdA2m5kosGGEHpC3UP2z6uRJb9fx8SwsJEL+nwBNwEKgWqBSoXaORQqtH+VNhDdErJMNnYf/ViqwbBNO3lRbVZFSS9yyIG1jucRuVuGnM6TZZL4d/wS9KEgawIH/gF5EzAWBvzecto9KPG7PqgkBTu0NLHVs7VBlcxnwS8ALgtyp6Kco3S9/OF850lQWYCD41RpMZUiUH5BZmgkRDqmyVaCqeJYeS1dqwJq4UoG56S5w7hb4PMp6YH426LJR1+qSAOrzWYPLZCvIPuAWAIHXxGGXY3geWAV6DOTrJRR+r5q8P9dskNtJ1etBVl4R19FPdh4eLQowEPR5RKxfgebOeGMqGvLMX/V0YrK/W+B+4ATCYZRnEJ5E+Q5gFM4AFwQ+I8hbLks2Ltt/ZKTUg163Rwfamrcj5q/54spvLZes9nZ2/yIx0b8jW/wCLmeLOLoCAEdeAjmYnaWPGXga9Jiia1O28+bAbt8dswJQEFF5IrO2chGVBzxdsY0r2qNnBx5uvkuELkAFedDTHj+nIl4AIzJsjL2XTAOisB+XtqryKLBcLHNyKLSpsSyAgKrKJoRtbksaPV3R5yFz7BaHOOBGOdAQib6SRV4L4KQZqe+I/wvYmZWqE1ue8nbFggjbgDoH/VOxY3vZXdDT0uKuqR37I+jdIH9JV9r3NIbjU717fLe4jPkASDVEYhW5730i2PwqIvdlZkK3eCPdv06E/GuAbmCBJxJbUnIGill13b8fyxRnRG070BiOTwG4MeuyszBSeNiw3KZFYDTzdPLzU7u3LPZEYu+qTq5Tlev+K2YESAQD94rKjqzgl72Pxd/P3VNLsgAyXJizoj161kG3Z4d1aZP6HIC36/i4tyt6dE4AasQNDIhxNnoisXevvZndJcLw9DxvpLsb5XGE9yzD2ZlqzPpVPN0SIf854FaUZz1dsW0fVqdsD5Q05Qhgg7z+oTX+Xyv2pzNX+x+eTlGviPgh3AAAAABJRU5ErkJggg==",IA="/assets/legna-code-6TqgZ4Ls.png",$w="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAbGSURBVHgBzZo/bBtVHMd/ZzuJA0gYCYlsOFO7xRFDy1R3olucqd0SJtiSjiCknBckpjZjBxRn7BR3owOqs5Wp7tZKoDgSQysh4UqUOCG2eZ/3/Oznv/fObqJ+pfPZd+/ufn++vz/vnQN5FwjbGZFGQSRYUb+yIu2c2tSxIOOMqpktqKpzz9X3ioSLNZkRgUwLhA4aW9KWvPqVl6mgldmVGZSJr0BX8Pb2gIVnRUltxbiKxFOgeLJzAYL3I5BQdhaL/sN9EJ5k1dADw+1LQU1tN328kYgaIMWzDSX4s0sUHmSVwZ5JeFqIGjhZgeKpokyzdKGUGQuyWOtA03YCxlNIC98K5X3AhLgYrYB2ndLeE5l0IFvXklK4mpRsxvyuvmqrrSX71aZUjlsyM4LkpuzM7w8dHhqoAxbO+9Fm63pSwhspLTSo1dt6n830bl1SStx9fK6/Z9LmWL3B1hZ/BHUl1+pgYI9S4Eh0EEVjJ5/SwiPI7m9Nuf+02SfUZi4pO+o8ynDcKmlRqRkPlZ43xQ+q8IXpVfdIsu88vJd2ZOSD/OcJKRXmtMW//PlMyi9a0jjvH5NZCDStEDydCjSlfvm9pa/hd24poc+zf/zH8PUjsCT57wOp/FjpqtQ9pakjR+KJo60Fbdnl3dMubSw4vrc2J/msSXLlF4ZCg+M4zzjGEzM39888aAWVFpYlZN+fRnfEE1iMh8JtVygsDWWefTOvhYMiCLX+8L8h4QHnVx+cas/klgLZvpb0eDrp9d/trjr609P6brbhgesPDXXA5kpS7t0ywYwVi4fERD8noJ1WfIDzBDYeRRw8GscL1gP5iCv0g7FsqAIX4UH9pHeegEb44uG5EuKsT3iuPbg9J08252VPxQ3CoowFGYlgRhEMEY2eFzp3CbbEQ3j28BnXjwI0CSvnXQu6lMJrnOd67qOV6fAf2HuuLPn2l4kbRgGT9yf2OU825o11lXDw+bgenb8LV5JdjwE8s/rAxMPXj0xMkGbxBkpWX8epCRp5WvuERNAHl9qADQ+j8xz0QuGDOz3rIizXW8/wHa7bzISSKAveNCQGGoVElPU3coaTcDQKhmoL3QxEkLMna2FplzKAOCFLGf6b4x+nJQbauURnHjsWWJQg8+1nsChCsZGh2LuUwTvb11J94zfVeVtPGOOej4CuNNlJI2xa9BUeQQaD3FKG83iAdItHClcSQ4rzLJvRohGsRCowqoexyCxKbNiUqVPrnf5MhBL0VKRTv6IWZCJnZJR4bujm7eprY+GD2/M6g/hZyypgKENGspThHha2fqxdjZ4sUg8iRz16aYLXBrN5SLPLa5tBMrGCT3T7wD0GgYcM1XwU0IWsXZ80wPY7WMpVguM2g0ABvMDmZhkXZox4w3dswvQV44FFSIe4vqT46rrbzSAEru1pXF6j1L2vTND6Us10p15Zr5Ywq2OTQRwUO0UMyiCM27PYDDKYLomRoy2VNq+n9HGfbGbvyzM9FWgd+4zMfWY4iaV1v6+assHCZNOl7XcKnUC0bUQ9osrq3qnTevgUTtZYUz4ecGEDDwtjaTYER8jsx0YAO5Gxc2EfyyP83lqq27b4Fc6gqhRolEXSe1FDrRBUZioslrYpkD3WthzHSyg0WNCIkVFeoNWw3S7UsQsAHqiobvQTgrgSNbL80gizdmU4EyEswsNzPMQxV3hqiO1oR3kDoyD87tOm57QStKusUNiUcigRXSlZQRchZW2qpc0Sdg5AbQDuw3XboDIQcwGAUm7uh3LWEPvPx88zRiNgWd5OaBr3o+oBrmeaCJhdDeZ7BB83kbETdjZ3bmzryii6eaDCR8c0PzUk/wOdTX7SFU//bEmg5EYoUiOCvv5H5NXbnuDffpHUGYoxLJN892uvarsgXXIPa/14SJTU+pBepXOWVf5W88yFI58VOWqBW9DAYNM3KQMRE0x4gO2JYmLZrtD1ItLTC3ooK2rKasdvzAIVwNp2PfTqpwmdWZY+CswMKzDeYZp579acNgDjodSLv+IK31JvcT4o218jlhYbM78LcJcUR8EG8xSWrynLL7sHZl7cnQQUoYKvLJn0eVwnHTenCVgxSSbwWNwF4cmm+owsbpeLxLqEC+WhoyPHhosl4Y3hewN4Pyw8mNzfhiehxFgzvRgg/IfhuLPRDXr4ljfwe5f/nkxz/m6HDWMR4zWrPBHPFx+zQ7/BX/d5zRrvRfeFU0pbfVcJHvpeMcVfDfAGby8TG/LO0BFc0vftiwtfzPBnD02rvFnZnrrwVUR3wvEFt5heARddZVDE/uXGjRdt4bru4UWODcfT5WmFdvE/Jeqz44iuBr4AAAAASUVORK5CYII=",AA="/assets/gemini-D4G1NbrE.png",RA="/assets/kimi-BWNNSh7e.png",PA="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAABzUlEQVR4AeycQQrCQBAEF1+g6J/0o5LPCXmCnnNx0E2nNqGEPciw024VffV0PZ/fHo7BqflBCSgAxd+aAhQAE4DjbYACYAJwvA1QAEwAjrcBCgAIDBRpA2AZClAATACOtwEKgAnA8TZAATABOD7egNc8tz2ftJ+4gPQD9r5fAbDBDQXALx00XgGwGAUoACYAx9sABcAE4HgboACYABxvAxSwJHC7XFryLNP4bzYg7KBar4CKUHiugDDgar0CKkLhuQLCgKv1CqgIhecKCAOu1iugIhSeKyAMuFqvgIpQeK6AMOBq/XAC7o9H6z5fdlRAtp4PJ2BrAHSeAmADClAATACOtwEKgAnA8TZAATABON4GKAAmAMev2AD4JTuNVwAsTgEKgAnA8TZAATABON4GKAAmAMfbAAXABOB4G9ApoPe6AnoJdt5XQCfA3uvDCXhOU0ueXmBr3x9OwNoPHH2fAmBDClAATACOtwEKgAnA8TZAAX8QONAVGwDLVIACYAJwfLwByf/+2WJ32k9cQPoBe9+vANigAhQAE4DjbYACYAJw/A8NgH/pQeMVAItVgAJgAnC8DVAATACOtwEKgAnA8TZAATABON4GFALS4w8AAAD//x7wkLQAAAAGSURBVAMAKj5LkLSa6SQAAAAASUVORK5CYII=",MA=new Set(["low","medium","high","xhigh"]),zw=["claude-code","codex","opencode","gemini","kimi","legna-code"],Dm=["codex","claude-code","opencode","gemini","kimi","legna-code"];function Gg(e){const t=new Set,n=[],r=[...Dm,...zw];for(const i of r)e.includes(i)&&(t.has(i)||(t.add(i),n.push(i)));for(const i of e)t.has(i)||(t.add(i),n.push(i));return n}const Hw={"claude-code":{displayNameKey:"conversation.providerClaude",fullDisplayNameKey:"shell.providerClaudeCode",draftTitleKey:"conversation.draftTitleClaude",defaultModelLabelKey:"conversation.modelUseCliDefault",icon:TA,defaultRunInputMode:"streaming_guidance",reasoningLevelPersists:!1,defaultReasoningLevel:void 0,supportsSlashMenuByDefault:!0,supportsRunSteeringByDefault:!0,supportsSessionDeleteByDefault:!0,foldRulesMessagesByDefault:!1},"legna-code":{displayNameKey:"conversation.providerLegna",fullDisplayNameKey:"shell.providerLegnaCode",draftTitleKey:"conversation.draftTitleLegna",defaultModelLabelKey:"conversation.modelUseCliDefault",icon:IA,defaultRunInputMode:"streaming_guidance",reasoningLevelPersists:!1,defaultReasoningLevel:void 0,supportsSlashMenuByDefault:!0,supportsRunSteeringByDefault:!0,supportsSessionDeleteByDefault:!0,foldRulesMessagesByDefault:!1},codex:{displayNameKey:"conversation.providerCodex",draftTitleKey:"conversation.draftTitleCodex",defaultModelLabelKey:"conversation.modelUseCliDefault",icon:$w,defaultRunInputMode:"streaming_guidance",reasoningLevelPersists:!0,defaultReasoningLevel:null,supportsSlashMenuByDefault:!1,supportsRunSteeringByDefault:!0,supportsQueueWhileRunningByDefault:!0,supportsSessionDeleteByDefault:!0,foldRulesMessagesByDefault:!0},opencode:{displayNameKey:"conversation.providerOpenCode",draftTitleKey:"conversation.draftTitleOpenCode",defaultModelLabelKey:"conversation.modelUseCliDefault",icon:PA,defaultRunInputMode:"none",reasoningLevelPersists:!1,defaultReasoningLevel:void 0,supportsSlashMenuByDefault:!1,supportsSessionDeleteByDefault:!0,foldRulesMessagesByDefault:!1},gemini:{displayNameKey:"conversation.providerGemini",draftTitleKey:"conversation.draftTitleGemini",defaultModelLabelKey:"conversation.modelUseCliDefault",icon:AA,defaultRunInputMode:"none",reasoningLevelPersists:!1,defaultReasoningLevel:null,supportsInterrupt:!0,supportsAttachments:!1,supportsPermissionPrompt:!1,supportsSlashMenuByDefault:!1,supportsSessionDeleteByDefault:!0,foldRulesMessagesByDefault:!1},kimi:{displayNameKey:"conversation.providerKimi",draftTitleKey:"conversation.draftTitleKimi",defaultModelLabelKey:"conversation.modelUseCliDefault",icon:RA,defaultRunInputMode:"none",reasoningLevelPersists:!1,defaultReasoningLevel:null,supportsInterrupt:!0,supportsAttachments:!1,supportsPermissionPrompt:!1,supportsSlashMenuByDefault:!1,supportsSessionDeleteByDefault:!0,foldRulesMessagesByDefault:!0}},EA=Array.from(new Set(Object.values(Hw).map(e=>e.icon)));let Yg=!1;function LA(e){return zw.includes(e)}function Wr(e){return!e||!LA(e)?null:Hw[e]}function DA(e){return[{id:"provider-default",name:a(e),usesProviderDefault:!0}]}function OA(e){const t=Wr(e);return DA((t==null?void 0:t.defaultModelLabelKey)??"conversation.modelUseCliDefault")}function FA(e){return!!(e&&Wr(e))}function _A(e){const t=Wr(e);return a((t==null?void 0:t.draftTitleKey)??"conversation.draftTitleCodex")}function Ui(e,t="compact"){const n=Wr(e);return n?t==="full"&&n.fullDisplayNameKey?a(n.fullDisplayNameKey):a(n.displayNameKey):(e==null?void 0:e.trim())||a("conversation.providerCodex")}function Uw(e){const t=Wr(e);return(t==null?void 0:t.icon)??$w}function qw(){Yg||typeof window>"u"||(Yg=!0,EA.forEach(e=>{const t=new window.Image;t.decoding="async",t.src=e,typeof t.decode=="function"&&t.decode().catch(()=>{})}))}function Ja(e){const t=Wr(e);return{provider:e,canStartSession:!0,canResumeSession:!0,canSendMessage:!0,inRunInputMode:(t==null?void 0:t.defaultRunInputMode)??"none",supportsSubagents:!1,supportsInterrupt:(t==null?void 0:t.supportsInterrupt)??!1,supportsStructuredToolCalls:!0,supportsTokenUsage:!0,supportsAttachments:(t==null?void 0:t.supportsAttachments)??!0,supportsPermissionPrompt:(t==null?void 0:t.supportsPermissionPrompt)??!0,supportsCheckpoint:!1,supportsSessionDelete:(t==null?void 0:t.supportsSessionDeleteByDefault)??!1,modelOptions:OA(e),defaultReasoningLevel:t==null?void 0:t.defaultReasoningLevel,supportsRunSteering:t==null?void 0:t.supportsRunSteeringByDefault,supportsQueueWhileRunning:t==null?void 0:t.supportsQueueWhileRunningByDefault,limitations:[]}}function BA(e){return(e==null?void 0:e.provider)??"claude-code"}function WA(e){var n;if((e==null?void 0:e.supportsSlashMenu)!==void 0)return e.supportsSlashMenu;const t=(e==null?void 0:e.provider)??null;return((n=Wr(t))==null?void 0:n.supportsSlashMenuByDefault)??!1}function $A(e){var t;return(e==null?void 0:e.supportsReasoningSelector)!==void 0?e.supportsReasoningSelector:!!((t=e==null?void 0:e.modelOptions)!=null&&t.some(n=>{var r;return((r=n.supportedReasoningEfforts)==null?void 0:r.some(i=>MA.has(i)))??!1}))}function zA(e,t){var o;if((e==null?void 0:e.supportsQueueWhileRunning)!==void 0)return e.supportsQueueWhileRunning;const n=(e==null?void 0:e.provider)??null,r=(o=Wr(n))==null?void 0:o.supportsQueueWhileRunningByDefault;if(r!==void 0)return r;const i=(e==null?void 0:e.inRunInputMode)??"none";return i==="queued_guidance"||i==="none"||i==="streaming_guidance"&&t===!1}function HA(e){var n;if((e==null?void 0:e.supportsRunSteering)!==void 0)return e.supportsRunSteering;const t=(e==null?void 0:e.provider)??null;return((n=Wr(t))==null?void 0:n.supportsRunSteeringByDefault)??(e==null?void 0:e.inRunInputMode)==="streaming_guidance"}function UA(e){const t=Wr(e);return(t==null?void 0:t.reasoningLevelPersists)??!1}function qA(e,t){var r;return((r=Wr(t??null))==null?void 0:r.foldRulesMessagesByDefault)??!1}typeof window<"u"&&qw();function VA(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const KA=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,GA=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,YA={};function Jg(e,t){return(YA.jsx?GA:KA).test(e)}const JA=/[ \t\n\f\r]/g;function XA(e){return typeof e=="object"?e.type==="text"?Xg(e.value):!1:Xg(e)}function Xg(e){return e.replace(JA,"")===""}class Rl{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Rl.prototype.normal={};Rl.prototype.property={};Rl.prototype.space=void 0;function Vw(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new Rl(n,r,t)}function hh(e){return e.toLowerCase()}class lr{constructor(t,n){this.attribute=n,this.property=t}}lr.prototype.attribute="";lr.prototype.booleanish=!1;lr.prototype.boolean=!1;lr.prototype.commaOrSpaceSeparated=!1;lr.prototype.commaSeparated=!1;lr.prototype.defined=!1;lr.prototype.mustUseProperty=!1;lr.prototype.number=!1;lr.prototype.overloadedBoolean=!1;lr.prototype.property="";lr.prototype.spaceSeparated=!1;lr.prototype.space=void 0;let QA=0;const Yt=ba(),ys=ba(),mh=ba(),qe=ba(),Bn=ba(),Xa=ba(),pr=ba();function ba(){return 2**++QA}const ph=Object.freeze(Object.defineProperty({__proto__:null,boolean:Yt,booleanish:ys,commaOrSpaceSeparated:pr,commaSeparated:Xa,number:qe,overloadedBoolean:mh,spaceSeparated:Bn},Symbol.toStringTag,{value:"Module"})),Od=Object.keys(ph);class Om extends lr{constructor(t,n,r,i){let o=-1;if(super(t,n),Qg(this,"space",i),typeof r=="number")for(;++o<Od.length;){const l=Od[o];Qg(this,Od[o],(r&ph[l])===ph[l])}}}Om.prototype.defined=!0;function Qg(e,t,n){n&&(e[t]=n)}function po(e){const t={},n={};for(const[r,i]of Object.entries(e.properties)){const o=new Om(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(o.mustUseProperty=!0),t[r]=o,n[hh(r)]=r,n[hh(o.attribute)]=r}return new Rl(t,n,e.space)}const Kw=po({properties:{ariaActiveDescendant:null,ariaAtomic:ys,ariaAutoComplete:null,ariaBusy:ys,ariaChecked:ys,ariaColCount:qe,ariaColIndex:qe,ariaColSpan:qe,ariaControls:Bn,ariaCurrent:null,ariaDescribedBy:Bn,ariaDetails:null,ariaDisabled:ys,ariaDropEffect:Bn,ariaErrorMessage:null,ariaExpanded:ys,ariaFlowTo:Bn,ariaGrabbed:ys,ariaHasPopup:null,ariaHidden:ys,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Bn,ariaLevel:qe,ariaLive:null,ariaModal:ys,ariaMultiLine:ys,ariaMultiSelectable:ys,ariaOrientation:null,ariaOwns:Bn,ariaPlaceholder:null,ariaPosInSet:qe,ariaPressed:ys,ariaReadOnly:ys,ariaRelevant:null,ariaRequired:ys,ariaRoleDescription:Bn,ariaRowCount:qe,ariaRowIndex:qe,ariaRowSpan:qe,ariaSelected:ys,ariaSetSize:qe,ariaSort:null,ariaValueMax:qe,ariaValueMin:qe,ariaValueNow:qe,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Gw(e,t){return t in e?e[t]:t}function Yw(e,t){return Gw(e,t.toLowerCase())}const ZA=po({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Xa,acceptCharset:Bn,accessKey:Bn,action:null,allow:null,allowFullScreen:Yt,allowPaymentRequest:Yt,allowUserMedia:Yt,alt:null,as:null,async:Yt,autoCapitalize:null,autoComplete:Bn,autoFocus:Yt,autoPlay:Yt,blocking:Bn,capture:null,charSet:null,checked:Yt,cite:null,className:Bn,cols:qe,colSpan:null,content:null,contentEditable:ys,controls:Yt,controlsList:Bn,coords:qe|Xa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Yt,defer:Yt,dir:null,dirName:null,disabled:Yt,download:mh,draggable:ys,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Yt,formTarget:null,headers:Bn,height:qe,hidden:mh,high:qe,href:null,hrefLang:null,htmlFor:Bn,httpEquiv:Bn,id:null,imageSizes:null,imageSrcSet:null,inert:Yt,inputMode:null,integrity:null,is:null,isMap:Yt,itemId:null,itemProp:Bn,itemRef:Bn,itemScope:Yt,itemType:Bn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Yt,low:qe,manifest:null,max:null,maxLength:qe,media:null,method:null,min:null,minLength:qe,multiple:Yt,muted:Yt,name:null,nonce:null,noModule:Yt,noValidate:Yt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Yt,optimum:qe,pattern:null,ping:Bn,placeholder:null,playsInline:Yt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Yt,referrerPolicy:null,rel:Bn,required:Yt,reversed:Yt,rows:qe,rowSpan:qe,sandbox:Bn,scope:null,scoped:Yt,seamless:Yt,selected:Yt,shadowRootClonable:Yt,shadowRootDelegatesFocus:Yt,shadowRootMode:null,shape:null,size:qe,sizes:null,slot:null,span:qe,spellCheck:ys,src:null,srcDoc:null,srcLang:null,srcSet:null,start:qe,step:null,style:null,tabIndex:qe,target:null,title:null,translate:null,type:null,typeMustMatch:Yt,useMap:null,value:ys,width:qe,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Bn,axis:null,background:null,bgColor:null,border:qe,borderColor:null,bottomMargin:qe,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Yt,declare:Yt,event:null,face:null,frame:null,frameBorder:null,hSpace:qe,leftMargin:qe,link:null,longDesc:null,lowSrc:null,marginHeight:qe,marginWidth:qe,noResize:Yt,noHref:Yt,noShade:Yt,noWrap:Yt,object:null,profile:null,prompt:null,rev:null,rightMargin:qe,rules:null,scheme:null,scrolling:ys,standby:null,summary:null,text:null,topMargin:qe,valueType:null,version:null,vAlign:null,vLink:null,vSpace:qe,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Yt,disableRemotePlayback:Yt,prefix:null,property:null,results:qe,security:null,unselectable:null},space:"html",transform:Yw}),eR=po({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:pr,accentHeight:qe,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:qe,amplitude:qe,arabicForm:null,ascent:qe,attributeName:null,attributeType:null,azimuth:qe,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:qe,by:null,calcMode:null,capHeight:qe,className:Bn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:qe,diffuseConstant:qe,direction:null,display:null,dur:null,divisor:qe,dominantBaseline:null,download:Yt,dx:null,dy:null,edgeMode:null,editable:null,elevation:qe,enableBackground:null,end:null,event:null,exponent:qe,externalResourcesRequired:null,fill:null,fillOpacity:qe,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Xa,g2:Xa,glyphName:Xa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:qe,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:qe,horizOriginX:qe,horizOriginY:qe,id:null,ideographic:qe,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:qe,k:qe,k1:qe,k2:qe,k3:qe,k4:qe,kernelMatrix:pr,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:qe,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:qe,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:qe,overlineThickness:qe,paintOrder:null,panose1:null,path:null,pathLength:qe,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Bn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:qe,pointsAtY:qe,pointsAtZ:qe,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:pr,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:pr,rev:pr,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:pr,requiredFeatures:pr,requiredFonts:pr,requiredFormats:pr,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:qe,specularExponent:qe,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:qe,strikethroughThickness:qe,string:null,stroke:null,strokeDashArray:pr,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:qe,strokeOpacity:qe,strokeWidth:null,style:null,surfaceScale:qe,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:pr,tabIndex:qe,tableValues:null,target:null,targetX:qe,targetY:qe,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:pr,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:qe,underlineThickness:qe,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:qe,values:null,vAlphabetic:qe,vMathematical:qe,vectorEffect:null,vHanging:qe,vIdeographic:qe,version:null,vertAdvY:qe,vertOriginX:qe,vertOriginY:qe,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:qe,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Gw}),Jw=po({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Xw=po({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Yw}),Qw=po({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),tR={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},nR=/[A-Z]/g,Zg=/-[a-z]/g,sR=/^data[-\w.:]+$/i;function rR(e,t){const n=hh(t);let r=t,i=lr;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&sR.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(Zg,aR);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!Zg.test(o)){let l=o.replace(nR,iR);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}i=Om}return new i(r,t)}function iR(e){return"-"+e.toLowerCase()}function aR(e){return e.charAt(1).toUpperCase()}const oR=Vw([Kw,ZA,Jw,Xw,Qw],"html"),Fm=Vw([Kw,eR,Jw,Xw,Qw],"svg");function lR(e){return e.join(" ").trim()}var va={},Fd,eb;function cR(){if(eb)return Fd;eb=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,u=`
7
+ `,f="/",h="*",m="",g="comment",p="declaration";function b(x,k){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];k=k||{};var C=1,j=1;function H(te){var V=te.match(t);V&&(C+=V.length);var ee=te.lastIndexOf(u);j=~ee?te.length-ee:j+te.length}function _(){var te={line:C,column:j};return function(V){return V.position=new T(te),L(),V}}function T(te){this.start=te,this.end={line:C,column:j},this.source=k.source}T.prototype.content=x;function P(te){var V=new Error(k.source+":"+C+":"+j+": "+te);if(V.reason=te,V.filename=k.source,V.line=C,V.column=j,V.source=x,!k.silent)throw V}function z(te){var V=te.exec(x);if(V){var ee=V[0];return H(ee),x=x.slice(ee.length),V}}function L(){z(n)}function R(te){var V;for(te=te||[];V=K();)V!==!1&&te.push(V);return te}function K(){var te=_();if(!(f!=x.charAt(0)||h!=x.charAt(1))){for(var V=2;m!=x.charAt(V)&&(h!=x.charAt(V)||f!=x.charAt(V+1));)++V;if(V+=2,m===x.charAt(V-1))return P("End of comment missing");var ee=x.slice(2,V-2);return j+=2,H(ee),x=x.slice(V),j+=2,te({type:g,comment:ee})}}function E(){var te=_(),V=z(r);if(V){if(K(),!z(i))return P("property missing ':'");var ee=z(o),U=te({type:p,property:y(V[0].replace(e,m)),value:ee?y(ee[0].replace(e,m)):m});return z(l),U}}function D(){var te=[];R(te);for(var V;V=E();)V!==!1&&(te.push(V),R(te));return te}return L(),D()}function y(x){return x?x.replace(c,m):m}return Fd=b,Fd}var tb;function uR(){if(tb)return va;tb=1;var e=va&&va.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(va,"__esModule",{value:!0}),va.default=n;const t=e(cR());function n(r,i){let o=null;if(!r||typeof r!="string")return o;const l=(0,t.default)(r),c=typeof i=="function";return l.forEach(u=>{if(u.type!=="declaration")return;const{property:f,value:h}=u;c?i(f,h,u):h&&(o=o||{},o[f]=h)}),o}return va}var Io={},nb;function dR(){if(nb)return Io;nb=1,Object.defineProperty(Io,"__esModule",{value:!0}),Io.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,o=function(f){return!f||n.test(f)||e.test(f)},l=function(f,h){return h.toUpperCase()},c=function(f,h){return"".concat(h,"-")},u=function(f,h){return h===void 0&&(h={}),o(f)?f:(f=f.toLowerCase(),h.reactCompat?f=f.replace(i,c):f=f.replace(r,c),f.replace(t,l))};return Io.camelCase=u,Io}var Ao,sb;function fR(){if(sb)return Ao;sb=1;var e=Ao&&Ao.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(uR()),n=dR();function r(i,o){var l={};return!i||typeof i!="string"||(0,t.default)(i,function(c,u){c&&u&&(l[(0,n.camelCase)(c,o)]=u)}),l}return r.default=r,Ao=r,Ao}var hR=fR();const mR=Ok(hR),Zw=ev("end"),_m=ev("start");function ev(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function pR(e){const t=_m(e),n=Zw(e);if(t&&n)return{start:t,end:n}}function Qo(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?rb(e.position):"start"in e||"end"in e?rb(e):"line"in e||"column"in e?gh(e):""}function gh(e){return ib(e&&e.line)+":"+ib(e&&e.column)}function rb(e){return gh(e&&e.start)+"-"+gh(e&&e.end)}function ib(e){return e&&typeof e=="number"?e:1}class Js extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",o={},l=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof t=="string"?i=t:!o.cause&&t&&(l=!0,i=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof r=="string"){const u=r.indexOf(":");u===-1?o.ruleId=r:(o.source=r.slice(0,u),o.ruleId=r.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=c?c.line:void 0,this.name=Qo(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=l&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Js.prototype.file="";Js.prototype.name="";Js.prototype.reason="";Js.prototype.message="";Js.prototype.stack="";Js.prototype.column=void 0;Js.prototype.line=void 0;Js.prototype.ancestors=void 0;Js.prototype.cause=void 0;Js.prototype.fatal=void 0;Js.prototype.place=void 0;Js.prototype.ruleId=void 0;Js.prototype.source=void 0;const Bm={}.hasOwnProperty,gR=new Map,bR=/[A-Z]/g,yR=new Set(["table","tbody","thead","tfoot","tr"]),xR=new Set(["td","th"]),tv="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function kR(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=IR(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=TR(n,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Fm:oR,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=nv(i,e,void 0);return o&&typeof o!="string"?o:i.create(e,i.Fragment,{children:o||void 0},void 0)}function nv(e,t,n){if(t.type==="element")return wR(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return vR(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return CR(e,t,n);if(t.type==="mdxjsEsm")return SR(e,t);if(t.type==="root")return jR(e,t,n);if(t.type==="text")return NR(e,t)}function wR(e,t,n){const r=e.schema;let i=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=Fm,e.schema=i),e.ancestors.push(t);const o=rv(e,t.tagName,!1),l=AR(e,t);let c=$m(e,t);return yR.has(t.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!XA(u):!0})),sv(e,l,o,t),Wm(l,c),e.ancestors.pop(),e.schema=r,e.create(t,o,l,n)}function vR(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}fl(e,t.position)}function SR(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);fl(e,t.position)}function CR(e,t,n){const r=e.schema;let i=r;t.name==="svg"&&r.space==="html"&&(i=Fm,e.schema=i),e.ancestors.push(t);const o=t.name===null?e.Fragment:rv(e,t.name,!0),l=RR(e,t),c=$m(e,t);return sv(e,l,o,t),Wm(l,c),e.ancestors.pop(),e.schema=r,e.create(t,o,l,n)}function jR(e,t,n){const r={};return Wm(r,$m(e,t)),e.create(t,e.Fragment,r,n)}function NR(e,t){return t.value}function sv(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Wm(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function TR(e,t,n){return r;function r(i,o,l,c){const f=Array.isArray(l.children)?n:t;return c?f(o,l,c):f(o,l)}}function IR(e,t){return n;function n(r,i,o,l){const c=Array.isArray(o.children),u=_m(r);return t(i,o,l,c,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function AR(e,t){const n={};let r,i;for(i in t.properties)if(i!=="children"&&Bm.call(t.properties,i)){const o=PR(e,i,t.properties[i]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&xR.has(t.tagName)?r=c:n[l]=c}}if(r){const o=n.style||(n.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function RR(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const o=r.data.estree.body[0];o.type;const l=o.expression;l.type;const c=l.properties[0];c.type,Object.assign(n,e.evaluater.evaluateExpression(c.argument))}else fl(e,t.position);else{const i=r.name;let o;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const c=r.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else fl(e,t.position);else o=r.value===null?!0:r.value;n[i]=o}return n}function $m(e,t){const n=[];let r=-1;const i=e.passKeys?new Map:gR;for(;++r<t.children.length;){const o=t.children[r];let l;if(e.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const f=i.get(u)||0;l=u+"-"+f,i.set(u,f+1)}}const c=nv(e,o,l);c!==void 0&&n.push(c)}return n}function PR(e,t,n){const r=rR(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?VA(n):lR(n)),r.property==="style"){let i=typeof n=="object"?n:MR(e,String(n));return e.stylePropertyNameCase==="css"&&(i=ER(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&r.space?tR[r.property]||r.property:r.attribute,n]}}function MR(e,t){try{return mR(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,i=new Js("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=tv+"#cannot-parse-style-attribute",i}}function rv(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const i=t.split(".");let o=-1,l;for(;++o<i.length;){const c=Jg(i[o])?{type:"Identifier",name:i[o]}:{type:"Literal",value:i[o]};l=l?{type:"MemberExpression",object:l,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}r=l}else r=Jg(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const i=r.value;return Bm.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(r);fl(e)}function fl(e,t){const n=new Js("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=tv+"#cannot-handle-mdx-estrees-without-createevaluater",n}function ER(e){const t={};let n;for(n in e)Bm.call(e,n)&&(t[LR(n)]=e[n]);return t}function LR(e){let t=e.replace(bR,DR);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function DR(e){return"-"+e.toLowerCase()}const _d={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},OR={};function zm(e,t){const n=OR,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return iv(e,r,i)}function iv(e,t,n){if(FR(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return ab(e.children,t,n)}return Array.isArray(e)?ab(e,t,n):""}function ab(e,t,n){const r=[];let i=-1;for(;++i<e.length;)r[i]=iv(e[i],t,n);return r.join("")}function FR(e){return!!(e&&typeof e=="object")}const ob=document.createElement("i");function Hm(e){const t="&"+e+";";ob.innerHTML=t;const n=ob.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function xr(e,t,n,r){const i=e.length;let o=0,l;if(t<0?t=-t>i?0:i+t:t=t>i?i:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),e.splice(...l);else for(n&&e.splice(t,n);o<r.length;)l=r.slice(o,o+1e4),l.unshift(t,0),e.splice(...l),o+=1e4,t+=1e4}function Ar(e,t){return e.length>0?(xr(e,e.length,0,t),e):t}const lb={}.hasOwnProperty;function av(e){const t={};let n=-1;for(;++n<e.length;)_R(t,e[n]);return t}function _R(e,t){let n;for(n in t){const i=(lb.call(e,n)?e[n]:void 0)||(e[n]={}),o=t[n];let l;if(o)for(l in o){lb.call(i,l)||(i[l]=[]);const c=o[l];BR(i[l],Array.isArray(c)?c:c?[c]:[])}}}function BR(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);xr(e,0,0,r)}function ov(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function _r(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const sr=Gi(/[A-Za-z]/),Gs=Gi(/[\dA-Za-z]/),WR=Gi(/[#-'*+\--9=?A-Z^-~]/);function hu(e){return e!==null&&(e<32||e===127)}const bh=Gi(/\d/),$R=Gi(/[\dA-Fa-f]/),zR=Gi(/[!-/:-@[-`{-~]/);function Tt(e){return e!==null&&e<-2}function Ln(e){return e!==null&&(e<0||e===32)}function rn(e){return e===-2||e===-1||e===32}const qu=Gi(new RegExp("\\p{P}|\\p{S}","u")),ma=Gi(/\s/);function Gi(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function go(e){const t=[];let n=-1,r=0,i=0;for(;++n<e.length;){const o=e.charCodeAt(n);let l="";if(o===37&&Gs(e.charCodeAt(n+1))&&Gs(e.charCodeAt(n+2)))i=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(n+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),i=1):l="�"}else l=String.fromCharCode(o);l&&(t.push(e.slice(r,n),encodeURIComponent(l)),r=n+i+1,l=""),i&&(n+=i,i=0)}return t.join("")+e.slice(r)}function mn(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return rn(u)?(e.enter(n),c(u)):t(u)}function c(u){return rn(u)&&o++<i?(e.consume(u),c):(e.exit(n),t(u))}}const HR={tokenize:UR};function UR(e){const t=e.attempt(this.parser.constructs.contentInitial,r,i);let n;return t;function r(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),mn(e,t,"linePrefix")}function i(c){return e.enter("paragraph"),o(c)}function o(c){const u=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=u),n=u,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return Tt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const qR={tokenize:VR},cb={tokenize:KR};function VR(e){const t=this,n=[];let r=0,i,o,l;return c;function c(j){if(r<n.length){const H=n[r];return t.containerState=H[1],e.attempt(H[0].continuation,u,f)(j)}return f(j)}function u(j){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&C();const H=t.events.length;let _=H,T;for(;_--;)if(t.events[_][0]==="exit"&&t.events[_][1].type==="chunkFlow"){T=t.events[_][1].end;break}k(r);let P=H;for(;P<t.events.length;)t.events[P][1].end={...T},P++;return xr(t.events,_+1,0,t.events.slice(H)),t.events.length=P,f(j)}return c(j)}function f(j){if(r===n.length){if(!i)return g(j);if(i.currentConstruct&&i.currentConstruct.concrete)return b(j);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(cb,h,m)(j)}function h(j){return i&&C(),k(r),g(j)}function m(j){return t.parser.lazy[t.now().line]=r!==n.length,l=t.now().offset,b(j)}function g(j){return t.containerState={},e.attempt(cb,p,b)(j)}function p(j){return r++,n.push([t.currentConstruct,t.containerState]),g(j)}function b(j){if(j===null){i&&C(),k(0),e.consume(j);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:o}),y(j)}function y(j){if(j===null){x(e.exit("chunkFlow"),!0),k(0),e.consume(j);return}return Tt(j)?(e.consume(j),x(e.exit("chunkFlow")),r=0,t.interrupt=void 0,c):(e.consume(j),y)}function x(j,H){const _=t.sliceStream(j);if(H&&_.push(null),j.previous=o,o&&(o.next=j),o=j,i.defineSkip(j.start),i.write(_),t.parser.lazy[j.start.line]){let T=i.events.length;for(;T--;)if(i.events[T][1].start.offset<l&&(!i.events[T][1].end||i.events[T][1].end.offset>l))return;const P=t.events.length;let z=P,L,R;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){if(L){R=t.events[z][1].end;break}L=!0}for(k(r),T=P;T<t.events.length;)t.events[T][1].end={...R},T++;xr(t.events,z+1,0,t.events.slice(P)),t.events.length=T}}function k(j){let H=n.length;for(;H-- >j;){const _=n[H];t.containerState=_[1],_[0].exit.call(t,e)}n.length=j}function C(){i.write([null]),o=void 0,i=void 0,t.containerState._closeFlow=void 0}}function KR(e,t,n){return mn(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ro(e){if(e===null||Ln(e)||ma(e))return 1;if(qu(e))return 2}function Vu(e,t,n){const r=[];let i=-1;for(;++i<e.length;){const o=e[i].resolveAll;o&&!r.includes(o)&&(t=o(t,n),r.push(o))}return t}const yh={name:"attention",resolveAll:GR,tokenize:YR};function GR(e,t){let n=-1,r,i,o,l,c,u,f,h;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;u=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const m={...e[r][1].end},g={...e[n][1].start};ub(m,-u),ub(g,u),l={type:u>1?"strongSequence":"emphasisSequence",start:m,end:{...e[r][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:g},o={type:u>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},i={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[r][1].end={...l.start},e[n][1].start={...c.end},f=[],e[r][1].end.offset-e[r][1].start.offset&&(f=Ar(f,[["enter",e[r][1],t],["exit",e[r][1],t]])),f=Ar(f,[["enter",i,t],["enter",l,t],["exit",l,t],["enter",o,t]]),f=Ar(f,Vu(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),f=Ar(f,[["exit",o,t],["enter",c,t],["exit",c,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(h=2,f=Ar(f,[["enter",e[n][1],t],["exit",e[n][1],t]])):h=0,xr(e,r-1,n-r+3,f),n=r+f.length-h-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function YR(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=ro(r);let o;return l;function l(u){return o=u,e.enter("attentionSequence"),c(u)}function c(u){if(u===o)return e.consume(u),c;const f=e.exit("attentionSequence"),h=ro(u),m=!h||h===2&&i||n.includes(u),g=!i||i===2&&h||n.includes(r);return f._open=!!(o===42?m:m&&(i||!g)),f._close=!!(o===42?g:g&&(h||!m)),t(u)}}function ub(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const JR={name:"autolink",tokenize:XR};function XR(e,t,n){let r=0;return i;function i(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return sr(p)?(e.consume(p),l):p===64?n(p):f(p)}function l(p){return p===43||p===45||p===46||Gs(p)?(r=1,c(p)):f(p)}function c(p){return p===58?(e.consume(p),r=0,u):(p===43||p===45||p===46||Gs(p))&&r++<32?(e.consume(p),c):(r=0,f(p))}function u(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),t):p===null||p===32||p===60||hu(p)?n(p):(e.consume(p),u)}function f(p){return p===64?(e.consume(p),h):WR(p)?(e.consume(p),f):n(p)}function h(p){return Gs(p)?m(p):n(p)}function m(p){return p===46?(e.consume(p),r=0,h):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),t):g(p)}function g(p){if((p===45||Gs(p))&&r++<63){const b=p===45?g:m;return e.consume(p),b}return n(p)}}const Pl={partial:!0,tokenize:QR};function QR(e,t,n){return r;function r(o){return rn(o)?mn(e,i,"linePrefix")(o):i(o)}function i(o){return o===null||Tt(o)?t(o):n(o)}}const lv={continuation:{tokenize:eP},exit:tP,name:"blockQuote",tokenize:ZR};function ZR(e,t,n){const r=this;return i;function i(l){if(l===62){const c=r.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return n(l)}function o(l){return rn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(l))}}function eP(e,t,n){const r=this;return i;function i(l){return rn(l)?mn(e,o,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(lv,t,n)(l)}}function tP(e){e.exit("blockQuote")}const cv={name:"characterEscape",tokenize:nP};function nP(e,t,n){return r;function r(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),i}function i(o){return zR(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(o)}}const uv={name:"characterReference",tokenize:sP};function sP(e,t,n){const r=this;let i=0,o,l;return c;function c(m){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),u}function u(m){return m===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(m),e.exit("characterReferenceMarkerNumeric"),f):(e.enter("characterReferenceValue"),o=31,l=Gs,h(m))}function f(m){return m===88||m===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(m),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=$R,h):(e.enter("characterReferenceValue"),o=7,l=bh,h(m))}function h(m){if(m===59&&i){const g=e.exit("characterReferenceValue");return l===Gs&&!Hm(r.sliceSerialize(g))?n(m):(e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return l(m)&&i++<o?(e.consume(m),h):n(m)}}const db={partial:!0,tokenize:iP},fb={concrete:!0,name:"codeFenced",tokenize:rP};function rP(e,t,n){const r=this,i={partial:!0,tokenize:_};let o=0,l=0,c;return u;function u(T){return f(T)}function f(T){const P=r.events[r.events.length-1];return o=P&&P[1].type==="linePrefix"?P[2].sliceSerialize(P[1],!0).length:0,c=T,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),h(T)}function h(T){return T===c?(l++,e.consume(T),h):l<3?n(T):(e.exit("codeFencedFenceSequence"),rn(T)?mn(e,m,"whitespace")(T):m(T))}function m(T){return T===null||Tt(T)?(e.exit("codeFencedFence"),r.interrupt?t(T):e.check(db,y,H)(T)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(T))}function g(T){return T===null||Tt(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),m(T)):rn(T)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),mn(e,p,"whitespace")(T)):T===96&&T===c?n(T):(e.consume(T),g)}function p(T){return T===null||Tt(T)?m(T):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),b(T))}function b(T){return T===null||Tt(T)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),m(T)):T===96&&T===c?n(T):(e.consume(T),b)}function y(T){return e.attempt(i,H,x)(T)}function x(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),k}function k(T){return o>0&&rn(T)?mn(e,C,"linePrefix",o+1)(T):C(T)}function C(T){return T===null||Tt(T)?e.check(db,y,H)(T):(e.enter("codeFlowValue"),j(T))}function j(T){return T===null||Tt(T)?(e.exit("codeFlowValue"),C(T)):(e.consume(T),j)}function H(T){return e.exit("codeFenced"),t(T)}function _(T,P,z){let L=0;return R;function R(V){return T.enter("lineEnding"),T.consume(V),T.exit("lineEnding"),K}function K(V){return T.enter("codeFencedFence"),rn(V)?mn(T,E,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(V):E(V)}function E(V){return V===c?(T.enter("codeFencedFenceSequence"),D(V)):z(V)}function D(V){return V===c?(L++,T.consume(V),D):L>=l?(T.exit("codeFencedFenceSequence"),rn(V)?mn(T,te,"whitespace")(V):te(V)):z(V)}function te(V){return V===null||Tt(V)?(T.exit("codeFencedFence"),P(V)):z(V)}}}function iP(e,t,n){const r=this;return i;function i(l){return l===null?n(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o)}function o(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const Bd={name:"codeIndented",tokenize:oP},aP={partial:!0,tokenize:lP};function oP(e,t,n){const r=this;return i;function i(f){return e.enter("codeIndented"),mn(e,o,"linePrefix",5)(f)}function o(f){const h=r.events[r.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?l(f):n(f)}function l(f){return f===null?u(f):Tt(f)?e.attempt(aP,l,u)(f):(e.enter("codeFlowValue"),c(f))}function c(f){return f===null||Tt(f)?(e.exit("codeFlowValue"),l(f)):(e.consume(f),c)}function u(f){return e.exit("codeIndented"),t(f)}}function lP(e,t,n){const r=this;return i;function i(l){return r.parser.lazy[r.now().line]?n(l):Tt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i):mn(e,o,"linePrefix",5)(l)}function o(l){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?t(l):Tt(l)?i(l):n(l)}}const cP={name:"codeText",previous:dP,resolve:uP,tokenize:fP};function uP(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(i=r):(r===t||e[r][1].type==="lineEnding")&&(e[i][1].type="codeTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function dP(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function fP(e,t,n){let r=0,i,o;return l;function l(m){return e.enter("codeText"),e.enter("codeTextSequence"),c(m)}function c(m){return m===96?(e.consume(m),r++,c):(e.exit("codeTextSequence"),u(m))}function u(m){return m===null?n(m):m===32?(e.enter("space"),e.consume(m),e.exit("space"),u):m===96?(o=e.enter("codeTextSequence"),i=0,h(m)):Tt(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),u):(e.enter("codeTextData"),f(m))}function f(m){return m===null||m===32||m===96||Tt(m)?(e.exit("codeTextData"),u(m)):(e.consume(m),f)}function h(m){return m===96?(e.consume(m),i++,h):i===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(m)):(o.type="codeTextData",f(m))}}class hP{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const i=n||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&Ro(this.left,r),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Ro(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Ro(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);Ro(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Ro(this.left,n.reverse())}}}function Ro(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function dv(e){const t={};let n=-1,r,i,o,l,c,u,f;const h=new hP(e);for(;++n<h.length;){for(;n in t;)n=t[n];if(r=h.get(n),n&&r[1].type==="chunkFlow"&&h.get(n-1)[1].type==="listItemPrefix"&&(u=r[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,mP(h,n)),n=t[n],f=!0);else if(r[1]._container){for(o=n,i=void 0;o--;)if(l=h.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(i&&(h.get(i)[1].type="lineEndingBlank"),l[1].type="lineEnding",i=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;i&&(r[1].end={...h.get(i)[1].start},c=h.slice(i,n),c.unshift(r),h.splice(i,n-i+1,c))}}return xr(e,0,Number.POSITIVE_INFINITY,h.slice(0)),!f}function mP(e,t){const n=e.get(t)[1],r=e.get(t)[2];let i=t-1;const o=[];let l=n._tokenizer;l||(l=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],f={};let h,m,g=-1,p=n,b=0,y=0;const x=[y];for(;p;){for(;e.get(++i)[1]!==p;);o.push(i),p._tokenizer||(h=r.sliceStream(p),p.next||h.push(null),m&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(h),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),m=p,p=p.next}for(p=n;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(y=g+1,x.push(y),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):x.pop(),g=x.length;g--;){const k=c.slice(x[g],x[g+1]),C=o.pop();u.push([C,C+k.length-1]),e.splice(C,2,k)}for(u.reverse(),g=-1;++g<u.length;)f[b+u[g][0]]=b+u[g][1],b+=u[g][1]-u[g][0]-1;return f}const pP={resolve:bP,tokenize:yP},gP={partial:!0,tokenize:xP};function bP(e){return dv(e),e}function yP(e,t){let n;return r;function r(c){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),i(c)}function i(c){return c===null?o(c):Tt(c)?e.check(gP,l,o)(c):(e.consume(c),i)}function o(c){return e.exit("chunkContent"),e.exit("content"),t(c)}function l(c){return e.consume(c),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,i}}function xP(e,t,n){const r=this;return i;function i(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),mn(e,o,"linePrefix")}function o(l){if(l===null||Tt(l))return n(l);const c=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?t(l):e.interrupt(r.parser.constructs.flow,n,t)(l)}}function fv(e,t,n,r,i,o,l,c,u){const f=u||Number.POSITIVE_INFINITY;let h=0;return m;function m(k){return k===60?(e.enter(r),e.enter(i),e.enter(o),e.consume(k),e.exit(o),g):k===null||k===32||k===41||hu(k)?n(k):(e.enter(r),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),y(k))}function g(k){return k===62?(e.enter(o),e.consume(k),e.exit(o),e.exit(i),e.exit(r),t):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(k))}function p(k){return k===62?(e.exit("chunkString"),e.exit(c),g(k)):k===null||k===60||Tt(k)?n(k):(e.consume(k),k===92?b:p)}function b(k){return k===60||k===62||k===92?(e.consume(k),p):p(k)}function y(k){return!h&&(k===null||k===41||Ln(k))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(r),t(k)):h<f&&k===40?(e.consume(k),h++,y):k===41?(e.consume(k),h--,y):k===null||k===32||k===40||hu(k)?n(k):(e.consume(k),k===92?x:y)}function x(k){return k===40||k===41||k===92?(e.consume(k),y):y(k)}}function hv(e,t,n,r,i,o){const l=this;let c=0,u;return f;function f(p){return e.enter(r),e.enter(i),e.consume(p),e.exit(i),e.enter(o),h}function h(p){return c>999||p===null||p===91||p===93&&!u||p===94&&!c&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(e.exit(o),e.enter(i),e.consume(p),e.exit(i),e.exit(r),t):Tt(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),h):(e.enter("chunkString",{contentType:"string"}),m(p))}function m(p){return p===null||p===91||p===93||Tt(p)||c++>999?(e.exit("chunkString"),h(p)):(e.consume(p),u||(u=!rn(p)),p===92?g:m)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,m):m(p)}}function mv(e,t,n,r,i,o){let l;return c;function c(g){return g===34||g===39||g===40?(e.enter(r),e.enter(i),e.consume(g),e.exit(i),l=g===40?41:g,u):n(g)}function u(g){return g===l?(e.enter(i),e.consume(g),e.exit(i),e.exit(r),t):(e.enter(o),f(g))}function f(g){return g===l?(e.exit(o),u(l)):g===null?n(g):Tt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),mn(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),h(g))}function h(g){return g===l||g===null||Tt(g)?(e.exit("chunkString"),f(g)):(e.consume(g),g===92?m:h)}function m(g){return g===l||g===92?(e.consume(g),h):h(g)}}function Zo(e,t){let n;return r;function r(i){return Tt(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r):rn(i)?mn(e,r,n?"linePrefix":"lineSuffix")(i):t(i)}}const kP={name:"definition",tokenize:vP},wP={partial:!0,tokenize:SP};function vP(e,t,n){const r=this;let i;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return hv.call(r,e,c,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return i=_r(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):n(p)}function u(p){return Ln(p)?Zo(e,f)(p):f(p)}function f(p){return fv(e,h,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function h(p){return e.attempt(wP,m,m)(p)}function m(p){return rn(p)?mn(e,g,"whitespace")(p):g(p)}function g(p){return p===null||Tt(p)?(e.exit("definition"),r.parser.defined.push(i),t(p)):n(p)}}function SP(e,t,n){return r;function r(c){return Ln(c)?Zo(e,i)(c):n(c)}function i(c){return mv(e,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return rn(c)?mn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Tt(c)?t(c):n(c)}}const CP={name:"hardBreakEscape",tokenize:jP};function jP(e,t,n){return r;function r(o){return e.enter("hardBreakEscape"),e.consume(o),i}function i(o){return Tt(o)?(e.exit("hardBreakEscape"),t(o)):n(o)}}const NP={name:"headingAtx",resolve:TP,tokenize:IP};function TP(e,t){let n=e.length-2,r=3,i,o;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},o={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},xr(e,r,n-r+1,[["enter",i,t],["enter",o,t],["exit",o,t],["exit",i,t]])),e}function IP(e,t,n){let r=0;return i;function i(h){return e.enter("atxHeading"),o(h)}function o(h){return e.enter("atxHeadingSequence"),l(h)}function l(h){return h===35&&r++<6?(e.consume(h),l):h===null||Ln(h)?(e.exit("atxHeadingSequence"),c(h)):n(h)}function c(h){return h===35?(e.enter("atxHeadingSequence"),u(h)):h===null||Tt(h)?(e.exit("atxHeading"),t(h)):rn(h)?mn(e,c,"whitespace")(h):(e.enter("atxHeadingText"),f(h))}function u(h){return h===35?(e.consume(h),u):(e.exit("atxHeadingSequence"),c(h))}function f(h){return h===null||h===35||Ln(h)?(e.exit("atxHeadingText"),c(h)):(e.consume(h),f)}}const AP=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],hb=["pre","script","style","textarea"],RP={concrete:!0,name:"htmlFlow",resolveTo:EP,tokenize:LP},PP={partial:!0,tokenize:OP},MP={partial:!0,tokenize:DP};function EP(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function LP(e,t,n){const r=this;let i,o,l,c,u;return f;function f(M){return h(M)}function h(M){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(M),m}function m(M){return M===33?(e.consume(M),g):M===47?(e.consume(M),o=!0,y):M===63?(e.consume(M),i=3,r.interrupt?t:I):sr(M)?(e.consume(M),l=String.fromCharCode(M),x):n(M)}function g(M){return M===45?(e.consume(M),i=2,p):M===91?(e.consume(M),i=5,c=0,b):sr(M)?(e.consume(M),i=4,r.interrupt?t:I):n(M)}function p(M){return M===45?(e.consume(M),r.interrupt?t:I):n(M)}function b(M){const de="CDATA[";return M===de.charCodeAt(c++)?(e.consume(M),c===de.length?r.interrupt?t:E:b):n(M)}function y(M){return sr(M)?(e.consume(M),l=String.fromCharCode(M),x):n(M)}function x(M){if(M===null||M===47||M===62||Ln(M)){const de=M===47,Ne=l.toLowerCase();return!de&&!o&&hb.includes(Ne)?(i=1,r.interrupt?t(M):E(M)):AP.includes(l.toLowerCase())?(i=6,de?(e.consume(M),k):r.interrupt?t(M):E(M)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(M):o?C(M):j(M))}return M===45||Gs(M)?(e.consume(M),l+=String.fromCharCode(M),x):n(M)}function k(M){return M===62?(e.consume(M),r.interrupt?t:E):n(M)}function C(M){return rn(M)?(e.consume(M),C):R(M)}function j(M){return M===47?(e.consume(M),R):M===58||M===95||sr(M)?(e.consume(M),H):rn(M)?(e.consume(M),j):R(M)}function H(M){return M===45||M===46||M===58||M===95||Gs(M)?(e.consume(M),H):_(M)}function _(M){return M===61?(e.consume(M),T):rn(M)?(e.consume(M),_):j(M)}function T(M){return M===null||M===60||M===61||M===62||M===96?n(M):M===34||M===39?(e.consume(M),u=M,P):rn(M)?(e.consume(M),T):z(M)}function P(M){return M===u?(e.consume(M),u=null,L):M===null||Tt(M)?n(M):(e.consume(M),P)}function z(M){return M===null||M===34||M===39||M===47||M===60||M===61||M===62||M===96||Ln(M)?_(M):(e.consume(M),z)}function L(M){return M===47||M===62||rn(M)?j(M):n(M)}function R(M){return M===62?(e.consume(M),K):n(M)}function K(M){return M===null||Tt(M)?E(M):rn(M)?(e.consume(M),K):n(M)}function E(M){return M===45&&i===2?(e.consume(M),ee):M===60&&i===1?(e.consume(M),U):M===62&&i===4?(e.consume(M),xe):M===63&&i===3?(e.consume(M),I):M===93&&i===5?(e.consume(M),X):Tt(M)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(PP,le,D)(M)):M===null||Tt(M)?(e.exit("htmlFlowData"),D(M)):(e.consume(M),E)}function D(M){return e.check(MP,te,le)(M)}function te(M){return e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),V}function V(M){return M===null||Tt(M)?D(M):(e.enter("htmlFlowData"),E(M))}function ee(M){return M===45?(e.consume(M),I):E(M)}function U(M){return M===47?(e.consume(M),l="",he):E(M)}function he(M){if(M===62){const de=l.toLowerCase();return hb.includes(de)?(e.consume(M),xe):E(M)}return sr(M)&&l.length<8?(e.consume(M),l+=String.fromCharCode(M),he):E(M)}function X(M){return M===93?(e.consume(M),I):E(M)}function I(M){return M===62?(e.consume(M),xe):M===45&&i===2?(e.consume(M),I):E(M)}function xe(M){return M===null||Tt(M)?(e.exit("htmlFlowData"),le(M)):(e.consume(M),xe)}function le(M){return e.exit("htmlFlow"),t(M)}}function DP(e,t,n){const r=this;return i;function i(l){return Tt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):n(l)}function o(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function OP(e,t,n){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Pl,t,n)}}const FP={name:"htmlText",tokenize:_P};function _P(e,t,n){const r=this;let i,o,l;return c;function c(I){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(I),u}function u(I){return I===33?(e.consume(I),f):I===47?(e.consume(I),_):I===63?(e.consume(I),j):sr(I)?(e.consume(I),z):n(I)}function f(I){return I===45?(e.consume(I),h):I===91?(e.consume(I),o=0,b):sr(I)?(e.consume(I),C):n(I)}function h(I){return I===45?(e.consume(I),p):n(I)}function m(I){return I===null?n(I):I===45?(e.consume(I),g):Tt(I)?(l=m,U(I)):(e.consume(I),m)}function g(I){return I===45?(e.consume(I),p):m(I)}function p(I){return I===62?ee(I):I===45?g(I):m(I)}function b(I){const xe="CDATA[";return I===xe.charCodeAt(o++)?(e.consume(I),o===xe.length?y:b):n(I)}function y(I){return I===null?n(I):I===93?(e.consume(I),x):Tt(I)?(l=y,U(I)):(e.consume(I),y)}function x(I){return I===93?(e.consume(I),k):y(I)}function k(I){return I===62?ee(I):I===93?(e.consume(I),k):y(I)}function C(I){return I===null||I===62?ee(I):Tt(I)?(l=C,U(I)):(e.consume(I),C)}function j(I){return I===null?n(I):I===63?(e.consume(I),H):Tt(I)?(l=j,U(I)):(e.consume(I),j)}function H(I){return I===62?ee(I):j(I)}function _(I){return sr(I)?(e.consume(I),T):n(I)}function T(I){return I===45||Gs(I)?(e.consume(I),T):P(I)}function P(I){return Tt(I)?(l=P,U(I)):rn(I)?(e.consume(I),P):ee(I)}function z(I){return I===45||Gs(I)?(e.consume(I),z):I===47||I===62||Ln(I)?L(I):n(I)}function L(I){return I===47?(e.consume(I),ee):I===58||I===95||sr(I)?(e.consume(I),R):Tt(I)?(l=L,U(I)):rn(I)?(e.consume(I),L):ee(I)}function R(I){return I===45||I===46||I===58||I===95||Gs(I)?(e.consume(I),R):K(I)}function K(I){return I===61?(e.consume(I),E):Tt(I)?(l=K,U(I)):rn(I)?(e.consume(I),K):L(I)}function E(I){return I===null||I===60||I===61||I===62||I===96?n(I):I===34||I===39?(e.consume(I),i=I,D):Tt(I)?(l=E,U(I)):rn(I)?(e.consume(I),E):(e.consume(I),te)}function D(I){return I===i?(e.consume(I),i=void 0,V):I===null?n(I):Tt(I)?(l=D,U(I)):(e.consume(I),D)}function te(I){return I===null||I===34||I===39||I===60||I===61||I===96?n(I):I===47||I===62||Ln(I)?L(I):(e.consume(I),te)}function V(I){return I===47||I===62||Ln(I)?L(I):n(I)}function ee(I){return I===62?(e.consume(I),e.exit("htmlTextData"),e.exit("htmlText"),t):n(I)}function U(I){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),he}function he(I){return rn(I)?mn(e,X,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):X(I)}function X(I){return e.enter("htmlTextData"),l(I)}}const Um={name:"labelEnd",resolveAll:zP,resolveTo:HP,tokenize:UP},BP={tokenize:qP},WP={tokenize:VP},$P={tokenize:KP};function zP(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const i=r.type==="labelImage"?4:2;r.type="data",t+=i}}return e.length!==n.length&&xr(e,0,e.length,n),e}function HP(e,t){let n=e.length,r=0,i,o,l,c;for(;n--;)if(i=e[n][1],o){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[n][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(l){if(e[n][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(o=n,i.type!=="labelLink")){r=2;break}}else i.type==="labelEnd"&&(l=n);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},f={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},h={type:"labelText",start:{...e[o+r+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",u,t],["enter",f,t]],c=Ar(c,e.slice(o+1,o+r+3)),c=Ar(c,[["enter",h,t]]),c=Ar(c,Vu(t.parser.constructs.insideSpan.null,e.slice(o+r+4,l-3),t)),c=Ar(c,[["exit",h,t],e[l-2],e[l-1],["exit",f,t]]),c=Ar(c,e.slice(l+1)),c=Ar(c,[["exit",u,t]]),xr(e,o,e.length,c),e}function UP(e,t,n){const r=this;let i=r.events.length,o,l;for(;i--;)if((r.events[i][1].type==="labelImage"||r.events[i][1].type==="labelLink")&&!r.events[i][1]._balanced){o=r.events[i][1];break}return c;function c(g){return o?o._inactive?m(g):(l=r.parser.defined.includes(_r(r.sliceSerialize({start:o.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(g),e.exit("labelMarker"),e.exit("labelEnd"),u):n(g)}function u(g){return g===40?e.attempt(BP,h,l?h:m)(g):g===91?e.attempt(WP,h,l?f:m)(g):l?h(g):m(g)}function f(g){return e.attempt($P,h,m)(g)}function h(g){return t(g)}function m(g){return o._balanced=!0,n(g)}}function qP(e,t,n){return r;function r(m){return e.enter("resource"),e.enter("resourceMarker"),e.consume(m),e.exit("resourceMarker"),i}function i(m){return Ln(m)?Zo(e,o)(m):o(m)}function o(m){return m===41?h(m):fv(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(m)}function l(m){return Ln(m)?Zo(e,u)(m):h(m)}function c(m){return n(m)}function u(m){return m===34||m===39||m===40?mv(e,f,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(m):h(m)}function f(m){return Ln(m)?Zo(e,h)(m):h(m)}function h(m){return m===41?(e.enter("resourceMarker"),e.consume(m),e.exit("resourceMarker"),e.exit("resource"),t):n(m)}}function VP(e,t,n){const r=this;return i;function i(c){return hv.call(r,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return r.parser.defined.includes(_r(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(c):n(c)}function l(c){return n(c)}}function KP(e,t,n){return r;function r(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),i}function i(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),t):n(o)}}const GP={name:"labelStartImage",resolveAll:Um.resolveAll,tokenize:YP};function YP(e,t,n){const r=this;return i;function i(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),l):n(c)}function l(c){return c===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(c):t(c)}}const JP={name:"labelStartLink",resolveAll:Um.resolveAll,tokenize:XP};function XP(e,t,n){const r=this;return i;function i(l){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelLink"),o}function o(l){return l===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(l):t(l)}}const Wd={name:"lineEnding",tokenize:QP};function QP(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),mn(e,t,"linePrefix")}}const Yc={name:"thematicBreak",tokenize:ZP};function ZP(e,t,n){let r=0,i;return o;function o(f){return e.enter("thematicBreak"),l(f)}function l(f){return i=f,c(f)}function c(f){return f===i?(e.enter("thematicBreakSequence"),u(f)):r>=3&&(f===null||Tt(f))?(e.exit("thematicBreak"),t(f)):n(f)}function u(f){return f===i?(e.consume(f),r++,u):(e.exit("thematicBreakSequence"),rn(f)?mn(e,c,"whitespace")(f):c(f))}}const ar={continuation:{tokenize:sM},exit:iM,name:"list",tokenize:nM},eM={partial:!0,tokenize:aM},tM={partial:!0,tokenize:rM};function nM(e,t,n){const r=this,i=r.events[r.events.length-1];let o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,l=0;return c;function c(p){const b=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(b==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:bh(p)){if(r.containerState.type||(r.containerState.type=b,e.enter(b,{_container:!0})),b==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Yc,n,f)(p):f(p);if(!r.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return n(p)}function u(p){return bh(p)&&++l<10?(e.consume(p),u):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),f(p)):n(p)}function f(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,e.check(Pl,r.interrupt?n:h,e.attempt(eM,g,m))}function h(p){return r.containerState.initialBlankLine=!0,o++,g(p)}function m(p){return rn(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),g):n(p)}function g(p){return r.containerState.size=o+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function sM(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(Pl,i,o);function i(c){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,mn(e,t,"listItemIndent",r.containerState.size+1)(c)}function o(c){return r.containerState.furtherBlankLines||!rn(c)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(c)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(tM,t,l)(c))}function l(c){return r.containerState._closeFlow=!0,r.interrupt=void 0,mn(e,e.attempt(ar,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function rM(e,t,n){const r=this;return mn(e,i,"listItemIndent",r.containerState.size+1);function i(o){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(o):n(o)}}function iM(e){e.exit(this.containerState.type)}function aM(e,t,n){const r=this;return mn(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){const l=r.events[r.events.length-1];return!rn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?t(o):n(o)}}const mb={name:"setextUnderline",resolveTo:oM,tokenize:lM};function oM(e,t){let n=e.length,r,i,o;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!o&&e[n][1].type==="definition"&&(o=n);const l={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",o?(e.splice(i,0,["enter",l,t]),e.splice(o+1,0,["exit",e[r][1],t]),e[r][1].end={...e[o][1].end}):e[r][1]=l,e.push(["exit",l,t]),e}function lM(e,t,n){const r=this;let i;return o;function o(f){let h=r.events.length,m;for(;h--;)if(r.events[h][1].type!=="lineEnding"&&r.events[h][1].type!=="linePrefix"&&r.events[h][1].type!=="content"){m=r.events[h][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||m)?(e.enter("setextHeadingLine"),i=f,l(f)):n(f)}function l(f){return e.enter("setextHeadingLineSequence"),c(f)}function c(f){return f===i?(e.consume(f),c):(e.exit("setextHeadingLineSequence"),rn(f)?mn(e,u,"lineSuffix")(f):u(f))}function u(f){return f===null||Tt(f)?(e.exit("setextHeadingLine"),t(f)):n(f)}}const cM={tokenize:uM};function uM(e){const t=this,n=e.attempt(Pl,r,e.attempt(this.parser.constructs.flowInitial,i,mn(e,e.attempt(this.parser.constructs.flow,i,e.attempt(pP,i)),"linePrefix")));return n;function r(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const dM={resolveAll:gv()},fM=pv("string"),hM=pv("text");function pv(e){return{resolveAll:gv(e==="text"?mM:void 0),tokenize:t};function t(n){const r=this,i=this.parser.constructs[e],o=n.attempt(i,l,c);return l;function l(h){return f(h)?o(h):c(h)}function c(h){if(h===null){n.consume(h);return}return n.enter("data"),n.consume(h),u}function u(h){return f(h)?(n.exit("data"),o(h)):(n.consume(h),u)}function f(h){if(h===null)return!0;const m=i[h];let g=-1;if(m)for(;++g<m.length;){const p=m[g];if(!p.previous||p.previous.call(r,r.previous))return!0}return!1}}}function gv(e){return t;function t(n,r){let i=-1,o;for(;++i<=n.length;)o===void 0?n[i]&&n[i][1].type==="data"&&(o=i,i++):(!n[i]||n[i][1].type!=="data")&&(i!==o+2&&(n[o][1].end=n[i-1][1].end,n.splice(o+2,i-o-2),i=o+2),o=void 0);return e?e(n,r):n}}function mM(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],i=t.sliceStream(r);let o=i.length,l=-1,c=0,u;for(;o--;){const f=i[o];if(typeof f=="string"){for(l=f.length;f.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(f===-2)u=!0,c++;else if(f!==-1){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(c=0),c){const f={type:n===e.length||u||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:r.start._bufferIndex+l,_index:r.start._index+o,line:r.end.line,column:r.end.column-c,offset:r.end.offset-c},end:{...r.end}};r.end={...f.start},r.start.offset===r.end.offset?Object.assign(r,f):(e.splice(n,0,["enter",f,t],["exit",f,t]),n+=2)}n++}return e}const pM={42:ar,43:ar,45:ar,48:ar,49:ar,50:ar,51:ar,52:ar,53:ar,54:ar,55:ar,56:ar,57:ar,62:lv},gM={91:kP},bM={[-2]:Bd,[-1]:Bd,32:Bd},yM={35:NP,42:Yc,45:[mb,Yc],60:RP,61:mb,95:Yc,96:fb,126:fb},xM={38:uv,92:cv},kM={[-5]:Wd,[-4]:Wd,[-3]:Wd,33:GP,38:uv,42:yh,60:[JR,FP],91:JP,92:[CP,cv],93:Um,95:yh,96:cP},wM={null:[yh,dM]},vM={null:[42,95]},SM={null:[]},CM=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:vM,contentInitial:gM,disable:SM,document:pM,flow:yM,flowInitial:bM,insideSpan:wM,string:xM,text:kM},Symbol.toStringTag,{value:"Module"}));function jM(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const i={},o=[];let l=[],c=[];const u={attempt:P(_),check:P(T),consume:C,enter:j,exit:H,interrupt:P(T,{interrupt:!0})},f={code:null,containerState:{},defineSkip:y,events:[],now:b,parser:e,previous:null,sliceSerialize:g,sliceStream:p,write:m};let h=t.tokenize.call(f,u);return t.resolveAll&&o.push(t),f;function m(K){return l=Ar(l,K),x(),l[l.length-1]!==null?[]:(z(t,0),f.events=Vu(o,f.events,f),f.events)}function g(K,E){return TM(p(K),E)}function p(K){return NM(l,K)}function b(){const{_bufferIndex:K,_index:E,line:D,column:te,offset:V}=r;return{_bufferIndex:K,_index:E,line:D,column:te,offset:V}}function y(K){i[K.line]=K.column,R()}function x(){let K;for(;r._index<l.length;){const E=l[r._index];if(typeof E=="string")for(K=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===K&&r._bufferIndex<E.length;)k(E.charCodeAt(r._bufferIndex));else k(E)}}function k(K){h=h(K)}function C(K){Tt(K)?(r.line++,r.column=1,r.offset+=K===-3?2:1,R()):K!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===l[r._index].length&&(r._bufferIndex=-1,r._index++)),f.previous=K}function j(K,E){const D=E||{};return D.type=K,D.start=b(),f.events.push(["enter",D,f]),c.push(D),D}function H(K){const E=c.pop();return E.end=b(),f.events.push(["exit",E,f]),E}function _(K,E){z(K,E.from)}function T(K,E){E.restore()}function P(K,E){return D;function D(te,V,ee){let U,he,X,I;return Array.isArray(te)?le(te):"tokenize"in te?le([te]):xe(te);function xe(ye){return Be;function Be(We){const Ce=We!==null&&ye[We],ke=We!==null&&ye.null,we=[...Array.isArray(Ce)?Ce:Ce?[Ce]:[],...Array.isArray(ke)?ke:ke?[ke]:[]];return le(we)(We)}}function le(ye){return U=ye,he=0,ye.length===0?ee:M(ye[he])}function M(ye){return Be;function Be(We){return I=L(),X=ye,ye.partial||(f.currentConstruct=ye),ye.name&&f.parser.constructs.disable.null.includes(ye.name)?Ne():ye.tokenize.call(E?Object.assign(Object.create(f),E):f,u,de,Ne)(We)}}function de(ye){return K(X,I),V}function Ne(ye){return I.restore(),++he<U.length?M(U[he]):ee}}}function z(K,E){K.resolveAll&&!o.includes(K)&&o.push(K),K.resolve&&xr(f.events,E,f.events.length-E,K.resolve(f.events.slice(E),f)),K.resolveTo&&(f.events=K.resolveTo(f.events,f))}function L(){const K=b(),E=f.previous,D=f.currentConstruct,te=f.events.length,V=Array.from(c);return{from:te,restore:ee};function ee(){r=K,f.previous=E,f.currentConstruct=D,f.events.length=te,c=V,R()}}function R(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function NM(e,t){const n=t.start._index,r=t.start._bufferIndex,i=t.end._index,o=t.end._bufferIndex;let l;if(n===i)l=[e[n].slice(r,o)];else{if(l=e.slice(n,i),r>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(r):l.shift()}o>0&&l.push(e[i].slice(0,o))}return l}function TM(e,t){let n=-1;const r=[];let i;for(;++n<e.length;){const o=e[n];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
8
+ `;break}case-3:{l=`\r
9
+ `;break}case-2:{l=t?" ":" ";break}case-1:{if(!t&&i)continue;l=" ";break}default:l=String.fromCharCode(o)}i=o===-2,r.push(l)}return r.join("")}function IM(e){const r={constructs:av([CM,...(e||{}).extensions||[]]),content:i(HR),defined:[],document:i(qR),flow:i(cM),lazy:{},string:i(fM),text:i(hM)};return r;function i(o){return l;function l(c){return jM(r,o,c)}}}function AM(e){for(;!dv(e););return e}const pb=/[\0\t\n\r]/g;function RM(){let e=1,t="",n=!0,r;return i;function i(o,l,c){const u=[];let f,h,m,g,p;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),m=0,t="",n&&(o.charCodeAt(0)===65279&&m++,n=void 0);m<o.length;){if(pb.lastIndex=m,f=pb.exec(o),g=f&&f.index!==void 0?f.index:o.length,p=o.charCodeAt(g),!f){t=o.slice(m);break}if(p===10&&m===g&&r)u.push(-3),r=void 0;else switch(r&&(u.push(-5),r=void 0),m<g&&(u.push(o.slice(m,g)),e+=g-m),p){case 0:{u.push(65533),e++;break}case 9:{for(h=Math.ceil(e/4)*4,u.push(-2);e++<h;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:r=!0,e=1}m=g+1}return c&&(r&&u.push(-5),t&&u.push(t),u.push(null)),u}}const PM=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function MM(e){return e.replace(PM,EM)}function EM(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const i=n.charCodeAt(1),o=i===120||i===88;return ov(n.slice(o?2:1),o?16:10)}return Hm(n)||e}const bv={}.hasOwnProperty;function LM(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),DM(n)(AM(IM(n).document().write(RM()(e,t,!0))))}function DM(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Me),autolinkProtocol:L,autolinkEmail:L,atxHeading:o(Te),blockQuote:o(ke),characterEscape:L,characterReference:L,codeFenced:o(we),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(we,l),codeText:o(se,l),codeTextData:L,data:L,codeFlowValue:L,definition:o(ce),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(Y),hardBreakEscape:o(pe),hardBreakTrailing:o(pe),htmlFlow:o(fe,l),htmlFlowData:L,htmlText:o(fe,l),htmlTextData:L,image:o(W),label:l,link:o(Me),listItem:o(Q),listItemValue:g,listOrdered:o(je,m),listUnordered:o(je),paragraph:o(ge),reference:M,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(Te),strong:o(Oe),thematicBreak:o(Ve)},exit:{atxHeading:u(),atxHeadingSequence:_,autolink:u(),autolinkEmail:Ce,autolinkProtocol:We,blockQuote:u(),characterEscapeValue:R,characterReferenceMarkerHexadecimal:Ne,characterReferenceMarkerNumeric:Ne,characterReferenceValue:ye,characterReference:Be,codeFenced:u(x),codeFencedFence:y,codeFencedFenceInfo:p,codeFencedFenceMeta:b,codeFlowValue:R,codeIndented:u(k),codeText:u(V),codeTextData:R,data:R,definition:u(),definitionDestinationString:H,definitionLabelString:C,definitionTitleString:j,emphasis:u(),hardBreakEscape:u(E),hardBreakTrailing:u(E),htmlFlow:u(D),htmlFlowData:R,htmlText:u(te),htmlTextData:R,image:u(U),label:X,labelText:he,lineEnding:K,link:u(ee),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:de,resourceDestinationString:I,resourceTitleString:xe,resource:le,setextHeading:u(z),setextHeadingLineSequence:P,setextHeadingText:T,strong:u(),thematicBreak:u()}};yv(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(G){let ve={type:"root",children:[]};const _e={stack:[ve],tokenStack:[],config:t,enter:c,exit:f,buffer:l,resume:h,data:n},nt=[];let et=-1;for(;++et<G.length;)if(G[et][1].type==="listOrdered"||G[et][1].type==="listUnordered")if(G[et][0]==="enter")nt.push(et);else{const ot=nt.pop();et=i(G,ot,et)}for(et=-1;++et<G.length;){const ot=t[G[et][0]];bv.call(ot,G[et][1].type)&&ot[G[et][1].type].call(Object.assign({sliceSerialize:G[et][2].sliceSerialize},_e),G[et][1])}if(_e.tokenStack.length>0){const ot=_e.tokenStack[_e.tokenStack.length-1];(ot[1]||gb).call(_e,void 0,ot[0])}for(ve.position={start:Si(G.length>0?G[0][1].start:{line:1,column:1,offset:0}),end:Si(G.length>0?G[G.length-2][1].end:{line:1,column:1,offset:0})},et=-1;++et<t.transforms.length;)ve=t.transforms[et](ve)||ve;return ve}function i(G,ve,_e){let nt=ve-1,et=-1,ot=!1,jt,Ft,bt,_t;for(;++nt<=_e;){const xt=G[nt];switch(xt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{xt[0]==="enter"?et++:et--,_t=void 0;break}case"lineEndingBlank":{xt[0]==="enter"&&(jt&&!_t&&!et&&!bt&&(bt=nt),_t=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:_t=void 0}if(!et&&xt[0]==="enter"&&xt[1].type==="listItemPrefix"||et===-1&&xt[0]==="exit"&&(xt[1].type==="listUnordered"||xt[1].type==="listOrdered")){if(jt){let rt=nt;for(Ft=void 0;rt--;){const It=G[rt];if(It[1].type==="lineEnding"||It[1].type==="lineEndingBlank"){if(It[0]==="exit")continue;Ft&&(G[Ft][1].type="lineEndingBlank",ot=!0),It[1].type="lineEnding",Ft=rt}else if(!(It[1].type==="linePrefix"||It[1].type==="blockQuotePrefix"||It[1].type==="blockQuotePrefixWhitespace"||It[1].type==="blockQuoteMarker"||It[1].type==="listItemIndent"))break}bt&&(!Ft||bt<Ft)&&(jt._spread=!0),jt.end=Object.assign({},Ft?G[Ft][1].start:xt[1].end),G.splice(Ft||nt,0,["exit",jt,xt[2]]),nt++,_e++}if(xt[1].type==="listItemPrefix"){const rt={type:"listItem",_spread:!1,start:Object.assign({},xt[1].start),end:void 0};jt=rt,G.splice(nt,0,["enter",rt,xt[2]]),nt++,_e++,bt=void 0,_t=!0}}}return G[ve][1]._spread=ot,_e}function o(G,ve){return _e;function _e(nt){c.call(this,G(nt),nt),ve&&ve.call(this,nt)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(G,ve,_e){this.stack[this.stack.length-1].children.push(G),this.stack.push(G),this.tokenStack.push([ve,_e||void 0]),G.position={start:Si(ve.start),end:void 0}}function u(G){return ve;function ve(_e){G&&G.call(this,_e),f.call(this,_e)}}function f(G,ve){const _e=this.stack.pop(),nt=this.tokenStack.pop();if(nt)nt[0].type!==G.type&&(ve?ve.call(this,G,nt[0]):(nt[1]||gb).call(this,G,nt[0]));else throw new Error("Cannot close `"+G.type+"` ("+Qo({start:G.start,end:G.end})+"): it’s not open");_e.position.end=Si(G.end)}function h(){return zm(this.stack.pop())}function m(){this.data.expectingFirstListItemValue=!0}function g(G){if(this.data.expectingFirstListItemValue){const ve=this.stack[this.stack.length-2];ve.start=Number.parseInt(this.sliceSerialize(G),10),this.data.expectingFirstListItemValue=void 0}}function p(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.lang=G}function b(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.meta=G}function y(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.value=G.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function k(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.value=G.replace(/(\r?\n|\r)$/g,"")}function C(G){const ve=this.resume(),_e=this.stack[this.stack.length-1];_e.label=ve,_e.identifier=_r(this.sliceSerialize(G)).toLowerCase()}function j(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.title=G}function H(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.url=G}function _(G){const ve=this.stack[this.stack.length-1];if(!ve.depth){const _e=this.sliceSerialize(G).length;ve.depth=_e}}function T(){this.data.setextHeadingSlurpLineEnding=!0}function P(G){const ve=this.stack[this.stack.length-1];ve.depth=this.sliceSerialize(G).codePointAt(0)===61?1:2}function z(){this.data.setextHeadingSlurpLineEnding=void 0}function L(G){const _e=this.stack[this.stack.length-1].children;let nt=_e[_e.length-1];(!nt||nt.type!=="text")&&(nt=$e(),nt.position={start:Si(G.start),end:void 0},_e.push(nt)),this.stack.push(nt)}function R(G){const ve=this.stack.pop();ve.value+=this.sliceSerialize(G),ve.position.end=Si(G.end)}function K(G){const ve=this.stack[this.stack.length-1];if(this.data.atHardBreak){const _e=ve.children[ve.children.length-1];_e.position.end=Si(G.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(ve.type)&&(L.call(this,G),R.call(this,G))}function E(){this.data.atHardBreak=!0}function D(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.value=G}function te(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.value=G}function V(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.value=G}function ee(){const G=this.stack[this.stack.length-1];if(this.data.inReference){const ve=this.data.referenceType||"shortcut";G.type+="Reference",G.referenceType=ve,delete G.url,delete G.title}else delete G.identifier,delete G.label;this.data.referenceType=void 0}function U(){const G=this.stack[this.stack.length-1];if(this.data.inReference){const ve=this.data.referenceType||"shortcut";G.type+="Reference",G.referenceType=ve,delete G.url,delete G.title}else delete G.identifier,delete G.label;this.data.referenceType=void 0}function he(G){const ve=this.sliceSerialize(G),_e=this.stack[this.stack.length-2];_e.label=MM(ve),_e.identifier=_r(ve).toLowerCase()}function X(){const G=this.stack[this.stack.length-1],ve=this.resume(),_e=this.stack[this.stack.length-1];if(this.data.inReference=!0,_e.type==="link"){const nt=G.children;_e.children=nt}else _e.alt=ve}function I(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.url=G}function xe(){const G=this.resume(),ve=this.stack[this.stack.length-1];ve.title=G}function le(){this.data.inReference=void 0}function M(){this.data.referenceType="collapsed"}function de(G){const ve=this.resume(),_e=this.stack[this.stack.length-1];_e.label=ve,_e.identifier=_r(this.sliceSerialize(G)).toLowerCase(),this.data.referenceType="full"}function Ne(G){this.data.characterReferenceType=G.type}function ye(G){const ve=this.sliceSerialize(G),_e=this.data.characterReferenceType;let nt;_e?(nt=ov(ve,_e==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):nt=Hm(ve);const et=this.stack[this.stack.length-1];et.value+=nt}function Be(G){const ve=this.stack.pop();ve.position.end=Si(G.end)}function We(G){R.call(this,G);const ve=this.stack[this.stack.length-1];ve.url=this.sliceSerialize(G)}function Ce(G){R.call(this,G);const ve=this.stack[this.stack.length-1];ve.url="mailto:"+this.sliceSerialize(G)}function ke(){return{type:"blockquote",children:[]}}function we(){return{type:"code",lang:null,meta:null,value:""}}function se(){return{type:"inlineCode",value:""}}function ce(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Y(){return{type:"emphasis",children:[]}}function Te(){return{type:"heading",depth:0,children:[]}}function pe(){return{type:"break"}}function fe(){return{type:"html",value:""}}function W(){return{type:"image",title:null,url:"",alt:null}}function Me(){return{type:"link",title:null,url:"",children:[]}}function je(G){return{type:"list",ordered:G.type==="listOrdered",start:null,spread:G._spread,children:[]}}function Q(G){return{type:"listItem",spread:G._spread,checked:null,children:[]}}function ge(){return{type:"paragraph",children:[]}}function Oe(){return{type:"strong",children:[]}}function $e(){return{type:"text",value:""}}function Ve(){return{type:"thematicBreak"}}}function Si(e){return{line:e.line,column:e.column,offset:e.offset}}function yv(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?yv(e,r):OM(e,r)}}function OM(e,t){let n;for(n in t)if(bv.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function gb(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Qo({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Qo({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Qo({start:t.start,end:t.end})+") is still open")}function FM(e){const t=this;t.parser=n;function n(r){return LM(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function _M(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function BM(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
10
+ `}]}function WM(e,t){const n=t.value?t.value+`
11
+ `:"",r={},i=t.lang?t.lang.split(/\s+/):[];i.length>0&&(r.className=["language-"+i[0]]);let o={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function $M(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function zM(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function HM(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),i=go(r.toLowerCase()),o=e.footnoteOrder.indexOf(r);let l,c=e.footnoteCounts.get(r);c===void 0?(c=0,e.footnoteOrder.push(r),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(r,c);const u={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+i,id:n+"fnref-"+i+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(t,u);const f={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(t,f),e.applyData(t,f)}function UM(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function qM(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function xv(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const i=e.all(t),o=i[0];o&&o.type==="text"?o.value="["+o.value:i.unshift({type:"text",value:"["});const l=i[i.length-1];return l&&l.type==="text"?l.value+=r:i.push({type:"text",value:r}),i}function VM(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return xv(e,t);const i={src:go(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const o={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,o),e.applyData(t,o)}function KM(e,t){const n={src:go(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function GM(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function YM(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return xv(e,t);const i={href:go(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const o={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function JM(e,t){const n={href:go(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function XM(e,t,n){const r=e.all(t),i=n?QM(n):kv(t),o={},l=[];if(typeof t.checked=="boolean"){const h=r[0];let m;h&&h.type==="element"&&h.tagName==="p"?m=h:(m={type:"element",tagName:"p",properties:{},children:[]},r.unshift(m)),m.children.length>0&&m.children.unshift({type:"text",value:" "}),m.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<r.length;){const h=r[c];(i||c!==0||h.type!=="element"||h.tagName!=="p")&&l.push({type:"text",value:`
12
+ `}),h.type==="element"&&h.tagName==="p"&&!i?l.push(...h.children):l.push(h)}const u=r[r.length-1];u&&(i||u.type!=="element"||u.tagName!=="p")&&l.push({type:"text",value:`
13
+ `});const f={type:"element",tagName:"li",properties:o,children:l};return e.patch(t,f),e.applyData(t,f)}function QM(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r<n.length;)t=kv(n[r])}return t}function kv(e){const t=e.spread;return t??e.children.length>1}function ZM(e,t){const n={},r=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++i<r.length;){const l=r[i];if(l.type==="element"&&l.tagName==="li"&&l.properties&&Array.isArray(l.properties.className)&&l.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const o={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(r,!0)};return e.patch(t,o),e.applyData(t,o)}function eE(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function tE(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function nE(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function sE(e,t){const n=e.all(t),r=n.shift(),i=[];if(r){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],l),i.push(l)}if(n.length>0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},c=_m(t.children[1]),u=Zw(t.children[t.children.length-1]);c&&u&&(l.position={start:c,end:u}),i.push(l)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,o),e.applyData(t,o)}function rE(e,t,n){const r=n?n.children:void 0,o=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,c=l?l.length:t.children.length;let u=-1;const f=[];for(;++u<c;){const m=t.children[u],g={},p=l?l[u]:void 0;p&&(g.align=p);let b={type:"element",tagName:o,properties:g,children:[]};m&&(b.children=e.all(m),e.patch(m,b),b=e.applyData(m,b)),f.push(b)}const h={type:"element",tagName:"tr",properties:{},children:e.wrap(f,!0)};return e.patch(t,h),e.applyData(t,h)}function iE(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const bb=9,yb=32;function aE(e){const t=String(e),n=/\r?\n|\r/g;let r=n.exec(t),i=0;const o=[];for(;r;)o.push(xb(t.slice(i,r.index),i>0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return o.push(xb(t.slice(i),i>0,!1)),o.join("")}function xb(e,t,n){let r=0,i=e.length;if(t){let o=e.codePointAt(r);for(;o===bb||o===yb;)r++,o=e.codePointAt(r)}if(n){let o=e.codePointAt(i-1);for(;o===bb||o===yb;)i--,o=e.codePointAt(i-1)}return i>r?e.slice(r,i):""}function oE(e,t){const n={type:"text",value:aE(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function lE(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const cE={blockquote:_M,break:BM,code:WM,delete:$M,emphasis:zM,footnoteReference:HM,heading:UM,html:qM,imageReference:VM,image:KM,inlineCode:GM,linkReference:YM,link:JM,listItem:XM,list:ZM,paragraph:eE,root:tE,strong:nE,table:sE,tableCell:iE,tableRow:rE,text:oE,thematicBreak:lE,toml:cc,yaml:cc,definition:cc,footnoteDefinition:cc};function cc(){}const wv=-1,Ku=0,el=1,mu=2,qm=3,Vm=4,Km=5,Gm=6,vv=7,Sv=8,kb=typeof self=="object"?self:globalThis,uE=(e,t)=>{const n=(i,o)=>(e.set(o,i),i),r=i=>{if(e.has(i))return e.get(i);const[o,l]=t[i];switch(o){case Ku:case wv:return n(l,i);case el:{const c=n([],i);for(const u of l)c.push(r(u));return c}case mu:{const c=n({},i);for(const[u,f]of l)c[r(u)]=r(f);return c}case qm:return n(new Date(l),i);case Vm:{const{source:c,flags:u}=l;return n(new RegExp(c,u),i)}case Km:{const c=n(new Map,i);for(const[u,f]of l)c.set(r(u),r(f));return c}case Gm:{const c=n(new Set,i);for(const u of l)c.add(r(u));return c}case vv:{const{name:c,message:u}=l;return n(new kb[c](u),i)}case Sv:return n(BigInt(l),i);case"BigInt":return n(Object(BigInt(l)),i);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:c}=new Uint8Array(l);return n(new DataView(c),l)}}return n(new kb[o](l),i)};return r},wb=e=>uE(new Map,e)(0),Sa="",{toString:dE}={},{keys:fE}=Object,Po=e=>{const t=typeof e;if(t!=="object"||!e)return[Ku,t];const n=dE.call(e).slice(8,-1);switch(n){case"Array":return[el,Sa];case"Object":return[mu,Sa];case"Date":return[qm,Sa];case"RegExp":return[Vm,Sa];case"Map":return[Km,Sa];case"Set":return[Gm,Sa];case"DataView":return[el,n]}return n.includes("Array")?[el,n]:n.includes("Error")?[vv,n]:[mu,n]},uc=([e,t])=>e===Ku&&(t==="function"||t==="symbol"),hE=(e,t,n,r)=>{const i=(l,c)=>{const u=r.push(l)-1;return n.set(c,u),u},o=l=>{if(n.has(l))return n.get(l);let[c,u]=Po(l);switch(c){case Ku:{let h=l;switch(u){case"bigint":c=Sv,h=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);h=null;break;case"undefined":return i([wv],l)}return i([c,h],l)}case el:{if(u){let g=l;return u==="DataView"?g=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(g=new Uint8Array(l)),i([u,[...g]],l)}const h=[],m=i([c,h],l);for(const g of l)h.push(o(g));return m}case mu:{if(u)switch(u){case"BigInt":return i([u,l.toString()],l);case"Boolean":case"Number":case"String":return i([u,l.valueOf()],l)}if(t&&"toJSON"in l)return o(l.toJSON());const h=[],m=i([c,h],l);for(const g of fE(l))(e||!uc(Po(l[g])))&&h.push([o(g),o(l[g])]);return m}case qm:return i([c,l.toISOString()],l);case Vm:{const{source:h,flags:m}=l;return i([c,{source:h,flags:m}],l)}case Km:{const h=[],m=i([c,h],l);for(const[g,p]of l)(e||!(uc(Po(g))||uc(Po(p))))&&h.push([o(g),o(p)]);return m}case Gm:{const h=[],m=i([c,h],l);for(const g of l)(e||!uc(Po(g)))&&h.push(o(g));return m}}const{message:f}=l;return i([c,{name:u,message:f}],l)};return o},vb=(e,{json:t,lossy:n}={})=>{const r=[];return hE(!(t||n),!!t,new Map,r)(e),r},pu=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?wb(vb(e,t)):structuredClone(e):(e,t)=>wb(vb(e,t));function mE(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function pE(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function gE(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||mE,r=e.options.footnoteBackLabel||pE,i=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const f=e.footnoteById.get(e.footnoteOrder[u]);if(!f)continue;const h=e.all(f),m=String(f.identifier).toUpperCase(),g=go(m.toLowerCase());let p=0;const b=[],y=e.footnoteCounts.get(m);for(;y!==void 0&&++p<=y;){b.length>0&&b.push({type:"text",value:" "});let C=typeof n=="string"?n:n(u,p);typeof C=="string"&&(C={type:"text",value:C}),b.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(u,p),className:["data-footnote-backref"]},children:Array.isArray(C)?C:[C]})}const x=h[h.length-1];if(x&&x.type==="element"&&x.tagName==="p"){const C=x.children[x.children.length-1];C&&C.type==="text"?C.value+=" ":x.children.push({type:"text",value:" "}),x.children.push(...b)}else h.push(...b);const k={type:"element",tagName:"li",properties:{id:t+"fn-"+g},children:e.wrap(h,!0)};e.patch(f,k),c.push(k)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...pu(l),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:`
14
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
15
+ `}]}}const Gu=(function(e){if(e==null)return kE;if(typeof e=="function")return Yu(e);if(typeof e=="object")return Array.isArray(e)?bE(e):yE(e);if(typeof e=="string")return xE(e);throw new Error("Expected function, string, or object as test")});function bE(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Gu(e[n]);return Yu(r);function r(...i){let o=-1;for(;++o<t.length;)if(t[o].apply(this,i))return!0;return!1}}function yE(e){const t=e;return Yu(n);function n(r){const i=r;let o;for(o in e)if(i[o]!==t[o])return!1;return!0}}function xE(e){return Yu(t);function t(n){return n&&n.type===e}}function Yu(e){return t;function t(n,r,i){return!!(wE(n)&&e.call(this,n,typeof r=="number"?r:void 0,i||void 0))}}function kE(){return!0}function wE(e){return e!==null&&typeof e=="object"&&"type"in e}const Cv=[],vE=!0,xh=!1,SE="skip";function jv(e,t,n,r){let i;typeof t=="function"&&typeof n!="function"?(r=n,n=t):i=t;const o=Gu(i),l=r?-1:1;c(e,void 0,[])();function c(u,f,h){const m=u&&typeof u=="object"?u:{};if(typeof m.type=="string"){const p=typeof m.tagName=="string"?m.tagName:typeof m.name=="string"?m.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=Cv,b,y,x;if((!t||o(u,f,h[h.length-1]||void 0))&&(p=CE(n(u,h)),p[0]===xh))return p;if("children"in u&&u.children){const k=u;if(k.children&&p[0]!==SE)for(y=(r?k.children.length:-1)+l,x=h.concat(k);y>-1&&y<k.children.length;){const C=k.children[y];if(b=c(C,y,x)(),b[0]===xh)return b;y=typeof b[1]=="number"?b[1]:y+l}}return p}}}function CE(e){return Array.isArray(e)?e:typeof e=="number"?[vE,e]:e==null?Cv:[e]}function Ym(e,t,n,r){let i,o,l;typeof t=="function"&&typeof n!="function"?(o=void 0,l=t,i=n):(o=t,l=n,i=r),jv(e,o,c,i);function c(u,f){const h=f[f.length-1],m=h?h.children.indexOf(u):void 0;return l(u,m,h)}}const kh={}.hasOwnProperty,jE={};function NE(e,t){const n=t||jE,r=new Map,i=new Map,o=new Map,l={...cE,...n.handlers},c={all:f,applyData:IE,definitionById:r,footnoteById:i,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:n,patch:TE,wrap:RE};return Ym(e,function(h){if(h.type==="definition"||h.type==="footnoteDefinition"){const m=h.type==="definition"?r:i,g=String(h.identifier).toUpperCase();m.has(g)||m.set(g,h)}}),c;function u(h,m){const g=h.type,p=c.handlers[g];if(kh.call(c.handlers,g)&&p)return p(c,h,m);if(c.options.passThrough&&c.options.passThrough.includes(g)){if("children"in h){const{children:y,...x}=h,k=pu(x);return k.children=c.all(h),k}return pu(h)}return(c.options.unknownHandler||AE)(c,h,m)}function f(h){const m=[];if("children"in h){const g=h.children;let p=-1;for(;++p<g.length;){const b=c.one(g[p],h);if(b){if(p&&g[p-1].type==="break"&&(!Array.isArray(b)&&b.type==="text"&&(b.value=Sb(b.value)),!Array.isArray(b)&&b.type==="element")){const y=b.children[0];y&&y.type==="text"&&(y.value=Sb(y.value))}Array.isArray(b)?m.push(...b):m.push(b)}}}return m}}function TE(e,t){e.position&&(t.position=pR(e))}function IE(e,t){let n=t;if(e&&e.data){const r=e.data.hName,i=e.data.hChildren,o=e.data.hProperties;if(typeof r=="string")if(n.type==="element")n.tagName=r;else{const l="children"in n?n.children:[n];n={type:"element",tagName:r,properties:{},children:l}}n.type==="element"&&o&&Object.assign(n.properties,pu(o)),"children"in n&&n.children&&i!==null&&i!==void 0&&(n.children=i)}return n}function AE(e,t){const n=t.data||{},r="value"in t&&!(kh.call(n,"hProperties")||kh.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function RE(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:`
16
+ `});++r<e.length;)r&&n.push({type:"text",value:`
17
+ `}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:`
18
+ `}),n}function Sb(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Cb(e,t){const n=NE(e,t),r=n.one(e,void 0),i=gE(n),o=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&o.children.push({type:"text",value:`
19
+ `},i),o}function PE(e,t){return e&&"run"in e?async function(n,r){const i=Cb(n,{file:r,...t});await e.run(i,r)}:function(n,r){return Cb(n,{file:r,...e||t})}}function jb(e){if(e)throw e}var $d,Nb;function ME(){if(Nb)return $d;Nb=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var h=e.call(f,"constructor"),m=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!h&&!m)return!1;var g;for(g in f);return typeof g>"u"||e.call(f,g)},l=function(f,h){n&&h.name==="__proto__"?n(f,h.name,{enumerable:!0,configurable:!0,value:h.newValue,writable:!0}):f[h.name]=h.newValue},c=function(f,h){if(h==="__proto__")if(e.call(f,h)){if(r)return r(f,h).value}else return;return f[h]};return $d=function u(){var f,h,m,g,p,b,y=arguments[0],x=1,k=arguments.length,C=!1;for(typeof y=="boolean"&&(C=y,y=arguments[1]||{},x=2),(y==null||typeof y!="object"&&typeof y!="function")&&(y={});x<k;++x)if(f=arguments[x],f!=null)for(h in f)m=c(y,h),g=c(f,h),y!==g&&(C&&g&&(o(g)||(p=i(g)))?(p?(p=!1,b=m&&i(m)?m:[]):b=m&&o(m)?m:{},l(y,{name:h,newValue:u(C,b,g)})):typeof g<"u"&&l(y,{name:h,newValue:g}));return y},$d}var EE=ME();const zd=Ok(EE);function wh(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function LE(){const e=[],t={run:n,use:r};return t;function n(...i){let o=-1;const l=i.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);c(null,...i);function c(u,...f){const h=e[++o];let m=-1;if(u){l(u);return}for(;++m<i.length;)(f[m]===null||f[m]===void 0)&&(f[m]=i[m]);i=f,h?DE(h,c)(...f):l(null,...f)}}function r(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function DE(e,t){let n;return r;function r(...l){const c=e.length>l.length;let u;c&&l.push(i);try{u=e.apply(this,l)}catch(f){const h=f;if(c&&n)throw h;return i(h)}c||(u&&u.then&&typeof u.then=="function"?u.then(o,i):u instanceof Error?i(u):o(u))}function i(l,...c){n||(n=!0,t(l,...c))}function o(l){i(null,l)}}const Kr={basename:OE,dirname:FE,extname:_E,join:BE,sep:"/"};function OE(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Ml(e);let n=0,r=-1,i=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(o){n=i+1;break}}else r<0&&(o=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let l=-1,c=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(o){n=i+1;break}}else l<0&&(o=!0,l=i+1),c>-1&&(e.codePointAt(i)===t.codePointAt(c--)?c<0&&(r=i):(c=-1,r=l));return n===r?r=l:r<0&&(r=e.length),e.slice(n,r)}function FE(e){if(Ml(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function _E(e){Ml(e);let t=e.length,n=-1,r=0,i=-1,o=0,l;for(;t--;){const c=e.codePointAt(t);if(c===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),c===46?i<0?i=t:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||n<0||o===0||o===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function BE(...e){let t=-1,n;for(;++t<e.length;)Ml(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":WE(n)}function WE(e){Ml(e);const t=e.codePointAt(0)===47;let n=$E(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function $E(e,t){let n="",r=0,i=-1,o=0,l=-1,c,u;for(;++l<=e.length;){if(l<e.length)c=e.codePointAt(l);else{if(c===47)break;c=47}if(c===47){if(!(i===l-1||o===1))if(i!==l-1&&o===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(u=n.lastIndexOf("/"),u!==n.length-1){u<0?(n="",r=0):(n=n.slice(0,u),r=n.length-1-n.lastIndexOf("/")),i=l,o=0;continue}}else if(n.length>0){n="",r=0,i=l,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,l):n=e.slice(i+1,l),r=l-i-1;i=l,o=0}else c===46&&o>-1?o++:o=-1}return n}function Ml(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const zE={cwd:HE};function HE(){return"/"}function vh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function UE(e){if(typeof e=="string")e=new URL(e);else if(!vh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return qE(e)}function qE(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}const Hd=["history","path","basename","stem","extname","dirname"];class Nv{constructor(t){let n;t?vh(t)?n={path:t}:typeof t=="string"||VE(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":zE.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Hd.length;){const o=Hd[r];o in n&&n[o]!==void 0&&n[o]!==null&&(this[o]=o==="history"?[...n[o]]:n[o])}let i;for(i in n)Hd.includes(i)||(this[i]=n[i])}get basename(){return typeof this.path=="string"?Kr.basename(this.path):void 0}set basename(t){qd(t,"basename"),Ud(t,"basename"),this.path=Kr.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Kr.dirname(this.path):void 0}set dirname(t){Tb(this.basename,"dirname"),this.path=Kr.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Kr.extname(this.path):void 0}set extname(t){if(Ud(t,"extname"),Tb(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Kr.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){vh(t)&&(t=UE(t)),qd(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Kr.basename(this.path,this.extname):void 0}set stem(t){qd(t,"stem"),Ud(t,"stem"),this.path=Kr.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const i=this.message(t,n,r);throw i.fatal=!0,i}info(t,n,r){const i=this.message(t,n,r);return i.fatal=void 0,i}message(t,n,r){const i=new Js(t,n,r);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Ud(e,t){if(e&&e.includes(Kr.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Kr.sep+"`")}function qd(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Tb(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function VE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const KE=(function(e){const r=this.constructor.prototype,i=r[e],o=function(){return i.apply(o,arguments)};return Object.setPrototypeOf(o,r),o}),GE={}.hasOwnProperty;class Jm extends KE{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=LE()}copy(){const t=new Jm;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(zd(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Gd("data",this.frozen),this.namespace[t]=n,this):GE.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Gd("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const i=n.call(t,...r);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=dc(t),r=this.parser||this.Parser;return Vd("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),Vd("process",this.parser||this.Parser),Kd("process",this.compiler||this.Compiler),n?i(void 0,n):new Promise(i);function i(o,l){const c=dc(t),u=r.parse(c);r.run(u,c,function(h,m,g){if(h||!m||!g)return f(h);const p=m,b=r.stringify(p,g);XE(b)?g.value=b:g.result=b,f(h,g)});function f(h,m){h||!m?l(h):o?o(m):n(void 0,m)}}}processSync(t){let n=!1,r;return this.freeze(),Vd("processSync",this.parser||this.Parser),Kd("processSync",this.compiler||this.Compiler),this.process(t,i),Ab("processSync","process",n),r;function i(o,l){n=!0,jb(o),r=l}}run(t,n,r){Ib(t),this.freeze();const i=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?o(void 0,r):new Promise(o);function o(l,c){const u=dc(n);i.run(t,u,f);function f(h,m,g){const p=m||t;h?c(h):l?l(p):r(void 0,p,g)}}}runSync(t,n){let r=!1,i;return this.run(t,n,o),Ab("runSync","run",r),i;function o(l,c){jb(l),i=c,r=!0}}stringify(t,n){this.freeze();const r=dc(n),i=this.compiler||this.Compiler;return Kd("stringify",i),Ib(t),i(t,r)}use(t,...n){const r=this.attachers,i=this.namespace;if(Gd("use",this.frozen),t!=null)if(typeof t=="function")u(t,n);else if(typeof t=="object")Array.isArray(t)?c(t):l(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function o(f){if(typeof f=="function")u(f,[]);else if(typeof f=="object")if(Array.isArray(f)){const[h,...m]=f;u(h,m)}else l(f);else throw new TypeError("Expected usable value, not `"+f+"`")}function l(f){if(!("plugins"in f)&&!("settings"in f))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");c(f.plugins),f.settings&&(i.settings=zd(!0,i.settings,f.settings))}function c(f){let h=-1;if(f!=null)if(Array.isArray(f))for(;++h<f.length;){const m=f[h];o(m)}else throw new TypeError("Expected a list of plugins, not `"+f+"`")}function u(f,h){let m=-1,g=-1;for(;++m<r.length;)if(r[m][0]===f){g=m;break}if(g===-1)r.push([f,...h]);else if(h.length>0){let[p,...b]=h;const y=r[g][1];wh(y)&&wh(p)&&(p=zd(!0,y,p)),r[g]=[f,p,...b]}}}}const YE=new Jm().freeze();function Vd(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Kd(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Gd(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Ib(e){if(!wh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ab(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function dc(e){return JE(e)?e:new Nv(e)}function JE(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function XE(e){return typeof e=="string"||QE(e)}function QE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ZE="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Rb=[],Pb={allowDangerousHtml:!0},eL=/^(https?|ircs?|mailto|xmpp)$/i,tL=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Tv(e){const t=nL(e),n=sL(e);return rL(t.runSync(t.parse(n),n),e)}function nL(e){const t=e.rehypePlugins||Rb,n=e.remarkPlugins||Rb,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Pb}:Pb;return YE().use(FM).use(n).use(PE,r).use(t)}function sL(e){const t=e.children||"",n=new Nv;return typeof t=="string"&&(n.value=t),n}function rL(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,o=t.disallowedElements,l=t.skipHtml,c=t.unwrapDisallowed,u=t.urlTransform||iL;for(const h of tL)Object.hasOwn(t,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+ZE+h.id,void 0);return Ym(e,f),kR(e,{Fragment:s.Fragment,components:i,ignoreInvalidStyle:!0,jsx:s.jsx,jsxs:s.jsxs,passKeys:!0,passNode:!0});function f(h,m,g){if(h.type==="raw"&&g&&typeof m=="number")return l?g.children.splice(m,1):g.children[m]={type:"text",value:h.value},m;if(h.type==="element"){let p;for(p in _d)if(Object.hasOwn(_d,p)&&Object.hasOwn(h.properties,p)){const b=h.properties[p],y=_d[p];(y===null||y.includes(h.tagName))&&(h.properties[p]=u(String(b||""),p,h))}}if(h.type==="element"){let p=n?!n.includes(h.tagName):o?o.includes(h.tagName):!1;if(!p&&r&&typeof m=="number"&&(p=!r(h,m,g)),p&&g&&typeof m=="number")return c&&h.children?g.children.splice(m,1,...h.children):g.children.splice(m,1),m}}}function iL(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||eL.test(e.slice(0,t))?e:""}function Mb(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function aL(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function oL(e,t,n){const i=Gu((n||{}).ignore||[]),o=lL(t);let l=-1;for(;++l<o.length;)jv(e,"text",c);function c(f,h){let m=-1,g;for(;++m<h.length;){const p=h[m],b=g?g.children:void 0;if(i(p,b?b.indexOf(p):void 0,g))return;g=p}if(g)return u(f,h)}function u(f,h){const m=h[h.length-1],g=o[l][0],p=o[l][1];let b=0;const x=m.children.indexOf(f);let k=!1,C=[];g.lastIndex=0;let j=g.exec(f.value);for(;j;){const H=j.index,_={index:j.index,input:j.input,stack:[...h,f]};let T=p(...j,_);if(typeof T=="string"&&(T=T.length>0?{type:"text",value:T}:void 0),T===!1?g.lastIndex=H+1:(b!==H&&C.push({type:"text",value:f.value.slice(b,H)}),Array.isArray(T)?C.push(...T):T&&C.push(T),b=H+j[0].length,k=!0),!g.global)break;j=g.exec(f.value)}return k?(b<f.value.length&&C.push({type:"text",value:f.value.slice(b)}),m.children.splice(x,1,...C)):C=[f],x+C.length}}function lL(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const n=!e[0]||Array.isArray(e[0])?e:[e];let r=-1;for(;++r<n.length;){const i=n[r];t.push([cL(i[0]),uL(i[1])])}return t}function cL(e){return typeof e=="string"?new RegExp(aL(e),"g"):e}function uL(e){return typeof e=="function"?e:function(){return e}}const Yd="phrasing",Jd=["autolink","link","image","label"];function dL(){return{transforms:[yL],enter:{literalAutolink:hL,literalAutolinkEmail:Xd,literalAutolinkHttp:Xd,literalAutolinkWww:Xd},exit:{literalAutolink:bL,literalAutolinkEmail:gL,literalAutolinkHttp:mL,literalAutolinkWww:pL}}}function fL(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Yd,notInConstruct:Jd},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Yd,notInConstruct:Jd},{character:":",before:"[ps]",after:"\\/",inConstruct:Yd,notInConstruct:Jd}]}}function hL(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Xd(e){this.config.enter.autolinkProtocol.call(this,e)}function mL(e){this.config.exit.autolinkProtocol.call(this,e)}function pL(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function gL(e){this.config.exit.autolinkEmail.call(this,e)}function bL(e){this.exit(e)}function yL(e){oL(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,xL],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),kL]],{ignore:["link","linkReference"]})}function xL(e,t,n,r,i){let o="";if(!Iv(i)||(/^w/i.test(t)&&(n=t+n,t="",o="http://"),!wL(n)))return!1;const l=vL(n+r);if(!l[0])return!1;const c={type:"link",title:null,url:o+t+l[0],children:[{type:"text",value:t+l[0]}]};return l[1]?[c,{type:"text",value:l[1]}]:c}function kL(e,t,n,r){return!Iv(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function wL(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function vL(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const i=Mb(e,"(");let o=Mb(e,")");for(;r!==-1&&i>o;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),o++;return[e,n]}function Iv(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||ma(n)||qu(n))&&(!t||n!==47)}Av.peek=PL;function SL(){this.buffer()}function CL(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function jL(){this.buffer()}function NL(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function TL(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=_r(this.sliceSerialize(e)).toLowerCase(),n.label=t}function IL(e){this.exit(e)}function AL(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=_r(this.sliceSerialize(e)).toLowerCase(),n.label=t}function RL(e){this.exit(e)}function PL(){return"["}function Av(e,t,n,r){const i=n.createTracker(r);let o=i.move("[^");const l=n.enter("footnoteReference"),c=n.enter("reference");return o+=i.move(n.safe(n.associationId(e),{after:"]",before:o})),c(),l(),o+=i.move("]"),o}function ML(){return{enter:{gfmFootnoteCallString:SL,gfmFootnoteCall:CL,gfmFootnoteDefinitionLabelString:jL,gfmFootnoteDefinition:NL},exit:{gfmFootnoteCallString:TL,gfmFootnoteCall:IL,gfmFootnoteDefinitionLabelString:AL,gfmFootnoteDefinition:RL}}}function EL(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Av},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,o,l){const c=o.createTracker(l);let u=c.move("[^");const f=o.enter("footnoteDefinition"),h=o.enter("label");return u+=c.move(o.safe(o.associationId(r),{before:u,after:"]"})),h(),u+=c.move("]:"),r.children&&r.children.length>0&&(c.shift(4),u+=c.move((t?`
20
+ `:" ")+o.indentLines(o.containerFlow(r,c.current()),t?Rv:LL))),f(),u}}function LL(e,t,n){return t===0?e:Rv(e,t,n)}function Rv(e,t,n){return(n?"":" ")+e}const DL=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Pv.peek=WL;function OL(){return{canContainEols:["delete"],enter:{strikethrough:_L},exit:{strikethrough:BL}}}function FL(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:DL}],handlers:{delete:Pv}}}function _L(e){this.enter({type:"delete",children:[]},e)}function BL(e){this.exit(e)}function Pv(e,t,n,r){const i=n.createTracker(r),o=n.enter("strikethrough");let l=i.move("~~");return l+=n.containerPhrasing(e,{...i.current(),before:l,after:"~"}),l+=i.move("~~"),o(),l}function WL(){return"~"}function $L(e){return e.length}function zL(e,t){const n=t||{},r=(n.align||[]).concat(),i=n.stringLength||$L,o=[],l=[],c=[],u=[];let f=0,h=-1;for(;++h<e.length;){const y=[],x=[];let k=-1;for(e[h].length>f&&(f=e[h].length);++k<e[h].length;){const C=HL(e[h][k]);if(n.alignDelimiters!==!1){const j=i(C);x[k]=j,(u[k]===void 0||j>u[k])&&(u[k]=j)}y.push(C)}l[h]=y,c[h]=x}let m=-1;if(typeof r=="object"&&"length"in r)for(;++m<f;)o[m]=Eb(r[m]);else{const y=Eb(r);for(;++m<f;)o[m]=y}m=-1;const g=[],p=[];for(;++m<f;){const y=o[m];let x="",k="";y===99?(x=":",k=":"):y===108?x=":":y===114&&(k=":");let C=n.alignDelimiters===!1?1:Math.max(1,u[m]-x.length-k.length);const j=x+"-".repeat(C)+k;n.alignDelimiters!==!1&&(C=x.length+C+k.length,C>u[m]&&(u[m]=C),p[m]=C),g[m]=j}l.splice(1,0,g),c.splice(1,0,p),h=-1;const b=[];for(;++h<l.length;){const y=l[h],x=c[h];m=-1;const k=[];for(;++m<f;){const C=y[m]||"";let j="",H="";if(n.alignDelimiters!==!1){const _=u[m]-(x[m]||0),T=o[m];T===114?j=" ".repeat(_):T===99?_%2?(j=" ".repeat(_/2+.5),H=" ".repeat(_/2-.5)):(j=" ".repeat(_/2),H=j):H=" ".repeat(_)}n.delimiterStart!==!1&&!m&&k.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&C==="")&&(n.delimiterStart!==!1||m)&&k.push(" "),n.alignDelimiters!==!1&&k.push(j),k.push(C),n.alignDelimiters!==!1&&k.push(H),n.padding!==!1&&k.push(" "),(n.delimiterEnd!==!1||m!==f-1)&&k.push("|")}b.push(n.delimiterEnd===!1?k.join("").replace(/ +$/,""):k.join(""))}return b.join(`
21
+ `)}function HL(e){return e==null?"":String(e)}function Eb(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function UL(e,t,n,r){const i=n.enter("blockquote"),o=n.createTracker(r);o.move("> "),o.shift(2);const l=n.indentLines(n.containerFlow(e,o.current()),qL);return i(),l}function qL(e,t,n){return">"+(n?"":" ")+e}function VL(e,t){return Lb(e,t.inConstruct,!0)&&!Lb(e,t.notInConstruct,!1)}function Lb(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function Db(e,t,n,r){let i=-1;for(;++i<n.unsafe.length;)if(n.unsafe[i].character===`
22
+ `&&VL(n.stack,n.unsafe[i]))return/[ \t]/.test(r.before)?"":" ";return`\\
23
+ `}function KL(e,t){const n=String(e);let r=n.indexOf(t),i=r,o=0,l=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;r!==-1;)r===i?++o>l&&(l=o):o=1,i=r+t.length,r=n.indexOf(t,i);return l}function GL(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function YL(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function JL(e,t,n,r){const i=YL(n),o=e.value||"",l=i==="`"?"GraveAccent":"Tilde";if(GL(e,n)){const m=n.enter("codeIndented"),g=n.indentLines(o,XL);return m(),g}const c=n.createTracker(r),u=i.repeat(Math.max(KL(o,i)+1,3)),f=n.enter("codeFenced");let h=c.move(u);if(e.lang){const m=n.enter(`codeFencedLang${l}`);h+=c.move(n.safe(e.lang,{before:h,after:" ",encode:["`"],...c.current()})),m()}if(e.lang&&e.meta){const m=n.enter(`codeFencedMeta${l}`);h+=c.move(" "),h+=c.move(n.safe(e.meta,{before:h,after:`
24
+ `,encode:["`"],...c.current()})),m()}return h+=c.move(`
25
+ `),o&&(h+=c.move(o+`
26
+ `)),h+=c.move(u),f(),h}function XL(e,t,n){return(n?"":" ")+e}function Xm(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function QL(e,t,n,r){const i=Xm(n),o=i==='"'?"Quote":"Apostrophe",l=n.enter("definition");let c=n.enter("label");const u=n.createTracker(r);let f=u.move("[");return f+=u.move(n.safe(n.associationId(e),{before:f,after:"]",...u.current()})),f+=u.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),f+=u.move("<"),f+=u.move(n.safe(e.url,{before:f,after:">",...u.current()})),f+=u.move(">")):(c=n.enter("destinationRaw"),f+=u.move(n.safe(e.url,{before:f,after:e.title?" ":`
27
+ `,...u.current()}))),c(),e.title&&(c=n.enter(`title${o}`),f+=u.move(" "+i),f+=u.move(n.safe(e.title,{before:f,after:i,...u.current()})),f+=u.move(i),c()),l(),f}function ZL(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function hl(e){return"&#x"+e.toString(16).toUpperCase()+";"}function gu(e,t,n){const r=ro(e),i=ro(t);return r===void 0?i===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Mv.peek=eD;function Mv(e,t,n,r){const i=ZL(n),o=n.enter("emphasis"),l=n.createTracker(r),c=l.move(i);let u=l.move(n.containerPhrasing(e,{after:i,before:c,...l.current()}));const f=u.charCodeAt(0),h=gu(r.before.charCodeAt(r.before.length-1),f,i);h.inside&&(u=hl(f)+u.slice(1));const m=u.charCodeAt(u.length-1),g=gu(r.after.charCodeAt(0),m,i);g.inside&&(u=u.slice(0,-1)+hl(m));const p=l.move(i);return o(),n.attentionEncodeSurroundingInfo={after:g.outside,before:h.outside},c+u+p}function eD(e,t,n){return n.options.emphasis||"*"}function tD(e,t){let n=!1;return Ym(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,xh}),!!((!e.depth||e.depth<3)&&zm(e)&&(t.options.setext||n))}function nD(e,t,n,r){const i=Math.max(Math.min(6,e.depth||1),1),o=n.createTracker(r);if(tD(e,n)){const h=n.enter("headingSetext"),m=n.enter("phrasing"),g=n.containerPhrasing(e,{...o.current(),before:`
28
+ `,after:`
29
+ `});return m(),h(),g+`
30
+ `+(i===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
31
+ `))+1))}const l="#".repeat(i),c=n.enter("headingAtx"),u=n.enter("phrasing");o.move(l+" ");let f=n.containerPhrasing(e,{before:"# ",after:`
32
+ `,...o.current()});return/^[\t ]/.test(f)&&(f=hl(f.charCodeAt(0))+f.slice(1)),f=f?l+" "+f:l,n.options.closeAtx&&(f+=" "+l),u(),c(),f}Ev.peek=sD;function Ev(e){return e.value||""}function sD(){return"<"}Lv.peek=rD;function Lv(e,t,n,r){const i=Xm(n),o=i==='"'?"Quote":"Apostrophe",l=n.enter("image");let c=n.enter("label");const u=n.createTracker(r);let f=u.move("![");return f+=u.move(n.safe(e.alt,{before:f,after:"]",...u.current()})),f+=u.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),f+=u.move("<"),f+=u.move(n.safe(e.url,{before:f,after:">",...u.current()})),f+=u.move(">")):(c=n.enter("destinationRaw"),f+=u.move(n.safe(e.url,{before:f,after:e.title?" ":")",...u.current()}))),c(),e.title&&(c=n.enter(`title${o}`),f+=u.move(" "+i),f+=u.move(n.safe(e.title,{before:f,after:i,...u.current()})),f+=u.move(i),c()),f+=u.move(")"),l(),f}function rD(){return"!"}Dv.peek=iD;function Dv(e,t,n,r){const i=e.referenceType,o=n.enter("imageReference");let l=n.enter("label");const c=n.createTracker(r);let u=c.move("![");const f=n.safe(e.alt,{before:u,after:"]",...c.current()});u+=c.move(f+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const m=n.safe(n.associationId(e),{before:u,after:"]",...c.current()});return l(),n.stack=h,o(),i==="full"||!f||f!==m?u+=c.move(m+"]"):i==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function iD(){return"!"}Ov.peek=aD;function Ov(e,t,n){let r=e.value||"",i="`",o=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++o<n.unsafe.length;){const l=n.unsafe[o],c=n.compilePattern(l);let u;if(l.atBreak)for(;u=c.exec(r);){let f=u.index;r.charCodeAt(f)===10&&r.charCodeAt(f-1)===13&&f--,r=r.slice(0,f)+" "+r.slice(u.index+1)}}return i+r+i}function aD(){return"`"}function Fv(e,t){const n=zm(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}_v.peek=oD;function _v(e,t,n,r){const i=Xm(n),o=i==='"'?"Quote":"Apostrophe",l=n.createTracker(r);let c,u;if(Fv(e,n)){const h=n.stack;n.stack=[],c=n.enter("autolink");let m=l.move("<");return m+=l.move(n.containerPhrasing(e,{before:m,after:">",...l.current()})),m+=l.move(">"),c(),n.stack=h,m}c=n.enter("link"),u=n.enter("label");let f=l.move("[");return f+=l.move(n.containerPhrasing(e,{before:f,after:"](",...l.current()})),f+=l.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=n.enter("destinationLiteral"),f+=l.move("<"),f+=l.move(n.safe(e.url,{before:f,after:">",...l.current()})),f+=l.move(">")):(u=n.enter("destinationRaw"),f+=l.move(n.safe(e.url,{before:f,after:e.title?" ":")",...l.current()}))),u(),e.title&&(u=n.enter(`title${o}`),f+=l.move(" "+i),f+=l.move(n.safe(e.title,{before:f,after:i,...l.current()})),f+=l.move(i),u()),f+=l.move(")"),c(),f}function oD(e,t,n){return Fv(e,n)?"<":"["}Bv.peek=lD;function Bv(e,t,n,r){const i=e.referenceType,o=n.enter("linkReference");let l=n.enter("label");const c=n.createTracker(r);let u=c.move("[");const f=n.containerPhrasing(e,{before:u,after:"]",...c.current()});u+=c.move(f+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const m=n.safe(n.associationId(e),{before:u,after:"]",...c.current()});return l(),n.stack=h,o(),i==="full"||!f||f!==m?u+=c.move(m+"]"):i==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function lD(){return"["}function Qm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function cD(e){const t=Qm(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function uD(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function Wv(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function dD(e,t,n,r){const i=n.enter("list"),o=n.bulletCurrent;let l=e.ordered?uD(n):Qm(n);const c=e.ordered?l==="."?")":".":cD(n);let u=t&&n.bulletLastUsed?l===n.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&h&&(!h.children||!h.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(u=!0),Wv(n)===l&&h){let m=-1;for(;++m<e.children.length;){const g=e.children[m];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),n.bulletCurrent=l;const f=n.containerFlow(e,r);return n.bulletLastUsed=l,n.bulletCurrent=o,i(),f}function fD(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function hD(e,t,n,r){const i=fD(n);let o=n.bulletCurrent||Qm(n);t&&t.type==="list"&&t.ordered&&(o=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let l=o.length+1;(i==="tab"||i==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=n.createTracker(r);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=n.enter("listItem"),f=n.indentLines(n.containerFlow(e,c.current()),h);return u(),f;function h(m,g,p){return g?(p?"":" ".repeat(l))+m:(p?o:o+" ".repeat(l-o.length))+m}}function mD(e,t,n,r){const i=n.enter("paragraph"),o=n.enter("phrasing"),l=n.containerPhrasing(e,r);return o(),i(),l}const pD=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function gD(e,t,n,r){return(e.children.some(function(l){return pD(l)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function bD(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}$v.peek=yD;function $v(e,t,n,r){const i=bD(n),o=n.enter("strong"),l=n.createTracker(r),c=l.move(i+i);let u=l.move(n.containerPhrasing(e,{after:i,before:c,...l.current()}));const f=u.charCodeAt(0),h=gu(r.before.charCodeAt(r.before.length-1),f,i);h.inside&&(u=hl(f)+u.slice(1));const m=u.charCodeAt(u.length-1),g=gu(r.after.charCodeAt(0),m,i);g.inside&&(u=u.slice(0,-1)+hl(m));const p=l.move(i+i);return o(),n.attentionEncodeSurroundingInfo={after:g.outside,before:h.outside},c+u+p}function yD(e,t,n){return n.options.strong||"*"}function xD(e,t,n,r){return n.safe(e.value,r)}function kD(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function wD(e,t,n){const r=(Wv(n)+(n.options.ruleSpaces?" ":"")).repeat(kD(n));return n.options.ruleSpaces?r.slice(0,-1):r}const zv={blockquote:UL,break:Db,code:JL,definition:QL,emphasis:Mv,hardBreak:Db,heading:nD,html:Ev,image:Lv,imageReference:Dv,inlineCode:Ov,link:_v,linkReference:Bv,list:dD,listItem:hD,paragraph:mD,root:gD,strong:$v,text:xD,thematicBreak:wD};function vD(){return{enter:{table:SD,tableData:Ob,tableHeader:Ob,tableRow:jD},exit:{codeText:ND,table:CD,tableData:Qd,tableHeader:Qd,tableRow:Qd}}}function SD(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function CD(e){this.exit(e),this.data.inTable=void 0}function jD(e){this.enter({type:"tableRow",children:[]},e)}function Qd(e){this.exit(e)}function Ob(e){this.enter({type:"tableCell",children:[]},e)}function ND(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,TD));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function TD(e,t){return t==="|"?t:e}function ID(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,o=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
33
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:l,tableCell:u,tableRow:c}};function l(p,b,y,x){return f(h(p,y,x),p.align)}function c(p,b,y,x){const k=m(p,y,x),C=f([k]);return C.slice(0,C.indexOf(`
34
+ `))}function u(p,b,y,x){const k=y.enter("tableCell"),C=y.enter("phrasing"),j=y.containerPhrasing(p,{...x,before:o,after:o});return C(),k(),j}function f(p,b){return zL(p,{align:b,alignDelimiters:r,padding:n,stringLength:i})}function h(p,b,y){const x=p.children;let k=-1;const C=[],j=b.enter("table");for(;++k<x.length;)C[k]=m(x[k],b,y);return j(),C}function m(p,b,y){const x=p.children;let k=-1;const C=[],j=b.enter("tableRow");for(;++k<x.length;)C[k]=u(x[k],p,b,y);return j(),C}function g(p,b,y){let x=zv.inlineCode(p,b,y);return y.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function AD(){return{exit:{taskListCheckValueChecked:Fb,taskListCheckValueUnchecked:Fb,paragraph:PD}}}function RD(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:MD}}}function Fb(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function PD(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const i=t.children;let o=-1,l;for(;++o<i.length;){const c=i[o];if(c.type==="paragraph"){l=c;break}}l===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function MD(e,t,n,r){const i=e.children[0],o=typeof e.checked=="boolean"&&i&&i.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=n.createTracker(r);o&&c.move(l);let u=zv.listItem(e,t,n,{...r,...c.current()});return o&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,f)),u;function f(h){return h+l}}function ED(){return[dL(),ML(),OL(),vD(),AD()]}function LD(e){return{extensions:[fL(),EL(e),FL(),ID(e),RD()]}}const DD={tokenize:$D,partial:!0},Hv={tokenize:zD,partial:!0},Uv={tokenize:HD,partial:!0},qv={tokenize:UD,partial:!0},OD={tokenize:qD,partial:!0},Vv={name:"wwwAutolink",tokenize:BD,previous:Gv},Kv={name:"protocolAutolink",tokenize:WD,previous:Yv},mi={name:"emailAutolink",tokenize:_D,previous:Jv},Zr={};function FD(){return{text:Zr}}let ta=48;for(;ta<123;)Zr[ta]=mi,ta++,ta===58?ta=65:ta===91&&(ta=97);Zr[43]=mi;Zr[45]=mi;Zr[46]=mi;Zr[95]=mi;Zr[72]=[mi,Kv];Zr[104]=[mi,Kv];Zr[87]=[mi,Vv];Zr[119]=[mi,Vv];function _D(e,t,n){const r=this;let i,o;return l;function l(m){return!Sh(m)||!Jv.call(r,r.previous)||Zm(r.events)?n(m):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(m))}function c(m){return Sh(m)?(e.consume(m),c):m===64?(e.consume(m),u):n(m)}function u(m){return m===46?e.check(OD,h,f)(m):m===45||m===95||Gs(m)?(o=!0,e.consume(m),u):h(m)}function f(m){return e.consume(m),i=!0,u}function h(m){return o&&i&&sr(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(m)):n(m)}}function BD(e,t,n){const r=this;return i;function i(l){return l!==87&&l!==119||!Gv.call(r,r.previous)||Zm(r.events)?n(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(DD,e.attempt(Hv,e.attempt(Uv,o),n),n)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(l)}}function WD(e,t,n){const r=this;let i="",o=!1;return l;function l(m){return(m===72||m===104)&&Yv.call(r,r.previous)&&!Zm(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(m),e.consume(m),c):n(m)}function c(m){if(sr(m)&&i.length<5)return i+=String.fromCodePoint(m),e.consume(m),c;if(m===58){const g=i.toLowerCase();if(g==="http"||g==="https")return e.consume(m),u}return n(m)}function u(m){return m===47?(e.consume(m),o?f:(o=!0,u)):n(m)}function f(m){return m===null||hu(m)||Ln(m)||ma(m)||qu(m)?n(m):e.attempt(Hv,e.attempt(Uv,h),n)(m)}function h(m){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(m)}}function $D(e,t,n){let r=0;return i;function i(l){return(l===87||l===119)&&r<3?(r++,e.consume(l),i):l===46&&r===3?(e.consume(l),o):n(l)}function o(l){return l===null?n(l):t(l)}}function zD(e,t,n){let r,i,o;return l;function l(f){return f===46||f===95?e.check(qv,u,c)(f):f===null||Ln(f)||ma(f)||f!==45&&qu(f)?u(f):(o=!0,e.consume(f),l)}function c(f){return f===95?r=!0:(i=r,r=void 0),e.consume(f),l}function u(f){return i||r||!o?n(f):t(f)}}function HD(e,t){let n=0,r=0;return i;function i(l){return l===40?(n++,e.consume(l),i):l===41&&r<n?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(qv,t,o)(l):l===null||Ln(l)||ma(l)?t(l):(e.consume(l),i)}function o(l){return l===41&&r++,e.consume(l),i}}function UD(e,t,n){return r;function r(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),r):c===38?(e.consume(c),o):c===93?(e.consume(c),i):c===60||c===null||Ln(c)||ma(c)?t(c):n(c)}function i(c){return c===null||c===40||c===91||Ln(c)||ma(c)?t(c):r(c)}function o(c){return sr(c)?l(c):n(c)}function l(c){return c===59?(e.consume(c),r):sr(c)?(e.consume(c),l):n(c)}}function qD(e,t,n){return r;function r(o){return e.consume(o),i}function i(o){return Gs(o)?n(o):t(o)}}function Gv(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Ln(e)}function Yv(e){return!sr(e)}function Jv(e){return!(e===47||Sh(e))}function Sh(e){return e===43||e===45||e===46||e===95||Gs(e)}function Zm(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const VD={tokenize:eO,partial:!0};function KD(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:XD,continuation:{tokenize:QD},exit:ZD}},text:{91:{name:"gfmFootnoteCall",tokenize:JD},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:GD,resolveTo:YD}}}}function GD(e,t,n){const r=this;let i=r.events.length;const o=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let l;for(;i--;){const u=r.events[i][1];if(u.type==="labelImage"){l=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return c;function c(u){if(!l||!l._balanced)return n(u);const f=_r(r.sliceSerialize({start:l.end,end:r.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?n(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),t(u))}}function YD(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",o,t],["enter",l,t],["exit",l,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...c),e}function JD(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o=0,l;return c;function c(m){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(m),e.exit("gfmFootnoteCallLabelMarker"),u}function u(m){return m!==94?n(m):(e.enter("gfmFootnoteCallMarker"),e.consume(m),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",f)}function f(m){if(o>999||m===93&&!l||m===null||m===91||Ln(m))return n(m);if(m===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return i.includes(_r(r.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(m),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(m)}return Ln(m)||(l=!0),o++,e.consume(m),m===92?h:f}function h(m){return m===91||m===92||m===93?(e.consume(m),o++,f):f(m)}}function XD(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(b){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(b),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(b){return b===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(b),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):n(b)}function h(b){if(l>999||b===93&&!c||b===null||b===91||Ln(b))return n(b);if(b===93){e.exit("chunkString");const y=e.exit("gfmFootnoteDefinitionLabelString");return o=_r(r.sliceSerialize(y)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(b),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return Ln(b)||(c=!0),l++,e.consume(b),b===92?m:h}function m(b){return b===91||b===92||b===93?(e.consume(b),l++,h):h(b)}function g(b){return b===58?(e.enter("definitionMarker"),e.consume(b),e.exit("definitionMarker"),i.includes(o)||i.push(o),mn(e,p,"gfmFootnoteDefinitionWhitespace")):n(b)}function p(b){return t(b)}}function QD(e,t,n){return e.check(Pl,t,e.attempt(VD,t,n))}function ZD(e){e.exit("gfmFootnoteDefinition")}function eO(e,t,n){const r=this;return mn(e,i,"gfmFootnoteDefinitionIndent",5);function i(o){const l=r.events[r.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?t(o):n(o)}}function tO(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:o,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let f=u;for(;f--;)if(l[f][0]==="exit"&&l[f][1].type==="strikethroughSequenceTemporary"&&l[f][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[f][1].end.offset-l[f][1].start.offset){l[u][1].type="strikethroughSequence",l[f][1].type="strikethroughSequence";const h={type:"strikethrough",start:Object.assign({},l[f][1].start),end:Object.assign({},l[u][1].end)},m={type:"strikethroughText",start:Object.assign({},l[f][1].end),end:Object.assign({},l[u][1].start)},g=[["enter",h,c],["enter",l[f][1],c],["exit",l[f][1],c],["enter",m,c]],p=c.parser.constructs.insideSpan.null;p&&xr(g,g.length,0,Vu(p,l.slice(f+1,u),c)),xr(g,g.length,0,[["exit",m,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",h,c]]),xr(l,f-1,u-f+3,g),u=f+g.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const f=this.previous,h=this.events;let m=0;return g;function g(b){return f===126&&h[h.length-1][1].type!=="characterEscape"?u(b):(l.enter("strikethroughSequenceTemporary"),p(b))}function p(b){const y=ro(f);if(b===126)return m>1?u(b):(l.consume(b),m++,p);if(m<2&&!n)return u(b);const x=l.exit("strikethroughSequenceTemporary"),k=ro(b);return x._open=!k||k===2&&!!y,x._close=!y||y===2&&!!k,c(b)}}}class nO{constructor(){this.map=[]}add(t,n,r){sO(this,t,n,r)}consume(t){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let i=r.pop();for(;i;){for(const o of i)t.push(o);i=r.pop()}this.map.length=0}}function sO(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i<e.map.length;){if(e.map[i][0]===t){e.map[i][1]+=n,e.map[i][2].push(...r);return}i+=1}e.map.push([t,n,r])}}function rO(e,t){let n=!1;const r=[];for(;t<e.length;){const i=e[t];if(n){if(i[0]==="enter")i[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const o=r.length-1;r[o]=r[o]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function iO(){return{flow:{null:{name:"table",tokenize:aO,resolveAll:oO}}}}function aO(e,t,n){const r=this;let i=0,o=0,l;return c;function c(R){let K=r.events.length-1;for(;K>-1;){const te=r.events[K][1].type;if(te==="lineEnding"||te==="linePrefix")K--;else break}const E=K>-1?r.events[K][1].type:null,D=E==="tableHead"||E==="tableRow"?T:u;return D===T&&r.parser.lazy[r.now().line]?n(R):D(R)}function u(R){return e.enter("tableHead"),e.enter("tableRow"),f(R)}function f(R){return R===124||(l=!0,o+=1),h(R)}function h(R){return R===null?n(R):Tt(R)?o>1?(o=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(R),e.exit("lineEnding"),p):n(R):rn(R)?mn(e,h,"whitespace")(R):(o+=1,l&&(l=!1,i+=1),R===124?(e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),l=!0,h):(e.enter("data"),m(R)))}function m(R){return R===null||R===124||Ln(R)?(e.exit("data"),h(R)):(e.consume(R),R===92?g:m)}function g(R){return R===92||R===124?(e.consume(R),m):m(R)}function p(R){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(R):(e.enter("tableDelimiterRow"),l=!1,rn(R)?mn(e,b,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):b(R))}function b(R){return R===45||R===58?x(R):R===124?(l=!0,e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),y):_(R)}function y(R){return rn(R)?mn(e,x,"whitespace")(R):x(R)}function x(R){return R===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(R),e.exit("tableDelimiterMarker"),k):R===45?(o+=1,k(R)):R===null||Tt(R)?H(R):_(R)}function k(R){return R===45?(e.enter("tableDelimiterFiller"),C(R)):_(R)}function C(R){return R===45?(e.consume(R),C):R===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(R),e.exit("tableDelimiterMarker"),j):(e.exit("tableDelimiterFiller"),j(R))}function j(R){return rn(R)?mn(e,H,"whitespace")(R):H(R)}function H(R){return R===124?b(R):R===null||Tt(R)?!l||i!==o?_(R):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(R)):_(R)}function _(R){return n(R)}function T(R){return e.enter("tableRow"),P(R)}function P(R){return R===124?(e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),P):R===null||Tt(R)?(e.exit("tableRow"),t(R)):rn(R)?mn(e,P,"whitespace")(R):(e.enter("data"),z(R))}function z(R){return R===null||R===124||Ln(R)?(e.exit("data"),P(R)):(e.consume(R),R===92?L:z)}function L(R){return R===92||R===124?(e.consume(R),z):z(R)}}function oO(e,t){let n=-1,r=!0,i=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,f,h,m;const g=new nO;for(;++n<e.length;){const p=e[n],b=p[1];p[0]==="enter"?b.type==="tableHead"?(c=!1,u!==0&&(_b(g,t,u,f,h),h=void 0,u=0),f={type:"table",start:Object.assign({},b.start),end:Object.assign({},b.end)},g.add(n,0,[["enter",f,t]])):b.type==="tableRow"||b.type==="tableDelimiterRow"?(r=!0,m=void 0,o=[0,0,0,0],l=[0,n+1,0,0],c&&(c=!1,h={type:"tableBody",start:Object.assign({},b.start),end:Object.assign({},b.end)},g.add(n,0,[["enter",h,t]])),i=b.type==="tableDelimiterRow"?2:h?3:1):i&&(b.type==="data"||b.type==="tableDelimiterMarker"||b.type==="tableDelimiterFiller")?(r=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],m=fc(g,t,o,i,void 0,m),o=[0,0,0,0]),l[2]=n)):b.type==="tableCellDivider"&&(r?r=!1:(o[1]!==0&&(l[0]=l[1],m=fc(g,t,o,i,void 0,m)),o=l,l=[o[1],n,0,0])):b.type==="tableHead"?(c=!0,u=n):b.type==="tableRow"||b.type==="tableDelimiterRow"?(u=n,o[1]!==0?(l[0]=l[1],m=fc(g,t,o,i,n,m)):l[1]!==0&&(m=fc(g,t,l,i,n,m)),i=0):i&&(b.type==="data"||b.type==="tableDelimiterMarker"||b.type==="tableDelimiterFiller")&&(l[3]=n)}for(u!==0&&_b(g,t,u,f,h),g.consume(t.events),n=-1;++n<t.events.length;){const p=t.events[n];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=rO(t.events,n))}return e}function fc(e,t,n,r,i,o){const l=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",c="tableContent";n[0]!==0&&(o.end=Object.assign({},La(t.events,n[0])),e.add(n[0],0,[["exit",o,t]]));const u=La(t.events,n[1]);if(o={type:l,start:Object.assign({},u),end:Object.assign({},u)},e.add(n[1],0,[["enter",o,t]]),n[2]!==0){const f=La(t.events,n[2]),h=La(t.events,n[3]),m={type:c,start:Object.assign({},f),end:Object.assign({},h)};if(e.add(n[2],0,[["enter",m,t]]),r!==2){const g=t.events[n[2]],p=t.events[n[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",n[3]>n[2]+1){const b=n[2]+1,y=n[3]-n[2]-1;e.add(b,y,[])}}e.add(n[3]+1,0,[["exit",m,t]])}return i!==void 0&&(o.end=Object.assign({},La(t.events,i)),e.add(i,0,[["exit",o,t]]),o=void 0),o}function _b(e,t,n,r,i){const o=[],l=La(t.events,n);i&&(i.end=Object.assign({},l),o.push(["exit",i,t])),r.end=Object.assign({},l),o.push(["exit",r,t]),e.add(n+1,0,o)}function La(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const lO={name:"tasklistCheck",tokenize:uO};function cO(){return{text:{91:lO}}}function uO(e,t,n){const r=this;return i;function i(u){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return Ln(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),l):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),l):n(u)}function l(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):n(u)}function c(u){return Tt(u)?t(u):rn(u)?e.check({tokenize:dO},t,n)(u):n(u)}}function dO(e,t,n){return mn(e,r,"whitespace");function r(i){return i===null?n(i):t(i)}}function fO(e){return av([FD(),KD(),tO(e),iO(),cO()])}const hO={};function Xv(e){const t=this,n=e||hO,r=t.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),o=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),l=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(fO(n)),o.push(ED()),l.push(LD(n))}const mO="X-CodingNS-Assistant-Source",pO="butler-ui",Zd=new Map;async function El(e,t={},n={}){const r=new Headers(t.headers);r.set(mO,pO);const i=gO();if(Zd.get(i)===!1){if(n.unsupportedFallback!==void 0)return Bb(n.unsupportedFallback);throw Wb()}try{const l=await ae.request(e,{...t,headers:r});return Zd.set(i,!0),l}catch(l){if(!bO(l))throw l;if(Zd.set(i,!1),n.unsupportedFallback!==void 0)return Bb(n.unsupportedFallback);throw Wb()}}function gO(){return jl()}function Bb(e){return typeof e=="function"?e():e}function bO(e){return e instanceof rr&&(e.status===404||e.status===405||e.status===501)}function Wb(){return new Error("当前 Host 版本不支持新版助手接口,请先升级 Host。")}function Qv(){return ae.request("/api/butler/profile")}function yO(e){return ae.request("/api/butler/profile/init",{method:"POST",body:JSON.stringify(e)})}function $b(e){return ae.request("/api/butler/profile",{method:"PATCH",body:JSON.stringify(e)})}function xO(e){const t=(e==null?void 0:e.trim())??"",n=t?`/api/butler/control-session?workspaceId=${encodeURIComponent(t)}`:"/api/butler/control-session";return ae.request(n)}function Ch(){return ae.request("/api/butler/control-sessions")}function kO(e){return ae.request(`/api/butler/control-sessions/${encodeURIComponent(e)}`)}function XV(e={}){var i;const t=new URLSearchParams;e.status&&t.set("status",e.status),(i=e.controlSessionId)!=null&&i.trim()&&t.set("controlSessionId",e.controlSessionId.trim()),e.limit&&e.limit>0&&t.set("limit",String(e.limit));const n=t.toString(),r=n?`/api/butler/control-timers?${n}`:"/api/butler/control-timers";return ae.request(r)}function wO(){return ae.request("/api/butler/control-session/reset",{method:"POST"})}function vO(e={}){return ae.request("/api/butler/control-session/start",{method:"POST",body:JSON.stringify(e)})}function SO(e){return ae.request("/api/butler/control-session/messages",{method:"POST",body:JSON.stringify(e)})}function CO(e={}){var i;const t=new URLSearchParams;e.status&&t.set("status",e.status),(i=e.controlSessionId)!=null&&i.trim()&&t.set("controlSessionId",e.controlSessionId.trim()),e.limit&&e.limit>0&&t.set("limit",String(e.limit));const n=t.toString(),r=n?`/api/assistant/automations?${n}`:"/api/assistant/automations";return El(r,{},{unsupportedFallback:()=>({payload:{items:[]}})})}function jO(e={}){var i;const t=new URLSearchParams;(i=e.controlSessionId)!=null&&i.trim()&&t.set("controlSessionId",e.controlSessionId.trim()),e.limit&&e.limit>0&&t.set("limit",String(e.limit));const n=t.toString(),r=n?`/api/assistant/automations/runs/recent?${n}`:"/api/assistant/automations/runs/recent";return El(r,{},{unsupportedFallback:()=>({payload:{items:[]}})})}function QV(e){return El(`/api/assistant/automations/${encodeURIComponent(e)}/cancel`,{method:"POST",body:JSON.stringify({})})}function ZV(e,t){return El(`/api/assistant/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}function eK(e){return El(`/api/assistant/automations/${encodeURIComponent(e)}/skip-wait`,{method:"POST",body:JSON.stringify({})})}function tK(e){return ae.request(`/api/butler/control-timers/${encodeURIComponent(e)}/cancel`,{method:"POST",body:JSON.stringify({})})}function NO(){return ae.request("/api/butler/control-session/events")}function Zv(){return ae.request("/api/butler/overview")}function eS(e,t){return ae.request(`/api/butler/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/resume`,{method:"POST"})}function TO(e={}){var i;const t=new URLSearchParams;(i=e.workspaceId)!=null&&i.trim()&&t.set("workspaceId",e.workspaceId.trim()),e.status&&t.set("status",e.status),e.riskLevel&&t.set("riskLevel",e.riskLevel);const n=t.toString(),r=n?`/api/butler/projects?${n}`:"/api/butler/projects";return ae.request(r)}function nK(e,t={}){const n=new URLSearchParams;t.enabled!==null&&t.enabled!==void 0&&n.set("enabled",String(t.enabled)),t.executionMode&&n.set("executionMode",t.executionMode);const r=n.toString(),i=r?`/api/butler/projects/${encodeURIComponent(e)}/patrol-plans?${r}`:`/api/butler/projects/${encodeURIComponent(e)}/patrol-plans`;return ae.request(i)}function ep(e={}){var i,o;const t=new URLSearchParams;(i=e.workspaceId)!=null&&i.trim()&&t.set("workspaceId",e.workspaceId.trim()),(o=e.projectId)!=null&&o.trim()&&t.set("projectId",e.projectId.trim()),e.status&&t.set("status",e.status),e.itemType&&t.set("itemType",e.itemType);const n=t.toString(),r=n?`/api/butler/inbox?${n}`:"/api/butler/inbox";return ae.request(r)}function IO(e){return ae.request("/api/butler/inbox",{method:"POST",body:JSON.stringify(e)})}function tS(e={}){var i,o;const t=new URLSearchParams;e.status&&t.set("status",e.status),(i=e.projectId)!=null&&i.trim()&&t.set("projectId",e.projectId.trim()),(o=e.sessionId)!=null&&o.trim()&&t.set("sessionId",e.sessionId.trim());const n=t.toString(),r=n?`/api/butler/follow-up-tasks?${n}`:"/api/butler/follow-up-tasks";return ae.request(r)}function sK(e){return ae.request("/api/butler/follow-up-tasks",{method:"POST",body:JSON.stringify(e)})}function AO(e){return ae.request(`/api/butler/follow-up-tasks/${encodeURIComponent(e)}`)}function rK(e){return ae.request(`/api/butler/follow-up-tasks/${encodeURIComponent(e)}/cancel`,{method:"POST"})}function iK(e,t){return ae.request(`/api/butler/projects/${encodeURIComponent(e)}/verifications/${encodeURIComponent(t)}/cancel`,{method:"POST"})}function zb(e,t){return ae.request(`/api/butler/inbox/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({projectId:t.projectId,itemType:t.itemType,title:t.title,content:t.content,priority:t.priority,status:t.status})})}function aK(e){return ae.request(`/api/butler/inbox/${encodeURIComponent(e)}/analyze`,{method:"POST",body:JSON.stringify({})})}function oK(e){return ae.request(`/api/butler/inbox/${encodeURIComponent(e)}/start-session`,{method:"POST",body:JSON.stringify({})})}function RO(e){return ae.request(`/api/butler/inbox/${encodeURIComponent(e)}`,{method:"DELETE"})}function PO(){return ae.request("/api/butler/notifications/archives")}function MO(e,t){return ae.request(`/api/butler/notifications/archives/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({archived:t})})}function EO(e){const t=new URLSearchParams;return t.set("sessionId",e),ae.request(`/api/butler/session-target?${t.toString()}`)}function lK(e){const t=new URLSearchParams;return t.set("sessionId",e),ae.request(`/api/butler/session-action-context?${t.toString()}`)}function cK(e){return ae.request("/api/butler/actions/start-verification",{method:"POST",body:JSON.stringify(e)})}const bu="*** Begin Patch",yu="*** End Patch";function Hb(e){const t=e.replace(/\r\n/g,`
35
+ `);if(!t.includes(bu)||!t.includes(yu))return null;const n=t.split(`
36
+ `),r=[];let i=null,o=null;for(const l of n){if(l===bu||l===yu)continue;if(l.startsWith("*** Update File: ")){i=ef("update",l.slice(17)),r.push(i),o=null;continue}if(l.startsWith("*** Add File: ")){i=ef("add",l.slice(14)),r.push(i),o={oldLineNumber:0,newLineNumber:1};continue}if(l.startsWith("*** Delete File: ")){i=ef("delete",l.slice(17)),r.push(i),o=null;continue}if(!i)continue;if(l.startsWith("*** Move to: ")){i.nextPath=l.slice(13),i.lines.push({kind:"meta",text:l,oldLineNumber:null,newLineNumber:null});continue}if(l.startsWith("@@")){o=OO(l)??{oldLineNumber:0,newLineNumber:0},i.lines.push({kind:"hunk",text:l,oldLineNumber:null,newLineNumber:null});continue}if(l==="*** End of File"){i.lines.push({kind:"meta",text:l,oldLineNumber:null,newLineNumber:null});continue}if(i.action==="add"&&l.startsWith("+")){i.additions+=1,i.statsKnown=!0,i.lines.push({kind:"add",text:l,oldLineNumber:null,newLineNumber:(o==null?void 0:o.newLineNumber)??i.additions}),o&&(o.newLineNumber+=1);continue}if(!o){i.lines.push({kind:"meta",text:l,oldLineNumber:null,newLineNumber:null});continue}if(l.startsWith("+")){i.additions+=1,i.statsKnown=!0,i.lines.push({kind:"add",text:l,oldLineNumber:null,newLineNumber:o.newLineNumber}),o.newLineNumber+=1;continue}if(l.startsWith("-")){i.deletions+=1,i.statsKnown=!0,i.lines.push({kind:"remove",text:l,oldLineNumber:o.oldLineNumber,newLineNumber:null}),o.oldLineNumber+=1;continue}if(l.startsWith(" ")||l.length===0){i.lines.push({kind:"context",text:l,oldLineNumber:o.oldLineNumber,newLineNumber:o.newLineNumber}),o.oldLineNumber+=1,o.newLineNumber+=1;continue}i.lines.push({kind:"meta",text:l,oldLineNumber:null,newLineNumber:null})}return r.length===0?null:{files:r,totalAdditions:r.reduce((l,c)=>l+c.additions,0),totalDeletions:r.reduce((l,c)=>l+c.deletions,0)}}function LO(e,t=[]){const n=e.replace(/\r\n/g,`
37
+ `).trim();if(!n)return null;if(n.includes(bu)&&n.includes(yu))return n;const r=[...new Set(t.map(i=>i.trim()).filter(i=>i.length>0))];return r.length!==1||!FO(n)?null:[bu,`*** Update File: ${r[0]}`,n,yu].join(`
38
+ `)}function DO(e){const t=_O(e);if(!t)return[];const n=t.replace(/\r\n/g,`
39
+ `).split(`
40
+ `),r=[];let i=!1;for(const o of n){const l=o.trim();if(!i){/^Success\.\s+Updated the following files:/i.test(l)&&(i=!0);continue}if(!l){if(r.length>0)break;continue}const c=l.match(/^[A-Z?]\s+(.+)$/),u=((c==null?void 0:c[1])??l).trim();if(!u)break;r.push(u)}return[...new Set(r)]}function Ub(e){return e.replace(/\\/g,"/").split("/").at(-1)||e}function ef(e,t){return{path:t,nextPath:null,action:e,additions:0,deletions:0,statsKnown:!1,lines:[]}}function OO(e){const t=e.match(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/);return t?{oldLineNumber:Number(t[1]),newLineNumber:Number(t[2])}:null}function FO(e){return e.startsWith("@@")||e.startsWith("*** Update File: ")||e.startsWith("*** Add File: ")||e.startsWith("*** Delete File: ")||e.includes(`
41
+ @@`)||e.startsWith("+")||e.startsWith("-")}function _O(e){const t=e.trim();if(!t)return"";if(!t.startsWith("{"))return t;try{const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return t;const r=n;if(typeof r.output=="string"&&r.output.trim().length>0)return r.output;if(typeof r.result=="string"&&r.result.trim().length>0)return r.result;if(typeof r.message=="string"&&r.message.trim().length>0)return r.message}catch{return t}return t}const BO=/data:image\/([a-zA-Z0-9.+-]+);base64,([A-Za-z0-9+/=]+)/g,WO=/!\[([^\]]*)\]\((data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+)\)/g,$O=/<img\b[^>]*src=["'](data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+)["'][^>]*>/gi,zO=/<image\b([^>]*)>([\s\S]*?)<\/image>/gi,HO=/\[\[CODINGNS_IMAGE_ATTACHMENTS\]\][\s\S]*?\[\[\/CODINGNS_IMAGE_ATTACHMENTS\]\]/g,qb=/```question\s*([\s\S]*?)```/i;function ml(e){const t=qO(e),n=UO(t);if(n)return n;const r=VO(t);return r||{...sS(t),structuredQuestions:null}}function UO(e){var r;const t=e.match(qb);if(!t)return null;const n=((r=t[1])==null?void 0:r.trim())??"";if(!n)return null;try{const i=JSON.parse(n),o=nS(i);return o?{text:tp(e.replace(qb,"").trim()),inlineImages:[],structuredQuestions:o}:null}catch{return null}}function qO(e){return e.replace(HO,"")}function VO(e){const t=e.trim();if(!GO(t))return null;try{const n=JSON.parse(t),r=nS(n),i=YO(r?KO(n):n);return i.text||i.inlineImages.length>0||r?{...i,structuredQuestions:r}:null}catch{return null}}function KO(e){const t=Ll(e);if(!t||!("questions"in t))return e;const{questions:n,...r}=t;return r}function GO(e){return e.length<2?!1:e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}")}function YO(e){const t=[],n=[];return Jc(e,t,n),{text:tp(t.join(`
42
+
43
+ `)),inlineImages:rS(n),structuredQuestions:null}}function nS(e){const t=Ll(e);if(!t)return null;const n=JO(t.questions);return n.length===0?null:{questions:n}}function JO(e){return Array.isArray(e)?e.map((t,n)=>XO(t,n)).filter(t=>t!==null):[]}function XO(e,t){const n=Ll(e);if(!n)return null;const r=Jr(_s(n.question));if(!r)return null;const i=QO(n.options);return i.length===0?null:{id:Jr(_s(n.id))??`structured-question-${t+1}`,header:Jr(_s(n.header))??"问题",question:r,allowOther:!!(n.allowOther??n.isOther),secret:!!(n.secret??n.isSecret),options:i}}function QO(e){return Array.isArray(e)?e.map(t=>{const n=Ll(t);if(!n)return null;const r=Jr(_s(n.label));return r?{label:r,description:Jr(_s(n.description))}:null}).filter(t=>t!==null):[]}function Jc(e,t,n){if(typeof e=="string"){const l=sS(e);l.text&&t.push(l.text),n.push(...l.inlineImages);return}if(e==null)return;if(Array.isArray(e)){e.forEach(l=>Jc(l,t,n));return}if(typeof e!="object")return;const r=e,i=new Set,o=ZO(r);o&&(n.push(o),["type","source","media_type","mime_type","mimeType","data","image_url","imageUrl","url","src","alt","name"].forEach(l=>{l in r&&i.add(l)}));for(const l of["image_url","url","src","source"]){const c=r[l];typeof c!="string"||!iS(c)||(n.push(la(c,_s(r.alt))),i.add(l))}for(const l of["text","message","content","output","result","summary","caption"])l in r&&(i.add(l),Jc(r[l],t,n));i.size>0||Object.values(r).forEach(l=>{Jc(l,t,n)})}function sS(e){const t=[];let n=e;return n=n.replace(zO,(r,i,o)=>{const l=s2(i,"name"),c=n2(o);return c!=null&&c.url&&t.push(la(c.url,c.altText||l)),""}),n=n.replace(WO,(r,i,o)=>(t.push(la(o,i)),"")),n=n.replace($O,(r,i)=>(t.push(la(i,null)),"")),n=n.replace(BO,(r,i,o)=>(t.push(la(r,null,`image/${i}`,xu(o))),"")),{text:tp(n),inlineImages:rS(t),structuredQuestions:null}}function la(e,t,n,r){const i=n??e2(e)??"image/png";return{url:e,mimeType:i,altText:Jr(t),estimatedBytes:r??t2(e)}}function ZO(e){const t=Ll(e.source);if(t){const i=_s(t.type).trim().toLowerCase(),o=Kb(t.media_type??t.mime_type??t.mimeType),l=Vb(t.data);if(i==="base64"&&o&&l)return la(`data:${o};base64,${l}`,Jr(_s(t.alt)||_s(t.name)||_s(e.alt)||_s(e.name)),o,xu(l))}const n=Kb(e.media_type??e.mime_type??e.mimeType),r=Vb(e.data);return n&&r?la(`data:${n};base64,${r}`,Jr(_s(e.alt)||_s(e.name)),n,xu(r)):null}function rS(e){const t=new Map;return e.forEach(n=>{t.has(n.url)||t.set(n.url,n)}),[...t.values()]}function tp(e){return e.replace(/\r\n/g,`
44
+ `).replace(/[ \t]{2,}/g," ").replace(/[ \t]+\n/g,`
45
+ `).replace(/\n{3,}/g,`
46
+
47
+ `).trim()}function iS(e){return/^data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+$/.test(e.trim())}function e2(e){var n;const t=e.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,/i);return((n=t==null?void 0:t[1])==null?void 0:n.toLowerCase())??null}function t2(e){const t=e.match(/^data:image\/[a-zA-Z0-9.+-]+;base64,([A-Za-z0-9+/=]+)$/i);return t?xu(t[1]):null}function xu(e){const t=e.trim(),n=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-n)}function Jr(e){const t=_s(e).trim();return t.length>0?t:null}function Vb(e){if(typeof e!="string")return null;const t=e.replace(/\s+/g,"").trim();return/^[A-Za-z0-9+/=]+$/.test(t)?t:null}function Kb(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t.startsWith("image/")?t:null}function _s(e){return typeof e=="string"?e:""}function Ll(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function n2(e){const t=e.trim();if(t.length===0)return null;try{const n=JSON.parse(t),r=_s(n.image_url??n.imageUrl).trim(),i=Jr(_s(n.name)||_s(n.alt));return{url:iS(r)?r:null,altText:i}}catch{const n=t.match(/(data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+)/i);return n?{url:n[1],altText:null}:null}}function s2(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|\\[([^\\]]*)\\]|([^\\s>]+))`,"i"));return Jr((r==null?void 0:r[1])??(r==null?void 0:r[2])??(r==null?void 0:r[3])??(r==null?void 0:r[4])??"")}const r2=new Set(["updateplan"]),aS=new Set(["todowrite"]),jh=new Set(["todoread"]),oS=new Set(["taskcreate","taskupdate","taskget","tasklist","taskdelete","taskremove"]);function i2(e,t){const n=o2(e,t);return n||l2(e,t)}function lS(e){return e.reduce((t,n)=>(t[n.status]+=1,t),{pending:0,in_progress:0,completed:0,failed:0,cancelled:0})}function a2(e,t,n){if(!e)return null;if(Nh(e.name)){const l=Qa(e);if(!l||!Xu(l.value))return null;const c=cS(l.value,n);return!c||c.items.length===0?null:{provider:t,source:"plan",explanation:c.explanation,items:c.items,updatedAt:n}}const r=Ju(e.name);if(!aS.has(r)&&!jh.has(r)&&!oS.has(r))return null;const i=Qa(e,(jh.has(r),"prefer-output"));if(!i)return null;if(r==="taskdelete"||r==="taskremove"){const l=uS(i.value);return l.length>0?{provider:t,source:"todo",explanation:null,items:l.map((c,u)=>({id:c,title:`Task ${u+1}`,status:"cancelled",detail:c,updatedAt:n})),updatedAt:n}:null}const o=$o(i.value,n);return o.length===0?null:{provider:t,source:Nh(e.name)?"plan":"todo",explanation:null,items:o,updatedAt:n}}function o2(e,t){let n=null;for(const r of e){const i=r.toolCall;if(!i||Ju(i.name)===""||!Nh(i.name))continue;const o=Qa(i);if(!o||typeof o.value!="object"||o.value===null)continue;const l=cS(o.value,r.timestamp);!l||l.items.length===0||(n={provider:t,source:"plan",explanation:l.explanation,items:l.items,updatedAt:r.timestamp})}return n}function l2(e,t){const n=new Map;let r=null;for(const o of e){const l=o.toolCall;if(!l)continue;const c=Ju(l.name);if(aS.has(c)){const h=Qa(l),m=h?$o(h.value,o.timestamp):[];m.length>0&&(tf(n,m),r=o.timestamp);continue}if(jh.has(c)){const h=Qa(l,"prefer-output"),m=h?$o(h.value,o.timestamp):[];m.length>0&&(tf(n,m),r=o.timestamp);continue}if(!oS.has(c))continue;const u=Qa(l,"prefer-output");if(!u)continue;if(c==="tasklist"||c==="taskget"){const h=$o(u.value,o.timestamp);h.length>0&&(tf(n,h),r=o.timestamp);continue}if(c==="taskdelete"||c==="taskremove"){const h=uS(u.value);if(h.length>0){for(const m of h)n.delete(m);r=o.timestamp}continue}const f=$o(u.value,o.timestamp);if(f.length!==0){for(const h of f)u2(n,h);r=o.timestamp}}const i=Array.from(n.values()).sort((o,l)=>o.updatedAt.localeCompare(l.updatedAt)).map(o=>({...o}));return i.length===0||!r?null:{provider:t,source:"todo",explanation:null,items:i,updatedAt:r}}function Nh(e){return r2.has(Ju(e))}function cS(e,t){const n=Array.isArray(e.plan)?e.plan:null;if(!n||n.length===0)return null;const r=n.map((i,o)=>dS(i,{fallbackIdPrefix:"plan",fallbackTitle:`Step ${o+1}`,fallbackStatus:"pending",updatedAt:t})).filter(i=>i!==null);return r.length===0?null:{items:r,explanation:Xn(e.explanation)}}function Qa(e,t="prefer-input"){const n=t==="prefer-output"?[{text:e.output,source:"output"},{text:e.input,source:"input"}]:[{text:e.input,source:"input"},{text:e.output,source:"output"}];for(const r of n){const i=c2(r.text);if(i!==null)return{value:i,source:r.source}}return null}function c2(e){const t=(e==null?void 0:e.trim())??"";if(!t)return null;const n=hc(t);if(n!==null)return n;const r=t.match(/```(?:json)?\s*([\s\S]+?)```/i);if(r!=null&&r[1]){const u=hc(r[1].trim());if(u!==null)return u}const i=t.indexOf("{"),o=t.lastIndexOf("}");if(i>=0&&o>i){const u=hc(t.slice(i,o+1));if(u!==null)return u}const l=t.indexOf("["),c=t.lastIndexOf("]");return l>=0&&c>l?hc(t.slice(l,c+1)):null}function hc(e){try{return JSON.parse(e)}catch{return null}}function $o(e,t){return tl(e).map((r,i)=>dS(r,{fallbackIdPrefix:"task",fallbackTitle:`Task ${i+1}`,fallbackStatus:"pending",updatedAt:t})).filter(r=>r!==null)}function tl(e){if(Array.isArray(e))return e.flatMap(n=>tl(n));if(!Xu(e))return[];if(m2(e))return[e];const t=["tasks","todos","items","entries","results","data"];for(const n of t){if(!(n in e))continue;const r=tl(e[n]);if(r.length>0)return r}return Object.values(e).flatMap(n=>tl(n))}function uS(e){const n=tl(e).map(i=>Th(i)).filter(i=>i!==null);if(n.length>0)return n;if(!Xu(e))return[];const r=Th(e);return r?[r]:[]}function dS(e,t){if(!Xu(e))return null;const n=Xn(e.step)??Xn(e.title)??Xn(e.content)??Xn(e.task)??Xn(e.text)??Xn(e.name)??Xn(e.subject)??Xn(e.description)??t.fallbackTitle,r=Th(e)??h2(t.fallbackIdPrefix,n),i=f2(e,n);return{id:r,title:n,status:d2(e.status,t.fallbackStatus),detail:i,updatedAt:t.updatedAt}}function u2(e,t){const n=e.get(t.id);if(!n){e.set(t.id,{...t});return}e.set(t.id,{id:n.id,title:t.title||n.title,status:t.status,detail:t.detail??n.detail,updatedAt:t.updatedAt})}function tf(e,t){e.clear();for(const n of t)e.set(n.id,{...n})}function d2(e,t){var r;const n=(r=Xn(e))==null?void 0:r.toLowerCase().replace(/[\s-]+/g,"_");return n?["pending","todo","open","queued","not_started","created"].includes(n)?"pending":["in_progress","progress","active","doing","running","started"].includes(n)?"in_progress":["completed","complete","done","success","succeeded","finished","closed"].includes(n)?"completed":["failed","error","errored"].includes(n)?"failed":["cancelled","canceled","aborted","skipped"].includes(n)?"cancelled":t:t}function f2(e,t){const n=[Xn(e.detail),Xn(e.details),Xn(e.description),Xn(e.reason),Xn(e.summary),Xn(e.note),Xn(e.priority)].filter(r=>r!==null);for(const r of n)if(r!==t)return r;return null}function Th(e){return Xn(e.id)??Xn(e.taskId)??Xn(e.task_id)??Xn(e.uuid)??Xn(e.key)}function h2(e,t){return`${e}:${t.trim().toLowerCase()}`}function m2(e){return[e.step,e.title,e.content,e.task,e.text,e.subject,e.name,e.description].some(t=>Xn(t)!==null)}function Ju(e){return e.trim().toLowerCase().replace(/[\s_.-]+/g,"")}function Xu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xn(e){if(typeof e!="string")return null;const t=e.trim();return t||null}function fS({snapshot:e,toolName:t="",expanded:n=!1,exportMode:r=!1,className:i,children:o,onToggleExpanded:l}){const c=lS(e.items),u=n?a("conversation.taskCardRawCollapse"):a("conversation.taskCardRawExpand"),f=i?`tool-call-item task-tool-item ${i}`:"tool-call-item task-tool-item";return s.jsxs("div",{className:f,children:[s.jsxs("div",{className:"task-tool-header",children:[s.jsxs("div",{className:"task-tool-heading",children:[s.jsx("span",{className:"task-tool-badge",children:e.source==="plan"?a("conversation.taskCardPlanTitle"):a("conversation.taskCardTodoTitle")}),s.jsxs("div",{className:"task-tool-heading-main",children:[s.jsx("strong",{children:p2(e,t)}),s.jsx("span",{className:"task-tool-summary-text",children:g2(e.items,c)})]})]}),!r&&l?s.jsx("button",{type:"button",className:"task-tool-raw-toggle",onClick:l,children:u}):null]}),s.jsx("ol",{className:"task-tool-list",children:e.items.map(h=>s.jsxs("li",{className:"task-tool-list-item","data-status":h.status,children:[s.jsx("span",{className:"task-tool-item-indicator","data-status":h.status,"aria-hidden":"true"}),s.jsx("strong",{className:"task-tool-item-title",children:h.title}),h.detail?s.jsx("span",{className:"task-tool-item-detail",children:h.detail}):null,s.jsx("span",{className:"task-tool-item-status",children:b2(h.status)})]},h.id))}),o]})}function p2(e,t){if(e.source==="plan")return a("conversation.taskCardPlanUpdated");const n=t.trim().toLowerCase();return n==="taskcreate"||n==="todowrite"||n==="todoread"?a("conversation.taskCardTodoUpdated"):n.startsWith("task")?a("conversation.taskCardTodoUpdated"):a("conversation.taskCardTodoUpdated")}function g2(e,t){const n=[a("conversation.taskCardSummaryTotal",{count:e.length})];return t.in_progress>0&&n.push(a("conversation.taskCardSummaryInProgress",{count:t.in_progress})),t.pending>0&&n.push(a("conversation.taskCardSummaryPending",{count:t.pending})),t.completed>0&&n.push(a("conversation.taskCardSummaryCompleted",{count:t.completed})),t.failed>0&&n.push(a("conversation.taskCardSummaryFailed",{count:t.failed})),n.join(" / ")}function b2(e){switch(e){case"in_progress":return a("conversation.taskProgressStatusInProgress");case"completed":return a("conversation.taskProgressStatusCompleted");case"failed":return a("conversation.taskProgressStatusFailed");case"cancelled":return a("conversation.taskProgressStatusCancelled");case"pending":default:return a("conversation.taskProgressStatusPending")}}function y2(){return s.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",className:"conversation-action-icon",children:[s.jsx("rect",{x:"7",y:"5",width:"9",height:"11",rx:"2.5"}),s.jsx("path",{d:"M5.5 12.5H5A2 2 0 0 1 3 10.5V5a2 2 0 0 1 2-2h5.5"})]})}function x2(){return s.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",className:"conversation-action-icon",children:[s.jsx("circle",{cx:"6",cy:"5",r:"2.25"}),s.jsx("circle",{cx:"14",cy:"6",r:"2.25"}),s.jsx("circle",{cx:"14",cy:"14",r:"2.25"}),s.jsx("path",{d:"M8.4 5.7h2.2a2.7 2.7 0 0 1 2.7 2.7v1.2"}),s.jsx("path",{d:"M8.1 5.9l4.1 6.2"})]})}function uK(){return s.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",className:"conversation-action-icon",children:[s.jsx("path",{d:"M10 2.8l1.6 3.4 3.8.5-2.8 2.6.7 3.9-3.3-1.8-3.3 1.8.7-3.9-2.8-2.6 3.8-.5L10 2.8z"}),s.jsx("path",{d:"M15.8 13.3l.7 1.5 1.7.2-1.2 1.1.3 1.8-1.5-.8-1.5.8.3-1.8-1.2-1.1 1.7-.2.7-1.5z"})]})}function dK(){return s.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",className:"conversation-action-icon",children:[s.jsx("circle",{cx:"6",cy:"5",r:"2.2"}),s.jsx("circle",{cx:"14",cy:"5",r:"2.2"}),s.jsx("circle",{cx:"10",cy:"14",r:"2.2"}),s.jsx("path",{d:"M8.2 5h3.6"}),s.jsx("path",{d:"M10 7.2v4.6"}),s.jsx("path",{d:"M7.3 6.8l1.7 4"}),s.jsx("path",{d:"M12.7 6.8l-1.7 4"})]})}function fK(){return s.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",fill:"currentColor",className:"conversation-action-icon",children:[s.jsx("circle",{cx:"4.5",cy:"10",r:"1.5"}),s.jsx("circle",{cx:"10",cy:"10",r:"1.5"}),s.jsx("circle",{cx:"15.5",cy:"10",r:"1.5"})]})}function k2(){return s.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",className:"conversation-action-icon",children:[s.jsx("path",{d:"M4.5 5.5h1.2"}),s.jsx("path",{d:"M8 5.5h7.5"}),s.jsx("path",{d:"M4.5 10h1.2"}),s.jsx("path",{d:"M8 10h7.5"}),s.jsx("path",{d:"M4.5 14.5h1.2"}),s.jsx("path",{d:"M8 14.5h7.5"}),s.jsx("path",{d:"M5.1 5.5l.5.5 1-1"}),s.jsx("circle",{cx:"5.1",cy:"10",r:".8",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M5.1 14.5l.5.5 1-1"})]})}const hS="codingns.user-app.conversation-scroll",Ca=1,w2=200,v2=1e7;function mS(){return typeof window<"u"&&typeof window.localStorage<"u"}function pS(e){return e.trim()}function gS(e){return!Number.isFinite(e)||e<=0?0:Math.min(Math.round(e),v2)}function bS(e){return!e||typeof e!="object"?null:{scrollTop:gS(e.scrollTop),stickToBottom:e.stickToBottom===!0,lastMessageSignature:typeof e.lastMessageSignature=="string"?e.lastMessageSignature:null,updatedAt:Number.isFinite(e.updatedAt)?e.updatedAt:0}}function yS(){if(!mS())return{schemaVersion:Ca,bySessionId:{}};const e=window.localStorage.getItem(hS);if(!e)return{schemaVersion:Ca,bySessionId:{}};try{const t=JSON.parse(e);if(!t||typeof t!="object"||t.schemaVersion!==Ca||!t.bySessionId||typeof t.bySessionId!="object"||Array.isArray(t.bySessionId))return{schemaVersion:Ca,bySessionId:{}};const n=Object.fromEntries(Object.entries(t.bySessionId).map(([r,i])=>{const o=bS(i);return o?[r,o]:null}).filter(r=>!!r));return{schemaVersion:Ca,bySessionId:n}}catch{return{schemaVersion:Ca,bySessionId:{}}}}function S2(e){if(mS())try{window.localStorage.setItem(hS,JSON.stringify(e))}catch{}}function mc(e){const t=pS(e);if(!t)return null;const n=yS().bySessionId[t],r=bS(n);return r?{scrollTop:r.scrollTop,stickToBottom:r.stickToBottom,lastMessageSignature:r.lastMessageSignature}:null}function Gb(e,t){const n=pS(e);if(!n)return;const r=yS();r.bySessionId[n]={scrollTop:gS(t.scrollTop),stickToBottom:t.stickToBottom,lastMessageSignature:t.lastMessageSignature,updatedAt:Date.now()};const i=Object.entries(r.bySessionId).sort((o,l)=>l[1].updatedAt-o[1].updatedAt).slice(0,w2);r.bySessionId=Object.fromEntries(i),S2(r)}const C2=5e3;let ja=null;function j2(){var t;if(ja!==null)return ja;if(typeof document>"u")return ja=0,ja;const e=document.createElement("div");return e.dataset.scrollbarProbe="true",e.style.position="absolute",e.style.top="-9999px",e.style.width="120px",e.style.height="120px",e.style.overflow="scroll",e.style.visibility="hidden",e.style.pointerEvents="none",(t=document.body)==null||t.appendChild(e),ja=Math.max(0,e.offsetWidth-e.clientWidth),e.remove(),ja}function N2(e){if(j2()>0){e.dataset.scrollbarLayout="stable";return}e.removeAttribute("data-scrollbar-layout")}function np(e){const t=d.useRef(null),n=e??t;return d.useEffect(()=>{const r=n.current;if(!r||typeof globalThis.window>"u")return;N2(r);let i=null;const o=()=>{i!==null&&(window.clearTimeout(i),i=null)},l=()=>{o(),r.removeAttribute("data-scrolling")},c=()=>{r.setAttribute("data-scrolling","true"),o(),i=window.setTimeout(()=>{r.removeAttribute("data-scrolling"),i=null},C2)},u=()=>{c()};return r.addEventListener("scroll",u,{passive:!0}),()=>{r.removeEventListener("scroll",u),l()}},[n]),n}function sp(e){var t,n;return e.runningState==="failed"||!!((t=e.lastErrorCode)!=null&&t.trim())||!!((n=e.lastErrorDetail)!=null&&n.trim())}function xS(e,t,n){return`${e} is-${kS(t,n)}`}function kS(e,t){t==null||t.isActive;const n=T2(e);return t!=null&&t.hasSubagents?n==="error"?"error":n==="unread"?"subagent-unread":n==="running"||n==="running_inferred"?"subagent-running":"subagent":n==="running_inferred"?"running-inferred":n.replace("_","-")}function wS(e){return e.runningState==="stale"?a("conversation.runtimeStale"):e.runningState==="unknown"?a("conversation.runtimeUnknown"):null}function vS(e,t){return t.runningState==="stale"?`${e} is-stale`:t.runningState==="unknown"?`${e} is-unknown`:null}function hK(e){return e?e.activityState==="running"?!0:e.runningState==="starting"||e.runningState==="running"||e.runningState==="reconnecting":!1}function T2(e){return sp(e)?"error":e.runningState==="stale"?"stale":e.runningState==="unknown"?"unknown":e.activityState==="running"?I2(e)?"running_inferred":"running":e.activityState==="completed_unread"?"unread":"idle"}function I2(e){return e.activityResolutionSource==="inferred_log"||e.activitySource==="inferred"}function A2(e){return sp(e)||e.syncStatus==="error"}function R2(e){if(!A2(e))return null;const t=M2(e.lastErrorCode),n=E2(e.lastErrorDetail),r=P2(t,n,e.syncStatus);return{title:e.syncStatus==="error"&&!sp(e)?a("conversation.syncStatusError"):a("conversation.runtimeErrorTitle"),summary:r,code:t,detail:n}}function P2(e,t,n){return t||(n==="error"?a("conversation.syncStatusError"):e?a("conversation.runtimeErrorFallbackDetail"):a("conversation.runtimeErrorFallbackDetail"))}function M2(e){const t=(e==null?void 0:e.trim())??"";return t.length>0?t:null}function E2(e){const t=(e==null?void 0:e.replace(/\s+/g," ").trim())??"";return t.length>0?t:null}function bo(e){const t=e.messages.map(i=>({type:"message",key:i.id,message:i})),n=e.runtimeThinkingPlaceholder??null,r=R2({runningState:e.sessionRunningState??null,syncStatus:e.sessionSyncStatus??null,lastErrorCode:e.sessionLastErrorCode??null,lastErrorDetail:e.sessionLastErrorDetail??null});return n&&t.push({type:"runtime_thinking",key:`runtime-thinking:${n}`,label:n}),r&&t.push({type:"session_error",key:`session-error:${r.code??"none"}:${r.summary??"none"}`,error:r}),t}function L2(e){return e.flatMap(t=>t.type==="message"?[t.message]:[])}function D2(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if((n==null?void 0:n.type)==="runtime_thinking")return n.label}return null}function mK(e,t){const n=e.filter(o=>o.type!=="runtime_thinking");if(!t)return n;const r={type:"runtime_thinking",key:`runtime-thinking:${t}`,label:t},i=n.findIndex(o=>o.type==="session_error");return i<0?[...n,r]:[...n.slice(0,i),r,...n.slice(i)]}function O2(e){return e.replace(/(\.{3,}|…+)$/,"").trimEnd()}function F2(e){const t=e.trim();if(!t)return[];const n=/\b(?:last status:\s*\d{3}\s+[A-Za-z][A-Za-z ]*|\d{3}\s+(?:Too Many Requests|Bad Gateway|Gateway Timeout|Service Unavailable|Unauthorized|Forbidden|Not Found|Internal Server Error))\b|\brequest id:\s*[A-Za-z0-9-]+\b/gi,r=[];let i=0;for(const o of t.matchAll(n)){const l=o.index??0,c=o[0];l>i&&r.push({type:"text",text:t.slice(i,l)}),r.push({type:/^request id:/i.test(c)?"request_id":"status_code",text:c}),i=l+c.length}return i<t.length&&r.push({type:"text",text:t.slice(i)}),r.filter(o=>o.text.length>0)}function SS(e){var r;const t=e.match(/^\s*<turn_aborted>([\s\S]*?)<\/turn_aborted>\s*$/i);if(!t)return null;const n=((r=t[1])==null?void 0:r.trim())??"";return!n||/^previous turn aborted$/i.test(n)?{detail:null}:{detail:n}}function _2(e){return e==="user"?a("conversation.turnAbortedUser"):e==="runtime"?a("conversation.turnAbortedUnexpected"):a("conversation.turnAbortedGeneric")}const B2=480,Yb=80,Jb=240,W2=120,$2=18,z2=50,H2=3500,Ih=d.createContext(!1);function pa(e){return e.replace(/\\/g,"/")}function ku(e){return/^[a-zA-Z]:\//.test(e)}function U2(e){return e.startsWith("/")||e.startsWith("//")||ku(e)}function CS(e){return/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e)&&!ku(e)}function Ah(e){return e.replace(/\/+$/,"")}function Qu(e){const t=e.indexOf("#"),n=t>=0?e.slice(0,t):e,r=n.indexOf("?");return(r>=0?n.slice(0,r):n).replace(/:(\d+)(?::(\d+))?$/,"")}function jS(e){const t=[];for(const n of pa(e).split("/"))if(!(!n||n===".")){if(n===".."){if(t.length===0)return null;t.pop();continue}t.push(n)}return t.join("/")}function Zu(e){try{return decodeURIComponent(e)}catch{return e}}function Rh(e,t){const n=Zu(e).trim();if(!n||n.startsWith("#"))return null;let r=n;if(/^file:\/\//i.test(r))try{r=decodeURIComponent(new URL(r).pathname),/^\/[a-zA-Z]:\//.test(r)&&(r=r.slice(1))}catch{return null}else if(CS(r))return null;if(r=pa(Qu(r.trim())),!r)return null;const i=Ah(pa(t.trim()));if(!i)return null;if(U2(r)){const o=Ah(r),l=ku(i)?i.toLowerCase():i,c=ku(o)?o.toLowerCase():o;if(c===l)return null;const u=`${l}/`;return c.startsWith(u)?o.slice(i.length+1):null}return jS(r)}function NS(e){const t=Zu(e).trim();if(!t||t.startsWith("#"))return null;let n=t;if(/^file:\/\//i.test(n))try{n=decodeURIComponent(new URL(n).pathname),/^\/[a-zA-Z]:\//.test(n)&&(n=n.slice(1))}catch{return null}else if(/^https?:\/\//i.test(n))try{n=decodeURIComponent(new URL(n).pathname)}catch{return null}else if(CS(n))return null;const r=pa(Qu(n)),i=r.match(/(?:^|\/)office-artifacts\/[^/]+\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-[^/]+$/i);if(!(i!=null&&i[1])){const o=r.match(/(?:^|\/)office-artifacts\/([^/]+)\/([^/]+)$/i);return!(o!=null&&o[1])||!(o!=null&&o[2])?null:{kind:"task_file",taskId:o[1],fileName:o[2]}}return{kind:"artifact",artifactId:i[1]}}function q2(e){if(e.name.trim()!=="view_image")return null;const t=ed(e.input);return(t?TS(t,"path").trim():"")||null}function nf(e){return pa(e).split("/").filter(Boolean).at(-1)??e}function Xc(e,t,n){var o;if(n>6||t.length>8||e==null)return;if(typeof e=="string"){const l=e.trim();if(/^data:image\//i.test(l)){t.push(l);return}if(l.startsWith("{")&&l.endsWith("}")||l.startsWith("[")&&l.endsWith("]"))try{Xc(JSON.parse(l),t,n+1)}catch{}return}if(Array.isArray(e)){for(const l of e){if(t.length>8)break;Xc(l,t,n+1)}return}if(!qi(e))return;const r=((o=hn(e,"type"))==null?void 0:o.toLowerCase())??null,i=hn(e,"image_url");i&&/^data:image\//i.test(i)&&(!r||r==="input_image"||r==="image_url")&&t.push(i);for(const l of Object.values(e)){if(t.length>8)break;Xc(l,t,n+1)}}function sf(e){var r,i;const t=[];(r=e.output)!=null&&r.trim()&&t.push(e.output),(i=e.input)!=null&&i.trim()&&t.push(e.input);const n=[];for(const o of t)if(Xc(o,n,0),n.length>0)return n[0]??null;return null}function V2(e,t){const n=pa(Qu(e)).trim();if(!n)return null;const r=n.match(/(?:^|\/)session-attachments\/([^/]+)\/[^/]+\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-[^/]+$/i);if(!(r!=null&&r[2]))return null;const i=(r[1]||(t==null?void 0:t.trim())||"").trim();return i?{kind:"session_attachment",sessionId:i,attachmentId:r[2]}:null}function K2(e,t,n){const r=q2(e);if(!r)return null;const i=NS(r);if(i)return{previewTarget:i.kind==="artifact"?{kind:"office_artifact",artifactId:i.artifactId}:{kind:"office_task_file",taskId:i.taskId,fileName:i.fileName},inlineImageUrl:sf(e),displayPath:r,fileName:nf(r)};const o=V2(r,n);if(o)return{previewTarget:o,inlineImageUrl:sf(e),displayPath:r,fileName:nf(r)};const l=t?Rh(r,t):jS(Qu(r));return{previewTarget:l?{kind:"workspace_file",relativePath:l}:null,inlineImageUrl:sf(e),displayPath:l??r,fileName:nf(r)}}function nl(e,t,n){var r;if(e&&!n&&typeof window<"u"&&((r=window.location)!=null&&r.origin))return new URL(e,window.location.origin).toString();if(e&&n)try{const i=Fu(jl()).baseUrl;return Fk(e,i)}catch{return t}return t}function pl(e){return e.kind==="tool_call"||e.kind==="tool_result"}function rp(e){return e.toolCall?e.toolCall:pl(e)?{callId:e.rawRef||e.id,name:"tool",input:e.kind==="tool_call"?e.content:"",output:e.kind==="tool_result"&&e.content?e.content:null,error:null,status:e.kind==="tool_call"?"running":"completed"}:null}function G2(e){return e==="shell_command"||e==="tool"?a("conversation.roleTool"):e==="web_search"||e==="web_search_20250305"?a("conversation.toolWebSearch"):e}function ed(e){if(!e.trim())return null;try{const t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function TS(e,t){const n=e[t];return typeof n=="string"?n:""}function ra(e,t){for(const n of t){const r=TS(e,n);if(r)return r}return""}function qi(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ps(e,t){if(!e)return null;const n=e[t];return qi(n)?n:null}function Qc(e,t){if(!e)return null;const n=e[t];return Array.isArray(n)?n:null}function hn(e,t){if(!e)return null;const n=e[t];if(typeof n=="string"){const r=n.trim();return r||null}return typeof n=="number"||typeof n=="boolean"?String(n):null}function Y2(e){const t=[e.output,e.input];for(const n of t){const r=IS(n,0);if(r)return r}return null}function IS(e,t){if(!(e!=null&&e.trim())||t>2)return null;try{return AS(JSON.parse(e),t)}catch{return null}}function AS(e,t){if(!qi(e))return null;if(J2(e))return{ok:!0,capability:hn(e,"capability")??"",auditId:hn(e,"auditId")??"",timestamp:hn(e,"timestamp")??"",targetRef:{kind:hn(Ps(e,"targetRef"),"kind")??"none",id:hn(Ps(e,"targetRef"),"id")},payload:Ps(e,"payload")??{}};const n=["output","result","data","payload"];for(const r of n){const i=e[r];if(typeof i=="string"){const o=IS(i,t+1);if(o)return o}if(qi(i)){const o=AS(i,t+1);if(o)return o}}return null}function J2(e){return e.ok===!0&&typeof e.capability=="string"&&typeof e.auditId=="string"&&typeof e.timestamp=="string"&&qi(e.targetRef)&&qi(e.payload)}function X2(e){const t=new Map,n=new Map,r=new Map;return e.forEach(i=>{t.set(i.workspace.id,i.workspace.name),i.sessions.forEach(o=>{const l=typeof o.title=="string"&&o.title.trim()?o.title.trim():o.sessionId;n.set(o.sessionId,l),r.set(o.sessionId,i.workspace.id)})}),{workspaceNamesById:t,sessionNamesById:n,sessionWorkspaceIdsById:r}}function Q2(e,t){const n=Y2(e);return n?{...PS(n.capability),rows:lF(n,t)}:null}function Z2(e,t){const n=eF(e);if(!n)return null;const r=tF(n);return r?{...rF(r),rows:oF(r,t)}:null}function eF(e){const t=ed(e.input),n=t&&typeof t.command=="string"?t.command.trim():"";if(!n)return null;const r=n.indexOf("codingns assistant");return r<0?null:n.slice(r).trim()}function tF(e){const t=nF(e),n=t.findIndex((h,m)=>h==="codingns"&&t[m+1]==="assistant");if(n<0)return null;const r=t.slice(n+2);if(r.length===0||r[0]==="--help"||r[0]==="-h")return{group:null,action:null,mode:"help",options:{},positionals:[]};if(r[0]==="help")return{group:r[1]??null,action:r[2]??null,mode:"help",options:{},positionals:[]};const i=r[0]??null,o=r[1],l=o&&!o.startsWith("-")?o:null,c=r.slice(l?2:1),{options:u,positionals:f}=sF(c);return!l&&u["--help"]?{group:i,action:null,mode:"help",options:u,positionals:f}:{group:i,action:l,mode:"execute",options:u,positionals:f}}function nF(e){const t=[],n=/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'|`([^`\\]|\\.)*`|\S+/g;for(const r of e.matchAll(n)){const i=r[0]??"";if(!i)continue;const o=i[0];if((o==='"'||o==="'"||o==="`")&&i[i.length-1]===o){t.push(i.slice(1,-1));continue}t.push(i)}return t}function sF(e){const t={},n=[];for(let r=0;r<e.length;r+=1){const i=e[r]??"";if(!i.startsWith("--")){n.push(i);continue}const o=e[r+1];if(!o||o.startsWith("--")){t[i]=!0;continue}t[i]=o,r+=1}return{options:t,positionals:n}}function rF(e){if(e.mode==="help")return iF(e.group,e.action);const t=aF(e.group,e.action);return t?PS(t):{kind:ip(e.group),badge:RS(e.group),title:a("conversation.assistantCapabilityQueryTitle"),summary:a("conversation.assistantCliSummaryCommand")}}function iF(e,t){return e?e==="sessions"?{kind:"session",badge:a("conversation.assistantCapabilityBadgeSession"),title:t?a("conversation.assistantCliHelpSessionActionTitle",{action:t}):a("conversation.assistantCliHelpSessionsTitle"),summary:a("conversation.assistantCliSummaryHelp")}:e==="timers"?{kind:"automation",badge:a("conversation.assistantCapabilityBadgeAutomation"),title:a("conversation.assistantCliHelpTimersTitle"),summary:a("conversation.assistantCliSummaryHelp")}:e==="terminals"?{kind:"terminal",badge:a("conversation.assistantCapabilityBadgeTerminal"),title:a("conversation.assistantCliHelpTerminalsTitle"),summary:a("conversation.assistantCliSummaryHelp")}:e==="workspaces"||e==="worktrees"?{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCliHelpWorkspacesTitle"),summary:a("conversation.assistantCliSummaryHelp")}:{kind:ip(e),badge:RS(e),title:a("conversation.assistantCliHelpGenericTitle",{group:e}),summary:a("conversation.assistantCliSummaryHelp")}:{kind:"query",badge:a("conversation.assistantCapabilityBadgeQuery"),title:a("conversation.assistantCliHelpRootTitle"),summary:a("conversation.assistantCliSummaryHelp")}}function aF(e,t){const n=e==null?void 0:e.trim(),r=t==null?void 0:t.trim();return n?n==="capabilities"&&r==="list"?"capabilities.list":n==="projects"&&r==="list"?"projects.list":n==="projects"&&r==="get"?"projects.get":n==="sessions"&&r==="list"?"projects.sessions.list":n==="sessions"&&r==="get"?"sessions.get":n==="sessions"&&r==="messages"?"sessions.messages.list":n==="sessions"&&r==="runtime"?"sessions.runtime.get":n==="sessions"&&r==="start"?"projects.sessions.start":n==="sessions"&&r==="send"?"sessions.message.send":n==="sessions"&&r==="fork"?"sessions.fork":n==="timers"&&r==="create"?"timers.create":n==="timers"&&r==="cancel"?"timers.cancel":n==="timers"&&r==="list"?"timers.list":n==="terminals"&&r==="send"?"terminals.input.send":n==="terminals"&&r==="close"?"terminals.close":n==="terminals"&&r==="history"?"terminals.history.read":n==="terminals"&&r==="list"?"terminals.list":n==="workspaces"&&r==="list"?"workspaces.list":n==="workspaces"&&r==="clone"?"workspaces.clone":n==="workspaces"&&r==="import"?"workspaces.import":n==="workspaces"&&r==="management"?"workspaces.management.get":n==="worktrees"&&r==="tree"?"worktrees.tree":n==="worktrees"&&r==="create"?"worktrees.create":null:null}function ip(e){switch(e){case"sessions":case"projects":return"session";case"timers":return"automation";case"terminals":return"terminal";case"workspaces":case"worktrees":return"workspace";case"debug-targets":case"debug-runtimes":return"debug";default:return"query"}}function RS(e){switch(ip(e)){case"session":return a("conversation.assistantCapabilityBadgeSession");case"automation":return a("conversation.assistantCapabilityBadgeAutomation");case"terminal":return a("conversation.assistantCapabilityBadgeTerminal");case"workspace":return a("conversation.assistantCapabilityBadgeWorkspace");case"debug":return a("conversation.assistantCapabilityBadgeDebug");case"query":default:return a("conversation.assistantCapabilityBadgeQuery")}}function oF(e,t){const n=[],r=Na(e,"--session-id")??e.positionals[0]??null,i=Na(e,"--project")??Na(e,"--project-id");return e.mode==="help"?(Jt(n,a("conversation.assistantCliLabelScope"),e.group??a("conversation.assistantCliScopeRoot")),Jt(n,a("conversation.assistantCliLabelAction"),e.action),n):(e.group==="sessions"&&Jt(n,a("conversation.assistantCapabilityLabelSession"),ca(r,null,t)),e.group==="timers"&&(Jt(n,a("conversation.assistantCapabilityLabelSession"),ca(r,null,t)),Jt(n,a("conversation.assistantCliLabelDelay"),Na(e,"--after-seconds"))),e.group==="terminals"&&Jt(n,a("conversation.assistantCapabilityLabelTerminal"),e.positionals[0]??null),(e.group==="workspaces"||e.group==="worktrees")&&Jt(n,a("conversation.assistantCapabilityLabelWorkspace"),Oi(e.positionals[0]??null,null,t)),Jt(n,a("conversation.assistantCliLabelProject"),i),Jt(n,a("conversation.assistantCliLabelMessage"),Na(e,"--message")),Jt(n,a("conversation.assistantCliLabelInput"),Na(e,"--input")),n.slice(0,4))}function Na(e,t){const n=e.options[t];return typeof n=="string"?n:null}function PS(e){switch(e){case"projects.sessions.start":return{kind:"session",badge:a("conversation.assistantCapabilityBadgeSession"),title:a("conversation.assistantCapabilityProjectSessionStartTitle"),summary:a("conversation.assistantCapabilitySummarySessionStart")};case"sessions.message.send":return{kind:"session",badge:a("conversation.assistantCapabilityBadgeSession"),title:a("conversation.assistantCapabilitySessionSendTitle"),summary:a("conversation.assistantCapabilitySummarySessionSend")};case"sessions.fork":return{kind:"session",badge:a("conversation.assistantCapabilityBadgeSession"),title:a("conversation.assistantCapabilitySessionForkTitle"),summary:a("conversation.assistantCapabilitySummarySessionFork")};case"timers.create":return{kind:"automation",badge:a("conversation.assistantCapabilityBadgeAutomation"),title:a("conversation.assistantCapabilityTimerCreateTitle"),summary:a("conversation.assistantCapabilitySummaryTimerCreate")};case"timers.cancel":return{kind:"automation",badge:a("conversation.assistantCapabilityBadgeAutomation"),title:a("conversation.assistantCapabilityTimerCancelTitle"),summary:a("conversation.assistantCapabilitySummaryTimerCancel")};case"terminals.input.send":return{kind:"terminal",badge:a("conversation.assistantCapabilityBadgeTerminal"),title:a("conversation.assistantCapabilityTerminalInputTitle"),summary:a("conversation.assistantCapabilitySummaryTerminalInput")};case"terminals.close":return{kind:"terminal",badge:a("conversation.assistantCapabilityBadgeTerminal"),title:a("conversation.assistantCapabilityTerminalCloseTitle"),summary:a("conversation.assistantCapabilitySummaryTerminalClose")};case"workspaces.directory.create":return{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorkspaceDirectoryCreateTitle"),summary:a("conversation.assistantCapabilitySummaryWorkspace")};case"workspaces.import":return{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorkspaceImportTitle"),summary:a("conversation.assistantCapabilitySummaryWorkspace")};case"workspaces.clone":return{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorkspaceCloneTitle"),summary:a("conversation.assistantCapabilitySummaryWorkspace")};case"workspaces.navigation-state.update":return{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorkspaceNavigationUpdateTitle"),summary:a("conversation.assistantCapabilitySummaryWorkspace")};case"workspaces.remove":return{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorkspaceRemoveTitle"),summary:a("conversation.assistantCapabilitySummaryWorkspace")};case"worktrees.create":return{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorktreeCreateTitle"),summary:a("conversation.assistantCapabilitySummaryWorktree")};case"worktrees.merge-into-parent":return{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorktreeMergeTitle"),summary:a("conversation.assistantCapabilitySummaryWorktree")};case"worktrees.cleanup":return{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorktreeCleanupTitle"),summary:a("conversation.assistantCapabilitySummaryWorktree")};case"debug-targets.run":return{kind:"debug",badge:a("conversation.assistantCapabilityBadgeDebug"),title:a("conversation.assistantCapabilityDebugRunTitle"),summary:a("conversation.assistantCapabilitySummaryDebug")};default:return e.startsWith("sessions.")||e.startsWith("projects.")?{kind:"session",badge:a("conversation.assistantCapabilityBadgeSession"),title:a("conversation.assistantCapabilitySessionReadTitle"),summary:a("conversation.assistantCapabilitySummaryRead")}:e.startsWith("timers.")?{kind:"automation",badge:a("conversation.assistantCapabilityBadgeAutomation"),title:a("conversation.assistantCapabilityAutomationReadTitle"),summary:a("conversation.assistantCapabilitySummaryRead")}:e.startsWith("terminals.")?{kind:"terminal",badge:a("conversation.assistantCapabilityBadgeTerminal"),title:a("conversation.assistantCapabilityTerminalReadTitle"),summary:a("conversation.assistantCapabilitySummaryRead")}:e.startsWith("workspaces.")||e.startsWith("worktrees.")?{kind:"workspace",badge:a("conversation.assistantCapabilityBadgeWorkspace"),title:a("conversation.assistantCapabilityWorkspaceReadTitle"),summary:a("conversation.assistantCapabilitySummaryRead")}:e.startsWith("debug-targets.")||e.startsWith("debug-runtimes.")?{kind:"debug",badge:a("conversation.assistantCapabilityBadgeDebug"),title:a("conversation.assistantCapabilityDebugReadTitle"),summary:a("conversation.assistantCapabilitySummaryRead")}:{kind:"query",badge:a("conversation.assistantCapabilityBadgeQuery"),title:a("conversation.assistantCapabilityQueryTitle"),summary:a("conversation.assistantCapabilitySummaryRead")}}}function lF(e,t){const n=[],r=e.payload;switch(e.capability){case"projects.sessions.start":{const i=Ps(r,"session");Jt(n,a("conversation.assistantCapabilityLabelSession"),ca(hn(i,"sessionId"),hn(i,"title"),t)),Jt(n,a("conversation.assistantCapabilityLabelProvider"),hn(i,"provider"));break}case"sessions.message.send":{const i=Ps(r,"result");Jt(n,a("conversation.assistantCapabilityLabelSession"),ca(e.targetRef.id,null,t)),Jt(n,a("conversation.assistantCapabilityLabelWorkspace"),MS(e.targetRef.id,t)),Jt(n,a("conversation.assistantCapabilityLabelStatus"),a("conversation.assistantCapabilityStatusCompleted")),Jt(n,a("conversation.assistantCapabilityLabelDueAt"),Xb(hn(i,"acceptedAt")??e.timestamp));break}case"sessions.fork":{const i=Ps(r,"session");Jt(n,a("conversation.assistantCapabilityLabelSession"),ca(hn(i,"sessionId"),hn(i,"title"),t)),Jt(n,a("conversation.assistantCapabilityLabelProvider"),hn(i,"provider"));break}case"timers.create":case"timers.cancel":{const i=Ps(r,"timer"),o=Ps(i,"controlSession"),l=Ps(o,"session");Jt(n,a("conversation.assistantCapabilityLabelTimer"),hn(i,"title")),Jt(n,a("conversation.assistantCapabilityLabelWorkspace"),Oi(hn(l,"workspaceId"),null,t)),Jt(n,a("conversation.assistantCapabilityLabelSession"),ca(hn(i,"targetSessionId"),null,t)),Jt(n,a("conversation.assistantCapabilityLabelDueAt"),Xb(hn(i,"dueAt"))),Jt(n,a("conversation.assistantCapabilityLabelStatus"),dF(hn(i,"status")));break}case"terminals.input.send":case"terminals.close":Jt(n,a("conversation.assistantCapabilityLabelTerminal"),e.targetRef.id);break;case"workspaces.directory.create":{const i=Ps(r,"result");Jt(n,a("conversation.assistantCapabilityLabelPath"),hn(i,"path"));break}case"workspaces.import":case"workspaces.clone":case"workspaces.remove":{const i=Ps(r,"workspace");Jt(n,a("conversation.assistantCapabilityLabelWorkspace"),Oi(hn(i,"id")??e.targetRef.id,hn(i,"name"),t)),Jt(n,a("conversation.assistantCapabilityLabelPath"),hn(i,"path"));break}case"workspaces.navigation-state.update":{const i=Ps(r,"state");Jt(n,a("conversation.assistantCapabilityLabelWorkspace"),Oi(hn(i,"workspaceId")??e.targetRef.id,null,t)),Jt(n,a("conversation.assistantCapabilityLabelStatus"),hn(i,"collapsed")==="true"?a("conversation.assistantCapabilityNavigationCollapsed"):a("conversation.assistantCapabilityNavigationExpanded"));break}case"worktrees.create":{const i=Ps(r,"result"),o=Ps(i,"workspace");Jt(n,a("conversation.assistantCapabilityLabelWorkspace"),Oi(hn(o,"id")??e.targetRef.id,hn(o,"name"),t)),Jt(n,a("conversation.assistantCapabilityLabelBranch"),hn(i,"branchName"));break}case"worktrees.merge-into-parent":case"worktrees.cleanup":{const i=Ps(r,"result");Jt(n,a("conversation.assistantCapabilityLabelWorkspace"),Oi(e.targetRef.id,null,t)),Jt(n,a("conversation.assistantCapabilityLabelStatus"),hn(i,"status"));break}case"debug-targets.run":{const i=Ps(r,"result");Jt(n,a("conversation.assistantCapabilityLabelDebugTarget"),e.targetRef.id),Jt(n,a("conversation.assistantCapabilityLabelRuntime"),hn(i,"runtimeId"));break}}return cF(n,e,t),n.slice(0,4)}function cF(e,t,n){t.targetRef.kind==="session"&&(Jt(e,a("conversation.assistantCapabilityLabelSession"),ca(t.targetRef.id,null,n)),Jt(e,a("conversation.assistantCapabilityLabelWorkspace"),MS(t.targetRef.id,n))),(t.targetRef.kind==="workspace"||t.targetRef.kind==="worktree")&&Jt(e,a("conversation.assistantCapabilityLabelWorkspace"),Oi(t.targetRef.id,null,n)),t.targetRef.kind==="terminal"&&Jt(e,a("conversation.assistantCapabilityLabelTerminal"),t.targetRef.id),t.targetRef.kind==="timer"&&Jt(e,a("conversation.assistantCapabilityLabelTimer"),t.targetRef.id);const r=uF(t.payload);r!==null&&Jt(e,a("conversation.assistantCapabilityLabelCount"),String(r))}function Jt(e,t,n){const r=n==null?void 0:n.trim();r&&(e.some(i=>i.label===t)||e.push({label:t,value:r}))}function ca(e,t,n){const r=t==null?void 0:t.trim();if(r)return r;const i=e==null?void 0:e.trim();return i?n.sessionNamesById.get(i)??i:null}function Oi(e,t,n){const r=t==null?void 0:t.trim();if(r)return r;const i=e==null?void 0:e.trim();return i?n.workspaceNamesById.get(i)??i:null}function MS(e,t){const n=e==null?void 0:e.trim();return n?Oi(t.sessionWorkspaceIdsById.get(n)??null,null,t):null}function uF(e){const t=Qc(e,"items");if(t)return t.length;const n=Ps(e,"page"),r=Qc(n,"items");if(r)return r.length;const i=Ps(e,"history"),o=Qc(i,"items");return o?o.length:null}function Xb(e){const t=e==null?void 0:e.trim();if(!t)return null;const n=Date.parse(t);return Number.isFinite(n)?new Intl.DateTimeFormat(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(n)):t}function dF(e){switch(e){case"active":return a("conversation.assistantCapabilityStatusActive");case"completed":return a("conversation.assistantCapabilityStatusCompleted");case"cancelled":return a("conversation.assistantCapabilityStatusCancelled");case"failed":return a("conversation.assistantCapabilityStatusFailed");default:return e}}function fF({kind:e}){switch(e){case"session":return s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:s.jsx("path",{d:"M5 7.5A2.5 2.5 0 0 1 7.5 5h9A2.5 2.5 0 0 1 19 7.5v5A2.5 2.5 0 0 1 16.5 15H11l-4 4v-4H7.5A2.5 2.5 0 0 1 5 12.5z"})});case"automation":return s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"12",r:"7.5"}),s.jsx("path",{d:"M12 8.5v4.2l2.8 1.8"})]});case"terminal":return s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("path",{d:"m7 8 3.5 3.5L7 15"}),s.jsx("path",{d:"M13 15h4"}),s.jsx("rect",{x:"4.5",y:"5.5",width:"15",height:"13",rx:"2.5"})]});case"workspace":return s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:s.jsx("path",{d:"M4.5 8.5A2.5 2.5 0 0 1 7 6h3l1.5 1.5H17A2.5 2.5 0 0 1 19.5 10v6A2.5 2.5 0 0 1 17 18.5H7A2.5 2.5 0 0 1 4.5 16z"})});case"debug":return s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("path",{d:"M9 4.5h6"}),s.jsx("path",{d:"M10 8h4a4 4 0 0 1 4 4v1a6 6 0 0 1-12 0v-1a4 4 0 0 1 4-4Z"}),s.jsx("path",{d:"M4.5 11h3M16.5 11h3M5.5 7.5l2 1.5M18.5 7.5l-2 1.5"})]});case"query":default:return s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("circle",{cx:"11",cy:"11",r:"5.5"}),s.jsx("path",{d:"m16 16 3.5 3.5"})]})}}function hF(e){if(e.name==="apply_patch"){const c=Hb(e.input);if(c)return c;const u=DO(e.output||e.error||""),f=LO(e.input,u);return f?Hb(f):null}const t=e.name.trim().toLowerCase(),n=mF(t);if(!n)return null;const r=ed(e.input);if(!r)return null;const i=ra(r,["file_path","filePath","path"]);if(!i)return null;if(n==="write"){const c=ra(r,["content","new_content","newContent"]),u=c.length>0?c.split(/\r?\n/):[];return{files:[{path:i,nextPath:null,action:"add",additions:u.length,deletions:0,statsKnown:!0,lines:u.map((f,h)=>({kind:"add",text:`+${f}`,oldLineNumber:null,newLineNumber:h+1}))}],totalAdditions:u.length,totalDeletions:0}}if(n==="edit"){const c=ra(r,["old_string","oldString","old_text","oldText","search","searchText"]).split(/\r?\n/),u=ra(r,["new_string","newString","new_text","newText","replacement","replacementText","replace"]).split(/\r?\n/);return Qb(i,[{oldLines:c,newLines:u}])}const l=(Array.isArray(r.edits)?r.edits:[]).map(c=>{if(!c||typeof c!="object"||Array.isArray(c))return null;const u=c;return{oldLines:ra(u,["old_string","oldString","old_text","oldText","search","searchText"]).split(/\r?\n/),newLines:ra(u,["new_string","newString","new_text","newText","replacement","replacementText","replace"]).split(/\r?\n/)}}).filter(c=>!!c);return l.length>0?Qb(i,l):null}function mF(e){return e==="write"||e==="overwrite"?"write":e==="edit"?"edit":e==="multiedit"||e==="multi_edit"?"multiedit":null}function Qb(e,t){const n=[];let r=0,i=0;return t.forEach((o,l)=>{n.push({kind:"hunk",text:`@@ -1,${o.oldLines.length} +1,${o.newLines.length} @@`,oldLineNumber:null,newLineNumber:null}),o.oldLines.forEach((c,u)=>{c.length===0&&o.oldLines.length===1&&o.newLines.length>0||(i+=1,n.push({kind:"remove",text:`-${c}`,oldLineNumber:u+1,newLineNumber:null}))}),o.newLines.forEach((c,u)=>{c.length===0&&o.newLines.length===1&&o.oldLines.length>0||(r+=1,n.push({kind:"add",text:`+${c}`,oldLineNumber:null,newLineNumber:u+1}))}),l<t.length-1&&n.push({kind:"meta",text:"***",oldLineNumber:null,newLineNumber:null})}),{files:[{path:e,nextPath:null,action:"update",additions:r,deletions:i,statsKnown:!0,lines:n}],totalAdditions:r,totalDeletions:i}}function pF(e){const t=ed(e.input),n=t&&typeof t.command=="string"?t.command.trim():"";if(n)return`${a("conversation.toolPreviewCommand")}:${n}`;if(e.name==="read_thread_terminal")return a("conversation.toolPreviewTerminal");if(e.name==="web_search"||e.name==="web_search_20250305"){const i=t?ra(t,["query","q"]):"";if(i)return`搜索:${i}`}const r=e.input||e.error||e.output||a("conversation.toolResultEmpty");return r.length>60?`${r.slice(0,60)}...`:r}function gF(e){var l;if(e.name!=="web_search"&&e.name!=="web_search_20250305")return null;const t=((l=e.output)==null?void 0:l.trim())??"";if(!t)return null;let n=null;try{n=JSON.parse(t)}catch{return null}if(!qi(n))return null;const r=hn(n,"detail")||a("conversation.toolResultEmpty"),i=hn(n,"query"),o=(Qc(n,"sources")??[]).filter(c=>qi(c)).map(c=>({title:hn(c,"title"),url:hn(c,"url")})).filter(c=>c.title||c.url).slice(0,8);return{detail:r,query:i,sources:o}}function Zb(e){var o;const t=e.map(l=>({message:l,tool:rp(l)})).filter(l=>!!l.tool);if(t.length===0)return null;const n={...t[0].tool};let r=!1,i=!1;for(const{message:l,tool:c}of t)l.kind==="tool_call"&&(r=!0,!n.input&&c.input&&(n.input=c.input)),l.kind==="tool_result"&&(i=!0,n.output=c.output,n.error=c.error,n.status=c.status,!n.input&&c.input&&(n.input=c.input)),!n.name&&c.name&&(n.name=c.name);return{key:t.map(({message:l})=>l.id).join(":"),messageIds:t.map(({message:l})=>l.id),tool:n,hasRequest:r,hasResult:i,updatedAt:((o=t.at(-1))==null?void 0:o.message.timestamp)??t[0].message.timestamp}}function ey(e,t){return e?t?{...t,callId:t.callId||e.callId,name:t.name||e.name,input:t.input||e.input,output:t.output||e.output,error:t.error||e.error,status:t.status==="completed"||t.status==="failed"?t.status:e.status}:{...e}:t?{...t}:null}function bF(e){const t=new Map;for(const n of e){if(!pl(n))continue;const r=rp(n),i=(r==null?void 0:r.callId.trim())??"";if(!r||!i||r.name.trim()!=="view_image")continue;const o=ey(t.get(i)??null,r);o&&t.set(i,o)}return e.map(n=>{if(!pl(n)||!n.toolCall||n.toolCall.name.trim()!=="view_image")return n;const r=n.toolCall.callId.trim();if(!r)return n;const i=t.get(r);if(!i)return n;const o=ey(n.toolCall,i);return o?{...n,toolCall:o}:n})}function yF(e){const t=[];let n=[],r=null;function i(){if(n.length===0)return;const o=Zb(n);o&&t.push(o),n=[],r=null}for(const o of e){const l=rp(o),c=(l==null?void 0:l.callId.trim())??"";if(!l||c.length===0){i();const u=Zb([o]);u&&t.push(u);continue}if(n.length===0){n=[o],r=c;continue}if(r===c){n.push(o);continue}i(),n=[o],r=c}return i(),t}function xF(e,t){const n=bF(t),r=new Map(n.map(f=>[f.id,f])),i=e.map(f=>f.type==="message"?{...f,message:r.get(f.message.id)??f.message}:f),o=[],l=[];let c=0;function u(){if(l.length===0)return;const f=yF(l);if(f.length===0){const h=l[0];h&&o.push({type:"message",key:h.id,message:h}),l.length=0;return}f.forEach(h=>{o.push({type:"tool_group",key:h.key,group:h})}),l.length=0}for(const f of i){if(f.type!=="message"){u(),o.push(f);continue}const h=f.message,m=c;if(c+=1,!LS(n,m)){if(!pl(h)){u(),o.push({type:"message",key:h.id,message:h});continue}l.push(h)}}return u(),o}function kF(e,t){var c;if(!e||e.forkSourceType!=="message"||typeof e.inheritedPrefixMessageCount!="number"||e.inheritedPrefixMessageCount<0)return{visibleItems:t,visibleMessages:t.flatMap(u=>u.type==="message"?[u.message]:[]),hiddenMessageIds:[]};const n=((c=e.createdAt)==null?void 0:c.trim())||"";if(n.length===0)return{visibleItems:t,visibleMessages:t.flatMap(u=>u.type==="message"?[u.message]:[]),hiddenMessageIds:[]};const r=Math.max(0,e.inheritedPrefixMessageCount),i=[],o=[],l=[];for(const u of t){if(u.type!=="message"){i.push(u);continue}const f=u.message;if(f.sequence<=r||f.timestamp>=n){i.push(u),o.push(f);continue}l.push(f.id)}return{visibleItems:i,visibleMessages:o,hiddenMessageIds:l}}function ES(e){const t=kF(e.sessionSummary,e.items),n=xF(t.visibleItems,t.visibleMessages),r=NF(t.visibleMessages,e.provider),i=VF(t.visibleMessages);return{visibleMessages:t.visibleMessages,renderItems:n,leadingSystemPromptMessageIds:r,actionStateByMessageId:i,hiddenMessageIds:t.hiddenMessageIds,validationIssues:wF(t.visibleMessages,n)}}function wF(e,t){const n=[],r=t.map(u=>u.key),i=vF(r);i.length>0&&n.push(`duplicate_render_keys:${i.join(",")}`);const o=[];for(const u of t){if(u.type==="message"){o.push(u.message.id);continue}u.type==="tool_group"&&o.push(...u.group.messageIds)}const l=new Set(o);for(const u of e)ty(e,u.id)&&!l.has(u.id)&&n.push(`missing_render_message:${u.id}`);const c=e.filter(u=>ty(e,u.id)).map(u=>u.id);return o.join(",")!==c.join(",")&&n.push("render_order_mismatch"),n}function ty(e,t){const n=e.findIndex(r=>r.id===t);return n<0?!1:!LS(e,n)}function vF(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)??0)+1);return Array.from(t.entries()).filter(([,n])=>n>1).map(([n])=>n)}function LS(e,t){const n=e[t];if(!n||SS(n.content)===null)return!1;for(let r=t-1;r>=0;r-=1){const i=e[r];if(!(!i||pl(i)))return i.role==="user"}return!1}function SF(e,t){if(!qA(null,e))return!1;const n=t.trim();return/AGENTS\.md instructions for/i.test(n)&&/<INSTRUCTIONS>/i.test(n)&&/<\/INSTRUCTIONS>/i.test(n)}function CF(e,t){if(e!=="claude-code")return!1;const n=t.trim();return/Base directory for this skill:/i.test(n)&&/^#\s+.+/im.test(n)&&/\bARGUMENTS:/i.test(n)}function jF(e,t){if(e==="skill_context"){const r=t.split(/\r?\n/).map(i=>i.trim()).find(i=>/^#\s+/.test(i));if(r)return r.replace(/^#+\s*/,"")}const n=t.split(/\r?\n/).map(r=>r.trim()).find(Boolean);return n?n.replace(/^#+\s*/,""):a("conversation.rulesMessageTitle")}function NF(e,t){const n=new Set;if(t!=="kimi")return n;for(const r of e){if(r.role==="system"&&r.kind==="text"){n.add(r.id);continue}break}return n}function TF(e){const t=[];for(const n of e){if(n.type==="message"){t.push(n.message.id);continue}n.type==="tool_group"&&t.push(...n.group.messageIds)}return t}function IF(e,t,n){if(!e)return[];const r=new Set(n.filter(u=>u.role==="assistant").map(u=>u.id));if(r.size===0)return[];const i=new Map(e.map((u,f)=>[u,f])),o=new Map(t.map((u,f)=>[u,f])),l=new Map(n.map(u=>[u.id,u])),c=[];for(const u of r){const f=i.get(u)??null,h=o.get(u)??null;if(f===h)continue;const m=l.get(u)??null;c.push({messageId:u,fromIndex:f,toIndex:h,sequence:(m==null?void 0:m.sequence)??null,rawRef:(m==null?void 0:m.rawRef)??null,timestamp:(m==null?void 0:m.timestamp)??null})}return c.slice(0,8)}function gl(e){var t;return typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(n=>gl(n)).join(""):e&&typeof e=="object"&&"props"in e?gl(((t=e.props)==null?void 0:t.children)??""):""}function AF(e){const t=Array.isArray(e)?e[0]:e;if(!d.isValidElement(t))return null;const n=t.props,r=typeof n.className=="string"?n.className:"",i=/language-([^\s]+)/.exec(r);return{content:gl(n.children).replace(/\n$/,""),codeClassName:r||void 0,language:(i==null?void 0:i[1])??null}}function RF(e){if(typeof document>"u"||typeof document.execCommand!="function")return!1;const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(t)}}async function ap(e,t){var n;if(!(t.isDesktop&&(await t.bridge.writeClipboardText(e)).ok)){if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText))try{await navigator.clipboard.writeText(e);return}catch{}if(!RF(e))throw new Error(a("conversation.copyContentFailed"))}}function PF({className:e,children:t,onCopy:n,exportMode:r=!1}){const i=d.useContext(Ih),o=gl(t).trim();if(r||i||!o)return s.jsx("code",{className:e||void 0,children:t});function l(c){c.key!=="Enter"&&c.key!==" "||(c.preventDefault(),n(o))}return s.jsx("code",{className:[e,"markdown-inline-copy"].filter(Boolean).join(" "),role:"button",tabIndex:0,"aria-label":a("conversation.copyAction"),onClick:()=>n(o),onKeyDown:l,children:t})}function MF({href:e,children:t,className:n,onInteract:r,exportMode:i=!1}){if(i)return s.jsx(Ih.Provider,{value:!0,children:s.jsx("a",{href:e,className:n,children:t})});const o=gl(t).trim()||(e?Zu(e).trim():"");return s.jsx(Ih.Provider,{value:!0,children:s.jsx("a",{href:e,className:[n,"markdown-interactive-link"].filter(Boolean).join(" "),onClick:l=>{l.preventDefault(),r(e,o)},children:t})})}function DS({language:e,codeClassName:t,content:n,exportMode:r=!1}){const{showToast:i}=Vn(),o=Hn(),l=(e==null?void 0:e.trim().toLowerCase())??null,c=l==="text",u=l||"code";async function f(){try{await ap(n,o),i({title:a("conversation.copyContentSuccess"),tone:"success"})}catch(h){i({title:h instanceof Error?h.message:a("conversation.copyContentFailed"),tone:"error"})}}return s.jsxs("div",{className:`code-block${c?" text-code-block":""}`,children:[s.jsxs("div",{className:"code-header",children:[s.jsx("span",{className:"code-header-label",children:u}),r?null:s.jsx("button",{className:"code-copy-button",type:"button",onClick:()=>void f(),children:a("conversation.copyAction")})]}),s.jsx("pre",{className:t,children:s.jsx("code",{children:n})})]})}function zo({content:e,className:t,exportMode:n=!1}){const{showToast:r}=Vn(),i=Hn(),{navigationGroups:o,currentWorkspaceId:l,revealWorkspaceFile:c}=Wp(),[u,f]=d.useState({}),h=d.useMemo(()=>{var b;return((b=o.find(y=>y.workspace.id===l))==null?void 0:b.workspace)??null},[l,o]),m=h!=null&&h.path?Ah(pa(h.path.trim())):null;d.useEffect(()=>{const y=Array.from(e.matchAll(/!\[[^\]]*]\(([^)\s]+(?:\s+"[^"]*")?)\)|<img\b[^>]*src=["']([^"']+)["'][^>]*>/gi)).map(H=>(H[1]??H[2]??"").trim()).filter(H=>H.length>0);if(y.length===0){f({});return}const x=Array.from(new Map(y.map(H=>{const _=H.replace(/^<|>$/g,"").replace(/\s+"[^"]*"$/,"");if(!_||_.startsWith("#"))return null;const T=NS(_);return T?[_,T]:null}).filter(H=>H!==null))),k=new Set(x.map(([H])=>H)),C=Array.from(new Map(y.map(H=>{const _=H.replace(/^<|>$/g,"").replace(/\s+"[^"]*"$/,"");if(!_||_.startsWith("#")||k.has(_)||/^data:image\//i.test(_)||/^https?:\/\//i.test(_)||!l||!m)return null;const T=Rh(_,m);return T?[_,T]:null}).filter(H=>H!==null)).entries()).map(([H,_])=>({sourceUrl:H,relativePath:_}));let j=!1;return Promise.all([...x.map(async([H,_])=>{try{const T=_.kind==="artifact"?await dw(_.artifactId):await fw(_.taskId,_.fileName),P=nl(T.previewPath,T.previewUrl,i.isDesktop);return P?[H,P]:null}catch{return null}}),...C.map(async H=>{try{if(!l)return null;const _=await zu(l,H.relativePath),T=nl(_.previewPath,_.previewUrl,i.isDesktop);return T?[H.sourceUrl,T]:null}catch{return null}})]).then(H=>{j||f(Object.fromEntries([...H.filter(_=>_!==null)]))}),()=>{j=!0}},[e,l,m,i.isDesktop]);async function g(b){if(b.trim())try{await ap(b,i),r({title:a("conversation.copyContentSuccess"),tone:"success"})}catch(y){r({title:y instanceof Error?y.message:a("conversation.copyContentFailed"),tone:"error"})}}function p(b,y){const x=b&&(h!=null&&h.path)?Rh(b,h.path):null;x&&c({workspaceId:(h==null?void 0:h.id)??l,filePath:x,openViewer:!1})||g(y||(b?Zu(b).trim():""))}return s.jsx("div",{className:t,children:s.jsx(Tv,{remarkPlugins:[Xv],components:{p:({node:b,...y})=>s.jsx("p",{...y}),a(b){return s.jsx(MF,{href:typeof b.href=="string"?b.href:void 0,className:typeof b.className=="string"?b.className:void 0,onInteract:p,exportMode:n,children:b.children})},img(b){const y=typeof b.src=="string"?b.src.trim():"",x=u[y]??y,k=typeof b.alt=="string"?b.alt:"";return x?s.jsx("img",{src:x,alt:k,className:"message-markdown-image",loading:"lazy",decoding:"async"}):null},pre(b){const y=AF(b.children);return y?s.jsx(DS,{language:y.language,codeClassName:y.codeClassName,content:y.content,exportMode:n}):s.jsx("pre",{children:b.children})},code(b){const y=typeof b.className=="string"?b.className:"";return s.jsx(PF,{className:y||void 0,exportMode:n,onCopy:x=>{g(x)},children:b.children})}},children:e})})}function ny(e,t){return e.kind!=="image"||!(t!=null&&t.contentBase64)||t.mimeType!==e.mimeType?null:`data:${t.mimeType};base64,${t.contentBase64}`}function EF(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function pc({sessionId:e,attachmentPayloads:t=[],attachments:n=[],inlineImages:r=[]}){return s.jsx(LF,{sessionId:e,attachments:n,attachmentPayloads:t,inlineImages:r})}function LF({sessionId:e,attachmentPayloads:t=[],attachments:n=[],inlineImages:r=[]}){const[i,o]=d.useState({}),[l,c]=d.useState(null),u=d.useMemo(()=>n.map((g,p)=>{const b=ny(g,t==null?void 0:t[p]);if(b)return{id:g.id,kind:g.kind,fileName:g.fileName,fileSize:g.fileSize,url:b,status:"ready"};const y=i[g.id];return{id:g.id,kind:g.kind,fileName:g.fileName,fileSize:g.fileSize,url:(y==null?void 0:y.url)??null,status:(y==null?void 0:y.status)??(e?"loading":"error")}}),[t,n,i,e]),f=d.useMemo(()=>r.map((g,p)=>({id:`inline-image-${p}`,kind:"image",fileName:g.altText||`${a("conversation.imageAttachmentLabel")} ${p+1}`,fileSize:g.estimatedBytes,url:g.url,status:"ready"})),[r]),h=d.useMemo(()=>[...f,...u],[u,f]),m=h.find(g=>g.id===l)??null;return d.useEffect(()=>{if(!l)return;function g(p){p.key==="Escape"&&c(null)}return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[l]),d.useEffect(()=>{const g=n.filter((y,x)=>!ny(y,t==null?void 0:t[x]));if(!e||g.length===0){o({});return}let p=!1;const b=[];return o(Object.fromEntries(g.map(y=>[y.id,{id:y.id,kind:y.kind,fileName:y.fileName,fileSize:y.fileSize,url:null,status:"loading"}]))),Promise.all(g.map(async y=>{try{const x=await lw(e,y.id),k=URL.createObjectURL(x);return b.push(k),{id:y.id,kind:y.kind,fileName:y.fileName,fileSize:y.fileSize,url:k,status:"ready"}}catch{return{id:y.id,kind:y.kind,fileName:y.fileName,fileSize:y.fileSize,url:null,status:"error"}}})).then(y=>{if(p){b.forEach(x=>URL.revokeObjectURL(x));return}o(Object.fromEntries(y.map(x=>[x.id,x])))}),()=>{p=!0,b.forEach(y=>URL.revokeObjectURL(y))}},[t,n,e]),h.length===0?null:s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"message-attachments",children:h.map(g=>{const p=g.kind==="image",b=g.status==="loading"?a("conversation.attachmentPreviewLoading"):g.status==="error"?a("conversation.attachmentPreviewUnavailable"):p?a("conversation.attachmentPreviewOpen"):a("conversation.attachmentDownload"),y=EF(g.fileSize),x=s.jsx("div",{className:"message-attachment-card",children:p?g.url?s.jsx("img",{className:"message-attachment-thumbnail",src:g.url,alt:g.fileName||a("conversation.attachmentPreviewAlt"),loading:"lazy"}):s.jsx("div",{className:"message-attachment-placeholder","aria-hidden":"true",children:g.status==="loading"?a("conversation.attachmentPreviewLoading"):a("conversation.attachmentPreviewUnavailable")}):s.jsxs("div",{className:"message-attachment-file-card",children:[s.jsx("div",{className:"message-attachment-file-icon","aria-hidden":"true",children:s.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),s.jsx("path",{d:"M14 2v5h5"}),s.jsx("path",{d:"M9 13h6"}),s.jsx("path",{d:"M9 17h6"})]})}),s.jsxs("div",{className:"message-attachment-file-meta",children:[s.jsx("strong",{title:g.fileName,children:g.fileName}),s.jsx("span",{children:y??a("conversation.fileAttachmentLabel")})]})]})});return!p&&g.url?s.jsx("a",{className:"message-attachment-button",href:g.url,download:g.fileName,"aria-label":`${g.fileName} - ${b}`,title:b,children:x},g.id):s.jsx("button",{type:"button",className:"message-attachment-button",onClick:()=>p&&g.url&&c(g.id),disabled:!g.url,"aria-label":`${g.fileName} - ${b}`,title:b,children:x},g.id)})}),s.jsx(Qr,{open:!!(m!=null&&m.url),title:a("conversation.imagePreviewTitle"),description:m==null?void 0:m.fileName,size:"xwide",layout:"viewer",className:"message-image-modal",bodyClassName:"message-image-modal-body",onClose:()=>c(null),children:m!=null&&m.url?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"message-image-modal-stage",children:s.jsx("img",{className:"message-image-modal-image",src:m.url,alt:m.fileName||a("conversation.attachmentPreviewAlt")})}),s.jsx("p",{className:"message-image-modal-hint",children:a("conversation.imagePreviewHint")})]}):null})]})}function DF(){return s.jsx("div",{className:"timeline-skeleton","aria-hidden":"true",children:Array.from({length:3},(e,t)=>s.jsxs("article",{className:`timeline-skeleton-item ${t%2===0?"assistant":"user"}`,children:[s.jsx("div",{className:"timeline-skeleton-avatar"}),s.jsxs("div",{className:"timeline-skeleton-bubble",children:[s.jsx("span",{className:"timeline-skeleton-line long"}),s.jsx("span",{className:"timeline-skeleton-line medium"}),s.jsx("span",{className:"timeline-skeleton-line short"})]})]},t))})}function OF({tool:e,preview:t,exportMode:n=!1}){const[r,i]=d.useState(null),o=r===null?null:t.files[r]??null;return d.useEffect(()=>{if(r===null)return;function l(c){c.key==="Escape"&&i(null)}return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[r]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"tool-call-item apply-patch-item",children:t.files.map((l,c)=>n?s.jsxs("div",{className:"apply-patch-summary-row",children:[s.jsx("span",{className:"apply-patch-summary-label",children:rf(l.action)}),s.jsx("span",{className:"apply-patch-summary-file",title:gc(l),children:Ub(l.nextPath??l.path)}),of(l)]},af(l,c)):s.jsxs("button",{type:"button",className:"apply-patch-summary-row",onClick:()=>i(c),children:[s.jsx("span",{className:"apply-patch-summary-label",children:rf(l.action)}),s.jsx("span",{className:"apply-patch-summary-file",title:gc(l),children:Ub(l.nextPath??l.path)}),of(l)]},af(l,c)))}),s.jsx(Qr,{open:o!==null,title:a("conversation.applyPatchDialogTitle"),description:a("conversation.applyPatchDialogDescription"),size:"full",layout:"viewer",className:"apply-patch-modal",bodyClassName:"apply-patch-modal-body",onClose:()=>i(null),children:o?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"apply-patch-modal-totals",children:BF(o)}),s.jsxs("section",{className:"apply-patch-file-panel",children:[s.jsxs("div",{className:"apply-patch-file-panel-header",children:[s.jsxs("div",{className:"apply-patch-file-panel-title",children:[s.jsx("span",{className:"apply-patch-summary-label",children:rf(o.action)}),s.jsx("strong",{children:gc(o)})]}),of(o)]}),s.jsx("div",{className:"apply-patch-diff-view",children:s.jsx("div",{className:"apply-patch-diff-scroll",children:o.lines.map((l,c)=>s.jsxs("div",{className:`apply-patch-diff-line ${WF(l.kind)}`,children:[s.jsx("span",{className:"apply-patch-line-number",children:ry(l.oldLineNumber)}),s.jsx("span",{className:"apply-patch-line-number",children:ry(l.newLineNumber)}),s.jsx("span",{className:"apply-patch-line-content",children:l.text||" "})]},`${gc(o)}:${c}`))})})]},af(o,r??0)),e.error?s.jsxs("section",{className:"apply-patch-error-panel",children:[s.jsx("div",{className:"tool-call-section-label",children:a("conversation.toolResultLabel")}),s.jsx("pre",{className:"tool-call-error",children:e.error})]}):null]}):null})]})}function FF({tool:e,snapshot:t,sessionId:n,workspaceId:r,exportMode:i=!1}){const o=Hn(),[l,c]=d.useState({status:"idle",url:null});return d.useEffect(()=>{if(i){c({status:"idle",url:null});return}if(t.inlineImageUrl){c({status:"ready",url:t.inlineImageUrl});return}if(!t.previewTarget){c({status:"idle",url:null});return}let u=!1,f=null;return c({status:"loading",url:null}),(t.previewTarget.kind==="workspace_file"?r?zu(r,t.previewTarget.relativePath).then(m=>({url:nl(m.previewPath,m.previewUrl,o.isDesktop)})):Promise.reject(new Error("workspace preview requires workspaceId")):t.previewTarget.kind==="session_attachment"?lw(t.previewTarget.sessionId||n||"",t.previewTarget.attachmentId).then(m=>(f=URL.createObjectURL(m),{url:f})):t.previewTarget.kind==="office_artifact"?dw(t.previewTarget.artifactId).then(m=>({url:nl(m.previewPath,m.previewUrl,o.isDesktop)})):fw(t.previewTarget.taskId,t.previewTarget.fileName).then(m=>({url:nl(m.previewPath,m.previewUrl,o.isDesktop)}))).then(({url:m})=>{if(u){f&&URL.revokeObjectURL(f);return}c(m?{status:"ready",url:m}:{status:"error",url:null})}).catch(()=>{f&&(URL.revokeObjectURL(f),f=null),u||c({status:"error",url:null})}),()=>{u=!0,f&&URL.revokeObjectURL(f)}},[i,o.isDesktop,n,t.inlineImageUrl,t.previewTarget,r]),s.jsxs("div",{className:`tool-call-item view-image-tool-item ${e.status==="completed"?"tool-result":""}`,children:[s.jsx("div",{className:"tool-call-header view-image-tool-header",children:s.jsxs("div",{className:"tool-call-info",children:[s.jsx("span",{className:"tool-call-name",children:a("conversation.toolViewImageActiveLabel")}),s.jsx("span",{className:"tool-call-input-preview",children:t.displayPath})]})}),i?null:s.jsx("div",{className:"view-image-tool-preview",children:l.status==="ready"?s.jsx("img",{src:l.url,alt:t.fileName||a("conversation.attachmentPreviewAlt")}):s.jsx("div",{className:"view-image-tool-placeholder",children:l.status==="loading"?a("conversation.attachmentPreviewLoading"):a("conversation.attachmentPreviewUnavailable")})})]})}function OS({group:e,sessionId:t,workspaceId:n,workspacePath:r,exportMode:i=!1}){const[o,l]=d.useState(!1),{navigationGroups:c}=Wp(),{tool:u,hasRequest:f,hasResult:h}=e,m=G2(u.name),g=d.useMemo(()=>K2(u,r,t),[t,u,r]),p=d.useMemo(()=>X2(c),[c]),b=d.useMemo(()=>Q2(u,p),[p,u]),y=d.useMemo(()=>Z2(u,p),[p,u]),x=d.useMemo(()=>a2(u,null,e.updatedAt),[e.updatedAt,u]),k=d.useMemo(()=>hF(u),[u.input,u.name]);if(g)return s.jsx(FF,{tool:u,snapshot:g,sessionId:t,workspaceId:n,exportMode:i});if(k)return s.jsx(OF,{tool:u,preview:k,exportMode:i});if(b)return s.jsx(sy,{tool:u,snapshot:b,expanded:o,hasRequest:f,hasResult:h,exportMode:i,onToggleExpanded:()=>{l(P=>!P)}});if(y)return s.jsx(sy,{tool:u,snapshot:y,expanded:o,hasRequest:f,hasResult:h,exportMode:i,onToggleExpanded:()=>{l(P=>!P)}});if(x)return s.jsx(_F,{tool:u,snapshot:x,expanded:o,hasRequest:f,hasResult:h,exportMode:i,onToggleExpanded:()=>{l(P=>!P)}});const C=pF(u),j=gF(u),H=!!(u.input||u.output||u.error),_=H&&!i,T=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"tool-call-info",children:[s.jsx("span",{className:"tool-call-name",children:m}),s.jsx("span",{className:"tool-call-input-preview",children:C})]}),s.jsx("div",{className:"tool-call-meta",children:_&&s.jsx("span",{className:`tool-call-toggle ${o?"expanded":""}`,children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:s.jsx("polyline",{points:"6 9 12 15 18 9"})})})})]});return s.jsxs("div",{className:`tool-call-item ${h?"tool-result":""}`,children:[i?s.jsx("div",{className:"tool-call-header",children:T}):s.jsx("button",{type:"button",className:"tool-call-header",onClick:()=>H&&l(P=>!P),children:T}),o&&H&&s.jsxs("div",{className:"tool-call-output",children:[f&&u.input&&s.jsxs("div",{className:"tool-call-section",children:[s.jsx("div",{className:"tool-call-section-label",children:a("conversation.toolInputLabel")}),s.jsx("pre",{children:u.input})]}),(h||u.error||u.output)&&s.jsxs("div",{className:"tool-call-section",children:[s.jsx("div",{className:"tool-call-section-label",children:a("conversation.toolResultLabel")}),j&&!u.error?s.jsxs("div",{className:"tool-web-search-result",children:[s.jsx("p",{className:"tool-web-search-detail",children:j.detail}),j.query?s.jsxs("div",{className:"tool-web-search-meta",children:[s.jsx("span",{className:"tool-web-search-meta-label",children:a("conversation.toolWebSearchQueryLabel")}),s.jsx("span",{className:"tool-web-search-meta-value",children:j.query})]}):null,j.sources.length>0?s.jsxs("div",{className:"tool-web-search-sources",children:[s.jsx("div",{className:"tool-web-search-sources-label",children:a("conversation.toolWebSearchSourcesLabel")}),s.jsx("ul",{className:"tool-web-search-source-list",children:j.sources.map((P,z)=>{const L=`${P.url||P.title||"source"}-${z}`,R=P.title||P.url||a("conversation.toolWebSearchUntitledSource");return s.jsxs("li",{className:"tool-web-search-source-item",children:[P.url?s.jsx("a",{className:"tool-web-search-source-link",href:P.url,target:"_blank",rel:"noreferrer",children:R}):s.jsx("span",{className:"tool-web-search-source-title",children:R}),P.url?s.jsx("span",{className:"tool-web-search-source-url",children:P.url}):null]},L)})})]}):null]}):s.jsx("pre",{className:u.error?"tool-call-error":void 0,children:u.error||u.output||a("conversation.toolResultEmpty")})]})]})]})}function sy({tool:e,snapshot:t,expanded:n,hasRequest:r,hasResult:i,onToggleExpanded:o,exportMode:l=!1}){const c=n?a("conversation.assistantCapabilityRawCollapse"):a("conversation.assistantCapabilityRawExpand");return s.jsxs("div",{className:"tool-call-item assistant-capability-item","data-kind":t.kind,children:[s.jsxs("div",{className:"assistant-capability-header",children:[s.jsxs("div",{className:"assistant-capability-heading",children:[s.jsx("span",{className:"assistant-capability-icon",children:s.jsx(fF,{kind:t.kind})}),s.jsxs("div",{className:"assistant-capability-heading-main",children:[s.jsx("span",{className:"assistant-capability-badge",children:t.badge}),s.jsx("strong",{children:t.title}),s.jsx("span",{className:"assistant-capability-summary",children:t.summary})]})]}),l?null:s.jsx("button",{type:"button",className:"task-tool-raw-toggle",onClick:o,children:c})]}),t.rows.length>0?s.jsx("div",{className:"assistant-capability-list",children:t.rows.map(u=>s.jsxs("div",{className:"assistant-capability-row",children:[s.jsx("span",{className:"assistant-capability-row-label",children:u.label}),s.jsx("span",{className:"assistant-capability-row-value",children:u.value})]},u.label))}):null,!l&&n?s.jsxs("div",{className:"tool-call-output",children:[r&&e.input?s.jsxs("div",{className:"tool-call-section",children:[s.jsx("div",{className:"tool-call-section-label",children:a("conversation.toolInputLabel")}),s.jsx("pre",{children:e.input})]}):null,i||e.error||e.output?s.jsxs("div",{className:"tool-call-section",children:[s.jsx("div",{className:"tool-call-section-label",children:a("conversation.toolResultLabel")}),s.jsx("pre",{className:e.error?"tool-call-error":void 0,children:e.error||e.output||a("conversation.toolResultEmpty")})]}):null]}):null]})}function _F({tool:e,snapshot:t,expanded:n,hasRequest:r,hasResult:i,onToggleExpanded:o,exportMode:l=!1}){return s.jsx(fS,{snapshot:t,toolName:e.name,expanded:n,exportMode:l,onToggleExpanded:l?void 0:o,children:!l&&n?s.jsxs("div",{className:"tool-call-output",children:[r&&e.input?s.jsxs("div",{className:"tool-call-section",children:[s.jsx("div",{className:"tool-call-section-label",children:a("conversation.toolInputLabel")}),s.jsx("pre",{children:e.input})]}):null,i||e.error||e.output?s.jsxs("div",{className:"tool-call-section",children:[s.jsx("div",{className:"tool-call-section-label",children:a("conversation.toolResultLabel")}),s.jsx("pre",{className:e.error?"tool-call-error":void 0,children:e.error||e.output||a("conversation.toolResultEmpty")})]}):null]}):null})}function rf(e){return e==="add"?a("conversation.applyPatchAddedLabel"):e==="delete"?a("conversation.applyPatchDeletedLabel"):a("conversation.applyPatchEditedLabel")}function gc(e){return e.nextPath&&e.nextPath!==e.path?`${e.path} -> ${e.nextPath}`:e.nextPath??e.path}function af(e,t){return`${e.path}:${e.nextPath??""}:${t}`}function of(e){return e.statsKnown?s.jsxs("span",{className:"apply-patch-summary-stats",children:[s.jsxs("span",{className:"apply-patch-summary-added",children:["+",e.additions]}),s.jsxs("span",{className:"apply-patch-summary-removed",children:["-",e.deletions]})]}):s.jsx("span",{className:"apply-patch-summary-stats",children:s.jsx("span",{className:"apply-patch-summary-edited",children:a("conversation.applyPatchEditedStat")})})}function BF(e){return e.statsKnown?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"apply-patch-stat-pill positive",children:[a("conversation.applyPatchAddedStat")," +",e.additions]}),s.jsxs("span",{className:"apply-patch-stat-pill negative",children:[a("conversation.applyPatchRemovedStat")," -",e.deletions]})]}):s.jsx("span",{className:"apply-patch-stat-pill neutral",children:a("conversation.applyPatchEditedStat")})}function WF(e){return e==="add"?"is-added":e==="remove"?"is-removed":e==="hunk"?"is-hunk":e==="meta"?"is-meta":"is-context"}function ry(e){return e===null||e<=0?"":String(e)}function $F(e){return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function FS({timestamp:e,leading:t,children:n}){return s.jsxs("div",{className:"user-message-footer",children:[s.jsx("div",{className:"user-message-footer-leading",children:t}),s.jsxs("div",{className:"user-message-footer-trailing",children:[s.jsx("time",{className:"message-time",dateTime:e,children:$F(e)}),n]})]})}function oa({text:e,canCopy:t=!0,canFork:n=!1,compact:r=!1,onFork:i}){const{showToast:o}=Vn(),l=Hn(),[c,u]=d.useState(!1),[f,h]=d.useState(!1),m=e.trim().length>0,g=t&&m;async function p(){if(!(!g||c)){u(!0);try{await ap(e,l),o({title:a("conversation.copyContentSuccess"),tone:"success"})}catch(y){o({title:y instanceof Error?y.message:a("conversation.copyContentFailed"),tone:"error"})}finally{u(!1)}}}async function b(){if(!(!i||f)){h(!0);try{await i()}finally{h(!1)}}}return!g&&!n?null:s.jsxs("div",{className:r?"message-metadata-bar compact":"message-metadata-bar",children:[g?s.jsx("button",{type:"button",className:"message-metadata-action","aria-label":a("conversation.copyAction"),title:a("conversation.copyAction"),onClick:()=>{p()},disabled:c,children:s.jsx(y2,{})}):null,n?s.jsx("button",{type:"button",className:"message-metadata-action","aria-label":f?a("conversation.forkingAction"):a("conversation.forkFromHereAction"),title:f?a("conversation.forkingAction"):a("conversation.forkFromHereAction"),onClick:()=>{b()},disabled:f,children:s.jsx(x2,{})}):null]})}function zF({message:e,kind:t,tone:n,actionState:r,onRetry:i,onForkMessage:o,forceExpanded:l=!1,exportMode:c=!1}){const[u,f]=d.useState(!1),h=jF(t,e.content),m=n==="user-message",g=l||u,p=t==="system_prompt"?a("conversation.systemPromptTitle"):t==="skill_context"?a("conversation.skillContextTitle"):a("conversation.rulesMessageTitle"),b=t==="system_prompt"?a("conversation.systemPromptHint"):t==="skill_context"?a("conversation.skillContextHint"):a("conversation.rulesMessageHint"),y=g?t==="system_prompt"?a("conversation.systemPromptCollapse"):t==="skill_context"?a("conversation.skillContextCollapse"):a("conversation.rulesMessageCollapse"):t==="system_prompt"?a("conversation.systemPromptExpand"):t==="skill_context"?a("conversation.skillContextExpand"):a("conversation.rulesMessageExpand");return s.jsx("article",{className:`message-item ${n} rules-message-row`,"data-message-id":e.id,children:s.jsxs("div",{className:"message-content-wrapper",children:[s.jsxs("div",{className:"rules-message-card",children:[l?s.jsx("div",{className:"rules-message-toggle","aria-expanded":g,children:s.jsxs("div",{className:"rules-message-heading",children:[s.jsx("span",{className:"rules-message-badge",children:p}),s.jsx("span",{className:"rules-message-summary",children:h})]})}):s.jsxs("button",{type:"button",className:"rules-message-toggle","aria-expanded":g,onClick:()=>f(x=>!x),children:[s.jsxs("div",{className:"rules-message-heading",children:[s.jsx("span",{className:"rules-message-badge",children:p}),s.jsx("span",{className:"rules-message-summary",children:h})]}),s.jsx("span",{className:"rules-message-action",children:y})]}),s.jsx("p",{className:"rules-message-hint",children:b}),g&&s.jsx("div",{className:"rules-message-body",children:s.jsx(zo,{content:e.content,className:"message-text message-content markdown-content",exportMode:c})}),m?s.jsx(FS,{timestamp:e.timestamp,children:s.jsx(oa,{text:e.content,canCopy:r.canCopy,canFork:r.canFork&&!!(o&&e.deliveryState==="sent"),compact:!0,onFork:o?()=>o(e):null})}):s.jsx(oa,{text:e.content,canCopy:r.canCopy,canFork:r.canFork&&!!(o&&e.deliveryState==="sent"),onFork:o?()=>o(e):null})]}),e.deliveryState==="failed"&&e.clientRequestId&&s.jsx("button",{className:"retry-button",type:"button",onClick:()=>i(e.clientRequestId),children:a("conversation.resendButton")})]})})}function _S({message:e,provider:t,interruptedSource:n=null,foldedPromptKind:r=null,actionState:i,onRetry:o,onForkMessage:l,assistantAvatar:c,exportMode:u=!1,onSubmitStructuredQuestion:f}){const h=e.role==="user",m=e.kind==="thinking",g=e.role==="assistant"&&e.kind==="text",p=t==="codex"&&e.kind==="text"?SS(e.content):null,b=r??(SF(t,e.content)?"rules":CF(t,e.content)?"skill_context":null),y=d.useMemo(()=>ml(e.content),[e.content]),x=y.text,k=y.inlineImages,C=y.structuredQuestions,[j,H]=d.useState(!1),[_,T]=d.useState(!1),[P,z]=d.useState(null),[L,R]=d.useState(null);if(b){const K=e.role==="user"?"user-message":e.role==="assistant"?"assistant-message":"system-message";return s.jsx(zF,{message:e,kind:b,tone:K,actionState:i,onRetry:o,onForkMessage:l,forceExpanded:u,exportMode:u})}if(p){const K=_2(n),E=p.detail?`${K}
48
+
49
+ ${p.detail}`:K;return s.jsxs("article",{className:"message-item assistant-message","data-message-id":e.id,children:[s.jsx("div",{className:"message-avatar",children:c??s.jsx(lf,{})}),s.jsxs("div",{className:"message-content-wrapper",children:[s.jsx(zo,{content:E,className:"message-text message-content markdown-content",exportMode:u}),s.jsx(oa,{text:E,canCopy:i.canCopy,canFork:!1,onFork:null})]})]})}if(h){const K=e.origin==="butler_proxy"||UF(e.clientRequestId),E=e.origin==="butler_proxy"&&typeof e.originRef=="string"&&e.originRef.trim().length>0;async function D(){if(!E)return;const V=!j;if(H(V),!(!V||L||_)){T(!0),z(null);try{const ee=await AO(e.originRef);R(ee.task)}catch(ee){z(ee instanceof Error?ee.message:a("conversation.butlerOriginDetailLoadFailed"))}finally{T(!1)}}}const te=K?E?s.jsxs("div",{className:"message-origin-detail-anchor",children:[s.jsx("button",{type:"button",className:"message-origin-badge message-origin-badge-button","aria-expanded":j,onClick:()=>{D()},children:a("conversation.butlerProxyMessageBadge")}),j?s.jsxs("div",{className:"message-origin-detail-popover",role:"dialog","aria-live":"polite",children:[s.jsx("strong",{children:a("conversation.butlerOriginDetailTitle")}),_?s.jsx("p",{children:a("conversation.butlerOriginDetailLoading")}):P?s.jsx("p",{children:P}):L?s.jsxs(s.Fragment,{children:[s.jsxs("p",{children:[a("conversation.butlerOriginDetailObjectiveLabel"),":",L.objective]}),s.jsxs("p",{children:[a("conversation.butlerOriginDetailStatusLabel"),":",qF(L.status)]}),s.jsxs("p",{children:[a("conversation.butlerOriginDetailSummaryLabel"),":",L.lastAutomationSummary||a("conversation.butlerAnalysisEmpty")]}),L.waitingReason?s.jsxs("p",{children:[a("conversation.butlerOriginDetailWaitingReasonLabel"),":",L.waitingReason]}):null]}):s.jsx("p",{children:a("conversation.butlerAnalysisEmpty")})]}):null]}):s.jsx("span",{className:"message-origin-badge",children:a("conversation.butlerProxyMessageBadge")}):null;return s.jsx("article",{className:"message-item user-message","data-message-id":e.id,children:s.jsxs("div",{className:"message-content-wrapper",children:[s.jsx(pc,{sessionId:e.sessionId,attachments:e.attachments,attachmentPayloads:e.attachmentPayloads,inlineImages:k}),x?s.jsx(zo,{content:x,className:"message-text message-content markdown-content",exportMode:u}):null,e.deliveryState==="failed"&&e.clientRequestId&&s.jsx("button",{className:"retry-button",type:"button",onClick:()=>o(e.clientRequestId),children:a("conversation.resendButton")}),s.jsx(FS,{timestamp:e.timestamp,leading:te,children:s.jsx(oa,{text:x,canCopy:i.canCopy,canFork:i.canFork&&!!(l&&e.deliveryState==="sent"),compact:!0,onFork:l?()=>l(e):null})})]})})}return m?s.jsxs("article",{className:"message-item assistant-message thinking-message-row","data-message-id":e.id,children:[s.jsx("div",{className:"message-avatar",children:c??s.jsx(lf,{})}),s.jsxs("div",{className:"thinking-message-content",children:[s.jsx("div",{className:"thinking-message-label",children:a("conversation.thinkingLabel")}),s.jsx(pc,{sessionId:e.sessionId,attachments:e.attachments,attachmentPayloads:e.attachmentPayloads,inlineImages:k}),x&&s.jsx(zo,{content:x,className:"message-text message-content markdown-content thinking-message-text",exportMode:u}),s.jsx(oa,{text:x,canCopy:i.canCopy,canFork:i.canFork&&!!(l&&e.deliveryState==="sent"),onFork:l?()=>l(e):null})]})]}):g?s.jsxs("article",{className:"message-item assistant-message","data-message-id":e.id,children:[s.jsx("div",{className:"message-avatar",children:c??s.jsx(lf,{})}),s.jsxs("div",{className:"message-content-wrapper",children:[s.jsx(pc,{sessionId:e.sessionId,attachments:e.attachments,attachmentPayloads:e.attachmentPayloads,inlineImages:k}),x&&s.jsx(zo,{content:x,className:"message-text message-content markdown-content",exportMode:u}),C&&f?s.jsx(HF,{messageId:e.id,prompt:C,onSubmit:f}):null,s.jsx(oa,{text:x,canCopy:i.canCopy,canFork:i.canFork&&!!(l&&e.deliveryState==="sent"),onFork:l?()=>l(e):null})]})]}):s.jsx("article",{className:"message-item system-message","data-message-id":e.id,children:s.jsxs("div",{className:"message-content-wrapper",children:[s.jsx(pc,{sessionId:e.sessionId,attachments:e.attachments,attachmentPayloads:e.attachmentPayloads,inlineImages:k}),x?s.jsx("div",{className:"message-text message-content",children:s.jsx(DS,{language:"text",content:x,exportMode:u})}):null,s.jsx(oa,{text:x,canCopy:i.canCopy,canFork:i.canFork&&!!(l&&e.deliveryState==="sent"),onFork:l?()=>l(e):null})]})})}function HF({messageId:e,prompt:t,onSubmit:n}){const[r,i]=d.useState({}),[o,l]=d.useState(!1),c=t.questions.some(u=>{var f;return(((f=r[u.id])==null?void 0:f.filter(Boolean).length)??0)===0});return s.jsxs("section",{className:"permission-request-card permission-request-card-inline",children:[s.jsxs("header",{className:"permission-request-card-header",children:[s.jsx("div",{className:"permission-request-provider",children:s.jsxs("div",{className:"permission-request-provider-copy",children:[s.jsx("strong",{children:a("conversation.permissionRequestQuestionsLabel")}),s.jsx("span",{children:a("conversation.permissionRequestSectionDescription")})]})}),s.jsx("span",{className:"permission-request-kind",children:a("conversation.permissionRequestKindUserInput")})]}),s.jsx("div",{className:"permission-request-card-body",children:s.jsxs("div",{className:"permission-request-block",children:[s.jsx("div",{className:"permission-request-block-label",children:a("conversation.permissionRequestQuestionsLabel")}),s.jsx("div",{className:"permission-request-question-list",children:t.questions.map(u=>s.jsxs("div",{className:"permission-request-question",children:[s.jsx("div",{className:"permission-request-question-header",children:u.header}),s.jsx("p",{children:u.question}),s.jsx("div",{className:"permission-request-question-options",children:u.options.map(f=>{var m;const h=((m=r[u.id])==null?void 0:m.includes(f.label))??!1;return s.jsxs("label",{className:"permission-request-question-option",children:[s.jsx("input",{type:"radio",name:`${e}:${u.id}`,checked:h,onChange:()=>{i(g=>({...g,[u.id]:[f.label]}))}}),s.jsxs("span",{children:[s.jsx("strong",{children:f.label}),f.description?s.jsx("small",{children:f.description}):null]})]},`${u.id}:${f.label}`)})})]},`${e}:${u.id}`))})]})}),s.jsx("footer",{className:"permission-request-card-footer",children:s.jsx("button",{type:"button",className:"primary-button permission-request-action",disabled:o||c,onClick:async()=>{l(!0);try{await n({messageId:e,answers:r})}finally{l(!1)}},children:o?a("conversation.permissionRequestSubmitting"):a("common.confirm")})})]})}function BS(e){return s.jsx("div",{className:"timeline-status timeline-status-inline thinking-status-inline","data-runtime-thinking-placeholder":"true",children:s.jsxs("span",{className:"status-text thinking-status-text","aria-label":e.label,children:[s.jsx("span",{children:O2(e.label)||e.label}),s.jsx("span",{className:"thinking-status-dots","aria-hidden":"true",children:"..."})]})},e.key)}function WS(e){return s.jsxs("article",{className:"message-item assistant-message session-runtime-error-row",children:[s.jsx("div",{className:"session-runtime-error-row__spacer","aria-hidden":"true"}),s.jsxs("section",{className:"message-content-wrapper session-runtime-error-panel",role:"status","aria-label":e.error.title,children:[s.jsxs("div",{className:"session-runtime-error-panel__header",children:[s.jsxs("div",{className:"session-runtime-error-panel__title-group",children:[s.jsx("span",{className:"session-runtime-error-panel__dot","aria-hidden":"true"}),s.jsx("strong",{children:e.error.title})]}),e.error.code?s.jsx("code",{className:"session-runtime-error-panel__code",children:e.error.code}):null]}),e.error.summary?s.jsx("p",{className:"session-runtime-error-panel__summary",children:F2(e.error.summary).map((t,n)=>t.type==="text"?s.jsx("span",{children:t.text},`${e.key}:text:${n}`):s.jsx("mark",{className:`session-runtime-error-panel__summary-token session-runtime-error-panel__summary-token--${t.type}`,children:t.text},`${e.key}:${t.type}:${n}`))}):null]})]},e.key)}function $S({sessionId:e,sessionSummary:t=null,workspaceId:n=null,workspacePath:r=null,items:i,provider:o,interruptedSource:l=null,assistantAvatar:c}){const u=d.useMemo(()=>ES({sessionSummary:t,items:i,provider:o}),[i,o,t]),f=u.renderItems,h=u.leadingSystemPromptMessageIds;return s.jsx("section",{className:"message-timeline message-timeline-export","aria-label":a("conversation.exportPrintContainerTitle"),children:s.jsxs("div",{className:"message-list message-list-export","data-export-mode":"true",children:[f.length===0?s.jsx("div",{className:"timeline-empty",children:s.jsx("p",{className:"status-text",children:a("conversation.timelineEmpty")})}):null,f.map(m=>m.type==="tool_group"?s.jsx("article",{className:"message-item tool-message-row",children:s.jsx(OS,{group:m.group,sessionId:e,workspaceId:n,workspacePath:r,exportMode:!0})},m.key):m.type==="runtime_thinking"?BS(m):m.type==="session_error"?WS(m):s.jsx(_S,{message:m.message,provider:o,foldedPromptKind:h.has(m.message.id)?"system_prompt":null,actionState:{canCopy:!1,canFork:!1},onRetry:()=>{},onForkMessage:null,interruptedSource:l,assistantAvatar:c,exportMode:!0},m.key))]})})}function lf(){return s.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 16v-4M12 8h.01"})]})}function UF(e){return typeof e=="string"&&e.startsWith("butler-follow-up:")}function qF(e){switch(e){case"waiting_user":return a("shell.butlerAutomationStatusWaitingUser");case"completed":return a("shell.butlerAutomationStatusCompleted");case"failed":return a("shell.butlerAutomationStatusFailed");case"cancelled":return a("shell.butlerAutomationStatusCancelled");case"active":default:return a("shell.butlerAutomationStatusActive")}}function td({sessionId:e="session",sessionSummary:t=null,workspaceId:n=null,workspacePath:r=null,items:i,historyState:o,loadingOlderMessages:l=!1,hasOlderMessages:c=!1,onLoadOlderMessages:u=()=>{},onRetryMessage:f,onForkMessage:h,provider:m,interruptedSource:g=null,assistantAvatar:p,followTailUpdates:b=!1,onSubmitStructuredQuestion:y}){var Ct;const{showToast:x}=Vn(),k=Hn(),C=!b,j=d.useRef(null);np(j);const H=d.useRef(e),_=d.useRef(0),T=d.useRef(null),P=d.useRef(!0),z=d.useRef(null),L=d.useRef(null),R=d.useRef(!1),K=d.useRef(b?null:mc(e)),E=d.useRef(b?null:((Ct=mc(e))==null?void 0:Ct.lastMessageSignature)??null),D=d.useRef(b?null:mc(e)),te=d.useRef(null),V=d.useRef(null),ee=d.useRef(null),U=d.useRef(0),he=d.useRef(!1),X=d.useRef(null),I=d.useRef(null),xe=d.useRef(null),[le,M]=d.useState(!1),[de,Ne]=d.useState(!1),ye=d.useRef(!1),Be=d.useRef(null),We=k.isMobile?0:H2,Ce=d.useMemo(()=>L2(i),[i]),ke=d.useMemo(()=>D2(i),[i]),we=d.useMemo(()=>ES({sessionSummary:t,items:i,provider:m}),[i,m,t]),se=we.visibleMessages,ce=we.renderItems,Y=we.leadingSystemPromptMessageIds,Te=we.actionStateByMessageId,pe=o==="loading"&&Ce.length===0;function fe(J){var Ue,ze,st;if(!J)return null;try{const q=JSON.parse(J);return{type:typeof q.type=="string"?q.type:"message",key:typeof q.key=="string"?q.key:null,id:typeof q.id=="string"?q.id:null,timestamp:typeof q.timestamp=="string"?q.timestamp:null,deliveryState:typeof q.deliveryState=="string"?q.deliveryState:null,contentLength:typeof q.content=="string"?q.content.length:0,labelLength:typeof q.label=="string"?q.label.length:0,summaryLength:typeof q.summary=="string"?q.summary.length:0,messageIdCount:Array.isArray(q.messageIds)?q.messageIds.length:0,attachmentCount:Array.isArray(q.attachments)?q.attachments.length:0,toolStatus:typeof((Ue=q.toolCall)==null?void 0:Ue.status)=="string"?q.toolCall.status:null,hasToolOutput:typeof((ze=q.toolCall)==null?void 0:ze.output)=="string"?q.toolCall.output.length>0:!1,hasToolError:typeof((st=q.toolCall)==null?void 0:st.error)=="string"?q.toolCall.error.length>0:!1}}catch{return{parseError:!0,length:J.length}}}function W(J){var Ue;return{id:J.id,rawRef:J.rawRef,role:J.role,kind:J.kind,deliveryState:J.deliveryState,timestamp:J.timestamp,sequence:J.sequence,attachmentCount:((Ue=J.attachments)==null?void 0:Ue.length)??0,contentPreview:ml(J.content).text.replace(/\r\n/g,`
50
+ `).trimEnd().slice(0,120)}}function Me(J){return J.type==="message"?{type:J.type,key:J.key,message:W(J.message)}:J.type==="runtime_thinking"?{type:J.type,key:J.key,labelPreview:J.label.slice(0,80)}:J.type==="session_error"?{type:J.type,key:J.key,code:J.error.code,summary:J.error.summary}:{type:J.type,key:J.key,callId:J.group.tool.callId,name:J.group.tool.name,hasRequest:J.group.hasRequest,hasResult:J.group.hasResult,updatedAt:J.group.updatedAt}}function je(J,Ue){const ze=J.getBoundingClientRect(),st=Ue.getBoundingClientRect(),q=Math.max(st.top,ze.top),re=Math.min(st.bottom,ze.bottom),ue=Math.max(0,re-q);return{top:Math.round(st.top),bottom:Math.round(st.bottom),height:Math.round(st.height),relativeTop:Math.round(st.top-ze.top),relativeBottom:Math.round(st.bottom-ze.top),bottomGap:Math.round(ze.bottom-st.bottom),visibleHeight:Math.round(ue),fullyVisible:st.top>=ze.top&&st.bottom<=ze.bottom}}function Q(J,Ue){var q;const ze=Ue.dataset.messageId??null,st=ze?se.find(re=>re.id===ze)??null:null;return{messageId:ze,role:(st==null?void 0:st.role)??null,kind:(st==null?void 0:st.kind)??null,className:Ue.className,textLength:((q=Ue.textContent)==null?void 0:q.length)??0,rect:je(J,Ue)}}function ge(J){var q;if(!J)return null;const Ue=J.getBoundingClientRect(),ze=Array.from(J.children).filter(re=>re instanceof HTMLElement&&re.classList.contains("message-item")),st=J.querySelector("[data-runtime-thinking-placeholder='true']");return{listRect:{top:Math.round(Ue.top),bottom:Math.round(Ue.bottom),height:Math.round(Ue.height)},messageElementCount:ze.length,tailDomItems:ze.slice(-5).map(re=>Q(J,re)),runtimeThinkingPlaceholderDom:st?{textLength:((q=st.textContent)==null?void 0:q.length)??0,rect:je(J,st)}:null}}function Oe(J,Ue={}){const ze=se[0]??null,st=se.at(-1)??null,q=ce.at(-1)??null,re=K.current,ue=D.current,Re=J?J.scrollHeight-J.clientHeight-J.scrollTop:null;return{sessionId:e,historyState:o,followTailUpdates:b,messagesLength:se.length,rawMessagesLength:Ce.length,renderItemsLength:ce.length,firstMessageId:(ze==null?void 0:ze.id)??null,firstMessageRole:(ze==null?void 0:ze.role)??null,lastMessageId:(st==null?void 0:st.id)??null,lastMessageRole:(st==null?void 0:st.role)??null,lastMessageKind:(st==null?void 0:st.kind)??null,lastMessageTimestamp:(st==null?void 0:st.timestamp)??null,runtimeThinkingPlaceholderVisible:!!ke,runtimeThinkingPlaceholderLength:(ke==null?void 0:ke.length)??0,runtimeThinkingPlaceholderPreview:(ke==null?void 0:ke.slice(0,80))??null,tailItemType:(q==null?void 0:q.type)??null,tailItemKey:(q==null?void 0:q.key)??null,tailToolCallId:q&&q.type==="tool_group"?q.group.tool.callId:null,scrollTop:(J==null?void 0:J.scrollTop)??null,scrollHeight:(J==null?void 0:J.scrollHeight)??null,clientHeight:(J==null?void 0:J.clientHeight)??null,distanceToBottom:Re,stickToBottomRef:P.current,hasNewMessagesBelow:ye.current,previousMessageCount:_.current,previousLastMessage:fe(T.current),hiddenMessageIds:we.hiddenMessageIds,validationIssues:we.validationIssues,tailMessages:se.slice(-5).map(W),tailRenderItems:ce.slice(-5).map(Me),dom:ge(J),pendingRestoreState:re===null?null:{scrollTop:re.scrollTop,stickToBottom:re.stickToBottom,lastMessage:fe(re.lastMessageSignature)},currentScrollState:ue===null?null:{scrollTop:ue.scrollTop,stickToBottom:ue.stickToBottom,lastMessage:fe(ue.lastMessageSignature)},restoredTailMessage:fe(E.current),...Ue}}function $e(J,Ue,ze={}){ih()&&H0(J,Oe(Ue,ze))}function Ve(J){const ze=J.scrollHeight-J.clientHeight-J.scrollTop<=Yb;return{scrollTop:J.scrollTop,stickToBottom:ze,lastMessageSignature:ye.current&&!ze?E.current:ia(ce.at(-1)??null)}}function G(J){return D.current=Ve(J),D.current}function ve(J){const Ue=J.scrollHeight-J.clientHeight-J.scrollTop,ze=Ue<=Yb;P.current=ze,ze&&ye.current&&(bt(),ye.current=!1,E.current=ia(ce.at(-1)??null),Ne(!1)),M(ce.length>0&&(Ue>Jb||ye.current)),G(J),$e("affordance.sync",J,{distanceToBottom:Ue,nextStickToBottom:ze})}function _e(J=j.current){C&&(J&&G(J),D.current&&Gb(e,D.current))}function nt(J){C&&D.current&&Gb(J,D.current)}function et(){te.current!==null&&(window.clearTimeout(te.current),te.current=null)}function ot(){C&&(et(),te.current=window.setTimeout(()=>{te.current=null,_e()},W2))}function jt(J,Ue,ze={}){$e("jump_to_bottom.before",J,{reason:Ue,...ze}),J.scrollTop=J.scrollHeight,$e("jump_to_bottom.after",J,{reason:Ue,...ze})}function Ft(){V.current!==null&&(window.clearTimeout(V.current),V.current=null)}function bt(){Ft(),he.current=!1,ee.current=null,U.current=0,X.current=null}function _t(J,Ue){const ze=Math.max(0,J.scrollHeight-J.clientHeight),st=Math.max(0,Math.min(Ue,ze));X.current=st,J.scrollTop=st,P.current=!1,$e("manual_restore.apply",J,{targetScrollTop:Ue,maxScrollableTop:ze,nextScrollTop:st}),M(ce.length>0&&(ze-st>Jb||ye.current))}function xt(){Ft(),he.current&&(V.current=window.setTimeout(()=>{V.current=null;const J=j.current,Ue=ee.current;if(!J||Ue===null){bt();return}if(_t(J,Ue),Date.now()<U.current){xt();return}bt(),ve(J)},z2))}function rt(J,Ue){if(We<=0){_t(Ue,J),bt();return}he.current=!0,ee.current=J,U.current=Date.now()+We,_t(Ue,J),xt()}function It(){he.current&&($e("manual_restore.interrupt",j.current),bt())}function $t(J){return R.current||!c||l||o!=="ready"||J.scrollTop>B2?!1:(R.current=!0,z.current=J.scrollHeight-J.scrollTop,L.current=ia(ce[0]??null),$e("older_history.prefetch",J,{pendingOlderLoadOffset:z.current,pendingOlderLoadHeadMessage:fe(L.current)}),u(),!0)}d.useEffect(()=>{o==="error"&&x({title:a("conversation.historyLoadFailed"),tone:"error"})},[o,x]),d.useLayoutEffect(()=>{var J,Ue;if(H.current!==e){const ze=H.current;nt(ze),H.current=e,_.current=0,T.current=null,K.current=b?null:mc(e),E.current=((J=K.current)==null?void 0:J.lastMessageSignature)??null,D.current=K.current,P.current=b?!0:((Ue=K.current)==null?void 0:Ue.stickToBottom)??!0,z.current=null,L.current=null,bt(),ye.current=!1,Ne(!1),M(!1),$e("session.switch",j.current,{previousSessionId:ze,nextSessionId:e})}},[b,C,e]),d.useLayoutEffect(()=>()=>{et(),bt(),nt(H.current)},[C,e]),d.useLayoutEffect(()=>{const J=j.current,Ue=ia(ce.at(-1)??null);if(!J){_.current=ce.length,T.current=Ue;return}const ze=_.current,st=T.current,q=K.current,re=ze===0||ce.length!==ze||Ue!==st;if($e("messages.effect.start",J,{previousCount:ze,previousLastMessage:fe(st),currentLastMessage:fe(Ue),hasTailUpdate:re}),q&&o==="ready"){const He=!q.stickToBottom&&q.lastMessageSignature!==null&&Ue!==null&&q.lastMessageSignature!==Ue;q.stickToBottom?(bt(),jt(J,"restore_ready_stick_to_bottom",{hasTailUpdates:He})):(rt(q.scrollTop,J),$e("restore_ready.manual",J,{hasTailUpdates:He,targetScrollTop:q.scrollTop})),ye.current=He,E.current=q.lastMessageSignature,Ne(He),K.current=null,ve(J),_.current=ce.length,T.current=Ue,G(J);return}if(q&&o==="error"){q.stickToBottom?(bt(),jt(J,"restore_error_stick_to_bottom")):(rt(q.scrollTop,J),$e("restore_error.manual",J,{targetScrollTop:q.scrollTop})),K.current=null,ve(J),_.current=ce.length,T.current=Ue,G(J);return}if(he.current){_t(J,ee.current??J.scrollTop),_.current=ce.length,T.current=Ue,G(J);return}const ue=ia(ce[0]??null),Re=z.current,Se=L.current,Ke=Re!==null&&!l&&Se!==null&&Se!==ue&&ce.length>=ze,De=re&&(b||P.current);$e("messages.effect.decision",J,{currentHeadMessage:fe(ue),pendingOlderLoadOffset:Re,pendingOlderLoadHeadMessage:fe(Se),shouldRestoreOlderLoadOffset:Ke,shouldFollowTailUpdate:De,loadingOlderMessages:l}),Ke?(J.scrollTop=Math.max(0,J.scrollHeight-Re),z.current=null,L.current=null):z.current!==null&&!l?(z.current=null,L.current=null,De&&jt(J,"older_load_offset_cleared_follow_tail",{pendingOlderLoadOffset:Re})):De&&jt(J,"tail_update_follow"),ve(J),_.current=ce.length,T.current=Ue},[o,l,ce,e]),d.useEffect(()=>{if(!c){R.current=!1;return}!l&&z.current===null&&(R.current=!1)},[c,l,se.length]),d.useLayoutEffect(()=>{const J=xe.current;J!==ke&&($e("runtime_thinking.placeholder_change",j.current,{previousVisible:!!J,nextVisible:!!ke,previousLength:(J==null?void 0:J.length)??0,nextLength:(ke==null?void 0:ke.length)??0,note:"Codex 思考中占位符已经并入统一 timeline source item 列表;调试时直接看 renderItems 尾部即可。"}),xe.current=ke)},[ke,e]),d.useEffect(()=>{const J=j.current;if(!ih()||!J||typeof ResizeObserver>"u")return;const Ue=new ResizeObserver(()=>{$e("list.resize",J)});return Ue.observe(J),()=>{Ue.disconnect()}},[e,se.length]),d.useEffect(()=>{const J=TF(ce),Ue=IF(Be.current,J,se);(we.hiddenMessageIds.length>0||we.validationIssues.length>0||Ue.length>0)&&z0("timeline.render",{sessionId:e,hiddenMessageIds:we.hiddenMessageIds,validationIssues:we.validationIssues,assistantRenderMoves:Ue,rawTailMessages:Ce.slice(-6).map(W),visibleTailMessages:se.slice(-6).map(W),renderTailItems:ce.slice(-6).map(Me)}),Be.current=J},[Ce,ce,e,we.hiddenMessageIds,we.validationIssues,se]);function pt(){const J=j.current;if(J){if(he.current){const Ue=X.current;Ue!==null&&Math.abs(J.scrollTop-Ue)<=1?X.current=null:It()}ve(J),ot(),$e("scroll",J),$t(J)}}function Ie(J){if(J.deltaY!==0&&It(),J.deltaY>=0)return;const Ue=j.current;Ue&&$t(Ue)}function kt(J){var Ue;It(),I.current=((Ue=J.touches[0])==null?void 0:Ue.clientY)??null}function St(J){var q;const Ue=I.current,ze=((q=J.touches[0])==null?void 0:q.clientY)??null;if(Ue===null||ze===null||ze-Ue<$2)return;It();const st=j.current;st&&$t(st)}function vt(){I.current=null}return s.jsxs("section",{className:"message-timeline",children:[o==="loading"&&s.jsx("div",{className:"timeline-status",children:s.jsx("span",{className:"status-text",children:a("conversation.historyLoading")})}),s.jsxs("div",{ref:j,className:"message-list","data-scrollbar-autohide":"true",onScroll:pt,onPointerDown:It,onWheel:Ie,onTouchStart:kt,onTouchMove:St,onTouchEnd:vt,onTouchCancel:vt,children:[pe?s.jsx(DF,{}):null,l?s.jsx("div",{className:"timeline-status timeline-status-inline",children:s.jsx("span",{className:"status-text",children:a("conversation.historyLoadingOlder")})}):null,ce.length===0&&o==="ready"&&s.jsx("div",{className:"timeline-empty",children:s.jsx("p",{className:"status-text",children:a("conversation.timelineEmpty")})}),ce.map(J=>J.type==="tool_group"?s.jsx("article",{className:"message-item tool-message-row",children:s.jsx(OS,{group:J.group,sessionId:e,workspaceId:n,workspacePath:r})},J.key):J.type==="runtime_thinking"?BS(J):J.type==="session_error"?WS(J):s.jsx(_S,{message:J.message,provider:m,foldedPromptKind:Y.has(J.message.id)?"system_prompt":null,actionState:Te.get(J.message.id)??{canCopy:J.message.role==="user",canFork:!1},onRetry:f,onForkMessage:h,interruptedSource:g,assistantAvatar:p,onSubmitStructuredQuestion:y},J.key))]}),le?s.jsxs("button",{type:"button",className:"conversation-scroll-to-bottom-button","data-has-new":de?"true":"false","aria-label":a("conversation.scrollToBottomAction"),title:a("conversation.scrollToBottomAction"),onClick:()=>{const J=j.current;J&&(bt(),jt(J,"scroll_button_click"),ye.current=!1,E.current=ia(ce.at(-1)??null),Ne(!1),ve(J),_e(J))},children:[de?s.jsx("span",{className:"conversation-scroll-to-bottom-button-badge",children:"NEW"}):null,s.jsx("svg",{className:"conversation-scroll-to-bottom-button-icon",viewBox:"0 0 20 20","aria-hidden":"true",focusable:"false",children:s.jsx("path",{d:"M10 4.25a.75.75 0 0 1 .75.75v7.19l2.72-2.72a.75.75 0 1 1 1.06 1.06l-4 4a.75.75 0 0 1-1.06 0l-4-4a.75.75 0 1 1 1.06-1.06l2.72 2.72V5a.75.75 0 0 1 .75-.75Zm-4 11a.75.75 0 0 1 0-1.5h8a.75.75 0 0 1 0 1.5H6Z",fill:"currentColor"})})]}):null]})}function ia(e){return e?"type"in e?e.type==="message"?ia(e.message):e.type==="tool_group"?JSON.stringify({type:e.type,key:e.key,messageIds:e.group.messageIds,timestamp:e.group.updatedAt,toolCall:{status:e.group.tool.status,output:e.group.tool.output,error:e.group.tool.error}}):e.type==="runtime_thinking"?JSON.stringify({type:e.type,key:e.key,label:e.label}):JSON.stringify({type:e.type,key:e.key,summary:e.error.summary,code:e.error.code}):JSON.stringify({type:"message",id:e.id,content:e.content,attachments:e.attachments,timestamp:e.timestamp,deliveryState:e.deliveryState,toolCall:e.toolCall?{status:e.toolCall.status,output:e.toolCall.output,error:e.toolCall.error}:null}):null}function VF(e){const t=new Map;let n=0;function r(i){let o=null;for(let l=i-1;l>=n;l-=1){const c=e[l];if(!(!c||!KF(c))){o=c.id;break}}for(let l=n;l<i;l+=1){const c=e[l];if(c){if(c.role==="user"){t.set(c.id,{canCopy:!0,canFork:!1});continue}t.set(c.id,{canCopy:c.id===o,canFork:c.id===o})}}}for(let i=0;i<e.length;i+=1){const o=e[i];o&&o.role==="user"&&i>n&&(r(i),n=i)}return r(e.length),t}function KF(e){return e.role==="user"?!1:e.kind!=="tool_call"&&e.kind!=="tool_result"}function GF(e){return op(e)!==null}function YF(e){return e.isSubagent===!0&&!GF(e)}function op(e){return e.forkMethod==="reconstructed_message_fork"||e.forkMethod==="reconstructed_session_fork"?"reconstructed":e.forkMethod==="native_message_fork"||e.forkSourceType==="message"?"message":e.forkMethod==="native_session_fork"||e.forkSourceType==="session"?"session":null}function JF(e){const t=op(e);return t==="reconstructed"?a("shell.sessionForkReconstructed"):t==="message"?a("shell.sessionForkMessage"):t==="session"?a("shell.sessionForkSession"):null}function XF(e){return e.sessionKind==="annotation"?"annotation":null}function pK(e){return XF(e)==="annotation"?a("conversation.actionSessionBadge"):null}const iy=120*1e3,QF=8,ZF=/\[\[CODINGNS_IMAGE_ATTACHMENTS\]\][\s\S]*?\[\[\/CODINGNS_IMAGE_ATTACHMENTS\]\]/g,e_=/\[\[CODINGNS_IMAGE_ATTACHMENTS\]\][\s\S]*?\[\[\/CODINGNS_IMAGE_ATTACHMENTS\]\]/;function gK(e){return{session:(e==null?void 0:e.session)??null,capabilities:(e==null?void 0:e.capabilities)??null,runtimeHasActiveRun:(e==null?void 0:e.runtimeHasActiveRun)??null,runtimeCanInterrupt:(e==null?void 0:e.runtimeCanInterrupt)??null,contextUsage:(e==null?void 0:e.contextUsage)??null,messages:(e==null?void 0:e.messages)??[],timelineItems:(e==null?void 0:e.timelineItems)??[],permissionRequests:(e==null?void 0:e.permissionRequests)??[],queuedMessages:(e==null?void 0:e.queuedMessages)??[],historyState:"idle",loadingOlderMessages:!1,olderCursor:(e==null?void 0:e.olderCursor)??null,hasOlderMessages:(e==null?void 0:e.hasOlderMessages)??!1,connectionState:"closed",lastCursor:(e==null?void 0:e.lastCursor)??null,pagesLoaded:(e==null?void 0:e.pagesLoaded)??0,interruptSource:(e==null?void 0:e.interruptSource)??null,errorCode:null,errorDetail:null}}function nd(e,t,n="sent",r=null){const i=t.kind??(t.role==="tool"?"tool_result":"text"),o=t.toolCall??(i==="tool_call"||i==="tool_result"?{callId:t.rawRef||t.messageId,name:"tool",input:i==="tool_call"?t.content:"",output:i==="tool_result"&&t.content?t.content:null,error:null,status:i==="tool_call"?"running":"completed"}:null);return{id:t.messageId,sessionId:e,role:t.role,kind:i,content:T_(t.provider,t.role,i,t.content),toolCall:o,attachments:t.attachments??[],attachmentPayloads:null,origin:t.origin??null,originRef:t.originRef??null,timestamp:t.timestamp,sequence:t.sequence,rawRef:t.rawRef,deliveryState:n,clientRequestId:r}}function zS(e,t,n,r=[],i=[],o=Number.MAX_SAFE_INTEGER){return{id:`pending-${n}`,sessionId:e,role:"user",kind:"text",content:t,toolCall:null,attachments:r,attachmentPayloads:i,origin:null,originRef:null,timestamp:new Date().toISOString(),sequence:o,rawRef:`pending://${n}`,deliveryState:"sending",clientRequestId:n}}function bK(e,t){return US([...e,t])}function yK(e,t,n){const r=new Map,i=new Set,o=[];for(const l of e)r.set(l.id,l),i.add(l.id);for(const l of n){const c=nd(t,l);o.push(c);const u=M_(r,c,t);if(u&&u!==c.id)continue;const f=P_(r,c,t),h=f&&f!==c.id?r.get(f)??null:null;f&&f!==c.id&&r.delete(f);const m=E_(r,i,c);if(m&&m!==c.id){const y=r.get(m)??null;if(y){const x=Ph(y,c);Hi("session.messages.codex_equivalent_replace",{sessionId:t,previous:Ls(y),incoming:Ls(c),merged:Ls(x)}),r.delete(m),r.set(l.messageId,x);continue}}const g=D_(r,c);if(g&&g!==c.id){const y=r.get(g)??null;if(y){const x=g_(y,c);Hi("session.messages.opencode_equivalent_replace",{sessionId:t,previous:Ls(y),incoming:Ls(c),merged:Ls(x)}),r.set(g,x);continue}}const p=r.get(l.messageId)??null,b=h===null?c:p_(c,h);r.set(l.messageId,p?Ph(p,b):b)}return US(O_(Array.from(r.values()),o))}function xK(e,t){const n=new Map;for(const r of e)n.set(cy(r),r);for(const r of t){const i=cy(r),o=n.get(i)??null;if(o){Hi("session.messages.runtime_overlay_merge",{overlayKey:i,mode:"update",previous:Ls(o),incoming:Ls(r)}),n.set(i,b_(o,r));continue}Hi("session.messages.runtime_overlay_merge",{overlayKey:i,mode:"insert",incoming:Ls(r)}),n.set(i,r)}return qS(Array.from(n.values()))}function HS(e,t){return e.map(n=>n.clientRequestId===t?{...n,deliveryState:"failed"}:n)}function t_(e){const t=[];let n=null,r=!1;for(const i of e)if(!x_(n,i,r)){if(t.push(i),xl(i)){n=i,r=!1;continue}n&&k_(i)&&(r=!0)}return t}function n_(e){const t=[];for(const n of e){const r=t.at(-1);if(!r||!YS(r,n)){t.push(n);continue}t[t.length-1]=JS(r,n)}return t}function s_(e){const t=[];for(const n of e){if(t.push(n),t.length<4)continue;const r=t[t.length-4],i=t[t.length-3],o=t[t.length-2],l=t[t.length-1];w_(r,i,o,l)&&t.splice(t.length-3,3,JS(i,l))}return t}function r_(e){const t=[];for(const n of e){const r=t.at(-1);if(!r||!v_(r,n)){t.push(n);continue}t[t.length-1]=C_(r,n)}return t}function i_(e){const t=[];for(const n of e){const r=t.findIndex(i=>S_(i,n));if(r===-1){t.push(n);continue}t[r]=j_(t[r],n)}return t}function US(e){const t=qS(e);return i_(r_(t_(s_(n_(t)))))}function qS(e){return[...e].sort((t,n)=>VS(t,n))}function VS(e,t){const n=a_(e.rawRef,t.rawRef);if(n!==null&&n!==0)return n;if(e.sequence!==t.sequence)return e.sequence-t.sequence;const r=o_(e.rawRef,t.rawRef);if(r!==0)return r;const i=e.timestamp.localeCompare(t.timestamp);if(i!==0)return i;const o=l_(e.rawRef,t.rawRef);if(o!==0)return o;const l=m_(e.role,t.role);if(l!==0)return l;const c=e.rawRef.localeCompare(t.rawRef);return c!==0?c:e.id.localeCompare(t.id)}function a_(e,t){if(!e.startsWith("codex://")||!t.startsWith("codex://"))return null;const n=bl(e),r=bl(t);if(!n||!r||n!==r)return null;const i=yl(e),o=yl(t);if(i===null||o===null)return null;if(i!==o)return i-o;const l=ga(e,"part")??0,c=ga(t,"part")??0;return l-c}function bl(e){const t=e.match(/^codex:\/\/(.+?)(?:#|$)/);return(t==null?void 0:t[1])??null}function o_(e,t){const n=h_(e,t);if(n!==null&&n!==0)return n;const r=c_(e,t);if(r!==null&&r!==0)return r;const i=oy(e),o=oy(t);if(!i&&!o||!i||!o)return 0;const l=Math.max(i.length,o.length);for(let c=0;c<l;c+=1){const u=i[c],f=o[c];if(u===void 0&&f===void 0)return 0;if(u===void 0)return-1;if(f===void 0)return 1;if(u!==f)return u-f}return 0}function l_(e,t){const n=yl(e),r=yl(t);return n===null&&r===null?0:n===null?1:r===null?-1:n-r}function yl(e){const t=e.match(/(?:^|[?#&])line=(\d+)(?:$|[&#])/);if(!t)return null;const n=Number.parseInt(t[1]??"",10);return Number.isFinite(n)?n:null}function c_(e,t){const n=ay(e),r=ay(t);if(!n||!r||n!==r)return null;const i=ga(e,"part"),o=ga(t,"part");return i===null||o===null?null:i-o}function ay(e){const t=e.match(/^(.+\/message\/[^/?#]+)\/part\/[^/?#]+(?:[?#].*)?$/i);return(t==null?void 0:t[1])??null}function oy(e){const t=yl(e);if(t!==null){const i=ga(e,"part");return i===null?[t]:[t,i]}const n=u_(e);if(n)return n;const r=d_(e);return r||null}function u_(e){const t=ga(e,"index");if(t===null)return null;const n=ga(e,"part");return n===null?[t]:[t,n]}function ga(e,t){const n=e.match(new RegExp(`(?:^|[?#&])${t}=(\\d+)(?:$|[&#])`));if(!n)return null;const r=Number.parseInt(n[1]??"",10);return Number.isFinite(r)?r:null}function d_(e){const t=e.match(/\/message\/(user|assistant|tool)-(\d+)\/part\/([a-z_]+)-(\d+)/i);if(!t)return null;const n=f_(t[1]??""),r=Number.parseInt(t[2]??"",10),i=Ho(t[3]??""),o=Number.parseInt(t[4]??"",10);return!Number.isFinite(r)||!Number.isFinite(o)?null:[r,n,i,o]}function f_(e){switch(e.toLowerCase()){case"user":return 0;case"assistant":return 1;case"tool":return 2;default:return 3}}function Ho(e){switch(e.toLowerCase()){case"reasoning":case"thinking":return 0;case"text":return 1;case"tool":case"tool_call":case"tool_result":return 2;default:return 3}}function h_(e,t){const n="claude-code://message/";if(!e.startsWith(n)||!t.startsWith(n))return null;let r="",i="";try{r=decodeURIComponent(e.slice(n.length)),i=decodeURIComponent(t.slice(n.length))}catch{return null}const o=r.match(/^message:(assistant|user):([^:]+):type:(thinking|text)$/i),l=i.match(/^message:(assistant|user):([^:]+):type:(thinking|text)$/i);if(o&&l){const x=o[1]??"",k=l[1]??"",C=o[2]??"",j=l[2]??"";return x!==k||C!==j?0:Ho(o[3]??"")-Ho(l[3]??"")}const c=r.match(/^message:(assistant|user):([^:]+):part:(\d+):type:([a-z_]+)$/i),u=i.match(/^message:(assistant|user):([^:]+):part:(\d+):type:([a-z_]+)$/i);if(!c||!u)return null;const f=c[1]??"",h=u[1]??"",m=c[2]??"",g=u[2]??"";if(f!==h||m!==g)return 0;const p=Number.parseInt(c[3]??"",10),b=Number.parseInt(u[3]??"",10);if(!Number.isFinite(p)||!Number.isFinite(b))return null;const y=p-b;return y!==0?y:Ho(c[4]??"")-Ho(u[4]??"")}function m_(e,t){return ly(e)-ly(t)}function ly(e){switch(e){case"user":return 0;case"assistant":return 1;case"tool":return 2;case"system":default:return 3}}function p_(e,t){if(!t)return e;const n=e.attachments??[];return{...e,attachments:n.length>0?n:t.attachments??[],attachmentPayloads:t.attachmentPayloads??null}}function Ph(e,t){if(e.id!==t.id)return t;if(KS(e,t)){const l=wu(e.toolCall,t.toolCall),c=GS(e,t,l,vu),u=Su(e.attachments,t.attachments),f=Cu(e,t);return{...hi(e,t),kind:(l==null?void 0:l.status)==="running"?"tool_call":"tool_result",content:c,toolCall:l,attachments:u,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:f.rawRef,timestamp:f.timestamp,sequence:f.sequence}}if(e.role!==t.role||e.kind!==t.kind)return hi(e,t);const n=wu(e.toolCall,t.toolCall),r=vu(e.content,t.content,e.timestamp,t.timestamp),i=Su(e.attachments,t.attachments),o=Cu(e,t);return{...hi(e,t),content:r,toolCall:n,attachments:i,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:o.rawRef,timestamp:o.timestamp,sequence:o.sequence}}function g_(e,t){if(KS(e,t)){const l=wu(e.toolCall,t.toolCall),c=GS(e,t,l,vu),u=Su(e.attachments,t.attachments),f=Cu(e,t);return{...hi(e,t),id:e.id,kind:(l==null?void 0:l.status)==="running"?"tool_call":"tool_result",content:c,toolCall:l,attachments:u,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:f.rawRef,timestamp:f.timestamp,sequence:f.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}if(e.role!==t.role||e.kind!==t.kind)return{...hi(e,t),id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId};const n=wu(e.toolCall,t.toolCall),r=vu(e.content,t.content,e.timestamp,t.timestamp),i=Su(e.attachments,t.attachments),o=Cu(e,t);return{...hi(e,t),id:e.id,content:r,toolCall:n,attachments:i,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:o.rawRef,timestamp:o.timestamp,sequence:o.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}function KS(e,t){return eC(e,t)||lp(e,t)}function GS(e,t,n,r){if((n==null?void 0:n.status)==="running"){if(t.kind==="tool_call"&&t.content)return t.content;if(e.kind==="tool_call"&&e.content)return e.content}else{if(t.kind==="tool_result"&&t.content)return t.content;if(e.kind==="tool_result"&&e.content)return e.content;if(n!=null&&n.output)return n.output}return r(e.content,t.content,e.timestamp,t.timestamp)}function b_(e,t){return{...Ph(e,{...t,id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId}),id:e.id,rawRef:e.rawRef,timestamp:e.timestamp,sequence:e.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}function cy(e){var t;if(e.role==="tool"&&(e.kind==="tool_call"||e.kind==="tool_result")){const n=((t=e.toolCall)==null?void 0:t.callId.trim())??"";if(n)return`toolCall:${n}`}if(e.role==="assistant"&&(e.kind==="text"||e.kind==="thinking")&&e.rawRef.startsWith("codex://")){const n=bl(e.rawRef);if(n)return`codexAssistantStream:${n}:${e.kind}:${e.sequence}`}return e.id?`id:${e.id}`:e.rawRef?`rawRef:${e.rawRef}`:`fallback:${e.role}:${e.kind}:${e.timestamp}:${e.sequence}`}function y_(e,t,n){if(e.deliveryState!=="sent"||t.deliveryState!=="sent"||!e.rawRef.startsWith("codex://")||!t.rawRef.startsWith("codex://")||e.role!==t.role||e.kind!==t.kind||e.toolCall!==null||t.toolCall!==null||e.kind!=="text"&&e.kind!=="thinking")return!1;const r=ml(e.content),i=ml(t.content);return ya(e.timestamp,t.timestamp,n)&&zn(r.text)===zn(i.text)&&R_(r.inlineImages,i.inlineImages)}function x_(e,t,n){return!e||n||!xl(e)||!xl(t)?!1:ya(e.timestamp,t.timestamp,120*1e3)&&zn(e.content)===zn(t.content)}function xl(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("opencode://")&&e.role==="user"&&e.kind==="text"}function Mh(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("opencode://")&&e.role==="assistant"&&(e.kind==="text"||e.kind==="thinking")}function k_(e){return Mh(e)&&e.kind==="text"}function YS(e,t){return Mh(e)&&Mh(t)&&e.kind===t.kind&&ya(e.timestamp,t.timestamp,120*1e3)&&zn(e.content)===zn(t.content)}function w_(e,t,n,r){return!e||!t||!n||!r||!xl(e)||!xl(n)?!1:YS(t,r)&&ya(e.timestamp,n.timestamp,120*1e3)&&zn(e.content)===zn(n.content)}function JS(e,t){var l,c;const n=((l=e.attachments)==null?void 0:l.length)??0,r=((c=t.attachments)==null?void 0:c.length)??0;if(n!==r)return n>r?e:t;const i=zn(e.content).length,o=zn(t.content).length;return i!==o?i>o?e:t:hi(e,t)}function v_(e,t){return!uy(e)||!uy(t)?!1:e.role===t.role&&ya(e.timestamp,t.timestamp,120*1e3)&&zn(e.content)===zn(t.content)}function S_(e,t){return!dy(e)||!dy(t)?!1:e.role===t.role&&ya(e.timestamp,t.timestamp,120*1e3)&&zn(e.content)===zn(t.content)}function uy(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("gemini://session/")&&e.kind==="text"&&e.toolCall===null&&(e.role==="user"||e.role==="assistant")}function dy(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("kimi://session/")&&e.kind==="text"&&e.toolCall===null&&(e.role==="user"||e.role==="assistant")}function C_(e,t){var u,f;const n=((u=e.attachments)==null?void 0:u.length)??0,r=((f=t.attachments)==null?void 0:f.length)??0;if(n!==r)return n>r?e:t;const i=zn(e.content).length,o=zn(t.content).length;if(i!==o)return i>o?e:t;const l=e.rawRef.includes("#file="),c=t.rawRef.includes("#file=");return l!==c?l?e:t:hi(e,t)}function j_(e,t){var u,f;const n=((u=e.attachments)==null?void 0:u.length)??0,r=((f=t.attachments)==null?void 0:f.length)??0;if(n!==r)return n>r?e:t;const i=zn(e.content).length,o=zn(t.content).length;if(i!==o)return i>o?e:t;const l=e.rawRef.includes("/context#"),c=t.rawRef.includes("/context#");return l!==c?l?e:t:hi(e,t)}function wu(e,t){return e?t?{...N_(e,t),input:XS(e.input,t.input),output:hy(e.output,t.output),error:hy(e.error,t.error)}:e:t}function N_(e,t){const n=fy(e.status),r=fy(t.status);return r!==n?r>n?t:e:t}function fy(e){return e==="running"?0:1}function vu(e,t,n,r){const i=zn(e),o=zn(t);if(i===o){const l=A_(e,t);return l!==null?l:e.length>=t.length?e:t}return i.length>o.length&&i.includes(o)?e:o.length>i.length&&o.includes(i)||r.localeCompare(n)>=0?t:e}function Su(e,t){const n=(e==null?void 0:e.length)??0,r=(t==null?void 0:t.length)??0;return r!==n?r>n?t:e:t??e}function XS(e,t){return t.length>e.length?t:e}function hy(e,t){return e===null?t:t===null?e:XS(e,t)}function hi(e,t){return t.timestamp!==e.timestamp?t.timestamp.localeCompare(e.timestamp)>=0?t:e:t.sequence!==e.sequence?t.sequence>=e.sequence?t:e:t}function Cu(e,t){return VS(e,t)<=0?e:t}function zn(e){return I_(e).replace(/\r\n/g,`
51
+ `).trimEnd()}function Eh(e){return zn(e).replace(/[ \t]+\n/g,`
52
+ `).replace(/\n{2,}/g,`
53
+ `).trim()}function T_(e,t,n,r){return e!=="claude-code"&&e!=="codex"||t!=="user"&&t!=="assistant"||n!=="text"&&n!=="thinking"?r:QS(r)}function I_(e){return QS(e).replace(/\r\n/g,`
54
+ `).trimEnd()}function Lh(e){return e_.test(e)}function QS(e){return Lh(e)?e.replace(ZF,"").replace(/[ \t]+\n/g,`
55
+ `).replace(/\n{3,}/g,`
56
+
57
+ `).trimEnd():e}function A_(e,t){const n=Lh(e),r=Lh(t);return n===r?null:n?t:e}function R_(e,t){return e.length===0||t.length===0?!0:e.length!==t.length?!1:e.every((n,r)=>{var i;return n.url===((i=t[r])==null?void 0:i.url)})}function P_(e,t,n){return tC(t)?ZS(e,t,"optimistic",n):null}function M_(e,t,n){return sd(t)?ZS(e,t,"authoritative",n):null}function E_(e,t,n){if(!ju(n))return null;for(const[r,i]of e.entries())if(!(r===n.id||!t.has(r)||!L_(i,n)))return Hi("session.messages.codex_identity_bridge_match",{previous:Ls(i),incoming:Ls(n)}),r;return null}function L_(e,t){if(!F_(e,t))return!1;if(e.rawRef===t.rawRef)return!0;if(e.kind==="tool_call"||e.kind==="tool_result")return lp(e,t);const n=bl(e.rawRef),r=bl(t.rawRef);if(!n||!r||n!==r)return!1;const i=Math.abs(e.sequence-t.sequence);return i>1?(Hi("session.messages.codex_identity_bridge_rejected",{reason:"sequence_distance",sequenceDistance:i,previous:Ls(e),incoming:Ls(t)}),!1):!0}function D_(e,t){if(!my(t))return null;const n=Nu(t.rawRef);if(n===null)return null;const r=Vi(t.timestamp);let i=null,o=Number.POSITIVE_INFINITY;for(const[l,c]of e.entries()){if(l===t.id||!my(c)||c.role!==t.role)continue;if(eC(c,t))return l;if(c.kind!==t.kind||Nu(c.rawRef)!==n)continue;const f=Vi(c.timestamp),h=Math.abs(f-r),g=Math.abs(c.sequence-t.sequence)*6e4+h;g<o&&(i=l,o=g)}return i}function ZS(e,t,n,r){const i=Vi(t.timestamp),o=zn(t.content),l=Eh(t.content),c=Dh(t.attachments);let u=null,f=Number.POSITIVE_INFINITY;const h=[];for(const[m,g]of e.entries()){if(!(n==="optimistic"?sd(g):tC(g)))continue;const b=zn(g.content),y=Eh(g.content),x=b===o,k=y===l;if(!x&&!k)continue;const C=Vi(g.timestamp),j=Math.abs(C-i);if(j>300*1e3)continue;const H=Math.abs(g.sequence-t.sequence),_=Dh(g.attachments),T=B_(_,c);if(T==="conflict"&&(x||o.length===0)){h.push(gy(g,{strictTextMatches:x,relaxedTextMatches:k,attachmentCompatibility:T,distanceMs:j,sequenceDistance:H}));continue}const P=j+H*15e3+(x?0:500)+W_(T);h.push(gy(g,{strictTextMatches:x,relaxedTextMatches:k,attachmentCompatibility:T,distanceMs:j,sequenceDistance:H})),P<f&&(u=m,f=P)}return h.length>0&&Hi("session.messages.user_match",{sessionId:r,target:n,matchedId:u,matchedScore:Number.isFinite(f)?f:null,incoming:$_(t,{relaxedContent:l,attachmentSignature:c}),candidates:h.slice(0,5)}),u}function ju(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("codex://")&&(e.role==="assistant"||e.role==="tool")}function O_(e,t){const n=t.filter(ju);return n.length===0?e:e.map(r=>{if(!__(r))return r;const i=Vi(r.timestamp),o=n.reduce((c,u)=>Vi(u.timestamp)<i?c:Math.min(c,u.sequence),Number.POSITIVE_INFINITY);if(!Number.isFinite(o)||o>=r.sequence)return r;const l={...r,sequence:o};return Hi("session.messages.synthetic_user_rebased",{syntheticMessage:Ls(r),rebasedMessage:Ls(l),incomingAnchors:n.slice(0,5).map(Ls)}),l})}function my(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("opencode://")&&!sd(e)&&(e.role==="user"||e.role==="assistant"||e.role==="tool")}function py(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("opencode://")&&e.role==="tool"&&(e.kind==="tool_call"||e.kind==="tool_result")&&e.toolCall!==null}function eC(e,t){var i,o;if(!py(e)||!py(t))return!1;const n=((i=e.toolCall)==null?void 0:i.callId.trim())??"",r=((o=t.toolCall)==null?void 0:o.callId.trim())??"";return n&&r?n===r:Nu(e.rawRef)===Nu(t.rawRef)}function Nu(e){if(!e.startsWith("opencode://"))return null;const t=e.indexOf("#"),n=t>=0?e.slice(t):"",r=t>=0?e.slice(0,t):e,i=r.indexOf("?");if(i<0)return e;const o=r.slice(0,i),l=new URLSearchParams(r.slice(i+1));if(!l.has("part"))return e;l.delete("part");const c=l.toString();return`${o}${c?`?${c}`:""}${n}`}function F_(e,t){if(!ju(e)||!ju(t)||e.role!==t.role)return!1;const n=(e.kind==="tool_call"||e.kind==="tool_result")&&(t.kind==="tool_call"||t.kind==="tool_result");return!n&&e.kind!==t.kind?!1:n?lp(e,t):Math.abs(e.sequence-t.sequence)>QF||!ya(e.timestamp,t.timestamp,iy)?!1:t.kind==="text"||t.kind==="thinking"?y_(e,t,iy):!1}function lp(e,t){if(e.deliveryState!=="sent"||t.deliveryState!=="sent"||!e.rawRef.startsWith("codex://")||!t.rawRef.startsWith("codex://")||e.role!=="tool"||t.role!=="tool"||e.kind!=="tool_call"&&e.kind!=="tool_result"||t.kind!=="tool_call"&&t.kind!=="tool_result"||e.toolCall===null||t.toolCall===null)return!1;const n=e.toolCall.callId.trim(),r=t.toolCall.callId.trim();return n.length>0&&n===r}function sd(e){return e.role!=="user"||e.kind!=="text"||e.deliveryState==="failed"?!1:e.rawRef.startsWith("pending://")||e.rawRef.startsWith("synthetic://")||e.rawRef.includes("#synthetic")}function __(e){return e.deliveryState==="sent"&&e.role==="user"&&e.kind==="text"&&e.rawRef.startsWith("synthetic://codex/")}function tC(e){return e.role==="user"&&e.kind==="text"&&!sd(e)}function Vi(e){const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ls(e){var t;return{id:e.id,rawRef:e.rawRef,role:e.role,kind:e.kind,sequence:e.sequence,timestamp:e.timestamp,callId:((t=e.toolCall)==null?void 0:t.callId)??null,contentPreview:e.kind==="text"||e.kind==="thinking"?zn(ml(e.content).text).slice(0,160):zn(e.content).slice(0,160)}}function Dh(e){return(e??[]).map(t=>[t.kind,t.fileName.trim().toLowerCase(),t.mimeType.trim().toLowerCase(),String(t.fileSize)].join(":")).sort().join("|")}function B_(e,t){return!e&&!t?"same":!e||!t?"one_side_missing":e===t?"same":"conflict"}function W_(e){switch(e){case"same":return 0;case"one_side_missing":return 2500;case"conflict":default:return 12e4}}function gy(e,t){return{...Ls(e),comparableContent:Eh(e.content).slice(0,160),attachmentSignature:Dh(e.attachments),strictTextMatches:t.strictTextMatches,relaxedTextMatches:t.relaxedTextMatches,attachmentCompatibility:t.attachmentCompatibility,distanceMs:t.distanceMs,sequenceDistance:t.sequenceDistance}}function $_(e,t){return{...Ls(e),comparableContent:t.relaxedContent.slice(0,160),attachmentSignature:t.attachmentSignature}}function kK(e){return e.reduce((n,r)=>Number.isFinite(r.sequence)&&r.sequence>n?r.sequence:n,0)+1}function ya(e,t,n){return Math.abs(Vi(e)-Vi(t))<=n}const z_=200;async function nC(e){const t=[],n=new Set;let r=null;for(;!(r&&n.has(r));){r&&n.add(r);const i=await uu(e,r,z_,"forward"),o=i.messages.map(l=>nd(e,l));if(t.push(...o),!i.nextCursor||i.nextCursor===r||o.length===0)break;r=i.nextCursor}return{messages:t}}function Za(e,t,n=new Date){return`${V_(e.title||a("conversation.titleFallback"))}-${q_(n)}.${t}`}function sC(e,t,n=new Date){const i=[`# ${(e.title||a("conversation.titleFallback")).trim()||a("conversation.titleFallback")}`,"",`${a("conversation.exportMarkdownSessionIdLabel")}:\`${e.sessionId}\``,`${a("conversation.exportMarkdownProviderLabel")}:${e.provider}`,`${a("conversation.exportMarkdownWorkspaceLabel")}:\`${e.workspaceId}\``,`${a("conversation.exportMarkdownCreatedAtLabel")}:${eo(e.createdAt)}`,`${a("conversation.exportMarkdownExportedAtLabel")}:${eo(n.toISOString())}`,""];return t.forEach((o,l)=>{var c,u,f;i.push(`## ${l+1}. ${oC(o)}`),i.push(""),i.push(`- ${a("conversation.exportMarkdownTimeLabel")}:${eo(o.timestamp)}`),i.push(`- ${a("conversation.exportMarkdownTypeLabel")}:${U_(o)}`),(((c=o.attachments)==null?void 0:c.length)??0)>0&&i.push(`- ${a("conversation.exportMarkdownAttachmentsLabel")}:${o.attachments.length}`),i.push(""),o.content.trim()&&(i.push(o.content),i.push("")),o.toolCall&&(i.push(`### ${a("conversation.exportMarkdownToolSectionTitle")}`),i.push(""),i.push(`- ${a("conversation.exportMarkdownToolNameLabel")}:${o.toolCall.name}`),i.push(`- ${a("conversation.exportMarkdownToolStatusLabel")}:${o.toolCall.status}`),i.push(""),o.toolCall.input.trim()&&(i.push(`#### ${a("conversation.exportMarkdownToolInputLabel")}`),i.push(""),i.push("```text"),i.push(o.toolCall.input),i.push("```"),i.push("")),(o.toolCall.output??"").trim()&&(i.push(`#### ${a("conversation.exportMarkdownToolOutputLabel")}`),i.push(""),i.push("```text"),i.push(o.toolCall.output??""),i.push("```"),i.push("")),(o.toolCall.error??"").trim()&&(i.push(`#### ${a("conversation.exportMarkdownToolErrorLabel")}`),i.push(""),i.push("```text"),i.push(o.toolCall.error??""),i.push("```"),i.push(""))),(((u=o.attachments)==null?void 0:u.length)??0)>0&&(i.push(`### ${a("conversation.exportMarkdownAttachmentsSectionTitle")}`),i.push(""),(f=o.attachments)==null||f.forEach(h=>{i.push(`- ${h.fileName} (${h.kind}, ${h.mimeType}, ${lC(h.fileSize)})`)}),i.push(""))}),`${i.join(`
58
+ `).trimEnd()}
59
+ `}function Tu(e,t,n="text/plain;charset=utf-8"){if(typeof document>"u")throw new Error(a("conversation.exportDownloadFailed"));const r=new Blob([t],{type:n}),i=URL.createObjectURL(r),o=document.createElement("a");o.href=i,o.download=e,document.body.append(o),o.click(),o.remove(),URL.revokeObjectURL(i)}function rC(e,t,n="application/octet-stream"){if(typeof document>"u")throw new Error(a("conversation.exportDownloadFailed"));const r=new Uint8Array(t.byteLength);r.set(t);const i=new Blob([r],{type:n}),o=URL.createObjectURL(i),l=document.createElement("a");l.href=o,l.download=e,document.body.append(l),l.click(),l.remove(),URL.revokeObjectURL(o)}function iC(e,t,n=new Date){const r=(e.title||a("conversation.titleFallback")).trim()||a("conversation.titleFallback"),i=[`${a("conversation.exportMarkdownSessionIdLabel")}:${e.sessionId}`,`${a("conversation.exportMarkdownProviderLabel")}:${e.provider}`,`${a("conversation.exportMarkdownWorkspaceLabel")}:${e.workspaceId}`,`${a("conversation.exportMarkdownCreatedAtLabel")}:${eo(e.createdAt)}`,`${a("conversation.exportMarkdownExportedAtLabel")}:${eo(n.toISOString())}`],o=new J_;return o.renderDocumentHeader(r,i),t.forEach((l,c)=>{o.renderMessageCard(c,l)}),aB(o.finish())}function aC(e){const t=by(e.htmlAttributes,e.htmlStyle),n=by(e.bodyAttributes,e.bodyStyle);return["<!DOCTYPE html>",`<html${t}>`,"<head>",'<meta charset="utf-8" />','<meta name="viewport" content="width=device-width, initial-scale=1" />',`<title>${cC(e.title)}</title>`,`<style>${e.styleText}</style>`,"</head>",`<body${n}>`,e.bodyHtml,"</body>","</html>"].join("")}function oC(e){return`${H_(e)} · ${eo(e.timestamp)}`}function H_(e){switch(e.role){case"user":return a("conversation.roleUser");case"assistant":return a("conversation.roleAssistant");case"tool":return a("conversation.roleTool");case"system":default:return a("conversation.roleSystem")}}function U_(e){return e.kind==="thinking"?a("conversation.thinkingLabel"):e.kind==="tool_call"?a("conversation.exportMarkdownToolCallType"):e.kind==="tool_result"?a("conversation.exportMarkdownToolResultType"):a("conversation.exportMarkdownTextType")}function eo(e){const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toLocaleString()}function q_(e){const t=String(e.getFullYear()),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),l=String(e.getSeconds()).padStart(2,"0");return`${t}${n}${r}-${i}${o}${l}`}function lC(e){return!Number.isFinite(e)||e<0?a("conversation.exportMarkdownUnknownSize"):e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function V_(e){return e.trim().replace(/[\\/:*?"<>|]+/g,"-").replace(/\s+/g,"-")||"session"}function by(e,t){const n=Object.entries(e??{}).filter(([,r])=>r.trim().length>0);return t!=null&&t.trim()&&n.push(["style",t.trim()]),n.length===0?"":` ${n.map(([r,i])=>`${r}="${K_(i)}"`).join(" ")}`}function cC(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function K_(e){return cC(e).replaceAll('"',"&quot;")}const uC=595.28,Uo=841.89,yy=40,xy=40,Da=36,dC=uC-Da*2,G_=14,Oh=12,bc=12,Y_=72,yc=11,za=9,Mo=12,ky=20;class J_{constructor(){ht(this,"pages",[[]]);ht(this,"cursorTop",yy)}renderDocumentHeader(t,n){this.drawRichText(t,Da,this.cursorTop,ky,[15,23,42],"sans"),this.cursorTop+=ky+8,n.forEach(r=>{this.drawRichText(r,Da,this.cursorTop,za,[71,85,105],"sans"),this.cursorTop+=ji(za)}),this.cursorTop+=18}renderMessageCard(t,n){const r=X_(t,n);let i=0,o=0;for(;i<r.lines.length||o===0;){this.ensureVerticalSpace(Y_);const l=this.pickSegmentLines(r.lines,i);l.count===0&&r.lines.length>0&&(l.lines.push(r.lines[i]),l.count=1,l.height=ji(r.lines[i].fontSize));const c=o===0?r.header:`${r.header} · 续`,u=bc*2+ji(Mo)+8+Math.max(l.height,0);if(this.ensureVerticalSpace(u),this.drawCardSegment(r,c,l.lines,l.height),this.cursorTop+=u+G_,i+=l.count,o+=1,r.lines.length===0)break}}finish(){return this.pages.map(t=>t.join(`
60
+ `))}drawCardSegment(t,n,r,i){const o=bc*2+ji(Mo)+8+Math.max(i,0),l=this.cursorTop,c=Uo-l-o;this.pushCommand(`${xc(t.backgroundColor)} rg ${xc(t.borderColor)} RG 1 w ${gr(Da)} ${gr(c)} ${gr(dC)} ${gr(o)} re B`);let u=l+bc;this.drawRichText(n,Da+Oh,u,Mo,t.headerColor,"sans"),u+=ji(Mo)+8,r.forEach(f=>{u+=f.gapBefore,this.drawRichText(f.text,Da+Oh,u,f.fontSize,f.color,f.fontKind),u+=ji(f.fontSize)})}pickSegmentLines(t,n){const r={lines:[],count:0,height:0},i=Uo-this.cursorTop-xy-bc*2-ji(Mo)-8;if(i<=0)return r;let o=0;for(let l=n;l<t.length;l+=1){const c=t[l],u=o+c.gapBefore+ji(c.fontSize);if(r.count>0&&u>i)break;r.lines.push(c),r.count+=1,o=u}return r.height=o,r}ensureVerticalSpace(t){this.cursorTop+t<=Uo-xy||(this.pages.push([]),this.cursorTop=yy)}drawRichText(t,n,r,i,o,l){const c=Uo-r-i;let u=n;tB(t).forEach(h=>{if(h.text){if(h.fontRef==="F1"){u=this.drawPdfUnicodeRun(h.text,u,c,i,o);return}this.pushCommand(`BT /${h.fontRef} ${gr(i)} Tf ${xc(o)} rg 1 0 0 1 ${gr(u)} ${gr(c)} Tm (${iB(h.text)}) Tj ET`),u+=sB(h.text,i,h.fontRef)}})}drawPdfUnicodeRun(t,n,r,i,o){let l=n;for(const c of Array.from(t))this.pushCommand(`BT /F1 ${gr(i)} Tf ${xc(o)} rg 1 0 0 1 ${gr(l)} ${gr(r)} Tm <${eB(c)}> Tj ET`),l+=cp(c,i,"F1");return l}pushCommand(t){var n;(n=this.pages[this.pages.length-1])==null||n.push(t)}}function X_(e,t){var l,c;const n=Q_(t.role),r=dC-Oh*2,i=[],o=`${e+1}. ${oC(t)}`;if(t.content.trim()&&Ci(i,t.content,r,yc,[15,23,42],0,"sans"),t.toolCall){const u=`${a("conversation.exportMarkdownToolSectionTitle")} · ${t.toolCall.name} · ${t.toolCall.status}`;Ci(i,u,r,yc,[30,41,59],10,"sans"),t.toolCall.input.trim()&&Ci(i,`${a("conversation.exportMarkdownToolInputLabel")}:${t.toolCall.input}`,r,za,[71,85,105],6,"mono"),(t.toolCall.output??"").trim()&&Ci(i,`${a("conversation.exportMarkdownToolOutputLabel")}:${t.toolCall.output??""}`,r,za,[71,85,105],6,"mono"),(t.toolCall.error??"").trim()&&Ci(i,`${a("conversation.exportMarkdownToolErrorLabel")}:${t.toolCall.error??""}`,r,za,[185,28,28],6,"mono")}return(((l=t.attachments)==null?void 0:l.length)??0)>0&&(Ci(i,a("conversation.exportMarkdownAttachmentsSectionTitle"),r,yc,[30,41,59],10,"sans"),(c=t.attachments)==null||c.forEach(u=>{Ci(i,`- ${u.fileName} (${u.kind}, ${u.mimeType}, ${lC(u.fileSize)})`,r,za,[71,85,105],4,"sans")})),i.length===0&&Ci(i,a("conversation.exportMarkdownTextType"),r,yc,[100,116,139],0,"sans"),{header:o,headerColor:n.headerColor,backgroundColor:n.backgroundColor,borderColor:n.borderColor,lines:i}}function Q_(e){switch(e){case"user":return{headerColor:[30,64,175],backgroundColor:[239,246,255],borderColor:[191,219,254]};case"tool":return{headerColor:[6,95,70],backgroundColor:[236,253,245],borderColor:[167,243,208]};case"system":return{headerColor:[71,85,105],backgroundColor:[248,250,252],borderColor:[226,232,240]};case"assistant":default:return{headerColor:[15,23,42],backgroundColor:[255,255,255],borderColor:[226,232,240]}}}function Ci(e,t,n,r,i,o=0,l="sans"){t.replace(/\r\n/g,`
61
+ `).split(`
62
+ `).forEach((f,h)=>{const m=Z_(f,n,r);if(m.length===0){e.push({text:" ",fontSize:r,color:i,gapBefore:h===0?o:4,fontKind:l});return}m.forEach((g,p)=>{e.push({text:g,fontSize:r,color:i,gapBefore:h===0&&p===0?o:p===0?4:0,fontKind:l})})})}function Z_(e,t,n,r){if(!e.trim())return[];const i=[];let o="",l=0;const c=fC();for(const u of Array.from(e)){const f=cp(u,n,c);if(o&&l+f>t){i.push(o.trimEnd()),o=u,l=f;continue}o+=u,l+=f}return o.trim().length>0&&i.push(o.trimEnd()),i}function cp(e,t,n){if(n==="F1")return t*(rB(e)/1e3);const r=n==="F3"?600:hC[e]??556;return t*(r/1e3)}function ji(e){return e*1.5}function xc(e){return e.map(t=>gr(t/255)).join(" ")}function gr(e){return Number.isInteger(e)?String(e):e.toFixed(3).replace(/0+$/u,"").replace(/\.$/u,"")}function eB(e){return[254,255,...Array.from(e).flatMap(r=>{const i=r.codePointAt(0)??32;if(i<=65535)return[i];const o=i-65536,l=55296+(o>>10&1023),c=56320+(o&1023);return[l,c]}).flatMap(r=>[r>>8&255,r&255])].map(r=>r.toString(16).padStart(2,"0").toUpperCase()).join("")}function tB(e,t){if(!e)return[];const n=fC();return[{text:e,fontRef:n}]}function fC(e,t){return"F1"}function nB(e){const t=e.codePointAt(0)??0;return t>=32&&t<=126}function sB(e,t,n){return Array.from(e).reduce((r,i)=>r+cp(i,t,n),0)}function rB(e){return nB(e)?hC[e]??556:e===" "?278:1e3}function iB(e){return e.replace(/\\/gu,"\\\\").replace(/\(/gu,"\\(").replace(/\)/gu,"\\)")}const hC={" ":278,"!":278,'"':355,"#":556,$:556,"%":889,"&":667,"'":191,"(":333,")":333,"*":389,"+":584,",":278,"-":333,".":278,"/":278,0:556,1:556,2:556,3:556,4:556,5:556,6:556,7:556,8:556,9:556,":":278,";":278,"<":584,"=":584,">":584,"?":556,"@":1015,A:667,B:667,C:722,D:722,E:667,F:611,G:778,H:722,I:278,J:500,K:667,L:556,M:833,N:722,O:778,P:667,Q:778,R:722,S:667,T:611,U:722,V:667,W:944,X:667,Y:667,Z:611,"[":278,"\\":278,"]":278,"^":469,_:556,"`":333,a:556,b:556,c:500,d:556,e:556,f:278,g:556,h:556,i:222,j:222,k:500,l:222,m:833,n:556,o:556,p:556,q:556,r:333,s:500,t:278,u:556,v:500,w:722,x:500,y:500,z:500,"{":334,"|":260,"}":334,"~":584};function aB(e){const t=[],n=[];t[1]="<< /Type /Catalog /Pages 2 0 R >>",t[3]="<< /Type /Font /Subtype /Type0 /BaseFont /STSong-Light /Encoding /UniGB-UCS2-H /DescendantFonts [4 0 R] >>",t[4]="<< /Type /Font /Subtype /CIDFontType0 /BaseFont /STSong-Light /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 4 >> /DW 1000 >>",t[5]="<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",t[6]="<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>";let c=7;e.forEach(b=>{const y=c,x=c+1;n.push(y),c+=2;const k=new TextEncoder().encode(b);t[x]=`<< /Length ${k.length} >>
63
+ stream
64
+ ${b}
65
+ endstream`,t[y]=["<< /Type /Page","/Parent 2 0 R",`/MediaBox [0 0 ${gr(uC)} ${gr(Uo)}]`,"/Resources << /Font << /F1 3 0 R /F2 5 0 R /F3 6 0 R >> >>",`/Contents ${x} 0 R`,">>"].join(" ")}),t[2]=`<< /Type /Pages /Kids [${n.map(b=>`${b} 0 R`).join(" ")}] /Count ${n.length} >>`;const u=t.filter(Boolean).length,f=[`%PDF-1.4
66
+ %----
67
+ `],h=[0];let m=new TextEncoder().encode(f[0]).length;for(let b=1;b<t.length;b+=1){const y=t[b];if(!y)continue;h[b]=m;const x=`${b} 0 obj
68
+ ${y}
69
+ endobj
70
+ `;f.push(x),m+=new TextEncoder().encode(x).length}const g=m,p=["xref",`0 ${u+1}`,"0000000000 65535 f "];for(let b=1;b<h.length;b+=1){const y=h[b];typeof y=="number"&&p.push(`${String(y).padStart(10,"0")} 00000 n `)}return f.push(`${p.join(`
71
+ `)}
72
+ `),f.push(["trailer",`<< /Size ${u+1} /Root 1 0 R >>`,"startxref",String(g),"%%EOF"].join(`
73
+ `)),new TextEncoder().encode(f.join(""))}const wy=48;function oB(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function rd(e,t){const n=oB(e)||t,r=n.length>wy?n.slice(0,wy).trimEnd():n;return{fullTitle:n,displayTitle:r}}function kc(e,t){return(t??"").localeCompare(e??"")}function vy(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"})}function wc(e){return(e==null?void 0:e.trim())??""}function kl(e,t,n){if(n==="updatedAt"){const l=kc(e.updatedAt,t.updatedAt);if(l!==0)return l}if(n==="title"){const l=vy(wc(e.title),wc(t.title));if(l!==0)return l}else{const l=kc(e.createdAt,t.createdAt);if(l!==0)return l}const r=kc(e.updatedAt,t.updatedAt);if(r!==0)return r;const i=kc(e.createdAt,t.createdAt);if(i!==0)return i;const o=vy(wc(e.title),wc(t.title));return o!==0?o:e.sessionId.localeCompare(t.sessionId)}function io(e,t){return[...e].sort((n,r)=>kl(n,r,t))}function up(e,t){return Array.isArray(e)?e.map(n=>({...n,sessions:io(n.sessions,t),children:up(n.children,t)})):[]}const cf=5,uf=["#2563eb","#0891b2","#16a34a","#d97706","#dc2626","#64748b"];function lB(e){const t=Math.round(e.ratio*1e3)/10;return`${t.toFixed(t%1===0?0:1)}%`}function cB(e,t){const n=e.reduce((c,u)=>c+u.count,0);if(n<=0)return[];const i=e.slice(0,cf).map((c,u)=>({...c,key:c.type,ratio:c.count/n,color:uf[u]??uf[0]})),o=e.slice(cf);if(o.length===0)return i;const l=o.reduce((c,u)=>c+u.count,0);return i.push({key:"other",type:t,count:l,ratio:l/n,color:uf[cf]}),i}function uB(e){if(e.length===0)return"conic-gradient(color-mix(in srgb, var(--border-primary) 78%, transparent) 0% 100%)";let t=0;return`conic-gradient(${e.map((r,i)=>{const o=t,l=i===e.length-1?1:Math.min(1,t+r.ratio);return t=l,`${r.color} ${Sy(o)} ${Sy(l)}`}).join(", ")})`}function dB(e){return{"--workbench-manage-chart-background":uB(e)}}function Sy(e){const t=Math.round(e*1e3)/10;return`${t.toFixed(t%1===0?0:1)}%`}const fB=8,hB=12,mB=160,Cy=96;function dp(e,t,n,r={}){const i=r.gapPx??fB,o=r.viewportMarginPx??hB,l=r.defaultWidthPx??mB,c=r.estimatedHeightPx??Cy,u=r.minHeightPx??Cy,f=Math.max(0,n.width),h=Math.max(0,n.height),m=Math.max(0,h-o*2),g=Math.max(0,f-o*2),p=vc(Math.max(t.width||l,l),0,g),b=Math.max(t.height||c,c),y=Math.max(0,f-e.x-o),x=Math.max(0,e.x-o),k=y<p&&x>y,C=Math.max(0,h-e.y-i-o),j=Math.max(0,e.y-i-o),H=C<b&&j>C,T=vc(Math.max(H?j:C,u),0,m),P=Math.min(b,T),z=k?e.x-p:e.x,L=Math.max(o,f-o-p),R=H?e.y-i-P:e.y+i,K=Math.max(o,h-o-P),E=vc(z,o,L),D=vc(R,o,K),te=k||E<e.x?"right":"left";return{top:D,left:E,width:p,maxHeight:Math.max(0,T),transformOrigin:`${H?"bottom":"top"} ${te}`}}function vc(e,t,n){return!Number.isFinite(e)||n<t?t:Math.min(Math.max(e,t),n)}const mC="workbench.navigation.snapshot",pC=1800*1e3,pB="workbench.navigation.snapshot.host.";function gC(e){return`${pB}${e}`}function gB(e=pC,t=_u(Fr.getState())){if(t){const n=Br(gC(t),e);if(n)return n}return Br(mC,e)}function Sc(e,t=_u(Fr.getState())){Rr(mC,e),t&&Rr(gC(t),e)}function jy(e,t="createdAt"){return!e||!Array.isArray(e.items)?[]:e.items.map(n=>({workspace:n.workspace,sessions:io(n.sessions,t),childWorktrees:bB(n.childWorktrees,t),affairsAssistantSessions:io(n.affairsAssistantSessions??[],t),affairsAssistantProjectId:n.affairsAssistantProjectId??null,affairsAssistantProjectWorkspaceId:n.affairsAssistantProjectWorkspaceId??null,affairsAssistantSessionsUpdatedAt:n.affairsAssistantSessionsUpdatedAt??null}))}function bB(e,t){return up(e,t)}function Iu(e){return{workspaceId:e.id,tone:"root",backgroundColor:e.backgroundColor??null,displayName:e.name,workspaceName:e.name,branchName:null,depth:0,rootWorkspaceId:e.id,rootDisplayName:e.name,parentWorkspaceId:null,parentDisplayName:null}}function yB(e){const t=new Map;for(const n of e)t.set(n.workspace.id,Iu(n.workspace)),bC(t,n.childWorktrees??[],n.workspace,n.workspace);return Object.fromEntries(t)}function Gr(e){if(e!=null&&e.backgroundColor)return{"--workspace-tone-color":e.backgroundColor}}function bC(e,t,n,r,i=r.name){var o;for(const l of t){const c=((o=l.meta.displayName)==null?void 0:o.trim())||l.workspace.name;e.set(l.workspace.id,{workspaceId:l.workspace.id,tone:"worktree",backgroundColor:l.workspace.backgroundColor??null,displayName:c,workspaceName:l.workspace.name,branchName:l.meta.branchName||null,depth:l.meta.depth,rootWorkspaceId:n.id,rootDisplayName:n.name,parentWorkspaceId:l.meta.parentWorkspaceId||r.id,parentDisplayName:i}),bC(e,l.children,n,l.workspace,c)}}function fp(e,t=!0){const n=d.useMemo(()=>Gg(e),[e]),{items:r,loading:i,requested:o}=Tw(t),l=d.useMemo(()=>{if(!r)return o&&!i?n:[];const c=new Set(n),u=r.filter(f=>f.enabled&&c.has(f.provider)).map(f=>f.provider);return Gg(u)},[n,r]);return{providerCatalog:r,visibleProviders:l,loading:i,ready:r!==null||o&&!i}}const hp=new Map;function xB(){hp.clear()}function yC({disabled:e=!1,workspaceId:t=null,pendingProvider:n=null,selectedProvider:r=null,providers:i=Dm,className:o,disabledReasons:l,statusHintByProvider:c,onSelect:u}){const f=Tl(),{visibleProviders:h,ready:m}=fp(i),g=!!t,[p,b]=d.useState(()=>Ny(h,t)),y=h.map(x=>({provider:x}));return d.useEffect(()=>{qw()},[]),d.useEffect(()=>{if(!m){b({});return}if(!t){b({});return}const x=Ny(h,t);b(x);const k=h.filter(j=>!x[j]);if(k.length===0)return;let C=!1;return km(k,t).then(j=>{wB(t,j),C||b(H=>({...H,...j}))}),()=>{C=!0}},[m,h,t]),m?s.jsx("div",{className:`session-provider-grid${o?` ${o}`:""}`,children:y.map(x=>{const k=Ui(x.provider,"full"),C=n===x.provider,j=r===x.provider,H=!!p[x.provider],_=kB(p[x.provider]??null),T=(l==null?void 0:l[x.provider])??_,P=C?a("shell.startingSession"):T||((c==null?void 0:c[x.provider])??(g&&!H&&!C?a("shell.providerChecking"):null));return s.jsxs("button",{type:"button",className:"session-provider-card","data-provider":x.provider,"data-pending":C?"true":"false","data-selected":j?"true":"false","aria-label":k,disabled:e||!!T,onClick:()=>{f.trigger("action"),u(x.provider)},children:[s.jsx("span",{className:"session-provider-card-icon","aria-hidden":"true",children:s.jsx("img",{src:Uw(x.provider),alt:"",loading:"eager",decoding:"async"})}),s.jsxs("span",{className:"session-provider-card-copy",children:[s.jsx("strong",{children:k}),P?s.jsx("span",{className:"session-provider-card-status",children:P}):null]})]},x.provider)})}):s.jsx("div",{className:`session-provider-grid${o?` ${o}`:""}`,children:s.jsx("div",{className:"session-provider-card","aria-hidden":"true","data-placeholder":"true",children:s.jsx("span",{className:"session-provider-card-copy",children:s.jsx("strong",{children:a("shell.providerChecking")})})})})}function kB(e){return!e||e.canStartSession!==!1?null:e.limitations[0]??a("conversation.capabilityDenied")}function Ny(e,t){const n=(t==null?void 0:t.trim())??"";if(!n)return{};const r=[];for(const i of e){const o=hp.get(xC(n,i));o&&r.push([i,o])}return Object.fromEntries(r)}function wB(e,t){const n=e.trim();if(n)for(const[r,i]of Object.entries(t))i&&hp.set(xC(n,r),i)}function xC(e,t){return`${e}::${t}`}class Fh extends Error{constructor(t,n){super(n),this.code=t,this.name="HostSwitchError"}}class vB{constructor(){ht(this,"inFlight",null)}async switchHost(t){this.inFlight&&await this.inFlight;const n=this.performSwitch(t).finally(()=>{this.inFlight===n&&(this.inFlight=null)});this.inFlight=n,await n}async performSwitch(t){const n=Fr.getState();if(_u(n)===t)return;const r=oT(n,t);if(!r)throw new Fh("HOST_NOT_FOUND",`找不到 HOST:${t}`);if(!(await lT(r.baseUrl)).reachable)throw new Fh("HOST_UNREACHABLE",`目标 HOST 不可达:${r.baseUrl}`);const o=_k(r.id);if(o)try{await fa.loginForHost(r,{username:o.username,password:o.password})}catch{}const l=Fr.getState(),c=new Date().toISOString();if(Bk(r)){Fr.updateRuntime({discoveredHosts:l.discoveredHosts.map(u=>u.id===t?{...u,lastConnectedAt:c,updatedAt:c}:u),activeDiscoveredHostId:t});return}eh.setActiveDiscoveredHost(null),await Fr.update({hosts:l.hosts.map(u=>u.id===t?{...u,lastConnectedAt:c,updatedAt:c}:u),activeHostId:t})}}const SB=new vB;function CB(){const e=Bu(n=>n),t=cT(n=>n);return jB(e,t)}function jB(e,t){var l;const n=au(e);if(!n)return null;const r=!!((l=n.relayTunnel)!=null&&l.enabled),o=!(e.platform==="web"&&r)&&t.activeHostId===n.id&&t.candidateProbePhase==="ready"?TB(t):null;if(o){const c=IB(o.kind);return{kind:c,url:o.url,endpointId:o.endpointId,autoDirect:r&&c!=="relay",probeInProgress:!1}}return{kind:AB(n),url:n.baseUrl,endpointId:null,autoDirect:!1,probeInProgress:r&&t.activeHostId===n.id&&t.candidateProbePhase==="probing"}}function NB(e){switch(e){case"relay":return"common.connectionRouteRelay";case"lan":return"common.connectionRouteLan";case"loopback":return"common.connectionRouteLoopback";case"tailscale":return"common.connectionRouteTailscale";default:return"common.connectionRouteDirect"}}function TB(e){const t=e.preferredDirectCandidateEndpointId??e.preferredCandidateEndpointId;return t?e.candidateEndpoints.find(n=>n.endpointId===t&&n.status==="verified")??null:null}function IB(e){return e==="custom"?"direct":e}function AB(e){var t;if((t=e.relayTunnel)!=null&&t.enabled&&RB(e.baseUrl,e.relayTunnel.tunnelDomain))return"relay";try{const n=new URL(e.baseUrl).hostname.toLowerCase();if(PB(n))return"loopback";if(MB(n))return"tailscale";if(EB(n))return"lan"}catch{return"direct"}return e.kind==="local"?"loopback":e.kind==="lan"?"lan":"direct"}function RB(e,t){try{return new URL(e).hostname.toLowerCase()===t.trim().toLowerCase()}catch{return!1}}function PB(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}function MB(e){if(e.endsWith(".ts.net"))return!0;const t=e.split(".").map(i=>Number(i));if(t.length!==4||t.some(i=>Number.isNaN(i)))return!1;const[n,r]=t;return n===100&&r>=64&&r<=127}function EB(e){const t=e.split(".").map(i=>Number(i));if(t.length!==4||t.some(i=>Number.isNaN(i)))return!1;const[n,r]=t;return n===10||n===192&&r===168||n===172&&r>=16&&r<=31}async function LB(){return await ae.request("/api/system/host/resources")}const df={status:"idle",latencyMs:null},ff={status:"idle",snapshot:null};function _h({collapsed:e=!1}){const[t,n]=d.useState(!1),[r,i]=d.useState(!1),[o,l]=d.useState(""),[c,u]=d.useState(""),[f,h]=d.useState(""),[m,g]=d.useState(""),[p,b]=d.useState(null),[y,x]=d.useState(null),[k,C]=d.useState(null),[j,H]=d.useState(null),[_,T]=d.useState(!1),[P,z]=d.useState(df),[L,R]=d.useState(ff),[K,E]=d.useState(null),D=d.useRef(null),te=d.useRef(null),V=Bu(Y=>Y),ee=iu(Y=>Y.session),{showToast:U}=Vn(),he=au(V),X=_u(V),I=CB(),xe=uT(X),le=d.useMemo(()=>Ty(V.hosts,X),[X,V.hosts]),M=d.useMemo(()=>Ty(Wk(V),X),[X,V]),de=d.useCallback(()=>{if(typeof window>"u")return;const Y=D.current;if(!Y)return;const Te=Y.getBoundingClientRect(),pe=window.innerWidth,fe=window.innerHeight,W=16,Me=8,Q=Math.min(360,Math.max(240,pe-W*2)),ge=Math.min(e?Math.max(W,Te.right+Me):Math.max(W,Te.left),Math.max(W,pe-Q-W)),Oe=r?520:j?600:320,$e=e?Te.top:Te.bottom+Me,Ve=Math.min(Math.max(W,$e),Math.max(W,fe-Oe-W));E({position:"fixed",top:Ve,left:ge,width:Q,maxWidth:pe-W*2})},[e,j,r]);d.useEffect(()=>{if(!t){E(null),H(null),z(df),R(ff);return}eh.refresh();function Y(pe){var fe,W;pe.target instanceof Node&&!((fe=D.current)!=null&&fe.contains(pe.target))&&!((W=te.current)!=null&&W.contains(pe.target))&&(n(!1),i(!1),H(null),C(null))}function Te(pe){pe.key==="Escape"&&(n(!1),i(!1),H(null),C(null))}return window.addEventListener("pointerdown",Y),window.addEventListener("keydown",Te),window.addEventListener("resize",de),window.addEventListener("scroll",de,!0),de(),()=>{window.removeEventListener("pointerdown",Y),window.removeEventListener("keydown",Te),window.removeEventListener("resize",de),window.removeEventListener("scroll",de,!0)}},[t,de]),d.useEffect(()=>{if(!j||j!==X||!t||(I==null?void 0:I.kind)!=="relay"){z(df);return}let Y=!1;const Te=performance.now();return z({status:"probing",latencyMs:null}),ae.request("/api/client/runtime-config").then(()=>{Y||z({status:"ready",latencyMs:performance.now()-Te})}).catch(()=>{Y||z({status:"error",latencyMs:null})}),()=>{Y=!0}},[X,I==null?void 0:I.kind,j,t]),d.useEffect(()=>{if(!j||j!==X||!t){R(ff);return}let Y=!1,Te=null;async function pe(fe){fe||R(W=>W.snapshot?{status:"refreshing",snapshot:W.snapshot}:{status:"loading",snapshot:null});try{const W=await LB();if(Y)return;R({status:"ready",snapshot:W})}catch{if(Y)return;R(W=>W.snapshot?W:{status:"error",snapshot:null})}}return pe(!1),Te=window.setInterval(()=>{pe(!0)},5e3),()=>{Y=!0,Te!==null&&window.clearInterval(Te)}},[X,j,t]);async function Ne(Y){if(p||y||Y.id===X){n(!1);return}b(Y.id);try{await SB.switchHost(Y.id),n(!1),i(!1),H(null),C(null)}catch(Te){U({title:BB(Te,Y.name),tone:"error"})}finally{b(null)}}async function ye(Y){if(!(Y.id===X||p||y)){if(k!==Y.id){C(Y.id);return}x(Y.id);try{await Fr.update({hosts:V.hosts.filter(Te=>Te.id!==Y.id)}),hT(Y.id),fa.clearHostSession(Y.id),C(null),U({title:a("shell.hostDeleteSuccess",{name:Y.name})})}catch{U({title:a("shell.hostDeleteFailed",{name:Y.name}),tone:"error"})}finally{x(null)}}}async function Be(){if(_)return;const Y=o.trim(),Te=f.trim();if((Te.length>0||m.length>0)&&(!Te||!m)){U({title:a("shell.hostAddIncompleteCredentials"),tone:"error"});return}let fe;try{fe=dT(c)}catch{U({title:a("shell.hostAddInvalidUrl"),tone:"error"});return}T(!0);try{const W=await WT(fe),Me=Fr.getState(),je=au(Me);if(W?Me.hosts.find(Ve=>{var G;return Ve.baseUrl===fe||!!W.bindingId&&((G=Ve.relayTunnel)==null?void 0:G.bindingId)===W.bindingId}):Me.hosts.find(Ve=>Ve.baseUrl===fe)){U({title:a("shell.hostAddDuplicate"),tone:"error"});return}const ge=Bk(je)&&je.baseUrl===fe;ge&&eh.setActiveDiscoveredHost(null);let Oe,$e;if(W){const G=(await Fr.update($T(Me,W,{activate:ge,displayName:Y}))).hosts.find(ve=>FB(ve,fe,W.bindingId??null));if(!G)throw new Error("relay entry host missing after save");Oe=G.id,$e=G.name}else{const Ve=new Date().toISOString(),G={id:_B(),name:Y||DB(fe),baseUrl:fe,kind:OB(fe),createdAt:Ve,updatedAt:Ve,lastConnectedAt:null,lastUserId:null,lastUsername:null};await Fr.update({hosts:[...Me.hosts,G],activeHostId:ge?G.id:Me.activeHostId}),Oe=G.id,$e=G.name}Te&&m&&fT({hostId:Oe,username:Te,password:m}),We(),i(!1),C(null),U({title:a("shell.hostAddSuccess",{name:$e})})}catch{U({title:a("shell.hostAddFailed"),tone:"error"})}finally{T(!1)}}function We(){l(""),u(""),h(""),g("")}if(!he)return null;const Ce=he.baseUrl,ke=ee!=null&&ee.user.username?`${he.baseUrl} · ${ee.user.username}`:he.baseUrl,we=(I==null?void 0:I.kind)==="relay"?a("shell.hostSwitcherDetailStatusRelay"):a("shell.hostSwitcherDetailStatusDirect"),se=I?a(NB(I.kind)):a("common.unknown");function ce(Y,Te){const pe=Y.id===X,fe=pe&&j===Y.id;return s.jsxs("div",{className:"workbench-host-switcher-item","data-active":pe,"data-discovered":Te.discovered?"true":void 0,"data-expanded":fe,children:[s.jsxs("div",{className:"workbench-host-switcher-item-row",children:[s.jsxs("button",{type:"button",className:"workbench-host-switcher-item-main",disabled:p!==null||y!==null,onClick:()=>{Ne(Y)},children:[s.jsxs("span",{className:"workbench-host-switcher-item-copy",children:[s.jsxs("span",{className:"workbench-host-switcher-item-title",children:[Y.name,Te.discovered?s.jsx("span",{className:"workbench-host-switcher-item-badge","data-tone":"discovered",children:a("shell.hostSwitcherDiscoveredBadge")}):null,pe?s.jsx("span",{className:"workbench-host-switcher-item-badge",children:a("shell.hostSwitcherCurrentBadge")}):null]}),s.jsx("span",{className:"workbench-host-switcher-item-meta",children:Te.statusText})]}),s.jsx("span",{className:"workbench-host-switcher-item-trailing",children:p===Y.id?a("shell.hostSwitcherSwitching"):pe?s.jsx(KB,{}):s.jsx(VB,{})})]}),pe?s.jsx("button",{type:"button",className:"workbench-host-switcher-item-action","aria-label":a("shell.hostSwitcherDetailAriaLabel",{name:Y.name}),"aria-expanded":fe,"data-tone":"detail",onClick:()=>{H(W=>W===Y.id?null:Y.id),C(null)},children:a("shell.hostSwitcherDetailAction")}):Te.deletable?s.jsx("button",{type:"button",className:"workbench-host-switcher-item-action","aria-label":a("shell.hostDeleteAriaLabel",{name:Y.name}),title:k===Y.id?a("shell.hostDeleteConfirmAction"):a("shell.hostDeleteAction"),"data-confirming":k===Y.id,disabled:p!==null||y!==null,onClick:()=>{ye(Y)},children:y===Y.id?a("shell.hostDeleteBusy"):k===Y.id?a("shell.hostDeleteConfirmAction"):s.jsx(YB,{})}):null]}),fe?s.jsxs("div",{className:"workbench-host-switcher-detail-panel",role:"region","aria-label":a("shell.hostSwitcherDetailTitle"),children:[s.jsx("div",{className:"workbench-host-switcher-detail-header",children:s.jsx("strong",{children:a("shell.hostSwitcherDetailTitle")})}),s.jsx("div",{className:"workbench-host-switcher-detail-section",children:s.jsxs("div",{className:"workbench-host-switcher-detail-grid",children:[s.jsxs("div",{className:"workbench-host-switcher-detail-row",children:[s.jsx("span",{className:"workbench-host-switcher-detail-label",children:a("shell.hostSwitcherDetailStatusLabel")}),s.jsx("span",{className:"workbench-host-switcher-detail-value",children:we})]}),s.jsxs("div",{className:"workbench-host-switcher-detail-row",children:[s.jsx("span",{className:"workbench-host-switcher-detail-label",children:a("shell.hostSwitcherDetailRouteLabel")}),s.jsx("span",{className:"workbench-host-switcher-detail-value",children:se})]}),s.jsxs("div",{className:"workbench-host-switcher-detail-row",children:[s.jsx("span",{className:"workbench-host-switcher-detail-label",children:a("shell.hostSwitcherDetailAddressLabel")}),s.jsx("span",{className:"workbench-host-switcher-detail-value","data-multiline":"true",children:(I==null?void 0:I.url)??Ce})]}),(I==null?void 0:I.kind)==="relay"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"workbench-host-switcher-detail-row",children:[s.jsx("span",{className:"workbench-host-switcher-detail-label",children:a("shell.hostSwitcherDetailLatencyLabel")}),s.jsx("span",{className:"workbench-host-switcher-detail-value",children:WB(P)})]}),s.jsxs("div",{className:"workbench-host-switcher-detail-row",children:[s.jsx("span",{className:"workbench-host-switcher-detail-label",children:a("shell.hostSwitcherDetailTrafficLabel")}),s.jsx("span",{className:"workbench-host-switcher-detail-value",children:wl(xe.totalBytes)})]})]}):null]})}),s.jsxs("div",{className:"workbench-host-switcher-detail-section",children:[s.jsx("div",{className:"workbench-host-switcher-detail-section-title",children:a("shell.hostSwitcherDetailResourceTitle")}),s.jsx("div",{className:"workbench-host-switcher-resource-list",children:UB(L).map(W=>s.jsxs("div",{className:"workbench-host-switcher-resource-item","data-tone":W.tone,"data-contrast":W.contrast,children:[s.jsx("span",{className:"workbench-host-switcher-resource-label",children:W.label}),s.jsxs("div",{className:"workbench-host-switcher-resource-bar",children:[s.jsx("span",{className:"workbench-host-switcher-resource-bar-fill",style:{width:`${Math.max(0,Math.min(100,Math.round((W.ratio??0)*100)))}%`}}),s.jsxs("span",{className:"workbench-host-switcher-resource-bar-content",children:[s.jsx("span",{className:"workbench-host-switcher-resource-summary",children:W.summary}),W.progressLabel?s.jsx("span",{className:"workbench-host-switcher-resource-percent",children:W.progressLabel}):null]}),s.jsxs("span",{className:"workbench-host-switcher-resource-bar-content workbench-host-switcher-resource-bar-content-overlay","data-fill-tone":W.fillTextTone,"aria-hidden":"true",style:{clipPath:`inset(0 ${Math.max(0,100-Math.max(0,Math.min(100,Math.round((W.ratio??0)*100))))}% 0 0)`},children:[s.jsx("span",{className:"workbench-host-switcher-resource-summary",children:W.summary}),W.progressLabel?s.jsx("span",{className:"workbench-host-switcher-resource-percent",children:W.progressLabel}):null]})]})]},W.key))})]})]}):null]},Y.id)}return s.jsxs("div",{ref:D,className:"workbench-host-switcher-anchor","data-collapsed":e,children:[s.jsx("button",{type:"button",className:e?"workbench-nav-toolbar-button workbench-collapsed-button":"workbench-nav-toolbar-button","aria-label":a("shell.hostSwitcherAriaLabel"),title:ke,"aria-expanded":t,onClick:()=>{n(Y=>!Y),i(!1),H(null)},children:s.jsx(qB,{})}),t&&K&&typeof document<"u"?Bs.createPortal(s.jsxs("div",{ref:te,className:"workbench-host-switcher-menu",style:K,role:"menu","aria-label":a("shell.hostSwitcherTitle"),children:[s.jsx("div",{className:"workbench-host-switcher-menu-header",children:s.jsx("strong",{children:a("shell.hostSwitcherTitle")})}),s.jsxs("div",{className:"workbench-host-switcher-list",children:[s.jsxs("section",{className:"workbench-host-switcher-section",children:[s.jsx("div",{className:"workbench-host-switcher-section-label",children:a("shell.hostSwitcherSavedSection")}),s.jsx("div",{className:"workbench-host-switcher-section-card",children:le.map(Y=>ce(Y,{statusText:Y.id===X?(ee==null?void 0:ee.user.username)??Y.lastUsername??Y.baseUrl:Y.lastUsername??Y.baseUrl,deletable:!0}))})]}),M.length>0?s.jsxs("section",{className:"workbench-host-switcher-section",children:[s.jsx("div",{className:"workbench-host-switcher-section-label",children:a("shell.hostSwitcherDiscoveredSection")}),s.jsx("div",{className:"workbench-host-switcher-section-card",children:M.map(Y=>{const Te=_k(Y.id),pe=Y.id===X?(ee==null?void 0:ee.user.username)??(Te==null?void 0:Te.username)??Y.baseUrl:(Te==null?void 0:Te.username)??Y.baseUrl;return ce(Y,{statusText:pe,discovered:!0})})})]}):null,V.localHostDiscovery.status==="refreshing"?s.jsx("div",{className:"workbench-host-switcher-state-row",children:a("shell.hostDiscoveryRefreshing")}):null,V.localHostDiscovery.status==="failed"?s.jsx("div",{className:"workbench-host-switcher-state-row","data-tone":"error",children:a("shell.hostDiscoveryFailed")}):null]}),r?s.jsxs("div",{className:"workbench-host-switcher-form",children:[s.jsxs("label",{className:"workbench-host-switcher-field",children:[s.jsx("span",{children:a("shell.hostSwitcherNameLabel")}),s.jsx("input",{value:o,disabled:_,onChange:Y=>l(Y.target.value),placeholder:a("shell.hostSwitcherNamePlaceholder")})]}),s.jsxs("label",{className:"workbench-host-switcher-field",children:[s.jsx("span",{children:a("shell.hostSwitcherUrlLabel")}),s.jsx("input",{value:c,disabled:_,onChange:Y=>u(Y.target.value),placeholder:a("shell.hostSwitcherUrlPlaceholder")})]}),s.jsxs("label",{className:"workbench-host-switcher-field",children:[s.jsx("span",{children:a("auth.username")}),s.jsx("input",{value:f,disabled:_,onChange:Y=>h(Y.target.value),autoComplete:"username"})]}),s.jsxs("label",{className:"workbench-host-switcher-field",children:[s.jsx("span",{children:a("auth.password")}),s.jsx("input",{type:"password",value:m,disabled:_,onChange:Y=>g(Y.target.value),autoComplete:"current-password"})]}),s.jsxs("div",{className:"workbench-host-switcher-form-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:_,onClick:()=>{i(!1),We()},children:a("common.cancel")}),s.jsx("button",{type:"button",className:"primary-button",disabled:_,onClick:()=>{Be()},children:_?a("common.loading"):a("shell.hostSwitcherSaveAction")})]})]}):s.jsxs("button",{type:"button",className:"workbench-host-switcher-add",onClick:()=>{i(!0),C(null)},children:[s.jsx(GB,{}),a("shell.hostSwitcherAddAction")]})]}),document.body):null]})}function Ty(e,t){return[...e].sort((n,r)=>{if(n.id===t)return-1;if(r.id===t)return 1;const i=n.lastConnectedAt??n.updatedAt??n.createdAt;return(r.lastConnectedAt??r.updatedAt??r.createdAt).localeCompare(i)})}function DB(e){try{const t=new URL(e),n=t.pathname==="/"?"":t.pathname.replace(/\/+$/,"");return`${t.host}${n}`}catch{return e}}function OB(e){try{const t=new URL(e).hostname.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"?"local":/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)?"lan":"remote"}catch{return"custom"}}function FB(e,t,n){var r;return!!(e.baseUrl===t||n&&((r=e.relayTunnel)==null?void 0:r.bindingId)===n)}function _B(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`host-${crypto.randomUUID()}`:`host-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function BB(e,t){return e instanceof Fh?e.code==="HOST_UNREACHABLE"?a("shell.hostSwitchUnreachable",{name:t}):a("shell.hostSwitchMissing"):a("shell.hostSwitchFailed")}function WB(e){return e.status==="probing"?a("shell.hostSwitcherDetailLatencyLoading"):e.status==="error"?a("shell.hostSwitcherDetailUnavailable"):e.status==="ready"?`${Math.max(1,Math.round(e.latencyMs))} ms`:a("shell.hostSwitcherDetailUnavailable")}function $B(e){return e.status==="loading"||e.status==="idle"?a("common.loading"):e.snapshot?a("shell.hostSwitcherDetailCpuValue",{usage:`${Math.max(0,Math.round(e.snapshot.cpu.usedRatio*100))}%`,cores:e.snapshot.cpu.logicalCoreCount}):a("shell.hostSwitcherDetailUnavailable")}function zB(e){return e.status==="loading"||e.status==="idle"?a("common.loading"):e.snapshot?`${wl(e.snapshot.memory.usedBytes)} / ${wl(e.snapshot.memory.totalBytes)}`:a("shell.hostSwitcherDetailUnavailable")}function HB(e){return e.status==="loading"||e.status==="idle"?a("common.loading"):e.snapshot?`${wl(e.snapshot.disk.freeBytes)} / ${wl(e.snapshot.disk.totalBytes)}`:a("shell.hostSwitcherDetailUnavailable")}function UB(e){if(e.status==="loading"||e.status==="idle")return[{key:"cpu",label:a("shell.hostSwitcherDetailCpuLabel"),summary:a("common.loading"),progressLabel:null,ratio:null,tone:"neutral",contrast:"dark",fillTextTone:"neutral-dark"},{key:"memory",label:a("shell.hostSwitcherDetailMemoryLabel"),summary:a("common.loading"),progressLabel:null,ratio:null,tone:"neutral",contrast:"dark",fillTextTone:"neutral-dark"},{key:"disk",label:a("shell.hostSwitcherDetailDiskLabel"),summary:a("common.loading"),progressLabel:null,ratio:null,tone:"neutral",contrast:"dark",fillTextTone:"neutral-dark"}];if(!e.snapshot)return[{key:"cpu",label:a("shell.hostSwitcherDetailCpuLabel"),summary:a("shell.hostSwitcherDetailUnavailable"),progressLabel:null,ratio:null,tone:"neutral",contrast:"dark",fillTextTone:"neutral-dark"},{key:"memory",label:a("shell.hostSwitcherDetailMemoryLabel"),summary:a("shell.hostSwitcherDetailUnavailable"),progressLabel:null,ratio:null,tone:"neutral",contrast:"dark",fillTextTone:"neutral-dark"},{key:"disk",label:a("shell.hostSwitcherDetailDiskLabel"),summary:a("shell.hostSwitcherDetailUnavailable"),progressLabel:null,ratio:null,tone:"neutral",contrast:"dark",fillTextTone:"neutral-dark"}];const t=hf(e.snapshot.cpu.usedRatio),n=hf(e.snapshot.memory.totalBytes>0?e.snapshot.memory.usedBytes/e.snapshot.memory.totalBytes:0),r=hf(e.snapshot.disk.totalBytes>0?e.snapshot.disk.freeBytes/e.snapshot.disk.totalBytes:0);return[{key:"cpu",label:a("shell.hostSwitcherDetailCpuLabel"),summary:$B(e),progressLabel:`${Math.round(t*100)}%`,ratio:t,tone:mf(t),contrast:pf(t),fillTextTone:gf("good",t)},{key:"memory",label:a("shell.hostSwitcherDetailMemoryLabel"),summary:zB(e),progressLabel:`${Math.round(n*100)}%`,ratio:n,tone:mf(n),contrast:pf(n),fillTextTone:gf(mf(n),n)},{key:"disk",label:a("shell.hostSwitcherDetailDiskLabel"),summary:HB(e),progressLabel:`${Math.round(r*100)}%`,ratio:r,tone:Iy(r),contrast:pf(r),fillTextTone:gf(Iy(r),r)}]}function hf(e){return!Number.isFinite(e)||e<=0?0:e>=1?1:e}function mf(e){return e>=.85?"danger":e>=.65?"warning":"good"}function Iy(e){return e<=.15?"danger":e<=.3?"warning":"good"}function pf(e){return e>=.58?"light":"dark"}function gf(e,t){return e==="danger"||t>=.72?"light":e==="warning"?"warning-dark":"neutral-dark"}function wl(e){return!Number.isFinite(e)||e<1024?`${Math.max(0,Math.round(e))} B`:e<1024**2?`${(e/1024).toFixed(1)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:e<1024**4?`${(e/1024**3).toFixed(1)} GB`:`${(e/1024**4).toFixed(1)} TB`}function qB(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[s.jsx("rect",{x:"4",y:"4.5",width:"16",height:"6.5",rx:"2.2",stroke:"currentColor",strokeWidth:"1.8"}),s.jsx("rect",{x:"4",y:"13",width:"16",height:"6.5",rx:"2.2",stroke:"currentColor",strokeWidth:"1.8"}),s.jsx("path",{d:"M11 7.75h5.5",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"}),s.jsx("path",{d:"M11 16.25h5.5",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"}),s.jsx("circle",{cx:"7.5",cy:"7.75",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"7.5",cy:"16.25",r:"1",fill:"currentColor",stroke:"none"})]})}function VB(){return s.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:s.jsx("path",{d:"M6 3.5L10.5 8 6 12.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.6"})})}function KB(){return s.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:s.jsx("path",{d:"M3.5 8.5L6.5 11.5L12.5 5.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8"})})}function GB(){return s.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:s.jsx("path",{d:"M8 3.5v9M3.5 8h9",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.6"})})}function YB(){return s.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:s.jsx("path",{d:"M3.5 4.5h9M6.5 2.75h3M5 4.5v7.25a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1V4.5M6.75 6.5v4M9.25 6.5v4",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.35"})})}function JB({checked:e,label:t,onChange:n,semanticRole:r="checkbox"}){return s.jsxs("label",{className:"settings-mobile-switch","aria-label":t,onClick:i=>{i.target instanceof HTMLInputElement||(i.preventDefault(),n(!e))},children:[s.jsx("input",{type:"checkbox",role:r,"aria-label":t,checked:e,onChange:i=>n(i.target.checked)}),s.jsx("span",{className:"settings-mobile-switch-track","aria-hidden":"true",children:s.jsx("span",{className:"settings-mobile-switch-thumb"})})]})}const Ay=1700;function mp({open:e,id:t,role:n="dialog",labelledBy:r,className:i,backdropClassName:o,anchorRef:l,popoverRef:c,children:u,maxWidth:f=360,gap:h=10,viewportPadding:m=16,showBackdrop:g=!1,onBackdropClick:p}){const[b,y]=d.useState(null);if(d.useEffect(()=>{if(!e||typeof window>"u"||typeof document>"u"){y(null);return}let k=0;const C=()=>{const H=l.current;if(!H)return;const _=H.getBoundingClientRect(),T=Math.max(180,Math.min(f,window.innerWidth-m*2)),P=Math.min(Math.max(m,_.right-T),Math.max(m,window.innerWidth-m-T)),z=_.top>=Math.min(240,window.innerHeight*.42),L=Math.round(z?_.top-h:_.bottom+h),R=z?_.top-h-m:window.innerHeight-_.bottom-h-m,K=Math.max(180,Math.floor(R));y({top:L,left:Math.round(P),width:T,placeAbove:z,maxHeight:K})},j=()=>{window.cancelAnimationFrame(k),k=window.requestAnimationFrame(C)};return C(),window.addEventListener("resize",j),window.addEventListener("scroll",j,!0),()=>{window.cancelAnimationFrame(k),window.removeEventListener("resize",j),window.removeEventListener("scroll",j,!0)}},[l,h,f,e,m]),!e||!b||typeof document>"u")return null;const x={position:"fixed",top:b.top,left:b.left,width:b.width,maxWidth:`calc(100vw - ${m*2}px)`,maxHeight:`${b.maxHeight}px`,zIndex:Ay,transform:b.placeAbove?"translateY(-100%)":void 0};return Bs.createPortal(s.jsxs(s.Fragment,{children:[g?s.jsx("button",{type:"button",className:o,"aria-hidden":"true",tabIndex:-1,onClick:p,style:{zIndex:Ay-1}}):null,s.jsx("div",{id:t,ref:c,role:n,"aria-labelledby":r,className:i,"data-placement":b.placeAbove?"top":"bottom",style:x,children:u})]}),document.body)}function kC({open:e,onClose:t,onImported:n,mode:r="import",title:i,description:o,submitLabel:l,initialPath:c,onSelectedPath:u}){const{showToast:f}=Vn(),[h,m]=d.useState(!1),[g,p]=d.useState(!1),[b,y]=d.useState(!1),[x,k]=d.useState(null),[C,j]=d.useState(""),[H,_]=d.useState(""),[T,P]=d.useState(null),[z,L]=d.useState([]),[R,K]=d.useState([]),[E,D]=d.useState(!1),[te,V]=d.useState(""),ee=h||g||b,U=d.useCallback(async de=>{m(!0),k(null);try{const Ne=await rw(de);j(Ne.currentPath),_(Ne.currentPath),P(Ne.parentPath),L(Ne.roots),K(Ne.items)}catch(Ne){j(""),P(null),K([]),k(Ne instanceof Error?Ne.message:a("shell.importBrowserBrowseFailed"))}finally{m(!1)}},[]);d.useEffect(()=>{if(!e){D(!1),V(""),k(null);return}U((c==null?void 0:c.trim())||C||void 0)},[C,c,U,e]);function he(){ee||(D(!1),V(""),t())}async function X(de){de.preventDefault(),await U(H)}function I(){!C||ee||(V(""),D(!0))}function xe(){g||(D(!1),V(""))}async function le(de){de==null||de.preventDefault();const Ne=te.trim();if(!(!C||!Ne||ee)){p(!0),k(null);try{const ye=await iw({parentPath:C,directoryName:Ne});f({title:a("shell.importBrowserCreateDirectorySuccess"),description:ye.path,tone:"success"}),D(!1),V(""),await U(ye.path)}catch(ye){const Be=ye instanceof Error?ye.message:a("shell.importBrowserCreateDirectoryFailed");k(Be),f({title:Be,tone:"error"})}finally{p(!1)}}}async function M(){const de=C.trim();if(!(!de||ee)){y(!0),k(null);try{if(r==="select-directory"){t(),Promise.resolve(u==null?void 0:u(de)).catch(ye=>{f({title:ye instanceof Error?ye.message:a("shell.importBrowserSelectDirectoryFailed"),tone:"error"})});return}const Ne=await HT({path:de});f({title:a("shell.importSuccess"),description:Ne.path,tone:"success"}),t(),Promise.resolve().then(()=>n==null?void 0:n(Ne)).catch(ye=>{f({title:ye instanceof Error?ye.message:a("shell.navigationLoadFailed"),tone:"error"})})}catch(Ne){f({title:Ne instanceof Error?Ne.message:a("shell.importFailed"),tone:"error"})}finally{y(!1)}}}return s.jsxs(s.Fragment,{children:[s.jsxs(ln,{open:e,title:i??(r==="select-directory"?a("shell.importBrowserSelectDirectoryTitle"):a("shell.importBrowserTitle")),description:o??(r==="select-directory"?a("shell.importBrowserSelectDirectoryDescription"):a("shell.importBrowserDescription")),onClose:he,children:[s.jsxs("form",{className:"workbench-directory-browser-form",onSubmit:X,children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.importBrowserCurrentPath")}),s.jsx("input",{type:"text",value:H,placeholder:a("shell.importPathPlaceholder"),onChange:de=>_(de.target.value)})]}),s.jsxs("div",{className:"workbench-directory-browser-toolbar",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:ee||!T,onClick:()=>{T&&U(T)},children:a("shell.importBrowserOpenParent")}),s.jsx("button",{type:"submit",className:"secondary-button",disabled:ee,children:a("shell.importBrowserOpenPath")}),s.jsx("button",{type:"button",className:"secondary-button",disabled:ee||!C,onClick:I,children:a("shell.importBrowserCreateDirectory")})]})]}),s.jsxs("section",{className:"workbench-directory-browser-panel",children:[s.jsxs("div",{className:"workbench-directory-browser-section",children:[s.jsx("span",{className:"workbench-directory-browser-section-title",children:a("shell.importBrowserRoots")}),s.jsx("div",{className:"workbench-directory-browser-root-list",children:z.map(de=>s.jsx("button",{type:"button",className:"workbench-directory-browser-chip",disabled:ee,onClick:()=>{U(de.path)},children:de.name},de.path))})]}),s.jsx("div",{className:"workbench-directory-browser-current-path",children:C}),x?s.jsx("p",{className:"workbench-directory-browser-status status-text","data-tone":"error",children:x}):null,h?s.jsx("p",{className:"workbench-directory-browser-status status-text",children:a("common.loading")}):R.length>0?s.jsx("div",{className:"workbench-directory-browser-list",children:R.map(de=>s.jsxs("button",{type:"button",className:"workbench-directory-browser-item",disabled:ee,onClick:()=>{U(de.path)},children:[s.jsx("span",{className:"workbench-directory-browser-item-name",children:de.name}),s.jsx("span",{className:"workbench-directory-browser-item-path",children:de.path})]},de.path))}):s.jsx("p",{className:"workbench-directory-browser-status status-text",children:a("shell.importBrowserEmpty")})]}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:ee,onClick:he,children:a("common.cancel")}),s.jsx("button",{type:"button",className:"primary-button",disabled:ee||!C,onClick:()=>{M()},children:b?a("shell.importSubmitting"):l??(r==="select-directory"?a("shell.importBrowserSelectDirectorySubmit"):a("shell.importBrowserSubmit"))})]})]}),s.jsx(ln,{open:e&&E,title:a("shell.importBrowserCreateDirectoryTitle"),description:a("shell.importBrowserCreateDirectoryDescription"),onClose:xe,children:s.jsxs("form",{className:"workbench-rename-form",onSubmit:de=>void le(de),children:[s.jsx("div",{className:"workbench-directory-browser-current-path",children:C}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.importBrowserCreateDirectoryLabel")}),s.jsx("input",{type:"text",value:te,placeholder:a("shell.importBrowserCreateDirectoryPlaceholder"),autoFocus:!0,onChange:de=>V(de.target.value)})]}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:g,onClick:xe,children:a("common.cancel")}),s.jsx("button",{type:"submit",className:"primary-button",disabled:g||!te.trim(),children:g?a("shell.importBrowserCreatingDirectory"):a("shell.importBrowserCreateDirectorySubmit")})]})]})})]})}const XB={displayName:"",providerId:"codex",agentsMode:"inline",personaTone:"direct",personaLanguage:"zh-CN",personaSummaryStyle:"brief",focusRiskPreference:"conservative",reportPriorityPreset:"risk-first"};function QB({form:e,onChange:t,submitting:n,submitLabel:r,previewName:i,previewAvatar:o,onSubmit:l,previewRuleLabel:c,affairsLibrary:u}){const[f,h]=d.useState(!1),[m,g]=d.useState((u==null?void 0:u.value.rootDir)??"");d.useEffect(()=>{g((u==null?void 0:u.value.rootDir)??"")},[u==null?void 0:u.value.rootDir]);const p=d.useMemo(()=>[{value:"inline",label:a("shell.butlerAgentsModeInline")},{value:"file",label:a("shell.butlerAgentsModeFile")}],[]),b=d.useMemo(()=>[{value:"direct",label:a("shell.butlerToneDirect")},{value:"steady",label:a("shell.butlerToneSteady")},{value:"friendly",label:a("shell.butlerToneFriendly")}],[]),y=d.useMemo(()=>[{value:"zh-CN",label:a("shell.butlerLanguageZhCn")},{value:"en-US",label:a("shell.butlerLanguageEnUs")},{value:"bilingual",label:a("shell.butlerLanguageBilingual")}],[]),x=d.useMemo(()=>[{value:"brief",label:a("shell.butlerSummaryBrief")},{value:"structured",label:a("shell.butlerSummaryStructured")},{value:"thorough",label:a("shell.butlerSummaryThorough")}],[]),k=d.useMemo(()=>[{value:"conservative",label:a("shell.butlerRiskConservative")},{value:"balanced",label:a("shell.butlerRiskBalanced")},{value:"proactive",label:a("shell.butlerRiskProactive")}],[]),C=d.useMemo(()=>[{value:"risk-first",label:a("shell.butlerReportRiskFirst")},{value:"blocker-first",label:a("shell.butlerReportBlockerFirst")},{value:"verification-first",label:a("shell.butlerReportVerificationFirst")},{value:"progress-first",label:a("shell.butlerReportProgressFirst")}],[]),j=Ta(p,e.agentsMode),H=Ta(b,e.personaTone),_=Ta(y,e.personaLanguage),T=Ta(x,e.personaSummaryStyle),P=Ta(k,e.focusRiskPreference),z=Ta(C,e.reportPriorityPreset),L=e.agentsMode==="inline"?a("shell.butlerAgentsModeInlineDescription"):a("shell.butlerAgentsModeFileDescription"),R=[j,_,P];function K(){u&&h(!0)}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"butler-init-backdrop","aria-hidden":"true",children:[s.jsx("span",{className:"butler-init-glow butler-init-glow-primary"}),s.jsx("span",{className:"butler-init-glow butler-init-glow-secondary"})]}),s.jsxs("div",{className:"butler-init-layout",children:[s.jsxs("aside",{className:"butler-init-sidebar",children:[s.jsx("section",{className:"butler-init-hero-card",children:s.jsxs("div",{className:"butler-init-hero-copy",children:[s.jsx("h1",{children:a("shell.butlerInitTitle")}),s.jsx("p",{children:a("shell.butlerInitDescription")})]})}),s.jsxs("section",{className:"butler-init-preview-card",children:[s.jsx("header",{className:"butler-init-section-header",children:s.jsx("div",{children:s.jsx("h2",{children:a("shell.butlerInitPreviewTitle")})})}),s.jsx("div",{className:"butler-init-preview-identity",children:s.jsxs("div",{className:"butler-init-preview-nameplate",children:[s.jsx("div",{className:"butler-chat-avatar butler-init-preview-avatar",children:s.jsx("span",{children:o})}),s.jsx("strong",{children:i})]})}),s.jsx("div",{className:"butler-init-chip-list",children:R.map(E=>s.jsx("span",{className:"butler-init-chip",children:E},E))}),s.jsxs("div",{className:"butler-init-preview-rows",children:[s.jsxs("div",{className:"butler-init-preview-row",children:[s.jsx("span",{children:a("shell.butlerPersonaToneLabel")}),s.jsx("strong",{children:H})]}),s.jsxs("div",{className:"butler-init-preview-row",children:[s.jsx("span",{children:c??a("shell.butlerInitPreviewRuleLabel")}),s.jsx("strong",{children:j})]}),s.jsxs("div",{className:"butler-init-preview-row",children:[s.jsx("span",{children:a("shell.butlerPersonaSummaryStyleLabel")}),s.jsx("strong",{children:T})]}),s.jsxs("div",{className:"butler-init-preview-row",children:[s.jsx("span",{children:a("shell.butlerReportPriorityPresetLabel")}),s.jsx("strong",{children:z})]}),u?s.jsxs("div",{className:"butler-init-preview-row",children:[s.jsx("span",{children:a("shell.affairsLibraryNav")}),s.jsx("strong",{children:u.value.enabled?a("shell.affairsLibraryEnabledState"):a("shell.affairsLibraryDisabledState")})]}):null]})]})]}),s.jsxs("form",{className:"butler-init-form",onSubmit:l,children:[s.jsxs("section",{className:"butler-init-form-section",children:[s.jsx("header",{className:"butler-init-section-header",children:s.jsx("div",{children:s.jsx("h2",{children:a("shell.butlerInitBasicsTitle")})})}),s.jsxs("div",{className:"butler-init-form-grid butler-init-basic-grid",children:[s.jsxs("label",{className:"butler-form-field",children:[s.jsx("span",{children:a("shell.butlerDisplayNameLabel")}),s.jsx("input",{className:"butler-form-control",value:e.displayName,onChange:E=>t(D=>({...D,displayName:E.target.value})),placeholder:a("shell.butlerDisplayNamePlaceholder")}),s.jsx("small",{children:a("shell.butlerDisplayNameHint")})]}),s.jsxs("label",{className:"butler-form-field butler-form-field-wide",children:[s.jsx("span",{children:a("shell.butlerAgentsModeLabel")}),s.jsx("select",{className:"butler-form-control",value:e.agentsMode,onChange:E=>t(D=>({...D,agentsMode:E.target.value})),children:p.map(E=>s.jsx("option",{value:E.value,children:E.label},E.value))}),s.jsx("small",{children:L})]})]})]}),s.jsxs("section",{className:"butler-init-form-section",children:[s.jsx("header",{className:"butler-init-section-header",children:s.jsx("div",{children:s.jsx("h2",{children:a("shell.butlerInitPersonaTitle")})})}),s.jsxs("div",{className:"butler-init-form-grid butler-init-persona-grid",children:[s.jsxs("label",{className:"butler-form-field",children:[s.jsx("span",{children:a("shell.butlerPersonaToneLabel")}),s.jsx("select",{className:"butler-form-control",value:e.personaTone,onChange:E=>t(D=>({...D,personaTone:E.target.value})),children:b.map(E=>s.jsx("option",{value:E.value,children:E.label},E.value))})]}),s.jsxs("label",{className:"butler-form-field",children:[s.jsx("span",{children:a("shell.butlerPersonaLanguageLabel")}),s.jsx("select",{className:"butler-form-control",value:e.personaLanguage,onChange:E=>t(D=>({...D,personaLanguage:E.target.value})),children:y.map(E=>s.jsx("option",{value:E.value,children:E.label},E.value))})]}),s.jsxs("label",{className:"butler-form-field",children:[s.jsx("span",{children:a("shell.butlerPersonaSummaryStyleLabel")}),s.jsx("select",{className:"butler-form-control",value:e.personaSummaryStyle,onChange:E=>t(D=>({...D,personaSummaryStyle:E.target.value})),children:x.map(E=>s.jsx("option",{value:E.value,children:E.label},E.value))})]})]})]}),s.jsxs("section",{className:"butler-init-form-section",children:[s.jsx("header",{className:"butler-init-section-header",children:s.jsx("div",{children:s.jsx("h2",{children:a("shell.butlerInitPreferenceTitle")})})}),s.jsxs("div",{className:"butler-init-form-grid butler-init-preferences-grid",children:[s.jsxs("label",{className:"butler-form-field",children:[s.jsx("span",{children:a("shell.butlerFocusRiskPreferenceLabel")}),s.jsx("select",{className:"butler-form-control",value:e.focusRiskPreference,onChange:E=>t(D=>({...D,focusRiskPreference:E.target.value})),children:k.map(E=>s.jsx("option",{value:E.value,children:E.label},E.value))})]}),s.jsxs("label",{className:"butler-form-field",children:[s.jsx("span",{children:a("shell.butlerReportPriorityPresetLabel")}),s.jsx("select",{className:"butler-form-control",value:e.reportPriorityPreset,onChange:E=>t(D=>({...D,reportPriorityPreset:E.target.value})),children:C.map(E=>s.jsx("option",{value:E.value,children:E.label},E.value))})]})]})]}),u?s.jsxs("section",{className:"butler-init-form-section",children:[s.jsx("header",{className:"butler-init-section-header",children:s.jsxs("div",{children:[s.jsx("h2",{children:a("shell.affairsInitLibraryTitle")}),s.jsx("p",{children:a("shell.affairsInitLibraryDescription")})]})}),s.jsxs("div",{className:"butler-init-basic-grid",children:[s.jsxs("label",{className:"butler-form-field butler-form-field-wide",children:[s.jsx("span",{children:a("shell.affairsInitLibraryEnabledLabel")}),s.jsxs("button",{type:"button",role:"switch","aria-checked":u.value.enabled,className:u.value.enabled?"butler-switch-field active":"butler-switch-field",onClick:()=>u.onChange({...u.value,enabled:!u.value.enabled}),children:[s.jsx("span",{className:"butler-switch-control","aria-hidden":"true",children:s.jsx("span",{className:"butler-switch-thumb"})}),s.jsxs("span",{className:"butler-switch-copy",children:[s.jsx("strong",{children:u.value.enabled?a("shell.affairsLibraryEnableAction"):a("shell.affairsLibraryDisableAction")}),s.jsx("small",{children:u.value.enabled?a("shell.affairsLibraryEnabledState"):a("shell.affairsLibraryDisabledState")})]})]}),s.jsx("small",{children:a("shell.affairsInitLibraryEnabledHint")})]}),u.value.enabled?s.jsxs("label",{className:"butler-form-field butler-form-field-wide",children:[s.jsx("span",{children:a("shell.affairsLibraryBindingFieldLabel")}),s.jsx("input",{className:"butler-form-control",value:m,onChange:E=>{const D=E.target.value;g(D),u.onChange({...u.value,rootDir:D})},placeholder:a("shell.affairsLibraryBindingFieldPlaceholder")}),s.jsx("small",{children:a("shell.affairsInitLibraryPathHint")})]}):null]}),u.value.enabled?s.jsx("div",{className:"butler-init-inline-actions",children:s.jsx("button",{type:"button",className:"secondary-button butler-library-pick-button",onClick:()=>{K()},children:a("shell.affairsLibraryBindingBrowseAction")})}):null]}):null,s.jsx("div",{className:"butler-init-actions",children:s.jsx("button",{className:"butler-init-submit",type:"submit",disabled:n,children:r})})]})]}),u?s.jsx(kC,{open:f,mode:"select-directory",title:a("shell.affairsLibraryBindingPickerTitle"),description:a("shell.affairsLibraryBindingPickerDescription"),submitLabel:a("shell.affairsLibraryBindingUseThisDirectory"),initialPath:m||null,onClose:()=>h(!1),onSelectedPath:async E=>{g(E),u.onChange({...u.value,rootDir:E}),h(!1)}}):null]})}function Ta(e,t){var n;return((n=e.find(r=>r.value===t))==null?void 0:n.label)??t}class ZB{constructor(t){ht(this,"socket",null);ht(this,"disposed",!1);ht(this,"authRecoveryInFlight",!1);ht(this,"latestCursor");ht(this,"subscribed",!1);ht(this,"pendingOlderRequest",null);ht(this,"inFlightOlderRequest",null);ht(this,"subscribeStartedAtMs",null);ht(this,"firstBackfillLogged",!1);ht(this,"olderRequestStartedAtMs",null);ht(this,"connectionManager");this.options=t,this.latestCursor=t.cursor,this.connectionManager=new Sw({onReconnect:n=>{this.connect(n)},onStateChange:t.onConnectionChange})}start(){this.connectionManager.start()}updateCursor(t){this.latestCursor=t}reconnectNow(){this.connectionManager.reconnectNow()}requestOlderMessages(t,n){return eW(this.socket)?this.subscribed?(this.sendOlderMessagesRequest(t,n),!0):(this.pendingOlderRequest={cursor:t,limit:n},!0):!1}close(){var t;this.disposed=!0,this.subscribed=!1,this.pendingOlderRequest=null,this.inFlightOlderRequest=null,this.connectionManager.close(),(t=this.socket)==null||t.close(),this.socket=null}connect(t){var u;if(this.disposed)return;t&&this.socket&&(this.socket.close(),this.socket=null);const n=(u=fa.getState().session)==null?void 0:u.accessToken;if(!n){this.options.onUnauthorized();return}const r=jl(),i=Fu(r),o=i.baseUrl,l=`${Dk("/ws",o)}?access_token=${encodeURIComponent(n)}`,c=i.transport.createWebSocket({path:"/ws",baseUrl:o,url:l});this.subscribed=!1,this.firstBackfillLogged=!1,this.socket=c,c.addEventListener("open",()=>{this.subscribeStartedAtMs=performance.now(),c.send(JSON.stringify({type:"session.subscribe",sessionId:this.options.sessionId,cursor:this.latestCursor,limit:this.options.limit})),Xt("session.subscribe.sent",{sessionId:this.options.sessionId,hasCursor:this.latestCursor!==null,limit:this.options.limit,baseUrl:o})}),c.addEventListener("message",f=>{if(!(f instanceof MessageEvent)||typeof f.data!="string")return;const h=JSON.parse(f.data);if(h.type==="system.connected"){this.connectionManager.markConnected();return}if(h.type==="session.subscribed"){this.subscribed=!0,Xt("session.subscribe.ack",{sessionId:h.sessionId,durationMs:bf(this.subscribeStartedAtMs)}),this.options.onSubscribed(),this.flushPendingOlderRequest();return}if(h.type==="session.error"){if(this.clearOlderMessagesRequest(),h.error_code==="UNAUTHORIZED"){this.handleUnauthorized();return}this.options.onError(h);return}if(h.type==="session.runtime_status"){this.options.onRuntimeStatus(h);return}if(h.type==="session.activity"){this.options.onActivity(h);return}if(h.type==="session.history_older"){Xt("session.history_older.received",{sessionId:h.sessionId,messageCount:h.messages.length,olderCursor:h.olderCursor,durationMs:bf(this.olderRequestStartedAtMs)}),this.olderRequestStartedAtMs=null,this.clearOlderMessagesRequest(),this.options.onOlderHistory(h);return}if(h.type==="session.runtime_message"){this.options.onRuntimeMessage(h);return}if(h.type==="session.runtime_error"){this.options.onRuntimeError(h);return}if(h.type==="session.interrupted"){this.options.onInterrupted(h);return}if(h.type==="session.permission_request"){this.options.onPermissionRequest(h);return}if(h.type==="session.permission_request_resolved"){this.options.onPermissionRequestResolved(h);return}this.latestCursor=h.cursor,this.firstBackfillLogged||(this.firstBackfillLogged=!0,Xt("session.initial_messages.received",{sessionId:h.sessionId,eventType:h.type,messageCount:h.messages.length,olderCursor:h.olderCursor??null,durationMs:bf(this.subscribeStartedAtMs)})),this.options.onEnvelope(h)}),c.addEventListener("close",()=>{this.disposed||this.socket!==c||(this.subscribed=!1,this.requeueInFlightOlderRequest(),this.connectionManager.markDisconnected())}),c.addEventListener("error",()=>{this.disposed||this.socket!==c||this.connectionManager.markTransientFailure()})}handleUnauthorized(){if(this.authRecoveryInFlight||this.disposed)return;this.authRecoveryInFlight=!0,this.subscribed=!1,this.requeueInFlightOlderRequest();const t=this.socket;this.socket=null,t==null||t.close(),fa.refresh().then(n=>{if(this.authRecoveryInFlight=!1,!this.disposed){if(n.status==="refreshed"){this.connectionManager.reconnectNow();return}if(n.status==="deferred"){this.connectionManager.markDisconnected();return}this.options.onUnauthorized()}})}sendOlderMessagesRequest(t,n){var r;this.inFlightOlderRequest={cursor:t,limit:n},this.olderRequestStartedAtMs=performance.now(),(r=this.socket)==null||r.send(JSON.stringify({type:"session.load_older",sessionId:this.options.sessionId,cursor:t,limit:n})),Xt("session.load_older.sent",{sessionId:this.options.sessionId,hasCursor:t!==null,limit:n})}flushPendingOlderRequest(){if(!this.pendingOlderRequest)return;const t=this.pendingOlderRequest;this.pendingOlderRequest=null,this.sendOlderMessagesRequest(t.cursor,t.limit)}clearOlderMessagesRequest(){this.pendingOlderRequest=null,this.inFlightOlderRequest=null}requeueInFlightOlderRequest(){this.inFlightOlderRequest&&(this.pendingOlderRequest=this.inFlightOlderRequest,this.inFlightOlderRequest=null,this.olderRequestStartedAtMs=null)}}function bf(e){return e===null||typeof performance>"u"?null:Math.round(performance.now()-e)}function eW(e){return e!==null&&e.readyState===1}function wC(){const e=Ga.getState().profile.defaultPermissionMode;return e==="default"?null:e}const yf=60,tW=400,vC="butler-diagnostic://",nW=15e3;class sW{constructor(t){ht(this,"state");ht(this,"listeners",new Set);ht(this,"realtimeClient",null);ht(this,"realtimeSessionId",null);ht(this,"selectedControlSessionId",null);ht(this,"controlSessionReloadInFlight",!1);ht(this,"terminalSyncTimer",null);ht(this,"terminalSyncArmed",!1);ht(this,"terminalSyncCompletedControlSessionId",null);ht(this,"pendingRunControlSession",null);ht(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));ht(this,"getState",()=>this.state);this.workspaceId=t,this.state={loading:!0,sending:!1,switchingProvider:!1,initialized:!1,affairsSetupCompleted:!1,profile:null,activeProvider:"codex",controlSession:null,capabilities:na("codex"),overview:null,events:[],messages:[],historyState:"idle",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,permissionRequests:[],error:null,bootstrapErrorCode:null}}dispose(){this.clearPendingRun(),this.teardownRealtime(),this.listeners.clear()}async initialize(){this.patch({loading:!0,error:null,bootstrapErrorCode:null});try{const t=await Qv();if(!t.initialized||!t.profile){this.clearPendingRun(),this.patch({loading:!1,initialized:!1,affairsSetupCompleted:!1,profile:null,activeProvider:"codex",capabilities:na("codex"),controlSession:null,messages:[],historyState:"idle",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,overview:null,events:[],runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,permissionRequests:[],bootstrapErrorCode:null});return}const n=t.profile;this.patch({initialized:!0,affairsSetupCompleted:t.affairsSetupCompleted??t.initialized,profile:n,activeProvider:n.providerId,capabilities:na(n.providerId),bootstrapErrorCode:null}),await this.reloadForProvider(n.providerId),this.patch({loading:!1})}catch(t){this.patch({loading:!1,error:Mr(t),bootstrapErrorCode:My(t)})}}async initializeProfile(t){this.patch({loading:!0,error:null,bootstrapErrorCode:null});try{const n=await yO(t);if(!n.initialized||!n.profile)throw new Error("BUTLER_PROFILE_INIT_FAILED");this.patch({initialized:!0,affairsSetupCompleted:n.affairsSetupCompleted??n.initialized,profile:n.profile,activeProvider:n.profile.providerId,capabilities:na(n.profile.providerId),bootstrapErrorCode:null}),await this.reloadForProvider(n.profile.providerId)}catch(n){throw this.patch({error:Mr(n),bootstrapErrorCode:My(n)}),n}finally{this.patch({loading:!1})}}async switchProvider(t){if(!this.state.initialized||!this.state.profile||this.state.activeProvider===t)return;const n={activeProvider:this.state.activeProvider,profile:this.state.profile,controlSession:this.state.controlSession,capabilities:this.state.capabilities,overview:this.state.overview,events:this.state.events,messages:this.state.messages,historyState:this.state.historyState,loadingOlderMessages:this.state.loadingOlderMessages,olderCursor:this.state.olderCursor,hasOlderMessages:this.state.hasOlderMessages,runtimeHasActiveRun:this.state.runtimeHasActiveRun,runtimeCanInterrupt:this.state.runtimeCanInterrupt,contextUsage:this.state.contextUsage};this.patch({switchingProvider:!0,error:null,activeProvider:t,controlSession:null,messages:[],historyState:"idle",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,overview:null,events:[],runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,capabilities:na(t)});try{const r=await $b({providerId:t});if(!r.initialized||!r.profile)throw new Error("BUTLER_PROFILE_UPDATE_FAILED");this.patch({initialized:!0,affairsSetupCompleted:r.affairsSetupCompleted??r.initialized,profile:r.profile,activeProvider:r.profile.providerId}),await Promise.all([this.refreshCapabilities(r.profile.providerId),this.refreshOverview(),this.refreshEvents()]),await this.startFreshSession({preserveSwitchingState:!0})}catch(r){throw this.patch({...n,error:Mr(r)}),r}finally{this.patch({switchingProvider:!1})}}async updateProfile(t){if(!(!this.state.initialized||!this.state.profile)){this.patch({loading:!0,error:null});try{const n=await $b(t);if(!n.initialized||!n.profile)throw new Error("BUTLER_PROFILE_UPDATE_FAILED");this.patch({initialized:!0,affairsSetupCompleted:n.affairsSetupCompleted??n.initialized,profile:n.profile,activeProvider:n.profile.providerId})}catch(n){throw this.patch({error:Mr(n)}),n}finally{this.patch({loading:!1})}}}async sendMessage(t,n){var i,o;const r=t.trim();if(!(!r||!this.state.initialized||!((i=this.workspaceId)!=null&&i.trim()))){this.patch({sending:!0,error:null});try{const l=this.state.controlSession,c=((o=this.state.capabilities)==null?void 0:o.supportsInterrupt)??!1,u=(n==null?void 0:n.permissionMode)??wC();if(l){const f=new Date().toISOString();this.patch({controlSession:{...l,status:"running",updatedAt:f,...l.session?{session:{...l.session,runningState:ai(l.session.runningState)?l.session.runningState:"starting",activitySource:"inferred",activityState:"running",lastEventAt:f,updatedAt:f}}:{}},runtimeHasActiveRun:!0,runtimeCanInterrupt:c})}if(l){const f=await SO({controlSessionId:l.id,content:r,model:(n==null?void 0:n.model)??null,reasoningLevel:(n==null?void 0:n.reasoningLevel)??null,permissionMode:u});this.selectedControlSessionId=f.controlSession.id,this.patch({controlSession:f.controlSession,runtimeHasActiveRun:!0,runtimeCanInterrupt:c})}else{const f=await vO({workspaceId:this.workspaceId,content:r,model:(n==null?void 0:n.model)??null,reasoningLevel:(n==null?void 0:n.reasoningLevel)??null,permissionMode:u});this.selectedControlSessionId=f.controlSession.id,this.patch({controlSession:f.controlSession,runtimeHasActiveRun:!0,runtimeCanInterrupt:c})}this.markPendingRun(this.selectedControlSessionId),await this.reloadControlSession(this.selectedControlSessionId),await Promise.all([this.refreshOverview(),this.refreshEvents()])}catch(l){throw this.patch({error:Mr(l)}),l}finally{this.patch({sending:!1})}}}async retryMessage(t){const n=this.state.messages.find(r=>r.clientRequestId===t);!n||!n.content.trim()||await this.sendMessage(n.content)}async interrupt(){var n,r;const t=((n=this.state.controlSession)==null?void 0:n.session.sessionId)??null;t&&(await R0(t),this.clearPendingRun(((r=this.state.controlSession)==null?void 0:r.id)??null),this.patch({runtimeHasActiveRun:!1,runtimeCanInterrupt:!1}))}async replyPermissionRequest(t,n){var l;const r=((l=this.state.controlSession)==null?void 0:l.session.sessionId)??null;if(!r||!(this.state.permissionRequests.find(c=>c.id===t)??null))return;const o=await P0(r,t,n);this.patch({permissionRequests:xf(this.state.permissionRequests,o)})}async startFreshSession(t){if(this.state.initialized){this.teardownRealtime(),this.selectedControlSessionId=null,this.clearPendingRun(),this.terminalSyncArmed=!1,this.terminalSyncCompletedControlSessionId=null,this.patch({sending:!1,error:null,controlSession:null,messages:[],historyState:"ready",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,permissionRequests:[]});try{await wO()}catch(n){throw this.patch({historyState:"error",error:Mr(n)}),n}this.patch({switchingProvider:t!=null&&t.preserveSwitchingState?this.state.switchingProvider:!1})}}async loadOlderMessages(){var r,i,o,l,c,u;const t=((r=this.state.controlSession)==null?void 0:r.id)??null,n=((i=this.state.controlSession)==null?void 0:i.session.sessionId)??null;if(!(!n||this.state.historyState!=="ready"||this.state.loadingOlderMessages||!this.state.olderCursor)){this.patch({loadingOlderMessages:!0,error:null});try{const f=await uu(n,this.state.olderCursor,yf,"backward");if(!t||((o=this.state.controlSession)==null?void 0:o.id)!==t||((l=this.state.controlSession)==null?void 0:l.session.sessionId)!==n){this.patch({loadingOlderMessages:!1});return}const h=Ry(this.state.messages,n,f.messages);this.patch({messages:kf(h,this.state.controlSession,{runningState:((c=this.state.controlSession)==null?void 0:c.session.runningState)??"idle",runtimeHasActiveRun:this.state.runtimeHasActiveRun??!1,runtimeCanInterrupt:this.state.runtimeCanInterrupt??!1,detail:null,errorDetail:this.state.error,updatedAt:((u=this.state.controlSession)==null?void 0:u.updatedAt)??new Date().toISOString()}),historyState:"ready",loadingOlderMessages:!1,olderCursor:f.nextCursor,hasOlderMessages:!!f.nextCursor})}catch(f){this.patch({loadingOlderMessages:!1,error:Mr(f)})}}}async refreshAll(){if(this.state.initialized){this.patch({loading:!0,error:null});try{await this.reloadForProvider(this.state.activeProvider)}finally{this.patch({loading:!1})}}}async reloadEventsAndOverview(){this.state.initialized&&await Promise.all([this.refreshOverview(),this.refreshEvents()])}async reloadForProvider(t){Xt("butler.runtime.reload_for_provider.start",{workspaceId:this.workspaceId,providerId:t,selectedControlSessionId:this.selectedControlSessionId}),await Promise.all([this.refreshCapabilities(t),this.refreshOverview(),this.refreshEvents()]),await this.reloadControlSession(this.selectedControlSessionId),Xt("butler.runtime.reload_for_provider.end",{workspaceId:this.workspaceId,providerId:t,selectedControlSessionId:this.selectedControlSessionId})}async openControlSession(t){this.selectedControlSessionId=t.trim()||null,await this.reloadControlSession(this.selectedControlSessionId)}async adoptControlSession(t){this.selectedControlSessionId=t.id,this.patch({controlSession:t}),await this.reloadControlSession(t.id)}async reloadControlSession(t){var i,o,l,c;const n=((i=this.state.controlSession)==null?void 0:i.id)??null,r=this.state.historyState==="ready"&&n!==null&&(t==null||t===n);Xt("butler.runtime.reload_control_session.start",{workspaceId:this.workspaceId,requestedControlSessionId:t??null,currentControlSessionId:n,currentSessionId:((l=(o=this.state.controlSession)==null?void 0:o.session)==null?void 0:l.sessionId)??null,currentMessages:this.state.messages.length,currentHistoryState:this.state.historyState,backgroundReload:r}),r||this.patch({historyState:"loading"});try{const f=(t?await kO(t):await xO(this.workspaceId)).controlSession;if(!f){this.selectedControlSessionId=null,this.clearPendingRun(),this.terminalSyncArmed=!1,this.terminalSyncCompletedControlSessionId=null,this.teardownRealtime(),this.patch({controlSession:null,messages:[],historyState:"ready",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,permissionRequests:[]}),Xt("butler.runtime.reload_control_session.empty",{workspaceId:this.workspaceId,requestedControlSessionId:t??null});return}this.selectedControlSessionId=f.id;const[h,m,g]=await Promise.all([uu(f.session.sessionId,null,yf,"backward"),A0(f.session.sessionId),ow(f.session.sessionId)]),p=this.resolvePendingRunControlSession(f,m),b=this.resolvePendingRunRuntimeState(p,m),y=m.hasActiveRun||m.canInterrupt||ai(m.runningState)||Ni(m.runningState);((c=this.state.controlSession)==null?void 0:c.id)!==f.id&&(this.terminalSyncCompletedControlSessionId=null),this.terminalSyncArmed=b.hasActiveRun||p.status==="running",y?(this.clearPendingRun(f.id),this.terminalSyncCompletedControlSessionId=null):this.terminalSyncArmed||(this.terminalSyncCompletedControlSessionId=f.id);const x=h.messages.map(k=>nd(f.session.sessionId,k));this.ensureRealtimeSubscription(f.session.sessionId,h.cursor),this.patch({controlSession:p,messages:kf(x,p,{runningState:m.runningState,runtimeHasActiveRun:b.hasActiveRun,runtimeCanInterrupt:b.canInterrupt,detail:m.detail,errorDetail:m.errorDetail,updatedAt:m.updatedAt}),historyState:"ready",loadingOlderMessages:!1,olderCursor:h.nextCursor,hasOlderMessages:!!h.nextCursor,runtimeHasActiveRun:b.hasActiveRun,runtimeCanInterrupt:b.canInterrupt,contextUsage:m.contextUsage,permissionRequests:g.items}),Xt("butler.runtime.reload_control_session.end",{workspaceId:this.workspaceId,controlSessionId:f.id,sessionId:f.session.sessionId,messages:x.length,historyState:"ready",hasActiveRun:b.hasActiveRun,canInterrupt:b.canInterrupt,terminalSyncArmed:this.terminalSyncArmed,terminalSyncCompletedControlSessionId:this.terminalSyncCompletedControlSessionId})}catch(u){this.patch({historyState:"error",error:Mr(u)}),Xt("butler.runtime.reload_control_session.error",{workspaceId:this.workspaceId,requestedControlSessionId:t??null,message:Mr(u)})}}async refreshCapabilities(t){var n;if(!((n=this.workspaceId)!=null&&n.trim())){this.patch({capabilities:na(t)});return}try{const r=await no(t,this.workspaceId);this.patch({capabilities:r})}catch{this.patch({capabilities:na(t)})}}async refreshOverview(){try{const t=await Zv();this.patch({overview:t.overview})}catch(t){this.patch({error:Mr(t)})}}async refreshEvents(){try{const t=await NO();this.patch({events:t.items})}catch(t){this.patch({error:Mr(t)})}}patch(t){this.state={...this.state,...t},this.emit()}emit(){for(const t of this.listeners)t()}ensureRealtimeSubscription(t,n){if(this.realtimeClient&&this.realtimeSessionId===t){this.realtimeClient.updateCursor(n),Xt("butler.runtime.realtime.reuse",{workspaceId:this.workspaceId,sessionId:t,cursor:n});return}this.teardownRealtime(),this.realtimeSessionId=t,Xt("butler.runtime.realtime.subscribe",{workspaceId:this.workspaceId,sessionId:t,cursor:n}),this.realtimeClient=new ZB({sessionId:t,cursor:n,limit:yf,onConnectionChange:()=>{},onSubscribed:()=>{},onEnvelope:r=>{this.handleRealtimeMessages(r.sessionId,r.messages)},onOlderHistory:r=>{this.handleRealtimeMessages(r.sessionId,r.messages)},onRuntimeMessage:r=>{this.handleRealtimeRuntimeMessage(r)},onActivity:r=>{this.handleRealtimeActivity(r)},onRuntimeStatus:r=>{this.handleRealtimeStatus(r)},onRuntimeError:r=>{this.handleRealtimeRuntimeError(r)},onInterrupted:r=>{this.handleRealtimeInterrupted(r)},onPermissionRequest:r=>{this.handlePermissionRequest(r)},onPermissionRequestResolved:r=>{this.handlePermissionRequestResolved(r)},onError:r=>{this.isActiveControlSession(r.sessionId??null)&&this.patch({error:r.detail})},onUnauthorized:()=>{this.patch({error:a("common.unauthorized")})}}),this.realtimeClient.start()}teardownRealtime(){var t;this.clearTerminalSyncTimer(),this.realtimeSessionId&&Xt("butler.runtime.realtime.teardown",{workspaceId:this.workspaceId,sessionId:this.realtimeSessionId}),(t=this.realtimeClient)==null||t.close(),this.realtimeClient=null,this.realtimeSessionId=null}clearTerminalSyncTimer(){this.terminalSyncTimer!==null&&(window.clearTimeout(this.terminalSyncTimer),this.terminalSyncTimer=null)}scheduleTerminalSessionSync(t,n){var r;this.clearTerminalSyncTimer(),Xt("butler.runtime.terminal_sync.scheduled",{workspaceId:this.workspaceId,controlSessionId:((r=this.state.controlSession)==null?void 0:r.id)??null,reason:t,...n}),this.terminalSyncTimer=window.setTimeout(()=>{var i,o,l;if(this.terminalSyncTimer=null,this.controlSessionReloadInFlight){Xt("butler.runtime.terminal_sync.skipped_inflight",{workspaceId:this.workspaceId,controlSessionId:((i=this.state.controlSession)==null?void 0:i.id)??null,reason:t,...n});return}this.controlSessionReloadInFlight=!0,this.terminalSyncCompletedControlSessionId=((o=this.state.controlSession)==null?void 0:o.id)??null,Xt("butler.runtime.terminal_sync.start",{workspaceId:this.workspaceId,controlSessionId:((l=this.state.controlSession)==null?void 0:l.id)??null,reason:t,...n}),this.reloadControlSession().finally(()=>{var c;this.controlSessionReloadInFlight=!1,Xt("butler.runtime.terminal_sync.end",{workspaceId:this.workspaceId,controlSessionId:((c=this.state.controlSession)==null?void 0:c.id)??null,reason:t,...n})})},tW)}handleRealtimeMessages(t,n){var i,o,l;if(!this.isActiveControlSession(t)){Xt("butler.runtime.realtime.messages.ignored",{workspaceId:this.workspaceId,sessionId:t,incoming:n.length,activeSessionId:((i=this.state.controlSession)==null?void 0:i.session.sessionId)??null});return}const r=Ry(this.state.messages,t,n);this.patch({messages:kf(r,this.state.controlSession,{runningState:((o=this.state.controlSession)==null?void 0:o.session.runningState)??"idle",runtimeHasActiveRun:this.state.runtimeHasActiveRun??!1,runtimeCanInterrupt:this.state.runtimeCanInterrupt??!1,detail:null,errorDetail:this.state.error,updatedAt:((l=this.state.controlSession)==null?void 0:l.updatedAt)??new Date().toISOString()}),historyState:"ready"}),this.promotePendingRunFromMessages(t,n),Xt("butler.runtime.realtime.messages",{workspaceId:this.workspaceId,sessionId:t,incoming:n.length,messages:r.length})}handleRealtimeRuntimeMessage(t){this.handleRealtimeMessages(t.sessionId,[t.message])}handleRealtimeActivity(t){var i;if(!this.isActiveControlSession(t.sessionId))return;t.hasActiveRun&&(this.terminalSyncArmed=!0,this.terminalSyncCompletedControlSessionId=null);const n=((i=this.state.controlSession)==null?void 0:i.id)??null,r=!t.hasActiveRun&&this.terminalSyncArmed&&n!==null&&this.terminalSyncCompletedControlSessionId!==n;Xt("butler.runtime.realtime.activity",{workspaceId:this.workspaceId,sessionId:t.sessionId,hasActiveRun:t.hasActiveRun,canInterrupt:t.canInterrupt,updatedAt:t.updatedAt,shouldSyncTerminalState:r,terminalSyncArmed:this.terminalSyncArmed,terminalSyncCompletedControlSessionId:this.terminalSyncCompletedControlSessionId}),this.patchActiveControlSessionRuntimeState({runningState:t.runningState,hasActiveRun:t.hasActiveRun,canInterrupt:t.canInterrupt,updatedAt:t.updatedAt}),r&&this.scheduleTerminalSessionSync("activity_terminal",{sessionId:t.sessionId,updatedAt:t.updatedAt})}handleRealtimeStatus(t){var l;if(!this.isActiveControlSession(t.sessionId))return;const n=t.status==="starting"||t.status==="running";n&&(this.terminalSyncArmed=!0,this.terminalSyncCompletedControlSessionId=null);const r=t.status==="completed"||t.status==="failed"||t.status==="interrupted",i=((l=this.state.controlSession)==null?void 0:l.id)??null,o=r&&!n&&this.terminalSyncArmed&&i!==null&&this.terminalSyncCompletedControlSessionId!==i;Xt("butler.runtime.realtime.status",{workspaceId:this.workspaceId,sessionId:t.sessionId,status:t.status,timestamp:t.timestamp,shouldSyncTerminalState:o,terminalSyncArmed:this.terminalSyncArmed,terminalSyncCompletedControlSessionId:this.terminalSyncCompletedControlSessionId}),this.patchActiveControlSessionRuntimeState({runningState:t.status,hasActiveRun:n,canInterrupt:n,updatedAt:t.timestamp}),o&&this.scheduleTerminalSessionSync("status_terminal",{sessionId:t.sessionId,status:t.status,timestamp:t.timestamp})}handleRealtimeRuntimeError(t){this.isActiveControlSession(t.sessionId)&&(Xt("butler.runtime.realtime.error",{workspaceId:this.workspaceId,sessionId:t.sessionId,detail:t.detail,errorCode:t.error_code}),this.patchActiveControlSessionRuntimeState({runningState:"failed",hasActiveRun:!1,canInterrupt:!1,updatedAt:t.timestamp,status:"failed",error:t.detail}),this.reloadControlSession())}handleRealtimeInterrupted(t){this.isActiveControlSession(t.sessionId)&&(Xt("butler.runtime.realtime.interrupted",{workspaceId:this.workspaceId,sessionId:t.sessionId,detail:t.detail}),this.patchActiveControlSessionRuntimeState({runningState:"interrupted",hasActiveRun:!1,canInterrupt:!1,updatedAt:t.timestamp,error:t.detail}),this.reloadControlSession())}handlePermissionRequest(t){this.isActiveControlSession(t.sessionId)&&this.patch({permissionRequests:xf(this.state.permissionRequests,t.request)})}handlePermissionRequestResolved(t){this.isActiveControlSession(t.sessionId)&&this.patch({permissionRequests:xf(this.state.permissionRequests,t.request)})}patchActiveControlSessionRuntimeState(t){var f;const n=this.state.controlSession;if(!n){this.patch({runtimeHasActiveRun:t.hasActiveRun,runtimeCanInterrupt:t.canInterrupt,...t.error!==void 0?{error:t.error}:{}});return}const r=n.session,i=r&&this.hasPendingRun(n.id)&&!t.hasActiveRun&&!t.canInterrupt&&!Ni(t.runningState)&&!Ni(r.runningState)&&n.status!=="failed"&&n.status!=="closed",o=i?ai(t.runningState)?t.runningState:ai(r.runningState)?r.runningState:"starting":t.runningState,l=i?!0:t.hasActiveRun,c=i?((f=this.state.capabilities)==null?void 0:f.supportsInterrupt)??this.state.runtimeCanInterrupt??t.canInterrupt:t.canInterrupt;i||this.clearPendingRun(n.id);const u=t.status??aW(n.status,o,l);if(!r){this.patch({controlSession:{...n,status:u,updatedAt:t.updatedAt},runtimeHasActiveRun:l,runtimeCanInterrupt:c,...t.error!==void 0?{error:t.error}:{}});return}this.patch({controlSession:{...n,status:u,updatedAt:t.updatedAt,session:{...r,runningState:o,activitySource:"runtime",activityState:oW(r.activityState,o,l),lastEventAt:t.updatedAt,updatedAt:t.updatedAt}},runtimeHasActiveRun:l,runtimeCanInterrupt:c,...t.error!==void 0?{error:t.error}:{}})}markPendingRun(t){t&&(this.pendingRunControlSession={controlSessionId:t,expiresAt:Date.now()+nW})}clearPendingRun(t){this.pendingRunControlSession&&(t==null||this.pendingRunControlSession.controlSessionId===t)&&(this.pendingRunControlSession=null)}hasPendingRun(t){return!t||!this.pendingRunControlSession||this.pendingRunControlSession.controlSessionId!==t?!1:this.pendingRunControlSession.expiresAt<=Date.now()?(this.pendingRunControlSession=null,!1):!0}resolvePendingRunControlSession(t,n){if(!this.hasPendingRun(t.id))return t;if(n.hasActiveRun||ai(n.runningState)||Ni(n.runningState)||ai(t.session.runningState)||Ni(t.session.runningState)||t.status==="failed"||t.status==="closed")return this.clearPendingRun(t.id),t;const r=n.updatedAt||t.updatedAt||new Date().toISOString();return{...t,status:"running",updatedAt:r,session:{...t.session,runningState:"starting",activitySource:"inferred",activityState:"running",lastEventAt:r,updatedAt:r}}}resolvePendingRunRuntimeState(t,n){var r;return this.hasPendingRun(t.id)?n.hasActiveRun||n.canInterrupt||Ni(n.runningState)||Ni(t.session.runningState)||t.status==="failed"||t.status==="closed"?{hasActiveRun:n.hasActiveRun,canInterrupt:n.canInterrupt}:ai(n.runningState)||ai(t.session.runningState)||t.status==="running"?{hasActiveRun:!0,canInterrupt:((r=this.state.capabilities)==null?void 0:r.supportsInterrupt)??n.canInterrupt}:{hasActiveRun:n.hasActiveRun,canInterrupt:n.canInterrupt}:{hasActiveRun:n.hasActiveRun,canInterrupt:n.canInterrupt}}promotePendingRunFromMessages(t,n){var o;const r=this.state.controlSession;if(!r||r.session.sessionId!==t||!this.hasPendingRun(r.id)||this.state.runtimeHasActiveRun===!0||ai(r.session.runningState)||Ni(r.session.runningState)||n.length===0)return;const i=((o=n.at(-1))==null?void 0:o.timestamp)??new Date().toISOString();this.patch({controlSession:{...r,status:"running",updatedAt:i,session:{...r.session,runningState:"running",activitySource:"inferred",activityState:"running",lastEventAt:i,updatedAt:i}}})}isActiveControlSession(t){var n;return!!(t&&((n=this.state.controlSession)==null?void 0:n.session.sessionId)===t)}}function Zt(e,t){const[n,r]=d.useState(()=>t(e.getState()));return d.useEffect(()=>(r(t(e.getState())),e.subscribe(()=>{r(t(e.getState()))})),[t,e]),n}function na(e){const t=[{id:"provider-default",name:a("conversation.modelUseCliDefault"),usesProviderDefault:!0}];return{provider:e,canStartSession:!0,canResumeSession:!0,canSendMessage:!0,inRunInputMode:e==="claude-code"?"streaming_guidance":"none",supportsSubagents:!1,supportsInterrupt:!0,supportsStructuredToolCalls:!0,supportsTokenUsage:!0,supportsAttachments:!1,supportsPermissionPrompt:!0,supportsCheckpoint:!1,supportsQueueWhileRunning:!1,supportsRunSteering:!1,supportsSlashMenu:!1,supportsReasoningSelector:!0,modelOptions:t,defaultReasoningLevel:null,limitations:[]}}function Ry(e,t,n){const r=new Map;for(const i of e.filter(o=>!SC(o)))r.set(Py(i),i);for(const i of n){const o=nd(t,i);r.set(Py(o),o)}return[...r.values()].sort((i,o)=>i.sequence!==o.sequence?i.sequence-o.sequence:i.timestamp.localeCompare(o.timestamp))}function Py(e){return e.id||e.rawRef}function xf(e,t){const n=e.filter(r=>r.id!==t.id);return n.push(t),n.sort((r,i)=>r.status!==i.status?r.status==="pending"?-1:1:i.createdAt.localeCompare(r.createdAt)),n}function kf(e,t,n){const r=e.filter(o=>!SC(o));if(r.length>0||!t)return r;const i=rW(t,n);return i?[...r,iW(t,i,n.updatedAt)]:r}function rW(e,t){var c,u,f;if(t.runtimeHasActiveRun)return null;const n=t.runningState,r=e.status==="failed"||n==="failed";if(!(r||n==="completed"||n==="interrupted"||n==="idle"&&e.status!=="running"))return null;const o=((c=e.lastSummary)==null?void 0:c.trim())||((u=t.errorDetail)==null?void 0:u.trim())||((f=t.detail)==null?void 0:f.trim())||null,l=[r?"本轮助手会话已结束,但没有收到可展示的助手消息。":"本轮助手会话已结束,但 provider 没有返回可展示的助手消息。"];return o&&(l.push(""),l.push(`诊断信息:${o}`)),l.join(`
74
+ `)}function iW(e,t,n){const r=Number.isFinite(e.session.messageCount)?e.session.messageCount:0;return{id:`butler-diagnostic-${e.id}`,sessionId:e.session.sessionId,role:"system",kind:"text",content:t,toolCall:null,attachments:[],attachmentPayloads:null,origin:"system",originRef:e.id,timestamp:n??e.updatedAt,sequence:r+1,rawRef:`${vC}${e.id}`,deliveryState:"sent",clientRequestId:null}}function SC(e){return e.rawRef.startsWith(vC)}function Mr(e){return e instanceof Error?e.message:String(e)}function My(e){return mT(e)||pT(e)||e instanceof rr?e.errorCode:null}function aW(e,t,n){return n||t==="starting"||t==="running"||t==="reconnecting"?"running":t==="failed"?"failed":e==="closed"?"closed":"idle"}function oW(e,t,n){return n||t==="starting"||t==="running"||t==="reconnecting"?"running":t==="completed"||t==="interrupted"||t==="failed"?"completed_unread":e==="running"?"idle":e}function ai(e){return e==="starting"||e==="running"||e==="reconnecting"}function Ni(e){return e==="completed"||e==="failed"||e==="interrupted"}function wf(e,t){if(!e)return{allowed:!1,hidden:!1,reason:a("conversation.capabilityDenied")};switch(t){case"send_message":return e.canSendMessage===!1?{allowed:!1,hidden:!1,reason:a("conversation.capabilitySendDisabled")}:{allowed:!0,hidden:!1,reason:null};case"attachments":return e.supportsAttachments?{allowed:!0,hidden:!1,reason:null}:{allowed:!1,hidden:!1,reason:a("conversation.capabilityAttachmentDisabled")};case"interrupt":return e.supportsInterrupt?{allowed:!0,hidden:!1,reason:null}:{allowed:!1,hidden:!1,reason:a("conversation.capabilityInterruptDisabled")};default:return{allowed:!1,hidden:!1,reason:a("conversation.capabilityDenied")}}}async function Bh(){return await ae.request("/api/system/model-switch")}async function wK(e){return await ae.request("/api/system/model-switch",{method:"POST",body:JSON.stringify(e)})}const Cc=12,Ti=16,lW=640,vf=180;function cW({provider:e,messages:t,variant:n="header"}){const[r,i]=d.useState(!1),[o,l]=d.useState(null),c=d.useId(),u=d.useRef(null),f=d.useRef(null),h=d.useMemo(()=>i2(t,e),[t,e]);if(d.useLayoutEffect(()=>{if(!r)return;function x(){const k=u.current;if(!k)return;const C=k.getBoundingClientRect(),j=window.innerWidth,H=window.innerHeight,_=Math.min(lW,Math.max(280,j-Ti*2)),P=C.left+C.width/2-_/2,z=uW(P,Ti,Math.max(Ti,j-_-Ti));if(n==="header"){l({left:z,width:_,top:Math.min(C.bottom+Cc,H-vf-Ti),maxHeight:Math.max(vf,H-C.bottom-Cc-Ti)});return}l({left:z,width:_,bottom:Math.max(Ti,H-C.top+Cc),maxHeight:Math.max(vf,C.top-Cc-Ti)})}return x(),window.addEventListener("resize",x),window.addEventListener("scroll",x,!0),()=>{window.removeEventListener("resize",x),window.removeEventListener("scroll",x,!0)}},[r,n]),d.useEffect(()=>{if(!r)return;function x(C){const j=u.current,H=f.current,_=C.target;_ instanceof Node&&(j!=null&&j.contains(_)||H!=null&&H.contains(_)||i(!1))}function k(C){C.key==="Escape"&&i(!1)}return document.addEventListener("pointerdown",x),document.addEventListener("keydown",k),()=>{document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",k)}},[r]),!h||h.items.length===0)return null;const m=lS(h.items),g=m.in_progress||m.pending,p=g>0?g:h.items.length,b=n==="composer"?"conversation-task-progress-button composer-task-progress-button":"conversation-header-ai-button conversation-task-progress-button",y=r&&o?Bs.createPortal(s.jsx("div",{id:c,ref:f,className:"conversation-task-progress-popover",role:"region","aria-label":a("conversation.taskProgressModalTitle"),style:{left:o.left,width:o.width,maxHeight:o.maxHeight,top:o.top,bottom:o.bottom},children:s.jsx(fS,{snapshot:h,className:"conversation-task-progress-popover-card"})}),document.body):null;return s.jsxs("div",{className:"conversation-task-progress-entry","data-variant":n,ref:u,children:[s.jsxs("button",{type:"button",className:b,"data-variant":n,"aria-label":a("conversation.taskProgressButton",{count:h.items.length}),"aria-expanded":r,"aria-controls":r?c:void 0,title:a("conversation.taskProgressButton",{count:h.items.length}),onClick:()=>{i(x=>!x)},children:[s.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:s.jsx(k2,{})}),s.jsx("span",{className:"conversation-task-progress-badge",children:p})]}),y]})}function uW(e,t,n){return Math.min(Math.max(e,t),n)}const CC=144,dW=196,fW=124,hW=72;let Ey=null;function mW(e,t){if(typeof document>"u")return t.length*8;Ey??(Ey=document.createElement("canvas"));const n=Ey.getContext("2d");if(!n)return t.length*8;const r=window.getComputedStyle(e),i=r.fontStyle||"normal",o=r.fontWeight||"600",l=r.fontSize||"13px",c=r.fontFamily||"system-ui";return n.font=`${i} ${o} ${l} ${c}`,n.measureText(t).width}function pW({labels:e,triggerWidth:t,maxWidth:n,preferredWidth:r,measureText:i}){const o=e.reduce((l,c)=>Math.max(l,Math.ceil(i(c)+hW)),0);return Math.min(n,Math.max(t,CC,r,o))}function Ha({triggerId:e,ariaLabel:t,value:n,options:r,onChange:i,disabled:o=!1,compact:l=!1,className:c}){const[u,f]=d.useState(!1),h=d.useRef(null),m=d.useRef(null),g=d.useRef(null),[p,b]=d.useState(null),y=d.useId(),x=r.find(j=>j.value===n)??r[0]??null,k=d.useMemo(()=>r.map(j=>j.label),[r]),C=d.useCallback(()=>{const j=m.current;if(!j||typeof window>"u")return;const H=j.getBoundingClientRect(),_=window.innerWidth,T=window.innerHeight,P=12,z=10,L=Math.max(CC,_-P*2),R=l?fW:dW,K=pW({labels:k,triggerWidth:H.width,maxWidth:L,preferredWidth:R,measureText:ee=>mW(j,ee)}),E=Math.min(Math.max(P,H.left),Math.max(P,_-K-P)),D=H.top-P,te=T-H.bottom-P,V=D>=180||D>=te;b({position:"fixed",left:E,width:K,maxWidth:L,zIndex:1905,top:V?void 0:H.bottom+z,bottom:V?T-H.top+z:void 0})},[l,k]);return d.useEffect(()=>{if(!u)return;function j(_){var P,z;const T=_.target;!((P=h.current)!=null&&P.contains(T))&&!((z=g.current)!=null&&z.contains(T))&&f(!1)}function H(_){_.key==="Escape"&&f(!1)}return window.addEventListener("pointerdown",j),window.addEventListener("keydown",H),window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),C(),()=>{window.removeEventListener("pointerdown",j),window.removeEventListener("keydown",H),window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0)}},[u,C]),x?s.jsxs("div",{ref:h,className:`composer-mac-select ${l?"is-compact":""}${c?` ${c}`:""}`,"data-open":u?"true":"false",children:[s.jsxs("button",{id:e,ref:m,type:"button",className:"composer-mac-select-trigger","aria-label":t,"aria-haspopup":"listbox","aria-expanded":u,"aria-controls":y,disabled:o,onClick:()=>f(j=>!j),children:[s.jsx("span",{className:"composer-mac-select-label",children:x.label}),s.jsx("svg",{className:"composer-mac-select-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:s.jsx("polyline",{points:"6 14 12 8 18 14"})})]}),u&&p&&typeof document<"u"?Bs.createPortal(s.jsx("div",{ref:g,className:"composer-mac-select-popover",style:p,role:"presentation",children:s.jsx("div",{id:y,className:"composer-mac-select-list",role:"listbox","aria-label":t,children:r.map(j=>{const H=j.value===n;return s.jsxs("button",{type:"button",role:"option","aria-selected":H,className:`composer-mac-select-option ${H?"is-selected":""}`,onClick:()=>{i(j.value),f(!1)},children:[s.jsx("span",{className:"composer-mac-select-option-check","aria-hidden":"true",children:H?"✓":""}),s.jsx("span",{className:"composer-mac-select-option-label",children:j.label})]},j.value)})})}),document.body):null]}):null}const di="provider-default",Dr="__global_default__";function Pi(e){switch(e){case"claude-code":case"codex":case"gemini":return e;default:return null}}function ci(e,t){const n=(t==null?void 0:t.trim())||null;return e==="cc-switch-preset"&&n?{providerConfigMode:"cc-switch-preset",providerPresetId:n}:{providerConfigMode:"global-default",providerPresetId:null}}function Wh(e){const t=e!=null&&e.currentPresetName?e.currentModel?`${e.currentPresetName} · ${e.currentModel}`:e.currentPresetName:null;return[{value:Dr,label:a("conversation.deploymentDefaultPreset"),summary:t},...((e==null?void 0:e.options)??[]).map(n=>({value:n.id,label:n.name,summary:n.model??n.summary??null}))]}function qo(e){return e.usesProviderDefault===!0||e.id===di}function $h(e){return e?e.cliAvailable===!0&&e.status!=="unavailable"&&e.options.length>1:!0}function zh({triggerId:e,ariaLabel:t,triggerLabel:n,presetOptions:r,selectedPresetValue:i,selectedPresetSummary:o,onSelectPreset:l,modelOptions:c,selectedModelValue:u,onSelectModel:f,loadingPresets:h=!1,loadingModels:m=!1,modelColumnDisabled:g=!1,showPresetColumn:p=!0,modelEmptyText:b}){const[y,x]=d.useState(!1),k=d.useRef(null),C=d.useRef(null),j=d.useRef(null),[H,_]=d.useState(null),T=d.useId(),P=d.useCallback(()=>{const z=C.current;if(!z||typeof window>"u")return;const L=z.getBoundingClientRect(),R=z.closest(".workbench-modal-card"),K=R instanceof HTMLElement?R.getBoundingClientRect():null,E=window.innerWidth,D=window.innerHeight,te=12,V=8,ee=320,U=Math.min(560,Math.max(320,E-te*2)),he=Math.min(U,420),X=Math.max(Math.min(U,Math.max(he,Math.round(L.width*1.9))),Math.min(320,U)),I=Math.min(Math.max(te,L.left),Math.max(te,E-X-te)),xe=K?Math.max(te,K.top+8):te,le=K?Math.min(D-te,K.bottom-8):D-te,M=Math.max(0,L.top-xe-V),de=Math.max(0,le-L.bottom-V),Ne=K?!(de>=ee||de>M+40):M>=240||M>=de;_({position:"fixed",left:I,width:X,maxWidth:U,zIndex:1905,top:Ne?void 0:L.bottom+V,bottom:Ne?D-L.top+V:void 0})},[]);return d.useEffect(()=>{if(!y)return;function z(R){var E,D;const K=R.target;!((E=k.current)!=null&&E.contains(K))&&!((D=j.current)!=null&&D.contains(K))&&x(!1)}function L(R){R.key==="Escape"&&x(!1)}return window.addEventListener("pointerdown",z),window.addEventListener("keydown",L),window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),P(),()=>{window.removeEventListener("pointerdown",z),window.removeEventListener("keydown",L),window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[y,P]),s.jsxs("div",{ref:k,className:"composer-mac-select composer-deployment-select","data-open":y?"true":"false",children:[s.jsxs("button",{id:e,ref:C,type:"button",className:"composer-mac-select-trigger composer-deployment-select-trigger","aria-label":t,"aria-haspopup":"dialog","aria-expanded":y,"aria-controls":T,onClick:()=>x(z=>!z),children:[s.jsx("span",{className:"composer-mac-select-label composer-deployment-select-label",children:n}),s.jsx("svg",{className:"composer-mac-select-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:s.jsx("polyline",{points:"6 14 12 8 18 14"})})]}),y&&H&&typeof document<"u"?Bs.createPortal(s.jsx("div",{ref:j,className:"composer-mac-select-popover composer-deployment-select-popover",style:H,role:"presentation",children:s.jsxs("div",{id:T,className:`composer-deployment-select-panel${p?"":" is-model-only"}`,role:"dialog","aria-label":t,children:[p?s.jsxs("div",{className:"composer-deployment-select-column",children:[s.jsx("div",{className:"composer-deployment-select-column-header",children:a("conversation.deploymentConfigColumn")}),s.jsxs("div",{className:"composer-deployment-select-list",role:"listbox","aria-label":a("conversation.deploymentConfigColumn"),children:[r.map(z=>{const L=z.value===i;return s.jsxs("button",{type:"button",role:"option","aria-selected":L,className:`composer-deployment-select-option ${L?"is-selected":""}`,onClick:()=>l(z.value),children:[s.jsx("span",{className:"composer-deployment-select-option-check","aria-hidden":"true",children:L?"✓":""}),s.jsxs("span",{className:"composer-deployment-select-option-copy",children:[s.jsx("span",{className:"composer-deployment-select-option-label",children:z.label}),z.summary?s.jsx("span",{className:"composer-deployment-select-option-summary",children:z.summary}):null]})]},z.value)}),h?s.jsx("div",{className:"composer-deployment-select-state",children:a("conversation.deploymentLoading")}):null]})]}):null,s.jsxs("div",{className:"composer-deployment-select-column","data-disabled":g?"true":"false",children:[s.jsx("div",{className:"composer-deployment-select-column-header",children:a("conversation.deploymentModelColumn")}),p&&o?s.jsx("div",{className:"composer-deployment-select-column-hint",children:o}):null,s.jsx("div",{className:"composer-deployment-select-list",role:"listbox","aria-label":a("conversation.deploymentModelColumn"),children:m&&g?s.jsx("div",{className:"composer-deployment-select-state",children:a("conversation.deploymentModelLoading")}):c.length>0?c.map(z=>{const L=z.value===u;return s.jsxs("button",{type:"button",role:"option","aria-selected":L,className:`composer-deployment-select-option ${L?"is-selected":""}`,disabled:g,onClick:()=>{f(z.value),x(!1)},children:[s.jsx("span",{className:"composer-deployment-select-option-check","aria-hidden":"true",children:L?"✓":""}),s.jsx("span",{className:"composer-deployment-select-option-copy",children:s.jsx("span",{className:"composer-deployment-select-option-label",children:z.label})})]},z.value)}):s.jsx("div",{className:"composer-deployment-select-state",children:b})})]})]})}),document.body):null]})}const gW="codingns.conversation.composer-draft:",bW=1,yW=[{id:"builtin-stage-and-summarize",text:"请将本次会话变更的所有代码提交到git暂存区,然后总结一条中文的提交信息"},{id:"builtin-review-module",text:"分析本项目 模块的代码实现,并分析存在的问题"},{id:"builtin-group-commits",text:"分析当前项目中的未提交文件,按照功能模块进行分类提交,提交信息格式请参考我最近的提交记录"}];function pp(){return typeof window<"u"&&typeof window.localStorage<"u"}function xW(e){if(!e||typeof e!="object")return null;const t="id"in e?e.id:null,n="fileName"in e?e.fileName:null,r="mimeType"in e?e.mimeType:null,i="fileSize"in e?e.fileSize:null,o="lastModified"in e?e.lastModified:null,l="contentBase64"in e?e.contentBase64:null;if(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof i!="number"||typeof o!="number"||typeof l!="string")return null;const c=t.trim(),u=n.trim(),f=r.trim(),h=l.trim();return!c||!u||!f||i<0||o<0||!h?null:{id:c,fileName:u,mimeType:f,fileSize:i,lastModified:o,contentBase64:h}}function kW(e){if(!e||typeof e!="object")return null;const t="content"in e?e.content:null,n="attachments"in e?e.attachments:null;if(typeof t!="string"||!Array.isArray(n))return null;const r=n.map(i=>xW(i)).filter(i=>i!==null);return r.length!==n.length||t.length===0&&r.length===0?null:{content:t,attachments:r}}function sl(e){return`${gW}${e}`}function wW(e){var t,n;return{id:((n=(t=globalThis.crypto)==null?void 0:t.randomUUID)==null?void 0:n.call(t))??`phrase-${Date.now()}-${Math.random().toString(16).slice(2)}`,text:e.trim()}}function vW(e){if(!pp())return null;const t=e.trim();if(!t)return null;const n=window.localStorage.getItem(sl(t));if(!n)return null;try{const r=JSON.parse(n),i=r&&typeof r=="object"&&"draft"in r&&r.draft&&typeof r.draft=="object"?r.draft:r,o=kW(i);return o||(window.localStorage.removeItem(sl(t)),null)}catch{return window.localStorage.removeItem(sl(t)),null}}function SW(e,t){if(!pp())return!1;const n=e.trim();if(!n)return!1;if(t.content.length===0&&t.attachments.length===0)return jC(n),!0;try{return window.localStorage.setItem(sl(n),JSON.stringify({schemaVersion:bW,draft:t})),!0}catch{return!1}}function jC(e){if(!pp())return;const t=e.trim();t&&window.localStorage.removeItem(sl(t))}const CW=5;async function jW(e){var l,c;const t=Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):CW,n=((l=e.keyword)==null?void 0:l.trim())??"",r=NW(e.provider),[i,o]=await Promise.all([ch(),(c=e.workspaceId)!=null&&c.trim()?K0(e.workspaceId.trim(),{limit:t,keyword:n}):Promise.resolve({items:[]})]);return{skills:TW({keyword:n,limit:t,targetCli:r,managedSkills:i.managedSkills,assistantRuntimeSkills:i.assistantRuntimeSkills}),files:o.items.slice(0,t)}}function NW(e){const t=e==null?void 0:e.trim();return t&&(t==="claude-code"||t==="codex"||t==="gemini"||t==="opencode")?t:null}function TW(e){const t=e.keyword.toLowerCase(),n=i=>t.length===0||i.toLowerCase().includes(t),r=[];for(const i of e.managedSkills){const o=i.bindings.filter(l=>l.enabled).map(l=>l.targetCli);e.targetCli&&!o.includes(e.targetCli)||!n(i.skill.name)&&!n(i.skill.directoryName)||r.push({id:i.skill.id,name:i.skill.name,source:"managed",targetCli:o,description:Ly(o)})}for(const i of e.assistantRuntimeSkills)e.targetCli&&!i.usedByTargetCli.includes(e.targetCli)||!n(i.name)&&!n(i.directoryName)||r.push({id:`assistant-runtime:${i.directoryName}`,name:i.name,source:"assistant-runtime",targetCli:i.usedByTargetCli,description:Ly(i.usedByTargetCli)});return r.sort((i,o)=>i.name.localeCompare(o.name)),r.slice(0,e.limit)}function Ly(e){return e.length===0?"当前还没有可用目标":`适用于 ${e.join("、")}`}const Dy="workbench:focus-composer",IW=["codex","claude-code","opencode","gemini","kimi"],AW=new Set(["codex","claude-code","opencode"]),RW=new Set(["codex","claude-code","opencode"]),Oy={position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Ia=new Map;function PW(e){return[{id:di,name:a("conversation.modelUseCliDefault"),provider:e,usesProviderDefault:!0}]}function Fy(e){return PW(e)}function MW(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`${Date.now()}-${Math.random().toString(16).slice(2)}`}function _y(e){if(e){e.value="";try{const t=e.showPicker;if(typeof t=="function"){t.call(e);return}}catch{}e.click()}}function EW(e,t,n,r){const i=globalThis.atob(n),o=Uint8Array.from(i,l=>l.charCodeAt(0));return new File([o],e,{type:t,lastModified:r})}function LW(e){return e.trim().toLowerCase().startsWith("image/")}function rl(e){const t=e.type.trim().toLowerCase();return t.length>0?t:"application/octet-stream"}function NC(e){return LW(rl(e))?"image":"file"}function TC(e,t=MW()){const n=NC(e);return{id:t,file:e,kind:n,previewUrl:n==="image"?URL.createObjectURL(e):null}}function DW(e){const t=EW(e.fileName,e.mimeType,e.contentBase64,e.lastModified);return TC(t,e.id)}function OW(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function FW(e){const t=e.trim().replace(/\s+/g," ");return t.length===0?a("conversation.forkDraftEmpty"):t.length>140?`${t.slice(0,140)}…`:t}function _W(e){const t=e.match(/(?:^|\s)@([^\s@]*)$/);return t?t[1]??"":null}function BW(e,t){return e.replace(/@([^\s@]*)$/,`${t} `)}function WW(e){return{id:`skill:${e.id}`,type:"skill",name:e.name,subtitle:e.description,insertText:`@skill:${e.name}`}}function $W(e){return{id:`file:${e.path}`,type:"file",name:e.name,subtitle:e.path,insertText:`@file:${e.path}`}}function zW(e){return Array.from(e.matchAll(/@(skill|file):([^\s]+)/g)).map((n,r)=>{const i=n[1]==="skill"?"skill":"file",o=n[2]??"",l=n[0]??"";return{id:`${i}:${o}:${r}`,type:i,label:o,token:l}})}function By(e){const t=zW(e).map(r=>({...r,id:IC(r.type,r.label)})),n=e.replace(/@(skill|file):([^\s]+)/g," ").replace(/[ \t]+\n/g,`
75
+ `).replace(/\n[ \t]+/g,`
76
+ `).replace(/[ \t]{2,}/g," ").trim();return{selections:t,plainText:n}}function Wy(e,t){const n=e.map(i=>i.token).join(" ").trim(),r=t.trim();return n&&r?`${n}
77
+ ${r}`:n||r}function IC(e,t){return`${e}:${t}:${Date.now()}:${Math.random().toString(16).slice(2)}`}function HW(e,t){return t===e?RW.has(t)?null:a("conversation.forkProviderNativeUnsupported"):AW.has(t)?null:a("conversation.forkProviderReconstructedUnsupported")}function AC(e){return(e==null?void 0:e.canStartSession)===!1}function UW(e){return AC(e)?(e==null?void 0:e.limitations[0])??a("conversation.capabilityDenied"):null}function qW(e,t){return{id:t,kind:NC(e),fileName:e.name,mimeType:rl(e),fileSize:e.size}}function $y(e){return new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>{n(r.error??new Error("FILE_READ_FAILED"))},r.onload=()=>{const i=typeof r.result=="string"?r.result:"",o=i.includes(",")?i.split(",").at(-1)??"":i;t(o)},r.readAsDataURL(e)})}function VW(e){e.forEach(t=>{t.previewUrl&&URL.revokeObjectURL(t.previewUrl)})}function KW(e,t){const n=new Set(e.map(i=>`${i.file.name}:${i.file.size}:${i.file.lastModified}`)),r=[...e];return t.forEach(i=>{const o=`${i.name}:${i.size}:${i.lastModified}`;n.has(o)||(n.add(o),r.push(TC(i)))}),r}function GW(e,t,n){const r=e.nativeEvent;return r.isComposing||r.keyCode===229||t||n}function id({capabilities:e,placeholder:t,draftStorageId:n,initialModel:r=null,workspaceId:i=null,initialProviderConfigMode:o="global-default",initialProviderPresetId:l=null,forkDraft:c=null,onClearForkDraft:u,onForkDraftChange:f,panelRef:h,portalContainer:m=null,hasActiveRun:g=null,canInterrupt:p=null,contextUsage:b=null,taskProvider:y=null,taskMessages:x=[],hasPendingQueuedMessages:k=!1,isSubmitting:C,isRunning:j=!1,onInterrupt:H,onQueueSend:_,onSend:T}){const P=Hn(),z=d.useId(),L=d.useId(),[R,K]=d.useState(""),[E,D]=d.useState([]),[te,V]=d.useState(""),[ee,U]=d.useState("medium"),[he,X]=d.useState([]),[I,xe]=d.useState(!1),[le,M]=d.useState(!1),[de,Ne]=d.useState(yW),[ye,Be]=d.useState(!1),[We,Ce]=d.useState(!1),[ke,we]=d.useState(""),[se,ce]=d.useState(!1),[Y,Te]=d.useState(!1),[pe,fe]=d.useState(!1),[W,Me]=d.useState([]),[je,Q]=d.useState(!1),[ge,Oe]=d.useState(0),[$e,Ve]=d.useState(!1),[G,ve]=d.useState(!1),[_e,nt]=d.useState(null),[et,ot]=d.useState(!1),[jt,Ft]=d.useState(null),[bt,_t]=d.useState(!1),xt=d.useMemo(()=>ci(o,l),[o,l]),[rt,It]=d.useState(xt.providerConfigMode),[$t,pt]=d.useState(xt.providerPresetId),Ie=d.useMemo(()=>ci(rt,$t),[rt,$t]),[kt,St]=d.useState(null),[vt,Ct]=d.useState(!1),[J,Ue]=d.useState(null),[ze,st]=d.useState(!1),[q,re]=d.useState("global-default"),[ue,Re]=d.useState(null),[Se,Ke]=d.useState({}),[De,He]=d.useState(null),lt=d.useRef(null),wt=d.useRef(null),it=d.useRef(null),Ze=d.useRef(null),Ht=d.useRef(!1),gt=d.useRef(!1),Nt=d.useRef(!1),dt=d.useRef(null),ft=d.useRef(new Set),en=d.useRef(new Map),cn=d.useRef(0),qt=d.useRef(null),Cn=d.useRef(0),{showToast:Bt}=Vn(),is=Tl(),{revealWorkspaceFile:Ws}=Wp(),fn=d.useCallback(()=>{dt.current!==null&&(globalThis.clearTimeout(dt.current),dt.current=null),Nt.current=!1},[]);d.useEffect(()=>fn,[fn]);const mt=(e==null?void 0:e.provider)??y??BA(e),O=Pi(mt),Ae=gT(w=>Cd(mt)?w.profile.providers[mt]:null),Xe=(Ae==null?void 0:Ae.defaultModel)??null,Qt=(Ae==null?void 0:Ae.defaultReasoningLevel)??null;d.useEffect(()=>{const w=ci(o,l);It(w.providerConfigMode),pt(w.providerPresetId)},[n,o,l,mt]),d.useEffect(()=>{if(!c){re("global-default"),Re(null);return}if(Pi(c.targetProvider)){const w=ci(c.targetProviderConfigMode,c.targetProviderPresetId);re(w.providerConfigMode),Re(w.providerPresetId);return}re("global-default"),Re(null)},[c]),d.useEffect(()=>{if(!O){nt(null),ot(!1);return}const w=Ia.get(O)??null;w&&nt(w);let F=!1;return ot(!w),Bh().then(Z=>{Z.items.forEach(be=>{Ia.set(be.app,be)}),F||nt(Ia.get(O)??null)}).catch(()=>{!F&&!w&&nt(null)}).finally(()=>{F||ot(!1)}),()=>{F=!0}},[O]),d.useEffect(()=>{const w=c?Pi(c.targetProvider):null;if(!w){Ue(null),st(!1);return}const F=Ia.get(w)??null;F&&Ue(F);let Z=!1;return st(!F),Bh().then(be=>{be.items.forEach(Ee=>{Ia.set(Ee.app,Ee)}),Z||Ue(Ia.get(w)??null)}).catch(()=>{!Z&&!F&&Ue(null)}).finally(()=>{Z||st(!1)}),()=>{Z=!0}},[c]),d.useEffect(()=>{if(rt==="cc-switch-preset"){if(!$t){It("global-default");return}_e&&!_e.options.some(w=>w.id===$t)&&(It("global-default"),pt(null))}},[_e,rt,$t]),d.useEffect(()=>{if(rt!=="cc-switch-preset"||!$t||!(i!=null&&i.trim())){Ft(null),_t(!1);return}let w=!1;return _t(!0),no(mt,i,{providerConfigMode:"cc-switch-preset",providerPresetId:$t}).then(F=>{w||Ft(F)}).catch(()=>{w||Ft(null)}).finally(()=>{w||_t(!1)}),()=>{w=!0}},[mt,rt,$t,i]),d.useEffect(()=>{if(!(!c||q!=="cc-switch-preset")){if(!ue){re("global-default");return}J&&!J.options.some(w=>w.id===ue)&&(re("global-default"),Re(null))}},[J,c,q,ue]);const Un=d.useMemo(()=>wf(e,"send_message"),[e]),as=d.useMemo(()=>wf(e,"interrupt"),[e]),tn=d.useMemo(()=>wf(e,"attachments"),[e]),sn=d.useMemo(()=>rt!=="cc-switch-preset"?e:jt??e,[e,jt,rt]),At=d.useMemo(()=>{var F;const w=(F=sn==null?void 0:sn.modelOptions)==null?void 0:F.map(Z=>{var be;return{...Z,provider:mt,supportedReasoningEfforts:(be=Z.supportedReasoningEfforts)==null?void 0:be.filter(Ee=>Ee==="low"||Ee==="medium"||Ee==="high"||Ee==="xhigh")}});return w!=null&&w.length?w:Fy(mt)},[sn==null?void 0:sn.modelOptions,mt]),Gt=d.useMemo(()=>Wh(_e),[_e]),Zn=rt==="cc-switch-preset"?$t??Dr:Dr,es=d.useMemo(()=>Gt.find(w=>w.value===Zn)??Gt[0]??null,[Gt,Zn]),os=d.useMemo(()=>At.find(w=>w.id===te)??null,[At,te]),ut=$A(e),Ds=WA(e),cr=d.useMemo(()=>[{value:"low",label:a("conversation.reasoningLow")},{value:"medium",label:a("conversation.reasoningMedium")},{value:"high",label:a("conversation.reasoningHigh")},{value:"xhigh",label:a("conversation.reasoningMaximum")}],[]),jn=d.useMemo(()=>{if(!ut)return[];const w=os==null?void 0:os.supportedReasoningEfforts;return!w||w.length===0?cr:cr.filter(F=>w.includes(F.value))},[ut,cr,os==null?void 0:os.supportedReasoningEfforts]),an=d.useMemo(()=>At.map(w=>({value:w.id,label:qo(w)?a("conversation.modelUseCliDefault"):w.name})),[At]),hs=d.useMemo(()=>$h(_e),[_e]),ur=d.useMemo(()=>{const w=os?qo(os)?a("conversation.modelUseCliDefault"):os.name:a("conversation.modelUseCliDefault");return hs?`${(es==null?void 0:es.label)??a("conversation.deploymentDefaultPreset")} · ${w}`:w},[os,es,hs]),ts=d.useMemo(()=>jn.map(w=>({value:w.value,label:w.label})),[jn]),Dn=d.useMemo(()=>[{command:"/plan",label:a("conversation.slashCommandPlan")},{command:"/review",label:a("conversation.slashCommandReview")},{command:"/explain",label:a("conversation.slashCommandExplain")}],[]),Kn=(e==null?void 0:e.provider)??y??null,Rn=(e==null?void 0:e.inRunInputMode)??"none",Nn=!!c,{visibleProviders:ks}=fp(IW,Nn),xn=(c==null?void 0:c.targetProvider)??null,$s=Pi(xn),Vt=d.useMemo(()=>ci(q,ue),[q,ue]),nn=!!c&&(e==null?void 0:e.provider)===xn&&Ie.providerConfigMode===Vt.providerConfigMode&&Ie.providerPresetId===Vt.providerPresetId,ns=d.useMemo(()=>c?nn?e:kt??Ja(c.targetProvider):null,[e,kt,c,nn]),ss=d.useMemo(()=>{var F;if(!c)return[];const w=(F=ns==null?void 0:ns.modelOptions)==null?void 0:F.map(Z=>{var be;return{...Z,provider:c.targetProvider,supportedReasoningEfforts:(be=Z.supportedReasoningEfforts)==null?void 0:be.filter(Ee=>Ee==="low"||Ee==="medium"||Ee==="high"||Ee==="xhigh")}});return w!=null&&w.length?w:Fy(c.targetProvider)},[ns==null?void 0:ns.modelOptions,c]),Ts=d.useMemo(()=>ss.map(w=>({value:w.id,label:qo(w)?a("conversation.modelUseCliDefault"):w.name})),[ss]),Xs=d.useMemo(()=>!c||!c.targetModel?di:ss.some(w=>w.id===c.targetModel)?c.targetModel:di,[ss,c]),ls=d.useMemo(()=>Wh(J),[J]),zs=Vt.providerConfigMode==="cc-switch-preset"?Vt.providerPresetId??Dr:Dr,ms=d.useMemo(()=>ls.find(w=>w.value===zs)??ls[0]??null,[ls,zs]),ps=d.useMemo(()=>ss.find(w=>w.id===Xs)??null,[ss,Xs]),ws=d.useMemo(()=>$h(J),[J]),On=d.useMemo(()=>{const w=ps?qo(ps)?a("conversation.modelUseCliDefault"):ps.name:a("conversation.modelUseCliDefault");return ws?`${(ms==null?void 0:ms.label)??a("conversation.deploymentDefaultPreset")} · ${w}`:w},[ps,ms,ws]),vs=d.useMemo(()=>c?ks.filter(w=>HW(c.sourceProvider,w)!==null?!1:!AC(Se[w]??null)):[],[c,Se,ks]),Ss=d.useMemo(()=>c?vs.length>0?vs:[c.targetProvider]:[],[c,vs]),Wn=d.useMemo(()=>Ss.map(w=>({value:w,label:Ui(w,"full")})),[Ss]),Gn=d.useMemo(()=>c?UW(Se[c.targetProvider]??ns??null):null,[ns,c,Se]),cs=g??null,Rt=j||cs===!0,Yn=Rt&&Rn==="streaming_guidance"&&cs===!1&&!HA(e),Mt=!Nn&&Rt&&Rn==="streaming_guidance"&&!Yn,A=!Nn&&Rt&&typeof _=="function"&&zA(e,cs),ie=!Nn&&Rt&&!Mt&&!A,tt=Nn&&!!Gn,Pt=R.trim().length>0||he.length>0,zt=p===!1&&cs===!0?as.allowed:p??as.allowed,pn=Rt&&zt&&!!H&&!$e,Os=!Pt&&(G||C||Rt||k),Tn=pn?a("conversation.capabilityInterrupt"):a("conversation.runtimeRunning"),Qs=Rt?A?a("conversation.queueGuidanceButton"):Mt?a("conversation.sendGuidanceButton"):a("conversation.sendButton"):a("conversation.sendButton"),Pn=d.useCallback(w=>{V(w),Cd(mt)&&Vp({providers:{[mt]:{defaultModel:w}}}).catch(()=>{})},[mt]),on=d.useCallback(w=>{if(w==="__global_default__"){It("global-default"),pt(null);return}It("cc-switch-preset"),pt(w)},[]),Sn=d.useCallback(w=>{U(w),Cd(mt)&&Vp({providers:{[mt]:{defaultReasoningLevel:w}}}).catch(()=>{})},[mt]),gn=d.useCallback(w=>{ft.current.forEach(F=>{URL.revokeObjectURL(F)}),ft.current.clear(),w.forEach(F=>{F.previewUrl&&ft.current.add(F.previewUrl)}),X(w)},[]),bn=d.useCallback(w=>{w.length!==0&&X(F=>{const Z=KW(F,w);return Z.forEach(be=>{be.previewUrl&&ft.current.add(be.previewUrl)}),Z})},[]),Cs=d.useCallback(w=>{en.current.delete(w),X(F=>{const Z=F.find(be=>be.id===w);return Z!=null&&Z.previewUrl&&(ft.current.delete(Z.previewUrl),URL.revokeObjectURL(Z.previewUrl)),F.filter(be=>be.id!==w)})},[]),js=d.useCallback(w=>{const F=Array.from(w.target.files??[]);F.length>0&&bn(F),w.target.value=""},[bn]),Ge=d.useCallback(w=>{var Z;P.isMobile||!tn.allowed||ie||!((((Z=w.dataTransfer.files)==null?void 0:Z.length)??0)>0||Array.from(w.dataTransfer.items??[]).some(be=>be.kind==="file"))||(w.preventDefault(),w.dataTransfer.dropEffect="copy",le||M(!0),Te(!1))},[tn.allowed,le,ie,P.isMobile]),ei=d.useCallback(w=>{const F=w.relatedTarget;F instanceof Node&&w.currentTarget.contains(F)||M(!1)},[]),Mn=d.useCallback(w=>{if(P.isMobile||!tn.allowed||ie)return;const F=Array.from(w.dataTransfer.files??[]);F.length!==0&&(w.preventDefault(),M(!1),bn(F))},[tn.allowed,ie,bn,P.isMobile]),Hs=d.useCallback(w=>{if(!tn.allowed||ie)return;const F=w==="camera"?Ze.current:it.current;_y(F),xe(!1)},[tn.allowed,ie]),ir=d.useCallback(()=>{if(!(!tn.allowed||ie)){if(Te(!1),P.isNativeMobile){is.trigger("selection"),xe(!0);return}_y(it.current)}},[tn.allowed,is,ie,P.isNativeMobile]),Is=d.useCallback(()=>{fe(!1),Q(!1),Oe(0)},[]),Zs=d.useCallback(async w=>{const F=Cn.current+1;Cn.current=F,Q(!0);try{const Z=await jW({workspaceId:i,provider:Kn,keyword:w,limit:5});if(Cn.current!==F)return;const be=Z.skills.map(Je=>WW(Je)),Ee=Z.files.map(Je=>$W(Je));Me([...be,...Ee]),Oe(0),fe(!0)}catch{if(Cn.current!==F)return;Me([]),Oe(0),fe(!0)}finally{Cn.current===F&&Q(!1)}},[Kn,i]),yn=d.useCallback(w=>{D(F=>[...F,{id:IC(w.type,w.name),type:w.type,label:w.name,token:w.insertText}]),K(F=>BW(F,"").trimStart()),Is(),globalThis.requestAnimationFrame(()=>{var F;(F=lt.current)==null||F.focus()})},[Is]);d.useEffect(()=>{const w=_W(R);if(w===null){Is(),Me([]);return}if(!(i!=null&&i.trim())&&w.length>0){Me([]),fe(!0),Q(!1);return}Zs(w)},[Is,R,Zs,i]),d.useEffect(()=>{if(W.length===0){Oe(0);return}Oe(w=>Math.min(w,W.length-1))},[W]),d.useEffect(()=>{if(!pe||W.length===0)return;const w=wt.current;if(!w)return;const F=w.querySelector(".composer-mention-item.is-active");if(!F)return;const Z=w.scrollTop,be=Z+w.clientHeight,Ee=F.offsetTop,Je=Ee+F.offsetHeight;if(Ee<Z){w.scrollTop=Ee;return}Je>be&&(w.scrollTop=Je-w.clientHeight)},[ge,W,pe]);const Us=d.useCallback(()=>{Te(w=>!w)},[]),qs=d.useCallback(w=>{var F;K(Z=>Z.trimStart().startsWith(w)?Z:Z.trim()?`${w} ${Z.trim()}`:`${w} `),Te(!1),(F=lt.current)==null||F.focus()},[]),us=d.useCallback(async w=>{const F=de;cn.current+=1,Ne(w),ce(!0);try{const Z=await y0(w.map(be=>({id:be.id,text:be.text})));return Ne(Z.items.map(be=>({id:be.id,text:be.text}))),!0}catch(Z){return Ne(F),Bt({title:Z instanceof Error?Z.message:a("conversation.quickPhraseSaveFailed"),tone:"error"}),!1}finally{ce(!1)}},[de,Bt]),kr=d.useCallback(async()=>{const w=ke.trim();!w||!await us([...de,wW(w)])||(we(""),Ce(!1))},[us,ke,de]),$r=d.useCallback(w=>{us(de.filter(F=>F.id!==w))},[us,de]),pi=d.useCallback((w,F)=>{const Z=de.findIndex(Et=>Et.id===w);if(Z<0)return;const be=Z+F;if(be<0||be>=de.length)return;const Ee=[...de],[Je]=Ee.splice(Z,1);Ee.splice(be,0,Je),us(Ee)},[us,de]),ti=d.useCallback(w=>{var F;K(w),Be(!1),(F=lt.current)==null||F.focus()},[]),gi=d.useCallback(w=>{D(F=>F.filter(Z=>Z.id!==w)),globalThis.requestAnimationFrame(()=>{var F;(F=lt.current)==null||F.focus()})},[]),En=d.useCallback(w=>{if(w.type==="file"){Ws({workspaceId:i,filePath:w.label,openViewer:!1});return}K(F=>{const Z=F.trim();return Z.length>0?`${Z} ${w.label}`:w.label}),globalThis.requestAnimationFrame(()=>{var F;(F=lt.current)==null||F.focus()})},[Ws,i]),dr=d.useCallback(w=>{const F=w?vW(w):null,Z=(F==null?void 0:F.attachments.map(Ee=>DW(Ee)))??[],be=By((F==null?void 0:F.content)??"");en.current=new Map(((F==null?void 0:F.attachments)??[]).map(Ee=>[Ee.id,Ee])),gn(Z),D(be.selections),K(be.plainText),Te(!1)},[gn]);d.useEffect(()=>{const w=By(R);w.selections.length!==0&&(D(F=>[...F,...w.selections]),K(w.plainText))},[R]),d.useEffect(()=>{if(!At.length)return;const w=(r==null?void 0:r.trim())||null,F=`${n??"default"}:${mt}:${w??""}`;if(!!(w&&At.some(Ee=>Ee.id===w))){if(qt.current!==F){qt.current=F,te!==w&&V(w);return}if(At.some(Ee=>Ee.id===te))return;V(w);return}if(!w&&qt.current!==F&&(qt.current=F),Xe&&At.some(Ee=>Ee.id===Xe)){te!==Xe&&V(Xe);return}if(At.some(Ee=>Ee.id===te))return;const be=At[0].id;V(be)},[At,n,mt,te,Xe,r]),d.useEffect(()=>{if(!UA(mt)||jn.length===0)return;if(Qt&&jn.some(Z=>Z.value===Qt)){ee!==Qt&&U(Qt);return}const w=e==null?void 0:e.defaultReasoningLevel;if(w&&jn.some(Z=>Z.value===w)){ee!==w&&U(w);return}if(jn.some(Z=>Z.value===ee))return;const F=jn[0].value;U(F)},[jn,e==null?void 0:e.defaultReasoningLevel,mt,ee,Qt]),d.useEffect(()=>{let w=!1;const F=cn.current;return b0().then(Z=>{w||cn.current!==F||Ne(Z.items.map(be=>({id:be.id,text:be.text})))}).catch(()=>{}),()=>{w=!0}},[]),d.useEffect(()=>{dr(n)},[n,dr]),d.useEffect(()=>{if(!n)return;const w=n,F=new Set(he.map(Ee=>Ee.id));en.current.forEach((Ee,Je)=>{F.has(Je)||en.current.delete(Je)});let Z=!1;async function be(){if(R.length===0&&he.length===0&&E.length===0){jC(w);return}const Ee=await Promise.all(he.map(async Je=>{const Et=en.current.get(Je.id);return Et&&Et.fileName===Je.file.name&&Et.fileSize===Je.file.size&&Et.lastModified===Je.file.lastModified&&Et.mimeType===rl(Je.file)?Et:{id:Je.id,fileName:Je.file.name,mimeType:rl(Je.file),fileSize:Je.file.size,lastModified:Je.file.lastModified,contentBase64:await $y(Je.file)}}));Z||(en.current=new Map(Ee.map(Je=>[Je.id,Je])),SW(w,{content:Wy(E,R),attachments:Ee}))}return be(),()=>{Z=!0}},[he,R,n,E]),d.useEffect(()=>{const w=lt.current;w&&(w.style.height="0px",w.style.height=`${Math.min(w.scrollHeight,120)}px`)},[R]),d.useEffect(()=>{tn.allowed||(en.current.clear(),xe(!1),gn([]))},[tn.allowed,gn]),d.useEffect(()=>{P.isMobile||xe(!1)},[P.isMobile]),d.useEffect(()=>()=>{ft.current.forEach(w=>{URL.revokeObjectURL(w)}),ft.current.clear()},[]),d.useEffect(()=>{function w(){var F;(F=lt.current)==null||F.focus()}return window.addEventListener(Dy,w),()=>{window.removeEventListener(Dy,w)}},[]),d.useEffect(()=>{if(!c){St(null),Ct(!1),Ue(null),st(!1),Ke({}),He(null);return}if(nn){St(null),Ct(!1);return}let w=!1;return St(Ja(c.targetProvider)),Ct(!0),no(c.targetProvider,c.workspaceId,{providerConfigMode:Vt.providerConfigMode,providerPresetId:Vt.providerConfigMode==="cc-switch-preset"?Vt.providerPresetId:null}).then(F=>{w||St(F)}).catch(()=>{w||St(Ja(c.targetProvider))}).finally(()=>{w||Ct(!1)}),()=>{w=!0}},[c,Vt.providerConfigMode,Vt.providerPresetId,nn]),d.useEffect(()=>{if(!c){Ke({});return}let w=!1;return km(ks,c.workspaceId).then(F=>{w||Ke(F)}),()=>{w=!0}},[c==null?void 0:c.workspaceId,ks]),d.useEffect(()=>{!c||!f||vs.length!==0&&(vs.includes(c.targetProvider)||f({...c,targetProvider:vs[0]??c.targetProvider,targetModel:null,targetProviderConfigMode:"global-default",targetProviderPresetId:null}))},[c,f,vs]),d.useEffect(()=>{!c||!c.targetModel||!f||ss.some(w=>w.id===c.targetModel)||f({...c,targetModel:null})},[ss,c,f]);const ni=d.useCallback(w=>{if(!(!c||!f||w===c.targetProvider)){if(w!==c.sourceProvider&&c.targetProvider===c.sourceProvider){He(w);return}w===mt&&Pi(w)?(re(Ie.providerConfigMode),Re(Ie.providerPresetId)):(re("global-default"),Re(null)),f({...c,targetProvider:w,targetModel:null,targetProviderConfigMode:w===mt&&Pi(w)?Ie.providerConfigMode:"global-default",targetProviderPresetId:w===mt&&Pi(w)?Ie.providerPresetId:null})}},[Ie,c,f,mt]),er=d.useCallback(w=>{!c||!f||f({...c,targetModel:w===di?null:w})},[c,f]),Pr=d.useCallback(w=>{!c||!f||(w===Dr?(re("global-default"),Re(null)):(re("cc-switch-preset"),Re(w)),f({...c,targetModel:null,targetProviderConfigMode:w===Dr?"global-default":"cc-switch-preset",targetProviderPresetId:w===Dr?null:w}))},[c,f]),Yi=d.useCallback(()=>{!c||!De||!f||(re("global-default"),Re(null),f({...c,targetProvider:De,targetModel:null,targetProviderConfigMode:"global-default",targetProviderPresetId:null}),He(null))},[c,f,De]),As=d.useCallback(()=>{He(null)},[]);async function tr(w){if(Ht.current)return;const F=R.trim(),Z=E,be=Wy(Z,F),Ee=he;if(be.length===0&&Ee.length===0||!Un.allowed||ie||tt){Bt({title:ie?a("conversation.runtimeRunning"):Gn??Un.reason??a("conversation.capabilityDenied"),tone:"error"});return}Ht.current=!0,is.trigger(w==="queue"?"selection":"action"),ve(!0),K(""),D([]),X([]),xe(!1),M(!1),Be(!1),Ce(!1),Te(!1);try{const Je=await Promise.all(Ee.map(async un=>({kind:un.kind,fileName:un.file.name,mimeType:rl(un.file),fileSize:un.file.size,contentBase64:await $y(un.file)}))),Et=Ee.map(un=>qW(un.file,un.id));await(w==="queue"&&_?_:T)(be,{model:Nn||os!=null&&os.usesProviderDefault?void 0:te||void 0,reasoningLevel:Nn?void 0:ut&&jn.length>0?ee:void 0,providerConfigMode:Nn?Vt.providerConfigMode:rt,providerPresetId:Nn?Vt.providerConfigMode==="cc-switch-preset"?Vt.providerPresetId:null:rt==="cc-switch-preset"?$t:null,attachments:Je,attachmentMeta:Et}),VW(Ee),Ee.forEach(un=>{un.previewUrl&&ft.current.delete(un.previewUrl)})}catch(Je){K(F),D(Z),X(Ee),Bt({title:Je instanceof Error&&Je.message==="FILE_READ_FAILED"?a("conversation.attachmentReadFailed"):Je instanceof Error?Je.message:a("conversation.capabilityDenied"),tone:"error"})}finally{ve(!1),Ht.current=!1}}async function fr(w){w.preventDefault(),await tr(A?"queue":"send")}async function si(){if(!(!zt||!H||$e))try{Ve(!0),is.trigger("action"),await H()}catch(w){Bt({title:w instanceof Error?w.message:a("conversation.capabilityInterruptDisabled"),tone:"error"})}finally{Ve(!1)}}const wr=G||C||ie||tt||!Un.allowed||!Pt,zr=G||C||ie||!tn.allowed,v=R.length===0&&!ie,$=s.jsxs("section",{ref:h,className:"composer-panel",children:[s.jsxs("form",{className:"composer-form",onSubmit:fr,children:[s.jsx("input",{id:z,ref:it,type:"file",multiple:!0,tabIndex:-1,"aria-hidden":"true",style:Oy,onChange:js}),s.jsx("input",{id:L,ref:Ze,type:"file",accept:"image/*",capture:"environment",tabIndex:-1,"aria-hidden":"true",style:Oy,onChange:js}),s.jsxs("div",{className:"composer-input-container","data-drag-active":le?"true":void 0,onDragOver:Ge,onDragLeave:ei,onDrop:Mn,children:[c?s.jsxs("div",{className:"composer-fork-draft",children:[s.jsxs("div",{className:"composer-fork-draft-main",children:[s.jsxs("div",{className:"composer-fork-draft-copy",children:[s.jsx("span",{className:"composer-fork-draft-label",children:a("conversation.forkDraftLabel")}),s.jsx("span",{className:"composer-fork-draft-text",children:FW(c.content)})]}),s.jsxs("div",{className:"composer-fork-config",children:[s.jsxs("div",{className:"composer-fork-config-grid",children:[s.jsxs("div",{className:"composer-fork-field",children:[s.jsx("span",{className:"composer-fork-model-label",children:a("conversation.forkTargetProviderLabel")}),s.jsx(Ha,{ariaLabel:a("conversation.forkTargetProviderLabel"),value:c.targetProvider,options:Wn,onChange:w=>ni(w),compact:!0})]}),s.jsxs("div",{className:"composer-fork-field",children:[s.jsx("span",{className:"composer-fork-model-label",children:a("conversation.forkTargetModelLabel")}),$s?s.jsx(zh,{ariaLabel:a("conversation.forkTargetModelLabel"),triggerLabel:On,presetOptions:ls,selectedPresetValue:zs,selectedPresetSummary:(ms==null?void 0:ms.summary)??null,onSelectPreset:Pr,modelOptions:Ts,selectedModelValue:Xs,onSelectModel:er,loadingPresets:ze,loadingModels:vt,modelColumnDisabled:Vt.providerConfigMode==="cc-switch-preset"&&vt&&kt===null,showPresetColumn:ws,modelEmptyText:a("conversation.deploymentModelEmpty")}):s.jsx(Ha,{ariaLabel:a("conversation.forkTargetModelLabel"),value:Xs,options:Ts,onChange:er,disabled:vt||tt,compact:!0})]})]}),Gn?s.jsx("p",{className:"composer-capability-hint",children:Gn}):null]})]}),u?s.jsx("button",{type:"button",className:"composer-fork-draft-clear","aria-label":a("conversation.forkDraftClear"),title:a("conversation.forkDraftClear"),onClick:u,children:s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}):null]}):null,he.length>0?s.jsx("div",{className:"composer-attachments",children:he.map(w=>s.jsxs("div",{className:"composer-attachment-card",children:[w.previewUrl?s.jsx("img",{src:w.previewUrl,alt:a("conversation.attachmentPreviewAlt"),className:"composer-attachment-preview"}):s.jsx("div",{className:"composer-attachment-file","aria-hidden":"true",children:s.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),s.jsx("path",{d:"M14 2v5h5"}),s.jsx("path",{d:"M9 13h6"}),s.jsx("path",{d:"M9 17h6"})]})}),s.jsxs("div",{className:"composer-attachment-meta",children:[s.jsx("span",{className:"attachment-name",title:w.file.name,children:w.file.name}),s.jsx("span",{className:"attachment-size",children:OW(w.file.size)})]}),s.jsx("button",{type:"button",className:"attachment-remove",onClick:()=>Cs(w.id),"aria-label":a("conversation.removeAttachment"),children:s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},w.id))}):null,le?s.jsx("div",{className:"composer-drop-hint",children:a("conversation.attachmentDropHint")}):null,s.jsxs("div",{className:"composer-input-wrapper",children:[E.length>0?s.jsx("div",{className:"composer-selected-mentions","aria-label":a("conversation.mentionSelectedListLabel"),children:E.map(w=>s.jsxs("span",{className:"composer-selected-mention-chip","data-kind":w.type,children:[s.jsxs("button",{type:"button",className:"composer-selected-mention-chip-main",onClick:()=>En(w),"aria-label":w.type==="skill"?a("conversation.mentionActivateSkill").replace("{name}",w.label):a("conversation.mentionActivateFile").replace("{name}",w.label),children:[s.jsx("span",{className:"composer-selected-mention-chip-tag",children:w.type==="skill"?a("conversation.mentionSkillTag"):a("conversation.mentionFileTag")}),s.jsx("span",{className:"composer-selected-mention-chip-label",title:w.label,children:w.label})]}),s.jsx("button",{type:"button",className:"composer-selected-mention-chip-remove","aria-label":w.type==="skill"?a("conversation.mentionRemoveSkill").replace("{name}",w.label):a("conversation.mentionRemoveFile").replace("{name}",w.label),title:a("common.close"),onClick:F=>{F.stopPropagation(),gi(w.id)},children:"×"})]},w.id))}):null,s.jsx("textarea",{ref:lt,className:"composer-input",value:R,placeholder:t??a("conversation.composerPlaceholder"),readOnly:ie,"aria-readonly":ie,onChange:w=>K(w.target.value),rows:1,onFocus:()=>Te(!1),onCompositionStart:()=>{fn(),gt.current=!0},onCompositionEnd:()=>{gt.current=!1,Nt.current=!0,dt.current=globalThis.setTimeout(()=>{Nt.current=!1,dt.current=null},0)},onPaste:w=>{if(ie||!tn.allowed)return;const F=Array.from(w.clipboardData.items).filter(Z=>Z.kind==="file").map(Z=>Z.getAsFile()).filter(Z=>!!Z);F.length!==0&&(w.preventDefault(),bn(F))},onKeyDown:w=>{if(w.key==="Escape"&&(Te(!1),Is()),pe&&W.length>0){if(w.key==="ArrowDown"){w.preventDefault(),Oe(F=>(F+1)%W.length);return}if(w.key==="ArrowUp"){w.preventDefault(),Oe(F=>(F-1+W.length)%W.length);return}}if(w.key==="Enter"&&!w.shiftKey){if(pe&&W.length>0){w.preventDefault(),yn(W[ge]??W[0]);return}if(GW(w,gt.current,Nt.current))return;w.preventDefault(),wr||fr(w)}}}),s.jsx("div",{className:"composer-input-actions",children:Os?s.jsx("button",{className:"composer-send composer-send-busy",type:"button",disabled:!pn,onClick:()=>{pn&&si()},"aria-label":Tn,title:Tn,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:s.jsx("rect",{x:"6",y:"6",width:"12",height:"12"})})}):s.jsx("button",{className:"composer-send",type:"submit",disabled:wr,"aria-label":Qs,title:Qs,children:s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[s.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),s.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})})]}),Y?s.jsx("div",{className:"composer-slash-menu",role:"menu","aria-label":a("conversation.slashMenuTitle"),children:Dn.map(w=>s.jsxs("button",{type:"button",className:"composer-slash-item",onClick:()=>qs(w.command),children:[s.jsx("span",{className:"composer-slash-command",children:w.command}),s.jsx("span",{className:"composer-slash-label",children:w.label})]},w.command))}):null,pe?s.jsx("div",{ref:wt,className:"composer-mention-menu",role:"listbox","aria-label":a("conversation.mentionMenuTitle"),children:je?s.jsx("div",{className:"composer-mention-empty",children:a("conversation.mentionLoading")}):W.length>0?W.map(w=>{var F,Z;return s.jsxs("button",{type:"button",className:((F=W[ge])==null?void 0:F.id)===w.id?"composer-mention-item is-active":"composer-mention-item","aria-selected":((Z=W[ge])==null?void 0:Z.id)===w.id,onClick:()=>yn(w),onMouseEnter:()=>{const be=W.findIndex(Ee=>Ee.id===w.id);be>=0&&Oe(be)},children:[s.jsxs("span",{className:"composer-mention-item-main",children:[s.jsx("span",{className:"composer-mention-item-title",children:w.name}),s.jsx("span",{className:"composer-mention-item-subtitle",children:w.subtitle})]}),s.jsx("span",{className:"composer-mention-item-tag",children:w.type==="skill"?a("conversation.mentionSkillTag"):a("conversation.mentionFileTag")})]},w.id)}):s.jsx("div",{className:"composer-mention-empty",children:a("conversation.mentionEmpty")})}):null,s.jsxs("div",{className:"composer-controls",children:[s.jsxs("div",{className:"composer-controls-left",children:[tn.allowed?P.isNativeMobile?s.jsx("button",{type:"button",className:"composer-attach-btn","aria-label":a("conversation.attachFiles"),title:a("conversation.attachFiles"),disabled:zr,onClick:ir,children:s.jsx(Sf,{})}):zr?s.jsx("button",{type:"button",className:"composer-attach-btn","aria-label":a("conversation.attachFiles"),title:a("conversation.attachFiles"),disabled:!0,children:s.jsx(Sf,{})}):s.jsx("label",{htmlFor:z,className:"composer-attach-btn","aria-label":a("conversation.attachFiles"),title:a("conversation.attachFiles"),onClick:()=>{Te(!1)},children:s.jsx(Sf,{})}):null,!Nn&&O?s.jsx(zh,{ariaLabel:a("conversation.modelSelectorLabel"),triggerLabel:ur,presetOptions:Gt,selectedPresetValue:Zn,selectedPresetSummary:(es==null?void 0:es.summary)??null,onSelectPreset:on,modelOptions:an,selectedModelValue:te,onSelectModel:Pn,loadingPresets:et,loadingModels:bt,modelColumnDisabled:rt==="cc-switch-preset"&&bt&&jt===null,showPresetColumn:hs,modelEmptyText:a("conversation.deploymentModelEmpty")}):null,!Nn&&!O?s.jsx(Ha,{ariaLabel:a("conversation.modelSelectorLabel"),value:te,options:an,onChange:Pn}):null,!Nn&&ut&&jn.length>0?s.jsx(Ha,{ariaLabel:a("conversation.reasoningSelectorLabel"),value:ee,options:ts,onChange:w=>Sn(w),compact:!0}):null,Ds?s.jsxs("button",{type:"button",className:"composer-slash-btn",onClick:Us,title:a("conversation.slashMenu"),children:[s.jsx("span",{className:"slash-icon",children:"/"}),s.jsx("span",{children:a("conversation.slashMenu")})]}):null,s.jsx(t5,{contextUsage:b}),s.jsx(cW,{provider:y,messages:x,variant:"composer"})]}),v?s.jsx("div",{className:"composer-quick-phrase-group",children:s.jsx("button",{type:"button",className:"composer-quick-phrase-trigger","aria-label":a("conversation.quickPhraseTrigger"),title:a("conversation.quickPhraseTrigger"),onClick:()=>{Be(!0),Te(!1)},children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M7 8h10"}),s.jsx("path",{d:"M7 12h8"}),s.jsx("path",{d:"M7 16h5"}),s.jsx("path",{d:"M5 5h14v14H9l-4 4V5z"})]})})}):null]})]})]}),s.jsx(ln,{open:ye,title:a("conversation.quickPhraseModalTitle"),description:a("conversation.quickPhraseModalDescription"),className:"composer-quick-phrase-modal",onClose:()=>{Be(!1),Ce(!1)},children:s.jsxs("div",{className:"composer-quick-phrase-modal-body",children:[s.jsxs("div",{className:"composer-quick-phrase-toolbar",children:[s.jsx("div",{className:"composer-quick-phrase-toolbar-copy",children:s.jsx("span",{children:a("conversation.quickPhraseListLabel")})}),s.jsx("button",{type:"button",className:"primary-button",disabled:se,onClick:()=>Ce(!0),children:a("conversation.quickPhraseOpenCreateAction")})]}),s.jsx("div",{className:"composer-quick-phrase-list",role:"list","aria-label":a("conversation.quickPhraseListLabel"),children:de.length===0?s.jsx("div",{className:"composer-quick-phrase-empty",children:a("conversation.quickPhraseEmpty")}):de.map((w,F)=>s.jsxs("div",{className:"composer-quick-phrase-item",role:"listitem",children:[s.jsxs("button",{type:"button",className:"composer-quick-phrase-select",onClick:()=>ti(w.text),children:[s.jsx("span",{className:"composer-quick-phrase-order",children:a("conversation.quickPhraseOrderLabel",{index:F+1})}),s.jsx("span",{className:"composer-quick-phrase-text",children:w.text})]}),s.jsxs("div",{className:"composer-quick-phrase-actions",children:[s.jsx("button",{type:"button",className:"composer-quick-phrase-action",disabled:se||F===0,"aria-label":a("conversation.quickPhraseMoveUp"),title:a("conversation.quickPhraseMoveUp"),onClick:()=>pi(w.id,-1),children:"↑"}),s.jsx("button",{type:"button",className:"composer-quick-phrase-action",disabled:se||F===de.length-1,"aria-label":a("conversation.quickPhraseMoveDown"),title:a("conversation.quickPhraseMoveDown"),onClick:()=>pi(w.id,1),children:"↓"}),s.jsx("button",{type:"button",className:"composer-quick-phrase-action is-danger",disabled:se,"aria-label":a("conversation.quickPhraseDelete"),title:a("conversation.quickPhraseDelete"),onClick:()=>$r(w.id),children:"×"})]})]},w.id))})]})}),s.jsx(ln,{open:We,title:a("conversation.quickPhraseCreateModalTitle"),description:a("conversation.quickPhraseCreateModalDescription"),className:"composer-quick-phrase-create-modal",onClose:()=>Ce(!1),children:s.jsxs("div",{className:"composer-quick-phrase-modal-body",children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("conversation.quickPhraseCreateLabel")}),s.jsx("textarea",{className:"composer-quick-phrase-textarea",value:ke,placeholder:a("conversation.quickPhraseCreatePlaceholder"),rows:4,onChange:w=>we(w.target.value)})]}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",onClick:()=>Ce(!1),children:a("common.cancel")}),s.jsx("button",{type:"button",className:"primary-button",disabled:se||ke.trim().length===0,onClick:()=>{kr()},children:a("conversation.quickPhraseCreateAction")})]})]})}),s.jsx(ln,{open:De!==null,title:a("conversation.forkSwitchConfirmTitle"),description:a("conversation.forkSwitchConfirmDescription"),className:"composer-fork-confirm-modal",onClose:As,children:s.jsxs("div",{className:"composer-fork-confirm-body",children:[s.jsxs("div",{className:"composer-fork-confirm-list",children:[s.jsxs("div",{className:"composer-fork-confirm-item",children:[s.jsx("span",{className:"composer-fork-confirm-icon is-keep","aria-hidden":"true",children:s.jsx(QW,{})}),s.jsxs("div",{className:"composer-fork-confirm-copy",children:[s.jsx("strong",{children:a("conversation.forkSwitchConfirmKeepTitle")}),s.jsx("p",{children:a("conversation.forkSwitchConfirmKeepBody")})]})]}),s.jsxs("div",{className:"composer-fork-confirm-item",children:[s.jsx("span",{className:"composer-fork-confirm-icon is-convert","aria-hidden":"true",children:s.jsx(ZW,{})}),s.jsxs("div",{className:"composer-fork-confirm-copy",children:[s.jsx("strong",{children:a("conversation.forkSwitchConfirmConvertTitle")}),s.jsx("p",{children:a("conversation.forkSwitchConfirmConvertBody")})]})]}),s.jsxs("div",{className:"composer-fork-confirm-item",children:[s.jsx("span",{className:"composer-fork-confirm-icon is-drop","aria-hidden":"true",children:s.jsx(e5,{})}),s.jsxs("div",{className:"composer-fork-confirm-copy",children:[s.jsx("strong",{children:a("conversation.forkSwitchConfirmDropTitle")}),s.jsx("p",{children:a("conversation.forkSwitchConfirmDropBody")})]})]})]}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",onClick:As,children:a("conversation.forkSwitchKeepNative")}),s.jsx("button",{type:"button",className:"primary-button",onClick:Yi,children:a("conversation.forkSwitchConfirmAction")})]})]})}),s.jsx(YW,{open:I&&P.isNativeMobile,onClose:()=>xe(!1),onSelectCamera:()=>Hs("camera"),onSelectLibrary:()=>Hs("library")})]});return m?Bs.createPortal($,m):$}function YW({open:e,onClose:t,onSelectCamera:n,onSelectLibrary:r}){return s.jsx(zi,{open:e,title:a("conversation.attachmentSourceSheetTitle"),description:a("conversation.attachmentSourceSheetDescription"),kind:"action",height:"auto",className:"composer-attachment-sheet",cardClassName:"composer-attachment-sheet-card",bodyClassName:"composer-attachment-sheet-body",showHandle:!0,onClose:t,children:s.jsxs(Wi,{className:"composer-attachment-sheet-actions",children:[s.jsx(rs,{as:"button",className:"mobile-workspace-home-row composer-attachment-sheet-option","aria-label":a("conversation.attachmentTakePhoto"),label:a("conversation.attachmentTakePhoto"),description:a("conversation.attachmentTakePhotoHint"),trailing:s.jsx(JW,{}),onClick:n}),s.jsx(rs,{as:"button",className:"mobile-workspace-home-row composer-attachment-sheet-option","aria-label":a("conversation.attachmentChooseFromLibrary"),label:a("conversation.attachmentChooseFromLibrary"),description:a("conversation.attachmentChooseFromLibraryHint"),trailing:s.jsx(XW,{}),onClick:r})]})})}function JW(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M4 8h3l1.5-2h7L17 8h3a1 1 0 0 1 1 1v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9a1 1 0 0 1 1-1Z"}),s.jsx("circle",{cx:"12",cy:"13",r:"4"})]})}function Sf(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"4"}),s.jsx("path",{d:"M8 12h8M12 8v8"})]})}function XW(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2.5"}),s.jsx("path",{d:"m7.5 15 3-3 2.5 2.5 3-4L18 13.5"}),s.jsx("circle",{cx:"8.75",cy:"8.75",r:"1.25",fill:"currentColor",stroke:"none"})]})}function QW(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("path",{d:"M12 3 4 7v5c0 5 3.5 8 8 9 4.5-1 8-4 8-9V7l-8-4Z"}),s.jsx("path",{d:"m9.5 12 1.8 1.8L15 10.2"})]})}function ZW(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("path",{d:"M4 7h9"}),s.jsx("path",{d:"m10 3 4 4-4 4"}),s.jsx("path",{d:"M20 17h-9"}),s.jsx("path",{d:"m14 13-4 4 4 4"})]})}function e5(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("path",{d:"m7 7 10 10"}),s.jsx("path",{d:"M17 7 7 17"}),s.jsx("path",{d:"M12 3v2"}),s.jsx("path",{d:"M12 19v2"})]})}function t5({contextUsage:e}){const[t,n]=d.useState(!1),r=d.useRef(null),i=d.useRef(null),[o,l]=d.useState(null),c=d.useId(),u=e?Math.round(e.usageRatio*100):null,f=e?Math.max(0,Math.min(e.usageRatio,1)):0,h=n5(f),m=e?s5(e.contextWindowSource):null,g=e?`${a("conversation.contextUsageTitle")} ${u}%`:a("conversation.contextUsageUnavailable"),p=d.useCallback(()=>{const b=r.current;if(!b||typeof window>"u")return;const y=b.getBoundingClientRect(),x=window.innerWidth,k=window.innerHeight,C=12,j=10,H=Math.min(240,Math.max(188,x-C*2)),_=Math.min(Math.max(C,y.left+y.width/2-H/2),Math.max(C,x-H-C)),T=y.top-C,P=k-y.bottom-C,z=T>=140||T>=P;l({position:"fixed",left:_,width:H,maxWidth:x-C*2,top:z?void 0:y.bottom+j,bottom:z?k-y.top+j:void 0})},[]);return d.useEffect(()=>{if(!t)return;function b(x){var C,j;const k=x.target;!((C=r.current)!=null&&C.contains(k))&&!((j=i.current)!=null&&j.contains(k))&&n(!1)}function y(x){x.key==="Escape"&&n(!1)}return window.addEventListener("pointerdown",b),window.addEventListener("keydown",y),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),p(),()=>{window.removeEventListener("pointerdown",b),window.removeEventListener("keydown",y),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)}},[t,p]),s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:r,type:"button",className:`composer-context-ring ${h}`,style:{"--context-usage-progress":`${f}`},"aria-label":g,"aria-expanded":t,"aria-describedby":t?c:void 0,onClick:()=>n(b=>!b),onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),onFocus:()=>n(!0),onBlur:()=>n(!1),children:s.jsx("span",{className:"composer-context-ring-value",children:u===null?"--":s.jsxs(s.Fragment,{children:[s.jsx("span",{children:u}),s.jsx("span",{className:"composer-context-ring-suffix",children:"%"})]})})}),t&&o&&typeof document<"u"?Bs.createPortal(s.jsx("div",{ref:i,id:c,className:"composer-context-tooltip",style:o,role:"tooltip",children:e?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"composer-context-tooltip-title",children:a("conversation.contextUsageTitle")}),s.jsxs("div",{className:"composer-context-tooltip-line",children:[u,"% · ",Cf(e.promptTokens)," /"," ",Cf(e.contextWindow)," tokens"]}),e.cachedInputTokens>0?s.jsx("div",{className:"composer-context-tooltip-line",children:a("conversation.contextUsageCachedTokens").replace("{count}",Cf(e.cachedInputTokens))}):null,m?s.jsx("div",{className:"composer-context-tooltip-meta",children:m}):null,e.isEstimated?s.jsx("div",{className:"composer-context-tooltip-meta",children:a("conversation.contextUsageEstimated")}):null]}):s.jsx("div",{className:"composer-context-tooltip-line",children:a("conversation.contextUsageUnavailable")})}),document.body):null]})}function n5(e){return e>=.95?"is-critical":e>=.8?"is-warning":"is-normal"}function s5(e){switch(e){case"provider-log":return a("conversation.contextUsageSourceProviderLog");case"provider-runtime":return a("conversation.contextUsageSourceProviderRuntime");case"provider-config":return a("conversation.contextUsageSourceProviderConfig");case"model-map":return a("conversation.contextUsageSourceModelMap");default:return""}}function Cf(e){return new Intl.NumberFormat().format(e)}function r5(e){const t=new URLSearchParams({workspaceId:e});return ae.request(`/api/files/workspace-bridge/capabilities?${t.toString()}`)}function i5(e,t,n){return ae.request("/api/files/workspace-bridge/list-dir",{method:"POST",body:JSON.stringify({workspaceId:e,path:t,options:n})})}function a5(e,t){return ae.request("/api/files/workspace-bridge/read-text",{method:"POST",body:JSON.stringify({workspaceId:e,path:t})})}function o5(e,t){return ae.request("/api/files/workspace-bridge/read-texts",{method:"POST",body:JSON.stringify({workspaceId:e,paths:t})})}function l5(e,t,n,r){return ae.request("/api/files/workspace-bridge/write-text",{method:"POST",body:JSON.stringify({workspaceId:e,path:t,content:n,options:r})})}function c5(e,t,n){return ae.request("/api/files/workspace-bridge/delete-file",{method:"POST",body:JSON.stringify({workspaceId:e,path:t,options:n})})}function u5(e,t){const n=new URLSearchParams({workspaceId:e,path:t});return ae.request(`/api/files/workspace-bridge/stat?${n.toString()}`)}function d5(e,t){const n=new URLSearchParams({workspaceId:e,path:t});return ae.request(`/api/files/workspace-bridge/exists?${n.toString()}`)}function f5(e,t){return ae.request("/api/files/workspace-bridge/open-file",{method:"POST",body:JSON.stringify({workspaceId:e,path:t})})}function h5(e,t){return ae.request("/api/files/workspace-bridge/reveal-in-file-manager",{method:"POST",body:JSON.stringify({workspaceId:e,path:t})})}function m5(e,t,n){return ae.request("/api/files/workspace-bridge/watch-dir",{method:"POST",body:JSON.stringify({workspaceId:e,path:t,options:n})})}function zy(e){return ae.request("/api/files/workspace-bridge/unwatch",{method:"POST",body:JSON.stringify({watchId:e})})}function p5(e,t){const n=new URLSearchParams({watchId:e});return typeof t=="number"&&Number.isFinite(t)&&n.set("cursor",String(Math.floor(t))),ae.request(`/api/files/workspace-bridge/watch-events?${n.toString()}`)}function RC(e){var p;const t=new Map;let n=null;const r={lastEventOrigin:null,lastEventMatchedSource:!1,lastEventRequestId:null,lastEventAction:null,lastResponseId:null,lastResponseOrigin:null,lastHandledRequestId:null,currentIframeWindowMatches:!1};i("create",{hasIframe:!!e.iframe,hasContentWindow:!!((p=e.iframe)!=null&&p.contentWindow),workspaceId:e.workspaceId??null});function i(b,y){const x={at:new Date().toISOString(),source:"html-preview-host",stage:b,payload:y??{}};typeof console<"u"&&typeof console.debug=="function"&&console.debug(`[html-preview-bridge] ${b}`,y??{}),o(x)}function o(b){var x;const y=(x=e.iframe)==null?void 0:x.contentWindow;!y||typeof y.postMessage!="function"||y.postMessage({type:"codingns.workspace.debug",payload:b},n??"*")}function l(b,y,x,k,C){i("post-error",{id:y.id,action:y.action,code:x,message:k,path:C,origin:b.origin}),c(b,{type:"codingns.workspace.response",id:y.id,ok:!1,error:{code:x,message:k,path:C}})}function c(b,y){const x=b.source;if(r.lastResponseId=y.id,r.lastResponseOrigin=b.origin,i("post-response",{id:y.id,ok:y.ok,origin:b.origin,targetCanPostMessage:jf(x)}),!jf(x)){i("drop-response",{id:y.id,reason:"event.source cannot postMessage",origin:b.origin});return}x.postMessage(y,b.origin)}function u(b){var x;const y=(x=e.iframe)==null?void 0:x.contentWindow;if(!y||!n){i("drop-watch-event",{watchId:b.watchId,hasIframeWindow:!!y,iframeOrigin:n});return}i("post-watch-event",{watchId:b.watchId,iframeOrigin:n}),y.postMessage(b,n)}async function f(b,y){var H,_;const x=(H=e.iframe)==null?void 0:H.contentWindow,k=((_=e.workspaceId)==null?void 0:_.trim())??"",C=jf(b.source),j=!!(x&&b.source===x);if(r.lastEventOrigin=b.origin,r.lastEventMatchedSource=j,r.lastEventRequestId=y.id,r.lastEventAction=y.action,r.currentIframeWindowMatches=j,i("handle-request",{id:y.id,action:y.action,origin:b.origin,hasIframeWindow:!!x,sourceCanPostMessage:C,sourceMatchesCurrentIframe:j,workspaceId:k||null}),!x||!C){i("drop-request",{id:y.id,action:y.action,reason:x?"event.source cannot postMessage":"missing iframe.contentWindow",origin:b.origin});return}if(n=b.origin,!k){l(b,y,"INTERNAL_ERROR","当前预览缺少 workspaceId");return}try{let T;const P=y.payload??{};switch(y.action){case"capabilities":T=await r5(k);break;case"listDir":T=await i5(k,typeof P.path=="string"?P.path:"",jc(P.options)?P.options:void 0);break;case"readText":T=await a5(k,typeof P.path=="string"?P.path:"");break;case"readTexts":T=await o5(k,Array.isArray(P.paths)?P.paths.filter(z=>typeof z=="string"):[]);break;case"writeText":T=await l5(k,typeof P.path=="string"?P.path:"",typeof P.content=="string"?P.content:"",jc(P.options)?P.options:void 0);break;case"deleteFile":T=await c5(k,typeof P.path=="string"?P.path:"",jc(P.options)?P.options:void 0);break;case"stat":T=await u5(k,typeof P.path=="string"?P.path:"");break;case"exists":T=await d5(k,typeof P.path=="string"?P.path:"");break;case"openWorkspaceFile":{const z=await f5(k,typeof P.path=="string"?P.path:""),L=await ha().fs.openFile(z.absolutePath);if(!L.ok)throw{code:L.errorCode??"DESKTOP_OPEN_FAILED",message:L.detail??"打开文件失败",path:z.relativePath};T=z;break}case"revealWorkspaceFile":{const z=await h5(k,typeof P.path=="string"?P.path:""),L=await ha().fs.revealInFileManager(z.absolutePath);if(!L.ok)throw{code:L.errorCode??"DESKTOP_REVEAL_FAILED",message:L.detail??"打开所在目录失败",path:z.relativePath};T=z;break}case"watchDir":{const z=await m5(k,typeof P.path=="string"?P.path:"",jc(P.options)?P.options:void 0);h(z.watchId),T=z;break}case"unwatch":{const z=typeof P.watchId=="string"?P.watchId.trim():"";if(!z){l(b,y,"INVALID_WATCH_ID","必须提供 watchId");return}m(z),T=await zy(z);break}case"applyIndexConfig":l(b,y,"INTERNAL_ERROR","当前预览宿主页暂未代理 applyIndexConfig,请优先走 Preview HTTP Bridge。");return;default:l(b,y,"INTERNAL_ERROR",`不支持的 workspace bridge 动作:${y.action}`);return}i("handle-success",{id:y.id,action:y.action,origin:b.origin}),c(b,{type:"codingns.workspace.response",id:y.id,ok:!0,payload:T}),r.lastHandledRequestId=y.id}catch(T){const P=Hy(T);i("handle-error",{id:y.id,action:y.action,code:P.code,message:P.message,path:P.path}),l(b,y,P.code,P.message,P.path)}}return{async onMessage(b){if(!g5(b.data)){const y=b.data;y&&typeof y=="object"&&typeof y.type=="string"&&y.type.startsWith("codingns.")&&i("ignore-message",{origin:b.origin,type:y.type,reason:"not workspace bridge request"});return}i("incoming-message",{origin:b.origin,id:b.data.id,action:b.data.action}),await f(b,b.data)},debug:r,dispose(){i("dispose",{activeWatchCount:t.size,lastEventRequestId:r.lastEventRequestId,lastHandledRequestId:r.lastHandledRequestId});for(const b of[...t.keys()])m(b),zy(b).catch(()=>{})}};function h(b){if(!b||t.has(b))return;const y={stopped:!1,cursor:0};t.set(b,y),g(b,y)}function m(b){const y=t.get(b);y&&(y.stopped=!0,t.delete(b))}async function g(b,y){for(;!y.stopped;){try{const x=await p5(b,y.cursor);y.cursor=x.nextCursor;for(const k of x.events)u({type:"codingns.workspace.event",watchId:b,payload:k})}catch(x){if(Hy(x).code==="WATCH_NOT_FOUND"){m(b);return}}await b5(700)}}}function jf(e){return!!e&&typeof e=="object"&&typeof e.postMessage=="function"}function g5(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="codingns.workspace.request"&&typeof t.id=="string"&&typeof t.action=="string"}function jc(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Hy(e){if(typeof e=="object"&&e!==null){const t=e;return{code:typeof t.code=="string"?t.code:"INTERNAL_ERROR",message:typeof t.message=="string"?t.message:typeof t.detail=="string"?t.detail:"请求失败",path:typeof t.path=="string"?t.path:void 0}}return e instanceof Error?{code:"INTERNAL_ERROR",message:e.message||"请求失败"}:{code:"INTERNAL_ERROR",message:"请求失败"}}function b5(e){return new Promise(t=>{window.setTimeout(t,e)})}async function y5(e){return await ae.request("/api/presentation-exports",{method:"POST",body:JSON.stringify(e)})}async function x5(e){return await ae.request(`/api/presentation-exports/${encodeURIComponent(e)}`)}async function k5(e){const t=`/api/presentation-exports/${encodeURIComponent(e)}/download`,n=await ae.requestRaw(t),r=await n.blob();return{fileName:w5(e,r.type,n.headers.get("Content-Disposition")),blob:r}}function w5(e,t,n){const r=v5(n);return r||(t==="application/pdf"?`${e}.pdf`:t==="application/vnd.openxmlformats-officedocument.presentationml.presentation"?`${e}.pptx`:e)}function v5(e){var i;if(!e)return null;const t=/filename\*=UTF-8''([^;]+)/i.exec(e);if(t!=null&&t[1])return decodeURIComponent(t[1]);const n=/filename="([^"]+)"/i.exec(e)??/filename=([^;]+)/i.exec(e),r=(i=n==null?void 0:n[1])==null?void 0:i.trim();return r?decodeURIComponent(r.replace(/^"|"$/g,"")):null}const ao={width:1600,height:900},PC=[{strategy:"deck-section-slide",selector:"body .deck > section.slide"},{strategy:"deck-direct-slide",selector:"body .deck > .slide"},{strategy:"section-slide",selector:"section.slide"},{strategy:"slide-data-title",selector:".slide[data-title]"},{strategy:"slide-data-slide",selector:".slide[data-slide]"},{strategy:"deck-direct-child",selector:"body > .deck > *"}],S5=[".panel",".slide-shell",".content",".hero-main",".slide-inner"],gp=new Set(["H1","H2","H3","H4","P","LI","SPAN","BUTTON","A"]),MC=[".slide-progress",".progress-bar",".ctrl-btn",".toc",".particle",".particles",".bg-glow",".bg-grid",".page","script"].join(", "),C5=["card","panel","metric","kpi","module","feature","timeline","diagram","table","grid","shell","content"],j5={position:"position",fontFamily:"font-family",fontSize:"font-size",fontWeight:"font-weight",fontStyle:"font-style",lineHeight:"line-height",letterSpacing:"letter-spacing",color:"color",textAlign:"text-align",textDecoration:"text-decoration",textDecorationColor:"text-decoration-color",whiteSpace:"white-space",padding:"padding",margin:"margin",borderRadius:"border-radius",borderWidth:"border-width",borderColor:"border-color",backgroundColor:"background-color",opacity:"opacity"};function bp(e,t){if(!/\.(html?|HTML?)$/.test(t))return If("unsupported-extension");const n=yp(e);if(!(n!=null&&n.documentElement)||!n.querySelector("html"))return If("invalid-html");const r=Au(n);if(!r)return If("missing-page-structure");const i=[],o=r.elements.map((l,c)=>{l.querySelector("svg")&&i.push(`第 ${c+1} 页包含 SVG,只能先按只读节点导入。`),l.querySelector(MC)&&i.push(`第 ${c+1} 页包含展示壳或装饰层,导入时会过滤非内容节点。`);const u=FC(l,c);return{index:c,title:z5(l,c),selector:u,sourceRef:{pageIndex:c,pageSelector:u,nodePath:[]}}});return{supported:!0,reason:null,mode:"presentation",strategy:r.strategy,pages:o,warnings:GC(i),viewport:H5(n)}}function N5(e){const t=bp(e.html,e.filePath);if(!t.supported)return null;const n=yp(e.html),r=Au(n,t.strategy??void 0);if(!r)return null;const i=t.warnings.map((u,f)=>({code:`probe-warning-${f+1}`,message:u})),o={},l=[],c=r.elements.map((u,f)=>{var y,x,k;const h=`page-${f+1}`,m=`${h}-root`,g=V5(u),p=FC(u,f),b=K5(u,g);if(o[m]=BC({id:m,name:((y=t.pages[f])==null?void 0:y.title)??`第 ${f+1} 页`,sourceRef:{pageIndex:f,pageSelector:p,nodePath:b},runtimeFlags:g.hasAttribute("data-cns-layout-freeze")?["layout-freeze-container"]:[]}),Hh({pageElement:u,containerElement:g,pageIndex:f,pageSelector:p,containerPath:b,parentNodeId:m,nodeIdPrefix:m,nodes:o,assets:l}),!o[m].children.length){const C=((x=u.textContent)==null?void 0:x.replace(/\s+/g," ").trim())??"";if(C){const j=`${m}-fallback-text`;o[j]=$C({id:j,name:"正文",text:C,sourceRef:{pageIndex:f,pageSelector:p,nodePath:b}}),o[m].children.push(j)}}return{id:h,order:f,title:((k=t.pages[f])==null?void 0:k.title)??`第 ${f+1} 页`,frame:{width:t.viewport.width,height:t.viewport.height,background:null},rootNodeId:m,sourceRef:{pageIndex:f,pageSelector:p,nodePath:[]},runtimeHints:{hasActiveStateClass:u.classList.contains("active"),hasDeckShell:!!u.closest(".deck")}}});return{id:c$(e.filePath),schemaVersion:1,mode:"presentation",source:{kind:e.sourceKind??"codingns",path:e.filePath,version:e.version??null,entryHtmlHash:wp(e.html)},canvas:{width:t.viewport.width,height:t.viewport.height,unit:"px",aspectRatioLocked:!0},pages:c,nodes:o,assets:l$(l),warnings:i,meta:{originalTitle:n.title||null,pageDetectionStrategy:r.strategy}}}function T5(e){return EC({html:e.html,project:e.project,pageIndex:e.pageIndex,selectedNodeId:e.selectedNodeId??null,selectedRunIndex:e.selectedRunIndex??null,inlineEditingNodeId:e.inlineEditingNodeId??null,baseHref:e.baseHref??null,mode:"preview"})}function I5(e){return EC({html:e.html,project:e.project,pageIndex:0,selectedNodeId:null,mode:"save"})}function EC(e){const t=yp(e.html),n=Au(t,e.project.meta.pageDetectionStrategy);if(!n)return null;B5({document:t,project:e.project,pageElements:n.elements});const r=Au(t,e.project.meta.pageDetectionStrategy);if(!r)return null;if(e.mode==="preview"&&(P5(t,e.project),A5(t,e.baseHref??null)),r.elements.forEach((i,o)=>{e.mode==="preview"&&(i.setAttribute("data-cns-page-root","true"),o===e.pageIndex?i.setAttribute("data-cns-active-page","true"):i.removeAttribute("data-cns-active-page"),i.classList.remove("prev","next"),i.classList.add("active"))}),Object.values(e.project.nodes).forEach(i=>{if(lo(i,"draft-clone")||!i.sourceRef)return;const o=YC(r.elements,i.sourceRef);o&&(e.mode==="preview"?(o.setAttribute("data-cns-node-id",i.id),o.removeAttribute("data-cns-node-selected"),o.removeAttribute("data-cns-inline-editing"),e.selectedNodeId&&i.id===e.selectedNodeId&&o.setAttribute("data-cns-node-selected","true"),e.inlineEditingNodeId&&i.id===e.inlineEditingNodeId&&o.setAttribute("data-cns-inline-editing","true")):(o.removeAttribute("data-cns-node-id"),o.removeAttribute("data-cns-node-selected"),o.removeAttribute("data-cns-inline-editing")),JC(o,i),e.mode==="preview"&&m$(o,i,{selected:e.selectedNodeId===i.id,selectedRunIndex:e.selectedNodeId===i.id?e.selectedRunIndex??null:null}))}),Object.values(e.project.nodes).forEach(i=>{lo(i,"draft-clone-root")&&v$({project:e.project,pageElements:r.elements,cloneRootNode:i,selectedNodeId:e.mode==="preview"?e.selectedNodeId:null,mode:e.mode})}),e.mode==="preview"){R5(t);const i=t.createElement("style");i.textContent=`
78
+ [data-cns-page-root="true"]:not([data-cns-active-page="true"]) {
79
+ display: none !important;
80
+ opacity: 0 !important;
81
+ pointer-events: none !important;
82
+ visibility: hidden !important;
83
+ }
84
+
85
+ [data-cns-page-root="true"][data-cns-active-page="true"] {
86
+ opacity: 1 !important;
87
+ pointer-events: auto !important;
88
+ visibility: visible !important;
89
+ transform: none !important;
90
+ transition: none !important;
91
+ width: ${e.project.canvas.width}px !important;
92
+ min-width: ${e.project.canvas.width}px !important;
93
+ max-width: ${e.project.canvas.width}px !important;
94
+ height: ${e.project.canvas.height}px !important;
95
+ min-height: ${e.project.canvas.height}px !important;
96
+ max-height: ${e.project.canvas.height}px !important;
97
+ margin: 0 !important;
98
+ box-sizing: border-box !important;
99
+ }
100
+
101
+ [data-cns-node-selected="true"] {
102
+ outline: 2px solid #007aff !important;
103
+ outline-offset: 2px !important;
104
+ box-shadow: 0 0 0 4px rgba(0, 122, 255, 0.14) !important;
105
+ }
106
+
107
+ [data-cns-node-host="true"] {
108
+ outline: none !important;
109
+ box-shadow: none !important;
110
+ }
111
+
112
+ [data-cns-inline-editing="true"] {
113
+ color: transparent !important;
114
+ text-shadow: none !important;
115
+ caret-color: transparent !important;
116
+ }
117
+
118
+ .deck {
119
+ width: ${e.project.canvas.width}px !important;
120
+ min-width: ${e.project.canvas.width}px !important;
121
+ max-width: ${e.project.canvas.width}px !important;
122
+ margin: 0 !important;
123
+ }
124
+
125
+ html,
126
+ body {
127
+ width: ${e.project.canvas.width}px !important;
128
+ min-width: ${e.project.canvas.width}px !important;
129
+ max-width: ${e.project.canvas.width}px !important;
130
+ height: ${e.project.canvas.height}px !important;
131
+ min-height: ${e.project.canvas.height}px !important;
132
+ max-height: ${e.project.canvas.height}px !important;
133
+ margin: 0 !important;
134
+ padding: 0 !important;
135
+ overflow: hidden !important;
136
+ }
137
+
138
+ body {
139
+ transform-origin: center center !important;
140
+ }
141
+
142
+ body[data-cns-preview-body-scale-reset="true"] {
143
+ transform: none !important;
144
+ }
145
+
146
+ [data-cns-page-root="true"][data-cns-active-page="true"] .fade-up,
147
+ [data-cns-page-root="true"][data-cns-active-page="true"] .roadmap-line,
148
+ [data-cns-page-root="true"][data-cns-active-page="true"] [class*="fade-"],
149
+ [data-cns-page-root="true"][data-cns-active-page="true"] [class*="reveal-"] {
150
+ opacity: 1 !important;
151
+ transform: none !important;
152
+ transition: none !important;
153
+ transition-delay: 0s !important;
154
+ animation-delay: 0s !important;
155
+ }
156
+
157
+ [data-cns-page-root="true"][data-cns-active-page="true"] .typing-cursor {
158
+ opacity: 1 !important;
159
+ animation: none !important;
160
+ }
161
+ `,t.head.appendChild(i);const o=t.createElement("script");o.setAttribute("data-cns-preview-bridge","true"),o.textContent=`
162
+ (() => {
163
+ const eventTypes = ["pointerdown", "click", "dblclick"];
164
+ let layoutModeEnabled = false;
165
+ let activeLayoutPointer = null;
166
+ let layoutHoveredNodeId = null;
167
+ const parsePixelValue = (value) => {
168
+ if (!value) {
169
+ return 0;
170
+ }
171
+
172
+ const matched = /-?\\d+(?:\\.\\d+)?/.exec(value);
173
+ return matched ? Number(matched[0]) : 0;
174
+ };
175
+ const isTransparentColor = (value) => {
176
+ if (!value) {
177
+ return true;
178
+ }
179
+
180
+ const normalized = value.trim().toLowerCase();
181
+
182
+ if (normalized === "transparent") {
183
+ return true;
184
+ }
185
+
186
+ if (/rgba\\((?:\\d+\\s*,\\s*){3}0(?:\\.0+)?\\)/.test(normalized)) {
187
+ return true;
188
+ }
189
+
190
+ return false;
191
+ };
192
+ const resolveTextNodes = (element) => {
193
+ if (!element) {
194
+ return [];
195
+ }
196
+
197
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, {
198
+ acceptNode(node) {
199
+ return node.textContent && node.textContent.trim()
200
+ ? NodeFilter.FILTER_ACCEPT
201
+ : NodeFilter.FILTER_REJECT;
202
+ }
203
+ });
204
+ const textNodes = [];
205
+ let current = walker.nextNode();
206
+
207
+ while (current) {
208
+ textNodes.push(current);
209
+ current = walker.nextNode();
210
+ }
211
+
212
+ return textNodes;
213
+ };
214
+ const resolveEditableRect = (element, computedStyle) => {
215
+ if (!element || !element.getBoundingClientRect) {
216
+ return {
217
+ rect: null,
218
+ useContentRect: false
219
+ };
220
+ }
221
+
222
+ const elementRect = element.getBoundingClientRect();
223
+
224
+ if (!computedStyle) {
225
+ return {
226
+ rect: elementRect,
227
+ useContentRect: false
228
+ };
229
+ }
230
+
231
+ const paddingLeft = parsePixelValue(computedStyle.paddingLeft);
232
+ const paddingTop = parsePixelValue(computedStyle.paddingTop);
233
+ const paddingRight = parsePixelValue(computedStyle.paddingRight);
234
+ const paddingBottom = parsePixelValue(computedStyle.paddingBottom);
235
+ const borderLeftWidth = parsePixelValue(computedStyle.borderLeftWidth);
236
+ const borderTopWidth = parsePixelValue(computedStyle.borderTopWidth);
237
+ const borderRightWidth = parsePixelValue(computedStyle.borderRightWidth);
238
+ const borderBottomWidth = parsePixelValue(computedStyle.borderBottomWidth);
239
+ const hasSurface = !isTransparentColor(computedStyle.backgroundColor)
240
+ || borderLeftWidth > 0
241
+ || borderTopWidth > 0
242
+ || borderRightWidth > 0
243
+ || borderBottomWidth > 0
244
+ || paddingLeft > 0
245
+ || paddingTop > 0
246
+ || paddingRight > 0
247
+ || paddingBottom > 0;
248
+
249
+ if (!hasSurface) {
250
+ return {
251
+ rect: elementRect,
252
+ useContentRect: false
253
+ };
254
+ }
255
+
256
+ const textNodes = resolveTextNodes(element);
257
+
258
+ if (textNodes.length > 0) {
259
+ const range = document.createRange();
260
+ range.setStart(textNodes[0], 0);
261
+ range.setEnd(textNodes[textNodes.length - 1], textNodes[textNodes.length - 1].textContent.length);
262
+ const textRect = range.getBoundingClientRect();
263
+
264
+ if (textRect && textRect.width > 0 && textRect.height > 0) {
265
+ return {
266
+ rect: textRect,
267
+ useContentRect: true
268
+ };
269
+ }
270
+ }
271
+
272
+ const innerWidth = Math.max(1, elementRect.width - paddingLeft - paddingRight - borderLeftWidth - borderRightWidth);
273
+ const innerHeight = Math.max(1, elementRect.height - paddingTop - paddingBottom - borderTopWidth - borderBottomWidth);
274
+
275
+ return {
276
+ rect: {
277
+ left: elementRect.left + paddingLeft + borderLeftWidth,
278
+ top: elementRect.top + paddingTop + borderTopWidth,
279
+ width: innerWidth,
280
+ height: innerHeight
281
+ },
282
+ useContentRect: true
283
+ };
284
+ };
285
+ const resolveElement = (target) => {
286
+ if (!target || typeof target !== "object") {
287
+ return null;
288
+ }
289
+
290
+ if (target.nodeType === Node.TEXT_NODE) {
291
+ return target.parentElement;
292
+ }
293
+
294
+ if (target.nodeType === Node.ELEMENT_NODE) {
295
+ return target;
296
+ }
297
+
298
+ return null;
299
+ };
300
+ const resolveLayoutMeasurementElement = (nodeId) => {
301
+ const hostElement = document.querySelector('[data-cns-node-host-id="' + CSS.escape(nodeId) + '"]');
302
+
303
+ if (hostElement instanceof HTMLElement) {
304
+ return hostElement;
305
+ }
306
+
307
+ const element = document.querySelector('[data-cns-node-id="' + CSS.escape(nodeId) + '"]');
308
+
309
+ if (!(element instanceof HTMLElement)) {
310
+ return null;
311
+ }
312
+
313
+ if (element.parentElement?.getAttribute("data-cns-node-host") === "true") {
314
+ return element.parentElement;
315
+ }
316
+
317
+ const hostParent = element.closest('[data-cns-node-host="true"]');
318
+ return hostParent instanceof HTMLElement ? hostParent : element;
319
+ };
320
+ const resolveLayoutParentElement = (element) => {
321
+ if (!(element instanceof HTMLElement)) {
322
+ return document.body instanceof HTMLElement ? document.body : null;
323
+ }
324
+
325
+ const positionedParent = element.offsetParent;
326
+
327
+ if (positionedParent instanceof HTMLElement) {
328
+ return positionedParent;
329
+ }
330
+
331
+ return document.body instanceof HTMLElement ? document.body : null;
332
+ };
333
+
334
+ const handler = (event) => {
335
+ const element = resolveElement(event.target);
336
+
337
+ if (!element) {
338
+ return;
339
+ }
340
+
341
+ const matched = element.closest("[data-cns-node-id]");
342
+
343
+ if (!matched) {
344
+ return;
345
+ }
346
+
347
+ const nodeId = matched.getAttribute("data-cns-node-id");
348
+ const runIndexValue = matched.getAttribute("data-cns-run-index");
349
+ const runIndex = runIndexValue !== null ? Number.parseInt(runIndexValue, 10) : null;
350
+
351
+ if (!nodeId) {
352
+ return;
353
+ }
354
+
355
+ const computedStyle = window.getComputedStyle ? window.getComputedStyle(matched) : null;
356
+ const editableRect = resolveEditableRect(matched, computedStyle);
357
+ const payload = {
358
+ type: "codingns-static-html-node-select",
359
+ nodeId,
360
+ runIndex: Number.isInteger(runIndex) ? runIndex : null,
361
+ eventType: event.type,
362
+ metaKey: Boolean(event.metaKey),
363
+ ctrlKey: Boolean(event.ctrlKey),
364
+ rect: editableRect.rect
365
+ ? {
366
+ left: editableRect.rect.left,
367
+ top: editableRect.rect.top,
368
+ width: editableRect.rect.width,
369
+ height: editableRect.rect.height
370
+ }
371
+ : matched.getBoundingClientRect
372
+ ? {
373
+ left: matched.getBoundingClientRect().left,
374
+ top: matched.getBoundingClientRect().top,
375
+ width: matched.getBoundingClientRect().width,
376
+ height: matched.getBoundingClientRect().height
377
+ }
378
+ : null,
379
+ appearance: computedStyle
380
+ ? {
381
+ fontFamily: computedStyle.fontFamily || null,
382
+ fontSize: computedStyle.fontSize || null,
383
+ fontWeight: computedStyle.fontWeight || null,
384
+ fontStyle: computedStyle.fontStyle || null,
385
+ lineHeight: computedStyle.lineHeight || null,
386
+ letterSpacing: computedStyle.letterSpacing || null,
387
+ color: computedStyle.color || null,
388
+ textAlign: computedStyle.textAlign || null,
389
+ whiteSpace: computedStyle.whiteSpace || null,
390
+ padding: editableRect.useContentRect ? "0px" : (computedStyle.padding || null),
391
+ textTransform: computedStyle.textTransform || null
392
+ }
393
+ : null
394
+ };
395
+
396
+ window.parent?.postMessage(payload, "*");
397
+
398
+ if (layoutModeEnabled && event.type === "pointerdown") {
399
+ if (typeof matched.setPointerCapture === "function" && typeof event.pointerId === "number") {
400
+ try {
401
+ matched.setPointerCapture(event.pointerId);
402
+ } catch {
403
+ // ignore setPointerCapture failures
404
+ }
405
+ }
406
+
407
+ activeLayoutPointer = {
408
+ pointerId: typeof event.pointerId === "number" ? event.pointerId : null,
409
+ nodeId
410
+ };
411
+
412
+ window.parent?.postMessage({
413
+ type: "codingns-static-html-layout-pointer",
414
+ phase: "start",
415
+ nodeId,
416
+ clientX: event.clientX,
417
+ clientY: event.clientY,
418
+ metaKey: Boolean(event.metaKey),
419
+ ctrlKey: Boolean(event.ctrlKey)
420
+ }, "*");
421
+
422
+ event.preventDefault();
423
+ }
424
+ };
425
+
426
+ const handlePointerOver = (event) => {
427
+ if (!layoutModeEnabled) {
428
+ return;
429
+ }
430
+
431
+ const element = resolveElement(event.target);
432
+ const matched = element?.closest ? element.closest("[data-cns-node-id]") : null;
433
+ const nodeId = matched?.getAttribute("data-cns-node-id")?.trim() || null;
434
+
435
+ if (nodeId === layoutHoveredNodeId) {
436
+ return;
437
+ }
438
+
439
+ layoutHoveredNodeId = nodeId;
440
+ window.parent?.postMessage({
441
+ type: "codingns-static-html-layout-hover",
442
+ nodeId: nodeId || ""
443
+ }, "*");
444
+ };
445
+
446
+ const handlePointerLeaveViewport = () => {
447
+ if (!layoutModeEnabled || !layoutHoveredNodeId) {
448
+ return;
449
+ }
450
+
451
+ layoutHoveredNodeId = null;
452
+ window.parent?.postMessage({
453
+ type: "codingns-static-html-layout-hover",
454
+ nodeId: ""
455
+ }, "*");
456
+ };
457
+
458
+ const syncSelectionState = (payload) => {
459
+ layoutModeEnabled = Boolean(payload?.layoutModeEnabled);
460
+ layoutHoveredNodeId = typeof payload?.layoutHoveredNodeId === "string" && payload.layoutHoveredNodeId.trim()
461
+ ? payload.layoutHoveredNodeId.trim()
462
+ : null;
463
+ if (!layoutModeEnabled) {
464
+ activeLayoutPointer = null;
465
+ layoutHoveredNodeId = null;
466
+ }
467
+
468
+ const selectedNodeId = typeof payload?.selectedNodeId === "string" && payload.selectedNodeId.trim()
469
+ ? payload.selectedNodeId.trim()
470
+ : null;
471
+ const selectedRunIndex = typeof payload?.selectedRunIndex === "number" && Number.isInteger(payload.selectedRunIndex)
472
+ ? payload.selectedRunIndex
473
+ : null;
474
+ const inlineEditingNodeId = typeof payload?.inlineEditingNodeId === "string" && payload.inlineEditingNodeId.trim()
475
+ ? payload.inlineEditingNodeId.trim()
476
+ : null;
477
+ const layoutSelectedNodeIds = Array.isArray(payload?.layoutSelectedNodeIds)
478
+ ? payload.layoutSelectedNodeIds.filter((value) => typeof value === "string" && value.trim()).map((value) => value.trim())
479
+ : [];
480
+
481
+ document.querySelectorAll("[data-cns-node-selected]").forEach((element) => {
482
+ if (element.getAttribute("data-cns-node-id") !== selectedNodeId) {
483
+ element.removeAttribute("data-cns-node-selected");
484
+ }
485
+ });
486
+
487
+ document.querySelectorAll("[data-cns-inline-editing]").forEach((element) => {
488
+ if (element.getAttribute("data-cns-node-id") !== inlineEditingNodeId) {
489
+ element.removeAttribute("data-cns-inline-editing");
490
+ }
491
+ });
492
+
493
+ if (selectedNodeId) {
494
+ if (selectedRunIndex !== null) {
495
+ const selectedRunElement = document.querySelector(
496
+ '[data-cns-node-id="' + CSS.escape(selectedNodeId) + '"][data-cns-run-index="' + String(selectedRunIndex) + '"]'
497
+ );
498
+
499
+ if (selectedRunElement) {
500
+ selectedRunElement.setAttribute("data-cns-node-selected", "true");
501
+ }
502
+ } else {
503
+ const selectedElement = document.querySelector('[data-cns-node-id="' + CSS.escape(selectedNodeId) + '"]');
504
+
505
+ if (selectedElement) {
506
+ selectedElement.setAttribute("data-cns-node-selected", "true");
507
+ }
508
+ }
509
+ }
510
+
511
+ document.querySelectorAll("[data-cns-layout-selected]").forEach((element) => {
512
+ if (!layoutSelectedNodeIds.includes(element.getAttribute("data-cns-node-id") || "")) {
513
+ element.removeAttribute("data-cns-layout-selected");
514
+ }
515
+ });
516
+
517
+ document.querySelectorAll("[data-cns-layout-hovered]").forEach((element) => {
518
+ if (element.getAttribute("data-cns-node-id") !== layoutHoveredNodeId) {
519
+ element.removeAttribute("data-cns-layout-hovered");
520
+ }
521
+ });
522
+
523
+ layoutSelectedNodeIds.forEach((nodeId) => {
524
+ const layoutElement = resolveLayoutMeasurementElement(nodeId);
525
+
526
+ if (layoutElement) {
527
+ layoutElement.setAttribute("data-cns-layout-selected", "true");
528
+ }
529
+ });
530
+
531
+ if (layoutHoveredNodeId) {
532
+ const hoveredElement = resolveLayoutMeasurementElement(layoutHoveredNodeId);
533
+
534
+ if (hoveredElement) {
535
+ hoveredElement.setAttribute("data-cns-layout-hovered", "true");
536
+ }
537
+ }
538
+
539
+ if (inlineEditingNodeId) {
540
+ const editingElement = document.querySelector('[data-cns-node-id="' + CSS.escape(inlineEditingNodeId) + '"]');
541
+
542
+ if (editingElement) {
543
+ editingElement.setAttribute("data-cns-inline-editing", "true");
544
+ }
545
+ }
546
+ };
547
+
548
+ const postLayoutMeasurements = (payload) => {
549
+ const nodeIds = Array.isArray(payload?.nodeIds)
550
+ ? payload.nodeIds.filter((value) => typeof value === "string" && value.trim()).map((value) => value.trim())
551
+ : [];
552
+
553
+ const measurements = nodeIds
554
+ .map((nodeId) => {
555
+ const element = resolveLayoutMeasurementElement(nodeId);
556
+
557
+ if (!(element instanceof HTMLElement)) {
558
+ return null;
559
+ }
560
+
561
+ const rect = element.getBoundingClientRect();
562
+ const parentElement = resolveLayoutParentElement(element);
563
+ const parentRect = parentElement?.getBoundingClientRect?.() ?? null;
564
+ const viewportRect = document.documentElement?.getBoundingClientRect?.() ?? null;
565
+ const localLeft = element.offsetLeft;
566
+ const localTop = element.offsetTop;
567
+ const absoluteLeft = viewportRect ? rect.left - viewportRect.left : rect.left;
568
+ const absoluteTop = viewportRect ? rect.top - viewportRect.top : rect.top;
569
+ const parentLeft = parentRect ? rect.left - parentRect.left : localLeft;
570
+ const parentTop = parentRect ? rect.top - parentRect.top : localTop;
571
+
572
+ return {
573
+ nodeId,
574
+ left: absoluteLeft,
575
+ top: absoluteTop,
576
+ width: rect.width,
577
+ height: rect.height,
578
+ localLeft: Number.isFinite(localLeft) ? localLeft : parentLeft,
579
+ localTop: Number.isFinite(localTop) ? localTop : parentTop
580
+ };
581
+ })
582
+ .filter(Boolean);
583
+
584
+ window.parent?.postMessage({
585
+ type: "codingns-static-html-layout-measurements",
586
+ measurements
587
+ }, "*");
588
+ };
589
+
590
+ eventTypes.forEach((eventType) => {
591
+ document.addEventListener(eventType, handler, true);
592
+ });
593
+
594
+ document.addEventListener("pointerover", handlePointerOver, true);
595
+ document.addEventListener("pointerleave", handlePointerLeaveViewport, true);
596
+
597
+ document.addEventListener("pointermove", (event) => {
598
+ if (!layoutModeEnabled || !activeLayoutPointer) {
599
+ return;
600
+ }
601
+
602
+ if (typeof activeLayoutPointer.pointerId === "number" && event.pointerId !== activeLayoutPointer.pointerId) {
603
+ return;
604
+ }
605
+
606
+ window.parent?.postMessage({
607
+ type: "codingns-static-html-layout-pointer",
608
+ phase: "move",
609
+ nodeId: activeLayoutPointer.nodeId,
610
+ clientX: event.clientX,
611
+ clientY: event.clientY
612
+ }, "*");
613
+ }, true);
614
+
615
+ const finishLayoutPointer = (event, phase) => {
616
+ if (!activeLayoutPointer) {
617
+ return;
618
+ }
619
+
620
+ if (typeof activeLayoutPointer.pointerId === "number" && event.pointerId !== activeLayoutPointer.pointerId) {
621
+ return;
622
+ }
623
+
624
+ window.parent?.postMessage({
625
+ type: "codingns-static-html-layout-pointer",
626
+ phase,
627
+ nodeId: activeLayoutPointer.nodeId,
628
+ clientX: event.clientX,
629
+ clientY: event.clientY
630
+ }, "*");
631
+
632
+ activeLayoutPointer = null;
633
+ };
634
+
635
+ document.addEventListener("pointerup", (event) => {
636
+ finishLayoutPointer(event, "end");
637
+ }, true);
638
+
639
+ document.addEventListener("pointercancel", (event) => {
640
+ finishLayoutPointer(event, "cancel");
641
+ }, true);
642
+
643
+ window.addEventListener("message", (event) => {
644
+ const payload = event.data;
645
+
646
+ if (!payload || typeof payload !== "object") {
647
+ return;
648
+ }
649
+
650
+ if (payload.type !== "codingns-static-html-selection-sync") {
651
+ if (payload.type === "codingns-static-html-layout-measure-request") {
652
+ postLayoutMeasurements(payload);
653
+ }
654
+
655
+ return;
656
+ }
657
+
658
+ syncSelectionState(payload);
659
+ });
660
+ })();
661
+ `,t.body.appendChild(o)}else j$(t);return t.documentElement.outerHTML}function A5(e,t){const n=(t==null?void 0:t.trim())??"";if(!n)return;const r=e.head??e.querySelector("head");if(!(r instanceof HTMLHeadElement))return;const i=r.querySelector("base");if(i){i.setAttribute("href",n);return}const o=e.createElement("base");o.setAttribute("href",n),r.insertBefore(o,r.firstChild)}function R5(e){e.querySelectorAll("script").forEach(t=>{t.remove()})}function P5(e,t){var o;const n=e.body;if(!n||!n.getAttribute)return;n.style.width=`${t.canvas.width}px`,n.style.minWidth=`${t.canvas.width}px`,n.style.maxWidth=`${t.canvas.width}px`,n.style.height=`${t.canvas.height}px`,n.style.minHeight=`${t.canvas.height}px`,n.style.maxHeight=`${t.canvas.height}px`;const r=((o=n.style.transform)==null?void 0:o.trim())??"",i=Array.from(e.querySelectorAll("style")).some(l=>{const c=l.textContent??"";return/body\s*\{[\s\S]*?transform\s*:\s*scale\(/i.test(c)});/scale\(/i.test(r)&&!/translate\(/i.test(r)&&(n.style.transform="none"),i?n.setAttribute("data-cns-preview-body-scale-reset","true"):n.removeAttribute("data-cns-preview-body-scale-reset")}function Nf(e,t,n){const r=e.nodes[t];return r?{...e,nodes:{...e.nodes,[t]:n(r)}}:e}function M5(e,t,n){if(t.length===0)return e;const r={...e.nodes};let i=!1;return t.forEach(o=>{const l=r[o];l&&(r[o]=n(l,o),i=!0)}),i?{...e,nodes:r}:e}function E5(e,t){if(!e.nodes[t])return{project:e,duplicatedNodeId:null};const r=_5(e,t);if(!r)return{project:e,duplicatedNodeId:null};const i={...e.nodes},o=w$(e.nodes),l=XC({project:e,sourceNodeId:t,nextNodes:i,idCounter:o,isRoot:!0}),c=i[r];if(!c)return{project:e,duplicatedNodeId:null};const u=c.children.indexOf(t),f=[...c.children];return f.splice(u>=0?u+1:f.length,0,l),i[r]={...c,children:f},{project:{...e,nodes:i},duplicatedNodeId:l}}function L5(e,t){const n=t!=null&&t.insertAfterPageId?e.pages.findIndex(h=>h.id===t.insertAfterPageId):-1,r=n>=0?n+1:e.pages.length,i=WC(e),o=`${i}-root`,l=e.pages[Math.max(0,r-1)]??e.pages[e.pages.length-1]??null,c=BC({id:o,name:a("conversation.fileViewerPresentationUntitled"),sourceRef:null}),u={id:i,order:r,title:a("conversation.fileViewerPresentationUntitled"),frame:(l==null?void 0:l.frame)??{width:e.canvas.width,height:e.canvas.height,background:null},rootNodeId:o,sourceRef:{pageIndex:r,pageSelector:`[data-cns-page-id="${i}"]`,nodePath:[]},runtimeHints:(l==null?void 0:l.runtimeHints)??{hasActiveStateClass:!1,hasDeckShell:!0}},f=[...e.pages];return f.splice(r,0,u),{pageId:i,project:ad({...e,pages:f,nodes:{...e.nodes,[o]:c}})}}function D5(e,t){const n=e.pages.find(h=>h.id===t);if(!n)return{project:e,pageId:null};const r=e.pages.findIndex(h=>h.id===t),i=r>=0?r+1:e.pages.length,o=WC(e),l=`${o}-root`,c={...e.nodes},u=n.sourceRef.pageIndex;QC({project:e,sourceNodeId:n.rootNodeId,targetNodeId:l,nextPageId:o,sourcePageIndex:u,nextNodes:c});const f=[...e.pages];return f.splice(i,0,{...n,id:o,order:i,title:n.title,rootNodeId:l,sourceRef:{...n.sourceRef}}),{pageId:o,project:ad({...e,pages:f,nodes:c})}}function O5(e,t){var u,f;if(e.pages.length<=1)return{project:e,nextPageId:((u=e.pages[0])==null?void 0:u.id)??null};const n=e.pages.find(h=>h.id===t);if(!n)return{project:e,nextPageId:((f=e.pages[0])==null?void 0:f.id)??null};const r=e.pages.findIndex(h=>h.id===t),i=e.pages.filter(h=>h.id!==t),o={...e.nodes};DC(o,n.rootNodeId);const l=ad({...e,pages:i,nodes:o}),c=l.pages[Math.min(r,l.pages.length-1)]??null;return{project:l,nextPageId:(c==null?void 0:c.id)??null}}function F5(e,t,n){const r=e.pages.findIndex(c=>c.id===t);if(r<0)return{project:e,pageId:null};const i=Math.max(0,Math.min(n,e.pages.length-1));if(r===i)return{project:e,pageId:t};const o=[...e.pages],[l]=o.splice(r,1);return l?(o.splice(i,0,l),{project:ad({...e,pages:o}),pageId:t}):{project:e,pageId:null}}function Tf(e,t){const n=e.pages.find(i=>i.id===t);if(!n)return[];const r=[];return LC(e,n.rootNodeId,r,!0),r}function LC(e,t,n,r=!1){const i=e.nodes[t];i&&(r||n.push(t),i.children.forEach(o=>{LC(e,o,n)}))}function _5(e,t){var n;return((n=Object.values(e.nodes).find(r=>r.children.includes(t)))==null?void 0:n.id)??null}function B5(e){var u;const{document:t,project:n}=e,r=[...e.pageElements],i=(u=r[0])==null?void 0:u.parentElement;if(!i)return;const o=r[r.length-1]??t.body.firstElementChild,l=new Set;n.pages.map((f,h)=>{const m=Y5(t,r,f);if(m&&!l.has(m))return l.add(m),Vy(m,f,!1,h),m;const g=J5(t,m??o,f,h,!!m);return g?(Vy(g,f,!0,h),g):null}).filter(f=>f instanceof Element).forEach(f=>{i.appendChild(f)}),r.forEach(f=>{l.has(f)||f.remove()})}function DC(e,t){const n=e[t];n&&(n.children.forEach(r=>{DC(e,r)}),delete e[t])}function ad(e){return W5(e)}function W5(e){const t={...e.nodes};return{...e,pages:e.pages.map((n,r)=>{var i;return OC(t,n.rootNodeId,r),{...n,order:r,title:(i=n.title)!=null&&i.trim()?n.title:a("conversation.fileViewerPresentationUntitled"),sourceRef:{...n.sourceRef,pageIndex:r}}}),nodes:t}}function OC(e,t,n){const r=e[t];r&&(r.sourceRef&&(e[t]={...r,sourceRef:{...r.sourceRef,pageIndex:n}}),r.children.forEach(i=>{OC(e,i,n)}))}function yp(e){return new DOMParser().parseFromString(e,"text/html")}function Au(e,t){if(t){const n=$5(t),r=Array.from(e.querySelectorAll(n));if(r.length>0)return{strategy:t,elements:r}}return PC.map(n=>({strategy:n.strategy,elements:Array.from(e.querySelectorAll(n.selector))})).find(n=>n.elements.length>0)??null}function If(e){return{supported:!1,reason:e,mode:"presentation",strategy:null,pages:[],warnings:[],viewport:{width:ao.width,height:ao.height}}}function $5(e){var t;return((t=PC.find(n=>n.strategy===e))==null?void 0:t.selector)??"section.slide"}function z5(e,t){var o,l;const n=(o=e.getAttribute("data-title"))==null?void 0:o.trim();if(n)return n;const r=e.querySelector("h1, h2, h3, .slide-title, .title, .page-title"),i=(l=r==null?void 0:r.textContent)==null?void 0:l.replace(/\s+/g," ").trim();return i||`第 ${t+1} 页`}function FC(e,t){const n=e.getAttribute("data-title");return n?`.slide[data-title="${Uy(n)}"]`:e.id?`#${Uy(e.id)}`:`.slide:nth-of-type(${t+1})`}function Uy(e){return e.replace(/"/g,'\\"')}function H5(e,t){const n=Array.from(e.querySelectorAll("style")).map(l=>l.textContent??"").join(`
662
+ `),r=qy(n,"--deck-width"),i=qy(n,"--deck-height");if(r&&i)return{width:r,height:i};const o=U5(n);return o||{width:ao.width,height:ao.height}}function U5(e){const t=q5(e,".slide"),n=Eo(e,".slide","width"),r=Eo(e,".slide","height"),i=Eo(e,".slide","max-height");if(n&&r)return{width:n,height:r};if(n&&t)return{width:n,height:Math.round(n/t)};if(i&&t)return{width:Math.round(i*t),height:i};const o=Eo(e,".deck","width"),l=Eo(e,".deck","height");return o&&l?{width:o,height:l}:null}function qy(e,t){const n=new RegExp(`(?:^|[\\s;{])${il(t)}\\s*:\\s*(\\d{3,5})px`,"i").exec(e);return n?Number(n[1]):null}function Eo(e,t,n){const r=_C(e,t);if(!r)return null;const i=new RegExp(`(?:^|[\\s;])${il(n)}\\s*:\\s*(\\d{3,5})px`,"i").exec(r);if(i)return Number(i[1]);const o=new RegExp(`(?:^|[\\s;])${il(n)}\\s*:\\s*min\\(\\s*(\\d{3,5})px\\s*,`,"i").exec(r);if(o)return Number(o[1]);const l=new RegExp(`(?:^|[\\s;])${il(n)}\\s*:\\s*calc\\(\\s*100v[wh]\\s*-\\s*(\\d{1,4})px\\s*\\)`,"i").exec(r);return l?n.includes("height")?ao.height-Number(l[1]):ao.width-Number(l[1]):null}function q5(e,t){const n=_C(e,t);if(!n)return null;const r=/aspect-ratio\s*:\s*(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)/i.exec(n);if(!r)return null;const i=Number(r[1]),o=Number(r[2]);return!i||!o?null:i/o}function _C(e,t){const n=new RegExp(`${il(t)}\\s*\\{([\\s\\S]*?)\\}`,"i").exec(e);return(n==null?void 0:n[1])??null}function il(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function V5(e){const t=ld(e);if(t.length===1){const r=t[0];if(r&&!s$(r))return r}for(const r of S5){const i=e.querySelector(r);if(i)return i.parentElement===e&&t.length>1?e:i}const n=e.querySelector(".head + .content");return n||e}function K5(e,t){if(e===t)return[];const n=[];let r=t;for(;r&&r!==e;){const i=r.parentElement;if(!i)return[];const l=Array.from(i.children).indexOf(r);if(l<0)return[];n.unshift(l),r=i}return n}function od(e){if(e.matches(MC)||e.getAttribute("aria-hidden")==="true")return!0;const t=typeof e.className=="string"?e.className:"";return/(^|\s)(page|progress|ctrl|nav|particle|glow)(\s|$)/i.test(t)}function Hh(e){const{containerElement:t,containerPath:n,pageIndex:r,pageSelector:i,parentNodeId:o,nodeIdPrefix:l,nodes:c,assets:u}=e;Array.from(t.children).forEach((h,m)=>{var x;if(od(h))return;const g=[...n,m];if(VC(h)){Hh({...e,containerElement:h,containerPath:g,parentNodeId:o,nodeIdPrefix:l});return}const p=`${l}-node-${g.join("-")||"root"}`,b=G5({element:h,pageIndex:r,pageSelector:i,nodePath:g,nodeId:p,assets:u});if(!b)return;const y=[...b.runtimeFlags];t.hasAttribute("data-cns-layout-freeze")&&!y.includes("layout-freeze-child")&&y.push("layout-freeze-child"),h.hasAttribute("data-cns-layout-freeze")&&!y.includes("layout-freeze-container")&&y.push("layout-freeze-container"),c[b.id]=y.length===b.runtimeFlags.length?b:{...b,runtimeFlags:y},(x=c[o])==null||x.children.push(b.id),b.type==="group"&&Hh({...e,containerElement:h,containerPath:g,parentNodeId:b.id,nodeIdPrefix:b.id})})}function G5(e){const{element:t,pageIndex:n,pageSelector:r,nodePath:i,nodeId:o,assets:l}=e,c={pageIndex:n,pageSelector:r,nodePath:i},u=ld(t);if(t.tagName==="IMG"){const h=t.getAttribute("src")??"",m=t.getAttribute("alt")??"";return h&&l.push({id:`asset-${wp(h)}`,type:"image",src:h}),{id:o,type:"image",name:m||"图片",editable:!0,lockedReason:null,box:Vo(t),style:Ua(t),content:{src:h,alt:m},children:[],sourceRef:c,patchStrategy:"replace_node",runtimeFlags:[]}}if(t.tagName==="SVG"||t.querySelector(":scope > svg"))return{id:o,type:"svg",name:"SVG",editable:!1,lockedReason:"复杂 SVG 先按只读节点导入",box:Vo(t),style:Ua(t),content:{html:t.outerHTML},children:[],sourceRef:c,patchStrategy:"replace_node",runtimeFlags:["readonly"]};if(gp.has(t.tagName)||UC(t)||n$(t,u))return Af(o,t,c);if(!u.length){const h=Af(o,t,c);if(h)return h}if(u.length>0||o$(t))return{id:o,type:"group",name:Ky(t),editable:!0,lockedReason:null,box:Vo(t),style:Ua(t),content:{},children:[],sourceRef:c,patchStrategy:"style_only",runtimeFlags:[]};const f=t.outerHTML.trim();return f?{id:o,type:"html",name:Ky(t),editable:!1,lockedReason:"复杂 HTML 片段先按只读节点导入",box:Vo(t),style:Ua(t),content:{html:f},children:[],sourceRef:c,patchStrategy:"replace_node",runtimeFlags:["readonly"]}:null}function Af(e,t,n){const r=r$(t),i=xp(r);return i?$C({id:e,name:i.slice(0,20),text:i,runs:r,sourceRef:n,style:Ua(t),box:Vo(t),preserveStructure:a$(t)}):null}function BC(e){return{id:e.id,type:"group",name:e.name,editable:!0,lockedReason:null,box:zC(),style:{},content:{},children:[],sourceRef:e.sourceRef,patchStrategy:"style_only",runtimeFlags:e.runtimeFlags??[]}}function WC(e){return`page-${e.pages.reduce((n,r)=>{const i=/^page-(\d+)$/.exec(r.id);return i?Math.max(n,Number.parseInt(i[1]??"0",10)):n},0)+1}`}function Y5(e,t,n){var o;const r=(o=n.sourceRef.pageSelector)==null?void 0:o.trim();if(r){const l=Array.from(e.querySelectorAll(r)).filter(c=>t.includes(c));if(l.length===1&&l[0]instanceof Element)return l[0];if(/^\[data-cns-page-id=/.test(r))return null}const i=t[n.sourceRef.pageIndex]??null;return i instanceof Element?i:null}function J5(e,t,n,r,i=!1){var u,f;if(i&&t instanceof Element){const h=t.cloneNode(!0);if(h instanceof Element)return h}const o=e.createElement(((u=t==null?void 0:t.tagName)==null?void 0:u.toLowerCase())||"section");t instanceof Element?X5(t,o):o.className="slide";const l=e.createElement("div");l.className=Q5(t);const c=e.createElement("h1");return c.textContent=((f=n.title)==null?void 0:f.trim())||a("conversation.fileViewerPresentationUntitled"),l.appendChild(c),o.appendChild(l),o}function Vy(e,t,n,r){var l,c;const i=((l=t.title)==null?void 0:l.trim())||a("conversation.fileViewerPresentationUntitled");e.setAttribute("data-title",i),e.setAttribute("data-cns-page-id",t.id),e.setAttribute("data-cns-page-order",String(r));const o=e.querySelector("h1, h2, h3, .slide-title, .title, .page-title");o&&(n||!((c=o.textContent)!=null&&c.trim()))&&(o.textContent=i)}function X5(e,t){Array.from(e.attributes).forEach(n=>{n.name==="data-title"||n.name.startsWith("data-cns-")||t.setAttribute(n.name,n.value)})}function Q5(e){const t=e==null?void 0:e.querySelector(".slide-shell, .panel, .content, .slide-inner");return(typeof(t==null?void 0:t.className)=="string"?t.className.trim():"")||"slide-shell"}function $C(e){const t=!!e.preserveStructure||Array.isArray(e.runs)&&e.runs.some(n=>n.tagName||n.className||n.sourceKind==="element");return{id:e.id,type:"text",name:e.name,editable:!0,lockedReason:null,box:e.box??zC(),style:e.style??{},content:{text:e.text,runs:e.runs??null},children:[],sourceRef:e.sourceRef,patchStrategy:"text_and_style",runtimeFlags:t?["preserve-text-structure"]:[]}}function zC(){return{x:0,y:0,width:0,height:0,zIndex:0}}function Ua(e){const t=HC(e);return{position:t.get("position")??null,fontFamily:t.get("font-family")??null,fontSize:Ko(t.get("font-size")),fontWeight:t.get("font-weight")??null,fontStyle:t.get("font-style")??null,lineHeight:t.get("line-height")??null,letterSpacing:t.get("letter-spacing")??null,color:t.get("color")??null,textAlign:t.get("text-align")??null,textDecoration:t.get("text-decoration")??null,textDecorationColor:t.get("text-decoration-color")??null,whiteSpace:t.get("white-space")??null,padding:t.get("padding")??null,margin:t.get("margin")??null,borderRadius:t.get("border-radius")??null,borderWidth:t.get("border-width")??null,borderColor:t.get("border-color")??null,backgroundColor:t.get("background-color")??null,opacity:Z5(t.get("opacity"))}}function Vo(e){const t=HC(e);return{x:Ko(t.get("left"))??0,y:Ko(t.get("top"))??0,width:Ko(t.get("width"))??0,height:Ko(t.get("height"))??0,zIndex:e$(t.get("z-index"))??0}}function HC(e){const t=(e.getAttribute("style")??"").trim(),n=new Map;return t&&t.split(";").forEach(r=>{const[i,o]=r.split(":");!i||!o||n.set(i.trim(),o.trim())}),n}function Ko(e){if(!e)return null;const t=/(-?\d+(?:\.\d+)?)px/i.exec(e);return t?Number(t[1]):null}function Z5(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?t:null}function e$(e){if(!e)return null;const t=Number.parseInt(e,10);return Number.isFinite(t)?t:null}function UC(e){return e.tagName!=="SPAN"?!1:!!Dl(e.textContent??"")&&e.children.length===0}function ld(e){return Array.from(e.children).filter(t=>!od(t))}function qC(e){return Array.from(e.childNodes).some(t=>t.nodeType!==Node.TEXT_NODE?!1:!!oo(t.textContent??""))}const t$=new Set(["SPAN","STRONG","B","I","EM","U","SMALL","MARK","SUB","SUP","CODE","A","BR"]);function n$(e,t){return Ru(e,t)>0}function s$(e){return Ru(e)>0}function Ru(e,t){if(!Dl(e.textContent??""))return 0;if(gp.has(e.tagName))return 500;if(UC(e))return 460;const r=t??ld(e);return r.length===0?420:r.every(o=>cd(o))&&qC(e)?360:0}function VC(e){if(od(e)||Ru(e)>0)return!1;const t=ld(e);if(t.length!==1||qC(e))return!1;const n=t[0];return n?Ru(n)>0?!0:VC(n):!1}function cd(e){return!!(t$.has(e.tagName)||e.tagName==="SPAN"&&e.children.length===0)}function r$(e){const t=[];return KC(e,t,e),i$(t)}function KC(e,t,n){if(n.nodeType===Node.TEXT_NODE){const r=n.textContent??"";if(!kp(r))return;const i=oo(r);i&&t.push({text:i,sourceKind:"text"});return}if(n instanceof Element&&!(od(n)&&n!==e)){if(n!==e&&cd(n)){const r=oo(n.textContent??"");r&&t.push({text:r,tagName:n.tagName.toLowerCase(),className:typeof n.className=="string"&&n.className.trim()?n.className.trim():null,style:Ua(n),sourceKind:"element"});return}n.childNodes.forEach(r=>{KC(e,t,r)})}}function i$(e){return e.map(n=>{const r=oo(n.text);return r?{text:r,tagName:n.tagName??null,className:n.className??null,style:n.style??null,sourceKind:n.sourceKind??null}:null}).filter(n=>n!==null)}function xp(e){return Dl(e.map(t=>t.text).join(" "))}function a$(e){if(e.querySelector("br"))return!0;let t=0;return e.childNodes.forEach(n=>{if(n.nodeType===Node.TEXT_NODE){kp(n.textContent??"")&&(t+=1);return}n instanceof Element&&n.tagName!=="BR"&&cd(n)&&oo(n.textContent??"")&&(t+=1)}),t>1}function o$(e){const t=typeof e.className=="string"?e.className.toLowerCase():"";return C5.some(n=>t.includes(n))}function Ky(e){const t=typeof e.className=="string"?e.className.trim():"";return t?t.split(/\s+/)[0]??e.tagName.toLowerCase():e.tagName.toLowerCase()}function Dl(e){return e.replace(/\s+/g," ").trim()}function oo(e){return e.replace(/\r\n/g,`
663
+ `).replace(/[^\S\r\n]+/g," ")}function kp(e){return!e||!/\S/.test(e)?!1:!/^[\n\r\t ]+$/.test(e)}function GC(e){return Array.from(new Set(e))}function l$(e){const t=new Map;return e.forEach(n=>{t.set(n.id,n)}),Array.from(t.values())}function c$(e){return`static-html-${wp(e)}`}function YC(e,t){const n=e[t.pageIndex];if(!n)return null;let r=n;for(const i of t.nodePath){const o=r.children.item(i);if(!(o instanceof Element))return null;r=o}return r}function JC(e,t){switch(t.type){case"text":Array.isArray(t.content.runs)&&t.content.runs.length>0?u$(e,t.content.runs,{preserveStructure:lo(t,"preserve-text-structure")}):typeof t.content.text=="string"&&(e.textContent=t.content.text);break;case"image":typeof t.content.src=="string"&&t.content.src&&e.setAttribute("src",t.content.src),typeof t.content.alt=="string"&&e.setAttribute("alt",t.content.alt);break;default:!t.children.length&&typeof t.content.text=="string"&&t.content.text&&(e.textContent=t.content.text);break}ud(e,t.style),b$(e,t),y$(e,t)}function u$(e,t,n){if(n!=null&&n.preserveStructure&&d$(e,t))return;const r=e.ownerDocument;if(!r){e.textContent=xp(t);return}for(;e.firstChild;)e.removeChild(e.firstChild);t.forEach(i=>{if(!i.text)return;if(!i.tagName){e.appendChild(r.createTextNode(i.text));return}const o=r.createElement(i.tagName);i.className&&o.setAttribute("class",i.className),o.textContent=i.text,ud(o,i.style??{}),e.appendChild(o)})}function d$(e,t){if(Dl(e.textContent??"")===xp(t))return!0;const n=f$(t);if(!n.length)return!1;const r=h$(e);if(!r.length||r.length!==n.length)return!1;for(let i=0;i<r.length;i+=1){const o=r[i],l=n[i];if(!o||!l||o.kind!==l.kind||o.kind==="element"&&((o.tagName??null)!==(l.tagName??null)||(o.className??null)!==(l.className??null)))return!1}return r.forEach((i,o)=>{const l=n[o];if(l){if(i.kind==="text"&&i.node.nodeType===Node.TEXT_NODE){i.node.textContent=l.text;return}i.node instanceof Element&&(i.node.textContent=l.text,ud(i.node,l.style??{}))}}),!0}function f$(e){return e.map(t=>{const n=t.text??"";return n?{kind:t.tagName||t.className||t.sourceKind==="element"?"element":"text",text:n,tagName:t.tagName??null,className:t.className??null,style:t.style??null}:null}).filter(t=>!!t)}function h$(e){const t=[];return e.childNodes.forEach(n=>{if(n.nodeType===Node.TEXT_NODE){const i=n.textContent??"";if(!kp(i))return;t.push({kind:"text",node:n,tagName:null,className:null});return}!(n instanceof Element)||n.tagName==="BR"||!cd(n)||!oo(n.textContent??"")||t.push({kind:"element",node:n,tagName:n.tagName.toLowerCase(),className:typeof n.className=="string"&&n.className.trim()?n.className.trim():null})}),t}function m$(e,t,n){if(t.type!=="text"||!p$(e,t))return;const r=typeof t.content.text=="string"?t.content.text:Dl(e.textContent??""),i=Array.isArray(t.content.runs)?t.content.runs:[];if(!r)return;const o=e.ownerDocument;if(!o)return;const l=o.createElement("span");for(l.setAttribute("data-cns-text-proxy","true"),l.setAttribute("data-cns-node-id",t.id),e.setAttribute("data-cns-node-host","true"),e.setAttribute("data-cns-node-host-id",t.id),e.removeAttribute("data-cns-node-id"),n.selected&&(l.setAttribute("data-cns-node-selected","true"),e.removeAttribute("data-cns-node-selected")),l.setAttribute("style",["display: inline","background: transparent","border: none","padding: 0","margin: 0","white-space: inherit","color: inherit","font: inherit","letter-spacing: inherit","line-height: inherit","text-transform: inherit"].join("; ")),i.length>1?i.forEach((c,u)=>{const f=o.createElement(c.tagName||"span");f.setAttribute("data-cns-node-id",t.id),f.setAttribute("data-cns-run-index",String(u)),c.className&&f.setAttribute("class",c.className),n.selected&&n.selectedRunIndex===u&&f.setAttribute("data-cns-node-selected","true"),f.textContent=c.text,ud(f,c.style??{}),l.appendChild(f)}):l.textContent=r;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(l)}function p$(e,t){return e.childElementCount>0||gp.has(e.tagName)?!1:g$(t.style)}function g$(e){return!!(e.backgroundColor||e.padding||e.borderRadius||e.borderWidth||e.borderColor)}function ud(e,t){for(const[n,r]of Object.entries(t)){const i=j5[n];if(i){if(r==null||r===""){e instanceof HTMLElement?e.style.removeProperty(i):e.setAttribute("style",(e.getAttribute("style")??"").trim());continue}e.setAttribute("style",aa(e.getAttribute("style")??"",i,x$(n,r)))}}}function b$(e,t){if(!(lo(t,"draft-clone")||lo(t,"draft-box")))return;const r=e.getAttribute("style")??"";let i=aa(r,"position","absolute");i=aa(i,"left",`${t.box.x}px`),i=aa(i,"top",`${t.box.y}px`),t.box.width>0&&(i=aa(i,"width",`${t.box.width}px`)),t.box.height>0&&(i=aa(i,"height",`${t.box.height}px`)),t.box.zIndex!==0&&(i=aa(i,"z-index",String(t.box.zIndex))),e.setAttribute("style",i)}function y$(e,t){if(lo(t,"layout-freeze-container")){e.setAttribute("data-cns-layout-freeze","true");return}e.removeAttribute("data-cns-layout-freeze")}function aa(e,t,n){const r=new Map;return e.split(";").forEach(i=>{const[o,l]=i.split(":");!o||!l||r.set(o.trim(),l.trim())}),r.set(t,n),Array.from(r.entries()).map(([i,o])=>`${i}: ${o}`).join("; ")}function x$(e,t){return e==="fontSize"&&typeof t=="number"?`${t}px`:String(t)}function wp(e){let t=0;for(let n=0;n<e.length;n+=1)t=t*31+e.charCodeAt(n)>>>0;return t.toString(16)}function XC(e){const t=e.project.nodes[e.sourceNodeId];if(!t)return e.sourceNodeId;const n=k$(t.id,e.idCounter),r=`clone-source:${t.id}`,i=GC([...t.runtimeFlags.filter(c=>!c.startsWith("clone-source:")),"draft-clone",e.isRoot?"draft-clone-root":"draft-clone-child",r]),o={...t,id:n,name:`${t.name} 副本`,sourceRef:t.sourceRef,box:{...t.box,x:t.box.x+24,y:t.box.y+24},children:[],runtimeFlags:i};e.nextNodes[n]=o;const l=t.children.map(c=>XC({project:e.project,sourceNodeId:c,nextNodes:e.nextNodes,idCounter:e.idCounter,isRoot:!1}));return e.nextNodes[n]={...o,children:l},n}function QC(e){const t=e.project.nodes[e.sourceNodeId];if(!t)return e.targetNodeId;const n={...t,id:e.targetNodeId,sourceRef:t.sourceRef?{...t.sourceRef,pageIndex:e.sourcePageIndex}:null,children:[],runtimeFlags:t.runtimeFlags.filter(i=>i!=="draft-clone"&&i!=="draft-clone-root"&&i!=="draft-clone-child"&&!i.startsWith("clone-source:"))};e.nextNodes[e.targetNodeId]=n;const r=t.children.map((i,o)=>QC({project:e.project,sourceNodeId:i,targetNodeId:`${e.targetNodeId}-node-${o}`,nextPageId:e.nextPageId,sourcePageIndex:e.sourcePageIndex,nextNodes:e.nextNodes}));return e.nextNodes[e.targetNodeId]={...n,children:r},e.targetNodeId}function k$(e,t){const n=(t[e]??0)+1;return t[e]=n,`${e}-copy-${n}`}function w$(e){const t={};return Object.keys(e).forEach(n=>{const r=/^(.*)-copy-(\d+)$/.exec(n);if(!r)return;const i=r[1],o=Number.parseInt(r[2]??"0",10);!i||!Number.isFinite(o)||(t[i]=Math.max(t[i]??0,o))}),t}function v$(e){const t=C$(e.cloneRootNode);if(!t)return;const n=e.project.nodes[t];if(!(n!=null&&n.sourceRef))return;const r=YC(e.pageElements,n.sourceRef);if(!(r!=null&&r.parentElement))return;const i=r.cloneNode(!0);i instanceof Element&&(r.parentElement.insertBefore(i,r.nextSibling),ZC({project:e.project,cloneNodeId:e.cloneRootNode.id,cloneElement:i,sourceRootPath:n.sourceRef.nodePath,selectedNodeId:e.selectedNodeId,mode:e.mode}))}function ZC(e){const t=e.project.nodes[e.cloneNodeId];t&&(e.cloneElement.setAttribute("data-cns-node-id",t.id),e.mode==="preview"?(e.cloneElement.removeAttribute("data-cns-node-selected"),e.selectedNodeId&&t.id===e.selectedNodeId&&e.cloneElement.setAttribute("data-cns-node-selected","true")):e.cloneElement.removeAttribute("data-cns-node-selected"),JC(e.cloneElement,t),t.children.forEach(n=>{const r=e.project.nodes[n];if(!(r!=null&&r.sourceRef))return;const i=r.sourceRef.nodePath.slice(e.sourceRootPath.length),o=S$(e.cloneElement,i);o&&ZC({project:e.project,cloneNodeId:n,cloneElement:o,sourceRootPath:e.sourceRootPath,selectedNodeId:e.selectedNodeId,mode:e.mode})}))}function S$(e,t){let n=e;for(const r of t){const i=n.children.item(r);if(!(i instanceof Element))return null;n=i}return n}function lo(e,t){return e.runtimeFlags.includes(t)}function C$(e){const t=e.runtimeFlags.find(n=>n.startsWith("clone-source:"));return t?t.slice(13):null}function j$(e){e.querySelectorAll("[data-cns-page-root]").forEach(t=>{t.removeAttribute("data-cns-page-root"),t.removeAttribute("data-cns-active-page")}),e.querySelectorAll("[data-cns-text-proxy]").forEach(t=>{const n=t.parentElement;if(!n){t.remove();return}n.textContent=t.textContent??"",n.removeAttribute("data-cns-node-host"),n.removeAttribute("data-cns-node-host-id")}),e.querySelectorAll("[data-cns-node-id]").forEach(t=>{t.removeAttribute("data-cns-node-id")}),e.querySelectorAll("[data-cns-node-selected]").forEach(t=>{t.removeAttribute("data-cns-node-selected")}),e.querySelectorAll("[data-cns-inline-editing]").forEach(t=>{t.removeAttribute("data-cns-inline-editing")}),e.querySelectorAll("[data-cns-node-host]").forEach(t=>{t.removeAttribute("data-cns-node-host"),t.removeAttribute("data-cns-node-host-id")}),e.querySelectorAll("[data-cns-page-id]").forEach(t=>{t.removeAttribute("data-cns-page-id"),t.removeAttribute("data-cns-page-order")}),e.querySelectorAll("style").forEach(t=>{var n;(n=t.textContent)!=null&&n.includes("[data-cns-page-root")&&t.remove()}),e.querySelectorAll('script[data-cns-preview-bridge="true"]').forEach(t=>{t.remove()})}const Nc=24;function xs(e){return{x:Number.isFinite(e.x)?Math.round(e.x):0,y:Number.isFinite(e.y)?Math.round(e.y):0,width:Math.max(Nc,Number.isFinite(e.width)?Math.round(e.width):Nc),height:Math.max(Nc,Number.isFinite(e.height)?Math.round(e.height):Nc),zIndex:Number.isFinite(e.zIndex)?Math.round(e.zIndex):0}}function N$(e,t){const n=xs(t),r=e.runtimeFlags.includes("draft-box")?e.runtimeFlags:[...e.runtimeFlags,"draft-box"];return{...e,box:n,runtimeFlags:r}}function Rf(e,t){const n={...e.nodes};return Object.entries(t).forEach(([r,i])=>{const o=n[r];o&&(n[r]=N$(o,i))}),{...e,nodes:n}}function T$(e,t){const n=Object.entries(e);if(n.length===0)return{};const r=I$(n.map(([,o])=>o),t),i={};return n.forEach(([o,l])=>{const c=xs(l);if(t==="left"){i[o]={...c,x:r};return}if(t==="right"){i[o]={...c,x:r-c.width};return}if(t==="top"){i[o]={...c,y:r};return}i[o]={...c,y:r-c.height}}),i}function I$(e,t){return t==="left"?Math.min(...e.map(n=>n.x)):t==="right"?Math.max(...e.map(n=>n.x+n.width)):t==="top"?Math.min(...e.map(n=>n.y)):Math.max(...e.map(n=>n.y+n.height))}function A$(e){if(e.length===0)return null;const t=Math.min(...e.map(o=>o.x)),n=Math.min(...e.map(o=>o.y)),r=Math.max(...e.map(o=>o.x+o.width)),i=Math.max(...e.map(o=>o.y+o.height));return xs({x:t,y:n,width:r-t,height:i-n,zIndex:Math.max(...e.map(o=>o.zIndex))})}function Gy(e){return{verticals:[e.x,e.x+e.width/2,e.x+e.width],horizontals:[e.y,e.y+e.height/2,e.y+e.height]}}const R$=4;function P$({filePath:e,html:t,baseHref:n,onProjectChange:r,onSave:i,canSave:o=!1,saving:l=!1}){const c=d.useMemo(()=>bp(t,e),[e,t]),u=d.useMemo(()=>N5({html:t,filePath:e}),[e,t]),[f,h]=d.useState(u),[m,g]=d.useState(0),[p,b]=d.useState("content"),[y,x]=d.useState(null),[k,C]=d.useState([]),[j,H]=d.useState(null),[_,T]=d.useState(null),[P,z]=d.useState([]),[L,R]=d.useState(null),[K,E]=d.useState(null),[D,te]=d.useState(null),V=d.useRef(null),ee=d.useRef(null),U=d.useRef(null),he=d.useRef(null),X=d.useRef(null),I=d.useRef(null),xe=d.useRef(u),le=d.useRef(1),M=d.useRef(null),de=d.useRef({}),Ne=d.useRef(null),[ye,Be]=d.useState(1),[We,Ce]=d.useState(1),[ke,we]=d.useState({}),[se,ce]=d.useState({}),[Y,Te]=d.useState([]),[pe,fe]=d.useState(null),W=f,Me=(W==null?void 0:W.pages[m])??(W==null?void 0:W.pages[0])??null,je=d.useMemo(()=>!W||!Me?[]:Tf(W,Me.id),[Me,W]);d.useEffect(()=>{h(u),g(0),b("content"),x(null),C([]),H(null),T(null),z([]),R(null),E(null),te(null),we({}),ce({}),Te([]),fe(null),Ne.current=null},[u]),d.useEffect(()=>{r==null||r(f)},[f,r]),d.useEffect(()=>{xe.current=f},[f]),d.useEffect(()=>{le.current=ye},[ye]),d.useEffect(()=>{const q=X.current,re=I.current;if(!q||!re){Ce(1);return}const ue=()=>{const Se=q.clientWidth,Ke=q.clientHeight,De=re.scrollWidth,He=re.scrollHeight;if(Se<=0||Ke<=0||De<=0||He<=0){Ce(1);return}const lt=Se/De,wt=Ke/He,it=Math.min(1,lt,wt);Ce(Ze=>Math.abs(Ze-it)<.01?Ze:it)};if(ue(),typeof ResizeObserver>"u")return;const Re=new ResizeObserver(()=>{ue()});return Re.observe(q),Re.observe(re),()=>{Re.disconnect()}},[p,y,k,_]),d.useEffect(()=>{M.current=pe},[pe]),d.useEffect(()=>{de.current=se},[se]),d.useEffect(()=>{if(!W||!Me){x(null),C([]),H(null),T(null);return}const q=je.find(ue=>{var Re;return(Re=W.nodes[ue])==null?void 0:Re.editable})??null,re=k.filter(ue=>je.includes(ue));re.length!==k.length&&C(re),j&&!je.includes(j)&&H(null),!(y&&je.includes(y))&&(x(q),C(q?[q]:[]),T(null))},[Me,W,j,je,y,k]);const Q=y&&W?W.nodes[y]??null:null,ge=p==="content"&&(Q==null?void 0:Q.type)==="html"?null:Q,Oe=d.useMemo(()=>k.map(q=>(W==null?void 0:W.nodes[q])??null).filter(q=>!!q),[W,k]),$e=d.useMemo(()=>W?T5({html:t,project:W,pageIndex:m,baseHref:n??null}):null,[n,m,W,t]);d.useEffect(()=>{!he.current||!D||(Yy(he.current,D.text),L$(he.current))},[D==null?void 0:D.nodeId]),d.useEffect(()=>{!he.current||!D||Yy(he.current,D.text)},[D==null?void 0:D.text]),d.useEffect(()=>{if(!$e||!W)return;const q=re=>{const ue=re.data;if(!ue||typeof ue!="object")return;if(ue.type==="codingns-static-html-layout-pointer"){const He=typeof ue.phase=="string"?ue.phase:"",lt=typeof ue.nodeId=="string"?ue.nodeId.trim():"",wt=typeof ue.clientX=="number"?ue.clientX:Number.NaN,it=typeof ue.clientY=="number"?ue.clientY:Number.NaN;if(!lt||!Number.isFinite(wt)||!Number.isFinite(it))return;if(He==="start"){if(p!=="layout")return;const Ht=W.nodes[lt],gt=Li(Ht),dt=!!ue.metaKey||!!ue.ctrlKey?k.includes(lt)?k:[...k,lt]:[lt];if(x(lt),C(dt),T(null),te(null),!gt.movable)return;const ft=Object.fromEntries(dt.map(cn=>{const qt=W.nodes[cn];return qt?[cn,oi(qt,ke[cn])]:null}).filter(cn=>!!cn)),en=Object.fromEntries(je.map(cn=>{const qt=W.nodes[cn];return qt?[cn,oi(qt,ke[cn])]:null}).filter(cn=>!!cn));fe({source:"iframe",handle:"move",nodeIds:dt,pointerStartX:wt,pointerStartY:it,activated:!1,startProject:W,startPageIndex:m,pageNodeIds:je,referenceBoxes:en,startSelectedNodeId:y,startSelectedNodeIds:k,originBoxes:ft});return}const Ze=M.current;if(!Ze||Ze.source!=="iframe")return;if(He==="move"){xt(Ze,wt,it);return}if(He==="end"||He==="cancel"){rt(Ze);return}return}if(ue.type==="codingns-static-html-layout-hover"){if(p!=="layout")return;const He=typeof ue.nodeId=="string"?ue.nodeId.trim():"";H(He||null);return}if(ue.type!=="codingns-static-html-node-select")return;const Re=typeof ue.nodeId=="string"?ue.nodeId.trim():"",Se=typeof ue.runIndex=="number"&&Number.isInteger(ue.runIndex)?ue.runIndex:null;if(!Re||!W.nodes[Re])return;const Ke=W.pages.findIndex(He=>Tf(W,He.id).includes(Re));Ke>=0&&Ke!==m&&g(Ke);const De=W.nodes[Re];if(De){if(p==="layout"){if(De.type==="html")return;const He=Li(De);if(He.movable||He.resizable||He.alignable){const lt=ue.eventType==="click"&&(!!ue.metaKey||!!ue.ctrlKey);C(wt=>{if(!lt)return[Re];if(wt.includes(Re)){const it=wt.filter(Ze=>Ze!==Re);return it.length>0?it:[Re]}return[...wt,Re]})}x(Re),T(null),te(null);return}if(De.type!=="html"){if(x(Re),C([Re]),T(Se),ue.eventType==="dblclick"){const He=Array.isArray(De==null?void 0:De.content.runs)&&De.content.runs.length>1,lt=(De==null?void 0:De.editable)&&(De.type==="text"||typeof De.content.text=="string"),wt=M$(ue.rect)?ue.rect:null;if(lt&&wt&&!He&&Se===null){const it={nodeId:Re,text:De.content.text??"",rect:wt,appearance:E$(ue.appearance,De.style)};te(it);return}}te(null)}}};return window.addEventListener("message",q),()=>{window.removeEventListener("message",q)}},[m,W,p,ke,$e,y,k]),d.useEffect(()=>{var re;const q=(re=V.current)==null?void 0:re.contentWindow;q&&q.postMessage({type:"codingns-static-html-selection-sync",selectedNodeId:y,selectedRunIndex:_,inlineEditingNodeId:(D==null?void 0:D.nodeId)??null,layoutModeEnabled:p==="layout",layoutHoveredNodeId:p==="layout"?j:null,layoutSelectedNodeIds:p==="layout"?k:[]},"*")},[j,D==null?void 0:D.nodeId,p,$e,y,k,_]);const Ve=(Me==null?void 0:Me.id)??null,G=P.length>0;function ve(){const q=P[P.length-1];q&&(Ne.current=null,z(re=>re.slice(0,-1)),h(q.project),ce({}),Te([]),g(q.currentPageIndex),x(q.selectedNodeId),C(q.selectedNodeId?[q.selectedNodeId]:q.selectedNodeIds),T(null),te(null),fe(null))}d.useEffect(()=>{if(!W||!U.current){Be(1);return}const q=U.current,re=()=>{const Re=q.getBoundingClientRect(),Se=24,Ke=Math.max(1,Re.width-Se),De=Math.max(1,Re.height-Se),He=Ke/W.canvas.width,lt=De/W.canvas.height,wt=Math.min(He,lt,1);Be(wt>0?wt:1)};if(re(),window.addEventListener("resize",re),typeof ResizeObserver>"u")return()=>{window.removeEventListener("resize",re)};const ue=new ResizeObserver(()=>{re()});return ue.observe(q),()=>{ue.disconnect(),window.removeEventListener("resize",re)}},[W]);const _e=d.useMemo(()=>{if(!W)return;const q=W.canvas.width*ye,re=W.canvas.height*ye;return{display:"flex",alignItems:"flex-start",justifyContent:"flex-start",width:`${q}px`,height:`${re}px`}},[W,ye]),nt=d.useMemo(()=>{if(W)return{position:"absolute",left:0,top:0,width:`${W.canvas.width}px`,height:`${W.canvas.height}px`,transform:`scale(${ye})`,transformOrigin:"top left"}},[W,ye]),et=d.useMemo(()=>{var Se,Ke;if(!D)return null;const q=(Se=V.current)==null?void 0:Se.getBoundingClientRect(),re=(Ke=ee.current)==null?void 0:Ke.getBoundingClientRect();if(!q||!re)return{left:Math.max(0,D.rect.left),top:Math.max(0,D.rect.top),width:Math.max(120,D.rect.width),minHeight:Math.max(48,D.rect.height)};const ue=q.left-re.left+D.rect.left*ye,Re=q.top-re.top+D.rect.top*ye;return{left:Math.max(0,ue),top:Math.max(0,Re),width:Math.max(120,D.rect.width*ye),minHeight:Math.max(48,D.rect.height*ye)}},[ye,D]);d.useEffect(()=>{!he.current||!et||(he.current.style.height=`${et.minHeight}px`,he.current.style.height=`${Math.max(et.minHeight,he.current.scrollHeight)}px`)},[D==null?void 0:D.nodeId,D==null?void 0:D.text,et]);const ot=d.useMemo(()=>{if(!(!D||!et))return{left:`${et.left}px`,top:`${et.top}px`,width:`${et.width}px`,minHeight:`${et.minHeight}px`,fontFamily:D.appearance.fontFamily??void 0,fontSize:D.appearance.fontSize??void 0,fontWeight:D.appearance.fontWeight??void 0,fontStyle:D.appearance.fontStyle??void 0,lineHeight:D.appearance.lineHeight??void 0,letterSpacing:D.appearance.letterSpacing??void 0,color:D.appearance.color??void 0,caretColor:D.appearance.color??void 0,textAlign:O$(D.appearance.textAlign),whiteSpace:F$(D.appearance.whiteSpace),padding:D.appearance.padding??void 0,textTransform:_$(D.appearance.textTransform)}},[D,et]);function jt(q,re){if(!q)return{nextIndex:0,nextSelectedNodeId:null};const ue=re.pages.findIndex(De=>De.id===q),Re=ue>=0?ue:0,Se=re.pages[Re]??null,Ke=Se?Tf(re,Se.id):[];return{nextIndex:Re,nextSelectedNodeId:Ke.find(De=>{var He;return(He=re.nodes[De])==null?void 0:He.editable})??null}}function Ft(q,re){if(h(q),ce({}),Te([]),(re==null?void 0:re.focusPageId)!==void 0){const ue=jt(re.focusPageId,q);g(ue.nextIndex),x(re.selectedNodeId??ue.nextSelectedNodeId),C(re.selectedNodeIds??(re.selectedNodeId?[re.selectedNodeId]:ue.nextSelectedNodeId?[ue.nextSelectedNodeId]:[]));return}(re==null?void 0:re.selectedNodeId)!==void 0&&x(re.selectedNodeId),(re==null?void 0:re.selectedNodeIds)!==void 0&&C(re.selectedNodeIds)}function bt(q){W&&((!q.historyKey||Ne.current!==q.historyKey)&&z(re=>[...re,{project:W,currentPageIndex:m,selectedNodeId:y,selectedNodeIds:k}].slice(-10)),Ne.current=q.historyKey??null,Ft(q.nextProject,{focusPageId:q.focusPageId,selectedNodeId:q.selectedNodeId,selectedNodeIds:q.selectedNodeIds}),q.preserveInlineEditor||te(null))}function _t(q){z(re=>[...re,q].slice(-10))}function xt(q,re,ue){const Re=le.current,Se=Re>0?(re-q.pointerStartX)/Re:0,Ke=Re>0?(ue-q.pointerStartY)/Re:0,De=Math.hypot(Se,Ke);if(!q.activated&&q.handle==="move"&&De<R$)return;q.activated||fe(lt=>lt&&{...lt,activated:!0});const He=U$(q,Se,Ke);ce(He.previewBoxes),Te(He.guideLines)}function rt(q){const re=xe.current,ue=de.current;if(re&&q.activated&&Object.keys(ue).length>0){const Re=Object.fromEntries(Object.entries(ue).map(([Ke,De])=>{const He=re.nodes[Ke],lt=ke[Ke];if(!He)return null;const wt=Go(He,lt),it=oi(He,lt),Ze=it.x-wt.x,Ht=it.y-wt.y;return[Ke,xs({...De,x:De.x-Ze,y:De.y-Ht})]}).filter(Ke=>!!Ke)),Se=Rf(re,Re);Ne.current=null,_t({project:q.startProject,currentPageIndex:q.startPageIndex,selectedNodeId:q.startSelectedNodeId,selectedNodeIds:q.startSelectedNodeIds}),h(Se)}ce({}),Te([]),fe(null)}function It(q,re){if(!W||!W.nodes[q])return;const Re=(re==null?void 0:re.additive)??!1;x(q),T(null),re!=null&&re.switchToLayout&&b("layout"),C(Se=>{if(!Re)return[q];if(Se.includes(q)){const Ke=Se.filter(De=>De!==q);return Ke.length>0?Ke:[q]}return[...Se,q]})}function $t(q){var re;return W?((re=Object.values(W.nodes).find(ue=>ue.children.includes(q)))==null?void 0:re.id)??null:null}function pt(q){if(!W||!q)return null;const re=$t(q);if(!re)return null;const ue=W.nodes[re];return!ue||ue.runtimeFlags.includes("layout-freeze-container")||!ue.sourceRef?null:re}function Ie(q){if(!W)return!1;const re=pt(q);if(!re)return!1;const ue=W.nodes[re];if(!ue)return!1;const Re=W.nodes[q??""];if(!Re)return!1;const Se=St(re,ue);return Se?!!J(Re,Se):!1}function kt(){if(!W||!y||!Ie(y))return;const q=pt(y);if(!q)return;const re=W.nodes[q];if(!re)return;const ue=St(q,re);if(!ue)return;const Re=M5(W,[q,...re.children],(Se,Ke)=>{if(Ke===q){const lt=Se.runtimeFlags.includes("layout-freeze-container")?Se.runtimeFlags:[...Se.runtimeFlags,"layout-freeze-container"];return{...Se,style:{...Se.style,position:tj(Se.style.position)?Se.style.position:"relative"},runtimeFlags:lt}}const De=J(Se,ue);if(!De)return Se;const He=Se.runtimeFlags.filter(lt=>lt!=="layout-freeze-container").concat(Se.runtimeFlags.includes("layout-freeze-child")?[]:["layout-freeze-child"],Se.runtimeFlags.includes("draft-box")?[]:["draft-box"]);return{...Se,box:De,style:{...Se.style,position:"absolute",margin:"0px"},runtimeFlags:He}});bt({nextProject:Re,selectedNodeId:y,selectedNodeIds:[y],historyKey:`layout-freeze:${q}`}),b("layout")}function St(q,re){const ue=ke[q];if(ue)return oi(re,ue);if(q===(Me==null?void 0:Me.rootNodeId))return xs({x:0,y:0,width:(W==null?void 0:W.canvas.width)??re.box.width,height:(W==null?void 0:W.canvas.height)??re.box.height,zIndex:re.box.zIndex});for(const Se of re.children){const Ke=W==null?void 0:W.nodes[Se],De=ke[Se];if(!Ke||!De)continue;const He=De.left-De.localLeft,lt=De.top-De.localTop,wt=vt(re);return xs({x:He,y:lt,width:wt.width,height:wt.height,zIndex:re.box.zIndex})}const Re=vt(re);return xs({x:re.box.x,y:re.box.y,width:Re.width,height:Re.height,zIndex:re.box.zIndex})}function vt(q){const re=q.children.map(De=>Ct((W==null?void 0:W.nodes[De])??null)).filter(De=>!!De),ue=q.box.width,Re=q.box.height;if(!re.length)return{width:ue,height:Re};const Se=re.reduce((De,He)=>Math.max(De,He.x+He.width),0),Ke=re.reduce((De,He)=>Math.max(De,He.y+He.height),0);return{width:Math.max(ue,Se),height:Math.max(Re,Ke)}}function Ct(q){if(!q)return null;const re=ke[q.id];return xs(re?{x:re.localLeft,y:re.localTop,width:re.width,height:re.height,zIndex:q.box.zIndex}:q.box)}function J(q,re){const ue=ke[q.id];if(ue){const Se=oi(q,ue);return xs({x:Se.x-re.x,y:Se.y-re.y,width:Se.width,height:Se.height,zIndex:Se.zIndex})}const Re=Ct(q);return Re?xs(Re):null}function Ue(){if(!W||!y)return;const q=E5(W,y);q.duplicatedNodeId&&(bt({nextProject:q.project,selectedNodeId:q.duplicatedNodeId,selectedNodeIds:[q.duplicatedNodeId],historyKey:`duplicate:${y}`}),b("layout"))}function ze(q){if(!W||!y)return;const re=W.nodes[y];if(!re)return;const ue=Go(re,ke[y]),Re=xs({...ue,x:q.x??ue.x,y:q.y??ue.y,width:q.width??ue.width,height:q.height??ue.height,zIndex:ue.zIndex}),Se=Rf(W,{[y]:Re});bt({nextProject:Se,selectedNodeId:y,selectedNodeIds:k,historyKey:`layout-box:${y}`})}function st(q){if(!W)return;const re=k.filter(Se=>Li(W.nodes[Se]).alignable);if(re.length<2)return;const ue=T$(Object.fromEntries(re.map(Se=>{const Ke=W.nodes[Se];return Ke?[Se,Go(Ke,ke[Se])]:null}).filter(Se=>!!Se)),q),Re=Rf(W,ue);bt({nextProject:Re,selectedNodeId:y,selectedNodeIds:re,historyKey:`layout-align:${q}:${re.join(",")}`})}return d.useEffect(()=>{if(!$e||p!=="layout"){we({});return}const q=re=>{const ue=re.data;if(!ue||typeof ue!="object"||ue.type!=="codingns-static-html-layout-measurements"||!Array.isArray(ue.measurements))return;const Re={};ue.measurements.forEach(Se=>{if(!Se||typeof Se!="object")return;const Ke=Se,De=typeof Ke.nodeId=="string"?Ke.nodeId.trim():"",He=typeof Ke.left=="number"?Ke.left:Number.NaN,lt=typeof Ke.top=="number"?Ke.top:Number.NaN,wt=typeof Ke.width=="number"?Ke.width:Number.NaN,it=typeof Ke.height=="number"?Ke.height:Number.NaN,Ze=typeof Ke.localLeft=="number"?Ke.localLeft:He,Ht=typeof Ke.localTop=="number"?Ke.localTop:lt;!De||!Number.isFinite(He)||!Number.isFinite(lt)||!Number.isFinite(wt)||!Number.isFinite(it)||(Re[De]={left:He,top:lt,width:wt,height:it,localLeft:Ze,localTop:Ht})}),we(Re)};return window.addEventListener("message",q),()=>{window.removeEventListener("message",q)}},[p,$e]),d.useEffect(()=>{var re;if(p!=="layout"||!$e)return;const q=(re=V.current)==null?void 0:re.contentWindow;q&&q.postMessage({type:"codingns-static-html-layout-measure-request",nodeIds:Array.from(new Set([(Me==null?void 0:Me.rootNodeId)??"",...je].filter(ue=>ue&&(W==null?void 0:W.nodes[ue]))))},"*")},[Me==null?void 0:Me.rootNodeId,W,p,je,$e]),d.useEffect(()=>{if(!pe||pe.source!=="overlay")return;const q=ue=>{xt(pe,ue.clientX,ue.clientY)},re=()=>{rt(pe)};return window.addEventListener("pointermove",q),window.addEventListener("pointerup",re),()=>{window.removeEventListener("pointermove",q),window.removeEventListener("pointerup",re)}},[pe]),!c.supported||!W?s.jsxs("div",{className:"static-html-presentation-empty",children:[s.jsx("p",{className:"status-text",children:a("conversation.fileViewerPresentationUnsupported")}),c.reason?s.jsx("p",{className:"status-text",children:a("conversation.fileViewerPresentationUnsupportedReason").replace("{reason}",c.reason)}):null]}):s.jsxs("div",{className:"static-html-presentation-shell","data-testid":"static-html-presentation-view",children:[s.jsxs("aside",{className:"static-html-presentation-sidebar",children:[s.jsxs("div",{className:"static-html-presentation-sidebar-actions",children:[s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-sidebar-action-button",onClick:ve,disabled:!G,children:a("conversation.fileViewerPresentationUndoAction")}),s.jsx("button",{type:"button",className:"primary-button static-html-presentation-sidebar-action-button",onClick:i,disabled:!o||l,children:l?a("conversation.filePanelSaving"):a("conversation.filePanelSave")})]}),s.jsx("div",{className:"static-html-presentation-page-toolbar",children:s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-page-toolbar-button",onClick:()=>{const q=L5(W,{insertAfterPageId:Ve});bt({nextProject:q.project,focusPageId:q.pageId})},children:a("conversation.fileViewerPresentationAddPage")})}),s.jsx("div",{className:"static-html-presentation-page-list",role:"list",children:W.pages.map((q,re)=>s.jsxs("div",{className:"static-html-presentation-page-item","data-active":q.id===Ve?"true":void 0,"data-dragging":L===q.id?"true":void 0,"data-drop-target":(K==null?void 0:K.pageId)===q.id?"true":void 0,"data-drop-position":(K==null?void 0:K.pageId)===q.id?K.position:void 0,draggable:!0,onDragStart:ue=>{ue.dataTransfer.effectAllowed="move",ue.dataTransfer.setData("text/plain",q.id),R(q.id),E(null)},onDragOver:ue=>{ue.preventDefault(),ue.dataTransfer.dropEffect="move";const Re=B$(ue);E(Se=>(Se==null?void 0:Se.pageId)===q.id&&Se.position===Re?Se:{pageId:q.id,position:Re})},onDrop:ue=>{ue.preventDefault();const Re=ue.dataTransfer.getData("text/plain")||L;if(!Re||!K)return;const Se=W$(W.pages,Re,K);if(Se===null){R(null),E(null);return}const Ke=F5(W,Re,Se);bt({nextProject:Ke.project,focusPageId:Ke.pageId}),R(null),E(null)},onDragEnd:()=>{R(null),E(null)},children:[(K==null?void 0:K.pageId)===q.id&&K.position==="before"?s.jsx("div",{className:"static-html-presentation-page-drop-indicator","data-position":"before"}):null,s.jsxs("button",{type:"button",className:"static-html-presentation-page-main",onClick:()=>{const ue=W.pages.findIndex(Re=>Re.id===q.id);g(ue>=0?ue:0)},children:[s.jsx("span",{className:"static-html-presentation-page-no",children:String(re+1).padStart(2,"0")}),s.jsx("span",{className:"static-html-presentation-page-title",children:q.title??`第 ${re+1} 页`})]}),s.jsxs("div",{className:"static-html-presentation-page-actions","aria-label":a("conversation.fileViewerPresentationPageActions"),children:[s.jsx("span",{className:"static-html-presentation-page-drag-hint",children:a("conversation.fileViewerPresentationDragToSort")}),s.jsx("button",{type:"button",className:"static-html-presentation-page-action",onClick:()=>{const ue=D5(W,q.id);ue.pageId&&bt({nextProject:ue.project,focusPageId:ue.pageId})},"aria-label":a("conversation.fileViewerPresentationDuplicatePage"),title:a("conversation.fileViewerPresentationDuplicatePage"),children:s.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[s.jsx("rect",{x:"5",y:"5",width:"7",height:"7",rx:"1.5"}),s.jsx("path",{d:"M4 10H3.5A1.5 1.5 0 0 1 2 8.5v-5A1.5 1.5 0 0 1 3.5 2h5A1.5 1.5 0 0 1 10 3.5V4"})]})}),s.jsx("button",{type:"button",className:"static-html-presentation-page-action",onClick:()=>{const ue=O5(W,q.id);bt({nextProject:ue.project,focusPageId:ue.nextPageId??Ve})},disabled:W.pages.length<=1,"aria-label":a("conversation.fileViewerPresentationDeletePage"),title:a("conversation.fileViewerPresentationDeletePage"),children:"×"})]}),(K==null?void 0:K.pageId)===q.id&&K.position==="after"?s.jsx("div",{className:"static-html-presentation-page-drop-indicator","data-position":"after"}):null]},q.id))})]}),s.jsxs("section",{className:"static-html-presentation-stage",children:[s.jsxs("section",{className:"static-html-presentation-toolbar-panel",children:[s.jsx("div",{className:"static-html-presentation-toolbar-panel-header",children:s.jsxs("div",{className:"static-html-presentation-mode-switch",role:"group","aria-label":a("conversation.fileViewerModeLabel"),children:[s.jsx("button",{type:"button",className:"static-html-presentation-mode-button","data-active":p==="content"?"true":void 0,onClick:()=>b("content"),children:a("conversation.fileViewerPresentationTextMode")}),s.jsx("button",{type:"button",className:"static-html-presentation-mode-button","data-active":p==="layout"?"true":void 0,onClick:()=>{b("layout"),y&&C([y])},children:a("conversation.fileViewerPresentationLayoutMode")})]})}),s.jsx("div",{className:"static-html-presentation-toolbar-panel-body",children:s.jsx("div",{ref:X,className:"static-html-presentation-toolbar-viewport",children:s.jsx("div",{ref:I,className:"static-html-presentation-toolbar-scale-shell",style:{transform:`scale(${We})`,width:We<1?`${100/We}%`:"100%"},children:s.jsx("div",{className:"static-html-presentation-toolbar static-html-presentation-inspector",children:p==="layout"?s.jsx(V$,{selectedNode:Q,selectedLayoutBox:Q?Go(Q,y?ke[y]:void 0):null,selectedNodes:Oe,showFreezeContainerAction:!!(y&&pt(y)),canFreezeContainer:Ie(y),onDuplicate:Ue,onFreezeContainer:kt,onAlignLeft:()=>st("left"),onAlignRight:()=>st("right"),onAlignTop:()=>st("top"),onAlignBottom:()=>st("bottom"),onBoxChange:ze}):ge?s.jsx(K$,{node:ge,selectedRunIndex:_,onSelectedRunChange:T,compact:!0,onTextChange:({text:q,runs:re})=>{if(!y)return;const ue=Nf(W,y,Re=>({...Re,content:{...Re.content,text:q,runs:re??Xy(Re,q)}}));bt({nextProject:ue,historyKey:`text:${y}`})},onStyleChange:q=>{if(!y)return;const re=Nf(W,y,ue=>({...ue,style:{...ue.style,...q}}));bt({nextProject:re,historyKey:`style:${y}`})}}):s.jsx("div",{className:"static-html-presentation-toolbar-empty static-html-presentation-inspector-empty",children:s.jsx("p",{className:"status-text",children:a("conversation.fileViewerPresentationSelectNode")})})})})})})]}),s.jsx("section",{className:"static-html-presentation-content-panel",children:s.jsxs("div",{className:"static-html-presentation-workarea",children:[s.jsx("div",{className:"static-html-presentation-canvas-panel",children:s.jsx("div",{ref:U,className:"static-html-presentation-frame-shell",children:$e?s.jsxs("div",{ref:ee,className:"static-html-presentation-frame-stage",style:_e,children:[s.jsx("iframe",{ref:V,className:"static-html-presentation-frame","data-testid":"static-html-presentation-frame",title:(Me==null?void 0:Me.title)??e,srcDoc:$e,sandbox:"allow-forms allow-modals allow-scripts",style:nt,onLoad:()=>{var q,re;(re=(q=V.current)==null?void 0:q.contentWindow)==null||re.postMessage({type:"codingns-static-html-selection-sync",selectedNodeId:y,inlineEditingNodeId:(D==null?void 0:D.nodeId)??null,layoutModeEnabled:p==="layout",layoutHoveredNodeId:p==="layout"?j:null,layoutSelectedNodeIds:p==="layout"?k:[]},"*")}}),p==="layout"?s.jsxs("div",{className:"static-html-presentation-layout-overlay","data-testid":"static-html-presentation-layout-overlay",children:[Y.map((q,re)=>s.jsx("div",{className:"static-html-presentation-layout-guide","data-orientation":q.orientation,style:$$(q,ye)},`${q.orientation}-${q.position}-${re}`)),j&&!k.includes(j)&&ke[j]?s.jsx("div",{className:"static-html-presentation-layout-box static-html-presentation-layout-box-hover","data-hovered":"true",style:Pf(ke[j],ye)}):null,k.map(q=>{const re=se[q],ue=ke[q],Re=W.nodes[q],Se=Li(Re),Ke=re?Pf({left:re.x,top:re.y,width:re.width,height:re.height,localLeft:re.x,localTop:re.y},ye):ue?Pf(ue,ye):void 0;return!Ke||!Re?null:s.jsx("div",{className:"static-html-presentation-layout-box","data-primary":q===y?"true":void 0,"data-disabled":Se.movable?void 0:"true",style:Ke,onPointerEnter:()=>{H(q)},onPointerLeave:()=>{H(De=>De===q?null:De)},onPointerDown:De=>{if(!Se.movable)return;De.preventDefault(),De.stopPropagation(),It(q,{additive:De.metaKey||De.ctrlKey,switchToLayout:!0});const He=De.metaKey||De.ctrlKey?k.includes(q)?k:[...k,q]:[q],lt=Object.fromEntries(He.map(it=>{const Ze=W.nodes[it];return Ze?[it,oi(Ze,ke[it])]:null}).filter(it=>!!it)),wt=Object.fromEntries(je.map(it=>{const Ze=W.nodes[it];return Ze?[it,oi(Ze,ke[it])]:null}).filter(it=>!!it));fe({source:"overlay",handle:"move",nodeIds:He,pointerStartX:De.clientX,pointerStartY:De.clientY,startProject:W,startPageIndex:m,pageNodeIds:je,referenceBoxes:wt,startSelectedNodeId:y,startSelectedNodeIds:k,activated:!1,originBoxes:lt})},children:Se.resizable?s.jsx("button",{type:"button",className:"static-html-presentation-layout-resize-handle","aria-label":a("conversation.fileViewerPresentationResizeHandle"),onPointerDown:De=>{De.preventDefault(),De.stopPropagation(),It(q,{switchToLayout:!0}),fe({source:"overlay",handle:"resize-se",nodeIds:[q],pointerStartX:De.clientX,pointerStartY:De.clientY,startProject:W,startPageIndex:m,pageNodeIds:je,referenceBoxes:Object.fromEntries(je.map(He=>{const lt=W.nodes[He];return lt?[He,oi(lt,ke[He])]:null}).filter(He=>!!He)),startSelectedNodeId:y,startSelectedNodeIds:k,activated:!0,originBoxes:{[q]:oi(W.nodes[q],ke[q])}})},children:s.jsx("span",{})}):null},q)})]}):null,D?s.jsx("div",{ref:he,className:"static-html-presentation-inline-editor","data-testid":"static-html-presentation-inline-editor",role:"textbox","aria-multiline":"true",contentEditable:!0,suppressContentEditableWarning:!0,spellCheck:!1,style:ot,onInput:q=>{const re=ej(q.currentTarget),ue=D;if(te(Se=>Se&&{...Se,text:re}),!ue||!W.nodes[ue.nodeId])return;const Re=Nf(W,ue.nodeId,Se=>({...Se,content:{...Se.content,text:re,runs:Xy(Se,re)}}));bt({nextProject:Re,selectedNodeId:ue.nodeId,historyKey:`inline-text:${ue.nodeId}`,preserveInlineEditor:!0})},onBlur:()=>{te(null)},onPaste:q=>{q.preventDefault();const re=q.clipboardData.getData("text/plain");D$(re)},onKeyDown:q=>{q.key==="Escape"&&(q.preventDefault(),te(null))}}):null]}):s.jsx("p",{className:"status-text",children:a("conversation.fileViewerHtmlPreviewUnavailable")})})}),s.jsxs("aside",{className:"static-html-presentation-node-sidebar",children:[s.jsx("div",{className:"static-html-presentation-node-sidebar-header",children:s.jsx("p",{className:"static-html-presentation-node-sidebar-kicker",children:a("conversation.fileViewerPresentationComponentList")})}),s.jsx("div",{className:"static-html-presentation-node-strip",role:"list",children:je.map(q=>{const re=W.nodes[q];return re?s.jsxs("button",{type:"button",className:"static-html-presentation-node-chip","data-active":q===y?"true":void 0,"data-selected":k.includes(q)?"true":void 0,"data-locked":re.editable?void 0:"true",title:p==="layout"?Li(re).reason??void 0:void 0,onClick:ue=>{It(q,{additive:p==="layout"&&(ue.metaKey||ue.ctrlKey),switchToLayout:p==="layout"})},children:[s.jsx("span",{className:"static-html-presentation-node-chip-type",children:re.type}),s.jsx("span",{className:"static-html-presentation-node-chip-name",children:re.name||re.id}),p==="layout"?s.jsx("span",{className:"static-html-presentation-node-chip-status",children:Li(re).reason?a("conversation.fileViewerPresentationLayoutLocked"):a("conversation.fileViewerPresentationLayoutEditable")}):null]},q):null})})]})]})})]})]})}function M$(e){if(!e||typeof e!="object")return!1;const t=e;return["left","top","width","height"].every(n=>typeof t[n]=="number")}function E$(e,t){const n={fontFamily:t.fontFamily??null,fontSize:typeof t.fontSize=="number"?`${t.fontSize}px`:null,fontWeight:t.fontWeight??null,fontStyle:null,lineHeight:t.lineHeight??null,letterSpacing:t.letterSpacing??null,color:t.color??null,textAlign:t.textAlign??null,whiteSpace:t.whiteSpace??null,padding:t.padding??null,textTransform:null};if(!e||typeof e!="object")return n;const r=e;return{fontFamily:Er(r.fontFamily,n.fontFamily),fontSize:Er(r.fontSize,n.fontSize),fontWeight:Er(r.fontWeight,n.fontWeight),fontStyle:Er(r.fontStyle,n.fontStyle),lineHeight:Er(r.lineHeight,n.lineHeight),letterSpacing:Er(r.letterSpacing,n.letterSpacing),color:Er(r.color,n.color),textAlign:Er(r.textAlign,n.textAlign),whiteSpace:Er(r.whiteSpace,n.whiteSpace),padding:Er(r.padding,n.padding),textTransform:Er(r.textTransform,n.textTransform)}}function Er(e,t){return typeof e=="string"&&e.trim()?e:t}function Yy(e,t){ej(e)!==t&&(e.textContent=t)}function L$(e){e.focus();const t=window.getSelection();if(!t)return;const n=document.createRange();n.selectNodeContents(e),n.collapse(!1),t.removeAllRanges(),t.addRange(n)}function ej(e){return Ol(typeof e.innerText=="string"?e.innerText:e.textContent??"")}function Ol(e){return e.replace(/\r\n/g,`
664
+ `).replace(/\u00a0/g," ")}function D$(e){const t=window.getSelection();if(!t||t.rangeCount===0)return;const n=t.getRangeAt(0);n.deleteContents();const r=document.createTextNode(e);n.insertNode(r),n.setStartAfter(r),n.collapse(!0),t.removeAllRanges(),t.addRange(n)}function O$(e){if(!e)return;const t=e.trim().toLowerCase();if(t==="left"||t==="right"||t==="center"||t==="justify"||t==="start"||t==="end")return t}function F$(e){if(!e)return;const t=e.trim().toLowerCase();if(t==="normal"||t==="nowrap"||t==="pre"||t==="pre-wrap"||t==="pre-line"||t==="break-spaces")return t}function _$(e){if(!e)return;const t=e.trim().toLowerCase();if(t==="none"||t==="capitalize"||t==="uppercase"||t==="lowercase")return t}function B$(e){const t=e.currentTarget.getBoundingClientRect();return t.height<=0||e.clientY-t.top<t.height/2?"before":"after"}function W$(e,t,n){const r=e.findIndex(c=>c.id===t),i=e.findIndex(c=>c.id===n.pageId);if(r<0||i<0)return null;const o=n.position==="before"?i:i+1,l=r<o?o-1:o;return Math.max(0,Math.min(l,e.length-1))}function Li(e){return e?e.editable?e.type==="svg"||e.type==="html"||e.type==="decoration"?{movable:!1,resizable:!1,alignable:!1,reason:a("conversation.fileViewerPresentationLayoutUnsupported"),strictModeLocked:!1}:e.id.endsWith("-root")?{movable:!1,resizable:!1,alignable:!1,reason:a("conversation.fileViewerPresentationLayoutRootLocked"),strictModeLocked:!1}:z$(e)?{movable:!0,resizable:!0,alignable:!0,reason:null,strictModeLocked:!1}:{movable:!1,resizable:!1,alignable:!1,reason:a("conversation.fileViewerPresentationLayoutStrictLocked"),strictModeLocked:!0}:{movable:!1,resizable:!1,alignable:!1,reason:e.lockedReason||a("conversation.fileViewerPresentationLayoutUnsupported"),strictModeLocked:!1}:{movable:!1,resizable:!1,alignable:!1,reason:a("conversation.fileViewerPresentationLayoutUnsupported"),strictModeLocked:!1}}function Pf(e,t){return{left:`${e.left*t}px`,top:`${e.top*t}px`,width:`${e.width*t}px`,height:`${e.height*t}px`}}function $$(e,t){return e.orientation==="vertical"?{left:`${e.position*t}px`,top:`${e.start*t}px`,width:"1px",height:`${Math.max(0,(e.end-e.start)*t)}px`}:{left:`${e.start*t}px`,top:`${e.position*t}px`,width:`${Math.max(0,(e.end-e.start)*t)}px`,height:"1px"}}function z$(e){return e.runtimeFlags.includes("draft-clone")||e.runtimeFlags.includes("draft-box")?!0:e.sourceRef?!!(e.runtimeFlags.includes("layout-freeze-child")||tj(e.style.position)):!1}function tj(e){const t=(e==null?void 0:e.trim().toLowerCase())??"";return t==="absolute"||t==="fixed"}function Go(e,t){return e.runtimeFlags.includes("draft-clone")||e.runtimeFlags.includes("draft-box")?xs(e.box):xs(t?{x:t.localLeft,y:t.localTop,width:t.width,height:t.height,zIndex:e.box.zIndex}:e.box)}function oi(e,t){return xs(t?{x:t.left,y:t.top,width:t.width,height:t.height,zIndex:e.box.zIndex}:e.box)}function H$(e,t){if(e.nodeIds.length!==1)return[];const n=e.nodeIds[0],r=t[n];if(!n||!r)return[];const i=[r.x,r.x+r.width/2,r.x+r.width],o=[r.y,r.y+r.height/2,r.y+r.height],l=6,c=[];return Object.entries(e.originBoxes).forEach(([u])=>{}),Object.entries(e.startProject.nodes).forEach(([u,f])=>{if(u===n||e.nodeIds.includes(u))return;const h=e.startProject.nodes[u]?Go(f,void 0):null;if(!h)return;const m=[h.x,h.x+h.width/2,h.x+h.width],g=[h.y,h.y+h.height/2,h.y+h.height];i.forEach(p=>{const b=m.find(y=>Math.abs(y-p)<=l);b!==void 0&&c.push({orientation:"vertical",position:b,start:Math.min(r.y,h.y),end:Math.max(r.y+r.height,h.y+h.height)})}),o.forEach(p=>{const b=g.find(y=>Math.abs(y-p)<=l);b!==void 0&&c.push({orientation:"horizontal",position:b,start:Math.min(r.x,h.x),end:Math.max(r.x+r.width,h.x+h.width)})})}),nj(c)}function U$(e,t,n){const r={};if(e.nodeIds.forEach(o=>{const l=e.originBoxes[o];if(l){if(e.handle==="move"){r[o]=xs({...l,x:l.x+t,y:l.y+n});return}r[o]=xs({...l,width:l.width+t,height:l.height+n})}}),e.handle!=="move")return{previewBoxes:r,guideLines:H$(e,r)};const i=q$(e,r);return{previewBoxes:i.previewBoxes,guideLines:i.guideLines}}function q$(e,t){const n=e.nodeIds.map(p=>t[p]).filter(p=>!!p),r=A$(n);if(!r)return{previewBoxes:t,guideLines:[]};const i=6,o=Gy(r);let l=0,c=0,u=i+1,f=i+1;const h=[],m=e.pageNodeIds.filter(p=>!e.nodeIds.includes(p)).map(p=>e.referenceBoxes[p]).filter(p=>!!p&&p.width>0&&p.height>0),g={x:0,y:0,width:e.startProject.canvas.width,height:e.startProject.canvas.height,zIndex:0};return[...m,g].forEach(p=>{const b=Gy(p);o.verticals.forEach(y=>{b.verticals.forEach(x=>{const k=Math.abs(x-(y+l));k>i||k>=u||(u=k,l=x-y,h.push({orientation:"vertical",position:x,start:Math.min(r.y,p.y),end:Math.max(r.y+r.height,p.y+p.height)}))})}),o.horizontals.forEach(y=>{b.horizontals.forEach(x=>{const k=Math.abs(x-(y+c));k>i||k>=f||(f=k,c=x-y,h.push({orientation:"horizontal",position:x,start:Math.min(r.x,p.x),end:Math.max(r.x+r.width,p.x+p.width)}))})})}),(l!==0||c!==0)&&e.nodeIds.forEach(p=>{const b=t[p];b&&(t[p]=xs({...b,x:b.x+l,y:b.y+c}))}),{previewBoxes:t,guideLines:nj(h)}}function nj(e){const t=new Map;return e.forEach(n=>{const r=`${n.orientation}:${Math.round(n.position)}`,i=t.get(r);if(!i){t.set(r,n);return}t.set(r,{...n,start:Math.min(i.start,n.start),end:Math.max(i.end,n.end)})}),Array.from(t.values())}function Tc(e){return{x:e?String(e.x):"",y:e?String(e.y):"",width:e?String(e.width):"",height:e?String(e.height):""}}function V$({selectedNode:e,selectedLayoutBox:t,selectedNodes:n,showFreezeContainerAction:r,canFreezeContainer:i,onDuplicate:o,onFreezeContainer:l,onAlignLeft:c,onAlignRight:u,onAlignTop:f,onAlignBottom:h,onBoxChange:m}){const g=Li(e),b=n.length>1&&n.every(j=>Li(j).alignable),y=!!e&&g.strictModeLocked&&r,[x,k]=d.useState(()=>Tc(t));d.useEffect(()=>{k(Tc(t))},[e==null?void 0:e.id,t==null?void 0:t.x,t==null?void 0:t.y,t==null?void 0:t.width,t==null?void 0:t.height]);function C(j){if(!e)return;const H=x[j].trim();if(!H){k(Tc(t));return}const _=Number(H);if(!Number.isFinite(_)){k(Tc(t));return}m({[j]:_})}return s.jsxs("div",{className:"static-html-presentation-layout-toolbar",children:[s.jsxs("div",{className:"static-html-presentation-layout-toolbar-row",children:[s.jsx("span",{className:"static-html-presentation-layout-badge",children:n.length>1?a("conversation.fileViewerPresentationLayoutSelectionCount").replace("{count}",String(n.length)):a("conversation.fileViewerPresentationLayoutMode")}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-layout-action",onClick:o,disabled:!e||!g.movable,children:a("conversation.fileViewerPresentationDuplicateAction")}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-layout-action",onClick:c,disabled:!b,children:a("conversation.fileViewerPresentationLayoutAlignLeft")}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-layout-action",onClick:u,disabled:!b,children:a("conversation.fileViewerPresentationLayoutAlignRight")}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-layout-action",onClick:f,disabled:!b,children:a("conversation.fileViewerPresentationLayoutAlignTop")}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-layout-action",onClick:h,disabled:!b,children:a("conversation.fileViewerPresentationLayoutAlignBottom")}),y?s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-layout-action",onClick:l,disabled:!i,children:a("conversation.fileViewerPresentationLayoutFreezeContainer")}):null]}),e?s.jsxs("div",{className:"static-html-presentation-layout-form",children:[s.jsxs("label",{className:"static-html-presentation-layout-field",children:[s.jsx("span",{children:a("conversation.fileViewerPresentationPositionXLabel")}),s.jsx("input",{type:"number",value:x.x,onChange:j=>k(H=>({...H,x:j.target.value})),onBlur:()=>C("x"),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),C("x"))},disabled:!g.movable})]}),s.jsxs("label",{className:"static-html-presentation-layout-field",children:[s.jsx("span",{children:a("conversation.fileViewerPresentationPositionYLabel")}),s.jsx("input",{type:"number",value:x.y,onChange:j=>k(H=>({...H,y:j.target.value})),onBlur:()=>C("y"),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),C("y"))},disabled:!g.movable})]}),s.jsxs("label",{className:"static-html-presentation-layout-field",children:[s.jsx("span",{children:a("conversation.fileViewerPresentationWidthLabel")}),s.jsx("input",{type:"number",value:x.width,onChange:j=>k(H=>({...H,width:j.target.value})),onBlur:()=>C("width"),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),C("width"))},disabled:!g.resizable})]}),s.jsxs("label",{className:"static-html-presentation-layout-field",children:[s.jsx("span",{children:a("conversation.fileViewerPresentationHeightLabel")}),s.jsx("input",{type:"number",value:x.height,onChange:j=>k(H=>({...H,height:j.target.value})),onBlur:()=>C("height"),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),C("height"))},disabled:!g.resizable})]}),g.reason?null:s.jsx("p",{className:"static-html-presentation-layout-hint",children:a("conversation.fileViewerPresentationLayoutHint")})]}):s.jsx("div",{className:"static-html-presentation-toolbar-empty static-html-presentation-inspector-empty",children:s.jsx("p",{className:"status-text",children:a("conversation.fileViewerPresentationLayoutSelectNode")})})]})}function K$({node:e,selectedRunIndex:t,onSelectedRunChange:n,compact:r=!1,onTextChange:i,onStyleChange:o}){const l=e.type==="text"||typeof e.content.text=="string",c=typeof e.style.fontSize=="number"?e.style.fontSize:null,u=e.style.fontFamily??"",f=Y$(e.style.fontWeight),h=e.style.fontStyle??"",m=e.style.textDecoration??"",g=e.style.lineHeight??"",p=Jy(e.style.color),b=Jy(e.style.backgroundColor);return s.jsx("div",{className:"static-html-presentation-inspector-panel","data-compact":r?"true":void 0,children:s.jsx("div",{className:"static-html-presentation-inspector-controls","data-compact":r?"true":void 0,children:l?s.jsxs("div",{className:"static-html-presentation-text-edit-row",children:[s.jsx("div",{className:"static-html-presentation-text-toolbar",role:"toolbar","aria-label":a("conversation.fileViewerPresentationTextToolbar"),children:s.jsxs("div",{className:"static-html-presentation-text-toolbar-row",children:[s.jsxs("select",{className:"static-html-presentation-text-toolbar-select static-html-presentation-text-toolbar-font",value:u,onChange:y=>o({fontFamily:y.target.value||null}),disabled:!e.editable,"aria-label":a("conversation.fileViewerPresentationFontFamilyLabel"),children:[s.jsx("option",{value:"",children:a("conversation.fileViewerPresentationKeepOriginal")}),s.jsx("option",{value:'"PingFang SC", "Microsoft YaHei", sans-serif',children:a("conversation.fileViewerPresentationFontPresetTitle")}),s.jsx("option",{value:'"Noto Sans SC", "PingFang SC", sans-serif',children:a("conversation.fileViewerPresentationFontPresetSans")}),s.jsx("option",{value:'Georgia, "Times New Roman", serif',children:a("conversation.fileViewerPresentationFontPresetSerif")}),s.jsx("option",{value:'"SF Mono", "Cascadia Mono", monospace',children:a("conversation.fileViewerPresentationFontPresetMono")})]}),s.jsxs("select",{className:"static-html-presentation-text-toolbar-select static-html-presentation-text-toolbar-size",value:c?String(c):"",onChange:y=>{const x=y.target.value.trim();o({fontSize:x?Number(x):null})},disabled:!e.editable,"aria-label":a("conversation.fileViewerPresentationFontSizeLabel"),children:[s.jsx("option",{value:"",children:a("conversation.fileViewerPresentationKeepOriginal")}),[12,14,16,18,20,24,28,32,40,48,60].map(y=>s.jsx("option",{value:y,children:y},y))]}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-text-toolbar-button","data-active":f==="700"?"true":void 0,onClick:()=>o({fontWeight:f==="700"?null:"700"}),disabled:!e.editable,"aria-label":a("conversation.fileViewerPresentationBoldAction"),children:"B"}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-text-toolbar-button static-html-presentation-text-toolbar-button-italic","data-active":h==="italic"?"true":void 0,onClick:()=>o({fontStyle:h==="italic"?null:"italic"}),disabled:!e.editable,"aria-label":a("conversation.fileViewerPresentationItalicAction"),children:"I"}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-text-toolbar-button static-html-presentation-text-toolbar-button-underline","data-active":m.includes("underline")?"true":void 0,onClick:()=>o({textDecoration:m.includes("underline")?null:"underline"}),disabled:!e.editable,"aria-label":a("conversation.fileViewerPresentationUnderlineAction"),children:"U"}),s.jsxs("label",{className:"static-html-presentation-text-toolbar-color","aria-label":a("conversation.fileViewerPresentationTextColorLabel"),children:[s.jsx("span",{className:"static-html-presentation-text-toolbar-color-label",style:{"--static-html-toolbar-color":p},children:"A"}),s.jsx("input",{type:"color",value:p,onChange:y=>o({color:y.target.value}),disabled:!e.editable})]}),s.jsxs("label",{className:"static-html-presentation-text-toolbar-color","aria-label":a("conversation.fileViewerPresentationBackgroundColorLabel"),children:[s.jsx("span",{className:"static-html-presentation-text-toolbar-color-label static-html-presentation-text-toolbar-color-label-fill",style:{"--static-html-toolbar-color":b},children:"A"}),s.jsx("input",{type:"color",value:b,onChange:y=>o({backgroundColor:y.target.value}),disabled:!e.editable})]}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-text-toolbar-button",onClick:()=>o({fontSize:Math.max(8,(c??24)-2)}),disabled:!e.editable,"aria-label":a("conversation.fileViewerPresentationFontSizeDecreaseAction"),children:"A-"}),s.jsx("button",{type:"button",className:"secondary-button static-html-presentation-text-toolbar-button",onClick:()=>o({fontSize:Math.min(160,(c??24)+2)}),disabled:!e.editable,"aria-label":a("conversation.fileViewerPresentationFontSizeIncreaseAction"),children:"A+"}),s.jsxs("select",{className:"static-html-presentation-text-toolbar-select static-html-presentation-text-toolbar-line-height",value:g,onChange:y=>o({lineHeight:y.target.value||null}),disabled:!e.editable,"aria-label":a("conversation.fileViewerPresentationLineHeightLabel"),children:[s.jsx("option",{value:"",children:a("conversation.fileViewerPresentationLineHeightAuto")}),s.jsx("option",{value:"1",children:"1.0"}),s.jsx("option",{value:"1.2",children:"1.2"}),s.jsx("option",{value:"1.4",children:"1.4"}),s.jsx("option",{value:"1.6",children:"1.6"}),s.jsx("option",{value:"1.8",children:"1.8"}),s.jsx("option",{value:"2",children:"2.0"})]})]})}),s.jsx("textarea",{hidden:!0,readOnly:!0,value:e.content.text??"","aria-hidden":"true",tabIndex:-1}),s.jsx(G$,{node:e,selectedRunIndex:t,onSelectedRunChange:n,disabled:!e.editable,onChange:i})]}):s.jsx("p",{className:"static-html-presentation-inspector-warning",children:e.lockedReason||a("conversation.fileViewerPresentationReadOnlyHint")})})})}function G$({node:e,selectedRunIndex:t,onSelectedRunChange:n,disabled:r,onChange:i}){const o=d.useMemo(()=>J$(e),[e]),l=d.useMemo(()=>o.length?t!==null&&t>=0&&t<o.length?t:0:null,[o,t]);function c(u,f){const h=o.map((m,g)=>g===u?{...Qy(m),text:Ol(f)}:Qy(m));i({text:X$(h),runs:h})}return s.jsx("div",{className:"static-html-presentation-textarea static-html-presentation-textarea-standalone static-html-presentation-runs-editor","data-testid":"static-html-presentation-runs-editor",role:"group","aria-label":a("conversation.fileViewerPresentationTextToolbar"),children:o.map((u,f)=>s.jsx("label",{className:u.className??void 0,"data-static-html-run":String(f),"data-static-html-run-wrapper":"true","data-active":l===f?"true":void 0,"data-static-html-run-text":u.text,children:s.jsx("textarea",{className:"static-html-presentation-run-input","data-static-html-run-input":"true",value:u.text,disabled:r,rows:1,spellCheck:!1,"aria-label":`${a("conversation.fileViewerPresentationNodeTextLabel")} ${f+1}`,onFocus:()=>n(f),onClick:()=>n(f),onChange:h=>{c(f,h.target.value)},style:Z$(u.style??null)})},`${f}-${u.tagName??"text"}-${u.className??"none"}`))})}function Jy(e){if(!e||!/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(e.trim()))return"#000000";const t=e.trim();return t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t}function Y$(e){return e?e==="bold"?"700":e:""}function Xy(e,t){const n=Ol(t),r=Array.isArray(e.content.runs)?e.content.runs:[];if(r.length===0)return n?[{text:n}]:null;const i=r.map(l=>({...l})),o=e4(i);return o<0?n?[{text:n}]:null:(i[o]={...i[o],text:n},i)}function J$(e){if(Array.isArray(e.content.runs)&&e.content.runs.length>0)return e.content.runs.map(n=>({...n,style:n.style?{...n.style}:null}));const t=Ol(e.content.text??"");return t?[{text:t}]:[]}function X$(e){return!e||e.length===0?"":Ol(e.map(t=>t.text).join(""))}function Qy(e){return{...e,style:e.style?{...e.style}:null}}function Q$(e){if(e)return{fontFamily:e.fontFamily??void 0,fontSize:typeof e.fontSize=="number"?`${e.fontSize}px`:void 0,fontWeight:e.fontWeight??void 0,fontStyle:e.fontStyle??void 0,lineHeight:e.lineHeight??void 0,letterSpacing:e.letterSpacing??void 0,color:e.color??void 0,textDecoration:e.textDecoration??void 0,textDecorationColor:e.textDecorationColor??void 0,backgroundColor:e.backgroundColor??void 0,whiteSpace:"pre-wrap"}}function Z$(e){return{...Q$(e),width:"100%",minHeight:"34px",padding:"6px 8px",border:"none",outline:"none",resize:"none",overflow:"hidden",background:"transparent"}}function e4(e){let t=-1,n=-1;return e.forEach((r,i)=>{const o=r.text.trim().length;o>n&&(n=o,t=i)}),t}const Zc="allow-forms allow-modals allow-scripts",t4=`${Zc} allow-same-origin`,n4=new Set(["abstract","as","async","await","break","case","catch","class","const","continue","default","delete","do","else","enum","export","extends","false","finally","for","from","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","readonly","return","static","super","switch","this","throw","true","try","type","typeof","undefined","var","void","while","with","yield"]),s4=new Set(["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","False","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","try","while","with","yield"]),r4=new Set(["case","do","done","elif","else","esac","export","fi","for","function","if","in","local","readonly","return","then","until","while"]),i4=new Set(["add","alter","and","as","asc","between","by","create","delete","desc","drop","from","group","having","insert","into","join","left","like","limit","not","null","offset","on","or","order","right","select","set","table","union","update","values","where"]),a4=new Set(["add","arg","cmd","copy","entrypoint","env","expose","from","healthcheck","label","maintainer","onbuild","run","shell","stopsignal","user","volume","workdir","as"]),o4=new Set(["trace","debug","info","warn","warning","error","fatal"]);function vK(e){return s.jsx(vp,{...e,chrome:"modal"})}function vp({workspaceId:e,filePath:t,open:n,onClose:r,onSaved:i,diffContent:o,chrome:l="modal",windowTitle:c=null,showDetachAction:u=!1,onDetach:f,previewLoader:h=vm,saveHandler:m=g4,saveDisabledReason:g=null,officeDisplayMode:p="default"}){var wt,it;const b=d.useRef(null),[y,x]=d.useState(null),[k,C]=d.useState(""),[j,H]=d.useState(null),[_,T]=d.useState(!1),[P,z]=d.useState(!1),[L,R]=d.useState(!1),[K,E]=d.useState(!1),[D,te]=d.useState("preview"),[V,ee]=d.useState("regular"),[U,he]=d.useState(0),[X,I]=d.useState("fit"),[xe,le]=d.useState(1),[M,de]=d.useState(1),[Ne,ye]=d.useState(110),[Be,We]=d.useState(!0),[Ce,ke]=d.useState("default"),{showToast:we}=Vn(),se=Hn(),ce=d.useRef(r),Y=d.useRef(we),Te=d.useMemo(()=>Cp(t),[t]),pe=d.useMemo(()=>az(o),[o]),fe=d.useMemo(()=>oz(k,pe),[k,pe]),W=(y==null?void 0:y.kind)??null,Me=!!((wt=y==null?void 0:y.capabilities)!=null&&wt.canEdit),je=!!((it=y==null?void 0:y.capabilities)!=null&&it.canRefresh),Q=d.useMemo(()=>x4(y,se.isDesktop),[se.isDesktop,y]),ge=d.useMemo(()=>k4(y,se.isDesktop),[se.isDesktop,y]),Oe=d.useMemo(()=>Uh(Q,U),[Q,U]),$e=d.useMemo(()=>w4(Q,U,M,Ne,Be),[Q,U,M,Ne,Be]),Ve=d.useMemo(()=>Uh(Q,U),[Q,U]),G=(y==null?void 0:y.content)??"",ve=d.useMemo(()=>W!=="html"||!j?null:I5({html:G,project:j}),[G,j,W]),_e=Me&&(k!==G||D==="presentation"&&!!ve&&ve!==G),nt=d.useMemo(()=>W!=="html"||!G.trim()?null:bp(G,t??"document.html"),[G,t,W]),et=d.useMemo(()=>u4({filePath:t,html:G,probe:nt}),[G,t,nt]),ot=ij(W),Ft=aj(W)&&W!=="html",bt=oj(W)&&Me&&!g,_t=se.isMobile,xt=l==="window",rt=l==="inline",It=l==="modal",$t=D==="presentation"&&W==="html",pt=!xt&&!_t&&(W==="html"||W==="office"),Ie=_t||pt?"full":V,kt=rt&&ot?"preview":D,St=c??t??a("conversation.fileViewerWindowTitle");if(d.useEffect(()=>{ce.current=r},[r]),d.useEffect(()=>{Y.current=we},[we]),d.useLayoutEffect(()=>{if(!n||!t||rt){ke("default");return}const Ze=b.current;if(!Ze||typeof window>"u"){ke("default");return}const Ht=()=>{const dt=Ze.scrollHeight>Ze.clientHeight+1?"tight":"default";ke(ft=>ft===dt?ft:dt)};if(Ht(),typeof ResizeObserver>"u")return;const gt=new ResizeObserver(Ht);gt.observe(Ze);const Nt=Ze.parentElement;return Nt&&gt.observe(Nt),()=>{gt.disconnect()}},[t,rt,n,c]),d.useEffect(()=>{if(!n){x(null),C(""),H(null),T(!1),z(!1),R(!1),E(!1),te(sj(t,null)),rj({setResourceRefreshVersion:he,setImageScale:le,setImageScaleMode:I,setPdfPage:de,setPdfScale:ye,setPdfFitWidth:We}),ee("regular");return}if(!e||!t)return;const Ze=e,Ht=t;let gt=!1;async function Nt(){T(!0);try{const dt=await h(Ze,Ht,{officeDisplayMode:p});gt||Mf(dt,Ht,{preserveMode:!1,setPreview:x,setEditorContent:C,setPresentationProject:H,setMode:te,setResourceRefreshVersion:he,setImageScale:le,setImageScaleMode:I,setPdfPage:de,setPdfScale:ye,setPdfFitWidth:We})}catch(dt){gt||(Y.current({title:Ic(dt,a("conversation.filePanelOpenFailed")),tone:"error"}),ce.current())}finally{gt||T(!1)}}return Nt(),()=>{gt=!0}},[t,p,n,h,e]),!n||!t)return null;const vt=t,Ct=e;async function J(){if(!(!Ct||!(y!=null&&y.version)||!Me)){z(!0);try{await m({workspaceId:Ct,filePath:vt,content:D==="presentation"&&j?ve??k:k,expectedVersion:y.version,preview:y});const Ht=await h(Ct,vt,{officeDisplayMode:p});Mf(Ht,vt,{preserveMode:!1,setPreview:x,setEditorContent:C,setPresentationProject:H,setMode:te,setResourceRefreshVersion:he,setImageScale:le,setImageScaleMode:I,setPdfPage:de,setPdfScale:ye,setPdfFitWidth:We}),await i(vt),we({title:a("conversation.filePanelSaveSuccess"),tone:"success"})}catch(Ze){we({title:Ic(Ze,a("conversation.filePanelSaveFailed")),tone:"error"})}finally{z(!1)}}}async function Ue(){if(!(!Ct||!je||_e)){T(!0);try{const Ze=await h(Ct,vt,{officeDisplayMode:p});Mf(Ze,vt,{preserveMode:!0,setPreview:x,setEditorContent:C,setPresentationProject:H,setMode:te,setResourceRefreshVersion:he,setImageScale:le,setImageScaleMode:I,setPdfPage:de,setPdfScale:ye,setPdfFitWidth:We}),he(Ht=>Ht+1)}catch(Ze){we({title:Ic(Ze,a("conversation.fileViewerRefreshFailed")),tone:"error"})}finally{T(!1)}}}async function ze(){if(!ge)return;const Ze=await se.bridge.openExternal(ge);Ze.ok||we({title:Ze.detail??a("conversation.fileViewerOpenExternalFailed"),tone:"error"})}async function st(){await re("pdf")}async function q(){await re("pptx")}async function re(Ze){if(!Ct||W!=="html"||!et||(Ze==="pdf"?L:K))return;const gt=D==="presentation"&&j?ve??k:k;if(!gt.trim()){we({title:Ze==="pdf"?a("conversation.fileViewerExportPdfMissingHtml"):a("conversation.fileViewerExportPptxMissingHtml"),tone:"error"});return}Ze==="pdf"?R(!0):E(!0);try{const Nt=await y5({workspaceId:Ct,path:vt,htmlContent:gt,format:Ze}),dt=await sz(Nt.taskId);if(dt.status!=="succeeded")throw new rr(500,{detail:dt.errorMessage??(Ze==="pdf"?a("conversation.fileViewerExportPdfFailed"):a("conversation.fileViewerExportPptxFailed")),error_code:"PRESENTATION_EXPORT_FAILED"});const ft=await k5(dt.taskId);cz(ft.fileName,ft.blob),we({title:Ze==="pdf"?a("conversation.fileViewerExportPdfSuccess",{path:ft.fileName}):a("conversation.fileViewerExportPptxSuccess",{path:ft.fileName}),tone:"success"})}catch(Nt){we({title:Ic(Nt,Ze==="pdf"?a("conversation.fileViewerExportPdfFailed"):a("conversation.fileViewerExportPptxFailed")),tone:"error"})}finally{Ze==="pdf"?R(!1):E(!1)}}const ue=p4({canShowPresentationTab:et,canShowPreviewTab:ot,canShowCodeTab:Ft,canShowEditTab:bt}),Re=b4({preview:y,canOpenExternal:!!ge,canExportPdf:W==="html"&&et,canExportPptx:W==="html"&&et,exportingPdf:L,exportingPptx:K,isDirty:_e,handleRefreshPreview:Ue,handleExportPdf:st,handleExportPptx:q,handleOpenExternal:ze,imageScaleMode:X,imageScale:xe,setImageScale:le,setImageScaleMode:I,pdfPage:M,setPdfPage:de,pdfScale:Ne,setPdfScale:ye,pdfFitWidth:Be,setPdfFitWidth:We}),Se=_t?Re.filter(y4):Re,Ke=!rt&&Me&&kt==="edit"&&!$t,De=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"file-viewer-header-tabs",role:"tablist","aria-label":a("conversation.fileViewerModeLabel"),children:[ue.includes("presentation")?s.jsx("button",{type:"button",className:"file-viewer-tab","data-active":D==="presentation",role:"tab","aria-selected":D==="presentation",onClick:()=>te("presentation"),children:a("conversation.fileViewerPresentation")}):null,ue.includes("preview")?s.jsx("button",{type:"button",className:"file-viewer-tab","data-active":D==="preview",role:"tab","aria-selected":D==="preview",onClick:()=>te("preview"),children:a("conversation.fileViewerPreview")}):null,ue.includes("code")?s.jsx("button",{type:"button",className:"file-viewer-tab","data-active":D==="code",role:"tab","aria-selected":D==="code",onClick:()=>te("code"),children:a("conversation.fileViewerCode")}):null,ue.includes("edit")?s.jsx("button",{type:"button",className:"file-viewer-tab","data-active":D==="edit",role:"tab","aria-selected":D==="edit",onClick:()=>te("edit"),disabled:!Me,children:a("conversation.fileViewerEdit")}):null]}),!xt&&!_t&&!pt?s.jsxs("div",{className:"file-viewer-size-group",role:"group","aria-label":a("conversation.fileViewerSizeLabel"),children:[s.jsx("button",{type:"button",className:"secondary-button file-viewer-action-button","data-active":V==="regular",onClick:()=>ee("regular"),children:a("conversation.fileViewerSizeDefault")}),s.jsx("button",{type:"button",className:"secondary-button file-viewer-action-button","data-active":V==="full",onClick:()=>ee("full"),children:a("conversation.fileViewerSizeFull")})]}):null,s.jsxs("div",{className:"file-viewer-header-action-buttons",children:[Se.map(Ze=>s.jsx("button",{type:"button",className:"secondary-button file-viewer-action-button","data-active":Ze.active?"true":void 0,onClick:()=>void Ze.onClick(),disabled:Ze.disabled,children:Ze.label},Ze.id)),Ke?s.jsx("button",{type:"button",className:"primary-button",onClick:()=>void J(),disabled:!_e||P,children:P?a("conversation.filePanelSaving"):a("conversation.filePanelSave")}):null]})]}),He=u&&f?s.jsx("button",{type:"button",className:"workbench-modal-close file-viewer-detach-button","aria-label":a("conversation.fileViewerOpenInWindow"),title:a("conversation.fileViewerOpenInWindow"),onClick:()=>void f(),children:s.jsx("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true",children:s.jsx("path",{d:"M5 3.5h7.5V11M12.5 3.5 7.8 8.2M3.5 6.5v6h6",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round"})})}):null,lt=s.jsxs(s.Fragment,{children:[_t&&It?s.jsx("div",{className:"file-viewer-toolbar",children:De}):null,s.jsx("div",{className:"file-viewer-body",children:_?s.jsx("p",{className:"status-text",children:a("common.loading")}):(y==null?void 0:y.supported)===!1?s.jsx("p",{className:"status-text",children:y.reason??a("conversation.filePanelUnsupported")}):kt==="presentation"&&W==="html"?s.jsx(P$,{filePath:t,html:k,baseHref:Ve,onProjectChange:H,onSave:()=>void J(),canSave:_e,saving:P}):kt==="edit"?s.jsx(j4,{content:k,language:Te,onContentChange:C}):kt==="preview"&&W==="html"?s.jsx(S4,{src:Ve,workspaceId:Ct,filePath:t,overviewMarkers:pe,overviewTotalLines:fe}):kt==="preview"&&W==="image"?s.jsx(N4,{src:Oe,filePath:t,scale:xe,scaleMode:X,overviewMarkers:pe,overviewTotalLines:fe}):kt==="preview"&&W==="pdf"?s.jsx(T4,{src:$e,filePath:t,overviewMarkers:pe,overviewTotalLines:fe}):kt==="preview"&&W==="office"?s.jsx(I4,{onlyOffice:(y==null?void 0:y.onlyOffice)??null,filePath:t,overviewMarkers:pe,overviewTotalLines:fe,mode:se.isMobile?"mobile":"desktop",displayMode:p}):kt==="preview"&&W==="markdown"?s.jsx(P4,{content:k,overviewMarkers:pe,overviewTotalLines:fe}):s.jsx(uj,{content:k,language:Te,overviewMarkers:pe,overviewTotalLines:fe})})]});return xt?s.jsxs("section",{className:"file-viewer-window-panel","aria-label":St,children:[s.jsxs("header",{className:"file-viewer-window-header","data-tauri-drag-region":"",children:[s.jsx("div",{className:"file-viewer-window-title-wrap","data-tauri-drag-region":"",children:s.jsx("h1",{className:"file-viewer-title","data-scale-tier":Ce,"data-tauri-drag-region":"",ref:b,children:c??t})}),s.jsxs("div",{className:"file-viewer-header-controls file-viewer-window-controls","data-window-drag":"ignore",children:[De,s.jsx(Zk,{onClick:r})]})]}),s.jsx("div",{className:"file-viewer-modal-body file-viewer-window-body",children:lt})]}):rt?s.jsx("section",{className:"file-viewer-inline-panel","aria-label":St,children:lt}):s.jsx(Qr,{open:n,title:c??t,size:Ie,layout:"viewer",className:`file-viewer-modal${se.isDesktop&&Ie!=="full"?" is-resizable":""}`,bodyClassName:"file-viewer-modal-body",titleClassName:"file-viewer-title",titleRef:b,titleProps:{"data-scale-tier":Ce},headerActions:_t?void 0:s.jsx("div",{className:"file-viewer-header-controls",children:De}),beforeCloseButton:He,onClose:r,children:lt})}const l4=new Set(["slides","slide","presentations","presentation","deck","decks","ppt","pptx"]),c4=new Set(["tools","tool"]);function u4(e){const{filePath:t,html:n,probe:r}=e;if(!(r!=null&&r.supported)||!n.trim())return!1;const i=d4(t);return i.some(o=>c4.has(o))?!1:f4(n)||i.some(o=>l4.has(o))?!0:r.strategy==="deck-direct-child"?!1:h4(n)}function d4(e){return e?e.split(/[\\/]+/).map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function f4(e){return/<meta[^>]+name=["'](?:codingns-preview-mode|codingns-presentation|cns-preview-mode|cns-presentation)["'][^>]+content=["']presentation["'][^>]*>/i.test(e)||/\bdata-(?:codingns|cns)-(?:preview-mode|presentation)\s*=\s*["']presentation["']/i.test(e)}function h4(e){const t=/\bclass\s*=\s*["'][^"']*\bdeck\b[^"']*["']/i.test(e),n=/\bclass\s*=\s*["'][^"']*\bslide\b[^"']*["']/i.test(e),r=/\bdata-(?:slide|title)\s*=\s*["'][^"']+["']/i.test(e),i=/--deck-width\s*:|--deck-height\s*:|aspect-ratio\s*:\s*16\s*\/\s*9/i.test(e);return n&&(t||r||i)}function sj(e,t){return t==="markdown"||t==="html"||t==="image"||t==="pdf"||t==="office"||ez(e??"")||tz(e??"")?"preview":"code"}function Mf(e,t,n){n.setPreview(e),n.setEditorContent(e.content??""),n.setPresentationProject(null),n.setMode(r=>n.preserveMode&&m4(r,e.kind)?r:sj(t,e.kind)),rj(n)}function rj(e){e.setResourceRefreshVersion(0),e.setImageScale(1),e.setImageScaleMode("fit"),e.setPdfPage(1),e.setPdfScale(110),e.setPdfFitWidth(!0)}function ij(e){return e==="markdown"||e==="html"||e==="image"||e==="pdf"||e==="office"}function aj(e){return e==="text"||e==="markdown"||e==="html"}function oj(e){return e==="text"||e==="markdown"||e==="html"}function m4(e,t){return e==="presentation"?t==="html":e==="preview"?ij(t):e==="code"?aj(t):oj(t)}function p4(e){const t=[];return e.canShowPresentationTab&&t.push("presentation"),e.canShowPreviewTab&&t.push("preview"),e.canShowCodeTab&&t.push("code"),e.canShowEditTab&&t.push("edit"),t}async function g4(e){await q0(e.workspaceId,e.filePath,e.content,e.expectedVersion)}function b4(e){var r,i;if(!((r=e.preview)!=null&&r.supported))return[];const t=[],n=!((i=e.preview.capabilities)!=null&&i.canRefresh)||e.isDirty;return e.preview.kind==="image"&&t.push({id:"image-zoom-out",label:a("conversation.fileViewerZoomOut"),onClick:()=>{e.setImageScaleMode("custom"),e.setImageScale(o=>Math.max(.25,Zy(o-.25)))}},{id:"image-zoom-in",label:a("conversation.fileViewerZoomIn"),onClick:()=>{e.setImageScaleMode("custom"),e.setImageScale(o=>Math.min(4,Zy(o+.25)))}},{id:"image-fit",label:a("conversation.fileViewerFit"),active:e.imageScaleMode==="fit",onClick:()=>{e.setImageScaleMode("fit"),e.setImageScale(1)}},{id:"image-actual",label:a("conversation.fileViewerActualSize"),active:e.imageScaleMode==="actual",onClick:()=>{e.setImageScaleMode("actual"),e.setImageScale(1)}},{id:"image-refresh",label:a("conversation.fileViewerRefreshPreview"),disabled:n,onClick:e.handleRefreshPreview}),e.preview.kind==="pdf"&&t.push({id:"pdf-refresh",label:a("conversation.fileViewerRefreshPreview"),disabled:n,onClick:e.handleRefreshPreview}),e.preview.kind==="office"&&t.push({id:"office-refresh",label:a("conversation.fileViewerRefreshPreview"),disabled:n,onClick:e.handleRefreshPreview}),(e.preview.kind==="html"||e.preview.kind==="markdown"||e.preview.kind==="text")&&t.push({id:"text-refresh",label:a("conversation.fileViewerRefreshPreview"),disabled:n,onClick:e.handleRefreshPreview}),e.preview.kind==="html"&&e.canExportPdf&&t.push({id:"presentation-export-pdf",label:e.exportingPdf?a("conversation.fileViewerExportPdfRunning"):a("conversation.fileViewerExportPdf"),disabled:e.exportingPdf,onClick:e.handleExportPdf}),e.preview.kind==="html"&&e.canExportPptx&&t.push({id:"presentation-export-pptx",label:e.exportingPptx?a("conversation.fileViewerExportPptxRunning"):a("conversation.fileViewerExportPptx"),disabled:e.exportingPptx,onClick:e.handleExportPptx}),e.canOpenExternal&&t.push({id:"open-external",label:a("conversation.fileViewerOpenExternal"),onClick:e.handleOpenExternal}),t}function y4(e){return e.id.endsWith("-refresh")||e.id==="text-refresh"||e.id==="presentation-export-pdf"||e.id==="presentation-export-pptx"}function Uh(e,t){if(!e)return null;const n=new URL(e,window.location.origin);return n.searchParams.set("_preview",String(t)),n.searchParams.set("_cns_parent_origin",window.location.origin),n.hash="",n.toString()}function x4(e,t){var n;if(!e)return null;if(e.previewPath){if(!t&&typeof window<"u"&&((n=window.location)!=null&&n.origin))return new URL(e.previewPath,window.location.origin).toString();if(t){const r=lj(e.previewPath);if(r)return r}}return e.previewUrl??null}function k4(e,t){var n;if(!e)return null;if(e.previewPath){if(!t&&typeof window<"u"&&((n=window.location)!=null&&n.origin))return new URL(e.previewPath,window.location.origin).toString();if(t){const r=lj(e.previewPath);if(r)return r}}return e.previewUrl??null}function lj(e){try{const t=Fu(jl()).baseUrl;return Fk(e,t)}catch{return null}}function w4(e,t,n,r,i){const o=Uh(e,t);if(!o)return null;const l=new URL(o,window.location.origin),c=new URLSearchParams;return c.set("page",String(n)),c.set("zoom",i?"page-width":String(r)),l.hash=c.toString(),l.toString()}function v4(e){var t;if(typeof window>"u"||!((t=window.location)!=null&&t.origin))return Zc;try{if(new URL(e,window.location.origin).origin!==window.location.origin)return t4}catch{return Zc}return Zc}function Zy(e){return Math.round(e*100)/100}function S4({src:e,workspaceId:t,filePath:n,overviewMarkers:r,overviewTotalLines:i}){const o=d.useRef(null),l=d.useRef(null);if(d.useEffect(()=>{if(!e||!t)return;const u=RC({iframe:l.current,workspaceId:t});function f(h){u.onMessage(h)}return window.addEventListener("message",f),()=>{window.removeEventListener("message",f),u.dispose()}},[e,t]),!e)return s.jsx("p",{className:"status-text",children:a("conversation.fileViewerHtmlPreviewUnavailable")});const c=v4(e);return s.jsx(Fl,{overviewMarkers:r,overviewTotalLines:i,scrollContainerRef:o,children:s.jsx("div",{className:"file-viewer-html-frame-shell",ref:o,children:s.jsx("iframe",{ref:l,className:"file-viewer-html-frame","data-testid":"file-viewer-html-preview",title:n,src:e,sandbox:c},e)})})}function Fl({children:e,overviewMarkers:t,overviewTotalLines:n,scrollContainerRef:r}){const i=C4(t);return s.jsxs("div",{className:"file-viewer-preview-overview-shell",children:[e,i?s.jsx("div",{className:"file-viewer-preview-diff-badge","data-kind":i,children:i==="modify"?a("conversation.fileViewerDiffModified"):a("conversation.fileViewerDiffAdded")}):null,s.jsx(gj,{markers:t,totalLines:n,scrollContainerRef:r,hideWithoutMarkers:!0})]})}function C4(e){return e.some(t=>t.kind==="modify")?"modify":e.some(t=>t.kind==="add")?"add":null}function j4(e){return s.jsx(uj,{content:e.content,language:e.language,overviewMarkers:[],overviewTotalLines:Math.max(1,e.content.split(/\r?\n/).length),editable:!0,onContentChange:e.onContentChange})}function N4({src:e,filePath:t,scale:n,scaleMode:r,overviewMarkers:i,overviewTotalLines:o}){const l=d.useRef(null);return e?s.jsx(Fl,{overviewMarkers:i,overviewTotalLines:o,scrollContainerRef:l,children:s.jsx("div",{className:"file-viewer-media-shell","data-mode":r,ref:l,children:s.jsx("div",{className:"file-viewer-image-stage",children:s.jsx("img",{className:"file-viewer-image","data-testid":"file-viewer-image-preview","data-mode":r,src:e,alt:t,style:r==="fit"?void 0:{transform:`scale(${n})`}})})})}):s.jsx("p",{className:"status-text",children:a("conversation.fileViewerImageUnavailable")})}function T4({src:e,filePath:t,overviewMarkers:n,overviewTotalLines:r}){const i=d.useRef(null);return e?s.jsx(Fl,{overviewMarkers:n,overviewTotalLines:r,scrollContainerRef:i,children:s.jsx("div",{className:"file-viewer-pdf-shell",ref:i,children:s.jsx("iframe",{className:"file-viewer-pdf-frame","data-testid":"file-viewer-pdf-preview",title:t,src:e},e)})}):s.jsx("p",{className:"status-text",children:a("conversation.fileViewerPdfUnavailable")})}const Ef=new Map;function I4({onlyOffice:e,filePath:t,overviewMarkers:n,overviewTotalLines:r,mode:i,displayMode:o}){const l=d.useRef(null),c=d.useRef(null),u=d.useMemo(()=>`onlyoffice-${t.replace(/[^a-zA-Z0-9_-]+/g,"-")}-${Math.random().toString(36).slice(2,8)}`,[t]),[f,h]=d.useState(null),[m,g]=d.useState(!1);return d.useEffect(()=>{let p=!1;if(!e){h(a("conversation.fileViewerOfficeUnavailable")),g(!1);return}return h(null),g(!1),A4(e.apiScriptUrl).then(()=>{var b,y,x;if(!p){if(!((b=window.DocsAPI)!=null&&b.DocEditor))throw new Error(a("conversation.fileViewerOfficeScriptUnavailable"));(x=(y=c.current)==null?void 0:y.destroyEditor)==null||x.call(y),c.current=new window.DocsAPI.DocEditor(u,e.editorConfig),g(!0)}}).catch(b=>{p||h(b instanceof Error?b.message:a("conversation.fileViewerOfficeUnavailable"))}),()=>{var b,y;p=!0,(y=(b=c.current)==null?void 0:b.destroyEditor)==null||y.call(b),c.current=null}},[u,e]),e?s.jsx(Fl,{overviewMarkers:n,overviewTotalLines:r,scrollContainerRef:l,children:s.jsxs("div",{className:"file-viewer-office-shell",ref:l,children:[!m&&!f?s.jsx("p",{className:"status-text",children:a("conversation.fileViewerOfficeLoading")}):null,f?s.jsx("p",{className:"status-text",children:f}):null,s.jsx("div",{id:u,className:"file-viewer-office-stage","data-testid":"file-viewer-office-preview","aria-label":t})]})}):s.jsx("p",{className:"status-text",children:a("conversation.fileViewerOfficeUnavailable")})}function A4(e){const t=Ef.get(e);if(t)return t;const n=new Promise((r,i)=>{if(typeof document>"u"){i(new Error(a("conversation.fileViewerOfficeUnavailable")));return}const o=document.querySelector(`script[data-onlyoffice-src="${R4(e)}"]`);if((o==null?void 0:o.dataset.loaded)==="true"){r();return}const l=o??document.createElement("script");l.src=e,l.async=!0,l.dataset.onlyofficeSrc=e,l.onload=()=>{l.dataset.loaded="true",r()},l.onerror=()=>{Ef.delete(e),i(new Error(a("conversation.fileViewerOfficeScriptUnavailable")))},o||document.head.appendChild(l)});return Ef.set(e,n),n}function R4(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function P4({content:e,overviewMarkers:t,overviewTotalLines:n}){const r=d.useRef(null),i=d.useMemo(()=>M4(t),[t]),o=d.useMemo(()=>E4(i),[i]);return s.jsx(Fl,{overviewMarkers:t,overviewTotalLines:n,scrollContainerRef:r,children:s.jsx("div",{className:"markdown-content file-viewer-markdown",ref:r,children:s.jsx(Tv,{remarkPlugins:[Xv],components:o,children:e})})})}function M4(e){return{ranges:e.map(t=>({start:t.line,end:t.line+t.span-1,kind:t.kind})).sort((t,n)=>t.start-n.start)}}function E4(e){return{h1(t){const{node:n,className:r,...i}=t;return s.jsx("h1",{...i,className:Lr(r,n,e)})},h2(t){const{node:n,className:r,...i}=t;return s.jsx("h2",{...i,className:Lr(r,n,e)})},h3(t){const{node:n,className:r,...i}=t;return s.jsx("h3",{...i,className:Lr(r,n,e)})},h4(t){const{node:n,className:r,...i}=t;return s.jsx("h4",{...i,className:Lr(r,n,e)})},h5(t){const{node:n,className:r,...i}=t;return s.jsx("h5",{...i,className:Lr(r,n,e)})},h6(t){const{node:n,className:r,...i}=t;return s.jsx("h6",{...i,className:Lr(r,n,e)})},p(t){const{node:n,className:r,...i}=t;return s.jsx("p",{...i,className:Lr(r,n,e)})},li(t){const{node:n,className:r,...i}=t;return s.jsx("li",{...i,className:Lr(r,n,e)})},blockquote(t){const{node:n,className:r,...i}=t;return s.jsx("blockquote",{...i,className:Lr(r,n,e)})},table(t){const{node:n,className:r,...i}=t;return s.jsx("table",{...i,className:Lr(r,n,e)})},pre(t){const{node:n,className:r}=t,i=F4(t.children);return i?s.jsx(O4,{content:i.content,language:i.language,codeClassName:i.codeClassName,changeKind:cj(n,e)}):s.jsx("pre",{className:Lr(r,n,e),children:t.children})},code(t){const n=typeof t.className=="string"?t.className:"";return s.jsx("code",{className:n||void 0,children:t.children})}}}function Lr(e,t,n){const r=typeof e=="string"?e:"",i=cj(t,n);return dj(r,i?"markdown-diff-block":null,i?`diff-block-${i}`:null)}function cj(e,t){var l,c,u,f;const n=(c=(l=e==null?void 0:e.position)==null?void 0:l.start)==null?void 0:c.line,r=(f=(u=e==null?void 0:e.position)==null?void 0:u.end)==null?void 0:f.line;if(!n||!r)return null;let i=!1;const o=L4(t.ranges,n);for(let h=o;h<t.ranges.length;h+=1){const m=t.ranges[h];if(!m||m.start>r)break;if(m.end>=n){if(m.kind==="modify")return"modify";i=!0}}return i?"add":null}function L4(e,t){let n=0,r=e.length;for(;n<r;){const i=Math.floor((n+r)/2),o=e[i];o&&o.end<t?n=i+1:r=i}return n}function uj({content:e,language:t,overviewMarkers:n=[],overviewTotalLines:r,editable:i=!1,onContentChange:o}){const l=e.split(/\r?\n/),c=d.useRef(null),u=d.useMemo(()=>{const f=new Map;for(const h of n)for(let m=0;m<h.span;m++)f.set(h.line+m,h.kind);return f},[n]);return s.jsxs("div",{className:"file-viewer-code-block",children:[s.jsxs("div",{className:"file-viewer-code-header",children:[s.jsx("span",{className:"file-viewer-code-header-label",children:pj(t)}),s.jsx(fj,{content:e})]}),s.jsxs("div",{className:"file-viewer-scroll-shell",children:[s.jsx("div",{className:"file-viewer-code-body","data-editable":i?"true":void 0,ref:c,children:i?s.jsx(D4,{content:e,language:t,onContentChange:o,lineChangeMap:u}):l.map((f,h)=>{const m=hj(f,t),g=h+1,p=u.get(g);return s.jsxs("div",{className:`file-viewer-code-line${p?` diff-line-${p}`:""}`,children:[s.jsx("span",{className:"file-viewer-code-gutter",children:g}),s.jsx("code",{className:"file-viewer-code-content",children:m.length?m.map((b,y)=>s.jsx("span",{className:`code-token ${b.kind}`,children:b.text},`${h}-${y}-${b.text}`)):s.jsx("span",{className:"code-token plain",children:" "})})]},`${h}-${f}`)})}),s.jsx(gj,{markers:n,totalLines:r,scrollContainerRef:c})]})]})}function D4({content:e,language:t,onContentChange:n,lineChangeMap:r}){const i=d.useRef(null),o=d.useRef(null),[l,c]=d.useState([]);d.useLayoutEffect(()=>{const h=i.current;if(!h)return;let m=0;const g=h;function p(){const k=Array.from(g.querySelectorAll("[data-editor-line-index]")).map(C=>Math.max(24,Math.ceil(C.getBoundingClientRect().height)));c(C=>C.length===k.length&&C.every((j,H)=>j===k[H])?C:k)}const b=globalThis.window;function y(){if(!b){p();return}b.cancelAnimationFrame(m),m=b.requestAnimationFrame(p)}y();const x=typeof ResizeObserver>"u"?null:new ResizeObserver(y);return x==null||x.observe(g),()=>{b==null||b.cancelAnimationFrame(m),x==null||x.disconnect()}},[e,t]);function u(h){const m=i.current,g=o.current;m&&(m.scrollTop=h.currentTarget.scrollTop,m.scrollLeft=h.currentTarget.scrollLeft,g&&(g.scrollTop=h.currentTarget.scrollTop))}const f=e.split(/\r?\n/);return s.jsxs("div",{className:"file-viewer-code-editor-shell",children:[s.jsx("div",{ref:o,className:"file-viewer-code-editor-gutter","aria-hidden":"true",children:f.map((h,m)=>{const g=m+1,p=r.get(g);return s.jsx("div",{className:`file-viewer-code-editor-gutter-line${p?` diff-line-${p}`:""}`,style:l[m]?{height:`${l[m]}px`}:void 0,children:s.jsx("span",{className:"file-viewer-code-gutter",children:g})},`gutter-${m}-${h}`)})}),s.jsxs("div",{className:"file-viewer-code-editor-pane",children:[s.jsx("div",{ref:i,className:"file-viewer-code-editor-render","data-testid":"file-viewer-inline-render","aria-hidden":"true",children:f.map((h,m)=>{const g=hj(h,t),p=m+1,b=r.get(p);return s.jsx("div",{className:`file-viewer-code-editor-line${b?` diff-line-${b}`:""}`,"data-editor-line-index":m,children:s.jsx("code",{className:"file-viewer-code-content",children:g.length?g.map((y,x)=>s.jsx("span",{className:`code-token ${y.kind}`,children:y.text},`${m}-${x}-${y.text}`)):s.jsx("span",{className:"code-token plain",children:" "})})},`${m}-${h}`)})}),s.jsx("textarea",{className:"file-viewer-editor file-viewer-code-editor-input","data-testid":"file-viewer-editor",value:e,onChange:h=>n==null?void 0:n(h.target.value),onScroll:u,spellCheck:!1})]})]})}function O4({content:e,language:t,codeClassName:n,changeKind:r=null}){const i=t?jp(t):null;return s.jsxs("div",{className:dj("file-viewer-markdown-copy-block",r?"markdown-diff-block":null,r?`diff-block-${r}`:null),children:[s.jsxs("div",{className:"file-viewer-markdown-copy-header",children:[s.jsx("span",{className:"file-viewer-markdown-copy-label",children:i?pj(i):a("conversation.fileViewerPlainText")}),s.jsx(fj,{content:e})]}),s.jsx("pre",{className:n,children:s.jsx("code",{children:e})})]})}function dj(...e){return e.filter(Boolean).join(" ")||void 0}function fj({content:e}){const{showToast:t}=Vn(),n=Hn(),[r,i]=d.useState(!1);if(!e.trim())return null;async function o(){if(!r){i(!0);try{await B4(e,n),t({title:a("conversation.copyContentSuccess"),tone:"success"})}catch(l){t({title:l instanceof Error?l.message:a("conversation.copyContentFailed"),tone:"error"})}finally{i(!1)}}}return s.jsx("button",{type:"button",className:"file-viewer-copy-button","aria-label":a("conversation.copyAction"),title:a("conversation.copyAction"),onClick:()=>void o(),disabled:r,children:s.jsx(nz,{})})}function qh(e){var t;return typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(n=>qh(n)).join(""):d.isValidElement(e)?qh(((t=e.props)==null?void 0:t.children)??""):""}function F4(e){const t=Array.isArray(e)?e[0]:e;if(!d.isValidElement(t))return null;const n=t.props,r=typeof n.className=="string"?n.className:"",i=/language-([^\s]+)/.exec(r);return{content:qh(n.children).replace(/\n$/,""),codeClassName:r||void 0,language:(i==null?void 0:i[1])??null}}function _4(e){if(typeof document>"u"||typeof document.execCommand!="function")return!1;const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(t)}}async function B4(e,t){var n;if(!(t.isDesktop&&(await t.bridge.writeClipboardText(e)).ok)){if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText))try{await navigator.clipboard.writeText(e);return}catch{}if(!_4(e))throw new Error(a("conversation.copyContentFailed"))}}function hj(e,t){const n=jp(t);return n==="json"?W4(e):n==="yaml"?U4(e):n==="toml"?q4(e):n==="ini"?mj(e):n==="env"?V4(e):n==="properties"?K4(e):n==="conf"?G4(e):n==="editorconfig"?Y4(e):n==="dockerfile"?J4(e):n==="gitignore"?X4(e):n==="log"?Q4(e):n==="python"?al(e,s4,"#"):n==="shell"?al(e,r4,"#"):n==="sql"?H4(e):n==="html"||n==="xml"?$4(e):n==="css"?z4(e):n==="markdown"?[{text:e,kind:"plain"}]:al(e,n4,"//")}function al(e,t,n){const r=[];let i=0;for(;i<e.length;){const o=e.slice(i);if(o.startsWith(n)){r.push({text:o,kind:"comment"});break}const l=/^(?:'[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"|`[^`\\]*(?:\\.[^`\\]*)*`)/.exec(o);if(l){r.push({text:l[0],kind:"string"}),i+=l[0].length;continue}const c=/^(?:0x[\da-fA-F]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)/.exec(o);if(c){r.push({text:c[0],kind:"number"}),i+=c[0].length;continue}const u=/^[A-Za-z_][\w$-]*/.exec(o);if(u){const h=u[0],m=h.toLowerCase();h==="true"||h==="false"||m==="true"||m==="false"?r.push({text:h,kind:"boolean"}):h==="null"||h==="None"||m==="none"?r.push({text:h,kind:"null"}):t.has(h)||t.has(m)?r.push({text:h,kind:"keyword"}):r.push({text:h,kind:"plain"}),i+=h.length;continue}const f=/^(?:===|!==|==|!=|<=|>=|=>|&&|\|\||[+\-*/%=<>!?:|&^~]+)/.exec(o);if(f){r.push({text:f[0],kind:"operator"}),i+=f[0].length;continue}r.push({text:o[0]??"",kind:"plain"}),i+=1}return r}function W4(e){const t=[];let n=0;for(;n<e.length;){const r=e.slice(n),i=/^"(?:[^"\\]|\\.)*"/.exec(r);if(i){const u=e.slice(n+i[0].length).trimStart()[0];t.push({text:i[0],kind:u===":"?"attr":"string"}),n+=i[0].length;continue}const o=/^(?:-?\d+(?:\.\d+)?(?:e[+-]?\d+)?)/i.exec(r);if(o){t.push({text:o[0],kind:"number"}),n+=o[0].length;continue}const l=/^(?:true|false|null)\b/.exec(r);if(l){const u=l[0]==="null"?"null":"boolean";t.push({text:l[0],kind:u}),n+=l[0].length;continue}const c=/^(?::|,|\{|\}|\[|\])/.exec(r);if(c){t.push({text:c[0],kind:"operator"}),n+=c[0].length;continue}t.push({text:r[0]??"",kind:"plain"}),n+=1}return t}function $4(e){const t=[];let n=0;for(;n<e.length;){const r=e.slice(n);if(r.startsWith("<!--")){t.push({text:r,kind:"comment"});break}const i=/^(<\/?[\w:-]+)/.exec(r);if(i){t.push({text:i[0],kind:"tag"}),n+=i[0].length;continue}const o=/^([\w:-]+)(=)/.exec(r);if(o){t.push({text:o[1]??"",kind:"attr"}),t.push({text:o[2]??"",kind:"operator"}),n+=o[0].length;continue}const l=/^(?:'[^']*'|"[^"]*")/.exec(r);if(l){t.push({text:l[0],kind:"string"}),n+=l[0].length;continue}const c=/^(?:\/?>)/.exec(r);if(c){t.push({text:c[0],kind:"operator"}),n+=c[0].length;continue}t.push({text:r[0]??"",kind:"plain"}),n+=1}return t}function z4(e){const t=[];let n=0;for(;n<e.length;){const r=e.slice(n);if(r.startsWith("/*")){t.push({text:r,kind:"comment"});break}const i=/^(?:'[^']*'|"[^"]*")/.exec(r);if(i){t.push({text:i[0],kind:"string"}),n+=i[0].length;continue}const o=/^([A-Za-z-]+)(\s*:)/.exec(r);if(o){t.push({text:o[1]??"",kind:"attr"}),t.push({text:o[2]??"",kind:"operator"}),n+=o[0].length;continue}const l=/^(?:#(?:[\da-fA-F]{3,8})|\d+(?:\.\d+)?(?:px|rem|em|vh|vw|%)?)/.exec(r);if(l){t.push({text:l[0],kind:"number"}),n+=l[0].length;continue}const c=/^(?:@media|@supports|@import|@keyframes)\b/.exec(r);if(c){t.push({text:c[0],kind:"keyword"}),n+=c[0].length;continue}const u=/^(?:[{}:;(),.>])/.exec(r);if(u){t.push({text:u[0],kind:"operator"}),n+=u[0].length;continue}t.push({text:r[0]??"",kind:"plain"}),n+=1}return t}function H4(e){return al(e,i4,"--")}function U4(e){const t=[];let n=0;for(;n<e.length;){const r=e.slice(n);if(r.startsWith("#")){t.push({text:r,kind:"comment"});break}const i=/^([A-Za-z0-9_.-]+)(\s*:)/.exec(r);if(i){t.push({text:i[1]??"",kind:"attr"}),t.push({text:i[2]??"",kind:"operator"}),n+=i[0].length;continue}const o=/^(?:'[^']*'|"[^"]*")/.exec(r);if(o){t.push({text:o[0],kind:"string"}),n+=o[0].length;continue}const l=/^(?:-?\d+(?:\.\d+)?)/.exec(r);if(l){t.push({text:l[0],kind:"number"}),n+=l[0].length;continue}const c=/^(?:true|false|yes|no|null|~)\b/i.exec(r);if(c){const f=c[0].toLowerCase(),h=f==="null"||f==="~"?"null":"boolean";t.push({text:c[0],kind:h}),n+=c[0].length;continue}const u=/^(?:[-?:,[\]{}|>])/.exec(r);if(u){t.push({text:u[0],kind:"operator"}),n+=u[0].length;continue}t.push({text:r[0]??"",kind:"plain"}),n+=1}return t}function q4(e){const t=[];let n=0;for(;n<e.length;){const r=e.slice(n);if(r.startsWith("#")){t.push({text:r,kind:"comment"});break}const i=/^(\[\[?[^\]]+\]?\])/.exec(r);if(i){t.push({text:i[0],kind:"tag"}),n+=i[0].length;continue}const o=/^([A-Za-z0-9_.-]+)(\s*=)/.exec(r);if(o){t.push({text:o[1]??"",kind:"attr"}),t.push({text:o[2]??"",kind:"operator"}),n+=o[0].length;continue}const l=dd(r,{trueValues:["true"],falseValues:["false"],nullValues:[]});if(l){t.push(...l.tokens),n+=l.length;continue}const c=/^(?:[,[\]{}])/.exec(r);if(c){t.push({text:c[0],kind:"operator"}),n+=c[0].length;continue}t.push({text:r[0]??"",kind:"plain"}),n+=1}return t}function mj(e){const t=[];let n=0;for(;n<e.length;){const r=e.slice(n),i=r.trimStart();if(i.startsWith(";")||i.startsWith("#")){t.push({text:r,kind:"comment"});break}const o=/^(\[[^\]]+\])/.exec(r);if(o){t.push({text:o[0],kind:"tag"}),n+=o[0].length;continue}const l=/^([A-Za-z0-9_.-]+)(\s*[=:])/.exec(r);if(l){t.push({text:l[1]??"",kind:"attr"}),t.push({text:l[2]??"",kind:"operator"}),n+=l[0].length;continue}const c=dd(r,{trueValues:["true","yes","on"],falseValues:["false","no","off"],nullValues:["null"]});if(c){t.push(...c.tokens),n+=c.length;continue}t.push({text:r[0]??"",kind:"plain"}),n+=1}return t}function V4(e){if(e.trimStart().startsWith("#"))return[{text:e,kind:"comment"}];const n=/^(\s*)(export)(\s+)/.exec(e),r=n?n[0].length:0,i=[];n&&(i.push({text:n[1]??"",kind:"plain"}),i.push({text:n[2]??"",kind:"keyword"}),i.push({text:n[3]??"",kind:"plain"}));const o=e.slice(r),l=/^([A-Za-z_][A-Za-z0-9_]*)(=)/.exec(o);if(!l)return mj(e);i.push({text:l[1]??"",kind:"attr"}),i.push({text:l[2]??"",kind:"operator"});const c=o.slice(l[0].length),u=dd(c,{trueValues:["true"],falseValues:["false"],nullValues:["null"]});return u?(i.push(...u.tokens),i):(i.push({text:c,kind:"plain"}),i)}function K4(e){return Sp(e,{commentPrefixes:["#","!"],allowSection:!1,delimiters:["=",":"]})}function G4(e){return Sp(e,{commentPrefixes:["#",";"],allowSection:!0,delimiters:["=",":"]})}function Y4(e){return Sp(e,{commentPrefixes:["#",";"],allowSection:!0,delimiters:["="]})}function J4(e){return al(e,a4,"#")}function X4(e){const t=e.trimStart();if(!t)return[];if(t.startsWith("#"))return[{text:e,kind:"comment"}];if(t.startsWith("!")){const n=e.length-t.length,r=e.slice(0,n),i=t.slice(1);return[{text:r,kind:"plain"},{text:"!",kind:"operator"},{text:i,kind:"string"}]}return[{text:e,kind:"string"}]}function Q4(e){const t=[];let n=0;for(;n<e.length;){const r=e.slice(n);if(r.startsWith("#")){t.push({text:r,kind:"comment"});break}const i=/^(?:\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:[.,]\d{3,6})?(?:Z|[+-]\d{2}:\d{2})?)/.exec(r);if(i){t.push({text:i[0],kind:"tag"}),n+=i[0].length;continue}const o=/^(?:\[(TRACE|DEBUG|INFO|WARN|WARNING|ERROR|FATAL)\])/.exec(r);if(o){t.push({text:r.slice(0,o[0].length),kind:"keyword"}),n+=o[0].length;continue}const l=/^[A-Za-z_][\w-]*/.exec(r);if(l){const u=l[0];o4.has(u.toLowerCase())?t.push({text:u,kind:"keyword"}):t.push({text:u,kind:"plain"}),n+=u.length;continue}const c=/^(?:\d+(?:\.\d+)?)/.exec(r);if(c){t.push({text:c[0],kind:"number"}),n+=c[0].length;continue}t.push({text:r[0]??"",kind:"plain"}),n+=1}return t}function Sp(e,t){const n=e.trimStart();if(t.commentPrefixes.some(u=>n.startsWith(u)))return[{text:e,kind:"comment"}];if(t.allowSection){const u=/^(\[[^\]]+\])/.exec(e);if(u)return[{text:u[0],kind:"tag"}]}const r=/^([A-Za-z0-9_.\-*?]+)(\s*(?:=|:))/.exec(e);if(!r)return[{text:e,kind:"plain"}];const i=(r[2]??"").trim();if(!t.delimiters.includes(i))return[{text:e,kind:"plain"}];const o=[{text:r[1]??"",kind:"attr"},{text:r[2]??"",kind:"operator"}],l=e.slice(r[0].length),c=Z4(l);return c.length&&o.push(...c),o}function Z4(e){if(!e)return[];const t=[];let n=0;for(;n<e.length;){const r=e.slice(n),i=dd(r,{trueValues:["true","yes","on"],falseValues:["false","no","off"],nullValues:["null"]});if(i){t.push(...i.tokens),n+=i.length;continue}if(r.startsWith("#")||r.startsWith(";")){t.push({text:r,kind:"comment"});break}t.push({text:r[0]??"",kind:"plain"}),n+=1}return t}function dd(e,t){const n=/^(?:'[^']*'|"[^"]*")/.exec(e);if(n)return{tokens:[{text:n[0],kind:"string"}],length:n[0].length};const r=/^(?:-?\d+(?:\.\d+)?)/.exec(e);if(r)return{tokens:[{text:r[0],kind:"number"}],length:r[0].length};const i=/^[A-Za-z0-9_.:+/-]+/.exec(e);if(!i)return null;const o=i[0],l=o.toLowerCase();return t.trueValues.includes(l)?{tokens:[{text:o,kind:"boolean"}],length:o.length}:t.falseValues.includes(l)?{tokens:[{text:o,kind:"boolean"}],length:o.length}:t.nullValues.includes(l)?{tokens:[{text:o,kind:"null"}],length:o.length}:{tokens:[{text:o,kind:"plain"}],length:o.length}}function Cp(e){var r,i;if(!e)return"plain";const t=((r=e.split(/[\\/]/).pop())==null?void 0:r.toLowerCase())??"";if(t===".env"||t.startsWith(".env."))return"env";if(t===".editorconfig")return"editorconfig";if(t==="dockerfile"||t.endsWith(".dockerfile"))return"dockerfile";if(t===".gitignore")return"gitignore";switch(((i=e.split(".").pop())==null?void 0:i.toLowerCase())??""){case"md":case"markdown":return"markdown";case"ts":case"tsx":return"typescript";case"js":case"jsx":case"mjs":case"cjs":return"javascript";case"json":return"json";case"log":return"log";case"properties":return"properties";case"toml":return"toml";case"ini":return"ini";case"conf":return"conf";case"dockerfile":return"dockerfile";case"css":case"scss":case"less":return"css";case"html":case"htm":return"html";case"xml":case"svg":return"xml";case"py":return"python";case"sh":case"bash":case"zsh":return"shell";case"sql":return"sql";case"yml":case"yaml":return"yaml";case"rs":return"rust";case"go":return"go";case"java":return"java";case"c":case"h":case"cpp":case"cc":case"hpp":return"cpp";default:return"plain"}}function jp(e){const t=e.toLowerCase();switch(t){case"ts":case"tsx":case"typescript":return"typescript";case"js":case"jsx":case"javascript":return"javascript";case"bash":case"shell":case"sh":case"zsh":return"shell";case"md":case"markdown":return"markdown";case"properties":return"properties";case"toml":return"toml";case"ini":return"ini";case"env":return"env";case"conf":return"conf";case"editorconfig":return"editorconfig";case"dockerfile":return"dockerfile";case"gitignore":return"gitignore";case"log":return"log";default:return t}}function pj(e){switch(jp(e)){case"typescript":return"TypeScript";case"javascript":return"JavaScript";case"markdown":return"Markdown";case"json":return"JSON";case"properties":return"Properties";case"toml":return"TOML";case"ini":return"INI";case"env":return"ENV";case"conf":return"CONF";case"editorconfig":return"EditorConfig";case"dockerfile":return"Dockerfile";case"gitignore":return"GitIgnore";case"log":return"Log";case"css":return"CSS";case"html":return"HTML";case"xml":return"XML";case"python":return"Python";case"shell":return"Shell";case"sql":return"SQL";case"yaml":return"YAML";case"rust":return"Rust";case"go":return"Go";case"java":return"Java";case"cpp":return"C/C++";default:return a("conversation.fileViewerPlainText")}}function ez(e){return Cp(e)==="markdown"}function tz(e){return Cp(e)==="html"}function nz(){return s.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[s.jsx("path",{d:"M5 2.5h7.5v9H5z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),s.jsx("path",{d:"M3.5 5H2.4V13.5H10V12.4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Ic(e,t){return e instanceof rr?e.message:t}async function sz(e){const t=Date.now();for(;Date.now()-t<6e4;){const n=await x5(e);if(n.status==="queued"||n.status==="running"){await rz(800);continue}return n}throw new rr(408,{detail:a("conversation.fileViewerExportTaskTimeout"),error_code:"PRESENTATION_EXPORT_TIMEOUT"})}function rz(e){return new Promise(t=>{window.setTimeout(t,e)})}function iz(e){const t=[],n=e.replace(/\r\n/g,`
665
+ `).split(`
666
+ `);let r=0,i=0;for(const o of n){if(o.startsWith("diff --git")||o.startsWith("index ")||o.startsWith("--- ")||o.startsWith("+++ ")){t.push({kind:"meta",text:o,oldLineNo:null,newLineNo:null});continue}const l=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(o);if(l){r=parseInt(l[1],10),i=parseInt(l[2],10),t.push({kind:"hunk",text:o,oldLineNo:null,newLineNo:null});continue}if(o.startsWith(" ")||o===""){t.push({kind:"context",text:o.slice(1),oldLineNo:r,newLineNo:i}),r++,i++;continue}if(o.startsWith("+")){t.push({kind:"add",text:o.slice(1),oldLineNo:null,newLineNo:i}),i++;continue}if(o.startsWith("-")){t.push({kind:"remove",text:o.slice(1),oldLineNo:r,newLineNo:null}),r++;continue}t.push({kind:"meta",text:o,oldLineNo:null,newLineNo:null})}return t}function az(e){if(!(e!=null&&e.trim()))return[];const t=iz(e),n=[];let r=0,i=[];function o(){if(i.length===0){r=0;return}const l=r>0?"modify":"add";lz(n,i,l),r=0,i=[]}for(const l of t){if(l.kind==="remove"){r+=1;continue}if(l.kind==="add"){l.newLineNo!==null&&i.push(l.newLineNo);continue}o()}return o(),n}function oz(e,t){const n=e?e.split(/\r?\n/).length:1,r=t.reduce((i,o)=>Math.max(i,o.line+o.span-1),0);return Math.max(n,r,1)}function lz(e,t,n){const r=t.filter(l=>l>0);if(r.length===0)return;let i=r[0]??1,o=i;for(let l=1;l<r.length;l+=1){const c=r[l]??o;if(c===o+1){o=c;continue}e.push({line:i,span:o-i+1,kind:n}),i=c,o=c}e.push({line:i,span:o-i+1,kind:n})}function gj({markers:e,totalLines:t,scrollContainerRef:n,hideWithoutMarkers:r=!1}){const i=d.useRef(null),o=!r||e.length>0;if(d.useEffect(()=>{const c=n.current,u=i.current;if(!c||!u||!o)return;const f=c,h=u;let m=null;function g(){m=null;const{clientHeight:b,scrollHeight:y,scrollTop:x}=f;if(y<=0||b<=0||y<=b){h.style.display="none";return}const k=b/y,C=Math.min(100,Math.max(12,k*100)),j=y-b,H=Math.max(0,100-C),_=j<=0?0:x/j*H;h.style.display="block",h.style.top=`${_}%`,h.style.height=`${C}%`}function p(){m===null&&(m=window.requestAnimationFrame(g))}return g(),f.addEventListener("scroll",p,{passive:!0}),window.addEventListener("resize",p),()=>{m!==null&&window.cancelAnimationFrame(m),f.removeEventListener("scroll",p),window.removeEventListener("resize",p)}},[n,o]),r&&e.length===0)return null;const l=Math.max(t,1);return s.jsxs("div",{className:"file-overview-ruler","data-testid":"file-overview-ruler","aria-hidden":"true",children:[e.map(c=>{const u=(c.line-1)/l*100,f=Math.max(2,c.span/l*100);return s.jsx("div",{className:`file-overview-marker is-${c.kind}`,"data-kind":c.kind,style:{top:`${u}%`,height:`${f}%`}},`${c.kind}-${c.line}-${c.span}`)}),o?s.jsx("div",{ref:i,className:"file-overview-viewport"}):null]})}function cz(e,t){if(typeof document>"u")throw new Error(a("conversation.filePanelDownloadFailed"));const n=window.URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=e,document.body.append(r),r.click(),r.remove(),window.URL.revokeObjectURL(n)}function Np({requests:e,replyingRequestId:t,onReply:n}){const[r,i]=d.useState({}),o=d.useMemo(()=>e.filter(l=>l.status==="pending"),[e]);return o.length===0?null:s.jsxs("section",{className:"permission-request-list",children:[s.jsxs("div",{className:"permission-request-list-header",children:[s.jsxs("div",{children:[s.jsx("strong",{children:a("conversation.permissionRequestSectionTitle")}),s.jsx("p",{children:a("conversation.permissionRequestSectionDescription")})]}),s.jsx("span",{className:"permission-request-count",children:o.length})]}),s.jsx("div",{className:"permission-request-stack",children:o.map(l=>{var g,p;const c=r[l.id]??{},u=l.paths.filter(Boolean),f=l.kind==="command"&&!!((g=l.command)!=null&&g.trim()),h=l.questions.length===0&&u.length===0&&!f&&!!((p=l.summary)!=null&&p.trim()),m=l.kind==="user_input"&&l.questions.some(b=>{var y;return(((y=c[b.id])==null?void 0:y.filter(Boolean).length)??0)===0});return s.jsxs("article",{className:"permission-request-card",children:[s.jsxs("header",{className:"permission-request-card-header",children:[s.jsxs("div",{className:"permission-request-provider",children:[s.jsx("span",{className:"permission-request-provider-icon","aria-hidden":"true",children:s.jsx("img",{src:Uw(l.provider),alt:"",loading:"lazy"})}),s.jsxs("div",{className:"permission-request-provider-copy",children:[s.jsx("strong",{children:l.title}),s.jsx("span",{children:Ui(l.provider,"full")})]})]}),s.jsx("span",{className:"permission-request-kind",children:dz(l.kind)})]}),s.jsxs("div",{className:"permission-request-card-body",children:[u.length>0?s.jsx("div",{className:"permission-request-block",children:s.jsx("ul",{className:"permission-request-target-list",children:u.map(b=>s.jsxs("li",{className:"permission-request-target-item",children:[s.jsx("strong",{children:fz(b)}),s.jsx("span",{children:b})]},`${l.id}:${b}`))})}):null,f?s.jsxs("div",{className:"permission-request-block",children:[s.jsx("div",{className:"permission-request-block-label",children:a("conversation.permissionRequestCommandLabel")}),s.jsx("pre",{children:l.command})]}):null,h?s.jsx("p",{className:"permission-request-summary",children:l.summary}):null,l.questions.length>0?s.jsxs("div",{className:"permission-request-block",children:[s.jsx("div",{className:"permission-request-block-label",children:a("conversation.permissionRequestQuestionsLabel")}),s.jsx("div",{className:"permission-request-question-list",children:l.questions.map(b=>s.jsxs("div",{className:"permission-request-question",children:[s.jsx("div",{className:"permission-request-question-header",children:b.header}),s.jsx("p",{children:b.question}),s.jsx("div",{className:"permission-request-question-options",children:b.options.map(y=>{var k;const x=((k=c[b.id])==null?void 0:k.includes(y.label))??!1;return s.jsxs("label",{className:"permission-request-question-option",children:[s.jsx("input",{type:"radio",name:`${l.id}:${b.id}`,checked:x,onChange:()=>{i(C=>({...C,[l.id]:{...C[l.id]??{},[b.id]:[y.label]}}))}}),s.jsxs("span",{children:[s.jsx("strong",{children:y.label}),y.description?s.jsx("small",{children:y.description}):null]})]},`${b.id}:${y.label}`)})})]},b.id))})]}):null]}),s.jsx("footer",{className:"permission-request-card-footer",children:l.actions.map(b=>s.jsx("button",{type:"button",className:uz(b.tone),disabled:t===l.id||b.value==="submit"&&m,onClick:()=>void n(l.id,{action:b.value,answers:Object.keys(c).length>0?c:void 0}),children:t===l.id?a("conversation.permissionRequestSubmitting"):b.label},`${l.id}:${b.value}`))})]},l.id)})})]})}function uz(e){return e==="danger"?"workbench-danger-button permission-request-action":e==="primary"?"primary-button permission-request-action":"secondary-button permission-request-action"}function dz(e){return e==="command"?a("conversation.permissionRequestKindCommand"):e==="file_change"?a("conversation.permissionRequestKindFileChange"):e==="permissions"?a("conversation.permissionRequestKindPermissions"):e==="user_input"?a("conversation.permissionRequestKindUserInput"):a("conversation.permissionRequestKindToolCall")}function fz(e){return e.split(/[/\\]+/).filter(Boolean).at(-1)??e}function hz(e){const t=e.trim().length;return t<=16?"xl":t<=26?"lg":t<=38?"md":"sm"}function Tp({session:e,actions:t,workspaceContext:n=null}){const r=Hn(),i=Lm(r);if(!e)return s.jsxs("header",{className:"conversation-header conversation-header-skeleton","aria-hidden":"true","data-window-drag-handle":"conversation-header","data-tauri-drag-region":i,children:[s.jsxs("div",{className:"conversation-header-main","data-tauri-drag-region":i,children:[s.jsx("span",{className:"skeleton-line short"}),s.jsx("span",{className:"skeleton-line long"})]}),t?s.jsx("div",{className:"conversation-header-actions",children:t}):null]});const o=rd(e.title,a("conversation.titleFallback")),l=hz(o.displayTitle);return s.jsxs("header",{className:"conversation-header","data-workspace-tone":(n==null?void 0:n.tone)??"root",style:Gr(n),"data-window-drag-handle":"conversation-header","data-tauri-drag-region":i,children:[s.jsx("div",{className:"conversation-header-main","data-tauri-drag-region":i,children:s.jsx("h1",{className:`conversation-title is-${l}`,title:o.fullTitle,"data-tauri-drag-region":i,children:o.displayTitle})}),t?s.jsx("div",{className:"conversation-header-actions",children:t}):null]})}const mz=new Set([".ds_store","thumbs.db","ehthumbs.db","desktop.ini",".spotlight-v100",".trashes",".fseventsd","__macosx","$recycle.bin","system volume information",".apdisk",".appledouble",".temporaryitems"]),pz=["._"];function Pu(e){return e.split(/[/\\]/).filter(Boolean).pop()??e}function gz(e){const t=e.trim().toLowerCase();return t?mz.has(t)||pz.some(n=>t.startsWith(n)):!1}function bz(e,t,n){return n?[...e]:e.filter(r=>!gz(t(r)))}function yz(e,t){return bz(e,n=>n.name,t)}function SK(e,t){return t?e:Object.entries(e).reduce((n,[r,i])=>(n[r]=yz(i,!1),n),{})}function xz(e){const t=e.toLowerCase();if(t===".env"||t.startsWith(".env."))return"ENV";if(t.endsWith(".d.ts"))return"DTS";switch(t.includes(".")?t.slice(t.lastIndexOf(".")+1):""){case"ts":return"TS";case"tsx":return"TSX";case"js":return"JS";case"jsx":return"JSX";case"json":return"{}";case"md":return"MD";case"css":return"CSS";case"scss":return"SASS";case"html":return"HTML";case"yml":case"yaml":return"YAML";case"png":case"jpg":case"jpeg":case"gif":case"svg":case"webp":return"IMG";case"txt":return"TXT";default:return"FILE"}}function kz(e){const t=e.toLowerCase();return t===".env"||t.startsWith(".env.")?"env":t.endsWith(".md")?"md":t.endsWith(".css")||t.endsWith(".scss")?"style":t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".svg")||t.endsWith(".webp")?"image":t.endsWith(".ts")||t.endsWith(".tsx")||t.endsWith(".js")||t.endsWith(".jsx")?"code":t.endsWith(".json")||t.endsWith(".yml")||t.endsWith(".yaml")?"data":"default"}const Vh=134,ex=10,Kh=104,tx=12,nx=2,wz=80;function vz(e){const t=Math.max(e,Vh);return Math.max(1,Math.floor((t+ex)/(Vh+ex)))}function Sz(e,t,n){return e>=wz&&t>=Vh&&n>=Kh}function Cz(e,t,n,r){const i=vz(t),o=Kh+tx,l=Math.ceil(e/i),c=Math.max(1,Math.ceil(Math.max(n,o)/o)),u=Math.max(0,Math.floor(r/o)-nx),f=Math.min(l,u+c+nx*2);return{columns:i,startIndex:u*i,endIndex:Math.min(e,f*i),offsetTop:u*o,totalHeight:l>0?l*Kh+Math.max(0,l-1)*tx:0}}const jz=[[["md","mdx"],{kind:"markdown",tone:"emerald",badge:"MD"}],[["txt","text","log","rtf"],{kind:"text",tone:"slate",badge:"TXT"}],[["pdf"],{kind:"pdf",tone:"red",badge:"PDF"}],[["doc","docx","odt","wps"],{kind:"word",tone:"blue",badge:"DOC"}],[["xls","xlsx","ods","et","csv","tsv"],{kind:"spreadsheet",tone:"green",badge:"XLS"}],[["numbers"],{kind:"spreadsheet",tone:"green",badge:"NUM"}],[["ppt","pptx","odp","key"],{kind:"presentation",tone:"orange",badge:"PPT"}],[["jpg","jpeg","png","gif","webp","svg","bmp","ico","heic","heif","avif","tif","tiff"],{kind:"image",tone:"purple",badge:"IMG"}],[["zip","rar","7z","tar","gz","tgz","bz2","xz","iso"],{kind:"archive",tone:"amber",badge:"ZIP"}],[["html","htm"],{kind:"web",tone:"sky",badge:"HTML"}],[["css","scss","less"],{kind:"code",tone:"sky",badge:"CSS"}],[["js","jsx","ts","tsx","py","java","c","cpp","h","hpp","go","rs","php","rb","sh","bash","zsh","ps1","vue"],{kind:"code",tone:"indigo",badge:"CODE"}],[["json"],{kind:"json",tone:"cyan",badge:"JSON"}],[["xml"],{kind:"xml",tone:"cyan",badge:"XML"}],[["yaml","yml","toml","ini","conf"],{kind:"yaml",tone:"cyan",badge:"YAML"}],[["sql"],{kind:"database",tone:"cyan",badge:"SQL"}],[["db","sqlite","sqlite3"],{kind:"database",tone:"cyan",badge:"DB"}],[["mp3","wav","flac","m4a","aac","ogg"],{kind:"audio",tone:"pink",badge:"AUDIO"}],[["mp4","mov","m4v","mkv","avi","webm"],{kind:"video",tone:"violet",badge:"VIDEO"}],[["fig","sketch","xd","psd","ai"],{kind:"design",tone:"rose",badge:"DES"}],[["ttf","otf","woff","woff2"],{kind:"font",tone:"stone",badge:"FONT"}],[["epub","mobi","azw3"],{kind:"ebook",tone:"teal",badge:"BOOK"}]],bj=new Map;for(const[e,t]of jz)for(const n of e)bj.set(n,t);function yj(e){const t=e.trim(),n=t.lastIndexOf(".");return n<0||n===t.length-1?"document":t.slice(n+1).toLowerCase()}function Ip(e){const t=yj(e);if(t==="document")return{extension:t,kind:"file",badge:"FILE",tone:"neutral"};const n=bj.get(t);return n?{extension:t,kind:n.kind,badge:n.badge,tone:n.tone}:{extension:t,kind:"file",badge:t.slice(0,4).toUpperCase(),tone:"neutral"}}const Aa=120,Nz=220,vl=5,Yo="__root__",xj="codingns.affairs.tag-tree.state.",Lo=40,sx=2,Tz=3e3,Iz=12e3,Az=3e3,Rz=12e3,Pz=3e4,rx=1200,ix=8e3,Mz=1200,Ez=8e3,Lz=600,Dz=8e3,Ap=300*1e3,Oz=1800*1e3,Fz=600,fd=[".md",".mdx",".txt",".rtf",".html",".htm",".xml",".json",".yaml",".yml",".tsv",".pdf",".doc",".docx",".odt",".wps",".ppt",".pptx",".odp",".key",".xls",".xlsx",".ods",".et",".numbers",".csv"],Oa={name:240,size:88,updatedAt:156,type:120,createdAt:156},Fa={name:320,size:96,updatedAt:176,type:132,createdAt:176},kj="__affairs_current_library__",br=12,ax=44,Lf=12,Gh=.6,Yh=.6,_z={small:{w:4,h:4,minW:4,minH:3},medium:{w:6,h:5,minW:4,minH:3},large:{w:12,h:7,minW:6,minH:4}},eu="allow-forms allow-modals allow-scripts",Bz=`${eu} allow-same-origin`,wj=d.createContext(null);function vj(e){return e.type!=="html"?null:e.variant??"embed"}function Wz(e){const t=vj(e);return t==="stat"?"small":t==="app"||t==="embed"?"large":"medium"}function $z(e,t,n){let r=0,i=0,o=0;return e.map(l=>{const c=_z[Wz(l)],u=t.get(l.id),f=Math.max(1,Math.min(br,n?c.w:(u==null?void 0:u.w)??c.w)),h=Math.max(3,n?c.h:(u==null?void 0:u.h)??c.h),m=Math.max(1,Math.min(f,n?c.minW??f:(u==null?void 0:u.minW)??c.minW??f)),g=Math.max(1,Math.min(h,n?c.minH??h:(u==null?void 0:u.minH)??c.minH??h));r>0&&r+f>br&&(i+=o,r=0,o=0);const p={widgetId:l.id,x:r,y:i,w:f,h,minW:m,minH:g};return r+=f,o=Math.max(o,h),r>=br&&(i+=o,r=0,o=0),p})}function Sj(e){const t=Math.max(1,Math.min(br,e.w)),n=Math.max(1,e.h),r=Math.max(1,Math.min(t,e.minW??t)),i=Math.max(1,Math.min(n,e.minH??n));return{...e,x:Math.max(0,Math.min(br-t,e.x)),y:Math.max(0,e.y),w:t,h:n,minW:r,minH:i}}function ox(e,t){return!(e.x+e.w<=t.x||t.x+t.w<=e.x||e.y+e.h<=t.y||t.y+t.h<=e.y)}function qa(e,t,n){let r=0,i=Number.POSITIVE_INFINITY;for(const o of t){const l=o-e,c=Math.abs(l);c>n||c>=i||(r=l,i=c)}return Number.isFinite(i)?r:0}function zz(e,t){const n=[0,br],r=[0];return e.forEach(i=>{i.widgetId!==t&&(n.push(i.x,i.x+i.w),r.push(i.y,i.y+i.h))}),{x:n,y:r}}function Hz(e,t){const n=qa(e.x,t.x,Gh),r=qa(e.x+e.w,t.x,Gh),i=qa(e.y,t.y,Yh),o=qa(e.y+e.h,t.y,Yh);return{x:e.x+(Math.abs(n)<=Math.abs(r)?n:r),y:e.y+(Math.abs(i)<=Math.abs(o)?i:o)}}function Uz(e,t,n){const r=n==="x"||n==="xy"?qa(e.x+e.w,t.x,Gh):0,i=n==="y"||n==="xy"?qa(e.y+e.h,t.y,Yh):0;return{w:e.w+r,h:e.h+i}}function qz(e,t,n){const r=new Set(e.map(u=>u.id)),i=new Map(t.filter(u=>r.has(u.widgetId)).map(u=>[u.widgetId,Sj(u)])),o=[...n?[n]:[],...e.map(u=>u.id).filter(u=>u!==n)],l=[];for(const u of o){const f=i.get(u);if(!f)continue;const h={...f};for(;l.some(m=>ox(m,h));){const m=l.filter(g=>ox(g,h)).reduce((g,p)=>Math.max(g,p.y+p.h),h.y+1);h.y=m}l.push(h)}const c=new Map(l.map(u=>[u.widgetId,u]));return e.map(u=>c.get(u.id)).filter(u=>!!u)}function Ac(e,t=[],n=!1,r){const i=new Map(t.map(c=>[c.widgetId,c])),o=$z(e,i,n),l=e.map((c,u)=>{const f=o[u];if(n)return f;const h=i.get(c.id);return h?Sj({...f,...h,widgetId:c.id,minW:h.minW??f.minW,minH:h.minH??f.minH}):f});return qz(e,l,r)}function Ra(e,t,n){const r=new Date().toISOString();let i=!1;const o=e.tabs.map(l=>l.id!==t?l:(i=!0,n(l,r)));return i?{...e,tabs:o,updatedAt:r}:e}function Jh(e){var t;if(typeof window>"u"||!((t=window.location)!=null&&t.origin))return`${e}${e.includes("?")?"&":"?"}_preview=0`;try{const n=new URL(e,window.location.origin);return n.searchParams.set("_preview","0"),n.toString()}catch{return`${e}${e.includes("?")?"&":"?"}_preview=0`}}function Vz(e){var t;if(typeof window>"u"||!((t=window.location)!=null&&t.origin))return eu;try{if(new URL(e,window.location.origin).origin!==window.location.origin)return Bz}catch{return eu}return eu}function Sl(e,t){var n,r;return e instanceof rr?((n=e.message)==null?void 0:n.trim())||t:e instanceof Error&&((r=e.message)==null?void 0:r.trim())||t}function Ki(e,t){const n=(t==null?void 0:t.trim())??"";return n||Pu(e.trim())||e.trim()}function lx(e,t,n){return{...e,[t]:n}}function cx(e,t){return t||($k(e)??wT(e))}function Kz(e){const t=e.trim();if(!t)return"应用";const n=Array.from(t).filter(i=>/[㐀-鿿]/.test(i));if(n.length>0)return n.slice(0,2).join("");const r=t.split(/[\s\-_/]+/).map(i=>i.trim()).filter(Boolean).map(i=>{var o;return((o=i[0])==null?void 0:o.toUpperCase())??""}).filter(Boolean);return r.length>0?r.slice(0,2).join(""):Array.from(t).slice(0,2).join("").toUpperCase()}function Gz(e){const t=e.trim()||"快捷应用";let n=0;for(const o of t)n=(n<<5)-n+o.charCodeAt(0),n|=0;const r=Math.abs(n)%360,i=(r+28)%360;return{background:`linear-gradient(135deg, hsl(${r} 82% 91%), hsl(${i} 78% 85%))`,color:`hsl(${r} 46% 20%)`}}async function Yz(e,t){const n=t.trim();if(!ou(n))throw new Error(a("shell.affairsWorkbenchHtmlSourceInvalid"));const r=await vm(e,n);if(!r.supported||r.kind!=="html"||!r.previewUrl)throw new Error(a("shell.affairsWorkbenchHtmlSourceUnsupported"));return{path:n,title:Ki(n)}}async function Jz(e,t){const n=t.trim();if(!n)throw new Error(a("shell.affairsShortcutRailSourceInvalid"));if(!(await vm(e,n)).supported)throw new Error(a("shell.affairsShortcutRailSourceUnsupported"));return{path:n,title:Ki(n)}}async function Xz(e,t){const n=t.trim();if(!ou(n))throw new Error(a("shell.affairsWorkbenchHtmlSourceInvalid"));const r=await $u(e,n);if(!r.supported||r.kind!=="html"||!r.previewUrl)throw new Error(a("shell.affairsWorkbenchHtmlSourceUnsupported"));return{path:n,title:Ki(n)}}async function Qz(e,t){const n=t.trim();if(!n)throw new Error(a("shell.affairsShortcutRailSourceInvalid"));if(!(await $u(e,n)).supported)throw new Error(a("shell.affairsShortcutRailSourceUnsupported"));return{path:n,title:Ki(n)}}async function Zz(e,t){if(!e)throw new Error(a("shell.affairsWorkbenchHtmlSourceInvalid"));return e.kind==="affairs_library"?Xz(e.workspaceId,t):Yz(e.workspaceId,t)}async function eH(e,t){if(!e)throw new Error(a("shell.affairsShortcutRailSourceInvalid"));return e.kind==="affairs_library"?Qz(e.workspaceId,t):Jz(e.workspaceId,t)}function Cj(e,t,n){var l,c;const r=new Set,i=[],o=(u,f)=>{const h=u.trim();!h||r.has(h)||(r.add(h),i.push({value:h,workspaceId:h,label:f,kind:"workspace"}))};return n&&i.push(n),e.forEach(u=>{var h;const f=u.workspace.id.trim();!f||r.has(f)||o(f,((h=u.workspace.name)==null?void 0:h.trim())||u.workspace.path||f)}),r.has(t)||i.unshift({value:t,workspaceId:t,label:((c=(l=e.find(u=>u.workspace.id===t))==null?void 0:l.workspace.name)==null?void 0:c.trim())||t,kind:"workspace"}),i}function jj(e,t){var i,o;const n=((i=e==null?void 0:e.rootDir)==null?void 0:i.trim())??"",r=((o=e==null?void 0:e.workspaceId)==null?void 0:o.trim())||t.trim();return!n||!r?null:{value:kj,kind:"affairs_library",workspaceId:r,rootDir:n,label:a("shell.affairsWorkbenchHtmlSourceWorkspaceCurrentLibraryOption")}}function Nj(e){var r,i,o;const t=((i=(r=e.currentLibraryWorkspace)==null?void 0:r.value)==null?void 0:i.trim())??"";if(t&&e.options.some(l=>l.value===t))return t;const n=e.currentWorkspaceId.trim();return n&&e.options.some(l=>l.value===n)?n:((o=e.options[0])==null?void 0:o.value)??n}function tH(e,t){var n;return((n=e==null?void 0:e.workspaceId)==null?void 0:n.trim())||t}function Tj(e,t){const n=t.trim();return e.find(r=>r.value===n)??null}const nH=["codex","claude-code"],sH=["codex","claude-code"],rH={pathname:""},Ij=d.createContext(null);function iH({workspaceId:e,workspaceName:t,navigationGroups:n,state:r,onStateChange:i,onRefreshNavigation:o,children:l}){var fr,si,wr,zr;const c=d.useContext(CT),u=d.useContext(jT),f=d.useCallback(v=>{var $;($=c==null?void 0:c.navigator)==null||$.push(v)},[c]),h=(u==null?void 0:u.location)??rH,m=d.useMemo(()=>n.find(v=>v.workspace.id===e)??null,[n,e]),g=(m==null?void 0:m.sessions)??[],p=d.useMemo(()=>new Set(g.map(v=>v.sessionId)),[g]),b=d.useMemo(()=>g.map(v=>v.sessionId.trim()).filter(v=>v.length>0).sort((v,$)=>v.localeCompare($)).join("|"),[g]),y=d.useMemo(()=>Object.fromEntries(g.map(v=>{var $;return[v.sessionId,(($=v.title)==null?void 0:$.trim())||v.sessionId]})),[g]),x=d.useRef(null),[k,C]=d.useState(!1),[j,H]=d.useState("all"),[_,T]=d.useState(null),[P,z]=d.useState(null),[L,R]=d.useState(null),[K,E]=d.useState(null),[D,te]=d.useState(""),[V,ee]=d.useState(null),[U,he]=d.useState(null),[X,I]=d.useState(null),[xe,le]=d.useState(null),[M,de]=d.useState(null),[Ne,ye]=d.useState({}),Be=d.useMemo(()=>E6(e)??[],[e]),We=d.useMemo(()=>Array.isArray(m==null?void 0:m.affairsAssistantSessions)?m.affairsAssistantSessions:[],[m==null?void 0:m.affairsAssistantSessions]),Ce=(m==null?void 0:m.affairsAssistantProjectId)??null,ke=d.useMemo(()=>We,[We]),[we,se]=d.useState(Be),[ce,Y]=d.useState(!1),[Te,pe]=d.useState(ke),fe=!1,[W,Me]=d.useState(null),je=d.useRef(null),Q=d.useRef(null),ge=d.useMemo(()=>new Set(we.map(v=>v.sessionId)),[we]),Oe=d.useMemo(()=>Ex(e),[e]),$e=d.useMemo(()=>Lx(e),[e]),Ve=d.useMemo(()=>Dx(e,r),[e,r]),G=Nq(r.primarySection),[ve,_e]=d.useState(Oe===null),[nt,et]=d.useState(!1),[ot,jt]=d.useState(!1),[Ft,bt]=d.useState(null),[_t,xt]=d.useState(null),[rt,It]=d.useState(null),[$t,pt]=d.useState(null),[Ie,kt]=d.useState(Oe),[St,vt]=d.useState($e),[Ct,J]=d.useState(Ve),[Ue,ze]=d.useState(!1),[st,q]=d.useState(!1),[re,ue]=d.useState(null),[Re,Se]=d.useState(!1),[Ke,De]=d.useState([]),[He,lt]=d.useState(null),[wt,it]=d.useState(null),[Ze,Ht]=d.useState(null),[gt,Nt]=d.useState(null),[dt,ft]=d.useState(null),[en,cn]=d.useState([]),[qt,Cn]=d.useState(null),[Bt,is]=d.useState(null),[Ws,fn]=d.useState([]),[mt,O]=d.useState([]),[Ae,Xe]=d.useState([]),[Qt,Un]=d.useState([]),as=Kp(v=>v.affairsDashboardStatesByWorkspace??{}),tn=Kp(v=>v.source),sn=as[e]??null,[At,Gt]=d.useState(()=>cx(e,sn)),Zn=d.useRef(null),es=d.useRef(sn?JSON.stringify(sn):null),os=d.useMemo(()=>At.tabs.find(v=>v.id===At.activeTabId)??At.tabs[0]??null,[At]),ut=(Ie==null?void 0:Ie.binding)??null,Ds=d.useMemo(()=>kq(ut),[ut]),cr=d.useMemo(()=>vq(Ds,n),[Ds,n]),jn=d.useMemo(()=>cr??(m==null?void 0:m.affairsAssistantProjectWorkspaceId)??null,[cr,m==null?void 0:m.affairsAssistantProjectWorkspaceId]),an=d.useMemo(()=>new sW(jn),[jn]),hs=Zt(an,v=>v.loading),ur=Zt(an,v=>v.initialized),ts=Zt(an,v=>v.affairsSetupCompleted??v.initialized),Dn=Zt(an,v=>v.bootstrapErrorCode),Kn=Zt(an,v=>v.error),Rn=Zt(an,v=>v.profile),Nn=Zt(an,v=>v.activeProvider),ks=Zt(an,v=>v.controlSession),{showToast:xn}=Vn(),$s=Dn==="NETWORK_ERROR"||Dn==="INVALID_RESPONSE",Vt=(Ie==null?void 0:Ie.status)??null,nn=(Ct==null?void 0:Ct.directoryStatus)??null,ns=d.useMemo(()=>({loading:hs,initialized:ts,butlerInitialized:ur,unavailable:!hs&&$s,errorMessage:Kn,profile:Rn?{displayName:Rn.displayName,providerId:Rn.providerId,personaTone:Rn.persona.tone}:null}),[ts,$s,Kn,hs,ur,Rn]),ss=h.pathname===Xo(e),Ts=d.useCallback(()=>{ss||f(Xo(e))},[ss,f,e]);d.useRef(null);const Xs=d.useRef(Oe),ls=d.useRef(null),zs=d.useRef(!1),ms=Fo(G,r.auxiliaryTab);d.useEffect(()=>{typeof an.initialize=="function"&&an.initialize()},[an]),d.useEffect(()=>()=>{an.dispose()},[an]),d.useEffect(()=>{Me(null)},[e]),d.useEffect(()=>{Q.current=null,se(Be),pe(ke),ye({})},[ke,Be,e]),d.useEffect(()=>{pe(v=>dx(v,We))},[We]),d.useEffect(()=>{Xs.current=Ie},[Ie]),d.useEffect(()=>{hs||$s||ts||G==="conversation"||(Ts(),i({...r,primarySection:"conversation",selectedNodeId:null,selectedObjectId:null,selectedDocumentId:null,auxiliaryTab:Fo("conversation",r.auxiliaryTab)}))},[G,ts,$s,hs,Ts,i,r]),d.useEffect(()=>{if(Q.current!==e){Q.current=e;return}L6(e,we)},[we,e]),d.useEffect(()=>{T(yq(r.selectedNodeId)),z(xq(r.selectedNodeId))},[r.selectedNodeId]),d.useEffect(()=>{var v;(v=r.selectedNodeId)!=null&&v.startsWith("conversation:")&&(x.current=r.selectedNodeId)},[r.selectedNodeId]),d.useEffect(()=>{P&&R(v=>!v||v.session.sessionId===P.sessionId?v:null)},[P]);const ps=d.useCallback((v,$)=>{ye(w=>{const F=w[v]??null,Z=typeof $=="function"?$(F):$;if(!Z){if(!(v in w))return w;const{[v]:be,...Ee}=w;return Ee}return{...w,[v]:Z}})},[]),ws=d.useCallback(v=>{z($=>($==null?void 0:$.sessionId)===v.sessionId&&$.kind===v.kind?null:$),R($=>($==null?void 0:$.session.sessionId)===v.sessionId?null:$),ps(v.sessionId,null),x.current===li(v.kind,v.sessionId)&&(x.current=null),r.selectedNodeId===li(v.kind,v.sessionId)&&i({...r,primarySection:"conversation",selectedNodeId:null,selectedObjectId:null,selectedDocumentId:null})},[i,ps,r]);d.useEffect(()=>{if(P&&(L==null?void 0:L.session.sessionId)!==P.sessionId){if(P.kind==="lightweight"){if(we.some(v=>v.sessionId===P.sessionId))return}else if(Te.some(v=>v.sessionId===P.sessionId))return;ws(P)}},[Te,ws,L==null?void 0:L.session.sessionId,we,P]);const On=d.useCallback(async()=>{Y(!0);try{const v=await v0(e);se(v.items)}catch(v){xn({tone:"error",title:a("shell.affairsConversationLightweightLoadFailed"),description:dN(v,a("shell.affairsConversationLightweightLoadFailed"))})}finally{Y(!1)}},[xn,e]);d.useEffect(()=>{G==="conversation"&&On()},[G,On]);const vs=d.useCallback(async()=>{pe(v=>dx(v,We))},[We]),Ss=d.useCallback(v=>{cn($=>[v,...$.filter(F=>F.id!==v.id)].sort((F,Z)=>Z.createdAt-F.createdAt).slice(0,5))},[]),Wn=d.useCallback(v=>{var $;v&&Ss({id:`folder:${v.folderPath}`,targetType:"folder",targetKey:v.folderPath,targetLabel:v.folderPath==="."?a("shell.affairsLibraryDirectoryStatusRootPath"):Pu(v.folderPath)||v.folderPath,taskId:v.taskId,snapshot:v.snapshot,operation:v.operation,createdAt:(($=v.snapshot)==null?void 0:$.enqueuedAt)??Date.now()})},[Ss]),Gn=d.useCallback(v=>{var $;v&&Ss({id:`document:${v.documentId}`,targetType:"document",targetKey:v.documentId,targetLabel:v.documentTitle||v.documentId,taskId:v.taskId,snapshot:v.snapshot,operation:v.operation,createdAt:(($=v.snapshot)==null?void 0:$.enqueuedAt)??Date.now()})},[Ss]);d.useEffect(()=>{if(!gt)return;let v=!1,$=null;const w=async()=>{try{const F=await a0(e,gt.folderPath);if(v||(Nt(Z=>{if(!Z||Z.taskId!==gt.taskId||Z.folderPath!==gt.folderPath||$f(Z.snapshot,F))return Z;const be={...Z,snapshot:F};return Wn(be),be}),!F||Or(F.status)))return}catch{if(v)return}v||($=setTimeout(()=>{w()},rx))};return w(),()=>{v=!0,$&&clearTimeout($)}},[gt==null?void 0:gt.folderPath,gt==null?void 0:gt.taskId,Wn,e]),d.useEffect(()=>{if(!dt)return;let v=!1,$=null;const w=async()=>{try{const F=await s0(e,dt.documentId);if(v||(ft(Z=>{if(!Z||Z.taskId!==dt.taskId||Z.documentId!==dt.documentId||$f(Z.snapshot,F))return Z;const be={...Z,snapshot:F};return Gn(be),be}),!F||Or(F.status)))return}catch{if(v)return}v||($=setTimeout(()=>{w()},rx))};return w(),()=>{v=!0,$&&clearTimeout($)}},[dt==null?void 0:dt.documentId,dt==null?void 0:dt.taskId,Gn,e]),d.useEffect(()=>{if(!qt)return;let v=!1,$=null;const w=async()=>{try{const F=await Xp(e),Z=F.task;if(v||(is(be=>Nx(be,F)?be:F),Cn(be=>!be||be.taskId!==qt.taskId||$f(be.snapshot,Z)?be:{...be,snapshot:Z}),Z&&Or(Z.status)))return}catch{if(v)return}v||($=setTimeout(()=>{w()},Mz))};return w(),()=>{v=!0,$&&clearTimeout($)}},[qt==null?void 0:qt.taskId,e]),d.useEffect(()=>{if(!(gt!=null&&gt.snapshot)||!Or(gt.snapshot.status))return;const v=gt.taskId,$=setTimeout(()=>{Nt(w=>(w==null?void 0:w.taskId)===v?null:w)},ix);return()=>{clearTimeout($)}},[(fr=gt==null?void 0:gt.snapshot)==null?void 0:fr.status,gt==null?void 0:gt.taskId]),d.useEffect(()=>{if(!(dt!=null&&dt.snapshot)||!Or(dt.snapshot.status))return;const v=dt.taskId,$=setTimeout(()=>{ft(w=>(w==null?void 0:w.taskId)===v?null:w)},ix);return()=>{clearTimeout($)}},[(si=dt==null?void 0:dt.snapshot)==null?void 0:si.status,dt==null?void 0:dt.taskId]),d.useEffect(()=>{if(!Re)return;let v=!1;return Xp(e).then($=>{v||(is(w=>Nx(w,$)?w:$),!(!$.task||qt)&&Cn({taskId:$.task.taskId,snapshot:$.task}))}).catch(()=>{}),()=>{v=!0}},[qt,Re,e]),d.useEffect(()=>{if(!(qt!=null&&qt.snapshot)||!Or(qt.snapshot.status))return;const v=qt.taskId,$=setTimeout(()=>{Cn(w=>(w==null?void 0:w.taskId)===v?null:w)},Ez);return()=>{clearTimeout($)}},[(wr=qt==null?void 0:qt.snapshot)==null?void 0:wr.status,qt==null?void 0:qt.taskId]);const cs=async()=>{if(!(ut!=null&&ut.enabled)){De([]);return}try{const v=await XT(e);De(v.items)}catch{De([])}},Rt=async(v,$)=>{const w=(v==null?void 0:v.trim())||null,F=$.trim();if(!F)return;const Z=Date.now()+Dz;let be=null;for(;Date.now()<=Z;){try{const Ee=await Zi(e);be=Ee,kt(un=>Ai(un,Ee)?un:Ee),Ii(e,Ee);const Je=new Set((Ee.tags??[]).map(un=>un.path)),Et=Je.has(F),Hr=!w||w===F||!Je.has(w);if(Et&&Hr)break}catch{}await new Promise(Ee=>{window.setTimeout(Ee,Lz)})}if(w&&w!==F&&r.browseMode==="tag"&&(r.selectedTagPath===w||pn.includes(w))){const Ee=Array.from(new Set(pn.map(Je=>Je===w?F:Je)));i({...r,selectedTagPath:r.selectedTagPath===w?F:Ee[Ee.length-1]??null,selectedTagPaths:Ee})}if(be&&r.browseMode==="tag"){const Ee=await jo(e,{browseMode:"tag",selectedFolderPath:r.selectedFolderPath,selectedTagPath:w&&r.selectedTagPath===w?F:r.selectedTagPath,selectedTagPaths:w?pn.map(Je=>Je===w?F:Je):pn,selectedFavoriteId:r.selectedFavoriteId,offset:0,limit:Aa}).catch(()=>null);Ee&&(J(Je=>Pa(Je,Ee)?Je:Ee),Do(e,{...r,selectedTagPath:w&&r.selectedTagPath===w?F:r.selectedTagPath,selectedTagPaths:w?pn.map(Je=>Je===w?F:Je):pn},Ee))}};d.useEffect(()=>{var $;if(G!=="library"||!(ut!=null&&ut.enabled)||r.browseMode!=="folder")return;const v=B6(G,r.browseMode,r.selectedFolderPath);if(ls.current!==v){if(!zs.current){zs.current=!0,ls.current=v;return}ls.current=v,Promise.resolve(Jp(e,{reason:"directory_hint",targetPath:(($=r.selectedFolderPath)==null?void 0:$.trim())||null})).catch(()=>{})}},[G,ut==null?void 0:ut.enabled,r.browseMode,r.selectedFolderPath,e]),d.useEffect(()=>{let v=!1;const $=Ex(e),w=Lx(e);return kt(F=>Ai(F,$)?F:$),vt(F=>Oo(F,w)?F:w),_e($===null),bt(null),Zi(e).then(F=>{v||(kt(Z=>Ai(Z,F)?Z:F),Ii(e,F),_e(!1))}).catch(F=>{v||(bt(F instanceof Error?F.message:a("shell.navigationLoadFailed")),_e(!1))}),Xl(e).then(F=>{v||(vt(Z=>Oo(Z,F)?Z:F),Ec(e,F))}).catch(()=>{v||w||vt(null)}),()=>{v=!0}},[e]),d.useEffect(()=>{let v=!1;return tw().then($=>{v||pt(w=>zf(w,$)?w:$)}).catch(()=>{v||pt(null)}),()=>{v=!0}},[e]),d.useEffect(()=>{cs()},[ut==null?void 0:ut.enabled,e]),d.useEffect(()=>{var be;if(!((be=Ie==null?void 0:Ie.binding)!=null&&be.enabled))return;const v=Ie.status.state==="fresh"?Iz:Tz;let $=!1,w=null;const F=()=>{w=setTimeout(()=>{Z()},v)},Z=async()=>{try{const Ee=await Zi(e);if($)return;kt(Je=>Ai(Je,Ee)?Je:Ee),Ii(e,Ee)}catch{if($)return}$||F()};return F(),()=>{$=!0,w&&clearTimeout(w)}},[(zr=Ie==null?void 0:Ie.binding)==null?void 0:zr.enabled,Ie==null?void 0:Ie.status.state,e]),d.useEffect(()=>{let v=!1;return et(!0),xt(null),Promise.all([ep({workspaceId:e}),tS()]).then(([$,w])=>{v||(fn($.items.filter(F=>F.workspaceId===e)),O(w.items.filter(F=>F.workspaceId===e)),et(!1))}).catch($=>{v||(xt($ instanceof Error?$.message:a("shell.navigationLoadFailed")),et(!1))}),()=>{v=!0}},[e]),d.useEffect(()=>{let v=!1;return jt(!0),It(null),Promise.all([CO({limit:200}),jO({limit:200})]).then(([$,w])=>{v||(Xe($.payload.items.filter(F=>{var Ee,Je,Et;const Z=((Ee=F.actionConfig.targetSessionId)==null?void 0:Ee.trim())??"",be=((Et=(Je=F.controlSession)==null?void 0:Je.sessionId)==null?void 0:Et.trim())??"";return p.size===0||p.has(Z)||p.has(be)})),Un(w.payload.items),jt(!1))}).catch($=>{v||(It($ instanceof Error?$.message:a("shell.navigationLoadFailed")),jt(!1))}),()=>{v=!0}},[e,p,b]);const Yn=(Ct==null?void 0:Ct.items)??[],Mt=d.useMemo(()=>w6(Yn,(ut==null?void 0:ut.rootDir)??null),[ut==null?void 0:ut.rootDir,Yn]),A=d.useMemo(()=>Mt.filter(v=>v.isFavorite),[Mt]),ie=d.useMemo(()=>v6((Ie==null?void 0:Ie.tags)??[]).filter(C6),[Ie==null?void 0:Ie.tags]),tt=d.useMemo(()=>j6((Ie==null?void 0:Ie.folders)??[]),[Ie==null?void 0:Ie.folders]),Pt=d.useMemo(()=>(Ie==null?void 0:Ie.favorites)??[],[Ie==null?void 0:Ie.favorites]),zt=d.useMemo(()=>new Set(Pt.filter(v=>v.kind==="folder").map(v=>v.path)),[Pt]),pn=d.useMemo(()=>Xj(r),[r.selectedTagPath,r.selectedTagPaths]),Os=d.useMemo(()=>(Ct==null?void 0:Ct.tagFacetCounts)??{},[Ct==null?void 0:Ct.tagFacetCounts]),Tn=d.useMemo(()=>{var v;return((v=r.selectedFolderPath)==null?void 0:v.trim())||null},[r.selectedFolderPath]),Qs=d.useMemo(()=>r.browseMode==="folder"?(Ie==null?void 0:Ie.status.lastCompletedAt)??null:null,[Ie==null?void 0:Ie.status.lastCompletedAt,r.browseMode]);d.useEffect(()=>{if(G!=="library"||!(ut!=null&&ut.enabled)||r.browseMode!=="folder")return;let v=!1,$=null;const w=(Vt==null?void 0:Vt.state)==="running",F=w?Pz:(nn==null?void 0:nn.state)==="queued"||(nn==null?void 0:nn.state)==="running"?Az:Rz,Z=async()=>{if(w){v||($=setTimeout(()=>{Z()},F));return}try{const be=await jo(e,{browseMode:"folder",selectedFolderPath:Tn,selectedTagPath:r.selectedTagPath,selectedTagPaths:pn,selectedFavoriteId:r.selectedFavoriteId,offset:0,limit:Aa});v||(J(Ee=>Pa(Ee,be)?Ee:be),Do(e,r,be))}catch{}v||($=setTimeout(()=>{Z()},F))};return $=setTimeout(()=>{Z()},F),()=>{v=!0,$&&clearTimeout($)}},[G,ut==null?void 0:ut.enabled,nn==null?void 0:nn.state,Vt==null?void 0:Vt.state,pn,r.browseMode,r.selectedFavoriteId,r.selectedFolderEntryPath,r.selectedFolderPath,r.selectedTagPath,Tn,e]);const Pn=d.useMemo(()=>G!=="library"||!ut?[]:Mt,[G,ut,Mt]),on=async()=>{q(!0);try{await Jp(e,{reason:"manual_refresh"});const v=await Zi(e);if(kt($=>Ai($,v)?$:v),Ii(e,v),G==="library"&&ut){ze(!0);try{const $=await jo(e,{browseMode:r.browseMode,selectedFolderPath:Tn,selectedTagPath:r.selectedTagPath,selectedTagPaths:pn,selectedFavoriteId:r.selectedFavoriteId,offset:0,limit:Aa});J(w=>Pa(w,$)?w:$),Do(e,r,$)}finally{ze(!1)}}xn({title:a("shell.affairsLibraryRefreshQueued"),description:a("shell.affairsLibraryRefreshQueuedDescription"),tone:"success"})}catch(v){throw xn({title:a("shell.affairsLibraryRefreshFailed"),description:v instanceof Error?v.message:a("shell.affairsLibraryRefreshFailed"),tone:"error"}),v}finally{q(!1)}};d.useEffect(()=>{if(G!=="library"||!(ut!=null&&ut.enabled)){J(null),ze(!1);return}let v=!1;const $=Dx(e,r);return $?(J(w=>Pa(w,$)?w:$),ze(!1)):(J(null),ze(!0)),jo(e,{browseMode:r.browseMode,selectedFolderPath:Tn,selectedTagPath:r.selectedTagPath,selectedTagPaths:pn,selectedFavoriteId:r.selectedFavoriteId,offset:0,limit:Aa}).then(w=>{if(v)return;const F=O6($,w);J(Z=>Pa(Z,F)?Z:F),Do(e,r,F),ze(!1)}).catch(()=>{v||($||J({total:0,offset:0,limit:Aa,items:[]}),ze(!1))}),()=>{v=!0}},[G,ut==null?void 0:ut.enabled,Qs,r.browseMode,r.selectedFavoriteId,r.selectedFolderEntryPath,r.selectedFolderPath,r.selectedTagPath,pn,Tn,e]);const Sn=async()=>{if(G!=="library"||!ut||Ue)return;const v=Ct,$=(v==null?void 0:v.items.length)??0,w=(v==null?void 0:v.total)??0;if(!(v&&$>=w)){ze(!0);try{const F=await jo(e,{browseMode:r.browseMode,selectedFolderPath:Tn,selectedTagPath:r.selectedTagPath,selectedTagPaths:pn,selectedFavoriteId:r.selectedFavoriteId,offset:$,limit:Aa});J(Z=>{const be=F6(Z,F);return Do(e,r,be),Pa(Z,be)?Z:be})}finally{ze(!1)}}},gn=d.useMemo(()=>rq(Ws,mt),[mt,Ws]),bn=d.useMemo(()=>G==="workbench"?cl(r.selectedNodeId):r.selectedNodeId,[G,r.selectedNodeId]),Cs=d.useMemo(()=>G!=="workbench"?[]:!bn||bn==="workbench:overview"||bn==="workbench:todo:all"?gn:bn==="workbench:todo:inbox"?gn.filter(v=>v.kind==="inbox"):bn==="workbench:todo:follow_up"?gn.filter(v=>v.kind==="follow_up"):gn,[G,bn,gn]),js=d.useMemo(()=>iq(Ae,y),[Ae,y]),Ge=G==="library"?ve:G==="conversation"?!1:nt||ot,ei=G==="library"?Ft:G==="conversation"?null:_t??rt,Mn=d.useMemo(()=>{if(G==="library"){const v=r.selectedDocumentId??r.selectedObjectId,$=Pn.find(Z=>Z.id===v)??null,w=Ys(r.selectedFolderEntryPath),F=Ys(r.selectedFolderPath);return{section:"library",record:$??(w&&w!==F?null:$)}}if(G==="conversation")return{section:"conversation",record:null};if(!bn||bn==="workbench:overview")return{section:"workbench",record:null};if(bn.startsWith("workbench:todo:"))return{section:"todo",record:Cs.find($=>$.id===r.selectedObjectId)??Cs[0]??null};if(bn.startsWith("workbench:automation:")){const v=bn.startsWith("workbench:automation:item:")?bn.slice(26):null;return{section:"automation",record:js.find(w=>w.id===(r.selectedObjectId??v))??js[0]??null}}return{section:"workbench",record:null}},[G,bn,js,Pn,Cs,r.selectedDocumentId,r.selectedFolderEntryPath,r.selectedFolderPath,r.selectedObjectId]);d.useEffect(()=>{var v;if(!(ut!=null&&ut.enabled)){it(null);return}if(Mn.section==="library"&&((v=Mn.record)!=null&&v.id)){nh(e,Mn.record.id).then(it).catch(()=>it(null));return}it(null)},[ut==null?void 0:ut.enabled,Mn,e]),d.useEffect(()=>{var v,$;if(!(ut!=null&&ut.enabled)){Ht(null);return}if(Mn.section==="library"&&!Mn.record){const w=((v=r.selectedFolderEntryPath)==null?void 0:v.trim())||(($=r.selectedFolderPath)==null?void 0:$.trim())||".";sh(e,w).then(Ht).catch(()=>Ht(null));return}Ht(null)},[ut==null?void 0:ut.enabled,Mn,r.selectedFolderEntryPath,r.selectedFolderPath,e]),d.useEffect(()=>{var F;const v=((F=Mn.record)==null?void 0:F.id)??null,$=Hf(G),w={...r,primarySection:G,selectedNodeId:G==="library"?r.selectedNodeId??$:G==="workbench"?bn??$:r.selectedNodeId??$,selectedObjectId:v,selectedDocumentId:G==="library"?v:r.selectedDocumentId};JSON.stringify(w)!==JSON.stringify(r)&&i(w)},[G,bn,js,ut,i,Mn.record,r]);const Hs=d.useMemo(()=>{if(Mn.section==="library"){const $=Mn.record;return $?{objectType:"document",objectId:$.id,title:$.displayName,summary:$.summary,sourceRef:$.filePath,assistantScope:`workspace:${e}:document:${$.id}`}:null}if(Mn.section==="todo"){const $=Mn.record;return $?{objectType:"todo",objectId:$.id,title:$.title,summary:`${$.statusLabel} · ${$.summary}`,sourceRef:$.sourceSessionId,assistantScope:`workspace:${e}:todo:${$.id}`}:null}if(Mn.section==="conversation"||Mn.section==="workbench")return null;const v=Mn.record;return v?{objectType:"automation",objectId:v.id,title:v.title,summary:`${v.statusLabel} · ${v.summary}`,sourceRef:v.targetSessionLabel,assistantScope:`workspace:${e}:automation:${v.id}`}:null},[Mn,e]),ir=d.useMemo(()=>{if(G!=="workbench")return null;const v=aq(bn),$=Cs.map(F=>{var Z;return((Z=F.title)==null?void 0:Z.trim())||""}).filter(Boolean).slice(0,3),w=Cs.length>0?$.length>0?a("shell.affairsWorkbenchAssistantContextSummary",{scopeLabel:v,count:Cs.length,titles:$.join("、")}):a("shell.affairsWorkbenchAssistantContextSummaryCompact",{scopeLabel:v,count:Cs.length}):a("shell.affairsWorkbenchAssistantContextEmpty");return{objectType:"workbench",objectId:`workbench:${e}:${cl(bn)??"overview"}`,title:a("shell.affairsWorkbenchAssistantContextTitle"),summary:w,sourceRef:v,assistantScope:`workspace:${e}:workbench:todo`}},[G,bn,Cs,e]);d.useEffect(()=>{Hs&&Me(v=>$6(v,Hs)?v:Hs)},[Hs]);const Is=G==="workbench"?ir:G==="conversation"?Hs??W:Hs,Zs=d.useMemo(()=>{if(G==="library")return[];if(G==="conversation"){const v=(Array.isArray(we)?we:[]).map(be=>({id:li("lightweight",be.sessionId),label:be.title,summary:[Cl("lightweight"),Eu(be.provider),be.lastMessageAt?uo(be.lastMessageAt):null].filter(Boolean).join(" · "),tone:"conversation"})),$=hd(ks,jn)?(ks==null?void 0:ks.session)??null:null,w=Array.isArray(Te)?Te:[],Z=($?[$,...w.filter(be=>be.sessionId!==$.sessionId)]:w).map(be=>({id:li("agent",be.sessionId),label:be.title,summary:[Cl("agent"),Eu(be.provider),be.lastMessageAt?uo(be.lastMessageAt):null].filter(Boolean).join(" · "),tone:"conversation"}));return[...v,...Z]}return G==="workbench"?[{id:"workbench:overview",label:a("shell.affairsWorkbenchOverviewLabel"),count:gn.length+js.length,summary:a("shell.affairsWorkbenchOverviewSummary",{todoCount:gn.length,automationCount:js.length}),tone:"workbench"},{id:"workbench:todo:all",label:a("shell.affairsTodoAllFilter"),count:gn.length,summary:a("shell.affairsTodoAllFilterSummary"),tone:"default"},{id:"workbench:todo:inbox",label:a("shell.affairsTodoInboxFilter"),count:gn.filter(v=>v.kind==="inbox").length,summary:a("shell.affairsTodoInboxSummary"),tone:"source"},{id:"workbench:todo:follow_up",label:a("shell.affairsTodoFollowUpFilter"),count:gn.filter(v=>v.kind==="follow_up").length,summary:a("shell.affairsTodoFollowUpSummary"),tone:"source"},...js.map(v=>({id:`workbench:automation:item:${v.id}`,label:v.title,summary:`${v.triggerLabel} · ${v.statusLabel}`,tone:"automation"}))]:[]},[Ds,G,jn,js,ks,Mt.length,Pt,tt,we,r.browseMode,ie,gn,g]),yn=d.useCallback(v=>{x.current=Lu(v),R(null),z(null),T(v)},[]),Us=d.useCallback(v=>{const $=new Date().toISOString(),w=Pc(v.session,$);v.kind==="lightweight"?(se(F=>Rc(F,w)),pe(F=>F.map(Z=>Z.sessionId===w.sessionId?w:Z))):(se(F=>F.map(Z=>Z.sessionId===w.sessionId?w:Z)),pe(F=>Rc(F,w))),T(null),R({kind:v.kind,session:w,bootstrapMessages:v.bootstrapMessages}),z({kind:v.kind,sessionId:w.sessionId}),x.current=li(v.kind,w.sessionId),Promise.resolve(v.kind==="lightweight"?Zp(e,w.sessionId,$):Qp(w.sessionId)).catch(()=>{})},[e]);d.useEffect(()=>{const v=cx(e,sn),$=JSON.stringify(v);Gt(w=>JSON.stringify(w)===$?w:v),sn&&(es.current=$)},[sn,e]),d.useEffect(()=>{bT(At)},[At]),d.useEffect(()=>{if(tn!=="remote"||sn)return;const v=$k(e);v&&Ga.updateProfile({affairsDashboardStatesByWorkspace:lx(as,e,v)}).catch(()=>{})},[tn,sn,as,e]),d.useEffect(()=>{if(tn!=="remote")return;const v=JSON.stringify(At);if((sn?JSON.stringify(sn):null)===v){es.current=v;return}if(es.current!==v)return Zn.current&&clearTimeout(Zn.current),Zn.current=setTimeout(()=>{const F=Ga.getState().affairsDashboardStatesByWorkspace??{},Z=F[e]??null;if((Z?JSON.stringify(Z):null)===v){es.current=v;return}const Ee=yT(e,At)??At;Ga.updateProfile({affairsDashboardStatesByWorkspace:lx(F,e,Ee)}).then(()=>{es.current=v}).catch(()=>{})},Fz),()=>{Zn.current&&(clearTimeout(Zn.current),Zn.current=null)}},[At,tn,sn,e]);const qs=d.useCallback(v=>{Gt($=>!$.tabs.some(w=>w.id===v)||$.activeTabId===v?$:{...$,activeTabId:v,updatedAt:new Date().toISOString()})},[]),us=d.useCallback(()=>{Gt(v=>{const $=new Date().toISOString(),w=xT(a("shell.affairsWorkbenchNewTabTitle",{count:v.tabs.length+1}),$);return{...v,activeTabId:w.id,tabs:[...v.tabs,w],updatedAt:$}})},[]),kr=d.useCallback((v,$)=>{const w=$.trim();w&&Gt(F=>Ra(F,v,(Z,be)=>Z.title===w?Z:{...Z,title:w,updatedAt:be}))},[]),$r=d.useCallback(v=>{Gt($=>{var Ee,Je;if($.tabs.length<=1||!$.tabs.some(Et=>Et.id===v))return $;const w=new Date().toISOString(),F=$.tabs.findIndex(Et=>Et.id===v),Z=$.tabs.filter(Et=>Et.id!==v),be=$.activeTabId===v?((Ee=Z[Math.max(0,F-1)])==null?void 0:Ee.id)??((Je=Z[0])==null?void 0:Je.id)??$.activeTabId:$.activeTabId;return{...$,tabs:Z,activeTabId:be,updatedAt:w}})},[]),pi=d.useCallback(()=>{Gt(v=>({...v,layoutLocked:!v.layoutLocked,updatedAt:new Date().toISOString()}))},[]),ti=d.useCallback(v=>{Gt($=>Ra($,$.activeTabId,(w,F)=>{const Z=vT({type:v.type,variant:v.variant,title:v.title,sourceRef:v.sourceRef,config:v.config},F),be=[...w.widgets,Z];return{...w,widgets:be,layout:Ac(be,w.layout),updatedAt:F}}))},[]),gi=d.useCallback((v,$)=>{Gt(w=>Ra(w,w.activeTabId,(F,Z)=>({...F,widgets:F.widgets.map(be=>be.id===v?{...be,config:{...be.config,...$},updatedAt:Z}:be),updatedAt:Z})))},[]),En=d.useCallback((v,$)=>{Gt(w=>Ra(w,w.activeTabId,(F,Z)=>{const be=F.widgets;if(!F.layout.find(Et=>Et.widgetId===v))return F;const Je=Ac(be,F.layout.map(Et=>Et.widgetId===v?{...Et,...$,widgetId:v}:Et),!1,v);return{...F,layout:Je,updatedAt:Z}}))},[]),dr=d.useCallback(v=>{Gt($=>Ra($,$.activeTabId,(w,F)=>{const Z=w.widgets.filter(be=>be.id!==v);return{...w,widgets:Z,layout:Ac(Z,w.layout),updatedAt:F}}))},[]),ni=d.useCallback(()=>{Gt(v=>Ra(v,v.activeTabId,($,w)=>({...$,layout:Ac($.widgets,$.layout,!0),updatedAt:w})))},[]),er=d.useCallback(v=>{Gt($=>{const w=v.sourceKind==="affairs_library"?"affairs_library":"workspace",F=v.workspaceId.trim(),Z=v.entryPath.trim(),be=new Date().toISOString(),Ee=$.shortcutApps.findIndex(Je=>Je.sourceKind===w&&Je.workspaceId===F&&Je.entryPath===Z);if(Ee>=0){const Je={...$.shortcutApps[Ee],title:Ki(Z,v.title),sourceKind:w,workspaceId:F,updatedAt:be},Et=[...$.shortcutApps];return Et.splice(Ee,1),Et.unshift(Je),{...$,shortcutApps:Et,updatedAt:be}}return{...$,shortcutApps:[kT({title:v.title,sourceKind:w,workspaceId:F,entryPath:Z,sourceId:Z},be),...$.shortcutApps],updatedAt:be}})},[]),Pr=d.useCallback((v,$)=>{Gt(w=>{const F=$.sourceKind==="affairs_library"?"affairs_library":"workspace",Z=$.workspaceId.trim(),be=$.entryPath.trim(),Ee=new Date().toISOString(),Je=w.shortcutApps.find(un=>un.id===v);if(!Je)return w;const Et=w.shortcutApps.find(un=>un.id!==v&&un.sourceKind===F&&un.workspaceId===Z&&un.entryPath===be),Hr={...Je,title:Ki(be,$.title),sourceKind:F,workspaceId:Z,entryPath:be,sourceId:be,updatedAt:Ee};return{...w,shortcutApps:[Hr,...w.shortcutApps.filter(un=>un.id!==v&&un.id!==(Et==null?void 0:Et.id))],updatedAt:Ee}})},[]),Yi=d.useCallback(v=>{Gt($=>({...$,shortcutApps:$.shortcutApps.filter(w=>w.id!==v),updatedAt:new Date().toISOString()}))},[]),As={dashboardState:At,activeDashboardTab:os,layoutLocked:At.layoutLocked,selectDashboardTab:qs,addDashboardTab:us,renameDashboardTab:kr,removeDashboardTab:$r,toggleDashboardLayoutLocked:pi,addDashboardWidget:ti,updateDashboardWidgetConfig:gi,setDashboardWidgetLayout:En,removeDashboardWidget:dr,resetActiveDashboardLayout:ni,addShortcutApp:er,updateShortcutApp:Pr,removeShortcutApp:Yi},tr=d.useMemo(()=>({workspaceId:e,workspaceName:t,navigationGroups:n,agentWorkspaceId:jn,agentProjectId:Ce,agentWorkspacePath:Ds,state:r,activeSection:G,initGuard:ns,loading:Ge,error:ei,libraryLoading:ve,libraryDocumentsLoading:Ue,libraryRefreshPending:st,libraryDocumentTotal:(Ct==null?void 0:Ct.total)??0,libraryDocumentHasMore:((Ct==null?void 0:Ct.items.length)??0)<((Ct==null?void 0:Ct.total)??0),binding:ut,globalLibraryBinding:$t,libraryConfig:St,indexStatus:Vt,currentDirectoryStatus:nn,documentRecords:Mt,filteredDocuments:Pn,favoriteDocuments:A,favoriteEntries:Pt,tagRecords:ie,selectedTagPaths:pn,libraryTagFacetCounts:Os,folderRecords:tt,todoRecords:gn,filteredTodoRecords:Cs,automationRecords:js,selectedObject:Mn,assistantContext:Is,automationRuns:Qt,sidebarNodes:Zs,auxiliaryTab:ms,toolbarExpanded:r.toolbarExpanded,detailViewerCollapsed:r.detailViewerCollapsed,selectSection:v=>{var w;Ts();const $=v==="conversation"?(w=r.selectedNodeId)!=null&&w.startsWith("conversation:")?r.selectedNodeId:x.current:null;i({...r,primarySection:v,selectedNodeId:$??Hf(v),selectedObjectId:null,selectedDocumentId:v==="library"?null:r.selectedDocumentId,auxiliaryTab:Fo(v,r.auxiliaryTab)})},openInitializedSection:v=>{var w;Ts();const $=v==="conversation"?(w=r.selectedNodeId)!=null&&w.startsWith("conversation:")?r.selectedNodeId:x.current:null;i({...r,primarySection:v,selectedNodeId:$??Hf(v),selectedObjectId:null,selectedDocumentId:v==="library"?null:r.selectedDocumentId,auxiliaryTab:Fo(v,r.auxiliaryTab)})},selectSidebarNode:v=>{if(G==="library"){if(v.startsWith("library:folder:")){i({...r,browseMode:"folder",selectedNodeId:v,selectedFolderPath:v.slice(15),selectedFolderEntryPath:null,selectedTagPath:null,selectedTagPaths:[],selectedFavoriteId:null,selectedObjectId:null,selectedDocumentId:null});return}if(v.startsWith("library:tag:")){const $=v.slice(12),w=R6(ie,pn,$);i({...r,browseMode:"tag",selectedNodeId:w.length>0?`library:tag:${w[w.length-1]}`:"library:tag-root",selectedTagPath:w[w.length-1]??null,selectedTagPaths:w,selectedFolderPath:null,selectedFolderEntryPath:null,selectedFavoriteId:null,selectedObjectId:null,selectedDocumentId:null});return}if(v.startsWith("library:favorite:")){const $=v,w=Pt.find(F=>rm(F)===$);i({...r,browseMode:(w==null?void 0:w.kind)==="tag"?"tag":"folder",selectedNodeId:v,selectedFavoriteId:$,selectedFolderPath:(w==null?void 0:w.kind)==="folder"?w.path:null,selectedTagPath:(w==null?void 0:w.kind)==="tag"?w.path:null,selectedTagPaths:(w==null?void 0:w.kind)==="tag"?[w.path]:[],selectedObjectId:null,selectedDocumentId:null});return}i({...r,selectedNodeId:v,selectedFavoriteId:null,selectedFolderPath:null,selectedFolderEntryPath:null,selectedTagPath:null,selectedTagPaths:[],selectedObjectId:null,selectedDocumentId:null});return}i({...r,selectedNodeId:G==="workbench"?cl(v)??"workbench:overview":v,selectedObjectId:Cq(G,v)})},selectObject:v=>{i({...r,selectedObjectId:v,selectedDocumentId:G==="library"?v:r.selectedDocumentId,selectedFolderEntryPath:G==="library"&&v?null:r.selectedFolderEntryPath})},selectAuxiliaryTab:v=>{i({...r,auxiliaryTab:Fo(G,v)})},setLibraryBrowseMode:v=>{i({...r,browseMode:v,selectedNodeId:v==="folder"?"library:all":"library:tag-root",selectedFavoriteId:null,selectedFolderPath:null,selectedFolderEntryPath:null,selectedTagPath:null,selectedTagPaths:[],selectedObjectId:null,selectedDocumentId:null})},setLibraryViewMode:v=>{i({...r,viewMode:v})},selectLibraryFolderEntry:v=>{i({...r,selectedObjectId:null,selectedDocumentId:null,selectedFolderEntryPath:(v==null?void 0:v.trim())||null})},navigateLibraryFolder:v=>{var F;const $=(v==null?void 0:v.trim())||null,w=((F=r.selectedFolderPath)==null?void 0:F.trim())||null;i({...r,browseMode:"folder",selectedNodeId:$?`library:folder:${$}`:"library:all",selectedFolderPath:$,selectedFolderEntryPath:tq(w,$),selectedTagPath:null,selectedTagPaths:[],selectedFavoriteId:null,selectedObjectId:null,selectedDocumentId:null})},navigateLibraryTag:v=>{const $=(v==null?void 0:v.trim())||null;i({...r,browseMode:"tag",selectedNodeId:$?`library:tag:${$}`:"library:tag-root",selectedTagPath:$,selectedTagPaths:$?[$]:[],selectedFolderPath:null,selectedFolderEntryPath:null,selectedFavoriteId:null,selectedObjectId:null,selectedDocumentId:null})},toggleDetailViewerCollapsed:()=>{i({...r,detailViewerCollapsed:!r.detailViewerCollapsed})},toggleToolbarExpanded:()=>{i({...r,toolbarExpanded:!r.toolbarExpanded})},initializeButlerProfile:async v=>{await an.initializeProfile(v)},updateButlerProfile:async v=>{await an.updateProfile(v)},reloadButlerProfile:async()=>{await an.initialize()},openLibraryViewer:v=>{ue({filePath:v.filePath,title:v.displayName})},saveLibraryBinding:async v=>{const[$,w,F]=await Promise.all([nw({rootDir:v}),Zi(e),Xl(e)]);pt(Z=>zf(Z,$)?Z:$),kt(Z=>Ai(Z,w)?Z:w),vt(Z=>Oo(Z,F)?Z:F),Ii(e,w),Ec(e,F)},setLibraryEnabled:async v=>{const[$,w,F]=await Promise.all([sw({enabled:v}),Zi(e),Xl(e)]);pt(Z=>zf(Z,$)?Z:$),kt(Z=>Ai(Z,w)?Z:w),vt(Z=>Oo(Z,F)?Z:F),Ii(e,w),Ec(e,F)},saveLibraryConfig:async v=>{const w=await KT(e,v)??await Xl(e);vt(Z=>Oo(Z,w)?Z:w),Ec(e,w);const F=await Zi(e);return kt(Z=>Ai(Z,F)?Z:F),Ii(e,F),w},refreshLibrary:on,toggleFavorite:async v=>{const $=(Ie==null?void 0:Ie.favorites)??[],w=$.some(be=>be.kind===v.kind&&be.path===v.path),F=w?$.filter(be=>!(be.kind===v.kind&&be.path===v.path)):[...$,v],Z=await JT({favorites:F});kt(be=>{const Ee=be&&{...be,favorites:Z.items};return Ee&&Ii(e,Ee),Ee}),xn({title:w?a("shell.affairsFavoriteRemoved"):a("shell.affairsFavoriteAdded"),description:v.label,tone:"success"})},loadMoreLibraryDocuments:Sn,tagManagementOpen:Re,openTagManagement:()=>Se(!0),closeTagManagement:()=>Se(!1),managedTags:Ke,selectedManagedTag:He,documentTagDetails:wt,folderTagDetails:Ze,folderTagTaskMonitor:gt,recentTagTasks:en,fullTagRecomputeTaskMonitor:qt,tagRecoveryStatus:Bt,reloadTagManagement:cs,selectManagedTag:async v=>{if(!v){lt(null);return}lt(await ZT(e,v))},saveManagedTag:async v=>{var F;const $=v.tagId?((F=He==null?void 0:He.path)==null?void 0:F.trim())??null:null,w=v.tagId?await e0(e,v.tagId,v):await QT(e,v);return lt(w),await cs(),Rt($,w.path),w},deleteManagedTag:async v=>{const $=await t0(e,v);return lt(w=>(w==null?void 0:w.id)===v||$.deletedTagIds.includes((w==null?void 0:w.id)??"")?null:w),await cs(),await on(),{deletedTagIds:$.deletedTagIds,deletedPaths:$.deletedPaths}},requestFullTagRecompute:async()=>{const v=await n0(e);return Cn({taskId:v.taskId,snapshot:null}),v},saveDocumentTagSelection:async(v,$,w=[],F=[],Z)=>{const be=Sx(F,$),Ee={documentId:v,documentTitle:(Z==null?void 0:Z.trim())||(wt==null?void 0:wt.title)||v,taskId:`pending:document:${v}:${Date.now()}`,snapshot:Cx(`doc:${v}`,be),operation:be};ft(Ee),Gn(Ee);const Je=w.length>0?await i0(e,v,{tagIds:$,createTagPaths:w}):await r0(e,v,{tagIds:$});if(Je!=null&&Je.refreshTask){const Et={documentId:v,documentTitle:(Z==null?void 0:Z.trim())||(wt==null?void 0:wt.title)||v,taskId:Je.refreshTask.taskId,snapshot:null,operation:be};ft(Et),Gn(Et)}else{const Et={...Ee,snapshot:jx(Ee.snapshot,be)};ft(Et),Gn(Et)}w.length>0&&await cs(),it(await nh(e,v)),await on()},saveFolderTagSelection:async(v,$,w=[],F=[])=>{const Z=Sx(F,$),be={folderPath:v,taskId:`pending:${v}:${Date.now()}`,snapshot:Cx(`folder:${v}`,Z),operation:Z};Nt(be),Wn(be);const Ee=w.length>0?await l0(e,{folderPath:v,tagIds:$,createTagPaths:w}):await o0(e,{folderPath:v,tagIds:$});if(Ee.refreshTask){const Je={folderPath:Ee.target.folderPath,taskId:Ee.refreshTask.taskId,snapshot:null,operation:Z};Nt(Je),Wn(Je)}else{const Je={...be,snapshot:jx(be.snapshot,Z)};Nt(Je),Wn(Je)}w.length>0&&await cs(),Ht(await sh(e,v)),await on()},conversationCreateModalOpen:k,conversationCreateModalMode:j,openConversationCreateModal:v=>{H((v==null?void 0:v.mode)==="agent-only"?"agent-only":"all"),C(!0)},closeConversationCreateModal:()=>{C(!1),H("all")},prepareAssistantConversation:async v=>{var be,Ee;if(!jn)return;yn({kind:"agent",provider:v}),!an.getState().initialized&&typeof an.initialize=="function"&&await an.initialize();const $=an.getState(),w=to($.activeProvider)?$.activeProvider:null,F=((Ee=(be=$.controlSession)==null?void 0:be.session.sessionId)==null?void 0:Ee.trim())??"",Z=Array.isArray($.messages)&&$.messages.length>0;w!==v?await an.switchProvider(v):(F||Z)&&await an.startFreshSession()},rememberConversationDraft:yn,rememberConversationSession:Us,butlerStore:an,archiveConversationSession:async v=>{const $=v.kind==="lightweight"?await eg(e,v.session.sessionId,!0):await cu(v.session.sessionId,!0);v.kind==="lightweight"?se(w=>w.map(F=>F.sessionId===$.sessionId?$:F)):pe(w=>w.map(F=>F.sessionId===$.sessionId?$:F)),ws({kind:v.kind,sessionId:$.sessionId}),await(o==null?void 0:o())},unarchiveConversationSession:async v=>{const $=v.kind==="lightweight"?await eg(e,v.session.sessionId,!1):await cu(v.session.sessionId,!1);v.kind==="lightweight"?se(w=>Rc(w,$)):pe(w=>Rc(w,$)),await(o==null?void 0:o())},toggleConversationSessionFavorite:async v=>{const $=v.kind==="lightweight"?await j0(e,v.session.sessionId,v.session.isFavorite!==!0):await aw(v.session.sessionId,v.session.isFavorite!==!0);v.kind==="lightweight"?se(w=>w.map(F=>F.sessionId===$.sessionId?$:F)):pe(w=>w.map(F=>F.sessionId===$.sessionId?$:F)),await(o==null?void 0:o())},markConversationSessionSeen:(v,$,w)=>{const F=w??new Date().toISOString();se(Z=>Z.map(be=>be.sessionId===$?Pc(be,F):be)),pe(Z=>Z.map(be=>be.sessionId===$?Pc(be,F):be)),R(Z=>Z&&Z.session.sessionId===$?{...Z,session:Pc(Z.session,F)}:Z),(v==="lightweight"?Zp(e,$,F):Qp($)).catch(()=>{})},openConversationRenameModal:v=>{E(v),te(v.session.title??"")},openConversationDeleteModal:v=>{he(v)},renameConversationSession:async v=>{const $=v.kind==="lightweight"?await C0(e,v.session.sessionId,v.title.trim()):await xm(v.session.sessionId,v.title.trim());return v.kind==="lightweight"?se(w=>w.map(F=>F.sessionId===$.sessionId?$:F)):pe(w=>w.map(F=>F.sessionId===$.sessionId?$:F)),R(w=>w&&w.session.sessionId===$.sessionId?{...w,session:$}:w),$},deleteConversationSession:async v=>{v.kind==="lightweight"?(await N0(e,v.session.sessionId),se($=>$.filter(w=>w.sessionId!==v.session.sessionId))):(await rh(v.session.sessionId),pe($=>$.filter(w=>w.sessionId!==v.session.sessionId))),ws({kind:v.kind,sessionId:v.session.sessionId}),await(o==null?void 0:o())},exportConversationSession:async({session:v,format:$})=>{var w,F;if(!xe){le(v.sessionId);try{const Z=ge.has(v.sessionId)?await RH(e,v.sessionId):await nC(v.sessionId),be=vH();if($==="md"){Tu(Za(v,"md"),sC(v,Z.messages),"text/markdown;charset=utf-8");return}Bs.flushSync(()=>{de({session:v,items:bo({messages:Z.messages}),shellWidthPx:be.shellWidthPx})}),await kH(je.current);const Ee=((w=je.current)==null?void 0:w.innerHTML.trim())??"";if(!Ee)throw new Error(a("conversation.exportLoadFailed"));const Je=px(document.documentElement),Et=document.body?px(document.body):{},Hr=document.documentElement.getAttribute("style"),un=((F=document.body)==null?void 0:F.getAttribute("style"))??null,yo=`${wH()}
667
+ ${gH}`,xa=aC({title:v.title||a("conversation.titleFallback"),bodyHtml:`<div class="session-export-document-root">${Ee}</div>`,styleText:yo,htmlAttributes:Je,bodyAttributes:Et,htmlStyle:Hr,bodyStyle:un});if($==="html"){Tu(Za(v,"html"),xa,"text/html;charset=utf-8");return}rC(Za(v,"pdf"),iC(v,Z.messages),"application/pdf")}finally{Bs.flushSync(()=>{de(null)}),le(null)}}},selectedConversationDraft:_,selectConversationDraft:v=>{yn(v),i({...r,primarySection:"conversation",selectedNodeId:Lu(v),selectedObjectId:null,selectedDocumentId:null})},selectedConversationSession:P,conversationRuntimeSeed:L,lightweightRuntimeBySessionId:Ne,setLightweightRuntimeSnapshot:ps,lightweightConversationSessions:we,lightweightConversationSessionsLoading:ce,reloadLightweightConversationSessions:On,agentConversationSessions:Te,agentConversationSessionsLoading:fe,reloadAgentConversationSessions:vs,activateConversationSession:v=>{Us(v),i({...r,primarySection:"conversation",selectedNodeId:li(v.kind,v.session.sessionId),selectedObjectId:null,selectedDocumentId:null})}}),[G,jn,Ds,Is,js,Qt,ut,$t,Nn,ks,an,St,Mt,ei,A,Pt,zt,Pn,Cs,tt,k,Vt,i,nn,Ct,Ue,ve,st,Ie,Sn,Ge,Ke,ns,i,o,He,_,P,L,Ne,ps,we,ce,On,Te,fe,vs,ws,Mn,Zs,pn,r,ie,gn,Re,wt,Ze,gt,en,qt,Bt,dt,yn,Us,on,cs,Gn,Wn,re,xn,e,t,xe]);return s.jsx(Ij.Provider,{value:tr,children:s.jsxs(wj.Provider,{value:As,children:[l,s.jsx(jH,{}),s.jsx(SH,{target:K,value:D,busySessionId:V,onChange:te,onClose:()=>{V||(E(null),te(""))},onSubmit:async v=>{if(v.preventDefault(),!K)return;const $=D.trim();if($){ee(K.session.sessionId);try{await tr.renameConversationSession({kind:K.kind,session:K.session,title:$}),E(null),te(""),xn({title:a("shell.renameSuccess"),tone:"success"})}catch(w){xn({title:w instanceof Error?w.message:a("shell.renameFailed"),tone:"error"})}finally{ee(null)}}}}),s.jsx(CH,{target:U,busySessionId:X,onClose:()=>{X||he(null)},onConfirm:async()=>{if(U){I(U.session.sessionId);try{await tr.deleteConversationSession({kind:U.kind,session:U.session}),he(null),xn({title:a("shell.deleteSessionSuccess"),tone:"success"})}catch(v){xn({title:v instanceof Error?v.message:a("shell.deleteSessionFailed"),tone:"error"})}finally{I(null)}}}}),M?s.jsx("div",{ref:je,className:"session-export-print-root","aria-hidden":"true",children:s.jsxs("div",{className:"session-export-print-shell",style:M.shellWidthPx?{width:`${M.shellWidthPx}px`,maxWidth:"100%"}:void 0,children:[s.jsxs("header",{className:"session-export-print-header",children:[s.jsx("h1",{children:M.session.title||a("conversation.titleFallback")}),s.jsx("p",{children:a("conversation.exportAction")})]}),s.jsx($S,{sessionId:M.session.sessionId,items:M.items,provider:M.session.provider})]})}):null,s.jsx(MU,{workspaceId:e,viewerState:re,onClose:()=>ue(null),onSaved:()=>on()})]})})}function aH(){const{activeSection:e,selectSection:t}=Qn();return s.jsxs("div",{className:"workbench-nav-code-entries",role:"tablist","aria-label":a("shell.affairsSidebarMenuLabel"),children:[s.jsxs("button",{type:"button",className:e==="library"?"workbench-nav-segment-button active":"workbench-nav-segment-button",role:"tab","aria-selected":e==="library",onClick:()=>t("library"),children:[s.jsx(FU,{}),s.jsx("span",{children:a("shell.affairsLibraryNav")})]}),s.jsxs("button",{type:"button",className:e==="conversation"?"workbench-nav-segment-button active":"workbench-nav-segment-button",role:"tab","aria-selected":e==="conversation",onClick:()=>t("conversation"),children:[s.jsx(WU,{}),s.jsx("span",{children:a("shell.affairsConversationNav")})]}),s.jsxs("button",{type:"button",className:e==="workbench"?"workbench-nav-segment-button active":"workbench-nav-segment-button",role:"tab","aria-selected":e==="workbench",onClick:()=>t("workbench"),children:[s.jsx($U,{}),s.jsx("span",{children:a("shell.affairsWorkbenchNav")})]})]})}function ux({standalone:e=!1}){const{workspaceId:t,navigationGroups:n,globalLibraryBinding:r}=Qn(),{dashboardState:i,addShortcutApp:o,updateShortcutApp:l,removeShortcutApp:c}=Op(),{showToast:u}=Vn(),f=Hn(),[h,m]=d.useState(!1),[g,p]=d.useState(!1),[b,y]=d.useState(null),[x,k]=d.useState(!e),C=d.useMemo(()=>jj(r,t),[r,t]),j=d.useMemo(()=>Cj(n,t,C),[C,n,t]),H=d.useMemo(()=>Nj({currentWorkspaceId:t,currentLibraryWorkspace:C,options:j}),[C,j,t]),[_,T]=d.useState(H),P=d.useMemo(()=>Tj(j,_),[_,j]),z=d.useMemo(()=>(P==null?void 0:P.label)??"",[P]),[L,R]=d.useState(""),[K,E]=d.useState(""),[D,te]=d.useState(!1),[V,ee]=d.useState(null);d.useEffect(()=>{g||(T(H),R(""),E(""),y(null))},[g,H]),d.useEffect(()=>{k(!e),m(!1),p(!1),y(null)},[e]);const U=d.useCallback(async I=>{if(I.preventDefault(),!D){te(!0);try{const xe=await eH(P,L),le=Ki(xe.path,K);b?l(b,{sourceKind:(P==null?void 0:P.kind)==="affairs_library"?"affairs_library":"workspace",title:le,workspaceId:(P==null?void 0:P.workspaceId)??t,entryPath:xe.path}):o({sourceKind:(P==null?void 0:P.kind)==="affairs_library"?"affairs_library":"workspace",title:le,workspaceId:(P==null?void 0:P.workspaceId)??t,entryPath:xe.path}),T(H),R(""),E(""),p(!1),u({title:b?a("shell.affairsShortcutRailUpdatedTitle"):a("shell.affairsShortcutRailAddedTitle"),description:le,tone:"success"})}catch(xe){u({title:Sl(xe,b?a("shell.affairsShortcutRailUpdateFailed"):a("shell.affairsShortcutRailAddFailed")),tone:"error"})}finally{te(!1)}}},[o,H,b,L,P,u,D,K,l,t]),he=d.useCallback(I=>{if(h){y(I.id),T(I.sourceKind==="affairs_library"?kj:I.workspaceId),R(I.entryPath),E(I.title),p(!0);return}ee(I)},[h]),X=d.useCallback(async()=>{if(V)try{if(V.sourceKind==="affairs_library"){const I=await $u(V.workspaceId,V.entryPath);if(!I.previewUrl)throw new Error(a("shell.affairsShortcutRailOpenFailed"));window.open(Jh(I.previewUrl),"_blank","noopener,noreferrer")}else{const I=await zu(V.workspaceId,V.entryPath);window.open(Jh(I.previewUrl),"_blank","noopener,noreferrer")}}catch(I){u({title:Sl(I,a("shell.affairsShortcutRailOpenFailed")),description:V.title,tone:"error"})}},[V,u]);return s.jsxs("section",{className:e?"workbench-section-block affairs-shortcut-rail affairs-shortcut-rail-standalone":"workbench-section-block affairs-shortcut-rail","data-collapsed":!e&&x?"true":void 0,"aria-label":a("shell.affairsShortcutRailTitle"),children:[s.jsxs("div",{className:"affairs-sidebar-block-header affairs-shortcut-rail-header",children:[s.jsx("div",{children:s.jsx("h2",{children:a("shell.affairsShortcutRailTitle")})}),s.jsxs("div",{className:"affairs-shortcut-rail-header-actions",children:[s.jsx("span",{className:"affairs-sidebar-block-count",children:i.shortcutApps.length}),(e||!x)&&h?s.jsx("button",{type:"button",className:"affairs-dashboard-toolbar-icon-button affairs-shortcut-rail-header-icon-button","aria-label":g?a("shell.affairsWorkbenchCancelAction"):a("shell.affairsShortcutRailAddAction"),title:g?a("shell.affairsWorkbenchCancelAction"):a("shell.affairsShortcutRailAddAction"),onClick:()=>{p(I=>{const xe=!I;return xe&&(y(null),T(H),R(""),E("")),xe})},children:g?s.jsx(Dp,{}):s.jsx(qj,{})}):null,e||!x?s.jsx("button",{type:"button",className:"affairs-dashboard-toolbar-icon-button affairs-shortcut-rail-header-icon-button","aria-label":h?a("shell.affairsShortcutRailDoneAction"):a("shell.affairsShortcutRailEditAction"),title:h?a("shell.affairsShortcutRailDoneAction"):a("shell.affairsShortcutRailEditAction"),onClick:()=>{m(I=>{const xe=!I;return xe||p(!1),xe})},children:h?s.jsx(VU,{}):s.jsx(qU,{})}):null,e?null:s.jsx("button",{type:"button",className:"affairs-dashboard-toolbar-icon-button affairs-shortcut-rail-header-icon-button","aria-expanded":!x,"aria-label":x?a("shell.affairsShortcutRailExpandAction"):a("shell.affairsShortcutRailCollapseAction"),title:x?a("shell.affairsShortcutRailExpandAction"):a("shell.affairsShortcutRailCollapseAction"),onClick:()=>k(I=>!I),children:s.jsx(zj,{collapsed:x})})]})]}),!x&&h&&g?s.jsxs("form",{className:"affairs-shortcut-rail-editor",onSubmit:U,children:[s.jsxs("label",{className:"affairs-dashboard-inline-field",htmlFor:"affairs-shortcut-source-workspace",children:[s.jsx("span",{children:a("shell.affairsWorkbenchHtmlSourceWorkspaceField")}),s.jsx("select",{id:"affairs-shortcut-source-workspace",className:"affairs-dashboard-inline-select",value:_,onChange:I=>{T(I.currentTarget.value),R("")},children:j.map(I=>s.jsx("option",{value:I.value,children:I.label},I.value))})]}),(P==null?void 0:P.kind)==="affairs_library"?s.jsx("p",{className:"affairs-dashboard-inline-help",children:a("shell.affairsWorkbenchHtmlSourceWorkspaceCurrentLibraryHelper",{path:P.rootDir})}):null,s.jsx(Vj,{sourceOption:P,workspaceLabel:z,inputId:"affairs-shortcut-entry-path",value:L,onChange:R,label:a("shell.affairsShortcutRailSourceSelectField"),placeholder:a("shell.affairsShortcutRailSourceSelectPlaceholder"),helpText:a("shell.affairsShortcutRailSourceHelper"),listFailedMessage:a("shell.affairsShortcutRailSourceListFailed")}),s.jsxs("label",{className:"affairs-dashboard-inline-field",htmlFor:"affairs-shortcut-title",children:[s.jsx("span",{children:a("shell.affairsShortcutRailTitleField")}),s.jsx("input",{id:"affairs-shortcut-title",className:"affairs-dashboard-inline-input",value:K,onChange:I=>E(I.currentTarget.value),placeholder:a("shell.affairsShortcutRailTitlePlaceholder")})]}),s.jsx("div",{className:"affairs-dashboard-inline-actions",children:s.jsx("button",{type:"submit",className:"secondary-button",disabled:D,children:D?a("common.loading"):b?a("shell.affairsShortcutRailConfirmEditAction"):a("shell.affairsShortcutRailConfirmAddAction")})})]}):null,x?null:i.shortcutApps.length===0?s.jsx("div",{className:"affairs-shortcut-rail-empty",children:a("shell.affairsShortcutRailEmpty")}):s.jsx("div",{className:"affairs-shortcut-rail-list","data-editing":h?"true":void 0,children:i.shortcutApps.map(I=>s.jsxs("div",{className:"affairs-shortcut-rail-item",children:[h?s.jsx("button",{type:"button",className:"affairs-shortcut-rail-remove-button","aria-label":a("shell.affairsShortcutRailRemoveAction"),onClick:()=>c(I.id),children:s.jsx("span",{"aria-hidden":"true",children:"×"})}):null,s.jsxs("button",{type:"button",className:"affairs-shortcut-rail-launcher","aria-label":h?a("shell.affairsShortcutRailEditEntryAction",{title:I.title}):a("shell.affairsShortcutRailLaunchAction",{title:I.title}),onClick:()=>he(I),children:[s.jsx("span",{className:"affairs-shortcut-rail-icon",style:Gz(I.title),"aria-hidden":"true",children:Kz(I.title)}),s.jsx("span",{className:"affairs-shortcut-rail-copy",children:s.jsx("strong",{children:I.title})})]})]},I.id))}),V?s.jsx(vp,{workspaceId:V.workspaceId,filePath:V.entryPath,open:!0,onClose:()=>ee(null),onSaved:()=>{},windowTitle:V.title,previewLoader:V.sourceKind==="affairs_library"?((I,xe,le)=>ym(I,xe,le)):void 0,saveHandler:V.sourceKind==="affairs_library"?(async({workspaceId:I,filePath:xe,content:le,expectedVersion:M})=>{await Wa(I,{opType:"write",srcPath:xe,content:le,expectedVersion:M})}):void 0,showDetachAction:f.isDesktop&&f.bridge.supported,onDetach:()=>void X()}):null]})}function co(e){const t=e.lastMessageAt??e.updatedAt??e.createdAt??null,n=t?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:0}function Aj(e){return[...e].sort((t,n)=>co(n)-co(t))}function Rc(e,t){const n=e.filter(r=>r.sessionId!==t.sessionId);return n.push(t),Aj(n)}function dx(e,t){const n=new Map(t.map(r=>[r.sessionId,r]));for(const r of e)n.has(r.sessionId)||r.rawStoreRef.startsWith("butler://")||n.set(r.sessionId,r);return Aj(Array.from(n.values()))}function Rj(e){const t=(e==null?void 0:e.trim())??"";return t.startsWith("butler://")&&t.slice(9).trim()||null}function Rp(e){return Ui(e,"compact")}function Pp(e){const t=e.lastMessageAt??e.updatedAt??e.createdAt;return t?uo(t):""}function Pc(e,t){return{...e,lastSeenAt:e.lastSeenAt&&e.lastSeenAt>t?e.lastSeenAt:t,activityState:e.activityState==="completed_unread"?"idle":e.activityState}}function oH(e,t){return xS("session-state-indicator",e,{isActive:t==null?void 0:t.isActive})}function fx({active:e=!1}){return s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:e?"currentColor":"none","aria-hidden":"true",children:s.jsx("path",{d:"m10 2.9 2.18 4.41 4.87.71-3.52 3.43.83 4.85L10 14.02 5.64 16.3l.83-4.85L2.95 8.02l4.87-.71L10 2.9Z",stroke:"currentColor",strokeWidth:"1.4",strokeLinejoin:"round"})})}function lH(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[s.jsx("path",{d:"M3.5 5.5h13v10a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 15.5z",stroke:"currentColor",strokeWidth:"1.4"}),s.jsx("path",{d:"M2.75 3.25h14.5v2.5H2.75zM7 9.25h6",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]})}function cH(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[s.jsx("path",{d:"M4.75 14.25v1h1l7.98-7.98-1.99-1.99-6.99 6.99Z",stroke:"currentColor",strokeWidth:"1.4",strokeLinejoin:"round"}),s.jsx("path",{d:"m11.74 5.28 1.99 1.99 1.24-1.24a1.41 1.41 0 1 0-1.99-1.99z",stroke:"currentColor",strokeWidth:"1.4",strokeLinejoin:"round"})]})}function uH(){return s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:s.jsx("path",{d:"M10 3.5v8m0 0 3-3m-3 3-3-3M4.5 13.5v1A1.5 1.5 0 0 0 6 16h8a1.5 1.5 0 0 0 1.5-1.5v-1",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})})}function dH(){return s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:s.jsx("path",{d:"M4 6.25c0-.69.56-1.25 1.25-1.25h9.5c.69 0 1.25.56 1.25 1.25v1.5c0 .69-.56 1.25-1.25 1.25h-9.5C4.56 9 4 8.44 4 7.75zm1.5 4.25h9v3.25A1.25 1.25 0 0 1 14.25 15h-8.5A1.25 1.25 0 0 1 4.5 13.75zm2.25 1.5h4.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})})}function fH(){return s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:s.jsx("path",{d:"M5.5 6.25h9l-.62 8.06A1.5 1.5 0 0 1 12.39 15.7H7.61a1.5 1.5 0 0 1-1.49-1.39zM7.75 6.25V4.9A1.4 1.4 0 0 1 9.15 3.5h1.7a1.4 1.4 0 0 1 1.4 1.4v1.35M4 6.25h12",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})})}function hH({item:e,isActive:t,role:n,onOpen:r,onRename:i,onExport:o,onToggleFavorite:l,onArchive:c,onDelete:u}){const f=Hn(),h=d.useRef(null),[m,g]=d.useState(!1),[p,b]=d.useState(null),[y,x]=d.useState(null),[k,C]=d.useState(!1),j=wS(e.session),H=vS("session-activity-badge",e.session),_=Pp(e.session);d.useEffect(()=>{m||C(!1)},[m]),d.useEffect(()=>{if(!m||f.isDesktop)return;const R=E=>{var D;(D=h.current)!=null&&D.contains(E.target)||(g(!1),b(null))},K=E=>{E.key==="Escape"&&(g(!1),b(null))};return document.addEventListener("pointerdown",R),document.addEventListener("keydown",K),()=>{document.removeEventListener("pointerdown",R),document.removeEventListener("keydown",K)}},[m,f.isDesktop]),d.useLayoutEffect(()=>{if(f.isDesktop||!m||!p||typeof window>"u"){x(null);return}const R=()=>{var E,D;const K=dp(p,{width:((E=h.current)==null?void 0:E.offsetWidth)??0,height:((D=h.current)==null?void 0:D.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:132});x({position:"fixed",top:`${Math.round(K.top)}px`,left:`${Math.round(K.left)}px`,width:`${Math.round(K.width)}px`,maxWidth:"calc(100vw - 24px)",maxHeight:`${Math.round(K.maxHeight)}px`,transformOrigin:K.transformOrigin})};return R(),window.addEventListener("resize",R),window.addEventListener("scroll",R,!0),()=>{window.removeEventListener("resize",R),window.removeEventListener("scroll",R,!0)}},[p,m,f.isDesktop]);const T=d.useCallback(()=>{g(!1),b(null)},[]),P=d.useCallback(R=>{b(R),g(!0)},[]),z=d.useCallback(async()=>{await dl([{id:`rename:${e.session.sessionId}`,label:a("shell.renameAction"),onSelect:i},{id:`export:${e.session.sessionId}`,label:a("conversation.exportAction"),items:[{id:`export-markdown:${e.session.sessionId}`,label:a("conversation.exportMarkdownAction"),onSelect:()=>o("md")},{id:`export-pdf:${e.session.sessionId}`,label:a("conversation.exportPdfAction"),onSelect:()=>o("pdf")},{id:`export-html:${e.session.sessionId}`,label:a("conversation.exportHtmlAction"),onSelect:()=>o("html")}]},{id:`favorite:${e.session.sessionId}`,label:e.session.isFavorite?a("shell.unfavoriteAction"):a("shell.favoriteAction"),onSelect:l},{id:`archive:${e.session.sessionId}`,label:a("shell.archiveAction"),onSelect:c},{id:`delete:${e.session.sessionId}`,label:a("shell.deleteSessionAction"),onSelect:u}])},[e.session.isFavorite,e.session.sessionId,c,u,o,i,l]),L=!f.isDesktop&&m&&typeof document<"u"?Bs.createPortal(s.jsxs("div",{ref:h,className:"workbench-session-menu",role:"menu","aria-label":a("shell.sessionMoreAction"),onClick:R=>R.stopPropagation(),style:y??{position:"fixed",top:0,left:0,visibility:"hidden"},children:[s.jsxs("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{T(),i()},children:[s.jsx(cH,{}),s.jsx("span",{children:a("shell.renameAction")})]}),s.jsxs("div",{className:"workbench-session-submenu","data-open":k,children:[s.jsxs("button",{type:"button",className:"workbench-session-menu-item","aria-haspopup":"menu","aria-expanded":k,onClick:()=>C(R=>!R),children:[s.jsx(uH,{}),s.jsx("span",{children:a("conversation.exportAction")}),s.jsx("span",{className:"workbench-session-submenu-caret","aria-hidden":"true",children:"›"})]}),k?s.jsxs("div",{className:"workbench-session-submenu-panel",role:"menu","aria-label":a("conversation.exportAction"),children:[s.jsx("button",{type:"button",className:"workbench-session-menu-item",role:"menuitem",onClick:()=>{o("md").finally(T)},children:s.jsx("span",{children:a("conversation.exportMarkdownAction")})}),s.jsx("button",{type:"button",className:"workbench-session-menu-item",role:"menuitem",onClick:()=>{o("pdf").finally(T)},children:s.jsx("span",{children:a("conversation.exportPdfAction")})}),s.jsx("button",{type:"button",className:"workbench-session-menu-item",role:"menuitem",onClick:()=>{o("html").finally(T)},children:s.jsx("span",{children:a("conversation.exportHtmlAction")})})]}):null]}),s.jsxs("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{l().finally(T)},children:[s.jsx(fx,{active:e.session.isFavorite}),s.jsx("span",{children:e.session.isFavorite?a("shell.unfavoriteAction"):a("shell.favoriteAction")})]}),s.jsxs("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{c().finally(T)},children:[s.jsx(lH,{}),s.jsx("span",{children:a("shell.archiveAction")})]}),s.jsxs("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{T(),u()},children:[s.jsx(fH,{}),s.jsx("span",{children:a("shell.deleteSessionAction")})]})]}),document.body):null;return s.jsxs("article",{role:n,className:"workbench-session-card affairs-conversation-session-card","data-active":t,"data-kind":e.kind,"data-workspace-tone":"root",onContextMenu:R=>{if(R.preventDefault(),R.stopPropagation(),f.isDesktop){z();return}P({x:R.clientX,y:R.clientY})},children:[s.jsxs("div",{className:"workbench-session-main",children:[s.jsx("span",{className:oH(e.session,{isActive:t}),"data-activity-source":e.session.activitySource,"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"workbench-session-link","data-active":t,onClick:r,onKeyDown:R=>{if(R.key!=="ContextMenu"&&!(R.shiftKey&&R.key==="F10"))return;if(R.preventDefault(),R.stopPropagation(),f.isDesktop){z();return}const K=R.currentTarget.getBoundingClientRect();P({x:K.right,y:K.bottom})},children:s.jsxs("div",{className:"workbench-session-link-copy",children:[s.jsxs("div",{className:"session-title-row",children:[s.jsx("span",{className:"session-title",title:e.session.title,children:e.session.title}),e.session.isFavorite?s.jsx("span",{className:"affairs-conversation-favorite-badge","aria-hidden":"true",children:s.jsx(fx,{active:!0})}):null]}),s.jsxs("div",{className:"session-meta-row",children:[s.jsx("span",{className:"session-meta",children:[Cl(e.kind),_].filter(Boolean).join(" · ")}),j&&H?s.jsx("span",{className:H,children:j}):null,s.jsx("span",{className:`session-provider-badge ${e.session.provider}`,children:Rp(e.session.provider)})]})]})})]}),L]})}function mH(){const{activeSection:e,agentWorkspaceId:t,agentConversationSessions:n,agentConversationSessionsLoading:r,binding:i,butlerStore:o,initGuard:l,lightweightConversationSessions:c,lightweightConversationSessionsLoading:u,markConversationSessionSeen:f,openConversationCreateModal:h,openTagManagement:m,archiveConversationSession:g,unarchiveConversationSession:p,documentRecords:b,favoriteEntries:y,folderRecords:x,indexStatus:k,sidebarNodes:C,state:j,tagRecords:H,libraryTagFacetCounts:_,toggleFavorite:T,toggleConversationSessionFavorite:P,todoRecords:z,automationRecords:L,selectSidebarNode:R,selectedTagPaths:K,loading:E,error:D,libraryDocumentTotal:te,openConversationRenameModal:V,openConversationDeleteModal:ee,exportConversationSession:U}=Qn(),he=Zt(o,de=>de.controlSession),X=Hn(),[I,xe]=d.useState(!1),{showToast:le}=Vn(),M=de=>s.jsxs("div",{className:"affairs-sidebar-shell",children:[s.jsx("div",{className:"affairs-sidebar-content",children:de}),s.jsx(ux,{})]});if(e==="conversation"&&l.loading)return M(s.jsxs("section",{className:"workbench-section-block affairs-sidebar-block",children:[s.jsx("div",{className:"affairs-sidebar-block-header",children:s.jsxs("div",{children:[s.jsx("h2",{children:a("shell.affairsConnectionCheckingTitle")}),s.jsx("p",{children:a("shell.affairsConnectionCheckingDescription")})]})}),s.jsx("div",{className:"affairs-sidebar-empty",children:a("shell.affairsConnectionCheckingSidebarEmpty")})]}));if(e==="conversation"&&l.unavailable)return M(s.jsxs("section",{className:"workbench-section-block affairs-sidebar-block",children:[s.jsx("div",{className:"affairs-sidebar-block-header",children:s.jsxs("div",{children:[s.jsx("h2",{children:a("shell.affairsHostUnavailableTitle")}),s.jsx("p",{children:a("shell.affairsHostUnavailableDescription")})]})}),s.jsx("div",{className:"affairs-sidebar-empty",children:a("shell.affairsHostUnavailableSidebarEmpty")})]}));if(e==="conversation"&&!l.initialized)return M(s.jsxs("section",{className:"workbench-section-block affairs-sidebar-block",children:[s.jsx("div",{className:"affairs-sidebar-block-header",children:s.jsxs("div",{children:[s.jsx("h2",{children:a("shell.affairsConversationSidebarTitle")}),s.jsx("p",{children:a("shell.affairsInitRouteGuardHint")})]})}),s.jsx("div",{className:"affairs-sidebar-empty",children:a("shell.affairsInitRouteGuardSidebarEmpty")})]}));if(e==="conversation"){const de=hd(he,t)?(he==null?void 0:he.session)??null:null,Ne=de&&n.every(ce=>ce.sessionId!==de.sessionId)?[de,...n]:n,ye=[...c.map(ce=>({id:li("lightweight",ce.sessionId),kind:"lightweight",session:ce})),...Ne.map(ce=>({id:li("agent",ce.sessionId),kind:"agent",session:ce}))].sort((ce,Y)=>ce.session.isFavorite!==Y.session.isFavorite?ce.session.isFavorite?-1:1:co(Y.session)-co(ce.session)),Be=ye.filter(ce=>ce.session.isArchived!==!0),We=ye.filter(ce=>ce.session.isArchived===!0),ke=(u||r)&&Be.length===0,we=Be.length>0?bq({lightweightLoading:u,agentLoading:r}):null,se=We.length>0?s.jsx(Wi,{className:"workbench-archive-list",children:We.map(ce=>s.jsx(rs,{className:"workbench-archive-item",trailing:s.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{p({kind:ce.kind,session:ce.session}).then(()=>{xe(Y=>We.length>1?Y:!1)})},children:a("shell.unarchiveAction")}),children:s.jsxs("div",{className:"workbench-archive-item-main",children:[s.jsx("strong",{title:ce.session.title,children:ce.session.title||a("common.unknown")}),s.jsxs("p",{children:[Cl(ce.kind)," · ",Pp(ce.session)," · ",Rp(ce.session.provider)]})]})},ce.id))}):s.jsx($i,{title:a("shell.archiveEmpty"),compact:!0,className:"workbench-section-empty"});return M(s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"workbench-section-block affairs-sidebar-block",children:[s.jsxs("div",{className:"affairs-sidebar-block-header affairs-sidebar-block-header-with-count",children:[s.jsxs("div",{className:"affairs-sidebar-block-header-title-row",children:[s.jsx("h2",{children:a("shell.affairsConversationSidebarTitle")}),s.jsx("span",{className:"affairs-sidebar-block-count",children:Be.length})]}),s.jsx(Pj,{compact:!0,onClick:h})]}),s.jsx("div",{className:"affairs-sidebar-groups",role:"list",children:s.jsx("section",{className:"affairs-sidebar-group",children:ke?s.jsx("div",{className:"affairs-sidebar-empty compact",children:a("common.loading")}):s.jsxs(s.Fragment,{children:[Be.length===0?s.jsx("div",{className:"affairs-sidebar-empty affairs-sidebar-empty-plain compact",children:We.length>0?a("shell.archiveModalDescription"):a("shell.affairsConversationCreateHint")}):s.jsx("div",{className:"workbench-session-list affairs-conversation-session-list",role:"list",children:Be.map(ce=>s.jsx(hH,{item:ce,isActive:ce.id===j.selectedNodeId,role:"listitem",onOpen:()=>{f(ce.kind,ce.session.sessionId),R(ce.id)},onRename:()=>{V({kind:ce.kind,session:ce.session})},onExport:async Y=>{try{await U({session:ce.session,format:Y}),le({title:Y==="md"?a("conversation.exportMarkdownSuccess"):Y==="pdf"?a("conversation.exportPdfPreparing"):a("conversation.exportHtmlSuccess"),tone:"success"})}catch(Te){le({title:Te instanceof Error?Te.message:a("conversation.exportLoadFailed"),tone:"error"})}},onToggleFavorite:()=>P({kind:ce.kind,session:ce.session}),onArchive:()=>g({kind:ce.kind,session:ce.session}),onDelete:async()=>{ee({kind:ce.kind,session:ce.session})}},ce.id))}),We.length>0?s.jsxs("button",{type:"button",className:"workbench-archive-folder","data-workspace-tone":"root",onClick:()=>xe(!0),children:[s.jsxs("span",{className:"workbench-archive-folder-main",children:[s.jsx(dH,{}),s.jsx("span",{children:a("shell.archiveFolderLabel")})]}),s.jsx("span",{className:"workbench-section-counter",children:We.length})]}):null,we?s.jsx("div",{className:"affairs-sidebar-empty compact",children:we}):null]})})})]}),X.isMobile?s.jsx(zi,{open:I,onClose:()=>xe(!1),title:a("shell.archiveModalTitle"),description:a("shell.archiveModalDescription"),height:"half",children:se}):s.jsx(Qr,{open:I,onClose:()=>xe(!1),title:a("shell.archiveModalTitle"),description:a("shell.archiveModalDescription"),size:"regular",children:se})]}))}if(e==="workbench")return s.jsx("div",{className:"affairs-sidebar-shell",children:s.jsx(ux,{standalone:!0})});if(e!=="library"){const de=jq(e,C);return M(s.jsxs("section",{className:"workbench-section-block affairs-sidebar-block",children:[s.jsx("div",{className:"affairs-sidebar-block-header",children:s.jsxs("div",{children:[s.jsx("h2",{children:cq(e)}),s.jsx("p",{children:uq(e,{documentCount:b.length,favoriteCount:y.length,tagCount:H.length,todoCount:z.length,automationCount:L.length})})]})}),E?s.jsx("div",{className:"affairs-sidebar-empty compact",children:a("common.loading")}):null,D?s.jsx("div",{className:"affairs-sidebar-empty",children:D}):null,!E&&!D?s.jsx("div",{className:"affairs-sidebar-groups",role:"list",children:de.length===0?s.jsx("div",{className:"affairs-sidebar-empty",children:dq(e)}):de.map(Ne=>s.jsxs("section",{className:"affairs-sidebar-group",children:[s.jsxs("header",{className:"affairs-sidebar-group-header",children:[s.jsx("span",{children:Ne.label}),s.jsx("span",{children:Ne.items.length})]}),s.jsx("div",{className:"affairs-sidebar-list",role:"list",children:Ne.items.map(ye=>s.jsx("div",{className:ye.id===j.selectedNodeId?"affairs-sidebar-item active":"affairs-sidebar-item","data-tone":ye.tone??"default",children:s.jsxs("button",{type:"button",className:"affairs-sidebar-item-button",onClick:()=>R(ye.id),children:[s.jsxs("div",{className:"affairs-sidebar-item-row",children:[s.jsx("span",{className:"affairs-sidebar-item-title",children:ye.label}),typeof ye.count=="number"?s.jsx("span",{className:"affairs-sidebar-item-badge",children:ye.count}):null]}),ye.summary?s.jsx("span",{className:"affairs-sidebar-item-summary",children:ye.summary}):null]})},ye.id))})]},Ne.id))}):null]}))}return M(s.jsx(pH,{}))}function pH(){const{binding:e,documentRecords:t,favoriteEntries:n,folderRecords:r,indexStatus:i,libraryTagFacetCounts:o,loading:l,error:c,openTagManagement:u,selectSidebarNode:f,selectedTagPaths:h,state:m,tagRecords:g,toggleFavorite:p}=Qn(),b=n.filter(D=>D.kind==="folder"),y=n.filter(D=>D.kind==="tag"&&Gj(D.path)),[x,k]=d.useState(()=>Mx(m.workspaceId)),C=x.expandedPaths??[],j=x.expandedOverflowPaths??[],H=x.accessCounts??{},_=d.useMemo(()=>N6(g,H),[H,g]),T=h.length>0,P=d.useMemo(()=>Yj(_,o,T),[T,o,_]),z=d.useMemo(()=>P6(P,h,o),[o,h,P]),L=d.useMemo(()=>Qj(P,z.visiblePathSet),[z.visiblePathSet,P]);d.useEffect(()=>{k(Mx(m.workspaceId))},[m.workspaceId]),d.useEffect(()=>{m.browseMode!=="tag"||h.length===0||k(D=>{const te=new Set(D.expandedPaths??[]);h.forEach(U=>{for(const he of Zj(U))te.add(he)});const V=Array.from(te),ee=Array.from(new Set([...D.expandedOverflowPaths??[],...h.flatMap(U=>A6(L,U))]));return Rx(D.expandedPaths??[],V)&&Rx(D.expandedOverflowPaths??[],ee)?D:{...D,expandedPaths:V,expandedOverflowPaths:ee}})},[h,m.browseMode,L]),d.useEffect(()=>{m.browseMode!=="tag"||h.length===0||h.every(D=>g.some(te=>te.path===D))||f("library:tag-root")},[f,h,m.browseMode,g]),d.useEffect(()=>{M6(m.workspaceId,x)},[m.workspaceId,x]),d.useEffect(()=>{m.browseMode!=="tag"||h.length===0||k(D=>{const V={...D.accessCounts??{}};return h.forEach(ee=>{V[ee]=(V[ee]??0)+1}),{...D,accessCounts:V}})},[h,m.browseMode]);const R=d.useMemo(()=>Jj(L,Yo,j),[j,L]),K=D=>{k(te=>{const V=te.expandedPaths??[];return{...te,expandedPaths:V.includes(D)?V.filter(ee=>ee!==D):[...V,D]}})},E=D=>{k(te=>{const V=te.expandedOverflowPaths??[];return{...te,expandedOverflowPaths:V.includes(D)?V.filter(ee=>ee!==D):[...V,D]}})};return s.jsxs("section",{className:"workbench-section-block affairs-sidebar-block",children:[l?s.jsx("div",{className:"affairs-sidebar-empty compact",children:a("common.loading")}):null,c?s.jsx("div",{className:"affairs-sidebar-empty",children:c}):null,!l&&!c?s.jsxs("div",{className:"affairs-sidebar-groups affairs-library-sidebar-groups",children:[n.length>0?s.jsxs("section",{className:"affairs-sidebar-group affairs-sidebar-group-plain affairs-favorites-panel",children:[s.jsxs("header",{className:"affairs-sidebar-group-header",children:[s.jsx("span",{children:a("shell.affairsSectionGroupFavorites")}),s.jsx("span",{children:n.length})]}),s.jsx("div",{className:"affairs-sidebar-list affairs-sidebar-list-plain",role:"list",children:s.jsxs(s.Fragment,{children:[b.length>0?s.jsx("div",{className:"affairs-sidebar-subtitle",children:a("shell.affairsLibraryBrowseModeFolder")}):null,b.map(D=>{const te=rm(D);return s.jsx("div",{className:te===m.selectedNodeId?"affairs-sidebar-item active":"affairs-sidebar-item","data-tone":"favorite",children:s.jsxs("div",{className:"affairs-sidebar-item-button-shell",children:[s.jsx("button",{type:"button",className:"affairs-sidebar-item-button affairs-sidebar-item-button-content",onClick:()=>f(te),children:s.jsx("div",{className:"affairs-sidebar-item-row",children:s.jsx("span",{className:"affairs-sidebar-item-title",children:D.label})})}),s.jsx("div",{className:"affairs-sidebar-item-actions",children:im(te,D.label,p)})]})},te)}),y.length>0?s.jsx("div",{className:"affairs-sidebar-subtitle",children:a("shell.affairsLibraryBrowseModeTag")}):null,y.map(D=>{const te=rm(D);return s.jsx("div",{className:te===m.selectedNodeId?"affairs-sidebar-item active":"affairs-sidebar-item","data-tone":"favorite",children:s.jsxs("div",{className:"affairs-sidebar-item-button-shell",children:[s.jsx("button",{type:"button",className:"affairs-sidebar-item-button affairs-sidebar-item-button-content",onClick:()=>f(te),children:s.jsx("div",{className:"affairs-sidebar-item-row",children:s.jsx("span",{className:"affairs-sidebar-item-title",children:D.label})})}),s.jsx("div",{className:"affairs-sidebar-item-actions",children:im(te,D.label,p)})]})},te)})]})})]}):null,s.jsxs("section",{className:"affairs-sidebar-group affairs-sidebar-group-plain affairs-tag-tree-panel",children:[s.jsxs("header",{className:"affairs-sidebar-group-header",children:[s.jsx("span",{children:a("shell.affairsLibraryTagTreeTitle")}),s.jsxs("div",{className:"affairs-sidebar-group-header-actions",children:[s.jsx("span",{children:g.length}),T?s.jsx("button",{type:"button",className:"affairs-tag-tree-icon-button affairs-tag-tree-reset","aria-label":a("shell.affairsLibraryTagTreeReset"),title:a("shell.affairsLibraryTagTreeReset"),onClick:()=>f("library:tag-root"),children:s.jsx(p6,{})}):null,s.jsx("button",{type:"button",className:"affairs-tag-tree-icon-button","aria-label":a("shell.affairsTagManagerAction"),title:a("shell.affairsTagManagerAction"),onClick:u,children:s.jsx(b6,{})})]})]}),L.length===0?s.jsx("div",{className:"affairs-sidebar-empty affairs-sidebar-empty-plain compact",children:am(i)}):s.jsxs("div",{className:"affairs-tag-tree-list",role:"tree","aria-label":a("shell.affairsLibraryTagTreeTitle"),children:[R.map(D=>s.jsx(Bj,{node:D,state:m,selectedTagPaths:h,expandedPaths:C,expandedOverflowPaths:j,onSelect:f,onToggleExpand:K,onToggleOverflow:E,onToggleFavorite:p},D.path)),L.length>vl?s.jsxs("button",{type:"button",className:"affairs-tag-tree-more",onClick:()=>E(Yo),children:[s.jsx("span",{className:"affairs-tag-tree-more-icon","aria-hidden":"true",children:j.includes(Yo)?"▴":"▾"}),s.jsx("span",{className:"affairs-tag-tree-more-label",children:j.includes(Yo)?a("shell.affairsLibraryTagTreeShowLess"):a("shell.affairsLibraryTagTreeShowMore")})]}):null]})]}),e&&r.length===0&&g.length===0?s.jsx("div",{className:"affairs-sidebar-empty affairs-sidebar-empty-plain",children:am(i)}):null]}):null]})}function Pj({compact:e=!1,onClick:t}){return s.jsxs("button",{type:"button",className:e?"secondary-button affairs-conversation-create-trigger icon-only":"secondary-button affairs-conversation-create-trigger","aria-label":a("shell.affairsConversationCreateAction"),title:a("shell.affairsConversationCreateAction"),onClick:t,children:[s.jsx(Mj,{}),e?null:s.jsx("span",{children:a("shell.affairsConversationCreateAction")})]})}function Mj(){return s.jsx("svg",{viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:s.jsx("path",{d:"M10 4.25V15.75M4.25 10H15.75",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}function hx({kind:e,title:t,description:n,providers:r}){const{agentWorkspaceId:i,closeConversationCreateModal:o,conversationCreateModalMode:l,prepareAssistantConversation:c,selectConversationDraft:u}=Qn();return s.jsxs("section",{className:"create-session-modal-section affairs-conversation-create-modal-section",children:[s.jsxs("div",{className:"create-session-modal-section-header",children:[s.jsx("strong",{children:t}),s.jsx("p",{children:n})]}),s.jsx(yC,{workspaceId:e==="agent"?i:null,providers:r,onSelect:f=>{if(l==="agent-only"&&e==="agent"&&to(f)){c(f).finally(()=>{o()});return}u({kind:e,provider:f}),o()}})]})}const gH=`
668
+ html,
669
+ body {
670
+ width: 100% !important;
671
+ height: auto !important;
672
+ min-height: auto !important;
673
+ overflow: visible !important;
674
+ overflow-x: visible !important;
675
+ }
676
+
677
+ body {
678
+ margin: 0 !important;
679
+ padding: 0 !important;
680
+ }
681
+
682
+ .session-export-document-root {
683
+ position: static !important;
684
+ inset: auto !important;
685
+ z-index: auto !important;
686
+ opacity: 1 !important;
687
+ pointer-events: auto !important;
688
+ overflow: visible !important;
689
+ }
690
+
691
+ .session-export-document-root,
692
+ .session-export-document-root * {
693
+ font-family: var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif);
694
+ letter-spacing: normal !important;
695
+ word-spacing: normal !important;
696
+ text-align: left !important;
697
+ -webkit-text-fill-color: currentColor !important;
698
+ text-fill-color: currentColor !important;
699
+ -webkit-background-clip: border-box !important;
700
+ background-clip: border-box !important;
701
+ text-shadow: none !important;
702
+ mix-blend-mode: normal !important;
703
+ }
704
+
705
+ .session-export-document-root .markdown-content p,
706
+ .session-export-document-root .markdown-content blockquote,
707
+ .session-export-document-root .markdown-content td {
708
+ display: block !important;
709
+ }
710
+
711
+ .session-export-document-root .markdown-content li {
712
+ display: list-item !important;
713
+ }
714
+
715
+ .session-export-document-root .markdown-content code,
716
+ .session-export-document-root .markdown-content pre,
717
+ .session-export-document-root .code-block pre,
718
+ .session-export-document-root .tool-call-section pre,
719
+ .session-export-document-root .tool-call-input-preview,
720
+ .session-export-document-root .apply-patch-line-content,
721
+ .session-export-document-root .apply-patch-summary-file {
722
+ font-family:
723
+ var(--font-mono, "SF Mono", "Consolas", "Cascadia Code", "Courier New", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", monospace) !important;
724
+ }
725
+
726
+ .session-export-document-root .thinking-message-label,
727
+ .session-export-document-root .thinking-status-text {
728
+ background: none !important;
729
+ color: var(--text-secondary, #475569) !important;
730
+ -webkit-text-fill-color: currentColor !important;
731
+ animation: none !important;
732
+ }
733
+
734
+ @media print {
735
+ body * {
736
+ visibility: hidden;
737
+ }
738
+
739
+ .session-export-document-root,
740
+ .session-export-document-root * {
741
+ visibility: visible;
742
+ }
743
+
744
+ .session-export-document-root {
745
+ position: static !important;
746
+ }
747
+
748
+ .session-export-document-root .session-export-print-shell {
749
+ width: 100%;
750
+ max-width: none;
751
+ margin: 0;
752
+ padding: 0;
753
+ }
754
+
755
+ .session-export-document-root .message-timeline-export,
756
+ .session-export-document-root .message-timeline-export .message-list-export {
757
+ overflow: visible;
758
+ height: auto;
759
+ max-height: none;
760
+ }
761
+
762
+ .session-export-document-root .tool-call-header,
763
+ .session-export-document-root .tool-call-info,
764
+ .session-export-document-root .task-tool-header,
765
+ .session-export-document-root .task-tool-heading,
766
+ .session-export-document-root .task-tool-heading-main,
767
+ .session-export-document-root .task-tool-list-item,
768
+ .session-export-document-root .assistant-capability-header,
769
+ .session-export-document-root .assistant-capability-heading,
770
+ .session-export-document-root .assistant-capability-heading-main,
771
+ .session-export-document-root .assistant-capability-row,
772
+ .session-export-document-root .apply-patch-summary-row,
773
+ .session-export-document-root .rules-message-toggle {
774
+ display: flex !important;
775
+ flex-wrap: wrap !important;
776
+ align-items: flex-start !important;
777
+ justify-content: flex-start !important;
778
+ }
779
+
780
+ .session-export-document-root .task-tool-list-item,
781
+ .session-export-document-root .assistant-capability-row,
782
+ .session-export-document-root .apply-patch-summary-row {
783
+ row-gap: 4px !important;
784
+ }
785
+
786
+ .session-export-document-root .tool-call-input-preview,
787
+ .session-export-document-root .rules-message-summary,
788
+ .session-export-document-root .task-tool-summary-text,
789
+ .session-export-document-root .task-tool-item-title,
790
+ .session-export-document-root .task-tool-item-detail,
791
+ .session-export-document-root .task-tool-item-status,
792
+ .session-export-document-root .assistant-capability-heading-main strong,
793
+ .session-export-document-root .assistant-capability-summary,
794
+ .session-export-document-root .assistant-capability-row-label,
795
+ .session-export-document-root .assistant-capability-row-value,
796
+ .session-export-document-root .apply-patch-summary-file,
797
+ .session-export-document-root .apply-patch-summary-stats,
798
+ .session-export-document-root .session-title,
799
+ .session-export-document-root .message-text,
800
+ .session-export-document-root .markdown-content,
801
+ .session-export-document-root .thinking-message-text,
802
+ .session-export-document-root .thinking-message-text :where(p, li, blockquote, strong, em, a, span),
803
+ .session-export-document-root .thinking-message-label,
804
+ .session-export-document-root .thinking-status-text {
805
+ white-space: normal !important;
806
+ overflow: visible !important;
807
+ text-overflow: clip !important;
808
+ word-break: break-word !important;
809
+ overflow-wrap: anywhere !important;
810
+ }
811
+
812
+ .session-export-document-root .assistant-capability-summary {
813
+ display: inline !important;
814
+ }
815
+
816
+ .session-export-document-root .task-tool-list {
817
+ list-style: decimal !important;
818
+ padding-left: 24px !important;
819
+ }
820
+
821
+ .session-export-document-root .message-timeline-export .conversation-scroll-to-bottom-button,
822
+ .session-export-document-root .message-timeline-export .message-metadata-bar,
823
+ .session-export-document-root .message-timeline-export .retry-button,
824
+ .session-export-document-root .message-timeline-export .code-copy-button,
825
+ .session-export-document-root .message-timeline-export .rules-message-action,
826
+ .session-export-document-root .message-timeline-export .message-origin-detail-popover {
827
+ display: none !important;
828
+ }
829
+
830
+ .session-export-document-root .message-item,
831
+ .session-export-document-root .tool-message-row,
832
+ .session-export-document-root .rules-message-row {
833
+ break-inside: avoid;
834
+ page-break-inside: avoid;
835
+ }
836
+ }
837
+ `;async function mx(){await new Promise(e=>{window.requestAnimationFrame(()=>e())})}function Mp(e){return new Promise(t=>{window.setTimeout(t,e)})}async function bH(e,t){const n=e.fonts;!n||typeof n.ready>"u"||await Promise.race([n.ready.catch(()=>{}),Mp(t)])}function yH(e){return e.complete?Promise.resolve():new Promise(t=>{const n=()=>{e.removeEventListener("load",r),e.removeEventListener("error",r)},r=()=>{n(),t()};e.addEventListener("load",r,{once:!0}),e.addEventListener("error",r,{once:!0})})}async function xH(e,t){const n=Array.from(e.querySelectorAll("img"));n.length!==0&&await Promise.race([Promise.all(n.map(r=>yH(r))),Mp(t)])}async function kH(e,t=document){await mx(),await mx(),await Mp(420),await bH(t,1800),e&&await xH(e,1800)}function wH(){if(typeof document>"u")return"";const e=[];for(const t of Array.from(document.styleSheets))try{const n=t.cssRules;if(!n||n.length===0)continue;e.push(Array.from(n).map(r=>r.cssText).join(`
838
+ `))}catch{continue}return e.join(`
839
+ `)}function px(e){const t={};for(const n of Array.from(e.attributes))n.name!=="style"&&(t[n.name]=n.value);return t}function vH(){if(typeof document>"u")return{shellWidthPx:null};const e=[".affairs-conversation-timeline-shell",".conversation-timeline-shell",".affairs-conversation-main",".conversation-main",".conversation-panel"];for(const t of e){const n=document.querySelector(t);if(!(n instanceof HTMLElement))continue;const r=n.getBoundingClientRect();if(!(!Number.isFinite(r.width)||r.width<=0))return{shellWidthPx:Math.round(r.width)}}return{shellWidthPx:null}}function SH({target:e,value:t,busySessionId:n,onChange:r,onClose:i,onSubmit:o}){return s.jsx(ln,{open:e!==null,title:a("shell.renameModalTitle"),description:a("shell.renameModalDescription"),onClose:i,children:s.jsxs("form",{className:"workbench-rename-form",onSubmit:o,children:[s.jsx(Ot,{label:a("shell.renameInputLabel"),htmlFor:"affairs-conversation-rename-input",children:s.jsx("input",{id:"affairs-conversation-rename-input",type:"text",value:t,placeholder:a("shell.renameInputPlaceholder"),maxLength:120,autoFocus:!0,onChange:l=>r(l.target.value)})}),s.jsxs(Es,{children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:!!n,onClick:i,children:a("common.cancel")}),s.jsx("button",{type:"submit",className:"primary-button",disabled:!t.trim()||n===(e==null?void 0:e.session.sessionId),children:n===(e==null?void 0:e.session.sessionId)?a("shell.renamingSession"):a("common.save")})]})]})})}function CH({target:e,busySessionId:t,onClose:n,onConfirm:r}){return s.jsxs(ln,{open:e!==null,title:a("shell.deleteSessionConfirmTitle"),description:a("shell.deleteSessionConfirmDescription"),onClose:n,children:[s.jsx(Jn,{children:e?s.jsx("p",{children:e.session.title||a("conversation.titleFallback")}):null}),s.jsxs(Es,{children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:!!t,onClick:n,children:a("common.cancel")}),s.jsx("button",{type:"button",className:"workbench-danger-button",disabled:t===(e==null?void 0:e.session.sessionId),onClick:()=>{r()},children:t===(e==null?void 0:e.session.sessionId)?a("common.loading"):a("shell.deleteSessionAction")})]})]})}function jH(){const{binding:e,conversationCreateModalOpen:t,conversationCreateModalMode:n,closeConversationCreateModal:r,agentWorkspacePath:i,workspaceName:o}=Qn(),l=d.useMemo(()=>wq({rootDir:(e==null?void 0:e.rootDir)??null,mirrorRoot:(e==null?void 0:e.mirrorRoot)??null,agentWorkspacePath:i,workspaceName:o}),[i,e==null?void 0:e.mirrorRoot,e==null?void 0:e.rootDir,o]);return s.jsxs(ln,{open:t,title:a("shell.createSessionModalTitle"),description:l?a("shell.affairsConversationCreateModalDescriptionWithWorkspace",{workspace:l}):a("shell.affairsConversationCreateModalDescription"),className:"workbench-create-session-modal affairs-conversation-create-modal",onClose:r,children:[n!=="agent-only"?s.jsx(hx,{kind:"lightweight",title:a("shell.affairsConversationLightweightTitle"),description:a("shell.affairsConversationLightweightDescription"),providers:nH}):null,s.jsx(hx,{kind:"agent",title:a("shell.affairsConversationAssistantTitle"),description:a("shell.affairsConversationAssistantDescription"),providers:sH})]})}function Df(){const{openConversationCreateModal:e,selectedConversationDraft:t}=Qn(),n=[{title:a("shell.affairsConversationEmptyCreateTitle"),body:a("shell.affairsConversationEmptyCreateBody")},t?{title:a("shell.affairsConversationEmptySelectedTitle"),body:Sq(t)}:{title:a("shell.affairsConversationEmptyModeTitle"),body:a("shell.affairsConversationEmptyModeBody")},{title:a("shell.affairsConversationEmptyCompanionTitle"),body:a("shell.affairsConversationEmptyCompanionBody")}];return s.jsx("div",{className:"affairs-conversation-empty-state",children:s.jsxs("section",{className:"workbench-empty-guide surface-card affairs-conversation-empty-guide",children:[s.jsx("p",{className:"workbench-empty-eyebrow",children:a("shell.affairsConversationEmptyEyebrow")}),s.jsx("div",{className:"workbench-empty-main affairs-conversation-empty-main",children:s.jsxs("div",{className:"workbench-empty-copy affairs-conversation-empty-copy",children:[s.jsx("h1",{children:a("shell.affairsConversationStageTitle")}),s.jsx("p",{className:"workbench-empty-body",children:a("shell.affairsConversationEmptyBody")}),s.jsx("div",{className:"affairs-conversation-empty-actions",children:s.jsx(Pj,{onClick:e})})]})}),s.jsx("ol",{className:"workbench-empty-steps affairs-conversation-empty-steps",children:n.map((r,i)=>s.jsxs("li",{className:"workbench-empty-step",children:[s.jsx("span",{className:"workbench-empty-step-index",children:i+1}),s.jsxs("div",{className:"workbench-empty-step-copy",children:[s.jsx("h2",{children:r.title}),s.jsx("p",{children:r.body})]})]},r.title))}),s.jsx("p",{className:"workbench-empty-tip",children:a("shell.affairsConversationEmptyTip")})]})})}function NH(){return s.jsx("div",{className:"affairs-conversation-empty-state",children:s.jsxs("header",{className:"affairs-conversation-empty-header",children:[s.jsx("span",{className:"affairs-inline-pill",children:a("shell.workbenchModeAffairs")}),s.jsx("h2",{children:a("shell.affairsConnectionCheckingTitle")}),s.jsx("p",{children:a("shell.affairsConnectionCheckingDescription")})]})})}function TH(e){const{activateConversationSession:t,reloadLightweightConversationSessions:n,lightweightRuntimeBySessionId:r,setLightweightRuntimeSnapshot:i}=Qn(),o=d.useMemo(()=>Ej(e.draft.provider),[e.draft.provider]),l=d.useMemo(()=>cN(e.workspaceId,e.draft),[e.draft,e.workspaceId]),c=r[l.sessionId]??Ms({session:l,historyState:"ready"});return s.jsx("main",{className:"workbench-page conversation-page-shell affairs-conversation-page-shell","data-affairs-section":"conversation",children:s.jsxs("div",{className:"conversation-main affairs-conversation-main",children:[s.jsx(Tp,{session:l}),s.jsx(Dj,{status:c.streamingToolStatus}),s.jsx("div",{className:"conversation-timeline-shell affairs-conversation-timeline-shell",children:s.jsx(td,{sessionId:l.sessionId,sessionSummary:l,workspaceId:l.workspaceId,workspacePath:null,items:bo({messages:c.messages}),historyState:c.historyState,provider:e.draft.provider,onRetryMessage:()=>{}})}),s.jsx(id,{capabilities:o,draftStorageId:Lu(e.draft),workspaceId:e.workspaceId,contextUsage:null,taskProvider:e.draft.provider,taskMessages:c.messages,isSubmitting:c.sending,isRunning:!1,onSend:async(u,f)=>{const h=uN(),m=[...c.messages,zS(l.sessionId,u,h,(f==null?void 0:f.attachmentMeta)??[],(f==null?void 0:f.attachments)??[]),Ep(l.sessionId,h)];i(l.sessionId,Ms({session:l,messages:m,historyState:"ready",sending:!0,streamingToolStatus:null}));let g=null;try{const p=await T0(e.workspaceId,{provider:e.draft.provider,content:u,clientRequestId:h,model:(f==null?void 0:f.model)??null,reasoningLevel:(f==null?void 0:f.reasoningLevel)??null},y=>{if(y.type==="started"){g=y.session.sessionId;const k=m.map(C=>({...C,sessionId:y.session.sessionId}));i(y.session.sessionId,Ms({session:y.session,messages:k,historyState:"ready",sending:!0,streamingToolStatus:null})),i(l.sessionId,null),t({kind:"lightweight",session:y.session,bootstrapMessages:[]}),n();return}const x=PH({fallbackSessionId:l.sessionId,activeSessionId:g,eventSessionId:null});if(y.type==="delta"){i(x,k=>{const C=k??Ms({session:x===l.sessionId?l:null,historyState:"ready"});return{...C,messages:_j(C.messages,x,h,y.delta)}});return}y.type==="tool"&&i(x,k=>{const C=k??Ms({session:x===l.sessionId?l:null,historyState:"ready"});return{...C,messages:Fj(C.messages,{sessionId:x,toolCallId:y.toolCallId,toolName:y.toolName,status:y.status,detail:y.detail??null,toolInput:y.input??null,toolOutput:y.output??null}),streamingToolStatus:Oj(y.toolName,y.detail??null,y.status)}})}),b=p.session;i(b.sessionId,y=>{var x;return Ms({session:b,messages:p.messages.length>0?p.messages.map(k=>ol(k,b.sessionId)):(y==null?void 0:y.messages)??((x=r[b.sessionId])==null?void 0:x.messages)??m.map(k=>({...k,sessionId:b.sessionId})),historyState:"ready",sending:!1,streamingToolStatus:null})}),await n(),t({kind:"lightweight",session:b,bootstrapMessages:p.messages})}catch(p){const b=g??l.sessionId;throw i(b,y=>{const x=y??Ms({session:b===l.sessionId?l:null,historyState:"ready"});return{...x,messages:HS(x.messages,h),sending:!1,streamingToolStatus:x.streamingToolStatus?{...x.streamingToolStatus,phase:"failed"}:null}}),p}finally{const p=g??l.sessionId;i(p,b=>b&&{...b,sending:!1})}}})]})})}function IH(e){var r,i,o,l,c,u;const t=AH({sessionId:e.sessionId,externalSession:((r=e.runtimeSeed)==null?void 0:r.session.sessionId)===e.sessionId?e.runtimeSeed.session:null,bootstrapMessages:((i=e.runtimeSeed)==null?void 0:i.session.sessionId)===e.sessionId?e.runtimeSeed.bootstrapMessages:[]}),n=t.session;return s.jsx("main",{className:"workbench-page conversation-page-shell affairs-conversation-page-shell","data-affairs-section":"conversation",children:s.jsxs("div",{className:"conversation-main affairs-conversation-main",children:[s.jsx(Tp,{session:n}),s.jsx(Dj,{status:t.streamingToolStatus}),s.jsx(Np,{requests:t.permissionRequests,replyingRequestId:t.replyingPermissionRequestId,onReply:t.replyPermissionRequest}),s.jsx("div",{className:"conversation-timeline-shell affairs-conversation-timeline-shell",children:s.jsx(td,{sessionId:e.sessionId,sessionSummary:n,workspaceId:(n==null?void 0:n.workspaceId)??((o=e.runtimeSeed)==null?void 0:o.session.workspaceId)??null,workspacePath:null,items:t.timelineItems,historyState:t.historyState,loadingOlderMessages:t.loadingOlderMessages,hasOlderMessages:t.hasOlderMessages,provider:(n==null?void 0:n.provider)??((l=e.runtimeSeed)==null?void 0:l.session.provider)??null,interruptedSource:t.runtimeInterruptSource,onLoadOlderMessages:t.loadOlderMessages,onRetryMessage:t.retryMessage})}),s.jsx(id,{capabilities:t.capabilities,draftStorageId:e.sessionId,workspaceId:(n==null?void 0:n.workspaceId)??((c=e.runtimeSeed)==null?void 0:c.session.workspaceId)??null,initialProviderConfigMode:"global-default",initialProviderPresetId:null,hasActiveRun:!1,canInterrupt:!1,contextUsage:null,taskProvider:(n==null?void 0:n.provider)??((u=e.runtimeSeed)==null?void 0:u.session.provider)??null,taskMessages:t.messages,isSubmitting:t.sending,isRunning:!1,onSend:t.send})]})})}function AH(e){var h;const{workspaceId:t,reloadLightweightConversationSessions:n,lightweightRuntimeBySessionId:r,setLightweightRuntimeSnapshot:i}=Qn(),o=r[e.sessionId]??null,l=d.useMemo(()=>e.bootstrapMessages.map(m=>ol(m,e.sessionId)),[e.bootstrapMessages,e.sessionId]);d.useEffect(()=>{if(!o&&e.externalSession){i(e.sessionId,Ms({session:e.externalSession,messages:l,historyState:e.bootstrapMessages.length>0?"ready":"loading",sending:!1,streamingToolStatus:null}));return}if(!e.externalSession)return;const m=e.externalSession;i(e.sessionId,g=>{var p;return!g||((p=g.session)==null?void 0:p.sessionId)===m.sessionId?g:{...g,session:m}})},[l,e.bootstrapMessages.length,e.externalSession,e.sessionId,o,i]),d.useEffect(()=>{e.bootstrapMessages.length!==0&&i(e.sessionId,m=>{const g=m??Ms({session:e.externalSession,historyState:"ready"});return g.messages.length>0?g:{...g,messages:l,historyState:"ready"}})},[l,e.bootstrapMessages.length,e.externalSession,e.sessionId,i]),d.useEffect(()=>{let m=!1;return Promise.all([S0(t,e.sessionId),cw(t,e.sessionId)]).then(([g,p])=>{m||i(e.sessionId,b=>{const y=p.messages.map(C=>ol(C,e.sessionId)),x=y.length>0?y:(b==null?void 0:b.messages)??[],k=((b==null?void 0:b.sending)??!1)||x.some(C=>{var j;return((j=C.toolCall)==null?void 0:j.status)==="running"});return{...b??Ms(),session:g,messages:x,historyState:"ready",sending:(b==null?void 0:b.sending)??!1,streamingToolStatus:k?(b==null?void 0:b.streamingToolStatus)??null:null}})}).catch(()=>{m||i(e.sessionId,g=>({...g??Ms(),historyState:"ready"}))}),()=>{m=!0}},[e.sessionId,i,t]);const c=o??Ms({session:e.externalSession,messages:l,historyState:e.bootstrapMessages.length>0?"ready":"loading"}),u=c.session??e.externalSession,f=c.messages;return{session:u,messages:f,timelineItems:bo({messages:f}),historyState:c.historyState,sending:c.sending,streamingToolStatus:c.streamingToolStatus,capabilities:Ej((u==null?void 0:u.provider)??((h=e.externalSession)==null?void 0:h.provider)??"codex"),send:async(m,g)=>{const p=(g==null?void 0:g.clientRequestId)??uN(),b=[...f,zS(e.sessionId,m,p,(g==null?void 0:g.attachmentMeta)??[],[]),Ep(e.sessionId,p)];i(e.sessionId,y=>({...y??Ms({session:u}),session:(y==null?void 0:y.session)??u,messages:b,historyState:"ready",sending:!0,streamingToolStatus:null}));try{const y=await I0(t,e.sessionId,{content:m,clientRequestId:p,model:(g==null?void 0:g.model)??null,reasoningLevel:(g==null?void 0:g.reasoningLevel)??null},x=>{if(x.type==="started"){i(e.sessionId,k=>({...k??Ms(),session:x.session,messages:(k==null?void 0:k.messages)??b,historyState:"ready",sending:!0,streamingToolStatus:(k==null?void 0:k.streamingToolStatus)??null}));return}if(x.type==="delta"){i(e.sessionId,k=>{const C=k??Ms({session:u,historyState:"ready"});return{...C,messages:_j(C.messages,e.sessionId,p,x.delta)}});return}x.type==="tool"&&i(e.sessionId,k=>{const C=k??Ms({session:u,historyState:"ready"});return{...C,messages:Fj(C.messages,{sessionId:e.sessionId,toolCallId:x.toolCallId,toolName:x.toolName,status:x.status,detail:x.detail??null,toolInput:x.input??null,toolOutput:x.output??null}),streamingToolStatus:Oj(x.toolName,x.detail??null,x.status)}})});i(e.sessionId,x=>{const k=y.messages.map(C=>ol(C,e.sessionId));return Ms({session:y.session,messages:k.length>0?k:(x==null?void 0:x.messages)??[],historyState:"ready",sending:!1,streamingToolStatus:null})}),await n()}catch(y){throw i(e.sessionId,x=>{const k=x??Ms({session:u,historyState:"ready"});return{...k,messages:HS(k.messages,p),sending:!1,streamingToolStatus:k.streamingToolStatus?{...k.streamingToolStatus,phase:"failed"}:null}}),y}},retryMessage:()=>{},loadingOlderMessages:!1,hasOlderMessages:!1,permissionRequests:[],replyingPermissionRequestId:null,replyPermissionRequest:async()=>{},runtimeInterruptSource:null,loadOlderMessages:async()=>{}}}function gx(e){var he;const{activateConversationSession:t,assistantContext:n,butlerStore:r,reloadAgentConversationSessions:i,agentProjectId:o,agentConversationSessions:l}=Qn(),c=Zt(r,X=>X.initialized),u=Zt(r,X=>X.loading),f=Zt(r,X=>X.profile),h=Zt(r,X=>X.activeProvider),m=Zt(r,X=>X.controlSession),g=Zt(r,X=>X.capabilities),p=Zt(r,X=>X.messages),b=Zt(r,X=>X.historyState),y=Zt(r,X=>X.loadingOlderMessages),x=Zt(r,X=>X.hasOlderMessages),k=Zt(r,X=>X.runtimeHasActiveRun),C=Zt(r,X=>X.runtimeCanInterrupt),j=Zt(r,X=>X.contextUsage),H=Zt(r,X=>X.permissionRequests),_=Zt(r,X=>X.sending),[T,P]=d.useState(null),z=((he=e.draft)==null?void 0:he.provider)??null,L=hd(m,e.workspaceId)?m:null,R=(L==null?void 0:L.session.provider)??z??h,K=d.useMemo(()=>Lj(R??"codex"),[R]),E=d.useMemo(()=>e.draft?cN(e.workspaceId,e.draft):null,[e.draft,e.workspaceId]),[D,te]=d.useState(null),V=d.useRef(null),ee=d.useMemo(()=>e.sessionId?l.find(X=>X.sessionId===e.sessionId)??null:null,[l,e.sessionId]),U=d.useMemo(()=>L!=null&&L.session&&(!e.sessionId||L.session.sessionId===e.sessionId)?L.session:ee||E,[ee,E,e.sessionId,L==null?void 0:L.session]);return d.useEffect(()=>{if(!e.sessionId||e.draft){V.current=null;return}const X=e.sessionId;if((L==null?void 0:L.session.sessionId)===X){V.current=X,D===X&&te(null);return}if(V.current===X)return;if(!ee||ee.isArchived){V.current=X,D===X&&te(null);return}const I=Rj((ee==null?void 0:ee.rawStoreRef)??null);if(!o||!I)return;let xe=!1;return te(X),(async()=>{try{const le=await eS(o,I);if(xe)return;const M=await Ch();if(xe)return;const de=M.items.find(Ne=>Ne.session.sessionId===le.resumed.session.sessionId)??null;V.current=X,await r.openControlSession((de==null?void 0:de.id)??""),t({kind:"agent",session:oq(le.resumed.session,(ee==null?void 0:ee.workspaceId)??e.workspaceId),bootstrapMessages:[]})}catch{if(xe)return;V.current=X}finally{xe||te(null)}})(),()=>{xe=!0}},[t,o,r,ee==null?void 0:ee.isArchived,ee==null?void 0:ee.rawStoreRef,ee==null?void 0:ee.workspaceId,L==null?void 0:L.session.sessionId,e.draft,e.sessionId,e.workspaceId,D]),s.jsx("main",{className:"workbench-page conversation-page-shell affairs-conversation-page-shell","data-affairs-section":"conversation",children:s.jsxs("div",{className:"conversation-main affairs-conversation-main",children:[s.jsx(Tp,{session:U}),s.jsx(Np,{requests:H,replyingRequestId:T,onReply:async(X,I)=>{P(X);try{await r.replyPermissionRequest(X,I)}finally{P(null)}}}),s.jsx("div",{className:"conversation-timeline-shell affairs-conversation-timeline-shell",children:s.jsx(td,{sessionId:(L==null?void 0:L.session.sessionId)??e.sessionId??(E==null?void 0:E.sessionId),sessionSummary:U,workspaceId:(U==null?void 0:U.workspaceId)??e.workspaceId,workspacePath:(f==null?void 0:f.workspacePath)??null,items:bo({messages:p}),historyState:b,loadingOlderMessages:y,hasOlderMessages:x,provider:R,onLoadOlderMessages:()=>{r.loadOlderMessages()},onRetryMessage:X=>{r.retryMessage(X)}})}),s.jsx(id,{capabilities:z&&h!==z?K:g??K,draftStorageId:e.sessionId??(E==null?void 0:E.sessionId)??`affairs-agent:${e.workspaceId}`,workspaceId:e.workspaceId,initialProviderConfigMode:"global-default",initialProviderPresetId:null,hasActiveRun:!!k||_,canInterrupt:C??!1,contextUsage:j,taskProvider:R,taskMessages:p,isSubmitting:_||u||!c||D===e.sessionId,isRunning:!!k||_||D===e.sessionId,onInterrupt:async()=>{await r.interrupt()},onSend:async(X,I)=>{var ye,Be;const xe=to(z)?z:h,le=((ye=r.getState().controlSession)==null?void 0:ye.session.sessionId)??null,M=!!xe&&h!==xe,de=!!e.draft&&!!le;xe&&M?await r.switchProvider(xe):de&&await r.startFreshSession(),await r.sendMessage(`${oN(n)}${X}`,{model:(I==null?void 0:I.model)??null,reasoningLevel:(I==null?void 0:I.reasoningLevel)??null,permissionMode:null}),await i();const Ne=((Be=r.getState().controlSession)==null?void 0:Be.session)??null;Ne&&t({kind:"agent",session:Ne,bootstrapMessages:[]})}})]})})}function to(e){return e==="codex"||e==="claude-code"}function Ej(e){return{provider:e,canStartSession:!0,canResumeSession:!0,canSendMessage:!0,inRunInputMode:"none",supportsSubagents:!1,supportsInterrupt:!1,supportsStructuredToolCalls:!1,supportsTokenUsage:!1,supportsAttachments:!1,supportsPermissionPrompt:!1,supportsCheckpoint:!1,supportsSlashMenu:!1,supportsReasoningSelector:!1,supportsRunSteering:!1,supportsQueueWhileRunning:!1,limitations:[a("shell.affairsConversationLightweightCapabilityHint")]}}function Lj(e){return{provider:e,canStartSession:!0,canResumeSession:!0,canSendMessage:!0,inRunInputMode:e==="claude-code"?"streaming_guidance":"none",supportsSubagents:!1,supportsInterrupt:!0,supportsStructuredToolCalls:!0,supportsTokenUsage:!0,supportsAttachments:!1,supportsPermissionPrompt:!0,supportsCheckpoint:!1,supportsSlashMenu:!1,supportsReasoningSelector:!1,supportsRunSteering:!1,supportsQueueWhileRunning:!1,limitations:[]}}function ol(e,t){return{id:e.messageId,sessionId:t,role:e.role,kind:e.kind??"text",content:e.content,toolCall:e.toolCall??null,attachments:e.attachments,attachmentPayloads:null,origin:e.origin??null,originRef:e.originRef??null,timestamp:e.timestamp,sequence:e.sequence,rawRef:e.rawRef,deliveryState:"sent",clientRequestId:null}}async function RH(e,t){return{messages:(await cw(e,t)).messages.map(r=>ol(r,t))}}function Ep(e,t){return{id:`lightweight-streaming-assistant-${t}`,sessionId:e,role:"assistant",kind:"text",content:"",toolCall:null,attachments:[],attachmentPayloads:null,origin:null,originRef:null,timestamp:new Date().toISOString(),sequence:Number.MAX_SAFE_INTEGER,rawRef:`pending://assistant/${t}`,deliveryState:"sending",clientRequestId:t}}function Dj({status:e}){var t;return e?s.jsxs("div",{className:"affairs-lightweight-status-bar",role:"status","aria-live":"polite","data-phase":e.phase,children:[s.jsx("span",{className:"affairs-lightweight-status-dot","aria-hidden":"true"}),s.jsx("span",{className:"affairs-lightweight-status-label",children:e.label}),(t=e.detail)!=null&&t.trim()?s.jsx("span",{className:"affairs-lightweight-status-detail",children:e.detail.trim()}):null]}):null}function Ms(e){return{session:(e==null?void 0:e.session)??null,messages:(e==null?void 0:e.messages)??[],historyState:(e==null?void 0:e.historyState)??"loading",sending:(e==null?void 0:e.sending)??!1,streamingToolStatus:(e==null?void 0:e.streamingToolStatus)??null}}function Oj(e,t,n){return{label:e==="web_search"?a("conversation.toolWebSearch"):e,detail:t,phase:n==="completed"?"completed":n==="failed"?"failed":"running"}}function PH(e){var t;return((t=e.activeSessionId)==null?void 0:t.trim())||e.fallbackSessionId}function Fj(e,t){var f,h,m,g;const n=`lightweight-tool-${t.toolCallId}`,r=e.findIndex(p=>p.id.startsWith("lightweight-streaming-assistant-")),i=r>=0?r:e.length,o=i>0?((f=e[i-1])==null?void 0:f.sequence)??0:0,l={id:n,sessionId:t.sessionId,role:"tool",kind:t.status==="running"?"tool_call":"tool_result",content:((h=t.detail)==null?void 0:h.trim())||((m=t.toolOutput)==null?void 0:m.trim())||((g=t.toolInput)==null?void 0:g.trim())||t.toolName,toolCall:{callId:t.toolCallId,name:t.toolName,input:t.toolInput??"",output:t.toolOutput,error:t.status==="failed"?t.detail??t.toolOutput??null:null,status:t.status},attachments:[],attachmentPayloads:null,origin:null,originRef:null,timestamp:new Date().toISOString(),sequence:o+1,rawRef:`lightweight-tool://${t.toolCallId}`,deliveryState:"sent",clientRequestId:null},c=e.findIndex(p=>{var b;return((b=p.toolCall)==null?void 0:b.callId)===t.toolCallId||p.id===n});if(c<0)return[...e.slice(0,i),l,...e.slice(i).map(p=>({...p,sequence:p.sequence>=l.sequence?p.sequence+1:p.sequence}))];const u=[...e];return u[c]={...u[c],...l,timestamp:u[c].timestamp,sequence:u[c].sequence,rawRef:u[c].rawRef},u}function _j(e,t,n,r){if(!r)return e;const i=`lightweight-streaming-assistant-${n}`;let o=!1;const l=e.map(c=>c.id!==i?c:(o=!0,{...c,content:`${c.content}${r}`}));return o?l:[...e,{...Ep(t,n),content:r}]}function MH({errorMessage:e,retrying:t,onRetry:n}){return s.jsxs("div",{className:"affairs-conversation-empty-state",children:[s.jsxs("header",{className:"affairs-conversation-empty-header",children:[s.jsx("span",{className:"affairs-inline-pill",children:a("shell.workbenchModeAffairs")}),s.jsx("h2",{children:a("shell.affairsHostUnavailableTitle")}),s.jsx("p",{children:a("shell.affairsHostUnavailableDescription")})]}),s.jsxs("section",{className:"affairs-conversation-empty-section affairs-conversation-create-section",children:[s.jsx("button",{type:"button",className:"secondary-button affairs-conversation-create-trigger",onClick:()=>{n()},disabled:t,children:s.jsx("span",{children:t?a("common.loading"):a("shell.affairsHostUnavailableRetryAction")})}),s.jsx("p",{children:a("shell.affairsHostUnavailableRetryHint")})]}),e!=null&&e.trim()?s.jsx("section",{className:"affairs-conversation-empty-section",children:s.jsxs("div",{className:"affairs-conversation-empty-section-header",children:[s.jsx("strong",{children:a("shell.affairsHostUnavailableErrorTitle")}),s.jsx("p",{children:e.trim()})]})}):null]})}function EH(e){const t=e.tone==="friendly"?["🐼","🦊","🐶","🌼"]:e.tone==="steady"?["🐢","🪨","🌲","🧭"]:e.providerId==="claude-code"?["🦉","📚","🔍","🧪"]:["🧠","🤖","🛠️","⚡"],n=`${e.displayName.trim()}:${e.providerId}:${e.tone}`;if(!n)return t[0];const r=Array.from(n).reduce((i,o)=>i+(o.codePointAt(0)??0),0);return t[r%t.length]}const LH={"risk-first":["risk","blocker","verification"],"blocker-first":["blocker","risk","verification"],"verification-first":["verification","risk","blocker"],"progress-first":["progress","risk","blocker"]};function DH({workspaceId:e}){var te;const{initGuard:t,initializeButlerProfile:n,updateButlerProfile:r,openInitializedSection:i,reloadButlerProfile:o,selectedConversationDraft:l,selectedConversationSession:c,conversationRuntimeSeed:u,agentWorkspaceId:f,agentWorkspacePath:h}=Qn(),m=t.initialized,g=t.loading,p=t.unavailable,b=t.butlerInitialized,y=t.profile,[x,k]=d.useState(XB),[C,j]=d.useState(!1),[H,_]=d.useState(!1),[T,P]=d.useState(!1),[z,L]=d.useState({enabled:!0,rootDir:""}),{showToast:R}=Vn(),K=((te=y==null?void 0:y.displayName)==null?void 0:te.trim())||x.displayName.trim()||a("shell.butlerEntry"),E=d.useMemo(()=>EH({displayName:K,providerId:(y==null?void 0:y.providerId)??x.providerId,tone:(y==null?void 0:y.personaTone)??x.personaTone}),[K,x.personaTone,x.providerId,y==null?void 0:y.personaTone,y==null?void 0:y.providerId]);if(d.useEffect(()=>{m||tw().then(V=>{L({enabled:(V==null?void 0:V.enabled)??!0,rootDir:(V==null?void 0:V.rootDir)??""})}).catch(()=>{})},[m,e]),d.useEffect(()=>{y&&k(V=>({...V,displayName:V.displayName.trim()?V.displayName:y.displayName,providerId:y.providerId,personaTone:y.personaTone}))},[y]),d.useEffect(()=>{!m||!T||(i("library"),P(!1))},[m,i,T]),m)return(c==null?void 0:c.kind)==="lightweight"?s.jsx(IH,{sessionId:c.sessionId,runtimeSeed:(u==null?void 0:u.kind)==="lightweight"&&u.session.sessionId===c.sessionId?u:null}):(c==null?void 0:c.kind)==="agent"?f?s.jsx(gx,{workspaceId:f,sessionId:c.sessionId}):s.jsx(Df,{}):(l==null?void 0:l.kind)==="lightweight"?s.jsx(TH,{workspaceId:e,draft:l}):(l==null?void 0:l.kind)==="agent"?f?s.jsx(gx,{workspaceId:f,draft:l}):s.jsx(Df,{}):s.jsx(Df,{});if(g)return s.jsx("main",{className:"workbench-page butler-page-shell butler-init-shell affairs-conversation-page-shell",children:s.jsx(NH,{})});if(p)return s.jsx("main",{className:"workbench-page butler-page-shell butler-init-shell affairs-conversation-page-shell",children:s.jsx(MH,{errorMessage:t.errorMessage,retrying:H,onRetry:async()=>{_(!0);try{await o()}finally{_(!1)}}})});async function D(V){var he;V.preventDefault();const ee=x.displayName.trim()||((he=y==null?void 0:y.displayName)==null?void 0:he.trim())||"";if(!ee){R({title:a("shell.butlerInitNameRequired"),tone:"warning"});return}if(z.enabled&&!z.rootDir.trim()){R({title:a("shell.affairsInitLibraryPathRequired"),tone:"warning"});return}const U={displayName:ee,providerId:x.providerId,agentsMode:x.agentsMode,persona:{tone:x.personaTone,language:x.personaLanguage,summaryStyle:x.personaSummaryStyle},focus:{projectIds:[],riskPreference:x.focusRiskPreference,reportPriority:LH[x.reportPriorityPreset],summaryDebounceSeconds:300}};j(!0);try{b?await r(U):await n(U),z.rootDir.trim()&&(await nw({rootDir:z.rootDir.trim()}),await sw({enabled:z.enabled})),await o(),P(!0),R({title:a("shell.affairsInitSuccess"),tone:"success"})}catch(X){R({title:a("shell.affairsInitFailed"),description:X instanceof Error?X.message:void 0,tone:"error"})}finally{j(!1)}}return s.jsx("main",{className:"workbench-page butler-page-shell butler-init-shell affairs-conversation-page-shell",children:s.jsxs("section",{className:"affairs-init-panel",children:[s.jsx("header",{className:"affairs-init-panel-header",children:s.jsxs("div",{children:[s.jsx("span",{className:"affairs-inline-pill",children:a("shell.workbenchModeAffairs")}),s.jsx("h2",{children:a("shell.butlerInitTitle")}),s.jsx("p",{children:a("shell.affairsInitRouteGuardHint")})]})}),s.jsx(QB,{form:x,onChange:k,submitting:g||C,submitLabel:g||C?a("shell.butlerInitSubmitting"):a("shell.affairsInitSubmit"),previewName:K,previewAvatar:E,previewRuleLabel:a("shell.affairsInitPreviewRuleLabel"),affairsLibrary:{value:z,onChange:L},onSubmit:D})]})})}function OH({workspaceId:e}){const{activeSection:t,initGuard:n,binding:r,documentRecords:i,favoriteEntries:o,filteredDocuments:l,filteredTodoRecords:c,automationRecords:u,folderRecords:f,tagRecords:h,indexStatus:m,libraryConfig:g,currentDirectoryStatus:p,loading:b,openLibraryViewer:y,error:x,selectedObject:k,state:C,selectedTagPaths:j,managedTags:H,saveDocumentTagSelection:_,saveFolderTagSelection:T,documentTagDetails:P,folderTagDetails:z,recentTagTasks:L,selectObject:R,navigateLibraryFolder:K,navigateLibraryTag:E,libraryDocumentsLoading:D,libraryRefreshPending:te,libraryDocumentHasMore:V,loadMoreLibraryDocuments:ee,refreshLibrary:U,selectLibraryFolderEntry:he,setLibraryViewMode:X,selectSidebarNode:I}=Qn(),xe=d.useRef(null),[le,M]=d.useState(!1);d.useEffect(()=>{le&&t!=="library"&&M(!1)},[t,le]);const[de,Ne]=d.useState(0),[ye,Be]=d.useState(0),[We,Ce]=d.useState(0),[ke,we]=d.useState({mode:"recent",direction:"desc"}),[se,ce]=d.useState(Fa),[Y,Te]=d.useState(null),[pe,fe]=d.useState(null),[W,Me]=d.useState(null),je=d.useRef(null),[Q,ge]=d.useState(null),[Oe,$e]=d.useState(!1),[Ve,G]=d.useState(null),[ve,_e]=d.useState(null),[nt,et]=d.useState(!1),[ot,jt]=d.useState(null),Ft=d.useRef(null),bt=d.useRef(null),_t=d.useRef(null),{showToast:xt}=Vn(),rt=Hn(),It=d.useId(),$t=d.useMemo(()=>new Set(o.filter(O=>O.kind==="folder").map(O=>O.path)),[o]),pt=d.useMemo(()=>t==="library"?J6(f,C.selectedFolderPath):[],[t,f,C.selectedFolderPath]),Ie=d.useMemo(()=>t==="library"&&C.browseMode==="folder"?X6(i,C.selectedFolderPath):[],[t,i,C.browseMode,C.selectedFolderPath]),kt=d.useMemo(()=>t==="library"?Q6({browseMode:C.browseMode,childFolders:pt,documents:C.browseMode==="folder"?Ie:l,favoriteFolderPathSet:$t}):[],[t,pt,$t,l,Ie,C.browseMode]),St=d.useMemo(()=>U6(kt,ke),[kt,ke]),vt=d.useMemo(()=>Cz(St.length,ye,de,We),[St.length,de,ye,We]),Ct=d.useMemo(()=>St.slice(vt.startIndex,vt.endIndex),[vt.endIndex,vt.startIndex,St]),J=d.useMemo(()=>H6(St.length,de,We),[St.length,de,We]),Ue=d.useMemo(()=>St.slice(J.startIndex,J.endIndex),[St,J.endIndex,J.startIndex]),ze=Sz(St.length,ye,de),st=d.useMemo(()=>nq(C.selectedFolderPath),[C.selectedFolderPath]),q=d.useMemo(()=>Rq(se),[se]);d.useLayoutEffect(()=>{if(!Y||!_t.current||typeof window>"u")return;const O=_t.current.getBoundingClientRect(),Ae=dp({x:Y.left,y:Y.top},{width:O.width,height:O.height},{width:window.innerWidth,height:window.innerHeight},{defaultWidthPx:216,estimatedHeightPx:360,minHeightPx:180}),Xe=_t.current;Xe.style.left=`${Ae.left}px`,Xe.style.top=`${Ae.top}px`,Xe.style.width=`${Ae.width}px`,Xe.style.maxHeight=`${Ae.maxHeight}px`,Xe.style.transformOrigin=Ae.transformOrigin},[Y]),d.useEffect(()=>{if(!Y)return;const O=()=>Te(null),Ae=Xe=>{Xe.key==="Escape"&&O()};return window.addEventListener("pointerdown",O),window.addEventListener("scroll",O,!0),window.addEventListener("resize",O),window.addEventListener("keydown",Ae),()=>{window.removeEventListener("pointerdown",O),window.removeEventListener("scroll",O,!0),window.removeEventListener("resize",O),window.removeEventListener("keydown",Ae)}},[Y]),d.useEffect(()=>{Y||(Me(null),je.current!==null&&(window.clearTimeout(je.current),je.current=null))},[Y]),d.useEffect(()=>()=>{je.current!==null&&(window.clearTimeout(je.current),je.current=null)},[]),d.useLayoutEffect(()=>{const O=C.viewMode==="list"?bt.current:xe.current;if(!O)return;const Ae=()=>{Ne(O.clientHeight),Be(Ox(O))};if(Ae(),typeof ResizeObserver>"u")return;const Xe=new ResizeObserver(Ae);return Xe.observe(O),()=>Xe.disconnect()},[C.viewMode,t]),d.useEffect(()=>{const O=C.viewMode==="list"?bt.current:xe.current;if(!O)return;let Ae=0,Xe=0;const Qt=()=>{Ne(O.clientHeight),Be(Ox(O))};return Ae=window.requestAnimationFrame(Qt),Xe=window.setTimeout(Qt,80),()=>{window.cancelAnimationFrame(Ae),window.clearTimeout(Xe)}},[t,C.viewMode,St.length]),d.useEffect(()=>{const O=C.viewMode==="list"?bt.current:xe.current;if(!O||t!=="library")return;const Ae=()=>{if(Ce(O.scrollTop),!V||D)return;O.scrollHeight-O.scrollTop-O.clientHeight<=320&&ee()};return O.addEventListener("scroll",Ae,{passive:!0}),Ae(),()=>O.removeEventListener("scroll",Ae)},[t,V,D,ee,C.viewMode]),d.useEffect(()=>()=>{document.documentElement.removeAttribute("data-workbench-finder-column-resizing")},[]),d.useEffect(()=>{C.viewMode!=="list"&&document.documentElement.removeAttribute("data-workbench-finder-column-resizing")},[C.viewMode]);function re(O,Ae){Ae.preventDefault(),Ae.stopPropagation(),Ft.current={column:O,startX:Ae.clientX,startWidth:se[O]},document.documentElement.setAttribute("data-workbench-finder-column-resizing","true");const Xe=Ae.currentTarget;typeof Xe.setPointerCapture=="function"&&Xe.setPointerCapture(Ae.pointerId);const Qt=as=>{const tn=Ft.current;if(!tn||tn.column!==O||!Number.isFinite(as.clientX))return;const sn=as.clientX-tn.startX,At=Math.max(Oa[O],Math.round(tn.startWidth+sn));ce(Gt=>Gt[O]===At?Gt:{...Gt,[O]:At})},Un=()=>{Ft.current=null,document.documentElement.removeAttribute("data-workbench-finder-column-resizing"),window.removeEventListener("pointermove",Qt),window.removeEventListener("pointerup",Un),window.removeEventListener("pointercancel",Un)};window.addEventListener("pointermove",Qt),window.addEventListener("pointerup",Un),window.addEventListener("pointercancel",Un)}function ue(O){if(O.kind==="document"){const Ae=i.find(Xe=>Xe.id===O.documentId);return{kind:"document",entry:O,record:Ae??{id:O.documentId,title:O.title,displayName:O.title,filePath:O.path,fullPath:Mu((r==null?void 0:r.rootDir)??null,O.path),summary:O.summary,isFavorite:O.isFavorite,tags:[],derivedTags:[],createdAt:O.createdAt,sizeBytes:O.sizeBytes,updatedAt:O.updatedAt}}}return{kind:"folder",entry:O,record:f.find(Ae=>Ae.path===O.path)??null}}async function Re(O){const Ae=jU({target:O,bindingRootDir:(r==null?void 0:r.rootDir)??null,libraryClipboard:pe,onPreview:O.kind==="document"?()=>y(O.record):null,onOpen:O.kind==="document"||O.kind==="folder"?()=>Ze(O):null,onLocate:O.kind==="document"||O.kind==="folder"?()=>Ht(O):null,onDownload:O.kind==="document"?()=>He(O):null,onOpenWithLocalApp:rt.isDesktop&&rt.ui.osFamily==="macos"&&O.kind==="document"?()=>ft(O):null,onCopyFile:O.kind==="blank"?null:()=>it(Ks(O),a("shell.affairsLibraryCopyFileSuccess")),onCopyFileName:O.kind==="blank"?null:()=>it(Mc(O),a("shell.affairsLibraryCopyFileNameSuccess")),onCopyAbsolutePath:O.kind==="blank"?null:()=>{const Xe=Bf((r==null?void 0:r.rootDir)??null,O);if(!Xe)throw new Error(a("shell.affairsLibraryAbsolutePathMissing"));return it(Xe,a("shell.affairsLibraryCopyAbsolutePathSuccess"))},onCopyRelativePath:O.kind==="blank"?null:()=>it(Ks(O),a("shell.affairsLibraryCopyRelativePathSuccess")),onCut:O.kind==="document"||O.kind==="folder"?()=>{fe({mode:"cut",target:O}),xt({title:a("shell.affairsLibraryCutSuccess",{name:Mc(O)}),tone:"success"})}:null,onPaste:pe?()=>en(O):null,onDelete:O.kind==="document"||O.kind==="folder"?()=>cn(O):null,onCreateDirectory:()=>Bt(O,"directory"),onCreateMarkdownFile:()=>Bt(O,"markdown"),onCreateTextFile:()=>Bt(O,"text"),onCreateCustomFile:()=>Bt(O,"custom"),onRefresh:()=>U(),onOpenTagAssignment:O.kind==="document"||O.kind==="folder"?()=>Ws(O):null,onProperties:()=>{if(O.kind==="document"){R(O.record.id);return}R(null),gt(O.kind==="folder"?O.entry.path:C.selectedFolderPath)}});Ae.length!==0&&await dl(Ae)}function Se(O,Ae){if(O.preventDefault(),O.stopPropagation(),Ae.kind==="document"&&R(Ae.record.id),rt.isDesktop&&rt.ui.osFamily==="macos"&&rt.bridge.supported){Re(Ae);return}Te({left:O.clientX,top:O.clientY,target:Ae})}function Ke(O){O.target===O.currentTarget&&Se(O,{kind:"blank",folderPath:C.selectedFolderPath})}async function De(O){Te(null);try{await O()}catch(Ae){xt({title:Wf(Ae,a("shell.affairsLibraryActionFailed")),tone:"error"})}}async function He(O){const Ae=await YT(e,O.record.filePath),Xe=IU(Ae.contentBase64);AU(Ae.fileName,new Blob([Xe],{type:"application/octet-stream"})),xt({title:a("shell.affairsLibraryDownloadSuccess",{name:Ae.fileName}),tone:"success"})}function lt(){if(typeof window>"u"){Me(null);return}je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{Me(null),je.current=null},220)}function wt(O){je.current!==null&&(window.clearTimeout(je.current),je.current=null),Me(O)}async function it(O,Ae){await RU(O,rt),xt({title:Ae,tone:"success"})}async function Ze(O){if(O.kind==="document"&&!rt.isDesktop){await He(O);return}const Ae=Bf((r==null?void 0:r.rootDir)??null,O);if(!Ae)throw new Error(a("shell.affairsLibraryAbsolutePathMissing"));const Xe=await ha().fs.openFile(Ae);if(!Xe.ok)throw new Error(Xe.detail??a("shell.affairsLibraryOpenLocalFileFailed"))}function Ht(O){if(O.kind==="document"){K(_l(O.record.filePath)||null);return}K(O.entry.path||null)}function gt(O){he(O)}function Nt(O){K(O)}function dt(O){if(((g==null?void 0:g.folderOpenBehavior)==="single_click"?"single_click":"double_click")==="single_click"){Nt(O);return}gt(O)}async function ft(O){const Ae=Qh(g==null?void 0:g.mirrorRoot,O.record.filePath);if(!Ae)throw new Error(a("shell.affairsLibraryMirrorRootEmpty"));const Xe=await ha().fs.openFile(Ae.absolutePath);if(!Xe.ok)throw new Error(Xe.detail??a("shell.affairsLibraryOpenLocalFileFailed"))}async function en(O){if(!pe)return;const Ae=kx(O),Xe=Ks(pe.target),Qt=SU(Ae,Pu(Xe),kt);await Wa(e,{opType:pe.mode==="cut"?"move":"copy",srcPath:Xe,dstPath:Qt}),pe.mode==="cut"&&fe(null),await U(),xt({title:a("shell.affairsLibraryPasteSuccess",{name:Pu(Qt)}),tone:"success"})}function cn(O){Te(null),_e(O)}async function qt(O){var Ae;await Wa(e,{opType:"delete",srcPath:Ks(O)}),O.kind==="document"&&k.section==="library"&&((Ae=k.record)==null?void 0:Ae.id)===O.record.id&&R(null),await U(),xt({title:a("shell.affairsLibraryDeleteSuccess",{name:Mc(O)}),tone:"success"})}async function Cn(){if(ve){et(!0);try{await qt(ve),_e(null)}catch(O){xt({title:Wf(O,a("shell.affairsLibraryActionFailed")),tone:"error"})}finally{et(!1)}}}function Bt(O,Ae){Te(null),G(null),ge({folderPath:kx(O),kind:Ae,fileName:NU(Ae)})}async function is(){if(!Q||!r)return;const O=Q.fileName.trim();if(!O){G(a("shell.affairsLibraryCreateNameRequired"));return}const Ae=tu(Q.folderPath,O);$e(!0),G(null);try{if(Q.kind==="directory")if(rt.isDesktop){const Xe=Q.folderPath?Mu(r.rootDir,Q.folderPath):r.rootDir;if(!Xe)throw new Error(a("shell.affairsLibraryAbsolutePathMissing"));await iw({parentPath:Xe,directoryName:O})}else await Wa(e,{opType:"create_directory",dstPath:Ae});else await Wa(e,{opType:"create_file",dstPath:Ae,content:TU(Q.kind)});await U(),ge(null),xt({title:a("shell.affairsLibraryCreateSuccess",{name:O}),tone:"success"})}catch(Xe){G(Wf(Xe,a("shell.affairsLibraryCreateFailed")))}finally{$e(!1)}}async function Ws(O){if(Te(null),O.kind==="document"){const Qt=O.record.id===(P==null?void 0:P.documentId)?P:await nh(e,O.record.id);jt({kind:"document",title:O.record.displayName,documentId:O.record.id,existingTagIds:Qt.manualTagIds,resolvedTagPaths:Lp((Qt.resolvedTags??[]).map(Un=>Un.path))});return}const Ae=O.entry.path||".",Xe=(z==null?void 0:z.folderPath)===Ae?z:await sh(e,Ae);jt({kind:"folder",title:O.entry.title,folderPath:Ae,existingTagIds:Xe.bindingTagIds})}const fn=[{key:"name",label:a("shell.affairsFinderColumnName"),resizable:!0},{key:"size",label:a("shell.affairsFinderColumnSize"),resizable:!0},{key:"updatedAt",label:a("shell.affairsFinderColumnUpdatedAt"),resizable:!0},{key:"type",label:a("shell.affairsFinderColumnType"),resizable:!0},{key:"createdAt",label:a("shell.affairsFinderColumnCreatedAt"),resizable:!1}],mt=()=>{if(!Y)return null;const O=Y.target,Ae=O.kind==="blank"?null:O,Xe=!!pe,Qt=Ae?Ks(Ae):"",Un=Ae?Mc(Ae):"",as=Ae?Bf((r==null?void 0:r.rootDir)??null,Ae)??"":"",tn=O.kind==="document",sn=O.kind==="document"||O.kind==="folder",At=O.kind==="blank",Gt=s.jsxs("div",{ref:_t,className:"affairs-library-context-menu",role:"menu","aria-label":a("shell.affairsLibraryContextMenuLabel"),onPointerDown:Zn=>Zn.stopPropagation(),onContextMenu:Zn=>Zn.preventDefault(),children:[tn?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>y(O.record)),children:a("shell.affairsLibraryContextPreview")}):null,sn?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>Ze(O)),children:a("shell.affairsLibraryContextOpen")}):null,sn?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>Ht(O)),children:a("shell.affairsLibraryContextLocate")}):null,tn&&rt.isDesktop&&rt.ui.osFamily==="macos"&&Qh(g==null?void 0:g.mirrorRoot,O.record.filePath)?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>ft(O)),children:a("shell.affairsLibraryOpenWithLocalAppAction")}):null,tn?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>He(O)),children:a("shell.affairsLibraryContextDownload")}):null,At?s.jsxs("div",{className:"affairs-library-context-submenu","data-open":W==="new"?"true":void 0,onPointerEnter:()=>wt("new"),onPointerLeave:()=>lt(),children:[s.jsxs("button",{type:"button",role:"menuitem","aria-haspopup":"menu","aria-expanded":W==="new",children:[s.jsx("span",{children:a("shell.affairsLibraryContextNew")}),s.jsx("span",{"aria-hidden":"true",children:"›"})]}),s.jsxs("div",{className:"affairs-library-context-submenu-panel",role:"menu",onPointerEnter:()=>wt("new"),onPointerLeave:()=>lt(),children:[s.jsx("button",{type:"button",role:"menuitem",onClick:()=>Bt(O,"directory"),children:a("shell.affairsLibraryContextNewDirectory")}),s.jsx("button",{type:"button",role:"menuitem",onClick:()=>Bt(O,"markdown"),children:a("shell.affairsLibraryContextNewMarkdown")}),s.jsx("button",{type:"button",role:"menuitem",onClick:()=>Bt(O,"text"),children:a("shell.affairsLibraryContextNewText")}),s.jsx("button",{type:"button",role:"menuitem",onClick:()=>Bt(O,"custom"),children:a("shell.affairsLibraryContextNewCustomFile")})]})]}):null,Ae?s.jsxs("div",{className:"affairs-library-context-submenu","data-open":W==="copy"?"true":void 0,onPointerEnter:()=>wt("copy"),onPointerLeave:()=>lt(),children:[s.jsxs("button",{type:"button",role:"menuitem","aria-haspopup":"menu","aria-expanded":W==="copy",children:[s.jsx("span",{children:a("shell.affairsLibraryContextCopy")}),s.jsx("span",{"aria-hidden":"true",children:"›"})]}),s.jsxs("div",{className:"affairs-library-context-submenu-panel",role:"menu",onPointerEnter:()=>wt("copy"),onPointerLeave:()=>lt(),children:[s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>it(Qt,a("shell.affairsLibraryCopyFileSuccess"))),children:a("shell.affairsLibraryContextCopyFile")}),s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>it(Un,a("shell.affairsLibraryCopyFileNameSuccess"))),children:a("shell.affairsLibraryContextCopyFileName")}),s.jsx("button",{type:"button",role:"menuitem",disabled:!as,onClick:()=>void De(()=>it(as,a("shell.affairsLibraryCopyAbsolutePathSuccess"))),children:a("shell.affairsLibraryContextCopyAbsolutePath")}),s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>it(Qt,a("shell.affairsLibraryCopyRelativePathSuccess"))),children:a("shell.affairsLibraryContextCopyRelativePath")})]})]}):null,sn?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>fe({mode:"cut",target:O})),children:a("shell.affairsLibraryContextCut")}):null,s.jsx("button",{type:"button",role:"menuitem",disabled:!Xe,onClick:()=>void De(()=>en(O)),children:a("shell.affairsLibraryContextPaste")}),sn?s.jsx("button",{type:"button",role:"menuitem",className:"danger",onClick:()=>cn(O),children:a("shell.affairsLibraryContextDelete")}):null,sn?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>Ws(O)),children:a("shell.affairsLibraryContextTags")}):null,At?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>U()),children:a("shell.affairsLibraryContextRefresh")}):null,sn||At?s.jsx("button",{type:"button",role:"menuitem",onClick:()=>void De(()=>{if(O.kind==="document"){R(O.record.id);return}R(null),gt(O.kind==="folder"?O.entry.path:C.selectedFolderPath)}),children:a("shell.affairsLibraryContextProperties")}):null]});return typeof document>"u"?Gt:Bs.createPortal(Gt,document.body)};return!n.loading&&!n.unavailable&&!n.initialized?s.jsx(DH,{workspaceId:e}):t==="conversation"?s.jsx("div",{className:"affairs-main-panel",children:s.jsx("section",{className:"affairs-stage-panel",children:s.jsx(Zh,{workspaceId:e,context:null})})}):s.jsxs("div",{className:"affairs-main-panel",children:[s.jsxs("section",{className:"affairs-stage-panel",children:[b?s.jsx(yx,{viewMode:C.viewMode}):null,x?s.jsx("div",{className:"affairs-stage-empty",children:x}):null,!b&&!x?t==="library"?r?s.jsxs(s.Fragment,{children:[s.jsx(qH,{browseMode:C.browseMode,folderBreadcrumbs:st,recentTagTasks:L,tagRecords:h,indexStatus:m,directoryStatus:C.browseMode==="folder"?p:null,selectedTagPath:C.selectedTagPath,selectedTagPaths:j,sortState:ke,viewMode:C.viewMode,onNavigateFolder:K,onNavigateTag:E,onResetTags:()=>I("library:tag-root"),onOpenSettings:()=>M(!0),onRefresh:U,onSetSortState:we,onSetViewMode:X,refreshPending:te}),kt.length===0?D?s.jsx(yx,{viewMode:C.viewMode}):s.jsx("div",{className:"affairs-stage-empty",children:am(m)}):C.viewMode==="grid"?s.jsx(s.Fragment,{children:s.jsxs("div",{ref:xe,className:"affairs-doc-grid-scroll",onContextMenu:Ke,children:[s.jsx("div",{className:"affairs-doc-grid-viewport",onContextMenu:Ke,children:ze?s.jsx("div",{className:"affairs-doc-grid-spacer",style:{height:`${vt.totalHeight}px`},children:s.jsx("div",{className:"affairs-doc-grid affairs-doc-grid-virtual",style:{transform:`translateY(${vt.offsetTop}px)`},children:Ct.map(O=>{var Ae;return O.kind==="folder"?s.jsxs("button",{type:"button",className:C.selectedFolderEntryPath===O.path?"affairs-doc-item grid active":"affairs-doc-item grid",onClick:()=>dt(O.path),onDoubleClick:()=>Nt(O.path),onContextMenu:Xe=>Se(Xe,ue(O)),children:[s.jsx("div",{className:"affairs-doc-icon",children:Ff()}),s.jsx("div",{className:"affairs-doc-title",title:O.title,children:O.title}),s.jsx("div",{className:"affairs-doc-footer",children:s.jsx("span",{className:"affairs-doc-muted",children:a("shell.affairsLibraryFolderCardCount",{count:O.count})})})]},O.id):s.jsxs("button",{type:"button",className:k.section==="library"&&((Ae=k.record)==null?void 0:Ae.id)===O.documentId?"affairs-doc-item grid active":"affairs-doc-item grid",onClick:()=>R(O.documentId),onContextMenu:Xe=>Se(Xe,ue(O)),onDoubleClick:()=>{const Xe=i.find(Qt=>Qt.id===O.documentId);Xe&&y(Xe)},children:[s.jsx("div",{className:"affairs-doc-icon",children:_f(O.path)}),s.jsx("div",{className:"affairs-doc-title",title:O.title,children:O.title}),s.jsx("div",{className:"affairs-doc-footer",children:s.jsx("span",{className:"affairs-doc-muted",children:uo(O.updatedAt)})})]},O.id)})})}):s.jsx("div",{className:"affairs-doc-grid",children:St.map(O=>{var Ae;return O.kind==="folder"?s.jsxs("button",{type:"button",className:C.selectedFolderEntryPath===O.path?"affairs-doc-item grid active":"affairs-doc-item grid",onClick:()=>dt(O.path),onDoubleClick:()=>Nt(O.path),onContextMenu:Xe=>Se(Xe,ue(O)),children:[s.jsx("div",{className:"affairs-doc-icon",children:Ff()}),s.jsx("div",{className:"affairs-doc-title",title:O.title,children:O.title}),s.jsx("div",{className:"affairs-doc-footer",children:s.jsx("span",{className:"affairs-doc-muted",children:a("shell.affairsLibraryFolderCardCount",{count:O.count})})})]},O.id):s.jsxs("button",{type:"button",className:k.section==="library"&&((Ae=k.record)==null?void 0:Ae.id)===O.documentId?"affairs-doc-item grid active":"affairs-doc-item grid",onClick:()=>R(O.documentId),onContextMenu:Xe=>Se(Xe,ue(O)),onDoubleClick:()=>{const Xe=i.find(Qt=>Qt.id===O.documentId);Xe&&y(Xe)},children:[s.jsx("div",{className:"affairs-doc-icon",children:_f(O.path)}),s.jsx("div",{className:"affairs-doc-title",title:O.title,children:O.title}),s.jsx("div",{className:"affairs-doc-footer",children:s.jsx("span",{className:"affairs-doc-muted",children:uo(O.updatedAt)})})]},O.id)})})}),D||V?s.jsx("div",{className:"affairs-doc-grid-loading",children:a("common.loading")}):null]})}):s.jsx(s.Fragment,{children:s.jsxs("div",{className:"affairs-finder-shell",children:[s.jsx("div",{className:"affairs-finder-header",style:{gridTemplateColumns:q},children:fn.map(O=>s.jsxs("span",{className:"affairs-finder-header-cell affairs-finder-cell","data-column":O.key,children:[s.jsxs("button",{type:"button",className:"affairs-finder-header-sort-button",onClick:()=>we(Ae=>q6(Ae,O.key)),"aria-label":K6(O.label,ke,O.key),children:[s.jsx("span",{className:"affairs-finder-header-label",children:O.label}),s.jsx("span",{className:"affairs-finder-header-sort-indicator","aria-hidden":"true",children:V6(ke,O.key)})]}),O.resizable?s.jsx("span",{role:"separator","aria-orientation":"vertical","aria-label":a("shell.affairsFinderResizeColumn",{column:O.label}),className:"affairs-finder-column-resizer","data-column":O.key,onPointerDown:Ae=>re(O.key,Ae)}):null]},O.key))}),s.jsxs("div",{ref:bt,className:"affairs-finder-list affairs-finder-viewport",onContextMenu:Ke,children:[s.jsx("div",{className:"affairs-finder-spacer",style:{height:`${J.totalHeight}px`},children:s.jsx("div",{className:"affairs-finder-virtual",style:{transform:`translateY(${J.offsetTop}px)`},children:Ue.map(O=>{var Ae;return O.kind==="folder"?s.jsxs("button",{type:"button",className:C.selectedFolderEntryPath===O.path?"affairs-finder-row active":"affairs-finder-row",onClick:()=>dt(O.path),onDoubleClick:()=>Nt(O.path),onContextMenu:Xe=>Se(Xe,ue(O)),style:{gridTemplateColumns:q},children:[s.jsxs("span",{className:"affairs-finder-name-cell",children:[s.jsx("span",{className:"affairs-finder-icon",children:Ff("row")}),s.jsx("span",{className:"affairs-finder-name",title:O.title,children:O.title})]}),s.jsx("span",{className:"affairs-finder-cell",children:sm(null)}),s.jsx("span",{className:"affairs-finder-cell",children:Lc(O.updatedAt)}),s.jsx("span",{className:"affairs-finder-cell",children:a("shell.affairsFinderKindFolder")}),s.jsx("span",{className:"affairs-finder-cell",children:Lc(O.createdAt)})]},O.id):s.jsxs("button",{type:"button",className:k.section==="library"&&((Ae=k.record)==null?void 0:Ae.id)===O.documentId?"affairs-finder-row active":"affairs-finder-row",onClick:()=>R(O.documentId),onContextMenu:Xe=>Se(Xe,ue(O)),style:{gridTemplateColumns:q},onDoubleClick:()=>{const Xe=i.find(Qt=>Qt.id===O.documentId);Xe&&y(Xe)},children:[s.jsxs("span",{className:"affairs-finder-name-cell",children:[s.jsx("span",{className:"affairs-finder-icon",children:_f(O.path,"row")}),s.jsx("span",{className:"affairs-finder-name",title:O.title,children:O.title})]}),s.jsx("span",{className:"affairs-finder-cell",children:sm(O.sizeBytes)}),s.jsx("span",{className:"affairs-finder-cell",children:Lc(O.updatedAt)}),s.jsx("span",{className:"affairs-finder-cell",children:Aq(O.path)}),s.jsx("span",{className:"affairs-finder-cell",children:Lc(O.createdAt)})]},O.id)})})}),D||V?s.jsx("div",{className:"affairs-finder-loading",children:a("common.loading")}):null]})]})})]}):null:s.jsx(ZU,{}):null]}),s.jsx(mU,{open:le,onClose:()=>M(!1)}),s.jsx(wU,{}),Q?rt.isMobile?s.jsxs(zi,{open:!0,title:a("shell.affairsLibraryCreateModalTitle"),description:a("shell.affairsLibraryCreateModalDescription",{path:nm(Q.folderPath)}),height:"auto",kind:"form",onClose:()=>{Oe||(ge(null),G(null))},footer:s.jsxs(Es,{children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:Oe,onClick:()=>{ge(null),G(null)},children:a("common.cancel")}),s.jsx("button",{type:"button",className:"primary-button",disabled:Oe,onClick:()=>void is(),children:Oe?a("common.loading"):a("shell.affairsLibraryCreateConfirmAction")})]}),children:[s.jsx(Ot,{label:a("shell.affairsLibraryCreateNameLabel"),htmlFor:It,description:a("shell.affairsLibraryCreateTypeHint",{type:wx(Q.kind)}),children:s.jsx("input",{id:It,value:Q.fileName,onChange:O=>ge(Ae=>Ae&&{...Ae,fileName:O.target.value}),placeholder:a("shell.affairsLibraryCreateNamePlaceholder"),autoFocus:!0})}),Ve?s.jsx("div",{className:"affairs-binding-hint affairs-create-error",children:Ve}):null]}):s.jsxs(Qr,{open:!0,title:a("shell.affairsLibraryCreateModalTitle"),description:a("shell.affairsLibraryCreateModalDescription",{path:nm(Q.folderPath)}),size:"compact",layout:"form",onClose:()=>{Oe||(ge(null),G(null))},footer:s.jsxs(Es,{children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:Oe,onClick:()=>{ge(null),G(null)},children:a("common.cancel")}),s.jsx("button",{type:"button",className:"primary-button",disabled:Oe,onClick:()=>void is(),children:Oe?a("common.loading"):a("shell.affairsLibraryCreateConfirmAction")})]}),children:[s.jsx(Ot,{label:a("shell.affairsLibraryCreateNameLabel"),htmlFor:It,description:a("shell.affairsLibraryCreateTypeHint",{type:wx(Q.kind)}),children:s.jsx("input",{id:It,value:Q.fileName,onChange:O=>ge(Ae=>Ae&&{...Ae,fileName:O.target.value}),placeholder:a("shell.affairsLibraryCreateNamePlaceholder"),autoFocus:!0})}),Ve?s.jsx("div",{className:"affairs-binding-hint affairs-create-error",children:Ve}):null]}):null,ve?s.jsx(LU,{mobile:rt.isMobile,target:ve,busy:nt,onClose:()=>{nt||_e(null)},onConfirm:()=>{Cn()}}):null,ot?rt.isMobile?s.jsx(zi,{open:!0,title:a("shell.affairsTagQuickAssignModalTitle"),description:ot.kind==="document"?a("shell.affairsTagQuickAssignDocumentDescription",{name:ot.title}):a("shell.affairsTagQuickAssignFolderDescription",{name:ot.title}),height:"auto",kind:"form",backdropVisible:!1,onClose:()=>jt(null),footer:s.jsx(Es,{children:s.jsx("button",{type:"button",className:"secondary-button",onClick:()=>jt(null),children:a("common.close")})}),children:ot.kind==="document"?s.jsx(Va,{assignedTagIds:ot.existingTagIds,resolvedTagPaths:ot.resolvedTagPaths,emptyText:a("shell.affairsDocumentTagsEmpty"),inputLabel:a("shell.affairsDocumentTagAddLabel"),suggestionsLabel:a("shell.affairsDocumentTagSuggestionsLabel"),onSave:(O,Ae)=>_(ot.documentId,O,Ae,ot.existingTagIds,ot.title),onSaved:()=>jt(null)}):s.jsx(Va,{assignedTagIds:ot.existingTagIds,emptyText:a("shell.affairsFolderTagsEmpty"),inputLabel:a("shell.affairsFolderTagAddLabel"),suggestionsLabel:a("shell.affairsFolderTagSuggestionsLabel"),onSave:(O,Ae)=>T(ot.folderPath,O,Ae,ot.existingTagIds),onSaved:()=>jt(null)})}):s.jsx(Qr,{open:!0,title:a("shell.affairsTagQuickAssignModalTitle"),description:ot.kind==="document"?a("shell.affairsTagQuickAssignDocumentDescription",{name:ot.title}):a("shell.affairsTagQuickAssignFolderDescription",{name:ot.title}),size:"compact",layout:"form",backdropVisible:!1,onClose:()=>jt(null),footer:s.jsx(Es,{children:s.jsx("button",{type:"button",className:"secondary-button",onClick:()=>jt(null),children:a("common.close")})}),children:ot.kind==="document"?s.jsx(Va,{assignedTagIds:ot.existingTagIds,resolvedTagPaths:ot.resolvedTagPaths,emptyText:a("shell.affairsDocumentTagsEmpty"),inputLabel:a("shell.affairsDocumentTagAddLabel"),suggestionsLabel:a("shell.affairsDocumentTagSuggestionsLabel"),onSave:(O,Ae)=>_(ot.documentId,O,Ae,ot.existingTagIds,ot.title),onSaved:()=>jt(null)}):s.jsx(Va,{assignedTagIds:ot.existingTagIds,emptyText:a("shell.affairsFolderTagsEmpty"),inputLabel:a("shell.affairsFolderTagAddLabel"),suggestionsLabel:a("shell.affairsFolderTagSuggestionsLabel"),onSave:(O,Ae)=>T(ot.folderPath,O,Ae,ot.existingTagIds),onSaved:()=>jt(null)})}):null,mt()]})}function FH({workspaceId:e,onToggleCollapse:t}){var je;const{activeSection:n,agentConversationSessions:r,agentConversationSessionsLoading:i,agentProjectId:o,agentWorkspaceId:l,binding:c,assistantContext:u,auxiliaryTab:f,automationRuns:h,butlerStore:m,documentTagDetails:g,detailViewerCollapsed:p,filteredDocuments:b,filteredTodoRecords:y,folderRecords:x,initGuard:k,indexStatus:C,libraryConfig:j,markConversationSessionSeen:H,navigateLibraryFolder:_,openConversationCreateModal:T,reloadAgentConversationSessions:P,rememberConversationSession:z,selectAuxiliaryTab:L,toggleDetailViewerCollapsed:R,selectedObject:K,state:E,tagRecords:D,selectedTagPaths:te}=Qn(),V=Zt(m,Q=>Q.controlSession),[ee,U]=d.useState(!1),he=n==="conversation"&&!k.initialized,X=d.useRef(null),I=d.useRef(null),[xe,le]=d.useState(!1),M=n==="library",de=n==="workbench"||c?u:null,Ne=d.useMemo(()=>K.section!=="automation"||!K.record?[]:h.filter(Q=>{var ge;return Q.automationId===((ge=K.record)==null?void 0:ge.id)}).slice(0,12),[h,K]),ye=d.useMemo(()=>Z6(x,b,E.selectedFolderPath,E.selectedFolderEntryPath,K),[b,x,K,E.selectedFolderEntryPath,E.selectedFolderPath]),Be=d.useMemo(()=>eq(D,b,E.selectedTagPath,te),[b,te,E.selectedTagPath,D]),We=K.section==="library"?K.record:null,Ce=K.section==="todo"?K.record:null,ke=K.section==="automation"?K.record:null,we=d.useMemo(()=>We?Qh(j==null?void 0:j.mirrorRoot,We.filePath):null,[We,j==null?void 0:j.mirrorRoot]),se=d.useMemo(()=>hd(V,l)?(V==null?void 0:V.session)??null:null,[l,V]),ce=d.useMemo(()=>(se&&r.every(ge=>ge.sessionId!==se.sessionId)?[se,...r]:r).map(ge=>({id:li("agent",ge.sessionId),kind:"agent",session:ge})).sort((ge,Oe)=>ge.session.isFavorite!==Oe.session.isFavorite?ge.session.isFavorite?-1:1:co(Oe.session)-co(ge.session)).filter(ge=>ge.session.isArchived!==!0),[r,se]),Y=i,{showToast:Te}=Vn(),[pe,fe]=d.useState(!1);d.useEffect(()=>{if(f!=="detail"||K.section!=="library"||!K.record){U(!1);return}U(!1);const Q=window.setTimeout(()=>{U(!0)},Nz);return()=>window.clearTimeout(Q)},[f,K]),d.useEffect(()=>{fe(!1)},[K]),d.useEffect(()=>{f!=="assistant"&&le(!1)},[f]),d.useEffect(()=>{if(!xe)return;const Q=Oe=>{var $e,Ve;Oe.target instanceof Node&&(($e=X.current)!=null&&$e.contains(Oe.target)||(Ve=I.current)!=null&&Ve.contains(Oe.target)||le(!1))},ge=Oe=>{Oe.key==="Escape"&&le(!1)};return window.addEventListener("pointerdown",Q),window.addEventListener("keydown",ge),()=>{window.removeEventListener("pointerdown",Q),window.removeEventListener("keydown",ge)}},[xe]);const W=d.useCallback(()=>{le(Q=>!Q),P().catch(()=>{})},[P]),Me=d.useCallback(async Q=>{if(Q.kind!=="agent")return;H(Q.kind,Q.session.sessionId),le(!1);const ge=m.getState().controlSession;if((ge==null?void 0:ge.session.sessionId)===Q.session.sessionId){z({kind:"agent",session:ge.session,bootstrapMessages:[]});return}try{let $e=(await Ch()).items.find(Ve=>Ve.session.sessionId===Q.session.sessionId)??null;if(!$e){const Ve=Rj(Q.session.rawStoreRef??null);if(!o||!Ve)throw new Error(a("shell.butlerLoadFailed"));const G=await eS(o,Ve);$e=(await Ch()).items.find(_e=>_e.session.sessionId===G.resumed.session.sessionId)??null}if(!$e)throw new Error(a("shell.butlerLoadFailed"));await m.openControlSession($e.id),z({kind:"agent",session:$e.session,bootstrapMessages:[]})}catch(Oe){Te({title:dN(Oe,a("shell.butlerLoadFailed")),tone:"error"})}},[o,m,H,z,Te]);return n==="conversation"&&k.loading?s.jsxs("section",{className:"workbench-section-block affairs-sidebar-block affairs-auxiliary-block",children:[s.jsx("div",{className:"affairs-sidebar-block-header",children:s.jsxs("div",{children:[s.jsx("h2",{children:a("shell.affairsConnectionCheckingTitle")}),s.jsx("p",{children:a("shell.affairsConnectionCheckingDescription")})]})}),s.jsx("div",{className:"affairs-stage-empty",children:a("shell.affairsConnectionCheckingAuxiliaryEmpty")})]}):n==="conversation"&&k.unavailable?s.jsxs("section",{className:"workbench-section-block affairs-sidebar-block affairs-auxiliary-block",children:[s.jsx("div",{className:"affairs-sidebar-block-header",children:s.jsxs("div",{children:[s.jsx("h2",{children:a("shell.affairsHostUnavailableTitle")}),s.jsx("p",{children:a("shell.affairsHostUnavailableDescription")})]})}),s.jsx("div",{className:"affairs-stage-empty",children:a("shell.affairsHostUnavailableAuxiliaryEmpty")})]}):s.jsxs("div",{className:"affairs-auxiliary-shell",children:[s.jsxs("div",{className:"workbench-auxiliary-header",children:[t?s.jsx("button",{type:"button",className:"workbench-nav-toolbar-button","aria-label":a("shell.hideInfoSidebar"),title:a("shell.hideInfoSidebar"),onClick:t,children:s.jsx(zU,{})}):null,s.jsxs("div",{className:"workbench-info-tabs affairs-auxiliary-tabs",role:"tablist","aria-label":a("shell.affairsAuxiliaryTabsLabel"),children:[M?s.jsx("button",{type:"button",role:"tab","aria-selected":f==="detail",className:f==="detail"?"workbench-info-tab active":"workbench-info-tab",onClick:()=>L("detail"),children:a("shell.affairsDetailTitle")}):null,s.jsx("button",{type:"button",role:"tab","aria-selected":f==="assistant",className:f==="assistant"?"workbench-info-tab active":"workbench-info-tab",onClick:()=>L("assistant"),children:a("shell.affairsAssistantTitle")})]}),s.jsx("div",{className:"affairs-auxiliary-header-tools",children:s.jsx("div",{className:"affairs-auxiliary-header-actions","data-visible":f==="assistant"?"true":"false","aria-hidden":f==="assistant"?void 0:"true",children:f==="assistant"?s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:X,type:"button",className:"workbench-nav-toolbar-button","aria-label":a("shell.butlerHistoryAction"),title:a("shell.butlerHistoryAction"),"aria-haspopup":"dialog","aria-expanded":xe,onClick:W,children:s.jsx(HU,{})}),s.jsx(mp,{open:xe&&X.current!==null,className:"affairs-assistant-history-popover",anchorRef:X,popoverRef:I,role:"dialog",labelledBy:"affairs-assistant-history-title",maxWidth:420,gap:8,children:s.jsxs("div",{className:"affairs-assistant-history-popover-card",children:[s.jsxs("div",{className:"affairs-assistant-history-popover-header",children:[s.jsx("strong",{id:"affairs-assistant-history-title",children:a("shell.affairsConversationSidebarTitle")}),s.jsx("span",{children:ce.length})]}),Y&&ce.length===0?s.jsx("div",{className:"affairs-assistant-history-empty",children:a("common.loading")}):ce.length===0?s.jsx("div",{className:"affairs-assistant-history-empty",children:a("shell.affairsConversationCreateHint")}):s.jsx("div",{className:"affairs-assistant-history-list",role:"list",children:ce.map(Q=>s.jsxs("button",{type:"button",role:"listitem",className:"affairs-assistant-history-item","data-active":E.selectedNodeId===Q.id?"true":void 0,onClick:()=>Me(Q),children:[s.jsxs("div",{className:"affairs-assistant-history-item-main",children:[s.jsxs("div",{className:"affairs-assistant-history-item-title-row",children:[s.jsx("span",{className:"affairs-assistant-history-item-title",title:Q.session.title,children:Q.session.title}),Q.session.isFavorite?s.jsx("span",{className:"affairs-assistant-history-item-favorite","aria-hidden":"true",children:"★"}):null]}),s.jsx("div",{className:"affairs-assistant-history-item-meta",children:[Cl(Q.kind),Pp(Q.session)].filter(Boolean).join(" · ")})]}),s.jsx("span",{className:`session-provider-badge ${Q.session.provider}`,children:Rp(Q.session.provider)})]},Q.id))})]})}),s.jsx("button",{type:"button",className:"workbench-nav-toolbar-button","aria-label":a("shell.butlerNewSessionAction"),title:a("shell.butlerNewSessionAction"),onClick:()=>T({mode:"agent-only"}),children:s.jsx(Mj,{})})]}):null})})]}),s.jsx("div",{className:"workbench-auxiliary-body","data-scrollbar-autohide":"true","data-affairs-auxiliary-tab":f,children:he?f==="assistant"?s.jsx(Zh,{workspaceId:e,context:null}):s.jsx("div",{className:"affairs-stage-empty",children:a("shell.affairsInitRouteGuardAuxiliaryEmpty")}):f==="detail"?K.section==="library"?c?We?s.jsxs("div",{className:"affairs-detail-panel",children:[s.jsxs("section",{className:"workbench-section-block affairs-detail-block affairs-detail-hero-block",children:[s.jsx("div",{className:"affairs-detail-headline affairs-detail-headline-document",children:s.jsxs("div",{className:"affairs-detail-headline-main affairs-detail-headline-main-centered",children:[s.jsx("span",{className:"affairs-detail-headline-label",children:a("shell.affairsLibraryDocumentDetailTitle")}),s.jsx("h2",{children:We.displayName}),s.jsxs("div",{className:"affairs-detail-summary-block",children:[s.jsx("p",{className:"affairs-detail-summary","data-expanded":pe?"true":void 0,children:We.summary}),fN(We.summary)?s.jsx("button",{type:"button",className:"affairs-detail-summary-toggle","aria-expanded":pe,onClick:()=>fe(Q=>!Q),children:pe?a("shell.affairsDocumentSummaryCollapseAction"):a("shell.affairsDocumentSummaryExpandAction")}):null]})]})}),s.jsxs("dl",{className:"affairs-detail-meta-list",children:[s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsDetailMetaPath")}),s.jsx("dd",{children:s.jsx(Iq,{path:We.filePath,rootLabel:a("shell.affairsLibraryFolderRootLabel"),onNavigate:_})})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryDocumentSize")}),s.jsx("dd",{children:sm(We.sizeBytes)})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryDocumentCreatedAt")}),s.jsx("dd",{children:Du(We.createdAt)})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryDocumentUpdatedAt")}),s.jsx("dd",{children:Du(We.updatedAt)})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryMirrorRootLabel")}),s.jsx("dd",{children:((je=j==null?void 0:j.mirrorRoot)==null?void 0:je.trim())||a("shell.affairsLibraryMirrorRootEmpty")})]})]}),s.jsxs("div",{className:"affairs-detail-tag-editor",children:[s.jsx("strong",{children:a("shell.affairsDocumentTagsSectionTitle")}),s.jsx(BH,{documentId:We.id,details:g})]}),s.jsxs("div",{className:"affairs-binding-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",onClick:()=>_(_l(We.filePath)||null),children:a("shell.affairsLibraryLocateFolderAction")}),we?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"secondary-button",onClick:async()=>{const Q=await ha().fs.openFile(we.absolutePath);Q.ok||Te({title:a("shell.affairsLibraryOpenLocalFileFailed"),description:Q.detail??we.absolutePath,tone:"error"})},children:a("shell.affairsLibraryOpenLocalFileAction")}),s.jsx("button",{type:"button",className:"secondary-button",onClick:async()=>{const Q=await ha().fs.revealInFileManager(we.absolutePath);Q.ok||Te({title:a("shell.affairsLibraryRevealLocalFileFailed"),description:Q.detail??we.absolutePath,tone:"error"})},children:a("shell.affairsLibraryRevealLocalFileAction")})]}):null]})]}),s.jsx("div",{className:"affairs-detail-viewer-shell","data-collapsed":p?"true":void 0,children:s.jsx(EU,{workspaceId:e,filePath:We.filePath,windowTitle:We.displayName,collapsed:p,loading:!ee,onToggleCollapsed:R})})]}):E.browseMode==="folder"?s.jsx(_H,{detail:ye}):s.jsx(VH,{detail:Be}):s.jsx("div",{className:"affairs-stage-empty",children:a("shell.affairsDetailEmpty")}):K.section==="todo"?Ce?s.jsxs("section",{className:"workbench-section-block affairs-detail-block affairs-detail-hero-block",children:[s.jsxs("div",{className:"affairs-detail-headline",children:[s.jsxs("div",{children:[s.jsx("h2",{children:Ce.title}),s.jsx("p",{children:Ce.summary})]}),s.jsx("span",{className:"affairs-inline-pill",children:Ce.sourceLabel})]}),s.jsxs("dl",{className:"affairs-detail-meta-list",children:[s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsTodoDetailStatus")}),s.jsx("dd",{children:Ce.statusLabel})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsTodoDetailSource")}),s.jsx("dd",{children:Ce.sourceDescription})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsTodoDetailNotes")}),s.jsx("dd",{children:Ce.detail})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsTodoDetailTotal")}),s.jsx("dd",{children:a("shell.affairsTodoDetailTotalValue",{count:y.length})})]})]})]}):s.jsx("div",{className:"affairs-stage-empty",children:a("shell.affairsTodoEmpty")}):K.section==="workbench"?s.jsx("section",{className:"workbench-section-block affairs-detail-block affairs-detail-hero-block",children:s.jsxs("div",{className:"affairs-detail-headline",children:[s.jsxs("div",{children:[s.jsx("h2",{children:a("shell.affairsWorkbenchDetailTitle")}),s.jsx("p",{children:a("shell.affairsWorkbenchDetailDescription")})]}),s.jsx("span",{className:"affairs-inline-pill",children:a("shell.affairsWorkbenchNav")})]})}):ke?s.jsxs("div",{className:"affairs-detail-panel",children:[s.jsxs("section",{className:"workbench-section-block affairs-detail-block affairs-detail-hero-block",children:[s.jsxs("div",{className:"affairs-detail-headline",children:[s.jsxs("div",{children:[s.jsx("h2",{children:ke.title}),s.jsx("p",{children:ke.summary})]}),s.jsx("span",{className:"affairs-inline-pill",children:ke.statusLabel})]}),s.jsxs("dl",{className:"affairs-detail-meta-list",children:[s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsAutomationDetailTrigger")}),s.jsx("dd",{children:ke.triggerLabel})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsAutomationDetailTarget")}),s.jsx("dd",{children:ke.targetSessionLabel})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsAutomationDetailStatus")}),s.jsx("dd",{children:ke.statusLabel})]})]})]}),s.jsxs("section",{className:"workbench-section-block affairs-detail-block",children:[s.jsxs("div",{className:"affairs-detail-headline compact",children:[s.jsx("h3",{children:a("shell.affairsAutomationRunsTitle")}),s.jsx("p",{children:a("shell.affairsAutomationRunsDescription")})]}),Ne.length===0?s.jsx("div",{className:"affairs-stage-empty compact",children:a("shell.affairsAutomationRunsEmpty")}):s.jsx("div",{className:"affairs-run-list",children:Ne.map(Q=>{var ge,Oe;return s.jsxs("div",{className:"affairs-run-item",children:[s.jsxs("div",{className:"affairs-run-item-row",children:[s.jsx("strong",{children:lN(Q.status)}),s.jsx("span",{className:"affairs-run-item-time",children:uo(Q.finishedAt||Q.startedAt||Q.createdAt)})]}),s.jsx("span",{children:((ge=Q.summary)==null?void 0:ge.trim())||((Oe=Q.error)==null?void 0:Oe.trim())||a("shell.affairsAutomationRunsFallback")})]},Q.id)})})]})]}):s.jsx("div",{className:"affairs-stage-empty",children:a("shell.affairsAutomationEmpty")}):s.jsx(Zh,{workspaceId:e,context:de})})]})}function Bj({node:e,state:t,selectedTagPaths:n,expandedPaths:r,expandedOverflowPaths:i,onSelect:o,onToggleExpand:l,onToggleOverflow:c,onToggleFavorite:u}){const f=`library:tag:${e.path}`,h=e.children.length>0,m=h&&r.includes(e.path),g=Jj(e.children,e.path,i),p=e.children.length>vl,b=i.includes(e.path),y=n.includes(e.path);return s.jsxs("div",{className:"affairs-tag-tree-node",role:"treeitem","aria-expanded":h?m:void 0,children:[s.jsx("div",{className:y||f===t.selectedNodeId?"affairs-sidebar-item active":"affairs-sidebar-item","data-tone":"tag",children:s.jsxs("div",{className:"affairs-tag-tree-row",children:[h?s.jsx("button",{type:"button",className:"affairs-tag-tree-toggle","aria-label":m?a("shell.subagentCollapse"):a("shell.subagentExpand"),onClick:()=>l(e.path),children:s.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})}):s.jsx("span",{className:"affairs-tag-tree-toggle placeholder","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"affairs-sidebar-item-button affairs-sidebar-item-button-content",onClick:()=>o(f),children:s.jsxs("div",{className:"affairs-sidebar-item-row",children:[s.jsx("span",{className:"affairs-sidebar-item-title",children:e.label}),s.jsx("div",{className:"affairs-sidebar-item-actions",children:s.jsx("span",{className:"affairs-sidebar-item-badge",children:e.count})})]})}),im(f,e.label,u)]})}),m?s.jsxs("div",{className:"affairs-tag-tree-children",role:"group",children:[g.map(x=>s.jsx(Bj,{node:x,state:t,selectedTagPaths:n,expandedPaths:r,expandedOverflowPaths:i,onSelect:o,onToggleExpand:l,onToggleOverflow:c,onToggleFavorite:u},x.path)),p?s.jsxs("button",{type:"button",className:"affairs-tag-tree-more",onClick:()=>c(e.path),children:[s.jsx("span",{className:"affairs-tag-tree-more-icon","aria-hidden":"true",children:b?"▴":"▾"}),s.jsx("span",{className:"affairs-tag-tree-more-label",children:b?a("shell.affairsLibraryTagTreeShowLess"):a("shell.affairsLibraryTagTreeShowMore")})]}):null]}):null]})}function _H({detail:e}){const{folderTagDetails:t,saveFolderTagSelection:n}=Qn(),[r,i]=d.useState(!1);return d.useEffect(()=>{i(!1)},[e==null?void 0:e.path]),e?s.jsxs("section",{className:"workbench-section-block affairs-detail-block affairs-detail-hero-block",children:[s.jsx("div",{className:"affairs-detail-headline affairs-detail-headline-document",children:s.jsxs("div",{className:"affairs-detail-headline-main affairs-detail-headline-main-centered",children:[s.jsx("span",{className:"affairs-detail-headline-label",children:a("shell.affairsLibraryFolderDetailTitle")}),s.jsx("h2",{children:e.title}),s.jsxs("div",{className:"affairs-detail-summary-block",children:[s.jsx("p",{className:"affairs-detail-summary","data-expanded":r?"true":void 0,children:e.summary}),fN(e.summary)?s.jsx("button",{type:"button",className:"affairs-detail-summary-toggle","aria-expanded":r,onClick:()=>i(o=>!o),children:r?a("shell.affairsDocumentSummaryCollapseAction"):a("shell.affairsDocumentSummaryExpandAction")}):null]})]})}),s.jsxs("dl",{className:"affairs-detail-meta-list",children:[s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryCurrentFolder")}),s.jsx("dd",{children:e.path})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryDirectFolderCount")}),s.jsx("dd",{children:e.childFolderCount})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryDirectDocumentCount")}),s.jsx("dd",{children:e.directDocumentCount})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryNestedDocumentCount")}),s.jsx("dd",{children:e.totalDocumentCount})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryDocumentCreatedAt")}),s.jsx("dd",{children:Du(e.createdAt)})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryDocumentUpdatedAt")}),s.jsx("dd",{children:Du(e.updatedAt)})]})]}),s.jsxs("div",{className:"affairs-detail-tag-editor",children:[s.jsx("strong",{children:a("shell.affairsFolderTagsSectionTitle")}),s.jsx(Va,{assignedTagIds:(t==null?void 0:t.bindingTagIds)??[],emptyText:a("shell.affairsFolderTagsEmpty"),inputLabel:a("shell.affairsFolderTagAddLabel"),suggestionsLabel:a("shell.affairsFolderTagSuggestionsLabel"),onSave:(o,l)=>n((t==null?void 0:t.folderPath)??e.folderPath??".",o,l,(t==null?void 0:t.bindingTagIds)??[])})]})]}):s.jsx("div",{className:"affairs-detail-empty-state",children:a("shell.affairsDetailEmpty")})}function BH({documentId:e,details:t}){const{saveDocumentTagSelection:n}=Qn();return t?s.jsx(Va,{assignedTagIds:t.manualTagIds,resolvedTagPaths:Lp((t.resolvedTags??[]).map(r=>r.path)),emptyText:a("shell.affairsDocumentTagsEmpty"),inputLabel:a("shell.affairsDocumentTagAddLabel"),suggestionsLabel:a("shell.affairsDocumentTagSuggestionsLabel"),onSave:(r,i)=>n(e,r,i,t.manualTagIds,t.title)}):s.jsx("span",{className:"affairs-binding-hint",children:a("shell.affairsTagDetailsLoading")})}function Va({assignedTagIds:e,resolvedTagPaths:t=[],emptyText:n,inputLabel:r,suggestionsLabel:i,onSave:o,onSaved:l}){const{managedTags:c}=Qn(),[u,f]=d.useState(""),[h,m]=d.useState(!1),g=d.useMemo(()=>new Set(e),[e]),p=d.useMemo(()=>(Array.isArray(c)?c:[]).filter(Xh),[c]),b=d.useMemo(()=>p.filter(z=>g.has(z.id)),[p,g]),y=d.useMemo(()=>{const z=new Map;return b.forEach(L=>z.set(L.path,L)),z},[b]),x=d.useMemo(()=>Lp([...t,...b.map(z=>z.path)]),[t,b]),k=zH(u),C=k.toLowerCase(),j=d.useMemo(()=>C?p.filter(z=>!g.has(z.id)).filter(z=>`${z.path} ${z.name}`.toLowerCase().includes(C)).slice(0,8):[],[p,C,g]),H=d.useMemo(()=>p.find(z=>z.path.toLowerCase()===C)??null,[p,C]),_=k.length>0&&!H,T=async(z,L=[])=>{m(!0);try{await o(CU(z),L),f(""),l==null||l()}finally{m(!1)}},P=async()=>{if(k){if(H){if(g.has(H.id)){f("");return}await T([...e,H.id]);return}await T([...e],[k])}};return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"affairs-document-tag-list",children:x.length===0?s.jsx("span",{className:"affairs-binding-hint",children:n}):x.map(z=>{const L=y.get(z);return L?s.jsxs("button",{type:"button",className:"affairs-document-tag-token","aria-label":a("shell.affairsDocumentTagRemoveAction",{tag:L.path}),disabled:h,onClick:()=>{T(e.filter(R=>R!==L.id))},children:[s.jsx(Of,{label:L.path,path:L.path}),s.jsx("span",{"aria-hidden":"true",children:"×"})]},L.id):s.jsx(Of,{label:z,path:z},z)})}),s.jsxs("div",{className:"affairs-document-tag-picker",children:[s.jsxs("label",{className:"affairs-document-tag-input-label",children:[s.jsx("span",{children:r}),s.jsx("input",{value:u,disabled:h,onChange:z=>f(z.target.value),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),P())},placeholder:a("shell.affairsTagQuickSearchPlaceholder")})]}),k?s.jsxs("div",{className:"affairs-document-tag-suggestions",role:"listbox","aria-label":i,children:[j.map(z=>s.jsx("button",{type:"button",className:"affairs-document-tag-suggestion",disabled:h,onClick:()=>{T([...e,z.id])},children:s.jsx(Of,{label:z.path,path:z.path})},z.id)),_?s.jsxs("button",{type:"button",className:"affairs-document-tag-suggestion affairs-document-tag-create-suggestion",disabled:h,onClick:()=>{T([...e],[k])},children:[s.jsx("span",{className:"affairs-document-tag-create-label",children:a("shell.affairsTagQuickCreateAction",{tag:k})}),s.jsx("span",{className:"affairs-binding-hint",children:a("shell.affairsTagQuickCreateHint")})]}):null,j.length===0&&!_?s.jsx("span",{className:"affairs-binding-hint",children:a("shell.affairsTagQuickAlreadyAssigned")}):null]}):null]})]})}function Of({label:e,path:t}){return s.jsx("span",{className:"affairs-color-tag",style:HH(t),children:e})}function WH(e){const t=new Map;e.forEach(i=>{t.set(i.id,{tag:i,children:[]})});const n=[];t.forEach(i=>{if(i.tag.parentId){const o=t.get(i.tag.parentId);if(o){o.children.push(i);return}}n.push(i)});const r=i=>{i.sort((o,l)=>o.tag.path.localeCompare(l.tag.path,"zh-Hans-CN")),i.forEach(o=>r(o.children))};return r(n),n}function Wj(e,t=0){return e.flatMap(n=>[{tag:n.tag,depth:t},...Wj(n.children,t+1)])}function $H(e,t){if(!t)return!0;if(e.id===t.id)return!1;const n=`${t.path}/`;return!e.path.startsWith(n)}function Xh(e){if(e.status!=="active")return!1;const t=e.rootType.trim().toLowerCase();return t!=="类型"&&t!=="type"&&t!=="时间"&&t!=="time"}function zH(e){return e.trim().replace(/^\/+/,"").replace(/\/+$/g,"").split("/").map(t=>t.trim()).filter(Boolean).join("/")}function Lp(e){const t=Array.from(new Set(e.map(i=>i.trim()).filter(Boolean))),n=t.map(i=>({path:i,days:bx(i)})).filter(i=>i.days!==null),r=n.length>0?n.reduce((i,o)=>o.days<i.days?o:i).path:null;return t.filter(i=>bx(i)===null||i===r)}function bx(e){const t=e.trim(),n=/^时间\/最近(\d+)天$/.exec(t)??/^time\/recent-(\d+)-days$/i.exec(t);if(!n)return null;const r=Number.parseInt(n[1]??"",10);return Number.isFinite(r)?r:null}function HH(e){const t=UH(e)%360;return{"--affairs-tag-hue":String(t)}}function UH(e){let t=0;for(const n of e)t=t*31+n.charCodeAt(0)>>>0;return t}function yx({viewMode:e}){return e==="list"?s.jsx("div",{className:"affairs-stage-skeleton affairs-stage-skeleton-list","aria-hidden":"true",children:Array.from({length:10}).map((t,n)=>s.jsx("div",{className:"affairs-stage-skeleton-row"},n))}):s.jsx("div",{className:"affairs-stage-skeleton affairs-stage-skeleton-grid","aria-hidden":"true",children:Array.from({length:18}).map((t,n)=>s.jsx("div",{className:"affairs-stage-skeleton-card"},n))})}function qH({browseMode:e,folderBreadcrumbs:t,recentTagTasks:n=[],tagRecords:r,indexStatus:i,directoryStatus:o,selectedTagPath:l,selectedTagPaths:c,sortState:u,viewMode:f,onNavigateFolder:h,onNavigateTag:m,onResetTags:g,onOpenSettings:p,onRefresh:b,onSetSortState:y,onSetViewMode:x,refreshPending:k}){const C=d.useRef(null),j=d.useRef(null),H=d.useRef(new Map),_=d.useRef(null),T=d.useRef(null),P=d.useRef(null),[z,L]=d.useState(0),[R,K]=d.useState(!1),[E,D]=d.useState(!1),te=d.useMemo(()=>G6(e,t,r,l,c),[e,t,l,c,r]),V=d.useMemo(()=>Y6(te,H.current,z),[z,te]),ee=mN(i),U=a("shell.affairsLibraryStatusIndicatorAction",{status:ee}),he=_q(i),X=d.useMemo(()=>Oq(i,o??null),[o,i]);d.useEffect(()=>{const le=C.current,M=j.current;if(!le||!M||typeof ResizeObserver>"u")return;const de=()=>{const ye=Math.max(120,le.clientWidth-M.clientWidth-32);L(ye)};de();const Ne=new ResizeObserver(de);return Ne.observe(le),Ne.observe(M),()=>Ne.disconnect()},[]),d.useEffect(()=>{R||D(!1)},[R]),d.useEffect(()=>{if(!R){P.current!==null&&(window.clearTimeout(P.current),P.current=null);return}function le(de){var Ne,ye;de.target instanceof Node&&!((Ne=_.current)!=null&&Ne.contains(de.target))&&!((ye=T.current)!=null&&ye.contains(de.target))&&K(!1)}function M(de){de.key==="Escape"&&K(!1)}return window.addEventListener("pointerdown",le),window.addEventListener("keydown",M),()=>{window.removeEventListener("pointerdown",le),window.removeEventListener("keydown",M)}},[R]),d.useEffect(()=>()=>{P.current!==null&&window.clearTimeout(P.current)},[]);function I(){P.current!==null&&(window.clearTimeout(P.current),P.current=null),K(!0)}function xe(){P.current!==null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{K(!1),P.current=null},120)}return s.jsxs("div",{ref:C,className:"affairs-stage-toolbar",children:[s.jsxs("div",{className:"affairs-stage-toolbar-left",children:[s.jsxs("div",{className:"affairs-stage-breadcrumb","aria-label":a("shell.affairsLibraryBindingFieldLabel"),children:[s.jsx("button",{type:"button",className:"affairs-stage-breadcrumb-button root","aria-label":a("shell.affairsLibraryFolderRootLabel"),title:a("shell.affairsLibraryFolderRootLabel"),onClick:()=>h(null),children:s.jsx(d6,{})}),V.map((le,M)=>s.jsxs(d.Fragment,{children:[s.jsx("span",{className:"affairs-stage-breadcrumb-separator","aria-hidden":"true",children:">"}),le.kind==="collapsed"?s.jsx("span",{className:"affairs-stage-breadcrumb-ellipsis",children:"..."}):s.jsx("button",{type:"button",className:M===V.length-1?"affairs-stage-breadcrumb-button current":"affairs-stage-breadcrumb-button",onClick:()=>le.mode==="folder"?h(le.value):m(le.value),children:le.label})]},le.key)),e==="tag"&&c.length>1?s.jsx("button",{type:"button",className:"affairs-stage-breadcrumb-reset",onClick:g,children:a("shell.affairsLibraryTagTreeReset")}):null]}),s.jsx("div",{className:"affairs-stage-breadcrumb-measure","aria-hidden":"true",children:te.map(le=>s.jsxs("span",{ref:M=>{M?H.current.set(le.key,M):H.current.delete(le.key)},className:"affairs-stage-breadcrumb-measure-item",children:["> ",le.label]},le.key))})]}),s.jsxs("div",{ref:j,className:"affairs-stage-toolbar-right",children:[s.jsxs("div",{className:"affairs-stage-toolbar-group",children:[s.jsx("button",{type:"button",className:f==="grid"?"affairs-stage-toolbar-icon active":"affairs-stage-toolbar-icon",onClick:()=>x("grid"),"aria-label":a("shell.affairsLibraryViewModeGrid"),title:a("shell.affairsLibraryViewModeGrid"),children:s.jsx(f6,{})}),s.jsx("button",{type:"button",className:f==="list"?"affairs-stage-toolbar-icon active":"affairs-stage-toolbar-icon",onClick:()=>x("list"),"aria-label":a("shell.affairsLibraryViewModeList"),title:a("shell.affairsLibraryViewModeList"),children:s.jsx(h6,{})})]}),s.jsx("div",{className:"affairs-stage-toolbar-group",children:s.jsxs("select",{className:"affairs-stage-toolbar-select",value:u.mode,onChange:le=>y(iN(le.target.value)),"aria-label":a("shell.affairsLibrarySortLabel"),title:a("shell.affairsLibrarySortLabel"),children:[s.jsx("option",{value:"recent",children:a("shell.affairsLibrarySortRecent")}),s.jsx("option",{value:"name",children:a("shell.affairsLibrarySortName")}),s.jsx("option",{value:"type",children:a("shell.affairsLibrarySortType")}),s.jsx("option",{value:"size",children:a("shell.affairsLibrarySortSize")}),s.jsx("option",{value:"createdAt",children:a("shell.affairsLibrarySortCreatedAt")})]})}),s.jsx("div",{className:"affairs-stage-toolbar-group",children:s.jsx("button",{type:"button",className:"affairs-stage-toolbar-icon",disabled:k,"aria-label":a("shell.affairsLibraryRefreshAction"),title:a("shell.affairsLibraryRefreshAction"),onClick:()=>{b()},children:s.jsx(m6,{})})}),n.length>0?s.jsx("div",{className:"affairs-stage-toolbar-group",children:s.jsx(KH,{tasks:n})}):null,s.jsxs("div",{className:"affairs-stage-toolbar-group",children:[s.jsxs("button",{ref:_,type:"button",className:"affairs-stage-status-trigger","aria-label":U,title:U,"aria-haspopup":"dialog","aria-expanded":R,onClick:()=>K(le=>!le),onMouseEnter:I,onMouseLeave:xe,onFocus:I,onBlur:xe,children:[s.jsx("span",{className:`affairs-stage-status-dot state-${(i==null?void 0:i.state)??"stale"}`}),he?s.jsx("span",{className:"affairs-stage-status-text",children:he}):null]}),s.jsx(mp,{open:R&&_.current!==null,className:"affairs-index-status-popover",anchorRef:_,popoverRef:T,role:"dialog",labelledBy:"affairs-index-status-popover-title",maxWidth:420,gap:8,children:s.jsxs("div",{className:"affairs-index-status-popover-card",onMouseEnter:I,onMouseLeave:xe,children:[s.jsx("div",{className:"affairs-index-status-popover-header",children:s.jsx("strong",{id:"affairs-index-status-popover-title",children:a("shell.affairsLibraryStatusPopoverTitle")})}),X.summaryMetrics.length>0?s.jsx("div",{className:"affairs-index-status-summary",children:X.summaryMetrics.map(le=>s.jsxs("div",{className:"affairs-index-status-summary-item","data-tone":le.tone??"default",children:[s.jsx("span",{className:"affairs-index-status-summary-label",children:le.label}),s.jsx("strong",{className:"affairs-index-status-summary-value",children:le.value})]},le.label))}):null,s.jsxs("div",{className:"affairs-index-status-primary",children:[s.jsx("div",{className:"affairs-index-status-section-title",children:a("shell.affairsLibraryStatusPrimaryTitle")}),s.jsx("div",{className:"affairs-index-status-popover-grid",children:X.primaryRows.map(le=>s.jsxs("div",{className:"affairs-index-status-popover-row",children:[s.jsx("span",{className:"affairs-index-status-popover-label",children:le.label}),s.jsx("span",{className:"affairs-index-status-popover-value","data-multiline":le.multiline?"true":void 0,children:le.value})]},le.label))})]}),X.technicalSections.length>0?s.jsxs("div",{className:"affairs-index-status-technical",children:[s.jsx("button",{type:"button",className:"secondary-button affairs-index-status-technical-toggle","aria-expanded":E,onClick:()=>D(le=>!le),children:a("shell.affairsLibraryStatusTechnicalToggle")}),E?s.jsx("div",{className:"affairs-index-status-section-list",children:X.technicalSections.map(le=>s.jsxs("section",{className:"affairs-index-status-section",children:[s.jsx("div",{className:"affairs-index-status-section-title",children:le.title}),s.jsx("div",{className:"affairs-index-status-popover-grid",children:le.rows.map(M=>s.jsxs("div",{className:"affairs-index-status-popover-row",children:[s.jsx("span",{className:"affairs-index-status-popover-label",children:M.label}),s.jsx("span",{className:"affairs-index-status-popover-value","data-multiline":M.multiline?"true":void 0,children:M.value})]},M.label))})]},le.title))}):null]}):null]})})]}),s.jsx("div",{className:"affairs-stage-toolbar-group",children:s.jsx("button",{type:"button",className:"affairs-stage-toolbar-icon","aria-label":a("shell.affairsLibrarySettingsAction"),title:a("shell.affairsLibrarySettingsAction"),onClick:p,children:s.jsx(g6,{})})})]})]})}function VH({detail:e}){const{selectedManagedTag:t,openTagManagement:n}=Qn();return e?s.jsxs("section",{className:"workbench-section-block affairs-detail-block affairs-detail-hero-block",children:[s.jsxs("div",{className:"affairs-detail-headline",children:[s.jsxs("div",{children:[s.jsx("h2",{children:e.title}),s.jsx("p",{children:a("shell.affairsLibraryTagDetailDescription")})]}),s.jsx("span",{className:"affairs-inline-pill",children:a("shell.affairsLibraryTagDetailTitle")})]}),s.jsxs("dl",{className:"affairs-detail-meta-list",children:[s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryCurrentTag")}),s.jsx("dd",{children:e.path})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryTagRootType")}),s.jsx("dd",{children:e.rootType})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryTagDocumentCount")}),s.jsx("dd",{children:e.documentCount})]}),s.jsxs("div",{children:[s.jsx("dt",{children:a("shell.affairsLibraryNestedTagDocumentCount")}),s.jsx("dd",{children:e.nestedDocumentCount})]})]}),s.jsxs("div",{className:"affairs-detail-tag-editor",children:[s.jsx("strong",{children:a("shell.affairsTagManagerSectionTitle")}),s.jsxs("div",{className:"affairs-library-settings-inline-actions",children:[s.jsx("span",{className:"affairs-binding-hint",children:(t==null?void 0:t.path)??a("shell.affairsTagDetailManageHint")}),s.jsx("button",{type:"button",className:"secondary-button",onClick:n,children:a("shell.affairsTagManagerAction")})]})]})]}):s.jsx("div",{className:"affairs-detail-empty-state",children:Hq()})}function KH({tasks:e}){const t=d.useRef(null),n=d.useRef(null),[r,i]=d.useState(!1),o=d.useMemo(()=>e.find(p=>!p.snapshot||!Or(p.snapshot.status))??e[0]??null,[e]);if(!o)return null;const l=o.snapshot,c=(l==null?void 0:l.status)??"queued",u=(l==null?void 0:l.progress)??null,f=Math.max(0,Math.min(100,Math.round((u==null?void 0:u.percent)??(Or(c)?100:0)))),h=em(c),m=tm(o.operation),g=e.filter(p=>!p.snapshot||!Or(p.snapshot.status)).length;return s.jsxs(s.Fragment,{children:[s.jsxs("button",{ref:t,type:"button",className:"affairs-folder-tag-task-trigger","aria-label":a("shell.affairsTagTaskHistoryButtonLabel",{count:e.length,operation:m,target:o.targetLabel,status:h,percent:f}),"aria-expanded":r,onClick:()=>i(p=>!p),children:[s.jsx("span",{className:`affairs-folder-tag-task-dot state-${c}`,"aria-hidden":"true"}),s.jsx("span",{className:"affairs-folder-tag-task-text",children:a("shell.affairsTagTaskHistoryShortTitle")}),s.jsx("span",{className:"affairs-folder-tag-task-badge",children:g>0?a("shell.affairsTagTaskHistoryRunningCount",{count:g}):c==="running"?`${f}%`:h})]}),s.jsx(mp,{open:r&&t.current!==null,className:"affairs-folder-tag-task-popover",anchorRef:t,popoverRef:n,role:"dialog",labelledBy:"affairs-tag-task-popover-title",maxWidth:360,gap:8,children:s.jsxs("div",{className:"affairs-folder-tag-task-popover-card",children:[s.jsxs("div",{className:"affairs-folder-tag-task-popover-header",children:[s.jsx("strong",{id:"affairs-tag-task-popover-title",children:a("shell.affairsTagTaskHistoryTitle")}),s.jsx("span",{children:a("shell.affairsTagTaskHistoryCount",{count:e.length})})]}),s.jsx("div",{className:"affairs-tag-task-history-list",children:e.map(p=>{const b=p.snapshot,y=(b==null?void 0:b.status)??"queued",x=(b==null?void 0:b.progress)??null,k=Math.max(0,Math.min(100,Math.round((x==null?void 0:x.percent)??(Or(y)?100:0)))),C=em(y),j=y6((x==null?void 0:x.phase)??null),H=x&&typeof x.current=="number"&&typeof x.total=="number"?a("shell.affairsFolderTagTaskProgressCount",{current:x.current,total:x.total}):a("shell.affairsFolderTagTaskPreparing"),_=tm(p.operation);return s.jsxs("div",{className:"affairs-tag-task-history-item",children:[s.jsxs("div",{className:"affairs-tag-task-history-item-header",children:[s.jsxs("div",{className:"affairs-tag-task-history-item-title",children:[s.jsx("span",{className:`affairs-folder-tag-task-dot state-${y}`,"aria-hidden":"true"}),s.jsx("strong",{children:a("shell.affairsFolderTagTaskTitle",{operation:_})})]}),s.jsx("span",{className:"affairs-tag-task-history-item-status",children:y==="running"?`${k}%`:C})]}),s.jsxs("div",{className:"affairs-folder-tag-task-popover-grid",children:[s.jsxs("div",{className:"affairs-folder-tag-task-popover-row",children:[s.jsx("span",{className:"affairs-folder-tag-task-popover-label",children:p.targetType==="folder"?a("shell.affairsFolderTagTaskFolderLabel"):a("shell.affairsTagTaskDocumentLabel")}),s.jsx("span",{className:"affairs-folder-tag-task-popover-value",children:p.targetLabel})]}),s.jsxs("div",{className:"affairs-folder-tag-task-popover-row",children:[s.jsx("span",{className:"affairs-folder-tag-task-popover-label",children:a("shell.affairsFolderTagTaskPhaseLabel")}),s.jsx("span",{className:"affairs-folder-tag-task-popover-value",children:j})]}),s.jsxs("div",{className:"affairs-folder-tag-task-popover-row",children:[s.jsx("span",{className:"affairs-folder-tag-task-popover-label",children:a("shell.affairsFolderTagTaskProgressLabel")}),s.jsx("span",{className:"affairs-folder-tag-task-popover-value",children:H})]})]}),s.jsx("div",{className:"affairs-folder-tag-task-progress-track","aria-hidden":"true",children:s.jsx("span",{className:"affairs-folder-tag-task-progress-fill",style:{width:`${k}%`}})}),s.jsxs("p",{className:"affairs-folder-tag-task-popover-detail",children:[(x==null?void 0:x.label)??a("shell.affairsFolderTagTaskPreparing"),x!=null&&x.detail?` · ${x.detail}`:""]}),b!=null&&b.errorMessage?s.jsx("p",{className:"affairs-folder-tag-task-popover-error",children:b.errorMessage}):null]},p.id)})})]})})]})}function GH(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("path",{d:"M8 3.5h6l4 4V20a1.5 1.5 0 0 1-1.5 1.5h-8A1.5 1.5 0 0 1 7 20V5A1.5 1.5 0 0 1 8.5 3.5z"}),s.jsx("path",{d:"M14 3.5V8h4"}),s.jsx("path",{d:"M10 12h6"}),s.jsx("path",{d:"M10 16h6"})]})}function YH(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M7 8.5h10"}),s.jsx("path",{d:"M7 12h10"}),s.jsx("path",{d:"M7 15.5h6.5"})]})}function JH(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"5.5",y:"6.5",width:"13",height:"10",rx:"2"}),s.jsx("path",{d:"M5.5 9.5h13"}),s.jsx("path",{d:"m9 12.3-1.8 1.7L9 15.7"}),s.jsx("path",{d:"m15 12.3 1.8 1.7-1.8 1.7"})]})}function XH(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M10 8.5c-1.2 0-2 .8-2 2v1c0 .9-.4 1.5-1 1.8.6.3 1 .9 1 1.8v1c0 1.2.8 2 2 2"}),s.jsx("path",{d:"M14 8.5c1.2 0 2 .8 2 2v1c0 .9.4 1.5 1 1.8-.6.3-1 .9-1 1.8v1c0 1.2-.8 2-2 2"})]})}function QH(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"m9.5 9.5-3 3 3 3"}),s.jsx("path",{d:"m14.5 9.5 3 3-3 3"}),s.jsx("path",{d:"m13 8-2 9"})]})}function ZH(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"m8 8.5 4 4 4-4"}),s.jsx("path",{d:"M12 12.5v4"}),s.jsx("path",{d:"M8.5 17h7"})]})}function eU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M7.5 15.5v-7h2.4a2.2 2.2 0 1 1 0 4.4H7.5"}),s.jsx("path",{d:"M12.5 15.5v-7h2.3a2.8 2.8 0 0 1 0 5.6h-2.3"}),s.jsx("path",{d:"M18 8.5h-3.8v7"})]})}function tU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"m6.8 8.5 1.3 7 2.3-4.7 2.2 4.7 1.4-7"}),s.jsx("path",{d:"M16.8 8.5h.1"})]})}function nU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"6.5",y:"7",width:"11",height:"10",rx:"1.8"}),s.jsx("path",{d:"M10.2 7v10"}),s.jsx("path",{d:"M13.9 7v10"}),s.jsx("path",{d:"M6.5 10.3h11"}),s.jsx("path",{d:"M6.5 13.7h11"})]})}function sU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"5.5",y:"6.5",width:"13",height:"9",rx:"2"}),s.jsx("path",{d:"M12 15.5v3"}),s.jsx("path",{d:"M9 18.5h6"}),s.jsx("path",{d:"M8.5 10h7"})]})}function rU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"6",y:"7",width:"12",height:"10",rx:"2"}),s.jsx("circle",{cx:"10",cy:"10.5",r:"1.3"}),s.jsx("path",{d:"m8 15 2.7-2.7a1.6 1.6 0 0 1 2.3 0L16 15"})]})}function iU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M10 7h4"}),s.jsx("path",{d:"M10 10h4"}),s.jsx("path",{d:"M10 13h4"}),s.jsx("path",{d:"M12 7v10"}),s.jsx("rect",{x:"8",y:"6.5",width:"8",height:"11",rx:"1.8"})]})}function aU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"m10 8-3.5 4 3.5 4"}),s.jsx("path",{d:"m14 8 3.5 4-3.5 4"})]})}function oU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("ellipse",{cx:"12",cy:"8",rx:"4.5",ry:"2.3"}),s.jsx("path",{d:"M7.5 8v4c0 1.3 2 2.3 4.5 2.3s4.5-1 4.5-2.3V8"}),s.jsx("path",{d:"M7.5 12v4c0 1.3 2 2.3 4.5 2.3s4.5-1 4.5-2.3v-4"})]})}function lU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M10 16a1.8 1.8 0 1 1-3.6 0c0-1 .8-1.8 1.8-1.8H10z"}),s.jsx("path",{d:"M10 16V7l7-1.5v8.7a1.8 1.8 0 1 1-3.6 0c0-1 .8-1.8 1.8-1.8H17"})]})}function cU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"6",y:"7",width:"10",height:"10",rx:"2"}),s.jsx("path",{d:"m16 10 3-1.5v7L16 14"}),s.jsx("path",{d:"m10 10.5 3 1.8-3 1.7z"})]})}function uU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("circle",{cx:"9",cy:"8.5",r:"2.5"}),s.jsx("circle",{cx:"15",cy:"8.5",r:"2.5"}),s.jsx("circle",{cx:"9",cy:"14.5",r:"2.5"}),s.jsx("path",{d:"M15 11v6a2.5 2.5 0 0 0 0-5z"})]})}function dU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M7.5 17 12 7l4.5 10"}),s.jsx("path",{d:"M9 13.5h6"})]})}function fU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M7 6.8A2.8 2.8 0 0 1 9.8 4H17v15.5H9.8A2.8 2.8 0 0 0 7 22Z"}),s.jsx("path",{d:"M17 4v15.5"}),s.jsx("path",{d:"M9.8 8.5H14"})]})}function Ff(e="grid"){return s.jsxs("span",{className:e==="row"?"affairs-folder-shape row":"affairs-folder-shape",children:[s.jsx("span",{className:"affairs-folder-tab-shape"}),s.jsx("span",{className:"affairs-folder-body-shape"})]})}function _f(e,t="grid"){const n=Ip(e);return s.jsxs("span",{className:t==="row"?`affairs-document-sheet row tone-${n.tone}`:`affairs-document-sheet tone-${n.tone}`,children:[s.jsx("span",{className:"affairs-document-fold"}),s.jsx("span",{className:"affairs-document-glyph",children:hU(n.kind)}),s.jsx("span",{className:"affairs-document-lines"}),s.jsx("span",{className:"affairs-document-badge",children:n.badge})]})}function hU(e){switch(e){case"markdown":case"text":return s.jsx(YH,{});case"web":return s.jsx(JH,{});case"json":return s.jsx(XH,{});case"xml":return s.jsx(QH,{});case"yaml":return s.jsx(ZH,{});case"pdf":return s.jsx(eU,{});case"word":return s.jsx(tU,{});case"spreadsheet":return s.jsx(nU,{});case"presentation":return s.jsx(sU,{});case"image":return s.jsx(rU,{});case"archive":return s.jsx(iU,{});case"code":return s.jsx(aU,{});case"database":return s.jsx(oU,{});case"audio":return s.jsx(lU,{});case"video":return s.jsx(cU,{});case"design":return s.jsx(uU,{});case"font":return s.jsx(dU,{});case"ebook":return s.jsx(fU,{});default:return s.jsx(GH,{})}}function mU({open:e,onClose:t}){const{binding:n}=Qn(),r=Hn();return n?r.isMobile?s.jsx(zi,{open:e,title:a("shell.affairsLibraryConfigTitle"),description:a("shell.affairsLibraryConfigDescription"),height:"three-quarter",kind:"form",onClose:t,children:s.jsx(xx,{onCancel:t,onSaved:t})}):s.jsx(Qr,{open:e,title:a("shell.affairsLibraryConfigTitle"),description:a("shell.affairsLibraryConfigDescription"),size:"regular",layout:"form",className:"affairs-library-settings-modal",onClose:t,children:s.jsx(xx,{onCancel:t,onSaved:t})}):null}function pU(e){return{id:`draft-rule-${e}-${Math.random().toString(36).slice(2,8)}`,relation:"and",ruleType:"file_name_contains",matcher:{keyword:""},enabled:!0,priority:e}}function gU(e){return e.map((t,n)=>({...t,matcher:{...t.matcher},priority:Number.isFinite(t.priority)?t.priority:n})).sort((t,n)=>t.priority-n.priority)}function bU(e){var t,n;switch(e.ruleType){case"file_name_contains":case"file_content_contains":return{keyword:String(e.matcher.keyword??"").trim()};case"file_extension_in":return{extensions:(Array.isArray(e.matcher.extensions)?(e.matcher.extensions??[]).join(", "):String(e.matcher.extensionsText??"")).split(/[,,\n]/g).map(i=>i.trim().toLowerCase()).filter(Boolean).map(i=>i.startsWith(".")?i:`.${i}`)};case"modified_time_between":{const r=e.matcher;return{start:((t=r.start)==null?void 0:t.trim())||null,end:((n=r.end)==null?void 0:n.trim())||null}}case"document_path_in_folder":return{folderPath:String(e.matcher.folderPath??"").trim()||"."};default:return{}}}function yU(e){switch(e){case"file_name_contains":case"file_content_contains":return{keyword:""};case"file_extension_in":return{extensions:[]};case"modified_time_between":return{start:"",end:""};case"document_path_in_folder":return{folderPath:"."};default:return{}}}function xU(e){switch(e){case"and":return a("shell.affairsTagSmartRuleRelationAnd");case"or":return a("shell.affairsTagSmartRuleRelationOr");case"not":return a("shell.affairsTagSmartRuleRelationNot");default:return e}}function kU(e){switch(e){case"file_name_contains":return a("shell.affairsTagSmartRuleTypeFileNameContains");case"file_content_contains":return a("shell.affairsTagSmartRuleTypeFileContentContains");case"file_extension_in":return a("shell.affairsTagSmartRuleTypeFileExtensionIn");case"modified_time_between":return a("shell.affairsTagSmartRuleTypeModifiedTimeBetween");case"document_path_in_folder":return a("shell.affairsTagSmartRuleTypeDocumentPathInFolder");default:return e}}function wU(){const{workspaceId:e,tagManagementOpen:t,closeTagManagement:n,managedTags:r,selectedManagedTag:i,selectManagedTag:o,saveManagedTag:l,deleteManagedTag:c,requestFullTagRecompute:u,fullTagRecomputeTaskMonitor:f}=Qn(),h=Hn(),{showToast:m}=Vn(),[g,p]=d.useState("create-root"),[b,y]=d.useState(""),[x,k]=d.useState(""),[C,j]=d.useState([]),[H,_]=d.useState(!1),[T,P]=d.useState(!1),[z,L]=d.useState(null),R=d.useMemo(()=>(Array.isArray(r)?r:[]).filter(Xh),[r]),K=d.useMemo(()=>WH(R),[R]),E=d.useMemo(()=>Wj(K),[K]),D=i&&Xh(i)?i:null,te=d.useMemo(()=>R.find(pe=>pe.id===(D==null?void 0:D.id))??null,[D==null?void 0:D.id,R]),V=g==="edit"?(D==null?void 0:D.id)??null:null,ee=d.useMemo(()=>E.filter(({tag:pe})=>$H(pe,D)),[E,D]),U=(f==null?void 0:f.snapshot)??null,he=U?em(U.status):a("shell.affairsTagRecoveryStatusIdle"),X=(U==null?void 0:U.progress)??null,I=Math.max(0,Math.min(100,Number((X==null?void 0:X.percent)??0))),xe=(X==null?void 0:X.current)!==void 0&&(X==null?void 0:X.current)!==null&&(X==null?void 0:X.total)!==void 0&&(X==null?void 0:X.total)!==null?a("shell.affairsFolderTagTaskProgressCount",{current:X.current,total:X.total}):a("shell.affairsTagRecoveryProgressIdle"),le=U?!Or(U.status):!1,M=(pe,fe)=>{p(pe),L(null),y(""),k(pe==="create-child"?(fe==null?void 0:fe.id)??"":""),j([])},de=()=>{M("create-root"),o(null)},Ne=()=>{D&&M("create-child",D)},ye=()=>{if(!D){de();return}p("edit"),y(D.name),k(D.parentId??""),j(gU(D.smartRules??[])),L(null)};d.useEffect(()=>{if(t){if(g==="edit"){ye();return}g==="create-child"&&k((D==null?void 0:D.id)??x)}},[g,x,D,t]),d.useEffect(()=>{if(t){if(D){p("edit");return}p("create-root")}},[D,t]);const Be=g==="edit"?a("shell.affairsTagEditorEditTitle"):g==="create-child"?a("shell.affairsTagEditorCreateChildTitle"):a("shell.affairsTagEditorCreateRootTitle"),We=g==="create-child"&&D?a("shell.affairsTagEditorCreateChildDescription",{tag:D.path}):null,Ce=(te==null?void 0:te.documentCount)??(D==null?void 0:D.documentCount)??0,ke=D?a("shell.affairsTagTreeDocumentCount",{count:Ce}):null,we=g==="edit"?a("shell.affairsTagUpdateSubmitAction"):a("shell.affairsTagCreateSubmitAction"),se=g==="edit",ce=C.map((pe,fe)=>({...pe,priority:fe,matcher:bU(pe)})),Y=async()=>{_(!0),L(null);try{const pe=await u();m({title:a("shell.affairsTagRecoveryAction"),description:pe.deduped?a("shell.affairsTagRecoveryQueuedDescription"):a("shell.affairsTagRecoveryStartedDescription"),tone:"success"})}catch(pe){L(pe instanceof Error?pe.message:a("shell.affairsTagRecoveryFailed"))}finally{_(!1)}},Te=s.jsxs("div",{className:"affairs-library-settings-form affairs-tag-management-shell",children:[s.jsxs("div",{className:"affairs-tag-management-layout",children:[s.jsxs(Jn,{className:"affairs-tag-management-tree-panel",heading:a("shell.affairsTagTreeSectionTitle"),children:[s.jsxs("div",{className:"affairs-tag-management-toolbar",children:[s.jsx("button",{type:"button",className:g==="create-root"?"secondary-button active":"secondary-button",disabled:T,onClick:de,children:a("shell.affairsTagCreateRootAction")}),s.jsx("button",{type:"button",className:g==="create-child"?"secondary-button active":"secondary-button",disabled:T||!D,onClick:Ne,children:a("shell.affairsTagCreateChildAction")})]}),K.length===0?s.jsx($i,{compact:!0,title:a("shell.affairsTagTreeEmpty"),description:a("shell.affairsTagTreeEmptyDescription")}):s.jsx("div",{className:"affairs-tag-management-tree",role:"tree","aria-label":a("shell.affairsTagTreeSectionTitle"),children:s.jsx($j,{nodes:K,selectedTagId:V,onSelect:pe=>{p("edit"),L(null),o(pe)}})})]}),s.jsxs("div",{className:"affairs-tag-management-editor-column",children:[s.jsxs(Jn,{className:"affairs-tag-management-editor",heading:Be,description:We??void 0,children:[g==="edit"&&D?s.jsxs("div",{className:"affairs-tag-management-editor-summary",children:[s.jsxs("div",{className:"affairs-tag-management-editor-summary-item",children:[s.jsx("span",{className:"affairs-tag-management-editor-summary-label",children:a("shell.affairsTagEditorPathLabel")}),s.jsx("strong",{className:"affairs-tag-management-editor-summary-value",children:D.path})]}),s.jsxs("div",{className:"affairs-tag-management-editor-summary-item",children:[s.jsx("span",{className:"affairs-tag-management-editor-summary-label",children:a("shell.affairsTagEditorDocumentCountLabel")}),s.jsx("strong",{className:"affairs-tag-management-editor-summary-value",children:ke})]})]}):null,s.jsx(Ot,{label:a("shell.affairsTagNameLabel"),children:s.jsx("input",{className:"affairs-tag-name-input",value:b,onChange:pe=>y(pe.target.value),placeholder:a("shell.affairsTagNamePlaceholder")})}),se?s.jsx(Ot,{label:a("shell.affairsTagParentLabel"),children:s.jsxs("select",{className:"affairs-tag-parent-select",value:x,onChange:pe=>k(pe.target.value),children:[s.jsx("option",{value:"",children:a("shell.affairsTagParentRootOption")}),ee.map(({tag:pe,depth:fe})=>s.jsx("option",{value:pe.id,children:`${" ".repeat(fe)}${pe.path}`},pe.id))]})}):null]}),s.jsxs(Jn,{className:"affairs-tag-management-editor",heading:a("shell.affairsTagSmartRulesSectionTitle"),children:[C.length===0?s.jsx("div",{className:"affairs-tag-management-empty-note",children:a("shell.affairsTagSmartRulesEmpty")}):s.jsx("div",{className:"affairs-tag-smart-rule-list",children:C.map((pe,fe)=>s.jsxs("div",{className:"affairs-tag-smart-rule-card",children:[s.jsxs("div",{className:"affairs-tag-smart-rule-header",children:[s.jsx("strong",{className:"affairs-tag-smart-rule-title",children:a("shell.affairsTagSmartRuleOrderHint",{index:fe+1})}),s.jsxs("div",{className:"affairs-tag-smart-rule-header-actions",children:[s.jsxs("label",{className:"affairs-tag-smart-rule-toggle","data-disabled":T?"true":void 0,children:[s.jsxs("span",{className:"affairs-tag-smart-rule-toggle-switch",children:[s.jsx("input",{className:"affairs-tag-smart-rule-toggle-input",type:"checkbox",checked:pe.enabled!==!1,disabled:T,onChange:W=>{const Me=W.target.checked;j(je=>je.map(Q=>Q.id===pe.id?{...Q,enabled:Me}:Q))}}),s.jsx("span",{className:"affairs-tag-smart-rule-toggle-track","aria-hidden":"true",children:s.jsx("span",{className:"affairs-tag-smart-rule-toggle-thumb"})})]}),s.jsx("span",{className:"affairs-tag-smart-rule-toggle-label",children:a("shell.affairsTagSmartRuleEnabledLabel")})]}),s.jsx("button",{type:"button",className:"secondary-button",disabled:T,onClick:()=>{j(W=>W.filter(Me=>Me.id!==pe.id).map((Me,je)=>({...Me,priority:je})))},children:a("shell.affairsTagSmartRuleRemoveAction")})]})]}),s.jsxs("div",{className:"affairs-tag-smart-rule-top-row",children:[s.jsx(Ot,{label:a("shell.affairsTagSmartRuleRelationLabel"),className:"affairs-tag-smart-rule-field",children:s.jsx("select",{className:"affairs-tag-smart-rule-relation-select",value:pe.relation,disabled:T,onChange:W=>{const Me=W.target.value;j(je=>je.map(Q=>Q.id===pe.id?{...Q,relation:Me}:Q))},children:["and","or","not"].map(W=>s.jsx("option",{value:W,children:xU(W)},W))})}),s.jsx(Ot,{label:a("shell.affairsTagSmartRuleTypeLabel"),className:"affairs-tag-smart-rule-field",children:s.jsx("select",{className:"affairs-tag-smart-rule-type-select",value:pe.ruleType,disabled:T,onChange:W=>{const Me=W.target.value;j(je=>je.map(Q=>Q.id===pe.id?{...Q,ruleType:Me,matcher:yU(Me)}:Q))},children:["file_name_contains","file_content_contains","file_extension_in","modified_time_between","document_path_in_folder"].map(W=>s.jsx("option",{value:W,children:kU(W)},W))})})]}),s.jsxs("div",{className:"affairs-tag-smart-rule-value-row",children:[pe.ruleType==="file_name_contains"||pe.ruleType==="file_content_contains"?s.jsx(Ot,{label:a("shell.affairsTagSmartRuleKeywordLabel"),className:"affairs-tag-smart-rule-field",children:s.jsx("input",{value:String(pe.matcher.keyword??""),disabled:T,placeholder:a("shell.affairsTagSmartRuleKeywordPlaceholder"),onChange:W=>{const Me=W.target.value;j(je=>je.map(Q=>Q.id===pe.id?{...Q,matcher:{keyword:Me}}:Q))}})}):null,pe.ruleType==="file_extension_in"?s.jsx(Ot,{label:a("shell.affairsTagSmartRuleExtensionsLabel"),className:"affairs-tag-smart-rule-field",children:s.jsx("input",{value:Array.isArray(pe.matcher.extensions)?(pe.matcher.extensions??[]).join(", "):"",disabled:T,placeholder:a("shell.affairsTagSmartRuleExtensionsPlaceholder"),onChange:W=>{const Me=W.target.value.split(/[,,\n]/g).map(je=>je.trim()).filter(Boolean);j(je=>je.map(Q=>Q.id===pe.id?{...Q,matcher:{extensions:Me}}:Q))}})}):null,pe.ruleType==="modified_time_between"?s.jsxs(s.Fragment,{children:[s.jsx(Ot,{label:a("shell.affairsTagSmartRuleModifiedStartLabel"),className:"affairs-tag-smart-rule-field",children:s.jsx("input",{type:"datetime-local",value:String(pe.matcher.start??""),disabled:T,onChange:W=>{const Me=W.target.value;j(je=>je.map(Q=>Q.id===pe.id?{...Q,matcher:{...Q.matcher,start:Me}}:Q))}})}),s.jsx(Ot,{label:a("shell.affairsTagSmartRuleModifiedEndLabel"),className:"affairs-tag-smart-rule-field",children:s.jsx("input",{type:"datetime-local",value:String(pe.matcher.end??""),disabled:T,onChange:W=>{const Me=W.target.value;j(je=>je.map(Q=>Q.id===pe.id?{...Q,matcher:{...Q.matcher,end:Me}}:Q))}})})]}):null,pe.ruleType==="document_path_in_folder"?s.jsx(Ot,{label:a("shell.affairsTagSmartRuleFolderPathLabel"),className:"affairs-tag-smart-rule-field",children:s.jsx("input",{value:String(pe.matcher.folderPath??"."),disabled:T,placeholder:a("shell.affairsTagSmartRuleFolderPathPlaceholder"),onChange:W=>{const Me=W.target.value;j(je=>je.map(Q=>Q.id===pe.id?{...Q,matcher:{folderPath:Me}}:Q))}})}):null]})]},pe.id))}),s.jsx("button",{type:"button",className:"secondary-button",disabled:T,onClick:()=>{j(pe=>[...pe,pU(pe.length)])},children:a("shell.affairsTagSmartRuleAddAction")})]}),s.jsxs(Jn,{className:"affairs-tag-management-editor",heading:a("shell.affairsTagRecoverySectionTitle"),children:[s.jsxs("div",{className:"affairs-tag-recovery-status",children:[s.jsxs("div",{className:"affairs-tag-recovery-status-grid",children:[s.jsx("span",{className:"affairs-tag-recovery-status-label",children:a("shell.affairsTagRecoveryStatusLabel")}),s.jsx("span",{className:"affairs-tag-recovery-status-value",children:he}),s.jsx("span",{className:"affairs-tag-recovery-status-label",children:a("shell.affairsFolderTagTaskPhaseLabel")}),s.jsx("span",{className:"affairs-tag-recovery-status-value",children:(X==null?void 0:X.label)??a("shell.affairsTagRecoveryPhaseIdle")}),s.jsx("span",{className:"affairs-tag-recovery-status-label",children:a("shell.affairsFolderTagTaskProgressLabel")}),s.jsx("span",{className:"affairs-tag-recovery-status-value",children:xe})]}),s.jsx("div",{className:"affairs-folder-tag-task-progress-track affairs-tag-recovery-progress-track","aria-hidden":"true",children:s.jsx("span",{className:"affairs-folder-tag-task-progress-fill",style:{width:`${I}%`}})})]}),s.jsx("div",{className:"affairs-tag-management-batch-actions",children:s.jsx("button",{type:"button",className:"secondary-button",disabled:T||H||le,onClick:()=>void Y(),children:H||le?a("shell.affairsTagRecoveryRunningAction"):a("shell.affairsTagRecoveryAction")})}),U!=null&&U.errorMessage?s.jsx("span",{className:"affairs-binding-error",children:U.errorMessage}):null]}),g==="edit"&&D?s.jsx(Jn,{className:"affairs-tag-management-danger",heading:a("shell.affairsTagDangerZoneTitle"),description:a("shell.affairsTagDangerZoneDescription"),children:s.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:T,onClick:async()=>{if(typeof window>"u"||window.confirm(a("shell.affairsTagDeleteConfirm",{tag:D.path}))){P(!0),L(null);try{await c(D.id),de(),m({title:a("shell.affairsTagDeleteSuccess"),description:a("shell.affairsTagDeleteSuccessDescription"),tone:"success"})}catch(fe){L(fe instanceof Error?fe.message:a("shell.affairsTagDeleteFailed"))}finally{P(!1)}}},children:a("shell.affairsTagDeleteAction")})}):null]})]}),s.jsxs(Es,{className:"affairs-library-settings-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:T,onClick:n,children:a("shell.affairsTagCloseAction")}),s.jsx("button",{type:"button",className:"secondary-button",disabled:T,onClick:()=>{if(g==="edit"){ye();return}if(g==="create-child"){M("create-child",D);return}de()},children:g==="edit"?a("shell.affairsTagRevertAction"):a("shell.affairsTagResetFormAction")}),s.jsx("button",{type:"button",className:"secondary-button",disabled:T||!b.trim(),onClick:async()=>{P(!0),L(null);try{await l({tagId:g==="edit"?D==null?void 0:D.id:void 0,name:b.trim(),parentId:x||null,status:(D==null?void 0:D.status)??"active",smartRules:ce}),p("edit"),m({title:a("shell.affairsTagSaveSuccess"),description:a("shell.affairsTagSaveSuccessDescription"),tone:"success"})}catch(pe){L(pe instanceof Error?pe.message:a("shell.affairsTagSaveFailed"))}finally{P(!1)}},children:T?a("common.loading"):we})]}),z?s.jsx("span",{className:"affairs-binding-error",children:z}):null]});return h.isMobile?s.jsx(zi,{open:t,title:a("shell.affairsTagManagerTitle"),height:"three-quarter",kind:"form",onClose:n,children:Te}):s.jsx(Qr,{open:t,title:a("shell.affairsTagManagerTitle"),size:"wide",layout:"form",className:"affairs-library-settings-modal",onClose:n,children:Te})}function $j({nodes:e,selectedTagId:t,depth:n=0,onSelect:r}){return s.jsx("ul",{className:"affairs-tag-management-tree-list",children:e.map(i=>s.jsxs("li",{className:"affairs-tag-management-tree-node",role:"treeitem","aria-selected":t===i.tag.id,"data-depth":n,children:[s.jsx("button",{type:"button",className:t===i.tag.id?"affairs-tag-management-tree-button active":"affairs-tag-management-tree-button","aria-label":i.tag.path,onClick:()=>r(i.tag.id),children:s.jsx("span",{className:"affairs-tag-management-tree-button-main",children:s.jsx("span",{className:"affairs-tag-management-tree-main",children:s.jsx("span",{className:"affairs-tag-management-tree-name",children:i.tag.name})})})}),i.children.length>0?s.jsx($j,{nodes:i.children,selectedTagId:t,depth:n+1,onSelect:r}):null]},i.tag.id))})}function xx({onCancel:e,onSaved:t}){const{binding:n,libraryConfig:r,saveLibraryConfig:i,setLibraryEnabled:o}=Qn(),l=Hn(),{showToast:c}=Vn(),u=d.useId(),f=d.useId(),h=d.useMemo(()=>fi((r==null?void 0:r.allowedExtensions)??[]),[r==null?void 0:r.allowedExtensions]),m=h.join("|"),g=d.useMemo(()=>rN((r==null?void 0:r.includedHiddenPaths)??[]),[r==null?void 0:r.includedHiddenPaths]),p=g.join("|"),[b,y]=d.useState((r==null?void 0:r.mirrorRoot)??""),[x,k]=d.useState((r==null?void 0:r.folderOpenBehavior)==="single_click"?"single_click":"double_click"),[C,j]=d.useState(()=>Wx((r==null?void 0:r.allowedExtensions)??[])),[H,_]=d.useState(()=>g.join(`
840
+ `)),[T,P]=d.useState(""),[z,L]=d.useState(!1),[R,K]=d.useState(null);return d.useEffect(()=>{y((r==null?void 0:r.mirrorRoot)??""),k((r==null?void 0:r.folderOpenBehavior)==="single_click"?"single_click":"double_click"),j(Wx(h)),_(g.join(`
841
+ `)),P("")},[r==null?void 0:r.folderOpenBehavior,h,m,g,p,r==null?void 0:r.mirrorRoot]),n?s.jsxs("div",{className:"affairs-library-settings-form",children:[s.jsxs("div",{className:"affairs-library-config-section",children:[s.jsx("strong",{children:a("shell.affairsLibraryEnableLabel")}),s.jsx("p",{children:a("shell.affairsLibraryEnableHint")}),s.jsxs("div",{className:"affairs-library-settings-inline-actions",children:[s.jsx("span",{className:"affairs-inline-pill",children:n.enabled?a("shell.affairsLibraryEnabledState"):a("shell.affairsLibraryDisabledState")}),s.jsx("button",{type:"button",className:"secondary-button",disabled:z,onClick:async()=>{L(!0),K(null);try{await o(!n.enabled)}catch(E){K(E instanceof Error?E.message:a("shell.affairsLibraryEnableSaveFailed"))}finally{L(!1)}},children:z?a("common.loading"):n.enabled?a("shell.affairsLibraryDisableAction"):a("shell.affairsLibraryEnableAction")})]})]}),n.enabled?null:s.jsx("div",{className:"affairs-binding-hint",children:a("shell.affairsLibraryDisabledSummary")}),s.jsx(Ot,{label:a("shell.affairsLibraryMirrorRootLabel"),htmlFor:u,children:s.jsx("input",{id:u,value:b,onChange:E=>y(E.target.value),placeholder:a("shell.affairsLibraryMirrorRootPlaceholder")})}),s.jsx("div",{className:"affairs-library-settings-inline-actions",children:s.jsx("button",{type:"button",className:"secondary-button",disabled:z||!l.isDesktop,onClick:async()=>{if(!l.isDesktop)return;const E=await ha().fs.pickDirectory();!E.ok||!E.value||y(String(E.value).trim())},children:a("shell.affairsLibraryMirrorRootBrowseAction")})}),l.isDesktop?null:s.jsx("span",{className:"affairs-binding-hint",children:a("shell.affairsLibraryMirrorRootDesktopOnlyHint")}),s.jsx("div",{className:"affairs-library-config-section",children:s.jsxs("div",{className:"affairs-library-behavior-switch-row",children:[s.jsx("span",{className:"affairs-library-behavior-switch-title",children:a("shell.affairsLibraryFolderOpenBehaviorSwitchLabel")}),s.jsx(JB,{checked:x==="single_click",label:a("shell.affairsLibraryFolderOpenBehaviorSwitchLabel"),semanticRole:"switch",onChange:E=>k(E?"single_click":"double_click")})]})}),s.jsx(Ot,{label:a("shell.affairsLibraryIncludedHiddenPathsLabel"),htmlFor:f,description:a("shell.affairsLibraryIncludedHiddenPathsHint"),children:s.jsx("textarea",{id:f,value:H,onChange:E=>_(E.target.value),placeholder:a("shell.affairsLibraryIncludedHiddenPathsPlaceholder"),rows:4})}),s.jsxs(Ot,{label:a("shell.affairsLibraryAllowedExtensionsLabel"),description:a("shell.affairsLibraryAllowedExtensionsHint"),children:[s.jsx("div",{className:"affairs-extension-chip-list",children:Lq(C).map(E=>{const D=C.includes(E),te=fd.includes(E);return s.jsxs("button",{type:"button",className:D?te?"affairs-extension-chip active":"affairs-extension-chip active custom":te?"affairs-extension-chip":"affairs-extension-chip custom","aria-pressed":D,"data-selected":D?"true":"false",onClick:()=>{j(V=>V.includes(E)?V.filter(ee=>ee!==E):fi([...V,E]))},children:[s.jsx("span",{children:E}),te?null:s.jsx("span",{className:"affairs-extension-chip-badge",children:a("shell.affairsLibraryCustomExtensionBadge")})]},E)})}),s.jsxs("div",{className:"affairs-extension-manual-row",children:[s.jsx("input",{value:T,onChange:E=>P(E.target.value),placeholder:a("shell.affairsLibraryAllowedExtensionsCustomPlaceholder")}),s.jsx("button",{type:"button",className:"secondary-button",disabled:z,onClick:()=>{try{const E=hN(T);if(!E)throw new Error(a("shell.affairsLibraryAllowedExtensionsCustomInvalid"));j(D=>D.includes(E)?D:fi([...D,E])),P(""),K(null)}catch(E){K(E instanceof Error?E.message:a("shell.affairsLibraryAllowedExtensionsCustomInvalid"))}},children:a("shell.affairsLibraryAllowedExtensionsCustomAddAction")})]})]}),s.jsxs(Es,{className:"affairs-library-settings-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:z,onClick:e,children:a("common.cancel")}),s.jsx("button",{type:"button",className:"secondary-button",disabled:z,onClick:async()=>{L(!0),K(null);try{const E=b.trim()||null,D=fi(C),te=z6(H),V=Eq(h,D)?[]:D,U=await i({mirrorRoot:E,allowedExtensions:V,includedHiddenPaths:te,folderOpenBehavior:x==="single_click"?"single_click":"double_click"}),he=U==null?void 0:U.applyConfigStatus;c({title:a("shell.affairsLibraryConfigSaved"),description:vU(he),tone:(he==null?void 0:he.state)==="failed"?"warning":"success"}),t()}catch(E){K(E instanceof Error?E.message:a("shell.affairsLibraryConfigSaveFailed"))}finally{L(!1)}},children:z?a("common.loading"):a("shell.affairsLibraryConfigSaveAction")})]}),R?s.jsx("span",{className:"affairs-binding-error",children:R}):null]}):null}function vU(e){var t;if(e)return e.state==="failed"?((t=e.errorSummary)==null?void 0:t.trim())||a("shell.affairsLibraryConfigAppliedFailed"):e.state==="running"?a("shell.affairsLibraryConfigAppliedRunning"):a("shell.affairsLibraryConfigAppliedSuccess")}function Qh(e,t){const n=(e==null?void 0:e.trim())??"",r=t.trim().replace(/^\/+/,"");if(!n||!r)return null;const i=n.replace(/\/+$/g,"");return{absolutePath:`${i}/${r}`.replace(/\/{2,}/g,"/"),mirrorRoot:i}}function Mu(e,t){const n=(e==null?void 0:e.trim().replace(/\/+$/g,""))??"",r=t.trim().replace(/^\/+/,"");return!n||!r?null:`${n}/${r}`.replace(/\/{2,}/g,"/")}function Ks(e){return e.kind==="document"?e.record.filePath:e.entry.path}function Mc(e){return e.kind==="document"?e.record.displayName:e.entry.title}function Bf(e,t){return Mu(e,Ks(t))}function kx(e){return e.kind==="blank"?e.folderPath:e.kind==="folder"?e.entry.path:aN(e.record.filePath)}function SU(e,t,n){const r=t.trim()||a("shell.affairsLibraryUntitledFileName"),i=new Set(n.map(f=>f.path)),o=tu(e,r);if(!i.has(o))return o;const l=r.lastIndexOf("."),c=l>0?r.slice(0,l):r,u=l>0?r.slice(l):"";for(let f=2;f<1e3;f+=1){const h=tu(e,`${c} ${f}${u}`);if(!i.has(h))return h}return tu(e,`${c} ${Date.now()}${u}`)}function tu(e,t){const n=(e==null?void 0:e.trim().replace(/^\/+|\/+$/g,""))??"",r=t.trim().replace(/^\/+/,"");return n?`${n}/${r}`:r}function CU(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function jU(e){const{target:t}=e,n=[];return t.kind==="document"&&e.onPreview&&n.push({id:`preview:${t.record.id}`,label:a("shell.affairsLibraryContextPreview"),onSelect:e.onPreview}),(t.kind==="document"||t.kind==="folder")&&e.onOpen&&n.push({id:`open:${t.kind}:${Ks(t)}`,label:a("shell.affairsLibraryContextOpen"),onSelect:e.onOpen}),(t.kind==="document"||t.kind==="folder")&&e.onLocate&&n.push({id:`locate:${t.kind}:${Ks(t)}`,label:a("shell.affairsLibraryContextLocate"),onSelect:e.onLocate}),t.kind==="document"&&e.onOpenWithLocalApp&&n.push({id:`open-local-app:${t.record.id}`,label:a("shell.affairsLibraryOpenWithLocalAppAction"),onSelect:e.onOpenWithLocalApp}),t.kind==="document"&&e.onDownload&&n.push({id:`download:${t.record.id}`,label:a("shell.affairsLibraryContextDownload"),onSelect:e.onDownload}),t.kind!=="blank"&&n.push({id:`copy:${t.kind}:${Ks(t)}`,label:a("shell.affairsLibraryContextCopy"),items:[{id:`copy-file:${t.kind}`,label:a("shell.affairsLibraryContextCopyFile"),onSelect:()=>{var r;return(r=e.onCopyFile)==null?void 0:r.call(e)}},{id:`copy-file-name:${t.kind}`,label:a("shell.affairsLibraryContextCopyFileName"),onSelect:()=>{var r;return(r=e.onCopyFileName)==null?void 0:r.call(e)}},{id:`copy-absolute-path:${t.kind}`,label:a("shell.affairsLibraryContextCopyAbsolutePath"),disabled:!Mu(e.bindingRootDir,Ks(t)),onSelect:()=>{var r;return(r=e.onCopyAbsolutePath)==null?void 0:r.call(e)}},{id:`copy-relative-path:${t.kind}`,label:a("shell.affairsLibraryContextCopyRelativePath"),onSelect:()=>{var r;return(r=e.onCopyRelativePath)==null?void 0:r.call(e)}}]}),t.kind==="blank"&&(n.push({id:"new:blank",label:a("shell.affairsLibraryContextNew"),items:[{id:"new-directory",label:a("shell.affairsLibraryContextNewDirectory"),onSelect:()=>{var r;return(r=e.onCreateDirectory)==null?void 0:r.call(e)}},{id:"new-markdown",label:a("shell.affairsLibraryContextNewMarkdown"),onSelect:()=>{var r;return(r=e.onCreateMarkdownFile)==null?void 0:r.call(e)}},{id:"new-text",label:a("shell.affairsLibraryContextNewText"),onSelect:()=>{var r;return(r=e.onCreateTextFile)==null?void 0:r.call(e)}},{id:"new-custom",label:a("shell.affairsLibraryContextNewCustomFile"),onSelect:()=>{var r;return(r=e.onCreateCustomFile)==null?void 0:r.call(e)}}]}),n.push({id:"refresh:blank",label:a("shell.affairsLibraryContextRefresh"),onSelect:()=>{var r;return(r=e.onRefresh)==null?void 0:r.call(e)}})),(t.kind==="document"||t.kind==="folder")&&e.onCut&&n.push({id:`cut:${t.kind}:${Ks(t)}`,label:a("shell.affairsLibraryContextCut"),onSelect:e.onCut}),n.push({id:`paste:${t.kind==="blank"?"blank":Ks(t)}`,label:a("shell.affairsLibraryContextPaste"),disabled:!e.libraryClipboard,onSelect:()=>{var r;return(r=e.onPaste)==null?void 0:r.call(e)}}),(t.kind==="document"||t.kind==="folder")&&e.onDelete&&n.push({id:`delete:${t.kind}:${Ks(t)}`,label:a("shell.affairsLibraryContextDelete"),onSelect:e.onDelete}),(t.kind==="document"||t.kind==="folder")&&e.onOpenTagAssignment&&n.push({id:`tags:${t.kind}:${Ks(t)}`,label:a("shell.affairsLibraryContextTags"),onSelect:e.onOpenTagAssignment}),e.onProperties&&n.push({id:t.kind==="blank"?"properties:blank":`properties:${t.kind}:${Ks(t)}`,label:a("shell.affairsLibraryContextProperties"),onSelect:e.onProperties}),n}function NU(e){switch(e){case"directory":return a("shell.affairsLibraryCreateDirectoryDefaultName");case"markdown":return a("shell.affairsLibraryCreateMarkdownDefaultName");case"text":return a("shell.affairsLibraryCreateTextDefaultName");case"custom":return a("shell.affairsLibraryCreateCustomDefaultName");default:return a("shell.affairsLibraryUntitledFileName")}}function TU(e){switch(e){case"markdown":return`# ${a("shell.affairsLibraryCreateMarkdownHeading")}
842
+ `;case"text":case"custom":default:return""}}function wx(e){switch(e){case"directory":return a("shell.affairsLibraryContextNewDirectory");case"markdown":return a("shell.affairsLibraryContextNewMarkdown");case"text":return a("shell.affairsLibraryContextNewText");case"custom":return a("shell.affairsLibraryContextNewCustomFile");default:return a("common.unknown")}}function IU(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)n[r]=t.charCodeAt(r);return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}function AU(e,t){if(typeof document>"u")throw new Error(a("shell.affairsLibraryDownloadFailed"));const n=window.URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=e,document.body.append(r),r.click(),r.remove(),window.URL.revokeObjectURL(n)}async function RU(e,t){var n;if(!(t.isDesktop&&(await t.bridge.writeClipboardText(e)).ok)){if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText))try{await navigator.clipboard.writeText(e);return}catch{}if(!PU(e))throw new Error(a("shell.affairsLibraryCopyFailed"))}}function PU(e){if(typeof document>"u"||typeof document.execCommand!="function")return!1;const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(t)}}function Wf(e,t){return e instanceof rr||e instanceof Error?e.message:t}function MU({workspaceId:e,viewerState:t,onClose:n,onSaved:r}){return t?s.jsx(Hj,{workspaceId:e,filePath:t.filePath,windowTitle:t.title,chrome:"modal",officeDisplayMode:"default",open:!0,onClose:n,onSaved:r}):null}function EU({workspaceId:e,filePath:t,windowTitle:n,collapsed:r,loading:i,onToggleCollapsed:o}){return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"affairs-detail-viewer-header",onClick:o,"aria-expanded":!r,"aria-label":r?a("conversation.fileViewerExpand"):a("conversation.fileViewerCollapse"),title:r?a("conversation.fileViewerExpand"):a("conversation.fileViewerCollapse"),children:[s.jsx("h3",{className:"affairs-detail-viewer-title",children:a("conversation.fileViewerWindowTitle")}),s.jsx("span",{className:"affairs-detail-viewer-toggle","aria-hidden":"true",children:s.jsx(zj,{collapsed:r})})]}),r?null:s.jsx("div",{className:"affairs-detail-viewer-body",children:i?s.jsx("div",{className:"affairs-stage-empty compact",children:a("common.loading")}):s.jsx(Hj,{workspaceId:e,filePath:t,windowTitle:n,chrome:"window",officeDisplayMode:"reading",open:!0,onClose:()=>{},onSaved:()=>{}})})]})}function zj({collapsed:e}){return s.jsx("svg",{viewBox:"0 0 16 16",width:"14",height:"14",fill:"none","aria-hidden":"true",children:e?s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 12.5h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),s.jsx("path",{d:"M5.25 8.75 8 6l2.75 2.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),s.jsx("path",{d:"M8 6v4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}):s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 12.5h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),s.jsx("path",{d:"M5.25 7.25 8 10l2.75-2.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),s.jsx("path",{d:"M8 6v4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})})}function Hj({workspaceId:e,filePath:t,windowTitle:n,chrome:r,officeDisplayMode:i,open:o,onClose:l,onSaved:c}){const u=d.useMemo(()=>(f,h)=>ym(f,h,{officeDisplayMode:i}),[i]);return s.jsx(vp,{workspaceId:e,filePath:t,open:o,chrome:r==="window"?"inline":r,windowTitle:n,onClose:l,onSaved:c,previewLoader:u,saveHandler:async({workspaceId:f,filePath:h,content:m,expectedVersion:g})=>{await Wa(f,{opType:"write",srcPath:h,content:m,expectedVersion:g})},officeDisplayMode:i})}function LU({mobile:e,target:t,busy:n,onClose:r,onConfirm:i}){const o=a("shell.affairsLibraryDeleteConfirmDescription"),l=Ks(t),c=t.kind==="folder"?a("shell.affairsLibraryDeleteFolderConfirm",{path:l}):a("shell.affairsLibraryDeleteDocumentConfirm",{path:l}),u=s.jsxs(Es,{children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:n,onClick:r,children:a("common.cancel")}),s.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:n,onClick:i,children:n?a("shell.affairsLibraryDeleteSubmitting"):a("shell.affairsLibraryDeleteConfirmAction")})]});return e?s.jsx(zi,{open:!0,title:a("shell.affairsLibraryDeleteConfirmTitle"),description:o,height:"auto",kind:"action",dismissible:!n,showHandle:!0,showCancelButton:!1,footer:u,onClose:r,children:s.jsx("p",{className:"workbench-section-empty",children:c})}):s.jsx(Qr,{open:!0,title:a("shell.affairsLibraryDeleteConfirmTitle"),description:o,size:"compact",layout:"confirm",dismissible:!n,footer:u,onClose:r,children:s.jsx("p",{className:"workbench-section-empty",children:c})})}function Zh({workspaceId:e,context:t}){var E,D,te;const{butlerStore:n,rememberConversationSession:r,reloadAgentConversationSessions:i}=Qn(),o=Zt(n,V=>V.initialized),l=Zt(n,V=>V.loading),c=Zt(n,V=>V.profile),u=Zt(n,V=>V.activeProvider),f=Zt(n,V=>V.controlSession),h=Zt(n,V=>V.capabilities),m=Zt(n,V=>V.messages),g=Zt(n,V=>V.historyState),p=Zt(n,V=>V.loadingOlderMessages),b=Zt(n,V=>V.hasOlderMessages),y=Zt(n,V=>V.runtimeHasActiveRun),x=Zt(n,V=>V.runtimeCanInterrupt),k=Zt(n,V=>V.contextUsage),C=Zt(n,V=>V.permissionRequests),j=Zt(n,V=>V.sending),[H,_]=d.useState(null),T=t?a("shell.affairsAssistantPlaceholder",{title:t.title??a("common.unknown")}):a("shell.affairsAssistantPlaceholderEmpty"),P=to(u)?u:to(c==null?void 0:c.providerId)?c.providerId:"codex",z=d.useMemo(()=>Lj(P),[P]),L=!!((D=(E=f==null?void 0:f.session)==null?void 0:E.sessionId)!=null&&D.trim())||m.length>0,R=d.useMemo(()=>DU(t),[t]),K=(t==null?void 0:t.objectType)==="document";return s.jsxs("section",{className:"affairs-assistant-panel",children:[t?s.jsx("section",{className:"workbench-section-block affairs-detail-block affairs-assistant-context-block",children:s.jsxs("div",{className:K?"affairs-assistant-context-card compact":"affairs-assistant-context-card","data-object-type":t.objectType,children:[s.jsx("div",{className:"affairs-assistant-context-icon","data-tone":R.tone,children:R.badge?s.jsx("span",{children:R.badge}):OU(R.iconKind)}),s.jsx("div",{className:"affairs-assistant-context-copy",children:K?s.jsx("h3",{children:t.title}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"affairs-assistant-context-topline",children:s.jsx("span",{className:"affairs-inline-pill subtle",children:R.label})}),s.jsx("h3",{children:t.title}),s.jsx("p",{children:t.sourceRef||t.summary||a("shell.affairsAssistantContextFallback")}),t.summary&&t.summary!==t.sourceRef?s.jsx("span",{className:"affairs-assistant-context-summary",children:t.summary}):null]})})]})}):L?null:s.jsx("section",{className:"workbench-section-block affairs-detail-block affairs-assistant-context-block",children:s.jsxs("div",{className:"affairs-assistant-context-card empty","data-object-type":"empty",children:[s.jsx("div",{className:"affairs-assistant-context-icon","data-tone":"neutral",children:s.jsx(Uj,{})}),s.jsxs("div",{className:"affairs-assistant-context-copy",children:[s.jsx("div",{className:"affairs-assistant-context-topline",children:s.jsx("span",{className:"affairs-inline-pill subtle",children:a("shell.affairsAssistantTitle")})}),s.jsx("h3",{children:a("shell.affairsAssistantTitle")}),s.jsx("p",{children:a("shell.affairsAssistantPlaceholderEmpty")})]})]})}),s.jsx(Np,{requests:C,replyingRequestId:H,onReply:async(V,ee)=>{_(V);try{await n.replyPermissionRequest(V,ee)}finally{_(null)}}}),s.jsx("div",{className:"affairs-assistant-timeline",children:s.jsx(td,{sessionId:(te=f==null?void 0:f.session)==null?void 0:te.sessionId,items:bo({messages:m}),historyState:g,loadingOlderMessages:p,hasOlderMessages:b,provider:u,onLoadOlderMessages:()=>{n.loadOlderMessages()},onRetryMessage:V=>{n.retryMessage(V)}})}),s.jsx("div",{className:"affairs-assistant-composer",children:s.jsx(id,{capabilities:h??z,draftStorageId:`affairs-assistant:${e}:${(t==null?void 0:t.objectId)??"empty"}`,placeholder:T,hasActiveRun:!!y||j,canInterrupt:x??!1,contextUsage:k,isSubmitting:j||l||!o,isRunning:!!y||j,onInterrupt:async()=>{await n.interrupt()},onSend:async(V,ee)=>{var X;!o&&typeof n.initialize=="function"&&await n.initialize();const U=to(n.getState().activeProvider)?n.getState().activeProvider:P;U&&n.getState().activeProvider!==U&&await n.switchProvider(U),await n.sendMessage(`${oN(t)}${V}`,{model:(ee==null?void 0:ee.model)??null,reasoningLevel:(ee==null?void 0:ee.reasoningLevel)??null,permissionMode:null}),await i();const he=((X=n.getState().controlSession)==null?void 0:X.session)??null;he&&r({kind:"agent",session:he,bootstrapMessages:[]})}})})]})}function Uj(){return s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M12 3.5 14 9l5.5 2-5.5 2L12 18.5 10 13 4.5 11 10 9 12 3.5Z"})})}function DU(e){if(!e)return{badge:null,iconKind:"spark",label:a("shell.affairsAssistantTitle"),tone:"neutral"};if(e.objectType==="document"){const t=Ip(e.sourceRef??e.title??"");return{badge:t.badge,iconKind:"spark",label:a("shell.affairsObjectTypeDocument"),tone:t.tone}}return e.objectType==="todo"?{badge:null,iconKind:"todo",label:a("shell.affairsTodoNav"),tone:"green"}:e.objectType==="workbench"?{badge:null,iconKind:"todo",label:a("shell.affairsWorkbenchNav"),tone:"blue"}:e.objectType==="automation"?{badge:null,iconKind:"automation",label:a("shell.affairsAutomationNav"),tone:"purple"}:{badge:null,iconKind:"spark",label:a("shell.affairsAssistantTitle"),tone:"neutral"}}function OU(e){switch(e){case"todo":return s.jsx(_U,{});case"automation":return s.jsx(BU,{});case"spark":default:return s.jsx(Uj,{})}}function FU(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9","aria-hidden":"true",children:[s.jsx("path",{d:"M4 7.5A2.5 2.5 0 0 1 6.5 5H10l2 2h5.5A2.5 2.5 0 0 1 20 9.5v8A2.5 2.5 0 0 1 17.5 20h-11A2.5 2.5 0 0 1 4 17.5z"}),s.jsx("path",{d:"M4 9h16"})]})}function _U(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9","aria-hidden":"true",children:[s.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"3"}),s.jsx("path",{d:"m8.5 11 2 2 5-5"})]})}function BU(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9","aria-hidden":"true",children:[s.jsx("path",{d:"M12 3v4"}),s.jsx("path",{d:"M12 17v4"}),s.jsx("path",{d:"M4.93 4.93l2.83 2.83"}),s.jsx("path",{d:"M16.24 16.24l2.83 2.83"}),s.jsx("path",{d:"M3 12h4"}),s.jsx("path",{d:"M17 12h4"}),s.jsx("path",{d:"M4.93 19.07l2.83-2.83"}),s.jsx("path",{d:"M16.24 7.76l2.83-2.83"}),s.jsx("circle",{cx:"12",cy:"12",r:"3.5"})]})}function WU(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9","aria-hidden":"true",children:[s.jsx("path",{d:"M6.5 5h11A2.5 2.5 0 0 1 20 7.5v7A2.5 2.5 0 0 1 17.5 17H9l-4 3V7.5A2.5 2.5 0 0 1 7.5 5Z"}),s.jsx("path",{d:"M9 10h6"}),s.jsx("path",{d:"M9 13h4"})]})}function $U(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9","aria-hidden":"true",children:[s.jsx("rect",{x:"4",y:"5",width:"7",height:"6",rx:"1.5"}),s.jsx("rect",{x:"13",y:"5",width:"7",height:"10",rx:"1.5"}),s.jsx("rect",{x:"4",y:"13",width:"7",height:"6",rx:"1.5"}),s.jsx("rect",{x:"13",y:"17",width:"7",height:"2",rx:"1"})]})}function zU(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),s.jsx("line",{x1:"9",y1:"4",x2:"9",y2:"20"}),s.jsx("polyline",{points:"11 9 14 12 11 15"})]})}function HU(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9","aria-hidden":"true",children:[s.jsx("path",{d:"M4.5 12a7.5 7.5 0 1 0 2.2-5.3",strokeLinecap:"round"}),s.jsx("path",{d:"M4.5 5.5v4h4",strokeLinecap:"round",strokeLinejoin:"round"}),s.jsx("path",{d:"M12 8.25v4.25l2.75 1.75",strokeLinecap:"round",strokeLinejoin:"round"})]})}function qj(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[s.jsx("path",{d:"M12 5v14",strokeLinecap:"round"}),s.jsx("path",{d:"M5 12h14",strokeLinecap:"round"})]})}function UU(){return s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[s.jsx("path",{d:"m12 20 7-7-3-3-7 7-1 4z",strokeLinecap:"round",strokeLinejoin:"round"}),s.jsx("path",{d:"m14.5 8.5 3 3",strokeLinecap:"round",strokeLinejoin:"round"})]})}function qU(){return s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9","aria-hidden":"true",children:[s.jsx("path",{d:"M9 5.75H8a3.25 3.25 0 0 0-3.25 3.25V16A3.25 3.25 0 0 0 8 19.25h8A3.25 3.25 0 0 0 19.25 16v-1",strokeLinecap:"round",strokeLinejoin:"round"}),s.jsx("path",{d:"m13.2 7.55 3.25-3.25a1.6 1.6 0 0 1 2.27 2.27l-3.25 3.25-3.4.85z",strokeLinecap:"round",strokeLinejoin:"round"})]})}function Dp(){return s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[s.jsx("path",{d:"M18 6 6 18",strokeLinecap:"round"}),s.jsx("path",{d:"m6 6 12 12",strokeLinecap:"round"})]})}function VU(){return s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:s.jsx("path",{d:"m5 12 4.2 4.2L19 6.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function KU(e){return e===a("shell.affairsWorkbenchDefaultTabTitle")?a("shell.affairsWorkbenchDefaultTabShortTitle"):e}function GU(e){if(e.type==="todo")return a("shell.affairsWorkbenchWidgetTodoHint");if(e.type==="automation")return a("shell.affairsWorkbenchWidgetAutomationHint");const t=vj(e);return t==="app"?a("shell.affairsWorkbenchWidgetHtmlAppHint"):t==="stat"?a("shell.affairsWorkbenchWidgetHtmlStatHint"):a("shell.affairsWorkbenchWidgetHtmlEmbedHint")}function YU(e,t,n){return e.type==="todo"?a("shell.affairsWorkbenchWidgetCountValue",{count:t}):e.type==="automation"?a("shell.affairsWorkbenchWidgetCountValue",{count:n}):a("shell.affairsWorkbenchHtmlWidgetBadge")}function JU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"10",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 1 1 8 0v3",strokeLinecap:"round"})]})}function XU(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"10",rx:"2"}),s.jsx("path",{d:"M15 11V8a4 4 0 0 0-7.5-2",strokeLinecap:"round"})]})}function QU({className:e}){const{activeSection:t}=Qn(),{layoutLocked:n,toggleDashboardLayoutLocked:r}=Op();return t!=="workbench"?null:s.jsx("button",{type:"button",className:e??"workbench-nav-toolbar-button","aria-label":n?a("shell.affairsWorkbenchUnlockLayoutAction"):a("shell.affairsWorkbenchLockLayoutAction"),title:n?a("shell.affairsWorkbenchUnlockLayoutAction"):a("shell.affairsWorkbenchLockLayoutAction"),"aria-pressed":!n,onClick:r,children:n?s.jsx(JU,{}):s.jsx(XU,{})})}function ZU(){const{filteredTodoRecords:e,automationRecords:t,automationRuns:n,selectSidebarNode:r,workspaceId:i,navigationGroups:o,globalLibraryBinding:l}=Qn(),{dashboardState:c,activeDashboardTab:u,layoutLocked:f,selectDashboardTab:h,addDashboardTab:m,renameDashboardTab:g,removeDashboardTab:p,addDashboardWidget:b,updateDashboardWidgetConfig:y,setDashboardWidgetLayout:x,removeDashboardWidget:k,resetActiveDashboardLayout:C}=Op(),{showToast:j}=Vn(),[H,_]=d.useState(!1),[T,P]=d.useState(null),[z,L]=d.useState(""),[R,K]=d.useState("todo"),[E,D]=d.useState("embed"),te=d.useMemo(()=>jj(l,i),[l,i]),V=d.useMemo(()=>Cj(o,i,te),[te,o,i]),ee=d.useMemo(()=>Nj({currentWorkspaceId:i,currentLibraryWorkspace:te,options:V}),[te,V,i]),[U,he]=d.useState(ee),X=d.useMemo(()=>Tj(V,U),[U,V]),[I,xe]=d.useState(""),[le,M]=d.useState(""),[de,Ne]=d.useState(!1),[ye,Be]=d.useState(null),We=d.useRef(null),Ce=d.useRef(null),ke=d.useMemo(()=>new Map(((u==null?void 0:u.layout)??[]).map(fe=>[fe.widgetId,fe])),[u]);d.useEffect(()=>{H||(he(ee),xe(""))},[ee,H]),d.useEffect(()=>{f&&(P(null),L(""))},[f]);const we=d.useMemo(()=>u?[...u.widgets].sort((fe,W)=>{const Me=ke.get(fe.id),je=ke.get(W.id),Q=(Me==null?void 0:Me.y)??0,ge=(je==null?void 0:je.y)??0,Oe=(Me==null?void 0:Me.x)??0,$e=(je==null?void 0:je.x)??0;return Q!==ge?Q-ge:Oe!==$e?Oe-$e:u.widgets.findIndex(Ve=>Ve.id===fe.id)-u.widgets.findIndex(Ve=>Ve.id===W.id)}):[],[u,ke]),se=d.useCallback(()=>{Ce.current=null,Be(null)},[]);d.useEffect(()=>{f&&H&&_(!1)},[H,f]),d.useEffect(()=>{f&&ye&&se()},[ye,f,se]),d.useEffect(()=>{function fe(Me){const je=Ce.current;if(!je)return;Me.preventDefault();const Q=Math.round((Me.clientX-je.startX)/je.columnPitch),ge=Math.round((Me.clientY-je.startY)/je.rowPitch);if(je.kind==="move"){const Ve={x:Math.max(0,Math.min(br-je.startLayout.w,je.startLayout.x+Q)),y:Math.max(0,je.startLayout.y+ge),w:je.startLayout.w,h:je.startLayout.h},G=Hz(Ve,je.snapGuides);x(je.widgetId,{x:Math.max(0,Math.min(br-je.startLayout.w,Math.round(G.x))),y:Math.max(0,Math.round(G.y))});return}const Oe={x:je.startLayout.x,y:je.startLayout.y,w:je.resizeMode==="x"||je.resizeMode==="xy"?Math.max(je.startLayout.minW??1,Math.min(br-je.startLayout.x,je.startLayout.w+Q)):je.startLayout.w,h:je.resizeMode==="y"||je.resizeMode==="xy"?Math.max(je.startLayout.minH??1,je.startLayout.h+ge):je.startLayout.h},$e=Uz(Oe,je.snapGuides,je.resizeMode);x(je.widgetId,{...je.resizeMode==="x"||je.resizeMode==="xy"?{w:Math.max(je.startLayout.minW??1,Math.min(br-je.startLayout.x,Math.round($e.w)))}:{},...je.resizeMode==="y"||je.resizeMode==="xy"?{h:Math.max(je.startLayout.minH??1,Math.round($e.h))}:{}})}function W(){se()}return window.addEventListener("pointermove",fe,{passive:!1}),window.addEventListener("pointerup",W),window.addEventListener("pointercancel",W),()=>{window.removeEventListener("pointermove",fe),window.removeEventListener("pointerup",W),window.removeEventListener("pointercancel",W)}},[x,se]);const ce=d.useCallback((fe,W,Me,je="xy")=>{var _e,nt;if(f||fe.button!==0)return;const Q=ke.get(W),ge=We.current;if(!Q||!ge)return;const Ve=(ge.getBoundingClientRect().width-Lf*(br-1))/br+Lf,G=ax+Lf,ve=zz((u==null?void 0:u.layout)??[],W);Ce.current={kind:Me,widgetId:W,startX:fe.clientX,startY:fe.clientY,startLayout:Q,columnPitch:Ve,rowPitch:G,resizeMode:je,snapGuides:ve},Be({widgetId:W,kind:Me}),(nt=(_e=fe.currentTarget).setPointerCapture)==null||nt.call(_e,fe.pointerId),fe.preventDefault(),fe.stopPropagation()},[u==null?void 0:u.layout,f,ke]),Y=d.useCallback(async fe=>{if(fe.preventDefault(),!de){Ne(!0);try{if(R==="todo")b({type:"todo",title:le.trim()||a("shell.affairsTodoAllFilter"),config:{filter:"all",view:"compact"}});else if(R==="automation")b({type:"automation",title:le.trim()||a("shell.affairsAutomationStageTitle"),config:{scope:"all",view:"list"}});else{const W=await Zz(X,I);b({type:"html",variant:E,title:Ki(W.path,le),sourceRef:{kind:(X==null?void 0:X.kind)==="affairs_library"?"affairs_library_html":"html_shortcut",workspaceId:(X==null?void 0:X.workspaceId)??i,sourceId:W.path},config:{}})}M(""),he(ee),xe(""),_(!1)}catch(W){j({title:Sl(W,a("shell.affairsWorkbenchAddWidgetFailed")),tone:"error"})}finally{Ne(!1)}}},[b,I,U,E,X,R,j,de,le,ee,i]);if(!u)return s.jsx("div",{className:"affairs-stage-empty",children:a("shell.affairsWorkbenchEmpty")});const Te=fe=>{P(fe.id),L(fe.title)},pe=()=>{T&&(g(T,z),P(null),L(""))};return s.jsxs("div",{className:"affairs-dashboard-shell",children:[s.jsxs("div",{className:"affairs-dashboard-tabbar-shell",children:[s.jsxs("div",{className:"affairs-dashboard-tabbar",role:"tablist","aria-label":a("shell.affairsWorkbenchNav"),children:[c.tabs.map(fe=>s.jsxs("div",{role:"tab","aria-selected":fe.id===u.id,className:fe.id===u.id?"affairs-dashboard-tab active":"affairs-dashboard-tab",children:[s.jsx("button",{type:"button",className:"affairs-dashboard-tab-main",onClick:()=>h(fe.id),children:T===fe.id?s.jsx("input",{autoFocus:!0,className:"affairs-dashboard-tab-input",value:z,onChange:W=>L(W.currentTarget.value),onBlur:pe,onKeyDown:W=>{if(W.key==="Enter"){W.preventDefault(),pe();return}W.key==="Escape"&&(W.preventDefault(),P(null),L(""))},"aria-label":a("shell.affairsWorkbenchRenameTabAction")}):s.jsx("span",{className:"affairs-dashboard-tab-title",children:KU(fe.title)})}),f?null:s.jsxs("div",{className:"affairs-dashboard-tab-actions",children:[s.jsx("button",{type:"button",className:"affairs-dashboard-tab-action","aria-label":a("shell.affairsWorkbenchRenameTabAction"),title:a("shell.affairsWorkbenchRenameTabAction"),onClick:W=>{W.stopPropagation(),Te(fe)},children:s.jsx(UU,{})}),s.jsx("button",{type:"button",className:"affairs-dashboard-tab-action","aria-label":a("shell.affairsWorkbenchDeleteTabAction"),title:a("shell.affairsWorkbenchDeleteTabAction"),onClick:W=>{W.stopPropagation(),p(fe.id)},disabled:c.tabs.length<=1,children:s.jsx(Dp,{})})]})]},fe.id)),f?null:s.jsx("button",{type:"button",className:"affairs-dashboard-add-tab","aria-label":a("shell.affairsWorkbenchAddTabAction"),title:a("shell.affairsWorkbenchAddTabAction"),onClick:m,children:s.jsx(qj,{})})]}),s.jsx("div",{className:"affairs-dashboard-tabbar-actions",children:s.jsx(QU,{})})]}),s.jsxs("section",{className:"workbench-section-block affairs-dashboard-canvas-block",children:[f?null:s.jsx("div",{className:"affairs-dashboard-canvas-header affairs-dashboard-canvas-header-with-actions",children:s.jsxs("div",{className:"affairs-dashboard-canvas-actions",children:[s.jsx("button",{type:"button",className:"workbench-secondary-button",onClick:()=>{_(fe=>{const W=!fe;return W&&(he(ee),xe("")),W})},children:H?a("shell.affairsWorkbenchCancelAction"):a("shell.affairsWorkbenchAddWidgetAction")}),s.jsx("button",{type:"button",className:"workbench-secondary-button",onClick:C,disabled:we.length===0,children:a("shell.affairsWorkbenchResetLayoutAction")})]})}),!f&&H?s.jsxs("form",{className:"affairs-dashboard-editor-panel",onSubmit:Y,children:[s.jsx("div",{className:"affairs-dashboard-editor-types",role:"tablist","aria-label":a("shell.affairsWorkbenchAddWidgetAction"),children:["todo","automation","html"].map(fe=>s.jsx("button",{type:"button",className:fe===R?"affairs-dashboard-editor-type active":"affairs-dashboard-editor-type",onClick:()=>{K(fe),fe==="html"&&(he(ee),xe(""))},children:fe==="todo"?a("shell.affairsWorkbenchWidgetTypeTodo"):fe==="automation"?a("shell.affairsWorkbenchWidgetTypeAutomation"):a("shell.affairsWorkbenchWidgetTypeHtml")},fe))}),s.jsxs("label",{className:"affairs-dashboard-inline-field",htmlFor:"affairs-dashboard-widget-title",children:[s.jsx("span",{children:a("shell.affairsWorkbenchWidgetTitleField")}),s.jsx("input",{id:"affairs-dashboard-widget-title",className:"affairs-dashboard-inline-input",value:le,onChange:fe=>M(fe.currentTarget.value),placeholder:a("shell.affairsWorkbenchWidgetTitlePlaceholder")})]}),R==="html"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"affairs-dashboard-inline-field-group",children:[s.jsxs("label",{className:"affairs-dashboard-inline-field",htmlFor:"affairs-dashboard-widget-source-workspace",children:[s.jsx("span",{children:a("shell.affairsWorkbenchHtmlSourceWorkspaceField")}),s.jsx("select",{id:"affairs-dashboard-widget-source-workspace",className:"affairs-dashboard-inline-select",value:U,onChange:fe=>{he(fe.currentTarget.value),xe("")},children:V.map(fe=>s.jsx("option",{value:fe.value,children:fe.label},fe.value))})]}),s.jsx("p",{className:"affairs-dashboard-inline-help",children:a("shell.affairsWorkbenchHtmlSourceWorkspaceHelper")}),(X==null?void 0:X.kind)==="affairs_library"?s.jsx("p",{className:"affairs-dashboard-inline-help",children:a("shell.affairsWorkbenchHtmlSourceWorkspaceCurrentLibraryHelper",{path:X.rootDir})}):null]}),s.jsxs("div",{className:"affairs-dashboard-inline-field-group",children:[s.jsxs("div",{className:"affairs-dashboard-inline-field",children:[s.jsx("span",{children:a("shell.affairsWorkbenchHtmlVariantField")}),s.jsx("div",{className:"affairs-dashboard-editor-types",role:"tablist","aria-label":a("shell.affairsWorkbenchHtmlVariantField"),children:["app","stat","embed"].map(fe=>s.jsx("button",{type:"button",className:fe===E?"affairs-dashboard-editor-type active":"affairs-dashboard-editor-type",onClick:()=>D(fe),children:fe==="app"?a("shell.affairsWorkbenchHtmlVariantApp"):fe==="stat"?a("shell.affairsWorkbenchHtmlVariantStat"):a("shell.affairsWorkbenchHtmlVariantEmbed")},fe))})]}),s.jsx("p",{className:"affairs-dashboard-inline-help",children:a("shell.affairsWorkbenchHtmlVariantHelper")})]}),s.jsx(Vj,{sourceOption:X,workspaceLabel:X==null?void 0:X.label,inputId:"affairs-dashboard-widget-source",value:I,onChange:xe,mode:"html",label:a("shell.affairsWorkbenchHtmlSourceSelectField"),placeholder:a("shell.affairsWorkbenchHtmlSourceSelectPlaceholder"),helpText:a("shell.affairsWorkbenchHtmlSourceHelper"),listFailedMessage:a("shell.affairsWorkbenchHtmlSourceListFailed")})]}):null,s.jsx("div",{className:"affairs-dashboard-inline-actions",children:s.jsx("button",{type:"submit",className:"secondary-button",disabled:de,children:de?a("common.loading"):a("shell.affairsWorkbenchConfirmAddWidgetAction")})})]}):null,we.length===0?s.jsx("section",{className:"workbench-empty-guide surface-card affairs-dashboard-empty-guide",children:s.jsx("div",{className:"workbench-empty-main affairs-conversation-empty-main",children:s.jsxs("div",{className:"workbench-empty-copy affairs-conversation-empty-copy",children:[s.jsx("h2",{children:a("shell.affairsWorkbenchCanvasEmptyTitle")}),s.jsx("p",{className:"workbench-empty-body",children:a("shell.affairsWorkbenchCanvasEmptyBody")})]})})}):s.jsx("div",{ref:We,className:"affairs-dashboard-canvas-grid",children:we.map(fe=>{const W=ke.get(fe.id),Me={gridColumnStart:((W==null?void 0:W.x)??0)+1,gridColumnEnd:`span ${Math.max(1,Math.min(br,(W==null?void 0:W.w)??6))}`,gridRowStart:((W==null?void 0:W.y)??0)+1,gridRowEnd:`span ${Math.max(1,(W==null?void 0:W.h)??5)}`,minHeight:`${Math.max(180,((W==null?void 0:W.h)??5)*ax)}px`};return s.jsx(e6,{widget:fe,style:Me,editable:!f,todoCount:e.length,automationCount:t.length,gestureKind:(ye==null?void 0:ye.widgetId)===fe.id?ye.kind:null,onMovePointerDown:je=>ce(je,fe.id,"move"),onResizePointerDown:(je,Q)=>ce(je,fe.id,"resize",Q),onRemove:()=>k(fe.id),children:s.jsx(n6,{widget:fe,workspaceId:i,todoRecords:e,automationRecords:t,automationRuns:n,onUpdateConfig:je=>y(fe.id,je),onOpenTodo:()=>r("workbench:todo:all"),onOpenAutomation:()=>r(t[0]?`workbench:automation:item:${t[0].id}`:"workbench:overview")})},fe.id)})})]})]})}function e6({widget:e,style:t,editable:n,todoCount:r,automationCount:i,gestureKind:o,children:l,onMovePointerDown:c,onResizePointerDown:u,onRemove:f}){return s.jsxs("section",{className:["affairs-dashboard-widget",n?"editable":"locked",o==="move"?"dragging":"",o==="resize"?"resizing":""].filter(Boolean).join(" "),style:t,children:[s.jsxs("div",{className:n?"affairs-dashboard-widget-header affairs-dashboard-widget-header-draggable":"affairs-dashboard-widget-header",onPointerDown:n?c:void 0,children:[s.jsx("div",{className:"affairs-dashboard-widget-header-main",children:s.jsxs("div",{children:[s.jsx("h3",{children:e.title}),s.jsx("p",{children:GU(e)})]})}),s.jsxs("div",{className:"affairs-dashboard-widget-header-meta",children:[s.jsx("span",{className:"affairs-inline-pill",children:YU(e,r,i)}),n?s.jsx("div",{className:"affairs-dashboard-widget-toolbar",children:s.jsx("button",{type:"button",className:"affairs-dashboard-toolbar-icon-button danger",title:a("shell.affairsWorkbenchRemoveWidgetAction"),"aria-label":a("shell.affairsWorkbenchRemoveWidgetAction"),onPointerDown:h=>h.stopPropagation(),onClick:f,children:s.jsx(Dp,{})})}):null]})]}),s.jsx("div",{className:"affairs-dashboard-widget-body",children:l}),n?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"affairs-dashboard-resize-edge right","aria-hidden":"true",onPointerDown:h=>u(h,"x")}),s.jsx("div",{className:"affairs-dashboard-resize-edge bottom","aria-hidden":"true",onPointerDown:h=>u(h,"y")}),s.jsx("div",{className:"affairs-dashboard-resize-corner","aria-hidden":"true",onPointerDown:h=>u(h,"xy")})]}):null]})}class t6 extends d.Component{constructor(t){super(t),this.state={hasError:!1,message:null}}static getDerivedStateFromError(t){return{hasError:!0,message:t.message}}render(){return this.state.hasError?s.jsxs("div",{className:"affairs-dashboard-widget-error",children:[s.jsx("strong",{children:this.props.fallbackTitle}),s.jsx("p",{children:this.state.message||a("shell.affairsWorkbenchWidgetErrorBody")})]}):this.props.children}}function n6({widget:e,workspaceId:t,todoRecords:n,automationRecords:r,automationRuns:i,onUpdateConfig:o,onOpenTodo:l,onOpenAutomation:c}){return s.jsx(t6,{fallbackTitle:a("shell.affairsWorkbenchWidgetErrorTitle"),children:e.type==="todo"?s.jsx(s6,{widget:e,todoRecords:n,onUpdateConfig:o,onOpen:l}):e.type==="automation"?s.jsx(r6,{widget:e,automationRecords:r,automationRuns:i,onUpdateConfig:o,onOpen:c}):s.jsx(i6,{widget:e,workspaceId:t})})}function s6({widget:e,todoRecords:t,onUpdateConfig:n,onOpen:r}){const i=e.config.view==="detail"?"detail":"compact";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"affairs-dashboard-widget-inline-tabs",role:"tablist","aria-label":a("shell.affairsWorkbenchWidgetTodoViewLabel"),children:[s.jsx("button",{type:"button",className:i==="compact"?"affairs-dashboard-widget-inline-tab active":"affairs-dashboard-widget-inline-tab",onClick:()=>n({view:"compact"}),children:a("shell.affairsWorkbenchWidgetCompactView")}),s.jsx("button",{type:"button",className:i==="detail"?"affairs-dashboard-widget-inline-tab active":"affairs-dashboard-widget-inline-tab",onClick:()=>n({view:"detail"}),children:a("shell.affairsWorkbenchWidgetDetailView")})]}),s.jsxs("div",{className:"affairs-dashboard-widget-preview-list",children:[t.slice(0,i==="detail"?4:3).map(o=>s.jsxs("div",{className:"affairs-dashboard-widget-preview-item affairs-dashboard-widget-preview-item-stack",children:[s.jsxs("div",{children:[s.jsx("strong",{children:o.title}),s.jsx("span",{children:o.statusLabel})]}),i==="detail"?s.jsx("p",{children:o.summary||o.detail||o.sourceDescription}):null]},o.id)),t.length===0?s.jsx("div",{className:"affairs-stage-empty compact",children:a("shell.affairsTodoEmpty")}):null]}),s.jsx("button",{type:"button",className:"secondary-button",onClick:r,children:a("shell.affairsWorkbenchWidgetOpenTodoAction")})]})}function r6({widget:e,automationRecords:t,automationRuns:n,onUpdateConfig:r,onOpen:i}){const o=e.config.view==="recent"?"recent":"list";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"affairs-dashboard-widget-inline-tabs",role:"tablist","aria-label":a("shell.affairsWorkbenchWidgetAutomationViewLabel"),children:[s.jsx("button",{type:"button",className:o==="list"?"affairs-dashboard-widget-inline-tab active":"affairs-dashboard-widget-inline-tab",onClick:()=>r({view:"list"}),children:a("shell.affairsWorkbenchWidgetAutomationListView")}),s.jsx("button",{type:"button",className:o==="recent"?"affairs-dashboard-widget-inline-tab active":"affairs-dashboard-widget-inline-tab",onClick:()=>r({view:"recent"}),children:a("shell.affairsWorkbenchWidgetAutomationRecentView")})]}),o==="recent"?s.jsxs("div",{className:"affairs-dashboard-widget-preview-list",children:[n.slice(0,3).map(l=>{const c=t.find(u=>u.id===l.automationId);return s.jsxs("div",{className:"affairs-dashboard-widget-preview-item affairs-dashboard-widget-preview-item-stack",children:[s.jsxs("div",{children:[s.jsx("strong",{children:(c==null?void 0:c.title)||a("shell.affairsWorkbenchWidgetAutomationRunFallbackTitle")}),s.jsx("span",{children:lN(l.status)})]}),s.jsx("p",{children:l.summary||(c==null?void 0:c.summary)||a("shell.affairsAutomationEmpty")})]},l.id)}),n.length===0?s.jsx("div",{className:"affairs-stage-empty compact",children:a("shell.affairsAutomationEmpty")}):null]}):s.jsxs("div",{className:"affairs-dashboard-widget-preview-list",children:[t.slice(0,3).map(l=>s.jsxs("div",{className:"affairs-dashboard-widget-preview-item affairs-dashboard-widget-preview-item-stack",children:[s.jsxs("div",{children:[s.jsx("strong",{children:l.title}),s.jsx("span",{children:l.statusLabel})]}),s.jsx("p",{children:l.summary||l.lastRunSummary||l.triggerLabel})]},l.id)),t.length===0?s.jsx("div",{className:"affairs-stage-empty compact",children:a("shell.affairsAutomationEmpty")}):null]}),s.jsx("button",{type:"button",className:"secondary-button",onClick:i,children:a("shell.affairsWorkbenchWidgetOpenAutomationAction")})]})}function i6({widget:e,workspaceId:t}){var p,b,y;const{showToast:n}=Vn(),[r,i]=d.useState(null),[o,l]=d.useState(!0),[c,u]=d.useState(null),f=((b=(p=e.sourceRef)==null?void 0:p.sourceId)==null?void 0:b.trim())??"",h=tH(e.sourceRef,t),m=((y=e.sourceRef)==null?void 0:y.kind)??"html_shortcut";d.useEffect(()=>{let x=!1;if(!f){i(null),l(!1),u(a("shell.affairsWorkbenchHtmlSourceMissing"));return}return l(!0),u(null),(m==="affairs_library_html"?$u(h,f).then(k=>k.previewUrl?{previewUrl:k.previewUrl}:Promise.reject(new Error(a("shell.affairsWorkbenchHtmlSourceLoadFailed")))):zu(h,f)).then(k=>{x||i(Jh(k.previewUrl))}).catch(k=>{x||u(Sl(k,a("shell.affairsWorkbenchHtmlSourceLoadFailed")))}).finally(()=>{x||l(!1)}),()=>{x=!0}},[m,f,h]);const g=d.useCallback(()=>{r&&window.open(r,"_blank","noopener,noreferrer")},[r]);return o?s.jsx("div",{className:"affairs-stage-empty compact",children:a("common.loading")}):c?s.jsxs("div",{className:"affairs-dashboard-widget-error",children:[s.jsx("strong",{children:a("shell.affairsWorkbenchHtmlSourceLoadFailed")}),s.jsx("p",{children:c})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"affairs-dashboard-html-meta",children:[s.jsx("span",{children:f}),s.jsx("button",{type:"button",className:"affairs-dashboard-toolbar-button",onClick:()=>{if(!r){n({title:a("shell.affairsWorkbenchHtmlSourceLoadFailed"),tone:"error"});return}g()},children:a("shell.affairsWorkbenchOpenHtmlAction")})]}),s.jsx(a6,{src:r,workspaceId:h,title:e.title})]})}function a6({src:e,workspaceId:t,title:n}){const r=d.useRef(null);return d.useEffect(()=>{if(!e)return;const i=RC({iframe:r.current,workspaceId:t});function o(l){i.onMessage(l)}return window.addEventListener("message",o),()=>{window.removeEventListener("message",o),i.dispose()}},[e,t]),e?s.jsx("div",{className:"affairs-dashboard-html-frame-shell",children:s.jsx("iframe",{ref:r,className:"affairs-dashboard-html-frame",title:n,src:e,sandbox:Vz(e)},e)}):s.jsx("div",{className:"affairs-stage-empty compact",children:a("shell.affairsWorkbenchHtmlSourceMissing")})}const vx="__shortcut_root__",o6=12,l6=18;function Vj({sourceOption:e,workspaceLabel:t,inputId:n,value:r,onChange:i,mode:o="file",helpText:l,label:c,placeholder:u,listFailedMessage:f}){const[h,m]=d.useState(!1),[g,p]=d.useState([]),[b,y]=d.useState({}),[x,k]=d.useState([]),[C,j]=d.useState([]),[H,_]=d.useState(null),[T,P]=d.useState(r),z=d.useRef(0);d.useEffect(()=>{h||P(r)},[h,r]);const L=d.useCallback(async X=>{if(!e){p([]),y({});return}const I=X??vx,xe=z.current;j(le=>le.includes(I)?le:[...le,I]);try{if(e.kind==="affairs_library"){const le=await GT(e.workspaceId,{path:X??null,limit:1e3});if(z.current!==xe)return;const M=(le.items??[]).filter(de=>de.kind==="directory"||o==="file"||ou(de.path));X?y(de=>({...de,[X]:M})):p(M)}else{const le=await U0(e.workspaceId,X||void 0);if(z.current!==xe)return;const M=(le.items??[]).filter(de=>de.kind==="directory"||o==="file"||ou(de.path));X?y(de=>({...de,[X]:M})):p(M)}_(null)}catch(le){if(z.current!==xe)return;_(Sl(le,f??a("shell.affairsShortcutRailSourceListFailed")))}finally{z.current===xe&&j(le=>le.filter(M=>M!==I))}},[f,o,e]),R=d.useCallback(async()=>{z.current+=1,p([]),y({}),k([]),_(null),P(r),await L()},[L,r]);d.useEffect(()=>{h&&R()},[R,h]),d.useEffect(()=>{z.current+=1,m(!1),p([]),y({}),k([]),j([]),_(null),P(r)},[e,r]);const K=d.useCallback(async X=>{const I=x.includes(X)?x.filter(xe=>xe!==X):[...x,X];k(I),!x.includes(X)&&!b[X]&&await L(X)},[x,L,b]),E=d.useCallback(()=>{T&&(i(T),m(!1))},[i,T]),D=d.useCallback((X,I)=>s.jsx(s.Fragment,{children:X.map(xe=>{const le=xe.kind==="directory",M=le&&x.includes(xe.path),de=b[xe.path]??[],Ne=C.includes(xe.path),ye=T===xe.path;return s.jsxs("div",{className:"file-tree-node",children:[s.jsxs("button",{type:"button",className:"file-tree-item","data-kind":xe.kind,"data-selected":ye?"true":void 0,"aria-expanded":le?M:void 0,style:{paddingInlineStart:`${o6+I*l6}px`},onClick:()=>{if(le){K(xe.path);return}P(xe.path)},children:[s.jsx("span",{className:`file-tree-chevron${le?"":" is-hidden"}`,"aria-hidden":"true",children:s.jsx(u6,{expanded:M})}),le?s.jsx("span",{className:"affairs-shortcut-file-picker-folder-dot","aria-hidden":"true"}):s.jsx("span",{className:"git-tree-file-icon","data-kind":kz(xe.name),"aria-hidden":"true",children:xz(xe.name)}),s.jsx("span",{className:"file-tree-label",children:xe.name})]}),le&&M?s.jsx("div",{className:"file-tree-children",children:Ne&&!de.length?s.jsx("p",{className:"file-tree-empty",children:a("common.loading")}):de.length?D(de,I+1):s.jsx("p",{className:"file-tree-empty",children:a("conversation.filePanelEmptyDirectory")})}):null]},`${xe.kind}-${xe.path}`)})}),[x,C,T,K,b]),te=c??a("shell.affairsShortcutRailSourceSelectField"),V=u??a("shell.affairsShortcutRailSourceSelectPlaceholder"),ee=T||r||a("shell.affairsShortcutRailSourcePickerCurrentEmpty"),U=t||a("shell.affairsWorkbenchHtmlSourceWorkspaceCurrent"),he=C.includes(vx);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"affairs-dashboard-inline-field-group",children:[s.jsxs("label",{className:"affairs-dashboard-inline-field",htmlFor:n,children:[s.jsx("span",{children:te}),s.jsxs("button",{id:n,type:"button",className:"affairs-dashboard-inline-picker-button","data-empty":r?void 0:"true",onClick:()=>m(!0),children:[s.jsx("span",{className:"affairs-dashboard-inline-picker-button-value",children:r||V}),s.jsx("span",{className:"affairs-dashboard-inline-picker-button-icon","aria-hidden":"true",children:s.jsx(c6,{})})]})]}),s.jsx("p",{className:"affairs-dashboard-inline-help",children:l}),H?s.jsx("p",{className:"affairs-dashboard-inline-error",children:H}):null]}),s.jsx(ln,{open:h,title:a("shell.affairsShortcutRailSourcePickerTitle"),description:a("shell.affairsShortcutRailSourcePickerDescription"),size:"regular",bodyClassName:"affairs-shortcut-file-picker-modal-body",onClose:()=>m(!1),children:s.jsxs("div",{className:"affairs-shortcut-file-picker-modal",children:[s.jsx(Ot,{label:a("shell.affairsShortcutRailSourcePickerCurrentField"),description:U,children:s.jsx("div",{className:"affairs-shortcut-file-picker-selected",children:s.jsx("strong",{children:ee})})}),s.jsx(Jn,{heading:a("shell.affairsShortcutRailSourcePickerTreeTitle"),actions:H?s.jsx("button",{type:"button",className:"ghost-button",onClick:()=>{R()},children:a("shell.affairsShortcutRailSourcePickerRetryAction")}):null,children:s.jsx("div",{className:"affairs-shortcut-file-picker-tree",role:"tree","aria-label":a("shell.affairsShortcutRailSourcePickerTreeTitle"),children:he&&!g.length?s.jsx($i,{compact:!0,title:a("common.loading")}):g.length?D(g,0):s.jsx($i,{compact:!0,title:a("shell.affairsShortcutRailSourcePickerTreeEmpty"),description:H??a("shell.affairsShortcutRailSourcePickerTreeEmptyDescription"),action:H?s.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{R()},children:a("shell.affairsShortcutRailSourcePickerRetryAction")}):null})})}),s.jsxs(Es,{children:[s.jsx("button",{type:"button",className:"ghost-button",onClick:()=>m(!1),children:a("common.cancel")}),s.jsx("button",{type:"button",className:"secondary-button",disabled:!T,onClick:E,children:a("shell.affairsShortcutRailSourcePickerConfirmAction")})]})]})})]})}function c6(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("path",{d:"M9 18h6",strokeLinecap:"round"}),s.jsx("path",{d:"m8 10 4 4 4-4",strokeLinecap:"round",strokeLinejoin:"round"})]})}function u6({expanded:e}){return s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:e?s.jsx("path",{d:"M2 3.5 5 6.5l3-3",strokeLinecap:"round",strokeLinejoin:"round"}):s.jsx("path",{d:"M3.5 2 6.5 5l-3 3",strokeLinecap:"round",strokeLinejoin:"round"})})}function d6(){return s.jsxs("svg",{className:"affairs-stage-breadcrumb-home-icon",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.55",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M4.5 10.5 12 4.5l7.5 6"}),s.jsx("path",{d:"M6.75 9.75v8.75h10.5V9.75"}),s.jsx("path",{d:"M10.25 18.5v-4.75h3.5v4.75"})]})}function f6(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[s.jsx("rect",{x:"1.5",y:"1.5",width:"4",height:"4",rx:"1",fill:"currentColor"}),s.jsx("rect",{x:"8.5",y:"1.5",width:"4",height:"4",rx:"1",fill:"currentColor"}),s.jsx("rect",{x:"1.5",y:"8.5",width:"4",height:"4",rx:"1",fill:"currentColor"}),s.jsx("rect",{x:"8.5",y:"8.5",width:"4",height:"4",rx:"1",fill:"currentColor"})]})}function h6(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[s.jsx("rect",{x:"1.5",y:"2",width:"2.5",height:"2.5",rx:"0.8",fill:"currentColor"}),s.jsx("rect",{x:"1.5",y:"5.75",width:"2.5",height:"2.5",rx:"0.8",fill:"currentColor"}),s.jsx("rect",{x:"1.5",y:"9.5",width:"2.5",height:"2.5",rx:"0.8",fill:"currentColor"}),s.jsx("rect",{x:"5.5",y:"2.4",width:"7",height:"1.7",rx:"0.85",fill:"currentColor"}),s.jsx("rect",{x:"5.5",y:"6.15",width:"7",height:"1.7",rx:"0.85",fill:"currentColor"}),s.jsx("rect",{x:"5.5",y:"9.9",width:"7",height:"1.7",rx:"0.85",fill:"currentColor"})]})}function m6(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("path",{d:"M20 5v5h-5"}),s.jsx("path",{d:"M4 19v-5h5"}),s.jsx("path",{d:"M6.8 9A7 7 0 0 1 18 6.4L20 10"}),s.jsx("path",{d:"M17.2 15A7 7 0 0 1 6 17.6L4 14"})]})}function p6(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M4 5h16"}),s.jsx("path",{d:"M7 12h10"}),s.jsx("path",{d:"M10 19h4"}),s.jsx("path",{d:"M18 6l-4 4"}),s.jsx("path",{d:"M14 6l4 4"})]})}function g6(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82L4.21 7.1a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 8.92 4a1.65 1.65 0 0 0 1-1.51V2.4a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9c0 .66.39 1.25 1 1.51h.09a2 2 0 0 1 0 4h-.09c-.61.26-1 .85-1 1.49z"})]})}function b6(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("path",{d:"M4 7h10"}),s.jsx("path",{d:"M4 12h16"}),s.jsx("path",{d:"M4 17h12"}),s.jsx("circle",{cx:"17",cy:"7",r:"2"}),s.jsx("circle",{cx:"9",cy:"17",r:"2"})]})}function em(e){switch(e){case"running":return a("shell.affairsFolderTagTaskStatusRunning");case"succeeded":return a("shell.affairsFolderTagTaskStatusSucceeded");case"failed":return a("shell.affairsFolderTagTaskStatusFailed");case"cancelled":return a("shell.affairsFolderTagTaskStatusCancelled");case"timeout":return a("shell.affairsFolderTagTaskStatusTimeout");case"queued":default:return a("shell.affairsFolderTagTaskStatusQueued")}}function y6(e){switch(e){case"prepare":return a("shell.affairsFolderTagTaskPhasePrepare");case"recompute":return a("shell.affairsFolderTagTaskPhaseRecompute");case"write":return a("shell.affairsFolderTagTaskPhaseWrite");case"export":return a("shell.affairsFolderTagTaskPhaseExport");case"finished":return a("shell.affairsFolderTagTaskPhaseFinished");default:return a("shell.affairsFolderTagTaskPhasePrepare")}}function Kj(e){switch(e){case"attach":return a("shell.affairsFolderTagTaskOperationAttach");case"remove":return a("shell.affairsFolderTagTaskOperationRemove");default:return a("shell.affairsFolderTagTaskOperationUpdate")}}function tm(e){return Kj(e)}function x6(e,t){const n=new Set(e),r=new Set(t);let i=0,o=0;return r.forEach(l=>{n.has(l)||(i+=1)}),n.forEach(l=>{r.has(l)||(o+=1)}),i>0&&o===0?"attach":o>0&&i===0?"remove":"update"}function k6(e,t){const n=Date.now();return{taskId:`pending-folder-tag-${n}`,taskType:"affairs.library_tag_apply_bindings",key:`pending:${e}`,executionLane:"helper_process",status:"queued",source:"affairs_tag.save_folder_bindings",attempt:0,enqueuedAt:n,startedAt:null,finishedAt:null,timeoutMs:null,progress:{phase:"prepare",label:a("shell.affairsFolderTagTaskSubmitting",{operation:Kj(t)}),detail:a("shell.affairsFolderTagTaskSubmittingDetail"),current:0,total:1,percent:0,updatedAt:n}}}function Sx(e,t){return x6(e,t)}function Cx(e,t){return k6(e,t)}function jx(e,t){const n=Date.now(),r=`completed-tag-task-${n}`;return{taskId:(e==null?void 0:e.taskId)??r,taskType:(e==null?void 0:e.taskType)??"affairs.library_tag_apply_bindings",key:(e==null?void 0:e.key)??`completed:${r}`,executionLane:(e==null?void 0:e.executionLane)??"helper_process",source:(e==null?void 0:e.source)??"affairs_tag.completed_local",attempt:(e==null?void 0:e.attempt)??1,enqueuedAt:(e==null?void 0:e.enqueuedAt)??n,timeoutMs:(e==null?void 0:e.timeoutMs)??null,status:"succeeded",startedAt:(e==null?void 0:e.startedAt)??(e==null?void 0:e.enqueuedAt)??n,finishedAt:n,progress:{phase:"finished",label:a("shell.affairsFolderTagTaskSubmitting",{operation:tm(t)}),detail:a("shell.affairsFolderTagTaskPhaseFinished"),current:1,total:1,percent:100,updatedAt:n}}}function Or(e){return e==="succeeded"||e==="failed"||e==="cancelled"||e==="timeout"}function $f(e,t){return e===t?!0:!e||!t?!1:JSON.stringify(e)===JSON.stringify(t)}function Nx(e,t){return e===t?!0:!e||!t?!1:JSON.stringify(e)===JSON.stringify(t)}function Qn(){const e=d.useContext(Ij);if(!e)throw new Error("AffairsWorkbench components must be used inside AffairsWorkbenchProvider");return e}function Op(){const e=d.useContext(wj);if(!e)throw new Error("AffairsDashboard components must be used inside AffairsWorkbenchProvider");return e}function w6(e,t){return[...e].sort((n,r)=>r.updatedAt.localeCompare(n.updatedAt)).map(n=>{var r;return{id:n.documentId,title:n.title,displayName:_6(n.path),filePath:n.path,fullPath:t?`${t}/${n.path}`:null,summary:((r=n.summary)==null?void 0:r.trim())||a("shell.affairsAssistantContextFallback"),isFavorite:n.isFavorite,tags:n.tags,derivedTags:n.derivedTags,createdAt:n.createdAt??null,sizeBytes:typeof n.sizeBytes=="number"?n.sizeBytes:null,updatedAt:n.updatedAt}})}function v6(e){return[...e].sort((t,n)=>t.path.localeCompare(n.path,"zh-CN")).map(t=>({id:t.path,label:t.name,path:t.path,rootType:t.rootType,parentPath:t.parentPath,depth:t.depth,count:t.documentCount}))}const S6=new Set(["来源","主题","状态"]);function C6(e){return Gj(e.path)}function Gj(e){var r;const t=e.trim();if(!t)return!1;const n=((r=t.split("/")[0])==null?void 0:r.trim())??"";return!S6.has(n)}function j6(e){return[...e].sort((t,n)=>t.path.localeCompare(n.path,"zh-CN")).map(t=>({id:t.path,label:t.name,path:t.path,parentPath:t.parentPath,depth:t.path?t.path.split("/").length-1:0,directCount:t.directDocumentCount,count:t.documentCount,createdAt:t.createdAt??null,updatedAt:t.updatedAt??null}))}function N6(e,t){const n=new Map;e.forEach(o=>{n.set(o.path,{...o,children:[]})});const r=[];n.forEach(o=>{var l;if(o.parentPath&&n.has(o.parentPath)){(l=n.get(o.parentPath))==null||l.children.push(o);return}r.push(o)});const i=o=>{o.sort((l,c)=>T6(l,c,t)),o.forEach(l=>i(l.children))};return i(r),r}function Yj(e,t,n){return n?e.map(r=>({...r,count:t[r.path]??0,children:Yj(r.children,t,n)})):e}function T6(e,t,n){if(Tx(e)||Tx(t)){const o=I6(e,t);if(o!==0)return o}const r=(n[t.path]??0)-(n[e.path]??0);if(r!==0)return r;const i=t.count-e.count;return i!==0?i:e.label.localeCompare(t.label,"zh-CN")}function Tx(e){const t=e.rootType.trim().toLowerCase();return t==="时间"||t==="time"}function I6(e,t){const n=Ix(e),r=Ix(t);if(n!==null||r!==null){if(n===null)return 1;if(r===null)return-1;if(n!==r)return n-r}const i=Ax(e),o=Ax(t);if(i!==null||o!==null){if(i===null)return 1;if(o===null)return-1;if(i!==o)return o-i}return 0}function Ix(e){const t=e.path.trim(),n=t.startsWith("时间/")?t.slice(3):t;return n==="最近3天"?0:n==="最近7天"?1:n==="最近30天"?2:null}function Ax(e){const t=e.path.trim();if(t==="时间")return Number.MAX_SAFE_INTEGER;const r=(t.startsWith("时间/")?t.slice(3):t).split("/").filter(Boolean);if(r.length===0)return null;const i=r.map(o=>Number.parseInt(o,10));return i.some(o=>!Number.isFinite(o))?null:i.length===1?i[0]:i.length===2?i[0]*100+i[1]:i.length===3?i[0]*1e4+i[1]*100+i[2]:i.reduce((o,l)=>o*100+l,0)}function Jj(e,t,n){return e.length<=vl||n.includes(t)?e:e.slice(0,vl)}function A6(e,t){const n=[],r=(i,o)=>{i.slice(vl).some(u=>t===u.path||t.startsWith(`${u.path}/`))&&n.push(o),i.forEach(u=>{(t===u.path||t.startsWith(`${u.path}/`))&&r(u.children,u.path)})};return r(e,Yo),n}function Rx(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Xj(e){var r;const t=Array.isArray(e.selectedTagPaths)?e.selectedTagPaths.map(i=>i.trim()).filter(i=>i.length>0):[];if(t.length>0)return Array.from(new Set(t));const n=(r=e.selectedTagPath)==null?void 0:r.trim();return n?[n]:[]}function R6(e,t,n){const r=n.trim();if(!r)return[];const i=Px(e,r),o=t.includes(r),l=t.filter(c=>Px(e,c)!==i);return o?l:[...l,r]}function Px(e,t){var i;const n=t.trim();if(!n)return"";const r=e.find(o=>o.path===n);return(i=r==null?void 0:r.rootType)!=null&&i.trim()?r.rootType.trim():n.split("/")[0]??n}function P6(e,t,n){const r=new Map,i=new Set,o=new Set(t),l=u=>{for(const f of Zj(u))i.add(f)},c=u=>{r.set(u.path,u);const f=n[u.path]??0,m=t.some(b=>b===u.path||b.startsWith(`${u.path}/`)||u.path.startsWith(`${b}/`))||f>0;let g=!1;u.children.forEach(b=>{c(b)&&(g=!0)});const p=m||g||t.length===0;return p&&(i.add(u.path),o.has(u.path)&&l(u.path)),p};return e.forEach(u=>{c(u)}),{nodeMap:r,visiblePathSet:i}}function Qj(e,t){return e.filter(n=>t.has(n.path)).map(n=>({...n,children:Qj(n.children,t)}))}function Zj(e){const t=e.trim();if(!t)return[];const n=t.split("/"),r=[];for(let i=0;i<n.length-1;i+=1)r.push(n.slice(0,i+1).join("/"));return r}function Mx(e){if(typeof window>"u")return{};try{const t=window.localStorage.getItem(`${xj}${e}`);if(!t)return{};const n=JSON.parse(t);return{expandedPaths:Array.isArray(n.expandedPaths)?n.expandedPaths.filter(r=>typeof r=="string"):[],expandedOverflowPaths:Array.isArray(n.expandedOverflowPaths)?n.expandedOverflowPaths.filter(r=>typeof r=="string"):[],accessCounts:n.accessCounts&&typeof n.accessCounts=="object"?n.accessCounts:{}}}catch{return{}}}function M6(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(`${xj}${e}`,JSON.stringify({expandedPaths:t.expandedPaths??[],expandedOverflowPaths:t.expandedOverflowPaths??[],accessCounts:t.accessCounts??{}}))}catch{}}function eN(e){return`affairs.library.snapshot.${e}`}function tN(e){return`affairs.conversation.lightweight.sessions.${e}`}function nN(e){return`affairs.library.config.${e}`}function sN(e,t){var n,r,i;return["affairs.library.documents",e,t.browseMode,((n=t.selectedFolderPath)==null?void 0:n.trim())||".",Xj(t).join("|")||((r=t.selectedTagPath)==null?void 0:r.trim())||".",((i=t.selectedFavoriteId)==null?void 0:i.trim())||"."].join("::")}function Ex(e){return Br(eN(e),Ap)}function Ii(e,t){Rr(eN(e),t)}function Lx(e){return Br(nN(e),Ap)}function Ec(e,t){Rr(nN(e),t)}function Dx(e,t){return Br(sN(e,t),Ap)}function Do(e,t,n){Rr(sN(e,t),n)}function E6(e){return Br(tN(e),Oz)}function L6(e,t){Rr(tN(e),t)}function D6(e,t){if(e.length===0)return t;const n=new Set(e.map(i=>i.documentId)),r=[...e];for(const i of t)n.has(i.documentId)||(n.add(i.documentId),r.push(i));return r}function O6(e,t){return t}function F6(e,t){return{total:t.total,offset:0,limit:Math.max((e==null?void 0:e.limit)??0,t.limit),items:D6((e==null?void 0:e.items)??[],t.items),tagFacetCounts:t.tagFacetCounts??(e==null?void 0:e.tagFacetCounts)??{}}}function _6(e){const t=e.trim().replace(/\/+$/g,"");if(!t)return a("common.unknown");const n=t.split("/").filter(Boolean);return n[n.length-1]||t}function B6(e,t,n,r){return[e,t,(n==null?void 0:n.trim())||".","."].join("|")}function Pa(e,t){return e===t?!0:!e||!t||e.total!==t.total||e.offset!==t.offset||e.limit!==t.limit||JSON.stringify(e.tagFacetCounts??{})!==JSON.stringify(t.tagFacetCounts??{})||e.items.length!==t.items.length?!1:e.items.every((n,r)=>{const i=t.items[r];return!!i&&W6(n,i)})}function W6(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ai(e,t){return e===t?!0:!e||!t?!1:JSON.stringify(e)===JSON.stringify(t)}function Oo(e,t){return e===t?!0:!e||!t?!1:JSON.stringify(e)===JSON.stringify(t)}function zf(e,t){return e===t?!0:!e||!t?!1:JSON.stringify(e)===JSON.stringify(t)}function $6(e,t){return e===t?!0:!e||!t?!1:e.objectType===t.objectType&&e.objectId===t.objectId&&e.title===t.title&&e.summary===t.summary&&e.sourceRef===t.sourceRef&&e.assistantScope===t.assistantScope}function rN(e){return[...new Set(e.map(t=>String(t??"").trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/g,"")).filter(Boolean))].sort((t,n)=>t.localeCompare(n,"zh-Hans-CN"))}function z6(e){return rN(e.split(/\r?\n|,/).map(t=>t.trim()).filter(Boolean))}function H6(e,t,n){const r=Math.max(1,Math.ceil(Math.max(t,Lo)/Lo)),i=Math.max(0,Math.floor(n/Lo)-sx),o=Math.min(e,i+r+sx*2);return{startIndex:i,endIndex:o,offsetTop:i*Lo,totalHeight:e*Lo}}function Ox(e){const t=window.getComputedStyle(e),n=Number.parseFloat(t.paddingLeft||"0"),r=Number.parseFloat(t.paddingRight||"0");return Math.max(0,e.clientWidth-n-r)}function U6(e,t){const n=[...e];return n.sort((r,i)=>{if(r.kind!==i.kind)return r.kind==="folder"?-1:1;const o=t.direction==="asc"?1:-1;if(t.mode==="type"){const u=r.kind==="folder"?"folder":Fx(r.path),f=i.kind==="folder"?"folder":Fx(i.path),h=u.localeCompare(f,"zh-CN")*o;return h!==0?h:r.title.localeCompare(i.title,"zh-CN")}if(t.mode==="name")return r.title.localeCompare(i.title,"zh-CN")*o;if(t.mode==="size"){const u=r.kind==="folder"?-1:r.sizeBytes??-1,f=i.kind==="folder"?-1:i.sizeBytes??-1;return u!==f?(u-f)*o:r.title.localeCompare(i.title,"zh-CN")}if(t.mode==="createdAt"){const u=Date.parse(r.createdAt||"")||0,f=Date.parse(i.createdAt||"")||0;return u!==f?(u-f)*o:r.title.localeCompare(i.title,"zh-CN")}const l=Date.parse(r.updatedAt||"")||0,c=Date.parse(i.updatedAt||"")||0;return l!==c?(l-c)*o:r.title.localeCompare(i.title,"zh-CN")}),n}function iN(e){return{mode:e,direction:e==="name"||e==="type"?"asc":"desc"}}function Fp(e){switch(e){case"name":return"name";case"size":return"size";case"updatedAt":return"recent";case"type":return"type";case"createdAt":return"createdAt"}}function q6(e,t){const n=Fp(t);return e.mode!==n?iN(n):{mode:n,direction:e.direction==="asc"?"desc":"asc"}}function V6(e,t){const n=Fp(t);return e.mode!==n?"↕":e.direction==="asc"?"↑":"↓"}function K6(e,t,n){const r=Fp(n);return t.mode!==r?a("shell.affairsFinderSortAction",{column:e}):a("shell.affairsFinderSortCurrent",{column:e,direction:t.direction==="asc"?a("shell.affairsFinderSortDirectionAsc"):a("shell.affairsFinderSortDirectionDesc")})}const Fx=yj;function G6(e,t,n,r,i){return e==="folder"?t.map(o=>({key:o.path,kind:"item",label:o.label,value:o.path,mode:"folder"})):sq(n,r,i)}function Y6(e,t,n){var g,p,b;if(e.length<=1||n<=0||e.reduce((y,x)=>{var k;return y+(((k=t.get(x.key))==null?void 0:k.offsetWidth)??0)},0)<=n)return e;const i=28,o=e[0],l=e[e.length-1],c=((g=t.get(o.key))==null?void 0:g.offsetWidth)??0,u=((p=t.get(l.key))==null?void 0:p.offsetWidth)??0,f=c+u+i,h=[];let m=f;for(let y=e.length-2;y>=1;y-=1){const x=e[y],k=((b=t.get(x.key))==null?void 0:b.offsetWidth)??0;if(m+k>n)break;h.unshift(x),m+=k}return[o,{key:"collapsed",kind:"collapsed"},...h,l]}function J6(e,t){const n=Ys(t);return e.filter(r=>Ys(r.parentPath)===n)}function X6(e,t){const n=Ys(t);return e.filter(r=>Ys(_l(r.filePath))===n)}function Q6({browseMode:e,childFolders:t,documents:n,favoriteFolderPathSet:r}){return e==="tag"?n.map(i=>({id:`document:${i.id}`,kind:"document",title:i.displayName,path:i.filePath,updatedAt:i.updatedAt,createdAt:i.createdAt,sizeBytes:i.sizeBytes,summary:i.summary,isFavorite:i.isFavorite,documentId:i.id})):[...t.map(i=>({id:`folder:${i.path}`,kind:"folder",title:i.label,path:i.path,count:i.count,isFavorite:r.has(i.path),createdAt:i.createdAt,updatedAt:i.updatedAt})),...n.map(i=>({id:`document:${i.id}`,kind:"document",title:i.displayName,path:i.filePath,updatedAt:i.updatedAt,createdAt:i.createdAt,sizeBytes:i.sizeBytes,summary:i.summary,isFavorite:i.isFavorite,documentId:i.id}))]}function Z6(e,t,n,r,i){if(i.section!=="library"||i.record)return null;const o=(r==null?void 0:r.trim())||n,l=Ys(o),c=e.find(g=>Ys(g.path)===l)??null,u=e.filter(g=>Ys(g.parentPath)===l).length,f=t.filter(g=>Ys(_l(g.filePath))===l).length,h=(c==null?void 0:c.label)||a("shell.affairsLibraryFolderRootLabel"),m=nm(o);return{title:h,path:m,folderPath:(o==null?void 0:o.trim())||null,summary:a("shell.affairsLibraryFolderDetailSummary",{path:m,folderCount:u,directDocumentCount:f,totalDocumentCount:(c==null?void 0:c.count)??t.filter(g=>Bx(g.filePath,o)).length}),childFolderCount:u,directDocumentCount:f,totalDocumentCount:(c==null?void 0:c.count)??t.filter(g=>Bx(g.filePath,o)).length,createdAt:(c==null?void 0:c.createdAt)??null,updatedAt:(c==null?void 0:c.updatedAt)??null}}function eq(e,t,n,r){const i=r.length>0?r:n!=null&&n.trim()?[n.trim()]:[],o=i[0]??"",l=i.length===1?e.find(c=>c.path===o)??null:null;return{title:i.length>1?a("shell.affairsLibraryTagMultiTitle"):(l==null?void 0:l.label)||a("shell.affairsLibraryTagRootLabel"),path:i.length>0?i.join(" · "):a("shell.affairsLibraryTagRootLabel"),rootType:i.length>1?a("shell.affairsLibraryTagMultiRootType"):(l==null?void 0:l.rootType)||a("common.unknown"),documentCount:i.length>0?t.filter(c=>i.every(u=>Mq(c,u))).length:0,nestedDocumentCount:t.length}}function Ys(e){const t=(e==null?void 0:e.trim())??"";return!t||t==="."?"":t.replace(/^\/+|\/+$/g,"")}function _l(e){const t=e.trim(),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function nm(e){return Ys(e)||a("shell.affairsLibraryFolderRootLabel")}function aN(e){const t=Ys(e);if(!t)return null;const n=t.lastIndexOf("/");return n>=0?t.slice(0,n):null}function tq(e,t){const n=Ys(e),r=Ys(t);if(!n||n===r)return null;if(aN(n)===r)return n;if(!r){const[l]=n.split("/");return l||null}if(!n.startsWith(`${r}/`))return null;const i=n.slice(r.length+1),[o]=i.split("/");return o?`${r}/${o}`:null}function nq(e){const t=Ys(e);if(!t)return[];const n=t.split("/");return n.map((r,i)=>({label:r,path:n.slice(0,i+1).join("/")}))}function sq(e,t,n){var f;const r=n.length>0?n:t!=null&&t.trim()?[t.trim()]:[];if(r.length===0)return[];if(r.length>1)return r.map(h=>{const m=h.trim(),g=e.find(p=>p.path===m);return{key:m,kind:"item",label:(g==null?void 0:g.label)??m.split("/").pop()??m,value:m,mode:"tag"}});const i=r[0],o=new Map(e.map(h=>[h.path,h])),l=[];let c=i;const u=new Set;for(;c&&!u.has(c);){u.add(c);const h=o.get(c);if(h){l.unshift({key:h.path,kind:"item",label:h.label,value:h.path,mode:"tag"}),c=((f=h.parentPath)==null?void 0:f.trim())||"";continue}const m=i.split("/");return m.map((g,p)=>({key:m.slice(0,p+1).join("/"),kind:"item",label:g,value:m.slice(0,p+1).join("/"),mode:"tag"}))}return l}function rq(e,t){const n=e.filter(i=>i.status!=="closed").map(i=>{var o,l,c,u;return{id:`inbox:${i.id}`,kind:"inbox",title:i.title,summary:i.content,statusLabel:fq(i.status),detail:((o=i.assistantState.analysisSummary)==null?void 0:o.trim())||((l=i.assistantState.generatedPrompt)==null?void 0:l.trim())||((c=i.assistantState.lastError)==null?void 0:c.trim())||i.content,sourceSessionId:i.assistantState.linkedSessionId,updatedAt:i.updatedAt,sourceLabel:a("shell.affairsTodoInboxFilter"),sourceDescription:((u=i.projectName)==null?void 0:u.trim())||a("common.unknown")}}),r=t.filter(i=>i.status==="active"||i.status==="waiting_user").map(i=>{var o,l,c,u;return{id:`follow-up:${i.id}`,kind:"follow_up",title:((o=i.sessionTitle)==null?void 0:o.trim())||i.projectName,summary:i.objective,statusLabel:hq(i.status),detail:((l=i.waitingReason)==null?void 0:l.trim())||((c=i.lastAutomationSummary)==null?void 0:c.trim())||i.objective,sourceSessionId:i.sessionId,updatedAt:i.updatedAt,sourceLabel:a("shell.affairsTodoFollowUpFilter"),sourceDescription:((u=i.sessionTitle)==null?void 0:u.trim())||i.projectName}});return[...n,...r].sort((i,o)=>o.updatedAt.localeCompare(i.updatedAt))}function iq(e,t){return[...e].sort((n,r)=>r.updatedAt.localeCompare(n.updatedAt)).map(n=>{var r,i,o;return{id:n.id,title:((r=n.title)==null?void 0:r.trim())||a("shell.affairsAutomationUntitled"),summary:n.actionConfig.content.trim()||a("shell.affairsAutomationPromptFallback"),statusLabel:mq(n.status),triggerLabel:pq(n.triggerType),targetSessionLabel:gq(n,t),updatedAt:n.updatedAt,lastRunSummary:((i=n.lastRunSummary)==null?void 0:i.trim())||null,lastRunStatusLabel:(o=n.lastError)!=null&&o.trim()?a("shell.affairsAutomationRunsStatusFailed"):n.lastRunAt?a("shell.affairsAutomationRunsStatusFinished"):null}})}function oN(e){return e?`${a("shell.affairsAssistantPromptPreamble",{title:e.title??a("common.unknown"),summary:e.summary??a("shell.affairsAssistantContextFallback"),sourceRef:e.sourceRef??a("common.unknown")})}
843
+
844
+ `:`${a("shell.affairsAssistantPromptPreambleEmpty")}
845
+
846
+ `}function Fo(e,t){return e==="workbench"||t==="assistant"?"assistant":"detail"}function aq(e){const t=cl(e);return t==="workbench:todo:inbox"?a("shell.affairsTodoInboxFilter"):t==="workbench:todo:follow_up"?a("shell.affairsTodoFollowUpFilter"):a("shell.affairsTodoAllFilter")}function oq(e,t){var n;return{sessionId:e.sessionId,workspaceId:t,provider:e.provider??"codex",providerSessionId:e.sessionId,rawStoreRef:`butler://${e.id}`,providerConfigMode:"global-default",providerPresetId:null,parentSessionId:null,isSubagent:!1,subagentLabel:null,isArchived:e.isArchived,isFavorite:e.isFavorite===!0,title:((n=e.title)==null?void 0:n.trim())||e.sessionId,messageCount:0,lastMessageAt:e.updatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,syncStatus:"idle",syncCursor:null,lastSyncAt:e.updatedAt,lastErrorCode:null,lastErrorDetail:null,resumedAt:null,runningState:lq(e.runningState),activitySource:"inferred",lastEventAt:e.updatedAt,completedAt:e.status==="closed"?e.updatedAt:null,lastSeenAt:null,activityState:e.status==="running"?"running":"completed_unread"}}function lq(e){switch(e){case"idle":case"starting":case"running":case"reconnecting":case"stale":case"unknown":case"completed":case"interrupted":case"failed":return e;default:return"idle"}}function cq(e){switch(e){case"conversation":return a("shell.affairsConversationSidebarTitle");case"workbench":return a("shell.affairsWorkbenchSidebarTitle");case"library":default:return a("shell.affairsLibrarySidebarTitle")}}function uq(e,t){switch(e){case"conversation":return a("shell.affairsConversationSidebarDescription",{count:4});case"workbench":return a("shell.affairsWorkbenchSidebarDescription",{todoCount:t.todoCount,automationCount:t.automationCount});case"library":default:return a("shell.affairsLibrarySidebarDescription",{favorites:t.favoriteCount,tags:t.tagCount,count:t.documentCount})}}function dq(e){switch(e){case"conversation":return a("shell.affairsConversationEmpty");case"workbench":return a("shell.affairsWorkbenchEmpty");case"library":default:return a("shell.affairsLibraryEmpty")}}function fq(e){switch(e){case"in_progress":return a("shell.affairsTodoStatusInProgress");case"closed":return a("shell.affairsTodoStatusClosed");case"pending":default:return a("shell.affairsTodoStatusPending")}}function hq(e){switch(e){case"waiting_user":return a("shell.affairsTodoStatusWaitingUser");case"completed":return a("shell.affairsTodoStatusCompleted");case"failed":return a("shell.affairsTodoStatusFailed");case"cancelled":return a("shell.affairsTodoStatusCancelled");case"active":default:return a("shell.affairsTodoStatusActive")}}function mq(e){switch(e){case"paused":return a("shell.affairsAutomationStatusPaused");case"completed":return a("shell.affairsAutomationStatusCompleted");case"cancelled":return a("shell.affairsAutomationStatusCancelled");case"failed":return a("shell.affairsAutomationStatusFailed");case"active":default:return a("shell.affairsAutomationStatusActive")}}function lN(e){switch(e){case"queued":return a("shell.affairsAutomationRunsStatusQueued");case"running":return a("shell.affairsAutomationRunsStatusRunning");case"failed":return a("shell.affairsAutomationRunsStatusFailed");case"cancelled":return a("shell.affairsAutomationRunsStatusCancelled");case"skipped":return a("shell.affairsAutomationRunsStatusSkipped");case"succeeded":default:return a("shell.affairsAutomationRunsStatusFinished")}}function pq(e){switch(e){case"interval":return a("shell.affairsAutomationTriggerInterval");case"cron":return a("shell.affairsAutomationTriggerCron");case"condition":return a("shell.affairsAutomationTriggerCondition");case"once":default:return a("shell.affairsAutomationTriggerOnce")}}function gq(e,t){var r,i,o;const n=((r=e.actionConfig.targetSessionId)==null?void 0:r.trim())||((o=(i=e.controlSession)==null?void 0:i.sessionId)==null?void 0:o.trim())||"";return t[n]??a("shell.affairsAutomationTargetFallback")}function bq(e){return e.lightweightLoading&&e.agentLoading?a("shell.affairsConversationSidebarLoadingAll"):e.agentLoading?a("shell.affairsConversationSidebarLoadingAgent"):e.lightweightLoading?a("shell.affairsConversationSidebarLoadingLightweight"):null}function Cl(e){return e==="agent"?a("shell.affairsConversationKindAgent"):a("shell.affairsConversationKindLightweight")}function Eu(e){return Ui(e,"full")}function Lu(e){return`conversation:draft:${e.kind}:${e.provider}`}function li(e,t){return`conversation:${e}:session:${t}`}function yq(e){const t=(e==null?void 0:e.trim())??"";if(!t.startsWith("conversation:draft:"))return null;const n=t.split(":");if(n.length<4)return null;const r=n[2],i=n.slice(3).join(":");return r!=="lightweight"&&r!=="agent"||!FA(i)?null:{kind:r,provider:i}}function xq(e){var o;const t=(e==null?void 0:e.trim())??"";if(!t.startsWith("conversation:"))return null;const n=t.split(":");if(n.length!==4||n[2]!=="session")return null;const r=n[1],i=((o=n[3])==null?void 0:o.trim())??"";return r!=="lightweight"&&r!=="agent"||!i?null:{kind:r,sessionId:i}}function kq(e){var r,i;const t=((r=e==null?void 0:e.mirrorRoot)==null?void 0:r.trim())??"";return t||(((i=e==null?void 0:e.rootDir)==null?void 0:i.trim())??"")||null}function wq(e){var o,l,c,u;const t=((o=e.rootDir)==null?void 0:o.trim())??"";if(t)return t;const n=((l=e.mirrorRoot)==null?void 0:l.trim())??"";if(n)return n;const r=((c=e.agentWorkspacePath)==null?void 0:c.trim())??"";return r||(((u=e.workspaceName)==null?void 0:u.trim())??"")||null}function vq(e,t){var i;const n=ll(e);return n?((i=t.map(o=>{const l=ll(o.workspace.path),c=ll(o.workspace.repoRoot??null),u=Math.max(_x(l,n),_x(c,n));return{workspaceId:o.workspace.id,matchLength:u}}).filter(o=>o.matchLength>0).sort((o,l)=>l.matchLength-o.matchLength)[0])==null?void 0:i.workspaceId)??null:null}function _x(e,t){const n=ll(e),r=ll(t);return!n||!r?0:n===r||r.startsWith(`${n}/`)?n.length:n.startsWith(`${r}/`)?r.length:0}function ll(e){return(e==null?void 0:e.trim().replace(/\/+$/g,""))??""}function hd(e,t){var i;const n=(t==null?void 0:t.trim())??"",r=((i=e==null?void 0:e.session.workspaceId)==null?void 0:i.trim())??"";return n.length>0&&r===n}function Sq(e){return e.kind==="agent"?a("shell.affairsConversationOptionSummaryAgent",{provider:Eu(e.provider)}):a("shell.affairsConversationOptionSummaryLightweight",{provider:Eu(e.provider)})}function cN(e,t){const n=new Date().toISOString();return{sessionId:Lu(t),workspaceId:e,provider:t.provider,providerSessionId:`draft://${t.provider}/${e}`,rawStoreRef:`draft://${t.provider}/${e}`,providerConfigMode:"global-default",providerPresetId:null,parentSessionId:null,isSubagent:!1,subagentLabel:null,isArchived:!1,isFavorite:!1,title:_A(t.provider),messageCount:0,lastMessageAt:null,createdAt:n,updatedAt:n,syncStatus:"idle",syncCursor:null,lastSyncAt:null,lastErrorCode:null,lastErrorDetail:null,resumedAt:null,runningState:"idle",activitySource:"none",lastEventAt:null,completedAt:null,lastSeenAt:null,activityState:"idle"}}function uN(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function dN(e,t){return(e instanceof rr||e instanceof Error)&&e.message||t}function Hf(e,t,n){switch(e){case"conversation":return"conversation:home";case"workbench":return"workbench:overview";case"library":default:return"library:all"}}function cl(e){const t=(e==null?void 0:e.trim())??"";return t?t==="todo:all"?"workbench:todo:all":t==="todo:inbox"?"workbench:todo:inbox":t==="todo:follow_up"?"workbench:todo:follow_up":t==="automation:all"?"workbench:overview":t.startsWith("automation:item:")?`workbench:${t}`:t.startsWith("workbench:")?t:"workbench:overview":"workbench:overview"}function Cq(e,t){if(e!=="workbench")return null;const n=cl(t);return!n||n==="workbench:overview"?null:n.startsWith("workbench:automation:item:")&&n.slice(26)||null}function jq(e,t){return e==="conversation"?[{id:"conversation",label:a("shell.affairsConversationSidebarGroupModes"),items:t}]:e==="workbench"?[{id:"overview",label:a("shell.affairsWorkbenchSidebarGroupOverview"),items:t.filter(n=>n.id==="workbench:overview")},{id:"todo",label:a("shell.affairsTodoSidebarGroupSources"),items:t.filter(n=>n.id.startsWith("workbench:todo:"))},{id:"automation",label:a("shell.affairsAutomationSidebarGroupTasks"),items:t.filter(n=>n.id.startsWith("workbench:automation:"))}]:[]}function Nq(e){return e==="conversation"||e==="workbench"?e:"library"}function uo(e){return e?new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(e)):a("common.unknown")}function Du(e){if(!e)return a("common.unknown");const t=new Date(e);return Number.isNaN(t.getTime())?a("common.unknown"):new Intl.DateTimeFormat(Ga.getState().profile.language??"zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).format(t)}function fN(e){const t=(e==null?void 0:e.trim())??"";return t?t.split(/\r?\n/).filter(r=>r.trim().length>0).length>3||t.length>120:!1}function Tq(e){const t=Ys(e);if(!t)return[];const n=t.split("/").filter(Boolean);return n.map((r,i)=>({label:r,path:i<n.length-1?n.slice(0,i+1).join("/"):_l(t)||null}))}function Iq({path:e,rootLabel:t,onNavigate:n}){const r=d.useMemo(()=>Tq(e),[e]);return s.jsxs("span",{className:"affairs-detail-path-breadcrumbs",children:[s.jsx("button",{type:"button",className:"affairs-detail-path-segment root",onClick:()=>n(null),children:t}),r.map((i,o)=>s.jsxs(d.Fragment,{children:[s.jsx("span",{className:"affairs-detail-path-separator","aria-hidden":"true",children:"/"}),s.jsx("button",{type:"button",className:o===r.length-1?"affairs-detail-path-segment current":"affairs-detail-path-segment",onClick:()=>n(i.path),children:i.label})]},`${i.label}:${i.path??o}`))]})}function Lc(e){if(!e)return"—";const t=new Date(e);if(Number.isNaN(t.getTime()))return"—";const n=Ga.getState().profile.language??"zh-CN",r=n==="en-US",i=new Date,o=new Date(i.getFullYear(),i.getMonth(),i.getDate()),l=new Date(t.getFullYear(),t.getMonth(),t.getDate()),c=Math.round((o.getTime()-l.getTime())/864e5),u=new Intl.DateTimeFormat(n,{hour:"2-digit",minute:"2-digit",hour12:!1}).format(t);return c===0?`${a("shell.affairsFinderDateToday")} ${u}`:c===1?`${a("shell.affairsFinderDateYesterday")} ${u}`:r?new Intl.DateTimeFormat(n,{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(t):`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()} ${u}`}function sm(e){if(!Number.isFinite(e)||e===null||e===void 0||e<0)return"—";const t=Number(e);return t<1024?`${Math.round(t)} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(2)} GB`}function Aq(e){const t=Ip(e),n=t.extension;if(n==="document")return a("shell.affairsFinderKindFile");switch(t.kind){case"markdown":return a("shell.affairsFinderKindMarkdown");case"text":return a("shell.affairsFinderKindText");case"web":return a("shell.affairsFinderKindHtml");case"json":return a("shell.affairsFinderKindJson");case"xml":return a("shell.affairsFinderKindXml");case"yaml":return a("shell.affairsFinderKindYaml");case"pdf":return a("shell.affairsFinderKindPdf");case"word":return a("shell.affairsFinderKindWord");case"spreadsheet":return a("shell.affairsFinderKindExcel");case"presentation":return a("shell.affairsFinderKindPowerPoint");case"image":return a("shell.affairsFinderKindImage");case"archive":return a("shell.affairsFinderKindArchive");case"code":return a("shell.affairsFinderKindCode");case"database":return n==="sql"?a("shell.affairsFinderKindSql"):a("shell.affairsFinderKindDatabase");case"audio":return a("shell.affairsFinderKindAudio");case"video":return a("shell.affairsFinderKindVideo");case"design":return a("shell.affairsFinderKindDesign");case"font":return a("shell.affairsFinderKindFont");case"ebook":return a("shell.affairsFinderKindEbook");default:return n.toUpperCase()}}function Rq(e){const t={name:Number.isFinite(e.name)?e.name:Fa.name,size:Number.isFinite(e.size)?e.size:Fa.size,updatedAt:Number.isFinite(e.updatedAt)?e.updatedAt:Fa.updatedAt,type:Number.isFinite(e.type)?e.type:Fa.type,createdAt:Number.isFinite(e.createdAt)?e.createdAt:Fa.createdAt};return[`minmax(${Oa.name}px, ${Math.round(t.name)}px)`,`minmax(${Oa.size}px, ${Math.round(t.size)}px)`,`minmax(${Oa.updatedAt}px, ${Math.round(t.updatedAt)}px)`,`minmax(${Oa.type}px, ${Math.round(t.type)}px)`,`minmax(${Oa.createdAt}px, 1fr)`].join(" ")}function Pq(e){return e?new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(e)):a("common.unknown")}function rm(e){return`library:favorite:${e.kind}:${e.path}`}function im(e,t,n){if(e.startsWith("library:folder:")){const r={kind:"folder",path:e.slice(15),label:t};return s.jsx("button",{type:"button",className:"affairs-favorite-toggle","aria-label":a("shell.affairsFavoriteAddAction"),onClick:i=>{i.stopPropagation(),n(r)},children:"☆"})}if(e.startsWith("library:tag:")){const r={kind:"tag",path:e.slice(12),label:t};return s.jsx("button",{type:"button",className:"affairs-favorite-toggle","aria-label":a("shell.affairsFavoriteAddAction"),onClick:i=>{i.stopPropagation(),n(r)},children:"☆"})}if(e.startsWith("library:favorite:")){const[,,,r,...i]=e.split(":"),o={kind:r==="tag"?"tag":"folder",path:i.join(":"),label:t};return s.jsx("button",{type:"button",className:"affairs-favorite-toggle active","aria-label":a("shell.affairsFavoriteRemoveAction"),onClick:l=>{l.stopPropagation(),n(o)},children:"★"})}return null}function Bx(e,t){const n=(t==null?void 0:t.trim())??"";return!n||n==="."?!0:e===n||e.startsWith(`${n}/`)}function Mq(e,t){const n=t.trim();return n?[...e.tags,...e.derivedTags].some(r=>r===n):!1}function hN(e){const t=e.trim().toLowerCase();if(!t)return"";const n=t.startsWith(".")?t:`.${t}`;return/^.[a-z0-9]+(?:[._-][a-z0-9]+)*$/i.test(n)?n:""}function Wx(e){const t=fi(e);return t.length>0?t:[...fd]}function Eq(e,t){return fi(e).length>0?!1:Dq(fi(fd),fi(t))}function Lq(e){return fi([...fd,...e])}function fi(e){return Array.from(new Set(e.map(t=>hN(t)).filter(Boolean))).sort((t,n)=>t.localeCompare(n,"zh-Hans-CN"))}function Dq(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function mN(e){if(!e)return a("shell.affairsLibraryStatusIdle");switch(e.state){case"queued":return a("shell.affairsLibraryStatusQueued");case"running":return a("shell.affairsLibraryStatusRunning");case"queue_timeout":return a("shell.affairsLibraryStatusQueueTimeout");case"cooldown":return a("shell.affairsLibraryStatusCooldown");case"failed":return a("shell.affairsLibraryStatusFailed");case"stale":return a("shell.affairsLibraryStatusStale");case"fresh":default:return a("shell.affairsLibraryStatusFresh")}}function Oq(e,t){var h,m,g,p,b,y,x,k;const n=[{label:a("shell.affairsLibraryStatusCurrentLabel"),value:mN(e)}],r=[],i=[],o=[],l=[],c=[];if(!e)return{summaryMetrics:[],primaryRows:n,technicalSections:[]};const u=e.progress?[{label:a("shell.affairsLibraryStatusSummaryTotalLabel"),value:Fq(e.progress.totalCount)},{label:a("shell.affairsLibraryStatusSummaryScannedLabel"),value:String(e.progress.scannedCount)},{label:a("shell.affairsLibraryStatusSummaryIssueLabel"),value:String(e.progress.failedCount),tone:e.progress.failedCount>0?"danger":"default"},{label:a("shell.affairsLibraryStatusSummaryUpdatedLabel"),value:String(e.progress.indexedCount),tone:e.progress.indexedCount>0?"success":"default"}]:[];if(Rs(i,a("shell.affairsLibraryStatusLastRequestedAtLabel"),e.lastRequestedAt),Rs(i,a("shell.affairsLibraryStatusLastStartedAtLabel"),e.lastStartedAt),Rs(i,a("shell.affairsLibraryStatusLastCompletedAtLabel"),e.lastCompletedAt),Rs(i,a("shell.affairsLibraryStatusLastFailedAtLabel"),e.lastFailedAt),Rs(i,a("shell.affairsLibraryStatusNextAllowedAtLabel"),e.nextAllowedAt),(h=e.runningTaskId)!=null&&h.trim()&&r.push({label:a("shell.affairsLibraryStatusRunningTaskIdLabel"),value:e.runningTaskId.trim(),multiline:!0}),(m=e.runningStage)!=null&&m.trim()&&n.push({label:a("shell.affairsLibraryStatusRunningStageLabel"),value:Bq(e.runningStage.trim())}),e.progress&&(o.push({label:a("shell.affairsLibraryStatusProgressUnchangedLabel"),value:String(e.progress.unchangedCount)}),o.push({label:a("shell.affairsLibraryStatusProgressSkippedLabel"),value:String(e.progress.skippedCount)}),o.push({label:a("shell.affairsLibraryStatusProgressFailedLabel"),value:String(e.progress.failedCount)})),e.dirtyReasons.length>0&&r.push({label:a("shell.affairsLibraryStatusDirtyReasonsLabel"),value:e.dirtyReasons.join("、"),multiline:!0}),(g=e.errorSummary)!=null&&g.trim()&&n.push({label:a("shell.affairsLibraryStatusErrorSummaryLabel"),value:e.errorSummary.trim(),multiline:!0}),(p=t==null?void 0:t.path)!=null&&p.trim()&&(n.push({label:a("shell.affairsLibraryDirectoryStatusPathLabel"),value:t.path==="."?a("shell.affairsLibraryDirectoryStatusRootPath"):t.path}),n.push({label:a("shell.affairsLibraryDirectoryStatusStateLabel"),value:Wq(t.state)}),l.push({label:a("shell.affairsLibraryDirectoryStatusSourceLabel"),value:$q(t.source)}),Rs(l,a("shell.affairsLibraryDirectoryStatusLastRequestedAtLabel"),t.lastRequestedAt),Rs(l,a("shell.affairsLibraryDirectoryStatusLastCompletedAtLabel"),t.lastCompletedAt),Rs(l,a("shell.affairsLibraryDirectoryStatusLastFailedAtLabel"),t.lastFailedAt),(b=t.runningTaskId)!=null&&b.trim()&&l.push({label:a("shell.affairsLibraryDirectoryStatusRunningTaskIdLabel"),value:t.runningTaskId.trim(),multiline:!0}),(y=t.errorSummary)!=null&&y.trim()&&l.push({label:a("shell.affairsLibraryDirectoryStatusErrorSummaryLabel"),value:t.errorSummary.trim(),multiline:!0}),Rs(l,a("shell.affairsLibraryDirectoryStatusGeneratedAtLabel"),t.generatedAt??null),Rs(l,a("shell.affairsLibraryDirectoryStatusFilesystemObservedAtLabel"),t.filesystemObservedAt??null),(x=t.staleReason)!=null&&x.trim()&&l.push({label:a("shell.affairsLibraryDirectoryStatusStaleReasonLabel"),value:t.staleReason.trim(),multiline:!0})),e.workerHealth){const C=e.workerHealth;c.push({label:a("shell.affairsLibraryWorkerHealthStateLabel"),value:zq(C.state)}),c.push({label:a("shell.affairsLibraryWorkerHealthPidLabel"),value:C.pid===null?a("common.none"):String(C.pid)}),c.push({label:a("shell.affairsLibraryWorkerHealthLocalInflightLabel"),value:String(C.inflightLocalCount)}),c.push({label:a("shell.affairsLibraryWorkerHealthRemoteInflightLabel"),value:String(C.inflightRemoteRequestCount)}),Rs(c,a("shell.affairsLibraryWorkerHealthStartedAtLabel"),C.startedAt),Rs(c,a("shell.affairsLibraryWorkerHealthHeartbeatLabel"),C.lastHeartbeatAt),Rs(c,a("shell.affairsLibraryWorkerHealthLastStartedAtLabel"),C.lastStartedAt),Rs(c,a("shell.affairsLibraryWorkerHealthLastCompletedAtLabel"),C.lastCompletedAt),Rs(c,a("shell.affairsLibraryWorkerHealthLastFailedAtLabel"),C.lastFailedAt),Rs(c,a("shell.affairsLibraryWorkerHealthSoftCancelAtLabel"),C.lastSoftCancelRequestedAt),Rs(c,a("shell.affairsLibraryWorkerHealthHardKillAtLabel"),C.lastHardKillAt),Rs(c,a("shell.affairsLibraryWorkerHealthLastExitAtLabel"),C.lastExitAt),(k=C.lastTerminationReason)!=null&&k.trim()&&c.push({label:a("shell.affairsLibraryWorkerHealthTerminationReasonLabel"),value:C.lastTerminationReason.trim(),multiline:!0})}const f=[];return _o(f,a("shell.affairsLibraryStatusSectionOverviewTitle"),r),_o(f,a("shell.affairsLibraryStatusSectionTimelineTitle"),i),_o(f,a("shell.affairsLibraryStatusSectionProgressTitle"),o),_o(f,a("shell.affairsLibraryStatusSectionDirectoryTitle"),l),_o(f,a("shell.affairsLibraryStatusSectionWorkerTitle"),c),{summaryMetrics:u,primaryRows:n,technicalSections:f}}function Rs(e,t,n){n&&e.push({label:t,value:Pq(n)})}function _o(e,t,n){n.length!==0&&e.push({title:t,rows:n})}function Fq(e){return e==null?"—":String(e)}function _q(e){return(e==null?void 0:e.state)!=="running"||!e.progress?null:a("shell.affairsLibraryStatusIndicatorProgress",{scanned:e.progress.scannedCount})}function Bq(e){switch(e){case"init":return a("shell.affairsLibraryStatusStageInit");case"apply_config":return a("shell.affairsLibraryStatusStageApplyConfig");case"index":return a("shell.affairsLibraryStatusStageIndex");case"incremental_index":return a("shell.affairsLibraryStatusStageIncrementalIndex");case"recompute_tags":return a("shell.affairsLibraryStatusStageRecomputeTags");case"export":return a("shell.affairsLibraryStatusStageExport");case"export_meta_detail":return a("shell.affairsLibraryStatusStageExportMetaDetail");case"export_tag":return a("shell.affairsLibraryStatusStageExportTag");case"export_relation":return a("shell.affairsLibraryStatusStageExportRelation");case"export_search":return a("shell.affairsLibraryStatusStageExportSearch");case"sqlite":return a("shell.affairsLibraryStatusStageSqlite");case"queued":return a("shell.affairsLibraryStatusStageQueued");default:return e}}function Wq(e){switch(e){case"queued":return a("shell.affairsLibraryDirectoryStatusQueued");case"running":return a("shell.affairsLibraryDirectoryStatusRunning");case"queue_timeout":return a("shell.affairsLibraryDirectoryStatusQueueTimeout");case"fresh":return a("shell.affairsLibraryDirectoryStatusFresh");case"failed":return a("shell.affairsLibraryDirectoryStatusFailed");case"idle":default:return a("shell.affairsLibraryDirectoryStatusIdle")}}function $q(e){switch(e){case"live":return a("shell.affairsLibraryDirectoryStatusSourceLive");case"snapshot":return a("shell.affairsLibraryDirectoryStatusSourceSnapshot");case"stale_fallback":return a("shell.affairsLibraryDirectoryStatusSourceStaleFallback");case"mixed":default:return a("shell.affairsLibraryDirectoryStatusSourceMixed")}}function zq(e){switch(e){case"running":return a("shell.affairsLibraryWorkerHealthStateRunning");case"terminating":return a("shell.affairsLibraryWorkerHealthStateTerminating");case"recycled":return a("shell.affairsLibraryWorkerHealthStateRecycled");case"idle":default:return a("shell.affairsLibraryWorkerHealthStateIdle")}}function am(e){var t;return e?e.state==="running"?a("shell.affairsLibraryEmptyRunning"):((t=e.errorSummary)==null?void 0:t.trim())||a("shell.affairsLibraryEmpty"):a("shell.affairsLibraryEmpty")}function Hq(e){return a("shell.affairsDetailEmpty")}function $x({children:e}){return s.jsx(s.Fragment,{children:e})}const Uq="workbench.mode.workspace.",qq="workbench.mode.code.last-path.",Vq="workbench.mode.affairs.last-path.",Kq="workbench.affairs.state.",_p=365*24*60*60*1e3,An={primarySection:"library",selectedNodeId:"library",selectedObjectId:null,toolbarExpanded:!1,detailViewerCollapsed:!1,auxiliaryTab:"detail",browseMode:"folder",viewMode:"grid",selectedFolderPath:null,selectedFolderEntryPath:null,selectedTagPath:null,selectedTagPaths:[],selectedDocumentId:null,selectedFavoriteId:null};function pN(e){return`${Uq}${e}`}function gN(e,t){return`${t==="code"?qq:Vq}${e}`}function bN(e){return`${Kq}${e}`}function Gq(e){return e==="conversation"||e==="library"||e==="workbench"?e:e==="todo"||e==="automation"?"workbench":An.primarySection}function Yq(e,t){const n=(t==null?void 0:t.trim())??"";return e==="library"?n||An.selectedNodeId:e==="conversation"?n||"conversation:home":n==="todo:all"?"workbench:todo:all":n==="todo:inbox"?"workbench:todo:inbox":n==="todo:follow_up"?"workbench:todo:follow_up":n==="automation:all"?"workbench:overview":n.startsWith("automation:item:")?`workbench:${n}`:n||"workbench:overview"}function yN(e){return Kt("/workspaces/:workspaceId/affairs",e)?"affairs":Kt("/workspaces/:workspaceId/sessions",e)||Kt("/workspaces/:workspaceId/sessions/:sessionId",e)||Kt("/workspaces/:workspaceId/tools",e)||Kt("/workspaces/:workspaceId/tools/files",e)||Kt("/workspaces/:workspaceId/tools/git",e)||Kt("/workspaces/:workspaceId/tools/processes",e)||Kt("/workspaces/:workspaceId/terminals",e)||Kt("/workspaces/:workspaceId/butler",e)||Kt("/workspaces/:workspaceId/plugins",e)||Kt("/workspaces/:workspaceId/plugins/:pluginId",e)||Kt("/workspaces/:workspaceId/plugins/:pluginId/run",e)?"code":null}function Jq(e){var n;const t=e==null?void 0:e.trim();return t?((n=Br(pN(t),_p))==null?void 0:n.mode)??null:null}function zx(e,t,n=new Date().toISOString()){Rr(pN(e),{workspaceId:e,mode:t,updatedAt:n})}function Xq(e,t){const n=e==null?void 0:e.trim();return n?Br(gN(n,t),_p)??null:null}function Qq(e,t,n){Rr(gN(e,t),n)}function Hx(e){var i;const t=e==null?void 0:e.trim();if(!t)return null;const n=Br(bN(t),_p);if(!n)return null;const r=Gq(n.primarySection);return{workspaceId:t,primarySection:r,selectedNodeId:Yq(r,n.selectedNodeId),selectedObjectId:n.selectedObjectId??An.selectedObjectId,toolbarExpanded:n.toolbarExpanded??An.toolbarExpanded,detailViewerCollapsed:n.detailViewerCollapsed??An.detailViewerCollapsed,auxiliaryTab:n.auxiliaryTab??An.auxiliaryTab,browseMode:n.browseMode??An.browseMode,viewMode:n.viewMode??An.viewMode,selectedFolderPath:n.selectedFolderPath??An.selectedFolderPath,selectedFolderEntryPath:n.selectedFolderEntryPath??An.selectedFolderEntryPath,selectedTagPath:n.selectedTagPath??An.selectedTagPath,selectedTagPaths:Array.isArray(n.selectedTagPaths)?n.selectedTagPaths.filter(o=>typeof o=="string"&&o.trim().length>0):(i=n.selectedTagPath)!=null&&i.trim()?[n.selectedTagPath.trim()]:An.selectedTagPaths,selectedDocumentId:n.selectedDocumentId??An.selectedDocumentId,selectedFavoriteId:n.selectedFavoriteId??An.selectedFavoriteId}}function Zq(e){Rr(bN(e.workspaceId),e)}function nu(e){return{workspaceId:e,primarySection:An.primarySection,selectedNodeId:An.selectedNodeId,selectedObjectId:An.selectedObjectId,toolbarExpanded:An.toolbarExpanded,detailViewerCollapsed:An.detailViewerCollapsed,auxiliaryTab:An.auxiliaryTab,browseMode:An.browseMode,viewMode:An.viewMode,selectedFolderPath:An.selectedFolderPath,selectedFolderEntryPath:An.selectedFolderEntryPath,selectedTagPath:An.selectedTagPath,selectedTagPaths:An.selectedTagPaths,selectedDocumentId:An.selectedDocumentId,selectedFavoriteId:An.selectedFavoriteId}}function Ux(e,t){return{...{...nu(e),...t??{},workspaceId:e},primarySection:"library",selectedNodeId:"library",selectedObjectId:null,browseMode:"folder",selectedFolderPath:null,selectedFolderEntryPath:null,selectedTagPath:null,selectedTagPaths:[],selectedDocumentId:null,selectedFavoriteId:null}}const Dc={repositoryUrl:"",parentPath:"",directoryName:"",name:"",authMode:"none",username:"",password:"",token:""};function e3({open:e,onClose:t,onCloned:n}){const{showToast:r}=Vn(),[i,o]=d.useState(!1),[l,c]=d.useState(Dc),[u,f]=d.useState(!1),[h,m]=d.useState(!1),[g,p]=d.useState(null),[b,y]=d.useState(""),[x,k]=d.useState(""),[C,j]=d.useState(null),[H,_]=d.useState([]),[T,P]=d.useState([]),z=i||h;d.useEffect(()=>{!e&&!i&&(c(Dc),f(!1),p(null))},[i,e]);const L=d.useCallback(async ee=>{m(!0),p(null);try{const U=await rw(ee);y(U.currentPath),k(U.currentPath),j(U.parentPath),_(U.roots),P(U.items),c(he=>({...he,parentPath:U.currentPath}))}catch(U){y(""),j(null),P([]),p(U instanceof Error?U.message:a("shell.importBrowserBrowseFailed"))}finally{m(!1)}},[]);function R(){i||(f(!1),p(null),c(Dc),t())}function K(){f(!0),L(l.parentPath||void 0)}function E(){i||(f(!1),p(null))}async function D(ee){ee.preventDefault(),await L(x)}function te(){c(ee=>({...ee,parentPath:b})),f(!1),p(null)}async function V(ee){ee.preventDefault();const U=l.repositoryUrl.trim(),he=l.parentPath.trim();if(!U){r({title:a("shell.cloneRepoRequired"),tone:"error"});return}if(!he){r({title:a("shell.clonePathRequired"),tone:"error"});return}o(!0);try{const X=await UT({repositoryUrl:U,parentPath:he,directoryName:l.directoryName.trim()||void 0,name:l.name.trim()||void 0,auth:l.authMode==="none"?{mode:"none"}:l.authMode==="basic"?{mode:"basic",username:l.username.trim(),password:l.password}:{mode:"token",username:l.username.trim()||void 0,token:l.token}});await(n==null?void 0:n(X)),c(Dc),f(!1),r({title:a("shell.cloneSuccess"),description:X.path,tone:"success"}),t()}catch(X){r({title:X instanceof Error?X.message:a("shell.cloneFailed"),tone:"error"})}finally{o(!1)}}return s.jsxs(s.Fragment,{children:[s.jsx(ln,{open:e,title:a("shell.cloneWorkspaceTitle"),description:a("shell.cloneWorkspaceHint"),onClose:R,children:s.jsxs("form",{className:"workbench-clone-form",onSubmit:ee=>void V(ee),children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.cloneRepositoryLabel")}),s.jsx("input",{type:"text",value:l.repositoryUrl,placeholder:a("shell.cloneRepositoryPlaceholder"),onChange:ee=>c(U=>({...U,repositoryUrl:ee.target.value}))})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.cloneParentPathLabel")}),s.jsxs("div",{className:"workbench-modal-inline-field",children:[s.jsx("input",{type:"text",value:l.parentPath,placeholder:a("shell.cloneParentPathPlaceholder"),onChange:ee=>c(U=>({...U,parentPath:ee.target.value}))}),s.jsx("button",{type:"button",className:"secondary-button",disabled:i,onClick:K,children:a("shell.clonePickDirectory")})]})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.cloneDirectoryNameLabel")}),s.jsx("input",{type:"text",value:l.directoryName,placeholder:a("shell.cloneDirectoryNamePlaceholder"),onChange:ee=>c(U=>({...U,directoryName:ee.target.value}))})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.importNameLabel")}),s.jsx("input",{type:"text",value:l.name,placeholder:a("shell.importNamePlaceholder"),onChange:ee=>c(U=>({...U,name:ee.target.value}))})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.cloneAuthModeLabel")}),s.jsxs("select",{value:l.authMode,onChange:ee=>c(U=>({...U,authMode:ee.target.value})),children:[s.jsx("option",{value:"none",children:a("shell.cloneAuthModeNone")}),s.jsx("option",{value:"basic",children:a("shell.cloneAuthModeBasic")}),s.jsx("option",{value:"token",children:a("shell.cloneAuthModeToken")})]})]}),l.authMode==="basic"?s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.cloneUsernameLabel")}),s.jsx("input",{type:"text",value:l.username,placeholder:a("shell.cloneUsernamePlaceholder"),autoComplete:"username",onChange:ee=>c(U=>({...U,username:ee.target.value}))})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.clonePasswordLabel")}),s.jsx("input",{type:"password",value:l.password,placeholder:a("shell.clonePasswordPlaceholder"),autoComplete:"current-password",onChange:ee=>c(U=>({...U,password:ee.target.value}))})]})]}):null,l.authMode==="token"?s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.cloneUsernameLabel")}),s.jsx("input",{type:"text",value:l.username,placeholder:a("shell.cloneTokenUsernamePlaceholder"),onChange:ee=>c(U=>({...U,username:ee.target.value}))})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.cloneTokenLabel")}),s.jsx("input",{type:"password",value:l.token,placeholder:a("shell.cloneTokenPlaceholder"),onChange:ee=>c(U=>({...U,token:ee.target.value}))})]})]}):null,s.jsx("p",{className:"workbench-import-hint",children:a("shell.cloneHint")}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:i,onClick:R,children:a("common.cancel")}),s.jsx("button",{type:"submit",className:"primary-button",disabled:i,children:i?a("shell.cloneSubmitting"):a("shell.cloneSubmit")})]})]})}),s.jsxs(ln,{open:e&&u,title:a("shell.cloneBrowserTitle"),description:a("shell.cloneBrowserDescription"),onClose:E,children:[s.jsxs("form",{className:"workbench-directory-browser-form",onSubmit:D,children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.importBrowserCurrentPath")}),s.jsx("input",{type:"text",value:x,placeholder:a("shell.importPathPlaceholder"),onChange:ee=>k(ee.target.value)})]}),s.jsxs("div",{className:"workbench-directory-browser-toolbar",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:z||!C,onClick:()=>{C&&L(C)},children:a("shell.importBrowserOpenParent")}),s.jsx("button",{type:"submit",className:"secondary-button",disabled:z,children:a("shell.importBrowserOpenPath")})]})]}),s.jsxs("section",{className:"workbench-directory-browser-panel",children:[s.jsxs("div",{className:"workbench-directory-browser-section",children:[s.jsx("span",{className:"workbench-directory-browser-section-title",children:a("shell.importBrowserRoots")}),s.jsx("div",{className:"workbench-directory-browser-root-list",children:H.map(ee=>s.jsx("button",{type:"button",className:"workbench-directory-browser-chip",disabled:z,onClick:()=>{L(ee.path)},children:ee.name},ee.path))})]}),s.jsx("div",{className:"workbench-directory-browser-current-path",children:b}),g?s.jsx("p",{className:"workbench-directory-browser-status status-text","data-tone":"error",children:g}):null,h?s.jsx("p",{className:"workbench-directory-browser-status status-text",children:a("common.loading")}):T.length>0?s.jsx("div",{className:"workbench-directory-browser-list",children:T.map(ee=>s.jsxs("button",{type:"button",className:"workbench-directory-browser-item",disabled:z,onClick:()=>{L(ee.path)},children:[s.jsx("span",{className:"workbench-directory-browser-item-name",children:ee.name}),s.jsx("span",{className:"workbench-directory-browser-item-path",children:ee.path})]},ee.path))}):s.jsx("p",{className:"workbench-directory-browser-status status-text",children:a("shell.importBrowserEmpty")})]}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:i,onClick:E,children:a("common.cancel")}),s.jsx("button",{type:"button",className:"primary-button",disabled:z||!b,onClick:te,children:a("shell.cloneBrowserSubmit")})]})]})]})}const t3="butler:inbox-updated";function Uf(){typeof window>"u"||window.dispatchEvent(new Event(t3))}const qx={projectId:"",itemType:"task",title:"",content:"",status:"pending"};function xN({active:e,preferredWorkspaceId:t,preferredSessionId:n,creationRequestId:r=0,initialDraft:i=null,compactComposer:o=!1,composerOpen:l=!0,onComposerOpenChange:c}){const{showToast:u}=Vn(),[f,h]=d.useState(!1),[m,g]=d.useState(!1),[p,b]=d.useState([]),[y,x]=d.useState([]),[k,C]=d.useState(null),[j,H]=d.useState(null),[_,T]=d.useState(qx),[P,z]=d.useState(!1),L=d.useMemo(()=>Kx(p,t,j),[j,t,p]),R=d.useMemo(()=>P?y:y.filter(U=>U.status!=="closed"),[y,P]);d.useEffect(()=>{e&&K()},[e,n]),d.useEffect(()=>{!e||k||T(U=>{const he=Yx({projects:L,currentProjectId:U.projectId,preferredProjectId:j,preferredWorkspaceId:t});return he===U.projectId?U:{...U,projectId:he}})},[e,k,j,t,L]),d.useEffect(()=>{!e||r<=0||(E(void 0,t,i,j),c==null||c(!0))},[e,r,i,c,j,t]);async function K(){h(!0);try{const[U,he,X]=await Promise.all([TO(),ep(),n?EO(n).catch(()=>null):Promise.resolve(null)]),I=(X==null?void 0:X.target.project.id)??null;H(I),b(U.items),x(he.items),k||E(U.items,t,r>0?i:null,I)}catch(U){u({title:a("shell.butlerInboxLoadFailed"),description:U instanceof Error?U.message:void 0,tone:"error"})}finally{h(!1)}}function E(U=p,he=t,X=i,I=j){var le,M;const xe=Kx(U,he,I);C(null),T({...qx,projectId:Yx({projects:xe,preferredProjectId:I,preferredWorkspaceId:he}),title:((le=X==null?void 0:X.title)==null?void 0:le.trim())??"",content:((M=X==null?void 0:X.content)==null?void 0:M.trim())??""})}function D(U){C(U.id),T({projectId:U.projectId,itemType:U.itemType,title:U.title,content:U.content,status:U.status}),o&&(c==null||c(!0))}async function te(U){U.preventDefault(),g(!0);try{k?(await zb(k,{projectId:_.projectId,itemType:_.itemType,title:_.title,content:_.content,status:_.status,priority:"medium"}),u({title:a("shell.butlerInboxUpdated"),tone:"success"})):(await IO({projectId:_.projectId,itemType:_.itemType,title:_.title,content:_.content,status:_.status,priority:"medium"}),u({title:a("shell.butlerInboxCreated"),tone:"success"})),Uf(),await K(),E(),o&&(c==null||c(!1))}catch(he){u({title:a("shell.butlerInboxSaveFailed"),description:he instanceof Error?he.message:void 0,tone:"error"})}finally{g(!1)}}async function V(U){g(!0);try{await RO(U),u({title:a("shell.butlerInboxDeleted"),tone:"success"}),Uf(),await K(),k===U&&E()}catch(he){u({title:a("shell.butlerInboxDeleteFailed"),description:he instanceof Error?he.message:void 0,tone:"error"})}finally{g(!1)}}async function ee(U,he){if(U.status!==he){g(!0);try{await zb(U.id,{status:he}),u({title:a("shell.butlerInboxUpdated"),tone:"success"}),Uf(),await K(),k===U.id&&T(X=>({...X,status:he}))}catch(X){u({title:a("shell.butlerInboxSaveFailed"),description:X instanceof Error?X.message:void 0,tone:"error"})}finally{g(!1)}}}return s.jsxs("div",{className:"workspace-inbox-modal",children:[o?null:s.jsx("section",{className:"workspace-inbox-panel",children:s.jsx(Vx,{selectableProjects:L,formState:_,saving:m,editingItemId:k,useMobilePicker:!1,onProjectChange:U=>{T(he=>({...he,projectId:U}))},onItemTypeChange:U=>{T(he=>({...he,itemType:U}))},onStatusChange:U=>{T(he=>({...he,status:U}))},onTitleChange:U=>{T(he=>({...he,title:U}))},onContentChange:U=>{T(he=>({...he,content:U}))},onCancel:()=>E(),onSubmit:te})}),s.jsxs("section",{className:"workspace-inbox-panel",children:[s.jsxs("header",{className:"workspace-inbox-panel-header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:a("shell.butlerInboxListTitle")}),s.jsx("p",{children:a("shell.butlerInboxListDescription")})]}),s.jsxs("label",{className:"workspace-inbox-closed-toggle",children:[s.jsx("input",{type:"checkbox",checked:P,onChange:U=>z(U.target.checked)}),s.jsx("span",{children:a("shell.butlerInboxShowClosedAction")})]})]}),f?s.jsx("p",{className:"workspace-inbox-status",children:a("shell.butlerInboxLoading")}):null,!f&&R.length===0?s.jsx("p",{className:"workspace-inbox-status",children:a("shell.butlerInboxEmpty")}):null,!f&&R.length>0?s.jsx("div",{className:"workspace-inbox-list",children:R.map(U=>s.jsxs("article",{className:"workspace-inbox-item",children:[s.jsxs("div",{className:"workspace-inbox-item-header",children:[s.jsxs("div",{children:[s.jsx("strong",{children:U.title}),s.jsx("p",{children:U.projectName})]}),s.jsxs("div",{className:"workspace-inbox-item-badges",children:[s.jsx("span",{className:"workspace-inbox-badge",children:Jx(U.status)}),s.jsx("span",{className:"workspace-inbox-badge",children:a3(U.itemType)})]})]}),s.jsx("p",{className:"workspace-inbox-item-content",children:U.content}),s.jsxs("div",{className:"workspace-inbox-item-footer",children:[s.jsx("span",{children:o3(U.updatedAt)}),s.jsxs("div",{className:"workspace-inbox-item-actions",children:[s.jsx("div",{className:"workspace-inbox-status-quick-actions",role:"group","aria-label":a("shell.butlerInboxQuickStatusLabel"),children:["pending","in_progress","closed"].map(he=>{const X=U.status===he;return s.jsx("button",{type:"button",className:"secondary-button","data-active":X,disabled:m,onClick:()=>{ee(U,he)},children:Jx(he)},`${U.id}:${he}`)})}),s.jsx("button",{type:"button",className:"secondary-button",disabled:m,onClick:()=>D(U),children:a("shell.butlerInboxEditAction")}),s.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:m,onClick:()=>{V(U.id)},children:a("shell.butlerInboxDeleteAction")})]})]})]},U.id))}):null]}),o?s.jsx(ln,{open:e&&l,title:k?a("shell.butlerInboxEditingTitle"):a("shell.butlerInboxCreateTitle"),description:a("shell.butlerInboxFormDescription"),className:"workspace-inbox-modal-card workspace-inbox-composer-modal-card",onClose:()=>{c==null||c(!1),E()},children:s.jsx("div",{className:"workspace-inbox-composer-modal-body",children:s.jsx(Vx,{selectableProjects:L,formState:_,saving:m,editingItemId:k,useMobilePicker:!0,onProjectChange:U=>{T(he=>({...he,projectId:U}))},onItemTypeChange:U=>{T(he=>({...he,itemType:U}))},onStatusChange:U=>{T(he=>({...he,status:U}))},onTitleChange:U=>{T(he=>({...he,title:U}))},onContentChange:U=>{T(he=>({...he,content:U}))},onCancel:()=>{c==null||c(!1),E()},onSubmit:te})})}):null]})}function Vx(e){const t=e.selectableProjects.map(i=>({value:i.id,label:i.name})),n=[{value:"task",label:a("shell.butlerInboxTypeTask")},{value:"bug",label:a("shell.butlerInboxTypeBug")},{value:"feature",label:a("shell.butlerInboxTypeFeature")},{value:"change",label:a("shell.butlerInboxTypeChange")}],r=[{value:"pending",label:a("shell.butlerInboxStatusPending")},{value:"in_progress",label:a("shell.butlerInboxStatusInProgress")},{value:"closed",label:a("shell.butlerInboxStatusClosed")}];return s.jsxs(s.Fragment,{children:[s.jsxs("header",{className:"workspace-inbox-panel-header",children:[s.jsx("h3",{children:e.editingItemId?a("shell.butlerInboxEditingTitle"):a("shell.butlerInboxCreateTitle")}),s.jsx("p",{children:a("shell.butlerInboxFormDescription")})]}),e.selectableProjects.length===0?s.jsx("p",{className:"workspace-inbox-status",children:a("shell.butlerInboxProjectsEmpty")}):s.jsxs("form",{className:"workspace-inbox-form",onSubmit:e.onSubmit,children:[s.jsx("div",{className:"workspace-inbox-form-grid",children:e.useMobilePicker?s.jsxs(s.Fragment,{children:[s.jsx(qf,{label:a("shell.butlerInboxProjectLabel"),value:e.formState.projectId,options:t,disabled:e.saving,onChange:e.onProjectChange}),s.jsx(qf,{label:a("shell.butlerInboxTypeLabel"),value:e.formState.itemType,options:n,disabled:e.saving,onChange:e.onItemTypeChange}),s.jsx(qf,{label:a("shell.butlerInboxStatusLabel"),value:e.formState.status,options:r,disabled:e.saving,onChange:e.onStatusChange})]}):s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.butlerInboxProjectLabel")}),s.jsx("select",{value:e.formState.projectId,disabled:e.saving,onChange:i=>e.onProjectChange(i.target.value),children:e.selectableProjects.map(i=>s.jsx("option",{value:i.id,children:i.name},i.id))})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.butlerInboxTypeLabel")}),s.jsxs("select",{value:e.formState.itemType,disabled:e.saving,onChange:i=>e.onItemTypeChange(i.target.value),children:[s.jsx("option",{value:"task",children:a("shell.butlerInboxTypeTask")}),s.jsx("option",{value:"bug",children:a("shell.butlerInboxTypeBug")}),s.jsx("option",{value:"feature",children:a("shell.butlerInboxTypeFeature")}),s.jsx("option",{value:"change",children:a("shell.butlerInboxTypeChange")})]})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.butlerInboxStatusLabel")}),s.jsxs("select",{value:e.formState.status,disabled:e.saving,onChange:i=>e.onStatusChange(i.target.value),children:[s.jsx("option",{value:"pending",children:a("shell.butlerInboxStatusPending")}),s.jsx("option",{value:"in_progress",children:a("shell.butlerInboxStatusInProgress")}),s.jsx("option",{value:"closed",children:a("shell.butlerInboxStatusClosed")})]})]})]})}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.butlerInboxTitleLabel")}),s.jsx("input",{value:e.formState.title,placeholder:a("shell.butlerInboxTitlePlaceholder"),disabled:e.saving,onChange:i=>e.onTitleChange(i.target.value)})]}),s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.butlerInboxContentLabel")}),s.jsx("textarea",{rows:4,value:e.formState.content,placeholder:a("shell.butlerInboxContentPlaceholder"),disabled:e.saving,onChange:i=>e.onContentChange(i.target.value)})]}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:e.saving,onClick:e.onCancel,children:e.editingItemId?a("shell.butlerInboxCancelEditAction"):a("common.cancel")}),s.jsx("button",{type:"submit",className:"primary-button",disabled:e.saving||!e.formState.projectId,children:e.editingItemId?a("shell.butlerInboxUpdateAction"):a("shell.butlerInboxCreateAction")})]})]})]})}function qf({label:e,value:t,options:n,disabled:r,onChange:i}){const[o,l]=d.useState(!1),c=n.find(u=>u.value===t)??n[0]??null;return d.useEffect(()=>{if(!o)return;function u(f){f.key==="Escape"&&l(!1)}return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[o]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"workbench-modal-field workspace-inbox-mobile-picker",children:[s.jsx("span",{children:e}),s.jsxs("button",{type:"button",className:"workspace-inbox-mobile-picker-trigger","aria-label":e,"aria-haspopup":"dialog","aria-expanded":o,disabled:r||n.length===0,onClick:()=>l(!0),children:[s.jsx("span",{className:"workspace-inbox-mobile-picker-trigger-value",children:(c==null?void 0:c.label)??""}),s.jsx("span",{className:"workspace-inbox-mobile-picker-trigger-icon",children:s.jsx(r3,{expanded:o})})]})]}),s.jsx(n3,{open:o,title:e,options:n,selectedValue:t,onClose:()=>l(!1),onSelect:u=>{i(u),l(!1)}})]})}function n3({open:e,title:t,options:n,selectedValue:r,onClose:i,onSelect:o}){return e?s.jsx(zi,{open:e,title:t,kind:"picker",height:"half",className:"workspace-inbox-picker-sheet",cardClassName:"workspace-inbox-picker-sheet-card",bodyClassName:"workspace-inbox-picker-sheet-body",showHandle:!0,onClose:i,children:s.jsx(Wi,{className:"workspace-inbox-picker-sheet-options",role:"listbox","aria-label":t,children:n.map(l=>{const c=l.value===r;return s.jsx(rs,{as:"button",className:"workspace-inbox-picker-option",role:"option","aria-selected":c,selected:c,trailing:s.jsx("span",{className:"workspace-inbox-picker-option-indicator","aria-hidden":"true",children:c?s.jsx(i3,{}):null}),onClick:()=>o(l.value),children:s.jsxs("span",{className:"workspace-inbox-picker-option-copy",children:[s.jsx("strong",{children:l.label}),l.description?s.jsx("span",{children:l.description}):null]})},l.value)})})}):null}function CK({open:e,preferredWorkspaceId:t,preferredSessionId:n,creationRequestId:r=0,initialDraft:i=null,onClose:o,compactComposer:l=!1}){const[c,u]=d.useState(0),[f,h]=d.useState(!l);return d.useEffect(()=>{e||h(!l)},[l,e]),s.jsx(ln,{open:e,title:a("shell.butlerInboxModalTitle"),description:a("shell.butlerInboxModalDescription"),className:"workspace-inbox-modal-card",showCloseButton:!l,headerActions:l?s.jsx("button",{type:"button",className:"workspace-inbox-modal-create-button","aria-label":a("shell.butlerInboxCreateAction"),title:a("shell.butlerInboxCreateAction"),onClick:()=>{u(m=>m+1),h(!0)},children:s.jsx(s3,{})}):void 0,onClose:o,children:s.jsx(xN,{active:e,preferredWorkspaceId:t,preferredSessionId:n,creationRequestId:Math.max(r,c),initialDraft:i,compactComposer:l,composerOpen:f,onComposerOpenChange:h})})}function Kx(e,t,n){return[...e].filter(r=>r.lifecycleStatus!=="archived").sort((r,i)=>{const o=Gx(r,t,n),l=Gx(i,t,n);return o!==l?l-o:r.name.localeCompare(i.name,"zh-Hans-CN")})}function Gx(e,t,n){return n&&e.id===n?2:t&&e.workspaceId===t?1:0}function Yx({projects:e,currentProjectId:t,preferredProjectId:n,preferredWorkspaceId:r}){var o;if(t&&e.some(l=>l.id===t))return t;if(n&&e.some(l=>l.id===n))return n;const i=r?e.find(l=>l.workspaceId===r):null;return(i==null?void 0:i.id)||((o=e[0])==null?void 0:o.id)||""}function s3(){return s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M5 12h14"})]})}function r3({expanded:e}){return s.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true","data-expanded":e?"true":void 0,children:s.jsx("path",{d:"M3.5 6 8 10l4.5-4",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.6"})})}function i3(){return s.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:s.jsx("path",{d:"M3.5 8.4 6.6 11.5 12.5 5.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8"})})}function a3(e){switch(e){case"bug":return a("shell.butlerInboxTypeBug");case"feature":return a("shell.butlerInboxTypeFeature");case"change":return a("shell.butlerInboxTypeChange");case"task":default:return a("shell.butlerInboxTypeTask")}}function Jx(e){switch(e){case"in_progress":return a("shell.butlerInboxStatusInProgress");case"closed":return a("shell.butlerInboxStatusClosed");case"pending":default:return a("shell.butlerInboxStatusPending")}}function o3(e){return new Date(e).toLocaleString()}function l3({onOpenSoftwareUpdate:e}){var r;const t=Bu(i=>i.platform),n=NT(i=>i.latestState);return t!=="desktop"||!(n!=null&&n.hasUpdate)?null:s.jsx("button",{className:"workbench-nav-update-badge",type:"button",title:((r=n.manifest)==null?void 0:r.version)??a("settings.releaseUpdateReady"),onClick:e,children:s.jsx("span",{className:"workbench-nav-update-badge-label",children:a("settings.releaseUpdateBadge")})})}const Oc=["codex","claude-code","gemini"];function kN(e){return{provider:e,model:"",providerConfigMode:"global-default",providerPresetId:null,memberPrompt:"",workspaceIsolationMode:"none"}}function Xx(e,t){return Array.from({length:t},()=>kN(e))}function Vf(e,t){var n;return(n=e==null?void 0:e.modelOptions)!=null&&n.length?e.modelOptions:Ja(t).modelOptions??[]}function Qx(e,t,n){return t!=="cc-switch-preset"||!n?null:`${e}::${n}`}function Zx(e,t){return Math.max(0,e-t.length)}function c3({open:e,source:t,onClose:n,onCreated:r}){const i=d.useId(),o=(t==null?void 0:t.defaultProvider)??"codex",l=(t==null?void 0:t.kind)==="group",c=(t==null?void 0:t.kind)==="group"?Math.max(0,4-t.currentMemberCount):4,u=d.useMemo(()=>(t==null?void 0:t.kind)==="group"?Array.from({length:c},(Q,ge)=>ge+1):[2,3,4],[c,t==null?void 0:t.kind]),f=(t==null?void 0:t.kind)==="group"?1:2,h=(t==null?void 0:t.kind)==="group"?t.sharedPrompt:"",{visibleProviders:m}=fp(Dm,e),[g,p]=d.useState(h),[b,y]=d.useState(f),[x,k]=d.useState(()=>Xx(o,f)),[C,j]=d.useState({}),[H,_]=d.useState({}),[T,P]=d.useState({}),[z,L]=d.useState({}),[R,K]=d.useState({}),[E,D]=d.useState(!1),[te,V]=d.useState(!1),[ee,U]=d.useState(null),[he,X]=d.useState(null),[I,xe]=d.useState({}),le=d.useRef(!1),M=d.useRef({});d.useEffect(()=>{if(!e)return;const Q=(t==null?void 0:t.defaultProvider)??"codex",ge=(t==null?void 0:t.kind)==="group"?1:2;p((t==null?void 0:t.kind)==="group"?t.sharedPrompt:""),y(ge),k(Xx(Q,ge)),j({}),_({}),P({}),L({}),K({}),D(!1),V(!1),U(null),X(null),xe({}),le.current=!1,Object.keys(M.current).forEach(Oe=>{delete M.current[Oe]})},[e,t==null?void 0:t.defaultProvider,t==null?void 0:t.kind,t==null?void 0:t.workspaceId,(t==null?void 0:t.kind)==="session"?t.sessionId:null,(t==null?void 0:t.kind)==="group"?t.groupId:null,(t==null?void 0:t.kind)==="group"?t.sharedPrompt:null]),d.useEffect(()=>{k(Q=>{var $e;if(Q.length===b)return Q;if(Q.length>b)return Q.slice(0,b);const ge=Q.slice(),Oe=(($e=Q[0])==null?void 0:$e.provider)??o;for(;ge.length<b;)ge.push(kN(Oe));return ge})},[o,b]),d.useEffect(()=>{u.length!==0&&y(Q=>u.includes(Q)?Q:u[0]??Q)},[u]),d.useEffect(()=>{if(!e||!t)return;let Q=!1;return D(!0),km(m,t.workspaceId).then(ge=>{Q||j(ge)}).finally(()=>{Q||D(!1)}),()=>{Q=!0}},[e,t==null?void 0:t.workspaceId,m]),d.useEffect(()=>{e&&(le.current||(le.current=!0,P(Q=>({...Q,...Object.fromEntries(Oc.map(ge=>[ge,!0]))})),Bh().then(Q=>{const ge=Object.fromEntries(Q.items.map(Oe=>[Oe.app,Oe]));_(Object.fromEntries(Oc.map(Oe=>[Oe,ge[Oe]??null])))}).catch(()=>{_(Object.fromEntries(Oc.map(Q=>[Q,null])))}).finally(()=>{P(Q=>({...Q,...Object.fromEntries(Oc.map(ge=>[ge,!1]))}))})))},[e]),d.useEffect(()=>{if(!e||!t)return;const Q=Array.from(new Set(x.map(ge=>{const Oe=ci(ge.providerConfigMode,ge.providerPresetId);return Qx(ge.provider,Oe.providerConfigMode,Oe.providerPresetId)}).filter(ge=>ge!==null))).filter(ge=>z[ge]===void 0&&!M.current[ge]);if(Q.length!==0)for(const ge of Q){const[Oe,$e]=ge.split("::");M.current[ge]=!0,K(Ve=>({...Ve,[ge]:!0})),no(Oe,t.workspaceId,{providerConfigMode:"cc-switch-preset",providerPresetId:$e}).then(Ve=>{L(G=>({...G,[ge]:Ve}))}).catch(()=>{L(Ve=>({...Ve,[ge]:null}))}).finally(()=>{delete M.current[ge],K(Ve=>({...Ve,[ge]:!1}))})}},[z,x,e,t]);const de=d.useMemo(()=>m.filter(Q=>{const ge=C[Q];return ge?ge.canStartSession!==!1:!1}),[C,m]);d.useEffect(()=>{if(!de.length)return;const Q=de.includes(o)?o:de[0];k(ge=>{let Oe=!1;const $e=ge.map(Ve=>de.includes(Ve.provider)?Ve:(Oe=!0,{...Ve,provider:Q,providerConfigMode:"global-default",providerPresetId:null,model:""}));return Oe?$e:ge})},[de,o]);const Ne=d.useMemo(()=>x.map((Q,ge)=>{var pt;const Oe=ci(Q.providerConfigMode,Q.providerPresetId),$e=Pi(Q.provider),Ve=$e?H[$e]??null:null,G=Wh(Ve),ve=Oe.providerConfigMode==="cc-switch-preset"?Oe.providerPresetId??Dr:Dr,_e=G.find(Ie=>Ie.value===ve)??G[0]??null,nt=Qx(Q.provider,Oe.providerConfigMode,Oe.providerPresetId),et=C[Q.provider]??null,ot=nt?z[nt]??null:null,Ft=(Oe.providerConfigMode==="cc-switch-preset"?ot?Vf(ot,Q.provider):[{id:di,name:a("conversation.modelUseCliDefault"),usesProviderDefault:!0}]:Vf(et,Q.provider)).map(Ie=>({value:Ie.id,label:qo(Ie)?a("conversation.modelUseCliDefault"):Ie.name})),bt=Q.model.trim()||di,_t=((pt=Ft.find(Ie=>Ie.value===bt))==null?void 0:pt.label)??a("conversation.modelUseCliDefault"),xt=$h(Ve),rt=$e!==null,It=nt?R[nt]===!0:!1,$t=!!(nt&&It&&ot===null);return{index:ge,draft:Q,supportsDeploymentPicker:rt,showPresetColumn:xt,deploymentPresetOptions:G,selectedPresetValue:ve,selectedPresetOption:_e,triggerLabel:xt?`${(_e==null?void 0:_e.label)??a("conversation.deploymentDefaultPreset")} · ${_t}`:_t,selectedModelValue:bt,modelOptions:Ft,loadingPresets:$e?T[$e]===!0:!1,loadingModels:It,modelColumnDisabled:$t}}),[z,H,T,R,x,C]);if(d.useEffect(()=>{e&&k(Q=>{let ge=!1;const Oe=Q.map(($e,Ve)=>{const G=Ne[Ve];if(!G)return $e;let ve=$e;const _e=ci($e.providerConfigMode,$e.providerPresetId);_e.providerConfigMode==="cc-switch-preset"&&_e.providerPresetId&&!G.loadingPresets&&!G.deploymentPresetOptions.some(ot=>ot.value===_e.providerPresetId)&&(ve={...ve,providerConfigMode:"global-default",providerPresetId:null,model:""},ge=!0);const nt=new Set(G.modelOptions.map(ot=>ot.value)),et=ve.model.trim()||di;return nt.has(et)||(ve={...ve,model:""},ge=!0),ve});return ge?Oe:Q})},[Ne,e]),!e||!t)return null;const ye=t,Be=he?Zx(x.length,he.memberFailures):0,We=new Set(he?x.map((Q,ge)=>ge).filter(Q=>!(Q in I)):[]),Ce=ye.kind==="group"?a("shell.parallelAppendModalTitle"):a("shell.parallelCreateModalTitle"),ke=ye.kind==="session"?`${ye.workspaceName} · ${ye.sessionTitle}`:ye.workspaceName,we=ye.kind==="group"?a("shell.parallelAppendSharedPromptLabel"):a("shell.parallelCreateSharedPromptLabel"),se=ye.kind==="group"?a("shell.parallelAppendCountLabel"):a("shell.parallelCreateCountLabel"),ce=ye.kind==="group"?a("shell.parallelAppendSubmit"):a("shell.parallelCreateSubmit"),Y=ye.kind==="group"?a("shell.parallelAppendSubmitting"):a("shell.parallelCreateSubmitting"),Te=ee??(ye.kind==="group"&&c===0?a("shell.parallelAppendNoRemainingSlots"):null)??(!E&&de.length===0?a("shell.parallelCreateNoAvailableProviders"):null),pe={"--parallel-member-columns":String(Math.max(1,Math.min(b,4)))};function fe(Q){U(null),X(null),xe(ge=>{if(!(Q in ge))return ge;const Oe={...ge};return delete Oe[Q],Oe})}function W(){U(null),X(null),xe({})}function Me(Q,ge){fe(Q);const Oe=ge?"temporary_worktree":"none";k($e=>$e.map((Ve,G)=>G===Q?{...Ve,workspaceIsolationMode:Oe}:Ve))}async function je(){const Q=g.trim();if(!l&&!Q){U(a("shell.parallelCreatePromptRequired"));return}if(ye.kind==="group"&&c===0){U(a("shell.parallelAppendNoRemainingSlots"));return}if(!de.length){U(a("shell.parallelCreateNoAvailableProviders"));return}V(!0),U(null),X(null),xe({});try{const ge=wC(),Oe=x.map(Ve=>{const G=ci(Ve.providerConfigMode,Ve.providerPresetId);return{provider:Ve.provider,model:Ve.model.trim()||null,providerConfigMode:G.providerConfigMode,providerPresetId:G.providerConfigMode==="cc-switch-preset"?G.providerPresetId:null,memberPrompt:Ve.memberPrompt.trim()||null,workspaceIsolationMode:Ve.workspaceIsolationMode}}),$e=ye.kind==="group"?await f0(ye.groupId,{permissionMode:ge,members:Oe}):ye.kind==="session"?await u0(ye.sessionId,{sharedPrompt:Q,permissionMode:ge,members:Oe}):await d0(ye.workspaceId,{sharedPrompt:Q,permissionMode:ge,members:Oe});if($e.memberFailures.length>0){const Ve=Zx(x.length,$e.memberFailures);X($e),xe(Object.fromEntries($e.memberFailures.map(G=>[G.ordinal,G]))),U(Ve>0?a("shell.parallelCreatePartialFailure",{successCount:Ve,failureCount:$e.memberFailures.length}):a("shell.parallelCreateAllFailed",{failureCount:$e.memberFailures.length}));return}await r($e)}catch(ge){U(ge instanceof Error?ge.message:a("shell.parallelGroupLoadFailed"))}finally{V(!1)}}return s.jsx(Qr,{open:e,title:Ce,description:ke,size:"xwide",layout:"form",className:"parallel-create-modal",bodyClassName:"parallel-create-modal-body",dismissible:!te,onClose:n,footer:s.jsxs(Es,{align:"between",className:"parallel-create-modal-footer",children:[s.jsx("div",{className:"parallel-create-modal-status",role:"status","aria-live":"polite",children:Te?s.jsx("span",{className:"parallel-create-modal-error",children:Te}):null}),s.jsxs("div",{className:"parallel-create-modal-footer-actions",children:[he&&Be>0?s.jsx("button",{type:"button",className:"secondary-button",disabled:te,onClick:()=>{r(he)},children:a("shell.parallelCreateContinuePartial")}):null,s.jsx("button",{type:"button",className:"secondary-button",disabled:te,onClick:n,children:a("common.cancel")}),s.jsx("button",{type:"button",className:"primary-button",disabled:te||E||de.length===0||ye.kind==="group"&&c===0,onClick:()=>{je()},children:te?Y:ce})]})]}),children:s.jsxs("div",{className:"parallel-create-layout",children:[s.jsx(Jn,{className:"parallel-create-shared-section",tone:"accent",children:s.jsxs("div",{className:"parallel-create-target-row",children:[s.jsx(Ot,{className:"parallel-create-target-field",label:we,htmlFor:`${i}-shared-prompt`,children:s.jsx("textarea",{id:`${i}-shared-prompt`,className:"parallel-create-textarea parallel-create-textarea-target",rows:2,value:g,readOnly:l,"aria-readonly":l,"data-readonly":l?"true":void 0,onChange:Q=>{l||(W(),p(Q.target.value))}})}),s.jsx(Ot,{className:"parallel-create-count-field",label:se,children:s.jsx("div",{className:"parallel-create-count-group",role:"group","aria-label":se,children:u.map(Q=>s.jsx("button",{type:"button",className:"parallel-create-count-button","data-active":b===Q,onClick:()=>{W(),y(Q)},children:Q},Q))})})]})}),s.jsx(Jn,{className:"parallel-create-members-section",heading:a("shell.parallelCreateMembersTitle"),children:s.jsx("div",{className:"parallel-create-member-list",style:pe,children:Ne.map(({draft:Q,index:ge,supportsDeploymentPicker:Oe,showPresetColumn:$e,deploymentPresetOptions:Ve,selectedPresetValue:G,selectedPresetOption:ve,triggerLabel:_e,selectedModelValue:nt,modelOptions:et,loadingPresets:ot,loadingModels:jt,modelColumnDisabled:Ft})=>{var $t;const bt=de,_t=bt.includes(Q.provider)?Q.provider:"",xt=bt.length>0?bt.map(pt=>({value:pt,label:Ui(pt,"full")})):[{value:"",label:E?a("shell.parallelCreateProvidersLoading"):a("shell.parallelCreateNoAvailableProviders")}],rt=Vf(C[Q.provider]??null,Q.provider),It=rt.length>0?[{value:"",label:(($t=rt.find(pt=>pt.usesProviderDefault===!0))==null?void 0:$t.name)??a("shell.parallelPaneModelFallback")},...rt.filter(pt=>pt.usesProviderDefault!==!0).map(pt=>({value:pt.id,label:pt.name}))]:[{value:"",label:a("shell.parallelCreateNoModelsAvailable")}];return s.jsxs("article",{className:"parallel-create-member-card","data-state":I[ge]?"error":We.has(ge)?"success":void 0,children:[s.jsxs("header",{className:"parallel-create-member-header",children:[s.jsxs("div",{className:"parallel-create-member-title-block",children:[s.jsx("strong",{children:a("shell.parallelCreateMemberTitle",{index:ge+1})}),s.jsx("span",{className:"parallel-create-member-provider",children:Ui(Q.provider,"full")}),s.jsxs("label",{className:"parallel-create-isolation-toggle",children:[s.jsx("input",{type:"checkbox",checked:Q.workspaceIsolationMode==="temporary_worktree",onChange:pt=>{Me(ge,pt.target.checked)}}),s.jsx("span",{className:"parallel-create-isolation-copy",children:a("shell.parallelCreateIsolationLabel")})]})]}),I[ge]?s.jsx("span",{className:"parallel-create-member-status error",children:a("shell.parallelCreateMemberFailed")}):We.has(ge)?s.jsx("span",{className:"parallel-create-member-status success",children:a("shell.parallelCreateMemberSucceeded")}):null]}),s.jsxs("div",{className:"parallel-create-member-grid",children:[s.jsx(Ot,{label:a("shell.createSessionProviderLabel"),htmlFor:`${i}-member-${ge}-provider`,children:s.jsx(Ha,{triggerId:`${i}-member-${ge}-provider`,className:"parallel-create-provider-select",ariaLabel:a("shell.createSessionProviderLabel"),value:_t,options:xt,disabled:!bt.length,onChange:pt=>{fe(ge);const Ie=pt;k(kt=>kt.map((St,vt)=>vt===ge?{...St,provider:Ie,providerConfigMode:"global-default",providerPresetId:null,model:""}:St))}})}),s.jsx(Ot,{label:a("shell.parallelCreateModelLabel"),htmlFor:Oe?void 0:`${i}-member-${ge}-model`,children:Oe?s.jsx("div",{className:"parallel-create-deployment-select",children:s.jsx(zh,{triggerId:`${i}-member-${ge}-model`,ariaLabel:a("shell.parallelCreateModelLabel"),triggerLabel:_e,presetOptions:Ve,selectedPresetValue:G,selectedPresetSummary:(ve==null?void 0:ve.summary)??null,onSelectPreset:pt=>{fe(ge),k(Ie=>Ie.map((kt,St)=>St!==ge?kt:pt===Dr?{...kt,providerConfigMode:"global-default",providerPresetId:null,model:""}:{...kt,providerConfigMode:"cc-switch-preset",providerPresetId:pt,model:""}))},modelOptions:et,selectedModelValue:nt,onSelectModel:pt=>{fe(ge),k(Ie=>Ie.map((kt,St)=>St===ge?{...kt,model:pt===di?"":pt}:kt))},loadingPresets:ot,loadingModels:jt,modelColumnDisabled:Ft,showPresetColumn:$e,modelEmptyText:a("conversation.deploymentModelEmpty")})}):s.jsx(Ha,{triggerId:`${i}-member-${ge}-model`,className:"parallel-create-provider-select",ariaLabel:a("shell.parallelCreateModelLabel"),value:Q.model,options:It,disabled:!bt.length||rt.length===0,onChange:pt=>{fe(ge),k(Ie=>Ie.map((kt,St)=>St===ge?{...kt,model:pt}:kt))}})})]}),s.jsx(Ot,{label:a("shell.parallelCreateMemberPromptLabel"),htmlFor:`${i}-member-${ge}-prompt`,children:s.jsx("textarea",{id:`${i}-member-${ge}-prompt`,className:"parallel-create-textarea member",rows:2,value:Q.memberPrompt,onChange:pt=>{fe(ge);const Ie=pt.target.value;k(kt=>kt.map((St,vt)=>vt===ge?{...St,memberPrompt:Ie}:St))}})}),I[ge]?s.jsxs("div",{className:"parallel-create-member-error",role:"alert",children:[s.jsx("strong",{children:a("shell.parallelCreateMemberErrorTitle")}),s.jsx("p",{children:I[ge].detail})]}):null]},`parallel-member-${ge}`)})})})]})})}const u3=12,d3=180,ek=72;function f3(e,t){const[n,r]=d.useState(!1),[i,o]=d.useState(""),[l,c]=d.useState({}),[u,f]=d.useState({}),[h,m]=d.useState(!1),[g,p]=d.useState(null);d.useEffect(()=>{e||(r(!1),o(""),p(null))},[e]),d.useEffect(()=>{if(!e||!n)return;const x=t.filter(C=>u[C.sessionId]!==!0);if(x.length===0)return;let k=!1;return m(!0),p(null),Promise.allSettled(x.map(async C=>{const j=await uu(C.sessionId,null,u3,"backward");return{sessionId:C.sessionId,summary:h3(j.messages)}})).then(C=>{if(k)return;const j={},H={};let _=0;x.forEach(T=>{j[T.sessionId]=!0});for(const T of C){if(T.status==="fulfilled"){H[T.value.sessionId]=T.value.summary;continue}_+=1}f(T=>({...T,...j})),Object.keys(H).length>0&&c(T=>({...T,...H})),p(_>0?a("shell.archiveSearchSummaryFailed"):null)}).finally(()=>{k||m(!1)}),()=>{k=!0}},[u,e,n,t]);const b=d.useMemo(()=>{const x=Kf(i);return x?t.filter(k=>Kf(k.title).includes(x)?!0:Kf(l[k.sessionId]??"").includes(x)):t},[i,t,l]);function y(){r(x=>{const k=!x;return k||(o(""),p(null)),k})}return{searchOpen:n,searchKeyword:i,filteredSessions:b,summaryLoading:h,summaryError:g,summaryBySessionId:l,setSearchKeyword:o,toggleSearch:y}}function h3(e){const t=[...e].sort((r,i)=>r.sequence-i.sequence).map(m3).filter(r=>r.length>0);if(t.length===0)return"";const n=t.slice(-3).join(" · ");return om(n,d3)}function m3(e){var n,r;const t=wN(e.content);return t.length>0?om(t,ek):(r=(n=e.toolCall)==null?void 0:n.name)!=null&&r.trim()?om(e.toolCall.name.trim(),ek):""}function Kf(e){return wN(e).toLocaleLowerCase()}function wN(e){return e.replace(/\s+/g," ").trim()}function om(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}const tk="workbench.left.width",nk="workbench.right.width",sk="workbench.left.collapsed",rk="workbench.right.collapsed",Fc="workbench.last.session.path",Gf="workbench.workspace.selected.id",ik="workbench.notifications.seen_at",p3=280,g3=320,ak=240,ok=280,lk=520,ck=560,b3=200,Yf=20,Bo=40,_c=5,y3=3e4,x3=12,uk=60*1e3,k3=4e3,dk=220,fk=18,w3=6,Ma="data-workbench-panel-resizing",Bc="data-workbench-window-resizing",v3=180,S3="workbench:focus-composer",C3=new Set(["starting","running","reconnecting","stale","unknown"]),j3=["#34C759","#22C55E","#14B8A6","#06B6D4","#0EA5E9","#3B82F6","#6366F1","#8B5CF6","#A855F7","#D946EF","#EC4899","#F43F5E","#EF4444","#F97316","#F59E0B","#EAB308","#84CC16","#10B981"],N3=["--workbench-titlebar-live-content-shift-y","--workbench-nav-toolbar-live-shift-y","--workbench-info-tabs-live-shift-y","--workbench-auxiliary-toolbar-button-live-shift-y","--workbench-conversation-header-main-live-shift-y","--workbench-conversation-header-actions-live-shift-y","--workbench-terminal-tabbar-live-shift-y","--workbench-collapsed-controls-live-shift-y","--workbench-collapsed-left-controls-live-shift-y","--workbench-collapsed-right-controls-live-shift-y"],$n={navToolbar:{selector:".workbench-nav-toolbar",variableName:"--workbench-nav-toolbar-live-shift-y"},infoTabs:{selector:".workbench-info-tabs",variableName:"--workbench-info-tabs-live-shift-y"},auxiliaryToolbarButton:{selector:".workbench-auxiliary-header > .workbench-nav-toolbar-button",variableName:"--workbench-auxiliary-toolbar-button-live-shift-y"},conversationHeaderMain:{selector:".conversation-header-main",variableName:"--workbench-conversation-header-main-live-shift-y"},conversationHeaderActions:{selector:".conversation-header-actions",variableName:"--workbench-conversation-header-actions-live-shift-y"},terminalTabbarMain:{selector:".terminal-tabbar-main",variableName:"--workbench-terminal-tabbar-live-shift-y"},collapsedLeftControls:{selector:'.workbench-collapsed-controls.left[data-visible="true"] .workbench-nav-toolbar-button',variableName:"--workbench-collapsed-left-controls-live-shift-y"},collapsedRightControls:{selector:'.workbench-collapsed-controls.right[data-visible="true"] .workbench-nav-toolbar-button',variableName:"--workbench-collapsed-right-controls-live-shift-y"}};function vN(e,t){const n=e.getPropertyValue(t).trim();if(!n)return null;const r=Number.parseFloat(n);return Number.isFinite(r)?r:null}function T3(e){return Math.round(e*100)/100}function I3(e,t){const n=t.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;const r=window.getComputedStyle(t);return r.display==="none"||r.visibility==="hidden"?null:n.top-e.top+n.height/2}function Ri(e,t){const n=e.getBoundingClientRect(),i=Array.from(e.querySelectorAll(t)).map(o=>I3(n,o)).filter(o=>o!==null);return i.length===0?null:i.reduce((o,l)=>o+l,0)/i.length}function qr(e,t,n){const r=e.style.getPropertyValue(t).trim();if(n===null||!Number.isFinite(n)){r&&e.style.removeProperty(t);return}const i=`${T3(n)}px`;r!==i&&e.style.setProperty(t,i)}function Vr(e,t,n,r){return r===null?null:(vN(e,t)??0)+(n-r)}function hk(e){if(e)for(const t of N3)e.style.removeProperty(t)}function A3(e){return C3.has(e.runningState??"idle")||e.activityState==="running"}function R3(e,t){const n=[];for(const r of[...t].sort()){const i=e.get(r);!i||i.size===0||n.push(`${r}:${[...i].sort().join(",")}`)}return n.join("|")}function P3(e){var i,o;const t=((i=e.lastErrorCode)==null?void 0:i.trim())??"",n=((o=e.lastErrorDetail)==null?void 0:o.trim())??"",r=[t,n].filter(l=>l.length>0).join(" · ");return r?r.length<=dk?r:`${r.slice(0,dk-3)}...`:null}function M3(e,t,n){var o,l,c,u,f,h,m,g,p,b,y,x;const r=new Map(e.projects.map(k=>[k.id,k.workspaceId])),i=[];for(const k of n){const C=k.title.trim()||k.projectName;if(k.assistantState.lifecycleStage==="analyzed"&&!((o=k.assistantState.linkedSessionId)!=null&&o.trim())&&k.assistantState.lastAnalyzedAt){i.push({id:`todo-analysis-completed:${k.id}:${k.assistantState.lastAnalyzedAt}`,kind:"todo_analyzed",title:a("shell.globalNotificationTodoAnalyzedTitle",{title:C}),body:((l=k.assistantState.analysisSummary)==null?void 0:l.trim())||((c=k.assistantState.generatedPrompt)==null?void 0:c.trim())||k.content,routePath:Fi(k.workspaceId),workspaceId:k.workspaceId,createdAt:k.assistantState.lastAnalyzedAt});continue}k.assistantState.lifecycleStage==="failed"&&i.push({id:`todo-analysis-failed:${k.id}:${k.updatedAt}`,kind:"todo_analyze_failed",title:a("shell.globalNotificationTodoAnalyzeFailedTitle",{title:C}),body:((u=k.assistantState.lastError)==null?void 0:u.trim())||k.content,routePath:Fi(k.workspaceId),workspaceId:k.workspaceId,createdAt:k.updatedAt})}for(const k of t){const C=((f=k.sessionTitle)==null?void 0:f.trim())||k.projectName,j=k.updatedAt||k.lastAutomationAt||k.createdAt;if(k.status==="waiting_user"){i.push({id:`follow-up-waiting:${k.id}`,kind:"follow_up_waiting_user",title:a("shell.globalNotificationFollowUpWaitingTitle",{title:C}),body:((h=k.waitingReason)==null?void 0:h.trim())||((m=k.lastAutomationSummary)==null?void 0:m.trim())||k.objective,routePath:Yr(k.workspaceId,k.sessionId),workspaceId:k.workspaceId,createdAt:j});continue}if(k.status==="completed"){i.push({id:`follow-up-completed:${k.id}`,kind:"follow_up_completed",title:a("shell.globalNotificationFollowUpCompletedTitle",{title:C}),body:((g=k.lastAutomationSummary)==null?void 0:g.trim())||k.objective,routePath:Yr(k.workspaceId,k.sessionId),workspaceId:k.workspaceId,createdAt:j});continue}k.status==="failed"&&i.push({id:`follow-up-failed:${k.id}`,kind:"follow_up_failed",title:a("shell.globalNotificationFollowUpFailedTitle",{title:C}),body:((p=k.lastAutomationSummary)==null?void 0:p.trim())||((b=k.waitingReason)==null?void 0:b.trim())||k.objective,routePath:Yr(k.workspaceId,k.sessionId),workspaceId:k.workspaceId,createdAt:j})}for(const k of e.verifications){if(k.status!=="failed")continue;const C=k.projectId?r.get(k.projectId)??null:null,j=((y=k.targetRef)==null?void 0:y.trim())||k.verificationType;i.push({id:`verification-failed:${k.id}`,kind:"verification_failed",title:a("shell.globalNotificationVerificationFailedTitle",{title:j}),body:((x=k.summary)==null?void 0:x.trim())||a("shell.globalNotificationVerificationFailedFallback"),routePath:C?Fi(C):null,workspaceId:C,createdAt:k.finishedAt||k.startedAt||k.createdAt})}return i.sort((k,C)=>{const j=mk(k.kind)-mk(C.kind);return j!==0?j:Bi(C.createdAt)-Bi(k.createdAt)}).slice(0,x3)}function mk(e){switch(e){case"follow_up_waiting_user":return 0;case"todo_analyze_failed":return 1;case"follow_up_failed":return 2;case"verification_failed":return 3;case"todo_analyzed":return 4;case"follow_up_completed":return 5;default:return 9}}function E3(e){switch(e){case"follow_up_waiting_user":return a("shell.globalNotificationKindWaitingUser");case"todo_analyzed":return a("shell.globalNotificationKindTodoAnalyzed");case"todo_analyze_failed":return a("shell.globalNotificationKindTodoAnalyzeFailed");case"follow_up_completed":return a("shell.globalNotificationKindFollowUpCompleted");case"follow_up_failed":return a("shell.globalNotificationKindFollowUpFailed");case"verification_failed":return a("shell.globalNotificationKindVerificationFailed");default:return a("shell.globalNotificationsPanelTitle")}}function Bi(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function L3(e){return/^(?:[A-Za-z0-9_-]+)(?:\/[A-Za-z0-9_-]+)*$/.test(e)}function D3(e){return/^(?:[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*\/?)?$/.test(e)}function O3(e,t){const n=new Set,r=(e==null?void 0:e.currentBranch)??"",i=((e==null?void 0:e.local)??[]).slice().sort((c,u)=>Number(u.current)-Number(c.current)||c.name.localeCompare(u.name)).map(c=>({value:c.name,current:c.current,recommended:c.name===r})).filter(c=>!c.value||n.has(c.value)?!1:(n.add(c.value),!0)),o=((e==null?void 0:e.remote)??[]).map(c=>({value:c.name})).filter(c=>!c.value||n.has(c.value)?!1:(n.add(c.value),!0)),l=t.map(c=>({value:c.name})).filter(c=>!c.value||n.has(c.value)?!1:(n.add(c.value),!0));return{localBranches:i,remoteBranches:o,tags:l}}function F3(e){return e.getBoundingClientRect()}function _3(e,t){return t?Bi(e.createdAt)>Bi(t):!0}function B3(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(t)}function lm(e,t){var l,c;const n=["/workspaces/:workspaceId","/workspaces/:workspaceId/affairs","/workspaces/:workspaceId/sessions","/workspaces/:workspaceId/sessions/:sessionId","/workspaces/:workspaceId/tools","/workspaces/:workspaceId/tools/files","/workspaces/:workspaceId/tools/git","/workspaces/:workspaceId/tools/processes","/workspaces/:workspaceId/terminals","/workspaces/:workspaceId/plugins","/workspaces/:workspaceId/plugins/:pluginId","/workspaces/:workspaceId/plugins/:pluginId/run","/workspaces/:workspaceId/butler"];for(const u of n){const f=Kt(u,e),h=(l=f==null?void 0:f.params.workspaceId)==null?void 0:l.trim();if(h)return h}const r=ul(e),i=(r==null?void 0:r.sessionId)??null;return!i||!ZN(i)?null:((c=new URLSearchParams(t).get("workspaceId"))==null?void 0:c.trim())||null}function cm(e,t){var r;const n=(r=Xq(e,t))==null?void 0:r.trim();if(!n)return null;try{const i=new URL(n,"https://codingns.local"),o=i.pathname,l=i.search;return yN(o)!==t||lm(o,l)!==e?null:`${o}${l}`}catch{return null}}function W3(e){return e.startsWith("/sessions")||e.startsWith("/terminals")||e.startsWith("/tools")}function Jf(e){return e==="mobile"?Fs():"/landing"}function ul(e){var o,l,c;const t=Kt("/workspaces/:workspaceId/sessions/:sessionId",e),n=(o=t==null?void 0:t.params.sessionId)==null?void 0:o.trim();if(n)return{sessionId:n,workspaceId:((l=t==null?void 0:t.params.workspaceId)==null?void 0:l.trim())??null};const r=Kt("/sessions/:sessionId",e),i=(c=r==null?void 0:r.params.sessionId)==null?void 0:c.trim();return i?{sessionId:i,workspaceId:null}:null}function $3(e){return!!(Kt("/sessions",e)||Kt("/workspaces/:workspaceId/sessions",e))}function pk(e){return!!ul(e)}function z3(e){return!!(Kt("/tools",e)||Kt("/tools/files",e)||Kt("/tools/git",e)||Kt("/tools/processes",e)||Kt("/workspaces/:workspaceId/tools",e)||Kt("/workspaces/:workspaceId/tools/files",e)||Kt("/workspaces/:workspaceId/tools/git",e)||Kt("/workspaces/:workspaceId/tools/processes",e))}function su(e){return!!(Kt("/terminals",e)||Kt("/workspaces/:workspaceId/terminals",e))}function ru(e){return!!Kt("/workspaces/:workspaceId/butler",e)}function H3(e){return!!(Kt("/workspaces/:workspaceId/plugins",e)||Kt("/workspaces/:workspaceId/plugins/:pluginId",e)||Kt("/workspaces/:workspaceId/plugins/:pluginId/run",e))}function U3(e,t){return Kt("/workspaces/:workspaceId/debug",e)?Jk(t):Kt("/workspaces/:workspaceId",e)?Hk(t):Kt("/workspaces/:workspaceId/tools/files",e)||Kt("/tools/files",e)?Gk(t):Kt("/workspaces/:workspaceId/tools/git",e)||Kt("/tools/git",e)?Kk(t):Kt("/workspaces/:workspaceId/tools/processes",e)||Kt("/tools/processes",e)?Vk(t):Kt("/workspaces/:workspaceId/tools",e)||Kt("/tools",e)?zk(t):su(e)?Mi(t):ru(e)?Fi(t):H3(e)?RT(t):ua(t)}function q3(e){return e.trim().replace(/\\/g,"/").replace(/^(?:\.\/)+/,"").replace(/^\/+/,"")}const V3=d.lazy(async()=>({default:(await bm(()=>import("./FileContextPanel-BrKO8Xt6.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11]))).FileContextPanel})),K3=d.lazy(async()=>({default:(await bm(()=>import("./GitSidebar-BdwiDtOr.js"),__vite__mapDeps([12,1,2,3,4,6,7,5,8,9,10,11]))).GitSidebar})),G3=d.lazy(async()=>({default:(await bm(()=>import("./TerminalManagerPanel-CjzbiWjl.js"),__vite__mapDeps([13,1,2,7,3,4,5,11,14,15,8,9,6,10]))).TerminalManagerPanel}));function Y3(e){return!!((e==null?void 0:e.item)??(e==null?void 0:e.session))}function or(e){return PT(e)}function J3(e){return e&&"item"in e?e.item:(e==null?void 0:e.session)??null}function _a(e){return Array.isArray(e==null?void 0:e.visibleSessionTree)?e.visibleSessionTree.filter(Y3):[]}async function SN(e,t){const n=await no(t,e);if(n.canStartSession===!1)throw new Error(n.limitations[0]??a("conversation.capabilityDenied"))}const X3="code",CN=d.createContext(null);function Ou(e){return YF(e)}function Xr(e){return e.isArchived===!0}function Bl(e){return MT(e)}function jN(e,t){return Yk(e,{getId:n=>n.sessionId,getParentId:Bl,compare:(n,r)=>kl(n,r,t)})}function Q3(e,t){const n=Z3(e);return NN(n,t)}function NN(e,t){const n=e8(e);return Yk(n,{getId:r=>r.session.sessionId,getParentId:r=>Bl(r.session),compare:(r,i)=>kl(r.session,i.session,t)}).map(r=>IN(r))}function Z3(e){return e.flatMap(t=>[...t.visibleSessions.map(n=>({session:n,workspace:t.workspace})),...TN(t.childWorktrees)])}function TN(e){return e.flatMap(t=>[...t.visibleSessions.map(n=>({session:n,workspace:t.workspace})),...TN(t.children)])}function e8(e){const t=[],n=new Set;for(const r of e){const i=r.session.sessionId.trim();!i||n.has(i)||(n.add(i),t.push(r))}return t}function IN(e,t=0){return{item:e.item.session,depth:t,children:e.children.map(n=>IN(n,t+1))}}function um(e,t){return{...e,depth:e.depth+t,children:or(e).map(n=>um(n,t))}}function gk(e){return`${e}::parallel-anchor-member`}function bk(e){const{session:t,depth:n,children:r}=e;return{item:t,depth:n,children:[...r]}}function dm(e,t){for(const n of e){if(n.item.sessionId===t)return n;const r=dm(or(n),t);if(r)return r}return null}function t8(e,t){const n=t.trim();if(!n)return null;for(const r of e){const i=AN(r,n,null);if(i)return i}return null}function AN(e,t,n){var i,o;const r=((o=(i=e.item.parallelGroup)==null?void 0:i.groupId)==null?void 0:o.trim())||n;if(e.item.sessionId===t)return r;for(const l of or(e)){const c=AN(l,t,r);if(c)return c}return null}function RN(e){return e.filter(t=>{if(Xr(t))return!1;const n=Bl(t);if(!n)return!0;const r=e.find(i=>i.sessionId===n);return r&&Xr(r)?!Ou(t):!0})}function n8(e){return e.flatMap(t=>{const n=J3(t);return n?[n,...OT(or(t))]:[]})}function s8(e,t,n){var g;const r=or(e),i=Ea(r).sort((p,b)=>kl(p.item,b.item,n));if(!(((g=e.item.parallelGroup)==null?void 0:g.role)==="anchor"&&r.some(p=>{var b,y;return((b=p.item.parallelGroup)==null?void 0:b.groupId)===((y=e.item.parallelGroup)==null?void 0:y.groupId)}))){const p=new Set(i.slice(0,Math.max(0,t)).map(b=>b.item.sessionId));return{...e,children:fm(r,p)}}const l=r.slice().sort((p,b)=>kl(p.item,b.item,n)),c=l.filter(p=>{var b,y;return((b=p.item.parallelGroup)==null?void 0:b.groupId)===((y=e.item.parallelGroup)==null?void 0:y.groupId)}).map(p=>p.item.sessionId),u=l.filter(p=>{var b,y;return((b=p.item.parallelGroup)==null?void 0:b.groupId)!==((y=e.item.parallelGroup)==null?void 0:y.groupId)}).map(p=>p.item.sessionId),f=[...c,...u],h=Math.max(0,t-f.length),m=new Set(f);for(const p of i){if(m.size>=f.length+h)break;m.add(p.item.sessionId)}return{...e,children:fm(r,m)}}function fm(e,t){return e.flatMap(n=>{const r=fm(or(n),t);return!t.has(n.item.sessionId)&&r.length===0?[]:[{...n,children:r}]})}function Wc(e,t,n,r=-1){if(e<=0)return 0;const i=r>=0?Math.max(t,r+1):t;return Math.min(e,Math.max(n??0,i))}function yk(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>e[i]===t[i])}function r8(e){const t=e.lastMessageAt??e.updatedAt;return t?new Date(t).toLocaleDateString():""}function md(e,t="compact"){return Ui(e,t)}const i8={position:"relative",zIndex:0},a8={zIndex:1};function PN(e,t,n,r){const i=[],o=(r==null?void 0:r.trim())||t.name;n&&i.push(o);const l=r8(e);return l&&i.push(l),i.join(" · ")||o}function xk(e,t){return xS("session-state-indicator",e,t)}function o8(e,t){return kS(e,t)}function kk(e,t){try{const n=window.localStorage.getItem(e),r=n?Number(n):Number.NaN;return Number.isFinite(r)?r:t}catch{return t}}function wk(e,t){try{const n=window.localStorage.getItem(e);return n===null?t:n==="true"}catch{return t}}function vk(e){var t;try{const n=(t=window.localStorage.getItem(e))==null?void 0:t.trim();return n||null}catch{return null}}function sa(e,t){try{window.localStorage.setItem(e,t)}catch{}}function l8(e){try{window.localStorage.removeItem(e)}catch{}}function $c(e,t,n){return Math.max(t,Math.min(n,e))}function zc(e){const t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function c8(e){const t=window.getComputedStyle(e),n=zc(t.getPropertyValue("--desktop-macos-titlebar-height")),r=zc(t.getPropertyValue("--workbench-header-min-height")),i=zc(t.getPropertyValue("--workbench-macos-titlebar-padding-top")),o=zc(t.getPropertyValue("--workbench-macos-titlebar-padding-bottom"));return Math.max(n,r,40)+i+o+8}function Sk(e,t){const n=t.getBoundingClientRect();return e>=n.top&&e<=n.top+c8(t)}function u8(e){return e instanceof HTMLElement?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||!!e.closest("[contenteditable='true']"):!1}function d8(){typeof window>"u"||window.dispatchEvent(new CustomEvent(S3))}function MN(e,t){const n=t==null?void 0:t.trim();if(!n)return null;for(const r of e){if(r.workspace.id===n)return r;const i=MN(r.children,n);if(i)return i}return null}function Ck(e,t){const n=t==null?void 0:t.trim();if(!n)return null;for(const r of e){const i=MN(r.childWorktrees,n);if(i)return i}return null}function EN(e){return e.flatMap(t=>[t.workspace.id,...EN(t.children)])}function LN(e){return new Set(e.flatMap(t=>[t.workspace.id,...EN(t.childWorktrees)]))}function jk(e){return!e||!Array.isArray(e.items)?[]:e.items.filter(t=>{var n;return t.collapsed===!0&&((n=t.workspace)==null?void 0:n.id)}).map(t=>t.workspace.id)}function Xf(e,t){const n=new Set(t);return{items:e.map(r=>({workspace:r.workspace,sessions:r.sessions,childWorktrees:r.childWorktrees,collapsed:n.has(r.workspace.id)}))}}function DN(e,t,n,r=new Set){return e.map(i=>{const o=i.sessions.filter(c=>!r.has(c.sessionId)),l=RN(o);return{workspace:i.workspace,meta:i.meta,visibleSessions:l,archivedSessions:o.filter(c=>Xr(c)&&!Bl(c)),visibleSessionTree:jN(l,n).filter(c=>!t.has(c.item.sessionId)&&!Uk(or(c),u=>t.has(u.sessionId))),children:DN(i.children,t,n,r)}})}function hm(e){return e.flatMap(t=>[t.workspace.id,...hm(t.children)])}function Jo(e){return e.flatMap(t=>[...t.visibleSessionTree,...Jo(t.children)])}function ON(e){return e.flatMap(t=>[t,...ON(t.children)])}function f8(e,t){if(!t)return null;for(const n of e){if(n.workspace.id===t)return{workspace:n.workspace,visibleSessionTree:_a(n)};const r=FN(n.childWorktrees,t);if(r)return r}return null}function FN(e,t){for(const n of e){if(n.workspace.id===t)return{workspace:n.workspace,visibleSessionTree:n.visibleSessionTree};const r=FN(n.children,t);if(r)return r}return null}function h8(e,t){if(!t)return null;for(const n of e){if(n.workspace.id===t)return{workspace:n.workspace,archivedSessions:n.archivedSessions};const r=_N(n.childWorktrees,t);if(r)return r}return null}function Qf(e,t){if(!t)return null;for(const n of e){if(n.workspace.id===t)return n.workspace;const r=BN(n.childWorktrees,t);if(r)return r}return null}function _N(e,t){for(const n of e){if(n.workspace.id===t)return{workspace:n.workspace,archivedSessions:n.archivedSessions};const r=_N(n.children,t);if(r)return r}return null}function BN(e,t){for(const n of e){if(n.workspace.id===t)return n.workspace;const r=BN(n.children,t);if(r)return r}return null}function WN(e,t){for(const n of e){if(n.workspace.id===t)return[n.workspace.id];const r=WN(n.children,t);if(r.length>0)return[n.workspace.id,...r]}return[]}function Nk(e){return e.flatMap(t=>[t.workspace.id,...$N(t.childWorktrees)])}function $N(e){return e.flatMap(t=>[t.workspace.id,...$N(t.children)])}function m8(e,t=[]){if(e.tone!=="worktree")return e.rootDisplayName;if(t.length>0)return t.join(" / ");const n=[e.rootDisplayName];return e.parentDisplayName&&e.parentDisplayName!==e.rootDisplayName&&n.push(e.parentDisplayName),n.join(" / ")}function p8(e,t,n,r){if(t===n)return e;const i=e.findIndex(f=>f.workspace.id===t),o=e.findIndex(f=>f.workspace.id===n);if(i<0||o<0)return e;const l=[...e],[c]=l.splice(i,1);if(!c)return e;const u=l.findIndex(f=>f.workspace.id===n);return u<0?e:(l.splice(r==="before"?u:u+1,0,c),l.every((f,h)=>{var m;return f.workspace.id===((m=e[h])==null?void 0:m.workspace.id)})?e:l)}function g8(e,t){if(!Array.isArray(e.items)||t.size===0)return e;let n=!1;const r=e.items.map(i=>{let o=!1;const l=i.sessions.map(u=>{const f=t.get(u.sessionId);return f===void 0||Xr(u)===f?u:(n=!0,o=!0,{...u,isArchived:f})}),c=HN(i.childWorktrees??[],t,u=>{u&&(n=!0,o=!0)});return o?{...i,sessions:l,childWorktrees:c}:i});return n?{...e,items:r}:e}function b8(e,t){if(!(!Array.isArray(t.items)||e.size===0))for(const n of t.items){for(const r of n.sessions){const i=e.get(r.sessionId);i!==void 0&&Xr(r)===i&&e.delete(r.sessionId)}UN(e,n.childWorktrees??[])}}function y8(e,t,n){let r=!1;const i=e.map(o=>{if(o.workspace.id!==t.workspaceId){const{nodes:u,changed:f}=qN(o.childWorktrees,t,n);return f?(r=!0,{...o,childWorktrees:u}):o}const l=o.sessions.findIndex(u=>u.sessionId===t.sessionId),c=l>=0?o.sessions.map((u,f)=>f===l?t:u):[t,...o.sessions];return r=!0,{...o,sessions:io(c,n)}});return r?i:e}function x8(e,t,n){let r=!1;const i=e.map(o=>{let l=!1;const c=o.sessions.map(f=>f.sessionId!==t?f:(r=!0,l=!0,{...f,lastSeenAt:f.lastSeenAt&&f.lastSeenAt>n?f.lastSeenAt:n,activityState:f.activityState==="completed_unread"?"idle":f.activityState})),u=pd(o.childWorktrees,f=>f.sessionId!==t?f:(r=!0,l=!0,{...f,lastSeenAt:f.lastSeenAt&&f.lastSeenAt>n?f.lastSeenAt:n,activityState:f.activityState==="completed_unread"?"idle":f.activityState}));return l?{...o,sessions:c,childWorktrees:u}:o});return r?i:e}function Tk(e,t,n){let r=!1;const i=e.map(o=>{let l=!1;const c=o.sessions.map(f=>f.sessionId!==t||f.isArchived===n?f:(r=!0,l=!0,{...f,isArchived:n})),u=pd(o.childWorktrees,f=>f.sessionId!==t||f.isArchived===n?f:(r=!0,l=!0,{...f,isArchived:n}));return l?{...o,sessions:c,childWorktrees:u}:o});return r?i:e}function Ik(e,t,n){let r=!1;const i=e.map(o=>{let l=!1;const c=o.sessions.map(f=>f.sessionId!==t||f.isFavorite===!0===n?f:(r=!0,l=!0,{...f,isFavorite:n})),u=pd(o.childWorktrees,f=>f.sessionId!==t||f.isFavorite===!0===n?f:(r=!0,l=!0,{...f,isFavorite:n}));return l?{...o,sessions:c,childWorktrees:u}:o});return r?i:e}function k8(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function w8(e){return e?e.slice(0,8):"--"}function Ak(e,t,n){return n?e.includes(t)?e:[...e,t]:e.includes(t)?e.filter(r=>r!==t):e}function zN(e,t){const n=e.filter(r=>t.has(r));return n.length===e.length?e:n}function HN(e,t,n){return e.map(r=>{let i=!1;const o=r.sessions.map(c=>{const u=t.get(c.sessionId);return u===void 0||Xr(c)===u?c:(i=!0,{...c,isArchived:u})}),l=HN(r.children,t,c=>{c&&(i=!0)});return n(i),i?{...r,sessions:o,children:l}:r})}function UN(e,t){for(const n of t){for(const r of n.sessions){const i=e.get(r.sessionId);i!==void 0&&Xr(r)===i&&e.delete(r.sessionId)}UN(e,n.children)}}function qN(e,t,n){let r=!1;const i=e.map(o=>{if(o.workspace.id===t.workspaceId){const c=o.sessions.findIndex(f=>f.sessionId===t.sessionId),u=c>=0?o.sessions.map((f,h)=>h===c?t:f):[t,...o.sessions];return r=!0,{...o,sessions:io(u,n)}}const l=qN(o.children,t,n);return l.changed?(r=!0,{...o,children:l.nodes}):o});return{nodes:r?i:[...e],changed:r}}function v8(e,t){return e.map(n=>({...n,sessions:io(n.sessions,t),childWorktrees:up(n.childWorktrees,t)}))}function pd(e,t){let n=!1;const r=e.map(i=>{let o=!1;const l=i.sessions.map(u=>{const f=t(u);return f!==u&&(o=!0,n=!0),f}),c=pd(i.children,t);return c!==i.children&&(o=!0,n=!0),o?{...i,sessions:l,children:c}:i});return n?r:[...e]}function mm(e){return`workspace-management.summary.${e}`}function VN(e){return`git-sidebar.snapshot.${e}`}function KN(e,t){const n=e.repoRoot??null;return{workspaceId:e.id,name:e.name,path:e.path,git:{isRepository:!!n,repoRoot:n,currentBranch:null,commitCount:null,remotes:[],error:null},codeComposition:{scannedFileCount:0,truncated:!1,items:[],error:null}}}function GN(e,t){const n=e.git.repoRoot??t.repoRoot??null;return{...e,workspaceId:t.id,name:t.name,path:t.path,git:{...e.git,isRepository:e.git.isRepository||!!n,repoRoot:n}}}function YN(e,t){var o,l,c,u;const n=((o=t.status)==null?void 0:o.snapshot.enabled)!==!1,r=n?((l=t.status)==null?void 0:l.snapshot.repoRoot)??e.git.repoRoot:e.git.repoRoot,i=n?((c=t.status)==null?void 0:c.snapshot.branch)??((u=t.branches)==null?void 0:u.currentBranch)??e.git.currentBranch??null:e.git.currentBranch??null;return{...e,git:{...e.git,isRepository:n&&(e.git.isRepository||!!r),repoRoot:r,currentBranch:i,error:null}}}function JN({count:e,className:t="workbench-skeleton-lines"}){return s.jsx("div",{className:t,"aria-hidden":"true",children:Array.from({length:e},(n,r)=>s.jsx("span",{className:"skeleton-line"},r))})}function S8(){return s.jsx("div",{className:"workbench-nav-loading","aria-hidden":"true",children:Array.from({length:3},(e,t)=>s.jsxs("section",{className:"workbench-skeleton-card",children:[s.jsxs("div",{className:"workbench-skeleton-heading",children:[s.jsx("span",{className:"skeleton-line short"}),s.jsx("span",{className:"skeleton-line tiny"})]}),s.jsx("div",{className:"workbench-skeleton-list",children:Array.from({length:3},(n,r)=>s.jsxs("div",{className:"workbench-skeleton-session",children:[s.jsx("span",{className:"workbench-skeleton-dot"}),s.jsx(JN,{count:2,className:"workbench-skeleton-lines compact"})]},r))})]},t))})}function Hc(){return s.jsx("section",{className:"workbench-info-skeleton","aria-hidden":"true",children:Array.from({length:4},(e,t)=>s.jsxs("article",{className:"workbench-info-skeleton-card",children:[s.jsx("span",{className:"skeleton-line short"}),s.jsx(JN,{count:3})]},t))})}function C8({side:e,collapsed:t}){const n=e==="left"?8.5:15.5,r=e==="left"?t?"12 9 15 12 12 15":"15 9 12 12 15 15":t?"12 9 9 12 12 15":"9 9 12 12 9 15";return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),s.jsx("line",{x1:n,y1:"4",x2:n,y2:"20"}),s.jsx("polyline",{points:r})]})}function Uc({ariaLabel:e,side:t,collapsed:n,className:r="panel-icon-button",onClick:i}){return s.jsx("button",{className:r,type:"button","aria-label":e,title:e,onClick:i,children:s.jsx(C8,{side:t,collapsed:n})})}function Ka({expanded:e}){return s.jsx("svg",{className:e?"workbench-chevron":"workbench-chevron collapsed",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function j8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("polyline",{points:"7 10 12 15 17 10"}),s.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})}function N8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"12",y2:"14"}),s.jsx("circle",{cx:"17.5",cy:"15.5",r:"2.5"})]})}function T8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M7.5 10.2a4.5 4.5 0 1 1 9 0v3.1c0 .8.3 1.6.9 2.2l.8.8H5.8l.8-.8c.6-.6.9-1.4.9-2.2z",strokeLinecap:"round",strokeLinejoin:"round"}),s.jsx("path",{d:"M10 18.5a2 2 0 0 0 4 0",strokeLinecap:"round"})]})}function pm(e){return s.jsx("div",{className:"workbench-notification-anchor",children:s.jsxs("button",{type:"button",className:e.collapsed?"workbench-nav-toolbar-button workbench-collapsed-button":"workbench-nav-toolbar-button","aria-label":a("shell.globalNotificationsAction"),title:a("shell.globalNotificationsAction"),"aria-expanded":e.open,onClick:e.onToggle,children:[s.jsx(T8,{}),e.unreadCount>0?s.jsx("span",{className:"workbench-notification-badge","aria-label":a("shell.globalNotificationsUnreadAria",{count:String(e.unreadCount)}),children:e.unreadCount>99?"99+":e.unreadCount}):null]})})}function I8(e){const[t,n]=d.useState("notifications");d.useEffect(()=>{e.open&&n("notifications")},[e.open]);const r=d.useMemo(()=>e.notifications.filter(i=>e.showArchivedNotifications||!e.archivedNotificationIds.has(i.id)),[e.archivedNotificationIds,e.notifications,e.showArchivedNotifications]);return s.jsxs(ln,{open:e.open,title:a("shell.globalNotificationsPanelTitle"),description:a("shell.globalNotificationsPanelDescription"),className:"workbench-notification-modal-card workspace-inbox-modal-card",showCloseButton:!1,onClose:e.onClose,children:[s.jsxs("div",{className:"workbench-notification-tabs",role:"tablist","aria-label":a("shell.globalNotificationsPanelTitle"),children:[s.jsx("button",{type:"button",className:t==="notifications"?"workbench-notification-tab active":"workbench-notification-tab",role:"tab","aria-selected":t==="notifications",onClick:()=>n("notifications"),children:a("shell.globalNotificationsAction")}),s.jsx("button",{type:"button",className:t==="inbox"?"workbench-notification-tab active":"workbench-notification-tab",role:"tab","aria-selected":t==="inbox",onClick:()=>n("inbox"),children:a("shell.butlerInboxAction")})]}),s.jsx("div",{className:"workbench-notification-content","data-tab":t,children:t==="notifications"?s.jsxs("div",{className:"workbench-notification-pane",role:"tabpanel","aria-label":a("shell.globalNotificationsAction"),children:[s.jsx("div",{className:"workbench-notification-toolbar",children:s.jsxs("label",{className:"workbench-notification-filter",children:[s.jsx("input",{type:"checkbox",checked:e.showArchivedNotifications,onChange:i=>e.onToggleShowArchivedNotifications(i.target.checked)}),s.jsx("span",{children:a("shell.globalNotificationsShowArchived")})]})}),r.length>0?s.jsx("div",{className:"workbench-notification-list",children:r.map(i=>{const o=e.archivedNotificationIds.has(i.id);return s.jsxs("article",{className:"workbench-notification-item","data-archived":o,children:[s.jsxs("button",{type:"button",className:"workbench-notification-item-content",onClick:()=>{e.onSelectNotification(i)},children:[s.jsx("span",{className:"workbench-notification-item-kind",children:E3(i.kind)}),s.jsx("strong",{children:i.title}),s.jsx("p",{children:i.body})]}),s.jsxs("div",{className:"workbench-notification-item-side",children:[s.jsx("time",{children:B3(i.createdAt)}),s.jsx("button",{type:"button",className:"secondary-button workbench-notification-item-action-button",onClick:()=>{if(o){e.onUnarchiveNotification(i.id);return}e.onArchiveNotification(i.id)},children:o?a("shell.globalNotificationsRemoveArchiveAction"):a("shell.globalNotificationsArchiveAction")})]})]},i.id)})}):s.jsx("p",{className:"workbench-notification-empty",children:a("shell.globalNotificationsEmpty")})]}):s.jsx("div",{className:"workbench-notification-pane",role:"tabpanel","aria-label":a("shell.butlerInboxAction"),children:s.jsx(xN,{active:e.open&&t==="inbox",preferredWorkspaceId:e.preferredWorkspaceId,preferredSessionId:e.preferredSessionId})})}),s.jsx("div",{className:"workbench-modal-actions workbench-notification-footer-actions",children:s.jsx("button",{type:"button",className:"secondary-button",onClick:e.onClose,children:a("common.close")})})]})}function A8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function gm(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("circle",{cx:"10.5",cy:"10.5",r:"5.75"}),s.jsx("path",{d:"m15 15 4 4",strokeLinecap:"round"})]})}function R8(){return s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",children:s.jsx("path",{d:"M7 6.5h10a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3H11l-4.5 3v-3H7a3 3 0 0 1-3-3v-5a3 3 0 0 1 3-3Z",strokeLinecap:"round",strokeLinejoin:"round"})})}function P8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",children:[s.jsx("rect",{x:"3.5",y:"5",width:"17",height:"14",rx:"2.5"}),s.jsx("path",{d:"m8 10 2.5 2.5L8 15",strokeLinecap:"round",strokeLinejoin:"round"}),s.jsx("path",{d:"M13.5 15h3.5",strokeLinecap:"round"})]})}function M8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",children:[s.jsx("path",{d:"M12 5.5 13.5 10l4.5 1.5-4.5 1.5-1.5 4.5-1.5-4.5L6 11.5 10.5 10 12 5.5Z",strokeLinejoin:"round"}),s.jsx("path",{d:"M18.5 5.5v3",strokeLinecap:"round"}),s.jsx("path",{d:"M17 7h3",strokeLinecap:"round"})]})}function XN(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),s.jsx("line",{x1:"9",y1:"4",x2:"9",y2:"20"}),s.jsx("polyline",{points:"14 9 11 12 14 15"})]})}function E8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"6",r:"3"}),s.jsx("circle",{cx:"18",cy:"18",r:"3"}),s.jsx("path",{d:"M6 9v6a3 3 0 0 0 3 3h3"}),s.jsx("line",{x1:"18",y1:"9",x2:"18",y2:"15"})]})}function L8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82L4.21 7.1a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 8.92 4a1.65 1.65 0 0 0 1-1.51V2.4a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9c0 .66.39 1.25 1 1.51h.09a2 2 0 0 1 0 4h-.09c-.61.26-1 .85-1 1.49z"})]})}function D8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("rect",{x:"4",y:"5",width:"6",height:"6",rx:"1.5"}),s.jsx("rect",{x:"14",y:"5",width:"6",height:"6",rx:"1.5"}),s.jsx("rect",{x:"4",y:"13",width:"6",height:"6",rx:"1.5"}),s.jsx("path",{d:"M14 16l2 2 4-4"})]})}function O8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("rect",{x:"4",y:"6",width:"10",height:"12",rx:"2"}),s.jsx("path",{d:"M10 12h8"}),s.jsx("path",{d:"M15 8l4 4-4 4"})]})}function F8({selected:e}){return e?s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"4"}),s.jsx("path",{d:"M8 12.5l2.8 2.8L16.5 9.5"})]}):s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:s.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"4"})})}function QN({active:e,className:t}){return e?s.jsx("svg",{className:t,width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"1.5",children:s.jsx("polygon",{points:"12 3 15 9 22 10 17 15 18 22 12 18 6 22 7 15 2 10 9 9"})}):s.jsx("svg",{className:t,width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:s.jsx("polygon",{points:"12 3 15 9 22 10 17 15 18 22 12 18 6 22 7 15 2 10 9 9"})})}function _8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M3 7h18"}),s.jsx("path",{d:"M5 7l1 12h12l1-12"}),s.jsx("path",{d:"M9 11h6"}),s.jsx("path",{d:"M8 4h8l1 3H7l1-3z"})]})}function B8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M12 20h9"}),s.jsx("path",{d:"M16.5 3.5a2.12 2.12 0 1 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]})}function W8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M12 4v10"}),s.jsx("path",{d:"M8.5 7.5L12 4l3.5 3.5"}),s.jsx("path",{d:"M5 14v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4"})]})}function $8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M3 6h18"}),s.jsx("path",{d:"M8 6V4h8v2"}),s.jsx("path",{d:"M6 6l1 14h10l1-14"}),s.jsx("path",{d:"M10 11v5"}),s.jsx("path",{d:"M14 11v5"})]})}function z8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",children:[s.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}),s.jsx("path",{d:"M9 13h6"})]})}function H8(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M9.7 9.4a2.5 2.5 0 1 1 4.1 2c-.8.7-1.8 1.2-1.8 2.6",strokeLinecap:"round"}),s.jsx("circle",{cx:"12",cy:"17.2",r:"1",fill:"currentColor",stroke:"none"})]})}function U8({open:e,mode:t,keyword:n,codeWorkspaceId:r,codeResults:i,codeLoading:o,codeError:l,workspaceOptions:c,sessionResults:u,onClose:f,onModeChange:h,onKeywordChange:m,onCodeWorkspaceChange:g,onCodeSearch:p,onOpenSession:b}){const y=n.trim().length>0&&r.trim().length>0;return s.jsx(ln,{open:e,title:a("shell.searchModalTitle"),description:a("shell.searchModalDescription"),onClose:f,children:s.jsxs("div",{className:"workbench-search-modal",children:[s.jsxs("div",{className:"workbench-search-mode-switch",role:"tablist","aria-label":a("shell.searchModeLabel"),children:[s.jsx("button",{type:"button",className:t==="sessions"?"workbench-search-mode-button active":"workbench-search-mode-button",role:"tab","aria-selected":t==="sessions",onClick:()=>h("sessions"),children:a("shell.searchModeSessions")}),s.jsx("button",{type:"button",className:t==="code"?"workbench-search-mode-button active":"workbench-search-mode-button",role:"tab","aria-selected":t==="code",onClick:()=>h("code"),children:a("shell.searchModeCode")})]}),t==="sessions"?s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.searchKeywordLabel")}),s.jsx("input",{type:"text",value:n,placeholder:a("shell.searchSessionPlaceholder"),autoFocus:!0,onChange:x=>m(x.target.value)})]}),s.jsx("div",{className:"workbench-search-results",children:n.trim().length===0?s.jsx("p",{className:"workbench-search-empty",children:a("shell.searchSessionHint")}):u.length>0?u.map(x=>{const k=rd(x.session.title,a("common.unknown"));return s.jsxs("button",{type:"button",className:"workbench-search-result-item",onClick:()=>b(x.session.sessionId),children:[s.jsx("span",{className:"workbench-search-result-title",title:k.fullTitle,children:k.displayTitle}),s.jsxs("span",{className:"workbench-search-result-meta",children:[x.workspace.name," · ",md(x.session.provider,"full")]})]},x.session.sessionId)}):s.jsx("p",{className:"workbench-search-empty",children:a("shell.searchSessionEmpty")})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.searchWorkspaceLabel")}),s.jsx("select",{value:r,onChange:x=>g(x.target.value),children:c.map(x=>s.jsx("option",{value:x.id,children:x.name},x.id))})]}),s.jsxs("form",{className:"workbench-search-code-form",onSubmit:x=>{x.preventDefault(),p()},children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.searchKeywordLabel")}),s.jsx("input",{type:"text",value:n,placeholder:a("shell.searchCodePlaceholder"),autoFocus:!0,onChange:x=>m(x.target.value)})]}),s.jsx("button",{type:"submit",className:"primary-button",disabled:!y||o,children:o?a("common.loading"):a("shell.searchSubmit")})]}),s.jsxs("div",{className:"workbench-search-results",children:[l?s.jsx("p",{className:"status-text","data-tone":"error",children:l}):null,!l&&n.trim().length===0?s.jsx("p",{className:"workbench-search-empty",children:a("shell.searchCodeHint")}):null,!l&&n.trim().length>0&&!o&&i.length===0?s.jsx("p",{className:"workbench-search-empty",children:a("shell.searchCodeEmpty")}):null,i.map(x=>s.jsxs("div",{className:"workbench-search-result-item static",children:[s.jsx("span",{className:"workbench-search-result-title",children:x.name}),s.jsx("span",{className:"workbench-search-result-meta",children:x.path})]},`${x.path}-${x.kind}`))]})]})]})})}const q8=`
847
+ html,
848
+ body {
849
+ width: 100% !important;
850
+ height: auto !important;
851
+ min-height: auto !important;
852
+ overflow: visible !important;
853
+ overflow-x: visible !important;
854
+ }
855
+
856
+ body {
857
+ margin: 0 !important;
858
+ padding: 0 !important;
859
+ }
860
+
861
+ .session-export-document-root {
862
+ position: static !important;
863
+ inset: auto !important;
864
+ z-index: auto !important;
865
+ opacity: 1 !important;
866
+ pointer-events: auto !important;
867
+ overflow: visible !important;
868
+ }
869
+
870
+ .session-export-document-root,
871
+ .session-export-document-root * {
872
+ font-family: var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif);
873
+ letter-spacing: normal !important;
874
+ word-spacing: normal !important;
875
+ text-align: left !important;
876
+ -webkit-text-fill-color: currentColor !important;
877
+ text-fill-color: currentColor !important;
878
+ -webkit-background-clip: border-box !important;
879
+ background-clip: border-box !important;
880
+ text-shadow: none !important;
881
+ mix-blend-mode: normal !important;
882
+ }
883
+
884
+ .session-export-document-root .markdown-content p,
885
+ .session-export-document-root .markdown-content blockquote,
886
+ .session-export-document-root .markdown-content td {
887
+ display: block !important;
888
+ }
889
+
890
+ .session-export-document-root .markdown-content li {
891
+ display: list-item !important;
892
+ }
893
+
894
+ .session-export-document-root .markdown-content code,
895
+ .session-export-document-root .markdown-content pre,
896
+ .session-export-document-root .code-block pre,
897
+ .session-export-document-root .tool-call-section pre,
898
+ .session-export-document-root .tool-call-input-preview,
899
+ .session-export-document-root .apply-patch-line-content,
900
+ .session-export-document-root .apply-patch-summary-file {
901
+ font-family:
902
+ var(--font-mono, "SF Mono", "Consolas", "Cascadia Code", "Courier New", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", monospace) !important;
903
+ }
904
+
905
+ .session-export-document-root .thinking-message-label,
906
+ .session-export-document-root .thinking-status-text {
907
+ background: none !important;
908
+ color: var(--text-secondary, #475569) !important;
909
+ -webkit-text-fill-color: currentColor !important;
910
+ animation: none !important;
911
+ }
912
+
913
+ @media print {
914
+ body * {
915
+ visibility: hidden;
916
+ }
917
+
918
+ .session-export-document-root,
919
+ .session-export-document-root * {
920
+ visibility: visible;
921
+ }
922
+
923
+ .session-export-document-root {
924
+ position: static !important;
925
+ }
926
+
927
+ .session-export-document-root .session-export-print-shell {
928
+ width: 100%;
929
+ max-width: none;
930
+ margin: 0;
931
+ padding: 0;
932
+ }
933
+
934
+ .session-export-document-root .message-timeline-export,
935
+ .session-export-document-root .message-timeline-export .message-list-export {
936
+ overflow: visible;
937
+ height: auto;
938
+ max-height: none;
939
+ }
940
+
941
+ .session-export-document-root .tool-call-header,
942
+ .session-export-document-root .tool-call-info,
943
+ .session-export-document-root .task-tool-header,
944
+ .session-export-document-root .task-tool-heading,
945
+ .session-export-document-root .task-tool-heading-main,
946
+ .session-export-document-root .task-tool-list-item,
947
+ .session-export-document-root .assistant-capability-header,
948
+ .session-export-document-root .assistant-capability-heading,
949
+ .session-export-document-root .assistant-capability-heading-main,
950
+ .session-export-document-root .assistant-capability-row,
951
+ .session-export-document-root .apply-patch-summary-row,
952
+ .session-export-document-root .rules-message-toggle {
953
+ display: flex !important;
954
+ flex-wrap: wrap !important;
955
+ align-items: flex-start !important;
956
+ justify-content: flex-start !important;
957
+ }
958
+
959
+ .session-export-document-root .task-tool-list-item,
960
+ .session-export-document-root .assistant-capability-row,
961
+ .session-export-document-root .apply-patch-summary-row {
962
+ row-gap: 4px !important;
963
+ }
964
+
965
+ .session-export-document-root .tool-call-input-preview,
966
+ .session-export-document-root .rules-message-summary,
967
+ .session-export-document-root .task-tool-summary-text,
968
+ .session-export-document-root .task-tool-item-title,
969
+ .session-export-document-root .task-tool-item-detail,
970
+ .session-export-document-root .task-tool-item-status,
971
+ .session-export-document-root .assistant-capability-heading-main strong,
972
+ .session-export-document-root .assistant-capability-summary,
973
+ .session-export-document-root .assistant-capability-row-label,
974
+ .session-export-document-root .assistant-capability-row-value,
975
+ .session-export-document-root .apply-patch-summary-file,
976
+ .session-export-document-root .apply-patch-summary-stats,
977
+ .session-export-document-root .session-title,
978
+ .session-export-document-root .message-text,
979
+ .session-export-document-root .markdown-content,
980
+ .session-export-document-root .thinking-message-text,
981
+ .session-export-document-root .thinking-message-text :where(p, li, blockquote, strong, em, a, span),
982
+ .session-export-document-root .thinking-message-label,
983
+ .session-export-document-root .thinking-status-text {
984
+ white-space: normal !important;
985
+ overflow: visible !important;
986
+ text-overflow: clip !important;
987
+ word-break: break-word !important;
988
+ overflow-wrap: anywhere !important;
989
+ }
990
+
991
+ .session-export-document-root .assistant-capability-summary {
992
+ display: inline !important;
993
+ }
994
+
995
+ .session-export-document-root .task-tool-list {
996
+ list-style: decimal !important;
997
+ padding-left: 24px !important;
998
+ }
999
+
1000
+ .session-export-document-root .message-timeline-export .conversation-scroll-to-bottom-button,
1001
+ .session-export-document-root .message-timeline-export .message-metadata-bar,
1002
+ .session-export-document-root .message-timeline-export .retry-button,
1003
+ .session-export-document-root .message-timeline-export .code-copy-button,
1004
+ .session-export-document-root .message-timeline-export .rules-message-action,
1005
+ .session-export-document-root .message-timeline-export .message-origin-detail-popover {
1006
+ display: none !important;
1007
+ }
1008
+
1009
+ .session-export-document-root .message-item,
1010
+ .session-export-document-root .tool-message-row,
1011
+ .session-export-document-root .rules-message-row {
1012
+ break-inside: avoid;
1013
+ page-break-inside: avoid;
1014
+ }
1015
+ }
1016
+ `;function V8({menuKey:e,session:t,workspace:n,workspaceContext:r,isActive:i,isFavorite:o,menuOpen:l,menuAnchorPoint:c,showWorkspaceName:u,depth:f=0,showActions:h=!0,exportDisabled:m=!1,hasSubagents:g=!1,subagentListExpanded:p=!1,showParallelBadge:b=!0,selectionMode:y=!1,selected:x=!1,onToggleSelect:k,onToggleSubagents:C,onOpen:j,onRename:H,onOpenContextMenu:_,onExport:T,onToggleFavorite:P,onArchive:z,onDelete:L,onCloseMenu:R}){var Ce,ke,we,se;const K=Hn(),E=Ja(t.provider).supportsSessionDelete===!0,D=!K.isDesktop&&!K.isMobile,te=Ou(t)?((Ce=t.subagentLabel)==null?void 0:Ce.trim())||a("shell.subagentBadge"):null,V=rd(t.title,a("common.unknown")),ee=wS(t),U=ee?vS("session-activity-badge",t):null,he=op(t),X=JF(t),I=b&&((ke=t.parallelGroup)==null?void 0:ke.role)==="anchor"?FT(t.parallelGroup):null,xe=_T(t.parallelGroup),le=d.useRef(null),[M,de]=d.useState(null),[Ne,ye]=d.useState(!1);d.useEffect(()=>{l||ye(!1)},[l]),d.useLayoutEffect(()=>{if(K.isDesktop||!l||!c||typeof window>"u"){de(null);return}const ce=()=>{var Te,pe;const Y=dp(c,{width:((Te=le.current)==null?void 0:Te.offsetWidth)??0,height:((pe=le.current)==null?void 0:pe.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:E&&L?216:168});de({position:"fixed",top:`${Math.round(Y.top)}px`,left:`${Math.round(Y.left)}px`,width:`${Math.round(Y.width)}px`,maxWidth:"calc(100vw - 24px)",maxHeight:`${Math.round(Y.maxHeight)}px`,transformOrigin:Y.transformOrigin})};return ce(),window.addEventListener("resize",ce),window.addEventListener("scroll",ce,!0),()=>{window.removeEventListener("resize",ce),window.removeEventListener("scroll",ce,!0)}},[c,l,K.isDesktop]);async function Be(){await dl([{id:`rename:${t.sessionId}`,label:a("shell.renameAction"),onSelect:H},{id:`export:${t.sessionId}`,label:a("conversation.exportAction"),disabled:m,items:[{id:`export-markdown:${t.sessionId}`,label:a("conversation.exportMarkdownAction"),onSelect:()=>T("md")},{id:`export-pdf:${t.sessionId}`,label:a("conversation.exportPdfAction"),onSelect:()=>T("pdf")},{id:`export-html:${t.sessionId}`,label:a("conversation.exportHtmlAction"),onSelect:()=>T("html")}]},{id:`favorite:${t.sessionId}`,label:o?a("shell.unfavoriteAction"):a("shell.favoriteAction"),onSelect:P},{id:`archive:${t.sessionId}`,label:a("shell.archiveAction"),onSelect:z},...E&&L?[{id:`delete:${t.sessionId}`,label:a("shell.deleteSessionAction"),onSelect:L}]:[]])}const We=!K.isDesktop&&l&&typeof document<"u"?Bs.createPortal(s.jsxs("div",{ref:le,className:"workbench-session-menu","data-menu-key":e,role:"menu","aria-label":a("shell.sessionMoreAction"),onClick:ce=>ce.stopPropagation(),style:M??{position:"fixed",top:0,left:0,visibility:"hidden"},children:[s.jsxs("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{H(),R()},children:[s.jsx(B8,{}),s.jsx("span",{children:a("shell.renameAction")})]}),s.jsxs("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{P(),R()},children:[s.jsx(QN,{active:o}),s.jsx("span",{children:o?a("shell.unfavoriteAction"):a("shell.favoriteAction")})]}),s.jsxs("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{z(),R()},children:[s.jsx(_8,{}),s.jsx("span",{children:a("shell.archiveAction")})]}),D?s.jsxs("div",{className:"workbench-session-submenu","data-open":Ne,children:[s.jsxs("button",{type:"button",className:"workbench-session-menu-item","aria-haspopup":"menu","aria-expanded":Ne,onClick:()=>{ye(ce=>!ce)},children:[s.jsx(W8,{}),s.jsx("span",{children:a("conversation.exportAction")}),s.jsx("span",{className:"workbench-session-submenu-caret","aria-hidden":"true",children:s.jsx(Ka,{expanded:Ne})})]}),Ne?s.jsxs("div",{className:"workbench-session-submenu-panel",role:"menu","aria-label":a("conversation.exportAction"),children:[s.jsx("button",{type:"button",className:"workbench-session-menu-item",role:"menuitem",disabled:m,onClick:()=>{T("md"),R()},children:s.jsx("span",{children:a("conversation.exportMarkdownAction")})}),s.jsx("button",{type:"button",className:"workbench-session-menu-item",role:"menuitem",disabled:m,onClick:()=>{T("pdf"),R()},children:s.jsx("span",{children:a("conversation.exportPdfAction")})}),s.jsx("button",{type:"button",className:"workbench-session-menu-item",role:"menuitem",disabled:m,onClick:()=>{T("html"),R()},children:s.jsx("span",{children:a("conversation.exportHtmlAction")})})]}):null]}):null,E&&L?s.jsxs("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{L(),R()},children:[s.jsx($8,{}),s.jsx("span",{children:a("shell.deleteSessionAction")})]}):null]}),document.body):null;return s.jsxs("article",{className:"workbench-session-card","data-active":i,"data-depth":f,"data-subagent":Ou(t),"data-workspace-tone":r.tone,"data-worktree-depth":r.depth,"data-has-subagents":g,"data-selecting":y,"data-selected":x,"data-parallel-group":t.parallelGroup?"true":void 0,"data-parallel-role":((we=t.parallelGroup)==null?void 0:we.role)??void 0,"data-parallel-color-token":((se=t.parallelGroup)==null?void 0:se.colorToken)??void 0,style:{...Gr(r)??{},...xe??{}},onContextMenu:ce=>{if(!(y||!h||!_)){if(ce.preventDefault(),ce.stopPropagation(),K.isDesktop){Be();return}_({x:ce.clientX,y:ce.clientY})}},children:[s.jsxs("div",{className:"workbench-session-main",children:[y?s.jsx("span",{className:"workbench-session-selection-indicator","data-selected":x,"aria-hidden":"true",children:s.jsx(F8,{selected:x})}):g?s.jsxs("button",{type:"button",className:"workbench-session-subagent-toggle",style:a8,"data-indicator-variant":o8(t,{hasSubagents:!0,isActive:i}),"aria-label":p?a("shell.subagentCollapse"):a("shell.subagentExpand"),title:p?a("shell.subagentCollapse"):a("shell.subagentExpand"),"aria-expanded":p,onClick:ce=>{ce.stopPropagation(),C==null||C()},children:[s.jsx("span",{className:xk(t,{hasSubagents:!0,isActive:i}),"data-activity-source":t.activitySource,"aria-hidden":"true"}),s.jsx("span",{className:"workbench-session-subagent-toggle-icon","aria-hidden":"true",children:s.jsx(Ka,{expanded:p})})]}):s.jsx("span",{className:xk(t,{isActive:i}),"data-activity-source":t.activitySource,"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"workbench-session-link",style:g?i8:void 0,"data-active":i,"aria-pressed":y?x:void 0,onClick:y?k:j,onKeyDown:ce=>{if(y||!h||!_||ce.key!=="ContextMenu"&&!(ce.shiftKey&&ce.key==="F10"))return;if(ce.preventDefault(),ce.stopPropagation(),K.isDesktop){Be();return}const Y=ce.currentTarget.getBoundingClientRect();_({x:Y.right,y:Y.bottom})},children:s.jsxs("div",{className:"workbench-session-link-copy",children:[s.jsxs("div",{className:"session-title-row",children:[s.jsx("span",{className:"session-title",title:V.fullTitle,children:V.displayTitle}),te?s.jsx("span",{className:"session-subagent-badge",children:te}):null,I?s.jsx("span",{className:"session-parallel-badge",children:I}):null,!I&&X&&he?s.jsx("span",{className:`session-fork-badge ${he}`,children:X}):null]}),s.jsxs("div",{className:"session-meta-row",children:[s.jsx("span",{className:"session-meta",children:PN(t,n,u,r.displayName)}),ee&&U?s.jsx("span",{className:U,children:ee}):null,s.jsx("span",{className:`session-provider-badge ${t.provider}`,children:md(t.provider)})]})]})})]}),We]})}async function K8(e,t=document){await Pk(),await Pk(),await Bp(420),await Y8(t,1800),e&&await J8(e,1800)}function G8(){if(typeof document>"u")return"";const e=[];for(const t of Array.from(document.styleSheets))try{const n=t.cssRules;if(!n||n.length===0)continue;e.push(Array.from(n).map(r=>r.cssText).join(`
1017
+ `))}catch{continue}return e.join(`
1018
+ `)}function Rk(e){const t={};for(const n of Array.from(e.attributes))n.name!=="style"&&(t[n.name]=n.value);return t}function Pk(){return new Promise(e=>{window.requestAnimationFrame(()=>e())})}function Bp(e){return new Promise(t=>{window.setTimeout(t,e)})}async function Y8(e,t){const n=e.fonts;!n||typeof n.ready>"u"||await Promise.race([n.ready.catch(()=>{}),Bp(t)])}async function J8(e,t){const n=Array.from(e.querySelectorAll("img"));n.length!==0&&await Promise.race([Promise.all(n.map(r=>Q8(r))),Bp(t)])}function X8(){if(typeof document>"u")return{shellWidthPx:null};const e=[".conversation-timeline-shell",".conversation-main",".conversation-panel"];for(const t of e){const n=document.querySelector(t);if(!(n instanceof HTMLElement))continue;const r=n.getBoundingClientRect();if(!(!Number.isFinite(r.width)||r.width<=0))return{shellWidthPx:Math.round(r.width)}}return{shellWidthPx:null}}function Q8(e){return e.complete?Promise.resolve():new Promise(t=>{const n=()=>{e.removeEventListener("load",n),e.removeEventListener("error",n),t()};e.addEventListener("load",n),e.addEventListener("error",n)})}function Zf({workspaceGroups:e,workspaceVisualContextMap:t,sessionDisplaySortMode:n,favoriteSessions:r,favoriteSessionIds:i,activeWorkspaceId:o,activeWorkbenchMode:l,isConversationActive:c,isTerminalActive:u,isButlerActive:f,isSearchOpen:h,navigationLoading:m,navigationError:g,activeSessionId:p,onRefreshNavigation:b,onSessionUpdated:y,onNavigateConversation:x,onSelectWorkbenchMode:k,onNavigateTerminals:C,onNavigateButler:j,onOpenSearch:H,onOpenSettings:_,onSelectWorkspace:T,onToggleWorkspaceCollapse:P,onStartWorkspaceReorder:z,onPreviewWorkspaceReorder:L,onCommitWorkspaceReorder:R,allowWorkspaceReorder:K,subscribeGitSnapshot:E,requestGitRefresh:D,subscribeWorkspaceManagementSnapshot:te,requestWorkspaceManagementRefresh:V,onToggleFavoriteSession:ee,onArchiveSession:U,onUnarchiveSession:he,workspaceManagementStateById:X,setWorkspaceManagementStateById:I,unreadNotificationCount:xe,notificationPanelOpen:le,onToggleNotificationPanel:M,onClose:de,onToggleCollapse:Ne,affairsMenuSlot:ye,affairsContentSlot:Be}){var Kl;const We=Nl(),Ce=Hn(),ke=Lm(Ce),{showToast:we}=Vn(),se=np(),ce=Bu(N=>N),Y=((Kl=au(ce))==null?void 0:Kl.name)??"",Te=d.useCallback(async N=>{const ne=cm(N,"code")??ua(N),me=await rI(Ce,{workspaceId:N,focusOwner:"code-workbench",routePath:ne});me.ok||we({title:me.detail??a("desktopWindow.invalidCodeTarget"),tone:"error"})},[Ce,we]),pe=d.useCallback(async N=>{const ne=await sI(Ce,{workspaceId:N,focusOwner:"affairs-workbench"});ne.ok||we({title:ne.detail??a("desktopWindow.invalidAffairsTarget"),tone:"error"})},[Ce,we]),fe=d.useCallback(async N=>{!Ce.isDesktop||!Ce.bridge.supported||!o||(N.preventDefault(),N.stopPropagation(),await dl([{id:"open-code-new-window",label:a("shell.workbenchModeCodeOpenInNewWindow"),onSelect:()=>Te(o)}]))},[o,Te,Ce.bridge.supported,Ce.isDesktop]),W=d.useCallback(async N=>{!Ce.isDesktop||!Ce.bridge.supported||!o||(N.preventDefault(),N.stopPropagation(),await dl([{id:"open-affairs-new-window",label:a("shell.workbenchModeAffairsOpenInNewWindow"),onSelect:()=>pe(o)}]))},[o,pe,Ce.bridge.supported,Ce.isDesktop]),Me=ce.hosts.length+Wk(ce).length>1&&Y.length>0,[je,Q]=d.useState(!1),[ge,Oe]=d.useState(!1),[$e,Ve]=d.useState(!1),[G,ve]=d.useState([]),[_e,nt]=d.useState(null),[et,ot]=d.useState(null),[jt,Ft]=d.useState(null),[bt,_t]=d.useState(null),[xt,rt]=d.useState(null),[It,$t]=d.useState(null),[pt,Ie]=d.useState(null),[kt,St]=d.useState(!1),[vt,Ct]=d.useState(!1),[J,Ue]=d.useState(""),[ze,st]=d.useState(""),[q,re]=d.useState(""),[ue,Re]=d.useState({localBranches:[],remoteBranches:[],tags:[]}),[Se,Ke]=d.useState(!1),[De,He]=d.useState(-1),[lt,wt]=d.useState(!1),[it,Ze]=d.useState(!1),[Ht,gt]=d.useState(null),[Nt,dt]=d.useState(null),[ft,en]=d.useState(null),[cn,qt]=d.useState(null),[Cn,Bt]=d.useState(null),[is,Ws]=d.useState(null),[fn,mt]=d.useState(null),[O,Ae]=d.useState(!1),[Xe,Qt]=d.useState(null),[Un,as]=d.useState(null),[tn,sn]=d.useState(null),[At,Gt]=d.useState(null),[Zn,es]=d.useState(Yf),[os,ut]=d.useState({}),[Ds,cr]=d.useState({}),[jn,an]=d.useState([]),[hs,ur]=d.useState({expandedWorkspaceIds:[],collapsedWorkspaceIds:[]}),[ts,Dn]=d.useState(null),[Kn,Rn]=d.useState(""),[Nn,ks]=d.useState(null),[xn,$s]=d.useState(null),[Vt,nn]=d.useState([]),[ns,ss]=d.useState(!1),[Ts,Xs]=d.useState({}),[ls,zs]=d.useState(null),ms=d.useRef(null),ps=d.useRef(null),ws=d.useRef(null),On=d.useRef(null),vs=d.useRef(new Map),Ss=d.useRef(null),Wn=d.useRef(null),Gn=d.useRef(null),cs=d.useMemo(()=>new Set(hs.expandedWorkspaceIds),[hs.expandedWorkspaceIds]),Rt=d.useMemo(()=>new Set(hs.collapsedWorkspaceIds),[hs.collapsedWorkspaceIds]),Yn=ls!==null,Mt=K&&Ce.isDesktop&&Ce.ui.osFamily==="macos",A=d.useMemo(()=>Q3(e,n),[e,n]),ie=d.useMemo(()=>{const N=new Map;for(const ne of e){N.set(ne.workspace.id,_a(ne).map(me=>dm(A,me.item.sessionId)??me));for(const me of ON(ne.childWorktrees)){const Le=me.visibleSessionTree.map(Fe=>dm(A,Fe.item.sessionId)??Fe).filter(Fe=>Fe.item.workspaceId===me.workspace.id&&Fe.depth===0);N.set(me.workspace.id,Le)}}return N},[A,e]),tt=d.useCallback(()=>{Qt(null),as(null)},[]),Pt=d.useCallback((N,ne)=>{Qt(N),as(ne)},[]),zt=Qf(e,xt)??((pt==null?void 0:pt.id)===xt?pt:null),pn=q.trim().toLowerCase(),Os=d.useMemo(()=>[{key:"localBranches",label:a("shell.createWorktreeBaseRefLocalGroup"),items:ue.localBranches},{key:"remoteBranches",label:a("shell.createWorktreeBaseRefRemoteGroup"),items:ue.remoteBranches},{key:"tags",label:a("shell.createWorktreeBaseRefTagGroup"),items:ue.tags}].map(ne=>({...ne,items:ne.items.filter(me=>pn?me.value.toLowerCase().includes(pn):!0)})).filter(ne=>ne.items.length>0),[pn,ue]),Tn=d.useMemo(()=>Os.flatMap(N=>N.items),[Os]),Qs=zt?`create-worktree-base-ref-listbox-${zt.id}`:"create-worktree-base-ref-listbox",Pn=h8(e,cn),on=Pn?Sr(Pn.workspace):null,Sn=(Pn==null?void 0:Pn.archivedSessions)??[],{searchOpen:gn,searchKeyword:bn,filteredSessions:Cs,summaryLoading:js,summaryError:Ge,summaryBySessionId:ei,setSearchKeyword:Mn,toggleSearch:Hs}=f3(Pn!==null,Sn),ir=d.useId(),Is=d.useMemo(()=>f8(e,xn),[xn,e]),Zs=d.useMemo(()=>Is?n8(Is.visibleSessionTree):[],[Is]),yn=d.useMemo(()=>Zs.map(N=>N.sessionId),[Zs]),Us=d.useMemo(()=>new Set(yn),[yn]),qs=d.useMemo(()=>new Set(Vt),[Vt]),us=yn.length>0&&Vt.length===yn.length;d.useEffect(()=>{I(N=>{const ne=Nk(e),me=new Set(ne),Le={};Object.entries(N).forEach(([at,dn])=>{me.has(at)&&(Le[at]=dn)}),ne.forEach(at=>{const dn=Qf(e,at);if(!dn)return;const qn=Br(mm(at),uk),Fn=Br(VN(at),uk),Ns=Le[at];let Cr=GN((Ns==null?void 0:Ns.detail)??qn??KN(dn),dn);(Fn!=null&&Fn.status||Fn!=null&&Fn.branches)&&(Cr=YN(Cr,{status:Fn.status??null,branches:Fn.branches??null})),Le[at]={detail:Cr,loading:!1,error:null}});const Fe=Object.keys(N),Lt=Object.keys(Le);return Fe.length===Lt.length&&Lt.every(at=>N[at]===Le[at])?N:Le})},[e]);const kr=d.useCallback(async N=>{await b(),await Ce.bridge.showNotification(a("shell.importSuccess"),N.path)},[b,Ce.bridge]),$r=d.useCallback(async N=>{await b(),await Ce.bridge.showNotification(a("shell.cloneSuccess"),N.path)},[b,Ce.bridge]);function pi(N){if(G.includes(N)){ve(me=>me.filter(Le=>Le!==N));return}ve(me=>[...me,N]),E(N),D(N),te(N),V(N)}async function ti(N,ne){if(Ts[N])return;const me=(ne==null?void 0:ne.trim().toUpperCase())??null;Xs(Le=>({...Le,[N]:!0}));try{await ew(N,{backgroundColor:me}),await b()}catch(Le){we({title:Le instanceof Error?Le.message:a("shell.manageWorkspaceColorSaveFailed"),tone:"error"})}finally{Xs(Le=>({...Le,[N]:!1}))}}async function gi(){if(!(!_e||et)){ot(_e.id);try{await qT(_e.id),ve(N=>N.filter(ne=>ne!==_e.id)),I(N=>{const ne={...N};return delete ne[_e.id],ne}),nt(null),await b(),we({title:a("shell.manageWorkspaceRemoveSuccess"),tone:"success"})}catch(N){we({title:N instanceof Error?N.message:a("shell.manageWorkspaceRemoveFailed"),tone:"error"})}finally{ot(null)}}}d.useEffect(()=>{if(!Xe)return;function N(ne){const me=ne.target;me instanceof HTMLElement&&me.closest(".workbench-session-menu")||tt()}return window.addEventListener("pointerdown",N),()=>{window.removeEventListener("pointerdown",N)}},[tt,Xe]),d.useEffect(()=>{if(!xn){Vt.length>0&&nn([]),fn&&mt(null);return}if(!Is){$s(null),nn([]),mt(null);return}nn(N=>zN(N,Us))},[Is,fn,Us,xn,Vt.length]),d.useEffect(()=>{xn&&yn.length===0&&($s(null),nn([]),mt(null))},[yn.length,xn]),d.useEffect(()=>{const N=new Set(Nk(e)),ne=new Set(e.flatMap(me=>hm(me.childWorktrees)));ve(me=>me.filter(Le=>N.has(Le))),ur(me=>({expandedWorkspaceIds:me.expandedWorkspaceIds.filter(Le=>ne.has(Le)),collapsedWorkspaceIds:me.collapsedWorkspaceIds.filter(Le=>ne.has(Le))})),nt(me=>me&&N.has(me.id)?me:null),Xs(me=>Object.fromEntries(Object.entries(me).filter(([Le,Fe])=>Fe&&N.has(Le))))},[e]),d.useEffect(()=>{const N=r.findIndex(ne=>ne.session.sessionId===p);es(ne=>{const me=Wc(r.length,Yf,ne,N);return me===ne?ne:me})},[p,r]),d.useEffect(()=>{ut(N=>{const ne={};for(const me of e){const Le=_a(me),Fe=Le.findIndex(Lt=>Lt.item.sessionId===p||Co([Lt],p??"",at=>at.sessionId).length>0);ne[me.workspace.id]=Wc(Le.length,Bo,N[me.workspace.id],Fe);for(const Lt of Jo(me.childWorktrees)){Lt.item.sessionId===p||Co([Lt],p??"",Fn=>Fn.sessionId).length>0;const at=Lt.item.workspaceId;if(ne[at]!==void 0)continue;const dn=Jo(me.childWorktrees).filter(Fn=>Fn.item.workspaceId===at&&Fn.depth===0),qn=dn.findIndex(Fn=>Fn.item.sessionId===p||Co([Fn],p??"",Ns=>Ns.sessionId).length>0);ne[at]=Wc(dn.length,Bo,N[at],qn)}}return yk(N,ne)?N:ne})},[p,e]),d.useEffect(()=>{cr(N=>{const ne={};for(const me of e)for(const Le of[..._a(me),...Jo(me.childWorktrees)])for(const Fe of Ea(or(Le))){const Lt=or(Fe);if(Lt.length===0)continue;const at=Ea(Lt),dn=at.findIndex(qn=>qn.item.sessionId===p);ne[Fe.item.sessionId]=Wc(at.length,_c,N[Fe.item.sessionId],dn)}return yk(N,ne)?N:ne})},[p,e]),d.useEffect(()=>{if(!p)return;const N=e.flatMap(ne=>[...Co(_a(ne),p,me=>me.sessionId),...Jo(ne.childWorktrees).flatMap(me=>Co([me],p,Le=>Le.sessionId))]);N.length!==0&&an(ne=>{const me=new Set(ne);let Le=!1;for(const Fe of N)me.has(Fe)||(me.add(Fe),Le=!0);return Le?Array.from(me):ne})},[p,e]),d.useEffect(()=>{if(!o)return;const N=[];for(const ne of e){const me=WN(ne.childWorktrees,o);me.length!==0&&N.push(...me)}N.length>0&&ur(ne=>{const me=new Set(ne.expandedWorkspaceIds);let Le=!1;for(const Fe of N)me.has(Fe)||(me.add(Fe),Le=!0);return Le?{expandedWorkspaceIds:Array.from(me),collapsedWorkspaceIds:ne.collapsedWorkspaceIds}:ne})},[o,e]),d.useEffect(()=>{if(!xt){Ie(null),St(!1),Ct(!1),Ue(""),st(""),re(""),Ke(!1),He(-1),wt(!1),Re({localBranches:[],remoteBranches:[],tags:[]}),Ze(!1),gt(null);return}St(!1),Ue(""),st(""),re(""),Ke(!1),He(-1),wt(!1),Re({localBranches:[],remoteBranches:[],tags:[]}),Ze(!1),gt(null)},[xt]),d.useEffect(()=>{const N=zt;if(!kt||!N)return;let ne=!1;const me=N.id;return Ze(!0),gt(null),Promise.all([G0(me),Y0(me)]).then(([Le,Fe])=>{ne||Re(O3(Le,Fe))}).catch(()=>{ne||(Re({localBranches:[],remoteBranches:[],tags:[]}),gt(a("shell.createWorktreeBaseRefLoadFailed")))}).finally(()=>{ne||Ze(!1)}),()=>{ne=!0}},[zt==null?void 0:zt.id,kt]),d.useLayoutEffect(()=>{if(!Se||!ms.current){dt(null),en(null);return}const N=()=>{const me=ms.current;if(!me)return;const Le=F3(me);dt({top:Le.bottom+8,left:Le.left,width:Le.width})};N();const ne=me=>{var Fe,Lt;const Le=me.target;Le instanceof Node&&((Fe=ms.current)!=null&&Fe.contains(Le)||(Lt=ps.current)!=null&&Lt.contains(Le)||(Ke(!1),He(-1)))};return window.addEventListener("resize",N),window.addEventListener("scroll",N,!0),window.addEventListener("pointerdown",ne),()=>{window.removeEventListener("resize",N),window.removeEventListener("scroll",N,!0),window.removeEventListener("pointerdown",ne)}},[Tn.length,Se]),d.useLayoutEffect(()=>{if(!Se||!ps.current){en(null);return}const N=ps.current,ne=()=>{const Le=Math.ceil(N.getBoundingClientRect().height);en(Fe=>Fe===Le?Fe:Le)};if(ne(),typeof ResizeObserver>"u")return;const me=new ResizeObserver(()=>{ne()});return me.observe(N),()=>{me.disconnect()}},[Se,Os,it,Ht]);function En(){Q(!0)}function dr(){Oe(!0)}function ni(N){er(),rt(null),$t({kind:"workspace",workspaceId:N.id,workspaceName:N.name})}function er(){St(!1),Ue(""),st(""),re(""),Ke(!1),He(-1),wt(!1)}function Pr(N,ne){const me=N.getBoundingClientRect();return ne<=me.top+me.height/2?"before":"after"}function Yi(){On.current!==null&&(cancelAnimationFrame(On.current),On.current=null),zs(null)}function As(N){const ne=(N==null?void 0:N.commit)??!1,me=(N==null?void 0:N.preserveClickSuppression)??!1,Le=Ss.current,Fe=Wn.current;Ss.current=null,Wn.current=null,Fe==null||Fe(),Le!=null&&Le.dragging&&(Yi(),ne&&R(),!me&&Gn.current===Le.workspaceId&&(Gn.current=null))}function tr(N){if(Gn.current===N){Gn.current=null;return}P(N)}function fr(N,ne){if(ne){vs.current.set(N,ne);return}vs.current.delete(N)}function si(N,ne){for(const[me,Le]of vs.current){const Fe=Le.getBoundingClientRect();if(N>=Fe.left&&N<=Fe.right&&ne>=Fe.top&&ne<=Fe.bottom)return{workspaceId:me,element:Le}}return null}function wr(N,ne){var dn;if(!Mt||N.button!==0)return;As();const me=N.currentTarget,Le={pointerId:N.pointerId,workspaceId:ne,startX:N.clientX,startY:N.clientY,pointerTarget:me,dragging:!1};Ss.current=Le,(dn=me.setPointerCapture)==null||dn.call(me,N.pointerId);const Fe=qn=>{zr(qn)},Lt=qn=>{v(qn.pointerId,{commit:!0,preserveClickSuppression:!0})},at=qn=>{v(qn.pointerId,{commit:!1,preserveClickSuppression:!1})};Wn.current=()=>{me.removeEventListener("pointermove",Fe),me.removeEventListener("pointerup",Lt),me.removeEventListener("pointercancel",at),window.removeEventListener("pointermove",Fe),window.removeEventListener("pointerup",Lt),window.removeEventListener("pointercancel",at)},me.addEventListener("pointermove",Fe),me.addEventListener("pointerup",Lt),me.addEventListener("pointercancel",at),window.addEventListener("pointermove",Fe,{passive:!1}),window.addEventListener("pointerup",Lt),window.addEventListener("pointercancel",at)}function zr(N){const ne=Ss.current;if(!ne||ne.pointerId!==N.pointerId)return;if(!ne.dragging){if(Math.hypot(N.clientX-ne.startX,N.clientY-ne.startY)<w3)return;ne.dragging=!0,Gn.current=ne.workspaceId,z(),zs(ne.workspaceId)}N.preventDefault();const me=si(N.clientX,N.clientY);!me||me.workspaceId===ne.workspaceId||L(ne.workspaceId,me.workspaceId,Pr(me.element,N.clientY))}function v(N,ne){var Le,Fe;const me=Ss.current;!me||me.pointerId!==N||((Fe=(Le=me.pointerTarget).releasePointerCapture)==null||Fe.call(Le,N),As(ne))}function $(N){zr(N)}function w(N){v(N.pointerId,{commit:!0,preserveClickSuppression:!0})}function F(N){v(N.pointerId,{commit:!1,preserveClickSuppression:!1})}function Z(N,ne){N.dataTransfer.effectAllowed="move",N.dataTransfer.setData("text/plain",ne),z(),On.current!==null&&cancelAnimationFrame(On.current),On.current=requestAnimationFrame(()=>{On.current=null,zs(ne)})}function be(N,ne){const me=ls||N.dataTransfer.getData("text/plain");!me||me===ne||(N.preventDefault(),N.dataTransfer.dropEffect="move",L(me,ne,Pr(N.currentTarget,N.clientY)))}function Ee(N){N.preventDefault()}function Je(){Yi(),R()}d.useEffect(()=>()=>{As()},[]);function Et(N){return Ds[N]??_c}function Hr(N){return jn.includes(N)}function un(N){return os[N]??Bo}function yo(){es(N=>Math.min(r.length,N+Yf))}function xa(N,ne){ut(me=>({...me,[N]:Math.min(ne,(me[N]??Bo)+Bo)}))}function Wl(N){cr(ne=>({...ne,[N]:(ne[N]??_c)+_c}))}function $l(N){an(ne=>ne.includes(N)?ne.filter(me=>me!==N):[...ne,N])}function zl(N,ne){return Rt.has(N)?!1:ne||cs.has(N)}function gd(N,ne){const me=!zl(N,ne);ur(Le=>{const Fe=Le.expandedWorkspaceIds.filter(at=>at!==N),Lt=Le.collapsedWorkspaceIds.filter(at=>at!==N);return me?{expandedWorkspaceIds:[...Fe,N],collapsedWorkspaceIds:Lt}:{expandedWorkspaceIds:Fe,collapsedWorkspaceIds:[...Lt,N]}})}function ri(N){const ne=Ea(A).find(me=>me.item.sessionId===N)??null;return ne?or(ne):[]}function bi(N,ne){const me=Sr(N);return s.jsxs("button",{type:"button",className:"workbench-archive-folder","data-workspace-tone":me.tone,style:Gr(me),onClick:()=>qt(N.id),children:[s.jsxs("span",{className:"workbench-archive-folder-main",children:[s.jsx(z8,{}),s.jsx("span",{children:a("shell.archiveFolderLabel")})]}),s.jsx("span",{className:"workbench-section-counter",children:ne.length})]})}function yi(){return s.jsxs("div",{className:"workbench-workspace-batch-toolbar",children:[s.jsx("span",{className:"workbench-workspace-batch-label",children:a("shell.batchSelectionMode")}),s.jsxs("span",{className:"workbench-workspace-batch-counter",children:[Vt.length,"/",yn.length]}),s.jsx("button",{type:"button",className:"workbench-workspace-batch-action",onClick:Ul,children:us?a("shell.clearSelectedSessions"):a("shell.selectAllSessions")}),s.jsx("button",{type:"button",className:"workbench-workspace-batch-action primary",disabled:Vt.length===0||ns||O,onClick:()=>{Vl()},children:ns?a("shell.batchArchiving"):a("shell.batchArchiveAction")}),s.jsx("button",{type:"button",className:"workbench-workspace-batch-action danger",disabled:Vt.length===0||ns||O,onClick:yd,children:O?a("shell.batchDeleting"):a("shell.batchDeleteAction")}),s.jsx("button",{type:"button",className:"workbench-workspace-batch-action",onClick:Hl,children:a("common.cancel")})]})}function xo(N,ne="workbench-workspace-actions"){return s.jsxs("div",{className:ne,children:[s.jsx("button",{type:"button",className:"workbench-workspace-icon-button","aria-label":a("shell.switchWorkspace"),title:a("shell.switchWorkspace"),"aria-pressed":o===N,onClick:()=>{T(N),de==null||de()},children:s.jsx(O8,{})}),s.jsx("button",{type:"button",className:"workbench-workspace-icon-button","aria-label":a("shell.batchSelectSessions"),title:a("shell.batchSelectSessions"),onClick:()=>xi(N),children:s.jsx(D8,{})}),s.jsx("button",{type:"button",className:"workbench-workspace-icon-button workbench-workspace-create","aria-label":a("shell.createSession"),title:a("shell.createSession"),onClick:()=>rt(N),children:s.jsx(A8,{})})]})}function ko(N){const ne=ie.get(N.workspace.id)??N.visibleSessionTree,Le=new Set(hm(N.children)).has(o??""),Fe=N.workspace.id===o||Le,Lt=Yn||!zl(N.workspace.id,Fe),at=Sr(N.workspace);return s.jsxs("section",{className:"workbench-workspace-group","data-worktree-node":"true","data-batch-active":xn===N.workspace.id,"data-worktree-depth":N.meta.depth,"data-workspace-tone":"worktree",style:Gr(at),children:[s.jsxs("div",{className:"workbench-workspace-header minimal",children:[s.jsxs("button",{type:"button",className:"workbench-workspace-toggle","aria-label":Lt?a("shell.worktreeExpand"):a("shell.worktreeCollapse"),onClick:()=>gd(N.workspace.id,Fe),children:[s.jsx("span",{className:"workbench-workspace-toggle-icon","aria-hidden":"true",children:s.jsx(Ka,{expanded:!Lt})}),s.jsxs("span",{children:[s.jsx("strong",{children:N.meta.displayName||N.workspace.name}),s.jsx("span",{className:"session-meta",children:N.meta.branchName})]})]}),xn===N.workspace.id?yi():xo(N.workspace.id)]}),Lt?null:s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"workbench-session-list","data-workspace-tone":at.tone,style:Gr(at),children:[ne.length===0?s.jsx("p",{className:"workbench-session-empty",children:a("shell.emptyWorkspaceSessions")}):ne.slice(0,un(N.workspace.id)).map(dn=>Ji({node:dn,workspace:N.workspace,workspaceContext:at,menuKeyPrefix:`worktree:${N.workspace.id}`,showWorkspaceName:!1,selectionMode:xn===N.workspace.id,favoriteEnabled:!0})),ne.length>un(N.workspace.id)?s.jsx("button",{type:"button",className:"workbench-subsession-expand ghost-button",onClick:()=>xa(N.workspace.id,ne.length),children:a("shell.sessionExpandMore")}):null]}),N.children.length>0?s.jsx("div",{className:"workbench-session-list workbench-worktree-child-list",children:N.children.map(dn=>ko(dn))}):null,bi(N.workspace,N.archivedSessions)]})]},N.workspace.id)}function Ji(N){var zp,Hp,Up,qp;const{node:ne,fullNode:me=ne,branchKey:Le,subagentStateKey:Fe,workspace:Lt,workspaceContext:at,menuKeyPrefix:dn,showWorkspaceName:qn,selectionMode:Fn,favoriteEnabled:Ns,showParallelBadge:Cr=!0,forceInactive:jr=!1,ancestorExpanded:wi=!1,allowToggle:ii=ne.depth===0,ancestorHasNextSiblings:hr=[],hasNextSibling:In=!1,isFirstSibling:Gl=!1}=N,wn=ne.item,vi=Qf(e,wn.workspaceId)??Lt,Yl=Sr(vi),S=or(me),B=Fe??wn.sessionId,oe=Hr(B),Pe=wi&&or(ne).length>0,Ye=oe,Qe=Pe||Ye,yt=oe&&ii,Ut=Pe?ne:yt?s8(ne,Et(B),n):me,Dt=Qe?or(Ut):[],ct=Ea(S).length,kn=Ea(Dt).length,mr=yt&&kn<ct,Nr=ne.depth>0?[...hr,In]:[...hr],_n=((Hp=(zp=wn.parallelGroup)==null?void 0:zp.groupId)==null?void 0:Hp.trim())||null,Tr=((Up=wn.parallelGroup)==null?void 0:Up.role)==="anchor"&&((qp=wn.parallelGroup)==null?void 0:qp.sourceType)==="new"&&!!_n,vo=Tr&&_n?Dt.filter(vn=>{var ds;return((ds=vn.item.parallelGroup)==null?void 0:ds.groupId)===_n}):[],eT=Dt.filter(vn=>{var ds;return((ds=vn.item.parallelGroup)==null?void 0:ds.groupId)!==_n}),tT=Tr&&_n?S.filter(vn=>{var ds;return((ds=vn.item.parallelGroup)==null?void 0:ds.groupId)===_n}):[],nT=S.filter(vn=>{var ds;return((ds=vn.item.parallelGroup)==null?void 0:ds.groupId)!==_n}),sT=vo.length>0?eT:[],$p=vo.length>0?[bk({session:wn,depth:ne.depth+1,children:sT.map(vn=>um(vn,1))}),...vo].map((vn,ds)=>{const So=ds===0,rT=bk({session:wn,depth:ne.depth+1,children:nT.map(Sd=>um(Sd,1))});return{node:vn,fullNode:So?rT:tT.find(Sd=>Sd.item.sessionId===vn.item.sessionId)??vn,branchKey:So?gk(wn.sessionId):void 0,subagentStateKey:So?gk(wn.sessionId):void 0,showParallelBadge:!So,forceInactive:So}}):Dt.map(vn=>({node:vn,fullNode:S.find(ds=>ds.item.sessionId===vn.item.sessionId)??vn}));return s.jsxs("div",{className:"workbench-session-tree-node",children:[s.jsxs("div",{className:"workbench-session-tree-row",style:{"--workbench-session-tree-depth":ne.depth},children:[ne.depth>0?s.jsxs("div",{className:"workbench-session-tree-guides","aria-hidden":"true",children:[hr.map((vn,ds)=>vn?s.jsx("span",{className:"workbench-session-tree-guide-column",style:{"--workbench-session-tree-level":ds+1}},`${wn.sessionId}:ancestor:${ds}`):null),s.jsx("span",{className:"workbench-session-tree-guide-branch","data-continue":In,"data-first":Gl,style:{"--workbench-session-tree-level":ne.depth},children:s.jsx("span",{className:"workbench-session-tree-guide-branch-horizontal"})})]}):null,s.jsx(V8,{menuKey:`${dn}:${Le??wn.sessionId}`,session:wn,workspace:vi,workspaceContext:Yl,isActive:!jr&&wn.sessionId===p,isFavorite:Ns&&i.has(wn.sessionId),menuOpen:Xe===`${dn}:${Le??wn.sessionId}`,showWorkspaceName:qn,depth:ne.depth,showActions:Ns,exportDisabled:tn!==null,hasSubagents:ii&&S.length>0,subagentListExpanded:Ye,showParallelBadge:Cr,selectionMode:Fn,selected:qs.has(wn.sessionId),onToggleSelect:()=>bd(wn.sessionId),onToggleSubagents:()=>$l(B),onOpen:()=>{We(Yr(vi.id,wn.sessionId)),de==null||de()},onRename:()=>bs(wn,vi),menuAnchorPoint:Xe===`${dn}:${Le??wn.sessionId}`?Un:null,onOpenContextMenu:vn=>Pt(`${dn}:${Le??wn.sessionId}`,vn),onExport:vn=>ql(wn,vn),onToggleFavorite:()=>Xi(wn.sessionId),onArchive:()=>xd(wn.sessionId),onDelete:Ja(wn.provider).supportsSessionDelete===!0?()=>{tt(),Bt({session:wn,workspace:vi})}:void 0,onCloseMenu:tt})]}),S.length>0&&Qe?s.jsxs("div",{className:"workbench-subsession-list",children:[$p.map((vn,ds)=>Ji({node:vn.node,fullNode:vn.fullNode,branchKey:vn.branchKey,subagentStateKey:vn.subagentStateKey,workspace:Lt,workspaceContext:at,menuKeyPrefix:dn,showWorkspaceName:qn,selectionMode:Fn,favoriteEnabled:Ns,showParallelBadge:vn.showParallelBadge,forceInactive:vn.forceInactive,allowToggle:!0,ancestorHasNextSiblings:Nr,hasNextSibling:ds<$p.length-1,isFirstSibling:ds===0})),mr?s.jsx("button",{type:"button",className:"workbench-subsession-expand ghost-button",onClick:()=>Wl(B),children:a("shell.subagentExpandMore")}):null]}):null]},Le??wn.sessionId)}function xi(N){tt(),$s(N),nn([]),mt(null)}function Hl(){$s(null),nn([]),mt(null)}function bd(N){nn(ne=>k8(ne,N))}function Ul(){nn(N=>N.length===yn.length?[]:yn)}function yd(){if(!Is||Vt.length===0||ns||O)return;const N=new Map(Zs.map(me=>[me.sessionId,me])),ne=Vt.flatMap(me=>{const Le=N.get(me);return Le?[Le]:[]});ne.length!==0&&(tt(),mt({workspace:Is.workspace,sessions:ne}))}async function ka(N,ne){Ft(N),_t(ne);try{await SN(N,ne),rt(null),We(qk(N,ne)),de==null||de()}catch(me){we({title:me instanceof Error?me.message:a("shell.startSessionFailed"),tone:"error"})}finally{Ft(null),_t(null)}}async function wo(N){if(N.preventDefault(),!zt||vt)return;const ne=J.trim(),me=ze.trim(),Le=q.trim();if(!ne){we({title:a("shell.createWorktreeBranchRequired"),tone:"error"});return}if(!L3(ne)){we({title:a("shell.createWorktreeBranchInvalid"),tone:"error"});return}Ct(!0);try{const Fe=await h0({sourceWorkspaceId:zt.id,branchName:ne,displayName:me||void 0,baseRef:Le||void 0});Ie(Fe.workspace),T(Fe.workspace.id),await b(),rt(Fe.workspace.id),er(),we({title:a("shell.createWorktreeSucceeded",{name:Fe.meta.displayName||Fe.workspace.name}),tone:"success"})}catch(Fe){we({title:Fe instanceof Error?Fe.message:a("shell.createWorktreeFailed"),tone:"error"})}finally{Ct(!1)}}async function Xi(N){const ne=i.has(N);tt();try{await ee(N),we({title:ne?a("shell.favoriteRemoved"):a("shell.favoriteAdded"),tone:"success"})}catch(me){we({title:me instanceof Error?me.message:a("shell.favoriteToggleFailed"),tone:"error"})}}async function xd(N){tt();try{await U(N),we({title:a("shell.archiveAdded"),tone:"success"})}catch(ne){we({title:ne instanceof Error?ne.message:a("shell.navigationLoadFailed"),tone:"error"})}}async function ql(N,ne){var me,Le;if(!tn){tt(),sn(N.sessionId);try{const Fe=await nC(N.sessionId),Lt=X8();if(ne==="md"){const hr=Za(N,"md"),In=sC(N,Fe.messages);Tu(hr,In,"text/markdown;charset=utf-8"),we({title:a("conversation.exportMarkdownSuccess"),tone:"success"});return}Bs.flushSync(()=>{Gt({session:N,items:bo({messages:Fe.messages}),shellWidthPx:Lt.shellWidthPx})}),await K8(ws.current);const at=((me=ws.current)==null?void 0:me.innerHTML.trim())??"";if(!at)throw new Error(a("conversation.exportLoadFailed"));const dn=Rk(document.documentElement),qn=document.body?Rk(document.body):{},Fn=document.documentElement.getAttribute("style"),Ns=((Le=document.body)==null?void 0:Le.getAttribute("style"))??null,Cr=`${G8()}
1019
+ ${q8}`,jr=aC({title:N.title||a("conversation.titleFallback"),bodyHtml:`<div class="session-export-document-root">${at}</div>`,styleText:Cr,htmlAttributes:dn,bodyAttributes:qn,htmlStyle:Fn,bodyStyle:Ns});if(ne==="html"){const hr=Za(N,"html");Tu(hr,jr,"text/html;charset=utf-8"),we({title:a("conversation.exportHtmlSuccess"),tone:"success"});return}const wi=Za(N,"pdf"),ii=iC(N,Fe.messages);rC(wi,ii,"application/pdf"),we({title:a("conversation.exportPdfPreparing"),tone:"success"})}catch(Fe){we({title:Fe instanceof Error?Fe.message:a("conversation.exportLoadFailed"),tone:"error"})}finally{Bs.flushSync(()=>{Gt(null)}),sn(null)}}}async function kd(){if(!Cn||is)return;const{session:N,workspace:ne}=Cn;Ws(N.sessionId),tt();try{await rh(N.sessionId),nn(me=>me.filter(Le=>Le!==N.sessionId)),Bt(null),p===N.sessionId&&We(ne.id?ua(ne.id):Fs()),await b(),we({title:a("shell.deleteSessionSuccess"),tone:"success"})}catch(me){we({title:me instanceof Error?me.message:a("shell.deleteSessionFailed"),tone:"error"})}finally{Ws(null)}}async function Vl(){if(!(Vt.length===0||ns||O)){tt(),ss(!0);try{const N=[...Vt],ne=await Promise.allSettled(N.map(async Fe=>({sessionId:Fe,session:await cu(Fe,!0)}))),me=[];let Le=0;for(const Fe of ne){if(Fe.status==="fulfilled"){me.push(Fe.value.sessionId),y(Fe.value.session);continue}Le+=1}me.length>0&&(await b(),nn(Fe=>Fe.filter(Lt=>!me.includes(Lt)))),Le>0?we({title:me.length>0?a("shell.batchArchivePartialFailed"):a("shell.batchArchiveFailed"),tone:"error"}):we({title:a("shell.batchArchiveSuccess"),tone:"success"})}catch(N){we({title:N instanceof Error?N.message:a("shell.batchArchiveFailed"),tone:"error"})}finally{ss(!1)}}}async function vr(){if(!fn||O)return;const{workspace:N,sessions:ne}=fn,me=ne.map(Le=>Le.sessionId);if(me.length===0){mt(null);return}Ae(!0),tt();try{const Le=await Promise.allSettled(me.map(async at=>(await rh(at),at))),Fe=[];let Lt=0;for(const at of Le){if(at.status==="fulfilled"){Fe.push(at.value);continue}Lt+=1}if(Fe.length>0&&(p&&Fe.includes(p)&&We(N.id?ua(N.id):Fs()),nn(at=>at.filter(dn=>!Fe.includes(dn))),await b()),Lt>0){mt(at=>{if(!at)return at;const dn=at.sessions.filter(qn=>!Fe.includes(qn.sessionId));return dn.length>0?{...at,sessions:dn}:null}),we({title:Fe.length>0?a("shell.batchDeletePartialFailed"):a("shell.batchDeleteFailed"),tone:"error"});return}mt(null),we({title:a("shell.batchDeleteSuccess"),tone:"success"})}catch(Le){we({title:Le instanceof Error?Le.message:a("shell.batchDeleteFailed"),tone:"error"})}finally{Ae(!1)}}async function gs(N){tt();try{await he(N),we({title:a("shell.archiveRestored"),tone:"success"})}catch(ne){we({title:ne instanceof Error?ne.message:a("shell.navigationLoadFailed"),tone:"error"})}}function bs(N,ne){tt(),Dn({session:N,workspace:ne}),Rn(N.title)}async function wd(N){if(N.preventDefault(),!ts)return;const ne=Kn.trim();if(ne){ks(ts.session.sessionId);try{const me=await xm(ts.session.sessionId,ne);y(me),Dn(null),Rn(""),we({title:a("shell.renameSuccess"),tone:"success"})}catch(me){we({title:me instanceof Error?me.message:a("shell.renameFailed"),tone:"error"})}finally{ks(null)}}}const Qi=r.slice(0,Zn),vd=Qi.length<r.length;function Sr(N){return t[N.id]??Iu(N)}function ki(N,ne,me,Le,Fe=[]){var hr;const Lt=G.includes(N.id),at=X[N.id]??{detail:null,loading:!1,error:null},dn=et===N.id,qn=Ts[N.id]===!0,Fn=(hr=at.detail)!=null&&hr.git.remotes.length?at.detail.git.remotes.map(In=>`${In.name}: ${In.url}`).join(" · "):a("shell.manageWorkspaceNoRemote"),Ns=at.detail?cB(at.detail.codeComposition.items,a("shell.manageWorkspaceCodeCompositionOther")):[],Cr=Ns.length>0?dB(Ns):void 0,jr=Sr(N),wi=m8(jr,Fe),ii=[...Fe,jr.displayName];return s.jsxs("article",{className:"workbench-manage-item","data-workspace-tone":jr.tone,"data-worktree-node":Le,style:Gr(jr),children:[s.jsxs("button",{type:"button",className:"workbench-manage-item-toggle","aria-expanded":Lt,onClick:()=>pi(N.id),children:[s.jsxs("span",{className:"workbench-manage-item-heading",children:[s.jsx(Ka,{expanded:Lt}),s.jsxs("span",{className:"workbench-manage-item-heading-copy",children:[s.jsx("strong",{children:jr.displayName}),s.jsx("span",{className:"workbench-manage-item-tree-path",children:wi})]})]}),s.jsx("span",{className:"workbench-section-counter",children:ne})]}),Lt?s.jsxs("div",{className:"workbench-manage-item-body",children:[s.jsxs("div",{className:"workbench-manage-detail-block",children:[s.jsx("span",{className:"workbench-manage-detail-label",children:a("shell.manageWorkspacePathLabel")}),s.jsx("p",{className:"workbench-manage-detail-value",children:N.path})]}),Le?s.jsxs("div",{className:"workbench-manage-detail-block",children:[s.jsxs("div",{className:"workbench-manage-detail-header",children:[s.jsx("span",{className:"workbench-manage-detail-label",children:a("shell.manageWorkspaceColorLabel")}),s.jsxs("div",{className:"workbench-manage-color-actions",children:[s.jsx("div",{className:"workbench-manage-color-palette","aria-label":a("shell.manageWorkspaceColorLabel"),children:j3.map(In=>s.jsx("button",{type:"button",className:"workbench-manage-color-swatch","aria-label":a("shell.manageWorkspaceColorSelectSwatch",{color:In}),"aria-pressed":N.backgroundColor===In,disabled:qn,"data-selected":N.backgroundColor===In,style:{backgroundColor:In},onClick:()=>{ti(N.id,In)}},In))}),s.jsx("button",{type:"button",className:"ghost-button",disabled:qn||!N.backgroundColor,onClick:()=>{ti(N.id,null)},children:a("shell.manageWorkspaceColorClearAction")})]})]}),s.jsx("p",{className:"workbench-manage-hint",children:N.backgroundColor??a("shell.manageWorkspaceColorUnset")})]}):null,at.loading&&at.detail===null?s.jsx("p",{className:"workbench-manage-status status-text",children:a("shell.manageWorkspaceLoading")}):null,at.error?s.jsx("p",{className:"workbench-manage-status status-text","data-tone":"error",children:at.error}):null,at.detail?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"workbench-manage-detail-block",children:s.jsxs("div",{className:"workbench-manage-detail-header",children:[s.jsx("span",{className:"workbench-manage-detail-label",children:a("shell.manageWorkspaceGitCommitCount")}),s.jsx("strong",{className:"workbench-manage-detail-accent",children:at.detail.git.commitCount??"--"})]})}),s.jsxs("div",{className:"workbench-manage-detail-block",children:[s.jsx("span",{className:"workbench-manage-detail-label",children:a("shell.manageWorkspaceGitInfoLabel")}),at.detail.git.isRepository?s.jsxs("div",{className:"workbench-manage-kv-list",children:[s.jsxs("div",{className:"workbench-manage-kv-item",children:[s.jsx("span",{children:a("shell.manageWorkspaceRepoRoot")}),s.jsx("span",{children:at.detail.git.repoRoot??"--"})]}),s.jsxs("div",{className:"workbench-manage-kv-item",children:[s.jsx("span",{children:a("shell.manageWorkspaceCurrentBranch")}),s.jsx("span",{children:at.detail.git.currentBranch??"--"})]}),s.jsxs("div",{className:"workbench-manage-kv-item",children:[s.jsx("span",{children:a("shell.manageWorkspaceRemoteLabel")}),s.jsx("span",{children:Fn})]})]}):s.jsx("p",{className:"workbench-section-empty",children:at.detail.git.error??a("shell.manageWorkspaceNotGit")})]}),s.jsxs("div",{className:"workbench-manage-detail-block",children:[s.jsx("span",{className:"workbench-manage-detail-label",children:a("shell.manageWorkspaceCodeCompositionLabel")}),Ns.length>0?s.jsxs("div",{className:"workbench-manage-type-chart",children:[s.jsxs("div",{className:"workbench-manage-type-chart-ring",style:Cr,"aria-hidden":"true",children:[s.jsx("strong",{className:"workbench-manage-type-chart-total",children:at.detail.codeComposition.scannedFileCount}),s.jsx("span",{className:"workbench-manage-type-chart-caption",children:a("shell.manageWorkspaceCodeCompositionFiles")})]}),s.jsx("div",{className:"workbench-manage-type-list",children:Ns.map(In=>s.jsxs("div",{className:"workbench-manage-type-item",children:[s.jsxs("span",{className:"workbench-manage-type-meta",children:[s.jsx("span",{className:"workbench-manage-type-swatch",style:{backgroundColor:In.color},"aria-hidden":"true"}),s.jsx("span",{className:"workbench-manage-type-name",children:In.type})]}),s.jsxs("span",{children:[In.count," · ",lB(In)]})]},In.key))})]}):s.jsx("p",{className:"workbench-section-empty",children:at.detail.codeComposition.error??a("shell.manageWorkspaceNoCodeComposition")}),at.detail.codeComposition.truncated?s.jsx("p",{className:"workbench-manage-hint",children:a("shell.manageWorkspaceCodeTruncated",{count:at.detail.codeComposition.scannedFileCount})}):null]})]}):null,s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{Ve(!1),We(Jk(N.id))},children:a("shell.workspaceDetailDebugOpenPageAction")}),s.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!et,onClick:()=>nt(N),children:dn?a("shell.manageWorkspaceRemoving"):a("shell.manageWorkspaceRemoveAction")})]})]}):null,me.length>0?s.jsx("div",{className:"workbench-manage-children",children:me.map(In=>ki(In.workspace,In.visibleSessions.length+In.archivedSessions.length,In.children,!0,ii))}):null]},N.id)}return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"workbench-nav-header","data-window-drag-handle":"workbench-nav-header","data-tauri-drag-region":ke,children:s.jsxs("div",{className:"workbench-nav-toolbar","data-tauri-drag-region":ke,children:[Ne?s.jsx("button",{type:"button",className:"workbench-nav-toolbar-button","aria-label":a("shell.hideSessionSidebar"),title:a("shell.hideSessionSidebar"),onClick:Ne,children:s.jsx(XN,{})}):null,s.jsx(_h,{}),s.jsx(pm,{unreadCount:xe,open:le,onToggle:M}),s.jsx("button",{type:"button",className:"workbench-nav-toolbar-button","data-open":h,"aria-label":a("shell.searchEntry"),title:a("shell.searchEntry"),"aria-haspopup":"dialog","aria-expanded":h,onClick:H,children:s.jsx(gm,{})})]})}),s.jsxs("div",{ref:se,className:"workbench-nav-body","data-scrollbar-autohide":"true",children:[s.jsxs("div",{className:"workbench-nav-segment",children:[s.jsxs("div",{className:"workbench-nav-segment-tabs",role:"tablist","aria-label":a("shell.workbenchModeTabsLabel"),children:[s.jsxs("div",{className:"workbench-nav-segment-pair","data-variant":"mode",children:[s.jsx("button",{type:"button",className:l==="code"?"workbench-nav-segment-button active":"workbench-nav-segment-button","data-layout":"paired","data-variant":"mode",role:"tab","aria-selected":l==="code",onClick:()=>k("code"),onContextMenu:N=>{fe(N)},children:s.jsx("span",{children:a("shell.workbenchModeCode")})}),s.jsx("button",{type:"button",className:l==="affairs"?"workbench-nav-segment-button active":"workbench-nav-segment-button","data-layout":"paired","data-variant":"mode",role:"tab","aria-selected":l==="affairs",onClick:()=>k("affairs"),onContextMenu:N=>{W(N)},children:s.jsx("span",{children:a("shell.workbenchModeAffairs")})})]}),l==="code"?s.jsxs("div",{className:"workbench-nav-code-entries",children:[s.jsxs("button",{type:"button",className:c?"workbench-nav-segment-button active":"workbench-nav-segment-button",role:"tab","aria-selected":c,onClick:x,children:[s.jsx(R8,{}),s.jsx("span",{children:a("shell.conversationEntry")})]}),s.jsxs("button",{type:"button",className:u?"workbench-nav-segment-button active":"workbench-nav-segment-button",role:"tab","aria-selected":u,onClick:C,children:[s.jsx(P8,{}),s.jsx("span",{children:a("shell.terminalsEntry")})]})]}):null]}),l==="code"?s.jsx(F1,{triggerClassName:"workbench-nav-segment-button",triggerLabel:a("shell.skillsEntry"),triggerLeading:s.jsx(M8,{}),workspaceId:o,sessionId:p}):l==="affairs"?ye??s.jsx("div",{className:"affairs-sidebar-empty",children:a("common.loading")}):null]}),l==="affairs"?Be??null:s.jsxs(s.Fragment,{children:[g?s.jsx("div",{className:"workbench-status-row",children:s.jsx("p",{className:"status-text","data-tone":"error",children:g})}):null,r.length>0?s.jsxs("section",{className:"workbench-section-block workbench-favorite-section",children:[s.jsxs("div",{className:"workbench-section-heading",children:[s.jsxs("div",{className:"workbench-section-heading-main",children:[s.jsx(QN,{active:!0,className:"workbench-favorite-heading-icon"}),s.jsx("span",{children:a("shell.favoriteSectionTitle")})]}),s.jsx("span",{className:"workbench-section-counter",children:r.length})]}),s.jsxs("div",{className:"workbench-session-list",children:[Qi.map(N=>{const ne=ri(N.session.sessionId);return s.jsx("div",{children:Ji({node:{item:N.session,depth:0,children:ne},workspace:N.workspace,workspaceContext:Sr(N.workspace),menuKeyPrefix:"favorite",showWorkspaceName:!0,selectionMode:!1,favoriteEnabled:!0})},N.session.sessionId)}),vd?s.jsx("button",{type:"button",className:"workbench-subsession-expand ghost-button",onClick:yo,children:a("shell.favoriteExpandMore")}):null]})]}):null,m&&e.length===0?s.jsx(S8,{}):null,!m&&!g&&e.length===0?s.jsx("div",{className:"workbench-empty-state minimal",children:s.jsx("p",{children:a("shell.emptyNavigationBody")})}):null,s.jsxs("section",{className:"workbench-section-block workbench-workspace-section",children:[s.jsxs("div",{className:"workbench-section-heading",children:[s.jsx("div",{className:"workbench-section-heading-main",children:s.jsx("span",{children:a("shell.workspaceSectionTitle")})}),s.jsxs("div",{className:"workbench-section-actions",children:[s.jsx("button",{type:"button",className:"workbench-workspace-icon-button","aria-label":a("shell.manageWorkspaceAction"),title:a("shell.manageWorkspaceAction"),onClick:()=>Ve(!0),children:s.jsx(N8,{})}),s.jsx("button",{type:"button",className:"workbench-workspace-icon-button","aria-label":a("shell.importWorkspaceTitle"),title:a("shell.importWorkspaceTitle"),onClick:En,children:s.jsx(j8,{})}),s.jsx("button",{type:"button",className:"workbench-workspace-icon-button","aria-label":a("shell.cloneWorkspaceTitle"),title:a("shell.cloneWorkspaceTitle"),onClick:dr,children:s.jsx(E8,{})})]})]}),e.map(N=>{const ne=ie.get(N.workspace.id)??_a(N),me=ls===N.workspace.id,Le=N.isCollapsed||Yn;return s.jsxs("section",{className:"workbench-workspace-group",ref:Fe=>fr(N.workspace.id,Fe),"data-workspace-group-id":N.workspace.id,"data-batch-active":xn===N.workspace.id,"data-dragging":me,onDragOver:Fe=>be(Fe,N.workspace.id),onDrop:Ee,children:[s.jsxs("div",{className:"workbench-workspace-header minimal",children:[s.jsxs("button",{type:"button",className:"workbench-workspace-toggle","aria-label":Le?a("shell.workspaceExpand"):a("shell.workspaceCollapse"),draggable:K&&!Mt,onClick:()=>tr(N.workspace.id),onPointerDown:Mt?Fe=>wr(Fe,N.workspace.id):void 0,onPointerMove:Mt?$:void 0,onPointerUp:Mt?w:void 0,onPointerCancel:Mt?F:void 0,onDragStart:K&&!Mt?Fe=>Z(Fe,N.workspace.id):void 0,onDragEnd:K&&!Mt?Je:void 0,"data-reorder-enabled":K?"true":void 0,children:[s.jsx("span",{className:"workbench-workspace-toggle-icon","aria-hidden":"true",children:s.jsx(Ka,{expanded:!Le})}),s.jsx("strong",{children:N.workspace.name})]}),xn===N.workspace.id?yi():xo(N.workspace.id)]}),Le?null:s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"workbench-session-list",children:[ne.length===0?s.jsx("p",{className:"workbench-session-empty",children:a("shell.emptyWorkspaceSessions")}):ne.slice(0,un(N.workspace.id)).map(Fe=>Ji({node:Fe,workspace:N.workspace,workspaceContext:Sr(N.workspace),menuKeyPrefix:`workspace:${N.workspace.id}`,showWorkspaceName:!1,selectionMode:xn===N.workspace.id,favoriteEnabled:!0})),ne.length>un(N.workspace.id)?s.jsx("button",{type:"button",className:"workbench-subsession-expand ghost-button",onClick:()=>xa(N.workspace.id,ne.length),children:a("shell.sessionExpandMore")}):null]}),N.childWorktrees.length>0?s.jsx("div",{className:"workbench-session-list workbench-worktree-child-list",children:N.childWorktrees.map(Fe=>ko(Fe))}):null,bi(N.workspace,N.archivedSessions)]})]},N.workspace.id)})]})]})]}),s.jsx("div",{className:"workbench-nav-footer minimal",children:s.jsxs("div",{className:"workbench-nav-footer-actions",children:[s.jsxs("button",{className:"settings-entry-button workbench-nav-settings-button",type:"button",onClick:_,title:Me?`${a("settings.title")} · ${Y}`:a("settings.title"),children:[s.jsx(L8,{}),s.jsx("span",{className:"settings-entry-label",children:a("settings.title")}),Me?s.jsx("span",{className:"workbench-nav-settings-host-badge",title:Y,children:Y}):null]}),s.jsx(l3,{onOpenSoftwareUpdate:()=>We("/settings/software-update")})]})}),s.jsx(ln,{open:$e,title:a("shell.manageWorkspaceTitle"),className:"workbench-manage-workspaces-modal",description:a("shell.manageWorkspaceDescription"),headerActions:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"secondary-button workbench-manage-modal-action",onClick:En,children:a("shell.manageWorkspaceImportAction")}),s.jsx("button",{type:"button",className:"secondary-button workbench-manage-modal-action",onClick:dr,children:a("shell.manageWorkspaceCloneAction")})]}),onClose:()=>{et||Ve(!1)},children:e.length>0?s.jsx("div",{className:"workbench-manage-list",children:e.map(N=>ki(N.workspace,N.visibleSessions.length+N.archivedSessions.length,N.childWorktrees,!1))}):s.jsx("p",{className:"workbench-section-empty",children:a("shell.manageWorkspaceEmpty")})}),s.jsxs(ln,{open:Cn!==null,title:a("shell.deleteSessionConfirmTitle"),description:a("shell.deleteSessionConfirmDescription"),onClose:()=>{is||Bt(null)},children:[s.jsx("p",{className:"workbench-section-empty",children:Cn?Cn.session.title:""}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:!!is,onClick:()=>Bt(null),children:a("common.cancel")}),s.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!is,onClick:()=>{kd()},children:is?a("common.loading"):a("shell.deleteSessionAction")})]})]}),s.jsxs(ln,{open:fn!==null,title:a("shell.batchDeleteConfirmTitle"),description:a("shell.batchDeleteConfirmDescription",{count:`${(fn==null?void 0:fn.sessions.length)??0}`}),onClose:()=>{O||mt(null)},children:[s.jsx("p",{className:"workbench-section-empty",children:fn?a("shell.batchDeleteSelectionSummary",{count:`${fn.sessions.length}`}):""}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:O,onClick:()=>mt(null),children:a("common.cancel")}),s.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:O,onClick:()=>{vr()},children:O?a("shell.batchDeleting"):a("shell.batchDeleteAction")})]})]}),s.jsxs(ln,{open:_e!==null,title:a("shell.manageWorkspaceRemoveConfirmTitle"),description:a("shell.manageWorkspaceRemoveConfirmDescription"),onClose:()=>{et||nt(null)},children:[s.jsx("p",{className:"workbench-section-empty",children:_e?a("shell.manageWorkspaceRemoveConfirmTarget",{name:_e.name}):""}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:!!et,onClick:()=>nt(null),children:a("common.cancel")}),s.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!et,onClick:()=>{gi()},children:et?a("shell.manageWorkspaceRemoving"):a("shell.manageWorkspaceRemoveConfirmAction")})]})]}),s.jsx(e3,{open:ge,onClose:()=>Oe(!1),onCloned:$r}),s.jsx(kC,{open:je,onClose:()=>Q(!1),onImported:kr}),s.jsx(c3,{open:It!==null,source:It,onClose:()=>$t(null),onCreated:async N=>{N.members.forEach(me=>{y(me.session)}),LT(N.group.id),await b();const ne=N.members.find(me=>me.session.sessionId===N.group.anchorSessionId)??N.members[0]??null;ne&&We(Yr(DT(ne.session,ne.sessionIsolatedWorkspace),ne.session.sessionId)),$t(null),we({title:a("shell.parallelCreateSucceeded"),tone:"success"})}}),s.jsx(ln,{open:zt!==null,title:a("shell.createSessionModalTitle"),className:"workbench-create-session-modal",description:zt?`${a("shell.createSessionTarget")} · ${zt.name}`:a("shell.createSessionModalDescription"),headerActions:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"primary-button create-session-parallel-trigger",disabled:vt||!!jt||!zt,onClick:()=>{zt&&ni(zt)},children:a("shell.parallelCreateAction")}),s.jsx("button",{type:"button",className:"primary-button create-session-worktree-trigger",disabled:vt||!!jt,onClick:()=>St(!0),children:a("shell.createWorktreeAction")})]}),onClose:()=>rt(null),children:s.jsxs("section",{className:"create-session-modal-section",children:[s.jsx("div",{className:"create-session-modal-section-header",children:s.jsx("strong",{children:a("shell.createSessionProviderLabel")})}),s.jsx(yC,{disabled:!!jt||vt,workspaceId:(zt==null?void 0:zt.id)??null,pendingProvider:jt===(zt==null?void 0:zt.id)?bt??null:null,onSelect:N=>{zt&&ka(zt.id,N)}})]})}),s.jsx(ln,{open:zt!==null&&kt,title:a("shell.createWorktreeAction"),className:"workbench-create-worktree-modal",headerActions:s.jsx("button",{type:"button",className:lt?"workbench-modal-help-button active":"workbench-modal-help-button","aria-label":a("shell.createWorktreeHelpAction"),title:a("shell.createWorktreeHelpAction"),"aria-pressed":lt,onClick:()=>wt(N=>!N),children:s.jsx(H8,{})}),description:zt?`${a("shell.createWorktreeSectionDescription")} ${a("shell.createSessionTarget")} · ${zt.name}`:a("shell.createWorktreeSectionDescription"),onClose:er,children:s.jsxs("form",{className:"create-session-worktree-form",onSubmit:wo,children:[lt?s.jsxs("section",{className:"create-session-worktree-help-card","aria-label":a("shell.createWorktreeHelpTitle"),children:[s.jsx("strong",{children:a("shell.createWorktreeHelpTitle")}),s.jsxs("div",{className:"create-session-worktree-help-grid",children:[s.jsxs("article",{children:[s.jsx("h3",{children:a("shell.createWorktreeHelpBranchTitle")}),s.jsx("p",{children:a("shell.createWorktreeHelpBranchBody")})]}),s.jsxs("article",{children:[s.jsx("h3",{children:a("shell.createWorktreeHelpDisplayNameTitle")}),s.jsx("p",{children:a("shell.createWorktreeHelpDisplayNameBody")})]}),s.jsxs("article",{children:[s.jsx("h3",{children:a("shell.createWorktreeHelpBaseRefTitle")}),s.jsx("p",{children:a("shell.createWorktreeHelpBaseRefBody")})]})]})]}):null,s.jsxs("label",{className:"create-session-worktree-field",children:[s.jsx("span",{children:a("shell.createWorktreeBranchLabel")}),s.jsx("input",{className:"settings-text-input",value:J,placeholder:a("shell.createWorktreeBranchPlaceholder"),onChange:N=>{const ne=N.target.value;D3(ne)&&Ue(ne)}})]}),s.jsxs("label",{className:"create-session-worktree-field",children:[s.jsx("span",{children:a("shell.createWorktreeDisplayNameLabel")}),s.jsx("input",{className:"settings-text-input",value:ze,placeholder:a("shell.createWorktreeDisplayNamePlaceholder"),onChange:N=>st(N.target.value)})]}),s.jsxs("label",{className:"create-session-worktree-field",children:[s.jsx("span",{children:a("shell.createWorktreeBaseRefLabel")}),s.jsx("div",{className:"create-session-worktree-combobox",ref:ms,onBlurCapture:N=>{var me,Le;const ne=N.relatedTarget;ne instanceof Node&&((me=ms.current)!=null&&me.contains(ne)||(Le=ps.current)!=null&&Le.contains(ne))||(Ke(!1),He(-1))},children:s.jsxs("div",{className:"create-session-worktree-combobox-input-wrap",children:[s.jsx("input",{className:"settings-text-input create-session-worktree-combobox-input",role:"combobox","aria-autocomplete":"list","aria-expanded":Se,"aria-controls":Qs,value:q,placeholder:a("shell.createWorktreeBaseRefPlaceholder"),onFocus:()=>{Ke(!0),He(Tn.length>0?0:-1)},onChange:N=>{re(N.target.value),Ke(!0),He(Tn.length>0?0:-1)},onKeyDown:N=>{if(N.key==="ArrowDown"){if(N.preventDefault(),!Se){Ke(!0);return}Tn.length>0&&He(ne=>ne>=Tn.length-1?0:ne+1);return}if(N.key==="ArrowUp"){if(N.preventDefault(),!Se){Ke(!0);return}Tn.length>0&&He(ne=>ne<=0?Tn.length-1:ne-1);return}if(N.key==="Enter"&&Se&&De>=0){N.preventDefault();const ne=Tn[De];ne&&(re(ne.value),Ke(!1),He(-1));return}N.key==="Escape"&&Ke(!1)}}),s.jsx("button",{type:"button",className:"create-session-worktree-combobox-toggle","aria-label":a("shell.createWorktreeBaseRefToggle"),"aria-expanded":Se,onClick:()=>{Ke(N=>!N),He(!Se&&Tn.length>0?0:-1)},children:s.jsx(Ka,{expanded:Se})})]})}),s.jsx("span",{className:"create-session-worktree-field-hint",children:it?a("shell.createWorktreeBaseRefLoading"):Ht||a("shell.createWorktreeBaseRefHint",{localCount:ue.localBranches.length,remoteCount:ue.remoteBranches.length,tagCount:ue.tags.length})})]}),Se&&Nt&&typeof document<"u"?Bs.createPortal(s.jsxs("div",{className:"create-session-worktree-combobox-floating-layer",children:[s.jsx("div",{className:"create-session-worktree-combobox-floating-backdrop",style:{"--create-worktree-combobox-top":`${Nt.top}px`,"--create-worktree-combobox-left":`${Nt.left}px`,"--create-worktree-combobox-width":`${Nt.width}px`,"--create-worktree-combobox-height":`${ft??0}px`}}),s.jsx("div",{ref:ps,className:"create-session-worktree-combobox-popover floating",style:{"--create-worktree-combobox-top":`${Nt.top}px`,"--create-worktree-combobox-left":`${Nt.left}px`,"--create-worktree-combobox-width":`${Nt.width}px`},children:it?s.jsx("p",{className:"create-session-worktree-combobox-empty",children:a("shell.createWorktreeBaseRefLoading")}):Ht?s.jsx("p",{className:"create-session-worktree-combobox-empty",children:Ht}):Os.length>0?s.jsx("div",{id:Qs,className:"create-session-worktree-combobox-list",role:"listbox",children:Os.map(N=>s.jsxs("section",{className:"create-session-worktree-combobox-group","aria-label":N.label,children:[s.jsx("header",{className:"create-session-worktree-combobox-group-title",children:N.label}),s.jsx("div",{className:"create-session-worktree-combobox-group-options",children:N.items.map(ne=>{const me=Tn.findIndex(Lt=>Lt.value===ne.value),Le=q===ne.value,Fe=De===me;return s.jsxs("button",{type:"button",role:"option",className:"create-session-worktree-combobox-option","aria-selected":Le,"data-highlighted":Fe,onMouseDown:Lt=>Lt.preventDefault(),onMouseEnter:()=>He(me),onClick:()=>{re(ne.value),Ke(!1),He(-1)},children:[s.jsx("span",{className:"create-session-worktree-combobox-option-label",children:ne.value}),s.jsxs("span",{className:"create-session-worktree-combobox-option-badges",children:[ne.current?s.jsx("span",{className:"create-session-worktree-combobox-badge",children:a("shell.createWorktreeBaseRefCurrentBadge")}):null,ne.recommended?s.jsx("span",{className:"create-session-worktree-combobox-badge recommended",children:a("shell.createWorktreeBaseRefRecommendedBadge")}):null]})]},`${N.key}:${ne.value}`)})})]},N.key))}):s.jsx("p",{className:"create-session-worktree-combobox-empty",children:a("shell.createWorktreeBaseRefEmpty")})})]}),document.body):null,s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:vt,onClick:er,children:a("common.cancel")}),s.jsx("button",{type:"submit",className:"primary-button",disabled:vt,children:vt?a("shell.createWorktreeSubmitting"):a("shell.createWorktreeSubmit")})]})]})}),s.jsxs(ln,{open:Pn!==null,title:a("shell.archiveModalTitle"),description:Pn?`${Pn.workspace.name} · ${a("shell.archiveModalDescription")}`:a("shell.archiveModalDescription"),headerActions:Sn.length>0?s.jsx("button",{type:"button",className:"secondary-button","aria-pressed":gn,onClick:Hs,children:a("shell.archiveSearchAction")}):void 0,onClose:()=>qt(null),children:[gn?s.jsxs("div",{className:"workbench-archive-search-panel",children:[s.jsx(Ot,{label:a("shell.archiveSearchLabel"),htmlFor:ir,children:s.jsx("input",{id:ir,type:"text",value:bn,placeholder:a("shell.archiveSearchPlaceholder"),autoFocus:!0,onChange:N=>Mn(N.target.value)})}),js?s.jsx("p",{className:"workbench-archive-search-status",children:a("shell.archiveSearchSummaryLoading")}):null,Ge?s.jsx("p",{className:"workbench-archive-search-status status-text","data-tone":"warning",children:Ge}):null]}):null,Pn&&Cs.length>0?s.jsx(Wi,{className:"workbench-archive-list","data-workspace-tone":(on==null?void 0:on.tone)??"root",style:Gr(on),children:Cs.map(N=>{var Le;const ne=rd(N.title,a("common.unknown")),me=((Le=ei[N.sessionId])==null?void 0:Le.trim())??"";return s.jsx(rs,{className:"workbench-archive-item","data-workspace-tone":(on==null?void 0:on.tone)??"root",style:Gr(on),trailing:s.jsx("button",{type:"button",className:"secondary-button",onClick:()=>gs(N.sessionId),children:a("shell.unarchiveAction")}),children:s.jsxs("div",{className:"workbench-archive-item-main",children:[s.jsx("strong",{title:ne.fullTitle,children:ne.displayTitle}),s.jsxs("p",{children:[PN(N,Pn.workspace,!1)," ·"," ",md(N.provider)]}),gn&&me?s.jsx("p",{className:"workbench-archive-item-summary",children:me}):null]})},N.sessionId)})}):s.jsx($i,{title:Sn.length>0&&bn.trim().length>0?a("shell.archiveSearchEmpty"):a("shell.archiveEmpty"),compact:!0,className:"workbench-section-empty"})]}),s.jsx(ln,{open:ts!==null,title:a("shell.renameModalTitle"),description:a("shell.renameModalDescription"),onClose:()=>{Nn||(Dn(null),Rn(""))},children:s.jsxs("form",{className:"workbench-rename-form",onSubmit:wd,children:[s.jsxs("label",{className:"workbench-modal-field",children:[s.jsx("span",{children:a("shell.renameInputLabel")}),s.jsx("input",{type:"text",value:Kn,placeholder:a("shell.renameInputPlaceholder"),maxLength:120,autoFocus:!0,onChange:N=>Rn(N.target.value)})]}),s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:!!Nn,onClick:()=>{Dn(null),Rn("")},children:a("common.cancel")}),s.jsx("button",{type:"submit",className:"primary-button",disabled:!Kn.trim()||Nn===(ts==null?void 0:ts.session.sessionId),children:Nn===(ts==null?void 0:ts.session.sessionId)?a("shell.renamingSession"):a("common.save")})]})]})}),At?s.jsx("div",{ref:ws,className:"session-export-print-root","aria-hidden":"true",children:s.jsxs("div",{className:"session-export-print-shell",style:At.shellWidthPx?{width:`${At.shellWidthPx}px`,maxWidth:"100%"}:void 0,children:[s.jsxs("header",{className:"session-export-print-header",children:[s.jsx("h1",{children:At.session.title||a("conversation.titleFallback")}),s.jsx("p",{children:a("conversation.exportAction")})]}),s.jsx($S,{sessionId:At.session.sessionId,items:At.items,provider:At.session.provider})]})}):null]})}function Mk({panelReady:e,activeTab:t,fileRevealRequest:n,onTabChange:r,onToggleCollapse:i,currentSessionId:o,activeWorkspaceId:l,navigationGroups:c,workspaceContext:u,worktreeMeta:f,worktreeMergeState:h,onRefreshWorktreeMergePreview:m,onApplyWorktreeMerge:g,onCleanupWorktree:p}){var xe;const b=l??((xe=c[0])==null?void 0:xe.workspace.id)??null,y=(l==null?void 0:l.trim())||null,x=d.useMemo(()=>LN(c),[c]),[k,C]=d.useState(()=>y),j=Hn(),H=Lm(j),{showToast:_}=Vn(),T=np(),P=d.useRef(null),z=d.useRef(null),L=j.isDesktop&&j.bridge.supported,R=L&&!!l,K=L&&!!b,E=L&&!!b,D=typeof globalThis<"u"&&"PointerEvent"in globalThis,te=y??k,V=te&&te===y?o:null,ee=te&&te===y?n:null;d.useEffect(()=>{if(y){C(le=>le===y?le:y);return}x.size!==0&&C(le=>le&&x.has(le)?le:null)},[x,y]);const U=d.useCallback(async(le,M,de)=>{if(le==="files"){const ye=await eI(j,{workspaceId:M,sessionId:de,focusOwner:"file-context-panel"});ye.ok||_({title:ye.detail??a("conversation.filePanelOpenExternalFailed"),tone:"error"});return}if(le==="git"){const ye=await tI(j,{workspaceId:M,focusOwner:"git-sidebar"});ye.ok||_({title:ye.detail??a("git.openExternalFailed"),tone:"error"});return}const Ne=await nI(j,{workspaceId:M,focusOwner:"terminal-manager-panel"});Ne.ok||_({title:Ne.detail??a("terminalManager.openExternalFailed"),tone:"error"})},[j,_]),he=d.useCallback((le,M)=>{if(le.button!==0||!L)return;const de=M==="files"?l:M==="git"||M==="terminals"?b:null;if(!de)return;const Ne=M==="files"?o:null;P.current={tab:M,startX:le.clientX,startY:le.clientY,workspaceId:de,sessionId:Ne,detached:!1,preview:null};const ye=ke=>{var Y;const we=P.current;if(!we)return;const se=Math.abs(ke.clientX-we.startX),ce=Math.abs(ke.clientY-we.startY);!we.detached&&Math.max(se,ce)<fk||(we.detached||(we.detached=!0,z.current=we.tab,we.preview=xg({title:we.tab==="files"?a("shell.filesEntry"):we.tab==="git"?a("shell.gitEntry"):a("shell.terminalManagerEntry"),x:ke.clientX,y:ke.clientY})),(Y=we.preview)==null||Y.updatePosition(ke.clientX,ke.clientY))},Be=ke=>{var se;const we=(se=P.current)==null?void 0:se.preview;ke&&(we==null||we.cancel()),window.removeEventListener("mousemove",ye),window.removeEventListener("mouseup",We),window.removeEventListener("blur",Ce),P.current=null},We=async()=>{var we;const ke=P.current;Be(!1),ke!=null&&ke.detached&&(await((we=ke.preview)==null?void 0:we.complete()),await U(ke.tab,ke.workspaceId,ke.sessionId))},Ce=()=>{Be(!0)};window.addEventListener("mousemove",ye),window.addEventListener("mouseup",We),window.addEventListener("blur",Ce)},[l,L,o,b,U]),X=d.useCallback((le,M)=>{if(le.button!==0||!L)return;const de=M==="files"?l:M==="git"||M==="terminals"?b:null;if(!de)return;const Ne=le.currentTarget,ye=le.pointerId;Ne.setPointerCapture(ye);const Be=M==="files"?o:null;P.current={tab:M,startX:le.clientX,startY:le.clientY,workspaceId:de,sessionId:Be,detached:!1,preview:null};const We=ce=>{var fe;if(ce.pointerId!==ye)return;const Y=P.current;if(!Y)return;const Te=Math.abs(ce.clientX-Y.startX),pe=Math.abs(ce.clientY-Y.startY);!Y.detached&&Math.max(Te,pe)<fk||(Y.detached||(Y.detached=!0,z.current=Y.tab,Y.preview=xg({title:Y.tab==="files"?a("shell.filesEntry"):Y.tab==="git"?a("shell.gitEntry"):a("shell.terminalManagerEntry"),x:ce.clientX,y:ce.clientY})),(fe=Y.preview)==null||fe.updatePosition(ce.clientX,ce.clientY))},Ce=ce=>{var Te;const Y=(Te=P.current)==null?void 0:Te.preview;ce&&(Y==null||Y.cancel()),Ne.removeEventListener("pointermove",We),Ne.removeEventListener("pointerup",ke),Ne.removeEventListener("pointercancel",we),Ne.removeEventListener("lostpointercapture",we),window.removeEventListener("blur",se),P.current=null,Ne.hasPointerCapture(ye)&&Ne.releasePointerCapture(ye)},ke=async ce=>{var Te;if(ce.pointerId!==ye)return;const Y=P.current;Ce(!1),Y!=null&&Y.detached&&(await((Te=Y.preview)==null?void 0:Te.complete()),await U(Y.tab,Y.workspaceId,Y.sessionId))},we=ce=>{ce.pointerId===ye&&Ce(!0)},se=()=>{Ce(!0)};Ne.addEventListener("pointermove",We),Ne.addEventListener("pointerup",ke),Ne.addEventListener("pointercancel",we),Ne.addEventListener("lostpointercapture",we),window.addEventListener("blur",se)},[l,L,o,b,U]),I=d.useCallback(le=>{if(z.current===le){z.current=null;return}r(le)},[r]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"workbench-auxiliary-header","data-workspace-tone":(u==null?void 0:u.tone)??"root",style:Gr(u),"data-window-drag-handle":"workbench-auxiliary-header","data-tauri-drag-region":H,children:[i?s.jsx("button",{type:"button",className:"workbench-nav-toolbar-button","aria-label":a("shell.hideInfoSidebar"),title:a("shell.hideInfoSidebar"),onClick:i,children:s.jsx(XN,{})}):null,s.jsxs("div",{className:"workbench-info-tabs",role:"tablist","aria-label":a("shell.infoTabsLabel"),"data-tauri-drag-region":H,children:[s.jsx("button",{className:t==="files"?"workbench-info-tab active":"workbench-info-tab",type:"button",role:"tab","aria-selected":t==="files",title:R?"拖拽标签到独立窗口":void 0,onPointerDown:le=>X(le,"files"),onMouseDown:D?void 0:le=>he(le,"files"),onClick:()=>I("files"),children:a("shell.filesEntry")}),s.jsx("button",{className:t==="git"?"workbench-info-tab active":"workbench-info-tab",type:"button",role:"tab","aria-selected":t==="git",title:K?"拖拽标签到独立窗口":void 0,onPointerDown:le=>X(le,"git"),onMouseDown:D?void 0:le=>he(le,"git"),onClick:()=>I("git"),children:a("shell.gitEntry")}),s.jsx("button",{className:t==="terminals"?"workbench-info-tab active":"workbench-info-tab",type:"button",role:"tab","aria-selected":t==="terminals",title:E?"拖拽标签到独立窗口":void 0,onPointerDown:le=>X(le,"terminals"),onMouseDown:D?void 0:le=>he(le,"terminals"),onClick:()=>I("terminals"),children:a("shell.terminalManagerEntry")})]})]}),s.jsxs("div",{ref:T,className:"workbench-auxiliary-body","data-scrollbar-autohide":"true",children:[e?null:s.jsx(Hc,{}),e&&t==="git"&&f?s.jsx(Z8,{meta:f,state:h,onRefresh:()=>m(f.workspaceId,!0),onApply:()=>g(f.workspaceId),onCleanup:()=>p(f)}):null,e&&t==="files"?te?s.jsx(d.Suspense,{fallback:s.jsx(Hc,{}),children:s.jsx(V3,{sessionId:V,workspaceId:te,externalRevealRequest:ee})}):s.jsx("section",{className:"workbench-empty-state minimal",children:s.jsx("p",{children:a("shell.filesPanelEmpty")})}):null,e&&t==="git"?b?s.jsx(d.Suspense,{fallback:s.jsx(Hc,{}),children:s.jsx(K3,{workspaceId:b})}):s.jsx("section",{className:"workbench-empty-state minimal",children:s.jsx("p",{children:a("shell.gitPanelEmpty")})}):null,e&&t==="terminals"?s.jsx(d.Suspense,{fallback:s.jsx(Hc,{}),children:s.jsx(G3,{currentWorkspaceId:l,navigationGroups:c})}):null]})]})}function Z8({meta:e,state:t,onRefresh:n,onApply:r,onCleanup:i}){const[o,l]=d.useState(!1),c=(t==null?void 0:t.preview)??null,u=(t==null?void 0:t.loading)??!1,f=(t==null?void 0:t.applying)??!1,h=(t==null?void 0:t.cleaning)??!1,m=c!==null,g=(c==null?void 0:c.alreadyMerged)===!0,p=new Set((c==null?void 0:c.blockers.map(E=>E.code))??[]),b=p.size>0||!!(t!=null&&t.error),y=g&&!b,x=(c==null?void 0:c.canMerge)===!0&&!u&&!f&&!h&&!y,k=y&&!u&&!f&&!h&&!p.has("SOURCE_DIRTY")&&!p.has("HAS_ACTIVE_CHILDREN"),C=u||f||h?"loading":b?"blocked":y?"merged":c!=null&&c.canMerge?"ready":m?"blocked":"idle",j=(c==null?void 0:c.targetWorkspace.name)??a("common.unknown"),H=(c==null?void 0:c.sourceBranchName)??e.branchName,_=(c==null?void 0:c.targetBranchName)??e.baseRef??a("common.unknown"),T=tV({t:a,hasPreview:m,showMergedState:y,isMerged:g,canMerge:(c==null?void 0:c.canMerge)===!0,ahead:(c==null?void 0:c.ahead)??0,blockerCodeSet:p}),P=u?a("shell.worktreeMergePreviewLoading"):f?a("shell.worktreeMergeApplying"):h?a("shell.worktreeCleanupRunning"):y?a("shell.worktreeMergeAlreadyMerged"):c!=null&&c.canMerge?a("shell.worktreeMergeReady"):m?a("shell.worktreeMergeBlocked"):a("shell.worktreeMergePreviewIdle"),z=[a("shell.worktreeMergeCurrentBranch",{branch:H}),a("shell.worktreeMergeParentBranch",{branch:_}),a("shell.worktreeMergeTargetWorkspace",{name:j}),c?a("shell.worktreeMergeAheadBehind",{ahead:c.ahead,behind:c.behind}):a("shell.worktreeMergeAheadBehindPending"),c!=null&&c.mergeBaseCommit?a("shell.worktreeMergeBaseCommit",{commit:w8(c.mergeBaseCommit)}):null].filter(E=>!!E),L=`worktree-merge-panel-details-${e.workspaceId}`,R=o?a("shell.worktreeMergeCollapseDetails"):a("shell.worktreeMergeExpandDetails"),K=eV({t:a,loading:u,applying:f,cleaning:h,hasPreview:m,canMerge:(c==null?void 0:c.canMerge)===!0,showMergedState:y,blockerCodeSet:p});return d.useEffect(()=>{l(!1)},[e.workspaceId]),s.jsxs("section",{className:"worktree-merge-panel","data-state":C,children:[s.jsxs("button",{type:"button",className:"worktree-merge-panel-summary","aria-label":R,"aria-expanded":o,"aria-controls":L,onClick:()=>{l(E=>!E)},children:[s.jsx("span",{className:"worktree-merge-panel-summary-label",children:a("shell.worktreeMergePanelLabel")}),s.jsx("span",{className:"worktree-merge-panel-summary-main",children:s.jsx("span",{className:"worktree-merge-panel-summary-tags",children:K.map(E=>s.jsx("span",{className:"worktree-merge-panel-summary-tag","data-state":C,children:E},E))})}),s.jsx("span",{className:"worktree-merge-panel-summary-toggle",children:R})]}),o?s.jsxs("div",{id:L,className:"worktree-merge-panel-details",children:[s.jsx("div",{className:"worktree-merge-panel-detail-head",children:s.jsx("span",{className:"worktree-merge-panel-status","data-state":C,children:P})}),s.jsx("div",{className:"worktree-merge-panel-meta",children:z.map(E=>s.jsx("span",{children:E},E))}),m?s.jsx("div",{className:"worktree-merge-panel-checklist","aria-label":a("shell.worktreeMergeChecklistTitle"),children:T.map(E=>s.jsxs("div",{className:"worktree-merge-panel-checklist-item","data-state":E.state,children:[s.jsx("span",{className:"worktree-merge-panel-checklist-marker","aria-hidden":"true",children:E.state==="done"?"✓":E.state==="blocked"?"!":"·"}),s.jsxs("span",{className:"worktree-merge-panel-checklist-copy",children:[s.jsx("strong",{children:E.label}),E.detail?s.jsx("span",{children:E.detail}):null]})]},E.key))}):null,t!=null&&t.error?s.jsx("p",{className:"worktree-merge-panel-error status-text","data-tone":"error",children:t.error}):null,c!=null&&c.conflictPaths.length?s.jsxs("div",{className:"worktree-merge-panel-conflicts",children:[s.jsx("span",{className:"worktree-merge-panel-conflicts-label",children:a("shell.worktreeMergeConflictLabel")}),s.jsx("div",{className:"worktree-merge-panel-conflict-list",children:c.conflictPaths.map(E=>s.jsx("code",{children:E},E))})]}):null,s.jsxs("div",{className:"worktree-merge-panel-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:u||f||h,onClick:n,children:m?a("shell.worktreeMergePreviewRefresh"):a("shell.worktreeMergePreviewAction")}),s.jsx("button",{type:"button",className:"primary-button",disabled:!x,onClick:r,children:f?a("shell.worktreeMergeApplying"):a("shell.worktreeMergeApplyAction")}),s.jsx("button",{type:"button",className:"secondary-button worktree-merge-panel-cleanup-button",disabled:!k,onClick:i,children:h?a("shell.worktreeCleanupRunning"):a("shell.worktreeCleanupAction")})]})]}):null]})}function eV(e){const{t,loading:n,applying:r,cleaning:i,hasPreview:o,canMerge:l,showMergedState:c,blockerCodeSet:u}=e;if(n)return[t("shell.worktreeMergeCompactChecking")];if(r)return[t("shell.worktreeMergeCompactMerging")];if(i)return[t("shell.worktreeMergeCompactCleaning")];const f=[];return u.has("SOURCE_NOT_ACTIVE")&&f.push(t("shell.worktreeMergeCompactInactive")),u.has("SOURCE_DIRTY")&&f.push(t("shell.worktreeMergeCompactDirty")),u.has("TARGET_DIRTY")&&f.push(t("shell.worktreeMergeCompactTargetDirty")),u.has("HAS_CONFLICTS")&&f.push(t("shell.worktreeMergeCompactConflict")),u.has("HAS_ACTIVE_CHILDREN")&&f.push(t("shell.worktreeMergeCompactChildren")),f.length>0?f:l?[t("shell.worktreeMergeCompactReady")]:c?[t("shell.worktreeMergeCompactMerged")]:o?u.has("NO_COMMITS_TO_MERGE")?[t("shell.worktreeMergeCompactNoCommits")]:[t("shell.worktreeMergeCompactBlocked")]:[t("shell.worktreeMergeCompactPending")]}function tV(e){const{t,hasPreview:n,showMergedState:r,isMerged:i,canMerge:o,ahead:l,blockerCodeSet:c}=e,u=c.has("SOURCE_NOT_ACTIVE"),f=c.has("SOURCE_DIRTY"),h=c.has("TARGET_DIRTY"),m=c.has("HAS_ACTIVE_CHILDREN"),g=c.has("HAS_CONFLICTS"),p=n&&!i&&(c.has("NO_COMMITS_TO_MERGE")||l<=0),b=r?{key:"merge-result",label:t("shell.worktreeMergeChecklistResultMerged"),detail:t("shell.worktreeMergeMergedHint"),state:"done"}:o?{key:"merge-result",label:t("shell.worktreeMergeChecklistResultReady"),detail:t("shell.worktreeMergeChecklistResultReadyDetail"),state:"done"}:n?{key:"merge-result",label:t("shell.worktreeMergeChecklistResultBlocked"),detail:t("shell.worktreeMergeChecklistResultBlockedDetail"),state:"blocked"}:{key:"merge-result",label:t("shell.worktreeMergeChecklistResultPending"),detail:null,state:"pending"};return[{key:"source-state",label:t("shell.worktreeMergeChecklistSourceState"),detail:n&&u?t("shell.worktreeMergeChecklistSourceStateBlocked"):null,state:n?u?"blocked":"done":"pending"},{key:"clean-source",label:t("shell.worktreeMergeChecklistSourceClean"),detail:n&&f?t("shell.worktreeMergeChecklistSourceCleanBlocked"):null,state:n?f?"blocked":"done":"pending"},{key:"clean-target",label:t("shell.worktreeMergeChecklistTargetClean"),detail:n&&h?t("shell.worktreeMergeChecklistTargetCleanBlocked"):null,state:n?h?"blocked":"done":"pending"},{key:"children",label:t("shell.worktreeMergeChecklistChildren"),detail:n&&m?t("shell.worktreeMergeChecklistChildrenBlocked"):null,state:n?m?"blocked":"done":"pending"},{key:"commits",label:t("shell.worktreeMergeChecklistCommits"),detail:p?t(i?"shell.worktreeMergeMergedDirtyHint":"shell.worktreeMergeChecklistCommitsBlocked"):null,state:p?i?"done":"blocked":n?"done":"pending"},{key:"conflicts",label:t("shell.worktreeMergeChecklistConflicts"),detail:g?t("shell.worktreeMergeChecklistConflictsBlocked"):null,state:g?"blocked":n?"done":"pending"},b]}function jK({shellMode:e="desktop"}){var Fe,Lt,at,dn,qn,Fn,Ns,Cr,jr,wi,ii,hr,In,Gl,wn,vi,Yl;const t=Wu(),n=Nl(),r=Hn(),{showToast:i}=Vn(),o=Ql(S=>S.sessionDisplaySortMode),l=Ql(S=>S.notificationPreferences.notifyOnPermissionRequest),c=Ql(S=>S.notificationPreferences.notifyOnSessionCompleted),u=Ql(S=>S.notificationPreferences.notifyOnSessionFailed),f=d.useRef(gB(pC)),h=d.useRef(0),m=d.useRef((((Lt=(Fe=f.current)==null?void 0:Fe.items)==null?void 0:Lt.length)??0)>0),g=d.useRef(new Map),p=d.useRef(!1),b=d.useRef(null),y=d.useRef(0),x=d.useRef(null),k=d.useRef(null),C=d.useRef(new Set),j=d.useRef(new Set),H=d.useRef(new Set),_=d.useRef(new Set),T=d.useRef(null),P=d.useRef(null),z=d.useRef(null),L=d.useRef(null),R=d.useRef(null),K=d.useRef(null),E=d.useRef(null),D=d.useRef(null),te=d.useRef(0),V=d.useRef(0),ee=d.useRef(i),U=d.useRef(r.bridge),he=d.useRef(null),X=d.useRef(0),I=d.useRef(0),xe=d.useRef(null),le=d.useRef(null),M=d.useRef(null),de=d.useRef(!1),Ne=d.useRef(!1),ye=d.useRef(!1),Be=d.useRef(new Map),We=d.useRef(!1),Ce=d.useRef(new Map),ke=d.useRef(""),we=d.useRef([]),se=d.useRef(o),ce=d.useRef(null),[Y,Te]=d.useState(()=>jy(f.current,o)),pe=d.useRef(Y),[fe,W]=d.useState(()=>{var S,B;return(((B=(S=f.current)==null?void 0:S.items)==null?void 0:B.length)??0)===0}),[Me,je]=d.useState(null),[Q,ge]=d.useState(()=>$c(kk(tk,p3),ak,lk)),[Oe,$e]=d.useState(()=>$c(kk(nk,g3),ok,ck)),[Ve,G]=d.useState(()=>wk(sk,!1)),[ve,_e]=d.useState(()=>wk(rk,!1)),[nt,et]=d.useState(!0),[ot,jt]=d.useState(null),[Ft,bt]=d.useState(null),[_t,xt]=d.useState(()=>jk(f.current)),[rt,It]=d.useState(()=>vk(Gf)),[$t,pt]=d.useState(!1),[Ie,kt]=d.useState("files"),[St,vt]=d.useState(null),[Ct,J]=d.useState(!1),[Ue,ze]=d.useState(!1),[st,q]=d.useState(null),[re,ue]=d.useState({}),[Re,Se]=d.useState(!1),[Ke,De]=d.useState("sessions"),[He,lt]=d.useState(""),[wt,it]=d.useState(""),[Ze,Ht]=d.useState(!1),[gt,Nt]=d.useState(null),[dt,ft]=d.useState([]),[en,cn]=d.useState(null),[qt,Cn]=d.useState({}),Bt=jw(r),is=d.useCallback(S=>{if(Bt)return;const B=he.current;B&&(!lh(r,S.button,S.target)||!Sk(S.clientY,B)||UI({platform:r,button:S.button,target:S.target,clientX:S.clientX,clientY:S.clientY}))},[r,Bt]),Ws=d.useCallback(S=>{if(Bt)return;const B=he.current;B&&(!lh(r,S.button,S.target)||!Sk(S.clientY,B)||r.bridge.setWindowState("toggle-zoom"))},[r,Bt]),[fn,mt]=d.useState({}),[O,Ae]=d.useState(null),[Xe,Qt]=d.useState(!1),[Un,as]=d.useState([]),[tn,sn]=d.useState(()=>new Set),[At,Gt]=d.useState(!1),[Zn,es]=d.useState(!1),[os,ut]=d.useState(0),[Ds,cr]=d.useState(()=>vk(ik)),jn=e==="desktop"&&r.isDesktop&&r.ui.osFamily==="macos"&&r.ui.prefersOverlayTitlebar,{theme:an}=TT();d.useEffect(()=>{ee.current=i},[i]),d.useEffect(()=>{if(typeof document>"u")return;const{documentElement:S,body:B}=document,oe=document.getElementById("root");if(!jn){S.removeAttribute("data-workbench-macos-vibrancy"),B==null||B.removeAttribute("data-workbench-macos-vibrancy");return}const Pe=S.style.background,Ye=(B==null?void 0:B.style.background)??"",Qe=(oe==null?void 0:oe.style.background)??"";return S.setAttribute("data-workbench-macos-vibrancy","true"),B==null||B.setAttribute("data-workbench-macos-vibrancy","true"),S.style.background="transparent",B==null||B.style.setProperty("background","transparent"),oe==null||oe.style.setProperty("background","transparent"),()=>{S.removeAttribute("data-workbench-macos-vibrancy"),B==null||B.removeAttribute("data-workbench-macos-vibrancy"),S.style.background=Pe,B&&(B.style.background=Ye),oe instanceof HTMLElement&&(oe.style.background=Qe)}},[jn]),d.useEffect(()=>()=>{M.current!==null&&window.clearTimeout(M.current)},[]),d.useEffect(()=>{var Ye;if(typeof document>"u")return;const{documentElement:S,body:B}=document;if(!Ft){S.removeAttribute(Ma),B==null||B.removeAttribute(Ma);return}const oe=S.style.cursor,Pe=(B==null?void 0:B.style.cursor)??"";return S.setAttribute(Ma,Ft),B==null||B.setAttribute(Ma,Ft),S.style.cursor="col-resize",B==null||B.style.setProperty("cursor","col-resize"),(Ye=window.getSelection())==null||Ye.removeAllRanges(),()=>{S.removeAttribute(Ma),B==null||B.removeAttribute(Ma),S.style.cursor=oe,B&&(B.style.cursor=Pe)}},[Ft]),d.useEffect(()=>{se.current=o,Te(S=>v8(S,o))},[o]),d.useEffect(()=>{pe.current=Y},[Y]),d.useEffect(()=>{U.current=r.bridge},[r.bridge]),d.useEffect(()=>{X.current=Q},[Q]),d.useEffect(()=>{I.current=Oe},[Oe]),d.useEffect(()=>()=>{xe.current!==null&&window.cancelAnimationFrame(xe.current)},[]);const hs=d.useCallback(async()=>{const S=te.current+1;te.current=S;try{const B=await Qv();if(S!==te.current)return;if(!B.initialized){as([]),sn(new Set);return}const[oe,Pe,Ye,Qe]=await Promise.all([Zv(),tS(),ep(),PO()]);if(S!==te.current)return;as(M3(oe.overview,Pe.items,Ye.items)),sn(new Set(Qe.items.map(yt=>yt.notificationId)))}catch{if(S!==te.current)return;as([]),sn(new Set)}},[]),ur=d.useCallback(S=>{const B=S.map(oe=>oe.createdAt).sort((oe,Pe)=>Bi(Pe)-Bi(oe))[0]??null;B&&cr(oe=>oe&&Bi(oe)>=Bi(B)?oe:B)},[]);d.useEffect(()=>{Ds&&sa(ik,Ds)},[Ds]),d.useEffect(()=>{hs();const S=window.setInterval(()=>{hs()},y3);return()=>{window.clearInterval(S)}},[hs]),d.useEffect(()=>{Xt("workbench.layout_mounted",{path:t.pathname,search:t.search})},[t.pathname,t.search]),d.useEffect(()=>{var S,B;Xt("workbench.cached_snapshot_loaded",{cached:!!f.current,workspaceCount:((S=f.current)==null?void 0:S.items.length)??0,sessionCount:((B=f.current)==null?void 0:B.items.reduce((oe,Pe)=>oe+Pe.sessions.length,0))??0})},[]);function ts(S){var Pe;if(!S||!Array.isArray(S.items))return;b8(g.current,S);const B=g8(S,g.current);Xt("workbench.apply_snapshot",{workspaceCount:B.items.length,sessionCount:B.items.reduce((Ye,Qe)=>Ye+Qe.sessions.length,0),currentSessionId:((Pe=ul(t.pathname))==null?void 0:Pe.sessionId)??null});const oe=jy(B,se.current);f.current=B,Sc(B),pe.current=oe,Te(oe),xt(jk(B)),je(null)}const Dn=d.useCallback(async()=>{const S=h.current+1;h.current=S,W(B=>B||!m.current),Xt("workbench.refresh_navigation.start",{requestId:S,hasNavigationData:m.current});try{const B=await zT({refresh:!0,awaitDiscovery:!0});if(S!==h.current){Xt("workbench.refresh_navigation.stale",{requestId:S});return}ts(B)}catch(B){if(S!==h.current)return;je(B instanceof Error?B.message:a("shell.navigationLoadFailed")),ee.current({title:B instanceof Error?B.message:a("shell.navigationLoadFailed"),tone:"error"})}finally{Xt("workbench.refresh_navigation.end",{requestId:S,success:S===h.current}),S===h.current&&W(!1)}},[]),Kn=d.useCallback(S=>{Te(B=>{const oe=y8(B,S,se.current);return pe.current=oe,oe})},[]),Rn=d.useCallback(()=>{var S;(S=k.current)==null||S.requestRefresh()},[]),Nn=d.useCallback((S,B)=>{n(Yr(S,B))},[n]),ks=d.useCallback((S,B,oe)=>{var Pe;T.current={workspaceId:S,paths:B,knownRevisionByPath:oe==null?void 0:oe.knownRevisionByPath},(Pe=k.current)==null||Pe.subscribeFileTree(S,B,oe)},[]),xn=d.useCallback((S,B,oe)=>{var Pe;P.current={workspaceId:S,paths:B,knownRevisionByPath:oe==null?void 0:oe.knownRevisionByPath},(Pe=k.current)==null||Pe.requestFileTreeRefresh(S,B,oe)},[]),$s=d.useCallback(S=>(C.current.add(S),()=>{C.current.delete(S)}),[]),Vt=d.useCallback((S,B)=>{var oe;z.current={workspaceId:S,knownRevision:B==null?void 0:B.knownRevision},(oe=k.current)==null||oe.subscribeGit(S,B)},[]),nn=d.useCallback((S,B)=>{var oe;L.current={workspaceId:S,knownRevision:B==null?void 0:B.knownRevision},(oe=k.current)==null||oe.requestGitRefresh(S,B)},[]),ns=d.useCallback(S=>(j.current.add(S),()=>{j.current.delete(S)}),[]),ss=d.useCallback((S,B)=>{var oe;R.current={workspaceId:S,knownRevision:B==null?void 0:B.knownRevision},(oe=k.current)==null||oe.subscribeWorkspaceManagement(S,B)},[]),Ts=d.useCallback((S,B)=>{var oe;K.current={workspaceId:S,knownRevision:B==null?void 0:B.knownRevision},Cn(Pe=>{var Ye;return{...Pe,[S]:{detail:((Ye=Pe[S])==null?void 0:Ye.detail)??null,loading:!0,error:null}}}),(oe=k.current)==null||oe.requestWorkspaceManagementRefresh(S,B)},[]),Xs=d.useCallback(S=>(H.current.add(S),()=>{H.current.delete(S)}),[]),ls=d.useCallback(async(S,B=!1)=>{const oe=S.trim();if(!oe)return;let Pe=!0;if(mt(Ye=>{const Qe=Ye[oe];return!B&&(Qe!=null&&Qe.loading)?(Pe=!1,Ye):{...Ye,[oe]:{preview:(Qe==null?void 0:Qe.preview)??null,loading:!0,applying:(Qe==null?void 0:Qe.applying)??!1,cleaning:(Qe==null?void 0:Qe.cleaning)??!1,error:null}}}),!!Pe)try{const Ye=await m0(oe);mt(Qe=>{var yt,Ut;return{...Qe,[oe]:{preview:Ye,loading:!1,applying:((yt=Qe[oe])==null?void 0:yt.applying)??!1,cleaning:((Ut=Qe[oe])==null?void 0:Ut.cleaning)??!1,error:null}}})}catch(Ye){mt(Qe=>{var yt,Ut,Dt;return{...Qe,[oe]:{preview:((yt=Qe[oe])==null?void 0:yt.preview)??null,loading:!1,applying:((Ut=Qe[oe])==null?void 0:Ut.applying)??!1,cleaning:((Dt=Qe[oe])==null?void 0:Dt.cleaning)??!1,error:Ye instanceof Error?Ye.message:a("shell.worktreeMergePreviewFailed")}}})}},[]),zs=d.useCallback(async S=>{const B=S.trim();if(B){mt(oe=>{var Pe,Ye;return{...oe,[B]:{preview:((Pe=oe[B])==null?void 0:Pe.preview)??null,loading:!1,applying:!0,cleaning:((Ye=oe[B])==null?void 0:Ye.cleaning)??!1,error:null}}});try{const oe=await p0(B);mt(Pe=>{var Ye;return{...Pe,[B]:{preview:oe.preview,loading:!1,applying:!1,cleaning:((Ye=Pe[B])==null?void 0:Ye.cleaning)??!1,error:null}}}),Rn(),Dn(),ls(B,!0),nn(oe.preview.targetWorkspace.id),ee.current({title:oe.applied?a("shell.worktreeMergeApplySuccess"):a("shell.worktreeMergeAlreadyMerged"),tone:"success"})}catch(oe){mt(Pe=>{var Ye,Qe;return{...Pe,[B]:{preview:((Ye=Pe[B])==null?void 0:Ye.preview)??null,loading:!1,applying:!1,cleaning:((Qe=Pe[B])==null?void 0:Qe.cleaning)??!1,error:oe instanceof Error?oe.message:a("shell.worktreeMergeApplyFailed")}}}),ee.current({title:oe instanceof Error?oe.message:a("shell.worktreeMergeApplyFailed"),tone:"error"})}}},[ls,Dn,nn,Rn]),ms=d.useCallback(async S=>{var Pe,Ye;const B=S.workspaceId,oe=Xe&&((Ye=(Pe=fn[B])==null?void 0:Pe.preview)==null?void 0:Ye.alreadyMerged)===!0;mt(Qe=>{var yt;return{...Qe,[B]:{preview:((yt=Qe[B])==null?void 0:yt.preview)??null,loading:!1,applying:!1,cleaning:!0,error:null}}});try{const Qe=await g0(B,{deleteBranch:oe});if(mt(yt=>{var Ut;return{...yt,[B]:{preview:((Ut=yt[B])==null?void 0:Ut.preview)??null,loading:!1,applying:!1,cleaning:!1,error:null}}}),Qt(!1),Ae(yt=>(yt==null?void 0:yt.workspaceId)===B?null:yt),Rn(),await Dn(),n(Hk(S.parentWorkspaceId),{replace:!0}),Qe.branchDeleted){ee.current({title:a("shell.worktreeCleanupDeleteBranchSuccess",{branch:Qe.deletedBranchName||S.branchName}),tone:"success"});return}if(Qe.branchDeleteRequested){ee.current({title:a("shell.worktreeCleanupDeleteBranchPartialFailed",{branch:S.branchName}),description:Qe.branchDeleteError||void 0,tone:"warning"});return}ee.current({title:a("shell.worktreeCleanupSuccess"),tone:"success"})}catch(Qe){mt(yt=>{var Ut;return{...yt,[B]:{preview:((Ut=yt[B])==null?void 0:Ut.preview)??null,loading:!1,applying:!1,cleaning:!1,error:Qe instanceof Error?Qe.message:a("shell.worktreeCleanupFailed")}}}),ee.current({title:Qe instanceof Error?Qe.message:a("shell.worktreeCleanupFailed"),tone:"error"})}},[Xe,n,Dn,Rn,fn]),ps=d.useCallback(S=>{Qt(!1),Ae(S)},[]),ws=d.useCallback((S,B)=>{var oe;E.current={workspaceId:S,knownRevision:B==null?void 0:B.knownRevision},(oe=k.current)==null||oe.subscribeTerminalManager(S,B)},[]),On=d.useCallback((S,B)=>{var oe;D.current={workspaceId:S,knownRevision:B==null?void 0:B.knownRevision},(oe=k.current)==null||oe.requestTerminalManagerRefresh(S,B)},[]),vs=d.useCallback(S=>(_.current.add(S),()=>{_.current.delete(S)}),[]),Ss=d.useCallback((S,B)=>{Te(oe=>x8(oe,S,B??new Date().toISOString()))},[]),Wn=d.useCallback(async(S,B)=>{g.current.set(S,B),Te(oe=>Tk(oe,S,B));try{const oe=await cu(S,B),Pe=Xr(oe);Pe===B?g.current.set(S,Pe):g.current.delete(S),Kn(oe),Rn(),Dn()}catch(oe){throw g.current.delete(S),Te(Pe=>Tk(Pe,S,!B)),oe}},[Dn,Rn,Kn]),Gn=d.useCallback((S,B)=>{Xt("workbench.set_session_workspace",{sessionId:S,workspaceId:B}),ue(oe=>{if(!B){if(!(S in oe))return oe;const Pe={...oe};return delete Pe[S],Pe}return oe[S]===B?oe:{...oe,[S]:B}})},[]);d.useEffect(()=>{m.current=Y.length>0},[Y]),d.useEffect(()=>{Xt("workbench.navigation_state",{navigationLoading:fe,workspaceCount:Y.length,sessionCount:Y.reduce((S,B)=>S+B.sessions.length,0)})},[Y,fe]),d.useEffect(()=>{x.current!==null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{var ct;x.current=null,!(p.current||m.current)&&(Xt("workbench.refresh_navigation.ws_fallback_triggered"),(ct=k.current)==null||ct.requestRefresh())},1200);const S=new _I({onConnectionChange:ct=>{ct==="connected"&&xB(),ct==="reconnect_failed"&&!m.current&&(je(a("shell.navigationLoadFailed")),ee.current({id:"workbench-navigation-connection",title:a("shell.navigationLoadFailed"),tone:"warning",durationMs:3600}))},onSnapshot:ct=>{p.current=!0,Xt("workbench.ws_snapshot_received",{workspaceCount:ct.items.length,sessionCount:ct.items.reduce((kn,mr)=>kn+mr.sessions.length,0)}),x.current!==null&&(window.clearTimeout(x.current),x.current=null),ts(ct),W(!1)},onFileTreeSnapshot:ct=>{C.current.forEach(kn=>kn(ct))},onGitSnapshot:ct=>{Rr(VN(ct.workspaceId),{revision:ct.revision??null,status:ct.status,history:ct.history,historyTotalCount:ct.historyTotalCount,historyNextCursor:ct.historyNextCursor,branches:ct.branches}),Cn(kn=>{var Tr;const mr=((Tr=Y.find(vo=>vo.workspace.id===ct.workspaceId))==null?void 0:Tr.workspace)??null;if(!mr)return kn;const Nr=kn[ct.workspaceId],_n=YN(GN((Nr==null?void 0:Nr.detail)??KN(mr),mr),ct);return Rr(mm(ct.workspaceId),_n),{...kn,[ct.workspaceId]:{detail:_n,loading:!1,error:null}}}),j.current.forEach(kn=>kn(ct))},onWorkspaceManagementSnapshot:ct=>{Rr(mm(ct.workspaceId),ct),Cn(kn=>({...kn,[ct.workspaceId]:{detail:ct,loading:!1,error:null}})),H.current.forEach(kn=>kn(ct))},onTerminalManagerSnapshot:ct=>{_.current.forEach(kn=>kn(ct))},onUnauthorized:()=>{fa.clear(),n("/login",{replace:!0})}});S.primeWorkbenchSnapshot(f.current),k.current=S;const B=T.current,oe=P.current,Pe=z.current,Ye=L.current,Qe=R.current,yt=K.current,Ut=E.current,Dt=D.current;return B&&S.subscribeFileTree(B.workspaceId,B.paths,{knownRevisionByPath:B.knownRevisionByPath}),Pe&&S.subscribeGit(Pe.workspaceId,{knownRevision:Pe.knownRevision}),Qe&&S.subscribeWorkspaceManagement(Qe.workspaceId,{knownRevision:Qe.knownRevision}),Ut&&S.subscribeTerminalManager(Ut.workspaceId,{knownRevision:Ut.knownRevision}),oe&&S.requestFileTreeRefresh(oe.workspaceId,oe.paths,{knownRevisionByPath:oe.knownRevisionByPath}),Ye&&S.requestGitRefresh(Ye.workspaceId,{knownRevision:Ye.knownRevision}),yt&&S.requestWorkspaceManagementRefresh(yt.workspaceId,{knownRevision:yt.knownRevision}),Dt&&S.requestTerminalManagerRefresh(Dt.workspaceId,{knownRevision:Dt.knownRevision}),S.start(),()=>{x.current!==null&&(window.clearTimeout(x.current),x.current=null),k.current===S&&(k.current=null),S.close()}},[n]),d.useEffect(()=>{sa(tk,String(Q))},[Q]),d.useEffect(()=>{sa(nk,String(Oe))},[Oe]),d.useEffect(()=>{sa(sk,String(Ve))},[Ve]),d.useEffect(()=>{sa(rk,String(ve))},[ve]),d.useEffect(()=>{if(!rt){l8(Gf);return}sa(Gf,rt)},[rt]),d.useEffect(()=>{if($t||ve)return;const S=window.setTimeout(()=>{pt(!0)},b3);return()=>{window.clearTimeout(S)}},[$t,ve]);const cs=ul(t.pathname),Rt=(cs==null?void 0:cs.sessionId)??null,Yn=Rt?ZN(Rt):!1,Mt=d.useMemo(()=>IT(Y),[Y]),A=d.useMemo(()=>NN(Mt,o),[Mt,o]),ie=d.useMemo(()=>LN(Y),[Y]),tt=d.useMemo(()=>new Set(_t),[_t]),Pt=d.useMemo(()=>Mt.filter(S=>S.session.isFavorite===!0).map(S=>S.session.sessionId),[Mt]),zt=d.useMemo(()=>new Set(Pt),[Pt]),pn=d.useCallback(S=>{const B=Xf(S,_t);f.current=B,Sc(B),pe.current=S,Te(S)},[_t]),Os=d.useCallback(S=>{const B=!tt.has(S),oe=Ak(_t,S,B),Pe=Xf(Y,oe);f.current=Pe,Sc(Pe),xt(oe),ew(S,{collapsed:B}).catch(Ye=>{const Qe=Ak(oe,S,!B),yt=Xf(Y,Qe);f.current=yt,Sc(yt),xt(Qe),ee.current({title:Ye instanceof Error?Ye.message:a("shell.workspaceCollapseStateSaveFailed"),tone:"error"})})},[tt,_t,Y]),Tn=d.useCallback(()=>{ce.current={originalGroups:pe.current}},[]),Qs=d.useCallback((S,B,oe)=>{const Pe=pe.current,Ye=p8(Pe,S,B,oe);Ye!==Pe&&pn(Ye)},[pn]),Pn=d.useCallback(()=>{const S=ce.current;ce.current=null;const B=pe.current;S&&(S.originalGroups.length===B.length&&S.originalGroups.every((oe,Pe)=>{var Ye;return oe.workspace.id===((Ye=B[Pe])==null?void 0:Ye.workspace.id)})||VT({workspaceIds:B.map(oe=>oe.workspace.id)}).catch(oe=>{pn(S.originalGroups),ee.current({title:oe instanceof Error?oe.message:a("shell.workspaceReorderFailed"),tone:"error"})}))},[pn]);d.useEffect(()=>{const S=new Map;if(Mt.forEach(({session:B})=>{S.set(B.sessionId,{activityState:B.activityState,completedAt:B.completedAt??null,runningState:B.runningState??null})}),!ye.current){ye.current=!0,Be.current=S;return}Mt.forEach(({session:B})=>{var yt;if(B.sessionId===Rt)return;const oe=Be.current.get(B.sessionId);if(!oe)return;const Pe=oe.activityState!=="completed_unread"&&B.activityState==="completed_unread",Ye=((yt=B.title)==null?void 0:yt.trim())||a("common.unknown");if(c&&Pe){const Ut=a("conversation.backgroundCompletionToastDescription",{title:Ye});ee.current({id:`workbench-session-completed-${B.sessionId}-${B.completedAt??"unknown"}`,title:a("conversation.backgroundCompletionToastTitle"),description:Ut,tone:"success",durationMs:8e3,action:{label:a("shell.contextOpenSession"),onClick:()=>Nn(B.workspaceId,B.sessionId)}}),U.current.showNotification(a("conversation.backgroundCompletionToastTitle"),Ut)}const Qe=oe.runningState!=="failed"&&(B.runningState??null)==="failed";if(u&&Qe){const Ut=P3(B)??a("conversation.runtimeFailed"),Dt=a("conversation.backgroundFailureToastDescription",{title:Ye,detail:Ut});ee.current({id:`workbench-session-failed-${B.sessionId}-${B.updatedAt}`,title:a("conversation.backgroundFailureToastTitle"),description:Dt,tone:"error",durationMs:8e3,action:{label:a("shell.contextOpenSession"),onClick:()=>Nn(B.workspaceId,B.sessionId)}}),U.current.showNotification(a("conversation.backgroundFailureToastTitle"),Dt)}}),Be.current=S},[Rt,Mt,c,u,Nn]),d.useEffect(()=>{we.current=Mt.map(S=>S.session).filter(S=>S.sessionId!==Rt&&A3(S)).map(S=>{var B;return{sessionId:S.sessionId,workspaceId:S.workspaceId,title:((B=S.title)==null?void 0:B.trim())||a("common.unknown")}})},[Rt,Mt]),d.useEffect(()=>{let S=!1,B=null;const oe=()=>{B=window.setTimeout(()=>{Pe().finally(()=>{S||oe()})},k3)},Pe=async()=>{var Dt;const Ye=we.current;if(Ye.length===0){We.current||(We.current=!0),ke.current="";return}const Qe=new Set(Ye.map(ct=>ct.sessionId)),yt=await Promise.all(Ye.map(async ct=>{try{const kn=await ow(ct.sessionId);return{session:ct,items:kn.items}}catch{return{session:ct,items:null}}}));if(S)return;for(const ct of yt){if(!ct.items)continue;const kn=ct.items.filter(_n=>_n.status==="pending"),mr=new Set(kn.map(_n=>_n.id)),Nr=Ce.current.get(ct.session.sessionId)??new Set;We.current&&kn.forEach(_n=>{if(Nr.has(_n.id)||!l)return;const Tr=a("conversation.backgroundPermissionToastDescription",{title:ct.session.title,requestTitle:_n.title});ee.current({id:`workbench-permission-request-${_n.id}`,title:a("conversation.permissionRequestToastTitle"),description:Tr,tone:"warning",durationMs:8e3,action:{label:a("shell.contextOpenSession"),onClick:()=>Nn(ct.session.workspaceId,ct.session.sessionId)}}),U.current.showNotification(a("conversation.permissionRequestToastTitle"),Tr)}),Ce.current.set(ct.session.sessionId,mr)}for(const[ct,kn]of Ce.current.entries())!Qe.has(ct)&&kn.size===0&&Ce.current.delete(ct);const Ut=R3(Ce.current,Qe);We.current&&Ut!==ke.current&&((Dt=k.current)==null||Dt.requestRefresh()),ke.current=Ut,We.current=!0};return Pe().finally(()=>{S||oe()}),()=>{S=!0,B!==null&&window.clearTimeout(B)}},[l,Nn]),d.useEffect(()=>{fe&&Y.length===0||(xt(S=>zN(S,ie)),It(S=>S&&ie.has(S)?S:null))},[ie,fe]);const on=Mt.find(S=>S.session.sessionId===Rt)??null,Sn=(on==null?void 0:on.workspace.id)??(Rt?re[Rt]??null:null),gn=lm(t.pathname,t.search),bn=gn&&ie.has(gn)?gn:null,Cs=rt&&ie.has(rt)?rt:null,js=Sn??bn??Cs??null,Ge=js??((at=Y[0])==null?void 0:at.workspace.id)??null,ei=d.useCallback(S=>{if(S){const B=Mt.find(oe=>oe.workspace.id===S)??null;if(B)return B}return Mt[0]??null},[Mt]),Mn=d.useCallback(S=>{const B=typeof window>"u"?null:window.localStorage.getItem(Fc);if(!B)return null;const oe=B.split("?")[0]??B,Pe=ul(oe);if(!Pe)return window.localStorage.removeItem(Fc),null;const Ye=Pe.sessionId,Qe=Mt.find(Ut=>Ut.session.sessionId===Ye)??null,yt=Pe.workspaceId??(Qe==null?void 0:Qe.workspace.id)??null;return Qe&&(!S||yt===S)?Yr(Qe.workspace.id,Qe.session.sessionId):(window.localStorage.removeItem(Fc),null)},[Mt]),Hs=d.useMemo(()=>Un.filter(S=>!tn.has(S.id)),[tn,Un]),ir=d.useMemo(()=>Hs.filter(S=>_3(S,Ds)).length,[Hs,Ds]);d.useEffect(()=>{At&&ur(Hs)},[Hs,ur,At]);const Is=d.useCallback(S=>{Gt(!1),S.routePath&&n(S.routePath)},[n]),Zs=d.useCallback(async(S,B)=>{const oe=V.current+1;V.current=oe;try{const Pe=await MO(S,B);if(oe!==V.current)return;sn(Ye=>{const Qe=new Set(Ye);return Pe.item?Qe.add(Pe.item.notificationId):Qe.delete(S),Qe})}catch(Pe){if(oe!==V.current)return;ee.current({title:a("shell.globalNotificationsArchiveFailed"),description:Pe instanceof Error?Pe.message:void 0,tone:"error"})}},[]);d.useEffect(()=>{Sn&&It(S=>S===Sn?S:Sn)},[Sn]),d.useEffect(()=>{var Qe;if(fe)return;const S=((Qe=Y[0])==null?void 0:Qe.workspace.id)??null,B=bn??S??Cs,oe=Rt&&!Yn?ei(B):null,Pe=Rt&&!Yn?Mn(B):null,Ye=oe?Yr(oe.workspace.id,oe.session.sessionId):null;if(gn&&!bn){n(Pe??Ye??(S?U3(t.pathname,S):Jf(e)),{replace:!0});return}if(Rt&&!Yn&&!Sn){n(Pe??Ye??(S?ua(S):Jf(e)),{replace:!0});return}},[Rt,ei,Yn,t.pathname,n,Y,fe,Mn,gn,Sn,e,Cs,bn]),d.useEffect(()=>{Xt("workbench.current_workspace_resolved",{currentSessionId:Rt,sessionWorkspaceId:Sn,routeWorkspaceId:gn,currentWorkspaceId:Ge,source:Sn?on?"navigation":"sessionWorkspaceMap":gn?"route":rt?"workspaceSelection":"navigationFallback"})},[on,Rt,Ge,gn,rt,Sn]);const yn=su(t.pathname)?"terminals":ru(t.pathname)?"butler":"conversation",Us=yN(t.pathname),qs=Us??(Ge?Jq(Ge):null)??X3,us=Ge?St??nu(Ge):null,kr=qs==="affairs"&&!!(Ge&&us),$r=Us==="affairs"&&kr,pi=(us==null?void 0:us.primarySection)??"library",ti=$r&&pi!=="conversation",gi=ti&&!nt,En=e==="mobile",dr=Jf(e),ni=d.useMemo(()=>Y.map(S=>{const B=RN(S.sessions),oe=new Set(S.sessions.map(Pe=>Pe.sessionId));return{workspace:S.workspace,visibleSessions:B,archivedSessions:S.sessions.filter(Pe=>Xr(Pe)&&!Bl(Pe)),visibleSessionTree:jN(B,o).filter(Pe=>!zt.has(Pe.item.sessionId)&&!Uk(or(Pe),Ye=>zt.has(Ye.sessionId))),childWorktrees:DN(S.childWorktrees,zt,o,oe),isCollapsed:tt.has(S.workspace.id)}}),[tt,zt,Y,o]),er=d.useMemo(()=>yB(Y),[Y]),Pr=d.useMemo(()=>Ck(Y,Ge),[Ge,Y]),As=(on?AT(on.session,on.session.sessionIsolatedWorkspace):Ge)??Ge,tr=d.useMemo(()=>Ck(Y,As),[As,Y]),fr=d.useMemo(()=>Ge?(Pr==null?void 0:Pr.workspace)??Y.map(S=>S.workspace).find(S=>S.id===Ge)??null:null,[Ge,Pr,Y]),si=d.useMemo(()=>As?(tr==null?void 0:tr.workspace)??Y.map(S=>S.workspace).find(S=>S.id===As)??null:null,[As,tr,Y]),wr=(tr==null?void 0:tr.meta)??null,zr=(Ge?er[Ge]??null:null)??(fr?Iu(fr):null),v=(As?er[As]??null:null)??(si?Iu(si):zr),$=wr?fn[wr.workspaceId]??null:null,w=d.useMemo(()=>{var B,oe,Pe;if(!Rt)return null;const S=((Pe=(oe=(B=on==null?void 0:on.session)==null?void 0:B.parallelGroup)==null?void 0:oe.groupId)==null?void 0:Pe.trim())||null;return S||t8(A,Rt)},[(qn=(dn=on==null?void 0:on.session)==null?void 0:dn.parallelGroup)==null?void 0:qn.groupId,Rt,A]),F=yn==="conversation"&&!!w;d.useEffect(()=>{if(typeof window>"u"||!F||!w){jt(null);return}const S=ET(w);if(!S||S.sidebarCollapseDurationMs<=0){jt(null);return}jt(S);const B=Date.now()-S.createdAt,oe=S.totalDurationMs-B;if(oe<=0){jt(null);return}const Pe=window.setTimeout(()=>{jt(null)},oe);return()=>{window.clearTimeout(Pe)}},[w,F]),d.useEffect(()=>{Xt("workbench.info_panel_state",{infoPanelReady:$t,rightCollapsed:ve||F,currentWorkspaceId:Ge,sessionWorkspaceId:Sn,currentSessionId:Rt})},[Rt,Ge,$t,F,ve,Sn]);const Z=d.useMemo(()=>Mt.filter(S=>zt.has(S.session.sessionId)&&!Xr(S.session)&&!Ou(S.session)),[zt,Mt]),be=t.pathname.startsWith("/settings")?"settings":qs==="affairs"?"workspaces":ru(t.pathname)?"terminals":su(t.pathname)?"butler":z3(t.pathname)?t.pathname.endsWith("/tools/processes")||t.pathname==="/tools/processes"?"butler":"sessions":$3(t.pathname)||pk(t.pathname)?"sessions":"workspaces",Ee=En&&(be==="sessions"&&pk(t.pathname)||ru(t.pathname)),Je=Uu({isNativeMobile:r.isNativeMobile,viewportClass:r.viewportClass}),Et=Il({viewportClass:r.viewportClass,activeEntry:be,hasNavigationPanel:En,hasAuxiliaryPanel:En,preferCompactLayout:Je}),Hr=En&&ww(Et),un=En&&vw(Et),yo=d.useMemo(()=>Y.map(S=>S.workspace),[Y]),xa=d.useMemo(()=>{const S=He.trim().toLowerCase();return S?Mt.filter(B=>{const oe=(B.session.title||"").toLowerCase(),Pe=B.workspace.name.toLowerCase(),Ye=md(B.session.provider,"full").toLowerCase();return oe.includes(S)||Pe.includes(S)||Ye.includes(S)}):[]},[Mt,He]);d.useEffect(()=>{var B;const S=Ge??((B=Y[0])==null?void 0:B.workspace.id)??"";S&&it(oe=>oe&&Y.some(Ye=>Ye.workspace.id===oe)?oe:S)},[Ge,Y]),d.useEffect(()=>{Rt&&!Yn&&Sn&&sa(Fc,`${t.pathname}${t.search}`)},[Rt,Yn,t.pathname,t.search,Sn]),d.useEffect(()=>{!Ge||Us===null||(zx(Ge,qs),Qq(Ge,qs,`${t.pathname}${t.search}`))},[qs,Ge,t.pathname,t.search,Us]),d.useEffect(()=>{if(!Ge){vt(null);return}vt(Ux(Ge,Hx(Ge)??nu(Ge)))},[Ge]),d.useEffect(()=>{!Ge||Us!=="affairs"||ST(Ge)},[Ge,Us]),d.useEffect(()=>{St&&Zq(St)},[St]),d.useEffect(()=>{if(Rt&&Yn){b.current=`${t.pathname}${t.search}`;return}Rt&&!Yn&&(b.current=null)},[Rt,Yn,t.pathname,t.search]),d.useEffect(()=>{En||(J(!1),ze(!1))},[En]),d.useEffect(()=>{!En||fe||!W3(t.pathname)||js||(J(!1),ze(!1),n(dr,{replace:!0}))},[js,En,t.pathname,n,fe,dr]);function Wl(){if(En){J(!0);return}G(!1)}function $l(){if(kr){et(!1);return}if(!F){if(ri(),En){ze(!0);return}_e(!1)}}function zl(){if(En){J(S=>!S);return}G(S=>!S)}function gd(){if(kr){et(S=>!S);return}if(!F){if(ri(),En){ze(S=>!S);return}_e(S=>!S)}}function ri(){pt(!0)}function bi(S){if(It(S),ri(),qs==="affairs"){const B=Xo(S);t.pathname!==B&&n(B);return}if(su(t.pathname)){const B=Mi(S);t.pathname!==B&&n(B);return}Rt&&Sn!==S&&n(dr)}const yi=d.useCallback(async S=>{var Pe;const B=((Pe=Mt.find(Ye=>Ye.session.sessionId===S))==null?void 0:Pe.session)??null,oe=(B==null?void 0:B.isFavorite)!==!0;Te(Ye=>Ik(Ye,S,oe));try{const Ye=await aw(S,oe);Kn(Ye),Rn()}catch(Ye){throw Te(Qe=>Ik(Qe,S,!oe)),Ye}},[Mt,Rn,Kn]),xo=d.useCallback((S,B)=>{SN(S,B).then(()=>{n(qk(S,B))}).catch(oe=>{i({title:oe instanceof Error?oe.message:a("shell.startSessionFailed"),tone:"error"})})},[n,i]),ko=d.useCallback(S=>{var Pe;const B=((Pe=S.workspaceId)==null?void 0:Pe.trim())||Ge,oe=q3(S.filePath);return!B||!oe?!1:(ri(),kt("files"),En?(J(!1),ze(!0)):_e(!1),cn({requestId:y.current+1,workspaceId:B,filePath:oe,openViewer:S.openViewer===!0}),y.current+=1,!0)},[Ge,En]),Ji=d.useCallback(async(S,B)=>{const oe=await xm(S,B.trim());return Kn(oe),oe},[Kn]);function xi(S){Se(!0)}function Hl(){Se(!1),De("sessions"),lt(""),Nt(null),ft([]),Ht(!1)}async function bd(){const S=He.trim();if(!S||!wt.trim()){ft([]),Nt(null);return}Ht(!0),Nt(null);try{const B=await V0(wt,S);ft(B.items)}catch(B){ft([]),Nt(B instanceof Error?B.message:a("shell.searchCodeFailed"))}finally{Ht(!1)}}function Ul(S,B){const oe=he.current;oe&&(oe.style.setProperty("--workbench-left-width",`${S}px`),oe.style.setProperty("--workbench-left-current-width",gs?"0px":`${S}px`),oe.style.setProperty("--workbench-right-width",`${B}px`),oe.style.setProperty("--workbench-right-current-width",bs?"0px":`${B}px`))}function yd(S={}){return{leftWidth:S.leftWidth??(gs?0:X.current),rightWidth:S.rightWidth??(vr&&!bs?I.current:0),leftCollapsed:S.leftCollapsed??gs,rightCollapsed:S.rightCollapsed??(!vr||bs),prefersDarkAppearance:S.prefersDarkAppearance??an!=="light",isResizing:S.isResizing??Ft!==null}}function ka(S,B){var Ut;B.preventDefault(),B.stopPropagation(),(Ut=window.getSelection())==null||Ut.removeAllRanges();const oe=B.clientX,Pe=S==="left"?Q:Oe;bt(S);const Ye=()=>{const Dt=le.current;if(le.current=null,Dt!==null){if(S==="left"){X.current=Dt,ge(ct=>ct===Dt?ct:Dt),Ul(Dt,I.current);return}I.current=Dt,$e(ct=>ct===Dt?ct:Dt),Ul(X.current,Dt)}};function Qe(Dt){var Nr;Dt.preventDefault(),(Nr=window.getSelection())==null||Nr.removeAllRanges();const ct=Dt.clientX-oe,kn=S==="left"?$c(Pe+ct,ak,lk):$c(Pe-ct,ok,ck),mr=S==="left"?X.current:I.current;kn===mr&&le.current===null||(le.current=kn,xe.current===null&&(xe.current=window.requestAnimationFrame(()=>{xe.current=null,Ye()})))}function yt(){document.removeEventListener("mousemove",Qe),document.removeEventListener("mouseup",yt),xe.current!==null&&(window.cancelAnimationFrame(xe.current),xe.current=null),Ye(),bt(ct=>ct===S?null:ct);const Dt=yd({isResizing:!1});ne.current=Dt,r.bridge.syncNativeSidebarLayout(Dt)}document.addEventListener("mousemove",Qe,{passive:!1}),document.addEventListener("mouseup",yt)}function wo(S){if(!Ge||Us===S)return;zx(Ge,S),S==="affairs"&&Bs.flushSync(()=>{vt(oe=>Ux(Ge,oe??Hx(Ge)??nu(Ge)))});const B=cm(Ge,S)??(S==="affairs"?Xo(Ge):cm(Ge,"code")??ua(Ge));n(B)}function Xi(){if(qs==="affairs"&&Ge){n(Xo(Ge));return}if(ql())return;if(Mt.length===0){n(dr);return}const S=Yr(Mt[0].workspace.id,Mt[0].session.sessionId);n(S)}function xd(){if(!ql(Ge)){if(Ge){n(ua(Ge));return}n(dr)}}function ql(S){if(Rt&&Sn)return S&&Sn&&Sn!==S?!1:(n(`${t.pathname}${t.search}`),!0);if(b.current){if(S){const[oe,Pe=""]=b.current.split("?"),Ye=lm(oe??b.current,Pe?`?${Pe}`:"");if(Ye&&Ye!==S)return!1}return n(b.current),!0}const B=Mn(S);return B?(n(B),!0):!1}d.useEffect(()=>{if(typeof window>"u")return;function S(B){if(!(B.metaKey||B.ctrlKey)){B.key==="Escape"&&(J(!1),ze(!1));return}if(u8(B.target))return;const Pe=B.key.toLowerCase();if(!B.shiftKey&&Pe==="b"){B.preventDefault(),zl();return}if(B.shiftKey&&Pe==="i"){B.preventDefault(),gd();return}if(!B.shiftKey&&Pe===","){B.preventDefault(),n("/settings");return}if(!B.shiftKey&&Pe==="1"){B.preventDefault(),Xi();return}if(!B.shiftKey&&Pe==="2"){B.preventDefault(),n(Ge?Mi(Ge):Fs());return}if(!B.shiftKey&&Pe==="k"){B.preventDefault(),d8();return}B.shiftKey&&Pe==="r"&&(B.preventDefault(),Dn())}return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[n,Dn,En,Xi]);const kd=d.useMemo(()=>({shellMode:e,navigationGroups:Y,navigationLoading:fe,navigationError:Me,currentWorkspaceId:Ge,currentSessionId:Rt,favoriteSessionIds:Pt,favoriteSessions:Z,globalNotifications:Un,archivedNotificationIds:Array.from(tn),showArchivedNotifications:Zn,unreadNotificationCount:ir,refreshNavigation:Dn,requestNavigationRefresh:Rn,openNotificationPanel:()=>{Gt(!0)},closeNotificationPanel:()=>{Gt(!1)},setShowArchivedNotifications:es,archiveNotification:S=>{Zs(S,!0)},unarchiveNotification:S=>{Zs(S,!1)},setAuxiliaryPanel:q,subscribeFileTree:ks,requestFileTreeRefresh:xn,addFileTreeSnapshotListener:$s,subscribeGitSnapshot:Vt,requestGitRefresh:nn,addGitSnapshotListener:ns,subscribeWorkspaceManagementSnapshot:ss,requestWorkspaceManagementRefresh:Ts,addWorkspaceManagementSnapshotListener:Xs,workspaceManagementStateById:qt,subscribeTerminalManagerSnapshot:ws,requestTerminalManagerRefresh:On,addTerminalManagerSnapshotListener:vs,selectWorkspace:bi,toggleFavoriteSession:yi,archiveSession:S=>Wn(S,!0),unarchiveSession:S=>Wn(S,!1),renameSession:Ji,startDraftSession:xo,markNavigationSessionSeen:Ss,upsertNavigationSession:Kn,setSessionWorkspace:Gn,revealWorkspaceFile:ko}),[$s,ns,Xs,vs,Wn,Rt,Ge,Un,Pt,Z,bi,tn,Ss,Me,Y,fe,ir,xn,nn,Ts,Dn,Rn,es,q,On,Ji,Zn,qt,e,xo,Gn,ks,Vt,ss,ws,Zs,yi,Kn,ko]),Vl=yn==="butler"?st:s.jsx(Mk,{panelReady:$t,activeTab:Ie,fileRevealRequest:en,onTabChange:S=>{ri(),kt(S)},currentSessionId:Yn?null:Rt,activeWorkspaceId:As,navigationGroups:Y,workspaceContext:v,worktreeMeta:wr,worktreeMergeState:$,onRefreshWorktreeMergePreview:ls,onApplyWorktreeMerge:zs,onCleanupWorktree:ms}),vr=$r?gi:Vl!==null,gs=Ve,bs=$r?nt:ve||F,wd=bs,Qi=F&&ot!==null&&!ve,vd={"--workbench-left-width":`${Q}px`,"--workbench-left-current-width":gs?"0px":`${Q}px`,"--workbench-right-width":`${Oe}px`,"--workbench-right-current-width":bs?"0px":`${Oe}px`,"--workbench-right-sidebar-duration":ot&&!ve?`${ot.sidebarCollapseDurationMs}ms`:void 0,"--workbench-right-sidebar-content-duration":ot&&!ve?`${Math.max(320,ot.sidebarCollapseDurationMs-120)}ms`:void 0},Sr=r.isDesktop&&r.ui.osFamily==="macos"&&r.ui.prefersOverlayTitlebar;d.useEffect(()=>{!kr||!us||et(us.primarySection!=="library")},[us==null?void 0:us.primarySection,kr]),d.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const{documentElement:S,body:B}=document,oe=()=>{M.current!==null&&(window.clearTimeout(M.current),M.current=null);const Ye=de.current;de.current=!1,S.removeAttribute(Bc),B==null||B.removeAttribute(Bc),Ye&&Ne.current&&(Ne.current=!1,ut(Qe=>Qe+1))};if(!Sr){oe();return}const Pe=()=>{de.current=!0,S.setAttribute(Bc,"true"),B==null||B.setAttribute(Bc,"true"),M.current!==null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{oe()},v3)};return window.addEventListener("resize",Pe),()=>{window.removeEventListener("resize",Pe),oe()}},[Sr]);const ki=d.useMemo(()=>({leftWidth:gs?0:Q,rightWidth:vr&&!bs?Oe:0,leftCollapsed:gs,rightCollapsed:!vr||bs,prefersDarkAppearance:an!=="light",isResizing:Ft!==null}),[Ft,bs,gs,Q,Oe,vr,an]),Kl=d.useDeferredValue(ki),N=Ft===null?Kl:ki,ne=d.useRef(ki);d.useEffect(()=>{ne.current=ki},[ki]),d.useEffect(()=>{if(typeof window>"u")return;let S=null;const B=()=>{S=null,r.bridge.syncNativeSidebarLayout(N)},oe=()=>{S!==null&&window.cancelAnimationFrame(S),S=window.requestAnimationFrame(B)};return jn?(oe(),()=>{S!==null&&window.cancelAnimationFrame(S)}):(r.bridge.syncNativeSidebarLayout({leftWidth:0,rightWidth:0,leftCollapsed:!0,rightCollapsed:!0,prefersDarkAppearance:!1,isResizing:!1}),()=>{S!==null&&window.cancelAnimationFrame(S)})},[N,r.bridge,jn]),d.useLayoutEffect(()=>{const S=he.current;if(!S||!Sr||typeof window>"u"){hk(S);return}let B=null,oe=null;const Pe=new Set([S]),Ye=()=>{Ne.current=!1;const yt=window.getComputedStyle(S),Ut=vN(yt,"--desktop-macos-traffic-light-center-y");if(Ut===null){hk(S);return}const Dt={navToolbar:Ri(S,$n.navToolbar.selector),infoTabs:Ri(S,$n.infoTabs.selector),auxiliaryToolbarButton:Ri(S,$n.auxiliaryToolbarButton.selector),conversationHeaderMain:Ri(S,$n.conversationHeaderMain.selector),conversationHeaderActions:Ri(S,$n.conversationHeaderActions.selector),terminalTabbarMain:Ri(S,$n.terminalTabbarMain.selector),collapsedLeftControls:Ri(S,$n.collapsedLeftControls.selector),collapsedRightControls:Ri(S,$n.collapsedRightControls.selector)},ct=[Dt.infoTabs,Dt.conversationHeaderMain,Dt.conversationHeaderActions,Dt.terminalTabbarMain].filter(_n=>_n!==null),kn=[Dt.collapsedLeftControls,Dt.collapsedRightControls].filter(_n=>_n!==null),mr=kn.length>0?Vr(yt,"--workbench-collapsed-controls-live-shift-y",Ut,kn.reduce((_n,Tr)=>_n+Tr,0)/kn.length):null,Nr=ct.length>0?Vr(yt,"--workbench-titlebar-live-content-shift-y",Ut,ct.reduce((_n,Tr)=>_n+Tr,0)/ct.length):null;qr(S,"--workbench-titlebar-live-content-shift-y",Nr),qr(S,"--workbench-collapsed-controls-live-shift-y",mr),qr(S,$n.navToolbar.variableName,Vr(yt,$n.navToolbar.variableName,Ut,Dt.navToolbar)),qr(S,$n.infoTabs.variableName,Vr(yt,$n.infoTabs.variableName,Ut,Dt.infoTabs)),qr(S,$n.auxiliaryToolbarButton.variableName,Vr(yt,$n.auxiliaryToolbarButton.variableName,Ut,Dt.auxiliaryToolbarButton)),qr(S,$n.conversationHeaderMain.variableName,Vr(yt,$n.conversationHeaderMain.variableName,Ut,Dt.conversationHeaderMain)),qr(S,$n.conversationHeaderActions.variableName,Vr(yt,$n.conversationHeaderActions.variableName,Ut,Dt.conversationHeaderActions)),qr(S,$n.terminalTabbarMain.variableName,Vr(yt,$n.terminalTabbarMain.variableName,Ut,Dt.terminalTabbarMain)),qr(S,$n.collapsedLeftControls.variableName,Vr(yt,$n.collapsedLeftControls.variableName,Ut,Dt.collapsedLeftControls)),qr(S,$n.collapsedRightControls.variableName,Vr(yt,$n.collapsedRightControls.variableName,Ut,Dt.collapsedRightControls))},Qe=()=>{if(de.current){Ne.current=!0;return}B!==null&&window.cancelAnimationFrame(B),B=window.requestAnimationFrame(()=>{B=null,Ye()})};if(Qe(),typeof ResizeObserver<"u"){oe=new ResizeObserver(()=>{Qe()});for(const yt of Object.values($n))for(const Ut of S.querySelectorAll(yt.selector))Pe.add(Ut);for(const yt of Pe)oe.observe(yt)}return window.addEventListener("resize",Qe),()=>{B!==null&&window.cancelAnimationFrame(B),window.removeEventListener("resize",Qe),oe==null||oe.disconnect()}},[yn,$t,Ve,t.pathname,t.search,ve,vr,Sr,os]);const me=En?s.jsx(Zf,{workspaceGroups:ni,workspaceVisualContextMap:er,sessionDisplaySortMode:o,favoriteSessions:Z,favoriteSessionIds:zt,activeWorkspaceId:Ge,activeWorkbenchMode:qs,isConversationActive:yn==="conversation",isTerminalActive:yn==="terminals",isButlerActive:yn==="butler",isSearchOpen:Re,navigationLoading:fe,navigationError:Me,activeSessionId:Rt,onRefreshNavigation:Dn,onSessionUpdated:Kn,onNavigateConversation:Xi,onSelectWorkbenchMode:wo,onNavigateTerminals:()=>{J(!1),n(Ge?Mi(Ge):Fs())},onNavigateButler:()=>{J(!1),n(Ge?Fi(Ge):Fs())},onOpenSearch:()=>{J(!1),xi()},onOpenSettings:()=>{J(!1),n("/settings")},onSelectWorkspace:bi,onToggleWorkspaceCollapse:Os,onStartWorkspaceReorder:Tn,onPreviewWorkspaceReorder:Qs,onCommitWorkspaceReorder:Pn,allowWorkspaceReorder:!1,subscribeGitSnapshot:Vt,requestGitRefresh:nn,subscribeWorkspaceManagementSnapshot:ss,requestWorkspaceManagementRefresh:Ts,onToggleFavoriteSession:yi,onArchiveSession:S=>Wn(S,!0),onUnarchiveSession:S=>Wn(S,!1),workspaceManagementStateById:qt,setWorkspaceManagementStateById:Cn,unreadNotificationCount:ir,notificationPanelOpen:At,onToggleNotificationPanel:()=>{Gt(S=>!S)},onClose:()=>J(!1)}):null,Le=En&&vr?Vl:null;return s.jsxs(CN.Provider,{value:kd,children:[En?s.jsx(s.Fragment,{children:s.jsx(AI,{activeEntry:be,presentation:Ee?"conversation-focus":"default",navigationPanel:me,auxiliaryPanel:Le,onOpenNavigation:()=>{ze(!1),J(!0)},onOpenSearch:()=>{J(!1),ze(!1),xi()},onOpenAuxiliary:()=>{vr&&(ri(),J(!1),ze(!0))},onNavigateWorkspaces:()=>{J(!1),ze(!1),n(Fs())},onNavigateTerminals:()=>{J(!1),ze(!1),n(Ge?Mi(Ge):Fs())},onNavigateButler:()=>{J(!1),ze(!1),n(Ge?Fi(Ge):Fs())},onNavigateSessions:()=>{J(!1),ze(!1),xd()},onNavigateToolFiles:()=>{J(!1),ze(!1),n(Ge?Gk(Ge):Fs())},onNavigateToolGit:()=>{J(!1),ze(!1),n(Ge?Kk(Ge):Fs())},onNavigateToolProcesses:()=>{J(!1),ze(!1),n(Ge?Vk(Ge):Fs())},onNavigateSettings:()=>{J(!1),ze(!1),n("/settings")},children:s.jsx(jd,{})})}):s.jsx("div",{className:"workbench-shell",ref:he,style:vd,onMouseDownCapture:is,onDoubleClickCapture:Ws,"data-nav-loading":fe,"data-left-collapsed":gs,"data-right-collapsed":wd,"data-info-ready":$t,"data-parallel-conversation-active":F?"true":void 0,"data-parallel-sidebar-transition":Qi?"true":void 0,"data-runtime-platform":r.platform,"data-os-family":r.ui.osFamily,"data-overlay-titlebar":r.ui.prefersOverlayTitlebar,children:s.jsx("div",{className:"workbench-body-shell",children:kr?s.jsxs(iH,{workspaceId:Ge,workspaceName:(fr==null?void 0:fr.name)??null,navigationGroups:Y,state:us,onStateChange:vt,onRefreshNavigation:Dn,children:[s.jsx("aside",{className:"workbench-nav surface-card","data-collapsed":gs,children:s.jsx(Zf,{workspaceGroups:ni,workspaceVisualContextMap:er,sessionDisplaySortMode:o,favoriteSessions:Z,favoriteSessionIds:zt,activeWorkspaceId:Ge,activeWorkbenchMode:qs,isConversationActive:yn==="conversation",isTerminalActive:yn==="terminals",isButlerActive:yn==="butler",isSearchOpen:Re,navigationLoading:fe,navigationError:Me,activeSessionId:Rt,onRefreshNavigation:Dn,onSessionUpdated:Kn,onNavigateConversation:Xi,onSelectWorkbenchMode:wo,onNavigateTerminals:()=>n(Ge?Mi(Ge):Fs()),onNavigateButler:()=>n(Ge?Fi(Ge):Fs()),onOpenSearch:()=>xi(),onOpenSettings:()=>n("/settings"),onSelectWorkspace:bi,onToggleWorkspaceCollapse:Os,onStartWorkspaceReorder:Tn,onPreviewWorkspaceReorder:Qs,onCommitWorkspaceReorder:Pn,allowWorkspaceReorder:!0,subscribeGitSnapshot:Vt,requestGitRefresh:nn,subscribeWorkspaceManagementSnapshot:ss,requestWorkspaceManagementRefresh:Ts,onToggleFavoriteSession:yi,onArchiveSession:S=>Wn(S,!0),onUnarchiveSession:S=>Wn(S,!1),workspaceManagementStateById:qt,setWorkspaceManagementStateById:Cn,unreadNotificationCount:ir,notificationPanelOpen:At,onToggleNotificationPanel:()=>{Gt(S=>!S)},onToggleCollapse:()=>{G(!0)},affairsMenuSlot:s.jsx(aH,{}),affairsContentSlot:s.jsx(mH,{})})}),s.jsx("div",{className:"workbench-side-resizer","data-side":"left","data-collapsed":gs,role:"separator","aria-label":a("shell.leftResizerLabel"),onMouseDown:gs?void 0:S=>ka("left",S)}),s.jsxs("div",{className:"workbench-main-shell",children:[s.jsxs("div",{className:"workbench-collapsed-rail","aria-hidden":!gs&&!bs,children:[s.jsxs("div",{className:"workbench-collapsed-controls left","data-visible":gs,children:[s.jsx(Uc,{className:"workbench-nav-toolbar-button workbench-collapsed-button",ariaLabel:a("shell.showSessionSidebar"),side:"left",collapsed:!0,onClick:Wl}),s.jsx(_h,{collapsed:!0}),s.jsx(pm,{unreadCount:ir,open:At,onToggle:()=>{Gt(S=>!S)},collapsed:!0}),s.jsx("button",{type:"button",className:"workbench-nav-toolbar-button workbench-collapsed-button","data-open":Re,"aria-label":a("shell.searchEntry"),title:a("shell.searchEntry"),"aria-haspopup":"dialog","aria-expanded":Re,onClick:()=>xi(),children:s.jsx(gm,{})})]}),!F&&ti?s.jsx("div",{className:"workbench-collapsed-controls right","data-visible":bs,children:s.jsx(Uc,{className:"workbench-nav-toolbar-button workbench-collapsed-button",ariaLabel:a("shell.showInfoSidebar"),side:"right",collapsed:!0,onClick:$l})}):null]}),$r?s.jsx(OH,{workspaceId:Ge}):s.jsx($x,{children:s.jsx(jd,{})})]}),gi?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"workbench-side-resizer","data-side":"right","data-collapsed":bs,role:"separator","aria-label":a("shell.rightResizerLabel"),onMouseDown:bs?void 0:S=>ka("right",S)}),s.jsx("aside",{className:"workbench-auxiliary surface-card","data-collapsed":bs,"aria-hidden":bs,children:s.jsx(FH,{workspaceId:Ge,onToggleCollapse:()=>et(!0)})})]}):null]}):s.jsxs(s.Fragment,{children:[s.jsx("aside",{className:"workbench-nav surface-card","data-collapsed":gs,children:s.jsx(Zf,{workspaceGroups:ni,workspaceVisualContextMap:er,sessionDisplaySortMode:o,favoriteSessions:Z,favoriteSessionIds:zt,activeWorkspaceId:Ge,activeWorkbenchMode:qs,isConversationActive:yn==="conversation",isTerminalActive:yn==="terminals",isButlerActive:yn==="butler",isSearchOpen:Re,navigationLoading:fe,navigationError:Me,activeSessionId:Rt,onRefreshNavigation:Dn,onSessionUpdated:Kn,onNavigateConversation:Xi,onSelectWorkbenchMode:wo,onNavigateTerminals:()=>n(Ge?Mi(Ge):Fs()),onNavigateButler:()=>n(Ge?Fi(Ge):Fs()),onOpenSearch:()=>xi(),onOpenSettings:()=>n("/settings"),onSelectWorkspace:bi,onToggleWorkspaceCollapse:Os,onStartWorkspaceReorder:Tn,onPreviewWorkspaceReorder:Qs,onCommitWorkspaceReorder:Pn,allowWorkspaceReorder:!0,subscribeGitSnapshot:Vt,requestGitRefresh:nn,subscribeWorkspaceManagementSnapshot:ss,requestWorkspaceManagementRefresh:Ts,onToggleFavoriteSession:yi,onArchiveSession:S=>Wn(S,!0),onUnarchiveSession:S=>Wn(S,!1),workspaceManagementStateById:qt,setWorkspaceManagementStateById:Cn,unreadNotificationCount:ir,notificationPanelOpen:At,onToggleNotificationPanel:()=>{Gt(S=>!S)},onToggleCollapse:()=>{G(!0)}})}),s.jsx("div",{className:"workbench-side-resizer","data-side":"left","data-collapsed":gs,role:"separator","aria-label":a("shell.leftResizerLabel"),onMouseDown:gs?void 0:S=>ka("left",S)}),s.jsxs("div",{className:"workbench-main-shell",children:[s.jsxs("div",{className:"workbench-collapsed-rail","aria-hidden":!gs&&!ve,children:[s.jsxs("div",{className:"workbench-collapsed-controls left","data-visible":gs,children:[s.jsx(Uc,{className:"workbench-nav-toolbar-button workbench-collapsed-button",ariaLabel:a("shell.showSessionSidebar"),side:"left",collapsed:!0,onClick:Wl}),s.jsx(_h,{collapsed:!0}),s.jsx(pm,{unreadCount:ir,open:At,onToggle:()=>{Gt(S=>!S)},collapsed:!0}),s.jsx("button",{type:"button",className:"workbench-nav-toolbar-button workbench-collapsed-button","data-open":Re,"aria-label":a("shell.searchEntry"),title:a("shell.searchEntry"),"aria-haspopup":"dialog","aria-expanded":Re,onClick:()=>xi(),children:s.jsx(gm,{})})]}),vr&&!F?s.jsx("div",{className:"workbench-collapsed-controls right","data-visible":ve,children:s.jsx(Uc,{className:"workbench-nav-toolbar-button workbench-collapsed-button",ariaLabel:a("shell.showInfoSidebar"),side:"right",collapsed:!0,onClick:$l})}):null]}),s.jsx($x,{children:s.jsx(jd,{})})]}),vr?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"workbench-side-resizer","data-side":"right","data-collapsed":bs,"data-auto-hidden":F?"true":void 0,role:"separator","aria-label":a("shell.rightResizerLabel"),onMouseDown:bs?void 0:S=>ka("right",S)}),s.jsx("aside",{className:"workbench-auxiliary surface-card","data-workspace-tone":(v==null?void 0:v.tone)??"root","data-worktree-depth":(v==null?void 0:v.depth)??0,"data-collapsed":bs,"data-auto-hidden":F?"true":void 0,"data-custom-panel":yn==="butler","data-parallel-transition":Qi?"true":void 0,"aria-hidden":bs&&!Qi,style:Gr(v),children:F&&!Qi?null:yn==="butler"?s.jsx("div",{className:"workbench-auxiliary-custom-panel",children:st}):s.jsx(Mk,{panelReady:$t,activeTab:Ie,fileRevealRequest:en,onTabChange:S=>{ri(),kt(S)},onToggleCollapse:()=>_e(!0),currentSessionId:Yn?null:Rt,activeWorkspaceId:As,navigationGroups:Y,workspaceContext:v,worktreeMeta:wr,worktreeMergeState:$,onRefreshWorktreeMergePreview:ls,onApplyWorktreeMerge:zs,onCleanupWorktree:ps})})]}):null]})})}),s.jsx(I8,{open:At,notifications:Un,archivedNotificationIds:tn,showArchivedNotifications:Zn,onClose:()=>Gt(!1),onToggleShowArchivedNotifications:es,onArchiveNotification:S=>{Zs(S,!0)},onUnarchiveNotification:S=>{Zs(S,!1)},onSelectNotification:Is,preferredWorkspaceId:Ge,preferredSessionId:Yn?null:Rt}),s.jsx(U8,{open:Re,mode:Ke,keyword:He,codeWorkspaceId:wt,codeResults:dt,codeLoading:Ze,codeError:gt,workspaceOptions:yo,sessionResults:xa,onClose:Hl,onModeChange:S=>{De(S),Nt(null),ft([])},onKeywordChange:S=>{lt(S),Ke==="code"&&!S.trim()&&(ft([]),Nt(null))},onCodeWorkspaceChange:S=>it(S),onCodeSearch:()=>{bd()},onOpenSession:S=>{Hl();const B=Mt.find(oe=>oe.session.sessionId===S)??null;n(B?Yr(B.workspace.id,S):Fs())}}),s.jsxs(ln,{open:O!==null,title:a("shell.worktreeCleanupModalTitle"),description:a("shell.worktreeCleanupModalDescription"),onClose:()=>{var S;O&&((S=fn[O.workspaceId])!=null&&S.cleaning)||(Qt(!1),Ae(null))},children:[s.jsx("p",{className:"workbench-section-empty",children:O?a("shell.worktreeCleanupConfirm",{name:O.displayName||O.branchName}):""}),O?s.jsxs("div",{className:"worktree-cleanup-modal-options",children:[s.jsxs("label",{className:"conversation-selection-checkbox worktree-cleanup-modal-option",children:[s.jsx("input",{type:"checkbox",checked:Xe,disabled:!!((Fn=fn[O.workspaceId])!=null&&Fn.cleaning)||((Cr=(Ns=fn[O.workspaceId])==null?void 0:Ns.preview)==null?void 0:Cr.alreadyMerged)!==!0,onChange:S=>Qt(S.target.checked)}),s.jsx("span",{children:a("shell.worktreeCleanupDeleteBranchLabel",{branch:O.branchName})})]}),((wi=(jr=fn[O.workspaceId])==null?void 0:jr.preview)==null?void 0:wi.alreadyMerged)!==!0?s.jsx("p",{className:"conversation-selection-hint worktree-cleanup-modal-hint",children:a("shell.worktreeCleanupDeleteBranchHint")}):null]}):null,s.jsxs("div",{className:"workbench-modal-actions",children:[s.jsx("button",{type:"button",className:"secondary-button",disabled:!!(O&&((ii=fn[O.workspaceId])!=null&&ii.cleaning)),onClick:()=>{Qt(!1),Ae(null)},children:a("common.cancel")}),s.jsx("button",{type:"button",className:Xe&&O&&((In=(hr=fn[O.workspaceId])==null?void 0:hr.preview)==null?void 0:In.alreadyMerged)===!0?"secondary-button workbench-danger-button":"primary-button",disabled:!O||!!(O&&((Gl=fn[O.workspaceId])!=null&&Gl.cleaning)),onClick:()=>{O&&ms(O)},children:O&&((wn=fn[O.workspaceId])!=null&&wn.cleaning)?a("shell.worktreeCleanupRunning"):Xe&&O&&((Yl=(vi=fn[O.workspaceId])==null?void 0:vi.preview)==null?void 0:Yl.alreadyMerged)===!0?a("shell.worktreeCleanupDeleteBranchAction"):a("shell.worktreeCleanupAction")})]})]}),En?s.jsxs(s.Fragment,{children:[Hr?null:s.jsx(Ek,{isOpen:Ct,side:"left",onClose:()=>J(!1),children:me}),un?null:s.jsx(Ek,{isOpen:Ue,side:"right",onClose:()=>ze(!1),children:Le})]}):null]})}function Ek({isOpen:e,side:t,onClose:n,children:r,className:i,overlayClassName:o}){if(!e)return null;const l=s.jsxs(s.Fragment,{children:[s.jsx("div",{className:["mobile-nav-overlay","open",o].filter(Boolean).join(" "),onClick:n,role:"button",tabIndex:0,"aria-label":a("common.back"),onKeyDown:c=>{c.key==="Escape"&&n()}}),s.jsx("div",{className:["mobile-nav-drawer",t,"open",i].filter(Boolean).join(" "),children:r})]});return typeof document>"u"?l:Bs.createPortal(l,document.body)}function Wp(){return d.useContext(CN)??{navigationGroups:[],navigationLoading:!1,navigationError:null,shellMode:"desktop",currentWorkspaceId:null,currentSessionId:null,favoriteSessionIds:[],favoriteSessions:[],globalNotifications:[],archivedNotificationIds:[],showArchivedNotifications:!1,unreadNotificationCount:0,refreshNavigation:async()=>{},requestNavigationRefresh:()=>{},openNotificationPanel:()=>{},closeNotificationPanel:()=>{},setShowArchivedNotifications:()=>{},archiveNotification:()=>{},unarchiveNotification:()=>{},setAuxiliaryPanel:()=>{},subscribeFileTree:()=>{},requestFileTreeRefresh:()=>{},addFileTreeSnapshotListener:()=>()=>{},subscribeGitSnapshot:()=>{},requestGitRefresh:()=>{},addGitSnapshotListener:()=>()=>{},subscribeWorkspaceManagementSnapshot:()=>{},requestWorkspaceManagementRefresh:()=>{},addWorkspaceManagementSnapshotListener:()=>()=>{},workspaceManagementStateById:{},subscribeTerminalManagerSnapshot:()=>{},requestTerminalManagerRefresh:()=>{},addTerminalManagerSnapshotListener:()=>()=>{},selectWorkspace:()=>{},toggleFavoriteSession:async()=>{},archiveSession:async()=>{},unarchiveSession:async()=>{},renameSession:async()=>{throw new Error("workbench shell unavailable")},startDraftSession:()=>{},setSessionWorkspace:()=>{},upsertNavigationSession:()=>{},markNavigationSessionSeen:()=>{},revealWorkspaceFile:()=>!1}}function ZN(e){return e.startsWith("draft-")}export{pV as $,iH as A,t3 as B,hV as C,fV as D,mV as E,vp as F,CB as G,NB as H,ci as I,fp as J,Pi as K,$h as L,Wh as M,Dr as N,Ja as O,di as P,qo as Q,Bh as R,Dm as S,no as T,km as U,zh as V,_I as W,wV as X,SV as Y,wC as Z,vV as _,Hx as a,_A as a$,Tw as a0,lK as a1,uK as a2,yC as a3,rK as a4,iK as a5,cK as a6,sK as a7,fK as a8,dp as a9,cy as aA,ml as aB,VS as aC,Tl as aD,HA as aE,mK as aF,yB as aG,Iu as aH,c3 as aI,bV as aJ,Gr as aK,Np as aL,td as aM,id as aN,rh as aO,yV as aP,eI as aQ,tI as aR,nI as aS,VV as aT,op as aU,JF as aV,XF as aW,pK as aX,wS as aY,GV as aZ,Tp as a_,gK as aa,zS as ab,jV as ac,NV as ad,TV as ae,R0 as af,P0 as ag,ZB as ah,Xt as ai,z0 as aj,Qp as ak,uu as al,A0 as am,xV as an,ow as ao,CV as ap,kV as aq,nd as ar,Hi as as,yK as at,HS as au,bK as av,xK as aw,bo as ax,kK as ay,FA as az,OH as b,HV as b$,f3 as b0,dK as b1,xS as b2,vS as b3,Sw as b4,qV as b5,XB as b6,sW as b7,Zt as b8,Ch as b9,PV as bA,gV as bB,np as bC,bz as bD,LV as bE,xz as bF,kz as bG,yz as bH,SK as bI,EV as bJ,vK as bK,Pu as bL,IV as bM,V0 as bN,KV as bO,AV as bP,RV as bQ,U0 as bR,dl as bS,MV as bT,FV as bU,WV as bV,G0 as bW,_V as bX,DV as bY,BV as bZ,OV as b_,AO as ba,aK as bb,oK as bc,tK as bd,QV as be,ZV as bf,eK as bg,QB as bh,mp as bi,XV as bj,CO as bk,jO as bl,nK as bm,gB as bn,SB as bo,Fh as bp,wK as bq,xB as br,JB as bs,Cg as bt,nc as bu,i1 as bv,YV as bw,JV as bx,f1 as by,ig as bz,Ux as c,UV as c0,zV as c1,$V as c2,FH as d,jK as e,Wp as f,zT as g,Ui as h,hK as i,kC as j,e3 as k,CK as l,jy as m,YF as n,Qv as o,Zv as p,tS as q,Lm as r,ep as s,cB as t,Ql as u,dB as v,Zq as w,lB as x,rd as y,qT as z};