@researai/deepscientist 1.5.15 → 1.5.17

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/README.md +385 -104
  2. package/bin/ds.js +1241 -110
  3. package/docs/en/00_QUICK_START.md +100 -19
  4. package/docs/en/01_SETTINGS_REFERENCE.md +34 -1
  5. package/docs/en/02_START_RESEARCH_GUIDE.md +7 -0
  6. package/docs/en/05_TUI_GUIDE.md +6 -0
  7. package/docs/en/06_RUNTIME_AND_CANVAS.md +4 -3
  8. package/docs/en/09_DOCTOR.md +25 -8
  9. package/docs/en/14_PROMPT_SKILLS_AND_MCP_GUIDE.md +63 -13
  10. package/docs/en/15_CODEX_PROVIDER_SETUP.md +37 -11
  11. package/docs/en/19_EXTERNAL_CONTROLLER_GUIDE.md +226 -0
  12. package/docs/en/19_LOCAL_BROWSER_AUTH.md +70 -0
  13. package/docs/en/20_WORKSPACE_MODES_GUIDE.md +250 -0
  14. package/docs/en/21_LOCAL_MODEL_BACKENDS_GUIDE.md +283 -0
  15. package/docs/en/91_DEVELOPMENT.md +237 -0
  16. package/docs/en/README.md +24 -2
  17. package/docs/zh/00_QUICK_START.md +89 -19
  18. package/docs/zh/01_SETTINGS_REFERENCE.md +34 -1
  19. package/docs/zh/02_START_RESEARCH_GUIDE.md +7 -0
  20. package/docs/zh/05_TUI_GUIDE.md +6 -0
  21. package/docs/zh/09_DOCTOR.md +26 -9
  22. package/docs/zh/14_PROMPT_SKILLS_AND_MCP_GUIDE.md +63 -13
  23. package/docs/zh/15_CODEX_PROVIDER_SETUP.md +37 -11
  24. package/docs/zh/19_EXTERNAL_CONTROLLER_GUIDE.md +226 -0
  25. package/docs/zh/19_LOCAL_BROWSER_AUTH.md +68 -0
  26. package/docs/zh/20_WORKSPACE_MODES_GUIDE.md +251 -0
  27. package/docs/zh/21_LOCAL_MODEL_BACKENDS_GUIDE.md +281 -0
  28. package/docs/zh/README.md +24 -2
  29. package/install.sh +46 -4
  30. package/package.json +2 -1
  31. package/pyproject.toml +1 -1
  32. package/src/deepscientist/__init__.py +1 -1
  33. package/src/deepscientist/acp/envelope.py +6 -0
  34. package/src/deepscientist/artifact/service.py +647 -22
  35. package/src/deepscientist/bash_exec/service.py +234 -9
  36. package/src/deepscientist/bridges/connectors.py +8 -2
  37. package/src/deepscientist/cli.py +115 -19
  38. package/src/deepscientist/codex_cli_compat.py +367 -22
  39. package/src/deepscientist/config/models.py +2 -1
  40. package/src/deepscientist/config/service.py +183 -13
  41. package/src/deepscientist/daemon/api/handlers.py +255 -31
  42. package/src/deepscientist/daemon/api/router.py +9 -0
  43. package/src/deepscientist/daemon/app.py +1146 -105
  44. package/src/deepscientist/diagnostics/__init__.py +6 -0
  45. package/src/deepscientist/diagnostics/runner_failures.py +130 -0
  46. package/src/deepscientist/doctor.py +207 -3
  47. package/src/deepscientist/gitops/__init__.py +10 -1
  48. package/src/deepscientist/gitops/diff.py +129 -0
  49. package/src/deepscientist/gitops/service.py +4 -1
  50. package/src/deepscientist/mcp/server.py +39 -0
  51. package/src/deepscientist/prompts/builder.py +275 -34
  52. package/src/deepscientist/quest/layout.py +15 -2
  53. package/src/deepscientist/quest/service.py +707 -55
  54. package/src/deepscientist/quest/stage_views.py +6 -1
  55. package/src/deepscientist/runners/codex.py +143 -43
  56. package/src/deepscientist/shared.py +19 -0
  57. package/src/deepscientist/skills/__init__.py +2 -2
  58. package/src/deepscientist/skills/installer.py +196 -5
  59. package/src/deepscientist/skills/registry.py +66 -0
  60. package/src/prompts/connectors/qq.md +18 -8
  61. package/src/prompts/connectors/weixin.md +16 -6
  62. package/src/prompts/contracts/shared_interaction.md +14 -2
  63. package/src/prompts/system.md +23 -5
  64. package/src/prompts/system_copilot.md +56 -0
  65. package/src/skills/analysis-campaign/SKILL.md +1 -0
  66. package/src/skills/baseline/SKILL.md +8 -0
  67. package/src/skills/decision/SKILL.md +8 -0
  68. package/src/skills/experiment/SKILL.md +8 -0
  69. package/src/skills/figure-polish/SKILL.md +1 -0
  70. package/src/skills/finalize/SKILL.md +1 -0
  71. package/src/skills/idea/SKILL.md +1 -0
  72. package/src/skills/intake-audit/SKILL.md +8 -0
  73. package/src/skills/mentor/SKILL.md +217 -0
  74. package/src/skills/mentor/references/correction-rules.md +210 -0
  75. package/src/skills/mentor/references/knowledge-profile.md +91 -0
  76. package/src/skills/mentor/references/persona-profile.md +138 -0
  77. package/src/skills/mentor/references/taste-profile.md +128 -0
  78. package/src/skills/mentor/references/thought-style-profile.md +138 -0
  79. package/src/skills/mentor/references/work-profile.md +289 -0
  80. package/src/skills/mentor/references/workflow-profile.md +240 -0
  81. package/src/skills/optimize/SKILL.md +1 -0
  82. package/src/skills/rebuttal/SKILL.md +1 -0
  83. package/src/skills/review/SKILL.md +1 -0
  84. package/src/skills/scout/SKILL.md +8 -0
  85. package/src/skills/write/SKILL.md +1 -0
  86. package/src/tui/dist/app/AppContainer.js +19 -11
  87. package/src/tui/dist/index.js +4 -1
  88. package/src/tui/dist/lib/api.js +33 -3
  89. package/src/tui/package.json +1 -1
  90. package/src/ui/dist/assets/AiManusChatView-Bv-Z8YpU.js +204 -0
  91. package/src/ui/dist/assets/AnalysisPlugin-BCKAfjba.js +1 -0
  92. package/src/ui/dist/assets/CliPlugin-BCKcpc35.js +109 -0
  93. package/src/ui/dist/assets/CodeEditorPlugin-DbOfSJ8K.js +2 -0
  94. package/src/ui/dist/assets/CodeViewerPlugin-CbaFRrUU.js +270 -0
  95. package/src/ui/dist/assets/DocViewerPlugin-DAjLVeQD.js +7 -0
  96. package/src/ui/dist/assets/GitCommitViewerPlugin-CIUqbUDO.js +1 -0
  97. package/src/ui/dist/assets/GitDiffViewerPlugin-CQACjoAA.js +6 -0
  98. package/src/ui/dist/assets/GitSnapshotViewer-0r4nLPke.js +30 -0
  99. package/src/ui/dist/assets/ImageViewerPlugin-nBOmI2v_.js +26 -0
  100. package/src/ui/dist/assets/LabCopilotPanel-BHxOxF4z.js +14 -0
  101. package/src/ui/dist/assets/LabPlugin-BKoZGs95.js +22 -0
  102. package/src/ui/dist/assets/LatexPlugin-ZwtV8pIp.js +25 -0
  103. package/src/ui/dist/assets/MarkdownViewerPlugin-DKqVfKyW.js +128 -0
  104. package/src/ui/dist/assets/MarketplacePlugin-BwxStZ9D.js +13 -0
  105. package/src/ui/dist/assets/NotebookEditor-BEQhaQbt.js +81 -0
  106. package/src/ui/dist/assets/{NotebookEditor-CccQYZjX.css → NotebookEditor-BHH8rdGj.css} +1 -1
  107. package/src/ui/dist/assets/NotebookEditor-BOr3x3Ej.css +1 -0
  108. package/src/ui/dist/assets/NotebookEditor-DB9N_T9q.js +361 -0
  109. package/src/ui/dist/assets/PdfLoader-Cy5jtWrr.css +1 -0
  110. package/src/ui/dist/assets/PdfLoader-eWBONbQP.js +16 -0
  111. package/src/ui/dist/assets/PdfMarkdownPlugin-D22YOZL3.js +1 -0
  112. package/src/ui/dist/assets/PdfViewerPlugin-c-RK9DLM.js +17 -0
  113. package/src/ui/dist/assets/PdfViewerPlugin-nwwE-fjJ.css +1 -0
  114. package/src/ui/dist/assets/SearchPlugin-CxF9ytAx.js +16 -0
  115. package/src/ui/dist/assets/SearchPlugin-DA4en4hK.css +1 -0
  116. package/src/ui/dist/assets/TextViewerPlugin-C5xqeeUH.js +54 -0
  117. package/src/ui/dist/assets/VNCViewer-BoLGLnHz.js +11 -0
  118. package/src/ui/dist/assets/bot-DREQOxzP.js +6 -0
  119. package/src/ui/dist/assets/browser-CTB2jwNe.js +8 -0
  120. package/src/ui/dist/assets/chevron-up-C9Qpx4DE.js +6 -0
  121. package/src/ui/dist/assets/code-WlFHE7z_.js +6 -0
  122. package/src/ui/dist/assets/file-content-BZMz3RYp.js +1 -0
  123. package/src/ui/dist/assets/file-diff-panel-CQhw0jS2.js +1 -0
  124. package/src/ui/dist/assets/file-jump-queue-DA-SdG__.js +1 -0
  125. package/src/ui/dist/assets/file-socket-CfQPKQKj.js +1 -0
  126. package/src/ui/dist/assets/git-commit-horizontal-DxZ8DCZh.js +6 -0
  127. package/src/ui/dist/assets/image-Bgl4VIyx.js +6 -0
  128. package/src/ui/dist/assets/index-BpV6lusQ.css +33 -0
  129. package/src/ui/dist/assets/index-CBNVuWcP.js +2496 -0
  130. package/src/ui/dist/assets/index-CwNu1aH4.js +11 -0
  131. package/src/ui/dist/assets/index-DrUnlf6K.js +1 -0
  132. package/src/ui/dist/assets/index-NW-h8VzN.js +1 -0
  133. package/src/ui/dist/assets/monaco-CiHMMNH_.js +1 -0
  134. package/src/ui/dist/assets/pdf-effect-queue-J8OnM0jE.js +6 -0
  135. package/src/ui/dist/assets/plugin-monaco-C8UgLomw.js +19 -0
  136. package/src/ui/dist/assets/plugin-notebook-HbW2K-1c.js +169 -0
  137. package/src/ui/dist/assets/plugin-pdf-CR8hgQBV.js +357 -0
  138. package/src/ui/dist/assets/plugin-terminal-MXFIPun8.js +227 -0
  139. package/src/ui/dist/assets/popover-CLc0pPP8.js +1 -0
  140. package/src/ui/dist/assets/project-sync-C9IdzdZW.js +1 -0
  141. package/src/ui/dist/assets/select-Cs2PmzwL.js +11 -0
  142. package/src/ui/dist/assets/sigma-ClKcHAXm.js +6 -0
  143. package/src/ui/dist/assets/trash-DwpbFr3w.js +11 -0
  144. package/src/ui/dist/assets/useCliAccess-NQ8m0Let.js +1 -0
  145. package/src/ui/dist/assets/useFileDiffOverlay-FuhcnKiw.js +1 -0
  146. package/src/ui/dist/assets/wrap-text-BC-Hltpd.js +11 -0
  147. package/src/ui/dist/assets/zoom-out-E_gaeAxL.js +11 -0
  148. package/src/ui/dist/index.html +5 -2
  149. package/src/ui/dist/assets/AiManusChatView-DDjbFnbt.js +0 -26597
  150. package/src/ui/dist/assets/AnalysisPlugin-Yb5IdmaU.js +0 -123
  151. package/src/ui/dist/assets/CliPlugin-e64sreyu.js +0 -31037
  152. package/src/ui/dist/assets/CodeEditorPlugin-C4D2TIkU.js +0 -427
  153. package/src/ui/dist/assets/CodeViewerPlugin-BVoNZIvC.js +0 -905
  154. package/src/ui/dist/assets/DocViewerPlugin-CLChbllo.js +0 -278
  155. package/src/ui/dist/assets/GitDiffViewerPlugin-C4xeFyFQ.js +0 -2661
  156. package/src/ui/dist/assets/ImageViewerPlugin-OiMUAcLi.js +0 -500
  157. package/src/ui/dist/assets/LabCopilotPanel-BjD2ThQF.js +0 -4104
  158. package/src/ui/dist/assets/LabPlugin-DQPg-NrB.js +0 -2677
  159. package/src/ui/dist/assets/LatexPlugin-CI05XAV9.js +0 -1792
  160. package/src/ui/dist/assets/MarkdownViewerPlugin-DpeBLYZf.js +0 -308
  161. package/src/ui/dist/assets/MarketplacePlugin-DolE58Q2.js +0 -413
  162. package/src/ui/dist/assets/NotebookEditor-7Qm2rSWD.js +0 -4214
  163. package/src/ui/dist/assets/NotebookEditor-C1kWaxKi.js +0 -84873
  164. package/src/ui/dist/assets/NotebookEditor-C3VQ7ylN.css +0 -1405
  165. package/src/ui/dist/assets/PdfLoader-BfOHw8Zw.js +0 -25468
  166. package/src/ui/dist/assets/PdfLoader-C-Y707R3.css +0 -49
  167. package/src/ui/dist/assets/PdfMarkdownPlugin-BulDREv1.js +0 -409
  168. package/src/ui/dist/assets/PdfViewerPlugin-C-daaOaL.js +0 -3095
  169. package/src/ui/dist/assets/PdfViewerPlugin-DQ11QcSf.css +0 -3627
  170. package/src/ui/dist/assets/SearchPlugin-CjpaiJ3A.js +0 -741
  171. package/src/ui/dist/assets/SearchPlugin-DDMrGDkh.css +0 -379
  172. package/src/ui/dist/assets/TextViewerPlugin-BxIyqPQC.js +0 -472
  173. package/src/ui/dist/assets/VNCViewer-HAg9mF7M.js +0 -18821
  174. package/src/ui/dist/assets/awareness-C0NPR2Dj.js +0 -292
  175. package/src/ui/dist/assets/bot-0DYntytV.js +0 -21
  176. package/src/ui/dist/assets/browser-BAcuE0Xj.js +0 -2895
  177. package/src/ui/dist/assets/code-B20Slj_w.js +0 -17
  178. package/src/ui/dist/assets/file-content-DT24KFma.js +0 -377
  179. package/src/ui/dist/assets/file-diff-panel-DK13YPql.js +0 -92
  180. package/src/ui/dist/assets/file-jump-queue-r5XKgJEV.js +0 -16
  181. package/src/ui/dist/assets/file-socket-B4T2o4nR.js +0 -58
  182. package/src/ui/dist/assets/function-B5QZkkHC.js +0 -1895
  183. package/src/ui/dist/assets/image-DSeR_sDS.js +0 -18
  184. package/src/ui/dist/assets/index-BrFje2Uk.js +0 -120
  185. package/src/ui/dist/assets/index-BwRJaoTl.js +0 -25
  186. package/src/ui/dist/assets/index-D_E4281X.js +0 -221322
  187. package/src/ui/dist/assets/index-DnYB3xb1.js +0 -159
  188. package/src/ui/dist/assets/index-G7AcWcMu.css +0 -12594
  189. package/src/ui/dist/assets/monaco-LExaAN3Y.js +0 -623
  190. package/src/ui/dist/assets/pdf-effect-queue-BJk5okWJ.js +0 -47
  191. package/src/ui/dist/assets/pdf_viewer-e0g1is2C.js +0 -8206
  192. package/src/ui/dist/assets/popover-D3Gg_FoV.js +0 -476
  193. package/src/ui/dist/assets/project-sync-C_ygLlVU.js +0 -297
  194. package/src/ui/dist/assets/select-CpAK6uWm.js +0 -1690
  195. package/src/ui/dist/assets/sigma-DEccaSgk.js +0 -22
  196. package/src/ui/dist/assets/square-check-big-uUfyVsbD.js +0 -17
  197. package/src/ui/dist/assets/trash-CXvwwSe8.js +0 -32
  198. package/src/ui/dist/assets/useCliAccess-Bnop4mgR.js +0 -957
  199. package/src/ui/dist/assets/useFileDiffOverlay-B8eUAX0I.js +0 -53
  200. package/src/ui/dist/assets/wrap-text-9vbOBpkW.js +0 -35
  201. package/src/ui/dist/assets/yjs-DncrqiZ8.js +0 -11243
  202. package/src/ui/dist/assets/zoom-out-BgVMmOW4.js +0 -34
