@jetcrab/pi-desk 1.1.20-dev → 1.1.22-dev

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 (202) hide show
  1. package/docs/plugins.md +81 -1
  2. package/package.json +3 -3
  3. package/src/app/page.tsx +6 -1
  4. package/src/app/project-preview/page.tsx +10 -0
  5. package/src/client/l1_entry/pages/l1-home-page.tsx +30 -0
  6. package/src/client/l1_entry/pages/l1-project-preview-page.tsx +33 -0
  7. package/src/client/l1_entry/providers/l1-app-providers.tsx +18 -15
  8. package/src/client/l1_entry/providers/l1-app-runtime-provider.tsx +2 -2
  9. package/src/client/l2_biz/auth/l2-login-biz.ts +3 -0
  10. package/src/client/l2_biz/auth/l2-login.tsx +2 -3
  11. package/src/client/l2_biz/plugin-host/l2-plugin-capability-details.tsx +6 -1
  12. package/src/client/l2_biz/plugin-host/l2-plugin-contribution-host.tsx +71 -10
  13. package/src/client/l2_biz/plugin-host/l2-plugin-management-controls.tsx +9 -0
  14. package/src/client/l2_biz/plugin-host/l2-plugin-session-header-layout.ts +18 -0
  15. package/src/client/l2_biz/plugin-host/l2-plugin-session-header.tsx +247 -0
  16. package/src/client/l2_biz/plugin-host/l2-plugin-widgets.tsx +50 -0
  17. package/src/client/l2_biz/plugin-host/views/l2-plugin-session-header-action.tsx +112 -0
  18. package/src/client/l2_biz/project-preview/hooks/l2-use-project-picker.ts +76 -0
  19. package/src/client/l2_biz/project-preview/hooks/l2-use-project-preview.ts +214 -0
  20. package/src/client/l2_biz/project-preview/l2-project-preview-biz.ts +49 -4
  21. package/src/client/l2_biz/project-preview/l2-project-preview-dialog.tsx +42 -450
  22. package/src/client/l2_biz/project-preview/l2-project-preview-page.tsx +61 -0
  23. package/src/client/l2_biz/project-preview/l2-project-preview.tsx +342 -0
  24. package/src/client/l2_biz/project-preview/runtime/l2-project-history-runtime.ts +9 -3
  25. package/src/client/l2_biz/project-preview/views/l2-project-picker.tsx +168 -0
  26. package/src/client/l2_biz/settings/hooks/l2-use-model-settings.ts +34 -31
  27. package/src/client/l2_biz/settings/views/l2-model-replacement-preview.tsx +7 -1
  28. package/src/client/l2_biz/workbench/file-workspace/l2-project-preview-biz.ts +4 -3
  29. package/src/client/l2_biz/workbench/hooks/l2-workbench-chat-viewport.ts +28 -21
  30. package/src/client/l2_biz/workbench/l2-work-session-columns.module.css +32 -0
  31. package/src/client/l2_biz/workbench/l2-work-session-columns.tsx +55 -16
  32. package/src/client/l2_biz/workbench/l2-work-session-sidebar.tsx +19 -8
  33. package/src/client/l2_biz/workbench/l2-workbench-chat-composer.tsx +12 -1
  34. package/src/client/l2_biz/workbench/l2-workbench-initialization-notice.tsx +8 -3
  35. package/src/client/l2_biz/workbench/l2-workbench-plugin-slots.ts +13 -0
  36. package/src/client/l2_biz/workbench/l2-workbench.tsx +15 -2
  37. package/src/client/l3_modules/conversation/l3-conversation-viewport.tsx +12 -6
  38. package/src/client/l3_modules/project-files/l3-markdown-preview.module.css +1 -1
  39. package/src/client/l3_modules/project-files/l3-project-document-git.ts +4 -3
  40. package/src/client/l3_modules/project-files/l3-project-document-view.tsx +4 -1
  41. package/src/client/l3_modules/project-files/l3-project-reader.ts +23 -35
  42. package/src/client/l4_foundation/lib/l4-client-id.tsx +11 -0
  43. package/src/client/l4_foundation/plugin-host/l4-plugin-host-runtime.ts +316 -35
  44. package/src/common/l2_biz/auth/l2-auth-return-to.ts +41 -0
  45. package/src/common/l2_biz/model-settings/l2-model-settings-contract.ts +5 -1
  46. package/src/common/l2_biz/plugin/l2-plugin-management-messages.ts +4 -0
  47. package/src/common/l2_biz/project-preview/l2-project-history-messages.ts +28 -0
  48. package/src/common/l2_biz/project-preview/l2-project-preview-navigation.ts +5 -0
  49. package/src/common/l2_biz/settings/l2-settings-messages.ts +4 -3
  50. package/src/common/l2_biz/workbench/l2-workbench-locale-messages.ts +2 -0
  51. package/src/server/l1_entry/node/l1-server.ts +8 -4
  52. package/src/server/l4_foundation/model-settings/l4-model-settings-store.ts +29 -20
  53. package/src/server/l4_foundation/model-settings/l4-model-settings-types.ts +1 -1
  54. package/src/server/l4_foundation/pi/l4-pi-chat-worker.ts +22 -5
  55. package/src/server/l4_foundation/pi/l4-pi-plugin-owner-runtime.ts +133 -13
  56. package/src/server/l4_foundation/pi/l4-pi-session-initialization.ts +9 -0
  57. package/temp/build/pi-desk/release/.next/BUILD_ID +1 -1
  58. package/temp/build/pi-desk/release/.next/app-path-routes-manifest.json +3 -2
  59. package/temp/build/pi-desk/release/.next/build-manifest.json +3 -3
  60. package/temp/build/pi-desk/release/.next/react-loadable-manifest.json +1 -2
  61. package/temp/build/pi-desk/release/.next/required-server-files.js +2 -2
  62. package/temp/build/pi-desk/release/.next/required-server-files.json +2 -2
  63. package/temp/build/pi-desk/release/.next/routes-manifest.json +6 -0
  64. package/temp/build/pi-desk/release/.next/server/app/_global-error/page.js +1 -1
  65. package/temp/build/pi-desk/release/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  66. package/temp/build/pi-desk/release/.next/server/app/_global-error.html +1 -1
  67. package/temp/build/pi-desk/release/.next/server/app/_global-error.rsc +3 -3
  68. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_full.segment.rsc +3 -3
  69. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +3 -3
  70. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  71. package/temp/build/pi-desk/release/.next/server/app/_not-found/page.js +1 -1
  72. package/temp/build/pi-desk/release/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  73. package/temp/build/pi-desk/release/.next/server/app/api/auth/login/route.js +1 -1
  74. package/temp/build/pi-desk/release/.next/server/app/api/auth/logout/route.js +1 -1
  75. package/temp/build/pi-desk/release/.next/server/app/api/auth-settings/get/route.js +1 -1
  76. package/temp/build/pi-desk/release/.next/server/app/api/auth-settings/replace/route.js +1 -1
  77. package/temp/build/pi-desk/release/.next/server/app/api/capability-modes/get/route.js +1 -1
  78. package/temp/build/pi-desk/release/.next/server/app/api/capability-modes/replace/route.js +1 -1
  79. package/temp/build/pi-desk/release/.next/server/app/api/chat/context/get/route.js +1 -1
  80. package/temp/build/pi-desk/release/.next/server/app/api/chat/images/get/route.js +1 -1
  81. package/temp/build/pi-desk/release/.next/server/app/api/chat/messages/get/route.js +1 -1
  82. package/temp/build/pi-desk/release/.next/server/app/api/health/route.js +1 -1
  83. package/temp/build/pi-desk/release/.next/server/app/api/mcp-check/get/route.js +1 -1
  84. package/temp/build/pi-desk/release/.next/server/app/api/mcp-settings/del/route.js +1 -1
  85. package/temp/build/pi-desk/release/.next/server/app/api/mcp-settings/get/route.js +1 -1
  86. package/temp/build/pi-desk/release/.next/server/app/api/mcp-settings/replace/route.js +1 -1
  87. package/temp/build/pi-desk/release/.next/server/app/api/model-catalog/list/route.js +1 -1
  88. package/temp/build/pi-desk/release/.next/server/app/api/model-settings/get/route.js +1 -1
  89. package/temp/build/pi-desk/release/.next/server/app/api/model-settings/preview/route.js +1 -1
  90. package/temp/build/pi-desk/release/.next/server/app/api/model-settings/replace/route.js +1 -1
  91. package/temp/build/pi-desk/release/.next/server/app/api/pi/directories/list/route.js +1 -1
  92. package/temp/build/pi-desk/release/.next/server/app/api/pi/directory-entries/list/route.js +1 -1
  93. package/temp/build/pi-desk/release/.next/server/app/api/pi/directory-ignores/list/route.js +1 -1
  94. package/temp/build/pi-desk/release/.next/server/app/api/pi/directory-ignores/replace/route.js +1 -1
  95. package/temp/build/pi-desk/release/.next/server/app/api/pi/models/list/route.js +1 -1
  96. package/temp/build/pi-desk/release/.next/server/app/api/pi/session-user-messages/list/route.js +1 -1
  97. package/temp/build/pi-desk/release/.next/server/app/api/pi/sessions/list/route.js +1 -1
  98. package/temp/build/pi-desk/release/.next/server/app/api/plugin-catalog/get/route.js +1 -1
  99. package/temp/build/pi-desk/release/.next/server/app/api/plugin-catalog/search/route.js +1 -1
  100. package/temp/build/pi-desk/release/.next/server/app/api/plugin-catalog/settings-get/route.js +1 -1
  101. package/temp/build/pi-desk/release/.next/server/app/api/plugin-catalog/settings-replace/route.js +1 -1
  102. package/temp/build/pi-desk/release/.next/server/app/api/plugins/add/route.js +1 -1
  103. package/temp/build/pi-desk/release/.next/server/app/api/plugins/apply/route.js +1 -1
  104. package/temp/build/pi-desk/release/.next/server/app/api/plugins/batch/route.js +1 -1
  105. package/temp/build/pi-desk/release/.next/server/app/api/plugins/browser-resources/[resourceGroup]/[...resourcePath]/route.js +1 -1
  106. package/temp/build/pi-desk/release/.next/server/app/api/plugins/del/route.js +1 -1
  107. package/temp/build/pi-desk/release/.next/server/app/api/plugins/enabled-set/route.js +1 -1
  108. package/temp/build/pi-desk/release/.next/server/app/api/plugins/get/route.js +1 -1
  109. package/temp/build/pi-desk/release/.next/server/app/api/plugins/host-runtime/[runtimeVersion]/[...resourcePath]/route.js +1 -1
  110. package/temp/build/pi-desk/release/.next/server/app/api/plugins/list/route.js +1 -1
  111. package/temp/build/pi-desk/release/.next/server/app/api/plugins/reload/route.js +1 -1
  112. package/temp/build/pi-desk/release/.next/server/app/api/plugins/update/route.js +1 -1
  113. package/temp/build/pi-desk/release/.next/server/app/api/project-files/get/route.js +1 -1
  114. package/temp/build/pi-desk/release/.next/server/app/api/project-files/list/route.js +1 -1
  115. package/temp/build/pi-desk/release/.next/server/app/api/project-files/reveal/route.js +1 -1
  116. package/temp/build/pi-desk/release/.next/server/app/api/project-files/search/route.js +2 -2
  117. package/temp/build/pi-desk/release/.next/server/app/api/project-git/get/route.js +1 -1
  118. package/temp/build/pi-desk/release/.next/server/app/api/project-git-branches/list/route.js +1 -1
  119. package/temp/build/pi-desk/release/.next/server/app/api/project-git-changes/list/route.js +1 -1
  120. package/temp/build/pi-desk/release/.next/server/app/api/project-git-diff/get/route.js +2 -2
  121. package/temp/build/pi-desk/release/.next/server/app/api/project-git-heads/get/route.js +1 -1
  122. package/temp/build/pi-desk/release/.next/server/app/api/project-git-log/list/route.js +2 -2
  123. package/temp/build/pi-desk/release/.next/server/app/api/project-model-default/get/route.js +1 -1
  124. package/temp/build/pi-desk/release/.next/server/app/api/project-model-default/replace/route.js +1 -1
  125. package/temp/build/pi-desk/release/.next/server/app/api/skill-files/get/route.js +1 -1
  126. package/temp/build/pi-desk/release/.next/server/app/api/skill-files/list/route.js +1 -1
  127. package/temp/build/pi-desk/release/.next/server/app/api/skill-files/replace/route.js +1 -1
  128. package/temp/build/pi-desk/release/.next/server/app/api/skills/list/route.js +1 -1
  129. package/temp/build/pi-desk/release/.next/server/app/api/task-center/images/get/route.js +1 -1
  130. package/temp/build/pi-desk/release/.next/server/app/api/task-center/messages/get/route.js +1 -1
  131. package/temp/build/pi-desk/release/.next/server/app/api/work-session-git-branch/add/route.js +1 -1
  132. package/temp/build/pi-desk/release/.next/server/app/api/work-session-git-branch/replace/route.js +1 -1
  133. package/temp/build/pi-desk/release/.next/server/app/api/work-session-tree/get/route.js +1 -1
  134. package/temp/build/pi-desk/release/.next/server/app/api/work-session-tree-entry/get/route.js +1 -1
  135. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/add/route.js +1 -1
  136. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/branch/route.js +1 -1
  137. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/del/route.js +1 -1
  138. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/rename/route.js +1 -1
  139. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/replace/route.js +1 -1
  140. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/sort/route.js +1 -1
  141. package/temp/build/pi-desk/release/.next/server/app/favicon.ico/route.js +1 -1
  142. package/temp/build/pi-desk/release/.next/server/app/login/page.js +1 -1
  143. package/temp/build/pi-desk/release/.next/server/app/login/page_client-reference-manifest.js +1 -1
  144. package/temp/build/pi-desk/release/.next/server/app/page.js +140 -140
  145. package/temp/build/pi-desk/release/.next/server/app/page_client-reference-manifest.js +1 -1
  146. package/temp/build/pi-desk/release/.next/server/app/project-preview/page.js +1 -0
  147. package/temp/build/pi-desk/release/.next/server/app/project-preview/page_client-reference-manifest.js +1 -0
  148. package/temp/build/pi-desk/release/.next/server/app-paths-manifest.json +3 -2
  149. package/temp/build/pi-desk/release/.next/server/chunks/10912.js +2 -2
  150. package/temp/build/pi-desk/release/.next/server/chunks/20460.js +15 -0
  151. package/temp/build/pi-desk/release/.next/server/chunks/25406.js +8 -8
  152. package/temp/build/pi-desk/release/.next/server/chunks/35985.js +3 -17
  153. package/temp/build/pi-desk/release/.next/server/chunks/36361.js +1 -1
  154. package/temp/build/pi-desk/release/.next/server/chunks/48180.js +1 -1
  155. package/temp/build/pi-desk/release/.next/server/chunks/56830.js +235 -0
  156. package/temp/build/pi-desk/release/.next/server/chunks/78262.js +1 -1
  157. package/temp/build/pi-desk/release/.next/server/chunks/79686.js +62 -0
  158. package/temp/build/pi-desk/release/.next/server/chunks/80780.js +1 -0
  159. package/temp/build/pi-desk/release/.next/server/chunks/81363.js +1 -1
  160. package/temp/build/pi-desk/release/.next/server/chunks/82499.js +4 -4
  161. package/temp/build/pi-desk/release/.next/server/chunks/92386.js +8 -8
  162. package/temp/build/pi-desk/release/.next/server/middleware-build-manifest.js +1 -1
  163. package/temp/build/pi-desk/release/.next/server/middleware-react-loadable-manifest.js +1 -1
  164. package/temp/build/pi-desk/release/.next/server/pages/500.html +1 -1
  165. package/temp/build/pi-desk/release/.next/static/MV6_lBt7Mzmi1rBNI-3dx/_buildManifest.js +1 -0
  166. package/temp/build/pi-desk/release/.next/static/chunks/11937-1d0a9822f2c7995b.js +1 -0
  167. package/temp/build/pi-desk/release/.next/static/chunks/14825-5579aed34a631ad7.js +62 -0
  168. package/temp/build/pi-desk/release/.next/static/chunks/15302-9c807afc6c60de0c.js +1 -0
  169. package/temp/build/pi-desk/release/.next/static/chunks/19991.8aa2e4b6df15fad6.js +1 -0
  170. package/temp/build/pi-desk/release/.next/static/chunks/22092-6d1bfbefa825ec03.js +1 -0
  171. package/temp/build/pi-desk/release/.next/static/chunks/37313-d5970e2d0c270d22.js +238 -0
  172. package/temp/build/pi-desk/release/.next/static/chunks/57235-03ba1044f22b6c84.js +1 -0
  173. package/temp/build/pi-desk/release/.next/static/chunks/79267-7d21d7cdbd7cfca1.js +1 -0
  174. package/temp/build/pi-desk/release/.next/static/chunks/82371-f7ba4a07a5dbcf34.js +1 -0
  175. package/temp/build/pi-desk/release/.next/static/chunks/9038-03144ed96d613f75.js +15 -0
  176. package/temp/build/pi-desk/release/.next/static/chunks/app/{error-0296a3b20cd1bf00.js → error-216b14b5da089ed3.js} +1 -1
  177. package/temp/build/pi-desk/release/.next/static/chunks/app/layout-20718f1503910291.js +1 -0
  178. package/temp/build/pi-desk/release/.next/static/chunks/app/login/page-0d3d4827802108e5.js +1 -0
  179. package/temp/build/pi-desk/release/.next/static/chunks/app/{not-found-2aab8b33ebbf3257.js → not-found-720cdf6a606b821a.js} +1 -1
  180. package/temp/build/pi-desk/release/.next/static/chunks/app/page-e8a5274c115f528d.js +158 -0
  181. package/temp/build/pi-desk/release/.next/static/chunks/app/project-preview/page-d70ee4e9409b970a.js +1 -0
  182. package/temp/build/pi-desk/release/.next/static/chunks/webpack-b60891a214e0925d.js +1 -0
  183. package/temp/build/pi-desk/release/.next/static/css/{250a6b93cc2222d1.css → 1e780a4936aa6ba3.css} +1 -1
  184. package/temp/build/pi-desk/release/.next/static/css/f646ca6c07245c4c.css +1 -0
  185. package/temp/build/pi-desk/release/.next/trace-build +1 -1
  186. package/temp/build/pi-desk/release/.next/server/chunks/10881.js +0 -296
  187. package/temp/build/pi-desk/release/.next/static/RLKcK-RQF5FvEeDmS9uih/_buildManifest.js +0 -1
  188. package/temp/build/pi-desk/release/.next/static/chunks/27611-0890482fe76bd9d6.js +0 -238
  189. package/temp/build/pi-desk/release/.next/static/chunks/31087-d8e5765d541d5c26.js +0 -1
  190. package/temp/build/pi-desk/release/.next/static/chunks/3814-35cfab0ce3aa7c41.js +0 -1
  191. package/temp/build/pi-desk/release/.next/static/chunks/70669.07f3670bfb7d6dd2.js +0 -1
  192. package/temp/build/pi-desk/release/.next/static/chunks/74220-795a2e7185bd66cb.js +0 -1
  193. package/temp/build/pi-desk/release/.next/static/chunks/77592-5bef6acb8e7c4b96.js +0 -13
  194. package/temp/build/pi-desk/release/.next/static/chunks/78923-17a9c337b29dcecd.js +0 -1
  195. package/temp/build/pi-desk/release/.next/static/chunks/81881-f11dbe7dc0d04ed9.js +0 -1
  196. package/temp/build/pi-desk/release/.next/static/chunks/96995-8f8313ea2ac3abd7.js +0 -62
  197. package/temp/build/pi-desk/release/.next/static/chunks/app/layout-a50c456648537afb.js +0 -3
  198. package/temp/build/pi-desk/release/.next/static/chunks/app/login/page-84892b06243891f0.js +0 -1
  199. package/temp/build/pi-desk/release/.next/static/chunks/app/page-0789c43551b29dd2.js +0 -158
  200. package/temp/build/pi-desk/release/.next/static/chunks/webpack-d7248206b7fc7ba8.js +0 -1
  201. package/temp/build/pi-desk/release/.next/static/css/a4cf28fd76c70165.css +0 -1
  202. /package/temp/build/pi-desk/release/.next/static/{RLKcK-RQF5FvEeDmS9uih → MV6_lBt7Mzmi1rBNI-3dx}/_ssgManifest.js +0 -0
@@ -1,158 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[58974],{2870:e=>{e.exports={branchTrigger:"l2-git-branch-button_branchTrigger__tCiwT",branchFull:"l2-git-branch-button_branchFull____dIA",branchFallback:"l2-git-branch-button_branchFallback__jNrXL",diverged:"l2-git-branch-button_diverged__nhSv5"}},4780:e=>{e.exports={guide:"l2-workbench-session-guide_guide__it3P8",otter:"l2-workbench-session-guide_otter__MjdUm",arrow:"l2-workbench-session-guide_arrow__p59pG"}},17708:(e,t,s)=>{"use strict";s.d(t,{Hr:()=>$,Ht:()=>R,I:()=>C,M5:()=>A,SQ:()=>I,_2:()=>M,dc:()=>j,lp:()=>S,lv:()=>z,mB:()=>T,nV:()=>E,rI:()=>k,ty:()=>N});var n=s(7962);s(69266);var r=s(6387),a=s(79102),i=s(40678),l=s(60454),o=s(93750),d=s(47150),c=s(85037),u=s(39608),m=s(98655),p=s(99577),h=s(15351),g=s(90099),x=s(47252),f=s(4947),b=s(49426),v=s(13464),w=s(36670),y=s(90458);function k({...e}){return(0,n.jsx)(r.i,{"data-slot":"dropdown-menu",...e})}function j({...e}){return(0,n.jsx)(a.g,{"data-slot":"dropdown-menu-portal",...e})}function N({...e}){return(0,n.jsx)(i.c,{"data-slot":"dropdown-menu-trigger",...e})}function I({align:e="start",alignOffset:t=0,side:s="bottom",sideOffset:r=4,className:i,finalFocus:d=!1,...c}){return(0,n.jsx)(a.g,{children:(0,n.jsx)(l.y,{className:"isolate z-50 outline-none",align:e,alignOffset:t,side:s,sideOffset:r,children:(0,n.jsx)(o._,{"data-slot":"dropdown-menu-content",finalFocus:d,className:(0,b.cn)(v.hD,i),...c})})})}function C({...e}){return(0,n.jsx)(d.r,{"data-slot":"dropdown-menu-group",...e})}function S({className:e,inset:t,...s}){return(0,n.jsx)(c.N,{"data-slot":"dropdown-menu-label","data-inset":t,className:(0,b.cn)("px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",e),...s})}function M({className:e,inset:t,variant:s="default",...r}){return(0,n.jsx)(u.D,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":s,className:(0,b.cn)(v.S6,v.dQ,"group/dropdown-menu-item",e),...r})}function z({...e}){return(0,n.jsx)(m.h,{"data-slot":"dropdown-menu-sub",...e})}function E({className:e,inset:t,children:s,...r}){return(0,n.jsxs)(p.f,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:(0,b.cn)(v.S6,"data-popup-open:bg-accent data-popup-open:text-accent-foreground",e),...r,children:[s,(0,n.jsx)(w.A,{className:"ml-auto"})]})}function A({align:e="start",alignOffset:t=-3,side:s="right",sideOffset:r=0,className:a,finalFocus:i=!0,...l}){return(0,n.jsx)(I,{"data-slot":"dropdown-menu-sub-content",finalFocus:i,className:(0,b.cn)("w-auto min-w-40",a),align:e,alignOffset:t,side:s,sideOffset:r,...l})}function $({...e}){return(0,n.jsx)(h.a,{"data-slot":"dropdown-menu-radio-group",...e})}function R({className:e,children:t,inset:s,...r}){return(0,n.jsxs)(g.i,{"data-slot":"dropdown-menu-radio-item","data-inset":s,className:(0,b.cn)(v.S6,"pr-8",e),...r,children:[(0,n.jsx)("span",{className:"pointer-events-none absolute right-2 flex items-center justify-center","data-slot":"dropdown-menu-radio-item-indicator",children:(0,n.jsx)(x.p,{children:(0,n.jsx)(y.A,{})})}),t]})}function T({className:e,...t}){return(0,n.jsx)(f.w,{"data-slot":"dropdown-menu-separator",className:(0,b.cn)("-mx-1 my-1 h-px bg-border",e),...t})}},19562:(e,t,s)=>{"use strict";s.d(t,{k:()=>c});var n=s(7962),r=s(66153),a=s(95929),i=s(69266),l=s(78121),o=s(49426),d=s(73429);function c({className:e,disabled:t,id:s,...u}){let{t:m}=(0,l.Bd)("common"),[p,h]=(0,i.useState)(!1),g=m(p?"hidePassword":"showPassword");return(0,n.jsxs)("div",{className:"relative min-w-0",children:[(0,n.jsx)(d.p,{...u,id:s,disabled:t,type:p?"text":"password",autoCapitalize:"none",spellCheck:!1,className:(0,o.cn)("pr-9",e)}),(0,n.jsx)("button",{type:"button",className:"absolute top-1/2 right-1 flex size-6 -translate-y-1/2 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50","aria-label":g,"aria-controls":s,"aria-pressed":p,title:g,disabled:t,onClick:()=>h(e=>!e),children:p?(0,n.jsx)(r.A,{className:"size-4","aria-hidden":"true"}):(0,n.jsx)(a.A,{className:"size-4","aria-hidden":"true"})})]})}},20314:e=>{e.exports={sidebarAction:"l2-work-session-sidebar_sidebarAction__9dyyW",rowMetadata:"l2-work-session-sidebar_rowMetadata__5pI6i",sessionRow:"l2-work-session-sidebar_sessionRow__gNO1s",runningBorder:"l2-work-session-sidebar_runningBorder__E7unr",rowActions:"l2-work-session-sidebar_rowActions__ioeUA",desktopRow:"l2-work-session-sidebar_desktopRow__RI8_L",rowTitle:"l2-work-session-sidebar_rowTitle__2iXeS"}},33941:(e,t,s)=>{"use strict";s.d(t,{G6:()=>l,Kc:()=>c,W:()=>r,Xm:()=>i,mj:()=>a,uZ:()=>d});var n=s(38979);let r=n.Ik({password:n.Yj().min(1).max(64)}).strict(),a=n.Ik({}).strict();n.Ik({}).strict();let i=n.Ik({}).strict();n.Ik({}).strict();let l=n.Ik({enabled:n.zM(),configPath:n.Yj()}).strict(),o=n.Yj().min(12).max(64).refine(e=>e===e.trim()&&!/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(e)).refine(e=>[/[A-Z]/,/[a-z]/,/[0-9]/,/[\p{P}\p{S}]/u].filter(t=>t.test(e)).length>=3),d=n.KC([r.extend({password:o}),n.Ik({password:n.ch()}).strict()]),c=n.Ik({}).strict()},37975:(e,t,s)=>{"use strict";s.d(t,{D:()=>i,Yj:()=>l,s6:()=>r});var n=s(38979);let r="project-preview",a=n.Ik({directories:n.YO(n.Yj().min(1).max(4096)).max(32),defaultDirectory:n.Yj().min(1).max(4096).nullable()}).strict();function i(e){let t=a.safeParse(e);return t.success?t.data:{directories:[],defaultDirectory:null}}function l(e){let t=e.replaceAll("\\","/").replace(/\/+$/,"")||"/";return/^[a-z]:/i.test(t)||t.startsWith("//")?t.toLowerCase():t}},42655:(e,t,s)=>{"use strict";s.d(t,{V:()=>i});var n=s(7962),r=s(50153);let a={src:"/_next/static/media/l4-brand-icon.d4f68daf.svg",height:348,width:464,blurWidth:0,blurHeight:0};function i({size:e=40,className:t}){return(0,n.jsx)(r.default,{src:a,width:e,height:3*e/4,alt:"",className:t})}},43769:e=>{e.exports={userText:"l3-conversation-messages_userText__oC8vv",userTextCollapsed:"l3-conversation-messages_userTextCollapsed__EjqBN",detailText:"l3-conversation-messages_detailText__JzS9c",toolOutput:"l3-conversation-messages_toolOutput__qydfS",toolCode:"l3-conversation-messages_toolCode__m6mgv",toolCodeLine:"l3-conversation-messages_toolCodeLine__gVs5q",toolFilePath:"l3-conversation-messages_toolFilePath__br6R2",toolFileDirectory:"l3-conversation-messages_toolFileDirectory__8BdId",usageToolbar:"l3-conversation-messages_usageToolbar__LDQnR",messageCopyAction:"l3-conversation-messages_messageCopyAction__xfZe0",copyableMessage:"l3-conversation-messages_copyableMessage__lrg9E",usageLabeled:"l3-conversation-messages_usageLabeled__BWv7V",usageCompact:"l3-conversation-messages_usageCompact__0ukdy"}},45458:(e,t,s)=>{"use strict";s.d(t,{L1HomePage:()=>gg});var n=s(7962),r=s(69266),a=s(38979),i=s(9626);let l={cols:a.ai().int().min(2).max(400),rows:a.ai().int().min(2).max(200)},o=a.Ik({...l,data:a.Yj().max(8388608)}).strict(),d=a.gM("type",[a.Ik({type:a.eu("snapshot"),snapshot:o}).strict(),a.Ik({type:a.eu("output"),data:a.Yj().min(1).max(65536)}).strict(),a.Ik({type:a.eu("resize"),...l}).strict(),a.Ik({type:a.eu("exit"),exitCode:a.ai().int()}).strict()]),c=a.Yj().uuid(),u=a.Ik({}).strict(),m=a.Ik({terminalId:c,cwd:a.Yj().min(1),shell:a.Yj().min(1),title:a.Yj().max(512),status:a.k5(["running","exited"]),exitCode:a.ai().int().nullable()}).strict(),p=a.Ik({terminals:a.YO(m).max(32)}).strict(),h=Object.freeze({list:(0,i.Vc)({path:"terminals/list",inputSchema:u,outputSchema:p}),create:(0,i.Vc)({path:"terminals/create",inputSchema:a.Ik({cwd:a.Yj().min(1).max(32768).optional()}).strict(),outputSchema:m}),remove:(0,i.Vc)({path:"terminals/remove",inputSchema:a.Ik({terminalId:c}).strict(),outputSchema:u}),watch:(0,i.Vc)({path:"terminals/watch",inputSchema:a.Ik({terminalId:c.nullable()}).strict(),outputSchema:a.Ik({snapshot:o.nullable()}).strict()}),unwatch:(0,i.Vc)({path:"terminals/unwatch",inputSchema:a.Ik({terminalId:c}).strict(),outputSchema:u}),input:(0,i.Vc)({path:"terminals/input",inputSchema:a.Ik({terminalId:c,data:a.Yj().min(1).max(16384)}).strict(),outputSchema:u}),activate:(0,i.Vc)({path:"terminals/activate",inputSchema:a.Ik({terminalId:c,...l}).strict(),outputSchema:u}),resize:(0,i.Vc)({path:"terminals/resize",inputSchema:a.Ik({terminalId:c,...l}).strict(),outputSchema:u}),update:(0,i._G)({path:"terminals/update",bodySchema:p}),event:(0,i._G)({path:"terminals/event",bodySchema:a.Ik({terminalId:c,event:d}).strict()})}),g=new TextEncoder;class x{constructor(e,t=()=>void 0){this.socket=e,this.onError=t,this.state={terminals:[],selectedId:null,expanded:!1,ready:!1,busy:!1,opening:!1,error:null,tabs:{}},this.listeners=new Set,this.screens=new Map,this.observedIds=new Set,this.unsubscribers=[],this.connectionEpoch=0,this.listEpoch=0,this.pageVisible=!0,this.watchChain=Promise.resolve(),this.commandRunning=!1,this.pendingActivation=null,this.pendingResize=null,this.inputQueue=[],this.inputBytes=0,this.inputTimer=null,this.resizeTimer=null,this.getSnapshot=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.start=()=>{this.unsubscribers.length||(this.unsubscribers=[this.socket.subscribe(h.update,({terminals:e})=>{this.state.ready&&(this.listEpoch+=1,this.replaceList(e))}),this.socket.subscribe(h.event,({terminalId:e,event:t})=>{let s=this.screens.get(e)?.watch;s?.observing&&this.valid(s)&&this.enqueue(s,t)})])},this.connected=async()=>{this.start();let e=++this.connectionEpoch;for(let e of(this.clearInput(),this.screens.values()))e.watch=null;this.patch({ready:!0});try{if(await this.refreshList(),e!==this.connectionEpoch||!this.state.ready)return;for(let e of this.screens.values())e.watch||this.scheduleWatch(e)}catch(t){e===this.connectionEpoch&&this.fail(t)}},this.disconnected=()=>{for(let e of(this.connectionEpoch+=1,this.listEpoch+=1,this.observedIds.clear(),this.screens.values()))e.watch=null,e.operated=!1;this.clearInput();let e=Object.fromEntries(Object.entries(this.state.tabs).map(([e,t])=>[e,{...t,syncing:!1}]));this.patch({ready:!1,tabs:e})},this.dispose=()=>{for(let e of(this.state.ready&&this.socket.request(h.watch,{terminalId:null}).catch(()=>void 0),this.disconnected(),this.unsubscribers))e();this.unsubscribers=[],this.screens.clear()},this.open=async(e,t)=>{if(t?.throwIfAborted(),!this.state.ready)throw Error("终端尚未连接");if(this.state.busy)return;let s=this.connectionEpoch,n=performance.now();this.patch({busy:!0,opening:!0,expanded:!0,error:null}),this.retainSelected();try{let r=await this.socket.request(h.create,e?{cwd:e}:{});if(s!==this.connectionEpoch)throw Error("连接已变化,请查看终端列表确认创建结果");this.state.terminals.some(e=>e.terminalId===r.terminalId)||this.replaceList([...this.state.terminals,r]),t?.throwIfAborted(),this.patch({selectedId:r.terminalId}),this.retainSelected(),console.info("[Pi Desk][Terminal] 已收到创建结果",{terminalId:r.terminalId,elapsedMs:Math.round(performance.now()-n)})}catch(e){throw t?.aborted||this.fail(e),this.state.ready&&this.refreshList().catch(e=>this.fail(e)),e}finally{this.patch({busy:!1,opening:!1,expanded:this.state.expanded&&(this.state.terminals.length>0||null!==this.state.error)})}},this.remove=async e=>{if(!this.state.ready||this.state.busy)return;let t=performance.now();this.patch({busy:!0,error:null});try{await this.socket.request(h.remove,{terminalId:e}),console.info("[Pi Desk][Terminal] 服务端已接纳关闭",{terminalId:e,elapsedMs:Math.round(performance.now()-t)})}catch(t){this.fail(t,e),this.state.ready&&this.refreshList().catch(e=>this.fail(e))}finally{this.patch({busy:!1})}},this.refreshList=async()=>{let e=this.connectionEpoch,t=++this.listEpoch,s=await this.socket.request(h.list,{});e===this.connectionEpoch&&t===this.listEpoch&&this.state.ready&&this.replaceList(s.terminals)},this.retry=()=>{if(!this.state.ready)return;this.patch({error:null});let e=this.state.selectedId?this.screens.get(this.state.selectedId):void 0;this.refreshList().then(()=>{e&&this.screens.get(e.id)===e&&this.scheduleWatch(e)}).catch(e=>this.fail(e))},this.setPageVisible=e=>{this.pageVisible=e},this.select=e=>{this.state.terminals.some(t=>t.terminalId===e)&&(this.patch({selectedId:e,expanded:!0}),this.retainSelected())},this.setExpanded=e=>{this.patch({expanded:e}),this.retainSelected()},this.attach=(e,t)=>{let s=this.screens.get(e);s&&(s.watch=null,this.cancelInput(e));let n={id:e,sink:t,watch:null,parsing:s?.parsing??Promise.resolve(),operated:!1};return this.screens.set(e,n),this.patchTab(e,{retained:!0}),this.state.ready&&this.scheduleWatch(n),()=>{this.screens.get(e)===n&&(n.watch=null,this.screens.delete(e),this.cancelInput(e),this.unwatch(e))}},this.activate=(e,t)=>{let s=this.inputTarget(e,t);s&&(s.watch.owner.operated=!0,this.pendingActivation=s,this.flushCommands())},this.input=(e,t,s)=>{let n=this.inputTarget(e,s);if(!n||!t)return;n.watch.owner.operated=!0;let r=g.encode(t).length;if(this.inputBytes+r>262144||this.inputQueue.length>=256){this.clearInput(),this.fail(Error("输入过多,尚未发送的内容已取消"),e);return}this.inputBytes+=r,this.inputQueue.push({...n,data:t}),this.inputTimer||(this.inputTimer=setTimeout(()=>{this.inputTimer=null,this.flushCommands()},8))},this.resize=(e,t)=>{let s=this.inputTarget(e,t);s&&s.watch.owner.operated&&(this.resizeTimer&&clearTimeout(this.resizeTimer),this.resizeTimer=setTimeout(()=>{this.resizeTimer=null,this.viewCommandValid(s)&&(this.pendingResize=s,this.flushCommands())},80))}}async flushCommands(){let e;if(!this.commandRunning){this.commandRunning=!0;try{for(;this.pendingActivation||this.inputQueue.length||this.pendingResize;)if(this.pendingActivation){let t=this.pendingActivation;if(this.pendingActivation=null,!this.viewCommandValid(t))continue;e=t,await this.socket.request(h.activate,{terminalId:t.id,...t.dimensions})}else if(this.inputQueue.length){let t=this.inputQueue.shift(),s=t.data;for(;this.inputQueue[0]?.watch===t.watch&&g.encode(s+this.inputQueue[0].data).length<=16384;)s+=this.inputQueue.shift().data;if(this.inputBytes-=g.encode(s).length,!this.commandValid(t))continue;for(let n of(e=t,await this.socket.request(h.activate,{terminalId:t.id,...t.dimensions}),function(e){let t=[],s="",n=0;for(let r of e){let e=g.encode(r).length;n+e>16384&&(t.push(s),s="",n=0),s+=r,n+=e}return s&&t.push(s),t}(s))){if(!this.commandValid(t))break;await this.socket.request(h.input,{terminalId:t.id,data:n})}}else if(this.pendingResize){let t=this.pendingResize;if(this.pendingResize=null,!this.viewCommandValid(t))continue;e=t,await this.socket.request(h.resize,{terminalId:t.id,...t.dimensions})}}catch(t){e&&this.commandValid(e)&&(this.cancelInput(e.id),this.fail(t,e.id))}finally{this.commandRunning=!1,(this.pendingActivation||this.inputQueue.length||this.pendingResize)&&this.flushCommands()}}}inputTarget(e,t){let s=this.screens.get(e)?.watch;return this.state.ready&&this.pageVisible&&this.state.expanded&&this.state.selectedId===e&&s?.baseline&&!this.state.tabs[e]?.syncing&&this.valid(s)&&this.state.terminals.some(t=>t.terminalId===e&&"running"===t.status)?{id:e,dimensions:t,connection:this.connectionEpoch,watch:s}:null}commandValid(e){return e.connection===this.connectionEpoch&&this.valid(e.watch)&&e.watch.baseline&&this.state.terminals.some(t=>t.terminalId===e.id&&"running"===t.status)}viewCommandValid(e){return this.commandValid(e)&&!!this.inputTarget(e.id,e.dimensions)}cancelInput(e){this.inputQueue=this.inputQueue.filter(t=>t.id!==e),this.inputBytes=this.inputQueue.reduce((e,t)=>e+g.encode(t.data).length,0),this.pendingActivation?.id===e&&(this.pendingActivation=null),this.pendingResize?.id===e&&(this.pendingResize=null),!this.inputQueue.length&&this.inputTimer&&(clearTimeout(this.inputTimer),this.inputTimer=null)}clearInput(){this.inputTimer&&clearTimeout(this.inputTimer),this.resizeTimer&&clearTimeout(this.resizeTimer),this.inputTimer=null,this.resizeTimer=null,this.inputQueue=[],this.inputBytes=0,this.pendingActivation=null,this.pendingResize=null}replaceList(e){let t=new Set(e.map(e=>e.terminalId));for(let e of this.observedIds)t.has(e)||this.observedIds.delete(e);for(let e of this.screens.values())t.has(e.id)||(e.watch=null,this.screens.delete(e.id),this.cancelInput(e.id));let s=Object.fromEntries(Object.entries(this.state.tabs).filter(([e])=>t.has(e))),n=t.has(this.state.selectedId??"")?this.state.selectedId:e[0]?.terminalId??null;this.patch({terminals:e,tabs:s,selectedId:n,expanded:this.state.expanded&&(e.length>0||this.state.opening||null!==this.state.error)}),this.retainSelected()}retainSelected(){let e=this.state.expanded?this.state.selectedId:null;e&&!this.state.tabs[e]?.retained&&this.patchTab(e,{retained:!0})}unwatch(e){let t=this.connectionEpoch;this.watchChain=this.watchChain.then(async()=>{t===this.connectionEpoch&&this.state.ready&&(await this.socket.request(h.unwatch,{terminalId:e}),t===this.connectionEpoch&&this.observedIds.delete(e))}).catch(s=>{t===this.connectionEpoch&&this.fail(s,e)})}scheduleWatch(e){let t={owner:e,connection:this.connectionEpoch,buffered:[],bytes:0,baseline:!1,observing:!1,draining:!1};e.watch=t,this.cancelInput(e.id),this.patchTab(e.id,{syncing:!0,error:null}),this.watchChain=this.watchChain.then(async()=>{if(!this.valid(t))return;let s=performance.now();if(this.observedIds.has(e.id)){if(await this.socket.request(h.unwatch,{terminalId:e.id}),!this.valid(t))return;this.observedIds.delete(e.id)}t.observing=!0,this.observedIds.add(e.id);let{snapshot:n}=await this.socket.request(h.watch,{terminalId:e.id});if(this.valid(t)){if(!n)throw Error("终端画面不可用");this.restoreWatch(t,n).then(()=>{this.valid(t)&&console.info("[Pi Desk][Terminal] 终端画面同步完成",{terminalId:e.id,elapsedMs:Math.round(performance.now()-s)})}).catch(e=>this.failWatch(t,e))}}).catch(e=>this.failWatch(t,e))}async restoreWatch(e,t){let s=e.owner;s.parsing=s.parsing.catch(()=>void 0).then(async()=>{this.valid(e)&&await s.sink.restore(t)}),await s.parsing,this.valid(e)&&(e.baseline=!0,await this.drain(e),this.valid(e)&&this.patchTab(s.id,{syncing:!1,error:null}))}failWatch(e,t){this.valid(e)&&(e.owner.watch=null,this.patchTab(e.owner.id,{syncing:!1}),this.fail(t,e.owner.id))}valid(e){return this.state.ready&&e.connection===this.connectionEpoch&&this.screens.get(e.owner.id)===e.owner&&e.owner.watch===e}enqueue(e,t){let s="output"===t.type?g.encode(t.data).length:"snapshot"===t.type?g.encode(t.snapshot.data).length:32;if(e.bytes+s>1048576||e.buffered.length>=256){console.warn("[Pi Desk][Terminal] 渲染队列已满,重新建立画面",{terminalId:e.owner.id}),this.scheduleWatch(e.owner);return}e.bytes+=s,e.buffered.push(t),e.baseline&&this.drain(e)}async drain(e){if(e.draining)return;e.draining=!0;let t=e.owner;t.parsing=t.parsing.catch(()=>void 0).then(async()=>{for(;this.valid(e)&&e.buffered.length;){let s=e.buffered.shift();"output"===s.type?(e.bytes-=g.encode(s.data).length,await t.sink.write(s.data)):"resize"===s.type?(e.bytes-=32,t.sink.resize(s)):"snapshot"===s.type?(e.bytes-=g.encode(s.snapshot.data).length,await t.sink.restore(s.snapshot)):e.bytes-=32}});try{await t.parsing}catch(s){this.valid(e)&&(this.fail(s,t.id),this.scheduleWatch(t))}finally{e.draining=!1,this.valid(e)&&e.buffered.length&&await this.drain(e)}}patchTab(e,t){let s=this.state.tabs[e]??{retained:!1,syncing:!1,error:null};this.patch({tabs:{...this.state.tabs,[e]:{...s,...t}}})}patch(e){for(let t of(this.state={...this.state,...e},this.listeners))t()}fail(e,t){let s=e instanceof Error?e.message:"终端操作失败";if(console.warn("[Pi Desk][Terminal] 终端操作失败",{terminalId:t,message:s}),t){this.state.terminals.some(e=>e.terminalId===t)&&this.patchTab(t,{error:s});return}s!==this.state.error&&this.onError(s),this.patch({error:s})}}var f=s(78121),b=s(14044),v=s(59252);let w=null;function y(){return w??=Promise.all([s.e(14307).then(s.bind(s,64935)),s.e(20573).then(s.bind(s,20573)),Promise.all([s.e(2281),s.e(3584)]).then(s.t.bind(s,3584,23))]).catch(e=>{throw w=null,e})}async function k(){await y()}async function j(e,t){let[{Terminal:s},{FitAddon:n}]=await y();t.signal.throwIfAborted();let r=new s({cols:80,rows:24,scrollback:2e3,fontFamily:'Consolas, "Cascadia Mono", Menlo, monospace',cursorBlink:!0,allowProposedApi:!0,windowOptions:{},overviewRuler:{width:0}}),a=new n;r.loadAddon(a);let i=function(e){let t=[];for(let s of[{final:"c"},{prefix:">",final:"c"},{final:"n"},{prefix:"?",final:"n"},{intermediates:"$",final:"p"},{prefix:"?",intermediates:"$",final:"p"}])t.push(e.parser.registerCsiHandler(s,()=>!0));for(let s of(t.push(e.parser.registerCsiHandler({final:"t"},e=>22!==e[0]&&23!==e[0])),t.push(e.parser.registerDcsHandler({intermediates:"$",final:"q"},()=>!0)),[4,10,11,12]))t.push(e.parser.registerOscHandler(s,e=>e.split(";").includes("?")));return t}(r),l=!1,o=!0,d=!0,c=0,u=!1,m=!1,p=new Set,h=Promise.resolve();r.open(e),r.textarea&&(r.textarea.setAttribute("aria-label","Terminal input"),r.textarea.style.fontSize="1rem");let g=()=>{let t=e.parentElement?.getBoundingClientRect();return o&&"visible"===document.visibilityState&&!!(t&&t.width>0&&t.height>0)},x=()=>{if(!g())return{cols:r.cols,rows:r.rows};let t=e.parentElement;if(t){let s=t.getBoundingClientRect(),n=getComputedStyle(t),r=parseFloat(n.paddingLeft)+parseFloat(n.paddingRight),a=parseFloat(n.paddingTop)+parseFloat(n.paddingBottom);e.style.width=`${Math.max(0,s.width-r-16)}px`,e.style.height=`${Math.max(0,s.height-a-16)}px`}let s=a.proposeDimensions();return{cols:Math.max(2,Math.min(400,s?.cols??r.cols)),rows:Math.max(2,Math.min(200,s?.rows??r.rows))}},f=()=>{if(!o)return;let e=r.element?.querySelector(".xterm-screen");e&&r.element&&(r.element.style.width=`${e.offsetWidth+14}px`,r.element.style.height=`${e.offsetHeight}px`)},b=()=>{if(l||!o)return;let e=getComputedStyle(document.documentElement),s=document.documentElement.classList.contains("dark");r.options.fontSize=.875*parseFloat(e.fontSize),r.options.theme={background:e.getPropertyValue("--background").trim()||(s?"#202020":"#ffffff"),foreground:e.getPropertyValue("--foreground").trim()||(s?"#eeeeee":"#292929"),cursor:s?"#eeeeee":"#292929",selectionBackground:s?"#555555":"#cccccc",...s?{}:{black:"#202020",red:"#a31515",green:"#006b2d",yellow:"#795e26",blue:"#0451a5",magenta:"#7f00aa",cyan:"#006b6b",white:"#555555",brightBlack:"#666666",brightRed:"#a31515",brightGreen:"#006b2d",brightYellow:"#795e26",brightBlue:"#0451a5",brightMagenta:"#7f00aa",brightCyan:"#006b6b",brightWhite:"#202020"}},f(),g()&&t.onResize(x())},v=e=>l?Promise.resolve():(c+=1,h=new Promise(t=>{let s=()=>{p.delete(s)&&(c-=1,f(),t())};p.add(s),r.write(e,s)})),w=e=>{l||d||!g()||("\x1b[I"!==e&&"\x1b[O"!==e||m&&!(c>0))&&(u&&(/^[a-zA-Z@\[\]\\^_]$/.test(e)&&(e=String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)),u=!1),t.onInput(e))};i.push(r.onData(w)),i.push(r.onBinary(w)),r.attachCustomKeyEventHandler(e=>(e.stopPropagation(),!((e.ctrlKey||e.metaKey)&&"c"===e.key.toLowerCase()&&r.hasSelection()))),i.push(r.onRender(f));let k=()=>{!d&&!l&&g()&&(m=!0,t.onActivate(x()),queueMicrotask(()=>{m=!1}))};e.addEventListener("pointerdown",k,!0),e.addEventListener("paste",k,!0);let j=null,N=new ResizeObserver(()=>{!l&&g()&&null===j&&(j=requestAnimationFrame(()=>{j=null,!l&&g()&&t.onResize(x())}))});N.observe(e.parentElement??e);let I=new MutationObserver(b);return I.observe(document.documentElement,{attributes:!0,attributeFilter:["class","style","data-display-size"]}),b(),{measure:x,async restore(e){l||(d=!0,await h,l||(r.reset(),r.resize(e.cols,e.rows),f(),await v(e.data),d=!1))},write:v,resize(e){l||(r.resize(e.cols,e.rows),f())},focus(){g()&&(k(),r.focus())},key(e){if(!g())return;k();let t=r.modes.applicationCursorKeysMode?"\x1bO":"\x1b[";w({escape:"\x1b",tab:" ",up:`${t}A`,down:`${t}B`,right:`${t}C`,left:`${t}D`}[e])},setControl(e){u=e},setVisible(e){if(!l&&o!==e){if(!(o=e)){r.blur(),null!==j&&cancelAnimationFrame(j),j=null;return}b(),r.refresh(0,r.rows-1)}},dispose(){if(l)return;for(let t of(l=!0,null!==j&&cancelAnimationFrame(j),N.disconnect(),I.disconnect(),e.removeEventListener("pointerdown",k,!0),e.removeEventListener("paste",k,!0),i))t.dispose();let t=r.element;for(let e of(r.dispose(),p))e();t?.remove()}}}var N=s(86963),I=s(72282),C=s(49426),S=s(55493);let M={dock:"bottom",height:280,width:440},z="pi-desk-terminal-dock";var E=s(57731),A=s(31123),$=s(28436),R=s(56164),T=s(79814),P=s.n(T);function D({biz:e,mobile:t,terminalId:s,visible:a}){let{t:i}=(0,f.Bd)("workbench"),l=(0,r.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot),o=function(e,t,s){let n=(0,r.useRef)(null),a=(0,r.useRef)(null),[i,l]=(0,r.useState)(null),[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(!0),[m,p]=(0,r.useState)(0),h=(0,r.useRef)(s);return(0,r.useLayoutEffect)(()=>{h.current=s,a.current?.setVisible(s)},[s]),(0,r.useEffect)(()=>{let s,r,i=n.current;if(!i)return;let o=!0,c=new AbortController;return j(i,{signal:c.signal,onInput:s=>{o&&r&&(e.input(t,s,r.measure()),d(!1))},onActivate:s=>{o&&e.activate(t,s)},onResize:s=>{o&&e.resize(t,s)}}).then(n=>{o?(r=n,a.current=n,n.setVisible(h.current),s=e.attach(t,{...n,async restore(e){await n.restore(e),o&&u(!1)}})):n.dispose()}).catch(e=>{o&&(u(!1),l(e instanceof Error?e.message:"终端加载失败"))}),()=>{o=!1,c.abort(),s?.(),a.current=null,r?.dispose()}},[m,e,t]),{container:n,loading:c,loadError:i,control:o,focus:()=>a.current?.focus(),key:e=>a.current?.key(e),toggleControl:()=>{a.current?.setControl(!o),d(!o)},retry:()=>{u(!0),l(null),p(e=>e+1)}}}(e,s,a),{container:d,loadError:c,loading:u,control:m}=o,p=l.tabs[s],h=l.terminals.find(e=>e.terminalId===s),g=h?.status!=="running"||!l.ready||p?.syncing||u,x=c??p?.error,v=x?null:l.ready?u?i("terminalOpening"):p?.syncing?i("terminalSyncing"):null:i("terminalReconnecting");return(0,n.jsxs)("div",{role:"tabpanel",id:`terminal-screen-${s}`,"aria-labelledby":`terminal-tab-${s}`,"aria-hidden":!a||void 0,hidden:!a,"data-testid":"terminal-tabpanel","data-terminal-id":s,className:(0,C.cn)("relative min-h-0 min-w-0 flex-1 flex-col",a?"flex":"hidden"),children:[(0,n.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:[(0,n.jsx)("div",{className:(0,C.cn)(P().viewport,"min-h-0 min-w-0 flex-1 overflow-auto p-2",u&&"invisible"),"data-testid":"terminal-viewport","aria-busy":!!v,onKeyDown:e=>e.stopPropagation(),children:(0,n.jsx)("div",{ref:d,className:P().canvas,"aria-label":i("terminalScreen")})}),v?(0,n.jsxs)("div",{role:"status",className:(0,C.cn)("pointer-events-none absolute flex items-center gap-2 text-muted-foreground",u?"inset-0 justify-center text-sm":"right-3 top-2 rounded-md bg-background/95 px-2 py-1 text-xs"),children:[(0,n.jsx)(b.A,{className:"size-4 shrink-0 motion-safe:animate-spin","aria-hidden":!0}),(0,n.jsx)("span",{children:v})]}):null,x?(0,n.jsxs)("div",{role:"alert",className:"absolute inset-x-2 top-2 flex items-center gap-2 rounded border bg-background px-3 py-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 break-words",children:x}),(0,n.jsx)(N.$,{variant:"outline",size:"sm",disabled:!c&&!l.ready,onClick:c?o.retry:e.retry,children:i("retry",{ns:"common"})})]}):null]}),t?(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto border-t px-2 py-1 pb-[max(.25rem,env(safe-area-inset-bottom))]",children:[(0,n.jsx)(N.$,{size:"sm",variant:"ghost",disabled:g,onClick:o.focus,children:i("terminalInput")}),(0,n.jsx)(N.$,{size:"sm",variant:"ghost",disabled:g,onPointerDown:e=>e.preventDefault(),onClick:()=>o.key("escape"),children:"Esc"}),(0,n.jsx)(N.$,{size:"sm",variant:"ghost",disabled:g,onPointerDown:e=>e.preventDefault(),onClick:()=>o.key("tab"),children:"Tab"}),(0,n.jsx)(N.$,{size:"sm",variant:m?"secondary":"ghost","aria-pressed":m,disabled:g,onPointerDown:e=>e.preventDefault(),onClick:o.toggleControl,children:"Ctrl"}),[{key:"left",Icon:E.A},{key:"up",Icon:A.A},{key:"down",Icon:$.A},{key:"right",Icon:R.A}].map(({key:e,Icon:t})=>(0,n.jsx)(N.$,{variant:"ghost",size:"icon-sm","aria-label":i(`terminalKey${e}`),disabled:g,onPointerDown:e=>e.preventDefault(),onClick:()=>o.key(e),children:(0,n.jsx)(t,{className:"size-4"})},e))]}):null]})}var O=s(37918),L=s(41513),F=s(24925),_=s(48155),B=s(84630),q=s(63013),W=s(85937),Y=s(49362),U=s(35592),V=s(23457),K=s(17708);function H({terminals:e,selectedId:t,tabStates:s,ready:a,busy:i,opening:l,mobile:o,right:d,maximized:c,onSelect:u,onClose:m,onCreate:p,onDock:h,onMaximize:g,onCollapse:x}){let{t:w}=(0,f.Bd)("workbench"),y=(0,r.useRef)(null),[k,j]=(0,r.useState)(!0);(0,r.useEffect)(()=>{let e=y.current;if(!e)return;let t=new ResizeObserver(([e])=>{e.contentRect.width>0&&j(e.contentRect.width<480)});return t.observe(e),()=>t.disconnect()},[]);let I=d?O.A:L.A,S=c?F.A:_.A,M=d?B.A:q.A,z=w(d?"terminalDockBottom":"terminalDockRight"),E=w(c?"terminalRestore":"terminalMaximize");return(0,n.jsxs)("header",{ref:y,className:"flex min-h-9 shrink-0 items-center gap-1 border-b bg-muted px-2 pt-[env(safe-area-inset-top)] lg:pt-0",children:[o?null:(0,n.jsx)(v.A,{className:"mr-1 size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{role:"tablist","aria-label":w("terminalTabs"),className:"flex min-w-0 shrink overflow-x-auto",children:[e.map(r=>{let l=r.terminalId===t,o=function(e){if(e.title)return e.title;let t=e.shell.split(/[\\/]/).pop().replace(/\.exe$/i,"");return/^(powershell|pwsh)$/i.test(t)?"PowerShell":t}(r),d=s[r.terminalId]?.error;return(0,n.jsxs)("div",{role:"presentation",className:(0,C.cn)("flex min-h-8 shrink-0 items-center border-b-2",l?"border-foreground bg-accent text-foreground":"border-transparent text-muted-foreground"),children:[(0,n.jsxs)("button",{type:"button",role:"tab",id:`terminal-tab-${r.terminalId}`,"aria-controls":`terminal-screen-${r.terminalId}`,"aria-selected":l,tabIndex:l?0:-1,title:`${o}
2
- ${r.cwd}${"exited"===r.status?`
3
- ${w("terminalExitCode",{code:r.exitCode??"—"})}`:""}${d?`
4
- ${d}`:""}`,"data-testid":"terminal-tab","data-terminal-id":r.terminalId,onClick:()=>u(r.terminalId),onKeyDown:t=>((t,s)=>{let n=e.findIndex(e=>e.terminalId===s),r="ArrowRight"===t.key?(n+1)%e.length:"ArrowLeft"===t.key?(n+e.length-1)%e.length:"Home"===t.key?0:"End"===t.key?e.length-1:null;if(null===r)return;t.preventDefault(),t.stopPropagation();let a=e[r].terminalId;u(a),document.getElementById(`terminal-tab-${a}`)?.focus({preventScroll:!0})})(t,r.terminalId),className:"flex min-h-8 min-w-0 cursor-pointer items-center gap-1 px-2 text-sm outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[(0,n.jsx)("span",{className:"max-w-48 truncate",children:o}),d?(0,n.jsx)(W.A,{className:"size-3.5 shrink-0 text-destructive","aria-label":d}):null,"exited"===r.status?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["\xb7 ",w("terminalExited")]}):null]}),(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost",disabled:!a||i,"aria-label":w("terminalCloseTab",{title:o}),title:w("terminalCloseTab",{title:o}),"data-testid":"terminal-tab-close","data-terminal-id":r.terminalId,onClick:e=>{e.stopPropagation(),m(r)},children:(0,n.jsx)(Y.A,{className:"size-4"})})]},r.terminalId)}),l&&e.length>0?(0,n.jsx)("span",{role:"status",className:"flex min-h-8 shrink-0 items-center px-2 text-sm text-muted-foreground",children:w("terminalOpening")}):null]}),(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost",className:"shrink-0",disabled:!a||i,"aria-label":w("newTerminal"),title:w("newTerminal"),"data-testid":"terminal-new",onClick:p,children:l?(0,n.jsx)(b.A,{className:"size-4 motion-safe:animate-spin","aria-hidden":!0}):(0,n.jsx)(U.A,{className:"size-4"})}),(0,n.jsx)("div",{className:"min-w-0 flex-1"}),!o&&k?(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost",className:"shrink-0","aria-label":w("terminalActions"),"data-testid":"terminal-actions"}),children:(0,n.jsx)(V.A,{className:"size-4"})}),(0,n.jsxs)(K.SQ,{align:"end",children:[(0,n.jsxs)(K._2,{"data-testid":"terminal-dock",onClick:h,children:[(0,n.jsx)(I,{}),z]}),(0,n.jsxs)(K._2,{"data-testid":"terminal-maximize",onClick:g,children:[(0,n.jsx)(S,{}),E]})]})]}):null,o||k?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost",className:"shrink-0","aria-label":z,title:z,"data-testid":"terminal-dock",onClick:h,children:(0,n.jsx)(I,{className:"size-4"})}),(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost",className:"shrink-0","aria-label":E,title:E,"data-testid":"terminal-maximize",onClick:g,children:(0,n.jsx)(S,{className:"size-4"})})]}),(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost",className:"shrink-0","aria-label":w("terminalCollapse"),title:w("terminalCollapse"),"data-testid":"terminal-collapse",onClick:x,children:(0,n.jsx)(M,{className:"size-4"})})]})}function G({biz:e,mobile:t,children:s}){let{t:a}=(0,f.Bd)("workbench"),i=(0,r.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot),l=i.terminals.length>0,o=i.expanded;(0,r.useEffect)(()=>{i.opening&&k().catch(e=>{console.warn("[Pi Desk][Terminal] 终端依赖预加载失败,将在画面加载时重试",{cause:e})})},[i.opening]);let{root:d,terminalPanel:c,preferences:u,right:m,maximized:p,pageVisible:h,setDock:g,toggleMaximized:x,saveSize:w,collapse:y,expand:j}=function(e,t,s){let[n,a]=(0,r.useState)(M),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(!0),m=(0,S.fk)(),p=(0,r.useRef)(null),h=(0,r.useRef)(null),g=!t&&"right"===n.dock;return(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{e&&(a(function(){try{let e=JSON.parse(localStorage.getItem(z)??"null");return{dock:e?.dock==="right"?"right":"bottom",height:"number"==typeof e?.height?Math.max(160,Math.min(1200,e.height)):M.height,width:"number"==typeof e?.width?Math.max(240,Math.min(1600,e.width)):M.width}}catch{return M}}()),l(!0))}),()=>{e=!1}},[]),(0,r.useEffect)(()=>{if(i)try{localStorage.setItem(z,JSON.stringify(n))}catch{}},[i,n]),(0,r.useLayoutEffect)(()=>{let e=requestAnimationFrame(()=>{m.current?.resize(s?t||o?"100%":g?n.width:n.height:0)});return()=>cancelAnimationFrame(e)},[s,o,t,n,g,m]),(0,r.useLayoutEffect)(()=>{if(!t)return;let e=window.visualViewport,s=()=>{let t=p.current;if(!t)return;let s=t.getBoundingClientRect().top,n=(e?.offsetTop??0)+(e?.height??window.innerHeight);t.style.setProperty("--terminal-visible-height",`${Math.max(120,n-s)}px`)};return s(),e?.addEventListener("resize",s),e?.addEventListener("scroll",s),window.addEventListener("resize",s),()=>{e?.removeEventListener("resize",s),e?.removeEventListener("scroll",s),window.removeEventListener("resize",s)}},[t]),(0,r.useEffect)(()=>{let t=()=>{let t="visible"===document.visibilityState;e.setPageVisible(t),u(t)};return t(),document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},[e]),{root:p,terminalPanel:m,preferences:n,right:g,maximized:o,pageVisible:c,setDock:()=>a(e=>({...e,dock:g?"bottom":"right"})),toggleMaximized:()=>d(e=>!e),saveSize:()=>{if(t||!s||o)return;let e=m.current?.getSize().inPixels;void 0!==e&&a(t=>({...t,[g?"width":"height"]:e}))},collapse:(0,r.useCallback)(()=>{e.setExpanded(!1),h.current?.isConnected&&h.current.focus({preventScroll:!0})},[e]),expand:()=>{h.current=document.activeElement instanceof HTMLElement?document.activeElement:null,e.setExpanded(!0)}}}(e,t,o),E=i.terminals.find(e=>e.terminalId===i.selectedId),A=o&&(t||p),$=(0,r.useCallback)(e=>{!t||!o||e.isTrusted||"Escape"!==e.key||e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||d.current?.closest("[inert]")||(e.preventDefault(),e.stopImmediatePropagation(),y())},[y,o,t,d]);return(0,r.useEffect)(()=>{if(t&&o)return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[o,$,t]),(0,n.jsxs)("div",{ref:d,className:(0,C.cn)("relative flex size-full min-h-0 min-w-0",m?"flex-row":"flex-col"),"data-terminal-dock":t?"mobile":u.dock,onKeyDownCapture:e=>{e.target instanceof Node&&e.currentTarget.contains(e.target)&&$(e.nativeEvent)},children:[(0,n.jsxs)(I.HK,{orientation:m?"horizontal":"vertical",disabled:t||!o||p,className:"min-h-0 min-w-0 flex-1",onLayoutChanged:(e,t)=>{t.isUserInteraction&&w()},children:[(0,n.jsx)(I.wV,{id:"terminal-workspace-chat",minSize:A||t?0:120,defaultSize:"100%","aria-hidden":A||void 0,inert:A||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:s}),(0,n.jsx)(I.WM,{disabled:t||!o||p,"aria-label":a("terminalResize"),"aria-hidden":!o||p||t||void 0,className:(0,C.cn)(t||!o||p?"hidden":m?"cursor-col-resize":"cursor-row-resize")}),(0,n.jsx)(I.wV,{id:"terminal-workspace-panel",panelRef:c,defaultSize:0,minSize:o?t||p?"100%":m?240:160:0,maxSize:o?t||p?"100%":"85%":0,className:"flex min-h-0 min-w-0 !overflow-hidden","aria-hidden":!o||void 0,inert:!o||void 0,children:(0,n.jsxs)("section",{className:(0,C.cn)("flex size-full min-h-0 min-w-0 flex-col bg-background",t&&P().mobile,!o&&"invisible"),"aria-label":a("terminal"),"data-testid":"terminal-panel",children:[(0,n.jsx)(H,{terminals:i.terminals,selectedId:i.selectedId,tabStates:i.tabs,ready:i.ready,busy:i.busy,opening:i.opening,mobile:t,right:m,maximized:p,onSelect:e.select,onClose:t=>{e.remove(t.terminalId)},onCreate:()=>{e.open(E?.cwd).catch(()=>void 0)},onDock:g,onMaximize:x,onCollapse:y}),i.error?(0,n.jsxs)("div",{role:"alert",className:"flex shrink-0 items-center gap-2 border-b px-3 py-1 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 break-words",children:i.error}),l?(0,n.jsx)(N.$,{size:"sm",variant:"ghost",disabled:!i.ready,onClick:e.retry,children:a("retry",{ns:"common"})}):null]}):null,!i.opening||l||i.error?null:(0,n.jsxs)("div",{role:"status",className:"flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-4 shrink-0 motion-safe:animate-spin","aria-hidden":!0}),(0,n.jsx)("span",{children:a("terminalOpening")})]}),i.terminals.map(s=>i.tabs[s.terminalId]?.retained?(0,n.jsx)(D,{terminalId:s.terminalId,biz:e,mobile:t,visible:o&&h&&s.terminalId===i.selectedId},s.terminalId):(0,n.jsx)("div",{role:"tabpanel",id:`terminal-screen-${s.terminalId}`,"aria-labelledby":`terminal-tab-${s.terminalId}`,hidden:!0},s.terminalId))]})})]}),l&&!o?(0,n.jsxs)("button",{type:"button","data-testid":"terminal-collapsed-bar",onClick:j,"aria-label":a("terminalExpand",{count:i.terminals.length}),className:(0,C.cn)("flex shrink-0 cursor-pointer items-center justify-center gap-2 border-t bg-muted text-sm text-muted-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",m?"w-9 flex-col border-l border-t-0":"min-h-8 px-3 pb-[env(safe-area-inset-bottom)] lg:pb-0"),children:[(0,n.jsx)(v.A,{className:"size-4"}),(0,n.jsx)("span",{children:i.terminals.length})]}):null]})}var J=s(74166),Q=s(51821),X=s(70943),Z=s(35995),ee=s(87733),et=s(90680),es=s(31052),en=s(6397),er=s(67069),ea=s(54379);a.Ik({}).strict();let ei=a.Ik({modes:en.f$,catalog:en.IS}).strict(),el=a.Ik({modes:en.f$}).strict(),eo=a.Ik({}).strict();var ed=s(73230);async function ec(e,t,s,n,r={}){let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r.signal}),i=await a.json();if(!a.ok||0!==i.code||null===i.data)throw Error(i.msg?(0,ed.B)(i):r.fallbackMessage??"请求失败");return n.parse(i.data)}var eu=s(73429),em=s(90458),ep=s(41148),eh=s(90213);let eg=`
5
- [data-pi-desk-ui-root]{box-sizing:border-box;min-width:0;max-width:100%;container-type:inline-size;color:var(--pi-desk-plugin-foreground,var(--foreground));font:inherit;font-size:.875rem;line-height:1.5}
6
- [data-pi-desk-ui-root] *,[data-pi-desk-ui-root] *::before,[data-pi-desk-ui-root] *::after{box-sizing:border-box}
7
- .pi-desk-ui-panel-header{display:grid;gap:.35rem;min-width:0;border-bottom:1px solid var(--pi-desk-plugin-border,var(--border));padding:1rem}
8
- .pi-desk-ui-panel-header-main{display:flex;min-width:0;align-items:flex-start;justify-content:space-between;gap:.75rem}.pi-desk-ui-panel-header-copy{display:grid;min-width:0;gap:.2rem}.pi-desk-ui-panel-header-title{margin:0;font-size:1.25rem;font-weight:600;line-height:1.4;color:inherit}.pi-desk-ui-panel-header-description{color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));font-size:.875rem;line-height:1.5;overflow-wrap:anywhere}.pi-desk-ui-panel-header-actions{display:flex;flex:none;align-items:center;gap:.4rem}.pi-desk-ui-panel-header-meta{display:flex;min-width:0;align-items:center;gap:.4rem;flex-wrap:wrap}
9
- .pi-desk-ui-panel-header-compact{gap:.25rem;padding:.75rem}.pi-desk-ui-panel-header-compact .pi-desk-ui-panel-header-title{font-size:.875rem}
10
- .pi-desk-ui-section{display:grid;min-width:0;gap:.6rem}.pi-desk-ui-section-header{display:flex;min-width:0;align-items:flex-start;justify-content:space-between;gap:.75rem}.pi-desk-ui-section-copy{display:grid;min-width:0;gap:.2rem}.pi-desk-ui-section-title{margin:0;font-size:.875rem;font-weight:600;line-height:1.5;color:var(--pi-desk-plugin-foreground,var(--foreground))}.pi-desk-ui-section-description{font-size:.875rem;line-height:1.5;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground))}.pi-desk-ui-section-action{display:flex;flex:none;align-items:center}.pi-desk-ui-section-content{min-width:0}.pi-desk-ui-section-compact{gap:.5rem}
11
- .pi-desk-ui-action-row{display:flex;min-width:0;align-items:center;gap:.5rem;flex-wrap:wrap}.pi-desk-ui-action-row-end{justify-content:flex-end}.pi-desk-ui-action-row-between{justify-content:space-between}
12
- .pi-desk-ui-tabs{display:flex;min-width:0;align-items:center;gap:.5rem;flex-wrap:wrap;border-bottom:1px solid var(--pi-desk-plugin-border,var(--border))}
13
- .pi-desk-ui-tab{display:inline-flex;min-height:2rem;align-items:center;justify-content:center;border:0;border-bottom:2px solid transparent;padding:.25rem .5rem;background:transparent;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));font:inherit;font-size:.875rem;font-weight:500;cursor:pointer;outline:none;transition:background-color 150ms ease-out,color 150ms ease-out}
14
- .pi-desk-ui-tab:hover{background:color-mix(in oklab,var(--foreground) 8%,transparent);color:var(--foreground)}
15
- .pi-desk-ui-tab[data-active="true"]{border-bottom-color:var(--foreground);color:var(--foreground)}.pi-desk-ui-tab:focus-visible{outline:2px solid var(--pi-desk-plugin-ring,var(--ring));outline-offset:2px}.pi-desk-ui-tab:disabled{cursor:not-allowed;opacity:.5}
16
- .pi-desk-ui-key-values{display:grid;min-width:0;gap:.5rem;margin:0}.pi-desk-ui-key-value{display:grid;min-width:0;grid-template-columns:minmax(5rem,auto) minmax(0,1fr) auto;align-items:start;gap:.3rem .65rem}.pi-desk-ui-key-value-label{color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));font-size:.75rem;line-height:1.45}.pi-desk-ui-key-value-value{min-width:0;margin:0;font-size:.875rem;line-height:1.5;overflow-wrap:anywhere}.pi-desk-ui-key-value-action{display:flex;align-items:center}.pi-desk-ui-key-values-compact{gap:.35rem}.pi-desk-ui-key-values-compact .pi-desk-ui-key-value{grid-template-columns:minmax(3.5rem,auto) minmax(0,1fr) auto;gap:.2rem .5rem}.pi-desk-ui-key-values-compact .pi-desk-ui-key-value-label{font-size:.75rem}.pi-desk-ui-key-values-stacked .pi-desk-ui-key-value{grid-template-columns:minmax(0,1fr);gap:.1rem}.pi-desk-ui-key-values-stacked .pi-desk-ui-key-value-action{justify-self:start}
17
- .pi-desk-ui-loading{display:flex;min-height:6rem;align-items:center;justify-content:center;gap:.5rem;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));font-size:.875rem;text-align:center}.pi-desk-ui-loading-error{display:grid;gap:.6rem}.pi-desk-ui-spinner{width:1rem;height:1rem;animation:pi-desk-ui-spin .8s linear infinite;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round}@keyframes pi-desk-ui-spin{to{transform:rotate(360deg)}}
18
- .pi-desk-ui-split{display:grid;grid-template-columns:minmax(11rem,13.5rem) minmax(0,1fr);gap:1rem;align-items:start}
19
- .pi-desk-ui-navigation,.pi-desk-ui-content{min-width:0;min-height:0}.pi-desk-ui-navigation{overflow:hidden}
20
- .pi-desk-ui-list{display:grid;gap:.375rem;min-width:0}.pi-desk-ui-list-compact{gap:.25rem}
21
- .pi-desk-ui-list-item{display:flex;width:100%;min-width:0;align-items:flex-start;gap:.625rem;border:1px solid transparent;border-radius:calc(var(--pi-desk-plugin-radius,var(--radius,.45rem)) + .25rem);padding:.7rem .75rem;background:transparent;color:inherit;text-align:left;font:inherit;cursor:pointer;outline:none;transition:background-color .15s,border-color .15s,color .15s}.pi-desk-ui-list-item-compact{gap:.45rem;border-radius:var(--pi-desk-plugin-radius,var(--radius,.45rem));padding:.5rem .55rem}
22
- .pi-desk-ui-list-item:hover{background:var(--pi-desk-plugin-muted,var(--muted))}
23
- .pi-desk-ui-list-item[aria-pressed="true"]{background:var(--accent);color:var(--accent-foreground)}
24
- .pi-desk-ui-list-item[aria-pressed="true"]:hover{background:color-mix(in oklab,var(--accent),var(--foreground) 5%)}
25
- .pi-desk-ui-list-item:focus-visible,.pi-desk-ui-button:focus-visible,.pi-desk-ui-control:focus-visible{outline:2px solid var(--pi-desk-plugin-ring,var(--ring));outline-offset:2px}
26
- .pi-desk-ui-list-item:disabled,.pi-desk-ui-button:disabled,.pi-desk-ui-control:disabled{cursor:not-allowed;opacity:.5}
27
- .pi-desk-ui-card{min-width:0;border:1px solid var(--pi-desk-plugin-border,var(--border));border-radius:.75rem;padding:1rem;background:var(--pi-desk-plugin-surface,var(--card));color:var(--pi-desk-plugin-surface-foreground,var(--card-foreground,var(--foreground)))}.pi-desk-ui-card-compact{border-radius:.5rem;padding:.75rem}
28
- .pi-desk-ui-markdown{min-width:0;font-size:var(--chat-body-font-size,1rem);line-height:1.7;color:inherit}
29
- .pi-desk-ui-markdown>*{margin-block:0}
30
- .pi-desk-ui-markdown :where(p){margin-block:0;line-height:1.7}
31
- .pi-desk-ui-markdown>:is(h1,h2,h3,h4,h5,h6){margin-block:0;font-weight:600;letter-spacing:-.015em}
32
- .pi-desk-ui-markdown>h1{font-size:1.5rem;line-height:1.3}
33
- .pi-desk-ui-markdown>h2{font-size:1.25rem;line-height:1.35}
34
- .pi-desk-ui-markdown>h3{font-size:1.125rem;line-height:1.4}
35
- .pi-desk-ui-markdown>h4{font-size:1rem;line-height:1.45}
36
- .pi-desk-ui-markdown>h5{font-size:.9375rem;line-height:1.5}
37
- .pi-desk-ui-markdown>h6{font-size:.875rem;line-height:1.5}
38
- .pi-desk-ui-markdown>h1:not(:first-child){margin-block-start:1rem}
39
- .pi-desk-ui-markdown>h2:not(:first-child){margin-block-start:.875rem}
40
- .pi-desk-ui-markdown>h3:not(:first-child){margin-block-start:.75rem}
41
- .pi-desk-ui-markdown>:is(h4,h5,h6):not(:first-child){margin-block-start:.625rem}
42
- .pi-desk-ui-markdown>:is(h1,h2,h3,h4,h5,h6)+*{margin-block-start:.375rem}
43
- .pi-desk-ui-markdown :where([data-streamdown="ordered-list"],[data-streamdown="unordered-list"]){margin-block:0}
44
- .pi-desk-ui-markdown [data-streamdown="list-item"]{padding-block:.125rem;line-height:1.625}
45
- .pi-desk-ui-markdown :where([data-streamdown="blockquote"]){margin-block:0;border-left-width:2px;padding-left:.75rem;line-height:1.6}
46
- .pi-desk-ui-markdown>*+*{margin-block-start:.5rem}
47
- .pi-desk-ui-markdown [data-streamdown="horizontal-rule"]{margin-block:.875rem}
48
- .pi-desk-ui-markdown a{color:inherit;text-decoration:underline;text-underline-offset:3px}
49
- /* Streamdown 的 200px 虚拟高度会在代码块首次可见时改变内容总高度。 */
50
- .pi-desk-ui-markdown [data-streamdown="code-block"]{position:relative;display:block;margin-block:.375rem;overflow:hidden;content-visibility:visible!important;contain-intrinsic-size:none!important;gap:0;padding:0;border:0;border-radius:var(--pi-desk-plugin-radius,var(--radius));background:var(--pi-desk-plugin-muted,var(--muted))}
51
- .pi-desk-ui-markdown>[data-streamdown="code-block"]+*{margin-block-start:.375rem}
52
- .pi-desk-ui-markdown>[data-streamdown="code-block"]+[data-streamdown="horizontal-rule"]{margin-block-start:.875rem}
53
- .pi-desk-ui-markdown [data-streamdown="code-block-header"]{display:none}
54
- .pi-desk-ui-markdown [data-streamdown="code-block-body"]{max-width:100%;overflow-x:auto;border:0;border-radius:0;background:transparent;padding:.5rem 2.5rem .5rem .875rem;font-size:var(--chat-code-font-size,.875rem);line-height:var(--chat-code-line-height,1.6)}
55
- .pi-desk-ui-markdown [data-streamdown="code-block-body"] pre,.pi-desk-ui-markdown [data-streamdown="code-block-body"] code{background:transparent;font-size:inherit;line-height:inherit;white-space:var(--pi-desk-code-white-space,pre-wrap);overflow-wrap:var(--pi-desk-code-overflow-wrap,anywhere)}
56
- .pi-desk-ui-markdown [data-streamdown="code-block-body"] code>span{display:block}
57
- .pi-desk-ui-markdown [data-streamdown="code-block-body"] code>span::before{display:none;content:none}
58
- .pi-desk-ui-markdown [data-streamdown="code-block"]>div:has(>[data-streamdown="code-block-actions"]){position:absolute;top:.25rem;right:.375rem;z-index:10;display:block;height:auto;margin:0;pointer-events:none}
59
- .pi-desk-ui-markdown [data-streamdown="code-block-actions"]{pointer-events:auto;gap:0;border:0;background:var(--pi-desk-plugin-muted,var(--muted));padding:0;opacity:0;box-shadow:none;backdrop-filter:none;transition:opacity 120ms ease}
60
- .pi-desk-ui-markdown [data-streamdown="code-block-actions"]>button{display:flex;width:1.75rem;height:1.75rem;align-items:center;justify-content:center;border-radius:.375rem;padding:0}
61
- .pi-desk-ui-markdown [data-streamdown="code-block-actions"]>button:hover{background:var(--accent);color:var(--accent-foreground)}
62
- .pi-desk-ui-markdown [data-streamdown="code-block"]:hover [data-streamdown="code-block-actions"],.pi-desk-ui-markdown [data-streamdown="code-block"]:focus-within [data-streamdown="code-block-actions"]{opacity:1}
63
- @media(hover:none),(max-width:640px){.pi-desk-ui-markdown [data-streamdown="code-block-actions"]{opacity:1}}
64
- .pi-desk-ui-markdown table{display:block;max-width:100%;overflow:auto;border-collapse:collapse}.pi-desk-ui-markdown :where(th,td){border:1px solid var(--pi-desk-plugin-border,var(--border));padding:.4rem .55rem;text-align:left}
65
- .pi-desk-ui-markdown hr{border:0;border-top:1px solid var(--pi-desk-plugin-border,var(--border))}
66
- .pi-desk-ui-markdown img{max-width:100%;height:auto}
67
- .pi-desk-ui-button {
68
- display: inline-flex;
69
- min-height: 2rem;
70
- align-items: center;
71
- justify-content: center;
72
- gap: .5rem;
73
- border: 1px solid transparent;
74
- border-radius: .5rem;
75
- padding: .25rem .5rem;
76
- font: inherit;
77
- font-size: .875rem;
78
- font-weight: 500;
79
- line-height: 1.5;
80
- white-space: nowrap;
81
- cursor: pointer;
82
- outline: none;
83
- transition: background-color 150ms ease-out, color 150ms ease-out, border-color 150ms ease-out;
84
- }
85
- .pi-desk-ui-button-sm, .pi-desk-ui-button-xs {
86
- min-height: 1.75rem;
87
- border-radius: .375rem;
88
- padding: .125rem .5rem;
89
- }
90
- .pi-desk-ui-button svg { width: 1rem; height: 1rem; flex: none; }
91
- .pi-desk-ui-button-primary{background:var(--pi-desk-plugin-primary,var(--primary));color:var(--pi-desk-plugin-primary-foreground,var(--primary-foreground))}
92
- .pi-desk-ui-button-primary:hover{background:color-mix(in oklab,var(--pi-desk-plugin-primary,var(--primary)),var(--pi-desk-plugin-primary-foreground,var(--primary-foreground)) 8%)}
93
- .pi-desk-ui-button-primary:active{background:color-mix(in oklab,var(--pi-desk-plugin-primary,var(--primary)),var(--pi-desk-plugin-primary-foreground,var(--primary-foreground)) 14%)}
94
- .pi-desk-ui-button-secondary{background:var(--secondary);color:var(--secondary-foreground)}
95
- .pi-desk-ui-button-secondary:hover{background:color-mix(in oklab,var(--secondary),var(--foreground) 8%)}
96
- .pi-desk-ui-button-secondary:active{background:color-mix(in oklab,var(--secondary),var(--foreground) 14%)}
97
- .pi-desk-ui-button-ghost:hover{background:color-mix(in oklab,var(--foreground) 8%,transparent);color:var(--foreground)}
98
- .pi-desk-ui-button-ghost:active{background:color-mix(in oklab,var(--foreground) 14%,transparent)}
99
- .pi-desk-ui-button-danger{border-color:color-mix(in srgb,var(--pi-desk-plugin-destructive,var(--destructive)) 45%,transparent);background:color-mix(in srgb,var(--pi-desk-plugin-destructive,var(--destructive)) 12%,transparent);color:var(--pi-desk-plugin-destructive,var(--destructive))}
100
- .pi-desk-ui-button-danger:hover{background:color-mix(in srgb,var(--pi-desk-plugin-destructive,var(--destructive)) 20%,transparent)}
101
- .pi-desk-ui-button-ghost{background:transparent;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground))}
102
- .pi-desk-ui-button[aria-pressed="true"]{background:var(--accent);color:var(--accent-foreground)}
103
- .pi-desk-ui-button[aria-pressed="true"]:hover{background:color-mix(in oklab,var(--accent),var(--foreground) 5%)}
104
- .pi-desk-ui-context-menu-positioner{z-index:1020;outline:none}.pi-desk-ui-context-menu{max-height:min(20rem,var(--available-height));min-width:10rem;overflow:auto;border:1px solid var(--pi-desk-plugin-border,var(--border));border-radius:calc(var(--pi-desk-plugin-radius,var(--radius,.45rem)) + .2rem);padding:.25rem;background:var(--pi-desk-plugin-popover,var(--popover,var(--card)));color:var(--pi-desk-plugin-popover-foreground,var(--popover-foreground,var(--foreground)));box-shadow:0 .6rem 1.6rem color-mix(in srgb,#000 22%,transparent);transform-origin:var(--transform-origin);outline:none;transition:transform .1s ease-out,opacity .1s ease-out}.pi-desk-ui-context-menu[data-starting-style],.pi-desk-ui-context-menu[data-ending-style]{opacity:0;transform:scale(.98)}.pi-desk-ui-context-menu-item{display:flex;min-height:1.75rem;align-items:center;gap:.5rem;border-radius:.375rem;padding:.25rem .5rem;font:inherit;font-size:.875rem;line-height:1.5;cursor:pointer;outline:none;user-select:none}.pi-desk-ui-context-menu-item[data-highlighted]{background:var(--accent);color:var(--accent-foreground)}.pi-desk-ui-context-menu-item[data-disabled]{pointer-events:none;opacity:.5}
105
- .pi-desk-ui-badge{display:inline-flex;min-height:1.25rem;align-items:center;border-radius:.375rem;padding:.0625rem .375rem;font-size:.75rem;line-height:1.5;font-weight:500;white-space:nowrap}
106
- .pi-desk-ui-badge-neutral{background:var(--pi-desk-plugin-muted,var(--muted));color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground))}
107
- .pi-desk-ui-badge-info{background:var(--muted);color:var(--foreground)}
108
- .pi-desk-ui-badge-success{background:var(--muted);color:var(--status-success,var(--foreground))}
109
- .pi-desk-ui-badge-warning{background:var(--muted);color:var(--status-warning,var(--foreground))}
110
- .pi-desk-ui-badge-error{background:var(--muted);color:var(--pi-desk-plugin-destructive,var(--destructive))}
111
- .pi-desk-ui-alert{border:1px solid var(--pi-desk-plugin-border,var(--border));border-radius:calc(var(--pi-desk-plugin-radius,var(--radius,.45rem)) + .25rem);padding:.75rem .85rem;background:color-mix(in srgb,var(--pi-desk-plugin-muted,var(--muted)) 70%,transparent);color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));line-height:1.5}.pi-desk-ui-alert-compact{border-radius:.5rem;padding:.75rem;font-size:.875rem}
112
- .pi-desk-ui-alert-info{border-color:color-mix(in srgb,var(--pi-desk-plugin-primary,var(--primary)) 35%,var(--pi-desk-plugin-border,var(--border)))}
113
- .pi-desk-ui-alert-warning{border-color:color-mix(in oklab,var(--status-warning,var(--foreground)) 45%,var(--border));color:var(--pi-desk-plugin-foreground,var(--foreground))}
114
- .pi-desk-ui-alert-error{border-color:color-mix(in srgb,var(--pi-desk-plugin-destructive,var(--destructive)) 42%,var(--pi-desk-plugin-border,var(--border)));color:var(--pi-desk-plugin-destructive,var(--destructive))}
115
- .pi-desk-ui-dialog-backdrop{position:fixed;inset:0;z-index:1000;background:rgb(0 0 0 / .35)}.pi-desk-ui-dialog{position:fixed;top:50%;left:50%;z-index:1010;display:flex;max-height:calc(100dvh - 2rem);width:calc(100vw - 2rem);max-width:27.5rem;transform:translate(-50%,-50%);flex-direction:column;overflow:hidden;container-type:inline-size;border:1px solid var(--pi-desk-plugin-border,var(--border));border-radius:.75rem;font-size:.875rem;line-height:1.5;background:var(--pi-desk-plugin-popover,var(--popover,var(--card)));color:var(--pi-desk-plugin-popover-foreground,var(--popover-foreground,var(--foreground)));box-shadow:0 .5rem 1.5rem rgb(0 0 0 / .18);outline:none}.pi-desk-ui-dialog-sm{max-width:20rem}.pi-desk-ui-dialog-lg{max-width:45rem}.pi-desk-ui-dialog-header{display:grid;flex:none;gap:.2rem;border-bottom:1px solid var(--pi-desk-plugin-border,var(--border));padding:1rem 3.5rem 1rem 1rem}.pi-desk-ui-dialog-title{margin:0;font-size:1.125rem;font-weight:600;line-height:1.4}.pi-desk-ui-dialog-description{font-size:.875rem;line-height:1.5;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));overflow-wrap:anywhere}.pi-desk-ui-dialog-close{position:absolute;top:.5rem;right:.5rem;display:inline-flex;width:2rem;height:2rem;align-items:center;justify-content:center;border:0;border-radius:var(--pi-desk-plugin-radius,var(--radius,.45rem));background:transparent;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));font:inherit;font-size:1.25rem;cursor:pointer;outline:none}.pi-desk-ui-dialog-close:hover{background:var(--pi-desk-plugin-muted,var(--muted));color:var(--pi-desk-plugin-foreground,var(--foreground))}.pi-desk-ui-dialog-close:focus-visible{outline:2px solid var(--pi-desk-plugin-ring,var(--ring));outline-offset:2px}.pi-desk-ui-dialog-scroll{min-height:0;flex:1}.pi-desk-ui-dialog-body{min-height:0;padding:1rem}.pi-desk-ui-dialog-footer{display:flex;flex:none;flex-wrap:wrap;justify-content:flex-end;gap:.5rem;border-top:1px solid var(--pi-desk-plugin-border,var(--border));padding:.75rem 1rem}.pi-desk-ui-empty{display:flex;align-items:center;justify-content:center;padding:1.5rem 1rem;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));font-size:.875rem;text-align:center;line-height:1.5}
116
- .pi-desk-ui-field{display:grid;gap:.25rem;min-width:0}
117
- .pi-desk-ui-field-label{font-size:.875rem;font-weight:500;color:var(--pi-desk-plugin-foreground,var(--foreground))}
118
- .pi-desk-ui-field-description,.pi-desk-ui-field-error{font-size:.875rem;line-height:1.5;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground))}
119
- .pi-desk-ui-field-error{color:var(--pi-desk-plugin-destructive,var(--destructive))}
120
- .pi-desk-ui-control {
121
- width: 100%;
122
- min-height: 2rem;
123
- border: 1px solid var(--pi-desk-plugin-input,var(--input));
124
- border-radius: .5rem;
125
- padding: .25rem .625rem;
126
- background: var(--pi-desk-plugin-surface,var(--card));
127
- color: var(--pi-desk-plugin-foreground,var(--foreground));
128
- font: inherit;
129
- font-size: .875rem;
130
- line-height: 1.5;
131
- outline: none;
132
- }
133
- .pi-desk-ui-control-sm{min-height:1.75rem;border-radius:.375rem;padding:.125rem .625rem}
134
- .pi-desk-ui-control:focus-visible{outline-offset:-2px}
135
- .pi-desk-ui-control[aria-invalid="true"]{border-color:var(--destructive);outline-color:var(--destructive)}
136
- .pi-desk-ui-checkbox{appearance:none;display:inline-grid;width:1rem;height:1rem;flex:none;place-content:center;border:1px solid var(--pi-desk-plugin-input,var(--input,var(--border)));border-radius:.25rem;background:var(--pi-desk-plugin-background,var(--background));color:var(--pi-desk-plugin-primary-foreground,var(--primary-foreground));cursor:pointer;outline:none;transition:background-color .15s,border-color .15s,box-shadow .15s}.pi-desk-ui-checkbox::before{content:"";width:.68rem;height:.68rem;transform:scale(0);transform-origin:center;clip-path:polygon(14% 44%,0 59%,38% 100%,100% 22%,84% 8%,37% 70%);background:currentColor;transition:transform .12s ease}.pi-desk-ui-checkbox:checked{border-color:var(--pi-desk-plugin-primary,var(--primary));background:var(--pi-desk-plugin-primary,var(--primary))}.pi-desk-ui-checkbox:checked::before{transform:scale(1)}.pi-desk-ui-checkbox:hover:not(:disabled){border-color:color-mix(in srgb,var(--pi-desk-plugin-primary,var(--primary)) 65%,var(--pi-desk-plugin-input,var(--input,var(--border))))}.pi-desk-ui-checkbox:focus-visible{outline:2px solid var(--pi-desk-plugin-ring,var(--ring));outline-offset:2px}.pi-desk-ui-checkbox:disabled{cursor:not-allowed;opacity:.5}
137
- .pi-desk-ui-secret{position:relative;min-width:0}
138
- .pi-desk-ui-secret .pi-desk-ui-control{padding-right:2.25rem}
139
- .pi-desk-ui-secret-control{-webkit-text-security:disc}
140
- .pi-desk-ui-secret-toggle{position:absolute;top:50%;right:.25rem;display:inline-flex;width:1.5rem;height:1.5rem;align-items:center;justify-content:center;transform:translateY(-50%);border:0;border-radius:.375rem;background:transparent;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground));cursor:pointer;outline:none}
141
- .pi-desk-ui-secret-toggle:hover{background:var(--pi-desk-plugin-muted,var(--muted));color:var(--pi-desk-plugin-foreground,var(--foreground))}
142
- .pi-desk-ui-secret-toggle:focus-visible{box-shadow:0 0 0 2px var(--pi-desk-plugin-ring,var(--ring))}
143
- .pi-desk-ui-secret-toggle:disabled{pointer-events:none;opacity:.5}
144
- .pi-desk-ui-secret-toggle svg{width:.875rem;height:.875rem}
145
- textarea.pi-desk-ui-control{min-height:13rem;resize:vertical;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;line-height:1.5}textarea.pi-desk-ui-control-sm{min-height:7rem}
146
- .pi-desk-ui-control::placeholder{color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground))}
147
- .pi-desk-ui-select-trigger{display:flex;width:100%;min-width:0;max-width:100%;min-height:2rem;align-items:center;justify-content:space-between;gap:.5rem;border:1px solid var(--pi-desk-plugin-input,var(--input));border-radius:.5rem;padding:.25rem .625rem;background:var(--pi-desk-plugin-surface,var(--card));color:var(--pi-desk-plugin-foreground,var(--foreground));font:inherit;font-size:.875rem;line-height:1.5;text-align:left;outline:none;cursor:pointer}.pi-desk-ui-select-trigger:hover{background:var(--accent)}.pi-desk-ui-select-trigger:focus-visible{outline:2px solid var(--pi-desk-plugin-ring,var(--ring));outline-offset:-2px}.pi-desk-ui-select-trigger[data-disabled]{cursor:not-allowed;opacity:.5}.pi-desk-ui-select-trigger-sm{min-height:1.75rem;border-radius:.375rem;padding:.125rem .625rem}.pi-desk-ui-select-value{min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pi-desk-ui-select-value[data-placeholder]{color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground))}.pi-desk-ui-select-icon{display:inline-flex;width:1rem;height:1rem;flex:none;color:var(--pi-desk-plugin-muted-foreground,var(--muted-foreground))}.pi-desk-ui-select-icon svg,.pi-desk-ui-select-indicator svg{width:100%;height:100%;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
148
- .pi-desk-ui-select-positioner{z-index:1020}.pi-desk-ui-select-popup{max-height:min(20rem,var(--available-height));min-width:max(9rem,var(--anchor-width));overflow:auto;border:1px solid var(--pi-desk-plugin-border,var(--border));border-radius:calc(var(--pi-desk-plugin-radius,var(--radius,.45rem)) + .2rem);padding:.25rem;background:var(--pi-desk-plugin-popover,var(--popover,var(--card)));color:var(--pi-desk-plugin-popover-foreground,var(--popover-foreground,var(--foreground)));box-shadow:0 .6rem 1.6rem color-mix(in srgb,#000 22%,transparent);outline:none}.pi-desk-ui-select-item{position:relative;display:flex;min-height:2rem;align-items:center;gap:.5rem;border-radius:var(--pi-desk-plugin-radius,var(--radius,.45rem));padding:.35rem 2rem .35rem .55rem;font-size:.875rem;line-height:1.5;cursor:pointer;outline:none}.pi-desk-ui-select-item[data-highlighted]{background:var(--accent);color:var(--accent-foreground)}.pi-desk-ui-select-item[data-disabled]{pointer-events:none;opacity:.5}.pi-desk-ui-select-indicator{position:absolute;right:.55rem;display:inline-flex;width:.9rem;height:.9rem;align-items:center;justify-content:center;color:var(--pi-desk-plugin-primary,var(--primary))}
149
- @container (max-width:40rem){.pi-desk-ui-split{grid-template-columns:minmax(0,1fr)}.pi-desk-ui-split-navigation-scroll{height:auto;max-height:11rem}}
150
- @media(prefers-reduced-motion:reduce){.pi-desk-ui-button,.pi-desk-ui-list-item,.pi-desk-ui-context-menu{transition:none}}
151
- @container (max-width:28rem){.pi-desk-ui-action-row-mobile-stack{align-items:flex-start;flex-direction:column}.pi-desk-ui-key-value{grid-template-columns:minmax(0,1fr)}.pi-desk-ui-key-value-action{justify-self:start}}
152
- `;function ex(...e){return e.filter(Boolean).join(" ")}function ef({className:e,children:t,...s}){return(0,n.jsxs)("div",{...s,"data-pi-desk-ui-root":"",className:ex("pi-desk-ui-root",e),children:[(0,n.jsx)("style",{href:"pi-desk-ui",precedence:"pi-desk-ui",children:eg}),t]})}function eb({className:e,...t}){return(0,n.jsx)("input",{...t,type:"checkbox",className:ex("pi-desk-ui-checkbox",e)})}r.Component;var ev=s(84942);let ew=[{key:"all",label:"policyAll"},{key:"allow",label:"policyAllow"},{key:"deny",label:"policyDeny"},{key:"none",label:"policyNone"}];function ey({label:e,rule:t,options:s,disabled:a,onChange:i}){let{t:l}=(0,f.Bd)("capabilityModes"),[o,d]=(0,r.useState)(()=>void 0!==t.allow?0===t.allow.length?"none":"allow":t.deny?.length?"deny":"all"),[c,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)(!1),[x,b]=(0,r.useState)(160),[v,w]=(0,r.useState)(()=>[...new Set([...t.allow??[],...t.deny??[]])]),y="deny"===o||"all"===o||"allow"===o&&c?"deny":"allow",k=t[y]??[],j=new Set(k),I=(0,r.useMemo)(()=>{let e=new Map(s.map(e=>[e.value,e]));for(let s of[...v,...t.allow??[],...t.deny??[]])e.has(s)||e.set(s,{value:s});return[...e.values()].sort((e,t)=>e.value.localeCompare(t.value))},[v,s,t.allow,t.deny]),S=m.trim(),M=I.filter(e=>(!h||!!j.has(e.value))&&(!S||`${e.value} ${e.label??""} ${e.description??""}`.toLowerCase().includes(S.toLowerCase())||S.includes("*")&&(0,ev.RC)({allow:[S]},e.value))),z=M.slice(0,x),E=S.length>0&&S.length<=256&&!j.has(S);function A(e){"all"===o&&e.length>0&&d("deny"),"none"===o&&e.length>0&&d("allow"),i({...t,[y]:e})}function $(e,t){A(t?[...new Set([...k,e])]:k.filter(t=>t!==e))}function R(){E&&!a&&(w(e=>[...new Set([...e,S])]),$(S,!0),p(""))}return(0,n.jsxs)(ef,{className:"flex min-h-0 flex-1 flex-col","aria-label":l("ruleEditor",{name:e}),children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 border-b px-4 py-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("div",{className:"flex flex-wrap gap-1",role:"group","aria-label":l("ruleMode",{name:e}),children:ew.map(e=>(0,n.jsxs)(N.$,{size:"sm",variant:o===e.key?"secondary":"ghost","aria-pressed":o===e.key,disabled:a,onClick:()=>{var s;d(s=e.key),u(!1),g(!1),"all"===s?i({}):"none"===s?i({allow:[]}):"deny"===s?i({deny:t.deny??[]}):i({allow:t.allow??[],...t.deny?.length?{deny:t.deny}:{}})},children:[o===e.key&&(0,n.jsx)(em.A,{className:"size-3.5"}),l(e.label)]},e.key))}),"allow"===o&&(0,n.jsxs)(N.$,{size:"sm",variant:c?"secondary":"ghost",disabled:a,"aria-pressed":c,onClick:()=>{u(!c),g(!1)},children:[l("exclusions"),t.deny?.length?` \xb7 ${t.deny.length}`:""]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,n.jsx)(ep.A,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(eu.p,{"aria-label":l("ruleSearch"),placeholder:l("ruleSearchPlaceholder"),maxLength:256,className:"pl-9 pr-9",value:m,disabled:a,onChange:e=>{p(e.target.value),b(160)},onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),R())}}),m&&(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost","aria-label":l("clearSearch"),className:"absolute right-0.5 top-1/2 -translate-y-1/2",onClick:()=>p(""),children:(0,n.jsx)(Y.A,{className:"size-3.5"})})]}),(0,n.jsxs)(N.$,{size:"sm",variant:h?"secondary":"ghost","aria-pressed":h,onClick:()=>g(!h),children:[(0,n.jsx)(eh.A,{className:"size-4"}),(0,n.jsx)("span",{className:"hidden @min-[420px]:inline",children:l("selectedOnly")}),(0,n.jsx)("span",{className:"@min-[420px]:hidden",children:l("selectedShort")})]})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:[l("allow"===y?"allowRules":"excludeRules")," \xb7"," ",l("selectedCount",{count:k.length})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.jsx)(N.$,{size:"sm",variant:"ghost",disabled:a||0===z.length,onClick:()=>A([...new Set([...k,...z.map(e=>e.value)])]),children:l("selectVisible")}),k.length>0&&(0,n.jsx)(N.$,{size:"sm",variant:"ghost",disabled:a,onClick:()=>A([]),children:l("clearSelected")})]})]})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain p-3",children:[E&&(0,n.jsxs)(N.$,{variant:"outline",disabled:a,className:"mb-3 h-auto min-h-9 max-w-full justify-start",onClick:R,children:[(0,n.jsx)(U.A,{className:"size-4 shrink-0"}),l("addRule")," ",(0,n.jsx)("span",{className:"min-w-0 truncate font-mono",children:S})]}),(0,n.jsx)("div",{className:"grid min-w-0 grid-cols-1 gap-1 @min-[620px]:grid-cols-2",children:z.map(e=>{let t=j.has(e.value);return(0,n.jsxs)("label",{className:(0,C.cn)("flex min-h-9 min-w-0 cursor-pointer items-start gap-3 rounded-lg px-3 py-2 transition-colors hover:bg-muted",t&&"bg-accent text-accent-foreground",a&&"pointer-events-none opacity-50"),children:[(0,n.jsx)(eb,{checked:t,disabled:a,"aria-label":l("allow"===y?"allowValue":"excludeValue",{name:e.value}),className:"mt-1 shrink-0",onChange:t=>$(e.value,t.target.checked)}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block break-all text-sm font-medium",children:e.label??e.value}),e.label&&e.label!==e.value&&(0,n.jsx)("span",{className:"block break-all font-mono text-xs text-muted-foreground",children:e.value}),e.description?(0,n.jsxs)("details",{className:"mt-0.5 text-xs leading-5 text-muted-foreground",onClick:e=>e.stopPropagation(),children:[(0,n.jsx)("summary",{className:"line-clamp-1 cursor-pointer list-none",children:e.description}),(0,n.jsx)("span",{className:"block whitespace-pre-wrap break-words pt-1 text-sm",children:e.description})]}):e.value.includes("*")?(0,n.jsx)("span",{className:"block text-xs text-muted-foreground",children:l("pattern")}):null]})]},e.value)})}),0===z.length&&(0,n.jsx)("p",{className:"px-3 py-6 text-sm text-muted-foreground",children:S?l("noMatches"):h?l("noSelection"):l("enterPattern")}),M.length>z.length&&(0,n.jsx)(N.$,{variant:"ghost",className:"mt-3",onClick:()=>b(e=>e+160),children:l("moreRules",{count:M.length-z.length})})]})]})}function ek({modeKey:e,mode:t,catalog:s,disabled:a,onChange:i}){var l;let{t:o}=(0,f.Bd)("capabilityModes"),d=(0,r.useMemo)(()=>(function(e,t,s){let n=[{key:"tools",label:s,options:e?.tools??[],target:{kind:"tools"}},{key:"skills",label:"Skills",options:e?.skills??[],target:{kind:"skills"}}];for(let s of new Set([...Object.keys(e?.plugins??{}),...Object.keys(t.plugins??{})])){let r=e?.plugins[s]??{};for(let e of new Set([...Object.keys(r),...Object.keys(t.plugins?.[s]??{})]))n.push({key:`plugin:${s}:${e}`,label:r[e]?.label??`${s} / ${e}`,options:r[e]?.options??[],target:{kind:"plugin",pluginName:s,group:e}})}return n})(s,t,o("groupTools")),[s,t,o]),[c,u]=(0,r.useState)("tools"),m=d.find(e=>e.key===c)??d[0];return(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-3",children:(0,n.jsxs)("label",{className:"flex max-w-xl flex-wrap items-center gap-2 text-sm font-medium",children:[(0,n.jsx)("span",{children:o("modeName")}),(0,n.jsx)(eu.p,{"aria-label":o("modeName"),value:t.name,maxLength:64,disabled:a,className:"min-w-40 flex-1",onChange:e=>i({...t,name:e.target.value})})]})}),(0,n.jsx)("div",{className:"flex shrink-0 flex-wrap gap-1 border-b px-4 py-2",role:"tablist","aria-label":o("category"),children:d.map(e=>(0,n.jsx)(N.$,{variant:e.key===m.key?"secondary":"ghost",size:"sm",role:"tab","aria-selected":e.key===m.key,onClick:()=>u(e.key),children:e.label},e.key))}),(0,n.jsx)(ey,{label:m.label,rule:"plugin"===(l=m.target).kind?t.plugins?.[l.pluginName]?.[l.group]??{}:t[l.kind]??{},options:m.options,disabled:a,onChange:e=>i(function(e,t,s){let n={...void 0===s.allow?{}:{allow:[...new Set(s.allow)]},...s.deny?.length?{deny:[...new Set(s.deny)]}:{}},r=0===Object.keys(n).length;if("plugin"!==t.kind){let s={...e};return r?delete s[t.kind]:s[t.kind]=n,s}let a={...e.plugins?.[t.pluginName]};r?delete a[t.group]:a[t.group]=n;let i={...e.plugins};Object.keys(a).length?i[t.pluginName]=a:delete i[t.pluginName];let l={...e};return Object.keys(i).length?l.plugins=i:delete l.plugins,l}(t,m.target,e))},`${e}:${m.key}`)]})}var ej=s(5464);function eN({open:e,deleteName:t,saving:s,error:r,onCancel:a,onDelete:i,onLeave:l}){let{t:o}=(0,f.Bd)("capabilityModes");return(0,n.jsx)(ej.YV,{open:e,onOpenChange:e=>{e||s||a()},children:(0,n.jsxs)(ej.hA,{className:"z-[150]",showCloseButton:!s,children:[(0,n.jsxs)(ej.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(ej.YM,{children:o(t?"deleteConfirm":"saveConfirm")}),(0,n.jsx)(ej.uX,{children:t?o("deleteDescription",{name:t}):o("unsavedDescription")})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-3 text-sm text-destructive",children:r}),(0,n.jsxs)(ej.vu,{children:[(0,n.jsx)(N.$,{variant:"outline",disabled:s,onClick:a,children:o("cancel")}),t?(0,n.jsx)(N.$,{variant:"destructive",onClick:i,children:o("delete")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{variant:"ghost",disabled:s,onClick:()=>l("discard"),children:o("discard")}),(0,n.jsx)(N.$,{disabled:s,onClick:()=>l("save"),children:o(s?"saving":"saveContinue")})]})]})]})})}function eI({modeNames:e,onBeforeLeaveChange:t}){let{t:s}=(0,f.Bd)("capabilityModes"),{clientId:a}=(0,er.gM)(),i=(0,Q.G)(),l=function(e){let{t}=(0,f.Bd)("capabilityModes"),[s,n]=(0,r.useState)(null),[a,i]=(0,r.useState)({}),[l,o]=(0,r.useState)(null),[d,c]=(0,r.useState)(null),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(!1),[g,x]=(0,r.useState)(null),[b,v]=(0,r.useState)(!1),w=(0,r.useRef)(null),y=(0,r.useRef)(null),k=null!==s&&JSON.stringify(s)!==JSON.stringify(a);(0,r.useEffect)(()=>{let e=new AbortController;return y.current=e,()=>{e.abort(),w.current?.(!1),w.current=null}},[]);let j=(0,r.useCallback)(async(r=!1)=>{if(null!==s&&!r)return a;m(!0),x(null);try{let t=await e.get(y.current?.signal);if(y.current?.signal.aborted)return null;return o(t.catalog),null!==s&&k||(n(t.modes),i(structuredClone(t.modes))),null!==s&&k?a:t.modes}catch(e){return y.current?.signal.aborted||x(e instanceof Error?e.message:t("catalogFailed")),null}finally{y.current?.signal.aborted||m(!1)}},[e,k,a,s,t]),N=(0,r.useCallback)(async e=>{if(null===e)return void c(null);let t=await j();t&&Object.hasOwn(t,e)&&c(e)},[j]),I=(0,r.useCallback)(async(e=!1)=>{let s=await j();if(!s)return;let n=e&&d?s[d]:void 0,r=crypto.randomUUID(),a=function(e,t){let s=new Set(Object.values(e).map(e=>e.name));if(!s.has(t))return t;let n=2;for(;s.has(`${t} ${n}`);)n+=1;return`${t} ${n}`}(s,n?t("copySuffix",{name:n.name}):t("newMode"));i({...s,[r]:{...n?structuredClone(n):{},name:a}}),c(r)},[j,d,t]),C=(0,r.useCallback)(e=>{d&&i(t=>({...t,[d]:e}))},[d]),S=(0,r.useCallback)(()=>{d&&(i(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==d))),c(null))},[d]),M=(0,r.useCallback)(async()=>{if(!k)return!0;h(!0),x(null);try{let t=await e.replace(a,y.current?.signal);if(y.current?.signal.aborted)return!1;return n(t),i(structuredClone(t)),!0}catch(e){return y.current?.signal.aborted||x(e instanceof Error?e.message:t("saveFailed")),!1}finally{y.current?.signal.aborted||h(!1)}},[e,k,a,t]),z=(0,r.useCallback)(()=>k?(v(!0),new Promise(e=>{w.current=e})):Promise.resolve(!0),[k]);return{draft:a,saved:s,catalog:l,selected:d,loading:u,saving:p,error:g,dirty:k,leaveOpen:b,beforeLeave:z,decideLeave:(0,r.useCallback)(async e=>{("save"!==e||await M())&&(v(!1),w.current?.("cancel"!==e),w.current=null)},[M]),load:j,select:N,add:I,update:C,remove:S,save:M}}((0,r.useMemo)(()=>(function(e){async function t(t,s,n,r){return ec(e,t,s,n,{signal:r,fallbackMessage:(0,ed.B)({msg:"能力模式请求失败",i18n:{key:"errors:capabilityFailed"}})})}return{get:e=>t("/api/capability-modes/get",{},ei,e),async replace(e,s){let n=el.safeParse({modes:e});if(!n.success)throw Error((0,ed.B)({msg:"请检查模式规则",i18n:{key:"errors:capabilityRuleInvalid"}}));return await t("/api/capability-modes/replace",n.data,eo,s),n.data.modes}}})(a),[a])),[o,d]=(0,r.useState)(null),{beforeLeave:c}=l;(0,r.useEffect)(()=>(t(c),()=>t(null)),[c,t]);let u=null===l.saved?e:(0,en.HE)(l.draft),m=l.selected?l.draft[l.selected]:void 0,p=l.loading||l.saving,h=async()=>{await l.save()&&i.success(s("saved"))},g=(0,n.jsxs)(N.$,{size:"sm",disabled:!l.dirty||p,onClick:()=>void h(),children:[l.saving?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(X.A,{className:"size-4"}),l.saving?s("saving"):s("saveModes")]});return(0,n.jsxs)("section",{"aria-label":s("settings"),className:"flex h-full min-h-0 flex-col bg-background",children:[(0,n.jsxs)("header",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-3",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"shrink-0 text-sm font-medium",children:s("editMode")}),(0,n.jsxs)(ea.l6,{value:l.selected??"",disabled:p,onValueChange:e=>{"string"==typeof e&&l.select(e||null)},children:[(0,n.jsx)(ea.bq,{"aria-label":s("selectMode"),className:"w-40 sm:w-48",children:(0,n.jsx)(ea.yv,{children:l.selected?u[l.selected]||s("unnamedMode"):s("allDefault")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[140]",children:[(0,n.jsx)(ea.eb,{value:"",children:s("allDefault")}),Object.entries(u).map(([e,t])=>(0,n.jsx)(ea.eb,{value:e,children:t||s("unnamedMode")},e))]})]})]}),(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,n.jsxs)(N.$,{size:"sm",variant:"ghost",disabled:p,onClick:()=>void l.add(),children:[(0,n.jsx)(U.A,{className:"size-4"}),s("addMode")]}),m&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost","aria-label":s("copyMode"),title:s("copyTitle"),disabled:p,onClick:()=>void l.add(!0),children:(0,n.jsx)(Z.A,{className:"size-4"})}),(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost","aria-label":s("deleteMode"),title:s("deleteTitle"),disabled:p,onClick:()=>d(m.name||s("unnamedMode")),children:(0,n.jsx)(ee.A,{className:"size-4"})})]}),l.catalog&&(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost","aria-label":s("refreshCatalog"),title:s("refreshCatalog"),disabled:p,onClick:()=>void l.load(!0),children:(0,n.jsx)(et.A,{className:"size-4"})}),(0,n.jsx)("span",{className:"ml-1 hidden sm:inline-flex",children:g})]})]}),l.error&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 border-b px-4 py-3 text-sm text-destructive",children:[l.error,(0,n.jsx)(N.$,{variant:"ghost",size:"sm",onClick:()=>void l.load(!0),children:s("retryRead")})]}),l.loading&&(0,n.jsxs)("div",{role:"status",className:"flex shrink-0 items-center gap-2 border-b px-4 py-3 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),s("loadingCatalog")]}),m&&l.selected?(0,n.jsx)(ek,{modeKey:l.selected,mode:m,catalog:l.catalog,disabled:l.saving,onChange:l.update}):(0,n.jsxs)("div",{className:"flex items-start gap-3 p-6",children:[(0,n.jsx)(es.A,{className:"mt-0.5 size-6 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:"text-sm font-semibold",children:s("allEnabled")}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:s("allDescription")})]})]}),(0,n.jsxs)("footer",{className:"mt-auto flex shrink-0 items-center justify-between gap-3 border-t px-4 py-3 pb-[max(.75rem,env(safe-area-inset-bottom))] text-xs text-muted-foreground sm:py-2",children:[(0,n.jsx)("span",{role:"status",children:l.dirty?s("unsaved"):s("allIsDefault")}),(0,n.jsx)("span",{className:"sm:hidden",children:g})]}),(0,n.jsx)(eN,{open:l.leaveOpen||null!==o,deleteName:o,saving:l.saving,error:l.leaveOpen?l.error:null,onCancel:()=>{null!==o?d(null):l.decideLeave("cancel")},onDelete:()=>{l.remove(),d(null)},onLeave:e=>void l.decideLeave(e)})]})}var eC=s(87372),eS=s(79566),eM=s(13344),ez=s(54359),eE=s(24022),eA=s(77483),e$=s(95526),eR=s(66584),eT=s(76085),eP=s(58619),eD=s(90695),eO=s(6609);let eL={plugin:eC.A,server:eS.A,rocket:eM.A,settings:ez.A,panel:eE.A,message:eA.A,terminal:v.A,file:e$.A,folder:eR.A,bot:eT.A,wrench:eP.A,database:eD.A,globe:eO.A},eF=new Map;function e_({icon:e,className:t}){if(e?.type==="svg"){let s=function(e){if(eF.has(e))return eF.get(e)??null;let t=e.trim(),s=t.length>16384||!/^<svg[\s>]/i.test(t)||!/<\/svg>$/i.test(t)||/<\s*(script|foreignObject|iframe|object|embed|link|style)\b/i.test(t)||/\son[a-z]+\s*=/i.test(t)||/(javascript:|data:text\/html|https?:\/\/)/i.test(t)?null:t;return eF.set(e,s),s}(e.content);if(s)return(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("block [&>svg]:size-full",t),dangerouslySetInnerHTML:{__html:s}})}let s=e?.type==="builtin"?eL[e.name]:eC.A;return(0,n.jsx)(s,{"aria-hidden":"true",className:t})}var eB=s(94173),eq=s(86758),eW=s(81649);function eY({error:e,children:t}){let{t:s}=(0,f.Bd)("common"),r=e.message.trim().split(/\r?\n/)[0]||s("unknownError");return(0,n.jsxs)("div",{className:"mt-1 min-w-0",children:[(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:r}),(0,n.jsxs)(eW.Nt,{defaultOpen:!1,children:[(0,n.jsxs)(eW.R6,{className:"group mt-1 inline-flex min-h-8 cursor-pointer items-center gap-2 rounded-md text-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eq.A,{"aria-hidden":"true",className:"size-4 shrink-0 transition-transform group-aria-expanded:rotate-180 motion-reduce:transition-none"}),s("errorDetails")]}),(0,n.jsx)(eW.Ke,{className:"h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none",children:(0,n.jsxs)("div",{className:"space-y-3 pt-2",children:[(0,n.jsx)("pre",{className:"max-h-[min(20rem,45dvh)] overflow-auto rounded-md bg-background p-3 font-mono text-sm leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]",children:e.stack||e.message}),t]})})]})]})}function eU({pluginName:e,kind:t,contributionName:s,target:a,targetKey:i,className:l,layout:o="fill"}){let{t:d}=(0,f.Bd)("pluginManagement"),c=(0,J.t4)();(0,J.So)();let u=c.getEntryState(e),m="ready"===u.status?u.runtime:u.status,p="failed"===u.status?u.error:null,h=(0,r.useRef)(null),g=(0,r.useRef)(a),x=i??a,[v,w]=(0,r.useState)(0),[y,k]=(0,r.useState)({status:"loading"});(0,r.useEffect)(()=>{g.current=a},[a]),(0,r.useEffect)(()=>{let n=h.current;if(!n)return;let r=new AbortController,a=!0,i=null;if("ready"!==u.status)return queueMicrotask(()=>{a&&k(p?{status:"error",error:p}:{status:"loading"})}),()=>{a=!1,r.abort()};let l=Promise.resolve().then(()=>a?((i=document.createElement("div")).className="intrinsic"===o?"inline-block min-h-0 min-w-0 align-top":"h-full min-h-0 w-full min-w-0",n.append(i),c.mountContribution({pluginName:e,kind:t,contributionName:s,container:i,target:g.current,signal:r.signal})):null);return queueMicrotask(()=>{a&&k({status:"loading"})}),l.then(e=>{a&&e&&k({status:"ready"})},e=>{a&&k({status:"error",error:e instanceof Error?e:Error(String(e))})}),()=>{a=!1,r.abort(),i?.remove(),l.then(async n=>{if(n)try{await n()}catch(n){console.error("[Pi Desk][PluginHost] Contribution disposer 执行失败",{pluginName:e,kind:t,contributionName:s,errorName:n instanceof Error?n.name:"UnknownError",message:n instanceof Error?n.message:String(n)})}},()=>void 0)}},[v,s,m,u.status,p,t,o,x,e,c]);let j="loading"===y.status?"h-[200px] w-[360px]":"error"===y.status?"w-[min(480px,calc(100dvw-3rem))]":"h-fit w-fit";return(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar relative min-h-0 min-w-0","intrinsic"===o?(0,C.cn)("max-h-[calc(100dvh-7rem)] max-w-[calc(100dvw-3rem)] overflow-auto max-sm:max-h-[calc(100dvh-5rem)] max-sm:max-w-[calc(100dvw-2rem)]",j):"h-full w-full",l),children:[(0,n.jsx)("div",{ref:h,"data-pi-desk-plugin":e,"data-pi-desk-kind":t,"data-pi-desk-contribution":s,className:(0,C.cn)("intrinsic"===o?"inline-block min-h-0 min-w-0 align-top":"h-full min-h-0 w-full min-w-0","error"===y.status&&"hidden")}),"loading"===y.status?(0,n.jsxs)("div",{className:"absolute inset-0 flex items-center justify-center bg-popover p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"mr-2 size-4 animate-spin"}),d("viewLoading")]}):null,"error"===y.status?(0,n.jsx)("div",{role:"alert",className:(0,C.cn)("flex items-center justify-center overflow-auto bg-background p-4","fill"===o&&"absolute inset-0"),children:(0,n.jsx)("div",{className:"w-full max-w-xl rounded-lg border border-destructive/35 bg-muted p-4",children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)(eB.A,{className:"mt-0.5 size-5 shrink-0 text-destructive"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"font-medium text-destructive",children:d("viewFailed")}),(0,n.jsx)(eY,{error:y.error,children:(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e," \xb7 ",t," \xb7 ",s]})}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{if("failed"===u.status){k({status:"loading"}),c.retryEntry(e).catch(t=>{"failed"===c.getEntryState(e).status&&k({status:"error",error:t instanceof Error?t:Error(String(t))})});return}"failed"!==c.getContributionLoadState(e,t,s).status?w(e=>e+1):(k({status:"loading"}),c.retryContribution(e,t,s).then(()=>{c.getEntryState(e)===u&&w(e=>e+1)},t=>{c.getEntryState(e)===u&&k({status:"error",error:t instanceof Error?t:Error(String(t))})}))},children:[(0,n.jsx)(et.A,{}),d("retry")]})]})]})})}):null]})}function eV({pluginName:e,descriptor:t,workSessions:s,preferredWorkId:a,onClose:i}){let{t:l}=(0,f.Bd)("pluginManagement"),o=(0,J.t4)();(0,J.So)();let d=o.getEntryState(e),[c]=(0,r.useState)(()=>{let e=s.find(e=>e.workId===a);return e?{source:{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId},cwd:e.cwd}:null}),u=(0,r.useMemo)(()=>({kind:"application",initialContext:c,close:()=>{o.getEntryState(e)===d&&i()}}),[d,c,i,e,o]),m="host"===t.chrome;return(0,n.jsx)(ej.YV,{open:!0,onOpenChange:(e,t)=>{e||"focus-out"===t.reason||i()},children:(0,n.jsxs)(ej.hA,{finalFocus:!1,showCloseButton:!1,className:(0,C.cn)("w-fit max-w-[calc(100dvw-2rem)] max-h-[calc(100dvh-2rem)]",!m&&"rounded-none border-0 bg-transparent shadow-none ring-0"),children:[m?(0,n.jsx)(ej.Hl,{className:"border-b px-4 py-3",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(e_,{icon:t.icon,className:"size-5"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(ej.YM,{className:"break-words",children:t.title}),(0,n.jsx)(ej.uX,{className:"sr-only",children:e})]}),(0,n.jsx)(N.$,{variant:"ghost",size:"icon","aria-label":l("closeNamedApplication",{name:t.title}),title:l("closeApplication"),onClick:i,className:"text-muted-foreground",children:(0,n.jsx)(Y.A,{className:"size-4"})})]})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ej.YM,{className:"sr-only",children:t.title}),(0,n.jsx)(ej.uX,{className:"sr-only",children:e})]}),(0,n.jsx)("div",{className:"min-h-0 min-w-0 max-w-full overflow-hidden",children:(0,n.jsx)(eU,{pluginName:e,kind:"application",contributionName:t.contributionName,target:u,layout:"intrinsic"})})]})})}function eK({pluginName:e,descriptor:t,source:s,onClose:a}){let i=(0,r.useMemo)(()=>({kind:"composer-panel",source:s,close:a}),[a,s]);return(0,n.jsx)(ej.YV,{open:!0,onOpenChange:e=>!e&&a(),children:(0,n.jsxs)(ej.hA,{finalFocus:!1,className:"h-[min(720px,calc(100dvh-2rem))] max-w-4xl max-sm:h-dvh max-sm:max-h-dvh max-sm:w-full max-sm:max-w-none max-sm:rounded-none max-sm:border-0",children:[(0,n.jsx)(ej.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(e_,{icon:t.icon,className:"size-5"})}),(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)(ej.YM,{className:"truncate",children:t.label}),(0,n.jsx)(ej.uX,{className:"sr-only",children:e})]})]})}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(eU,{pluginName:e,kind:"composer-panel",contributionName:t.contributionName,target:i,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})})]})})}var eH=s(15265),eG=s(5816),eJ=s(90434),eQ=s(31026),eX=s(59095),eZ=s(12720),e0=s(43016),e1=s(73392);function e2({className:e,orientation:t="horizontal",...s}){return(0,n.jsx)(eQ.p,{"data-slot":"tabs","data-orientation":t,className:(0,C.cn)("group/tabs flex gap-2 data-horizontal:flex-col",e),...s})}let e5=(0,e1.F)("group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",{variants:{variant:{default:"bg-muted",line:"gap-1 bg-transparent"}},defaultVariants:{variant:"default"}});function e3({className:e,variant:t="default",...s}){return(0,n.jsx)(eX.j,{"data-slot":"tabs-list","data-variant":t,className:(0,C.cn)(e5({variant:t}),e),...s})}function e4({className:e,...t}){return(0,n.jsx)(eZ.M,{"data-slot":"tabs-trigger",className:(0,C.cn)("relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent","data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground","after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",e),...t})}function e6({className:e,...t}){return(0,n.jsx)(e0.R,{"data-slot":"tabs-content",className:(0,C.cn)("flex-1 text-sm outline-none",e),...t})}var e8=s(36670),e7=s(99084);let e9=new Set(["bash","edit","find","grep","ls","read","write"]),te="__pi_desk_unknown_schema_type__",tt={before_agent_start:{label:"eventAgentStart",description:"eventAgentStartDescription"},context:{label:"eventContext",description:"eventContextDescription"},input:{label:"eventInput",description:"eventInputDescription"},before_provider_request:{label:"eventProvider",description:"eventProviderDescription"},tool_call:{label:"eventToolCall",description:"eventToolCallDescription"},tool_result:{label:"eventToolResult",description:"eventToolResultDescription"},message_end:{label:"eventMessageEnd",description:"eventMessageEndDescription"},session_before_compact:{label:"eventBeforeCompact",description:"eventBeforeCompactDescription"}},ts={application:"contributionApplication","composer-panel":"contributionComposer","settings-page":"contributionSettings","message-view":"contributionMessage","session-sidebar-tab":"contributionSidebar"};function tn(e){let t=[];for(let s of e.extensions)for(let e of s.events){let n=tt[e.name];n&&t.push({name:e.name,count:e.count,path:s.path,label:n.label,description:n.description})}return t.sort((e,t)=>{let s=e.name.localeCompare(t.name);return 0===s?e.path.localeCompare(t.path):s})}function tr(e){return null===e||"object"!=typeof e||Array.isArray(e)?null:e}function ta({state:e}){let{t}=(0,f.Bd)("pluginManagement"),s=t("active"===e?"stateActive":"inactive"===e?"stateInactive":"stateShadowed");return(0,n.jsx)("span",{className:`rounded-md px-1.5 py-0.5 text-xs font-medium ${"active"===e?"bg-muted text-status-success":"inactive"===e?"bg-muted text-muted-foreground":"bg-muted text-status-warning"}`,children:s})}function ti({text:e,label:t}){let{t:s}=(0,f.Bd)("pluginManagement"),[a,i]=(0,r.useState)(!1);return(0,n.jsx)(N.$,{type:"button",size:"icon",variant:"ghost","aria-label":t,title:s(a?"copied":"copy"),onClick:()=>{(0,e7.x)(e).then(e=>{e&&i(!0)})},children:a?(0,n.jsx)(em.A,{className:"size-3.5"}):(0,n.jsx)(Z.A,{className:"size-3.5"})})}function tl({title:e,text:t}){let{t:s}=(0,f.Bd)("pluginManagement");return(0,n.jsxs)("div",{className:"rounded-lg bg-muted",children:[(0,n.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-2 px-3",children:[(0,n.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:e}),(0,n.jsx)(ti,{text:t,label:s("copyNamed",{name:e})})]}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words px-3 py-3 font-mono text-sm leading-[1.6]",children:t})]})}function to({title:e,description:t,children:s}){return(0,n.jsxs)(eW.Nt,{className:"border-t",children:[(0,n.jsxs)(eW.R6,{className:"group flex min-h-8 w-full cursor-pointer items-center gap-2 py-2 text-left text-sm font-medium outline-none hover:text-muted-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[(0,n.jsx)(e8.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),e]}),(0,n.jsx)(eW.Ke,{children:(0,n.jsxs)("div",{className:"space-y-3 pb-3",children:[t?(0,n.jsx)("p",{className:"text-sm leading-5 text-muted-foreground",children:t}):null,s]})})]})}function td({capabilities:e}){let{t}=(0,f.Bd)("pluginManagement"),s=tn(e);return 0===s.length?null:(0,n.jsx)(to,{title:t("dynamicTitle"),description:t("dynamicDescription"),children:(0,n.jsx)("div",{className:"divide-y",children:s.map((e,s)=>(0,n.jsxs)("div",{className:"px-3 py-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"text-xs font-semibold",children:e.name}),e.count>1?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["\xd7",e.count]}):null,(0,n.jsx)("span",{className:"text-xs font-medium",children:t(e.label)})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:t(e.description)}),(0,n.jsx)("p",{className:"mt-1 truncate font-mono text-xs text-muted-foreground",title:e.path,children:e.path})]},`${e.path}:${e.name}:${s}`))})})}function tc({tool:e}){let{t}=(0,f.Bd)("pluginManagement"),s=function(e){var t;let s=tr(e.properties);if(!s)return[];let n=new Set(Array.isArray(t=e.required)?t.filter(e=>"string"==typeof e):[]);return Object.entries(s).map(([e,t])=>{let s=tr(t);return{name:e,required:n.has(e),type:function e(t){let s=tr(t);if(!s)return te;let n=Array.isArray(s.enum)?s.enum.filter(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e):[];if(n.length>0)return n.map(String).join(" | ");if("string"==typeof s.type){if("array"!==s.type)return s.type;let t=e(s.items);return t===te?"array":`${t}[]`}for(let t of["anyOf","oneOf"]){if(!Array.isArray(s[t]))continue;let n=s[t].map(e).filter(e=>e!==te);if(n.length>0)return[...new Set(n)].join(" | ")}return te}(t),description:"string"==typeof s?.description?s.description:null}})}(e.parameters);return(0,n.jsxs)("div",{className:"mt-4",children:[(0,n.jsxs)("p",{className:"text-sm font-medium",children:[t("arguments")," \xb7 ",s.length>0?s.length:t("none")]}),(0,n.jsxs)("div",{className:"py-3",children:[s.length>0?(0,n.jsx)("div",{className:"space-y-2",children:s.map(e=>(0,n.jsxs)("div",{className:"grid gap-1 text-sm sm:grid-cols-[minmax(8rem,0.8fr)_minmax(0,1.5fr)] sm:gap-3",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(e.required?"required":"optional")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.type===te?t("unknown"):e.type})]}),(0,n.jsx)("p",{className:"min-w-0 break-words leading-5 text-muted-foreground",children:e.description??"—"})]},e.name))}):(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("noArguments")}),(0,n.jsxs)(eW.Nt,{className:"mt-3",children:[(0,n.jsxs)(eW.R6,{className:"group flex min-h-8 cursor-pointer items-center gap-2 text-sm text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e8.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),t("rawSchema")]}),(0,n.jsx)(eW.Ke,{keepMounted:!0,children:(0,n.jsx)("pre",{className:"mt-2 whitespace-pre-wrap break-words rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:JSON.stringify(e.parameters,null,2)})})]})]})]})}function tu({detail:e}){let{t}=(0,f.Bd)("pluginManagement");return 0===e.tools.length?null:(0,n.jsx)(to,{title:t("toolCapabilities"),description:t("toolDescription"),children:(0,n.jsx)("div",{className:"space-y-2",children:e.tools.map((e,s)=>(0,n.jsxs)(eW.Nt,{className:"border-b py-3 last:border-b-0",children:[(0,n.jsxs)(eW.R6,{className:"group w-full cursor-pointer text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e8.A,{"aria-hidden":"true",className:"mr-2 inline-block size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),(0,n.jsxs)("span",{className:"inline-flex min-w-0 flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),e.label&&e.label!==e.name?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.label}):null,(0,n.jsx)(ta,{state:e.state}),e9.has(e.name)&&"shadowed"!==e.state?(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs font-medium text-foreground",children:t("overridesBuiltin")}):null]}),(0,n.jsx)("span",{className:"mt-1.5 block break-words text-sm leading-5 text-muted-foreground",children:e.description||t("noDescription")})]}),(0,n.jsxs)(eW.Ke,{keepMounted:!0,children:[(0,n.jsx)(tc,{tool:e}),e.promptSnippet||e.promptGuidelines.length>0?(0,n.jsxs)("div",{className:"mt-3 space-y-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"text-xs font-medium",children:t("systemPrompts")}),"active"!==e.state?(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("inactivePrompt")}):null]}),e.promptSnippet?(0,n.jsx)(tl,{title:"Available tools",text:e.promptSnippet}):null,e.promptGuidelines.length>0?(0,n.jsx)(tl,{title:`Guidelines \xb7 ${e.promptGuidelines.length}`,text:e.promptGuidelines.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}):null]}):null]})]},`${e.name}:${s}`))})})}function tm({title:e,content:t,truncated:s}){let{t:r}=(0,f.Bd)("pluginManagement");return(0,n.jsxs)(eW.Nt,{className:"mt-3",children:[(0,n.jsxs)(eW.R6,{className:"group flex min-h-8 w-full cursor-pointer items-center gap-2 py-2 text-left text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(e8.A,{"aria-hidden":"true",className:"size-3.5 shrink-0 transition-transform group-aria-expanded:rotate-90"}),e]}),(0,n.jsxs)(eW.Ke,{keepMounted:!0,className:"border-t",children:[(0,n.jsx)("div",{className:"flex justify-end px-2 pt-1",children:(0,n.jsx)(ti,{text:t,label:r("copyNamed",{name:e})})}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:t}),s?(0,n.jsx)("p",{className:"py-2 text-sm text-status-warning",children:r("truncated")}):null]})]})}function tp({detail:e}){let{t}=(0,f.Bd)("pluginManagement");return 0===e.skills.length&&0===e.prompts.length?null:(0,n.jsx)(to,{title:t("resourcesTitle"),description:t("resourcesDescription"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[e.skills.map(e=>(0,n.jsxs)("article",{className:"border-b py-4 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"font-semibold",children:e.name}),(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:t(e.modelVisible?"skillModelVisible":"manualOnly")})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:e.description}),(0,n.jsx)("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:e.path}),e.modelVisible?(0,n.jsx)("div",{className:"mt-2",children:(0,n.jsx)(tl,{title:t("skillMetadata"),text:`name: ${e.name}
153
- description: ${e.description}
154
- location: ${e.path}`})}):null,(0,n.jsx)(tm,{title:t("viewSkillContent"),content:e.content,truncated:e.truncated})]},e.path)),e.prompts.map(e=>(0,n.jsxs)("article",{className:"border-b py-4 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)("code",{className:"font-semibold",children:["/",e.name]}),(0,n.jsx)("span",{className:"rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:t("manualOnly")})]}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:e.description}),(0,n.jsx)("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:e.path}),(0,n.jsx)(tm,{title:t("viewPromptContent"),content:e.content,truncated:e.truncated})]},e.path))]})})}function th({capabilities:e,browserContributions:t}){let{t:s}=(0,f.Bd)("pluginManagement"),r=e.extensions.some(e=>e.events.length>0||e.commands.length>0||e.shortcuts.length>0||e.flags.length>0||e.messageRenderers.length>0||e.entryRenderers.length>0),a=e.piDesk.methods.length>0||e.piDesk.browserEntries.length>0||e.piDesk.messageDeclarations.length>0||t.length>0,i=e.themes.length>0||e.providers.length>0;return r||a||i?(0,n.jsx)(to,{title:s("otherCapabilities"),children:(0,n.jsxs)("div",{className:"space-y-2",children:[a?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("p",{className:"font-semibold",children:"Pi Desk"}),(0,n.jsxs)("div",{className:"mt-2 space-y-1.5 text-muted-foreground",children:[e.piDesk.methods.map(e=>(0,n.jsxs)("p",{children:["Method:",(0,n.jsxs)("code",{children:[e.pluginName,"/",e.method]})]},`${e.pluginName}:${e.method}`)),t.map(e=>(0,n.jsxs)("p",{children:[s(ts[e.kind]),":","message-view"===e.kind?e.viewKey:"application"===e.kind?e.title:e.label]},`${e.kind}:${e.contributionName}`)),e.piDesk.messageDeclarations.map(e=>(0,n.jsxs)("p",{children:[s("messageDeclarations"),(0,n.jsxs)("code",{children:[e.pluginName,"/",e.declarationName]})]},`${e.pluginName}:${e.declarationName}`))]})]}):null,r?e.extensions.map(e=>(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs",children:[(0,n.jsx)("code",{className:"block break-all font-semibold",children:e.path}),e.commands.length>0?(0,n.jsxs)("p",{className:"mt-2 leading-5 text-muted-foreground",children:["Commands:",e.commands.map(e=>`/${e.name}`).join("、")]}):null,e.shortcuts.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Shortcuts:",e.shortcuts.map(e=>e.shortcut).join("、")]}):null,e.flags.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Flags:",e.flags.map(e=>`--${e.name}`).join("、")]}):null,e.events.length>0?(0,n.jsxs)("p",{className:"mt-1 leading-5 text-muted-foreground",children:["Events:",e.events.map(e=>e.name).join("、")]}):null]},e.path)):null,i?(0,n.jsxs)("div",{className:"rounded-xl border bg-card p-3 text-xs text-muted-foreground",children:[e.themes.length>0?(0,n.jsxs)("p",{children:["Theme:",e.themes.map(e=>e.name).join("、")]}):null,e.providers.length>0?(0,n.jsxs)("p",{className:"mt-1",children:["Provider:",e.providers.map(e=>e.name).join("、")]}):null]}):null]})}):null}function tg({plugin:e,detail:t,detailLoading:s,detailError:r,browserContributions:a,onRetry:i}){let{t:l}=(0,f.Bd)("pluginManagement"),{locale:o}=(0,eG.i)(),d=function(e,t,s){let n=[];e.tools.length>0&&n.push({label:s("tagTools",{count:e.tools.length}),tone:"neutral"});let r=e.tools.reduce((e,t)=>"active"!==t.state?e:e+ +!!t.promptSnippet+t.promptGuidelineCount,0)+e.skills.filter(e=>e.modelVisible).length;r>0&&n.push({label:s("tagFixed",{count:r}),tone:"prompt"});let a=tn(e).reduce((e,t)=>e+t.count,0);a>0&&n.push({label:s("tagDynamic",{count:a}),tone:"dynamic"});let i=e.tools.filter(e=>"shadowed"!==e.state&&e9.has(e.name)).length;i>0&&n.push({label:s("tagOverride",{count:i}),tone:"override"});let l=e.prompts.length+e.skills.filter(e=>!e.modelVisible).length;l>0&&n.push({label:s("tagManual",{count:l}),tone:"neutral"});let o=t.length+e.piDesk.methods.length+e.piDesk.messageDeclarations.length;o>0&&n.push({label:`Pi Desk ${o}`,tone:"neutral"});let d=e.providers.length+e.themes.length+e.extensions.reduce((e,t)=>e+t.commands.length+t.shortcuts.length+t.flags.length,0);return d>0&&n.push({label:s("tagInteraction",{count:d}),tone:"neutral"}),0===n.length&&e.extensions.length>0&&n.push({label:`Extension ${e.extensions.length}`,tone:"neutral"}),n}(e.capabilities,a,l);return(0,n.jsxs)("div",{className:"space-y-3 text-sm","data-testid":"plugin-capability-detail",children:[(0,n.jsx)("p",{className:"break-all font-mono text-xs text-muted-foreground",children:e.source}),d.length>0?(0,n.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":l("capabilityCategories"),children:d.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground",children:e.label},e.label))}):null,e.capabilities.error?(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-5 text-status-warning",children:l("incompleteCapabilities",{error:(0,eH.fD)(e.capabilities.error,o)})}):null,s?(0,n.jsxs)("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),l("loadingFullDetails")]}):r?(0,n.jsxs)("div",{className:"flex items-start gap-2",role:"alert",children:[(0,n.jsx)("p",{className:"min-w-0 flex-1 break-words text-sm text-destructive",children:r}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",onClick:i,children:[(0,n.jsx)(et.A,{"data-icon":"inline-start"}),l("retry")]})]}):t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tu,{detail:t}),(0,n.jsx)(tp,{detail:t})]}):null,(0,n.jsx)(td,{capabilities:e.capabilities}),(0,n.jsx)(th,{capabilities:e.capabilities,browserContributions:a})]})}var tx=s(76782),tf=s(44980);function tb({className:e,size:t="default",...s}){return(0,n.jsx)(tx.l,{"data-slot":"switch","data-size":t,className:(0,C.cn)("peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",e),...s,children:(0,n.jsx)(tf.p,{"data-slot":"switch-thumb",className:"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"})})}function tv({plugin:e,displayName:t,browserError:s,disabled:r,pending:a,browserRetryPending:i,onAction:l}){let{t:o}=(0,f.Bd)("pluginManagement"),d=e.operation?.phase,c="disabled"!==e.status;return(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-3",children:[a?(0,n.jsxs)("span",{role:"status",className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:["waiting"!==d?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):null,o(d&&"failed"!==d?`phase_${d}`:"submitting")]}):e.updateAvailable&&"extension"!==e.kind&&"failed"!==d?(0,n.jsx)(N.$,{size:"sm",disabled:r,onClick:()=>l("update"),children:o("update")}):null,"failed"===d?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:r||a,onClick:()=>l("retry"),children:o("retry")}):s&&e.pluginName?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:r||i,onClick:()=>l("retry-browser"),children:o("retryView")}):null,(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(tb,{checked:c,"aria-label":o("togglePlugin",{name:t}),disabled:r||a,onCheckedChange:e=>l(e?"enable":"disable")}),o(c?"enabled":"disabled")]}),"extension"!==e.kind?(0,n.jsx)(N.$,{size:"icon-sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive","aria-label":o("removeNamed",{name:t}),title:o("remove"),disabled:r||a,onClick:()=>l("remove"),children:(0,n.jsx)(ee.A,{})}):null]})}function tw({plugin:e,requestError:t,browserError:s}){let{t:r}=(0,f.Bd)("pluginManagement"),{locale:a}=(0,eG.i)(),i=e.operation?.phase,l=[t,"failed"===i?e.operation?.message:null,e.error?(0,eH.fD)(e.error.message,a):null,s,e.updateError?r("itemCheckFailed",{error:e.updateError}):null].filter((e,t,s)=>!!e&&s.indexOf(e)===t);return l.length||"waiting"===i||"failed"===e.status?(0,n.jsxs)("div",{className:"space-y-1",children:[l.map(e=>(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive [overflow-wrap:anywhere]",children:e},e)),l.length||"failed"!==e.status?null:(0,n.jsx)("p",{className:"text-sm text-destructive",children:r("notLoaded")}),"waiting"===i&&e.operation?.message?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operation.message}):null]}):null}function ty(e){let t=e.startsWith("npm:")?e.slice(4):e,s=/^((?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*)(?:@([^\s/]+))?$/i.exec(t);return s?{name:s[1],...s[2]?{version:s[2]}:{}}:null}function tk(e){return e.source.startsWith("npm:")?ty(e.source)?.name??e.source:e.pluginName??("extension"===e.kind?e.source.replaceAll("\\","/").split("/").at(-1):null)??e.source}function tj(e){return`source:${ty(e)?.name??e}`}function tN(e){switch(e.kind){case"batch":return"add"===e.input.action?"batchInstall":"update"===e.input.action?"updateSelected":"del"===e.input.action?"removeSelected":"setChannel";case"add":return"actionAdd";case"update":return"actionUpdate";case"del":return"actionDelete";case"enable":return"enable";case"disable":return"disable";case"reload":return"normal"===e.mode?"restartNormal":"actionReload"}}let tI=a.Yj().trim().min(1).max(128).regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/),tC=a.Yj().trim().url().max(2048).refine(e=>{let t=new URL(e);return["https:","http:"].includes(t.protocol)&&!t.username&&!t.password&&!t.search&&!t.hash},"插件源必须是 HTTP 或 HTTPS 仓库地址"),tS=a.gM("mode",[a.Ik({mode:a.eu("auto")}).strict(),a.Ik({mode:a.eu("local")}).strict(),a.Ik({mode:a.eu("official")}).strict(),a.Ik({mode:a.eu("domestic")}).strict(),a.Ik({mode:a.eu("custom"),registry:tC}).strict()]),tM=a.Ik({description:a.Yj().trim().min(1).max(4e3).optional(),readme:a.Yj().trim().min(1).max(1024).optional()});a.Ik({description:a.Yj().optional(),piDesk:a.Ik({i18n:a.g1(a.Yj().min(1).max(35),tM).optional()}).passthrough().optional()}).passthrough();let tz=a.Ik({downloadSource:tS,recommendedRegistry:tC}).strict(),tE=a.Ik({downloadSource:tS}).strict(),tA=a.Ik({query:a.Yj().trim().max(200).default(""),page:a.ai().int().min(1).max(100).default(1),kind:a.k5(["all","desk","pi"]).default("all"),registry:tC.optional()}).strict(),t$=a.Ik({name:a.Yj().trim().min(1).max(214).regex(/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/i),version:a.Yj().trim().min(1).max(128).optional(),registry:tC.optional()}).strict(),tR=a.Ik({name:a.Yj(),description:eH.qf.nullable(),version:a.Yj(),publisher:a.Yj().nullable(),kind:a.k5(["desk","pi","unknown"]),official:a.zM(),registry:tC}).strict(),tT=a.Ik({items:a.YO(tR),hasMore:a.zM()}).strict(),tP=tR.extend({versions:a.YO(a.Yj()),readme:eH.qf.nullable(),homepage:a.Yj().nullable(),repository:a.Yj().nullable(),compatible:a.zM().nullable(),compatibilityNote:a.Yj().nullable()}).strict();function tD({id:e,mode:t,registry:s,recommendedRegistry:r,savedRegistry:a,loading:i,saving:l,error:o,override:d,onMode:c,onRegistry:u,onSave:m,onRetry:p}){let{t:h}=(0,f.Bd)("pluginManagement"),g="auto"===t?r:"official"===t?"https://registry.npmjs.org":"domestic"===t?"https://mirrors.cloud.tencent.com/npm":"custom"===t?a??s:null,x=[...d?[{value:"default",label:h("useDefaultSource")}]:[],...["local","auto","domestic","official","custom"].map(e=>({value:e,label:h(`download_${e}`)}))];return(0,n.jsxs)("div",{className:"min-w-0 space-y-3 text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:e,className:"font-medium",children:h(d?"installDownloadSource":"downloadSource")}),(0,n.jsxs)(ea.l6,{value:t,items:x,disabled:i,onValueChange:e=>{e&&!l&&c(e)},children:[(0,n.jsx)(ea.bq,{id:e,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:x.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:l,children:e.label},e.value))})]}),l?(0,n.jsx)("span",{role:"status",className:"text-muted-foreground",children:h("saving")}):null]}),"custom"===t?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:`${e}-url`,className:"block",children:h("registryUrl")}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(eu.p,{id:`${e}-url`,type:"url",value:s,placeholder:"https://registry.example.com",className:"min-w-0 flex-1 basis-48",disabled:l,onChange:e=>u(e.target.value)}),m?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:l,onClick:m,children:h("save")}):null]})]}):!d&&g?(0,n.jsx)("p",{className:"break-all text-xs text-muted-foreground",children:g}):null,o?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:o}),p?(0,n.jsx)(N.$,{variant:"outline",size:"sm",onClick:p,children:h("retry")}):null]}):null]})}var tO=s(3058),tL=s(97724),tF=s(48742);function t_({className:e,...t}){return(0,n.jsx)(tL.y,{"data-slot":"checkbox",className:(0,C.cn)("peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",e),...t,children:(0,n.jsx)(tF.P,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none [&>svg]:size-3.5",children:(0,n.jsx)(em.A,{})})})}function tB(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,eG.i)(),r=e.snapshot?.plugins??[],a=t=>e.requests.has(tj(t.source))||!!(t.operation&&"failed"!==t.operation.phase),i=r.filter(t=>("updates"!==e.statusFilter||!!t.updateAvailable)&&("disabled"!==e.statusFilter||"disabled"===t.status)&&("failed"!==e.statusFilter||!!("failed"===t.status||t.operation?.phase==="failed"||t.updateError||t.pluginName&&e.browserErrors.has(t.pluginName)))&&`${tk(t)} ${t.description?(0,eH.fD)(t.description,s):""}`.toLocaleLowerCase().includes(e.filter.trim().toLocaleLowerCase())),l=i.filter(e=>"extension"!==e.kind),o=r.filter(t=>e.selected.has(tj(t.source))),d=r.filter(e=>!0===e.updateAvailable&&"extension"!==e.kind&&!a(e)),c=d.filter(t=>e.selected.has(tj(t.source))),u=o.filter(e=>!a(e)),m=l.length>0&&l.every(t=>e.selected.has(tj(t.source))),p=l.some(t=>e.selected.has(tj(t.source))),h=["all","updates","disabled","failed"].map(e=>({value:e,label:t(`statusFilter_${e}`)}));return(0,n.jsxs)("section",{"aria-label":t("installed"),className:"flex min-h-0 min-w-0 flex-col gap-3",children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 bg-popover pb-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(eu.p,{"aria-label":t("filterInstalled"),value:e.filter,onChange:t=>e.onFilter(t.target.value),placeholder:t("filterInstalled"),className:"min-w-40 flex-1 basis-52"}),(0,n.jsxs)(ea.l6,{value:e.statusFilter,items:h,onValueChange:t=>{t&&e.onStatusFilter(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("filterStatus"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:h.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))})]}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.loading||e.disabled,onClick:e.onRefresh,children:t(e.loading?"checkingUpdates":"checkUpdates")}),d.length>0?(0,n.jsx)(N.$,{size:"sm",disabled:e.disabled||e.loading,onClick:e.onUpdateAll,children:t("updateAll",{count:d.length})}):null,r.some(e=>"extension"!==e.kind)?(0,n.jsx)(N.$,{size:"sm",variant:"ghost",onClick:()=>e.onBatchMode(!e.batchMode),children:t(e.batchMode?"finishSelection":"batchManage")}):null]}),e.batchMode?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 rounded-lg bg-muted px-3 py-2",children:[(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsxs)("span",{className:"relative flex size-4 items-center justify-center",children:[(0,n.jsx)(t_,{checked:m,indeterminate:p&&!m,className:"data-indeterminate:[&_svg]:hidden",disabled:!l.length,onCheckedChange:t=>e.onSelect(l.map(e=>tj(e.source)),t)}),p&&!m?(0,n.jsx)(tO.A,{"aria-hidden":!0,className:"pointer-events-none absolute size-3.5"}):null]}),t(e.filter||"all"!==e.statusFilter?"selectFiltered":"selectAll")]}),(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("selectedCount",{count:o.length})}),o.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled||e.loading||!c.length,onClick:e.onUpdateSelected,children:t("updateSelected")}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled||!u.length,onClick:e.onRemoveSelected,children:t("removeSelected")}),(0,n.jsx)(N.$,{size:"sm",variant:"ghost",onClick:()=>e.onSelect([...e.selected],!1),children:t("clearSelection")})]}):null]}):null,e.errors.list?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.errors.list}):null]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto",children:e.loading&&!e.snapshot?(0,n.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:t("loading")}):i.length?(0,n.jsx)("div",{className:"divide-y rounded-lg border bg-card",children:i.map(r=>{let i=tk(r),l=tj(r.source),o=r.pluginName?e.browserErrors.get(r.pluginName)??null:null;return(0,n.jsx)("article",{"aria-label":i,className:`min-w-0 px-4 py-3 ${e.selected.has(l)&&e.batchMode?"bg-accent/40":""}`,children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[e.batchMode&&"extension"!==r.kind?(0,n.jsx)("div",{className:"flex min-h-8 shrink-0 items-center",children:(0,n.jsx)(t_,{checked:e.selected.has(l),"aria-label":t("selectPlugin",{name:i}),onCheckedChange:t=>e.onSelect([l],t)})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-1 basis-64 flex-wrap items-center gap-x-2 gap-y-1",children:[(0,n.jsx)(N.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full justify-start p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]","aria-label":t("viewDetails",{name:i}),onClick:()=>e.onDetail(r.source),children:i}),r.version?(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",r.version]}):null,r.updateAvailable?(0,n.jsx)("span",{className:"inline-flex rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:r.availableVersion?t("newVersion",{version:r.availableVersion}):t("updateAvailable")}):null,r.updateTag&&"latest"!==r.updateTag?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"dev"===r.updateTag?t("channelDev"):r.updateTag}):null]}),(0,n.jsx)(tv,{plugin:r,displayName:i,browserError:o,disabled:e.disabled,pending:a(r),browserRetryPending:e.requests.has(`entry:${r.pluginName}`),onAction:t=>e.onAction(r,t)})]}),r.description?(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eH.fD)(r.description,s)}):null,(0,n.jsx)(tw,{plugin:r,browserError:o,requestError:e.errors[l]??e.errors[`entry:${r.pluginName}`]})]})]})},l)})}):(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t(e.filter||"all"!==e.statusFilter?"noMatches":"empty")})})]})}function tq(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,eG.i)(),r=new Map(e.snapshot?.plugins.filter(e=>e.source.startsWith("npm:")).map(e=>[ty(e.source)?.name,e]));return(0,n.jsxs)("section",{className:"min-w-0 space-y-4","aria-label":t("searchPlugins"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("label",{htmlFor:"plugin-catalog-query",className:"sr-only",children:t("searchPlugins")}),(0,n.jsx)(eu.p,{id:"plugin-catalog-query",value:e.query,placeholder:t("searchPlaceholder"),className:"min-w-40 flex-1 basis-56",maxLength:200,onChange:t=>e.onQuery(t.target.value),onCompositionStart:e.onCompositionStart,onCompositionEnd:e.onCompositionEnd}),(0,n.jsxs)(ea.l6,{value:e.searchSource,items:[{value:"public",label:t("publicNpm")},{value:"custom",label:t("customSearchSource")}],onValueChange:t=>{t&&e.onSearchSource(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("searchSource"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"public",children:t("publicNpm")}),(0,n.jsx)(ea.eb,{value:"custom",children:t("customSearchSource")})]})]}),(0,n.jsxs)(ea.l6,{value:e.kind,items:["all","desk","pi"].map(e=>({value:e,label:t(`kind_${e}`)})),onValueChange:t=>{t&&e.onKind(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("pluginKind"),children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:["all","desk","pi"].map(e=>(0,n.jsx)(ea.eb,{value:e,children:t(`kind_${e}`)},e))})]}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:e.onDirectInstall,children:t("directInstall")}),"custom"===e.searchSource?(0,n.jsxs)("div",{className:"w-full space-y-1",children:[(0,n.jsx)("label",{htmlFor:"plugin-search-registry",className:"block text-sm",children:t("searchRegistryUrl")}),(0,n.jsx)(eu.p,{id:"plugin-search-registry",type:"url",value:e.registry,onChange:t=>e.onRegistry(t.target.value),placeholder:"https://registry.example.com"})]}):null]}),e.error?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 [overflow-wrap:anywhere]",children:e.error}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:e.onRetry,children:t("retry")})]}):null,e.items.length?(0,n.jsx)("div",{className:"@container/catalog divide-y rounded-lg border bg-card",children:e.items.map(a=>{let i=r.get(a.name),l=tj(`npm:${a.name}`),o=i?.description??a.description,d=!!(i?.operation&&"failed"!==i.operation.phase),c=e.requests.has(l)||d||e.preparing.has(a.name),u=i&&(i.operation?.action!=="add"||"failed"!==i.operation.phase),m=e.installErrors[a.name]??e.errors[l]??(i?.error?(0,eH.fD)(i.error.message,s):null);return(0,n.jsxs)("article",{"aria-label":a.name,className:"grid min-w-0 gap-x-4 gap-y-2 px-4 py-3 @xl/catalog:grid-cols-[minmax(0,1fr)_auto]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(N.$,{variant:"link",className:"h-auto min-h-8 min-w-0 max-w-full p-0 text-left text-sm font-semibold whitespace-normal no-underline hover:underline [overflow-wrap:anywhere]",onClick:()=>e.onDetail(a),children:a.name}),(0,n.jsxs)("span",{className:"text-xs text-muted-foreground",children:["v",u&&i.version?i.version:a.version]}),u&&i.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:i.availableVersion?t("newVersion",{version:i.availableVersion}):t("updateAvailable")}):null,(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`kind_${a.kind}`)}),a.publisher?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:a.publisher}):null]}),(0,n.jsx)("p",{className:"line-clamp-2 text-sm text-muted-foreground [overflow-wrap:anywhere]",children:o?(0,eH.fD)(o,s):t("noPluginDescription")})]}),(0,n.jsx)("div",{className:"flex min-h-8 items-center self-start @xl/catalog:justify-end",children:c?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:d?t(`phase_${i?.operation?.phase}`):e.preparing.has(a.name)?t("loadingPackage"):t("submitting")}):u?(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),i.updateAvailable?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onUpdate(i.source),children:t("update")}):null]}):(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.disabled,onClick:()=>e.onInstall(a),children:t("install")})}),m?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:m}):null,i?.operation?.phase==="failed"&&i.operation.message?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere] @xl/catalog:col-span-2",children:i.operation.message}):null]},a.name)})}):null,e.loading?(0,n.jsx)("p",{role:"status",className:"py-4 text-sm text-muted-foreground",children:t("searching")}):e.error||!e.searched||e.items.length?null:(0,n.jsx)("p",{className:"py-8 text-center text-sm text-muted-foreground",children:t("noSearchResults")}),e.hasMore?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onMore,children:t("loadMore")}):null]})}let tW=(0,e1.F)("flex w-fit items-stretch *:focus-visible:relative *:focus-visible:z-10 has-[>[data-slot=button-group]]:gap-2 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-lg [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",{variants:{orientation:{horizontal:"*:data-slot:rounded-r-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-r-lg! [&>[data-slot]~[data-slot]]:rounded-l-none [&>[data-slot]~[data-slot]]:border-l-0",vertical:"flex-col *:data-slot:rounded-b-none [&>[data-slot]:not(:has(~[data-slot]))]:rounded-b-lg! [&>[data-slot]~[data-slot]]:rounded-t-none [&>[data-slot]~[data-slot]]:border-t-0"}},defaultVariants:{orientation:"horizontal"}});function tY({className:e,orientation:t,...s}){return(0,n.jsx)("div",{role:"group","data-slot":"button-group","data-orientation":t,className:(0,C.cn)(tW({orientation:t}),e),...s})}var tU=s(32892),tV=s(57445),tK=s(73028),tH=s(48318),tG=s(93356),tJ=s(10508);let tQ=({className:e,from:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("group flex w-full max-w-[95%] flex-col gap-2","user"===t?"is-user ml-auto justify-end":"is-assistant",e),...s}),tX=({children:e,className:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("flex w-fit min-w-0 max-w-full flex-col gap-2 overflow-hidden text-base leading-[1.8]","group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground","group-[.is-assistant]:text-foreground",t),...s,children:e}),tZ=({tooltip:e,children:t,label:s,variant:r="ghost",size:a="icon-sm",...i})=>{let l=(0,n.jsxs)(N.$,{size:a,type:"button",variant:r,...i,children:[t,(0,n.jsx)("span",{className:"sr-only",children:s||e})]});return e?(0,n.jsx)(tU.Bc,{children:(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:l}),(0,n.jsx)(tU.ZI,{children:(0,n.jsx)("p",{children:e})})]})}):l},t0={cjk:tV.h,code:tK.a,math:tH.D,mermaid:tG.a},t1=(0,r.memo)(({className:e,...t})=>(0,n.jsx)(tJ.jH,{className:(0,C.cn)("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),plugins:t0,...t}),(e,t)=>e.children===t.children&&t.isAnimating===e.isAnimating);t1.displayName="MessageResponse";let t2=({className:e,children:t,...s})=>(0,n.jsx)("div",{className:(0,C.cn)("mt-4 flex w-full items-center justify-between gap-4",e),...s,children:t});function t5({readme:e}){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,eG.i)(),[a,i]=(0,r.useState)(null),l=e&&"string"!=typeof e?e.translations:{},o=Object.keys(l).filter(e=>/^(zh(?:-|$)|en(?:-|$))/.test(e)),d=a&&void 0!==l[a]?a:null,c=e?d?l[d]:(0,eH.fD)(e,s):null;return(0,n.jsxs)("section",{className:"min-w-0 space-y-3","aria-label":t("readme"),children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("readme")}),o.length>0?(0,n.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("readmeLanguage")}),(0,n.jsxs)(ea.l6,{value:d??"",onValueChange:e=>i(e||null),children:[(0,n.jsx)(ea.bq,{"aria-label":t("readmeLanguage"),children:(0,n.jsx)(ea.yv,{children:d?d.startsWith("zh")?"中文":"English":t("defaultLanguage")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",children:t("defaultLanguage")}),o.map(e=>(0,n.jsx)(ea.eb,{value:e,children:e.startsWith("zh")?"中文":"English"},e))]})]})]}):null]}),c?(0,n.jsx)("div",{className:"min-w-0 overflow-x-auto text-base leading-relaxed [overflow-wrap:anywhere]",children:(0,n.jsx)(t1,{mode:"static",isAnimating:!1,skipHtml:!0,controls:!1,className:"min-w-0 [&_img]:max-w-full [&_pre]:overflow-x-auto",children:c})}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:t("noReadme")})]})}function t3({value:e,label:t,placeholder:s,disabled:r,onChange:a}){let{t:i}=(0,f.Bd)("pluginManagement"),l=[...s?[{value:"",label:s}]:[],{value:"latest",label:i("channelLatest")},{value:"dev",label:i("channelDev")},...e&&!["latest","dev"].includes(e)?[{value:e,label:e}]:[]];return(0,n.jsxs)(ea.l6,{value:e,items:l,onOpenChange:(e,t)=>{e&&r&&t.cancel()},onValueChange:e=>{null===e||r||a(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t,"aria-disabled":r,className:"max-w-full aria-disabled:opacity-50",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:l.map(e=>(0,n.jsx)(ea.eb,{value:e.value,disabled:r,children:e.label},e.value))})]})}function t4(e){if(!e)return null;try{let t=new URL(e);return["https:","http:"].includes(t.protocol)?t.href:null}catch{return null}}function t6(e){let{t}=(0,f.Bd)("pluginManagement"),{locale:s}=(0,eG.i)(),r=e.detail,a=e.installed&&e.installedVersion===r.version,i=t4(r.homepage),l=t4(r.repository),o=[...new Set([r.version,...r.versions])];return(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:["v",r.version]}),(0,n.jsx)("span",{children:t(`kind_${r.kind}`)}),r.publisher?(0,n.jsx)("span",{className:"[overflow-wrap:anywhere]",children:r.publisher}):null]}),r.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:(0,eH.fD)(r.description,s)}):null,!1===r.compatible?(0,n.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:[t("incompatible"),r.compatibilityNote?` \xb7 ${r.compatibilityNote}`:""]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[e.pending?(0,n.jsx)("span",{role:"status",className:"text-sm text-muted-foreground",children:e.operationMessage??t("submitting")}):a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:t("alreadyInstalled")}),e.updateAvailable?(0,n.jsx)(N.$,{size:"sm",disabled:e.disabled,onClick:e.onUpdate,children:t("update")}):null]}):(0,n.jsx)(N.$,{size:"sm",disabled:e.disabled||!1===r.compatible,onClick:e.onInstall,children:t(e.installed?"installVersion":"install")}),i?(0,n.jsx)("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("homepage")}):null,l?(0,n.jsx)("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"text-sm underline underline-offset-4",children:t("repository")}):null]}),e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:e.error}):null]}),(0,n.jsxs)(eW.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eW.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eq.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eW.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 px-3 pb-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t3,{value:e.channel,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onChannel}),(0,n.jsxs)(ea.l6,{value:r.version,items:o.map(e=>({value:e,label:e})),onOpenChange:(t,s)=>{t&&e.pending&&s.cancel()},onValueChange:t=>{t&&!e.pending&&e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.pending,children:(0,n.jsx)(ea.yv,{})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[160]",children:o.map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.pending,children:t},t))})]})]}),(0,n.jsx)(tD,{id:"plugin-detail-download",mode:e.downloadMode,registry:e.downloadRegistry,override:!0,saving:e.pending,onMode:e.onDownloadMode,onRegistry:e.onDownloadRegistry})]})})]}),(0,n.jsx)("div",{className:"border-t pt-4",children:(0,n.jsx)(t5,{readme:r.readme},`${r.name}@${r.version}`)})]})}var t8=s(68017);function t7(e){let{t}=(0,f.Bd)("pluginManagement");return(0,n.jsxs)("section",{"aria-label":t("directInstall"),className:"min-w-0 space-y-3 rounded-lg border bg-card p-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:t("directInstall")}),(0,n.jsx)(N.$,{size:"sm",variant:"ghost",onClick:e.onClose,children:t("close")})]}),(0,n.jsx)("label",{htmlFor:"plugin-direct-source",className:"block text-sm font-medium",children:t("source")}),(0,n.jsx)(t8.T,{id:"plugin-direct-source",value:e.source,placeholder:t("batchSourcePlaceholder"),rows:2,disabled:e.pending,onChange:t=>e.onSource(t.target.value)}),e.isNpm||e.multiple?(0,n.jsxs)(eW.Nt,{children:[(0,n.jsxs)(eW.R6,{className:"group flex min-h-8 items-center gap-2 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t("advancedOptions"),(0,n.jsx)(eq.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eW.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"space-y-3 pt-2",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{children:t("installChannel")}),(0,n.jsx)(t3,{value:e.tag,label:t("installChannel"),placeholder:t("defaultChannel"),disabled:e.pending,onChange:e.onTag})]}),e.isNpm?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:e.loading,onClick:e.onRead,children:t(e.loading?"loadingPackage":"readPackage")}):null,e.detail?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.detail.name}),(0,n.jsxs)(ea.l6,{value:e.selectedVersion,onOpenChange:(t,s)=>{t&&(e.loading||e.pending)&&s.cancel()},items:[{value:"",label:t("automaticVersion")},...[...new Set([e.detail.version,...e.detail.versions])].map(e=>({value:e,label:e}))],onValueChange:t=>{null===t||e.loading||e.pending||e.onVersion(t)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("version"),"aria-disabled":e.loading||e.pending,className:"max-w-full",children:(0,n.jsx)(ea.yv,{})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[160]",children:[(0,n.jsx)(ea.eb,{value:"",disabled:e.loading||e.pending,children:t("automaticVersion")}),[...new Set([e.detail.version,...e.detail.versions])].map(t=>(0,n.jsx)(ea.eb,{value:t,disabled:e.loading||e.pending,children:t},t))]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t("targetVersion",{version:e.detail.version})})]}):null,(0,n.jsx)(tD,{id:"plugin-direct-download",mode:e.override,registry:e.registry,override:!0,saving:e.pending,onMode:e.onMode,onRegistry:e.onRegistry})]})})]}):null,e.error?(0,n.jsx)("p",{role:"alert",className:"text-sm whitespace-pre-wrap text-destructive [overflow-wrap:anywhere]",children:e.error}):null,e.operationMessage?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground [overflow-wrap:anywhere]",children:e.operationMessage}):null,(0,n.jsx)(N.$,{size:"sm",disabled:e.disabled||e.loading||e.pending||!e.source.trim(),onClick:e.onInstall,children:t(e.pending?"installing":e.multiple?"batchInstall":"install")})]})}function t9({confirmation:e,onClose:t,onConfirm:s}){let{t:r}=(0,f.Bd)("pluginManagement"),a=e?r(tN(e)):null,i=e?.kind==="del"||e?.kind==="batch"&&"del"===e.input.action,l=e?.kind==="add"||e?.kind==="batch"&&"add"===e.input.action;return(0,n.jsx)(ej.YV,{open:!!e,onOpenChange:e=>{e||t()},children:(0,n.jsxs)(ej.hA,{className:"z-[150] max-w-lg",backdropClassName:"z-[140]",children:[(0,n.jsxs)(ej.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(ej.YM,{children:r("confirmAction",{action:a})}),(0,n.jsx)(ej.uX,{children:r(i?"removeDescription":l?"thirdPartyDescription":e?.kind==="reload"?"normal"===e.mode?"restartNormalDescription":"restartDescription":"confirmChange")})]}),(0,n.jsx)(ej._Y,{className:"min-h-0",children:(0,n.jsx)("div",{className:"min-w-0 p-4 pt-0",children:e?.kind==="batch"?(0,n.jsx)("ul",{className:"space-y-2 text-sm",children:("add"===e.input.action?e.input.items.map(e=>e.source):e.input.sources).map(e=>(0,n.jsx)("li",{className:"font-medium [overflow-wrap:anywhere]",children:e.startsWith("npm:")?ty(e)?.name??e:e},e))}):e?.kind==="add"?(0,n.jsxs)("dl",{className:"space-y-3 text-sm",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("packageName")}),(0,n.jsx)("dd",{className:"mt-1 font-medium [overflow-wrap:anywhere]",children:e.package?.name??e.input.source})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("version")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.version??ty(e.input.source)?.version??r("fromSource")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("publisher")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.package?.publisher??r("unknownPublisher")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:r("source")}),(0,n.jsx)("dd",{className:"[overflow-wrap:anywhere]",children:e.input.registry??e.package?.registry??e.input.source})]})]}):e&&"reload"!==e.kind?(0,n.jsx)("p",{className:"text-sm font-medium [overflow-wrap:anywhere]",children:e.source.startsWith("npm:")?ty(e.source)?.name??e.source:e.source}):null})}),(0,n.jsxs)(ej.vu,{children:[(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:t,children:r("cancel")}),(0,n.jsx)(N.$,{size:"sm",variant:i?"destructive":"default",onClick:()=>{e&&s(e)},children:a})]})]})})}function se({basicMode:e=!1,snapshot:t,biz:s,onSnapshot:a,onRestartScheduled:i}){let{t:l}=(0,f.Bd)("pluginManagement"),{locale:o}=(0,eG.i)(),[d,c]=(0,r.useState)("installed"),[u,m]=(0,r.useState)(""),[p,h]=(0,r.useState)("all"),[g,x]=(0,r.useState)(!1),[b,v]=(0,r.useState)(()=>new Set);(0,r.useEffect)(()=>{if(!t)return;let e=new Set(t.plugins.map(e=>tj(e.source)));[...b].some(t=>!e.has(t))&&queueMicrotask(()=>v(t=>new Set([...t].filter(t=>e.has(t)))))},[t,b]);let[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)(!1),I=function({basicMode:e=!1,biz:t,snapshot:s,onSnapshot:n,onRestartScheduled:a}){let{t:i}=(0,f.Bd)("pluginManagement"),l=(0,J.t4)();(0,J.So)();let[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(()=>new Set),m=(0,r.useRef)(new Set),[p,h]=(0,r.useState)(null),[g,x]=(0,r.useState)({}),[b,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(null),C=(0,r.useRef)(0),S=(0,r.useRef)(0),M=(0,r.useRef)(!0),z=(e,t)=>{t?m.current.add(e):m.current.delete(e),M.current&&u(new Set(m.current))},E=(e,t)=>{M.current&&x(s=>{let n={...s};return t?n[e]=t:delete n[e],n})},A=e=>{let t=tj(e);return m.current.has(t)||!!s?.plugins.some(e=>tj(e.source)===t&&e.operation&&"failed"!==e.operation.phase)},$=async(e=!1)=>{let s=++S.current,r=await t.list(e);M.current&&s===S.current&&n(r)},R=async(e,t)=>{if(m.current.has("check"))return;let n=e??s?.plugins.filter(e=>"package"===e.kind&&(!t||e.updateTag===t)).map(e=>e.source)??[],r=n.filter(A),a=n.filter(e=>!A(e));if(r.forEach(e=>E(tj(e),i("sourceBusy"))),!a.length)return;let l=a.map(tj);z("check",!0),l.forEach(e=>z(e,!0)),d(!0),E("list",null);try{if(e||r.length)for(let e=0;e<a.length&&(await $({checkUpdates:!0,sources:a.slice(e,e+32),...t?{tag:t}:{}}),M.current);e+=32);else await $({checkUpdates:!0,...t?{tag:t}:{}})}catch(e){E("list",e instanceof Error?e.message:i("updateCheckFailed"))}finally{z("check",!1),l.forEach(e=>z(e,!1)),M.current&&d(!1)}};(0,r.useEffect)(()=>{M.current=!0;let s=!0,r=++S.current;return queueMicrotask(()=>{s&&(d(!0),t.list(!1).then(async a=>{if(!s||r!==S.current)return;n(a);let i=a.plugins.some(e=>"package"===e.kind&&/^(npm:|git:|https?:|git@)/.test(e.source)&&null===e.updateAvailable&&!e.updateError&&!e.operation);if(!e&&i){let e=await t.list(!0);s&&r===S.current&&n(e)}}).catch(e=>{s&&E("list",e instanceof Error?e.message:i("updateCheckFailed"))}).finally(()=>{s&&d(!1)}))}),()=>{s=!1,M.current=!1,C.current+=1,S.current+=1}},[t,n,i,e]);let T=async e=>{let s="add"===e.action?e.items.map(e=>e.source):e.sources,r=s.filter(e=>!A(e));if(s.filter(A).forEach(e=>E(tj(e),i("sourceBusy"))),!r.length)return;let a=r.map(tj);a.forEach(e=>{z(e,!0),E(e,null)}),h(null);let l=[...r];try{let s=await t.list(),r=Date.now()+9e5;for(;l.length;){let a=s.plugins.filter(e=>e.operation&&"failed"!==e.operation.phase),o="tag"===e.action?32:Math.max(0,32-a.length);if(!o){if(a.some(e=>e.operation?.phase==="waiting")||Date.now()>=r){l.forEach(e=>E(tj(e),i("batchWaiting")));break}await new Promise(e=>setTimeout(e,750)),s=await t.list(),M.current&&(S.current+=1,n(s));continue}let d=l.slice(0,o),c="add"===e.action?{...e,items:e.items.filter(e=>d.includes(e.source))}:{...e,sources:d},u=await t.batch(c);s=u.snapshot,M.current&&(S.current+=1,n(s)),u.results.forEach(e=>E(tj(e.source),e.error)),d.forEach(e=>z(tj(e),!1)),l=l.slice(d.length)}}catch(t){let e=t instanceof Error?t.message:i("batchFailed");l.forEach(t=>E(tj(t),e))}finally{a.forEach(e=>z(e,!1))}},P=async e=>{if("batch"===e.kind)return void await T(e.input);if("reload"!==e.kind&&A("add"===e.kind?e.input.source:e.source))return;let s="reload"===e.kind?"reload":tj("add"===e.kind?e.input.source:e.source);if(!m.current.has(s)){z(s,!0),h(null),E(s,null);try{let s="add"===e.kind?await t.add(e.input):"update"===e.kind?await t.update(e.source):"del"===e.kind?await t.del(e.source):"enable"===e.kind||"disable"===e.kind?await t.setEnabled(e.source,"enable"===e.kind):await t.reload(e.mode);if(!M.current)return;S.current+=1,n(s),"reload"===e.kind?a():await $()}catch(t){E(s,t instanceof Error?t.message:i("actionFailed",{action:i(tN(e))}))}finally{z(s,!1)}}},D=(e,t)=>{let s={kind:"add",input:e,package:t};t?.official===!0?P(s):h(s)},O=async e=>{let s=e?.[0]?tj(e[0]):"apply";if(!m.current.has(s)){z(s,!0),E(s,null);try{let s=await t.apply(e);M.current&&(S.current+=1,n(s),await $())}catch(e){E(s,e instanceof Error?e.message:i("actionFailed",{action:i("reloadOne")}))}finally{z(s,!1)}}},L=async(e,t)=>{if(!m.current.has(e)){z(e,!0),E(e,null);try{await t()}catch(t){E(e,t instanceof Error?t.message:i("retryFailed"))}finally{z(e,!1)}}},F=async e=>{let s=++C.current;j(!0),I(null);try{let n=await t.get(e);M.current&&s===C.current&&y(n)}catch(e){M.current&&s===C.current&&I(e instanceof Error?e.message:i("detailFailed"))}finally{M.current&&s===C.current&&j(!1)}};return{loading:o,requests:c,confirmation:p,setConfirmation:h,errors:g,detailSource:b,detail:w,detailLoading:k,detailError:N,pluginHost:l,refresh:R,executeBatch:T,execute:P,requestInstall:D,applyChanges:O,loadDetail:F,openDetail:e=>{v(e),y(null),F(e)},closeDetail:()=>{C.current+=1,v(null),y(null),I(null),j(!1)},handleControlAction:(e,t)=>{switch(t){case"reload":O([e.source]);break;case"update":P({kind:"update",source:e.source});break;case"remove":h({kind:"del",source:e.source});break;case"enable":case"disable":P({kind:t,source:e.source});break;case"retry-browser":e.pluginName&&L(`entry:${e.pluginName}`,()=>l.retryEntry(e.pluginName));break;case"retry":{let t=e.operation?.action;"apply"===t?O([e.source]):"add"===t?D({source:e.source}):t&&P({kind:t,source:e.source})}}},refreshEntries:()=>L("entries",()=>l.refreshEntries())}}({biz:s,snapshot:t,onSnapshot:a,onRestartScheduled:i,basicMode:e}),C=function(e,t){let{t:s}=(0,f.Bd)("pluginManagement"),[n,a]=(0,r.useState)(""),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)("all"),[c,u]=(0,r.useState)("public"),[m,p]=(0,r.useState)(""),[h,g]=(0,r.useState)([]),[x,b]=(0,r.useState)(!1),[v,w]=(0,r.useState)(1),[y,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),[I,C]=(0,r.useState)(!1),[S,M]=(0,r.useState)(null),[z,E]=(0,r.useState)(null),[A,$]=(0,r.useState)(!1),[R,T]=(0,r.useState)(null),[P,D]=(0,r.useState)(()=>new Set),[O,L]=(0,r.useState)({}),F=(0,r.useRef)(0),_=(0,r.useRef)(0),B=(0,r.useRef)(new Set),q=(0,r.useRef)(null),[W,Y]=(0,r.useState)(!1),[U,V]=(0,r.useState)("default"),[K,H]=(0,r.useState)(""),G=(0,r.useRef)(!0);(0,r.useEffect)(()=>(G.current=!0,()=>{G.current=!1,F.current+=1,_.current+=1}),[]);let J=(0,r.useCallback)(async(t,n)=>{k(!0),N(null);try{let s=await e.searchCatalog(t);if(!G.current||n!==F.current)return;g(e=>{let n=1===t.page?s.items:[...e,...s.items],r=e=>e.official?0:"desk"===e.kind?1:"pi"===e.kind?2:3;return[...new Map(n.map(e=>[e.name,e])).values()].sort((e,t)=>r(e)-r(t))}),w(t.page),b(s.hasMore),C(!0)}catch(e){G.current&&n===F.current&&N(e instanceof Error?e.message:s("searchFailed"))}finally{G.current&&n===F.current&&k(!1)}},[e,s]);(0,r.useEffect)(()=>{t&&queueMicrotask(()=>Y(!0))},[t]),(0,r.useEffect)(()=>{if(!W||i)return;let e=++F.current;q.current=null,queueMicrotask(()=>{G.current&&e===F.current&&(k(!0),N(null),b(!1))});let t=setTimeout(()=>{let t="custom"===c?tC.safeParse(m):null;if(t&&!t.success){q.current=null,g([]),b(!1),C(!1),N(s("invalidRegistry")),k(!1);return}let r={query:n.trim(),kind:o,page:1,...t?.success?{registry:t.data}:{}};q.current=r,g([]),b(!1),C(!1),J(r,e)},300);return()=>clearTimeout(t)},[n,o,c,m,i,J,W,s]);let Q=async(t,n=t.version)=>{let r=++_.current;$(!0),T(null),L(e=>{let s={...e};return delete s[t.name],s});try{let s=await e.getCatalog({name:t.name,registry:t.registry,version:n});G.current&&r===_.current&&E(s)}catch(e){G.current&&r===_.current&&T(e instanceof Error?e.message:s("detailFailed"))}finally{G.current&&r===_.current&&$(!1)}};return{query:n,setQuery:a,composing:i,beginComposition:()=>{F.current+=1,q.current=null,k(!1),l(!0)},endComposition:()=>l(!1),kind:o,setKind:d,searchSource:c,setSearchSource:u,registry:m,setRegistry:p,items:h,loading:y,error:j,searched:I,hasMore:x,loadMore:()=>{q.current&&!y&&x&&J({...q.current,page:v+1},F.current)},retry:()=>{if(i||y)return;let e="custom"===c?tC.safeParse(m):null;if(e&&!e.success)return void N(s("invalidRegistry"));let t={query:n.trim(),kind:o,page:1,...e?.success?{registry:e.data}:{}};q.current=t,g([]),J(t,++F.current)},selection:S,detail:z,detailLoading:A,detailError:R,openDetail:e=>{M(e),E(null),V("default"),H(""),Q(e)},closeDetail:()=>{_.current+=1,M(null),E(null),$(!1),T(null)},loadDetail:Q,prepareInstall:async(t,n)=>{if(!B.current.has(t.name)){B.current.add(t.name),D(new Set(B.current)),L(e=>{let s={...e};return delete s[t.name],s});try{let r=await e.getCatalog({name:t.name,version:t.version,registry:t.registry});if(!G.current)return;if(!1===r.compatible)return void L(e=>({...e,[t.name]:s("installIncompatible")}));n(r)}catch(e){G.current&&L(n=>({...n,[t.name]:e instanceof Error?e.message:s("detailFailed")}))}finally{B.current.delete(t.name),G.current&&D(new Set(B.current))}}},preparing:P,installErrors:O,downloadMode:U,setDownloadMode:V,downloadRegistry:K,setDownloadRegistry:H,installDetail:e=>{if(!z||A)return;if(!1===z.compatible)return void L(e=>({...e,[z.name]:s("installIncompatible")}));let t="default"===U?null:tS.safeParse("custom"===U?{mode:U,registry:K}:{mode:U});t&&!t.success?L(e=>({...e,[z.name]:s("invalidRegistry")})):(L(e=>{let t={...e};return delete t[z.name],t}),e({source:`npm:${z.name}@${z.version}`,registry:z.registry,...t?.success?{downloadSource:t.data}:{}},z))}}}(s,"search"===d),S=function(e,t){let{t:s}=(0,f.Bd)("pluginManagement"),[n,a]=(0,r.useState)(null),[i,l]=(0,r.useState)("auto"),[o,d]=(0,r.useState)(""),[c,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null),x=(0,r.useRef)(!0),b=(0,r.useRef)(!1),v=(0,r.useRef)(0),w=(0,r.useRef)("load"),y=async()=>{let t=v.current;u(!0),g(null);try{let s=await e.getCatalogSettings();if(!x.current)return;t===v.current?(a(s),l(s.downloadSource.mode),"custom"===s.downloadSource.mode&&d(s.downloadSource.registry)):a(e=>e??s)}catch(e){w.current="load",x.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{x.current&&u(!1)}};(0,r.useEffect)(()=>{x.current=!0;let e=!0;return queueMicrotask(()=>{e&&y()}),()=>{e=!1,x.current=!1}},[e]);let k=async(n=i)=>{if(b.current)return;let r=tS.safeParse("custom"===n?{mode:n,registry:o}:{mode:n});if(!r.success){w.current="save",g(s("invalidRegistry"));return}b.current=!0,p(!0),g(null);try{let s=await e.saveCatalogSettings(r.data);x.current&&(a(s),l(s.downloadSource.mode),t())}catch(e){w.current="save",x.current&&g(e instanceof Error?e.message:s("settingsFailed"))}finally{b.current=!1,x.current&&p(!1)}};return{settings:n,mode:i,registry:o,setRegistry:e=>{v.current+=1,d(e)},loading:c,saving:m,error:h,load:y,save:k,changeMode:e=>{v.current+=1,l(e),"custom"!==e&&k(e)},retry:()=>"save"===w.current?k():y()}}(s,()=>{e||I.refresh()}),M=function(e,t=[]){let{t:s}=(0,f.Bd)("pluginManagement"),[n,a]=(0,r.useState)(!1),[i,l]=(0,r.useState)(""),[o,d]=(0,r.useState)(""),[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[x,b]=(0,r.useState)(null),[v,w]=(0,r.useState)("default"),[y,k]=(0,r.useState)(""),j=(0,r.useRef)(0),N=(0,r.useRef)(!0),I=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),C=1===I.length?ty(I[0]):null;(0,r.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current+=1}),[]);let S=()=>{j.current+=1,p(null),g(!1),b(null)},M=async n=>{let r;if(!C)return null;void 0!==n&&u(n||null);let a=t.find(e=>ty(e.source)?.name===C.name)?.updateTag,i=C.version??(o||a||"latest"),l=""===n?i:n??c??i;if("custom"===v){let e=tC.safeParse(y);if(!e.success)return b(s("invalidRegistry")),null;r=e.data}else"official"===v?r="https://registry.npmjs.org":"domestic"===v&&(r="https://registry.npmmirror.com");let d=++j.current;g(!0),p(null),b(null);try{let t=await e.getCatalog({...C,...l?{version:l}:{},...r?{registry:r}:{}});if(!N.current||d!==j.current)return null;return p(t),t}catch(e){return N.current&&d===j.current&&b(e instanceof Error?e.message:s("detailFailed")),null}finally{N.current&&d===j.current&&g(!1)}},z=async(e,t)=>{if(!I.length||h)return;b(null);let n="default"===v?null:tS.safeParse("custom"===v?{mode:v,registry:y}:{mode:v});if(n&&!n.success)return void b(s("invalidRegistry"));let r={...o?{tag:o}:{},...n?.success?{downloadSource:n.data}:{}};if(I.length>1){let e=I.map(ty);if(I.length>32||e.some(e=>!e))return void b(s(I.length>32?"batchLimit":"batchNpmOnly"));let n=new Map;return e.forEach(e=>{e&&n.set(e.name,{source:`npm:${e.name}${e.version?`@${e.version}`:""}`,...r})}),void t([...n.values()])}if(!C)return void e({source:I[0]});let a=m?Promise.resolve(m):M(c??void 0),i=j.current,l=await a;if(l&&N.current&&i===j.current){if(!1===l.compatible)return void b(s("installIncompatible"));e({source:`npm:${l.name}${c||C.version?`@${c??C.version}`:""}`,registry:l.registry,...r},l)}};return{open:n,setOpen:a,source:i,sources:I,tag:o,selectedVersion:c??"",setTag:e=>{S(),u(null),d(e)},changeSource:e=>{S(),u(null),l(e)},spec:C,detail:m,loading:h,error:x,override:v,setOverride:e=>{S(),w(e)},registry:y,setRegistry:e=>{S(),k(e)},loadDetail:M,install:z}}(s,t?.plugins),z=e||I.requests.has("reload"),A=new Map(I.pluginHost.getFailedEntries().map(e=>[e.pluginName,e.error.message])),$=I.pluginHost.getEntryListError(),R=t?.plugins.find(e=>e.source===I.detailSource),T=C.selection?t?.plugins.find(e=>e.source.startsWith("npm:")&&ty(e.source)?.name===C.selection?.name):void 0,P=C.selection?tj(`npm:${C.selection.name}`):"",D=tj(M.detail?`npm:${M.detail.name}`:M.spec?`npm:${M.spec.name}`:M.source.trim()),O=t?.plugins.find(e=>tj(e.source)===D),L=e=>{let s=t?.plugins.find(t=>tj(t.source)===tj(e));return I.requests.has(tj(e))||!!(s?.operation&&"failed"!==s.operation.phase)},F=L(`npm:${C.selection?.name??""}`),_=M.sources.some(L),B=M.sources.map(e=>{let s=tj(e),n=t?.plugins.find(e=>tj(e.source)===s),r=I.errors[s]??(n?.operation?.phase==="failed"?n.operation.message:null);return r?`${e}: ${r}`:null}).filter(Boolean).join("\n"),q=!!(I.detailSource||C.selection),W=(0,r.useRef)(null),Y=(0,r.useRef)(null);(0,r.useEffect)(()=>{q?W.current?.focus():Y.current?.isConnected&&(Y.current.focus(),Y.current=null)},[q]);let U=()=>{Y.current=document.activeElement instanceof HTMLElement?document.activeElement:null},V=e=>{let s=t?.plugins.find(t=>ty(t.source)?.name===e.name);return{...e,version:s?.updateTag??"latest"}},K=e=>t?.plugins.filter(t=>"extension"!==t.kind&&!0===t.updateAvailable&&!L(t.source)&&(!e||b.has(tj(t.source)))).map(e=>e.source)??[],H=e=>e?l(`phase_${e}`):null,G=()=>{c("installed"),M.setOpen(!0)};return(0,n.jsxs)("div",{className:"flex h-full min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("header",{className:"shrink-0 space-y-3 border-b p-4 sm:px-6",children:[q?(0,n.jsxs)(N.$,{ref:W,size:"sm",variant:"ghost",className:"-ml-2",onClick:()=>{I.closeDetail(),C.closeDetail()},children:[(0,n.jsx)(E.A,{}),l("backToList")]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h2",{className:"min-w-0 text-xl font-semibold [overflow-wrap:anywhere]",children:q?R?tk(R):C.selection?.name??l("details"):l("title")}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[q?null:(0,n.jsxs)(eJ.AM,{children:[(0,n.jsxs)(eJ.Wv,{render:(0,n.jsx)(N.$,{size:"sm",variant:"ghost"}),children:[l("downloadSource"),":",S.loading&&!S.settings?l("loading"):l(`download_${S.settings?.downloadSource.mode??S.mode}`),(0,n.jsx)(eq.A,{className:"size-4"})]}),(0,n.jsx)(eJ.hl,{align:"end",positionerClassName:"z-[150]",className:"w-80 max-w-[calc(100vw-2rem)]",children:(0,n.jsx)(tD,{id:"plugin-default-download",mode:S.mode,registry:S.registry,savedRegistry:S.settings?.downloadSource.mode==="custom"?S.settings.downloadSource.registry:void 0,recommendedRegistry:S.settings?.recommendedRegistry,loading:S.loading,saving:S.saving,error:S.error,onMode:e=>{"default"!==e&&S.changeMode(e)},onRegistry:S.setRegistry,onSave:()=>void S.save(),onRetry:()=>void S.retry()})})]}),e||t?.restartRequired?(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:I.requests.has("reload"),onClick:()=>I.setConfirmation({kind:"reload",mode:e?"normal":void 0}),children:l(e?"restartNormal":"restartApply")}):null]})]}),e?(0,n.jsx)("p",{role:"status",className:"rounded-lg bg-muted p-3 text-sm",children:l("basicModeNotice")}):null,t?.restartRequired?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("pendingRestart")}):null,t?.loadError||$?(0,n.jsxs)("div",{role:"alert",className:"max-h-32 space-y-1 overflow-y-auto text-sm text-destructive",children:[t?.loadError?(0,n.jsx)("p",{className:"[overflow-wrap:anywhere]",children:(0,eH.fD)(t.loadError,o)}):null,$?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"min-w-0 [overflow-wrap:anywhere]",children:$}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:I.requests.has("entries"),onClick:()=>void I.refreshEntries(),children:l("retry")})]}):null]}):null,I.errors.reload||I.errors.entries?(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive [overflow-wrap:anywhere]",children:I.errors.reload??I.errors.entries}):null]}),(0,n.jsxs)(e2,{value:d,onValueChange:e=>c(String(e)),className:`min-h-0 flex-1 gap-0 ${q?"hidden":""}`,children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 pt-2 sm:px-6",children:(0,n.jsxs)(e3,{variant:"line","aria-label":l("title"),className:"h-9",children:[(0,n.jsxs)(e4,{value:"installed",className:"px-3",children:[l("installedTab"),t?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t.plugins.length}):null]}),(0,n.jsx)(e4,{value:"search",className:"px-3",children:l("searchPlugins")})]})}),(0,n.jsx)(e6,{value:"installed",keepMounted:!0,className:"flex min-h-0 flex-col overflow-hidden p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[M.open?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar max-h-1/2 shrink-0 overflow-y-auto",children:(0,n.jsx)(t7,{source:M.source,isNpm:!!M.spec,multiple:M.sources.length>1,tag:M.tag,selectedVersion:M.selectedVersion,onTag:M.setTag,detail:M.detail,loading:M.loading,pending:_,disabled:z,error:M.error??(B||null),operationMessage:_?H(O?.operation?.phase)??l("submitting"):null,override:M.override,registry:M.registry,onSource:M.changeSource,onMode:M.setOverride,onRegistry:M.setRegistry,onRead:()=>void M.loadDetail(),onVersion:e=>void M.loadDetail(e),onInstall:()=>void M.install(I.requestInstall,e=>I.setConfirmation({kind:"batch",input:{action:"add",items:e}})),onClose:()=>M.setOpen(!1)})}):null,(0,n.jsx)(tB,{snapshot:t,loading:I.loading,filter:u,statusFilter:p,batchMode:g,selected:b,onStatusFilter:h,onBatchMode:e=>{x(e),e||v(new Set)},onSelect:(e,t)=>{v(s=>{let n=new Set(s);return e.forEach(e=>{t?n.add(e):n.delete(e)}),n})},onUpdateAll:()=>void I.executeBatch({action:"update",sources:K(!1)}),onUpdateSelected:()=>void I.executeBatch({action:"update",sources:K(!0)}),onRemoveSelected:()=>I.setConfirmation({kind:"batch",input:{action:"del",sources:t?.plugins.filter(e=>b.has(tj(e.source))&&!L(e.source)).map(e=>e.source)??[]}}),disabled:z,requests:I.requests,errors:I.errors,browserErrors:A,onFilter:m,onDetail:e=>{U(),C.closeDetail(),I.openDetail(e)},onAction:I.handleControlAction,onRefresh:()=>void I.refresh()}),t?.plugins.length||M.open?null:(0,n.jsx)(N.$,{size:"sm",variant:"outline",className:"shrink-0 self-start",disabled:z,onClick:G,children:l("directInstall")})]})}),(0,n.jsx)(e6,{value:"search",keepMounted:!0,className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto p-4 data-[hidden]:hidden sm:p-6",children:(0,n.jsx)(tq,{query:C.query,kind:C.kind,searchSource:C.searchSource,registry:C.registry,items:C.items,loading:C.loading,error:C.error,searched:C.searched,hasMore:C.hasMore,disabled:z,snapshot:t,requests:I.requests,preparing:C.preparing,errors:I.errors,installErrors:C.installErrors,onQuery:C.setQuery,onCompositionStart:C.beginComposition,onCompositionEnd:C.endComposition,onKind:C.setKind,onSearchSource:e=>{C.setSearchSource(e),"custom"!==e||C.registry||S.settings?.downloadSource.mode!=="custom"||C.setRegistry(S.settings.downloadSource.registry)},onRegistry:C.setRegistry,onDetail:e=>{U(),I.closeDetail(),y(""),j(!1),C.openDetail(V(e))},onInstall:e=>{C.prepareInstall(V(e),e=>I.requestInstall({source:`npm:${e.name}`,registry:e.registry},e))},onUpdate:e=>void I.execute({kind:"update",source:e}),onMore:C.loadMore,onRetry:C.retry,onDirectInstall:G})})]}),q?(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:R?(0,n.jsxs)("div",{className:"min-w-0 space-y-5",children:[(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[R.version?(0,n.jsxs)("span",{children:["v",R.version]}):null,R.updateAvailable?(0,n.jsx)("span",{className:"rounded-md bg-status-success/10 px-2 py-0.5 text-xs font-medium text-status-success",children:R.availableVersion?l("newVersion",{version:R.availableVersion}):l("updateAvailable")}):null]}),(0,n.jsx)(tv,{plugin:R,displayName:tk(R),browserError:R.pluginName?A.get(R.pluginName)??null:null,disabled:z,pending:L(R.source),browserRetryPending:I.requests.has(`entry:${R.pluginName}`),onAction:e=>I.handleControlAction(R,e)})]}),R.description?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:(0,eH.fD)(R.description,o)}):null,(0,n.jsx)(tw,{plugin:R,requestError:I.errors[tj(R.source)],browserError:R.pluginName?A.get(R.pluginName)??null:null})]}),(0,n.jsxs)(eW.Nt,{className:"rounded-lg border",children:[(0,n.jsxs)(eW.R6,{className:"group flex min-h-9 w-full items-center justify-between px-3 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("advancedOptions"),(0,n.jsx)(eq.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eW.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 px-3 pb-3",children:[R.source.startsWith("npm:")?(0,n.jsx)(t3,{value:R.updateTag??"latest",label:l("installChannel"),disabled:z||L(R.source),onChange:e=>void I.executeBatch({action:"tag",sources:[R.source],tag:e})}):null,(0,n.jsx)(N.$,{size:"sm",variant:"outline",disabled:z||L(R.source)&&R.operation?.phase!=="waiting",onClick:()=>I.handleControlAction(R,"reload"),children:l("reloadOne")})]})})]}),I.detailLoading?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("loadingPackage")}):null,I.detail?.readme?(0,n.jsx)(t5,{readme:I.detail.readme},R.source):null,(0,n.jsxs)(eW.Nt,{className:"border-t pt-2",children:[(0,n.jsxs)(eW.R6,{className:"group flex min-h-9 w-full items-center justify-between text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l("capabilityDetails"),(0,n.jsx)(eq.A,{className:"size-4 transition-transform group-aria-expanded:rotate-180"})]}),(0,n.jsx)(eW.Ke,{keepMounted:!0,className:"hidden data-open:block",children:(0,n.jsx)(tg,{plugin:R,detail:I.detail,detailLoading:I.detailLoading,detailError:I.detailError,browserContributions:R.pluginName?I.pluginHost.getRegisteredBrowserDescriptors().find(e=>e.pluginName===R.pluginName)?.contributions??[]:[],onRetry:()=>void I.loadDetail(R.source)})})]}),I.detailError?(0,n.jsxs)("div",{role:"alert",className:"flex items-center gap-2 text-sm text-destructive",children:[(0,n.jsx)("span",{children:I.detailError}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:()=>void I.loadDetail(R.source),children:l("retry")})]}):null]}):C.selection?(0,n.jsxs)(n.Fragment,{children:[C.detailLoading?(0,n.jsx)("p",{role:"status",className:"mb-3 text-sm text-muted-foreground",children:l("loadingPackage")}):null,C.detailError?(0,n.jsxs)("div",{role:"alert",className:"mb-3 space-y-2 text-sm",children:[(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:C.detailError}),(0,n.jsx)(N.$,{size:"sm",variant:"outline",onClick:()=>void C.loadDetail(C.selection),children:l("retry")})]}):null,C.detail?(0,n.jsx)(t6,{detail:C.detail,disabled:z||!!C.detailError,pending:F||C.detailLoading,installed:!!(T&&(T.operation?.action!=="add"||"failed"!==T.operation.phase)),installedVersion:T?.version??null,updateAvailable:!!T?.updateAvailable,error:C.installErrors[C.detail.name]??I.errors[P]??(T?.operation?.phase==="failed"?T.operation.message:null),operationMessage:C.detailLoading?l("loadingPackage"):H(T?.operation?.phase),channel:w,onChannel:e=>{y(e),j(!1),C.loadDetail(C.selection,e||T?.updateTag||"latest")},downloadMode:C.downloadMode,downloadRegistry:C.downloadRegistry,onDownloadMode:C.setDownloadMode,onDownloadRegistry:C.setDownloadRegistry,onVersion:e=>{j(!0),C.loadDetail(C.selection,e)},onInstall:()=>C.installDetail((e,t)=>I.requestInstall({...e,source:k?e.source:`npm:${t.name}`,...w?{tag:w}:{}},t)),onUpdate:()=>{T&&I.execute({kind:"update",source:T.source})}}):null]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:l("pluginRemoved")})}):null,(0,n.jsx)(t9,{confirmation:I.confirmation,onClose:()=>I.setConfirmation(null),onConfirm:e=>void I.execute(e)})]})}var st=s(99739);let ss=a.Yj().trim().min(1).max(2048),sn=a.YO(ss).min(1).max(32),sr=a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eH.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0)}).strict(),sa=a.Yj().trim().min(1).max(4096),si=a.Yj().trim().min(1).max(256),sl=a.Yj().max(32768),so=a.Ik({name:si,label:sl,state:a.k5(["active","inactive","shadowed"]),description:sl,promptSnippet:sl.nullable(),promptGuidelineCount:a.ai().int().nonnegative(),promptGuidelinePreview:sl.nullable()}).strict(),sd=a.Ik({name:si,label:sl,state:a.k5(["active","inactive","shadowed"]),description:sl,parameters:st.Dz,promptSnippet:sl.nullable(),promptGuidelines:a.YO(sl)}).strict(),sc=a.Ik({path:sa,events:a.YO(a.Ik({name:si,count:a.ai().int().positive()}).strict()),commands:a.YO(a.Ik({name:si,description:sl.nullable()}).strict()),shortcuts:a.YO(a.Ik({shortcut:si,description:sl.nullable()}).strict()),flags:a.YO(a.Ik({name:si,type:a.k5(["boolean","string"]),description:sl.nullable(),default:a.KC([a.zM(),a.Yj(),a.ch()])}).strict()),messageRenderers:a.YO(si),entryRenderers:a.YO(si)}).strict(),su=a.Ik({name:si,description:sl,path:sa}).strict(),sm=su.extend({modelVisible:a.zM()}).strict(),sp=su.extend({content:a.Yj().max(65536),truncated:a.zM()}).strict(),sh=sp.extend({modelVisible:a.zM()}).strict(),sg=a.Ik({name:si,path:sa}).strict(),sx=a.Ik({name:si,kind:a.k5(["config","native"])}).strict(),sf=a.Ik({methods:a.YO(a.Ik({pluginName:si,method:si}).strict()),browserEntries:a.YO(a.Ik({pluginName:si}).strict()),messageDeclarations:a.YO(a.Ik({pluginName:si,declarationName:si,priority:a.ai().int().safe()}).strict())}).strict(),sb=a.Ik({error:eH.qf.refine(e=>"string"==typeof e?e.length<=32768:[e.default,...Object.values(e.translations)].every(e=>e.length<=32768)).nullable(),extensions:a.YO(sc),tools:a.YO(so),skills:a.YO(sm),prompts:a.YO(su),themes:a.YO(sg),providers:a.YO(sx),piDesk:sf}).strict(),sv=a.Ik({action:a.k5(["add","update","del","apply","enable","disable"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().max(4e3).nullable()}).strict(),sw=(0,i._G)({path:"plugins/management-update",bodySchema:a.Ik({}).strict()}),sy=a.Ik({source:ss,kind:a.k5(["package","extension"]).default("package"),operation:sv.nullable().default(null),pluginName:a.Yj().trim().min(1).nullable(),description:eH.qf.nullable().default(null),version:a.Yj().trim().min(1).nullable(),updateAvailable:a.zM().nullable(),updateTag:tI.nullable().optional(),availableVersion:a.Yj().min(1).nullable().optional(),updateError:a.Yj().max(4e3).nullable().optional(),status:a.k5(["ready","available","disabled","failed"]),error:sr.nullable(),capabilities:sb}).strict(),sk=a.Ik({source:ss,readme:eH.qf.nullable().default(null),tools:a.YO(sd),skills:a.YO(sh),prompts:a.YO(sp)}).strict(),sj=a.Ik({plugins:a.YO(sy),restartRequired:a.zM(),loadError:eH.qf.refine(e=>"string"==typeof e?e.length>0:e.default.length>0).nullable()}).strict(),sN=a.Ik({sources:a.YO(ss).min(1).max(32).optional()}).strict(),sI=a.Ik({}).strict().extend({mode:a.k5(["normal","basic"]).optional()}).strict(),sC=a.Ik({checkUpdates:a.zM().optional(),sources:sn.optional(),tag:tI.optional()}).strict(),sS=a.Ik({source:ss}).strict(),sM=sS.extend({downloadSource:tS.optional(),registry:tC.optional(),tag:tI.optional()}).strict(),sz=a.gM("action",[a.Ik({action:a.eu("add"),items:a.YO(sM).min(1).max(32)}).strict(),a.Ik({action:a.eu("update"),sources:sn}).strict(),a.Ik({action:a.eu("del"),sources:sn}).strict(),a.Ik({action:a.eu("tag"),sources:sn,tag:tI}).strict()]),sE=a.Ik({snapshot:sj,results:a.YO(a.Ik({source:ss,error:a.Yj().max(4e3).nullable()}).strict()).max(32)}).strict(),sA=sS.extend({enabled:a.zM()}).strict();async function s$(e,t,s,n){return ec(e,t,s,n,{fallbackMessage:"插件管理请求失败"})}function sR({pluginName:e,descriptor:t,source:s,cwd:r,onPreviewFile:a,onRevealFile:i,onHeaderActionsChange:l}){let o=`${s.workId}\u0000${s.sessionId}\u0000${s.branchId}\u0000${r}`;return(0,n.jsx)(eU,{pluginName:e,kind:"session-sidebar-tab",contributionName:t.contributionName,target:{kind:"session-sidebar-tab",source:s,cwd:r,files:{preview:a,reveal:i},setHeaderActions:l},targetKey:o,layout:"fill"})}function sT({pluginName:e,descriptor:t,onClose:s,onBeforeLeaveChange:a}){let i=(0,J.t4)();(0,J.So)();let l=i.getEntryState(e),o="ready"===l.status?l.runtime:l.status;(0,r.useEffect)(()=>()=>{a(null)},[o,a]);let d=(0,r.useMemo)(()=>({kind:"settings-page",close:()=>{i.getEntryState(e)===l&&s()},setBeforeLeave:t=>{i.getEntryState(e)===l&&a(t)}}),[l,a,s,e,i]);return(0,n.jsx)(eU,{pluginName:e,kind:"settings-page",contributionName:t.contributionName,target:d,className:"pi-desk-chat-scrollbar h-full min-h-0 overflow-auto"})}var sP=s(10263),sD=s(11831),sO=s(79615),sL=s(24863),sF=s(10672);let s_="1.1.20-dev".trim()||"未知",sB="2026-10-25T17:12:44+08:00".trim()||null;var sq=s(42655),sW=s(55079),sY=s(49667),sU=s(61286),sV=s(33550),sK=s(66453),sH=s(67765);let sG=a.Yj().min(1).max(sH.uV).refine(e=>!e.includes("\0")&&(e.startsWith("/")||e.startsWith("\\\\")||/^[a-zA-Z]:[\\/]/.test(e)),"必须是绝对路径"),sJ=a.Ik({cwd:sK.m4.nullable()}).strict(),sQ=a.Ik({skillPath:sG,name:a.Yj().min(1),description:a.Yj(),packageSource:a.Yj().nullable()}).strict(),sX=a.Ik({skills:a.YO(sQ),diagnostics:a.YO(a.Ik({path:a.Yj(),message:eH.qf}).strict())}).strict(),sZ=sJ.extend({skillPath:sG}),s0=sZ.extend({path:sH.rh}).strict(),s1=a.Ik({entries:a.YO(a.Ik({name:a.Yj().min(1),type:a.k5(["directory","file"])}).strict()).max(sH.xm),truncated:a.zM()}).strict(),s2=sZ.extend({path:sH._g}).strict(),s5=a.gM("kind",[a.Ik({kind:a.eu("text"),content:a.Yj(),size:a.ai().int().nonnegative().max(sH.NL),readOnlyReason:eH.qf.nullable()}).strict(),a.Ik({kind:a.eu("image"),mimeType:sH.CT,data:a.Yj(),size:a.ai().int().nonnegative()}).strict(),a.Ik({kind:a.eu("unsupported"),size:a.ai().int().nonnegative(),reason:a.Yj()}).strict()]),s3=s2.extend({content:a.Yj().max(sH.NL)}).strict(),s4=a.Ik({}).strict(),s6={path:"/api/skills/list",request:sJ,response:sX},s8={path:"/api/skill-files/list",request:s0,response:s1},s7={path:"/api/skill-files/get",request:s2,response:s5},s9={path:"/api/skill-files/replace",request:s3,response:s4},ne=a.Ik({code:a.ai(),msg:a.Yj(),data:a.L5(),i18n:sU.N.optional()});async function nt(e,t,s,n){let r=await fetch(t.path,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(t.request.parse(s)),signal:n}),a=ne.parse(await r.json());if(!r.ok||0!==a.code||null===a.data)throw Error(a.msg?(0,ed.B)(a):"Skills 请求失败");return t.response.parse(a.data)}function ns(e){(0,sV.ZQ)({wrapLines:e})}async function nn(e){let t=e.skillPath.replaceAll("\\","/");await navigator.clipboard.writeText(t.slice(0,t.lastIndexOf("/")+1)+e.path)}var nr=s(46782);function na(e){return(0,ed.B)({msg:nr.P["zh-CN"][e],i18n:{key:`skills:${e}`}})}function ni(e){return JSON.stringify(e)}function nl(e){return JSON.stringify([e.cwd,e.skillPath,e.path])}function no(e){return e.replace(/\r\n|\r/g,"\n")}function nd(e){return e?.file?.kind==="text"&&e.draft!==no(e.file.content)}var nc=s(60794),nu=s(89757),nm=s(55628),np=s(91182);function nh(e){let{t}=(0,f.Bd)("common"),{wrapLines:s}=(0,sV.TX)(),a=e.path,i=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),d=(0,r.useRef)(null),c=(0,r.useRef)(null),u=(0,r.useRef)(0),m=(0,r.useRef)(e),[p,h]=(0,r.useState)(!1),[g,x]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{m.current=e}),(0,r.useEffect)(()=>{let e=!1,s=()=>void 0,n=()=>void 0;return(0,np.cu)().then(r=>{if(e||!i.current)return;let a=m.current,o=r.editor.create(i.current,{model:null,theme:(0,np.dC)(),automaticLayout:!0,readOnly:a.readOnly,domReadOnly:a.readOnly,wordWrap:(0,sV.E6)().wrapLines?"on":"off",wrappingIndent:"same",minimap:{enabled:!1},stickyScroll:{enabled:!1},scrollBeyondLastLine:!1,...(0,np.R)(),lineNumbersMinChars:3,padding:{top:14,bottom:14},unicodeHighlight:{nonBasicASCII:!1},renderWhitespace:"selection",overviewRulerBorder:!1,ariaLabel:t("skillEditor")});l.current=o,o.addCommand(r.KeyMod.CtrlCmd|r.KeyCode.KeyS,()=>m.current.onSave()),s=(0,np.Tr)(e=>r.editor.setTheme(e)),n=(0,np.BK)(e=>o.updateOptions(e)),x(!0)}).catch(()=>{e||h(!0)}),()=>{e=!0,s(),n(),d.current?.dispose(),d.current=null,o.current?.dispose(),o.current=null,c.current=null,l.current?.dispose(),l.current=null}},[t]),(0,r.useEffect)(()=>{let e=!1,t=u.current+1;return u.current=t,(0,np.cu)().then(s=>{if(e||t!==u.current||!l.current)return;let n=m.current,r=s.editor.createModel(n.content,(0,np.ix)(n.path,n.size),(0,np.B3)(s,n.path,"edit")),i=o.current;d.current?.dispose(),d.current=r.onDidChangeContent(()=>{m.current.onChange(r.getValue(s.editor.EndOfLinePreference.LF))}),o.current=r,c.current=a,l.current.setModel(r),i?.dispose()}),()=>{e=!0}},[a]),(0,r.useEffect)(()=>{let t=o.current;t&&c.current===e.path&&t.getValue().replace(/\r\n|\r/g,"\n")!==e.content&&t.setValue(e.content)},[e.content,e.path]),(0,r.useEffect)(()=>{l.current?.updateOptions({readOnly:e.readOnly,domReadOnly:e.readOnly,wordWrap:s?"on":"off"})},[e.readOnly,s]),(0,n.jsxs)("div",{"data-testid":"code-editor",className:"relative h-full min-h-0 w-full overflow-hidden bg-background",children:[(0,n.jsx)("div",{ref:i,className:"size-full"}),!g&&(0,n.jsx)("div",{role:"status",className:"absolute inset-0 flex items-center justify-center p-6 text-sm text-muted-foreground",children:p?t("editorFailed"):t("editorLoading")})]})}var ng=s(58840);function nx({file:e,path:t}){let{t:s}=(0,f.Bd)("skills"),a=(0,r.useMemo)(()=>[{src:`data:${e.mimeType};base64,${e.data}`,alt:t}],[e,t]);return(0,n.jsx)(ng.k,{mode:"inline",slides:a,className:"h-full w-full",ariaLabel:s("imagePreview")})}function nf(e){let{document:t,skill:s,dirty:r,loading:a,saving:i,opening:l}=e,{t:o}=(0,f.Bd)("skills"),{locale:d}=(0,eG.i)();if(!t)return(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center",children:[(0,n.jsx)(nc.A,{className:"size-6 text-muted-foreground"}),(0,n.jsx)("h3",{className:"text-sm font-medium",children:o("chooseFile")}),(0,n.jsx)("p",{className:"max-w-xs text-sm leading-6 text-muted-foreground",children:o("chooseFileDescription")})]});let c=t.file,u=c?.kind==="text"?c.readOnlyReason:null;return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-14 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:s?.description,children:[s?.name??t.target.skillPath.split("/").at(-2),(0,n.jsx)("span",{className:"mx-1.5",children:"/"}),o(null===t.target.cwd?"global":"project"),` \xb7 ${o(s?.packageSource?"package":"local")}`]}),(0,n.jsx)("p",{className:"mt-1 truncate font-mono text-sm",title:t.target.path,children:t.target.path})]}),c?.kind==="text"&&(0,n.jsxs)("span",{role:"status","aria-label":o(i?"saving":l?"switchingFile":r?"unsavedChanges":u?"readOnlyFile":"fileSaved"),className:"hidden shrink-0 items-center gap-1 text-xs text-muted-foreground sm:flex",children:[i||l?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):r?(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-status-warning"}):u?(0,n.jsx)(nu.A,{className:"size-3.5"}):(0,n.jsx)(em.A,{className:"size-3.5"}),o(i?"saving":l?"switchingFile":r?"unsaved":u?"readOnly":"saved")]}),r&&(0,n.jsx)("span",{"aria-label":o("unsavedChanges"),className:"size-2 shrink-0 rounded-full bg-status-warning sm:hidden"}),(0,n.jsx)(N.$,{variant:"ghost",size:"icon","aria-label":o("copySkillPath"),title:o("copyPath"),onClick:e.onCopy,children:(0,n.jsx)(Z.A,{className:"size-4"})}),(0,n.jsxs)(N.$,{"aria-label":o("saveSkill"),disabled:!r||!!u||a||i,onClick:e.onSave,children:[i?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(X.A,{className:"size-4"}),o("save")]})]}),u&&(0,n.jsxs)("div",{role:"note",className:"flex shrink-0 items-start gap-2 border-b bg-muted px-4 py-2 text-sm leading-5 text-muted-foreground",children:[(0,n.jsx)(nu.A,{className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsx)("p",{children:(0,eH.fD)(u,d)})]}),t.error&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:[t.error,!c&&(0,n.jsx)(N.$,{variant:"ghost",size:"sm",onClick:e.onReload,children:o("reload")})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:a&&!c?(0,n.jsxs)("div",{role:"status",className:"flex h-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),o("loadingFile")]}):c?.kind==="text"?(0,n.jsx)(nh,{path:t.target.skillPath.slice(0,t.target.skillPath.lastIndexOf("/")+1)+t.target.path,content:t.draft,size:c.size,readOnly:!!u||i||l,onChange:e.onChange,onSave:e.onSave}):c?.kind==="image"?(0,n.jsx)(nx,{file:c,path:t.target.path}):c?.kind==="unsupported"?(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(nc.A,{className:"mb-2 size-8"}),(0,n.jsx)("p",{children:c.reason}),(0,n.jsx)("p",{children:o("fileSize",{size:c.size.toLocaleString("en"===d?"en-US":"zh-CN")})})]}):null}),c?.kind==="text"&&(0,n.jsxs)("div",{className:"flex min-h-9 shrink-0 items-center justify-between gap-2 border-t px-3 py-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{className:"truncate",children:["UTF-8 \xb7 ",o(u?"readOnly":"saveShortcut")]}),(0,n.jsxs)(N.$,{variant:"ghost",size:"sm","aria-label":o("wrapLines"),"aria-pressed":e.wrapLines,onClick:e.onWrapLines,children:[(0,n.jsx)(nm.A,{className:"size-3.5"}),o("wrapLines")]})]})]})}function nb({open:e,saving:t,path:s,error:r,onDecide:a}){let{t:i}=(0,f.Bd)("skills");return(0,n.jsx)(ej.YV,{open:e,onOpenChange:e=>{e||t||a("cancel")},children:(0,n.jsxs)(ej.hA,{className:"z-[150]",showCloseButton:!t,children:[(0,n.jsxs)(ej.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(ej.YM,{children:i("saveChangesTitle")}),(0,n.jsx)(ej.uX,{children:i("saveChangesDescription",{path:s??""})})]}),r&&(0,n.jsx)("p",{role:"alert",className:"px-4 pb-4 text-sm text-destructive",children:r}),(0,n.jsxs)(ej.vu,{children:[(0,n.jsx)(N.$,{variant:"outline",disabled:t,onClick:()=>void a("cancel"),children:i("cancel")}),(0,n.jsx)(N.$,{variant:"ghost",disabled:t,onClick:()=>void a("discard"),children:i("discard")}),(0,n.jsx)(N.$,{disabled:t,onClick:()=>void a("save"),children:i(t?"savingChanges":"saveContinue")})]})]})})}var nv=s(19932),nw=s(43326),ny=s(17511);function nk(e,t){return!!(e&&e.cwd===t.cwd&&e.skillPath===t.skillPath&&e.path===t.path)}function nj({target:e,props:t,depth:s=0,skillName:a}){let{t:i}=(0,f.Bd)("skills"),l=t.directories[nl(e)],{onLoadDirectory:o}=t;return((0,r.useEffect)(()=>{l||o(e)},[l,o,e]),l?.error)?(0,n.jsxs)("div",{className:"px-3 py-2 text-xs text-destructive",children:[l.error,(0,n.jsx)(N.$,{variant:"ghost",size:"sm",onClick:()=>void t.onLoadDirectory(e),children:i("retryFolder")})]}):l?.data?(0,n.jsxs)("div",{className:"relative ml-5 border-l border-border/70 py-1 pl-3",children:[l.data.entries.map(r=>{let l=e.path?`${e.path}/${r.name}`:r.name,o={...e,path:l};if("directory"===r.type)return(0,n.jsx)(nN,{target:o,props:t,depth:s,name:r.name,skillName:a},l);let d=nk(t.selected,o),c=nk(t.pending,o);return(0,n.jsxs)(N.$,{variant:"ghost","aria-label":i("skillFile",{path:`${a}/${l}`}),"aria-pressed":d,title:l,className:(0,C.cn)("min-h-9 w-full justify-start text-left font-normal text-muted-foreground",d&&"font-medium",c&&"bg-muted text-foreground"),onClick:()=>void t.onOpenFile(o),children:["SKILL.md"===r.name?(0,n.jsx)(nv.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(nc.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r.name}),c&&(0,n.jsx)(b.A,{className:"size-3.5 shrink-0 animate-spin"})]},l)}),0===l.data.entries.length&&(0,n.jsx)("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:i("emptyFolder")}),l.data.truncated&&(0,n.jsx)("p",{className:"px-3 py-2 text-sm text-status-warning",children:i("folderTruncated")})]}):(0,n.jsx)("p",{role:"status",className:"px-4 py-2 text-xs text-muted-foreground",children:i("loadingFolder")})}function nN({target:e,props:t,depth:s,name:a,skillName:i}){let{t:l}=(0,f.Bd)("skills"),[o,d]=(0,r.useState)(!1);return(0,n.jsxs)("div",{children:[(0,n.jsxs)(N.$,{variant:"ghost","aria-expanded":o,"aria-label":l("skillFolder",{path:`${i}/${e.path}`}),className:(0,C.cn)("min-h-9 w-full justify-start font-normal text-muted-foreground",o&&"bg-muted text-foreground"),onClick:()=>d(!o),children:[o?(0,n.jsx)(eq.A,{className:"size-3.5 shrink-0"}):(0,n.jsx)(e8.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)(eR.A,{className:"size-3.5 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:a})]}),o&&(0,n.jsx)("div",{className:s>3?"-ml-3":void 0,children:(0,n.jsx)(nj,{target:e,props:t,depth:s+1,skillName:i})})]})}function nI({cwd:e,skill:t,props:s}){let{t:a}=(0,f.Bd)("skills"),i=s.selected?.cwd===e&&s.selected.skillPath===t.skillPath,l=s.pending?.cwd===e&&s.pending.skillPath===t.skillPath,[o,d]=(0,r.useState)(null),c=o??i,u=async()=>{if(c)return void d(!1);let n=t.skillPath.replaceAll("\\","/").split("/").at(-1);await s.onOpenFile({cwd:e,skillPath:t.skillPath,path:n})&&d(!0)};return(0,n.jsxs)("div",{className:"py-0.5",children:[(0,n.jsxs)(N.$,{variant:"ghost","aria-label":a("skillName",{name:t.name}),"aria-expanded":c,title:`${t.description}
155
- ${t.skillPath}`,className:(0,C.cn)("min-h-14 w-full justify-start whitespace-normal text-left",c&&"bg-accent hover:bg-accent",i&&"text-foreground"),onClick:()=>void u(),children:[c?(0,n.jsx)(eq.A,{className:"size-3.5 shrink-0 text-muted-foreground"}):(0,n.jsx)(e8.A,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",children:t.name}),t.description&&(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs font-normal text-muted-foreground",children:t.description})]}),l?(0,n.jsx)(b.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):t.packageSource?(0,n.jsx)(nw.A,{"aria-label":a("packageSkill"),className:"size-3.5 shrink-0 text-muted-foreground"}):null]}),c&&(0,n.jsx)(nj,{target:{cwd:e,skillPath:t.skillPath,path:""},props:s,skillName:t.name})]})}function nC({cwd:e,name:t,props:s}){let{t:a}=(0,f.Bd)("skills"),{locale:i}=(0,eG.i)(),l=s.selected?.cwd===e||s.pending?.cwd===e,[o,d]=(0,r.useState)(null),{onLoadScope:c}=s,u=s.scopes[ni(e)],m=s.query.trim().toLowerCase(),p=o??(null===e||s.focusedCwd===e||l),h=p||!!m;(0,r.useEffect)(()=>{h&&!u&&c(e)},[e,h,u,c]);let g=`${t} ${e??""}`.toLowerCase().includes(m),x=u?.data?.skills.filter(e=>!m||g||`${e.name} ${e.description}`.toLowerCase().includes(m))??[];if(m&&u?.data&&!x.length&&!g&&!u.error)return null;let v=null===e;return(0,n.jsxs)("section",{className:"mx-2 mt-2 min-w-0 border-b pb-2","aria-label":v?a("globalSkills"):a("projectSkills",{name:t}),children:[(0,n.jsxs)(N.$,{variant:"ghost",className:"min-h-14 w-full justify-start text-left","aria-label":a("skillsGroup",{name:v?a("global"):t}),"aria-expanded":h,onClick:()=>d(!p),children:[h?(0,n.jsx)(eq.A,{className:"size-4 shrink-0"}):(0,n.jsx)(e8.A,{className:"size-4 shrink-0"}),v?(0,n.jsx)(eO.A,{className:"size-4 shrink-0 text-primary"}):(0,n.jsx)(eR.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",children:v?a("globalSkills"):t}),e&&(0,n.jsx)("p",{title:e,className:"mt-1 truncate text-xs font-normal text-muted-foreground",children:e})]}),u?.loading?(0,n.jsx)(b.A,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground"}):u?.data?(0,n.jsx)("span",{className:"text-xs tabular-nums text-muted-foreground",children:m?x.length:u.data.skills.length}):null]}),h&&(0,n.jsxs)("div",{className:"px-1 py-1",children:[u?.error&&(0,n.jsxs)("p",{className:"px-3 py-2 text-xs text-destructive",children:[u.error,(0,n.jsx)(N.$,{variant:"ghost",size:"sm",onClick:()=>void s.onLoadScope(e),children:a("retryGroup")})]}),x.map(t=>(0,n.jsx)(nI,{cwd:e,skill:t,props:s},t.skillPath)),u?.data&&0===x.length&&!u.error&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:a(m?"noSkillMatches":"noSkills")}),!!u?.data?.diagnostics.length&&(0,n.jsxs)("details",{className:"mx-2 mb-1 mt-2 rounded-md bg-muted p-2 text-sm text-muted-foreground",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-status-warning",children:a("diagnostics",{count:u.data.diagnostics.length})}),(0,n.jsx)("div",{className:"mt-2 space-y-3",children:u.data.diagnostics.map((e,t)=>(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"break-words",children:(0,eH.fD)(e.message,i)}),(0,n.jsx)("p",{className:"mt-1 break-all text-xs",children:e.path})]},`${e.path}:${t}`))})]})]})]})}function nS(e){let{t}=(0,f.Bd)("skills");return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsx)("div",{className:"shrink-0 border-b p-3",children:(0,n.jsxs)(ny.MG,{children:[(0,n.jsx)(ny.Sq,{children:(0,n.jsx)(ep.A,{className:"size-4"})}),(0,n.jsx)(ny.iV,{"aria-label":t("searchSkills"),value:e.query,onChange:t=>e.onQuery(t.target.value),placeholder:t("searchSkillsPlaceholder")})]})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain pb-4",children:[(0,n.jsx)(nC,{cwd:null,name:t("global"),props:e}),(0,n.jsxs)("div",{className:"flex items-center gap-2 px-4 pb-1 pt-5",children:[(0,n.jsx)("span",{className:"h-px flex-1 bg-border"}),(0,n.jsx)("p",{className:"shrink-0 text-xs font-medium text-muted-foreground",children:t("workspaceCount",{count:e.projects.length})}),(0,n.jsx)("span",{className:"h-px flex-1 bg-border"})]}),e.projects.map(t=>(0,n.jsx)(nC,{cwd:t.cwd,name:t.projectName,props:e},t.cwd)),0===e.projects.length&&(0,n.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground",children:t("workspaceEmpty")})]})]})}function nM({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{t:a}=(0,f.Bd)("skills"),{clientId:i}=(0,er.gM)(),l=(0,Q.G)(),o=(0,r.useMemo)(()=>({list:(e,t)=>nt(i,s6,e,t),listFiles:(e,t)=>nt(i,s8,e,t),getFile:(e,t)=>nt(i,s7,e,t),async replaceFile(e){await nt(i,s9,e)}}),[i]),d=function(e,t){let[s,n]=(0,r.useState)({}),[a,i]=(0,r.useState)({}),l=(0,r.useRef)(new Map),o=(0,r.useRef)(!0);(0,r.useEffect)(()=>{o.current=!0;let e=l.current;return()=>{for(let t of(o.current=!1,e.values()))t.abort();e.clear()}},[]);let d=(0,r.useCallback)(async t=>{let s=ni(t),r=`scope:${s}`;l.current.get(r)?.abort();let a=new AbortController;l.current.set(r,a),n(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let r=await e.list({cwd:t},a.signal);!a.signal.aborted&&o.current&&n(e=>({...e,[s]:{data:r,loading:!1,error:null}}))}catch(e){!a.signal.aborted&&o.current&&n(t=>({...t,[s]:{data:t[s]?.data??null,loading:!1,error:e instanceof Error?e.message:na("skillsReadFailed")}}))}finally{l.current.get(r)===a&&l.current.delete(r)}},[e]),c=(0,r.useCallback)(async t=>{let s=nl(t),n=`directory:${s}`;l.current.get(n)?.abort();let r=new AbortController;l.current.set(n,r),i(e=>({...e,[s]:{data:e[s]?.data??null,loading:!0,error:null}}));try{let n=await e.listFiles(t,r.signal);!r.signal.aborted&&o.current&&i(e=>({...e,[s]:{data:n,loading:!1,error:null}}))}catch(e){!r.signal.aborted&&o.current&&i(t=>({...t,[s]:{data:null,loading:!1,error:e instanceof Error?e.message:na("directoryReadFailed")}}))}finally{l.current.get(n)===r&&l.current.delete(n)}},[e]),u=JSON.stringify(t.map(e=>e.cwd));return(0,r.useEffect)(()=>{let e=new Set([ni(null),...JSON.parse(u).map(ni)]);for(let[t,s]of(n(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(t)))),i(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.has(ni(JSON.parse(t)[0]))))),l.current)){let n=t.startsWith("scope:")?t.slice(6):ni(JSON.parse(t.slice(10))[0]);e.has(n)||(s.abort(),l.current.delete(t))}},[u]),{scopes:s,directories:a,loadScope:d,loadDirectory:c}}(o,e),{loadScope:c}=d,u=function(e,t){let{wrapLines:s}=(0,sV.TX)(),[n,a]=(0,r.useState)(null),i=(0,r.useRef)(null),l=(0,r.useRef)(!0),[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(!1),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),x=(0,r.useRef)(null),[f,b]=(0,r.useState)(!1),v=(0,r.useRef)(null),w=(0,r.useCallback)(e=>{l.current&&(i.current=e,a(e))},[]);(0,r.useEffect)(()=>(l.current=!0,()=>{l.current=!1,x.current?.abort(),v.current?.resolve(!1),v.current=null}),[]);let y=(0,r.useCallback)(()=>{if(h.current)return h.current;let s=i.current;if(!s||s.file?.kind!=="text"||s.file.readOnlyReason)return Promise.resolve(!1);if(!nd(s))return Promise.resolve(!0);p(!0);let n=(async()=>{try{await e.replaceFile({...s.target,content:s.draft});let n=i.current;return n?.file?.kind==="text"&&n.target===s.target&&w({...n,file:{...n.file,content:s.draft},error:null}),l.current&&t(s.target.cwd),!0}catch(t){let e=i.current;return e?.target===s.target&&w({...e,error:t instanceof Error?t.message:na("saveFailed")}),!1}finally{h.current=null,l.current&&p(!1)}})();return h.current=n,n},[w,e,t]),k=(0,r.useCallback)(async()=>{let e;if(h.current&&await h.current,!l.current)return!1;if(!nd(i.current))return!0;if(v.current)return v.current.promise;let t=new Promise(t=>{e=t});return v.current={promise:t,resolve:e},b(!0),t},[]),j=(0,r.useCallback)(async e=>{if(!v.current||h.current||"save"===e&&(!await y()||nd(i.current)))return;if("discard"===e){let e=i.current;e?.file?.kind==="text"&&w({...e,draft:no(e.file.content),error:null})}let t=v.current;v.current=null,b(!1),t?.resolve("cancel"!==e)},[w,y]),N=(0,r.useCallback)(async t=>{if(g.current)return!1;g.current=!0;try{if(!await k()||!l.current)return!1;x.current?.abort();let s=new AbortController;x.current=s,u(t),d(!0);try{let n=await e.getFile(t,s.signal);if(s.signal.aborted||!l.current)return!1;return w({target:t,file:n,draft:"text"===n.kind?no(n.content):"",error:null}),!0}catch(e){if(!s.signal.aborted){let s=i.current,n=e instanceof Error?e.message:na("fileReadFailed");w(s?{...s,error:n}:{target:t,file:null,draft:"",error:n})}return!1}finally{l.current&&(u(null),d(!1))}}finally{g.current=!1}},[w,k,e]),I=(0,r.useCallback)(e=>{let t=i.current;t?.file?.kind!=="text"||t.file.readOnlyReason||t.draft===e||w({...t,draft:e})},[w]),C=nd(n);return(0,r.useEffect)(()=>{if(!C)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[C]),{document:n,dirty:C,loading:o,openingTarget:c,saving:m,confirmOpen:f,wrapLines:s,setWrapLines:ns,change:I,open:N,save:y,beforeLeave:k,decide:j}}(o,(0,r.useCallback)(e=>{c(e)},[c])),{document:m,open:p}=u,[h,g]=(0,r.useState)(""),[x,v]=(0,r.useState)(!1),[w,y]=(0,r.useState)(!0),k=(0,r.useRef)(!1),j=(0,r.useRef)(t);(0,r.useEffect)(()=>(s(u.beforeLeave),()=>s(null)),[u.beforeLeave,s]),(0,r.useEffect)(()=>{if(k.current||m)return;let e=d.scopes[ni(j.current)];if(!e||e.loading)return;let t=d.scopes[ni(null)],s=e.data?.skills[0];if(!s&&(!t||t.loading))return;let n=s??t?.data?.skills[0];k.current=!0,n&&p({cwd:s?j.current:null,skillPath:n.skillPath,path:n.skillPath.split("/").at(-1)})},[d.scopes,m,p]);let I=(0,r.useCallback)(async e=>{let t=await p(e);return t&&v(!1),t},[p]),S=async()=>{if(u.document)try{await nn(u.document.target),l.success(a("pathCopied"))}catch{l.error(a("copyFailed"))}},M=u.document?.target??null,z=M?d.scopes[ni(M.cwd)]?.data?.skills.find(e=>e.skillPath===M.skillPath)??null:null,E=Object.values(d.scopes).some(e=>e.loading)||Object.values(d.directories).some(e=>e.loading),A={projects:e,focusedCwd:t,query:h,onQuery:g,scopes:d.scopes,directories:d.directories,selected:M,pending:u.openingTarget,onLoadScope:d.loadScope,onLoadDirectory:d.loadDirectory,onOpenFile:I};return(0,n.jsxs)("section",{"aria-label":a("skillsManagement"),className:"flex h-full min-h-0 flex-col bg-background",children:[(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b px-4 py-2",children:[(0,n.jsx)(N.$,{variant:"ghost",size:"icon",className:"lg:hidden","aria-label":a("openSkillsFolder"),onClick:()=>v(!0),children:(0,n.jsx)(sL.A,{className:"size-4"})}),(0,n.jsx)(N.$,{variant:"ghost",size:"icon",className:"hidden lg:inline-flex","aria-label":a(w?"collapseSkillsFolder":"expandSkillsFolder"),onClick:()=>y(!w),children:w?(0,n.jsx)(sW.A,{className:"size-4"}):(0,n.jsx)(sY.A,{className:"size-4"})}),(0,n.jsx)("h2",{className:"text-xl font-semibold",children:"Skills"}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsxs)(N.$,{variant:"ghost",size:"sm",disabled:E,"aria-label":a("refreshSkillsFolder"),onClick:()=>{for(let e of Object.keys(d.scopes))d.loadScope(JSON.parse(e));for(let e of Object.keys(d.directories)){let[t,s,n]=JSON.parse(e);d.loadDirectory({cwd:t,skillPath:s,path:n})}},children:[E?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(et.A,{className:"size-3.5"}),a("refreshFolder")]})]}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,n.jsx)("aside",{"aria-label":a("skillsProjectFolder"),className:(0,C.cn)("hidden w-64 shrink-0 border-r bg-sidebar xl:w-72",w&&"lg:block"),children:(0,n.jsx)(nS,{...A})}),(0,n.jsx)("main",{className:"min-h-0 min-w-0 flex-1",children:(0,n.jsx)(nf,{document:u.document,skill:z,dirty:u.dirty,loading:u.loading,saving:u.saving,opening:!!u.openingTarget,wrapLines:u.wrapLines,onWrapLines:()=>u.setWrapLines(!u.wrapLines),onChange:u.change,onSave:()=>void u.save(),onReload:()=>{M&&I(M)},onCopy:()=>void S()})})]}),(0,n.jsx)(ej.YV,{open:x,onOpenChange:v,children:(0,n.jsxs)(ej.hA,{className:"left-0 top-0 z-[130] h-dvh max-h-dvh w-[min(360px,calc(100dvw-2rem))] max-w-none translate-x-0 translate-y-0 rounded-l-none",finalFocus:!1,children:[(0,n.jsx)(ej.Hl,{className:"shrink-0 border-b px-4 py-3 pr-12",children:(0,n.jsx)(ej.YM,{children:a("skillsFolderTitle")})}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(nS,{...A})})]})}),(0,n.jsx)(nb,{open:u.confirmOpen,saving:u.saving,path:M?.path??null,error:u.document?.error??null,onDecide:u.decide})]})}var nz=s(75851),nE=s(17247),nA=s(4090),n$=s(19562);function nR(){let{t:e}=(0,f.Bd)("common"),[t,s]=(0,r.useState)(null),a=(0,r.useRef)(null),i=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{a.current?.(!1),a.current=null},[]);let l=e=>{let t=a.current;a.current=null,s(null),t?.(e)};return{confirm:e=>(a.current?.(!1),s(e),new Promise(e=>{a.current=e})),dialog:t?(0,n.jsx)(ej.YV,{open:!0,onOpenChange:e=>{e||l(!1)},children:(0,n.jsxs)(ej.hA,{initialFocus:i,className:"z-[130] max-w-[27.5rem]",children:[(0,n.jsxs)(ej.Hl,{className:"p-4 pr-12",children:[(0,n.jsx)(ej.YM,{children:t.title}),(0,n.jsx)(ej.uX,{className:"break-words",children:t.description})]}),t.content?(0,n.jsx)(ej._Y,{className:"grid grid-rows-[minmax(0,1fr)]",children:t.content}):null,(0,n.jsxs)(ej.vu,{children:[(0,n.jsx)(N.$,{ref:i,variant:"outline",onClick:()=>l(!1),children:e("cancel")}),(0,n.jsx)(N.$,{variant:t.confirmVariant??"destructive",onClick:()=>l(!0),children:t.confirmLabel??e("delete")})]})]})}):null}}var nT=s(33941);async function nP(e,t,s,n,r){let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r});401===a.status&&window.location.replace("/login");let i=await a.json();if(!a.ok||0!==i.code||null===i.data)throw Error(0===i.code?(0,ed.B)({msg:"登录保护设置处理失败",i18n:{key:"auth:settingsFailed"}}):(0,ed.B)(i));return n.parse(i.data)}async function nD(e){await nP(e,"/api/auth/logout",{},nT.Xm),window.location.replace("/login")}async function nO(e,t){let s=nT.uZ.safeParse(t);if(!s.success)throw Error((0,ed.B)({msg:"密码不符合要求,请按输入框下方的规则调整。",i18n:{key:"auth:settingsInvalid"}}));await nP(e,"/api/auth-settings/replace",s.data,nT.Kc),window.location.replace(null===t.password?"/":"/login")}function nL(){let{t:e}=(0,f.Bd)("auth"),t=function(){let{t:e}=(0,f.Bd)("auth"),{clientId:t}=(0,er.gM)(),{confirm:s,dialog:n}=nR(),[a,i]=(0,r.useState)(null),[l,o]=(0,r.useState)(!0),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),[g,x]=(0,r.useState)(0),[b,v]=(0,r.useState)(""),w=(0,r.useRef)(!1);(0,r.useEffect)(()=>{var s;let n=new AbortController;return(s=n.signal,nP(t,"/api/auth-settings/get",{},nT.G6,s)).then(e=>{n.signal.aborted||(i(e),o(!1))}).catch(t=>{n.signal.aborted||(h(t instanceof Error?t.message:e("settingsFailed")),o(!1))}),()=>n.abort()},[t,g,e]);let y=async()=>{if(!w.current&&a){w.current=!0,c(!0),h(null);try{await nO(t,{password:b})}catch(t){w.current=!1,c(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},k=async()=>{if(!w.current&&a){if(w.current=!0,!await s({title:e("disableTitle"),description:e("disableDescription"),confirmLabel:e("disable")})){w.current=!1;return}c(!0),h(null);try{await nO(t,{password:null})}catch(t){w.current=!1,c(!1),h(t instanceof Error?t.message:e("settingsFailed"))}}},j=async()=>{if(!w.current&&a?.enabled){w.current=!0,m(!0),h(null);try{await nD(t)}catch(t){w.current=!1,m(!1),h(t instanceof Error?t.message:e("logoutFailed"))}}};return{settings:a,loading:l,saving:d,signingOut:u,error:p,password:b,setPassword:v,save:y,generatePassword:()=>{if(!w.current)try{v(function(){for(;;){let e=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@"[e%64]).join("");if(/[A-Z]/.test(e)&&/[a-z]/.test(e)&&/[0-9]/.test(e)&&/[!@]/.test(e))return e}}()),h(null)}catch{h(e("generatePasswordFailed"))}},disable:k,logout:j,dialog:n,retry:()=>{o(!0),h(null),x(e=>e+1)}}}(),s=t.settings?.enabled??!1,a=t.saving||t.signingOut,i=s?es.A:nz.A;return(0,n.jsxs)("section",{"aria-labelledby":"auth-settings-title",className:"@container min-w-0 space-y-6",children:[(0,n.jsx)("h2",{id:"auth-settings-title",className:"text-xl font-semibold",children:e("settings:loginProtection")}),t.loading?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",role:"status",children:e("common:loading")}):t.settings?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 rounded-xl bg-muted p-4",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-3",children:[(0,n.jsx)(i,{className:"size-5 shrink-0","aria-hidden":"true"}),(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:e("protection")}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e(s?"enabled":"disabled")})]})]}),s?(0,n.jsxs)(N.$,{type:"button",variant:"outline",className:"border-destructive/50 text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:a,"aria-busy":t.signingOut,onClick:()=>void t.logout(),children:[t.signingOut?(0,n.jsx)(b.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):(0,n.jsx)(nE.A,{"aria-hidden":"true"}),e(t.signingOut?"signingOut":"logout")]}):null]}),(0,n.jsxs)("form",{className:"grid gap-4 @min-[36rem]:grid-cols-[10rem_minmax(0,1fr)] @min-[36rem]:gap-6","aria-busy":a,onSubmit:e=>{e.preventDefault(),t.save()},children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:e(s?"changePassword":"setPassword")}),s?null:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("publicAccess")})]}),(0,n.jsxs)("div",{className:"min-w-0 max-w-[40rem] space-y-4",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("label",{className:"block text-sm font-medium",htmlFor:"auth-password",children:e(s?"newPassword":"password")}),(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:a,title:e("generatePasswordHint"),onClick:t.generatePassword,children:[(0,n.jsx)(nA.A,{"aria-hidden":"true"}),e("generatePassword")]})]}),(0,n.jsx)(n$.k,{id:"auth-password",name:"password",className:"[&::-ms-reveal]:hidden",autoComplete:"new-password",minLength:12,maxLength:64,required:!0,disabled:a,value:t.password,"aria-describedby":`auth-password-hint${t.error?" auth-settings-error":""}`,onChange:e=>t.setPassword(e.target.value)}),(0,n.jsx)("p",{id:"auth-password-hint",className:"text-sm text-muted-foreground",children:e("passwordHint")})]}),t.error?(0,n.jsx)("p",{id:"auth-settings-error",className:"text-sm text-destructive",role:"alert",children:t.error}):null,(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("saveEffect")}),(0,n.jsxs)(N.$,{type:"submit",disabled:a,children:[t.saving?(0,n.jsx)(b.A,{className:"motion-safe:animate-spin","aria-hidden":"true"}):null,e(t.saving?"saving":s?"saveAndSignIn":"enable")]})]})]}),s?(0,n.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4 border-t pt-4",children:[(0,n.jsxs)("details",{className:"group min-w-0 flex-1 text-sm",children:[(0,n.jsxs)("summary",{className:"flex min-h-8 w-fit cursor-pointer items-center gap-1 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring",children:[(0,n.jsx)(e8.A,{className:"size-4 shrink-0 transition-transform group-open:rotate-90","aria-hidden":"true"}),e("recovery")]}),(0,n.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,n.jsx)("p",{className:"text-muted-foreground",children:e("recoveryDescription")}),(0,n.jsx)("code",{className:"block break-all text-xs",children:t.settings.configPath})]})]}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",className:"text-muted-foreground",disabled:a,onClick:()=>void t.disable(),children:e("disable")})]}):null]}):(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:t.error}),(0,n.jsx)(N.$,{variant:"outline",onClick:t.retry,children:e("common:retry")})]}),t.dialog]})}var nF=s(60471),n_=s(62851);let nB=Object.freeze({apply:(0,i.Vc)({path:"app-runtime/apply",inputSchema:n_.$C,outputSchema:n_.Pq}),update:(0,i._G)({path:"app-runtime/update",bodySchema:n_.YT})});var nq=s(48708);async function nW(e,t,s,n){let r=(0,nq.fx)();if(!r)return"cancelled";let a=e!==r.locale;if(a&&!window.confirm(t))return"cancelled";if(a&&n&&!await n())return"blocked";try{await s.request(nB.apply,{key:"settings",update:{region:{locale:e}}})}catch{return"save-failed"}return a&&window.location.reload(),"changed"}async function nY(e,t){try{return await t.request(nB.apply,{key:"settings",update:{region:{timeZone:e}}}),!0}catch{return!1}}function nU({canLeave:e}){let{t}=(0,f.Bd)("settings"),s=(0,eG.i)(),{appSocket:a}=(0,er.gM)(),[i,l]=(0,r.useState)(null),[o,d]=(0,r.useState)(()=>new Date);(0,r.useEffect)(()=>{let e=window.setInterval(()=>d(new Date),6e4);return()=>window.clearInterval(e)},[]);let c=(0,r.useMemo)(()=>[...["UTC",...Intl.supportedValuesOf("timeZone").filter(e=>"UTC"!==e)].map(e=>({value:e,label:e.replaceAll("_"," ")}))],[]),u=async s=>{l(null);let n=await nW(s,t("common:reloadConfirm"),a,e);"save-failed"===n&&l(t("common:localeError")),"blocked"===n&&l(t("common:reloadBlocked"))},m=async e=>{l(await nY(e,a)?null:t("common:timeZoneError"))};return(0,n.jsxs)("section",{className:"@container min-w-0 space-y-6","aria-labelledby":"region-settings-title",children:[(0,n.jsx)("h2",{id:"region-settings-title",className:"text-xl font-semibold",children:t("region")}),(0,n.jsxs)("div",{className:"grid max-w-[40rem] gap-6 @min-[32rem]:grid-cols-2",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("label",{className:"block text-sm font-medium",htmlFor:"region-language",children:t("language")}),(0,n.jsxs)(ea.l6,{value:s.localePreference,onValueChange:e=>{("zh-CN"===e||"en"===e)&&u(e)},children:[(0,n.jsx)(ea.bq,{id:"region-language",className:"w-full",children:(0,n.jsx)(ea.yv,{children:"zh-CN"===s.localePreference?t("common:chinese"):"English"})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(ea.eb,{value:"zh-CN",children:t("common:chinese")}),(0,n.jsx)(ea.eb,{value:"en",children:"English"})]})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("currentLanguage",{locale:s.locale})}),s.pendingLocale&&(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("common:languagePending")}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void u(s.localePreference),children:t("reloadLanguage")})]})]}),(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("span",{className:"block text-sm font-medium",children:t("timeZone")}),(0,n.jsx)(nF.b,{value:s.timeZonePreference,options:c,onChange:e=>void m(e),ariaLabel:t("timeZone"),searchPlaceholder:t("searchTimeZones"),emptyText:t("common:unavailable"),className:"w-full"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("currentTimeZone",{timeZone:s.timeZone})})]})]}),(0,n.jsxs)("div",{className:"space-y-1 rounded-xl bg-muted p-4",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:t("timeExample")}),(0,n.jsx)("p",{className:"text-sm font-medium tabular-nums",children:new Intl.DateTimeFormat("en"===s.locale?"en-US":"zh-CN",{timeZone:s.timeZone,year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(o)})]}),i&&(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:i})]})}var nV=s(90772),nK=s(90164),nH=s(52871),nG=s(96646);function nJ({label:e,value:t,options:s,onChange:r,layout:a="list",disabled:i=!1}){let l=s.some(e=>e.value===t);return(0,n.jsx)("div",{role:"radiogroup","aria-label":e,onKeyDown:e=>{if(i||e.nativeEvent.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=["ArrowRight","ArrowDown"].includes(e.key)?1:["ArrowLeft","ArrowUp"].includes(e.key)?-1:0;if(!n&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault();let a=Math.max(0,s.findIndex(e=>e.value===t)),l="Home"===e.key?0:"End"===e.key?s.length-1:(a+n+s.length)%s.length,o=s[l];o&&(r(o.value),e.currentTarget.querySelectorAll('[role="radio"]')[l]?.focus())},className:(0,C.cn)("segmented"===a?"inline-flex max-w-full flex-wrap gap-0.5 rounded-lg bg-muted p-0.5":"grid gap-2"),children:s.map((e,s)=>{let o=e.value===t,d=e.icon;return(0,n.jsxs)("button",{type:"button",role:"radio","aria-checked":o,tabIndex:o||!l&&0===s?0:-1,disabled:i,"data-testid":e.testId,onClick:()=>r(e.value),className:(0,C.cn)("flex min-w-0 cursor-pointer items-center gap-2 text-left text-sm leading-5 outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset","segmented"===a?"min-h-7 rounded-md px-2 py-0.5":"min-h-9 rounded-lg border border-transparent px-3 py-2",o?"segmented"===a?"bg-card text-card-foreground shadow-sm":"border-border bg-accent text-accent-foreground":"text-muted-foreground hover:bg-foreground/8 hover:text-foreground"),children:[d?(0,n.jsx)(d,{className:"size-4 shrink-0"}):null,(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block font-medium",children:e.label}),e.description?(0,n.jsx)("span",{className:"mt-1 block text-sm font-normal text-muted-foreground",children:e.description}):null]}),"list"===a?(0,n.jsx)(em.A,{"aria-hidden":"true",className:(0,C.cn)("size-4 shrink-0",!o&&"invisible")}):null]},e.value)})})}var nQ=s(74052),nX=s(38903),nZ=s(90740),n0=s(67796),n1=s(8001),n2=s(46376),n5=s.n(n2);let n3={code:{copy:!0,download:!1}};function n4({href:e,children:t,...s}){return delete s.node,(0,n.jsx)("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",children:t})}function n6({src:e,alt:t,className:s,onError:a,...i}){let{t:l}=(0,f.Bd)("conversation"),[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(!1),m=t||l("image"),p=(0,r.useMemo)(()=>"string"==typeof e&&e?[{src:e,alt:m}]:[],[m,e]);if(delete i.node,0===p.length)return null;if(c)return(0,n.jsx)("span",{className:n5().imageFallback,children:l("imageUnavailable")});let h=p[0].src;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:n5().imageTrigger,"aria-label":l("previewImage",{name:m}),onClick:()=>d(!0),children:[(0,n.jsx)("img",{...i,src:h,alt:m,"data-streamdown":"image",className:(0,C.cn)(n5().image,s),onError:e=>{u(!0),a?.(e)}}),(0,n.jsx)("span",{className:n5().imageAction,"aria-hidden":"true",children:(0,n.jsx)(_.A,{className:"size-4"})})]}),o?(0,n.jsx)(ng.k,{mode:"modal",open:!0,slides:p,ariaLabel:l("imagePreview"),onClose:()=>d(!1)}):null]})}function n8({className:e,isAnimating:t,components:s,...r}){let a=(0,Q.G)(),{t:i}=(0,f.Bd)("conversation"),{locale:l}=(0,eG.i)();return(0,n.jsx)("div",{className:"contents",onClickCapture:e=>{if("u">typeof navigator&&"function"==typeof navigator.clipboard?.writeText)return;let t=function(e){if(!(e instanceof Element))return null;let t=e.closest('[data-streamdown="code-block-copy-button"]');return t?t.closest('[data-streamdown="code-block"]')?.querySelector('[data-streamdown="code-block-body"]')?.textContent??null:null}(e.target);null!==t&&(e.preventDefault(),e.stopPropagation(),(0,e7.x)(t).then(e=>{e||a.error(i("codeCopyFailed"))}))},children:(0,n.jsx)(t1,{className:(0,C.cn)("space-y-0",n5().markdown,n1.om,e),controls:n3,isAnimating:t,lineNumbers:!1,allowedTags:n1.IV,remarkPlugins:n1.XC,components:{...n1.e6,...s,a:n4,img:n6},...r,translations:"zh-CN"===l?n0.X:void 0})})}let n7=[{value:"system",label:"common:system",icon:nV.A},{value:"light",label:"themeLight",icon:nK.A},{value:"dark",label:"themeDark",icon:nH.A}],n9=[{value:"compact",label:"sizeCompact"},{value:"standard",label:"sizeStandard"},{value:"large",label:"sizeLarge"}];function re(){let{t:e}=(0,f.Bd)("settings"),t=(0,r.useSyncExternalStore)(nQ.Cy,nQ.Is,()=>nG.Pl),s=(0,r.useSyncExternalStore)(nZ.wm,nZ.Ev,()=>nX.Y8);return(0,n.jsxs)("section",{"aria-labelledby":"settings-appearance-title",className:"@container grid gap-6",children:[(0,n.jsx)("h2",{id:"settings-appearance-title",className:"text-xl font-semibold",children:e("appearance")}),(0,n.jsxs)("div",{className:"grid min-w-0 gap-6 @min-[40rem]:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[(0,n.jsxs)("div",{className:"min-w-0 space-y-4",children:[(0,n.jsxs)("div",{className:"space-y-2 border-b pb-4",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("theme")}),(0,n.jsx)(nJ,{label:e("theme"),layout:"segmented",value:t,options:n7.map(t=>({...t,label:e(t.label)})),onChange:nQ.VS})]}),(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displaySize")}),(0,n.jsx)(nJ,{label:e("displaySize"),layout:"segmented",value:s,options:n9.map(t=>({...t,label:e(t.label)})),onChange:nZ.$y})]})]}),(0,n.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,n.jsx)("h3",{className:"text-sm font-medium",children:e("displayPreview")}),(0,n.jsx)("div",{"aria-label":e("displayPreview"),className:"min-w-0 rounded-xl bg-muted p-4",children:(0,n.jsx)(n8,{mode:"static",isAnimating:!1,children:e("displayPreviewContent")})})]})]})]})}var rt=s(50163),rs=s(93780),rn=s(88707),rr=s(31848),ra=s(71057),ri=s(20476);let rl="pi-super:new-work-session-behavior",ro="activate",rd=new Set,rc=ro,ru=!1;function rm(){if(!ru){ru=!0;try{var e;e=window.localStorage.getItem(rl),rc="none"===e||"activate"===e||"pin"===e?e:ro}catch{rc=ro}}}function rp(){return rm(),rc}function rh(e){if(rm(),rc!==e){rc=e;try{window.localStorage.setItem(rl,e)}catch{}for(let e of[...rd])e()}}function rg(e){return rd.add(e),()=>rd.delete(e)}let rx=[{value:"none",label:"behaviorNone",description:"behaviorNoneDescription",icon:rt.A,testId:"new-work-session-behavior-none"},{value:"activate",label:"behaviorActivate",description:"behaviorActivateDescription",icon:rs.A,testId:"new-work-session-behavior-activate"},{value:"pin",label:"behaviorPin",description:"behaviorPinDescription",icon:rn.A,testId:"new-work-session-behavior-pin"}],rf=[{value:"compressed",label:"imageCompressed",description:"imageCompressedDescription",icon:rr.A,testId:"image-preview-mode-compressed"},{value:"original",label:"imageOriginal",description:"imageOriginalDescription",icon:ra.A,testId:"image-preview-mode-original"}];function rb(){let{t:e}=(0,f.Bd)("settings"),t=(0,r.useSyncExternalStore)(rg,rp,rp),s=(0,r.useSyncExternalStore)(ri.ku,ri.Wq,ri.Wq);return(0,n.jsxs)("section",{"aria-labelledby":"settings-habits-title",className:"@container grid min-w-0 gap-6",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"settings-habits-title",className:"text-xl font-semibold",children:e("habits")}),(0,n.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:e("browserOnly")})]}),(0,n.jsxs)("div",{className:"grid min-w-0 gap-6 lg:@min-[40rem]:grid-cols-2",children:[(0,n.jsxs)("section",{className:"hidden min-w-0 lg:block","aria-labelledby":"new-session-behavior-title",children:[(0,n.jsx)("h3",{id:"new-session-behavior-title",className:"mb-3 text-sm font-semibold",children:e("newSessionBehavior")}),(0,n.jsx)(nJ,{label:e("newSessionBehavior"),value:t,options:rx.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:rh}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("desktopOnlyBehavior")})]}),(0,n.jsxs)("section",{className:"min-w-0 lg:border-t lg:pt-4 lg:@min-[40rem]:border-t-0 lg:@min-[40rem]:border-l lg:@min-[40rem]:pt-0 lg:@min-[40rem]:pl-6","aria-labelledby":"image-preview-mode-title",children:[(0,n.jsx)("h3",{id:"image-preview-mode-title",className:"mb-3 text-sm font-semibold",children:e("imagePreviewMode")}),(0,n.jsx)(nJ,{label:e("imagePreviewMode"),value:s,options:rf.map(t=>({...t,label:e(t.label),description:e(t.description)})),onChange:ri.lU}),(0,n.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:e("imagePreviewApply")})]})]})]})}var rv=s(17339);let rw={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function ry({projectDefaults:e}){let{t}=(0,f.Bd)("settings");return(0,n.jsx)("ul",{className:"space-y-3 px-4 pb-4",children:e.map(({cwd:e,from:s,to:r})=>(0,n.jsxs)("li",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"break-all font-medium",children:e}),(0,n.jsxs)("p",{className:"break-all text-muted-foreground",children:[s.provider,"/",s.modelId," \xb7 ",t(rw[s.thinkingLevel]),(0,n.jsx)("span",{className:"mx-1.5",children:"→"}),(0,n.jsxs)("span",{className:"text-foreground",children:[r.provider,"/",r.modelId," \xb7 ",t(rw[r.thinkingLevel])]})]})]},e))})}var rk=s(26357),rj=s(70698);let rN=a.Yj().trim().min(1).max(128),rI=a.Yj().trim().min(1).max(256),rC=a.Yj().trim().min(1).max(256),rS=a.Yj().trim().min(1).nullable(),rM=a.g1(a.Yj().trim().min(1),a.Yj()),rz=a.Yj().trim().min(1).max(128),rE=a.g1(a.Yj(),a.Pq()),rA=a.Ik({level:rk.$,providerValue:a.Yj().trim().min(1).nullable()}).strict(),r$=a.Ik({input:a.ai().nonnegative().finite(),output:a.ai().nonnegative().finite(),cacheRead:a.ai().nonnegative().finite(),cacheWrite:a.ai().nonnegative().finite()}).strict(),rR=a.Ik({supportsDeveloperRole:a.zM().nullable(),thinkingFormat:a.Yj().trim().min(1).max(128).nullable(),requiresReasoningContentOnAssistantMessages:a.zM().nullable()}).strict(),rT=a.Ik({modelId:rI,name:rC,api:rz.nullable(),baseUrl:rS,reasoning:a.zM(),thinkingLevels:a.YO(rA).min(1).max(7),input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),cost:r$.nullable(),headers:rM,compat:rR.nullable()}).strict().superRefine((e,t)=>{let s=new Set;for(let n of e.thinkingLevels)s.has(n.level)&&t.addIssue({code:"custom",message:`思考等级 ${n.level} 重复`}),s.add(n.level),("xhigh"===n.level||"max"===n.level)&&null===n.providerValue&&t.addIssue({code:"custom",message:`${n.level} 必须配置 Provider 映射`});e.reasoning||1===e.thinkingLevels.length&&s.has("off")||t.addIssue({code:"custom",message:"非推理模型只允许 off 思考等级"})}),rP=a.Ik({provider:rN,name:rS,baseUrl:rS,api:rz.nullable(),apiKey:a.Yj().nullable(),authHeader:a.zM().nullable(),headers:rM,models:a.YO(rT)}).strict().superRefine((e,t)=>{let s=new Set;for(let n of e.models)s.has(n.modelId)&&t.addIssue({code:"custom",message:`模型 ${n.modelId} 重复`}),s.add(n.modelId)}),rD=a.Ik({provider:rN,modelId:rI,thinkingLevel:rk.$,color:a.Yj().regex(/^#[0-9a-fA-F]{6}$/).nullable()}).strict(),rO=a.Ik({provider:rN,modelId:rI,name:rC,input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),thinkingLevels:a.YO(rk.$).min(1).max(7)}).strict(),rL=a.Ik({provider:rN,modelId:rI,thinkingLevel:rk.$}).strict(),rF=a.Ik({contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),cost:r$.partial().optional()}).strict(),r_=a.Ik({provider:rN,modelId:rI,overrides:rF}).strict(),rB=a.Ik({provider:rN,name:rC,loggedIn:a.zM(),subscription:a.zM(),models:a.YO(rT)}).strict();a.Ik({}).strict();let rq=a.Ik({providers:a.YO(rP),presets:a.YO(rD),models:a.YO(rO),nativeConfig:rE,accountModels:a.YO(r_),accounts:a.YO(rB)}).strict(),rW=a.Ik({provider:rN,modelId:rI}).strict(),rY=a.Ik({from:rW,to:rW}).strict(),rU=a.Ik({providers:a.YO(rP).optional(),presets:a.YO(rD).optional(),accountModels:a.YO(r_).optional(),modelReplacements:a.YO(rY).optional()}).strict().refine(e=>void 0!==e.providers||void 0!==e.presets||void 0!==e.accountModels,{message:"请提交需要保存的模型配置"}),rV=a.KC([rU,a.Ik({nativeConfig:rE}).strict()]),rK=a.Ik({}).strict(),rH=a.Ik({projectDefaults:a.YO(a.Ik({cwd:sK.m4,from:rL,to:rL}).strict())}).strict(),rG=a.Ik({query:a.Yj().trim().max(256),refresh:a.zM(),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive().max(100)}).strict()}).strict(),rJ=a.Ik({reasoning:a.zM(),thinkingLevels:a.YO(rA).min(1).max(7),input:a.YO(a.k5(["text","image"])).min(1).max(2),contextWindow:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),maxTokens:a.ai().int().positive().max(Number.MAX_SAFE_INTEGER),cost:r$.nullable()}).strict(),rQ=a.Ik({provider:rN,providerName:rC,modelId:rI,official:a.zM(),defaults:rJ}).strict(),rX=a.Ik({referenceId:a.Yj().trim().min(1).max(512),name:rC,match:a.k5(["exact","similar"]).nullable(),sources:a.YO(rQ).min(1)}).strict(),rZ=a.Ik({updatedAt:rj.k,refreshResult:a.k5(["not-requested","updated","unchanged","partial","cached"]),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive(),total:a.ai().int().nonnegative()}).strict(),models:a.YO(rX)}).strict();a.Ik({cwd:sK.m4}).strict();let r0=a.Ik({cwd:sK.m4,default:rL.nullable(),models:a.YO(rO)}).strict(),r1=a.Ik({cwd:sK.m4,default:rL.nullable()}).strict(),r2=a.Ik({}).strict(),r5=a.Ik({cwd:sK.m4,sessionCount:a.ai().int().nonnegative(),updatedAt:rj.k}).strict();a.Ik({forceRefresh:a.zM().default(!1)}).strict();let r3=a.Ik({directories:a.YO(r5)}).strict();a.Ik({cwd:sK.m4,ignored:a.zM()}).strict(),a.Ik({}).strict();let r4=a.Ik({cwd:sK.m4,name:a.Yj().trim().min(1)}).strict();a.Ik({cwd:sK.m4.nullable()}).strict();let r6=a.Ik({cwd:sK.m4.nullable(),parentCwd:sK.m4.nullable(),directories:a.YO(r4)}).strict(),r8=a.k5(["title","user","assistant","sessionId"]),r7=a.Ik({scope:r8,count:a.ai().int().positive(),entryId:sK.Rv.nullable(),timestampMs:rj.k.nullable(),preview:a.Yj().min(1).max(160)}).strict(),r9=a.Ik({sessionId:sK.$E,cwd:sK.m4,name:a.Yj().nullable(),createdAt:rj.k,updatedAt:rj.k,messageCount:a.ai().int().nonnegative(),userMessageCount:a.ai().int().nonnegative(),firstMessage:a.Yj().max(160),matches:a.YO(r7).min(1).max(4).nullable()}).strict();a.Ik({cwd:sK.m4,query:a.Yj().trim().max(120).default(""),forceRefresh:a.zM().default(!1),searchIn:a.YO(r8).min(1).max(4).default(["title","user"])}).strict(),a.Ik({cwd:sK.m4,sessions:a.YO(r9)}).strict(),a.Ik({cwd:sK.m4,sessionId:sK.$E,query:a.Yj().trim().max(120).default(""),page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive().max(50)}).strict()}).strict();let ae=a.Ik({entryId:sK.Rv,timestampMs:rj.k,text:a.Yj()}).strict();a.Ik({page:a.Ik({index:a.ai().int().positive(),size:a.ai().int().positive(),total:a.ai().int().nonnegative()}).strict(),messages:a.YO(ae)}).strict();let at="pi-desk:pi-directories",as="pi-desk:ignored-pi-directories",an="pi-desk:pi-directory-entries",ar=!1,aa=null,ai=null,al=!1,ao=new Map;function ad(e){if(null===e)return"<root>";let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function ac(e){try{return JSON.parse(window.localStorage.getItem(e)??"null")}catch{return null}}function au(){ar||(ar=!0,aa=ac(at),ai=ac(as))}function am(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function ap(e){au(),aa=e,am(at,e)}function ah(){if(al)return;al=!0;let e=ac(an);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.entries;if(!(!t||"object"!=typeof t||Array.isArray(t)))for(let[e,s]of Object.entries(t))ao.set(e,s)}function ag(e){return ah(),ao.get(ad(e))??null}let ax="pi-desk:project-model-defaults",af=!1,ab=new Map;function av(e){let t=e.replaceAll("\\","/");return/^[A-Za-z]:\//.test(t)?t.toLowerCase():t}function aw(){if(!af){af=!0;try{let e=JSON.parse(window.localStorage.getItem(ax)??"null");if(!e||"object"!=typeof e||Array.isArray(e))return;for(let[t,s]of Object.entries(e)){let e=r0.safeParse(s);e.success&&ab.set(t,e.data)}let t=!1;for(;ab.size>64;){let e=ab.keys().next().value;if(void 0===e)break;ab.delete(e),t=!0}t&&ay()}catch{ab.clear()}}}function ay(){try{window.localStorage.setItem(ax,JSON.stringify(Object.fromEntries(ab)))}catch{}}function ak(e){let t=r0.safeParse(e);if(!t.success)return;aw();let s=av(t.data.cwd);for(ab.delete(s),ab.set(s,t.data);ab.size>64;){let e=ab.keys().next().value;if(void 0===e)break;ab.delete(e)}ay()}function aj(e){let t=rV.safeParse(e);if(!t.success){let e=t.error.issues[0]?.path.at(-1);if("modelId"===e)throw Error("请填写模型 ID 后再保存配置。");if("provider"===e)throw Error("请填写 Provider ID 后再保存配置。");throw Error("模型配置不完整或格式不正确,请检查必填字段和数值。")}return t.data}let aN=a.KC([a.k5(["appearance","region","habits","auth","models","mcp-settings","capability-modes","skills","plugins","about"]),a.Uy(["plugin:",a.Yj(),":",a.Yj()])]),aI=a.k5(["providers","presets","project-default"]),aC="pi-super:settings:section",aS="pi-super:settings:model-tab";function aM(e,t,s){try{let n=t.safeParse(window.localStorage.getItem(e));return n.success?n.data:s}catch{return s}}function az(e,t){try{window.localStorage.setItem(e,t)}catch(e){console.warn("[Pi Desk][Settings] 保存设置导航位置失败,仅当前窗口生效",e)}}function aE({open:e,text:t,error:s,saving:r,dirty:a,onChange:i,onClose:l,onSave:o}){let{t:d}=(0,f.Bd)("settings");return(0,n.jsx)(ej.YV,{open:e,onOpenChange:e=>{e||l()},children:(0,n.jsxs)(ej.hA,{className:"max-w-[52rem]",initialFocus:!1,showCloseButton:!r,children:[(0,n.jsxs)(ej.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(ej.YM,{children:d("nativeConfig")}),(0,n.jsx)(ej.uX,{children:d("nativeConfigScope")})]}),(0,n.jsx)(ej._Y,{className:"max-h-[70dvh]",children:(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(t8.T,{"aria-label":d("nativeConfigEditor"),value:t,disabled:r,spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",className:"min-h-[min(28rem,50dvh)] resize-y font-mono text-sm",onChange:e=>i(e.target.value)}),s?(0,n.jsx)("p",{role:"alert",className:"break-words text-sm text-destructive",children:s}):null]})}),(0,n.jsxs)(ej.vu,{children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",disabled:r,onClick:l,children:d("cancel",{ns:"common"})}),(0,n.jsxs)(N.$,{type:"button",disabled:r||!a,onClick:o,children:[r?(0,n.jsx)(b.A,{className:"animate-spin"}):null,d(r?"savingModels":"saveNativeConfig")]})]})]})})}var aA=s(43209),a$=s(54346),aR=s(55289),aT=s(24121),aP=s(78844);let aD=[{value:"#3b82f6",label:"presetColorBlue"},{value:"#0891b2",label:"presetColorCyan"},{value:"#16a34a",label:"presetColorGreen"},{value:"#b7791f",label:"presetColorAmber"},{value:"#ea580c",label:"presetColorOrange"},{value:"#dc2626",label:"presetColorRed"},{value:"#db2777",label:"presetColorPink"},{value:"#8b5cf6",label:"presetColorPurple"}];function aO(e){return aD.map(({value:t})=>({value:t,count:e.filter(e=>e.color?.toLowerCase()===t).length})).reduce((e,t)=>t.count<e.count?t:e).value}let aL=["OpenAI Chat Completions","OpenAI Responses","Anthropic Messages","Google Generative AI","Mistral Conversations","Azure OpenAI Responses","OpenAI Codex Responses","Amazon Bedrock","Google Vertex AI","Pi Messages"],aF=["openai-completions","openai-responses","anthropic-messages","google-generative-ai","mistral-conversations","azure-openai-responses","openai-codex-responses","bedrock-converse-stream","google-vertex","pi-messages"].map((e,t)=>({value:e,label:aL[t]})),a_=["openai","openrouter","together","deepseek","zai","qwen","chat-template","qwen-chat-template","string-thinking","ant-ling","baseten"];function aB(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join("\n")}function aq({headers:e,onChange:t,placeholder:s}){let[a,i]=(0,r.useState)(null);return(0,n.jsx)(t8.T,{value:a??aB(e),onFocus:()=>i(aB(e)),onChange:e=>{let s=e.target.value;i(s),t(Object.fromEntries(s.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(":");return t>0?[e.slice(0,t).trim(),e.slice(t+1).trim()]:[e,""]})))},onBlur:()=>i(null),rows:4,placeholder:s,className:"font-mono"})}function aW(e){let t=Math.floor(e/1e3),s=e%1e3;return s?`${t}.${String(s).padStart(3,"0").replace(/0+$/,"")}`:String(t)}function aY(e){if(!/^\d+(?:\.\d{0,3})?$/.test(e))return null;let[t,s=""]=e.split("."),n=1e3*Number(t)+Number(s.padEnd(3,"0"));return Number.isSafeInteger(n)&&n>0?n:null}function aU({label:e,children:t,className:s}){return(0,n.jsxs)("label",{className:(0,C.cn)("grid gap-1 text-sm text-foreground",s),children:[(0,n.jsx)("span",{className:"font-medium",children:e}),t]})}let aV="__pi-desk_empty__";function aK({value:e,options:t,onChange:s,ariaLabel:r,placeholder:a,allowEmpty:i=!0,className:l}){let{t:o}=(0,f.Bd)("settings"),d=a??o("useDefault"),c=e||(i?aV:t[0]?.value??null),u=!!e&&!t.some(t=>t.value===e);return(0,n.jsxs)(ea.l6,{value:c,onValueChange:e=>s(e===aV||null===e?"":e),children:[(0,n.jsx)(ea.bq,{"aria-label":r,className:(0,C.cn)("w-full",l),children:(0,n.jsx)(ea.yv,{children:t.find(t=>t.value===e)?.label??(e||d)})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[i?(0,n.jsx)(ea.eb,{value:aV,children:d}):null,u?(0,n.jsx)(ea.eb,{value:e,children:e}):null,t.map(e=>(0,n.jsx)(ea.eb,{value:e.value,children:e.label},e.value))]})]})}function aH({value:e,onChange:t,ariaLabel:s}){let{t:r}=(0,f.Bd)("settings");return(0,n.jsx)(aK,{value:null===e?"":String(e),ariaLabel:s,options:[{value:"true",label:r("yes")},{value:"false",label:r("no")}],onChange:e=>t(""===e?null:"true"===e)})}let aG={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function aJ(e,t){return JSON.stringify([e,t])}function aQ(e,t){return JSON.stringify([e.provider,e.modelId,e.thinkingLevel,t])}function aX(e){return e.map(e=>({value:aJ(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider}))}function aZ(e,t){return(e?.thinkingLevels??[]).map(e=>({value:e,label:t(aG[e])}))}function a0({id:e,preset:t,model:s,models:r,canMoveUp:a,canMoveDown:i,onChange:l,onDelete:o,onMoveUp:d,onMoveDown:c}){let{t:u}=(0,f.Bd)("settings"),{attributes:m,listeners:p,setActivatorNodeRef:h,setNodeRef:g,transform:x,transition:b,isDragging:v}=(0,a$.gl)({id:e}),w=x?`translate3d(${x.x}px, ${x.y}px, 0) scaleX(${x.scaleX??1}) scaleY(${x.scaleY??1})`:void 0,y=t.color?.toLowerCase()??"none",k=aD.find(e=>e.value===y),j=k?u(k.label):u(t.color?"presetColorCustom":"presetColorNone"),I=[{value:"none",color:null,label:u("presetColorNone")},...t.color&&!k?[{value:y,color:t.color,label:u("presetColorCustom")}]:[],...aD.map(e=>({value:e.value,color:e.value,label:u(e.label)}))];return(0,n.jsxs)("div",{ref:g,style:{transform:w,transition:b},className:(0,C.cn)("grid min-w-0 items-center gap-3 border-b bg-card py-3 @[48rem]/presets:grid-cols-[auto_minmax(0,1fr)_7.5rem_4rem_auto]",v&&"z-10 opacity-70 shadow-lg"),children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(N.$,{variant:"ghost",size:"icon-sm",ref:h,type:"button",title:u("presetDrag"),"aria-label":u("presetDrag"),className:"touch-none cursor-grab text-muted-foreground active:cursor-grabbing",...m,...p,children:(0,n.jsx)(aR.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(N.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveUp"),"aria-label":u("presetMoveUp"),disabled:!a,onClick:d,children:(0,n.jsx)(aT.A,{className:"size-4"})}),(0,n.jsx)(N.$,{variant:"ghost",size:"icon-sm",type:"button",title:u("presetMoveDown"),"aria-label":u("presetMoveDown"),disabled:!i,onClick:c,children:(0,n.jsx)(eq.A,{className:"size-4"})})]})]}),(0,n.jsx)(aU,{label:u("modelsHeading"),children:(0,n.jsx)(nF.b,{value:aJ(t.provider,t.modelId),options:aX(r),ariaLabel:u("presetModel"),searchPlaceholder:u("modelSearch"),onChange:e=>{let s=r.find(t=>aJ(t.provider,t.modelId)===e);s&&l({...t,provider:s.provider,modelId:s.modelId,thinkingLevel:s.thinkingLevels.includes(t.thinkingLevel)?t.thinkingLevel:s.thinkingLevels[0]})}})}),(0,n.jsx)(aU,{label:u("thinkingLevel"),children:(0,n.jsx)(aK,{value:t.thinkingLevel,options:aZ(s,u),ariaLabel:u("presetThinking"),allowEmpty:!1,onChange:e=>l({...t,thinkingLevel:e})})}),(0,n.jsx)(aU,{label:u("presetColor"),children:(0,n.jsxs)(ea.l6,{value:y,onValueChange:e=>{null!==e&&l({...t,color:"none"===e?null:e})},children:[(0,n.jsx)(ea.bq,{"aria-label":u("presetColorLabel"),className:"w-16",children:(0,n.jsxs)(ea.yv,{children:[t.color?(0,n.jsx)("span",{"aria-hidden":"true",className:"size-4 shrink-0 rounded-full",style:{backgroundColor:t.color}}):(0,n.jsx)(aP.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"sr-only",children:j})]})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[120]",className:"w-40 min-w-40",align:"end",alignItemWithTrigger:!1,children:(0,n.jsx)(ea.s3,{className:"grid grid-cols-4 gap-1 p-2",children:I.map(e=>(0,n.jsx)(ea.eb,{value:e.value,label:e.label,"aria-label":e.label,className:"size-8 justify-center p-0 data-selected:bg-accent data-selected:ring-1 data-selected:ring-ring data-selected:ring-inset [&>span:first-child]:justify-center [&>span:last-child]:hidden",children:e.color?(0,n.jsx)("span",{"aria-hidden":"true",className:"size-4 shrink-0 self-center rounded-full",style:{backgroundColor:e.color}}):(0,n.jsx)(aP.A,{"aria-hidden":"true",className:"size-4 text-muted-foreground"})},e.value))})})]})}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm",title:u("presetDelete"),"aria-label":u("presetDelete"),onClick:o,children:(0,n.jsx)(ee.A,{})})]})}function a1({presets:e,models:t,onChange:s}){let{t:a}=(0,f.Bd)("settings"),[i,l]=(0,r.useState)(()=>t[0]?aJ(t[0].provider,t[0].modelId):""),o=t.find(e=>aJ(e.provider,e.modelId)===i),[d,c]=(0,r.useState)(o?.thinkingLevels[0]??"off"),u=(0,aA.FR)((0,aA.MS)(aA.AN,{activationConstraint:{distance:6}}),(0,aA.MS)(aA.uN,{coordinateGetter:a$.JR})),m=(0,r.useMemo)(()=>e.map(aQ),[e]);return(0,n.jsxs)("div",{className:"@container/presets space-y-4 p-4 sm:p-6",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:a("presetDescription")}),(0,n.jsxs)("div",{className:"grid gap-3 border-b pb-4 @[32rem]/presets:grid-cols-[minmax(0,1fr)_7.5rem_auto]",children:[(0,n.jsx)(aU,{label:a("modelsHeading"),children:(0,n.jsx)(nF.b,{value:i,options:aX(t),ariaLabel:a("presetModelNew"),searchPlaceholder:a("modelSearch"),disabled:0===t.length,onChange:e=>{l(e);let s=t.find(t=>aJ(t.provider,t.modelId)===e);s&&c(s.thinkingLevels[0])}})}),(0,n.jsx)(aU,{label:a("thinkingLevel"),children:(0,n.jsx)(aK,{value:d,options:aZ(o,a),ariaLabel:a("presetThinkingNew"),allowEmpty:!1,onChange:e=>c(e)})}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",className:"self-end justify-self-start",onClick:function(){let n=t.find(e=>aJ(e.provider,e.modelId)===i);if(!n)return;let r=n.thinkingLevels.includes(d)?d:n.thinkingLevels[0];e.some(e=>e.provider===n.provider&&e.modelId===n.modelId&&e.thinkingLevel===r)||s([...e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r,color:aO(e)}])},disabled:!o,children:[(0,n.jsx)(U.A,{})," ",a("presetAdd")]})]}),0===e.length?(0,n.jsx)("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:a("presetEmpty")}):(0,n.jsx)(aA.Mp,{sensors:u,collisionDetection:aA.fp,onDragEnd:function(t){if(!t.over||t.active.id===t.over.id)return;let n=m.indexOf(String(t.active.id)),r=m.indexOf(String(t.over.id));n>=0&&r>=0&&s((0,a$.be)(e,n,r))},children:(0,n.jsx)(a$.gB,{items:m,strategy:a$._G,children:(0,n.jsx)("div",{className:"space-y-2",children:e.map((r,a)=>{let i=t.find(e=>e.provider===r.provider&&e.modelId===r.modelId);return(0,n.jsx)(a0,{id:m[a],preset:r,model:i,models:t,canMoveUp:a>0,canMoveDown:a<e.length-1,onChange:t=>s(e.map((e,s)=>s===a?t:e)),onDelete:()=>s(e.filter((e,t)=>t!==a)),onMoveUp:()=>s((0,a$.be)(e,a,a-1)),onMoveDown:()=>s((0,a$.be)(e,a,a+1))},m[a])})})})})]})}var a2=s(72910),a5=s(61108),a3=s(46783),a4=s(89790);function a6(e){return 100*!!e.official+10*!!e.defaults.cost}let a8=[["off","thinkingOff"],["minimal","thinkingMinimal"],["low","thinkingLow"],["medium","thinkingMedium"],["high","thinkingHigh"],["xhigh","thinkingXhigh"],["max","thinkingMax"]],a7=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function a9(e){return{input:String(e.cost?.input??""),output:String(e.cost?.output??""),cacheRead:String(e.cost?.cacheRead??""),cacheWrite:String(e.cost?.cacheWrite??"")}}function ie(e,t){return Object.values(e).some(e=>null===aY(e))||Object.values(t).some(e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e)))}function it({biz:e,provider:t,model:s,onChange:a,onInputState:i}){let{t:l}=(0,f.Bd)("settings"),o=(0,r.useId)(),[d,c]=(0,r.useState)({contextWindow:aW(s.contextWindow),maxTokens:aW(s.maxTokens)}),[u,m]=(0,r.useState)(()=>a9(s)),{searchText:p,setSearchText:h,catalogOpen:g,setCatalogOpen:x,loadingCatalog:v,candidates:w,visibleCandidates:y,showAllCandidates:k,setShowAllCandidates:j,selectedCandidateKey:I,setSelectedCandidateKey:C}=function(e,t){let{t:s}=(0,f.Bd)("settings"),n=(0,Q.G)(),a=(0,r.useRef)(0),[i,l]=(0,r.useState)(t),[o,d]=(0,r.useState)([]),[c,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[x,b]=(0,r.useState)(!1),v=(0,r.useMemo)(()=>{let e=new Map,t=o.filter(e=>"exact"===e.match);for(let s of t.length?t:o)for(let t of s.sources){let n=JSON.stringify([s.referenceId,t.modelId,t.defaults]),r=e.get(n);r?r.sources.push(t):e.set(n,{item:s,sources:[t]})}let s=i.trim().toLocaleLowerCase();return[...e.entries()].map(([e,t])=>{let s=[...t.sources].sort((e,t)=>a6(t)-a6(e)||e.providerName.localeCompare(t.providerName)),n=s[0];return{key:e,item:t.item,source:n,equivalentSourceCount:s.length,recommended:n.official}}).sort((e,t)=>("exact"===e.item.match?0:"similar"===e.item.match?1:2)-("exact"===t.item.match?0:"similar"===t.item.match?1:2)||Number(t.recommended)-Number(e.recommended)||Number(t.source.modelId.toLocaleLowerCase()===s)-Number(e.source.modelId.toLocaleLowerCase()===s)||e.source.providerName.localeCompare(t.source.providerName))},[o,i]);return(0,r.useEffect)(()=>{let t=++a.current;if(!c)return;let r=window.setTimeout(()=>{g(!0),e.listCatalog({query:i.trim(),refresh:!1,page:{index:1,size:10}}).then(e=>{a.current===t&&d(e.models)}).catch(e=>{a.current===t&&(d([]),n.error(e instanceof Error?e.message:s("catalogSearchFailed")))}).finally(()=>{a.current===t&&g(!1)})},250);return()=>{window.clearTimeout(r),a.current===t&&(a.current+=1)}},[e,c,i,n,s]),{searchText:i,setSearchText:l,catalogOpen:c,setCatalogOpen:e=>{u(e),e||g(!1)},loadingCatalog:h,candidates:v,visibleCandidates:x?v:v.slice(0,6),showAllCandidates:x,setShowAllCandidates:b,selectedCandidateKey:m,setSelectedCandidateKey:p}}(e,s.modelId),S=new Map(s.thinkingLevels.map(e=>[e.level,e])),M=aF.find(e=>e.value===t.api)?.label??t.api;function z(e){a({...s,...e})}return(0,n.jsxs)("div",{className:"@container/model-editor space-y-6",children:[(0,n.jsxs)("div",{className:"grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[(0,n.jsxs)("div",{className:"grid gap-1 text-sm @[32rem]/model-editor:col-span-2",children:[(0,n.jsx)("label",{htmlFor:o,className:"font-medium",children:l("modelId")}),(0,n.jsx)(a4.uB,{shouldFilter:!1,loop:!0,className:"h-auto w-full overflow-visible rounded-none bg-transparent p-0 [&_[data-slot=command-input-wrapper]]:p-0 [&_[data-slot=input-group-addon]]:hidden",onKeyDown:e=>{"Escape"===e.key&&g&&(e.preventDefault(),e.stopPropagation(),x(!1))},children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(a4.G7,{id:o,value:p,onValueChange:e=>{h(e),z({modelId:e}),C(null),j(!1),x(!0)},placeholder:l("modelIdSearch"),"aria-label":l("modelId"),"aria-autocomplete":"list",className:"pr-9"}),(0,n.jsxs)(eJ.AM,{open:g,onOpenChange:e=>{x(e),e&&j(!1)},children:[(0,n.jsx)(eJ.Wv,{render:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm",title:l("chooseModel"),"aria-label":l("chooseModel"),"aria-busy":v,className:"absolute top-0.5 right-0.5 z-10",children:v?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(a3.A,{})})}),(0,n.jsx)(eJ.hl,{align:"end",sideOffset:4,initialFocus:!1,finalFocus:!1,positionerClassName:"z-[120]",className:"w-[min(32rem,calc(100vw-2rem))] gap-0 p-0",children:(0,n.jsx)(a4.oI,{className:"max-h-[min(24rem,var(--available-height))] p-1",children:v&&0===w.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:l("matchingCatalog")}):0===w.length?(0,n.jsx)(a4.xL,{className:"py-6 text-sm",children:l("noCatalogMatches")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a4.L$,{className:"p-0",children:y.map(e=>(0,n.jsx)(a4.h_,{value:e.key,"data-checked":I===e.key?"true":void 0,className:"px-3 py-2",onSelect:()=>(function(e){let{item:t,source:n}=e,r={...s,modelId:n.modelId,name:t.name,...n.defaults};a(r),c({contextWindow:aW(r.contextWindow),maxTokens:aW(r.maxTokens)}),m(a9(r)),i({dirty:!1,invalid:!1}),h(n.modelId),C(e.key),j(!1),x(!1)})(e),children:(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("span",{className:"break-all font-mono text-sm font-semibold",children:e.source.modelId}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.source.providerName})]}),(0,n.jsxs)("span",{className:"mt-1 block text-xs text-muted-foreground",children:[e.item.name," \xb7"," ",l("contextAndOutput",{context:`${aW(e.source.defaults.contextWindow)}K`,output:`${aW(e.source.defaults.maxTokens)}K`})]}),(0,n.jsx)("span",{className:"mt-1 block text-xs text-muted-foreground",children:e.source.defaults.cost?`${l("priceInput",{price:`$${e.source.defaults.cost.input}`})} \xb7 ${l("priceOutput",{price:`$${e.source.defaults.cost.output}`})}${l("perMillionTokens")}`:l("priceMissing")})]})},e.key))}),!k&&w.length>y.length?(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:()=>j(!0),children:l("moreConfigurations",{count:w.length-y.length})}):null]})})})]})]})}),s.modelId.trim()?null:(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("modelIdRequired")})]}),(0,n.jsxs)(aU,{label:l("modelName"),className:"@[32rem]/model-editor:col-span-2",children:[(0,n.jsx)(eu.p,{value:s.name,onChange:e=>z({name:e.target.value})}),s.name.trim()?null:(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("modelNameRequired")})]}),[["contextWindow","contextLength"],["maxTokens","maximumOutput"]].map(([e,t])=>{let s=null===aY(d[e]);return(0,n.jsxs)(aU,{label:l(t),children:[(0,n.jsxs)(ny.MG,{children:[(0,n.jsx)(ny.iV,{"aria-label":l(t),inputMode:"decimal",value:d[e],"aria-invalid":s,"aria-describedby":s?`${o}-${e}-error`:void 0,onChange:t=>{var s;let n,r,a;return s=t.target.value,c(n={...d,[e]:s}),i({dirty:r=ie(n,u),invalid:r}),void(null!==(a=aY(s))&&z({[e]:a}))}}),(0,n.jsx)(ny.Sq,{align:"inline-end",children:"K"})]}),s?(0,n.jsx)("span",{id:`${o}-${e}-error`,role:"alert",className:"text-xs text-destructive",children:l("capacityInvalid")}):null]},e)})]}),(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:l("capabilities")}),(0,n.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2 text-sm",children:[s.input.map(e=>(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-1",children:l("text"===e?"textInput":"imageInput")},e)),s.reasoning?(0,n.jsx)("span",{className:"rounded-md bg-muted px-2 py-1",children:l("supportsThinking")}):null]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("inputAndThinking")}),(0,n.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[["text","image"].map(e=>{let t=s.input.includes(e);return(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline","aria-pressed":t,onClick:()=>{t&&1===s.input.length||z({input:t?s.input.filter(t=>t!==e):[...s.input,e]})},children:[t?(0,n.jsx)(em.A,{}):null,l("text"===e?"textInput":"imageInput")]},e)}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline","aria-pressed":s.reasoning,onClick:()=>z({reasoning:!s.reasoning,thinkingLevels:s.reasoning?[{level:"off",providerValue:null}]:[{level:"high",providerValue:null}]}),children:[s.reasoning?(0,n.jsx)(em.A,{}):null,l("supportsThinking")]})]}),s.reasoning?(0,n.jsxs)("details",{className:"mt-4 border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-medium",children:l("thinkingMapping")}),(0,n.jsx)("div",{className:"mt-2 grid max-w-[40rem] gap-x-4 @[32rem]/model-editor:grid-cols-2",children:a8.map(([e,t])=>{let r=S.get(e);return(0,n.jsxs)("div",{className:"grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-2 border-b py-2",children:[(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm","aria-pressed":!!r,className:"justify-start",onClick:()=>{let t=r?s.thinkingLevels.filter(t=>t.level!==e):[...s.thinkingLevels,{level:e,providerValue:"off"===e?null:e}];t.length&&z({thinkingLevels:t})},children:[r?(0,n.jsx)(em.A,{}):null,l(t)]}),(0,n.jsx)(eu.p,{"aria-label":l("providerMapping",{level:l(t)}),disabled:!r||"off"===e,value:"off"===e?l("noMapping"):r?.providerValue??"",placeholder:e,onChange:t=>z({thinkingLevels:s.thinkingLevels.map(s=>s.level===e?{...s,providerValue:t.target.value||null}:s)})})]},e)})})]}):null]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("price")}),(0,n.jsxs)("div",{className:"mt-3 grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[a7.map(([e,t])=>{let r=""!==u[e]&&(!Number.isFinite(Number(u[e]))||0>Number(u[e]));return(0,n.jsxs)(aU,{label:l(t),children:[(0,n.jsx)(eu.p,{inputMode:"decimal",value:u[e],"aria-invalid":r,onChange:t=>(function(e,t){let n={...u,[e]:t};m(n);let r=ie(d,n);if(i({dirty:r,invalid:r}),Object.values(n).every(e=>""===e))return void z({cost:null});let a=Number(t);Number.isFinite(a)&&!(a<0)&&z({cost:{input:s.cost?.input??0,output:s.cost?.output??0,cacheRead:s.cost?.cacheRead??0,cacheWrite:s.cost?.cacheWrite??0,[e]:a}})})(e,t.target.value)}),r?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:l("priceInvalid")}):null]},e)}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",className:"justify-self-start",onClick:()=>{let e={input:"",output:"",cacheRead:"",cacheWrite:""};m(e),i({dirty:!0,invalid:ie(d,e)}),z({cost:null})},children:l("clearPrice")})]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("advancedCompatibility")}),(0,n.jsxs)("div",{className:"mt-3 grid max-w-[40rem] gap-3 @[32rem]/model-editor:grid-cols-2",children:[(0,n.jsx)(aU,{label:l("apiOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(aK,{value:s.api??"",ariaLabel:l("apiOverride"),options:aF,placeholder:M?l("inheritServiceValue",{value:M}):l("inheritService"),onChange:e=>z({api:e||null})})}),(0,n.jsx)(aU,{label:l("baseUrlOverride"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(eu.p,{value:s.baseUrl??"","aria-label":l("baseUrlOverride"),placeholder:t.baseUrl?l("inheritServiceValue",{value:t.baseUrl}):l("inheritService"),onChange:e=>z({baseUrl:e.target.value||null})})}),(0,n.jsx)(aU,{label:l("modelHeaders"),className:"@[32rem]/model-editor:col-span-2",children:(0,n.jsx)(aq,{headers:s.headers,onChange:e=>z({headers:e}),placeholder:l("headerPlaceholder")})}),(0,n.jsx)(aU,{label:l("developerRole"),children:(0,n.jsx)(aH,{value:s.compat?.supportsDeveloperRole??null,ariaLabel:l("developerRole"),onChange:e=>z({compat:{supportsDeveloperRole:e,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(aU,{label:"Thinking Format",children:(0,n.jsx)(aK,{value:s.compat?.thinkingFormat??"",ariaLabel:"Thinking Format",options:a_.map(e=>({value:e,label:e})),onChange:e=>z({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:e||null,requiresReasoningContentOnAssistantMessages:s.compat?.requiresReasoningContentOnAssistantMessages??null}})})}),(0,n.jsx)(aU,{label:l("replayReasoning"),children:(0,n.jsx)(aH,{value:s.compat?.requiresReasoningContentOnAssistantMessages??null,ariaLabel:l("replayReasoning"),onChange:e=>z({compat:{supportsDeveloperRole:s.compat?.supportsDeveloperRole??null,thinkingFormat:s.compat?.thinkingFormat??null,requiresReasoningContentOnAssistantMessages:e}})})})]})]})]})}var is=s(66153),ir=s(95929);function ia({className:e,disabled:t,id:s,...a}){let{t:i}=(0,f.Bd)("common"),[l,o]=r.useState(!1),d=i(l?"hideSecret":"revealSecret");return(0,n.jsxs)("div",{className:"relative min-w-0",children:[(0,n.jsx)(eu.p,{...a,id:s,disabled:t,type:"text",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,className:(0,C.cn)("pr-9",!l&&"[-webkit-text-security:disc]",e)}),(0,n.jsx)("button",{type:"button",className:"absolute top-1/2 right-1 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50","aria-label":d,"aria-controls":s,"aria-pressed":l,title:d,disabled:t,onClick:()=>o(e=>!e),children:l?(0,n.jsx)(is.A,{className:"size-3.5"}):(0,n.jsx)(ir.A,{className:"size-3.5"})})]})}function ii({provider:e,existingIds:t,isNew:s,onApply:a,onDelete:i,onClose:l,onDirtyChange:o}){let{t:d}=(0,f.Bd)("settings"),{confirm:c,dialog:u}=nR(),[m,p]=(0,r.useState)(()=>structuredClone(e)),h=JSON.stringify(m)!==JSON.stringify(e),g=!m.provider.trim()||t.includes(m.provider.trim()),x=m.provider||d("providerUnnamed");function b(e){p(t=>({...t,...e}))}async function v(){(!h||await c({title:d("discardServiceTitle"),description:d("discardServiceDescription"),confirmLabel:d("discardModelConfirm")}))&&l()}async function w(){await c({title:d("providerDeleteTitle"),description:d("providerDeleteDescription",{name:x,count:e.models.length})})&&i()}return(0,r.useEffect)(()=>(o(h),()=>o(!1)),[h,o]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ej.YV,{open:!0,onOpenChange:e=>{e||v()},children:(0,n.jsxs)(ej.hA,{className:"max-w-[40rem]",initialFocus:!1,children:[(0,n.jsxs)(ej.Hl,{className:"border-b px-4 py-4 pr-12",children:[(0,n.jsx)(ej.YM,{children:d("serviceConnection")}),(0,n.jsx)(ej.uX,{children:d("serviceDraftScope",{count:e.models.length})})]}),(0,n.jsx)(ej._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-5 p-4",children:[(0,n.jsxs)(aU,{label:d("serviceId"),children:[(0,n.jsx)(eu.p,{value:m.provider,"aria-label":d("serviceId"),autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:d("providerIdExample"),"aria-invalid":g,onChange:e=>b({provider:e.target.value})}),g?(0,n.jsx)("span",{role:"alert",className:"text-xs text-destructive",children:d("serviceIdInvalid")}):null]}),(0,n.jsx)(aU,{label:d("serviceAddress"),children:(0,n.jsx)(eu.p,{value:m.baseUrl??"",placeholder:"https://api.example.com/v1",onChange:e=>b({baseUrl:e.target.value||null})})}),(0,n.jsx)(aU,{label:d("providerApiType"),children:(0,n.jsx)(aK,{value:m.api??"",ariaLabel:d("providerApiType"),options:aF,onChange:e=>b({api:e||null})})}),(0,n.jsx)(aU,{label:d("serviceKey"),children:(0,n.jsx)(ia,{value:m.apiKey??"",onChange:e=>b({apiKey:e.target.value||null})})}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:d("providerAdvanced")}),(0,n.jsxs)("div",{className:"mt-3 space-y-3",children:[(0,n.jsx)(aU,{label:d("providerAuthHeader"),children:(0,n.jsx)(aH,{value:m.authHeader,ariaLabel:d("providerAuthHeader"),onChange:e=>b({authHeader:e})})}),(0,n.jsx)(aU,{label:d("providerHeaders"),children:(0,n.jsx)(aq,{headers:m.headers,onChange:e=>b({headers:e}),placeholder:d("headerPlaceholder")})})]})]})]})}),(0,n.jsxs)(ej.vu,{children:[s?null:(0,n.jsxs)(N.$,{type:"button",variant:"ghost",className:"mr-auto text-destructive hover:text-destructive",onClick:w,children:[(0,n.jsx)(ee.A,{}),d("providerDelete")]}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",onClick:l,children:d("cancel",{ns:"common"})}),(0,n.jsx)(N.$,{type:"button",disabled:g||!h&&!s,onClick:()=>a(m),children:d("applyServiceDraft")})]})]})}),u]})}let il=a.Ik({}).strict(),io=a.Yj().trim().min(1).max(128),id=a.Yj().max(32768),ic=a.Ik({url:id,label:id.optional()}).strict(),iu=a.Ik({provider:io,name:id,loggedIn:a.zM(),conflict:a.Yj().nullable()}).strict(),im=a.Ik({id:a.Yj().uuid(),type:a.k5(["text","secret","select","manual_code"]),message:id,placeholder:id.optional(),options:a.YO(a.Ik({id:id,label:id,description:id.optional()}).strict()).optional()}).strict(),ip=a.gM("type",[a.Ik({type:a.eu("auth_url"),url:id,instructions:id.optional()}).strict(),a.Ik({type:a.eu("device_code"),userCode:id,verificationUri:id}).strict(),a.Ik({type:a.eu("info"),message:id,links:a.YO(ic).optional()}).strict(),a.Ik({type:a.eu("progress"),message:id}).strict()]),ih=a.Ik({loginId:a.Yj().uuid(),provider:io,status:a.k5(["running","completed","cancelled","error"]),notice:ip.nullable(),prompt:im.nullable(),message:a.Yj().nullable()}).strict(),ig=Object.freeze({list:(0,i.Vc)({path:"model-auth/list",inputSchema:il,outputSchema:a.Ik({providers:a.YO(iu)}).strict()}),start:(0,i.Vc)({path:"model-auth/start",inputSchema:a.Ik({loginId:a.Yj().uuid(),provider:io}).strict(),outputSchema:il}),respond:(0,i.Vc)({path:"model-auth/respond",inputSchema:a.Ik({loginId:a.Yj().uuid(),promptId:a.Yj().uuid(),value:id}).strict(),outputSchema:il}),cancel:(0,i.Vc)({path:"model-auth/cancel",inputSchema:a.Ik({loginId:a.Yj().uuid()}).strict(),outputSchema:il}),logout:(0,i.Vc)({path:"model-auth/logout",inputSchema:a.Ik({provider:io}).strict(),outputSchema:il}),state:(0,i._G)({path:"model-auth/state",bodySchema:ih})});function ix(e){try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}}function ib(e){let t=ix(e);t&&window.open(t,"_blank","noopener,noreferrer")}async function iv(e){await navigator.clipboard.writeText(e)}function iw({prompt:e,submitting:t,onRespond:s}){let{t:a}=(0,f.Bd)("settings"),[i,l]=(0,r.useState)(""),o="select"!==e.type||i.length>0;return(0,n.jsxs)("form",{className:"grid gap-3",onSubmit:n=>{n.preventDefault(),o&&!t&&s(e.id,i)},children:[(0,n.jsx)(aU,{label:e.message,children:"select"===e.type?(0,n.jsx)(aK,{value:i,ariaLabel:e.message,placeholder:e.placeholder??a("accountChooseOption"),options:(e.options??[]).map(e=>({value:e.id,label:e.description?`${e.label} — ${e.description}`:e.label})),onChange:l}):"secret"===e.type?(0,n.jsx)(ia,{value:i,placeholder:e.placeholder,disabled:t,onChange:e=>l(e.target.value)}):(0,n.jsx)(eu.p,{value:i,placeholder:e.placeholder,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,disabled:t,onChange:e=>l(e.target.value)})}),(0,n.jsx)(N.$,{type:"submit",disabled:!o||t,className:"justify-self-end",children:a("accountContinue")})]})}function iy({notice:e,onCopy:t,onOpenUrl:s}){let{t:r}=(0,f.Bd)("settings"),a="auth_url"===e.type?[{url:e.url}]:"device_code"===e.type?[{url:e.verificationUri}]:"info"===e.type?e.links??[]:[];return(0,n.jsxs)("div",{className:"space-y-3",children:["auth_url"===e.type&&e.instructions?(0,n.jsx)("p",{className:"whitespace-pre-wrap text-sm",children:e.instructions}):null,"info"===e.type||"progress"===e.type?(0,n.jsx)("p",{className:"whitespace-pre-wrap text-sm",role:"status",children:e.message}):null,"device_code"===e.type?(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border p-3",children:[(0,n.jsx)("span",{className:"text-sm",children:r("accountDeviceCode")}),(0,n.jsx)("code",{className:"select-all break-all text-lg font-semibold",children:e.userCode}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t(e.userCode),children:r("accountCopyCode")})]}):null,a.map((e,a)=>ix(e.url)?(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:e.url}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>s(e.url),children:e.label??r("accountOpenLink")}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>void t(e.url),children:r("accountCopyLink")})]})]},`${a}:${e.url}`):(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:r("accountInvalidLink")},a))]})}function ik({open:e,connected:t,providers:s,state:r,loading:a,submitting:i,error:l,onClose:o,onStart:d,onRespond:c,onCopy:u,onOpenUrl:m,onRetry:p}){let{t:h}=(0,f.Bd)("settings"),g=r?.status==="running";return(0,n.jsx)(ej.YV,{open:e,onOpenChange:e=>{e||o()},children:(0,n.jsxs)(ej.hA,{className:"max-w-lg",children:[(0,n.jsx)(ej.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(ej.YM,{children:r?s.find(e=>e.provider===r.provider)?.name??r.provider:h("accountLogin")})}),(0,n.jsx)(ej._Y,{className:"max-h-[65dvh]",children:(0,n.jsxs)("div",{className:"space-y-4 p-4",children:[l?(0,n.jsx)("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-destructive",children:l}):null,r?.message?(0,n.jsx)("p",{role:"error"===r.status?"alert":"status",className:"whitespace-pre-wrap text-sm",children:r.message}):null,r&&"cancelled"!==r.status&&"error"!==r.status?null:a?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:h("accountLoadingProviders")}):(0,n.jsxs)("div",{className:"grid gap-2",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:h("accountChooseProvider")}),s.length?null:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:h("accountNoProviders")}),s.map(e=>(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsxs)(N.$,{type:"button",variant:"outline",className:"h-auto min-h-10 justify-between whitespace-normal text-left",disabled:!t||!!e.conflict,onClick:()=>void d(e.provider),children:[(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.loggedIn?h("accountRelogin"):h("accountLogin")})]}),e.conflict?(0,n.jsx)("p",{className:"text-sm text-destructive",children:e.conflict}):null]},e.provider))]}),g&&r.notice?(0,n.jsx)(iy,{notice:r.notice,onCopy:u,onOpenUrl:m}):null,g&&r.prompt?(0,n.jsx)(iw,{prompt:r.prompt,submitting:i||!t,onRespond:c},r.prompt.id):null,g&&!r.prompt?(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:h("accountWaiting")}):null,r?.status==="completed"?(0,n.jsx)("p",{role:"status",className:"text-sm",children:h("accountLoggedIn")}):null]})}),(0,n.jsxs)(ej.vu,{children:[l&&!g?(0,n.jsx)(N.$,{type:"button",variant:"outline",disabled:a,onClick:p,children:h("retry",{ns:"common"})}):null,(0,n.jsx)(N.$,{type:"button",variant:"ghost",onClick:o,children:h(g?"cancel":"close",{ns:"common"})})]})]})})}function ij({account:e,existingIds:t,onAdd:s,onClose:a}){let{t:i}=(0,f.Bd)("settings"),[l,o]=(0,r.useState)(""),[d,c]=(0,r.useState)([]),u=e.models.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(l.toLocaleLowerCase()));return(0,n.jsx)(ej.YV,{open:!0,onOpenChange:e=>{e||a()},children:(0,n.jsxs)(ej.hA,{className:"max-w-xl",children:[(0,n.jsx)(ej.Hl,{className:"border-b p-4 pr-12",children:(0,n.jsx)(ej.YM,{children:i("modelAddToService",{name:e.name})})}),(0,n.jsx)("div",{className:"p-4 pb-2",children:(0,n.jsx)(eu.p,{value:l,"aria-label":i("accountModelSearch"),placeholder:i("accountModelSearch"),onChange:e=>o(e.target.value)})}),(0,n.jsx)(ej._Y,{className:"max-h-[55dvh]",children:(0,n.jsxs)("div",{className:"space-y-1 px-4 pb-4",children:[u.map(e=>{let s=t.includes(e.modelId);return(0,n.jsxs)("label",{className:"flex min-h-14 cursor-pointer items-center gap-3 rounded-lg px-3 py-2 hover:bg-accent",children:[(0,n.jsx)("input",{type:"checkbox",className:"size-4 shrink-0 accent-primary",checked:s||d.includes(e.modelId),disabled:s,onChange:t=>c(s=>t.target.checked?[...s,e.modelId]:s.filter(t=>t!==e.modelId))}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block break-words text-sm font-medium",children:e.name}),(0,n.jsxs)("span",{className:"block break-all text-xs text-muted-foreground",children:[e.modelId," \xb7 ",aW(e.contextWindow)," K"]})]}),s?(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:i("accountModelAdded")}):null]},e.modelId)}),u.length?null:(0,n.jsx)("p",{className:"py-6 text-center text-sm text-muted-foreground",children:i("accountNoModels")})]})}),(0,n.jsxs)(ej.vu,{children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",onClick:a,children:i("accountAddLater")}),(0,n.jsx)(N.$,{type:"button",disabled:!d.length,onClick:()=>s(d),children:i("accountAddSelected",{count:d.length})})]})]})})}let iN=[["input","inputPrice"],["output","outputPrice"],["cacheRead","cacheReadPrice"],["cacheWrite","cacheWritePrice"]];function iI({model:e,account:t,overrides:s,onChange:a,onInputState:i}){let{t:l}=(0,f.Bd)("settings"),[o,d]=(0,r.useState)(()=>({contextWindow:void 0===s.contextWindow?"":aW(s.contextWindow),maxTokens:void 0===s.maxTokens?"":aW(s.maxTokens),...Object.fromEntries(iN.map(([e])=>[e,s.cost?.[e]===void 0?"":String(s.cost[e])]))})),c=e=>""!==e&&null===aY(e),u=e=>""!==e&&(!Number.isFinite(Number(e))||0>Number(e));function m(e,t){let n={...o,[e]:t};d(n);let r=c(n.contextWindow)||c(n.maxTokens)||iN.some(([e])=>u(n[e]));if(i({dirty:r,invalid:r}),"contextWindow"===e||"maxTokens"===e){if(c(t))return;let n={...s};""===t?delete n[e]:n[e]=aY(t),a(n)}else{if(iN.some(([e])=>u(n[e])))return;let e={...s};iN.every(([e])=>""===n[e])?delete e.cost:e.cost=Object.fromEntries(iN.filter(([e])=>""!==n[e]).map(([e])=>[e,Number(n[e])])),a(e)}}if(!e)return(0,n.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:l("accountModelUnavailable")});let p=e.cost?{...e.cost,...s.cost}:s.cost;return(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-6",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)("span",{children:l(t?.loggedIn?"accountLoggedIn":"accountLoggedOut")}),t?.subscription?(0,n.jsx)("span",{className:"rounded-md bg-muted px-2",children:l("accountSubscription")}):null]}),(0,n.jsxs)("dl",{className:"grid gap-4 sm:grid-cols-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("contextLength")}),(0,n.jsxs)("dd",{className:"mt-1 text-lg font-semibold",children:[aW(s.contextWindow??e.contextWindow)," K"]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("maximumOutput")}),(0,n.jsxs)("dd",{className:"mt-1 text-lg font-semibold",children:[aW(s.maxTokens??e.maxTokens)," K"]})]}),(0,n.jsxs)("div",{className:"sm:col-span-2",children:[(0,n.jsx)("dt",{className:"text-sm text-muted-foreground",children:l("capabilities")}),(0,n.jsx)("dd",{className:"mt-1 text-sm",children:[...e.input.map(e=>l("image"===e?"imageInput":"textInput")),...e.reasoning?[l("supportsThinking")]:[]].join(" \xb7 ")})]})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("accountReferencePrice")}),(0,n.jsx)("div",{className:"mt-3 text-sm text-muted-foreground",children:p?iN.map(([e,t])=>(0,n.jsxs)("p",{children:[l(t),": ",void 0===p[e]?"—":`$${p[e]}`]},e)):l("priceMissing")})]}),(0,n.jsxs)("details",{className:"border-t pt-3",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-semibold",children:l("accountAdjustParameters")}),(0,n.jsxs)("div",{className:"mt-4 space-y-4",children:[(0,n.jsx)("div",{className:"grid gap-3 sm:grid-cols-2",children:["contextWindow","maxTokens"].map(t=>(0,n.jsxs)(aU,{label:`${l("contextWindow"===t?"contextLength":"maximumOutput")} (K)`,children:[(0,n.jsx)(eu.p,{value:o[t],placeholder:aW(e[t]),inputMode:"decimal","aria-invalid":c(o[t]),onChange:e=>m(t,e.target.value)}),c(o[t])?(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("capacityInvalid")}):null]},t))}),(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"cursor-pointer text-sm font-medium",children:l("price")}),(0,n.jsx)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:iN.map(([t,s])=>(0,n.jsxs)(aU,{label:l(s),children:[(0,n.jsx)(eu.p,{value:o[t],inputMode:"decimal",placeholder:String(e.cost?.[t]??""),"aria-invalid":u(o[t]),onChange:e=>m(t,e.target.value)}),u(o[t])?(0,n.jsx)("span",{className:"text-xs text-destructive",children:l("priceInvalid")}):null]},t))})]}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{d({contextWindow:"",maxTokens:"",input:"",output:"",cacheRead:"",cacheWrite:""}),a({}),i({dirty:!1,invalid:!1})},children:l("accountRestoreDefaults")})]})]})]})}var iC=s(34506);function iS({name:e,hasAccount:t,loggedIn:s,hasCustom:a,onCustomSettings:i,onLogin:l,onLogout:o}){let{t:d}=(0,f.Bd)("settings"),[c,u]=(0,r.useState)(!1),m=(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":d("serviceSettingsNamed",{name:e}),onClick:t?void 0:i,children:(0,n.jsx)(iC.A,{})});function p(e){u(!1),e()}return t?(0,n.jsxs)(eJ.AM,{open:c,onOpenChange:u,children:[(0,n.jsx)(eJ.Wv,{render:m}),(0,n.jsxs)(eJ.hl,{align:"end",positionerClassName:"z-[120]",className:"w-52 gap-1 p-1",children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(l),children:d(s?"accountRelogin":"accountLogin")}),s?(0,n.jsx)(N.$,{type:"button",variant:"ghost",className:"justify-start text-destructive",onClick:()=>p(o),children:d("accountLogout")}):null,a?(0,n.jsx)(N.$,{type:"button",variant:"ghost",className:"justify-start",onClick:()=>p(i),children:d("accountCustomSettings")}):null]})]}):m}function iM({providerId:e,custom:t,account:s,accountModels:r,query:a,modelKeys:i,selectedCustomIndex:l,selectedAccountId:o,presets:d,onSelectCustom:c,onSelectAccount:u,onCustomSettings:m,onAddCustom:p,onAddAccount:h,onLogin:g,onLogout:x,onGroupRef:b,onRowRef:v}){let{t:w}=(0,f.Bd)("settings"),y=(t?e:s?.name)||e||w("providerUnnamed"),k=r.filter(e=>!t?.models.some(t=>t.modelId===e.modelId)),j=[...(t?.models??[]).map((e,t)=>({key:i[t],modelId:e.modelId,name:e.name,model:e,selected:l===t,select:()=>c(t)})),...k.map(t=>{let n=s?.models.find(e=>e.modelId===t.modelId);return{key:`account:${e}:${t.modelId}`,modelId:t.modelId,name:n?.name??t.modelId,model:n?{...n,...t.overrides}:void 0,selected:o===t.modelId,select:()=>u(t.modelId)}})],I=j.filter(t=>`${e} ${y} ${s?.name??""} ${t.name} ${t.modelId}`.toLocaleLowerCase().includes(a.toLocaleLowerCase()));if(a&&!I.length&&!`${e} ${y} ${s?.name??""}`.toLocaleLowerCase().includes(a.toLocaleLowerCase()))return null;let S=!!s||r.length>0;return(0,n.jsxs)("section",{ref:b,className:"mb-3",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1 text-foreground",children:[(0,n.jsx)(eS.A,{"aria-hidden":"true",className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold",title:s?.name,children:y}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:j.length}),(0,n.jsx)(iS,{name:y,hasAccount:S,loggedIn:s?.loggedIn??!1,hasCustom:!!t,onCustomSettings:m,onLogin:g,onLogout:x})]}),(0,n.jsxs)("div",{className:"space-y-1",children:[I.map(t=>(0,n.jsxs)("button",{ref:e=>v(t.key,e),type:"button","aria-current":t.selected?"true":void 0,className:(0,C.cn)("flex min-h-14 w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",t.selected&&"bg-accent text-accent-foreground"),onClick:t.select,children:[(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",children:t.name||t.modelId||w("modelUnnamed")}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:t.model?`${aW(t.model.contextWindow)} K \xb7 ${w(t.model.input.includes("image")?"imageInput":"textInput")}`:w("accountModelUnavailableShort")})]}),d.some(s=>s.provider===e&&s.modelId===t.modelId)?(0,n.jsx)(a5.A,{className:"size-4 shrink-0 text-muted-foreground"}):null]},t.key)),S?(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",className:"mt-1 w-full border border-dashed border-input","aria-label":w("modelAddToService",{name:s?.name??y}),onClick:h,children:[(0,n.jsx)(U.A,{}),w("modelAdd")]}):null,t?(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",className:"mt-1 w-full border border-dashed border-input","aria-label":w("modelAddToService",{name:y}),onClick:p,children:[(0,n.jsx)(U.A,{}),S?w("accountCustomModel"):null]}):null]})]})}let iz={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function iE({biz:e,connectionReady:t,providers:s,accounts:a,accountModels:i,onAccountModelsChange:l,onRefreshAccounts:o,savedModels:d,savedProviders:c,presets:u,resetVersion:m,onChange:p,onPresetsChange:h,onInputState:g,onServiceDirtyChange:x}){let{t:b}=(0,f.Bd)("settings"),{confirm:v,dialog:w}=nR(),y=(0,Q.G)(),[k,j]=(0,r.useState)(null),[I,S]=(0,r.useState)(null),[M,z]=(0,r.useState)(!1),[A,$]=(0,r.useState)(()=>new Set),R=function(e,t){let{appSocket:s}=(0,er.gM)(),n=(0,r.useMemo)(()=>({list:async()=>(await s.request(ig.list,{})).providers,async start(e,t){await s.request(ig.start,{loginId:e,provider:t})},async respond(e,t,n){await s.request(ig.respond,{loginId:e,promptId:t,value:n})},async cancel(e){await s.request(ig.cancel,{loginId:e})},async logout(e){await s.request(ig.logout,{provider:e})},subscribe:e=>s.subscribe(ig.state,e)}),[s]),{t:a}=(0,f.Bd)("settings"),i=(0,Q.G)(),[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)([]),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),[g,x]=(0,r.useState)(!1),[b,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(null),k=(0,r.useRef)(e),j=(0,r.useRef)(null),N=(0,r.useRef)(null),I=(0,r.useRef)(null),C=(0,r.useRef)(null),S=(0,r.useRef)(0),M=(0,r.useRef)(t);function z(){let e=j.current;j.current=null,N.current=null,I.current=null,C.current?.(),C.current=null,e?.status==="running"&&n.cancel(e.loginId).catch(e=>{console.warn("[Pi Desk][ModelAuth] 取消登录失败",{message:e instanceof Error?e.message:String(e)})})}function E(){S.current+=1,z(),o(!1)}async function A(){let e=j.current;if(!e||"completed"!==e.status||I.current)return;I.current=e.loginId,x(!0),y(null);let t=()=>j.current?.loginId===e.loginId;try{await M.current(e.provider,t),t()&&E()}catch(e){t()&&y(e instanceof Error?e.message:a("accountRefreshFailed"))}finally{t()&&(I.current=null,x(!1))}}async function $(e){if(!k.current)return void y(a("accountConnectionNotReady"));if(j.current?.status==="running")return;z();let t={loginId:crypto.randomUUID(),provider:e,status:"running",notice:null,prompt:null,message:null};j.current=t,m(t),y(null),v(null),C.current=n.subscribe(e=>{j.current?.loginId===e.loginId&&((j.current.prompt?.id!==e.prompt?.id||"running"!==e.status)&&(N.current=null,v(null)),j.current=e,m(e),y("error"!==e.status||e.message?null:a("accountLoginFailed")),"completed"===e.status&&A())});try{await n.start(t.loginId,e)}catch(e){if(j.current?.loginId!==t.loginId||"running"!==j.current.status)return;z(),m(null),y(e instanceof Error?e.message:a("accountLoginFailed"))}}async function R(e,t){let s=j.current;if(!k.current||!s||"running"!==s.status||s.prompt?.id!==e||N.current)return;let r={loginId:s.loginId,promptId:e};N.current=r,v(e),y(null);try{await n.respond(s.loginId,e,t)}catch(t){j.current?.loginId===s.loginId&&j.current.prompt?.id===e&&y(t instanceof Error?t.message:a("accountLoginFailed"))}finally{N.current===r&&(N.current=null,v(null))}}return(0,r.useEffect)(()=>{M.current=t},[t]),(0,r.useEffect)(()=>()=>{S.current+=1;let e=j.current;j.current=null,C.current?.(),e?.status==="running"&&n.cancel(e.loginId).catch(()=>void 0)},[n]),(0,r.useEffect)(()=>{k.current=e;let t=j.current;if(e||t?.status!=="running")return;j.current=null,N.current=null,C.current?.(),C.current=null,n.cancel(t.loginId).catch(()=>void 0);let s=S.current;queueMicrotask(()=>{S.current===s&&(m(null),v(null),y(a("accountDisconnected")))})},[e,n,a]),{open:l,providers:d,state:u,loading:p||g,submitting:null!==b&&b===u?.prompt?.id,error:w,show:function(e){if(E(),m(null),y(null),v(null),x(!1),o(!0),!k.current){h(!1),y(a("accountConnectionNotReady"));return}h(!0);let t=++S.current;n.list().then(s=>{S.current===t&&(c(s),e&&s.some(t=>t.provider===e&&!t.conflict)&&$(e))}).catch(e=>{S.current===t&&y(e instanceof Error?e.message:a("accountLoginFailed"))}).finally(()=>{S.current===t&&h(!1)})},close:E,start:$,respond:R,finish:A,async logout(e){if(!k.current)throw Error(a("accountConnectionNotReady"));await n.logout(e)},async copy(e){try{await iv(e),i.success(a("accountCopied"))}catch{i.error(a("accountCopyFailed"))}},openUrl:ib}}(t,async(e,t)=>{await o(),t()&&S(e)}),T=function(e,t,s,n){let[a,i]=(0,r.useState)(()=>{let t=e.findIndex(e=>e.models.length>0);return t<0?null:{providerIndex:t,modelIndex:0}}),[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)(""),[u,m]=(0,r.useState)(()=>e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),p=(0,r.useRef)(0),h=(0,r.useRef)(new Map(e.flatMap((e,t)=>e.models.map((s,n)=>[`${t}:${n}`,{provider:e.provider,modelId:s.modelId}])))),[g,x]=(0,r.useState)({}),[f,b]=(0,r.useState)(null),[v,w]=(0,r.useState)(!1),y=(0,r.useRef)(e);function k(e){x(t=>Object.fromEntries(Object.entries(t).filter(([t])=>!e.includes(t))))}function j(e,s=u){let n=[];e.forEach((e,t)=>{e.models.forEach((r,a)=>{let i=h.current.get(s[t][a]),l={provider:e.provider.trim(),modelId:r.modelId.trim()};i&&(i.provider!==l.provider||i.modelId!==l.modelId)&&n.push({from:i,to:l})})}),t(e,n)}function N(){b(null),w(!1)}return(0,r.useEffect)(()=>{y.current=e},[e]),(0,r.useEffect)(()=>{queueMicrotask(()=>{let e=y.current;h.current=new Map(e.flatMap((e,t)=>e.models.map((s,n)=>[`${t}:${n}`,{provider:e.provider,modelId:s.modelId}]))),x({}),m(e.map((e,t)=>e.models.map((e,s)=>`${t}:${s}`))),i(t=>{if(t&&e[t.providerIndex]?.models[t.modelIndex])return t;let s=e.findIndex(e=>e.models.length);return s<0?null:{providerIndex:s,modelIndex:0}})})},[n]),(0,r.useEffect)(()=>{let e=Object.values(g);s({dirty:e.some(e=>e.dirty),invalid:e.some(e=>e.invalid)})},[g,s]),{selection:a,mobileDetail:l,query:d,setQuery:c,modelKeys:u,serviceIndex:f,newService:v,openService:e=>{b(e),w(null===e)},closeService:N,applyService:t=>{v?(j([...e,t],[...u,[]]),m(e=>[...e,[]])):j(e.map((e,s)=>s===f?t:e)),N()},deleteService:()=>{if(null===f)return;k(u[f]);let t=e.filter((e,t)=>t!==f);j(t,u.filter((e,t)=>t!==f)),m(e=>e.filter((e,t)=>t!==f)),i(e=>{if(!e||e.providerIndex===f){let e=t.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.providerIndex>f?{...e,providerIndex:e.providerIndex-1}:e}),o(!1),N()},addModel:t=>{let s=e[t],n=`new-${++p.current}`;j(e.map((e,s)=>s===t?{...e,models:[...e.models,{modelId:"",name:"",api:null,baseUrl:null,reasoning:!1,thinkingLevels:[{level:"off",providerValue:null}],input:["text"],contextWindow:128e3,maxTokens:16384,cost:null,headers:{},compat:null}]}:e),u.map((e,s)=>s===t?[...e,n]:e)),m(e=>e.map((e,s)=>s===t?[...e,n]:e)),i({providerIndex:t,modelIndex:s.models.length}),c(""),o(!0)},selectModel:(e,t)=>{i({providerIndex:e,modelIndex:t}),o(!0)},backToList:()=>{o(!1),c("")},updateModel:function(t,s,n){j(e.map((e,r)=>r===t?{...e,models:e.models.map((e,t)=>t===s?n:e)}:e))},deleteModel:(t,s)=>{k([u[t][s]]);let n=e.map((e,n)=>n===t?{...e,models:e.models.filter((e,t)=>t!==s)}:e);j(n,u.map((e,n)=>n===t?e.filter((e,t)=>t!==s):e)),m(e=>e.map((e,n)=>n===t?e.filter((e,t)=>t!==s):e)),i(e=>{if(!e||e.providerIndex!==t)return e;if(e.modelIndex===s){if(n[t].models.length)return{providerIndex:t,modelIndex:Math.min(s,n[t].models.length-1)};let e=n.findIndex(e=>e.models.length);return e<0?null:{providerIndex:e,modelIndex:0}}return e.modelIndex>s?{...e,modelIndex:e.modelIndex-1}:e}),o(!1)},updateInputState:(e,t)=>x(s=>({...s,[e]:t}))}}(s,p,g,m),{selection:P,mobileDetail:D,query:O,setQuery:L,modelKeys:F,serviceIndex:_,newService:B}=T,q=(0,r.useRef)(new Map),W=(0,r.useRef)(new Map),[Y,V]=(0,r.useState)(!1),[K,H]=(0,r.useState)("off"),G=i.find(e=>e.provider===k?.provider&&e.modelId===k?.modelId)??(s.some(e=>e.models.length)?void 0:i[0]),J=a.find(e=>e.provider===G?.provider),X=J?.models.find(e=>e.modelId===G?.modelId),Z=!!G,et=!Z&&P?s[P.providerIndex]:null,es=!Z&&P?et?.models[P.modelIndex]:null,en=Z?M:D&&!!es,ea=Z?X?.name??G?.modelId:es?.name||es?.modelId||b("modelUnnamed"),ei=G?.provider||et?.provider||b("providerUnnamed"),el=a.find(e=>e.provider===I),eo=[...new Set([...s.map(e=>e.provider),...a.map(e=>e.provider),...i.map(e=>e.provider)])],ed=e=>`account:${e.provider}:${e.modelId}`,ec=new Set(i.map(ed)),em=new Set([...A].filter(e=>ec.has(e)));G&&em.add(ed(G)),(em.size!==A.size||G&&!A.has(ed(G)))&&$(em);let[ep,eh]=(0,r.useState)(()=>new Set),eg=P?F[P.providerIndex]?.[P.modelIndex]:void 0,ex=new Set(F.flat()),ef=new Set([...ep].filter(e=>ex.has(e)));eg&&ef.add(eg),(ef.size!==ep.size||eg&&!ep.has(eg))&&eh(ef);let eb=Z?d.find(e=>e.provider===G?.provider&&e.modelId===G.modelId):et&&es&&c.some(e=>e.provider===et.provider&&e.models.some(e=>e.modelId===es.modelId))?d.find(e=>e.provider===et.provider&&e.modelId===es.modelId):void 0;async function ev(){if(G){await v({title:b("accountRemoveTitle"),description:b("accountRemoveDescription",{name:ea})})&&(l(i.filter(e=>e!==G)),T.updateInputState(ed(G),{dirty:!1,invalid:!1}),j(null),z(!1));return}P&&es&&await v({title:b("modelDeleteTitle"),description:b("modelDeleteDescription",{name:es.name||es.modelId||b("modelUnnamed")})})&&T.deleteModel(P.providerIndex,P.modelIndex)}async function ew(e){if(await v({title:b("accountLogoutTitle"),description:b("accountLogoutDescription",{name:a.find(t=>t.provider===e)?.name??e}),confirmLabel:b("accountLogout")}))try{await R.logout(e),await o()}catch(e){y.error(e instanceof Error?e.message:b("accountLogoutFailed"))}}return(0,n.jsxs)("section",{className:"@container/models h-full min-h-0 overflow-hidden bg-card",children:[(0,n.jsxs)("div",{className:"grid h-full min-h-0 grid-cols-1 @[48rem]/models:grid-cols-[15rem_minmax(0,1fr)]",children:[(0,n.jsxs)("aside",{"aria-label":b("providerList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/models:flex @[48rem]/models:border-r",en?"hidden":"flex"),children:[(0,n.jsx)("div",{className:"shrink-0 p-3",children:(0,n.jsx)(eu.p,{value:O,"aria-label":b("modelSearch"),placeholder:b("modelSearch"),onChange:e=>L(e.target.value)})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:[eo.map(e=>{let t=s.findIndex(t=>t.provider===e);return(0,n.jsx)(iM,{providerId:e,custom:s[t],account:a.find(t=>t.provider===e),accountModels:i.filter(t=>t.provider===e),query:O,modelKeys:F[t]??[],selectedCustomIndex:Z||P?.providerIndex!==t?null:P.modelIndex,selectedAccountId:G?.provider===e?G.modelId:null,presets:u,onSelectCustom:e=>{j(null),T.selectModel(t,e)},onSelectAccount:t=>{j({provider:e,modelId:t}),z(!0),$(s=>new Set([...s,ed({provider:e,modelId:t})]))},onCustomSettings:()=>T.openService(t),onAddCustom:()=>{j(null),T.addModel(t)},onAddAccount:()=>{let t;return t=a.find(t=>t.provider===e),void(t?.loggedIn?S(e):R.show(e))},onLogin:()=>R.show(e),onLogout:()=>void ew(e),onGroupRef:e=>{t<0||(e?q.current.set(t,e):q.current.delete(t))},onRowRef:(e,t)=>{t?W.current.set(e,t):W.current.delete(e)}},e)}),eo.length?null:(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:b("providerEmpty")})]}),(0,n.jsxs)("div",{className:"flex shrink-0 gap-2 border-t p-3",children:[(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>T.openService(null),children:[(0,n.jsx)(U.A,{}),b("accountCustomApi")]}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>R.show(),children:[(0,n.jsx)(a2.A,{}),b("accountLogin")]})]})]}),(0,n.jsx)("section",{"aria-label":b("modelsHeading"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/models:flex",en?"flex":"hidden"),children:Z||es&&P?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2 @[48rem]/models:hidden",children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":b("backModelList"),onClick:function(){if(G){z(!1),window.requestAnimationFrame(()=>{let e=W.current.get(ed(G));e?.scrollIntoView({block:"nearest"}),e?.focus({preventScroll:!0})});return}T.backToList(),window.requestAnimationFrame(()=>{if(!P)return;let e=F[P.providerIndex]?.[P.modelIndex];q.current.get(P.providerIndex)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.scrollIntoView({block:"nearest"}),W.current.get(e)?.focus({preventScroll:!0})})},children:(0,n.jsx)(E.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",title:J?.name??ei,children:J?.name??ei}),(0,n.jsx)(iS,{name:ei,hasAccount:a.some(e=>e.provider===ei)||i.some(e=>e.provider===ei),loggedIn:a.find(e=>e.provider===ei)?.loggedIn??!1,hasCustom:s.some(e=>e.provider===ei),onCustomSettings:()=>T.openService(s.findIndex(e=>e.provider===ei)),onLogin:()=>R.show(ei),onLogout:()=>void ew(ei)})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 @[48rem]/models:p-6",children:[(0,n.jsxs)("div",{className:"mb-5 flex flex-wrap items-center justify-between gap-2",children:[(0,n.jsx)("h3",{className:"min-w-0 break-all text-lg font-semibold",children:ea}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:!eb,title:eb?void 0:b("saveBeforePreset"),onClick:()=>{H(eb?.thinkingLevels[0]??"off"),V(!0)},children:[(0,n.jsx)(a5.A,{}),b("addModelPreset")]}),(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm",className:"text-destructive hover:text-destructive","aria-label":Z?`${b("accountRemove")} ${ea}`:b("modelDeleteNamed",{name:ea}),onClick:ev,children:(0,n.jsx)(ee.A,{})})}),(0,n.jsx)(tU.ZI,{children:b(Z?"accountRemove":"modelDelete")})]})]})]}),i.map(e=>{let t=ed(e);if(!em.has(t))return null;let s=a.find(t=>t.provider===e.provider);return(0,n.jsx)("div",{hidden:!Z||G!==e,children:(0,n.jsx)(iI,{account:s,model:s?.models.find(t=>t.modelId===e.modelId),overrides:e.overrides,onChange:t=>l(i.map(s=>s===e?{...e,overrides:t}:s)),onInputState:e=>T.updateInputState(t,e)})},`${t}:${m}`)}),s.flatMap((t,s)=>t.models.map((r,a)=>{let i=!Z&&P?.providerIndex===s&&P.modelIndex===a,l=F[s]?.[a];return ef.has(l)?(0,n.jsx)("div",{hidden:!i,children:(0,n.jsx)(it,{biz:e,provider:t,model:r,onChange:e=>T.updateModel(s,a,e),onInputState:e=>T.updateInputState(l,e)})},`${l}:${m}`):null}))]})]}):(0,n.jsxs)("div",{className:"flex flex-col items-center gap-3 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(eD.A,{className:"size-6"}),b("selectModelToEdit")]})})]}),(0,n.jsx)(ik,{open:R.open,connected:t,providers:R.providers,state:R.state,loading:R.loading,submitting:R.submitting,error:R.error,onClose:R.close,onStart:R.start,onRespond:R.respond,onCopy:R.copy,onOpenUrl:R.openUrl,onRetry:()=>R.state?.status==="completed"?void R.finish():R.show()}),el?(0,n.jsx)(ij,{account:el,existingIds:[...i.filter(e=>e.provider===el.provider).map(e=>e.modelId),...s.filter(e=>e.provider===el.provider).flatMap(e=>e.models.map(e=>e.modelId))],onAdd:function(e){if(!el)return;let t=e.filter(e=>!i.some(t=>t.provider===el.provider&&t.modelId===e)&&!s.some(t=>t.provider===el.provider&&t.models.some(t=>t.modelId===e))).map(e=>({provider:el.provider,modelId:e,overrides:{}}));l([...i,...t]),S(null)},onClose:()=>S(null)},el.provider):null,B||null!==_?(0,n.jsx)(ii,{provider:B?{provider:"",name:null,baseUrl:null,api:"openai-responses",apiKey:null,authHeader:null,headers:{},models:[]}:s[_],existingIds:s.filter((e,t)=>B||t!==_).map(e=>e.provider),isNew:B,onApply:T.applyService,onDelete:T.deleteService,onClose:T.closeService,onDirtyChange:x}):null,(0,n.jsx)(ej.YV,{open:Y,onOpenChange:V,children:(0,n.jsxs)(ej.hA,{children:[(0,n.jsx)(ej.Hl,{className:"border-b px-4 py-4 pr-12",children:(0,n.jsx)(ej.YM,{children:b("addModelPreset")})}),(0,n.jsx)(ej._Y,{children:(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(aU,{label:b("thinkingLevel"),children:(0,n.jsx)(aK,{value:K,allowEmpty:!1,ariaLabel:b("presetThinkingNew"),options:(eb?.thinkingLevels??[]).map(e=>({value:e,label:b(iz[e])})),onChange:e=>H(e)})})})}),(0,n.jsxs)(ej.vu,{children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",onClick:()=>V(!1),children:b("cancel",{ns:"common"})}),(0,n.jsx)(N.$,{type:"button",onClick:function(){eb&&(u.some(e=>e.provider===eb.provider&&e.modelId===eb.modelId&&e.thinkingLevel===K)||h([...u,{provider:eb.provider,modelId:eb.modelId,thinkingLevel:K,color:aO(u)}]),V(!1))},disabled:!eb,children:b("presetAdd")})]})]})}),w]})}let iA={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function i$(e,t){return JSON.stringify([e,t])}function iR(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function iT({biz:e,presets:t,onDirtyChange:s}){let{t:a}=(0,f.Bd)("settings"),i=function(e,t){let{t:s}=(0,f.Bd)("settings"),n=(0,Q.G)(),{confirm:a,dialog:i}=nR(),[l,o]=(0,r.useState)([]),[d,c]=(0,r.useState)(""),[u,m]=(0,r.useState)([]),[p,h]=(0,r.useState)(null),[g,x]=(0,r.useState)(!1),[b,v]=(0,r.useState)(!0),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[C,S]=(0,r.useState)(null),[M,z]=(0,r.useState)(null),[E,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[T,P]=(0,r.useState)(0),D=C===d&&null===E&&!w&&!k,O=(0,r.useRef)(!1),L=(0,r.useRef)(""),F=(0,r.useRef)(0),_=(0,r.useCallback)(e=>{O.current=e,t?.(e)},[t]);function B(e){m(e.models),x(null!==e.default),h(e.default??(e.models[0]?{provider:e.models[0].provider,modelId:e.models[0].modelId,thinkingLevel:e.models[0].thinkingLevels[0]}:null))}async function q(e){return!N&&(e===d||(!O.current||!!await a({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}))&&(F.current+=1,j(!0),c(e),!0))}async function W(){if(d&&D&&!w&&!k&&!N&&(!g||p)){I(!0);try{await e.replaceProjectDefault({cwd:d,default:g?p:null}),ak({cwd:d,default:g?p:null,models:u}),_(!1),n.success(g?s("projectDefaultSaved"):s("projectDefaultGlobalSaved"))}catch(e){n.error(e instanceof Error?e.message:s("projectDefaultSaveFailed"))}finally{I(!1)}}}return(0,r.useEffect)(()=>{let t=!1,n=r3.safeParse((au(),aa)),r=n.success?n.data.directories:null;return queueMicrotask(()=>{!t&&(z(null),v(!r),r&&(o(r),c(e=>e&&r.some(t=>t.cwd===e)?e:r[0]?.cwd??"")))}),(async()=>{try{let s=await e.listDirectories();if(t)return;o(s.directories),c(e=>e&&s.directories.some(t=>t.cwd===e)?e:s.directories[0]?.cwd??"")}catch(e){if(!t&&!r){let t=e instanceof Error?e.message:s("projectDirectoriesFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目目录失败",{message:t}),z(t)}}finally{t||v(!1)}})(),()=>{t=!0}},[e,s,$]),(0,r.useEffect)(()=>{let t=!1,n=++F.current;function r(){return!t&&n===F.current}let a=L.current!==d;if(L.current=d,a&&_(!1),!d)return queueMicrotask(()=>{r()&&(m([]),h(null),x(!1),S(null),A(null),y(!1),j(!1))}),()=>{t=!0};let i=(aw(),ab.get(av(d))??null);return queueMicrotask(()=>{r()&&(A(null),!O.current&&i&&(B(i),S(d)),y(!i&&!O.current),j(!!i||O.current))}),(async()=>{try{let t=await e.getProjectDefault(d);if(!r())return;O.current||B(t),S(d)}catch(e){if(r()){let t=e instanceof Error?e.message:s("projectDefaultFailed");console.warn("[Pi Desk][ProjectModelDefault] 读取项目模型配置失败",{cwd:d,message:t}),A(t)}}finally{r()&&(y(!1),j(!1))}})(),()=>{t=!0}},[e,d,s,_,T]),{directories:l,cwd:d,loadedCwd:C,models:u,selection:p,fixed:g,directoriesLoading:b,projectLoading:w,projectRefreshing:k,saving:N,projectReady:D,directoriesError:M,projectError:E,dialog:i,selectProject:q,changeFixed:function(e){D&&!N&&(_(!0),x(e))},selectModel:function(e){D&&!N&&(_(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevels[0]}))},selectThinking:function(e){if(!D||N)return;let t=u.find(e=>e.provider===p?.provider&&e.modelId===p.modelId),s=t?.thinkingLevels.find(t=>t===e);p&&s&&(_(!0),h({...p,thinkingLevel:s}))},applyPreset:function(e){D&&!N&&(_(!0),h({provider:e.provider,modelId:e.modelId,thinkingLevel:e.thinkingLevel}))},retryDirectories:function(){R(e=>e+1)},retryProject:function(){F.current+=1,j(!0),P(e=>e+1)},save:W}}(e,s),[l,o]=(0,r.useState)(""),[d,c]=(0,r.useState)(!1),u=i.models.find(e=>e.provider===i.selection?.provider&&e.modelId===i.selection.modelId),m=t.filter(e=>i.models.some(t=>t.provider===e.provider&&t.modelId===e.modelId&&t.thinkingLevels.includes(e.thinkingLevel))),p=i.directories.filter(e=>e.cwd.toLocaleLowerCase().includes(l.trim().toLocaleLowerCase())),h=i.models.map(e=>({value:i$(e.provider,e.modelId),label:e.name||e.modelId,description:e.provider})),g=!i.projectReady||i.saving,x=i.loadedCwd??i.cwd;async function v(e){await i.selectProject(e)&&c(!0)}return(0,n.jsxs)("section",{className:"@container/project-default h-full min-h-0 overflow-hidden bg-card",children:[(0,n.jsxs)("div",{className:"grid h-full min-h-0 grid-cols-1 @[48rem]/project-default:grid-cols-[18rem_minmax(0,1fr)]",children:[(0,n.jsxs)("aside",{"aria-label":a("projectList"),className:(0,C.cn)("min-h-0 min-w-0 flex-col bg-sidebar @[48rem]/project-default:flex @[48rem]/project-default:border-r",d&&i.cwd?"hidden":"flex"),children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-3 p-3",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold",children:a("projectList")}),(0,n.jsx)(eu.p,{value:l,"aria-label":a("projectSearch"),placeholder:a("projectSearch"),onChange:e=>o(e.target.value)})]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-2 pb-3",children:i.directoriesLoading&&0===i.directories.length?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 px-3 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{"aria-hidden":"true",className:"size-4 animate-spin"}),a("projectLoading")]}):i.directoriesError?(0,n.jsxs)("div",{className:"space-y-3 px-3 py-6 text-sm",children:[(0,n.jsx)("p",{role:"alert",className:"break-words text-destructive",children:i.directoriesError}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:i.retryDirectories,children:a("retry",{ns:"common"})})]}):0===p.length?(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:a("projectEmpty")}):(0,n.jsx)("div",{className:"space-y-1",children:p.map(e=>{let t=e.cwd===i.cwd;return(0,n.jsx)(N.$,{type:"button",variant:"ghost","aria-current":t?"true":void 0,disabled:i.saving,className:(0,C.cn)("h-auto min-h-14 w-full items-start justify-start gap-2 whitespace-normal px-3 py-2 text-left",t&&"bg-accent text-accent-foreground ring-1 ring-border ring-inset"),onClick:()=>{v(e.cwd)},children:(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex items-start gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 break-all text-sm font-medium",children:iR(e.cwd)}),t?(0,n.jsx)(em.A,{"aria-hidden":"true",className:"mt-0.5 size-4 shrink-0"}):null]}),(0,n.jsx)("span",{className:"mt-1 block break-all text-xs font-normal text-muted-foreground",children:e.cwd}),(0,n.jsx)("span",{className:"mt-1 block text-xs font-normal text-muted-foreground",children:a("projectSessionCount",{count:e.sessionCount})})]})},e.cwd)})})})]}),(0,n.jsx)("section",{"aria-label":a("projectDefaultSource"),className:(0,C.cn)("min-h-0 min-w-0 flex-col @[48rem]/project-default:flex",d&&i.cwd?"flex":"hidden"),children:i.cwd?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-2 @[48rem]/project-default:hidden",children:(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(!1),children:[(0,n.jsx)(E.A,{"aria-hidden":"true"}),a("backProjectList")]})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 @[48rem]/project-default:p-6",children:(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-6",children:[(0,n.jsxs)("header",{className:"space-y-1",children:[(0,n.jsxs)("h3",{className:"flex items-center gap-2 text-lg font-semibold",children:[(0,n.jsx)("span",{className:"min-w-0 break-all",children:iR(x)}),(0,n.jsx)("span",{className:"inline-flex size-4 shrink-0",children:!i.projectReady&&!i.projectError&&(0,n.jsx)(b.A,{role:"status","aria-label":a("projectLoading"),className:"size-4 animate-spin text-muted-foreground"})})]}),(0,n.jsx)("p",{className:"break-all text-sm text-muted-foreground",children:x})]}),i.projectError?(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,n.jsx)("p",{role:"alert",className:"min-w-0 flex-1 break-words text-destructive",children:i.projectError}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:i.retryProject,disabled:i.projectLoading||i.projectRefreshing,children:a("retry",{ns:"common"})})]}):null,null!==i.loadedCwd?(0,n.jsxs)("fieldset",{disabled:g,className:"min-w-0 space-y-6",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:a("projectDefaultSource")}),(0,n.jsx)(nJ,{label:a("projectDefaultSource"),value:i.fixed?"fixed":"global",layout:"segmented",disabled:g,options:[{value:"global",label:a("projectFollowGlobal")},{value:"fixed",label:a("projectFixed")}],onChange:e=>i.changeFixed("fixed"===e)})]}),i.fixed?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)(aU,{label:a("projectDefaultModel"),children:(0,n.jsx)(nF.b,{value:i.selection?i$(i.selection.provider,i.selection.modelId):"",options:h,ariaLabel:a("projectDefaultModel"),searchPlaceholder:a("modelSearch"),disabled:g||0===i.models.length,onChange:function(e){let t=i.models.find(t=>i$(t.provider,t.modelId)===e);t&&i.selectModel(t)}})}),(0,n.jsx)(aU,{label:a("thinkingLevel"),children:(0,n.jsx)(aK,{value:i.selection?.thinkingLevel??"",options:(u?.thinkingLevels??[]).map(e=>({value:e,label:a(iA[e])})),ariaLabel:a("projectDefaultThinking"),allowEmpty:!1,onChange:i.selectThinking})}),m.length>0?(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:a("fromPreset")}),(0,n.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.map((e,t)=>{let s=i.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId);return(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"xs",disabled:g,className:"h-auto min-h-7 max-w-full whitespace-normal text-left",onClick:()=>i.applyPreset(e),children:[(0,n.jsx)("span",{className:"size-2 shrink-0 rounded-full bg-current",style:e.color?{color:e.color}:void 0}),(0,n.jsxs)("span",{className:"min-w-0 break-all",children:[s?.name||e.modelId," \xb7"," ",a(iA[e.thinkingLevel])]})]},`${e.provider}/${e.modelId}/${e.thinkingLevel}/${t}`)})})]}):null]}):null]}):null]})}),(0,n.jsx)("div",{className:"shrink-0 border-t px-4 py-3 @[48rem]/project-default:px-6",children:(0,n.jsxs)(N.$,{type:"button",onClick:i.save,disabled:!i.projectReady||g||i.fixed&&!i.selection,children:[i.saving?(0,n.jsx)(b.A,{"aria-hidden":"true",className:"animate-spin"}):(0,n.jsx)(X.A,{"aria-hidden":"true"}),i.saving?a("savingModels"):a("saveProjectDefault")]})})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2 p-6 text-sm text-muted-foreground",children:[(0,n.jsx)(eR.A,{"aria-hidden":"true",className:"size-6 shrink-0"}),a("selectProjectToConfigure")]})})]}),i.dialog]})}let iP=[{value:"providers",label:"modelProviders"},{value:"presets",label:"modelPresets"},{value:"project-default",label:"projectDefault"}];function iD({loading:e,error:t,onRetry:s}){let{t:r}=(0,f.Bd)("settings");return(0,n.jsx)("div",{className:"flex min-h-72 flex-col items-center justify-center gap-3 p-5 text-sm text-muted-foreground",children:e?(0,n.jsxs)("span",{className:"flex items-center gap-2",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"})," ",r("loadingModels")]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-destructive",children:t??r("modelsUnavailable")}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:s,children:r("retry",{ns:"common"})})]})})}function iO({onBeforeLeaveChange:e,connectionReady:t=!1,initialTab:s}){let{t:a}=(0,f.Bd)("settings"),{locale:i,timeZone:l}=(0,eG.i)(),[o,d]=(0,r.useState)(!1),{biz:c,tab:u,settings:m,providers:p,presets:h,accountModels:g,changeAccountModels:x,refreshAccounts:v,resetVersion:w,formDirty:y,formInvalid:k,serviceDirty:j,nativeOpen:I,nativeText:S,nativeError:M,nativeDirty:z,setNativeText:E,openNative:A,closeNative:$,saveNative:R,revertConfig:T,setInputState:P,setServiceDirty:D,loading:O,saving:L,refreshing:F,catalogUpdatedAt:_,loadError:B,dialog:q,setProjectDefaultDirty:W,changeProviders:Y,changePresets:U,selectTab:K,retry:H,refreshCatalog:G,saveConfig:J}=function(e,t){let{t:s}=(0,f.Bd)("settings"),{clientId:n}=(0,er.gM)(),a=(0,Q.G)(),{confirm:i,dialog:l}=nR(),o=(0,r.useMemo)(()=>{let e;return e=null,{parseNativeConfig(e){let t=JSON.parse(e);return rE.parse(t)},getSettings:()=>(e||(e=ec(n,"/api/model-settings/get",{},rq).finally(()=>{e=null})),e),previewSettings:e=>ec(n,"/api/model-settings/preview",aj(e),rH),async replaceSettings(e){await ec(n,"/api/model-settings/replace",aj(e),rK)},listCatalog:e=>ec(n,"/api/model-catalog/list",rG.parse(e),rZ),async listDirectories(){let e=await ec(n,"/api/pi/directories/list",{forceRefresh:!1},r3);return ap(e),e},async getProjectDefault(e){let t=await ec(n,"/api/project-model-default/get",{cwd:e},r0);return ak(t),t},async replaceProjectDefault(e){await ec(n,"/api/project-model-default/replace",r1.parse(e),r2)}}},[n]),[d,c]=(0,r.useState)(()=>t??aM(aS,aI,"providers"));(0,r.useEffect)(()=>{az(aS,d)},[d]);let[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)([]),[g,x]=(0,r.useState)([]),[b,v]=(0,r.useState)([]),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,I]=(0,r.useState)(!1),[C,S]=(0,r.useState)(!1),[M,z]=(0,r.useState)(!0),[E,A]=(0,r.useState)(!1),[$,R]=(0,r.useState)(!1),[T,P]=(0,r.useState)(null),[D,O]=(0,r.useState)(null),[L,F]=(0,r.useState)(0),[_,B]=(0,r.useState)(0),[q,W]=(0,r.useState)({dirty:!1,invalid:!1}),[Y,U]=(0,r.useState)(!1),[V,K]=(0,r.useState)(!1),[H,G]=(0,r.useState)(""),[J,X]=(0,r.useState)(null),Z=(0,r.useRef)(!1),ee=(0,r.useRef)([]),et=u?JSON.stringify(u.nativeConfig,null,2):"",es=V&&H!==et,en=k||N||w||q.dirty,ea=en||C||Y||es;(0,r.useEffect)(()=>(e(ea?()=>!E&&i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}):null),()=>e(null)),[e,ea,E,i,s]),(0,r.useEffect)(()=>{if(!ea)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[ea]);let ei=(0,r.useCallback)(e=>{ee.current=[],m(e),h(structuredClone(e.providers)),x(structuredClone(e.presets)),v(structuredClone(e.accountModels)),y(!1),j(!1),I(!1),W({dirty:!1,invalid:!1}),B(e=>e+1)},[]);async function el(){R(!0);try{let e=await o.listCatalog({query:"",refresh:!0,page:{index:1,size:1}});P(e.updatedAt),await ed(),a.success("cached"===e.refreshResult?s("catalogCached"):"partial"===e.refreshResult?s("catalogPartial"):"unchanged"===e.refreshResult?s("catalogUnchanged"):s("catalogUpdated"))}catch(e){a.error(e instanceof Error?e.message:s("catalogRefreshFailed"))}finally{R(!1)}}async function eo(){if(!Z.current&&!q.invalid&&!Y&&!V){if(!u||!en)return void a.success(s("modelsNoChanges"));Z.current=!0,A(!0);try{let e=new Set([...p.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...b.map(e=>`${e.provider}\u0000${e.modelId}`)]),t=new Set([...u.providers.flatMap(e=>e.models.map(t=>`${e.provider}\u0000${t.modelId}`)),...u.accountModels.map(e=>`${e.provider}\u0000${e.modelId}`)]),n=g.filter(s=>{let n=`${s.provider}\u0000${s.modelId}`;return!t.has(n)||e.has(n)}),l=g.length-n.length,d={...k||q.dirty?{providers:p}:{},...w?{accountModels:b}:{},...N||l>0?{presets:n}:{},...ee.current.length?{modelReplacements:ee.current}:{}},{projectDefaults:c}=ee.current.length?await o.previewSettings(d):{projectDefaults:[]};if(c.length>0){let e=[s("replaceProjectDefaultsDescription"),...l>0?[s("removeInvalidPresets",{count:l})]:[]].join(" ");if(!await i({title:s("replaceProjectDefaultsTitle"),description:e,content:(0,r.createElement)(ry,{projectDefaults:c}),confirmLabel:s("confirmAndSaveModels"),confirmVariant:"default"}))return}else if(l>0&&!await i({title:s("removeInvalidPresetsTitle"),description:s("removeInvalidPresets",{count:l}),confirmLabel:s("removeAndSave")}))return;await o.replaceSettings(d),ei(await o.getSettings()),j(!1),I(!1),a.success(s("modelSaved"))}catch(e){a.error(e instanceof Error?e.message:s("modelSaveFailed"))}finally{Z.current=!1,A(!1)}}}async function ed(){let e=await o.getSettings();return m(t=>t?{...t,accounts:e.accounts,models:e.models,nativeConfig:e.nativeConfig}:e),e}async function eu(){!u||Z.current||Y||await i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")})&&ei(u)}async function em(){Z.current||(!es||await i({title:s("discardNativeTitle"),description:s("discardNativeDescription"),confirmLabel:s("discardModelConfirm")}))&&K(!1)}async function ep(){if(!Z.current&&V&&es){Z.current=!0,A(!0),X(null);try{let e=o.parseNativeConfig(H);await o.replaceSettings({nativeConfig:e}),ei(await o.getSettings()),K(!1),a.success(s("modelSaved"))}catch(t){let e=t instanceof Error?t.message:s("modelSaveFailed");console.warn("[Pi Desk][ModelSettings] 保存 Pi 配置失败",{message:e}),X(e)}finally{Z.current=!1,A(!1)}}}return(0,r.useEffect)(()=>{let e=!1;return queueMicrotask(()=>{e||(z(!0),O(null))}),o.getSettings().then(t=>{e||ei(t)}).catch(t=>{if(e)return;let n=t instanceof Error?t.message:s("modelsLoadFailed");console.warn("[Pi Desk][ModelSettings] 读取模型配置失败",{message:n}),O(n)}).finally(()=>{e||z(!1)}),()=>{e=!0}},[o,s,L,ei]),{biz:o,tab:d,settings:u,providers:p,presets:g,accountModels:b,changeAccountModels:e=>{v(e),y(JSON.stringify(e)!==JSON.stringify(u?.accountModels))},refreshAccounts:ed,providersDirty:k,presetsDirty:N,loading:M,saving:E,refreshing:$,catalogUpdatedAt:T,loadError:D,resetVersion:_,formDirty:en,formInvalid:q.invalid,serviceDirty:Y,nativeOpen:V,nativeText:H,nativeError:J,nativeDirty:es,setNativeText:G,openNative:function(){if(u&&!Z.current){if(en||Y||C)return void a.error(s("nativeProtectDraft"));G(et),X(null),K(!0)}},closeNative:em,saveNative:ep,revertConfig:eu,setInputState:W,setServiceDirty:U,dialog:l,setProjectDefaultDirty:S,changeProviders:(e,t)=>{ee.current=t,h(e),j(JSON.stringify(e)!==JSON.stringify(u?.providers))},changePresets:e=>{x(e),I(JSON.stringify(e)!==JSON.stringify(u?.presets))},selectTab:e=>{if(e!==d&&!Z.current){if("project-default"===d&&C)return void i({title:s("discardModelTitle"),description:s("discardModelDescription"),confirmLabel:s("discardModelConfirm")}).then(t=>{t&&(S(!1),c(e))});c(e)}},retry:()=>F(e=>e+1),refreshCatalog:el,saveConfig:eo}}(e,s);return(0,n.jsxs)("div",{className:"@container/model-settings flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b p-4",children:[(0,n.jsx)(nJ,{label:a("models"),layout:"segmented",value:u,options:iP.map(e=>({...e,label:a(e.label)})),onChange:K}),(0,n.jsxs)("div",{className:"hidden gap-2 @[40rem]/model-settings:flex",children:[(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:!m||L,onClick:A,children:[(0,n.jsx)(rv.A,{}),a("nativeConfig")]}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",title:_?a("catalogUpdatedAt",{time:new Date(_).toLocaleString("en"===i?"en-US":"zh-CN",{timeZone:l,timeZoneName:"shortOffset",hourCycle:"h23"})}):a("catalogUnavailable"),onClick:G,disabled:F,children:[(0,n.jsx)(et.A,{className:(0,C.cn)(F&&"animate-spin")}),F?a("refreshingCatalog"):a("refreshCatalog")]})]}),(0,n.jsxs)(eJ.AM,{open:o,onOpenChange:d,children:[(0,n.jsx)(eJ.Wv,{render:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon-sm","aria-label":a("modelMoreActions"),className:"shrink-0 @[40rem]/model-settings:hidden",children:(0,n.jsx)(V.A,{})})}),(0,n.jsxs)(eJ.hl,{align:"end",positionerClassName:"z-[120]",className:"w-48 gap-1 p-1",children:[(0,n.jsxs)(N.$,{type:"button",variant:"ghost",className:"justify-start",disabled:!m||L,onClick:()=>{d(!1),A()},children:[(0,n.jsx)(rv.A,{}),a("nativeConfig")]}),(0,n.jsxs)(N.$,{type:"button",variant:"ghost",className:"justify-start",disabled:F,onClick:()=>{d(!1),G()},children:[(0,n.jsx)(et.A,{}),a("refreshCatalog")]})]})]})]}),(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar min-h-0 flex-1","presets"===u?"overflow-y-auto":"overflow-hidden"),children:["project-default"===u?(0,n.jsx)(iT,{biz:c,presets:m?.presets??[],onDirtyChange:W}):m?null:(0,n.jsx)(iD,{loading:O,error:B,onRetry:H}),m?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("fieldset",{disabled:L,className:(0,C.cn)("h-full min-h-0 min-w-0","providers"!==u&&"hidden"),children:(0,n.jsx)(iE,{biz:c,connectionReady:t,providers:p,accounts:m.accounts,accountModels:g,onAccountModelsChange:x,onRefreshAccounts:v,savedProviders:m.providers,savedModels:m.models,presets:h,resetVersion:w,onChange:Y,onPresetsChange:U,onInputState:P,onServiceDirtyChange:D})}),(0,n.jsx)("fieldset",{disabled:L,className:(0,C.cn)("min-w-0","presets"!==u&&"hidden"),children:(0,n.jsx)(a1,{presets:h,models:m.models,onChange:U})})]}):null]}),"project-default"!==u&&m?(0,n.jsxs)("footer",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-t bg-card px-4 py-3",children:[(0,n.jsx)("span",{className:(0,C.cn)("text-xs text-muted-foreground",k&&"text-destructive"),role:"status",children:k?a("fixModelInputs"):y?a("modelDraftPending"):a("modelDraftClean")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:L||!y||j,onClick:T,children:a("revertModels")}),(0,n.jsxs)(N.$,{type:"button",size:"sm",onClick:J,disabled:L||!y||k||j,children:[L?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(X.A,{}),L?a("savingModels"):a("saveModels")]})]})]}):null,(0,n.jsx)(aE,{open:I,text:S,error:M,saving:L,dirty:z,onChange:E,onClose:$,onSave:R}),q]})}function iL({render:e,input:t}){return e(t)}let iF=[{id:"appearance",label:"appearance",icon:sP.A},{id:"region",label:"region",icon:sD.A},{id:"habits",label:"habits",icon:sO.A},{id:"models",label:"models",icon:eT.A},{id:"mcp-settings",label:"mcpSettings",icon:eC.A},{id:"capability-modes",label:"capabilityModes",icon:eh.A},{id:"skills",label:"skills",icon:sL.A},{id:"plugins",label:"plugins",icon:eC.A},{id:"auth",label:"loginProtection",icon:es.A},{id:"about",label:"about",icon:sF.A}];function i_(e,t){return`plugin:${e}:${t}`}function iB(){let{t:e}=(0,f.Bd)("settings"),t=(0,eG.i)();return(0,n.jsxs)("section",{"aria-labelledby":"settings-about-title",className:"min-w-0 space-y-6",children:[(0,n.jsx)("h2",{id:"settings-about-title",className:"text-xl font-semibold",children:e("about")}),(0,n.jsxs)("div",{className:"flex items-center gap-3 rounded-xl bg-muted p-4",children:[(0,n.jsx)(sq.V,{size:48,className:"shrink-0"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:"Pi Desk"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:e("webDescription")})]})]}),(0,n.jsxs)("dl",{className:"divide-y border-y text-sm",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:e("version")}),(0,n.jsxs)("dd",{className:"font-mono",children:["v",s_]})]}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:e("versionUpdated")}),(0,n.jsx)("dd",{className:"tabular-nums",children:function(e,t,s,n){if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:new Intl.DateTimeFormat(t,{timeZone:s,year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(r)}(sB,"en"===t.locale?"en-US":"zh-CN",t.timeZone,e("common:unavailable"))})]})]})]})}function iq({open:e,connectionReady:t=!1,initialModelTab:s,workSessions:a,focusedCwd:i,pluginAttention:l,renderPluginManagement:o,renderMcpSettings:d,renderCapabilityModesSettings:c,renderPluginSettingsPage:u,onOpenChange:m,onBeforeReload:p}){let{t:h}=(0,f.Bd)("settings"),g=(0,J.So)(),x=(0,r.useMemo)(()=>{let e=new Map;for(let{cwd:t,projectName:s}of a){let n=t.replaceAll("\\","/").replace(/\/+$/,""),r=/^[a-zA-Z]:\//.test(n)||n.startsWith("//")?n.toLowerCase():n;e.has(r)||e.set(r,{cwd:t,projectName:s})}return[...e.values()]},[a]),b=(0,r.useMemo)(()=>g.flatMap(e=>e.contributions.flatMap(t=>"settings-page"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[g]),[v,w]=(0,r.useState)(()=>s?"models":aM(aC,aN,"appearance"));(0,r.useEffect)(()=>{e&&az(aC,v)},[v,e]);let[y,k]=(0,r.useState)(!1),[j,I]=(0,r.useState)(!1),S=(0,r.useRef)(null),M=(0,r.useRef)(!1),z=b.find(e=>i_(e.pluginName,e.descriptor.contributionName)===v),E=v.startsWith("plugin:")&&!z?"appearance":v,A=iF.find(e=>e.id===E),$=A?.icon,R=(0,r.useCallback)(async e=>{if(!M.current){M.current=!0,I(!0);try{let t=S.current;if(t&&!await t())return;S.current=null,e()}finally{M.current=!1,I(!1)}}},[]),T=(0,r.useCallback)(()=>{R(()=>m(!1))},[m,R]),P=(0,r.useCallback)(e=>{S.current=e},[]),D=e=>{e!==E&&R(()=>w(e))};return(0,n.jsx)(ej.YV,{open:e,onOpenChange:(e,t)=>{e?m(!0):"focus-out"!==t.reason&&T()},children:(0,n.jsxs)(ej.hA,{className:"h-[min(48rem,calc(100dvh-2rem))] max-w-6xl max-sm:h-dvh max-sm:max-h-dvh max-sm:w-dvw max-sm:max-w-none max-sm:rounded-none max-sm:border-0",finalFocus:!1,showCloseButton:!j,children:[(0,n.jsx)(ej.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsx)(ej.YM,{children:h("title")})}),(0,n.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col sm:flex-row",children:[(0,n.jsx)("div",{className:"shrink-0 border-b bg-sidebar p-3 sm:hidden",children:(0,n.jsxs)(ea.l6,{value:E,disabled:j,onValueChange:e=>{if("string"!=typeof e)return;let t=iF.find(t=>t.id===e);if(t)return void D(t.id);let s=b.find(t=>i_(t.pluginName,t.descriptor.contributionName)===e);s&&D(i_(s.pluginName,s.descriptor.contributionName))},children:[(0,n.jsx)(ea.bq,{"aria-label":h("category"),className:"w-full",children:(0,n.jsx)(ea.yv,{children:z?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(e_,{icon:z.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:z.descriptor.label})]}):A&&$?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)($,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:h(A.label)})]}):null})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",align:"start",children:[iF.map(e=>{let t=e.icon;return(0,n.jsxs)(ea.eb,{value:e.id,children:[(0,n.jsxs)("span",{className:"relative shrink-0",children:[(0,n.jsx)(t,{className:"size-4"}),"plugins"===e.id&&l?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute -right-1 -top-1 size-1.5 rounded-full","error"===l?"bg-destructive":"bg-primary")}):null]}),(0,n.jsx)("span",{children:h(e.label)})]},e.id)}),b.length>0?(0,n.jsxs)(ea.s3,{children:[(0,n.jsx)(ea.TR,{children:h("pluginSettings")}),b.map(e=>{let t=i_(e.pluginName,e.descriptor.contributionName);return(0,n.jsxs)(ea.eb,{value:t,children:[(0,n.jsx)(e_,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{children:e.descriptor.label})]},t)})]}):null]})]})}),(0,n.jsxs)("nav",{"aria-label":h("category"),className:"pi-desk-chat-scrollbar hidden w-48 shrink-0 space-y-4 overflow-auto border-r bg-sidebar p-3 sm:block",children:[(0,n.jsx)("div",{className:"grid grid-cols-1 gap-1",children:iF.map(e=>{let t=e.icon,s=e.id===E;return(0,n.jsxs)(N.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,"aria-label":`${h("category")}:${h(e.label)}`,onClick:()=>D(e.id),className:(0,C.cn)("min-w-0 justify-start",s?"bg-accent text-accent-foreground hover:bg-accent":"text-muted-foreground"),children:[(0,n.jsxs)("span",{className:"relative shrink-0",children:[(0,n.jsx)(t,{className:"size-4"}),"plugins"===e.id&&l?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute -right-1 -top-1 size-1.5 rounded-full","error"===l?"bg-destructive":"bg-primary")}):null]}),(0,n.jsx)("span",{className:"truncate",children:h(e.label)})]},e.id)})}),b.length>0?(0,n.jsxs)(eW.Nt,{open:y||!!z,onOpenChange:k,className:"mt-2 border-t pt-2",children:[(0,n.jsxs)(eW.R6,{type:"button","aria-label":h("pluginSettings"),className:"flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-sm font-medium text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 text-left",children:h("pluginSettings")}),(0,n.jsx)("span",{className:"tabular-nums",children:b.length}),(0,n.jsx)(eq.A,{className:(0,C.cn)("size-3.5 transition-transform",y||z?"rotate-180":null)})]}),(0,n.jsx)(eW.Ke,{children:(0,n.jsx)("div",{className:"mt-1 grid grid-cols-1 gap-1",children:b.map(e=>{let t=i_(e.pluginName,e.descriptor.contributionName),s=t===E;return(0,n.jsxs)(N.$,{variant:"ghost",disabled:j,"aria-current":s?"page":void 0,onClick:()=>D(t),className:(0,C.cn)("min-w-0 justify-start",s?"bg-accent text-accent-foreground hover:bg-accent":"text-muted-foreground"),children:[(0,n.jsx)(e_,{icon:e.descriptor.icon,className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},t)})})})]}):null]}),z?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,n.jsx)(iL,{render:u,input:{pluginName:z.pluginName,descriptor:z.descriptor,onClose:T,onBeforeLeaveChange:P}})}):"skills"===E?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(nM,{projects:x,focusedCwd:i,onBeforeLeaveChange:P})}):"mcp-settings"===E?(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(iL,{render:d,input:{onBeforeLeaveChange:P}})}):"capability-modes"===E?(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(iL,{render:c,input:{onBeforeLeaveChange:P}})}):"models"===E?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:e&&(0,n.jsx)(iO,{connectionReady:t,initialTab:s,onBeforeLeaveChange:P})}):"plugins"===E?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:o()}):(0,n.jsx)(ej._Y,{className:"min-w-0 max-h-none",children:(0,n.jsx)("div",{className:"p-4 sm:p-6",children:"appearance"===E?(0,n.jsx)(re,{}):"habits"===E?(0,n.jsx)(rb,{}):"auth"===E?e&&(0,n.jsx)(nL,{}):"region"===E?(0,n.jsx)(nU,{canLeave:p}):(0,n.jsx)(iB,{})})})]})]})})}let iW=a.Ik({cwd:a.Yj().trim().min(1).nullable()}).strict(),iY=a.g1(a.Yj(),a.Pq()),iU=a.g1(a.Yj().min(1).max(128),iY),iV=a.Ik({local:iU,inherited:iU,projectTrusted:a.zM().nullable(),diagnostics:a.YO(a.Ik({name:a.Yj().nullable(),message:a.Yj()}).strict())}).strict();iW.extend({servers:iU}).strict(),iW.extend({name:a.Yj().min(1).max(128)}).strict();let iK=a.Ik({output:a.Yj()}).strict(),iH=a.Ik({}).strict(),iG=["command","args","url","type","description","enabled","exposure"];function iJ(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Object.values(e).every(e=>"string"==typeof e)}function iQ(e){return iJ(e)?Object.entries(e).map(([e,t])=>({key:e,value:t})):[]}function iX(e){return!("command"in e)&&!("url"in e)&&!("type"in e)}function iZ(e,t){let s=t??{};return{originalName:e,name:e??"",transport:t&&iX(t)?"inherit":"url"in s?"http":"stdio",command:"string"==typeof s.command?s.command:"",args:Array.isArray(s.args)?s.args.join("\n"):"",env:iQ(s.env),headers:iQ(s.headers),url:"string"==typeof s.url?s.url:"",description:"string"==typeof s.description?s.description:"",enabled:!1!==s.enabled,exposure:"string"==typeof s.exposure?s.exposure:"",advanced:JSON.stringify(Object.fromEntries(Object.entries(s).filter(([e,t])=>!iG.includes(e)&&!(["env","headers"].includes(e)&&iJ(t)))),null,2)}}class i0 extends Error{constructor(e,t){super(t),this.field=e}}function i1(e){return"string"==typeof e.url?e.url:"string"==typeof e.command?e.command:"继承全局连接"}let i2={MCP:"MCP",服务列表:"Servers",配置服务:"Configure server",服务配置:"Server configuration",手动配置:"Configure manually","导入 JSON":"Import JSON",返回服务列表:"Back to servers",服务操作:"Server actions",恢复全局配置:"Restore global configuration",删除服务:"Delete server",继承全局:"Inherited from global",项目配置:"Project configuration","项目配置 \xb7 继承全局连接":"Project configuration \xb7 inherits global connection","连接参数沿用全局,仅保存本项目的启用和工具设置。":"Connection settings are inherited from global. Only enablement and tool settings are saved for this project.",环境变量:"Environment variables",请求头:"Request headers",名称:"Name",值:"Value",添加:"Add ",删除行:"Remove row",高级设置:"Advanced settings","其他配置(JSON)":"Other configuration (JSON)",保存并测试:"Save and test",连接测试结果:"Connection test result","正在测试连接…":"Testing connection…","已保存,正在测试连接…":"Saved. Testing connection…",连接测试通过:"Connection test passed",连接测试失败:"Connection test failed",查看详细输出:"View output","已保存,连接测试通过。":"Saved. Connection test passed.","已保存,连接测试失败。":"Saved. Connection test failed.","请填写名称,或删除空白行。":"Enter a name or remove the empty row.","名称不能重复。":"Names must be unique.","环境变量和请求头不能在表单与 JSON 中重复配置。":"Do not configure environment variables or request headers in both the form and JSON.","连接请求最多等待 10 秒;凭据命令可能延长检查时间。":"Connection requests wait up to 10 seconds; credential commands may extend the check.",配置范围:"Configuration scope",全局:"Global",当前项目:"Current project",手动添加:"Add manually","添加 JSON":"Add JSON","正在读取配置…":"Loading configuration…",重试:"Retry","添加第一个 MCP 服务":"Add your first MCP server","添加服务地址或本地程序。":"Add a server URL or a local program.",已启用:"Enabled",已停用:"Disabled",启用:"Enable",停用:"Disable",编辑:"Edit",为本项目配置:"Configure for this project",独立检查:"Check independently",删除:"Delete",来自全局:"Inherited from global",本项目:"This project",覆盖全局:"Overrides global","项目设置 \xb7 继承全局连接":"Project settings \xb7 inherits global connection",继承全局连接:"Inherit global connection","本项目尚未受信任,不能执行检查;仍可编辑和保存配置。":"This project is not trusted. Checking is disabled; editing and saving remain available.","配置启用不代表已连接。保存不会自动连接或重载会话。":"Enabled configuration does not mean connected. Saving does not connect or reload sessions.","正在检查…":"Checking…",检查输出:"Check output",检查完成:"Check completed",检查失败:"Check failed","检查连接已关闭,当前聊天会话状态未改变。":"The check connection is closed. Current chat session state is unchanged.",返回编辑:"Edit configuration",关闭结果:"Dismiss result",返回:"Back",添加服务:"Add server",编辑服务:"Edit server",保存范围:"Save scope",服务名称:"Server name",连接方式:"Transport",本地程序:"Local program","HTTP 地址":"HTTP URL",启动程序:"Command","参数(每行一个)":"Arguments (one per line)","服务说明(可选)":"Description (optional)",工具使用方式:"Tool exposure",沿用默认:"Use default",通过脚本调用:"Via scripts",按需发现:"On-demand discovery",直接使用:"Direct use",隐藏:"Hidden","高级配置(JSON)":"Advanced configuration (JSON)","继承全局连接,仅保存本项目启用与曝光设置,不复制全局凭据。":"Inherits the global connection. Only project enablement and exposure settings are saved; global credentials are not copied.","本项目的完整定义会整体替换同名全局配置。":"A complete project definition replaces the global configuration of the same name.","配置 JSON":"Configuration JSON","仅接受包含 mcpServers 的标准 JSON。":"Only standard JSON with mcpServers is accepted.",解析预览:"Preview",待保存服务:"Servers to save",新增:"New",替换已有配置:"Replace existing configuration","覆盖全局(仅本项目)":"Override global (this project only)",允许替换以上同名已有配置:"Allow replacing existing configuration with the same names","重新编辑 JSON":"Edit JSON again",取消:"Cancel",保存:"Save","保存中…":"Saving…","已保存。新会话使用新配置;已有会话需重载 Pi 配置。":"Saved. New sessions use the new configuration; existing sessions must reload Pi configuration.","放弃未保存的修改?":"Discard unsaved changes?","当前修改尚未保存。放弃后将保留已保存的配置。":"Your changes have not been saved. Discarding keeps the saved configuration.",放弃修改:"Discard changes",删除配置:"Delete configuration","删除本项目配置后,将恢复使用同名全局配置。":"Deleting this project configuration restores the global configuration of the same name.","此范围内的服务配置将被删除。":"The server configuration will be deleted from this scope.","请输入有效的 JSON。":"Enter valid JSON.","仅接受包含 mcpServers 的标准配置,不允许其他根级字段。":"Only a standard mcpServers object is accepted; other root fields are not allowed.","配置中至少需要一个服务。":"At least one server is required.","服务名称需要 1–128 个字符。":"Server names must contain 1–128 characters.","高级配置需要是 JSON 对象。":"Advanced configuration must be a JSON object.","连接、说明、启用和曝光字段请在上方表单中填写。":"Set connection, description, enablement and exposure in the fields above.","继承连接只允许启用、曝光和 toolExposure 设置。":"Inherited connections only allow enablement, exposure and toolExposure settings.","请输入启动程序。":"Enter a command.","请输入有效的 HTTP 或 HTTPS 地址。":"Enter a valid HTTP or HTTPS URL.","请明确勾选替换已有配置。":"Explicitly allow replacing existing configuration.","该名称已存在,请编辑已有服务或使用其他名称。":"This name already exists. Edit that server or choose another name.","请求失败,请重试。":"The request failed. Please retry."};function i5(){let{locale:e}=(0,eG.i)();return t=>"en"===e?i2[t]??t:t}function i3(e){return e instanceof Error?e.message:"请求失败,请重试。"}var i4=s(60454),i6=s(93750),i8=s(13464);function i7({id:e,label:t,value:s,options:r,disabled:a,onChange:i}){return(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsx)("label",{id:`${e}-label`,htmlFor:e,className:"text-sm font-medium",children:t}),(0,n.jsxs)(ea.l6,{value:s,disabled:a,onValueChange:e=>{"string"==typeof e&&i(e)},children:[(0,n.jsx)(ea.bq,{id:e,"aria-labelledby":`${e}-label`,className:"w-full min-w-0 whitespace-normal [&_[data-slot=select-value]]:line-clamp-none [&_[data-slot=select-value]]:break-all",children:(0,n.jsx)(ea.yv,{children:r.find(e=>e.value===s)?.label??s})}),(0,n.jsx)(ea.gC,{positionerClassName:"z-[125]",align:"start",children:r.map(e=>(0,n.jsx)(ea.eb,{value:e.value,className:"[&_span]:whitespace-normal [&_span]:break-all",children:e.label},e.value))})]})]})}function i9({trigger:e,children:t}){return(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:e}),(0,n.jsx)(K.dc,{children:(0,n.jsx)(i4.y,{sideOffset:4,align:"end",className:"z-[125] outline-none",children:(0,n.jsx)(i6._,{className:i8.hD,children:t})})})]})}function le({message:e,id:t}){let s=i5();return e?(0,n.jsx)("p",{id:t,role:"alert",className:"break-words text-sm text-destructive",children:s(e)}):null}function lt({rows:e,selectedName:t,pending:s,onSelect:r}){let a=i5();return(0,n.jsx)("ul",{"aria-label":a("服务列表"),className:"divide-y",children:e.map(e=>{let i="string"==typeof e.config.url?eO.A:v.A;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button","aria-label":`${a("配置服务")} \xb7 ${e.name}`,"aria-current":t===e.name?"true":void 0,disabled:s,onClick:()=>r(e),className:(0,C.cn)("flex w-full min-w-0 cursor-pointer items-center gap-3 p-4 text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-default",t===e.name&&"bg-accent"),children:[(0,n.jsx)(i,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1 space-y-1",children:[(0,n.jsxs)("span",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)("span",{className:"min-w-0 break-all text-sm font-medium",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:a(!1===e.config.enabled?"已停用":"已启用")})]}),(0,n.jsxs)("span",{className:"block text-xs text-muted-foreground",children:[a(e.source)," \xb7"," ",a("string"==typeof e.config.url?"HTTP 地址":"本地程序")]}),(0,n.jsx)("span",{className:"block truncate font-mono text-xs text-muted-foreground",children:i1(e.config)})]}),(0,n.jsx)(e8.A,{"aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})},e.name)})})}function ls({id:e,label:t,rows:s,disabled:r,error:a,onChange:i}){let l=i5();return(0,n.jsxs)("fieldset",{className:"min-w-0 space-y-2",disabled:r,children:[(0,n.jsx)("legend",{className:"text-sm font-medium",children:t}),s.length>0&&(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2 text-xs text-muted-foreground","aria-hidden":"true",children:[(0,n.jsx)("span",{children:l("名称")}),(0,n.jsx)("span",{children:l("值")})]}),s.map((o,d)=>(0,n.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_2rem] gap-2",children:[(0,n.jsx)(eu.p,{"aria-label":`${t} \xb7 ${l("名称")} ${d+1}`,"aria-invalid":!!a,"aria-describedby":a?`${e}-error`:void 0,value:o.key,spellCheck:!1,className:"min-w-0 font-mono",onChange:e=>i(s.map((t,s)=>s===d?{...t,key:e.target.value}:t))}),(0,n.jsx)(eu.p,{"aria-label":`${t} \xb7 ${l("值")} ${d+1}`,value:o.value,spellCheck:!1,autoComplete:"off",className:"min-w-0 font-mono",onChange:e=>i(s.map((t,s)=>s===d?{...t,value:e.target.value}:t))}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":`${l("删除行")} \xb7 ${t} ${d+1}`,disabled:r,onClick:()=>i(s.filter((e,t)=>t!==d)),children:(0,n.jsx)(ee.A,{"aria-hidden":"true"})})]},d)),(0,n.jsx)(le,{id:`${e}-error`,message:a}),(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>i([...s,{key:"",value:""}]),children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),l("添加"),t]})]})}var ln=s(27315);function lr({check:e,onRetry:t,onDismiss:s}){let r=i5(),a=e.loading?b.A:e.error?W.A:ln.A;return(0,n.jsxs)("section",{"aria-label":r("连接测试结果"),"aria-busy":e.loading,className:"space-y-2 border-b pb-4",children:[(0,n.jsxs)("p",{role:"status",className:"flex items-center gap-2 text-sm font-medium",children:[(0,n.jsx)(a,{"aria-hidden":"true",className:`size-4 shrink-0 ${e.loading?"motion-safe:animate-spin":e.error?"text-destructive":""}`}),r(e.loading?"已保存,正在测试连接…":e.error?"已保存,连接测试失败。":"已保存,连接测试通过。")]}),(0,n.jsx)(le,{message:e.error}),e.loading?(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:r("连接请求最多等待 10 秒;凭据命令可能延长检查时间。")}):(0,n.jsxs)(n.Fragment,{children:[e.output&&(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"w-fit cursor-pointer rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:r("查看详细输出")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded-lg bg-muted p-3 font-mono text-sm",children:e.output})]}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:r("检查连接已关闭,当前聊天会话状态未改变。")}),(0,n.jsxs)("div",{className:"flex gap-2",children:[e.error&&(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:t,children:r("重试")}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:s,children:r("关闭结果")})]})]})]})}function la({editor:e,scopeLabel:t,project:s,projectTrusted:a,check:i,local:l,inherited:o,pending:d,saving:c,error:u,onDraft:m,onJson:p,onPreview:h,onOverwrite:g,onSave:x,onCancel:f,onRemove:b,onDismissCheck:v}){let w=i5(),y=(0,r.useId)(),k=(0,r.useRef)(null),[j,I]=(0,r.useState)(!1);(0,r.useEffect)(()=>{u&&k.current?.querySelector('[aria-invalid="true"]')?.focus()},[u]);let C=e=>`${y}-${e}`,S="manual"===e.kind?e.draft:null,M="json"===e.kind&&e.preview?Object.keys(e.preview).filter(e=>Object.hasOwn(l,e)):[],z="json"===e.kind?"导入 JSON":S?.originalName?"服务配置":"添加服务",A=S?.originalName,$=!!(A&&Object.hasOwn(l,A)),R=!!(s&&A&&Object.hasOwn(o,A)),T=(e,t,s)=>(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:C(e),className:"text-sm font-medium",children:w(t)}),s,(0,n.jsx)(le,{id:C(`${e}-error`),message:u?.field===e?u.message:null})]}),P=(e,t)=>T(e,t,(0,n.jsx)(eu.p,{id:C(e),value:S?.[e]??"",disabled:d||"name"===e&&!!S?.originalName,"aria-invalid":u?.field===e,"aria-describedby":u?.field===e?C(`${e}-error`):void 0,onChange:t=>m({[e]:t.target.value})}));return(0,n.jsxs)("form",{ref:k,"aria-label":w(z),className:"flex min-h-0 min-w-0 flex-1 flex-col",onSubmit:e=>{e.preventDefault(),x()},children:[(0,n.jsxs)("div",{className:"shrink-0 space-y-1 border-b p-4 sm:px-6",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":w("返回服务列表"),disabled:d,onClick:f,children:(0,n.jsx)(E.A,{"aria-hidden":"true"})}),(0,n.jsx)("h3",{className:"min-w-0 flex-1 text-sm font-semibold",children:w(z)}),$&&A&&(0,n.jsx)(i9,{trigger:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":w("服务操作"),disabled:d,children:(0,n.jsx)(V.A,{"aria-hidden":"true"})}),children:(0,n.jsx)(K._2,{variant:R?"default":"destructive",onClick:()=>b(A),children:w(R?"恢复全局配置":"删除服务")})})]}),s&&(0,n.jsxs)("p",{className:"break-all text-xs text-muted-foreground",children:[w("保存范围"),":",t]})]}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:[S?(0,n.jsxs)("div",{className:"max-w-[40rem] space-y-4",children:[i&&(0,n.jsx)(lr,{check:i,onRetry:()=>x(!0),onDismiss:v}),P("name","服务名称"),"inherit"===S.transport?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("p",{className:"text-sm font-medium",children:w("继承全局连接")}),A&&o[A]&&(0,n.jsx)("p",{className:"break-all font-mono text-sm text-muted-foreground",children:i1(o[A])}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("连接参数沿用全局,仅保存本项目的启用和工具设置。")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(i7,{id:C("transport"),label:w("连接方式"),value:S.transport,disabled:d,options:[{value:"stdio",label:w("本地程序")},{value:"http",label:w("HTTP 地址")}],onChange:e=>m({transport:"http"===e?"http":"stdio"})}),"stdio"===S.transport?(0,n.jsxs)(n.Fragment,{children:[P("command","启动程序"),T("args","参数(每行一个)",(0,n.jsx)(t8.T,{id:C("args"),className:"min-h-24 font-mono",value:S.args,disabled:d,onChange:e=>m({args:e.target.value})}))]}):P("url","HTTP 地址"),("stdio"===S.transport||u?.field==="env")&&(0,n.jsx)(ls,{id:C("env"),label:w("环境变量"),rows:S.env,disabled:d,error:u?.field==="env"?u.message:null,onChange:e=>m({env:e})}),("http"===S.transport||u?.field==="headers")&&(0,n.jsx)(ls,{id:C("headers"),label:w("请求头"),rows:S.headers,disabled:d,error:u?.field==="headers"?u.message:null,onChange:e=>m({headers:e})}),s&&(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("本项目的完整定义会整体替换同名全局配置。")})]}),(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",checked:S.enabled,disabled:d,onChange:e=>m({enabled:e.target.checked}),className:"size-4 shrink-0 accent-primary"}),w("已启用")]}),(0,n.jsxs)(eW.Nt,{open:j||u?.field==="advanced",onOpenChange:I,children:[(0,n.jsxs)(eW.R6,{type:"button",className:"group flex min-h-8 cursor-pointer items-center gap-2 rounded-lg px-2 text-sm font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eq.A,{"aria-hidden":"true",className:"size-4 transition-transform group-data-panel-open:rotate-180"}),w("高级设置")]}),(0,n.jsxs)(eW.Ke,{className:"space-y-3 pt-3",children:["inherit"!==S.transport&&P("description","服务说明(可选)"),(0,n.jsx)(i7,{id:C("exposure"),label:w("工具使用方式"),value:S.exposure,disabled:d,options:[{value:"",label:w("沿用默认")},{value:"codemode",label:w("通过脚本调用")},{value:"deferred",label:w("按需发现")},{value:"direct",label:w("直接使用")},{value:"hidden",label:w("隐藏")},...["","codemode","deferred","direct","hidden"].includes(S.exposure)?[]:[{value:S.exposure,label:S.exposure}]],onChange:e=>m({exposure:e})}),(0,n.jsx)("label",{htmlFor:C("advanced"),className:"block text-sm font-medium",children:w("其他配置(JSON)")}),(0,n.jsx)(t8.T,{id:C("advanced"),onFocus:()=>I(!0),value:S.advanced,disabled:d,className:"min-h-40 font-mono",spellCheck:!1,"aria-invalid":u?.field==="advanced","aria-describedby":u?.field==="advanced"?C("advanced-error"):void 0,onChange:e=>m({advanced:e.target.value})}),(0,n.jsx)(le,{id:C("advanced-error"),message:u?.field==="advanced"?u.message:null})]})]})]}):"json"===e.kind?(0,n.jsxs)("div",{className:"space-y-3",children:[T("json","配置 JSON",(0,n.jsx)(t8.T,{id:C("json"),value:e.text,disabled:d,"aria-invalid":u?.field==="json","aria-describedby":u?.field==="json"?C("json-error"):void 0,spellCheck:!1,className:"min-h-48 font-mono",placeholder:'{ "mcpServers": { "docs": { "url": "https://example.com/mcp" } } }',onChange:e=>p(e.target.value)})),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:w("仅接受包含 mcpServers 的标准 JSON。")}),(0,n.jsx)(N.$,{type:"button",variant:"outline",onClick:h,disabled:d||!e.text.trim(),children:w("解析预览")}),e.preview&&(0,n.jsxs)("section",{"aria-label":w("待保存服务"),className:"space-y-3",children:[(0,n.jsx)("ul",{className:"divide-y border-y",children:Object.entries(e.preview).map(([e,t])=>(0,n.jsxs)("li",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 break-all font-medium",children:e}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(iX(t)?"继承全局连接":"url"in t?"HTTP 地址":"本地程序")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(Object.hasOwn(l,e)?"替换已有配置":Object.hasOwn(o,e)?"覆盖全局(仅本项目)":"新增")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:w(!1===t.enabled?"已停用":"已启用")})]},e))}),M.length>0&&(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-start gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",checked:e.overwrite,disabled:d,className:"mt-1 size-4 shrink-0 accent-primary",onChange:e=>g(e.target.checked)}),(0,n.jsx)("span",{children:w("允许替换以上同名已有配置")})]})]})]}):null,(0,n.jsx)("div",{className:"mt-3",children:(0,n.jsx)(le,{message:u?.field==="save"?u.message:null})})]}),(0,n.jsxs)("footer",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t bg-background px-4 py-3 sm:px-6",children:[(0,n.jsx)(N.$,{type:"button",variant:"outline",disabled:d,onClick:f,children:w("取消")}),S&&(0,n.jsx)(N.$,{type:"button",variant:"outline",disabled:d||!S.enabled||!1===a,onClick:()=>x(!0),children:w("保存并测试")}),(0,n.jsx)(N.$,{type:"submit",disabled:d||"json"===e.kind&&(!e.preview||M.length>0&&!e.overwrite),children:w(i?.loading?"正在测试连接…":c?"保存中…":"保存")})]})]})}function li({pending:e,onAdd:t,onImport:s}){let r=i5();return(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-6",children:(0,n.jsx)("div",{className:"grid min-h-full grid-rows-[1fr_auto_2fr]",children:(0,n.jsxs)("div",{className:"row-start-2 flex flex-col items-center gap-6 text-center",children:[(0,n.jsxs)("div",{"aria-hidden":"true",className:"relative h-28 w-60 shrink-0 text-muted-foreground",children:[(0,n.jsxs)("svg",{viewBox:"0 0 240 112",fill:"none",className:"absolute inset-0 size-full text-muted-foreground/40",children:[(0,n.jsx)("path",{d:"M44 76H64Q76 76 76 64V60Q76 56 92 56M148 56H164Q180 56 180 44Q180 40 196 40M120 12V28",stroke:"currentColor"}),(0,n.jsx)("circle",{cx:"120",cy:"8",r:"3",className:"fill-background stroke-current"}),(0,n.jsx)("circle",{cx:"64",cy:"76",r:"2",className:"fill-muted-foreground"}),(0,n.jsx)("circle",{cx:"180",cy:"44",r:"2",className:"fill-muted-foreground"})]}),(0,n.jsx)("div",{className:"absolute top-14 left-1 flex size-10 items-center justify-center rounded-xl border bg-muted/50",children:(0,n.jsx)(v.A,{className:"size-4"})}),(0,n.jsx)("div",{className:"absolute top-7 left-[92px] flex size-14 items-center justify-center rounded-xl border bg-background text-foreground",children:(0,n.jsx)(eC.A,{className:"size-6"})}),(0,n.jsx)("div",{className:"absolute top-5 right-1 flex size-10 items-center justify-center rounded-xl border bg-muted/50",children:(0,n.jsx)(eO.A,{className:"size-4"})})]}),(0,n.jsx)("h3",{className:"text-lg font-semibold",children:r("添加第一个 MCP 服务")}),(0,n.jsxs)("div",{className:"flex flex-wrap justify-center gap-2",children:[(0,n.jsxs)(N.$,{disabled:e,onClick:t,children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),r("添加服务")]}),(0,n.jsx)(N.$,{variant:"outline",disabled:e,onClick:s,children:r("导入 JSON")})]})]})})})}function ll({projects:e,focusedCwd:t,onBeforeLeaveChange:s}){let{clientId:i}=(0,er.gM)(),l=function(e,t){let s=i5(),n=(0,r.useMemo)(()=>({getMcp:(t,s)=>ec(e,"/api/mcp-settings/get",{cwd:t},iV,{signal:s}),replaceMcp:(t,s)=>ec(e,"/api/mcp-settings/replace",t,iH,{signal:s}),deleteMcp:(t,s,n)=>ec(e,"/api/mcp-settings/del",{cwd:t,name:s},iH,{signal:n}),checkMcp:(t,s,n)=>ec(e,"/api/mcp-check/get",{cwd:t,name:s},iK,{signal:n})}),[e]),{confirm:i,dialog:l}=nR(),[o,d]=(0,r.useState)(null),[c,u]=(0,r.useState)(null),m=c?.data??null,p=c?c.cwd:o,[h,g]=(0,r.useState)(null),[x,f]=(0,r.useState)(!0),[b,v]=(0,r.useState)(!1),[w,y]=(0,r.useState)(null),[k,j]=(0,r.useState)(null),[N,I]=(0,r.useState)(null),[C,S]=(0,r.useState)(null),M=(0,r.useRef)(null),z=(0,r.useRef)(0),E=(0,r.useRef)(0),A=(0,r.useRef)(i),$=(0,r.useRef)(s);(0,r.useEffect)(()=>{A.current=i,$.current=s},[i,s]);let R=null!==c&&c.cwd===o&&!x&&!w,T=R&&(h?.kind==="manual"&&JSON.stringify(h.draft)!==h.initial||h?.kind==="json"&&!!h.text),P=(0,r.useCallback)(()=>{g(null),j(null)},[]),D=(0,r.useCallback)(async()=>!(b||C?.loading)&&(!T||await A.current({title:$.current("放弃未保存的修改?"),description:$.current("当前修改尚未保存。放弃后将保留已保存的配置。"),confirmLabel:$.current("放弃修改")})),[T,b,C?.loading]);(0,r.useEffect)(()=>(t(D),()=>t(null)),[D,t]);let O=(0,r.useCallback)(async(e,t,s=!1)=>{f(!0),y(null);try{let r=await n.getMcp(o,e);if(e.aborted||z.current!==t)return!1;return u({cwd:o,data:r}),s&&g(null),!0}catch(s){return e.aborted||z.current!==t||(console.warn("[Pi Desk][MCP] 读取配置失败",{cwd:o,message:i3(s)}),y(i3(s))),!1}finally{e.aborted||z.current!==t||f(!1)}},[n,o]);(0,r.useEffect)(()=>{let e=new AbortController;M.current=e;let t=++z.current;return O(e.signal,t,!0),()=>e.abort()},[O]);let L=async e=>{await D()&&(P(),I(null),e())},F=async e=>{e!==o&&await D()&&(M.current?.abort(),j(null),I(null),S(null),y(null),f(!0),d(e))},_=(e,t)=>{let s=iZ(e,t);j(null),I(null),S(null),g({kind:"manual",draft:s,initial:JSON.stringify(s)})},B=async(e,t)=>{let s=M.current?.signal;if(!s||!R||b||C?.loading)return!1;let n=z.current;v(!0),j(null),I(null);try{if(await e(s),s.aborted||z.current!==n)return!1;return t(),S(null),I("已保存。新会话使用新配置;已有会话需重载 Pi 配置。"),await O(s,n)}catch(e){return s.aborted||z.current!==n||j({field:e instanceof i0?e.field:"save",message:i3(e)}),!1}finally{s.aborted||z.current!==n||v(!1)}},q=async(e=!1)=>{if(!(!h||!m||!R||b||C?.loading)&&(!e||"manual"===h.kind&&h.draft.enabled&&!1!==m.projectTrusted))try{let t="manual"===h.kind?function(e,t){let s,n=e.name.trim();if(!n||n.length>128)throw new i0("name","服务名称需要 1–128 个字符。");try{s=iY.parse(JSON.parse(e.advanced))}catch{throw new i0("advanced","高级配置需要是 JSON 对象。")}if(iG.some(e=>e in s))throw new i0("advanced","连接、说明、启用和曝光字段请在上方表单中填写。");if("inherit"===e.transport&&Object.keys(s).some(e=>"toolExposure"!==e))throw new i0("advanced","继承连接只允许启用、曝光和 toolExposure 设置。");let r={...s,enabled:e.enabled};if(e.exposure&&(r.exposure=e.exposure),"inherit"!==e.transport){for(let n of(e.description&&(r.description=e.description),["env","headers"]))if(e[n].length>0||iJ(t?.[n])){if(n in s)throw new i0("advanced","环境变量和请求头不能在表单与 JSON 中重复配置。");r[n]=function(e,t){let s=[],n=new Set;for(let r of e){if(!r.key.trim()&&!r.value)continue;if(!r.key.trim())throw new i0(t,"请填写名称,或删除空白行。");let e=r.key.trim(),a="headers"===t?e.toLowerCase():e;if(n.has(a))throw new i0(t,"名称不能重复。");n.add(a),s.push([e,r.value])}return Object.fromEntries(s)}(e[n],n)}}if("stdio"===e.transport){if(!e.command.trim())throw new i0("command","请输入启动程序。");r.command=e.command.trim(),r.args=Array.isArray(t?.args)&&t.args.join("\n")===e.args?t.args:e.args?e.args.split(/\r?\n/):[],(t?.type!==void 0||!t||"url"in t)&&(r.type="stdio")}else if("http"===e.transport){try{let t=new URL(e.url.trim());if(!["https:","http:"].includes(t.protocol))throw Error()}catch{throw new i0("url","请输入有效的 HTTP 或 HTTPS 地址。")}r.url=e.url.trim(),(t?.type!==void 0||!t||"command"in t)&&(r.type="http")}return{[n]:r}}(h.draft,h.draft.originalName?m.local[h.draft.originalName]:void 0):h.preview;if(!t)return;let s=Object.keys(t).filter(e=>Object.hasOwn(m.local,e));if("json"===h.kind&&s.length&&!h.overwrite)throw new i0("json","请明确勾选替换已有配置。");if("manual"===h.kind&&s.some(e=>e!==h.draft.originalName))throw new i0("name","该名称已存在,请编辑已有服务或使用其他名称。");if(await B(e=>n.replaceMcp({cwd:o,servers:t},e),()=>{if("json"===h.kind)g(null);else{let e=h.draft.name.trim(),s=iZ(e,t[e]);g({kind:"manual",draft:s,initial:JSON.stringify(s)})}})&&e&&"manual"===h.kind){let e=await Y(h.draft.name.trim());M.current?.signal.aborted||I(e?"已保存,连接测试通过。":"已保存,连接测试失败。")}}catch(e){j({field:e instanceof i0?e.field:"save",message:i3(e)})}},W=async e=>{if(!m||!R||b||!Object.hasOwn(m.local,e))return;let t=null!==o&&Object.hasOwn(m.inherited,e);await A.current({title:`${$.current(t?"恢复全局配置":"删除服务")} \xb7 ${e}`,description:$.current(t?"删除本项目配置后,将恢复使用同名全局配置。":"此范围内的服务配置将被删除。"),confirmLabel:$.current(t?"恢复全局配置":"删除服务")})&&await B(t=>n.deleteMcp(o,e,t),()=>g(null))},Y=async e=>{let t=M.current?.signal;if(!t||!m||!1===m.projectTrusted||C?.loading)return!1;let s=++E.current;S({name:e,loading:!0,output:null,error:null});try{let r=await n.checkMcp(o,e,t);return t.aborted||E.current!==s||S({name:e,loading:!1,output:r.output.slice(0,32768),error:null}),!0}catch(n){return t.aborted||E.current!==s||S({name:e,loading:!1,output:null,error:i3(n)}),!1}},U=m?[...new Set([...Object.keys(m.inherited),...Object.keys(m.local)])].map(e=>{let t=m.local[e],s=m.inherited[e],n=!!(t&&s&&iX(t));return{name:e,config:n?{...s,...t}:t??s,local:t??null,source:null===p?"全局":t?n?"项目配置 \xb7 继承全局连接":"项目配置":"继承全局"}}):[];return{cwd:o,displayCwd:p,ready:R,mcp:m,editor:h,setEditor:g,loading:x,pending:b,loadError:w,error:k,notice:N,check:C,rows:U,dirty:T,dialog:l,retry:()=>{M.current&&O(M.current.signal,z.current,c?.cwd!==o)},navigate:L,setCwd:F,startManual:_,startInherited:(e,t)=>{_(e,{enabled:!1!==t.enabled})},updateDraft:e=>{g(t=>t?.kind==="manual"?{...t,draft:{...t.draft,...e}}:t),j(null),I(null),S(null)},updateJson:e=>{g({kind:"json",text:e,preview:null,overwrite:!1}),j(null)},previewJson:()=>{if(h?.kind==="json"&&m)try{let t=function(e){let t;try{t=JSON.parse(e)}catch{throw Error("请输入有效的 JSON。")}let s=a.Ik({mcpServers:iU}).strict().safeParse(t);if(!s.success)throw Error("仅接受包含 mcpServers 的标准配置,不允许其他根级字段。");if(0===Object.keys(s.data.mcpServers).length)throw Error("配置中至少需要一个服务。");return s.data.mcpServers}(h.text);var e=m.inherited;for(let[s,n]of Object.entries(t)){if(!s.trim()||s!==s.trim())throw new i0("json","服务名称不能为空或带有首尾空格。");if(iX(n)){if(null===o||!Object.hasOwn(e,s)||Object.keys(n).some(e=>!["enabled","exposure","toolExposure"].includes(e)))throw new i0("json",`${s}:继承配置需要同名全局服务,且只允许启用和曝光设置。`)}else if("sse"===n.type)throw new i0("json",`${s}:不支持 SSE,请使用 HTTP 连接。`);else if("string"!=typeof n.command&&"string"!=typeof n.url)throw new i0("json",`${s}:请提供启动程序或服务地址。`)}g({...h,preview:t,overwrite:!1}),j(null)}catch(e){j({field:"json",message:i3(e)})}},saveEditor:q,remove:W,dismissCheck:()=>{S(null)},beforeLeave:D}}(i,s),o=i5(),d=(0,r.useId)(),c=(0,r.useMemo)(()=>{let s=new Map;for(let t of e){let e=t.cwd.replaceAll("\\","/").replace(/\/+$/,""),n=/^[a-zA-Z]:\//.test(e)||e.startsWith("//")?e.toLowerCase():e;s.has(n)||s.set(n,t)}return[...s.values()].sort((e,s)=>Number(s.cwd===t)-Number(e.cwd===t))},[e,t]),u=null===l.displayCwd?o("全局"):`${c.find(e=>e.cwd===l.displayCwd)?.projectName??o("当前项目")} \xb7 ${l.displayCwd}`,m=!!(l.editor&&l.mcp),p=l.pending||!!l.check?.loading,h=p||!l.ready,g=l.editor?.kind==="manual"?l.editor.draft.originalName:null,x=()=>{l.navigate(()=>l.startManual(null))},f=()=>{l.navigate(()=>l.setEditor({kind:"json",text:"",preview:null,overwrite:!1}))};return(0,n.jsxs)("section",{"aria-label":"MCP",className:"@container/mcp flex h-full min-h-0 min-w-0 flex-col",children:[l.dialog,(0,n.jsxs)("header",{className:"grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border-b p-4 @min-[40rem]/mcp:grid-cols-[auto_minmax(0,1fr)_auto]",children:[(0,n.jsxs)("h2",{className:"flex items-center gap-2 text-xl font-semibold",children:["MCP",(0,n.jsx)("span",{className:"inline-flex size-4",children:l.loading&&(0,n.jsx)(b.A,{role:"status","aria-label":o("正在读取配置…"),className:"size-4 animate-spin text-muted-foreground"})})]}),(0,n.jsxs)("div",{className:"col-start-2 flex flex-wrap justify-end gap-2 @min-[40rem]/mcp:col-start-3 @min-[40rem]/mcp:self-end",children:[(0,n.jsxs)(N.$,{disabled:h,onClick:x,children:[(0,n.jsx)(U.A,{"aria-hidden":"true"}),o("添加服务")]}),(0,n.jsx)(N.$,{variant:"outline",disabled:h,onClick:f,children:o("导入 JSON")})]}),(0,n.jsx)("div",{className:"col-span-2 row-start-2 w-full @min-[40rem]/mcp:col-span-1 @min-[40rem]/mcp:col-start-2 @min-[40rem]/mcp:row-start-1 @min-[40rem]/mcp:max-w-80 @min-[40rem]/mcp:justify-self-end @min-[40rem]/mcp:[&_[data-slot=select-trigger]]:mb-0",children:(0,n.jsx)(i7,{id:`${d}-scope`,label:o("配置范围"),value:l.cwd??"",disabled:p,options:[{value:"",label:o("全局")},...c.map(e=>({value:e.cwd,label:`${e.projectName}${e.cwd===t?` \xb7 ${o("当前项目")}`:""}`}))],onChange:e=>{l.setCwd(e||null)}})})]}),l.notice&&!l.check&&(0,n.jsx)("p",{role:"status",className:"shrink-0 break-words border-b px-4 py-2 text-sm",children:o(l.notice)}),l.mcp?.projectTrusted===!1&&(0,n.jsx)("p",{className:"shrink-0 px-4 pt-3 text-sm text-muted-foreground",children:o("本项目尚未受信任,不能执行检查;仍可编辑和保存配置。")}),l.mcp&&l.mcp.diagnostics.length>0&&(0,n.jsx)("div",{className:"max-h-32 shrink-0 space-y-2 overflow-y-auto px-4 pt-3",children:l.mcp.diagnostics.map((e,t)=>(0,n.jsx)(le,{message:`${e.name?`${e.name}:`:""}${e.message}`},t))}),l.loadError&&(0,n.jsxs)("div",{className:"space-y-3 p-4",children:[(0,n.jsx)(le,{message:l.loadError}),(0,n.jsx)(N.$,{variant:"outline",onClick:l.retry,disabled:l.loading,children:o("重试")})]}),l.loading&&!l.mcp?(0,n.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:o("正在读取配置…")}):l.mcp?(0,n.jsxs)("div",{"aria-busy":l.loading,className:"flex min-h-0 min-w-0 flex-1",children:[l.editor?.kind!=="json"&&l.rows.length>0&&(0,n.jsxs)("div",{className:(0,C.cn)("pi-desk-chat-scrollbar min-h-0 min-w-0 overflow-y-auto",m?"hidden @min-[48rem]/mcp:block @min-[48rem]/mcp:w-56 @min-[48rem]/mcp:shrink-0 @min-[48rem]/mcp:border-r":"flex-1"),children:[!m&&l.error&&(0,n.jsx)("div",{className:"p-4",children:(0,n.jsx)(le,{message:l.error.message})}),(0,n.jsx)(lt,{rows:l.rows,selectedName:g,pending:h,onSelect:e=>{g!==e.name&&l.navigate(()=>e.local?l.startManual(e.name,e.local):l.startInherited(e.name,e.config))}})]}),l.editor?(0,n.jsx)(la,{editor:l.editor,scopeLabel:u,project:null!==l.displayCwd,projectTrusted:l.mcp.projectTrusted,local:l.mcp.local,inherited:l.mcp.inherited,pending:h,saving:l.pending,error:l.error,check:l.check?.name===g?l.check:null,onDraft:l.updateDraft,onJson:l.updateJson,onPreview:l.previewJson,onOverwrite:e=>l.setEditor(t=>t?.kind==="json"?{...t,overwrite:e}:t),onSave:e=>void l.saveEditor(e),onCancel:()=>void l.navigate(()=>l.setEditor(null)),onRemove:e=>void l.remove(e),onDismissCheck:l.dismissCheck},"manual"===l.editor.kind?g??"new":"json"):0===l.rows.length?(0,n.jsx)(li,{pending:h,onAdd:x,onImport:f}):null]}):null]})}var lo=s(267),ld=s(59605),lc=s(55438);let lu=a.Yj().trim().min(1).max(200),lm=a.Yj().trim().min(1).max(100).nullable(),lp=a.Yj().trim().min(1).max(100).nullable(),lh=a.Yj().trim().min(1).max(200),lg=a.Ik({label:a.Yj().trim().min(1).max(64),value:a.Yj().trim().min(1).max(500)}).strict(),lx=a.Yj().trim().min(1).max(300).nullable(),lf=a.k5(["running","completed","failed","stopped","interrupted"]),lb=a.Ik({taskId:lu,taskKind:lm,taskType:lp,title:lh,info:a.YO(lg).max(12),status:lf,activity:lx,startedAt:rj.k,endedAt:rj.k.nullable()}).strict().superRefine((e,t)=>{"running"===e.status&&null!==e.endedAt&&t.addIssue({code:"custom",message:"running task requires endedAt=null",path:["endedAt"]}),"running"!==e.status&&null===e.endedAt&&t.addIssue({code:"custom",message:"terminal task requires endedAt",path:["endedAt"]})}),lv=a.Ik({tasks:a.YO(lb)}).strict().superRefine((e,t)=>{let s=new Set;for(let[n,r]of e.tasks.entries())s.has(r.taskId)&&t.addIssue({code:"custom",message:"taskId values must be unique",path:["tasks",n,"taskId"]}),s.add(r.taskId)}),lw=a.Ik({kind:a.eu("text"),text:a.Yj(),truncated:a.zM()}).strict(),ly=ld.RX.extend({kind:a.eu("conversation"),truncated:a.zM()}).strict(),lk=a.KC([a.ch(),lw,ly]),lj=a.Ik({taskId:lu,canInterrupt:a.zM(),body:lk}).strict(),lN=lc.mv,lI=a.KC([a.Ik({type:a.eu("snapshot"),snapshot:lj}).strict(),a.Ik({type:a.eu("text_append"),text:a.Yj().min(1)}).strict(),a.Ik({type:a.eu("conversation_event"),event:lN}).strict(),a.Ik({type:a.eu("unavailable")}).strict()]);a.Ik({source:lo.R,taskId:lu,entryId:sK.Rv}).strict().extend({imageIndex:a.ai().int().nonnegative()}).strict();let lC=a.Ik({source:lo.R,taskId:lu.nullable()}).strict(),lS=a.Ik({snapshot:lj.nullable()}).strict(),lM=a.Ik({source:lo.R,taskId:lu}).strict(),lz=a.Ik({}).strict(),lE=a.Ik({source:lo.R,taskId:lu,event:lI}).strict(),lA=Object.freeze({detailWatch:(0,i.Vc)({path:"task-center/detail-watch",inputSchema:lC,outputSchema:lS}),interrupt:(0,i.Vc)({path:"task-center/interrupt",inputSchema:lM,outputSchema:lz}),detailEvent:(0,i._G)({path:"task-center/detail-event",bodySchema:lE})});var l$=s(45811),lR=s(14510),lT=s(12019),lP=s(86075),lD=s(84571),lO=s(67011);let lL=({className:e,...t})=>(0,n.jsx)(lO.z,{className:(0,C.cn)("relative flex-1 overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...t}),lF=({className:e,...t})=>(0,n.jsx)(lO.z.Content,{className:(0,C.cn)("flex flex-col gap-8 p-4",e),...t});var l_=s(47744),lB=s(30973),lq=s(14203),lW=s(26575),lY=s(11953);function lU({onOpenChange:e,...t}){let s=(0,r.useRef)(null);return(0,n.jsx)(l_.j,{"data-slot":"hover-card",...t,onOpenChange:(t,n)=>{if(e?.(t,n),n.isCanceled)return;if(t){s.current=n.trigger??null;return}let r=s.current;s.current=null,"escape-key"===n.reason&&r instanceof HTMLElement&&r.ownerDocument.activeElement===r&&r.blur()}})}function lV({...e}){return(0,n.jsx)(lB.Z,{"data-slot":"hover-card-trigger",...e})}function lK({className:e,side:t="bottom",sideOffset:s=4,align:r="center",alignOffset:a=4,...i}){return(0,n.jsx)(lq.D,{"data-slot":"hover-card-portal",children:(0,n.jsx)(lW.p,{align:r,alignOffset:a,side:t,sideOffset:s,className:"isolate z-50",children:(0,n.jsx)(lY.p,{"data-slot":"hover-card-content",className:(0,C.cn)("z-50 w-80 max-w-[calc(100vw-2rem)] origin-(--transform-origin) rounded-lg border border-border bg-popover p-3 text-sm text-popover-foreground shadow-md outline-hidden duration-100 motion-reduce:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...i})})})}let lH=({className:e,...t})=>(0,n.jsx)(ny.Sq,{align:"block-end",className:(0,C.cn)("justify-between gap-1",e),...t}),lG=({className:e,...t})=>(0,n.jsx)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-1",e),...t}),lJ=({variant:e="ghost",className:t,size:s,tooltip:a,...i})=>{let l=s??(r.Children.count(i.children)>1?"sm":"icon-sm"),o=(0,n.jsx)(ny.Ik,{className:(0,C.cn)(t),size:l,type:"button",variant:e,...i});if(!a)return o;let d="string"==typeof a?a:a.content,c="string"==typeof a?void 0:a.shortcut,u="string"==typeof a?"top":a.side??"top";return(0,n.jsxs)(tU.m_,{children:[(0,n.jsx)(tU.k$,{render:o}),(0,n.jsxs)(tU.ZI,{side:u,children:[d,c&&(0,n.jsx)("span",{className:"ml-2 text-muted-foreground",children:c})]})]})},lQ=a.Ik({input:a.g1(a.Yj(),a.Pq())}).strict(),lX=a.Ik({output:a.Yj()}).strict(),lZ="pideskHelp",l0=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,l1=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function l2(e){return/^[a-zA-Z0-9_./:@=+-]+$/.test(e)?e:JSON.stringify(e)}let l5=a.Ik({name:a.Yj(),scope:a.eu("global").optional(),source:a.Yj(),kind:a.k5(["package","extension"]),version:a.Yj().nullable(),status:a.k5(["ready","available","disabled","failed"]),updateTag:a.Yj().nullish(),availableVersion:a.Yj().nullish(),updateError:a.Yj().nullish(),operation:a.Ik({action:a.k5(["add","update","del","apply"]),phase:a.k5(["queued","checking","applying","waiting","failed"]),message:a.Yj().nullable()}).strict().nullish(),error:a.Ik({phase:a.k5(["package","entry","setup","resources","resolve","native"]),message:eH.qf}).strict().nullish()}).strict(),l3=a.Ik({plugins:a.YO(l5),restartRequired:a.zM(),loadError:eH.qf.nullish()}).strict(),l4=l5.extend({detail:a.g1(a.Yj(),a.Pq())}).strict(),l6=a.Ik({version:a.Yj(),environment:a.k5(["development","production"]),mode:a.k5(["basic","normal"]),cwd:a.Yj(),agentDir:a.Yj(),docsDirectory:a.Yj()}).strict(),l8=null,l7=new WeakMap,l9=new WeakMap,oe=new WeakMap;function ot(e){switch(e.fixed.type){case"user":{let t=ld.lJ.safeParse(e.summary);return{summary:{type:"user",...t.success?t.data:{text:"",images:[]},hasDetail:!1},detail:void 0}}case"assistant":{let t="pi-desk/assistant"===e.fixed.viewKey?ld.Er.safeParse(e.summary):null,s=t?.success?t.data:{text:"",errorMessage:null},n="pi-desk/assistant"===e.fixed.viewKey?ld.Rh.safeParse(e.detail):null;return{summary:{type:"assistant",text:s.text,model:"model"in s?s.model:null,errorMessage:s.errorMessage,status:e.fixed.status,usage:e.fixed.usage,hasDetail:e.fixed.hasDetail},detail:n?.success?{type:"assistant",...n.data}:void 0}}case"tool":{let t={name:e.fixed.viewKey,reasoning:null,inputPreview:null,activity:null},s={status:e.fixed.status,usage:e.fixed.usage,hasDetail:e.fixed.hasDetail};switch(e.fixed.viewKey){case"pi-desk/codemode":{let n=ld.UT.safeParse(e.summary),r=n.success?n.data:t,a=ld.ny.safeParse(e.detail);return{summary:{type:"tool",kind:"codemode",...r,...s},detail:a.success?{type:"tool",kind:"codemode",...a.data}:void 0}}case"pi-desk/pidesk":{let n=lQ.safeParse(e.summary),r=n.success?n.data:{input:{}},a=lX.safeParse(e.detail);return{summary:{type:"tool",kind:"pidesk",...t,...r,...s},detail:a.success?{type:"tool",kind:"pidesk",output:a.data.output}:void 0}}case"pi-desk/bash-tool":{let n=ld.Qi.safeParse(e.summary),r=n.success?n.data:{...t,timing:null},a=ld.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"bash",...r,...s},detail:a.success?{type:"tool",kind:"bash",output:a.data.output}:void 0}}case"pi-desk/read":{let n=ld.Gx.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=ld.Xj.safeParse(e.detail);return{summary:{type:"tool",kind:"read",...r,...s},detail:a.success?{type:"tool",kind:"read",content:a.data.content}:void 0}}case"pi-desk/edit":{let n=ld.aV.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=ld.Rk.safeParse(e.detail);return{summary:{type:"tool",kind:"edit",...r,...s},detail:a.success?{type:"tool",kind:"edit",contentKind:a.data.kind,content:a.data.content}:void 0}}case"pi-desk/write":{let n=ld.bN.safeParse(e.summary),r=n.success?n.data:{...t,path:null},a=ld.O_.safeParse(e.detail);return{summary:{type:"tool",kind:"write",...r,...s},detail:a.success?{type:"tool",kind:"write",contentKind:a.data.kind,content:a.data.content}:void 0}}default:{let n=ld.Px.safeParse(e.summary),r=n.success?n.data:t,a=ld.Ok.safeParse(e.detail);return{summary:{type:"tool",kind:"generic",...r,...s},detail:a.success?{type:"tool",kind:"generic",output:a.data.output}:void 0}}}}case"bash":{let t=ld.ai.safeParse(e.summary),s=t.success?t.data:{command:e.fixed.viewKey},n=ld.bG.safeParse(e.detail);return{summary:{type:"bash",command:s.command,status:e.fixed.status,hasDetail:e.fixed.hasDetail},detail:n.success?{type:"bash",...n.data}:void 0}}case"custom":{if("pi-desk/compaction"===e.fixed.viewKey){let t=ld.sL.safeParse(e.detail);return{summary:{type:"compaction",hasDetail:e.fixed.hasDetail},detail:t.success?{type:"compaction",...t.data}:void 0}}let t=ld.Rt.safeParse(e.summary);return{summary:{type:"custom",text:(t.success?t.data:{text:""}).text,hasDetail:!1},detail:void 0}}}}function os(e){return e.temporary||"status"in e.summary&&"running"===e.summary.status}function on(e){return"assistant"===e.summary.type&&("error"===e.summary.status||!!e.summary.errorMessage||(e.detail?.type==="assistant"?e.detail.thinking.trim().length>0:e.summary.hasDetail))}function or(e,t,s){if("compaction"===s.summary.type){oa(e,t),e.push({identity:s.identity,user:null,processItems:[],finalAssistant:null,compaction:s,running:os(s),toolCount:0});return}"user"!==s.summary.type?t.body.push(s):(oa(e,t),t.user=s)}function oa(e,t){if(!t.user&&0===t.body.length)return;let s=t.user?.identity??t.body[0].identity;e.push(function(e,t,s){let n=function(e){for(let t=e.length-1;t>=0;t-=1){let s=e[t];if("custom"!==s.summary.type){if("assistant"!==s.summary.type)return -1;return s.summary.text.trim()||"pi-desk/assistant"!==s.viewKey?t:-1}}return -1}(s),r=n>=0?s[n]:null,a=[];for(let[e,t]of s.entries()){if(e!==n){("assistant"!==t.summary.type||"pi-desk/assistant"!==t.viewKey||t.summary.text.trim().length>0||on(t))&&a.push({message:t,hideAssistantText:!1});continue}on(t)&&a.push({message:t,hideAssistantText:!0})}return{identity:e,user:t,processItems:a,finalAssistant:r,compaction:null,running:s.some(os),toolCount:s.filter(e=>"tool"===e.summary.type||"bash"===e.summary.type).length}}(s,t.user,t.body)),t.user=null,t.body=[]}function oi(e,t=!1){let s=function(e){let t=oe.get(e);if(t)return t;let s=[],n={user:null,body:[]},r=new Set,a=[],i=(e[0]?.location.index??0)>0;for(let t of e){if(r.has(t.location.entryId))continue;r.add(t.location.entryId);let e=function(e){let t=l7.get(e);if(t)return t;let s=ot(e),n={identity:`position:${e.location.index}`,position:e.location.index,viewKey:e.fixed.viewKey,snapshot:e,...s,temporary:!1,timestampMs:e.fixed.timestampMs,durable:e,tempId:null};return l7.set(e,n),n}(t);"compaction"===e.summary.type?(a=[],i=!1):"assistant"===t.fixed.type&&(a.push(e),"assistant"===e.summary.type&&null!==e.timestampMs&&(e.summary.text.trim()||"pi-desk/assistant"!==e.viewKey)&&(e={...e,usageCalls:a,usageIncomplete:i},a=[],i=!1)),or(s,n,e)}let l={turns:s,user:n.user,body:n.body};return oe.set(e,l),l}(e.messages),n=[...s.turns],r={user:s.user,body:[...s.body]};for(let[t,s]of e.temporaryMessages.entries())or(n,r,function(e,t){let s=l9.get(e);if(s?.position===t)return s.message;let n=ot(e),r={identity:`position:${t}`,position:t,viewKey:e.fixed.viewKey,snapshot:e,...n,temporary:!0,timestampMs:e.fixed.timestampMs,durable:null,tempId:e.location.tempId};return l9.set(e,{position:t,message:r}),r}(s,e.messages.length+t));oa(n,r);let a=n.at(-1);return t&&a&&!a.compaction&&(a.running=!0),n}function ol(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}function oo(e){return 0===e?"$0":e<1e-4?"<$0.0001":`$${e.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function od(e,t=Date.now(),s="en",n="UTC"){let r=new Date(e),a=new Date(t),i=function(e,t){if(l8?.locale===e&&l8.timeZone===t)return l8;let s="en"===e?"en-US":"zh-CN";return l8={locale:e,timeZone:t,compactTime:new Intl.DateTimeFormat(s,{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),compactDateTime:new Intl.DateTimeFormat(s,{timeZone:t,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),fullDateTime:new Intl.DateTimeFormat(s,{timeZone:t,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),dateKey:new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"})}}(s,n);return{compact:i.dateKey.format(r)===i.dateKey.format(a)?i.compactTime.format(r):i.compactDateTime.format(r),full:i.fullDateTime.format(r)}}function oc(e,t,s={}){if("1"!==new URLSearchParams(window.location.search).get("chatScrollDebug"))return;let n=op(t);console.info("[Pi Desk][ChatScroll]",e,{time:Math.round(10*performance.now())/10,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,distanceFromBottom:t.scrollHeight-t.scrollTop-t.clientHeight,tailSpace:n?oh(n):0,tailMinHeight:n?.style.minHeight||null,tailAnchor:n?.dataset.chatTailAnchor??null,...s})}function ou(e,t,s){let n=Array.from(e.querySelectorAll(`[${t}]`));return void 0===s?n.at(-1)??null:n.find(e=>e.getAttribute(t)===s)??null}function om(e){let t,s=(t=e.querySelectorAll("[data-chat-turn]")).item(t.length-1);return s?.hasAttribute("data-chat-logical-tail")?s:null}function op(e){return e.querySelector("[data-chat-tail-space]")}function oh(e){let t=e.lastElementChild;return t instanceof HTMLElement?Math.max(0,e.getBoundingClientRect().bottom-t.getBoundingClientRect().bottom):0}function og(e,t,s,n){let r=e.getBoundingClientRect(),a=e.scrollTop,i=Math.max(0,a+t.getBoundingClientRect().top-r.top-n),l=a+s.getBoundingClientRect().top-r.top;return{targetScrollTop:i,minHeight:Math.max(0,i+e.clientHeight-l-function(e){let t=e.parentElement;if(!t)return 0;let s=Number.parseFloat(getComputedStyle(t).paddingBottom);return Number.isFinite(s)?s:0}(s))}}function ox(e){for(let t of e.querySelectorAll("[data-chat-tail-space]"))oc("tail:clear:start",e),t.style.removeProperty("min-height"),delete t.dataset.chatTailSpace,delete t.dataset.chatTailAnchor,delete t.dataset.chatTailOffset,oc("tail:clear:end",e)}function of(e){let t=op(e);if(!t)return;if(t!==om(e))return void ox(e);let s=t.dataset.chatTailAnchor,n=Number.parseFloat(t.dataset.chatTailOffset??"");if(!s||!Number.isFinite(n))return;let r=ou(e,"data-chat-scroll-anchor",s);if(!r)return void ox(e);let{minHeight:a}=og(e,r,t,n),i=`${Math.ceil(a)}px`;t.style.minHeight!==i&&(oc("tail:refresh:start",e,{nextMinHeight:i}),t.style.minHeight=i,oc("tail:refresh:end",e,{nextMinHeight:i}))}function ob(e,t,s,n){oc("position:start",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n}),ox(e);let r=n?om(e):null;if(!r){e.scrollTop=Math.max(0,e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-s),oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n});return}let{targetScrollTop:a,minHeight:i}=og(e,t,r,s);r.style.minHeight=`${Math.ceil(i)}px`,r.dataset.chatTailSpace="";let l=t.dataset.chatScrollAnchor;l&&(r.dataset.chatTailAnchor=l),r.dataset.chatTailOffset=String(s),e.scrollTop=a,oc("position:end",e,{target:t.dataset.chatScrollAnchor??null,offset:s,addTailSpace:n,minHeight:i})}function ov({active:e=!0}){let{scrollRef:t,state:s}=(0,lO.B)();return(0,r.useEffect)(()=>{let n,r=t.current;if(!r||!e)return;let a=null,i=new Set,l=()=>{null===a&&(a=window.requestAnimationFrame(()=>{a=null,of(r)}))},o=new ResizeObserver(l),d=()=>{let e=new Set,t=op(r);if(t)for(let s of t.children)s instanceof HTMLElement&&e.add(s);for(let t of i)e.has(t)||o.unobserve(t);for(let t of e)i.has(t)||o.observe(t);i=e},c=new MutationObserver(()=>{d(),l()}),u=0,m=null,p=null,h=new ResizeObserver(([e])=>{let t=e?.contentRect.height;if(void 0===t)return;let i=t-(n??t);(n=t,i)?(oc("viewport:resize",r,{difference:i,isAtBottom:s.isAtBottom,escapedFromLock:s.escapedFromLock}),u=i,s.resizeDifference=i,null!==a&&(window.cancelAnimationFrame(a),a=null),of(r),s.isAtBottom&&(s.scrollTop=Math.max(0,s.calculatedTargetScrollTop)),oc("viewport:resize:positioned",r,{difference:i}),null!==m&&window.cancelAnimationFrame(m),null!==p&&window.clearTimeout(p),m=window.requestAnimationFrame(()=>{m=null,p=window.setTimeout(()=>{p=null,s.resizeDifference===i&&(s.resizeDifference=0),u=0},1)})):l()});return c.observe(r,{attributes:!0,attributeFilter:["data-chat-tail-space","data-chat-logical-tail"],childList:!0,subtree:!0}),h.observe(r),d(),l(),()=>{null!==a&&window.cancelAnimationFrame(a),null!==m&&window.cancelAnimationFrame(m),null!==p&&window.clearTimeout(p),u&&s.resizeDifference===u&&(s.resizeDifference=0),c.disconnect(),o.disconnect(),h.disconnect()}},[e,t,s]),null}function ow(e){let t=[e.user,...e.processItems.map(e=>e.message),e.finalAssistant,e.compaction].filter(e=>null!==e),s=new Set;return t.filter(e=>!s.has(e.identity)&&(s.add(e.identity),!0))}function oy(e,t,s){let n=0;for(let r=t;r<s;r+=1)e[r]?.user&&(n+=1);return n}function ok(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,oy(e,0,s)),r=s,a=0,i=0,l=0;for(;r>0;){let t=e[r-1],s=ow(t).length,o=l<n;if(a>0&&!o&&(a>=30||i+s>200))break;r-=1,a+=1,i+=s,t.user&&(l+=1)}return r}function oj(e,t){let s=Math.max(0,Math.min(e.length,t)),n=Math.min(2,oy(e,s,e.length)),r=s,a=0,i=0,l=0;for(;r<e.length;){let t=e[r],s=ow(t).length,o=l<n;if(a>0&&!o&&(a>=30||i+s>200))break;r+=1,a+=1,i+=s,t.user&&(l+=1)}return r}function oN(e){return{startIndex:ok(e,e.length),endIndex:e.length}}function oI(e,t){let s,n;if(0===e.length)return{startIndex:0,endIndex:0};if(!t)return oN(e);let r=(n=(s=t.lastIndexOf(":"))>0?t.slice(0,s):t,e.findIndex(e=>ow(e).some(e=>e.identity===n)));if(r<0)return oN(e);let a=Math.min(e.length,r+1+10);return{startIndex:ok(e,a),endIndex:a}}function oC({active:e=!0,turns:t,focusTurnIdentity:s,initialAnchor:a,children:i}){let{scrollRef:l}=(0,lO.B)(),[o,d]=(0,r.useState)(()=>({...oI(t,a),turnCount:t.length,focusTurnIdentity:s}));e||o.focusTurnIdentity===s||d({...o,focusTurnIdentity:s});let c=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useMemo)(()=>{if(0===t.length)return{startIndex:0,endIndex:0};if(e&&o.focusTurnIdentity!==s)return oN(t);if(0===o.turnCount&&0===o.endIndex)return oI(t,a);let n=o.endIndex>=o.turnCount;return{startIndex:Math.min(o.startIndex,t.length),endIndex:n?t.length:Math.max(o.startIndex,Math.min(o.endIndex,t.length))}},[e,s,a,t,o]),p=(0,r.useCallback)(e=>{d({...e,turnCount:t.length,focusTurnIdentity:s})},[s,t.length]),h=(0,r.useCallback)(()=>{let e=l.current,t=e?.querySelector("[data-chat-turn]");e&&t?.dataset.chatTurn&&(c.current={turnIdentity:t.dataset.chatTurn,offset:t.getBoundingClientRect().top-e.getBoundingClientRect().top})},[l]),g=(0,r.useCallback)(()=>{if(m.startIndex<=0||u.current)return;let e=ok(t,m.startIndex);if(e>=m.startIndex)return;h();let s=l.current;s&&oc("window:expand-earlier",s,{previousStartIndex:m.startIndex,nextStartIndex:e}),u.current=!0,p({...m,startIndex:e})},[h,p,m,l,t]),x=(0,r.useCallback)(()=>{if(m.endIndex>=t.length||u.current)return;let e=oj(t,m.endIndex);e<=m.endIndex||(u.current=!0,p({...m,endIndex:e}))},[p,m,t]),f=(0,r.useCallback)(e=>{!Number.isSafeInteger(e)||e<0||e>=t.length||e>=m.startIndex&&e<m.endIndex||(e<m.startIndex?p({...m,startIndex:Math.min(e,ok(t,e+1))}):p({...m,endIndex:Math.max(e+1,oj(t,e))}))},[p,m,t]),b=(0,r.useCallback)(()=>{p(oN(t))},[p,t]);(0,r.useLayoutEffect)(()=>{var e;u.current=!1;let t=c.current;if(!t)return;let s=l.current,n=s?(e=t.turnIdentity,Array.from(s.querySelectorAll("[data-chat-turn]")).find(t=>t.dataset.chatTurn===e)??null):null;if(c.current=null,!s||!n)return;let r=n.getBoundingClientRect().top-s.getBoundingClientRect().top,a=r-t.offset;oc("window:anchor-correction:start",s,{turnIdentity:t.turnIdentity,previousOffset:t.offset,nextOffset:r,correction:a}),s.scrollTop+=a,oc("window:anchor-correction:end",s,{turnIdentity:t.turnIdentity,correction:a})},[m.endIndex,m.startIndex,l]),(0,r.useLayoutEffect)(()=>{let s=l.current;if(!s||!e)return;let n=null,r=()=>{(n=null,s.scrollTop<=24&&m.startIndex>0)?g():s.scrollHeight-s.scrollTop-s.clientHeight<=24&&m.endIndex<t.length&&x()},a=()=>{null===n&&(n=window.requestAnimationFrame(r))},i=e=>{e.deltaY<0&&s.scrollTop<=24?g():e.deltaY>0&&a()},o=()=>{s.scrollTop<=24?g():a()};return s.addEventListener("scroll",a,{passive:!0}),s.addEventListener("wheel",i,{passive:!0}),s.addEventListener("touchmove",o,{passive:!0}),()=>{s.removeEventListener("scroll",a),s.removeEventListener("wheel",i),s.removeEventListener("touchmove",o),null!==n&&window.cancelAnimationFrame(n)}},[e,m,g,x,l,t.length]);let v=(0,r.useMemo)(()=>t.slice(m.startIndex,m.endIndex),[m.endIndex,m.startIndex,t]),w=(0,r.useMemo)(()=>({...m,visibleTurns:v,containsTail:m.endIndex>=t.length,revealTurn:f,resetToTail:b}),[m,b,f,t.length,v]);return(0,n.jsx)(n.Fragment,{children:i(w)})}let oS={canMoveUp:!1,canMoveDown:!1,hasNextMessage:!1};function oM(e,t,s,n){let r=0,a=e.length;for(;r<a;){let i=Math.floor((r+a)/2),l=e[i].getBoundingClientRect().top-t;(n?l>=s:l>s)?a=i:r=i+1}return r}function oz(e){return e.user?`${e.user.identity}:user`:null}function oE(e,t,s){let n,r=Array.from(e.querySelectorAll("[data-chat-user-message]")),a=e.getBoundingClientRect().top+12,i=oM(r,a,-2,!0),l=oM(r,a,2,!1),o=s.find(e=>e>=t.startIndex&&e<t.endIndex),d=s.findLast(e=>e>=t.startIndex&&e<t.endIndex),c=0===i?s.findLast(e=>e<(o??t.startIndex))??null:null,u=l>=r.length?s.find(e=>e>(d??t.endIndex-1))??null:null,m=e.scrollHeight-e.scrollTop-e.clientHeight,p=(n=op(e))?oh(n):0,h=t.containsTail&&m<=2;return oc("navigation:inspect",e,{containsTail:t.containsTail,tailSpacerHeight:p,atBottom:h,previousMessage:r[i-1]?.dataset.chatUserMessage??null,nextMessage:r[l]?.dataset.chatUserMessage??null,previousOutsideTurnIndex:c,nextOutsideTurnIndex:u}),{previousMessage:r[i-1]??null,nextMessage:r[l]??null,previousOutsideTurnIndex:c,nextOutsideTurnIndex:u,atBottom:h}}function oA({turns:e,window:t}){let{t:s}=(0,f.Bd)("conversation"),{scrollRef:a,scrollToBottom:i,stopScroll:l}=(0,lO.B)(),o=(0,r.useMemo)(()=>e.flatMap((e,t)=>e.user?[t]:[]),[e]),[d,c]=(0,r.useState)(!1),[u,m]=(0,r.useState)(oS),[p,h]=(0,r.useState)(null),g=(0,r.useRef)(null),x=(0,r.useRef)(!1),b=(0,r.useRef)(!1),v=(0,r.useRef)(null),w=(0,r.useRef)(null),y=(0,r.useRef)(!1),k=(0,r.useRef)(null),j=(0,r.useRef)(!1),I=(0,r.useRef)(!1),C=(0,r.useCallback)(e=>{var s;let n,r=(n=!(s=oE(e,t,o)).atBottom,{canMoveUp:null!==s.previousMessage||null!==s.previousOutsideTurnIndex,canMoveDown:n,hasNextMessage:n&&(null!==s.nextMessage||null!==s.nextOutsideTurnIndex)});y.current&&(r.canMoveDown=!1),m(e=>e.canMoveUp===r.canMoveUp&&e.canMoveDown===r.canMoveDown&&e.hasNextMessage===r.hasNextMessage?e:r)},[t,o]),S=(0,r.useCallback)(e=>{null===w.current&&(w.current=window.requestAnimationFrame(()=>{w.current=null,C(e)}))},[C]),M=(0,r.useCallback)(()=>{null!==v.current&&(window.clearTimeout(v.current),v.current=null)},[]),z=(0,r.useCallback)(()=>{M(),b.current||(v.current=window.setTimeout(()=>{v.current=null,x.current=!1,c(!1),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null)},2e3))},[M]),E=(0,r.useCallback)(()=>{null!==g.current&&window.clearTimeout(g.current),g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},[]),R=(0,r.useCallback)(e=>{null!==g.current&&window.clearTimeout(g.current),h({index:e,visible:!0}),g.current=window.setTimeout(()=>{g.current=null,h(e=>e?.visible?{...e,visible:!1}:e)},2e3)},[]),T=(0,r.useCallback)(()=>{let e=a.current;e&&(x.current||m(oS),x.current=!0,c(!0),S(e),z())},[S,z,a]);(0,r.useLayoutEffect)(()=>{let e=a.current;if(!e)return;let s=k.current;if(s){let n=Array.from(e.querySelectorAll("[data-chat-scroll-anchor]")).find(e=>e.dataset.chatScrollAnchor===s.anchor);n&&(k.current=null,l(),ob(e,n,12,t.containsTail))}j.current&&t.containsTail&&(j.current=!1,ox(e),Promise.resolve(i({animation:"instant"})).finally(()=>{y.current=!1,I.current&&x.current&&S(e)}))},[S,a,i,l,t.containsTail,t.endIndex,t.startIndex]),(0,r.useLayoutEffect)(()=>{let e=a.current;if(!e)return;I.current=!0;let t=()=>{E(),T()},s=()=>{x.current&&S(e)},n=t=>{t.target===e&&E()},r=e=>{["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&E()};return e.addEventListener("wheel",t,{passive:!0}),e.addEventListener("touchmove",t,{passive:!0}),e.addEventListener("pointerdown",n,{passive:!0}),e.addEventListener("keydown",r),e.addEventListener("scroll",s,{passive:!0}),()=>{e.removeEventListener("wheel",t),e.removeEventListener("touchmove",t),e.removeEventListener("pointerdown",n),e.removeEventListener("keydown",r),e.removeEventListener("scroll",s),null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null),I.current=!1}},[E,S,a,T]),(0,r.useLayoutEffect)(()=>()=>{M(),null!==g.current&&window.clearTimeout(g.current),y.current=!1,k.current=null,j.current=!1},[M]),(0,r.useLayoutEffect)(()=>{d&&(u.canMoveUp||u.canMoveDown)||(b.current=!1)},[u.canMoveDown,u.canMoveUp,d]);let P=(0,r.useCallback)((s,n)=>{let r=a.current;if(!r)return;T();let d=oE(r,t,o),c="up"===s?d.previousMessage:d.atBottom?null:d.nextMessage;if(c){let s=o.findIndex(t=>oz(e[t])===c.dataset.chatScrollAnchor);s>=0&&R(s+1),y.current=!1,l(),ob(r,c,12,t.containsTail)}else{let a="up"===s?d.previousOutsideTurnIndex:d.nextOutsideTurnIndex;if(null!==a){let s=oz(e[a]);s&&(R(o.indexOf(a)+1),y.current=!1,k.current={anchor:s},t.revealTurn(a))}else"down"===s&&(o.length>0&&R(o.length),n&&(n.disabled=!0),m(e=>e.canMoveDown?{...e,canMoveDown:!1}:e),d.atBottom||y.current||(oc("navigation:bottom:start",r,{containsTail:t.containsTail}),y.current=!0,ox(r),t.containsTail?Promise.resolve(i({animation:"instant"})).finally(()=>{y.current=!1,I.current&&x.current&&S(r)}):(j.current=!0,t.resetToTail())))}S(r)},[S,a,i,T,R,l,e,t,o]),D=d&&(u.canMoveUp||u.canMoveDown),O=s(u.hasNextMessage?"nextUserMessage":"bottom");return(0,n.jsxs)(n.Fragment,{children:[p&&o.length>0?(0,n.jsxs)("div",{role:"status","aria-hidden":!p.visible,"aria-label":`${s("userNavigation")} ${p.index} / ${o.length}`,className:`pointer-events-none absolute top-1/2 left-3 z-10 -translate-y-1/2 rounded-lg border bg-background/95 px-2 py-2 shadow-sm transition-opacity duration-150 motion-reduce:transition-none sm:left-4 ${p.visible?"opacity-100":"opacity-0"}`,children:[(0,n.jsxs)("div",{className:"text-center text-sm font-medium tabular-nums",children:[p.index," / ",o.length]}),(0,n.jsx)("div",{className:"relative mx-auto mt-2 h-28 w-0.5 rounded-full bg-border",children:(0,n.jsx)("span",{className:"absolute left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground",style:{top:`${(p.index-1)/Math.max(1,o.length-1)*100}%`}})})]}):null,D?(0,n.jsxs)(tY,{orientation:"vertical",className:"absolute right-3 bottom-4 z-10 rounded-lg shadow-sm sm:right-4","aria-label":s("userNavigation"),onMouseEnter:()=>{b.current=!0,M()},onMouseLeave:()=>{b.current=!1,x.current&&z()},children:[(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveUp,"aria-label":s("previousUserMessage"),title:s("previousUserShort"),onClick:()=>P("up"),children:(0,n.jsx)(A.A,{className:"size-4"})}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"icon",className:"size-10 bg-background/90 backdrop-blur dark:bg-background/90",disabled:!u.canMoveDown,"aria-label":O,title:O,onClick:e=>P("down",e.currentTarget),children:(0,n.jsx)($.A,{className:"size-4"})})]}):null]})}let o$=(0,r.createContext)({basic:!1});function oR({basic:e,onRecover:t,children:s}){let a=(0,r.useMemo)(()=>({basic:e,recover:t}),[e,t]);return(0,n.jsx)(o$.Provider,{value:a,children:s})}function oT(e){return{location:e.snapshot.location,fixed:e.snapshot.fixed,summary:e.snapshot.summary,...void 0===e.snapshot.detail?{}:{detail:e.snapshot.detail}}}class oP{constructor(e,t){this.listeners=new Set,this.pending=null,this.requestEpoch=0,this.disposed=!1,this.basic=!1,this.message=e,this.snapshot=oT(e),this.loader=t,this.detailLoaded=void 0!==this.snapshot.detail||!this.snapshot.fixed.hasDetail}getSnapshot(){return this.snapshot}subscribe(e){if(this.disposed)throw Error("Message Handle has been disposed");return this.listeners.add(e),()=>{this.listeners.delete(e)}}loadDetail(){if(this.detailLoaded)return Promise.resolve(this.snapshot.detail??null);if(!this.snapshot.fixed.hasDetail)return Promise.resolve(null);if(!("entryId"in this.snapshot.location))return Promise.reject(Error("Temporary Message 不能读取 canonical Detail"));if(this.pending)return this.pending;let e=this.requestEpoch,t=this.loader(this.message).then(t=>(this.disposed||e!==this.requestEpoch||(this.detailLoaded=!0,this.snapshot={...this.snapshot,...null===t?{}:{detail:t}},this.notify()),t)).finally(()=>{this.pending===t&&(this.pending=null)});return this.pending=t,t}replace(e,t,s){if(this.disposed)return;let n=oT(e);if(this.snapshot===n)return;let r=this.basic!==s||void 0!==this.snapshot.detail&&void 0===n.detail||this.snapshot.fixed.viewKey!==n.fixed.viewKey||"entryId"in this.snapshot.location&&"entryId"in n.location&&this.snapshot.location.entryId!==n.location.entryId;this.basic=s,this.message=e,this.loader=t,this.snapshot=n,r?(this.requestEpoch+=1,this.pending=null,this.detailLoaded=void 0!==n.detail||!n.fixed.hasDetail):void 0===n.detail&&n.fixed.hasDetail||(this.detailLoaded=!0),this.notify()}dispose(){this.disposed||(this.disposed=!0,this.listeners.clear(),this.requestEpoch+=1,this.pending=null)}notify(){for(let e of[...this.listeners])e()}}function oD({message:e,pluginName:t,contributionName:s,phase:a,error:i,handle:l,fallback:o,onRetry:d}){let{t:c}=(0,f.Bd)("conversation"),[u,m]=(0,r.useState)(l.getSnapshot().detail),[p,h]=(0,r.useState)(!1),[g,x]=(0,r.useState)(null),v=(0,r.useContext)(o$),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),I=i.name,C=i.message,S=i.stack;return(0,r.useEffect)(()=>{console.error("[Pi Desk][MessageView] 消息视图无法展示",{messageId:e.identity,viewKey:e.viewKey,pluginName:t,contributionName:s,phase:a,errorName:I,message:C,stack:S})},[e.identity,e.viewKey,t,s,a,I,C,S]),(0,n.jsxs)("div",{className:"space-y-2","data-message-id":e.identity,children:[o,(0,n.jsx)("div",{role:"alert",className:"rounded-lg border border-destructive/35 bg-muted/30 p-3 text-sm",children:(0,n.jsxs)("div",{className:"flex items-start gap-2",children:[(0,n.jsx)(eB.A,{className:"mt-0.5 size-4 shrink-0 text-destructive"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"font-medium text-destructive",children:c("viewFailed")}),"pi-desk/message-declaration-error"===e.viewKey&&"string"==typeof e.snapshot.summary.text&&e.snapshot.summary.text.length>0?(0,n.jsx)("p",{className:"mt-2 whitespace-pre-wrap break-words text-foreground",children:e.snapshot.summary.text}):null,(0,n.jsxs)(eY,{error:i,children:[(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[t??"Host"," \xb7 ",s??c("reservedView")," \xb7 ",e.viewKey," ","\xb7 ",a]}),(0,n.jsxs)("details",{className:"text-sm",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:c("publicSnapshot")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(l.getSnapshot(),null,2)})]}),!e.temporary&&e.snapshot.fixed.hasDetail&&void 0===u?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:p,onClick:()=>{h(!0),x(null),l.loadDetail().then(m,e=>{x(e instanceof Error?e.message:c("detailFailed"))}).finally(()=>h(!1))},children:[p?(0,n.jsx)(b.A,{className:"animate-spin"}):null,c("loadDetail")]}):null,g?(0,n.jsx)("p",{className:"text-sm text-destructive [overflow-wrap:anywhere]",children:g}):null,u?(0,n.jsx)("pre",{className:"max-h-48 overflow-auto rounded-md bg-background p-3 font-mono text-sm whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(u,null,2)}):null]}),v.recover?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",className:"mt-2 mr-2",disabled:w,onClick:()=>{y(!0),v.recover().catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>y(!1))},children:[w?(0,n.jsx)(b.A,{className:"animate-spin"}):null,c("useBasicPresentation")]}):null,d?(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",className:"mt-2",disabled:k,onClick:()=>{j(!0),x(null),Promise.resolve().then(d).catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>j(!1))},children:[k?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(et.A,{}),c("retry")]}):null]})]})})]})}function oO({message:e}){let{t}=(0,f.Bd)("conversation");return(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm","aria-busy":"true",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",role:"status",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),t("viewLoading")]}),(0,n.jsxs)("details",{className:"mt-2",children:[(0,n.jsx)("summary",{className:"cursor-pointer text-muted-foreground",children:t("messageContent")}),(0,n.jsx)("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]",children:JSON.stringify(e.snapshot.summary,null,2)})]})]})}function oL({message:e,loadDetail:t,defaultView:s}){let{t:a}=(0,f.Bd)("conversation"),i=(0,J.t4)();(0,J.So)();let l=(0,r.useContext)(o$),o=(0,r.useRef)(null),d=(0,r.useRef)(null),c=(0,r.useRef)(null),[u,m]=(0,r.useState)({status:"loading"}),[p]=(0,r.useState)(()=>new oP(e,t)),[h,g]=(0,r.useState)(0),x=i.getMessageViewResolution(e.viewKey),b=i.areEntriesInitialized(),v=!x&&i.isRefreshingEntries(),w=x?.status==="winner"?`${e.viewKey}\u0000${x.pluginName}\u0000${x.descriptor.contributionName}\u0000${x.descriptor.priority}`:x?.status==="conflict"?`${e.viewKey}\u0000${x.candidates.map(e=>`${e.pluginName}:${e.descriptor.contributionName}`).join(",")}`:e.viewKey,y=x?.status==="winner"?x.pluginName:null,k=x?.status==="winner"?x.descriptor.contributionName:null,j=y?i.getEntryState(y):null,N=j?.status==="ready"?j.runtime:j?.status,I=e.viewKey.startsWith("pi-desk/")&&"pi-desk/message-declaration-error"!==e.viewKey,C=I&&null===x,S=(0,r.useMemo)(()=>({attempt:h,basic:l.basic,resolutionKey:w,winnerIdentity:N}),[h,l.basic,w,N]),M=(0,r.useMemo)(()=>({kind:"message-view",message:{getSnapshot:()=>p.getSnapshot(),subscribe:e=>c.current!==S?()=>void 0:p.subscribe(()=>{if(c.current===S&&y&&i.getEntryState(y)===j)try{e()}catch(e){m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"update",generation:S})}}),loadDetail:async()=>{if(c.current!==S)throw Error("Message View 已释放");let e=await p.loadDetail();if(c.current!==S)throw Error("Message View 已释放");return e}},reportError(e){c.current===S&&y&&i.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"report-error",generation:S})}}),[p,S,i,j,y]);if((0,r.useLayoutEffect)(()=>(c.current=S,p.replace(e,t,l.basic),()=>{c.current===S&&(c.current=null)}),[p,t,e,l.basic,S]),(0,r.useEffect)(()=>{let e={};return d.current=e,()=>{d.current===e&&(d.current=null),queueMicrotask(()=>{null===d.current&&p.dispose()})}},[p]),(0,r.useEffect)(()=>{if(l.basic)return void queueMicrotask(()=>m({status:"loading"}));if(!b||C||"pi-desk/message-declaration-error"===e.viewKey||!y||!k||j?.status!=="ready")return;let t=o.current;if(!t)return;let s=new AbortController,n=!0,r=null;queueMicrotask(()=>{n&&m({status:"loading"})});let a=Promise.resolve().then(()=>n?(r=document.createElement("div"),t.append(r),i.mountContribution({pluginName:y,kind:"message-view",contributionName:k,container:r,target:M,signal:s.signal})):null);return a.then(e=>{n&&e&&i.getEntryState(y)===j&&m(e=>"error"===e.status&&e.generation===S?e:{status:"ready",generation:S})},e=>{n&&i.getEntryState(y)===j&&m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"mount",generation:S})}),()=>{n=!1,s.abort(),r?.remove(),a.then(async e=>{await e?.()},()=>void 0)}},[h,C,b,e.viewKey,S,y,k,j,i,M,l.basic]),l.basic)return(0,n.jsx)(n.Fragment,{children:s});if("pi-desk/message-declaration-error"===e.viewKey)return(0,n.jsx)(oD,{message:e,pluginName:"pi-desk",contributionName:"message-declaration-error",phase:"declaration",error:Error(a("declarationFailed")),handle:p});if(!b)return I?(0,n.jsx)(n.Fragment,{children:s}):(0,n.jsx)(oO,{message:e});if(x?.status==="conflict")return(0,n.jsx)(oD,{message:e,pluginName:null,contributionName:null,phase:"priority-conflict",error:Error(a("viewConflict")),handle:p,fallback:I?s:void 0});if(!x)return I?(0,n.jsx)(n.Fragment,{children:s}):v?(0,n.jsx)(oO,{message:e}):(0,n.jsx)(oD,{message:e,pluginName:null,contributionName:null,phase:"missing-view",error:Error(a("viewMissing",{viewKey:e.viewKey})),handle:p,onRetry:async()=>{await i.refreshEntries(),await Promise.all(i.getFailedEntries().map(({pluginName:e})=>i.retryEntry(e)))}});if("error"===u.status&&u.generation===S)return(0,n.jsx)(oD,{message:e,pluginName:x.pluginName,contributionName:x.descriptor.contributionName,phase:u.phase,error:u.error,handle:p,fallback:I?s:void 0,onRetry:()=>{let e=i.getContributionLoadState(x.pluginName,"message-view",x.descriptor.contributionName);(m({status:"loading"}),"failed"!==e.status)?g(e=>e+1):i.retryContribution(x.pluginName,"message-view",x.descriptor.contributionName).then(()=>g(e=>e+1),e=>{m({status:"error",error:e instanceof Error?e:Error(String(e)),phase:"load",generation:S})})}});let z="ready"===u.status&&u.generation===S;return(0,n.jsxs)("div",{className:"relative","data-message-id":e.identity,"aria-busy":!z,children:[z?null:I?s:(0,n.jsx)(oO,{message:e}),(0,n.jsx)("div",{ref:o,className:z?void 0:"pointer-events-none invisible absolute inset-x-0 top-0","data-pi-desk-plugin":x.pluginName,"data-pi-desk-kind":"message-view","data-pi-desk-contribution":x.descriptor.contributionName})]})}var oF=s(41934),o_=s(4795),oB=s(33353),oq=s(15948),oW=s(7010),oY=s(64572),oU=s(50153);let oV={src:"/_next/static/media/console.fdac8a18.svg",height:16,width:16,blurWidth:0,blurHeight:0},oK={src:"/_next/static/media/docker.1e10aab8.svg",height:24,width:24,blurWidth:0,blurHeight:0},oH={src:"/_next/static/media/git.f893cb5f.svg",height:32,width:32,blurWidth:0,blurHeight:0},oG={src:"/_next/static/media/html.97f145d3.svg",height:32,width:32,blurWidth:0,blurHeight:0},oJ={src:"/_next/static/media/image.69ad851c.svg",height:16,width:16,blurWidth:0,blurHeight:0},oQ={src:"/_next/static/media/javascript.9ef61c53.svg",height:16,width:16,blurWidth:0,blurHeight:0},oX={src:"/_next/static/media/json.eb8fe488.svg",height:960,width:960,blurWidth:0,blurHeight:0},oZ={src:"/_next/static/media/markdown.ee1bbe18.svg",height:32,width:32,blurWidth:0,blurHeight:0},o0={src:"/_next/static/media/nodejs.2f5d7983.svg",height:32,width:32,blurWidth:0,blurHeight:0},o1={src:"/_next/static/media/typescript.cd97905b.svg",height:16,width:16,blurWidth:0,blurHeight:0},o2={src:"/_next/static/media/yaml.8927dd24.svg",height:24,width:24,blurWidth:0,blurHeight:0},o5=new Map(Object.entries({"agents.md":{src:"/_next/static/media/agent.84538518.svg",height:32,width:32,blurWidth:0,blurHeight:0},"skill.md":{src:"/_next/static/media/skill.a97e8eb6.svg",height:16,width:16,blurWidth:0,blurHeight:0},"package.json":o0,"package-lock.json":o0,"npm-shrinkwrap.json":o0,dockerfile:oK,".dockerignore":oK,".gitignore":oH,".gitattributes":oH,".gitmodules":oH})),o3=new Map(Object.entries({ts:o1,mts:o1,cts:o1,tsx:{src:"/_next/static/media/react_ts.3d16336c.svg",height:32,width:32,blurWidth:0,blurHeight:0},js:oQ,mjs:oQ,cjs:oQ,jsx:{src:"/_next/static/media/react.b5a87f7d.svg",height:32,width:32,blurWidth:0,blurHeight:0},json:oX,jsonc:oX,jsonl:oX,yaml:o2,yml:o2,md:oZ,mdx:oZ,png:oJ,jpg:oJ,jpeg:oJ,gif:oJ,webp:oJ,avif:oJ,bmp:oJ,ico:oJ,svg:{src:"/_next/static/media/svg.4aa98763.svg",height:32,width:32,blurWidth:0,blurHeight:0},sh:oV,bash:oV,zsh:oV,fish:oV,ps1:oV,bat:oV,cmd:oV,html:oG,htm:oG,css:{src:"/_next/static/media/css.0d88d948.svg",height:32,width:32,blurWidth:0,blurHeight:0},py:{src:"/_next/static/media/python.e376d0bc.svg",height:24,width:24,blurWidth:0,blurHeight:0}}));function o4({path:e,className:t}){let s=e.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()??"",r=s.includes(".")?s.slice(s.lastIndexOf(".")+1):"",a=o5.get(s)??(s.startsWith("dockerfile.")?oK:void 0)??o3.get(r);return a?(0,n.jsx)(oU.default,{src:a,alt:"","aria-hidden":"true",width:16,height:16,className:t,unoptimized:!0}):(0,n.jsx)(nv.A,{className:t,"aria-hidden":"true"})}var o6=s(47125),o8=s(9922);let o7=new Map,o9=(0,r.memo)(({children:e,as:t="p",className:s,duration:a=2,spread:i=2})=>{let l,o=((l=o7.get(t))||(l=o8.PY1.create(t),o7.set(t,l)),l),d=(0,r.useMemo)(()=>(e?.length??0)*i,[e,i]);return(0,n.jsx)(o,{animate:{backgroundPosition:"0% center"},className:(0,C.cn)("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",s),initial:{backgroundPosition:"100% center"},style:{"--spread":`${d}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{duration:a,ease:"linear",repeat:1/0},children:e})}),de=(0,r.createContext)(null),dt=(0,r.memo)(({className:e,isStreaming:t=!1,open:s,defaultOpen:a,onOpenChange:i,duration:l,children:o,...d})=>{let c=a??t,u=!1===a,[m,p]=(0,o6.i)({defaultProp:c,onChange:i,prop:s}),[h,g]=(0,o6.i)({defaultProp:void 0,prop:l}),x=(0,r.useRef)(t),[f,b]=(0,r.useState)(!1),v=(0,r.useRef)(null);(0,r.useEffect)(()=>{t?(x.current=!0,null===v.current&&(v.current=Date.now())):null!==v.current&&(g(Math.ceil((Date.now()-v.current)/1e3)),v.current=null)},[t,g]),(0,r.useEffect)(()=>{!t||m||u||p(!0)},[t,m,p,u]),(0,r.useEffect)(()=>{if(x.current&&!t&&m&&!f){let e=setTimeout(()=>{p(!1),b(!0)},1e3);return()=>clearTimeout(e)}},[t,m,p,f]);let w=(0,r.useCallback)(e=>{p(e)},[p]),y=(0,r.useMemo)(()=>({duration:h,isOpen:m,isStreaming:t,setIsOpen:p}),[h,m,t,p]);return(0,n.jsx)(de.Provider,{value:y,children:(0,n.jsx)(eW.Nt,{className:(0,C.cn)("not-prose mb-4",e),onOpenChange:w,open:m,...d,children:o})})}),ds=(e,t)=>e||0===t?(0,n.jsx)(o9,{duration:1,children:"Thinking..."}):void 0===t?(0,n.jsx)("p",{children:"Thought for a few seconds"}):(0,n.jsxs)("p",{children:["Thought for ",t," seconds"]}),dn=(0,r.memo)(({className:e,children:t,getThinkingMessage:s=ds,...a})=>{let{isStreaming:i,isOpen:l,duration:o}=(()=>{let e=(0,r.useContext)(de);if(!e)throw Error("Reasoning components must be used within Reasoning");return e})();return(0,n.jsx)(eW.R6,{className:(0,C.cn)("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...a,children:t??(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oF.A,{className:"size-4"}),s(i,o),(0,n.jsx)(eq.A,{className:(0,C.cn)("size-4 transition-transform",l?"rotate-180":"rotate-0")})]})})}),dr={cjk:tV.h,code:tK.a,math:tH.D,mermaid:tG.a},da=(0,r.memo)(({className:e,children:t,...s})=>(0,n.jsx)(eW.Ke,{className:(0,C.cn)("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...s,children:(0,n.jsx)(tJ.jH,{plugins:dr,children:t})}));dt.displayName="Reasoning",dn.displayName="ReasoningTrigger",da.displayName="ReasoningContent";var di=s(52216),dl=s.n(di);function dd({messages:e,incomplete:t,children:s}){let{t:a}=(0,f.Bd)("conversation"),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(!1),c=(0,r.useRef)(null),u=(0,r.useRef)(!1);return(0,n.jsxs)(eJ.AM,{open:i,onOpenChange:(e,t)=>{if(!e&&"trigger-press"===t.reason&&u.current){u.current=!1,t.cancel();return}e&&"trigger-hover"===t.reason&&o||!e&&"trigger-hover"===t.reason&&(!u.current||c.current?.contains(document.activeElement))?t.cancel():(e?u.current="trigger-hover"===t.reason:"trigger-hover"!==t.reason&&(u.current=!1,d(!0)),l(e))},children:[(0,n.jsx)(eJ.Wv,{openOnHover:!o,delay:250,closeDelay:180,onPointerLeave:()=>d(!1),className:"min-w-0 cursor-pointer rounded-sm text-left text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:s}),(0,n.jsxs)(eJ.hl,{ref:c,align:"start",side:"top",initialFocus:()=>!u.current,className:(0,C.cn)(dl().panel,"w-[30rem] gap-0 p-2"),children:[(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b px-1 pb-1",children:[(0,n.jsx)(eJ.eO,{className:"min-w-0 flex-1 text-xs font-medium text-muted-foreground",children:a(t?"calls.loadedTitle":"calls.title")}),(0,n.jsx)("button",{type:"button","aria-label":a("calls.close"),className:"flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{u.current=!1,d(!0),l(!1)},children:(0,n.jsx)(Y.A,{className:"size-3.5"})})]}),i?(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto overscroll-contain",children:(0,n.jsxs)("div",{className:dl().table,children:[(0,n.jsxs)("div",{className:(0,C.cn)(dl().row,"text-muted-foreground"),children:[(0,n.jsx)("span",{children:a("calls.model")}),(0,n.jsx)("span",{children:a("calls.input")}),(0,n.jsx)("span",{children:a("calls.output")}),(0,n.jsx)("span",{children:a("calls.cached")}),(0,n.jsx)("span",{children:a("calls.cost")})]}),e.map(e=>{let t=e.snapshot.fixed;if("assistant"!==t.type)return null;let s="assistant"===e.summary.type?e.summary.model:null,r=t.usage;return(0,n.jsxs)("div",{className:dl().row,children:[(0,n.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[(0,n.jsxs)("span",{className:"min-w-0 truncate",title:s?`${s.modelId} \xb7 ${s.provider}`:void 0,children:[s?.modelId||a("calls.unknownModel"),s?.provider?(0,n.jsxs)("span",{className:"text-muted-foreground",children:[" \xb7 ",s.provider]}):null]}),"error"===t.status||"aborted"===t.status?(0,n.jsx)("span",{className:"shrink-0 text-destructive",children:a(`calls.${t.status}`)}):null]}),(0,n.jsx)("span",{children:ol(r.inputTokens)}),(0,n.jsx)("span",{children:ol(r.outputTokens)}),(0,n.jsx)("span",{children:ol(r.cacheReadTokens)}),(0,n.jsx)("span",{children:oo(r.costUsd)})]},e.durable.location.entryId)})]})}):null]})]})}function dc({nestedCalls:e}){let{t}=(0,f.Bd)("conversation");return(0,n.jsxs)("section",{className:"border-t px-3 py-3 text-sm",children:[(0,n.jsx)("h4",{className:"mb-2 font-medium",children:t(e.complete?"nestedCalls":"nestedCallsIncomplete")}),(0,n.jsx)("ol",{className:"max-h-[min(24rem,45dvh)] space-y-2 overflow-auto",children:e.calls.map((e,s)=>(0,n.jsxs)("li",{className:"border-b pb-2 last:border-0 last:pb-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[(0,n.jsx)("span",{className:"text-xs tabular-nums text-muted-foreground",children:s+1}),(0,n.jsx)("span",{className:"min-w-0 break-words font-mono font-medium",children:e.name}),(0,n.jsx)("span",{className:"error"===e.status?"text-xs text-destructive":"text-xs text-muted-foreground",children:t(`nestedStatus.${e.status}`)}),void 0===e.durationMs?null:(0,n.jsxs)("span",{className:"ml-auto text-xs tabular-nums text-muted-foreground",children:[e.durationMs," ms"]})]}),e.arguments?(0,n.jsxs)("details",{className:"mt-1",children:[(0,n.jsx)("summary",{className:"min-h-7 cursor-pointer text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring",children:t("nestedArguments")}),(0,n.jsx)("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap break-words py-2 font-mono text-sm",children:JSON.stringify(e.arguments,null,2)})]}):null,void 0===e.argumentsBytes?null:(0,n.jsx)("p",{className:"mt-1 text-xs tabular-nums text-muted-foreground",children:t("nestedArgumentsBytes",{count:e.argumentsBytes})}),e.error?(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-destructive",children:e.error}):null]},s))})]})}function du({plugin:e}){let{t}=(0,f.Bd)("conversation"),{locale:s}=(0,eG.i)();return(0,n.jsxs)("div",{className:"min-w-0 space-y-1 py-2 first:pt-0 last:pb-0",role:"listitem",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[(0,n.jsx)("span",{className:"min-w-0 font-medium [overflow-wrap:anywhere]",children:e.name}),(0,n.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:e.version??t("pidesk.unknownVersion")}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:t(`pidesk.status.${e.status}`)})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[t(`pidesk.kind.${e.kind}`)," \xb7 ",(0,n.jsx)("span",{className:"font-mono",children:e.source})]}),e.updateTag||e.availableVersion?(0,n.jsxs)("p",{className:"flex flex-wrap gap-x-3 text-xs text-muted-foreground [overflow-wrap:anywhere]",children:[e.updateTag?(0,n.jsx)("span",{children:t("pidesk.updateChannel",{tag:e.updateTag})}):null,e.availableVersion?(0,n.jsx)("span",{children:t("pidesk.targetVersion",{version:e.availableVersion})}):null]}):null,e.updateError?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:e.updateError}):null,e.operation?(0,n.jsxs)("p",{className:"[overflow-wrap:anywhere]",children:[t(`pidesk.action.${e.operation.action}`)," \xb7 ",t(`pidesk.phase.${e.operation.phase}`),e.operation.message?` \xb7 ${e.operation.message}`:""]}):null,e.error?(0,n.jsxs)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:[t(`pidesk.errorPhase.${e.error.phase}`)," \xb7 ",(0,eH.fD)(e.error.message,s)]}):null]})}function dm({result:e}){let{t}=(0,f.Bd)("conversation"),{locale:s}=(0,eG.i)();return"info"===e.kind?(0,n.jsx)("dl",{className:"grid grid-cols-[max-content_minmax(0,1fr)] gap-x-4 gap-y-2",children:Object.entries(e.data).map(([e,s])=>(0,n.jsxs)("div",{className:"contents",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:t(`pidesk.info.${e}`)}),(0,n.jsx)("dd",{className:"min-w-0 [overflow-wrap:anywhere]",children:"environment"===e?t(`pidesk.environment.${s}`):"mode"===e?t(`pidesk.mode.${s}`):(0,n.jsx)("span",{className:"font-mono",children:s})})]},e))}):"plugin"===e.kind?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{role:"list",children:(0,n.jsx)(du,{plugin:e.data})}),(0,n.jsx)("p",{className:"mt-3 mb-2 font-medium",children:t("pidesk.pluginDetail")}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:JSON.stringify(e.data.detail,null,2)})]}):(0,n.jsxs)(n.Fragment,{children:[e.data.restartRequired?(0,n.jsx)("p",{className:"mb-2",children:t("pidesk.restartRequired")}):null,e.data.loadError?(0,n.jsx)("p",{className:"mb-2 text-destructive [overflow-wrap:anywhere]",children:(0,eH.fD)(e.data.loadError,s)}):null,e.data.plugins.length>0?(0,n.jsx)("div",{className:"divide-y divide-border",role:"list",children:e.data.plugins.map((e,t)=>(0,n.jsx)(du,{plugin:e},`${e.source}:${t}`))}):(0,n.jsx)("p",{className:"text-muted-foreground",children:t("pidesk.noPlugins")})]})}function dp({identity:e,command:t,output:s,expandable:r,open:a,loading:i,error:l,onOpenChange:o,commandAction:d,outputAction:c}){let{t:u}=(0,f.Bd)("conversation"),m=t.label?[u(t.label),t.name,t.version].filter(Boolean).join(" \xb7 "):t.command,p=null===s?null:function(e,t){let s;if(!["pideskListPlugins","pideskShowPlugin","pideskInfo"].includes(e??""))return null;try{s=JSON.parse(t)}catch{return null}switch(e){case"pideskListPlugins":{let e=l3.safeParse(s);return e.success?{kind:"plugins",data:e.data}:null}case"pideskShowPlugin":{let e=l4.safeParse(s);return e.success?{kind:"plugin",data:e.data}:null}case"pideskInfo":{let e=l6.safeParse(s);return e.success?{kind:"info",data:e.data}:null}default:return null}}(t.label,s);return(0,n.jsxs)(eW.Nt,{open:r&&a,onOpenChange:o,className:"w-full min-w-0 overflow-hidden rounded-lg border border-border bg-card text-sm leading-relaxed","data-message-id":e,"data-chat-scroll-anchor":`${e}:tool`,children:[(0,n.jsxs)(eW.R6,{disabled:!r,"aria-label":r?u(a?"collapseTool":"expandTool",{name:m}):m,className:(0,C.cn)("flex min-h-9 w-full min-w-0 items-center gap-2 px-3 py-1.5 text-left",r&&"cursor-pointer hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"),children:[(0,n.jsx)(nV.A,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,n.jsx)("span",{className:(0,C.cn)("min-w-0 flex-1 truncate font-medium",!t.label&&"font-mono"),title:m,children:m}),r?(0,n.jsx)(eq.A,{className:(0,C.cn)("size-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)(eW.Ke,{className:"h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none",children:(0,n.jsxs)("div",{className:"border-t",children:[(0,n.jsxs)("section",{className:"border-b px-3 py-2","aria-label":u("pidesk.command"),children:[(0,n.jsxs)("div",{className:"mb-1 flex min-h-7 items-center justify-between gap-2",children:[(0,n.jsx)("h4",{className:"font-medium text-muted-foreground",children:u("pidesk.command")}),d]}),(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:t.command})]}),(0,n.jsxs)("section",{"aria-label":u("pidesk.output"),children:[(0,n.jsxs)("div",{className:"flex min-h-9 items-center justify-between gap-2 px-3 pt-2",children:[(0,n.jsx)("h4",{className:"font-medium text-muted-foreground",children:u("pidesk.output")}),c]}),(0,n.jsx)("div",{className:"max-h-[min(24rem,50dvh)] overflow-auto px-3 pt-1 pb-3",role:"region","aria-label":u("pidesk.output"),tabIndex:0,children:i?(0,n.jsx)("p",{className:"text-muted-foreground",children:u("loadingResult")}):l?(0,n.jsx)("p",{className:"text-destructive [overflow-wrap:anywhere]",children:l}):s?p?(0,n.jsx)(dm,{result:p}):(0,n.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono leading-relaxed",children:s}):(0,n.jsx)("p",{className:"text-muted-foreground",children:u("pidesk.empty")})})]})]})})]})}var dh=s(43769),dg=s.n(dh);let dx="max-h-[min(20rem,45dvh)] overflow-auto [scrollbar-gutter:stable]",df=(0,r.createContext)(()=>void 0),db=(0,r.createContext)(null),dv=(0,r.createContext)(null),dw="h-[var(--collapsible-panel-height)] overflow-hidden transition-[height,opacity] duration-200 ease-out data-starting-style:h-0 data-starting-style:opacity-0 data-ending-style:h-0 data-ending-style:opacity-0 motion-reduce:transition-none";function dy({children:e}){let{isAtBottom:t,stopScroll:s}=(0,lO.B)(),a=(0,r.useRef)(t),i=(0,r.useRef)(s);(0,r.useLayoutEffect)(()=>{a.current=t,i.current=s},[t,s]);let l=(0,r.useCallback)(()=>{a.current&&i.current()},[]);return(0,n.jsx)(df.Provider,{value:l,children:e})}function dk(e,t){let{t:s}=(0,f.Bd)("conversation"),[n,a]=(0,r.useState)(!1),[i,l]=(0,r.useState)(null),o=(0,r.useCallback)(async()=>{if(!e.temporary&&e.durable&&e.snapshot.fixed.hasDetail&&void 0===e.detail&&!n){a(!0),l(null);try{await t(e)}catch(e){l(e instanceof Error?e.message:s("detailFailed"))}finally{a(!1)}}},[n,e,t,s]);return{loading:n,error:i,load:o}}function dj(e,t){let[s,n]=(0,r.useState)(!1),a=(0,r.useContext)(df),{loading:i,error:l,load:o}=dk(e,t),d=!e.temporary&&(e.summary.hasDetail||"tool"===e.summary.type&&!!e.summary.images?.length);return{open:s,expandable:d,loading:i,error:l,handleOpenChange:e=>{d&&(e&&(a(),o()),n(e))}}}function dN({timestampMs:e}){let{locale:t,timeZone:s}=(0,eG.i)(),r=od(e,void 0,t,s);return(0,n.jsx)("time",{dateTime:new Date(e).toISOString(),title:r.full,className:"shrink-0",children:r.compact})}function dI({text:e,copyLabel:t,alwaysVisible:s=!1}){let{t:a}=(0,f.Bd)("conversation"),i=(0,Q.G)(),[l,o]=(0,r.useState)(!1),d=(0,r.useRef)(null);(0,r.useEffect)(()=>()=>{null!==d.current&&window.clearTimeout(d.current)},[]);let c=(0,r.useCallback)(async()=>{let t=!1;try{t=await (0,e7.x)(e)}catch{t=!1}t?(o(!0),null!==d.current&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{d.current=null,o(!1)},1500)):i.error(a("messageCopyFailed"))},[e,i,a]);if(!e.trim())return null;let u=l?a("copied"):t??a("copyMessage");return(0,n.jsx)(tZ,{tooltip:u,label:u,size:"icon-sm",className:(0,C.cn)(!s&&dg().messageCopyAction,"text-muted-foreground"),onClick:()=>void c(),children:l?(0,n.jsx)(em.A,{className:"size-3.5"}):(0,n.jsx)(Z.A,{className:"size-3.5"})})}function dC({usage:e,compactOnly:t=!1}){let{t:s}=(0,f.Bd)("conversation"),r=ol(e.inputTokens),a=ol(e.outputTokens),i=ol(e.cacheReadTokens),l=oo(e.costUsd),o=s("usage",{input:r,output:a,cached:i,cost:l}),d=`${r}/${a}/${i}/${l}`;return t?(0,n.jsx)("span",{className:"shrink-0 font-mono text-xs tabular-nums text-muted-foreground",title:o,"aria-label":o,children:d}):(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("span",{className:dg().usageLabeled,children:o}),(0,n.jsx)("span",{className:dg().usageCompact,children:d})]})}function dS({message:e}){if("assistant"!==e.summary.type||null===e.timestampMs)return null;let t="running"!==e.summary.status?e.summary.text:null;return(0,n.jsxs)(t2,{className:(0,C.cn)(dg().usageToolbar,"mt-1 flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground"),children:[e.usageCalls?.length?(0,n.jsx)(dd,{messages:e.usageCalls,incomplete:e.usageIncomplete??!1,children:(0,n.jsx)(dC,{usage:e.summary.usage})},e.durable.location.entryId):(0,n.jsx)(dC,{usage:e.summary.usage}),(0,n.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-1",children:[null===t?null:(0,n.jsx)(dI,{text:t}),null===e.timestampMs?null:(0,n.jsx)(dN,{timestampMs:e.timestampMs})]})]})}function dM({message:e,onAcquireImage:t}){let{t:s}=(0,f.Bd)("conversation"),a="user"===e.summary.type||"tool"===e.summary.type?e.summary.images??[]:[],i=a.length,l=(0,r.useRef)(e);(0,r.useLayoutEffect)(()=>{l.current=e},[e]);let[o,d]=(0,r.useState)(()=>Array.from({length:i},()=>({status:"loading"}))),[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(0);return(0,r.useLayoutEffect)(()=>{let e=!0,s=Array.from({length:i},()=>null);for(let n=0;n<i;n+=1){let r=t=>{e?(s[n]=t.release,d(e=>{let s=[...e];return s[n]={status:"ready",url:t.url},s})):t.release()},a=()=>{e&&d(e=>{let t=[...e];return t[n]={status:"error"},t})};try{let e=t(l.current,n);"then"in e?e.then(r).catch(a):r(e)}catch{a()}}return()=>{e=!1,s.forEach(e=>e?.())}},[i,e.identity,e.tempId,e.durable?.location.entryId,t,m]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"mb-2 grid grid-cols-2 gap-2 sm:grid-cols-3",children:a.map((e,t)=>{let r=o[t];return r?.status==="error"?(0,n.jsxs)("button",{type:"button",className:"flex aspect-square min-h-20 cursor-pointer flex-col items-center justify-center gap-2 rounded-md border bg-muted px-2 text-center text-xs text-muted-foreground hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{u(null),d(e=>e.map(e=>"error"===e.status?{status:"loading"}:e)),p(e=>e+1)},children:[(0,n.jsx)("span",{children:s("imageUnavailable")}),(0,n.jsx)("span",{className:"text-sm font-medium text-foreground",children:s("retry",{ns:"common"})})]},`${t}:${e.width}:${e.height}`):r?.status!=="ready"?(0,n.jsx)("div",{className:"grid aspect-square min-h-20 place-items-center rounded-md border bg-muted px-2 text-center text-xs text-muted-foreground",children:s("imageLoading")},`${t}:${e.width}:${e.height}`):(0,n.jsx)("button",{type:"button",className:"group block aspect-square w-full cursor-zoom-in overflow-hidden rounded-md border bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>{let e,n;return e=[],n=-1,void(o.forEach((r,i)=>{if("ready"!==r.status)return;i===t&&(n=e.length);let l=a[i];e.push({src:r.url,alt:s("chatImage",{count:i+1}),width:l.width,height:l.height})}),n>=0&&u({slides:e,index:n}))},"aria-label":s("previewImageNumber",{count:t+1}),children:(0,n.jsx)("img",{src:r.url,alt:s("chatImage",{count:t+1}),className:"aspect-square size-full object-cover transition-transform duration-200 group-hover:scale-[1.02] motion-reduce:transition-none"})},`${t}:${e.width}:${e.height}`)})}),c?(0,n.jsx)(ng.k,{mode:"modal",open:!0,slides:c.slides,index:c.index,ariaLabel:s("chatImagePreview"),onClose:()=>u(null),onIndexChange:e=>u(t=>t?{...t,index:e}:t)}):null]})}function dz({text:e}){let{t}=(0,f.Bd)("conversation"),s=(0,r.useRef)(null),[a,i]=(0,r.useState)(!1),[l,o]=(0,r.useState)(null),d=(0,r.useContext)(df);(0,r.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=new ResizeObserver(([t])=>{if(!t||0===t.contentRect.height)return;let s=Number.parseFloat(getComputedStyle(e).lineHeight);o(t.contentRect.height>6*s+1)});return t.observe(e),()=>t.disconnect()},[]);let c=(0,r.useCallback)(()=>{a||d(),i(e=>!e)},[d,a]);return(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:(0,C.cn)("relative",!a&&!1!==l&&dg().userTextCollapsed),children:[(0,n.jsx)("p",{ref:s,className:"whitespace-pre-wrap break-words",children:e}),l&&!a?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-secondary to-transparent","aria-hidden":"true"}):null]}),l?(0,n.jsxs)("button",{type:"button","aria-expanded":a,onClick:c,className:"-mb-1 ml-auto mt-1 flex min-h-7 cursor-pointer items-center gap-1 rounded-md px-1 text-xs font-medium text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t(a?"collapse":"expand"),(0,n.jsx)(eq.A,{className:(0,C.cn)("size-3.5 transition-transform",a&&"rotate-180"),"aria-hidden":"true"})]}):null]})}function dE({message:e,onAcquireImage:t}){if("user"!==e.summary.type)throw Error("UserMessage requires a user summary");return(0,n.jsxs)(tQ,{from:"user","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:user`,"data-chat-user-message":"",className:(0,C.cn)(dg().copyableMessage,"max-w-[92%] sm:max-w-[84%]"),children:[(0,n.jsxs)(tX,{className:(0,C.cn)(dg().userText,"group-[.is-user]:px-3 group-[.is-user]:py-2"),children:[e.summary.images.length>0?(0,n.jsx)(dM,{message:e,onAcquireImage:t},`${e.tempId}:${e.durable?.location.entryId??"temporary"}`):null,e.summary.text?(0,n.jsx)(dz,{text:e.summary.text}):null]}),null===e.timestampMs?null:(0,n.jsxs)(t2,{className:"mt-0 justify-end gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(dI,{text:e.summary.text}),(0,n.jsx)(dN,{timestampMs:e.timestampMs})]})]})}function dA({message:e,text:t}){let s=e.temporary&&"assistant"===e.summary.type&&"running"===e.summary.status;return(0,n.jsxs)(tQ,{from:"assistant","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:text`,className:(0,C.cn)(dg().copyableMessage,"max-w-full gap-1"),children:[(0,n.jsx)(tX,{className:"w-full",children:(0,n.jsx)(n8,{isAnimating:s,mode:s?"streaming":"static",children:t})}),(0,n.jsx)(dS,{message:e})]})}function d$(){let{t:e}=(0,f.Bd)("conversation");return(0,n.jsxs)("div",{role:"status",className:(0,C.cn)(dg().detailText,"flex min-h-9 w-full items-center gap-2 py-1 text-muted-foreground"),children:[(0,n.jsx)(oF.A,{className:"size-4","aria-hidden":"true"}),(0,n.jsx)(o9,{as:"span",duration:1,children:e("thinking")})]})}function dR({content:e,streaming:t}){let{t:s}=(0,f.Bd)("conversation"),{scrollRef:r,contentRef:a}=(0,oY.q)({initial:!!t&&"instant",resize:"instant"}),i=e.length>5e3,l=e.slice(-5e3);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{ref:r,className:"max-h-56 overflow-y-auto pb-2 pr-2 [scrollbar-gutter:stable] sm:max-h-72",children:(0,n.jsx)("div",{ref:a,children:(0,n.jsx)(n8,{isAnimating:t,mode:t?"streaming":"static",children:l},i?e.length:void 0)})}),i?(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 pt-1",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:s("thinkingTruncated",{count:5e3})}),(0,n.jsx)(dI,{text:e,copyLabel:s("copyThinking"),alwaysVisible:!0})]}):null]})}function dT({message:e,detailLoad:t}){let{t:s}=(0,f.Bd)("conversation");if("assistant"!==e.summary.type)return null;let{loading:r,error:a,load:i}=t,l=void 0!==e.detail,o=e.detail?.type==="assistant"?e.detail:null,d=o?.thinking??"",c=d.trim().length>0,u=c&&e.temporary&&"running"===e.summary.status&&0===e.summary.text.trim().length;if(!(c||!l&&e.summary.hasDetail))return null;let m=d||(r?s("thinkingLoading"):a??s("thinkingUnavailable"));return(0,n.jsxs)(dt,{className:"mb-0 w-full",isStreaming:u,onOpenChange:e=>{e&&i()},children:[(0,n.jsx)(dn,{className:(0,C.cn)(dg().detailText,"min-h-9 justify-start py-1"),getThinkingMessage:e=>e?(0,n.jsx)(o9,{as:"span",duration:1,children:s("thinking")}):(0,n.jsx)("span",{children:s("thinkingProcess")})}),(0,n.jsx)(eW.Ke,{className:(0,C.cn)(dw,"text-sm leading-6 text-muted-foreground outline-none"),children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)("div",{className:"border-l pl-4",children:(0,n.jsx)(dR,{content:m,streaming:u})})})})]})}function dP({message:e}){let{t}=(0,f.Bd)("conversation"),{locale:s}=(0,eG.i)();if("assistant"!==e.summary.type)return null;let r=function(e,t){let s=e?.trim();if(!s)return null;switch(s.toLowerCase()){case"terminated":return n0.W[t].streamInterrupted;case"request timed out":case"request timed out.":return n0.W[t].requestTimedOut;default:return e}}(e.summary.errorMessage,s)??("error"===e.summary.status?t("modelFailed"):null);return r?(0,n.jsx)("pre",{className:(0,C.cn)(dg().toolOutput,"whitespace-pre-wrap break-words rounded-lg border border-destructive/40 bg-muted p-3 font-sans text-destructive"),children:r}):null}function dD({item:e,onLoadDetail:t}){let{message:s,hideAssistantText:r}=e,a=dk(s,t);if("assistant"!==s.summary.type)throw Error("AssistantProcessItem requires an assistant summary");return(0,n.jsxs)("div",{className:"space-y-2","data-message-id":s.identity,"data-chat-scroll-anchor":`${s.identity}:process`,children:[(0,n.jsx)(dT,{message:s,detailLoad:a}),r||!s.summary.text.trim()?null:(0,n.jsx)(dA,{message:s,text:s.summary.text}),(0,n.jsx)(dP,{message:s})]})}function dO({name:e,filePath:t,className:s}){let r=e.toLowerCase().split(".").at(-1)??e.toLowerCase(),a={className:s};switch(r){case"read":return t?(0,n.jsx)(o4,{path:t,...a}):(0,n.jsx)(nv.A,{...a});case"write":return(0,n.jsx)(o_.A,{...a});case"edit":return(0,n.jsx)(oB.A,{...a});case"bash":return(0,n.jsx)(v.A,{...a});case"grep":case"find":return(0,n.jsx)(ep.A,{...a});case"ls":return(0,n.jsx)(eR.A,{...a});case"agent":case"agent_resume":return(0,n.jsx)(eT.A,{...a});default:return(0,n.jsx)(eP.A,{...a})}}function dL(e){let t=e.replaceAll("\\","/");return"/"===t||/^[A-Za-z]:\/$/.test(t)?t:t.replace(/\/+$/,"")}function dF({status:e,timing:t}){let s=t&&"startedAtMs"in t?t.startedAtMs:null,a=t&&"durationMs"in t?t.durationMs:null,[i,l]=(0,r.useState)(()=>Date.now());(0,r.useEffect)(()=>{if("running"!==e||null===s)return;let t=window.setInterval(()=>l(Date.now()),1e3);return()=>window.clearInterval(t)},[s,e]);let o=a??(null===s?null:Math.max(0,i-s));return null===o?null:(0,n.jsx)(n.Fragment,{children:function(e){let t=Math.max(0,Math.floor(e/1e3)),s=t%60,n=Math.floor(t/60);if(0===n)return`${s}s`;let r=n%60,a=Math.floor(n/60);return 0===a?`${r}m ${s}s`:`${a}h ${r}m ${s}s`}(o)})}function d_({message:e,onLoadDetail:t,previewPath:s,onPreviewFile:a,renderDetail:i}){let{t:l}=(0,f.Bd)("conversation");if("tool"!==e.summary.type&&"bash"!==e.summary.type)throw Error("ToolCardShell requires a tool or bash summary");let o=(0,r.useContext)(db),d=(0,r.useContext)(dv),c=!e.temporary&&"tool"===e.summary.type&&!!e.summary.images?.length,{open:u,expandable:m,loading:p,error:h,handleOpenChange:g}=dj(e,t),{name:x,reasoning:b,inputPreview:v,activity:w,usage:y}="tool"===e.summary.type?{name:e.summary.name,reasoning:e.summary.reasoning,inputPreview:e.summary.inputPreview,activity:e.summary.activity,usage:e.summary.usage}:{name:"bash",reasoning:null,inputPreview:e.summary.command,activity:null,usage:null},k="tool"===e.summary.type&&"bash"===e.summary.kind?e.summary:null,j="error"===e.summary.status,N=!e.temporary&&null!==s&&void 0!==a,I=s?function(e,t){let{compactPath:s,fullPath:n}=function(e,t){let s=dL(e);if(!t)return{compactPath:s,fullPath:s};let n=dL(t);if(!(s.startsWith("/")||/^[A-Za-z]:\//.test(s))){let e=s.replace(/^(?:\.\/)+/,""),t=n.endsWith("/")?n:`${n}/`;return{compactPath:e,fullPath:`${t}${e}`}}let r=n.endsWith("/")?n:`${n}/`,a=/^[A-Za-z]:\//.test(s)&&/^[A-Za-z]:\//.test(n),i=a?s.toLowerCase():s,l=a?r.toLowerCase():r;return i.startsWith(l)?{compactPath:s.slice(r.length),fullPath:s}:{compactPath:s,fullPath:s}}(e,t),r=s.match(/^[A-Za-z]:\//)?.[0]??null??(s.startsWith("/")?"/":""),a=s.slice(r.length).split("/").filter(Boolean),i=a.pop()??s,l=i.lastIndexOf("."),o=a.length>2?`…/${a.slice(-2).join("/")}`:`${r}${a.join("/")}`;return{fileStem:l>0?i.slice(0,l):i,fileExtension:l>0?i.slice(l):"",directory:o||null,fullPath:n}}(s,o):null;return(0,n.jsxs)(eW.Nt,{open:m&&u,onOpenChange:g,className:(0,C.cn)(dg().detailText,"w-full overflow-hidden rounded-lg border bg-muted/45 dark:bg-card",j?"border-destructive":"border-border"),"data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:tool`,children:[(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsxs)(eW.R6,{disabled:!m,className:(0,C.cn)("relative grid min-h-14 w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-2 px-3 py-1.5 text-left",m&&"cursor-pointer hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"),"aria-label":l(m?u?"collapseTool":"expandTool":"tool",{name:x}),children:[(0,n.jsx)(dO,{name:x,filePath:s,className:"col-start-1 row-start-1 size-4 text-muted-foreground"}),(0,n.jsxs)("span",{className:"col-start-2 row-start-1 flex min-h-7 min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"shrink-0 font-mono font-medium",children:x}),b?(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-foreground",children:b}):null,y?(0,n.jsx)(dC,{usage:y,compactOnly:!0}):null]}),(0,n.jsxs)("span",{className:"col-start-3 row-start-1 flex min-h-7 items-center justify-end gap-2",children:[N?(0,n.jsx)("span",{className:"size-7","aria-hidden":"true"}):null,m?(0,n.jsx)("span",{className:"flex size-7 items-center justify-center","aria-hidden":"true",children:(0,n.jsx)(eq.A,{"data-tool-disclosure":"",className:(0,C.cn)("size-4 text-muted-foreground transition-transform",u&&"rotate-180")})}):null]}),I?(0,n.jsxs)("span",{className:(0,C.cn)(dg().toolFilePath,"col-start-2 row-start-2 flex min-w-0 items-baseline overflow-hidden font-mono text-xs"),title:I.fullPath,children:[(0,n.jsxs)("span",{className:"flex min-w-0 max-w-full shrink-0 items-baseline text-foreground",children:[(0,n.jsx)("span",{className:"min-w-0 truncate",children:I.fileStem}),(0,n.jsx)("span",{className:"shrink-0",children:I.fileExtension})]}),I.directory?(0,n.jsxs)("span",{className:(0,C.cn)(dg().toolFileDirectory,"min-w-0 truncate text-muted-foreground"),children:["\xa0\xb7\xa0",I.directory]}):null]}):v?(0,n.jsx)("span",{className:"col-start-2 row-start-2 truncate font-mono text-xs text-muted-foreground",children:v}):null,k?.timing?(0,n.jsx)("span",{className:"col-start-3 row-start-2 text-right font-mono text-xs tabular-nums whitespace-nowrap text-muted-foreground",children:(0,n.jsx)(dF,{status:k.status,timing:k.timing})}):w?(0,n.jsx)("span",{className:"col-start-3 row-start-2 max-w-36 truncate text-right font-mono text-xs tabular-nums text-muted-foreground",title:w,children:w}):null]}),N?(0,n.jsx)("button",{type:"button",title:l("previewFile"),"aria-label":l("previewFilePath",{path:s}),onClick:()=>a(s),className:(0,C.cn)("absolute top-1.5 flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",m?"right-12":"right-3"),children:(0,n.jsx)(oq.A,{className:"size-4","aria-hidden":"true"})}):null]}),(0,n.jsx)(eW.Ke,{className:dw,children:(0,n.jsxs)("div",{className:"border-t",children:[I?(0,n.jsx)("p",{className:"border-b px-3 py-2 font-mono text-xs text-muted-foreground [overflow-wrap:anywhere]",children:I.fullPath}):null,u&&c&&d?(0,n.jsx)("div",{className:"px-3 pt-3",children:(0,n.jsx)(dM,{message:e,onAcquireImage:d})}):null,i({loading:p,error:h})]})})]})}function dB({children:e,destructive:t=!1}){return(0,n.jsx)("p",{className:(0,C.cn)(dg().detailText,"px-3 py-3",t?"text-destructive":"text-muted-foreground"),children:e})}function dq({message:e,loading:t,error:s}){let{t:r}=(0,f.Bd)("conversation"),a=e.detail?.type==="bash"||e.detail?.type==="tool"&&("generic"===e.detail.kind||"bash"===e.detail.kind||"codemode"===e.detail.kind)?e.detail:null,i=a?.output??"";return t?(0,n.jsx)(dB,{children:r("loadingResult")}):s?(0,n.jsx)(dB,{destructive:!0,children:s}):i?(0,n.jsx)("pre",{role:"region","aria-label":r("toolOutput"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono"),children:i}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(dB,{children:r("emptyResult")})}function dW({message:e,loading:t,error:s}){let{t:r}=(0,f.Bd)("conversation"),a=e.detail?.type==="tool"&&"read"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(dB,{children:r("loadingRead")}):s?(0,n.jsx)(dB,{destructive:!0,children:s}):a?a.content?(0,n.jsx)("pre",{role:"region","aria-label":r("readContent"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,dg().toolCode,"px-3 py-3 font-mono"),children:a.content}):(0,n.jsx)(dB,{children:r("readEmpty")}):"tool"===e.summary.type&&e.summary.images?.length?(0,n.jsx)(n.Fragment,{}):(0,n.jsx)(dB,{children:r("readUnavailable")})}function dY({content:e}){let{t}=(0,f.Bd)("conversation");return(0,n.jsx)("div",{role:"region","aria-label":t("editDiff"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,"font-mono"),children:e.split("\n").map((e,t)=>{let s=e.startsWith("+")?"bg-emerald-500/10 text-emerald-800 dark:text-emerald-200":e.startsWith("-")?"bg-red-500/10 text-red-800 dark:text-red-200":e.trimEnd().endsWith("...")?"bg-muted/40 text-muted-foreground":"text-foreground";return(0,n.jsx)("span",{className:(0,C.cn)(dg().toolCode,dg().toolCodeLine,"block px-3",s),children:e||" "},t)})})}function dU({message:e,loading:t,error:s}){let{t:r}=(0,f.Bd)("conversation"),a=e.detail?.type==="tool"&&"edit"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(dB,{children:r("loadingDiff")}):s?(0,n.jsx)(dB,{destructive:!0,children:s}):a?"diff"===a.contentKind?(0,n.jsx)(dY,{content:a.content}):(0,n.jsx)("pre",{role:"region","aria-label":r("editResult"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,"whitespace-pre-wrap break-words px-3 py-3 font-mono","tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:a.content}):(0,n.jsx)(dB,{children:r("diffUnavailable")})}function dV({message:e,loading:t,error:s}){let{t:r}=(0,f.Bd)("conversation"),a=e.detail?.type==="tool"&&"write"===e.detail.kind?e.detail:null;return t?(0,n.jsx)(dB,{children:r("loadingWrite")}):s?(0,n.jsx)(dB,{destructive:!0,children:s}):a?"content"!==a.contentKind||a.content?(0,n.jsx)("pre",{role:"region","aria-label":r("content"===a.contentKind?"writeContent":"writeResult"),tabIndex:0,className:(0,C.cn)(dx,dg().toolOutput,"px-3 py-3 font-mono","content"===a.contentKind?dg().toolCode:"whitespace-pre-wrap break-words","output"===a.contentKind&&"tool"===e.summary.type&&"error"===e.summary.status&&"text-destructive"),children:a.content}):(0,n.jsx)(dB,{children:r("writeEmpty")}):(0,n.jsx)(dB,{children:r("writeUnavailable")})}function dK({message:e,onLoadDetail:t}){let{t:s}=(0,f.Bd)("conversation"),{open:r,expandable:a,loading:i,error:l,handleOpenChange:o}=dj(e,t);if("tool"!==e.summary.type||"pidesk"!==e.summary.kind)throw Error("PiDeskToolView requires a pidesk summary");let d=function(e){let t=e.args,s={command:0===Object.keys(e).length?"pidesk":`pidesk ${JSON.stringify(e)}`,label:null,name:null,version:null};if(1!==Object.keys(e).length||!Array.isArray(t)||t.length>32||!t.every(e=>"string"==typeof e))return s;s.command=["pidesk",...t.map(l2)].join(" ");let n=t.some(e=>/\s/.test(e))?"":t.join(" ");if(0===t.length||["--help","-h","plugins","session","plugins --help","plugins -h","session --help","session -h"].includes(n))return{...s,label:lZ};if("--version"===n)return{...s,label:"pideskVersion"};if("info"===n)return{...s,label:"pideskInfo"};if("session reload"===n)return{...s,label:"pideskReload"};if(3===t.length&&["--help","-h"].includes(t[2])&&("plugins"===t[0]&&["list","show","install","remove"].includes(t[1])||"session"===t[0]&&"reload"===t[1]))return{...s,label:lZ};let r=t[1];if("plugins"!==t[0]||!r||!["list","show","install","remove"].includes(r))return s;let a=null,i=[],l=null,o=null,d=!1;for(let e=2;e<t.length;e+=1){let n=t[e];if("--scope"===n&&null===a&&"global"===t[e+1])a=t[++e];else if("--version"===n&&"install"===r&&null===l&&l1.test(t[e+1]??""))l=t[++e];else if("--tag"===n&&["list","install"].includes(r)&&null===o&&(t[e+1]?.length??0)<=128&&/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(t[e+1]??""))o=t[++e];else if("--check-updates"!==n||"list"!==r||d)if(!("list"!==r&&("show"!==r||0===i.length)&&"node_modules"!==n&&l0.test(n)))return s;else i.push(n);else d=!0}if(null!==o&&null!==l||"list"!==r&&(0===i.length||null===a))return s;let c=i.length>0?i.join("、"):null;switch(r){case"list":return{...s,label:"pideskListPlugins"};case"show":return{...s,label:"pideskShowPlugin",name:c};case"install":return{...s,label:"pideskInstallPlugin",name:c,version:l};case"remove":return{...s,label:"pideskRemovePlugin",name:c};default:return s}}(e.summary.input),c=e.detail?.type==="tool"&&"pidesk"===e.detail.kind?e.detail.output:null;return(0,n.jsx)(dp,{identity:e.identity,command:d,output:c,expandable:a,open:r,loading:i,error:l,onOpenChange:o,commandAction:(0,n.jsx)(dI,{text:d.command,copyLabel:s("pidesk.copyCommand"),alwaysVisible:!0}),outputAction:c?(0,n.jsx)(dI,{text:c,copyLabel:s("pidesk.copyOutput"),alwaysVisible:!0}):null})}function dH({message:e,onLoadDetail:t}){return(0,n.jsx)(d_,{message:e,onLoadDetail:t,previewPath:null,renderDetail:t=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(dq,{message:e,...t}),e.detail?.type==="tool"&&"codemode"===e.detail.kind&&e.detail.nestedCalls?(0,n.jsx)(dc,{nestedCalls:e.detail.nestedCalls}):null]})})}function dG({message:e,onLoadDetail:t}){return(0,n.jsx)(dH,{message:e,onLoadDetail:t})}function dJ({message:e,onLoadDetail:t,onPreviewFile:s}){if("tool"!==e.summary.type||"read"!==e.summary.kind)throw Error("ReadToolView requires a read summary");return(0,n.jsx)(d_,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(dW,{message:e,...t})})}function dQ({message:e,onLoadDetail:t,onPreviewFile:s}){if("tool"!==e.summary.type||"edit"!==e.summary.kind)throw Error("EditToolView requires an edit summary");return(0,n.jsx)(d_,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(dU,{message:e,...t})})}function dX({message:e,onLoadDetail:t,onPreviewFile:s}){if("tool"!==e.summary.type||"write"!==e.summary.kind)throw Error("WriteToolView requires a write summary");return(0,n.jsx)(d_,{message:e,onLoadDetail:t,previewPath:e.summary.path,onPreviewFile:s,renderDetail:t=>(0,n.jsx)(dV,{message:e,...t})})}function dZ({message:e}){let{t}=(0,f.Bd)("conversation");if("custom"!==e.summary.type)throw Error("CustomMessage requires a custom summary");return(0,n.jsx)("div",{"data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:custom`,className:(0,C.cn)(dg().toolOutput,"rounded-lg border-l-2 bg-muted px-3 py-2 text-muted-foreground"),children:e.summary.text||t("emptyMessage")})}function d0({message:e,onLoadDetail:t}){let{t:s}=(0,f.Bd)("conversation");if("compaction"!==e.summary.type)throw Error("CompactionMessage requires a compaction summary");let{open:r,expandable:a,loading:i,error:l,handleOpenChange:o}=dj(e,t),d=e.detail?.type==="compaction"?e.detail:null;return(0,n.jsxs)(eW.Nt,{open:a&&r,onOpenChange:o,className:"w-full py-1","data-message-id":e.identity,"data-chat-scroll-anchor":`${e.identity}:compaction`,children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("span",{className:"h-px min-w-3 flex-1 bg-border/70","aria-hidden":"true"}),(0,n.jsxs)(eW.R6,{disabled:!a,"aria-label":a?`${s(r?"collapse":"expand")} ${s("compactionSummary")}`:s(e.temporary?"compactionRunning":"compactionComplete"),className:(0,C.cn)("inline-flex min-h-8 max-w-full items-center gap-2 rounded-full border border-border/70 bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground outline-none transition-colors",a?"hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring":"cursor-default"),children:[e.temporary?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin","aria-hidden":"true"}):(0,n.jsx)(oW.A,{className:"size-3.5","aria-hidden":"true"}),(0,n.jsx)("span",{children:s(e.temporary?"compactionRunning":"compactionComplete")}),a?(0,n.jsx)(eq.A,{className:(0,C.cn)("size-3.5 transition-transform",r&&"rotate-180"),"aria-hidden":"true"}):null]}),(0,n.jsx)("span",{className:"h-px min-w-3 flex-1 bg-border/70","aria-hidden":"true"})]}),(0,n.jsx)(eW.Ke,{className:dw,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)("div",{className:"rounded-xl border border-border/70 bg-muted/20 px-3 py-3 sm:px-4",children:(0,n.jsx)("div",{role:"region","aria-label":s("compactionSummaryContent"),tabIndex:0,className:"max-h-80 overflow-y-auto pr-2 [scrollbar-gutter:stable]",children:i?(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionLoading")}):l?(0,n.jsx)("p",{className:"text-sm text-destructive",children:l}):d?.text?(0,n.jsx)(n8,{isAnimating:!1,mode:"static",children:d.text}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:s("compactionUnavailable")})})})})})]})}let d1=(0,r.memo)(function({item:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:r}){let a=(()=>{switch(e.message.summary.type){case"assistant":return(0,n.jsx)(dD,{item:e,onLoadDetail:t});case"tool":switch(e.message.summary.kind){case"pidesk":return(0,n.jsx)(dK,{message:e.message,onLoadDetail:t});case"read":return(0,n.jsx)(dJ,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"edit":return(0,n.jsx)(dQ,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"write":return(0,n.jsx)(dX,{message:e.message,onLoadDetail:t,onPreviewFile:r});case"bash":case"codemode":case"generic":return(0,n.jsx)(dH,{message:e.message,onLoadDetail:t})}case"bash":return(0,n.jsx)(dG,{message:e.message,onLoadDetail:t});case"custom":return(0,n.jsx)(dZ,{message:e.message});case"compaction":return(0,n.jsx)(d0,{message:e.message,onLoadDetail:t});case"user":return(0,n.jsx)(dE,{message:e.message,onAcquireImage:s})}})();return(0,n.jsx)(oL,{message:e.message,loadDetail:t,defaultView:a})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.item.hideAssistantText===t.item.hideAssistantText&&d3(e.item.message,t.item.message));function d2({items:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a}){let{scrollRef:i}=(0,lO.B)(),l=(0,r.useRef)(null),o=(0,r.useRef)(null),d=(0,r.useRef)(e.length),c=(0,r.useRef)(null),[u,m]=(0,r.useState)(()=>Math.min(64,e.length)),p=Math.max(0,e.length-u),h=p>0,g=(0,r.useCallback)(()=>{if(!h)return;let t=i.current,s=l.current?.querySelector("[data-chat-process-item]");t&&s?.dataset.chatProcessItem&&(c.current={identity:s.dataset.chatProcessItem,offset:s.getBoundingClientRect().top-t.getBoundingClientRect().top}),m(t=>Math.min(e.length,t+64))},[h,e.length,i]);return(0,r.useLayoutEffect)(()=>{let t=d.current;d.current=e.length,u>=t&&u<e.length&&m(e.length)},[u,e.length]),(0,r.useLayoutEffect)(()=>{let e=c.current;if(!e)return;let t=i.current,s=Array.from(l.current?.querySelectorAll("[data-chat-process-item]")??[]).find(t=>t.dataset.chatProcessItem===e.identity);if(c.current=null,!t||!s)return;let n=s.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=n-e.offset},[p,i]),(0,r.useEffect)(()=>{let e=i.current,t=o.current;if(!e||!t||!h)return;let s=()=>{let s=e.getBoundingClientRect().top,n=t.getBoundingClientRect().top;return n>=s-96&&n<=s+96},n=e=>{e.deltaY<0&&s()&&g()},r=()=>{s()&&g()};return e.addEventListener("wheel",n,{passive:!0}),e.addEventListener("touchmove",r,{passive:!0}),()=>{e.removeEventListener("wheel",n),e.removeEventListener("touchmove",r)}},[h,g,i]),(0,n.jsxs)("div",{ref:l,children:[h?(0,n.jsx)("div",{ref:o,className:"h-px","data-chat-process-history":!0,"aria-hidden":"true"}):null,e.slice(p).map((r,i)=>{let l=p+i,o=e[l-1],d=o?.message.summary.type==="assistant"&&!o.hideAssistantText&&!!o.message.summary.text.trim();return(0,n.jsx)("div",{"data-chat-process-item":r.message.identity,className:l>0?d?"mt-5":"mt-2":void 0,children:(0,n.jsx)(d1,{item:r,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a})},r.message.identity)})]})}let d5=(0,r.memo)(function({turn:e,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a}){let{t:i}=(0,f.Bd)("conversation"),[l,o]=(0,r.useState)(!1),d=(0,r.useContext)(df),c=(0,J.t4)();(0,J.So)();let u=e.processItems.filter(e=>!e.hideAssistantText||"pi-desk/assistant"===e.message.viewKey&&null===c.getMessageViewResolution(e.message.viewKey)),m=e.running||l,p=(0,r.useCallback)(t=>{e.running||(t&&d(),o(t))},[d,e.running]);return 0===u.length?null:(0,n.jsxs)(eW.Nt,{open:m,onOpenChange:p,className:"w-full",children:[(0,n.jsxs)(eW.R6,{className:(0,C.cn)(dg().detailText,"flex min-h-9 w-full cursor-pointer items-center gap-2 py-1 text-left text-muted-foreground hover:text-foreground"),children:[(0,n.jsxs)("span",{className:"flex-1",children:[i("processGroup"),e.toolCount>0?` \xb7 ${i("toolCalls",{count:e.toolCount})}`:""]}),(0,n.jsx)(eq.A,{className:(0,C.cn)("size-4 transition-transform",m&&"rotate-180")})]}),(0,n.jsx)(eW.Ke,{className:dw,children:(0,n.jsx)("div",{className:"pt-2",children:(0,n.jsx)(d2,{items:u,onLoadDetail:t,onAcquireImage:s,onPreviewFile:a})})})]})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&e.onPreviewFile===t.onPreviewFile&&e.turn.running===t.turn.running&&e.turn.toolCount===t.turn.toolCount&&d4(e.turn.processItems,t.turn.processItems));function d3(e,t){return e===t||!!e&&!!t&&e.identity===t.identity&&(e.durable||t.durable?e.durable===t.durable&&e.usageIncomplete===t.usageIncomplete&&(e.usageCalls?.length??0)===(t.usageCalls?.length??0)&&(e.usageCalls??[]).every((e,s)=>e.durable===t.usageCalls?.[s]?.durable):e.tempId===t.tempId&&e.summary===t.summary&&e.detail===t.detail&&e.timestampMs===t.timestampMs)}function d4(e,t){return e===t||e.length===t.length&&e.every((e,s)=>{let n=t[s];return void 0!==n&&e.hideAssistantText===n.hideAssistantText&&d3(e.message,n.message)})}let d6=(0,r.memo)(function({message:e,onLoadDetail:t,onAcquireImage:s}){return(0,n.jsx)(oL,{message:e,loadDetail:t,defaultView:(0,n.jsx)(dE,{message:e,onAcquireImage:s})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&e.onAcquireImage===t.onAcquireImage&&d3(e.message,t.message)),d8=(0,r.memo)(function({message:e,onLoadDetail:t}){return"assistant"!==e.summary.type?null:(0,n.jsx)(oL,{message:e,loadDetail:t,defaultView:(0,n.jsx)(dA,{message:e,text:e.summary.text})})},(e,t)=>e.onLoadDetail===t.onLoadDetail&&d3(e.message,t.message)),d7=(0,r.memo)(function({turn:e,cwd:t,logicalTail:s=!1,onLoadDetail:r,onAcquireImage:a,onPreviewFile:i}){if(e.compaction)return(0,n.jsx)("section",{className:(0,C.cn)(!e.running&&"pi-desk-chat-turn-contained"),"data-chat-turn":e.identity,"data-chat-logical-tail":s?"":void 0,children:(0,n.jsx)(oL,{message:e.compaction,loadDetail:r,defaultView:(0,n.jsx)(d0,{message:e.compaction,onLoadDetail:r})})});let l=e.running&&0===e.processItems.length&&null===e.finalAssistant;return(0,n.jsxs)("section",{className:(0,C.cn)("space-y-3",!e.running&&"pi-desk-chat-turn-contained"),"data-chat-turn":e.identity,"data-chat-logical-tail":s?"":void 0,children:[e.user?(0,n.jsx)(d6,{message:e.user,onLoadDetail:r,onAcquireImage:a}):null,(0,n.jsx)(dv.Provider,{value:a,children:(0,n.jsx)(db.Provider,{value:t,children:(0,n.jsx)(d5,{turn:e,onLoadDetail:r,onAcquireImage:a,onPreviewFile:i})})}),l?(0,n.jsx)(d$,{}):null,e.finalAssistant?(0,n.jsx)(d8,{message:e.finalAssistant,onLoadDetail:r}):null]})},(e,t)=>{var s,n;return e.cwd===t.cwd&&e.logicalTail===t.logicalTail&&e.onAcquireImage===t.onAcquireImage&&e.onLoadDetail===t.onLoadDetail&&e.onPreviewFile===t.onPreviewFile&&((s=e.turn)===(n=t.turn)||s.identity===n.identity&&s.running===n.running&&s.toolCount===n.toolCount&&d3(s.user,n.user)&&d3(s.finalAssistant,n.finalAssistant)&&d3(s.compaction,n.compaction)&&d4(s.processItems,n.processItems))});d7.displayName="L3ConversationTurnView";let d9={running:"statusRunning",completed:"statusCompleted",failed:"statusFailed",stopped:"statusStopped",interrupted:"statusInterrupted"};function ce(e,t){return null!==e&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}function ct(e,t){let s=Math.max(0,Math.round(((e.endedAt??Date.now())-e.startedAt)/1e3));if(s<60)return t("seconds",s);let n=Math.floor(s/60);if(n<60)return t("minutes",n);let r=Math.floor(n/60);return`${t("hours",r)}${n%60?` ${t("minutes",n%60)}`:""}`}function cs(e){return[e.taskKind,e.taskType].filter(e=>!!e).join(" / ")}function cn(e){switch(e){case"running":return(0,n.jsx)(b.A,{className:"size-4 animate-spin text-foreground"});case"completed":return(0,n.jsx)(ln.A,{className:"size-4 text-status-success"});case"failed":return(0,n.jsx)(l$.A,{className:"size-4 text-destructive"});case"interrupted":return(0,n.jsx)(lR.A,{className:"size-4 text-status-warning"});case"stopped":return(0,n.jsx)(lT.A,{className:"size-4 text-muted-foreground"})}}function cr({info:e}){let{t}=(0,f.Bd)("taskCenter"),s=(0,Q.G)(),[a,i]=(0,r.useState)(null);if(0===e.length)return null;let l=(e,n)=>{(0,e7.x)(e.value).then(r=>{r?i(n):s.error(t("copyFailed",{name:e.label}))})};return(0,n.jsx)("div",{"data-task-info-scroll":"",className:"max-h-32 overflow-y-auto pr-1 [scrollbar-gutter:stable]",children:(0,n.jsx)("dl",{className:"flex flex-wrap gap-2",children:e.map((e,s)=>{let r=`${e.label}:${s}:${e.value}`,i=a===r;return(0,n.jsxs)("div",{role:"button",tabIndex:0,"aria-label":t(i?"copied":"copy",{name:e.label}),title:i?t("copiedShort"):t("clickToCopy",{name:e.label}),className:(0,C.cn)("flex min-h-8 min-w-0 max-w-full cursor-pointer items-start gap-2 rounded-md px-2 py-1 text-sm outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",i&&"bg-muted"),onClick:()=>l(e,r),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),l(e,r))},children:[(0,n.jsx)("dt",{className:"shrink-0 pt-0.5 font-medium text-muted-foreground",children:e.label}),(0,n.jsx)("dd",{className:"min-w-0 flex-1 break-words text-foreground",children:e.value}),(0,n.jsx)("span",{className:"shrink-0 pt-0.5 text-muted-foreground","aria-hidden":"true",children:i?(0,n.jsx)(em.A,{className:"size-3.5 text-status-success"}):(0,n.jsx)(Z.A,{className:"size-3.5"})})]},`${e.label}:${s}`)})})})}function ca({snapshot:e,running:t,runtime:s,cwd:a}){let{t:i}=(0,f.Bd)("taskCenter"),l=(0,r.useMemo)(()=>oi(e,t),[t,e]),o=l.findLast(e=>null!==e.user)??null;return(0,n.jsx)(lL,{className:"h-full min-h-0",initial:"instant",resize:"instant","aria-label":i("conversationDetails"),children:(0,n.jsx)(oC,{turns:l,focusTurnIdentity:o?.identity??null,initialAnchor:null,children:e=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ov,{}),(0,n.jsx)(dy,{children:(0,n.jsxs)(lF,{scrollClassName:"pi-desk-chat-scrollbar",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-4 pt-3 pb-6 sm:px-6",children:[l.length>0?e.visibleTurns.map((t,r)=>{let i=e.startIndex+r;return(0,n.jsx)(d7,{turn:t,cwd:a,logicalTail:e.containsTail&&i===l.length-1,onLoadDetail:s.loadMessageDetail,onAcquireImage:s.acquireImage},t.identity)}):(0,n.jsx)("div",{className:"grid min-h-48 place-items-center text-sm text-muted-foreground",children:i("noMessages")}),(0,n.jsx)("div",{className:"h-4 shrink-0","aria-hidden":"true"})]})}),(0,n.jsx)(oA,{turns:l,window:e})]})})})}function ci({task:e,runtime:t,cwd:s}){let{t:a}=(0,f.Bd)("taskCenter"),i=(0,r.useSyncExternalStore)(t.subscribe,t.getState,t.getState),l=e?i.details[e.taskId]:void 0,[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),h=async()=>{if(!o)return void d(!0);u(!0),p(null);try{await t.interruptSelected(),d(!1)}catch(e){p(e instanceof Error?e.message:a("interruptFailed"))}finally{u(!1)}};if(!e)return(0,n.jsx)("div",{className:"grid h-full min-h-0 place-items-center px-6 text-center text-sm text-muted-foreground",children:a("selectTask")});let g=cs(e);return(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsx)("header",{className:"shrink-0 border-b px-4 py-3 lg:pr-16",children:(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-start gap-2",children:[(0,n.jsx)("span",{className:"mt-0.5 shrink-0",children:cn(e.status)}),(0,n.jsx)("h3",{className:"min-w-0 break-words text-sm font-semibold",children:g?`${g} \xb7 ${e.title}`:e.title})]}),(0,n.jsxs)("div",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs",children:[(0,n.jsx)("span",{className:(0,C.cn)("rounded-md px-1.5 py-0.5 font-medium",function(e){switch(e){case"running":return"bg-muted text-foreground";case"completed":return"bg-muted text-status-success";case"failed":return"bg-muted text-destructive";case"interrupted":return"bg-muted text-status-warning";case"stopped":return"bg-muted text-muted-foreground"}}(e.status)),children:a(d9[e.status])}),(0,n.jsx)("span",{className:"text-muted-foreground",children:ct(e,(e,t)=>a(e,{count:t}))}),e.activity?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground/60",children:"\xb7"}),(0,n.jsx)("span",{className:"min-w-0 break-words text-muted-foreground",children:e.activity})]}):null]})]}),l?.canInterrupt?(0,n.jsxs)(N.$,{className:"shrink-0",type:"button",size:"sm",variant:o?"destructive":"outline",disabled:c,onClick:()=>void h(),children:[c?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(lT.A,{}),o?a("confirmInterrupt"):a("interrupt")]}):null]})}),m?(0,n.jsx)("p",{role:"alert",className:"shrink-0 border-b bg-muted px-4 py-2 text-sm text-destructive",children:m}):null,e.info.length>0?(0,n.jsx)("div",{className:"shrink-0 border-b px-4 py-2",children:(0,n.jsx)(cr,{info:e.info})}):null,(0,n.jsxs)("div",{className:"relative min-h-0 flex-1",children:[l?.body?.kind==="conversation"?(0,n.jsx)(ca,{snapshot:l.body,running:"running"===e.status,runtime:t,cwd:s}):l?.body?.kind==="text"?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("pre",{className:(0,C.cn)("whitespace-pre-wrap break-words font-mono text-sm leading-[1.6]"),children:l.body.text||a("waitingOutput")})}):l?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("div",{className:"grid min-h-48 place-items-center px-2 text-center text-sm text-muted-foreground",children:a("noDetails")})}):(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-5",children:(0,n.jsx)("div",{className:"grid min-h-48 place-items-center px-2 text-center text-sm text-muted-foreground",children:i.error?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-destructive",children:i.error}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",onClick:()=>t.selectTask(e.taskId),children:[(0,n.jsx)(lP.A,{}),a("retry")]})]}):(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),a("loadingDetail")]})})}),i.refreshing?(0,n.jsxs)("div",{className:"pointer-events-none absolute right-3 top-3 flex items-center gap-2 rounded-md border bg-popover px-2 py-1 text-xs text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-3 animate-spin"}),a("refreshing")]}):null]})]})}function cl({source:e,tasks:t,runtime:s,cwd:a}){let{t:i}=(0,f.Bd)("taskCenter"),{locale:l,timeZone:o}=(0,eG.i)(),d=(0,r.useCallback)(()=>{let e=s.getState();return JSON.stringify([e.open,e.source?.workId??null,e.source?.sessionId??null,e.source?.branchId??null,e.selectedTaskId])},[s]);(0,r.useSyncExternalStore)(s.subscribe,d,d);let c=s.getState(),[u,m]=(0,r.useState)(!1),p=t.find(e=>e.taskId===c.selectedTaskId)??null;(0,r.useEffect)(()=>{c.open&&ce(c.source,e)&&s.reconcileTasks(e,t)},[s,e,c.open,c.source,t]);let h=u&&null!==c.selectedTaskId,g=c.open&&ce(c.source,e);return(0,n.jsx)(ej.YV,{open:g,onOpenChange:e=>{e||s.close()},children:(0,n.jsxs)(ej.hA,{"aria-label":i("title"),showCloseButton:!1,className:"h-[calc(100dvh-2rem)] max-w-[70rem] flex-row bg-background max-lg:h-dvh max-lg:max-h-dvh max-lg:w-dvw max-lg:max-w-none max-lg:rounded-none max-lg:border-0",children:[(0,n.jsxs)("div",{className:(0,C.cn)("flex min-w-0 flex-1 flex-col border-r bg-sidebar lg:max-w-80",h&&"hidden lg:flex"),children:[(0,n.jsxs)("header",{className:"flex min-h-14 items-center gap-3 border-b px-4 py-3",children:[(0,n.jsx)(lD.A,{className:"size-5 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(ej.YM,{children:i("title")}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:i("recordCount",{count:t.length})})]}),(0,n.jsx)(N.$,{className:"lg:hidden",type:"button",variant:"ghost",size:"icon","aria-label":i("close"),onClick:()=>s.close(),children:(0,n.jsx)(Y.A,{})})]}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:t.length>0?(0,n.jsx)("div",{className:"space-y-1",children:t.map(e=>{let t=cs(e),r=ct(e,(e,t)=>i(e,{count:t})),a=od(e.startedAt,void 0,l,o);return(0,n.jsxs)("button",{type:"button","aria-current":e.taskId===c.selectedTaskId?"true":void 0,onClick:()=>{var t;return t=e.taskId,void(s.selectTask(t),m(!0))},className:(0,C.cn)("grid min-h-14 w-full cursor-pointer grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-x-2 rounded-lg px-3 py-3 text-left outline-none transition-colors hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",e.taskId===c.selectedTaskId&&"bg-accent text-accent-foreground hover:bg-accent"),children:[(0,n.jsx)("span",{className:"mt-0.5 shrink-0",children:cn(e.status)}),(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsxs)("span",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-baseline gap-x-3",children:[(0,n.jsx)("span",{className:"truncate text-sm font-medium",children:e.title}),(0,n.jsxs)("span",{className:"whitespace-nowrap text-xs tabular-nums text-muted-foreground","aria-label":i("runningTime",{duration:r,time:a.full}),children:[r,(0,n.jsx)("span",{className:"mx-1 text-muted-foreground/50","aria-hidden":"true",children:"\xb7"}),(0,n.jsx)("time",{dateTime:new Date(e.startedAt).toISOString(),children:a.compact})]})]}),t?(0,n.jsx)("span",{className:"mt-1 block truncate text-xs text-muted-foreground",children:t}):null]}),(0,n.jsx)(e8.A,{className:"mt-1 size-4 shrink-0 text-muted-foreground lg:hidden"})]},e.taskId)})}):(0,n.jsx)("div",{className:"grid min-h-48 place-items-center text-sm text-muted-foreground",children:i("noTasks")})})]}),(0,n.jsx)("div",{className:(0,C.cn)("min-w-0 flex-1",!h&&"hidden lg:block"),children:(0,n.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-12 items-center gap-2 border-b bg-muted/10 px-3 lg:hidden",children:[(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":i("back"),onClick:()=>m(!1),children:(0,n.jsx)(E.A,{})}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-center text-xs text-muted-foreground",children:p?.title??i("detail")}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"icon","aria-label":i("close"),onClick:()=>s.close(),children:(0,n.jsx)(Y.A,{})})]}),(0,n.jsx)("div",{className:"min-h-0 flex-1",children:(0,n.jsx)(ci,{task:p,runtime:s,cwd:a},p?.taskId??"no-task")})]})}),(0,n.jsx)(N.$,{className:"absolute right-4 top-3 z-10 hidden lg:inline-flex",type:"button",variant:"ghost",size:"icon","aria-label":i("close"),onClick:()=>s.close(),children:(0,n.jsx)(Y.A,{})})]})})}function co({source:e,cwd:t,tasks:s,runtime:r,variant:a}){let{t:i}=(0,f.Bd)("taskCenter"),l=s.filter(e=>"running"===e.status),o=l[0],d=()=>{r.open(e,(s.find(e=>"running"===e.status)??s[0]??null)?.taskId??null)};return"footer"===a?s.length>0?(0,n.jsx)(lJ,{tooltip:i("title"),"aria-label":i("open"),onClick:d,children:(0,n.jsx)(lD.A,{className:"size-4"})}):(0,n.jsx)(n.Fragment,{}):"menu"===a?(0,n.jsxs)(K._2,{onClick:d,children:[(0,n.jsx)(lD.A,{className:"size-4"}),i("title")]}):(0,n.jsxs)(n.Fragment,{children:[o?(0,n.jsxs)("button",{type:"button",className:"mb-2 flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-md border bg-muted px-2.5 text-left text-sm text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",onClick:d,"aria-label":`${i("open")}, ${i("runningCount",{count:l.length})}`,children:[(0,n.jsx)(b.A,{className:"size-3.5 shrink-0 animate-spin text-foreground"}),(0,n.jsx)("span",{className:"shrink-0 font-medium text-foreground",children:i("runningCount",{count:l.length})}),(0,n.jsxs)("span",{className:"min-w-0 flex-1 truncate",children:[o.title,o.activity?` \xb7 ${o.activity}`:""]}),(0,n.jsx)(e8.A,{className:"size-3.5 shrink-0"})]}):null,(0,n.jsx)(cl,{source:e,tasks:s,runtime:r,cwd:t})]})}function cd({source:e,cwd:t,pluginState:s,runtime:a,variant:i}){let l=(0,r.useMemo)(()=>{let e=lv.safeParse(s);return e.success?e.data.tasks:[]},[s]);return(0,n.jsx)(co,{source:e,cwd:t,tasks:l,runtime:a,variant:i})}var cc=s(74577),cu=s(85232);function cm(e){return`${e.location.index}:${e.location.entryId}`}let cp={user:["viewKey","hasDetail"],assistant:["viewKey","status","hasDetail","usage"],tool:["viewKey","status","hasDetail","usage"],bash:["viewKey","status","hasDetail"],custom:["viewKey","hasDetail"]};function ch(e,t,s){if(!t)return e;let n={...e,...t};return"summary"===s?ld.Hf.parse(n):ld.D8.parse(n)}function cg(e,t){if(Array.isArray(e.parent)){if("number"!=typeof e.key)throw Error("Increment array key is invalid");e.parent[e.key]=t;return}if("string"!=typeof e.key)throw Error("Increment object key is invalid");e.parent[e.key]=t}function cx(e,t,s){let n=structuredClone(e),r=function(e,t){if(0===t.length)throw Error("Increment cannot append to the message layer root");let s=e;for(let e of t.slice(0,-1)){if("number"==typeof e){if(!Array.isArray(s)||e>=s.length)throw Error(`Increment array path does not exist: ${e}`);s=s[e];continue}if(!s||"object"!=typeof s||Array.isArray(s))throw Error(`Increment object path does not exist: ${e}`);if(!Object.hasOwn(s,e))throw Error(`Increment object field does not exist: ${e}`);s=s[e]}let n=t.at(-1);if("number"==typeof n){if(!Array.isArray(s)||n>=s.length)throw Error(`Increment array target does not exist: ${n}`);return{parent:s,key:n,value:s[n]}}if(!s||"object"!=typeof s||Array.isArray(s))throw Error(`Increment object target does not exist: ${n}`);if(!Object.hasOwn(s,n))throw Error(`Increment target does not exist: ${n}`);return{parent:s,key:n,value:s[n]}}(n,t);if("string"==typeof s){if("string"!=typeof r.value)throw Error("Increment target is not a string");return cg(r,`${r.value}${s}`),ld.Hf.parse(n)}if(!Array.isArray(r.value))throw Error("Increment target is not an array");return cg(r,[...r.value,...s]),ld.Hf.parse(n)}function cf(e,t,s){let n=new Map(e.messages.filter(e=>void 0!==e.detail).map(e=>[cm(e),e]));return{messages:t.map(e=>{let t=n.get(cm(e));return e.fixed.hasDetail&&t&&t.fixed.type===e.fixed.type&&t.fixed.viewKey===e.fixed.viewKey&&void 0!==t.detail?ld.mj.parse({...e,detail:t.detail}):e}),temporaryMessages:[...s]}}function cb(e,t){if("message_start"===t.type){if(e.temporaryMessages.some(e=>e.location.tempId===t.snapshot.location.tempId))throw Error(`Temporary conversation message already exists: ${t.snapshot.location.tempId}`);return{...e,temporaryMessages:[...e.temporaryMessages,t.snapshot]}}let s=e.temporaryMessages.findIndex(e=>e.location.tempId===t.location.tempId);if(s<0)throw Error(`Temporary conversation message was not found: ${t.location.tempId}`);if("message_update"===t.type){let n=[...e.temporaryMessages];return n[s]=function(e,t){var s,n;if(e.location.tempId!==t.location.tempId)throw Error(`Conversation update tempId mismatch: ${t.location.tempId}`);let r=(s=e.fixed,(n=t.fixed)?(!function(e,t,s){let n=Object.keys(e).filter(e=>!t.includes(e));if(n.length>0)throw Error(`${s} patch contains fields invalid for the current message: ${n}`)}(n,cp[s.type],`${s.type} fixed`),ld.q5.parse({...s,...n})):s),a=ch(e.summary,t.summary,"summary"),i=e.detail;if(void 0!==t.detail||Object.keys(t.increments??{}).some(e=>"detail"===(0,cu.U)(e).root)){if(t.fixed?.hasDetail===!1)throw Error("Realtime detail cannot be updated while explicitly clearing hasDetail");r.hasDetail||(r=ld.q5.parse({...r,hasDetail:!0}))}for(let[e,s]of(t.detail&&(i=ch(i??{},t.detail,"detail")),Object.entries(t.increments??{}))){let t=(0,cu.U)(e);"summary"===t.root?a=cx(a,t.segments,s):i=cx(i??{},t.segments,s)}return r.hasDetail||(i=void 0),ld.s4.parse({location:e.location,fixed:r,summary:a,...void 0===i?{}:{detail:i}})}(n[s],t),{...e,temporaryMessages:n}}if("message_discard"===t.type)return{...e,temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)};if(t.durable.index!==e.messages.length)throw Error(`Conversation commit index is not continuous: expected ${e.messages.length}, received ${t.durable.index}`);if(e.messages.some(e=>e.location.entryId===t.durable.entryId))throw Error(`Conversation commit entryId already exists: ${t.durable.entryId}`);let{detail:n,fixed:r,...a}=e.temporaryMessages[s],i=ld.mj.parse({...a,location:t.durable,fixed:{...r,timestampMs:t.fixed.timestampMs},...r.hasDetail&&void 0!==n?{detail:n}:{}});return{messages:[...e.messages,i],temporaryMessages:e.temporaryMessages.filter(e=>e.location.tempId!==t.location.tempId)}}function cv(e,t){let s=e.messages.findIndex(e=>e.location.index===t.index&&e.location.entryId===t.entryId);if(s<0)throw Error(`Conversation detail target was not found: ${t.index}/${t.entryId}`);let n=e.messages[s];if(null!==t.detail&&!n.fixed.hasDetail)throw Error("Message without hasDetail cannot accept detail");let r=[...e.messages];return r[s]=ld.mj.parse({...n,...null===t.detail?{detail:void 0}:{detail:t.detail}}),{...e,messages:r}}function cw(e,t){return e.taskId!==t.taskId||e.body?.kind!=="conversation"||t.body?.kind!=="conversation"?t:lj.parse({...t,body:{kind:"conversation",truncated:t.body.truncated,...cf(e.body,t.body.messages,t.body.temporaryMessages)}})}var cy=s(7237);function ck(e){return(0,ed.B)({msg:cc.U["zh-CN"][e],i18n:{key:`taskCenter:${e}`}})}let cj=Object.freeze({open:!1,source:null,selectedTaskId:null,details:{},loading:!1,refreshing:!1,error:null});function cN(e,t){return e===t||null!==e&&null!==t&&e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}var cI=s(15381),cC=s(94853);let cS=sH.rh,cM=sH.eC,cz=a.Ik({workId:cI.eW,cwd:cI.ik}).strict(),cE=cz.extend({path:cS}).strict(),cA=cz.extend(sH.Nu.shape).strict(),c$=cC.Ot.request.safeExtend({workId:cI.eW});cC.Ot.response;let cR=sH.p$,cT=cz.extend({path:cM,imagePreviewMode:cR}).strict();var cP=s(46117),cD=s.n(cP);function cO({mobile:e,open:t,sidebar:s,children:a,onClose:i}){let{t:l}=(0,f.Bd)("workbench"),o=(0,S.fk)(),d=(0,r.useRef)(288);return((0,r.useLayoutEffect)(()=>{if(e)return;let s=requestAnimationFrame(()=>{o.current?.resize(t?d.current:0)});return()=>cancelAnimationFrame(s)},[e,t,o]),e)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button","aria-label":l("closeSessionMenu"),"aria-hidden":!t,tabIndex:t?0:-1,onClick:i,className:(0,C.cn)(cD().backdrop,"fixed inset-0 z-40 bg-black/35",t?"opacity-100":"pointer-events-none opacity-0")}),(0,n.jsx)("div",{"data-testid":"mobile-work-session-drawer","data-open":t,"aria-hidden":!t||void 0,inert:!t||void 0,className:(0,C.cn)(cD().drawer,"fixed inset-y-0 left-0 z-50 flex w-[min(86vw,320px)] flex-col border-r bg-sidebar shadow-2xl",!t&&"pointer-events-none"),children:s}),(0,n.jsx)("div",{className:"flex min-h-0 min-w-0 flex-1",inert:t||void 0,children:a})]}):(0,n.jsxs)(I.HK,{orientation:"horizontal",disableCursor:!0,className:(0,C.cn)(cD().panelGroup,"pi-desk-workbench-resize-group min-h-0 min-w-0 flex-1"),onLayoutChanged:(e,s)=>{if(!s.isUserInteraction||!t)return;let n=o.current?.getSize().inPixels;void 0!==n&&(d.current=n)},children:[(0,n.jsx)(I.wV,{id:"work-session-sidebar",panelRef:o,defaultSize:288,minSize:224*!!t,maxSize:480*!!t,disabled:!t,"aria-hidden":!t||void 0,inert:!t||void 0,className:"flex h-full min-h-0 min-w-0 !overflow-hidden bg-sidebar",children:(0,n.jsx)("div",{className:"flex h-full w-full min-w-[224px] flex-col border-r",children:s})}),(0,n.jsx)(I.WM,{withHandle:!0,"aria-label":l("resizeSessionList"),"aria-hidden":!t||void 0,disabled:!t,className:(0,C.cn)("cursor-col-resize",!t&&"w-0 pointer-events-none opacity-0")}),(0,n.jsx)(I.wV,{id:"work-session-content",minSize:360,className:"flex h-full min-h-0 min-w-0 !overflow-hidden",children:a})]})}let cL=a.Ik({application:a.eu("Pi Desk"),status:a.eu("ready"),version:a.Yj().trim().min(1).nullable().default(null),boundaries:a.Ik({client:a.eu("isolated"),server:a.eu("isolated"),common:a.eu("shared")}),layers:a.PV([a.eu("L1 Entry"),a.eu("L2 Biz"),a.eu("L3 Modules"),a.eu("L4 Foundation")])});var cF=s(5011),c_=s(42515),cB=s(91399),cq=s(95826),cW=s(37975),cY=s(56592),cU=s(31343);function cV(e,t){return(0,ed.B)({msg:cU.R["zh-CN"][e],i18n:{key:`workbench:${e}`,...t?{params:t}:{}}})}function cK(e){let{workId:t,sessionId:s,branchId:n}=e.source;return JSON.stringify([t,s,n,e.cwd])}function cH(e,t,s){return`${cK(e)}\u0000${s}\u0000${t}`}class cG{peek(e,t,s){let n=this.images.get(cH(e,t,s));return!n||0===n.references&&Date.now()-n.unusedAt>=6e4?null:n.url}get(e,t,s){this.trim();let n=cH(e,t,s),r=this.images.get(n);return r?this.acquire(n,r):null}store(e,t,s,n){if(this.disposed||!this.validSources.has(cK(e)))throw Error("工作会话来源已变化");let r=cH(e,t,s),a=this.images.get(r);if(a)return this.acquire(r,a);let i={url:URL.createObjectURL(n),size:n.size,references:0,unusedAt:Date.now()};return this.images.set(r,i),this.acquire(r,i)}invalidate(e,t,s){this.remove(cH(e,t,s))}reconcileWorkSessions(e){for(let t of(this.validSources=new Set(e.map(e=>cK({source:e,cwd:e.cwd}))),this.images.keys()))this.validSources.has(t.split("\0")[0])||this.remove(t);this.trim()}dispose(){for(let e of(this.disposed=!0,this.images.keys()))this.remove(e);this.validSources.clear()}acquire(e,t){t.references+=1,this.images.delete(e),this.images.set(e,t),this.trim();let s=!1;return{url:t.url,release:()=>{s||(s=!0,t.references-=1,0===t.references&&(t.unusedAt=Date.now()),this.trim())}}}remove(e){let t=this.images.get(e);t&&(URL.revokeObjectURL(t.url),this.images.delete(e))}trim(){let e=Date.now(),t=[...this.images.values()].reduce((e,t)=>e+t.size,0);for(let[s,n]of this.images)!(n.references>0)&&(e-n.unusedAt<6e4&&t<=0x4000000&&this.images.size<=64||(this.remove(s),t-=n.size))}constructor(){this.images=new Map,this.validSources=new Set,this.disposed=!1}}class cJ{constructor(e,t,s=()=>void 0){this.biz=e,this.gitBiz=t,this.onNotice=s,this.standaloneImages=new cG,this.listeners=new Set,this.workspaces=new Map,this.sources=new Map,this.previewDirectories=new Map,this.expandedWorkId=null,this.revision=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getRevision=()=>this.revision}getWorkspace(e){let t=e?this.workspaces.get(e):null;return t?{...t.files.state,cwd:t.files.cwd,windowOpen:t.windowOpen,chatWidthPercent:t.chatWidthPercent,activePane:t.activePane}:null}getFileRuntime(e){return this.workspaceFor(e).files}getExpandedWorkId(){return this.expandedWorkId}getDirectories(e){return this.previewDirectories.get(e)?.directories??[]}getDirectory(e){let t=this.previewDirectories.get(e);if(!t)throw Error(cV("sourceChanged"));return t.selectedDirectory}applyPreviewDirectories(e,t){let s=this.sources.get(e.workId);if(!s||s.sessionId!==e.sessionId||s.branchId!==e.branchId)return;let n=this.previewDirectories.get(e.workId),r=new Map([[(0,cW.Yj)(s.cwd),s.cwd]]);for(let e of t.directories){let t=(0,cW.Yj)(e);r.has(t)||r.set(t,e)}let a=t.defaultDirectory?r.get((0,cW.Yj)(t.defaultDirectory))??null:null,i=(n.defaultDirectory?(0,cW.Yj)(n.defaultDirectory):null)!==(a?(0,cW.Yj)(a):null)?a??s.cwd:r.get((0,cW.Yj)(n.selectedDirectory))??s.cwd,l=[...r.values()];if(n.defaultDirectory===a&&n.selectedDirectory===i&&n.directories.length===l.length&&n.directories.every((e,t)=>e===l[t]))return;this.previewDirectories.set(e.workId,{directories:l,defaultDirectory:a,selectedDirectory:i});let o=this.workspaces.get(e.workId);if(o){for(let[e,t]of o.roots)r.has(e)||(t.unsubscribe(),t.files.dispose(),o.roots.delete(e));this.switchFiles(e.workId,o)}this.publish()}selectDirectory(e,t){let s=this.previewDirectories.get(e);if(!s)throw Error(cV("sourceChanged"));let n=s.directories.find(e=>(0,cW.Yj)(e)===(0,cW.Yj)(t));if(!n)throw Error(cV("sourceChanged"));if(s.selectedDirectory===n)return;s.selectedDirectory=n;let r=this.workspaces.get(e);r&&this.switchFiles(e,r),this.publish()}reconcileWorkSessions(e){this.standaloneImages.reconcileWorkSessions(e);let t=new Map(e.map(({workId:e,cwd:t,sessionId:s,branchId:n})=>[e,{workId:e,cwd:t,sessionId:s,branchId:n}])),s=!1;for(let[e,n]of this.sources){let r=t.get(e);if(r?.cwd===n.cwd&&r.sessionId===n.sessionId&&r.branchId===n.branchId)continue;let a=this.workspaces.get(e);a&&(this.disposeLayout(a),this.workspaces.delete(e)),this.previewDirectories.delete(e),s=!0,this.expandedWorkId===e&&(this.expandedWorkId=null)}for(let[e,s]of(this.sources.clear(),t))this.sources.set(e,s),this.previewDirectories.has(e)||this.previewDirectories.set(e,{directories:[s.cwd],defaultDirectory:null,selectedDirectory:s.cwd});s&&this.publish()}ensureRoot(e){return this.getFileRuntime(e).ensureRoot()}ensureDirectory(e,t){return this.getFileRuntime(e).ensureDirectory(t)}setExpandedPaths(e,t){this.getFileRuntime(e).setExpandedPaths(t)}setTreeScrollTop(e,t){this.workspaces.get(e)?.files.setTreeScrollTop(t)}refreshTree(e){this.getFileRuntime(e).refreshTree()}setSearchQuery(e,t){this.getFileRuntime(e).setSearchQuery(t)}search(e,t){return this.getFileRuntime(e).search(t)}openFile(e,t){let s=this.workspaceFor(e);s.windowOpen=!0,s.activePane="files",s.files.openFile(t)}async revealFile(e,t){await this.getFileRuntime(e).revealFile(t)}activateFile(e,t){this.workspaces.get(e)?.files.state.tabs.includes(t)&&this.openFile(e,t)}closeFile(e,t){this.closeTabs(e,t,"current")}closeTabs(e,t,s){this.workspaces.get(e)?.files.closeTabs(t,s)}hideWindow(e){let t=this.workspaces.get(e);t?.windowOpen&&(t.windowOpen=!1,t.activePane="chat",this.expandedWorkId===e&&(this.expandedWorkId=null),this.publish())}showWindow(e){let t=this.workspaceFor(e),{tabs:s,activeDiff:n,activePath:r}=t.files.state;(s.length||n||this.expandedWorkId===e)&&(t.windowOpen=!0,t.activePane="files",this.publish(),!n&&r&&t.files.ensureDocument(r))}setChatWidthPercent(e,t){let s=this.workspaces.get(e);!s||!Number.isFinite(t)||t<=0||t>=100||.001>Math.abs(s.chatWidthPercent-t)||(s.chatWidthPercent=t,this.publish())}setActivePane(e,t){let s=this.workspaces.get(e);s&&s.activePane!==t&&(s.activePane=t,this.publish())}expandWindow(e){this.expandedWorkId=e,this.showWindow(e)}collapseExpandedWindow(){if(!this.expandedWorkId)return;let e=this.workspaces.get(this.expandedWorkId);this.expandedWorkId=null,!e||e.files.state.tabs.length||e.files.state.activeDiff||(e.windowOpen=!1,e.activePane="chat"),this.publish()}reloadFile(e,t){this.workspaces.get(e)?.files.reloadFile(t)}openDiff(e,t,s){let n=this.workspaceFor(e);n.windowOpen=!0,n.activePane="files",n.files.openDiff(t,s)}closeDiff(e){this.closeTabs(e,null,"current")}reloadDiff(e){this.workspaces.get(e)?.files.reloadDiff()}setDiffViewMode(e,t){this.workspaces.get(e)?.files.setDiffViewMode(t)}setDiffWrapLines(e,t){this.workspaces.get(e)?.files.setDiffWrapLines(t)}setDiffCollapseUnchanged(e,t){this.workspaces.get(e)?.files.setDiffCollapseUnchanged(t)}handleGitBranchChanged(e,t){for(let s of this.workspaces.values())for(let n of s.roots.values())n.files.cwd===e&&n.files.handleGitBranchChanged(t)}saveEditorState(e,t,s){this.workspaces.get(e)?.files.saveEditorState(t,s)}setWrapLines(e,t,s){this.workspaces.get(e)?.files.setWrapLines(t,s)}setTextViewMode(e,t,s){this.workspaces.get(e)?.files.setTextViewMode(t,s)}dispose(){for(let e of(this.standaloneImages.dispose(),this.workspaces.values()))this.disposeLayout(e);this.workspaces.clear(),this.sources.clear(),this.previewDirectories.clear(),this.expandedWorkId=null,this.listeners.clear()}workspaceFor(e){if(!this.sources.get(e))throw Error(cV("sourceChanged"));let t=this.workspaces.get(e);if(t)return t;let s={files:this.createFiles(e,this.getDirectory(e)),roots:new Map,windowOpen:!1,chatWidthPercent:50,activePane:"files"};return this.attachRoot(e,s,s.files),this.workspaces.set(e,s),s}createFiles(e,t){let s={workId:e,cwd:t};return new cY.h(t,{list:(e,t)=>this.biz.list({...s,path:e},t),search:(e,t)=>this.biz.search({...s,...e},t),get:(e,t,n)=>this.biz.get({...s,path:e,imagePreviewMode:t},n),diff:(e,t,n)=>this.gitBiz.getDiff({...s,repositoryRoot:e,path:t},n)},{imagePreviewMode:ri.Wq,htmlPreview:!0,onNotice:this.onNotice,reveal:async(e,t)=>{await this.biz.reveal({...s,path:e,..."directory"===t?{targetType:t}:{}})}})}attachRoot(e,t,s){let n=s.subscribe(()=>{t.files===s&&(s.state.activePath||s.state.activeDiff||this.expandedWorkId===e||(t.windowOpen=!1,t.activePane="chat"),this.publish())});t.roots.set((0,cW.Yj)(s.cwd),{files:s,unsubscribe:n})}switchFiles(e,t){let s=this.getDirectory(e),n=(0,cW.Yj)(s);if((0,cW.Yj)(t.files.cwd)===n)return;let r=t.roots.get(n);if(!r){let a=this.createFiles(e,s);this.attachRoot(e,t,a),r=t.roots.get(n)}t.files=r.files,r.files.state.activePath||r.files.state.activeDiff||this.expandedWorkId===e||(t.windowOpen=!1,t.activePane="chat")}disposeLayout(e){for(let t of e.roots.values())t.unsubscribe(),t.files.dispose();e.roots.clear()}publish(){for(let e of(this.revision+=1,this.listeners))e()}}var cQ=s(70657);function cX(e,t,s,n){t.reconcileWorkSessions(s,n,s.flatMap(({workId:t})=>e.getDirectories(t).map(e=>({workId:t,cwd:e}))))}var cZ=s(90504),c0=s(46487),c1=s(97921),c2=s(36510);let c5='data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/%3E';function c3({target:e,paths:t,index:s,onIndexChange:a,biz:i,images:l}){let{t:o}=(0,f.Bd)("workbench"),[d,c]=(0,r.useState)({}),u=(0,r.useRef)(new Map),m=t[s],p=d[m],h=(0,ri.Wq)(),g=l.peek(e,m,h),x=p?.status==="ready"||!p&&null!==g;return(0,r.useLayoutEffect)(()=>{let e=u.current;return()=>{for(let t of e.values())t.release();e.clear()}},[]),(0,r.useLayoutEffect)(()=>{let t,s=u.current;if(p?.status==="error"||s.has(m))return;let n=l.get(e,m,h);if(n)return void s.set(m,n);let r=new AbortController;return(async()=>{try{let n=await i.get({workId:e.source.workId,cwd:e.cwd,path:m,imagePreviewMode:h},r.signal);if(r.signal.aborted)return;if("image"!==n.kind)throw Error(o("standaloneReadFailed"));t=l.store(e,m,h,(0,cy.E)(n));let a=new Image;if(a.src=t.url,await a.decode(),r.signal.aborted)return;let d=t.url;s.set(m,t),c(e=>({...e,[m]:{status:"ready",objectUrl:d}}))}catch(n){if(t&&(t.release(),l.invalidate(e,m,h)),r.signal.aborted)return;let s=n instanceof Error?n.message:o("standaloneReadFailed");console.warn("[Pi Desk][StandaloneImageGallery] 读取图片失败",{workId:e.source.workId,path:m,error:s}),c(e=>({...e,[m]:{status:"error",message:s}}))}})(),()=>{r.abort(),s.get(m)!==t&&t?.release()}},[i,p,l,h,m,o,e]),(0,n.jsxs)("div",{className:"relative size-full","data-testid":"standalone-image-gallery",children:[(0,n.jsx)(ng.k,{mode:"inline",thumbnails:!1,slides:t.map(e=>{let t=d[e];return{src:t?.status==="ready"?t.objectUrl:e===m?g??c5:c5,alt:e}}),index:s,onIndexChange:a}),x?null:(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 z-[2] flex items-center justify-center p-6 pb-20",children:p?.status==="error"?(0,n.jsxs)("div",{className:"flex max-w-full flex-col items-center gap-3 rounded-lg bg-background/95 p-4 text-center",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:p.message}),(0,n.jsx)(N.$,{className:"pointer-events-auto",variant:"outline",onClick:()=>{l.invalidate(e,m,(0,ri.Wq)()),c(e=>{let t={...e};return delete t[m],t})},children:o("reloadFile")})]}):(0,n.jsxs)("div",{role:"status",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),o("loadingFile")]})})]})}function c4(e){return e.replaceAll("\\","/").split("/").at(-1)??e}function c6(e,t){return e instanceof Error?e.message:t}function c8({target:e,biz:t,images:s,mobile:a,onClose:i}){let{t:l}=(0,f.Bd)("workbench"),{t:o}=(0,f.Bd)("projectFiles"),d=(0,r.useRef)(null),[c,u]=(0,r.useState)({mode:"preview",scrollTop:0}),m=(0,r.useRef)(0),[p,h]=(0,r.useState)(null),[g,x]=(0,r.useState)(0),[b,v]=(0,r.useState)(()=>{let t=e&&!e.imagePaths?s.peek(e,e.path,(0,ri.Wq)()):null;return t?{status:"image",objectUrl:t}:{status:"loading"}}),[w,y]=(0,r.useState)(()=>e?.imagePaths?e.imagePaths.indexOf(e.path):0);if((0,r.useLayoutEffect)(()=>{let n;if(!e||e.imagePaths)return;let r=new AbortController,a=!0,i=(0,ri.Wq)(),o=s.get(e,e.path,i);return o?o.release:(t.get({workId:e.source.workId,cwd:e.cwd,path:e.path,imagePreviewMode:i},r.signal).then(t=>{if(!a)return;if("text"===t.kind)return void v({status:"text",content:t.content,size:t.size});let r=s.store(e,e.path,i,(0,cy.E)(t));n=r.release,v({status:"image",objectUrl:r.url})}).catch(t=>{a&&!r.signal.aborted&&(console.warn("[Pi Desk][PluginStandaloneFilePreview] 读取文件失败",{workId:e.source.workId,path:e.path,error:c6(t,l("standaloneReadFailed"))}),v({status:"error",message:c6(t,l("standaloneReadFailed"))}))}),()=>{a=!1,r.abort(),n?.()})},[t,s,g,e,l]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.source===d.current?.contentWindow&&"pi-desk:file-escape"===e.data&&i()};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[i,e]),!e)return null;let k=e.imagePaths?.[w]??e.path,j=(0,c1.g)(k);return(0,n.jsx)(ej.YV,{open:!0,onOpenChange:e=>{e||i()},children:(0,n.jsxs)(ej.hA,{className:a?"inset-0 h-dvh max-h-none w-dvw max-w-none translate-x-0 translate-y-0 rounded-none border-0 ring-0":"h-[min(94dvh,1080px)] w-[min(96dvw,1600px)] max-w-none",children:[(0,n.jsx)(ej.YM,{className:"sr-only",children:c4(k)}),(0,n.jsxs)("section",{"data-testid":"plugin-standalone-file-preview",className:"flex size-full min-h-0 min-w-0 flex-col overflow-hidden bg-background","aria-label":l("standaloneViewer",{name:e.projectName}),children:[(0,n.jsxs)("header",{className:"flex min-h-14 shrink-0 items-center gap-3 border-b pl-3 pr-14 pt-[env(safe-area-inset-top)]",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-semibold",title:c4(k),children:c4(k)}),(0,n.jsxs)("p",{className:"truncate text-xs text-muted-foreground",title:`${e.projectName} \xb7 ${k}`,children:[e.projectName," \xb7 ",k]})]}),"markdown"===j&&"text"===b.status?(0,n.jsx)("div",{className:"flex shrink-0",role:"group","aria-label":o("markdownMode"),children:["preview","source"].map(e=>(0,n.jsx)(N.$,{size:"sm",variant:c.mode===e?"secondary":"ghost","aria-pressed":c.mode===e,onClick:()=>{c.mode!==e&&u({mode:e,scrollTop:m.current})},children:o("preview"===e?"previewMode":"sourceMode")},e))}):null]}),(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden pb-[env(safe-area-inset-bottom)]",children:e.imagePaths?(0,n.jsx)(c3,{target:e,paths:e.imagePaths,index:w,onIndexChange:y,biz:t,images:s}):"loading"===b.status?(0,n.jsx)(c7,{}):"error"===b.status?(0,n.jsxs)("div",{className:"flex size-full flex-col items-center justify-center gap-3 p-6 text-center",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:b.message}),(0,n.jsx)(N.$,{variant:"outline",onClick:()=>{s.invalidate(e,e.path,(0,ri.Wq)()),v({status:"loading"}),x(e=>e+1)},children:l("reloadFile")})]}):"image"===b.status?(0,n.jsx)(ng.k,{mode:"inline",slides:[{src:b.objectUrl,alt:e.path}],ariaLabel:l("standaloneImage",{name:c4(e.path)})}):"markdown"===j&&"preview"===c.mode?(0,n.jsx)(c0.n,{content:b.content,label:o("markdownPreview",{name:k}),savedScrollTop:c.scrollTop,onScroll:e=>{m.current=e}}):"html"===j?(0,n.jsx)("iframe",{ref:d,className:"block size-full border-0 bg-white",sandbox:"allow-scripts",srcDoc:(0,c2.z)(b.content),title:l("standaloneHtml",{name:e.path})}):(0,n.jsx)(cZ.e,{path:e.path,content:b.content,size:b.size,savedState:p,onSaveState:(e,t)=>h(t),onEscape:i})})]})]})})}function c7(){let{t:e}=(0,f.Bd)("workbench");return(0,n.jsxs)("div",{className:"flex size-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),e("loadingFile")]})}var c9=s(3635),ue=s(76812),ut=s.n(ue);let us=(0,c9.default)(()=>Promise.all([s.e(31087),s.e(70669)]).then(s.bind(s,19991)).then(e=>e.L2FileWorkspaceView),{loadableGenerated:{webpack:()=>[19991]},ssr:!1});function un({workSession:e,runtime:t,gitRuntime:s,mobile:a,onOpenGitBranches:i,onOpenSidebar:l,children:o}){let{t:d}=(0,f.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let c=(0,r.useRef)(null),u=(0,S.OG)(),m=(0,r.useRef)(null),p=(0,r.useRef)(null),h=(0,r.useRef)(null),g=(0,r.useRef)(null),x=(0,r.useRef)(null),[b,v]=(0,r.useState)(!1),{workId:w}=e,y=t.getWorkspace(w),k=y?.windowOpen===!0,j=`session-chat-pane-${w}`,N=`session-file-pane-${w}`,M=y?.chatWidthPercent??50,[z]=(0,r.useState)(()=>k?M:100),E=!!(y?.tabs.length||y?.activeDiff),A=b&&!a,$=A&&k,R=t.getExpandedWorkId()===w,T=k&&($||y?.activePane==="files"),P=!T||$;(0,r.useLayoutEffect)(()=>{let e=c.current;if(!e)return;let t=new ResizeObserver(([e])=>{v((e?.contentRect.width??0)>=880)});return t.observe(e),()=>t.disconnect()},[]),(0,r.useLayoutEffect)(()=>{if(!A)return;let e=requestAnimationFrame(()=>{u.current?.setLayout({[j]:k?M:100,[N]:k?100-M:0})});return()=>cancelAnimationFrame(e)},[j,M,N,k,u,A]);let D=e=>{x.current=e};(0,r.useLayoutEffect)(()=>{let e=x.current;if(e&&("chat"===e?P:T)){let t,s;x.current=null,t="chat"===e?m.current:p.current,s="chat"===e?h.current:g.current,s?.isConnected&&t?.contains(s)&&!s.closest("[inert]")?s.focus({preventScroll:!0}):t?.querySelector("chat"===e?'textarea, [data-testid="session-files-entry"]':'[data-testid="file-workspace"]')?.focus({preventScroll:!0})}},[P,T,y?.activePane]);let O=()=>{if(!E)return;let e=t.getWorkspace(w)?.activePane==="files"?"chat":"files";D(e),"files"===e?t.showWindow(w):t.setActivePane(w,"chat")};return(0,n.jsx)("div",{ref:c,"data-testid":"session-file-layout","data-file-layout":$?"split":"single",className:"relative size-full min-h-0 min-w-0 overflow-hidden",onKeyDownCapture:e=>{"Tab"!==e.key||!e.ctrlKey||e.altKey||e.metaKey||e.repeat||e.nativeEvent.isComposing||!E||e.target instanceof Element&&e.target.closest('[role="menu"], [data-slot="app-dialog-content"]')||(e.preventDefault(),e.stopPropagation(),O())},children:(0,n.jsxs)(I.HK,{groupRef:u,className:(0,C.cn)("pi-desk-workbench-resize-group relative size-full min-h-0 min-w-0",A?[cD().panelGroup,ut().wide]:ut().single),orientation:"horizontal",disabled:!$,resizeTargetMinimumSize:{fine:8,coarse:20},onLayoutChanged:(e,s)=>{if(!$||!s.isUserInteraction)return;let n=e[j];void 0!==n&&t.setChatWidthPercent(w,n)},children:[(0,n.jsx)(I.wV,{id:j,"data-pane":"chat",defaultSize:`${z}%`,minSize:320*!!$,"aria-hidden":!P||void 0,inert:!P||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:(0,n.jsx)("div",{ref:m,className:"size-full min-h-0 min-w-0",onPointerDownCapture:()=>t.setActivePane(w,"chat"),onFocusCapture:e=>{h.current=e.target,t.setActivePane(w,"chat")},children:o(P)})}),(0,n.jsx)(I.WM,{id:`session-file-divider-${w}`,"aria-label":d("resizeChatFile"),"aria-hidden":!$||void 0,disabled:!$,disableDoubleClick:!0,className:(0,C.cn)("z-10 w-px cursor-col-resize bg-transparent aria-disabled:cursor-default",!$&&"hidden")}),(0,n.jsx)(I.wV,{id:N,"data-pane":"files",defaultSize:`${100-z}%`,minSize:320*!!$,maxSize:A&&!k?0:void 0,"aria-hidden":!T||void 0,inert:!T||void 0,className:"flex min-h-0 min-w-0 !overflow-hidden",children:(0,n.jsx)("div",{ref:p,className:"size-full min-h-0 min-w-0 overflow-hidden",onPointerDownCapture:()=>t.setActivePane(w,"files"),onFocusCapture:e=>{g.current=e.target,t.setActivePane(w,"files")},children:E&&!R?(0,n.jsx)(us,{workSession:e,runtime:t,gitRuntime:s,mobile:a,presentation:A?"split":"single",onOpenGitBranches:i,onOpenSidebar:l,onHide:()=>{D("chat"),t.hideWindow(w)},onExpand:()=>t.expandWindow(w),onSwitchPane:O},`${e.sessionId}:${e.branchId}`):null})})]})})}function ur({workSessions:e,runtime:t,gitRuntime:s,mobile:a,onOpenGitBranches:i,onOpenSidebar:l,onOpenTerminal:o}){let{t:d}=(0,f.Bd)("workbench");(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let c=e.find(e=>e.workId===t.getExpandedWorkId());if(!c)return null;let u=()=>{a?t.hideWindow(c.workId):t.collapseExpandedWindow()},m=()=>{let e=document.querySelector(`[data-work-id="${CSS.escape(c.workId)}"] textarea`);e&&(t.hideWindow(c.workId),requestAnimationFrame(()=>e.focus({preventScroll:!0})))};return(0,n.jsx)(ej.YV,{open:!0,onOpenChange:e=>{e||u()},children:(0,n.jsxs)(ej.hA,{showCloseButton:!1,onKeyDownCapture:e=>{"Tab"!==e.key||!e.ctrlKey||e.altKey||e.metaKey||e.repeat||e.nativeEvent.isComposing||e.target instanceof Element&&e.target.closest('[role="menu"]')||(e.preventDefault(),e.stopPropagation(),m())},className:a?"inset-0 h-dvh max-h-none w-dvw max-w-none translate-x-0 translate-y-0 rounded-none border-0 ring-0":"h-[min(94dvh,1080px)] w-[min(96dvw,1600px)] max-w-none",finalFocus:()=>{let e=document.querySelector(`[data-work-id="${CSS.escape(c.workId)}"]`);return e?.querySelector("[data-file-expand-trigger]")??e?.querySelector('[data-testid="session-files-entry"]')??!1},children:[(0,n.jsx)(ej.YM,{className:"sr-only",children:d("fileViewer",{name:c.projectName})}),(0,n.jsx)(us,{workSession:c,runtime:t,gitRuntime:s,mobile:a,presentation:a?"single":"expanded",onOpenGitBranches:i,onOpenSidebar:()=>{t.collapseExpandedWindow(),l(c.workId)},onSwitchPane:m,onOpenTerminal:o,onHide:()=>t.hideWindow(c.workId),onExpand:u},`${c.workId}:${c.sessionId}:${c.branchId}`)]})})}var ua=s(93320);async function ui(e,t,s){try{let n=await e.get({...t,imagePreviewMode:"compressed"},s);if("image"!==n.kind)throw Error("该文件不是可展示的图片");return(0,cy.E)(n)}catch(e){if(e instanceof ua.aw&&"errors:fileMissing"===e.errorKey)return null;throw e}}var ul=s(72114),uo=s(31761),ud=s(50479),uc=s(35989);let uu=[];function um(e,t){let s=t.trim().toLocaleLowerCase();return s?e.filter(e=>e.toLocaleLowerCase().includes(s)):[...e]}function up({target:e,runtime:t,mobile:s,onClose:a}){let{t:i}=(0,f.Bd)("workbench"),{locale:l}=(0,eG.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let o=(0,Q.G)(),[d,c]=(0,r.useState)(null),[u,m]=(0,r.useState)(e?.repositoryRoot!==null),[p,h]=(0,r.useState)(""),[g,x]=(0,r.useState)(()=>({repositoryRoot:null,overrides:new Map})),[v,w]=(0,r.useState)(null),[y,k]=(0,r.useState)(!1),[j,I]=(0,r.useState)(""),[S,M]=(0,r.useState)(null),[z,A]=(0,r.useState)(null),$=t.getWorkspace(e?.cwd??null),R=$?.heads.repositories??uu,T=e?null!==e.repositoryRoot&&R.some(t=>t.root===e.repositoryRoot)?e.repositoryRoot:R.find(e=>""===e.root)?.root??R[0]?.root??null:null,P=d??T;(0,r.useEffect)(()=>{e&&t.refreshHeads(e.cwd)},[t,e]),(0,r.useEffect)(()=>{if(!e||null===P||$?.heads.status!=="ready")return;let s=R.find(e=>e.root===P);s?.state==="ready"&&t.loadBranches(e.cwd,P)},[P,R,t,e,$?.heads.status]);let D=R.find(e=>e.root===P)??null,O=null===P?null:$?.branches.get(P)??null,L=O?.data??null,F=null!==P&&!!$?.branchOperations.has(P),_=(0,r.useMemo)(()=>um(L?.local??[],p),[L?.local,p]),B=(0,r.useMemo)(()=>um(L?.remote??[],p),[L?.remote,p]),q=(0,r.useMemo)(()=>um(L?.recent??[],p),[L?.recent,p]),W=(0,r.useMemo)(()=>(0,uc.oY)(_),[_]),Y=(0,r.useMemo)(()=>(0,uc.oY)(B),[B]),V=L?.head.type==="branch"?L.head.name:null,K=(0,r.useMemo)(()=>{let e=new Set;if(!V?.includes("/"))return e;let t=V.split("/");for(let s=1;s<t.length;s+=1)e.add(`local:${t.slice(0,s).join("/")}`);return e},[V]);if(!e)return null;let H=e=>{M(e),I(""),k(!0),w(null),A(null)},G=async(e,t)=>{A(null);try{await e(),o.success(t),a()}catch(e){A(e instanceof Error?e.message:i("gitOperationFailed"))}},J=R.length>1,X=1===R.length?i("repositorySummary",{name:(0,uc.Hj)(e.projectName,R[0].root),branch:"ready"===R[0].state?(0,uc.ws)(R[0].head):i("repositoryUnavailable")}):R.length>1?i("repositoryCount",{count:R.length}):i("readingRepos"),Z=(s,r,a=s.name,l=0)=>{let o="local"===s.type&&s.name===V,d=v?.type===s.type&&v.name===s.name;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button","data-testid":"recent"===r?`git-branch-recent-${s.name}`:`git-branch-${s.type}-${s.name}`,className:(0,C.cn)("grid min-h-9 w-full cursor-pointer grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-2 rounded-lg pr-2 text-left outline-none hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-ring",o&&"font-medium text-foreground",d&&"bg-accent"),style:{paddingLeft:`${8+16*l}px`},title:s.name,onClick:()=>w(d?null:s),children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:o?(0,n.jsx)(em.A,{className:"size-4 text-foreground"}):"remote"===s.type?(0,n.jsx)(ul.A,{className:"size-3.5"}):(0,n.jsx)(uo.A,{className:"size-3.5"})}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:a}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:o?i("current"):"recent"===r?i("recent"):""})]}),d?(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 border-l-2 border-border py-2 pl-2",style:{marginLeft:`${32+16*l}px`},children:[o?null:(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"outline",disabled:F,onClick:()=>{null!==P&&!F&&G(()=>t.replaceBranch(e.cwd,P,s),i("remote"===s.type?"checkedOut":"switchedBranch",{name:s.name}))},children:i("remote"===s.type?"checkoutRemote":"switchGitBranch")}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",disabled:F,onClick:()=>H(s),children:i("branchFromHere")})]}):null]},`${r}:${s.type}:${s.name}`)},ee=(e,t)=>{let s=`${e}:${t}`;return(g.repositoryRoot===P?g.overrides.get(s):void 0)??K.has(s)},es=(e,t,s=0)=>e.map(e=>{if(0===e.children.length&&e.branchName)return Z({type:t,name:e.branchName},t,e.name,s);let r=`${t}:${e.path}`,a=!!p.trim()||ee(t,e.path);return(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button","data-testid":`git-branch-group-${t}-${e.path}`,"aria-expanded":a,className:"grid min-h-9 w-full cursor-pointer grid-cols-[1rem_1rem_minmax(0,1fr)] items-center gap-2 rounded-lg pr-2 text-left text-muted-foreground outline-none hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",style:{paddingLeft:`${8+16*s}px`},title:e.path,onClick:()=>((e,t)=>{if(p.trim())return;let s=`${e}:${t}`,n=ee(e,t);x(e=>{let t=e.repositoryRoot===P?new Map(e.overrides):new Map;return t.set(s,!n),{repositoryRoot:P,overrides:t}})})(t,e.path),children:[(0,n.jsx)(e8.A,{className:(0,C.cn)("size-3 transition-transform",a&&"rotate-90")}),a?(0,n.jsx)(ud.A,{className:"size-4 text-muted-foreground"}):(0,n.jsx)(eR.A,{className:"size-4 text-muted-foreground"}),(0,n.jsx)("span",{className:"truncate font-mono text-sm",children:e.name})]}),a?es(e.children,t,s+1):null]},r)});return(0,n.jsx)(ej.YV,{open:!0,onOpenChange:e=>!e&&a(),children:(0,n.jsxs)(ej.hA,{"data-testid":"git-branch-picker",showCloseButton:!1,finalFocus:!1,className:"h-[min(40rem,calc(100dvh-2rem))] max-w-[45rem] gap-0",children:[(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b px-3",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(ej.YM,{children:i("gitBranches")}),(0,n.jsx)(ej.uX,{className:"truncate text-xs",children:X})]}),(0,n.jsx)(N.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":i("refreshBranches"),disabled:$?.heads.status==="loading",onClick:()=>void t.refreshHeads(e.cwd),children:(0,n.jsx)(et.A,{className:(0,C.cn)("size-4",$?.heads.status==="loading"&&"animate-spin")})}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:a,children:i("close")})]}),(0,n.jsxs)("div",{className:(0,C.cn)("grid min-h-0 flex-1",J&&!s?"grid-cols-[220px_minmax(0,1fr)]":"grid-cols-1"),children:[!J||s&&u?null:(0,n.jsxs)("aside",{className:"pi-desk-chat-scrollbar min-h-0 overflow-y-auto border-r bg-sidebar p-2 max-sm:border-r-0",children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:i("repositories")}),R.map(t=>{let s=(0,uc.Hj)(e.projectName,t.root),r=t.root===P;return(0,n.jsxs)("button",{"data-testid":`git-branch-picker-repository-${t.root||"root"}`,type:"button",className:(0,C.cn)("grid min-h-12 w-full grid-cols-[minmax(0,1fr)_auto] items-center gap-2 rounded-lg px-2 text-left hover:bg-muted/70",r&&"bg-accent text-accent-foreground"),onClick:()=>{var e;c(e=t.root),m(!0),h(""),x({repositoryRoot:e,overrides:new Map}),w(null),k(!1),M(null),A(null)},children:[(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("strong",{className:"block truncate text-sm font-medium",children:s}),(0,n.jsx)("span",{className:"mt-1 block truncate font-mono text-xs text-muted-foreground",children:t.root||"."})]}),(0,n.jsx)("span",{className:"flex flex-col items-end gap-1 text-xs text-muted-foreground",children:(0,n.jsx)("span",{className:"max-w-28 truncate",children:"ready"===t.state?(0,uc.ws)(t.head):i("unavailable")})})]},t.root)})]}),s&&J&&!u?null:(0,n.jsxs)("section",{className:"flex min-h-0 min-w-0 flex-col",children:[(0,n.jsxs)("div",{className:"flex min-h-13 shrink-0 items-center gap-2 border-b px-3",children:[s&&J?(0,n.jsx)(N.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":i("backRepositories"),onClick:()=>m(!1),children:(0,n.jsx)(E.A,{className:"size-4"})}):null,(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("p",{className:"truncate text-sm font-semibold",children:[D?(0,uc.Hj)(e.projectName,D.root):i("chooseRepository"),D?.state==="ready"?` \xb7 ${(0,uc.ws)(D.head)}`:""]}),(0,n.jsx)("p",{className:"mt-1 break-words font-mono text-xs text-muted-foreground",children:D?.root||"."})]}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",disabled:D?.state!=="ready"||F,onClick:()=>H(null),children:[(0,n.jsx)(U.A,{className:"size-3.5"})," ",i("createBranch")]})]}),$?.heads.status==="error"?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:$.heads.error}):null,z?(0,n.jsx)("p",{className:"border-b bg-muted px-3 py-2 text-sm text-destructive",children:z}):null,(0,n.jsx)("div",{className:"flex shrink-0 items-center gap-2 border-b p-2",children:y?(0,n.jsxs)("form",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",onSubmit:s=>{let n;s.preventDefault(),(n=j.trim())&&null!==P&&!F&&G(()=>t.addBranch(e.cwd,P,n,S),i("branchCreated",{name:n}))},children:[(0,n.jsx)(eu.p,{autoFocus:!0,value:j,onChange:e=>I(e.currentTarget.value),placeholder:i("newBranchName"),"aria-label":i("newBranchName"),className:"min-w-[12rem] flex-1"}),(0,n.jsxs)(N.$,{type:"submit",size:"sm",disabled:!j.trim()||F,children:[F?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):null,i("createAndSwitch")]}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>{k(!1),M(null)},children:i("cancel")})]}):(0,n.jsx)(eu.p,{value:p,onChange:e=>h(e.currentTarget.value),placeholder:i("searchBranches"),"aria-label":i("searchBranches")})}),(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto p-2",children:D?.state==="unavailable"?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-destructive",children:(0,eH.fD)(D.message,l)}):O?.status!=="loading"||L?O?.status==="error"?(0,n.jsxs)("div",{className:"flex min-h-24 flex-col items-center justify-center gap-2 text-center text-xs text-destructive",children:[(0,n.jsx)("p",{children:O.error}),null!==P?(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"outline",onClick:()=>void t.loadBranches(e.cwd,P),children:i("retry")}):null]}):L?(0,n.jsxs)("div",{className:"space-y-3",children:[q.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:i("recentlyUsed")}),q.map(e=>Z({type:"local",name:e},"recent"))]}):null,_.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:i("localBranches")}),es(W,"local")]}):null,B.length>0?(0,n.jsxs)("section",{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs font-medium text-muted-foreground",children:i("remoteBranches")}),es(Y,"remote")]}):null,0===q.length&&0===_.length&&0===B.length?(0,n.jsx)("p",{className:"p-5 text-center text-xs text-muted-foreground",children:i("noBranchMatches")}):null]}):null:(0,n.jsxs)("div",{className:"flex min-h-24 items-center justify-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"})," ",i("loadingBranches")]})})]})]})]})})}function uh(e,t){return e instanceof DOMException&&"AbortError"===e.name?t:e instanceof Error?e.message:t}class ug{constructor(e,t){this.biz=e,this.onRepositoryChanged=t,this.listeners=new Set,this.workspaces=new Map,this.projectRefs=new Map,this.revision=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getRevision=()=>this.revision}getWorkspace(e){return e?this.workspaces.get(e)??null:null}reconcileWorkSessions(e,t,s=[]){let n=new Map,r=t?e.find(e=>e.workId===t)??null:null;for(let t of(r&&n.set(r.cwd,{workId:r.workId,cwd:r.cwd}),e))n.has(t.cwd)||n.set(t.cwd,{workId:t.workId,cwd:t.cwd});for(let e of s)n.has(e.cwd)||n.set(e.cwd,{...e,readOnly:!0});if(n.size!==this.projectRefs.size||[...n].some(([e,t])=>this.projectRefs.get(e)?.workId!==t.workId||this.projectRefs.get(e)?.readOnly!==t.readOnly)){for(let[e,t]of(this.projectRefs.clear(),n))this.projectRefs.set(e,t);for(let[e,t]of this.workspaces)n.has(e)||(this.abortRequests(t),this.workspaces.delete(e))}}ensureSnapshot(e){let t=this.workspaceFor(e);return"ready"===t.snapshot.status||"loading"===t.snapshot.status?Promise.resolve():this.loadSnapshot(e,!1)}refreshSnapshot(e){return this.loadSnapshot(e,!0)}async refreshHeads(e){let t=this.workspaceFor(e);if(t.headsRequest||Date.now()-t.lastHeadsStartedAt<3e4)return;let s=this.projectRefs.get(e);if(!s){t.heads={...t.heads,status:"error",error:cV("gitNoProjectStatus")},this.publish();return}let n=new AbortController,r={};t.headsRequest={controller:n,token:r},t.lastHeadsStartedAt=Date.now(),t.heads={...t.heads,status:"loading",error:null},this.publish();try{let a=await this.biz.getHeads({workId:s.workId,cwd:e},n.signal);if(t.headsRequest?.token!==r)return;t.headsRequest=null,t.heads={status:"ready",repositories:a.repositories,error:null},this.publish()}catch(e){if(t.headsRequest?.token!==r||(t.headsRequest=null,n.signal.aborted))return;t.heads={...t.heads,status:"error",error:uh(e,cV("gitStatusReadFailed"))},this.publish()}}setLayout(e,t){let s=this.workspaceFor(e);s.layout!==t&&(s.layout=t,this.publish())}setChangesOnly(e,t){let s=this.workspaceFor(e);s.changesOnly!==t&&(s.changesOnly=t,this.publish())}toggleRepository(e,t){let s=this.workspaceFor(e);s.expandedRepositories.has(t)?s.expandedRepositories.delete(t):s.expandedRepositories.add(t),this.publish()}async loadBranches(e,t){let s=this.workspaceFor(e),n=this.projectRefs.get(e);if(!n){s.branches.set(t,{status:"error",data:null,error:cV("gitNoProjectBranches")}),this.publish();return}s.branchRequests.get(t)?.controller.abort();let r=new AbortController,a={};s.branchRequests.set(t,{controller:r,token:a}),s.branches.set(t,{status:"loading",data:s.branches.get(t)?.data??null,error:null}),this.publish();try{let i=await this.biz.listBranches({workId:n.workId,cwd:e,repositoryRoot:t},r.signal);if(s.branchRequests.get(t)?.token!==a)return;s.branchRequests.delete(t),s.branches.set(t,{status:"ready",data:i,error:null}),this.publish()}catch(e){if(s.branchRequests.get(t)?.token!==a||(s.branchRequests.delete(t),r.signal.aborted))return;s.branches.set(t,{status:"error",data:null,error:uh(e,cV("gitBranchesReadFailed"))}),this.publish()}}async replaceBranch(e,t,s){let n=this.requireWritableProject(e),r=this.workspaceFor(e);if(!r.branchOperations.has(t)){r.branchOperations.add(t),this.publish();try{let a=await this.biz.replaceBranch({...n,repositoryRoot:t,target:s});this.applyRepository(r,a.repository),this.clearBranches(r,t),this.onRepositoryChanged(e,t)}finally{r.branchOperations.delete(t),this.publish()}}}async addBranch(e,t,s,n){let r=this.requireWritableProject(e),a=this.workspaceFor(e);if(!a.branchOperations.has(t)){a.branchOperations.add(t),this.publish();try{let i=await this.biz.addBranch({...r,repositoryRoot:t,name:s,startPoint:n});this.applyRepository(a,i.repository),this.clearBranches(a,t),this.onRepositoryChanged(e,t)}finally{a.branchOperations.delete(t),this.publish()}}}getDiff(e,t,s,n){return this.biz.getDiff({...this.requireProject(e),repositoryRoot:t,path:s},n)}dispose(){for(let e of this.workspaces.values())this.abortRequests(e);this.workspaces.clear(),this.projectRefs.clear(),this.listeners.clear()}async loadSnapshot(e,t){let s=this.workspaceFor(e);if(s.snapshotRequest&&!t)return;let n=this.projectRefs.get(e);if(!n){s.snapshot={status:"error",repositories:s.snapshot.repositories,error:cV("gitNoProjectStatus")},this.publish();return}s.snapshotRequest?.controller.abort();let r=new AbortController,a={};s.snapshotRequest={controller:r,token:a},s.snapshot={status:"loading",repositories:s.snapshot.repositories,error:null},this.publish();try{let t=await this.biz.get({workId:n.workId,cwd:e},r.signal);if(s.snapshotRequest?.token!==a)return;s.snapshotRequest=null,s.snapshot={status:"ready",repositories:t.repositories,error:null};let i=new Set(t.repositories.map(e=>e.root));for(let e of(t.repositories.length>0&&!i.has("")&&i.add(""),[...s.expandedRepositories]))i.has(e)||s.expandedRepositories.delete(e);this.publish()}catch(e){if(s.snapshotRequest?.token!==a||(s.snapshotRequest=null,r.signal.aborted))return;s.snapshot={status:"error",repositories:s.snapshot.repositories,error:uh(e,cV("gitStatusReadFailed"))},this.publish()}}requireProject(e){let t=this.projectRefs.get(e);if(!t)throw Error(cV("gitNoProjectOperation"));return{workId:t.workId,cwd:t.cwd}}requireWritableProject(e){if(this.projectRefs.get(e)?.readOnly)throw Error(cV("gitNoProjectOperation"));return this.requireProject(e)}applyRepository(e,t){e.headsRequest?.controller.abort(),e.headsRequest=null,e.snapshotRequest?.controller.abort(),e.snapshotRequest=null;let s={root:t.root,state:t.state,head:t.head},n=[...e.heads.repositories],r=n.findIndex(e=>e.root===t.root);if(r>=0?n[r]=s:n.push(s),e.heads={status:"ready",repositories:n,error:null},e.lastHeadsStartedAt=Date.now(),"idle"===e.snapshot.status)return;let a="loading"===e.snapshot.status,i=[...e.snapshot.repositories],l=i.findIndex(e=>e.root===t.root);l>=0?i[l]=t:i.push(t),e.snapshot={status:"ready"===e.snapshot.status?"ready":"idle",repositories:i,error:null},a&&this.refreshSnapshot(e.cwd)}abortRequests(e){for(let t of(e.headsRequest?.controller.abort(),e.headsRequest=null,e.snapshotRequest?.controller.abort(),e.snapshotRequest=null,e.branchRequests.values()))t.controller.abort();e.branchRequests.clear()}clearBranches(e,t){e.branchRequests.get(t)?.controller.abort(),e.branchRequests.delete(t),e.branches.delete(t)}workspaceFor(e){let t=this.workspaces.get(e);if(t)return t;let s={cwd:e,heads:{status:"idle",repositories:[],error:null},headsRequest:null,lastHeadsStartedAt:0,snapshot:{status:"idle",repositories:[],error:null},snapshotRequest:null,branches:new Map,branchRequests:new Map,layout:"directory",changesOnly:!1,expandedRepositories:new Set,branchOperations:new Set};return this.workspaces.set(e,s),s}publish(){for(let e of(this.revision+=1,[...this.listeners]))e()}}var ux=s(24985);let uf=ux.y2,ub=a.Ik({workId:cI.eW,cwd:cI.ik}).strict(),uv=ux.Ww,uw=ux.cP,uy=ux.zp,uk=ux.u2;a.Ik({repositories:a.YO(uk).max(uf)}).strict();let uj=ub.extend({repositoryRoot:uv}).strict(),uN=ux.zt,uI=ub.extend({repositoryRoot:uv,target:uN}).strict(),uC=ub.extend({repositoryRoot:uv,name:uw,startPoint:uN.nullable()}).strict(),uS=a.Ik({repository:uy}).strict(),uM=ub.extend({repositoryRoot:uv,path:sH._g}).strict();var uz=s(68269);let uE=Object.freeze({messages:[],temporaryMessages:[],runtime:{extensionMode:"normal",presentationMode:"normal",initializationError:null,queues:{steering:[],followUp:[]},model:null,capabilityMode:null,contextUsage:null,plugins:{}}});function uA(e){let t=new Set;for(let[s,n]of e.entries()){if(n.location.index!==s||t.has(n.location.entryId))return null;t.add(n.location.entryId)}let s=e.at(-1);return s?{index:s.location.index,entryId:s.location.entryId}:null}var u$=s(82639);let uR="messages",uT="source",uP="drafts",uD="outbox",uO="pi-super-chat",uL=null,uF=null;function u_(e){return Error((0,ed.B)({msg:u$.n["zh-CN"].common[e],i18n:{key:`common:${e}`}}))}function uB(e,t){e.objectStoreNames.contains(t)||e.createObjectStore(t,{keyPath:["sessionId","branchId"]})}function uq(){return new Promise((e,t)=>{let s=indexedDB.open(uO,2),n=!1,r=window.setTimeout(()=>{a(u_("dbOpenTimeout"))},1e4),a=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("upgradeneeded",()=>{let e=s.result;e.objectStoreNames.contains(uR)||e.createObjectStore(uR,{keyPath:["sessionId","branchId","index"]}).createIndex(uT,["sessionId","branchId"],{unique:!1}),uB(e,uP),uB(e,uD)},{once:!0}),s.addEventListener("blocked",()=>{a(u_("dbOpenBlocked"))},{once:!0}),s.addEventListener("success",()=>{let t=s.result;n?t.close():(n=!0,window.clearTimeout(r),e(t))},{once:!0}),s.addEventListener("error",()=>a(s.error??u_("dbOpenFailed")),{once:!0})})}async function uW(){try{return await uq()}catch(e){if(!("object"==typeof e&&null!==e&&"name"in e&&"VersionError"===e.name))throw e;return console.warn("[Pi Desk][ChatIndexedDB] 本地数据库版本高于当前版本,清空全部本地聊天数据后重建",{databaseName:uO,requestedVersion:2}),await new Promise((e,t)=>{let s=indexedDB.deleteDatabase(uO),n=!1,r=window.setTimeout(()=>{a(u_("dbDeleteTimeout"))},1e4),a=e=>{n||(n=!0,window.clearTimeout(r),t(e))};s.addEventListener("blocked",()=>{a(u_("dbDeleteBlocked"))},{once:!0}),s.addEventListener("success",()=>{n||(n=!0,window.clearTimeout(r),e())},{once:!0}),s.addEventListener("error",()=>a(s.error??u_("dbDeleteFailed")),{once:!0})}),uq()}}function uY(){return uF?Promise.resolve(uF):uL||(uL=uW().then(e=>(uF=e,e.addEventListener("versionchange",()=>{e.close(),uF===e&&(uF=null,uL=null),console.warn("[Pi Desk][ChatIndexedDB] 数据库版本已变化,当前连接已关闭")}),e)).catch(e=>{throw uL=null,e}))}function uU(e){return new Promise((t,s)=>{e.addEventListener("success",()=>t(e.result),{once:!0}),e.addEventListener("error",()=>s(e.error??u_("dbRequestFailed")),{once:!0})})}function uV(e,t,s){let n=e.target;return n?.error??t.error??Error(s)}function uK(e){return new Promise((t,s)=>{e.addEventListener("complete",()=>t(),{once:!0}),e.addEventListener("abort",t=>s(uV(t,e,u_("dbTransactionAborted").message)),{once:!0}),e.addEventListener("error",t=>s(uV(t,e,u_("dbTransactionFailed").message)),{once:!0})})}let uH=a.Ik({sessionId:a.Yj().trim().min(1),branchId:a.Yj().trim().min(1),index:a.ai().int().nonnegative(),entryId:a.Yj().trim().min(1),fixed:uz.ao,summary:uz.lV,detail:uz.wI.optional()}).strict();function uG(e,t){return uH.parse({sessionId:e.sessionId,branchId:e.branchId,index:t.location.index,entryId:t.location.entryId,fixed:t.fixed,summary:t.summary,...void 0===t.detail?{}:{detail:t.detail}})}function uJ(e){let t=uH.parse(e);if("assistant"===t.fixed.type&&"pi-desk/assistant"===t.fixed.viewKey){if(!Object.hasOwn(t.summary,"errorMessage"))throw Error("Assistant Summary cache uses an outdated projection");uz.Y2.parse(t.summary),void 0!==t.detail&&uz.$f.parse(t.detail)}return uz.wR.parse({location:{index:t.index,entryId:t.entryId},fixed:t.fixed,summary:t.summary,...void 0===t.detail?{}:{detail:t.detail}})}function uQ(e,t){e.delete(IDBKeyRange.bound([t.sessionId,t.branchId,0],[t.sessionId,t.branchId,Number.MAX_SAFE_INTEGER]))}let uX=a.Yj().max(65536),uZ=a.Ik({id:a.Yj().uuid(),title:uX,expiresAt:a.ai().int().nonnegative().nullable()}),u0=a.gM("method",[uZ.extend({method:a.eu("confirm"),message:uX}).strict(),uZ.extend({method:a.eu("select"),options:a.YO(uX).max(200)}).strict(),uZ.extend({method:a.eu("input"),placeholder:uX}).strict(),uZ.extend({method:a.eu("editor"),prefill:uX}).strict()]),u1=a.Ik({requests:a.YO(u0).max(32),statuses:a.g1(a.Yj().max(128),uX),widgets:a.g1(a.Yj().max(128),a.Ik({lines:a.YO(uX).max(200),placement:a.k5(["aboveEditor","belowEditor"])}).strict())}).strict(),u2=a.Ik({id:a.Yj().uuid(),value:a.KC([a.zM(),uX,a.ch()])}).strict(),u5=a.gM("type",[a.Ik({type:a.eu("snapshot"),snapshot:u1}).strict(),a.Ik({type:a.eu("notify"),message:uX,level:a.k5(["info","warning","error"])}).strict(),a.Ik({type:a.eu("editor_text"),text:uX,mode:a.k5(["replace","paste"])}).strict()]),u3=a.Ik({source:lo.R}).strict(),u4=a.Ik({}).strict(),u6=Object.freeze({subscribe:(0,i.Vc)({path:"pi/ui/subscribe",inputSchema:u3,outputSchema:u1}),unsubscribe:(0,i.Vc)({path:"pi/ui/unsubscribe",inputSchema:u3,outputSchema:u4}),respond:(0,i.Vc)({path:"pi/ui/respond",inputSchema:u3.extend({response:u2}).strict(),outputSchema:u4}),event:(0,i._G)({path:"pi/ui/event",bodySchema:u3.extend({event:u5}).strict()})});function u8(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}class u7{constructor(e){this.socket=e,this.records=new Map,this.listeners=new Set,this.notices=new Set,this.releasePush=null,this.connected=!1,this.epoch=0,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e))}onNotice(e){return this.notices.add(e),()=>this.notices.delete(e)}getState(e){return this.record(e).state}watch(e){this.releasePush||(this.releasePush=this.socket.subscribe(u6.event,({source:e,event:t})=>{let s=this.records.get(u8(e));if(s&&this.connected)if("snapshot"===t.type)s.state.refreshing?s.latest=t.snapshot:this.apply(s,t.snapshot);else if("editor_text"===t.type)this.patch(s,{prefill:t});else for(let n of(this.appendNotice(s,t),this.notices))n(e,t)}));let t=this.record(e);!this.connected||t.state.ready||t.state.refreshing||this.refresh(t)}ready(e){for(let t of(this.reconcile(e),this.connected=!0,this.records.values()))this.refresh(t)}reconcile(e){let t=new Set(e.map(u8));for(let[e,s]of this.records)!t.has(e)&&(this.records.delete(e),this.connected&&this.socket.request(u6.unsubscribe,{source:s.source}).catch(()=>void 0));this.emit()}disconnected(){for(let e of(this.connected=!1,this.epoch+=1,this.records.values()))e.latest=null,this.patch(e,{ready:!1,refreshing:!1,submitting:null,commandPending:null,unknown:e.state.submitting??e.state.unknown})}edit(e,t){this.patch(this.record(e),t)}refreshSource(e){return this.refresh(this.record(e))}async respond(e,t){let s=this.record(e);if(!s.state.ready||s.state.submitting||s.state.unknown)return;let n=this.epoch;this.patch(s,{submitting:t.id,error:null});try{await this.socket.request(u6.respond,{source:e,response:t}),this.current(s,n)&&s.state.submitting===t.id&&this.patch(s,{submitting:null})}catch(r){if(!this.current(s,n)||!s.state.snapshot.requests.some(e=>e.id===t.id))return;let e=r instanceof Error&&"code"in r;this.patch(s,{submitting:null,unknown:e?null:t.id,error:e?r.message:cV("nativeUiUnknown")}),this.connected&&await this.refresh(s,e)}}async executeCommand(e,t,s){let n=this.record(e);if(!n.state.ready||n.state.commandPending)return;let r=this.epoch;this.patch(n,{commandPending:`/${t}${s?` ${s}`:""}`});try{await this.socket.request(cq.QV.commandExecute,{source:e,command:t,args:s})}catch(e){this.current(n,r)&&this.appendNotice(n,{level:"error",message:e instanceof Error?e.message:cV("operationFailed")})}finally{this.current(n,r)&&this.patch(n,{commandPending:null})}}dispose(){this.disconnected(),this.releasePush?.(),this.releasePush=null,this.records.clear(),this.listeners.clear(),this.notices.clear()}record(e){let t=u8(e),s=this.records.get(t);return s||(s={source:e,latest:null,state:{snapshot:{requests:[],statuses:{},widgets:{}},notices:[],commandPending:null,ready:!1,refreshing:!1,error:null,submitting:null,unknown:null,answers:{},collapsed:!1,prefill:null}},this.records.set(t,s)),s}current(e,t){return this.epoch===t&&this.records.get(u8(e.source))===e}async refresh(e,t=!1){if(!this.connected||e.state.refreshing)return;let s=this.epoch;e.latest=null,this.patch(e,{ready:!1,refreshing:!0});try{let n=await this.socket.request(u6.subscribe,{source:e.source});if(!this.current(e,s))return;this.apply(e,e.latest??n),this.patch(e,{ready:!0,unknown:null,...!t?{error:null}:{}})}catch(t){this.current(e,s)&&this.patch(e,{ready:!1,error:t instanceof Error?t.message:cV("nativeUiFailed")})}finally{this.current(e,s)&&(e.latest=null,this.patch(e,{refreshing:!1}))}}apply(e,t){let s=new Set(t.requests.map(e=>e.id)),n=Object.fromEntries(Object.entries(e.state.answers).filter(([e])=>s.has(e)));this.patch(e,{snapshot:t,answers:n,submitting:e.state.submitting&&s.has(e.state.submitting)?e.state.submitting:null,unknown:e.state.unknown&&s.has(e.state.unknown)?e.state.unknown:null,...t.requests[0]?.id!==e.state.snapshot.requests[0]?.id?{error:null}:{}})}appendNotice(e,t){let s=[...e.state.notices,{level:t.level,message:t.message.slice(0,65536)}].slice(-32),n=s.reduce((e,t)=>e+t.message.length,0);for(;n>65536&&s.length>1;)n-=s.shift().message.length;this.patch(e,{notices:s})}patch(e,t){e.state={...e.state,...t},this.emit()}emit(){for(let e of this.listeners)e()}}let u9=Object.freeze({...uE,syncStatus:"loading"});function me(e){return uz.Pi.parse({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})}function mt(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function ms(e,t){return e.workId===t.workId&&e.sessionId===t.sessionId&&e.branchId===t.branchId}let mn={text:"",images:[]};function mr(e){return[e.sessionId,e.branchId]}function ma(e,t){return{sessionId:e.sessionId,branchId:e.branchId,text:t.text,images:t.images}}function mi(e){if(!e||"object"!=typeof e||"string"!=typeof e.text||!Array.isArray(e.images))return null;let t=[];for(let s of e.images){if(!s||"object"!=typeof s||!(s.blob instanceof Blob)||"string"!=typeof s.mimeType||!Number.isSafeInteger(s.width)||s.width<=0||!Number.isSafeInteger(s.height)||s.height<=0||"boolean"!=typeof s.optimized)return null;t.push({blob:s.blob,mimeType:s.mimeType,width:s.width,height:s.height,optimized:s.optimized})}return{text:e.text,images:t}}function ml(e,t){return t?{text:[e.text,t.text].filter(e=>e.trim()).join("\n\n"),images:[...e.images,...t.images]}:e}var mo=s(67837);let md=new Set(["image/jpeg","image/png","image/webp","image/gif","image/bmp"]),mc=new Set(["image/jpeg","image/png","image/webp","image/gif"]),mu=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function mm(e){return e.type.toLowerCase().split(";")[0]??""}async function mp(e){let t;try{t=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{throw Error(cV("imageDecodeFailed"))}if(!Number.isSafeInteger(t.width)||t.width<=0||t.height<=0)throw t.close(),Error(cV("imageInvalidDimensions"));return{bitmap:t,width:t.width,height:t.height}}function mh(e,t,s){let n=Math.max(e,t);if(n<=s)return{width:e,height:t};let r=s/n;return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}}function mg(e,t,s,n,r){let a=document.createElement("canvas");a.width=t,a.height=s;let i=a.getContext("2d");if(!i)throw Error(cV("canvasUnavailable"));return i.drawImage(e,0,0,t,s),new Promise((e,t)=>{a.toBlob(s=>s?e(s):t(Error(cV("imageCompressFailed"))),n,r)})}async function mx(e){let t=new Uint8Array(await e.slice(0,262144).arrayBuffer());if(t.length<4||255!==t[0]||216!==t[1])return null;let s=2;for(;s+3<t.length;){for(;s<t.length&&255!==t[s];)s+=1;for(;s<t.length&&255===t[s];)s+=1;if(s>=t.length)break;let e=t[s];if(s+=1,216===e||1===e||e>=208&&e<=215)continue;if(217===e||218===e||s+1>=t.length)break;let n=t[s]<<8|t[s+1];if(n<2||s+n>t.length)break;if(mu.has(e)&&n>=7)return{width:t[s+5]<<8|t[s+6],height:t[s+3]<<8|t[s+4]};s+=n}return null}async function mf(e){let t=mm(e);if(!md.has(t))throw Error(cV("imageTypeUnsupported"));let s=await mp(e);return s.bitmap.close(),{blob:e,mimeType:t,width:s.width,height:s.height,optimized:"image/gif"===t}}async function mb(e){if(e.optimized){if(e.blob.size>0xa00000)throw Error(cV("singleImageLimit"));return e}let t=await mp(e.blob);try{var s;let n=mh(t.width,t.height,2560),r=(s=e.mimeType,"image/jpeg"===s?"image/jpeg":"image/webp"),a=e.blob.size>5242880?.85:"image/jpeg"===r?.9:.92,i=await mg(t.bitmap,n.width,n.height,r,a),l=n.width,o=n.height,d=l!==t.width||o!==t.height,c="image/jpeg"===e.mimeType?await mx(e.blob):null,u="image/jpeg"===e.mimeType&&(null===c||c.width!==t.width||c.height!==t.height),m=mc.has(e.mimeType)&&!u;if(!d&&m&&i.size>=.9*e.blob.size&&(i=e.blob,l=t.width,o=t.height),i.size>0xa00000){let e=mh(t.width,t.height,2048);i=await mg(t.bitmap,e.width,e.height,r,.82),l=e.width,o=e.height}if(i.size>0xa00000)throw Error(cV("compressedImageTooLarge"));let p=mm(i);if(!mc.has(p))throw Error(cV("compressedTypeUnsupported"));return{blob:i,mimeType:p,width:l,height:o,optimized:!0}}finally{t.bitmap.close()}}async function mv(e){if(!e.optimized)throw Error(cV("imagesPending"));let t=new Uint8Array(await e.blob.arrayBuffer()),s="";for(let e=0;e<t.length;e+=32768)s+=String.fromCharCode(...t.subarray(e,e+32768));return{mimeType:e.mimeType,width:e.width,height:e.height,data:btoa(s)}}function mw(e,t,s=e.optimized?"ready":"optimizing"){return{...e,localId:(0,mo.y)(),objectUrl:URL.createObjectURL(e.blob),name:t,status:s,error:null}}function my(e){URL.revokeObjectURL(e.objectUrl)}function mk(e){return JSON.stringify([e.workId,e.sessionId,e.branchId])}function mj(e){return{text:e.text,images:e.images.map(({blob:e,mimeType:t,width:s,height:n,optimized:r})=>({blob:e,mimeType:t,width:s,height:n,optimized:r}))}}function mN(e,t){return e instanceof Error&&e.message?e.message:t}function mI(e,t){return[e,t].filter(e=>e.trim()).join("\n\n")}function mC(e,t,s){return`${mk(e)}\u0000temp\u0000${t}\u0000${s}`}function mS(e,t,s){return`${mk(e)}\u0000entry\u0000${t}\u0000${s}`}function mM(e){for(let t of e)my(t)}var mz=s(63273),mE=s(15104),mA=s(11039),m$=s(97906),mR=s(94411);function mT(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e}function mP(e){return e.trim().toLocaleLowerCase()}let mD=["title","user"],mO=[{value:"title",label:"scopeTitle"},{value:"user",label:"scopeUser"},{value:"assistant",label:"scopeAssistant"},{value:"sessionId",label:"Session ID"}];function mL(e,t,s){return"title"===e?s("scopeTitle"):"sessionId"===e?"Session ID":s("user"===e?"scopeUserMatches":"scopeAssistantMatches",{count:t})}function mF(e){switch(e){case"user":case"assistant":case"title":return"bg-muted text-foreground";case"sessionId":return"bg-muted text-muted-foreground"}}function m_(e){switch(e){case"user":case"assistant":case"title":return"bg-accent text-accent-foreground";case"sessionId":return"bg-muted-foreground/25 text-foreground"}}function mB({scope:e,className:t}){switch(e){case"user":return(0,n.jsx)(mz.A,{className:t});case"assistant":return(0,n.jsx)(eT.A,{className:t});case"title":return(0,n.jsx)(mE.A,{className:t});case"sessionId":return(0,n.jsx)(mA.A,{className:t})}}function mq(e,t,s="bg-primary/20 text-foreground"){if(!t)return e;let r=e.toLocaleLowerCase(),a=[],i=0,l=r.indexOf(t);for(;l>=0;){l>i&&a.push(e.slice(i,l));let o=l+t.length;a.push((0,n.jsx)("mark",{className:`rounded-sm px-px ${s}`,children:e.slice(l,o)},`${l}-${o}`)),i=o,l=r.indexOf(t,i)}return i<e.length&&a.push(e.slice(i)),a.length?a:e}function mW({open:e,pickerMode:t,pickerView:s,pickerCwd:a,directories:i,ignoredDirectories:l,directoryBrowser:o,historySessions:d,replacementTarget:c,unavailableSessionIds:u,error:m,loading:p,creatingCwd:h,replacingSessionId:g,updatingIgnoreCwd:x,onOpenChange:b,onBack:v,onSearchHistory:w,onListSessionUserMessages:y,onRefresh:k,onOpenIgnoredDirectories:j,onOpenDirectoryBrowser:I,onNavigateDirectory:C,onSelectBrowserDirectory:S,onReplaceDirectoryIgnore:M,onSelectDirectory:z,onSelectSession:A}){let{t:$}=(0,f.Bd)("workbenchPicker"),{locale:R,timeZone:T}=(0,eG.i)(),P=(0,r.useMemo)(()=>new Intl.DateTimeFormat("en"===R?"en-US":"zh-CN",{timeZone:T,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),[R,T]),[D,O]=(0,r.useState)(""),[L,F]=(0,r.useState)(mD),[_,B]=(0,r.useState)(""),[q,W]=(0,r.useState)(null),Y=(0,r.useRef)(""),U=(0,r.useRef)(0),V=(0,r.useRef)(null),K=null!==h||null!==g||null!==x,H=(0,r.useMemo)(()=>new Set(u),[u]),G=mP(D),J=function(e){let t=e.trim();if(t.length<2)return t;let s=t.at(0);return('"'===s||"'"===s)&&t.at(-1)===s?t.slice(1,-1).trim():t}(_),Q=/^(?:[A-Za-z]:[\\/]|[\\/]{2}|\/)/.test(J),X="ignored"===s?l:i,Z=X.filter(e=>!G||mP(`${mT(e.cwd)} ${e.cwd}`).includes(G)),ee=(o?.directories??[]).filter(e=>!G||mP(`${e.name} ${e.cwd}`).includes(G));(0,r.useEffect)(()=>{O(""),F(mD),B(""),Y.current=""},[e,t,a,s]);let es=`${G}\u0000${L.join("\0")}`;(0,r.useEffect)(()=>{if("history"!==s||!G||es===Y.current)return;let e=window.setTimeout(()=>{Y.current=es,w(G,L)},300);return()=>window.clearTimeout(e)},[es,w,s,G,L]),(0,r.useEffect)(()=>{U.current+=1,V.current?.abort(),V.current=null,W(null)},[e,a,s,G]),(0,r.useEffect)(()=>()=>{V.current?.abort()},[]);let en=async(e,t,s,n)=>{if(!a)return;let r=++U.current;V.current?.abort();let i=new AbortController;V.current=i,W(s=>({sessionId:e,query:t,messages:n&&s?.sessionId===e?s.messages:[],page:n&&s?.sessionId===e?s.page:null,loading:!0,error:null}));try{let l=await y({cwd:a,sessionId:e,query:t,page:{index:s,size:20}},i.signal);if(U.current!==r)return;W(s=>({sessionId:e,query:t,messages:n&&s?.sessionId===e?[...s.messages,...l.messages]:l.messages,page:l.page,loading:!1,error:null}))}catch(s){if(U.current!==r||s instanceof Error&&"AbortError"===s.name)return;W(n=>({sessionId:e,query:t,messages:n?.sessionId===e?n.messages:[],page:n?.sessionId===e?n.page:null,loading:!1,error:s instanceof Error?s.message:$("loadUserFailed")}))}finally{V.current===i&&(V.current=null)}},er=e=>{if(q?.sessionId===e.sessionId){U.current+=1,V.current?.abort(),V.current=null,W(null);return}let t=e.matches?.some(e=>"user"===e.scope)?G:"";en(e.sessionId,t,1,!1)},ea="ignored"===s?$("ignoredRestoreTitle"):"browser"===s?$("browseOtherTitle"):"replace"===t?$("replaceTitle"):$("createTitle"),ei="ignored"===s?$("ignoredRestoreDescription"):"browser"===s?$("browseDescription"):"replace"===t?c?$("replaceDescription",{project:c.projectName,session:c.sessionTitle??$("newSession")}):$("replaceMissingDescription"):$("createDescription"),el="history"===s?$("searchHistory"):"browser"===s?$("searchBrowser"):"ignored"===s?$("searchIgnored"):$("searchProjects"),eo="history"===s?d.length:"browser"===s?o?.directories.length??0:X.length,ed=p&&("browser"===s?null===o:0===eo),ec="history"===s?$("currentProject",{path:a??""}):"ignored"===s?$("ignoredCount",{count:l.length}):"browser"===s?o?.cwd??$("rootChoose"):"replace"===t?$("replaceChooseFirst"):$("regularExcludesIgnored"),em="history"===s?$("loadingHistory"):"ignored"===s?$("loadingIgnored"):"browser"===s?$("loadingBrowser"):$("loadingProjects"),eh=e=>{O(""),B(""),C(e)},eg=()=>{p||K||!Q||(O(""),C(J))};return(0,n.jsx)(ej.YV,{open:e,onOpenChange:e=>{(e||!K)&&b(e)},children:(0,n.jsxs)(ej.hA,{className:"h-[min(44rem,calc(100dvh-2rem))] max-w-[45rem]",showCloseButton:!K,finalFocus:!1,children:[(0,n.jsx)(ej.Hl,{className:"border-b px-4 py-3 pr-12",children:(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:["directories"!==s?(0,n.jsx)("button",{type:"button",disabled:K,onClick:v,"aria-label":$("backFolders"),title:$("backFolders"),className:(0,N.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(E.A,{className:"size-4"})}):(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:(0,n.jsx)(eR.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)(ej.YM,{children:ea}),(0,n.jsx)(ej.uX,{className:"mt-1 truncate",title:ei,children:ei})]})]})}),(0,n.jsxs)("div",{className:"shrink-0 border-b px-3 py-2.5 sm:px-4",children:["browser"===s?(0,n.jsxs)("div",{className:"mb-2",children:[(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,n.jsx)(ud.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(eu.p,{value:_,onChange:e=>B(e.target.value),onKeyDown:e=>{"Enter"===e.key&&Q&&(e.preventDefault(),eg())},placeholder:$("pastePath"),"aria-label":$("fullPath"),disabled:p||K,className:"pl-9"})]}),(0,n.jsx)("button",{"data-testid":"workbench-picker-open-directory-path",type:"button",disabled:p||K||!Q,onClick:eg,title:Q?$("openTyped"):$("enterAbsolute"),className:(0,N.r)({variant:"outline"}),children:$("open")})]}),(0,n.jsx)("p",{className:"mt-1.5 px-0.5 text-sm text-muted-foreground",children:_.trim()&&!Q?$("absoluteExample"):$("pasteHint")})]}):null,(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(ep.A,{className:"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(eu.p,{value:D,onChange:e=>O(e.target.value),placeholder:el,"aria-label":el,disabled:K,className:"pl-9"})]}),"history"===s?(0,n.jsxs)("fieldset",{className:"mt-2 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1.5 px-0.5",children:[(0,n.jsx)("legend",{className:"mr-1 text-xs text-muted-foreground",children:$("searchScopes")}),mO.map(e=>{let t=L.includes(e.value);return(0,n.jsxs)("label",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-sm text-muted-foreground has-[:focus-visible]:rounded-sm has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring",children:[(0,n.jsx)("input",{type:"checkbox",checked:t,disabled:K||t&&1===L.length,onChange:()=>{var t;return t=e.value,void F(e=>e.includes(t)?1===e.length?e:e.filter(e=>e!==t):[...e,t])},className:"size-4 accent-primary"}),(0,n.jsx)("span",{children:$(e.label)})]},e.value)})]}):null]}),(0,n.jsx)(ej._Y,{className:"max-h-none min-h-0",children:(0,n.jsxs)("div",{className:"p-2 sm:p-3","aria-busy":p||K,"aria-live":"polite",children:[m?(0,n.jsx)("p",{role:"alert",className:"mb-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:m}):null,"replace"===t&&null===c?(0,n.jsx)("p",{role:"alert",className:"mb-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:$("replaceTargetMissing")}):null,ed?(0,n.jsxs)("div",{className:"flex min-h-36 flex-col items-center justify-center gap-3 text-center text-sm text-muted-foreground",children:[(0,n.jsx)(et.A,{className:"size-5 animate-spin"}),(0,n.jsx)("p",{children:em})]}):"history"===s?0===d.length?null===m?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:G?$("noHistoryMatches"):$("noReplaceHistory")}):null:(0,n.jsxs)(n.Fragment,{children:[G?(0,n.jsx)("p",{className:"px-3 pb-1 pt-0.5 text-xs text-muted-foreground",children:$("sessionFound",{count:d.length})}):null,(0,n.jsx)("div",{className:"divide-y",children:d.map(e=>{let t,s=e.name?.trim()||e.firstMessage.trim()||$("sessionFallback",{id:e.sessionId.slice(0,8)}),r=$("sessionMessages",{users:e.userMessageCount,total:e.messageCount,time:(t=e.updatedAt,P.format(t))}),a=c?.sessionId===e.sessionId,i=H.has(e.sessionId),l=g===e.sessionId,o=null===c,d=K||a||i||o,u=q?.sessionId===e.sessionId?q:null,m=e.matches??[],p=m.filter(e=>"title"!==e.scope),h=m.find(e=>"user"===e.scope),x=null===u&&p.length>0,f=`workbench-picker-user-message-panel-${e.sessionId}`,b=l?$("replacing"):a?$("current"):i?$("alreadyUsed"):o?$("targetUnavailable"):$("replace"),v=a?$("currentBound"):i?$("historyUsed"):o?$("replaceTargetUnavailable"):$("replaceWith",{name:s}),w=u?$("hideUserMessages"):h?$("viewMatching",{count:h.count}):$("viewUserMessages",{count:e.userMessageCount}),y=u?.page!==null&&null!==u&&u.messages.length<u.page.total;return(0,n.jsxs)("div",{className:"px-2 sm:px-3",children:[(0,n.jsxs)("div",{className:"flex min-h-15 items-center gap-2 py-2",children:[(0,n.jsx)(m$.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",title:s,children:m.some(e=>"title"===e.scope)?mq(s,G,m_("title")):s}),(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",title:r,children:r})]}),e.userMessageCount>0?(0,n.jsx)("button",{"data-testid":`workbench-picker-user-messages-${e.sessionId}`,type:"button",disabled:K,"aria-label":w,"aria-expanded":null!==u,"aria-controls":f,onClick:()=>er(e),title:w,className:(0,N.r)({variant:"ghost",size:"icon"}),children:(0,n.jsx)(eq.A,{className:`size-4 transition-transform${u?" rotate-180":""}`})}):null,(0,n.jsx)("button",{"data-testid":`workbench-picker-replace-${e.sessionId}`,type:"button",disabled:d,onClick:()=>A(e.sessionId),title:v,className:(0,N.r)({variant:"outline"}),children:l?(0,n.jsx)(et.A,{className:"size-3.5 animate-spin"}):b})]}),x?(0,n.jsx)("div",{className:"mb-2 ml-6 min-w-0 space-y-1.5 overflow-hidden",children:p.map(t=>{let s,r="user"===t.scope,a=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(mB,{scope:t.scope,className:"mt-0.5 size-3.5 shrink-0"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs leading-5",children:[(0,n.jsx)("span",{className:`shrink-0 rounded px-1.5 py-0.5 font-medium ${mF(t.scope)}`,children:mL(t.scope,t.count,$)}),null!==t.timestampMs?(0,n.jsx)("span",{className:"truncate text-muted-foreground",children:(s=t.timestampMs,P.format(s))}):null]}),(0,n.jsx)("p",{className:"mt-1 line-clamp-2 break-words text-sm leading-5 text-foreground",children:mq(t.preview,G,m_(t.scope))})]})]}),i=`flex w-full max-w-full min-w-0 items-start gap-2 overflow-hidden rounded-md px-2.5 py-2 text-left ${mF(t.scope)}`;return r?(0,n.jsx)("button",{"data-testid":`workbench-picker-user-message-preview-${e.sessionId}`,type:"button",disabled:K,onClick:()=>er(e),"aria-label":$("viewMatch",{label:mL(t.scope,t.count,$)}),className:`${i} outline-none transition-colors hover:brightness-95 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50`,children:a},t.scope):(0,n.jsx)("div",{className:i,children:a},t.scope)})}):null,u?(0,n.jsxs)("div",{id:f,"data-testid":f,className:"mb-2 ml-6 rounded-md border bg-background px-3 py-2.5",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[(0,n.jsxs)("p",{className:"flex min-w-0 items-center gap-1.5 text-xs font-medium",children:[(0,n.jsx)(mR.A,{className:"size-3.5 shrink-0 text-primary"}),(0,n.jsx)("span",{className:"truncate",children:u.query?$("matchingUserCount",{count:u.page?.total??0}):$("userCount",{count:u.page?.total??e.userMessageCount})})]}),u.query?(0,n.jsx)("button",{type:"button",disabled:u.loading||K,onClick:()=>void en(e.sessionId,"",1,!1),className:(0,N.r)({variant:"ghost",size:"sm"}),children:$("viewAll")}):null]}),u.error?(0,n.jsx)("p",{className:"mt-2 text-xs text-destructive",children:u.error}):null,u.loading&&0===u.messages.length?(0,n.jsx)("div",{className:"flex min-h-16 items-center justify-center text-muted-foreground",children:(0,n.jsx)(et.A,{className:"size-4 animate-spin"})}):0===u.messages.length?(0,n.jsx)("p",{className:"py-4 text-center text-xs text-muted-foreground",children:$("noUserMessages")}):(0,n.jsx)("div",{className:"mt-2 divide-y",children:u.messages.map(e=>{let t;return(0,n.jsxs)("div",{className:"py-2 first:pt-0 last:pb-0",children:[(0,n.jsx)("p",{className:"text-xs tabular-nums text-muted-foreground",children:(t=e.timestampMs,P.format(t))}),(0,n.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-sm leading-6",children:e.text?mq(e.text,u.query):$("noText")})]},e.entryId)})}),y?(0,n.jsxs)("button",{type:"button",disabled:u.loading||K,onClick:()=>void en(e.sessionId,u.query,(u.page?.index??0)+1,!0),className:(0,N.r)({variant:"outline",className:"mt-2"}),children:[u.loading?(0,n.jsx)(et.A,{className:"size-3.5 animate-spin"}):null,$("loadMore")]}):null]}):null]},e.sessionId)})})]}):"browser"===s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"mb-2 flex min-h-10 items-center gap-2 rounded-md bg-muted/60 px-3 text-xs text-muted-foreground",children:[(0,n.jsx)(ud.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"truncate",title:o?.cwd??$("root"),children:o?.cwd??$("root")})]}),0===ee.length?null===m?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:(o?.directories.length??0)===0?o?.cwd?$("browserEmpty"):$("rootsEmpty"):$("subfoldersNoMatches")}):null:(0,n.jsx)("div",{className:"divide-y",children:ee.map(e=>(0,n.jsxs)("button",{type:"button",disabled:p||K,onClick:()=>eh(e.cwd),className:"group flex min-h-15 w-full items-center gap-3 rounded-md px-2 py-2 text-left outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55 sm:px-3",children:[(0,n.jsx)(eR.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-primary"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",title:e.name,children:e.name}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),(0,n.jsx)(e8.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-foreground"})]},e.cwd))})]}):0===Z.length?null===m?(0,n.jsx)("p",{className:"px-3 py-10 text-center text-sm text-muted-foreground",children:0===X.length?"ignored"===s?$("ignoredEmpty"):$("projectsEmpty"):$("projectNoMatches")}):null:"ignored"===s?(0,n.jsx)("div",{className:"divide-y",children:Z.map(e=>{let t=mT(e.cwd),s=x===e.cwd;return(0,n.jsxs)("div",{className:"flex min-h-15 items-center gap-3 px-2 py-2 sm:px-3",children:[(0,n.jsx)(eR.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",title:t,children:t}),(0,n.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),(0,n.jsxs)("button",{"data-testid":`workbench-picker-restore-directory-${e.cwd}`,type:"button",disabled:K,onClick:()=>M(e.cwd,!1),"aria-label":$("restoreFolder",{name:t}),title:$("restoreTip"),className:(0,N.r)({variant:"outline"}),children:[s?(0,n.jsx)(et.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(lP.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:$("restore")})]})]},e.cwd)})}):(0,n.jsx)("div",{className:"divide-y",children:Z.map(e=>{let s,r=mT(e.cwd),a=$("directorySessions",{count:e.sessionCount,time:(s=e.updatedAt,P.format(s))}),i=h===e.cwd,l=x===e.cwd;return(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.jsxs)("button",{"data-testid":`workbench-picker-directory-${e.cwd}`,type:"button",disabled:K,onClick:()=>z(e.cwd),className:"group flex min-h-15 min-w-0 flex-1 items-center gap-3 rounded-md px-2 py-2 text-left outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55 sm:px-3",children:[(0,n.jsx)(eR.A,{className:"size-4 shrink-0 text-muted-foreground group-hover:text-primary"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium",title:r,children:r}),(0,n.jsx)("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",title:e.cwd,children:e.cwd})]}),i?(0,n.jsxs)("span",{className:"flex min-h-10 shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(et.A,{className:"size-3.5 animate-spin"}),$("creating")]}):(0,n.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs text-muted-foreground",title:a,children:[(0,n.jsx)("span",{children:$("directoryCount",{count:e.sessionCount})}),(0,n.jsx)(e8.A,{className:"size-4 group-hover:text-foreground"})]})]}),"create"===t?(0,n.jsx)("button",{"data-testid":`workbench-picker-ignore-directory-${e.cwd}`,type:"button",disabled:K,onClick:()=>M(e.cwd,!0),"aria-label":$("ignoreFolder",{name:r}),title:$("ignoreTip"),className:(0,N.r)({variant:"ghost",size:"icon"}),children:l?(0,n.jsx)(et.A,{className:"size-3.5 animate-spin"}):(0,n.jsx)(is.A,{className:"size-4"})}):null]},e.cwd)})})]})}),(0,n.jsxs)(ej.vu,{className:"flex-row flex-wrap items-center justify-between gap-2 px-3 py-2.5 sm:px-4",children:[(0,n.jsx)("p",{className:"min-w-24 flex-1 truncate text-xs text-muted-foreground",title:ec,children:ec}),(0,n.jsxs)("div",{className:"ml-auto flex items-center gap-2",children:["create"===t&&"directories"===s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",disabled:p||K,onClick:j,className:(0,N.r)({variant:"outline"}),children:$("ignoredFolders")}),(0,n.jsx)("button",{type:"button",disabled:p||K,onClick:I,className:(0,N.r)({variant:"outline"}),children:$("chooseOther")})]}):null,"browser"===s&&o?.cwd?(0,n.jsx)("button",{"data-testid":"workbench-picker-select-browser-directory",type:"button",disabled:p||K,onClick:()=>S(o.cwd),className:(0,N.r)(),children:$("selectCurrent")}):null,"browser"===s&&o?.parentCwd?(0,n.jsx)("button",{type:"button",disabled:p||K,onClick:()=>eh(o.parentCwd),"aria-label":$("parentDirectory"),title:$("parentDirectory"),className:(0,N.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(E.A,{className:"size-4"})}):null,"browser"===s&&o?.cwd?(0,n.jsx)("button",{type:"button",disabled:p||K,onClick:()=>eh(null),"aria-label":$("backRoots"),title:$("backRoots"),className:(0,N.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(ud.A,{className:"size-4"})}):null,(0,n.jsx)("button",{"data-testid":"workbench-picker-refresh",type:"button",disabled:p||K,onClick:()=>k(G,L),"aria-label":$("refreshList"),title:$("refreshList"),className:(0,N.r)({variant:"outline",size:"icon"}),children:(0,n.jsx)(et.A,{className:`size-4${p?" animate-spin":""}`})})]})]})]})})}let mY="pi-super:workbench-layout";function mU(e,t,s=[]){let n=new Set(t.map(e=>e.workId)),r=new Set(s),a=e.primaryWorkId&&n.has(e.primaryWorkId)&&!r.has(e.primaryWorkId)?e.primaryWorkId:null;return e.primaryWorkId===a?e:{primaryWorkId:a}}function mV({variant:e,className:t,children:s}){let{t:r}=(0,f.Bd)("workbench");return(0,n.jsx)("div",{className:(0,C.cn)("@container/empty-state flex size-full min-h-0 flex-1 items-center justify-center overflow-hidden px-6 py-8 text-center",t),children:"select-session"===e?(0,n.jsxs)("div",{className:"relative",children:[s,(0,n.jsx)("h1",{className:"text-base font-medium text-muted-foreground",children:r("emptySelectSession")})]}):(0,n.jsxs)("div",{role:"status","aria-live":"polite",className:"flex flex-col items-center gap-3 animate-in fade-in-0 fill-mode-both delay-150 duration-150 motion-reduce:animate-none",children:[(0,n.jsx)(b.A,{className:"size-5 animate-spin text-muted-foreground motion-reduce:animate-none"}),(0,n.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:r("emptyLoading")})]})})}var mK=s(39569),mH=s(31175),mG=s(74873),mJ=s(77065),mQ=s(36919);let mX=new Set(["custom","model_change","thinking_level_change","session_info","label"]),mZ=[],m0=[{value:"default",label:"filterDefault"},{value:"no-tools",label:"filterNoTools"},{value:"user-only",label:"filterUserOnly"},{value:"labeled-only",label:"filterLabeled"},{value:"all",label:"filterAll"}],m1={user:{label:"kindUser",labelClassName:"font-semibold text-primary",contentClassName:"font-medium text-foreground",rowClassName:""},assistant:{label:"AI",labelClassName:"font-medium text-muted-foreground",contentClassName:"text-foreground",rowClassName:""},tool:{label:"kindTool",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:"text-muted-foreground"},bash:{label:"Bash",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:"text-muted-foreground"},custom_message:{label:"kindMessage",labelClassName:"text-muted-foreground",contentClassName:"text-foreground",rowClassName:""},compaction:{label:"kindCompaction",labelClassName:"font-medium text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:"bg-primary/[0.025]"},branch_summary:{label:"kindBranchSummary",labelClassName:"font-medium text-foreground",contentClassName:"text-muted-foreground",rowClassName:"bg-amber-500/[0.025]"},custom:{label:"kindCustom",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""},model_change:{label:"kindModel",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""},thinking_level_change:{label:"kindThinking",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""},session_info:{label:"kindSession",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""},label:{label:"kindLabel",labelClassName:"text-muted-foreground",contentClassName:"text-muted-foreground",rowClassName:""}};function m2(e){switch(e.action){case"tree":return"treeIntent";case"fork":return"forkIntent";case"clone":return"cloneIntent"}}function m5(e){e.preventDefault()}function m3({confirmation:e,disabled:t,onConfirm:s,onBack:a}){let{t:i}=(0,f.Bd)("workbenchPicker"),[l,o]=(0,r.useState)(0),d=(0,r.useRef)(new Map);(0,r.useEffect)(()=>{d.current.get(0)?.focus()},[]);let c=n=>{e.waiting||t&&0===n||(0===n?s():a())};return(0,n.jsxs)("div",{className:"p-3 sm:p-4",onKeyDown:e=>{if(e.stopPropagation(),"Escape"===e.key){e.preventDefault(),a();return}if("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault();let t=+(0===l);o(t),queueMicrotask(()=>d.current.get(t)?.focus());return}"Enter"===e.key&&(e.preventDefault(),c(l))},children:[(0,n.jsxs)("div",{className:"rounded-lg border bg-muted/25 px-3 py-2.5",children:[(0,n.jsx)("p",{className:"text-sm font-semibold",children:i("runningTitle")}),(0,n.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:"main"===e.reason?i("runningStop",{action:i(m2(e.intent))}):i("runningWait",{action:i(m2(e.intent))})})]}),(0,n.jsx)("div",{className:"mt-3 grid grid-cols-2 gap-2",children:[{label:i(e.waiting?"confirming":"confirmContinue"),confirm:!0},{label:i("back"),confirm:!1}].map((s,r)=>(0,n.jsxs)("button",{ref:e=>{e?d.current.set(r,e):d.current.delete(r)},type:"button",disabled:e.waiting||t&&s.confirm,tabIndex:l===r?0:-1,className:(0,C.cn)("flex min-h-11 items-center justify-center gap-2 rounded-lg border px-3 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-60",l===r?"border-primary/40 bg-primary/10 text-foreground":"border-border bg-background hover:bg-muted/60"),onFocus:()=>o(r),onClick:()=>c(r),children:[e.waiting&&s.confirm?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):null,s.label]},s.label))}),(0,n.jsx)("p",{className:"mt-2 text-center text-xs text-muted-foreground",children:i("confirmHint")})]})}function m4({model:e,projectName:t,sessionTitle:s,mobile:a,onClose:i,onRetry:l,onSelectEntry:o,onAction:d,onConfirmRunning:c,onCancelRunning:u}){let{t:m}=(0,f.Bd)("workbenchPicker"),p=(0,mJ.tF)(),h=(0,mQ.I)(),{locale:g,timeZone:x}=(0,eG.i)(),v=(0,r.useMemo)(()=>new Intl.DateTimeFormat("en"===g?"en-US":"zh-CN",{timeZone:x,timeZoneName:"shortOffset",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),[g,x]),[w,y]=(0,r.useState)(""),[k,j]=(0,r.useState)("default"),[I,S]=(0,r.useState)(!1),[M,z]=(0,r.useState)(()=>new Set),[E,A]=(0,r.useState)(null),[$,R]=(0,r.useState)(0),[T,P]=(0,r.useState)(480),D=(0,r.useRef)(null),O=(0,r.useRef)(null),L=(0,r.useRef)(null),F=(0,r.useRef)(null),_=(0,r.useRef)(!1),B=e.tree?.nodes??mZ,q=(0,r.useMemo)(()=>(function(e){let t=new Map;e.nodes.forEach((e,s)=>t.set(e.entryId,{node:e,index:s}));let s=function(e,t){let s=new Set,n=t;for(;n&&!s.has(n);){let t=e.get(n);if(!t)break;s.add(n),n=t.node.parentEntryId}return s}(t,e.leafEntryId),n=new Set(e.nodes.filter(t=>(function(e,t,s){if("assistant"===e.kind&&!e.preview&&e.entryId!==s)return!1;switch(t){case"default":return!mX.has(e.kind);case"no-tools":return!mX.has(e.kind)&&"tool"!==e.kind;case"user-only":return"user"===e.kind;case"labeled-only":return null!==e.label;case"all":return!0}})(t,e.filter,e.leafEntryId)&&function(e,t){let s=t.toLocaleLowerCase().split(/\s+/).filter(Boolean);if(0===s.length)return!0;let n=[e.kind,e.preview,e.label??""].join(" ").toLocaleLowerCase();return s.every(e=>n.includes(e))}(t,e.query)).map(e=>e.entryId)),r=new Map,a=new Map;for(let e of t.values()){if(!n.has(e.node.entryId))continue;let s=e.node.parentEntryId,i=new Set;for(;s&&!n.has(s);){if(i.has(s)){s=null;break}i.add(s),s=t.get(s)?.node.parentEntryId??null}s===e.node.entryId&&(s=null),a.set(e.node.entryId,s);let l=r.get(s)??[];l.push(e),r.set(s,l)}for(let e of r.values())e.sort((e,t)=>(function(e,t,s){let n=Number(!s.has(e.node.entryId))-Number(!s.has(t.node.entryId));if(0!==n)return n;let r=e.node.timestampMs-t.node.timestampMs;return 0!==r?r:e.index-t.index})(e,t,s));let i=[],l=new Set;return(t=>{let n=[...t].reverse().map(e=>({indexed:e,depth:0,connector:!1,lastSibling:!0}));for(;n.length>0;){let t=n.pop(),o=t.indexed.node.entryId;if(l.has(o))continue;l.add(o);let d=r.get(o)??[],c=a.get(o)??null,u=null===c?[]:r.get(c)??[],m=d.length>0&&(null===c||u.length>1),p=!m||!e.foldedEntryIds.has(o);if(i.push({node:t.indexed.node,depth:t.depth,active:s.has(o),current:o===e.leafEntryId,hasChildren:d.length>0,foldable:m,expanded:p,connector:t.connector,lastSibling:t.lastSibling,visibleParentEntryId:a.get(o)??null}),!p)continue;let h=d.length>1;for(let[e,s]of[...d].reverse().entries()){let r=d.length-e-1;n.push({indexed:s,depth:t.depth+ +!!h,connector:h,lastSibling:r===d.length-1})}}})(r.get(null)??[]),i})({nodes:B,leafEntryId:e.tree?.leafEntryId??null,filter:k,query:w,foldedEntryIds:M}),[k,M,e.tree?.leafEntryId,B,w]),W=function(e,t,s){if(0===t.length)return null;let n=new Set(t.map(e=>e.node.entryId)),r=new Map(e.map(e=>[e.entryId,e])),a=s,i=new Set;for(;a&&!i.has(a);){if(n.has(a))return a;i.add(a),a=r.get(a)?.parentEntryId??null}return t.at(-1)?.node.entryId??null}(B,q,E??e.tree?.leafEntryId??null),U=q.findIndex(e=>e.node.entryId===W),V=U>=0?q[U]:null,H=Math.max(0,Math.floor($/36)-8),G=Math.min(q.length,Math.ceil(($+T)/36)+8),J=Math.min(q.length,Math.max(G,H+8)),Q=q.slice(H,J),X=e.detail?.entryId===W?e.detail:null,Z=m(m0.find(e=>e.value===k)?.label??"filterDefault"),ee=e.runningConfirmation,et=`work-session-branch-tree-${e.workId}`,es=W?`${et}-entry-${W}`:void 0,en=(0,r.useCallback)(()=>{a?O.current?.focus({preventScroll:!0}):D.current?.focus({preventScroll:!0})},[a]),er=(0,r.useCallback)(t=>{e.pending||(_.current=t,i())},[e.pending,i]);(0,r.useEffect)(()=>{if(p)return F.current=document.activeElement instanceof HTMLElement?document.activeElement:null,_.current=!1,queueMicrotask(en),()=>{_.current&&F.current?.focus({preventScroll:!0})}},[en,p]),(0,r.useEffect)(()=>{p&&!ee&&queueMicrotask(en)},[ee,en,p]),(0,r.useEffect)(()=>{if(!p)return;let t=t=>{if(e.pending)return;let s=t.target;!(s instanceof Node)||O.current?.contains(s)||s instanceof Element&&s.closest('[data-workbench-branch-picker-popup="true"]')||er(!1)};return document.addEventListener("pointerdown",t,!0),()=>document.removeEventListener("pointerdown",t,!0)},[e.pending,p,er]),(0,r.useEffect)(()=>{let e=L.current;if(!e)return;let t=new ResizeObserver(([e])=>{P(e?.contentRect.height??0)});return t.observe(e),()=>t.disconnect()},[ee]),(0,r.useEffect)(()=>{if(!p||!W||ee)return;o(W);let e=L.current;if(!e||U<0)return;let t=36*U,s=t+36,n=e.scrollTop;t<e.scrollTop?n=t:s>e.scrollTop+e.clientHeight&&(n=s-e.clientHeight),n!==e.scrollTop&&(e.scrollTop=n),queueMicrotask(()=>R(n))},[ee,W,o,p,36,U]);let ea=(0,r.useCallback)(e=>{L.current&&(L.current.scrollTop=e),R(e)},[]),ei=(0,r.useCallback)(e=>{if(0===q.length)return;let t=Math.max(0,Math.min(q.length-1,e));A(q[t].node.entryId);let s=L.current;if(!s)return;let n=36*t,r=n+36,a=s.scrollTop;n<s.scrollTop?a=n:r>s.scrollTop+s.clientHeight&&(a=r-s.clientHeight),ea(a)},[36,q,ea]),el=(0,r.useCallback)((e,t)=>{z(s=>{let n=new Set(s);return t??!n.has(e)?n.add(e):n.delete(e),n})},[]),eo=(0,r.useCallback)(e=>{j(e),z(new Set),ea(0),queueMicrotask(en)},[en,ea]),ed=(0,r.useCallback)(e=>{let t=(m0.findIndex(e=>e.value===k)+e+m0.length)%m0.length;eo(m0[t].value)},[eo,k]),ec=(0,r.useCallback)((t,s)=>{e.actionsDisabled||(_.current=!1,d(t,s))},[e.actionsDisabled,d]),em=(0,r.useCallback)(()=>{!V||V.current||e.pending||ec(V.node.entryId,"tree")},[e.pending,ec,V]),eh=(0,r.useCallback)(()=>{if(!V?.visibleParentEntryId)return;let e=q.findIndex(e=>e.node.entryId===V.visibleParentEntryId);e>=0&&ei(e)},[q,ei,V]),eg=(0,r.useCallback)(()=>{if(!V)return;let e=q.findIndex(e=>e.visibleParentEntryId===V.node.entryId);e>=0&&ei(e)},[q,ei,V]),ex=(0,r.useCallback)(()=>{ee?u():w?(y(""),z(new Set),ea(0)):er(!0)},[ee,u,w,er,ea]);(0,r.useEffect)(()=>{if(!a||!p)return;let e=e=>{"Escape"!==e.key||e.defaultPrevented||e.isComposing||e.repeat||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||O.current?.closest("[inert]")||(e.preventDefault(),e.stopImmediatePropagation(),ex())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ex,a,p]);let ef=V?.node??null,eb=ef?m1[ef.kind]:null,ev=ee?a?"inset-x-0 bottom-0 rounded-t-2xl border-x-0 border-b-0":"inset-x-2 bottom-2 h-auto max-h-[calc(100%-4rem)] rounded-xl":a?"inset-x-0 bottom-0 top-14 rounded-t-2xl border-x-0 border-b-0":"inset-x-2 bottom-2 h-[min(82%,48rem)] rounded-xl";return(0,n.jsxs)(o8.PY1.div,{className:"pointer-events-none absolute inset-0 z-30","aria-hidden":!p||void 0,inert:!p||void 0,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15*!h,ease:"easeOut"},children:[(0,n.jsx)("div",{"aria-hidden":"true","data-carousel-swipe-lock":!0,className:(0,C.cn)("absolute inset-x-0 bottom-0 top-14 z-30 bg-background/65",p?"pointer-events-auto":"pointer-events-none")}),(0,n.jsxs)(o8.PY1.section,{ref:O,initial:{y:12*!h},animate:{y:0},exit:{y:8*!h},transition:{duration:.2*!h,ease:"easeOut"},tabIndex:-1,"data-carousel-swipe-lock":!0,role:"region","aria-label":m("branchPicker"),"aria-busy":e.pending||e.loading,className:(0,C.cn)("absolute z-40 flex min-h-0 flex-col overflow-hidden border bg-popover text-popover-foreground shadow-lg outline-none",p?"pointer-events-auto":"pointer-events-none",ev),children:[(0,n.jsxs)("header",{className:"shrink-0 border-b bg-muted/10",children:[(0,n.jsxs)("div",{className:"flex min-h-10 items-center gap-2 px-2.5",children:[(0,n.jsx)("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold",title:`${t} \xb7 ${s??m("newSession")}`,children:m("branchTitle")}),ee?null:(0,n.jsxs)("span",{className:"shrink-0 text-xs text-muted-foreground",children:[U>=0?U+1:0," / ",q.length]}),(0,n.jsx)("button",{type:"button",disabled:e.pending,"aria-label":m("closeBranchPicker"),className:(0,N.r)({variant:"ghost",size:"icon"}),onClick:()=>er(!0),children:(0,n.jsx)(Y.A,{className:"size-4"})})]}),ee?null:(0,n.jsxs)("div",{className:"flex items-center gap-1.5 border-t border-border/60 px-2 py-1.5",children:[(0,n.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,n.jsx)(ep.A,{className:"pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(eu.p,{ref:D,role:"combobox",value:w,"aria-label":m("branchSearch"),"aria-controls":et,"aria-expanded":"true","aria-activedescendant":es,placeholder:m("branchSearchPlaceholder"),className:"pl-7",onChange:e=>{y(e.currentTarget.value),z(new Set),ea(0)},onKeyDown:e=>{if(!e.nativeEvent.isComposing)switch(e.stopPropagation(),e.key){case"Tab":e.preventDefault(),ed(e.shiftKey?-1:1);return;case"ArrowUp":e.preventDefault(),ei(U-1);return;case"ArrowDown":e.preventDefault(),ei(U+1);return;case"PageUp":e.preventDefault(),ei(U-Math.max(1,Math.floor(T/36)));return;case"PageDown":e.preventDefault(),ei(U+Math.max(1,Math.floor(T/36)));return;case"ArrowLeft":if(w||!V)return;e.preventDefault(),V.foldable&&V.expanded?el(V.node.entryId,!0):eh();return;case"ArrowRight":if(w||!V)return;e.preventDefault(),V.foldable&&!V.expanded?el(V.node.entryId,!1):eg();return;case"Enter":e.preventDefault(),em();return;case"Escape":e.preventDefault(),ex();return}}})]}),(0,n.jsxs)(K.rI,{open:I,onOpenChange:S,onOpenChangeComplete:e=>{e||queueMicrotask(en)},children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)("button",{type:"button","aria-label":m("branchFilter",{filter:Z}),className:(0,N.r)({variant:"outline"})}),children:[Z,(0,n.jsx)(eq.A,{className:"size-3.5"})]}),(0,n.jsx)(K.SQ,{"data-workbench-branch-picker-popup":"true",align:"end",side:"bottom",className:"w-32",finalFocus:()=>a?O.current:D.current,children:m0.map(e=>(0,n.jsxs)(K._2,{onClick:()=>eo(e.value),children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:m(e.label)}),k===e.value?(0,n.jsx)("span",{className:"text-xs text-primary",children:"●"}):null]},e.value))})]})]})]}),e.error?(0,n.jsx)("div",{role:"alert",className:"shrink-0 border-b bg-muted px-3 py-2 text-sm text-destructive",children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:e.error}),e.pending||e.tree?null:(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"outline",disabled:e.actionsDisabled,onClick:l,children:m("retry")})]})}):null,ee?(0,n.jsx)(m3,{confirmation:ee,disabled:e.actionsDisabled,onConfirm:c,onBack:()=>{_.current=!0,u()}},`${ee.intent.action}:${"entryId"in ee.intent?ee.intent.entryId:""}`):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"pi-desk-chat-scrollbar h-36 shrink-0 overflow-y-auto border-b bg-muted px-3 py-3",children:ef&&eb?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:eb.labelClassName,children:m(eb.label)}),ef.label?(0,n.jsx)("span",{className:"min-w-0 truncate rounded-sm bg-amber-500/10 px-1 text-amber-700 dark:text-amber-300",children:ef.label}):null,(0,n.jsx)("time",{className:"ml-auto shrink-0",children:v.format(ef.timestampMs)})]}),(0,n.jsx)("div",{className:"mt-2 whitespace-pre-wrap break-words text-sm leading-6",children:e.detailLoading||!X?e.detailError?(0,n.jsx)("span",{className:"text-destructive",children:e.detailError}):(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}),m("loadingEntry")]}):(0,n.jsxs)(n.Fragment,{children:[X.content||m("entryEmpty"),X.truncated?(0,n.jsx)("span",{className:"mt-1 block text-muted-foreground",children:m("entryTruncated")}):null]})})]}):(0,n.jsx)("div",{className:"grid min-h-12 place-items-center text-xs text-muted-foreground",children:m("selectEntry")})}),e.pending&&!e.runningConfirmation?(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b bg-primary/8 px-2.5 py-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(b.A,{className:"size-3.5 animate-spin text-primary"}),m("branchWorking")]}):null,e.loading&&!e.tree?(0,n.jsx)("div",{className:"grid min-h-0 flex-1 place-items-center text-sm text-muted-foreground",children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(b.A,{className:"size-4 animate-spin"}),m("branchLoading")]})}):0===q.length?(0,n.jsx)("div",{className:"grid min-h-0 flex-1 place-items-center px-4 text-center text-sm text-muted-foreground",children:0===B.length?m("branchEmpty"):m("branchNoMatches")}):(0,n.jsxs)("div",{ref:L,id:et,role:"tree","aria-label":m("branchTree"),className:"pi-desk-chat-scrollbar min-h-0 flex-1 overflow-y-auto px-1 py-1",onScroll:e=>R(e.currentTarget.scrollTop),children:[(0,n.jsx)("div",{style:{height:`${36*H}px`},"aria-hidden":"true"}),Q.map(t=>{let s=t.node.entryId===W,r=Math.min(t.depth,10),i=m1[t.node.kind];return(0,n.jsxs)("div",{id:`${et}-entry-${t.node.entryId}`,role:"treeitem","aria-level":t.depth+1,"aria-selected":s,"aria-expanded":t.foldable?t.expanded:void 0,className:(0,C.cn)("group relative flex min-w-0 items-center rounded-md outline-none transition-colors",i.rowClassName,s?"bg-accent text-accent-foreground":t.current?"bg-primary/[0.055] hover:bg-primary/[0.08]":"hover:bg-muted/50"),style:{height:"36px",paddingLeft:`${10*r}px`},children:[r>0?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("pointer-events-none absolute bottom-0 top-0 w-px",t.active?"bg-primary/25":"bg-border/60"),style:{left:`${10*r-5}px`}}):null,t.connector?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("pointer-events-none absolute h-px w-2",t.active?"bg-primary/25":"bg-border/60"),style:{left:`${10*r-5}px`}}):null,(0,n.jsx)("div",{className:"flex w-6 shrink-0 items-center justify-center",children:t.foldable?(0,n.jsx)("button",{type:"button","aria-label":m(t.expanded?"collapseBranch":"expandBranch"),className:"flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-foreground/8 hover:text-foreground",onMouseDown:m5,onClick:()=>{el(t.node.entryId),queueMicrotask(en)},children:(0,n.jsx)(e8.A,{className:(0,C.cn)("size-3 transition-transform",t.expanded&&"rotate-90")})}):null}),(0,n.jsxs)("button",{type:"button",tabIndex:-1,className:"flex h-full min-w-0 flex-1 items-center gap-1.5 overflow-hidden text-left outline-none",onMouseDown:m5,onClick:()=>{A(t.node.entryId),queueMicrotask(en)},onDoubleClick:()=>{a||t.current||ec(t.node.entryId,"tree")},children:[(0,n.jsx)("span",{className:(0,C.cn)("w-9 shrink-0 text-xs",i.labelClassName),children:m(i.label)}),t.node.label?(0,n.jsx)("span",{className:"max-w-24 shrink-0 truncate rounded-md bg-muted px-1 text-xs text-foreground",children:t.node.label}):null,(0,n.jsx)("span",{className:(0,C.cn)("min-w-0 flex-1 truncate text-sm",i.contentClassName,s&&"font-semibold text-accent-foreground"),children:t.node.preview||m("noPreview")})]}),a?(0,n.jsxs)("div",{className:"ml-2 flex shrink-0 items-center gap-1 border-l border-border/55 py-0.5 pl-1.5 pr-1",children:[(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||t.current||e.pending,"aria-label":m("switchToMessage",{kind:m(i.label)}),className:(0,N.r)({variant:"secondary",size:"sm"}),onClick:()=>ec(t.node.entryId,"tree"),children:m("switch")}),"user"===t.node.kind?(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||e.pending,"aria-label":m("forkFromUser"),className:(0,N.r)({variant:"outline",size:"sm"}),onClick:()=>ec(t.node.entryId,"fork"),children:"Fork"}):null]}):"user"===t.node.kind?(0,n.jsx)("div",{className:"ml-2 flex shrink-0 items-center border-l border-border/50 pl-2 pr-1",children:(0,n.jsx)("button",{type:"button",disabled:e.actionsDisabled||e.pending,"aria-label":m("forkFromUser"),className:(0,N.r)({variant:"ghost",size:"sm"}),onMouseDown:m5,onClick:()=>ec(t.node.entryId,"fork"),children:"Fork"})}):null]},t.node.entryId)}),(0,n.jsx)("div",{style:{height:`${36*Math.max(0,q.length-J)}px`},"aria-hidden":"true"})]}),(0,n.jsxs)("footer",{className:"flex min-h-9 shrink-0 items-center gap-2 border-t bg-muted/10 px-2",children:[(0,n.jsxs)("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:[U>=0?U+1:0," / ",q.length,a?"":` \xb7 ${m("branchShortcuts")}`]}),a?null:(0,n.jsx)(N.$,{type:"button",size:"sm",disabled:e.actionsDisabled||!V||V.current||e.loading||e.pending,onMouseDown:m5,onClick:em,children:m("switch")})]})]})]})]})}var m6=s(15450),m8=s(31210),m7=s(66722),m9=s(40942),pe=s(61989),pt=s(63434),ps=s(26690),pn=s(2870),pr=s.n(pn);function pa({workSession:e,runtime:t,active:s,chatReady:a,onOpen:i}){let{t:l}=(0,f.Bd)("workbench"),{locale:o}=(0,eG.i)();(0,r.useSyncExternalStore)(t.subscribe,t.getRevision,t.getRevision);let d=t.getWorkspace(e.cwd)?.heads;(0,r.useEffect)(()=>{let n;if(!s||!a)return;let r=()=>{window.clearTimeout(n),n=void 0},i=()=>{r(),"visible"===document.visibilityState&&document.hasFocus()&&(n=window.setTimeout(()=>{n=void 0,"visible"===document.visibilityState&&document.hasFocus()&&t.refreshHeads(e.cwd)},1e3))},l=()=>{"visible"!==document.visibilityState&&r()};return i(),window.addEventListener("focus",i),window.addEventListener("blur",r),document.addEventListener("visibilitychange",l),()=>{r(),window.removeEventListener("focus",i),window.removeEventListener("blur",r),document.removeEventListener("visibilitychange",l)}},[s,a,t,e.cwd]);let c=d?.repositories??[],u=(0,uc.A_)(e.projectName,c,o);if(d?.status==="ready"&&!u)return null;let m=d?.status==="loading"&&!u,p=d?.status==="error"&&!u,h=m?null:u;return(0,n.jsxs)(lJ,{"data-testid":"composer-git-branch",tooltip:p?d.error??l("gitStatusReadFailed"):h?.title??l("gitBranches"),"aria-label":l("gitBranches"),className:pr().branchTrigger,disabled:m,onClick:()=>i({workId:e.workId,cwd:e.cwd,projectName:e.projectName,repositoryRoot:null}),children:[m?(0,n.jsx)(b.A,{className:"size-4 shrink-0 animate-spin"}):(0,n.jsx)(uo.A,{className:"size-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),p?(0,n.jsx)("span",{className:(0,C.cn)(pr().branchFallback,"text-amber-600 dark:text-amber-400"),children:"Git !"}):h?(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("span",{"data-git-branch-full":!0,className:(0,C.cn)(pr().branchFull,h.diverged&&"text-amber-600 dark:text-amber-400"),children:h.full})}):null]})}let pi="l2-workbench-slash-command-menu",pl={key:"builtin:reload",name:"reload",description:"重新读取 Pi 最新配置与扩展资源",source:"builtin"},po=[{source:"builtin",label:"Pi 内置命令"},{source:"skill",label:"Skills"},{source:"prompt",label:"提示模板"},{source:"extension",label:"扩展命令"}];function pd(e){return`${pi}-option-${e}`}function pc(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function pu(e){return[...e.children].filter(e=>e instanceof HTMLElement)}function pm(e,t,s){return e.reduce((e,t)=>e+(s.get(t)??0),0)+Math.max(0,e.length-1)*t}var pp=s(64696);let ph=2*Math.PI*7;function pg(e){if(null===e)return"--";let t=Math.round(e);return t<1e3?String(t):`${Math.round(t/100)/10}K`}function px(e){return Math.min(100,Math.max(0,e))}function pf(e){return ph-e/100*ph}function pb({sessionId:e,cwd:t,tokens:s,contextWindow:a,contextIgnorePlugin:i,ignoreDisabled:l,ignorePending:o,compactDisabled:d,compactPending:c,onIgnoreContext:u,onCompactContext:m}){let p,h,g,x,v,{t:w}=(0,f.Bd)("workbench"),y=(0,r.useId)(),k=(0,r.useRef)(!1),[j,I]=(0,r.useState)(!1),[S,M]=(0,r.useState)(!1),[z,E]=(0,r.useState)(!1),A=(0,Q.G)(),$=(p=!i||"object"!=typeof i||Array.isArray(i)||"number"!=typeof i.ignoredTokens||!Number.isFinite(i.ignoredTokens)||i.ignoredTokens<0||"number"!=typeof i.potentialTokens||!Number.isFinite(i.potentialTokens)||i.potentialTokens<0||void 0!==i.effectiveTokens&&null!==i.effectiveTokens&&("number"!=typeof i.effectiveTokens||!Number.isFinite(i.effectiveTokens)||i.effectiveTokens<0)?null:{ignoredTokens:i.ignoredTokens,potentialTokens:i.potentialTokens,...void 0!==i.effectiveTokens?{effectiveTokens:i.effectiveTokens}:{}},g=null===(h=p?.effectiveTokens===void 0?s:p.effectiveTokens)?0:px(h/a*100),v=null===(x=null===h||null===p?null:Math.max(0,h-p.potentialTokens))?null:px(x/a*100),{contextIgnore:p,currentTokens:h,usedPercent:g,projectedTokens:x,projectedPercent:v,potentialSegmentPercent:null===v?0:Math.max(0,g-v)}),R=Math.round($.usedPercent),T=null===$.projectedPercent?null:Math.round($.projectedPercent),P=R>=90?"text-destructive":R>=80?"text-status-warning":"text-muted-foreground",D=R>=90?"bg-destructive":R>=80?"bg-status-warning":"bg-primary",O=$.contextIgnore?w("contextUsageWithIgnore",{percent:R,projected:T??0,ignored:pg($.contextIgnore.ignoredTokens),potential:pg($.contextIgnore.potentialTokens)}):w("contextUsageSimple",{percent:R,limit:pg(a)});return(0,n.jsxs)(lU,{open:j,triggerId:y,onOpenChange:(e,t)=>{k.current&&"trigger-focus"===t.reason||(e||(M(!1),E(!1)),I(e))},children:[(0,n.jsx)(lV,{id:y,delay:100,closeDelay:100,render:(0,n.jsx)("button",{type:"button","aria-label":O,"aria-expanded":j,className:"inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full bg-transparent transition-colors outline-none hover:bg-accent focus-visible:ring-1 focus-visible:ring-ring/50 data-open:bg-accent",onPointerDown:e=>{k.current="mouse"!==e.pointerType},onPointerCancel:()=>{k.current=!1},onClick:e=>{k.current&&(e.preventDefault(),I(e=>!e),queueMicrotask(()=>{k.current=!1}))},children:(0,n.jsxs)("svg",{className:"pointer-events-none block size-5 -rotate-90",viewBox:"0 0 20 20","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-muted-foreground opacity-20"}),$.contextIgnore?(0,n.jsxs)(n.Fragment,{children:[$.usedPercent>0?(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",strokeDasharray:ph,strokeDashoffset:pf($.usedPercent),className:"text-muted-foreground"}):null,null!==$.projectedPercent&&$.projectedPercent>0?(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",strokeDasharray:ph,strokeDashoffset:pf($.projectedPercent),className:"text-foreground"}):null]}):$.usedPercent>0?(0,n.jsx)("circle",{cx:"10",cy:"10",r:7,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",strokeDasharray:ph,strokeDashoffset:pf($.usedPercent),className:P}):null]})})}),(0,n.jsx)(lK,{side:"top",align:"center",sideOffset:6,"aria-label":w("contextDetails"),className:"w-80 max-w-[calc(100vw-2rem)] p-4 text-sm",children:(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 text-sm",children:[(0,n.jsx)("span",{className:"whitespace-nowrap text-muted-foreground",children:w("contextMetrics")}),(0,n.jsxs)("span",{className:"whitespace-nowrap font-medium tabular-nums text-foreground",children:[pg($.currentTokens)," / ",pg(a)," / ",R,"%"]})]}),(0,n.jsx)("div",{className:"flex h-1.5 overflow-hidden rounded-full bg-muted",children:$.contextIgnore&&null!==$.projectedPercent?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"h-full bg-foreground",style:{width:`${$.projectedPercent}%`}}),(0,n.jsx)("div",{className:"h-full bg-muted-foreground",style:{width:`${$.potentialSegmentPercent}%`}})]}):(0,n.jsx)("div",{className:(0,C.cn)("h-full rounded-full",D),style:{width:`${$.usedPercent}%`}})})]}),$.contextIgnore&&null!==$.projectedTokens?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-foreground"}),w("afterIgnore")]}),(0,n.jsxs)("span",{className:"font-medium tabular-nums text-foreground",children:[pg($.projectedTokens)," \xb7 ",T,"%"]})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-muted-foreground"}),w("potentialIgnore")]}),(0,n.jsx)("span",{className:"font-medium tabular-nums text-foreground",children:pg($.contextIgnore.potentialTokens)})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:w("alreadyIgnored")}),(0,n.jsx)("span",{className:"font-medium tabular-nums text-foreground",children:pg($.contextIgnore.ignoredTokens)})]})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:[(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",disabled:l||o||!$.contextIgnore||$.contextIgnore.potentialTokens<=0,"aria-label":$.contextIgnore&&$.contextIgnore.potentialTokens>0?w("ignoreNow",{amount:pg($.contextIgnore.potentialTokens)}):w("nothingToIgnore"),"aria-busy":o,onClick:()=>void u(),children:[o?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(pp.A,{}),o?w("ignoring"):w("ignore")]}),(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"outline",disabled:d||c,"aria-busy":c,onClick:()=>void m(),children:[c?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(oW.A,{}),c?w("compacting"):w("compact")]})]}),R>=80?(0,n.jsx)("p",{className:(0,C.cn)("pt-1 text-sm",R>=90?"text-destructive":"text-status-warning"),children:R>=90?w("contextCritical"):w("contextWarning")}):null,(0,n.jsx)("div",{className:"border-t border-border"}),(0,n.jsxs)("button",{type:"button","aria-label":w("copySessionId",{id:e}),className:"w-full cursor-pointer rounded-md px-1 py-1 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50",onClick:()=>{(0,e7.x)(e).then(e=>{e?M(!0):A.error(w("copySessionFailed"))})},children:[(0,n.jsxs)("span",{className:"flex items-center justify-between gap-3 text-muted-foreground",children:[(0,n.jsx)("span",{children:w("currentSessionId")}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:[S?w("copied"):w("clickToCopy"),S?(0,n.jsx)(em.A,{className:"size-3.5"}):(0,n.jsx)(Z.A,{className:"size-3.5"})]})]}),(0,n.jsx)("span",{className:"mt-1 block break-all font-mono text-xs leading-5 text-foreground",children:e})]}),(0,n.jsxs)("button",{type:"button","aria-label":w("copyCurrentPath",{path:t}),className:"w-full cursor-pointer rounded-md px-1 py-1 text-left transition-colors outline-none hover:bg-muted focus-visible:ring-1 focus-visible:ring-ring/50",onClick:()=>{(0,e7.x)(t).then(e=>{e?E(!0):A.error(w("copyPathFailed"))})},children:[(0,n.jsxs)("span",{className:"flex items-center justify-between gap-3 text-muted-foreground",children:[(0,n.jsx)("span",{children:w("currentPath")}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:[z?w("copied"):w("clickToCopy"),z?(0,n.jsx)(em.A,{className:"size-3.5"}):(0,n.jsx)(Z.A,{className:"size-3.5"})]})]}),(0,n.jsx)("span",{className:"mt-1 block min-w-0 break-words font-mono text-xs leading-5 text-foreground",title:t,children:t})]})]})})]})}function pv(e,t){let[s,n]=(0,r.useState)({value:null,loading:!1,error:null}),[a,i]=(0,r.useState)(0);return(0,r.useEffect)(()=>{if(!e)return;let s=!0;return Promise.resolve().then(async()=>{if(s){n({value:null,loading:!0,error:null});try{let e=await t();s&&n({value:e,loading:!1,error:null})}catch(e){s&&n({value:null,loading:!1,error:e instanceof Error?e.message:String(e)})}}}),()=>{s=!1}},[a,e,t]),{...s,retry:()=>i(e=>e+1)}}let pw={direct:["toolExposureDirect","直接使用"],"model-only":["toolExposureModelOnly","仅模型调用"],codemode:["toolExposureCodemode","通过脚本调用"],deferred:["toolExposureDeferred","按需发现"],hidden:["toolExposureHidden","不可调用"]};function py({tools:e}){let{t}=(0,f.Bd)("workbench"),[s,a]=(0,r.useState)(""),[i,l]=(0,r.useState)("all"),o=s.trim().toLocaleLowerCase(),d=e.filter(e=>(!o||`${e.name} ${e.source??""} ${e.description}`.toLocaleLowerCase().includes(o))&&("all"===i||("blocked"===i?e.blockedByMode:e.exposure===i)));return(0,n.jsxs)("section",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsxs)(ny.MG,{className:"min-w-0 flex-1 basis-56",children:[(0,n.jsx)(ny.Sq,{children:(0,n.jsx)(ep.A,{className:"size-4"})}),(0,n.jsx)(ny.iV,{"aria-label":t("searchTools"),placeholder:t("searchToolsSources",{defaultValue:"搜索名称、来源或描述"}),value:s,onChange:e=>a(e.target.value)})]}),(0,n.jsxs)(ea.l6,{value:i,onValueChange:e=>{"string"==typeof e&&l(e)},children:[(0,n.jsx)(ea.bq,{"aria-label":t("toolFilter"),className:"max-w-full",children:(0,n.jsx)(ea.yv,{children:"all"===i?t("allTools"):"blocked"===i?t("toolBlockedByMode"):t(pw[i]?.[0]??"toolUnknown")})}),(0,n.jsxs)(ea.gC,{positionerClassName:"z-[120]",children:[(0,n.jsx)(ea.eb,{value:"all",children:t("allTools")}),Object.entries(pw).map(([e,[s,r]])=>(0,n.jsx)(ea.eb,{value:e,children:t(s,{defaultValue:r})},e)),(0,n.jsx)(ea.eb,{value:"blocked",children:t("toolBlockedByMode")})]})]})]}),(0,n.jsxs)("div",{className:"divide-y",children:[d.map(e=>{let s=e.exposure?pw[e.exposure]:null;return(0,n.jsxs)("article",{className:"space-y-2 py-3",children:[(0,n.jsx)("h3",{className:"wrap-anywhere font-mono text-sm font-medium",children:e.name}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:[t("toolSource",{defaultValue:"来源"}),":"," ",e.source??t("toolUnknown",{defaultValue:"未知"})]}),(0,n.jsx)("span",{children:s?t(s[0],{defaultValue:s[1]}):t("toolUnknown",{defaultValue:"未知"})}),(0,n.jsx)("span",{children:void 0===e.active?t("toolUnknown",{defaultValue:"未知"}):e.active?t("toolActive",{defaultValue:"当前已选用"}):t("toolInactive",{defaultValue:"当前未选用"})}),(0,n.jsx)("span",{children:void 0===e.blockedByMode?t("toolModeUnknown",{defaultValue:"模式限制未知"}):e.blockedByMode?t("toolBlockedByMode",{defaultValue:"受模式限制"}):t("toolNotBlocked",{defaultValue:"未受模式限制"})})]}),(0,n.jsx)("p",{className:"whitespace-pre-wrap wrap-anywhere text-sm text-muted-foreground",children:e.description}),(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{className:"min-h-7 cursor-pointer text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:t("parameterSchema")}),(0,n.jsx)("pre",{className:"mt-2 whitespace-pre-wrap wrap-anywhere rounded-lg bg-muted p-3 font-mono text-sm leading-[1.6]",children:JSON.stringify(e.parameters,null,2)})]})]},e.name)}),d.length?null:(0,n.jsxs)("div",{className:"space-y-3 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)("p",{children:o||"all"!==i?t("noMatchingTools"):t("noRegisteredTools",{defaultValue:"当前会话没有登记工具"})}),o||"all"!==i?(0,n.jsx)(N.$,{variant:"outline",size:"sm",onClick:()=>{a(""),l("all")},children:t("clearSearch")}):null]})]})]})}function pk({notices:e}){let{t}=(0,f.Bd)("workbench");return(0,n.jsx)("section",{"aria-label":t("nativeCommandOutput",{defaultValue:"会话命令输出"}),className:"space-y-3",children:e.length?e.map((e,t)=>(0,n.jsx)("p",{className:`whitespace-pre-wrap wrap-anywhere font-mono text-sm leading-[1.6] ${"error"===e.level?"text-destructive":"warning"===e.level?"text-amber-700 dark:text-amber-300":""}`,children:function(e){let t=[],s=0;for(let r of e.matchAll(/https?:\/\/[^\s<>"']+/g)){let a=r.index,i=r[0].replace(/[)\]。,.;]+$/,"");t.push(e.slice(s,a)),t.push((0,n.jsx)("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"underline underline-offset-2 wrap-anywhere",children:i},a)),s=a+i.length}return t.push(e.slice(s)),t}(e.message)},t)):(0,n.jsx)("p",{className:"py-6 text-sm text-muted-foreground",children:t("nativeCommandOutputEmpty",{defaultValue:"暂无会话命令输出"})})})}function pj({available:e,state:t,disabled:s,onExecute:a}){let{t:i}=(0,f.Bd)("workbench"),[l,o]=(0,r.useState)("status"),[d,c]=(0,r.useState)(""),[u,m]=(0,r.useState)(!1),p="status"!==l,h=d.trim(),g=p&&!/^[a-zA-Z0-9_-]+$/.test(h);return(0,n.jsxs)("div",{className:"space-y-4",children:[e?(0,n.jsxs)("form",{className:"space-y-3",onSubmit:e=>{e.preventDefault(),s||!t.ready||t.commandPending||g||"logout"===l&&!u||a("status"===l?"":`${l} ${h}`,"login"===l)},children:[(0,n.jsx)(nJ,{label:i("mcpSessionActions",{defaultValue:"MCP 会话操作"}),layout:"segmented",value:l,onChange:e=>{o(e),m(!1)},options:[{value:"status",label:i("mcpStatus",{defaultValue:"状态"})},{value:"login",label:i("mcpLogin",{defaultValue:"登录"})},{value:"reconnect",label:i("mcpReconnect",{defaultValue:"重连"})},{value:"logout",label:i("mcpLogout",{defaultValue:"退出登录"})}]}),p?(0,n.jsxs)("label",{className:"block space-y-1 text-sm font-medium",children:[(0,n.jsx)("span",{children:i("mcpServerName",{defaultValue:"服务名称"})}),(0,n.jsx)(eu.p,{value:d,onChange:e=>c(e.target.value),placeholder:i("mcpServerNamePlaceholder",{defaultValue:"输入真实服务名称"}),autoComplete:"off",maxLength:128})]}):null,p&&h&&g?(0,n.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:i("mcpServerNameInvalid",{defaultValue:"服务名称只能包含字母、数字、下划线和连字符。"})}):null,"logout"===l?(0,n.jsxs)("label",{className:"flex min-h-8 cursor-pointer items-start gap-2 text-sm",children:[(0,n.jsx)("input",{type:"checkbox",className:"mt-1 size-4 accent-primary",checked:u,onChange:e=>m(e.target.checked)}),(0,n.jsx)("span",{children:i("mcpLogoutConfirm",{defaultValue:"删除共享登录凭据,其他会话下次访问也可能需要重新登录。"})})]}):null,(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)(N.$,{type:"submit",size:"sm",disabled:s||!t.ready||null!==t.commandPending||g||"logout"===l&&!u,children:i("mcpExecute",{defaultValue:"执行"})}),t.commandPending?(0,n.jsxs)("span",{role:"status",className:"wrap-anywhere text-sm text-muted-foreground",children:[i("mcpExecuting",{defaultValue:"正在执行"})," ",t.commandPending]}):null]})]}):(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:i("mcpCommandUnavailable",{defaultValue:"当前会话未注册 MCP 命令。"})}),(0,n.jsxs)("div",{className:"border-t pt-4",children:[(0,n.jsx)("h3",{className:"mb-3 text-sm font-medium",children:i("nativeCommandOutput",{defaultValue:"会话命令输出"})}),(0,n.jsx)(pk,{notices:t.notices})]})]})}function pN({open:e,source:t,runtime:s,getContext:a,listCommands:i,nativeUi:l,nativeBiz:o,commandsDisabled:d,onOpenChange:c,onOpenSettings:u}){let{t:m,i18n:p}=(0,f.Bd)("workbench"),[h,g]=(0,r.useState)(!1),[x,b]=(0,r.useState)("tools"),v=(0,Q.G)(),{context:w,tools:y,commands:k}=function(e){let{source:t,runtime:s,getContext:n,listCommands:a,open:i,tab:l}=e,o=(0,r.useCallback)(()=>n({source:t}),[n,t]),d=(0,r.useCallback)(()=>s.listTools(t),[s,t]),c=(0,r.useCallback)(()=>a({source:t}),[a,t]);return{context:pv(i&&"system"===l,o),tools:pv(i&&"tools"===l,d),commands:pv(i&&"mcp"===l,c)}}({source:t,open:e,tab:x,runtime:s,getContext:a,listCommands:i}),j="system"===x?w:"tools"===x?y:k,I=l.state.snapshot.requests[0]?.id;(0,r.useEffect)(()=>{e&&I&&(l.setCollapsed(!1),c(!1))},[e,I,l,c]);let C=async()=>{w.value&&(await (0,e7.x)(w.value.systemPrompt)?g(!0):v.error(m("contextCopyFailed")))};return(0,n.jsx)(ej.YV,{open:e,onOpenChange:c,children:(0,n.jsxs)(ej.hA,{className:"h-[min(42rem,calc(100dvh-2rem))] max-w-[45rem]",children:[(0,n.jsxs)(ej.Hl,{className:"border-b p-4 pr-12",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)(nv.A,{className:"size-5 shrink-0 text-muted-foreground"}),(0,n.jsx)(ej.YM,{children:m("toolsAndContext",{defaultValue:"工具与上下文"})})]}),(0,n.jsx)(ej.uX,{className:"sr-only",children:m("sessionContextDescription",{defaultValue:"当前会话的登记工具、系统提示词和 MCP 原生命令"})})]}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-3",children:[(0,n.jsx)(nJ,{label:m("contextContents"),layout:"segmented",value:x,onChange:b,options:[{value:"tools",label:m("tools")},{value:"system",label:m("systemPrompt")},{value:"mcp",label:m("mcpSession",{defaultValue:"会话 MCP"})}]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:["system"===x?(0,n.jsxs)(N.$,{variant:"ghost",size:"sm",disabled:!w.value||w.loading,onClick:()=>void C(),children:[h?(0,n.jsx)(em.A,{}):(0,n.jsx)(Z.A,{}),h?m("copied"):m("copy")]}):null,u?(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{c(!1),u()},children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]})]}),(0,n.jsx)(ej._Y,{children:(0,n.jsx)("div",{className:"p-4",children:!j.loading&&(j.value||j.error)?j.error?(0,n.jsxs)("div",{className:"space-y-3 py-6",children:[(0,n.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error}),(0,n.jsxs)(N.$,{variant:"outline",size:"sm",onClick:j.retry,children:[(0,n.jsx)(et.A,{}),m("contextRetry")]})]}):"tools"===x&&y.value?(0,n.jsx)(py,{tools:y.value.tools}):"system"===x&&w.value?(0,n.jsx)("section",{"aria-label":m("systemPrompt"),children:(0,n.jsx)("pre",{className:"whitespace-pre-wrap wrap-anywhere font-mono text-sm leading-[1.6]",children:w.value.systemPrompt||m("emptyContent")})}):"mcp"===x&&k.value?(0,n.jsx)(pj,{available:k.value.commands.some(e=>"mcp"===e.name&&"extension"===e.source),state:l.state,disabled:d,onExecute:(e,s)=>{o.executeCommand(t,"mcp",e),s&&(l.setCollapsed(!1),c(!1))}}):null:(0,n.jsxs)("div",{role:"status",className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,n.jsx)(et.A,{className:"size-4 animate-spin"}),m("contextLoading")]})})})]})})}let pI={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pC({source:e,runtime:t,catalog:s,current:a,label:i,title:l,disabled:o,triggerClassName:d,detailsClassName:c,onOpenSettings:u}){let{t:m,i18n:p}=(0,f.Bd)("workbench"),[h,g]=(0,r.useState)(null),{open:x,pending:b,error:v,changeOpen:w,refresh:y,submit:k}=function(e,t,s){let[n,a]=(0,r.useState)(!1),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(null),c=(0,r.useRef)(null),u=(0,r.useRef)(!1),m=(0,r.useRef)(!0);(0,r.useEffect)(()=>(m.current=!0,()=>{m.current=!1,c.current=null}),[]);let p=()=>{t.loadModels(e,!0)},h=e=>{c.current=e?{}:null,a(e),e&&(d(null),p())},g=async(n,r)=>{if(s||u.current)return;let a=c.current;u.current=!0,l(!0),d(null);try{await t.setModel(e,{provider:n.provider,modelId:n.modelId,thinkingLevel:r}),a&&c.current===a&&h(!1)}catch(e){a&&c.current===a&&d(e instanceof Error?e.message:String(e))}finally{u.current=!1,m.current&&l(!1)}};return{open:n,pending:i,error:o,changeOpen:h,refresh:p,submit:g}}(e,t,o),j=s.models.find(e=>e.provider===a?.provider&&e.modelId===a.modelId),N=s.models.some(e=>"virtual"===e.kind)?[{key:"virtual",label:m("modelAutomaticRouting",{defaultValue:"自动路由"}),models:s.models.filter(e=>"virtual"===e.kind)},{key:"physical",label:m("modelFixed",{defaultValue:"固定模型"}),models:s.models.filter(e=>"physical"===e.kind)}].filter(e=>e.models.length>0):[{key:"all",label:m("allModels"),models:s.models}];return(0,n.jsxs)(K.rI,{open:x,onOpenChange:e=>{g(null),w(e)},children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)(lJ,{title:l,"aria-label":m("chooseModel"),className:d}),children:[(0,n.jsx)(eT.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{"data-model-trigger-details":!0,className:c,children:(0,n.jsxs)("span",{className:"flex min-w-0 items-center gap-2 pl-2",children:[(0,n.jsx)("span",{className:"min-w-0 truncate",children:i}),(0,n.jsx)(eq.A,{className:"size-3 shrink-0"})]})})]}),(0,n.jsxs)(K.SQ,{align:"start",side:"top",className:"flex max-h-96 w-72 flex-col overflow-hidden p-0",children:[(0,n.jsxs)(K.I,{className:"shrink-0 p-1",children:[(0,n.jsx)(K.lp,{children:m("currentModel")}),(0,n.jsxs)("div",{className:"mx-1 mb-1 flex items-center gap-2 rounded-md border bg-muted/50 px-2 py-2",children:[(0,n.jsx)(eT.A,{className:"size-4 shrink-0 text-muted-foreground"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"truncate text-sm font-medium",children:j?.name||a?.modelId||m("selectModel")}),(0,n.jsx)("p",{className:"truncate text-xs text-muted-foreground",children:a?.provider||m("selectModel")})]}),a?(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground",children:m("thinkingLevel",{level:m(pI[a.thinkingLevel])})}):null]}),v?(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:v}):null,b?(0,n.jsx)("p",{role:"status",className:"px-2 py-1 text-sm text-muted-foreground",children:m("modelChanging",{defaultValue:"正在切换模型…"})}):null]}),(0,n.jsx)(K.mB,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar min-h-0 flex-auto overflow-x-hidden overflow-y-auto overscroll-contain p-1",children:["loading"===s.status?(0,n.jsxs)(K._2,{disabled:!0,children:[(0,n.jsx)(et.A,{className:"size-4 animate-spin"}),m("modelsLoading")]}):null,"error"===s.status?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{role:"alert",className:"wrap-anywhere px-2 py-1 text-sm text-destructive",children:s.error||m("modelsFailed")}),(0,n.jsxs)(K._2,{closeOnClick:!1,onClick:y,children:[(0,n.jsx)(et.A,{className:"size-4"}),m("retry")]})]}):null,N.map(e=>(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:e.label}),e.models.map(e=>{let t=`${e.provider}:${e.modelId}`,s=a?.provider===e.provider&&a.modelId===e.modelId;return(0,n.jsxs)(K.lv,{open:h===t,onOpenChange:e=>{g(s=>e?t:s===t?null:s)},children:[(0,n.jsxs)(K.nV,{disabled:o||b,label:e.name||e.modelId,children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.name||e.modelId}),e.input.includes("image")?(0,n.jsx)(ra.A,{className:"size-3 text-muted-foreground"}):null,s?(0,n.jsx)(em.A,{className:"size-3 text-muted-foreground"}):null]}),(0,n.jsx)(K.M5,{children:(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:m("thinkingLevels")}),e.thinkingLevels.map(t=>(0,n.jsxs)(K._2,{disabled:o||b,closeOnClick:!1,onClick:()=>{g(null),k(e,t)},children:[(0,n.jsx)("span",{className:"flex-1",children:m(pI[t])}),s&&a?.thinkingLevel===t?(0,n.jsx)(em.A,{className:"size-3 text-muted-foreground"}):null]},t))]})})]},t)})]},e.key)),"ready"===s.status&&0===s.models.length?(0,n.jsx)(K._2,{disabled:!0,children:m("noModels")}):null,u&&("error"===s.status||"ready"===s.status&&0===s.models.length)?(0,n.jsx)(K._2,{onClick:()=>u(),children:m("openSettings",{defaultValue:(p.resolvedLanguage??p.language).startsWith("en")?"Open settings":"打开设置"})}):null]}),"ready"===s.status||s.presets.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(K.mB,{className:"mx-0 my-0 shrink-0"}),(0,n.jsxs)(K.I,{className:"shrink-0 p-1",children:[(0,n.jsx)(K.lp,{children:m("presets")}),0===s.presets.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:m("commonCombinationsEmpty")}),u?(0,n.jsxs)(K._2,{onClick:()=>{w(!1),u("model-presets")},children:[(0,n.jsx)(iC.A,{className:"size-4"}),m("configureCommonCombinations")]}):null]}):null,s.presets.map((e,t)=>(0,n.jsxs)(K._2,{disabled:o||b,closeOnClick:!1,onClick:()=>void k(e,e.thinkingLevel),children:[(0,n.jsx)("span",{className:"size-2 rounded-full bg-current",style:e.color?{color:e.color}:void 0}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate",children:s.models.find(t=>t.provider===e.provider&&t.modelId===e.modelId)?.name||e.modelId}),(0,n.jsx)("span",{className:"text-muted-foreground",children:m(pI[e.thinkingLevel])})]},`${e.provider}:${e.modelId}:${e.thinkingLevel}:${t}`))]})]}):null]})]})}var pS=s(15824);function pM({label:e,description:t,markerClass:s,countClass:r,inputs:a}){let{t:i}=(0,f.Bd)("workbench");return 0===a.length?null:(0,n.jsxs)("section",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-3 px-1",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:`size-1.5 shrink-0 rounded-full ${s}`}),(0,n.jsx)("h3",{className:"text-sm font-medium text-foreground",children:e})]}),(0,n.jsx)("p",{className:"mt-1 pl-3.5 text-sm leading-5 text-muted-foreground",children:t})]}),(0,n.jsx)("span",{className:`shrink-0 rounded-md px-1.5 py-0.5 text-xs font-medium tabular-nums ${r}`,children:i("queueItems",{count:a.length})})]}),(0,n.jsx)("ol",{className:"divide-y divide-border overflow-hidden",children:a.map((e,t)=>{let s=e.text.trim();return(0,n.jsxs)("li",{className:"grid grid-cols-[1.25rem_minmax(0,1fr)] gap-2.5 px-3 py-2.5",children:[(0,n.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center rounded-md bg-muted text-xs tabular-nums text-muted-foreground",children:t+1}),(0,n.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,n.jsx)("p",{className:"whitespace-pre-wrap break-words text-sm leading-6 text-foreground",children:s||i(e.images.length>0?"imageOnly":"noMessageText")}),e.images.length>0?(0,n.jsxs)("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[(0,n.jsx)(ra.A,{className:"size-3"}),i("queueImages",{count:e.images.length})]}):null]})]},e.tempId)})})]})}function pz({queues:e,disabled:t,onRestore:s}){let{t:a}=(0,f.Bd)("workbench"),i=(0,r.useId)(),l=(0,r.useRef)(!1),[o,d]=(0,r.useState)(!1),c=e.steering.length+e.followUp.length;return 0===c?null:(0,n.jsxs)(lU,{open:o,triggerId:i,onOpenChange:(e,t)=>{l.current&&"trigger-focus"===t.reason||d(e)},children:[(0,n.jsx)(lV,{id:i,delay:100,closeDelay:120,render:(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",disabled:t,"aria-label":a("viewQueued",{count:c}),"aria-expanded":o,onPointerDown:e=>{l.current="mouse"!==e.pointerType},onPointerCancel:()=>{l.current=!1},onClick:e=>{l.current&&(e.preventDefault(),d(e=>!e),queueMicrotask(()=>{l.current=!1}))},children:a("queuedCount",{count:c})})}),(0,n.jsxs)(lK,{side:"top",align:"end",sideOffset:6,"aria-label":a("queueCurrent"),className:"w-[22rem] max-w-[calc(100vw-2rem)] overflow-hidden p-0",children:[(0,n.jsx)("div",{className:"border-b px-4 py-3",children:(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground",children:(0,n.jsx)(pS.A,{className:"size-4"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("h2",{className:"text-sm font-semibold tracking-tight text-foreground",children:a("queueCurrent")}),(0,n.jsx)("p",{className:"mt-1 text-sm leading-5 text-muted-foreground",children:a("queuePendingDescription")})]}),(0,n.jsx)("span",{className:"shrink-0 rounded-md bg-muted px-2 py-1 text-xs tabular-nums text-foreground",children:a("queueItems",{count:c})})]})}),(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar max-h-[min(24rem,55dvh)] space-y-4 overflow-y-auto p-4",children:[(0,n.jsx)(pM,{label:a("queueSteer"),description:a("queueSteerDescription"),markerClass:"bg-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.steering}),(0,n.jsx)(pM,{label:a("queueFollowUp"),description:a("queueFollowUpDescription"),markerClass:"bg-muted-foreground",countClass:"bg-muted text-muted-foreground",inputs:e.followUp})]}),(0,n.jsx)("div",{className:"border-t border-border/60 bg-muted/15 p-2",children:(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",className:"w-full text-muted-foreground hover:text-foreground",disabled:t,onClick:s,children:[(0,n.jsx)(lP.A,{}),a("queueRestore")]})})]})]})}let pE={builtin:"slashGroupBuiltin",skill:"slashGroupSkill",prompt:"slashGroupPrompt",extension:"slashGroupExtension"};function pA({open:e,loading:t,error:s,groups:a,activeIndex:i,onActiveIndexChange:l,onSelect:o}){let{t:d}=(0,f.Bd)("workbench"),c=(0,r.useRef)(null),u=a.reduce((e,t)=>e+t.commands.length,0);if((0,r.useEffect)(()=>{c.current?.scrollIntoView({block:"nearest"})},[i]),!e)return null;let m=0,p=u>0,h=t?d("slashLoadingMore"):s?d("slashMoreFailed"):null;return(0,n.jsxs)("div",{id:pi,role:"listbox","aria-label":d("slashCandidates"),"aria-busy":t,className:"absolute bottom-full left-[-1px] z-20 mb-2 flex w-[calc(100%+2px)] origin-bottom-left flex-col overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2 duration-100",children:[(0,n.jsxs)("div",{className:"pi-desk-chat-scrollbar max-h-72 overflow-x-hidden overflow-y-auto overscroll-contain p-1 scroll-py-8 max-sm:max-h-[40dvh]",children:[a.map((e,t)=>(0,n.jsxs)("section",{role:"group","aria-label":d(pE[e.source]),className:(0,C.cn)(t>0&&"mt-1 border-t pt-1"),children:[(0,n.jsxs)("div",{className:"sticky -top-1 z-10 flex h-7 items-center gap-2 bg-popover px-2 text-xs font-medium text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-1.5 rounded-full bg-muted-foreground"}),(0,n.jsx)("span",{children:d(pE[e.source])}),(0,n.jsx)("span",{className:"ml-auto font-normal tabular-nums opacity-70",children:e.commands.length})]}),e.commands.map(e=>{let t=m++,s=t===i;return(0,n.jsxs)("div",{id:pd(t),ref:s?c:void 0,role:"option","aria-selected":s,"data-active":s?"true":"false",className:"grid min-h-9 cursor-pointer grid-cols-[minmax(6.75rem,0.9fr)_minmax(0,1.2fr)_0.75rem] items-center gap-2 rounded-md px-2 py-1 text-sm outline-none select-none data-[active=true]:bg-accent sm:grid-cols-[minmax(7rem,0.8fr)_minmax(0,1.5fr)_1rem]",onPointerMove:e=>{"mouse"===e.pointerType&&l(t)},onPointerDown:e=>e.preventDefault(),onClick:()=>o(t),children:[(0,n.jsxs)("span",{className:"min-w-0 truncate font-mono text-sm font-medium",children:[(0,n.jsx)("span",{className:"text-primary",children:"/"}),e.name]}),(0,n.jsx)("span",{className:"min-w-0 truncate text-sm text-muted-foreground",children:"builtin"===e.source&&"reload"===e.name?d("reloadDescription"):e.description}),(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("text-right text-sm text-muted-foreground opacity-0",s&&"opacity-80"),children:"↵"})]},e.key)})]},e.source)),p?h?(0,n.jsxs)("div",{className:"flex min-h-7 items-center gap-2 px-2 text-xs text-muted-foreground",children:[t?(0,n.jsx)(b.A,{className:"size-3 animate-spin"}):null,(0,n.jsx)("span",{children:h})]}):null:(0,n.jsxs)("div",{className:"flex min-h-20 items-center justify-center gap-2 px-4 text-xs text-muted-foreground",children:[t?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):null,(0,n.jsx)("span",{children:t?d("slashLoading"):s?d("slashFailed"):d("slashEmpty")})]})]}),(0,n.jsxs)("div",{className:"flex min-h-7 items-center justify-between gap-3 border-t px-2.5 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:"tabular-nums",children:a.length>0?d("slashSummary",{commands:u,groups:a.length}):d("slashCount",{count:u})}),(0,n.jsxs)("span",{className:"flex items-center gap-2 max-sm:hidden","aria-hidden":"true",children:[(0,n.jsx)("span",{children:d("slashUpDown")}),(0,n.jsx)("span",{children:d("slashEnter")}),(0,n.jsx)("span",{children:d("slashEscape")})]})]})]})}var p$=s(58270),pR=s.n(p$);function pT({modes:e,value:t,disabled:s,onChange:r}){let{t:a}=(0,f.Bd)("capabilityModes");if(0===Object.keys(e).length)return null;let i=null===t?a("allEnabled"):Object.hasOwn(e,t)?e[t]:a("modeSwitching");return(0,n.jsxs)(K.rI,{children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)(N.$,{variant:"ghost",size:"sm",disabled:s,"aria-label":a("modePicker",{name:i}),className:"min-w-0 max-w-40 text-muted-foreground"}),children:[(0,n.jsx)(eh.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:i}),(0,n.jsx)(eq.A,{className:"size-3 shrink-0"})]}),(0,n.jsx)(K.SQ,{side:"top",align:"start",className:"max-h-80 min-w-40 overflow-y-auto",children:(0,n.jsxs)(K.Hr,{value:t??"",onValueChange:e=>r("string"==typeof e&&e?e:null),children:[(0,n.jsx)(K.Ht,{value:"",children:a("allEnabled")}),Object.entries(e).map(([e,t])=>(0,n.jsx)(K.Ht,{value:e,children:t},e))]})})]})}var pP=s(18903),pD=s(8356),pO=s(93192);function pL({request:e,model:t}){let{t:s}=(0,f.Bd)("workbench"),a=(0,r.useId)(),[i,l]=(0,r.useState)(!1),[o,d]=(0,r.useState)(()=>Date.now()),{state:c}=t,u=Object.hasOwn(c.answers,e.id),m=c.answers[e.id]??("editor"===e.method?e.prefill:""),p=null!==e.expiresAt&&e.expiresAt<=o,h=!c.ready||null!==c.submitting||null!==c.unknown||p,g=h||"select"===e.method&&!u;(0,r.useEffect)(()=>{if(null===e.expiresAt)return;let t=window.setInterval(()=>d(Date.now()),500);return()=>window.clearInterval(t)},[e.expiresAt]);let x=s=>{s?.preventDefault(),g||t.answer(e.id,"confirm"===e.method||m)},b=s=>(0,n.jsx)(t8.T,{"aria-label":e.title,"aria-labelledby":s?void 0:a,className:s?"min-h-0 flex-1 resize-none text-base":"h-32 min-h-20 resize-none text-base",value:m,disabled:null!==c.submitting,maxLength:65536,onChange:s=>t.setAnswer(e.id,s.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),x())}}),v=(r=!1)=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",disabled:!r&&!t.canStop,onClick:r?()=>l(!1):t.stop,children:r?s("nativeUiBack"):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(pe.A,{className:"size-3.5"}),s("nativeUiStop")]})}),(0,n.jsx)("span",{className:"flex-1"}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"outline",disabled:h,onClick:()=>t.answer(e.id,"confirm"!==e.method&&null),children:s("confirm"===e.method?"nativeUiReject":"nativeUiCancel")}),(0,n.jsx)(N.$,{type:r?"button":"submit",size:"sm",disabled:g,onClick:r?()=>x():void 0,children:s(c.submitting?"nativeUiSubmitting":"confirm"===e.method?"nativeUiConfirm":"nativeUiSubmit")})]});return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("section",{className:"mb-2 overflow-hidden rounded-xl border border-input bg-background","aria-label":s("nativeUiTitle"),"data-testid":"native-ui-question",onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||i||(e.preventDefault(),e.stopPropagation(),t.setCollapsed(!0))},children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 px-3 pt-2 text-xs text-muted-foreground",children:[(0,n.jsx)(pP.A,{className:"size-3.5"}),(0,n.jsx)("span",{children:s("nativeUiTitle")}),c.snapshot.requests.length>1?(0,n.jsx)("span",{children:s("nativeUiMore",{count:c.snapshot.requests.length-1})}):null,(0,n.jsx)("span",{className:"flex-1"}),"editor"===e.method?(0,n.jsxs)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>l(!0),children:[(0,n.jsx)(_.A,{className:"size-3.5"}),s("nativeUiExpand")]}):null,(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>t.setCollapsed(!0),children:s("nativeUiLater")})]}),(0,n.jsxs)("form",{onSubmit:x,children:[(0,n.jsxs)("div",{className:"max-h-[40dvh] space-y-3 overflow-y-auto px-3 pt-2 pb-3",children:[(0,n.jsx)("h3",{id:a,className:"text-base leading-6 font-medium whitespace-pre-wrap wrap-anywhere",children:e.title}),"confirm"===e.method?(0,n.jsx)("p",{className:"text-sm leading-6 whitespace-pre-wrap wrap-anywhere text-muted-foreground",children:e.message}):null,"select"===e.method?(0,n.jsx)(nJ,{label:e.title,value:u?String(e.options.indexOf(m)):"",disabled:h,options:e.options.map((e,t)=>({value:String(t),label:e})),onChange:s=>t.setAnswer(e.id,e.options[Number(s)])}):null,"input"===e.method?(0,n.jsx)(eu.p,{"aria-labelledby":a,value:m,placeholder:e.placeholder,maxLength:65536,className:"text-base",disabled:null!==c.submitting,onChange:s=>t.setAnswer(e.id,s.target.value)}):null,"editor"===e.method?b(!1):null,null!==e.expiresAt?(0,n.jsxs)("p",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,n.jsx)(pD.A,{className:"size-3.5"}),s("nativeUiCountdown",{seconds:Math.max(0,Math.ceil((e.expiresAt-o)/1e3))})]}):null]}),(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-2 border-t px-3 py-2",children:v()})]})]}),"editor"===e.method&&i?(0,n.jsx)(ej.YV,{open:!0,onOpenChange:l,children:(0,n.jsxs)(ej.hA,{className:"h-[min(40rem,calc(100dvh-2rem))] max-w-3xl","data-testid":"native-ui-editor-dialog",children:[(0,n.jsx)(ej.Hl,{className:"px-4 pt-4 pr-12 pb-3",children:(0,n.jsx)(ej.YM,{children:e.title})}),c.error||!c.ready?(0,n.jsx)("p",{role:"status",className:"px-4 pb-3 text-sm text-muted-foreground",children:c.error??s("nativeUiDisconnected")}):null,(0,n.jsx)("div",{className:"flex min-h-0 flex-1 px-4 pb-4",children:b(!0)}),(0,n.jsx)(ej.vu,{children:v(!0)})]})}):null]})}function pF({model:e}){let{t}=(0,f.Bd)("workbench"),{state:s}=e,r=s.snapshot.requests[0];return(0,n.jsxs)(n.Fragment,{children:[s.error||!s.ready&&r?(0,n.jsxs)("div",{role:"status",className:"mb-2 flex flex-wrap items-center gap-2 rounded-lg bg-muted px-3 py-2 text-sm",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:s.error??t("nativeUiDisconnected")}),(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:s.refreshing,onClick:e.refresh,children:[s.refreshing?(0,n.jsx)(b.A,{className:"size-3.5 animate-spin"}):null,t("nativeUiRetry")]}),r?null:(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:e.dismissError,children:t("close",{ns:"common"})})]}):null,r?s.collapsed?(0,n.jsxs)("div",{className:"mb-2 flex items-center gap-2 rounded-lg border px-3 py-2","data-testid":"native-ui-collapsed",children:[(0,n.jsx)(pP.A,{className:"size-4 shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 text-sm",children:t("nativeUiPending",{count:s.snapshot.requests.length})}),(0,n.jsx)(N.$,{type:"button",variant:"outline",size:"sm",onClick:()=>e.setCollapsed(!1),children:t("nativeUiResume")})]}):(0,n.jsx)(pL,{request:r,model:e},r.id):null,s.notices.length>0?(0,n.jsxs)(eW.Nt,{defaultOpen:!!(r||s.commandPending?.startsWith("/mcp login ")),className:"mb-2 rounded-lg border px-3 py-2","data-testid":"native-ui-output",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)(eW.R6,{className:"group flex min-h-7 min-w-0 flex-1 cursor-pointer items-center gap-2 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(eq.A,{className:"size-3.5 shrink-0 transition-transform group-data-panel-open:rotate-180 motion-reduce:transition-none"}),t("nativeCommandOutput",{defaultValue:"会话命令输出"})]}),(0,n.jsx)(N.$,{type:"button",size:"icon-sm",variant:"ghost","aria-label":t("close",{ns:"common"}),onClick:e.dismissNotices,children:(0,n.jsx)(Y.A,{className:"size-3.5"})})]}),(0,n.jsx)(eW.Ke,{children:(0,n.jsx)("div",{className:"mt-2 max-h-40 overflow-y-auto",children:(0,n.jsx)(pk,{notices:s.notices})})})]}):null,s.prefill?(0,n.jsxs)("div",{className:"mb-2 rounded-lg border px-3 py-2","data-testid":"native-ui-prefill",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"flex-1 text-sm font-medium",children:t("nativeUiDraft")}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("dismiss"),children:t("nativeUiDismiss")})]}),(0,n.jsx)("p",{className:"my-2 max-h-24 overflow-y-auto text-sm whitespace-pre-wrap wrap-anywhere",children:s.prefill.text}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"secondary",onClick:()=>e.usePrefill("append"),children:t("nativeUiAppend")}),(0,n.jsx)(N.$,{type:"button",size:"sm",variant:"ghost",onClick:()=>e.usePrefill("replace"),children:t("nativeUiReplace")})]})]}):null]})}function p_({snapshot:e,placement:t}){let{t:s}=(0,f.Bd)("workbench"),r=Object.entries(e.widgets).filter(([,e])=>e.placement===t),a="belowEditor"===t?Object.values(e.statuses):[];return r.length||a.length?(0,n.jsxs)("div",{className:"my-1.5 space-y-1","data-testid":`native-ui-extras-${t}`,children:[r.length?(0,n.jsxs)("details",{className:"group",children:[(0,n.jsxs)("summary",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-xs text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)(pO.A,{className:"size-3.5"}),s("nativeUiInfo"),(0,n.jsx)("span",{children:r.length>1?r.length:""}),(0,n.jsx)(eq.A,{className:"size-3.5 transition-transform group-open:rotate-180"})]}),(0,n.jsx)("div",{className:"max-h-36 space-y-2 overflow-y-auto px-2 pb-2 text-sm leading-6",children:r.map(([e,t])=>(0,n.jsx)("p",{className:"whitespace-pre-wrap wrap-anywhere",children:t.lines.join("\n")},e))})]}):null,a.length?(0,n.jsxs)("details",{className:"group",children:[(0,n.jsxs)("summary",{className:"flex min-h-7 cursor-pointer items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)("span",{className:"size-1.5 shrink-0 rounded-full bg-current"}),(0,n.jsx)("span",{className:"min-w-0 truncate group-open:hidden",children:a[0]}),(0,n.jsx)("span",{className:"hidden group-open:inline",children:s("nativeUiStatus")}),a.length>1?(0,n.jsxs)("span",{children:["+",a.length-1]}):null]}),(0,n.jsx)("div",{className:"max-h-32 space-y-1 overflow-y-auto px-2 py-1 text-sm whitespace-pre-wrap wrap-anywhere",children:a.map((e,t)=>(0,n.jsx)("p",{children:e},t))})]}):null]}):null}let pB={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"};function pq(e){return e<1048576?`${Math.max(1,Math.round(e/1024))}KB`:`${(e/1048576).toFixed(1)}MB`}let pW=(0,r.memo)(function({onOpenSettings:e,workSession:t,chatRuntime:s,inputRuntime:a,renderTaskSummary:i,renderTaskMenu:l,renderPluginComposerPanel:o,gitRuntime:d,active:c,mobile:u,invokePluginMethod:m,listPiCommands:p,getChatModelContext:h,capabilityModes:g,setChatCapabilityMode:x,newSessionPending:v,newSessionDisabled:w,onNewSession:y,clonePending:k,cloneDisabled:j,onCloneWorkSession:I,onOpenBranchPicker:S,onOpenGitBranchPicker:M}){var z;let E,A,$,T,P,{t:D}=(0,f.Bd)("workbench"),O=(0,Q.G)(),L=(0,J.So)(),F=(0,r.useMemo)(()=>uz.Pi.parse({workId:t.workId,sessionId:t.sessionId,branchId:t.branchId}),[t.branchId,t.sessionId,t.workId]),_=(0,r.useCallback)(()=>a.getState(F),[a,F]),B=(0,r.useCallback)(()=>s.getSourceState(F).runtime,[s,F]),q=(0,r.useSyncExternalStore)(a.subscribe,_,_),W=(0,r.useSyncExternalStore)(s.subscribe,B,B),U=(0,r.useCallback)(()=>s.getSourceState(F).syncStatus,[s,F]),H="ready"===(0,r.useSyncExternalStore)(s.subscribe,U,U),G=(z=s.nativeUi,E=(0,Q.G)(),A=(0,r.useCallback)(()=>z.getState(F),[z,F]),$=(0,r.useSyncExternalStore)(z.subscribe,A,A),T=(0,r.useCallback)(()=>a.getState(F),[a,F]),P=(0,r.useSyncExternalStore)(a.subscribe,T,T),(0,r.useEffect)(()=>{z.watch(F)},[z,F]),(0,r.useEffect)(()=>z.onNotice((e,t)=>{e.workId===F.workId&&e.sessionId===F.sessionId&&e.branchId===F.branchId&&E.show({level:t.level,title:t.message})}),[z,F,E]),(0,r.useEffect)(()=>{!$.prefill||!P.loaded||P.loading||P.outbox||P.text.length>0||(a.setText(F,$.prefill.text),z.edit(F,{prefill:null}))},[z,F,a,$.prefill,P.loaded,P.loading,P.outbox,P.text]),{state:$,canStop:H,setAnswer:(e,t)=>z.edit(F,{answers:{...z.getState(F).answers,[e]:t}}),setCollapsed:e=>z.edit(F,{collapsed:e}),answer:(e,t)=>{z.respond(F,{id:e,value:t})},refresh:()=>{z.refreshSource(F)},dismissError:()=>z.edit(F,{error:null}),dismissNotices:()=>z.edit(F,{notices:[]}),usePrefill:e=>{let t=z.getState(F).prefill;if(t){if("dismiss"!==e){let s=a.getState(F).text;a.setText(F,"replace"===e?t.text:`${s}${s?"\n":""}${t.text}`)}z.edit(F,{prefill:null})}},stop:()=>{a.interrupt(F).catch(e=>E.error(e instanceof Error?e.message:String(e)))}}),X=G.state.snapshot.requests.length>0,Z="basic"===W.extensionMode,es="basic"===W.presentationMode,en=(0,r.useRef)(null),er=(0,r.useRef)(null),ea=(0,r.useRef)(null),ei=(0,r.useRef)(null),el=function(e,t,s,n){let[a,i]=(0,r.useState)(!1);return(0,r.useLayoutEffect)(()=>{if(e)return;let r=t.current,a=r?.querySelector('[data-composer-tools="primary"]'),l=r?.querySelector('[data-composer-tools="metadata"]'),o=s.current;if(!r||!a||!l||!o)return;let d=0,c=null,u=()=>{if(null===c){let e=window.getComputedStyle(r);d=r.clientWidth-pc(e.paddingLeft)-pc(e.paddingRight);let t=pc(e.columnGap),s=pu(a),i=pu(l),u=pu(o),m=pc(window.getComputedStyle(a).columnGap),p=pc(window.getComputedStyle(l).columnGap),h=pc(window.getComputedStyle(o).columnGap),g=n.current,x=function(e){let t=[...new Set(e)],s=t.map(e=>({element:e,flex:e.style.flex,width:e.style.width,minWidth:e.style.minWidth}));try{for(let{element:e}of s)e.style.flex="0 0 auto",e.style.width="max-content",e.style.minWidth="max-content";return new Map(t.map(e=>[e,e.getBoundingClientRect().width]))}finally{for(let{element:e,flex:t,width:n,minWidth:r}of s)e.style.flex=t,e.style.width=n,e.style.minWidth=r}}([...s,...i,...u,...g?[g]:[]]),f=[pm(s,m,x),pm(i,p,x),g?x.get(g)??0:0,pm(u,h,x)].filter(e=>e>0);c=f.reduce((e,t)=>e+t,0)+Math.max(0,f.length-1)*t}i(c>d+1)},m=null,p=()=>{null===m&&(m=window.requestAnimationFrame(()=>{m=null,u()}))},h=()=>{c=null,p()},g=new ResizeObserver(([e])=>{e&&d!==e.contentRect.width&&(d=e.contentRect.width,p())}),x=new MutationObserver(h);return g.observe(r),x.observe(r,{childList:!0,characterData:!0,subtree:!0}),window.addEventListener("resize",h),document.fonts.addEventListener("loadingdone",h),u(),()=>{g.disconnect(),x.disconnect(),window.removeEventListener("resize",h),document.fonts.removeEventListener("loadingdone",h),null!==m&&window.cancelAnimationFrame(m)}},[t,e,n,s]),a}(u,er,ea,ei),[eo,ed]=(0,r.useState)(null),[ec,eu]=(0,r.useState)(null),em=(0,r.useCallback)(()=>{eu(null)},[]),[ep,eh]=(0,r.useState)(!1),[eg,ex]=(0,r.useState)(null),[ef,eb]=(0,r.useState)(!1),[ev,ew]=(0,r.useState)(!1),[ey,ek]=(0,r.useState)(!1),[ej,eN]=(0,r.useState)(null),[eI,eC]=(0,r.useState)(null),eS=JSON.stringify([F.workId,F.sessionId,F.branchId]),eM=(0,r.useMemo)(()=>Z?[]:L.flatMap(e=>e.contributions.flatMap(t=>"composer-panel"===t.kind?[{pluginName:e.pluginName,descriptor:t}]:[])),[L,Z]),ez=ec?eM.find(e=>e.pluginName===ec.pluginName&&e.descriptor.contributionName===ec.contributionName):void 0;(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{e&&(eu(e=>e&&e.sourceKey!==eS?null:e),ex(null))}),()=>{e=!1}},[eS]),(0,r.useEffect)(()=>{a.loadSource(F),a.loadModels(F)},[a,F]);let eE="main_running"===t.status,eA=eE||"background_running"===t.status,e$="completed"===t.status,eR=null!==eI,eT=eI?.text??q.text,eP=eI?.images??q.images,eD=0===eP.length&&eT.trim()===`/${pl.name}`,eO=eP.reduce((e,t)=>e+t.blob.size,0),eL=q.outbox&&!(eR&&"sending"===q.outbox.status)?q.outbox:null,eF=eE&&!eR,eB=W.queues,eq=q.images.reduce((e,t)=>e+t.blob.size,0),eW=q.images.some(e=>"optimizing"===e.status),eY=q.images.some(e=>"error"===e.status),eU=W.model,eV=eU?q.models.models.find(e=>e.provider===eU.provider&&e.modelId===eU.modelId):null,eK=q.images.length>0&&!eV?.input.includes("image"),eH=ep&&!ev,eG=H&&!X&&q.loaded&&!q.outbox&&(q.text.trim().length>0||q.images.length>0)&&q.images.length<=10&&!eW&&!eY&&eq<=0x1400000&&!eK,eJ=W.plugins["task-center"],eQ=W.contextUsage,eX=eV?.name||eU?.modelId||D("noModelSelected"),eZ=H?eU?`${eX} \xb7 ${D(pB[eU.thinkingLevel])}`:D("selectModel"):D("synchronizing"),e0=eU?D("modelTooltip",{model:eZ}):D("chooseModel"),e1=eo??q.error,e2=(0,r.useCallback)(async(e,t)=>{eh(!0),ed(null);try{await e(),t&&O.success(t)}catch(e){ed(e instanceof Error?e.message:D("operationFailed"))}finally{eh(!1)}},[D,O]),e5=(0,r.useCallback)(e=>{ed(null),x({source:F,capabilityMode:e}).catch(e=>{ed(e instanceof Error?e.message:D("modeChangeFailed"))})},[x,F,D]),e3=(0,r.useCallback)(async()=>{if(!ef&&"ready"===s.getSourceState(F).syncStatus){eb(!0);try{await e2(async()=>{await m({pluginName:"context-ignore",method:"ignore",scope:"session",source:F,input:{}})})}finally{eb(!1)}}},[s,ef,m,e2,F]),e4=(0,r.useCallback)(async()=>{if(!ev){ew(!0);try{await e2(()=>s.compact(F))}finally{ew(!1)}}},[s,ev,e2,F]),e6=(0,r.useCallback)(e=>{a.setText(F,`/${e.name} `)},[a,F]),e8=function({source:e,text:t,enabled:s,listPiCommands:n,onSelect:a}){let i=JSON.stringify([e.workId,e.sessionId,e.branchId]),[l,o]=(0,r.useState)(!1),[d,c]=(0,r.useState)(null),[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)({sourceKey:i,status:"idle",commands:[],error:null}),g=(0,r.useRef)(0),x=(0,r.useRef)(!0),f=s&&!l?/^\/[^\s/]*$/.test(t)?t.slice(1):null:null,b=null===f?null:`${i}\u0000${t}`,v=null!==b&&b!==d,{workId:w,sessionId:y,branchId:k}=e;(0,r.useEffect)(()=>(x.current=!0,()=>{x.current=!1,g.current+=1}),[]);let j=(0,r.useCallback)(async()=>{let e=++g.current;queueMicrotask(()=>{x.current&&g.current===e&&h(e=>e.sourceKey===i?{...e,status:"loading",error:null}:{sourceKey:i,status:"loading",commands:[],error:null})});try{let t=await n({source:{workId:w,sessionId:y,branchId:k}});if(!x.current||g.current!==e)return;h({sourceKey:i,status:"ready",commands:t.commands,error:null})}catch(t){if(!x.current||g.current!==e)return;throw console.warn("[Pi Desk][SlashCommand] 查询当前会话命令失败",{workId:w,sessionId:y,branchId:k,errorName:t instanceof Error?t.name:"UnknownError"}),h(e=>({sourceKey:i,status:"error",commands:e.sourceKey===i?e.commands:[],error:t instanceof Error?t.message:"查询命令失败"})),t}},[k,i,n,y,w]);(0,r.useEffect)(()=>{v&&j().catch(()=>void 0)},[v,j]);let N=(0,r.useMemo)(()=>[pl,...(p.sourceKey===i?p.commands:[]).filter(e=>e.name!==pl.name).map(e=>({key:`${e.source}:${e.name}`,name:e.name,description:e.description,source:e.source}))],[i,p.commands,p.sourceKey]),I=(0,r.useMemo)(()=>{let e;return e=(f??"").toLocaleLowerCase(),po.flatMap(t=>{let s=N.map((t,s)=>({command:t,order:s,score:function(e,t){if(!t)return 3;let s=e.name.toLocaleLowerCase(),n=e.description?.toLocaleLowerCase()??"";return s===t?0:s.startsWith(t)?1:s.includes(t)?2:n.includes(t)?4:1/0}(t,e)})).filter(e=>e.command.source===t.source&&Number.isFinite(e.score)).sort((t,s)=>t.score!==s.score?t.score-s.score:e?t.order-s.order:t.command.name.localeCompare(s.command.name)).map(e=>e.command);return s.length>0?[{...t,commands:s}]:[]})},[N,f]),C=(0,r.useMemo)(()=>I.flatMap(e=>e.commands),[I]),S=b&&u?.contextKey===b?C.findIndex(e=>e.key===u.commandKey):-1,M=S>=0?S:0,z=(0,r.useCallback)(e=>{if(!b||0===C.length)return;let t=(e+C.length)%C.length,s=C[t];s&&m({contextKey:b,commandKey:s.key})},[C,b]),E=(0,r.useCallback)(()=>{b&&c(b)},[b]),A=(0,r.useCallback)(()=>{b&&c(null)},[b]),$=(0,r.useCallback)(e=>{let t=C[e];t&&(b&&c(b),a(t))},[C,b,a]),R=(0,r.useCallback)(e=>!!v&&!e.nativeEvent.isComposing&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&("Escape"===e.key?(e.preventDefault(),E(),!0):0!==C.length&&("ArrowDown"===e.key?(e.preventDefault(),z(M+1),!0):"ArrowUp"===e.key?(e.preventDefault(),z(M-1),!0):("Enter"===e.key||"Tab"===e.key)&&(e.preventDefault(),$(M),!0))),[M,C.length,E,v,$,z]),T=(0,r.useCallback)(()=>{o(!0)},[]),P=(0,r.useCallback)(()=>{o(!1),c(null)},[]);return{open:v,loading:p.sourceKey===i&&"loading"===p.status,error:p.sourceKey===i&&"error"===p.status?p.error:null,groups:I,commands:C,activeIndex:M,dismiss:E,reopen:A,refresh:j,select:$,setActiveIndex:z,handleKeyDown:R,handleCompositionStart:T,handleCompositionEnd:P}}({source:F,text:eT,enabled:c&&H&&q.loaded&&!q.loading&&!eR,listPiCommands:p,onSelect:e6}),e7=e8.refresh,e9=(0,r.useCallback)(async e=>{if(!ey&&!ep){ek(!0);try{await e2(async()=>{await s.reload(F),await e7(),await a.loadModels(F,!0),e&&a.setText(F,"")})}finally{ek(!1)}}},[ep,s,a,e7,ey,e2,F]),te=(0,r.useCallback)(e=>{eR||0===e.length||(ed(null),a.addFiles(F,e))},[eR,a,F]),tt=(0,r.useCallback)(async e=>{if("ready"!==s.getSourceState(F).syncStatus)return;if(eD){if(!q.loaded||q.loading)return;await e9(!0);return}if(!eG||eH)return;let t=eE?null:{text:q.text,images:q.images};t&&eC(t),ed(null);try{await a.send(F,e)}catch(e){ed(e instanceof Error?e.message:D("sendFailed"))}finally{t&&eC(null)}},[eG,eH,s,a,q.images,q.loaded,q.loading,q.text,eD,eE,e9,F,D]);return(0,n.jsxs)("div",{className:"mx-auto w-full max-w-3xl px-2 pb-2 sm:px-4 sm:pb-3",children:[eL?(0,n.jsx)("div",{className:(0,C.cn)("mb-2 rounded-lg border px-3 py-2 text-xs","unknown"===eL.status?"border-amber-500/50 bg-amber-500/10 text-amber-900 dark:text-amber-200":"failed"===eL.status?"border-destructive/40 bg-destructive/5 text-destructive":"border-border bg-muted/50 text-muted-foreground"),children:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:"sending"===eL.status?D("confirmingSend"):"unknown"===eL.status?D("sendUnknown"):D("sendFailure",{error:eL.error??D("unknownError")})}),"sending"===eL.status?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:ep,onClick:()=>void e2(()=>a.restoreOutbox(F),D("outboxRestored")),children:[(0,n.jsx)(lP.A,{}),D("restoreDraft")]}),(0,n.jsxs)(N.$,{type:"button",variant:"ghost",size:"sm",disabled:ep,onClick:()=>void e2(()=>a.deleteOutbox(F),D("outboxDeleted")),children:[(0,n.jsx)(ee.A,{}),D("delete")]})]})]})}):null,q.notice||e1?(0,n.jsx)("div",{role:e1?"alert":"status",className:(0,C.cn)("mb-2 rounded-md px-2 py-1 text-sm",e1?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"),children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1",children:e1??q.notice}),q.loaded||q.loading||!q.error?q.loaded?(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{ed(null),a.dismissFeedback(F)},children:D("close",{ns:"common"})}):null:(0,n.jsxs)(N.$,{type:"button",variant:"outline",size:"sm",disabled:ep,onClick:()=>void e2(()=>a.loadSource(F)),children:[(0,n.jsx)(lP.A,{}),D("retryDraft")]})]})}):null,i({source:F,cwd:t.cwd,pluginState:eJ}),(0,n.jsx)(pF,{model:G}),(0,n.jsx)(p_,{snapshot:G.state.snapshot,placement:"aboveEditor"}),X?(0,n.jsx)("p",{className:"mb-1 px-1 text-xs text-muted-foreground",children:D("nativeUiComposer")}):null,(0,n.jsxs)("form",{"aria-label":eA?D("composerRunning"):e$?D("composerCompleted"):D("composer"),className:pR().inputFrame,"data-composer-mobile":u?"true":"false","data-composer-metadata-row":el?"true":"false",onSubmit:e=>{e.preventDefault(),tt("auto")},onDragOver:e=>{e.dataTransfer.types.includes("Files")&&e.preventDefault()},onDrop:e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),te([...e.dataTransfer.files]))},children:[(0,n.jsx)(pA,{open:e8.open,loading:e8.loading,error:e8.error,groups:e8.groups,activeIndex:e8.activeIndex,onActiveIndexChange:e8.setActiveIndex,onSelect:e8.select}),(0,n.jsx)("input",{ref:en,type:"file",accept:"image/jpeg,image/png,image/webp,image/gif,image/bmp",multiple:!0,className:"hidden",onChange:e=>{e.currentTarget.files&&te([...e.currentTarget.files]),e.currentTarget.value=""}}),(0,n.jsxs)(ny.MG,{className:"overflow-hidden rounded-xl border-border bg-card shadow-xs transition-[background-color,border-color] duration-150 ease-out has-disabled:bg-card has-disabled:opacity-100 dark:shadow-none motion-reduce:transition-none","aria-busy":eR,children:[eP.length>0?(0,n.jsxs)(ny.Sq,{align:"block-start",className:"pi-desk-chat-scrollbar gap-2 overflow-x-auto px-3 pt-3 pb-1",children:[eP.map(e=>(0,n.jsxs)("div",{className:"relative size-16 shrink-0 overflow-hidden rounded-md border bg-muted",title:`${e.name} \xb7 ${e.width}\xd7${e.height} \xb7 ${pq(e.blob.size)}`,children:[(0,n.jsx)("button",{type:"button",disabled:"ready"!==e.status,"aria-label":D("imagePreview",{name:e.name}),className:"group size-full cursor-zoom-in outline-none disabled:cursor-default focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",onClick:()=>{var t;let s,n;return t=e.localId,void(!((n=(s=eP.filter(e=>"ready"===e.status)).findIndex(e=>e.localId===t))<0)&&eN({index:n,slides:s.map(e=>({src:e.objectUrl,alt:e.name,width:e.width,height:e.height}))}))},children:(0,n.jsx)("img",{src:e.objectUrl,alt:e.name,className:"size-full object-cover transition-transform duration-200 group-hover:scale-105 motion-reduce:transition-none"})}),"optimizing"===e.status?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 grid place-items-center bg-background/85 text-xs",children:D("imageProcessing")}):null,"error"===e.status?(0,n.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 bg-popover px-1 py-0.5 text-xs text-destructive",children:D("imageFailed")}):null,(0,n.jsx)("button",{type:"button","aria-label":D("imageRemove",{name:e.name}),"aria-disabled":eR,className:"absolute right-0.5 top-0.5 z-10 grid size-6 cursor-pointer place-items-center rounded-md bg-popover text-popover-foreground shadow-sm hover:bg-accent",onClick:()=>{eR||a.removeImage(F,e.localId)},children:(0,n.jsx)(Y.A,{className:"size-3"})})]},e.localId)),(0,n.jsxs)("span",{className:"self-end whitespace-nowrap text-xs text-muted-foreground",children:[eP.length,"/10 \xb7 ",pq(eO)]})]}):null,(0,n.jsx)(ny.oR,{value:eT,disabled:!q.loaded||q.loading,readOnly:eR,"aria-disabled":eR,"aria-autocomplete":"list","aria-controls":e8.open?pi:void 0,"aria-expanded":e8.open,"aria-activedescendant":e8.open&&e8.commands.length>0?pd(e8.activeIndex):void 0,placeholder:q.loading?D("draftLoading"):!q.loaded&&q.error?D("draftFailed"):D("inputPlaceholder"),className:(0,C.cn)(pR().inputText,"pi-desk-chat-scrollbar max-h-48 min-h-9 overflow-y-auto px-3 pt-3 pb-1"),onChange:e=>a.setText(F,e.currentTarget.value),onClick:e8.reopen,onBlur:e8.dismiss,onCompositionStart:e8.handleCompositionStart,onCompositionEnd:e8.handleCompositionEnd,onKeyDown:e=>{e8.handleKeyDown(e)||"Enter"!==e.key||e.shiftKey||e.nativeEvent.isComposing||null===e.currentTarget.form||(e.preventDefault(),e.currentTarget.form.requestSubmit())},onPaste:e=>{let t=[...e.clipboardData?.items??[]].flatMap(e=>{if("file"!==e.kind)return[];let t=e.getAsFile();return t?[t]:[]});0!==t.length&&(e.preventDefault(),te(t))}}),(0,n.jsxs)(lH,{ref:er,className:pR().footer,children:[(0,n.jsxs)(lG,{"data-composer-tools":"primary",className:pR().primaryTools,children:[(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:(0,n.jsx)(lJ,{tooltip:D("more"),"aria-label":D("moreActions")}),children:(0,n.jsx)(V.A,{className:"size-4"})}),(0,n.jsxs)(K.SQ,{align:"start",side:"top",className:"w-52",children:[(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:D("session")}),(0,n.jsxs)(K._2,{"aria-label":D("switchBranch"),disabled:!H||!q.loaded||q.loading,onClick:()=>S(t.workId),children:[(0,n.jsx)(uo.A,{className:"size-4"}),D("sessionBranch"),(0,n.jsx)("span",{className:"ml-auto text-xs text-muted-foreground",children:D("escapeTwice")})]}),(0,n.jsxs)(K._2,{"aria-label":D("clone"),disabled:!H||j||k,title:0===t.messageCounts.total?D("cloneEmpty"):D("cloneTip"),onClick:I,children:[k?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(m6.A,{className:"size-4"}),k?D("cloning"):D("clone")]}),(0,n.jsxs)(K._2,{"aria-label":D("replaceSession"),"aria-busy":v,disabled:!H||w||v,onClick:y,children:[v?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(m8.A,{className:"size-4"}),v?D("replacing"):D("replaceSession")]})]}),(0,n.jsx)(K.mB,{}),(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:D("tools")}),l({source:F,cwd:t.cwd,pluginState:eJ}),(0,n.jsxs)(K._2,{"aria-label":D("toolsAndContext",{defaultValue:"工具与上下文"}),disabled:!H||X,onClick:()=>ex(eS),children:[(0,n.jsx)(nv.A,{className:"size-4"}),D("toolsAndContext",{defaultValue:"工具与上下文"})]}),(0,n.jsxs)(K._2,{"aria-label":D("reloadPi"),disabled:!q.loaded||q.loading||!H||eA||ep||ey,title:D("reloadPiTip"),onClick:()=>void e9(!1),children:[ey?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):(0,n.jsx)(et.A,{className:"size-4"}),ey?D("reloadingPi"):D("reloadPi")]}),es&&!Z?(0,n.jsxs)(K._2,{disabled:!H||ep||ey,onClick:()=>void e2(()=>s.setPresentation(F,"normal")),children:[(0,n.jsx)(nv.A,{className:"size-4"}),D("restorePluginPresentation")]}):null]}),eM.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(K.mB,{}),(0,n.jsxs)(K.I,{children:[(0,n.jsx)(K.lp,{children:D("plugins")}),eM.map(e=>(0,n.jsxs)(K._2,{onClick:()=>eu({pluginName:e.pluginName,contributionName:e.descriptor.contributionName,sourceKey:eS}),children:[(0,n.jsx)(e_,{icon:e.descriptor.icon,className:"size-4"}),(0,n.jsx)("span",{className:"truncate",children:e.descriptor.label})]},`${e.pluginName}:${e.descriptor.contributionName}`))]})]}):null]})]}),(0,n.jsx)(lJ,{tooltip:D("addImage"),"aria-label":D("addImage"),disabled:q.images.length>=10,"aria-disabled":eR||q.images.length>=10,onClick:()=>{eR||en.current?.click()},children:(0,n.jsx)(m7.A,{className:"size-4"})}),eQ&&eV?.contextWindow!==null?(0,n.jsx)(pb,{sessionId:t.sessionId,cwd:t.cwd,tokens:eQ.tokens,contextWindow:eQ.contextWindow,contextIgnorePlugin:W.plugins["context-ignore"],ignoreDisabled:!H||eE||ep,ignorePending:ef,compactDisabled:!H||eE||ep,compactPending:ev,onIgnoreContext:e3,onCompactContext:e4}):eV?.contextWindow===null?(0,n.jsx)("span",{className:"px-1 text-xs text-muted-foreground",children:D("modelContextUnknown",{defaultValue:"上下文未知"})}):null]}),(0,n.jsxs)(lG,{"data-composer-tools":"metadata",className:pR().metadataTools,children:[(0,n.jsx)(pa,{workSession:t,runtime:d,active:c,chatReady:H,onOpen:M}),(0,n.jsx)(pT,{modes:g,value:W.capabilityMode,disabled:!H,onChange:e5}),(0,n.jsx)(pC,{source:F,runtime:a,catalog:q.models,current:eU,label:eZ,title:e0,disabled:!H||eA||eR||ep,triggerClassName:pR().modelTrigger,detailsClassName:pR().modelTriggerDetails,onOpenSettings:e},eS)]}),eE&&eR?(0,n.jsx)("span",{ref:ei,className:"min-w-0 truncate px-2 text-xs text-muted-foreground",children:D("preparingContext")}):null,(0,n.jsxs)("div",{ref:ea,className:pR().submitTools,children:[(0,n.jsx)(pz,{queues:eB,disabled:!H||ep,onRestore:()=>void e2(()=>a.restoreQueue(F),D("queuesRestored"))}),eF?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(lJ,{tooltip:D("steerNow"),"aria-label":D("steerNow"),variant:"secondary",disabled:!eG||eH,onClick:()=>void tt("auto"),children:(0,n.jsx)(R.A,{className:"size-3.5"})}),(0,n.jsx)(lJ,{tooltip:D("sendFollowUp"),"aria-label":D("sendFollowUp"),variant:"outline",disabled:!eG||eH,onClick:()=>void tt("follow_up"),children:(0,n.jsx)(m9.A,{className:"size-3.5"})}),(0,n.jsx)(lJ,{tooltip:D("stopResponse"),"aria-label":D("stopResponse"),variant:"destructive",disabled:!H||ep,onClick:()=>void e2(()=>a.interrupt(F)),children:(0,n.jsx)(pe.A,{className:"size-3.5 fill-current"})})]}):(0,n.jsx)(N.$,{type:eR?"button":"submit",size:"icon",disabled:!eR&&(!eG||eH),"aria-disabled":eR||!eG||eH,"aria-busy":eR,"aria-label":eR?D("sending"):H?D("send"):D("synchronizing"),children:eR?(0,n.jsx)(pt.A,{className:"size-4"}):H?(0,n.jsx)(ps.A,{}):(0,n.jsx)(b.A,{className:"size-4 animate-spin"})})]})]})]})]}),(0,n.jsx)(p_,{snapshot:G.state.snapshot,placement:"belowEditor"}),ec&&ec.sourceKey===eS&&ez?o({pluginName:ec.pluginName,descriptor:ez.descriptor,source:F,onClose:em}):null,eg===eS&&H?(0,n.jsx)(pN,{open:!0,source:F,runtime:a,getContext:h,listCommands:p,nativeUi:G,nativeBiz:s.nativeUi,commandsDisabled:eA||eR||ep,onOpenChange:e=>ex(e?eS:null),onOpenSettings:e},eS):null,ej?(0,n.jsx)(ng.k,{mode:"modal",open:!0,slides:ej.slides,index:ej.index,ariaLabel:D("imagePreviewPending"),onClose:()=>eN(null),onIndexChange:e=>eN(t=>t?{...t,index:e}:t)}):null,q.images.length>10?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:D("tooManyImages")}):eK?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:D("imageUnsupported")}):eq>0x1400000?(0,n.jsx)("p",{className:"mt-1 px-1 text-sm text-destructive",children:D("imagesTooLarge")}):null]})});pW.displayName="L2WorkbenchChatComposer";var pY=s(61600);function pU({svgRef:e}){let t=(0,r.useId)(),s=`${t}-head`,a=`${t}-fur`;return(0,n.jsxs)("svg",{ref:e,viewBox:"0 0 640 560",fill:"none","aria-hidden":"true",className:"pointer-events-none absolute left-1/2 top-1/2 max-w-none -translate-x-1/2 -translate-y-1/2 overflow-visible",style:{width:"144.8%",height:"168.93%"},children:[(0,n.jsxs)("g",{"data-part":"busy-dots",opacity:"0",fill:"currentColor",children:[(0,n.jsx)("circle",{cx:"294",cy:"481",r:"5.5"}),(0,n.jsx)("circle",{cx:"320",cy:"481",r:"5.5"}),(0,n.jsx)("circle",{cx:"346",cy:"481",r:"5.5"})]}),(0,n.jsx)("g",{"data-part":"head",children:(0,n.jsxs)("g",{transform:"translate(64 20)",children:[(0,n.jsxs)("defs",{children:[(0,n.jsx)("path",{id:s,d:"M256 88C190 88 132 109 90 161C62 153 35 171 35 198C35 217 45 231 61 240L54 277C47 316 64 353 104 379C144 406 195 419 256 419C317 419 368 406 408 379C448 353 465 316 458 277L451 240C467 231 477 217 477 198C477 171 450 153 422 161C380 109 322 88 256 88Z"}),(0,n.jsxs)("mask",{id:a,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"512",height:"512",children:[(0,n.jsx)("rect",{width:"512",height:"512",fill:"white"}),(0,n.jsx)("path",{fill:"black",d:"M170 272C201 253 229 240 256 240C283 240 311 253 342 272C383 255 425 261 444 288C472 327 443 369 406 389C367 430 315 448 256 448C197 448 145 430 106 389C69 369 40 327 68 288C87 261 129 255 170 272Z"})]})]}),(0,n.jsx)("use",{href:`#${s}`,fill:"#F3E2C6"}),(0,n.jsx)("use",{href:`#${s}`,fill:"#B87945",mask:`url(#${a})`}),(0,n.jsxs)("g",{fill:"#303030",children:[(0,n.jsx)("path",{d:"M76 180C62 177 53 186 53 198C53 207 57 215 64 220L76 180Z"}),(0,n.jsx)("path",{d:"M436 180C450 177 459 186 459 198C459 207 455 215 448 220L436 180Z"})]}),(0,n.jsxs)("g",{"data-part":"face",children:[["left","right"].map((e,t)=>(0,n.jsxs)("g",{"data-part":`${e}-eye`,transform:`translate(${0===t?158:354} 239)`,children:[(0,n.jsx)("path",{"data-part":`${e}-eye-shape`,fill:"#303030",d:"M-26 0a26 28 0 1 0 52 0a26 28 0 1 0-52 0"}),(0,n.jsx)("circle",{"data-part":`${e}-eye-shine`,cx:"8",cy:"-11",r:"6.5",fill:"#fff"})]},e)),(0,n.jsxs)("g",{"data-part":"cheeks",fill:"#D69973",opacity:"0",children:[(0,n.jsx)("ellipse",{cx:"133",cy:"316",rx:"26",ry:"13"}),(0,n.jsx)("ellipse",{cx:"379",cy:"316",rx:"26",ry:"13"})]}),(0,n.jsx)("path",{fill:"#303030",d:"M219 269C219 254 240 254 256 254C272 254 293 254 293 269C293 282 276 299 256 303C236 299 219 282 219 269Z"}),(0,n.jsxs)("g",{"data-part":"smile",stroke:"#303030",strokeLinecap:"round",strokeWidth:"10",children:[(0,n.jsx)("path",{d:"M256 300C256 317 246 327 232 327C220 327 211 322 207 314"}),(0,n.jsx)("path",{d:"M256 300C256 317 266 327 280 327C292 327 301 322 305 314"})]}),(0,n.jsxs)("g",{"data-part":"mouth",opacity:"0",children:[(0,n.jsx)("ellipse",{cx:"256",cy:"333",rx:"16",ry:"22",fill:"#303030"}),(0,n.jsx)("ellipse",{cx:"256",cy:"347",rx:"9",ry:"5",fill:"#D69973"})]}),(0,n.jsx)("g",{stroke:"#303030",strokeLinecap:"round",strokeWidth:"9",children:(0,n.jsx)("path",{d:"M101 298C116 293 132 292 146 292M110 327C123 318 135 312 148 310M411 298C396 293 380 292 366 292M402 327C389 318 377 312 364 310"})})]})]})}),(0,n.jsxs)("g",{"data-part":"thoughts",fill:"currentColor",opacity:"0",children:[(0,n.jsx)("circle",{cx:"504",cy:"132",r:"5"}),(0,n.jsx)("circle",{cx:"524",cy:"102",r:"8"}),(0,n.jsx)("circle",{cx:"544",cy:"65",r:"11"})]}),(0,n.jsx)("g",{"data-part":"surprise",stroke:"currentColor",strokeWidth:"7",strokeLinecap:"round",opacity:"0",children:(0,n.jsx)("path",{d:"M465 91L479 66M498 113L521 100M443 69L446 44"})}),(0,n.jsxs)("g",{"data-part":"sleep",fill:"currentColor",fontFamily:"Arial,sans-serif",fontWeight:"600",opacity:"0",children:[(0,n.jsx)("text",{x:"479",y:"137",fontSize:"24",children:"z"}),(0,n.jsx)("text",{x:"522",y:"92",fontSize:"32",children:"z"})]}),(0,n.jsxs)("g",{"data-part":"sparkles",opacity:"0",fill:"#BE8656",children:[(0,n.jsx)("path",{d:"M93 158Q96 177 111 180Q96 184 93 202Q90 184 75 180Q90 177 93 158Z"}),(0,n.jsx)("path",{d:"M545 126Q550 151 570 155Q550 159 545 184Q540 159 521 155Q540 151 545 126Z"}),(0,n.jsx)("circle",{cx:"513",cy:"76",r:"5"})]})]})}let pV={x:0,y:0,angle:0,sx:1,sy:1,gazeX:0,gazeY:0,eye:1,wink:0,smile:0,sleepy:0,mouth:0,blush:0,thought:0,surprise:0,sleep:0,sparkle:0,busy:0,follow:1},pK=Object.keys(pV),pH={idle:.46,hello:.36,point:.45,think:.5,busy:.4,happy:.35,surprise:.2,sleep:.72};function pG(e){return Math.min(1,Math.max(0,e))}function pJ(e){let t=pG(e);return t*t*t*(t*(6*t-15)+10)}function pQ(e,t){let s={...pV};switch(e){case"hello":{let e=t%3.5,n=Math.exp(-Math.pow((e-.7)/.35,2));s.y=6*n,s.angle=-3+3*n,s.wink=.94*Math.exp(-Math.pow((e-1.2)/.23,2)),s.sx=1+.012*Math.sin(3.2*t),s.sy=1-.014*Math.sin(3.2*t),s.blush=.23;break}case"point":s.x=-9,s.y=-5,s.angle=-9,s.gazeX=-17,s.gazeY=-16,s.sx=1.018,s.sy=.987,s.follow=0;break;case"think":s.angle=8+2*Math.sin(1.6*t),s.gazeX=12+5*Math.sin(1.8*t),s.gazeY=-13,s.eye=.85,s.thought=1,s.follow=.1;break;case"busy":{let e=t%3.6,n=pJ(e/1.45),r=pJ((e-2.15)/.65),a=Math.exp(-Math.pow((e-1.9)/.22,2));s.gazeX=-11+22*n-22*r,s.gazeY=8+2*a,s.angle=.1*s.gazeX,s.y=3+4*a,s.eye=.9+.05*a,s.sy=1-.006*a,s.busy=1,s.follow=0;break}case"happy":{let e=(1-Math.cos(5.5*t))/2;s.y=-(14*e),s.sx=1.025-.035*e,s.sy=.975+.045*e,s.angle=4*Math.sin(2.5*t),s.smile=1,s.blush=.6,s.sparkle=1,s.follow=.15;break}case"surprise":s.y=-9-6*Math.exp(-(1.5*t)),s.eye=1.2,s.mouth=1,s.sx=.96,s.sy=1.045,s.surprise=1,s.follow=.25;break;case"sleep":s.angle=11+2*Math.sin(1.25*t),s.y=6+3*Math.sin(1.25*t),s.sy=.965+.01*Math.sin(1.25*t),s.sleepy=1,s.sleep=1,s.follow=0;break;default:s.gazeX=4*Math.sin(.8*t),s.gazeY=2*Math.sin(.67*t)}return s}class pX{setState(e,t){if(e===this.state)return;let s=this.transition&&t-this.transition.at<pH[this.state];this.transition=s?{pose:this.sample(t),at:t}:{state:this.state,started:this.started,at:t},this.state=e,this.started=t}sample(e,t=!1){let s=pQ(this.state,t?1.2:Math.max(0,e-this.started));if(!this.transition||t)return s;let n=pG((e-this.transition.at)/pH[this.state]);if(1===n)return s;let r="pose"in this.transition?this.transition.pose:pQ(this.transition.state,Math.max(0,e-this.transition.started)),a=1-(1-n)**5;for(let e of pK)s[e]=r[e]+(s[e]-r[e])*a;return s}constructor(){this.state="idle",this.started=0,this.transition=null}}let pZ=["head","face","left-eye","right-eye","left-eye-shape","right-eye-shape","left-eye-shine","right-eye-shine","smile","mouth","cheeks","thoughts","surprise","sleep","sparkles","busy-dots"];function p0(e,t=0,s=1){return Math.min(s,Math.max(t,e))}function p1(e){return e.toFixed(3)}function p2({state:e,active:t=!0,size:s=100,className:a}){let i=(0,r.useRef)(null),l=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e=function(e){let t=Object.fromEntries(pZ.map(t=>[t,e.querySelector(`[data-part="${t}"]`)])),s=e.parentElement,n=new pX,r=matchMedia("(prefers-reduced-motion: reduce)"),a=!0,i=!1,l=0,o=null,d=0,c=-10,u=1.7,m={x:0,y:0},p={x:0,y:0};function h(e,s){t[e].setAttribute("opacity",p1(s))}function g(e,s){t[e].setAttribute("transform",s)}function x(){let e=n.sample(d,r.matches),s=r.matches?1.2:d,a=r.matches?0:.005*Math.sin(1.7*d),i=e.gazeX+(r.matches?0:m.x*e.follow),l=e.gazeY+(r.matches?0:m.y*e.follow);g("head",`translate(${p1(e.x)} ${p1(e.y)}) translate(320 274) rotate(${p1(e.angle+(r.matches?0:m.x*e.follow*.12))}) scale(${p1(e.sx)} ${p1(e.sy+a)}) translate(-320 -274)`),g("face",`translate(${p1(.16*i)} ${p1(.12*l)})`);let o=r.matches?-1:(d-c)/.19,u=o>=0&&o<=1?.07+.93*Math.abs(2*o-1):1;for(let[s,n]of[["left",158],["right",354]]){g(`${s}-eye`,`translate(${p1(n+i)} ${p1(239+l)})`);let r=1-p0(e.smile+e.sleepy),a=(3.5+(28*e.eye-3.5)*r)*u*("left"===s?1-e.wink:1);t[`${s}-eye-shape`].setAttribute("d",function(e,t,s){let n=p1(e),r=p1(t+s),a=p1(-t+s),i=p1(.5523*e),l=p1(-(.5523*t)+s),o=p1(.5523*t+s);return`M-${n} 0C-${n} ${l} -${i} ${a} 0 ${a}C${i} ${a} ${n} ${l} ${n} 0C${n} ${o} ${i} ${r} 0 ${r}C-${i} ${r} -${n} ${o} -${n} 0Z`}(22+4*r,a,(-13*e.smile+8*e.sleepy)*u)),h(`${s}-eye-shine`,r*p0((a-8)/16))}h("smile",1-e.mouth),h("mouth",e.mouth),h("cheeks",e.blush),h("thoughts",e.thought),Array.from(t.thoughts.children).forEach((e,t)=>{e.setAttribute("opacity",p1(.25+.75*(1+Math.sin(2.8*s-.9*t))/2)),e.setAttribute("transform",`translate(0 ${p1(3*Math.sin(2*s-t))})`)}),h("surprise",e.surprise),h("sleep",e.sleep),Array.from(t.sleep.children).forEach((e,t)=>{let n=(.4*s+.45*t)%1;e.setAttribute("transform",`translate(${p1(8*n)} ${p1(-(20*n))})`),e.setAttribute("opacity",p1(Math.sin(n*Math.PI)))}),h("sparkles",e.sparkle*(.55+.45*(1+Math.sin(3*s))/2)),g("sparkles",`translate(0 ${p1(5*Math.sin(2*s))})`),h("busy-dots",e.busy),Array.from(t["busy-dots"].children).forEach((e,t)=>{let n=Math.sin(Math.PI*p0(((s-.18*t)%1.4+1.4)%1.4/.55));e.setAttribute("opacity",p1(.26+.65*n)),e.setAttribute("transform",`translate(0 ${p1(-4*n)})`)})}function f(){return a&&i&&!document.hidden&&!r.matches}function b(e){if(l=0,!f())return;let t=null===o?0:Math.min((e-o)/1e3,.05);o=e,(d+=t)>=u&&(c=d,u=d+2.4+2.8*Math.random());let s=1-Math.exp(-(9*t));m.x+=(p.x-m.x)*s,m.y+=(p.y-m.y)*s,x(),l=requestAnimationFrame(b)}function v(){cancelAnimationFrame(l),l=0,o=null,x(),f()&&(l=requestAnimationFrame(b))}function w(e){if("mouse"!==e.pointerType||!f())return;let t=s.getBoundingClientRect();p.x=p0((e.clientX-t.left-t.width/2)/Math.max(t.width,window.innerWidth/2)*24,-18,18),p.y=p0((e.clientY-t.top-t.height/2)/Math.max(t.height,window.innerHeight/2)*20,-14,12)}function y(){p.x=0,p.y=0}let k=new IntersectionObserver(([e])=>{i=e.isIntersecting,v()});return k.observe(s),document.addEventListener("visibilitychange",v),r.addEventListener("change",v),document.addEventListener("pointermove",w,{passive:!0}),document.documentElement.addEventListener("pointerleave",y),window.addEventListener("blur",y),x(),{setState(e){n.setState(e,d),"point"!==e&&"think"!==e||r.matches||(c=d),x()},setActive(e){a=e,v()},dispose(){cancelAnimationFrame(l),k.disconnect(),document.removeEventListener("visibilitychange",v),r.removeEventListener("change",v),document.removeEventListener("pointermove",w),document.documentElement.removeEventListener("pointerleave",y),window.removeEventListener("blur",y)}}}(i.current);return l.current=e,()=>{e.dispose(),l.current=null}},[]),(0,r.useEffect)(()=>{l.current?.setState(e)},[e]),(0,r.useEffect)(()=>{l.current?.setActive(t)},[t]),(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("relative block shrink-0 text-muted-foreground",a),style:{width:s,height:.75*s},children:(0,n.jsx)(pU,{svgRef:i})})}let p5=Object.keys(cU.R.en).filter(e=>e.startsWith("emptyQuip")),p3=null;function p4(){let{t:e}=(0,f.Bd)("workbench"),t=(0,mJ.tF)(),s=!0===(0,pY.D)(),a=(0,mQ.I)(),{state:i,textKey:l}=function(e){let[t,s]=(0,r.useState)(null),[n,a]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{let e=requestAnimationFrame(()=>{let e,t;return s((e=Math.floor(Math.random()*(null===p3?p5.length:p5.length-1)),null!==p3&&e>=p3&&(e+=1),p3=e,"emptyQuip16"===(t=p5[e])||"emptyQuip10"===t?{quip:t,waiting:"sleep",reaction:"surprise",recover:"hello",reply:"emptyWakeReply"}:"emptyQuip1"===t||"emptyQuip14"===t?{quip:t,waiting:"sleep",reaction:"hello",recover:"idle",reply:"emptyFishReply"}:"emptyQuip12"===t||"emptyQuip15"===t?{quip:t,waiting:"think",reaction:"surprise",recover:"idle",reply:"emptyCuriousReply"}:{quip:t,waiting:"idle",reaction:"happy",recover:"hello",reply:"emptyPartnerReply"}))});return()=>cancelAnimationFrame(e)},[]),(0,r.useEffect)(()=>{let t=window.setTimeout(()=>a(!e),320*!e);return()=>window.clearTimeout(t)},[e]),{state:t?e?t.waiting:n?t.recover:t.reaction:"sleep",textKey:t?e?t.quip:t.reply:null}}(t);return t||s&&!a?(0,n.jsxs)(o8.PY1.div,{"data-testid":"workbench-empty-session","data-otter-state":i,"data-leaving":t?void 0:"true",initial:!1,animate:{opacity:1,y:0},exit:{opacity:0,y:-4,transition:{delay:.55,duration:1.15,ease:"easeInOut"}},className:"flex max-w-sm flex-col items-center gap-5",children:[(0,n.jsx)(p2,{state:i,size:100}),(0,n.jsx)("p",{className:"min-h-6 text-sm leading-6 text-muted-foreground",children:l?e(l):null})]}):null}function p6({active:e,ready:t,empty:s,hasUserMessage:r}){return(0,n.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center px-6 py-8 text-center",children:[(0,n.jsx)(mG.N,{initial:!1,custom:e&&t&&r,children:e&&t&&s?(0,n.jsx)(p4,{},"welcome"):null}),e&&!t&&s?(0,n.jsx)(mV,{variant:"loading"}):null]})}function p8({active:e,turns:t,window:s}){return e?(0,n.jsx)(oA,{turns:t,window:s}):null}function p7(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function p9(){return"visible"===document.visibilityState}function he(){return!0}function ht(e,t){e.scrollTop=t.scrollTop}function hs(e){let t=e.getBoundingClientRect().top,s=null;for(let n of e.querySelectorAll("[data-chat-scroll-anchor]")){let e=n.dataset.chatScrollAnchor;if(!e)continue;let r=n.getBoundingClientRect().top-t,a=Math.abs(r);(!s||a<s.distance)&&(s={messageId:e,offset:r,distance:a})}return s?{messageId:s.messageId,offset:s.offset}:null}function hn({active:e,visible:t=!0,running:s,ready:n,containsTail:a,latestUserAnchor:i,entrySnapshot:l,onResetToTail:o,onSaveSnapshot:d,onClearSnapshot:c}){let{isAtBottom:u,scrollRef:m,scrollToBottom:p,state:h,stopScroll:g}=(0,lO.B)(),x=(0,r.useSyncExternalStore)(p7,p9,he),f=(0,r.useRef)(x),b=(0,r.useRef)(!1),v=(0,r.useRef)(!1),w=(0,r.useRef)(null),y=(0,r.useRef)(null),k=(0,r.useRef)(s?l:null),j=(0,r.useRef)(null);return(0,r.useLayoutEffect)(()=>{let e=m.current;if(!e||!t||!u)return;let s=e.style.overflowAnchor;return e.style.overflowAnchor="none",oc("viewport:anchor-lock",e),()=>{e.style.overflowAnchor=s}},[u,m,t]),(0,r.useLayoutEffect)(()=>{let n=m.current;if(!n)return;if(!e&&!s){v.current=!1,k.current=null,y.current=null,j.current=null,g(),oc("viewport:leave-ended",n);return}if(!t){y.current=null,v.current&&null===j.current&&(j.current=!e&&a&&h.isAtBottom?"follow":{snapshot:hs(n),scrollTop:n.scrollTop},oc("viewport:suspend",n,{follow:"follow"===j.current})),g();return}let r=j.current;if(null!==r){if("follow"===r)c(),n.scrollTop=Math.max(0,n.scrollHeight-n.clientHeight),ht(h,n),p({animation:"instant"}),oc("viewport:restore-follow",n);else{g();let{snapshot:e}=r,t=e?ou(n,"data-chat-scroll-anchor",e.messageId):null;e&&t?ob(n,t,e.offset,a):n.scrollTop=r.scrollTop,ht(h,n),oc("viewport:restore-reading",n,{running:s,snapshot:e})}v.current=!0,w.current=i,j.current=null}},[e,a,i,c,s,m,p,h,g,t]),(0,r.useLayoutEffect)(()=>{let e=x&&!f.current;if(f.current=x,e&&t&&!s&&(v.current=!1,k.current=null,y.current=null),!n||!t||!x)return;s||c();let r=!v.current,l=null!==i&&i!==w.current,d=l?null:y.current;if(!r&&!l&&!d)return;if(r&&!s&&!a)return void o();let u=m.current;l&&(y.current=null,c(),u&&ox(u));let j=null,N=null,I=null;b.current=!0;let C=()=>{let e=m.current;if(!e){b.current=!1;return}oc("viewport:initialize:start",e,{initializing:r,running:s,containsTail:a,latestUserAnchor:i});let t=null,n=12,l=d?d.anchor:r&&s?k.current:null;if(l){let s=ou(e,"data-chat-scroll-anchor",l.messageId);s&&(t=s,n=l.offset)}!t&&i&&(t=ou(e,"data-chat-scroll-anchor",i)),t??=ou(e,"data-chat-user-message",void 0);let o=d?.follow??(null!==t&&null===l&&(s||!r)),c=d?.follow??(r&&s&&null===l),u=t,x=()=>{g(),u?ob(e,u,n,a):ox(e),(c||!u)&&(e.scrollTop=Math.max(0,e.scrollHeight-e.clientHeight)),ht(h,e),(o||!u)&&p({animation:"instant"})};if(x(),oc("viewport:initialize:positioned",e,{initializing:r,running:s,target:t?.dataset.chatScrollAnchor??null,followAfterPosition:o,enterRunningAtBottom:c}),v.current=!0,w.current=i,k.current=null,r||d){let s=t?.dataset.chatScrollAnchor;y.current={anchor:s?{messageId:s,offset:n}:null,follow:o||null===t};let r=new ResizeObserver(x);r.observe(e),e.firstElementChild&&r.observe(e.firstElementChild);let a=e.parentElement,i=["wheel","touchstart","pointerdown","keydown","click"],l=e=>{for(let e of(r.disconnect(),i))a.removeEventListener(e,l,!0);e&&(y.current=null),I=null,b.current=!1};for(let e of i)a.addEventListener(e,l,{passive:!0,capture:!0});I=l}N=window.requestAnimationFrame(()=>{b.current=null!==I})};return m.current?C():j=window.requestAnimationFrame(C),()=>{null!==j&&window.cancelAnimationFrame(j),null!==N&&window.cancelAnimationFrame(N),I?.(),b.current=!1}},[a,i,c,o,x,n,s,m,p,h,g,t]),(0,r.useEffect)(()=>{let e=m.current;if(!e||!t)return;let s=()=>{if(oc("viewport:scroll",e,{positioning:b.current,isAtBottom:h.isAtBottom,escapedFromLock:h.escapedFromLock,resizeDifference:h.resizeDifference}),b.current||h.isAtBottom)return;let t=e.querySelector("[data-chat-tail-space]");!t||t.dataset.chatTailAnchor!==i||e.scrollHeight-e.scrollTop-e.clientHeight<=2&&(oc("viewport:resume-follow",e,{isAtBottom:h.isAtBottom,escapedFromLock:h.escapedFromLock}),p({animation:"instant"}))};return e.addEventListener("scroll",s,{passive:!0}),()=>e.removeEventListener("scroll",s)},[i,m,p,h,t]),(0,r.useLayoutEffect)(()=>{if(!s||!t)return;let e=m.current;if(!e)return;let n=()=>{if(b.current)return;if(a&&h.isAtBottom)return void c();let t=hs(e);t?d(t):c()};return e.addEventListener("scroll",n,{passive:!0}),()=>{e.removeEventListener("scroll",n),n()}},[a,c,d,s,m,h,t]),null}let hr=(0,r.memo)(function({active:e,visible:t,workSession:s,chatRuntime:a,inputRuntime:i,onPreviewFile:l}){let{t:o}=(0,f.Bd)("workbench"),d=(0,r.useMemo)(()=>uz.Pi.parse({workId:s.workId,sessionId:s.sessionId,branchId:s.branchId}),[s.branchId,s.sessionId,s.workId]),c=(0,r.useMemo)(()=>a.getViewportSnapshot(d),[a,d]),u=(0,r.useCallback)(()=>a.getSourceState(d),[a,d]),m=(0,r.useSyncExternalStore)(a.subscribe,u,u),p="main_running"===s.status||"background_running"===s.status,h=(0,r.useMemo)(()=>oi({messages:m.messages,temporaryMessages:m.temporaryMessages},p),[p,m.messages,m.temporaryMessages]),g=m.messages.length>0||m.temporaryMessages.length>0,x=m.messages.some(e=>"user"===e.fixed.type)||m.temporaryMessages.some(e=>"user"===e.fixed.type),b=p||m.temporaryMessages.length>0,v=h.findLast(e=>null!==e.user)??null,w=v?.user??null,y=w?`${w.identity}:user`:null,k=(0,r.useCallback)(async e=>e.durable?void 0!==e.detail?e.detail:a.loadMessageDetail(d,e.durable.location.index,e.durable.location.entryId):null,[a,d]),j=(0,r.useCallback)((e,t)=>i.acquireMessageImage({source:d,tempId:e.tempId,entryId:e.durable?.location.entryId??null,imageIndex:t}),[i,d]),N=(0,r.useCallback)(e=>l(d,e),[l,d]),I=(0,r.useCallback)(e=>{a.saveViewportSnapshot(d,e)},[a,d]),C=(0,r.useCallback)(()=>{a.clearViewportSnapshot(d)},[a,d]),S=(0,r.useCallback)(()=>a.setPresentation(d,"basic"),[a,d]);return(0,n.jsx)(oR,{basic:"basic"===m.runtime.presentationMode,onRecover:S,children:(0,n.jsxs)(lL,{className:"min-h-0",initial:!1,resize:"instant","aria-label":o("chatMessages",{name:s.sessionTitle??s.projectName}),children:[(0,n.jsx)(oC,{turns:h,active:t,focusTurnIdentity:v?.identity??null,initialAnchor:b?c?.messageId??null:null,children:r=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(dy,{children:(0,n.jsx)(lF,{scrollClassName:"pi-desk-chat-scrollbar pi-desk-chat-conversation-scroll overflow-auto",className:"mx-auto min-h-full w-full max-w-3xl gap-6 px-3 pt-3 pb-4 sm:px-5",children:r.visibleTurns.map((e,t)=>{let a=r.startIndex+t;return(0,n.jsx)(d7,{turn:e,cwd:s.cwd,logicalTail:r.containsTail&&a===h.length-1,onLoadDetail:k,onAcquireImage:j,onPreviewFile:N},e.identity)})})}),(0,n.jsx)(hn,{active:e,visible:t,running:b,ready:g,containsTail:r.containsTail,latestUserAnchor:y,entrySnapshot:c,onResetToTail:r.resetToTail,onSaveSnapshot:I,onClearSnapshot:C},`viewport:${d.sessionId}:${d.branchId}`),(0,n.jsx)(ov,{active:t}),(0,n.jsx)(p8,{active:t,turns:h,window:r},`navigation:${d.sessionId}:${d.branchId}`)]})},`window:${d.sessionId}:${d.branchId}`),(0,n.jsx)(p6,{active:t,ready:"ready"===m.syncStatus,empty:!g,hasUserMessage:x})]})})});function ha({error:e,copied:t,reloading:s,canReload:r,onCopy:a,onReload:i}){let{t:l}=(0,f.Bd)("workbench");return(0,n.jsxs)(eJ.AM,{children:[(0,n.jsx)(eJ.Wv,{openOnHover:!0,delay:150,closeDelay:150,render:(0,n.jsx)(N.$,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive"}),children:l("initializationDegraded")}),(0,n.jsxs)(eJ.hl,{align:"end",alignOffset:8,className:"max-h-[min(28rem,var(--available-height))] w-[28rem] gap-0 overflow-hidden p-0",initialFocus:e=>"keyboard"===e,children:[(0,n.jsx)(eJ.eO,{className:"shrink-0 border-b px-3 py-2",children:l("initializationDetails")}),(0,n.jsx)("pre",{className:"min-h-0 overflow-auto overscroll-contain whitespace-pre-wrap break-words p-3 font-mono text-sm leading-[1.6]","aria-label":l("initializationDetails"),children:e}),(0,n.jsxs)("div",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t px-3 py-2",children:[(0,n.jsxs)(N.$,{variant:"outline",size:"sm",onClick:a,children:[t?(0,n.jsx)(em.A,{}):(0,n.jsx)(Z.A,{}),l(t?"copied":"copyInitializationError")]}),(0,n.jsxs)(N.$,{size:"sm",disabled:!r,onClick:i,children:[s?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(et.A,{}),l(s?"reloadingPi":"reloadPi")]})]})]})]})}hr.displayName="L2WorkbenchChatView";var hi=s(4780),hl=s.n(hi);function ho({sidebarOpen:e,onOpen:t}){let{t:s}=(0,f.Bd)("workbench"),r=(0,mQ.I)();return(0,n.jsxs)("div",{"data-testid":"workbench-session-guide",className:hl().guide,children:[(0,n.jsx)(p2,{state:e?"idle":"point",size:120,className:hl().otter}),e?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{"data-testid":"workbench-session-guide-arrow","aria-hidden":"true",viewBox:"0 0 36 32",className:hl().arrow,fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)(o8.PY1.path,{d:"M30 26Q10 25 9 10",initial:!r&&{pathLength:0},animate:{pathLength:1},transition:{duration:.7*!r,ease:"easeOut"},opacity:".65"}),(0,n.jsx)("path",{d:"M4 16L9 10L15 15",opacity:".65"})]}),(0,n.jsx)(N.$,{variant:"ghost","aria-label":s("showSessionMenu"),onClick:t,className:"absolute inset-0 size-full p-0 hover:bg-foreground/5"})]})]})}var hd=s(45087);let hc=r.createContext(null);function hu(){let e=r.useContext(hc);if(!e)throw Error("useCarousel must be used within a <Carousel />");return e}function hm({orientation:e="horizontal",opts:t,setApi:s,plugins:a,className:i,children:l,...o}){let[d,c]=(0,hd.A)({...t,axis:"horizontal"===e?"x":"y"},a),[u,m]=r.useState(!1),[p,h]=r.useState(!1),g=r.useCallback(e=>{e&&(m(e.canScrollPrev()),h(e.canScrollNext()))},[]),x=r.useCallback(()=>{c?.scrollPrev()},[c]),f=r.useCallback(()=>{c?.scrollNext()},[c]),b=r.useCallback(e=>{"ArrowLeft"===e.key?(e.preventDefault(),x()):"ArrowRight"===e.key&&(e.preventDefault(),f())},[x,f]);return r.useEffect(()=>{c&&s&&s(c)},[c,s]),r.useEffect(()=>{if(!c)return;let e=!1;return queueMicrotask(()=>{e||g(c)}),c.on("reInit",g),c.on("select",g),()=>{e=!0,c.off("reInit",g),c.off("select",g)}},[c,g]),(0,n.jsx)(hc.Provider,{value:{carouselRef:d,api:c,opts:t,orientation:e||(t?.axis==="y"?"vertical":"horizontal"),scrollPrev:x,scrollNext:f,canScrollPrev:u,canScrollNext:p},children:(0,n.jsx)("div",{onKeyDownCapture:b,className:(0,C.cn)("relative",i),role:"region","aria-roledescription":"carousel","data-slot":"carousel",...o,children:l})})}function hp({className:e,...t}){let{carouselRef:s,orientation:r}=hu();return(0,n.jsx)("div",{ref:s,className:"overflow-hidden","data-slot":"carousel-content",children:(0,n.jsx)("div",{className:(0,C.cn)("flex","horizontal"===r?"-ml-4":"-mt-4 flex-col",e),...t})})}function hh({className:e,...t}){let{orientation:s}=hu();return(0,n.jsx)("div",{role:"group","aria-roledescription":"slide","data-slot":"carousel-item",className:(0,C.cn)("min-w-0 shrink-0 grow-0 basis-full","horizontal"===s?"pl-4":"pt-4",e),...t})}function hg(e){let t=e.scrollWidth-e.clientWidth;return t<=1||!["auto","scroll"].includes(getComputedStyle(e).overflowX)?null:{left:e.scrollLeft,maximum:t}}function hx(e){return e.sessionTitle?`${e.projectName} \xb7 ${e.sessionTitle}`:e.projectName}function hf({items:e,activeWorkId:t,onActiveWorkSessionChange:s,children:a}){let i,l,{t:o}=(0,f.Bd)("workbench"),d=(0,mQ.I)(),c=r.Children.toArray(a),u=e[0]?.workId??null,m=e.some(e=>e.workId===t)?t:u,[p]=(0,r.useState)(()=>Math.max(0,e.findIndex(e=>e.workId===m))),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),[x,b]=(0,r.useState)(),[v,w]=(0,r.useState)({index:p,position:p,visible:!1}),y=(0,r.useCallback)(()=>{null!==h.current&&(window.clearTimeout(h.current),h.current=null)},[]),k=(0,r.useCallback)(()=>{y(),h.current=window.setTimeout(()=>{h.current=null,w(e=>e.visible?{...e,visible:!1}:e)},900)},[y]),j=(0,r.useCallback)((t,s)=>{var n;let r=(n=t.scrollProgress()*(e.length-1),Math.max(0,Math.min(e.length-1,n))),a=Math.round(r);w(e=>{let t=s??e.visible;return e.index===a&&.001>Math.abs(e.position-r)&&e.visible===t?e:{index:a,position:r,visible:t}})},[e.length]),N=(0,r.useCallback)(e=>{j(e,!0),k()},[k,j]),I=(i=(0,r.useRef)(null),l=(0,r.useCallback)((e,t)=>{i.current=null;let s=t.target;if(!(s instanceof Element))return!0;if(s.closest('[data-carousel-swipe-lock],[data-testid="file-workspace"],[data-streamdown="mermaid-block"],[data-slot="plugin-scrollbar"],[data-slot="scroll-area-scrollbar"],.monaco-editor,[contenteditable="true"],[role="application"],[role="dialog"],[role="menu"],input,textarea,select,a,summary,img'))return!1;let n=s.closest("button");if(n&&(!("touches"in t)||!n.matches('[data-slot="collapsible-trigger"]')||!n.closest('[data-chat-scroll-anchor$=":tool"]')))return!1;let r=function(e){let t=[];for(let s=e;s&&!s.matches('[data-slot="carousel-item"]');s=s.parentElement){if(!(s instanceof HTMLElement))continue;let n=hg(s);if(n&&t.push(n),s.matches('[data-streamdown="code-block"],[data-streamdown="table-wrapper"],[data-pi-desk-scroll],[data-slot="l4-scroll-area"]'))for(let n of s.children){if(!(n instanceof HTMLElement)||n.contains(e))continue;let s=hg(n);s&&t.push(s)}}return t}(s);if(!("touches"in t))return!r.length&&!s.closest('pre,table,[data-streamdown="code-block"]');if(1!==t.touches.length)return!1;if(!r.length)return!0;let a=t.touches[0];return i.current={x:a.clientX,y:a.clientY,scrolls:r,owner:"pending"},!1},[]),(0,r.useEffect)(()=>{if(!x)return;let e=x.rootNode(),t=()=>{i.current=null},s=e=>{let s=i.current;if(!s)return;if(1!==e.touches.length)return void t();let n=e.touches[0],r=n.clientX-s.x,a=n.clientY-s.y;if("pending"===s.owner){if(6>Math.max(Math.abs(r),Math.abs(a)))return;let e=s.scrolls.some(e=>r<0?e.left<e.maximum-1:e.left>1);s.owner=Math.abs(a)>=Math.abs(r)||e?"content":r<0?"next":"previous"}if("content"!==s.owner){if(!e.cancelable){s.owner="content";return}e.preventDefault()}},n=s=>{let n=i.current;if(t(),!n||"pending"===n.owner||"content"===n.owner)return;let r=s.changedTouches[0],a=r.clientX-n.x,l=r.clientY-n.y,o=Math.max(50,Math.min(225,.2*e.clientWidth));("next"===n.owner?-a:a)<o||Math.abs(l)>=Math.abs(a)||("next"===n.owner?x.canScrollNext():x.canScrollPrev())&&(N(x),"next"===n.owner?x.scrollNext():x.scrollPrev())};return e.addEventListener("touchmove",s,{passive:!1}),e.addEventListener("touchend",n),e.addEventListener("touchcancel",t),x.on("reInit",t),()=>{t(),e.removeEventListener("touchmove",s),e.removeEventListener("touchend",n),e.removeEventListener("touchcancel",t),x.off("reInit",t)}},[x,N]),l),S=(0,r.useMemo)(()=>({align:"start",containScroll:"trimSnaps",dragFree:!1,loop:!1,skipSnaps:!1,duration:25*!d,startIndex:p,watchDrag:I}),[p,d,I]);if((0,r.useEffect)(()=>{m&&m!==t&&s(m)},[t,m,s]),(0,r.useLayoutEffect)(()=>{if(!x||!m)return;let t=e.findIndex(e=>e.workId===m);t<0||x.selectedScrollSnap()===t||x.scrollTo(t,!0)},[x,m,e]),(0,r.useEffect)(()=>{if(!x)return;let n=()=>{g.current=!0},r=()=>{g.current=!1,k()},a=e=>{if(g.current){y(),j(e,!0);return}j(e)},i=n=>{let r=e[n.selectedScrollSnap()];r&&r.workId!==t&&s(r.workId),j(n)},l=e=>{j(e),k()},o=e=>{j(e,!1)};return x.on("pointerDown",n),x.on("pointerUp",r),x.on("scroll",a),x.on("select",i),x.on("settle",l),x.on("reInit",o),()=>{g.current=!1,x.off("pointerDown",n),x.off("pointerUp",r),x.off("scroll",a),x.off("select",i),x.off("settle",l),x.off("reInit",o)}},[t,x,y,e,s,k,j]),(0,r.useEffect)(()=>y,[y]),e.length<=1)return(0,n.jsx)("div",{className:"size-full min-h-0 min-w-0 overflow-hidden",children:c[0]??null});let M=e[v.index]??e[0],z=`${100/e.length}%`,E=`translate3d(${100*v.position}%, 0, 0)`;return(0,n.jsxs)(hm,{opts:S,setApi:b,"aria-label":o("sessionWindows"),onKeyDownCapture:()=>void 0,className:"size-full min-h-0 min-w-0 [&_[data-slot=carousel-content]]:h-full [&_[data-slot=carousel-content]]:touch-auto",children:[(0,n.jsx)(hp,{className:"ml-0 h-full",children:e.map((t,s)=>(0,n.jsx)(hh,{"aria-label":`${s+1} / ${e.length},${hx(t)}`,className:"h-full pl-0",children:c[s]??null},t.workId))}),(0,n.jsx)("div",{"aria-hidden":"true","data-testid":"mobile-work-session-position",className:(0,C.cn)("pointer-events-none absolute top-16 left-1/2 z-30 w-[min(82vw,20rem)] -translate-x-1/2 transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none",v.visible?"translate-y-0 opacity-100":"-translate-y-2 opacity-0"),children:(0,n.jsxs)("div",{className:"rounded-xl border bg-popover px-3 py-2 text-popover-foreground shadow-lg",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs",children:[(0,n.jsx)("span",{className:"shrink-0 text-muted-foreground",children:o(M.fixed?"fixedSession":"primarySession")}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:hx(M)}),(0,n.jsxs)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:[v.index+1," / ",e.length]})]}),(0,n.jsx)("div",{className:"mt-2 h-1 overflow-hidden rounded-full bg-muted",children:(0,n.jsx)("div",{className:"h-full rounded-full bg-foreground",style:{width:z,transform:E}})})]})})]})}function hb(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}var hv=s(78653),hw=s.n(hv);function hy({sidebarOpen:e,onToggle:t}){let{t:s}=(0,f.Bd)("workbench");return(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":s(e?"hideSessionMenu":"showSessionMenu"),className:(0,C.cn)((0,N.r)({variant:"ghost",size:"icon"}),"text-muted-foreground"),children:e?(0,n.jsx)(sW.A,{className:"size-4"}):(0,n.jsx)(mK.A,{className:"size-5"})})}let hk=(0,r.memo)(function({onOpenSettings:e,workSession:t,fixed:s,focused:a,contentActive:i,composerActive:l,sidebarOpen:o,replacingWithEmpty:d,replacementDisabled:c,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,gitRuntime:x,invokePluginMethod:b,listPiCommands:v,getChatModelContext:w,capabilityModes:y,setChatCapabilityMode:k,branchPicker:j,branchPending:I,mobile:S,fileRuntime:M,onOpenFileSidebar:z,onPreviewFile:E,onAcknowledgeCompleted:A,onFocusWorkSession:$,onReplaceWithEmptyWorkSession:R,onOpenBranchPicker:T,onOpenGitBranchPicker:P,onCloseBranchPicker:D,onRetryBranchPicker:O,onSelectBranchEntry:L,onBranchAction:F,onConfirmRunningBranch:_,onCancelRunningBranch:B,onCloneWorkSession:q,onUnpinWorkSession:W,onToggleSidebar:U}){let{t:V}=(0,f.Bd)("workbench"),K=(0,r.useRef)(null),H=function(e,t){let{t:s}=(0,f.Bd)("workbench"),n=(0,Q.G)(),a=(0,r.useMemo)(()=>({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId}),[e.workId,e.sessionId,e.branchId]),i=(0,r.useCallback)(()=>t.getSourceState(a).runtime,[t,a]),l=(0,r.useSyncExternalStore)(t.subscribe,i,i),o=(0,r.useCallback)(()=>t.getSourceState(a).syncStatus,[t,a]),d=(0,r.useSyncExternalStore)(t.subscribe,o,o),c="basic"===l.extensionMode?l.initializationError:null,[u,m]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),g=!p&&"ready"===d&&"main_running"!==e.status&&"background_running"!==e.status,x=c?`${e.cwd}
156
- ${a.sessionId}
157
-
158
- ${c}`:"";return{error:c,copied:""!==x&&u===x,reloading:p,canReload:g,onCopy:()=>{x&&(0,e7.x)(x).then(e=>{e?m(x):n.error(s("initializationCopyFailed"))})},onReload:()=>{g&&(h(!0),t.reload(a).catch(e=>{n.error(e instanceof Error?e.message:String(e))}).finally(()=>h(!1)))}}}(t,u);(0,r.useSyncExternalStore)(M.subscribe,M.getRevision,M.getRevision);let G=M.getWorkspace(t.workId),J=(G?.tabs.length??0)+ +!!G?.activeDiff;return(0,r.useEffect)(()=>{let e=K.current;if(!e||"completed"!==t.status)return;let s=!1,n=()=>{s||(s=!0,A(t.workId))};return e.addEventListener("pointerdown",n,{once:!0}),e.addEventListener("wheel",n,{passive:!0,once:!0}),e.addEventListener("keydown",n,{once:!0}),()=>{e.removeEventListener("pointerdown",n),e.removeEventListener("wheel",n),e.removeEventListener("keydown",n)}},[A,t.status,t.workId]),(0,n.jsxs)("section",{ref:K,className:"pi-desk-workbench-resize-interactions relative flex h-full min-h-0 min-w-0 flex-1 flex-col bg-background","data-work-id":t.workId,"data-degraded":H.error?"true":void 0,onPointerDown:()=>$(t.workId),onFocusCapture:()=>$(t.workId),children:[H.error?(0,n.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-20 border border-destructive"}):null,(0,n.jsx)(un,{workSession:t,runtime:M,gitRuntime:x,mobile:S,onOpenGitBranches:P,onOpenSidebar:()=>z(t.workId),children:r=>(0,n.jsxs)("div",{className:"flex h-full min-h-0 min-w-0 flex-1 flex-col",children:[(0,n.jsxs)("header",{className:"flex min-h-14 items-center gap-3 px-3",children:[s&&!S?null:(0,n.jsx)(hy,{sidebarOpen:o,onToggle:U}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:(0,C.cn)("truncate text-sm transition-colors duration-150 motion-reduce:transition-none",a?"font-semibold text-foreground":"font-medium text-muted-foreground"),children:t.projectName}),(0,n.jsx)("p",{className:"truncate text-xs text-muted-foreground",children:t.sessionTitle??V("newSession")})]}),(0,n.jsxs)("div",{className:"-mr-1 flex shrink-0 items-center",children:[H.error?(0,n.jsx)(ha,{error:H.error,copied:H.copied,reloading:H.reloading,canReload:H.canReload,onCopy:H.onCopy,onReload:H.onReload},`${t.sessionId}:${t.branchId}`):null,J>0?(0,n.jsxs)(N.$,{variant:"ghost","data-testid":"session-files-entry","aria-label":V("openSessionFiles"),"aria-pressed":G?.windowOpen??!1,onClick:()=>M.showWindow(t.workId),children:[(0,n.jsx)(mH.A,{className:"size-4"}),V("sessionFiles",{count:J})]}):null,W?(0,n.jsx)("button",{type:"button",disabled:c,"aria-label":V("unpinWorkSession",{name:t.sessionTitle??t.projectName}),title:V("unpin"),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),W(t.workId)},className:(0,C.cn)((0,N.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground"),children:(0,n.jsx)(Y.A,{className:"size-4"})}):null]})]}),(0,n.jsx)(hr,{active:i,visible:r&&i,workSession:t,chatRuntime:u,inputRuntime:m,onPreviewFile:E}),(0,n.jsx)("footer",{className:"bg-background pt-3","data-carousel-swipe-lock":!0,children:(0,n.jsx)(pW,{workSession:t,chatRuntime:u,inputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,gitRuntime:x,active:l,mobile:S,invokePluginMethod:b,listPiCommands:v,getChatModelContext:w,capabilityModes:y,setChatCapabilityMode:k,newSessionPending:d,newSessionDisabled:c||I,onNewSession:()=>R(t.workId),clonePending:I,cloneDisabled:c||0===t.messageCounts.total,onCloneWorkSession:()=>q(t.workId),onOpenBranchPicker:T,onOpenGitBranchPicker:P,onOpenSettings:e})})]})}),(0,n.jsx)(mG.N,{children:j?(0,n.jsx)(m4,{model:j,projectName:t.projectName,sessionTitle:t.sessionTitle,mobile:S,onClose:D,onRetry:O,onSelectEntry:L,onAction:F,onConfirmRunning:_,onCancelRunning:B},"branch-picker"):null})]})}),hj=(0,r.memo)(function({position:e,workSession:t,loading:s,onExpand:r}){let{t:a}=(0,f.Bd)("workbench"),i=t?.projectName??a("workSession"),l=t?t.sessionTitle??a("newSession"):a(s?"loading":"chooseSession"),o=`${i} \xb7 ${l}`;return(0,n.jsx)("section",{className:"relative isolate flex h-full min-h-0 min-w-0 flex-1 bg-background","data-work-id":t?.workId,children:(0,n.jsx)("button",{type:"button",title:o,"aria-label":a("expandSession",{name:o}),onClick:()=>r(e,t?.workId??null),className:"flex h-full w-full min-w-0 flex-col items-center overflow-hidden bg-background px-1 text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:z-30 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:(0,n.jsxs)("span",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-3 overflow-hidden py-3",children:[(0,n.jsx)("span",{className:(0,C.cn)(hw().collapsedText,"max-h-[38%] text-xs leading-none text-muted-foreground"),children:i}),(0,n.jsx)("span",{className:(0,C.cn)(hw().collapsedText,"max-h-[55%] text-xs font-semibold leading-none"),children:l})]})})})});function hN({loading:e,sidebarOpen:t,onToggleSidebar:s}){return(0,n.jsxs)("section",{className:"relative isolate flex h-full min-w-0 flex-1 overflow-hidden bg-background",children:[(0,n.jsx)("div",{className:"absolute left-3 top-3 z-20",children:(0,n.jsx)(hy,{sidebarOpen:t,onToggle:s})}),(0,n.jsx)(mV,{variant:e?"loading":"select-session",children:e?null:(0,n.jsx)(ho,{sidebarOpen:t,onOpen:s})})]})}function hI({onOpenSettings:e,workSessions:t,primaryWorkId:s,pinnedWorkIds:a,focusedWorkId:i,sidebarOpen:l,mobile:o,loading:d,replacingWithEmptyWorkId:c,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,gitRuntime:x,invokePluginMethod:b,listPiCommands:v,getChatModelContext:w,capabilityModes:y,setChatCapabilityMode:k,branchPicker:j,branchPendingWorkId:N,fileRuntime:M,onOpenFileSidebar:z,onPreviewFile:E,onAcknowledgeCompleted:A,onFocusWorkSession:$,onReplaceWithEmptyWorkSession:R,onOpenBranchPicker:T,onOpenGitBranchPicker:P,onCloseBranchPicker:D,onRetryBranchPicker:O,onSelectBranchEntry:L,onBranchAction:F,onConfirmRunningBranch:_,onCancelRunningBranch:B,onCloneWorkSession:q,onUnpinWorkSession:W,onToggleSidebar:Y}){let{t:U}=(0,f.Bd)("workbench"),V=(0,r.useMemo)(()=>{let e=t.find(e=>e.workId===s)??null,n=new Set(a);return[{key:"work-session-primary",workSession:e,fixed:!1},...t.filter(e=>e.workId!==s&&n.has(e.workId)).map(e=>({key:`work-session-${e.workId}`,workSession:e,fixed:!0}))]},[a,s,t]),K=(0,r.useMemo)(()=>V.flatMap(e=>e.workSession?[{workId:e.workSession.workId,projectName:e.workSession.projectName,sessionTitle:e.workSession.sessionTitle,fixed:e.fixed}]:[]),[V]),H=V.length,{containerRef:G,expandedCount:J}=function(e){let t=(0,r.useRef)(null),s=+(e>0),n=(0,r.useRef)(s),[a,i]=(0,r.useState)(s);return(0,r.useLayoutEffect)(()=>{let s=t.current;if(!s)return;let r=t=>{let s=function(e,t){let s=hb(t);if(0===s)return 0;let n=Math.floor(((Number.isFinite(e)?Math.max(0,Math.floor(e)):0)-48*s)/252);return Math.min(s,Math.max(1,n))}(t,e);n.current!==s&&(n.current=s,i(s))};r(s.clientWidth);let a=new ResizeObserver(e=>{r(e[0]?.contentRect.width??s.clientWidth)});return a.observe(s),()=>a.disconnect()},[e]),{containerRef:t,expandedCount:a}}(H),[Q,X]=(0,r.useState)(null),Z=j?V.findIndex(e=>e.workSession?.workId===j.workId):-1,ee=Z>=0?Z:null!==Q&&Q>=0&&Q<H?Q:null,et=(0,r.useMemo)(()=>(function(e,t,s){let n=hb(e);if(0===n)return[];let r=Math.min(n,Math.max(1,hb(t))),a=null!==s&&Number.isInteger(s)&&s>=0&&s<n?s:null,i=Array(n).fill("expanded"),l=n-r;for(let e=n-1;e>=0&&l>0;e-=1)e!==a&&(i[e]="collapsed",l-=1);return i})(H,J,ee),[H,ee,J]),es=(0,S.OG)(),en=JSON.stringify(V.map(e=>e.key)),er=et.map(e=>"expanded"===e?"e":"c").join("");(0,r.useLayoutEffect)(()=>{let e=JSON.parse(en);if(e.length<=1||e.length!==er.length)return;let t=null,s=0,n=()=>{let r=es.current,a=G.current;if(!r||!a||a.clientWidth<=0)return;let i=Object.keys(r.getLayout());if(!(i.length===e.length&&e.every(e=>i.includes(e))))return void((s+=1)<8?t=window.requestAnimationFrame(n):console.warn("[Pi Desk][WorkbenchColumns] 面板拓扑未及时就绪,跳过本次均分",{expectedPanelCount:e.length,registeredPanelCount:i.length}));let l=[...er].filter(e=>"c"===e).length,o=e.length-l;if(o<=0)return;let d=48/a.clientWidth*100,c=(100-l*d)/o;if(!Number.isFinite(c)||c<=0)return;let u={};for(let[t,s]of e.entries())u[s]="c"===er[t]?d:c;r.setLayout(u)};return t=window.requestAnimationFrame(n),()=>{null!==t&&window.cancelAnimationFrame(t)}},[er,G,es,en]);let ea=V[0]?.workSession??null,ei=V.reduce((e,t)=>e+ +!!t.workSession,0),el=i??ea?.workId??null,eo=d||null!==c,ed=(0,r.useCallback)((e,t)=>{X(e),t&&$(t)},[$]);return o?0===ei?(0,n.jsx)(hN,{loading:d,sidebarOpen:l,onToggleSidebar:Y}):(0,n.jsx)(hf,{items:K,activeWorkId:el,onActiveWorkSessionChange:$,children:V.flatMap(t=>{let s=t.workSession;return s?[(0,n.jsx)(hk,{workSession:s,fixed:t.fixed,focused:1===ei||s.workId===el,contentActive:s.workId===el,composerActive:s.workId===el,sidebarOpen:l,replacingWithEmpty:c===s.workId,replacementDisabled:eo,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,gitRuntime:x,invokePluginMethod:b,listPiCommands:v,getChatModelContext:w,capabilityModes:y,setChatCapabilityMode:k,branchPicker:j?.workId===s.workId?j:null,branchPending:N===s.workId,mobile:!0,fileRuntime:M,onOpenFileSidebar:z,onPreviewFile:E,onAcknowledgeCompleted:A,onFocusWorkSession:$,onReplaceWithEmptyWorkSession:R,onOpenBranchPicker:T,onOpenGitBranchPicker:P,onOpenSettings:e,onCloseBranchPicker:D,onRetryBranchPicker:O,onSelectBranchEntry:L,onBranchAction:F,onConfirmRunningBranch:_,onCancelRunningBranch:B,onCloneWorkSession:q,onUnpinWorkSession:t.fixed?W:null,onToggleSidebar:Y},`${s.workId}:${s.sessionId}:${s.branchId}`)]:[]})}):(0,n.jsx)(I.HK,{id:"work-session-columns",orientation:"horizontal",disableCursor:!0,elementRef:G,groupRef:es,className:(0,C.cn)(cD().sessionPanelGroup,"relative h-full min-h-0 min-w-0 flex-1 overflow-hidden",!o&&"pi-desk-workbench-resize-group"),children:V.flatMap((t,s)=>{let r=t.workSession,a="collapsed"===et[s],i=s>0&&"collapsed"===et[s-1],f=a&&i,S=(0,n.jsx)(I.wV,{id:t.key,minSize:a?48:300,maxSize:a?48:void 0,defaultSize:a?48:300,disabled:a,groupResizeBehavior:a?"preserve-pixel-size":"preserve-relative-size",className:(0,C.cn)("flex h-full min-h-0 min-w-0 !overflow-hidden bg-background",s>0&&"border-l"),children:(0,n.jsx)("div",{className:cD().columnContent,children:a?(0,n.jsx)(hj,{position:s,workSession:r,loading:d,onExpand:ed}):r?(0,n.jsx)(hk,{workSession:r,fixed:t.fixed,focused:1===ei||r.workId===el,contentActive:!0,composerActive:r.workId===el,sidebarOpen:l,replacingWithEmpty:c===r.workId,replacementDisabled:eo,chatRuntime:u,chatInputRuntime:m,renderTaskSummary:p,renderTaskMenu:h,renderPluginComposerPanel:g,gitRuntime:x,invokePluginMethod:b,listPiCommands:v,getChatModelContext:w,capabilityModes:y,setChatCapabilityMode:k,branchPicker:j?.workId===r.workId?j:null,branchPending:N===r.workId,mobile:o,fileRuntime:M,onOpenFileSidebar:z,onPreviewFile:E,onAcknowledgeCompleted:A,onFocusWorkSession:$,onReplaceWithEmptyWorkSession:R,onOpenBranchPicker:T,onOpenGitBranchPicker:P,onOpenSettings:e,onCloseBranchPicker:D,onRetryBranchPicker:O,onSelectBranchEntry:L,onBranchAction:F,onConfirmRunningBranch:_,onCancelRunningBranch:B,onCloneWorkSession:q,onUnpinWorkSession:t.fixed?W:null,onToggleSidebar:Y},`${r.workId}:${r.sessionId}:${r.branchId}`):(0,n.jsx)(hN,{loading:d,sidebarOpen:l,onToggleSidebar:Y})})},t.key);return 0===s?[S]:[(0,n.jsx)(I.WM,{withHandle:!f,disabled:f,"aria-label":U("resizeColumns",{left:s,right:s+1}),className:"w-0 cursor-col-resize bg-transparent aria-disabled:cursor-default"},`${V[s-1].key}-${t.key}-resize-handle`),S]})})}let hC="work-session-pin:boundary";function hS(e,t){hz(e,t);let s=e.slice(0,t),n=e.slice(t);return s.length>0&&n.length>0?[...n,hC,...s]:[...n,...s]}function hM(e,t,s){let n=[...e],[r]=n.splice(t,1);return r&&n.splice(s,0,r),n}function hz(e,t){if(!Number.isInteger(t)||t<0||t>e.length)throw Error("Invalid work session pinnedCount")}function hE(e,t){return e instanceof Error?e.message:t}function hA(e){return e instanceof Error&&"AbortError"===e.name}function h$(e){return"main_running"===e.status||"background_running"===e.status}function hR(e){return{workId:e.workId,sessionId:e.sessionId,branchId:e.branchId}}function hT({open:e,title:t,saving:s,disabled:a,error:i,onTitleChange:l,onSave:o,onClose:d}){let{t:c}=(0,f.Bd)("workbench"),u=(0,r.useId)(),m=(0,r.useRef)(null);return(0,n.jsx)(ej.YV,{open:e,onOpenChange:e=>!e&&d(),children:(0,n.jsx)(ej.hA,{"data-testid":"work-session-rename-dialog",showCloseButton:!1,initialFocus:m,className:"max-w-sm",children:(0,n.jsxs)("form",{className:"flex flex-col gap-4 overflow-y-auto p-4",onSubmit:e=>{e.preventDefault(),o()},children:[(0,n.jsx)(ej.YM,{children:c("renameSessionTitle")}),(0,n.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,n.jsx)("label",{htmlFor:u,className:"font-medium",children:c("sessionTitleLabel")}),(0,n.jsx)(eu.p,{ref:m,id:u,value:t,disabled:s,onChange:e=>l(e.currentTarget.value),onFocus:e=>e.currentTarget.select(),onKeyDown:e=>{"Enter"===e.key&&e.nativeEvent.isComposing&&e.preventDefault()}})]}),i?(0,n.jsx)("p",{role:"alert",className:"break-words text-destructive",children:i}):null,(0,n.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,n.jsx)(N.$,{type:"button",variant:"outline",disabled:s,onClick:d,children:c("cancel",{ns:"common"})}),(0,n.jsxs)(N.$,{type:"submit",disabled:a||s||!t.trim(),"aria-busy":s,children:[s?(0,n.jsx)(b.A,{className:"size-4 animate-spin"}):null,c("save",{ns:"common"})]})]})]})})})}let hP=["title","user"];function hD(e){return e.length===hP.length&&hP.every(t=>e.includes(t))}var hO=s(1503),hL=s(40155),hF=s(17864),h_=s(98347),hB=s(74675),hq=s(1364),hW=s(89517),hY=s.n(hW);function hU(e){return{"--pi-desk-project-color":function(e){let t=e.replaceAll("\\","/").toLowerCase(),s=0x811c9dc5;for(let e=0;e<t.length;e+=1)s^=t.charCodeAt(e),s=Math.imul(s,0x1000193);let n=(s>>>0)%360;return`oklch(var(--project-color-lightness, 0.49) var(--project-color-chroma, 0.1) ${n})`}(e)}}let hV={info:{icon:"text-muted-foreground",label:"noticeInfo"},success:{icon:"text-status-success",label:"noticeSuccess"},warning:{icon:"text-status-warning",label:"noticeWarning"},error:{icon:"text-destructive",label:"noticeError"}};function hK({level:e}){let t="size-3.5";switch(e){case"success":return(0,n.jsx)(ln.A,{className:t});case"warning":return(0,n.jsx)(eB.A,{className:t});case"error":return(0,n.jsx)(W.A,{className:t});case"info":return(0,n.jsx)(sF.A,{className:t})}}function hH({notification:e,latest:t,mobile:s,moreCount:r,busy:a,onConsume:i,onDismiss:l,onToggleMore:o,showDismiss:d}){let{t:c}=(0,f.Bd)("workbench"),u=hV[e.level],m=null!==e.event;return(0,n.jsxs)("div",{"data-testid":`app-notification-${e.notificationId}`,"data-latest":t?"true":void 0,className:(0,C.cn)("group flex min-w-0 items-stretch overflow-hidden rounded-lg bg-foreground/[0.04]",t?"h-14":"min-h-14"),children:[(0,n.jsxs)("button",{type:"button",disabled:!m||a,onClick:i,"aria-label":c(m?"actionableNotice":"noticeLabel",{level:c(u.label),title:e.title}),className:"grid min-w-0 flex-1 grid-cols-[1.6rem_minmax(0,1fr)_auto] items-center gap-1.5 px-2 text-left outline-none transition-colors enabled:cursor-pointer enabled:hover:bg-foreground/8 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-default",children:[(0,n.jsx)("span",{className:(0,C.cn)("grid size-6 place-items-center rounded-md",u.icon),children:(0,n.jsx)(hK,{level:e.level})}),(0,n.jsxs)("span",{className:"min-w-0",children:[(0,n.jsx)("span",{className:"block truncate text-sm font-medium leading-5 text-foreground",children:e.title}),e.description?(0,n.jsx)("span",{className:"block truncate text-xs leading-5 text-muted-foreground",children:e.description}):null]}),!s&&t&&r>0?(0,n.jsxs)("span",{className:"px-1 text-xs tabular-nums text-muted-foreground",children:["+",r]}):null]}),s&&t&&r>0?(0,n.jsx)("button",{"data-testid":"app-notification-more",type:"button",disabled:a,onClick:o,"aria-label":c("olderNotices",{count:r}),className:"mr-1 grid size-7 shrink-0 place-items-center self-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50",children:(0,n.jsx)(V.A,{className:"size-4"})}):null,d?(0,n.jsx)("button",{type:"button",disabled:a,onClick:l,"aria-label":c("deleteNotice",{title:e.title}),title:c("dismissNotice"),className:(0,C.cn)("mr-1 grid size-7 shrink-0 place-items-center self-center rounded-md text-muted-foreground outline-none transition-[background-color,color,opacity] hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50",!s&&"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:(0,n.jsx)(Y.A,{className:"size-3.5"})}):null]})}function hG({mobile:e,notifications:t,onConsume:s,onDismiss:a}){let i=(0,r.useRef)(null),l=(0,r.useRef)(null),o=(0,r.useRef)(null),d=(0,r.useRef)(null),[c,u]=(0,r.useState)(!1),[m,p]=(0,r.useState)(null),h=t.at(-1)??null,g=t.slice(0,-1),x=g.length>0,f=c&&x,b=64+60*Math.min(g.length,5)+8,v=(0,r.useCallback)(()=>{o.current&&clearTimeout(o.current),o.current=null},[]),w=(0,r.useCallback)(()=>{d.current&&clearTimeout(d.current),d.current=null},[]),y=(0,r.useCallback)(()=>{v(),w(),x&&u(!0)},[x,w,v]),k=(0,r.useCallback)(()=>{v(),w(),u(!1)},[w,v]),j=(0,r.useCallback)(()=>{!e&&x&&(w(),v(),o.current=setTimeout(y,120))},[x,w,v,e,y]),N=(0,r.useCallback)(()=>{e||(v(),w(),d.current=setTimeout(k,180))},[w,v,k,e]);(0,r.useEffect)(()=>{if(!f)return;let e=l.current;e&&(e.scrollTop=e.scrollHeight)},[g.length,f]),(0,r.useEffect)(()=>{if(!e||!f)return;let t=e=>{i.current?.contains(e.target)||k()},s=e=>{"Escape"===e.key&&k()};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",s)}},[k,e,f]),(0,r.useEffect)(()=>()=>{v(),w()},[w,v]);let I=(0,r.useCallback)(async e=>{if(e.event&&!m){p(e.notificationId),u(!1);try{await s(e)}finally{p(null)}}},[m,s]),S=(0,r.useCallback)(async e=>{if(!m){p(e);try{await a(e)}finally{p(null)}}},[m,a]);return h?(0,n.jsx)("div",{"data-testid":"app-notification-slot",className:"relative z-20 h-16 shrink-0",children:(0,n.jsxs)("div",{ref:i,"data-testid":"app-notification-panel","data-expanded":f?"true":"false",onPointerEnter:e=>{"mouse"===e.pointerType&&j()},onPointerLeave:e=>{"mouse"===e.pointerType&&N()},onFocus:()=>{e||y()},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||N()},className:(0,C.cn)("absolute inset-x-0 bottom-0 flex max-h-[calc(100dvh-8rem)] flex-col overflow-hidden bg-sidebar text-sidebar-foreground transition-[height,box-shadow] duration-150 ease-out motion-reduce:transition-none",f&&"shadow-lg duration-200"),style:{height:f?b:64},children:[(0,n.jsx)("div",{ref:l,className:(0,C.cn)("pi-desk-chat-scrollbar absolute inset-x-0 bottom-16 top-0 space-y-1 overflow-y-auto px-2 pt-2",!f&&"invisible"),children:g.map(t=>(0,n.jsx)(hH,{notification:t,latest:!1,mobile:e,moreCount:0,busy:null!==m,onConsume:()=>void I(t),onDismiss:()=>void S(t.notificationId),onToggleMore:()=>void 0,showDismiss:!0},t.notificationId))}),(0,n.jsx)("div",{className:"absolute inset-x-0 bottom-0 h-16 px-2 py-1",children:(0,n.jsx)(hH,{notification:h,latest:!0,mobile:e,moreCount:g.length,busy:null!==m,onConsume:()=>void I(h),onDismiss:()=>void S(h.notificationId),onToggleMore:()=>u(e=>!e),showDismiss:!e||0===g.length||f})})]})}):null}function hJ(e,t){return Math.max(0,Math.floor((t-e)/6e4))}let hQ=null;function hX(e,t){let s=t.formatToParts(e),n=e=>Number(s.find(t=>t.type===e)?.value);return Date.UTC(n("year"),n("month")-1,n("day"))}var hZ=s(20314),h0=s.n(hZ);function h1(e,t){return`plugin:${e}:${t}`}let h2=[[5,3],[11,3],[5,8],[11,8],[5,13],[11,13]],h5=(0,C.cn)((0,N.r)({variant:"ghost"}),h0().sidebarAction,"relative h-[3.25rem] max-w-24 min-w-0 flex-1 flex-col gap-1 whitespace-normal px-1 text-xs font-normal text-muted-foreground"),h3=(0,N.r)({variant:"ghost",size:"icon"}),h4=(0,C.cn)((0,N.r)({variant:"ghost",size:"icon"}),h0().sidebarAction,"text-muted-foreground");function h6({items:e,appearance:t,label:s,className:r}){let{t:a}=(0,f.Bd)("workbench"),i="action"===t&&e.length>3?e.slice(2):[],l=i.length>0?e.slice(0,2):e;return(0,n.jsxs)("div",{className:(0,C.cn)("flex min-w-0 items-center gap-0",r),role:"group","aria-label":s,children:[l.map(e=>{var s,r;return(0,n.jsx)("button",{"data-testid":e.testId,type:"button",disabled:e.disabled,"aria-pressed":e.pressed,"aria-busy":e.busy||void 0,"aria-label":"mode"===t?a("showSidebarMode",{name:e.label}):e.label,title:e.label,onClick:e.onSelect,className:(s=!0===e.pressed,r=!0===e.busy,"mode"===t?(0,C.cn)(h3,s?"bg-accent text-accent-foreground":(0,C.cn)(h0().sidebarAction,"text-muted-foreground")):(0,C.cn)(h4,s&&"bg-muted text-foreground",r?"disabled:cursor-wait":"disabled:cursor-not-allowed")),children:(0,n.jsx)("span",{className:(0,C.cn)("flex shrink-0","mode"===t?"[&_svg]:size-5":"[&_svg]:size-4"),children:e.icon})},e.key)}),i.length>0?(0,n.jsxs)(K.rI,{children:[(0,n.jsx)(K.ty,{render:(0,n.jsx)("button",{type:"button","aria-label":s,title:s,className:h4,children:(0,n.jsx)(V.A,{className:"size-4"})})}),(0,n.jsx)(K.SQ,{align:"end",children:i.map(e=>(0,n.jsxs)(K._2,{disabled:e.disabled,onClick:e.onSelect,children:[(0,n.jsx)("span",{className:"shrink-0 [&_svg]:size-4",children:e.icon}),e.label]},e.key))})]}):null]})}function h8({modeItems:e,actionItems:t}){let{t:s}=(0,f.Bd)("workbench");return(0,n.jsxs)("header",{className:"flex min-h-12 shrink-0 items-center gap-2 px-2",children:[(0,n.jsx)(h6,{items:e,appearance:"mode",label:s("sidebarContents"),className:"max-w-full overflow-x-auto rounded-lg p-0.5 dark:bg-muted"}),t.length>0?(0,n.jsx)(h6,{items:t,appearance:"action",label:s("sidebarActions"),className:"ml-auto shrink-0"}):null]})}function h7(){return(0,n.jsx)("svg",{className:"block size-full",viewBox:"0 0 16 16","aria-hidden":"true",children:h2.map(([e,t])=>(0,n.jsx)("circle",{cx:e,cy:t,r:"1.15",fill:"currentColor"},`${e}-${t}`))})}let h9=(0,r.memo)(function({workSession:e,mobile:t,selected:s,pinned:a,deleting:i,disabled:l,ordering:o,now:d,onSelect:c,onTogglePin:u,onDelete:m,onRename:p,syncing:h,onReloadChat:g}){var x,v;let w=(0,r.useRef)(!1),y=(0,r.useRef)(""),k=l||o,{attributes:j,listeners:I,setNodeRef:S,setActivatorNodeRef:M,transform:z,transition:E,isDragging:A}=(0,a$.gl)({id:e.workId,disabled:k}),$=(0,Q.G)(),{t:R}=(0,f.Bd)("workbench"),{locale:T,timeZone:P}=(0,eG.i)(),D=R(function(e){switch(e.status){case"main_running":return"mainRunning";case"background_running":return"backgroundRunning";case"completed":return"completedUnread";case"idle":return"idle"}}(e)),O=e.sessionTitle??R("newSession"),L=`${e.messageCounts.user}/${e.messageCounts.total}`,F=function(e,t,s="en",n="UTC"){let r=function(e,t){if(null===e||null===t)return"old";let s=hJ(e,t);return s<5?"fresh":s<60?"recent":"old"}(e,t);if(null===e)return{compact:"--",title:"en"===s?"No messages yet":"暂无消息时间",tone:r};let a=function(e,t){if(hQ?.locale===e&&hQ.timeZone===t)return hQ;let s="en"===e?"en-US":"zh-CN";return hQ={locale:e,timeZone:t,title:new Intl.DateTimeFormat(s,{timeZone:t,timeZoneName:"shortOffset",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),dateKey:new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"numeric",day:"numeric"}),compact:new Intl.DateTimeFormat(s,{timeZone:t,month:"short",day:"numeric"})}}(s,n),i=a.title.format(e);if(null===t)return{compact:i,title:i,tone:r};let l=hJ(e,t);if(l<1)return{compact:"en"===s?"Just now":"刚刚",title:i,tone:r};if(l<60)return{compact:"en"===s?`${l} min ago`:`${l} 分钟前`,title:i,tone:r};let o=Math.floor(l/60);if(o<24)return{compact:"en"===s?`${o} hr ago`:`${o} 小时前`,title:i,tone:r};let d=(hX(t,a.dateKey)-hX(e,a.dateKey))/864e5;return 1===d?{compact:"en"===s?"Yesterday":"昨天",title:i,tone:r}:2===d?{compact:"en"===s?"2 days ago":"前天",title:i,tone:r}:{compact:a.compact.format(e),title:i,tone:r}}(e.lastMessageUpdatedAt,d,T,P),_="main_running"===e.status||"background_running"===e.status,B=(x=e.cwd,{className:hY().surface,style:hU(x)}),q=(v=e.cwd,{className:hY().identity,style:hU(v)}),W=z?`translate3d(${z.x}px, ${z.y}px, 0)`:void 0,Y=(0,r.useCallback)(()=>c(e.workId),[c,e.workId]),U=(0,r.useCallback)(()=>u(e.workId),[u,e.workId]),V=(0,r.useCallback)(()=>m(e.workId),[m,e.workId]),K=(0,r.useCallback)(()=>{(0,e7.x)(e.cwd).then(e=>{e?$.success(R("copiedProjectPath")):$.error(R("copyProjectPathFailed"))})},[$,e.cwd,R]),H=(0,n.jsxs)("div",{ref:S,"data-testid":`work-session-row-${e.workId}`,"data-dragging":A?"true":void 0,role:"button",tabIndex:0,"aria-pressed":s,onClick:Y,onKeyDown:e=>{e.target===e.currentTarget&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),Y())},className:(0,C.cn)(B.className,h0().sessionRow,!t&&h0().desktopRow,"grid min-h-15 min-w-0 cursor-pointer grid-cols-[1.75rem_minmax(0,1fr)] items-center rounded-lg border border-transparent px-1 py-0.5 outline-none transition-[background-color,opacity] duration-150 ease-out focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",s?"text-accent-foreground":"hover:text-foreground","completed"===e.status&&"border-[var(--pi-desk-project-color)]",A&&"cursor-grabbing opacity-30"),style:{...B.style,transform:W,transition:E},children:[_?(0,n.jsx)("svg",{"aria-hidden":"true",focusable:"false","data-testid":"work-session-running-border",className:h0().runningBorder,children:(0,n.jsx)("rect",{x:"0.5",y:"0.5"})}):null,(0,n.jsx)("button",{ref:M,"data-testid":`work-session-drag-${e.workId}`,type:"button",...j,...I,onTouchStart:e=>{I?.onTouchStart?.(e),e.stopPropagation()},onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>e.stopPropagation(),disabled:k,"aria-label":R("dragSession",{name:O}),title:`${D} \xb7 ${R("dragOrder")}`,className:(0,C.cn)(q.className,"flex size-7 touch-none cursor-grab items-center justify-center outline-none transition-[color,filter] hover:brightness-125 active:cursor-grabbing focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none",l&&"opacity-50"),children:(0,n.jsx)("span",{className:"size-4",children:(0,n.jsx)(h7,{})})}),(0,n.jsxs)("div",{className:"min-w-0 py-0.5",children:[(0,n.jsx)("span",{className:"sr-only",children:D}),(0,n.jsxs)("div",{className:"flex min-w-0 items-center justify-between gap-1",children:[(0,n.jsx)("p",{className:(0,C.cn)(q.className,"truncate text-xs font-medium"),title:e.projectName,children:e.projectName}),(0,n.jsxs)("span",{className:(0,C.cn)(h0().rowMetadata,"flex shrink-0 items-center gap-1 whitespace-nowrap text-xs leading-4 text-muted-foreground"),title:R("sessionMessages",{count:L,time:F.title}),children:[(0,n.jsx)("span",{children:L}),(0,n.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,n.jsx)("span",{className:(0,C.cn)("transition-colors","fresh"===F.tone&&"dark:text-sidebar-primary"),children:F.compact})]})]}),(0,n.jsxs)("div",{className:"relative flex min-h-7 min-w-0 items-center",children:[(0,n.jsx)("p",{className:(0,C.cn)(h0().rowTitle,"min-w-0 flex-1 truncate pr-1 text-sm",s?"font-semibold":"font-medium"),title:O,children:O}),(0,n.jsxs)("div",{className:(0,C.cn)(h0().rowActions,"flex shrink-0 items-center"),children:[(0,n.jsx)("button",{"data-testid":`work-session-pin-${e.workId}`,type:"button",onClick:e=>{e.stopPropagation(),U()},disabled:k,"aria-label":R(a?"unpinSession":"pinSession",{name:O}),title:R(a?"unpin":"pin"),className:(0,C.cn)((0,N.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground",a&&q.className),children:a?(0,n.jsx)(hO.A,{className:"size-4"}):(0,n.jsx)(rn.A,{className:"size-4"})}),(0,n.jsx)("button",{"data-testid":`work-session-delete-${e.workId}`,type:"button",disabled:k||i,onClick:e=>{e.stopPropagation(),V()},"aria-label":R("deleteSession",{name:O}),title:R("deleteSessionTitle"),className:(0,C.cn)((0,N.r)({variant:"ghost",size:"icon-sm"}),"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"),children:(0,n.jsx)(ee.A,{className:"size-4"})})]})]})]})]});return(0,n.jsxs)(hq.tz,{onOpenChange:(e,t)=>{e&&("touch"===y.current||t.event.type.startsWith("touch"))&&(w.current=!0)},children:[(0,n.jsx)(hq.Rc,{render:H,onPointerDown:e=>{y.current=e.pointerType,w.current=!1},onTouchEndCapture:e=>{w.current&&e.cancelable&&e.preventDefault()},onClickCapture:e=>{w.current&&(e.preventDefault(),e.stopPropagation(),w.current=!1)},onKeyDownCapture:e=>{if(e.target!==e.currentTarget||e.nativeEvent.isComposing||(y.current="keyboard",w.current=!1,"ContextMenu"!==e.key&&!("F10"===e.key&&e.shiftKey)))return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getBoundingClientRect();e.currentTarget.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,button:2,clientX:t.left+t.width/2,clientY:t.top+t.height/2}))}}),(0,n.jsxs)(hq.Ip,{children:[(0,n.jsxs)(hq.kt,{"data-testid":`work-session-rename-${e.workId}`,disabled:k||i,onClick:()=>p(e),children:[(0,n.jsx)(hL.A,{}),R("renameSessionTitle")]}),(0,n.jsxs)(hq.kt,{"data-testid":`work-session-reload-chat-${e.workId}`,disabled:k||i||h,onClick:()=>g(e),children:[h?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(et.A,{}),R("reloadChatData")]}),(0,n.jsxs)(hq.kt,{"data-testid":`work-session-copy-project-path-${e.workId}`,onClick:K,children:[(0,n.jsx)(Z.A,{}),R("copyProjectPath")]})]})]})});function ge({id:e,label:t}){let{setNodeRef:s,transform:r,transition:a}=(0,a$.gl)({id:e,disabled:{draggable:!0}}),i=r?`translate3d(${r.x}px, ${r.y}px, 0) scaleX(${r.scaleX??1}) scaleY(${r.scaleY??1})`:void 0;return(0,n.jsxs)("div",{ref:s,"data-testid":e,"aria-hidden":"true",className:"pointer-events-none flex h-5 items-center gap-2 px-1 text-xs text-muted-foreground",style:{transform:i,transition:a},children:[(0,n.jsx)("span",{className:"h-px flex-1 bg-border/75"}),(0,n.jsx)("span",{children:t}),(0,n.jsx)("span",{className:"h-px flex-1 bg-border/75"})]})}let gt=(0,r.memo)(function({mode:e,mobile:t,fileBrowser:s,pluginTabContent:a,pluginHeaderActions:i=[],pluginSessionTabs:l,fileRefreshLoading:o,canBrowseFiles:d,workSessions:c,focusedWorkId:u,pinnedCount:m,ordering:p,deletingWorkId:h,canReplace:g,disabled:x,pluginApplications:w,settingsAttention:y,notifications:k,onConsumeNotification:j,onDismissNotification:N,onModeChange:I,onRefreshFiles:S,onPreviewProject:M,onOpenTerminal:z,onCreate:E,onReplace:A,onSettings:$,onOpenPluginApplication:R,onSelect:T,onTogglePin:P,onDelete:D,onRename:O,syncingWorkIds:L,onReloadChat:F,onArrangementChange:_}){let{t:B}=(0,f.Bd)("workbench"),[q,W]=(0,r.useState)(null),Y=(0,r.useRef)(null),H=(0,r.useRef)(3),[G,J]=(0,r.useState)(3),Q=(0,aA.FR)((0,aA.MS)(aA.cA,{activationConstraint:{distance:6}}),(0,aA.MS)(aA.IG,{activationConstraint:{delay:250,tolerance:8}}),(0,aA.MS)(aA.uN,{coordinateGetter:a$.JR}));(0,r.useEffect)(()=>{let e=()=>W(Date.now());e();let t=window.setInterval(e,6e4);return()=>window.clearInterval(t)},[]);let X=[{key:"sessions",label:B("sidebarSessions"),icon:(0,n.jsx)(mR.A,{}),pressed:"sessions"===e,testId:"sidebar-mode-sessions",onSelect:()=>I("sessions")},{key:"files",label:B("sidebarFiles"),icon:(0,n.jsx)(sL.A,{}),pressed:"files"===e,testId:"sidebar-mode-files",onSelect:()=>I("files")},...l.map(t=>{let s=h1(t.pluginName,t.contributionName);return{key:`${t.pluginName}:${t.contributionName}`,label:t.label,icon:(0,n.jsx)(e_,{icon:t.icon}),disabled:!d,pressed:e===s,onSelect:()=>I(s)}})],Z="sessions"===e?[{key:"replace",label:B("sidebarReplaceSession"),disabled:x||!g,busy:x,testId:"sidebar-replace-work-session",icon:(0,n.jsx)(hF.A,{}),onSelect:A},{key:"create",label:B("createSession"),disabled:x,busy:x,testId:"sidebar-create-work-session",icon:(0,n.jsx)(U.A,{}),onSelect:E}]:"files"===e?[{key:"new-terminal",label:B("newTerminal"),disabled:x,icon:(0,n.jsx)(v.A,{}),testId:"project-files-terminal-open",onSelect:z},{key:"preview-project",label:B("projectPreview"),disabled:!d,icon:(0,n.jsx)(h_.A,{}),testId:"project-preview-open",onSelect:M},{key:"refresh-files",label:B("refreshFiles"),disabled:!d||o,icon:o?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(et.A,{}),busy:o,testId:"project-files-refresh",onSelect:S}]:i.map((e,t)=>({key:String(t),label:e.label,icon:e.busy?(0,n.jsx)(b.A,{className:"animate-spin"}):(0,n.jsx)(e_,{icon:e.icon}),disabled:e.disabled||e.busy,busy:e.busy,onSelect:()=>{e.onSelect()}}));(0,r.useLayoutEffect)(()=>{let e=Y.current;if(!e)return;let t=e=>{let t=Math.max(1,Math.floor(e/56));H.current!==t&&(H.current=t,J(t))};t(e.clientWidth);let s=new ResizeObserver(([s])=>{t(s?.contentRect.width??e.clientWidth)});return s.observe(e),()=>s.disconnect()},[]);let ee=(0,r.useMemo)(()=>c.map(e=>e.workId),[c]),es=(0,r.useMemo)(()=>hS(ee,m),[m,ee]),en=(0,r.useMemo)(()=>new Map(c.map(e=>[e.workId,e])),[c]),er=(0,r.useMemo)(()=>new Set(ee.slice(0,m)),[m,ee]),{visiblePluginApplications:ea,overflowPluginApplications:ei,shortcutRowItemCounts:el}=(0,r.useMemo)(()=>{var e;let s,n,r,a,i,l,o,d=t?2:3,c=(e=w.length,i=Math.ceil((a=(r=(n=e+1>(s=G*d))?Math.max(0,s-2):e)+1+ +!!n)/G),l=Math.floor(a/i),o=a%i,{visibleApplicationCount:r,rowItemCounts:Array.from({length:i},(e,t)=>l+ +(t<o))});return{visiblePluginApplications:w.slice(0,c.visibleApplicationCount),overflowPluginApplications:w.slice(c.visibleApplicationCount),shortcutRowItemCounts:c.rowItemCounts}},[t,w,G]),eo=(0,r.useCallback)(e=>{if(p||!e.over||e.active.id===e.over.id)return;let t=String(e.active.id),s=function(e,t,s,n){if(hz(e,t),s===n||s===hC)return null;let r=hS(e,t),a=r.indexOf(s),i=r.indexOf(n);if(a<0||i<0)return null;if(0>r.indexOf(hC))return{workIds:hM(r,a,i),pinnedCount:t};let l=e.indexOf(s)<t,o=n===hC?function(e,t,s){let n=[...e],[r]=n.splice(t,1);if(!r)return n;let a=n.indexOf(hC);return a<0?[...e]:(n.splice(s?a:a+1,0,r),n)}(r,a,l):hM(r,a,i),d=o.indexOf(hC);if(d<0)return null;let c=o.slice(0,d),u=o.slice(d+1),m=[...u,...c];return m.length!==e.length||new Set(m).size!==e.length?null:{workIds:m,pinnedCount:u.length}}(ee,m,t,String(e.over.id));s&&_(s,t)},[_,p,m,ee]),ed=es.map(e=>{if(e===hC)return(0,n.jsx)(ge,{id:e,label:B("pinnedBelow")},e);let s=en.get(e);return s?(0,n.jsx)(h9,{workSession:s,mobile:t,selected:s.workId===u,pinned:er.has(s.workId),deleting:h===s.workId,disabled:x,ordering:p,now:q,onSelect:T,onTogglePin:P,onDelete:D,onRename:O,syncing:L.includes(s.workId),onReloadChat:F},s.workId):null}),ec=[(0,n.jsxs)("button",{type:"button",title:B("settings"),"aria-label":B("error"===y?"settingsWarning":"settings"),onClick:$,className:h5,children:[(0,n.jsx)(ez.A,{className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full truncate text-center",children:B("settings")}),y?(0,n.jsx)("span",{"aria-hidden":"true",className:(0,C.cn)("absolute right-1.5 top-1.5 size-2 rounded-full ring-2 ring-sidebar","error"===y?"bg-destructive":"bg-primary")}):null]},"settings"),...ea.map(e=>(0,n.jsxs)("button",{type:"button",disabled:x,title:e.label,onClick:()=>R(e),className:h5,children:[(0,n.jsx)(e_,{icon:e.icon,className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full line-clamp-2 break-words text-center leading-4",children:e.label})]},`${e.pluginName}:${e.contributionName}`))];ei.length>0&&ec.push((0,n.jsxs)(K.rI,{children:[(0,n.jsxs)(K.ty,{render:(0,n.jsx)("button",{type:"button",disabled:x,title:B("more"),"aria-label":B("moreShortcuts"),className:h5}),children:[(0,n.jsx)(V.A,{className:"size-5 shrink-0"}),(0,n.jsx)("span",{className:"w-full truncate text-center",children:B("more")})]}),(0,n.jsx)(K.SQ,{align:"end",side:"top",className:"w-56",children:ei.map(e=>(0,n.jsxs)(K._2,{disabled:x,onClick:()=>R(e),className:"py-2",children:[(0,n.jsx)(e_,{icon:e.icon,className:"size-4"}),(0,n.jsx)("span",{className:"min-w-0 truncate",children:e.label})]},`${e.pluginName}:${e.contributionName}`))})]},"more"));let eu=el.map((e,t)=>{let s=el.slice(0,t).reduce((e,t)=>e+t,0);return(0,n.jsx)("div",{className:"flex justify-evenly",children:ec.slice(s,s+e)},`shortcut-row:${s}`)});return(0,n.jsxs)("aside",{className:"flex h-full w-full min-w-0 flex-col bg-sidebar text-sidebar-foreground",children:[(0,n.jsx)(h8,{modeItems:X,actionItems:Z}),(0,n.jsx)(hB.V,{"data-testid":"work-session-list",className:(0,C.cn)("min-h-0 flex-1","sessions"!==e&&"hidden"),viewportClassName:"p-2 data-[has-overflow-y]:pr-4",children:0===c.length?(0,n.jsx)("p",{className:"px-2 py-5 text-center text-sm leading-6 text-muted-foreground",children:B("noSessions")}):(0,n.jsx)(aA.Mp,{sensors:Q,collisionDetection:aA.fp,onDragEnd:eo,children:(0,n.jsx)(a$.gB,{items:es,strategy:a$._G,children:(0,n.jsx)("div",{className:"flex flex-col gap-1",children:ed})})})}),(0,n.jsx)("div",{className:(0,C.cn)("min-h-0 flex-1 overflow-hidden","files"!==e&&"hidden"),children:s??(0,n.jsx)("div",{className:"flex h-full items-center justify-center p-5 text-center text-sm text-muted-foreground",children:B("selectSessionFirst")})}),e.startsWith("plugin:")?(0,n.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:a}):null,(0,n.jsx)(hG,{mobile:t,notifications:k,onConsume:j,onDismiss:N}),(0,n.jsx)("footer",{"data-testid":"sidebar-shortcuts",className:"shrink-0 px-2 py-1.5","aria-label":B("shortcuts"),children:(0,n.jsx)("div",{ref:Y,className:"flex flex-col gap-1",children:eu})})]})});gt.displayName="L2WorkSessionSidebar";let gs={primaryWorkId:null},gn={mode:"normal",notifications:[],plugins:{},capabilityModes:{},settings:{region:{locale:"en",timeZone:"UTC"}}};function gr(e){let t=window.matchMedia("(max-width: 1023px)");return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function ga(){return window.matchMedia("(max-width: 1023px)").matches}function gi(e,t){return e instanceof Error?e.message:t}function gl(e){let t=r3.safeParse(e);return t.success?t.data.directories:null}function go(e){let t=r6.safeParse(e);return t.success?t.data:null}function gd({render:e,input:t}){return e(t)}function gc({onTerminalReady:e,onTerminalDisconnected:t,onOpenTerminal:s,renderTerminalWorkspace:a,listPluginManagement:l,subscribePluginManagementChanges:o,onTaskCenterStart:d,onTaskCenterDispose:c,onTaskCenterReconcileWorkSessions:u,onTaskCenterDisconnected:m,onTaskCenterReconnected:p,renderPluginApplication:h,renderPluginSessionSidebarTab:g,renderSettings:x,renderTaskSummary:b,renderTaskMenu:v,renderPluginComposerPanel:w}){var y;let{t:k}=(0,f.Bd)("workbench"),{clientId:j,appSocket:I}=(0,er.gM)(),C=(0,Q.G)(),S=(0,J.t4)(),M=(0,J.So)(),z=(0,r.useMemo)(()=>(function(e,t){async function s(t,n,r,a="POST"){let i=await fetch(t,{method:a,..."GET"===a?{cache:"no-store"}:{},headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},...void 0===n?{}:{body:JSON.stringify(n)},...r?{signal:r}:{}}),l=await i.json();if(!i.ok||0!==l.code||null===l.data)throw Error(l.msg?(0,ed.B)(l):"请求失败");return l.data}return{async readServerVersion(e){let t=await s("/api/health",void 0,e,"GET");return cL.parse(t).version},getChatMessageDetail:e=>s("/api/chat/messages/get",e),getChatModelContext:e=>s("/api/chat/context/get",e),getChatImage:e=>s("/api/chat/images/get",e),listModels:e=>s("/api/pi/models/list",e),listPiCommands:e=>t.request(cq.QV.commandsList,e),listPiTools:e=>t.request(cq.QV.toolsList,e),sendChat:e=>t.request(cF.P6.send,e),async interruptChat(e){await t.request(cF.P6.interrupt,e)},restoreChatQueue:e=>t.request(cF.P6.queueRestore,e),async setChatModel(e){await t.request(cF.P6.modelSet,e)},async setChatCapabilityMode(e){await t.request(cF.P6.capabilityModeSet,e)},invokePluginMethod:e=>t.request(c_.OY.invoke,e),listWorkSessions:()=>t.request(cB.kM.list,{}),async applyAppRuntimeUpdate(e){await t.request(nB.apply,e)},sortWorkSessions:e=>s("/api/work-sessions/sort",e),deleteWorkSession:e=>s("/api/work-sessions/del",{workId:e}),async renameWorkSession(e){await s("/api/work-sessions/rename",e)},async listDirectories(e){let t=await s("/api/pi/directories/list",{forceRefresh:e});return ap(t),t},async listIgnoredDirectories(e){let t=await s("/api/pi/directory-ignores/list",{forceRefresh:e});return au(),ai=t,am(as,t),t},async replaceDirectoryIgnore(e){await s("/api/pi/directory-ignores/replace",e)},async listDirectoryEntries(e){let t=await s("/api/pi/directory-entries/list",{cwd:e});return!function(e){let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.cwd;if("string"==typeof t||null===t)return t}(e);if(void 0===t)return;ah();let s=ad(t);for(ao.delete(s),ao.set(s,e);ao.size>64;){let e=ao.keys().next().value;if(void 0===e)break;ao.delete(e)}am(an,{entries:Object.fromEntries(ao)})}(t),t},listSessionHistory:(e,t)=>s("/api/pi/sessions/list",e,t),listSessionUserMessages:(e,t)=>s("/api/pi/session-user-messages/list",e,t),createWorkSession:e=>s("/api/work-sessions/add",e),replaceWorkSession:e=>s("/api/work-sessions/replace",e),getWorkSessionTree:(e,t)=>s("/api/work-session-tree/get",e,t),getWorkSessionTreeEntry:(e,t)=>s("/api/work-session-tree-entry/get",e,t),branchWorkSession:e=>s("/api/work-sessions/branch",e),async acknowledgeCompleted(e){await t.request(cB.kM.acknowledgeCompleted,{workId:e})},async readWorkSessionUpdates(s,n,r,a){let l=t.subscribe(cB.kM.update,r),o=t.subscribe(nB.update,a),d=()=>void 0,c=new Promise(e=>{let t=()=>e({code:1e3,reason:"页面业务已卸载"});s.addEventListener("abort",t,{once:!0}),d=()=>s.removeEventListener("abort",t)});try{let e=await t.connect(s);if(s.aborted)return await c;let r=await t.request(cB.kM.list,{});if(s.aborted)return await c;await n(r,e);let a=await Promise.race([t.waitForClose(),c]);return s.aborted||a.code!==i.Sp||window.location.replace("/login"),a}catch(t){if(!s.aborted){let t=await fetch("/api/auth-settings/get",{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:"{}",signal:s}).catch(()=>null);t?.status===401&&window.location.replace("/login")}throw t}finally{d(),o(),l()}}}})(j,I),[I,j]),E=(0,r.useMemo)(()=>{var e,t;let s,n,r;return e=z.readServerVersion,t=()=>{window.location.reload()},s=!1,n=null,r=!1,async(a,i,l)=>{if(i.aborted)return;let o=s&&a;if(s=!0,!o||r)return;n?.abort();let d=new AbortController;n=d;let c=()=>d.abort();i.addEventListener("abort",c,{once:!0}),l.then(c,c);let u=setTimeout(c,5e3);try{let s=await e(d.signal);if(d.signal.aborted||!s||s===s_||r)return;r=!0,t()}catch(e){d.signal.aborted||console.warn("[Pi Desk][VersionRefresh] 重连版本检查失败,保留当前页面",{message:e instanceof Error?e.message:String(e)})}finally{clearTimeout(u),i.removeEventListener("abort",c),n===d&&(n=null)}}},[z]),A=(0,r.useRef)([]),$=(0,r.useRef)(0),R=(0,r.useRef)(gn),T=(0,r.useRef)(!1),P=(0,r.useRef)(null),D=(0,r.useRef)(0),O=(0,r.useRef)(!0),L=(0,r.useRef)(new Set),F=(0,r.useRef)(new Set),_=(0,r.useSyncExternalStore)(gr,ga,()=>!0),B=(0,r.useSyncExternalStore)(rg,rp,rp),q=(0,r.useMemo)(()=>({list:(e,t)=>(0,ua.QL)(j,cC.Xe,cE.parse(e),t),search:(e,t)=>(0,ua.QL)(j,cC.fg,cA.parse(e),t),get:(e,t)=>(0,ua.QL)(j,cC.ZI,cT.parse(e),t),reveal:e=>(0,ua.QL)(j,cC.Ot,c$.parse(e))}),[j]),W=(0,r.useMemo)(()=>(function(e){async function t(t,s,n,r){let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s),signal:r}),i=await a.json();if(!a.ok||0!==i.code||null===i.data)throw Error(i.msg?(0,ed.B)(i):"Git 请求失败");return n.parse(i.data)}return{getHeads:(t,s)=>(0,ua.QL)(e,cC._X,t,s),get:(t,s)=>(0,ua.QL)(e,cC.p0,{...ub.parse(t),refresh:!0},s),listBranches:async(t,s)=>{let{head:n,recent:r,local:a,remote:i}=await (0,ua.QL)(e,cC.ry,uj.parse(t),s);return{head:n,recent:r,local:a,remote:i}},replaceBranch:(e,s)=>t("/api/work-session-git-branch/replace",uI.parse(e),uS,s),addBranch:(e,s)=>t("/api/work-session-git-branch/add",uC.parse(e),uS,s),getDiff:async(t,s)=>{let n=await (0,ua.QL)(e,cC.OC,uM.parse(t),s);return"metadata"===n.kind?{kind:"binary"}:n}}})(j),[j]),[Y]=(0,r.useState)(()=>new cJ(q,W,e=>{C.show({level:"info",title:e})})),[U]=(0,r.useState)(()=>new ug(W,(e,t)=>{Y.handleGitBranchChanged(e,t)}));(0,r.useSyncExternalStore)(Y.subscribe.bind(Y),Y.getRevision,Y.getRevision);let[V,K]=(0,r.useState)([]),[H,G]=(0,r.useState)(0),[X,Z]=(0,r.useState)(gn),[ee,et]=(0,r.useState)(gs),[es,en]=(0,r.useState)(!1),[ea,ei]=(0,r.useState)(null),[el,eo]=(0,r.useState)(!0),[ec,eu]=(0,r.useState)(!1),em=(0,r.useRef)(ec);(0,r.useEffect)(()=>{em.current=ec},[ec]);let ep=(0,r.useCallback)(()=>{em.current=!1,eu(!1)},[]),[eh,eg]=(0,r.useState)("sessions"),[ex,ef]=(0,r.useState)(null),[eb,ev]=(0,r.useState)(!1),[ew,ey]=(0,r.useState)(!1),[ek,ej]=(0,r.useState)(),[eN,eI]=(0,r.useState)(null),[eC,eS]=(0,r.useState)(null),[eM,ez]=(0,r.useState)(null),[eE,eA]=(0,r.useState)(null),[e$,eR]=(0,r.useState)(null),eT=(0,r.useCallback)(()=>{ez(null)},[]),[eP,eD]=(0,r.useState)("initial"),eO="ready"!==eP,eL=function(e,t){let{t:s}=(0,f.Bd)("workbench"),[n,a]=(0,r.useState)(null),[i,l]=(0,r.useState)(""),[o,d]=(0,r.useState)(!1),[c,u]=(0,r.useState)(null),m=(0,r.useCallback)(e=>{a({workId:e.workId,sessionId:e.sessionId}),l(e.sessionTitle??""),u(null)},[]),p=async()=>{let r=i.trim();if(n&&!o&&!t&&r){d(!0),u(null);try{await e.renameWorkSession({...n,title:r}),a(null)}catch(e){u(e instanceof Error?e.message:s("renameSessionFailed"))}finally{d(!1)}}};return{open:null!==n,title:i,saving:o,error:c,show:m,close:()=>{o||a(null)},setTitle:l,save:p}}(z,eO),[eF,e_]=(0,r.useState)(!1),[eB,eq]=(0,r.useState)(null),[eW,eY]=(0,r.useState)(!1),[eU,eV]=(0,r.useState)(null),[eK,eH]=(0,r.useState)("directories"),[eG,eJ]=(0,r.useState)(null),[eQ,eX]=(0,r.useState)(null),[eZ,e0]=(0,r.useState)([]),[e1,e2]=(0,r.useState)([]),[e5,e3]=(0,r.useState)(null),[e4,e6]=(0,r.useState)(!1),[e8,e7]=(0,r.useState)(!1),[e9,te]=(0,r.useState)(!1),[tt,ts]=(0,r.useState)(null),[tn,tr]=(0,r.useState)(null),[ta,ti]=(0,r.useState)(null),[tl,to]=(0,r.useState)(null),[td,tc]=(0,r.useState)(null),{sessions:tu,loading:tm,load:tp,cancel:th,showCached:tg}=function(e,t){let{t:s}=(0,f.Bd)("workbench"),[n,a]=(0,r.useState)([]),[i,l]=(0,r.useState)(!1),o=(0,r.useRef)(0),d=(0,r.useRef)(null),c=(0,r.useRef)(new Map);(0,r.useEffect)(()=>()=>{o.current+=1,d.current?.abort(),d.current=null},[]);let u=(0,r.useCallback)(()=>{o.current+=1,d.current?.abort(),d.current=null,l(!1)},[]),m=(0,r.useCallback)(e=>{a(c.current.get(e)?.base??[])},[]);return{sessions:n,loading:i,load:(0,r.useCallback)(async(n,r="",i=hP,u=!1)=>{let m=++o.current;d.current?.abort(),d.current=null;let p=r.trim(),h=c.current.get(n),g=hD(i)&&!p?h?.base:h?.recent?.query===p&&h.recent.searchIn.length===i.length&&h.recent.searchIn.every(e=>i.includes(e))?h.recent.sessions:null;if(g&&!u){a(g),l(!1),t(null);return}g&&a(g);let x=new AbortController;d.current=x,l(!0),t(null);try{let t=await e.listSessionHistory({cwd:n,query:p,forceRefresh:u,searchIn:[...i]},x.signal);if(o.current!==m)return;let s=c.current.get(n)??{base:null,recent:null};for(hD(i)&&!p?s.base=t.sessions:s.recent={query:p,searchIn:[...i],sessions:t.sessions},c.current.delete(n),c.current.set(n,s);c.current.size>8;){let e=c.current.keys().next().value;if(!e)break;c.current.delete(e)}a(t.sessions)}catch(e){if(o.current!==m||e instanceof Error&&"AbortError"===e.name)return;t(e instanceof Error?e.message:s("historyFailed"))}finally{o.current===m&&(d.current===x&&(d.current=null),l(!1))}},[t,e,s]),cancel:u,showCached:m}}(z,tc),[tx,tf]=(0,r.useState)(null),[tb,tv]=(0,r.useState)(0),tw=(0,r.useRef)(null),ty=(0,r.useRef)(0),tk=(0,r.useRef)(0),tj=(0,r.useRef)(0),tN=(0,r.useRef)(null),tI=(0,r.useRef)(0),tC=(0,r.useMemo)(()=>(function(e,t,s={async readMessages(e){let t=uz.Pi.parse(e),s=(await uY()).transaction(uR,"readonly"),n=uK(s),r=await uU(s.objectStore(uR).index(uT).getAll(IDBKeyRange.only([t.sessionId,t.branchId])));return await n,r.map(uJ).sort((e,t)=>e.location.index-t.location.index)},async readLatestCursor(e){try{let t=await this.readMessages(e),s=uA(t);return null===s&&t.length>0&&await this.clearSource(e),s}catch(t){return console.warn("[Pi Desk][WorkbenchChatRepository] 本地消息缓存无效,回退全量同步",{sessionId:e.sessionId,branchId:e.branchId,errorName:t instanceof Error?t.name:"UnknownError"}),await this.clearSource(e),null}},async replaceMessages(e,t){let s=uz.Pi.parse(e),n=(await uY()).transaction(uR,"readwrite"),r=uK(n),a=n.objectStore(uR);for(let e of(uQ(a,s),t))a.put(uG(s,e));await r},async appendMessage(e,t){let s=uz.Pi.parse(e),n=uG(s,t),r=(await uY()).transaction(uR,"readwrite"),a=uK(r),i=r.objectStore(uR),l=[n.sessionId,n.branchId,n.index],o=i.get(l),d=null;if(o.addEventListener("success",()=>{if(void 0===o.result)return void i.add(n);let e=uH.safeParse(o.result);if(e.success&&e.data.entryId===n.entryId)return;let t=e.success?e.data.entryId:"invalid-record";d=Error(`IndexedDB 消息身份冲突:${n.index}/${n.entryId}/${t}`),uQ(i,s)},{once:!0}),await a,d)throw d},async saveDetail(e,t,s,n){let r=uz.Pi.parse(e),a=uz.wI.parse(n),i=(await uY()).transaction(uR,"readwrite"),l=uK(i),o=i.objectStore(uR),d=[r.sessionId,r.branchId,t],c=await uU(o.get(d)),u=uH.parse(c);if(u.entryId!==s)throw i.abort(),await l.catch(()=>void 0),Error(`IndexedDB 消息身份不匹配:${t}/${s}`);let{detail:m,...p}=u;o.put(null===a?p:{...p,detail:a}),await l},async clearSource(e){let t=uz.Pi.parse(e),s=(await uY()).transaction(uR,"readwrite"),n=uK(s);uQ(s.objectStore(uR),t),await n}}){let n=new u7(e),r=new Map,a=new Map,i=new Map,l=new Map,o=new Map,d=new Map,c=new Map,u=new Map,m=new Map,p=new Set,h=new Set,g=!1,x=0,f=null,b=()=>void 0,v=null,w=!1,y=()=>{for(let e of[...p])try{e()}catch(e){console.error("[Pi Desk][WorkbenchChat] 消息状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},k=(e=!1)=>{if(e){if(v)return;v=setTimeout(()=>{v=null,y()},50);return}v&&clearTimeout(v),v=null,y()},j=(e,t,s=!1)=>{i.set(mt(e),t),k(s)},N=e=>{let t=r.get(e.workId),s=a.get(e.workId);return void 0!==t&&void 0!==s&&ms(t,e)&&ms(me(s),e)},I=(e,t)=>{let s=mt(e),n=(u.get(s)??Promise.resolve()).then(t,t);u.set(s,n);let r=()=>{u.get(s)===n&&u.delete(s)};return n.then(r,r),n},C=e=>{let t=`${mt(e)}\u0000`;for(let e of c.keys())e.startsWith(t)&&c.delete(e)},S=async(t,n=!1)=>{if(!g||0===t.length||w)return;let r=x,a=t.filter(e=>N(e)&&!l.has(mt(e))).map(e=>{let t=mt(e),s={};l.set(t,s);let n=i.get(t);return n&&i.set(t,{...n,syncStatus:"syncing"}),{source:e,token:s}});if(0===a.length)return;k();let o=({source:e,token:t})=>!w&&g&&r===x&&N(e)&&l.get(mt(e))===t;try{let t=(await Promise.all(a.map(async e=>({...e,cursor:n?null:await s.readLatestCursor(e.source)})))).filter(o).map(({source:e,cursor:t})=>({source:e,cursor:t}));if(0===t.length)return;await e.request(cF.P6.subscribe,{subscriptions:t})}catch(t){let e=a.filter(o);for(let{source:t}of e)l.delete(mt(t));if(e.length>0)throw t}},M=async e=>{let t=mt(e),n=i.get(t);return n||uz.oc.parse({messages:await s.readMessages(e),temporaryMessages:[],runtime:uE.runtime})},z=async e=>{N(e)&&g&&!w&&(l.delete(mt(e)),await S([e],!0))},E=async e=>{let{epoch:t,push:n}=e,{source:r,event:a}=n,o=mt(r),d=l.get(o),c=()=>!w&&g&&t===x&&N(r)&&l.get(o)===d;if(!c()||"session_sync"!==a.type&&(d||!i.has(o)))return!1;if("session_sync"===a.type&&"full"===a.mode){C(r);let e=i.get(o);e&&j(r,{...e,syncStatus:"syncing"})}let u="session_sync"===a.type&&"full"===a.mode?i.get(o)??u9:await M(r);if(!c())return!1;if("session_sync"===a.type&&"incremental"===a.mode){let e=u.messages.at(-1);if(e?.location.index!==a.baseCursor.index||e.location.entryId!==a.baseCursor.entryId){let e=await s.readMessages(r);if(!c())return!1;let t=e.slice(0,a.baseCursor.index+1),n=uA(t);if(n?.index!==a.baseCursor.index||n.entryId!==a.baseCursor.entryId)throw Error(cV("chatCacheMismatch"));u={...u,messages:t}}}let m=function(e,t){if("session_sync"===t.type){if("full"===t.mode)return{...cf(e,t.messages,t.temporaryMessages),runtime:t.runtime};let s=e.messages.at(-1);if(!s||s.location.index!==t.baseCursor.index||s.location.entryId!==t.baseCursor.entryId)throw Error("Incremental chat sync does not match the current durable cursor");let n=new Set(e.messages.map(e=>e.location.entryId));for(let e of t.messages){if(n.has(e.location.entryId))throw Error(`Incremental chat sync contains a duplicate entryId: ${e.location.entryId}`);n.add(e.location.entryId)}return{messages:[...e.messages,...t.messages],temporaryMessages:t.temporaryMessages,runtime:t.runtime}}return"runtime_update"===t.type?{...e,runtime:t.runtime}:{...cb(e,t),runtime:e.runtime}}(u,a);if("session_sync"===a.type)await I(r,async()=>{c()&&await s.replaceMessages(r,m.messages)});else if("message_commit"===a.type){let e=m.messages.at(-1);if(!e||e.location.index!==a.durable.index||e.location.entryId!==a.durable.entryId)throw Error(`Chat commit result is missing: ${a.durable.index}/${a.durable.entryId}`);await I(r,async()=>{c()&&await s.appendMessage(r,e)})}if(!c())return!1;for(let e of("session_sync"===a.type&&l.delete(o),j(r,{...m,syncStatus:"session_sync"===a.type?"syncing":i.get(o).syncStatus},"message_update"===a.type),[...h]))try{e(n,m)}catch(e){console.error("[Pi Desk][WorkbenchChat] Source 事件观察器执行失败",{eventType:a.type,errorName:e instanceof Error?e.name:"UnknownError"})}return!0},A=async(e,t)=>{if(!t.processing){t.processing=!0;try{for(;!w&&d.get(e)===t;){let e=t.pushes.shift();if(!e)break;try{await E(e)&&"session_sync"===e.push.event.type&&(t.syncEpoch=e.epoch)}catch(r){if(w||e.epoch!==x||!N(e.push.source))continue;t.pushes.length=0,t.syncEpoch=null;let{push:s}=e,n="message_start"===s.event.type?s.event.snapshot.location.tempId:"location"in s.event?s.event.location.tempId:null;console.error("[Pi Desk][WorkbenchChat] 应用聊天 Source 事件失败,重新同步",{workId:s.source.workId,sessionId:s.source.sessionId,branchId:s.source.branchId,eventType:s.event.type,eventTempId:n,updateLayers:"message_update"===s.event.type?{fixed:void 0!==s.event.fixed,summary:void 0!==s.event.summary,detail:void 0!==s.event.detail,increments:void 0!==s.event.increments}:null,errorName:r instanceof Error?r.name:"UnknownError",errorMessage:r instanceof Error?r.message:String(r)});try{await z(s.source)}catch(e){b(e)}break}}}finally{if(t.processing=!1,d.get(e)!==t)return;if(0===t.pushes.length){d.delete(e);let s=i.get(e);w||!g||t.syncEpoch!==x||l.has(e)||s?.syncStatus!=="syncing"||(i.set(e,{...s,syncStatus:"ready"}),k())}else w||A(e,t)}}},$=e=>{if(w||!g||!N(e.source))return;let t=mt(e.source),s=d.get(t)??{pushes:[],processing:!1,syncEpoch:null};s.pushes.push({epoch:x,push:e}),d.set(t,s),s.processing||A(t,s)},R=e=>{for(let t of(a.clear(),e))a.set(t.workId,t);let t=!1;for(let e of[...r.values()]){let s=a.get(e.workId);s&&ms(e,me(s))||(r.delete(e.workId),i.delete(mt(e)),l.delete(mt(e)),o.delete(mt(e)),C(e),d.delete(mt(e)),t=!0)}t&&k()};return{nativeUi:n,start(t){b=t,f||(w=!1,f=e.subscribe(cF.P6.sourceEvent,$))},async applyWorkSessionsList(e){R(e),g=!0,n.ready(e.map(me)),await S([...r.values()])},reconcileWorkSessions(e){R(e),n.reconcile(e.map(me))},ensureDisplayedWorkSessions(e){(e=>{let t=[];for(let s of e){let e=me(s),n=a.get(s.workId);if(!n&&g)continue;let c=n?me(n):e;if(!ms(e,c))continue;let u=r.get(c.workId);u&&ms(u,c)||(u&&(i.delete(mt(u)),l.delete(mt(u)),o.delete(mt(u)),C(u),d.delete(mt(u))),r.set(c.workId,c),t.push(c))}0!==t.length&&(k(),g&&S(t).catch(e=>{b(e)}))})(e)},subscribe:e=>(p.add(e),()=>p.delete(e)),subscribeSourceEvents:e=>(h.add(e),()=>h.delete(e)),getSourceState(e){let t=uz.Pi.parse(e);return i.get(mt(t))??u9},getViewportSnapshot(e){let t=uz.Pi.parse(e);return o.get(mt(t))??null},saveViewportSnapshot(e,t){let s=uz.Pi.parse(e);t.messageId&&Number.isFinite(t.offset)&&o.set(mt(s),t)},clearViewportSnapshot(e){let t=uz.Pi.parse(e);o.delete(mt(t))},async loadMessageDetail(e,n,r){let a=uz.Pi.parse(e),l=(await M(a)).messages.find(e=>e.location.index===n&&e.location.entryId===r);if(!l)throw Error(cV("chatMessageMissing",{index:n,entryId:r}));if(void 0!==l.detail)return l.detail;if(!l.fixed.hasDetail)return null;if(i.get(mt(a))?.syncStatus!=="ready")throw Error(cV("sourceSyncing"));let o=x,d=`${mt(a)}\u0000${n}\u0000${r}`,u=c.get(d);if(u)return u;let m=(async()=>{let e=await t({sessionId:a.sessionId,branchId:a.branchId,entryId:r}),n=()=>!w&&x===o&&N(a)&&c.get(d)===m;if(await I(a,async()=>{if(!n())throw Error(cV("sourceSyncing"));await s.saveDetail(a,e.index,e.entryId,e.detail)}),!n())throw Error(cV("sourceSyncing"));if(N(a)&&!w){let t=i.get(mt(a));t&&j(a,{...{...cv(t,e),runtime:t.runtime},syncStatus:t.syncStatus})}return e.detail})().finally(()=>{c.get(d)===m&&c.delete(d)});return c.set(d,m),m},async compact(t){let s=uz.Pi.parse(t);if(i.get(mt(s))?.syncStatus!=="ready")throw Error(cV("sourceSyncing"));await e.request(cF.P6.compact,{source:s})},async reload(t,s){let n=uz.Pi.parse(t);if(i.get(mt(n))?.syncStatus!=="ready")throw Error(cV("sourceSyncing"));await e.request(cF.P6.reload,void 0===s?{source:n}:{source:n,mode:s})},async reloadMessages(t){let s=uz.Pi.parse(t),n=mt(s),o=a.get(s.workId);if(!o||!ms(me(o),s))throw Error(cV("reloadChatSourceChanged"));let c=i.get(n);if(!g||w||l.has(n)||c?.syncStatus==="syncing")throw Error(cV("sourceSyncing"));let u=x,m=d.get(n),p=m?.syncEpoch??null;m&&(m.syncEpoch=null),r.set(s.workId,s),j(s,{...c??u9,syncStatus:"syncing"});try{await e.request(cF.P6.subscribe,{subscriptions:[{source:s,cursor:null}]})}catch(e){if(!w&&u===x&&N(s)){m&&d.get(n)===m&&(m.syncEpoch=p);let e=i.get(n);e&&j(s,{...e,syncStatus:c?.syncStatus??"loading"})}throw console.error("[Pi Desk][WorkbenchChat] 重新加载聊天数据失败,保留已有缓存",{workId:s.workId,sessionId:s.sessionId,branchId:s.branchId,message:e instanceof Error?e.message:String(e)}),e}},async setPresentation(t,s){let n=uz.Pi.parse(t),r=mt(n),a=i.get(r);if(!a||"ready"!==a.syncStatus)throw Error(cV("sourceSyncing"));if(a.runtime.presentationMode===s)return;let l=`${r}\u0000${s}`,o=m.get(l);if(o)return o;let d=e.request(cF.P6.presentationSet,{source:n,mode:s}).then(()=>void 0).finally(()=>{m.get(l)===d&&m.delete(l)});return m.set(l,d),d},disconnected(){for(let e of(n.disconnected(),g=!1,x+=1,c.clear(),m.clear(),l.clear(),d.values()))e.pushes.length=0;let e=!1;for(let[t,s]of i)"syncing"!==s.syncStatus&&(i.set(t,{...s,syncStatus:"syncing"}),e=!0);e&&k()},dispose(){w||(n.dispose(),w=!0,g=!1,f?.(),f=null,b=()=>void 0,r.clear(),a.clear(),i.clear(),l.clear(),o.clear(),d.clear(),c.clear(),u.clear(),m.clear(),v&&clearTimeout(v),v=null,p.clear(),h.clear())}}})(I,e=>z.getChatMessageDetail(e)),[I,z]),tS=function(e,t){let{t:s}=(0,f.Bd)("workbench"),n=(0,Q.G)(),a=(0,r.useCallback)(()=>JSON.stringify(t.filter(({workId:t,sessionId:s,branchId:n})=>"syncing"===e.getSourceState({workId:t,sessionId:s,branchId:n}).syncStatus).map(e=>e.workId)),[e,t]),i=(0,r.useSyncExternalStore)(e.subscribe,a,a);return{syncingWorkIds:(0,r.useMemo)(()=>JSON.parse(i),[i]),reload:(0,r.useCallback)(t=>{let{workId:r,sessionId:a,branchId:i}=t;e.reloadMessages({workId:r,sessionId:a,branchId:i}).catch(e=>{n.error(e instanceof Error?e.message:s("reloadChatDataFailed"))})},[e,s,n])}}(tC,V),tM=(0,r.useMemo)(()=>(function(e,t,s={async recoverOutbox(e){let t=uz.Pi.parse(e),s=(await uY()).transaction([uP,uD],"readwrite"),n=uK(s),r=s.objectStore(uP),a=s.objectStore(uD),i=mr(t),[l,o]=await Promise.all([uU(r.get(i)),uU(a.get(i))]),d=mi(l),c=mi(o);if(!c)return await n,{input:d??mn,recovered:!1};let u=ml(c,d);return r.put(ma(t,u)),a.delete(i),await n,{input:u,recovered:!0}},async writeDraft(e,t){let s=uz.Pi.parse(e),n=(await uY()).transaction(uP,"readwrite"),r=uK(n),a=n.objectStore(uP);t.text||0!==t.images.length?a.put(ma(s,t)):a.delete(mr(s)),await r},async moveDraftToOutbox(e,t){let s=uz.Pi.parse(e),n=(await uY()).transaction([uP,uD],"readwrite"),r=uK(n);n.objectStore(uD).put(ma(s,t)),n.objectStore(uP).delete(mr(s)),await r},async clearOutbox(e){let t=uz.Pi.parse(e),s=(await uY()).transaction(uD,"readwrite"),n=uK(s);s.objectStore(uD).delete(mr(t)),await n},async restoreOutboxToDraft(e){let t=uz.Pi.parse(e),s=(await uY()).transaction([uP,uD],"readwrite"),n=uK(s),r=s.objectStore(uP),a=s.objectStore(uD),i=mr(t),[l,o]=await Promise.all([uU(r.get(i)),uU(a.get(i))]),d=mi(o);if(!d)throw s.abort(),await n.catch(()=>void 0),Error(cV("outboxMissing"));let c=ml(d,mi(l));return r.put(ma(t,c)),a.delete(i),await n,c},async deleteOutbox(e){await this.clearOutbox(e)},async clearSource(e){let t=uz.Pi.parse(e),s=(await uY()).transaction([uP,uD],"readwrite"),n=uK(s);s.objectStore(uP).delete(mr(t)),s.objectStore(uD).delete(mr(t)),await n}}){let n=new Map,r=new Map,a=new Set,i=new Map,l=new Set,o=0,d=new Map,c=[],u=new Map,m=new Map,p=0,h=!1,g=()=>{for(let e of[...a])try{e()}catch(e){console.error("[Pi Desk][WorkbenchChatInput] 状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},x=e=>{if("ready"!==t.getSourceState(e).syncStatus)throw Error(cV("sourceSyncing"))},f=e=>{let t=mk(e);r.set(t,e);let s=n.get(t);return s||(s={loaded:!1,loading:!1,text:"",images:[],outbox:null,notice:null,error:null,models:{status:"idle",models:[],presets:[],error:null}},n.set(t,s)),s},b=(e,t)=>{let s=t(f(e));return n.set(mk(e),s),g(),s},v=(e,t)=>{let n=mk(e);o+=1;let a=(i.get(n)??Promise.resolve()).then(()=>s.writeDraft(e,t)).then(()=>{l.delete(n)}).catch(t=>{l.add(n),console.error("[Pi Desk][WorkbenchChatInput] Draft 写入失败",{workId:e.workId,errorName:t instanceof Error?t.name:"UnknownError"}),r.has(n)&&b(e,e=>({...e,error:cV("draftSaveFailed")}))}).finally(()=>{i.get(n)===a&&i.delete(n)});i.set(n,a)},w=e=>{v(e,mj(f(e)))},y=()=>{for(;!h&&p<2&&c.length>0;){let e=c.shift();p+=1,e().finally(()=>{p-=1,y()})}},k=(e,t)=>{c.push(async()=>{let s=n.get(mk(e)),r=s?.images.find(e=>e.localId===t);if(r&&"optimizing"===r.status)try{let s=await mb(r),a=n.get(mk(e)),i=a?.images.findIndex(e=>e.localId===t)??-1;if(!a||i<0)return;let l=URL.createObjectURL(s.blob);URL.revokeObjectURL(a.images[i].objectUrl);let o=[...a.images];o[i]={...o[i],...s,objectUrl:l,status:"ready",error:null},n.set(mk(e),{...a,images:o,error:null}),w(e),g()}catch(i){let s=n.get(mk(e)),r=s?.images.findIndex(e=>e.localId===t)??-1;if(!s||r<0)return;let a=[...s.images];a[r]={...a[r],status:"error",error:mN(i,cV("imageProcessFailed"))},n.set(mk(e),{...s,images:a}),w(e),g()}}),y()},j=()=>{let e=[...u.values()].reduce((e,t)=>e+t.size,0);for(let[t,s]of u){if(e<=0x4000000&&u.size<=64)break;s.references>0||(URL.revokeObjectURL(s.url),u.delete(t),e-=s.size)}},N=e=>{let t=mk(e),s=n.get(t);for(let e of(s&&(mM(s.images),s.outbox&&mM(s.outbox.images)),n.delete(t),r.delete(t),i.delete(t),l.delete(t),d.delete(t),m.keys()))e.startsWith(`${t}\u0000`)&&m.delete(e);for(let[e,s]of[...u])e.startsWith(`${t}\u0000`)&&(URL.revokeObjectURL(s.url),u.delete(e))},I=t.subscribeSourceEvents((e,t)=>{let{source:s,event:n}=e;if("message_commit"===n.type){let e=`${mk(s)}\u0000temp\u0000${n.location.tempId}\u0000`;for(let[t,r]of[...u]){if(!t.startsWith(e))continue;let a=Number.parseInt(t.slice(e.length),10);u.delete(t),u.set(mS(s,n.durable.entryId,a),r)}g();return}if("message_discard"===n.type){let e=`${mk(s)}\u0000temp\u0000${n.location.tempId}\u0000`;for(let[t,s]of[...u])t.startsWith(e)&&(URL.revokeObjectURL(s.url),u.delete(t));g();return}if("session_sync"===n.type||"runtime_update"===n.type){let e=new Set([...t.temporaryMessages.map(e=>e.location.tempId),...t.runtime.queues.steering.map(e=>e.tempId),...t.runtime.queues.followUp.map(e=>e.tempId)]),n=`${mk(s)}\u0000temp\u0000`;for(let[t,s]of[...u]){if(!t.startsWith(n))continue;let r=t.slice(n.length).split("\0")[0];r&&e.has(r)||(URL.revokeObjectURL(s.url),u.delete(t))}}});return{subscribe:e=>(a.add(e),()=>a.delete(e)),getState:e=>f(e),async loadSource(e){let t=mk(e);if(f(e).loaded)return;let a=d.get(t);if(a)return a;let i=(async()=>{b(e,e=>({...e,loading:!0,error:null}));try{let a,i,l=await s.recoverOutbox(e);if(h||!r.has(t))return;let o=(a=l.input.images,i=cV("draftImage"),a.map((e,t)=>mw(e,`${i} ${t+1}`)));for(let s of(n.set(t,{...f(e),loaded:!0,loading:!1,text:l.input.text,images:o,notice:l.recovered?cV("uncertainRecovered"):null,error:null}),o))s.optimized||k(e,s.localId);g()}catch(t){b(e,e=>({...e,loaded:!1,loading:!1,error:mN(t,cV("draftLoadFailed"))}))}})().finally(()=>d.delete(t));return d.set(t,i),i},dismissFeedback(e){b(e,e=>({...e,notice:null,error:null}))},setText(e,t){let s=b(e,e=>({...e,text:t,notice:null,error:null}));v(e,mj(s))},async addFiles(e,t){let s=10-f(e).images.length;if(s<=0)return void b(e,e=>({...e,error:cV("imageAddLimit")}));let n=[...t].slice(0,s),r=[];for(let t of n)try{let e=await mf(t);r.push(mw(e,t.name))}catch(s){b(e,e=>({...e,error:cV("imageFileFailed",{name:t.name,error:mN(s,cV("imageUnavailable"))})}))}if(0===r.length)return;let a=b(e,e=>({...e,images:[...e.images,...r],notice:null,error:t.length>s?cV("imageAddOverflow"):null}));for(let t of(v(e,mj(a)),r))t.optimized||k(e,t.localId)},removeImage(e,t){let s=f(e).images.find(e=>e.localId===t);if(!s)return;my(s);let n=b(e,e=>({...e,images:e.images.filter(e=>e.localId!==t),error:null}));v(e,mj(n))},async send(t,r){x(t);let a=mk(t),l=f(t);if(l.outbox)throw Error(cV("resolveOutboxFirst"));if(!l.text.trim()&&0===l.images.length)throw Error(cV("emptyInput"));if(l.images.length>10)throw Error(cV("imageSendLimit"));if(l.images.some(e=>"optimizing"===e.status))throw Error(cV("imagesPending"));let o=l.images.find(e=>"error"===e.status);if(o)throw Error(o.error??cV("imageProcessingFailed"));if(l.images.reduce((e,t)=>e+t.blob.size,0)>0x1400000)throw Error(cV("imageBytesLimit"));await (i.get(a)??Promise.resolve()),x(t);let d=mj(l);await s.moveDraftToOutbox(t,d),n.set(a,{...l,text:"",images:[],outbox:{status:"sending",text:l.text,images:l.images,error:null},notice:null,error:null}),g();try{let i=await Promise.all(l.images.map(mv)),o={source:t,mode:r,text:l.text,images:i};if(new TextEncoder().encode(JSON.stringify({head:{op:"req",path:"chat/send",requestId:"00000000-0000-4000-8000-000000000000"},body:o})).byteLength>0x1f00000)throw Error(cV("messageBytesLimit"));let d=await e.sendChat(o);if(h||n.get(a)?.outbox?.images!==l.images)return;l.images.forEach((e,s)=>{u.set(mC(t,d.tempId,s),{url:URL.createObjectURL(e.blob),size:e.blob.size,references:0})}),j(),await s.clearOutbox(t);let c=n.get(a);c?.outbox?.images===l.images&&(mM(l.images),n.set(a,{...c,outbox:null,error:null})),g()}catch(r){let e,t,s=n.get(a);throw s?.outbox?.images===l.images&&n.set(a,{...s,outbox:{...s.outbox,status:(t="string"==typeof(e=r instanceof Error&&"rawMessage"in r?r.rawMessage:null)?e:mN(r,""),/WebSocket.*(?:断开|连接|替换)|请求超时|尚未连接/.test(t))?"unknown":"failed",error:mN(r,cV("sendFailed"))}}),g(),r}},async prepareForPageReload(){let e=o;return await Promise.all([...i.values()]),o===e&&!(l.size>0)&&[...n.values()].every(e=>e.outbox?.status!=="sending"&&e.outbox?.status!=="unknown")},async restoreOutbox(e){let t=mk(e);await (i.get(t)??Promise.resolve());let r=f(e);r.outbox&&(await s.restoreOutboxToDraft(e),n.set(t,{...r,text:mI(r.outbox.text,r.text),images:[...r.outbox.images,...r.images],outbox:null,notice:null,error:null}),g())},async deleteOutbox(e){let t=f(e);t.outbox&&(await s.deleteOutbox(e),mM(t.outbox.images),n.set(mk(e),{...t,outbox:null,notice:null,error:null}),g())},async interrupt(t){x(t);try{await e.interruptChat({source:t}),b(t,e=>({...e,error:null}))}catch(e){throw b(t,t=>({...t,error:mN(e,cV("interruptFailed"))})),e}},async restoreQueue(t){x(t);try{let s=await e.restoreChatQueue({source:t}),n=s.images.map((e,t)=>mw({blob:(0,cy.E)(e),mimeType:e.mimeType,width:e.width,height:e.height,optimized:!0},cV("restoredImage",{count:t+1}))),r=b(t,e=>({...e,text:mI(s.text,e.text),images:[...n,...e.images],notice:null,error:null}));v(t,mj(r))}catch(e){throw b(t,t=>({...t,error:mN(e,cV("queueRestoreFailed"))})),e}},listTools:async t=>(x(t),e.listPiTools({source:t})),async loadModels(t,s=!1){let r=f(t);if("loading"===r.models.status||!s&&"ready"===r.models.status)return;let a=b(t,e=>({...e,models:{...e.models,status:"loading",error:null}})).models,i=mk(t);try{let s=await e.listModels({workId:t.workId});if(h||n.get(i)?.models!==a)return;b(t,e=>({...e,models:{status:"ready",models:s.models,presets:s.presets,error:null}}))}catch(e){if(h||n.get(i)?.models!==a)return;b(t,t=>({...t,models:{...t.models,status:"error",error:mN(e,cV("modelCatalogFailed"))}}))}},async setModel(t,s){x(t);let n=mk(t);f(t);try{await e.setChatModel({source:t,model:s}),!h&&r.has(n)&&b(t,e=>({...e,error:null}))}catch(e){throw!h&&r.has(n)&&b(t,t=>({...t,error:mN(e,cV("setModelFailed"))})),e}},acquireMessageImage(t){if(h)throw Error(cV("imageUnavailable"));let s=t.entryId?mS(t.source,t.entryId,t.imageIndex):t.tempId?mC(t.source,t.tempId,t.imageIndex):null;if(!s)throw Error(cV("imageIdentityInvalid"));r.set(mk(t.source),t.source);let n=e=>{if(h||u.get(s)!==e)throw Error(cV("imageUnavailable"));e.references+=1,u.delete(s),u.set(s,e),j();let t=!1;return{url:e.url,release:()=>{t||(t=!0,e.references-=1,j())}}},a=u.get(s);if(a)return n(a);let i=m.get(s);if(!i){if(!t.entryId)throw Error(cV("localImagePending"));i=e.getChatImage({sessionId:t.source.sessionId,branchId:t.source.branchId,entryId:t.entryId,imageIndex:t.imageIndex}).then(e=>{if(h||m.get(s)!==i)throw Error(cV("imageUnavailable"));let t=(0,cy.E)(e),n={url:URL.createObjectURL(t),size:t.size,references:0};return u.set(s,n),n}).catch(e=>{throw console.warn("[Pi Desk][WorkbenchChatInput] 读取聊天图片失败",{entryId:t.entryId,error:mN(e,cV("imageUnavailable"))}),e}).finally(()=>{m.get(s)===i&&m.delete(s)}),m.set(s,i)}return i.then(n)},reconcileWorkSessions(e){let t=new Set(e.map(e=>mk({workId:e.workId,sessionId:e.sessionId,branchId:e.branchId})));for(let[e,n]of[...r]){if(t.has(e))continue;let r=i.get(e)??Promise.resolve();N(n),r.then(()=>s.clearSource(n),()=>s.clearSource(n)).catch(e=>{console.error("[Pi Desk][WorkbenchChatInput] 清理失效 Source 输入失败",{workId:n.workId,errorName:e instanceof Error?e.name:"UnknownError"})})}g()},dispose(){if(!h){for(let e of(h=!0,I(),c.length=0,[...r.values()]))N(e);for(let e of u.values())URL.revokeObjectURL(e.url);u.clear(),m.clear(),l.clear(),a.clear()}}}})(z,tC),[tC,z]),tz=(0,r.useRef)(null),tE=(0,r.useRef)(null),tA=(0,r.useMemo)(()=>V.slice(0,H).map(e=>e.workId),[H,V]),t$=(0,r.useMemo)(()=>M.flatMap(e=>e.contributions.flatMap(t=>"application"===t.kind?[{pluginName:e.pluginName,contributionName:t.contributionName,label:t.label,...t.icon?{icon:t.icon}:{}}]:[])),[M]),tR=(0,r.useMemo)(()=>M.flatMap(e=>e.contributions.flatMap(t=>"session-sidebar-tab"===t.kind?[{pluginName:e.pluginName,contributionName:t.contributionName,label:t.label,...t.icon?{icon:t.icon}:{}}]:[])),[M]),tT=!!(eC||eN?.loadError||eN?.plugins.some(e=>"failed"===e.status||e.operation?.phase==="failed")||S.getEntryListError()||S.getFailedEntries().length>0),tP=!!(eN?.restartRequired||eN?.plugins.some(e=>!0===e.updateAvailable)),tD=tT?"error":tP?"notice":null,tO=eM?M.find(e=>e.pluginName===eM.pluginName)?.contributions.find(e=>"application"===e.kind&&e.contributionName===eM.contributionName):void 0,tL=V.find(e=>e.workId===ea)??null,tF=tL?.cwd??null,t_=eh.startsWith("plugin:")?tR.find(e=>h1(e.pluginName,e.contributionName)===eh):void 0,tB=t_?M.find(e=>e.pluginName===t_.pluginName)?.contributions.find(e=>"session-sidebar-tab"===e.kind&&e.contributionName===t_.contributionName):void 0,tq=tL?.workId??null,tW=tL?.sessionId??null,tY=tL?.branchId??null,tU=tq&&tW&&tY?{workId:tq,sessionId:tW,branchId:tY}:null,tV=JSON.stringify([eh,tq,tW,tY,tF]),tK=(0,r.useCallback)(e=>{ef(t=>e.length>0?{targetKey:tV,actions:e}:t?.targetKey===tV?null:t)},[tV]),tH=Y.getWorkspace(ea);(0,r.useEffect)(()=>{if(!eh.startsWith("plugin:")||tL&&t_&&tB?.kind==="session-sidebar-tab")return;let e=!0;return queueMicrotask(()=>{e&&eg("sessions")}),()=>{e=!1}},[t_,tB,tL,eh]);let tG=(0,r.useMemo)(()=>{let e=V.find(e=>e.workId===eG);return e?{projectName:e.projectName,sessionTitle:e.sessionTitle,sessionId:e.sessionId}:null},[eG,V]),tJ=(0,r.useMemo)(()=>V.filter(e=>e.workId!==eG).map(e=>e.sessionId),[eG,V]),tQ=(0,r.useCallback)(e=>{eI(e),eS(null);let t=e.plugins.some(e=>null!==e.operation&&"failed"!==e.operation.phase&&"waiting"!==e.operation.phase);t||S.refreshEntries().catch(()=>void 0),S.setEntriesMaintaining(t)},[S]),tX=(0,r.useCallback)(()=>{tN.current&&clearTimeout(tN.current);let e=++tI.current,t=15,s=n=>{tN.current=setTimeout(()=>{tN.current=null,tI.current===e&&l().then(t=>{tI.current===e&&tQ(t)}).catch(n=>{if(tI.current===e){if((t-=1)>0)return void s(2e3);eS(n instanceof Error?n.message:k("pluginRestoreFailed"))}})},n)};s(1500)},[tQ,l,k]),tZ=(0,r.useCallback)(e=>{P.current!==e&&(P.current=e,D.current=0,ei(e))},[]),t0=(0,r.useCallback)(e=>{eO||F.current.has(e)||(F.current.add(e),z.acknowledgeCompleted(e).catch(t=>{console.warn("[Pi Desk][Workbench] 确认工作会话完成状态失败",{workId:e,message:gi(t,"请求失败")})}).finally(()=>{F.current.delete(e)}))},[eO,z]),t1=(0,r.useCallback)(e=>{var t;let s,n=(t=A.current,s=new Map(e.workSessions.map(e=>[e.workId,e])),t.flatMap(e=>{let t=s.get(e.workId);return t&&t.cwd===e.cwd&&t.sessionId===e.sessionId?[]:[e.workId]})),r=new Set(e.workSessions.map(e=>e.workId)),a=n.filter(e=>!L.current.has(e)||!r.has(e));T.current=!0,S.replaceWorkSessions(e.workSessions),A.current=e.workSessions,Y.reconcileWorkSessions(e.workSessions),$.current=e.pinnedCount,eA(t=>{if(!t)return null;let s=e.workSessions.find(e=>e.workId===t.source.workId);return s?.sessionId===t.source.sessionId&&s.branchId===t.source.branchId&&s.cwd===t.cwd?t:null}),K(e.workSessions),G(e.pinnedCount),et(t=>mU(t,e.workSessions,a));let i=P.current;i&&a.includes(i)&&(O.current=!1,tZ(null))},[Y,S,tZ]),t2=(0,r.useCallback)(e=>{t1(e),tC.reconcileWorkSessions(e.workSessions),tM.reconcileWorkSessions(e.workSessions),u(e.workSessions)},[t1,tM,tC,u]),t5=(0,r.useCallback)(e=>{R.current=e,Z(e),S.replaceGlobalPluginStates(e.plugins),(0,nq.UV)(e.settings)},[S]),t3=(0,r.useCallback)(e=>{t2(e),t5(e.appRuntime)},[t5,t2]),t4=(0,r.useCallback)(()=>{if(tw.current)return;eD(e=>"initial"===e?"initial":"refresh");let e=(async()=>{let e=await z.listWorkSessions();t3(e),await tC.applyWorkSessionsList(e.workSessions),tf(null),eD("ready")})().catch(e=>{tf(gi(e,k("syncFailed")))}).finally(()=>{tw.current===e&&(tw.current=null)});tw.current=e},[t3,tC,z,k]),t6=(0,r.useCallback)(e=>{try{let t=function(e,t){if("snapshot"===t.type)return cI.kg.parse({workSessions:t.workSessions,pinnedCount:t.pinnedCount});let s=e.workSessions.findIndex(e=>e.workId===t.workId);if(s<0){if("delete"===t.type)return e;throw Error(`WorkSession update target was not found: ${t.workId}`)}if("delete"===t.type)return{workSessions:e.workSessions.filter(e=>e.workId!==t.workId),pinnedCount:e.pinnedCount-Number(s<e.pinnedCount)};let n=[...e.workSessions];return n[s]=cI.MY.parse({...e.workSessions[s],...t.changes}),{workSessions:n,pinnedCount:e.pinnedCount}}({workSessions:A.current,pinnedCount:$.current},e);t2(t)}catch(e){tf(gi(e,k("workSessionUpdateInvalid"))),t4()}},[t2,t4,k]),t8=(0,r.useCallback)(e=>{try{t5(function(e,t){if("replace"===t.type)return n_.GR.parse(t.runtime);if("notifications"===t.key)return n_.GR.parse({...e,notifications:function(e,t){if("add"===t.type){if(e.some(e=>e.notificationId===t.notification.notificationId))throw Error(`Notification already exists: ${t.notification.notificationId}`);return[...e,t.notification]}let s=e.findIndex(e=>e.notificationId===t.notificationId);if(s<0)throw Error(`Notification does not exist: ${t.notificationId}`);if("delete"===t.type)return e.filter(e=>e.notificationId!==t.notificationId);let n=[...e];return n[s]={...e[s],...t.changes},n}(e.notifications,t.update)});if("settings"===t.key)return n_.GR.parse({...e,settings:t.update});if("capabilityModes"===t.key)return n_.GR.parse({...e,capabilityModes:t.update});let s={...e.plugins};if(null===t.update.state){if(!(t.update.pluginName in s))throw Error(`Plugin global state does not exist: ${t.update.pluginName}`);delete s[t.update.pluginName]}else s[t.update.pluginName]=t.update.state;return n_.GR.parse({...e,plugins:s})}(R.current,e))}catch(e){tf(gi(e,k("appRuntimeUpdateInvalid"))),t4()}},[t5,t4,k]),t7=(0,r.useCallback)(async(e=!1)=>{let t=++ty.current;e6(!0),tc(null);try{let s=await z.listDirectories(e);if(ty.current!==t)return null;return e0(s.directories),s.directories}catch(e){if(ty.current!==t)return null;return tc(gi(e,k("projectDirectoriesFailed"))),null}finally{ty.current===t&&e6(!1)}},[z,k]),t9=(0,r.useCallback)(async(e=!1)=>{let t=++tk.current;e7(!0),tc(null);try{let s=await z.listIgnoredDirectories(e);if(tk.current!==t)return;e2(s.directories)}catch(e){if(tk.current!==t)return;tc(gi(e,k("ignoredDirectoriesFailed")))}finally{tk.current===t&&e7(!1)}},[z,k]),se=(0,r.useCallback)(async e=>{let t=++tj.current;te(!0),tc(null);try{let s=await z.listDirectoryEntries(e);if(tj.current!==t)return;e3(s)}catch(e){if(tj.current!==t)return;tc(gi(e,k("browseDirectoryFailed")))}finally{tj.current===t&&te(!1)}},[z,k]);y="initial"!==eP,(0,r.useEffect)(()=>{let e;if(!y)return;let t=!0,s=!1,n=!1,r=()=>{!t||(n=!0,s||(s=!0,(async()=>{try{for(;t&&n;){n=!1;let e=await l();t&&tQ(e)}}catch(s){let e=s instanceof Error?s.message:String(s);t&&eS(e||"读取插件健康状态失败"),console.warn("[Pi Desk][Workbench] 读取插件健康状态失败",{message:e})}finally{s=!1}})()))},a=o(r);if("function"==typeof window.requestIdleCallback){let t=window.requestIdleCallback(r,{timeout:3e3});e=()=>{window.cancelIdleCallback(t)}}else{let t=window.setTimeout(r,1500);e=()=>{window.clearTimeout(t)}}return()=>{t=!1,a(),e()}},[eS,tQ,l,y,o]),(0,r.useEffect)(()=>()=>{tI.current+=1,tN.current&&clearTimeout(tN.current)},[]),(0,r.useEffect)(()=>{let e=!0;return queueMicrotask(()=>{if(!e)return;let t=function(){var e=window.localStorage.getItem(mY)??window.sessionStorage.getItem(mY);if(!e)return{primaryWorkId:null};try{let t=JSON.parse(e);if(!t||"object"!=typeof t)return{primaryWorkId:null};return{primaryWorkId:"string"==typeof t.primaryWorkId?t.primaryWorkId:null}}catch{return{primaryWorkId:null}}}();et(T.current?mU(t,A.current):t),en(!0)}),()=>{e=!1}},[]),(0,r.useEffect)(()=>{cX(Y,U,V,ea)},[Y,ea,U,V]),(0,r.useEffect)(()=>(function(e,t,s,n,r){let a=e.subscribeSourceEvents(({source:e,event:a},i)=>{("session_sync"===a.type||"runtime_update"===a.type)&&(t.applyPreviewDirectories(e,(0,cW.D)(i.runtime.plugins[cW.s6])),cX(t,s,n(),r()))});for(let s of n()){let n=e.getSourceState(s);"loading"!==n.syncStatus&&t.applyPreviewDirectories(s,(0,cW.D)(n.runtime.plugins[cW.s6]))}return cX(t,s,n(),r()),a})(tC,Y,U,()=>A.current,()=>P.current),[tC,Y,U]),(0,r.useEffect)(()=>{let e={};return tE.current={token:e,fileRuntime:Y,gitRuntime:U},()=>{tE.current?.token===e&&(tE.current=null),queueMicrotask(()=>{let e=tE.current;e?.fileRuntime!==Y&&Y.dispose(),e?.gitRuntime!==U&&U.dispose()})}},[Y,U]),(0,r.useEffect)(()=>{let e={};return tz.current={token:e,chatRuntime:tC,chatInputRuntime:tM,taskCenterStart:d},tC.start(e=>{tf(gi(e,k("chatSyncFailed"))),t4()}),d(e=>{tf(gi(e,k("taskSyncFailed")))}),()=>{tz.current?.token===e&&(tz.current=null),queueMicrotask(()=>{let e=tz.current;(e?.chatRuntime!==tC||e.chatInputRuntime!==tM||e.taskCenterStart!==d)&&(c(),tM.dispose(),tC.dispose())})}},[tM,tC,t4,d,c,k]),(0,r.useEffect)(()=>{let s=new AbortController,n=null,r=null,a=async()=>{eD(e=>"initial"===e?"initial":"refresh");let r=!0;try{let n=await z.readWorkSessionUpdates(s.signal,async(n,r)=>{r&&(tC.disconnected(),m(),t()),t3(n),await tC.applyWorkSessionsList(n.workSessions),p(),e(),tf(null),eD("ready"),E(r,s.signal,I.waitForClose())},t6,t8);if(s.signal.aborted)return;tC.disconnected(),m(),t(),eD(e=>"initial"===e?"initial":"refresh"),n.code===i.Sp&&(r=!1),(0,er.p)(n)&&(r=!1,tf(k("replacedConnection")))}catch(e){if(s.signal.aborted)return;tC.disconnected(),m(),t(),console.warn("[Pi Desk][Workbench] 工作会话实时连接失败,将重新连接",{message:gi(e,"连接失败")}),T.current||tf(gi(e,k("realtimeFailed")))}!s.signal.aborted&&r&&(n=setTimeout(()=>void a(),1e3))};return r=setTimeout(()=>void a(),0),()=>{s.abort(),r&&clearTimeout(r),n&&clearTimeout(n)}},[I,t8,t3,t6,tC,E,m,p,e,t,z,k,tb]),(0,r.useEffect)(()=>{if(!es||eO||null!==ea||!O.current||!ee.primaryWorkId)return;let e=A.current.find(e=>e.workId===ee.primaryWorkId);(O.current=!1,e)?tZ(e.workId):et(e=>({...e,primaryWorkId:null}))},[ea,ee.primaryWorkId,es,eO,tZ]),(0,r.useEffect)(()=>{let e;if(!es)return;let t=new Map(V.map(e=>[e.workId,e])),s=((e=ee.primaryWorkId?[ee.primaryWorkId]:[]).push(...tA),Array.from(new Set(e))).map(e=>t.get(e)).filter(e=>void 0!==e);eb&&tL&&"files"===eh&&!s.some(e=>e.workId===tL.workId)&&s.push(tL),tC.ensureDisplayedWorkSessions(s)},[tL,tC,eb,ee,es,tA,eh,V]),(0,r.useEffect)(()=>{es&&window.localStorage.setItem(mY,JSON.stringify(ee))},[ee,es]);let st=(0,r.useCallback)(e=>{if(!A.current.find(t=>t.workId===e))return;O.current=!1;let t=A.current.slice(0,$.current).map(e=>e.workId),s=P.current===e;if(t.includes(e)&&e!==ee.primaryWorkId){s||tZ(e),_&&eu(!1);return}ee.primaryWorkId!==e&&et(t=>t.primaryWorkId===e?t:{...t,primaryWorkId:e}),s||tZ(e),_&&eu(!1)},[ee,_,tZ]),ss=(0,r.useCallback)(e=>{let t=A.current.find(t=>t.workId===e);t?.status==="completed"&&t0(e),st(e)},[t0,st]),sn=(0,r.useCallback)(async e=>{if(eO)throw Error(k("workSessionInitializing"));let t="workId"in e?A.current.find(t=>t.workId===e.workId):A.current.find(t=>t.sessionId===e.sessionId);if(t)return ss(t.workId),t;if("workId"in e||!e.cwd)throw Error(k("sessionNotFound"));let{workSession:s}=await z.createWorkSession({cwd:e.cwd,sessionId:e.sessionId});return O.current=!1,et({primaryWorkId:s.workId}),tZ(s.workId),_&&eu(!1),s},[eO,_,ss,tZ,z,k]),sr=(0,r.useCallback)(async(e,t)=>{if(eO||eF)return;let s={workSessions:A.current,pinnedCount:$.current},n=s.workSessions.findIndex(e=>e.workId===t),r=e.workIds.indexOf(t);if(n<0||r<0)return;let a=new Map(s.workSessions.map(e=>[e.workId,e])),i=e.workIds.map(e=>a.get(e)).filter(e=>void 0!==e);if(i.length!==s.workSessions.length)return;let l=n<s.pinnedCount,o=r<e.pinnedCount;t1({workSessions:i,pinnedCount:e.pinnedCount}),e_(!0),tf(null);let d=!1;try{t2(await z.sortWorkSessions(e)),d=!0}catch(e){t1(s),tf(gi(e,k("sortFailed")))}finally{e_(!1)}if(d&&l!==o){if(_){o||P.current!==t||t===ee.primaryWorkId||tZ(ee.primaryWorkId);return}if(o)return void et(e=>e.primaryWorkId===t?{primaryWorkId:null}:e);P.current===t&&tZ(ee.primaryWorkId)}},[t2,t1,ee.primaryWorkId,eO,_,eF,tZ,z,k]),sa=(0,r.useCallback)(e=>{if(eO||eF)return;let t=function(e,t,s){hz(e,t);let n=e.indexOf(s);if(n<0)return null;let r=e.filter(e=>e!==s),a=n<t,i=a?t-1:t+1;return r.splice(a?r.length:t,0,s),{workIds:r,pinnedCount:i}}(A.current.map(e=>e.workId),$.current,e);t&&sr(t,e)},[eO,eF,sr]),si=(0,r.useCallback)(async e=>{if(!eO){eq(e),tf(null);try{t2(await z.deleteWorkSession(e))}catch(e){tf(gi(e,k("deleteFailed")))}finally{eq(null)}}},[t2,eO,z,k]),sl=(0,r.useCallback)(()=>{if(eO)return;let e=gl((au(),aa));e&&e0(e),tc(null),eV("create"),eH("directories"),eJ(null),tk.current+=1,e7(!1),tj.current+=1,te(!1),th(),eX(null),eY(!0),t7().then(e=>{e?.length===0&&(eH("browser"),e3(go(ag(null))),se(null))})},[th,t7,se,eO]),so=(0,r.useCallback)(()=>{if(eO)return;let e=V.find(e=>e.workId===ea);e&&(tc(null),ty.current+=1,e6(!1),tk.current+=1,e7(!1),tj.current+=1,te(!1),eV("replace"),eH("history"),eJ(e.workId),eX(e.cwd),tg(e.cwd),eY(!0),tp(e.cwd))},[ea,tp,eO,tg,V]),sd=async(e,t)=>{if(!eO&&"create"===eU&&null===ta){ti(e),tc(null);try{await z.replaceDirectoryIgnore({cwd:e,ignored:t}),await Promise.all([t7(),t9()])}catch(e){tc(gi(e,k(t?"ignoreFailed":"restoreIgnoredFailed")))}finally{ti(null)}}},sc=(0,r.useCallback)(async e=>{let t=_?"activate":B;if("activate"===t){O.current=!1,et({primaryWorkId:e.workId}),tZ(e.workId),_&&eu(!1);return}if("pin"!==t)return;let s=function(e,t,s){hz(e,t);let n=e.indexOf(s);if(n>=0&&n<t)return null;let r=e.filter(e=>e!==s);return r.splice(t,0,s),{workIds:r,pinnedCount:t+1}}(A.current.map(e=>e.workId),$.current,e.workId);if(s){e_(!0);try{t2(await z.sortWorkSessions(s))}catch(e){tf(gi(e,k("autoPinFailed")))}finally{e_(!1)}}},[t2,_,B,tZ,z,k]),{model:su,open:sm,close:sp,retry:sh,selectEntry:sg,requestAction:sx,clone:sf,confirmRunning:sb,cancelRunning:sv,pendingWorkId:sw}=function({disabled:e,workSessions:t,workbenchBiz:s,chatInputRuntime:n,applyWorkSessionSnapshot:a,applyCreatedWorkSessionBehavior:i,focusWorkSession:l,onError:o,mobile:d}){let[c,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[x,f]=(0,r.useState)(null),[b,v]=(0,r.useState)(null),[w,y]=(0,r.useState)(!1),[k,j]=(0,r.useState)(null),[N,I]=(0,r.useState)(null),[C,S]=(0,r.useState)(null),M=(0,r.useRef)(0),z=(0,r.useRef)(null),E=(0,r.useRef)(0),A=(0,r.useRef)(null),$=(0,r.useRef)(new Map),R=(0,r.useRef)(null),T=(0,r.useCallback)(()=>{M.current+=1,z.current?.abort(),z.current=null,E.current+=1,A.current?.abort(),A.current=null,$.current.clear(),R.current=null,u(null),p(null),g(!1),f(null),v(null),y(!1),j(null),I(null)},[]),P=(0,r.useCallback)(()=>{C||T()},[C,T]);(0,r.useEffect)(()=>()=>{z.current?.abort(),A.current?.abort()},[]);let D=(0,r.useCallback)(async e=>{let t=++M.current;z.current?.abort();let n=new AbortController;z.current=n,E.current+=1,A.current?.abort(),A.current=null,$.current.clear(),u(e),p(null),g(!0),f(null),v(null),y(!1),j(null),I(null);try{let r=await s.getWorkSessionTree({workId:e.workId,sessionId:e.sessionId},n.signal);if(M.current!==t)return;p(r)}catch(e){if(M.current!==t||hA(e))return;f(hE(e,cV("treeLoadFailed")))}finally{M.current===t&&(z.current===n&&(z.current=null),g(!1))}},[s]),O=(0,r.useCallback)(s=>{if(e)return;let n=t.find(e=>e.workId===s);n?(l(s),D(hR(n))):o(cV("treeSourceInvalid"))},[e,l,D,o,t]),L=(0,r.useCallback)(()=>{c&&!e&&D(c)},[e,D,c]),F=(0,r.useCallback)(e=>{if(!c)return;let t=$.current.get(e);if(t){E.current+=1,A.current?.abort(),A.current=null,v(t),y(!1),j(null);return}let n=++E.current;A.current?.abort();let r=new AbortController;A.current=r,v(null),y(!0),j(null),s.getWorkSessionTreeEntry({workId:c.workId,sessionId:c.sessionId,entryId:e},r.signal).then(t=>{E.current===n&&($.current.set(e,t),v(t))}).catch(e=>{E.current!==n||hA(e)||j(hE(e,cV("treeDetailFailed")))}).finally(()=>{E.current===n&&(A.current===r&&(A.current=null),y(!1))})},[c,s]),_=(0,r.useCallback)(e=>{o(e)},[o]),B=(0,r.useCallback)(async(t,r)=>{if(e)return;let o="tree"===r.action?n.getState(t).text:null;S({source:t,intent:r,phase:"executing"}),f(null);try{let e=await s.branchWorkSession(function(e,t){let s={workId:e.workId,sessionId:e.sessionId};switch(t.action){case"tree":return{...s,action:"tree",entryId:t.entryId};case"fork":return{...s,action:"fork",entryId:t.entryId};case"clone":return{...s,action:"clone"}}}(t,r)),c={workSessions:e.workSessions,pinnedCount:e.pinnedCount};a(c);let u=e.workSessions.find(t=>t.workId===e.targetWorkId);if(!u)throw Error(cV("branchTargetMissing"));let m=hR(u);if("tree"===r.action){var d;l(u.workId),await n.loadSource(m),n.setText(m,(d=o??"",e.editorText??d))}else null!==e.editorText&&(await n.loadSource(m),n.setText(m,e.editorText)),await i(u);S(null),R.current=null,T()}catch(e){S(null),R.current=null,I(e=>e?{...e,waiting:!1}:null),_(hE(e,cV("branchOperationFailed")))}},[i,a,n,e,l,_,T,s]),q=(0,r.useCallback)((e,t,s)=>{S({source:e,intent:t,phase:"waiting"}),I(e=>e?{...e,waiting:!0}:e),"main_running"===s.status&&n.interrupt(e).catch(e=>{S(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),_(hE(e,cV("interruptForBranchFailed")))})},[n,_]),W=(0,r.useCallback)((s,n)=>{if(e||C)return;R.current=null;let r=t.find(e=>e.workId===s.workId);if(!r||r.sessionId!==s.sessionId||r.branchId!==s.branchId)return void _(cV("treeChanged"));if("fork"===n.action||!h$(r))return void B(s,n);let a="main_running"===r.status?"main":"background";d?q(s,n,r):(I({intent:n,reason:a,waiting:!1}),u(s),f(null))},[e,B,d,C,_,q,t]),Y=(0,r.useCallback)((e,t)=>{c&&W(c,{action:t,entryId:e})},[W,c]),U=(0,r.useCallback)(e=>{let s=t.find(t=>t.workId===e);s?W(hR(s),{action:"clone"}):o(cV("cloneUnavailable"))},[o,W,t]),V=(0,r.useCallback)(()=>{if(e||!c||!N||N.waiting||C)return;let s=t.find(e=>e.workId===c.workId);s?h$(s)?q(c,N.intent,s):B(c,N.intent):_(cV("branchUnavailable"))},[N,e,B,C,_,c,q,t]),K=(0,r.useCallback)(()=>{if(N?.waiting||C)return;let e=N?.intent.action==="clone"&&null===m;I(null),e&&T()},[N,C,T,m]);return(0,r.useEffect)(()=>{if(e||!C||"waiting"!==C.phase)return;let s=t.find(e=>e.workId===C.source.workId);if(!s){let e=`${C.source.workId}:${C.intent.action}:missing`;if(R.current===e)return;R.current=e,queueMicrotask(()=>{S(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),_(cV("branchUnavailable"))});return}if(s.sessionId!==C.source.sessionId||s.branchId!==C.source.branchId){let e=`${C.source.workId}:${C.intent.action}:changed`;if(R.current===e)return;R.current=e,queueMicrotask(()=>{S(null),R.current=null,I(e=>e?{...e,waiting:!1}:e),_(cV("branchChanged"))});return}if(h$(s))return;let n=`${C.source.workId}:${C.intent.action}:${"entryId"in C.intent?C.intent.entryId:""}`;if(R.current===n)return;R.current=n;let r=!0;return queueMicrotask(()=>{r&&B(C.source,C.intent)}),()=>{r=!1,R.current===n&&(R.current=null)}},[e,B,C,_,t]),(0,r.useEffect)(()=>{if(!c||C||N)return;let e=t.find(e=>e.workId===c.workId);if(e?.sessionId===c.sessionId&&e.branchId===c.branchId)return;let s=!0;return queueMicrotask(()=>{s&&T()}),()=>{s=!1}},[N,C,T,c,t]),{model:(0,r.useMemo)(()=>{if(!c)return null;let s=t.find(e=>e.workId===c.workId),n=s?.sessionId===c.sessionId&&s.branchId===c.branchId;return C||N||n?{workId:c.workId,tree:m,loading:h,actionsDisabled:e,pending:null!==C,error:x,detail:b,detailLoading:w,detailError:k,runningConfirmation:N}:null},[N,b,k,w,e,x,h,C,c,m,t]),open:O,close:P,retry:L,selectEntry:F,requestAction:Y,clone:U,confirmRunning:V,cancelRunning:K,pendingWorkId:C?.source.workId??null}}({disabled:eO,workSessions:V,workbenchBiz:z,chatInputRuntime:tM,applyWorkSessionSnapshot:t2,applyCreatedWorkSessionBehavior:sc,focusWorkSession:tZ,onError:(0,r.useCallback)(e=>{C.error(e)},[C]),mobile:_});(0,r.useEffect)(()=>{let e=e=>{if("Escape"!==e.key)return;if(e.defaultPrevented||e.target instanceof Element&&e.target.closest('[data-testid="file-workspace"], [role="menu"], [data-slot="app-dialog-content"]')){D.current=0;return}if(e.repeat||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.isComposing)return;if(_&&em.current){e.preventDefault(),D.current=0,ep();return}if(null!==su)return;let t=P.current;if(!t)return;if(_){D.current=0;let s=Y.getWorkspace(t),n=document.querySelector(`[data-work-id="${CSS.escape(t)}"]`);s?.windowOpen&&"files"===s.activePane&&n&&!n.closest("[inert]")&&(e.preventDefault(),Y.hideWindow(t));return}let s=Date.now();if(s-D.current>=500){D.current=s;return}e.preventDefault(),D.current=0,sm(t)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[su,ep,Y,_,sm]),(0,r.useEffect)(()=>S.bindWorkSessionCreate(async e=>{if(eO)throw Error(k("workSessionInitializing"));let{workSession:t}=await z.createWorkSession({cwd:e});return await sc(t),t}),[sc,eO,S,z,k]),(0,r.useEffect)(()=>S.bindWorkSessionGoTo(sn),[sn,S]);let sy=async e=>{if(!eO){ty.current+=1,e6(!1),tj.current+=1,te(!1),ts(e),tc(null);try{let{workSession:t}=await z.createWorkSession({cwd:e});tc(null),eY(!1),await sc(t)}catch(e){tc(gi(e,k("createFailed")))}finally{ts(null)}}},sk=async e=>{if(!eO&&eG&&eQ){if(!A.current.some(e=>e.workId===eG))return void tc(k("replaceTargetMissing"));th(),L.current.add(eG),tr(e),tc(null);try{let t=await z.replaceWorkSession({workId:eG,cwd:eQ,sessionId:e});if(t2(t),!t.workSessions.find(e=>e.workId===eG))throw Error(k("replacementMissing"));O.current=!1,tZ(eG),tc(null),eY(!1),_&&eu(!1)}catch(e){tc(gi(e,k("replaceFailed")))}finally{L.current.delete(eG),tr(null)}}},sj=(0,r.useCallback)(async e=>{if(!eO&&null===tl&&A.current.some(t=>t.workId===e)){L.current.add(e),to(e),tf(null);try{let t=await z.replaceWorkSession({workId:e});if(t2(t),!t.workSessions.find(t=>t.workId===e))throw Error(k("emptyReplacementMissing"));O.current=!1,tZ(e)}catch(e){tf(gi(e,k("replaceEmptyFailed")))}finally{L.current.delete(e),to(null)}}},[t2,eO,tl,tZ,z,k]),sN=(0,r.useCallback)(e=>{eg(e),"files"===e&&ev(!0)},[]),sI=(0,r.useCallback)(()=>{_&&ep(),ea&&!document.querySelector(`[data-work-id="${CSS.escape(ea)}"] [data-testid="session-file-layout"]`)&&Y.expandWindow(ea)},[ea,ep,Y,_]),sC=(0,r.useCallback)(()=>{tF&&ea&&(Y.refreshTree(ea),U.refreshSnapshot(Y.getDirectory(ea)))},[tF,ea,Y,U]),sS=(0,r.useCallback)(e=>{eR(e)},[]),sM=(0,r.useCallback)(()=>{eR(null)},[]),sz=(0,r.useCallback)((e,t,s="session",n)=>{let r=A.current.find(t=>t.workId===e.workId&&t.sessionId===e.sessionId&&t.branchId===e.branchId);if(!r)return void C.error(k("sourceChanged"));if("standalone"===s){eA({source:{workId:r.workId,sessionId:r.sessionId,branchId:r.branchId},cwd:r.cwd,projectName:r.projectName,path:t,imagePaths:n}),ep();return}Y.selectDirectory(r.workId,r.cwd),Y.openFile(r.workId,t),st(r.workId),ep();let a=document.querySelector(`[data-work-id="${CSS.escape(r.workId)}"] [data-testid="session-file-layout"]`);"expanded"!==s&&a?eM&&eT():Y.expandWindow(r.workId)},[eM,ep,eT,Y,st,C,k]),sE=(0,r.useCallback)((e,t,s,n)=>{let r=cM.safeParse(t),a=cM.array().nonempty().optional().safeParse(n);r.success&&a.success&&(!a.data||"standalone"===s&&a.data.includes(r.data))?sz(e,r.data,s,a.data?[...new Set(a.data)]:void 0):C.error(k("invalidFilePath"))},[sz,C,k]),sA=(0,r.useCallback)((e,t)=>{let s=cM.safeParse(t);s.success?sz(e,s.data):C.error(k("invalidToolFilePath"))},[sz,C,k]);(0,r.useEffect)(()=>S.bindWorkSessionFilePreview(({source:e,path:t,mode:s,imagePaths:n})=>{sE(e,t,s??"session",n)}),[S,sE]),(0,r.useEffect)(()=>S.bindImageReader(({source:e,cwd:t,path:s},n)=>ui(q,{workId:e.workId,cwd:t,path:s},n)),[S,q]);let s$=(0,r.useCallback)(async(e,t)=>{let s=cM.safeParse(t);if(!s.success)throw Error(k("invalidFilePath"));let n=A.current.find(t=>t.workId===e.workId&&t.sessionId===e.sessionId&&t.branchId===e.branchId);if(!n)throw Error(k("sourceChanged"));await q.reveal({workId:n.workId,cwd:n.cwd,path:s.data})},[q,k]);(0,r.useEffect)(()=>S.bindWorkSessionFileReveal(({source:e,path:t})=>s$(e,t)),[S,s$]);let sR=(0,r.useCallback)((e,t)=>{tq&&tW&&tY?sE({workId:tq,sessionId:tW,branchId:tY},e,t?.mode??"session",t?.imagePaths):C.error(k("noPreviewSession"))},[tY,tW,tq,sE,C,k]),sT=(0,r.useCallback)(e=>tq&&tW&&tY?s$({workId:tq,sessionId:tW,branchId:tY},e):Promise.reject(Error(k("noRevealSession"))),[tY,tW,tq,s$,k]),sP=(0,r.useCallback)(async e=>{await z.applyAppRuntimeUpdate({key:"notifications",update:{type:"delete",notificationId:e}})},[z]),sD=(0,r.useCallback)(async e=>{if(e.event)try{await S.dispatchNotificationEvent(e.notificationId,e.event),await sP(e.notificationId)}catch(e){C.error(gi(e,k("notificationActionFailed")))}},[sP,S,C,k]),sO=(0,r.useCallback)(async e=>{try{await sP(e)}catch(e){C.error(gi(e,k("notificationDeleteFailed")))}},[sP,C,k]),sL=(0,r.useCallback)(e=>{ep(),ej(e),ey(!0)},[ep]),sF=(0,r.useCallback)(e=>{ep(),ez(e)},[ep]),sB=(0,r.useCallback)(e=>void si(e),[si]),sq=(0,r.useCallback)((e,t)=>void sr(e,t),[sr]),sW=(0,r.useCallback)(e=>void sj(e),[sj]),sY=(0,r.useCallback)(()=>{_?eu(e=>!e):eo(e=>!e)},[_]),sU=(0,r.useCallback)(e=>{st(e),_?eu(!0):eo(!0)},[st,_]),sV=_?ec:el,sK=e$&&V.some(e=>e.workId===e$.workId&&e.cwd===e$.cwd)?e$:null,sH=(0,r.useMemo)(()=>eb&&tL?(0,n.jsx)(r.Activity,{mode:sV&&"files"===eh?"visible":"hidden",children:(0,n.jsx)(cQ.k,{workId:tL.workId,cwd:tL.cwd,projectName:tL.projectName,runtime:Y,gitRuntime:U,onOpenGitBranches:sS,onFileOpened:sI},`${tL.workId}:${tL.sessionId}:${tL.branchId}`)}):null,[tL,eb,Y,U,sI,sS,eh,sV]),sG=sV&&t_&&tB?.kind==="session-sidebar-tab"&&tU&&tL?(0,n.jsx)(gd,{render:g,input:{pluginName:t_.pluginName,descriptor:tB,source:tU,cwd:tL.cwd,onPreviewFile:sR,onRevealFile:sT,onHeaderActionsChange:tK}}):null,sJ=(0,n.jsx)(gt,{mode:eh,mobile:_,fileBrowser:sH,pluginTabContent:sG,pluginHeaderActions:sV&&ex?.targetKey===tV?ex.actions:[],pluginSessionTabs:tR,fileRefreshLoading:tH?.directories.get("")?.status==="loading",canBrowseFiles:null!==tF,workSessions:V,focusedWorkId:ea,pinnedCount:H,ordering:eF,deletingWorkId:eB,canReplace:null!==ea,disabled:eO,pluginApplications:t$,settingsAttention:tD,notifications:X.notifications,onConsumeNotification:sD,onDismissNotification:sO,onModeChange:sN,onRefreshFiles:sC,onPreviewProject:()=>{tF&&(ep(),Y.collapseExpandedWindow(),S.previewProject(ea?Y.getDirectory(ea):tF))},onOpenTerminal:()=>{ep(),Y.collapseExpandedWindow(),s(tF??void 0).catch(()=>void 0)},onCreate:sl,onReplace:so,onSettings:()=>sL(),onOpenPluginApplication:sF,onSelect:ss,onTogglePin:sa,onDelete:sB,onRename:eL.show,syncingWorkIds:tS.syncingWorkIds,onReloadChat:tS.reload,onArrangementChange:sq}),sQ=(0,n.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:[tx?(0,n.jsxs)("div",{role:"alert",className:"flex flex-wrap items-center gap-2 border-b border-destructive/30 bg-destructive/10 px-4 py-2 text-sm text-destructive",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 wrap-anywhere",children:tx}),(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>tv(e=>e+1),children:k("retry",{ns:"common"})}),"initial"!==eP?(0,n.jsx)(N.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>tf(null),children:k("close",{ns:"common"})}):null]}):null,(0,n.jsxs)("div",{className:"relative h-full min-h-0 min-w-0 flex-1",children:[(0,n.jsx)(hI,{workSessions:V,primaryWorkId:ee.primaryWorkId,pinnedWorkIds:tA,focusedWorkId:ea,sidebarOpen:sV,mobile:_,loading:eO,replacingWithEmptyWorkId:tl,chatRuntime:tC,chatInputRuntime:tM,renderTaskSummary:b,renderTaskMenu:v,renderPluginComposerPanel:w,gitRuntime:U,invokePluginMethod:z.invokePluginMethod,listPiCommands:z.listPiCommands,getChatModelContext:z.getChatModelContext,capabilityModes:X.capabilityModes,setChatCapabilityMode:z.setChatCapabilityMode,branchPicker:su,branchPendingWorkId:sw,fileRuntime:Y,onOpenFileSidebar:sU,onPreviewFile:sA,onAcknowledgeCompleted:t0,onFocusWorkSession:st,onReplaceWithEmptyWorkSession:sW,onOpenBranchPicker:sm,onOpenGitBranchPicker:sS,onOpenSettings:sL,onCloseBranchPicker:sp,onRetryBranchPicker:sh,onSelectBranchEntry:sg,onBranchAction:sx,onConfirmRunningBranch:sb,onCancelRunningBranch:sv,onCloneWorkSession:sf,onUnpinWorkSession:sa,onToggleSidebar:sY}),"initial"===eP?(0,n.jsx)(mV,{variant:"loading",className:"absolute inset-0 z-20 bg-background"}):null]})]}),sX=null!==eM&&tO?.kind==="application",sZ=(0,n.jsxs)("div",{className:"flex min-h-0 min-w-0 flex-1",children:[(0,n.jsx)(gd,{render:a,input:{mobile:_,children:sQ}}),sX?(0,n.jsx)(gd,{render:h,input:{pluginName:eM.pluginName,descriptor:tO,workSessions:V,preferredWorkId:ea,onClose:eT}}):null]});return(0,n.jsxs)("main",{className:"pi-desk-workbench flex h-dvh overflow-hidden bg-background",children:[(0,n.jsx)(cO,{mobile:_,open:sV,sidebar:sJ,onClose:ep,children:sZ}),(0,n.jsx)(c8,{target:eE,biz:q,images:Y.standaloneImages,mobile:_,onClose:()=>eA(null)},eE?`${eE.source.workId}:${eE.source.sessionId}:${eE.source.branchId}:${eE.path}`:"closed"),(0,n.jsx)(ur,{workSessions:V,runtime:Y,gitRuntime:U,mobile:_,onOpenGitBranches:sS,onOpenSidebar:sU,onOpenTerminal:e=>{Y.collapseExpandedWindow(),ep(),s(e).catch(()=>void 0)}}),(0,n.jsx)(up,{target:sK,runtime:U,mobile:_,onClose:sM},sK?`${sK.workId}:${sK.cwd}:${sK.repositoryRoot??""}`:"git-branch-picker-closed"),(0,n.jsx)(gd,{render:x,input:{open:ew,connectionReady:"ready"===eP,initialPage:ek,capabilityModes:X.capabilityModes,workSessions:V,focusedCwd:tF,basicMode:"basic"===X.mode,pluginManagementSnapshot:eN,pluginAttention:tD,onPluginManagementSnapshot:tQ,onPluginRestartScheduled:tX,onOpenChange:ey,onBeforeReload:()=>tM.prepareForPageReload()}}),(0,n.jsx)(hT,{open:eL.open,title:eL.title,saving:eL.saving,disabled:eO,error:eL.error,onTitleChange:eL.setTitle,onSave:()=>void eL.save(),onClose:eL.close}),(0,n.jsx)(mW,{open:eW,pickerMode:eU,pickerView:eK,pickerCwd:eQ,directories:eZ,ignoredDirectories:e1,directoryBrowser:e5,historySessions:tu,replacementTarget:"create"===eU?null:tG,unavailableSessionIds:tJ,error:td,loading:"history"===eK?tm:"ignored"===eK?e8:"browser"===eK?e9:e4,creatingCwd:tt,replacingSessionId:tn,updatingIgnoreCwd:ta,onOpenChange:e=>{eY(e),e||(ty.current+=1,e6(!1),tk.current+=1,e7(!1),tj.current+=1,te(!1),th(),eV(null),eH("directories"),tc(null))},onBack:()=>{tc(null),tk.current+=1,e7(!1),tj.current+=1,te(!1),th();let e=gl((au(),aa));e&&e0(e),eH("directories"),eX(null),t7()},onSearchHistory:(e,t)=>{"history"===eK&&eQ&&tp(eQ,e,t)},onListSessionUserMessages:(e,t)=>z.listSessionUserMessages(e,t),onRefresh:(e,t)=>{"history"===eK&&eQ?tp(eQ,e,t,!0):"ignored"===eK?t9(!0):"browser"===eK?se(e5?.cwd??null):t7(!0)},onOpenIgnoredDirectories:()=>{if(eO||"create"!==eU)return;let e=gl((au(),ai));e?e2(e):e2([]),tc(null),ty.current+=1,e6(!1),tj.current+=1,te(!1),eH("ignored"),t9()},onOpenDirectoryBrowser:()=>{eO||"create"!==eU||(tc(null),ty.current+=1,e6(!1),tk.current+=1,e7(!1),eH("browser"),e3(go(ag(null))),se(null))},onNavigateDirectory:e=>{if(eO||"create"!==eU)return;let t=go(ag(e));t&&e3(t),se(e)},onSelectBrowserDirectory:e=>void sy(e),onReplaceDirectoryIgnore:(e,t)=>void sd(e,t),onSelectDirectory:e=>{"replace"===eU?(ty.current+=1,e6(!1),eH("history"),eX(e),tg(e),tp(e)):sy(e)},onSelectSession:e=>void sk(e)})]})}function gu(e){return(0,n.jsx)(eV,{...e},`${e.pluginName}:${e.descriptor.contributionName}`)}function gm(e){return(0,n.jsx)(sR,{...e},`${e.pluginName}:${e.descriptor.contributionName}:${e.source.workId}:${e.source.sessionId}:${e.source.branchId}`)}function gp(e){let t=JSON.stringify([e.source.workId,e.source.sessionId,e.source.branchId]);return(0,n.jsx)(eK,{...e},`${e.pluginName}:${e.descriptor.contributionName}:${t}`)}function gh(e){return(0,n.jsx)(sT,{...e},`${e.pluginName}:${e.descriptor.contributionName}`)}function gg(){let{clientId:e,appSocket:t}=(0,er.gM)(),s=(0,J.t4)(),a=(0,Q.G)(),i=(0,r.useMemo)(()=>new x(t,a.error),[t,a.error]);(0,r.useEffect)(()=>{i.start();let e=s.bindTerminalOpen((e,t)=>i.open(e,t));return()=>{e(),i.dispose()}},[s,i]);let l=(0,r.useCallback)(e=>(0,n.jsx)(G,{...e,biz:i}),[i]),o=(0,r.useMemo)(()=>({subscribeChanges:e=>t.subscribe(sw,e),list:(t=!1)=>s$(e,"/api/plugins/list",sC.parse("boolean"==typeof t?t?{checkUpdates:!0}:{}:t),sj),batch:t=>s$(e,"/api/plugins/batch",sz.parse(t),sE),get:t=>s$(e,"/api/plugins/get",sS.parse({source:t}),sk),add:t=>s$(e,"/api/plugins/add",sM.parse(t),sj),setEnabled:(t,s)=>s$(e,"/api/plugins/enabled-set",sA.parse({source:t,enabled:s}),sj),searchCatalog:t=>s$(e,"/api/plugin-catalog/search",tA.parse(t),tT),getCatalog:t=>s$(e,"/api/plugin-catalog/get",t$.parse(t),tP),getCatalogSettings:()=>s$(e,"/api/plugin-catalog/settings-get",{},tz),saveCatalogSettings:t=>s$(e,"/api/plugin-catalog/settings-replace",tE.parse({downloadSource:t}),tz),update:t=>s$(e,"/api/plugins/update",sS.parse({source:t}),sj),del:t=>s$(e,"/api/plugins/del",sS.parse({source:t}),sj),reload:t=>s$(e,"/api/plugins/reload",sI.parse({mode:t}),sj),apply:t=>s$(e,"/api/plugins/apply",sN.parse({sources:t}),sj)}),[e,t]),d=(0,r.useMemo)(()=>(function(e,t){async function s(t,s){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Pi-Desk-Client-Id":e},body:JSON.stringify(s)}),r=await n.json();if(!n.ok||0!==r.code||null===r.data)throw Error(r.msg?(0,ed.B)(r):"请求失败");return r.data}return{watchDetail:e=>t.request(lA.detailWatch,e),async interrupt(e){await t.request(lA.interrupt,e)},subscribeDetailEvents:e=>t.subscribe(lA.detailEvent,e),getMessageDetail:e=>s("/api/task-center/messages/get",e),getImage:e=>s("/api/task-center/images/get",e)}})(e,t),[t,e]),c=(0,r.useMemo)(()=>{let e,t,s,n,r,a,i,l,o,c,u,m,p,h,g,x;return e=new Set,t=new Map,s=cj,n=0,r=0,a=!1,i=null,l=()=>void 0,o=null,c=!1,u=()=>{for(let t of[...e])try{t()}catch(e){console.error("[Pi Desk][TaskCenterClient] 状态监听器执行失败",{errorName:e instanceof Error?e.name:"UnknownError"})}},m=(e,t=!1)=>{s=e,((e=!1)=>{if(e){if(o)return;o=setTimeout(()=>{o=null,u()},16);return}o&&clearTimeout(o),o=null,u()})(t)},p=e=>{for(let[s,n]of t)(void 0===e||n.taskId===e)&&(URL.revokeObjectURL(n.url),t.delete(s))},h=()=>{if(!s.open&&null===s.source)return;let e=s.source;n+=1,a=!1,m(cj),p(),e&&d.watchDetail({source:e,taskId:null}).catch(()=>void 0)},g=e=>{if(c||!s.open||!a||!cN(s.source,e.source)||s.selectedTaskId!==e.taskId)return;let t=s.details[e.taskId];if(t)try{let n=function(e,t){var s,n;if("snapshot"===t.type)return cw(e,t.snapshot);if("unavailable"===t.type)return null;if("text_append"===t.type){if(e.body?.kind!=="text")throw Error("Text append requires a text task detail snapshot");return{...e,body:{...e.body,text:e.body.text+t.text}}}if(e.body?.kind!=="conversation")throw Error("Conversation event requires a conversation task detail snapshot");return{...e,body:{...(s=e.body,"durable_append"===(n=t.event).type?function(e,t){let s=e.messages.length;if(t.messages[0]?.location.index!==s)throw Error(`Conversation append index is not continuous: expected ${s}, received ${t.messages[0]?.location.index}`);let n=new Set(e.messages.map(e=>e.location.entryId));for(let e of t.messages){if(n.has(e.location.entryId))throw Error(`Conversation append entryId already exists: ${e.location.entryId}`);n.add(e.location.entryId)}return{...e,messages:[...e.messages,...t.messages]}}(s,n):cb(s,n)),kind:"conversation",truncated:e.body.truncated}}}(t,e.event);if(!n){let t={...s.details};delete t[e.taskId],p(e.taskId),m({...s,details:t,loading:!1,refreshing:!1,error:ck("detailUnavailable")});return}let r="text_append"===e.event.type||"conversation_event"===e.event.type&&"message_update"===e.event.event.type;m({...s,details:{...s.details,[e.taskId]:n},loading:!1,refreshing:!1,error:null},r)}catch(t){a=!1,l(t),x(e.taskId)}},x=async e=>{if(c||!s.open||!s.source)return;let t=e.trim();if(!t)return;let i=s.source,l=++n,o=r,u=s.details[t];a=!1,m({...s,selectedTaskId:t,loading:void 0===u,refreshing:void 0!==u,error:null});try{let e=await d.watchDetail({source:i,taskId:t});if(c||l!==n||o!==r||!s.open||!cN(s.source,i)||s.selectedTaskId!==t)return;if(!e.snapshot)throw Error(ck("detailResponseMissing"));let p=lj.parse(e.snapshot),h=u?cw(u,p):p;m({...s,details:{...s.details,[t]:h},loading:!1,refreshing:!1,error:null}),a=!0}catch(e){if(l!==n||!s.open||s.selectedTaskId!==t)return;m({...s,loading:!1,refreshing:!1,error:e instanceof Error?e.message:ck("detailLoadFailed")})}},{start(e){l=e,i||(c=!1,i=d.subscribeDetailEvents(g))},subscribe:t=>(e.add(t),()=>e.delete(t)),getState:()=>s,open(e,t){let r=lo.R.parse(e);s.open&&cN(s.source,r)||(n+=1,a=!1,p(),m({...cj,open:!0,source:r})),t&&x(t)},close:h,selectTask(e){x(e)},reconcileWorkSessions(e){if(!s.open||!s.source)return;let t=e.find(e=>e.workId===s.source?.workId);t&&t.sessionId===s.source.sessionId&&t.branchId===s.source.branchId||h()},reconcileTasks(e,t){let r=lo.R.parse(e);if(!s.open||!cN(s.source,r))return;let i=new Set(t.map(e=>e.taskId)),l={...s.details},o=!1;for(let e of Object.keys(l))i.has(e)||(delete l[e],p(e),o=!0);if(s.selectedTaskId&&!i.has(s.selectedTaskId)){n+=1,a=!1,m({...s,selectedTaskId:null,details:l,loading:!1,refreshing:!1,error:null});return}o&&m({...s,details:l})},async interruptSelected(){s.open&&s.source&&s.selectedTaskId&&await d.interrupt({source:s.source,taskId:s.selectedTaskId})},async loadMessageDetail(e){let t=s.source,n=s.selectedTaskId;if(!s.open||!t||!n||!e.durable)return null;let r=s.details[n];if(!r||r.body?.kind!=="conversation")return null;if(void 0!==e.detail)return e.detail;if(!e.snapshot.fixed.hasDetail)return null;let a=await d.getMessageDetail({source:t,taskId:n,entryId:e.durable.location.entryId}),i=s.details[n];return i&&m({...s,details:{...s.details,[n]:function(e,t){if(e.body?.kind!=="conversation")throw Error("Task message detail requires a conversation snapshot");return lj.parse({...e,body:{kind:"conversation",truncated:e.body.truncated,...cv(e.body,t)}})}(i,a)}}),a.detail},async acquireImage(e,n){let r=s.source,a=s.selectedTaskId,i=e.durable?.location.entryId;if(!s.open||!r||!a||!i)throw Error(ck("imageDurableOnly"));let l=JSON.stringify([r.workId,r.sessionId,r.branchId,a,i,n]),o=t.get(l);if(o)return{url:o.url,release:()=>void 0};let c=await d.getImage({source:r,taskId:a,entryId:i,imageIndex:n});if(!s.open||!cN(s.source,r))throw Error(ck("centerClosed"));let u=t.get(l);if(u)return{url:u.url,release:()=>void 0};let m=URL.createObjectURL((0,cy.E)(c));return t.set(l,{taskId:a,url:m}),{url:m,release:()=>void 0}},disconnected(){r+=1,a=!1,s.open&&m({...s,loading:null!==s.selectedTaskId&&void 0===s.details[s.selectedTaskId],refreshing:null!==s.selectedTaskId&&void 0!==s.details[s.selectedTaskId]})},reconnected(){s.open&&s.selectedTaskId&&x(s.selectedTaskId)},dispose(){if(c)return;c=!0;let t=s.source;n+=1,r+=1,a=!1,i?.(),i=null,p(),t&&d.watchDetail({source:t,taskId:null}).catch(()=>void 0),s=cj,o&&clearTimeout(o),o=null,e.clear(),l=()=>void 0}}},[d]),u=(0,r.useCallback)(e=>(0,n.jsx)(cd,{...e,runtime:c,variant:"summary"}),[c]),m=(0,r.useCallback)(e=>(0,n.jsx)(cd,{...e,runtime:c,variant:"menu"}),[c]),p=(0,r.useCallback)(e=>(0,n.jsx)(iq,{open:e.open,connectionReady:e.connectionReady,initialModelTab:"model-presets"===e.initialPage?"presets":void 0,workSessions:e.workSessions,focusedCwd:e.focusedCwd,pluginAttention:e.pluginAttention,onOpenChange:e.onOpenChange,onBeforeReload:e.onBeforeReload,renderPluginSettingsPage:gh,renderMcpSettings:({onBeforeLeaveChange:t})=>(0,n.jsx)(ll,{projects:e.workSessions,focusedCwd:e.focusedCwd,onBeforeLeaveChange:t}),renderCapabilityModesSettings:({onBeforeLeaveChange:t})=>(0,n.jsx)(eI,{modeNames:e.capabilityModes,onBeforeLeaveChange:t}),renderPluginManagement:()=>(0,n.jsx)(se,{basicMode:e.basicMode,snapshot:e.pluginManagementSnapshot,biz:o,onSnapshot:e.onPluginManagementSnapshot,onRestartScheduled:e.onPluginRestartScheduled})},`${e.open}:${e.initialPage??"default"}`),[o]);return(0,n.jsx)(gc,{onTerminalReady:i.connected,onTerminalDisconnected:i.disconnected,onOpenTerminal:i.open,renderTerminalWorkspace:l,listPluginManagement:o.list,subscribePluginManagementChanges:o.subscribeChanges,onTaskCenterStart:c.start,onTaskCenterDispose:c.dispose,onTaskCenterReconcileWorkSessions:c.reconcileWorkSessions,onTaskCenterDisconnected:c.disconnected,onTaskCenterReconnected:c.reconnected,renderPluginApplication:gu,renderPluginSessionSidebarTab:gm,renderPluginComposerPanel:gp,renderSettings:p,renderTaskSummary:u,renderTaskMenu:m})}},46117:e=>{e.exports={sessionPanelGroup:"l2-workbench-motion_sessionPanelGroup__83WwS",panelGroup:"l2-workbench-motion_panelGroup__yxZEK",drawer:"l2-workbench-motion_drawer____5mR",backdrop:"l2-workbench-motion_backdrop__F0q19",columnContent:"l2-workbench-motion_columnContent__1RfUq"}},46376:e=>{e.exports={markdown:"l3-conversation-markdown_markdown__KmlPt",imageTrigger:"l3-conversation-markdown_imageTrigger__0YMnp",image:"l3-conversation-markdown_image__0h0S8",imageAction:"l3-conversation-markdown_imageAction__mBi4a",imageFallback:"l3-conversation-markdown_imageFallback__F30Mz"}},52216:e=>{e.exports={panel:"l3-conversation-call-summary_panel__sUGhX",table:"l3-conversation-call-summary_table__cf6vS",row:"l3-conversation-call-summary_row__eGK_L"}},54379:(e,t,s)=>{"use strict";s.d(t,{TR:()=>M,bq:()=>C,eb:()=>z,gC:()=>S,l6:()=>j,s3:()=>N,yv:()=>I});var n=s(7962);s(69266);var r=s(66341),a=s(91068),i=s(57160),l=s(39148),o=s(95532),d=s(34358),c=s(75970),u=s(12124),m=s(6398),p=s(15639),h=s(44788),g=s(40963),x=s(10949),f=s(46468),b=s(93282),v=s(49426),w=s(86758),y=s(90458),k=s(24121);let j=r.H;function N({className:e,...t}){return(0,n.jsx)(a.s,{"data-slot":"select-group",className:(0,v.cn)("scroll-my-1 p-1",e),...t})}function I({className:e,...t}){return(0,n.jsx)(i.y,{"data-slot":"select-value",className:(0,v.cn)("flex flex-1 text-left",e),...t})}function C({className:e,size:t="default",children:s,...r}){return(0,n.jsxs)(l.b,{"data-slot":"select-trigger","data-size":t,className:(0,v.cn)("flex w-fit cursor-pointer items-center justify-between gap-2 rounded-lg border border-input bg-card px-2.5 py-1 text-sm leading-5 whitespace-nowrap transition-colors outline-none select-none hover:bg-accent focus-visible:border-ring focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:min-h-8 data-[size=sm]:min-h-7 data-[size=sm]:rounded-md data-[size=sm]:py-0.5 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r,children:[s,(0,n.jsx)(o.w,{render:(0,n.jsx)(w.A,{className:"pointer-events-none size-4 text-muted-foreground"})})]})}function S({className:e,positionerClassName:t,children:s,side:r="bottom",sideOffset:a=4,align:i="center",alignOffset:l=0,alignItemWithTrigger:o=!0,finalFocus:p=!1,...h}){return(0,n.jsx)(d.V,{children:(0,n.jsx)(c.l,{side:r,sideOffset:a,align:i,alignOffset:l,alignItemWithTrigger:o,className:(0,v.cn)("isolate z-50",t),children:(0,n.jsxs)(u.t,{"data-slot":"select-content",finalFocus:p,"data-align-trigger":o,className:(0,v.cn)("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...h,children:[(0,n.jsx)(E,{}),(0,n.jsx)(m.B,{children:s}),(0,n.jsx)(A,{})]})})})}function M({className:e,...t}){return(0,n.jsx)(p.M,{"data-slot":"select-label",className:(0,v.cn)("px-1.5 py-1 text-xs text-muted-foreground",e),...t})}function z({className:e,children:t,...s}){return(0,n.jsxs)(h.e,{"data-slot":"select-item",className:(0,v.cn)("relative flex min-h-8 w-full cursor-pointer items-center gap-2 rounded-md py-1 pr-8 pl-2 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...s,children:[(0,n.jsx)(g.h,{className:"flex flex-1 shrink-0 gap-2 whitespace-nowrap",children:t}),(0,n.jsx)(x.h,{render:(0,n.jsx)("span",{className:"pointer-events-none absolute right-2 flex size-4 items-center justify-center"}),children:(0,n.jsx)(y.A,{className:"pointer-events-none"})})]})}function E({className:e,...t}){return(0,n.jsx)(f.w,{"data-slot":"select-scroll-up-button",className:(0,v.cn)("top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:(0,n.jsx)(k.A,{})})}function A({className:e,...t}){return(0,n.jsx)(b.d,{"data-slot":"select-scroll-down-button",className:(0,v.cn)("bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",e),...t,children:(0,n.jsx)(w.A,{})})}},58270:e=>{e.exports={inputFrame:"l2-workbench-chat-composer_inputFrame__zhb9v",inputText:"l2-workbench-chat-composer_inputText__3DU2N",footer:"l2-workbench-chat-composer_footer__7wBQh",primaryTools:"l2-workbench-chat-composer_primaryTools__8KCVm",metadataTools:"l2-workbench-chat-composer_metadataTools__XEVFA",submitTools:"l2-workbench-chat-composer_submitTools__x8f4c",modelTrigger:"l2-workbench-chat-composer_modelTrigger__tDV8k",modelTriggerDetails:"l2-workbench-chat-composer_modelTriggerDetails__sdSS2"}},70657:(e,t,s)=>{"use strict";s.d(t,{k:()=>m});var n=s(7962),r=s(86758),a=s(66584),i=s(69266),l=s(78121),o=s(37975),d=s(17708),c=s(35800);function u(e){return e.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??e}function m({workId:e,cwd:t,projectName:s,runtime:p,gitRuntime:h,onOpenGitBranches:g,onFileOpened:x}){let f,{t:b}=(0,l.Bd)("projectFiles");(0,i.useSyncExternalStore)(p.subscribe,p.getRevision,p.getRevision);let v=p.getDirectory(e),w=p.getDirectories(e),y=(0,o.Yj)(t)===(0,o.Yj)(v),k=y?s:u(v);return(0,n.jsx)(c.F,{cwd:v,projectName:k,gitReadOnly:!y,rootTitle:w.length>1?(0,n.jsxs)(d.rI,{children:[(0,n.jsxs)(d.ty,{"data-testid":"project-preview-directory-trigger","aria-label":b("selectPreviewDirectory"),title:v,className:"flex min-h-7 min-w-0 flex-1 items-center gap-1 rounded-md px-1 text-left hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",children:[(0,n.jsx)("span",{className:"max-w-[45%] truncate text-xs font-semibold",children:k}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"\xb7"}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground",children:(f=v.replaceAll("\\","/").split("/").filter(Boolean)).length<=2?v:`…/${f.slice(-2).join("/")}`}),(0,n.jsx)(r.A,{className:"size-3.5 shrink-0 text-muted-foreground"})]}),(0,n.jsx)(d.SQ,{finalFocus:!0,className:"w-[23rem] min-w-0 max-w-[calc(100vw-1.5rem)]","aria-label":b("previewDirectories"),children:(0,n.jsxs)(d.I,{children:[(0,n.jsx)(d.lp,{children:b("previewDirectories")}),(0,n.jsx)(d.Hr,{value:v,onValueChange:t=>p.selectDirectory(e,t),children:w.map(e=>(0,n.jsxs)(d.Ht,{value:e,"data-testid":"project-preview-directory-option","data-directory":e,className:"items-start py-2 data-checked:bg-muted",children:[(0,n.jsx)(a.A,{className:"mt-0.5 size-4 text-muted-foreground"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("span",{className:"flex items-start gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 break-all",children:(0,o.Yj)(e)===(0,o.Yj)(t)?s:u(e)}),(0,o.Yj)(e)===(0,o.Yj)(t)?(0,n.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:b("sessionDirectory")}):null]}),(0,n.jsx)("span",{className:"mt-0.5 block break-all font-mono text-xs leading-5 text-muted-foreground",children:e})]})]},(0,o.Yj)(e)))})]})})]}):void 0,runtime:p.getFileRuntime(e),gitRuntime:h,onOpenGitBranches:n=>{y&&g({workId:e,cwd:t,projectName:s,repositoryRoot:n})},onFileOpened:()=>{p.showWindow(e),x?.()}})}},76169:(e,t,s)=>{Promise.resolve().then(s.bind(s,45458))},76812:e=>{e.exports={single:"l2-work-session-file-layout_single__LVPWJ",wide:"l2-work-session-file-layout_wide__NEecW"}},78653:e=>{e.exports={collapsedText:"l2-work-session-columns_collapsedText__f7OAU"}},79814:e=>{e.exports={viewport:"l2-terminal-workspace_viewport__lAZHJ",canvas:"l2-terminal-workspace_canvas__h6ngK",mobile:"l2-terminal-workspace_mobile__4Ae83"}},89517:e=>{e.exports={surface:"l3-work-session-visual-effects_surface__N89k0",identity:"l3-work-session-visual-effects_identity__Aujuw"}}},e=>{e.O(0,[82705,357,85959,26717,94287,78923,96995,46270,27611,14197,51474,74220,77592,4904,64444,77358],()=>e(e.s=76169)),_N_E=e.O()}]);