@@ -0,0 +1,26 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CBNVuWcP.js","assets/plugin-monaco-C8UgLomw.js","assets/plugin-terminal-MXFIPun8.js","assets/plugin-notebook-HbW2K-1c.js","assets/index-BpV6lusQ.css"])))=>i.map(i=>d[i]);
2
+ import{y as O,j as e,b as z,am as Z,an as B,a3 as V,L as q,_ as G}from"./index-CBNVuWcP.js";import{r as t}from"./plugin-monaco-C8UgLomw.js";import{I as F}from"./image-Bgl4VIyx.js";import{Z as K,a as J}from"./zoom-out-E_gaeAxL.js";import"./plugin-notebook-HbW2K-1c.js";import"./plugin-terminal-MXFIPun8.js";/**
3
+ * @license lucide-react v0.511.0 - ISC
4
+ *
5
+ * This source code is licensed under the ISC license.
6
+ * See the LICENSE file in the root directory of this source tree.
7
+ */const Q=[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]],ee=O("image-off",Q);/**
8
+ * @license lucide-react v0.511.0 - ISC
9
+ *
10
+ * This source code is licensed under the ISC license.
11
+ * See the LICENSE file in the root directory of this source tree.
12
+ */const te=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],ae=O("maximize",te);/**
13
+ * @license lucide-react v0.511.0 - ISC
14
+ *
15
+ * This source code is licensed under the ISC license.
16
+ * See the LICENSE file in the root directory of this source tree.
17
+ */const se=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],re=O("rotate-cw",se),$=.1,H=10,Y=.1;function ne({src:r,alt:E,onLoad:w,onError:N,rotation:f,className:C}){const[v,x]=t.useState(!0),[s,l]=t.useState({scale:1,translateX:0,translateY:0}),[c,p]=t.useState(!1),[d,j]=t.useState({x:0,y:0}),m=t.useRef(null),u=t.useRef(null);t.useEffect(()=>{l({scale:1,translateX:0,translateY:0}),x(!0)},[r]);const k=t.useCallback(()=>{x(!1),u.current&&w&&w({width:u.current.width,height:u.current.height,naturalWidth:u.current.naturalWidth,naturalHeight:u.current.naturalHeight})},[w]),i=t.useCallback(()=>{x(!1),N?.()},[N]);t.useCallback(()=>{l(a=>({...a,scale:Math.min(a.scale+Y,H)}))},[]),t.useCallback(()=>{l(a=>({...a,scale:Math.max(a.scale-Y,$)}))},[]);const I=t.useCallback(()=>{l({scale:1,translateX:0,translateY:0})},[]);t.useCallback(()=>{if(!m.current||!u.current)return;const a=m.current.getBoundingClientRect(),o=u.current,b=o.naturalWidth,h=o.naturalHeight,R=(a.width-40)/b,D=(a.height-40)/h,X=Math.min(R,D,1);l({scale:X,translateX:0,translateY:0})},[]);const L=t.useCallback(a=>{a.preventDefault();const o=a.deltaY>0?-Y:Y,b=Math.max($,Math.min(H,s.scale+o));if(m.current){const h=m.current.getBoundingClientRect(),R=a.clientX-h.left-h.width/2,D=a.clientY-h.top-h.height/2,X=b/s.scale,A=R-X*(R-s.translateX),P=D-X*(D-s.translateY);l({scale:b,translateX:A,translateY:P})}else l(h=>({...h,scale:b}))},[s]),_=t.useCallback(a=>{a.button===0&&(a.preventDefault(),p(!0),j({x:a.clientX-s.translateX,y:a.clientY-s.translateY}))},[s.translateX,s.translateY]),U=t.useCallback(a=>{c&&(a.preventDefault(),l(o=>({...o,translateX:a.clientX-d.x,translateY:a.clientY-d.y})))},[c,d]),M=t.useCallback(()=>{p(!1)},[]),S=t.useCallback(a=>{if(a.touches.length===1){const o=a.touches[0];p(!0),j({x:o.clientX-s.translateX,y:o.clientY-s.translateY})}},[s.translateX,s.translateY]),n=t.useCallback(a=>{if(!c||a.touches.length!==1)return;const o=a.touches[0];l(b=>({...b,translateX:o.clientX-d.x,translateY:o.clientY-d.y}))},[c,d]),g=t.useCallback(()=>{p(!1)},[]),T=t.useCallback(()=>{I()},[I]),y=`
18
+ translate(${s.translateX}px, ${s.translateY}px)
19
+ scale(${s.scale})
20
+ rotate(${f}deg)
21
+ `;return e.jsxs("div",{ref:m,className:z("relative w-full h-full overflow-hidden select-none",c?"cursor-grabbing":"cursor-grab",C),onWheel:L,onMouseDown:_,onMouseMove:U,onMouseUp:M,onMouseLeave:M,onTouchStart:S,onTouchMove:n,onTouchEnd:g,onDoubleClick:T,children:[v&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("img",{ref:u,src:r,alt:E,className:z("max-w-none transition-transform duration-100",v&&"opacity-0"),style:{transform:y,transformOrigin:"center center"},onLoad:k,onError:i,draggable:!1})}),e.jsxs("div",{className:"absolute bottom-4 left-4 px-2 py-1 bg-background/80 backdrop-blur rounded text-xs text-muted-foreground",children:[Math.round(s.scale*100),"%"]})]})}const oe="https://via.placeholder.com/1920x1080?text=DeepScientist+Image+Viewer";function le(r){return r?r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`:"Unknown"}function W(r){return(r.split(".").pop()?.toLowerCase()||"").toUpperCase()}function he({context:r,tabId:E,setDirty:w,setTitle:N}){const[f,C]=t.useState(""),[v,x]=t.useState(!0),[s,l]=t.useState(null),[c,p]=t.useState(null),[d,j]=t.useState(0),[m,u]=t.useState(!1),k=t.useRef(null),i=r.resourceName||r.resourcePath||"Image";t.useEffect(()=>{N(i)},[i,N]),t.useEffect(()=>{let n=!1,g=null;return x(!0),l(null),r.resourceId?((async()=>{try{const{createFileObjectUrl:y}=await G(async()=>{const{createFileObjectUrl:a}=await import("./index-CBNVuWcP.js").then(o=>o.em);return{createFileObjectUrl:a}},__vite__mapDeps([0,1,2,3,4]));if(g=await y(r.resourceId),n){URL.revokeObjectURL(g);return}C(g)}catch(y){console.error("Failed to get image URL:",y),l("Failed to load image"),x(!1)}})(),()=>{n=!0,g&&URL.revokeObjectURL(g)}):(C(oe),()=>{n=!0})},[r.resourceId]);const I=t.useCallback(n=>{x(!1),p(n)},[]),L=t.useCallback(()=>{x(!1),l("Failed to load image")},[]),_=t.useCallback(()=>{j(n=>(n-90)%360)},[]),U=t.useCallback(()=>{j(n=>(n+90)%360)},[]);t.useCallback(()=>{j(0)},[]);const M=t.useCallback(()=>{if(!f)return;const n=document.createElement("a");n.href=f,n.download=i,n.click()},[f,i]),S=r.customData?.size;return s&&!v?e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsx("div",{className:"flex items-center px-4 py-2 border-b border-border bg-muted/30",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(F,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-foreground",children:i})]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[e.jsx(ee,{className:"w-16 h-16 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-medium text-foreground",children:"Failed to load image"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s})]}),e.jsx("button",{className:"px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",onClick:()=>window.location.reload(),children:"Retry"})]})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-background",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(F,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-foreground",children:i}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground",children:W(i)}),c&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[c.naturalWidth," x ",c.naturalHeight]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>k.current?.zoomOut?.(),className:"p-2 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground",title:"Zoom out",children:e.jsx(K,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>k.current?.resetTransform?.(),className:"p-2 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground",title:"Reset zoom (double-click image)",children:e.jsx(ae,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>k.current?.zoomIn?.(),className:"p-2 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground",title:"Zoom in",children:e.jsx(J,{className:"w-4 h-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx("button",{onClick:_,className:"p-2 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground",title:"Rotate left",children:e.jsx(Z,{className:"w-4 h-4"})}),e.jsx("button",{onClick:U,className:"p-2 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground",title:"Rotate right",children:e.jsx(re,{className:"w-4 h-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx("button",{onClick:()=>u(!m),className:z("p-2 rounded transition-colors",m?"bg-primary text-primary-foreground":"hover:bg-accent text-muted-foreground hover:text-foreground"),title:"Image info",children:e.jsx(B,{className:"w-4 h-4"})}),e.jsx("button",{onClick:M,className:"p-2 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground",title:"Download image",children:e.jsx(V,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"flex-1 relative overflow-hidden bg-[#1a1a1a]",children:[e.jsx("div",{className:"absolute inset-0 opacity-20",style:{backgroundImage:`
22
+ linear-gradient(45deg, #808080 25%, transparent 25%),
23
+ linear-gradient(-45deg, #808080 25%, transparent 25%),
24
+ linear-gradient(45deg, transparent 75%, #808080 75%),
25
+ linear-gradient(-45deg, transparent 75%, #808080 75%)
26
+ `,backgroundSize:"20px 20px",backgroundPosition:"0 0, 0 10px, 10px -10px, -10px 0px"}}),v&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:e.jsx(q,{className:"w-8 h-8 animate-spin text-muted-foreground"})}),f&&e.jsx(ne,{src:f,alt:i,rotation:d,onLoad:I,onError:L}),m&&c&&e.jsxs("div",{className:"absolute top-4 right-4 p-4 bg-background/90 backdrop-blur rounded-lg shadow-lg border border-border",children:[e.jsx("h3",{className:"font-medium text-foreground mb-3",children:"Image Information"}),e.jsxs("dl",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between gap-8",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Filename"}),e.jsx("dd",{className:"text-foreground font-mono",children:i})]}),e.jsxs("div",{className:"flex justify-between gap-8",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Dimensions"}),e.jsxs("dd",{className:"text-foreground font-mono",children:[c.naturalWidth," x ",c.naturalHeight]})]}),e.jsxs("div",{className:"flex justify-between gap-8",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Format"}),e.jsx("dd",{className:"text-foreground font-mono",children:W(i)})]}),S&&e.jsxs("div",{className:"flex justify-between gap-8",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Size"}),e.jsx("dd",{className:"text-foreground font-mono",children:le(S)})]}),d!==0&&e.jsxs("div",{className:"flex justify-between gap-8",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Rotation"}),e.jsxs("dd",{className:"text-foreground font-mono",children:[d,"deg"]})]})]})]})]}),e.jsx("div",{className:"flex items-center justify-center gap-2 px-4 py-2 border-t border-border bg-background",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Scroll to zoom | Drag to pan | Double-click to reset"})})]})}export{he as default};
@@ -0,0 +1,14 @@
1
+ import{y as qt,aP as Ft,j as s,aQ as St,n as Ct,u as Pt,ao as H,aR as He,aS as We,aT as zt,aU as vt,aV as ns,aW as yt,aX as Ve,at as Ce,au as at,aY as is,aZ as xt,J as _t,a_ as wt,av as Dt,d as $t,b as Me,x as Bt,a$ as Ht,b0 as dt,b1 as Wt,L as Vt,b2 as os,b3 as rs,b4 as as,b5 as ls,b6 as cs,k as us,b7 as ds,b8 as ms,b9 as fs,ba as hs,bb as ps,bc as gs,bd as bs}from"./index-CBNVuWcP.js";import{r}from"./plugin-monaco-C8UgLomw.js";import{r as Ye}from"./plugin-notebook-HbW2K-1c.js";import{P as xs,a as vs,b as ys}from"./popover-CLc0pPP8.js";import{S as _s,a as ws,b as Ss,c as Cs,d as Ms}from"./select-Cs2PmzwL.js";import{A as js,D as Es,C as ks,a as Mt,u as Ns,b as Qt,r as Ls}from"./AiManusChatView-Bv-Z8YpU.js";import"./plugin-terminal-MXFIPun8.js";import"./chevron-up-C9Qpx4DE.js";import"./file-content-BZMz3RYp.js";import"./file-jump-queue-DA-SdG__.js";import"./pdf-effect-queue-J8OnM0jE.js";import"./file-diff-panel-CQhw0jS2.js";import"./bot-DREQOxzP.js";import"./git-commit-horizontal-DxZ8DCZh.js";import"./NotebookEditor-DB9N_T9q.js";import"./trash-DwpbFr3w.js";/**
2
+ * @license lucide-react v0.511.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const As=[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]],Rs=qt("message-circle",As);/**
7
+ * @license lucide-react v0.511.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const Ts=[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]],jt=qt("thumbs-up",Ts);function it(i,u,t){let n=t.initialDeps??[],e,a=!0;function f(){var d,x,w;let _;t.key&&((d=t.debug)!=null&&d.call(t))&&(_=Date.now());const S=i();if(!(S.length!==n.length||S.some((q,k)=>n[k]!==q)))return e;n=S;let D;if(t.key&&((x=t.debug)!=null&&x.call(t))&&(D=Date.now()),e=u(...S),t.key&&((w=t.debug)!=null&&w.call(t))){const q=Math.round((Date.now()-_)*100)/100,k=Math.round((Date.now()-D)*100)/100,K=k/16,C=(T,I)=>{for(T=String(T);T.length<I;)T=" "+T;return T};console.info(`%c⏱ ${C(k,5)} /${C(q,5)} ms`,`
12
+ font-size: .6rem;
13
+ font-weight: bold;
14
+ color: hsl(${Math.max(0,Math.min(120-120*K,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(a&&t.skipInitialOnChange)&&t.onChange(e),a=!1,e}return f.updateDeps=d=>{n=d},f}function Et(i,u){if(i===void 0)throw new Error("Unexpected undefined");return i}const Os=(i,u)=>Math.abs(i-u)<1.01,Is=(i,u,t)=>{let n;return function(...e){i.clearTimeout(n),n=i.setTimeout(()=>u.apply(this,e),t)}},kt=i=>{const{offsetWidth:u,offsetHeight:t}=i;return{width:u,height:t}},qs=i=>i,Fs=i=>{const u=Math.max(i.startIndex-i.overscan,0),t=Math.min(i.endIndex+i.overscan,i.count-1),n=[];for(let e=u;e<=t;e++)n.push(e);return n},Ps=(i,u)=>{const t=i.scrollElement;if(!t)return;const n=i.targetWindow;if(!n)return;const e=f=>{const{width:d,height:x}=f;u({width:Math.round(d),height:Math.round(x)})};if(e(kt(t)),!n.ResizeObserver)return()=>{};const a=new n.ResizeObserver(f=>{const d=()=>{const x=f[0];if(x?.borderBoxSize){const w=x.borderBoxSize[0];if(w){e({width:w.inlineSize,height:w.blockSize});return}}e(kt(t))};i.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(d):d()});return a.observe(t,{box:"border-box"}),()=>{a.unobserve(t)}},Nt={passive:!0},Lt=typeof window>"u"?!0:"onscrollend"in window,zs=(i,u)=>{const t=i.scrollElement;if(!t)return;const n=i.targetWindow;if(!n)return;let e=0;const a=i.options.useScrollendEvent&&Lt?()=>{}:Is(n,()=>{u(e,!1)},i.options.isScrollingResetDelay),f=_=>()=>{const{horizontal:S,isRtl:E}=i.options;e=S?t.scrollLeft*(E&&-1||1):t.scrollTop,a(),u(e,_)},d=f(!0),x=f(!1);t.addEventListener("scroll",d,Nt);const w=i.options.useScrollendEvent&&Lt;return w&&t.addEventListener("scrollend",x,Nt),()=>{t.removeEventListener("scroll",d),w&&t.removeEventListener("scrollend",x)}},Ds=(i,u,t)=>{if(u?.borderBoxSize){const n=u.borderBoxSize[0];if(n)return Math.round(n[t.options.horizontal?"inlineSize":"blockSize"])}return i[t.options.horizontal?"offsetWidth":"offsetHeight"]},$s=(i,{adjustments:u=0,behavior:t},n)=>{var e,a;const f=i+u;(a=(e=n.scrollElement)==null?void 0:e.scrollTo)==null||a.call(e,{[n.options.horizontal?"left":"top"]:f,behavior:t})};class Bs{constructor(u){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,n,e;return((e=(n=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:n.now)==null?void 0:e.call(n))??Date.now()},this.observer=(()=>{let t=null;const n=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(e=>{e.forEach(a=>{const f=()=>{this._measureElement(a.target,a)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(f):f()})}));return{disconnect:()=>{var e;(e=n())==null||e.disconnect(),t=null},observe:e=>{var a;return(a=n())==null?void 0:a.observe(e,{box:"border-box"})},unobserve:e=>{var a;return(a=n())==null?void 0:a.unobserve(e)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([n,e])=>{typeof e>"u"&&delete t[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:qs,rangeExtractor:Fs,onChange:()=>{},measureElement:Ds,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...t}},this.notify=t=>{var n,e;(e=(n=this.options).onChange)==null||e.call(n,this,t)},this.maybeNotify=it(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,a)=>{this.scrollAdjustments=0,this.scrollDirection=a?this.getScrollOffset()<e?"forward":"backward":null,this.scrollOffset=e,this.isScrolling=a,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,n)=>{const e=new Map,a=new Map;for(let f=n-1;f>=0;f--){const d=t[f];if(e.has(d.lane))continue;const x=a.get(d.lane);if(x==null||d.end>x.end?a.set(d.lane,d):d.end<x.end&&e.set(d.lane,!0),e.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((f,d)=>f.end===d.end?f.index-d.index:f.end-d.end)[0]:void 0},this.getMeasurementOptions=it(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes],(t,n,e,a,f,d)=>(this.prevLanes!==void 0&&this.prevLanes!==d&&(this.lanesChangedFlag=!0),this.prevLanes=d,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:n,scrollMargin:e,getItemKey:a,enabled:f,lanes:d}),{key:!1}),this.getMeasurements=it(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:n,scrollMargin:e,getItemKey:a,enabled:f,lanes:d},x)=>{if(!f)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const E of this.laneAssignments.keys())E>=t&&this.laneAssignments.delete(E);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(E=>{this.itemSizeCache.set(E.key,E.size)}));const w=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const _=this.measurementsCache.slice(0,w),S=new Array(d).fill(void 0);for(let E=0;E<w;E++){const D=_[E];D&&(S[D.lane]=E)}for(let E=w;E<t;E++){const D=a(E),q=this.laneAssignments.get(E);let k,K;if(q!==void 0&&this.options.lanes>1){k=q;const A=S[k],R=A!==void 0?_[A]:void 0;K=R?R.end+this.options.gap:n+e}else{const A=this.options.lanes===1?_[E-1]:this.getFurthestMeasurement(_,E);K=A?A.end+this.options.gap:n+e,k=A?A.lane:E%this.options.lanes,this.options.lanes>1&&this.laneAssignments.set(E,k)}const C=x.get(D),T=typeof C=="number"?C:this.options.estimateSize(E),I=K+T;_[E]={index:E,start:K,size:T,end:I,key:D,lane:k},S[k]=E}return this.measurementsCache=_,_},{key:!1,debug:()=>this.options.debug}),this.calculateRange=it(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,n,e,a)=>this.range=t.length>0&&n>0?Hs({measurements:t,outerSize:n,scrollOffset:e,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=it(()=>{let t=null,n=null;const e=this.calculateRange();return e&&(t=e.startIndex,n=e.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,n]},(t,n,e,a,f)=>a===null||f===null?[]:t({startIndex:a,endIndex:f,overscan:n,count:e}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const n=this.options.indexAttribute,e=t.getAttribute(n);return e?parseInt(e,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const e=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(e!==void 0&&this.range){const a=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),f=Math.max(0,e-a),d=Math.min(this.options.count-1,e+a);return t>=f&&t<=d}return!0},this._measureElement=(t,n)=>{if(!t.isConnected){this.observer.unobserve(t);return}const e=this.indexFromElement(t),a=this.measurementsCache[e];if(!a)return;const f=a.key,d=this.elementsCache.get(f);d!==t&&(d&&this.observer.unobserve(d),this.observer.observe(t),this.elementsCache.set(f,t)),this.shouldMeasureDuringScroll(e)&&this.resizeItem(e,this.options.measureElement(t,n,this))},this.resizeItem=(t,n)=>{var e;const a=this.measurementsCache[t];if(!a)return;const f=this.itemSizeCache.get(a.key)??a.size,d=n-f;d!==0&&(((e=this.scrollState)==null?void 0:e.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(a,d,this):a.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=d,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(a.index),this.itemSizeCache=new Map(this.itemSizeCache.set(a.key,n)),this.notify(!1))},this.measureElement=t=>{if(!t){this.elementsCache.forEach((n,e)=>{n.isConnected||(this.observer.unobserve(n),this.elementsCache.delete(e))});return}this._measureElement(t,void 0)},this.getVirtualItems=it(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,n)=>{const e=[];for(let a=0,f=t.length;a<f;a++){const d=t[a],x=n[d];e.push(x)}return e},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const n=this.getMeasurements();if(n.length!==0)return Et(n[Ut(0,n.length-1,e=>Et(n[e]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,n,e=0)=>{if(!this.scrollElement)return 0;const a=this.getSize(),f=this.getScrollOffset();n==="auto"&&(n=t>=f+a?"end":"start"),n==="center"?t+=(e-a)/2:n==="end"&&(t-=a);const d=this.getMaxScrollOffset();return Math.max(Math.min(d,t),0)},this.getOffsetForIndex=(t,n="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const e=this.getSize(),a=this.getScrollOffset(),f=this.measurementsCache[t];if(!f)return;if(n==="auto")if(f.end>=a+e-this.options.scrollPaddingEnd)n="end";else if(f.start<=a+this.options.scrollPaddingStart)n="start";else return[a,n];if(n==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),n];const d=n==="end"?f.end+this.options.scrollPaddingEnd:f.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(d,n,f.size),n]},this.scrollToOffset=(t,{align:n="start",behavior:e="auto"}={})=>{const a=this.getOffsetForAlignment(t,n),f=this.now();this.scrollState={index:null,align:n,behavior:e,startedAt:f,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:e}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:n="auto",behavior:e="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const a=this.getOffsetForIndex(t,n);if(!a)return;const[f,d]=a,x=this.now();this.scrollState={index:t,align:d,behavior:e,startedAt:x,lastTargetOffset:f,stableFrames:0},this._scrollToOffset(f,{adjustments:void 0,behavior:e}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:n="auto"}={})=>{const e=this.getScrollOffset()+t,a=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:a,lastTargetOffset:e,stableFrames:0},this._scrollToOffset(e,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const n=this.getMeasurements();let e;if(n.length===0)e=this.options.paddingStart;else if(this.options.lanes===1)e=((t=n[n.length-1])==null?void 0:t.end)??0;else{const a=Array(this.options.lanes).fill(null);let f=n.length-1;for(;f>=0&&a.some(d=>d===null);){const d=n[f];a[d.lane]===null&&(a[d.lane]=d.end),f--}e=Math.max(...a.filter(d=>d!==null))}return Math.max(e-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:n,behavior:e})=>{this.options.scrollToFn(t,{behavior:e,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(u)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,e=n?n[0]:this.scrollState.lastTargetOffset,a=1,f=e!==this.scrollState.lastTargetOffset;if(!f&&Os(e,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.scrollState=null;return}}else this.scrollState.stableFrames=0,f&&(this.scrollState.lastTargetOffset=e,this.scrollState.behavior="auto",this._scrollToOffset(e,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Ut=(i,u,t,n)=>{for(;i<=u;){const e=(i+u)/2|0,a=t(e);if(a<n)i=e+1;else if(a>n)u=e-1;else return e}return i>0?i-1:0};function Hs({measurements:i,outerSize:u,scrollOffset:t,lanes:n}){const e=i.length-1,a=x=>i[x].start;if(i.length<=n)return{startIndex:0,endIndex:e};let f=Ut(0,e,a,t),d=f;if(n===1)for(;d<e&&i[d].end<t+u;)d++;else if(n>1){const x=Array(n).fill(0);for(;d<e&&x.some(_=>_<t+u);){const _=i[d];x[_.lane]=_.end,d++}const w=Array(n).fill(t+u);for(;f>=0&&w.some(_=>_>=t);){const _=i[f];w[_.lane]=_.start,f--}f=Math.max(0,f-f%n),d=Math.min(e,d+(n-1-d%n))}return{startIndex:f,endIndex:d}}const At=typeof document<"u"?r.useLayoutEffect:r.useEffect;function Ws({useFlushSync:i=!0,...u}){const t=r.useReducer(()=>({}),{})[1],n={...u,onChange:(a,f)=>{var d;i&&f?Ye.flushSync(t):t(),(d=u.onChange)==null||d.call(u,a,f)}},[e]=r.useState(()=>new Bs(n));return e.setOptions(n),At(()=>e._didMount(),[]),At(()=>e._willUpdate()),e}function Kt(i){return Ws({observeElementRect:Ps,observeElementOffset:zs,scrollToFn:$s,...i})}const Rt="lab-animation-level";function Vs(){const i=Ft(),[u,t]=r.useState("full");return r.useEffect(()=>{if(typeof window>"u")return;const e=window.localStorage.getItem(Rt);if(e){t(e);return}if(i){t("off");return}const a=typeof navigator<"u"&&navigator.hardwareConcurrency<=4;t(a?"simple":"full")},[i]),{level:u,setLevel:e=>{t(e),typeof window<"u"&&window.localStorage.setItem(Rt,e)}}}function Qs({projectId:i,readOnly:u,visible:t,prefill:n,leadMessage:e,hideCopilotGreeting:a,mentionablesOverride:f,defaultAgentOverride:d,mentionsEnabledOverride:x,enforcedMentionPrefix:w,lockedMentionPrefix:_,messageMetadata:S,composerMode:E,composerFooter:D,busyOverride:q,onActionsChange:k,onMetaChange:K,onUserSubmit:C}){const T=r.useMemo(()=>{if(!n?.text)return n??null;const N=n.text;if(!N.startsWith("@"))return n;const Q=N.match(/^@[^\s]+/);if(!Q)return n;const W=Q[0].length;return N[W]===" "?n:{...n,text:`${N.slice(0,W)} ${N.slice(W)}`}},[n]),[I,A]=r.useState(!1),R=r.useId();return s.jsx(js,{mode:"lab-direct",uiMode:"copilot",projectId:i,readOnly:u,visible:t,prefill:T,embedded:!0,historyMode:"overlay",layoutPadding:"flush",sessionListEnabled:!1,historyPanelId:R,historyOpenOverride:I,onHistoryOpenChange:A,onActionsChange:k,onMetaChange:K,mentionablesOverride:f,defaultAgentOverride:d,mentionsEnabledOverride:x,enforcedMentionPrefix:w,lockedMentionPrefix:_,lockLeadingMentionSpace:!0,messageMetadata:S,hideCopilotGreeting:a,composerMode:E,composerFooter:D,leadMessage:e,busyOverride:q,onUserSubmit:C})}const Gt=10,Us=300,Tt=(i,u)=>`text-${i.trim()?i.trim():"text"}-${u}`,Ot=(i,u=Gt)=>{const{scrollTop:t,scrollHeight:n,clientHeight:e}=i;return n-t-e<=u},It=(i,u=Gt)=>i.scrollTop<=u,Yt=({projectId:i,questId:u,surface:t,enabled:n})=>{const[e,a]=r.useState(null),[f,d]=r.useState([]),[x,w]=r.useState(!1),[_,S]=r.useState(null),[E,D]=r.useState(!1),[q,k]=r.useState(!1),[K,C]=r.useState(!1),[T,I]=r.useState(0),A=r.useRef(null),R=r.useRef(null),N=r.useRef([]),Q=r.useRef(new Map),W=r.useRef(new Set),$=r.useRef(null),U=r.useRef(0),P=r.useRef(!1),ie=r.useRef(!1),te=We(O=>O.setSessionIdForSurface),V=`lab-${t}`,J=r.useCallback(O=>typeof O=="number"&&Number.isFinite(O)?(O>U.current&&(U.current=O),O):(U.current+=1,U.current),[]),X=r.useCallback(O=>{N.current=O,d(O)},[]),G=r.useCallback(O=>{X([...N.current,O])},[X]),se=r.useCallback(()=>{N.current=[],d([]),Q.current=new Map,W.current=new Set,$.current=null,U.current=0},[]),y=r.useCallback(()=>{w(!1),S(null),D(!1),k(!1),C(!1),P.current=!1,ie.current=!1,I(0)},[]),h=r.useCallback(O=>{e&&Mt(O,{sessionId:e,messagesRef:N,assistantMessageIndexRef:Q,lastAssistantSegmentIdRef:$,attachmentsSeenRef:W,resolveTimelineSeq:J,buildTextDeltaId:Tt,appendMessage:G,updateMessages:X})},[G,J,e,X]),{sendMessage:m,restoreSession:F,stop:z,connection:ne}=Ns({sessionId:e,projectId:i,onEvent:h}),de=r.useRef(null),ge=r.useRef(!1);r.useEffect(()=>{if(!n||!i||!u){a(null),se(),y();return}A.current&&a(null);let O=!0;return(async()=>{se(),y(),k(!0);try{const me=t==="group"?await gs(i,u):await bs(i,u);if(!O)return;const le=me?.session_id?.trim?.()??me?.session_id;if(!le){a(null),k(!1),C(!0);return}a(le),te(i,`lab-${t}`,le)}catch{O&&k(!1)}})(),()=>{O=!1}},[n,i,u,y,se,te,t]),r.useEffect(()=>{if(!n||!e)return;let O=!0;return(async()=>{const me=ie.current,le=P.current||me;me&&(ie.current=!1),se(),k(!0);try{const ee=await F(le?{full:!0}:{limit:Us});if(!O)return;const ce=Array.isArray(ee?.events)?ee.events:[];let ue=null;ce.forEach(oe=>{!oe||!oe.event||!oe.data||(oe.data?.event_id&&(ue=oe.data.event_id),Mt({event:oe.event,data:oe.data},{sessionId:e,messagesRef:N,assistantMessageIndexRef:Q,lastAssistantSegmentIdRef:$,attachmentsSeenRef:W,resolveTimelineSeq:J,buildTextDeltaId:Tt,appendMessage:G,updateMessages:X}))});const be=!!ee?.events_truncated,p=typeof ee?.event_limit=="number"?ee.event_limit:null;if(w(be),S(p),le?P.current=!be:P.current=!1,ue&&We.getState().setLastEventId(e,ue),!O)return;try{await m({sessionId:e,message:"",surface:`lab-${t}`,replayFromLastEvent:!0})}catch{}}finally{me&&O&&D(!1),O&&(k(!1),C(!0))}})(),()=>{O=!1}},[G,n,J,se,F,T,m,e,t,X]),r.useEffect(()=>{if(!n||!e)return;let O=!0;const Ee=()=>{const me=2e4+Math.floor(Math.random()*1e4);de.current=window.setTimeout(async()=>{if(!O||!e||ge.current){Ee();return}ge.current=!0;try{await m({sessionId:e,message:"",surface:V,replayFromLastEvent:!0})}catch{}finally{ge.current=!1}Ee()},me)};return Ee(),()=>{O=!1,de.current&&(window.clearTimeout(de.current),de.current=null)}},[n,m,e,V]),r.useEffect(()=>{if(!(!n||!e)&&(ne.status==="closed"||ne.status==="error")){if(ge.current)return;ge.current=!0,m({sessionId:e,message:"",surface:V,replayFromLastEvent:!0}).finally(()=>{ge.current=!1})}},[ne.status,n,m,e,V]),r.useEffect(()=>{A.current=e},[e]),r.useEffect(()=>{R.current&&R.current!==e&&z(R.current),R.current=e},[e,z]),r.useEffect(()=>()=>{A.current&&z(A.current)},[z]);const je=r.useCallback(()=>{!e||!n||E||P.current||(ie.current=!0,D(!0),I(O=>O+1))},[n,E,e]);return{sessionId:e,messages:f,connection:ne,sendMessage:m,historyTruncated:x,historyLimit:_,historyLoadingFull:E,historyLoading:q,hasLoadedOnce:K,loadFullHistory:je}},mt=i=>{const u=i.content;return typeof u?.content=="string"?u.content:""},Se=i=>i.content?.metadata??null,Xt=i=>{if(i)return{selection_type:i.selection_type,selection_ref:i.selection_ref,quest_id:i.quest_id,branch_name:i.branch_name??void 0,edge_id:i.edge_id??void 0,agent_instance_id:i.agent_instance_id??void 0,worktree_rel_path:i.worktree_rel_path??void 0}},Zt=i=>i?i.label?.trim()?i.label.trim():i.branch_name?.trim()||i.edge_id?.trim()||i.agent_instance_id?.trim()||i.selection_ref:"",Ks=(i,u)=>{const t=typeof u=="string"?u.trim().toLowerCase():"";return t?t==="queued"?i("copilot_group_reply_state_queued",void 0,"Queued"):t==="acked"?i("copilot_group_reply_state_acked",void 0,"Acknowledged"):t==="final"?i("copilot_group_reply_state_final",void 0,"Final"):t:null};function Jt({selection:i,proposal:u,onClearSelection:t,onClearProposal:n,selectionPrefix:e,proposalPrefix:a}){return!i&&!u?null:s.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-[var(--lab-border)] bg-[var(--lab-background)] px-4 py-3",children:[i?s.jsxs("button",{type:"button",onClick:t,className:"inline-flex items-center gap-2 rounded-full border border-[var(--lab-border)] bg-[var(--lab-surface)] px-3 py-1 text-[11px] font-medium text-[var(--lab-text-primary)]",children:[s.jsx("span",{className:"text-[var(--lab-text-secondary)]",children:e}),s.jsx("span",{children:Zt(i)}),s.jsx("span",{className:"text-[var(--lab-text-muted)]",children:"×"})]}):null,u?s.jsxs("button",{type:"button",onClick:n,className:"inline-flex items-center gap-2 rounded-full border border-[rgba(83,176,174,0.28)] bg-[rgba(83,176,174,0.12)] px-3 py-1 text-[11px] font-medium text-[var(--lab-text-primary)]",children:[s.jsx("span",{className:"text-[var(--lab-text-secondary)]",children:a}),s.jsx("span",{children:u.action_type}),s.jsxs("span",{className:"text-[var(--lab-text-muted)]",children:["· ",u.status]}),s.jsx("span",{className:"text-[var(--lab-text-muted)]",children:"×"})]}):null]})}const ut=i=>i.type!=="text_delta"?null:i.content.role,es=i=>{if(i==null)return"";const u=typeof i=="number"?new Date(i<1e12?i*1e3:i):new Date(i);if(Number.isNaN(u.getTime()))return"";const t=w=>String(w).padStart(2,"0"),n=t(u.getFullYear()%100),e=t(u.getMonth()+1),a=t(u.getDate()),f=t(u.getHours()),d=t(u.getMinutes()),x=t(u.getSeconds());return`${n}-${e}-${a} ${f}-${d}-${x}`},ft=i=>{if(ut(i)==="user")return"You";const t=Se(i);return t?.sender_name?t.sender_name:t?.agent_display_name?t.agent_display_name:t?.sender_label?t.sender_label:t?.agent_label?t.agent_label:t?.agent_id?`@${t.agent_id}`:"Agent"},Gs=i=>{if(!i)return[];const u=n=>{if(typeof n=="string"){const d=n.trim();return d?{url:d}:null}if(!n||typeof n!="object")return null;const e=n,a=typeof e.url=="string"&&e.url||typeof e.src=="string"&&e.src||typeof e.file_url=="string"&&e.file_url||typeof e.preview_url=="string"&&e.preview_url||typeof e.path=="string"&&e.path||"";if(!a)return null;const f=typeof e.label=="string"?e.label:void 0;return{url:a,label:f}},t=Array.isArray(i)?i:typeof i=="object"?i.items||i.images||i.files||[]:[];return Array.isArray(t)?t.map(n=>u(n)).filter(n=>!!n).slice(0,9):[]},Ys=i=>{if(!i)return[];const u=e=>{if(typeof e=="string"){const x=e.trim();return x?{name:x}:null}if(!e||typeof e!="object")return null;const a=e,d=(typeof a.name=="string"&&a.name||typeof a.user_name=="string"&&a.user_name||typeof a.username=="string"&&a.username||typeof a.display_name=="string"&&a.display_name||typeof a.label=="string"&&a.label||typeof a.user_id=="string"&&a.user_id||"").trim();return d?{name:d}:null},t=Array.isArray(i)?i:typeof i=="object"?i.items||i.users||i.likes||[]:[];return(Array.isArray(t)?t:[]).map(e=>u(e)).filter(e=>!!e)},Xs=i=>{if(!i)return[];const u=e=>{if(typeof e=="string"){const _=e.trim();return _?{name:"Unknown",content:_}:null}if(!e||typeof e!="object")return null;const a=e,f=typeof a.name=="string"&&a.name||typeof a.user_name=="string"&&a.user_name||typeof a.username=="string"&&a.username||typeof a.display_name=="string"&&a.display_name||typeof a.label=="string"&&a.label||typeof a.user_id=="string"&&a.user_id||"",d=typeof a.content=="string"&&a.content||typeof a.text=="string"&&a.text||typeof a.message=="string"&&a.message||typeof a.body=="string"&&a.body||"",x=f.trim()||"Unknown",w=d.trim();return w?{name:x,content:w}:null},t=Array.isArray(i)?i:typeof i=="object"?i.items||i.comments||i.entries||[]:[];return(Array.isArray(t)?t:[]).map(e=>u(e)).filter(e=>!!e)},Zs=(i,u)=>{const t=new Map;return i.forEach(n=>{const e=n.name.trim().toLowerCase();e&&(t.has(e)||t.set(e,n.name))}),u.forEach(n=>{const e=n.name.trim().toLowerCase();e&&(t.has(e)||t.set(e,n.name))}),Array.from(t.values())},Js=(i,u)=>{const t=new Map;return i.forEach(n=>{const e=`${n.name.trim().toLowerCase()}::${n.content.trim().toLowerCase()}`;t.has(e)||t.set(e,n)}),u.forEach(n=>{const e=`${n.name.trim().toLowerCase()}::${n.content.trim().toLowerCase()}`;t.has(e)||t.set(e,n)}),Array.from(t.values())},en=i=>{const u=i.content;if(typeof u?.timestamp=="number")return new Date(u.timestamp*1e3).toISOString();const t=u?.metadata;return typeof t?.source_ts=="string"?t.source_ts:null};function _n({disabled:i,agents:u,templates:t,quests:n,onClearChat:e,clearChatDisabled:a}){const f=H(m=>m.mode),d=H(m=>m.setMode),x=H(m=>m.activeAgentId),w=H(m=>m.activeQuestId),_=H(m=>m.followEffects),S=H(m=>m.setFollowEffects),E=H(m=>m.agentStatusOverrides),D=H(m=>m.piOnboardingActive),q=H(m=>m.endPiOnboarding),k=r.useMemo(()=>new Map(t.map(m=>[m.template_id,m])),[t]),K=r.useMemo(()=>zt(u),[u]),C=r.useMemo(()=>x?u.find(m=>m.instance_id===x)??null:null,[x,u]),T=C?.template_id?k.get(C.template_id)??null:null,I=C?.active_quest_id??w??null,A=I?n.find(m=>m.quest_id===I)??null:null,R=A?Dt(A):"Not joined yet",N=C?Ce(C):"",Q=C?Ve(C,T):"",W=C?K.get(C.instance_id)||wt(C.instance_id):null,U=(C?E[C.instance_id]??null:null)??C?.status??"",P=typeof U=="string"?U.trim():"",ie=f==="direct"&&C&&!!P&&vt(P)&&P.toLowerCase()!=="waiting",[te,V]=r.useState(null),J=!!(a||!e),X=[{value:"direct",label:"Direct"},{value:"group",label:"Group"},{value:"friends",label:"Friends"}],G=r.useCallback(m=>{e&&(m.preventDefault(),m.stopPropagation(),V({x:m.clientX,y:m.clientY}))},[e]),se=r.useCallback(()=>{J||!e||(e(),V(null))},[J,e]),y=r.useCallback(()=>{S(!_),V(null)},[_,S]);r.useEffect(()=>{if(!te)return;const m=()=>V(null),F=z=>{z.key==="Escape"&&V(null)};return window.addEventListener("click",m),window.addEventListener("contextmenu",m),window.addEventListener("keydown",F),window.addEventListener("scroll",m,!0),()=>{window.removeEventListener("click",m),window.removeEventListener("contextmenu",m),window.removeEventListener("keydown",F),window.removeEventListener("scroll",m,!0)}},[te]);const h=te&&typeof document<"u"?Ye.createPortal(s.jsxs("div",{className:"lab-copilot-context-menu",style:{left:te.x,top:te.y},children:[s.jsxs("div",{className:"lab-copilot-context-item",children:["Quest: ",R]}),s.jsx("button",{type:"button",onClick:se,disabled:J,children:"Clear chat"}),s.jsxs("button",{type:"button",onClick:y,children:[s.jsx($t,{size:14,className:Me("shrink-0",_?"opacity-100":"opacity-0")}),"Follow effects"]})]}),document.body):null;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"lab-copilot-header",children:[s.jsx("div",{className:"lab-section-tabs lab-copilot-tabs",role:"tablist","aria-label":"Copilot modes",children:X.map(m=>{const F=f===m.value;return s.jsxs("button",{type:"button",role:"tab","aria-selected":F,disabled:i,onClick:()=>d(m.value),className:Me("lab-section-tab",F&&"lab-section-tab-active",i&&"cursor-not-allowed opacity-60"),children:[m.label,F?s.jsx("span",{className:"lab-section-tab-indicator"}):null]},m.value)})}),f==="direct"&&C?s.jsxs("div",{className:"lab-copilot-agent",onContextMenu:G,children:[s.jsxs("div",{className:"lab-avatar lab-avatar-sm",children:[s.jsx("span",{className:"lab-avatar-ring",style:{borderColor:W||wt(C.instance_id)}}),s.jsx("img",{src:Q,alt:N||"Agent"})]}),s.jsxs("div",{className:"lab-copilot-agent-meta",children:[N?s.jsx("div",{className:"lab-copilot-agent-name",children:N}):null,ie?s.jsxs("div",{className:"lab-copilot-agent-status",children:[s.jsx("span",{className:"lab-status-dot lab-status-dot-running"}),s.jsx("span",{children:"Working"})]}):null]}),D?s.jsx("button",{type:"button",className:"lab-onboarding-exit",onClick:q,children:"Exit onboarding"}):null]}):null]}),h]})}function wn({projectId:i,readOnly:u,cliStatus:t,templates:n,agents:e,quests:a,prefill:f,onActionsChange:d}){const x=St(),{addToast:w}=Ct(),{t:_}=Pt("lab"),S=H(o=>o.mode),E=H(o=>o.activeAgentId),D=H(o=>o.activeQuestId),q=H(o=>o.directPrefill),k=H(o=>o.directComposeRequest),K=H(o=>o.setActiveQuest),C=H(o=>o.setActiveAgent),T=H(o=>o.setDirectPrefill),I=H(o=>o.clearDirectComposeRequest),A=H(o=>o.agentStatusOverrides),R=H(o=>o.setAgentStatusOverride),N=H(o=>o.piOnboardingActive),Q=H(o=>o.piOnboardingQuestId),W=H(o=>o.piOnboardingKind),$=H(o=>o.endPiOnboarding),U=He(o=>o.selection),P=He(o=>o.activeProposal),ie=He(o=>o.setSelection),te=He(o=>o.setActiveProposal),V=We(o=>o.setSessionIdForSurface),J=We(o=>o.clearSessionIdForSurface),X=We(o=>i?o.sessionIdsByProjectSurface[i]?.["lab-direct"]??null:null),G=We(o=>i?o.cliServerIdsByProject[i]??null:null),[se,y]=r.useState(null),[h,m]=r.useState(null),[F,z]=r.useState(null),ne=r.useRef(null),de=r.useRef("init"),ge=r.useRef(null),je=r.useRef(!1),{level:O}=Vs(),Ee=Ft(),me=O==="full"&&!Ee,le=r.useCallback((o,b)=>o?o.threadId===b.threadId&&o.historyOpen===b.historyOpen&&o.isResponding===b.isResponding&&o.ready===b.ready&&o.isRestoring===b.isRestoring&&o.restoreAttempted===b.restoreAttempted&&o.hasHistory===b.hasHistory&&o.error===b.error&&o.title===b.title&&o.statusText===b.statusText&&o.statusPrevText===b.statusPrevText&&o.statusKey===b.statusKey&&o.toolPanelVisible===b.toolPanelVisible&&o.toolToggleVisible===b.toolToggleVisible&&o.attachmentsDrawerOpen===b.attachmentsDrawerOpen&&o.fixWithAiRunning===b.fixWithAiRunning:!1,[]);r.useEffect(()=>{S!=="direct"&&(de.current="init")},[S]);const ee=r.useMemo(()=>new Map(n.map(o=>[o.template_id,o])),[n]),ce=r.useMemo(()=>new Map(e.map(o=>[o.instance_id,o])),[e]),ue=r.useMemo(()=>zt(e),[e]),be=E??null,p=be?ce.get(be)??null:null,oe=!!F?.isResponding,Xe=p&&A[p.instance_id]?A[p.instance_id]:p?.status??"",fe=typeof Xe=="string"?Xe.toLowerCase():"",Ze=!!p&&!!fe&&vt(fe)&&fe!=="waiting",Qe=typeof p?.status=="string"?p.status.toLowerCase():"",Re=S==="direct"&&!!p&&oe&&Qe!=="waiting"?"working":null,ze=p?A[p.instance_id]??null:null;r.useEffect(()=>{const o=ge.current,b=p?.instance_id??null;o&&o!==b&&R(o,null),ge.current=b},[p?.instance_id,R]),r.useEffect(()=>{p?.instance_id&&ze!==Re&&R(p.instance_id,Re)},[p?.instance_id,ze,Re,R]),r.useEffect(()=>{if(!i||S!=="direct"||!p?.instance_id){je.current=!1;return}const o=je.current;je.current=oe,o&&!oe&&x.invalidateQueries({queryKey:["lab-agents",i]})},[p?.instance_id,oe,S,i,x]);const _e=p?.template_id?ee.get(p.template_id)??null:null,Ue=_e?.init_question?.trim()||"",De=!!Ue,$e=(p?.active_quest_id?a.find(o=>o.quest_id===p.active_quest_id):a.find(o=>o.quest_id===D))??null,Ie=S==="direct"&&De,ae=!!(F?.ready&&F?.restoreAttempted&&!F?.isRestoring),ke=Ie&&ae&&!F?.hasHistory,Ke=Ie&&!ae,[Je,he]=r.useState(null),[et,ot]=r.useState(0),Ne=r.useRef(null),Te=r.useRef(0),Le=r.useCallback(()=>{Ne.current&&window.clearTimeout(Ne.current),Ne.current=null,Te.current=0},[]),qe=r.useCallback(()=>{if(Ne.current)return;const o=Math.min(Te.current,4),b=Math.min(15e3,1500*2**o);Te.current=o+1,Ne.current=window.setTimeout(()=>{Ne.current=null,ot(j=>j+1)},b)},[]);r.useEffect(()=>()=>Le(),[Le]),r.useEffect(()=>{D||a.length!==1||K(a[0].quest_id)},[D,a,K]),r.useEffect(()=>{if(!i||S!=="direct")return;if(!p?.instance_id){he(null),Le(),J(i,"lab-direct");return}const o=p.direct_session_id??null;o&&(he(j=>j===o?j:o),X!==o&&V(i,"lab-direct",o));let b=!1;return ns(i,p.instance_id).then(j=>{b||(Le(),he(j.session_id),X!==j.session_id&&V(i,"lab-direct",j.session_id))}).catch(j=>{if(b)return;const Z=typeof j?.response?.data?.detail=="string"?j.response.data.detail:null;if(Z&&["cli_server_required","cli_offline","cli_server_not_bound"].includes(Z)){qe(),x.invalidateQueries({queryKey:["lab-agents",i]});return}o||he(null)}),()=>{b=!0}},[p?.direct_session_id,p?.instance_id,p?.cli_server_id,p?.active_quest_id,p?.active_quest_node_id,J,X,et,S,i,x,Le,qe,V]),r.useEffect(()=>{if(N){if(!p){$();return}_e?.template_key!=="pi"&&p.agent_id!=="pi"&&$()}},[p,_e?.template_key,$,N]),r.useEffect(()=>{N&&F?.hasHistory&&$()},[F?.hasHistory,$,N]);const Be=t!=="online",xe=u||Be,tt=!xe&&!(S==="direct"&&ke),Ge=r.useMemo(()=>e.map(o=>{const b=o.template_id?ee.get(o.template_id)??null:null;return yt(o,b)}),[e,ee]),c=r.useMemo(()=>{if(!p)return;const o=p.template_id?ee.get(p.template_id)??null:null;return yt(p,o)},[p,ee]);r.useEffect(()=>{if(!p){y(null);return}if(ke){y(null);return}if(Ke){y(null);return}const o=p.mention_label?.trim()||p.agent_id,b=o.startsWith("@")?o:`@${o}`;y({text:`${b} `,focus:!1,token:Date.now()})},[p,Ke,ke]);const M=r.useMemo(()=>{if(p){const o=p.mention_label?.trim()||p.agent_id;return o.startsWith("@")?o:`@${o}`}return`@${Es}`},[p]),L=ke,B=S==="direct"?M:void 0,Y=p&&S==="direct"?M:void 0,ve=r.useCallback(()=>{if(xe){w({type:"warning",title:"Recruitment unavailable",description:t==="online"?"Recruitment is disabled in read-only mode.":"Bind an execution server to recruit agents."});return}typeof window<"u"&&window.dispatchEvent(new CustomEvent("lab:open-recruit"))},[w,t,xe]),we=r.useCallback(o=>{C(o)},[C]),st=r.useMemo(()=>{if(!p)return{agent_label:M};const o=Ve(p,_e);return{agent_label:M,agent_id:p.agent_id,agent_instance_id:p.instance_id,agent_display_name:Ce(p),agent_logo:o||void 0}},[p,_e,M]),nt=r.useMemo(()=>{if(!L)return null;const o=Math.floor(Date.now()/1e3);return{id:`lab-starter-${be??"unknown"}`,type:"text_delta",seq:0,ts:o,content:{content:Ue,role:"assistant",status:"completed",timestamp:o,metadata:st}}},[Ue,be,st,L]),rt=r.useCallback(o=>{m(o),d?.(o)},[d]),ht=r.useCallback(o=>{z(b=>le(b,o)?b:o)},[le]),pt=r.useCallback(o=>{k?I():q&&T(null),N&&$()},[I,k,q,$,N,T]),lt=r.useMemo(()=>f||(k?.text?.trim()?{text:k.text,focus:!0,token:k.token}:q&&q.trim()?{text:q,focus:!0,token:Date.now()}:se),[se,k,q,f]);r.useEffect(()=>{const o=k;if(!o||o.submitMode!=="auto"||S!=="direct"||!h?.setComposerValue||!h.submitComposer||F?.isResponding||ne.current===o.token)return;ne.current=o.token,h.setComposerValue(o.text,!0);const b=window.setTimeout(()=>{h.submitComposer?.()},30);return()=>{window.clearTimeout(b)}},[h,F?.isResponding,k,S]),r.useEffect(()=>{if(S!=="direct"||!h)return;const o=p?.instance_id??"none",b=Je??p?.direct_session_id??X??null;if(b){X!==b&&(h.clearThread?.(),h.setThreadId(b)),de.current=o;return}de.current!==o&&(de.current=o,h.setThreadId(null))},[p?.direct_session_id,p?.instance_id,h,X,Je,xe,S]);const ct=r.useMemo(()=>{if(!p)return null;const o=N&&Q?Q:null,b=Ve(p,_e),j=Xt(U);return{lab_mode:"direct",quest_id:o??p.active_quest_id??void 0,quest_node_id:p.active_quest_node_id??void 0,agent_id:p.agent_id,agent_label:at(p),agent_display_name:Ce(p),agent_logo:b||null,agent_avatar_color:p.avatar_frame_color??void 0,agent_instance_id:p.instance_id,cli_server_id:p.cli_server_id??G??void 0,pi_onboarding_kind:N?W??void 0:void 0,selection_context:j,proposal_id:P?.proposal_id??void 0,target_label:at(p),message_kind:j||P?"user_control":N?"pi_onboarding":"text"}},[p,_e,P,G,N,W,Q,U]),l=r.useMemo(()=>s.jsx(Jt,{selection:U,proposal:P?{proposal_id:P.proposal_id,action_type:P.action_type,status:P.status}:null,onClearSelection:()=>ie(null),onClearProposal:()=>te(null),selectionPrefix:_("copilot_selection_chip",void 0,"Ref"),proposalPrefix:_("copilot_proposal_chip",void 0,"Proposal")}),[P,U,te,ie,_]),v=me?{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:-12},transition:{duration:.2,ease:[0,0,.2,1]}}:{initial:!1,animate:{opacity:1},exit:{opacity:1},transition:{duration:0}};return s.jsx("div",{className:"flex h-full min-h-0 flex-col",children:s.jsxs(s.Fragment,{children:[Be?s.jsx("div",{className:"border-b border-[var(--lab-border)] px-5 py-2 text-xs text-[var(--lab-text-secondary)]",children:t==="unbound"?"Bind an execution server to activate Lab Copilot.":"Your execution server is offline. Messages will be sent once it reconnects."}):null,s.jsxs(is,{mode:"wait",initial:!1,children:[S==="direct"?s.jsx(xt.div,{className:"flex flex-1 min-h-0 flex-col overflow-hidden",...v,children:s.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden",children:[N?s.jsxs("div",{className:"lab-pi-onboarding-banner",children:[s.jsxs("div",{children:[s.jsx("div",{className:"lab-pi-onboarding-title",children:"Chat with PI"}),s.jsx("div",{className:"lab-pi-onboarding-subtitle",children:"Send your message to start the conversation."})]}),s.jsx("button",{type:"button",onClick:$,children:"Exit"})]}):null,p?s.jsx(Qs,{projectId:i,readOnly:xe,prefill:lt,leadMessage:L?nt:null,mentionablesOverride:Ge,defaultAgentOverride:c,mentionsEnabledOverride:tt,enforcedMentionPrefix:B,lockedMentionPrefix:Y,messageMetadata:ct??void 0,composerFooter:l,hideCopilotGreeting:L,busyOverride:Ze,onActionsChange:rt,onMetaChange:ht,onUserSubmit:pt}):s.jsx("div",{className:"flex h-full flex-col items-center justify-center px-6 py-8",children:s.jsxs("div",{className:"w-full max-w-3xl",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-base font-semibold text-[var(--lab-text-primary)]",children:"Choose an agent"}),s.jsx("div",{className:"text-xs text-[var(--lab-text-secondary)]",children:"Select an agent to start a direct chat."})]}),s.jsx(_t,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:ve,disabled:xe,children:"Recruit Agent"})]}),e.length===0?s.jsx("div",{className:"mt-4 rounded-xl border border-[var(--lab-border)] bg-[var(--lab-surface)] p-4 text-xs text-[var(--lab-text-secondary)]",children:"No agents yet. Recruit an agent to begin a direct chat."}):s.jsx("div",{className:"mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2",children:e.map((o,b)=>{const j=o.template_id?ee.get(o.template_id)??null:null,Z=Ce(o),Oe=at(o),Fe=ue.get(o.instance_id)??wt(o.instance_id,b),ye=Ve(o,j),re=typeof o.status=="string"?o.status.toLowerCase():"idle",Pe=re!=="waiting"&&vt(re),pe=Pe?"lab-status-dot-running":re==="waiting"?"lab-status-dot-busy":"lab-status-dot-idle";return s.jsx("button",{type:"button",className:"text-left",onClick:()=>we(o.instance_id),children:s.jsxs("div",{className:"lab-card lab-card-hover flex items-center gap-3 rounded-xl border border-[var(--lab-border)] bg-[var(--lab-surface)] p-3",children:[s.jsxs("div",{className:"lab-avatar lab-avatar-sm",children:[s.jsx("span",{className:"lab-avatar-ring",style:{borderColor:Fe}}),s.jsx("img",{src:ye,alt:Z})]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-sm font-semibold text-[var(--lab-text-primary)] truncate",children:Z}),s.jsx("div",{className:"text-xs text-[var(--lab-text-secondary)] truncate",children:Oe})]}),s.jsxs("div",{className:"flex items-center gap-2 text-[10px] uppercase text-[var(--lab-text-muted)]",children:[s.jsx("span",{className:`lab-status-dot ${pe}`}),Pe?"Working":re==="waiting"?"Waiting":"Idle"]})]})},o.instance_id)})})]})})]})},"direct"):null,S==="group"?s.jsx(xt.div,{className:"flex flex-1 min-h-0 flex-col overflow-hidden",...v,children:s.jsx(tn,{projectId:i,quest:$e,quests:a,agents:e,templatesById:ee,readOnly:xe,onQuestChange:K})},"group"):null,S==="friends"?s.jsx(xt.div,{className:"flex flex-1 min-h-0 flex-col overflow-hidden",...v,children:s.jsx(nn,{projectId:i,agents:e,templatesById:ee,readOnly:xe,quest:$e,quests:a,onQuestChange:K})},"friends"):null]})]})})}const ts=(i,u,t=90)=>{const n=i.trim();if(!n)return"";const e=u.trim().toLowerCase();if(!e)return n.slice(0,t);const f=n.toLowerCase().indexOf(e);if(f===-1)return n.slice(0,t);const d=Math.floor(t/2),x=Math.max(0,f-d),w=Math.min(n.length,f+e.length+d),_=x>0?"...":"",S=w<n.length?"...":"";return`${_}${n.slice(x,w)}${S}`};function ss({label:i,entities:u,emptyEntitiesLabel:t,searchValue:n,onSearchChange:e,searchResults:a,onSearchSelect:f,searchPlaceholder:d,questId:x,quests:w,onQuestChange:_,canManageRoster:S,rosterBusy:E,availableAgents:D,onAddAgents:q,onRemoveAgent:k}){const K=n.trim().length>0,C=!!(S&&!E),T=D??[],[I,A]=r.useState(!1),[R,N]=r.useState(new Set),[Q,W]=r.useState(!1),[$,U]=r.useState(null);r.useEffect(()=>{I||N(new Set)},[I]),r.useEffect(()=>{N(new Set)},[x]),r.useEffect(()=>{if(!$)return;const y=()=>U(null),h=m=>{m.key==="Escape"&&U(null)};return window.addEventListener("click",y),window.addEventListener("contextmenu",y),window.addEventListener("keydown",h),window.addEventListener("scroll",y,!0),()=>{window.removeEventListener("click",y),window.removeEventListener("contextmenu",y),window.removeEventListener("keydown",h),window.removeEventListener("scroll",y,!0)}},[$]);const P=r.useCallback(y=>{N(h=>{const m=new Set(h);return m.has(y)?m.delete(y):m.add(y),m})},[]),ie=r.useCallback(async()=>{if(!C||!q)return;const y=Array.from(R);if(y.length!==0){W(!0);try{await q(y),A(!1),N(new Set)}finally{W(!1)}}},[C,q,R]),te=r.useCallback((y,h)=>{!C||!k||(y.preventDefault(),y.stopPropagation(),U({agentId:h,x:y.clientX,y:y.clientY}))},[C,k]),V=r.useCallback(()=>{!$||!k||!C||(k($.agentId),U(null))},[$,C,k]),J=$&&typeof document<"u"?Ye.createPortal(s.jsx("div",{className:"lab-copilot-context-menu",style:{left:$.x,top:$.y},children:s.jsx("button",{type:"button",onClick:V,disabled:!C,children:"Remove from quest"})}),document.body):null,X=!!q,G=!C||T.length===0,se=x?T.length===0?"All available agents are already in this quest.":"Add agents to this quest.":"Select a quest to add agents.";return s.jsxs(xs,{modal:!1,children:[s.jsx(vs,{asChild:!0,children:s.jsx("button",{type:"button",className:"ds-copilot-icon-btn lab-copilot-overflow-trigger","aria-label":`${i} options`,"data-tooltip":`${i} options`,children:s.jsx(ls,{size:16})})}),s.jsxs(ys,{align:"end",sideOffset:12,className:"lab-copilot-menu",children:[s.jsxs("div",{className:"lab-copilot-menu-section",children:[s.jsxs("div",{className:"lab-copilot-menu-title",children:[i," roster"]}),s.jsxs("div",{className:"lab-copilot-entity-list",children:[u.map(y=>s.jsxs("div",{className:Me("lab-copilot-entity",C&&"is-manageable"),onContextMenu:h=>te(h,y.id),children:[s.jsx("div",{className:"lab-avatar lab-avatar-sm",children:s.jsx("img",{src:y.avatar,alt:y.name})}),s.jsx("span",{className:"lab-copilot-entity-name",title:y.name,children:y.name})]},y.id)),X?s.jsx("button",{type:"button",className:"lab-copilot-entity lab-copilot-entity-add",onClick:()=>A(!0),disabled:G,title:se,"aria-label":"Add agents",children:s.jsx(cs,{size:14})}):null]}),u.length?null:s.jsx("div",{className:"lab-copilot-menu-muted",children:t})]}),s.jsxs("div",{className:"lab-copilot-menu-section",children:[s.jsx("div",{className:"lab-copilot-menu-title",children:"Search chat"}),s.jsxs("div",{className:"lab-copilot-search",children:[s.jsx(us,{size:14}),s.jsx("input",{type:"text",value:n,onChange:y=>e(y.target.value),placeholder:d,className:"lab-copilot-search-input"})]}),K?a.length?s.jsx("div",{className:"lab-copilot-search-results",children:a.map(y=>s.jsxs("button",{type:"button",className:"lab-copilot-search-result",onClick:()=>f(y),children:[s.jsx("div",{className:"lab-copilot-search-title",children:y.title}),s.jsx("div",{className:"lab-copilot-search-excerpt",children:y.excerpt})]},y.id))}):s.jsx("div",{className:"lab-copilot-menu-muted",children:"No matches found."}):s.jsx("div",{className:"lab-copilot-menu-muted",children:"Type to search this chat."})]}),s.jsxs("div",{className:"lab-copilot-menu-section",children:[s.jsx("div",{className:"lab-copilot-menu-title",children:"Switch quest"}),w.length?s.jsxs(_s,{value:x??"",onValueChange:y=>_(y||null),children:[s.jsx(ws,{className:"lab-copilot-menu-select",children:s.jsx(Ss,{placeholder:"Select quest"})}),s.jsx(Cs,{children:w.map(y=>s.jsx(Ms,{value:y.quest_id,children:s.jsx("span",{className:"block max-w-[var(--radix-select-trigger-width)] line-clamp-2",children:Dt(y)})},y.quest_id))})]}):s.jsx("div",{className:"lab-copilot-menu-muted",children:"No quests available."})]})]}),J,X?s.jsx(ds,{open:I,onOpenChange:A,children:s.jsxs(ms,{className:"lab-copilot-add-dialog",showCloseButton:!0,children:[s.jsxs(fs,{children:[s.jsx(hs,{className:"lab-copilot-add-title",children:"Add agents"}),s.jsx("div",{className:"lab-copilot-add-subtitle",children:x?"Select agents to join this quest.":"Select a quest first to add agents."})]}),T.length?s.jsx("div",{className:"lab-copilot-add-list",children:T.map(y=>{const h=R.has(y.id);return s.jsxs("button",{type:"button",className:Me("lab-copilot-add-row",h&&"is-selected"),onClick:()=>P(y.id),children:[s.jsx("span",{className:"lab-copilot-add-check",children:h?s.jsx($t,{size:12}):null}),s.jsx("div",{className:"lab-avatar lab-avatar-sm",children:s.jsx("img",{src:y.avatar,alt:y.name})}),s.jsx("span",{className:"lab-copilot-add-name",title:y.name,children:y.name})]},y.id)})}):s.jsx("div",{className:"lab-copilot-add-empty",children:x?"No available agents to add right now.":"Select a quest to see available agents."}),s.jsxs(ps,{className:"lab-copilot-add-footer",children:[s.jsx(_t,{variant:"outline",size:"sm",className:"min-h-[40px] px-4 text-xs",onClick:()=>A(!1),children:"Cancel"}),s.jsx(_t,{size:"sm",className:"min-h-[40px] px-4 text-xs",onClick:ie,disabled:G||R.size===0||Q,children:Q?"Adding...":"Add to quest"})]})]})}):null]})}function tn({projectId:i,quest:u,quests:t,agents:n,templatesById:e,readOnly:a,onQuestChange:f}){const{t:d}=Pt("lab"),{addToast:x}=Ct(),w=St(),[_,S]=r.useState(""),[E,D]=r.useState([]),[q,k]=r.useState(!1),[K,C]=r.useState(null),[T,I]=r.useState(null),A=r.useRef(null),R=r.useRef(null),[N,Q]=r.useState(!0),W=H(l=>l.groupPrefill),$=H(l=>l.setGroupPrefill),U=He(l=>l.selection),P=He(l=>l.activeProposal),ie=He(l=>l.setSelection),te=He(l=>l.setActiveProposal),V=H(l=>l.setMode),J=H(l=>l.setActiveAgent),X=We(l=>l.setSessionIdForSurface),G=Bt(l=>l.user),se=Ht(),[y,h]=r.useState(""),m=u?.quest_id??null,{sessionId:F,messages:z,connection:ne,sendMessage:de,historyTruncated:ge,historyLimit:je,historyLoadingFull:O,historyLoading:Ee,hasLoadedOnce:me,loadFullHistory:le}=Yt({projectId:i,questId:m,surface:"group",enabled:!!m}),ee=r.useMemo(()=>new Map(n.map(l=>[l.instance_id,l])),[n]),ce=r.useMemo(()=>m?n.filter(l=>l.active_quest_id===m):[],[n,m]),ue=r.useMemo(()=>ce.map(l=>l.instance_id),[ce]),be=r.useMemo(()=>{const l=new Map;return ce.forEach(g=>{const v=at(g),o=new Set;v&&(o.add(v),o.add(v.replace(/^@/,""))),g.agent_id&&o.add(g.agent_id),g.display_name&&o.add(g.display_name),o.forEach(b=>{const j=b.trim().toLowerCase();j&&(l.has(j)||l.set(j,g.instance_id))})}),l},[ce]),p=r.useMemo(()=>{if(!m)return[];const l={id:"all",label:"@ALL",description:"Notify all agents in this quest",role:"broadcast",source:"lab"},g=ce.map(v=>{const o=v.template_id?e.get(v.template_id)??null:null;return yt(v,o)});return[l,...g]},[ce,m,e]),oe=r.useMemo(()=>ce.map(l=>{const g=l.template_id?e.get(l.template_id)??null:null;return{id:l.instance_id,name:Ce(l),avatar:Ve(l,g)}}),[ce,e]),Xe=r.useMemo(()=>m?n.filter(l=>l.active_quest_id!==m).map(l=>{const g=l.template_id?e.get(l.template_id)??null:null;return{id:l.instance_id,name:Ce(l),avatar:Ve(l,g)}}):[],[n,m,e]),fe=r.useMemo(()=>t.length===0?"Create a quest to get started.":"Select a quest to start collaborating.",[t.length]),Ze=m?"No agents assigned to this quest yet.":"Select a quest to see its agents.",Qe=r.useMemo(()=>ne.status==="rate_limited"?"Rate limited. Retrying...":ne.status==="reconnecting"?"Reconnecting...":ne.status==="error"?ne.error||"Connection error":null,[ne.error,ne.status]),Ae=ge&&!!F,Re=!!m&&Ee&&z.length===0&&!me,ze=typeof je=="number"&&je>0?`Showing latest ${je} messages.`:"Showing recent messages.";r.useMemo(()=>((G?.username||G?.email||G?.id||"You")?.trim?.()??"")||"You",[G?.email,G?.id,G?.username]),r.useEffect(()=>{h(""),C(null),A.current=null,Q(!0),S("")},[m]),r.useEffect(()=>{if(!T)return;const l=()=>I(null),g=v=>{v.key==="Escape"&&I(null)};return window.addEventListener("click",l),window.addEventListener("contextmenu",l),window.addEventListener("keydown",g),window.addEventListener("scroll",l,!0),()=>{window.removeEventListener("click",l),window.removeEventListener("contextmenu",l),window.removeEventListener("keydown",g),window.removeEventListener("scroll",l,!0)}},[T]),r.useEffect(()=>{W&&(_.trim()||S(W.trim()?`${W} `:""),$(null))},[W,_,$]);const _e=r.useCallback(l=>{const g=l.trim();if(!g)return"";const v=g.split(/\s+/);let o=0;for(;o<v.length;){const b=v[o];if(!b||!b.startsWith("@")||b.length===1)break;o+=1}return v.slice(o).join(" ").trim()},[]),Ue=r.useCallback(l=>{const g=l.trim(),v=/@([A-Za-z0-9_.-]+)/g,o=new Set,b=new Set;let j=!1,Z;for(;(Z=v.exec(g))!==null;){const ye=Z[1]?.trim();if(!ye)continue;const re=ye.toLowerCase();if(re==="all"){j=!0;continue}const Pe=re.startsWith("@")?re:`@${re}`,pe=be.get(Pe)??be.get(re);pe?o.add(pe):b.add(`@${ye}`)}return j&&(ue.forEach(ye=>o.add(ye)),b.clear()),{content:_e(g)||(o.size>0||j?"":g),targets:Array.from(o),missing:Array.from(b)}},[be,ue,_e]),De=r.useCallback(l=>{const g=ee.get(l);return g?at(g):""},[ee]),$e=async()=>{if(!(!m||!_.trim()||a||!F))try{const l=Ue(_);if(l.missing.length>0){x({type:"error",title:"Unknown agent",description:`Unknown mention: ${l.missing.join(", ")}`});return}if(l.targets.length===0){x({type:"error",title:"Mention required",description:"Mention a quest agent to start a group request."});return}Q(!0),await de({sessionId:F,message:l.content,surface:"lab-group",mentionTargets:l.targets,metadata:{selection_context:Xt(U),proposal_id:P?.proposal_id??void 0,message_kind:P||U?"user_control":l.targets.length>0?"group_request":"text",target_label:l.targets.length===1&&De(l.targets[0])||void 0}}),S(""),D([])}catch{x({type:"error",title:"Message failed",description:"Message couldn't be sent. Please check your connection and try again."})}};r.useEffect(()=>{const l=z[z.length-1];if(l?.id){if(!A.current){A.current=l.id;return}if(l.id!==A.current){A.current=l.id,C(l.id);const g=window.setTimeout(()=>C(null),1200);return()=>window.clearTimeout(g)}}},[z]);const Ie=r.useCallback(l=>{const g=Se(l),v=Array.isArray(g?.mention_targets)?g?.mention_targets:[];if(!v.length)return"";const o=v.map(b=>De(b)).filter(b=>!!b);return o.length?Array.from(new Set(o)).join(" "):""},[De]),ae=r.useCallback(l=>{const g=mt(l);if(ut(l)!=="user")return g;const v=Ie(l);return v?g?`${v} ${g}`:v:g},[Ie]),ke=r.useCallback(l=>{if(ut(l)!=="user")return l;const g=mt(l),v=ae(l);if(!v||v===g)return l;const o=l.content;return!o||typeof o!="object"||typeof o.content!="string"?l:{...l,content:{...o,content:v}}},[ae]),Ke=r.useMemo(()=>{const l=new Map;return z.forEach(g=>{const v=ae(g);v&&l.set(g.id,v)}),l},[z,ae]),Je=r.useMemo(()=>new Map(z.map(l=>[l.id,l])),[z]),he=r.useMemo(()=>{const l=new Map;return z.forEach(g=>{const v=Se(g),o=typeof v?.group_message_id=="string"?v.group_message_id:"";if(!o)return;const b=ae(g);b&&l.set(o,b)}),l},[z,ae]),et=r.useMemo(()=>{const l=new Map;return z.forEach(g=>{const v=Se(g),o=typeof v?.group_message_id=="string"?v.group_message_id:"";o&&l.set(o,g)}),l},[z]),ot=r.useCallback(l=>{const g=Se(l);if(!g)return null;const v=g,o=v.context&&typeof v.context=="object"?v.context:null,b=typeof v.reply_to_message_id=="string"&&v.reply_to_message_id||typeof v.quote_message_id=="string"&&v.quote_message_id||typeof o?.reply_to_message_id=="string"&&o.reply_to_message_id||typeof o?.quote_message_id=="string"&&o.quote_message_id||"",j=v.quote_snapshot&&typeof v.quote_snapshot=="object"?v.quote_snapshot:o?.quote_snapshot&&typeof o.quote_snapshot=="object"?o.quote_snapshot:null;if(!b&&!j)return null;const Z=j&&typeof j.group_message_id=="string"?j.group_message_id:"",Oe=b||Z,Fe=Oe?et.get(Oe)??null:null,ye=j&&typeof j.content=="string"?j.content:"",re=Oe?he.get(Oe)??"":"",Pe=(ye||re).replace(/\s+/g," ").trim();if(!Pe)return null;let pe="";return Fe?pe=ft(Fe):j&&(pe=typeof j.sender_name=="string"&&j.sender_name||typeof j.agent_display_name=="string"&&j.agent_display_name||typeof j.sender_label=="string"&&j.sender_label||typeof j.agent_label=="string"&&j.agent_label||""),pe||(pe="User"),{sender:pe,content:Pe}},[he,et]),Ne=r.useCallback((l,g)=>{const v=Se(g),o=v?.agent_instance_id??v?.sender_instance_id,b=v?.session_id;!o&&!b||I({messageId:g.id,x:l.clientX,y:l.clientY})},[]),Te=T?Je.get(T.messageId)??null:null,Le=Te?Se(Te):null,qe=Le?.agent_instance_id??null,Be=typeof Le?.session_id=="string"?Le.session_id:null,xe=!!qe,tt=r.useCallback(()=>{qe&&(J(qe),Be&&X(i,"lab-direct",Be),V("direct"),I(null))},[qe,Be,i,J,V,X]),Ge=r.useCallback(()=>{const l=R.current;l&&(typeof l.scrollTo=="function"?l.scrollTo({top:l.scrollHeight,behavior:"auto"}):l.scrollTop=l.scrollHeight)},[]),c=r.useCallback(l=>{const g=l.currentTarget,v=Ot(g);Q(o=>o===v?o:v)},[Ot]);r.useCallback(()=>{Q(!1),le()},[le]),r.useEffect(()=>{!m||z.length===0||N&&window.requestAnimationFrame(()=>Ge())},[N,z,m,Ge]);const M=Ae?1:0,L=z.length+M,B=L>20,Y=Kt({count:L,getScrollElement:()=>R.current,estimateSize:l=>Ae&&l===0?56:160,getItemKey:l=>Ae&&l===0?"lab-group-history-banner":z[l-M]?.id??`lab-group-${l}`,overscan:6}),ve=r.useMemo(()=>{const l=y.trim().toLowerCase();if(!l)return[];const g=[];return z.forEach((v,o)=>{const b=Ke.get(v.id)??"";if(!b||!b.toLowerCase().includes(l))return;const j=ft(v);g.push({id:v.id,index:o,title:j,excerpt:ts(b,l)})}),g},[Ke,z,y]),we=r.useCallback(async l=>{if(!(!m||a||l.length===0)){k(!0);try{const g=await Promise.allSettled(l.map(o=>dt(i,o,{quest_id:m,quest_node_id:null}))),v=[];if(g.forEach((o,b)=>{o.status!=="fulfilled"&&v.push(l[b])}),v.length){const o=v.map(b=>{const j=ee.get(b);return j?Ce(j):b});x({type:"error",title:"Unable to add agents",description:`Failed to add: ${o.join(", ")}`})}w.invalidateQueries({queryKey:["lab-agents",i]})}finally{k(!1)}}},[x,ee,i,w,m,a]),st=r.useCallback(async l=>{if(!(!m||a)){k(!0);try{await dt(i,l,{quest_id:null,quest_node_id:null}),w.invalidateQueries({queryKey:["lab-agents",i]})}catch{const v=ee.get(l),o=v?Ce(v):l;x({type:"error",title:"Unable to remove agent",description:`Failed to remove ${o} from this quest.`})}finally{k(!1)}}},[x,ee,i,w,m,a]),nt=r.useCallback(l=>{C(l),typeof window<"u"&&window.setTimeout(()=>C(null),1200)},[]),rt=r.useCallback(l=>{if(l&&R.current){if(Q(!1),B)Y.scrollToIndex(l.index,{align:"center"});else{const g=R.current?.querySelector(`[data-group-message-id="${l.id}"]`);g&&g.scrollIntoView({behavior:"smooth",block:"center"})}nt(l.id)}},[nt,M,Y,B]);r.useEffect(()=>{y.trim()&&ve.length!==0&&rt(ve[0])},[ve,rt,y]);const ht=se?Ye.createPortal(s.jsx(ss,{label:"Group",entities:oe,emptyEntitiesLabel:Ze,searchValue:y,onSearchChange:h,searchResults:ve,onSearchSelect:rt,searchPlaceholder:"Search group chat",questId:m,quests:t,onQuestChange:f,canManageRoster:!a&&!!m,rosterBusy:q,availableAgents:Xe,onAddAgents:we,onRemoveAgent:st}),se):null,pt=T&&typeof document<"u"?Ye.createPortal(s.jsx("div",{className:"lab-copilot-context-menu",style:{left:T.x,top:T.y},children:s.jsx("button",{type:"button",onClick:tt,disabled:!xe,children:"Open direct session"})}),document.body):null,lt=l=>{const g=ke(l),v=g.content,o=l.type==="text_delta"&&v.status==="in_progress",b=K===l.id,j=ut(g),Z=Se(g),Oe=j==="assistant"?es(v?.timestamp):"",Fe=ot(g),ye=typeof Z?.sender_label=="string"?Z.sender_label:typeof Z?.agent_label=="string"?Z.agent_label:null,re=typeof Z?.target_label=="string"?Z.target_label:null,Pe=typeof Z?.reply_state=="string"?Z.reply_state:null,pe=Ks(d,Pe),gt=typeof Z?.proposal_id=="string"?Z.proposal_id:null,bt=Zt(Z?.selection_context&&typeof Z.selection_context=="object"?{...Z.selection_context,label:typeof Z.selection_context.branch_name=="string"?Z.selection_context.branch_name:void 0}:null);return s.jsxs("div",{className:Me("rounded-[12px] px-1",b&&"lab-message-highlight"),"data-group-message-id":l.id,children:[ye||re||pe||gt||bt?s.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2 px-2",children:[ye||re?s.jsxs("span",{className:"inline-flex items-center rounded-full border border-[var(--lab-border)] bg-[var(--lab-surface)] px-2 py-0.5 text-[10px] font-medium text-[var(--lab-text-secondary)]",children:[ye||d("copilot_group_sender_fallback",void 0,"Agent"),re?` → ${re}`:""]}):null,pe?s.jsx("span",{className:"inline-flex items-center rounded-full border border-[rgba(83,176,174,0.2)] bg-[rgba(83,176,174,0.1)] px-2 py-0.5 text-[10px] font-medium text-[var(--lab-text-secondary)]",children:pe}):null,gt?s.jsxs("span",{className:"inline-flex items-center rounded-full border border-[var(--lab-border)] bg-[var(--lab-background)] px-2 py-0.5 text-[10px] text-[var(--lab-text-secondary)]",children:[d("copilot_group_proposal_badge",void 0,"Proposal")," · ",gt.slice(0,8)]}):null,bt?s.jsx("span",{className:"inline-flex items-center rounded-full border border-[var(--lab-border)] bg-[var(--lab-background)] px-2 py-0.5 text-[10px] text-[var(--lab-text-secondary)]",children:bt}):null]}):null,s.jsx(Qt,{message:g,compact:!0,onAvatarContextMenu:Ne,displayStreaming:o,streamActive:ne.status==="open"||ne.status==="connecting"||ne.status==="reconnecting"}),Fe?s.jsx("div",{className:Me("mt-2 flex w-full",j==="user"?"justify-end":"justify-start"),children:s.jsx("div",{className:"max-w-[85%] rounded-[8px] bg-[rgba(0,0,0,0.06)] px-3 py-2 text-[10px] leading-relaxed text-[var(--text-secondary)]",children:s.jsxs("div",{className:"line-clamp-2",children:[s.jsxs("span",{className:"font-medium text-[var(--text-tertiary)]",children:[Fe.sender,":"]})," ",Fe.content]})})}):null,Oe?s.jsx("div",{className:"lab-message-timestamp",children:Oe}):null]},l.id)},ct=()=>s.jsx("div",{className:"mb-3 flex justify-center",children:s.jsxs("div",{className:Me("inline-flex max-w-full items-center gap-2 rounded-full border px-3 py-1 font-medium","border-[var(--lab-border)] bg-[var(--lab-surface)] text-[var(--lab-text-secondary)]","text-[11px]"),children:[s.jsx("span",{children:ze}),s.jsx("button",{type:"button",onClick:()=>{Q(!1),le()},disabled:O,className:"text-[var(--lab-text-primary)] underline decoration-dotted underline-offset-4 disabled:cursor-not-allowed disabled:opacity-50",children:O?"Loading full history...":"Load full history"})]})});return s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[ht,pt,s.jsxs("div",{className:"ai-manus-root ai-manus-copilot ai-manus-embedded flex flex-1 min-h-0 flex-col",children:[s.jsxs("div",{className:"relative flex flex-1 min-h-0 flex-col",children:[s.jsx(Wt,{ref:R,className:"flex-1 min-h-0",onScroll:c,children:s.jsx("div",{className:"flex min-h-full flex-col px-4 py-4",children:m?s.jsxs(s.Fragment,{children:[Qe?s.jsx("div",{className:"mb-3 text-center text-[11px] text-[var(--text-tertiary)]",children:Qe}):null,B?s.jsx("div",{style:{height:Y.getTotalSize(),position:"relative"},children:Y.getVirtualItems().map(l=>{if(Ae&&l.index===0)return s.jsx("div",{"data-index":l.index,ref:Y.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${l.start}px)`},children:ct()},l.key);const g=z[l.index-M];return g?s.jsx("div",{"data-index":l.index,ref:Y.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${l.start}px)`},children:s.jsx("div",{className:"pb-3",children:lt(g)})},l.key):null})}):s.jsxs("div",{className:"flex flex-col",children:[Ae?ct():null,z.map(l=>lt(l))]})]}):s.jsx("div",{className:"flex flex-1 items-center justify-center text-[12px] text-[var(--text-tertiary)]",children:fe})})}),Re?s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center pointer-events-none",children:s.jsxs("div",{className:Me("flex items-center gap-2 rounded-full border px-3 py-1.5 text-[11px] font-medium shadow-sm","border-[var(--lab-border)] bg-[var(--lab-surface)] text-[var(--lab-text-secondary)]"),children:[s.jsx(Vt,{className:"h-4 w-4 animate-spin"}),s.jsx("span",{children:d("common_loading",void 0,"Loading...")})]})}):null]}),s.jsxs("div",{className:"border-t border-[var(--border-main)] px-4 py-3",children:[s.jsx(Jt,{selection:U,proposal:P?{proposal_id:P.proposal_id,action_type:P.action_type,status:P.status}:null,onClearSelection:()=>ie(null),onClearProposal:()=>te(null),selectionPrefix:d("copilot_selection_chip",void 0,"Ref"),proposalPrefix:d("copilot_proposal_chip",void 0,"Proposal")}),s.jsx(ks,{value:_,onChange:S,onSubmit:$e,isRunning:!1,mentionables:p,mentionEnabled:!a,includeDefaultAgent:!1,lockLeadingMentionSpace:!0,attachments:E,onAttachmentsChange:D,attachmentsEnabled:!1,readOnly:a,inputDisabled:!m,rows:2,placeholder:m?a?d("copilot_group_placeholder_offline",void 0,"Your execution server is offline. Messages will be sent once it reconnects."):d("copilot_group_placeholder",void 0,"Message @ALL or a quest agent"):fe,compact:!0,containerClassName:"pb-0"})]})]})]})}function sn({message:i,readOnly:u,liked:t,busy:n,likeUsers:e,comments:a,onToggleLike:f,onCommentSubmit:d,onAvatarContextMenu:x}){const w=Se(i),_=w,S=typeof w?.moment_id=="string"?w.moment_id:"",E=mt(i),D=Gs(w?.moment_media),q=w?.sender_name||ft(i),k=w?.sender_label||w?.agent_label,K=w?.sender_avatar_url||w?.agent_logo||"",C=w?.sender_avatar_color||w?.agent_avatar_color||"",T=es(en(i)),I=E?Ls(E):"",[A,R]=r.useState(!1),[N,Q]=r.useState("");r.useEffect(()=>{R(!1),Q("")},[S]);const W=h=>{if(typeof h=="number"&&Number.isFinite(h))return h;if(typeof h=="string"){const m=Number(h);if(Number.isFinite(m))return m}return 0},$=W(w?.moment_like_count),U=W(w?.moment_comment_count),P=q?.trim().slice(0,1).toUpperCase()||"?",ie=(()=>{const m=(k||q||"Agent").trim();return m?m.startsWith("@")?m:`@${m}`:"@Agent"})(),te=Zs(Ys(_?.moment_like_users??_?.moment_likes??_?.like_users??_?.likes??_?.moment_reactions??null),e.map(h=>({name:h}))),V=Js(Xs(_?.moment_comments??_?.moment_comment_list??_?.comments??_?.moment_comment_items??_?.comment_items??null),a),J=te.length>0||V.length>0,X=async()=>{!S||u||n||await f(S,!t)},G=()=>{u||R(h=>!h)},se=async()=>{if(!S||u||n)return;const h=N.trim();if(!h)return;await d(S,h)&&(Q(""),R(!1))},y=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),se())};return s.jsxs("div",{className:"lab-moment-card",children:[s.jsxs("div",{className:"lab-avatar lab-avatar-sm lab-moment-avatar",onContextMenu:h=>x?.(h,i),children:[s.jsx("span",{className:"lab-avatar-ring",style:C?{borderColor:C}:void 0}),K?s.jsx("img",{src:K,alt:q}):s.jsx("span",{children:P})]}),s.jsxs("div",{className:"lab-moment-main",children:[s.jsx("div",{className:"lab-moment-name",children:ie}),I?s.jsx("div",{className:"lab-moment-content",dangerouslySetInnerHTML:{__html:I}}):null,D.length?s.jsx("div",{className:"lab-moment-media",children:D.map((h,m)=>s.jsx("div",{className:"lab-moment-media-item",children:s.jsx("img",{src:h.url,alt:h.label||`Moment media ${m+1}`})},`${h.url}-${m}`))}):null,s.jsxs("div",{className:"lab-moment-meta-row",children:[T?s.jsx("div",{className:"lab-moment-timestamp",children:T}):s.jsx("div",{}),s.jsxs("div",{className:"lab-moment-actions",children:[s.jsxs("button",{type:"button",className:Me("lab-moment-action",t&&"is-active"),onClick:X,disabled:u||n,"aria-label":"Like moment",children:[s.jsx(jt,{size:14}),s.jsx("span",{children:$})]}),s.jsxs("button",{type:"button",className:"lab-moment-action",onClick:G,disabled:u||n,"aria-label":"Comment on moment",children:[s.jsx(Rs,{size:14}),s.jsx("span",{children:U})]})]})]}),J?s.jsxs("div",{className:"lab-moment-reactions",children:[te.length?s.jsxs("div",{className:"lab-moment-like-row",children:[s.jsx(jt,{size:12}),s.jsx("span",{className:"lab-moment-like-names",children:te.join(", ")})]}):null,V.map((h,m)=>s.jsxs("div",{className:"lab-moment-comment-row",children:[s.jsx("span",{className:"lab-moment-comment-name",children:h.name}),s.jsx("span",{className:"lab-moment-comment-sep",children:":"}),s.jsx("span",{className:"lab-moment-comment-text",children:h.content})]},`${h.name}-${m}`))]}):null,A?s.jsxs("div",{className:"lab-moment-comment",children:[s.jsx("textarea",{value:N,onChange:h=>Q(h.target.value),onKeyDown:y,placeholder:"Write a comment",className:"lab-moment-comment-input",rows:2,disabled:u||n}),s.jsxs("div",{className:"lab-moment-comment-actions",children:[s.jsx("button",{type:"button",className:"lab-moment-action lab-moment-action-secondary",onClick:()=>R(!1),disabled:u||n,children:"Cancel"}),s.jsx("button",{type:"button",className:"lab-moment-action lab-moment-action-primary",onClick:se,disabled:u||n||!N.trim(),children:"Send"})]})]}):null]})]})}function nn({projectId:i,agents:u,templatesById:t,readOnly:n,quest:e,quests:a,onQuestChange:f}){const{addToast:d}=Ct(),x=St(),[w,_]=r.useState(!1),[S,E]=r.useState(new Set),[D,q]=r.useState({}),[k,K]=r.useState({}),[C,T]=r.useState({}),[I,A]=r.useState(null),R=r.useRef(null),N=r.useRef(null),[Q,W]=r.useState(null),[$,U]=r.useState(!0),P=H(c=>c.setMode),ie=H(c=>c.setActiveAgent),te=We(c=>c.setSessionIdForSurface),V=Bt(c=>c.user),J=r.useMemo(()=>((V?.username||V?.email||V?.id||"You")?.trim?.()??"")||"You",[V?.email,V?.id,V?.username]),X=Ht(),[G,se]=r.useState(""),y=r.useMemo(()=>new Map(u.map(c=>[c.instance_id,c])),[u]),h=e?.quest_id??null,{messages:m,connection:F,historyTruncated:z,historyLimit:ne,historyLoadingFull:de,historyLoading:ge,hasLoadedOnce:je,loadFullHistory:O}=Yt({projectId:i,questId:h,surface:"friends",enabled:!!h}),Ee=r.useMemo(()=>h?u.filter(c=>c.active_quest_id===h).map(c=>{const M=c.template_id?t.get(c.template_id)??null:null;return{id:c.instance_id,name:Ce(c),avatar:Ve(c,M)}}):[],[u,h,t]),me=r.useMemo(()=>h?u.filter(c=>c.active_quest_id!==h).map(c=>{const M=c.template_id?t.get(c.template_id)??null:null;return{id:c.instance_id,name:Ce(c),avatar:Ve(c,M)}}):[],[u,h,t]),le=h?"No agents assigned to this quest yet.":"Select a quest to see its agents.",ee=r.useMemo(()=>h?"No friend updates yet for this quest.":"Select a quest to view friend updates.",[h]),ce=r.useMemo(()=>F.status==="rate_limited"?"Rate limited. Retrying...":F.status==="reconnecting"?"Reconnecting...":F.status==="error"?F.error||"Connection error":null,[F.error,F.status]),ue=z&&!!h,be=!!h&&ge&&m.length===0&&!je,p=typeof ne=="number"&&ne>0?`Showing latest ${ne} messages.`:"Showing recent messages.";r.useEffect(()=>{if(!I)return;const c=()=>A(null),M=L=>{L.key==="Escape"&&A(null)};return window.addEventListener("click",c),window.addEventListener("contextmenu",c),window.addEventListener("keydown",M),window.addEventListener("scroll",c,!0),()=>{window.removeEventListener("click",c),window.removeEventListener("contextmenu",c),window.removeEventListener("keydown",M),window.removeEventListener("scroll",c,!0)}},[I]),r.useEffect(()=>{se(""),W(null),N.current=null,U(!0),E(new Set),q({}),K({}),T({})},[h]),r.useEffect(()=>{const c=m[m.length-1];if(c?.id){if(!N.current){N.current=c.id;return}if(c.id!==N.current){N.current=c.id,W(c.id);const M=window.setTimeout(()=>W(null),1200);return()=>window.clearTimeout(M)}}},[m]);const oe=r.useMemo(()=>{const c=new Map;return m.forEach(M=>{const L=mt(M);L&&c.set(M.id,L)}),c},[m]),Xe=r.useMemo(()=>new Map(m.map(c=>[c.id,c])),[m]),fe=r.useMemo(()=>m.length?[...m].reverse():[],[m]),Ze=r.useCallback((c,M)=>{const L=Se(M),B=L?.agent_instance_id,Y=L?.session_id;!B&&!Y||A({messageId:M.id,x:c.clientX,y:c.clientY})},[]),Qe=I?Xe.get(I.messageId)??null:null,Ae=Qe?Se(Qe):null,Re=Ae?.agent_instance_id??null,ze=typeof Ae?.session_id=="string"?Ae.session_id:null,_e=!!Re,Ue=r.useCallback(()=>{Re&&(ie(Re),ze&&te(i,"lab-direct",ze),P("direct"),A(null))},[Re,ze,i,ie,P,te]),De=fe.length+(ue?1:0),$e=ue?fe.length:-1,Ie=De>20,ae=Kt({count:De,getScrollElement:()=>R.current,estimateSize:c=>ue&&c===$e?56:180,getItemKey:c=>ue&&c===$e?"lab-friends-history-banner":fe[c]?.id??`lab-friends-${c}`,overscan:6}),ke=r.useMemo(()=>{const c=G.trim().toLowerCase();if(!c)return[];const M=[];return fe.forEach((L,B)=>{const Y=oe.get(L.id)??"";if(!Y||!Y.toLowerCase().includes(c))return;const ve=ft(L);M.push({id:L.id,index:B,title:ve,excerpt:ts(Y,c)})}),M},[fe,oe,G]),Ke=r.useCallback(async c=>{if(!(!h||n||c.length===0)){_(!0);try{const M=await Promise.allSettled(c.map(B=>dt(i,B,{quest_id:h,quest_node_id:null}))),L=[];if(M.forEach((B,Y)=>{B.status!=="fulfilled"&&L.push(c[Y])}),L.length){const B=L.map(Y=>{const ve=y.get(Y);return ve?Ce(ve):Y});d({type:"error",title:"Unable to add agents",description:`Failed to add: ${B.join(", ")}`})}x.invalidateQueries({queryKey:["lab-agents",i]})}finally{_(!1)}}},[d,y,i,x,h,n]),Je=r.useCallback(async c=>{if(!(!h||n)){_(!0);try{await dt(i,c,{quest_id:null,quest_node_id:null}),x.invalidateQueries({queryKey:["lab-agents",i]})}catch{const L=y.get(c),B=L?Ce(L):c;d({type:"error",title:"Unable to remove agent",description:`Failed to remove ${B} from this quest.`})}finally{_(!1)}}},[d,y,i,x,h,n]),he=r.useCallback((c,M)=>{E(L=>{const B=new Set(L);return M?B.add(c):B.delete(c),B})},[]),et=r.useCallback(async(c,M)=>{if(!(!c||n)){he(c,!0);try{M?await os(i,c):await rs(i,c),q(L=>({...L,[c]:M})),K(L=>{const B=L[c]??[],Y=new Set(B);return M?Y.add(J):Y.delete(J),{...L,[c]:Array.from(Y)}})}catch{d({type:"error",title:"Unable to update like",description:"Please try again once your connection stabilizes."})}finally{he(c,!1)}}},[d,J,i,n,he]),ot=r.useCallback(async(c,M)=>{if(!c||n)return!1;he(c,!0);try{return await as(i,c,{content:M}),T(L=>{const B=L[c]??[],Y={name:J,content:M};return{...L,[c]:[...B,Y]}}),!0}catch{return d({type:"error",title:"Unable to send comment",description:"Please try again once your connection stabilizes."}),!1}finally{he(c,!1)}},[d,J,i,n,he]),Ne=r.useCallback(c=>{W(c),typeof window<"u"&&window.setTimeout(()=>W(null),1200)},[]),Te=r.useCallback(c=>{if(c&&R.current){if(Ie)ae.scrollToIndex(c.index,{align:"center"});else{const M=R.current?.querySelector(`[data-friend-post-id="${c.id}"]`);M&&M.scrollIntoView({behavior:"smooth",block:"center"})}Ne(c.id)}},[Ne,ae,Ie]);r.useEffect(()=>{G.trim()&&ke.length!==0&&Te(ke[0])},[ke,Te,G]);const Le=X?Ye.createPortal(s.jsx(ss,{label:"Friends",entities:Ee,emptyEntitiesLabel:le,searchValue:G,onSearchChange:se,searchResults:ke,onSearchSelect:Te,searchPlaceholder:"Search friend updates",questId:h,quests:a,onQuestChange:f,canManageRoster:!n&&!!h,rosterBusy:w,availableAgents:me,onAddAgents:Ke,onRemoveAgent:Je}),X):null,qe=I&&typeof document<"u"?Ye.createPortal(s.jsx("div",{className:"lab-copilot-context-menu",style:{left:I.x,top:I.y},children:s.jsx("button",{type:"button",onClick:Ue,disabled:!_e,children:"Open direct session"})}),document.body):null,Be=r.useCallback(c=>{const M=c.currentTarget,L=It(M);U(B=>B===L?B:L)},[It]),xe=c=>{const M=c.content,L=Se(c),B=c.type==="text_delta"&&M.status==="in_progress",Y=Q===c.id,ve=L?.message_kind==="moment",we=typeof L?.moment_id=="string"?L.moment_id:"",st=we?k[we]??[]:[],nt=we?C[we]??[]:[];return s.jsx("div",{className:Me("rounded-[12px] px-1",Y&&"lab-message-highlight"),"data-friend-post-id":c.id,children:ve?s.jsx(sn,{message:c,readOnly:n,liked:we?!!D[we]:!1,busy:we?S.has(we):!1,likeUsers:st,comments:nt,onToggleLike:et,onCommentSubmit:ot,onAvatarContextMenu:Ze}):s.jsx(Qt,{message:c,compact:!0,onAvatarContextMenu:Ze,displayStreaming:B,streamActive:F.status==="open"||F.status==="connecting"||F.status==="reconnecting"})},c.id)},tt=()=>s.jsx("div",{className:"mb-4 flex justify-center",children:s.jsxs("div",{className:Me("inline-flex max-w-full items-center gap-2 rounded-full border px-3 py-1 font-medium","border-[var(--lab-border)] bg-[var(--lab-surface)] text-[var(--lab-text-secondary)]","text-[11px]"),children:[s.jsx("span",{children:p}),s.jsx("button",{type:"button",onClick:()=>{U(!1),O()},disabled:de,className:"text-[var(--lab-text-primary)] underline decoration-dotted underline-offset-4 disabled:cursor-not-allowed disabled:opacity-50",children:de?"Loading full history...":"Load full history"})]})}),Ge=r.useCallback(()=>{const c=R.current;c&&(typeof c.scrollTo=="function"?c.scrollTo({top:0,behavior:"auto"}):c.scrollTop=0)},[]);return r.useEffect(()=>{!h||m.length===0||$&&window.requestAnimationFrame(()=>Ge())},[$,m,h,Ge]),s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[Le,qe,s.jsx("div",{className:"ai-manus-root ai-manus-copilot ai-manus-embedded flex flex-1 min-h-0 flex-col",children:s.jsxs("div",{className:"relative flex flex-1 min-h-0 flex-col",children:[s.jsx(Wt,{ref:R,className:"flex-1 min-h-0",onScroll:Be,children:s.jsxs("div",{className:"px-5 py-6",children:[ce?s.jsx("div",{className:"mb-3 text-center text-[11px] text-[var(--text-tertiary)]",children:ce}):null,h?m.length===0?s.jsx("div",{className:"flex min-h-[200px] items-center justify-center text-[12px] text-[var(--text-tertiary)]",children:ee}):Ie?s.jsx("div",{style:{height:ae.getTotalSize(),position:"relative"},children:ae.getVirtualItems().map(c=>{if(ue&&c.index===$e)return s.jsx("div",{"data-index":c.index,ref:ae.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${c.start}px)`},children:tt()},c.key);const M=fe[c.index];return M?s.jsx("div",{"data-index":c.index,ref:ae.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${c.start}px)`},children:s.jsx("div",{className:"pb-5",children:xe(M)})},c.key):null})}):s.jsxs("div",{className:"flex flex-col lab-friends-list",children:[fe.map(c=>xe(c)),ue?tt():null]}):s.jsx("div",{className:"flex min-h-[200px] items-center justify-center text-[12px] text-[var(--text-tertiary)]",children:ee})]})}),be?s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center pointer-events-none",children:s.jsxs("div",{className:Me("flex items-center gap-2 rounded-full border px-3 py-1.5 text-[11px] font-medium shadow-sm","border-[var(--lab-border)] bg-[var(--lab-surface)] text-[var(--lab-text-secondary)]"),children:[s.jsx(Vt,{className:"h-4 w-4 animate-spin"}),s.jsx("span",{children:"Loading..."})]})}):null]})})]})}export{_n as LabCopilotHeader,wn as default};
@@ -0,0 +1,22 @@
1
+ import{y as kt,H as le,j as e,be as ue,bf as ie,K as xt,bg as Jt,u as ke,at as He,aX as rt,a_ as Ye,aU as pt,bh as gt,bi as Zt,bj as It,bk as ea,bl as ta,b as ne,bm as We,bn as Xe,bo as Mt,bp as Bt,bq as Rt,br as Dt,aw as Ve,l as aa,aQ as ut,ao as Ue,aR as yt,bs as sa,J as Fe,R as Oe,bt as wt,bu as na,b1 as ia,O as at,bv as _t,bw as Nt,bx as ra,by as la,bz as oa,bA as ca,bB as ua,bC as da,bD as ma,bE as st,bF as va,s as ba,bG as ha,ap as fa,aq as xa,bH as pa,bI as ga,bJ as ya}from"./index-CBNVuWcP.js";import{r as i}from"./plugin-monaco-C8UgLomw.js";import{B as nt}from"./bot-DREQOxzP.js";import"./plugin-notebook-HbW2K-1c.js";import"./plugin-terminal-MXFIPun8.js";/**
2
+ * @license lucide-react v0.511.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const wa=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],_a=kt("inbox",wa);/**
7
+ * @license lucide-react v0.511.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const Na=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],ja=kt("layout-dashboard",Na),Ee=t=>{const a=String(t||"").trim().replace(/[_-]+/g," ");return a?a.replace(/\b\w/g,s=>s.toUpperCase()):"N/A"},Sa=t=>{try{return JSON.stringify(t,null,2)}catch{return String(t)}},qa=t=>!t||typeof t!="object"||Array.isArray(t)?null:t,Ea=t=>typeof t=="string"?t.trim()||null:typeof t=="number"||typeof t=="boolean"?String(t):null;function Ce({label:t,value:a}){return e.jsxs("div",{className:"rounded-[14px] border border-[var(--lab-border)] bg-[var(--lab-background)] px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-[0.12em] text-[var(--lab-text-secondary)]",children:t}),e.jsx("div",{className:"mt-1 text-sm text-[var(--lab-text-primary)]",children:a})]})}function Ca({projectId:t,questId:a,trace:s,isLoading:u,payloadJson:n,payloadTruncated:r}){const f=s?.payload_json||qa(n)?.payload||n||null,w=[...s?.actions||[]].reverse().find(c=>c.artifact_id||c.head_commit)||null,x=s?.head_commit||w?.head_commit||null,p=s?.artifact_kind||w?.artifact_kind||null,j=s?.artifact_id||w?.artifact_id||null,_=le({queryKey:["lab-trace-commit",a,x],queryFn:()=>xt.gitCommit(a,x),enabled:!!(a&&x),staleTime:15e3}),b=i.useMemo(()=>{const c=[...s?.changed_files||[]].filter(Boolean),g=_.data?.files?.map(G=>G.path).filter(Boolean)||[],K=Object.values(s?.paths_map||{}).map(G=>Ea(G)).filter(G=>!!(G&&!G.startsWith("/")));return[...new Set([...c,...g,...K])]},[_.data?.files,s?.changed_files,s?.paths_map]),[R,H]=i.useState(null);i.useEffect(()=>{if(!b.length){H(null);return}(!R||!b.includes(R))&&H(b[0]||null)},[b,R]);const y=le({queryKey:["lab-trace-commit-file",a,x,R],queryFn:()=>xt.gitCommitFile(a,x,R),enabled:!!(a&&x&&R),staleTime:15e3});return u&&!s?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"h-24 w-full rounded-[18px]"}),e.jsx(ue,{className:"h-20 w-full rounded-[18px]"}),e.jsx(ue,{className:"h-32 w-full rounded-[18px]"})]}):s?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-[18px] border border-[var(--lab-border)] bg-[var(--lab-surface)] px-4 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ie,{variant:"outline",children:Ee(s.selection_type)}),s.stage_title?e.jsx(ie,{variant:"outline",children:s.stage_title}):null,s.status?e.jsx(ie,{variant:"outline",children:Ee(s.status)}):null,p?e.jsx(ie,{variant:"outline",children:Ee(p)}):null]}),e.jsx("div",{className:"mt-3 text-sm font-semibold text-[var(--lab-text-primary)]",children:s.title}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-[var(--lab-text-secondary)]",children:s.summary||"No normalized summary is available for this node."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Ce,{label:"Branch",value:s.branch_name||"N/A"}),e.jsx(Ce,{label:"Stage",value:s.stage_title||"N/A"}),e.jsx(Ce,{label:"Artifact",value:j||"N/A"}),e.jsx(Ce,{label:"Commit",value:x||"N/A"}),e.jsx(Ce,{label:"Actions",value:s.counts?.actions??s.actions.length}),e.jsx(Ce,{label:"Updated",value:s.updated_at||"N/A"})]}),f?e.jsxs("div",{className:"rounded-[18px] border border-[var(--lab-border)] bg-[var(--lab-surface)] px-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.12em] text-[var(--lab-text-secondary)]",children:"Artifact Payload"}),r?e.jsx(ie,{variant:"outline",children:"Truncated"}):null]}),e.jsx("pre",{className:"mt-3 max-h-[280px] overflow-auto whitespace-pre-wrap rounded-[14px] bg-[var(--lab-background)] p-3 text-[11px] leading-5 text-[var(--lab-text-primary)]",children:Sa(f)})]}):null,x?e.jsxs("div",{className:"rounded-[18px] border border-[var(--lab-border)] bg-[var(--lab-surface)] px-4 py-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.12em] text-[var(--lab-text-secondary)]",children:"Commit"}),_.isLoading?e.jsx(ue,{className:"mt-3 h-20 w-full rounded-[14px]"}):_.data?e.jsxs("div",{className:"mt-3 space-y-2 text-xs text-[var(--lab-text-secondary)]",children:[e.jsx("div",{className:"text-sm font-semibold text-[var(--lab-text-primary)]",children:_.data.subject}),e.jsxs("div",{children:[_.data.short_sha," · ",_.data.author_name||"Unknown author"]}),e.jsx("div",{children:_.data.authored_at||"Unknown time"}),e.jsxs("div",{children:[_.data.file_count||0," files · +",_.data.stats?.added||0," / -",_.data.stats?.removed||0]})]}):e.jsx("div",{className:"mt-3 text-sm text-[var(--lab-text-secondary)]",children:"Commit metadata is unavailable."})]}):null,b.length?e.jsxs("div",{className:"rounded-[18px] border border-[var(--lab-border)] bg-[var(--lab-surface)] px-4 py-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.12em] text-[var(--lab-text-secondary)]",children:"Changed Files"}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:b.slice(0,12).map(c=>e.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-1 text-[11px] ${R===c?"border-[var(--lab-accent-strong)] bg-[rgba(64,113,175,0.1)] text-[var(--lab-text-primary)]":"border-[var(--lab-border)] bg-[var(--lab-background)] text-[var(--lab-text-secondary)]"}`,onClick:()=>H(c),children:c},c))}),R?e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-xs font-semibold text-[var(--lab-text-primary)]",children:R}),y.isLoading?e.jsx(ue,{className:"mt-2 h-36 w-full rounded-[14px]"}):y.data?.lines?.length?e.jsx("pre",{className:"mt-2 max-h-[320px] overflow-auto whitespace-pre-wrap rounded-[14px] bg-[var(--lab-background)] p-3 text-[11px] leading-5 text-[var(--lab-text-primary)]",children:y.data.lines.join(`
12
+ `)}):e.jsx("div",{className:"mt-2 text-sm text-[var(--lab-text-secondary)]",children:t&&a?"Preview unavailable for this file.":"Preview unavailable."})]}):null]}):null,e.jsxs("div",{className:"rounded-[18px] border border-[var(--lab-border)] bg-[var(--lab-surface)] px-4 py-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.12em] text-[var(--lab-text-secondary)]",children:"Trace Actions"}),e.jsx("div",{className:"mt-3 space-y-3",children:s.actions.length?s.actions.map(c=>e.jsxs("div",{className:"rounded-[14px] border border-[var(--lab-border)] bg-[var(--lab-background)] px-3 py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-sm font-semibold text-[var(--lab-text-primary)]",children:c.title||c.tool_name||c.raw_event_type||c.kind||c.action_id}),c.kind?e.jsx(ie,{variant:"outline",children:Ee(c.kind)}):null,c.status?e.jsx(ie,{variant:"outline",children:Ee(c.status)}):null,c.artifact_kind?e.jsx(ie,{variant:"outline",children:Ee(c.artifact_kind)}):null]}),e.jsx("div",{className:"mt-1 text-[11px] text-[var(--lab-text-secondary)]",children:c.created_at||"N/A"}),c.summary?e.jsx("div",{className:"mt-2 text-xs leading-5 text-[var(--lab-text-secondary)]",children:c.summary}):null,c.head_commit?e.jsxs("div",{className:"mt-2 text-xs text-[var(--lab-text-secondary)]",children:["Commit: ",e.jsx("span",{className:"font-semibold text-[var(--lab-text-primary)]",children:c.head_commit})]}):null,c.tool_name?e.jsxs("div",{className:"mt-2 text-xs text-[var(--lab-text-secondary)]",children:["Tool: ",e.jsx("span",{className:"font-semibold text-[var(--lab-text-primary)]",children:c.tool_name})]}):null,c.mcp_server||c.mcp_tool?e.jsxs("div",{className:"mt-2 text-xs text-[var(--lab-text-secondary)]",children:["MCP:"," ",e.jsxs("span",{className:"font-semibold text-[var(--lab-text-primary)]",children:[c.mcp_server||"unknown",c.mcp_tool?`.${c.mcp_tool}`:""]})]}):null,c.args?e.jsx("pre",{className:"mt-2 max-h-36 overflow-auto whitespace-pre-wrap rounded-[12px] bg-[rgba(15,23,42,0.04)] p-2 text-[11px] leading-5 text-[var(--lab-text-primary)]",children:c.args}):null,c.output?e.jsx("pre",{className:"mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded-[12px] bg-[rgba(15,23,42,0.04)] p-2 text-[11px] leading-5 text-[var(--lab-text-primary)]",children:c.output}):null]},c.action_id)):e.jsx("div",{className:"text-sm text-[var(--lab-text-secondary)]",children:"No action records yet."})})]})]}):e.jsx("div",{className:"rounded-[18px] border border-[var(--lab-border)] bg-[var(--lab-surface)] px-4 py-4 text-sm text-[var(--lab-text-secondary)]",children:"No trace is attached to this node yet."})}const lt="ds:lab:focus",ot=t=>{typeof window>"u"||window.dispatchEvent(new CustomEvent(lt,{detail:t}))},jt=t=>"kind"in t?t.kind:"quest",Aa=(t,a)=>{const s=jt(t),u=jt(a);if(s!==u)return!1;if(s==="quest"&&u==="quest"){const n=t,r=a;return n.questId===r.questId&&n.title===r.title&&n.status===r.status&&n.piState===r.piState&&n.baselineBound===r.baselineBound&&n.hasCliBinding===r.hasCliBinding&&n.headBranch===r.headBranch&&n.lastEventAt===r.lastEventAt&&n.pendingQuestionCount===r.pendingQuestionCount&&n.piAgentName===r.piAgentName&&n.piAgentLogo===r.piAgentLogo&&n.piAgentFrameColor===r.piAgentFrameColor&&n.createdAt===r.createdAt&&n.isActive===r.isActive}if(s==="agent"&&u==="agent"){const n=t,r=a;return n.questId===r.questId&&n.agentId===r.agentId&&n.name===r.name&&n.avatar===r.avatar&&n.avatarColor===r.avatarColor&&n.statusTone===r.statusTone&&n.statusState===r.statusState&&n.statusLabel===r.statusLabel}if(s==="pi"&&u==="pi"){const n=t,r=a;return n.agentId===r.agentId&&n.name===r.name&&n.avatar===r.avatar&&n.avatarColor===r.avatarColor&&n.statusTone===r.statusTone&&n.statusState===r.statusState&&n.statusLabel===r.statusLabel}if(s==="pending"&&u==="pending"){const n=t,r=a;return n.count===r.count}return!1},Je=2,W=14,oe=44,Qe=oe+12,La=420,Ta=520,ct=420,Kt=600,Pa=t=>{if(typeof window>"u")return null;try{const a=window.localStorage.getItem(`ds:lab:overview_layout:v${Je}:${t}`);if(!a)return null;const s=JSON.parse(a);return s?.version!==Je?null:s}catch{return null}},ka=(t,a)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(`ds:lab:overview_layout:v${Je}:${t}`,JSON.stringify(a))}catch{}},Ma=(t,a)=>{const r=t%3,f=Math.floor(t/3);return{x:a.x+r*260,y:a.y+f*170}},St=2,Ba=494,Ra=221,Da=340,Ka=150,$e=28,qt=28,Ft=0,Fa=40,Oa=220,Qa=(t,a)=>{const s=Math.max(1,Math.ceil(t/St)),u=(St-1)*Ba+Da,n=(s-1)*Ra+a,r=u+$e*2,f=n+$e*2+qt,w=Ft-u/2-$e,x=Fa-$e-qt;return{x:w,y:x,width:r,height:f}},_e=(t,a,s)=>Math.min(s,Math.max(a,t)),$a=(t,a)=>!(t.x+t.width<=a.x||a.x+a.width<=t.x||t.y+t.height<=a.y||a.y+a.height<=t.y),Et=.5,Ct=(t,a)=>{const s=Number.isFinite(t.x)?t.x:a.x,u=Number.isFinite(t.y)?t.y:a.y;return{x:s,y:u}},ze=(t,a)=>Math.abs(t.x-a.x)>Et||Math.abs(t.y-a.y)>Et,At=(t,a,s)=>{const u=W,n=Math.max(W,a.width-oe-W),r=W,f=Math.max(W,a.height-oe-W),w=_e(t.x,u,n),x=_e(t.y,r,f),j=[{edge:"left",dist:Math.abs(w-u)},{edge:"right",dist:Math.abs(w-n)},{edge:"top",dist:Math.abs(x-r)},{edge:"bottom",dist:Math.abs(x-f)}].sort((y,c)=>y.dist-c.dist)[0]?.edge??"left",_=[],b=(y,c)=>{_.push({x:_e(y,u,n),y:_e(c,r,f)})};if(j==="left"||j==="right"){const y=j==="left"?u:n;b(y,x),b(y,x+Qe),b(y,x-Qe),b(j==="left"?n:u,x)}else{const y=j==="top"?r:f;b(w,y),b(w+Qe,y),b(w-Qe,y),b(w,j==="top"?f:r)}b(u,r),b(n,r),b(u,f),b(n,f);const R=new Set,H=_.filter(y=>{const c=`${y.x}:${y.y}`;return R.has(c)?!1:(R.add(c),!0)});for(const y of H){const c={x:y.x,y:y.y,width:oe,height:oe};if(!s.some(g=>$a(c,g)))return y}return H[0]??{x:u,y:r}},Lt=(t,a,s)=>{if(a)return{width:oe,height:oe};const u=t==="action"?ct:La,n=t==="action"?Kt:Ta;return{width:Math.min(u,Math.max(oe,s.width-24)),height:Math.min(n,Math.max(oe,s.height-24))}},Tt=(t,a)=>({x:Number.isFinite(t?.x)?Number(t?.x):a.x,y:Number.isFinite(t?.y)?Number(t?.y):a.y,collapsed:typeof t?.collapsed=="boolean"?t.collapsed:a.collapsed}),Ot=i.createContext(null),za=({data:t})=>{const{t:a}=ke("lab"),s=t,u=s.status?String(s.status).toLowerCase():null,n=s.piState?String(s.piState).toLowerCase():null,r=!!s.baselineBound,f=s.headBranch?.trim()||"main",w=!!s.hasCliBinding,x=Math.max(0,Number(s.pendingQuestionCount??0)),p=x>0,j=s.lastEventAt?Ve(s.lastEventAt):a("overview_last_event_none",void 0,"No event yet");return e.jsxs("div",{className:ne("lab-overview-quest-node",s.isActive&&"is-active",u?`is-${u}`:null),children:[e.jsx(We,{type:"target",position:Xe.Left,className:"lab-flow-handle"}),e.jsx(We,{type:"source",position:Xe.Right,className:"lab-flow-handle"}),e.jsxs("div",{className:"lab-overview-quest-node__title-row",children:[e.jsx("div",{className:"lab-overview-quest-node__title",children:s.title||"Quest"}),s.piAgentName?e.jsxs("button",{type:"button",className:"lab-overview-pi-chip nodrag nopan nowheel",onClick:_=>{_.stopPropagation(),s.onPiClick?.()},"aria-label":a("overview_open_pi_chat",void 0,"Open PI chat"),title:a("overview_open_pi_chat",void 0,"Open PI chat"),children:[e.jsx("span",{className:"lab-overview-pi-avatar",style:s.piAgentFrameColor?{borderColor:s.piAgentFrameColor}:void 0,children:s.piAgentLogo?e.jsx("img",{src:s.piAgentLogo,alt:""}):e.jsx("span",{className:"lab-overview-pi-avatar__fallback",children:a("overview_pi_label")})}),e.jsx("span",{className:"lab-overview-pi-label",children:s.piAgentName})]}):null]}),e.jsxs("div",{className:"lab-overview-quest-node__meta",children:[e.jsx("span",{children:u||a("overview_unknown",void 0,"unknown")}),e.jsxs("span",{children:[a("overview_pi_label",void 0,"PI")," ",n||a("overview_unknown",void 0,"unknown")]})]}),e.jsxs("div",{className:"lab-overview-quest-node__chips",children:[e.jsx("span",{className:"lab-overview-quest-chip",children:r?a("overview_baseline_bound",void 0,"Baseline bound"):a("overview_baseline_pending",void 0,"Baseline pending")}),e.jsx("span",{className:"lab-overview-quest-chip",children:a("overview_head_branch",{branch:f},"Head {branch}")}),e.jsx("span",{className:"lab-overview-quest-chip",children:w?a("overview_cli_bound",void 0,"CLI bound"):a("overview_cli_pending",void 0,"CLI pending")}),p?e.jsx("span",{className:"lab-overview-quest-chip lab-overview-quest-chip--attention",children:a("overview_decision_count",{count:x},"{count} decisions")}):null,typeof s.progressingCount=="number"?e.jsx("span",{className:"lab-overview-quest-chip",children:a("overview_progressing_count",{count:s.progressingCount},"{count} progressing")}):null,typeof s.experimentCount=="number"?e.jsx("span",{className:"lab-overview-quest-chip",children:a("overview_experiment_count",{count:s.experimentCount},"{count} experiments")}):null,typeof s.pushFailedCount=="number"&&s.pushFailedCount>0?e.jsx("span",{className:"lab-overview-quest-chip lab-overview-quest-chip--attention",children:a("overview_push_failed_count",{count:s.pushFailedCount},"{count} push failed")}):null,typeof s.writerConflictCount=="number"&&s.writerConflictCount>0?e.jsx("span",{className:"lab-overview-quest-chip lab-overview-quest-chip--attention",children:a("overview_writer_conflict_count",{count:s.writerConflictCount},"{count} writer conflicts")}):null,s.runtimeLabel?e.jsx("span",{className:"lab-overview-quest-chip",children:s.runtimeLabel}):null,e.jsx("span",{className:"lab-overview-quest-chip",title:s.lastEventAt??void 0,children:a("overview_last_event",{value:j},"Last event {value}")})]})]})},Ga=({data:t})=>{const a=t,s=`lab-status-${a.statusTone}`;return e.jsxs("div",{className:"lab-overview-agent-node",children:[e.jsx(We,{type:"target",position:Xe.Left,className:"lab-flow-handle"}),e.jsxs("div",{className:ne("lab-avatar lab-avatar-sm",s),children:[e.jsx("span",{className:"lab-avatar-ring",style:{borderColor:a.avatarColor}}),e.jsx("img",{src:a.avatar,alt:a.name})]}),e.jsxs("div",{className:"lab-overview-agent-node__meta",children:[e.jsx("div",{className:"lab-overview-agent-node__name",children:a.name}),e.jsxs("div",{className:"lab-overview-agent-node__status",children:[e.jsx("span",{className:ne("lab-status-indicator",a.statusState==="working"&&"lab-status-indicator-working",a.statusState==="waiting"&&"lab-status-indicator-waiting"),"aria-label":a.statusLabel,title:a.statusLabel,children:a.statusState==="waiting"?e.jsx(Mt,{className:"h-3.5 w-3.5","aria-hidden":"true"}):a.statusState==="working"?e.jsx(Bt,{compact:!0,sizePx:16,className:"lab-status-orbit"}):a.statusState==="paused"?e.jsx(Rt,{className:"h-3.5 w-3.5","aria-hidden":"true"}):e.jsx(Dt,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),e.jsx("span",{className:"lab-overview-agent-node__status-label",children:a.statusLabel})]})]})]})},Va=({data:t})=>{const a=t,s=`lab-status-${a.statusTone}`;return e.jsxs("div",{className:"lab-overview-agent-node",children:[e.jsx(We,{type:"source",position:Xe.Right,className:"lab-flow-handle"}),e.jsxs("div",{className:ne("lab-avatar lab-avatar-sm",s),children:[e.jsx("span",{className:"lab-avatar-ring",style:{borderColor:a.avatarColor}}),e.jsx("img",{src:a.avatar,alt:a.name})]}),e.jsxs("div",{className:"lab-overview-agent-node__meta",children:[e.jsx("div",{className:"lab-overview-agent-node__name",children:a.name}),e.jsxs("div",{className:"lab-overview-agent-node__status",children:[e.jsx("span",{className:ne("lab-status-indicator",a.statusState==="working"&&"lab-status-indicator-working",a.statusState==="waiting"&&"lab-status-indicator-waiting"),"aria-label":a.statusLabel,title:a.statusLabel,children:a.statusState==="waiting"?e.jsx(Mt,{className:"h-3.5 w-3.5","aria-hidden":"true"}):a.statusState==="working"?e.jsx(Bt,{compact:!0,sizePx:16,className:"lab-status-orbit"}):a.statusState==="paused"?e.jsx(Rt,{className:"h-3.5 w-3.5","aria-hidden":"true"}):e.jsx(Dt,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),e.jsx("span",{className:"lab-overview-agent-node__status-label",children:a.statusLabel})]})]})]})},Ua=({data:t})=>{const{t:a}=ke("lab"),s=t,u=i.useContext(Ot);return e.jsxs("div",{className:"lab-overview-pending-node","aria-label":a("overview_pending_decisions"),children:[e.jsxs("div",{className:"lab-overview-pending-node__header",children:[e.jsxs("div",{children:[e.jsx("div",{className:"lab-overview-pending-node__title",children:a("overview_pending_decisions")}),e.jsx("div",{className:"lab-overview-pending-node__subtitle",children:s.count===1?a("overview_pending_single"):a("overview_pending_plural",{count:s.count})})]}),e.jsx("span",{className:"lab-overview-pending-node__count","aria-hidden":"true",children:s.count})]}),e.jsx("div",{className:"lab-overview-pending-node__content nodrag nowheel",children:u})]})},Ha={overviewQuest:za,overviewAgent:Ga,overviewPi:Va,overviewPending:Ua};function Pt({boundsRef:t,title:a,icon:s,state:u,zIndex:n,onChange:r,onActivate:f,className:w,children:x}){const p=i.useRef(null),j=i.useRef(null),_=i.useRef(null),b=i.useRef(!1);i.useEffect(()=>()=>{_.current?.(),_.current=null},[]);const R=i.useCallback(c=>{if(c.stopPropagation(),typeof c.button=="number"&&c.button!==0||(f?.(),!j.current))return;const g=t.current;if(!g)return;_.current?.(),b.current=!1;const K=g.getBoundingClientRect(),G=j.current.getBoundingClientRect(),Q=G.left-K.left,$=G.top-K.top;p.current={originX:Q,originY:$,pointerId:c.pointerId,startX:c.clientX,startY:c.clientY,moved:!1},j.current.setPointerCapture(c.pointerId);const Y=h=>{if(!p.current||h.pointerId!==p.current.pointerId)return;const E=h.clientX-p.current.startX,C=h.clientY-p.current.startY;Math.abs(E)+Math.abs(C)>2&&(p.current.moved=!0);const d=Math.max(W,K.width-G.width-W),V=Math.max(W,K.height-G.height-W),B=_e(p.current.originX+E,W,d),O=_e(p.current.originY+C,W,V);r({...u,x:B,y:O})},A=h=>{p.current&&h.pointerId===p.current.pointerId&&(b.current=p.current.moved,p.current=null,_.current?.(),_.current=null)};window.addEventListener("pointermove",Y),window.addEventListener("pointerup",A),window.addEventListener("pointercancel",A),_.current=()=>{window.removeEventListener("pointermove",Y),window.removeEventListener("pointerup",A),window.removeEventListener("pointercancel",A)}},[t,f,r,u]),H=i.useCallback(c=>{c.stopPropagation(),r({...u,collapsed:!0})},[r,u]),y=i.useCallback(()=>{if(b.current){b.current=!1;return}f?.(),r({...u,collapsed:!1})},[f,r,u]);return u.collapsed?e.jsx("button",{ref:j,type:"button",className:ne("lab-floating-orb nowheel nopan",w),style:{transform:`translate3d(${u.x}px, ${u.y}px, 0)`,zIndex:n},onPointerDown:R,onClick:c=>{c.stopPropagation(),y()},"aria-label":`Show ${a}`,children:s}):e.jsxs("div",{ref:j,className:ne("lab-floating-panel nowheel nopan",w),style:{transform:`translate3d(${u.x}px, ${u.y}px, 0)`,zIndex:n},onPointerDown:c=>{c.stopPropagation(),f?.()},children:[e.jsxs("div",{className:"lab-floating-panel__header",onPointerDown:R,children:[e.jsxs("div",{className:"lab-floating-panel__title",children:[e.jsx("span",{className:"lab-floating-panel__icon",children:s}),e.jsx("span",{children:a})]}),e.jsx("button",{type:"button",className:"lab-floating-panel__collapse",onPointerDown:c=>c.stopPropagation(),onClick:H,"aria-label":`Collapse ${a}`,children:e.jsx(aa,{size:16})})]}),e.jsx("div",{className:"lab-floating-panel__content",children:x})]})}function Ya({projectId:t,quests:a,agents:s=[],templates:u=[],graphVm:n,waitingAnswerByAgentId:r=new Map,pendingDecisionCount:f,activeQuestId:w,hasPiAgent:x,piAgent:p,readOnly:j,canvasLevel:_="map",actionPanel:b,overviewPanel:R,showFloatingPanels:H=!0,onOpenCanvas:y,onOpenQuestPiChat:c,onOpenPiChat:g,onSelectAgent:K}){const{t:G}=ke("lab"),Q=i.useRef(null),[$,Y]=i.useState(!1),A=i.useMemo(()=>Pa(t),[t]),h=A?.viewport??null,E=h&&Number.isFinite(h.x)&&Number.isFinite(h.y)&&Number.isFinite(h.zoom)&&h.zoom>=.15&&h.zoom<=3?h:void 0,C=i.useRef(!1),d=i.useRef(!1),V=i.useRef([]),B=i.useRef(A?.viewport??null),O=i.useRef(null),X=i.useRef(2),[z,de]=i.useState({overview:1,action:2}),[D,ce]=i.useState(()=>Tt(A?.panels?.overview,{x:16,y:16,collapsed:!1})),[U,J]=i.useState(()=>Tt(A?.panels?.action,{x:16,y:88,collapsed:!1})),Ne=i.useMemo(()=>{const m=new Map;return n?.quests?.forEach(l=>{m.set(l.questId,l)}),m},[n]),ee=i.useCallback(m=>{X.current+=1;const l=X.current;de(N=>({...N,[m]:l}))},[]),me=i.useCallback(()=>{typeof window>"u"||(O.current&&window.clearTimeout(O.current),O.current=window.setTimeout(()=>{const m={};V.current.forEach(l=>{m[l.id]={x:l.position.x,y:l.position.y}}),ka(t,{version:Je,viewport:B.current,nodes:m,panels:{overview:{x:D.x,y:D.y,collapsed:D.collapsed},action:{x:U.x,y:U.y,collapsed:U.collapsed}}})},450))},[U,D,t]),Z=i.useMemo(()=>Qa(4,Ka),[]),Se=i.useMemo(()=>{const m=Math.round(Z.x+Z.width+140),l=Math.round(Z.y);return{x:m,y:l}},[Z]),M=i.useMemo(()=>{if(typeof f=="number")return Math.max(0,f);let m=0;for(const l of r.values())l&&(m+=1);return m},[f,r]),te=_==="ops",fe=M>0&&!te,Le=te||!fe;i.useLayoutEffect(()=>{const m=Q.current;if(!m)return;const l=m.getBoundingClientRect();J(N=>{const F=Number.isFinite(A?.panels?.action?.x),k=Number.isFinite(A?.panels?.action?.y);if(F||k||N.x!==16||N.y!==88)return N;const v=Math.max(W,l.width-ct-W);return{...N,x:v}})},[A?.panels?.action?.x,A?.panels?.action?.y]),i.useLayoutEffect(()=>{const m=Q.current;if(!m)return;const l=m.getBoundingClientRect(),N=(q,se)=>{const I=Math.max(W,l.width-se.width-W),be=Math.max(W,l.height-se.height-W);return{x:_e(q.x,W,I),y:_e(q.y,W,be)}},F=Lt("overview",D.collapsed,l),k=Lt("action",U.collapsed,l);let v=D;if(!D.collapsed){const q=N(D,F);(q.x!==D.x||q.y!==D.y)&&(v={...D,...q})}let L=U;if(!U.collapsed){const q=N(U,k);(q.x!==U.x||q.y!==U.y)&&(L={...U,...q})}const T=[];if(v.collapsed||T.push({x:v.x,y:v.y,...F}),L.collapsed||T.push({x:L.x,y:L.y,...k}),v.collapsed){const q=Ct(At(v,l,T),v);ze(q,v)&&(v={...v,...q}),T.push({x:v.x,y:v.y,width:oe,height:oe})}if(L.collapsed){const q=Ct(At(L,l,T),L);ze(q,L)&&(L={...L,...q})}(ze(v,D)||v.collapsed!==D.collapsed)&&ce(v),(ze(L,U)||L.collapsed!==U.collapsed)&&J(L)},[U,D,A?.panels?.action?.x,A?.panels?.action?.y]),i.useEffect(()=>{te&&(ee("action"),J(m=>m.collapsed?{...m,collapsed:!1}:m))},[ee,te]);const o=i.useMemo(()=>{if(!fe)return null;const m=ct,l=Kt,N=A?.nodes?.["overview:pending"]??null,F=Math.round(Z.x+Z.width/2-m/2),k=Math.round(Z.y+Z.height+96);return{id:"overview:pending",type:"overviewPending",position:N||{x:F,y:k},draggable:!j,selectable:!j,data:{kind:"pending",count:M},style:{width:m,height:l,zIndex:2}}},[Z,fe,j,M,A?.nodes]),S=i.useMemo(()=>{const m=A?.nodes??{};return a.map((l,N)=>{const F=Ne.get(l.quest_id),k=`quest:${l.quest_id}`,v=m?.[k]??null,L=v||Ma(N,Se),T=F?.summary,q=F?.runtime,se=q&&q.runningAgents>0?G("overview_runtime_running",{count:q.runningAgents},"{count} running"):null;return{id:k,type:"overviewQuest",position:L,draggable:!j,data:{questId:l.quest_id,title:l.title||"Quest",status:l.status??null,piState:l.pi_state??q?.piState??null,baselineBound:F?.governance.formalBaselineState==="confirmed"||l.governance?.formalBaselineState==="confirmed",hasCliBinding:!!l.cli_server_id,headBranch:F?.topology.headBranch??l.git_head_branch??null,lastEventAt:l.last_event_at??null,pendingQuestionCount:Math.max(0,Number(l.pending_question_count??0)),piAgentName:p?.name??null,piAgentLogo:p?.logo??null,piAgentFrameColor:p?.frameColor??null,onPiClick:p?.name?()=>{if(c){c(l.quest_id);return}g?.()}:null,createdAt:l.created_at??null,isActive:l.quest_id===w,progressingCount:T?.progressingCount??void 0,experimentCount:T?.experimentCount??void 0,runtimeLabel:se,pushFailedCount:T?.pushFailedCount??void 0,writerConflictCount:T?.writerConflictCount??void 0}}})},[w,Ne,g,c,p,G,a,j,A?.nodes,Se]),P=i.useMemo(()=>new Map(u.map(m=>[m.template_id,m])),[u]),ae=i.useMemo(()=>{if(!x||!s.length)return null;const m=u.find(je=>je.template_key==="pi")??null,l=(m?s.find(je=>je.template_id===m.template_id):s.find(je=>je.agent_id==="pi"))??null;if(!l)return null;const N=A?.nodes??{},F={x:Ft-Oa/2,y:Z.y+Z.height+48},k=`pi:${l.instance_id}`,v=N?.[k]??F,L=l.template_id?P.get(l.template_id)??null:null,T=He(l)||"PI",q=rt(l,L),se=l.avatar_frame_color?.trim()||Ye(l.instance_id,0),I=typeof l.status=="string"?l.status.toLowerCase():"idle",be=r.get(l.instance_id)??!1,Be=I==="waiting"&&!be,Re=I==="waiting"&&!be?"idle":I,qe=be,Te=!qe&&pt(Re),De=qe?"waiting":Te?"working":gt(Re),bt=qe?"waiting":Te?"working":Be?"paused":"resting",Ze=qe?"Waiting for answer":Te?"Working":Be?"Paused":"Resting";return{id:k,type:"overviewPi",position:v,draggable:!j,data:{kind:"pi",agentId:l.instance_id,name:T,avatar:q,avatarColor:se,statusTone:De,statusState:bt,statusLabel:Ze}}},[s,Z,x,j,A?.nodes,u,P,r]),ve=i.useMemo(()=>{if(!s.length||!S.length)return[];const m=A?.nodes??{},l=new Map(S.map(v=>[v.id,v])),N=new Set(a.map(v=>v.quest_id)),F=new Map;s.forEach(v=>{const L=v.active_quest_id;if(!L||!N.has(L))return;const T=F.get(L)??[];T.push(v),F.set(L,T)});const k=[];return F.forEach((v,L)=>{const T=l.get(`quest:${L}`);if(!T)return;const q=v.length>3?2:1,se=Math.ceil(v.length/q);v.forEach((I,be)=>{const Be=be%q,Re=Math.floor(be/q),qe=240+Be*170,Te=(Re-(se-1)/2)*90,De=`agent:${L}:${I.instance_id}`,Ze=m?.[De]??null??{x:T.position.x+qe,y:T.position.y+Te},je=I.template_id?P.get(I.template_id)??null:null,Vt=He(I),Ut=rt(I,je),Ht=I.avatar_frame_color?.trim()||Ye(I.instance_id,be),Ie=typeof I.status=="string"?I.status.toLowerCase():"idle",et=r.get(I.instance_id)??!1,ht=Ie==="waiting"&&!et,ft=Ie==="waiting"&&!et?"idle":Ie,Ke=et,tt=!Ke&&pt(ft),Yt=Ke?"waiting":tt?"working":gt(ft),Wt=Ke?"waiting":tt?"working":ht?"paused":"resting",Xt=Ke?"Waiting for answer":tt?"Working":ht?"Paused":"Resting";k.push({id:De,type:"overviewAgent",position:Ze,draggable:!j,data:{kind:"agent",questId:L,agentId:I.instance_id,name:Vt,avatar:Ut,avatarColor:Ht,statusTone:Yt,statusState:Wt,statusLabel:Xt}})})}),k},[s,S,a,j,A?.nodes,P,r]),$t=i.useMemo(()=>{const m=ae?[ae]:[];return[...o?[o]:[],...m,...S,...ve]},[ve,o,ae,S]),[xe,dt,zt]=Zt($t),mt=i.useMemo(()=>{const m={stroke:"var(--lab-border-strong)",strokeWidth:1.2,strokeDasharray:"4 6"};return ve.map(l=>({id:`agent-edge:${l.data.questId}:${l.data.agentId}`,source:`quest:${l.data.questId}`,target:l.id,type:"smoothstep",style:m,animated:!1}))},[ve]),vt=i.useMemo(()=>ae?S.map(m=>({id:`pi-edge:${ae.id}:${m.id}`,source:ae.id,target:m.id,type:"smoothstep",style:{stroke:"var(--lab-accent-strong)",strokeWidth:1.4,strokeDasharray:"2 6"},animated:!1})):[],[ae,S]),Gt=i.useMemo(()=>[...vt,...mt],[mt,vt]),Me=It();return i.useEffect(()=>{V.current=xe},[xe]),i.useEffect(()=>{dt(m=>{const l=new Map(m.map(v=>[v.id,v])),N=ae?[ae]:[],k=[...o?[o]:[],...N,...S,...ve].map(v=>{const L=l.get(v.id);return L&&(v.type==="overviewQuest"||v.type==="overviewAgent"||v.type==="overviewPi"||v.type==="overviewPending")?{...v,position:L.position}:v});if(m.length===k.length){let v=!0;for(let L=0;L<k.length;L+=1){const T=m[L],q=k[L];if(!T||!q||T.id!==q.id){v=!1;break}if(T.position.x!==q.position.x||T.position.y!==q.position.y){v=!1;break}if(!Aa(T.data,q.data)){v=!1;break}}if(v)return m}return k})},[w,ve,o,ae,S,dt]),i.useEffect(()=>{me()},[U,D,me]),i.useEffect(()=>{if(!xe.length||E||C.current)return;let m=0,l=0;const N=()=>{l+=1;try{Me.fitView({padding:.2,duration:450}),C.current=!0}catch{l<8&&typeof window<"u"&&(m=window.requestAnimationFrame(N))}};return N(),()=>{m&&typeof window<"u"&&window.cancelAnimationFrame(m)}},[Me,E,xe.length]),i.useEffect(()=>{if(!xe.length||!E||C.current||d.current)return;const m=Q.current;if(!m)return;const l=m.getBoundingClientRect();if(!l.width||!l.height)return;const N=E.x,F=E.y,k=E.zoom,v=160;if(!xe.some(T=>{const q=T.position.x*k+N,se=T.position.y*k+F;return q>-v&&q<l.width+v&&se>-v&&se<l.height+v})){let T=0,q=0;const se=()=>{q+=1;try{Me.fitView({padding:.2,duration:450}),C.current=!0}catch{q<8&&typeof window<"u"&&(T=window.requestAnimationFrame(se))}};return se(),()=>{T&&typeof window<"u"&&window.cancelAnimationFrame(T)}}d.current=!0},[Me,E,xe]),i.useEffect(()=>()=>{O.current&&window.clearTimeout(O.current)},[]),i.useLayoutEffect(()=>{Y(!1);const m=Q.current;if(!m||typeof window>"u")return;let l=0,N=0;const F=()=>{N+=1;const k=m.getBoundingClientRect();if(k.width>0&&k.height>0){Y(!0);return}N<6&&(l=window.requestAnimationFrame(F))};return F(),()=>{l&&window.cancelAnimationFrame(l)}},[t]),e.jsx(Ot.Provider,{value:fe?b:null,children:e.jsxs("div",{ref:Q,className:ne("lab-overview-canvas",te&&"lab-overview-canvas--ops"),children:[$?null:e.jsx("div",{className:"space-y-3 p-4",children:H?e.jsxs(e.Fragment,{children:[te?null:R,b]}):null}),e.jsx("div",{className:"lab-quest-graph-shell lab-quest-graph-shell--full",children:e.jsx(ea,{nodes:xe,edges:Gt,nodeTypes:Ha,onNodesChange:zt,nodesDraggable:!j,panOnDrag:!0,zoomOnScroll:!0,zoomOnPinch:!0,minZoom:.15,maxZoom:3,defaultViewport:E,onNodeDragStop:()=>me(),onMoveEnd:(m,l)=>{B.current=l,me()},onNodeClick:(m,l)=>{const N=l.data;if(N&&typeof N=="object"&&N.kind==="pending"){ot({projectId:t,focusType:"overview",focusId:t}),H&&Le&&(ee("action"),J(k=>({...k,collapsed:!1})));return}if(N&&typeof N=="object"&&N.kind==="agent"){const k=N;K?.(k.agentId,k.questId);return}if(N&&typeof N=="object"&&N.kind==="pi"){K?.(N.agentId,null),g?.();return}const F=l.data?.questId;F&&(ot({projectId:t,focusType:"quest",focusId:F}),y?.(F))},children:e.jsx(ta,{color:"var(--lab-border)",gap:28,size:1,variant:"dots"})})}),$?e.jsxs(e.Fragment,{children:[H&&!te?e.jsx(Pt,{boundsRef:Q,title:G("overview_overall"),icon:e.jsx(ja,{size:16}),state:D,zIndex:z.overview,onChange:ce,onActivate:()=>ee("overview"),className:"lab-overview-panel--overview",children:R}):null,H&&Le?e.jsx(Pt,{boundsRef:Q,title:G("overview_action_center"),icon:e.jsx(_a,{size:16}),state:U,zIndex:z.action,onChange:J,onActivate:()=>ee("action"),className:"lab-overview-panel--action",children:b}):null]}):null]})})}function Wa(t){return e.jsx(Jt,{children:e.jsx(Ya,{...t})})}const Ae=t=>{const a=String(t||"").trim().replace(/[_-]+/g," ");return a?a.replace(/\b\w/g,s=>s.toUpperCase()):"N/A"};function pe({children:t,mono:a=!1}){return e.jsx("span",{className:ne("inline-flex max-w-full items-center rounded-full border border-[var(--lab-border)] px-2.5 py-1 text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--lab-text-secondary)]",a&&"font-mono normal-case tracking-[0.02em]"),children:e.jsx("span",{className:"truncate",children:t})})}function ge({title:t,hint:a,actions:s,children:u,first:n=!1}){return e.jsxs("section",{className:ne("py-5",n?"pt-0":"border-t border-dashed border-[var(--lab-border)]"),children:[e.jsxs("div",{className:"mb-5 flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.18em] text-[var(--lab-text-secondary)]",children:t}),a?e.jsx("div",{className:"mt-2 text-sm leading-7 text-[var(--lab-text-secondary)]",children:a}):null]}),s?e.jsx("div",{className:"shrink-0",children:s}):null]}),u]})}function ye({icon:t,label:a,value:s,hint:u}){return e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--lab-text-secondary)]",children:[e.jsx("span",{className:"shrink-0",children:t}),e.jsx("span",{children:a})]}),e.jsx("div",{className:"mt-2 break-words text-[15px] font-semibold leading-6 text-[var(--lab-text-primary)]",children:s}),u?e.jsx("div",{className:"mt-2 break-words text-sm leading-6 text-[var(--lab-text-secondary)]",children:u}):null]})}function Ge({items:t}){return e.jsx("div",{className:"divide-y divide-dashed divide-[var(--lab-border)]",children:t.map(a=>e.jsxs("div",{className:"grid gap-2 py-3 sm:grid-cols-[130px_minmax(0,1fr)]",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.16em] text-[var(--lab-text-secondary)]",children:a.label}),e.jsx("div",{className:"break-words text-sm leading-7 text-[var(--lab-text-primary)]",children:a.value})]},a.label))})}function Xa(t){return t==="truth"?"border-[rgba(64,113,175,0.24)] bg-[rgba(64,113,175,0.1)] text-[#315c97] dark:text-[#9ec5ff]":t==="runtime"?"border-[rgba(99,102,241,0.24)] bg-[rgba(99,102,241,0.1)] text-[#4f46e5] dark:text-[#c7d2fe]":t==="overlay"?"border-[rgba(83,176,174,0.26)] bg-[rgba(83,176,174,0.12)] text-[#0f766e] dark:text-[#8be4db]":"border-[rgba(148,163,184,0.26)] bg-[rgba(148,163,184,0.12)] text-[var(--lab-text-secondary)]"}function Ja({projectId:t,readOnly:a,onRefresh:s,onOpenStageSelection:u,cliStatus:n,labStream:r,projectName:f,templates:w,agents:x,quests:p,overview:j,isLoading:_,lockedQuestId:b=null,immersiveLockedQuest:R=!1}){const{t:H}=ke("lab"),y=ut(),c=Ue(o=>o.setActiveQuest),g=yt(o=>o.selection),K=yt(o=>o.clear),[G,Q]=i.useState(null),[$,Y]=i.useState(null),[A,h]=i.useState(null),[E,C]=i.useState(null),d=b??G,V=i.useMemo(()=>new Map(w.map(o=>[o.template_id,o])),[w]),B=i.useMemo(()=>p.find(o=>o.quest_id===d)??null,[p,d]),O=i.useMemo(()=>x.find(o=>o.instance_id===E)??null,[x,E]),X=i.useMemo(()=>{const o=w.filter(S=>["pi","principal-investigator"].includes(String(S.template_key||"").trim().toLowerCase()));if(o.length){const S=x.find(P=>o.some(ae=>P.template_id===ae.template_id))??null;if(S)return S}return x.find(S=>{const P=String(S.agent_id||"").trim().toLowerCase(),ae=String(S.mention_label||"").trim().replace(/^@/,"").toLowerCase();return P==="pi"||ae==="pi"||P.endsWith(":pi")||String(S.template_id||"").trim().toLowerCase().includes("principal")})??null},[x,w]),z=X?.template_id?V.get(X.template_id)??null:null,de=X?{name:He(X),logo:rt(X,z),frameColor:X.avatar_frame_color||Ye(X.instance_id,0)}:null,D=i.useMemo(()=>{const o=j.graph_vm?.project?.pendingDecisionCount;return typeof o=="number"?Math.max(0,o):p.reduce((S,P)=>S+Math.max(0,Number(P.pending_question_count??0)),0)},[j.graph_vm?.project?.pendingDecisionCount,p]);i.useEffect(()=>{b||d&&!B&&!_.quests&&(Q(null),Y(null),h(null),K())},[K,_.quests,b,B,d]),i.useEffect(()=>{b&&(Y(o=>o??null),h(o=>o??null),C(null))},[b]),i.useEffect(()=>{c(d)},[d,c]),i.useEffect(()=>{const o=S=>{const P=S.detail;if(P&&!(P.projectId&&P.projectId!==t)){if(P.focusType==="overview"||P.focusType==="canvas"){b||Q(null),Y(null),h(null),C(null),K();return}if(P.focusType==="agent"){C(P.focusId??null);return}if(P.focusType==="quest"||P.focusType==="quest-branch"||P.focusType==="quest-event"){if(b&&P.focusId&&P.focusId!==b)return;b||Q(P.focusId??null),Y(P.branch??null),h(P.eventId??null),C(null),K()}}};return window.addEventListener(lt,o),()=>window.removeEventListener(lt,o)},[K,b,t]);const ce=le({queryKey:["lab-quest-detail",t,d,"canvas-studio"],queryFn:()=>ra(t,d),enabled:!!(t&&d),staleTime:1e4}),U=le({queryKey:["lab-quest-summary",t,d,A??null,"canvas-studio"],queryFn:()=>la(t,d,{atEventId:A}),enabled:!!(t&&d),staleTime:1e4}),J=le({queryKey:["lab-quest-event-payload",t,d,g?.selection_type??null,g?.selection_ref??null,"canvas-studio"],queryFn:()=>oa(t,d,g?.selection_ref,{maxBytes:1e5}),enabled:!!(t&&d&&g?.selection_type==="event_node"&&g?.selection_ref),staleTime:1e4}),Ne=le({queryKey:["lab-quest-node-trace",t,d,g?.selection_type??null,g?.selection_ref??null,"canvas-studio"],queryFn:()=>ca(t,d,g?.selection_ref,{selectionType:g?.selection_type??null}),enabled:!!(t&&d&&g?.selection_ref&&["branch_node","event_node","stage_node"].includes(String(g?.selection_type||""))),staleTime:1e4}),ee=i.useMemo(()=>sa({selectionType:g?.selection_type,edgeType:g?.summary??g?.selection_ref??null,hasActiveProposal:!1}),[g?.selection_ref,g?.selection_type,g?.summary]),me=i.useCallback(()=>{Promise.resolve(s?.()),y.invalidateQueries({queryKey:["lab-agents",t]}),y.invalidateQueries({queryKey:["lab-quests",t]}),y.invalidateQueries({queryKey:["lab-overview",t]}),d&&(y.invalidateQueries({queryKey:["lab-quest-detail",t,d]}),y.invalidateQueries({queryKey:["lab-quest-summary",t,d]}),y.invalidateQueries({queryKey:["lab-quest-graph",t,d]}),y.invalidateQueries({queryKey:["lab-quest-node-trace",t,d]}))},[s,t,y,d]),Z=i.useCallback((o,S,P)=>{b&&o!==b||(b||Q(o),Y(S??null),h(P??null),C(null),K())},[K,b]),Se=i.useCallback(()=>{b||Q(null),Y(null),h(null),K()},[K,b]),M=()=>e.jsxs("div",{className:"space-y-0",children:[_.quests||_.agents||_.overview?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"h-24 w-full rounded-[18px]"}),e.jsx(ue,{className:"h-20 w-full rounded-[18px]"})]}):null,e.jsxs(ge,{first:!0,title:"Overall",hint:"Select a quest node to enter its canvas. After that, click a branch, event, or stage node to inspect its durable detail state here.",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(pe,{children:"Home"}),e.jsx(pe,{children:Ae(n)}),e.jsxs(pe,{children:[p.length," quests"]}),e.jsxs(pe,{children:[x.length," agents"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-2",children:[e.jsx(at,{className:"h-4 w-4 text-[#4071af]"}),e.jsx("div",{className:"text-[22px] font-semibold tracking-[-0.03em] text-[var(--lab-text-primary)]",children:f||H("plugin_home_title",void 0,"Home")})]})]}),e.jsx(ge,{title:"Operational Status",hint:"Keep this panel focused on high-signal canvas state rather than dashboard clutter.",children:e.jsxs("div",{className:"grid gap-x-8 gap-y-5 sm:grid-cols-2",children:[e.jsx(ye,{icon:e.jsx(_t,{className:"h-4 w-4"}),label:"Quests",value:p.length,hint:"Durable research repositories tracked in this project."}),e.jsx(ye,{icon:e.jsx(nt,{className:"h-4 w-4"}),label:"Agents",value:x.length,hint:"Live agent instances visible to the Lab surface."}),e.jsx(ye,{icon:e.jsx(at,{className:"h-4 w-4"}),label:"Pending",value:D,hint:"User decisions or unresolved blocking items."}),e.jsx(ye,{icon:e.jsx(Oe,{className:"h-4 w-4"}),label:"CLI",value:Ae(n),hint:"Shared runtime binding for this project workspace."})]})}),e.jsx(ge,{title:"Next Step",hint:"The Lab plugin is now canvas-first. Explorer handles navigation, center tabs handle content, and this rail only summarizes context.",children:e.jsx(Ge,{items:[{label:"Canvas",value:"Open a quest node to switch from map view into its research graph."},{label:"Selection",value:"Branch, event, and stage nodes expose stable detail summaries here."},{label:"Explorer",value:"Changed files now open in center tabs instead of rendering inline in the navigator."}]})}),O?te(O):null]}),te=o=>{const S=o.template_id?V.get(o.template_id)??null:null;return e.jsxs(ge,{title:"Agent",hint:"Current agent focus selected from the overview canvas.",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full border border-[var(--lab-border)] bg-[var(--lab-background)]",style:{boxShadow:`0 0 0 2px ${o.avatar_frame_color||Ye(o.instance_id)}`},children:e.jsx(nt,{className:"h-4 w-4 text-[var(--lab-text-primary)]"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-semibold text-[var(--lab-text-primary)]",children:He(o)}),e.jsx("div",{className:"truncate text-xs text-[var(--lab-text-secondary)]",children:S?.template_key||o.agent_id})]})]}),e.jsx("div",{className:"mt-5",children:e.jsx(Ge,{items:[{label:"Status",value:Ae(o.status)},{label:"Quest",value:o.active_quest_id||"Unassigned"},{label:"Branch",value:o.active_quest_branch||"N/A"},{label:"Stage",value:o.active_quest_stage_key||"N/A"}]})})]})},he=()=>{if(!d)return null;const o=ce.data?.quest??B,S=U.data?.quest??null,P=S?.runtime??null,ve=(S?.governance??null)?.lastPushStatus||(typeof o?.github_push?.status=="string"?o.github_push.status:null)||"N/A";return ce.isLoading&&!o?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ue,{className:"h-28 w-full rounded-[18px]"}),e.jsx(ue,{className:"h-20 w-full rounded-[18px]"}),e.jsx(ue,{className:"h-20 w-full rounded-[18px]"})]}):e.jsxs("div",{className:"space-y-0",children:[e.jsxs(ge,{first:!0,title:"Overall",hint:o?.description?.trim()||o?.summary?.trim()||"No quest description yet.",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(pe,{children:Ae(o?.status)}),e.jsx(pe,{children:S?.topology?.headBranch||o?.git_head_branch||"main"}),e.jsx(pe,{mono:!0,children:d}),$?e.jsx(pe,{children:$}):null]}),e.jsx("div",{className:"mt-4 text-[22px] font-semibold tracking-[-0.03em] text-[var(--lab-text-primary)]",children:o?.title||d}),e.jsxs("div",{className:"mt-5 grid gap-x-8 gap-y-5 sm:grid-cols-2",children:[e.jsx(ye,{icon:e.jsx(_t,{className:"h-4 w-4"}),label:"Branches",value:S?.topology?.branchCount??0,hint:`Head ${S?.topology?.headBranch||o?.git_head_branch||"main"}`}),e.jsx(ye,{icon:e.jsx(nt,{className:"h-4 w-4"}),label:"Running Agents",value:P?.runningAgents??0,hint:"Live agents attached to this quest."}),e.jsx(ye,{icon:e.jsx(at,{className:"h-4 w-4"}),label:"Pending Questions",value:Math.max(0,Number(o?.pending_question_count??0)),hint:"Open decisions or direct user replies still waiting."}),e.jsx(ye,{icon:e.jsx(Oe,{className:"h-4 w-4"}),label:"Push Status",value:ve,hint:o?.last_event_at?`Last event ${Ve(o.last_event_at)}`:"No event timestamp yet."})]})]}),g?e.jsxs(e.Fragment,{children:[e.jsxs(ge,{title:"Selection",hint:g.summary||"No structured summary is attached to this node yet.",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[ee?e.jsx("span",{className:ne("inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold",Xa(ee.tone)),children:H(Nt[ee.tone].labelKey,void 0,Nt[ee.tone].labelDefault)}):null,e.jsx(ie,{variant:"outline",children:Ae(g.selection_type)})]}),e.jsx("div",{className:"mt-4 text-base font-semibold text-[var(--lab-text-primary)]",children:g.label||g.selection_ref}),e.jsx("div",{className:"mt-5",children:e.jsx(Ge,{items:[{label:"Ref",value:g.selection_ref},{label:"Branch No",value:g.branch_no||"N/A"},{label:"Branch",value:g.branch_name||"N/A"},{label:"Parent",value:g.parent_branch||"N/A"},{label:"Foundation",value:g.foundation_label||"N/A"},{label:"Stage",value:g.stage_key||"N/A"},{label:"Worktree",value:g.worktree_rel_path||"N/A"},{label:"Agent",value:g.agent_instance_id||"N/A"}]})})]}),e.jsx(ge,{title:"Trace",hint:"Durable actions, artifact payloads, and commit evidence attached to the selected node.",children:e.jsx(Ca,{projectId:t,questId:d,trace:Ne.data?.trace??null,isLoading:Ne.isLoading,payloadJson:J.data?.payload_json??null,payloadTruncated:J.data?.truncated??null})})]}):e.jsx(ge,{title:"Operational Status",hint:"Quest-level runtime, topology, and governance signals.",children:e.jsx(Ge,{items:[{label:"Head Branch",value:S?.topology?.headBranch||o?.git_head_branch||"main"},{label:"Pending Questions",value:Math.max(0,Number(o?.pending_question_count??0))},{label:"Branch Count",value:S?.topology?.branchCount??0},{label:"Running Agents",value:P?.runningAgents??0},{label:"Push Status",value:ve},{label:"Last Event",value:o?.last_event_at?Ve(o.last_event_at):"N/A"},{label:"Created",value:o?.created_at?Ve(o.created_at):"N/A"}]})})]})},fe=B?B.title||B.quest_id:f||H("plugin_home_title",void 0,"Home"),Le=B?b?"Research canvas":"Quest canvas":"Quest map";return b&&R&&d?e.jsxs("div",{className:"relative flex h-full min-h-0 w-full flex-1 overflow-hidden",children:[e.jsx("div",{className:"absolute right-4 top-4 z-20",children:e.jsxs(Fe,{type:"button",size:"sm",variant:"outline",className:"h-9 rounded-full border-[var(--lab-border)] bg-[rgba(255,255,255,0.94)] px-3 text-[11px] text-[var(--lab-text-primary)] shadow-[0_10px_28px_rgba(15,23,42,0.08)] backdrop-blur dark:bg-[rgba(28,29,34,0.94)]",onClick:me,children:[e.jsx(Oe,{className:"mr-1.5 h-3.5 w-3.5"}),"Refresh"]})}),e.jsx("div",{className:"h-full min-h-0 w-full overflow-hidden",children:e.jsx(wt,{projectId:t,questId:d,readOnly:a,highlightBranch:$,atEventId:A,preferredViewMode:A?"event":"branch",activeBranch:$,onBranchSelect:o=>{Y(o),h(null)},onEventSelect:(o,S)=>{h(o),S&&Y(S)},showFloatingPanels:!1,minimalChrome:!0,onStageOpen:u})})]}):e.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-[20px] border border-[var(--lab-border)] bg-[var(--lab-surface)] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&!b?e.jsx(Fe,{type:"button",size:"sm",variant:"ghost",className:"h-8 px-2",onClick:Se,children:e.jsx(na,{className:"h-4 w-4"})}):null,e.jsx("div",{className:"truncate text-sm font-semibold text-[var(--lab-text-primary)]",children:fe})]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs text-[var(--lab-text-secondary)]",children:[e.jsx("span",{children:Le}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[p.length," quests"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[x.length," agents"]}),r?.status&&r.status!=="idle"?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{children:["stream ",r.status]})]}):null]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[$?e.jsx(ie,{variant:"outline",children:$}):null,e.jsx(ie,{variant:"outline",children:Ae(n)}),e.jsxs(Fe,{type:"button",size:"sm",variant:"outline",className:"h-8 px-3",onClick:me,children:[e.jsx(Oe,{className:"mr-1.5 h-3.5 w-3.5"}),"Refresh"]})]})]}),e.jsxs("div",{className:"grid min-h-0 flex-1 gap-4 xl:grid-cols-[minmax(0,1fr)_360px]",children:[e.jsx("div",{className:"min-h-0 overflow-hidden rounded-[24px] border border-[var(--lab-border)] bg-[var(--lab-surface)]",children:d?e.jsx(wt,{projectId:t,questId:d,readOnly:a,highlightBranch:$,atEventId:A,preferredViewMode:A?"event":"branch",activeBranch:$,onBranchSelect:o=>{Y(o),h(null)},onEventSelect:(o,S)=>{h(o),S&&Y(S)},showFloatingPanels:!1,onStageOpen:u}):e.jsx(Wa,{projectId:t,quests:p,agents:x,templates:w,graphVm:j.graph_vm??null,pendingDecisionCount:D,activeQuestId:d,hasPiAgent:!!de,piAgent:de,readOnly:a,actionPanel:null,overviewPanel:null,showFloatingPanels:!1,onOpenCanvas:Z,onSelectAgent:o=>{C(o)}})}),e.jsx("aside",{className:"min-h-0 overflow-hidden rounded-[24px] border border-[var(--lab-border)] bg-[var(--lab-surface)]",children:e.jsx(ia,{className:"h-full",children:e.jsxs("div",{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold text-[var(--lab-text-primary)]",children:"Details"}),e.jsx("div",{className:"mt-1 text-xs text-[var(--lab-text-secondary)]",children:d?"Selected node and quest context.":"Overview context and node guidance."})]}),d?e.jsx(Fe,{type:"button",size:"sm",variant:"ghost",className:"h-8 px-3",onClick:()=>{K(),h(null)},children:"Clear node"}):null]}),d?he():M()]})})})]})]})}const Za=80,Ia=new Set(["lab.agent.changed","lab.agent.status"]),es=new Set(["lab.assignment.changed"]),ts=new Set(["lab.quest.changed","lab.quest.event","lab.quest.sync"]),as=new Set(["lab.quest.runtime"]),ss=new Set(["lab.memory.changed"]),ns=new Set(["lab.paper.changed"]),is=new Set(["lab.baseline.archive","lab.baseline.restore"]),Pe=t=>!t||typeof t!="object"?null:t,re=t=>{if(typeof t!="string")return null;const a=t.trim();return a||null},rs=t=>{if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){const a=t.trim().toLowerCase();return a==="1"||a==="true"||a==="yes"}return!1},ls=t=>Array.isArray(t)?t.map(a=>re(a)).filter(a=>!!a):[],os=t=>{if(!t)return null;const a=Pe(t.data),s=re(a?.quest_id)??re(a?.questId)??re(a?.active_quest_id)??re(t.quest_id)??re(t.questId)??re(t.active_quest_id);if(s)return s;const u=Pe(a?.quest);return re(u?.quest_id)??re(u?.id)},Qt=t=>[{queryKey:["lab-agents",t]},{queryKey:["lab-quests",t]},{queryKey:["lab-overview",t]}],we=(t,a)=>a?[{queryKey:["lab-quest-detail",t,a]},{queryKey:["lab-quest",t,a]},{queryKey:["lab-quest-summary",t,a]},{queryKey:["lab-quest-graph",t,a]},{queryKey:["lab-quest-events",t,a]},{queryKey:["lab-quest-event-payload",t,a]},{queryKey:["lab-quest-node-trace",t,a]},{queryKey:["lab-quest-decision-events",t,a]},{queryKey:["lab-quest-pi-qa-events",t,a]},{queryKey:["lab-quest-branch-insights",t,a]},{queryKey:["lab-quest-runtime",t,a]},{queryKey:["lab-papers",t,a]},{queryKey:["lab-memory",t,a]}]:[{queryKey:["lab-quest-detail",t]},{queryKey:["lab-quest",t]},{queryKey:["lab-quest-summary",t]},{queryKey:["lab-quest-graph",t]},{queryKey:["lab-quest-events",t]},{queryKey:["lab-quest-event-payload",t]},{queryKey:["lab-quest-node-trace",t]},{queryKey:["lab-quest-decision-events",t]},{queryKey:["lab-quest-pi-qa-events",t]},{queryKey:["lab-quest-branch-insights",t]},{queryKey:["lab-quest-runtime",t]},{queryKey:["lab-papers",t]},{queryKey:["lab-memory",t]}],cs=t=>[{queryKey:["lab-memory",t]}],us=(t,a,s)=>Ia.has(t)?[{queryKey:["lab-agents",a]},{queryKey:["lab-overview",a]}]:es.has(t)?[{queryKey:["lab-agents",a]},{queryKey:["lab-quests",a]},{queryKey:["lab-overview",a]},...we(a,s)]:ts.has(t)?[{queryKey:["lab-agents",a]},{queryKey:["lab-quests",a]},{queryKey:["lab-overview",a]},...we(a,s)]:as.has(t)?[{queryKey:["lab-quests",a]},{queryKey:["lab-overview",a]},...we(a,s)]:ss.has(t)?[...cs(a),...we(a,s)]:ns.has(t)?[{queryKey:["lab-papers",a]},{queryKey:["lab-overview",a]},...we(a,s)]:is.has(t)?[{queryKey:["lab-baselines",a]},{queryKey:["lab-quests",a]},{queryKey:["lab-overview",a]},...we(a,s)]:t.startsWith("lab.")?[{queryKey:["lab-quests",a]},{queryKey:["lab-overview",a]},...s?we(a,s):[]]:Qt(a),ds=(t,a,s)=>{if(t!=="lab.agent.changed")return null;const u=Pe(s?.data);if(!u)return null;const n=re(u.action)?.toLowerCase();if(n!=="created"&&n!=="promoted"||!rs(u.auto_focus))return null;const r=re(u.agent_instance_id);return r?{projectId:a,focusType:"agent",focusId:r}:null};function ms({projectId:t,enabled:a}){const s=ut(),[u,n]=i.useState({status:"idle",lastEventAt:null}),r=ua();return i.useEffect(()=>{if(!a||!t||r){n(h=>h.status==="idle"?h:{...h,status:"idle"});return}let f=!1,w=null,x=null,p=0,j=null,_=null;const b=new Set,R=[],H=512,y=new Map,c=`${da()}/api/v1/projects/${t}/lab/stream`,g=h=>{const E=h.split(/\n/);let C="",d="";const V=[];for(const B of E)if(B){if(B.startsWith("event:")){C=B.slice(6).trim();continue}if(B.startsWith("data:")){V.push(B.slice(5).trimStart());continue}B.startsWith("id:")&&(d=B.slice(3).trim())}return V.length===0?null:{event:C||"message",data:V.join(`
13
+ `),id:d||void 0}},K=(h,E)=>{const C=(E||"").trim();if(!C)return!1;const d=(h||"").trim().toLowerCase(),V=d?`${d}|${C}`:C;if(b.has(V))return!0;if(b.add(V),R.push(V),R.length>H){const B=R.shift();B&&b.delete(B)}return!1},G=()=>{if(y.size===0)return;const h=Array.from(y.values());y.clear(),h.forEach(E=>{s.invalidateQueries({queryKey:E.queryKey,exact:E.exact})})},Q=h=>{h.forEach(E=>{const C=`${E.exact?1:0}:${JSON.stringify(E.queryKey)}`;y.set(C,E)}),!x&&(x=window.setTimeout(()=>{x=null,G()},Za))},$=(h,E)=>{if(h==="lab.ping")return;n(z=>({...z,lastEventAt:Date.now()}));let C=null;try{const z=JSON.parse(E||"{}");C=Pe(z)}catch{C=null}const d=os(C),V=Pe(C?.data),B=ls(V?.quest_ids),O=us(h,t,d);Q(O),B.forEach(z=>{Q(we(t,z))});const X=ds(h,t,C);X&&ot(X)},Y=()=>{if(f)return;w&&window.clearTimeout(w);const h=Math.min(p,4),E=Math.min(1e4,1e3*2**h),C=Math.min(250,p*50);n(d=>d.status==="connecting"||d.status==="open"?{...d,status:"reconnecting"}:d),w=window.setTimeout(A,E+C)},A=()=>{if(f)return;_&&_.abort(),_=new AbortController;const h=_;n(E=>({...E,status:p>0?"reconnecting":"connecting"})),(async()=>{try{const E=typeof window<"u"?window.localStorage.getItem("ds_access_token"):null;if(!E)return;const C={Accept:"text/event-stream",Authorization:`Bearer ${E}`};j&&(C["Last-Event-ID"]=j);const d=await fetch(c,{method:"GET",headers:C,signal:h.signal});if(f||h.signal.aborted)return;if(d.status===401){typeof window<"u"&&(window.localStorage.removeItem("ds_access_token"),ma("session_expired"));return}if(!d.ok)throw new Error(`HTTP ${d.status}: ${d.statusText}`);p=0,n(z=>({...z,status:"open"})),Q(Qt(t));const V=d.body?.getReader();if(!V)throw new Error("No response body");const B=new TextDecoder;let O="";for(;!(f||h.signal.aborted);){const{done:z,value:de}=await V.read();if(z||f||h.signal.aborted)break;O+=B.decode(de,{stream:!0}),O.includes("\r")&&(O=O.replace(/\r\n/g,`
14
+ `));let D=O.indexOf(`
15
+
16
+ `);for(;D!==-1;){const ce=O.slice(0,D);O=O.slice(D+2);const U=ce.replace(/\r\n/g,`
17
+ `).trim(),J=g(U);if(J?.id&&(j=J.id,K(J.event,J.id))){D=O.indexOf(`
18
+
19
+ `);continue}J&&!f&&!h.signal.aborted&&$(J.event,J.data),D=O.indexOf(`
20
+
21
+ `)}}const X=O.replace(/\r\n/g,`
22
+ `).trim();if(X&&!f&&!h.signal.aborted){const z=g(X);if(z?.id&&(j=z.id,K(z.event,z.id)))return;z&&$(z.event,z.data)}!f&&!h.signal.aborted&&(p+=1,Y())}catch{if(f||h.signal.aborted)return;n(E=>({...E,status:"error"})),p+=1,Y()}})()};return A(),()=>{f=!0,G(),w&&window.clearTimeout(w),x&&window.clearTimeout(x),_&&_.abort()}},[a,r,t,s]),u}function it({liveEnabled:t,streamStatus:a,fastMs:s,slowMs:u}){return t?a==="open"?u:s:!1}function vs({projectId:t,readOnly:a,lockedQuestId:s=null,immersiveLockedQuest:u=!1,onRefresh:n,onOpenStageSelection:r}){const f=ut(),w=Ue(M=>M.setActiveQuest),x=Ue(M=>M.activeQuestId),p=Ue(M=>M.clearSelections),j=st(M=>M.servers),_=st(M=>M.loadServers),b=st(M=>M.projectId),R=va(),H=i.useMemo(()=>{const M=R?.context?.customData,te=typeof M?.projectId=="string"?M.projectId:null,he=!te||te===t;return R?.pluginId===ba.LAB&&he},[R,t]);i.useEffect(()=>{t&&b!==t&&_(t)},[b,_,t]);const y=i.useMemo(()=>j.filter(M=>M.status!=="offline"&&M.status!=="error"),[j]),c=j.length===0?"unbound":y.length>0?"online":"offline",g=!0,[K,G]=i.useState(!0);i.useEffect(()=>{const M=()=>{G(typeof document<"u"&&document.visibilityState==="visible")};return M(),document.addEventListener("visibilitychange",M),()=>document.removeEventListener("visibilitychange",M)},[]);const Q=3e4,$=!!(t&&H&&K),Y=!!(t&&K),A=5e3,h=1e4,E=1e4,C=ms({projectId:t,enabled:Y}),d=C?.status??"idle",V=it({liveEnabled:$,streamStatus:d,fastMs:A,slowMs:A}),B=it({liveEnabled:$,streamStatus:d,fastMs:h,slowMs:3e4}),O=it({liveEnabled:$,streamStatus:d,fastMs:E,slowMs:3e4}),X=i.useRef($);i.useEffect(()=>{const M=X.current;X.current=$,!(!t||!$||M)&&(f.invalidateQueries({queryKey:["lab-agents",t]}),f.invalidateQueries({queryKey:["lab-quests",t]}),f.invalidateQueries({queryKey:["lab-overview",t]}))},[$,t,f]);const z=le({queryKey:["lab-templates",t],queryFn:()=>ha(t),enabled:!!t,staleTime:Q}),de=le({queryKey:["lab-agents",t],queryFn:()=>fa(t,{silent:!0}),enabled:!!t,staleTime:Q,refetchInterval:V}),D=le({queryKey:["lab-quests",t],queryFn:()=>xa(t,{silent:!0}),enabled:!!t,staleTime:Q,refetchInterval:B}),ce=le({queryKey:["lab-overview",t],queryFn:()=>pa(t,{silent:!0}),staleTime:Q,refetchInterval:O}),U=le({queryKey:["project",t],queryFn:()=>ga(t),enabled:!!t,staleTime:Q}),J=z.data?.items??[],Ne=de.data?.items??[],ee=D.data?.items??[],me=ce.data??{},Z=i.useMemo(()=>ee.length===0?null:ee.reduce((te,he)=>{const fe=te?.created_at?new Date(te.created_at).getTime():0;return(he?.created_at?new Date(he.created_at).getTime():0)>fe?he:te},ee[0])?.quest_id??null,[ee]),Se=U.data?.name??null;return i.useEffect(()=>{if(s){w(s);return}x||!Z||w(Z)},[x,Z,s,w]),i.useEffect(()=>{p()},[p,t]),e.jsx("div",{className:"lab-root flex h-full min-h-0 flex-col","data-activity":K?"active":"inactive",children:e.jsx("div",{className:ne("lab-panel h-full min-h-0 flex-1 overflow-hidden"),children:e.jsx(Ja,{projectId:t,readOnly:g,onRefresh:n,onOpenStageSelection:r,cliStatus:c,labStream:C,projectName:Se,templates:J,agents:Ne,quests:ee,overview:me,isLoading:{agents:de.isLoading,quests:D.isLoading,overview:ce.isLoading},lockedQuestId:s,immersiveLockedQuest:u})})})}const bs="ds:lab:focus";function ys({context:t,setTitle:a}){const{t:s}=ke("lab"),u=ya("lab.use"),n=typeof t.customData?.projectId=="string"?t.customData.projectId:null,r=!!t.customData?.readOnly,f=t.customData?.focusType==="agent"||t.customData?.focusType==="quest"||t.customData?.focusType==="quest-branch"||t.customData?.focusType==="quest-event"||t.customData?.focusType==="overview"?t.customData.focusType:null,w=typeof t.customData?.focusId=="string"?t.customData.focusId:null,x=typeof t.customData?.branch=="string"?t.customData.branch:null,p=typeof t.customData?.eventId=="string"?t.customData.eventId:null;return i.useEffect(()=>{a(s("plugin_home_title",void 0,"Home"))},[a,s]),i.useEffect(()=>{!n||!f||!w&&f!=="overview"||window.dispatchEvent(new CustomEvent(bs,{detail:{projectId:n,focusType:f,focusId:w,branch:x,eventId:p}}))},[x,p,w,f,n]),n?!u.isEntitlementLoading&&!u.isMaxEntitled?e.jsx("div",{className:"flex h-full items-center justify-center rounded-2xl border border-[var(--soft-border)] bg-[var(--soft-bg-surface)]",children:e.jsxs("div",{className:"px-6 text-center",children:[e.jsx("div",{className:"text-sm font-medium text-[var(--soft-text-primary)]",children:s("plugin_plan_access_required",void 0,"Plan access required")}),e.jsx("div",{className:"mt-1 text-xs text-[var(--soft-text-secondary)]",children:s("plugin_max_only_desc",void 0,"Lab is currently available for Max users only.")})]})}):e.jsx(vs,{projectId:n,readOnly:r}):e.jsx("div",{className:"flex h-full items-center justify-center rounded-2xl border border-[var(--soft-border)] bg-[var(--soft-bg-surface)]",children:e.jsx("div",{className:"text-sm text-[var(--soft-text-secondary)]",children:s("plugin_project_not_found",void 0,"Project not found.")})})}export{ys as default};
@@ -0,0 +1,25 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/plugin-monaco-C8UgLomw.js","assets/plugin-terminal-MXFIPun8.js","assets/plugin-notebook-HbW2K-1c.js"])))=>i.map(i=>d[i]);
2
+ import{y as ur,x as fr,u as mr,a as nt,f as br,t as hr,U as st,V as xr,K as gr,W as pr,Y as Ee,_ as lt,Z as wr,$ as vr,a0 as kr,j as n,b as F,h as yr,a1 as _r,L as ge,S as Nr,a2 as jr,T as Et,a3 as Sr,a4 as Lr,a5 as Cr,a6 as Ar,g as Ir}from"./index-CBNVuWcP.js";import{r as s}from"./plugin-monaco-C8UgLomw.js";import{P as Rr}from"./project-sync-C9IdzdZW.js";import{c as Er}from"./monaco-CiHMMNH_.js";import{P as ot,a as Fr,b as Pr,c as Mr,Z as D,d as Br}from"./PdfLoader-eWBONbQP.js";import{Z as $r,a as Tr}from"./zoom-out-E_gaeAxL.js";import"./plugin-notebook-HbW2K-1c.js";import"./plugin-terminal-MXFIPun8.js";import"./plugin-pdf-CR8hgQBV.js";/**
3
+ * @license lucide-react v0.511.0 - ISC
4
+ *
5
+ * This source code is licensed under the ISC license.
6
+ * See the LICENSE file in the root directory of this source tree.
7
+ */const Or=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8",key:"7n84p3"}]],Ur=ur("at-sign",Or),Dr=Ir(()=>lt(()=>import("./plugin-monaco-C8UgLomw.js").then(u=>u.i),__vite__mapDeps([0,1])),{});Er();function Wr(){const[u,h]=s.useState(()=>typeof document>"u"?!1:document.documentElement.classList.contains("dark"));return s.useEffect(()=>{const f=document.documentElement,R=new MutationObserver(()=>{h(f.classList.contains("dark"))});return R.observe(f,{attributes:!0,attributeFilter:["class"]}),()=>R.disconnect()},[]),u}function Fe(u){return[u.resourcePath||u.resourceName||"",u.line||0,u.severity,u.message].join("::")}const Ft=(u,h)=>Array.isArray(h)&&h.length>0?h.map(f=>({path:f.file??null,line:typeof f.line=="number"?f.line:null,message:f.message,severity:f.severity==="warning"?"warning":"error"})):Array.isArray(u)?u:[],zr=["pdflatex","xelatex","lualatex"],at=[{id:"article",labelKey:"bib_snippet_article",snippet:`@article{key,
8
+ title = {},
9
+ author = {},
10
+ journal = {},
11
+ year = {},
12
+ }
13
+ `},{id:"inproceedings",labelKey:"bib_snippet_inproceedings",snippet:`@inproceedings{key,
14
+ title = {},
15
+ author = {},
16
+ booktitle = {},
17
+ year = {},
18
+ }
19
+ `},{id:"misc",labelKey:"bib_snippet_misc",snippet:`@misc{key,
20
+ title = {},
21
+ author = {},
22
+ year = {},
23
+ note = {},
24
+ }
25
+ `}];function Pe(u){return u==="xelatex"||u==="lualatex"?u:"pdflatex"}function it(u){return String(u||"").trim().replace(/\\/g,"/").replace(/^\.\/+/,"").replace(/^\/+/,"").toLowerCase()}function qr(u,h){const f=[],R=String(u||""),E=/@([a-zA-Z]+)\s*\{\s*([^,\s]+)\s*,([\s\S]*?)\n\}/g;let c=null;for(;c=E.exec(R);){const x=c[3]||"",C=x.match(/title\s*=\s*[\{"']([^}"']+)/i)?.[1]?.trim(),O=x.match(/author\s*=\s*[\{"']([^}"']+)/i)?.[1]?.trim();f.push({key:c[2].trim(),title:C,author:O,sourceFile:h})}return f}function Vr(u,h){const f=[],R=String(u||""),E=/\\label\{([^}]+)\}/g;let c=null;for(;c=E.exec(R);)f.push({key:c[1].trim(),sourceFile:h});return f}function Pt(u,h){const f=it(h);if(!f)return null;const R=u.find(C=>it(C.name)===f);if(R)return R.id;const E=f.split("/").filter(Boolean).pop();if(!E)return null;const c=u.find(C=>it(C.name).endsWith(`/${E}`));return c?c.id:u.find(C=>C.name.toLowerCase()===E)?.id??null}function Kr({pdfDocument:u,zoomFactor:h,highlights:f,onPageWidth:R}){s.useEffect(()=>{let x=!1;return u.getPage(1).then(C=>{if(x)return;const O=C.getViewport({scale:1});O?.width&&R(O.width)}).catch(()=>{x||R(ot.A4_WIDTH)}),()=>{x=!0}},[R,u]);const E=Number.isFinite(h)&&h>0?h:1,c=Math.abs(E-1)<.001?"page-width":`page-width:${E}`;return n.jsx(Br,{pdfDocument:u,pdfScaleValue:c,highlights:f,highlightTransform:()=>n.jsx(n.Fragment,{}),onScrollChange:()=>{},scrollRef:()=>{},onSelectionFinished:(x,C,O,a)=>null,enableAreaSelection:()=>!1})}function nn({context:u,tabId:h,setDirty:f,setTitle:R}){const E=u.customData??{},c=E.projectId??void 0,x=E.latexFolderId??u.resourceId??void 0,C=!!E.readOnly,O=fr(e=>e.user),{t:a,language:Mt}=mr("latex"),ct=nt(e=>e.updateTabState),J=nt(e=>e.setActiveIssue),[Bt,Me]=s.useState(null),$t=Wr(),dt=br(e=>e.updateFileMeta),[_,Tt]=s.useState([]),Ot=E.openFileId??E.mainFileId??null,[d,Be]=s.useState(Ot),[P,pe]=s.useState("main.tex"),[Ut,ut]=s.useState(""),[we,ve]=s.useState("idle"),[K,ke]=s.useState("idle"),[Dt,$e]=s.useState(null),[U,G]=s.useState(!1),[W,Te]=s.useState(null),[p,Q]=s.useState("idle"),[Wt,oe]=s.useState(null),[M,ye]=s.useState([]),[ce,_e]=s.useState("pdflatex"),[ft,Oe]=s.useState(null),[Z,zt]=s.useState(null),[Ne,Ue]=s.useState(null),[Y,mt]=s.useState(1),[De,qt]=s.useState(ot.A4_WIDTH),[We,Vt]=s.useState(0),[ze,Kt]=s.useState(.58),[qe,bt]=s.useState(!1),[ee,Zt]=s.useState(!1),[te,je]=s.useState(!1),[ht,Ve]=s.useState(!1),[de,re]=s.useState(""),[ue,Ke]=s.useState([]),[fe,Ze]=s.useState([]),Ht=s.useMemo(()=>[],[]),He=s.useRef(""),ne=s.useRef(null),H=s.useRef(null),Xe=s.useRef(null),xt=s.useRef(""),Se=s.useRef([]),X=s.useRef(null),z=s.useRef(null),me=s.useRef(!1),gt=s.useRef(0),Je=s.useRef(!1),[Ge,Xt]=s.useState(0),se=s.useRef(null),pt=s.useRef(null),Qe=s.useRef(null),wt=s.useRef(null),be=s.useRef(null),Ye=s.useRef(null),vt=s.useRef([]),kt=s.useRef([]),Le=s.useRef([]),w=C||Bt===!1,yt="user",_t=hr(),Ce=P.toLowerCase().endsWith(".bib");s.useEffect(()=>{const e=_.find(t=>t.id===d)??_.find(t=>t.name===P)??null;ct(h,{contentKind:"latex",documentMode:"source",resourceName:e?.name||P||u.resourceName||"main.tex",resourcePath:e?.path?st(e.path):void 0,isReadOnly:w,compileState:p==="queued"||p==="running"?"compiling":K==="saving"?"saving":p==="error"?"error":"idle",diagnostics:{errors:M.filter(t=>t.severity!=="warning").length,warnings:M.filter(t=>t.severity==="warning").length}})},[d,P,M,p,u.resourceName,w,_,K,h,ct]),s.useEffect(()=>{R(u.resourceName||a("title"))},[u.resourceName,R,a]),s.useEffect(()=>{if(!c)return;if(C){Me(null);return}let e=!1;return(async()=>{try{const t=await xr(c);if(e)return;const r=String(t?.role??"");Me(r==="owner"||r==="admin"||r==="editor")}catch{if(e)return;Me(null)}})(),()=>{e=!0}},[c,C]),s.useEffect(()=>{if(!c){Oe(null);return}let e=!1;return gr.session(c).then(t=>{if(e)return;const r=t?.snapshot,i=typeof r?.current_workspace_branch=="string"&&r.current_workspace_branch.trim()?r.current_workspace_branch.trim():typeof r?.branch=="string"&&r.branch.trim()?r.branch.trim():null;Oe(i)}).catch(()=>{e||Oe(null)}),()=>{e=!0}},[c]),s.useEffect(()=>{if(!c||!x)return;let e=!1;return(async()=>{try{const t=await pr(c,x);if(e)return;const r=t.filter(i=>i.type==="file").map(i=>({id:i.id,name:i.name,path:i.path||void 0})).sort((i,l)=>i.name.localeCompare(l.name));if(Tt(r),d){const i=r.find(l=>l.id===d);i&&pe(i.name)}else{const i=r.find(l=>l.name.toLowerCase()==="main.tex")??r.find(l=>l.name.toLowerCase().endsWith(".tex"))??r[0];i&&(Be(i.id),pe(i.name))}}catch(t){console.error("[LatexPlugin] Failed to list files:",t),$e(t instanceof Error?t.message:a("load_files_failed"))}})(),()=>{e=!0}},[c,x]),s.useEffect(()=>{vt.current=ue},[ue]),s.useEffect(()=>{kt.current=fe},[fe]),s.useEffect(()=>()=>{Le.current.forEach(e=>{try{e?.dispose?.()}catch{}}),Le.current=[]},[]),s.useEffect(()=>{if(!c||_.length===0){Ke([]),Ze([]);return}let e=!1;const t=_.filter(r=>r.name.toLowerCase().endsWith(".bib")||r.name.toLowerCase().endsWith(".tex"));return(async()=>{try{const r=await Promise.all(t.map(async o=>{try{const N=await Ee(o.id);return{file:o,content:N}}catch{return{file:o,content:""}}}));if(e)return;const i=r.filter(o=>o.file.name.toLowerCase().endsWith(".bib")).flatMap(o=>qr(o.content,o.file.name)).sort((o,N)=>o.key.localeCompare(N.key)),l=r.filter(o=>o.file.name.toLowerCase().endsWith(".tex")).flatMap(o=>Vr(o.content,o.file.name)).sort((o,N)=>o.key.localeCompare(N.key));Ke(i),Ze(l)}catch{e||(Ke([]),Ze([]))}})(),()=>{e=!0}},[_,c]),s.useEffect(()=>()=>{try{z.current?.()}finally{z.current=null}},[d]),s.useEffect(()=>{if(!c||!d)return;let e=!1,t=null;return ve("loading"),$e(null),(async()=>{const{Doc:r,applyUpdate:i,encodeStateVector:l,encodeStateAsUpdate:o,mergeUpdates:N}=await lt(async()=>{const{Doc:g,applyUpdate:v,encodeStateVector:V,encodeStateAsUpdate:Re,mergeUpdates:T}=await import("./plugin-notebook-HbW2K-1c.js").then(xe=>xe.a8);return{Doc:g,applyUpdate:v,encodeStateVector:V,encodeStateAsUpdate:Re,mergeUpdates:T}},__vite__mapDeps([2,0,1])),S=new r,A=S.getText("content");if(ne.current=S,H.current=A,!_t){const g=await Ee(d);S.transact(()=>{const V=A.length||0;V&&A.delete(0,V),g&&A.insert(0,g)},"ds-local-seed");const v=A.toString();ut(v),He.current=v,G(!1),f(!1),ve("ready"),t=()=>{try{z.current?.()}finally{z.current=null,ne.current===S&&(ne.current=null),H.current===A&&(H.current=null)}};return}const j=new Rr(c,{authMode:yt,docKind:"latex"});Xe.current=j,await j.connect();const m=`ds-remote:${c}:${d}:${Date.now()}`;xt.current=m;const b=await j.loadDoc(d,l(S));if(b?.missing&&i(S,b.missing,m),Je.current){const g=await Ee(d);if(S.transact(()=>{const v=A.length||0;v&&A.delete(0,v),g&&A.insert(0,g)},"ds-reset"),!w){const v=o(S);await j.pushDocUpdate(d,v)}Je.current=!1}if(!b){const g=await Ee(d);if(S.transact(()=>{A.insert(0,g)},"ds-seed"),!w){const v=o(S);await j.pushDocUpdate(d,v)}}const L=j.onDocUpdate(g=>{g.docId===d&&i(S,g.update,m)}),k=j.onDocReset(g=>{if(g.docId!==d)return;const v=Number(g.timestamp||0);v&&v===gt.current||(gt.current=v||Date.now(),!e&&(Je.current=!0,Xt(V=>V+1)))}),B=()=>{X.current!=null&&window.clearTimeout(X.current),X.current=window.setTimeout(async()=>{X.current=null;const g=Se.current;if(g.length){Se.current=[];try{const v=g.length===1?g[0]:N(g);await j.pushDocUpdate(d,v)}catch(v){console.error("[LatexPlugin] Failed to push update:",v)}}},300)},y=(g,v)=>{v!==m&&(w||(Se.current.push(g),B()))};S.on("update",y);let I=null,$=null,le=null,Ie=null;if(!w)try{const{Awareness:g,encodeAwarenessUpdate:v,applyAwarenessUpdate:V}=await lt(async()=>{const{Awareness:T,encodeAwarenessUpdate:xe,applyAwarenessUpdate:tt}=await import("./plugin-notebook-HbW2K-1c.js").then(rt=>rt.a9);return{Awareness:T,encodeAwarenessUpdate:xe,applyAwarenessUpdate:tt}},__vite__mapDeps([2,0,1]));I=new g(S),I.setLocalStateField("user",{id:O?.id??null,name:O?.username??"User"}),await j.joinAwareness(d);const Re=`ds-awareness:${c}:${d}:${Date.now()}`;$=j.onAwarenessUpdate(d,T=>{V(I,T,Re)}),le=j.onAwarenessCollect(d,()=>{const T=v(I,[I.clientID]);j.broadcastAwareness(d,T)}),Ie=(T,xe)=>{if(xe===Re)return;const tt=[...T?.added??[],...T?.updated??[],...T?.removed??[]],rt=v(I,tt);j.broadcastAwareness(d,rt)},I.on("change",Ie),j.requestAwarenesses(d)}catch(g){console.warn("[LatexPlugin] Awareness init failed:",g)}const Rt=A.toString();ut(Rt),He.current=Rt,G(!1),f(!1),ve("ready"),t=()=>{try{try{z.current?.()}finally{z.current=null}L?.(),k?.();try{S.off("update",y)}catch{}if(X.current!=null&&(window.clearTimeout(X.current),X.current=null),Se.current=[],$&&$(),le&&le(),I&&Ie)try{I.off("change",Ie)}catch{}if(!w)try{j.leaveAwareness(d)}catch{}}finally{try{j.disconnect()}catch{}Xe.current===j&&(Xe.current=null),ne.current===S&&(ne.current=null),H.current===A&&(H.current=null)}}})().catch(r=>{console.error("[LatexPlugin] Sync init failed:",r),!e&&(ve("error"),$e(r instanceof Error?r.message:a("collaboration_failed")))}),()=>{e=!0,t?.()}},[d,_t,w,c,Ge,f,yt,a,O?.id,O?.username]);const Nt=s.useCallback(e=>{const t=be.current;if(!t)return!1;const r=t.getModel?.();if(!r)return!1;const i=Math.max(1,Number(r.getLineCount?.()??1)),l=Math.min(Math.max(1,Math.round(e||1)),i);return t.revealLineInCenter?.(l),t.setPosition?.({lineNumber:l,column:1}),t.setSelection?.({startLineNumber:l,startColumn:1,endLineNumber:l,endColumn:Number(r.getLineMaxColumn?.(l)??1)}),t.focus?.(),!0},[]),ae=s.useCallback(()=>{const e=Ye.current;e&&(e.fileId&&e.fileId!==d||Nt(e.line)&&(Ye.current=null))},[d,Nt]),q=s.useCallback(e=>{const t=be.current;if(!t||w)return;const r=t.getSelection?.();r&&(t.executeEdits?.("ds-latex-assist",[{range:r,text:e,forceMoveMarkers:!0}]),t.focus?.(),G(!0),f(!0))},[w,f]),Jt=s.useCallback((e,t="\\cite")=>{const r=be.current,i=r?.getModel?.(),l=r?.getPosition?.();if(!r||!i||!l){q(`${t}{${e.key}}`);return}const o=i.getValueInRange({startLineNumber:l.lineNumber,startColumn:1,endLineNumber:l.lineNumber,endColumn:l.column}),N=/\\(?:cite|citet|citep|autocite|parencite)\{[^}]*$/i.test(o);q(N?e.key:`${t}{${e.key}}`),je(!1),re("")},[q]),Gt=s.useCallback((e,t="\\ref")=>{const r=be.current,i=r?.getModel?.(),l=r?.getPosition?.();if(!r||!i||!l){q(`${t}{${e.key}}`);return}const o=i.getValueInRange({startLineNumber:l.lineNumber,startColumn:1,endLineNumber:l.lineNumber,endColumn:l.column}),N=/\\(?:ref|eqref)\{[^}]*$/i.test(o);q(N?e.key:`${t}{${e.key}}`),je(!1),re("")},[q]),Qt=s.useCallback(e=>{q(e),Ve(!1),re("")},[q]),jt=s.useMemo(()=>{const e=de.trim().toLowerCase();return e?ue.filter(t=>[t.key,t.title,t.author,t.sourceFile].some(r=>String(r||"").toLowerCase().includes(e))).slice(0,12):ue.slice(0,12)},[de,ue]),St=s.useMemo(()=>{const e=de.trim().toLowerCase();return e?fe.filter(t=>[t.key,t.sourceFile].some(r=>String(r||"").toLowerCase().includes(e))).slice(0,10):fe.slice(0,10)},[de,fe]),Yt=te||ht,er=s.useCallback((e,t)=>{be.current=e;const r=H.current,i=ne.current,l=xt.current;if(!r||!i)return;const o=e.getModel?.();if(!o)return;const N=m=>{(t.languages.getLanguages?.()||[]).some(L=>L.id===m)||t.languages.register({id:m})};N("latex-ds"),N("bibtex-ds"),t.editor.setModelLanguage(o,Ce?"bibtex-ds":"latex-ds"),Le.current.forEach(m=>{try{m?.dispose?.()}catch{}}),Le.current=[t.languages.registerCompletionItemProvider("latex-ds",{triggerCharacters:["\\","{"],provideCompletionItems:(m,b)=>{const L=m.getValueInRange({startLineNumber:b.lineNumber,startColumn:1,endLineNumber:b.lineNumber,endColumn:b.column}),k=m.getWordUntilPosition(b),B=new t.Range(b.lineNumber,k.startColumn,b.lineNumber,k.endColumn);return/\\(?:cite|citet|citep|autocite|parencite)\{[^}]*$/i.test(L)?{suggestions:vt.current.slice(0,40).map(y=>({label:y.key,kind:t.languages.CompletionItemKind.Reference,insertText:y.key,detail:y.title||y.author||y.sourceFile,documentation:[y.author,y.title].filter(Boolean).join(" · "),range:B}))}:/\\(?:ref|eqref)\{[^}]*$/i.test(L)?{suggestions:kt.current.slice(0,40).map(y=>({label:y.key,kind:t.languages.CompletionItemKind.Reference,insertText:y.key,detail:y.sourceFile,range:B}))}:{suggestions:[]}}}),t.languages.registerCompletionItemProvider("bibtex-ds",{triggerCharacters:["@"],provideCompletionItems:(m,b)=>{const L=new t.Range(b.lineNumber,b.column,b.lineNumber,b.column);return{suggestions:at.map(k=>({label:k.id,kind:t.languages.CompletionItemKind.Snippet,insertText:k.snippet,insertTextRules:t.languages.CompletionItemInsertTextRule.InsertAsSnippet,documentation:a(k.labelKey),range:L}))}}})],z.current?.(),me.current=!0;try{o.setValue(r.toString())}finally{me.current=!1}const S=m=>{if(!Array.isArray(m)||m.length===0)return;const b=[];let L=0;for(const k of m){const B=typeof k?.retain=="number"?k.retain:0;B&&(L+=B);const y=typeof k?.insert=="string"?k.insert:null;if(y!=null){const $=o.getPositionAt(L);b.push({range:new t.Range($.lineNumber,$.column,$.lineNumber,$.column),text:y,forceMoveMarkers:!0}),L+=y.length}const I=typeof k?.delete=="number"?k.delete:0;if(I){const $=o.getPositionAt(L),le=o.getPositionAt(L+I);b.push({range:new t.Range($.lineNumber,$.column,le.lineNumber,le.column),text:"",forceMoveMarkers:!0})}}if(b.length){me.current=!0;try{o.applyEdits(b)}finally{me.current=!1}}},A=m=>{m?.transaction?.origin===l&&(S(m.delta??[]),G(!0))};r.observe(A);const j=o.onDidChangeContent(m=>{if(me.current||w)return;const b=Array.isArray(m?.changes)?m.changes:[];b.length&&(i.transact(()=>{const L=[...b].sort((k,B)=>(B.rangeOffset??0)-(k.rangeOffset??0));for(const k of L){const B=Number(k.rangeOffset??0),y=Number(k.rangeLength??0),I=String(k.text??"");y&&r.delete(B,y),I&&r.insert(B,I)}},"ds-monaco"),G(!0))});z.current=()=>{try{j?.dispose?.()}catch{}try{r.unobserve(A)}catch{}},window.requestAnimationFrame(()=>{ae()})},[w,ae,Ce,f,a]);s.useEffect(()=>{we==="ready"&&ae()},[d,ae,Ge,we]);const et=s.useCallback(async()=>{if(!d||w)return!1;const e=H.current;if(!e)return!1;try{ke("saving");const t=String(e.toString?.()??""),r=await wr(d,t);return He.current=t,ke("idle"),G(!1),f(!1),r?.updated_at&&dt(d,{updatedAt:r.updated_at,size:typeof r.size=="number"?r.size:void 0,mimeType:r.mime_type}),!0}catch(t){return console.error("[LatexPlugin] Save failed:",t),ke("error"),window.setTimeout(()=>ke("idle"),1400),!1}},[d,w,f,dt]),tr=s.useCallback(async e=>{if(!(!c||!x)&&!C&&!(U&&!w&&!await et()))try{oe(null),ye([]),Ue(null),Q("queued");const t=await vr(c,x,{compiler:ce,auto:!!e?.auto,stop_on_first_error:!1});Te(t.build_id),_e(Pe(t.compiler)),Q(t.status??"queued")}catch(t){console.error("[LatexPlugin] Compile failed:",t),oe(t instanceof Error?t.message:a("compile_request_failed")),Q("error")}},[ce,w,U,x,c,et,a,C]);s.useEffect(()=>{if(!c||!x)return;const e=t=>{const r=t.detail;r&&(r.projectId!==c||r.folderId!==x||(r.buildId&&Te(r.buildId),Q(r.status??"queued"),oe(r.errorMessage??null),ye([]),Ue(null)))};return window.addEventListener("ds:latex-build",e),()=>{window.removeEventListener("ds:latex-build",e)}},[x,c]),s.useEffect(()=>{if(!c||!x||W)return;let e=!1;return(async()=>{try{const t=await kr(c,x,1);if(e)return;const r=t?.[0];r?.build_id&&(Te(r.build_id),_e(Pe(r.compiler)),Q(r.status??"idle"),oe(r.error_message??null),ye(Ft(r.errors,r.log_items)))}catch{}})(),()=>{e=!0}},[W,x,c]),s.useEffect(()=>{if(!c||!x||!W)return;let e=!1,t=null;const r=async()=>{try{const i=await Lr(c,x,W);if(e)return;if(_e(Pe(i.compiler)),Q(i.status),oe(i.error_message??null),ye(Ft(i.errors,i.log_items)),i.status==="success"&&i.pdf_ready&&pt.current!==W)try{const l=await Cr(c,x,W);if(e)return;const o=URL.createObjectURL(l);if(se.current)try{URL.revokeObjectURL(se.current)}catch{}se.current=o,zt(o),pt.current=W}catch(l){console.warn("[LatexPlugin] Failed to fetch PDF:",l)}if(i.status==="error"&&i.log_ready&&!Ne)try{const l=await Ar(c,x,W);if(e)return;Ue(l)}catch(l){console.warn("[LatexPlugin] Failed to fetch log:",l)}(i.status==="queued"||i.status==="running")&&(t=window.setTimeout(r,1e3))}catch{if(e)return;t=window.setTimeout(r,1500)}};return r(),()=>{e=!0,t!=null&&window.clearTimeout(t)}},[W,x,Ne,c]),s.useEffect(()=>()=>{if(se.current){try{URL.revokeObjectURL(se.current)}catch{}se.current=null}},[]),s.useEffect(()=>{f(U)},[U,f]),s.useEffect(()=>{if(typeof window>"u")return;const e=window.matchMedia("(min-width: 1024px)"),t=e,r=()=>Zt(e.matches);return r(),typeof e.addEventListener=="function"?(e.addEventListener("change",r),()=>e.removeEventListener("change",r)):(t.addListener?.(r),()=>t.removeListener?.(r))},[]),s.useEffect(()=>{const e=wt.current;if(!e)return;let t=null;const r=new ResizeObserver(i=>{const l=i[0];l&&(t!=null&&window.cancelAnimationFrame(t),t=window.requestAnimationFrame(()=>{Vt(l.contentRect.width)}))});return r.observe(e),()=>{t!=null&&window.cancelAnimationFrame(t),r.disconnect()}},[]);const rr=s.useMemo(()=>`${P?P.replace(/\.tex$/i,""):"document"}.pdf`,[P]),ie=s.useMemo(()=>M.filter(e=>e.severity==="warning"),[M]),nr=s.useMemo(()=>a(`compiler_${ce}`),[ce,a]),Lt=s.useMemo(()=>w?{label:a("status_read_only"),className:"border-black/10 bg-white/60 text-muted-foreground dark:bg-white/[0.04] dark:border-white/10"}:p==="queued"||p==="running"?{label:a("status_compiling"),className:"border-[#8FA3B8]/30 bg-[#8FA3B8]/10 text-[#52667a] dark:bg-[#8FA3B8]/12 dark:text-[#c8d4df]"}:K==="saving"?{label:a("status_saving"),className:"border-[#A6B0B6]/30 bg-[#A6B0B6]/12 text-[#5c666b] dark:bg-[#A6B0B6]/12 dark:text-[#d8dde0]"}:U?{label:a("status_unsaved"),className:"border-[#B7A59A]/30 bg-[#B7A59A]/12 text-[#7e695d] dark:bg-[#B7A59A]/12 dark:text-[#eadfd8]"}:p==="error"?{label:a("status_compile_failed"),className:"border-red-400/30 bg-red-50/80 text-red-600 dark:bg-red-500/10 dark:text-red-200"}:{label:a("status_saved"),className:"border-[#9AA79A]/30 bg-[#9AA79A]/12 text-[#5f6b5f] dark:bg-[#9AA79A]/12 dark:text-[#dbe4db]"},[p,w,U,K,a]),he=s.useCallback(e=>{const t=Pt(_,e.path)??d??_.find(N=>N.name.toLowerCase()==="main.tex")?.id??_[0]?.id??null,r=t?_.find(N=>N.id===t)??null:null,i=r?.name||e.path||P||"main.tex",l=r?.path?st(r.path):e.path?st(e.path):"",o=e.severity==="warning"?"warning":"error";return{kind:"latex_error",tabId:h,fileId:t||void 0,resourceId:t||void 0,resourcePath:l&&l!=="/FILES"?l:void 0,resourceName:i,line:typeof e.line=="number"?Math.max(1,Number(e.line||1)):void 0,message:e.message,severity:o,excerpt:e.path||e.line?`${e.path||i}${e.line?`:${e.line}`:""}`:void 0,createdAt:new Date().toISOString()}},[d,P,_,h]),Ae=s.useCallback(e=>{const t=he(e);return J(h,t),t},[he,J,h]);s.useEffect(()=>{if(p==="success"){J(h,null);return}if(M.length===0){p==="error"&&J(h,null);return}const e=M.find(l=>l.severity!=="warning")??M[0]??null;if(!e)return;const t=nt.getState().activeIssueByTabId[h],r=t?.kind==="latex_error"?M.find(l=>Fe(he(l))===Fe(t))??null:null,i=he(r??e);t&&Fe(t)===Fe(i)||J(h,i)},[M,he,p,J,h]);const Ct=s.useCallback(e=>{const r=Ae(e)?.fileId??Pt(_,e.path)??d??_.find(l=>l.name.toLowerCase()==="main.tex")?.id??_[0]?.id??null;if(!r)return;const i=_.find(l=>l.id===r);if(Ye.current={fileId:r,line:Math.max(1,Number(e.line||1))},i?.name&&i.name!==P&&pe(i.name),r!==d){Be(r);return}ae()},[d,P,_,ae,Ae]),At=s.useCallback(e=>{const t=Ae(e),r=e.severity==="warning"?a("warning_badge"):a("error_badge"),i=t?.line&&t.resourceName?`${t.resourceName}:${t.line}`:t?.resourceName||e.path||P||"main.tex",l=t?.resourcePath||t?.resourceName||e.path||P||"main.tex",o=typeof t?.line=="number"&&Number.isFinite(t.line)?String(Math.max(1,t.line)):a("issue_unknown_line"),N=a("issue_action_prompt",{severity:r,branch:ft||a("issue_unknown_branch"),file:l,line:o,location:i,message:e.message});window.dispatchEvent(new CustomEvent("ds:copilot:prefill",{detail:{text:N,focus:!0}}))},[P,ft,Ae,a]),It=s.useCallback((e,t,r)=>{const i=!!(e.path||e.line)&&!!(d||_.length),l=`${e.path??r}-${e.line??"0"}-${t}`,o=n.jsxs(n.Fragment,{children:[n.jsx("span",{className:F("px-1.5 py-0.5 rounded-full text-[10px] uppercase border",e.severity==="warning"?"text-amber-700 border-amber-400/40 bg-amber-50/70 dark:bg-amber-500/10":"text-red-600 border-red-400/40 bg-red-50/70 dark:bg-red-500/10"),children:e.severity==="warning"?a("warning_badge"):a("error_badge")}),n.jsxs("span",{className:"text-muted-foreground font-mono",children:[e.path||"main.tex",e.line?`:${e.line}`:""]}),n.jsx("span",{className:"text-muted-foreground break-words",children:e.message}),i?n.jsx("span",{className:"ml-auto shrink-0 text-[10px] text-muted-foreground/80",children:a("issue_hint_clickable")}):null]});return n.jsxs("div",{className:"flex items-start gap-2",children:[i?n.jsx("button",{type:"button",onClick:()=>Ct(e),className:"min-w-0 flex flex-1 items-start gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-black/5 dark:hover:bg-white/[0.04]",title:e.line?a("issue_jump_to_line",{line:e.line}):a("issue_jump_to_file",{file:e.path||"main.tex"}),children:o}):n.jsx("div",{className:"min-w-0 flex flex-1 items-start gap-2 px-2 py-1.5",children:o}),n.jsx("div",{className:"flex shrink-0 items-center gap-1 pt-1",children:n.jsx("button",{type:"button",onClick:()=>At(e),className:"rounded-md border border-black/10 dark:border-white/10 bg-white/70 dark:bg-white/[0.05] px-2 py-1 text-[11px] font-medium text-muted-foreground hover:bg-black/5 dark:hover:bg-white/[0.08]",title:a("issue_action_ask_deepscientist"),children:a("issue_action_ask_deepscientist")})})]},l)},[d,_,At,Ct,a]),sr=!Z||Y<=D[0],ar=!Z||Y>=D[D.length-1],ir=()=>{const e=D.findIndex(r=>r>=Y),t=e===-1?D.length-1:e;t<=0||mt(D[t-1])},lr=()=>{const e=D.findIndex(r=>r>=Y),t=e===-1?D.length-1:e;t>=D.length-1||mt(D[t+1])},or=s.useMemo(()=>{if(!We||!De)return 1;const e=Math.max(We-32,120);return Math.max(e/De,.2)},[We,De])*Y,cr=s.useCallback(e=>{qt(e||ot.A4_WIDTH)},[]),dr=s.useCallback(e=>{if(!ee||!Qe.current||e.button!==0)return;e.preventDefault();const r=Qe.current.getBoundingClientRect(),i=e.clientX,l=r.width*ze,o=360,S=Math.max(r.width-320,o),A=document.body.style.cursor,j=document.body.style.userSelect;document.body.style.cursor="col-resize",document.body.style.userSelect="none",bt(!0);let m=null;const b=k=>{const B=l+(k.clientX-i),I=Math.min(Math.max(B,o),S)/r.width;m!=null&&window.cancelAnimationFrame(m),m=window.requestAnimationFrame(()=>{Kt(I)})},L=()=>{m!=null&&window.cancelAnimationFrame(m),bt(!1),document.body.style.cursor=A,document.body.style.userSelect=j,window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",L)};window.addEventListener("pointermove",b),window.addEventListener("pointerup",L)},[ee,ze]);return n.jsx("div",{className:"h-full flex flex-col bg-white/70 dark:bg-black/30",children:n.jsxs("div",{ref:Qe,className:"flex-1 min-h-0 flex flex-col lg:flex-row",children:[n.jsxs("div",{className:F("min-h-0 flex flex-col min-w-0",ee?"lg:border-r-0":"border-b border-black/5 dark:border-white/10",qe?"transition-none":"transition-[flex-basis] duration-200 ease-out"),style:ee?{flexBasis:`${ze*100}%`,flexGrow:0,flexShrink:0}:void 0,children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2 px-3 py-2 border-b border-black/5 dark:border-white/10",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(yr,{className:"h-4 w-4 text-muted-foreground shrink-0"}),n.jsx("select",{className:F("h-8 rounded-lg px-2 text-sm bg-white/70 border border-black/10","dark:bg-white/[0.04] dark:border-white/10","min-w-[160px] max-w-[260px] truncate",w&&"opacity-70"),value:d??"",onChange:e=>{const t=e.target.value||null,r=_.find(i=>i.id===t);r&&pe(r.name),Be(t)},disabled:_.length===0,"aria-label":a("file_label"),title:P,children:_.map(e=>n.jsx("option",{value:e.id,children:e.name},e.id))})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-xs text-muted-foreground",children:a("compiler_label")}),n.jsx("select",{className:F("h-8 rounded-lg px-2 text-sm bg-white/70 border border-black/10","dark:bg-white/[0.04] dark:border-white/10","min-w-[122px]",p==="queued"||p==="running"?"opacity-70":""),value:ce,onChange:e=>_e(Pe(e.target.value)),disabled:p==="queued"||p==="running","aria-label":a("compiler_label"),title:nr,children:zr.map(e=>n.jsx("option",{value:e,children:a(`compiler_${e}`)},e))})]}),Ce?null:n.jsxs("button",{type:"button",onClick:()=>{je(e=>{const t=!e;return t&&Ve(!1),t||re(""),t})},className:F("h-8 px-3 rounded-lg text-sm border inline-flex items-center gap-2","bg-white/70 border-black/10 hover:bg-white/90","dark:bg-white/[0.04] dark:border-white/10 dark:hover:bg-white/[0.08]",te&&"border-[#8FA3B8]/28 bg-[#8FA3B8]/12 text-[#405267]"),"aria-label":a("assist_references"),title:a("assist_references"),children:[n.jsx(_r,{className:"h-4 w-4"}),a("assist_references")]}),Ce?n.jsxs("button",{type:"button",onClick:()=>{Ve(e=>{const t=!e;return t&&je(!1),t||re(""),t})},className:F("h-8 px-3 rounded-lg text-sm border inline-flex items-center gap-2","bg-white/70 border-black/10 hover:bg-white/90","dark:bg-white/[0.04] dark:border-white/10 dark:hover:bg-white/[0.08]",ht&&"border-[#A99EBE]/28 bg-[#A99EBE]/12 text-[#564f6a]"),"aria-label":a("assist_bibtex"),title:a("assist_bibtex"),children:[n.jsx(Ur,{className:"h-4 w-4"}),a("assist_bibtex")]}):null,n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[n.jsx("span",{className:F("text-xs px-2 py-0.5 rounded-full border",Lt.className),children:Lt.label}),n.jsx("button",{type:"button",onClick:et,disabled:w||K==="saving"||!U,className:F("h-8 px-3 rounded-lg text-sm font-medium border","bg-white/70 border-black/10 hover:bg-white/90","dark:bg-white/[0.04] dark:border-white/10 dark:hover:bg-white/[0.08]","disabled:opacity-50 disabled:cursor-not-allowed",U&&!w&&"border-black/20"),children:K==="saving"?n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(ge,{className:"h-4 w-4 animate-spin"}),a("button_saving")]}):n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(Nr,{className:"h-4 w-4"}),a("button_save")]})}),n.jsx("button",{type:"button",onClick:()=>void tr({auto:!1}),disabled:C||K==="saving"||p==="queued"||p==="running",className:F("h-8 px-3 rounded-lg text-sm font-medium border","bg-[#8FA3B8]/14 border-[#8FA3B8]/28 text-[#405267] hover:bg-[#8FA3B8]/20","dark:bg-[#8FA3B8]/14 dark:border-[#8FA3B8]/22 dark:text-[#dbe6ef] dark:hover:bg-[#8FA3B8]/20","disabled:opacity-50 disabled:cursor-not-allowed"),title:a(C?"compile_disabled_read_only":U&&!w?"button_save_and_compile":"button_compile"),children:p==="queued"||p==="running"?n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(ge,{className:"h-4 w-4 animate-spin"}),a("button_compiling")]}):n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(jr,{className:"h-4 w-4"}),a(U&&!w?"button_save_and_compile":"button_compile")]})})]})]}),Yt?n.jsxs("div",{className:"border-b border-black/5 dark:border-white/10 bg-black/[0.02] dark:bg-white/[0.02] px-3 py-3",children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-foreground",children:a(te?"assist_references_title":"assist_bibtex_title")}),n.jsx("div",{className:"text-xs text-muted-foreground",children:a(te?"assist_reference_hint":"assist_bibtex_hint")})]}),te?n.jsx("input",{value:de,onChange:e=>re(e.target.value),placeholder:a("assist_search_placeholder"),className:F("h-8 w-full rounded-lg border border-black/10 bg-white/80 px-3 text-sm","sm:w-[280px] dark:border-white/10 dark:bg-white/[0.05]")}):null]}),te?n.jsxs("div",{className:"mt-3 grid gap-3 lg:grid-cols-2",children:[n.jsxs("div",{className:"rounded-xl border border-black/5 bg-white/70 p-3 dark:border-white/10 dark:bg-white/[0.03]",children:[n.jsx("div",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:a("assist_citations")}),n.jsx("div",{className:"space-y-2",children:jt.length>0?jt.map(e=>n.jsxs("button",{type:"button",onClick:()=>Jt(e),className:"w-full rounded-lg border border-black/5 bg-black/[0.02] px-3 py-2 text-left hover:bg-black/[0.04] dark:border-white/10 dark:bg-white/[0.03] dark:hover:bg-white/[0.05]",title:e.title||e.key,children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("span",{className:"font-mono text-xs text-foreground",children:e.key}),n.jsx("span",{className:"text-[10px] text-muted-foreground",children:a("assist_insert_citation")})]}),e.title?n.jsx("div",{className:"mt-1 truncate text-xs text-muted-foreground",children:e.title}):null,n.jsx("div",{className:"mt-1 truncate text-[10px] text-muted-foreground/80",children:e.author||e.sourceFile})]},`${e.sourceFile}:${e.key}`)):n.jsx("div",{className:"rounded-lg border border-dashed border-black/10 px-3 py-4 text-xs text-muted-foreground dark:border-white/10",children:a("assist_empty_citations")})})]}),n.jsxs("div",{className:"rounded-xl border border-black/5 bg-white/70 p-3 dark:border-white/10 dark:bg-white/[0.03]",children:[n.jsx("div",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:a("assist_labels")}),n.jsx("div",{className:"space-y-2",children:St.length>0?St.map(e=>n.jsxs("button",{type:"button",onClick:()=>Gt(e),className:"w-full rounded-lg border border-black/5 bg-black/[0.02] px-3 py-2 text-left hover:bg-black/[0.04] dark:border-white/10 dark:bg-white/[0.03] dark:hover:bg-white/[0.05]",title:e.key,children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("span",{className:"font-mono text-xs text-foreground",children:e.key}),n.jsx("span",{className:"text-[10px] text-muted-foreground",children:a("assist_insert_reference")})]}),n.jsx("div",{className:"mt-1 truncate text-[10px] text-muted-foreground/80",children:e.sourceFile})]},`${e.sourceFile}:${e.key}`)):n.jsx("div",{className:"rounded-lg border border-dashed border-black/10 px-3 py-4 text-xs text-muted-foreground dark:border-white/10",children:a("assist_empty_labels")})})]})]}):n.jsx("div",{className:"mt-3 grid gap-2 md:grid-cols-3",children:at.length>0?at.map(e=>n.jsxs("button",{type:"button",onClick:()=>Qt(e.snippet),className:"rounded-xl border border-black/5 bg-white/70 px-3 py-3 text-left hover:bg-white/90 dark:border-white/10 dark:bg-white/[0.03] dark:hover:bg-white/[0.05]",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("span",{className:"font-mono text-sm text-foreground",children:["@",e.id]}),n.jsx("span",{className:"text-[10px] text-muted-foreground",children:a("assist_insert_snippet")})]}),n.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:a(e.labelKey)})]},e.id)):n.jsx("div",{className:"rounded-lg border border-dashed border-black/10 px-3 py-4 text-xs text-muted-foreground dark:border-white/10",children:a("assist_empty_bib")})})]}):null,n.jsx("div",{className:"flex-1 min-h-0",children:we==="loading"?n.jsxs("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:[n.jsx(ge,{className:"h-5 w-5 animate-spin mr-2"}),a("connecting")]}):we==="error"?n.jsx("div",{className:"h-full flex items-center justify-center text-sm text-red-600",children:Dt??a("load_files_failed")}):n.jsx(Dr,{defaultValue:Ut,language:"plaintext",theme:$t?"vs-dark":"light",onMount:(e,t)=>{try{er(e,t)}catch(r){console.error("[LatexPlugin] Failed to bind editor:",r)}},options:{readOnly:w,minimap:{enabled:!1},wordWrap:"on",fontSize:13,scrollBeyondLastLine:!1}},`${d??"latex"}:${Ge}`)}),p==="error"?n.jsxs("div",{className:"border-t border-black/5 dark:border-white/10 p-4 text-sm max-h-[35vh] overflow-auto",children:[n.jsxs("div",{className:"flex items-start gap-2 text-red-600",children:[n.jsx(Et,{className:"h-4 w-4 mt-0.5"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-medium",children:a("compile_failed_title")}),n.jsx("div",{className:"text-xs opacity-90 break-words",children:Wt??a("compile_failed_fallback")})]})]}),M.length>0?n.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[M.slice(0,12).map((e,t)=>It(e,t,"error")),M.length>12?n.jsx("div",{className:"text-muted-foreground",children:a("more_items",{count:M.length-12})}):null]}):null,Ne?n.jsx("pre",{className:"mt-3 text-xs whitespace-pre-wrap break-words text-muted-foreground max-h-[40vh] overflow-auto rounded-lg border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/[0.03] p-3",children:Ne.slice(0,8e3)}):null]}):null,p!=="error"&&ie.length>0?n.jsxs("div",{className:"border-t border-black/5 dark:border-white/10 p-4 text-sm max-h-[35vh] overflow-auto",children:[n.jsxs("div",{className:"flex items-start gap-2 text-amber-700",children:[n.jsx(Et,{className:"h-4 w-4 mt-0.5"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-medium",children:a("warnings_title")}),n.jsx("div",{className:"text-xs opacity-90 break-words",children:a("warnings_reported",{count:ie.length,suffix:Mt==="zh-CN"||ie.length===1?"":"s"})})]})]}),n.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[ie.slice(0,12).map((e,t)=>It(e,t,"warning")),ie.length>12?n.jsx("div",{className:"text-muted-foreground",children:a("more_items",{count:ie.length-12})}):null]})]}):null]}),ee?n.jsx("div",{className:F("hidden lg:flex w-3 relative items-stretch cursor-col-resize",qe?"bg-primary/10":"hover:bg-black/5 dark:hover:bg-white/[0.06]"),onPointerDown:dr,role:"separator","aria-orientation":"vertical","aria-label":a("resize_panels_aria"),children:n.jsx("div",{className:F("absolute inset-y-0 left-1/2 w-px",qe?"bg-primary/60":"bg-black/10 dark:bg-white/10")})}):null,n.jsx("div",{className:"min-h-0 flex flex-1 flex-col min-w-0",children:n.jsxs("div",{ref:wt,className:"relative flex-1 min-h-0 overflow-hidden",children:[n.jsxs("div",{className:F("absolute z-10 flex flex-col gap-2",ee?"left-3 top-1/2 -translate-y-1/2":"right-3 top-3","rounded-full border border-black/10 bg-white/80 p-1 shadow-sm","backdrop-blur dark:border-white/10 dark:bg-black/40"),onPointerDown:e=>e.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:ir,disabled:sr,className:F("h-7 w-7 rounded-full flex items-center justify-center","text-muted-foreground hover:text-foreground hover:bg-black/5","dark:hover:bg-white/[0.08]","disabled:opacity-40 disabled:cursor-not-allowed"),"aria-label":a("zoom_out"),title:a("zoom_out"),children:n.jsx($r,{className:"h-4 w-4"})}),n.jsx("div",{className:"text-[11px] font-medium text-muted-foreground text-center",children:Z?`${Math.round(or*100)}%`:"--"}),n.jsx("button",{type:"button",onClick:lr,disabled:ar,className:F("h-7 w-7 rounded-full flex items-center justify-center","text-muted-foreground hover:text-foreground hover:bg-black/5","dark:hover:bg-white/[0.08]","disabled:opacity-40 disabled:cursor-not-allowed"),"aria-label":a("zoom_in"),title:a("zoom_in"),children:n.jsx(Tr,{className:"h-4 w-4"})}),n.jsx("a",{href:Z??"#",download:rr,className:F("h-7 w-7 rounded-full text-xs font-medium border flex items-center justify-center","bg-white/70 border-black/10 hover:bg-white/90","dark:bg-white/[0.04] dark:border-white/10 dark:hover:bg-white/[0.08]",!Z&&"opacity-50 pointer-events-none"),title:a("download_pdf"),children:n.jsx(Sr,{className:"h-3.5 w-3.5"})})]}),Z?n.jsx(Fr,{url:Z,workerSrc:Mr,cMapUrl:Pr,cMapPacked:!0,beforeLoad:n.jsxs("div",{className:"flex-1 flex items-center justify-center text-sm text-muted-foreground",children:[n.jsx(ge,{className:"h-5 w-5 animate-spin mr-2"}),a("loading_pdf")]}),children:e=>n.jsx(Kr,{pdfDocument:e,zoomFactor:Y,highlights:Ht,onPageWidth:cr})}):p==="queued"||p==="running"?n.jsxs("div",{className:"flex-1 flex items-center justify-center text-sm text-muted-foreground",children:[n.jsx(ge,{className:"h-5 w-5 animate-spin mr-2"}),a("preview_compiling")]}):p==="error"?n.jsx("div",{className:"flex-1 flex items-center justify-center text-sm text-muted-foreground",children:a("preview_no_output")}):n.jsx("div",{className:"flex-1 flex items-center justify-center text-sm text-muted-foreground",children:a("preview_empty")})]})})]})})}export{nn as default};