cc-viewer 1.6.252 → 1.6.253
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.
- package/dist/assets/App-DbYqAJmv.js +1 -0
- package/dist/assets/{MdxEditorPanel-DW0ASwWk.js → MdxEditorPanel-CbV8qPts.js} +1 -1
- package/dist/assets/{Mobile-Blchmx6V.js → Mobile-B0WWR1YJ.js} +1 -1
- package/dist/assets/ProxyModal-D4xpZtn8.js +2 -0
- package/dist/assets/{ProxyModal-C_ap0Ysr.css → ProxyModal-I9RESzSM.css} +1 -1
- package/dist/assets/{index-mdguIo6K.js → index-eTBzi5lA.js} +2 -2
- package/dist/index.html +16 -3
- package/interceptor.js +1 -0
- package/lib/delta-reconstructor.js +2 -0
- package/package.json +1 -1
- package/server.js +32 -9
- package/dist/assets/App-Dy9iPmm1.js +0 -1
- package/dist/assets/ProxyModal-DD_ag2wy.js +0 -2
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-BeZMQR0-.js","assets/vendor-mdxeditor-C7DYEBoH.js","assets/vendor-antd-BeN8xqGk.js","assets/vendor-codemirror-2nbmPewy.js","assets/vendor-markdown-Bpu4AByL.js","assets/MdxEditorPanel-DW0ASwWk.js","assets/index-mdguIo6K.js","assets/index-sVTuiL15.css","assets/MdxEditorPanel-DvqnmX-m.css","assets/jszip.min-DKP-m-LG.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
var __defProp=Object.defineProperty,__publicField=(obj,key,value)=>((obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value)(obj,"symbol"!=typeof key?key+"":key,value);import{a as reactExports,I as Icon,b as _extends,F as Typography,V as RefIcon$d,i as Button,W as RefIcon$e,S as Spin,E as Empty,L as List,X as Card,Y as RefIcon$f,u as Space,Z as Popconfirm,j as RefIcon$g,s as staticMethods,M as Modal,$ as RefIcon$h,T as Tag,v as Input,R as React__default,N as Checkbox,P as Popover,o as RefIcon$i,a0 as ForwardTable,C as ConfigProvider,a1 as theme,A as Tooltip,w as RefIcon$j,c as ReactDOM,q as Collapse,D as Dropdown,g as getDefaultExportFromCjs,a2 as Divider,l as Select,K as Alert,k as RefIcon$k,m as Switch,n as Radio,a3 as RefIcon$l,a4 as RefIcon$m,a5 as RefIcon$n}from"./vendor-antd-BeN8xqGk.js";import{j as jsxRuntimeExports,E as EditorView,v as keymap,ac as showMinimap,ad as ReactCodeMirror,s as syntaxHighlighting,ae as sql$1,af as css$1,U as markdown$1,ag as yaml$1,ah as json$1,ai as xml$1,aj as php$1,ak as rust$1,al as go$1,am as cpp$1,an as java$1,ao as python$1,ap as javascript$2,H as HighlightStyle,t as tags}from"./vendor-codemirror-2nbmPewy.js";import{t,a as apiUrl,S as SettingsContext,g as getLang,d as isMobile,b as isPad,e as tc,i as isIOS,f as getClaudeConfigDir,h as handleStaleChunk}from"./index-mdguIo6K.js";import{_ as __vitePreload}from"./vendor-mdxeditor-C7DYEBoH.js";import{D as Dl,o,L,K as Ke,x as xr}from"./vendor-xterm-DckPrCx1.js";import{p as purify,g}from"./vendor-markdown-Bpu4AByL.js";import{r as requireCore}from"./vendor-highlight-IFTJ9nxW.js";import{q as qr}from"./vendor-virtuoso-COKXGpsa.js";var ApiOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M917.7 148.8l-42.4-42.4c-1.6-1.6-3.6-2.3-5.7-2.3s-4.1.8-5.7 2.3l-76.1 76.1a199.27 199.27 0 00-112.1-34.3c-51.2 0-102.4 19.5-141.5 58.6L432.3 308.7a8.03 8.03 0 000 11.3L704 591.7c1.6 1.6 3.6 2.3 5.7 2.3 2 0 4.1-.8 5.7-2.3l101.9-101.9c68.9-69 77-175.7 24.3-253.5l76.1-76.1c3.1-3.2 3.1-8.3 0-11.4zM769.1 441.7l-59.4 59.4-186.8-186.8 59.4-59.4c24.9-24.9 58.1-38.7 93.4-38.7 35.3 0 68.4 13.7 93.4 38.7 24.9 24.9 38.7 58.1 38.7 93.4 0 35.3-13.8 68.4-38.7 93.4zm-190.2 105a8.03 8.03 0 00-11.3 0L501 613.3 410.7 523l66.7-66.7c3.1-3.1 3.1-8.2 0-11.3L441 408.6a8.03 8.03 0 00-11.3 0L363 475.3l-43-43a7.85 7.85 0 00-5.7-2.3c-2 0-4.1.8-5.7 2.3L206.8 534.2c-68.9 69-77 175.7-24.3 253.5l-76.1 76.1a8.03 8.03 0 000 11.3l42.4 42.4c1.6 1.6 3.6 2.3 5.7 2.3s4.1-.8 5.7-2.3l76.1-76.1c33.7 22.9 72.9 34.3 112.1 34.3 51.2 0 102.4-19.5 141.5-58.6l101.9-101.9c3.1-3.1 3.1-8.2 0-11.3l-43-43 66.7-66.7c3.1-3.1 3.1-8.2 0-11.3l-36.6-36.2zM441.7 769.1a131.32 131.32 0 01-93.4 38.7c-35.3 0-68.4-13.7-93.4-38.7a131.32 131.32 0 01-38.7-93.4c0-35.3 13.7-68.4 38.7-93.4l59.4-59.4 186.8 186.8-59.4 59.4z"}}]},name:"api",theme:"outlined"},ApiOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:ApiOutlined$1}))},RefIcon$c=reactExports.forwardRef(ApiOutlined),ArrowUpOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M868 545.5L536.1 163a31.96 31.96 0 00-48.3 0L156 545.5a7.97 7.97 0 006 13.2h81c4.6 0 9-2 12.1-5.5L474 300.9V864c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V300.9l218.9 252.3c3 3.5 7.4 5.5 12.1 5.5h81c6.8 0 10.5-8 6-13.2z"}}]},name:"arrow-up",theme:"outlined"},ArrowUpOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:ArrowUpOutlined$1}))},RefIcon$b=reactExports.forwardRef(ArrowUpOutlined),BranchesOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M740 161c-61.8 0-112 50.2-112 112 0 50.1 33.1 92.6 78.5 106.9v95.9L320 602.4V318.1c44.2-15 76-56.9 76-106.1 0-61.8-50.2-112-112-112s-112 50.2-112 112c0 49.2 31.8 91 76 106.1V706c-44.2 15-76 56.9-76 106.1 0 61.8 50.2 112 112 112s112-50.2 112-112c0-49.2-31.8-91-76-106.1v-27.8l423.5-138.7a50.52 50.52 0 0034.9-48.2V378.2c42.9-15.8 73.6-57 73.6-105.2 0-61.8-50.2-112-112-112zm-504 51a48.01 48.01 0 0196 0 48.01 48.01 0 01-96 0zm96 600a48.01 48.01 0 01-96 0 48.01 48.01 0 0196 0zm408-491a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"}}]},name:"branches",theme:"outlined"},BranchesOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:BranchesOutlined$1}))},RefIcon$a=reactExports.forwardRef(BranchesOutlined),CameraOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M864 248H728l-32.4-90.8a32.07 32.07 0 00-30.2-21.2H358.6c-13.5 0-25.6 8.5-30.1 21.2L296 248H160c-44.2 0-80 35.8-80 80v456c0 44.2 35.8 80 80 80h704c44.2 0 80-35.8 80-80V328c0-44.2-35.8-80-80-80zm8 536c0 4.4-3.6 8-8 8H160c-4.4 0-8-3.6-8-8V328c0-4.4 3.6-8 8-8h186.7l17.1-47.8 22.9-64.2h250.5l22.9 64.2 17.1 47.8H864c4.4 0 8 3.6 8 8v456zM512 384c-88.4 0-160 71.6-160 160s71.6 160 160 160 160-71.6 160-160-71.6-160-160-160zm0 256c-53 0-96-43-96-96s43-96 96-96 96 43 96 96-43 96-96 96z"}}]},name:"camera",theme:"outlined"},CameraOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:CameraOutlined$1}))},RefIcon$9=reactExports.forwardRef(CameraOutlined),CloudDownloadOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M624 706.3h-74.1V464c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v242.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.7a8 8 0 0012.6 0l112-141.7c4.1-5.2.4-12.9-6.3-12.9z"}},{tag:"path",attrs:{d:"M811.4 366.7C765.6 245.9 648.9 160 512.2 160S258.8 245.8 213 366.6C127.3 389.1 64 467.2 64 560c0 110.5 89.5 200 199.9 200H304c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8h-40.1c-33.7 0-65.4-13.4-89-37.7-23.5-24.2-36-56.8-34.9-90.6.9-26.4 9.9-51.2 26.2-72.1 16.7-21.3 40.1-36.8 66.1-43.7l37.9-9.9 13.9-36.6c8.6-22.8 20.6-44.1 35.7-63.4a245.6 245.6 0 0152.4-49.9c41.1-28.9 89.5-44.2 140-44.2s98.9 15.3 140 44.2c19.9 14 37.5 30.8 52.4 49.9 15.1 19.3 27.1 40.7 35.7 63.4l13.8 36.5 37.8 10C846.1 454.5 884 503.8 884 560c0 33.1-12.9 64.3-36.3 87.7a123.07 123.07 0 01-87.6 36.3H720c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h40.1C870.5 760 960 670.5 960 560c0-92.7-63.1-170.7-148.6-193.3z"}}]},name:"cloud-download",theme:"outlined"},CloudDownloadOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:CloudDownloadOutlined$1}))},RefIcon$8=reactExports.forwardRef(CloudDownloadOutlined),DashboardOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M924.8 385.6a446.7 446.7 0 00-96-142.4 446.7 446.7 0 00-142.4-96C631.1 123.8 572.5 112 512 112s-119.1 11.8-174.4 35.2a446.7 446.7 0 00-142.4 96 446.7 446.7 0 00-96 142.4C75.8 440.9 64 499.5 64 560c0 132.7 58.3 257.7 159.9 343.1l1.7 1.4c5.8 4.8 13.1 7.5 20.6 7.5h531.7c7.5 0 14.8-2.7 20.6-7.5l1.7-1.4C901.7 817.7 960 692.7 960 560c0-60.5-11.9-119.1-35.2-174.4zM761.4 836H262.6A371.12 371.12 0 01140 560c0-99.4 38.7-192.8 109-263 70.3-70.3 163.7-109 263-109 99.4 0 192.8 38.7 263 109 70.3 70.3 109 163.7 109 263 0 105.6-44.5 205.5-122.6 276zM623.5 421.5a8.03 8.03 0 00-11.3 0L527.7 506c-18.7-5-39.4-.2-54.1 14.5a55.95 55.95 0 000 79.2 55.95 55.95 0 0079.2 0 55.87 55.87 0 0014.5-54.1l84.5-84.5c3.1-3.1 3.1-8.2 0-11.3l-28.3-28.3zM490 320h44c4.4 0 8-3.6 8-8v-80c0-4.4-3.6-8-8-8h-44c-4.4 0-8 3.6-8 8v80c0 4.4 3.6 8 8 8zm260 218v44c0 4.4 3.6 8 8 8h80c4.4 0 8-3.6 8-8v-44c0-4.4-3.6-8-8-8h-80c-4.4 0-8 3.6-8 8zm12.7-197.2l-31.1-31.1a8.03 8.03 0 00-11.3 0l-56.6 56.6a8.03 8.03 0 000 11.3l31.1 31.1c3.1 3.1 8.2 3.1 11.3 0l56.6-56.6c3.1-3.1 3.1-8.2 0-11.3zm-458.6-31.1a8.03 8.03 0 00-11.3 0l-31.1 31.1a8.03 8.03 0 000 11.3l56.6 56.6c3.1 3.1 8.2 3.1 11.3 0l31.1-31.1c3.1-3.1 3.1-8.2 0-11.3l-56.6-56.6zM262 530h-80c-4.4 0-8 3.6-8 8v44c0 4.4 3.6 8 8 8h80c4.4 0 8-3.6 8-8v-44c0-4.4-3.6-8-8-8z"}}]},name:"dashboard",theme:"outlined"},DashboardOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:DashboardOutlined$1}))},RefIcon$7=reactExports.forwardRef(DashboardOutlined),DatabaseOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 64H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V96c0-17.7-14.3-32-32-32zm-600 72h560v208H232V136zm560 480H232V408h560v208zm0 272H232V680h560v208zM304 240a40 40 0 1080 0 40 40 0 10-80 0zm0 272a40 40 0 1080 0 40 40 0 10-80 0zm0 272a40 40 0 1080 0 40 40 0 10-80 0z"}}]},name:"database",theme:"outlined"},DatabaseOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:DatabaseOutlined$1}))},RefIcon$6=reactExports.forwardRef(DatabaseOutlined),FileMarkdownOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326zm1.8 562H232V136h302v216a42 42 0 0042 42h216v494zM429 481.2c-1.9-4.4-6.2-7.2-11-7.2h-35c-6.6 0-12 5.4-12 12v272c0 6.6 5.4 12 12 12h27.1c6.6 0 12-5.4 12-12V582.1l66.8 150.2a12 12 0 0011 7.1H524c4.7 0 9-2.8 11-7.1l66.8-150.6V758c0 6.6 5.4 12 12 12H641c6.6 0 12-5.4 12-12V486c0-6.6-5.4-12-12-12h-34.7c-4.8 0-9.1 2.8-11 7.2l-83.1 191-83.2-191z"}}]},name:"file-markdown",theme:"outlined"},FileMarkdownOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:FileMarkdownOutlined$1}))},RefIcon$5=reactExports.forwardRef(FileMarkdownOutlined),FileZipOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M296 392h64v64h-64zm0 190v160h128V582h-64v-62h-64v62zm80 48v64h-32v-64h32zm-16-302h64v64h-64zm-64-64h64v64h-64zm64 192h64v64h-64zm0-256h64v64h-64zm494.6 88.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326zm1.8 562H232V136h64v64h64v-64h174v216a42 42 0 0042 42h216v494z"}}]},name:"file-zip",theme:"outlined"},FileZipOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:FileZipOutlined$1}))},RefIcon$4=reactExports.forwardRef(FileZipOutlined),RocketOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M864 736c0-111.6-65.4-208-160-252.9V317.3c0-15.1-5.3-29.7-15.1-41.2L536.5 95.4C530.1 87.8 521 84 512 84s-18.1 3.8-24.5 11.4L335.1 276.1a63.97 63.97 0 00-15.1 41.2v165.8C225.4 528 160 624.4 160 736h156.5c-2.3 7.2-3.5 15-3.5 23.8 0 22.1 7.6 43.7 21.4 60.8a97.2 97.2 0 0043.1 30.6c23.1 54 75.6 88.8 134.5 88.8 29.1 0 57.3-8.6 81.4-24.8 23.6-15.8 41.9-37.9 53-64a97 97 0 0043.1-30.5 97.52 97.52 0 0021.4-60.8c0-8.4-1.1-16.4-3.1-23.8H864zM762.3 621.4c9.4 14.6 17 30.3 22.5 46.6H700V558.7a211.6 211.6 0 0162.3 62.7zM388 483.1V318.8l124-147 124 147V668H388V483.1zM239.2 668c5.5-16.3 13.1-32 22.5-46.6 16.3-25.2 37.5-46.5 62.3-62.7V668h-84.8zm388.9 116.2c-5.2 3-11.2 4.2-17.1 3.4l-19.5-2.4-2.8 19.4c-5.4 37.9-38.4 66.5-76.7 66.5-38.3 0-71.3-28.6-76.7-66.5l-2.8-19.5-19.5 2.5a27.7 27.7 0 01-17.1-3.5c-8.7-5-14.1-14.3-14.1-24.4 0-10.6 5.9-19.4 14.6-23.8h231.3c8.8 4.5 14.6 13.3 14.6 23.8-.1 10.2-5.5 19.6-14.2 24.5zM464 400a48 48 0 1096 0 48 48 0 10-96 0z"}}]},name:"rocket",theme:"outlined"},RocketOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:RocketOutlined$1}))},RefIcon$3=reactExports.forwardRef(RocketOutlined),SaveOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M893.3 293.3L730.7 130.7c-7.5-7.5-16.7-13-26.7-16V112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V338.5c0-17-6.7-33.2-18.7-45.2zM384 184h256v104H384V184zm456 656H184V184h136v136c0 17.7 14.3 32 32 32h320c17.7 0 32-14.3 32-32V205.8l136 136V840zM512 442c-79.5 0-144 64.5-144 144s64.5 144 144 144 144-64.5 144-144-64.5-144-144-144zm0 224c-44.2 0-80-35.8-80-80s35.8-80 80-80 80 35.8 80 80-35.8 80-80 80z"}}]},name:"save",theme:"outlined"},SaveOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:SaveOutlined$1}))},RefIcon$2=reactExports.forwardRef(SaveOutlined),SettingOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M924.8 625.7l-65.5-56c3.1-19 4.7-38.4 4.7-57.8s-1.6-38.8-4.7-57.8l65.5-56a32.03 32.03 0 009.3-35.2l-.9-2.6a443.74 443.74 0 00-79.7-137.9l-1.8-2.1a32.12 32.12 0 00-35.1-9.5l-81.3 28.9c-30-24.6-63.5-44-99.7-57.6l-15.7-85a32.05 32.05 0 00-25.8-25.7l-2.7-.5c-52.1-9.4-106.9-9.4-159 0l-2.7.5a32.05 32.05 0 00-25.8 25.7l-15.8 85.4a351.86 351.86 0 00-99 57.4l-81.9-29.1a32 32 0 00-35.1 9.5l-1.8 2.1a446.02 446.02 0 00-79.7 137.9l-.9 2.6c-4.5 12.5-.8 26.5 9.3 35.2l66.3 56.6c-3.1 18.8-4.6 38-4.6 57.1 0 19.2 1.5 38.4 4.6 57.1L99 625.5a32.03 32.03 0 00-9.3 35.2l.9 2.6c18.1 50.4 44.9 96.9 79.7 137.9l1.8 2.1a32.12 32.12 0 0035.1 9.5l81.9-29.1c29.8 24.5 63.1 43.9 99 57.4l15.8 85.4a32.05 32.05 0 0025.8 25.7l2.7.5a449.4 449.4 0 00159 0l2.7-.5a32.05 32.05 0 0025.8-25.7l15.7-85a350 350 0 0099.7-57.6l81.3 28.9a32 32 0 0035.1-9.5l1.8-2.1c34.8-41.1 61.6-87.5 79.7-137.9l.9-2.6c4.5-12.3.8-26.3-9.3-35zM788.3 465.9c2.5 15.1 3.8 30.6 3.8 46.1s-1.3 31-3.8 46.1l-6.6 40.1 74.7 63.9a370.03 370.03 0 01-42.6 73.6L721 702.8l-31.4 25.8c-23.9 19.6-50.5 35-79.3 45.8l-38.1 14.3-17.9 97a377.5 377.5 0 01-85 0l-17.9-97.2-37.8-14.5c-28.5-10.8-55-26.2-78.7-45.7l-31.4-25.9-93.4 33.2c-17-22.9-31.2-47.6-42.6-73.6l75.5-64.5-6.5-40c-2.4-14.9-3.7-30.3-3.7-45.5 0-15.3 1.2-30.6 3.7-45.5l6.5-40-75.5-64.5c11.3-26.1 25.6-50.7 42.6-73.6l93.4 33.2 31.4-25.9c23.7-19.5 50.2-34.9 78.7-45.7l37.9-14.3 17.9-97.2c28.1-3.2 56.8-3.2 85 0l17.9 97 38.1 14.3c28.7 10.8 55.4 26.2 79.3 45.8l31.4 25.8 92.8-32.9c17 22.9 31.2 47.6 42.6 73.6L781.8 426l6.5 39.9zM512 326c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176zm79.2 255.2A111.6 111.6 0 01512 614c-29.9 0-58-11.7-79.2-32.8A111.6 111.6 0 01400 502c0-29.9 11.7-58 32.8-79.2C454 401.6 482.1 390 512 390c29.9 0 58 11.6 79.2 32.8A111.6 111.6 0 01624 502c0 29.9-11.7 58-32.8 79.2z"}}]},name:"setting",theme:"outlined"},SettingOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:SettingOutlined$1}))},RefIcon$1=reactExports.forwardRef(SettingOutlined),UploadOutlined$1={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M400 317.7h73.9V656c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V317.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 163a8 8 0 00-12.6 0l-112 141.7c-4.1 5.3-.4 13 6.3 13zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"}}]},name:"upload",theme:"outlined"},UploadOutlined=function(props,ref){return reactExports.createElement(Icon,_extends({},props,{ref:ref,icon:UploadOutlined$1}))},RefIcon=reactExports.forwardRef(UploadOutlined);const styles$r_root="_root_2zmas_2",styles$r_inner="_inner_2zmas_10",styles$r_header="_header_2zmas_17",styles$r_headerTitle="_headerTitle_2zmas_22",styles$r_headerFolderIcon="_headerFolderIcon_2zmas_27",styles$r_headerSubtitle="_headerSubtitle_2zmas_32",styles$r_addButtonRow="_addButtonRow_2zmas_36",styles$r_loadingCenter="_loadingCenter_2zmas_42",styles$r_emptyState="_emptyState_2zmas_47",styles$r_card="_card_2zmas_52",styles$r_cardRow="_cardRow_2zmas_59",styles$r_cardLeft="_cardLeft_2zmas_65",styles$r_cardNameRow="_cardNameRow_2zmas_70",styles$r_cardName="_cardName_2zmas_70",styles$r_cardPath="_cardPath_2zmas_82",styles$r_cardMeta="_cardMeta_2zmas_87",styles$r_dirPathHeader="_dirPathHeader_2zmas_96",styles$r_dirCurrentPath="_dirCurrentPath_2zmas_104",styles$r_dirFolderIcon="_dirFolderIcon_2zmas_113",styles$r_dirList="_dirList_2zmas_118",styles$r_dirListCenter="_dirListCenter_2zmas_124",styles$r_dirItem="_dirItem_2zmas_129",styles$r_dirItemInner="_dirItemInner_2zmas_137",styles$r_dirItemName="_dirItemName_2zmas_145",styles$r_dirGitTag="_dirGitTag_2zmas_153",styles$r_dirFooter="_dirFooter_2zmas_162",styles$r_dirPathInputRow="_dirPathInputRow_2zmas_170",styles$r_dirPathInput="_dirPathInput_2zmas_170",{Text:Text$4,Title:Title}=Typography;function formatSize(bytes){if(!bytes)return"0 B";const units=["B","KB","MB","GB"];let i=0,size=bytes;for(;size>=1024&&i<units.length-1;)size/=1024,i++;return`${size.toFixed(i>0?1:0)} ${units[i]}`}function timeAgo(isoString){if(!isoString)return"";const diff=Date.now()-new Date(isoString).getTime(),mins=Math.floor(diff/6e4);if(mins<1)return t("ui.workspaces.justNow");if(mins<60)return`${mins}m ago`;const hours=Math.floor(mins/60);if(hours<24)return`${hours}h ago`;return`${Math.floor(hours/24)}d ago`}function DirBrowser({open:open,onClose:onClose,onSelect:onSelect}){const[currentPath,setCurrentPath]=reactExports.useState(""),[parentPath,setParentPath]=reactExports.useState(null),[dirs,setDirs]=reactExports.useState([]),[loading2,setLoading]=reactExports.useState(!1),[pathInput,setPathInput]=reactExports.useState(""),browse=reactExports.useCallback(path=>{setLoading(!0);const url=path?`/api/browse-dir?path=${encodeURIComponent(path)}`:"/api/browse-dir";fetch(apiUrl(url)).then(res=>res.json()).then(data=>{data.error?staticMethods.error(data.error):(setCurrentPath(data.current),setParentPath(data.parent),setDirs(data.dirs||[]),setPathInput(data.current)),setLoading(!1)}).catch(()=>{staticMethods.error("Failed to browse directory"),setLoading(!1)})},[]);reactExports.useEffect(()=>{open&&browse("")},[open,browse]);const handleGoTo=()=>{const p=pathInput.trim();p&&browse(p)};return jsxRuntimeExports.jsxs(Modal,{title:t("ui.workspaces.selectDir"),open:open,onCancel:onClose,footer:null,width:600,styles:{body:{padding:"12px 0"}},children:[jsxRuntimeExports.jsxs("div",{className:styles$r_dirPathHeader,children:[jsxRuntimeExports.jsx(Button,{type:"text",icon:jsxRuntimeExports.jsx(RefIcon$b,{}),disabled:!parentPath,onClick:()=>parentPath&&browse(parentPath),size:"small"}),jsxRuntimeExports.jsxs(Text$4,{className:styles$r_dirCurrentPath,children:[jsxRuntimeExports.jsx(RefIcon$d,{className:styles$r_dirFolderIcon}),currentPath]})]}),jsxRuntimeExports.jsx("div",{className:styles$r_dirList,children:loading2?jsxRuntimeExports.jsx("div",{className:styles$r_dirListCenter,children:jsxRuntimeExports.jsx(Spin,{})}):0===dirs.length?jsxRuntimeExports.jsx("div",{className:styles$r_dirListCenter,children:jsxRuntimeExports.jsx(Text$4,{type:"secondary",children:t("ui.workspaces.emptyDir")})}):dirs.map(dir=>jsxRuntimeExports.jsxs("div",{className:styles$r_dirItem,onMouseEnter:e=>e.currentTarget.style.background="var(--bg-elevated)",onMouseLeave:e=>e.currentTarget.style.background="transparent",children:[jsxRuntimeExports.jsxs("div",{className:styles$r_dirItemInner,onClick:()=>browse(dir.path),children:[jsxRuntimeExports.jsx(RefIcon$h,{style:{color:dir.hasGit?"var(--color-primary)":"var(--text-muted)",fontSize:16,flexShrink:0}}),jsxRuntimeExports.jsx(Text$4,{className:styles$r_dirItemName,children:dir.name}),dir.hasGit&&jsxRuntimeExports.jsxs(Tag,{color:"blue",className:styles$r_dirGitTag,children:[jsxRuntimeExports.jsx(RefIcon$a,{style:{marginRight:2}}),"git"]})]}),jsxRuntimeExports.jsx(Button,{type:"primary",size:"small",onClick:e=>{e.stopPropagation(),onSelect(dir.path)},children:t("ui.workspaces.select")})]},dir.path))}),jsxRuntimeExports.jsxs("div",{className:styles$r_dirFooter,children:[jsxRuntimeExports.jsxs(Button,{type:"primary",ghost:!0,block:!0,icon:jsxRuntimeExports.jsx(RefIcon$d,{}),onClick:()=>onSelect(currentPath),children:[t("ui.workspaces.selectCurrent")," — ",currentPath.split("/").pop()||currentPath]}),jsxRuntimeExports.jsxs("div",{className:styles$r_dirPathInputRow,children:[jsxRuntimeExports.jsx(Input,{size:"small",value:pathInput,onChange:e=>setPathInput(e.target.value),onPressEnter:handleGoTo,placeholder:t("ui.workspaces.pathPlaceholder"),className:styles$r_dirPathInput}),jsxRuntimeExports.jsx(Button,{size:"small",onClick:handleGoTo,children:t("ui.workspaces.goTo")})]})]})]})}function WorkspaceList({onLaunch:onLaunch}){const[workspaces,setWorkspaces]=reactExports.useState([]),[loading2,setLoading]=reactExports.useState(!0),[launching,setLaunching]=reactExports.useState(null),[browseOpen,setBrowseOpen]=reactExports.useState(!1),fetchWorkspaces=()=>{fetch(apiUrl("/api/workspaces")).then(res=>res.json()).then(data=>{setWorkspaces(data.workspaces||[]),setLoading(!1)}).catch(()=>setLoading(!1))};reactExports.useEffect(()=>{fetchWorkspaces()},[]);const handleLaunch=(workspace,dangerousMode=!1)=>{var _a;setLaunching(workspace.id);const extraArgs=[];if(dangerousMode&&extraArgs.push("--dangerously-skip-permissions"),workspace.logCount>0&&extraArgs.push("-c"),null==(_a=window.electronAPI)?void 0:_a.launchWorkspace)return window.electronAPI.launchWorkspace(workspace.path,extraArgs),void setLaunching(null);fetch(apiUrl("/api/workspaces/launch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:workspace.path,extraArgs:extraArgs})}).then(res=>res.json()).then(data=>{data.error?(staticMethods.error(data.error),setLaunching(null)):onLaunch({projectName:data.projectName,path:workspace.path})}).catch(()=>{staticMethods.error("Launch failed"),setLaunching(null)})};return jsxRuntimeExports.jsxs("div",{className:styles$r_root,children:[jsxRuntimeExports.jsxs("div",{className:styles$r_inner,children:[jsxRuntimeExports.jsxs("div",{className:styles$r_header,children:[jsxRuntimeExports.jsxs(Title,{level:3,className:styles$r_headerTitle,children:[jsxRuntimeExports.jsx(RefIcon$d,{className:styles$r_headerFolderIcon}),t("ui.workspaces.title")]}),jsxRuntimeExports.jsx(Text$4,{type:"secondary",className:styles$r_headerSubtitle,children:t("ui.workspaces.subtitle")})]}),jsxRuntimeExports.jsx("div",{className:styles$r_addButtonRow,children:jsxRuntimeExports.jsx(Button,{type:"primary",icon:jsxRuntimeExports.jsx(RefIcon$e,{}),onClick:()=>setBrowseOpen(!0),size:"large",children:t("ui.workspaces.browse")})}),loading2?jsxRuntimeExports.jsx("div",{className:styles$r_loadingCenter,children:jsxRuntimeExports.jsx(Spin,{})}):0===workspaces.length?jsxRuntimeExports.jsx(Empty,{description:jsxRuntimeExports.jsx(Text$4,{type:"secondary",children:t("ui.workspaces.empty")}),className:styles$r_emptyState}):jsxRuntimeExports.jsx(List,{dataSource:workspaces,renderItem:item=>jsxRuntimeExports.jsx(Card,{size:"small",className:styles$r_card,hoverable:!0,onClick:()=>handleLaunch(item,!1),children:jsxRuntimeExports.jsxs("div",{className:styles$r_cardRow,children:[jsxRuntimeExports.jsxs("div",{className:styles$r_cardLeft,children:[jsxRuntimeExports.jsx("div",{className:styles$r_cardNameRow,children:jsxRuntimeExports.jsx(Text$4,{strong:!0,className:styles$r_cardName,children:item.projectName})}),jsxRuntimeExports.jsx(Text$4,{type:"secondary",className:styles$r_cardPath,children:item.path}),jsxRuntimeExports.jsxs("div",{className:styles$r_cardMeta,children:[jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(RefIcon$f,{style:{marginRight:4}}),timeAgo(item.lastUsed)]}),item.logCount>0&&jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(RefIcon$6,{style:{marginRight:4}}),item.logCount," logs (",formatSize(item.totalSize),")"]})]})]}),jsxRuntimeExports.jsxs(Space,{children:[jsxRuntimeExports.jsx(Button,{type:"primary",icon:jsxRuntimeExports.jsx(RefIcon$3,{}),loading:launching===item.id,onClick:e=>{e.stopPropagation(),handleLaunch(item,!1)},children:t("ui.workspaces.normalLaunch")}),jsxRuntimeExports.jsx(Button,{icon:jsxRuntimeExports.jsx(RefIcon$3,{}),loading:launching===item.id,onClick:e=>{e.stopPropagation(),handleLaunch(item,!0)},style:{background:"#d97706",borderColor:"#d97706",color:"#fff"},children:t("ui.workspaces.skipPermLaunch")}),jsxRuntimeExports.jsx(Popconfirm,{title:t("ui.workspaces.confirmRemove"),onConfirm:e=>{var id;null==e||e.stopPropagation(),id=item.id,fetch(apiUrl(`/api/workspaces/${id}`),{method:"DELETE"}).then(res=>res.json()).then(()=>fetchWorkspaces()).catch(()=>{})},onCancel:e=>null==e?void 0:e.stopPropagation(),okText:"Yes",cancelText:"No",children:jsxRuntimeExports.jsx(Button,{type:"text",danger:!0,icon:jsxRuntimeExports.jsx(RefIcon$g,{}),onClick:e=>e.stopPropagation()})})]})]})},item.id)})]}),jsxRuntimeExports.jsx(DirBrowser,{open:browseOpen,onClose:()=>setBrowseOpen(!1),onSelect:path=>{setBrowseOpen(!1),fetch(apiUrl("/api/workspaces/add"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:path})}).then(res=>res.json()).then(data=>{data.error?staticMethods.error(data.error):fetchWorkspaces()}).catch(()=>staticMethods.error("Failed to add workspace"))}})]})}const styles$q_iconBtn="_iconBtn_5ojec_1";function OpenFolderIcon({apiEndpoint:apiEndpoint,title:title2,size:size=16}){const[hovered,setHovered]=reactExports.useState(!1),handleClick=e=>{e.stopPropagation(),fetch(apiEndpoint,{method:"POST"}).catch(()=>{})},closedFolder=jsxRuntimeExports.jsx("svg",{width:size,height:size,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})}),openFolder=jsxRuntimeExports.jsxs("svg",{width:size,height:size,viewBox:"0 0 24 24",fill:"none",stroke:"var(--color-accent-yellow)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M5 19a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4l2 2h5a2 2 0 0 1 2 2v1",fill:"none"}),jsxRuntimeExports.jsx("path",{d:"M20 10H8.5A2.5 2.5 0 0 0 6 12.5L5 19h13.5a2 2 0 0 0 2-1.75l1-6.25A1 1 0 0 0 20.5 10z",fill:"var(--color-accent-yellow)",stroke:"var(--color-accent-yellow)"})]});return jsxRuntimeExports.jsx("span",{role:"button",tabIndex:0,onClick:handleClick,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),handleClick(e))},onMouseEnter:()=>setHovered(!0),onMouseLeave:()=>setHovered(!1),title:title2,className:styles$q_iconBtn,style:{opacity:hovered?1:.7},children:hovered?openFolder:closedFolder})}const NATIVE_TEAMMATE_RE=/You are a Claude agent/i,_cache=new WeakMap;function isNativeTeammate(req){var _a;if(!req)return!1;const cached=_cache.get(req);if(void 0!==cached)return cached;if(req.teammate)return _cache.set(req,!1),!1;const sysText=function(body2){const system=null==body2?void 0:body2.system;return"string"==typeof system?system:Array.isArray(system)?system.map(s=>s&&s.text||"").join(""):""}(req.body||{});if(!NATIVE_TEAMMATE_RE.test(sysText))return _cache.set(req,!1),!1;const tools=null==(_a=req.body)?void 0:_a.tools,result=Array.isArray(tools)&&tools.some(t2=>t2&&"SendMessage"===t2.name);return _cache.set(req,result),result}function isPostClearCheckpoint(entry,prevMessageCount=0){if(!entry||!0!==entry._isCheckpoint)return!1;const msgs=entry.body&&entry.body.messages;if(!Array.isArray(msgs)||0===msgs.length)return!1;if(prevMessageCount>0&&msgs.length>=prevMessageCount)return!1;const m0=msgs[0];if(!m0||"user"!==m0.role||!Array.isArray(m0.content))return!1;for(let i=0;i<m0.content.length;i++){const block=m0.content[i];if(block&&"text"===block.type&&"string"==typeof block.text&&-1!==block.text.indexOf("<command-name>/clear</command-name>"))return!0}return!1}const SUBAGENT_SYSTEM_RE=/command execution specialist|file search specialist|planning specialist|general-purpose agent/i,TEAMMATE_SYSTEM_RE=/running as an agent in a team|Agent Teammate Communication/i;function getSystemText(body2){const system=null==body2?void 0:body2.system;return"string"==typeof system?system:Array.isArray(system)?system.map(s=>s&&s.text||"").join(""):""}const _isTeammateCache=new WeakMap;function isTeammate(req){if(!req)return!1;const cached=_isTeammateCache.get(req);if(void 0!==cached)return cached;if(req.teammate)return _isTeammateCache.set(req,!0),!0;if(isNativeTeammate(req))return req.teammate||(req.teammate=function(req){if(!(null==req?void 0:req.body))return null;const msgs=req.body.messages||[];if(0===msgs.length)return null;for(const m of msgs){if("user"!==m.role)continue;const content2=m.content;let text="";if("string"==typeof content2?text=content2:Array.isArray(content2)&&(text=content2.filter(c=>c&&"text"===c.type).map(c=>c.text||"").join(" ")),!text)continue;const nameMatch=text.match(/Agent\s+(?:oh-my-claudecode:)?(\S+)\s+started/i)||text.match(/You are (\w+)[,.]/)||text.match(/name[::]\s*["']?(\w+)/i);if(nameMatch)return nameMatch[1]}return null}(req)||null),_isTeammateCache.set(req,!0),!0;const sysText=getSystemText(req.body||{}),result=TEAMMATE_SYSTEM_RE.test(sysText);return _isTeammateCache.set(req,result),result}const _isMainAgentCache=new WeakMap;function isMainAgent(req){if(!req)return!1;const cached=_isMainAgentCache.get(req);if(void 0!==cached)return cached;const result=function(req){if(!req)return!1;if(isTeammate(req))return!1;if(req.mainAgent){const sysText2=getSystemText(req.body||{});return!SUBAGENT_SYSTEM_RE.test(sysText2)}const body2=req.body||{};if(!body2.system||!Array.isArray(body2.tools))return!1;const sysText=getSystemText(body2);if(!sysText.includes("You are Claude Code"))return!1;if(SUBAGENT_SYSTEM_RE.test(sysText))return!1;const isSystemArray=Array.isArray(body2.system),hasToolSearch=body2.tools.some(t2=>"ToolSearch"===t2.name);if(isSystemArray&&hasToolSearch){const messages=body2.messages||[];if((messages.length>0?"string"==typeof messages[0].content?messages[0].content:Array.isArray(messages[0].content)?messages[0].content.map(c=>c.text||"").join(""):"":"").includes("<available-deferred-tools>"))return!0}if(body2.tools.length>5){const hasEdit=body2.tools.some(t2=>"Edit"===t2.name),hasBash=body2.tools.some(t2=>"Bash"===t2.name),hasTaskOrAgent=body2.tools.some(t2=>"Task"===t2.name||"Agent"===t2.name);if(hasEdit&&hasBash&&hasTaskOrAgent)return!0}return!1}(req);return _isMainAgentCache.set(req,result),result}function isSkillText(text){return!!text&&/^Base directory for this skill:/i.test(text.trim())}function stripSystemTags(text){return text?text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi,"").replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>/gi,"").replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>/gi,"").replace(/<command-name>[\s\S]*?<\/command-name>/gi,"").replace(/<command-message>[\s\S]*?<\/command-message>/gi,"").replace(/<command-args>[\s\S]*?<\/command-args>/gi,"").replace(/<teammate-message[\s\S]*?<\/teammate-message>/gi,"").replace(/<task-notification>[\s\S]*?<\/task-notification>/gi,"").trim():""}const SYNTHETIC_PROMPTS=[{subType:"Recap",pattern:/^The user stepped away and is coming back\. Recap in under/i},{subType:"Title",pattern:/^(Based on the above conversation, generate a|Please write a)\s+(short|concise)\s+title/i},{subType:"Compact",pattern:/^(Your task is to create a detailed summary of the conversation|This session is being continued from a previous conversation)/i},{subType:"Topic",pattern:/^Analyze if this message indicates a new/i},{subType:"Summary",pattern:/^Summarize this coding session/i}];function isSystemText(text){if(!text)return!0;const trimmed=text.trim();return!trimmed||!/Implement the following plan:/i.test(trimmed)&&(!!/^<[a-zA-Z_][\w-]*[\s>]/i.test(trimmed)||(!!/^\[SUGGESTION MODE:/i.test(trimmed)||(!!/^Your response was cut off because it exceeded the output token limit/i.test(trimmed)||(!!/^Base directory for this skill:/i.test(trimmed)||!!function(text){if(!text||"string"!=typeof text)return!1;const trimmed=text.trim();if(!trimmed)return!1;for(const{pattern:pattern}of SYNTHETIC_PROMPTS)if(pattern.test(trimmed))return!0;return!1}(trimmed)))))}function classifyUserContent(content2){if(!Array.isArray(content2))return{commands:[],textBlocks:[],skillBlocks:[],teammateBlocks:[],taskNotificationBlocks:[]};const teammateBlocks=[];for(const b of content2){if("text"!==b.type)continue;const text=b.text||"",re=/<teammate-message\s+([^>]*)>([\s\S]*?)<\/teammate-message>/gi;let match;for(;null!==(match=re.exec(text));){const attrs=match[1],body2=match[2].trim(),idMatch=attrs.match(/teammate_id="([^"]*)"/),colorMatch=attrs.match(/color="([^"]*)"/),summaryMatch=attrs.match(/summary="([^"]*)"/),tmId=idMatch?idMatch[1]:"teammate",tmColor=colorMatch?colorMatch[1]:null;if(body2.startsWith("{"))try{const j=JSON.parse(body2);if(j&&j.type){teammateBlocks.push({id:tmId,color:tmColor,summary:null,content:null,status:j.type,statusFrom:j.from||tmId});continue}}catch{}teammateBlocks.push({id:tmId,color:tmColor,summary:summaryMatch?summaryMatch[1]:null,content:body2,status:null})}}const taskNotificationBlocks=[];if(content2.some(b=>"text"===b.type&&/<task-notification>/i.test(b.text||"")))for(const b of content2){if("text"!==b.type)continue;const text=b.text||"",tnRe=/<task-notification>([\s\S]*?)<\/task-notification>/gi;let tnMatch;for(;null!==(tnMatch=tnRe.exec(text));){const inner2=tnMatch[1],field2=tag=>{const m=inner2.match(new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`,"i"));return m?m[1].trim():null},usageBlock=inner2.match(/<usage>([\s\S]*?)<\/usage>/i);let usage=null;if(usageBlock){const uf=tag=>{const m=usageBlock[1].match(new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`,"i"));return m?m[1].trim():null};usage={totalTokens:Number(uf("total_tokens")||0),toolUses:Number(uf("tool_uses")||0),durationMs:Number(uf("duration_ms")||0)}}taskNotificationBlocks.push({taskId:field2("task-id"),status:field2("status"),summary:field2("summary"),result:field2("result"),usage:usage})}}const hasCommand=content2.some(b=>"text"===b.type&&/<command-message>/i.test(b.text||"")),commands=[];if(hasCommand)for(const b of content2){if("text"!==b.type)continue;const m=(b.text||"").match(/<command-name>\s*([^<]*)<\/command-name>/i);if(m){const cmd=m[1].trim();commands.push(cmd.startsWith("/")?cmd:`/${cmd}`)}}let textBlocks=content2.filter(b=>"text"===b.type&&!isSystemText(b.text));for(const b of content2){if("text"!==b.type||!isSystemText(b.text))continue;const userText=stripSystemTags(b.text);userText&&textBlocks.push({...b,text:userText})}hasCommand&&(textBlocks=textBlocks.filter(b=>!/<command-message>/i.test(b.text||"")));const skillBlocks=textBlocks.filter(b=>isSkillText(b.text));return skillBlocks.length>0&&(textBlocks=textBlocks.filter(b=>!isSkillText(b.text))),{commands:commands,textBlocks:textBlocks,skillBlocks:skillBlocks,teammateBlocks:teammateBlocks,taskNotificationBlocks:taskNotificationBlocks}}const _promptRegistry=new Map;let _registryScanIdx=0,_registrySessionKey=null;const TM_TAG_RE=/<teammate-message[^>]*>/;function _extractSpawnPrompt(req){var _a;const msgs=null==(_a=req.body)?void 0:_a.messages;if(!Array.isArray(msgs)||0===msgs.length)return"";const content2=msgs[0].content;if("string"==typeof content2){const m=TM_TAG_RE.exec(content2);return m?content2.slice(m.index+m[0].length).trimStart():""}if(Array.isArray(content2))for(const b of content2){if("text"!==b.type||!b.text)continue;const m=TM_TAG_RE.exec(b.text);if(m)return b.text.slice(m.index+m[0].length).trimStart()}return""}function _extractRawPrompt(req){var _a;const msgs=null==(_a=req.body)?void 0:_a.messages;if(!Array.isArray(msgs)||0===msgs.length)return"";const content2=msgs[0].content;if("string"==typeof content2)return content2.trimStart();if(Array.isArray(content2))for(const b of content2)if("text"===b.type&&b.text)return b.text.trimStart();return""}function resolveTeammateNames(requests){var _a,_b,_c;if(!Array.isArray(requests)||0===requests.length)return;const sessionKey=(null==(_a=requests[0])?void 0:_a.timestamp)||null;sessionKey!==_registrySessionKey&&(_promptRegistry.clear(),_registryScanIdx=0,_registrySessionKey=sessionKey);for(let i=_registryScanIdx;i<requests.length;i++){const req=requests[i];if(!req.mainAgent)continue;const content2=null==(_c=null==(_b=req.response)?void 0:_b.body)?void 0:_c.content;if(Array.isArray(content2))for(const block of content2){if("tool_use"!==block.type||"Agent"!==block.name)continue;const inp=block.input;if(!inp||!inp.name||!inp.prompt)continue;const prefix2=inp.prompt.trimStart().slice(0,60);prefix2&&_promptRegistry.set(prefix2,inp.name)}}if(_registryScanIdx=requests.length,0!==_promptRegistry.size)for(const req of requests){if(req.teammate)continue;if(!isNativeTeammate(req)&&!TEAMMATE_SYSTEM_RE.test(getSystemText(req.body||{})))continue;let prompt=_extractSpawnPrompt(req);if(!prompt&&isNativeTeammate(req)&&(prompt=_extractRawPrompt(req)),!prompt)continue;const prefix2=prompt.slice(0,60),name=_promptRegistry.get(prefix2);name&&(req.teammate=name,null===req._cachedTeammateName&&(req._cachedTeammateName=name))}}const _readResultPool=new Map;function _readResultSig(s){if(s.length>512){const midIdx=Math.floor(s.length/2);return s.length+":"+s.slice(0,64)+":"+s.slice(midIdx,midIdx+64)+":"+s.slice(-64)}return s.length+":"+s.slice(0,64)+":"+s.slice(-64)}function internToolResult(s){return function(s){if("string"!=typeof s||s.length<256)return s;const sig=_readResultSig(s),pooled=_readResultPool.get(sig);return void 0!==pooled?pooled:(_readResultPool.size>=1e3&&_readResultPool.delete(_readResultPool.keys().next().value),_readResultPool.set(sig,s),s)}(s)}function internToolResultIfPooled(s){if("string"!=typeof s||s.length<256)return null;const sig=_readResultSig(s),pooled=_readResultPool.get(sig);return void 0!==pooled?pooled:(_readResultPool.size>=1e3&&_readResultPool.delete(_readResultPool.keys().next().value),_readResultPool.set(sig,s),null)}const _toolsPool=new Map,_systemPool=new Map;function _internOrAdd(pool,sig,value){let pooled=pool.get(sig);return pooled||(pool.size>=200&&pool.delete(pool.keys().next().value),Array.isArray(value)&&Object.freeze(value),pool.set(sig,value),value)}function internEntryBigFields(entry){if(!(null==entry?void 0:entry.body))return entry;const body2=entry.body;let newTools=body2.tools,newSystem=body2.system,newMessages=body2.messages,dirty=!1;if(Array.isArray(body2.tools)&&body2.tools.length>0){const sig=function(tools){var _a;if(!Array.isArray(tools)||0===tools.length)return"";let sig="t:"+tools.length;for(const t2 of tools)sig+="|"+((null==t2?void 0:t2.name)||"")+":"+((null==(_a=null==t2?void 0:t2.description)?void 0:_a.length)||0);return sig}(body2.tools),pooled=_internOrAdd(_toolsPool,sig,body2.tools);pooled!==body2.tools&&(newTools=pooled,dirty=!0)}if(Array.isArray(body2.system)&&body2.system.length>0||"string"==typeof body2.system){const sig=function(system){if(Array.isArray(system)){if(0===system.length)return"a:0";let sig="a:"+system.length;for(const b of system){const text=(null==b?void 0:b.text)||"",mid=text.length>100?Math.floor(text.length/2):0;sig+="|"+((null==b?void 0:b.type)||"")+":"+text.length+":"+text.slice(0,50)+":"+text.slice(mid,mid+50)}return sig}if("string"==typeof system){const mid=system.length>100?Math.floor(system.length/2):0;return"s:"+system.length+":"+system.slice(0,50)+":"+system.slice(mid,mid+50)}return""}(body2.system);if(sig){const pooled=_internOrAdd(_systemPool,sig,body2.system);pooled!==body2.system&&(newSystem=pooled,dirty=!0)}}if(Array.isArray(body2.messages)&&body2.messages.length>0){const interned=function(messages){if(!Array.isArray(messages)||0===messages.length)return messages;let newMessages=null;for(let i=0;i<messages.length;i++){const msg=messages[i],content2=null==msg?void 0:msg.content;if(!Array.isArray(content2)||0===content2.length)continue;let newContent=null;for(let j=0;j<content2.length;j++){const block=content2[j];if(!block||"tool_result"!==block.type)continue;const c=block.content;if("string"!=typeof c)continue;const pooled=internToolResultIfPooled(c);null!==pooled&&(null===newContent&&(newContent=content2.slice()),newContent[j]={...block,content:pooled})}null!==newContent&&(null===newMessages&&(newMessages=messages.slice()),newMessages[i]={...msg,content:newContent})}return newMessages||messages}(body2.messages);interned!==body2.messages&&(newMessages=interned,dirty=!0)}return dirty?{...entry,body:{...entry.body,tools:newTools,system:newSystem,messages:newMessages}}:entry}function slimBodyBigFields(body2){if(!body2)return body2;const next={...body2,messages:[]};return Array.isArray(body2.tools)&&(next.tools=body2.tools.map(t2=>({name:t2&&t2.name||null}))),Array.isArray(body2.system)?next.system=body2.system.map(blk=>{if(!blk||"object"!=typeof blk)return blk;if("text"===blk.type&&"string"==typeof blk.text&&blk.text.length>2048){return{...blk,text:blk.text.slice(0,2048)}}return blk}):"string"==typeof body2.system&&body2.system.length>2048&&(next.system=body2.system.slice(0,2048)),body2.metadata&&"object"==typeof body2.metadata&&(next.metadata=body2.metadata.user_id?{user_id:body2.metadata.user_id}:{}),"tool_choice"in next&&delete next.tool_choice,next}function restoreSlimmedEntry(entry,requests){var _a;if(!entry._slimmed||null==entry._fullEntryIndex)return entry;const fullEntry=requests[entry._fullEntryIndex];if(!(null==(_a=null==fullEntry?void 0:fullEntry.body)?void 0:_a.messages))return entry;if(fullEntry.body.messages.length<entry._messageCount)return entry;const fullBody=fullEntry.body;return{...entry,_slimmed:!1,_fullEntryIndex:void 0,body:{...entry.body,messages:fullBody.messages.slice(0,entry._messageCount),tools:fullBody.tools,system:fullBody.system,metadata:fullBody.metadata,tool_choice:fullBody.tool_choice}}}function indentLines(text,spaces=2){const pad=" ".repeat(spaces);return text.split("\n").map(line=>line.length>0?pad+line:line).join("\n")}function formatToolAsXml(tool){if(!tool||"object"!=typeof tool)return"";const name=tool.name||"unknown",description="string"==typeof tool.description?tool.description:"",schema=tool.input_schema||tool.parameters||{},properties=schema&&"object"==typeof schema&&schema.properties?schema.properties:{},requiredSet=new Set(Array.isArray(schema&&schema.required)?schema.required:[]),paramXmls=Object.entries(properties).map(([paramName,paramSchema])=>function(name,schema,required){const s=schema&&"object"==typeof schema?schema:{},type=s.type||(Array.isArray(s.enum)?"enum":"any"),desc="string"==typeof s.description?s.description:"",lines=["<parameter>",` <name>${name}</name>`,` <type>${type}</type>`];return desc&&lines.push(` <description>${desc}</description>`),lines.push(` <required>${required?"true":"false"}</required>`),Array.isArray(s.enum)&&s.enum.length>0&&lines.push(` <enum>${s.enum.map(v=>String(v)).join(", ")}</enum>`),void 0!==s.default&&lines.push(` <default>${JSON.stringify(s.default)}</default>`),"array"===type&&s.items&&lines.push(` <items>${JSON.stringify(s.items)}</items>`),"object"===type&&s.properties&&lines.push(` <properties>${JSON.stringify(s.properties)}</properties>`),lines.push("</parameter>"),lines.join("\n")}(paramName,paramSchema,requiredSet.has(paramName))),parametersBlock=paramXmls.length>0?"<parameters>\n"+indentLines(paramXmls.join("\n"))+"\n</parameters>":"<parameters></parameters>";return"<tool>\n"+indentLines([`<name>${name}</name>`,`<description>${description}</description>`,parametersBlock].join("\n"))+"\n</tool>"}const BUILTIN_SKILL_NAMES=new Set(["update-config","keybindings-help","simplify","fewer-permission-prompts","loop","schedule","claude-api","init","review","security-review"]);function skillToDisplayName(s){if(!s||"string"!=typeof s.name)return"";if("plugin"===s.source&&"string"==typeof s.pluginName&&s.pluginName.includes("@")){const short=s.pluginName.split("@")[0];if(short)return`${short}:${s.name}`}return s.name}const MODEL_CONTEXT_SIZES=[{match:/\[1m\]/i,tokens:1e6},{match:/opus/i,tokens:1e6},{match:/claude/i,tokens:2e5},{match:/gpt-4o|o1|o3|o4/i,tokens:128e3},{match:/gpt-4/i,tokens:128e3},{match:/gpt-3/i,tokens:16e3},{match:/deepseek-v4/i,tokens:1e6},{match:/deepseek/i,tokens:128e3}];function getModelMaxTokens(modelName2){if(!modelName2)return 2e5;for(const entry of MODEL_CONTEXT_SIZES)if(entry.match.test(modelName2))return entry.tokens;return 2e5}function getEffectiveModel(request){var _a,_b,_c;return(null==(_b=null==(_a=null==request?void 0:request.response)?void 0:_a.body)?void 0:_b.model)||(null==(_c=null==request?void 0:request.body)?void 0:_c.model)||null}const AUTO_COMPACT_USABLE_RATIO=.835,CALIBRATION_TOKEN_MAP={"1m":1e6,"200k":2e5};function resolveCalibrationTokens(calibrationModel,lastMainAgent){const direct=CALIBRATION_TOKEN_MAP[calibrationModel];if(direct)return direct;const raw=lastMainAgent?getEffectiveModel(lastMainAgent):null;if("string"!=typeof raw||!raw)return 1e6;const m=raw.toLowerCase();return m.includes("opus-4-7")||m.includes("opus-4.7")||m.includes("opus 4.7")||m.includes("1m")?1e6:2e5}function appendCacheLossMap(map,requests,startIndex,prevMainAgent){var _a,_b;for(let i=startIndex;i<requests.length;i++){const req=requests[i];if(isMainAgent(req)){if(prevMainAgent){const usage=null==(_b=null==(_a=req.response)?void 0:_a.body)?void 0:_b.usage;if(usage){const cacheCreate=usage.cache_creation_input_tokens||0,cacheRead=usage.cache_read_input_tokens||0;if(cacheCreate>0&&cacheCreate>cacheRead){const loss=_computeCacheLoss(prevMainAgent._slimmed?restoreSlimmedEntry(prevMainAgent,requests):prevMainAgent,req);loss&&map.set(i,loss)}}}prevMainAgent=req}}return prevMainAgent}const _jsonCache=new WeakMap;function _getCachedJson(entry,key){let cache=_jsonCache.get(entry);if(cache||(cache={},_jsonCache.set(entry,cache)),void 0===cache[key]){const body2=stripPrivateKeys(entry.body);cache[key]=JSON.stringify(null==body2?void 0:body2[key])}return cache[key]}function _computeCacheLoss(prevMainAgent,req){if(req.timestamp-prevMainAgent.timestamp>3e5)return{reason:"ttl",reasons:["ttl"]};const prev=stripPrivateKeys(prevMainAgent.body),curr=stripPrivateKeys(req.body);if(!prev||!curr)return{reason:"key_change",reasons:["key_change"]};const reasons=[];prev.model!==curr.model&&reasons.push("model_change");_getCachedJson(prevMainAgent,"system")!==_getCachedJson(req,"system")&&reasons.push("system_change");_getCachedJson(prevMainAgent,"tools")!==_getCachedJson(req,"tools")&&reasons.push("tools_change");const prevMsgs=prev.messages||[],currMsgs=curr.messages||[];if(currMsgs.length<prevMsgs.length)reasons.push("msg_truncated");else{const prefixLen=Math.min(prevMsgs.length,currMsgs.length);let prefixMatch=!0;for(let j=0;j<prefixLen;j++)if(JSON.stringify(prevMsgs[j])!==JSON.stringify(currMsgs[j])){prefixMatch=!1;break}prefixMatch||reasons.push("msg_modified")}return 0===reasons.length&&reasons.push("key_change"),{reason:reasons[0],reasons:reasons}}function escapeHtml(str){return str?str.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""):""}function extractToolResultText(toolResult){return toolResult.content?"string"==typeof toolResult.content?toolResult.content:Array.isArray(toolResult.content)?toolResult.content.filter(b=>"text"===b.type).map(b=>b.text).join("\n"):JSON.stringify(toolResult.content):String(toolResult.content??"")}const MODEL_PROVIDERS=[{match:/claude/i,name:"Claude",color:"var(--bg-model-avatar)",svg:'<svg t="1771495509570" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1570" width="200" height="200"><path d="M198.4 678.4l198.4-115.2 6.4-12.8H243.2l-96-6.4-102.4-6.4-19.2-6.4-25.6-25.6v-12.8l19.2-12.8h32l64 6.4 96 6.4 70.4 6.4L384 512h19.2V492.8l-6.4-6.4-102.4-64-108.8-76.8-51.2-38.4-32-19.2-19.2-25.6-6.4-38.4 32-32h44.8l38.4 32 83.2 64L384 364.8l12.8 12.8 6.4-6.4-6.4-12.8L339.2 256l-64-108.8-25.6-38.4-6.4-25.6c0-12.8-6.4-19.2-6.4-32l32-44.8 19.2-6.4 44.8 6.4 19.2 12.8 25.6 57.6 44.8 96 64 128 19.2 38.4 6.4 38.4 6.4 12.8h6.4V384l6.4-70.4 12.8-89.6 12.8-115.2 6.4-32 19.2-38.4 32-19.2 25.6 12.8 19.2 32v19.2l-32 70.4-19.2 121.6-19.2 83.2h6.4l12.8-12.8 44.8-57.6 70.4-89.6 32-32 38.4-38.4 25.6-19.2h44.8l32 51.2-12.8 51.2-51.2 57.6-38.4 51.2-51.2 70.4-38.4 57.6v6.4h6.4l121.6-25.6 64-12.8 76.8-12.8 38.4 19.2 6.4 19.2-12.8 32-83.2 19.2-96 19.2-147.2 32 64 6.4h96l128 6.4 32 19.2 25.6 38.4-6.4 19.2-51.2 25.6-70.4-12.8-160-38.4-57.6-12.8h-6.4v6.4l44.8 44.8 83.2 76.8 108.8 102.4 6.4 25.6-12.8 19.2h-12.8l-96-70.4-38.4-32-83.2-70.4h-6.4v6.4l19.2 25.6 102.4 147.2 6.4 44.8-6.4 12.8-25.6 6.4-25.6-6.4-57.6-83.2-64-83.2-51.2-83.2-6.4 6.4-25.6 307.2-12.8 12.8-32 12.8-25.6-19.2-12.8-32 12.8-64 19.2-83.2 12.8-64 12.8-83.2 6.4-25.6h-6.4l-64 83.2-96 128-70.4 76.8-19.2 6.4-32-12.8v-25.6l19.2-25.6 102.4-128 64-83.2 38.4-51.2v-6.4l-268.8 172.8-51.2 12.8-19.2-19.2v-32l12.8-12.8 76.8-57.6z m0 0" fill="#D97757" p-id="1571"></path></svg>',svgAnimated:'<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" fill="#D97757">\n <svg width="100" height="100" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" overflow="hidden">\n <animate attributeName="viewBox" calcMode="discrete" values="0 0 100 100;0 100 100 100;0 200 100 100;0 300 100 100;0 400 100 100;0 500 100 100;0 600 100 100;0 700 100 100" dur="0.720s" repeatCount="indefinite" />\n <path d="m19.622 66.499 19.675-11.033.325-.967-.325-.538h-.973l-3.297-.2-11.243-.301-9.73-.401-9.46-.502-2.378-.501L0 49.096l.216-1.454 2-1.354 2.865.251 6.324.451 9.514.652 6.865.402L38 49.097h1.622l.216-.652-.54-.401-.433-.402-9.838-6.67-10.649-7.02-5.567-4.063-2.973-2.056-1.514-1.906-.648-4.212 2.702-3.01 3.676.251.919.251 3.73 2.859 7.946 6.168 10.378 7.623 1.514 1.254.609-.411.093-.291-.703-1.154-5.621-10.18-6-10.381-2.703-4.313-.703-2.558c-.272-1.073-.432-1.961-.432-3.06L26.162.552 27.892 0l4.162.551 1.73 1.505 2.594 5.917 4.163 9.278 6.486 12.638 1.892 3.762 1.027 3.46.378 1.053h.649v-.602l.54-7.121.974-8.726.972-11.234.325-3.16L55.35 3.51l3.136-2.056 2.432 1.153 2 2.859-.27 1.855-1.19 7.724-2.324 12.086-1.513 8.124h.864l1.028-1.053 4.108-5.416 4.139-5.116 3.027-3.41 3.567-3.761 2.27-1.805h4.325l3.135 4.714-1.405 4.864-4.433 5.617-.95 1.254-5.27 7.06-3.27 5.678.293.468.788-.067 2.189-.4 6.433-1.154 7.675-1.304 3.46 1.605.378 1.655-1.351 3.36-8.217 2.006-9.621 1.956-4.625 1.216-.159.127.187.278 6.462.585 2.756.15h3.055l1.945.137 3.784.816 1.561 2.658-.55 2.181-3.75.995-3.882-.45-5.73-1.371-5.46-1.355h-.756v.452l4.54 4.463 4.193 4.174 1.595 2.688-.65 1.325-1.35 1.525-2.112-.635-1.388-.865L66 67.452h-.54v.702l1.837 2.708.753 1.388.49 2.45-1.49 1.8-3.1.882-2.3-.483-.9-.8-3.4-6.05-2.215-3.35-.574.363-2.831 30.23-1.298 1.554L47.405 100l-2.54-1.905-1.352-3.11 1.352-6.168 1.621-8.024 1.298-6.37 1.189-7.923.726-2.647-.064-.177-.58.097-5.974 8.193L34 84.252l-7.19 7.673-1.729.702-2.973-1.554.27-2.758 1.676-2.458L34 73.22l6-7.873 3.95-4.647-.1-.45-.234-.095-26.427 17.228-4.703.602-2.054-1.906.27-3.11.974-1.003zm21.192 52.148 8.753 16.491.408-.05 2.035-10.626 1.018-5.815 2.036-14.987 1.883-2.106 1.323-.351 2.85 1.905.305 1.203-.56 9.324-.865 7.568c-.288 3.793-.916 11.449-1.12 11.73-.203.281-.084 2.155 0 3.057l.866.452 1.374-1.354 2.9-4.461 5.751-7.769 7.888-11.228 3.97-1.053 2.544 1.654.458 1.905L80 123.158l-9.618 18.045-2.036 3.509.305.351 2.494-.351 6.514-1.403 5.649-1.705 4.987-1.253 4.682-1.153H94.5l2.548 1.153.502 1.999-1.2 3.4-2.406 1.017-5.649 1.705-9.974 2.506-8.55 2.306-.509.3 1.12.301 7.939.652h4.987l6.742.451 2.927.412 1.523 1.8-1.523 4.054-2.927.746h-3.2l-6.341-.746-13.079-2.156-2.29-.25-.458.25.458.351 3.817 3.359 6.158 4.26L77.659 169l3.541 3.15v3.15l-2.55 1.893h-2.1l-3.65-2.843-2.518-2.47-4.377-4.16-2.392-2.356-.254.15 4.071 7.469 2.162 3.871v3.996l-3.342 1.669-2.891-1.015-.79-1.341-6.488-9.987-.56-.301-.915.752-.329 3.85-.827 3.773-1.1 2.75-1.65 1.15h-3L46.2 181l-.276-1.898 1.76-12.585-.203-.752-1.425-.15-.458.3-1.653 2.284-.545.451-1.95 2.1-2.1 2.4-1.45 1.6-1.7.85-1.4.29-2.2-1.14v-2l.571-1.79 2.35-3.29 1.07-1.454-.306-.451-.407-.15-.509.15-1.476.752-4.53 2.456-3.765 2.406-6.361 4.21-4.02 2.356h-3.97l-1.476-1.203v-.852l1.018-2.155s1.187-1.103 1.73-1.604l2.29-2.206 1.578-1.554 1.628-1.002 4.53-2.857 7.786-4.562 9.211-5.413.305-.251v-.25l-.305-.151h-7.176l-11.145.151-11.959.25H5.7l-4.224-1.002L0 149.925v-1.704l.916-2.055 2.799-1.053 4.326.401 4.58.301 16.946 2.005 2.036.251 7.074.401v-.401l-.967-.702-14.402-10.025-8.397-6.015-6.565-4.261-1.323-3.709.305-2.306 1.323-1.353 1.527-1.253 1.629-.301 3.104 1.554 7.328 4.712 7.786 5.213 10.331 7.167.458-.2-5.496-8.471-4.427-7.77-5.09-7.719-3.358-6.466v-1.955L25.038 100l4.631.602 2.087 3.008zm-7.743 115.21c2.135 1.197 6.446 3.623 6.614 3.745l-4.147-8.857-2.152-4.908-5.46-9.009-4.986-7.135v-2.227c.453-.855 1.033-1.539 1.612-2.225.569-.671 1.138-1.343 1.59-2.178L27.927 200l4.724 1.873 3.517 4.555 2.1 4.605 3.045 9.362 6.561 14.12 1.313 2.631c.14-.455.44-1.488.525-1.973.083-.486.7-6.141.997-8.907l.787-12.045.683-6.528 2.52-4.049c.404-.318 3.989-1.113 3.989-1.113l2.572 2.131.84 2.474v9.616l-.84 4.149-2.205 10.729-.367 2.126v1.417l.367.607h.63l.893-.607 3.622-5.112 4.304-5.567 5.145-6.933 4.251-6.174 2.625-1.417 3.517-.202 2.31.506 1.522 2.682-1.784 3.796-9.45 14.119-7.558 12.601-.42.759.262.304h.263l2.1-.557 10.236-2.378 9.553-2.278 2.205-.607h4.567l1.26 2.379-1.26 3.137-.945.911-9.029 2.581-13.123 2.935-5.564 2.176-.263.102-.262.202.262.304h1.732l6.3.303h7.979l8.924.608 2.414.354 2.572.962 1.155 2.884-1.417 2.834-2.94 2.075-7.086-1.265-8.767-1.468-7.244-.607h-4.042v.304l.42.607 10.289 9.008 4.882 4.504 2.73 2.429.472 2.278s-1.465 1.601-2.047 2.125l-1.68.354-2.782-1.417-10.919-9.008-4.777-3.745-1.102-.86v.253l1.68 2.53 3.254 4.504 6.8 8.907.917 2.48-.393 1.872-2.82.503-3.479-.503-2.94-3.694-2.81-3.998-5.511-6.781-3.465-4.251-.315-.456-.525-.152c-.07.085-.23.274-.315.355s-.21 1.113-.262 1.619l-.577 10.577-.49 6.255-1.489 1.029-3.15.45-2.4-1.2-1.45-2.55v-1.64l.002-.016 1.05-11.134v-1.012l-.63-.405h-.577l-.63.152-5.932 6.326-.347.434-.336.295-2.4 1.65h-1.6l-1.8-1.65v-1.5l1.88-2.902 5.548-7.056.735-1.417v-1.771l-.473-.253h-.787l-4.567 2.682-4.042 2.025-1.614.972-.23.02h-2.35l-1.05-1.05-.9-2.1v-2l1.14-1.208 10.306-5.97.735-.253.157-.254-.367-.202h-.945l-2.745-.132-3.68-.431-3.35-.5-2.2-.55-1.5-1.3-.3-.85v-2.1l.9-1.7 3.6-1.5 2.995-.402 5.44-.403-9.291-6.984-17.218-11.336L3.99 225l-.315-1.973 1.89-3.188 3.36-1.62 3.254 1.215 10.236 6.427zM38.268 335.9l-4.456-2.448-3.204-2.117-.508-.235h-2.45l-1.6.95-1.55 2.5v1.9l1.6 2.083 6.425 4.659 3.614 2.906-.594.408H19.9l-.992.012-1.259 1.632v2.05l.95 2.3 2 1 7.076 1.115h.84c.197 0 2.97.05 3.217.152.198.082 2.36.102 3.416.102l.396.204v.204l-.396.357-2.327 1.938-1.832 1.173-2.97 2.142-4.06 2.754-1.98 1.325-1.683 1.02-.444.323L19 368.3v1.9l1.05 1.65 2 .35 3.25-.35.626-.219 1.649-1.106 2.128-1.173 1.09-.765 2.277-1.122 2.079-1.071.99-.408 1.436-1.02 1.04-.408 1.138-.459h.198v.102l-.149.204-2.376 2.805-1.535 1.785-2.821 3.111-1.337 1.529-2.03 2.091-2.673 3.621-.122.171-.258 2.132.35 1.9 1.3 1.3 3 .7 2.46-1.41.844-1.071 2.97-3.722 4.209-5.151 2.277-2.855.346-.459.396-.357.446.204.198.153-.198 1.479-.297 5.303-.743 7.853-.495 2.754-.198 2.652v1.784l1.776 2.754 2.828.204 1.832-.867s.759-1.479 1.04-2.091l.594-3.773.841-2.601 1.287-6.986 1.04-6.578.148-2.55.149-.867.346-.153.941.459.248.561 3.811 5.456 2.624 3.672 2.08 3.059 2.772 3.621 2.92 4.437 1.634.917h.792l1.832-.509.94-1.938-1.287-2.601-4.059-6.986-1.881-3.672-2.327-4.793-1.337-2.907 1.337.765 1.93 1.275.743.51 1.238.816 1.535 1.428 3.465 2.6 6.04 5.1c.577.427 1.164.845 1.751 1.265 1.379.984 2.76 1.97 4.04 3.069l1.436-.306c.764-.541 1.213-1.054 1.733-1.836l-.792-2.804-.495-1.071-5.644-4.437-3.168-3.008-4.456-3.825-2.722-2.244-4.703-4.283-1.931-1.683v-.357l1.782.357 9.555.867 7.03.816 6.188.816 5.693.204c.445-.17 1.366-.52 1.485-.561.489-.168.843-.571 1.173-.947l.064-.073.594-3.009-2.128-1.989-3.515-.866-9.258-.714-9.01-.561-5.445-.714-1.188-.255.445-.408 2.525-.561c.957-.374 2.92-1.122 3.119-1.122.198 0 2.624-.612 3.812-.918l6.485-1.632 3.218-.561 2.822-.612 4.802-1.427 1.732-2.142.99-3.621v-1.428l-2.277-1.326-4.109.204-2.376.714-5.1 1.071-6.187 1.326-1.584.408-5.891 1.275-1.98.306h-.298v-.561l.495-.714L75 332.585l3.466-6.272 4.406-7.548 1.633-2.855.545-2.091c0-1.007-.545-2.907-.545-2.907l-2.722-.969-4.01 1.479-4.258 4.233-1.188 1.53-5.05 6.017-2.87 3.723-4.01 4.844-3.812 4.029-.397.204-.148-.816.148-1.938.397-4.743 1.98-13.411.742-6.119.495-4.029v-2.142l-2.227-2.295L55.05 300l-2.673 3.314-.396 2.907-.396 5.609-.149 6.171-.693 6.731-.446 4.079-.396 1.632-.445 3.315-.347 3.212-.247.255-.297-.255-.495-1.529-1.139-3.162-1.04-2.04-2.128-4.079-.545-1.173-.643-1.275-7.327-12.851-5-8.567-2.97-1.173-1.882.867-1.98 5.712.248 2.957.89 1.632 4.704 7.7 2.772 4.743 1.139 1.938 2.425 3.773 1.733 3.009.693 1.326.248.663zm-3.027 97.937-2.39-5.488-.45-3.7 1.15-1.4 4.15-1.4h2l2.1 1.4 2.15 2.2 1.773 2.97 2.107 3.985 3.048 4.799.878-3.87.723-2.941.517-5.16.878-8.566.31-4.283.774-5.676 1.24-2.58 3.822-.98.827.98c.19.998.568 3.035.568 3.2v2.012l-.362 4.18-.62 4.076-.723 3.818-.93 6.399-.67 6.501 1.91-1.909 2.944-4.025 5.476-6.192 4.08-5.521 1.653-2.477 1.24-1.238 3.254-1.135 4.132 1.135 1.24 1.961v2.683l-2.944 6.14-2.118 3.509-4.029 5.624-2.84 3.922-5.476 7.946v.465l.775.155 3.874-.62 6.56-1.238 10.588-2.374 3.513-.825 3.822-.619 3.822 1.444.414.981-.672 3.251-3.564 2.064-2.79.98-6.972 2.27-5.527 1.497-7.438 1.806 1.911.412 2.893.568 3.667.361 9.659 1.548 3.46.516 1.654.361 2.17 1.961 1.135 3.199-1.136 2.477-2.686 1.032-2.48.207-6.87-.826-8.935-1.909-4.907-.981-6.25-.825 3.719 2.838 5.372 5.005 2.84 2.425 10.641 10.114 1.085 3.405-1.55 1.497h-1.394l-4.08-1.497-8.42-6.553-3.978-2.838-7.593-6.553.724 1.909 1.653 2.89 2.066 2.786 1.808 2.477 2.789 3.715 3.409 4.076.878 3.096-.878 3.354-.878.31-3.978-.31-2.22-3.354-2.015-3.508-2.066-3.148-2.325-3.509-2.53-4.231-1.292-1.754-2.118-3.612-1.652-2.632-.465-.309-.362.309-.568 3.87v2.064l-.878 4.489-.465 2.632-.775 5.521-1.653 10.836-.361 1.135-3.048.98H44.37l-1.756-2.631-.568-1.961 1.705-16.976 2.014-10.733.31-1.083-.568-.207-1.136 1.29-1.189 1.29-1.6 2.116-3.1 3.921-1.498 1.909-2.066 2.374-3.512 4.438-3.151 5.005-2.015 1.698-3.409-.202-1.394-2.477.464-.928 2.428-3.974 1.911-3.044 2.015-2.632 2.066-2.786 1.601-2.064 3.358-4.179 3.667-4.799 1.86-2.58-3.565 2.115-4.545 2.477-2.376 1.6-5.165 3.302c-.637.482-1.912 1.466-1.912 1.548 0 .045-.098.103-.53.357-.359.211-.947.556-1.897 1.14l-4.287 2.631-2.118.464-1.756-1.702-.362-2.787.362-.619 4.958-3.147 10.692-6.812 10.176-6.037h-2.79l-5.371-.361-7.541-.671-.126.005-8.903-.388-1.9-1.25-.75-1.9.75-2.55 3.25-1.45h3.862l4.281.258 7.955.413h1.86l1.033-.413-5.527-4.489-3.395-2.544-1.17-1.075-2.9-3.5v-2.7l1.15-1.65 1.75-.85h2.95l2.97 1.825 6.806 4.921.258-.155zm27 93.578 2.41-2.215 3.35-.4 2.45 1 2.25 2.1.45 2.9-1.05 3.35-1.65 4.1-.58 2.027-.07.189v.718c.305.086.968.257 1.184.257s2.493-.513 3.606-.77l3.283-.205 4.844-.924 7.965-1.54c1.5-.468 2.981-.808 4.495-1.154l.565-.13 1.668.976 2.584 2.053v.719l-.377.975-1.292 1.54-2.26.873-1.13.359-1.777.513-11.195 3.08-5.812 1.284-6.782 1.694c.072.085.258.277.43.359.173.082.862.137 1.185.154l1.937.36 1.238.256 1.992.257h.86l2.853.616 3.983.616 8.88 1.54 1.992.308 1.023.205 2.045 1.335v1.437L97.034 561l-1.291.924s-1.768.66-2.584.821h-1.453l-2.853-.308-2.045-.205c-.753-.086-2.4-.267-2.96-.308a174 174 0 0 1-2.745-.257l-5.49-.667-3.283-.308-4.09-.617h-1.453l.484.411.969 1.181 2.745 2.567c.646.684 2.002 2.074 2.26 2.156.259.082 2.045 1.642 2.907 2.412l1.291 1.181 2.745 2.361 5.275 3.953 1.184.976.915 2.104-.215 1.13-.539.616h-2.26c-1.47-.673-6.674-2.978-6.674-2.978s-.61-.53-.861-.718l-2.045-1.848-3.983-2.978-1.615-1.027-5.544-4.312-.484-.308h-.7v.565l.27.77 1.291 2.053.7 1.027.861 1.232 1.507 2.31 3.445 4.466 4.897 6.777.431 1.642-.43 2.516-2.692 1.54-2.206-.77s-1.683-2.017-2.476-3.08l-.969-1.181-2.368-3.132-2.26-2.772-2.046-3.234-.968-1.642-1.4-1.797-3.767-5.236-.377-.719h-.538l-.7.308v1.745l-.538 4.107-.323 2.978-1.13 8.727-.216 1.848-.807 9.548c-.072.325-.226.985-.269 1.027-.148.14-.264.338-.383.54-.112.19-.226.384-.37.538l-1.077.308-4.144-1.9-1.13-1.899v-1.797l.376-6.006.27-4.158.484-3.696 1.022-6.263.377-3.902v-1.334h-.377l-1.022.975-.485.616-.645.77-1.4 1.694-3.121 3.491c-.61.77-1.852 2.341-1.938 2.464s-.682.804-.969 1.129l-2.53 3.08-4.52 5.442c-.904 1.245-1.7 2.281-2.96 3.183-.582.415-1.169.413-1.835.411h-.008l-.06-.001h-.089l-2.045-.41-1.669-.976-.43-2.823.915-1.591.807-1.181.969-1.592 1.453-2.772.646-.77 1.56-2.104 1.077-1.489 1.346-1.643 1.614-1.848 2.046-2.721 1.83-2.053 1.237-1.335 3.068-3.336 1.83-2.567.485-.308.16-.257-.322-.103-.915.36-.861.565-1.13.718-1.615.719-1.076.873-1.938 1.129-2.422 1.437-1.991 1.335-3.122 2.002-6.512 4.312-2.368 1.592-2.96 1.54h-2.261l-1.292-1.797-.43-1.437.43-2.516.538-.873 1.561-1.078 4.413-3.08 2.584-1.95 2.153-1.489 2.637-1.489 1.238-.873 2.045-1.334 7.427-4.877.27-.205-.27-.308H21.415l-3.39.308-6.459.205-4.682-.205H5.323L3.6 551.195l.215-2.054 1.13-1.643 1.669-.718h6.512l3.39.308 4.63.41 3.605.411 6.136 1.078 4.682.616h4.79l-1.184-1.694-1.722-2.002-1.884-1.797-8.826-4.363-8.289-3.953-4.379-2.766-.282-.215-.75-2.3 1.4-2.9h2.1l2.75.35 4.06 1.516 1.775 1.079 5.328 3.593 4.199 1.643-1.238-1.643-1.992-3.593-.272-.475a291 291 0 0 0-2.51-5.52v-4.15l2.85-1.55h4.25l2 1.55 2.996 2.662 7.909 14.157 2.045 2.515v-9.548l-.45-7.356v-1.78l.95-2.75h2.1l2.25.75.6 2v6.9l.417 3.416c.143.189.452.586.538.668s.323.445.43.616l3.876-4.312zm3.813 99.929-2.211 2.764-.827 1.235c-.292.223-.898.72-.98.926-.084.206-1.034 1.39-1.499 1.956l-.723 1.029-.878.824h-.413v-3.242c0-6.68.204-8.63.828-14.593l.153-1.465-.206-1.904-.982-1.596-1.704-.566-1.602.257-1.188 1.699-.775 3.963a752 752 0 0 1-.968 8.164c-.154 1.248-.332 2.695-.581 4.754v3.088l-.103.566-.259.154h-.206l-.103-.103c-.083-.288-4.684-6.879-6.974-10.139l-5.423-8.8-2.738-4.221-3.202-1.955h-.775l-2.273 1.029-1.446 2.162.516 2.985 1.24 1.647 4.08 6.124 6.612 10.808 1.705 2.779.775 1.647-.207.824-.568.36h-.465l-2.325-1.801-7.024-5.456-4.597-3.705-4.236-3.243-3.616-2.882-3.615-2.573a9 9 0 0 1-.41-.223c-.459-.257-.978-.549-1.45-.549-.984 0-1.872.128-2.84.309l-.672.669v2.933c0 1.456 1.653 4.323 1.653 4.323l1.136 1.39 2.583 1.853 5.733 3.963 5.062 3.191c.258.103.827.37 1.033.617.207.247 2.428 1.544 3.513 2.162l2.014 1.338 2.376 1.544 1.188.875v.618l-.206.72-.569.206h-3.409l-7.696-.206h-6.818l-6.199-.412-6.146-.308H.517L0 647.606l1.085 2.78 1.136 1.132s4.79.645 6.922.772c2.13.127 5.423 0 5.423 0h8.058c.33 0 2.927-.137 4.184-.206.74.069 2.262.206 2.427.206s2.136-.137 3.1-.206h5.217l.516.206.362.566v.618l-.62.463-5.734 3.603-3.099 2.058-11.777 7.978-4.493 3.293-2.79 1.956.982 2.831 1.808.926h1.033l3.977-2.11s6.026-3.757 8.884-5.61l1.911-1.081 3.1-2.418 1.394-.978 3.977-2.316 2.635-1.956c.327-.172 1.033-.515 1.24-.515.206 0 .637-.309.826-.463h.465l.206.463-.361.361-3.203 4.168c-.602.721-1.807 2.203-1.807 2.368s-3.1 4.289-4.65 6.33l-2.169 2.831-1.653 2.522c-1.532 2.024-4.803 6.485-4.803 6.485l-1.343 2.161.258 3.14.361.772 1.912.617h1.91l2.428-.617c1.594-2.381 3.323-4.769 5.061-7.168 1.813-2.502 3.635-5.017 5.322-7.552 1.102-1.99 3.337-6.001 3.46-6.124.124-.124 2.841-4.615 4.184-6.845l1.705-2.471.981-1.184h.362v.567l-.362 2.11-1.394 4.426-.93 2.161-.362 1.853-2.117 11.735c-.448 2.127-1.385 6.495-1.55 6.948-.207.566-1.24 6.021-1.24 6.227 0 .165-.24 1.03-.361 1.441l1.601 1.956.672.772 2.272.412h2.015l2.17-1.905.619-.926.981-5.816.569-5.713c.24-1.921.754-5.805.878-5.97.124-.164.43-3.774.568-5.558.183-1.61.31-4.787.31-4.787l.568-3.448.465-.823.361.309.569.823 4.545 7.926 1.653 3.139 5.992 11.529s1.903 1.671 2.582 2.573c.248.33 1.068.995 1.447 1.287l2.014.412 2.376-.824q.123-.465.24-.925c.179-.705.356-1.404.587-2.111v-1.853l-4.288-6.794-2.84-4.529-2.428-4.117-1.447-2.265 1.343 1.03 1.912 1.492 4.235 3.86 4.649 3.912 2.582 2.316 4.236 3.396 2.17 1.081 1.343-.206 1.342-1.132s-.189-2.161-.258-3.139l-2.118-2.316-3.977-4.272-5.01-5.147-5.734-6.124-1.394-1.338-2.066-1.596-.569-.875v-.617c.018-.121.104-.361.31-.361s1.12.24 1.55.361l13.326 2.11 10.228.978h1.653l1.962-.978 1.24-2.471v-.875l-.981-1.441-1.602-.875-4.648-.566-5.217-.514-2.635-.206-9.349-1.184-5.268-.463h-.982l-.258-.618.258-.309 1.601-.257 6.882-1.842 1.499-1.499.75-1.95v-1.9l-.75-1.8-1.7-.85h-2.858l-1.24.371h-2.84l-.93-.823c-.07-.155-.207-.505-.207-.669v-1.184l.153-.225-.028-.02 1.7-3.85 1.8-3.4.7-3v-2.2l-2.5-2.15H68.2zm4.076 98.536a398 398 0 0 1 2.87-2.681l3.1-.9 2.95.9 1.2 2.8v2.6l-1.2 3.1-.573 1.069a73 73 0 0 0-1.463 1.974l-5.439 8.299-1.488 1.701c0 .138.072.485.36.774.287.288.598.12.718 0 .427.017 1.282.041 1.282 0 0-.042 2.634-.533 3.951-.774l4.183-.469 2.469.776.55 2-.55 2.8-1.1 1.35-1.7.95-2.28.797-2.752.508c-1.454.292-4.443.897-4.772.979-.328.083-.889.241-1.128.309l.77.258 2.821.413 3.49.618.763.044.638.174 2.1.9.65 1v.95l-1.8 1.85-2 .9-3.35-.35-3.854-.46-.228-.059-2.514-.31h-.873v.31l1.18.927 1.386 1.289 2.103 2.114 1.847 1.752.578.47.375 1.017-.25 1.6-2.35 2.55h-2l-2.682-1.399-.187-.114c-.256-.275-.852-.876-1.18-1.083s-.376.086-.359.258l.77 1.547.77 1.237.871 2.062.873.979 3.9 5.928 2.257 3.35 1.385 2.423 1.898 2.99v1.546l-.359.825-1.077.773-3.233-.464s-3.167-3.321-4.771-5.103l-1.745-2.629c-1.248-1.529-3.827-4.67-4.156-5s-.923-1.374-1.18-1.855c-.718-.877-2.216-2.66-2.463-2.784s-2.36-2.904-3.386-4.278l-.667-.722-.462-.361-.308 1.083-.256 2.371-.667 2.577c-.394 2.698-1.18 8.145-1.18 8.351v2.68l-1.642 10.825c-.795.399-2.668 1.083-2.668 1.083l-2.976-.464-1.54-2.629v-1.289c.155-1.306.452-4.041.411-4.536-.04-.495.496-2.646.77-3.66l1.334-5.103 2-9.227.924-3.608-.41-.722h-.872c-.137 0-.462.062-.667.309l-.02.025c-.285.342-1.22 1.47-1.52 1.47-.246 0-1.402 2.131-1.95 3.196-.41.481-1.303 1.485-1.59 1.65s-.94 1.168-1.231 1.649l-1.54 2.114-1.693 1.855-2.155 2.938c-.342.361-1.026 1.104-1.026 1.186s-2.257 2.887-3.386 4.278l-1.386 1.65-3.437 2.68h-3.13l-.956-1.708-.275-2.622 5.849-7.113 2.565-3.144 6.465-8.145 1.437-1.546 1.129-1.856.513-.361-.514-.464h-.461l-1.232.464c-.906.498-2.811 1.495-3.18 1.495-.27 0-1.1.563-1.837 1.062-.523.355-.999.678-1.191.742-.37.124-5.285 2.663-7.696 3.918l-6.927 4.02-1.744.413-2.412-.413-.41-2.628 1.231-2.114 6.362-5 8.158-5.361 7.953-5.155.36-.36v-.464l-1.13-.31h-2.616c-2.121-.189-6.475-.567-6.927-.567s-1.864-.206-2.514-.309l-9.954-1.495c-2.172-.257-6.772-.773-6.772-.773l-2.617-.773-2.053-2.474-.41-1.031 1.642-2.114 2.104-1.031h1.077l5.336.619 6.568.412H19.6l4.31.619 14.11 1.082h1.539v-1.082c-.171-.155-.565-.495-.77-.619-.205-.123-.599-.532-.77-.721l-2.565-1.908-1.847-1.34c-.428-.464-1.344-1.474-1.59-1.804-.247-.33-1.061-.962-1.437-1.237l-1.232-.773-15.238-12.423c-1.904-1.363-5.49-4.279-5.49-4.279v-2.835s.678-.914 1.026-1.237h4.464l3.95 2.887 1.54 1.443 7.388 4.846 7.286 5.103 2.052 1.649h.565l.308-.412-.308-1.237-.565-1.598-1.334-3.093-3.745-7.268-2.617-5.619-2.411-4.33v-5.258l1.539-.824h1.847l2.052.824 1.899.928c.24.447.728 1.402.77 1.65.04.247.769 1.546 1.128 2.165l1.437 2.062 3.9 6.082 5.746 9.588 4.669 7.577.256.361.513.567.821-.309V730c.253-3.301.694-6.585 1.135-9.876.332-2.474.664-4.952.918-7.444l1.18-4.175 2.822-1.65h2.822l1.744 2.835-.41 6.083c-1.013 4.859-1.653 9.803-2.292 14.736a572 572 0 0 1-.684 5.161l.308.309.872-.876 2.822-2.526 2.77-2.99z"/>\n </svg>\n</svg>\n'},{match:/gpt|o1|o3|o4/i,name:"OpenAI",color:"var(--bg-model-avatar)",svg:'<svg t="1771495569354" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2752" width="200" height="200"><path d="M565.265178 954.519092c-22.289934 0-48.400999-8.151747-67.952455-14.838727a103.425292 103.425292 0 0 1-26.875292-11.272338c-12.737105-7.769634-15.411897-8.342804-19.806198-24.773669 21.971506-5.158528 81.581157-41.905075 103.871091-55.342721 148.896757-89.159735 119.028246-10.444426 119.028246-364.981743 15.029784 3.566389 82.791182 32.415932 82.791182 57.316972 0 133.102747 20.570425 273.847757-52.604243 354.91943-22.799418 25.47421-91.834527 58.972796-138.388646 58.972796z m-433.061569-299.321966c258.626916 136.860193 184.369594 157.048504 357.721593 52.094759 44.579867-27.193719 90.433445-49.292596 132.593263-77.568969v101.896839c-95.528287 22.226248-272.319304 227.038896-419.050754 100.686815l-25.856323-25.155782c-37.319718-43.943012-45.344094-72.410442-45.344094-151.889977z m375.744596-19.105658c-19.933569-13.310275-79.479535-51.330533-101.896839-57.316972v-133.739602a1158.312326 1158.312326 0 0 0 101.896839-57.316973c43.943012 10.189684 70.690933 47.063603 114.633945 57.316973v127.371049c-17.831947 12.10025-95.846715 58.718054-114.633945 63.749211z m-426.693016-178.31947c0-63.685525-4.26693-90.306074 38.84817-145.776166 23.945757-30.88748 47.509402-39.612396 82.090641-57.953828v261.110652c44.134069 23.372588 83.873836 49.037854 129.345301 74.448379l131.765351 78.396881c-59.545966 15.921381-63.685525 61.32916-109.602788 33.753328-104.699003-62.730242-272.38299-129.345301-272.38299-243.91556z m866.123138 127.37105c0 79.543221-47.573087 161.188063-121.002497 178.31947v-165.582365c0-82.791182 9.743885-84.574377-48.910483-116.608196L565.265178 362.371082c15.79401-23.62733 22.608361-19.105657 48.146256-34.835982 41.714019-25.47421 39.039227-16.112438 117.053995 28.785857 94.190891 54.196382 216.849212 100.559444 216.849212 228.885777z m-541.326961-197.425127v-95.528287c43.751956-23.181531 90.688187-50.94842 133.357489-76.804743 82.154327-49.547338 95.528287-63.303412 185.006449-63.303412 48.464684 0 102.533695 36.746548 125.651541 65.405034 42.223503 52.22213 39.930824 92.662439 39.930824 151.125751-31.078536-16.494551-192.393971-121.002497-222.899337-121.002498s-229.650003 123.422547-261.110652 140.108155z m-50.94842 159.213812c-16.36718-10.95391-63.112355-39.99451-82.791183-44.579867 0-168.320842-33.880699-314.606493 67.952455-390.519639 56.043262-41.714019 113.169178-53.814269 181.376375-30.696423 25.47421 8.661231 35.536523 20.888852 56.36169 26.429493-11.781822 16.048752-80.68956 50.311565-102.278953 63.303412-154.564769 93.235608-120.620384 7.451206-120.620384 376.063024z m-292.953415 121.002498c0 169.148754 115.143429 280.853165 274.293556 273.847756 59.800708-2.674792 26.811606-7.705949 69.417222 25.47421 97.820966 76.741057 228.822091 73.747838 319.637649 1.018969a251.939936 251.939936 0 0 0 52.604244-55.661149c58.20857-85.274918-10.95391-45.598836 81.96327-83.619094 130.236898-53.241099 199.399378-217.358696 128.64476-355.428914-27.448461-53.559526-40.249252-28.849543-28.276373-104.699003 18.723544-118.582447-63.176041-230.032116-157.621674-269.771884-98.90362-41.586648-129.090559 12.737105-178.892639-37.574459A161.888604 161.888604 0 0 0 580.103905 28.913674C474.003821-27.766443 331.284559 1.528898 258.428319 93.681853c-81.326415 102.979494 9.489143 54.705866-92.407697 98.648878C15.149614 257.353652-33.251385 439.175825 41.579107 561.06992c56.807488 92.598753 20.570425 4.967471 20.570424 106.800625z" fill="#EFA474" p-id="2753"></path></svg>'},{match:/gemini/i,name:"Gemini",color:"var(--bg-model-avatar)",svg:'<svg t="1771495622863" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4556" width="200" height="200"><path d="M960 512.896A477.248 477.248 0 0 0 512.896 960h-1.792A477.184 477.184 0 0 0 64 512.896v-1.792A477.184 477.184 0 0 0 511.104 64h1.792A477.248 477.248 0 0 0 960 511.104z" fill="#448AFF" p-id="4557"></path></svg>'},{match:/qwen/i,name:"Qwen",color:"var(--bg-model-avatar)",svg:'<svg t="1771495640319" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5634" width="200" height="200"><path d="M537.782857 57.161143c16.749714 29.44 33.426286 58.953143 50.102857 88.502857a7.68 7.68 0 0 0 6.692572 3.913143h236.873143c7.424 0 13.750857 4.681143 19.017142 13.933714l62.061715 109.677714c8.082286 14.372571 10.24 20.370286 1.024 35.693715a2262.893714 2262.893714 0 0 0-32.438857 55.478857l-15.652572 28.086857c-4.534857 8.338286-9.508571 11.922286-1.718857 21.833143l113.152 197.851428c7.314286 12.8 4.754286 21.065143-1.828571 32.841143-18.651429 33.499429-37.632 66.742857-56.978286 99.84-6.765714 11.593143-14.994286 16.018286-29.001143 15.798857a1833.398857 1833.398857 0 0 0-99.291429 0.658286 4.242286 4.242286 0 0 0-3.437714 2.157714 24571.830857 24571.830857 0 0 1-115.419428 202.24c-7.204571 12.507429-16.201143 15.469714-30.939429 15.506286-42.532571 0.146286-85.430857 0.182857-128.731429 0.109714a22.930286 22.930286 0 0 1-19.821714-11.556571l-56.978286-99.108571a3.84 3.84 0 0 0-3.547428-2.121143h-218.331429a76.288 76.288 0 0 1-34.377143-3.913143l-68.388571-118.198857a23.149714 23.149714 0 0 1-0.073143-23.04l51.492572-90.441143a8.448 8.448 0 0 0 0-8.411429 23594.496 23594.496 0 0 1-80.018286-139.593143L47.542857 425.325714c-6.838857-13.202286-7.387429-21.138286 4.022857-41.179428 19.858286-34.669714 39.570286-69.302857 59.209143-103.936 5.632-9.984 12.946286-14.262857 24.905143-14.262857 36.827429-0.182857 73.654857-0.182857 110.445714-0.073143 1.901714 0 3.657143-1.024 4.571429-2.669715l119.734857-208.859428a20.845714 20.845714 0 0 1 17.993143-10.496c22.381714-0.036571 44.946286 0 67.547428-0.256l43.410286-0.987429c14.555429-0.109714 30.866286 1.389714 38.4 14.518857z m-146.432 17.188571a2.56 2.56 0 0 0-2.194286 1.28l-122.331428 213.942857a6.692571 6.692571 0 0 1-5.741714 3.364572H138.788571c-2.377143 0-2.962286 1.060571-1.755428 3.145143l247.917714 433.334857c1.060571 1.792 0.548571 2.633143-1.462857 2.669714l-119.222857 0.658286a9.289143 9.289143 0 0 0-8.557714 4.937143l-56.32 98.56c-1.865143 3.328-0.914286 5.046857 2.925714 5.046857l243.858286 0.365714c1.974857 0 3.401143 0.841143 4.425142 2.56l59.867429 104.704c1.974857 3.474286 3.913143 3.510857 5.924571 0l213.577143-373.76 33.426286-58.953143a2.340571 2.340571 0 0 1 4.096 0l60.745143 107.958857a5.193143 5.193143 0 0 0 4.571428 2.633143l117.906286-0.841143a1.718857 1.718857 0 0 0 1.462857-2.56l-123.721143-217.014857a4.608 4.608 0 0 1 0-4.827428l12.507429-21.613715 47.798857-84.370285c1.024-1.755429 0.512-2.633143-1.499428-2.633143H392.521143c-2.486857 0-3.108571-1.097143-1.828572-3.291429l61.184-106.861714a4.571429 4.571429 0 0 0 0-4.864l-58.258285-102.253714a2.56 2.56 0 0 0-2.267429-1.316572z m268.361143 342.198857c1.974857 0 2.486857 0.841143 1.462857 2.56l-35.474286 62.500572-111.542857 195.620571a2.377143 2.377143 0 0 1-2.121143 1.243429 2.486857 2.486857 0 0 1-2.121142-1.243429l-147.346286-257.353143c-0.841143-1.462857-0.402286-2.230857 1.206857-2.304l9.216-0.512 286.793143-0.512h-0.073143z" fill="#7D5DED" p-id="5635"></path></svg>'},{match:/kimi|moonshot/i,name:"Kimi",color:"var(--bg-model-avatar)",svg:'<svg t="1771495664798" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6649" width="200" height="200"><path d="M731.062857 590.262857v318.317714h-148.589714V443.977143a146.285714 146.285714 0 0 1-146.285714 146.285714l-214.491429-0.036571v318.354285H73.142857V165.814857h148.553143v275.858286h180.882286l119.771428-275.858286h167.753143l-67.84 156.269714a255.524571 255.524571 0 0 1-106.678857 119.588572h66.925714a148.553143 148.553143 0 0 1 148.516572 148.589714z m120.758857-473.965714a99.035429 99.035429 0 0 1 0 198.070857h-99.035428V215.332571a99.035429 99.035429 0 0 1 99.035428-99.035428z" fill="currentColor" p-id="6650"></path></svg>'},{match:/glm|chatglm/i,name:"GLM",color:"var(--bg-model-avatar)",svg:'<svg data-name="glm" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 217.2 200"> <defs> <style> .st0 { fill: currentColor; } </style> </defs> <path class="st0" d="M86.8,190.4H0L131.3,4.8h85.8L86.8,190.4h0ZM212.8,190h-107.9l14.9-21.6c2.3-3.3,6-5.2,9.9-5.2h83.1v26.8h0ZM99.4,26.3c-2.3,3.3-6,5.2-9.9,5.2H6.4V4.8h107.9l-14.9,21.6Z"/> </svg>'},{match:/minimax|abab/i,name:"MiniMax",color:"var(--bg-model-avatar)",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 8l4-4 4 4 4-4 4 4v8l-4 4-4-4-4 4-4-4z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/></svg>'},{match:/deepseek/i,name:"DeepSeek",color:"var(--bg-model-avatar)",svg:'<svg t="1771495947541" class="icon" viewBox="0 0 1391 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11539" width="200" height="200"><path d="M1326.70201318 112.02090779c-12.94676356-6.47485468-18.53640721 5.86654827-26.0997327 12.13814316-2.57756953 2.02376031-4.77807747 4.65435413-6.9785854 7.08168819-18.91788751 20.63528526-41.02017805 34.19182812-69.92725218 32.57311444-42.23384508-2.42733405-78.29772513 11.12773591-110.16384908 44.10589703-6.77679853-40.66668282-29.28560862-64.94444203-63.55255448-80.52327231-17.95608583-8.09209545-36.06388005-16.1856638-48.63358202-33.78825438-8.74900746-12.5431898-11.12773591-26.50330641-15.52727888-40.26016327-2.7823022-8.29535522-5.56460442-16.79249731-14.92044538-18.20942411-10.19244639-1.61871367-14.16337637 7.08168818-18.15934561 14.36516325-15.93232553 29.74073376-22.12880269 62.51710799-21.49692994 95.69705596 1.36684831 74.65672404 32.27117059 134.13819156 93.62469006 176.42358804 6.9800583 4.8546681 8.77551959 9.71080912 6.57501165 16.79102439-4.17271686 14.56695011-9.18056624 28.7303265-13.55506995 43.29727663-2.78377509 9.30723537-6.95501906 11.32952278-16.74241882 7.28347507-33.66158524-14.36516325-62.745407-35.60875491-88.46513227-61.30196806-43.62425973-43.09548975-83.0772755-90.64060097-132.26613965-127.86659667a581.67054343 581.67054343 0 0 0-35.07703915-24.48101901c-50.20074429-49.77065841 6.57501167-90.63912807 19.72650789-95.49526908 13.73181759-5.05792788 4.77955037-22.4572587-39.65480265-22.25547181s-85.07599655 15.3770434-136.87041526 35.60875491c-7.58541892 3.03416756-15.55379103 5.25971475-23.69596499 7.08168819-47.03990759-9.10544849-95.84876434-11.12773591-146.8596019-5.26118765-96.02551195 10.92594905-172.73103555 57.25739323-229.12678412 136.36373875-67.72674425 95.09022244-83.68558192 203.13015422-64.13582165 315.82149435 20.48504978 118.76262107 79.88992666 217.09027084 171.13736114 293.97106918 94.6350973 79.71317902 203.61031862 118.76262107 327.93607117 111.27735913 75.51542292-4.45256725 159.57953934-14.77020989 254.41642354-96.71040901 23.92426399 12.13961607 49.03715574 16.99575708 90.66564019 20.63675815 32.09295007 3.03416756 62.97223311-1.61871367 86.87145788-6.67664152 37.45429471-8.09209545 34.84874013-43.49906349 21.31870939-49.97244528-109.7838417-52.19946535-85.68283009-30.95587367-107.58333373-48.15194474 55.78891504-67.37324899 139.85303146-137.3770918 172.73103555-364.17669887 2.60408167-18.00616433 0.40357375-29.33568711 0-43.90263724-0.20325977-8.90218873 1.76894914-12.34287584 11.75960867-13.35328309 27.49014733-3.23742733 54.19671351-10.92594905 78.70277179-24.68280588 71.11440706-39.65480265 99.81822142-104.80250446 106.59649284-182.89844271 1.01188015-11.9363563-0.20178686-24.27775924-12.56970195-30.54935413M706.87018452 814.87993343c-106.36966673-85.37941333-157.98733782-113.5014334-179.30604722-112.28776638-19.92829476 1.21366703-16.33737217 24.48101902-11.96286844 39.65480264 4.5777635 14.97199677 10.57098089 25.2896394 18.94145384 38.44113563 5.76786417 8.70040186 9.76383341 21.64863831-5.78995762 31.35944742-34.26841876 21.64863831-93.82647692-7.28347506-96.60730623-8.69892897-69.3454579-41.67856295-127.33635378-96.710409-168.1797842-171.97249368-39.45154288-72.43117687-62.33888747-150.1220685-66.13306983-233.07267483-1.01188015-20.02992464 4.77955037-27.11161282 24.27923214-30.75408682a235.19659216 235.19659216 0 0 1 77.91771774-2.02228741c108.59668681 16.18713669 201.05631542 65.75453531 278.54394728 144.25552022 44.23256614 44.71125762 77.69089163 98.12439001 112.1861365 150.32385536 36.64567431 55.43394691 76.0986901 108.24024576 126.29943438 151.53604947 17.72778682 15.17378365 31.86465106 26.7065662 45.41972102 35.20370829-40.84343042 4.65435413-108.99878765 5.66476139-155.60860936-31.96628094m51.00936468-334.83953883c0-8.90218873 6.9815312-15.98387693 15.75557791-15.98387693q2.98408908 0.05155138 5.36134463 1.01188017a15.85720779 15.85720779 0 0 1 10.16740714 14.97199676 15.78061715 15.78061715 0 0 1-15.73053865 15.98387691 15.60386953 15.60386953 0 0 1-15.55379103-15.98387691m158.39238446 82.95060635c-10.1423679 4.24930749-20.30830215 7.89178146-30.09570191 8.29535522-15.12370514 0.81009328-31.66286419-5.46150162-40.61513142-13.15002332-13.96011661-11.93782919-23.92573689-18.61447073-28.09845373-39.45301577-1.79546129-8.90218873-0.81009328-22.65904557 0.78505403-30.54935414 3.59092258-16.99575708-0.40504665-27.92023321-12.13961606-37.8343021-9.55910075-8.09356835-21.72522894-10.31911553-35.07703915-10.31911552-4.98281013 0-9.55910075-2.22407429-12.94823645-4.04604774a13.27669246 13.27669246 0 0 1-5.76639128-18.61299783c1.39041466-2.8323807 8.16868608-9.71228202 9.7623605-10.92594905 18.13136058-10.52090241 39.04649623-7.08021529 58.36795748 0.81009328 17.93104659 7.48526194 31.46107731 21.24359167 51.01083757 40.6666828 19.92829476 23.46913885 23.51921733 29.94399353 34.84874013 47.54511123 8.97877936 13.75685685 17.14746545 27.92023321 22.71206987 44.10442409 3.41270206 10.11732865-0.98684091 18.41121097-12.74644958 23.46913885" fill="#4D6BFE" p-id="11540"></path></svg>'}],_modelInfoCache=new Map;function getModelInfo(modelName2){if(!modelName2)return null;const cached=_modelInfoCache.get(modelName2);if(cached)return cached;let info=null;for(const provider of MODEL_PROVIDERS)if(provider.match.test(modelName2)){info={name:modelName2.replace(/^claude-/,"").replace(/-\d{8,}$/,""),provider:provider.name,color:provider.color,svg:provider.svg,svgAnimated:provider.svgAnimated||null};break}return info||(info={name:modelName2,provider:modelName2,color:"var(--bg-model-avatar)",svg:null}),_modelInfoCache.set(modelName2,info),info}const AUTO_APPROVE_DEFAULTS={Claude:3,OpenAI:3,Gemini:5,DeepSeek:5,Qwen:5,GLM:10,Kimi:10,MiniMax:10};function getAutoApproveDefault(modelName2){const info=getModelInfo(modelName2);return info&&AUTO_APPROVE_DEFAULTS[info.provider]||10}function getSvgAvatar(type){return"user"===type?'<svg viewBox="0 0 24 24"><path d="M12 12c2.7 0 4.8-2.1 4.8-4.8S14.7 2.4 12 2.4 7.2 4.5 7.2 7.2 9.3 12 12 12zm0 2.4c-3.2 0-9.6 1.6-9.6 4.8v2.4h19.2v-2.4c0-3.2-6.4-4.8-9.6-4.8z"/></svg>':"agent"===type?'<svg viewBox="0 0 24 24"><path d="M12 2a2 2 0 012 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 017 7h1a1 1 0 011 1v3a1 1 0 01-1 1h-1.17A7 7 0 0113 22h-2a7 7 0 01-6.83-3H3a1 1 0 01-1-1v-3a1 1 0 011-1h1a7 7 0 017-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 012-2zM9.5 13a1.5 1.5 0 100 3 1.5 1.5 0 000-3zm5 0a1.5 1.5 0 100 3 1.5 1.5 0 000-3z"/></svg>':"sub-search"===type||"sub-explore"===type?'<svg viewBox="0 0 1024 1024"><path d="M128.957606 76.608479v495.401496c0 20.428928-17.875312 38.304239-38.304239 38.304239S52.349127 592.438903 52.349127 572.009975V38.304239c0-20.428928 17.875312-38.304239 38.30424-38.304239h426.453865c20.428928 0 38.304239 17.875312 38.304239 38.304239s-17.875312 38.304239-38.304239 38.30424H128.957606z m127.680798 127.680798v495.401496c0 20.428928-17.875312 38.304239-38.304239 38.304239S180.029925 720.119701 180.029925 699.690773V165.985037c0-20.428928 17.875312-38.304239 38.30424-38.304239h426.453865c20.428928 0 38.304239 17.875312 38.304239 38.304239s-17.875312 38.304239-38.304239 38.30424H256.638404z m579.670823 291.112219v-150.663341H399.640898v515.830424h76.608479c0 38.304239 30.643392 68.947631 43.411471 89.376558h-145.55611c-33.197007 0-61.286783-28.089776-61.286783-63.840399V321.755611c0-35.750623 28.089776-63.840399 61.286783-63.840399h490.294264c33.197007 0 61.286783 28.089776 61.286784 63.840399V564.349127c-20.428928-22.982544-58.733167-56.179551-89.376559-68.947631zM486.46384 411.13217h255.361596c15.321696 0 25.53616 10.214464 25.53616 25.536159s-10.214464 25.53616-25.53616 25.53616H486.46384c-15.321696 0-25.53616-10.214464-25.536159-25.53616s10.214464-25.53616 25.536159-25.536159z m0 102.144638h102.144639c15.321696 0 25.53616 10.214464 25.536159 25.53616s-10.214464 25.53616-25.536159 25.536159h-102.144639c-15.321696 0-25.53616-10.214464-25.536159-25.536159s10.214464-25.53616 25.536159-25.53616z m503.062345 492.84788c-2.553616 2.553616-7.660848 10.214464-12.76808 10.214464-10.214464 10.214464-35.750623 10.214464-45.965088 0l-81.71571-71.501247c-28.089776 17.875312-63.840399 28.089776-99.591023 28.089776-102.144638 0-186.413965-84.269327-186.413965-186.413965s84.269327-186.413965 186.413965-186.413965 186.413965 84.269327 186.413965 186.413965c0 38.304239-10.214464 71.501247-30.643391 99.591022l81.715711 71.501247c12.76808 12.76808 12.76808 35.750623 2.553616 48.518703z m-240.039901-324.309227c-58.733167 0-104.698254 48.518703-104.698254 104.698255 0 58.733167 48.518703 104.698254 104.698254 104.698254s104.698254-48.518703 104.698255-104.698254c2.553616-58.733167-45.965087-104.698254-104.698255-104.698255z" fill="currentColor"/></svg>':"sub-plan"===type?'<svg viewBox="0 0 1024 1024"><path d="M674.507676 598.338391 287.079856 598.338391c-14.136975 0-25.638937 11.499915-25.638937 25.63689 0 14.137998 11.501962 25.640983 25.638937 25.640983l387.42782 0c14.137998 0 25.640983-11.501962 25.640983-25.640983C700.148659 609.838306 688.646698 598.338391 674.507676 598.338391zM794.746154 384.583029c-14.137998 0-25.640983 11.501962-25.640983 25.63996l0 494.299873c0 0.130983 0 0.280386-0.001023 0.433882-0.899486 0.279363-2.665713 0.644683-5.764284 0.644683L200.047664 905.601426c-4.312212 0-7.564279-2.971681-7.564279-6.913457L192.483384 191.851493c0-4.493338 0.974188-8.28878 1.811252-9.821693l373.337917 0c14.136975 0 25.63996-11.501962 25.63996-25.63996 0-14.136975-11.501962-25.638937-25.63996-25.638937l-374.069581 0c-30.336936 0-52.357462 25.696242-52.357462 61.099566l0 706.836477c0 32.086789 26.396183 58.19133 58.84113 58.19133l563.293223 0c34.119075 0 57.042157-21.041222 57.042157-52.356438L820.382021 410.224012C820.383044 396.086014 808.883129 384.583029 794.746154 384.583029zM674.507676 745.295394 287.079856 745.295394c-14.136975 0-25.638937 11.499915-25.638937 25.63689 0 14.137998 11.501962 25.640983 25.638937 25.640983l387.42782 0c14.137998 0 25.640983-11.501962 25.640983-25.640983C700.148659 756.795309 688.646698 745.295394 674.507676 745.295394zM879.595634 157.107177c-3.77293-14.409175-12.871145-28.250414-24.964578-37.975916l-43.827181-35.240619c-12.880355-10.352789-29.27679-16.290011-44.986587-16.290011-16.876366 0-31.594579 6.747681-41.439808 18.995633l-19.624966 24.381293c-6.380314 7.968485-7.987928 17.577331-5.222955 26.916023l-114.241904 142.063553-2.486634 3.090385-22.812565 85.303828c-9.749038 30.859845 4.449335 48.075949 13.806447 55.608505 6.783497 5.450129 14.468526 8.728802 22.851451 9.754155 0.984421 0.246617 2.125407 0.488117 3.440355 0.632403 1.003863 0.110517 2.053776 0.167822 3.118014 0.167822l0.014326 0c4.588505 0 10.047844-0.9967 17.180288-3.13541l2.877537-1.065262 83.402525-41.897226 119.874181-149.07934c0.440022 0.017396 0.880043 0.032746 1.320065 0.032746 9.218966 0 17.411555-3.862981 23.077601-10.892071l19.562545-24.342408C880.924909 191.1976 884.15037 174.495196 879.595634 157.107177zM674.469813 348.564697l-56.738235 28.537963c-2.958378 0.579191-5.734608 1.684362-8.277524 3.296069-0.313132 0.198521-0.615007 0.385786-0.905626 0.562818 0.12382-0.318248 0.25378-0.639566 0.39295-0.971118 0.99977-2.437515 1.588171-5.022387 1.753947-7.702426l17.732873-66.078974 105.73209-131.488707 48.647977 39.113833L674.469813 348.564697zM831.385633 172.919305l-7.679913 9.550517-68.139913-54.779627 7.687076-9.56382c0.291642-0.132006 1.144056-0.38374 2.604314-0.38374 4.28356 0 9.735735 2.071172 13.570063 5.15644l43.832298 35.245735c3.493567 2.805906 6.421246 7.018857 7.642051 10.993378C831.497173 171.081447 831.492056 172.446537 831.385633 172.919305zM487.474932 291.067168l-200.394053 0c-14.136975 0-25.638937 11.501962-25.638937 25.63996 0 14.136975 11.501962 25.637913 25.638937 25.637913l200.394053 0c14.137998 0 25.63996-11.500938 25.63996-25.637913C513.114892 302.56913 501.611907 291.067168 487.474932 291.067168zM674.507676 438.023148 287.079856 438.023148c-14.136975 0-25.638937 11.500938-25.638937 25.638937s11.501962 25.638937 25.638937 25.638937l387.42782 0c14.137998 0 25.640983-11.501962 25.640983-25.638937S688.646698 438.023148 674.507676 438.023148z" fill="currentColor"/></svg>':"teammate"===type?'<svg viewBox="0 0 24 24"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z" fill="currentColor"/></svg>':'<svg viewBox="0 0 1024 1024"><path d="M810.666667 384l53.333333-117.333333L981.333333 213.333333l-117.333333-53.333333L810.666667 42.666667l-53.333334 117.333333L640 213.333333l117.333333 53.333334L810.666667 384zM810.666667 640l-53.333334 117.333333L640 810.666667l117.333333 53.333333L810.666667 981.333333l53.333333-117.333333L981.333333 810.666667l-117.333333-53.333334L810.666667 640zM490.666667 405.333333L384 170.666667 277.333333 405.333333 42.666667 512l234.666666 106.666667L384 853.333333l106.666667-234.666666L725.333333 512l-234.666666-106.666667z m-64.426667 148.906667L384 647.253333l-42.24-93.013333L248.746667 512l93.013333-42.24L384 376.746667l42.24 93.013333 93.013333 42.24-93.013333 42.24z" fill="currentColor"/></svg>'}function formatTokenCount(n){return null==n||0===n?"0":n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":String(n)}function stripPrivateKeys(obj){if(Array.isArray(obj))return obj.map(stripPrivateKeys);if(obj&&"object"==typeof obj){const result={};for(const key of Object.keys(obj))key.startsWith("_")||(result[key]=stripPrivateKeys(obj[key]));return result}return obj}function computeTokenStats(requests){var _a,_b,_c;const byModel={};for(const req of requests){const usage=null==(_b=null==(_a=req.response)?void 0:_a.body)?void 0:_b.usage;if(!usage)continue;const model=(null==(_c=req.body)?void 0:_c.model)||"unknown";byModel[model]||(byModel[model]={input:0,output:0,cacheCreation:0,cacheRead:0});const s=byModel[model];s.input+=usage.input_tokens||0,s.output+=usage.output_tokens||0,s.cacheCreation+=usage.cache_creation_input_tokens||0,s.cacheRead+=usage.cache_read_input_tokens||0}return byModel}function computeCacheRebuildStats(requests){var _a,_b,_c;const stats={ttl:{count:0,cacheCreate:0},system_change:{count:0,cacheCreate:0},tools_change:{count:0,cacheCreate:0},model_change:{count:0,cacheCreate:0},msg_truncated:{count:0,cacheCreate:0},msg_modified:{count:0,cacheCreate:0},key_change:{count:0,cacheCreate:0}},lossMap=function(requests){const map=new Map;return appendCacheLossMap(map,requests,0,null),map}(requests);for(const[i,result]of lossMap){const cacheCreate=(null==(_c=null==(_b=null==(_a=requests[i].response)?void 0:_a.body)?void 0:_b.usage)?void 0:_c.cache_creation_input_tokens)||0,reasons=result.reasons||[result.reason];for(const r of reasons)stats[r]&&(stats[r].count++,stats[r].cacheCreate+=cacheCreate)}return stats}function computeToolUsageStats(requests){var _a,_b;const toolCounts={};for(const req of requests){const content2=null==(_b=null==(_a=req.response)?void 0:_a.body)?void 0:_b.content;if(Array.isArray(content2))for(const block of content2)"tool_use"===block.type&&block.name&&(toolCounts[block.name]=(toolCounts[block.name]||0)+1)}return Object.entries(toolCounts).sort((a,b)=>b[1]-a[1])}function computeSkillUsageStats(requests){var _a;const skillCounts={};for(const req of requests){const messages=null==(_a=req.body)?void 0:_a.messages;if(Array.isArray(messages))for(const msg of messages){if("user"!==msg.role)continue;const content2=msg.content;if(Array.isArray(content2))for(const block of content2){if("text"!==block.type||!isSkillText(block.text))continue;const nameMatch=block.text.match(/^#\s+(.+)$/m),skillName=nameMatch?nameMatch[1]:"Skill";skillCounts[skillName]=(skillCounts[skillName]||0)+1}}}return Object.entries(skillCounts).sort((a,b)=>b[1]-a[1])}function isClaudeMdReminder(text){return"string"==typeof text&&(text.includes("<system-reminder>")&&text.includes("# claudeMd"))}function isSkillsReminder(text){return"string"==typeof text&&(text.includes("<system-reminder>")&&text.includes("skills are available"))}function hasClaudeMdReminder(body2){const messages=null==body2?void 0:body2.messages;if(!Array.isArray(messages))return!1;for(const msg of messages){const content2=null==msg?void 0:msg.content;if("string"==typeof content2){if(isClaudeMdReminder(content2))return!0}else if(Array.isArray(content2))for(const block of content2)if("text"===block.type&&isClaudeMdReminder(block.text))return!0}return!1}function hasSkillsReminder(body2){if(Array.isArray(null==body2?void 0:body2.system))for(const blk of body2.system)if("text"===(null==blk?void 0:blk.type)&&isSkillsReminder(blk.text))return!0;const messages=null==body2?void 0:body2.messages;if(!Array.isArray(messages))return!1;for(const msg of messages){const content2=null==msg?void 0:msg.content;if("string"==typeof content2){if(isSkillsReminder(content2))return!0}else if(Array.isArray(content2))for(const block of content2)if("text"===block.type&&isSkillsReminder(block.text))return!0}return!1}function getModelShort(model){return model?model.replace(/^claude-/,"").replace(/-\d{8,}$/,""):null}function isRelevantRequest(request){var _a,_b,_c;if(!request)return!1;const url=request.url||"";return!(request.isHeartbeat||request.isCountTokens||/\/api\/eval\/sdk-/.test(url)||/\/messages\/count_tokens/.test(url)||!0===request.inProgress||request.response&&0===request.response.status||1===(null==(_a=request.body)?void 0:_a.max_tokens)&&!(null==(_b=request.body)?void 0:_b.system)&&(!(null==(_c=request.body)?void 0:_c.tools)||0===request.body.tools.length))}function filterRelevantRequests(requests){return requests.filter(isRelevantRequest)}function findPrevMainAgentTimestamp(requests,startIndex){for(let i=startIndex-1;i>=0;i--)if(isMainAgent(requests[i])&&requests[i].timestamp)return requests[i].timestamp;return null}function extractCachedContent(requests){var _a,_b,_c,_d;if(!Array.isArray(requests)||0===requests.length)return null;let chosen=null;if(1===requests.length)chosen=requests[0];else{let latestMA=null,latestMAWithUsage=null;for(let i=requests.length-1;i>=0;i--)if(isMainAgent(requests[i])&&(latestMA||(latestMA=requests[i]),null==(_b=null==(_a=requests[i].response)?void 0:_a.body)?void 0:_b.usage)){latestMAWithUsage=requests[i];break}chosen=latestMAWithUsage||latestMA}if(!chosen||!chosen.body)return null;const body2=chosen.body,usage=null==(_d=null==(_c=chosen.response)?void 0:_c.body)?void 0:_d.usage,result={system:[],messages:[],tools:[],cacheCreateTokens:(null==usage?void 0:usage.cache_creation_input_tokens)||0,cacheReadTokens:(null==usage?void 0:usage.cache_read_input_tokens)||0};if(Array.isArray(body2.system)){let lastCacheIndex=-1;for(let i=body2.system.length-1;i>=0;i--)if(body2.system[i].cache_control){lastCacheIndex=i;break}if(lastCacheIndex>=0)for(let i=0;i<=lastCacheIndex;i++){const block=body2.system[i];"text"===block.type&&block.text&&result.system.push(block.text)}}if(Array.isArray(body2.messages)){let lastCacheIndex=-1;for(let i=body2.messages.length-1;i>=0;i--){const content2=body2.messages[i].content;if(Array.isArray(content2)){for(const block of content2)if(block.cache_control){lastCacheIndex=i;break}if(lastCacheIndex>=0)break}}if(lastCacheIndex<0&&result.cacheReadTokens>0&&body2.messages.length>0&&(lastCacheIndex=body2.messages.length-1),lastCacheIndex>=0)for(let i=0;i<=lastCacheIndex;i++){const msg=body2.messages[i],content2=msg.content;if("string"==typeof content2)result.messages.push(`[${msg.role}] ${content2}`);else if(Array.isArray(content2))for(const block of content2)if("text"===block.type&&block.text)result.messages.push(`[${msg.role}] ${block.text}`);else if("tool_use"===block.type){const inputStr=block.input?JSON.stringify(block.input):"",preview=inputStr.length>200?inputStr.substring(0,200)+"...":inputStr;result.messages.push(`[${msg.role}] ${block.name}(${preview})`)}else if("tool_result"===block.type){const toolText=extractToolResultText(block);toolText&&result.messages.push(`[tool_result: ${block.tool_use_id}] ${toolText}`)}}}if(Array.isArray(body2.tools)&&body2.tools.length>0&&result.system.length>0)for(const tool of body2.tools)result.tools.push(formatToolAsXml(tool));return result}let _dbInstance=null,_dbPromise=null;function getDB(){return _dbInstance?Promise.resolve(_dbInstance):_dbPromise||(_dbPromise=new Promise((resolve,reject)=>{const req=indexedDB.open("ccv_entryCache",2);req.onupgradeneeded=()=>{const db=req.result;db.objectStoreNames.contains("entries")||db.createObjectStore("entries"),db.objectStoreNames.contains("sessions")||db.createObjectStore("sessions"),db.objectStoreNames.contains("session_index")||db.createObjectStore("session_index")},req.onsuccess=()=>{_dbInstance=req.result,_dbInstance.onclose=()=>{_dbInstance=null},_dbPromise=null,resolve(_dbInstance)},req.onerror=()=>{_dbPromise=null,reject(req.error)}}),_dbPromise)}let _writeId=0;function getCacheMeta(){try{const raw=localStorage.getItem("ccv_cacheMeta");if(!raw)return null;const meta=JSON.parse(raw);return(null==meta?void 0:meta.lastTs)&&(null==meta?void 0:meta.count)>0&&(null==meta?void 0:meta.projectName)?meta:null}catch{return null}}async function saveEntries(projectName,entries){if(!projectName||!Array.isArray(entries)||0===entries.length)return;const myId=++_writeId;try{const db=await getDB();if(myId!==_writeId)return;return function(projectName,entries){try{const last=entries[entries.length-1],lastTs=(null==last?void 0:last.timestamp)||null;lastTs&&localStorage.setItem("ccv_cacheMeta",JSON.stringify({projectName:projectName,lastTs:lastTs,count:entries.length}))}catch{}}(projectName,entries),new Promise(resolve=>{const tx=db.transaction("entries","readwrite");tx.objectStore("entries").put({projectName:projectName,entries:entries,ts:Date.now()},"cache"),tx.oncomplete=()=>resolve(),tx.onerror=()=>resolve()})}catch{}}async function clearEntries(){!function(){try{localStorage.removeItem("ccv_cacheMeta")}catch{}}();try{const db=await getDB();return new Promise(resolve=>{const tx=db.transaction("entries","readwrite");tx.objectStore("entries").delete("cache"),tx.oncomplete=()=>resolve(),tx.onerror=()=>resolve()})}catch{}}async function saveSessionEntries(projectName,sessionId,entries){if(projectName&&null!=entries)try{const db=await getDB(),key=`${projectName}:${sessionId}`;return new Promise(resolve=>{const tx=db.transaction("sessions","readwrite");tx.objectStore("sessions").put({entries:entries,ts:Date.now()},key),tx.oncomplete=()=>resolve(),tx.onerror=()=>resolve()})}catch{}}async function saveSessionIndex(projectName,index){if(projectName&&Array.isArray(index))try{const db=await getDB();return new Promise(resolve=>{const tx=db.transaction("session_index","readwrite");tx.objectStore("session_index").put({index:index,ts:Date.now()},projectName),tx.oncomplete=()=>resolve(),tx.onerror=()=>resolve()})}catch{}}function assignMessageTimestamps(messages,prevMessages,isNewSession,prevCount,currentTs,prevMainAgentTs){if(!Array.isArray(messages))return messages;for(let i=0;i<messages.length;i++){const m=messages[i];m&&(!isNewSession&&i<prevCount&&prevMessages[i]&&prevMessages[i]._timestamp?(m._timestamp=prevMessages[i]._timestamp,prevMessages[i]._generatedTs&&(m._generatedTs=prevMessages[i]._generatedTs)):m._timestamp?"assistant"===m.role&&!m._generatedTs&&prevMainAgentTs&&(m._generatedTs=prevMainAgentTs):(m._timestamp=currentTs,"assistant"===m.role&&prevMainAgentTs&&(m._generatedTs=prevMainAgentTs)))}return messages}function resolveBubbleProducerTs(msg){return msg?"assistant"===msg.role?msg._generatedTs||msg._timestamp||null:msg._timestamp||null:null}function buildSessionIndex(entries,mainAgentSessions){const groupMap=new Map;for(const entry of entries){const id=entry._sessionId;if(null==id)continue;const ts=entry.timestamp||null;let g2=groupMap.get(id);g2||(g2={firstTs:ts,lastTs:ts,entryCount:0},groupMap.set(id,g2)),g2.entryCount++,ts&&((!g2.firstTs||ts<g2.firstTs)&&(g2.firstTs=ts),(!g2.lastTs||ts>g2.lastTs)&&(g2.lastTs=ts))}const sortedGroupKeys=Array.from(groupMap.keys()).sort(),result=[];for(let i=0;i<mainAgentSessions.length;i++){const session=mainAgentSessions[i],sessionId=sortedGroupKeys[i]||(null==session?void 0:session.entryTimestamp)||null,g2=sessionId&&groupMap.get(sessionId)||{firstTs:null,lastTs:null,entryCount:0};let msgCount=0,preview="",userId=null;if(session&&(msgCount=session.messages?session.messages.length:0,userId=session.userId||null,session.messages))for(const msg of session.messages)if("user"===msg.role){const text=extractTextContent(msg);if(text){preview=text.slice(0,80);break}}result.push({sessionId:sessionId,firstTs:g2.firstTs,lastTs:g2.lastTs||(null==session?void 0:session.entryTimestamp)||null,entryCount:g2.entryCount,msgCount:msgCount,preview:preview,userId:userId})}return result}function extractTextContent(msg){if(!msg)return"";if("string"==typeof msg.content)return msg.content;if(Array.isArray(msg.content))for(const block of msg.content)if("text"===block.type&&block.text)return block.text;return""}function splitHotCold(entries,mainAgentSessions,sessionIndex,hotCount,pinnedSessionIds=new Set){if(sessionIndex.length<=hotCount)return{hotEntries:entries,allSessions:mainAgentSessions,coldGroups:new Map};const hotSessionIds=new Set(pinnedSessionIds);let remaining=hotCount-hotSessionIds.size;for(let i=sessionIndex.length-1;i>=0&&remaining>0;i--){const sid=sessionIndex[i].sessionId;hotSessionIds.has(sid)||(hotSessionIds.add(sid),remaining--)}const hotEntries=[],coldGroups=new Map;for(const entry of entries)if(hotSessionIds.has(entry._sessionId))hotEntries.push(entry);else{let group=coldGroups.get(entry._sessionId);group||(group=[],coldGroups.set(entry._sessionId,group)),group.push(entry)}return{hotEntries:hotEntries,allSessions:mainAgentSessions.map((session,i)=>{const meta=sessionIndex[i],sid=null==meta?void 0:meta.sessionId;return sid&&!hotSessionIds.has(sid)?{_cold:!0,sessionId:sid,preview:meta.preview,msgCount:meta.msgCount,firstTs:meta.firstTs,lastTs:meta.lastTs,userId:meta.userId,messages:null,response:null,entryTimestamp:meta.lastTs}:session}),coldGroups:coldGroups}}function mergeSessionIndices(oldIndex,newIndex){if(!oldIndex||0===oldIndex.length)return newIndex||[];if(!newIndex||0===newIndex.length)return oldIndex;const newIdSet=new Set(newIndex.map(s=>s.sessionId)),merged=[];for(const item of oldIndex)newIdSet.has(item.sessionId)||merged.push(item);for(const item of newIndex)merged.push(item);return merged.sort((a,b)=>a.sessionId===b.sessionId?0:null==a.sessionId?-1:null==b.sessionId?1:a.sessionId<b.sessionId?-1:1),merged}function applyInPlaceLastMsgReplace(prevSessions,entry,timestamp,isNewSession){if(!entry||!0!==entry._inPlaceReplaceDetected||!0!==entry._isCheckpoint)return{applied:!1};if(isNewSession)return{applied:!1};if(!Array.isArray(prevSessions)||0===prevSessions.length)return{applied:!1};const lastSession=prevSessions[prevSessions.length-1];if(!lastSession||!Array.isArray(lastSession.messages))return{applied:!1};const messages=entry.body&&Array.isArray(entry.body.messages)?entry.body.messages:null;if(!messages||messages.length<2)return{applied:!1};if(messages.length!==lastSession.messages.length)return{applied:!1};if(!entry.response)return{applied:!1};const N=messages.length,stitched=lastSession.messages.slice(0,N-1),newLastMsg=messages[N-1];newLastMsg&&!newLastMsg._timestamp&&(newLastMsg._timestamp=timestamp),stitched.push(newLastMsg);const newLastSession={userId:lastSession.userId,messages:stitched,response:entry.response,entryTimestamp:timestamp};return{applied:!0,sessions:[...prevSessions.slice(0,-1),newLastSession]}}function messageFingerprint(msg){if(!msg||!msg.role)return"";const c=msg.content;if("string"==typeof c)return`${msg.role}|s|${c.slice(0,64)}`;if(!Array.isArray(c)||0===c.length)return`${msg.role}|empty`;const b=c[0];return"tool_use"===b.type?`${msg.role}|tu|${b.id||b.name||""}`:"tool_result"===b.type?`${msg.role}|tr|${b.tool_use_id||""}`:"text"===b.type?`${msg.role}|t|${(b.text||"").slice(0,64)}`:"thinking"===b.type?`${msg.role}|th|${(b.thinking||"").slice(0,64)}`:`${msg.role}|${b.type||"unknown"}`}function isCheckpointEntry(entry){var _a;if(!entry._deltaFormat)return!0;if(entry._isCheckpoint)return!0;const msgs=null==(_a=entry.body)?void 0:_a.messages;return!(!Array.isArray(msgs)||entry._totalMessageCount!==msgs.length)}function isDeltaEntry(entry){return entry._deltaFormat&&entry.mainAgent}function reconstructEntries(entries){var _a,_b;let accumulated=[];const broken=[];for(let i=0;i<entries.length;i++){const entry=entries[i];if(entry.inProgress)continue;if(!isDeltaEntry(entry)){entry.mainAgent&&Array.isArray(null==(_a=entry.body)?void 0:_a.messages)&&(accumulated=[...entry.body.messages]);continue}const msgs=null==(_b=entry.body)?void 0:_b.messages;Array.isArray(msgs)&&(isCheckpointEntry(entry)?accumulated=[...msgs]:(accumulated=[...accumulated,...msgs],entry.body.messages=accumulated,entry._totalMessageCount&&accumulated.length!==entry._totalMessageCount&&broken.push(i)))}return broken.length>0&&function(entries,brokenIndices){var _a;for(const brokenIdx of brokenIndices){const brokenEntry=entries[brokenIdx],expectedCount=brokenEntry._totalMessageCount;if(expectedCount)for(let j=brokenIdx+1;j<entries.length;j++){const candidate=entries[j];if(!candidate.mainAgent||!Array.isArray(null==(_a=candidate.body)?void 0:_a.messages))continue;const candidateMsgs=candidate.body.messages,candidateTotal=candidate._totalMessageCount||candidateMsgs.length;if((!candidate._deltaFormat||isCheckpointEntry(candidate))&&candidateTotal>=expectedCount){brokenEntry.body.messages=candidateMsgs.slice(0,expectedCount);break}}}}(entries,broken),entries}let _mermaidPromise=null,_mermaidInstance=null,_observerStarted=!1,_scanTimer=null,_pendingNodes=new Set;const THEME_DARK={theme:"dark",darkMode:!0,themeVariables:{darkMode:!0,background:"#0d1117",primaryColor:"#1a3a5c",primaryTextColor:"#c9d1d9",primaryBorderColor:"#30363d",lineColor:"#58a6ff",secondaryColor:"#161b22",tertiaryColor:"#0d1117",nodeTextColor:"#c9d1d9",edgeLabelBackground:"#0d1117"}},THEME_LIGHT={theme:"default",darkMode:!1,themeVariables:{darkMode:!1,background:"#FFFFFF",primaryColor:"#dce8f5",primaryTextColor:"#1a1a1a",primaryBorderColor:"#E0E0E0",lineColor:"#0969DA",secondaryColor:"#F0F0F0",tertiaryColor:"#F5F5F5",nodeTextColor:"#1a1a1a",edgeLabelBackground:"#FFFFFF"}};function getCurrentThemeConfig(){return"light"===document.documentElement.getAttribute("data-theme")?THEME_LIGHT:THEME_DARK}async function renderMermaidIn(container2){if(!container2)return;const codeEls=container2.querySelectorAll("code.language-mermaid");if(0===codeEls.length)return;const m=await(_mermaidPromise||(_mermaidPromise=__vitePreload(()=>import("./mermaid.core-BeZMQR0-.js").then(n=>n.bB),__vite__mapDeps([0,1,2,3,4])).then(mod=>{const m=mod.default,cfg=getCurrentThemeConfig();return m.initialize({startOnLoad:!1,securityLevel:"strict",flowchart:{useMaxWidth:!0},...cfg}),_mermaidInstance=m,m}).catch(()=>(_mermaidPromise=null,null)),_mermaidPromise));if(m)for(const code of codeEls){const pre=code.parentElement;if(!pre||pre.dataset.mermaidRendered)continue;pre.dataset.mermaidRendered="1";const src=code.textContent;try{const id="mmd-"+Math.random().toString(36).slice(2,9),{svg:svg}=await m.render(id,src),wrapper2=document.createElement("div");wrapper2.className="mermaid-diagram",wrapper2.dataset.mermaidSrc=src,wrapper2.innerHTML=purify.sanitize(svg,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["style","foreignObject"]}),pre.replaceWith(wrapper2)}catch{}}}function scheduleScan(){_scanTimer||(_scanTimer=requestAnimationFrame(()=>{_scanTimer=null;const nodes=_pendingNodes;_pendingNodes=new Set;for(const node of nodes)node.isConnected&&renderMermaidIn(node)}))}const styles$p={layout:"_layout_1r21f_1",header:"_header_1r21f_6",content:"_content_1r21f_14",mainContainer:"_mainContainer_1r21f_19",leftPanel:"_leftPanel_1r21f_24",leftPanelHeader:"_leftPanelHeader_1r21f_36",leftPanelCount:"_leftPanelCount_1r21f_47",leftPanelBody:"_leftPanelBody_1r21f_53",rightPanel:"_rightPanel_1r21f_58",modalActions:"_modalActions_1r21f_64",spinCenter:"_spinCenter_1r21f_68",emptyCenter:"_emptyCenter_1r21f_73",logListContainer:"_logListContainer_1r21f_83",loadingOverlay:"_loadingOverlay_1r21f_131",dragOverlay:"_dragOverlay_1r21f_144",dragOverlayContent:"_dragOverlayContent_1r21f_158",dragIcon:"_dragIcon_1r21f_167",loadingText:"_loadingText_1r21f_171",mobileLoadingOverlay:"_mobileLoadingOverlay_1r21f_177",mobileLoadingSpinner:"_mobileLoadingSpinner_1r21f_189",mobileLoadingLabel:"_mobileLoadingLabel_1r21f_202",footer:"_footer_1r21f_208",footerRight:"_footerRight_1r21f_220",footerLink:"_footerLink_1r21f_233",footerIcon:"_footerIcon_1r21f_245",footerSep:"_footerSep_1r21f_250",footerVersion:"_footerVersion_1r21f_255",newBadgeText:"_newBadgeText_1r21f_265",guideContainer:"_guideContainer_1r21f_293",guideContent:"_guideContent_1r21f_301",guideTitle:"_guideTitle_1r21f_306",guideStep:"_guideStep_1r21f_313",guideStepNum:"_guideStepNum_1r21f_319",guideStepBody:"_guideStepBody_1r21f_334",guideText:"_guideText_1r21f_339",guideCode:"_guideCode_1r21f_346",mobileChatOverlay:"_mobileChatOverlay_1r21f_359",mobileChatOverlayVisible:"_mobileChatOverlayVisible_1r21f_371",mobileNavBtn:"_mobileNavBtn_1r21f_375",mobileChatInner:"_mobileChatInner_1r21f_380",mobileGitDiffOverlay:"_mobileGitDiffOverlay_1r21f_399",mobileGitDiffOverlayVisible:"_mobileGitDiffOverlayVisible_1r21f_411",mobileGitDiffInner:"_mobileGitDiffInner_1r21f_415",mobileFileExplorerOverlay:"_mobileFileExplorerOverlay_1r21f_435",mobileFileExplorerOverlayVisible:"_mobileFileExplorerOverlayVisible_1r21f_447",mobileFileExplorerInner:"_mobileFileExplorerInner_1r21f_451",mobileCachePanelOverlay:"_mobileCachePanelOverlay_1r21f_471",mobileCachePanelOverlayVisible:"_mobileCachePanelOverlayVisible_1r21f_483",mobileCachePanelInner:"_mobileCachePanelInner_1r21f_487",mobileCachePanelHeader:"_mobileCachePanelHeader_1r21f_506",mobileCachePanelTitle:"_mobileCachePanelTitle_1r21f_515",mobileCachePanelClose:"_mobileCachePanelClose_1r21f_524",mobileCachePanelBody:"_mobileCachePanelBody_1r21f_539",mobileMenuBtn:"_mobileMenuBtn_1r21f_562",mobileMenuOverlay:"_mobileMenuOverlay_1r21f_579",mobileMenuDropdown:"_mobileMenuDropdown_1r21f_585",mobileMenuItem:"_mobileMenuItem_1r21f_601",mobileMenuDivider:"_mobileMenuDivider_1r21f_620",mobileStatsOverlay:"_mobileStatsOverlay_1r21f_626",mobileStatsOverlayVisible:"_mobileStatsOverlayVisible_1r21f_638",mobileStatsInner:"_mobileStatsInner_1r21f_642",mobileLogMgmtOverlay:"_mobileLogMgmtOverlay_1r21f_649",mobileLogMgmtOverlayVisible:"_mobileLogMgmtOverlayVisible_1r21f_661",mobileLogMgmtHeader:"_mobileLogMgmtHeader_1r21f_665",mobileLogMgmtTitle:"_mobileLogMgmtTitle_1r21f_674",mobileLogMgmtClose:"_mobileLogMgmtClose_1r21f_680",mobileLogMgmtActions:"_mobileLogMgmtActions_1r21f_695",mobileLogMgmtBody:"_mobileLogMgmtBody_1r21f_703",mobileSettingsOverlay:"_mobileSettingsOverlay_1r21f_710",mobileSettingsOverlayVisible:"_mobileSettingsOverlayVisible_1r21f_722",mobilePromptOverlay:"_mobilePromptOverlay_1r21f_726",mobilePromptOverlayVisible:"_mobilePromptOverlayVisible_1r21f_738",mobilePromptBody:"_mobilePromptBody_1r21f_742",mobilePromptList:"_mobilePromptList_1r21f_750",mobilePromptItem:"_mobilePromptItem_1r21f_756",mobilePromptTimestamp:"_mobilePromptTimestamp_1r21f_761",mobilePromptCard:"_mobilePromptCard_1r21f_768",mobilePromptPreText:"_mobilePromptPreText_1r21f_776",tableTimestampCell:"_tableTimestampCell_1r21f_786",tablePreviewText:"_tablePreviewText_1r21f_790",tablePreviewTextClickable:"_tablePreviewTextClickable_1r21f_799",tableTag:"_tableTag_1r21f_809",tableActionsCell:"_tableActionsCell_1r21f_815",mobileCLIRoot:"_mobileCLIRoot_1r21f_821",mobileCLIHeader:"_mobileCLIHeader_1r21f_830",mobileCLIHeaderLeft:"_mobileCLIHeaderLeft_1r21f_841",mobileCLIStatusLabel:"_mobileCLIStatusLabel_1r21f_849",mobileCtxTag:"_mobileCtxTag_1r21f_855",mobileCtxTagFill:"_mobileCtxTagFill_1r21f_874",mobileCtxTagContent:"_mobileCtxTagContent_1r21f_884",mobileCLIHeaderRight:"_mobileCLIHeaderRight_1r21f_892",mobileCLIBody:"_mobileCLIBody_1r21f_898",mobileSettingsBody:"_mobileSettingsBody_1r21f_907",mobileSettingsGroup:"_mobileSettingsGroup_1r21f_912",mobileSettingsRow:"_mobileSettingsRow_1r21f_918",mobileSettingsSectionTitle:"_mobileSettingsSectionTitle_1r21f_922",mobileSettingsLabel:"_mobileSettingsLabel_1r21f_939",mobilePromptEmpty:"_mobilePromptEmpty_1r21f_947",mobilePromptHeader:"_mobilePromptHeader_1r21f_954",mobilePromptCount:"_mobilePromptCount_1r21f_962",chatViewWrapper:"_chatViewWrapper_1r21f_968",resumeFooterRight:"_resumeFooterRight_1r21f_974",resumeFooterLeft:"_resumeFooterLeft_1r21f_979",resumeCheckboxOpacity:"_resumeCheckboxOpacity_1r21f_983",btnMarginLeft:"_btnMarginLeft_1r21f_987",btnMarginRight:"_btnMarginRight_1r21f_991",modalTitleInline:"_modalTitleInline_1r21f_996",previewPopover:"_previewPopover_1r21f_1003",previewItem:"_previewItem_1r21f_1009",previewText:"_previewText_1r21f_1021"},MAX_SESSIONS=isMobile&&!isPad?30:100,OPTIMISTIC_CLEAR_PERCENT=5,LIGHT_THEME_CONFIG=Object.freeze({algorithm:theme.defaultAlgorithm,token:Object.freeze({colorPrimary:"#0969DA",colorBgContainer:"#FFFFFF",colorBgLayout:"#FAFAFA",colorBgElevated:"#FFFFFF",colorBorder:"#E0E0E0",controlOutline:"transparent",controlOutlineWidth:0})}),DARK_THEME_CONFIG=Object.freeze({algorithm:theme.darkAlgorithm,token:Object.freeze({colorPrimary:"#1668dc",colorBgContainer:"#111",colorBgLayout:"#0a0a0a",colorBgElevated:"#1e1e1e",colorBorder:"#2a2a2a",controlOutline:"transparent",controlOutlineWidth:0})});class AppBase extends React__default.Component{constructor(props){super(props),__publicField(this,"_resetSSETimeout",()=>{this._sseTimeoutTimer&&clearTimeout(this._sseTimeoutTimer),this._sseReconnectCount=0,this._sseTimeoutTimer=setTimeout(()=>{console.warn("SSE heartbeat timeout, reconnecting..."),this._reconnectSSE()},45e3)}),__publicField(this,"_teardownTransientLiveState",()=>{this._pendingEntries=[],this._flushRafId&&(cancelAnimationFrame(this._flushRafId),this._flushRafId=null),this._streamingOffTimer&&(clearTimeout(this._streamingOffTimer),this._streamingOffTimer=null),this._loadingCountRafId&&(cancelAnimationFrame(this._loadingCountRafId),this._loadingCountRafId=null),this._chunkedEntries=[],this._chunkedTotal=0,this._isIncremental=!1,this._sseSlimmer=null,this._sseReconstructor=null}),__publicField(this,"_flushPendingEntries",()=>{this._flushRafId=null;const batch=this._pendingEntries;this._pendingEntries=[],0!==batch.length&&this.setState(prev=>{var _a,_b,_c,_d,_e;const requests=[...prev.requests];let cacheExpireAt=prev.cacheExpireAt,cacheType=prev.cacheType,mainAgentSessions=prev.mainAgentSessions,shouldClearStreaming=!1;this._sseSlimmer||(this._sseSlimmer=function(isMainAgentFn){let prevMainIdx=-1,prevMsgCount=0,prevUserId=null;const sessionSlimmedIndices=new Set;return{processEntry(entry,requests,currentIdx){var _a,_b,_c,_d,_e;if(!isMainAgentFn(entry))return entry;if(!(null==(_b=null==(_a=entry.body)?void 0:_a.messages)?void 0:_b.length))return entry;const count=entry.body.messages.length,userId=(null==(_c=entry.body.metadata)?void 0:_c.user_id)||null,isNewSession=prevMsgCount>0&&(count<.5*prevMsgCount&&prevMsgCount-count>4||prevUserId&&userId&&userId!==prevUserId);if(isNewSession&&count<=4&&prevMsgCount>4)return entry;if(isNewSession)return sessionSlimmedIndices.clear(),prevMainIdx=currentIdx,prevMsgCount=count,prevUserId=userId,entry;if(prevMainIdx>=0&&prevMainIdx<requests.length){const orig=requests[prevMainIdx];if((null==(_e=null==(_d=orig.body)?void 0:_d.messages)?void 0:_e.length)>0){const cloned={...orig,body:slimBodyBigFields(orig.body),_messageCount:orig.body.messages.length,_slimmed:!0,_fullEntryIndex:currentIdx};requests[prevMainIdx]=cloned,sessionSlimmedIndices.add(prevMainIdx)}}for(const idx of sessionSlimmedIndices)requests[idx]._fullEntryIndex!==currentIdx&&(requests[idx]={...requests[idx],_fullEntryIndex:currentIdx});return entry._prevMsgCount=prevMsgCount,prevMainIdx=currentIdx,prevMsgCount=count,prevUserId=userId,entry},onDedup(existingIndex){sessionSlimmedIndices.delete(existingIndex)}}}(isMainAgent)),this._sseReconstructor||(this._sseReconstructor=function(){let accumulated=[];return{reconstruct(entry){var _a,_b,_c;if(entry.inProgress){if(isDeltaEntry(entry)&&!isCheckpointEntry(entry)){const msgs2=null==(_a=entry.body)?void 0:_a.messages;Array.isArray(msgs2)&&(entry.body.messages=[...accumulated,...msgs2])}return entry}if(!isDeltaEntry(entry))return entry.mainAgent&&Array.isArray(null==(_b=entry.body)?void 0:_b.messages)&&(accumulated=[...entry.body.messages]),entry;const msgs=null==(_c=entry.body)?void 0:_c.messages;return Array.isArray(msgs)?(isCheckpointEntry(entry)?accumulated=[...msgs]:(accumulated=[...accumulated,...msgs],entry.body.messages=accumulated),entry):entry},reset(){accumulated=[]}}}());for(const rawEntry of batch){const entry=internEntryBigFields(this._sseReconstructor.reconstruct(rawEntry)),key=`${entry.timestamp}|${entry.url}`,existingIndex=this._requestIndexMap.get(key);if(void 0!==existingIndex)requests[existingIndex]=entry,this._sseSlimmer&&this._sseSlimmer.onDedup(existingIndex);else{const newIdx=requests.length;this._sseSlimmer&&this._sseSlimmer.processEntry(entry,requests,newIdx),this._requestIndexMap.set(key,newIdx),requests.push(entry)}if(isMainAgent(entry)&&!entry.inProgress&&(null==(_b=null==(_a=entry.response)?void 0:_a.body)?void 0:_b.usage)){const kvCached=extractCachedContent([entry]);kvCached&&(kvCached.system.length>0||kvCached.messages.length>0||kvCached.tools.length>0)&&(this._lastKvCacheContent=kvCached)}if(!entry.inProgress&&isMainAgent(entry)&&prev.streamingLatest&&prev.streamingLatest.timestamp===entry.timestamp&&(shouldClearStreaming=!0),isMainAgent(entry)){const usage=null==(_d=null==(_c=entry.response)?void 0:_c.body)?void 0:_d.usage;if(null==usage?void 0:usage.cache_creation){const cc=usage.cache_creation,reqTime=entry.timestamp?new Date(entry.timestamp).getTime():Date.now();let newExpireAt=null,newType=null;if(cc.ephemeral_1h_input_tokens>0?(newExpireAt=reqTime+36e5,newType="1h"):cc.ephemeral_5m_input_tokens>0&&(newExpireAt=reqTime+3e5,newType="5m"),newExpireAt&&newExpireAt>Date.now()){cacheExpireAt=newExpireAt;const cacheTotal=(usage.cache_read_input_tokens||0)+(usage.cache_creation_input_tokens||0);cacheType=cacheTotal>0?formatTokenCount(cacheTotal):newType,localStorage.setItem("ccv_cacheExpireAt",String(cacheExpireAt)),localStorage.setItem("ccv_cacheType",cacheType)}}}if(isMainAgent(entry)&&entry.body&&Array.isArray(entry.body.messages)&&!entry._slimmed){const timestamp=entry.timestamp||(new Date).toISOString(),lastSession=mainAgentSessions.length>0?mainAgentSessions[mainAgentSessions.length-1]:null,prevMessages=(null==lastSession?void 0:lastSession.messages)||[],messages=entry.body.messages,prevCount=prevMessages.length,userId=(null==(_e=entry.body.metadata)?void 0:_e.user_id)||null,sameUser=null!==userId&&(null==lastSession?void 0:lastSession.userId)===userId,isNewSession=isPostClearCheckpoint(entry,prevCount)||!sameUser&&prevCount>0&&messages.length<.5*prevCount&&prevCount-messages.length>4;isNewSession?(this._currentSessionId=timestamp,this._prevMainAgentTs=null):null===this._currentSessionId&&(this._currentSessionId=timestamp),assignMessageTimestamps(messages,prevMessages,isNewSession,prevCount,timestamp,this._prevMainAgentTs);const inPlaceResult=applyInPlaceLastMsgReplace(mainAgentSessions,entry,timestamp,isNewSession);mainAgentSessions=inPlaceResult.applied?inPlaceResult.sessions:this.mergeMainAgentSessions(mainAgentSessions,entry,{skipTransientFilter:!0}),this._prevMainAgentTs=timestamp}entry._sessionId=this._currentSessionId}let selectedIndex=prev.selectedIndex;return mainAgentSessions.length>MAX_SESSIONS&&(mainAgentSessions=mainAgentSessions.slice(-MAX_SESSIONS)),null===selectedIndex&&requests.length>0&&(this._autoSelectTimer&&clearTimeout(this._autoSelectTimer),this._autoSelectTimer=setTimeout(()=>{this.setState(s=>{if(null===s.selectedIndex&&s.requests.length>0){const filtered=s.showAll?s.requests:filterRelevantRequests(s.requests);return filtered.length>0?{selectedIndex:filtered.length-1}:null}return null})},200)),{requests:requests,cacheExpireAt:cacheExpireAt,cacheType:cacheType,mainAgentSessions:mainAgentSessions,...shouldClearStreaming&&{streamingLatest:null}}},()=>{isMobile&&this.state.projectName&&(this._cacheSaveTimer&&clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=setTimeout(()=>{this.state.projectName&&0===this.state.sessionIndex.length&&saveEntries(this.state.projectName,this.state.requests)},5e3),this.state.mainAgentSessions.length>10&&(this._evictionTimer||(this._evictionTimer=setTimeout(()=>{this._evictionTimer=null,this._evictColdSessions()},1e4))))})}),__publicField(this,"handleSelectRequest",index=>{this.setState({selectedIndex:index,scrollCenter:!1})}),__publicField(this,"handleScrollDone",()=>{this.setState({scrollCenter:!1})}),__publicField(this,"handleScrollTsDone",()=>{this.setState({chatScrollToTs:null})}),__publicField(this,"handleClearContextOptimistic",()=>{this.setState({contextBarOptimistic:!0}),this._clearOptimisticTimer&&clearTimeout(this._clearOptimisticTimer),this._clearOptimisticTimer=setTimeout(()=>{this.setState({contextBarOptimistic:!1}),this._clearOptimisticTimer=null},3e4)}),__publicField(this,"handleWorkspaceLaunch",({projectName:projectName})=>{this._isLocalLog=!1,this._localLogFile=null,this.setState({workspaceMode:!1,projectName:projectName,viewMode:"chat",cliMode:!0,terminalVisible:!1})}),__publicField(this,"handleReturnToWorkspaces",()=>{fetch(apiUrl("/api/workspaces/stop"),{method:"POST"}).then(()=>{this._teardownTransientLiveState(),this._rebuildRequestIndex([]),this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null,streamingLatest:null})}).catch(()=>{})}),__publicField(this,"handleProxyProfileChange",data=>{fetch(apiUrl("/api/proxy-profiles"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(data)}).then(r=>r.json()).then(()=>{this.setState({proxyProfiles:data.profiles,activeProxyId:data.active})}).catch(()=>{})}),__publicField(this,"handleLangChange",()=>{const lang=getLang();this.setState({lang:lang}),this.context.updatePreferences({lang:lang})}),__publicField(this,"handleCollapseToolResultsChange",checked=>{this.setState({collapseToolResults:checked}),this.context.updatePreferences({collapseToolResults:checked})}),__publicField(this,"handleExpandThinkingChange",checked=>{this.setState({expandThinking:checked}),this.context.updatePreferences({expandThinking:checked})}),__publicField(this,"handleExpandDiffChange",checked=>{this.setState({expandDiff:checked}),this.context.updatePreferences({expandDiff:checked})}),__publicField(this,"handleAutoApproveChange",seconds=>{this.setState({autoApproveSeconds:seconds}),this.context.updatePreferences({autoApproveSeconds:seconds})}),__publicField(this,"_injectProjectName",(data,slot2)=>{if(!data)return data;const projectName=this.state.projectName||"";if(!projectName)return data;const innerKey=slot2;return data[innerKey]&&void 0===data[innerKey].projectName?{...data,[innerKey]:{...data[innerKey],projectName:projectName}}:data}),__publicField(this,"_setApprovalKind",(kind,data)=>{const enriched=this._injectProjectName(data,kind);this.setState(prev=>{const next={...prev.approvalGlobal};next[kind]=enriched||null;const dismissed=new Set(prev.approvalDismissedIds);let changed=!1;for(const id of dismissed)id.startsWith(`${kind}:`)&&(dismissed.delete(id),changed=!0);return changed?{approvalGlobal:next,approvalDismissedIds:dismissed}:{approvalGlobal:next}})}),__publicField(this,"handleApprovalAsk",data=>this._setApprovalKind("ask",data)),__publicField(this,"handleApprovalPtyPlan",data=>this._setApprovalKind("ptyPlan",data)),__publicField(this,"handleApprovalDismiss",(kind,id)=>{kind&&id&&this.setState(prev=>{const next=new Set(prev.approvalDismissedIds);return next.add(`${kind}:${id}`),{approvalDismissedIds:next}})}),__publicField(this,"handleApprovalReopen",()=>{this.setState({approvalDismissedIds:new Set})}),__publicField(this,"handleApprovalJumpTab",tabId=>{var _a;if("undefined"!=typeof window&&(null==(_a=window.tabBridge)?void 0:_a.jumpToTab)&&null!=tabId)try{window.tabBridge.jumpToTab(tabId)}catch{}}),__publicField(this,"handleApprovalPrefsChange",patch=>{var _a,_b;const next={...this.state.approvalPrefs,...patch};this.setState({approvalPrefs:next});try{null==(_b=null==(_a=window.tabBridge)?void 0:_a.setApprovalPref)||_b.call(_a,next)}catch(e){console.warn("[approvalPref IPC] onChange sync failed:",e)}this.context.updatePreferences({approvalModal:next})}),__publicField(this,"handleThemeColorChange",value=>{this.setState({themeColor:value}),document.documentElement.setAttribute("data-theme","light"===value?"light":"dark"),async function(){if(!_mermaidInstance)return;const cfg=getCurrentThemeConfig();_mermaidInstance.initialize({startOnLoad:!1,securityLevel:"strict",flowchart:{useMaxWidth:!0},...cfg});const diagrams=document.querySelectorAll(".mermaid-diagram[data-mermaid-src]");for(const wrapper2 of diagrams){const src=wrapper2.dataset.mermaidSrc;try{const id="mmd-"+Math.random().toString(36).slice(2,9),{svg:svg}=await _mermaidInstance.render(id,src);wrapper2.innerHTML=purify.sanitize(svg,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["style","foreignObject"]})}catch{}}}(),this.context.updatePreferences({themeColor:value}),window.dispatchEvent(new CustomEvent("ccv-focus-terminal"))}),__publicField(this,"handleLogDirChange",value=>{if(!value||"string"!=typeof value)return;const trimmed=value.trim();trimmed&&(this.setState({logDir:trimmed}),this.context.updatePreferences({logDir:trimmed}).then(data=>{data&&data.logDir&&this.setState({logDir:data.logDir})}))}),__publicField(this,"handleShowFullToolContentChange",checked=>{this.setState({showFullToolContent:checked}),this.context.updatePreferences({showFullToolContent:checked})}),__publicField(this,"handleFilterIrrelevantChange",checked=>{this.setState(prev=>{const newShowAll=!checked,newFiltered=newShowAll?prev.requests:filterRelevantRequests(prev.requests);return{showAll:newShowAll,selectedIndex:newFiltered.length>0?newFiltered.length-1:null}}),this.context.updatePreferences({filterIrrelevant:checked})}),__publicField(this,"handleImportLocalLogs",()=>{this.setState({importModalVisible:!0,localLogsLoading:!0}),fetch(apiUrl("/api/local-logs")).then(res=>res.json()).then(data=>{const{_currentProject:_currentProject,...logs}=data;this.setState({localLogs:logs,currentProject:_currentProject||"",localLogsLoading:!1})}).catch(()=>{this.setState({localLogs:{},localLogsLoading:!1})})}),__publicField(this,"handleCloseImportModal",()=>{this.setState({importModalVisible:!1,selectedLogs:new Set})}),__publicField(this,"handleRefreshStats",()=>{this.setState({refreshingStats:!0}),fetch(apiUrl("/api/refresh-stats"),{method:"POST"}).then(res=>res.json()).then(data=>{if(!data.ok)throw new Error(data.error||"refresh failed");return fetch(apiUrl("/api/local-logs"))}).then(res=>res.json()).then(data=>{const{_currentProject:_currentProject,...logs}=data;this.setState({localLogs:logs,refreshingStats:!1}),staticMethods.success(t("ui.refreshStatsSuccess"))}).catch(()=>{this.setState({refreshingStats:!1}),staticMethods.error(t("ui.refreshStatsFailed"))})}),__publicField(this,"handleToggleLogSelect",(file,checked)=>{this.setState(prev=>{const selectedLogs=new Set(prev.selectedLogs);return checked?selectedLogs.add(file):selectedLogs.delete(file),{selectedLogs:selectedLogs}})}),__publicField(this,"handleMergeLogs",()=>{const{selectedLogs:selectedLogs,localLogs:localLogs,currentProject:currentProject}=this.state;if(selectedLogs.size<2)return;const logs=localLogs[currentProject];if(!logs)return;const indices=[];if(logs.forEach((log,i)=>{selectedLogs.has(log.file)&&indices.push(i)}),indices.sort((a,b)=>a-b),selectedLogs.has(logs[0].file))return void staticMethods.warning(t("ui.mergeLatestNotAllowed"));for(let i=1;i<indices.length;i++)if(indices[i]-indices[i-1]!==1)return void staticMethods.warning(t("ui.mergeNotConsecutive"));if(indices.reduce((sum,i)=>sum+logs[i].size,0)>524288e3)return void staticMethods.warning(t("ui.mergeTooLarge"));const files=indices.map(i=>logs[i].file).reverse();fetch(apiUrl("/api/merge-logs"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:files})}).then(res=>res.json()).then(data=>{data.ok?(staticMethods.success(t("ui.mergeSuccess")),this.setState({selectedLogs:new Set}),this.handleImportLocalLogs()):staticMethods.error(data.error||"Merge failed")}).catch(()=>staticMethods.error("Merge failed"))}),__publicField(this,"handleDeleteLogs",()=>{const{selectedLogs:selectedLogs}=this.state;0!==selectedLogs.size&&Modal.confirm({title:t("ui.deleteLogs"),content:t("ui.deleteLogsConfirm",{count:selectedLogs.size}),okText:t("ui.deleteLogs"),okButtonProps:{danger:!0},cancelText:t("ui.cancel"),onOk:()=>{const files=[...selectedLogs];fetch(apiUrl("/api/delete-logs"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:files})}).then(res=>res.json()).then(data=>{if(data.results){const deleted=data.results.filter(r=>r.ok).length,failed=data.results.filter(r=>r.error).length;deleted>0&&staticMethods.success(t("ui.deleteSuccess",{count:deleted})),failed>0&&staticMethods.error(t("ui.deleteFailed",{count:failed})),this.setState({selectedLogs:new Set}),this.handleImportLocalLogs()}}).catch(()=>staticMethods.error("Delete failed"))}})}),__publicField(this,"handleOpenLogFile",async file=>{let base=`${window.location.protocol}//${window.location.host}`,token=new URLSearchParams(window.location.search).get("token");if(!token)try{const r=await fetch(apiUrl("/api/local-url"));if(r.ok){const data=await r.json();data.url&&(base=data.url.split("?")[0],token=new URL(data.url).searchParams.get("token"))}}catch{}const tokenParam=token?`&token=${encodeURIComponent(token)}`:"";window.open(`${base}?logfile=${encodeURIComponent(file)}${tokenParam}`,"_blank"),this.setState({importModalVisible:!1})}),__publicField(this,"handleDownloadLogFile",file=>{const url=apiUrl(`/api/download-log?file=${encodeURIComponent(file)}`),a=document.createElement("a");a.href=url,a.download="",document.body.appendChild(a),a.click(),document.body.removeChild(a)}),__publicField(this,"handleResumeChoice",choice=>{this.state.resumeRememberChoice&&(this.setState({resumeAutoChoice:choice}),this.context.updatePreferences({resumeAutoChoice:choice})),fetch(apiUrl("/api/resume-choice"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({choice:choice})}).catch(err=>console.error("resume-choice failed:",err))}),__publicField(this,"handleResumeAutoChoiceToggle",enabled=>{const value=enabled?"continue":null;this.setState({resumeAutoChoice:value}),this.context.updatePreferences({resumeAutoChoice:value})}),__publicField(this,"handleResumeAutoChoiceChange",value=>{this.setState({resumeAutoChoice:value}),this.context.updatePreferences({resumeAutoChoice:value})}),__publicField(this,"_finishLocalLoad",(entries,fileNames)=>{if(0===entries.length)return staticMethods.error(t("ui.noLogs")),void this.setState({fileLoading:!1,fileLoadingCount:0});this.animateLoadingCount(entries.length,()=>{this._batchSlim(entries);const{mainAgentSessions:mainAgentSessions,filtered:filtered}=this._processEntries(entries);this._isLocalLog=!0,this._localLogFile=1===fileNames.length?fileNames[0]:`${fileNames.length} files`,this.eventSource&&(this.eventSource.close(),this.eventSource=null),this._streamingOffTimer&&(clearTimeout(this._streamingOffTimer),this._streamingOffTimer=null),this.setState({requests:entries,selectedIndex:filtered.length>0?filtered.length-1:null,mainAgentSessions:mainAgentSessions,importModalVisible:!1,fileLoading:!1,fileLoadingCount:0})})});const savedExpireAt=parseInt(localStorage.getItem("ccv_cacheExpireAt"),10)||null,savedCacheType=localStorage.getItem("ccv_cacheType")||null,now=Date.now(),cacheExpireAt=savedExpireAt&&savedExpireAt>now?savedExpireAt:null,cacheType=cacheExpireAt?savedCacheType:null;this.state={requests:[],selectedIndex:null,viewMode:"raw",cacheExpireAt:cacheExpireAt,cacheType:cacheType,mainAgentSessions:[],importModalVisible:!1,localLogs:{},localLogsLoading:!1,refreshingStats:!1,showAll:!1,lang:getLang(),userProfile:null,projectName:"",resumeModalVisible:!1,resumeFileName:"",resumeRememberChoice:!1,resumeAutoChoice:null,autoApproveSeconds:0,collapseToolResults:!0,expandThinking:!1,expandDiff:!1,logDir:"",showFullToolContent:!1,showThinkingSummaries:!1,themeColor:"dark",claudeMissing:!1,updateModalVisible:!1,fileLoading:!1,fileLoadingCount:0,isDragging:!1,selectedLogs:new Set,githubStars:null,cliMode:!1,sdkMode:!1,workspaceMode:!1,serverCachedContent:null,updateInfo:null,pendingUploadPaths:[],contextWindow:null,contextBarOptimistic:!1,isStreaming:!1,streamingLatest:null,hasMoreHistory:!1,loadingMore:!1,sessionIndex:[],loadingSessionId:null,proxyProfiles:[],activeProxyId:"max",defaultConfig:null,approvalGlobal:{ptyPlan:null,ask:null},approvalDismissedIds:new Set,approvalOtherTabs:[],approvalOwnPending:{ask:0,ptyPlan:0},ownTabId:null,approvalPrefs:{modalEnabled:!0,soundEnabled:!1,notifyOnlyWhenHidden:!0}},this.eventSource=null,this._currentSessionId=null,this._prevMainAgentTs=null,this._autoSelectTimer=null,this._chunkedEntries=[],this._chunkedTotal=0,this.mainContainerRef=React__default.createRef(),this._layoutRef=React__default.createRef(),this._requestIndexMap=new Map,this._pendingEntries=[],this._flushRafId=null,this._cacheLossMap=new Map,this._cacheLossProcessedCount=0,this._cacheLossLastMainAgent=null,this._cacheLossShowAll=void 0,this._lastKvCacheContent=null,this._sseSlimmer=null,this._sseReconstructor=null}_batchSlim(entries){for(let i=0;i<entries.length;i++)entries[i]=internEntryBigFields(entries[i]);const slimmer=function(isMainAgentFn){let prevMainIdx=-1,prevMsgCount=0,prevUserId=null;return{process(entry,entries,currentIdx){var _a,_b,_c;if(!isMainAgentFn(entry))return entry;if(!entry.body||!Array.isArray(entry.body.messages)||0===entry.body.messages.length)return entry;const count=entry.body.messages.length,userId=(null==(_a=entry.body.metadata)?void 0:_a.user_id)||null,isNewSession=prevMsgCount>0&&(count<.5*prevMsgCount&&prevMsgCount-count>4||prevUserId&&userId&&userId!==prevUserId);if(isNewSession&&count<=4&&prevMsgCount>4)return entry;if(isNewSession)return prevMainIdx=currentIdx,prevMsgCount=count,prevUserId=userId,entry;if(prevMainIdx>=0&&prevMainIdx<entries.length){const prev=entries[prevMainIdx];if((null==(_c=null==(_b=prev.body)?void 0:_b.messages)?void 0:_c.length)>0){const pCount=prev.body.messages.length,idxArr=[];for(let j=prev._prevMsgCount||0;j<pCount;j++)idxArr.push(j);prev._messageCount=pCount,prev._messagesIndex=idxArr,prev._slimmed=!0,prev.body=slimBodyBigFields(prev.body)}}return entry._prevMsgCount=prevMsgCount,prevMainIdx=currentIdx,prevMsgCount=count,prevUserId=userId,entry},finalize(entries){var _a,_b,_c,_d,_e,_f;let sessionSlimmed=[],currentFullIdx=-1,pCount=0,pUserId=null;for(let i=0;i<entries.length;i++){const e=entries[i],isSlimmed=e._slimmed,hasMsgs=(null==(_b=null==(_a=e.body)?void 0:_a.messages)?void 0:_b.length)>0;if(!isSlimmed&&!hasMsgs)continue;if(!isSlimmed&&!isMainAgentFn(e))continue;const count=e._messageCount||(null==(_d=null==(_c=e.body)?void 0:_c.messages)?void 0:_d.length)||0,userId=(null==(_f=null==(_e=e.body)?void 0:_e.metadata)?void 0:_f.user_id)||null,isNew=pCount>0&&(count<.5*pCount&&pCount-count>4||pUserId&&userId&&userId!==pUserId);if(!(isNew&&count<=4&&pCount>10)){if(isNew){for(const idx of sessionSlimmed)entries[idx]._fullEntryIndex=currentFullIdx;sessionSlimmed=[],currentFullIdx=-1,pCount=0}isSlimmed&&sessionSlimmed.push(i),!hasMsgs&&isSlimmed||(currentFullIdx=i),pCount=count,pUserId=userId}}for(const idx of sessionSlimmed)entries[idx]._fullEntryIndex=currentFullIdx}}}(isMainAgent);for(let i=0;i<entries.length;i++)slimmer.process(entries[i],entries,i);slimmer.finalize(entries)}_rebuildRequestIndex(entries){this._requestIndexMap.clear();for(let i=0;i<entries.length;i++){const e=entries[i];this._requestIndexMap.set(`${e.timestamp}|${e.url}`,i)}this._cacheLossProcessedCount=0,this._cacheLossLastMainAgent=null,this._cacheLossMap=new Map,this._lastKvCacheContent=null,this._sseSlimmer=null,this._sseReconstructor=null}_settingsProps(){const ctx=this.context||{};return{claudeSettings:ctx.claudeSettings,preferences:ctx.preferences,onUpdatePreferences:ctx.updatePreferences,onUpdateClaudeSettings:ctx.updateClaudeSettings}}_processEntries(entries){var _a;let timestamps=[],generatedTimestamps=[],prevMainAgentTs=null,prevUserId=null,sessions=[];const filtered=[];this._requestIndexMap.clear(),this._cacheLossProcessedCount=0,this._cacheLossLastMainAgent=null,this._cacheLossMap=new Map,this._lastKvCacheContent=null,this._sseSlimmer=null,this._sseReconstructor=null;let currentSessionId=null;for(let i=0;i<entries.length;i++){const entry=entries[i];if(this._requestIndexMap.set(`${entry.timestamp}|${entry.url}`,i),isRelevantRequest(entry)&&filtered.push(entry),isMainAgent(entry)&&entry.body&&Array.isArray(entry.body.messages)){const messages=entry.body.messages,count=entry._messageCount||messages.length,userId=(null==(_a=entry.body.metadata)?void 0:_a.user_id)||null,timestamp=entry.timestamp||(new Date).toISOString(),prevCount=timestamps.length,postClearCheckpoint=isPostClearCheckpoint(entry,prevCount),isNewSession=postClearCheckpoint||prevCount>0&&(count<.5*prevCount&&prevCount-count>4||prevUserId&&userId&&userId!==prevUserId);isNewSession&&!(isNewSession&&!postClearCheckpoint&&count<=4&&prevCount>4&&count<.5*prevCount)?(currentSessionId=timestamp,timestamps=[],generatedTimestamps=[],prevMainAgentTs=null):null===currentSessionId&&(currentSessionId=timestamp);for(let j=timestamps.length;j<count;j++)timestamps.push(timestamp),generatedTimestamps.push(prevMainAgentTs||null);if(messages.length>0)for(let j=0;j<messages.length;j++){const m=messages[j];m&&(m._timestamp=timestamps[j],"assistant"===m.role&&generatedTimestamps[j]&&(m._generatedTs=generatedTimestamps[j]))}prevUserId=userId,prevMainAgentTs=timestamp,entry._slimmed||(sessions=this.mergeMainAgentSessions(sessions,entry))}entry._sessionId=currentSessionId}return this._currentSessionId=currentSessionId,{mainAgentSessions:sessions,filtered:filtered}}componentDidMount(){var _a,_b,_c,_d;if(this.context._claudeSettingsReady.then(data=>{data&&(data.showThinkingSummaries&&this.setState({showThinkingSummaries:!0}),!1===data.claudeAvailable&&this.setState({claudeMissing:!0}))}),this._tabBridgeDisposers=[],"undefined"!=typeof window&&window.tabBridge)try{const offTabId=null==(_b=(_a=window.tabBridge).onTabIdInit)?void 0:_b.call(_a,tabId=>{this.setState({ownTabId:tabId})}),offBroadcast=null==(_d=(_c=window.tabBridge).onApprovalBroadcast)?void 0:_d.call(_c,payload=>{if(!payload)return;const op=payload.ownPending,ownPendingCount=op&&"object"==typeof op?{ask:Array.isArray(op.ask)?op.ask.length:0,ptyPlan:Array.isArray(op.ptyPlan)?op.ptyPlan.length:0}:{ask:0,ptyPlan:0};this.setState(prev=>({ownTabId:null!=payload.ownTabId?payload.ownTabId:prev.ownTabId,approvalOtherTabs:Array.isArray(payload.others)?payload.others:[],approvalOwnPending:ownPendingCount}))});"function"==typeof offTabId&&this._tabBridgeDisposers.push(offTabId),"function"==typeof offBroadcast&&this._tabBridgeDisposers.push(offBroadcast)}catch{}this.context._prefsReady.then(data=>{if(!data)return;data.lang&&this.setState({lang:data.lang}),void 0!==data.collapseToolResults&&this.setState({collapseToolResults:!!data.collapseToolResults}),void 0!==data.expandThinking&&this.setState({expandThinking:!!data.expandThinking}),void 0!==data.expandDiff&&this.setState({expandDiff:!!data.expandDiff}),void 0!==data.showFullToolContent&&this.setState({showFullToolContent:!!data.showFullToolContent}),data.resumeAutoChoice&&this.setState({resumeAutoChoice:data.resumeAutoChoice}),"number"==typeof data.autoApproveSeconds&&this.setState({autoApproveSeconds:data.autoApproveSeconds}),data.approvalModal&&"object"==typeof data.approvalModal&&this.setState(prev=>{var _a2,_b2;const next={modalEnabled:void 0!==data.approvalModal.modalEnabled?!!data.approvalModal.modalEnabled:prev.approvalPrefs.modalEnabled,soundEnabled:void 0!==data.approvalModal.soundEnabled?!!data.approvalModal.soundEnabled:prev.approvalPrefs.soundEnabled,notifyOnlyWhenHidden:void 0!==data.approvalModal.notifyOnlyWhenHidden?!!data.approvalModal.notifyOnlyWhenHidden:prev.approvalPrefs.notifyOnlyWhenHidden};try{null==(_b2=null==(_a2=window.tabBridge)?void 0:_a2.setApprovalPref)||_b2.call(_a2,next)}catch(e){console.warn("[approvalPref IPC] hydrate sync failed:",e)}return{approvalPrefs:next}}),data.themeColor&&(this.setState({themeColor:data.themeColor}),document.documentElement.setAttribute("data-theme","light"===data.themeColor?"light":"dark"));const filterIrrelevant=void 0===data.filterIrrelevant||!!data.filterIrrelevant;this.setState({showAll:!filterIrrelevant}),data.logDir&&this.setState({logDir:data.logDir});const urlTheme=new URLSearchParams(window.location.search).get("theme");"light"!==urlTheme&&"dark"!==urlTheme||(this.setState({themeColor:urlTheme}),document.documentElement.setAttribute("data-theme",urlTheme))}),fetch(apiUrl("/api/user-profile")).then(res=>res.json()).then(data=>this.setState({userProfile:data})).catch(()=>{}),fetch(apiUrl("/api/proxy-profiles")).then(res=>res.json()).then(data=>{if(!data.profiles)return;let activeId=data.active||"max";const dc=data.defaultConfig;if("max"===activeId&&(null==dc?void 0:dc.origin)){const match=data.profiles.find(p=>{if("max"===p.id||!p.baseURL)return!1;try{if(new URL(p.baseURL).origin!==dc.origin)return!1}catch{return!1}if(dc.apiKey&&p.apiKey){if(dc.apiKey.slice(-4)!==p.apiKey.slice(-4))return!1}return!dc.model||!p.activeModel||dc.model===p.activeModel});match&&(activeId=match.id,this.handleProxyProfileChange({active:match.id,profiles:data.profiles}))}this.setState({proxyProfiles:data.profiles,activeProxyId:activeId,defaultConfig:dc||null})}).catch(()=>{});const logfile=new URLSearchParams(window.location.search).get("logfile");fetch(apiUrl("/api/project-name")).then(res=>res.json()).then(data=>{const projectName=data.projectName||"";this.setState({projectName:projectName}),projectName&&(document.title=projectName),isMobile&&projectName&&!logfile&&0===this.state.requests.length&&async function(projectName){try{const db=await getDB();return new Promise(resolve=>{const req=db.transaction("entries","readonly").objectStore("entries").get("cache");req.onsuccess=()=>{const data=req.result;data&&data.projectName===projectName&&Array.isArray(data.entries)&&0!==data.entries.length?data.ts&&Date.now()-data.ts>6048e5?(clearEntries(),resolve(null)):resolve(data.entries):resolve(null)},req.onerror=()=>resolve(null)})}catch{return null}}(projectName).then(cached=>{if(cached&&0===this.state.requests.length){this._batchSlim(cached);const{mainAgentSessions:mainAgentSessions,filtered:filtered}=this._processEntries(cached);if(mainAgentSessions.length>8){const sessionIndex=buildSessionIndex(cached,mainAgentSessions),unslimmed=cached.map(e=>e._slimmed?restoreSlimmedEntry(e,cached):e),{hotEntries:hotEntries,allSessions:allSessions}=splitHotCold(unslimmed,mainAgentSessions,sessionIndex,8);this._sseSlimmer=null,this._sseReconstructor=null;const hotFiltered=hotEntries.filter(e=>isRelevantRequest(e));this._oldestTs=hotEntries.length>0?hotEntries[0].timestamp:null,this.setState({requests:hotEntries,selectedIndex:hotFiltered.length>0?hotFiltered.length-1:null,mainAgentSessions:allSessions,sessionIndex:sessionIndex,hasMoreHistory:!!this._oldestTs,fileLoading:!1})}else this._oldestTs=cached.length>0?cached[0].timestamp:null,this.setState({requests:cached,selectedIndex:filtered.length>0?filtered.length-1:null,mainAgentSessions:mainAgentSessions,hasMoreHistory:!!this._oldestTs,fileLoading:!1})}})}).catch(()=>{}),fetch("https://api.github.com/repos/weiesky/cc-viewer").then(res=>res.json()).then(data=>{null!=data.stargazers_count&&this.setState({githubStars:data.stargazers_count})}).catch(()=>{}),fetch(apiUrl("/api/cli-mode")).then(res=>res.json()).then(data=>{data.workspaceMode?this.setState({cliMode:!0,workspaceMode:!0,isWorkspaceServer:!0}):data.cliMode&&this.setState({cliMode:!0,sdkMode:!!data.sdkMode,viewMode:"chat"})}).catch(()=>{}),logfile?this.loadLocalLogFile(logfile):this.initSSE()}componentDidUpdate(prevProps,prevState){const cs=this.context&&this.context.claudeSettings;cs&&!!cs.showThinkingSummaries!=!!this.state.showThinkingSummaries&&this.setState({showThinkingSummaries:!!cs.showThinkingSummaries})}componentWillUnmount(){if(Array.isArray(this._tabBridgeDisposers)){for(const off of this._tabBridgeDisposers)try{off()}catch{}this._tabBridgeDisposers=null}this.eventSource&&this.eventSource.close(),this._localLogES&&(this._localLogES.close(),this._localLogES=null),this._autoSelectTimer&&clearTimeout(this._autoSelectTimer),this._loadingCountTimer&&cancelAnimationFrame(this._loadingCountTimer),this._loadingCountRafId&&cancelAnimationFrame(this._loadingCountRafId),this._cacheSaveTimer&&clearTimeout(this._cacheSaveTimer),this._evictionTimer&&clearTimeout(this._evictionTimer),this._sseTimeoutTimer&&clearTimeout(this._sseTimeoutTimer),this._sseReconnectTimer&&clearTimeout(this._sseReconnectTimer),this._streamingOffTimer&&clearTimeout(this._streamingOffTimer),this._streamingRaf&&(cancelAnimationFrame(this._streamingRaf),this._streamingRaf=null),this._clearOptimisticTimer&&clearTimeout(this._clearOptimisticTimer),this._pendingStreamingLatest=null}_reconnectSSE(){if(this.state.streamingLatest&&this.setState({streamingLatest:null}),this._sseReconnectCount>=10)console.error("SSE reconnect limit reached");else{if(this._sseReconnectCount=(this._sseReconnectCount||0)+1,this.eventSource&&(this.eventSource.close(),this.eventSource=null),this._chunkedEntries&&this._chunkedEntries.length>0&&isMobile)try{const partial=reconstructEntries([...this._chunkedEntries]);if(Array.isArray(partial)&&partial.length>0){this._batchSlim(partial);const{mainAgentSessions:mainAgentSessions}=this._processEntries(partial);if(this.setState({requests:partial,mainAgentSessions:mainAgentSessions}),this.state.projectName){const meta=getCacheMeta(),existingCount=meta&&meta.projectName===this.state.projectName?meta.count:0;partial.length>=existingCount&&saveEntries(this.state.projectName,partial)}}}catch(e){console.warn("Failed to save partial entries on reconnect:",e)}this._teardownTransientLiveState(),this.setState({isStreaming:!1}),this._sseReconnectTimer&&clearTimeout(this._sseReconnectTimer),this._sseReconnectTimer=setTimeout(()=>{this.initSSE()},2e3)}}animateLoadingCount(target,onDone){this._loadingCountTimer&&(cancelAnimationFrame(this._loadingCountTimer),this._loadingCountTimer=null);const duration=Math.min(800,Math.max(300,.5*target)),start=performance.now(),step=now=>{const progress=Math.min((now-start)/duration,1),current=Math.round(progress*target);this.setState({fileLoadingCount:current}),progress<1?this._loadingCountTimer=requestAnimationFrame(step):(this._loadingCountTimer=null,onDone())};this._loadingCountTimer=requestAnimationFrame(step)}async loadMoreHistory(){if(this.state.hasMoreHistory&&!this._loadingMore)if(this._oldestTs){this._loadingMore=!0,this.setState({loadingMore:!0});try{const res=await fetch(apiUrl(`/api/entries/page?before=${encodeURIComponent(this._oldestTs)}&limit=100`));if(!res.ok)throw new Error(`HTTP ${res.status}`);const data=await res.json();if(Array.isArray(data.entries)&&data.entries.length>0){const merged=[...reconstructEntries(data.entries),...this.state.requests];this._batchSlim(merged);const{mainAgentSessions:mainAgentSessions}=this._processEntries(merged);if(this._oldestTs=data.oldestTimestamp,isMobile&&mainAgentSessions.length>8){const sessionIndex=buildSessionIndex(merged,mainAgentSessions),fullIndex=mergeSessionIndices(this.state.sessionIndex,sessionIndex),unslimmed=merged.map(e=>e._slimmed?restoreSlimmedEntry(e,merged):e),{hotEntries:hotEntries,allSessions:allSessions,coldGroups:coldGroups}=splitHotCold(unslimmed,mainAgentSessions,fullIndex,8);this._sseSlimmer=null,this._sseReconstructor=null;const pn=this.state.projectName;if(pn){for(const[sid,coldEntries]of coldGroups)saveSessionEntries(pn,sid,coldEntries);saveSessionIndex(pn,fullIndex),saveEntries(pn,merged)}this.setState({requests:hotEntries,mainAgentSessions:allSessions,sessionIndex:fullIndex,hasMoreHistory:!!data.hasMore&&!!data.oldestTimestamp,loadingMore:!1})}else this.setState({requests:merged,mainAgentSessions:mainAgentSessions,hasMoreHistory:!!data.hasMore&&!!data.oldestTimestamp,loadingMore:!1}),isMobile&&this.state.projectName&&saveEntries(this.state.projectName,merged)}else this.setState({hasMoreHistory:!1,loadingMore:!1})}catch(e){console.error("loadMoreHistory failed:",e),this.setState({loadingMore:!1}),staticMethods.error(t("ui.loadMoreHistoryFailed"))}this._loadingMore=!1}else this.setState({hasMoreHistory:!1})}initSSE(){try{let url="/events",hasCache=!1;if(isMobile){const meta=getCacheMeta();meta&&meta.lastTs&&meta.count>0&&(url=`/events?since=${encodeURIComponent(meta.lastTs)}&cc=${meta.count}&project=${encodeURIComponent(meta.projectName||"")}`,hasCache=!0)}!hasCache&&isMobile&&(url="/events?limit=200"),hasCache||this.setState({fileLoading:!0,fileLoadingCount:0}),this.eventSource=new EventSource(apiUrl(url)),this.eventSource.onmessage=event=>{this._resetSSETimeout(),this.handleEventMessage(event)},this.eventSource.onopen=()=>{this._resetSSETimeout()},this.eventSource.addEventListener("stream-progress",event=>{this._resetSSETimeout();try{const data=JSON.parse(event.data);if(this.state.requests.find(r=>r&&r.timestamp===data.timestamp&&!r.inProgress))return;if(this._pendingStreamingLatest={timestamp:data.timestamp,url:data.url,content:data.content||[],model:data.model,updatedAt:Date.now()},this._streamingRaf)return;this._streamingRaf=requestAnimationFrame(()=>{this._streamingRaf=null;const pending=this._pendingStreamingLatest;this._pendingStreamingLatest=null,pending&&React__default.startTransition(()=>{this.setState({streamingLatest:pending})})})}catch{}}),this.eventSource.addEventListener("resume_prompt",event=>{this._resetSSETimeout();try{const data=JSON.parse(event.data);(this.context._prefsReady||Promise.resolve({})).then(prefs=>{(null==prefs?void 0:prefs.resumeAutoChoice)?fetch(apiUrl("/api/resume-choice"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({choice:prefs.resumeAutoChoice})}).catch(err=>console.error("resume-choice failed:",err)):this.setState({resumeModalVisible:!0,resumeFileName:data.recentFileName||""})})}catch{}}),this.eventSource.addEventListener("resume_resolved",()=>{this._resetSSETimeout(),this.setState({resumeModalVisible:!1,resumeFileName:"",resumeRememberChoice:!1})}),this.eventSource.addEventListener("update_major_available",event=>{this._resetSSETimeout();try{const data=JSON.parse(event.data);this.setState({updateInfo:{type:"major",version:data.version}})}catch{}}),this.eventSource.addEventListener("load_start",event=>{this._resetSSETimeout();try{const data=JSON.parse(event.data);this._chunkedEntries=[],this._chunkedTotal=data.total||0,this._isIncremental=!!data.incremental,this._hasMoreHistory=!!data.hasMore,this._oldestTs=data.oldestTs||null,this._isIncremental||this.setState({fileLoading:!0,fileLoadingCount:0})}catch{}}),this.eventSource.addEventListener("load_chunk",event=>{this._resetSSETimeout();try{const chunk=JSON.parse(event.data);Array.isArray(chunk)&&(this._chunkedEntries.push(...chunk),this._isIncremental||this._loadingCountRafId||(this._loadingCountRafId=requestAnimationFrame(()=>{this._loadingCountRafId=null,this.setState({fileLoadingCount:this._chunkedEntries.length})})))}catch{}}),this.eventSource.addEventListener("load_end",()=>{this._resetSSETimeout(),this._loadingCountRafId&&(cancelAnimationFrame(this._loadingCountRafId),this._loadingCountRafId=null);const delta=this._chunkedEntries;this._chunkedEntries=[],this._chunkedTotal=0;const isIncremental=this._isIncremental;let rawEntries;if(this._isIncremental=!1,isIncremental&&isMobile&&this.state.requests.length>0){if(0===delta.length)return void this.setState({fileLoading:!1,fileLoadingCount:0});const eKey=(e,i)=>e.timestamp&&e.url?`${e.timestamp}|${e.url}`:`__nokey_c${i}`,map=new Map;this.state.requests.forEach((e,i)=>map.set(eKey(e,i),e)),delta.forEach((e,i)=>map.set(e.timestamp&&e.url?`${e.timestamp}|${e.url}`:`__nokey_d${i}`,e)),rawEntries=Array.from(map.values())}else rawEntries=delta;const entries=Array.isArray(rawEntries)?reconstructEntries(rawEntries):rawEntries;if(Array.isArray(entries)&&entries.length>0){this._batchSlim(entries);const{mainAgentSessions:mainAgentSessions,filtered:filtered}=this._processEntries(entries);if(isMobile&&mainAgentSessions.length>8){const sessionIndex=buildSessionIndex(entries,mainAgentSessions),fullIndex=isIncremental?mergeSessionIndices(this.state.sessionIndex,sessionIndex):sessionIndex,unslimmed=entries.map(e=>e._slimmed?restoreSlimmedEntry(e,entries):e),{hotEntries:hotEntries,allSessions:allSessions,coldGroups:coldGroups}=splitHotCold(unslimmed,mainAgentSessions,fullIndex,8);this._sseSlimmer=null,this._sseReconstructor=null;const pn=this.state.projectName;if(pn){for(const[sid,coldEntries]of coldGroups)saveSessionEntries(pn,sid,coldEntries);saveSessionIndex(pn,fullIndex),saveEntries(pn,entries)}const hotFiltered=hotEntries.filter(e=>isRelevantRequest(e)),newState={requests:hotEntries,selectedIndex:hotFiltered.length>0?hotFiltered.length-1:null,mainAgentSessions:allSessions,sessionIndex:fullIndex,fileLoading:!1,fileLoadingCount:0};isIncremental||(newState.hasMoreHistory=!!this._hasMoreHistory&&!!this._oldestTs),this.setState(newState)}else{const newState={requests:entries,selectedIndex:filtered.length>0?filtered.length-1:null,mainAgentSessions:mainAgentSessions,fileLoading:!1,fileLoadingCount:0};isIncremental||(newState.hasMoreHistory=!!this._hasMoreHistory&&!!this._oldestTs),this.setState(newState),isMobile&&this.state.projectName&&saveEntries(this.state.projectName,entries)}}else this.setState({fileLoading:!1,fileLoadingCount:0})}),this.eventSource.addEventListener("full_reload",event=>{this._resetSSETimeout();try{const entries=JSON.parse(event.data);if(Array.isArray(entries)){entries.length>0&&this._batchSlim(entries);const{mainAgentSessions:mainAgentSessions,filtered:filtered}=entries.length>0?this._processEntries(entries):{mainAgentSessions:[],filtered:[]};entries.length>0?this.animateLoadingCount(entries.length,()=>{this.setState({requests:entries,selectedIndex:filtered.length>0?filtered.length-1:null,mainAgentSessions:mainAgentSessions,fileLoading:!1,fileLoadingCount:0,serverCachedContent:null}),isMobile&&this.state.projectName&&saveEntries(this.state.projectName,entries)}):(this.setState({requests:entries,selectedIndex:null,mainAgentSessions:mainAgentSessions,fileLoading:!1,fileLoadingCount:0,serverCachedContent:null}),isMobile&&clearEntries())}else this.setState({fileLoading:!1,fileLoadingCount:0})}catch{this.setState({fileLoading:!1,fileLoadingCount:0})}}),this.eventSource.addEventListener("workspace_started",event=>{this._resetSSETimeout();try{const data=JSON.parse(event.data);this._loadingCountTimer&&(cancelAnimationFrame(this._loadingCountTimer),this._loadingCountTimer=null),this._rebuildRequestIndex([]),data.projectName&&(document.title=`${data.projectName} - CC Viewer`),this.setState({workspaceMode:!1,projectName:data.projectName||"",viewMode:"chat",cliMode:!0,requests:[],mainAgentSessions:[],selectedIndex:null,streamingLatest:null}),isMobile&&clearEntries()}catch{}}),this.eventSource.addEventListener("workspace_stopped",()=>{this._resetSSETimeout(),this._teardownTransientLiveState(),this._rebuildRequestIndex([]),this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null,streamingLatest:null})}),this.eventSource.addEventListener("context_window",event=>{this._resetSSETimeout();try{const data=JSON.parse(event.data);this.setState({contextWindow:data,contextBarOptimistic:!1}),this._clearOptimisticTimer&&(clearTimeout(this._clearOptimisticTimer),this._clearOptimisticTimer=null)}catch{}}),this.eventSource.addEventListener("kv_cache_content",event=>{var _a,_b,_c;this._resetSSETimeout();try{const cached=JSON.parse(event.data);cached&&((null==(_a=cached.system)?void 0:_a.length)>0||(null==(_b=cached.messages)?void 0:_b.length)>0||(null==(_c=cached.tools)?void 0:_c.length)>0)&&this.setState({serverCachedContent:cached})}catch(err){console.error("Failed to parse kv_cache_content:",err)}}),this.eventSource.addEventListener("proxy_profile",event=>{this._resetSSETimeout();try{const data=JSON.parse(event.data);data.active&&this.setState({activeProxyId:data.active}),data.profile&&fetch(apiUrl("/api/proxy-profiles")).then(r=>r.json()).then(d=>{d.profiles&&this.setState({proxyProfiles:d.profiles,activeProxyId:d.active||"max"})}).catch(()=>{})}catch{}}),this.eventSource.addEventListener("ping",()=>{this._resetSSETimeout()}),this.eventSource.addEventListener("streaming_status",e=>{this._resetSSETimeout();try{JSON.parse(e.data).active?(clearTimeout(this._streamingOffTimer),this.setState({isStreaming:!0})):(clearTimeout(this._streamingOffTimer),this._streamingOffTimer=setTimeout(()=>{this.setState({isStreaming:!1})},2e3))}catch(err){console.error("Failed to parse streaming_status:",err)}}),this.eventSource.onerror=()=>{console.error("SSE连接错误")}}catch(error2){console.error("EventSource初始化失败:",error2),this.setState({fileLoading:!1,fileLoadingCount:0})}}loadLocalLogFile(file){this._isLocalLog=!0,this._localLogFile=file,this.setState({fileLoading:!0,fileLoadingCount:0,serverCachedContent:null}),this._localLogES&&(this._localLogES.close(),this._localLogES=null);const entries=[],es=new EventSource(apiUrl(`/api/local-log?file=${encodeURIComponent(file)}`));this._localLogES=es,es.addEventListener("load_start",event=>{try{JSON.parse(event.data);this.setState({fileLoadingCount:0})}catch{}}),es.addEventListener("load_chunk",event=>{try{const chunk=JSON.parse(event.data);if(Array.isArray(chunk)){for(const entry of chunk)entries.push(entry);this.setState({fileLoadingCount:entries.length})}}catch{}}),es.addEventListener("load_end",()=>{es.close();const reconstructed=reconstructEntries(entries);if(this._batchSlim(reconstructed),Array.isArray(reconstructed)&&reconstructed.length>0){const{mainAgentSessions:mainAgentSessions,filtered:filtered}=this._processEntries(reconstructed);this.setState({requests:reconstructed,selectedIndex:filtered.length>0?filtered.length-1:null,mainAgentSessions:mainAgentSessions,fileLoading:!1,fileLoadingCount:0,serverCachedContent:null})}else this.setState({fileLoading:!1,fileLoadingCount:0,serverCachedContent:null})}),es.onerror=()=>{es.close(),console.error("加载日志文件 SSE 连接错误"),this.setState({fileLoading:!1,fileLoadingCount:0})}}handleEventMessage(event){try{const entry=JSON.parse(event.data);this._pendingEntries.push(entry),this._flushRafId||(this._flushRafId=requestAnimationFrame(this._flushPendingEntries))}catch(error2){console.error("处理事件消息失败:",error2)}}async loadSession(sessionId){if(null==this._loadingSessionId){this._loadingSessionId=sessionId,this.setState({loadingSessionId:sessionId});try{let entries=await async function(projectName,sessionId){try{const db=await getDB(),key=`${projectName}:${sessionId}`;return new Promise(resolve=>{const req=db.transaction("sessions","readonly").objectStore("sessions").get(key);req.onsuccess=()=>{const data=req.result;data&&Array.isArray(data.entries)&&0!==data.entries.length?data.ts&&Date.now()-data.ts>6048e5?resolve(null):resolve(data.entries):resolve(null)},req.onerror=()=>resolve(null)})}catch{return null}}(this.state.projectName,sessionId);if(!entries||0===entries.length){const meta=(this.state.sessionIndex||[]).find(s=>s.sessionId===sessionId);if(meta&&meta.lastTs){const res=await fetch(apiUrl(`/api/entries/page?before=${encodeURIComponent(meta.lastTs)}&limit=200`));entries=(await res.json()).entries||[]}}if(entries&&entries.length>0){const merged=[...reconstructEntries(entries),...this.state.requests];this._batchSlim(merged);const{mainAgentSessions:mainAgentSessions}=this._processEntries(merged),sessionIndex=buildSessionIndex(merged,mainAgentSessions),fullIndex=mergeSessionIndices(this.state.sessionIndex,sessionIndex),unslimmed=merged.map(e=>e._slimmed?restoreSlimmedEntry(e,merged):e),{hotEntries:hotEntries,allSessions:allSessions,coldGroups:coldGroups}=splitHotCold(unslimmed,mainAgentSessions,fullIndex,8,new Set([sessionId]));this._sseSlimmer=null,this._sseReconstructor=null;const pn=this.state.projectName;if(pn){for(const[sid,coldEntries]of coldGroups)saveSessionEntries(pn,sid,coldEntries);saveSessionIndex(pn,fullIndex),saveEntries(pn,merged)}this.setState({requests:hotEntries,mainAgentSessions:allSessions,sessionIndex:fullIndex,loadingSessionId:null})}else this.setState({loadingSessionId:null})}catch(e){console.error("loadSession failed:",e),this.setState({loadingSessionId:null})}this._loadingSessionId=null}}_evictColdSessions(){const{requests:requests,mainAgentSessions:mainAgentSessions,projectName:projectName}=this.state;if(!isMobile||mainAgentSessions.length<=8)return;const unslimmed=requests.map(e=>e._slimmed?restoreSlimmedEntry(e,requests):e),{hotEntries:hotEntries,allSessions:allSessions,coldGroups:coldGroups}=splitHotCold(unslimmed,mainAgentSessions,this.state.sessionIndex,8);this._sseSlimmer=null,this._sseReconstructor=null;const fullIndex=this.state.sessionIndex;if(projectName){for(const[sid,coldEntries]of coldGroups)saveSessionEntries(projectName,sid,coldEntries);saveSessionIndex(projectName,fullIndex)}this.setState({requests:hotEntries,mainAgentSessions:allSessions,sessionIndex:fullIndex})}mergeMainAgentSessions(prevSessions,entry,options){return function(prevSessions,entry,options={}){var _a;const newMessages=entry.body.messages,newResponse=entry.response,userId=(null==(_a=entry.body.metadata)?void 0:_a.user_id)||null,entryTimestamp=entry.timestamp||null;if(0===prevSessions.length)return[{userId:userId,messages:newMessages,response:newResponse,entryTimestamp:entryTimestamp}];const lastSession=prevSessions[prevSessions.length-1],prevMsgCount=lastSession.messages?lastSession.messages.length:0,isNewConversation=prevMsgCount>0&&newMessages.length<.5*prevMsgCount&&prevMsgCount-newMessages.length>4,sameUser=null!==userId&&userId===lastSession.userId;if(isPostClearCheckpoint(entry,prevMsgCount)){for(let i=0;i<newMessages.length;i++)newMessages[i]._timestamp||(newMessages[i]._timestamp=entryTimestamp);return[...prevSessions,{userId:userId,messages:newMessages,response:newResponse,entryTimestamp:entryTimestamp}]}if(!options.skipTransientFilter&&isNewConversation&&newMessages.length<=4&&prevMsgCount>4)return prevSessions;if(sameUser||userId===lastSession.userId&&!isNewConversation){const currentLen=prevMsgCount,newLen=newMessages.length;if(newLen>currentLen){lastSession.messages||(lastSession.messages=[]);for(let i=currentLen;i<newLen;i++)newMessages[i]._timestamp||(newMessages[i]._timestamp=entryTimestamp),lastSession.messages.push(newMessages[i])}else if(newLen<currentLen){const newFps=newMessages.map(messageFingerprint),tailFps=lastSession.messages.slice(-newLen).map(messageFingerprint);let isCompressionWindow=newLen>0;for(let i=0;i<newLen;i++)if(newFps[i]!==tailFps[i]){isCompressionWindow=!1;break}if(!isCompressionWindow){for(let i=0;i<newMessages.length;i++)newMessages[i]._timestamp||(newMessages[i]._timestamp=entryTimestamp);lastSession.messages=newMessages}}else if(messageFingerprint(newMessages[newLen-1])!==messageFingerprint(lastSession.messages[currentLen-1])){const newFpsAll=newMessages.map(messageFingerprint),curMsgs=lastSession.messages;let overlap=0;for(let k=Math.min(newLen-1,currentLen);k>0;k--){let match=!0;for(let i=0;i<k;i++)if(newFpsAll[i]!==messageFingerprint(curMsgs[currentLen-k+i])){match=!1;break}if(match){overlap=k;break}}for(let i=overlap;i<newLen;i++)newMessages[i]._timestamp||(newMessages[i]._timestamp=entryTimestamp),lastSession.messages.push(newMessages[i])}return lastSession.response=newResponse,lastSession.entryTimestamp=entryTimestamp,[...prevSessions]}return[...prevSessions,{userId:userId,messages:newMessages,response:newResponse,entryTimestamp:entryTimestamp}]}(prevSessions,entry,options)}renderLogTable(logs,mobile){const columns=[{title:"",dataIndex:"file",key:"check",width:40,fixed:!!mobile&&"left",render:file=>jsxRuntimeExports.jsx(Checkbox,{checked:this.state.selectedLogs.has(file)||!1,onClick:e=>e.stopPropagation(),onChange:e=>{e.stopPropagation(),this.handleToggleLogSelect(file,e.target.checked)}})},{title:t("ui.logTime"),dataIndex:"timestamp",key:"time",width:mobile?150:180,render:ts=>jsxRuntimeExports.jsx("span",{className:styles$p.tableTimestampCell,children:this.formatTimestamp(ts,mobile)})},{title:t("ui.logPreview"),dataIndex:"preview",key:"preview",width:mobile?150:void 0,ellipsis:!0,render:arr=>{if(!Array.isArray(arr)||0===arr.length)return"—";const first=arr[0],displayText=first.length<=30&&arr.length>1?`${first} | ${arr[1]}`:first;return arr.length<=1?jsxRuntimeExports.jsx("span",{className:styles$p.tablePreviewText,children:displayText}):jsxRuntimeExports.jsx(Popover,{trigger:mobile?"click":"hover",placement:mobile?"bottomLeft":"leftTop",autoAdjustOverflow:{adjustX:!1,adjustY:!0},overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-hover)",borderRadius:8,padding:0,maxHeight:400,overflowY:"auto"},content:jsxRuntimeExports.jsx("div",{className:styles$p.previewPopover,children:arr.map((text,i)=>jsxRuntimeExports.jsx("div",{className:styles$p.previewItem,children:jsxRuntimeExports.jsx("pre",{className:styles$p.previewText,children:text})},i))}),children:jsxRuntimeExports.jsx("span",{className:styles$p.tablePreviewTextClickable,style:{textDecoration:mobile?"underline dotted #666":"none"},children:displayText})})}},...mobile?[]:[{title:t("ui.logTurns"),dataIndex:"turns",key:"turns",width:80,render:v=>jsxRuntimeExports.jsx(Tag,{className:styles$p.tableTag,children:v||0})}],{title:t("ui.logSize"),dataIndex:"size",key:"size",width:90,render:v=>jsxRuntimeExports.jsx(Tag,{className:styles$p.tableTag,children:this.formatSize(v)})},{title:t("ui.logActions"),key:"actions",width:mobile?160:180,render:(_,log)=>jsxRuntimeExports.jsxs("span",{className:styles$p.tableActionsCell,children:[jsxRuntimeExports.jsx(Button,{size:"small",type:"primary",onClick:e=>{e.stopPropagation(),this.handleOpenLogFile(log.file)},children:t("ui.openLog")}),jsxRuntimeExports.jsx(Button,{size:"small",icon:jsxRuntimeExports.jsx(RefIcon$i,{}),onClick:e=>{e.stopPropagation(),this.handleDownloadLogFile(log.file)},children:t("ui.downloadLog")})]})}];return jsxRuntimeExports.jsx(ForwardTable,{size:"small",dataSource:logs,columns:columns,rowKey:"file",pagination:!1,scroll:mobile?{x:"max-content",y:"calc(100vh - 160px)"}:{y:400},onRow:log=>({onClick:()=>{const checked=!this.state.selectedLogs.has(log.file);this.handleToggleLogSelect(log.file,checked)},style:{cursor:"pointer"}})})}formatTimestamp(ts,mobile){return!ts||ts.length<15?ts:mobile?`${ts.slice(4,6)}-${ts.slice(6,8)} ${ts.slice(9,11)}:${ts.slice(11,13)}:${ts.slice(13,15)}`:`${ts.slice(0,4)}-${ts.slice(4,6)}-${ts.slice(6,8)} ${ts.slice(9,11)}:${ts.slice(11,13)}:${ts.slice(13,15)}`}formatSize(bytes){return bytes<1024?bytes+" B":bytes<1048576?(bytes/1024).toFixed(1)+" KB":(bytes/1048576).toFixed(1)+" MB"}renderPrepare(){const{requests:requests,selectedIndex:selectedIndex,showAll:showAll,fileLoading:fileLoading,fileLoadingCount:fileLoadingCount,mainAgentSessions:mainAgentSessions,viewMode:viewMode}=this.state;this._filteredSource===requests&&this._filteredShowAll===showAll||(this._filteredSource=requests,this._filteredShowAll=showAll,this._filteredRequests=showAll?requests:filterRelevantRequests(requests));const filteredRequests=this._filteredRequests;this._cacheLossShowAll!==showAll&&(this._cacheLossShowAll=showAll,this._cacheLossMap=new Map,this._cacheLossLastMainAgent=null,this._cacheLossProcessedCount=0),filteredRequests.length<this._cacheLossProcessedCount&&(this._cacheLossMap=new Map,this._cacheLossLastMainAgent=null,this._cacheLossProcessedCount=0),filteredRequests.length>this._cacheLossProcessedCount&&(this._cacheLossLastMainAgent=appendCacheLossMap(this._cacheLossMap,filteredRequests,this._cacheLossProcessedCount,this._cacheLossLastMainAgent),this._cacheLossProcessedCount=filteredRequests.length);return{filteredRequests:filteredRequests,selectedRequest:null!==selectedIndex?filteredRequests[selectedIndex]:null,fileLoading:fileLoading,fileLoadingCount:fileLoadingCount,mainAgentSessions:mainAgentSessions,viewMode:viewMode}}renderWorkspaceMode(){return jsxRuntimeExports.jsx(ConfigProvider,{theme:this.themeConfig,children:jsxRuntimeExports.jsx(WorkspaceList,{onLaunch:this.handleWorkspaceLaunch})})}get themeConfig(){return"light"===this.state.themeColor?LIGHT_THEME_CONFIG:DARK_THEME_CONFIG}}__publicField(AppBase,"contextType",SettingsContext),function(){if(_observerStarted||"undefined"==typeof document)return;_observerStarted=!0;const observer=new MutationObserver(mutations=>{var _a;for(const mutation of mutations)for(const node of mutation.addedNodes)if(1===node.nodeType&&(null==(_a=node.querySelector)?void 0:_a.call(node,"code.language-mermaid")))return _pendingNodes.add(node),void scheduleScan()}),start=()=>observer.observe(document.body,{childList:!0,subtree:!0});document.body?start():document.addEventListener("DOMContentLoaded",start)}();const _mdCache=new Map;function renderMarkdown(text){if(!text)return"";const hit=_mdCache.get(text);if(void 0!==hit)return hit;let html;try{html=(()=>purify.sanitize(g.parse(text,{breaks:!0})))()}catch(e){html=escapeHtml(text)}return _mdCache.size>=1024&&_mdCache.delete(_mdCache.keys().next().value),_mdCache.set(text,html),html}function useMarkdownExport({getText:getText,getSnapshotTarget:getSnapshotTarget,onDone:onDone}){const savingRef=reactExports.useRef(!1);return{handleCopy:reactExports.useCallback(e=>{null==e||e.stopPropagation();const text=getText();null!=text&&(navigator.clipboard.writeText(text).then(()=>staticMethods.success(t("ui.copySuccess"))).catch(()=>{}),null==onDone||onDone())},[getText,onDone]),handleSaveAs:reactExports.useCallback(async e=>{null==e||e.stopPropagation(),null==onDone||onDone();const text=getText();if(null==text)return;const blob=new Blob([text],{type:"text/markdown;charset=utf-8"}),defaultName=`content-${(new Date).toISOString().slice(0,19).replace(/[:.]/g,"-")}.md`;if(window.showSaveFilePicker)try{const handle=await window.showSaveFilePicker({suggestedName:defaultName,types:[{description:"Markdown",accept:{"text/markdown":[".md"]}}]}),writable=await handle.createWritable();return await writable.write(blob),void(await writable.close())}catch(err){if("AbortError"===err.name)return}const url=URL.createObjectURL(blob),a=document.createElement("a");a.href=url,a.download=defaultName,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(url)},[getText,onDone]),handleSaveAsImage:reactExports.useCallback(e=>{if(null==e||e.stopPropagation(),null==onDone||onDone(),savingRef.current)return;const target=null==getSnapshotTarget?void 0:getSnapshotTarget();if(!target)return;savingRef.current=!0;const prev={height:target.style.height,maxHeight:target.style.maxHeight,overflow:target.style.overflow,overflowY:target.style.overflowY,scrollTop:target.scrollTop},needsExpand=target.scrollHeight>target.clientHeight;needsExpand&&(target.scrollTop=0,target.style.height=target.scrollHeight+"px",target.style.maxHeight="none",target.style.overflow="visible",target.style.overflowY="visible");const restore=()=>{needsExpand&&(target.style.height=prev.height,target.style.maxHeight=prev.maxHeight,target.style.overflow=prev.overflow,target.style.overflowY=prev.overflowY,target.scrollTop=prev.scrollTop)},isDark="light"!==document.documentElement.getAttribute("data-theme");__vitePreload(async()=>{const{default:html2canvas}=await import("./html2canvas.esm-HFdlUwfn.js");return{default:html2canvas}},[]).then(({default:html2canvas})=>{html2canvas(target,{backgroundColor:isDark?"#0a0a0a":"#ffffff",scale:2,useCORS:!0}).then(canvas=>{restore(),canvas.toBlob(blob=>{if(!blob)return void(savingRef.current=!1);const url=URL.createObjectURL(blob),a=document.createElement("a");a.href=url,a.download=`content-${(new Date).toISOString().slice(0,19).replace(/[:.]/g,"-")}.png`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(url),canvas.width=0,canvas.height=0,savingRef.current=!1},"image/png")}).catch(err=>{restore(),console.warn("html2canvas render failed:",err),savingRef.current=!1})}).catch(err=>{restore(),console.warn("html2canvas load failed:",err),savingRef.current=!1})},[getSnapshotTarget,onDone]),handleSaveToProject:reactExports.useCallback(async e=>{null==e||e.stopPropagation(),null==onDone||onDone();const text=getText();if(null==text)return;const defaultName=`content-${(new Date).toISOString().slice(0,19).replace(/[:.]/g,"-")}.md`,fileName2=window.prompt(t("ui.saveToProject.prompt"),defaultName);if(fileName2)try{const res=await fetch(apiUrl("/api/file-content"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:fileName2,content:text})});if(res.ok)staticMethods.success(t("ui.saveToProject.success",{name:fileName2}));else{const data=await res.json().catch(()=>({}));staticMethods.error(data.error||t("ui.saveFailed"))}}catch(err){staticMethods.error(err.message||t("ui.saveFailed"))}},[getText,onDone])}}const styles$o_mdBlockWrapper="_mdBlockWrapper_7yafy_1",styles$o_actionBar="_actionBar_7yafy_5",styles$o_hoverPad="_hoverPad_7yafy_28",styles$o_hoverPadTop="_hoverPadTop_7yafy_34",styles$o_hoverPadBottom="_hoverPadBottom_7yafy_37",styles$o_actionBtn="_actionBtn_7yafy_46",styles$o_saveAsWrap="_saveAsWrap_7yafy_68",styles$o_saveMenu="_saveMenu_7yafy_72",styles$o_saveMenuItem="_saveMenuItem_7yafy_87",styles$o_streamingTail="_streamingTail_7yafy_110";const MarkdownBlock$1=React__default.memo(function({text:text,className:className,style:style,trailingCursor:trailingCursor}){const[hovered,setHovered]=reactExports.useState(!1),[saveMenuOpen,setSaveMenuOpen]=reactExports.useState(!1),timerRef=reactExports.useRef(null),wrapRef=reactExports.useRef(null);reactExports.useRef(0);const textRef=reactExports.useRef(text);textRef.current=text;const{handleCopy:handleCopy,handleSaveAs:handleSaveAs,handleSaveAsImage:handleSaveAsImage,handleSaveToProject:handleSaveToProject}=useMarkdownExport({getText:reactExports.useCallback(()=>textRef.current,[]),getSnapshotTarget:reactExports.useCallback(()=>{var _a;return(null==(_a=wrapRef.current)?void 0:_a.closest('[class*="bubble"]'))||wrapRef.current},[]),onDone:reactExports.useCallback(()=>setSaveMenuOpen(!1),[])});reactExports.useEffect(()=>()=>clearTimeout(timerRef.current),[]);const html=reactExports.useMemo(()=>text?trailingCursor?function(text){const[frozen,tail]=function(text){if(!text)return["",""];if((text.match(/^```/gm)||[]).length%2==1)return["",text];if(/^\[[^\]]+\]:\s/m.test(text))return["",text];const idx=text.lastIndexOf("\n\n");if(idx<0)return["",text];const prevLineStart=text.lastIndexOf("\n",idx-1)+1,lineBefore=text.slice(prevLineStart,idx),nextLineEnd=text.indexOf("\n",idx+2),lineAfter=text.slice(idx+2,nextLineEnd<0?text.length:nextLineEnd);return lineBefore.trimStart().startsWith("|")||lineAfter.trimStart().startsWith("|")?["",text]:[text.slice(0,idx+2),text.slice(idx+2)]}(text);return renderMarkdown(frozen)+(tail?renderMarkdown(tail):"")}(text):renderMarkdown(text):"",[text,trailingCursor]);if(reactExports.useEffect(()=>{}),!text)return null;const handleMouseEnter=reactExports.useCallback(()=>{clearTimeout(timerRef.current),setHovered(!0)},[]),handleMouseLeave=reactExports.useCallback(()=>{timerRef.current=setTimeout(()=>{setHovered(!1),setSaveMenuOpen(!1)},150)},[]);return jsxRuntimeExports.jsxs("div",{ref:wrapRef,className:styles$o_mdBlockWrapper,onMouseEnter:isMobile&&!isPad?void 0:handleMouseEnter,onMouseLeave:isMobile&&!isPad?void 0:handleMouseLeave,children:[jsxRuntimeExports.jsx("div",{className:`chat-md ${className||""} ${trailingCursor?styles$o_streamingTail:""}`,style:style,dangerouslySetInnerHTML:{__html:html}}),(!isMobile||isPad)&&hovered&&jsxRuntimeExports.jsxs("div",{className:styles$o_actionBar,"data-html2canvas-ignore":!0,children:[jsxRuntimeExports.jsx("div",{className:`${styles$o_hoverPad} ${styles$o_hoverPadTop}`,"aria-hidden":"true"}),jsxRuntimeExports.jsxs("div",{className:styles$o_saveAsWrap,onMouseEnter:()=>setSaveMenuOpen(!0),onMouseLeave:()=>setSaveMenuOpen(!1),children:[jsxRuntimeExports.jsx(Tooltip,{title:saveMenuOpen?"":t("ui.saveAs"),mouseEnterDelay:.3,children:jsxRuntimeExports.jsx("span",{className:styles$o_actionBtn,children:jsxRuntimeExports.jsx(RefIcon$i,{})})}),saveMenuOpen&&jsxRuntimeExports.jsxs("div",{className:styles$o_saveMenu,children:[jsxRuntimeExports.jsxs("button",{className:styles$o_saveMenuItem,onClick:handleSaveAs,children:[jsxRuntimeExports.jsx(RefIcon$i,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveAsMd")})]}),jsxRuntimeExports.jsxs("button",{className:styles$o_saveMenuItem,onClick:handleCopy,children:[jsxRuntimeExports.jsx(RefIcon$j,{}),jsxRuntimeExports.jsx("span",{children:t("ui.copyTextContent")})]}),jsxRuntimeExports.jsxs("button",{className:styles$o_saveMenuItem,onClick:handleSaveAsImage,children:[jsxRuntimeExports.jsx(RefIcon$9,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveAsImage")})]}),jsxRuntimeExports.jsxs("button",{className:styles$o_saveMenuItem,onClick:handleSaveToProject,children:[jsxRuntimeExports.jsx(RefIcon$2,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveToProject")})]})]})]}),jsxRuntimeExports.jsx("div",{className:`${styles$o_hoverPad} ${styles$o_hoverPadBottom}`,"aria-hidden":"true"})]})]})}),ROLE_MAP={worker:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Wrench: represents hands-on execution and building --\x3e\n <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>\n</svg>\n'},reviewer:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Eye with checkmark: represents code review and approval --\x3e\n \x3c!-- Eye shape --\x3e\n <path d="M3 12s3-7 9-7 9 7 9 7-3 7-9 7-9-7-9-7z"/>\n \x3c!-- Checkmark inside eye (replaces pupil) --\x3e\n <path d="m9 12 2 2 4-4"/>\n</svg>\n'},researcher:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Microscope: eyepiece, tube, lens, stage, base --\x3e\n <path d="M14 4l2 1"/>\n <path d="M12 6l2-1"/>\n <path d="M13 5l-3 8"/>\n <circle cx="9" cy="15" r="2"/>\n <line x1="5" y1="18" x2="15" y2="18"/>\n <line x1="10" y1="18" x2="10" y2="21"/>\n <line x1="6" y1="21" x2="14" y2="21"/>\n</svg>\n'},explorer:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Compass: outer circle with diamond pointer --\x3e\n <circle cx="12" cy="12" r="9"/>\n <polygon points="12,4 14,11 12,9 10,11" fill="currentColor" stroke="none"/>\n <polygon points="12,20 10,13 12,15 14,13" fill="currentColor" stroke="none"/>\n <circle cx="12" cy="12" r="2"/>\n</svg>\n'},analyst:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Bar chart: represents data analysis --\x3e\n \x3c!-- Three vertical bars of varying height --\x3e\n <line x1="18" y1="20" x2="18" y2="10"/>\n <line x1="12" y1="20" x2="12" y2="4"/>\n <line x1="6" y1="20" x2="6" y2="14"/>\n</svg>\n'},tracer:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Winding path with waypoints: tracing execution flow --\x3e\n <path d="M4 6c4 0 4 4 8 4s4-4 8-4" stroke-dasharray="3 2"/>\n <path d="M4 18c4 0 4-4 8-4s4 4 8 4" stroke-dasharray="3 2"/>\n <circle cx="4" cy="6" r="1.5" fill="currentColor" stroke="none"/>\n <circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none"/>\n <circle cx="20" cy="18" r="1.5" fill="currentColor" stroke="none"/>\n</svg>\n'},investigator:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <circle cx="10" cy="10" r="6"/>\n <line x1="14.2" y1="14.2" x2="20" y2="20"/>\n <path d="M8 8.5c0.5-0.5 1.5-1 2.5-0.5"/>\n <circle cx="10" cy="11" r="1.5"/>\n</svg>\n'},builder:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <rect x="3" y="15" width="8" height="5" rx="0.5"/>\n <rect x="7" y="9" width="8" height="5" rx="0.5"/>\n <rect x="11" y="3" width="8" height="5" rx="0.5"/>\n</svg>\n'},implementer:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="5 7 3 12 5 17"/>\n <polyline points="19 7 21 12 19 17"/>\n <line x1="9" y1="12" x2="15" y2="12"/>\n <polyline points="13 9 15 12 13 15"/>\n</svg>\n'},auditor:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <rect x="5" y="3" width="14" height="18" rx="2" />\n <rect x="9" y="2" width="6" height="3" rx="1" />\n <polyline points="9 13 11 15 15 11" />\n</svg>\n'},translator:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <circle cx="10" cy="12" r="7" />\n <path d="M10 5 C7 5 5 8 5 12 S7 19 10 19" />\n <path d="M10 5 C13 5 15 8 15 12 S13 19 10 19" />\n <line x1="3" y1="12" x2="17" y2="12" />\n <line x1="10" y1="5" x2="10" y2="19" />\n <path d="M18 7 L20 7 L19 10" />\n <path d="M18 7 C18.5 8.5 20 10 21 10" />\n</svg>\n'},security:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M12 3 L4 7 C4 7 3 16 12 21 C21 16 20 7 20 7 L12 3 Z" />\n <rect x="10" y="10" width="4" height="4" rx="1" />\n <path d="M12 10 V8 A2 2 0 0 1 14 8 V10" />\n</svg>\n'},scanner:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M12 12L18 6"/>\n <path d="M12 12a3 3 0 0 1-2.12-5.12"/>\n <path d="M12 12a5 5 0 0 1-3.54-8.54"/>\n <path d="M12 12a8 8 0 0 1-5.66-2.34"/>\n <circle cx="12" cy="12" r="2"/>\n</svg>\n'},expert:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polygon points="12,4 14.5,9.5 20,10 16,14 17,20 12,17 7,20 8,14 4,10 9.5,9.5"/>\n <circle cx="12" cy="12" r="9"/>\n</svg>\n'},executor:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polygon points="13,2 5,14 12,14 11,22 19,10 12,10"/>\n</svg>\n'},designer:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M12 19l7-7 3 3-7 7-3-3z"/>\n <path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/>\n <path d="M2 2l7.586 7.586"/>\n <circle cx="11" cy="11" r="2"/>\n</svg>\n'},default:{svg:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <circle cx="10" cy="7" r="4"/>\n <path d="M3 21v-2a7 7 0 0 1 14 0v2"/>\n <path d="M20 9v0a2 2 0 1 1 0 4"/>\n <path d="M20 17v1"/>\n</svg>\n'}},PREFIX_RULES=[{prefix:"worker-",role:"worker"},{prefix:"reviewer-",role:"reviewer"},{prefix:"researcher-",role:"researcher"},{prefix:"explorer-",role:"explorer"},{prefix:"explore-",role:"explorer"},{prefix:"translator-",role:"translator"},{prefix:"svg-creator-",role:"designer"}],SUFFIX_RULES=[{suffix:"-reviewer",role:"reviewer"},{suffix:"-analyst",role:"analyst"},{suffix:"-tracer",role:"tracer"},{suffix:"-investigator",role:"investigator"},{suffix:"-builder",role:"builder"},{suffix:"-impl",role:"implementer"},{suffix:"-auditor",role:"auditor"},{suffix:"-scanner",role:"scanner"},{suffix:"-expert",role:"expert"},{suffix:"-executor",role:"executor"}],CONTAINS_RULES=[{keyword:"security",role:"security"},{keyword:"implementer",role:"implementer"},{keyword:"review",role:"reviewer"},{keyword:"explor",role:"explorer"},{keyword:"research",role:"researcher"},{keyword:"analy",role:"analyst"},{keyword:"trac",role:"tracer"},{keyword:"investigat",role:"investigator"},{keyword:"build",role:"builder"},{keyword:"audit",role:"auditor"},{keyword:"translat",role:"translator"},{keyword:"scan",role:"scanner"},{keyword:"expert",role:"expert"},{keyword:"execut",role:"executor"},{keyword:"design",role:"designer"},{keyword:"work",role:"worker"}],ABBREV_PREFIX_RULES=[{prefix:"cr-",role:"reviewer"},{prefix:"r-",role:"reviewer"},{prefix:"ui-",role:"reviewer"},{prefix:"ux-",role:"reviewer"}],ROLE_KEYS=Object.keys(ROLE_MAP).filter(k=>"default"!==k);function getTeammateAvatar(name){let clean=(name||"").trim();clean=clean.replace(/^Teammate:\s*/i,""),clean=clean.replace(/\([^)]*\)\s*$/,"").trim();const role=function(name){const lower=name.toLowerCase();for(const{prefix:prefix2,role:role}of PREFIX_RULES)if(lower.startsWith(prefix2))return role;for(const{suffix:suffix,role:role}of SUFFIX_RULES)if(lower.endsWith(suffix))return role;for(const{keyword:keyword,role:role}of CONTAINS_RULES)if(lower.includes(keyword))return role;for(const{prefix:prefix2,role:role}of ABBREV_PREFIX_RULES)if(lower.startsWith(prefix2))return role;if(lower.length>0){let hash=0;for(let i=0;i<lower.length;i++)hash=lower.charCodeAt(i)+((hash<<5)-hash);return ROLE_KEYS[(hash%ROLE_KEYS.length+ROLE_KEYS.length)%ROLE_KEYS.length]}return"default"}(clean),entry=ROLE_MAP[role],color=`var(--avatar-bg-${function(name){let hash=0;for(let i=0;i<name.length;i++)hash=name.charCodeAt(i)+((hash<<5)-hash);return(hash%20+20)%20}(clean)})`;return{svg:entry.svg,color:color,role:role}}const SYSTEM_TAGS=["system-reminder","local-command-caveat","project-reminder","important-instruction-reminders","file-modified-reminder","todo-reminder","user-prompt-submit-hook","local-command-stdout","command-name","task-notification","environment_details","context"];const _tagCache=new Map;function renderAssistantText(text){if(!text)return{segments:[]};const hit=_tagCache.get(text);if(hit)return hit;const result=function(text){if(!text)return{segments:[]};const tagPattern=new RegExp("<("+SYSTEM_TAGS.join("|")+")\\b[^>]*>([\\s\\S]*?)</\\1>","gi"),segments=[];let match,lastIndex=0;for(;null!==(match=tagPattern.exec(text));){if(match.index>lastIndex){const before=text.slice(lastIndex,match.index).trim();before&&segments.push({type:"text",content:before})}segments.push({type:"system-tag",tag:match[1],content:match[2].trim()}),lastIndex=match.index+match[0].length}if(lastIndex<text.length){const rest=text.slice(lastIndex).trim();rest&&segments.push({type:"text",content:rest})}return{segments:segments}}(text);return _tagCache.size>=512&&_tagCache.delete(_tagCache.keys().next().value),_tagCache.set(text,result),result}function optionAriaLabel(opt){return opt&&null!=opt.label?opt.description?`${opt.label}: ${opt.description}`:String(opt.label):""}function hasOptionDescription(opt){return Boolean(opt&&opt.description)}const styles$n_avatar="_avatar_1e4n5_3",styles$n_avatarImg="_avatarImg_1e4n5_20",styles$n_messageRow="_messageRow_1e4n5_41",styles$n_messageRowEnd="_messageRowEnd_1e4n5_47",styles$n_contentCol="_contentCol_1e4n5_56",styles$n_contentColLimited="_contentColLimited_1e4n5_60",styles$n_labelRow="_labelRow_1e4n5_68",styles$n_labelRowEnd="_labelRowEnd_1e4n5_75",styles$n_labelRight="_labelRight_1e4n5_82",styles$n_labelText="_labelText_1e4n5_90",styles$n_timeText="_timeText_1e4n5_94",styles$n_timeTextNoMargin="_timeTextNoMargin_1e4n5_100",styles$n_cacheContextText="_cacheContextText_1e4n5_106",styles$n_labelTextRight="_labelTextRight_1e4n5_114",styles$n_bubbleUser="_bubbleUser_1e4n5_121 _bubble_1e4n5_28",styles$n_bubbleAssistant="_bubbleAssistant_1e4n5_133 _bubble_1e4n5_28",styles$n_bubbleHighlight="_bubbleHighlight_1e4n5_149",styles$n_bubbleHighlightFading="_bubbleHighlightFading_1e4n5_153",styles$n_borderSvg="_borderSvg_1e4n5_158",styles$n_borderSvgInset="_borderSvgInset_1e4n5_167",styles$n_borderSvgFading="_borderSvgFading_1e4n5_171",styles$n_borderRect="_borderRect_1e4n5_176",styles$n_bubblePlan="_bubblePlan_1e4n5_185 _bubble_1e4n5_28",styles$n_bubbleSubAgent="_bubbleSubAgent_1e4n5_193 _bubble_1e4n5_28",styles$n_systemTagLabel="_systemTagLabel_1e4n5_213",styles$n_skillLabel="_skillLabel_1e4n5_217",styles$n_systemTagPre="_systemTagPre_1e4n5_222",styles$n_collapseMargin="_collapseMargin_1e4n5_230",styles$n_collapseNoMargin="_collapseNoMargin_1e4n5_234",styles$n_collapseStream="_collapseStream_1e4n5_239",styles$n_thinkingLabel="_thinkingLabel_1e4n5_255",styles$n_thinkingEmptyHint="_thinkingEmptyHint_1e4n5_259",styles$n_thinkingEmptyText="_thinkingEmptyText_1e4n5_267",styles$n_enableThinkingBtn="_enableThinkingBtn_1e4n5_272",styles$n_bashCollapseLabel="_bashCollapseLabel_1e4n5_277",styles$n_toolBox="_toolBox_1e4n5_284",styles$n_toolLabel="_toolLabel_1e4n5_297",styles$n_simplifiedToolLabel="_simplifiedToolLabel_1e4n5_301",styles$n_simplifiedToolTag="_simplifiedToolTag_1e4n5_310",styles$n_simplifiedToolPopoverContent="_simplifiedToolPopoverContent_1e4n5_328",styles$n_codePre="_codePre_1e4n5_341",styles$n_pathTag="_pathTag_1e4n5_372",styles$n_pathTagClickable="_pathTagClickable_1e4n5_377",styles$n_descSpan="_descSpan_1e4n5_390",styles$n_secondarySpan="_secondarySpan_1e4n5_395",styles$n_patternSpan="_patternSpan_1e4n5_399",styles$n_kvContainer="_kvContainer_1e4n5_405",styles$n_kvItem="_kvItem_1e4n5_410",styles$n_kvKey="_kvKey_1e4n5_414",styles$n_kvValue="_kvValue_1e4n5_418",styles$n_teammateStatusRow="_teammateStatusRow_1e4n5_439",styles$n_teammateStatusRowCenter="_teammateStatusRowCenter_1e4n5_445",styles$n_teammateStatusBubble="_teammateStatusBubble_1e4n5_451",styles$n_taskNotifUsage="_taskNotifUsage_1e4n5_468",styles$n_sendMessageBlock="_sendMessageBlock_1e4n5_478",styles$n_sendMessageHeader="_sendMessageHeader_1e4n5_486",styles$n_compactLabel="_compactLabel_1e4n5_493",styles$n_compactPre="_compactPre_1e4n5_498",styles$n_viewRequestBtn="_viewRequestBtn_1e4n5_508",styles$n_viewRequestIcon="_viewRequestIcon_1e4n5_520",styles$n_optionList="_optionList_1e4n5_545",styles$n_questionSpacing="_questionSpacing_1e4n5_557",styles$n_askQuestionBox="_askQuestionBox_1e4n5_570",styles$n_askValidationErrorBadge="_askValidationErrorBadge_1e4n5_579",styles$n_askValidationErrorTitle="_askValidationErrorTitle_1e4n5_588",styles$n_askValidationErrorDetails="_askValidationErrorDetails_1e4n5_593",styles$n_askValidationErrorRawText="_askValidationErrorRawText_1e4n5_602",styles$n_askQuestionHeader="_askQuestionHeader_1e4n5_616",styles$n_askQuestionText="_askQuestionText_1e4n5_627",styles$n_askOptionItem="_askOptionItem_1e4n5_633",styles$n_askOptionSelected="_askOptionSelected_1e4n5_642",styles$n_askOptionDesc="_askOptionDesc_1e4n5_647",styles$n_askCheckSvg="_askCheckSvg_1e4n5_651",styles$n_planModeBox="_planModeBox_1e4n5_658",styles$n_planStatusPending="_planStatusPending_1e4n5_668",styles$n_planModeLabel="_planModeLabel_1e4n5_673",styles$n_planModePermissions="_planModePermissions_1e4n5_678",styles$n_planModePermLabel="_planModePermLabel_1e4n5_684",styles$n_planModeHeader="_planModeHeader_1e4n5_690",styles$n_planStatusBadge="_planStatusBadge_1e4n5_696",styles$n_planStatusApproved="_planStatusApproved_1e4n5_704",styles$n_planStatusRejected="_planStatusRejected_1e4n5_713",styles$n_planContentPreview="_planContentPreview_1e4n5_731",styles$n_planFeedback="_planFeedback_1e4n5_744",styles$n_planFeedbackLabel="_planFeedbackLabel_1e4n5_753",styles$n_planApprovalActions="_planApprovalActions_1e4n5_758",styles$n_planApproveBtn="_planApproveBtn_1e4n5_765",styles$n_planRejectBtn="_planRejectBtn_1e4n5_780",styles$n_planOptionBtn="_planOptionBtn_1e4n5_795",styles$n_dangerApprovalBox="_dangerApprovalBox_1e4n5_810",styles$n_dangerApprovalBoxDenied="_dangerApprovalBoxDenied_1e4n5_819",styles$n_ultraplanBadge="_ultraplanBadge_1e4n5_823",styles$n_dangerApprovalHeader="_dangerApprovalHeader_1e4n5_829",styles$n_dangerApprovalIcon="_dangerApprovalIcon_1e4n5_835",styles$n_dangerApprovalLabel="_dangerApprovalLabel_1e4n5_840",styles$n_dangerApprovalActions="_dangerApprovalActions_1e4n5_845",styles$n_dangerApproveBtn="_dangerApproveBtn_1e4n5_852",styles$n_dangerRejectBtn="_dangerRejectBtn_1e4n5_867",styles$n_dangerOptionBtn="_dangerOptionBtn_1e4n5_882",styles$n_dangerDeniedBadge="_dangerDeniedBadge_1e4n5_897",styles$n_dangerDeniedDetail="_dangerDeniedDetail_1e4n5_908",styles$n_planFeedbackInputWrap="_planFeedbackInputWrap_1e4n5_918",styles$n_planFeedbackTextarea="_planFeedbackTextarea_1e4n5_922",styles$n_planFeedbackBtnRow="_planFeedbackBtnRow_1e4n5_942",styles$n_planFeedbackSendBtn="_planFeedbackSendBtn_1e4n5_949",styles$n_planFeedbackCancelBtn="_planFeedbackCancelBtn_1e4n5_969",styles$n_askQuestionInteractive="_askQuestionInteractive_1e4n5_986",styles$n_askRadioGroup="_askRadioGroup_1e4n5_997",styles$n_askRadioItem="_askRadioItem_1e4n5_1005",styles$n_askRadioItemSelected="_askRadioItemSelected_1e4n5_1028",styles$n_askRadioDot="_askRadioDot_1e4n5_1034",styles$n_askOptionBody="_askOptionBody_1e4n5_1045",styles$n_askOptionLabel="_askOptionLabel_1e4n5_1053",styles$n_askCheckboxGroup="_askCheckboxGroup_1e4n5_1072",styles$n_askOtherInput="_askOtherInput_1e4n5_1098",styles$n_askSubmitRow="_askSubmitRow_1e4n5_1118",styles$n_askSubmitBtn="_askSubmitBtn_1e4n5_1124",styles$n_askMarkdownLayout="_askMarkdownLayout_1e4n5_1144",styles$n_askOptionsBody="_askOptionsBody_1e4n5_1156",styles$n_askMarkdownPreview="_askMarkdownPreview_1e4n5_1160",styles$n_chatImageFallback="_chatImageFallback_1e4n5_1186",styles$n_chatImageImg="_chatImageImg_1e4n5_1191",styles$n_bubbleRelative="_bubbleRelative_1e4n5_1202",styles$n_skillSpacer="_skillSpacer_1e4n5_1208",styles$n_skillTimeIndent="_skillTimeIndent_1e4n5_1215",styles$n_previewPlaceholder="_previewPlaceholder_1e4n5_1219";class AskQuestionForm extends React__default.Component{constructor(props){super(props),this.state={selections:{},multiSelections:{},otherActive:{},otherText:{},submitting:!1}}componentWillUnmount(){this._submitTimeout&&clearTimeout(this._submitTimeout)}render(){const{questions:rawQuestions,onSubmit:onSubmit}=this.props,questions=Array.isArray(rawQuestions)?rawQuestions:[],{selections:selections,multiSelections:multiSelections,otherActive:otherActive,otherText:otherText,submitting:submitting}=this.state,allValid=questions.every((q,qi)=>{if(otherActive[qi])return(otherText[qi]||"").trim().length>0;if(q.multiSelect){const set=multiSelections[qi];return set&&set.size>0}return null!=selections[qi]});return jsxRuntimeExports.jsxs("div",{className:styles$n_askQuestionInteractive,children:[jsxRuntimeExports.jsx("svg",{className:`${styles$n_borderSvg} ${styles$n_borderSvgInset}`,preserveAspectRatio:"none",children:jsxRuntimeExports.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",rx:"6",ry:"6",fill:"none",stroke:"#1668dc",strokeWidth:"1",strokeDasharray:"6 4",className:styles$n_borderRect})}),questions.map((q,qi)=>{var _a;const isMulti=q.multiSelect,hasPreview=!isMulti&&(null==(_a=q.options)?void 0:_a.some(o2=>o2.preview)),selectedLabel=selections[qi],focusedPreview=hasPreview&&selectedLabel?(q.options.find(o2=>o2.label===selectedLabel)||{}).preview:null,headerAndQuestion=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[q.header&&jsxRuntimeExports.jsx("span",{className:styles$n_askQuestionHeader,children:q.header}),jsxRuntimeExports.jsx("div",{className:styles$n_askQuestionText,children:q.question})]}),optionsBody=jsxRuntimeExports.jsxs("div",{className:styles$n_askOptionsBody,children:[isMulti?jsxRuntimeExports.jsxs("div",{className:styles$n_askCheckboxGroup,role:"group",children:[(q.options||[]).map((opt,oi)=>{const checked=!(!multiSelections[qi]||!multiSelections[qi].has(opt.label)),activate=()=>{this.setState(prev=>{const prevSet=prev.multiSelections[qi]||new Set,next=new Set(prevSet);return next.has(opt.label)?next.delete(opt.label):next.add(opt.label),{multiSelections:{...prev.multiSelections,[qi]:next},otherActive:{...prev.otherActive,[qi]:!1}}})};return jsxRuntimeExports.jsxs("div",{role:"checkbox","aria-checked":checked,tabIndex:0,"aria-label":optionAriaLabel(opt),className:`${styles$n_askRadioItem}${checked?" "+styles$n_askRadioItemSelected:""}`,onClick:activate,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),activate())},children:[jsxRuntimeExports.jsx("span",{className:styles$n_askRadioDot,children:checked?"☑":"☐"}),jsxRuntimeExports.jsxs("span",{className:styles$n_askOptionBody,children:[jsxRuntimeExports.jsx("span",{className:styles$n_askOptionLabel,children:opt.label}),hasOptionDescription(opt)&&jsxRuntimeExports.jsx("span",{className:styles$n_askOptionDesc,children:opt.description})]})]},oi)}),!(q.options||[]).some(o2=>/^other$/i.test(o2.label))&&(()=>{const activate=()=>{this.setState(prev=>({otherActive:{...prev.otherActive,[qi]:!0},multiSelections:{...prev.multiSelections,[qi]:new Set}}))};return jsxRuntimeExports.jsxs("div",{role:"checkbox","aria-checked":!!otherActive[qi],tabIndex:0,"aria-label":t("ui.askOther"),className:`${styles$n_askRadioItem}${otherActive[qi]?" "+styles$n_askRadioItemSelected:""}`,onClick:activate,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),activate())},children:[jsxRuntimeExports.jsx("span",{className:styles$n_askRadioDot,children:otherActive[qi]?"☑":"☐"}),jsxRuntimeExports.jsx("span",{className:styles$n_askOptionBody,children:jsxRuntimeExports.jsx("span",{className:styles$n_askOptionLabel,children:t("ui.askOther")})})]})})()]}):jsxRuntimeExports.jsxs("div",{className:styles$n_askRadioGroup,role:"radiogroup",children:[(q.options||[]).map((opt,oi)=>{const isOtherOpt=/^other$/i.test(opt.label),isSelected=isOtherOpt?otherActive[qi]:!otherActive[qi]&&selectedLabel===opt.label,activate=()=>{isOtherOpt?this.setState(prev=>({otherActive:{...prev.otherActive,[qi]:!0},selections:{...prev.selections,[qi]:void 0}})):this.setState(prev=>({selections:{...prev.selections,[qi]:opt.label},otherActive:{...prev.otherActive,[qi]:!1}}))};return jsxRuntimeExports.jsxs("div",{role:"radio","aria-checked":isSelected,tabIndex:0,"aria-label":optionAriaLabel(opt),className:`${styles$n_askRadioItem}${isSelected?" "+styles$n_askRadioItemSelected:""}`,onClick:activate,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),activate())},children:[jsxRuntimeExports.jsx("span",{className:styles$n_askRadioDot,children:isSelected?"◉":"○"}),jsxRuntimeExports.jsxs("span",{className:styles$n_askOptionBody,children:[jsxRuntimeExports.jsx("span",{className:styles$n_askOptionLabel,children:opt.label}),hasOptionDescription(opt)&&jsxRuntimeExports.jsx("span",{className:styles$n_askOptionDesc,children:opt.description})]})]},oi)}),!(q.options||[]).some(o2=>/^other$/i.test(o2.label))&&(()=>{const activate=()=>{this.setState(prev=>({otherActive:{...prev.otherActive,[qi]:!0},selections:{...prev.selections,[qi]:void 0}}))};return jsxRuntimeExports.jsxs("div",{role:"radio","aria-checked":!!otherActive[qi],tabIndex:0,"aria-label":t("ui.askOther"),className:`${styles$n_askRadioItem}${otherActive[qi]?" "+styles$n_askRadioItemSelected:""}`,onClick:activate,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),activate())},children:[jsxRuntimeExports.jsx("span",{className:styles$n_askRadioDot,children:otherActive[qi]?"◉":"○"}),jsxRuntimeExports.jsx("span",{className:styles$n_askOptionBody,children:jsxRuntimeExports.jsx("span",{className:styles$n_askOptionLabel,children:t("ui.askOther")})})]})})()]}),otherActive[qi]&&jsxRuntimeExports.jsx("div",{className:styles$n_askOtherInput,children:jsxRuntimeExports.jsx(Input,{size:"small",placeholder:t("ui.askOtherPlaceholder"),value:otherText[qi]||"",onChange:e=>this.setState(prev=>({otherText:{...prev.otherText,[qi]:e.target.value}})),autoFocus:!0})})]});return jsxRuntimeExports.jsxs("div",{className:qi<questions.length-1?styles$n_questionSpacing:void 0,children:[headerAndQuestion,hasPreview?jsxRuntimeExports.jsxs("div",{className:styles$n_askMarkdownLayout,children:[optionsBody,jsxRuntimeExports.jsx("div",{className:styles$n_askMarkdownPreview,children:focusedPreview?jsxRuntimeExports.jsx("pre",{children:focusedPreview}):jsxRuntimeExports.jsx("span",{className:styles$n_previewPlaceholder,children:"—"})})]}):optionsBody]},qi)}),jsxRuntimeExports.jsx("div",{className:styles$n_askSubmitRow,children:jsxRuntimeExports.jsx("button",{className:styles$n_askSubmitBtn,disabled:!allValid||submitting,onClick:()=>{if(!allValid||submitting)return;this.setState({submitting:!0}),this._submitTimeout&&clearTimeout(this._submitTimeout),this._submitTimeout=setTimeout(()=>{this.setState({submitting:!1})},3e4);const answers=questions.map((q,qi)=>{if(otherActive[qi]){return{questionIndex:qi,type:"other",optionIndex:(q.options||[]).length,text:(otherText[qi]||"").trim(),isMultiSelect:!!q.multiSelect}}if(q.multiSelect){const set=multiSelections[qi]||new Set,selectedIndices=[];return(q.options||[]).forEach((opt,oi)=>{set.has(opt.label)&&selectedIndices.push(oi)}),{questionIndex:qi,type:"multi",selectedIndices:selectedIndices}}const selectedLabel=selections[qi];return{questionIndex:qi,type:"single",optionIndex:(q.options||[]).findIndex(o2=>o2.label===selectedLabel)}});onSubmit&&onSubmit(answers)},children:t(submitting?"ui.askSubmitting":"ui.askSubmit")})})]})}}const ApprovalPortalContext=reactExports.createContext({ptyPlanSlot:null,askSlot:null,activePtyPlanId:null,activeAskId:null});function isPlanApprovalPrompt(prompt){if(!prompt||!prompt.question)return!1;const q=prompt.question.toLowerCase();if(/plan/i.test(q)&&(/approv/i.test(q)||/proceed/i.test(q)||/accept/i.test(q)))return!0;if(Array.isArray(prompt.options)&&3===prompt.options.length){const texts=prompt.options.map(o2=>(o2.text||"").toLowerCase()),hasApprove=texts.some(t2=>/\bapprov/i.test(t2)),hasEdit=texts.some(t2=>/\bedits?\b|\bmodify/i.test(t2)),hasReject=texts.some(t2=>/\breject\b|\bdeny\b|keep planning|\bno,/i.test(t2));if(hasApprove&&hasEdit&&hasReject)return!0}return!1}function isDangerousOperationPrompt(prompt){if(!prompt||!prompt.question)return!1;const q=prompt.question;if(isPlanApprovalPrompt(prompt))return!1;if(/do you want to (make this edit|write|proceed|create|delete)|allow\b.*\bto\b|want to allow|wants to (execute|run|read|write|access|create|delete|modify|use)|may .*(read|write|execute|run|access|create|delete|modify)|grant .*(access|permission)|permit/i.test(q))return!0;if(prompt.options&&prompt.options.length>=2){const texts=prompt.options.map(o2=>(o2.text||"").toLowerCase()),hasAllow=texts.some(t2=>/^allow|^yes/i.test(t2)),hasDeny=texts.some(t2=>/^no$|^no[^a-z]|^deny|^reject/i.test(t2));if(hasAllow&&hasDeny)return!0}return!1}class Diff{diff(oldStr,newStr,options={}){let callback;"function"==typeof options?(callback=options,options={}):"callback"in options&&(callback=options.callback);const oldString=this.castInput(oldStr,options),newString=this.castInput(newStr,options),oldTokens=this.removeEmpty(this.tokenize(oldString,options)),newTokens=this.removeEmpty(this.tokenize(newString,options));return this.diffWithOptionsObj(oldTokens,newTokens,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){var _a;const done=value=>(value=this.postProcess(value,options),callback?void setTimeout(function(){callback(value)},0):value),newLen=newTokens.length,oldLen=oldTokens.length;let editLength=1,maxEditLength=newLen+oldLen;null!=options.maxEditLength&&(maxEditLength=Math.min(maxEditLength,options.maxEditLength));const maxExecutionTime=null!==(_a=options.timeout)&&void 0!==_a?_a:1/0,abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}];let newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0;const execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath;const removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];removePath&&(bestPath[diagonalPath-1]=void 0);let canAdd=!1;if(addPath){const addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}const canRemove=removePath&&removePath.oldPos+1<oldLen;if(canAdd||canRemove){if(basePath=!canRemove||canAdd&&removePath.oldPos<addPath.oldPos?this.addToPath(addPath,!0,!1,0,options):this.addToPath(removePath,!1,!0,1,options),newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options),basePath.oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;bestPath[diagonalPath]=basePath,basePath.oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newPos+1>=newLen&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}else bestPath[diagonalPath]=void 0}editLength++};if(callback)!function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback(void 0);execEditLength()||exec()},0)}();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp;){const ret=execEditLength();if(ret)return ret}}addToPath(path,added,removed,oldPosInc,options){const last=path.lastComponent;return last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed?{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added:added,removed:removed,previousComponent:last.previousComponent}}:{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added:added,removed:removed,previousComponent:last}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){const newLen=newTokens.length,oldLen=oldTokens.length;let oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;for(;newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options);)newPos++,oldPos++,commonCount++,options.oneChangePerToken&&(basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1});return commonCount&&!options.oneChangePerToken&&(basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1}),basePath.oldPos=oldPos,newPos}equals(left,right,options){return options.comparator?options.comparator(left,right):left===right||!!options.ignoreCase&&left.toLowerCase()===right.toLowerCase()}removeEmpty(array){const ret=[];for(let i=0;i<array.length;i++)array[i]&&ret.push(array[i]);return ret}castInput(value,options){return value}tokenize(value,options){return Array.from(value)}join(chars){return chars.join("")}postProcess(changeObjects,options){return changeObjects}get useLongestToken(){return!1}buildValues(lastComponent,newTokens,oldTokens){const components=[];let nextComponent;for(;lastComponent;)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();const componentLen=components.length;let componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){const component=components[componentPos];if(component.removed)component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count)),oldPos+=component.count;else{if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value2,i){const oldValue=oldTokens[oldPos+i];return oldValue.length>value2.length?oldValue:value2}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));newPos+=component.count,component.added||(oldPos+=component.count)}}return components}}const lineDiff=new class extends Diff{constructor(){super(...arguments),this.tokenize=tokenize}equals(left,right,options){return options.ignoreWhitespace?(options.newlineIsToken&&left.includes("\n")||(left=left.trim()),options.newlineIsToken&&right.includes("\n")||(right=right.trim())):options.ignoreNewlineAtEof&&!options.newlineIsToken&&(left.endsWith("\n")&&(left=left.slice(0,-1)),right.endsWith("\n")&&(right=right.slice(0,-1))),super.equals(left,right,options)}};function diffLines(oldStr,newStr,options){return lineDiff.diff(oldStr,newStr,options)}function tokenize(value,options){options.stripTrailingCr&&(value=value.replace(/\r\n/g,"\n"));const retLines=[],linesAndNewlines=value.split(/(\n|\r\n)/);linesAndNewlines[linesAndNewlines.length-1]||linesAndNewlines.pop();for(let i=0;i<linesAndNewlines.length;i++){const line=linesAndNewlines[i];i%2&&!options.newlineIsToken?retLines[retLines.length-1]+=line:retLines.push(line)}return retLines}const styles$m_wrapper="_wrapper_vsc0z_1",styles$m_header="_header_vsc0z_13",styles$m_headerRight="_headerRight_vsc0z_20",styles$m_filePath="_filePath_vsc0z_28",styles$m_filePathClickable="_filePathClickable_vsc0z_34",styles$m_toggle="_toggle_vsc0z_46",styles$m_diffSummary="_diffSummary_vsc0z_55",styles$m_diffBody="_diffBody_vsc0z_62",styles$m_gutter="_gutter_vsc0z_72",styles$m_gutterRow="_gutterRow_vsc0z_77",styles$m_lineNumOld="_lineNumOld_vsc0z_82",styles$m_lineNumNew="_lineNumNew_vsc0z_83",styles$m_prefix="_prefix_vsc0z_90",styles$m_codeWrap="_codeWrap_vsc0z_98",styles$m_codeInner="_codeInner_vsc0z_105",styles$m_codeLine="_codeLine_vsc0z_110",styles$m_rowContext="_rowContext_vsc0z_118",styles$m_rowDel="_rowDel_vsc0z_123",styles$m_rowAdd="_rowAdd_vsc0z_131",{Text:Text$3}=Typography;function DiffView({file_path:file_path,old_string:old_string,new_string:new_string,startLine:startLine=1,onOpenFile:onOpenFile}){const[collapsed,setCollapsed]=reactExports.useState(!1),diffLines2=reactExports.useMemo(()=>function(oldStr,newStr,startLine){const changes=diffLines(oldStr,newStr),lines=[];let oldLineNum2=startLine,newLineNum2=startLine;for(const part of changes){const partLines=part.value.replace(/\n$/,"").split("\n");if(""!==part.value)for(const text of partLines)part.added?lines.push({type:"add",oldNum:null,newNum:newLineNum2++,text:text}):part.removed?lines.push({type:"del",oldNum:oldLineNum2++,newNum:null,text:text}):lines.push({type:"context",oldNum:oldLineNum2++,newNum:newLineNum2++,text:text})}return lines}(old_string,new_string,startLine),[old_string,new_string,startLine]),added=diffLines2.filter(l=>"add"===l.type).length,removed=diffLines2.filter(l=>"del"===l.type).length,maxLineNum=reactExports.useMemo(()=>{let max=1;for(const dl of diffLines2)null!=dl.oldNum&&dl.oldNum>max&&(max=dl.oldNum),null!=dl.newNum&&dl.newNum>max&&(max=dl.newNum);return max},[diffLines2]),lineNumWidth=8*String(maxLineNum).length+10,rowCls=type=>"del"===type?styles$m_rowDel:"add"===type?styles$m_rowAdd:styles$m_rowContext;return jsxRuntimeExports.jsxs("div",{className:styles$m_wrapper,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_header,children:[jsxRuntimeExports.jsxs(Text$3,{className:onOpenFile?styles$m_filePathClickable:styles$m_filePath,children:["Edit: ",jsxRuntimeExports.jsx("span",{onClick:onOpenFile?e=>{e.stopPropagation(),onOpenFile(file_path)}:void 0,children:file_path})]}),jsxRuntimeExports.jsxs("span",{className:styles$m_headerRight,children:[jsxRuntimeExports.jsx(Text$3,{className:styles$m_diffSummary,children:t("ui.diffSummary",{added:added,removed:removed})}),jsxRuntimeExports.jsx(Text$3,{className:styles$m_toggle,onClick:()=>setCollapsed(c=>!c),children:t(collapsed?"ui.expand":"ui.collapse")})]})]}),!collapsed&&jsxRuntimeExports.jsxs("div",{className:styles$m_diffBody,children:[jsxRuntimeExports.jsx("div",{className:styles$m_gutter,style:{"--line-num-w":`${lineNumWidth}px`},children:diffLines2.map((dl,i)=>{const prefix2="del"===dl.type?"-":"add"===dl.type?"+":" ";return jsxRuntimeExports.jsxs("div",{className:`${styles$m_gutterRow} ${rowCls(dl.type)}`,children:[jsxRuntimeExports.jsx("span",{className:styles$m_lineNumOld,style:{width:lineNumWidth},children:dl.oldNum??""}),jsxRuntimeExports.jsx("span",{className:styles$m_lineNumNew,style:{width:lineNumWidth},children:dl.newNum??""}),jsxRuntimeExports.jsx("span",{className:styles$m_prefix,children:prefix2})]},i)})}),jsxRuntimeExports.jsx("div",{className:styles$m_codeWrap,children:jsxRuntimeExports.jsx("div",{className:styles$m_codeInner,children:diffLines2.map((dl,i)=>jsxRuntimeExports.jsx("div",{className:`${styles$m_codeLine} ${rowCls(dl.type)}`,children:dl.text},i))})})]})]})}const styles$l_plainResult="_plainResult_hq7oa_1",styles$l_plainTitle="_plainTitle_hq7oa_14",styles$l_plainPre="_plainPre_hq7oa_18",styles$l_codeResult="_codeResult_hq7oa_27",styles$l_codeHeader="_codeHeader_hq7oa_39",styles$l_codeTitle="_codeTitle_hq7oa_51",styles$l_codeToggle="_codeToggle_hq7oa_56",styles$l_codePre="_codePre_hq7oa_63",styles$l_markdownBody="_markdownBody_hq7oa_73",{Text:Text$2}=Typography,EXT_LANG={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"css",less:"css",html:"html",htm:"html",xml:"xml",svg:"xml",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",sh:"shell",bash:"shell",zsh:"shell",md:"markdown",sql:"sql"},CODE_TOOLS=["Read","Grep","Glob","Bash","Write","Edit"];const RULES={javascript:[{pattern:/(\/\/.*$)/gm,cls:"hl-comment"},{pattern:/(\/\*[\s\S]*?\*\/)/g,cls:"hl-comment"},{pattern:/('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/g,cls:"hl-string"},{pattern:/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|default|new|this|async|await|try|catch|throw|switch|case|break|continue|typeof|instanceof|in|of|null|undefined|true|false)\b/g,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],typescript:null,python:[{pattern:/(#.*$)/gm,cls:"hl-comment"},{pattern:/('''[\s\S]*?'''|"""[\s\S]*?"""|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/g,cls:"hl-string"},{pattern:/\b(def|class|return|if|elif|else|for|while|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await)\b/g,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],go:[{pattern:/(\/\/.*$)/gm,cls:"hl-comment"},{pattern:/(\/\*[\s\S]*?\*\/)/g,cls:"hl-comment"},{pattern:/('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`[^`]*`)/g,cls:"hl-string"},{pattern:/\b(func|return|if|else|for|range|switch|case|default|break|continue|go|defer|select|chan|map|struct|interface|package|import|var|const|type|nil|true|false|make|new|append|len|cap)\b/g,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],rust:[{pattern:/(\/\/.*$)/gm,cls:"hl-comment"},{pattern:/("(?:[^"\\]|\\.)*")/g,cls:"hl-string"},{pattern:/\b(fn|let|mut|return|if|else|for|while|loop|match|struct|enum|impl|trait|pub|use|mod|crate|self|super|where|async|await|move|ref|true|false|Some|None|Ok|Err)\b/g,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],java:[{pattern:/(\/\/.*$)/gm,cls:"hl-comment"},{pattern:/(\/\*[\s\S]*?\*\/)/g,cls:"hl-comment"},{pattern:/("(?:[^"\\]|\\.)*")/g,cls:"hl-string"},{pattern:/\b(public|private|protected|class|interface|extends|implements|return|if|else|for|while|switch|case|break|continue|new|this|super|static|final|void|int|long|double|float|boolean|char|String|import|package|try|catch|throw|throws|null|true|false)\b/g,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*[fFdDlL]?)\b/g,cls:"hl-number"}],ruby:[{pattern:/(#.*$)/gm,cls:"hl-comment"},{pattern:/('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/g,cls:"hl-string"},{pattern:/\b(def|end|class|module|return|if|elsif|else|unless|for|while|do|begin|rescue|ensure|raise|yield|block_given\?|nil|true|false|self|require|include|attr_accessor|attr_reader)\b/g,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],css:[{pattern:/(\/\*[\s\S]*?\*\/)/g,cls:"hl-comment"},{pattern:/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,cls:"hl-string"},{pattern:/([.#][\w-]+)/g,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms)?)\b/g,cls:"hl-number"}],json:[{pattern:/("(?:[^"\\]|\\.)*")\s*:/g,cls:"hl-keyword"},{pattern:/:\s*("(?:[^"\\]|\\.)*")/g,cls:"hl-string"},{pattern:/\b(true|false|null)\b/g,cls:"hl-keyword"},{pattern:/\b(-?\d+\.?\d*([eE][+-]?\d+)?)\b/g,cls:"hl-number"}],shell:[{pattern:/(#.*$)/gm,cls:"hl-comment"},{pattern:/('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/g,cls:"hl-string"},{pattern:/\b(if|then|else|elif|fi|for|while|do|done|case|esac|function|return|exit|export|source|alias|cd|ls|grep|find|echo|cat|mkdir|rm|cp|mv|chmod|sudo|apt|npm|pip|git)\b/g,cls:"hl-keyword"}],sql:[{pattern:/(--.*$)/gm,cls:"hl-comment"},{pattern:/('(?:[^'\\]|\\.)*')/g,cls:"hl-string"},{pattern:/\b(SELECT|FROM|WHERE|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|TABLE|INDEX|JOIN|LEFT|RIGHT|INNER|OUTER|ON|AND|OR|NOT|IN|IS|NULL|AS|ORDER|BY|GROUP|HAVING|LIMIT|OFFSET|UNION|SET|VALUES|INTO|DISTINCT|COUNT|SUM|AVG|MAX|MIN|LIKE|BETWEEN|EXISTS|CASE|WHEN|THEN|ELSE|END)\b/gi,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],html:[{pattern:/(<!--[\s\S]*?-->)/g,cls:"hl-comment"},{pattern:/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,cls:"hl-string"},{pattern:/(<\/?[\w-]+|\/?>)/g,cls:"hl-keyword"}],xml:null,yaml:[{pattern:/(#.*$)/gm,cls:"hl-comment"},{pattern:/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,cls:"hl-string"},{pattern:/^([\w.-]+)\s*:/gm,cls:"hl-keyword"},{pattern:/\b(true|false|null|yes|no)\b/gi,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],markdown:[{pattern:/^(#{1,6}\s.*$)/gm,cls:"hl-keyword"},{pattern:/(`[^`]+`)/g,cls:"hl-string"},{pattern:/(\*\*[^*]+\*\*|__[^_]+__)/g,cls:"hl-keyword"},{pattern:/(\[[^\]]+\]\([^)]+\))/g,cls:"hl-string"}],toml:[{pattern:/(#.*$)/gm,cls:"hl-comment"},{pattern:/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,cls:"hl-string"},{pattern:/^([\w.-]+)\s*=/gm,cls:"hl-keyword"},{pattern:/(\[[\w.-]+\])/g,cls:"hl-keyword"},{pattern:/\b(true|false)\b/g,cls:"hl-keyword"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}]},FALLBACK_RULES=[{pattern:/(\/\/.*$|#.*$)/gm,cls:"hl-comment"},{pattern:/('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/g,cls:"hl-string"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],SHELL_OUTPUT_RULES=[{pattern:/^([\w/.~-]+:\d+[:-])/gm,cls:"hl-keyword"},{pattern:/('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/g,cls:"hl-string"},{pattern:/\b(\d+\.?\d*)\b/g,cls:"hl-number"}],FILE_LIST_RULES=[{pattern:/^(.*\.(jsx?|tsx?|mjs|cjs))$/gm,cls:"hl-string"},{pattern:/^(.*\.(py|rb|go|rs|java|c|cpp|h))$/gm,cls:"hl-keyword"},{pattern:/^(.*\.(json|ya?ml|toml|xml|html?|css|scss|less|md))$/gm,cls:"hl-number"},{pattern:/^(.*\.(log|txt|csv|jsonl))$/gm,cls:"hl-comment"}],_hlCache=new Map;function ToolResultView({toolName:toolName2,toolInput:toolInput,resultText:resultText,defaultCollapsed:defaultCollapsed}){const[collapsed,setCollapsed]=reactExports.useState(defaultCollapsed??!1);reactExports.useEffect(()=>{setCollapsed(defaultCollapsed??!1)},[defaultCollapsed]);const isCodeTool=CODE_TOOLS.includes(toolName2),lang=isCodeTool?function(toolName2,toolInput,resultText){if(!toolInput)return null;const filePath2=toolInput.file_path||"";if(filePath2){const ext=filePath2.split(".").pop().toLowerCase();if(EXT_LANG[ext])return EXT_LANG[ext]}if("Bash"===toolName2)return"shell-output";if("Glob"===toolName2)return"file-list";if("Grep"===toolName2){const glob=toolInput.glob||"";if(glob){const parts=glob.replace(/[{}*]/g,",").split(",").filter(Boolean);for(const p of parts){const ext=p.replace(/^\./,"").toLowerCase();if(EXT_LANG[ext])return EXT_LANG[ext]}}if("files_with_matches"===toolInput.output_mode||!toolInput.output_mode)return"file-list";if("content"===toolInput.output_mode&&resultText){const match=resultText.match(/^[\w/.~-]+\.([\w]+):\d+/m);if(match&&EXT_LANG[match[1].toLowerCase()])return EXT_LANG[match[1].toLowerCase()]}return"shell-output"}return resultText?function(text){const sample=text.substring(0,2e3);return/^\s*[\[{]/.test(sample)&&/[}\]]\s*$/.test(sample.trimEnd())?"json":/^\s*<!DOCTYPE|^\s*<html|^\s*<\?xml/i.test(sample)?"html":/^#!.*python/m.test(sample)||/\bdef\s+\w+\s*\(.*\)\s*:/m.test(sample)||/\bclass\s+\w+.*:/m.test(sample)||/^\s*(from\s+\w+\s+import|import\s+\w+)/m.test(sample)&&/:$/.test(sample)?"python":/\bfn\s+\w+\s*\(/.test(sample)&&/\blet\s+(mut\s+)?\w+/.test(sample)?"rust":/^package\s+\w+/m.test(sample)&&/\bfunc\s+/.test(sample)?"go":/\bpublic\s+(class|interface|static)\b/.test(sample)?"java":/\bdef\s+\w+/.test(sample)&&/\bend\b/.test(sample)&&!/;/.test(sample)?"ruby":/^#!.*\b(bash|sh|zsh)\b/m.test(sample)?"shell":/\b(const|let|var)\s+\w+\s*=/.test(sample)&&(/=>/.test(sample)||/\brequire\s*\(/.test(sample))||/^\s*import\s+.*\s+from\s+['"]/.test(sample)||/^\s*export\s+(default\s+)?(function|class|const)\b/m.test(sample)?"javascript":/[.#][\w-]+\s*\{[\s\S]*?:\s*[\w#]/.test(sample)?"css":/^[\w-]+\s*:(\s+\S|$)/m.test(sample)&&!/[{;]/.test(sample)?"yaml":/\b(SELECT|INSERT|UPDATE|DELETE|CREATE\s+TABLE)\b/i.test(sample)?"sql":null}(resultText):null}(toolName2,toolInput,resultText):null,displayText=resultText.length>5e3?resultText.substring(0,5e3)+"\n... (truncated)":resultText;let title2=toolName2?t("ui.toolReturnNamed",{name:toolName2}):"Result";if(toolInput){const filePath2=toolInput.file_path||toolInput.path||"";if(filePath2){const parts=filePath2.split("/");title2=`${toolName2}: ${parts[parts.length-1]}`}}if(!isCodeTool)return"Task"===toolName2?jsxRuntimeExports.jsxs("div",{className:styles$l_plainResult,children:[jsxRuntimeExports.jsxs("div",{className:styles$l_codeHeader,children:[jsxRuntimeExports.jsx(Text$2,{type:"secondary",className:styles$l_plainTitle,children:title2}),jsxRuntimeExports.jsx(Text$2,{className:styles$l_codeToggle,onClick:()=>setCollapsed(c=>!c),children:t(collapsed?"ui.expand":"ui.collapse")})]}),!collapsed&&jsxRuntimeExports.jsx("div",{className:`chat-md ${styles$l_markdownBody}`,dangerouslySetInnerHTML:{__html:renderMarkdown(displayText)}})]}):jsxRuntimeExports.jsxs("div",{className:styles$l_plainResult,children:[jsxRuntimeExports.jsxs("div",{className:styles$l_codeHeader,children:[jsxRuntimeExports.jsx(Text$2,{type:"secondary",className:styles$l_plainTitle,children:title2}),jsxRuntimeExports.jsx(Text$2,{className:styles$l_codeToggle,onClick:()=>setCollapsed(c=>!c),children:t(collapsed?"ui.expand":"ui.collapse")})]}),!collapsed&&jsxRuntimeExports.jsx("pre",{className:styles$l_plainPre,children:displayText})]});const highlighted=function(text,lang){const cacheKey=`${lang}\0${text}`,hit=_hlCache.get(cacheKey);if(void 0!==hit)return hit;let rules,resolvedLang=lang;"typescript"===resolvedLang&&(resolvedLang="javascript"),"xml"===resolvedLang&&(resolvedLang="html"),"c"!==resolvedLang&&"cpp"!==resolvedLang||(resolvedLang="javascript"),rules="shell-output"===resolvedLang?SHELL_OUTPUT_RULES:"file-list"===resolvedLang?FILE_LIST_RULES:RULES[resolvedLang]||FALLBACK_RULES;const lineNums=[],escaped=escapeHtml(text.replace(/^(\s*\d+→)/gm,match=>{const idx=lineNums.length;return lineNums.push(match),`L${idx}`})),placeholders=[];let result=escaped;for(const rule of rules)rule.pattern.lastIndex=0,result=result.replace(rule.pattern,match=>{const idx=placeholders.length;return placeholders.push(`<span class="${rule.cls}">${match}</span>`),`P${idx}`});return result=result.replace(/\x02P(\d+)\x02/g,(_,idx)=>placeholders[parseInt(idx)]),result=result.replace(/\x01L(\d+)\x01/g,(_,idx)=>`<span class="hl-linenum">${escapeHtml(lineNums[parseInt(idx)])}</span>`),_hlCache.size>=512&&_hlCache.delete(_hlCache.keys().next().value),_hlCache.set(cacheKey,result),result}(displayText,lang||"fallback");return jsxRuntimeExports.jsxs("div",{className:`tool-result-code ${styles$l_codeResult}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$l_codeHeader,children:[jsxRuntimeExports.jsxs(Text$2,{className:styles$l_codeTitle,children:[title2,lang?` (${lang})`:""]}),jsxRuntimeExports.jsx(Text$2,{className:styles$l_codeToggle,onClick:()=>setCollapsed(c=>!c),children:t(collapsed?"ui.expand":"ui.collapse")})]}),!collapsed&&jsxRuntimeExports.jsx("pre",{className:`code-highlight ${styles$l_codePre}`,dangerouslySetInnerHTML:{__html:highlighted}})]})}const styles$k={overlay:"_overlay_mhdoc_1",dragging:"_dragging_mhdoc_21",closing:"_closing_mhdoc_22",closeBtn:"_closeBtn_mhdoc_34",imageArea:"_imageArea_mhdoc_54",image:"_image_mhdoc_54",spinner:"_spinner_mhdoc_81",zoomLabel:"_zoomLabel_mhdoc_94",errorMsg:"_errorMsg_mhdoc_108"};function ImageLightbox({src:src,alt:alt,onClose:onClose,zIndex:zIndex}){const[zoom,setZoom]=reactExports.useState(1),[offset,setOffset]=reactExports.useState({x:0,y:0}),[dragging2,setDragging]=reactExports.useState(!1),[loaded,setLoaded]=reactExports.useState(!1),[error2,setError]=reactExports.useState(!1),[closing2,setClosing]=reactExports.useState(!1),dragRef=reactExports.useRef(null),imgRef=reactExports.useRef(null),touchRef=reactExports.useRef(null),overlayRef=reactExports.useRef(null),stateRef=reactExports.useRef({zoom:1,offset:{x:0,y:0}}),fitZoomRef=reactExports.useRef(1),mountedRef=reactExports.useRef(!0),clampZoom=z=>Math.min(10,Math.max(.1,z));reactExports.useEffect(()=>{stateRef.current.zoom=zoom},[zoom]),reactExports.useEffect(()=>{stateRef.current.offset=offset},[offset]),reactExports.useEffect(()=>()=>{mountedRef.current=!1},[]);const doClose=reactExports.useCallback(()=>{setClosing(!0)},[]);reactExports.useEffect(()=>{if(!closing2)return;const id=setTimeout(()=>{mountedRef.current&&onClose()},150);return()=>clearTimeout(id)},[closing2,onClose]),reactExports.useEffect(()=>{const onKey=e=>{"Escape"===e.key&&doClose()};window.addEventListener("keydown",onKey);const prevOverflow=document.body.style.overflow,prevScrollbarGutter=document.body.style.scrollbarGutter;return document.body.style.overflow="hidden",document.body.style.scrollbarGutter="stable",()=>{window.removeEventListener("keydown",onKey),document.body.style.overflow=prevOverflow,document.body.style.scrollbarGutter=prevScrollbarGutter}},[doClose]);const handleImageLoad=reactExports.useCallback(e=>{setLoaded(!0);const img=e.target,vw=.9*window.innerWidth,vh=.9*window.innerHeight,renderedW=img.clientWidth,renderedH=img.clientHeight,fit=Math.min(vw/renderedW,vh/renderedH);fitZoomRef.current=fit,fit>1.05&&setZoom(fit)},[]),handleWheel=reactExports.useCallback(e=>{e.preventDefault(),e.stopPropagation(),setZoom(prev=>{const next=clampZoom(prev*(e.deltaY<0?1.06:1/1.06)),ratio=next/prev;return setOffset(o2=>({x:o2.x*ratio,y:o2.y*ratio})),next})},[]);reactExports.useEffect(()=>{const el=overlayRef.current;if(el)return el.addEventListener("wheel",handleWheel,{passive:!1}),()=>el.removeEventListener("wheel",handleWheel)},[handleWheel]);const handleMouseDown=reactExports.useCallback(e=>{if(0!==e.button)return;e.preventDefault();const{offset:cur}=stateRef.current;dragRef.current={startX:e.clientX,startY:e.clientY,ox:cur.x,oy:cur.y},setDragging(!0);const onMove=ev=>{dragRef.current&&setOffset({x:dragRef.current.ox+ev.clientX-dragRef.current.startX,y:dragRef.current.oy+ev.clientY-dragRef.current.startY})},onUp=()=>{dragRef.current=null,mountedRef.current&&setDragging(!1),window.removeEventListener("mousemove",onMove),window.removeEventListener("mouseup",onUp)};window.addEventListener("mousemove",onMove),window.addEventListener("mouseup",onUp)},[]),handleTouchStart=reactExports.useCallback(e=>{const{zoom:z,offset:o2}=stateRef.current;if(2===e.touches.length){const dx=e.touches[0].clientX-e.touches[1].clientX,dy=e.touches[0].clientY-e.touches[1].clientY;touchRef.current={dist:Math.hypot(dx,dy),zoom:z,ox:o2.x,oy:o2.y,isPinch:!0}}else 1===e.touches.length&&(touchRef.current={startX:e.touches[0].clientX,startY:e.touches[0].clientY,ox:o2.x,oy:o2.y,isPinch:!1,moved:!1})},[]),handleTouchMove=reactExports.useCallback(e=>{if(touchRef.current)if(e.preventDefault(),touchRef.current.isPinch&&2===e.touches.length){const dx=e.touches[0].clientX-e.touches[1].clientX,dy=e.touches[0].clientY-e.touches[1].clientY,scale=Math.hypot(dx,dy)/touchRef.current.dist;setZoom(clampZoom(touchRef.current.zoom*scale))}else if(1===e.touches.length){if(touchRef.current.isPinch){const{offset:o2}=stateRef.current;return void(touchRef.current={startX:e.touches[0].clientX,startY:e.touches[0].clientY,ox:o2.x,oy:o2.y,isPinch:!1,moved:!1})}const dx=e.touches[0].clientX-touchRef.current.startX,dy=e.touches[0].clientY-touchRef.current.startY;(Math.abs(dx)>5||Math.abs(dy)>5)&&(touchRef.current.moved=!0),setOffset({x:touchRef.current.ox+dx,y:touchRef.current.oy+dy})}},[]),handleTouchEnd=reactExports.useCallback(e=>{if(touchRef.current)if(e.touches.length>0)touchRef.current=null;else{if(!touchRef.current.isPinch&&!touchRef.current.moved&&1===e.changedTouches.length){const target=e.target;(target===overlayRef.current||target.classList.contains(styles$k.imageArea))&&doClose()}touchRef.current=null}},[doClose]),handleOverlayClick=reactExports.useCallback(e=>{(e.target===overlayRef.current||e.target.classList.contains(styles$k.imageArea))&&doClose()},[doClose]),handleDoubleClick=reactExports.useCallback(e=>{e.stopPropagation(),setZoom(prev=>{setOffset({x:0,y:0});const fitZ=fitZoomRef.current;return Math.abs(prev-fitZ)<.05?1:fitZ})},[]),closeLabel=t("ui.imageLightbox.close"),overlayClass=[styles$k.overlay,dragging2&&styles$k.dragging,closing2&&styles$k.closing].filter(Boolean).join(" "),content2=jsxRuntimeExports.jsxs("div",{className:overlayClass,ref:overlayRef,role:"dialog","aria-modal":"true","aria-label":alt||"Image preview",style:null!=zIndex?{zIndex:zIndex}:void 0,onClick:handleOverlayClick,onTouchStart:handleTouchStart,onTouchMove:handleTouchMove,onTouchEnd:handleTouchEnd,children:[jsxRuntimeExports.jsx("button",{className:styles$k.closeBtn,onClick:doClose,title:closeLabel,"aria-label":closeLabel,children:jsxRuntimeExports.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntimeExports.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),jsxRuntimeExports.jsx("div",{className:styles$k.imageArea,children:error2?jsxRuntimeExports.jsx("div",{className:styles$k.errorMsg,children:"Failed to load image"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[!loaded&&jsxRuntimeExports.jsx("div",{className:styles$k.spinner}),jsxRuntimeExports.jsx("img",{ref:imgRef,className:styles$k.image,src:src,alt:alt||"",draggable:!1,onLoad:handleImageLoad,onError:()=>setError(!0),onMouseDown:handleMouseDown,onDoubleClick:handleDoubleClick,style:{transform:`translate(${offset.x}px, ${offset.y}px) scale(${zoom})`,opacity:loaded?1:0}})]})}),1!==zoom&&jsxRuntimeExports.jsxs("div",{className:styles$k.zoomLabel,children:[Math.round(100*zoom),"%"]})]});return ReactDOM.createPortal(content2,document.body)}const defaultAvatarUrl="/assets/default-avatar-CT9tlZjd.svg",{Text:Text$1}=Typography;function AskValidationBadge({resultText:resultText}){return resultText?jsxRuntimeExports.jsxs("div",{className:styles$n_askValidationErrorBadge,children:[jsxRuntimeExports.jsx("span",{className:styles$n_askValidationErrorTitle,children:t("ui.askValidationErrorBadge")}),jsxRuntimeExports.jsxs("details",{className:styles$n_askValidationErrorDetails,children:[jsxRuntimeExports.jsx("summary",{children:t("ui.askValidationErrorRaw")}),jsxRuntimeExports.jsx("pre",{className:styles$n_askValidationErrorRawText,children:resultText})]})]}):null}function ViewRequestIcon(){return jsxRuntimeExports.jsx("svg",{viewBox:"0 0 1024 1024",width:"12",height:"12",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M738.133333 580.266667c-17.066667-8.533333-38.4 0-38.4 21.333333v85.333333H268.8c-123.733333 0-200.533333-42.666667-200.533333-42.666666s21.333333 170.666667 200.533333 170.666666h430.933333v85.333334c0 21.333333 21.333333 34.133333 38.4 21.333333l204.8-149.333333c17.066667-8.533333 17.066667-34.133333 0-42.666667l-204.8-149.333333zM285.866667 443.733333c17.066667 8.533333 38.4 0 38.4-21.333333v-85.333333h430.933333c123.733333 0 200.533333 42.666667 200.533333 42.666666s-21.333333-170.666667-200.533333-170.666666H324.266667v-85.333334c0-21.333333-21.333333-34.133333-38.4-21.333333L81.066667 251.733333c-17.066667 8.533333-17.066667 34.133333 0 42.666667l204.8 149.333333z"})})}function ChatImage({src:src,alt:alt,fallbackText:fallbackText}){const[failed,setFailed]=React__default.useState(!1),[lightboxOpen,setLightboxOpen]=React__default.useState(!1);return failed?jsxRuntimeExports.jsx("span",{className:styles$n_chatImageFallback,children:fallbackText}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("img",{src:src,alt:alt,className:styles$n_chatImageImg,loading:"lazy",decoding:"async",onClick:()=>setLightboxOpen(!0),onError:()=>setFailed(!0)}),lightboxOpen&&jsxRuntimeExports.jsx(ImageLightbox,{src:src,alt:alt,onClose:()=>setLightboxOpen(!1)})]})}const ModelAvatar=React__default.memo(function({modelInfo:modelInfo,streaming:streaming}){const svgSource=streaming&&(null==modelInfo?void 0:modelInfo.svgAnimated)||(null==modelInfo?void 0:modelInfo.svg);return svgSource?jsxRuntimeExports.jsx("div",{className:styles$n_avatar,style:{background:modelInfo.color||"var(--bg-model-avatar)"},dangerouslySetInnerHTML:{__html:svgSource}}):jsxRuntimeExports.jsx("img",{src:"/assets/default-model-avatar-DlbUPjyv.svg",className:styles$n_avatarImg,alt:(null==modelInfo?void 0:modelInfo.name)||"Agent"})});function formatCacheK(n){return null==n?"":Number.isFinite(n)?0===n?"0K":n>=1e6?(n/1e3).toFixed(0)+"K":n>=1e3?(n/1e3).toFixed(1)+"K":(n/1e3).toFixed(2)+"K":""}const AssistantLabel=React__default.memo(function({name:name,extra:extra,timeStr:timeStr,requestIndex:requestIndex,onViewRequest:onViewRequest,cacheTotalTokens:cacheTotalTokens,showFullToolContent:showFullToolContent}){const viewBtn=null!=requestIndex&&onViewRequest?!showFullToolContent?jsxRuntimeExports.jsx("span",{className:styles$n_viewRequestIcon,title:t("ui.viewRequest"),onClick:e=>{e.stopPropagation(),onViewRequest(requestIndex)},children:jsxRuntimeExports.jsx(ViewRequestIcon,{})}):jsxRuntimeExports.jsx("span",{className:styles$n_viewRequestBtn,onClick:e=>{e.stopPropagation(),onViewRequest(requestIndex)},children:t("ui.viewRequest")}):null,showCache=showFullToolContent&&null!=cacheTotalTokens,cacheStr=showCache?formatCacheK(cacheTotalTokens):"";return jsxRuntimeExports.jsxs("div",{className:styles$n_labelRow,children:[jsxRuntimeExports.jsxs(Text$1,{type:"secondary",className:styles$n_labelText,children:[name,extra||""]}),jsxRuntimeExports.jsxs("span",{className:styles$n_labelRight,children:[viewBtn,showCache&&jsxRuntimeExports.jsx(Text$1,{className:styles$n_cacheContextText,title:t("ui.cacheContextTooltip",{value:cacheStr}),children:`[${cacheStr}]`}),timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$n_timeText,children:timeStr})]})]})});class ChatMessage extends React__default.Component{constructor(props){super(props),this.state={planFeedbackInput:!1,planFeedbackText:"",planFeedbackOptNumber:null,planApprovalSubmitting:!1}}shouldComponentUpdate(nextProps,nextState){var _a,_b;if(this.state!==nextState)return!0;const p=this.props,n=nextProps;return p.role!==n.role||p.content!==n.content||p.text!==n.text||p.timestamp!==n.timestamp||p.displayTs!==n.displayTs||p.highlight!==n.highlight||p.collapseToolResults!==n.collapseToolResults||p.expandThinking!==n.expandThinking||p.showFullToolContent!==n.showFullToolContent||p.showTrailingCursor!==n.showTrailingCursor||p.showThinkingSummaries!==n.showThinkingSummaries||p.toolResultMap!==n.toolResultMap||p.readContentMap!==n.readContentMap||p.editSnapshotMap!==n.editSnapshotMap||p.askAnswerMap!==n.askAnswerMap||p.planApprovalMap!==n.planApprovalMap||p.latestPlanContent!==n.latestPlanContent||p.ptyPrompt!==n.ptyPrompt||p.cliMode!==n.cliMode||p.lastPendingAskId!==n.lastPendingAskId||p.lastPendingPlanId!==n.lastPendingPlanId||p.activePlanPrompt!==n.activePlanPrompt||p.activeDangerousPrompt!==n.activeDangerousPrompt||p.activePtyPlanId!==n.activePtyPlanId||p.requestIndex!==n.requestIndex||p.cacheTotalTokens!==n.cacheTotalTokens||p.label!==n.label||p.isTeammate!==n.isTeammate||p.isHistoryLog!==n.isHistoryLog||p.userProfile!==n.userProfile||p.modelInfo!==n.modelInfo||p.resultText!==n.resultText||p.toolName!==n.toolName||p.onViewRequest!==n.onViewRequest||p.onOpenFile!==n.onOpenFile||p.onPlanApprovalClick!==n.onPlanApprovalClick||p.onPlanFeedbackSubmit!==n.onPlanFeedbackSubmit||p.onDangerousApprovalClick!==n.onDangerousApprovalClick||p.onAskQuestionSubmit!==n.onAskQuestionSubmit||(null==(_a=p.taskNotification)?void 0:_a.taskId)!==(null==(_b=n.taskNotification)?void 0:_b.taskId)}componentDidUpdate(prevProps){prevProps.lastPendingAskId!==this.props.lastPendingAskId&&this.setState({askSelections:{},askMultiSelections:{},askOtherActive:{},askOtherText:{},askSubmitting:!1}),prevProps.lastPendingPlanId!==this.props.lastPendingPlanId&&this.setState({planApprovalSubmitting:!1})}formatTime(ts){const effectiveTs=this.props.displayTs??ts;if(!effectiveTs)return null;try{const d=new Date(effectiveTs),pad=n=>String(n).padStart(2,"0"),{showFullToolContent:showFullToolContent,isHistoryLog:isHistoryLog}=this.props,compact=!showFullToolContent&&!isHistoryLog,hms=`${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;return compact?hms:`${pad(d.getMonth()+1)}-${pad(d.getDate())} ${hms}`}catch{return null}}renderViewRequestBtn(){const{requestIndex:requestIndex,onViewRequest:onViewRequest,showFullToolContent:showFullToolContent}=this.props;return null!=requestIndex&&onViewRequest?showFullToolContent?jsxRuntimeExports.jsx("span",{className:styles$n_viewRequestBtn,onClick:e=>{e.stopPropagation(),onViewRequest(requestIndex)},children:t("ui.viewRequest")}):jsxRuntimeExports.jsx("span",{className:styles$n_viewRequestIcon,title:t("ui.viewRequest"),onClick:e=>{e.stopPropagation(),onViewRequest(requestIndex)},children:jsxRuntimeExports.jsx(ViewRequestIcon,{})}):null}renderLabel(name,extra){const{timestamp:timestamp}=this.props,timeStr=this.formatTime(timestamp);return jsxRuntimeExports.jsxs("div",{className:styles$n_labelRow,children:[jsxRuntimeExports.jsxs(Text$1,{type:"secondary",className:styles$n_labelText,children:[name,extra||""]}),jsxRuntimeExports.jsxs("span",{className:styles$n_labelRight,children:[this.renderViewRequestBtn(),timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$n_timeText,children:timeStr})]})]})}renderModelAvatar(modelInfo){return(null==modelInfo?void 0:modelInfo.svg)?jsxRuntimeExports.jsx("div",{className:styles$n_avatar,style:{background:modelInfo.color||"var(--bg-model-avatar)"},dangerouslySetInnerHTML:{__html:modelInfo.svg}}):jsxRuntimeExports.jsx("img",{src:"/assets/default-model-avatar-DlbUPjyv.svg",className:styles$n_avatarImg,alt:(null==modelInfo?void 0:modelInfo.name)||"Agent"})}renderUserAvatar(bgColor){const{userProfile:userProfile}=this.props;return(null==userProfile?void 0:userProfile.avatar)?jsxRuntimeExports.jsx("img",{src:userProfile.avatar,className:styles$n_avatarImg,alt:userProfile.name||"User",onError:e=>{e.target.onerror=null,e.target.src=defaultAvatarUrl}}):jsxRuntimeExports.jsx("img",{src:defaultAvatarUrl,className:styles$n_avatarImg,alt:(null==userProfile?void 0:userProfile.name)||"User"})}getUserName(){const{userProfile:userProfile}=this.props;return(null==userProfile?void 0:userProfile.name)||"User"}renderSegments(segments,trailingCursor=!1){let lastMdIdx=-1;if(trailingCursor)for(let j=segments.length-1;j>=0;j--)if("system-tag"!==segments[j].type&&segments[j].content&&segments[j].content.trim()){lastMdIdx=j;break}return segments.map((seg,i)=>"system-tag"===seg.type?jsxRuntimeExports.jsx(Collapse,{ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$n_systemTagLabel,children:seg.tag}),children:jsxRuntimeExports.jsx("pre",{className:styles$n_systemTagPre,children:seg.content})}],className:styles$n_collapseMargin},i):jsxRuntimeExports.jsx(MarkdownBlock$1,{text:seg.content,trailingCursor:i===lastMdIdx},i))}renderToolCall(tu){var _a,_b,_c;if("string"==typeof tu.input)try{const cleaned=tu.input.replace(/^\[object Object\]/,"");tu={...tu,input:JSON.parse(cleaned)}}catch{}if("Edit"===tu.name&&tu.input&&null!=tu.input.old_string&&null!=tu.input.new_string){const editSnapshotMap=this.props.editSnapshotMap||{},filePath2=tu.input.file_path||"";let startLine=1;const snapshot=editSnapshotMap[tu.id];if(snapshot&&tu.input.old_string){const idx=snapshot.plainText.indexOf(tu.input.old_string);if(idx>=0){const lineOffset=snapshot.plainText.substring(0,idx).split("\n").length-1;startLine=snapshot.lineNums[lineOffset]??lineOffset+1}}return jsxRuntimeExports.jsx(DiffView,{file_path:filePath2,old_string:tu.input.old_string,new_string:tu.input.new_string,startLine:startLine,onOpenFile:this.props.onOpenFile},tu.id)}const inp=tu.input&&"object"==typeof tu.input?tu.input:{},box=(label2,children)=>jsxRuntimeExports.jsxs("div",{className:styles$n_toolBox,children:[jsxRuntimeExports.jsx(Text$1,{strong:!0,className:styles$n_toolLabel,children:label2}),children]},tu.id),codePre2=text=>jsxRuntimeExports.jsx("pre",{className:styles$n_codePre,children:text}),onOpenFile=this.props.onOpenFile,pathTag2=p=>onOpenFile?jsxRuntimeExports.jsx("span",{className:styles$n_pathTagClickable,onClick:e=>{e.stopPropagation(),onOpenFile(p)},children:p}):jsxRuntimeExports.jsx("span",{className:styles$n_pathTag,children:p});if("Bash"===tu.name){const cmd=inp.command||"",desc=inp.description||"",lineCount=cmd.split("\n").length;return lineCount>5?jsxRuntimeExports.jsxs("div",{className:styles$n_toolBox,children:[jsxRuntimeExports.jsxs(Text$1,{strong:!0,className:styles$n_toolLabel,children:["Bash",desc?jsxRuntimeExports.jsxs("span",{className:styles$n_descSpan,children:[" — ",desc]}):""]}),jsxRuntimeExports.jsx(Collapse,{ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsxs(Text$1,{type:"secondary",className:styles$n_bashCollapseLabel,children:[t("ui.bashCommand")," (",lineCount," ",t("ui.lines"),")"]}),children:codePre2(cmd)}],className:styles$n_collapseMargin})]},tu.id):box(jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["Bash",desc?jsxRuntimeExports.jsxs("span",{className:styles$n_descSpan,children:[" — ",desc]}):""]}),codePre2(cmd))}if("Read"===tu.name){const fp=inp.file_path||"",parts=[];inp.offset&&parts.push(`offset: ${inp.offset}`),inp.limit&&parts.push(`limit: ${inp.limit}`);const range=parts.length?` (${parts.join(", ")})`:"";return box(jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["Read: ",pathTag2(fp),jsxRuntimeExports.jsx("span",{className:styles$n_secondarySpan,children:range})]}),null)}if("Write"===tu.name){const fp=inp.file_path||"",content2=inp.content||"",lines=content2.split("\n");return box(jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["Write: ",pathTag2(fp)," ",jsxRuntimeExports.jsxs("span",{className:styles$n_secondarySpan,children:["(",lines.length," lines)"]})]}),codePre2(content2))}if("Glob"===tu.name){const pattern=inp.pattern||"",path=inp.path||"";return box(jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["Glob: ",jsxRuntimeExports.jsx("span",{className:styles$n_patternSpan,children:pattern}),path?jsxRuntimeExports.jsxs("span",{className:styles$n_secondarySpan,children:[" in ",path]}):""]}),null)}if("Grep"===tu.name){const pattern=inp.pattern||"",path=inp.path||"",opts=[];inp.glob&&opts.push(`glob: ${inp.glob}`),inp.output_mode&&opts.push(`mode: ${inp.output_mode}`),inp.head_limit&&opts.push(`limit: ${inp.head_limit}`);const optsStr=opts.length?` (${opts.join(", ")})`:"";return box(jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["Grep: ",jsxRuntimeExports.jsxs("span",{className:styles$n_patternSpan,children:["/",pattern,"/"]}),path?jsxRuntimeExports.jsxs("span",{className:styles$n_secondarySpan,children:[" in ",path]}):"",jsxRuntimeExports.jsx("span",{className:styles$n_secondarySpan,children:optsStr})]}),null)}if("Task"===tu.name){const st=inp.subagent_type||"",desc=inp.description||"";return box(jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["Task(",st,desc?": "+desc:"",")"]}),null)}if("AskUserQuestion"===tu.name){const questions=Array.isArray(inp.questions)?inp.questions:[],{askAnswerMap:askAnswerMap,toolResultMap:toolResultMap}=this.props,selectedAnswers=(null==askAnswerMap?void 0:askAnswerMap[tu.id])||{},isRejected=!0===selectedAnswers.__rejected__,hasAnswers=!isRejected&&Object.keys(selectedAnswers).length>0,isInteractive=!hasAnswers&&!isRejected&&this.props.onAskQuestionSubmit&&tu.id===this.props.lastPendingAskId,validationError=(null==(_a=null==toolResultMap?void 0:toolResultMap[tu.id])?void 0:_a.isInputValidationError)?toolResultMap[tu.id].resultText:null;if(isInteractive){const interactive=this.renderAskQuestionInteractive(tu.id,questions);return validationError?jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx(AskValidationBadge,{resultText:validationError}),interactive]},tu.id):interactive}const checkSvg=jsxRuntimeExports.jsx("svg",{className:styles$n_askCheckSvg,width:"1em",height:"1em",viewBox:"0 0 16 16",fill:"none",children:jsxRuntimeExports.jsx("path",{d:"M3 8.5L6.5 12L13 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})});return jsxRuntimeExports.jsxs("div",{className:styles$n_askQuestionBox,children:[jsxRuntimeExports.jsx(AskValidationBadge,{resultText:validationError}),questions.map((q,qi)=>{var _a2;const answer=selectedAnswers[q.question],answerLabels=null!=answer&&q.multiSelect?answer.split(",").map(s=>s.trim()):[],isOptionMatch=optLabel=>null!=answer&&(q.multiSelect?answerLabels.includes(optLabel):answer===optLabel),anyOptionMatched=null==(_a2=q.options)?void 0:_a2.some(opt=>isOptionMatch(opt.label)),isOtherAnswer=hasAnswers&&null!=answer&&!anyOptionMatched;return jsxRuntimeExports.jsxs("div",{className:qi<questions.length-1?styles$n_questionSpacing:void 0,children:[q.header&&jsxRuntimeExports.jsx("span",{className:styles$n_askQuestionHeader,children:q.header}),jsxRuntimeExports.jsx("div",{className:styles$n_askQuestionText,children:q.question}),jsxRuntimeExports.jsxs("div",{className:styles$n_optionList,children:[q.options&&q.options.map((opt,oi)=>{const selected=isOptionMatch(opt.label);return jsxRuntimeExports.jsxs("div",{className:`${styles$n_askOptionItem}${selected?" "+styles$n_askOptionSelected:""}`,children:[jsxRuntimeExports.jsx("span",{className:styles$n_askRadioDot,children:selected?checkSvg:"○"}),jsxRuntimeExports.jsxs("span",{className:styles$n_askOptionBody,children:[jsxRuntimeExports.jsx("span",{className:styles$n_askOptionLabel,children:opt.label}),hasOptionDescription(opt)&&jsxRuntimeExports.jsx("span",{className:styles$n_askOptionDesc,children:opt.description})]})]},oi)}),isOtherAnswer&&jsxRuntimeExports.jsxs("div",{className:`${styles$n_askOptionItem} ${styles$n_askOptionSelected}`,children:[jsxRuntimeExports.jsx("span",{className:styles$n_askRadioDot,children:checkSvg}),jsxRuntimeExports.jsx("span",{className:styles$n_askOptionBody,children:jsxRuntimeExports.jsx("span",{className:styles$n_askOptionLabel,children:answer})})]})]})]},qi)})]},tu.id)}if("EnterPlanMode"===tu.name)return jsxRuntimeExports.jsx("div",{className:styles$n_planModeBox,children:jsxRuntimeExports.jsx("span",{className:styles$n_planModeLabel,children:t("ui.enterPlanMode")})},tu.id);if("ExitPlanMode"===tu.name){const prompts=inp.allowedPrompts||[],{planApprovalMap:planApprovalMap}=this.props,approval=planApprovalMap&&planApprovalMap[tu.id]||{status:"pending"},isPending="pending"===approval.status,isInteractive=isPending&&this.props.cliMode&&tu.id===this.props.lastPendingPlanId;let planTextContent=null;if(isPending){if("string"==typeof inp.plan&&inp.plan.trim()&&(planTextContent=inp.plan),!planTextContent&&"string"==typeof inp.planFilePath&&inp.planFilePath&&this.props.planFileContents&&this.props.planFileContents[inp.planFilePath]&&(planTextContent=this.props.planFileContents[inp.planFilePath]),planTextContent||(planTextContent=this.props.latestPlanContent||null),!planTextContent&&Array.isArray(this.props.content))for(const b of this.props.content){if(b===tu)break;"tool_use"===b.type&&"Write"===b.name&&(null==(_b=b.input)?void 0:_b.file_path)&&/\.claude\/plans\//i.test(b.input.file_path)&&b.input.content&&(planTextContent=b.input.content)}if(!planTextContent&&Array.isArray(this.props.content)){const texts=[];for(const b of this.props.content){if(b===tu)break;"text"===b.type&&b.text&&texts.push(b.text)}planTextContent=texts.join("\n\n").trim()||null}}if("approved"===approval.status){const approvedText=approval.planContent||("string"==typeof inp.plan&&inp.plan.trim()?inp.plan:"")||"string"==typeof inp.planFilePath&&inp.planFilePath&&this.props.planFileContents&&this.props.planFileContents[inp.planFilePath]||"";if(approvedText)return jsxRuntimeExports.jsx("div",{className:styles$n_bubblePlan,children:jsxRuntimeExports.jsx(MarkdownBlock$1,{text:approvedText})},tu.id)}const detectedPrompt=isPlanApprovalPrompt(this.props.ptyPrompt)?this.props.ptyPrompt:this.props.activePlanPrompt||null,defaultPlanOptions=[{number:1,text:t("ui.planApprove"),selected:!0},{number:2,text:t("ui.planApproveWithEdits"),selected:!1},{number:3,text:t("ui.planReject"),selected:!1}],planOptions=(null==(_c=null==detectedPrompt?void 0:detectedPrompt.options)?void 0:_c.length)?detectedPrompt.options:defaultPlanOptions,statusClass="approved"===approval.status?styles$n_planStatusApproved:"rejected"===approval.status?styles$n_planStatusRejected:"ultraplan"===approval.status?styles$n_planStatusApproved:styles$n_planStatusPending,statusIcon="approved"===approval.status?"✓":"rejected"===approval.status?"✗":"ultraplan"===approval.status?"⚡":"●",statusKey="approved"===approval.status?"ui.planApproved":"rejected"===approval.status?"ui.planRejected":"ultraplan"===approval.status?"ui.planUltraplan":"ui.planPending",planModeBoxNode=jsxRuntimeExports.jsxs("div",{className:`${styles$n_planModeBox} ${statusClass}`,children:[isInteractive&&jsxRuntimeExports.jsx("svg",{className:`${styles$n_borderSvg} ${styles$n_borderSvgInset}`,preserveAspectRatio:"none",children:jsxRuntimeExports.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",rx:"6",ry:"6",fill:"none",stroke:"var(--color-primary)",strokeWidth:"1",strokeDasharray:"6 4",className:styles$n_borderRect})}),jsxRuntimeExports.jsxs("div",{className:styles$n_planModeHeader,children:[jsxRuntimeExports.jsx("span",{className:styles$n_planModeLabel,children:t(isPending?"ui.exitPlanMode":"ui.exitPlanModeResolved")}),!isInteractive&&jsxRuntimeExports.jsxs("span",{className:`${styles$n_planStatusBadge} ${statusClass}`,children:[statusIcon," ",t(statusKey)]})]}),isPending&&planTextContent&&jsxRuntimeExports.jsx("div",{className:styles$n_planContentPreview,children:jsxRuntimeExports.jsx(MarkdownBlock$1,{text:planTextContent})}),prompts.length>0&&jsxRuntimeExports.jsxs("div",{className:styles$n_planModePermissions,children:[jsxRuntimeExports.jsx("div",{className:styles$n_planModePermLabel,children:t("ui.allowedPrompts")}),prompts.map((p,pi)=>jsxRuntimeExports.jsxs("div",{className:styles$n_askOptionItem,children:["• ",p.prompt||p.tool]},pi))]}),isInteractive&&!this.state.planFeedbackInput&&jsxRuntimeExports.jsx("div",{className:styles$n_planApprovalActions,children:this.state.planApprovalSubmitting?jsxRuntimeExports.jsx("button",{className:styles$n_planOptionBtn,disabled:!0,children:t("ui.askSubmitting")}):planOptions.map((opt,optIdx)=>{const txt=(opt.text||"").toLowerCase();let btnCls=styles$n_planOptionBtn;/yes|approve|accept|proceed/i.test(txt)||null==detectedPrompt&&0===optIdx?btnCls=styles$n_planApproveBtn:(/no|reject|deny|feedback/i.test(txt)||null==detectedPrompt&&2===optIdx)&&(btnCls=styles$n_planRejectBtn);const isFeedbackOpt=/type|tell|change|feedback|edit/i.test(opt.text||"")||null==detectedPrompt&&1===optIdx;return jsxRuntimeExports.jsx("button",{className:btnCls,onClick:()=>{isFeedbackOpt?this.setState({planFeedbackInput:!0,planFeedbackOptNumber:opt.number,planFeedbackText:""}):(this.setState({planApprovalSubmitting:!0}),this.props.onPlanApprovalClick(opt.number))},children:opt.text},opt.number)})}),isInteractive&&this.state.planFeedbackInput&&jsxRuntimeExports.jsxs("div",{className:styles$n_planFeedbackInputWrap,children:[jsxRuntimeExports.jsx("textarea",{className:styles$n_planFeedbackTextarea,placeholder:t("ui.planFeedbackPlaceholder"),value:this.state.planFeedbackText,onChange:e=>this.setState({planFeedbackText:e.target.value}),onKeyDown:e=>{if((e.ctrlKey||e.metaKey)&&"Enter"===e.key){e.preventDefault();const text=this.state.planFeedbackText.trim();text&&this.props.onPlanFeedbackSubmit&&(this.props.onPlanFeedbackSubmit(this.state.planFeedbackOptNumber,text),this.setState({planFeedbackInput:!1,planFeedbackText:"",planFeedbackOptNumber:null}))}},autoFocus:!0,rows:3}),jsxRuntimeExports.jsxs("div",{className:styles$n_planFeedbackBtnRow,children:[jsxRuntimeExports.jsx("button",{className:styles$n_planFeedbackCancelBtn,onClick:()=>this.setState({planFeedbackInput:!1,planFeedbackText:"",planFeedbackOptNumber:null}),children:t("ui.cancel")}),jsxRuntimeExports.jsx("button",{className:styles$n_planFeedbackSendBtn,disabled:!this.state.planFeedbackText.trim(),onClick:()=>{const text=this.state.planFeedbackText.trim();text&&this.props.onPlanFeedbackSubmit&&(this.props.onPlanFeedbackSubmit(this.state.planFeedbackOptNumber,text),this.setState({planFeedbackInput:!1,planFeedbackText:"",planFeedbackOptNumber:null}))},children:t("ui.planFeedbackSubmit")})]})]}),"rejected"===approval.status&&approval.feedback&&jsxRuntimeExports.jsxs("div",{className:styles$n_planFeedback,children:[jsxRuntimeExports.jsxs("span",{className:styles$n_planFeedbackLabel,children:[t("ui.planFeedback"),":"]})," ",approval.feedback]})]},tu.id),ptyPlanCardId=isInteractive?String(tu.id):"";return jsxRuntimeExports.jsx(ApprovalPortalContext.Consumer,{children:ctx=>!(!(null==ctx?void 0:ctx.ptyPlanSlot)||null==(null==ctx?void 0:ctx.activePtyPlanId)||""===ptyPlanCardId||String(ctx.activePtyPlanId)!==ptyPlanCardId)?ReactDOM.createPortal(planModeBoxNode,ctx.ptyPlanSlot):planModeBoxNode},tu.id)}if("SendMessage"===tu.name&&null!=inp.message){const to=inp.to||"",msg=inp.message;if("object"==typeof msg&&msg.type){const statusKey=`ui.teammate.${msg.type}`,statusText=t(statusKey,{name:to}),display=statusText===statusKey?`${to}: ${msg.type}`:statusText;return jsxRuntimeExports.jsx("div",{className:styles$n_teammateStatusRow,children:jsxRuntimeExports.jsx("span",{className:styles$n_teammateStatusBubble,children:display})},tu.id)}if("string"==typeof msg){const header2=inp.summary?`→ ${to} — ${inp.summary}`:`→ ${to}`;return jsxRuntimeExports.jsxs("div",{className:styles$n_sendMessageBlock,children:[jsxRuntimeExports.jsx("div",{className:styles$n_sendMessageHeader,children:header2}),jsxRuntimeExports.jsx(MarkdownBlock$1,{text:msg})]},tu.id)}}let toolLabel2=tu.name;const keys=Object.keys(inp);if(0===keys.length)return box(toolLabel2,null);const items=keys.map(k=>{const v=inp[k],vs="string"==typeof v?v:JSON.stringify(v),display="Agent"===tu.name||"TaskCreate"===tu.name||"TaskUpdate"===tu.name||"SendMessage"===tu.name||vs.length<=200?vs:vs.substring(0,200)+"...";return jsxRuntimeExports.jsxs("div",{className:styles$n_kvItem,children:[jsxRuntimeExports.jsxs("span",{className:styles$n_kvKey,children:[k,": "]}),jsxRuntimeExports.jsx("span",{className:styles$n_kvValue,children:display})]},k)});return box(toolLabel2,jsxRuntimeExports.jsx("div",{className:styles$n_kvContainer,children:items}))}renderDangerApproval(toolId,dangerPrompt){if(!dangerPrompt)return null;const options=dangerPrompt.options||[];return jsxRuntimeExports.jsxs("div",{className:styles$n_dangerApprovalBox,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_dangerApprovalHeader,children:[jsxRuntimeExports.jsx("span",{className:styles$n_dangerApprovalIcon,children:"⚠"}),jsxRuntimeExports.jsx("span",{className:styles$n_dangerApprovalLabel,children:t("ui.dangerApproval")})]}),jsxRuntimeExports.jsx("div",{className:styles$n_dangerApprovalActions,children:options.map(opt=>{const txt=(opt.text||"").toLowerCase();let btnCls=styles$n_dangerOptionBtn;return/^no/i.test(txt)||/deny/i.test(txt)?btnCls=styles$n_dangerRejectBtn:(/^yes/i.test(txt)||/allow/i.test(txt))&&(btnCls=styles$n_dangerApproveBtn),jsxRuntimeExports.jsx("button",{className:btnCls,onClick:()=>{this.props.onDangerousApprovalClick&&this.props.onDangerousApprovalClick(opt.number)},children:opt.text},opt.number)})})]},`danger-${toolId}`)}renderAskQuestionInteractive(toolId,questions){const node=jsxRuntimeExports.jsx(AskQuestionForm,{questions:questions,onSubmit:answers=>{this.props.onAskQuestionSubmit&&this.props.onAskQuestionSubmit(answers,toolId,questions)}},toolId);return jsxRuntimeExports.jsx(ApprovalPortalContext.Consumer,{children:ctx=>{if(!ctx||!ctx.askSlot||null==ctx.activeAskId)return node;const isStrictMatch=String(ctx.activeAskId)===String(toolId),isPtyOwnerMatch="__ask__"===ctx.activeAskId&&this.props.lastPendingAskId===toolId;return isStrictMatch||isPtyOwnerMatch?ReactDOM.createPortal(node,ctx.askSlot):node}})}renderHighlightBubble(bubbleClass,children){const{highlight:highlight2}=this.props,cls=`${bubbleClass}${"active"===highlight2?" "+styles$n_bubbleHighlight:""}${"fading"===highlight2?" "+styles$n_bubbleHighlightFading:""}`,isUser=bubbleClass===styles$n_bubbleUser;return jsxRuntimeExports.jsxs("div",{className:`${cls} ${styles$n_bubbleRelative}`,children:[("active"===highlight2||"fading"===highlight2)&&jsxRuntimeExports.jsx("svg",{className:`${styles$n_borderSvg}${"fading"===highlight2?" "+styles$n_borderSvgFading:""}`,preserveAspectRatio:"none",children:jsxRuntimeExports.jsx("rect",{x:"0.5",y:"0.5",width:"calc(100% - 1px)",height:"calc(100% - 1px)",rx:"8",ry:"8",fill:"none",stroke:isUser?"#fff":"var(--color-primary)",strokeWidth:"1",strokeDasharray:"6 4",className:styles$n_borderRect})}),children]})}renderUserMessage(){const{text:text,timestamp:timestamp}=this.props,timeStr=this.formatTime(timestamp),userName=this.getUserName();return text&&text.includes("This session is being continued from a previous conversation that ran out of context")?jsxRuntimeExports.jsxs("div",{className:styles$n_messageRowEnd,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_contentColLimited,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_labelRow,children:[timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$n_timeTextNoMargin,children:timeStr}),this.renderViewRequestBtn(),jsxRuntimeExports.jsxs(Text$1,{type:"secondary",className:styles$n_labelTextRight,children:[userName," — /compact"]})]}),this.renderHighlightBubble(styles$n_bubbleUser,jsxRuntimeExports.jsx(Collapse,{ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsx(Text$1,{className:styles$n_compactLabel,children:"Compact Summary"}),children:jsxRuntimeExports.jsx("pre",{className:styles$n_compactPre,children:text})}],className:styles$n_collapseNoMargin}))]}),this.renderUserAvatar("#1e40af")]}):jsxRuntimeExports.jsxs("div",{className:styles$n_messageRowEnd,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_contentColLimited,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_labelRow,children:[timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$n_timeTextNoMargin,children:timeStr}),this.renderViewRequestBtn(),jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$n_labelTextRight,children:userName})]}),this.renderHighlightBubble(styles$n_bubbleUser,this.renderUserTextWithImages(text))]}),this.renderUserAvatar("#1e40af")]})}renderUserTextWithImages(text){if(!text)return text||"";const IMAGE_EXTS2=/\.(png|jpe?g|gif|webp|avif|svg|bmp|ico|icns)$/i,combinedPattern=/\[Image(?:\s*#\d+)?(?::?\s*source)?:\s*([^\]]+)\]|"(\/tmp\/cc-viewer-uploads\/[^"]+?)"/g,parts=[];let match,lastIndex=0;for(;null!==(match=combinedPattern.exec(text));){const filePath2=(match[1]||match[2]||"").trim();if(!filePath2||!IMAGE_EXTS2.test(filePath2))continue;match.index>lastIndex&&parts.push(jsxRuntimeExports.jsx("span",{children:text.slice(lastIndex,match.index)},`t-${lastIndex}`));const originalText=match[0];parts.push(jsxRuntimeExports.jsx(ChatImage,{src:apiUrl(`/api/file-raw?path=${encodeURIComponent(filePath2)}`),alt:filePath2.split("/").pop(),fallbackText:originalText},`img-${match.index}`)),lastIndex=match.index+match[0].length}return 0===parts.length?text:(lastIndex<text.length&&parts.push(jsxRuntimeExports.jsx("span",{children:text.slice(lastIndex)},`t-${lastIndex}`)),jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:parts}))}renderToolResult(tr){return tr?jsxRuntimeExports.jsx(ToolResultView,{toolName:tr.toolName,toolInput:tr.toolInput,resultText:tr.resultText,defaultCollapsed:this.props.collapseToolResults}):null}renderAssistantContent(content2,toolResultMap={}){const thinkingBlocks=content2.filter(b=>"thinking"===b.type),textBlocks=content2.filter(b=>"text"===b.type),toolUseBlocks=content2.filter(b=>"tool_use"===b.type),showTC=!!this.props.showTrailingCursor,hasTextWithContent=textBlocks.some(b=>b.text&&b.text.trim()),lastThinkingIdxWithContent=showTC&&!hasTextWithContent?thinkingBlocks.reduce((acc,b,i)=>b.thinking&&b.thinking.trim()?i:acc,-1):-1,lastTextIdxWithContent=showTC&&hasTextWithContent?textBlocks.reduce((acc,b,i)=>b.text&&b.text.trim()?i:acc,-1):-1,streamThinkingExpanded=!hasTextWithContent||!!this.props.expandThinking;let innerContent=[];thinkingBlocks.forEach((tb,i)=>{const thinkingText=tb.thinking||"",isEmpty=!thinkingText.trim(),isCursorTarget=i===lastThinkingIdxWithContent,collapseProps=showTC?{key:`think-stream-${i}`,activeKey:streamThinkingExpanded?["1"]:[]}:{key:`think-${i}-${this.props.expandThinking?"e":"c"}`,defaultActiveKey:this.props.expandThinking?["1"]:[]};innerContent.push(jsxRuntimeExports.jsx(Collapse,{...collapseProps,ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$n_thinkingLabel,children:t("ui.thinking")}),children:isEmpty?jsxRuntimeExports.jsxs("div",{className:styles$n_thinkingEmptyHint,children:[jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$n_thinkingEmptyText,children:t("ui.thinkingEmpty")}),!this.props.showThinkingSummaries&&jsxRuntimeExports.jsx(Tooltip,{title:tc("ui.enableThinkingSummariesTip"),children:jsxRuntimeExports.jsx(Button,{size:"small",type:"primary",ghost:!0,className:styles$n_enableThinkingBtn,onClick:e=>{e.stopPropagation(),this.context.updateClaudeSettings({showThinkingSummaries:!0}).then(data=>{data?staticMethods.success(tc("ui.enableThinkingSummariesTip")):staticMethods.error("Failed to save setting")})},children:t("ui.enableThinkingSummaries")})})]}):jsxRuntimeExports.jsx(MarkdownBlock$1,{text:thinkingText,trailingCursor:isCursorTarget})}],className:`${styles$n_collapseMargin}${showTC?" "+styles$n_collapseStream:""}`}))}),textBlocks.forEach((tb,i)=>{if(tb.text){const{segments:segments}=renderAssistantText(tb.text),isCursorTarget=i===lastTextIdxWithContent;innerContent.push(jsxRuntimeExports.jsx("div",{className:"chat-boxer",children:this.renderSegments(segments,isCursorTarget)},`text-${i}`))}});const simplify=!this.props.showFullToolContent;let simplifiedLabelAdded=!1;return toolUseBlocks.forEach((tu,tuIdx)=>{const isFullDisplayTool="Edit"===tu.name||"Write"===tu.name||"EnterPlanMode"===tu.name||"ExitPlanMode"===tu.name||"AskUserQuestion"===tu.name||"Agent"===tu.name||"TaskCreate"===tu.name||"SendMessage"===tu.name;simplify&&!isFullDisplayTool?(simplifiedLabelAdded||(simplifiedLabelAdded=!0,innerContent.push(jsxRuntimeExports.jsx("span",{className:styles$n_simplifiedToolLabel,children:t("ui.toolsUsed")},`stag-label-${tuIdx}`))),innerContent.push(jsxRuntimeExports.jsx(Popover,{placement:"top",overlayClassName:"simplifiedToolPopover",overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-hover)",borderRadius:8,padding:0},content:jsxRuntimeExports.jsx("div",{className:styles$n_simplifiedToolPopoverContent,children:this.renderToolCall(tu)}),mouseEnterDelay:.3,...isMobile&&!isPad?{trigger:"click",...!isIOS&&{getPopupContainer:node=>node.parentElement}}:{},children:jsxRuntimeExports.jsx("span",{className:styles$n_simplifiedToolTag,children:tu.name})},`stag-${tu.id}`))):(simplifiedLabelAdded=!1,innerContent.push(this.renderToolCall(tu)));const tr=toolResultMap[tu.id];if(!tr&&!toolUseBlocks.slice(0,tuIdx).some(t2=>!toolResultMap[t2.id])&&this.props.activeDangerousPrompt&&this.props.cliMode){const dp=this.props.activeDangerousPrompt;innerContent.push(this.renderDangerApproval(tu.id,dp))}if(tr){const approval=(this.props.planApprovalMap||{})[tu.id];"ExitPlanMode"===tu.name&&approval&&"approved"===approval.status&&approval.planContent||(simplify?tr.isPermissionDenied&&innerContent.push(jsxRuntimeExports.jsx(React__default.Fragment,{children:tr.isUltraplan?jsxRuntimeExports.jsx("div",{className:styles$n_ultraplanBadge,children:"◇ UltraPlan"}):jsxRuntimeExports.jsxs("div",{className:`${styles$n_dangerApprovalBox} ${styles$n_dangerApprovalBoxDenied}`,children:[jsxRuntimeExports.jsxs("span",{className:styles$n_dangerDeniedBadge,children:["✗ ",t("ui.dangerDenied")]}),tr.resultText&&jsxRuntimeExports.jsx("div",{className:styles$n_dangerDeniedDetail,children:tr.resultText})]})},`tr-denied-${tu.id}`)):tr.isPermissionDenied?innerContent.push(jsxRuntimeExports.jsx(React__default.Fragment,{children:tr.isUltraplan?jsxRuntimeExports.jsx("div",{className:styles$n_ultraplanBadge,children:"◇ UltraPlan"}):jsxRuntimeExports.jsxs("div",{className:`${styles$n_dangerApprovalBox} ${styles$n_dangerApprovalBoxDenied}`,children:[jsxRuntimeExports.jsxs("span",{className:styles$n_dangerDeniedBadge,children:["✗ ",t("ui.dangerDenied")]}),tr.resultText&&jsxRuntimeExports.jsx("div",{className:styles$n_dangerDeniedDetail,children:tr.resultText})]})},`tr-denied-${tu.id}`)):innerContent.push(jsxRuntimeExports.jsx(React__default.Fragment,{children:this.renderToolResult(tr)},`tr-${tu.id}`)))}}),innerContent}renderAssistantMessage(){const{content:content2,toolResultMap:toolResultMap={},modelInfo:modelInfo,timestamp:timestamp,requestIndex:requestIndex,onViewRequest:onViewRequest,showTrailingCursor:showTrailingCursor,cacheTotalTokens:cacheTotalTokens,showFullToolContent:showFullToolContent}=this.props,innerContent=this.renderAssistantContent(content2,toolResultMap);return 0===innerContent.length?null:jsxRuntimeExports.jsxs("div",{className:styles$n_messageRow,children:[jsxRuntimeExports.jsx(ModelAvatar,{modelInfo:modelInfo,streaming:!!showTrailingCursor}),jsxRuntimeExports.jsxs("div",{className:styles$n_contentCol,children:[jsxRuntimeExports.jsx(AssistantLabel,{name:(null==modelInfo?void 0:modelInfo.name)||"MainAgent",timeStr:this.formatTime(timestamp),requestIndex:requestIndex,onViewRequest:onViewRequest,cacheTotalTokens:cacheTotalTokens,showFullToolContent:showFullToolContent}),this.renderHighlightBubble(styles$n_bubbleAssistant,innerContent)]})]})}_getSubAvatarType(){if(this.props.isTeammate)return"teammate";const match=(this.props.label||"").match(/SubAgent:\s*(\w+)/i),st=match?match[1].toLowerCase():"";return"explore"===st||"search"===st?"sub-search":"plan"===st?"sub-plan":"sub"}renderSubAgentChatMessage(){const{content:content2,toolResultMap:toolResultMap={},label:label2,cacheTotalTokens:cacheTotalTokens,showFullToolContent:showFullToolContent}=this.props,innerContent=this.renderAssistantContent(content2,toolResultMap);if(0===innerContent.length)return null;const showCache=showFullToolContent&&null!=cacheTotalTokens,cacheStr=showCache?formatCacheK(cacheTotalTokens):"";return jsxRuntimeExports.jsxs("div",{className:styles$n_messageRowEnd,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_contentColLimited,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_labelRowEnd,children:[showCache&&jsxRuntimeExports.jsx(Text$1,{className:styles$n_cacheContextText,title:t("ui.cacheContextTooltip",{value:cacheStr}),children:`[${cacheStr}]`}),this.formatTime(this.props.timestamp)&&jsxRuntimeExports.jsx(Text$1,{className:styles$n_timeText,children:this.formatTime(this.props.timestamp)}),this.renderViewRequestBtn(),jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$n_labelTextRight,children:label2||"SubAgent"})]}),this.renderHighlightBubble(styles$n_bubbleAssistant,innerContent)]}),(()=>{const ta=this.props.isTeammate?getTeammateAvatar(label2):null;return jsxRuntimeExports.jsx("div",{className:styles$n_avatar,style:{background:ta?ta.color:"var(--bg-sub-avatar)"},dangerouslySetInnerHTML:{__html:ta?ta.svg:getSvgAvatar(this._getSubAvatarType())}})})()]})}renderSubAgentMessage(){const{label:label2,resultText:resultText,toolName:toolName2,toolInput:toolInput}=this.props,tmAvatar=this.props.isTeammate?getTeammateAvatar(label2):null;return jsxRuntimeExports.jsxs("div",{className:styles$n_messageRow,children:[jsxRuntimeExports.jsx("div",{className:styles$n_avatar,style:{background:tmAvatar?tmAvatar.color:"var(--bg-sub-avatar)"},dangerouslySetInnerHTML:{__html:tmAvatar?tmAvatar.svg:getSvgAvatar(this._getSubAvatarType())}}),jsxRuntimeExports.jsxs("div",{className:styles$n_contentCol,children:[this.renderLabel(label2),jsxRuntimeExports.jsx("div",{className:styles$n_bubbleSubAgent,children:jsxRuntimeExports.jsx(ToolResultView,{toolName:toolName2,toolInput:toolInput,resultText:resultText})})]})]})}renderTeammateMessage(){const{text:text,label:label2,timestamp:timestamp}=this.props,timeStr=this.formatTime(timestamp),ta=getTeammateAvatar(label2);return jsxRuntimeExports.jsxs("div",{className:styles$n_messageRowEnd,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_contentColLimited,children:[jsxRuntimeExports.jsxs("div",{className:styles$n_labelRowEnd,children:[timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$n_timeText,children:timeStr}),this.renderViewRequestBtn(),jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$n_labelTextRight,children:label2||"Teammate"})]}),this.renderHighlightBubble(styles$n_bubbleAssistant,jsxRuntimeExports.jsx(MarkdownBlock$1,{text:text||""}))]}),jsxRuntimeExports.jsx("div",{className:styles$n_avatar,style:{background:ta?ta.color:"var(--bg-sub-avatar)"},dangerouslySetInnerHTML:{__html:ta?ta.svg:getSvgAvatar("sub")}})]})}renderTeammateStatus(){const{label:label2,toolName:toolName2}=this.props,statusKey=`ui.teammate.${toolName2}`,statusText=t(statusKey,{name:label2||"Teammate"}),display=statusText===statusKey?`${label2||"Teammate"}: ${toolName2}`:statusText;return jsxRuntimeExports.jsx("div",{className:styles$n_teammateStatusRowCenter,children:jsxRuntimeExports.jsx("span",{className:styles$n_teammateStatusBubble,children:display})})}renderPlanPromptMessage(){const{text:text,timestamp:timestamp,modelInfo:modelInfo}=this.props;this.formatTime(timestamp);const planContent=(text||"").replace(/^[\s\S]*?Implement the following plan:\s*/i,"");return jsxRuntimeExports.jsxs("div",{className:styles$n_messageRow,children:[this.renderModelAvatar(modelInfo),jsxRuntimeExports.jsxs("div",{className:styles$n_contentColLimited,children:[this.renderLabel((null==modelInfo?void 0:modelInfo.name)||"MainAgent"," (Plan)"),jsxRuntimeExports.jsx("div",{className:styles$n_bubblePlan,children:jsxRuntimeExports.jsx(MarkdownBlock$1,{text:planContent})})]})]})}renderSkillLoadedMessage(){const{text:text,skillName:skillName,timestamp:timestamp}=this.props,timeStr=this.formatTime(timestamp);return jsxRuntimeExports.jsxs("div",{className:styles$n_messageRow,children:[jsxRuntimeExports.jsx("div",{className:styles$n_skillSpacer}),jsxRuntimeExports.jsx("div",{className:styles$n_contentCol,children:jsxRuntimeExports.jsx(Collapse,{ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsxs("span",{className:styles$n_skillLabel,children:["📦 ",t("ui.skillLoaded"),": ",skillName,timeStr&&jsxRuntimeExports.jsx(Text$1,{className:`${styles$n_timeTextNoMargin} ${styles$n_skillTimeIndent}`,children:timeStr})]}),children:jsxRuntimeExports.jsx(MarkdownBlock$1,{text:text})}],className:styles$n_collapseNoMargin})})]})}renderTaskNotification(){var _a,_b,_c;const{taskNotification:tn,modelInfo:modelInfo}=this.props;if(!tn)return null;const isError="error"===tn.status,statusIcon=isError?"✗":"✓",statusColor=isError?"#ff4d4f":"#52c41a",durationSec=(null==(_a=tn.usage)?void 0:_a.durationMs)?(tn.usage.durationMs/1e3).toFixed(1):null,tokens=(null==(_b=tn.usage)?void 0:_b.totalTokens)?tn.usage.totalTokens.toLocaleString():null,toolUses=(null==(_c=tn.usage)?void 0:_c.toolUses)||null,innerContent=[];return innerContent.push(jsxRuntimeExports.jsxs("div",{className:"chat-boxer",children:[jsxRuntimeExports.jsx("span",{style:{color:statusColor,fontWeight:"bold",marginRight:6},children:statusIcon}),tn.summary||"Background Task"]},"summary")),tn.result&&innerContent.push(jsxRuntimeExports.jsx(Collapse,{ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsx(Typography.Text,{type:"secondary",children:t("ui.taskNotification.result")||"Result"}),children:jsxRuntimeExports.jsx(MarkdownBlock$1,{text:tn.result})}]},"result")),(durationSec||tokens||toolUses)&&innerContent.push(jsxRuntimeExports.jsxs("div",{className:styles$n_taskNotifUsage,children:[durationSec&&jsxRuntimeExports.jsxs("span",{children:[durationSec,"s"]}),tokens&&jsxRuntimeExports.jsxs("span",{children:[tokens," tokens"]}),toolUses&&jsxRuntimeExports.jsxs("span",{children:[toolUses," tool uses"]})]},"usage")),jsxRuntimeExports.jsxs("div",{className:styles$n_messageRow,children:[this.renderModelAvatar(modelInfo),jsxRuntimeExports.jsxs("div",{className:styles$n_contentCol,children:[this.renderLabel((null==modelInfo?void 0:modelInfo.name)||"MainAgent"),this.renderHighlightBubble(styles$n_bubbleAssistant,innerContent)]})]})}render(){const{role:role}=this.props;return"user"===role?this.renderUserMessage():"skill-loaded"===role?this.renderSkillLoadedMessage():"plan-prompt"===role?this.renderPlanPromptMessage():"assistant"===role?this.renderAssistantMessage():"task-notification"===role?this.renderTaskNotification():"teammate-message"===role?this.renderTeammateMessage():"teammate-status"===role?this.renderTeammateStatus():"sub-agent-chat"===role?this.renderSubAgentChatMessage():"sub-agent"===role?this.renderSubAgentMessage():null}}__publicField(ChatMessage,"contextType",SettingsContext);const TerminalWsContext=reactExports.createContext({send:()=>!1,isOpen:()=>!1,addMessageHandler:()=>()=>{},addStateListener:()=>()=>{}});class TerminalWsProvider extends React__default.Component{constructor(props){super(props),__publicField(this,"connect",()=>{if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let url,ws;try{url=`${"https:"===window.location.protocol?"wss:":"ws:"}//${window.location.host}/ws/terminal`}catch(e){return}try{ws=new WebSocket(url)}catch(e){return console.warn("[TerminalWsProvider] WebSocket constructor failed:",e),void this._scheduleReconnect()}this.ws=ws,ws.onopen=()=>{this._notifyState("open")},ws.onmessage=ev=>{let msg;try{msg=JSON.parse(ev.data)}catch{return}for(const h of this.messageHandlers)try{h(msg)}catch(e){console.warn("[TerminalWsProvider] handler error:",e)}},ws.onerror=()=>{this._notifyState("error")},ws.onclose=()=>{this.ws===ws&&(this.ws=null),this._notifyState("close"),!this._unmounted&&this.props.open&&this._scheduleReconnect()}}),__publicField(this,"disconnect",()=>{if(this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws){const ws=this.ws;this.ws=null;try{ws.onclose=null}catch{}try{ws.close()}catch{}}}),__publicField(this,"_scheduleReconnect",()=>{this.reconnectTimer||this._unmounted||(this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this._unmounted&&this.props.open&&this.connect()},2e3))}),__publicField(this,"_notifyState",state=>{for(const l of this.stateListeners)try{l(state)}catch(e){console.warn("[TerminalWsProvider] state listener error:",e)}}),__publicField(this,"send",obj=>{const ws=this.ws;if(!ws||ws.readyState!==WebSocket.OPEN)return!1;try{return ws.send(JSON.stringify(obj)),!0}catch(e){return console.warn("[TerminalWsProvider] send error:",e),!1}}),__publicField(this,"isOpen",()=>{const ws=this.ws;return!(!ws||ws.readyState!==WebSocket.OPEN)}),__publicField(this,"addMessageHandler",fn=>"function"!=typeof fn?()=>{}:(this.messageHandlers.add(fn),()=>{this.messageHandlers.delete(fn)})),__publicField(this,"addStateListener",fn=>"function"!=typeof fn?()=>{}:(this.stateListeners.add(fn),()=>{this.stateListeners.delete(fn)})),this.ws=null,this.messageHandlers=new Set,this.stateListeners=new Set,this.reconnectTimer=null,this._unmounted=!1,this._ctxValue={send:this.send,isOpen:this.isOpen,addMessageHandler:this.addMessageHandler,addStateListener:this.addStateListener}}componentDidMount(){this.props.open&&this.connect()}componentDidUpdate(prevProps){!prevProps.open&&this.props.open?this.connect():prevProps.open&&!this.props.open&&this.disconnect()}componentWillUnmount(){this._unmounted=!0,this.disconnect()}render(){return jsxRuntimeExports.jsx(TerminalWsContext.Provider,{value:this._ctxValue,children:this.props.children})}}const styles$j_terminalPanel="_terminalPanel_1hkbt_1",styles$j_terminalContainer="_terminalContainer_1hkbt_4",styles$j_terminalHost="_terminalHost_1hkbt_23",styles$j_terminalContainerFocused="_terminalContainerFocused_1hkbt_43",styles$j_pendingFileStrip="_pendingFileStrip_1hkbt_59",styles$j_pendingFileTag="_pendingFileTag_1hkbt_67",styles$j_pendingFileName="_pendingFileName_1hkbt_84",styles$j_pendingFileClose="_pendingFileClose_1hkbt_91",styles$j_pendingImageItem="_pendingImageItem_1hkbt_105",styles$j_pendingImageThumb="_pendingImageThumb_1hkbt_120",styles$j_pendingImageRemove="_pendingImageRemove_1hkbt_127",styles$j_terminalToolbar="_terminalToolbar_1hkbt_162",styles$j_toolbarBtn="_toolbarBtn_1hkbt_177",styles$j_toolbarBtnDisabled="_toolbarBtnDisabled_1hkbt_198",styles$j_virtualKeybar="_virtualKeybar_1hkbt_213",styles$j_virtualKey="_virtualKey_1hkbt_213",styles$j_virtualKeyPressed="_virtualKeyPressed_1hkbt_244",styles$j_vkSeparator="_vkSeparator_1hkbt_251",styles$j_vkAction="_vkAction_1hkbt_260",styles$j_vkTeamLabel="_vkTeamLabel_1hkbt_272",styles$j_vkTeamPreset="_vkTeamPreset_1hkbt_281",styles$j_vkDisabled="_vkDisabled_1hkbt_286",styles$j_presetList="_presetList_1hkbt_292",styles$j_presetRow="_presetRow_1hkbt_300",styles$j_presetRowDragging="_presetRowDragging_1hkbt_312",styles$j_presetRowDragOver="_presetRowDragOver_1hkbt_316",styles$j_dragHandle="_dragHandle_1hkbt_321",styles$j_presetText="_presetText_1hkbt_339",styles$j_presetMenu="_presetMenu_1hkbt_349",styles$j_presetMenuItem="_presetMenuItem_1hkbt_354",styles$j_presetMenuItemMuted="_presetMenuItemMuted_1hkbt_373",styles$j_presetName="_presetName_1hkbt_392",styles$j_presetInput="_presetInput_1hkbt_402",styles$j_presetTextarea="_presetTextarea_1hkbt_418",styles$j_hiddenFileInput="_hiddenFileInput_1hkbt_435",styles$j_popoverEmptyHint="_popoverEmptyHint_1hkbt_439",styles$j_agentTeamDisabledTip="_agentTeamDisabledTip_1hkbt_446",styles$j_toolbarLeft="_toolbarLeft_1hkbt_453",styles$j_toolbarRight="_toolbarRight_1hkbt_455",styles$j_ctxBarSlot="_ctxBarSlot_1hkbt_454",styles$j_toolbarBtnActive="_toolbarBtnActive_1hkbt_480",styles$j_scratchWrap="_scratchWrap_1hkbt_494",styles$j_scratchTabs="_scratchTabs_1hkbt_492",styles$j_scratchTab="_scratchTab_1hkbt_492",styles$j_scratchTabActive="_scratchTabActive_1hkbt_533",styles$j_scratchTabIcon="_scratchTabIcon_1hkbt_541",styles$j_scratchTabLabel="_scratchTabLabel_1hkbt_550",styles$j_scratchTabClose="_scratchTabClose_1hkbt_557",styles$j_scratchTabAdd="_scratchTabAdd_1hkbt_588",styles$j_scratchPanes="_scratchPanes_1hkbt_492",styles$j_scratchPanesFocused="_scratchPanesFocused_1hkbt_625",styles$j_scratchPane="_scratchPane_1hkbt_492",styles$j_scratchPaneActive="_scratchPaneActive_1hkbt_639",styles$j_scratchResizer="_scratchResizer_1hkbt_645",styles$j_scratchResizerDragging="_scratchResizerDragging_1hkbt_658",styles$j_scratchInner="_scratchInner_1hkbt_35",styles$j_scratchHost="_scratchHost_1hkbt_35",styles$j_presetSectionHeader="_presetSectionHeader_1hkbt_705",styles$j_presetSectionTitle="_presetSectionTitle_1hkbt_709",styles$j_presetListEmptyHint="_presetListEmptyHint_1hkbt_715",styles$j_presetActions="_presetActions_1hkbt_722",styles$j_presetFormField="_presetFormField_1hkbt_728",styles$j_presetFormLabel="_presetFormLabel_1hkbt_732",styles$j_ultraplanPanel="_ultraplanPanel_1hkbt_740",styles$j_ultraplanHeader="_ultraplanHeader_1hkbt_746",styles$j_ultraplanHeaderTitle="_ultraplanHeaderTitle_1hkbt_757",styles$j_ultraplanCloseBtn="_ultraplanCloseBtn_1hkbt_763",styles$j_ultraplanCustomWrap="_ultraplanCustomWrap_1hkbt_782",styles$j_ultraplanCustomTitle="_ultraplanCustomTitle_1hkbt_788",styles$j_ultraplanEditPencil="_ultraplanEditPencil_1hkbt_795",styles$j_ultraplanVariantRow="_ultraplanVariantRow_1hkbt_826",styles$j_ultraplanRoleBtn="_ultraplanRoleBtn_1hkbt_834",styles$j_ultraplanAddExpertBtn="_ultraplanAddExpertBtn_1hkbt_859",styles$j_ultraplanRoleBtnActive="_ultraplanRoleBtnActive_1hkbt_882",styles$j_ultraplanTextarea="_ultraplanTextarea_1hkbt_891",styles$j_ultraplanFooter="_ultraplanFooter_1hkbt_915",styles$j_ultraplanSendBtn="_ultraplanSendBtn_1hkbt_922",styles$j_ultraplanUploadBtn="_ultraplanUploadBtn_1hkbt_944",styles$j_ultraplanFileList="_ultraplanFileList_1hkbt_966",styles$j_ultraplanFileChip="_ultraplanFileChip_1hkbt_973",styles$j_ultraplanFileName="_ultraplanFileName_1hkbt_996",styles$j_ultraplanFileRemove="_ultraplanFileRemove_1hkbt_1003",styles$j_ultraplanImageItem="_ultraplanImageItem_1hkbt_1016",styles$j_ultraplanImageThumb="_ultraplanImageThumb_1hkbt_1031",styles$j_ultraplanImageRemove="_ultraplanImageRemove_1hkbt_1038",BUILTIN_PRESETS=[{builtinId:"codereview-5",teamName:"ui.preset.codeReview5.name",description:"ui.preset.codeReview5.desc"}],ULTRAPLAN_VARIANTS={codeExpert:'<system-reminder>\n[SCOPED INSTRUCTION] The following instructions apply only to the next 1–3 interactions. Once the task is complete, these instructions should gradually decrease in priority and no longer affect subsequent interactions.\n\nPre-requisite: Use `AskUserQuestion` to clarify user intent whenever the request is ambiguous (target element, interaction style, scope of platforms, etc.). Skip only if the intent is unambiguous.\n\nLeverage a multi-agent exploration mechanism to formulate a highly detailed implementation plan.\n\nInstructions:\n1. Use the `Agent` tool to spawn parallel agents that simultaneously explore different aspects of the codebase:\n- If necessary, assign a preliminary researcher to use the `webSearch` tool to first investigate cutting-edge solutions in the relevant industry domain;\n- One agent responsible for understanding the relevant existing code and architecture;\n- One agent responsible for identifying all files that need to be modified;\n- One agent responsible for identifying potential risks, edge cases, and dependencies;\n- You may add other roles or deploy additional agents beyond the three listed above; the maximum number of concurrently dispatched agents is 5.\n\n2. Synthesize the findings from all agents into a detailed, step-by-step implementation plan.\n\n3. Use the `Agent` tool to spawn 2-3 review agents that examine the plan from different perspectives, checking for missing steps, potential risks, or corresponding mitigation strategies.\n\n4. Integrate the feedback gathered during the review process, then call `ExitPlanMode` to submit your final plan.\n\n5. Once `ExitPlanMode` returns a result:\n- If approved: proceed to execute the plan within this session.\n- If rejected: revise the plan based on the feedback provided and call `ExitPlanMode` again.\n- If an error occurs (including receiving a "Not in Plan Mode" message): do **not** follow the suggestions provided in the error message; instead, prompt the user for further instructions.\n\nYour final plan must include the following elements:\n- A clear summary of the implementation strategy;\n- An ordered list of files to be created or modified, with precise details of the required changes for each file;\n- A step-by-step execution sequence;\n- Testing and validation procedures;\n- Potential risks and their corresponding mitigation strategies;\n\n6. After the final plan has been successfully executed:\nFirst run `git diff --quiet && git diff --cached --quiet` (or equivalent) to detect whether the working tree actually has non-trivial changes; if there are no real changes (or only whitespace/comment-only edits), skip the UltraReview step.\nOtherwise, if the project is managed with Git:\nInitiate a team (`TeamCreate`), dynamically allocating the number of teammates based on task complexity (5 is recommended);\nTask: Conduct a Code Review of the current git changes from multiple perspectives;\nPre-requisites:\n- The git repository may be located in a subdirectory of the current directory; prefer `git rev-parse --show-toplevel` (fall back to recursive lookup) before proceeding;\n- In the case of multiple repositories, tasks may be executed separately;\nThe team\'s goal is to analyze the current Git change log and validate each modification from different perspectives, specifically including:\n- Whether requirements/objectives have been met and functionality is complete;\n- Whether newly added code introduces side effects, breaks existing functionality, or poses potential risks;\n- Code quality: naming, readability, complexity, technical debt, maintainability;\n- Testing and documentation: whether there is adequate test coverage, and whether critical logic has necessary comments or documentation;\n- Dependencies and compatibility: whether new dependencies or version compatibility issues have been introduced;\nWorkflow:\n- Each teammate, according to their own role, covers the review dimensions one by one and independently outputs a report;\n- After consolidating the reports, perform a cross-review to identify conflicts or shared concerns;\n- Distill specific, actionable modification suggestions and annotate them with priority levels (P0/P1/P2/P3);\n- Upon completion, adopt P0 items, and selectively adopt P1 items when they are concrete and low-risk; defer P2/P3 to backlog;\n- After execution is complete, close the team (`TeamDelete`);\n</system-reminder>',researchExpert:'<system-reminder>\n[SCOPED INSTRUCTION] The following instructions are intended for the next 1–3 interactions. Once the task is complete, these instructions should be gradually deprioritized and no longer influence subsequent interactions.\n\nPre-requisite: Use `AskUserQuestion` to clarify the research scope, target audience, and deliverable format whenever the user\'s intent is ambiguous. Skip only if the intent is unambiguous.\n\nLeverage a multi-agent exploration mechanism to formulate an exceptionally detailed implementation plan.\n\nInstructions:\n1. Utilize the Agent tool to spawn parallel agents that simultaneously explore various facets of the requirements:\n- If necessary, deploy a preliminary investigator to conduct an initial survey of industry-specific solutions using `webSearch`;\n- If necessary, deploy a specialized investigator to research authoritative sources—such as academic papers, news articles, and research reports—using `webSearch`;\n- Assign an agent to synthesize the target solution, while simultaneously verifying the rigor and credibility of the gathered papers, news, and research reports;\n- If necessary, assign an agent to analyze competitor data to provide supplementary analytical perspectives;\n- If necessary, assign an agent to handle the implementation of a product demo (generating outputs such as HTML, Markdown, etc.);\n- If the task is sufficiently complex, you may assign additional teammates to the roles defined above, or introduce other specialized roles; you are permitted to schedule up to 5 teammates concurrently.\n\n2. Synthesize the findings from the aforementioned agents into a comprehensive, step-by-step implementation plan.\n\n3. Utilize the Agent tool to spawn a set of parallel review agents; these agents shall scrutinize the plan from multiple roles and perspectives to identify any omitted steps and to propose reasonable additions or optimizations.\n\n4. Consolidate the feedback received from the review agents, then invoke `ExitPlanMode` to submit your final plan.\n\n5. Upon receiving the result from `ExitPlanMode`:\n- If Approved: Proceed to execute the plan within this current session.\n- If Rejected: Revise the plan based on the provided feedback, and then invoke `ExitPlanMode` once again.\n- If an Error Occurs (including the message "Not in Plan Mode"): Do *not* follow the suggestions provided by the error message; instead, prompt the user for further instructions.\n\nYour final plan must include the following elements:\n- A clear summary of the proposed implementation strategy;\n- An ordered list of files to be created or modified, specifying the exact changes required for each;\n- A step-by-step sequence for executing the implementation;\n- Identification of potential risks and corresponding mitigation strategies;\n- Creative ideation and suggestions for advanced enhancements;\n- If a product demo was generated, place the corresponding demo output in an appropriate location and notify the user.\n</system-reminder>'};function buildLocalUltraplan(userPrompt,variant="codeExpert",seedPlan,customContent){let template;if("custom"===variant){if(template=function(content2){const body2=(content2||"").trim();return body2?`<system-reminder>\n[SCOPED INSTRUCTION] The following instructions are intended for the next 1–3 interactions. Once the task is complete, these instructions should be gradually deprioritized and no longer influence subsequent interactions.\n\n${body2}\n</system-reminder>`:""}(customContent),!template)return""}else template=ULTRAPLAN_VARIANTS[variant]||ULTRAPLAN_VARIANTS.codeExpert;const parts=[];return parts.push(template),userPrompt&&parts.push("",userPrompt),parts.join("\n")}function buildArrows(currentIdx,targetIdx){const chunks=[],diff=targetIdx-currentIdx,arrow2=diff>0?"[B":"[A";for(let i=0;i<Math.abs(diff);i++)chunks.push(arrow2);return chunks}function getCursorIdx(prompt){if(prompt&&prompt.options){const idx=prompt.options.findIndex(o2=>o2.selected);return idx>=0?idx:0}return 0}function buildChunksForAnswer(answer,prompt,isMultiQuestion=!1){return"multi"===answer.type?function(answer,prompt,isMultiQuestion=!1){const chunks=[],indices=(answer.selectedIndices||[]).slice().sort((a,b)=>a-b);let currentIdx=getCursorIdx(prompt);for(const targetIdx of indices)chunks.push(...buildArrows(currentIdx,targetIdx)),chunks.push(" "),currentIdx=targetIdx;return chunks.push("[C"),!answer.isLast&&isMultiQuestion||chunks.push("\r"),chunks}(answer,prompt,isMultiQuestion):"other"===answer.type&&answer.isMultiSelect?function(answer,prompt,isMultiQuestion=!1){const chunks=[];let currentIdx=getCursorIdx(prompt);const targetIdx=answer.optionIndex;chunks.push(...buildArrows(currentIdx,targetIdx));const text=answer.text||"";for(const ch of text)chunks.push(ch);if(text.length>0){const chars=[...text];chunks.push(chars[chars.length-1])}return chunks.push("[C"),chunks.push("[A"),chunks.push("[C"),!answer.isLast&&isMultiQuestion||chunks.push("\r"),chunks}(answer,prompt,isMultiQuestion):"other"===answer.type?function(answer,prompt,isMultiQuestion=!1){const chunks=[];let currentIdx=getCursorIdx(prompt);const targetIdx=answer.optionIndex;chunks.push(...buildArrows(currentIdx,targetIdx));const text=answer.text||"";for(const ch of text)chunks.push(ch);return chunks.push("\r"),isMultiQuestion&&answer.isLast&&chunks.push("\r"),chunks}(answer,prompt,isMultiQuestion):function(answer,prompt,isMultiQuestion=!1){const chunks=[];let currentIdx=getCursorIdx(prompt),targetIdx=answer.optionIndex;if(prompt&&prompt.options){const targetNumber=answer.optionIndex+1,found=prompt.options.findIndex(o2=>o2.number===targetNumber);found>=0&&(targetIdx=found)}return chunks.push(...buildArrows(currentIdx,targetIdx)),chunks.push("\r"),isMultiQuestion&&answer.isLast&&chunks.push("\r"),chunks}(answer,prompt,isMultiQuestion)}function buildBracketPasteSubmitChunks(content2){return"string"!=typeof content2||0===content2.length?[]:[`[200~${content2}[201~`,"\r"]}const styles$i_helpBtn="_helpBtn_19lpl_1",styles$i_modalBody="_modalBody_19lpl_25",styles$i_spinWrap="_spinWrap_19lpl_124",KNOWN_DOCS=new Set(["Tool-Bash","Tool-Read","Tool-Edit","Tool-Write","Tool-Glob","Tool-Grep","Tool-NotebookEdit","Tool-WebFetch","Tool-WebSearch","Tool-Agent","Tool-TaskOutput","Tool-TaskStop","Tool-TaskCreate","Tool-TaskGet","Tool-TaskUpdate","Tool-TaskList","Tool-TeamCreate","Tool-TeamDelete","Tool-SendMessage","SubAgent-Search","Tool-EnterPlanMode","Tool-ExitPlanMode","Tool-AskUserQuestion","Tool-Skill","Tool-getDiagnostics","Tool-executeCode","Tool-EnterWorktree","Tool-ExitWorktree","Tool-CronCreate","Tool-CronDelete","Tool-CronList","Tool-Monitor","Tool-PushNotification","Tool-RemoteTrigger","Tool-ScheduleWakeup","MainAgent","Teammate","BodyFields","ResponseFields","Tools","ToolsFirst","CacheRebuild","BodyDiffJSON","TranslateContextPollution","KVCacheContent","ProxySwitch","GlobalSettings","QRCode","UltraPlan","CustomUltraplanExpert"]);function ConceptHelp({doc:doc,zIndex:zIndex,children:children}){const[open,setOpen]=reactExports.useState(!1),[loading2,setLoading]=reactExports.useState(!1),[html,setHtml]=reactExports.useState(""),[title2,setTitle]=reactExports.useState("");if(!doc||!KNOWN_DOCS.has(doc))return children||null;const loadDoc=reactExports.useCallback(async()=>{setOpen(!0),setLoading(!0),setHtml(""),setTitle(doc);const lang=getLang();let md=null;try{const res=await fetch(apiUrl(`/api/concept?lang=${lang}&doc=${encodeURIComponent(doc)}`));res.ok&&(md=await res.text())}catch(_){}if(md){const firstLine=md.match(/^#\s+(.+)/m);firstLine&&setTitle(firstLine[1]),setHtml(renderMarkdown(md))}else setHtml("<p>Document not found.</p>");setLoading(!1)},[doc]),modalStyles=isMobile&&!isPad?{header:{padding:"8px 12px",margin:0},body:{maxHeight:"80vh",overflow:"auto",padding:"8px 10px"},content:{padding:0}}:{body:{padding:"16px 24px 24px",background:"var(--bg-container)",borderRadius:"4px"},content:{padding:"12px 20px"}},triggerHandlers={onClick:e=>{e.stopPropagation(),e.nativeEvent.stopImmediatePropagation(),loadDoc()},onMouseDown:e=>{e.stopPropagation(),e.nativeEvent.stopImmediatePropagation()},onPointerDown:e=>{e.stopPropagation(),e.nativeEvent.stopImmediatePropagation()}};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[children?React__default.cloneElement(children,{...triggerHandlers,style:{cursor:"pointer",...children.props.style||{}}}):jsxRuntimeExports.jsx("span",{className:styles$i_helpBtn,...triggerHandlers,children:"?"}),jsxRuntimeExports.jsx(Modal,{title:title2,open:open,onCancel:()=>setOpen(!1),footer:null,width:isMobile&&!isPad?"98vw":800,centered:isMobile&&!isPad,styles:modalStyles,...zIndex?{zIndex:zIndex}:{},wrapProps:{onMouseDown:e=>e.stopPropagation()},children:loading2?jsxRuntimeExports.jsx("div",{className:styles$i_spinWrap,children:jsxRuntimeExports.jsx(Spin,{})}):jsxRuntimeExports.jsx("div",{className:styles$i_modalBody,dangerouslySetInnerHTML:{__html:html}})})]})}const styles$h={titleRow:"_titleRow_mfv69_1",field:"_field_mfv69_7",titleInput:"_titleInput_mfv69_11",contentTextarea:"_contentTextarea_mfv69_27",footer:"_footer_mfv69_48",footerRight:"_footerRight_mfv69_55"};function CustomUltraplanEditModal({open:open,initial:initial,onSave:onSave,onDelete:onDelete,onClose:onClose}){const[title2,setTitle]=reactExports.useState(""),[content2,setContent]=reactExports.useState("");reactExports.useEffect(()=>{open&&(setTitle((null==initial?void 0:initial.title)||""),setContent((null==initial?void 0:initial.content)||""))},[open,initial]);const canSave=title2.trim().length>0&&content2.trim().length>0,isEdit=!!(null==initial?void 0:initial.id),footer2=jsxRuntimeExports.jsxs("div",{className:styles$h.footer,children:[jsxRuntimeExports.jsx("div",{className:styles$h.footerLeft,children:isEdit&&jsxRuntimeExports.jsx(Popconfirm,{title:t("ui.ultraplan.customDeleteConfirm"),okText:t("ui.ultraplan.customDelete"),cancelText:t("ui.ultraplan.customCancel"),onConfirm:()=>{isEdit&&onDelete(initial.id)},children:jsxRuntimeExports.jsx(Button,{danger:!0,children:t("ui.ultraplan.customDelete")})})}),jsxRuntimeExports.jsxs("div",{className:styles$h.footerRight,children:[jsxRuntimeExports.jsx(Button,{onClick:onClose,children:t("ui.ultraplan.customCancel")}),jsxRuntimeExports.jsx(Button,{type:"primary",disabled:!canSave,onClick:()=>{if(!canSave)return;const id=isEdit?initial.id:`cue-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;onSave({id:id,title:title2.trim(),content:content2.trim()})},children:t("ui.ultraplan.customSave")})]})]});return jsxRuntimeExports.jsxs(Modal,{title:jsxRuntimeExports.jsxs("span",{className:styles$h.titleRow,children:[t(isEdit?"ui.ultraplan.customEditTitle":"ui.ultraplan.customCreateTitle"),jsxRuntimeExports.jsx(ConceptHelp,{doc:"CustomUltraplanExpert",zIndex:1300})]}),open:open,onCancel:onClose,footer:footer2,width:600,zIndex:1200,destroyOnClose:!0,styles:{content:{background:"var(--bg-elevated)",border:"1px solid var(--border-light)"},header:{background:"var(--bg-elevated)",borderBottom:"none"}},children:[jsxRuntimeExports.jsx("div",{className:styles$h.field,children:jsxRuntimeExports.jsx("input",{className:styles$h.titleInput,placeholder:t("ui.ultraplan.customTitlePlaceholder"),value:title2,maxLength:30,onChange:e=>setTitle(e.target.value),autoFocus:!0})}),jsxRuntimeExports.jsx("div",{className:styles$h.field,children:jsxRuntimeExports.jsx("textarea",{className:styles$h.contentTextarea,placeholder:t("ui.ultraplan.customContentPlaceholder"),value:content2,rows:10,onChange:e=>setContent(e.target.value)})})]})}class TerminalWriteQueue{constructor(getTerminal){this._getTerminal=getTerminal,this._queue=[],this._head=0,this._offset=0,this._rafId=0,this._unmounted=!1}push(data){data&&!this._unmounted&&"string"==typeof data&&(this._queue.push(data),this._schedule())}_schedule(){this._rafId||this._unmounted||(this._rafId=requestAnimationFrame(()=>this._flush()))}_flush(){if(this._rafId=0,this._unmounted)return;const term=this._getTerminal();if(!term)return;let out="";for(;this._head<this._queue.length&&out.length<32768;){const head=this._queue[this._head],offset=this._offset,remaining=head.length-offset,need=32768-out.length;if(need<=0)break;if(remaining<=need)out+=0===offset?head:head.slice(offset),this._head++,this._offset=0;else{let cut=offset+need;const codeAtEnd=head.charCodeAt(cut-1);codeAtEnd>=55296&&codeAtEnd<=56319&&(cut-1>offset?cut--:cut<head.length&&cut++),out+=head.slice(offset,cut),this._offset=cut}}if(!out)return;const headBefore=this._head,offsetBefore=this._offset;try{term.write(out)}catch{return this._head=headBefore,void(this._offset=offsetBefore)}(this._head>64||this._head>8&&2*this._head>this._queue.length)&&(this._queue=this._queue.slice(this._head),this._head=0),this._head<this._queue.length&&this._schedule()}drain(){if(this._unmounted)return;const term=this._getTerminal();if(!term||this._head>=this._queue.length)return;let out="";for(;this._head<this._queue.length;){const head=this._queue[this._head];out+=0===this._offset?head:head.slice(this._offset),this._head++,this._offset=0}if(out)try{term.write(out)}catch{}}dispose(){this._unmounted=!0,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=0),this._queue.length=0,this._head=0,this._offset=0}_pendingBytes(){let total=0;for(let i=this._head;i<this._queue.length;i++)total+=this._queue[i].length;return total-this._offset}}function ConfirmRemoveButton({title:title2,onConfirm:onConfirm,className:className,ariaLabel:ariaLabel,tag:tag="button",children:children,onPopupOpenChange:onPopupOpenChange}){const Tag2=tag,role="button"===tag?void 0:"button";if(isMobile){const handleClick=e=>{e.stopPropagation(),null==onPopupOpenChange||onPopupOpenChange(!0),Modal.confirm({title:title2,okText:t("ui.common.confirmYes"),cancelText:t("ui.common.confirmCancel"),okButtonProps:{danger:!0},centered:!0,zIndex:1200,onOk:()=>{onConfirm(),null==onPopupOpenChange||onPopupOpenChange(!1)},onCancel:()=>null==onPopupOpenChange?void 0:onPopupOpenChange(!1)})};return jsxRuntimeExports.jsx(Tag2,{className:className,onClick:handleClick,"aria-label":ariaLabel,role:role,children:children})}return jsxRuntimeExports.jsx(Popconfirm,{title:title2,okText:t("ui.common.confirmYes"),cancelText:t("ui.common.confirmCancel"),okButtonProps:{danger:!0},onOpenChange:onPopupOpenChange,onConfirm:e=>{null==e||e.stopPropagation(),onConfirm()},onCancel:e=>null==e?void 0:e.stopPropagation(),children:jsxRuntimeExports.jsx(Tag2,{className:className,onClick:e=>e.stopPropagation(),"aria-label":ariaLabel,role:role,children:children})})}TerminalWriteQueue.CHUNK_SIZE=32768,TerminalWriteQueue.GC_THRESHOLD_HEAD=64;const darkTerminalTheme={background:"#0a0a0a",foreground:"#d4d4d4",cursor:"#0a0a0a",selectionBackground:"#264f78",black:"#000000",red:"#ef4444",green:"#73c991",yellow:"#fbbf24",blue:"#3b82f6",magenta:"#d946ef",cyan:"#06b6d4",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#ff7b7b",brightGreen:"#9ddc6f",brightYellow:"#ffce5b",brightBlue:"#66b3ff",brightMagenta:"#e88ce8",brightCyan:"#7eddd9",brightWhite:"#ffffff"},lightTerminalTheme={background:"#ffffff",foreground:"#333333",cursor:"#333333",selectionBackground:"#cce5ff",black:"#000000",red:"#CD3131",green:"#107C10",yellow:"#949800",blue:"#0451A5",magenta:"#BC05BC",cyan:"#0598BC",white:"#555555",brightBlack:"#666666",brightRed:"#CD3131",brightGreen:"#14CE14",brightYellow:"#B5BA00",brightBlue:"#0451A5",brightMagenta:"#BC05BC",brightCyan:"#0598BC",brightWhite:"#A5A5A5"};class ScratchTerminal extends React__default.Component{constructor(props){super(props),__publicField(this,"_throttledWrite",data=>{this._writeQ.push(data)}),__publicField(this,"refit",()=>{if(!this.fitAddon||!this.terminal)return;const el=this.containerRef.current;if(!(!el||el.offsetWidth<=0||el.offsetHeight<=0))try{this.fitAddon.fit(),this.sendResize()}catch{}}),__publicField(this,"focus",()=>{var _a;try{null==(_a=this.terminal)||_a.focus()}catch{}}),__publicField(this,"requestKill",()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"kill"}))}catch{}if(this._closing=!0,this.ws){this.ws.onclose=null;try{this.ws.close()}catch{}this.ws=null}}),this.containerRef=React__default.createRef(),this.terminal=null,this.fitAddon=null,this.ws=null,this.resizeObserver=null,this._writeQ=new TerminalWriteQueue(()=>this.terminal),this._closing=!1}componentDidMount(){this.initTerminal(),this.connectWebSocket(),this.setupResizeObserver(),this._themeObserver=new MutationObserver(()=>{if(this.terminal){const isDark="light"!==document.documentElement.getAttribute("data-theme");this.terminal.options.theme=isDark?darkTerminalTheme:lightTerminalTheme}}),this._themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]})}componentWillUnmount(){var _a,_b,_c;if(this._closing=!0,this._wsReconnectTimer&&clearTimeout(this._wsReconnectTimer),this._themeObserver&&(this._themeObserver.disconnect(),this._themeObserver=null),this._writeQ){try{this._writeQ.drain()}catch{}this._writeQ.dispose()}if(this._resizeDebounceTimer&&clearTimeout(this._resizeDebounceTimer),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),null==(_a=this.terminal)?void 0:_a.textarea)try{this.terminal.textarea.removeEventListener("focus",this._handleScratchFocus),this.terminal.textarea.removeEventListener("blur",this._handleScratchBlur)}catch{}try{null==(_c=(_b=this.props).onFocusChange)||_c.call(_b,!1)}catch{}if(this.ws){this.ws.onclose=null;try{this.ws.close()}catch{}this.ws=null}if(this.terminal){try{this.terminal.dispose()}catch{}this.terminal=null}}initTerminal(){const isDark="light"!==document.documentElement.getAttribute("data-theme");this.terminal=new Dl({cursorBlink:!1,cursorStyle:"bar",cursorWidth:1,fontSize:13,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:isDark?darkTerminalTheme:lightTerminalTheme,allowProposedApi:!0,scrollback:1e3,smoothScrollDuration:0,scrollOnUserInput:!0}),this.fitAddon=new o,this.terminal.loadAddon(this.fitAddon),this.terminal.loadAddon(new L);const unicode11=new Ke;this.terminal.loadAddon(unicode11),this.terminal.unicode.activeVersion="11",this.terminal.open(this.containerRef.current),this.terminal.onData(data=>{this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"input",data:data}))}),this._handleScratchFocus=()=>{var _a,_b;try{null==(_b=(_a=this.props).onFocusChange)||_b.call(_a,!0)}catch{}},this._handleScratchBlur=()=>{var _a,_b;try{null==(_b=(_a=this.props).onFocusChange)||_b.call(_a,!1)}catch{}};const ta=this.terminal.textarea;ta&&(ta.addEventListener("focus",this._handleScratchFocus),ta.addEventListener("blur",this._handleScratchBlur))}connectWebSocket(){if(this._closing)return;const id=this.props.id;if(!id)return;const wsUrl=`${"https:"===window.location.protocol?"wss:":"ws:"}//${window.location.host}/ws/terminal-scratch?id=${encodeURIComponent(id)}`;this.ws=new WebSocket(wsUrl),this.ws.onmessage=event=>{var _a,_b;try{const msg=JSON.parse(event.data);if("data"===msg.type)this._throttledWrite(msg.data);else if("state"===msg.type){if(msg.shellBasename)try{null==(_b=(_a=this.props).onShellInfo)||_b.call(_a,msg.shellBasename)}catch{}}else if("exit"===msg.type)try{this.terminal&&this.terminal.write(`\r\n[90m[scratch shell exited: ${msg.exitCode??"?"}][0m\r\n`)}catch{}else if("toast"===msg.type)try{this.terminal&&this.terminal.write(`\r\n[33m⚠ ${msg.message}[0m\r\n`)}catch{}}catch{}},this.ws.onclose=()=>{this._closing||(this._wsReconnectTimer=setTimeout(()=>{!this._closing&&this.containerRef.current&&this.connectWebSocket()},2e3))},this.ws.onopen=()=>{this.sendResize()}}sendResize(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.terminal&&this.ws.send(JSON.stringify({type:"resize",cols:this.terminal.cols,rows:this.terminal.rows}))}setupResizeObserver(){this.resizeObserver=new ResizeObserver(()=>{this._resizeDebounceTimer&&clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{if(!this.fitAddon||!this.terminal)return;const el=this.containerRef.current;if(!(!el||el.offsetWidth<=0||el.offsetHeight<=0))try{this.fitAddon.fit(),this.sendResize()}catch{}},80)}),this.containerRef.current&&this.resizeObserver.observe(this.containerRef.current)}render(){return jsxRuntimeExports.jsx("div",{className:styles$j_scratchInner,children:jsxRuntimeExports.jsx("div",{ref:this.containerRef,className:styles$j_scratchHost})})}}const KEEP_FORMAT=new Set(["image/png","image/webp"]);function loadViaImgElement(file){return new Promise((resolve,reject)=>{const url=URL.createObjectURL(file),img=new Image;img.onload=()=>{URL.revokeObjectURL(url),resolve(img)},img.onerror=e=>{URL.revokeObjectURL(url),reject(e)},img.src=url})}async function resizeImageIfNeeded(file,maxDim=2e3){var _a,_b,_c,_d,_e;if(!file||"object"!=typeof file)return file;const type=(file.type||"").toLowerCase();if(!type.startsWith("image/"))return file;if("image/gif"===type)return file;let source2;try{source2=await function(file){return"function"==typeof createImageBitmap?createImageBitmap(file).catch(()=>loadViaImgElement(file)):loadViaImgElement(file)}(file)}catch{return file}const srcW=source2.width||source2.naturalWidth,srcH=source2.height||source2.naturalHeight;if(!srcW||!srcH){try{null==(_a=source2.close)||_a.call(source2)}catch{}return file}const maxSide=Math.max(srcW,srcH);if(maxSide<=maxDim){try{null==(_b=source2.close)||_b.call(source2)}catch{}return file}const scale=maxDim/maxSide,dstW=Math.max(1,Math.round(srcW*scale)),dstH=Math.max(1,Math.round(srcH*scale)),canvas=document.createElement("canvas");canvas.width=dstW,canvas.height=dstH;const ctx=canvas.getContext("2d");if(!ctx){try{null==(_c=source2.close)||_c.call(source2)}catch{}return file}ctx.imageSmoothingEnabled=!0,ctx.imageSmoothingQuality="high";try{ctx.drawImage(source2,0,0,dstW,dstH)}catch{try{null==(_d=source2.close)||_d.call(source2)}catch{}return file}try{null==(_e=source2.close)||_e.call(source2)}catch{}const outType=(inputType=type,KEEP_FORMAT.has(inputType)?inputType:"image/jpeg");var inputType;const quality="image/png"===outType?void 0:.92;let blob;try{blob=await function(canvas,type,quality){return new Promise((resolve,reject)=>{canvas.toBlob(blob=>blob?resolve(blob):reject(new Error("toBlob returned null")),type,quality)})}(canvas,outType,quality)}catch{return file}const nameOut=function(originalName,outType){const ext="image/jpeg"===outType?"jpg":"image/png"===outType?"png":"image/webp"===outType?"webp":"img",dot=originalName.lastIndexOf(".");return`${dot>0?originalName.slice(0,dot):originalName}.${ext}`}(file.name||"image",outType);return new File([blob],nameOut,{type:outType,lastModified:Date.now()})}const SCRATCH_TAB_ID_RE=/^[A-Za-z0-9_-]{1,64}$/;function readScratchOpen(){try{return"true"===localStorage.getItem("cc-viewer-scratch-open")}catch{return!1}}function readScratchHeight(){try{const v=parseInt(localStorage.getItem("cc-viewer-scratch-height"),10);return Number.isFinite(v)?Math.max(100,Math.min(600,v)):200}catch{return 200}}function genScratchTabId(){return("t-"+("undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).slice(2)+Date.now().toString(36))).slice(0,64)}function writeScratchTabs(tabs){try{localStorage.setItem("cc-viewer-scratch-tabs",JSON.stringify(tabs))}catch{}}function writeScratchActiveTab(id){try{localStorage.setItem("cc-viewer-scratch-active-tab",id)}catch{}}function PlusIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),jsxRuntimeExports.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function CloseIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",width:"10",height:"10",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntimeExports.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function ScratchTerminalIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),jsxRuntimeExports.jsx("polyline",{points:"7 9 10 12 7 15"}),jsxRuntimeExports.jsx("line",{x1:"13",y1:"15",x2:"17",y2:"15"})]})}const VIRTUAL_KEYS=[{label:"↑",seq:"[A"},{label:"↓",seq:"[B"},{label:"←",seq:"[D"},{label:"→",seq:"[C"},{label:"Enter",seq:"\r"},{label:"Tab",seq:"\t"},{label:"Esc",seq:""},{label:"Ctrl+C",seq:""}];function UploadIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),jsxRuntimeExports.jsx("polyline",{points:"17 8 12 3 7 8"}),jsxRuntimeExports.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]})}function UltraplanIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("circle",{cx:"12",cy:"12",r:"2.5"}),jsxRuntimeExports.jsx("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4"}),jsxRuntimeExports.jsx("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",transform:"rotate(60 12 12)"}),jsxRuntimeExports.jsx("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",transform:"rotate(120 12 12)"})]})}function TrashIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M3 6h18"}),jsxRuntimeExports.jsx("path",{d:"M8 6V4h8v2"}),jsxRuntimeExports.jsx("path",{d:"M5 6v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V6"}),jsxRuntimeExports.jsx("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),jsxRuntimeExports.jsx("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]})}function AgentTeamIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),jsxRuntimeExports.jsx("circle",{cx:"9",cy:"7",r:"4"}),jsxRuntimeExports.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),jsxRuntimeExports.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}async function uploadFileAndGetPath(file){let upload=file;try{upload=await resizeImageIfNeeded(file,2e3)}catch{upload=file}if(upload.size>104857600)throw new Error("File too large (max 100MB)");const form=new FormData;form.append("file",upload);const res=await fetch(apiUrl("/api/upload"),{method:"POST",body:form}),data=await res.json();if(!data.ok)throw new Error(data.error||"Upload failed");return data.path}class TerminalPanel extends React__default.Component{constructor(props){super(props),__publicField(this,"handleScratchTabClick",id=>{id!==this.state.activeScratchTabId&&this.setState({activeScratchTabId:id},()=>{writeScratchActiveTab(id);const r=this._scratchRefs.get(id);(null==r?void 0:r.current)&&(r.current.refit(),r.current.focus())})}),__publicField(this,"handleScratchTabAdd",()=>{if(this.state.scratchTabs.length>=8)return;const newId=genScratchTabId(),tabs=[...this.state.scratchTabs,{id:newId}];this.setState({scratchTabs:tabs,activeScratchTabId:newId},()=>{writeScratchTabs(tabs),writeScratchActiveTab(newId),Promise.resolve().then(()=>{var _a,_b;const r=this._scratchRefs.get(newId);null==(_a=null==r?void 0:r.current)||_a.refit(),null==(_b=null==r?void 0:r.current)||_b.focus()})})}),__publicField(this,"handleScratchTabClose",(id,e)=>{var _a,_b,_c;if(e&&(e.stopPropagation(),e.preventDefault()),this.state.scratchTabs.length<=1)return;const ref=this._scratchRefs.get(id);try{null==(_a=null==ref?void 0:ref.current)||_a.requestKill()}catch{}this._scratchRefs.delete(id);const idx=this.state.scratchTabs.findIndex(t2=>t2.id===id),tabs=this.state.scratchTabs.filter(t2=>t2.id!==id);let active=this.state.activeScratchTabId;active===id&&(active=(null==(_b=this.state.scratchTabs[idx+1]??this.state.scratchTabs[idx-1])?void 0:_b.id)??(null==(_c=tabs[0])?void 0:_c.id)??""),this.setState({scratchTabs:tabs,activeScratchTabId:active},()=>{var _a2,_b2;if(writeScratchTabs(tabs),writeScratchActiveTab(active),active){const r=this._scratchRefs.get(active);null==(_a2=null==r?void 0:r.current)||_a2.refit(),null==(_b2=null==r?void 0:r.current)||_b2.focus()}})}),__publicField(this,"handleScratchTabFocusChange",(id,focused)=>{id===this.state.activeScratchTabId&&focused!==this.state.scratchFocused&&this.setState({scratchFocused:focused})}),__publicField(this,"handleScratchShellInfo",name=>{name&&!this.state.scratchShellBasename&&this.setState({scratchShellBasename:name})}),__publicField(this,"toggleScratch",()=>{const next=!this.state.scratchOpen;this.setState({scratchOpen:next});try{localStorage.setItem("cc-viewer-scratch-open",String(next))}catch{}}),__publicField(this,"_applyScratchHeight",()=>{const el=this._scratchWrapRef.current;el&&(el.style.height=this.state.scratchHeight+"px")}),__publicField(this,"handleScratchResizerPointerDown",e=>{if(void 0===e.button||0===e.button){e.preventDefault(),this._scratchDragging=!0,this._scratchDragStartY=e.clientY,this._scratchDragStartH=this.state.scratchHeight,this._scratchDragLastH=this.state.scratchHeight,this._scratchPointerId=e.pointerId;try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}document.body.style.cursor="row-resize",document.body.style.userSelect="none",this.setState({isDraggingScratch:!0})}}),__publicField(this,"handleScratchResizerPointerMove",e=>{if(!this._scratchDragging)return;const newH=Math.max(100,Math.min(600,this._scratchDragStartH+(this._scratchDragStartY-e.clientY))),el=this._scratchWrapRef.current;el&&(el.style.height=newH+"px",this._scratchDragLastH=newH)}),__publicField(this,"handleScratchResizerPointerUp",e=>{this._scratchDragging&&this._endScratchDrag(e)}),__publicField(this,"_endScratchDrag",e=>{if(this._scratchDragging=!1,document.body.style.cursor="",document.body.style.userSelect="",e&&null!=this._scratchPointerId&&e.currentTarget)try{e.currentTarget.releasePointerCapture(this._scratchPointerId)}catch{}this._scratchPointerId=null;const h=this._scratchDragLastH;if(this._scratchDragLastH=null,null!=h){try{localStorage.setItem("cc-viewer-scratch-height",String(h))}catch{}this.setState({scratchHeight:h,isDraggingScratch:!1})}else this.setState({isDraggingScratch:!1})}),__publicField(this,"_onTerminalWsMessage",msg=>{try{"data"===msg.type?this._throttledWrite(msg.data):"exit"===msg.type?(this._flushWrite(),this.terminal.write(`\r\n[33m${t("ui.terminal.exited",{code:msg.exitCode??"?"})}[0m\r\n`),this.terminal.write(`[90m${t("ui.terminal.pressEnterForShell")}[0m\r\n`)):"editor-open"===msg.type?this.props.onEditorOpen&&this.props.onEditorOpen(msg.sessionId,msg.filePath):"state"===msg.type?msg.running||null===msg.exitCode||(this._flushWrite(),this.terminal.write(`[33m${t("ui.terminal.exited",{code:msg.exitCode})}[0m\r\n`),this.terminal.write(`[90m${t("ui.terminal.pressEnterForShell")}[0m\r\n`)):"toast"===msg.type&&(this._flushWrite(),this.terminal.write(`\r\n[33m⚠ ${msg.message}[0m\r\n`))}catch{}}),__publicField(this,"_onTerminalWsState",state=>{var _a;"open"===state?this.sendResize():"close"===state&&(null==(_a=this.terminal)||_a.reset())}),__publicField(this,"_handlePaste",e=>{var _a,_b,_c,_d;const items=null==(_a=e.clipboardData)?void 0:_a.items;if(items)for(const item of items)if(item.type.startsWith("image/")){e.preventDefault(),e.stopPropagation();const file=item.getAsFile();return void(file&&this._uploadClipboardImage(file))}if(null==(_c=null==(_b=this.terminal)?void 0:_b.modes)?void 0:_c.bracketedPasteMode)return;const text=null==(_d=e.clipboardData)?void 0:_d.getData("text");if(text&&this.ws&&this.ws.readyState===WebSocket.OPEN&&(text.includes("\n")||text.includes("\r"))){e.preventDefault(),e.stopPropagation();const wrapped=`[200~${text}[201~`;this.ws.send(JSON.stringify({type:"input",data:wrapped}))}}),__publicField(this,"_uploadClipboardImage",async file=>{try{const optimized=await this._downscaleForRetina(file),path=await uploadFileAndGetPath(optimized);this.props.onFilePath&&this.props.onFilePath(path),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"image-upload-notify",path:path,source:"terminal"})),this.terminal&&this.terminal.focus()}catch(err){console.error("[CC Viewer] Clipboard image upload failed:",err),staticMethods.error(t("ui.terminal.pasteImageFailed"))}}),__publicField(this,"handleVirtualKey",seq=>{var _a,_b;if(this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"input",data:seq})),isMobile&&!isPad){const ta=null==(_a=this.containerRef.current)?void 0:_a.querySelector(".xterm-helper-textarea");ta&&ta.blur()}else null==(_b=this.terminal)||_b.focus()}),__publicField(this,"_vkTouchStart",e=>{e.preventDefault();const touch=e.touches[0];this._vkStartX=touch.clientX,this._vkStartY=touch.clientY,this._vkMoved=!1,this._vkTarget=e.currentTarget,this._vkTarget.classList.add(styles$j_virtualKeyPressed)}),__publicField(this,"_vkTouchMove",e=>{if(this._vkMoved)return;const touch=e.touches[0],dx=touch.clientX-this._vkStartX,dy=touch.clientY-this._vkStartY;dx*dx+dy*dy>64&&(this._vkMoved=!0)}),__publicField(this,"_vkTouchEnd",(action,e)=>{var _a;e.preventDefault(),null==(_a=this._vkTarget)||_a.classList.remove(styles$j_virtualKeyPressed),this._vkTarget=null,this._vkMoved||action()}),__publicField(this,"handleFileUpload",async e=>{var _a;const file=null==(_a=e.target.files)?void 0:_a[0];if(file){try{const path=await uploadFileAndGetPath(file);this.props.onFilePath&&this.props.onFilePath(path),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"image-upload-notify",path:path,source:"terminal"})),isMobile&&!isPad||!this.terminal||this.terminal.focus()}catch(err){console.error("[CC Viewer] Upload failed:",err)}e.target.value=""}}),__publicField(this,"_savePresetShortcuts",(items,dismissed)=>{const payload={presetShortcuts:items.map(i=>{const o2={teamName:i.teamName,description:i.description};return i.builtinId&&(o2.builtinId=i.builtinId),i.modified&&(o2.modified=!0),o2})};dismissed&&(payload.dismissedBuiltinPresets=[...dismissed]),this.props.onUpdatePreferences&&this.props.onUpdatePreferences(payload)}),__publicField(this,"handlePresetAdd",()=>{const description=this.state.presetAddText.trim(),teamName=this.state.presetAddName.trim();if(!description&&!teamName)return;const{presetEditId:presetEditId,presetItems:presetItems}=this.state;let next;next=presetEditId?presetItems.map(i=>{if(i.id!==presetEditId)return i;const updated={...i,teamName:teamName,description:description};return i.builtinId&&(updated.modified=!0),updated}):[...presetItems,{id:Date.now(),teamName:teamName,description:description}],this.setState({presetItems:next,presetAddVisible:!1,presetAddText:"",presetAddName:"",presetEditId:null}),this._savePresetShortcuts(next)}),__publicField(this,"handlePresetDelete",()=>{const{presetItems:presetItems,presetSelected:presetSelected}=this.state;if(0===presetSelected.size)return;const dismissed=new Set(this._dismissedBuiltinPresets||[]);for(const item of presetItems)presetSelected.has(item.id)&&item.builtinId&&dismissed.add(item.builtinId);this._dismissedBuiltinPresets=dismissed;const next=presetItems.filter(i=>!presetSelected.has(i.id));this.setState({presetItems:next,presetSelected:new Set}),this._savePresetShortcuts(next,dismissed)}),__publicField(this,"handlePresetToggle",id=>{this.setState(prev=>{const next=new Set(prev.presetSelected);return next.has(id)?next.delete(id):next.add(id),{presetSelected:next}})}),__publicField(this,"_dragIdx",null),__publicField(this,"_dragOverIdx",null),__publicField(this,"handleDragStart",(idx,e)=>{e.stopPropagation(),this._dragIdx=idx,e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/x-preset-reorder",String(idx)),requestAnimationFrame(()=>this.forceUpdate())}),__publicField(this,"handleDragOver",(idx,e)=>{e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="move",this._dragOverIdx!==idx&&(this._dragOverIdx=idx,this.forceUpdate())}),__publicField(this,"handleDragEnd",e=>{e&&e.stopPropagation(),this._dragIdx=null,this._dragOverIdx=null,this.forceUpdate()}),__publicField(this,"handleDragLeave",(idx,e)=>{e.stopPropagation(),this._dragOverIdx===idx&&(this._dragOverIdx=null,this.forceUpdate())}),__publicField(this,"handleDrop",(idx,e)=>{e.preventDefault(),e.stopPropagation();const from=this._dragIdx;if(null===from||from===idx)return void this.handleDragEnd();const items=[...this.state.presetItems],[moved]=items.splice(from,1);items.splice(from<idx?idx-1:idx,0,moved),this.setState({presetItems:items}),this._savePresetShortcuts(items),this.handleDragEnd()}),__publicField(this,"handlePresetSend",description=>{description&&(this.setState({agentTeamPopoverOpen:!1}),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"input-sequential",chunks:buildBracketPasteSubmitChunks(description),settleMs:250})),isMobile&&!isPad||!this.terminal||this.terminal.focus())}),__publicField(this,"handleClearContext",()=>{var _a,_b;this.ws&&this.ws.readyState===WebSocket.OPEN&&(this.ws.send(JSON.stringify({type:"input-sequential",chunks:buildBracketPasteSubmitChunks("/clear"),settleMs:250})),null==(_b=(_a=this.props).onClearContextOptimistic)||_b.call(_a)),isMobile&&!isPad||!this.terminal||this.terminal.focus()}),__publicField(this,"handleUltraplanSend",()=>{const trimmed=this.state.ultraplanPrompt.trim();if(!trimmed&&0===this.state.ultraplanFiles.length)return;const filePaths=this.state.ultraplanFiles.map(f=>`"${f.path}"`).join(" "),userInput=filePaths?trimmed?`${filePaths} ${trimmed}`:filePaths:trimmed,variant=this.state.ultraplanVariant;let assembled;if("string"==typeof variant&&variant.startsWith("custom:")){const id=variant.slice(7),item=this.state.customUltraplanExperts.find(e=>e.id===id);if(!item)return;assembled=buildLocalUltraplan(userInput,"custom",0,item.content)}else assembled=buildLocalUltraplan(userInput,variant);assembled&&(this.setState({ultraplanOpen:!1,ultraplanPrompt:"",ultraplanVariant:"codeExpert",ultraplanFiles:[]}),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"input-sequential",chunks:buildBracketPasteSubmitChunks(assembled),settleMs:250})),isMobile&&!isPad||!this.terminal||this.terminal.focus())}),__publicField(this,"openCustomUltraplanEditor",item=>{this.setState(prev=>({customUltraplanEditOpen:!0,customUltraplanEditing:item||null,_ultraplanWasOpenBeforeEdit:prev.ultraplanOpen,ultraplanOpen:!1}))}),__publicField(this,"closeCustomUltraplanEditor",()=>{this.setState(prev=>({customUltraplanEditOpen:!1,customUltraplanEditing:null,ultraplanOpen:!!prev._ultraplanWasOpenBeforeEdit,_ultraplanWasOpenBeforeEdit:!1}))}),__publicField(this,"persistCustomUltraplanExperts",experts=>{this.setState({customUltraplanExperts:experts}),this.props.onUpdatePreferences&&this.props.onUpdatePreferences({customUltraplanExperts:experts})}),__publicField(this,"saveCustomUltraplanExpert",item=>{const existing=this.state.customUltraplanExperts,next=existing.findIndex(e=>e.id===item.id)>=0?existing.map(e=>e.id===item.id?item:e):[...existing,item];this.persistCustomUltraplanExperts(next),this.closeCustomUltraplanEditor()}),__publicField(this,"deleteCustomUltraplanExpert",id=>{const next=this.state.customUltraplanExperts.filter(e=>e.id!==id);this.persistCustomUltraplanExperts(next),this.state.ultraplanVariant==="custom:"+id&&this.setState({ultraplanVariant:"codeExpert"}),this.closeCustomUltraplanEditor()}),__publicField(this,"handleUltraplanUpload",async()=>{const input=document.createElement("input");input.type="file",input.onchange=async e=>{var _a;const file=null==(_a=e.target.files)?void 0:_a[0];if(file)try{const path=await uploadFileAndGetPath(file);this.setState(prev=>({ultraplanFiles:[...prev.ultraplanFiles,{name:file.name,path:path}]}))}catch(err){console.error("Ultraplan upload failed:",err),staticMethods.error((null==err?void 0:err.message)||"Upload failed")}},input.click()}),__publicField(this,"handleUltraplanPaste",async e=>{var _a;const items=null==(_a=e.clipboardData)?void 0:_a.items;if(items)for(const item of items)if(item.type.startsWith("image/")){e.preventDefault();const file=item.getAsFile();if(!file)return;try{const path=await uploadFileAndGetPath(file),name=file.name||`paste-${Date.now()}.png`;this.setState(prev=>({ultraplanFiles:[...prev.ultraplanFiles,{name:name,path:path}]}))}catch(err){console.error("Ultraplan paste upload failed:",err),staticMethods.error((null==err?void 0:err.message)||"Upload failed")}return}}),__publicField(this,"handleUltraplanRemoveFile",idx=>{this.setState(prev=>({ultraplanFiles:prev.ultraplanFiles.filter((_,i)=>i!==idx)}))}),__publicField(this,"handleEnableAgentTeam",()=>{if(!this.state.agentTeamEnabling){if(this.setState({agentTeamEnabling:!0}),this.ws&&this.ws.readyState===WebSocket.OPEN){const settingsPath=`${getClaudeConfigDir()}/settings.json`,prompt=`Add "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" to the env object in ${settingsPath}. If the env key does not exist, create it. Preserve all existing content. Only modify this one field. If ${settingsPath} does not exist, instead add the line: export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 to the user's shell profile (~/.zshrc or ~/.bashrc).`;this.ws.send(JSON.stringify({type:"input",data:prompt+"\r"})),staticMethods.success("需要重启 Claude Code 才能生效")}isMobile&&!isPad||!this.terminal||this.terminal.focus()}}),this.containerRef=React__default.createRef(),this.fileInputRef=React__default.createRef(),this.terminal=null,this.fitAddon=null,this._unsubWsHandler=null,this._unsubWsState=null,this.resizeObserver=null,this.state={terminalFocused:!1,agentTeamEnabled:!1,agentTeamPopoverOpen:!1,ultraplanOpen:!1,ultraplanVariant:"codeExpert",ultraplanPrompt:"",ultraplanFiles:[],customUltraplanExperts:[],customUltraplanEditOpen:!1,customUltraplanEditing:null,presetModalVisible:!1,presetItems:[],presetSelected:new Set,presetAddVisible:!1,presetAddText:"",presetAddName:"",presetEditId:null,lightbox:null,ultraplanLightbox:null,ultraplanConfirming:!1,scratchOpen:readScratchOpen(),scratchHeight:readScratchHeight(),isDraggingScratch:!1,scratchFocused:!1,scratchTabs:(()=>{const t2=function(){try{const raw=localStorage.getItem("cc-viewer-scratch-tabs");if(!raw)return[];const arr=JSON.parse(raw);if(!Array.isArray(arr))return[];const out=[];for(const t2 of arr)if(t2&&"string"==typeof t2.id&&SCRATCH_TAB_ID_RE.test(t2.id)&&(out.push({id:t2.id}),out.length>=8))break;return out}catch{return[]}}();return t2.length>0?t2:[{id:genScratchTabId()}]})(),activeScratchTabId:"",scratchShellBasename:""},this.state.activeScratchTabId=function(tabs){var _a;try{const v=localStorage.getItem("cc-viewer-scratch-active-tab");if(v&&tabs.some(t2=>t2.id===v))return v}catch{}return(null==(_a=tabs[0])?void 0:_a.id)??""}(this.state.scratchTabs),this._scratchWrapRef=React__default.createRef(),this._scratchRefs=new Map,this._scratchDragging=!1,this._scratchDragLastH=null,this._scratchPointerId=null}get ws(){const ctx=this.context;return ctx&&"function"==typeof ctx.send?{get readyState(){return ctx.isOpen&&ctx.isOpen()?WebSocket.OPEN:WebSocket.CLOSED},send:s=>{let obj;try{obj=JSON.parse(s)}catch{return!1}return ctx.send(obj)}}:null}_getScratchRef(id){let ref=this._scratchRefs.get(id);return ref||(ref=React__default.createRef(),this._scratchRefs.set(id,ref)),ref}componentDidMount(){var _a,_b;if(this.initTerminal(),this.context&&this.context.addMessageHandler&&(this._unsubWsHandler=this.context.addMessageHandler(this._onTerminalWsMessage)),this.context&&this.context.addStateListener&&(this._unsubWsState=this.context.addStateListener(this._onTerminalWsState)),this.context&&this.context.isOpen&&this.context.isOpen()&&this.sendResize(),this.setupResizeObserver(),this.props.claudeSettings){const enabled="1"===(null==(_b=null==(_a=this.props.claudeSettings)?void 0:_a.env)?void 0:_b.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS);this.setState({agentTeamEnabled:enabled})}this._loadPresetShortcuts(),this._onFocusTerminal=()=>{var _a2,_b2;this.terminal&&(null==(_b2=null==(_a2=this.containerRef)?void 0:_a2.current)?void 0:_b2.offsetWidth)>0&&this.terminal.focus()},window.addEventListener("ccv-focus-terminal",this._onFocusTerminal),this._themeObserver=new MutationObserver(()=>{if(this.terminal){const isDark="light"!==document.documentElement.getAttribute("data-theme");this.terminal.options.theme=isDark?darkTerminalTheme:lightTerminalTheme}}),this._themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),this.state.scratchOpen&&this._applyScratchHeight(),writeScratchTabs(this.state.scratchTabs),this.state.activeScratchTabId&&writeScratchActiveTab(this.state.activeScratchTabId)}componentDidUpdate(prevProps,prevState){var _a,_b;if(prevProps.claudeSettings!==this.props.claudeSettings){const enabled="1"===(null==(_b=null==(_a=this.props.claudeSettings)?void 0:_a.env)?void 0:_b.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS);enabled!==this.state.agentTeamEnabled&&this.setState({agentTeamEnabled:enabled})}prevProps.preferences!==this.props.preferences&&this._loadPresetShortcuts(),prevState.scratchOpen!==this.state.scratchOpen&&(this.state.scratchOpen?this._applyScratchHeight():this._scratchDragging&&(document.body.style.cursor="",document.body.style.userSelect="",this._scratchDragging=!1,this._scratchDragLastH=null,this._scratchPointerId=null,this.setState({isDraggingScratch:!1})))}_loadPresetShortcuts(){const data=this.props.preferences;if(!data)return;const dismissed=Array.isArray(data.dismissedBuiltinPresets)?new Set(data.dismissedBuiltinPresets):new Set;this._dismissedBuiltinPresets=dismissed;let items=[];Array.isArray(data.presetShortcuts)&&(items=data.presetShortcuts.map((item,i)=>"string"==typeof item?{id:Date.now()+i,teamName:"",description:item}:{id:Date.now()+i,teamName:item.teamName||"",description:item.description||"",...item.builtinId?{builtinId:item.builtinId}:{},...item.modified?{modified:!0}:{}}));const existingBuiltinIds=new Set(items.filter(i=>i.builtinId).map(i=>i.builtinId));for(const bp of BUILTIN_PRESETS)dismissed.has(bp.builtinId)||existingBuiltinIds.has(bp.builtinId)||items.unshift({id:Date.now()+Math.random(),builtinId:bp.builtinId,teamName:bp.teamName,description:bp.description});const customExperts=Array.isArray(data.customUltraplanExperts)?data.customUltraplanExperts:[],current=this.state.ultraplanVariant,next={presetItems:items,customUltraplanExperts:customExperts};if("string"==typeof current&¤t.startsWith("custom:")){const id=current.slice(7);customExperts.some(e=>e.id===id)||(next.ultraplanVariant="codeExpert")}this.setState(next)}componentWillUnmount(){var _a;if(this._scratchDragging&&(document.body.style.cursor="",document.body.style.userSelect="",this._scratchDragging=!1,this._scratchDragLastH=null,this._scratchPointerId=null),(null==(_a=this.terminal)?void 0:_a.textarea)&&(this.terminal.textarea.removeEventListener("focus",this._handleTermFocus),this.terminal.textarea.removeEventListener("blur",this._handleTermBlur)),this._themeObserver&&(this._themeObserver.disconnect(),this._themeObserver=null),window.removeEventListener("ccv-focus-terminal",this._onFocusTerminal),this._stopMobileMomentum&&this._stopMobileMomentum(),this._writeQ){try{this._writeQ.drain()}catch{}this._writeQ.dispose()}if(this._wsReconnectTimer&&clearTimeout(this._wsReconnectTimer),this._unsubWsHandler){try{this._unsubWsHandler()}catch{}this._unsubWsHandler=null}if(this._unsubWsState){try{this._unsubWsState()}catch{}this._unsubWsState=null}this._resizeDebounceTimer&&clearTimeout(this._resizeDebounceTimer),this._webglRecoveryTimer&&clearTimeout(this._webglRecoveryTimer),this.resizeObserver&&this.resizeObserver.disconnect(),this.webglAddon&&(this.webglAddon.dispose(),this.webglAddon=null),this.terminal&&(this.terminal.textarea&&this.terminal.textarea.removeEventListener("paste",this._handlePaste,!0),this.terminal.dispose())}initTerminal(){const isDark="light"!==document.documentElement.getAttribute("data-theme");this.terminal=new Dl({cursorBlink:!1,cursorStyle:"bar",cursorWidth:1,cursorInactiveStyle:"none",fontSize:isMobile&&!isPad?11:13,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:isDark?darkTerminalTheme:lightTerminalTheme,allowProposedApi:!0,scrollback:isPad?3e3:isIOS?200:isMobile?1e3:3e3,smoothScrollDuration:0,scrollOnUserInput:!0}),this.fitAddon=new o,this.terminal.loadAddon(this.fitAddon),this.terminal.loadAddon(new L);const unicode11=new Ke;this.terminal.loadAddon(unicode11),this.terminal.unicode.activeVersion="11",this.terminal.open(this.containerRef.current),this._handleTermFocus=()=>this.setState({terminalFocused:!0}),this._handleTermBlur=()=>this.setState({terminalFocused:!1});const termTextarea=this.terminal.textarea;termTextarea&&(termTextarea.addEventListener("focus",this._handleTermFocus),termTextarea.addEventListener("blur",this._handleTermBlur)),isIOS||this._loadWebglAddon(!1),this._writeQ=new TerminalWriteQueue(()=>this.terminal),isMobile&&!isPad?requestAnimationFrame(()=>{this._mobileFixedResize()}):requestAnimationFrame(()=>{this.fitAddon.fit(),this.terminal.focus()}),this.terminal.attachCustomKeyEventHandler(e=>{var _a,_b,_c,_d,_e,_f;if("keydown"===e.type&&"Enter"===e.key&&e.shiftKey)return e.preventDefault(),e.stopPropagation(),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"input",data:"\r"})),!1;if("keydown"===e.type&&"Enter"===e.key&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){const pending=this.props.pendingImages,inAlternateScreen="alternate"===(null==(_c=null==(_b=null==(_a=this.terminal)?void 0:_a.buffer)?void 0:_b.active)?void 0:_c.type);if((null==pending?void 0:pending.length)>0&&!inAlternateScreen&&(null==(_d=this.ws)?void 0:_d.readyState)===WebSocket.OPEN){const paths=pending.map(img=>`'${img.path.replace(/'/g,"'\\''")}'`).join(" ");return this.ws.send(JSON.stringify({type:"input",data:paths+" "})),null==(_f=(_e=this.props).onClearPendingImages)||_f.call(_e),!1}}return!0}),this.terminal.attachCustomWheelEventHandler(ev=>{var _a,_b,_c,_d,_e;if("alternate"!==(null==(_c=null==(_b=null==(_a=this.terminal)?void 0:_a.buffer)?void 0:_b.active)?void 0:_c.type))return!0;const scroller=null==(_e=(_d=this.props).getChatScroller)?void 0:_e.call(_d);if(scroller){const px=1===ev.deltaMode?16*ev.deltaY:2===ev.deltaMode?ev.deltaY*(scroller.clientHeight||0):ev.deltaY;scroller.scrollTop+=px}return ev.preventDefault(),!1}),this.terminal.onData(data=>{this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"input",data:data}))}),this.terminal.textarea&&this.terminal.textarea.addEventListener("paste",this._handlePaste,!0),isMobile&&this._setupMobileTouchScroll()}_setupMobileTouchScroll(){var _a;const screen=null==(_a=this.containerRef.current)?void 0:_a.querySelector(".xterm-screen");if(!screen)return;const term=this.terminal,getLineHeight=()=>{var _a2,_b,_c,_d;const cellDims=null==(_d=null==(_c=null==(_b=null==(_a2=term._core)?void 0:_a2._renderService)?void 0:_b.dimensions)?void 0:_c.css)?void 0:_d.cell;return(null==cellDims?void 0:cellDims.height)||15};let lastY=0,lastTime=0,momentumRaf=null,pixelAccum=0,pendingDy=0,scrollRaf=null,velocitySamples=[];const stopMomentum=()=>{momentumRaf&&(cancelAnimationFrame(momentumRaf),momentumRaf=null),scrollRaf&&(cancelAnimationFrame(scrollRaf),scrollRaf=null),pendingDy=0,pixelAccum=0},flushScroll=()=>{if(scrollRaf=null,0===pendingDy)return;pixelAccum+=pendingDy,pendingDy=0;const lh=getLineHeight(),lines=Math.trunc(pixelAccum/lh);0!==lines&&(term.scrollLines(lines),pixelAccum-=lines*lh)};screen.addEventListener("touchstart",e=>{stopMomentum(),1===e.touches.length&&(lastY=e.touches[0].clientY,lastTime=performance.now(),velocitySamples=[])},{passive:!0}),screen.addEventListener("touchmove",e=>{if(1!==e.touches.length)return;const y=e.touches[0].clientY,now=performance.now(),dt=now-lastTime,dy=lastY-y;if(dt>0){const v=dy/dt*16;for(velocitySamples.push({v:v,t:now});velocitySamples.length>0&&now-velocitySamples[0].t>100;)velocitySamples.shift()}pendingDy+=dy,scrollRaf||(scrollRaf=requestAnimationFrame(flushScroll)),lastY=y,lastTime=now},{passive:!0}),screen.addEventListener("touchend",()=>{if(scrollRaf&&(cancelAnimationFrame(scrollRaf),scrollRaf=null),0!==pendingDy){pixelAccum+=pendingDy,pendingDy=0;const lh=getLineHeight(),lines=Math.trunc(pixelAccum/lh);0!==lines&&term.scrollLines(lines),pixelAccum=0}let velocity=0;if(velocitySamples.length>=2){let totalWeight=0,weightedV=0;const latest=velocitySamples[velocitySamples.length-1].t;for(const s of velocitySamples){const w=Math.max(0,1-(latest-s.t)/100);weightedV+=s.v*w,totalWeight+=w}velocity=totalWeight>0?weightedV/totalWeight:0}if(velocitySamples=[],Math.abs(velocity)<.5)return;let mAccum=0;const tick=()=>{if(Math.abs(velocity)<.3){const lh2=getLineHeight(),rest=Math.round(mAccum/lh2);return 0!==rest&&term.scrollLines(rest),void(momentumRaf=null)}mAccum+=velocity;const lh=getLineHeight(),lines=Math.trunc(mAccum/lh);0!==lines&&(term.scrollLines(lines),mAccum-=lines*lh),velocity*=.95,momentumRaf=requestAnimationFrame(tick)};momentumRaf=requestAnimationFrame(tick)},{passive:!0}),this._stopMobileMomentum=stopMomentum}sendResize(){if(this.ws&&this.ws.readyState===WebSocket.OPEN&&this.terminal){const msg={type:"resize",cols:this.terminal.cols,rows:this.terminal.rows};isMobile&&(msg.mobile=!0),this.ws.send(JSON.stringify(msg))}}setupResizeObserver(){isMobile&&!isPad||(this.resizeObserver=new ResizeObserver(()=>{this._resizeDebounceTimer&&clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{if(this._resizeDebounceTimer=null,this.fitAddon&&this.containerRef.current)try{const vp=this.containerRef.current.querySelector(".xterm-viewport"),prevScrollTop=(null==vp?void 0:vp.scrollTop)??0,prevScrollHeight=(null==vp?void 0:vp.scrollHeight)??1,wasAtBottom=!vp||prevScrollTop+vp.clientHeight>=prevScrollHeight-5;if(this.fitAddon.fit(),vp)if(wasAtBottom)vp.scrollTop=vp.scrollHeight;else{const ratio=prevScrollHeight>0?prevScrollTop/prevScrollHeight:0;vp.scrollTop=ratio*vp.scrollHeight}this.sendResize()}catch{}},150)}),this.containerRef.current&&this.resizeObserver.observe(this.containerRef.current))}_loadWebglAddon(isRetry){try{this.webglAddon=new xr,this.webglAddon.onContextLoss(()=>{var _a;null==(_a=this.webglAddon)||_a.dispose(),this.webglAddon=null,isRetry||(this._webglRecoveryTimer=setTimeout(()=>{this._webglRecoveryTimer=null,this._loadWebglAddon(!0)},1e3))}),this.terminal.loadAddon(this.webglAddon)}catch{this.webglAddon=null}}_mobileFixedResize(){var _a,_b,_c,_d;if(!this.terminal)return;const cellDims=null==(_d=null==(_c=null==(_b=null==(_a=this.terminal._core)?void 0:_a._renderService)?void 0:_b.dimensions)?void 0:_c.css)?void 0:_d.cell;if(!cellDims||!cellDims.width||!cellDims.height)return void setTimeout(()=>this._mobileFixedResize(),50);const availableWidth=window.innerWidth-16,availableHeight=window.innerHeight-40-52-8,currentFontSize=this.terminal.options.fontSize,currentCharWidth=cellDims.width,targetFontSize=Math.floor(currentFontSize*availableWidth/(60*currentCharWidth)*10)/10;this.terminal.options.fontSize=targetFontSize,requestAnimationFrame(()=>{var _a2,_b2,_c2,_d2;const newCellDims=null==(_d2=null==(_c2=null==(_b2=null==(_a2=this.terminal._core)?void 0:_a2._renderService)?void 0:_b2.dimensions)?void 0:_c2.css)?void 0:_d2.cell,lineHeight=(null==newCellDims?void 0:newCellDims.height)||cellDims.height,rows=Math.max(5,Math.min(Math.floor(availableHeight/lineHeight),100));this.terminal.resize(60,rows),this.sendResize()})}_throttledWrite(data){this._writeQ.push(data)}_flushWrite(){this._writeQ.drain()}_downscaleForRetina(file){const dpr=window.devicePixelRatio||1;return dpr<=1?Promise.resolve(file):new Promise(resolve=>{const img=new Image,url=URL.createObjectURL(file);img.onload=()=>{URL.revokeObjectURL(url);const w=Math.round(img.width/dpr),h=Math.round(img.height/dpr),canvas=document.createElement("canvas");canvas.width=w,canvas.height=h;const ctx=canvas.getContext("2d");ctx?(ctx.drawImage(img,0,0,w,h),canvas.toBlob(blob=>{resolve(blob?new File([blob],file.name||"clipboard.png",{type:file.type}):file)},file.type)):resolve(file)},img.onerror=()=>{URL.revokeObjectURL(url),resolve(file)},img.src=url})}render(){const{pendingImages:pendingImages,onRemovePendingImage:onRemovePendingImage}=this.props;return jsxRuntimeExports.jsxs("div",{className:styles$j_terminalPanel,children:[jsxRuntimeExports.jsx("div",{className:`${styles$j_terminalContainer}${this.state.terminalFocused?` ${styles$j_terminalContainerFocused}`:""}`,children:jsxRuntimeExports.jsx("div",{ref:this.containerRef,className:styles$j_terminalHost})}),(null==pendingImages?void 0:pendingImages.length)>0&&jsxRuntimeExports.jsx("div",{className:styles$j_pendingFileStrip,children:pendingImages.map((img,i)=>{const fileName2=img.path.split("/").pop()||img.path,isImage=/\.(png|jpe?g|gif|svg|bmp|webp|avif|ico|icns)$/i.test(fileName2),src=apiUrl(`/api/file-raw?path=${encodeURIComponent(img.path)}`);return isImage?jsxRuntimeExports.jsxs("div",{className:styles$j_pendingImageItem,children:[jsxRuntimeExports.jsx("img",{src:src,className:styles$j_pendingImageThumb,alt:fileName2,role:"button",tabIndex:0,onClick:()=>this.setState({lightbox:{src:src,alt:fileName2}}),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.setState({lightbox:{src:src,alt:fileName2}}))}}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveImage"),onConfirm:()=>null==onRemovePendingImage?void 0:onRemovePendingImage(i),className:styles$j_pendingImageRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},img.path):jsxRuntimeExports.jsxs("span",{className:styles$j_pendingFileTag,children:[jsxRuntimeExports.jsx("span",{className:styles$j_pendingFileName,children:fileName2}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveFile"),onConfirm:()=>null==onRemovePendingImage?void 0:onRemovePendingImage(i),className:styles$j_pendingFileClose,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},img.path)})}),jsxRuntimeExports.jsx("input",{type:"file",ref:this.fileInputRef,className:styles$j_hiddenFileInput,onChange:this.handleFileUpload}),(!isMobile||isPad)&&jsxRuntimeExports.jsxs("div",{className:styles$j_terminalToolbar,children:[jsxRuntimeExports.jsxs("div",{className:styles$j_toolbarLeft,children:[this.state.agentTeamEnabled?jsxRuntimeExports.jsx(Popover,{trigger:"hover",placement:"top",open:this.state.agentTeamPopoverOpen,onOpenChange:v=>this.setState({agentTeamPopoverOpen:v}),overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-hover)",borderRadius:8,padding:4,minWidth:140},content:jsxRuntimeExports.jsxs("div",{className:styles$j_presetMenu,children:[jsxRuntimeExports.jsx("button",{className:`${styles$j_presetMenuItem} ${styles$j_presetMenuItemMuted}`,onClick:()=>{this.setState({agentTeamPopoverOpen:!1,presetModalVisible:!0})},children:t("ui.terminal.customShortcuts")}),0===this.state.presetItems.length?jsxRuntimeExports.jsx("div",{className:styles$j_popoverEmptyHint,children:"—"}):this.state.presetItems.map(item=>{const isBuiltinRaw=item.builtinId&&!item.modified,name=isBuiltinRaw?t(item.teamName):item.teamName,desc=isBuiltinRaw?t(item.description):item.description;return jsxRuntimeExports.jsx("button",{className:styles$j_presetMenuItem,onClick:()=>this.handlePresetSend(desc),title:desc,children:name||desc},item.id)})]}),children:jsxRuntimeExports.jsxs("button",{className:styles$j_toolbarBtn,title:t("ui.terminal.agentTeam"),children:[jsxRuntimeExports.jsx(AgentTeamIcon,{}),jsxRuntimeExports.jsx("span",{children:t("ui.terminal.agentTeam")})]})}):jsxRuntimeExports.jsx(Popover,{trigger:"click",placement:"top",overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-hover)",borderRadius:8,padding:"12px 16px",maxWidth:360},content:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:styles$j_agentTeamDisabledTip,children:tc("ui.terminal.agentTeamDisabledTip")}),jsxRuntimeExports.jsx(Button,{type:"primary",size:"small",loading:this.state.agentTeamEnabling,disabled:this.state.agentTeamEnabling,onClick:this.handleEnableAgentTeam,children:this.state.agentTeamEnabling?t("ui.terminal.agentTeamEnabling"):t("ui.terminal.agentTeamEnable")})]}),children:jsxRuntimeExports.jsxs("button",{className:`${styles$j_toolbarBtn} ${styles$j_toolbarBtnDisabled}`,title:t("ui.terminal.agentTeam"),children:[jsxRuntimeExports.jsx(AgentTeamIcon,{}),jsxRuntimeExports.jsx("span",{children:t("ui.terminal.agentTeam")})]})}),this.state.agentTeamEnabled?jsxRuntimeExports.jsx(Popover,{trigger:"click",placement:"top",open:this.state.ultraplanOpen,onOpenChange:v=>{!v&&(this.state.lightbox||this.state.ultraplanLightbox||this.state.ultraplanConfirming)||v||this.setState({ultraplanOpen:!1})},overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-hover)",borderRadius:8,padding:0,width:420},content:jsxRuntimeExports.jsxs("div",{className:styles$j_ultraplanPanel,children:[jsxRuntimeExports.jsxs("div",{className:styles$j_ultraplanHeader,children:[jsxRuntimeExports.jsxs("span",{className:styles$j_ultraplanHeaderTitle,children:[t("ui.ultraplan.title"),jsxRuntimeExports.jsx(ConceptHelp,{doc:"UltraPlan",zIndex:1100})]}),jsxRuntimeExports.jsx("button",{type:"button",className:styles$j_ultraplanCloseBtn,onClick:()=>this.setState({ultraplanOpen:!1}),children:jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[jsxRuntimeExports.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntimeExports.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),jsxRuntimeExports.jsxs("div",{className:styles$j_ultraplanVariantRow,children:[jsxRuntimeExports.jsxs("button",{className:`${styles$j_ultraplanRoleBtn} ${"codeExpert"===this.state.ultraplanVariant?styles$j_ultraplanRoleBtnActive:""}`,onClick:()=>this.setState({ultraplanVariant:"codeExpert"}),children:[jsxRuntimeExports.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("polyline",{points:"16 18 22 12 16 6"}),jsxRuntimeExports.jsx("polyline",{points:"8 6 2 12 8 18"})]}),t("ui.ultraplan.roleCodeExpert")]}),jsxRuntimeExports.jsxs("button",{className:`${styles$j_ultraplanRoleBtn} ${"researchExpert"===this.state.ultraplanVariant?styles$j_ultraplanRoleBtnActive:""}`,onClick:()=>this.setState({ultraplanVariant:"researchExpert"}),children:[jsxRuntimeExports.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("circle",{cx:"11",cy:"11",r:"8"}),jsxRuntimeExports.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),t("ui.ultraplan.roleResearchExpert")]}),this.state.customUltraplanExperts.map(item=>{const vkey="custom:"+item.id;return jsxRuntimeExports.jsxs("span",{className:styles$j_ultraplanCustomWrap,children:[jsxRuntimeExports.jsxs("button",{className:`${styles$j_ultraplanRoleBtn} ${this.state.ultraplanVariant===vkey?styles$j_ultraplanRoleBtnActive:""}`,onClick:()=>this.setState({ultraplanVariant:vkey}),title:item.title,children:[jsxRuntimeExports.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("path",{d:"M12 2l2.4 7.2L22 12l-7.6 2.8L12 22l-2.4-7.2L2 12l7.6-2.8z"})}),jsxRuntimeExports.jsx("span",{className:styles$j_ultraplanCustomTitle,children:item.title})]}),jsxRuntimeExports.jsx("span",{className:styles$j_ultraplanEditPencil,onClick:e=>{e.stopPropagation(),this.openCustomUltraplanEditor(item)},title:t("ui.ultraplan.customEditTitle"),children:jsxRuntimeExports.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M12 20h9"}),jsxRuntimeExports.jsx("path",{d:"M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z"})]})})]},item.id)}),jsxRuntimeExports.jsx("button",{type:"button",className:styles$j_ultraplanAddExpertBtn,onClick:()=>this.openCustomUltraplanEditor(null),title:t("ui.ultraplan.customAdd"),"aria-label":t("ui.ultraplan.customAdd"),children:jsxRuntimeExports.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:jsxRuntimeExports.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),this.state.ultraplanFiles.length>0&&jsxRuntimeExports.jsx("div",{className:styles$j_ultraplanFileList,children:this.state.ultraplanFiles.map((f,i)=>{const isImage=/\.(png|jpe?g|gif|svg|bmp|webp|avif|ico|icns)$/i.test(f.name),src=apiUrl(`/api/file-raw?path=${encodeURIComponent(f.path)}`);return isImage?jsxRuntimeExports.jsxs("div",{className:styles$j_ultraplanImageItem,title:f.name,children:[jsxRuntimeExports.jsx("img",{src:src,className:styles$j_ultraplanImageThumb,alt:f.name,role:"button",tabIndex:0,onClick:e=>{e.stopPropagation(),this.setState({ultraplanLightbox:{src:src,alt:f.name}})},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.setState({ultraplanLightbox:{src:src,alt:f.name}}))}}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveImage"),onConfirm:()=>this.handleUltraplanRemoveFile(i),onPopupOpenChange:open=>this.setState({ultraplanConfirming:open}),className:styles$j_ultraplanImageRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},i):jsxRuntimeExports.jsxs("span",{className:styles$j_ultraplanFileChip,title:f.name,children:[jsxRuntimeExports.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[jsxRuntimeExports.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),jsxRuntimeExports.jsx("polyline",{points:"14 2 14 8 20 8"})]}),jsxRuntimeExports.jsx("span",{className:styles$j_ultraplanFileName,children:f.name}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{tag:"span",title:t("ui.chatInput.confirmRemoveFile"),onConfirm:()=>this.handleUltraplanRemoveFile(i),onPopupOpenChange:open=>this.setState({ultraplanConfirming:open}),className:styles$j_ultraplanFileRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},i)})}),jsxRuntimeExports.jsx("textarea",{className:styles$j_ultraplanTextarea,value:this.state.ultraplanPrompt,onChange:e=>this.setState({ultraplanPrompt:e.target.value}),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(this.state.ultraplanPrompt.trim()||this.state.ultraplanFiles.length>0)&&(e.preventDefault(),this.handleUltraplanSend())},onPaste:this.handleUltraplanPaste,placeholder:t("ui.ultraplan.placeholder"),rows:5,autoFocus:!0}),jsxRuntimeExports.jsxs("div",{className:styles$j_ultraplanFooter,children:[jsxRuntimeExports.jsx("button",{className:styles$j_ultraplanSendBtn,disabled:!this.state.ultraplanPrompt.trim()&&0===this.state.ultraplanFiles.length,onClick:this.handleUltraplanSend,children:t("ui.ultraplan.send")}),jsxRuntimeExports.jsxs("button",{className:styles$j_ultraplanUploadBtn,onClick:this.handleUltraplanUpload,children:[jsxRuntimeExports.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),t("ui.ultraplan.upload")]})]})]}),children:jsxRuntimeExports.jsxs("button",{className:styles$j_toolbarBtn,onClick:()=>this.setState({ultraplanOpen:!0}),title:t("ui.ultraplan"),children:[jsxRuntimeExports.jsx(UltraplanIcon,{}),jsxRuntimeExports.jsx("span",{children:"UltraPlan"})]})}):jsxRuntimeExports.jsx(Popover,{trigger:"click",placement:"top",overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-hover)",borderRadius:8,padding:"12px 16px",maxWidth:360},content:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:styles$j_agentTeamDisabledTip,children:t("ui.ultraplan.agentTeamRequired")}),jsxRuntimeExports.jsx(Button,{type:"primary",size:"small",loading:this.state.agentTeamEnabling,disabled:this.state.agentTeamEnabling,onClick:this.handleEnableAgentTeam,children:this.state.agentTeamEnabling?t("ui.terminal.agentTeamEnabling"):t("ui.terminal.agentTeamEnable")})]}),children:jsxRuntimeExports.jsxs("button",{className:`${styles$j_toolbarBtn} ${styles$j_toolbarBtnDisabled}`,title:t("ui.ultraplan"),children:[jsxRuntimeExports.jsx(UltraplanIcon,{}),jsxRuntimeExports.jsx("span",{children:"UltraPlan"})]})}),jsxRuntimeExports.jsx("button",{className:styles$j_toolbarBtn,onClick:()=>{var _a;return null==(_a=this.fileInputRef.current)?void 0:_a.click()},title:t("ui.terminal.upload"),children:jsxRuntimeExports.jsx(UploadIcon,{})}),(()=>{const confirmFull=t("ui.chatInput.clearContextConfirm"),qIdx=Math.max(confirmFull.indexOf("?"),confirmFull.indexOf("?")),confirmTitle=qIdx>0?confirmFull.slice(0,qIdx+1):confirmFull,confirmDesc=qIdx>0?confirmFull.slice(qIdx+1).trim():null;return jsxRuntimeExports.jsx(Popconfirm,{title:confirmTitle,description:confirmDesc,okText:t("ui.chatInput.clearContext"),cancelText:t("ui.common.confirmCancel"),okButtonProps:{danger:!0},placement:"top",onConfirm:this.handleClearContext,children:jsxRuntimeExports.jsx("button",{className:styles$j_toolbarBtn,title:t("ui.chatInput.clearContext"),children:jsxRuntimeExports.jsx(TrashIcon,{})})})})()]}),jsxRuntimeExports.jsx("div",{className:styles$j_ctxBarSlot,ref:this.props.setContextBarSlot}),jsxRuntimeExports.jsx("div",{className:styles$j_toolbarRight,children:jsxRuntimeExports.jsx("button",{className:`${styles$j_toolbarBtn}${this.state.scratchOpen?` ${styles$j_toolbarBtnActive}`:""}`,onClick:this.toggleScratch,"aria-pressed":this.state.scratchOpen,"aria-label":this.state.scratchOpen?t("ui.terminal.scratchTerminalClose"):t("ui.terminal.scratchTerminalOpen"),title:this.state.scratchOpen?t("ui.terminal.scratchTerminalClose"):t("ui.terminal.scratchTerminalOpen"),children:jsxRuntimeExports.jsx(ScratchTerminalIcon,{})})})]}),(!isMobile||isPad)&&this.state.scratchOpen&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:`${styles$j_scratchResizer}${this.state.isDraggingScratch?` ${styles$j_scratchResizerDragging}`:""}`,onPointerDown:this.handleScratchResizerPointerDown,onPointerMove:this.handleScratchResizerPointerMove,onPointerUp:this.handleScratchResizerPointerUp,onPointerCancel:this.handleScratchResizerPointerUp,role:"separator","aria-orientation":"horizontal","aria-label":t("ui.terminal.scratchResizer")}),jsxRuntimeExports.jsxs("div",{ref:this._scratchWrapRef,className:styles$j_scratchWrap,children:[jsxRuntimeExports.jsxs("div",{className:styles$j_scratchTabs,role:"tablist","aria-orientation":"vertical",children:[this.state.scratchTabs.map((tab,idx)=>{const isActive=tab.id===this.state.activeScratchTabId,isLast=1===this.state.scratchTabs.length,label2=(this.state.scratchShellBasename||"zsh")+(this.state.scratchTabs.length>1?` ${idx+1}`:"");return jsxRuntimeExports.jsxs("div",{role:"tab","aria-selected":isActive,tabIndex:isActive?0:-1,className:`${styles$j_scratchTab}${isActive?` ${styles$j_scratchTabActive}`:""}`,onClick:()=>this.handleScratchTabClick(tab.id),title:label2,children:[jsxRuntimeExports.jsx("span",{className:styles$j_scratchTabIcon,children:jsxRuntimeExports.jsx(ScratchTerminalIcon,{})}),jsxRuntimeExports.jsx("span",{className:styles$j_scratchTabLabel,children:label2}),!isLast&&jsxRuntimeExports.jsx("button",{className:styles$j_scratchTabClose,onClick:e=>this.handleScratchTabClose(tab.id,e),title:t("ui.terminal.scratchTabClose"),"aria-label":t("ui.terminal.scratchTabClose"),children:jsxRuntimeExports.jsx(CloseIcon,{})})]},tab.id)}),jsxRuntimeExports.jsx("button",{className:styles$j_scratchTabAdd,onClick:this.handleScratchTabAdd,disabled:this.state.scratchTabs.length>=8,title:t("ui.terminal.scratchTabAdd"),"aria-label":t("ui.terminal.scratchTabAdd"),children:jsxRuntimeExports.jsx(PlusIcon,{})})]}),jsxRuntimeExports.jsx("div",{className:`${styles$j_scratchPanes}${this.state.scratchFocused?` ${styles$j_scratchPanesFocused}`:""}`,children:this.state.scratchTabs.map(tab=>{const isActive=tab.id===this.state.activeScratchTabId;return jsxRuntimeExports.jsx("div",{className:`${styles$j_scratchPane}${isActive?` ${styles$j_scratchPaneActive}`:""}`,role:"tabpanel",children:jsxRuntimeExports.jsx(ScratchTerminal,{ref:this._getScratchRef(tab.id),id:tab.id,onFocusChange:f=>this.handleScratchTabFocusChange(tab.id,f),onShellInfo:this.handleScratchShellInfo})},tab.id)})})]})]}),isMobile&&!isPad&&jsxRuntimeExports.jsxs("div",{className:styles$j_virtualKeybar,children:[VIRTUAL_KEYS.map(k=>jsxRuntimeExports.jsx("button",{className:styles$j_virtualKey,onTouchStart:this._vkTouchStart,onTouchMove:this._vkTouchMove,onTouchEnd:e=>this._vkTouchEnd(()=>this.handleVirtualKey(k.seq),e),children:k.label},k.label)),this.state.agentTeamEnabled?this.state.presetItems.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:styles$j_vkSeparator}),this.state.presetItems.map(item=>{const isBuiltinRaw=item.builtinId&&!item.modified,name=isBuiltinRaw?t(item.teamName):item.teamName,desc=isBuiltinRaw?t(item.description):item.description;return jsxRuntimeExports.jsxs("button",{className:`${styles$j_virtualKey} ${styles$j_vkAction} ${styles$j_vkTeamPreset}`,onTouchStart:this._vkTouchStart,onTouchMove:this._vkTouchMove,onTouchEnd:e=>this._vkTouchEnd(()=>this.handlePresetSend(desc),e),title:desc,children:[jsxRuntimeExports.jsx(AgentTeamIcon,{}),jsxRuntimeExports.jsx("span",{className:styles$j_vkTeamLabel,children:name||desc})]},item.id)})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:styles$j_vkSeparator}),jsxRuntimeExports.jsxs("button",{className:`${styles$j_virtualKey} ${styles$j_vkAction} ${styles$j_vkDisabled}`,onTouchStart:this._vkTouchStart,onTouchMove:this._vkTouchMove,onTouchEnd:e=>this._vkTouchEnd(()=>this.handleEnableAgentTeam(),e),children:[jsxRuntimeExports.jsx(AgentTeamIcon,{}),jsxRuntimeExports.jsx("span",{className:styles$j_vkTeamLabel,children:t("ui.terminal.agentTeam")})]})]})]}),jsxRuntimeExports.jsxs(Modal,{title:t("ui.terminal.presetShortcuts"),open:this.state.presetModalVisible,onCancel:()=>this.setState({presetModalVisible:!1,presetSelected:new Set}),footer:null,width:800,styles:{content:{background:"var(--bg-elevated)",border:"1px solid var(--border-light)"},header:{background:"var(--bg-elevated)",borderBottom:"none"}},children:[jsxRuntimeExports.jsx("div",{className:styles$j_presetSectionHeader,children:jsxRuntimeExports.jsx("span",{className:styles$j_presetSectionTitle,children:t("ui.terminal.agentTeamCustom")})}),jsxRuntimeExports.jsx("div",{className:styles$j_presetList,onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:e=>{e.preventDefault(),e.stopPropagation()},children:0===this.state.presetItems.length?jsxRuntimeExports.jsx("div",{className:styles$j_presetListEmptyHint,children:"—"}):this.state.presetItems.map((item,idx)=>{const isBuiltinRaw=item.builtinId&&!item.modified,name=isBuiltinRaw?t(item.teamName):item.teamName,desc=isBuiltinRaw?t(item.description):item.description,isDragging=this._dragIdx===idx,isDragOver=this._dragOverIdx===idx&&this._dragIdx!==idx;return jsxRuntimeExports.jsxs("div",{className:`${styles$j_presetRow} ${isDragging?styles$j_presetRowDragging:""} ${isDragOver?styles$j_presetRowDragOver:""}`,onDragOver:e=>this.handleDragOver(idx,e),onDragLeave:e=>this.handleDragLeave(idx,e),onDrop:e=>this.handleDrop(idx,e),onDragEnd:this.handleDragEnd,children:[jsxRuntimeExports.jsx("span",{className:styles$j_dragHandle,draggable:!0,onDragStart:e=>this.handleDragStart(idx,e),children:jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 10 16",width:"10",height:"16",fill:"currentColor",children:[jsxRuntimeExports.jsx("circle",{cx:"3",cy:"3",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"7",cy:"3",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"3",cy:"8",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"7",cy:"8",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"3",cy:"13",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"7",cy:"13",r:"1.2"})]})}),jsxRuntimeExports.jsx(Checkbox,{checked:this.state.presetSelected.has(item.id),onChange:()=>this.handlePresetToggle(item.id)}),jsxRuntimeExports.jsx("span",{className:styles$j_presetName,title:name,children:name||"—"}),jsxRuntimeExports.jsx("span",{className:styles$j_presetText,title:desc,children:desc}),jsxRuntimeExports.jsx(Button,{size:"small",type:"link",onClick:()=>this.setState({presetAddVisible:!0,presetAddName:isBuiltinRaw?t(item.teamName):item.teamName,presetAddText:isBuiltinRaw?t(item.description):item.description,presetEditId:item.id}),children:t("ui.terminal.editItem")})]},item.id)})}),jsxRuntimeExports.jsxs("div",{className:styles$j_presetActions,children:[jsxRuntimeExports.jsx(Button,{size:"small",danger:!0,disabled:0===this.state.presetSelected.size,onClick:this.handlePresetDelete,children:t("ui.terminal.deleteSelected")}),jsxRuntimeExports.jsx(Button,{size:"small",onClick:()=>this.setState({presetAddVisible:!0,presetAddName:"",presetAddText:"",presetEditId:null}),children:t("ui.terminal.addItem")})]})]}),jsxRuntimeExports.jsxs(Modal,{title:this.state.presetEditId?t("ui.terminal.editItem"):t("ui.terminal.addItem"),open:this.state.presetAddVisible,onCancel:()=>this.setState({presetAddVisible:!1,presetAddName:"",presetAddText:"",presetEditId:null}),onOk:this.handlePresetAdd,okText:this.state.presetEditId?t("ui.ok"):t("ui.terminal.addItem"),cancelText:t("ui.cancel"),okButtonProps:{disabled:!this.state.presetAddText.trim()&&!this.state.presetAddName.trim()},width:"fit-content",styles:{content:{background:"var(--bg-elevated)",border:"1px solid var(--border-light)"},header:{background:"var(--bg-elevated)",borderBottom:"none"}},children:[jsxRuntimeExports.jsxs("div",{className:styles$j_presetFormField,children:[jsxRuntimeExports.jsxs("label",{className:styles$j_presetFormLabel,children:["Team ",t("ui.terminal.teamName")]}),jsxRuntimeExports.jsx("input",{className:styles$j_presetInput,placeholder:t("ui.terminal.teamNamePlaceholder"),value:this.state.presetAddName,onChange:e=>this.setState({presetAddName:e.target.value})})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("label",{className:styles$j_presetFormLabel,children:["Team ",t("ui.terminal.teamDesc")]}),jsxRuntimeExports.jsx("textarea",{className:styles$j_presetTextarea,rows:6,placeholder:t("ui.terminal.presetInputPlaceholder"),value:this.state.presetAddText,onChange:e=>this.setState({presetAddText:e.target.value}),onKeyDown:e=>{"Enter"===e.key&&e.stopPropagation()}})]})]}),jsxRuntimeExports.jsx(CustomUltraplanEditModal,{open:this.state.customUltraplanEditOpen,initial:this.state.customUltraplanEditing,onSave:this.saveCustomUltraplanExpert,onDelete:this.deleteCustomUltraplanExpert,onClose:this.closeCustomUltraplanEditor}),this.state.lightbox&&jsxRuntimeExports.jsx(ImageLightbox,{src:this.state.lightbox.src,alt:this.state.lightbox.alt,onClose:()=>this.setState({lightbox:null})}),this.state.ultraplanLightbox&&jsxRuntimeExports.jsx(ImageLightbox,{src:this.state.ultraplanLightbox.src,alt:this.state.ultraplanLightbox.alt,zIndex:1200,onClose:()=>this.setState({ultraplanLightbox:null})})]})}}__publicField(TerminalPanel,"contextType",TerminalWsContext);const EXT_COLORS={js:"#e8d44d",jsx:"#61dafb",ts:"#3178c6",tsx:"#3178c6",json:"#999",md:"#519aba",css:"#a86fd9",scss:"#cd6799",less:"#a86fd9",html:"#e34c26",htm:"#e34c26",xml:"#e34c26",py:"#3572a5",go:"#00add8",rs:"#dea584",rb:"#cc342d",java:"#b07219",c:"#555",cpp:"#f34b7d",h:"#555",sh:"#4eaa25",bash:"#4eaa25",zsh:"#4eaa25",yml:"#cb171e",yaml:"#cb171e",toml:"#999",svg:"#e34c26",png:"#a86fd9",jpg:"#a86fd9",jpeg:"#a86fd9",gif:"#a86fd9",bmp:"#a86fd9",ico:"#a86fd9",icns:"#a86fd9",webp:"#a86fd9",avif:"#a86fd9"};function getFileIcon(name,type){if("directory"===type)return jsxRuntimeExports.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"var(--color-accent-yellow)",stroke:"none",children:jsxRuntimeExports.jsx("path",{d:"M2 6c0-1.1.9-2 2-2h5l2 2h9a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6z"})});const ext=name.includes(".")?name.split(".").pop().toLowerCase():"",color=EXT_COLORS[ext]||"#888";return jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:color,strokeWidth:"1.5",children:[jsxRuntimeExports.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),jsxRuntimeExports.jsx("polyline",{points:"14 2 14 8 20 8"})]})}const styles$g_fileExplorer="_fileExplorer_11rd4_1",styles$g_header="_header_11rd4_10",styles$g_headerTitle="_headerTitle_11rd4_20",styles$g_collapseBtn="_collapseBtn_11rd4_31",styles$g_treeContainer="_treeContainer_11rd4_50",styles$g_treeItem="_treeItem_11rd4_56",styles$g_treeItemSelected="_treeItemSelected_11rd4_72",styles$g_arrow="_arrow_11rd4_76",styles$g_icon="_icon_11rd4_85",styles$g_fileName="_fileName_11rd4_95",styles$g_fileNameInput="_fileNameInput_11rd4_100",styles$g_loading="_loading_11rd4_116",styles$g_error="_error_11rd4_122",styles$g_treeItemGitIgnored="_treeItemGitIgnored_11rd4_128",styles$g_treeItemDragging="_treeItemDragging_11rd4_132",styles$g_treeItemDragOver="_treeItemDragOver_11rd4_136",styles$g_arrowIcon="_arrowIcon_11rd4_141";function isExternalFileDrag(e){return e.dataTransfer.types.includes("Files")&&!e.dataTransfer.types.includes("text/x-internal-move")}function getTopLevelEntries(items){if(!items||!items.length)return null;if("function"!=typeof items[0].webkitGetAsEntry)return null;const entries=[];for(let i=0;i<items.length;i++){if("file"!==items[i].kind)continue;const entry=items[i].webkitGetAsEntry();entry&&entries.push(entry)}return entries.length?entries:null}function readAllEntries(reader){return new Promise((resolve,reject)=>{const acc=[],readBatch=()=>{reader.readEntries(batch=>{0===batch.length?resolve(acc):(acc.push(...batch),readBatch())},reject)};readBatch()})}const SKIP_ENTRY_NAMES=new Set([".DS_Store","Thumbs.db",".localized"]);async function expandEntries(entries,depth){if(depth>32)return[];const results=[];for(const entry of entries)if(entry&&!SKIP_ENTRY_NAMES.has(entry.name))if(entry.isFile)try{const file=await new Promise((resolve,reject)=>entry.file(resolve,reject)),rel=entry.fullPath?entry.fullPath.startsWith("/")?entry.fullPath.slice(1):entry.fullPath:file.name;results.push({file:file,relPath:rel})}catch(e){console.warn("[FileExplorer] skip unreadable file",entry.name,e&&e.message)}else if(entry.isDirectory)try{const reader=entry.createReader(),children=await readAllEntries(reader),sub=await expandEntries(children,depth+1);results.push(...sub)}catch(e){console.warn("[FileExplorer] skip unreadable dir",entry.name,e&&e.message)}return results}function TreeNode({item:item,path:path,depth:depth,onFileClick:onFileClick,expandedPaths:expandedPaths,onToggleExpand:onToggleExpand,currentFile:currentFile,onFileRenamed:onFileRenamed,refreshTrigger:refreshTrigger,onHtmlPreview:onHtmlPreview,onAttachToChat:onAttachToChat,onInsertPathToChat:onInsertPathToChat,onImportFiles:onImportFiles}){const[children,setChildren]=reactExports.useState(null),[loading2,setLoading]=reactExports.useState(!1),[error2,setError]=reactExports.useState(null),[editing,setEditing]=reactExports.useState(!1),[editName,setEditName]=reactExports.useState(""),[dragging2,setDragging]=reactExports.useState(!1),[dragOver,setDragOver]=reactExports.useState(!1),inputRef=reactExports.useRef(null),submittingRef=reactExports.useRef(!1),itemRef=reactExports.useRef(null),childPath=path?`${path}/${item.name}`:item.name,expanded=expandedPaths.has(childPath),isGitIgnored=item.gitIgnored||!1,fetchChildren=reactExports.useCallback(async()=>{setLoading(!0),setError(null);try{const res=await fetch(apiUrl(`/api/files?path=${encodeURIComponent(childPath)}`));if(!res.ok)throw new Error("Failed");const data=await res.json();setChildren(data)}catch{setError("Error")}finally{setLoading(!1)}},[childPath]);reactExports.useEffect(()=>{"directory"===item.type&&expanded&&null===children&&!loading2&&fetchChildren()},[expanded]),reactExports.useEffect(()=>{refreshTrigger>0&&"directory"===item.type&&expanded&&null!==children&&fetchChildren()},[refreshTrigger]);const toggle2=reactExports.useCallback(async()=>{if("directory"!==item.type){const ext=(childPath||"").split(".").pop().toLowerCase();return"html"===ext||"htm"===ext?void(onHtmlPreview&&onHtmlPreview(childPath)):void(onFileClick&&onFileClick(childPath))}expanded||null===children&&await fetchChildren(),onToggleExpand(childPath)},[expanded,children,childPath,item,onFileClick,onToggleExpand,fetchChildren,onHtmlPreview]),isDir="directory"===item.type,isSelected=currentFile&¤tFile===childPath;reactExports.useEffect(()=>{isSelected&&itemRef.current&&requestAnimationFrame(()=>{var _a;null==(_a=itemRef.current)||_a.scrollIntoView({block:"nearest",behavior:"instant"})})},[isSelected]);const startEditing=reactExports.useCallback(()=>{setEditName(item.name),setEditing(!0),submittingRef.current=!1},[item.name]);reactExports.useEffect(()=>{if(editing&&inputRef.current){inputRef.current.focus();const dotIdx=item.name.lastIndexOf(".");dotIdx>0&&"directory"!==item.type?inputRef.current.setSelectionRange(0,dotIdx):inputRef.current.select()}},[editing,item.name,item.type]);const submitRename=reactExports.useCallback(async()=>{if(submittingRef.current)return;const trimmed=editName.trim();if(trimmed&&trimmed!==item.name){submittingRef.current=!0;try{const res=await fetch(apiUrl("/api/rename-file"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPath:childPath,newName:trimmed})}),data=await res.json();if(!res.ok)return alert(t("ui.renameFailed",{error:data.error||res.statusText})),void setEditing(!1);setEditing(!1),onFileRenamed&&onFileRenamed(childPath,data.newPath)}catch(err){alert(t("ui.renameFailed",{error:err.message})),setEditing(!1)}}else setEditing(!1)},[editName,item.name,childPath,onFileRenamed]),cancelEditing=reactExports.useCallback(()=>{setEditing(!1)},[]),handleDoubleClick=reactExports.useCallback(e=>{e.stopPropagation(),isSelected&&startEditing()},[isSelected,startEditing]),handleKeyDown=reactExports.useCallback(e=>{editing||"Enter"!==e.key&&"F2"!==e.key||!isSelected||(e.preventDefault(),e.stopPropagation(),startEditing())},[editing,isSelected,startEditing]),handleInputKeyDown=reactExports.useCallback(e=>{"Enter"===e.key?(e.preventDefault(),submitRename()):"Escape"===e.key&&(e.preventDefault(),cancelEditing()),e.stopPropagation()},[submitRename,cancelEditing]),handleClick=reactExports.useCallback(e=>{editing?e.stopPropagation():toggle2()},[editing,toggle2]),handleDragStart=reactExports.useCallback(e=>{editing?e.preventDefault():(e.dataTransfer.setData("text/plain",childPath),e.dataTransfer.setData("text/x-internal-move","1"),e.dataTransfer.effectAllowed="move",setDragging(!0))},[childPath,editing]),handleDragEnd=reactExports.useCallback(()=>{setDragging(!1)},[]),autoExpandTimer=reactExports.useRef(null),handleDragOver=reactExports.useCallback(e=>{const isExternal=isExternalFileDrag(e),isInternal=e.dataTransfer.types.includes("text/x-internal-move");isInternal&&!isDir||(isExternal||isInternal)&&(e.preventDefault(),e.dataTransfer.dropEffect=isExternal?"copy":"move",setDragOver(!0),!isDir||expanded||autoExpandTimer.current||(autoExpandTimer.current=setTimeout(()=>{onToggleExpand(childPath),autoExpandTimer.current=null},500)))},[isDir,expanded,childPath,onToggleExpand]),handleDragLeave=reactExports.useCallback(e=>{itemRef.current&&!itemRef.current.contains(e.relatedTarget)&&(setDragOver(!1),autoExpandTimer.current&&(clearTimeout(autoExpandTimer.current),autoExpandTimer.current=null))},[]),handleDrop=reactExports.useCallback(async e=>{if(e.preventDefault(),setDragOver(!1),isExternalFileDrag(e)&&(e.dataTransfer.files.length>0||e.dataTransfer.items&&e.dataTransfer.items.length>0)){e.stopPropagation();const topEntries=getTopLevelEntries(e.dataTransfer.items),flatFiles=Array.from(e.dataTransfer.files),targetDir=isDir?childPath:childPath.includes("/")?childPath.substring(0,childPath.lastIndexOf("/")):"";return void(onImportFiles&&onImportFiles({topEntries:topEntries,flatFiles:flatFiles},targetDir))}const fromPath=e.dataTransfer.getData("text/plain");if(!fromPath||!isDir)return;if(fromPath===childPath)return;if(childPath.startsWith(fromPath+"/"))return;if((fromPath.includes("/")?fromPath.substring(0,fromPath.lastIndexOf("/")):"")!==childPath)try{const res=await fetch(apiUrl("/api/move-file"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fromPath:fromPath,toDir:childPath})}),data=await res.json();if(!res.ok)return void staticMethods.error(data.error||"Move failed");onFileRenamed&&onFileRenamed(fromPath,data.newPath)}catch(err){staticMethods.error(err.message||"Move failed")}},[childPath,isDir,onFileRenamed,onImportFiles]),contextMenuItems=reactExports.useMemo(()=>isDir?[{key:"reveal",label:t("ui.contextMenu.revealInExplorer")},{key:"openTerminal",label:t("ui.contextMenu.openTerminal")},{key:"newFile",label:t("ui.contextMenu.newFile")},{key:"newDir",label:t("ui.contextMenu.newDir")},{type:"divider"},{key:"copyPath",label:t("ui.contextMenu.copyPath")},{key:"copyRelPath",label:t("ui.contextMenu.copyRelativePath")},{type:"divider"},{key:"rename",label:t("ui.contextMenu.rename")},{key:"delete",label:t("ui.contextMenu.delete"),danger:!0}]:[{key:"reveal",label:t("ui.contextMenu.revealInExplorer")},{key:"copyPath",label:t("ui.contextMenu.copyPath")},{key:"copyRelPath",label:t("ui.contextMenu.copyRelativePath")},{key:"attachToChat",label:t("ui.contextMenu.attachToChat")},{key:"insertPathToChat",label:t("ui.contextMenu.insertPathToChat")},{type:"divider"},{key:"rename",label:t("ui.contextMenu.rename")},{key:"delete",label:t("ui.contextMenu.delete"),danger:!0}],[isDir]),handleMenuClick=reactExports.useCallback(({key:key})=>{switch(key){case"reveal":fetch(apiUrl("/api/reveal-file"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:childPath})}).catch(()=>{});break;case"openTerminal":fetch(apiUrl("/api/open-terminal"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:childPath})}).catch(()=>{});break;case"copyPath":fetch(apiUrl("/api/resolve-path"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:childPath})}).then(r=>r.json()).then(data=>{data.fullPath&&navigator.clipboard.writeText(data.fullPath).then(()=>staticMethods.success(t("ui.copied"))).catch(()=>{})}).catch(()=>{});break;case"copyRelPath":navigator.clipboard.writeText(childPath).then(()=>staticMethods.success(t("ui.copied"))).catch(()=>{});break;case"attachToChat":null==onAttachToChat||onAttachToChat(childPath);break;case"insertPathToChat":null==onInsertPathToChat||onInsertPathToChat(childPath);break;case"rename":startEditing();break;case"newFile":{const inputId=`ccv-newfile-${Date.now()}`;Modal.confirm({title:t("ui.contextMenu.newFile"),content:jsxRuntimeExports.jsx(Input,{id:inputId,autoFocus:!0,placeholder:"filename.ext",style:{background:"var(--bg-container)",borderColor:"var(--border-primary)",color:"var(--text-secondary)",caretColor:"var(--text-secondary)"},onPressEnter:()=>{var _a;null==(_a=document.querySelector(".ant-modal-confirm-btns .ant-btn-primary"))||_a.click()}}),okText:t("ui.contextMenu.newFile"),onOk:()=>{const input=document.getElementById(inputId),name=((null==input?void 0:input.value)||"").trim();return name?fetch(apiUrl("/api/create-file"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dirPath:childPath,name:name})}).then(r=>{r.ok&&onFileRenamed&&onFileRenamed(null,`${childPath}/${name}`)}):Promise.reject()}});break}case"newDir":{const inputId=`ccv-newdir-${Date.now()}`;Modal.confirm({title:t("ui.contextMenu.newDir"),content:jsxRuntimeExports.jsx(Input,{id:inputId,autoFocus:!0,placeholder:"folder-name",style:{background:"var(--bg-container)",borderColor:"var(--border-primary)",color:"var(--text-secondary)",caretColor:"var(--text-secondary)"},onPressEnter:()=>{var _a;null==(_a=document.querySelector(".ant-modal-confirm-btns .ant-btn-primary"))||_a.click()}}),okText:t("ui.contextMenu.newDir"),onOk:()=>{const input=document.getElementById(inputId),name=((null==input?void 0:input.value)||"").trim();return name?fetch(apiUrl("/api/create-dir"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dirPath:childPath,name:name})}).then(r=>{r.ok&&onFileRenamed&&onFileRenamed(null,`${childPath}/${name}`)}):Promise.reject()}});break}case"delete":Modal.confirm({title:t(isDir?"ui.contextMenu.deleteDirConfirm":"ui.contextMenu.deleteConfirm",{name:item.name}),okType:"danger",okText:t("ui.contextMenu.delete"),onOk:()=>fetch(apiUrl("/api/delete-file"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:childPath})}).then(r=>{r.ok&&onFileRenamed&&onFileRenamed(childPath,null)}).catch(()=>{})})}},[childPath,item.name,isDir,startEditing,onFileRenamed,onAttachToChat,onInsertPathToChat]),treeItemDiv=jsxRuntimeExports.jsxs("div",{ref:itemRef,className:`${styles$g_treeItem}${isSelected?" "+styles$g_treeItemSelected:""}${isGitIgnored?" "+styles$g_treeItemGitIgnored:""}${dragging2?" "+styles$g_treeItemDragging:""}${dragOver?" "+styles$g_treeItemDragOver:""}`,style:{paddingLeft:8+16*depth},onClick:handleClick,onDoubleClick:handleDoubleClick,onKeyDown:handleKeyDown,tabIndex:0,draggable:!editing,onDragStart:handleDragStart,onDragEnd:handleDragEnd,onDragOver:handleDragOver,onDragLeave:handleDragLeave,onDrop:handleDrop,children:[jsxRuntimeExports.jsx("span",{className:styles$g_arrow,children:isDir?jsxRuntimeExports.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:styles$g_arrowIcon,style:{transform:expanded?"rotate(90deg)":"none"},children:jsxRuntimeExports.jsx("polyline",{points:"9 6 15 12 9 18"})}):""}),jsxRuntimeExports.jsx("span",{className:styles$g_icon,children:getFileIcon(item.name,item.type)}),editing?jsxRuntimeExports.jsx("input",{ref:inputRef,className:styles$g_fileNameInput,value:editName,onChange:e=>setEditName(e.target.value),onKeyDown:handleInputKeyDown,onBlur:submitRename,onClick:e=>e.stopPropagation()}):jsxRuntimeExports.jsx("span",{className:styles$g_fileName,children:item.name})]});return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Dropdown,{menu:{items:contextMenuItems,onClick:handleMenuClick},trigger:["contextMenu"],children:treeItemDiv}),expanded&&loading2&&jsxRuntimeExports.jsx("div",{className:styles$g_loading,style:{paddingLeft:24+16*depth},children:"..."}),expanded&&error2&&jsxRuntimeExports.jsx("div",{className:styles$g_error,style:{paddingLeft:24+16*depth},children:error2}),expanded&&children&&children.map(child=>jsxRuntimeExports.jsx(TreeNode,{item:child,path:childPath,depth:depth+1,onFileClick:onFileClick,expandedPaths:expandedPaths,onToggleExpand:onToggleExpand,currentFile:currentFile,onFileRenamed:onFileRenamed,refreshTrigger:refreshTrigger,onHtmlPreview:onHtmlPreview,onAttachToChat:onAttachToChat,onInsertPathToChat:onInsertPathToChat,onImportFiles:onImportFiles},child.name))]})}function FileExplorer({style:style,onClose:onClose,onFileClick:onFileClick,expandedPaths:expandedPaths,onToggleExpand:onToggleExpand,currentFile:currentFile,refreshTrigger:refreshTrigger,onFileRenamed:onFileRenamed,onAttachToChat:onAttachToChat,onInsertPathToChat:onInsertPathToChat}){const[items,setItems]=reactExports.useState(null),[error2,setError]=reactExports.useState(null),[htmlPreviewPath,setHtmlPreviewPath]=reactExports.useState(null),[externalDragOver,setExternalDragOver]=reactExports.useState(!1),mounted=reactExports.useRef(!0),containerRef=reactExports.useRef(null),refreshRoot=reactExports.useCallback(()=>{mounted.current&&fetch(apiUrl("/api/files?path=")).then(r=>r.ok?r.json():Promise.reject()).then(data=>{mounted.current&&setItems(data)}).catch(()=>{mounted.current&&setError("Failed to load")})},[]);reactExports.useEffect(()=>(mounted.current=!0,fetch(apiUrl("/api/files?path=")).then(r=>r.ok?r.json():Promise.reject()).then(data=>{mounted.current&&setItems(data)}).catch(()=>{mounted.current&&setError("Failed to load")}),()=>{mounted.current=!1}),[]),reactExports.useEffect(()=>{refreshTrigger>0&&refreshRoot()},[refreshTrigger]);const headerMenuItems=reactExports.useMemo(()=>[{key:"reveal",label:t("ui.contextMenu.revealInExplorer")},{key:"openTerminal",label:t("ui.contextMenu.openTerminal")},{key:"newFile",label:t("ui.contextMenu.newFile")},{key:"newDir",label:t("ui.contextMenu.newDir")},{type:"divider"},{key:"copyPath",label:t("ui.contextMenu.copyPath")},{key:"copyRelPath",label:t("ui.contextMenu.copyRelativePath")}],[]),handleHeaderMenuClick=reactExports.useCallback(({key:key})=>{switch(key){case"reveal":fetch(apiUrl("/api/open-project-dir"),{method:"POST"}).catch(()=>{});break;case"openTerminal":fetch(apiUrl("/api/open-terminal"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:""})}).catch(()=>{});break;case"newFile":{const inputId=`ccv-newfile-root-${Date.now()}`;Modal.confirm({title:t("ui.contextMenu.newFile"),content:jsxRuntimeExports.jsx(Input,{id:inputId,autoFocus:!0,placeholder:"filename.ext",style:{background:"var(--bg-container)",borderColor:"var(--border-primary)",color:"var(--text-secondary)",caretColor:"var(--text-secondary)"},onPressEnter:()=>{var _a;null==(_a=document.querySelector(".ant-modal-confirm-btns .ant-btn-primary"))||_a.click()}}),okText:t("ui.contextMenu.newFile"),onOk:()=>{const input=document.getElementById(inputId),name=((null==input?void 0:input.value)||"").trim();return name?fetch(apiUrl("/api/create-file"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dirPath:"",name:name})}).then(r=>{r.ok&&onFileRenamed&&onFileRenamed(null,name)}):Promise.reject()}});break}case"newDir":{const inputId=`ccv-newdir-root-${Date.now()}`;Modal.confirm({title:t("ui.contextMenu.newDir"),content:jsxRuntimeExports.jsx(Input,{id:inputId,autoFocus:!0,placeholder:"folder-name",style:{background:"var(--bg-container)",borderColor:"var(--border-primary)",color:"var(--text-secondary)",caretColor:"var(--text-secondary)"},onPressEnter:()=>{var _a;null==(_a=document.querySelector(".ant-modal-confirm-btns .ant-btn-primary"))||_a.click()}}),okText:t("ui.contextMenu.newDir"),onOk:()=>{const input=document.getElementById(inputId),name=((null==input?void 0:input.value)||"").trim();return name?fetch(apiUrl("/api/create-dir"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dirPath:"",name:name})}).then(r=>{r.ok&&onFileRenamed&&onFileRenamed(null,name)}):Promise.reject()}});break}case"copyPath":fetch(apiUrl("/api/resolve-path"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:""})}).then(r=>r.json()).then(data=>{data.fullPath&&navigator.clipboard.writeText(data.fullPath).then(()=>staticMethods.success(t("ui.copied"))).catch(()=>{})}).catch(()=>{});break;case"copyRelPath":navigator.clipboard.writeText(".").then(()=>staticMethods.success(t("ui.copied"))).catch(()=>{})}},[onFileRenamed]),importFiles=reactExports.useCallback(async(payload,targetDir)=>{let entries=[];const topEntries=payload&&payload.topEntries,flatFiles=payload&&payload.flatFiles,isEntryShape=Array.isArray(topEntries)||Array.isArray(flatFiles);if(isEntryShape&&topEntries&&topEntries.length>0){const hideScan=staticMethods.loading(t("ui.importScanning"),0);let scanFailed=!1;try{entries=await expandEntries(topEntries,0)}catch(e){console.warn("[FileExplorer] expandEntries failed, falling back to flat files",e),scanFailed=!0}finally{hideScan()}(scanFailed||0===entries.length)&&flatFiles&&flatFiles.length>0&&(entries=flatFiles.map(f=>({file:f,relPath:f.name})))}else isEntryShape&&flatFiles&&flatFiles.length>0?entries=flatFiles.map(f=>({file:f,relPath:f.name})):Array.isArray(payload)&&(entries=payload.map(f=>({file:f,relPath:f.name})));if(0===entries.length)return void((topEntries&&topEntries.length>0||flatFiles&&flatFiles.length>0)&&staticMethods.info(t("ui.importNoFiles")));if(entries.length>1e3){if(!(await new Promise(resolve=>{Modal.confirm({title:t("ui.importConfirmLarge",{count:entries.length}),okText:t("ui.ok"),cancelText:t("ui.cancel"),onOk:()=>resolve(!0),onCancel:()=>resolve(!1)})})))return}const total=entries.length;let successCount=0;const failures=[];let firstOkRelPath=null;const hideLoading=staticMethods.loading(t("ui.importingProgress",{total:total}),0);let idx=0;const parallel=Math.min(3,entries.length);if(await Promise.all(Array.from({length:parallel},()=>(async()=>{for(;idx<entries.length;){const myIdx=idx++,{file:file,relPath:relPath}=entries[myIdx],lastSlash=relPath.lastIndexOf("/"),subDir=lastSlash>=0?relPath.slice(0,lastSlash):"",finalDir=[targetDir,subDir].filter(Boolean).join("/"),form=new FormData;form.append("file",file);try{const res=await fetch(apiUrl(`/api/import-file?dir=${encodeURIComponent(finalDir)}`),{method:"POST",body:form}),data=await res.json();res.ok?(successCount++,firstOkRelPath||(firstOkRelPath=data.relPath||relPath)):failures.push({name:relPath,error:data.error||"Import failed"})}catch(err){failures.push({name:relPath,error:err.message||"Import failed"})}}})())),hideLoading(),0===failures.length)1===successCount?staticMethods.success(t("ui.fileImported",{name:firstOkRelPath})):staticMethods.success(t("ui.filesImported",{count:successCount}));else{const preview=failures.slice(0,3).map(f=>f.name).join(", "),more=failures.length>3?` (+${failures.length-3})`:"";successCount>0?staticMethods.warning(t("ui.importPartialFailed",{ok:successCount,failed:failures.length,names:preview+more})):staticMethods.error(t("ui.importAllFailed",{failed:failures.length,names:preview+more}))}successCount>0&&onFileRenamed&&onFileRenamed(null,firstOkRelPath)},[onFileRenamed]),dragTimerRef=reactExports.useRef(null),resetDragState=reactExports.useCallback(()=>{dragTimerRef.current&&(clearTimeout(dragTimerRef.current),dragTimerRef.current=null),setExternalDragOver(!1)},[]);reactExports.useEffect(()=>{const handler=()=>resetDragState();return document.addEventListener("drop",handler),document.addEventListener("dragend",handler),()=>{document.removeEventListener("drop",handler),document.removeEventListener("dragend",handler)}},[resetDragState]);const handleContainerDragOver=reactExports.useCallback(e=>{isExternalFileDrag(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",externalDragOver||setExternalDragOver(!0),dragTimerRef.current&&clearTimeout(dragTimerRef.current),dragTimerRef.current=setTimeout(()=>{setExternalDragOver(!1),dragTimerRef.current=null},300))},[externalDragOver]),handleContainerDrop=reactExports.useCallback(e=>{if(resetDragState(),!isExternalFileDrag(e))return;e.preventDefault(),e.stopPropagation();const topEntries=getTopLevelEntries(e.dataTransfer.items),flatFiles=Array.from(e.dataTransfer.files);(topEntries&&topEntries.length>0||flatFiles.length>0)&&importFiles({topEntries:topEntries,flatFiles:flatFiles},"")},[importFiles,resetDragState]);return jsxRuntimeExports.jsxs("div",{ref:containerRef,className:styles$g_fileExplorer,style:style,"data-file-explorer":!0,onDragOver:handleContainerDragOver,onDrop:handleContainerDrop,children:[jsxRuntimeExports.jsxs("div",{className:styles$g_header,children:[jsxRuntimeExports.jsx(Dropdown,{menu:{items:headerMenuItems,onClick:handleHeaderMenuClick},trigger:["contextMenu"],children:jsxRuntimeExports.jsxs("span",{className:styles$g_headerTitle,children:[jsxRuntimeExports.jsx(OpenFolderIcon,{apiEndpoint:apiUrl("/api/open-project-dir"),title:t("ui.openProjectDir"),size:14}),t("ui.fileExplorer")]})}),jsxRuntimeExports.jsx("button",{className:styles$g_collapseBtn,onClick:onClose,title:"Close",children:jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("polyline",{points:"11 17 6 12 11 7"}),jsxRuntimeExports.jsx("polyline",{points:"18 17 13 12 18 7"})]})})]}),jsxRuntimeExports.jsxs("div",{className:styles$g_treeContainer,children:[error2&&jsxRuntimeExports.jsx("div",{className:styles$g_error,children:error2}),!items&&!error2&&jsxRuntimeExports.jsx("div",{className:styles$g_loading,children:"Loading..."}),items&&items.map(item=>jsxRuntimeExports.jsx(TreeNode,{item:item,path:"",depth:0,onFileClick:onFileClick,expandedPaths:expandedPaths,onToggleExpand:onToggleExpand,currentFile:currentFile,onFileRenamed:onFileRenamed,refreshTrigger:refreshTrigger,onHtmlPreview:setHtmlPreviewPath,onAttachToChat:onAttachToChat,onInsertPathToChat:onInsertPathToChat,onImportFiles:importFiles},item.name))]}),htmlPreviewPath&&jsxRuntimeExports.jsx(Modal,{open:!0,onCancel:()=>setHtmlPreviewPath(null),footer:null,closable:!0,maskClosable:!0,zIndex:1100,width:"calc(100vw - 80px)",title:jsxRuntimeExports.jsx("span",{style:{color:"var(--text-primary)",fontSize:14},children:htmlPreviewPath.split("/").pop()||"Preview"}),styles:{header:{background:"var(--bg-container)",borderBottom:"1px solid var(--border-primary)",padding:"12px 20px"},body:{background:"#fff",height:"calc(100vh - 160px)",overflow:"hidden",padding:0},mask:{background:"rgba(0,0,0,0.7)"},content:{background:"var(--bg-container)",border:"1px solid var(--border-primary)",borderRadius:8,padding:0}},centered:!0,children:jsxRuntimeExports.jsx("iframe",{src:apiUrl(`/api/file-raw?path=${encodeURIComponent(htmlPreviewPath)}`),style:{width:"100%",height:"100%",border:"none"},title:htmlPreviewPath,sandbox:"allow-scripts allow-popups allow-forms"})})]})}const RE_MERMAID_FENCE=/^[ \t]*```\s*mermaid\b/m,RE_MATH_FENCE=/^[ \t]*```\s*(?:math|latex|tex|katex)\b/im,RE_BLOCK_MATH=/\$\$[\s\S]+?\$\$/,RE_DIRECTIVE=/^[ \t]*:::[A-Za-z][\w-]*\b/m;let RE_INLINE_MATH=null;try{RE_INLINE_MATH=new RegExp("(?<![\\d$\\\\])\\$([^\\s$][^$\\n]{0,200}?[^\\s$\\\\])\\$(?![\\d])")}catch{RE_INLINE_MATH=null}const styles$f_fileContentView="_fileContentView_16e92_1",styles$f_closing="_closing_16e92_20",styles$f_editorBanner="_editorBanner_16e92_35",styles$f_header="_header_16e92_52",styles$f_headerLeft="_headerLeft_16e92_62",styles$f_headerRight="_headerRight_16e92_70",styles$f_backBtn="_backBtn_16e92_77",styles$f_filePath="_filePath_16e92_98",styles$f_fileSize="_fileSize_16e92_106",styles$f_closeBtn="_closeBtn_16e92_113",styles$f_viewToggleBtn="_viewToggleBtn_16e92_133",styles$f_viewToggleActive="_viewToggleActive_16e92_161",styles$f_downloadWrap="_downloadWrap_16e92_167",styles$f_downloadMenu="_downloadMenu_16e92_172",styles$f_downloadMenuItem="_downloadMenuItem_16e92_185",styles$f_markdownPreview="_markdownPreview_16e92_211",styles$f_saveBtn="_saveBtn_16e92_293",styles$f_saveStatus="_saveStatus_16e92_329",styles$f_saveStatusSaved="_saveStatusSaved_16e92_335",styles$f_saveStatusFailed="_saveStatusFailed_16e92_339",styles$f_contentContainer="_contentContainer_16e92_343",styles$f_editorWrapper="_editorWrapper_16e92_352",styles$f_lineNumCol="_lineNumCol_16e92_360",styles$f_lineNumRow="_lineNumRow_16e92_370",styles$f_editorCol="_editorCol_16e92_380",styles$f_loading="_loading_16e92_400",styles$f_error="_error_16e92_410",MdxEditorPanel=reactExports.lazy(()=>__vitePreload(()=>import("./MdxEditorPanel-DW0ASwWk.js"),__vite__mapDeps([5,3,2,1,6,7,8])).catch(err=>handleStaleChunk("MdxEditorPanel",err,{onReload:()=>staticMethods.warning(t("ui.chunkOutdatedReloading"))})));function readMdxFeatureFlag(){try{return"undefined"==typeof localStorage||"false"!==localStorage.getItem("mdxEditorEnabled")}catch{return!0}}const LANG_MAP$1={js:javascript$2,jsx:javascript$2,ts:javascript$2,tsx:javascript$2,py:python$1,java:java$1,c:cpp$1,cpp:cpp$1,cc:cpp$1,cxx:cpp$1,h:cpp$1,hpp:cpp$1,go:go$1,rs:rust$1,php:php$1,html:xml$1,htm:xml$1,xml:xml$1,svg:xml$1,json:json$1,yml:yaml$1,yaml:yaml$1,md:markdown$1,markdown:markdown$1,css:css$1,scss:css$1,sass:css$1,less:css$1,sql:sql$1};function getLanguageExtension(filePath2){var _a;const ext=null==(_a=filePath2.split(".").pop())?void 0:_a.toLowerCase();return LANG_MAP$1[ext]?[LANG_MAP$1[ext]()]:[]}const editorTheme=EditorView.theme({"&":{backgroundColor:"var(--bg-base-alt)",color:"var(--text-primary)",height:"100%",overflow:"visible"},".cm-gutters:not(.cm-minimap-gutter)":{display:"none"},"& .cm-scroller":{position:"absolute",inset:"0",fontFamily:"'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace",fontSize:"12px",lineHeight:"1.5"},".cm-minimap-gutter":{background:"var(--bg-base-alt)",borderLeft:"1px solid var(--border-primary)"},".cm-minimap-overlay":{border:"1px solid rgba(158, 174, 235, 0.8)",background:"rgba(95, 110, 185, 0.45)",borderRadius:"2px",transition:"opacity 0.2s ease"},".cm-minimap-gutter:hover .cm-minimap-overlay":{border:"1px solid rgba(178, 194, 255, 0.95)",background:"rgba(95, 110, 225, 0.45)"},".cm-activeLine":{backgroundColor:"var(--overlay-light-faint)"},".cm-cursor":{borderLeftColor:"var(--text-primary)"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground":{backgroundColor:"var(--color-selection-bg)"},".cm-panels":{backgroundColor:"var(--bg-container)",borderBottom:"1px solid var(--border-secondary)"},".cm-panel.cm-search":{padding:"8px 12px 10px",fontSize:"13px",color:"var(--text-primary)",backgroundColor:"var(--bg-container)"},".cm-panel.cm-search input[type=text], .cm-panel.cm-search input[main]":{height:"26px",padding:"2px 11px",fontSize:"100%",color:"var(--text-primary)",backgroundColor:"var(--bg-elevated)",border:"1px solid var(--border-light)",borderRadius:"6px",outline:"none",transition:"border-color 0.2s",verticalAlign:"middle",boxSizing:"border-box"},".cm-panel.cm-search input[type=text]:focus":{borderColor:"var(--color-primary)",boxShadow:"0 0 0 2px var(--color-primary-bg-light)"},".cm-textfield":{height:"26px",padding:"2px 11px",fontSize:"100%",color:"var(--text-primary) !important",backgroundColor:"var(--bg-elevated) !important",border:"1px solid var(--border-light) !important",borderRadius:"6px",outline:"none",verticalAlign:"middle",boxSizing:"border-box"},".cm-textfield:focus":{borderColor:"var(--color-primary) !important",boxShadow:"0 0 0 2px var(--color-primary-bg-light)"},".cm-panel.cm-search input[type=checkbox]":{accentColor:"var(--color-primary)",width:"14px",height:"14px",verticalAlign:"middle",marginRight:"4px",cursor:"pointer"},".cm-panel.cm-search button":{height:"26px",padding:"2px 12px",fontSize:"100%",color:"var(--text-primary)",backgroundColor:"transparent",backgroundImage:"none !important",border:"1px solid var(--border-light)",borderRadius:"6px",cursor:"pointer",transition:"background 0.2s, border-color 0.2s, color 0.2s",verticalAlign:"middle",lineHeight:"1"},".cm-panel.cm-search button:hover":{color:"var(--text-white)",backgroundColor:"var(--overlay-light-faint)",backgroundImage:"none !important",borderColor:"var(--text-disabled)"},".cm-panel.cm-search button:active":{backgroundColor:"var(--overlay-light-medium)",backgroundImage:"none !important"},".cm-button":{height:"26px",padding:"2px 12px",fontSize:"100%",color:"var(--text-primary) !important",backgroundColor:"transparent !important",backgroundImage:"none !important",border:"1px solid var(--border-light) !important",borderRadius:"6px",cursor:"pointer",lineHeight:"1"},".cm-button:hover":{color:"var(--text-white) !important",backgroundColor:"var(--overlay-light-faint) !important",backgroundImage:"none !important",borderColor:"var(--text-disabled) !important"},".cm-panel.cm-search button[name=close]":{position:"absolute",top:"8px",right:"8px",width:"28px",height:"28px",padding:"0",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",color:"var(--text-muted)",backgroundColor:"transparent",border:"none",borderRadius:"6px"},".cm-panel.cm-search button[name=close]:hover":{color:"var(--text-primary)",backgroundColor:"var(--bg-surface)"},".cm-panel.cm-search label":{fontSize:"13px",color:"var(--text-light)",verticalAlign:"middle",cursor:"pointer"},".cm-panel.cm-search label:hover":{color:"var(--text-primary)"},".cm-panel.cm-search [name=close]":{fontSize:"16px"},".cm-searchMatch":{backgroundColor:"rgba(255, 213, 79, 0.25)",outline:"1px solid rgba(255, 213, 79, 0.4)"},".cm-searchMatch-selected":{backgroundColor:"rgba(255, 152, 0, 0.35)"}},{dark:"undefined"==typeof document||"light"!==document.documentElement.getAttribute("data-theme")}),syntaxTheme=syntaxHighlighting(HighlightStyle.define([{tag:tags.keyword,color:"var(--code-keyword, #ff7b72)"},{tag:[tags.name,tags.deleted,tags.character,tags.propertyName,tags.macroName],color:"var(--code-name, #ffa657)"},{tag:[tags.function(tags.variableName),tags.labelName],color:"var(--code-function, #d2a8ff)"},{tag:[tags.color,tags.constant(tags.name),tags.standard(tags.name)],color:"var(--code-constant, #79c0ff)"},{tag:[tags.definition(tags.name),tags.separator],color:"var(--text-primary, #e0e0e0)"},{tag:[tags.typeName,tags.className,tags.number,tags.changed,tags.annotation,tags.modifier,tags.self,tags.namespace],color:"var(--code-name, #ffa657)"},{tag:[tags.operator,tags.operatorKeyword,tags.url,tags.escape,tags.regexp,tags.link,tags.special(tags.string)],color:"var(--code-constant, #79c0ff)"},{tag:[tags.meta,tags.comment],color:"var(--code-comment, #8b949e)",fontStyle:"italic"},{tag:tags.strong,fontWeight:"bold"},{tag:tags.emphasis,fontStyle:"italic"},{tag:tags.strikethrough,textDecoration:"line-through"},{tag:tags.link,color:"var(--code-constant, #79c0ff)",textDecoration:"underline"},{tag:tags.heading,fontWeight:"bold",color:"var(--code-name, #ffa657)"},{tag:[tags.atom,tags.bool,tags.special(tags.variableName)],color:"var(--code-constant, #79c0ff)"},{tag:[tags.processingInstruction,tags.string,tags.inserted],color:"var(--code-string, #a5d6ff)"},{tag:tags.invalid,color:"var(--code-error, #f85149)"}]));function FileContentView({filePath:filePath2,onClose:onClose,editorSession:editorSession,scrollToLine:scrollToLine}){const[content2,setContent]=reactExports.useState(null),[currentContent,setCurrentContent]=reactExports.useState(null),[error2,setError]=reactExports.useState(null),[fileSize2,setFileSize]=reactExports.useState(0),[loading2,setLoading]=reactExports.useState(!0),[saveStatus2,setSaveStatus]=reactExports.useState(null),[lineCount,setLineCount]=reactExports.useState(0),[closing2,setClosing]=reactExports.useState(!1),isMdFile=/\.md$/i.test(filePath2),[viewMode,setViewMode]=reactExports.useState(isMdFile?"markdown":"text"),[downloadMenuOpen,setDownloadMenuOpen]=reactExports.useState(!1),[mdxFeatureEnabled]=reactExports.useState(readMdxFeatureFlag),[extensionDetected,setExtensionDetected]=reactExports.useState(!1),[forceMdxOverride,setForceMdxOverride]=reactExports.useState(!1),[mdxParseErrored,setMdxParseErrored]=reactExports.useState(!1),containerRef=reactExports.useRef(null),mounted=reactExports.useRef(!0),saveTimeoutRef=reactExports.useRef(null),saveRef=reactExports.useRef(null),lineNumRef=reactExports.useRef(null),editorViewRef=reactExports.useRef(null),markdownPreviewRef=reactExports.useRef(null),downloadWrapRef=reactExports.useRef(null),editorWrapperRef=reactExports.useRef(null),mdxRef=reactExports.useRef(null),mdxWrapperRef=reactExports.useRef(null),filePathRef=reactExports.useRef(filePath2);filePathRef.current=filePath2;const isDirty=null!==content2&&null!==currentContent&&content2!==currentContent,useMdxEditor=isMdFile&&mdxFeatureEnabled&&!isMobile&&(!extensionDetected||forceMdxOverride)&&!mdxParseErrored,useLegacyPreview=isMdFile&&"markdown"===viewMode&&!useMdxEditor,getCurrentText=reactExports.useCallback(()=>{var _a;if(useMdxEditor&&(null==(_a=mdxRef.current)?void 0:_a.getMarkdown))try{const fromMdx=mdxRef.current.getMarkdown()??"";if(fromMdx.length>0||0===((null==content2?void 0:content2.length)??0))return fromMdx}catch{}return(isDirty?currentContent:content2)??""},[useMdxEditor,isDirty,currentContent,content2]),{handleCopy:handleCopy,handleSaveAs:handleSaveAs,handleSaveAsImage:handleSaveAsImage}=useMarkdownExport({getText:getCurrentText,getSnapshotTarget:reactExports.useCallback(()=>markdownPreviewRef.current,[]),onDone:reactExports.useCallback(()=>setDownloadMenuOpen(!1),[])});reactExports.useEffect(()=>{if(!downloadMenuOpen)return;const onDocClick=e=>{downloadWrapRef.current&&!downloadWrapRef.current.contains(e.target)&&setDownloadMenuOpen(!1)},onKey=e=>{"Escape"===e.key&&setDownloadMenuOpen(!1)};return document.addEventListener("mousedown",onDocClick),document.addEventListener("keydown",onKey),()=>{document.removeEventListener("mousedown",onDocClick),document.removeEventListener("keydown",onKey)}},[downloadMenuOpen]);const handleClose=reactExports.useCallback(()=>{if(closing2)return;setClosing(!0);const el=containerRef.current;el?el.addEventListener("animationend",()=>onClose(),{once:!0}):onClose()},[closing2,onClose]),handleMdxChange=reactExports.useCallback(md=>{"string"==typeof md&&(setCurrentContent(md),setLineCount(md.split("\n").length))},[]),handleMdxParseError=reactExports.useCallback(()=>{mdxWrapperRef.current&&(mdxWrapperRef.current.style.display="none"),setMdxParseErrored(!0);try{staticMethods.open({key:"mdxParseFallback",type:"info",content:t("ui.mdEditor.parseFallbackToast")})}catch{}},[]),requestViewModeSwitch=reactExports.useCallback(next=>{next!==viewMode&&(isDirty?Modal.confirm({title:t("ui.mdEditor.unsavedConfirmTitle"),content:t("ui.mdEditor.unsavedConfirmContent"),okText:t("ui.mdEditor.unsavedConfirmDiscard"),cancelText:t("ui.mdEditor.unsavedConfirmKeep"),okButtonProps:{danger:!0},onOk:()=>{setCurrentContent(content2),setLineCount((content2??"").split("\n").length),setViewMode(next)}}):setViewMode(next))},[viewMode,isDirty,content2]),requestForceMdx=reactExports.useCallback(()=>{Modal.confirm({title:t("ui.mdEditor.forceGuiEdit"),content:t("ui.mdEditor.forceGuiEditConfirm"),okText:t("ui.mdEditor.forceGuiEdit"),cancelText:t("ui.mdEditor.unsavedConfirmKeep"),okButtonProps:{danger:!0},onOk:()=>{setForceMdxOverride(!0),setMdxParseErrored(!1)}})},[]),doSave=reactExports.useCallback(async()=>{var _a;if(!isDirty)return;let saveContent=currentContent;if(useMdxEditor&&(null==(_a=mdxRef.current)?void 0:_a.getMarkdown))try{const fromMdx=mdxRef.current.getMarkdown();"string"==typeof fromMdx&&(fromMdx.length>0||0===((null==content2?void 0:content2.length)??0))&&(saveContent=fromMdx)}catch{}const startFilePath=filePathRef.current;setSaveStatus("saving");try{const res=await fetch(apiUrl("/api/file-content"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:filePath2,content:saveContent,...editorSession?{editorSession:!0}:{}})});if(!res.ok){const err=await res.json().catch(()=>({}));throw new Error(err.error||`HTTP ${res.status}`)}const data=await res.json();mounted.current&&filePathRef.current===startFilePath&&(setContent(saveContent),setCurrentContent(saveContent),setFileSize(data.size),setSaveStatus("saved"),saveTimeoutRef.current&&clearTimeout(saveTimeoutRef.current),saveTimeoutRef.current=setTimeout(()=>{mounted.current&&setSaveStatus(null)},2e3))}catch(err){mounted.current&&(setSaveStatus("failed"),saveTimeoutRef.current&&clearTimeout(saveTimeoutRef.current),saveTimeoutRef.current=setTimeout(()=>{mounted.current&&setSaveStatus(null)},3e3))}},[isDirty,filePath2,currentContent,useMdxEditor,editorSession]);saveRef.current=doSave,reactExports.useEffect(()=>{if(!useMdxEditor)return;const onKeyDown=e=>{var _a;!e.metaKey&&!e.ctrlKey||e.shiftKey||e.altKey||"s"!==e.key&&"S"!==e.key||(e.preventDefault(),null==(_a=saveRef.current)||_a.call(saveRef))};return document.addEventListener("keydown",onKeyDown),()=>document.removeEventListener("keydown",onKeyDown)},[useMdxEditor]);const scrollSyncExtension=reactExports.useMemo(()=>EditorView.updateListener.of(update=>{if(update.geometryChanged||update.viewportChanged){const scroller=update.view.scrollDOM;lineNumRef.current&&(lineNumRef.current.scrollTop=scroller.scrollTop)}}),[]),onEditorCreate=reactExports.useCallback(view=>{editorViewRef.current=view;const scroller=view.scrollDOM,syncScroll=()=>{lineNumRef.current&&(lineNumRef.current.scrollTop=scroller.scrollTop)};scroller.addEventListener("scroll",syncScroll),syncScroll()},[]),loadFileContent=reactExports.useCallback(()=>{mounted.current=!0,setContent(null),setCurrentContent(null),setError(null),setLoading(!0),setLineCount(0),setExtensionDetected(!1),setForceMdxOverride(!1),setMdxParseErrored(!1),fetch(apiUrl(`/api/file-content?path=${encodeURIComponent(filePath2)}${editorSession?"&editorSession=true":""}`)).then(r=>r.ok?r.json():r.json().then(err=>{const reasonMsg=err.reason?t(`ui.fileLoadError.reason.${err.reason}`)||err.error:err.error||"Failed to load",e=new Error(reasonMsg);throw err.allowedRoots&&(e.allowedRoots=err.allowedRoots),e}).catch(parsedErr=>{if(parsedErr&&parsedErr.message)throw parsedErr;throw new Error(`HTTP ${r.status}`)})).then(data=>{if(mounted.current&&(setContent(data.content),setCurrentContent(data.content),setFileSize(data.size),setLineCount(data.content.split("\n").length),setLoading(!1),isMdFile&&mdxFeatureEnabled)){if(function(markdown2){const result={hasMermaid:!1,hasKatex:!1,hasDirective:!1,anyExtension:!1};if("string"!=typeof markdown2||0===markdown2.length)return result;try{if(RE_MERMAID_FENCE.test(markdown2)&&(result.hasMermaid=!0),(RE_MATH_FENCE.test(markdown2)||RE_BLOCK_MATH.test(markdown2))&&(result.hasKatex=!0),RE_DIRECTIVE.test(markdown2)&&(result.hasDirective=!0),!result.hasKatex&&RE_INLINE_MATH){const stripped=markdown2.replace(/```[\s\S]*?```/g,"");if(RE_INLINE_MATH.test(stripped)){const inlineMatch=stripped.match(RE_INLINE_MATH);inlineMatch&&/[a-zA-Z\\^_=<>+\-*/(){}[\]]/.test(inlineMatch[1])&&(result.hasKatex=!0)}}}catch{}return result.anyExtension=result.hasMermaid||result.hasKatex||result.hasDirective,result}(data.content).anyExtension){setExtensionDetected(!0);try{staticMethods.open({key:"mdxExtFallback",type:"info",content:t("ui.mdEditor.extensionFallbackToast")})}catch{}}}}).catch(err=>{mounted.current&&(setError(`${t("ui.fileLoadError")}: ${err.message}`),setLoading(!1))})},[filePath2,editorSession,isMdFile,mdxFeatureEnabled]);reactExports.useEffect(()=>(loadFileContent(),()=>{mounted.current=!1,saveTimeoutRef.current&&clearTimeout(saveTimeoutRef.current)}),[loadFileContent]),reactExports.useEffect(()=>{if(scrollToLine&&editorViewRef.current&&!loading2&&null!==content2){const view=editorViewRef.current,lineNum=Math.min(scrollToLine,view.state.doc.lines),line=view.state.doc.line(lineNum);view.dispatch({effects:EditorView.scrollIntoView(line.from,{y:"start"})})}},[scrollToLine,loading2,content2]);const extensions=reactExports.useMemo(()=>{const exts=[...getLanguageExtension(filePath2),syntaxTheme,scrollSyncExtension,keymap.of([{key:"Mod-s",run:()=>{var _a;return null==(_a=saveRef.current)||_a.call(saveRef),!0}}])];return exts.push(showMinimap.compute(["doc"],state=>({create:view=>({dom:document.createElement("div")}),displayText:"characters",showOverlay:"mouse-over"}))),exts},[filePath2,scrollSyncExtension]),handleChange=reactExports.useCallback(value=>{setCurrentContent(value),setLineCount(value.split("\n").length)},[]),saveStatusText="saving"===saveStatus2?t("ui.saving"):"saved"===saveStatus2?t("ui.saved"):"failed"===saveStatus2?t("ui.saveFailed"):null,lineNumbers=reactExports.useMemo(()=>{if(lineCount<=0)return null;const lines=[];for(let i=1;i<=lineCount;i++)lines.push(jsxRuntimeExports.jsx("div",{className:styles$f_lineNumRow,children:i},i));return lines},[lineCount]);return jsxRuntimeExports.jsxs("div",{ref:containerRef,className:`${styles$f_fileContentView}${closing2?` ${styles$f_closing}`:""}`,children:[editorSession&&jsxRuntimeExports.jsx("div",{className:styles$f_editorBanner,onClick:handleClose,role:"button",tabIndex:0,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||handleClose()},children:t("ui.editorSession.banner")}),jsxRuntimeExports.jsxs("div",{className:styles$f_header,children:[jsxRuntimeExports.jsxs("div",{className:styles$f_headerLeft,children:[jsxRuntimeExports.jsx("button",{className:styles$f_backBtn,onClick:handleClose,title:t("ui.backToChat"),children:jsxRuntimeExports.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("polyline",{points:"15 18 9 12 15 6"})})}),jsxRuntimeExports.jsx("span",{className:styles$f_filePath,children:filePath2}),fileSize2>0&&jsxRuntimeExports.jsx("span",{className:styles$f_fileSize,children:(bytes=fileSize2,bytes<1024?`${bytes} B`:bytes<1048576?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/1048576).toFixed(1)} MB`)})]}),jsxRuntimeExports.jsxs("div",{className:styles$f_headerRight,children:[saveStatusText&&jsxRuntimeExports.jsx("span",{className:`${styles$f_saveStatus} ${"failed"===saveStatus2?styles$f_saveStatusFailed:"saved"===saveStatus2?styles$f_saveStatusSaved:""}`,children:saveStatusText}),isMdFile&&jsxRuntimeExports.jsxs("div",{className:styles$f_downloadWrap,ref:downloadWrapRef,children:[jsxRuntimeExports.jsx("button",{className:styles$f_viewToggleBtn,onClick:()=>setDownloadMenuOpen(v=>!v),title:t("ui.saveAs"),"aria-label":t("ui.saveAs"),"aria-expanded":downloadMenuOpen,children:jsxRuntimeExports.jsx(RefIcon$i,{})}),downloadMenuOpen&&jsxRuntimeExports.jsxs("div",{className:styles$f_downloadMenu,children:[jsxRuntimeExports.jsxs("button",{className:styles$f_downloadMenuItem,onClick:handleSaveAs,children:[jsxRuntimeExports.jsx(RefIcon$i,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveAsMd")})]}),jsxRuntimeExports.jsxs("button",{className:styles$f_downloadMenuItem,onClick:handleCopy,children:[jsxRuntimeExports.jsx(RefIcon$j,{}),jsxRuntimeExports.jsx("span",{children:t("ui.copyTextContent")})]}),jsxRuntimeExports.jsxs("button",{className:styles$f_downloadMenuItem,onClick:handleSaveAsImage,disabled:"markdown"!==viewMode||useMdxEditor,title:"markdown"!==viewMode?t("ui.saveAsImageHintMd"):useMdxEditor?t("ui.mdEditor.saveAsImageDisabled"):void 0,children:[jsxRuntimeExports.jsx(RefIcon$9,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveAsImage")})]})]})]}),isMdFile&&extensionDetected&&!forceMdxOverride&&mdxFeatureEnabled&&!isMobile&&jsxRuntimeExports.jsx("button",{className:styles$f_viewToggleBtn,onClick:requestForceMdx,title:t("ui.mdEditor.forceGuiEditConfirm"),children:t("ui.mdEditor.forceGuiEdit")}),isMdFile&&!useMdxEditor&&jsxRuntimeExports.jsxs("button",{className:`${styles$f_viewToggleBtn}${"markdown"===viewMode?` ${styles$f_viewToggleActive}`:""}`,onClick:()=>requestViewModeSwitch("markdown"===viewMode?"text":"markdown"),title:t("markdown"===viewMode?"ui.viewText":"ui.viewMarkdown"),children:["markdown"===viewMode?jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("polyline",{points:"16 18 22 12 16 6"}),jsxRuntimeExports.jsx("polyline",{points:"8 6 2 12 8 18"})]}):jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M2 3h20v18H2z"}),jsxRuntimeExports.jsx("path",{d:"M7 15V9l2 3 2-3v6"}),jsxRuntimeExports.jsx("path",{d:"M17 9l-2 3h4l-2 3"})]}),t("markdown"===viewMode?"ui.viewText":"ui.viewMarkdown")]}),jsxRuntimeExports.jsxs("button",{className:styles$f_saveBtn,onClick:doSave,disabled:!isDirty||"saving"===saveStatus2,title:`${t("ui.save")} (Ctrl+S)`,children:[jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"}),jsxRuntimeExports.jsx("polyline",{points:"17 21 17 13 7 13 7 21"}),jsxRuntimeExports.jsx("polyline",{points:"7 3 7 8 15 8"})]}),t("ui.save")]}),jsxRuntimeExports.jsx("button",{className:styles$f_closeBtn,onClick:handleClose,title:t("ui.backToChat"),children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntimeExports.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),jsxRuntimeExports.jsxs("div",{className:styles$f_contentContainer,children:[error2&&jsxRuntimeExports.jsx("div",{className:styles$f_error,children:error2}),loading2&&!error2&&jsxRuntimeExports.jsx("div",{className:styles$f_loading,children:t("ui.loading")}),!loading2&&null!==content2&&"markdown"===viewMode&&isMdFile&&useMdxEditor&&jsxRuntimeExports.jsx("div",{ref:mdxWrapperRef,style:{display:"contents"},children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:styles$f_loading,children:t("ui.loading")}),children:jsxRuntimeExports.jsx(MdxEditorPanel,{ref:mdxRef,initialMarkdown:content2,onChange:handleMdxChange,onParseError:handleMdxParseError},filePath2)})}),!loading2&&null!==content2&&useLegacyPreview&&jsxRuntimeExports.jsx("div",{ref:markdownPreviewRef,className:styles$f_markdownPreview,dangerouslySetInnerHTML:{__html:renderMarkdown(isDirty?currentContent:content2)}}),!loading2&&null!==content2&&!("markdown"===viewMode&&isMdFile)&&jsxRuntimeExports.jsxs("div",{className:styles$f_editorWrapper,ref:editorWrapperRef,children:[jsxRuntimeExports.jsx("div",{className:styles$f_lineNumCol,ref:lineNumRef,children:lineNumbers}),jsxRuntimeExports.jsx("div",{className:styles$f_editorCol,children:jsxRuntimeExports.jsx(ReactCodeMirror,{value:content2,height:"100%",theme:editorTheme,extensions:extensions,onChange:handleChange,onCreateEditor:onEditorCreate,basicSetup:{lineNumbers:!1,foldGutter:!1,highlightActiveLine:!0,highlightSelectionMatches:!0,bracketMatching:!0,autocompletion:!1}})})]})]})]});var bytes}const SMIL_TAGS=new Set(["set","animate","animatemotion","animatetransform"]),FORBIDDEN_ANIM_TARGET=/^(on|href$|xlink:href$|style$)/i;const SVG_SANITIZE_CONFIG=Object.freeze({USE_PROFILES:{svg:!0},ADD_TAGS:["animate","animateMotion","animateTransform","set","mpath"],ADD_ATTR:["attributeName","attributeType","calcMode","values","keyTimes","keySplines","dur","repeatCount","repeatDur","begin","end","from","to","by","restart","min","max","additive","accumulate","path","rotate","fill","href","xlink:href","type","origin"]}),svgPurify="undefined"!=typeof window?purify(window):purify;"function"==typeof svgPurify.addHook&&svgPurify.addHook("uponSanitizeAttribute",(node,data)=>{var tagName,attrName,attrValue;tagName=node&&node.nodeName,attrName=data&&data.attrName,attrValue=data&&data.attrValue,"attributename"===String(attrName||"").toLowerCase()&&SMIL_TAGS.has((tagName||"").toLowerCase())&&FORBIDDEN_ANIM_TARGET.test(String(attrValue||"").trim())&&(data.keepAttr=!1)});const styles$e_imageViewer="_imageViewer_cvqfs_1",styles$e_header="_header_cvqfs_8",styles$e_headerLeft="_headerLeft_cvqfs_18",styles$e_headerRight="_headerRight_cvqfs_26",styles$e_backBtn="_backBtn_cvqfs_33",styles$e_closeBtn="_closeBtn_cvqfs_54",styles$e_filePath="_filePath_cvqfs_73",styles$e_fileSize="_fileSize_cvqfs_81",styles$e_toolbar="_toolbar_cvqfs_87",styles$e_toolBtn="_toolBtn_cvqfs_97",styles$e_zoomLabel="_zoomLabel_cvqfs_118",styles$e_canvasArea="_canvasArea_cvqfs_126",styles$e_dragging="_dragging_cvqfs_141",styles$e_imageWrap="_imageWrap_cvqfs_145",styles$e_svgInline="_svgInline_cvqfs_158",styles$e_statusBar="_statusBar_cvqfs_173",styles$e_loading="_loading_cvqfs_185",styles$e_error="_error_cvqfs_195";function ImageViewer({filePath:filePath2,onClose:onClose,editorSession:editorSession}){const[zoom,setZoom]=reactExports.useState(1),[offset,setOffset]=reactExports.useState({x:0,y:0}),[naturalSize,setNaturalSize]=reactExports.useState(null),[fileSize2,setFileSize]=reactExports.useState(0),[loading2,setLoading]=reactExports.useState(!0),[error2,setError]=reactExports.useState(null),[svgContent,setSvgContent]=reactExports.useState(null),canvasRef=reactExports.useRef(null),dragRef=reactExports.useRef(null),isSvg=(filePath2||"").toLowerCase().endsWith(".svg"),imgSrc=apiUrl(`/api/file-raw?path=${encodeURIComponent(filePath2)}${editorSession?"&editorSession=true":""}`);reactExports.useEffect(()=>{isSvg?(setLoading(!0),fetch(imgSrc).then(r=>r.text()).then(text=>{setSvgContent(function(text){return"function"!=typeof svgPurify.sanitize?text:svgPurify.sanitize(text,SVG_SANITIZE_CONFIG)}(text));const vb=text.match(/viewBox=["']([^"']+)["']/),aspect=(vb&&vb[1].split(/[\s,]+/).map(Number)[2]||24)/(vb&&vb[1].split(/[\s,]+/).map(Number)[3]||24);setNaturalSize({w:Math.round(200*aspect),h:200}),setLoading(!1)}).catch(()=>{setError("Failed to load SVG"),setLoading(!1)})):setSvgContent(null)},[isSvg,imgSrc]),reactExports.useEffect(()=>{fetch(imgSrc,{method:"HEAD"}).then(r=>{if(!r.ok)return void fetch(imgSrc).then(rr=>rr.json()).then(err=>{const reasonMsg=err&&err.reason?t(`ui.fileLoadError.reason.${err.reason}`)||err.error:err&&err.error||`HTTP ${r.status}`;setError(reasonMsg),setLoading(!1)}).catch(()=>{setError(`HTTP ${r.status}`),setLoading(!1)});const len=r.headers.get("content-length");len&&setFileSize(parseInt(len,10))}).catch(()=>{})},[filePath2,editorSession,imgSrc]);const fitToWindow=reactExports.useCallback(()=>{if(!naturalSize||!canvasRef.current)return;const rect=canvasRef.current.getBoundingClientRect(),scaleX=(rect.width-40)/naturalSize.w,scaleY=(rect.height-40)/naturalSize.h,fit=Math.min(scaleX,scaleY);setZoom(fit),setOffset({x:(rect.width-naturalSize.w*fit)/2,y:(rect.height-naturalSize.h*fit)/2})},[naturalSize]),handleImageLoad=reactExports.useCallback(e=>{const img=e.target;setNaturalSize({w:img.naturalWidth,h:img.naturalHeight}),setLoading(!1)},[]);reactExports.useEffect(()=>{if(!naturalSize)return;const raf=requestAnimationFrame(()=>fitToWindow());let resizeRaf;const ro=new ResizeObserver(()=>{cancelAnimationFrame(resizeRaf),resizeRaf=requestAnimationFrame(()=>fitToWindow())});return canvasRef.current&&ro.observe(canvasRef.current),()=>{cancelAnimationFrame(raf),cancelAnimationFrame(resizeRaf),ro.disconnect()}},[naturalSize]);const handleImageError=reactExports.useCallback(()=>{setError("Failed to load image"),setLoading(!1)},[]),clampZoom=z=>Math.min(10,Math.max(.1,z)),handleWheel=reactExports.useCallback(e=>{e.preventDefault();const rect=canvasRef.current.getBoundingClientRect(),mx=e.clientX-rect.left,my=e.clientY-rect.top;setZoom(prev=>{const next=clampZoom(prev*(e.deltaY<0?1.15:1/1.15)),ratio=next/prev;return setOffset(o2=>({x:mx-ratio*(mx-o2.x),y:my-ratio*(my-o2.y)})),next})},[]),handleMouseDown=reactExports.useCallback(e=>{if(0!==e.button)return;dragRef.current={startX:e.clientX,startY:e.clientY,startOx:offset.x,startOy:offset.y};const canvas=canvasRef.current;canvas.classList.add(styles$e_dragging);const onMove=ev=>{dragRef.current&&setOffset({x:dragRef.current.startOx+ev.clientX-dragRef.current.startX,y:dragRef.current.startOy+ev.clientY-dragRef.current.startY})},onUp=()=>{dragRef.current=null,canvas.classList.remove(styles$e_dragging),window.removeEventListener("mousemove",onMove),window.removeEventListener("mouseup",onUp)};window.addEventListener("mousemove",onMove),window.addEventListener("mouseup",onUp)},[offset]);return jsxRuntimeExports.jsxs("div",{className:styles$e_imageViewer,children:[jsxRuntimeExports.jsxs("div",{className:styles$e_header,children:[jsxRuntimeExports.jsxs("div",{className:styles$e_headerLeft,children:[jsxRuntimeExports.jsx("button",{className:styles$e_backBtn,onClick:onClose,title:t("ui.backToChat"),children:jsxRuntimeExports.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("polyline",{points:"15 18 9 12 15 6"})})}),jsxRuntimeExports.jsx("span",{className:styles$e_filePath,children:filePath2})]}),jsxRuntimeExports.jsxs("div",{className:styles$e_headerRight,children:[fileSize2>0&&jsxRuntimeExports.jsx("span",{className:styles$e_fileSize,children:(bytes=fileSize2,bytes<1024?bytes+" B":bytes<1048576?(bytes/1024).toFixed(1)+" KB":(bytes/1048576).toFixed(1)+" MB")}),jsxRuntimeExports.jsx("button",{className:styles$e_closeBtn,onClick:onClose,title:t("ui.backToChat"),children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntimeExports.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),jsxRuntimeExports.jsxs("div",{className:styles$e_toolbar,children:[jsxRuntimeExports.jsx("button",{className:styles$e_toolBtn,onClick:()=>{setZoom(prev=>{const next=clampZoom(prev+.25),rect=canvasRef.current.getBoundingClientRect(),cx=rect.width/2,cy=rect.height/2,ratio=next/prev;return setOffset(o2=>({x:cx-ratio*(cx-o2.x),y:cy-ratio*(cy-o2.y)})),next})},title:t("ui.imageViewer.zoomIn"),children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("circle",{cx:"11",cy:"11",r:"8"}),jsxRuntimeExports.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"}),jsxRuntimeExports.jsx("line",{x1:"11",y1:"8",x2:"11",y2:"14"}),jsxRuntimeExports.jsx("line",{x1:"8",y1:"11",x2:"14",y2:"11"})]})}),jsxRuntimeExports.jsx("button",{className:styles$e_toolBtn,onClick:()=>{setZoom(prev=>{const next=clampZoom(prev-.25),rect=canvasRef.current.getBoundingClientRect(),cx=rect.width/2,cy=rect.height/2,ratio=next/prev;return setOffset(o2=>({x:cx-ratio*(cx-o2.x),y:cy-ratio*(cy-o2.y)})),next})},title:t("ui.imageViewer.zoomOut"),children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("circle",{cx:"11",cy:"11",r:"8"}),jsxRuntimeExports.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"}),jsxRuntimeExports.jsx("line",{x1:"8",y1:"11",x2:"14",y2:"11"})]})}),jsxRuntimeExports.jsx("button",{className:styles$e_toolBtn,onClick:()=>{if(!canvasRef.current)return;const rect=canvasRef.current.getBoundingClientRect(),w=naturalSize?naturalSize.w:0,h=naturalSize?naturalSize.h:0;setZoom(1),setOffset({x:(rect.width-w)/2,y:(rect.height-h)/2})},title:t("ui.imageViewer.resetZoom"),children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M3 3h7v7H3z"}),jsxRuntimeExports.jsx("path",{d:"M14 3h7v7h-7z"}),jsxRuntimeExports.jsx("path",{d:"M3 14h7v7H3z"}),jsxRuntimeExports.jsx("path",{d:"M14 14h7v7h-7z"})]})}),jsxRuntimeExports.jsx("button",{className:styles$e_toolBtn,onClick:fitToWindow,title:t("ui.imageViewer.fitToWindow"),children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),jsxRuntimeExports.jsx("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),jsxRuntimeExports.jsx("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),jsxRuntimeExports.jsx("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]})}),jsxRuntimeExports.jsxs("span",{className:styles$e_zoomLabel,children:[Math.round(100*zoom),"%"]})]}),jsxRuntimeExports.jsxs("div",{className:styles$e_canvasArea,ref:canvasRef,onWheel:handleWheel,onMouseDown:handleMouseDown,children:[loading2&&!error2&&jsxRuntimeExports.jsx("div",{className:styles$e_loading,children:t("ui.loading")}),error2&&jsxRuntimeExports.jsx("div",{className:styles$e_error,children:error2}),jsxRuntimeExports.jsx("div",{className:styles$e_imageWrap,style:{transform:`translate(${offset.x}px, ${offset.y}px) scale(${zoom})`},children:isSvg&&svgContent?jsxRuntimeExports.jsx("div",{className:styles$e_svgInline,dangerouslySetInnerHTML:{__html:svgContent}}):jsxRuntimeExports.jsx("img",{src:imgSrc,onLoad:handleImageLoad,onError:handleImageError,alt:filePath2,draggable:!1,style:{display:loading2?"none":"block"}})})]}),naturalSize&&jsxRuntimeExports.jsxs("div",{className:styles$e_statusBar,children:[jsxRuntimeExports.jsxs("span",{children:[naturalSize.w," × ",naturalSize.h]}),jsxRuntimeExports.jsxs("span",{children:[Math.round(100*zoom),"%"]})]})]});var bytes}async function fetchAllRepos(){let repoList;try{const repoRes=await fetch(apiUrl("/api/git-repos"));if(!repoRes.ok)throw new Error("No git-repos endpoint");repoList=(await repoRes.json()).repos||[]}catch{try{const statusRes=await fetch(apiUrl("/api/git-status"));if(!statusRes.ok)return[];const data=await statusRes.json();return[{name:".",path:".",isRoot:!0,changes:data.changes||[],insertions:data.insertions||0,deletions:data.deletions||0,commits:[],hasUpstream:!1}]}catch{return[]}}return await Promise.all(repoList.map(async repo=>{const[statusData,commitsData]=await Promise.all([fetch(apiUrl(`/api/git-status?repo=${encodeURIComponent(repo.path)}`)).then(r=>r.ok?r.json():{changes:[],insertions:0,deletions:0}).catch(()=>({changes:[],insertions:0,deletions:0})),fetch(apiUrl(`/api/git-log-unpushed?repo=${encodeURIComponent(repo.path)}`)).then(r=>r.ok?r.json():{commits:[],hasUpstream:!1}).catch(()=>({commits:[],hasUpstream:!1}))]);return{...repo,changes:statusData.changes||[],insertions:statusData.insertions||0,deletions:statusData.deletions||0,commits:commitsData.commits||[],hasUpstream:!!commitsData.hasUpstream,branch:commitsData.branch||null,upstream:commitsData.upstream||null,truncated:!!commitsData.truncated,totalCount:"number"==typeof commitsData.totalCount?commitsData.totalCount:(commitsData.commits||[]).length}}))}function buildGitTree(changes){const root2={dirs:{},files:[]};for(const change of changes){if(!change.file||change.file.endsWith("/"))continue;const parts=change.file.split("/").filter(Boolean);if(0===parts.length)continue;let node=root2;for(let i=0;i<parts.length-1;i++)node.dirs[parts[i]]||(node.dirs[parts[i]]={dirs:{},files:[]}),node=node.dirs[parts[i]];node.files.push({name:parts[parts.length-1],status:change.status,fullPath:change.file})}return root2}const styles$d_gitChanges="_gitChanges_255od_1",styles$d_header="_header_255od_10",styles$d_headerTitle="_headerTitle_255od_19",styles$d_collapseBtn="_collapseBtn_255od_27",styles$d_changesContainer="_changesContainer_255od_46",styles$d_changeItem="_changeItem_255od_52",styles$d_changeItemSelected="_changeItemSelected_255od_69",styles$d_dirItem="_dirItem_255od_73",styles$d_dirArrow="_dirArrow_255od_84",styles$d_dirName="_dirName_255od_93",styles$d_status="_status_255od_98",styles$d_icon="_icon_255od_107",styles$d_fileName="_fileName_255od_116",styles$d_actions="_actions_255od_122",styles$d_loading="_loading_255od_150",styles$d_error="_error_255od_156",styles$d_empty="_empty_255od_162",styles$d_rotated90="_rotated90_255od_169",styles$d_repoHeader="_repoHeader_255od_174",styles$d_repoArrow="_repoArrow_255od_193",styles$d_commitArrow="_commitArrow_255od_194",styles$d_repoArrowExpanded="_repoArrowExpanded_255od_205",styles$d_commitArrowExpanded="_commitArrowExpanded_255od_206",styles$d_repoName="_repoName_255od_210",styles$d_repoBadge="_repoBadge_255od_217",styles$d_statBadge="_statBadge_255od_226",styles$d_statInsert="_statInsert_255od_234",styles$d_statDelete="_statDelete_255od_238",styles$d_unpushedSeparator="_unpushedSeparator_255od_243",styles$d_unpushedHeader="_unpushedHeader_255od_249",styles$d_unpushedTitle="_unpushedTitle_255od_266",styles$d_commitItem="_commitItem_255od_275",styles$d_commitHash="_commitHash_255od_292",styles$d_commitSubject="_commitSubject_255od_302",styles$d_commitMeta="_commitMeta_255od_309",styles$d_commitFileBadge="_commitFileBadge_255od_315",STATUS_COLORS={M:"#e2c08d",A:"#73c991",D:"#f14c4c",R:"#73c991",C:"#73c991",U:"#e2c08d","?":"#73c991","??":"#73c991"},STATUS_LABELS={"??":"U"};function TreeDir({name:name,node:node,depth:depth,repoPath:repoPath,onFileClick:onFileClick,onOpenFile:onOpenFile,onRestore:onRestore,selectedFile:selectedFile,selectedRepo:selectedRepo,commitHash:commitHash2,selectedCommitHash:selectedCommitHash}){const dirNames=Object.keys(node.dirs).sort(),files=[...node.files].sort((a,b)=>a.name.localeCompare(b.name));return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[name&&jsxRuntimeExports.jsxs("div",{className:styles$d_dirItem,style:{paddingLeft:8+16*depth},children:[jsxRuntimeExports.jsx("span",{className:styles$d_dirArrow,children:jsxRuntimeExports.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:styles$d_rotated90,children:jsxRuntimeExports.jsx("polyline",{points:"9 6 15 12 9 18"})})}),jsxRuntimeExports.jsx("span",{className:styles$d_icon,children:getFileIcon("","directory")}),jsxRuntimeExports.jsx("span",{className:styles$d_dirName,children:name})]}),dirNames.map(dir=>jsxRuntimeExports.jsx(TreeDir,{name:dir,node:node.dirs[dir],depth:name?depth+1:depth,repoPath:repoPath,onFileClick:onFileClick,onOpenFile:onOpenFile,onRestore:onRestore,selectedFile:selectedFile,selectedRepo:selectedRepo,commitHash:commitHash2,selectedCommitHash:selectedCommitHash},dir)),files.map(file=>{const isSelected=selectedFile===file.fullPath&&selectedRepo===repoPath&&(commitHash2||null)===(selectedCommitHash||null);return jsxRuntimeExports.jsx(Dropdown,{menu:{items:[{key:"reveal",label:t("ui.contextMenu.revealInExplorer")},{key:"copyPath",label:t("ui.contextMenu.copyPath")},{key:"copyRelPath",label:t("ui.contextMenu.copyRelativePath")}],onClick:({key:key})=>{const resolvedPath=repoPath&&"."!==repoPath?`${repoPath}/${file.fullPath}`:file.fullPath;"reveal"===key?fetch(apiUrl("/api/reveal-file"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:resolvedPath})}).catch(()=>{}):"copyPath"===key?fetch(apiUrl("/api/resolve-path"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:resolvedPath})}).then(r=>r.json()).then(data=>{data.fullPath&&navigator.clipboard.writeText(data.fullPath).then(()=>staticMethods.success(t("ui.copied"))).catch(()=>{})}).catch(()=>{}):"copyRelPath"===key&&navigator.clipboard.writeText(resolvedPath).then(()=>staticMethods.success(t("ui.copied"))).catch(()=>{})}},trigger:["contextMenu"],children:jsxRuntimeExports.jsxs("div",{className:`${styles$d_changeItem} ${isSelected?styles$d_changeItemSelected:""}`,style:{paddingLeft:8+16*(name?depth+1:depth)},onClick:()=>onFileClick&&onFileClick(repoPath,file.fullPath,commitHash2||null),children:[jsxRuntimeExports.jsx("span",{className:styles$d_icon,children:getFileIcon(file.name)}),jsxRuntimeExports.jsx("span",{className:styles$d_fileName,children:file.name}),jsxRuntimeExports.jsxs("span",{className:styles$d_actions,children:[jsxRuntimeExports.jsx("span",{title:t("ui.gitChanges.openFile"),onClick:e=>{e.stopPropagation(),onOpenFile&&onOpenFile(repoPath,file.fullPath)},children:jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),jsxRuntimeExports.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),!commitHash2&&jsxRuntimeExports.jsx("span",{title:t("ui.gitChanges.restoreFile"),onClick:e=>{e.stopPropagation(),onRestore&&onRestore(repoPath,file.fullPath,file.name)},children:jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("polyline",{points:"1 4 1 10 7 10"}),jsxRuntimeExports.jsx("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]})})]}),jsxRuntimeExports.jsx("span",{className:styles$d_status,style:{color:STATUS_COLORS[file.status]||"#888"},children:STATUS_LABELS[file.status]||file.status})]})},`${commitHash2||"wt"}::${file.fullPath}`)})]})}function CommitRow({commit:commit,repoPath:repoPath,expanded:expanded,onToggle:onToggle,onFileClick:onFileClick,onOpenFile:onOpenFile,selectedFile:selectedFile,selectedRepo:selectedRepo,selectedCommitHash:selectedCommitHash,depth:depth=0}){const fileTree=reactExports.useMemo(()=>buildGitTree(commit.files),[commit.files]),dateLabel=reactExports.useMemo(()=>{if(!commit.date)return"";try{const d=new Date(commit.date);if(Number.isNaN(d.getTime()))return"";const now=new Date;return d.toDateString()===now.toDateString()?d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"})}catch{return""}},[commit.date]);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:styles$d_commitItem,style:{paddingLeft:8+16*depth},onClick:onToggle,title:commit.subject,children:[jsxRuntimeExports.jsx("span",{className:`${styles$d_commitArrow} ${expanded?styles$d_commitArrowExpanded:""}`,children:jsxRuntimeExports.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("polyline",{points:"9 6 15 12 9 18"})})}),jsxRuntimeExports.jsx("span",{className:styles$d_commitHash,children:commit.shortHash}),jsxRuntimeExports.jsx("span",{className:styles$d_commitSubject,children:commit.subject}),commit.author&&jsxRuntimeExports.jsx("span",{className:styles$d_commitMeta,children:commit.author}),dateLabel&&jsxRuntimeExports.jsx("span",{className:styles$d_commitMeta,children:dateLabel}),jsxRuntimeExports.jsx("span",{className:styles$d_commitFileBadge,children:commit.files.length})]}),expanded&&commit.files.length>0&&jsxRuntimeExports.jsx(TreeDir,{name:"",node:fileTree,depth:depth+1,repoPath:repoPath,onFileClick:onFileClick,onOpenFile:onOpenFile,onRestore:null,selectedFile:selectedFile,selectedRepo:selectedRepo,commitHash:commit.hash,selectedCommitHash:selectedCommitHash})]})}function GitChanges({style:style,onClose:onClose,onFileClick:onFileClick,onOpenFile:onOpenFile,refreshTrigger:refreshTrigger}){const[repos,setRepos]=reactExports.useState(null),[error2,setError]=reactExports.useState(null),[loading2,setLoading]=reactExports.useState(!0),[selectedFile,setSelectedFile]=reactExports.useState(null),[selectedRepo,setSelectedRepo]=reactExports.useState(null),[selectedCommitHash,setSelectedCommitHash]=reactExports.useState(null),[collapsedRepos,setCollapsedRepos]=reactExports.useState(new Set),[collapsedUnpushed,setCollapsedUnpushed]=reactExports.useState({}),[expandedCommits,setExpandedCommits]=reactExports.useState({}),mounted=reactExports.useRef(!0),refreshAllRepos=reactExports.useCallback(()=>{fetchAllRepos().then(results=>{mounted.current&&setRepos(results)}).catch(()=>{})},[]),handleRestore=reactExports.useCallback((repoPath,filePath2,fileName2)=>{Modal.confirm({title:t("ui.gitChanges.restoreConfirm",{name:fileName2}),okType:"danger",okText:t("ui.gitChanges.restoreFile"),onOk:()=>fetch(apiUrl("/api/git-restore"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:filePath2,repo:repoPath})}).then(r=>{r.ok&&refreshAllRepos()})})},[refreshAllRepos]);reactExports.useEffect(()=>(mounted.current=!0,setLoading(!0),fetchAllRepos().then(results=>{mounted.current&&(setRepos(results),setLoading(!1))}).catch(()=>{mounted.current&&(setError("Failed to load git status"),setLoading(!1))}),()=>{mounted.current=!1}),[]),reactExports.useEffect(()=>{refreshTrigger>0&&refreshAllRepos()},[refreshTrigger]),reactExports.useEffect(()=>{var _a;if(!repos)return;const validPaths=new Set(repos.map(r=>r.path)),pruneObj=obj=>{const next={};let changed=!1;for(const[k,v]of Object.entries(obj))validPaths.has(k)?next[k]=v:changed=!0;return changed?next:obj};if(setExpandedCommits(prev=>pruneObj(prev)),setCollapsedUnpushed(prev=>pruneObj(prev)),selectedCommitHash&&selectedRepo){const repo=repos.find(r=>r.path===selectedRepo);(null==(_a=null==repo?void 0:repo.commits)?void 0:_a.some(c=>c.hash===selectedCommitHash))||(setSelectedCommitHash(null),setSelectedFile(null))}},[repos,selectedCommitHash,selectedRepo]);const isSingleRepo=!repos||repos.length<=1,totalInsertions=repos?repos.reduce((sum,r)=>sum+(r.insertions||0),0):0,totalDeletions=repos?repos.reduce((sum,r)=>sum+(r.deletions||0),0):0;return jsxRuntimeExports.jsxs("div",{className:styles$d_gitChanges,style:style,children:[jsxRuntimeExports.jsxs("div",{className:styles$d_header,children:[jsxRuntimeExports.jsxs("span",{className:styles$d_headerTitle,children:[t("ui.gitChanges"),(totalInsertions>0||totalDeletions>0)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ",jsxRuntimeExports.jsxs("span",{className:`${styles$d_statBadge} ${styles$d_statInsert}`,children:["+",totalInsertions]})," ",jsxRuntimeExports.jsxs("span",{className:`${styles$d_statBadge} ${styles$d_statDelete}`,children:["-",totalDeletions]})]})]}),jsxRuntimeExports.jsx("button",{className:styles$d_collapseBtn,onClick:onClose,title:"Close",children:jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("polyline",{points:"11 17 6 12 11 7"}),jsxRuntimeExports.jsx("polyline",{points:"18 17 13 12 18 7"})]})})]}),jsxRuntimeExports.jsxs("div",{className:styles$d_changesContainer,children:[loading2&&jsxRuntimeExports.jsx("div",{className:styles$d_loading,children:"Loading..."}),error2&&jsxRuntimeExports.jsx("div",{className:styles$d_error,children:error2}),!loading2&&!error2&&(!repos||0===repos.length)&&jsxRuntimeExports.jsx("div",{className:styles$d_empty,children:"No changes"}),!loading2&&!error2&&repos&&repos.map(repo=>{const collapsed=collapsedRepos.has(repo.path),baseDepth=isSingleRepo?0:1,handleClickFile=(rp,fp,ch)=>{setSelectedFile(fp),setSelectedRepo(rp),setSelectedCommitHash(ch||null),onFileClick&&onFileClick(rp,fp,ch||null)},showUnpushed=repo.hasUpstream&&repo.commits&&repo.commits.length>0,unpushedCollapsed=!!collapsedUnpushed[repo.path],expandedSet=expandedCommits[repo.path]||new Set,unpushedNode=showUnpushed&&!unpushedCollapsed&&jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:repo.commits.map(c=>jsxRuntimeExports.jsx(CommitRow,{commit:c,repoPath:repo.path,expanded:expandedSet.has(c.hash),onToggle:()=>{return hash=c.hash,setExpandedCommits(prev=>{const cur=prev[repo.path]?new Set(prev[repo.path]):new Set;return cur.has(hash)?cur.delete(hash):cur.add(hash),{...prev,[repo.path]:cur}});var hash},onFileClick:handleClickFile,onOpenFile:onOpenFile,selectedFile:selectedFile,selectedRepo:selectedRepo,selectedCommitHash:selectedCommitHash,depth:baseDepth+1},c.hash))}),unpushedSeparator2=showUnpushed&&jsxRuntimeExports.jsx("div",{className:styles$d_unpushedSeparator,"aria-hidden":"true"}),unpushedHeader2=showUnpushed&&jsxRuntimeExports.jsxs("div",{className:styles$d_unpushedHeader,style:{paddingLeft:8+16*baseDepth},onClick:()=>setCollapsedUnpushed(prev=>({...prev,[repo.path]:!prev[repo.path]})),title:repo.upstream?`${repo.upstream}..HEAD`:"",children:[jsxRuntimeExports.jsx("span",{className:`${styles$d_commitArrow} ${unpushedCollapsed?"":styles$d_commitArrowExpanded}`,children:jsxRuntimeExports.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("polyline",{points:"9 6 15 12 9 18"})})}),jsxRuntimeExports.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[jsxRuntimeExports.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),jsxRuntimeExports.jsx("polyline",{points:"5 12 12 5 19 12"})]}),jsxRuntimeExports.jsx("span",{className:styles$d_unpushedTitle,children:t("ui.gitChanges.unpushedCommits")}),repo.truncated&&jsxRuntimeExports.jsx("span",{className:styles$d_commitMeta,title:`total ${repo.totalCount}`,children:t("ui.gitChanges.unpushedTruncated",{count:repo.commits.length})}),jsxRuntimeExports.jsx("span",{className:styles$d_repoBadge,children:repo.truncated?`${repo.commits.length}/${repo.totalCount}`:repo.commits.length})]}),workingTreeTree=jsxRuntimeExports.jsx(TreeDir,{name:"",node:buildGitTree(repo.changes),depth:baseDepth,repoPath:repo.path,onFileClick:handleClickFile,onOpenFile:onOpenFile,onRestore:handleRestore,selectedFile:selectedFile,selectedRepo:selectedRepo,commitHash:null,selectedCommitHash:selectedCommitHash});return isSingleRepo?jsxRuntimeExports.jsxs(React__default.Fragment,{children:[workingTreeTree,unpushedSeparator2,unpushedHeader2,unpushedNode]},repo.path):jsxRuntimeExports.jsxs(React__default.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:styles$d_repoHeader,onClick:()=>setCollapsedRepos(prev=>{const next=new Set(prev);return collapsed?next.delete(repo.path):next.add(repo.path),next}),children:[jsxRuntimeExports.jsx("span",{className:`${styles$d_repoArrow} ${collapsed?"":styles$d_repoArrowExpanded}`,children:jsxRuntimeExports.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("polyline",{points:"9 6 15 12 9 18"})})}),jsxRuntimeExports.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-muted)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[jsxRuntimeExports.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),jsxRuntimeExports.jsx("circle",{cx:"18",cy:"6",r:"3"}),jsxRuntimeExports.jsx("circle",{cx:"6",cy:"18",r:"3"}),jsxRuntimeExports.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),jsxRuntimeExports.jsx("span",{className:styles$d_repoName,children:repo.name}),(repo.insertions>0||repo.deletions>0)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("span",{className:`${styles$d_statBadge} ${styles$d_statInsert}`,children:["+",repo.insertions]}),jsxRuntimeExports.jsxs("span",{className:`${styles$d_statBadge} ${styles$d_statDelete}`,children:["-",repo.deletions]})]}),jsxRuntimeExports.jsx("span",{className:styles$d_repoBadge,children:repo.changes.length})]}),!collapsed&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[workingTreeTree,unpushedSeparator2,unpushedHeader2,unpushedNode]})]},repo.path)})]})]})}const IMAGE_EXTS=new Set(["png","jpg","jpeg","gif","svg","bmp","ico","icns","webp","avif"]);function isImageFile(path){const ext=(path||"").split(".").pop().toLowerCase();return IMAGE_EXTS.has(ext)}const MUTATING_CMD_RE=/\b(rm|mkdir|mv|cp|touch|chmod|chown|ln|git\s+(checkout|reset|stash|merge|rebase|cherry-pick|restore|clean|rm)|npm\s+(install|uninstall|ci)|yarn\s+(add|remove)|pnpm\s+(add|remove|install)|pip\s+install|tar|unzip|curl\s+-[^\s]*o|wget)\b|[^>]>(?!>)|>>/;function isMutatingCommand(cmd){return MUTATING_CMD_RE.test(cmd)}const HighlightJS=getDefaultExportFromCjs(requireCore()),KEYWORDS$1=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],LITERALS$1=["true","false","null","undefined","NaN","Infinity"],TYPES$1=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ERROR_TYPES$1=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],BUILT_IN_GLOBALS$1=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],BUILT_IN_VARIABLES$1=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],BUILT_INS$1=[].concat(BUILT_IN_GLOBALS$1,TYPES$1,ERROR_TYPES$1);const IDENT_RE="[A-Za-z$_][0-9A-Za-z$_]*",KEYWORDS=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],LITERALS=["true","false","null","undefined","NaN","Infinity"],TYPES=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ERROR_TYPES=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],BUILT_IN_GLOBALS=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],BUILT_IN_VARIABLES=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],BUILT_INS=[].concat(BUILT_IN_GLOBALS,TYPES,ERROR_TYPES);var frac$1="\\.([0-9](_*[0-9])*)",hexDigits$1="[0-9a-fA-F](_*[0-9a-fA-F])*",NUMERIC$1={className:"number",variants:[{begin:`(\\b([0-9](_*[0-9])*)((${frac$1})|\\.)?|(${frac$1}))[eE][+-]?([0-9](_*[0-9])*)[fFdD]?\\b`},{begin:`\\b([0-9](_*[0-9])*)((${frac$1})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${frac$1})[fFdD]?\\b`},{begin:"\\b([0-9](_*[0-9])*)[fFdD]\\b"},{begin:`\\b0[xX]((${hexDigits$1})\\.?|(${hexDigits$1})?\\.(${hexDigits$1}))[pP][+-]?([0-9](_*[0-9])*)[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${hexDigits$1})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function recurRegex(re,substitution,depth){return-1===depth?"":re.replace(substitution,_=>recurRegex(re,substitution,depth-1))}function source(re){return re?"string"==typeof re?re:re.source:null}function lookahead(re){return concat("(?=",re,")")}function concat(...args){return args.map(x=>source(x)).join("")}function either(...args){const opts=function(args){const opts=args[args.length-1];return"object"==typeof opts&&opts.constructor===Object?(args.splice(args.length-1,1),opts):{}}(args);return"("+(opts.capture?"":"?:")+args.map(x=>source(x)).join("|")+")"}const keywordWrapper=keyword=>concat(/\b/,keyword,/\w$/.test(keyword)?/\b/:/\B/),dotKeywords=["Protocol","Type"].map(keywordWrapper),optionalDotKeywords=["init","self"].map(keywordWrapper),keywordTypes=["Any","Self"],keywords=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],literals=["false","nil","true"],precedencegroupKeywords=["assignment","associativity","higherThan","left","lowerThan","none","right"],numberSignKeywords=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],builtIns=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],operatorHead=either(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),operatorCharacter=either(operatorHead,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),operator=concat(operatorHead,operatorCharacter,"*"),identifierHead=either(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),identifierCharacter=either(identifierHead,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),identifier=concat(identifierHead,identifierCharacter,"*"),typeIdentifier=concat(/[A-Z]/,identifierCharacter,"*"),keywordAttributes=["attached","autoclosure",concat(/convention\(/,either("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",concat(/objc\(/,identifier,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],availabilityKeywords=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];var frac="\\.([0-9](_*[0-9])*)",hexDigits="[0-9a-fA-F](_*[0-9a-fA-F])*",NUMERIC={className:"number",variants:[{begin:`(\\b([0-9](_*[0-9])*)((${frac})|\\.)?|(${frac}))[eE][+-]?([0-9](_*[0-9])*)[fFdD]?\\b`},{begin:`\\b([0-9](_*[0-9])*)((${frac})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${frac})[fFdD]?\\b`},{begin:"\\b([0-9](_*[0-9])*)[fFdD]\\b"},{begin:`\\b0[xX]((${hexDigits})\\.?|(${hexDigits})?\\.(${hexDigits}))[pP][+-]?([0-9](_*[0-9])*)[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${hexDigits})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};const TAGS$1=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],MEDIA_FEATURES$1=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),PSEUDO_CLASSES$1=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),PSEUDO_ELEMENTS$1=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),ATTRIBUTES$1=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();const TAGS=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],MEDIA_FEATURES=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),PSEUDO_CLASSES=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),PSEUDO_ELEMENTS=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),ATTRIBUTES=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();const styles$c_fullFileDiffView="_fullFileDiffView_1o8kb_1",styles$c_diffSummary="_diffSummary_1o8kb_12",styles$c_addedBadge="_addedBadge_1o8kb_22",styles$c_deletedBadge="_deletedBadge_1o8kb_33",styles$c_codeContainer="_codeContainer_1o8kb_44",styles$c_lineNumberCol="_lineNumberCol_1o8kb_54",styles$c_lineNumRow="_lineNumRow_1o8kb_62",styles$c_oldLineNum="_oldLineNum_1o8kb_67",styles$c_newLineNum="_newLineNum_1o8kb_68",styles$c_lineNumNormal="_lineNumNormal_1o8kb_77",styles$c_lineNumAdd="_lineNumAdd_1o8kb_82",styles$c_lineNumDelete="_lineNumDelete_1o8kb_95",styles$c_codeColWrap="_codeColWrap_1o8kb_108",styles$c_codeCol="_codeCol_1o8kb_108",styles$c_codeInner="_codeInner_1o8kb_122",styles$c_codeLine="_codeLine_1o8kb_127",styles$c_linePrefix="_linePrefix_1o8kb_138",styles$c_lineContent="_lineContent_1o8kb_147",styles$c_lineNormal="_lineNormal_1o8kb_153",styles$c_lineAdd="_lineAdd_1o8kb_157",styles$c_lineDelete="_lineDelete_1o8kb_165",styles$b_miniMap="_miniMap_1ho3j_1",styles$b_marker="_marker_1ho3j_11";function DiffMiniMap({diffLines:diffLines2,scrollRef:scrollRef}){const mapRef=reactExports.useRef(null),[visible,setVisible]=reactExports.useState(!1);reactExports.useEffect(()=>{const el=null==scrollRef?void 0:scrollRef.current;if(!el)return;let prevScrollHeight=0,rafId=null;const check=()=>{const overflow=el.scrollHeight>el.clientHeight+1;setVisible(overflow),prevScrollHeight=el.scrollHeight};let stableCount=0;const poll=()=>{el.scrollHeight!==prevScrollHeight?(check(),stableCount=0):stableCount++,stableCount<30&&(rafId=requestAnimationFrame(poll))};check(),rafId=requestAnimationFrame(poll);const ro=new ResizeObserver(check);return ro.observe(el),()=>{ro.disconnect(),rafId&&cancelAnimationFrame(rafId)}},[scrollRef,diffLines2]);const handleClick=reactExports.useCallback(e=>{const el=null==scrollRef?void 0:scrollRef.current,map=mapRef.current;if(!el||!map)return;const rect=map.getBoundingClientRect(),ratio=(e.clientY-rect.top)/rect.height;el.scrollTop=ratio*(el.scrollHeight-el.clientHeight)},[scrollRef]);if(!visible||!diffLines2.length)return null;const totalLines=diffLines2.length,markers=[];for(let i=0;i<totalLines;i++){const type=diffLines2[i].type;if("context"===type)continue;const start=i;for(;i+1<totalLines&&diffLines2[i+1].type===type;)i++;markers.push({type:type,start:start,end:i})}return jsxRuntimeExports.jsx("div",{className:styles$b_miniMap,ref:mapRef,onClick:handleClick,children:markers.map((m,idx)=>{const topPct=m.start/totalLines*100,heightPct=(m.end-m.start+1)/totalLines*100,color="add"===m.type?"rgba(115, 201, 145, 0.7)":"rgba(241, 76, 76, 0.7)";return jsxRuntimeExports.jsx("div",{className:styles$b_marker,style:{top:`${topPct}%`,height:`max(2px, ${heightPct}%)`,backgroundColor:color}},idx)})})}HighlightJS.registerLanguage("javascript",function(hljs){const regex=hljs.regex,IDENT_RE$1$1="[A-Za-z$_][0-9A-Za-z$_]*",FRAGMENT_begin="<>",FRAGMENT_end="</>",XML_TAG={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(match,response)=>{const afterMatchIndex=match[0].length+match.index,nextChar=match.input[afterMatchIndex];if("<"===nextChar||","===nextChar)return void response.ignoreMatch();let m;">"===nextChar&&(((match,{after:after})=>{const tag="</"+match[0].slice(1);return-1!==match.input.indexOf(tag,after)})(match,{after:afterMatchIndex})||response.ignoreMatch());const afterMatch=match.input.substring(afterMatchIndex);((m=afterMatch.match(/^\s*=/))||(m=afterMatch.match(/^\s+extends\s+/))&&0===m.index)&&response.ignoreMatch()}},KEYWORDS$1$1={$pattern:"[A-Za-z$_][0-9A-Za-z$_]*",keyword:KEYWORDS$1,literal:LITERALS$1,built_in:BUILT_INS$1,"variable.language":BUILT_IN_VARIABLES$1},frac2="\\.([0-9](_?[0-9])*)",NUMBER={className:"number",variants:[{begin:`(\\b(0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*)((${frac2})|\\.)?|(${frac2}))[eE][+-]?([0-9](_?[0-9])*)\\b`},{begin:`\\b(0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*)\\b((${frac2})\\b|\\.)?|(${frac2})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},SUBST={className:"subst",begin:"\\$\\{",end:"\\}",keywords:KEYWORDS$1$1,contains:[]},HTML_TEMPLATE={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs.BACKSLASH_ESCAPE,SUBST],subLanguage:"xml"}},CSS_TEMPLATE={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs.BACKSLASH_ESCAPE,SUBST],subLanguage:"css"}},GRAPHQL_TEMPLATE={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs.BACKSLASH_ESCAPE,SUBST],subLanguage:"graphql"}},TEMPLATE_STRING={className:"string",begin:"`",end:"`",contains:[hljs.BACKSLASH_ESCAPE,SUBST]},COMMENT={className:"comment",variants:[hljs.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:IDENT_RE$1$1+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),hljs.C_BLOCK_COMMENT_MODE,hljs.C_LINE_COMMENT_MODE]},SUBST_INTERNALS=[hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMPLATE,GRAPHQL_TEMPLATE,TEMPLATE_STRING,{match:/\$\d+/},NUMBER];SUBST.contains=SUBST_INTERNALS.concat({begin:/\{/,end:/\}/,keywords:KEYWORDS$1$1,contains:["self"].concat(SUBST_INTERNALS)});const SUBST_AND_COMMENTS=[].concat(COMMENT,SUBST.contains),PARAMS_CONTAINS=SUBST_AND_COMMENTS.concat([{begin:/(\s*)\(/,end:/\)/,keywords:KEYWORDS$1$1,contains:["self"].concat(SUBST_AND_COMMENTS)}]),PARAMS={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS$1$1,contains:PARAMS_CONTAINS},CLASS_OR_EXTENDS={variants:[{match:[/class/,/\s+/,IDENT_RE$1$1,/\s+/,/extends/,/\s+/,regex.concat(IDENT_RE$1$1,"(",regex.concat(/\./,IDENT_RE$1$1),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,IDENT_RE$1$1],scope:{1:"keyword",3:"title.class"}}]},CLASS_REFERENCE={relevance:0,match:regex.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...TYPES$1,...ERROR_TYPES$1]}},FUNCTION_DEFINITION={variants:[{match:[/function/,/\s+/,IDENT_RE$1$1,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[PARAMS],illegal:/%/},FUNCTION_CALL={match:regex.concat(/\b/,(list=[...BUILT_IN_GLOBALS$1,"super","import"].map(x=>`${x}\\s*\\(`),regex.concat("(?!",list.join("|"),")")),IDENT_RE$1$1,regex.lookahead(/\s*\(/)),className:"title.function",relevance:0};var list;const PROPERTY_ACCESS={begin:regex.concat(/\./,regex.lookahead(regex.concat(IDENT_RE$1$1,/(?![0-9A-Za-z$_(])/))),end:IDENT_RE$1$1,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},GETTER_OR_SETTER={match:[/get|set/,/\s+/,IDENT_RE$1$1,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},PARAMS]},FUNC_LEAD_IN_RE="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+hljs.UNDERSCORE_IDENT_RE+")\\s*=>",FUNCTION_VARIABLE={match:[/const|var|let/,/\s+/,IDENT_RE$1$1,/\s*/,/=\s*/,/(async\s*)?/,regex.lookahead(FUNC_LEAD_IN_RE)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[PARAMS]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:KEYWORDS$1$1,exports:{PARAMS_CONTAINS:PARAMS_CONTAINS,CLASS_REFERENCE:CLASS_REFERENCE},illegal:/#(?![$_A-z])/,contains:[hljs.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMPLATE,GRAPHQL_TEMPLATE,TEMPLATE_STRING,COMMENT,{match:/\$\d+/},NUMBER,CLASS_REFERENCE,{scope:"attr",match:IDENT_RE$1$1+regex.lookahead(":"),relevance:0},FUNCTION_VARIABLE,{begin:"("+hljs.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[COMMENT,hljs.REGEXP_MODE,{className:"function",begin:FUNC_LEAD_IN_RE,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:hljs.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS$1$1,contains:PARAMS_CONTAINS}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:FRAGMENT_begin,end:FRAGMENT_end},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:XML_TAG.begin,"on:begin":XML_TAG.isTrulyOpeningTag,end:XML_TAG.end}],subLanguage:"xml",contains:[{begin:XML_TAG.begin,end:XML_TAG.end,skip:!0,contains:["self"]}]}]},FUNCTION_DEFINITION,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+hljs.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[PARAMS,hljs.inherit(hljs.TITLE_MODE,{begin:IDENT_RE$1$1,className:"title.function"})]},{match:/\.\.\./,relevance:0},PROPERTY_ACCESS,{match:"\\$"+IDENT_RE$1$1,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[PARAMS]},FUNCTION_CALL,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},CLASS_OR_EXTENDS,GETTER_OR_SETTER,{match:/\$[(.]/}]}}),HighlightJS.registerLanguage("typescript",function(hljs){const regex=hljs.regex,tsLanguage=function(hljs){const regex=hljs.regex,IDENT_RE$12=IDENT_RE,FRAGMENT_begin="<>",FRAGMENT_end="</>",XML_TAG={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(match,response)=>{const afterMatchIndex=match[0].length+match.index,nextChar=match.input[afterMatchIndex];if("<"===nextChar||","===nextChar)return void response.ignoreMatch();let m;">"===nextChar&&(((match,{after:after})=>{const tag="</"+match[0].slice(1);return-1!==match.input.indexOf(tag,after)})(match,{after:afterMatchIndex})||response.ignoreMatch());const afterMatch=match.input.substring(afterMatchIndex);((m=afterMatch.match(/^\s*=/))||(m=afterMatch.match(/^\s+extends\s+/))&&0===m.index)&&response.ignoreMatch()}},KEYWORDS$12={$pattern:IDENT_RE,keyword:KEYWORDS,literal:LITERALS,built_in:BUILT_INS,"variable.language":BUILT_IN_VARIABLES},frac2="\\.([0-9](_?[0-9])*)",NUMBER={className:"number",variants:[{begin:`(\\b(0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*)((${frac2})|\\.)?|(${frac2}))[eE][+-]?([0-9](_?[0-9])*)\\b`},{begin:`\\b(0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*)\\b((${frac2})\\b|\\.)?|(${frac2})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},SUBST={className:"subst",begin:"\\$\\{",end:"\\}",keywords:KEYWORDS$12,contains:[]},HTML_TEMPLATE={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs.BACKSLASH_ESCAPE,SUBST],subLanguage:"xml"}},CSS_TEMPLATE={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs.BACKSLASH_ESCAPE,SUBST],subLanguage:"css"}},GRAPHQL_TEMPLATE={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs.BACKSLASH_ESCAPE,SUBST],subLanguage:"graphql"}},TEMPLATE_STRING={className:"string",begin:"`",end:"`",contains:[hljs.BACKSLASH_ESCAPE,SUBST]},COMMENT={className:"comment",variants:[hljs.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:IDENT_RE$12+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),hljs.C_BLOCK_COMMENT_MODE,hljs.C_LINE_COMMENT_MODE]},SUBST_INTERNALS=[hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMPLATE,GRAPHQL_TEMPLATE,TEMPLATE_STRING,{match:/\$\d+/},NUMBER];SUBST.contains=SUBST_INTERNALS.concat({begin:/\{/,end:/\}/,keywords:KEYWORDS$12,contains:["self"].concat(SUBST_INTERNALS)});const SUBST_AND_COMMENTS=[].concat(COMMENT,SUBST.contains),PARAMS_CONTAINS=SUBST_AND_COMMENTS.concat([{begin:/(\s*)\(/,end:/\)/,keywords:KEYWORDS$12,contains:["self"].concat(SUBST_AND_COMMENTS)}]),PARAMS={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS$12,contains:PARAMS_CONTAINS},CLASS_OR_EXTENDS={variants:[{match:[/class/,/\s+/,IDENT_RE$12,/\s+/,/extends/,/\s+/,regex.concat(IDENT_RE$12,"(",regex.concat(/\./,IDENT_RE$12),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,IDENT_RE$12],scope:{1:"keyword",3:"title.class"}}]},CLASS_REFERENCE={relevance:0,match:regex.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...TYPES,...ERROR_TYPES]}},FUNCTION_DEFINITION={variants:[{match:[/function/,/\s+/,IDENT_RE$12,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[PARAMS],illegal:/%/},FUNCTION_CALL={match:regex.concat(/\b/,(list=[...BUILT_IN_GLOBALS,"super","import"].map(x=>`${x}\\s*\\(`),regex.concat("(?!",list.join("|"),")")),IDENT_RE$12,regex.lookahead(/\s*\(/)),className:"title.function",relevance:0};var list;const PROPERTY_ACCESS={begin:regex.concat(/\./,regex.lookahead(regex.concat(IDENT_RE$12,/(?![0-9A-Za-z$_(])/))),end:IDENT_RE$12,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},GETTER_OR_SETTER={match:[/get|set/,/\s+/,IDENT_RE$12,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},PARAMS]},FUNC_LEAD_IN_RE="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+hljs.UNDERSCORE_IDENT_RE+")\\s*=>",FUNCTION_VARIABLE={match:[/const|var|let/,/\s+/,IDENT_RE$12,/\s*/,/=\s*/,/(async\s*)?/,regex.lookahead(FUNC_LEAD_IN_RE)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[PARAMS]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:KEYWORDS$12,exports:{PARAMS_CONTAINS:PARAMS_CONTAINS,CLASS_REFERENCE:CLASS_REFERENCE},illegal:/#(?![$_A-z])/,contains:[hljs.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMPLATE,GRAPHQL_TEMPLATE,TEMPLATE_STRING,COMMENT,{match:/\$\d+/},NUMBER,CLASS_REFERENCE,{scope:"attr",match:IDENT_RE$12+regex.lookahead(":"),relevance:0},FUNCTION_VARIABLE,{begin:"("+hljs.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[COMMENT,hljs.REGEXP_MODE,{className:"function",begin:FUNC_LEAD_IN_RE,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:hljs.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS$12,contains:PARAMS_CONTAINS}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:FRAGMENT_begin,end:FRAGMENT_end},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:XML_TAG.begin,"on:begin":XML_TAG.isTrulyOpeningTag,end:XML_TAG.end}],subLanguage:"xml",contains:[{begin:XML_TAG.begin,end:XML_TAG.end,skip:!0,contains:["self"]}]}]},FUNCTION_DEFINITION,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+hljs.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[PARAMS,hljs.inherit(hljs.TITLE_MODE,{begin:IDENT_RE$12,className:"title.function"})]},{match:/\.\.\./,relevance:0},PROPERTY_ACCESS,{match:"\\$"+IDENT_RE$12,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[PARAMS]},FUNCTION_CALL,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},CLASS_OR_EXTENDS,GETTER_OR_SETTER,{match:/\$[(.]/}]}}(hljs),IDENT_RE$12=IDENT_RE,TYPES2=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],NAMESPACE={begin:[/namespace/,/\s+/,hljs.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},INTERFACE={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:TYPES2},contains:[tsLanguage.exports.CLASS_REFERENCE]},KEYWORDS$12={$pattern:IDENT_RE,keyword:KEYWORDS.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:LITERALS,built_in:BUILT_INS.concat(TYPES2),"variable.language":BUILT_IN_VARIABLES},DECORATOR={className:"meta",begin:"@"+IDENT_RE$12},swapMode=(mode,label2,replacement)=>{const indx=mode.contains.findIndex(m=>m.label===label2);if(-1===indx)throw new Error("can not find mode to replace");mode.contains.splice(indx,1,replacement)};Object.assign(tsLanguage.keywords,KEYWORDS$12),tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR);const ATTRIBUTE_HIGHLIGHT=tsLanguage.contains.find(c=>"attr"===c.scope),OPTIONAL_KEY_OR_ARGUMENT=Object.assign({},ATTRIBUTE_HIGHLIGHT,{match:regex.concat(IDENT_RE$12,regex.lookahead(/\s*\?:/))});return tsLanguage.exports.PARAMS_CONTAINS.push([tsLanguage.exports.CLASS_REFERENCE,ATTRIBUTE_HIGHLIGHT,OPTIONAL_KEY_OR_ARGUMENT]),tsLanguage.contains=tsLanguage.contains.concat([DECORATOR,NAMESPACE,INTERFACE,OPTIONAL_KEY_OR_ARGUMENT]),swapMode(tsLanguage,"shebang",hljs.SHEBANG()),swapMode(tsLanguage,"use_strict",{className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/}),tsLanguage.contains.find(m=>"func.def"===m.label).relevance=0,Object.assign(tsLanguage,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),tsLanguage}),HighlightJS.registerLanguage("python",function(hljs){const regex=hljs.regex,IDENT_RE2=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),RESERVED_WORDS=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],KEYWORDS2={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:RESERVED_WORDS,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},PROMPT={className:"meta",begin:/^(>>>|\.\.\.) /},SUBST={className:"subst",begin:/\{/,end:/\}/,keywords:KEYWORDS2,illegal:/#/},LITERAL_BRACKET={begin:/\{\{/,relevance:0},STRING={className:"string",contains:[hljs.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[hljs.BACKSLASH_ESCAPE,PROMPT],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[hljs.BACKSLASH_ESCAPE,PROMPT],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[hljs.BACKSLASH_ESCAPE,PROMPT,LITERAL_BRACKET,SUBST]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[hljs.BACKSLASH_ESCAPE,PROMPT,LITERAL_BRACKET,SUBST]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[hljs.BACKSLASH_ESCAPE,LITERAL_BRACKET,SUBST]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[hljs.BACKSLASH_ESCAPE,LITERAL_BRACKET,SUBST]},hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE]},digitpart="[0-9](_?[0-9])*",pointfloat=`(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart})\\.`,lookahead2=`\\b|${RESERVED_WORDS.join("|")}`,NUMBER={className:"number",relevance:0,variants:[{begin:`(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?(?=${lookahead2})`},{begin:`(${pointfloat})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${lookahead2})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${lookahead2})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${lookahead2})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${lookahead2})`},{begin:`\\b(${digitpart})[jJ](?=${lookahead2})`}]},COMMENT_TYPE={className:"comment",begin:regex.lookahead(/# type:/),end:/$/,keywords:KEYWORDS2,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},PARAMS={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS2,contains:["self",PROMPT,NUMBER,STRING,hljs.HASH_COMMENT_MODE]}]};return SUBST.contains=[STRING,NUMBER,PROMPT],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:KEYWORDS2,illegal:/(<\/|\?)|=>/,contains:[PROMPT,NUMBER,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},STRING,COMMENT_TYPE,hljs.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,IDENT_RE2],scope:{1:"keyword",3:"title.function"},contains:[PARAMS]},{variants:[{match:[/\bclass/,/\s+/,IDENT_RE2,/\s*/,/\(\s*/,IDENT_RE2,/\s*\)/]},{match:[/\bclass/,/\s+/,IDENT_RE2]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[NUMBER,PARAMS,STRING]}]}}),HighlightJS.registerLanguage("java",function(hljs){const regex=hljs.regex,JAVA_IDENT_RE="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",GENERIC_IDENT_RE=JAVA_IDENT_RE+recurRegex("(?:<"+JAVA_IDENT_RE+"~~~(?:\\s*,\\s*"+JAVA_IDENT_RE+"~~~)*>)?",/~~~/g,2),KEYWORDS2={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},ANNOTATION={className:"meta",begin:"@"+JAVA_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},PARAMS={className:"params",begin:/\(/,end:/\)/,keywords:KEYWORDS2,relevance:0,contains:[hljs.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:KEYWORDS2,illegal:/<\/|#/,contains:[hljs.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[hljs.BACKSLASH_ESCAPE]},hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,JAVA_IDENT_RE],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[regex.concat(/(?!else)/,JAVA_IDENT_RE),/\s+/,JAVA_IDENT_RE,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,JAVA_IDENT_RE],className:{1:"keyword",3:"title.class"},contains:[PARAMS,hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+GENERIC_IDENT_RE+"\\s+)",hljs.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:KEYWORDS2,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:KEYWORDS2,relevance:0,contains:[ANNOTATION,hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE,NUMERIC$1,hljs.C_BLOCK_COMMENT_MODE]},hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE]},NUMERIC$1,ANNOTATION]}}),HighlightJS.registerLanguage("cpp",function(hljs){const regex=hljs.regex,C_LINE_COMMENT_MODE=hljs.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),FUNCTION_TYPE_RE="(?!struct)(decltype\\(auto\\)|"+regex.optional("[a-zA-Z_]\\w*::")+"[a-zA-Z_]\\w*"+regex.optional("<[^<>]+>")+")",CPP_PRIMITIVE_TYPES={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},STRINGS={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[hljs.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},hljs.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},NUMBERS={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},PREPROCESSOR={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},hljs.inherit(STRINGS,{className:"string"}),{className:"string",begin:/<.*?>/},C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE]},TITLE_MODE={className:"title",begin:regex.optional("[a-zA-Z_]\\w*::")+hljs.IDENT_RE,relevance:0},FUNCTION_TITLE=regex.optional("[a-zA-Z_]\\w*::")+hljs.IDENT_RE+"\\s*\\(",CPP_KEYWORDS={type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"]},FUNCTION_DISPATCH={className:"function.dispatch",relevance:0,keywords:{_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"]},begin:regex.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,hljs.IDENT_RE,regex.lookahead(/(<[^<>]+>|)\s*\(/))},EXPRESSION_CONTAINS=[FUNCTION_DISPATCH,PREPROCESSOR,CPP_PRIMITIVE_TYPES,C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE,NUMBERS,STRINGS],EXPRESSION_CONTEXT={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:CPP_KEYWORDS,contains:EXPRESSION_CONTAINS.concat([{begin:/\(/,end:/\)/,keywords:CPP_KEYWORDS,contains:EXPRESSION_CONTAINS.concat(["self"]),relevance:0}]),relevance:0},FUNCTION_DECLARATION={className:"function",begin:"("+FUNCTION_TYPE_RE+"[\\*&\\s]+)+"+FUNCTION_TITLE,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:CPP_KEYWORDS,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:"decltype\\(auto\\)",keywords:CPP_KEYWORDS,relevance:0},{begin:FUNCTION_TITLE,returnBegin:!0,contains:[TITLE_MODE],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[STRINGS,NUMBERS]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:CPP_KEYWORDS,relevance:0,contains:[C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE,STRINGS,NUMBERS,CPP_PRIMITIVE_TYPES,{begin:/\(/,end:/\)/,keywords:CPP_KEYWORDS,relevance:0,contains:["self",C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE,STRINGS,NUMBERS,CPP_PRIMITIVE_TYPES]}]},CPP_PRIMITIVE_TYPES,C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE,PREPROCESSOR]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:CPP_KEYWORDS,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(EXPRESSION_CONTEXT,FUNCTION_DECLARATION,FUNCTION_DISPATCH,EXPRESSION_CONTAINS,[PREPROCESSOR,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:CPP_KEYWORDS,contains:["self",CPP_PRIMITIVE_TYPES]},{begin:hljs.IDENT_RE+"::",keywords:CPP_KEYWORDS},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}),HighlightJS.registerLanguage("csharp",function(hljs){const KEYWORDS2={keyword:["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"].concat(["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"]),built_in:["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],literal:["default","false","null","true"]},TITLE_MODE=hljs.inherit(hljs.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),NUMBERS={className:"number",variants:[{begin:"\\b(0b[01']+)"},{begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},VERBATIM_STRING={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},VERBATIM_STRING_NO_LF=hljs.inherit(VERBATIM_STRING,{illegal:/\n/}),SUBST={className:"subst",begin:/\{/,end:/\}/,keywords:KEYWORDS2},SUBST_NO_LF=hljs.inherit(SUBST,{illegal:/\n/}),INTERPOLATED_STRING={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},hljs.BACKSLASH_ESCAPE,SUBST_NO_LF]},INTERPOLATED_VERBATIM_STRING={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},SUBST]},INTERPOLATED_VERBATIM_STRING_NO_LF=hljs.inherit(INTERPOLATED_VERBATIM_STRING,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},SUBST_NO_LF]});SUBST.contains=[INTERPOLATED_VERBATIM_STRING,INTERPOLATED_STRING,VERBATIM_STRING,hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE,NUMBERS,hljs.C_BLOCK_COMMENT_MODE],SUBST_NO_LF.contains=[INTERPOLATED_VERBATIM_STRING_NO_LF,INTERPOLATED_STRING,VERBATIM_STRING_NO_LF,hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE,NUMBERS,hljs.inherit(hljs.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];const STRING={variants:[{className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},INTERPOLATED_VERBATIM_STRING,INTERPOLATED_STRING,VERBATIM_STRING,hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE]},GENERIC_MODIFIER={begin:"<",end:">",contains:[{beginKeywords:"in out"},TITLE_MODE]},TYPE_IDENT_RE=hljs.IDENT_RE+"(<"+hljs.IDENT_RE+"(\\s*,\\s*"+hljs.IDENT_RE+")*>)?(\\[\\])?",AT_IDENTIFIER={begin:"@"+hljs.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:KEYWORDS2,illegal:/::/,contains:[hljs.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:"\x3c!--|--\x3e"},{begin:"</?",end:">"}]}]}),hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},STRING,NUMBERS,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},TITLE_MODE,GENERIC_MODIFIER,hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[TITLE_MODE,hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[TITLE_MODE,GENERIC_MODIFIER,hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+TYPE_IDENT_RE+"\\s+)+"+hljs.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:KEYWORDS2,contains:[{beginKeywords:["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"].join(" "),relevance:0},{begin:hljs.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[hljs.TITLE_MODE,GENERIC_MODIFIER],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS2,relevance:0,contains:[STRING,NUMBERS,hljs.C_BLOCK_COMMENT_MODE]},hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE]},AT_IDENTIFIER]}}),HighlightJS.registerLanguage("go",function(hljs){const KEYWORDS2={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:KEYWORDS2,illegal:"</",contains:[hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE,{className:"string",variants:[hljs.QUOTE_STRING_MODE,hljs.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[hljs.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:KEYWORDS2,illegal:/["']/}]}]}}),HighlightJS.registerLanguage("rust",function(hljs){const regex=hljs.regex,RAW_IDENTIFIER=/(r#)?/,UNDERSCORE_IDENT_RE=regex.concat(RAW_IDENTIFIER,hljs.UNDERSCORE_IDENT_RE),IDENT_RE2=regex.concat(RAW_IDENTIFIER,hljs.IDENT_RE),FUNCTION_INVOKE={className:"title.function.invoke",relevance:0,begin:regex.concat(/\b/,/(?!let|for|while|if|else|match\b)/,IDENT_RE2,regex.lookahead(/\s*\(/))},NUMBER_SUFFIX="([ui](8|16|32|64|128|size)|f(32|64))?",BUILTINS=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],TYPES2=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:hljs.IDENT_RE+"!?",type:TYPES2,keyword:["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],literal:["true","false","Some","None","Ok","Err"],built_in:BUILTINS},illegal:"</",contains:[hljs.C_LINE_COMMENT_MODE,hljs.COMMENT("/\\*","\\*/",{contains:["self"]}),hljs.inherit(hljs.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+NUMBER_SUFFIX},{begin:"\\b0o([0-7_]+)"+NUMBER_SUFFIX},{begin:"\\b0x([A-Fa-f0-9_]+)"+NUMBER_SUFFIX},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+NUMBER_SUFFIX}],relevance:0},{begin:[/fn/,/\s+/,UNDERSCORE_IDENT_RE],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[hljs.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,UNDERSCORE_IDENT_RE],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,UNDERSCORE_IDENT_RE,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,UNDERSCORE_IDENT_RE],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,UNDERSCORE_IDENT_RE],className:{1:"keyword",3:"title.class"}},{begin:hljs.IDENT_RE+"::",keywords:{keyword:"Self",built_in:BUILTINS,type:TYPES2}},{className:"punctuation",begin:"->"},FUNCTION_INVOKE]}}),HighlightJS.registerLanguage("php",function(hljs){const regex=hljs.regex,NOT_PERL_ETC=/(?![A-Za-z0-9])(?![$])/,IDENT_RE2=regex.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,NOT_PERL_ETC),PASCAL_CASE_CLASS_NAME_RE=regex.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,NOT_PERL_ETC),UPCASE_NAME_RE=regex.concat(/[A-Z]+/,NOT_PERL_ETC),VARIABLE={scope:"variable",match:"\\$+"+IDENT_RE2},SUBST={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},SINGLE_QUOTED=hljs.inherit(hljs.APOS_STRING_MODE,{illegal:null}),STRING={scope:"string",variants:[hljs.inherit(hljs.QUOTE_STRING_MODE,{illegal:null,contains:hljs.QUOTE_STRING_MODE.contains.concat(SUBST)}),SINGLE_QUOTED,{begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:hljs.QUOTE_STRING_MODE.contains.concat(SUBST),"on:begin":(m,resp)=>{resp.data._beginMatch=m[1]||m[2]},"on:end":(m,resp)=>{resp.data._beginMatch!==m[1]&&resp.ignoreMatch()}},hljs.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/})]},NUMBER={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},LITERALS2=["false","null","true"],KWS=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],BUILT_INS2=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],KEYWORDS2={keyword:KWS,literal:(items=>{const result=[];return items.forEach(item=>{result.push(item),item.toLowerCase()===item?result.push(item.toUpperCase()):result.push(item.toLowerCase())}),result})(LITERALS2),built_in:BUILT_INS2},normalizeKeywords=items=>items.map(item=>item.replace(/\|\d+$/,"")),CONSTRUCTOR_CALL={variants:[{match:[/new/,regex.concat("[ \t\n]","+"),regex.concat("(?!",normalizeKeywords(BUILT_INS2).join("\\b|"),"\\b)"),PASCAL_CASE_CLASS_NAME_RE],scope:{1:"keyword",4:"title.class"}}]},CONSTANT_REFERENCE=regex.concat(IDENT_RE2,"\\b(?!\\()"),LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON={variants:[{match:[regex.concat(/::/,regex.lookahead(/(?!class\b)/)),CONSTANT_REFERENCE],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[PASCAL_CASE_CLASS_NAME_RE,regex.concat(/::/,regex.lookahead(/(?!class\b)/)),CONSTANT_REFERENCE],scope:{1:"title.class",3:"variable.constant"}},{match:[PASCAL_CASE_CLASS_NAME_RE,regex.concat("::",regex.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[PASCAL_CASE_CLASS_NAME_RE,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},NAMED_ARGUMENT={scope:"attr",match:regex.concat(IDENT_RE2,regex.lookahead(":"),regex.lookahead(/(?!::)/))},PARAMS_MODE={relevance:0,begin:/\(/,end:/\)/,keywords:KEYWORDS2,contains:[NAMED_ARGUMENT,VARIABLE,LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,hljs.C_BLOCK_COMMENT_MODE,STRING,NUMBER,CONSTRUCTOR_CALL]},FUNCTION_INVOKE={relevance:0,match:[/\b/,regex.concat("(?!fn\\b|function\\b|",normalizeKeywords(KWS).join("\\b|"),"|",normalizeKeywords(BUILT_INS2).join("\\b|"),"\\b)"),IDENT_RE2,regex.concat("[ \t\n]","*"),regex.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[PARAMS_MODE]};PARAMS_MODE.contains.push(FUNCTION_INVOKE);const ATTRIBUTE_CONTAINS=[NAMED_ARGUMENT,LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,hljs.C_BLOCK_COMMENT_MODE,STRING,NUMBER,CONSTRUCTOR_CALL],ATTRIBUTES2={begin:regex.concat(/#\[\s*\\?/,regex.either(PASCAL_CASE_CLASS_NAME_RE,UPCASE_NAME_RE)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:LITERALS2,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:LITERALS2,keyword:["new","array"]},contains:["self",...ATTRIBUTE_CONTAINS]},...ATTRIBUTE_CONTAINS,{scope:"meta",variants:[{match:PASCAL_CASE_CLASS_NAME_RE},{match:UPCASE_NAME_RE}]}]};return{case_insensitive:!1,keywords:KEYWORDS2,contains:[ATTRIBUTES2,hljs.HASH_COMMENT_MODE,hljs.COMMENT("//","$"),hljs.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:hljs.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},{scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},{scope:"variable.language",match:/\$this\b/},VARIABLE,FUNCTION_INVOKE,LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,{match:[/const/,/\s/,IDENT_RE2],scope:{1:"keyword",3:"variable.constant"}},CONSTRUCTOR_CALL,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},hljs.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS2,contains:["self",ATTRIBUTES2,VARIABLE,LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,hljs.C_BLOCK_COMMENT_MODE,STRING,NUMBER]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},hljs.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[hljs.inherit(hljs.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},hljs.UNDERSCORE_TITLE_MODE]},STRING,NUMBER]}}),HighlightJS.registerLanguage("ruby",function(hljs){const regex=hljs.regex,RUBY_METHOD_RE="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",CLASS_NAME_RE=regex.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),CLASS_NAME_WITH_NAMESPACE_RE=regex.concat(CLASS_NAME_RE,/(::\w+)*/),RUBY_KEYWORDS={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield","include","extend","prepend","public","private","protected","raise","throw"],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},YARDOCTAG={className:"doctag",begin:"@[A-Za-z]+"},IRB_OBJECT={begin:"#<",end:">"},COMMENT_MODES=[hljs.COMMENT("#","$",{contains:[YARDOCTAG]}),hljs.COMMENT("^=begin","^=end",{contains:[YARDOCTAG],relevance:10}),hljs.COMMENT("^__END__",hljs.MATCH_NOTHING_RE)],SUBST={className:"subst",begin:/#\{/,end:/\}/,keywords:RUBY_KEYWORDS},STRING={className:"string",contains:[hljs.BACKSLASH_ESCAPE,SUBST],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:regex.concat(/<<[-~]?'?/,regex.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[hljs.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[hljs.BACKSLASH_ESCAPE,SUBST]})]}]},NUMBER={className:"number",relevance:0,variants:[{begin:"\\b([1-9](_?[0-9])*|0)(\\.([0-9](_?[0-9])*))?([eE][+-]?([0-9](_?[0-9])*)|r)?i?\\b"},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},PARAMS={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:RUBY_KEYWORDS}]},RUBY_DEFAULT_CONTAINS=[STRING,{variants:[{match:[/class\s+/,CLASS_NAME_WITH_NAMESPACE_RE,/\s+<\s+/,CLASS_NAME_WITH_NAMESPACE_RE]},{match:[/\b(class|module)\s+/,CLASS_NAME_WITH_NAMESPACE_RE]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:RUBY_KEYWORDS},{match:[/(include|extend)\s+/,CLASS_NAME_WITH_NAMESPACE_RE],scope:{2:"title.class"},keywords:RUBY_KEYWORDS},{relevance:0,match:[CLASS_NAME_WITH_NAMESPACE_RE,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:CLASS_NAME_RE,scope:"title.class"},{match:[/def/,/\s+/,RUBY_METHOD_RE],scope:{1:"keyword",3:"title.function"},contains:[PARAMS]},{begin:hljs.IDENT_RE+"::"},{className:"symbol",begin:hljs.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[STRING,{begin:RUBY_METHOD_RE}],relevance:0},NUMBER,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:RUBY_KEYWORDS},{begin:"("+hljs.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[hljs.BACKSLASH_ESCAPE,SUBST],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(IRB_OBJECT,COMMENT_MODES),relevance:0}].concat(IRB_OBJECT,COMMENT_MODES);SUBST.contains=RUBY_DEFAULT_CONTAINS,PARAMS.contains=RUBY_DEFAULT_CONTAINS;const IRB_DEFAULT=[{begin:/^\s*=>/,starts:{end:"$",contains:RUBY_DEFAULT_CONTAINS}},{className:"meta.prompt",begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]|(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>)(?=[ ])",starts:{end:"$",keywords:RUBY_KEYWORDS,contains:RUBY_DEFAULT_CONTAINS}}];return COMMENT_MODES.unshift(IRB_OBJECT),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:RUBY_KEYWORDS,illegal:/\/\*/,contains:[hljs.SHEBANG({binary:"ruby"})].concat(IRB_DEFAULT).concat(COMMENT_MODES).concat(RUBY_DEFAULT_CONTAINS)}}),HighlightJS.registerLanguage("swift",function(hljs){const WHITESPACE={match:/\s+/,relevance:0},BLOCK_COMMENT=hljs.COMMENT("/\\*","\\*/",{contains:["self"]}),COMMENTS=[hljs.C_LINE_COMMENT_MODE,BLOCK_COMMENT],DOT_KEYWORD={match:[/\./,either(...dotKeywords,...optionalDotKeywords)],className:{2:"keyword"}},KEYWORD_GUARD={match:concat(/\./,either(...keywords)),relevance:0},PLAIN_KEYWORDS=keywords.filter(kw=>"string"==typeof kw).concat(["_|0"]),KEYWORD={variants:[{className:"keyword",match:either(...keywords.filter(kw=>"string"!=typeof kw).concat(keywordTypes).map(keywordWrapper),...optionalDotKeywords)}]},KEYWORDS2={$pattern:either(/\b\w+/,/#\w+/),keyword:PLAIN_KEYWORDS.concat(numberSignKeywords),literal:literals},KEYWORD_MODES=[DOT_KEYWORD,KEYWORD_GUARD,KEYWORD],BUILT_INS2=[{match:concat(/\./,either(...builtIns)),relevance:0},{className:"built_in",match:concat(/\b/,either(...builtIns),/(?=\()/)}],OPERATOR_GUARD={match:/->/,relevance:0},OPERATORS=[OPERATOR_GUARD,{className:"operator",relevance:0,variants:[{match:operator},{match:`\\.(\\.|${operatorCharacter})+`}]}],NUMBER={className:"number",relevance:0,variants:[{match:"\\b(([0-9]_*)+)(\\.(([0-9]_*)+))?([eE][+-]?(([0-9]_*)+))?\\b"},{match:"\\b0x(([0-9a-fA-F]_*)+)(\\.(([0-9a-fA-F]_*)+))?([pP][+-]?(([0-9]_*)+))?\\b"},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},ESCAPED_CHARACTER=(rawDelimiter="")=>({className:"subst",variants:[{match:concat(/\\/,rawDelimiter,/[0\\tnr"']/)},{match:concat(/\\/,rawDelimiter,/u\{[0-9a-fA-F]{1,8}\}/)}]}),ESCAPED_NEWLINE=(rawDelimiter="")=>({className:"subst",match:concat(/\\/,rawDelimiter,/[\t ]*(?:[\r\n]|\r\n)/)}),INTERPOLATION=(rawDelimiter="")=>({className:"subst",label:"interpol",begin:concat(/\\/,rawDelimiter,/\(/),end:/\)/}),MULTILINE_STRING=(rawDelimiter="")=>({begin:concat(rawDelimiter,/"""/),end:concat(/"""/,rawDelimiter),contains:[ESCAPED_CHARACTER(rawDelimiter),ESCAPED_NEWLINE(rawDelimiter),INTERPOLATION(rawDelimiter)]}),SINGLE_LINE_STRING=(rawDelimiter="")=>({begin:concat(rawDelimiter,/"/),end:concat(/"/,rawDelimiter),contains:[ESCAPED_CHARACTER(rawDelimiter),INTERPOLATION(rawDelimiter)]}),STRING={className:"string",variants:[MULTILINE_STRING(),MULTILINE_STRING("#"),MULTILINE_STRING("##"),MULTILINE_STRING("###"),SINGLE_LINE_STRING(),SINGLE_LINE_STRING("#"),SINGLE_LINE_STRING("##"),SINGLE_LINE_STRING("###")]},REGEXP_CONTENTS=[hljs.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[hljs.BACKSLASH_ESCAPE]}],BARE_REGEXP_LITERAL={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:REGEXP_CONTENTS},EXTENDED_REGEXP_LITERAL=rawDelimiter=>{const begin=concat(rawDelimiter,/\//),end=concat(/\//,rawDelimiter);return{begin:begin,end:end,contains:[...REGEXP_CONTENTS,{scope:"comment",begin:`#(?!.*${end})`,end:/$/}]}},REGEXP={scope:"regexp",variants:[EXTENDED_REGEXP_LITERAL("###"),EXTENDED_REGEXP_LITERAL("##"),EXTENDED_REGEXP_LITERAL("#"),BARE_REGEXP_LITERAL]},QUOTED_IDENTIFIER={match:concat(/`/,identifier,/`/)},IDENTIFIERS=[QUOTED_IDENTIFIER,{className:"variable",match:/\$\d+/},{className:"variable",match:`\\$${identifierCharacter}+`}],ATTRIBUTES2=[{match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:availabilityKeywords,contains:[...OPERATORS,NUMBER,STRING]}]}},{scope:"keyword",match:concat(/@/,either(...keywordAttributes),lookahead(either(/\(/,/\s+/)))},{scope:"meta",match:concat(/@/,identifier)}],TYPE={match:lookahead(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:concat(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,identifierCharacter,"+")},{className:"type",match:typeIdentifier,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:concat(/\s+&\s+/,lookahead(typeIdentifier)),relevance:0}]},GENERIC_ARGUMENTS={begin:/</,end:/>/,keywords:KEYWORDS2,contains:[...COMMENTS,...KEYWORD_MODES,...ATTRIBUTES2,OPERATOR_GUARD,TYPE]};TYPE.contains.push(GENERIC_ARGUMENTS);const TUPLE={begin:/\(/,end:/\)/,relevance:0,keywords:KEYWORDS2,contains:["self",{match:concat(identifier,/\s*:/),keywords:"_|0",relevance:0},...COMMENTS,REGEXP,...KEYWORD_MODES,...BUILT_INS2,...OPERATORS,NUMBER,STRING,...IDENTIFIERS,...ATTRIBUTES2,TYPE]},GENERIC_PARAMETERS={begin:/</,end:/>/,keywords:"repeat each",contains:[...COMMENTS,TYPE]},FUNCTION_PARAMETERS={begin:/\(/,end:/\)/,keywords:KEYWORDS2,contains:[{begin:either(lookahead(concat(identifier,/\s*:/)),lookahead(concat(identifier,/\s+/,identifier,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:identifier}]},...COMMENTS,...KEYWORD_MODES,...OPERATORS,NUMBER,STRING,...ATTRIBUTES2,TYPE,TUPLE],endsParent:!0,illegal:/["']/},FUNCTION_OR_MACRO={match:[/(func|macro)/,/\s+/,either(QUOTED_IDENTIFIER.match,identifier,operator)],className:{1:"keyword",3:"title.function"},contains:[GENERIC_PARAMETERS,FUNCTION_PARAMETERS,WHITESPACE],illegal:[/\[/,/%/]},INIT_SUBSCRIPT={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[GENERIC_PARAMETERS,FUNCTION_PARAMETERS,WHITESPACE],illegal:/\[|%/},OPERATOR_DECLARATION={match:[/operator/,/\s+/,operator],className:{1:"keyword",3:"title"}},PRECEDENCEGROUP={begin:[/precedencegroup/,/\s+/,typeIdentifier],className:{1:"keyword",3:"title"},contains:[TYPE],keywords:[...precedencegroupKeywords,...literals],end:/}/},TYPE_DECLARATION={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,identifier,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:KEYWORDS2,contains:[GENERIC_PARAMETERS,...KEYWORD_MODES,{begin:/:/,end:/\{/,keywords:KEYWORDS2,contains:[{scope:"title.class.inherited",match:typeIdentifier},...KEYWORD_MODES],relevance:0}]};for(const variant of STRING.variants){const interpolation=variant.contains.find(mode=>"interpol"===mode.label);interpolation.keywords=KEYWORDS2;const submodes=[...KEYWORD_MODES,...BUILT_INS2,...OPERATORS,NUMBER,STRING,...IDENTIFIERS];interpolation.contains=[...submodes,{begin:/\(/,end:/\)/,contains:["self",...submodes]}]}return{name:"Swift",keywords:KEYWORDS2,contains:[...COMMENTS,FUNCTION_OR_MACRO,INIT_SUBSCRIPT,{match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},{match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},TYPE_DECLARATION,OPERATOR_DECLARATION,PRECEDENCEGROUP,{beginKeywords:"import",end:/$/,contains:[...COMMENTS],relevance:0},REGEXP,...KEYWORD_MODES,...BUILT_INS2,...OPERATORS,NUMBER,STRING,...IDENTIFIERS,...ATTRIBUTES2,TYPE,TUPLE]}}),HighlightJS.registerLanguage("kotlin",function(hljs){const KEYWORDS2={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},LABEL={className:"symbol",begin:hljs.UNDERSCORE_IDENT_RE+"@"},SUBST={className:"subst",begin:/\$\{/,end:/\}/,contains:[hljs.C_NUMBER_MODE]},VARIABLE={className:"variable",begin:"\\$"+hljs.UNDERSCORE_IDENT_RE},STRING={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[VARIABLE,SUBST]},{begin:"'",end:"'",illegal:/\n/,contains:[hljs.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[hljs.BACKSLASH_ESCAPE,VARIABLE,SUBST]}]};SUBST.contains.push(STRING);const ANNOTATION_USE_SITE={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+hljs.UNDERSCORE_IDENT_RE+")?"},ANNOTATION={className:"meta",begin:"@"+hljs.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[hljs.inherit(STRING,{className:"string"}),"self"]}]},KOTLIN_NUMBER_MODE=NUMERIC,KOTLIN_NESTED_COMMENT=hljs.COMMENT("/\\*","\\*/",{contains:[hljs.C_BLOCK_COMMENT_MODE]}),KOTLIN_PAREN_TYPE={variants:[{className:"type",begin:hljs.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},KOTLIN_PAREN_TYPE2=KOTLIN_PAREN_TYPE;return KOTLIN_PAREN_TYPE2.variants[1].contains=[KOTLIN_PAREN_TYPE],KOTLIN_PAREN_TYPE.variants[1].contains=[KOTLIN_PAREN_TYPE2],{name:"Kotlin",aliases:["kt","kts"],keywords:KEYWORDS2,contains:[hljs.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),hljs.C_LINE_COMMENT_MODE,KOTLIN_NESTED_COMMENT,{className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},LABEL,ANNOTATION_USE_SITE,ANNOTATION,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:KEYWORDS2,relevance:5,contains:[{begin:hljs.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[hljs.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:KEYWORDS2,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[KOTLIN_PAREN_TYPE,hljs.C_LINE_COMMENT_MODE,KOTLIN_NESTED_COMMENT],relevance:0},hljs.C_LINE_COMMENT_MODE,KOTLIN_NESTED_COMMENT,ANNOTATION_USE_SITE,ANNOTATION,STRING,hljs.C_NUMBER_MODE]},KOTLIN_NESTED_COMMENT]},{begin:[/class|interface|trait/,/\s+/,hljs.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},hljs.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},ANNOTATION_USE_SITE,ANNOTATION]},STRING,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:"\n"},KOTLIN_NUMBER_MODE]}}),HighlightJS.registerLanguage("css",function(hljs){const regex=hljs.regex,modes=(hljs=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:hljs.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:hljs.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(hljs),STRINGS=[hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[modes.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},modes.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},modes.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+PSEUDO_CLASSES$1.join("|")+")"},{begin:":(:)?("+PSEUDO_ELEMENTS$1.join("|")+")"}]},modes.CSS_VARIABLE,{className:"attribute",begin:"\\b("+ATTRIBUTES$1.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[modes.BLOCK_COMMENT,modes.HEXCOLOR,modes.IMPORTANT,modes.CSS_NUMBER_MODE,...STRINGS,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...STRINGS,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},modes.FUNCTION_DISPATCH]},{begin:regex.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:MEDIA_FEATURES$1.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...STRINGS,modes.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+TAGS$1.join("|")+")\\b"}]}}),HighlightJS.registerLanguage("scss",function(hljs){const modes=(hljs=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:hljs.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[hljs.APOS_STRING_MODE,hljs.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:hljs.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(hljs),PSEUDO_ELEMENTS$12=PSEUDO_ELEMENTS,PSEUDO_CLASSES$12=PSEUDO_CLASSES,VARIABLE={className:"variable",begin:"(\\$[a-zA-Z-][a-zA-Z0-9_-]*)\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE,modes.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},modes.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+TAGS.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+PSEUDO_CLASSES$12.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+PSEUDO_ELEMENTS$12.join("|")+")"},VARIABLE,{begin:/\(/,end:/\)/,contains:[modes.CSS_NUMBER_MODE]},modes.CSS_VARIABLE,{className:"attribute",begin:"\\b("+ATTRIBUTES.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[modes.BLOCK_COMMENT,VARIABLE,modes.HEXCOLOR,modes.CSS_NUMBER_MODE,hljs.QUOTE_STRING_MODE,hljs.APOS_STRING_MODE,modes.IMPORTANT,modes.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:"@[a-z-]+",keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:MEDIA_FEATURES.join(" ")},contains:[{begin:"@[a-z-]+",className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},VARIABLE,hljs.QUOTE_STRING_MODE,hljs.APOS_STRING_MODE,modes.HEXCOLOR,modes.CSS_NUMBER_MODE]},modes.FUNCTION_DISPATCH]}}),HighlightJS.registerLanguage("xml",function(hljs){const regex=hljs.regex,TAG_NAME_RE=regex.concat(/[\p{L}_]/u,regex.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),XML_ENTITIES={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},XML_META_KEYWORDS={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},XML_META_PAR_KEYWORDS=hljs.inherit(XML_META_KEYWORDS,{begin:/\(/,end:/\)/}),APOS_META_STRING_MODE=hljs.inherit(hljs.APOS_STRING_MODE,{className:"string"}),QUOTE_META_STRING_MODE=hljs.inherit(hljs.QUOTE_STRING_MODE,{className:"string"}),TAG_INTERNALS={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:/[\p{L}0-9._:-]+/u,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[XML_ENTITIES]},{begin:/'/,end:/'/,contains:[XML_ENTITIES]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[XML_META_KEYWORDS,QUOTE_META_STRING_MODE,APOS_META_STRING_MODE,XML_META_PAR_KEYWORDS,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[XML_META_KEYWORDS,XML_META_PAR_KEYWORDS,QUOTE_META_STRING_MODE,APOS_META_STRING_MODE]}]}]},hljs.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},XML_ENTITIES,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[QUOTE_META_STRING_MODE]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[TAG_INTERNALS],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[TAG_INTERNALS],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:regex.concat(/</,regex.lookahead(regex.concat(TAG_NAME_RE,regex.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:TAG_NAME_RE,relevance:0,starts:TAG_INTERNALS}]},{className:"tag",begin:regex.concat(/<\//,regex.lookahead(regex.concat(TAG_NAME_RE,/>/))),contains:[{className:"name",begin:TAG_NAME_RE,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}),HighlightJS.registerLanguage("json",function(hljs){const LITERALS2=["true","false","null"],LITERALS_MODE={scope:"literal",beginKeywords:LITERALS2.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:LITERALS2},contains:[{className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{match:/[{}[\],:]/,className:"punctuation",relevance:0},hljs.QUOTE_STRING_MODE,LITERALS_MODE,hljs.C_NUMBER_MODE,hljs.C_LINE_COMMENT_MODE,hljs.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}),HighlightJS.registerLanguage("yaml",function(hljs){const LITERALS2="true false yes no null",URI_CHARACTERS="[\\w#;/?:@&=+$,.~*'()[\\]]+",STRING={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[hljs.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},CONTAINER_STRING=hljs.inherit(STRING,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),TIMESTAMP={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},VALUE_CONTAINER={end:",",endsWithParent:!0,excludeEnd:!0,keywords:LITERALS2,relevance:0},OBJECT={begin:/\{/,end:/\}/,contains:[VALUE_CONTAINER],illegal:"\\n",relevance:0},ARRAY={begin:"\\[",end:"\\]",contains:[VALUE_CONTAINER],illegal:"\\n",relevance:0},MODES2=[{className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+URI_CHARACTERS},{className:"type",begin:"!<"+URI_CHARACTERS+">"},{className:"type",begin:"!"+URI_CHARACTERS},{className:"type",begin:"!!"+URI_CHARACTERS},{className:"meta",begin:"&"+hljs.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+hljs.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},hljs.HASH_COMMENT_MODE,{beginKeywords:LITERALS2,keywords:{literal:LITERALS2}},TIMESTAMP,{className:"number",begin:hljs.C_NUMBER_RE+"\\b",relevance:0},OBJECT,ARRAY,{className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},STRING],VALUE_MODES=[...MODES2];return VALUE_MODES.pop(),VALUE_MODES.push(CONTAINER_STRING),VALUE_CONTAINER.contains=VALUE_MODES,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:MODES2}}),HighlightJS.registerLanguage("markdown",function(hljs){const INLINE_HTML={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},LINK={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:hljs.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},BOLD={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},ITALIC={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},BOLD_WITHOUT_ITALIC=hljs.inherit(BOLD,{contains:[]}),ITALIC_WITHOUT_BOLD=hljs.inherit(ITALIC,{contains:[]});BOLD.contains.push(ITALIC_WITHOUT_BOLD),ITALIC.contains.push(BOLD_WITHOUT_ITALIC);let CONTAINABLE=[INLINE_HTML,LINK];return[BOLD,ITALIC,BOLD_WITHOUT_ITALIC,ITALIC_WITHOUT_BOLD].forEach(m=>{m.contains=m.contains.concat(CONTAINABLE)}),CONTAINABLE=CONTAINABLE.concat(BOLD,ITALIC),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:CONTAINABLE},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:CONTAINABLE}]}]},INLINE_HTML,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},BOLD,ITALIC,{className:"quote",begin:"^>\\s+",contains:CONTAINABLE,end:"$"},{className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{begin:"^[-\\*]{3,}",end:"$"},LINK,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}),HighlightJS.registerLanguage("bash",function(hljs){const regex=hljs.regex,VAR={},BRACED_VAR={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[VAR]}]};Object.assign(VAR,{className:"variable",variants:[{begin:regex.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},BRACED_VAR]});const SUBST={className:"subst",begin:/\$\(/,end:/\)/,contains:[hljs.BACKSLASH_ESCAPE]},COMMENT=hljs.inherit(hljs.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),HERE_DOC={begin:/<<-?\s*(?=\w+)/,starts:{contains:[hljs.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},QUOTE_STRING={className:"string",begin:/"/,end:/"/,contains:[hljs.BACKSLASH_ESCAPE,VAR,SUBST]};SUBST.contains.push(QUOTE_STRING);const ARITHMETIC={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},hljs.NUMBER_MODE,VAR]},KNOWN_SHEBANG=hljs.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),FUNCTION={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[hljs.inherit(hljs.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],literal:["true","false"],built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]},contains:[KNOWN_SHEBANG,hljs.SHEBANG(),FUNCTION,ARITHMETIC,COMMENT,HERE_DOC,{match:/(\/[a-z._-]+)+/},QUOTE_STRING,{match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},VAR]}}),HighlightJS.registerLanguage("sql",function(hljs){const regex=hljs.regex,COMMENT_MODE=hljs.COMMENT("--","$"),RESERVED_FUNCTIONS=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],FUNCTIONS=RESERVED_FUNCTIONS,KEYWORDS2=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(keyword=>!RESERVED_FUNCTIONS.includes(keyword)),FUNCTION_CALL={match:regex.concat(/\b/,regex.either(...FUNCTIONS),/\s*\(/),relevance:0,keywords:{built_in:FUNCTIONS}};function kws_to_regex(list){return regex.concat(/\b/,regex.either(...list.map(kw=>kw.replace(/\s+/,"\\s+"))),/\b/)}const MULTI_WORD_KEYWORDS={scope:"keyword",match:kws_to_regex(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),relevance:0};return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:function(list,{exceptions:exceptions,when:when}={}){const qualifyFn=when;return exceptions=exceptions||[],list.map(item=>item.match(/\|\d+$/)||exceptions.includes(item)?item:qualifyFn(item)?`${item}|0`:item)}(KEYWORDS2,{when:x=>x.length<3}),literal:["true","false","unknown"],type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]},contains:[{scope:"type",match:kws_to_regex(["double precision","large object","with timezone","without timezone"])},MULTI_WORD_KEYWORDS,FUNCTION_CALL,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{match:/""/}]},hljs.C_NUMBER_MODE,hljs.C_BLOCK_COMMENT_MODE,COMMENT_MODE,{scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}});const LANG_MAP={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",py:"python",java:"java",c:"cpp",cpp:"cpp",cc:"cpp",cxx:"cpp",h:"cpp",hpp:"cpp",cs:"csharp",go:"go",rs:"rust",php:"php",rb:"ruby",swift:"swift",kt:"kotlin",css:"css",scss:"scss",sass:"scss",less:"css",html:"xml",htm:"xml",xml:"xml",svg:"xml",json:"json",yml:"yaml",yaml:"yaml",md:"markdown",markdown:"markdown",sh:"bash",bash:"bash",zsh:"bash",sql:"sql"};function highlightLines(content2,lang){if(!content2)return[];const lines=content2.split("\n");if(lang)try{return HighlightJS.highlight(content2,{language:lang}).value.split("\n")}catch{return lines}return lines}function FullFileDiffView({file_path:file_path,old_string:old_string,new_string:new_string}){const lineNumScrollRef=reactExports.useRef(null),codeScrollRef=reactExports.useRef(null);reactExports.useEffect(()=>{const codeEl=codeScrollRef.current,lineEl=lineNumScrollRef.current;if(!codeEl||!lineEl)return;const onScroll=()=>{lineEl.scrollTop=codeEl.scrollTop};return codeEl.addEventListener("scroll",onScroll),()=>codeEl.removeEventListener("scroll",onScroll)});const isDeleted=!new_string||""===new_string.trim(),isNew=!old_string||""===old_string.trim(),lang=function(filePath2){var _a;const ext=null==(_a=filePath2.split(".").pop())?void 0:_a.toLowerCase();return LANG_MAP[ext]||null}(file_path),oldHighlightedLines=reactExports.useMemo(()=>highlightLines(old_string||"",lang),[old_string,lang]),newHighlightedLines=reactExports.useMemo(()=>highlightLines(new_string||"",lang),[new_string,lang]),diffLines2=reactExports.useMemo(()=>{if(isNew){return(new_string||"").split("\n").map((text,i)=>({type:"add",oldNum:null,newNum:i+1,text:text}))}if(isDeleted){return(old_string||"").split("\n").map((text,i)=>({type:"del",oldNum:i+1,newNum:null,text:text}))}return function(oldStr,newStr){const changes=diffLines(oldStr,newStr),lines=[];let oldLineNum2=1,newLineNum2=1;for(const part of changes){const partLines=part.value.replace(/\n$/,"").split("\n");if(""!==part.value)for(const text of partLines)part.added?lines.push({type:"add",oldNum:null,newNum:newLineNum2++,text:text,oldIdx:null,newIdx:lines.filter(l=>"del"!==l.type).length}):part.removed?lines.push({type:"del",oldNum:oldLineNum2++,newNum:null,text:text,oldIdx:null,newIdx:null}):lines.push({type:"context",oldNum:oldLineNum2++,newNum:newLineNum2++,text:text,oldIdx:null,newIdx:null})}return lines}(old_string,new_string)},[old_string,new_string,isDeleted,isNew]),highlightedDiffLines=reactExports.useMemo(()=>{let oldIdx=0,newIdx=0;return diffLines2.map(dl=>{let html;return"del"===dl.type?(html=oldHighlightedLines[oldIdx]??"",oldIdx++):"add"===dl.type?(html=newHighlightedLines[newIdx]??"",newIdx++):(html=newHighlightedLines[newIdx]??"",oldIdx++,newIdx++),{...dl,html:html}})},[diffLines2,oldHighlightedLines,newHighlightedLines]),addedCount=highlightedDiffLines.filter(l=>"add"===l.type).length,deletedCount=highlightedDiffLines.filter(l=>"del"===l.type).length;return jsxRuntimeExports.jsxs("div",{className:styles$c_fullFileDiffView,children:[jsxRuntimeExports.jsxs("div",{className:styles$c_diffSummary,children:[addedCount>0&&jsxRuntimeExports.jsxs("span",{className:styles$c_addedBadge,children:["+",addedCount]}),deletedCount>0&&jsxRuntimeExports.jsxs("span",{className:styles$c_deletedBadge,children:["-",deletedCount]})]}),jsxRuntimeExports.jsxs("div",{className:styles$c_codeContainer,children:[jsxRuntimeExports.jsx("div",{className:styles$c_lineNumberCol,ref:lineNumScrollRef,children:highlightedDiffLines.map((dl,idx)=>{let numClass=styles$c_lineNumNormal;return"add"===dl.type?numClass=styles$c_lineNumAdd:"del"===dl.type&&(numClass=styles$c_lineNumDelete),jsxRuntimeExports.jsxs("div",{className:`${styles$c_lineNumRow} ${numClass}`,children:[jsxRuntimeExports.jsx("span",{className:styles$c_oldLineNum,children:dl.oldNum??""}),jsxRuntimeExports.jsx("span",{className:styles$c_newLineNum,children:dl.newNum??""})]},idx)})}),jsxRuntimeExports.jsxs("div",{className:styles$c_codeColWrap,children:[jsxRuntimeExports.jsx("div",{className:styles$c_codeCol,ref:codeScrollRef,children:jsxRuntimeExports.jsx("div",{className:styles$c_codeInner,children:highlightedDiffLines.map((dl,idx)=>{let lineClass;lineClass="add"===dl.type?styles$c_lineAdd:"del"===dl.type?styles$c_lineDelete:styles$c_lineNormal;const prefix2="add"===dl.type?"+":"del"===dl.type?"-":" ";return jsxRuntimeExports.jsxs("div",{className:`${styles$c_codeLine} ${lineClass}`,children:[jsxRuntimeExports.jsx("span",{className:styles$c_linePrefix,children:prefix2}),jsxRuntimeExports.jsx("span",{className:styles$c_lineContent,dangerouslySetInnerHTML:{__html:dl.html||" "}})]},idx)})})}),jsxRuntimeExports.jsx(DiffMiniMap,{diffLines:highlightedDiffLines,scrollRef:codeScrollRef})]})]})]})}const styles$a_gitDiffView="_gitDiffView_ypk84_1",styles$a_closing="_closing_ypk84_21",styles$a_header="_header_ypk84_36",styles$a_headerLeft="_headerLeft_ypk84_46",styles$a_backBtn="_backBtn_ypk84_54",styles$a_filePath="_filePath_ypk84_75",styles$a_diffBadge="_diffBadge_ypk84_91",styles$a_headerRight="_headerRight_ypk84_103",styles$a_closeBtn="_closeBtn_ypk84_109",styles$a_contentContainer="_contentContainer_ypk84_129",styles$a_loading="_loading_ypk84_135",styles$a_error="_error_ypk84_144",styles$a_binaryNotice="_binaryNotice_ypk84_155",styles$a_largeFileWarning="_largeFileWarning_ypk84_167",styles$a_fileSize="_fileSize_ypk84_180",styles$a_imagePreviewWrap="_imagePreviewWrap_ypk84_186",styles$a_imagePreview="_imagePreview_ypk84_186";function getFirstChangedLine(oldStr,newStr){const oldLines=(oldStr||"").split("\n"),newLines=(newStr||"").split("\n");for(let i=0;i<newLines.length;i++)if(oldLines[i]!==newLines[i])return i+1;return 1}function GitDiffView({filePath:filePath2,repoPath:repoPath,commitHash:commitHash2,onClose:onClose,onOpenFile:onOpenFile}){const[diffData,setDiffData]=reactExports.useState(null),[error2,setError]=reactExports.useState(null),[loading2,setLoading]=reactExports.useState(!0),[closing2,setClosing]=reactExports.useState(!1),[lightboxOpen,setLightboxOpen]=reactExports.useState(!1),mounted=reactExports.useRef(!0),containerRef=reactExports.useRef(null),handleClose=reactExports.useCallback(()=>{if(closing2)return;setClosing(!0);const el=containerRef.current;el?el.addEventListener("animationend",()=>onClose(),{once:!0}):onClose()},[closing2,onClose]);reactExports.useEffect(()=>{mounted.current=!0,setLoading(!0),setDiffData(null),setError(null),setLightboxOpen(!1);const repoParam=repoPath&&"."!==repoPath?`&repo=${encodeURIComponent(repoPath)}`:"",commitParam=commitHash2?`&commit=${encodeURIComponent(commitHash2)}`:"";return fetch(apiUrl(`/api/git-diff?files=${encodeURIComponent(filePath2)}${repoParam}${commitParam}`)).then(r=>r.ok?r.json():r.json().then(err=>{throw new Error(err.error||"Failed to load diff")}).catch(()=>{throw new Error(`HTTP ${r.status}`)})).then(data=>{mounted.current&&(data.diffs&&data.diffs[0]?setDiffData(data.diffs[0]):setError("No diff data available"),setLoading(!1))}).catch(err=>{mounted.current&&(setError(`${t("ui.fileLoadError")}: ${err.message}`),setLoading(!1))}),()=>{mounted.current=!1}},[filePath2,repoPath,commitHash2]);const resolvedPath=repoPath&&"."!==repoPath?`${repoPath}/${filePath2}`:filePath2;return jsxRuntimeExports.jsxs("div",{ref:containerRef,className:`${styles$a_gitDiffView}${closing2?` ${styles$a_closing}`:""}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$a_header,children:[jsxRuntimeExports.jsxs("div",{className:styles$a_headerLeft,children:[jsxRuntimeExports.jsx("button",{className:styles$a_backBtn,onClick:handleClose,title:t("ui.backToChat"),children:jsxRuntimeExports.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("polyline",{points:"15 18 9 12 15 6"})})}),jsxRuntimeExports.jsx("span",{className:styles$a_filePath,onClick:()=>{if(onOpenFile&&diffData){const line=getFirstChangedLine(diffData.old_content,diffData.new_content);onOpenFile(filePath2,line)}},role:"button",tabIndex:0,onKeyDown:e=>{if(("Enter"===e.key||" "===e.key)&&onOpenFile&&diffData){const line=getFirstChangedLine(diffData.old_content,diffData.new_content);onOpenFile(filePath2,line)}},children:resolvedPath}),jsxRuntimeExports.jsx("span",{className:styles$a_diffBadge,children:"DIFF"}),commitHash2&&jsxRuntimeExports.jsx("span",{className:styles$a_diffBadge,style:{marginLeft:4},title:commitHash2,children:commitHash2.substring(0,7)})]}),jsxRuntimeExports.jsx("div",{className:styles$a_headerRight,children:jsxRuntimeExports.jsx("button",{className:styles$a_closeBtn,onClick:handleClose,title:t("ui.backToChat"),children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntimeExports.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})})]}),jsxRuntimeExports.jsxs("div",{className:styles$a_contentContainer,children:[loading2&&jsxRuntimeExports.jsx("div",{className:styles$a_loading,children:t("ui.loading")}),error2&&jsxRuntimeExports.jsx("div",{className:styles$a_error,children:error2}),!loading2&&!error2&&diffData&&jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:diffData.is_large?jsxRuntimeExports.jsxs("div",{className:styles$a_largeFileWarning,children:[jsxRuntimeExports.jsx("p",{children:t("ui.largeFileWarning")}),jsxRuntimeExports.jsxs("p",{className:styles$a_fileSize,children:[t("ui.fileSize"),": ",(diffData.size/1048576).toFixed(2)," MB"]})]}):isImageFile(filePath2)&&!diffData.is_deleted?jsxRuntimeExports.jsxs("div",{className:styles$a_imagePreviewWrap,children:[jsxRuntimeExports.jsx("img",{className:styles$a_imagePreview,src:apiUrl(`/api/file-raw?path=${encodeURIComponent(resolvedPath)}`),alt:resolvedPath,onClick:()=>setLightboxOpen(!0)}),lightboxOpen&&jsxRuntimeExports.jsx(ImageLightbox,{src:apiUrl(`/api/file-raw?path=${encodeURIComponent(resolvedPath)}`),alt:resolvedPath,onClose:()=>setLightboxOpen(!1)})]}):diffData.is_binary?jsxRuntimeExports.jsx("div",{className:styles$a_binaryNotice,children:t("ui.binaryFileNotice")}):jsxRuntimeExports.jsx(FullFileDiffView,{file_path:filePath2,old_string:diffData.old_content,new_string:diffData.new_content})})]})]})}const styles$9_panel="_panel_sccpn_1",styles$9_panelGlobal="_panelGlobal_sccpn_20",styles$9_toolName="_toolName_sccpn_43",styles$9_command="_command_sccpn_47",styles$9_allowBtn="_allowBtn_sccpn_53",styles$9_allowSessionBtn="_allowSessionBtn_sccpn_54",styles$9_denyBtn="_denyBtn_sccpn_55",styles$9_borderSvg="_borderSvg_sccpn_60",styles$9_borderSvgInset="_borderSvgInset_sccpn_69",styles$9_borderRect="_borderRect_sccpn_73",styles$9_exiting="_exiting_sccpn_92",styles$9_header="_header_sccpn_96",styles$9_label="_label_sccpn_110",styles$9_subAgentBadge="_subAgentBadge_sccpn_117",styles$9_body="_body_sccpn_128",styles$9_detail="_detail_sccpn_148",styles$9_actions="_actions_sccpn_159",styles$9_autoApproveBtn="_autoApproveBtn_sccpn_165",styles$9_autoApproveActive="_autoApproveActive_sccpn_183";function ToolApprovalPanel({toolName:toolName2,toolInput:toolInput,requestId:requestId,onAllow:onAllow,onAllowSession:onAllowSession,onDeny:onDeny,visible:visible,global:isGlobal,autoApproveSeconds:autoApproveSeconds=0,onAutoApproveChange:onAutoApproveChange,modelName:modelName2,source:source2,queueDepth:queueDepth=0}){const panelRef=reactExports.useRef(null),allowRef=reactExports.useRef(null),prevFocusRef=reactExports.useRef(null),[show,setShow]=reactExports.useState(!1),[exiting2,setExiting]=reactExports.useState(!1),[countdown,setCountdown]=reactExports.useState(-1),countdownRef=reactExports.useRef(null),deniedRef=reactExports.useRef(!1);reactExports.useEffect(()=>{if(visible)setShow(!0),setExiting(!1),deniedRef.current=!1,autoApproveSeconds<=0&&(prevFocusRef.current=document.activeElement,requestAnimationFrame(()=>{var _a;return null==(_a=allowRef.current)?void 0:_a.focus()}));else if(show){setExiting(!0);const timer=setTimeout(()=>{setShow(!1),setExiting(!1)},200);return()=>clearTimeout(timer)}},[visible]),reactExports.useEffect(()=>(countdownRef.current&&(clearInterval(countdownRef.current),countdownRef.current=null),visible&&autoApproveSeconds>0&&requestId?(deniedRef.current=!1,setCountdown(autoApproveSeconds),countdownRef.current=setInterval(()=>{setCountdown(prev=>prev<=1?(clearInterval(countdownRef.current),countdownRef.current=null,0):prev-1)},1e3)):setCountdown(-1),()=>{countdownRef.current&&(clearInterval(countdownRef.current),countdownRef.current=null)}),[visible,autoApproveSeconds,requestId]),reactExports.useEffect(()=>{0===countdown&&!deniedRef.current&&visible&&requestId&&onAllow(requestId)},[countdown,visible,requestId,onAllow]);const handleDeny=reactExports.useCallback(id=>{deniedRef.current=!0,countdownRef.current&&(clearInterval(countdownRef.current),countdownRef.current=null),setCountdown(-1),onDeny(id)},[onDeny]),handleAutoApproveToggle=reactExports.useCallback(()=>{if(onAutoApproveChange){const enabling=autoApproveSeconds<=0;onAutoApproveChange(enabling?getAutoApproveDefault(modelName2):0),enabling&&requestId&&onAllow&&onAllow(requestId)}},[onAutoApproveChange,autoApproveSeconds,modelName2,requestId,onAllow]),handleKeyDown=reactExports.useCallback(e=>{var _a;if("Escape"!==e.key){if("Tab"===e.key){e.preventDefault();const buttons=null==(_a=panelRef.current)?void 0:_a.querySelectorAll("button");if(!(null==buttons?void 0:buttons.length))return;const arr=Array.from(buttons),idx=arr.indexOf(document.activeElement);arr[e.shiftKey?idx<=0?arr.length-1:idx-1:idx>=arr.length-1?0:idx+1].focus()}}else handleDeny(requestId)},[handleDeny,requestId]),displayText=reactExports.useMemo(()=>{if(!toolInput)return"";switch(toolName2){case"Bash":return toolInput.command||toolInput.description||"";case"Edit":case"Write":return toolInput.file_path||toolInput.description||"";case"NotebookEdit":return toolInput.notebook_path||toolInput.description||"";case"ExitPlanMode":return("string"==typeof toolInput.plan&&toolInput.plan.trim()?toolInput.plan:"")||(toolInput.planFilePath?`(plan @ ${toolInput.planFilePath})`:toolInput.description||"");default:return toolInput.description?toolInput.description:JSON.stringify(toolInput,null,2).slice(0,500)}},[toolName2,toolInput]),detailText=reactExports.useMemo(()=>{if(!toolInput)return null;if("Bash"===toolName2&&toolInput.description)return toolInput.description;if("Edit"===toolName2&&null!=toolInput.old_string){return`${String(toolInput.old_string).slice(0,80)} → ${String(toolInput.new_string).slice(0,80)}`}return null},[toolName2,toolInput]);if(!show)return null;const allowLabel=countdown>0?t("ui.permission.allowCountdown",{seconds:countdown}):t("ui.permission.allow"),autoApproveBtnLabel=autoApproveSeconds>0?t("ui.permission.autoApprove.disable"):t("ui.permission.autoApprove.enable",{seconds:getAutoApproveDefault(modelName2)});return jsxRuntimeExports.jsxs("div",{ref:panelRef,className:`${isGlobal?styles$9_panelGlobal:styles$9_panel}${exiting2?` ${styles$9_exiting}`:""}`,onKeyDown:handleKeyDown,children:[jsxRuntimeExports.jsx("svg",{className:`${styles$9_borderSvg} ${styles$9_borderSvgInset}`,preserveAspectRatio:"none",children:jsxRuntimeExports.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",rx:"12",ry:"12",fill:"none",stroke:"var(--color-approval-border)",strokeWidth:"1",strokeDasharray:"6 4",className:styles$9_borderRect})}),jsxRuntimeExports.jsxs("div",{className:styles$9_header,children:[jsxRuntimeExports.jsx("span",{className:styles$9_toolName,children:toolName2}),"pty"===source2&&jsxRuntimeExports.jsx("span",{className:styles$9_subAgentBadge,children:t("ui.subAgentApproval")}),queueDepth>0&&jsxRuntimeExports.jsx("span",{className:styles$9_subAgentBadge,children:t("ui.permission.queued",{n:queueDepth})}),jsxRuntimeExports.jsx("span",{className:styles$9_label,children:t("ui.permission.approvalRequired")})]}),jsxRuntimeExports.jsxs("div",{className:styles$9_body,children:[jsxRuntimeExports.jsx("pre",{className:styles$9_command,children:displayText}),detailText&&jsxRuntimeExports.jsx("div",{className:styles$9_detail,children:detailText})]}),jsxRuntimeExports.jsxs("div",{className:styles$9_actions,children:[onAutoApproveChange&&jsxRuntimeExports.jsx("button",{className:`${styles$9_autoApproveBtn}${autoApproveSeconds>0?` ${styles$9_autoApproveActive}`:""}`,onClick:handleAutoApproveToggle,children:autoApproveBtnLabel}),jsxRuntimeExports.jsx("button",{className:styles$9_denyBtn,onClick:()=>handleDeny(requestId),children:t("ui.permission.deny")}),onAllowSession&&jsxRuntimeExports.jsx("button",{className:styles$9_allowSessionBtn,onClick:()=>onAllowSession(requestId),children:t("ui.permission.allowSession")}),jsxRuntimeExports.jsx("button",{ref:allowRef,className:styles$9_allowBtn,onClick:()=>onAllow(requestId),children:allowLabel})]})]})}function getMessageText(msg){const c=null==msg?void 0:msg.content;if("string"==typeof c)return c;if(Array.isArray(c))for(const block of c)if("text"===(null==block?void 0:block.type)&&block.text)return block.text;return""}function classifyRequest(req,nextReq){var _a;if(isTeammate(req))return req.teammate?{type:"Teammate",subType:req.teammate}:(void 0===req._cachedTeammateName&&(req._cachedTeammateName=function(body2){var _a;const msgs=null==body2?void 0:body2.messages;if(!Array.isArray(msgs))return null;for(let i=msgs.length-1;i>=0;i--){const content2=msgs[i].content;if(Array.isArray(content2))for(const block of content2){if("tool_result"!==block.type)continue;const items=Array.isArray(block.content)?block.content:[block];for(const item of items){const text=item.text||("string"==typeof item.content?item.content:"");if(text&&text.includes('"sender"'))try{const parsed=JSON.parse(text);if(null==(_a=null==parsed?void 0:parsed.routing)?void 0:_a.sender)return parsed.routing.sender}catch{}}}}return null}(req.body)||null),{type:"Teammate",subType:req._cachedTeammateName});const syntheticSub=function(req){var _a;if(!isMainAgent(req))return null;const msgs=(null==(_a=req.body)?void 0:_a.messages)||[];if(!msgs.length)return null;const last=msgs[msgs.length-1];if(!last||"user"!==last.role)return null;const text=getMessageText(last).trim();if(!text)return null;for(const{subType:subType,pattern:pattern}of SYNTHETIC_PROMPTS)if(pattern.test(text))return subType;return null}(req);if(syntheticSub)return{type:"Synthetic",subType:syntheticSub};if(isMainAgent(req))return{type:"MainAgent",subType:null};if(req.isCountTokens||function(req){var _a;const msgs=null==(_a=req.body)?void 0:_a.messages;if(!Array.isArray(msgs)||1!==msgs.length)return!1;const msg=msgs[0];return"user"===msg.role&&"count"===msg.content}(req))return{type:"Count",subType:null};if(function(req,nextReq){var _a;const body2=req.body||{},tools=body2.tools,msgs=body2.messages||[];if(Array.isArray(tools)&&tools.length>0)return!1;if(1!==msgs.length||"user"!==msgs[0].role)return!1;const text=getMessageText(msgs[0]);if(!text)return!1;if("count"===text.trim())return!1;const trimmed=text.trim();if(/^Command:/m.test(text)||/^<policy_spec>/i.test(trimmed)||/^<task-notification>/i.test(trimmed))return!1;const sysText=getSystemText(body2);if(!sysText.includes("Claude Code"))return!1;if(/process Bash commands/i.test(sysText))return!1;if(/Extract any file paths/i.test(sysText))return!1;if(nextReq){const nextMsgs=(null==(_a=nextReq.body)?void 0:_a.messages)||[],sig=text.slice(0,80);if(nextMsgs.some(m=>{const c=null==m?void 0:m.content;return"string"==typeof c?c.includes(sig):!!Array.isArray(c)&&c.some(block=>"text"===(null==block?void 0:block.type)&&block.text&&block.text.includes(sig))}))return!0}return!1}(req,nextReq)){const text=getMessageText(((null==(_a=req.body)?void 0:_a.messages)||[])[0]);return/Implement the following plan:/i.test(text.trim())?{type:"Plan",subType:"Prompt"}:{type:"Preflight",subType:null}}const subType=function(req){const body2=req.body||{},sysText=getSystemText(body2);if(/Extract any file paths/i.test(sysText))return"Bash";if(/process Bash commands/i.test(sysText))return"Bash";if(/command execution specialist/i.test(sysText))return"Bash";if(/file search specialist/i.test(sysText))return"Search";if(/planning specialist/i.test(sysText))return"Plan";if(/general-purpose agent/i.test(sysText))return"General";const msgs=body2.messages||[];for(let i=msgs.length-1;i>=0;i--){if("user"!==msgs[i].role)continue;const text=getMessageText(msgs[i]);if(/^Command:/m.test(text))return"Bash";break}return null}(req);return{type:"SubAgent",subType:subType}}function formatRequestTag(type,subType){return"Teammate"===type&&subType?`Teammate:${subType}`:"Plan"===type&&subType?`Plan:${subType}`:"SubAgent"===type&&subType?`SubAgent:${subType}`:"Synthetic"===type&&subType?`Synthetic:${subType}`:type}function formatTeammateLabel(name,model){const displayName=name||"X";if(!model)return`Teammate: ${displayName}`;return`Teammate: ${displayName}(${model.replace(/^claude-/i,"").replace(/-\d{8}$/,"")})`}function classifyToolResultError(resultText,isError){const isPermissionDenied=isError&&resultText&&/doesn't want to proceed|Permission.*denied|rejected.*tool use|interrupted by user for tool use/i.test(resultText);return{isPermissionDenied:isPermissionDenied,isInputValidationError:isError&&resultText&&/InputValidationError|<tool_use_error>/i.test(resultText)&&!isPermissionDenied,isUltraplan:isPermissionDenied&&resultText&&/ultraplan/i.test(resultText)}}const _toolResultCache=new WeakMap;function getToolResultCache(messages){return _toolResultCache.get(messages)||null}function appendToolResultMap(state,messages,startIndex){var _a,_b;const{toolUseMap:toolUseMap,toolResultMap:toolResultMap,readContentMap:readContentMap,editSnapshotMap:editSnapshotMap,askAnswerMap:askAnswerMap,planApprovalMap:planApprovalMap,_fileState:_fileState}=state;for(let i=startIndex;i<messages.length;i++){const msg=messages[i];if("assistant"===msg.role&&Array.isArray(msg.content)){for(const block of msg.content)if("tool_use"===block.type){let parsed=block;if("string"==typeof block.input)try{const cleaned=block.input.replace(/^\[object Object\]/,"");parsed={...block,input:JSON.parse(cleaned)}}catch{}if(toolUseMap[parsed.id]=parsed,"Write"===parsed.name&&(null==(_a=parsed.input)?void 0:_a.file_path)&&/[/\\]\.claude[/\\]plans[/\\]/.test(parsed.input.file_path)&&parsed.input.content&&(state.latestPlanContent=parsed.input.content),"ExitPlanMode"===parsed.name&&parsed.input&&"object"==typeof parsed.input&&("string"==typeof parsed.input.plan&&parsed.input.plan.trim()&&(state.latestPlanContent=parsed.input.plan,state._planDirty=(state._planDirty||0)+1),"string"==typeof parsed.input.planFilePath&&parsed.input.planFilePath&&(state.latestPlanFilePath=parsed.input.planFilePath)),"Edit"===parsed.name&&parsed.input){const fp=parsed.input.file_path,oldStr=parsed.input.old_string,newStr=parsed.input.new_string;if(fp&&null!=oldStr&&null!=newStr&&_fileState[fp]){const entry=_fileState[fp];if(!(parsed.id in editSnapshotMap)&&(editSnapshotMap[parsed.id]={plainText:entry.plainText,lineNums:entry.lineNums.slice()},state._editOrder.push(parsed.id),state._editOrder.length>300)){editSnapshotMap[state._editOrder.shift()]=null}const idx=entry.plainText.indexOf(oldStr);if(idx>=0){const lineOffset=entry.plainText.substring(0,idx).split("\n").length-1,oldLineCount=oldStr.split("\n").length,newLineCount=newStr.split("\n").length,lineDelta=newLineCount-oldLineCount;if(entry.plainText=entry.plainText.substring(0,idx)+newStr+entry.plainText.substring(idx+oldStr.length),0!==lineDelta){const startNum=entry.lineNums[lineOffset]||lineOffset+1,newNums=[];for(let j=0;j<newLineCount;j++)newNums.push(startNum+j);entry.lineNums=[...entry.lineNums.slice(0,lineOffset),...newNums,...entry.lineNums.slice(lineOffset+oldLineCount).map(n=>n+lineDelta)]}/[/\\]\.claude[/\\]plans[/\\]/.test(fp)&&(state.latestPlanContent=entry.plainText)}}}}}else if("user"===msg.role&&Array.isArray(msg.content))for(const block of msg.content)if("tool_result"===block.type){const matchedTool=toolUseMap[block.tool_use_id];let label2=t("ui.toolReturn"),toolName2=null,toolInput=null;if(matchedTool)if(toolName2=matchedTool.name,toolInput=matchedTool.input,"Task"===matchedTool.name&&matchedTool.input){const st=matchedTool.input.subagent_type||"",desc=matchedTool.input.description||"";label2=`SubAgent: ${st}${desc?" — "+desc:""}`}else label2=t("ui.toolReturnNamed",{name:matchedTool.name});let resultText=extractToolResultText(block);resultText=internToolResult(resultText);const isError=!!block.is_error,{isPermissionDenied:isPermissionDenied,isInputValidationError:isInputValidationError,isUltraplan:isUltraplan}=classifyToolResultError(resultText,isError);if(toolResultMap[block.tool_use_id]={label:label2,toolName:toolName2,toolInput:toolInput,resultText:resultText,isError:isError,isPermissionDenied:isPermissionDenied,isInputValidationError:isInputValidationError,isUltraplan:isUltraplan},matchedTool&&"Read"===matchedTool.name&&(null==(_b=matchedTool.input)?void 0:_b.file_path)){readContentMap[matchedTool.input.file_path]=resultText;const readLines=resultText.split("\n"),plainLines=[],lineNums=[];for(const rl of readLines){const m=rl.match(/^\s*(\d+)[\t→](.*)$/);m&&(lineNums.push(parseInt(m[1],10)),plainLines.push(m[2]))}if(plainLines.length>0){const existing=_fileState[matchedTool.input.file_path];if(existing){const mergedMap=new Map,existingLines=existing.plainText.split("\n");for(let j=0;j<existing.lineNums.length;j++)mergedMap.set(existing.lineNums[j],existingLines[j]);for(let j=0;j<lineNums.length;j++)mergedMap.set(lineNums[j],plainLines[j]);const sortedKeys=[...mergedMap.keys()].sort((a,b)=>a-b);_fileState[matchedTool.input.file_path]={plainText:sortedKeys.map(k=>mergedMap.get(k)).join("\n"),lineNums:sortedKeys}}else _fileState[matchedTool.input.file_path]={plainText:plainLines.join("\n"),lineNums:lineNums}}}if(matchedTool&&"AskUserQuestion"===matchedTool.name){const parsed=parseAskAnswerText(resultText);0===Object.keys(parsed).length&&isPermissionDenied?askAnswerMap[block.tool_use_id]={__rejected__:!0}:askAnswerMap[block.tool_use_id]=parsed,state._askDirty=(state._askDirty||0)+1}if(matchedTool&&"ExitPlanMode"===matchedTool.name){if(isPermissionDenied){const userSaid=resultText.match(/the user said:\s*([\s\S]*)/i);planApprovalMap[block.tool_use_id]={status:isUltraplan?"ultraplan":"rejected",feedback:userSaid?userSaid[1].trim():""}}else planApprovalMap[block.tool_use_id]=parsePlanApproval(resultText);state._planDirty=(state._planDirty||0)+1,state.latestPlanContent=null,state.latestPlanFilePath=null}}}}function cachedBuildToolResultMap(messages){let cached=_toolResultCache.get(messages);return cached||(cached=function(messages){const state={toolUseMap:{},toolResultMap:{},readContentMap:{},editSnapshotMap:{},askAnswerMap:{},planApprovalMap:{},latestPlanContent:null,latestPlanFilePath:null,_fileState:{},_editOrder:[]};return appendToolResultMap(state,messages,0),state}(messages),_toolResultCache.set(messages,cached)),cached}function parseAskAnswerText(text){const answers={},re=/"([^"]+)"="([^"]*)"/g;let m;for(;null!==(m=re.exec(text));)answers[m[1]]=m[2];return answers}function parsePlanApproval(text){if(!text)return{status:"pending"};if(/User has approved/i.test(text)){const planMatch=text.match(/##\s*Approved Plan:\s*\n([\s\S]*)/i);return{status:"approved",planContent:planMatch?planMatch[1].trim():""}}if(/User rejected/i.test(text)){const feedbackMatch=text.match(/feedback:\s*(.+)/i)||text.match(/User rejected[^:]*:\s*(.+)/i);return{status:"rejected",feedback:feedbackMatch?feedbackMatch[1].trim():""}}return{status:"pending"}}function refreshPlanApprovalOnCachedItems(items,prevMap,nextMap){if(prevMap===nextMap)return items;let dirty=!1;const out=items.map(m=>{if(!m||!m.props||"assistant"!==m.props.role||!Array.isArray(m.props.content))return m;return m.props.content.some(b=>"tool_use"===b.type&&"ExitPlanMode"===b.name)?(dirty=!0,React__default.cloneElement(m,{planApprovalMap:nextMap})):m});return dirty?out:items}function refreshAskAnswerOnCachedItems(items,prevMap,nextMap){if(prevMap===nextMap)return items;let dirty=!1;const out=items.map(m=>{if(!m||!m.props||"assistant"!==m.props.role||!Array.isArray(m.props.content))return m;return m.props.content.some(b=>"tool_use"===b.type&&"AskUserQuestion"===b.name)?(dirty=!0,React__default.cloneElement(m,{askAnswerMap:nextMap})):m});return dirty?out:items}const END_REASON=Object.freeze({DELETE_CONFIRMED:"deleteConfirmed",SUCCESSOR_CREATE:"successorCreate",SHUTDOWN_REQUEST:"shutdownRequest",LOG_TAIL:"logTail"});const styles$8_teamActiveSpinner="_teamActiveSpinner_9y80g_1",styles$8_teamPopover="_teamPopover_9y80g_17",styles$8_teamPopoverTitle="_teamPopoverTitle_9y80g_23",styles$8_teamPopoverItem="_teamPopoverItem_9y80g_31",styles$8_teamPopoverName="_teamPopoverName_9y80g_45",styles$8_teamPopoverMeta="_teamPopoverMeta_9y80g_53",styles$8_teamPopoverTime="_teamPopoverTime_9y80g_60",styles$8_teamModalBody="_teamModalBody_9y80g_66",styles$8_teamGanttToggle="_teamGanttToggle_9y80g_76",styles$8_ganttExportBtn="_ganttExportBtn_9y80g_90",styles$8_teamGanttWrap="_teamGanttWrap_9y80g_106",styles$8_teamGanttResizer="_teamGanttResizer_9y80g_115",styles$8_teamGanttRow="_teamGanttRow_9y80g_128",styles$8_teamGanttLabel="_teamGanttLabel_9y80g_135",styles$8_teamGanttTrack="_teamGanttTrack_9y80g_147",styles$8_teamGanttBar="_teamGanttBar_9y80g_156",styles$8_teamGanttDiamond="_teamGanttDiamond_9y80g_164",styles$8_teamGanttArrows="_teamGanttArrows_9y80g_181",styles$8_teamGanttIndicator="_teamGanttIndicator_9y80g_191",styles$8_teamModalLayout="_teamModalLayout_9y80g_203",styles$8_teamAgentCards="_teamAgentCards_9y80g_208",styles$8_teamAgentCard="_teamAgentCard_9y80g_208",styles$8_teamAgentCardActive="_teamAgentCardActive_9y80g_230",styles$8_teamAgentCardHeader="_teamAgentCardHeader_9y80g_234",styles$8_teamAgentAvatar="_teamAgentAvatar_9y80g_240",styles$8_teamAgentName="_teamAgentName_9y80g_258",styles$8_teamAgentType="_teamAgentType_9y80g_267",styles$8_teamAgentStatus="_teamAgentStatus_9y80g_273",styles$8_teamAgentPopover="_teamAgentPopover_9y80g_278",styles$8_teamAgentPopTeammateMsg="_teamAgentPopTeammateMsg_9y80g_283",styles$8_teamAgentPopTmSummary="_teamAgentPopTmSummary_9y80g_291",styles$8_teamAgentPopTmContent="_teamAgentPopTmContent_9y80g_298",styles$8_teamAgentPopTask="_teamAgentPopTask_9y80g_304",styles$8_teamAgentPopMsg="_teamAgentPopMsg_9y80g_313",styles$8_teammateReportEntry="_teammateReportEntry_9y80g_326",styles$8_teammateReportHeader="_teammateReportHeader_9y80g_334",styles$8_teammateReportName="_teammateReportName_9y80g_343",styles$8_teammateReportSummary="_teammateReportSummary_9y80g_349",styles$8_teammateReportBody="_teammateReportBody_9y80g_358",styles$8_teamModalContent="_teamModalContent_9y80g_364",styles$8_teamBtnRelative="_teamBtnRelative_9y80g_372",styles$8_ganttLabelLead="_ganttLabelLead_9y80g_376",styles$8_ganttLabelAgent="_ganttLabelAgent_9y80g_381",styles$8_ganttTimeAxisRow="_ganttTimeAxisRow_9y80g_385",styles$8_ganttTimeAxisTrack="_ganttTimeAxisTrack_9y80g_389",styles$8_ganttTickLabel="_ganttTickLabel_9y80g_395",styles$8_teamPopoverStatus="_teamPopoverStatus_9y80g_403",styles$8_statusConverged="_statusConverged_9y80g_409",styles$8_statusPending="_statusPending_9y80g_415",styles$8_statusPossiblyAlive="_statusPossiblyAlive_9y80g_420",styles$8_statusReused="_statusReused_9y80g_425",styles$8_ganttIndicatorInitial="_ganttIndicatorInitial_9y80g_430",styles$8_teamModalTitle="_teamModalTitle_9y80g_434",styles$8_teamLeadCard="_teamLeadCard_9y80g_439",styles$8_agentNoMessages="_agentNoMessages_9y80g_443",styles$8_teamAgentCardClickable="_teamAgentCardClickable_9y80g_448",styles$8_agentStatusDurSuffix="_agentStatusDurSuffix_9y80g_453";function deriveDisplayStatus(team,runtimeStatus){if(!team.endTime)return{glyph:"●",className:"",tooltipKey:"ui.teamSession.status.active"};if(function(team){return!!team&&(team.endReason===END_REASON.DELETE_CONFIRMED||team.endReason===END_REASON.SUCCESSOR_CREATE)}(team))return{glyph:"✓",className:"",colorVar:"var(--color-success)",tooltipKey:team.endReason===END_REASON.SUCCESSOR_CREATE?"ui.teamSession.status.successorCreate":"ui.teamSession.status.done"};const rt=runtimeStatus;if(rt){if("dead"===rt.state||"residue"===rt.state)return{glyph:"✓",className:styles$8_statusConverged,tooltipKey:"residue"===rt.state?"ui.teamSession.status.residue":"ui.teamSession.status.converged"};if("possiblyAlive"===rt.state)return{glyph:"⏱",className:styles$8_statusPossiblyAlive,tooltipKey:"ui.teamSession.status.possiblyAlive"};if("reused"===rt.state)return{glyph:"⏱",className:styles$8_statusReused,tooltipKey:"ui.teamSession.status.reused"}}return{glyph:"⏱",className:styles$8_statusPending,colorVar:"var(--text-tertiary)",tooltipKey:"ui.teamSession.status.pending"}}function isWeakEnd(team){const r=team.endReason;return r===END_REASON.SHUTDOWN_REQUEST||r===END_REASON.LOG_TAIL||!(r||!team._hasInferredEnd&&!team._inferredEnd)}function TeamButton({requests:requests,onOpenSession:onOpenSession,navBtnClass:navBtnClass}){const teamSessions=reactExports.useMemo(()=>function(requests){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s;const teams=[];let currentTeamIdx=-1;function findToolResult(toolUseId,fromRequestIdx){var _a2,_b2;for(let j=fromRequestIdx+1;j<requests.length&&j<=fromRequestIdx+10;j++){const entry=(null==(_a2=requests[j])?void 0:_a2._slimmed)?restoreSlimmedEntry(requests[j],requests):requests[j],msgs=null==(_b2=null==entry?void 0:entry.body)?void 0:_b2.messages;if(Array.isArray(msgs))for(const msg of msgs){const blocks="user"===msg.role&&Array.isArray(msg.content)?msg.content:[];for(const b of blocks)if("tool_result"===b.type&&b.tool_use_id===toolUseId)return"string"==typeof b.content?b.content:JSON.stringify(b.content||"")}}return null}function isDeleteSuccessful(resultText){return!(resultText&&!resultText.includes('"success":true')&&!resultText.includes('"success": true')&&!resultText.includes("Cleaned up")&&resultText.includes("Cannot cleanup"))}for(let i=0;i<requests.length;i++){const req=requests[i],respContent=null==(_b=null==(_a=req.response)?void 0:_a.body)?void 0:_b.content;if(Array.isArray(respContent))for(const block of respContent){if("tool_use"!==block.type)continue;const name=block.name,input="string"==typeof block.input?(()=>{try{return JSON.parse(block.input)}catch{return{}}})():block.input||{};if("TeamCreate"===name){const createResult=findToolResult(block.id,i);if(createResult&&(createResult.includes('"error":')||createResult.includes('"error" :')||createResult.includes("Already leading team")))continue;const teamName=input.team_name||input.teamName||"unknown",ts=req.timestamp||(null==(_c=req.response)?void 0:_c.timestamp);currentTeamIdx>=0&&!teams[currentTeamIdx].endTime&&(teams[currentTeamIdx].endTime=ts,teams[currentTeamIdx].endRequestIndex=Math.max(teams[currentTeamIdx].requestIndex,i-1),teams[currentTeamIdx].endReason=END_REASON.SUCCESSOR_CREATE,teams[currentTeamIdx]._hasInferredEnd=!0);const team={name:teamName,startTime:ts,endTime:null,requestIndex:i,endRequestIndex:null,taskCount:0,teammateCount:0,_teammates:new Set};teams.push(team),currentTeamIdx=teams.length-1}else if("TeamDelete"===name){const resultText=findToolResult(block.id,i);if(!isDeleteSuccessful(resultText))continue;const ts=req.timestamp||(null==(_d=req.response)?void 0:_d.timestamp);if(currentTeamIdx<0){let teamName="unknown";try{teamName=JSON.parse(resultText).team_name||teamName}catch{}let startIdx=0,startTs=(null==(_e=requests[0])?void 0:_e.timestamp)||(null==(_g=null==(_f=requests[0])?void 0:_f.response)?void 0:_g.timestamp);for(let k=0;k<i;k++){const kResp=null==(_j=null==(_i=null==(_h=requests[k])?void 0:_h.response)?void 0:_i.body)?void 0:_j.content;if(Array.isArray(kResp)){for(const kb of kResp)if("tool_use"===kb.type&&"Agent"===kb.name){const kInp="string"==typeof kb.input?(()=>{try{return JSON.parse(kb.input)}catch{return{}}})():kb.input||{};if((kInp.team_name||kInp.teamName)===teamName){startIdx=k,startTs=(null==(_k=requests[k])?void 0:_k.timestamp)||(null==(_m=null==(_l=requests[k])?void 0:_l.response)?void 0:_m.timestamp);break}}if(startIdx>0)break}}const team={name:teamName,startTime:startTs,endTime:ts,endReason:END_REASON.DELETE_CONFIRMED,requestIndex:startIdx,endRequestIndex:i,taskCount:0,teammateCount:0,_teammates:new Set,_inferredStart:!0};for(let k=startIdx;k<i;k++){const kResp=null==(_p=null==(_o=null==(_n=requests[k])?void 0:_n.response)?void 0:_o.body)?void 0:_p.content;if(Array.isArray(kResp))for(const kb of kResp)if("tool_use"===kb.type)if("Agent"===kb.name){const an=("string"==typeof kb.input?(()=>{try{return JSON.parse(kb.input)}catch{return{}}})():kb.input||{}).name||"";team._teammates.has(an)||(team._teammates.add(an),team.teammateCount++)}else"TaskCreate"!==kb.name&&"TaskUpdate"!==kb.name||team.taskCount++}teams.push(team);continue}teams[currentTeamIdx].endTime=ts,teams[currentTeamIdx].endRequestIndex=i,teams[currentTeamIdx].endReason=END_REASON.DELETE_CONFIRMED,currentTeamIdx=-1}else if("SendMessage"===name){if(currentTeamIdx>=0&&"shutdown_request"===(null==(_q=input.message)?void 0:_q.type)){const shutdownTs=req.timestamp||(null==(_r=req.response)?void 0:_r.timestamp);teams[currentTeamIdx]._lastShutdownTime=shutdownTs,teams[currentTeamIdx]._lastShutdownRequestIdx=i}}else if("TaskCreate"===name||"TaskUpdate"===name)currentTeamIdx>=0&&teams[currentTeamIdx].taskCount++;else if("Agent"===name){const teamName=input.team_name||input.teamName,agentName=input.name||"";let targetIdx=-1;if(teamName)for(let ti=teams.length-1;ti>=0;ti--)if(teams[ti].name===teamName&&!teams[ti].endTime){targetIdx=ti;break}if(targetIdx<0&¤tTeamIdx>=0&&(targetIdx=currentTeamIdx),targetIdx>=0){const t2=teams[targetIdx];t2._teammates.has(agentName)||(t2._teammates.add(agentName),t2.teammateCount++)}}}}for(const team of teams)if(!team.endTime)if(team._lastShutdownTime)team.endTime=team._lastShutdownTime,team.endRequestIndex=team._lastShutdownRequestIdx,team.endReason=END_REASON.SHUTDOWN_REQUEST,team._hasInferredEnd=!0;else{const lastReq=requests[requests.length-1],lastTs=(null==(_s=null==lastReq?void 0:lastReq.response)?void 0:_s.timestamp)||(null==lastReq?void 0:lastReq.timestamp);lastTs&&team.startTime!==lastTs&&(team.endTime=lastTs,team.endRequestIndex=requests.length-1,team.endReason=END_REASON.LOG_TAIL,team._hasInferredEnd=!0)}return teams}(requests),[requests]),[popoverOpen,setPopoverOpen]=reactExports.useState(!1),[runtimeMap,setRuntimeMap]=reactExports.useState({}),classifyTeams=reactExports.useCallback((teams,nowMs)=>{const historical={},fresh=[];for(const team of teams){if(!isWeakEnd(team))continue;const key=`${team.name}@${team.startTime}`,endMs=team.endTime?Date.parse(team.endTime):null;endMs&&nowMs-endMs>864e5?historical[key]={state:"dead",queriedAt:nowMs,historical:!0}:fresh.push({key:key,name:team.name,endTime:endMs})}return{historical:historical,fresh:fresh}},[]);if(reactExports.useEffect(()=>{if(!popoverOpen||0===teamSessions.length)return;const now=Date.now(),{historical:historical,fresh:fresh}=classifyTeams(teamSessions,now),ctrl=new AbortController;return setRuntimeMap(prev=>{const merged={...prev};for(const[k,v]of Object.entries(historical))merged[k]||(merged[k]=v);const needQuery=fresh.filter(q=>{const c=merged[q.key];return!c||now-c.queriedAt>=3e5});return needQuery.length>0&&fetch(apiUrl("/api/team-status"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({teams:needQuery.map(q=>({name:q.name,endTime:q.endTime}))}),signal:ctrl.signal}).then(r=>r.ok?r.json():Promise.reject(new Error("HTTP "+r.status))).then(data=>{var _a;const addl={},t2=Date.now();for(const q of needQuery){const st=null==(_a=null==data?void 0:data.statuses)?void 0:_a[q.name];st&&(addl[q.key]={...st,queriedAt:t2})}Object.keys(addl).length>0&&setRuntimeMap(p=>({...p,...addl}))}).catch(err=>{err.name}),merged}),()=>ctrl.abort()},[popoverOpen,teamSessions,classifyTeams]),0===teamSessions.length)return null;const content2=jsxRuntimeExports.jsxs("div",{className:styles$8_teamPopover,children:[jsxRuntimeExports.jsxs("div",{className:styles$8_teamPopoverTitle,children:[t("ui.teamSessions")," (",teamSessions.length,")"]}),teamSessions.map((team,i)=>{const time=team.startTime?new Date(team.startTime).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",rtKey=`${team.name}@${team.startTime}`,rt=runtimeMap[rtKey],disp=deriveDisplayStatus(team,rt),style=disp.colorVar?{color:disp.colorVar}:void 0,statusEl=jsxRuntimeExports.jsx("span",{className:`${styles$8_teamPopoverStatus} ${disp.className||""}`,style:style,children:disp.glyph});return jsxRuntimeExports.jsxs("div",{className:styles$8_teamPopoverItem,onClick:()=>onOpenSession(team),children:[jsxRuntimeExports.jsx(Tooltip,{title:t(disp.tooltipKey),children:statusEl}),jsxRuntimeExports.jsx("span",{className:styles$8_teamPopoverName,children:team.name}),jsxRuntimeExports.jsxs("span",{className:styles$8_teamPopoverMeta,children:[team.teammateCount,"p · ",team.taskCount,"t"]}),jsxRuntimeExports.jsx("span",{className:styles$8_teamPopoverTime,children:time})]},i)})]}),hasActiveTeam=teamSessions.some(s=>!s.endTime||isWeakEnd(s));return jsxRuntimeExports.jsx(Popover,{content:content2,trigger:"hover",placement:"rightTop",onOpenChange:setPopoverOpen,overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-light)",padding:0},children:jsxRuntimeExports.jsxs("button",{className:`${navBtnClass||""} ${styles$8_teamBtnRelative}`,title:t("ui.teamSessions"),children:[jsxRuntimeExports.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),jsxRuntimeExports.jsx("circle",{cx:"9",cy:"7",r:"4"}),jsxRuntimeExports.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),jsxRuntimeExports.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),hasActiveTeam&&jsxRuntimeExports.jsx("span",{className:styles$8_teamActiveSpinner})]})})}function TeamGantt({teamAgents:teamAgents,teamTotalStart:teamTotalStart,teamTotalEnd:teamTotalEnd,leadSegments:leadSegments,ganttWrapRef:ganttWrapRef,ganttIndicatorRef:ganttIndicatorRef,ganttHeight:ganttHeight,onGanttHeightChange:onGanttHeightChange}){const[ganttOpen,setGanttOpen]=reactExports.useState(!0);if(!teamAgents||0===teamAgents.length)return null;const totalMs=teamTotalEnd-teamTotalStart||1,pct=ms=>((ms-teamTotalStart)/totalMs*100).toFixed(2),widthPct=(start,end)=>((end-start)/totalMs*100).toFixed(2),ticks=[];for(let i=0;i<=4;i++){const d=new Date(teamTotalStart+totalMs*i/4);ticks.push({pct:25*i,label:d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})})}return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:styles$8_teamGanttToggle,onClick:()=>setGanttOpen(prev=>!prev),children:[ganttOpen?"▼":"▶"," Timeline",ganttOpen&&jsxRuntimeExports.jsx("span",{className:styles$8_ganttExportBtn,title:t("ui.exportTimelinePng")||"Export as PNG",onClick:e=>{e.stopPropagation();const wrap=ganttWrapRef.current;if(!wrap)return;const prevMaxH=wrap.style.maxHeight,prevH=wrap.style.height,prevOverflow=wrap.style.overflow;wrap.style.maxHeight="none",wrap.style.height="auto",wrap.style.overflow="visible",__vitePreload(async()=>{const{default:html2canvas}=await import("./html2canvas.esm-HFdlUwfn.js");return{default:html2canvas}},[]).then(({default:html2canvas})=>{html2canvas(wrap,{backgroundColor:"#0a0a0a",scale:2,useCORS:!0}).then(canvas=>{wrap.style.maxHeight=prevMaxH,wrap.style.height=prevH,wrap.style.overflow=prevOverflow;const link=document.createElement("a");link.download=`team-timeline-${Date.now()}.png`,link.href=canvas.toDataURL("image/png"),link.click()}).catch(()=>{wrap.style.maxHeight=prevMaxH,wrap.style.height=prevH,wrap.style.overflow=prevOverflow})}).catch(()=>{wrap.style.maxHeight=prevMaxH,wrap.style.height=prevH,wrap.style.overflow=prevOverflow})},children:jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),jsxRuntimeExports.jsx("polyline",{points:"7 10 12 15 17 10"}),jsxRuntimeExports.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),ganttOpen&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{ref:ganttWrapRef,className:styles$8_teamGanttWrap,style:ganttHeight?{maxHeight:"none",height:ganttHeight}:void 0,children:[jsxRuntimeExports.jsxs("div",{className:styles$8_teamGanttRow,children:[jsxRuntimeExports.jsx("div",{className:`${styles$8_teamGanttLabel} ${styles$8_ganttLabelLead}`,children:"team-lead"}),jsxRuntimeExports.jsxs("div",{className:styles$8_teamGanttTrack,children:[leadSegments&&leadSegments.map((seg,i)=>{const bgColor="thinking"===seg.label?"var(--color-code-purple)":"report-received"===seg.label?"var(--color-success)":"var(--color-primary)",op="idle"===seg.label?.25:"text"===seg.label?.5:"thinking"===seg.label?.4:"report-received"===seg.label?.6:.7;return jsxRuntimeExports.jsx("div",{className:styles$8_teamGanttBar,title:seg.label,style:{left:pct(seg.start)+"%",width:widthPct(seg.start,seg.end)+"%",background:bgColor,opacity:op}},`b${i}`)}),leadSegments&&leadSegments.filter(s=>"idle"!==s.label).map((seg,i)=>{const dColor="thinking"===seg.label?"var(--color-code-purple)":"report-received"===seg.label?"var(--color-success)":"var(--color-primary)";return jsxRuntimeExports.jsx("span",{title:{create:"Team Created",tasks:"Tasks Created",spawn:"Agents Spawned",msg:"SendMessage",cleanup:"Team Cleanup",text:"Status Update",thinking:"Thinking...","report-received":"Report Received"}[seg.label]||seg.label,className:styles$8_teamGanttDiamond,style:{left:pct(seg.start)+"%",color:dColor},children:"◆"},`d${i}`)})]})]}),teamAgents.map((ag,i)=>jsxRuntimeExports.jsxs("div",{className:styles$8_teamGanttRow,children:[jsxRuntimeExports.jsx("div",{className:`${styles$8_teamGanttLabel} ${styles$8_ganttLabelAgent}`,children:ag.name}),jsxRuntimeExports.jsxs("div",{className:styles$8_teamGanttTrack,children:[ag.segments.map((seg,si)=>{seg.label.startsWith("tool:");const op="spawn"===seg.label?.2:"claim"===seg.label?.7:"done"===seg.label?.4:"shutdown"===seg.label?.1:"report"===seg.label?.9:.5;return jsxRuntimeExports.jsx("div",{className:styles$8_teamGanttBar,title:seg.label,style:{left:pct(seg.start)+"%",width:widthPct(seg.start,seg.end)+"%",background:"var(--text-tertiary)",opacity:op}},`b${si}`)}),ag.events.filter(ev=>!ev.label.startsWith("tool:")).map((ev,ei)=>{const tip={spawn:"Agent Spawned",claim:"Task Claimed",done:"Task Completed",shutdown:"Shutdown Request","msg-in":"Message Received",report:"Report Submitted"}[ev.label]||ev.label;return jsxRuntimeExports.jsx("span",{title:`${ag.name}: ${tip}`,className:`${styles$8_teamGanttDiamond} ${styles$8_ganttLabelAgent}`,style:{left:pct(ev.ts)+"%"},children:"◆"},`d${ei}`)})]})]},i)),jsxRuntimeExports.jsxs("div",{className:`${styles$8_teamGanttRow} ${styles$8_ganttTimeAxisRow}`,children:[jsxRuntimeExports.jsx("div",{className:styles$8_teamGanttLabel}),jsxRuntimeExports.jsx("div",{className:`${styles$8_teamGanttTrack} ${styles$8_ganttTimeAxisTrack}`,children:ticks.map((tk,i)=>jsxRuntimeExports.jsx("span",{className:styles$8_ganttTickLabel,style:{left:tk.pct+"%"},children:tk.label},i))})]}),(()=>{const arrows=[];if(teamAgents.forEach((ag,ai)=>{const agentY=25*(ai+1)+12.5;if(ag.doneTime){const doneMs=new Date(ag.doneTime).getTime();arrows.push({key:`${ai}-done`,xPct:pct(doneMs),fromY:agentY,toY:12.5,color:"var(--color-warning-light)"})}ag.events.filter(ev=>"report"===ev.label).forEach((ev,ei)=>{arrows.push({key:`${ai}-rpt-${ei}`,xPct:pct(ev.ts),fromY:agentY,toY:12.5,color:"var(--color-success)"})})}),0===arrows.length)return null;const totalH=25*(teamAgents.length+2);return jsxRuntimeExports.jsxs("svg",{className:styles$8_teamGanttArrows,style:{height:totalH},children:[jsxRuntimeExports.jsxs("defs",{children:[jsxRuntimeExports.jsx("marker",{id:"gantt-arrow-yellow",markerWidth:"8",markerHeight:"8",refX:"6",refY:"4",orient:"auto",children:jsxRuntimeExports.jsx("path",{d:"M0,1 L7,4 L0,7 Z",fill:"var(--color-warning-light)"})}),jsxRuntimeExports.jsx("marker",{id:"gantt-arrow-green",markerWidth:"8",markerHeight:"8",refX:"6",refY:"4",orient:"auto",children:jsxRuntimeExports.jsx("path",{d:"M0,1 L7,4 L0,7 Z",fill:"var(--color-success)"})})]}),arrows.map(a=>jsxRuntimeExports.jsx("line",{x1:a.xPct+"%",y1:a.fromY,x2:a.xPct+"%",y2:a.toY+5,stroke:a.color,strokeWidth:"1.5",strokeDasharray:"4,3",opacity:"0.7",markerEnd:"var(--color-success)"===a.color?"url(#gantt-arrow-green)":"url(#gantt-arrow-yellow)"},a.key))]})})(),jsxRuntimeExports.jsx("div",{ref:ganttIndicatorRef,className:`${styles$8_teamGanttIndicator} ${styles$8_ganttIndicatorInitial}`})]}),jsxRuntimeExports.jsx("div",{className:styles$8_teamGanttResizer,onMouseDown:e=>{e.preventDefault();const wrap=ganttWrapRef.current;if(!wrap)return;const startY=e.clientY,startH=wrap.getBoundingClientRect().height,onMove=ev=>{const h=Math.max(60,startH+ev.clientY-startY);onGanttHeightChange(h)},onUp=()=>{document.removeEventListener("mousemove",onMove),document.removeEventListener("mouseup",onUp)};document.addEventListener("mousemove",onMove),document.addEventListener("mouseup",onUp)}})]})]})}function TeamModal({session:session,requests:requests,mainAgentSessions:mainAgentSessions,collapseToolResults:collapseToolResults,expandThinking:expandThinking,userProfile:userProfile,onViewRequest:onViewRequest,isHistoryLog:isHistoryLog,onClose:onClose}){const modalBodyRef=reactExports.useRef(null),ganttIndicatorRef=reactExports.useRef(null),ganttWrapRef=reactExports.useRef(null),ganttTrackElRef=reactExports.useRef(null),scrollRafRef=reactExports.useRef(null),[activeAgentCard,setActiveAgentCard]=reactExports.useState(null),[ganttHeight,setGanttHeight]=reactExports.useState(null);reactExports.useEffect(()=>()=>{scrollRafRef.current&&cancelAnimationFrame(scrollRafRef.current)},[]);const dataCacheRef=reactExports.useRef({team:null,requests:null,mainAgentSessions:null,result:null}),modalData=reactExports.useMemo(()=>{if(!session)return null;const c=dataCacheRef.current;if(c.team===session&&c.requests===requests&&c.mainAgentSessions===mainAgentSessions)return c.result;const result=function(team,requests,mainAgentSessions){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,_w;const startIdx=team.requestIndex,endIdx=null!=team.endRequestIndex?team.endRequestIndex+1:requests.length,teamRequests=requests.slice(startIdx,endIdx),teamStartTime=team.startTime,teamEndTime=team.endTime||(null==(_b=null==(_a=requests[endIdx-1])?void 0:_a.response)?void 0:_b.timestamp)||(null==(_c=requests[endIdx-1])?void 0:_c.timestamp),tsToIndex={};let modelName2=null;for(let i=startIdx;i<endIdx&&i<requests.length;i++){const req=requests[i];req.timestamp&&(tsToIndex[req.timestamp]=i);const effective=getEffectiveModel(req);effective&&(modelName2=effective)}const modelInfo=getModelInfo(modelName2),entries=[];let hasUserMsg=!1;if(mainAgentSessions){let closestBeforeTs=null;for(const session of mainAgentSessions)for(const msg of session.messages||[]){const ts=msg._timestamp;ts&&"user"===msg.role&&ts<=teamStartTime&&(!closestBeforeTs||ts>closestBeforeTs)&&(closestBeforeTs=ts)}const effectiveStart=closestBeforeTs||teamStartTime;for(const session of mainAgentSessions)for(const msg of session.messages||[]){const ts=msg._timestamp;if(!ts||ts<effectiveStart)continue;if(teamEndTime&&ts>teamEndTime)continue;if("user"!==msg.role)continue;const content2=msg.content;if(Array.isArray(content2)){const{textBlocks:textBlocks}=classifyUserContent(content2);for(const tb of textBlocks)tb.text&&tb.text.trim()&&(entries.push({type:"user",text:tb.text,timestamp:ts}),hasUserMsg=!0)}else"string"!=typeof content2||isSystemText(content2)||(entries.push({type:"user",text:content2,timestamp:ts}),hasUserMsg=!0)}}if(!hasUserMsg){const tcRaw=requests[team.requestIndex],tcReq=(null==tcRaw?void 0:tcRaw._slimmed)?restoreSlimmedEntry(tcRaw,requests):tcRaw,tcMsgs=(null==(_d=null==tcReq?void 0:tcReq.body)?void 0:_d.messages)||[];for(let m=tcMsgs.length-1;m>=0;m--){if("user"!==tcMsgs[m].role)continue;const c=tcMsgs[m].content;if(Array.isArray(c)){const{textBlocks:textBlocks}=classifyUserContent(c);for(const tb of textBlocks)tb.text&&tb.text.trim()&&(entries.push({type:"user",text:tb.text,timestamp:teamStartTime}),hasUserMsg=!0)}else"string"!=typeof c||isSystemText(c)||(entries.push({type:"user",text:c,timestamp:teamStartTime}),hasUserMsg=!0);if(hasUserMsg)break}}if(!hasUserMsg)for(let i=0;i<teamRequests.length;i++){const resp=null==(_f=null==(_e=teamRequests[i].response)?void 0:_e.body)?void 0:_f.content;if(Array.isArray(resp)){for(const block of resp)if("text"===block.type&&block.text&&block.text.trim()){entries.push({type:"context",text:block.text.trim(),timestamp:(null==(_g=teamRequests[i].response)?void 0:_g.timestamp)||teamRequests[i].timestamp}),hasUserMsg=!0;break}if(hasUserMsg)break}}for(let i=0;i<teamRequests.length;i++){const req=teamRequests[i],respContent=null==(_i=null==(_h=req.response)?void 0:_h.body)?void 0:_i.content;if(!Array.isArray(respContent)||0===respContent.length)continue;const cls=classifyRequest(req,teamRequests[i+1]),isMA=isMainAgent(req),isSub="SubAgent"===cls.type||"Teammate"===cls.type;if(isMA)entries.push({type:"assistant",content:respContent,timestamp:(null==(_j=req.response)?void 0:_j.timestamp)||req.timestamp,requestIndex:startIdx+i,modelInfo:modelInfo});else if(isSub){const subToolResultMap={},msgs=(null==(_k=req.body)?void 0:_k.messages)||[];for(const msg of msgs)if("tool_result"===msg.role||"user"===msg.role&&Array.isArray(msg.content)){const blocks=Array.isArray(msg.content)?msg.content:[msg];for(const b of blocks)"tool_result"===b.type&&b.tool_use_id&&(subToolResultMap[b.tool_use_id]={resultText:"string"==typeof b.content?b.content:JSON.stringify(b.content)})}entries.push({type:"sub-agent",content:respContent,toolResultMap:subToolResultMap,label:"Teammate"===cls.type?formatTeammateLabel(cls.subType,null==(_l=req.body)?void 0:_l.model):formatRequestTag(cls.type,cls.subType),isTeammate:"Teammate"===cls.type,timestamp:req.timestamp,requestIndex:startIdx+i})}}entries.sort((a,b)=>(a.timestamp||"").localeCompare(b.timestamp||""));const palette=["#1668dc","#52c41a","#faad14","#eb2f96","#722ed1","#13c2c2","#fa541c","#2f54eb"],teamAgents=[],agentMap=new Map,teamTotalStart=new Date(teamStartTime).getTime(),teamTotalEnd=new Date(teamEndTime||Date.now()).getTime(),leadSegments=[];let lastLeadTs=teamTotalStart;const _taskCreateSubjects=new Map,_taskOwnerMap=new Map;let _taskCreateCounter=1;for(let i=0;i<teamRequests.length;i++){const req=teamRequests[i],resp=null==(_n=null==(_m=req.response)?void 0:_m.body)?void 0:_n.content;if(!Array.isArray(resp))continue;const tsStr=(null==(_o=req.response)?void 0:_o.timestamp)||req.timestamp,ts=tsStr,tsMs=new Date(tsStr).getTime(),isMA=isMainAgent(req);for(const block of resp){if("tool_use"!==block.type)continue;const n=block.name,inp="string"==typeof block.input?(()=>{try{return JSON.parse(block.input)}catch{return{}}})():block.input||{};if("Agent"===n&&inp.name){const idx=teamAgents.length;teamAgents.push({name:inp.name,color:palette[idx%palette.length],type:(null==(_p=inp.subagent_type)?void 0:_p.split(":").pop())||"",spawnTime:ts,claimTime:null,doneTime:null,shutdownTime:null,taskSubject:null,events:[{ts:tsMs,label:"spawn"}]}),agentMap.set(inp.name,idx)}else if("TaskCreate"===n){if(inp.subject){const tId=String(inp.taskId||_taskCreateCounter++);_taskCreateSubjects.set(tId,inp.subject)}}else if("TaskUpdate"===n){const owner=inp.owner,taskId=null!=inp.taskId?String(inp.taskId):null;owner&&taskId&&_taskOwnerMap.set(taskId,owner);let targetAg=null;if(owner&&agentMap.has(owner))targetAg=teamAgents[agentMap.get(owner)];else if(taskId){const prevOwner=_taskOwnerMap.get(taskId);if(prevOwner&&agentMap.has(prevOwner))targetAg=teamAgents[agentMap.get(prevOwner)];else{const taskNum=parseInt(taskId,10);taskNum>0&&taskNum<=teamAgents.length&&(targetAg=teamAgents[taskNum-1],_taskOwnerMap.set(taskId,targetAg.name))}}targetAg&&("in_progress"!==inp.status||targetAg.claimTime||(targetAg.claimTime=ts,targetAg.events.push({ts:tsMs,label:"claim"})),"completed"!==inp.status||targetAg.doneTime||(targetAg.doneTime=ts,targetAg.events.push({ts:tsMs,label:"done"})),taskId&&_taskCreateSubjects.has(taskId)&&!targetAg.taskSubject&&(targetAg.taskSubject=_taskCreateSubjects.get(taskId)))}else if("SendMessage"===n)if("shutdown_request"===(null==(_q=inp.message)?void 0:_q.type)&&inp.to&&agentMap.has(inp.to)){const ag=teamAgents[agentMap.get(inp.to)];ag.shutdownTime=ts,ag.events.push({ts:tsMs,label:"shutdown"})}else"shutdown_response"===(null==(_r=inp.message)?void 0:_r.type)&&agentMap.has("team-lead"===inp.to?"":inp.to)||(inp.to&&"team-lead"!==inp.to&&agentMap.has(inp.to)?teamAgents[agentMap.get(inp.to)].events.push({ts:tsMs,label:"msg-in"}):"team-lead"===inp.to&&("string"==typeof inp.message||inp.message&&!inp.message.type)&&tsMs>lastLeadTs&&(leadSegments.push({start:lastLeadTs,end:tsMs,label:"report-received",color:"#52c41a"}),lastLeadTs=tsMs));if(isMA&&("TeamCreate"===n||"TaskCreate"===n||"Agent"===n||"SendMessage"===n||"TeamDelete"===n)){const label2="TeamCreate"===n?"create":"TaskCreate"===n?"tasks":"Agent"===n?"spawn":"SendMessage"===n?"msg":"cleanup";tsMs>lastLeadTs&&(leadSegments.push({start:lastLeadTs,end:tsMs,label:label2,color:"TeamDelete"===n?"#52c41a":"SendMessage"===n?"#ff4d4f":"#1668dc"}),lastLeadTs=tsMs)}}if(isMA)for(const block of resp)"text"===block.type&&block.text?tsMs>lastLeadTs&&(leadSegments.push({start:lastLeadTs,end:tsMs,label:"text",color:"#196ae1"}),lastLeadTs=tsMs):"thinking"===block.type&&tsMs>lastLeadTs&&(leadSegments.push({start:lastLeadTs,end:tsMs,label:"thinking",color:"#722ed1"}),lastLeadTs=tsMs)}for(let i=0;i<teamRequests.length;i++){const req=teamRequests[i];if(isMainAgent(req))continue;const resp=null==(_t=null==(_s=req.response)?void 0:_s.body)?void 0:_t.content;if(!Array.isArray(resp))continue;const tsStr=(null==(_u=req.response)?void 0:_u.timestamp)||req.timestamp,tsMs=new Date(tsStr).getTime(),cls=classifyRequest(req,teamRequests[i+1]),label2="Teammate"===cls.type?cls.subType:null;if(label2){let agIdx=agentMap.has(label2)?agentMap.get(label2):void 0;if(void 0===agIdx)for(const[name,idx]of agentMap)if(label2.includes(name)||name.includes(label2)){agIdx=idx;break}if(void 0!==agIdx){const ag=teamAgents[agIdx];for(const block of resp)"tool_use"===block.type&&block.name&&ag.events.push({ts:tsMs,label:"tool:"+block.name})}}}const teammateMessageRe=/<teammate-message\s+teammate_id="([^"]+)"[^>]*summary="([^"]*)"[^>]*>([\s\S]*?)<\/teammate-message>/g,seenTmMsg=new Set;teamAgents.forEach(ag=>{ag.teammateMessages=[]});for(let i=0;i<teamRequests.length;i++){const raw=teamRequests[i],req=(null==raw?void 0:raw._slimmed)?restoreSlimmedEntry(raw,requests):raw,msgs=(null==(_v=req.body)?void 0:_v.messages)||[];for(const m of msgs)if("user"===m.role&&Array.isArray(m.content))for(const b of m.content){if("text"!==b.type||!b.text)continue;let match;for(teammateMessageRe.lastIndex=0;null!==(match=teammateMessageRe.exec(b.text));){const[,tid,summary,content2]=match;if("system"===tid||"team-lead"===tid)continue;const dedupKey=tid+"|"+summary+"|"+content2.trim().slice(0,100);if(!seenTmMsg.has(dedupKey)){seenTmMsg.add(dedupKey);for(const ag of teamAgents)if(tid===ag.name||tid.includes(ag.name)||ag.name.includes(tid)){if(summary&&content2.trim()){ag.teammateMessages.push({summary:summary,content:content2.trim()});const reqTs=req.timestamp||(null==(_w=req.response)?void 0:_w.timestamp);entries.push({type:"teammate-report",agentName:ag.name,agentColor:getTeammateAvatar(ag.name).color,summary:summary,content:content2.trim(),timestamp:reqTs})}break}}}}}lastLeadTs<teamTotalEnd&&leadSegments.push({start:lastLeadTs,end:teamTotalEnd,label:"idle",color:"#333"});const segColors={spawn:"#555",claim:"#faad14",done:"#52c41a",shutdown:"#ff4d4f","msg-in":"#1668dc",report:"#52c41a","report-received":"#52c41a",text:"#196ae1",thinking:"#722ed1"};return teamAgents.forEach(ag=>{var _a2;const start=new Date(ag.spawnTime).getTime(),end=new Date(ag.doneTime||ag.shutdownTime||teamEndTime||Date.now()).getTime();ag.duration=end-start,ag.events.sort((a,b)=>a.ts-b.ts),ag.segments=[];for(let e=0;e<ag.events.length;e++){const ev=ag.events[e],nextTs=(null==(_a2=ag.events[e+1])?void 0:_a2.ts)||(ag.shutdownTime?new Date(ag.shutdownTime).getTime():teamTotalEnd);ag.segments.push({start:ev.ts,end:nextTs,label:ev.label,color:segColors[ev.label]||(ev.label.startsWith("tool:")?"#888":ag.color)})}}),{entries:entries,teamAgents:teamAgents,leadSegments:leadSegments,teamTotalStart:teamTotalStart,teamTotalEnd:teamTotalEnd,modelInfo:modelInfo,teamRequests:teamRequests}}(session,requests,mainAgentSessions);return dataCacheRef.current={team:session,requests:requests,mainAgentSessions:mainAgentSessions,result:result},result},[session,requests,mainAgentSessions]),teamTotalStart=modalData?modalData.teamTotalStart:0,teamTotalEnd=modalData?modalData.teamTotalEnd:0,onScroll=reactExports.useCallback(()=>{scrollRafRef.current||(scrollRafRef.current=requestAnimationFrame(()=>{var _a;scrollRafRef.current=null;const container2=modalBodyRef.current;if(!container2)return;const containerTop=container2.getBoundingClientRect().top;let closestTs=null;for(const child of container2.children){const ts=child.getAttribute("data-timestamp");if(!ts)continue;if(child.getBoundingClientRect().bottom>containerTop){closestTs=ts;break}}if(!closestTs)return;const tsMs=new Date(closestTs).getTime(),total=teamTotalEnd-teamTotalStart||1,pctVal=Math.max(0,Math.min(100,(tsMs-teamTotalStart)/total*100)),el=ganttIndicatorRef.current;if(!el)return;ganttTrackElRef.current&&ganttTrackElRef.current.isConnected||(ganttTrackElRef.current=null==(_a=el.parentElement)?void 0:_a.querySelector('[class*="teamGanttTrack"]'));const wrap=el.parentElement,track=ganttTrackElRef.current;if(track){const wrapRect=wrap.getBoundingClientRect(),trackRect=track.getBoundingClientRect(),trackLeft=trackRect.left-wrapRect.left,trackWidth=trackRect.width;el.style.left=trackLeft+trackWidth*pctVal/100+"px",el.style.height=wrap.scrollHeight+"px"}}))},[teamTotalStart,teamTotalEnd]);if(!session)return null;const{entries:entries,teamAgents:teamAgents,leadSegments:leadSegments,modelInfo:modelInfo}=modalData;return jsxRuntimeExports.jsx(Modal,{open:!0,onCancel:()=>{ganttTrackElRef.current=null,onClose()},footer:null,closable:!0,maskClosable:!0,zIndex:1100,width:"calc(100vw - 80px)",title:jsxRuntimeExports.jsxs("span",{className:styles$8_teamModalTitle,children:["Team: ",session.name]}),styles:{header:{background:"var(--bg-container)",borderBottom:"1px solid var(--border-primary)",padding:"12px 20px"},body:{background:"var(--bg-base)",height:"calc(100vh - 160px)",overflow:"hidden",padding:0},mask:{background:"rgba(0,0,0,0.7)"},content:{background:"var(--bg-container)",border:"1px solid var(--border-primary)",borderRadius:8,padding:0}},centered:!0,children:jsxRuntimeExports.jsxs("div",{className:styles$8_teamModalLayout,children:[jsxRuntimeExports.jsxs("div",{className:styles$8_teamAgentCards,children:[jsxRuntimeExports.jsxs("div",{className:`${styles$8_teamAgentCard} ${styles$8_teamLeadCard}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$8_teamAgentCardHeader,children:[(null==modelInfo?void 0:modelInfo.svg)?jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentAvatar,style:{background:modelInfo.color||"var(--bg-model-avatar)"},dangerouslySetInnerHTML:{__html:modelInfo.svg}}):jsxRuntimeExports.jsx("img",{src:"/assets/default-model-avatar-DlbUPjyv.svg",className:styles$8_teamAgentAvatar,alt:"lead"}),jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentName,children:"team-lead"})]}),jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentType,children:"orchestrator"}),(()=>{const disp=deriveDisplayStatus(session,null),style=disp.colorVar?{color:disp.colorVar}:void 0;return jsxRuntimeExports.jsxs("div",{className:`${styles$8_teamAgentStatus} ${disp.className||""}`,style:style,children:[disp.glyph," ",t(disp.tooltipKey)]})})()]}),teamAgents.map((ag,i)=>{const isDone=!!ag.doneTime,durSec=Math.round(ag.duration/1e3),durStr=durSec>=60?`${Math.floor(durSec/60)}m${durSec%60}s`:`${durSec}s`,agentMessages=entries.filter(e=>"sub-agent"===e.type&&e.label&&e.label.includes(ag.name)),popContent=jsxRuntimeExports.jsxs("div",{className:styles$8_teamAgentPopover,children:[ag.teammateMessages&&ag.teammateMessages.length>0&&jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentPopTeammateMsg,children:ag.teammateMessages.map((tm,ti)=>jsxRuntimeExports.jsxs("div",{children:[tm.summary&&jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentPopTmSummary,children:tm.summary}),jsxRuntimeExports.jsx("div",{className:`${styles$8_teamAgentPopTmContent} chat-md`,dangerouslySetInnerHTML:{__html:renderMarkdown(tm.content.length>3e3?tm.content.slice(0,3e3)+"\n\n...":tm.content)}})]},ti))}),ag.taskSubject&&jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentPopTask,children:ag.taskSubject}),agentMessages.length>0?agentMessages.map((msg,mi)=>{const texts=(msg.content||[]).filter(b=>"text"===b.type).map(b=>b.text).join("\n");return texts.trim()?jsxRuntimeExports.jsx("div",{className:`${styles$8_teamAgentPopMsg} chat-md`,dangerouslySetInnerHTML:{__html:renderMarkdown(texts.length>2e3?texts.slice(0,2e3)+"\n\n...":texts)}},mi):null}):jsxRuntimeExports.jsx("div",{className:styles$8_agentNoMessages,children:"No messages"})]});return jsxRuntimeExports.jsx(Popover,{content:popContent,trigger:"click",placement:"right",autoAdjustOverflow:!0,overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-light)",padding:0,maxWidth:800,maxHeight:"70vh",overflowY:"auto"},onOpenChange:open=>setActiveAgentCard(open?i:null),children:jsxRuntimeExports.jsxs("div",{className:`${styles$8_teamAgentCard} ${styles$8_teamAgentCardClickable} ${activeAgentCard===i?styles$8_teamAgentCardActive:""}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$8_teamAgentCardHeader,children:[(()=>{const _a=getTeammateAvatar(ag.name);return jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentAvatar,style:{background:_a.color},dangerouslySetInnerHTML:{__html:_a.svg}})})(),jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentName,children:ag.name})]}),jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentType,children:ag.type}),jsxRuntimeExports.jsxs("div",{className:styles$8_teamAgentStatus,style:{color:isDone?"var(--color-success)":"var(--color-warning-light)"},children:[isDone?"✓ done":"● working"," ",jsxRuntimeExports.jsxs("span",{className:styles$8_agentStatusDurSuffix,children:["· ",durStr]})]})]})},i)})]}),jsxRuntimeExports.jsxs("div",{className:styles$8_teamModalContent,children:[jsxRuntimeExports.jsx(TeamGantt,{teamAgents:teamAgents,teamTotalStart:teamTotalStart,teamTotalEnd:teamTotalEnd,leadSegments:leadSegments,ganttWrapRef:ganttWrapRef,ganttIndicatorRef:ganttIndicatorRef,ganttHeight:ganttHeight,onGanttHeightChange:setGanttHeight}),jsxRuntimeExports.jsxs("div",{className:styles$8_teamModalBody,ref:modalBodyRef,onScroll:onScroll,children:[entries.map((entry,i)=>jsxRuntimeExports.jsxs("div",{"data-timestamp":entry.timestamp,children:["user"===entry.type&&jsxRuntimeExports.jsx(ChatMessage,{role:"user",text:entry.text,timestamp:entry.timestamp,userProfile:userProfile,modelInfo:modelInfo,requestIndex:entry.requestIndex,onViewRequest:onViewRequest,isHistoryLog:isHistoryLog}),"assistant"===entry.type&&jsxRuntimeExports.jsx(ChatMessage,{role:"assistant",content:entry.content,timestamp:entry.timestamp,modelInfo:entry.modelInfo,collapseToolResults:collapseToolResults,expandThinking:expandThinking,toolResultMap:{},askAnswerMap:{},requestIndex:entry.requestIndex,onViewRequest:onViewRequest,isHistoryLog:isHistoryLog}),"sub-agent"===entry.type&&jsxRuntimeExports.jsx(ChatMessage,{role:"sub-agent-chat",content:entry.content,toolResultMap:entry.toolResultMap,label:entry.label,isTeammate:entry.isTeammate,timestamp:entry.timestamp,collapseToolResults:collapseToolResults,expandThinking:expandThinking,requestIndex:entry.requestIndex,onViewRequest:onViewRequest,isHistoryLog:isHistoryLog}),"context"===entry.type&&jsxRuntimeExports.jsx(ChatMessage,{role:"assistant",content:[{type:"text",text:entry.text}],timestamp:entry.timestamp,modelInfo:modelInfo,collapseToolResults:collapseToolResults,expandThinking:expandThinking,toolResultMap:{},askAnswerMap:{},isHistoryLog:isHistoryLog}),"teammate-report"===entry.type&&jsxRuntimeExports.jsxs("div",{className:styles$8_teammateReportEntry,children:[jsxRuntimeExports.jsxs("div",{className:styles$8_teammateReportHeader,children:[(()=>{const _a=getTeammateAvatar(entry.agentName);return jsxRuntimeExports.jsx("div",{className:styles$8_teamAgentAvatar,style:{background:_a.color},dangerouslySetInnerHTML:{__html:_a.svg}})})(),jsxRuntimeExports.jsx("span",{className:styles$8_teammateReportName,children:entry.agentName}),jsxRuntimeExports.jsx("span",{className:styles$8_teammateReportSummary,children:entry.summary})]}),jsxRuntimeExports.jsx("div",{className:`${styles$8_teammateReportBody} chat-md`,dangerouslySetInnerHTML:{__html:renderMarkdown(entry.content)}})]})]},`tw-${i}`)),0===entries.length&&jsxRuntimeExports.jsx(Empty,{description:"No entries",image:Empty.PRESENTED_IMAGE_SIMPLE})]})]})]})})}const styles$7_snapLine="_snapLine_1qd8k_1",styles$7_snapLineActive="_snapLineActive_1qd8k_13",styles$7_snapPreview="_snapPreview_1qd8k_24";function SnapLineOverlay({isDragging:isDragging,activeSnapLine:activeSnapLine,snapLines:snapLines,currentLeft:currentLeft}){if(!isDragging)return null;let snapPreview2=null;if(activeSnapLine){const snapLeft=activeSnapLine.linePosition,left=Math.min(currentLeft,snapLeft),width=Math.abs(snapLeft-currentLeft);snapPreview2=jsxRuntimeExports.jsx("div",{className:styles$7_snapPreview,style:{left:`${left}px`,width:`${width}px`}})}const sorted=[...snapLines].map(snap=>({...snap,dist:Math.abs(snap.linePosition-currentLeft)})).sort((a,b)=>a.dist-b.dist);let snapLineEl=null;if(sorted.length>0){const snap=sorted[0],isActive=activeSnapLine&&activeSnapLine.cols===snap.cols;snapLineEl=jsxRuntimeExports.jsx("div",{className:isActive?styles$7_snapLineActive:styles$7_snapLine,style:{left:`${snap.linePosition}px`}},snap.cols)}return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[snapPreview2,snapLineEl]})}const styles$6_roleFilterBar="_roleFilterBar_122ad_1",styles$6_roleChip="_roleChip_122ad_12",styles$6_roleChipActive="_roleChipActive_122ad_12",styles$6_roleAvatar="_roleAvatar_122ad_33",styles$6_roleAvatarImg="_roleAvatarImg_122ad_47",styles$6_roleName="_roleName_122ad_54",styles$6_roleCheck="_roleCheck_122ad_59";function RoleFilterBar({roles:roles,selectedRoles:selectedRoles,onToggle:onToggle,style:style}){return roles&&0!==roles.length?jsxRuntimeExports.jsx("div",{className:styles$6_roleFilterBar,style:style,children:roles.map(r=>{const selected=selectedRoles.has(r.key);return jsxRuntimeExports.jsxs("button",{className:selected?styles$6_roleChipActive:styles$6_roleChip,onClick:()=>onToggle(r.key),children:[r.avatarImg?jsxRuntimeExports.jsx("img",{src:r.avatarImg,className:styles$6_roleAvatarImg,alt:r.name,onError:e=>{e.target.onerror=null,e.target.style.display="none";const d=e.target.parentNode.querySelector("[data-role-avatar-fallback]");d&&(d.style.display="")}}):null,jsxRuntimeExports.jsx("div",{className:styles$6_roleAvatar,style:{background:r.color||"rgba(255,255,255,0.1)",display:r.avatarImg?"none":""},"data-role-avatar-fallback":"",dangerouslySetInnerHTML:{__html:r.avatarSvg||getSvgAvatar(r.avatarType)}}),jsxRuntimeExports.jsx("span",{className:styles$6_roleName,children:r.name}),selected&&jsxRuntimeExports.jsx("span",{className:styles$6_roleCheck,children:"✓"})]},r.key)})}):null}const styles$5_chatInputBar="_chatInputBar_1u3fp_1",styles$5_chatInputWrapper="_chatInputWrapper_1u3fp_7",styles$5_chatTextareaWrap="_chatTextareaWrap_1u3fp_21",styles$5_textareaWithGhost="_textareaWithGhost_1u3fp_28",styles$5_chatTextarea="_chatTextarea_1u3fp_21",styles$5_chatInputBottom="_chatInputBottom_1u3fp_52",styles$5_chatInputBottomLeft="_chatInputBottomLeft_1u3fp_60",styles$5_chatInputBottomRight="_chatInputBottomRight_1u3fp_62",styles$5_plusArea="_plusArea_1u3fp_74",styles$5_plusBtn="_plusBtn_1u3fp_78",styles$5_micBtn="_micBtn_1u3fp_79",styles$5_plusBtnOpen="_plusBtnOpen_1u3fp_94",styles$5_micBtnRecording="_micBtnRecording_1u3fp_105",styles$5_interimPreview="_interimPreview_1u3fp_125",styles$5_plusOverlay="_plusOverlay_1u3fp_144",styles$5_plusMenu="_plusMenu_1u3fp_153",styles$5_plusMenuItem="_plusMenuItem_1u3fp_166",styles$5_plusMenuItemMuted="_plusMenuItemMuted_1u3fp_186",styles$5_presetLabel="_presetLabel_1u3fp_205",styles$5_chatInputHint="_chatInputHint_1u3fp_211",styles$5_ctxBarSlot="_ctxBarSlot_1u3fp_61",styles$5_sendBtn="_sendBtn_1u3fp_236",styles$5_sendBtnDisabled="_sendBtnDisabled_1u3fp_251",styles$5_ghostText="_ghostText_1u3fp_262",styles$5_suggestionChip="_suggestionChip_1u3fp_278",styles$5_suggestionChipText="_suggestionChipText_1u3fp_294",styles$5_suggestionChipAction="_suggestionChipAction_1u3fp_303",styles$5_imagePreviewStrip="_imagePreviewStrip_1u3fp_310",styles$5_imagePreviewItem="_imagePreviewItem_1u3fp_322",styles$5_imagePreviewThumb="_imagePreviewThumb_1u3fp_337",styles$5_imagePreviewRemove="_imagePreviewRemove_1u3fp_344",styles$5_filePreviewClose="_filePreviewClose_1u3fp_372",styles$5_filePreviewChip="_filePreviewChip_1u3fp_379",styles$5_filePreviewName="_filePreviewName_1u3fp_402",styles$5_streamingSpinner="_streamingSpinner_1u3fp_559",styles$5_sendBtnWrap="_sendBtnWrap_1u3fp_569",styles$5_streamingSvg="_streamingSvg_1u3fp_590",styles$5_streamingSpinnerFading="_streamingSpinnerFading_1u3fp_597",SpeechRec="undefined"!=typeof window&&window.isSecureContext?window.SpeechRecognition||window.webkitSpeechRecognition:null,SPEECH_LANG_MAP={zh:"zh-CN","zh-TW":"zh-TW",en:"en-US",ko:"ko-KR",ja:"ja-JP",de:"de-DE",es:"es-ES",fr:"fr-FR",it:"it-IT",da:"da-DK",pl:"pl-PL",ru:"ru-RU",ar:"ar-SA",no:"nb-NO","pt-BR":"pt-BR",th:"th-TH",tr:"tr-TR",uk:"uk-UA"};function ChatInputBar({inputRef:inputRef,inputEmpty:inputEmpty,inputSuggestion:inputSuggestion,terminalVisible:terminalVisible,onKeyDown:onKeyDown,onChange:onChange,onSend:onSend,onStop:onStop,onSuggestionClick:onSuggestionClick,onUploadPath:onUploadPath,presetItems:presetItems,onPresetSend:onPresetSend,onOpenPresetModal:onOpenPresetModal,onOpenUltraPlan:onOpenUltraPlan,onClearContext:onClearContext,isStreaming:isStreaming,streamingFading:streamingFading,pendingImages:pendingImages,onRemovePendingImage:onRemovePendingImage,setContextBarSlot:setContextBarSlot}){const[plusOpen,setPlusOpen]=reactExports.useState(!1),[recording,setRecording]=reactExports.useState(!1),[interimText,setInterimText]=reactExports.useState(""),[lightbox,setLightbox]=reactExports.useState(null),recRef=reactExports.useRef(null),anchorRef=reactExports.useRef({prefix:"",suffix:""}),rootRef=reactExports.useRef(null);reactExports.useEffect(()=>()=>{const rec=recRef.current;if(rec){rec.onend=null,rec.onresult=null,rec.onerror=null;try{rec.abort()}catch{}recRef.current=null}},[]),reactExports.useLayoutEffect(()=>{const el=rootRef.current;if(!el)return;const setVar=()=>{var _a;const rect=el.getBoundingClientRect(),distFromBottom=((null==(_a=window.visualViewport)?void 0:_a.height)??window.innerHeight)-rect.top*(()=>{let p=el.parentElement;for(;p;){const z=parseFloat(getComputedStyle(p).zoom);if(z&&z>0&&1!==z)return z;p=p.parentElement}return 1})();distFromBottom<5||document.documentElement.style.setProperty("--chat-input-bar-height",distFromBottom+"px")};let ro;setVar(),"undefined"!=typeof ResizeObserver&&(ro=new ResizeObserver(setVar),ro.observe(el));const vv=window.visualViewport;return vv&&vv.addEventListener("resize",setVar),window.addEventListener("resize",setVar),()=>{ro&&ro.disconnect(),vv&&vv.removeEventListener("resize",setVar),window.removeEventListener("resize",setVar)}},[]),reactExports.useEffect(()=>{if(terminalVisible&&recRef.current)try{recRef.current.abort()}catch{}},[terminalVisible]);return terminalVisible?inputSuggestion?jsxRuntimeExports.jsxs("div",{className:styles$5_suggestionChip,onClick:onSuggestionClick,children:[jsxRuntimeExports.jsx("span",{className:styles$5_suggestionChipText,children:inputSuggestion}),jsxRuntimeExports.jsx("span",{className:styles$5_suggestionChipAction,children:"↵"})]}):null:jsxRuntimeExports.jsxs("div",{className:styles$5_chatInputBar,ref:rootRef,children:[jsxRuntimeExports.jsxs("div",{className:styles$5_chatInputWrapper,children:[jsxRuntimeExports.jsxs("div",{className:styles$5_chatTextareaWrap,children:[pendingImages&&pendingImages.length>0&&jsxRuntimeExports.jsx("div",{className:styles$5_imagePreviewStrip,children:pendingImages.map((img,i)=>{const fileName2=img.path.split("/").pop()||img.path,isImage=/\.(png|jpe?g|gif|svg|bmp|webp|avif|ico|icns)$/i.test(fileName2),src=apiUrl(`/api/file-raw?path=${encodeURIComponent(img.path)}`);return isImage?jsxRuntimeExports.jsxs("div",{className:styles$5_imagePreviewItem,children:[jsxRuntimeExports.jsx("img",{src:src,className:styles$5_imagePreviewThumb,alt:fileName2,role:"button",tabIndex:0,onClick:()=>setLightbox({src:src,alt:fileName2}),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),setLightbox({src:src,alt:fileName2}))}}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveImage"),onConfirm:()=>null==onRemovePendingImage?void 0:onRemovePendingImage(i),className:styles$5_imagePreviewRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},img.path):jsxRuntimeExports.jsxs("div",{className:styles$5_filePreviewChip,children:[jsxRuntimeExports.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),jsxRuntimeExports.jsx("polyline",{points:"14 2 14 8 20 8"})]}),jsxRuntimeExports.jsx("span",{className:styles$5_filePreviewName,children:fileName2}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveFile"),onConfirm:()=>null==onRemovePendingImage?void 0:onRemovePendingImage(i),className:styles$5_filePreviewClose,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},img.path)})}),jsxRuntimeExports.jsxs("div",{className:styles$5_textareaWithGhost,children:[jsxRuntimeExports.jsx("textarea",{ref:inputRef,className:styles$5_chatTextarea,placeholder:inputSuggestion?"":t("ui.chatInput.placeholder"),rows:1,onKeyDown:onKeyDown,onInput:e=>{var _a,_b;if(recRef.current&&(null==(_a=e.nativeEvent)?void 0:_a.inputType)&&!(null==(_b=e.nativeEvent)?void 0:_b.isComposing))try{recRef.current.abort()}catch{}null==onChange||onChange(e)},onPaste:async e=>{var _a;const items=null==(_a=e.clipboardData)?void 0:_a.items;if(items)for(const item of items)if(item.type.startsWith("image/")){e.preventDefault();try{const file=item.getAsFile();if(!file)return;const path=await uploadFileAndGetPath(file);null==onUploadPath||onUploadPath(path)}catch(err){console.error("[CC Viewer] Paste image upload failed:",err)}return}}}),inputSuggestion&&inputEmpty&&jsxRuntimeExports.jsx("div",{className:styles$5_ghostText,children:inputSuggestion}),recording&&interimText&&jsxRuntimeExports.jsx("div",{className:styles$5_interimPreview,children:interimText})]})]}),jsxRuntimeExports.jsxs("div",{className:styles$5_chatInputBottom,children:[jsxRuntimeExports.jsxs("div",{className:styles$5_chatInputBottomLeft,children:[jsxRuntimeExports.jsxs("div",{className:styles$5_plusArea,children:[jsxRuntimeExports.jsx("button",{className:`${styles$5_plusBtn}${plusOpen?` ${styles$5_plusBtnOpen}`:""}`,onClick:()=>setPlusOpen(p=>!p),title:t("ui.chatInput.more"),children:jsxRuntimeExports.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),jsxRuntimeExports.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),plusOpen&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:styles$5_plusOverlay,onClick:()=>setPlusOpen(!1)}),jsxRuntimeExports.jsxs("div",{className:styles$5_plusMenu,children:[presetItems&&presetItems.length>0&&onOpenPresetModal&&jsxRuntimeExports.jsxs("button",{className:`${styles$5_plusMenuItem} ${styles$5_plusMenuItemMuted}`,onClick:()=>{setPlusOpen(!1),onOpenPresetModal()},children:[jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("circle",{cx:"12",cy:"12",r:"3"}),jsxRuntimeExports.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]}),jsxRuntimeExports.jsx("span",{className:styles$5_presetLabel,children:t("ui.terminal.customShortcuts")})]}),presetItems&&presetItems.length>0&&presetItems.map(item=>{const isBuiltinRaw=item.builtinId&&!item.modified,name=isBuiltinRaw?t(item.teamName):item.teamName,desc=isBuiltinRaw?t(item.description):item.description;return jsxRuntimeExports.jsxs("button",{className:styles$5_plusMenuItem,onClick:()=>{setPlusOpen(!1),null==onPresetSend||onPresetSend(desc)},title:desc,children:[jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),jsxRuntimeExports.jsx("circle",{cx:"9",cy:"7",r:"4"}),jsxRuntimeExports.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),jsxRuntimeExports.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),jsxRuntimeExports.jsx("span",{className:styles$5_presetLabel,children:name||desc})]},item.id)}),onOpenUltraPlan&&jsxRuntimeExports.jsxs("button",{className:styles$5_plusMenuItem,onClick:()=>{setPlusOpen(!1),onOpenUltraPlan()},children:[jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("circle",{cx:"12",cy:"12",r:"2.5"}),jsxRuntimeExports.jsx("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4"}),jsxRuntimeExports.jsx("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",transform:"rotate(60 12 12)"}),jsxRuntimeExports.jsx("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",transform:"rotate(120 12 12)"})]}),jsxRuntimeExports.jsx("span",{children:"UltraPlan"})]}),onClearContext&&jsxRuntimeExports.jsxs("button",{className:styles$5_plusMenuItem,onClick:()=>{setPlusOpen(!1),onClearContext()},children:[jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M3 6h18"}),jsxRuntimeExports.jsx("path",{d:"M8 6V4h8v2"}),jsxRuntimeExports.jsx("path",{d:"M5 6v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V6"}),jsxRuntimeExports.jsx("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),jsxRuntimeExports.jsx("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]}),jsxRuntimeExports.jsx("span",{children:t("ui.chatInput.clearContext")})]}),jsxRuntimeExports.jsxs("button",{className:styles$5_plusMenuItem,onClick:()=>{setPlusOpen(!1);const input=document.createElement("input");input.type="file",input.onchange=async e=>{var _a;const file=null==(_a=e.target.files)?void 0:_a[0];if(file)try{const path=await uploadFileAndGetPath(file);onUploadPath(path)}catch(err){console.error("[CC Viewer] Upload failed:",err)}},input.click()},children:[jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),jsxRuntimeExports.jsx("polyline",{points:"17 8 12 3 7 8"}),jsxRuntimeExports.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),jsxRuntimeExports.jsx("span",{children:t("ui.terminal.upload")})]})]})]})]}),SpeechRec&&jsxRuntimeExports.jsx("button",{type:"button",className:`${styles$5_micBtn}${recording?` ${styles$5_micBtnRecording}`:""}`,onClick:()=>{recRef.current?(()=>{var _a;try{null==(_a=recRef.current)||_a.stop()}catch{}})():(()=>{if(!SpeechRec||recRef.current)return;const ta=null==inputRef?void 0:inputRef.current;if(!ta)return;const pos="number"==typeof ta.selectionStart?ta.selectionStart:ta.value.length;let rec;anchorRef.current={prefix:ta.value.slice(0,pos),suffix:ta.value.slice(pos)};try{rec=new SpeechRec}catch(err){return void console.error("[CC Viewer] SpeechRecognition init failed:",err)}rec.continuous=!0,rec.interimResults=!0,rec.lang=SPEECH_LANG_MAP[getLang()]||"en-US",rec.onresult=event=>{var _a;const t2=null==inputRef?void 0:inputRef.current;if(!t2)return;const{prefix:prefix2,suffix:suffix}=anchorRef.current;if(!t2.value.startsWith(prefix2)||!t2.value.endsWith(suffix)){try{rec.abort()}catch{}return}let interim="",finalAcc="";for(let i=0;i<event.results.length;i++){const r=event.results[i],transcript=(null==(_a=r[0])?void 0:_a.transcript)??"";r.isFinal?finalAcc+=transcript:interim+=transcript}t2.value=prefix2+finalAcc+suffix,t2.style.height="auto",t2.style.height=Math.min(t2.scrollHeight,120)+"px",setInterimText(interim),null==onChange||onChange({target:t2})},rec.onerror=event=>{if("not-allowed"===event.error||"service-not-allowed"===event.error)try{alert(t("ui.chatInput.voicePermissionDenied"))}catch{}else"no-speech"!==event.error&&"aborted"!==event.error&&console.error("[CC Viewer] SpeechRecognition error:",event.error)},rec.onend=()=>{setRecording(!1),setInterimText(""),recRef.current=null};try{rec.start(),recRef.current=rec,setRecording(!0)}catch(err){console.error("[CC Viewer] SpeechRecognition start failed:",err)}})()},title:t(recording?"ui.chatInput.voiceStop":"ui.chatInput.voiceStart"),"aria-label":t(recording?"ui.chatInput.voiceStop":"ui.chatInput.voiceStart"),"aria-pressed":recording,children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),jsxRuntimeExports.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),jsxRuntimeExports.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),jsxRuntimeExports.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})})]}),!(isMobile&&!isPad)&&!terminalVisible&&setContextBarSlot&&jsxRuntimeExports.jsx("div",{className:styles$5_ctxBarSlot,ref:setContextBarSlot}),jsxRuntimeExports.jsxs("div",{className:styles$5_chatInputBottomRight,children:[jsxRuntimeExports.jsx("div",{className:styles$5_chatInputHint,children:isMobile&&!isPad?null:t(inputSuggestion&&inputEmpty?"ui.chatInput.hintTab":"ui.chatInput.hintEnter")}),jsxRuntimeExports.jsxs("div",{className:styles$5_sendBtnWrap,children:[(isStreaming||streamingFading)&&jsxRuntimeExports.jsx("div",{className:`${styles$5_streamingSpinner}${streamingFading?` ${styles$5_streamingSpinnerFading}`:""}`,"aria-hidden":"true",children:jsxRuntimeExports.jsxs("svg",{className:styles$5_streamingSvg,viewBox:"0 0 32 32",children:[jsxRuntimeExports.jsx("circle",{cx:"16",cy:"16",r:"15",pathLength:"100",fill:"none",strokeWidth:"1.5",stroke:"var(--color-primary-lighter)",strokeOpacity:"0.25",strokeLinecap:"round",strokeDasharray:"14 86",strokeDashoffset:"0"}),jsxRuntimeExports.jsx("circle",{cx:"16",cy:"16",r:"15",pathLength:"100",fill:"none",strokeWidth:"1.5",stroke:"var(--color-primary-lighter)",strokeOpacity:"0.55",strokeLinecap:"round",strokeDasharray:"7 93",strokeDashoffset:"-6"}),jsxRuntimeExports.jsx("circle",{cx:"16",cy:"16",r:"15",pathLength:"100",fill:"none",strokeWidth:"1.5",stroke:"var(--color-primary-lighter)",strokeOpacity:"1",strokeLinecap:"round",strokeDasharray:"3 97",strokeDashoffset:"-10"})]})}),isStreaming&&onStop?jsxRuntimeExports.jsx("button",{type:"button",className:styles$5_sendBtn,onClick:onStop,title:t("ui.chatInput.stop"),"aria-label":t("ui.chatInput.stop"),children:jsxRuntimeExports.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"currentColor","aria-hidden":"true",children:jsxRuntimeExports.jsx("rect",{x:"1",y:"1",width:"10",height:"10",rx:"1.5"})})}):jsxRuntimeExports.jsx("button",{type:"button",className:`${styles$5_sendBtn} ${inputEmpty&&!(null==pendingImages?void 0:pendingImages.length)?styles$5_sendBtnDisabled:""}`,onClick:onSend,disabled:inputEmpty&&!(null==pendingImages?void 0:pendingImages.length),title:t("ui.chatInput.send"),children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),jsxRuntimeExports.jsx("polyline",{points:"5 12 12 5 19 12"})]})})]})]})]})]}),lightbox&&jsxRuntimeExports.jsx(ImageLightbox,{src:lightbox.src,alt:lightbox.alt,onClose:()=>setLightbox(null)})]})}function PresetModal({open:open,onClose:onClose,items:items,onItemsChange:onItemsChange,dismissedBuiltinPresets:dismissedBuiltinPresets,onSavePresets:onSavePresets}){const savePresets=reactExports.useCallback((nextItems,nextDismissed)=>{"function"==typeof onSavePresets&&onSavePresets(function(items,dismissed){const payload={presetShortcuts:items.map(i=>{const o2={teamName:i.teamName,description:i.description};return i.builtinId&&(o2.builtinId=i.builtinId),i.modified&&(o2.modified=!0),o2})};return dismissed&&(payload.dismissedBuiltinPresets=[...dismissed]),payload}(nextItems,nextDismissed))},[onSavePresets]),[selected,setSelected]=reactExports.useState(new Set),[addVisible,setAddVisible]=reactExports.useState(!1),[addName,setAddName]=reactExports.useState(""),[addText,setAddText]=reactExports.useState(""),[editId,setEditId]=reactExports.useState(null),dragIdx=reactExports.useRef(null),dragOverIdx=reactExports.useRef(null),[,forceRender]=reactExports.useState(0),dismissed=reactExports.useRef(new Set(dismissedBuiltinPresets||[])),handleClose=reactExports.useCallback(()=>{setSelected(new Set),onClose()},[onClose]),handleToggle=reactExports.useCallback(id=>{setSelected(prev=>{const next=new Set(prev);return next.has(id)?next.delete(id):next.add(id),next})},[]),handleDelete=reactExports.useCallback(()=>{if(0===selected.size)return;const d=new Set(dismissed.current);for(const item of items)selected.has(item.id)&&item.builtinId&&d.add(item.builtinId);dismissed.current=d;const next=items.filter(i=>!selected.has(i.id));setSelected(new Set),onItemsChange(next),savePresets(next,d)},[items,selected,onItemsChange]),handleAdd=reactExports.useCallback(()=>{const description=addText.trim(),teamName=addName.trim();if(!description&&!teamName)return;let next;next=editId?items.map(i=>{if(i.id!==editId)return i;const updated={...i,teamName:teamName,description:description};return i.builtinId&&(updated.modified=!0),updated}):[...items,{id:Date.now(),teamName:teamName,description:description}],onItemsChange(next),savePresets(next),setAddVisible(!1),setAddName(""),setAddText(""),setEditId(null)},[items,addName,addText,editId,onItemsChange]),handleDragEnd=()=>{dragIdx.current=null,dragOverIdx.current=null,forceRender(n=>n+1)};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs(Modal,{title:t("ui.terminal.presetShortcuts"),open:open,onCancel:handleClose,footer:null,width:800,styles:{content:{background:"var(--bg-elevated)",border:"1px solid var(--border-light)"},header:{background:"var(--bg-elevated)",borderBottom:"none"}},children:[jsxRuntimeExports.jsx("div",{className:styles$j_presetSectionHeader,children:jsxRuntimeExports.jsx("span",{className:styles$j_presetSectionTitle,children:t("ui.terminal.agentTeamCustom")})}),jsxRuntimeExports.jsx("div",{className:styles$j_presetList,onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:e=>{e.preventDefault(),e.stopPropagation()},children:0===items.length?jsxRuntimeExports.jsx("div",{className:styles$j_presetListEmptyHint,children:"—"}):items.map((item,idx)=>{const isBuiltinRaw=item.builtinId&&!item.modified,name=isBuiltinRaw?t(item.teamName):item.teamName,desc=isBuiltinRaw?t(item.description):item.description;return jsxRuntimeExports.jsxs("div",{className:`${styles$j_presetRow} ${dragIdx.current===idx?styles$j_presetRowDragging:""} ${dragOverIdx.current===idx&&dragIdx.current!==idx?styles$j_presetRowDragOver:""}`,onDragOver:e=>((idx,e)=>{e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="move",dragOverIdx.current!==idx&&(dragOverIdx.current=idx,forceRender(n=>n+1))})(idx,e),onDragLeave:e=>((idx,e)=>{e.stopPropagation(),dragOverIdx.current===idx&&(dragOverIdx.current=null,forceRender(n=>n+1))})(idx,e),onDrop:e=>((idx,e)=>{e.preventDefault(),e.stopPropagation();const from=dragIdx.current;if(null===from||from===idx)return void handleDragEnd();const arr=[...items],[moved]=arr.splice(from,1);arr.splice(from<idx?idx-1:idx,0,moved),onItemsChange(arr),savePresets(arr),handleDragEnd()})(idx,e),onDragEnd:handleDragEnd,children:[jsxRuntimeExports.jsx("span",{className:styles$j_dragHandle,draggable:!0,onDragStart:e=>((idx,e)=>{e.stopPropagation(),dragIdx.current=idx,e.dataTransfer.effectAllowed="move",requestAnimationFrame(()=>forceRender(n=>n+1))})(idx,e),children:jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 10 16",width:"10",height:"16",fill:"currentColor",children:[jsxRuntimeExports.jsx("circle",{cx:"3",cy:"3",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"7",cy:"3",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"3",cy:"8",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"7",cy:"8",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"3",cy:"13",r:"1.2"}),jsxRuntimeExports.jsx("circle",{cx:"7",cy:"13",r:"1.2"})]})}),jsxRuntimeExports.jsx(Checkbox,{checked:selected.has(item.id),onChange:()=>handleToggle(item.id)}),jsxRuntimeExports.jsx("span",{className:styles$j_presetName,title:name,children:name||"—"}),jsxRuntimeExports.jsx("span",{className:styles$j_presetText,title:desc,children:desc}),jsxRuntimeExports.jsx(Button,{size:"small",type:"link",onClick:()=>{setAddVisible(!0),setAddName(isBuiltinRaw?t(item.teamName):item.teamName),setAddText(isBuiltinRaw?t(item.description):item.description),setEditId(item.id)},children:t("ui.terminal.editItem")})]},item.id)})}),jsxRuntimeExports.jsxs("div",{className:styles$j_presetActions,children:[jsxRuntimeExports.jsx(Button,{size:"small",danger:!0,disabled:0===selected.size,onClick:handleDelete,children:t("ui.terminal.deleteSelected")}),jsxRuntimeExports.jsx(Button,{size:"small",onClick:()=>{setAddVisible(!0),setAddName(""),setAddText(""),setEditId(null)},children:t("ui.terminal.addItem")})]})]}),jsxRuntimeExports.jsxs(Modal,{title:t(editId?"ui.terminal.editItem":"ui.terminal.addItem"),open:addVisible,onCancel:()=>{setAddVisible(!1),setAddName(""),setAddText(""),setEditId(null)},onOk:handleAdd,okText:t(editId?"ui.ok":"ui.terminal.addItem"),cancelText:t("ui.cancel"),okButtonProps:{disabled:!addText.trim()&&!addName.trim()},width:"fit-content",styles:{content:{background:"var(--bg-elevated)",border:"1px solid var(--border-light)"},header:{background:"var(--bg-elevated)",borderBottom:"none"}},children:[jsxRuntimeExports.jsxs("div",{className:styles$j_presetFormField,children:[jsxRuntimeExports.jsxs("label",{className:styles$j_presetFormLabel,children:["Team ",t("ui.terminal.teamName")]}),jsxRuntimeExports.jsx("input",{className:styles$j_presetInput,placeholder:t("ui.terminal.teamNamePlaceholder"),value:addName,onChange:e=>setAddName(e.target.value)})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("label",{className:styles$j_presetFormLabel,children:["Team ",t("ui.terminal.teamDesc")]}),jsxRuntimeExports.jsx("textarea",{className:styles$j_presetTextarea,rows:6,placeholder:t("ui.terminal.presetInputPlaceholder"),value:addText,onChange:e=>setAddText(e.target.value),onKeyDown:e=>{"Enter"===e.key&&e.stopPropagation()}})]})]})]})}const styles$4_backdrop="_backdrop_9hzet_1",styles$4_modal="_modal_9hzet_11",styles$4_header="_header_9hzet_23",styles$4_title="_title_9hzet_30",styles$4_closeBtn="_closeBtn_9hzet_36",styles$4_headerActions="_headerActions_9hzet_54",styles$4_customWrap="_customWrap_9hzet_60",styles$4_customTitle="_customTitle_9hzet_66",styles$4_editPencil="_editPencil_9hzet_73",styles$4_disabledTip="_disabledTip_9hzet_104",styles$4_variantRow="_variantRow_9hzet_111",styles$4_roleBtn="_roleBtn_9hzet_119",styles$4_roleBtnActive="_roleBtnActive_9hzet_141",styles$4_addExpertBtn="_addExpertBtn_9hzet_151",styles$4_fileList="_fileList_9hzet_174",styles$4_fileChip="_fileChip_9hzet_181",styles$4_fileName="_fileName_9hzet_204",styles$4_fileRemove="_fileRemove_9hzet_211",styles$4_imageItem="_imageItem_9hzet_221",styles$4_imageThumb="_imageThumb_9hzet_235",styles$4_imageRemove="_imageRemove_9hzet_242",styles$4_textarea="_textarea_9hzet_274",styles$4_footer="_footer_9hzet_298",styles$4_sendBtn="_sendBtn_9hzet_305",styles$4_uploadBtn="_uploadBtn_9hzet_327";function UltraPlanModal({open:open,variant:variant,prompt:prompt,files:files,agentTeamEnabled:agentTeamEnabled,customExperts:customExperts,onClose:onClose,onVariantChange:onVariantChange,onPromptChange:onPromptChange,onSend:onSend,onUpload:onUpload,onPaste:onPaste,onRemoveFile:onRemoveFile,onOpenCustomEditor:onOpenCustomEditor}){const[lightbox,setLightbox]=reactExports.useState(null);if(!open)return null;const hasContent=(prompt||"").trim()||files.length>0,experts=Array.isArray(customExperts)?customExperts:[];return jsxRuntimeExports.jsxs("div",{className:styles$4_backdrop,onClick:onClose,children:[jsxRuntimeExports.jsxs("div",{className:styles$4_modal,onClick:e=>e.stopPropagation(),children:[jsxRuntimeExports.jsxs("div",{className:styles$4_header,children:[jsxRuntimeExports.jsx("span",{className:styles$4_title,children:t("ui.ultraplan.title")}),jsxRuntimeExports.jsx("div",{className:styles$4_headerActions,children:jsxRuntimeExports.jsx("button",{className:styles$4_closeBtn,onClick:onClose,children:jsxRuntimeExports.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[jsxRuntimeExports.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntimeExports.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})})]}),agentTeamEnabled?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:styles$4_variantRow,children:[jsxRuntimeExports.jsxs("button",{className:`${styles$4_roleBtn} ${"codeExpert"===variant?styles$4_roleBtnActive:""}`,onClick:()=>onVariantChange("codeExpert"),children:[jsxRuntimeExports.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("polyline",{points:"16 18 22 12 16 6"}),jsxRuntimeExports.jsx("polyline",{points:"8 6 2 12 8 18"})]}),t("ui.ultraplan.roleCodeExpert")]}),jsxRuntimeExports.jsxs("button",{className:`${styles$4_roleBtn} ${"researchExpert"===variant?styles$4_roleBtnActive:""}`,onClick:()=>onVariantChange("researchExpert"),children:[jsxRuntimeExports.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("circle",{cx:"11",cy:"11",r:"8"}),jsxRuntimeExports.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),t("ui.ultraplan.roleResearchExpert")]}),experts.map(item=>{const vkey="custom:"+item.id;return jsxRuntimeExports.jsxs("span",{className:styles$4_customWrap,children:[jsxRuntimeExports.jsxs("button",{className:`${styles$4_roleBtn} ${variant===vkey?styles$4_roleBtnActive:""}`,onClick:()=>onVariantChange(vkey),title:item.title,children:[jsxRuntimeExports.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("path",{d:"M12 2l2.4 7.2L22 12l-7.6 2.8L12 22l-2.4-7.2L2 12l7.6-2.8z"})}),jsxRuntimeExports.jsx("span",{className:styles$4_customTitle,children:item.title})]}),onOpenCustomEditor&&jsxRuntimeExports.jsx("span",{className:styles$4_editPencil,onClick:e=>{e.stopPropagation(),onOpenCustomEditor(item)},title:t("ui.ultraplan.customEditTitle"),children:jsxRuntimeExports.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M12 20h9"}),jsxRuntimeExports.jsx("path",{d:"M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z"})]})})]},item.id)}),onOpenCustomEditor&&jsxRuntimeExports.jsx("button",{type:"button",className:styles$4_addExpertBtn,onClick:()=>onOpenCustomEditor(null),title:t("ui.ultraplan.customAdd"),"aria-label":t("ui.ultraplan.customAdd"),children:jsxRuntimeExports.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:jsxRuntimeExports.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),files.length>0&&jsxRuntimeExports.jsx("div",{className:styles$4_fileList,children:files.map((f,i)=>{const isImage=/\.(png|jpe?g|gif|svg|bmp|webp|avif|ico|icns)$/i.test(f.name),src=apiUrl(`/api/file-raw?path=${encodeURIComponent(f.path)}`);return isImage?jsxRuntimeExports.jsxs("div",{className:styles$4_imageItem,title:f.name,children:[jsxRuntimeExports.jsx("img",{src:src,className:styles$4_imageThumb,alt:f.name,role:"button",tabIndex:0,onClick:e=>{e.stopPropagation(),setLightbox({src:src,alt:f.name})},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),setLightbox({src:src,alt:f.name}))}}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveImage"),onConfirm:()=>onRemoveFile(i),className:styles$4_imageRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},i):jsxRuntimeExports.jsxs("span",{className:styles$4_fileChip,title:f.name,children:[jsxRuntimeExports.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[jsxRuntimeExports.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),jsxRuntimeExports.jsx("polyline",{points:"14 2 14 8 20 8"})]}),jsxRuntimeExports.jsx("span",{className:styles$4_fileName,children:f.name}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveFile"),onConfirm:()=>onRemoveFile(i),className:styles$4_fileRemove,ariaLabel:t("ui.chatInput.removeImage"),tag:"span",children:"×"})]},i)})}),jsxRuntimeExports.jsx("textarea",{className:styles$4_textarea,value:prompt,onChange:e=>onPromptChange(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&hasContent&&(e.preventDefault(),onSend())},onPaste:onPaste,placeholder:t("ui.ultraplan.placeholder"),rows:5,autoFocus:!0}),jsxRuntimeExports.jsxs("div",{className:styles$4_footer,children:[jsxRuntimeExports.jsx("button",{className:styles$4_sendBtn,disabled:!hasContent,onClick:onSend,children:t("ui.ultraplan.send")}),jsxRuntimeExports.jsxs("button",{className:styles$4_uploadBtn,onClick:onUpload,children:[jsxRuntimeExports.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),t("ui.ultraplan.upload")]})]})]}):jsxRuntimeExports.jsx("div",{className:styles$4_disabledTip,children:t("ui.ultraplan.agentTeamRequired")})]}),lightbox&&jsxRuntimeExports.jsx(ImageLightbox,{src:lightbox.src,alt:lightbox.alt,zIndex:1150,onClose:()=>setLightbox(null)})]})}const NOOP=()=>{};class StickyBottomController{constructor(opts={}){this._getSticky=opts.getSticky||(()=>!1),this._setStickyExternal=opts.setSticky||NOOP,this._getMode=opts.getMode||(()=>"desktop"),this._thresholdEnter=opts.thresholdEnter??10,this._thresholdLeave=opts.thresholdLeave??50,this._touchSuppressMs=opts.touchSuppressMs??300,this._atBottomPx=opts.atBottomPx??60,this._now=opts.now||(()=>Date.now()),this._lockDepth=0,this._smoothLockHeld=!1,this._followTarget=0,this._smoothFollowRafId=null,this._scrollHandlerRafId=null,this._writeLockRafIds=new Set,this._resizeObserver=null,this._boundEl=null,this._touchListenersAttached=!1,this._recentTouchTs=0,this._lastStickyValue=null,this._lastStickyTs=0,this._disposed=!1,this._onScroll=()=>{this._disposed||this._lockDepth>0||null===this._scrollHandlerRafId&&(this._scrollHandlerRafId=this._raf(()=>{if(this._scrollHandlerRafId=null,this._disposed)return;const el=this._boundEl;if(!el)return;const gap=this._followTarget-el.scrollTop,sticky=this._getSticky();sticky&&gap>this._thresholdLeave?this._setSticky(!1):!sticky&&gap<=this._thresholdEnter&&this._setSticky(!0)}))},this._onTouchStart=()=>{this._recentTouchTs=-1},this._onTouchEnd=()=>{this._recentTouchTs=this._now()}}_raf(fn){return"function"==typeof globalThis.requestAnimationFrame?globalThis.requestAnimationFrame(fn):setTimeout(fn,0)}_cancelRaf(id){if(null!=id)if("function"==typeof globalThis.cancelAnimationFrame)try{globalThis.cancelAnimationFrame(id)}catch{}else try{clearTimeout(id)}catch{}}_setSticky(value){if(this._disposed)return;const ts=this._now();if(!(this._lastStickyValue===value&&ts-this._lastStickyTs<16)){this._lastStickyValue=value,this._lastStickyTs=ts;try{this._setStickyExternal(value)}catch{}}}_attachTouchListenersOnce(){if(!this._touchListenersAttached&&"undefined"!=typeof document&&"function"==typeof document.addEventListener){this._touchListenersAttached=!0;try{document.addEventListener("touchstart",this._onTouchStart,{passive:!0}),document.addEventListener("touchend",this._onTouchEnd,{passive:!0}),document.addEventListener("touchcancel",this._onTouchEnd,{passive:!0})}catch{}}}_detachTouchListeners(){if(this._touchListenersAttached&&"undefined"!=typeof document&&"function"==typeof document.removeEventListener){try{document.removeEventListener("touchstart",this._onTouchStart),document.removeEventListener("touchend",this._onTouchEnd),document.removeEventListener("touchcancel",this._onTouchEnd)}catch{}this._touchListenersAttached=!1}}bind(el){if(this._disposed)return;if(el===this._boundEl)return;if(this._boundEl&&this._detachFromBoundEl(),this._boundEl=el||null,!el)return;if("virtuoso"!==this._getMode())try{el.addEventListener("scroll",this._onScroll,{passive:!0})}catch{}if("undefined"!=typeof ResizeObserver)try{this._resizeObserver=new ResizeObserver(()=>this.handleScrollerResize(el)),this._resizeObserver.observe(el)}catch{}this.refreshFollowTarget(el),this._attachTouchListenersOnce()}_detachFromBoundEl(){const el=this._boundEl;if(el){try{el.removeEventListener("scroll",this._onScroll)}catch{}if(this._resizeObserver){try{this._resizeObserver.disconnect()}catch{}this._resizeObserver=null}this._boundEl=null}}unbind(){this._detachFromBoundEl(),null!==this._scrollHandlerRafId&&(this._cancelRaf(this._scrollHandlerRafId),this._scrollHandlerRafId=null),null!==this._smoothFollowRafId&&(this._cancelRaf(this._smoothFollowRafId),this._smoothFollowRafId=null);for(const id of this._writeLockRafIds)this._cancelRaf(id);this._writeLockRafIds.clear()}dispose(){this._disposed||(this._disposed=!0,this.unbind(),this._detachTouchListeners(),this._lockDepth=0,this._smoothLockHeld=!1)}isLocked(){return this._lockDepth>0}refreshFollowTarget(el){if(this._disposed)return;const target=el||this._boundEl;if(!target)return;const sh=target.scrollHeight??0,ch=target.clientHeight??0;this._followTarget=Math.max(0,sh-ch)}writeUnderLock(el,target){if(this._disposed)return;if(!el)return;if("number"!=typeof el.scrollTop)return;if(!Number.isFinite(target))return;this._lockDepth++;try{el.scrollTop=target}catch{}let inner2=null;const outer=this._raf(()=>{this._writeLockRafIds.delete(outer),this._disposed||(inner2=this._raf(()=>{this._writeLockRafIds.delete(inner2),this._disposed||(this._lockDepth=Math.max(0,this._lockDepth-1))}),null!=inner2&&this._writeLockRafIds.add(inner2))});null!=outer&&this._writeLockRafIds.add(outer)}suppressOnce(){if(this._disposed)return;this._lockDepth++;const id=this._raf(()=>{this._writeLockRafIds.delete(id),this._disposed||(this._lockDepth=Math.max(0,this._lockDepth-1))});null!=id&&this._writeLockRafIds.add(id)}startSmoothFollow(el){if(this._disposed)return;const scroller=el||this._boundEl;if(!scroller)return;this._smoothLockHeld||(this._lockDepth++,this._smoothLockHeld=!0),null!==this._smoothFollowRafId&&(this._cancelRaf(this._smoothFollowRafId),this._smoothFollowRafId=null);const release=()=>{this._smoothLockHeld&&(this._smoothLockHeld=!1,this._lockDepth=Math.max(0,this._lockDepth-1))},step=()=>{if(this._smoothFollowRafId=null,this._disposed)return void release();if(!this._getSticky())return void release();const target=this._followTarget,current=scroller.scrollTop??0,gap=target-current;if(!Number.isFinite(gap))return void release();if(gap<=.5){try{scroller.scrollTop=target}catch{}return void release()}const delta=Math.max(1,Math.min(.35*gap,120));try{scroller.scrollTop=current+delta}catch{}this._smoothFollowRafId=this._raf(step)};this._smoothFollowRafId=this._raf(()=>{this._disposed?release():this._smoothFollowRafId=this._raf(()=>{this._disposed?release():(this.refreshFollowTarget(scroller),step())})})}cancelSmoothFollow(){this._disposed||(null!==this._smoothFollowRafId&&(this._cancelRaf(this._smoothFollowRafId),this._smoothFollowRafId=null),this._smoothLockHeld&&(this._smoothLockHeld=!1,this._lockDepth=Math.max(0,this._lockDepth-1)))}handleScrollerResize(el){if(this._disposed)return;const target=el||this._boundEl;target&&(this.refreshFollowTarget(target),this._getSticky()&&(this._lockDepth>0||this._isWithinTouchSuppress()||this.writeUnderLock(target,this._followTarget)))}_isWithinTouchSuppress(){return-1===this._recentTouchTs||!(this._recentTouchTs<=0)&&this._now()-this._recentTouchTs<this._touchSuppressMs}notifyAtBottom(isAtBottom){if(this._disposed)return;if(this._lockDepth>0)return;const el=this._boundEl;if(el&&"number"==typeof el.scrollHeight){const realGap=(el.scrollHeight??0)-(el.scrollTop??0)-(el.clientHeight??0);if(!isAtBottom&&this._getSticky()&&realGap<=this._atBottomPx)return;if(isAtBottom&&!this._getSticky()&&realGap>this._atBottomPx)return}this._setSticky(!!isAtBottom)}}const SYSTEM_OPEN_EXTS=new Set(["doc","docx","xls","xlsx","ppt","pptx","odt","ods","odp","pdf"]);function tryOpenWithSystem(path,source2){const ext=(path||"").split(".").pop().toLowerCase();return!!SYSTEM_OPEN_EXTS.has(ext)&&(fetch(apiUrl("/api/open-file"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:path,source:source2})}).catch(()=>{}),!0)}const shimmerUrl="/assets/shimmer-BBDejmDf.svg",styles$3_centerEmpty="_centerEmpty_118cz_1",styles$3_container="_container_118cz_8",styles$3_mobileVirtuoso="_mobileVirtuoso_118cz_19",styles$3_sessionDividerText="_sessionDividerText_118cz_24",styles$3_lastResponseLabel="_lastResponseLabel_118cz_29",styles$3_splitContainer="_splitContainer_118cz_33",styles$3_chatSection="_chatSection_118cz_40",styles$3_vResizer="_vResizer_118cz_48",styles$3_terminalToggle="_terminalToggle_118cz_62",styles$3_messageListWrap="_messageListWrap_118cz_85",styles$3_stickyBottomBtn="_stickyBottomBtn_118cz_93",styles$3_loadingPet="_loadingPet_118cz_120",styles$3_loadMoreWrap="_loadMoreWrap_118cz_154",styles$3_loadMoreBtn="_loadMoreBtn_118cz_160",styles$3_navSidebar="_navSidebar_118cz_176",styles$3_navBtn="_navBtn_118cz_193",styles$3_navBtnActive="_navBtnActive_118cz_213",styles$3_navDivider="_navDivider_118cz_228",styles$3_navAvatarImg="_navAvatarImg_118cz_241",styles$3_userPromptNavList="_userPromptNavList_118cz_248",styles$3_userPromptNavItem="_userPromptNavItem_118cz_257",styles$3_terminalPanelWrap="_terminalPanelWrap_118cz_277",styles$3_navSidebarContent="_navSidebarContent_118cz_288",styles$3_innerSplitArea="_innerSplitArea_118cz_296",styles$3_chatSectionFlex="_chatSectionFlex_118cz_303",styles$3_inputStack="_inputStack_118cz_313",styles$3_overlayPanel="_overlayPanel_118cz_318",styles$3_streamingSpinnerWrap="_streamingSpinnerWrap_118cz_326",styles$3_streamingSpinnerHidden="_streamingSpinnerHidden_118cz_333",styles$3_sessionDivider="_sessionDivider_118cz_24",styles$3_loadMoreBtnLoading="_loadMoreBtnLoading_118cz_342",styles$3_loadMoreSpinner="_loadMoreSpinner_118cz_350",styles$3_lastResponseDivider="_lastResponseDivider_118cz_364",styles$3_hideLastResponseDivider="_hideLastResponseDivider_118cz_377",{Text:Text}=Typography,useVirtuoso=isMobile&&!isIOS&&!isPad,EMPTY_MAP={},ASK_KIND_HOOK="hook",ASK_KIND_SDK="sdk",VirtuosoScroller=React__default.forwardRef((props,ref)=>jsxRuntimeExports.jsx("div",{ref:ref,...props,className:styles$3_container}));class ChatView extends React__default.Component{constructor(props){super(props),__publicField(this,"handleStickToBottom",()=>{this.setState({stickyBottom:!0},()=>{if(useVirtuoso&&this.virtuosoRef.current)this.virtuosoRef.current.scrollToIndex({index:"LAST",behavior:"smooth"});else{const el=this.containerRef.current;el&&this._stickyController.writeUnderLock(el,el.scrollHeight)}})}),__publicField(this,"_addPendingImage",(path,source2)=>{path&&this.setState(prev=>prev.pendingImages.length>=20||prev.pendingImages.some(img=>img.path===path)?null:{pendingImages:[...prev.pendingImages,{path:path,source:source2}]})}),__publicField(this,"_removePendingImage",index=>{this.setState(prev=>{const img=prev.pendingImages[index];if(!img)return null;const next=prev.pendingImages.filter((_,i)=>i!==index);return img.path&&this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"image-remove-notify",path:img.path})),{pendingImages:next}})}),__publicField(this,"_clearPendingImages",()=>{this.state.pendingImages.length>0&&this.setState({pendingImages:[]})}),__publicField(this,"handleLoadMore",()=>{var _a;this._mobileExtraItems+=100;const prevLen=(null==(_a=this.state.allItems)?void 0:_a.length)||0,rawItems=this.buildAllItems(),allItems=this._applyMobileSlice(rawItems),addedCount=allItems.length-prevLen;if(useVirtuoso&&this.virtuosoRef.current)this.setState({allItems:allItems,lastResponseItems:this._lastResponseItems,visibleCount:allItems.length},()=>{this.virtuosoRef.current&&addedCount>0&&this.virtuosoRef.current.scrollToIndex({index:addedCount,align:"start"})});else{const el=this.containerRef.current,prevScrollHeight=el?el.scrollHeight:0,prevScrollTop=el?el.scrollTop:0;this.setState({allItems:allItems,lastResponseItems:this._lastResponseItems,visibleCount:allItems.length},()=>{if(el){this._stickyController.suppressOnce();const newScrollHeight=el.scrollHeight;el.scrollTop=prevScrollTop+(newScrollHeight-prevScrollHeight)}})}}),__publicField(this,"handlePresetSend",description=>{if(!description)return;const textarea2=this._inputRef.current;textarea2&&(textarea2.value=description,textarea2.style.height="auto",textarea2.style.height=Math.min(textarea2.scrollHeight,isMobile&&!isPad?160:120)+"px",this.setState({inputEmpty:!1}),textarea2.focus())}),__publicField(this,"_handleUltraplanSend",()=>{const trimmed=this.state.ultraplanPrompt.trim();if(!trimmed&&0===this.state.ultraplanFiles.length)return;const filePaths=this.state.ultraplanFiles.map(f=>`"${f.path}"`).join(" "),userInput=filePaths?trimmed?`${filePaths} ${trimmed}`:filePaths:trimmed,variant=this.state.ultraplanVariant;let assembled;if("string"==typeof variant&&variant.startsWith("custom:")){const id=variant.slice(7),item=this.state.customUltraplanExperts.find(e=>e.id===id);if(!item)return;assembled=buildLocalUltraplan(userInput,"custom",0,item.content)}else assembled=buildLocalUltraplan(userInput,variant);if(!assembled)return;const textarea2=this._inputRef.current;textarea2&&(textarea2.value=assembled,textarea2.style.height="auto",textarea2.style.height=Math.min(textarea2.scrollHeight,120)+"px",this.setState({inputEmpty:!1,ultraplanModalOpen:!1,ultraplanPrompt:"",ultraplanVariant:"codeExpert",ultraplanFiles:[]},()=>{this.handleInputSend()}))}),__publicField(this,"_handleUltraplanUpload",()=>{const input=document.createElement("input");input.type="file",input.onchange=async e=>{var _a;const file=null==(_a=e.target.files)?void 0:_a[0];if(file)try{const path=await uploadFileAndGetPath(file);this.setState(prev=>({ultraplanFiles:[...prev.ultraplanFiles,{name:file.name,path:path}]}))}catch(err){console.error("Ultraplan upload failed:",err),staticMethods.error((null==err?void 0:err.message)||"Upload failed")}},input.click()}),__publicField(this,"_handleUltraplanPaste",async e=>{var _a;const items=null==(_a=e.clipboardData)?void 0:_a.items;if(items)for(const item of items)if(item.type.startsWith("image/")){e.preventDefault();const file=item.getAsFile();if(!file)return;try{const path=await uploadFileAndGetPath(file),name=file.name||`paste-${Date.now()}.png`;this.setState(prev=>({ultraplanFiles:[...prev.ultraplanFiles,{name:name,path:path}]}))}catch(err){console.error("Ultraplan paste upload failed:",err),staticMethods.error((null==err?void 0:err.message)||"Upload failed")}return}}),__publicField(this,"_handleUltraplanRemoveFile",idx=>{this.setState(prev=>({ultraplanFiles:prev.ultraplanFiles.filter((_,i)=>i!==idx)}))}),__publicField(this,"_openCustomUltraplanEditor",item=>{this.setState(prev=>({customUltraplanEditOpen:!0,customUltraplanEditing:item||null,_ultraplanWasOpenBeforeEdit:prev.ultraplanModalOpen,ultraplanModalOpen:!1}))}),__publicField(this,"_closeCustomUltraplanEditor",()=>{this.setState(prev=>({customUltraplanEditOpen:!1,customUltraplanEditing:null,ultraplanModalOpen:!!prev._ultraplanWasOpenBeforeEdit,_ultraplanWasOpenBeforeEdit:!1}))}),__publicField(this,"_persistCustomUltraplanExperts",experts=>{this.setState({customUltraplanExperts:experts}),this.props.onUpdatePreferences&&this.props.onUpdatePreferences({customUltraplanExperts:experts})}),__publicField(this,"_saveCustomUltraplanExpert",item=>{const existing=this.state.customUltraplanExperts,next=existing.findIndex(e=>e.id===item.id)>=0?existing.map(e=>e.id===item.id?item:e):[...existing,item];this._persistCustomUltraplanExperts(next),this._closeCustomUltraplanEditor()}),__publicField(this,"_deleteCustomUltraplanExpert",id=>{const next=this.state.customUltraplanExperts.filter(e=>e.id!==id);this._persistCustomUltraplanExperts(next),this.state.ultraplanVariant==="custom:"+id&&this.setState({ultraplanVariant:"codeExpert"}),this._closeCustomUltraplanEditor()}),__publicField(this,"_promoteNextAskFromQueue",()=>{const queue=this.state.askQueue,next=queue&&queue.length>0?queue[0]:null;next?(next.kind===ASK_KIND_SDK?(this._sdkAskId=next.id,this._askHookActive=!1):(this._sdkAskId=null,this._askHookActive=!0),this._askHookQuestions=next.questions,this.setState({pendingAsk:{id:next.id,questions:next.questions},askQueue:queue.slice(1)})):(this._askHookActive=!1,this._sdkAskId=null,this._askHookQuestions=null,this.setState({pendingAsk:null,askQueue:[]}))}),__publicField(this,"_onTerminalWsMessage",msg=>{var _a,_b,_c,_d,_e,_f,_g,_h;try{if("data"===msg.type)this._appendPtyData(msg.data);else if("exit"===msg.type)this._clearPtyPrompt();else if("ask-hook-pending"===msg.type){if(Array.isArray(msg.questions)&&msg.questions.length>0){const askId=null!=msg.id?String(msg.id):"__ask__";null==msg.id&&"__ask__"===(null==(_a=this.state.pendingAsk)?void 0:_a.id)&&console.warn("[ChatView] legacy ask-hook-pending without id arrived while a placeholder ask is already active — second ask will be silently dropped (legacy server does not support concurrent asks). Upgrade server to enable multi-ask multiplexing."),this.setState(state=>state.pendingAsk?state.pendingAsk.id===askId||state.askQueue.some(a=>a.id===askId)?null:{askQueue:[...state.askQueue,{id:askId,questions:msg.questions,kind:ASK_KIND_HOOK}]}:(this._askHookActive=!0,this._askHookQuestions=msg.questions,this._sdkAskId=null,{pendingAsk:{id:askId,questions:msg.questions}}))}}else if("ask-hook-timeout"===msg.type){const askId=null!=msg.id?String(msg.id):null;if(null==askId)return void("__ask__"===(null==(_b=this.state.pendingAsk)?void 0:_b.id)&&this._promoteNextAskFromQueue());(null==(_c=this.state.pendingAsk)?void 0:_c.id)===askId?this._promoteNextAskFromQueue():this.state.askQueue.some(a=>a.id===askId)&&this.setState(state=>({askQueue:state.askQueue.filter(a=>a.id!==askId)}))}else if("sdk-plan-pending"===msg.type)this.setState({pendingPlanApproval:{id:msg.id,input:msg.input}});else if("sdk-ask-pending"===msg.type){if(null==msg.id)return void console.warn("[ChatView] sdk-ask-pending missing id — server invariant violated, ignoring");if(Array.isArray(msg.questions)&&msg.questions.length>0){const askId=String(msg.id);this.setState(state=>state.pendingAsk?state.pendingAsk.id===askId||state.askQueue.some(a=>a.id===askId)?null:{askQueue:[...state.askQueue,{id:askId,questions:msg.questions,kind:ASK_KIND_SDK}]}:(this._askHookActive=!0,this._askHookQuestions=msg.questions,this._sdkAskId=msg.id,{pendingAsk:{id:askId,questions:msg.questions}}))}}else if("sdk-ask-timeout"===msg.type){const askId=null!=msg.id?String(msg.id):null;if(null==askId)return;(null==(_d=this.state.pendingAsk)?void 0:_d.id)===askId?this._promoteNextAskFromQueue():this.state.askQueue.some(a=>a.id===askId)&&this.setState(state=>({askQueue:state.askQueue.filter(a=>a.id!==askId)}))}else if("perm-hook-pending"===msg.type)this.setState(state=>state.pendingPermission?{permissionQueue:[...state.permissionQueue,{id:msg.id,toolName:msg.toolName,input:msg.input}]}:{pendingPermission:{id:msg.id,toolName:msg.toolName,input:msg.input}});else if("perm-hook-timeout"===msg.type)this.setState(state=>{var _a2;if(msg.id&&(null==(_a2=state.pendingPermission)?void 0:_a2.id)===msg.id){return{pendingPermission:state.permissionQueue[0]||null,permissionQueue:state.permissionQueue.slice(1)}}return msg.id?{permissionQueue:state.permissionQueue.filter(p=>p.id!==msg.id)}:{pendingPermission:null,permissionQueue:[]}});else if("perm-hook-resolved"===msg.type)this.setState(state=>{var _a2;if((null==(_a2=state.pendingPermission)?void 0:_a2.id)===msg.id){return{pendingPermission:state.permissionQueue[0]||null,permissionQueue:state.permissionQueue.slice(1)}}return{permissionQueue:state.permissionQueue.filter(p=>p.id!==msg.id)}});else if("ask-hook-resolved"===msg.type){const askId=null!=msg.id?String(msg.id):null;null==askId?"__ask__"===(null==(_e=this.state.pendingAsk)?void 0:_e.id)&&this._promoteNextAskFromQueue():(null==(_f=this.state.pendingAsk)?void 0:_f.id)===askId?this._promoteNextAskFromQueue():this.state.askQueue.some(a=>a.id===askId)&&this.setState(state=>({askQueue:state.askQueue.filter(a=>a.id!==askId)}))}else if("sdk-ask-resolved"===msg.type){const askId=null!=msg.id?String(msg.id):null;null!=askId&&(null==(_g=this.state.pendingAsk)?void 0:_g.id)===askId?this._promoteNextAskFromQueue():null!=askId&&this.state.askQueue.some(a=>a.id===askId)&&this.setState(state=>({askQueue:state.askQueue.filter(a=>a.id!==askId)}))}else"sdk-plan-resolved"===msg.type?(null==(_h=this.state.pendingPlanApproval)?void 0:_h.id)===msg.id&&this.setState({pendingPlanApproval:null}):"image-upload-notify"===msg.type?this._addPendingImage(msg.path,msg.source):"image-remove-notify"===msg.type&&msg.path&&this.setState(prev=>{const next=prev.pendingImages.filter(img=>img.path!==msg.path);return next.length===prev.pendingImages.length?null:{pendingImages:next}})}catch{}}),__publicField(this,"_onTerminalWsState",state=>{var _a,_b,_c;if("close"===state){(null==(_a=this.state.pendingPtyPlan)?void 0:_a.id)&&this._resolvedPlanIds.add(this.state.pendingPtyPlan.id);try{if("undefined"!=typeof window&&(null==(_b=window.tabBridge)?void 0:_b.notifyAskResolved)){const tabId=this.props.ownTabId??null;if(this.state.pendingAsk)try{window.tabBridge.notifyAskResolved({id:this.state.pendingAsk.id,tabId:tabId})}catch{}for(const q of this.state.askQueue||[])try{window.tabBridge.notifyAskResolved({id:q.id,tabId:tabId})}catch{}}}catch{}(this.state.pendingPermission||this.state.pendingPlanApproval||this.state.pendingAsk||this.state.pendingPtyPlan||(null==(_c=this.state.askQueue)?void 0:_c.length))&&this.setState({pendingPermission:null,permissionQueue:[],pendingPlanApproval:null,pendingAsk:null,askQueue:[],pendingPtyPlan:null}),this._sdkAskId=null,this._askHookActive=!1,this._askHookQuestions=null}}),__publicField(this,"handlePromptOptionClick",number=>{var _a;if(this._promptSubmitting)return;const ws=this._inputWs;if(!ws||ws.readyState!==WebSocket.OPEN)return;let prompt=this.state.ptyPrompt;prompt||(prompt=this.state.ptyPromptHistory.slice().reverse().find(p=>"active"===p.status)||{options:Array.from({length:Math.max(number,3)},(_,i)=>({number:i+1,selected:0===i}))}),this._promptSubmitting=!0;const options=prompt.options,targetIdx=options.findIndex(o2=>o2.number===number);let currentIdx=options.findIndex(o2=>o2.selected);currentIdx<0&&(currentIdx=0);const diff=targetIdx-currentIdx,arrowKey=diff>0?"[B":"[A",steps=Math.abs(diff),sendStep=i=>{i<steps?(ws.send(JSON.stringify({type:"input",data:arrowKey})),setTimeout(()=>sendStep(i+1),30)):setTimeout(()=>{ws.readyState===WebSocket.OPEN&&ws.send(JSON.stringify({type:"input",data:"\r"}))},50)};sendStep(0),this._currentPtyPrompt=null,(null==(_a=this.state.pendingPtyPlan)?void 0:_a.id)&&this._resolvedPlanIds.add(this.state.pendingPtyPlan.id),this.setState(state=>{const history=state.ptyPromptHistory.slice(),last=history[history.length-1];return last&&"active"===last.status&&(history[history.length-1]={...last,status:"answered",selectedNumber:number}),{ptyPrompt:null,ptyPromptHistory:history,pendingPtyPlan:null}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),setTimeout(()=>{this._promptSubmitting=!1},500)}),__publicField(this,"_shiftPermissionQueue",()=>{this.setState(state=>({pendingPermission:state.permissionQueue[0]||null,permissionQueue:state.permissionQueue.slice(1)}))}),__publicField(this,"handlePermissionAllow",id=>{const perm=this.state.pendingPermission;if("pty"===(null==perm?void 0:perm.source)&&perm.ptyPrompt){const optNum=this._findPtyOptionNumber(perm.ptyPrompt,"allow");return this.handlePromptOptionClick(optNum),void this._shiftPermissionQueue()}const ws=this._inputWs;ws&&ws.readyState===WebSocket.OPEN&&ws.send(JSON.stringify({type:"perm-hook-answer",id:id,decision:"allow"})),this._shiftPermissionQueue()}),__publicField(this,"handlePermissionAllowSession",id=>{const perm=this.state.pendingPermission;if("pty"===(null==perm?void 0:perm.source)&&perm.ptyPrompt){const optNum=this._findPtyOptionNumber(perm.ptyPrompt,"allowSession");return this.handlePromptOptionClick(optNum),void this._shiftPermissionQueue()}const ws=this._inputWs;ws&&ws.readyState===WebSocket.OPEN&&ws.send(JSON.stringify({type:"perm-hook-answer",id:id,decision:"allow",allowSession:!0})),this._shiftPermissionQueue()}),__publicField(this,"handlePermissionDeny",id=>{const perm=this.state.pendingPermission;if("pty"===(null==perm?void 0:perm.source)&&perm.ptyPrompt){const optNum=this._findPtyOptionNumber(perm.ptyPrompt,"deny");return this.handlePromptOptionClick(optNum),void this._shiftPermissionQueue()}const ws=this._inputWs;ws&&ws.readyState===WebSocket.OPEN&&ws.send(JSON.stringify({type:"perm-hook-answer",id:id,decision:"deny"})),this._shiftPermissionQueue()}),__publicField(this,"handlePlanApprove",id=>{const ws=this._inputWs;ws&&ws.readyState===WebSocket.OPEN&&ws.send(JSON.stringify({type:"sdk-plan-answer",id:id,approve:!0})),this.setState({pendingPlanApproval:null})}),__publicField(this,"handlePlanReject",(id,feedback)=>{const ws=this._inputWs;ws&&ws.readyState===WebSocket.OPEN&&ws.send(JSON.stringify({type:"sdk-plan-answer",id:id,approve:!1,feedback:feedback||""})),this.setState({pendingPlanApproval:null})}),__publicField(this,"handlePlanFeedbackSubmit",(number,text)=>{var _a;const ws=this._inputWs;if(!ws||ws.readyState!==WebSocket.OPEN)return;let prompt=this.state.ptyPrompt;prompt||(prompt=this.state.ptyPromptHistory.slice().reverse().find(p=>"active"===p.status)||{options:Array.from({length:Math.max(number,3)},(_,i)=>({number:i+1,selected:0===i}))});const options=prompt.options,targetIdx=options.findIndex(o2=>o2.number===number);let currentIdx=options.findIndex(o2=>o2.selected);currentIdx<0&&(currentIdx=0);const diff=targetIdx-currentIdx,arrowKey=diff>0?"[B":"[A",steps=Math.abs(diff),sendStep=i=>{i<steps?(ws.send(JSON.stringify({type:"input",data:arrowKey})),setTimeout(()=>sendStep(i+1),30)):setTimeout(()=>{ws.send(JSON.stringify({type:"input",data:"\r"}));const startBuf=this._ptyBuffer;let attempts=0;const poll=()=>{attempts++,attempts>20||this._ptyBuffer!==startBuf?ws.readyState===WebSocket.OPEN&&(ws.send(JSON.stringify({type:"input",data:text})),setTimeout(()=>{ws.send(JSON.stringify({type:"input",data:"\r"}))},50)):setTimeout(poll,100)};setTimeout(poll,100)},50)};sendStep(0),this._currentPtyPrompt=null,(null==(_a=this.state.pendingPtyPlan)?void 0:_a.id)&&this._resolvedPlanIds.add(this.state.pendingPtyPlan.id),this.setState(state=>{const history=state.ptyPromptHistory.slice(),last=history[history.length-1];return last&&"active"===last.status&&(history[history.length-1]={...last,status:"answered",selectedNumber:number}),{ptyPrompt:null,ptyPromptHistory:history,pendingPtyPlan:null}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)}),__publicField(this,"handleAskQuestionSubmit",(answers,askId,questions)=>{var _a,_b,_c;const submitCtx={headAskId:(null==(_a=this.state.pendingAsk)?void 0:_a.id)||null,hookQuestions:this._askHookQuestions,wasHookActive:this._askHookActive,wasSdkAskId:this._sdkAskId};if(askId&&questions){const localAnswers={};for(const answer of answers){const q=questions[answer.questionIndex];if(q)if("other"===answer.type)localAnswers[q.question]=answer.text;else if("multi"===answer.type){const labels=answer.selectedIndices.map(i=>{var _a2;return null==(_a2=(q.options||[])[i])?void 0:_a2.label}).filter(Boolean);localAnswers[q.question]=labels.join(", ")}else localAnswers[q.question]=(null==(_b=(q.options||[])[answer.optionIndex])?void 0:_b.label)||""}this._lastClearedPendingAsk=this.state.pendingAsk,this._lastAskSubmitId=askId,this.setState(prev=>({localAskAnswers:{...prev.localAskAnswers||{},[askId]:localAnswers}})),this._promoteNextAskFromQueue()}if(this.props.sdkMode){const resolvedId=askId||submitCtx.wasSdkAskId;if(!resolvedId)return this._lastClearedPendingAsk=null,void(this._lastAskSubmitId=null);const ws=this._inputWs;if(ws&&ws.readyState===WebSocket.OPEN){const sdkAnswers={},qs=submitCtx.hookQuestions||questions;for(const answer of answers){const q=null==qs?void 0:qs[answer.questionIndex];if(q)if("other"===answer.type)sdkAnswers[q.question]=answer.text;else if("multi"===answer.type){const labels=answer.selectedIndices.map(i=>{var _a2;return null==(_a2=(q.options||[])[i])?void 0:_a2.label}).filter(Boolean);sdkAnswers[q.question]=labels.join(", ")}else sdkAnswers[q.question]=(null==(_c=(q.options||[])[answer.optionIndex])?void 0:_c.label)||""}ws.send(JSON.stringify({type:"sdk-ask-answer",id:resolvedId,answers:sdkAnswers})),this._lastClearedPendingAsk=null,this._lastAskSubmitId=null}else this._lastClearedPendingAsk=null,this._lastAskSubmitId=null;return}if(!submitCtx.wasHookActive||this._askSubmitting)return submitCtx.wasHookActive||this._askSubmitting||!this._inputWs||this._inputWs.readyState!==WebSocket.OPEN?void this._submitViaPty(answers):(this._pendingHookAnswers=answers,this._askHookWaitRetries=0,this._askSubmitting=!0,void this._waitForHookBridge());this._submitViaHookBridge(answers,submitCtx.headAskId,submitCtx.hookQuestions)}),__publicField(this,"handleInputStop",()=>{this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:""}))}),__publicField(this,"handleInputSend",()=>{const textarea2=this._inputRef.current;if(!textarea2)return;const userText=textarea2.value.trim(),imagePaths=this.state.pendingImages.map(img=>`"${img.path.replace(/"/g,"")}"`).join(" "),text=imagePaths?userText?`${imagePaths} ${userText}`:imagePaths:userText;text&&this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&(this.props.sdkMode?this._inputWs.send(JSON.stringify({type:"sdk-user-message",text:text})):(this._inputWs.send(JSON.stringify({type:"input",data:text})),setTimeout(()=>{this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:"\r"}))},50)),textarea2.value="",textarea2.style.height="auto",this._clearPendingImages(),this.setState({inputEmpty:!0,pendingInput:userText||imagePaths,inputSuggestion:null},()=>this.scrollToBottom()))}),__publicField(this,"handleInputKeyDown",e=>{if("Tab"===e.key&&this.state.inputSuggestion){e.preventDefault();const textarea2=this._inputRef.current;return textarea2&&(textarea2.value=this.state.inputSuggestion,textarea2.style.height="auto",textarea2.style.height=Math.min(textarea2.scrollHeight,120)+"px"),void this.setState({inputSuggestion:null,inputEmpty:!1})}"Enter"!==e.key||e.shiftKey||e.isComposing||229===e.keyCode||(e.preventDefault(),this.handleInputSend())}),__publicField(this,"handleInputChange",e=>{const textarea2=e.target;textarea2.style.height="auto",textarea2.style.height=Math.min(textarea2.scrollHeight,120)+"px";const empty2=!textarea2.value.trim();this.setState({inputEmpty:empty2}),this.state.inputSuggestion&&!empty2&&this.setState({inputSuggestion:null})}),__publicField(this,"handleSuggestionToTerminal",()=>{const text=this.state.inputSuggestion;text&&this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&(this._inputWs.send(JSON.stringify({type:"input",data:text})),setTimeout(()=>{this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:"\r"}))},50),this.setState({inputSuggestion:null,pendingInput:text},()=>this.scrollToBottom()))}),__publicField(this,"handleUploadPath",path=>{this._addPendingImage(path,"chat"),this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"image-upload-notify",path:path,source:"chat"}))}),__publicField(this,"handleSplitMouseDown",e=>{e.preventDefault(),this._resizing=!0,this._dragTarget="terminal";let snapLines=[];const container2=this.innerSplitRef.current;if(container2){const containerWidth=container2.getBoundingClientRect().width,charWidth=7.8,resizerWidth=5;snapLines=[60,80,100,120].map(cols=>{const terminalPx=cols*charWidth,totalTerminalWidth=terminalPx+resizerWidth;if(totalTerminalWidth>.75*containerWidth||totalTerminalWidth<.15*containerWidth)return null;return{cols:cols,terminalPx:terminalPx,linePosition:containerWidth-terminalPx-resizerWidth}}).filter(snap=>null!==snap)}this.setState({isDragging:!0,snapLines:snapLines});const onMouseMove=ev=>{if(!this._resizing)return;const container22=this.innerSplitRef.current;if(!container22)return;const rect=container22.getBoundingClientRect(),containerWidth=rect.width;let tw=rect.right-ev.clientX;tw=Math.max(200,Math.min(.75*containerWidth,tw));let activeSnapLine=null;if(snapLines.length>0){const snapThreshold=60;let minDistance=1/0,closestSnap=null;for(const snap of snapLines){const distance=Math.abs(ev.clientX-rect.left-snap.linePosition);distance<minDistance&&(minDistance=distance,closestSnap=snap)}closestSnap&&minDistance<snapThreshold&&(activeSnapLine=closestSnap)}this.setState({terminalWidth:tw,activeSnapLine:activeSnapLine})},onMouseUp=()=>{if(this._resizing=!1,this._dragTarget=null,this.state.activeSnapLine){const newWidth=this.state.activeSnapLine.terminalPx;localStorage.setItem("cc-viewer-terminal-width",newWidth.toString()),this.setState({terminalWidth:newWidth,isDragging:!1,activeSnapLine:null,snapLines:[],needsInitialSnap:!1})}else localStorage.setItem("cc-viewer-terminal-width",this.state.terminalWidth.toString()),this.setState({isDragging:!1,activeSnapLine:null,snapLines:[],needsInitialSnap:!1});document.removeEventListener("mousemove",onMouseMove),document.removeEventListener("mouseup",onMouseUp),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",onMouseMove),document.addEventListener("mouseup",onMouseUp),document.body.style.cursor="col-resize",document.body.style.userSelect="none"}),__publicField(this,"handleSidebarMouseDown",e=>{e.preventDefault(),this._resizing=!0,this._dragTarget="sidebar";const sidebarSnapWidths=[180,240,300,360],container2=this.innerSplitRef.current;let snapLines=[];if(container2){const containerWidth=container2.getBoundingClientRect().width;snapLines=sidebarSnapWidths.filter(w=>w<.4*containerWidth).map(w=>({cols:w,terminalPx:w,linePosition:w}))}this.setState({isDragging:!0,snapLines:snapLines});const onMouseMove=ev=>{if(!this._resizing)return;const container22=this.innerSplitRef.current;if(!container22)return;const rect=container22.getBoundingClientRect(),containerWidth=rect.width;let sw=ev.clientX-rect.left;sw=Math.max(160,Math.min(.4*containerWidth,sw));let activeSnapLine=null;if(snapLines.length>0){const snapThreshold=60;let minDistance=1/0,closestSnap=null;for(const snap of snapLines){const distance=Math.abs(sw-snap.linePosition);distance<minDistance&&(minDistance=distance,closestSnap=snap)}closestSnap&&minDistance<snapThreshold&&(activeSnapLine=closestSnap)}this.setState({sidebarWidth:sw,activeSnapLine:activeSnapLine})},onMouseUp=()=>{if(this._resizing=!1,this._dragTarget=null,this.state.activeSnapLine){const newWidth=this.state.activeSnapLine.linePosition;localStorage.setItem("cc-viewer-sidebar-width",newWidth.toString()),this.setState({sidebarWidth:newWidth,isDragging:!1,activeSnapLine:null,snapLines:[]})}else localStorage.setItem("cc-viewer-sidebar-width",this.state.sidebarWidth.toString()),this.setState({isDragging:!1,activeSnapLine:null,snapLines:[]});document.removeEventListener("mousemove",onMouseMove),document.removeEventListener("mouseup",onMouseUp),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",onMouseMove),document.addEventListener("mouseup",onMouseUp),document.body.style.cursor="col-resize",document.body.style.userSelect="none"}),__publicField(this,"handleToggleExpandPath",path=>{this.setState(state=>{const newSet=new Set(state.fileExplorerExpandedPaths);return newSet.has(path)?newSet.delete(path):newSet.add(path),{fileExplorerExpandedPaths:newSet}})}),__publicField(this,"handleMdImageClick",e=>{const img=e.target.closest(".chat-md img");img&&img.src&&(e.preventDefault(),this.setState({mdLightboxSrc:img.src}))}),__publicField(this,"handleOpenToolFilePath",async filePath2=>{if(!filePath2)return;if(tryOpenWithSystem(filePath2,"chat-message"))return;let resolved=filePath2;if(filePath2.startsWith("/")){if(!this._projectDirCache)try{const r=await fetch(apiUrl("/api/project-dir"));if(r.ok){const data=await r.json();data&&data.dir&&(this._projectDirCache=data.dir)}}catch{}this._projectDirCache&&filePath2.startsWith(this._projectDirCache+"/")&&(resolved=filePath2.slice(this._projectDirCache.length+1))}const parts=resolved.split("/"),ancestors=[];for(let i=1;i<parts.length;i++)ancestors.push(parts.slice(0,i).join("/"));this.props.onMobileOpenFile?this.props.onMobileOpenFile(resolved,ancestors):(this._setFileExplorerOpen(!0),this.setState(prev=>{const newSet=new Set(prev.fileExplorerExpandedPaths);return ancestors.forEach(p=>newSet.add(p)),{currentFile:resolved,currentGitDiff:null,scrollToLine:null,fileExplorerExpandedPaths:newSet}}))}),__publicField(this,"_handleInsertPathToChat",filePath2=>{const quoted=`"${filePath2}"`;if(this.props.terminalVisible&&this._inputWs&&this._inputWs.readyState===WebSocket.OPEN)return void this._inputWs.send(JSON.stringify({type:"input",data:quoted}));const textarea2=this._inputRef.current;if(!textarea2)return;const cur=textarea2.value;textarea2.value=cur?`${cur} ${quoted}`:quoted,textarea2.style.height="auto",textarea2.style.height=Math.min(textarea2.scrollHeight,120)+"px",this.setState({inputEmpty:!1}),textarea2.focus()}),this.containerRef=React__default.createRef(),this.virtuosoRef=React__default.createRef(),this.splitContainerRef=React__default.createRef(),this.innerSplitRef=React__default.createRef(),this._incToolState=null,this._incToolProcessedCount=0,this._incToolSessionIdx=-1,this._prevSessions=null,this._reqScanCache={tsToIndex:{},modelName:null,completedModelName:null,modelNameByReqIdx:[],subAgentEntries:[],processedCount:0,requestCacheTokenMap:new Map},this._sessionItemCache=[],this._itemCacheToggleSig=null;const savedWidth=localStorage.getItem("cc-viewer-terminal-width"),initialTerminalWidth=savedWidth?parseFloat(savedWidth):null;this.state={visibleCount:0,loading:!1,allItems:[],lastResponseItems:null,highlightTs:null,highlightFading:!1,highlightVisibleIdx:-1,sidebarWidth:parseInt(localStorage.getItem("cc-viewer-sidebar-width"),10)||240,terminalWidth:initialTerminalWidth||624,needsInitialSnap:null===initialTerminalWidth,inputEmpty:!0,pendingInput:null,stickyBottom:!0,ptyPrompt:null,ptyPromptHistory:[],inputSuggestion:null,fileExplorerOpen:isMobile?!!isPad&&"true"===localStorage.getItem("ccv_fileExplorerOpen"):"false"!==localStorage.getItem("ccv_fileExplorerOpen"),currentFile:null,currentGitDiff:null,scrollToLine:null,fileExplorerExpandedPaths:new Set,gitChangesOpen:!1,hasGit:!0,snapLines:[],activeSnapLine:null,isDragging:!1,fileVersion:0,editorSessionId:null,editorFilePath:null,fileExplorerRefresh:0,gitChangesRefresh:0,roleFilterOpen:!1,roleFilterSelected:new Set,teamModalSession:null,mdLightboxSrc:null,streamingFading:!1,presetItems:[],mobilePresetModalVisible:!1,localAskAnswers:{},pendingPermission:null,permissionQueue:[],pendingPlanApproval:null,pendingAsk:null,askQueue:[],pendingPtyPlan:null,pendingImages:[],agentTeamEnabled:!1,ultraplanModalOpen:!1,ultraplanVariant:"codeExpert",ultraplanPrompt:"",ultraplanFiles:[],customUltraplanExperts:[],customUltraplanEditOpen:!1,customUltraplanEditing:null,planFileContents:{}},this._processedToolIds=new Set,this._projectDirCache=null,this._fileRefreshTimer=null,this._gitRefreshTimer=null,this._queueTimer=null,this._prevItemsLen=0,this._scrollTargetIdx=null,this._scrollTargetRef=React__default.createRef(),this._scrollFadeTimer=null,this._resizing=!1,this._dragTarget=null,this._unsubWsHandler=null,this._unsubWsState=null,this._inputRef=React__default.createRef(),this._ptyBuffer="",this._ptyDataSeq=0,this._ptyDebounceTimer=null,this._currentPtyPrompt=null,this._askHookActive=!1,this._askHookQuestions=null,this._pendingHookAnswers=null,this._askHookWaitRetries=0,this._hookWaitTimer=null,this._mobileExtraItems=0,this._mobileSliceOffset=0,this._totalItemCount=0,this._currentLastPendingPlanId=null,this._resolvedPlanIds=new Set,this._lastObservedLpid=null,this._planFileFetches=new Set,this._streamSpinnerUrl=props.isStreaming?Math.random()<.5?"/assets/orbiting-BCD4Vuij.svg":shimmerUrl:null,this._unmounted=!1,this._stickyController=new StickyBottomController({getSticky:()=>this.state.stickyBottom,setSticky:v=>{this._unmounted||this.state.stickyBottom!==v&&this.setState({stickyBottom:v})},getMode:()=>useVirtuoso?"virtuoso":"desktop"})}get _inputWs(){const ctx=this.context;return ctx&&"function"==typeof ctx.send?{get readyState(){return ctx.isOpen&&ctx.isOpen()?WebSocket.OPEN:WebSocket.CLOSED},send:s=>{let obj;try{obj=JSON.parse(s)}catch{return!1}return ctx.send(obj)}}:null}_setFileExplorerOpen(open){localStorage.setItem("ccv_fileExplorerOpen",String(open)),this.setState({fileExplorerOpen:open})}_checkToolFileChanges(){var _a,_b;const sessions=this.props.mainAgentSessions;if(!sessions||0===sessions.length)return;this._processedToolIds.size>5e3&&this._processedToolIds.clear();let needFileRefresh=!1,needGitRefresh=!1,needContentRefresh=!1;for(const session of sessions){const sources=[];if((null==(_b=null==(_a=session.response)?void 0:_a.body)?void 0:_b.content)&&sources.push(session.response.body.content),Array.isArray(session.messages))for(const msg of session.messages)"assistant"===msg.role&&Array.isArray(msg.content)&&sources.push(msg.content);for(const blocks of sources)for(const block of blocks){if("tool_use"!==block.type||!block.id)continue;if(this._processedToolIds.has(block.id))continue;this._processedToolIds.add(block.id);const toolName2=block.name;let input=block.input;if("string"==typeof input)try{input=JSON.parse(input.replace(/^\[object Object\]/,""))}catch{input={}}if("Write"===toolName2?(needFileRefresh=!0,needGitRefresh=!0):"Edit"===toolName2||"NotebookEdit"===toolName2?needGitRefresh=!0:"Bash"===toolName2&&input&&input.command&&isMutatingCommand(input.command)&&(needFileRefresh=!0,needGitRefresh=!0),("Write"===toolName2||"Edit"===toolName2||"NotebookEdit"===toolName2)&&this.state.currentFile){const fp=input&&input.file_path;if(fp){let rel=fp;rel.startsWith("/")&&this._projectDirCache&&rel.startsWith(this._projectDirCache+"/")&&(rel=rel.slice(this._projectDirCache.length+1)),(rel===this.state.currentFile||rel.startsWith("/")&&rel.endsWith("/"+this.state.currentFile))&&(needContentRefresh=!0)}}}}needFileRefresh&&this.state.fileExplorerOpen&&(clearTimeout(this._fileRefreshTimer),this._fileRefreshTimer=setTimeout(()=>{this.setState(prev=>({fileExplorerRefresh:prev.fileExplorerRefresh+1}))},500)),needGitRefresh&&this.state.gitChangesOpen&&(clearTimeout(this._gitRefreshTimer),this._gitRefreshTimer=setTimeout(()=>{this.setState(prev=>({gitChangesRefresh:prev.gitChangesRefresh+1}))},500)),needContentRefresh&&(clearTimeout(this._contentRefreshTimer),this._contentRefreshTimer=setTimeout(()=>{this.setState(prev=>({fileVersion:prev.fileVersion+1}))},500))}componentDidMount(){var _a,_b;this.startRender(),this.context&&this.context.addMessageHandler&&(this._unsubWsHandler=this.context.addMessageHandler(this._onTerminalWsMessage)),this.context&&this.context.addStateListener&&(this._unsubWsState=this.context.addStateListener(this._onTerminalWsState)),fetch(apiUrl("/api/git-repos")).then(r=>r.ok?r.json():Promise.reject()).then(data=>{var _a2;(null==(_a2=data.repos)?void 0:_a2.length)||this.setState({hasGit:!1,gitChangesOpen:!1})}).catch(()=>{fetch(apiUrl("/api/git-status")).then(r=>{r.ok||this.setState({hasGit:!1,gitChangesOpen:!1})}).catch(()=>this.setState({hasGit:!1,gitChangesOpen:!1}))}),"1"===(null==(_b=null==(_a=this.props.claudeSettings)?void 0:_a.env)?void 0:_b.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS)&&this.setState({agentTeamEnabled:!0}),!useVirtuoso&&this.containerRef.current&&this._stickyController.bind(this.containerRef.current),this.state.needsInitialSnap&&this.props.cliMode&&this.props.terminalVisible&&this._snapToInitialPosition(),this._loadPresets()}shouldComponentUpdate(nextProps,nextState){return nextProps.requests!==this.props.requests||nextProps.mainAgentSessions!==this.props.mainAgentSessions||nextProps.streamingLatest!==this.props.streamingLatest||nextProps.collapseToolResults!==this.props.collapseToolResults||nextProps.expandThinking!==this.props.expandThinking||nextProps.showFullToolContent!==this.props.showFullToolContent||nextProps.scrollToTimestamp!==this.props.scrollToTimestamp||nextProps.cliMode!==this.props.cliMode||nextProps.terminalVisible!==this.props.terminalVisible||nextProps.userProfile!==this.props.userProfile||nextProps.pendingUploadPaths!==this.props.pendingUploadPaths||nextProps.isStreaming!==this.props.isStreaming||nextProps.hasMoreHistory!==this.props.hasMoreHistory||nextProps.loadingMore!==this.props.loadingMore||nextProps.loadingSessionId!==this.props.loadingSessionId||nextProps.lang!==this.props.lang||nextProps.showThinkingSummaries!==this.props.showThinkingSummaries||nextProps.fileLoading!==this.props.fileLoading||nextProps.claudeSettings!==this.props.claudeSettings||nextProps.preferences!==this.props.preferences||nextState!==this.state}componentDidUpdate(prevProps,prevState){var _a,_b,_c,_d,_e,_f,_g,_h;if(prevProps.isStreaming!==this.props.isStreaming&&(this._streamSpinnerUrl=this.props.isStreaming?Math.random()<.5?"/assets/orbiting-BCD4Vuij.svg":shimmerUrl:null),prevProps.claudeSettings!==this.props.claudeSettings){const enabled="1"===(null==(_b=null==(_a=this.props.claudeSettings)?void 0:_a.env)?void 0:_b.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS);enabled!==this.state.agentTeamEnabled&&this.setState({agentTeamEnabled:enabled}),this._loadPresets()}if(prevProps.preferences!==this.props.preferences&&this._loadPresets(),prevProps.messages!==this.props.messages){const messages=this.props.messages||[],cache=this.state.planFileContents||{};for(const msg of messages)if(msg&&"assistant"===msg.role&&Array.isArray(msg.content))for(const blk of msg.content){if(!blk||"tool_use"!==blk.type||"ExitPlanMode"!==blk.name)continue;const inp=blk.input||{};if("string"==typeof inp.plan&&inp.plan.trim())continue;const fp=inp.planFilePath;"string"==typeof fp&&fp&&(void 0===cache[fp]&&(this._planFileFetches.has(fp)||(this._planFileFetches.add(fp),fetch(apiUrl(`/api/plan-file?path=${encodeURIComponent(fp)}`)).then(r=>r.ok?r.json():null).then(j=>{this._unmounted||j&&j.ok&&"string"==typeof j.content&&this.setState(s=>({planFileContents:{...s.planFileContents||{},[fp]:j.content}}))}).catch(()=>{}))))}}{const lpid=this._currentLastPendingPlanId||null,curPtyPlan=this.state.pendingPtyPlan,skipped=lpid&&this._resolvedPlanIds.has(lpid);this.props.cliMode&&lpid&&!skipped?curPtyPlan&&curPtyPlan.id===lpid||this.setState({pendingPtyPlan:{id:lpid,prompt:null}}):curPtyPlan&&this.setState({pendingPtyPlan:null}),this._lastObservedLpid!==lpid&&(this._lastObservedLpid&&this._resolvedPlanIds.delete(this._lastObservedLpid),this._lastObservedLpid=lpid)}if(prevState.pendingPermission!==this.state.pendingPermission&&this.props.onPendingPermission&&(this.state.pendingPermission?this.props.onPendingPermission({permission:this.state.pendingPermission,modelName:null==(_c=this._reqScanCache)?void 0:_c.modelName,handlers:{allow:this.handlePermissionAllow,allowSession:this.props.sdkMode?this.handlePermissionAllowSession:null,deny:this.handlePermissionDeny}}):this.props.onPendingPermission(null)),prevState.pendingPlanApproval!==this.state.pendingPlanApproval&&this.props.onPendingPlanApproval&&(this.state.pendingPlanApproval?this.props.onPendingPlanApproval({plan:this.state.pendingPlanApproval,handlers:{approve:this.handlePlanApprove,reject:this.handlePlanReject}}):this.props.onPendingPlanApproval(null)),prevState.pendingAsk!==this.state.pendingAsk){this.props.onPendingAsk&&(this.state.pendingAsk?this.props.onPendingAsk({ask:this.state.pendingAsk,handlers:{submit:this.handleAskQuestionSubmit}}):this.props.onPendingAsk(null));try{"undefined"!=typeof window&&(null==(_d=window.tabBridge)?void 0:_d.notifyAskResolved)&&prevState.pendingAsk&&(null==this.state.pendingAsk||this.state.pendingAsk.id!==prevState.pendingAsk.id)&&window.tabBridge.notifyAskResolved({id:prevState.pendingAsk.id,tabId:this.props.ownTabId??null})}catch{}}if(prevState.pendingPtyPlan!==this.state.pendingPtyPlan){this.props.onPendingPtyPlan&&(this.state.pendingPtyPlan?this.props.onPendingPtyPlan({ptyPlan:this.state.pendingPtyPlan,handlers:{approve:this.handlePromptOptionClick,feedbackSubmit:this.handlePlanFeedbackSubmit}}):this.props.onPendingPtyPlan(null));try{"undefined"!=typeof window&&window.tabBridge&&(this.state.pendingPtyPlan?null==(_f=(_e=window.tabBridge).notifyPtyPlanPending)||_f.call(_e,{id:this.state.pendingPtyPlan.id,payload:{projectName:this.props.projectName||""},tabId:this.props.ownTabId??null}):prevState.pendingPtyPlan&&(null==(_h=(_g=window.tabBridge).notifyPtyPlanResolved)||_h.call(_g,{id:prevState.pendingPtyPlan.id,tabId:this.props.ownTabId??null})))}catch{}}if(useVirtuoso&&prevState.lastResponseItems!==this.state.lastResponseItems&&this.state.stickyBottom&&this._stickyController.startSmoothFollow(this._virtuosoScrollerEl),prevProps.streamingLatest!==this.props.streamingLatest&&this.state.stickyBottom){const el=useVirtuoso?this._virtuosoScrollerEl:this.containerRef.current;el&&this._stickyController.startSmoothFollow(el)}if(prevProps.isStreaming&&!this.props.isStreaming&&(this.setState({streamingFading:!0}),clearTimeout(this._streamingFadeTimer),this._streamingFadeTimer=setTimeout(()=>{this.setState({streamingFading:!1})},500)),!prevProps.isStreaming&&this.props.isStreaming&&this.state.streamingFading&&(clearTimeout(this._streamingFadeTimer),this.setState({streamingFading:!1})),this.props.pendingUploadPaths&&this.props.pendingUploadPaths.length>0&&this.props.pendingUploadPaths!==prevProps.pendingUploadPaths){for(const p of this.props.pendingUploadPaths){const raw=p.replace(/^"|"$/g,"");this._addPendingImage(raw,"drop")}this.props.onUploadPathsConsumed&&this.props.onUploadPathsConsumed()}if(prevProps.mainAgentSessions!==this.props.mainAgentSessions){if(this.props.mainAgentSessions!==this._prevSessions){const prev=this._prevSessions||[],next=this.props.mainAgentSessions||[];(prev.length!==next.length||prev.some((s,i)=>s!==next[i]))&&(this._incToolState=null,this._incToolProcessedCount=0,this._incToolSessionIdx=-1,this._reqScanCache={tsToIndex:{},modelName:null,completedModelName:null,modelNameByReqIdx:[],subAgentEntries:[],processedCount:0,subAgentProcessedCount:0,requestCacheTokenMap:new Map},this._sessionItemCache=[]),this._prevSessions=this.props.mainAgentSessions}isMobile&&(this._mobileExtraItems=0),this.startRender(),this.state.pendingInput&&this.setState({pendingInput:null}),this._clearPendingImages(),this._updateSuggestion(),this._checkToolFileChanges()}else if(prevProps.requests!==this.props.requests)this._reqScanCache.tsToIndex={},this._reqScanCache.modelName=null,this._reqScanCache.completedModelName=null,this._reqScanCache.modelNameByReqIdx=[],this._reqScanCache.processedCount=0,this._reqScanCache.subAgentEntries=[],this._reqScanCache.subAgentProcessedCount=0,this._reqScanCache.requestCacheTokenMap=new Map,this.startRender();else if(prevProps.collapseToolResults!==this.props.collapseToolResults||prevProps.expandThinking!==this.props.expandThinking){const rawItems=this.buildAllItems(),allItems=this._applyMobileSlice(rawItems);this.setState({allItems:allItems,lastResponseItems:this._lastResponseItems,visibleCount:allItems.length})}if(prevState.localAskAnswers!==this.state.localAskAnswers&&prevProps.mainAgentSessions===this.props.mainAgentSessions&&prevProps.requests===this.props.requests&&this.startRender(),!prevProps.scrollToTimestamp&&this.props.scrollToTimestamp)if(isMobile&&this.props.scrollToTimestamp){const rawItems=this.buildAllItems(),targetIdx=this._scrollTargetIdx;if(null!=targetIdx){const mobileLimit=isIOS?150:240,limit=mobileLimit+this._mobileExtraItems;targetIdx<(rawItems.length>limit?rawItems.length-limit:0)&&(this._mobileExtraItems=rawItems.length-targetIdx-mobileLimit,this._mobileExtraItems<0&&(this._mobileExtraItems=0))}const allItems=this._applyMobileSlice(rawItems);this.setState({allItems:allItems,lastResponseItems:this._lastResponseItems,visibleCount:allItems.length},()=>this.scrollToBottom())}else{const rawItems=this.buildAllItems(),allItems=this._applyMobileSlice(rawItems);this.setState({allItems:allItems,lastResponseItems:this._lastResponseItems,visibleCount:allItems.length},()=>this.scrollToBottom())}isMobile&&this.props.mobileChatVisible&&!prevProps.mobileChatVisible&&requestAnimationFrame(()=>{if(this.virtuosoRef.current)this.virtuosoRef.current.scrollToIndex({index:"LAST"});else{const el=this.containerRef.current;el&&this._stickyController.writeUnderLock(el,el.scrollHeight)}}),useVirtuoso||this._stickyController.bind(this.containerRef.current)}componentWillUnmount(){var _a,_b;this._unmounted=!0,this.props.onPendingPermission&&this.props.onPendingPermission(null),this.props.onPendingPlanApproval&&this.props.onPendingPlanApproval(null),this.props.onPendingAsk&&this.props.onPendingAsk(null),this.props.onPendingPtyPlan&&this.props.onPendingPtyPlan(null);try{if(this.state.pendingPtyPlan&&"undefined"!=typeof window&&(null==(_a=window.tabBridge)?void 0:_a.notifyPtyPlanResolved)&&window.tabBridge.notifyPtyPlanResolved({id:this.state.pendingPtyPlan.id,tabId:this.props.ownTabId??null}),"undefined"!=typeof window&&(null==(_b=window.tabBridge)?void 0:_b.notifyAskResolved)){const tabId=this.props.ownTabId??null;if(this.state.pendingAsk)try{window.tabBridge.notifyAskResolved({id:this.state.pendingAsk.id,tabId:tabId})}catch{}for(const q of this.state.askQueue||[])try{window.tabBridge.notifyAskResolved({id:q.id,tabId:tabId})}catch{}}}catch{}if(this._queueTimer&&clearTimeout(this._queueTimer),this._fadeClearTimer&&clearTimeout(this._fadeClearTimer),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._fileRefreshTimer&&clearTimeout(this._fileRefreshTimer),this._gitRefreshTimer&&clearTimeout(this._gitRefreshTimer),this._contentRefreshTimer&&clearTimeout(this._contentRefreshTimer),this._wsReconnectTimer&&clearTimeout(this._wsReconnectTimer),this._waitForWsTimer&&clearTimeout(this._waitForWsTimer),this._waitForPtyTimer&&clearTimeout(this._waitForPtyTimer),this._planFeedbackTimer&&clearTimeout(this._planFeedbackTimer),this._streamingFadeTimer&&clearTimeout(this._streamingFadeTimer),this._hookWaitTimer&&clearTimeout(this._hookWaitTimer),this._pendingHookAnswers=null,this._unbindScrollFade(),this._stickyController&&this._stickyController.dispose(),this._unsubWsHandler){try{this._unsubWsHandler()}catch{}this._unsubWsHandler=null}if(this._unsubWsState){try{this._unsubWsState()}catch{}this._unsubWsState=null}}startRender(){this._queueTimer&&clearTimeout(this._queueTimer);const rawItems=this.buildAllItems(),lastResponseItems=this._lastResponseItems,allItems=this._applyMobileSlice(rawItems);this._prevItemsLen=allItems.length,this.setState({allItems:allItems,lastResponseItems:lastResponseItems,visibleCount:allItems.length,loading:!1},()=>{if(null!=this._scrollTargetIdx||this.props.scrollToTimestamp)this.scrollToBottom();else if(this.state.stickyBottom){const el=useVirtuoso?this._virtuosoScrollerEl:this.containerRef.current;el&&(this._stickyController.refreshFollowTarget(el),this._stickyController.writeUnderLock(el,el.scrollHeight))}})}queueNext(current,total){current>=total||(this._queueTimer=setTimeout(()=>{this.setState({visibleCount:current+1},()=>{this.scrollToBottom(),this.queueNext(current+1,total)})},100+50*Math.random()))}_isNearBottom(){const el=this.containerRef.current;return!el||el.scrollHeight-el.scrollTop-el.clientHeight<=30}scrollToBottom(){const shouldStick=this.state.stickyBottom;if(useVirtuoso&&this.virtuosoRef.current){if(null!=this._scrollTargetIdx){this.virtuosoRef.current.scrollToIndex({index:this._scrollTargetIdx,align:"center"});const targetTs=this.props.scrollToTimestamp;return this._scrollTargetRef=React__default.createRef(),targetTs&&(this.setState({highlightTs:targetTs,highlightFading:!1}),this._bindScrollFade()),void(this.props.onScrollTsDone&&this.props.onScrollTsDone())}if(shouldStick){const scroller=this._virtuosoScrollerEl;scroller?this._stickyController.writeUnderLock(scroller,scroller.scrollHeight):this.virtuosoRef.current.scrollToIndex({index:"LAST",behavior:"auto"})}}else{if(this._scrollTargetRef.current&&this.props.scrollToTimestamp){const targetEl=this._scrollTargetRef.current,container2=this.containerRef.current;container2&&targetEl.offsetHeight>container2.clientHeight?targetEl.scrollIntoView({block:"start",behavior:"instant"}):targetEl.scrollIntoView({block:"center",behavior:"instant"});const targetTs=this.props.scrollToTimestamp;return this._scrollTargetRef=React__default.createRef(),targetTs&&(this.setState({highlightTs:targetTs,highlightFading:!1}),this._bindScrollFade()),void(this.props.onScrollTsDone&&this.props.onScrollTsDone())}if(shouldStick){const el=this.containerRef.current;el&&this._stickyController.writeUnderLock(el,el.scrollHeight)}}}_getScrollContainer(){return useVirtuoso?this._virtuosoScrollerEl:this.containerRef.current}_bindScrollFade(){this._unbindScrollFade(),this._scrollFadeDelayTimer=setTimeout(()=>{const container2=this._getScrollContainer();container2&&(this._scrollFadeBoundEl=container2,this._onScrollFade=()=>{this.setState({highlightFading:!0}),this._fadeClearTimer=setTimeout(()=>{this.setState({highlightTs:null,highlightFading:!1,highlightVisibleIdx:-1})},2e3),this._unbindScrollFade()},container2.addEventListener("scroll",this._onScrollFade,{passive:!0}))},500)}_unbindScrollFade(){this._scrollFadeDelayTimer&&(clearTimeout(this._scrollFadeDelayTimer),this._scrollFadeDelayTimer=null),this._fadeClearTimer&&(clearTimeout(this._fadeClearTimer),this._fadeClearTimer=null),this._onScrollFade&&this._scrollFadeBoundEl&&(this._scrollFadeBoundEl.removeEventListener("scroll",this._onScrollFade),this._scrollFadeBoundEl=null,this._onScrollFade=null)}_getMergedAskAnswerMap(messages,keyPrefix,localAsk){const cached=getToolResultCache(messages),askMap=(null==cached?void 0:cached.askAnswerMap)||EMPTY_MAP,askDirty=(null==cached?void 0:cached._askDirty)||0;if(this._mergedAskAnswerMapByKey||(this._mergedAskAnswerMapByKey={}),this._prevAskCacheByKey||(this._prevAskCacheByKey={}),this._prevAskDirtyByKey||(this._prevAskDirtyByKey={}),this._prevAskLocalByKey||(this._prevAskLocalByKey={}),this._prevAskCacheByKey[keyPrefix]!==askMap||this._prevAskDirtyByKey[keyPrefix]!==askDirty||this._prevAskLocalByKey[keyPrefix]!==localAsk){const hasLocal=localAsk&&Object.keys(localAsk).length>0;this._mergedAskAnswerMapByKey[keyPrefix]=hasLocal?{...askMap,...localAsk}:{...askMap},this._prevAskCacheByKey[keyPrefix]=askMap,this._prevAskDirtyByKey[keyPrefix]=askDirty,this._prevAskLocalByKey[keyPrefix]=localAsk}return this._mergedAskAnswerMapByKey[keyPrefix]}_getMergedPlanApprovalMap(messages,keyPrefix){const cached=getToolResultCache(messages);if(!cached)return EMPTY_MAP;const planDirty=cached._planDirty||0;return this._mergedPlanApprovalMapByKey||(this._mergedPlanApprovalMapByKey={}),this._prevPlanCacheByKey||(this._prevPlanCacheByKey={}),this._prevPlanDirtyByKey||(this._prevPlanDirtyByKey={}),this._prevPlanCacheByKey[keyPrefix]===cached.planApprovalMap&&this._prevPlanDirtyByKey[keyPrefix]===planDirty||(this._mergedPlanApprovalMapByKey[keyPrefix]={...cached.planApprovalMap},this._prevPlanCacheByKey[keyPrefix]=cached.planApprovalMap,this._prevPlanDirtyByKey[keyPrefix]=planDirty),this._mergedPlanApprovalMapByKey[keyPrefix]}_getIsHistoryLog(){return!this.props.cliMode&&!this.props.sdkMode}renderSessionMessages(messages,keyPrefix,resolveModelInfo,tsToIndex,requestCacheTokenMap,startIdx=0){var _a,_b,_c;const{userProfile:userProfile,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,showThinkingSummaries:showThinkingSummaries,onViewRequest:onViewRequest}=this.props,isHistoryLog=this._getIsHistoryLog();let cached=getToolResultCache(messages);if(cached&&messages.length>this._incToolProcessedCount&&(appendToolResultMap(cached,messages,this._incToolProcessedCount),this._incToolProcessedCount=messages.length),!cached){const si=parseInt(keyPrefix.slice(1),10);this._incToolSessionIdx===si&&messages.length>=this._incToolProcessedCount&&this._incToolProcessedCount>0?appendToolResultMap(this._incToolState,messages,this._incToolProcessedCount):(this._incToolState={toolUseMap:{},toolResultMap:{},readContentMap:{},editSnapshotMap:{},askAnswerMap:{},planApprovalMap:{},latestPlanContent:null,latestPlanFilePath:null,_fileState:{},_editOrder:[]},appendToolResultMap(this._incToolState,messages,0),this._incToolSessionIdx=si),this._incToolProcessedCount=messages.length,cached=this._incToolState,function(messages,state){_toolResultCache.set(messages,state)}(messages,cached)}const{toolUseMap:toolUseMap,toolResultMap:toolResultMap,readContentMap:readContentMap,editSnapshotMap:editSnapshotMap,askAnswerMap:askAnswerMap,latestPlanContent:latestPlanContent}=cached,planApprovalMap=this._getMergedPlanApprovalMap(messages,keyPrefix),activePlanPrompt=this.props.cliMode&&this.state.ptyPromptHistory.slice().reverse().find(p=>isPlanApprovalPrompt(p)&&"active"===p.status)||null,activeDangerousPrompt=this.props.cliMode&&"pty"!==(null==(_a=this.state.pendingPermission)?void 0:_a.source)&&this.state.ptyPromptHistory.slice().reverse().find(p=>isDangerousOperationPrompt(p)&&"active"===p.status)||null;let lastPendingPlanId=null,lastPendingAskId=null;const historyAskIds=new Set,_localAsk=this.state.localAskAnswers||{},mergedAskAnswerMap=this._getMergedAskAnswerMap(messages,keyPrefix,_localAsk);let lastPendingAskOwnerIdx=-1,lastPendingPlanOwnerIdx=-1;for(let _mi=0;_mi<messages.length;_mi++){const msg=messages[_mi];if("assistant"===msg.role&&Array.isArray(msg.content))for(const block of msg.content)"tool_use"===block.type&&"AskUserQuestion"===block.name&&historyAskIds.add(block.id)}let lastAssistantIdx=-1;for(let _mi=messages.length-1;_mi>=0;_mi--){const m=messages[_mi];if(m&&"assistant"===m.role&&Array.isArray(m.content)&&m.content.length>0){lastAssistantIdx=_mi;break}}if(lastAssistantIdx>=0){const lastMsg=messages[lastAssistantIdx];for(const block of lastMsg.content){if("tool_use"===block.type&&"ExitPlanMode"===block.name){const approval=planApprovalMap[block.id];approval&&"pending"!==approval.status||(lastPendingPlanId=block.id,lastPendingPlanOwnerIdx=lastAssistantIdx)}if("tool_use"===block.type&&"AskUserQuestion"===block.name){const answers=mergedAskAnswerMap[block.id];answers&&0!==Object.keys(answers).length||(lastPendingAskId=block.id,lastPendingAskOwnerIdx=lastAssistantIdx)}}}const renderedMessages=[];for(let mi=startIdx;mi<messages.length;mi++){const msg=messages[mi],content2=msg.content,ts=msg._timestamp||null,lookupTs=resolveBubbleProducerTs(msg),reqIdx=lookupTs?tsToIndex[lookupTs]:void 0,cacheTotalTokens=null!=reqIdx?(null==requestCacheTokenMap?void 0:requestCacheTokenMap.get(reqIdx))??0:null,hasViewRequest=null!=reqIdx&&onViewRequest,modelInfo=resolveModelInfo(ts,msg.role);if("user"===msg.role){if(Array.isArray(content2)){const suggestionText=content2.find(b=>"text"===b.type&&/^\[SUGGESTION MODE:/i.test((b.text||"").trim())),toolResults=content2.filter(b=>"tool_result"===b.type);if(suggestionText&&toolResults.length>0);else{const{commands:commands,textBlocks:textBlocks,skillBlocks:skillBlocks,teammateBlocks:teammateBlocks,taskNotificationBlocks:taskNotificationBlocks}=classifyUserContent(content2);for(let ci=0;ci<commands.length;ci++)renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:"user",text:commands[ci],timestamp:ts,userProfile:userProfile,modelInfo:modelInfo,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-cmd-${mi}-${ci}`));for(const sb of skillBlocks){const nameMatch=sb.text.match(/^#\s+(.+)$/m),skillName=nameMatch?nameMatch[1]:"Skill";renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:"skill-loaded",text:sb.text,skillName:skillName,timestamp:ts,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-skill-${mi}`))}for(let ti=0;ti<textBlocks.length;ti++){const isPlan=/Implement the following plan:/i.test(textBlocks[ti].text||"");renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:isPlan?"plan-prompt":"user",text:textBlocks[ti].text,timestamp:ts,userProfile:userProfile,modelInfo:modelInfo,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-user-${mi}-${ti}`))}for(let tmi=0;tmi<teammateBlocks.length;tmi++){const tm=teammateBlocks[tmi];renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:tm.status?"teammate-status":"teammate-message",text:tm.content,label:tm.status&&tm.statusFrom||tm.id,toolName:tm.status||null,timestamp:ts,modelInfo:modelInfo,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-teammate-${mi}-${tmi}`))}for(let tni=0;tni<taskNotificationBlocks.length;tni++){const tn=taskNotificationBlocks[tni];renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:"task-notification",taskNotification:tn,timestamp:ts,modelInfo:modelInfo,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-tasknotif-${mi}-${tni}`))}}}else if("string"==typeof content2)if(/<task-notification>/i.test(content2)){const{taskNotificationBlocks:strTnBlocks}=classifyUserContent([{type:"text",text:content2}]);for(let tni=0;tni<strTnBlocks.length;tni++)renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:"task-notification",taskNotification:strTnBlocks[tni],timestamp:ts,modelInfo:modelInfo,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-tasknotif-str-${mi}-${tni}`))}else if(!isSystemText(content2)){const isPlan=/Implement the following plan:/i.test(content2);renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:isPlan?"plan-prompt":"user",text:content2,timestamp:ts,userProfile:userProfile,modelInfo:modelInfo,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-user-${mi}`))}}else if("assistant"===msg.role){const msgLastAskId=mi===lastPendingAskOwnerIdx?lastPendingAskId:null,msgLastPlanId=mi===lastPendingPlanOwnerIdx?lastPendingPlanId:null;if(Array.isArray(content2)){const filteredContent=content2.filter(block=>"text"!==block.type||!isSystemText(block.text));filteredContent.length>0&&renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:"assistant",content:filteredContent,toolResultMap:toolResultMap,readContentMap:readContentMap,editSnapshotMap:editSnapshotMap,askAnswerMap:mergedAskAnswerMap,planApprovalMap:planApprovalMap,latestPlanContent:latestPlanContent,planFileContents:this.state.planFileContents,timestamp:ts,displayTs:msg._generatedTs,modelInfo:modelInfo,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,showThinkingSummaries:showThinkingSummaries,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:activePlanPrompt,activePtyPlanId:(null==(_b=this.state.pendingPtyPlan)?void 0:_b.id)??null,activeDangerousPrompt:activeDangerousPrompt,lastPendingPlanId:msgLastPlanId,lastPendingAskId:msgLastAskId,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onDangerousApprovalClick:this.handlePromptOptionClick,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,onOpenFile:this.handleOpenToolFilePath,cacheTotalTokens:cacheTotalTokens,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-asst-${mi}`))}else"string"==typeof content2&&(isSystemText(content2)||renderedMessages.push(jsxRuntimeExports.jsx(ChatMessage,{role:"assistant",content:[{type:"text",text:content2}],toolResultMap:toolResultMap,readContentMap:readContentMap,editSnapshotMap:editSnapshotMap,askAnswerMap:mergedAskAnswerMap,planApprovalMap:planApprovalMap,latestPlanContent:latestPlanContent,planFileContents:this.state.planFileContents,timestamp:ts,displayTs:msg._generatedTs,modelInfo:modelInfo,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,showThinkingSummaries:showThinkingSummaries,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:activePlanPrompt,activePtyPlanId:(null==(_c=this.state.pendingPtyPlan)?void 0:_c.id)??null,activeDangerousPrompt:activeDangerousPrompt,lastPendingPlanId:msgLastPlanId,lastPendingAskId:msgLastAskId,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onDangerousApprovalClick:this.handlePromptOptionClick,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,onOpenFile:this.handleOpenToolFilePath,cacheTotalTokens:cacheTotalTokens,requestIndex:hasViewRequest?reqIdx:void 0,onViewRequest:hasViewRequest?onViewRequest:void 0,isHistoryLog:isHistoryLog},`${keyPrefix}-asst-${mi}`)))}}return{items:renderedMessages,lastPendingAskId:lastPendingAskId,lastPendingPlanId:lastPendingPlanId,askOwnerInRange:lastPendingAskOwnerIdx>=startIdx,planOwnerInRange:lastPendingPlanOwnerIdx>=startIdx}}_buildTeammateFallbackItems(){var _a,_b,_c,_d;const{requests:requests,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,onViewRequest:onViewRequest}=this.props,isHistoryLog=this._getIsHistoryLog();if(!requests||0===requests.length)return[];resolveTeammateNames(requests);const teammateMap=new Map;for(const req of requests){if(!isTeammate(req)||!(null==(_b=null==(_a=req.body)?void 0:_a.messages)?void 0:_b.length))continue;const name=req.teammate||"teammate",existing=teammateMap.get(name);(!existing||req.body.messages.length>=existing.messages.length)&&teammateMap.set(name,{messages:req.body.messages,response:req.response,timestamp:req.timestamp})}if(0===teammateMap.size)return[];const nullModelInfoResolver=()=>null,allItems=[];let si=0;for(const[name,session]of teammateMap){allItems.push(jsxRuntimeExports.jsx(Divider,{className:styles$3_sessionDivider,children:jsxRuntimeExports.jsx(Text,{className:styles$3_sessionDividerText,children:name})},`tm-div-${si}`));const{items:msgs}=this.renderSessionMessages(session.messages,`tm${si}`,nullModelInfoResolver,{},this._reqScanCache.requestCacheTokenMap);if(allItems.push(...msgs),si===teammateMap.size-1&&(null==(_d=null==(_c=session.response)?void 0:_c.body)?void 0:_d.content)){const respContent=session.response.body.content;if(Array.isArray(respContent)){const lastItems=respContent.filter(b=>"text"===b.type&&b.text).map((b,bi)=>jsxRuntimeExports.jsx(ChatMessage,{role:"assistant",content:[b],timestamp:session.timestamp,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,onViewRequest:onViewRequest,onOpenFile:this.handleOpenToolFilePath,isHistoryLog:isHistoryLog},`tm-resp-${si}-${bi}`));lastItems.length>0&&(this._lastResponseItems=lastItems)}}si++}return allItems}buildAllItems(){var _a,_b,_c,_d,_e,_f,_g,_h;const{mainAgentSessions:mainAgentSessions,requests:requests,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,onViewRequest:onViewRequest}=this.props,isHistoryLog=this._getIsHistoryLog();if(this._lastResponseItems=null,this._lastResponseAskQuestions=null,!mainAgentSessions||0===mainAgentSessions.length)return this._currentLastPendingPlanId=null,this._buildTeammateFallbackItems();const cache=this._reqScanCache;if(requests){const startIdx=requests.length>=cache.processedCount?cache.processedCount:0;0===startIdx&&(cache.tsToIndex={},cache.modelName=null,cache.completedModelName=null,cache.modelNameByReqIdx=[],cache.requestCacheTokenMap=new Map);let lastModelName=cache.modelName;for(let i=startIdx;i<requests.length;i++){const req=requests[i],ma=isMainAgent(req);ma&&req.timestamp&&(cache.tsToIndex[req.timestamp]=i);const effectiveModel=getEffectiveModel(req);ma&&effectiveModel&&(lastModelName=effectiveModel,cache.modelName=lastModelName,req.response&&(cache.completedModelName=lastModelName)),cache.modelNameByReqIdx[i]=lastModelName;const usage=null==(_b=null==(_a=null==req?void 0:req.response)?void 0:_a.body)?void 0:_b.usage;if(usage){const total=(usage.cache_read_input_tokens||0)+(usage.cache_creation_input_tokens||0);cache.requestCacheTokenMap.set(i,total)}else cache.requestCacheTokenMap.delete(i)}cache.processedCount=requests.length,resolveTeammateNames(requests);let subStart=cache.subAgentProcessedCount||0;if(subStart>0&&subStart<requests.length)for(subStart--;cache.subAgentEntries.length>0&&cache.subAgentEntries[cache.subAgentEntries.length-1].requestIndex>=subStart;)cache.subAgentEntries.pop();for(let i=subStart;i<requests.length;i++){const req=requests[i];if(!req.timestamp)continue;const cls=classifyRequest(req,requests[i+1]);if("SubAgent"===cls.type||"Teammate"===cls.type){const respContent=null==(_d=null==(_c=req.response)?void 0:_c.body)?void 0:_d.content;if(Array.isArray(respContent)&&respContent.length>0){const subToolResultMap=cachedBuildToolResultMap((null==(_e=req.body)?void 0:_e.messages)||[]).toolResultMap,isTeammateEntry="Teammate"===cls.type;cache.subAgentEntries.push({timestamp:req.timestamp,content:respContent,toolResultMap:subToolResultMap,label:isTeammateEntry?formatTeammateLabel(cls.subType,null==(_f=req.body)?void 0:_f.model):formatRequestTag(cls.type,cls.subType),isTeammate:isTeammateEntry,requestIndex:i})}}}cache.subAgentProcessedCount=requests.length}const tsToIndex=cache.tsToIndex,requestCacheTokenMap=cache.requestCacheTokenMap,globalModelInfo=getModelInfo(cache.modelName),resolveModelInfo=(ts,role)=>function(ts,role,tsToIndex,modelNameByReqIdx){if(!ts)return null;const idx=tsToIndex[ts];if(null==idx)return null;const name=modelNameByReqIdx["assistant"===role?Math.max(idx-1,0):idx];return name?getModelInfo(name):null}(ts,role,tsToIndex,cache.modelNameByReqIdx),subAgentEntries=cache.subAgentEntries,allItems=[],tsItemMap={},{showThinkingSummaries:showThinkingSummaries}=this.props,activePromptIds=(this.state.ptyPromptHistory||[]).filter(p=>"active"===p.status).map(p=>p.id).join(","),toggleSig=`${collapseToolResults}|${expandThinking}|${showFullToolContent}|${showThinkingSummaries}|${this.props.cliMode}|${(null==(_g=this.state.ptyPrompt)?void 0:_g.id)||""}|${activePromptIds}|${(null==(_h=this.props.userProfile)?void 0:_h.name)||""}|${this.props.lang||""}|${Object.keys(this.state.localAskAnswers||{}).join(",")}`;toggleSig!==this._itemCacheToggleSig&&(this._sessionItemCache=[],this._itemCacheToggleSig=toggleSig),this._sessionItemCache.length>mainAgentSessions.length&&(this._sessionItemCache.length=mainAgentSessions.length);const _validS=mainAgentSessions.length,_byKeyDicts=[this._mergedPlanApprovalMapByKey,this._prevPlanCacheByKey,this._prevPlanDirtyByKey,this._mergedAskAnswerMapByKey,this._prevAskCacheByKey,this._prevAskDirtyByKey,this._prevAskLocalByKey];for(const dict of _byKeyDicts)if(dict)for(const k of Object.keys(dict)){if(!k.startsWith("s"))continue;const idx=parseInt(k.slice(1),10);Number.isFinite(idx)&&idx>=_validS&&delete dict[k]}(this.props.hasMoreHistory||this.props.loadingMore)&&allItems.push(jsxRuntimeExports.jsx("div",{className:styles$3_loadMoreWrap,children:this.props.loadingMore?jsxRuntimeExports.jsxs("div",{className:`${styles$3_loadMoreBtn} ${styles$3_loadMoreBtnLoading}`,children:[jsxRuntimeExports.jsx("span",{className:styles$3_loadMoreSpinner}),t("ui.loadingMoreHistory")]}):jsxRuntimeExports.jsx("button",{className:styles$3_loadMoreBtn,onClick:()=>this.props.onLoadMoreHistory&&this.props.onLoadMoreHistory(),children:t("ui.loadEarlierConversations")})},"load-more-history"));let subIdx=0,buildLpid=null;mainAgentSessions.forEach((session,si)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h2;if(si>0&&allItems.push(jsxRuntimeExports.jsx(Divider,{className:styles$3_sessionDivider,children:jsxRuntimeExports.jsx(Text,{className:styles$3_sessionDividerText,children:"Session"})},`session-div-${si}`)),session._cold){const isLoading=this.props.loadingSessionId===session.sessionId;return void allItems.push(jsxRuntimeExports.jsx("div",{className:styles$3_loadMoreWrap,children:isLoading?jsxRuntimeExports.jsxs("div",{className:`${styles$3_loadMoreBtn} ${styles$3_loadMoreBtnLoading}`,children:[jsxRuntimeExports.jsx("span",{className:styles$3_loadMoreSpinner}),t("ui.loadingMoreHistory")]}):jsxRuntimeExports.jsx("button",{className:styles$3_loadMoreBtn,onClick:()=>this.props.onLoadSession&&this.props.onLoadSession(session.sessionId),children:t("ui.loadSessionPlaceholder",{count:session.msgCount})})},`cold-session-${si}`))}const sc=this._sessionItemCache[si];let msgs,lastPendingAskId,lastPendingPlanId;const sessionPlanApprovalMap=(getToolResultCache(session.messages)||{}).planApprovalMap||{},mergedPlanApprovalMap=this._getMergedPlanApprovalMap(session.messages,`s${si}`),_localAskForSession=this.state.localAskAnswers||{},mergedAskAnswerMap=this._getMergedAskAnswerMap(session.messages,`s${si}`,_localAskForSession);let lrWillOwnAsk=!1,lrWillOwnPlan=!1,lrHistoryAskIds=null,lrHistoryPlanIds=null;if(si===mainAgentSessions.length-1&&(null==(_b2=null==(_a2=session.response)?void 0:_a2.body)?void 0:_b2.content)){const _resp=session.response.body.content;if(Array.isArray(_resp)){const _hasInteractiveBlock=_resp.some(b=>"tool_use"===b.type&&("AskUserQuestion"===b.name||"ExitPlanMode"===b.name));if(!(_resp.some(b=>"text"===b.type&&"string"==typeof b.text&&b.text.includes("[SUGGESTION MODE:"))&&!_hasInteractiveBlock)&&_hasInteractiveBlock){lrHistoryAskIds=new Set,lrHistoryPlanIds=new Set;for(const m of session.messages)if("assistant"===m.role&&Array.isArray(m.content))for(const b of m.content)"tool_use"===b.type&&"AskUserQuestion"===b.name&&lrHistoryAskIds.add(b.id),"tool_use"===b.type&&"ExitPlanMode"===b.name&&lrHistoryPlanIds.add(b.id);const _localAsk=this.state.localAskAnswers||{};for(const b of _resp)if("tool_use"===b.type){if("AskUserQuestion"===b.name){if(lrHistoryAskIds.has(b.id))continue;const merged=mergedAskAnswerMap[b.id];if(merged&&Object.keys(merged).length>0)continue;const la=_localAsk[b.id];la&&0!==Object.keys(la).length||(lrWillOwnAsk=!0)}if("ExitPlanMode"===b.name){if(!this.props.cliMode)continue;if(lrHistoryPlanIds.has(b.id))continue;const approval=sessionPlanApprovalMap[b.id];approval&&"pending"!==approval.status||(lrWillOwnPlan=!0)}}}}}if(sc&&sc.session===session&&sc.msgsLen===session.messages.length)msgs=refreshPlanApprovalOnCachedItems(sc.items,sc.planApprovalMap,mergedPlanApprovalMap),msgs=refreshAskAnswerOnCachedItems(msgs,sc.askAnswerMap,mergedAskAnswerMap),lastPendingAskId=sc.lastPendingAskId,lastPendingPlanId=sc.lastPendingPlanId;else if(sc&&sc.session===session&&session.messages.length>sc.msgsLen){const result=this.renderSessionMessages(session.messages,`s${si}`,resolveModelInfo,tsToIndex,requestCacheTokenMap,sc.msgsLen);if(msgs=refreshPlanApprovalOnCachedItems(sc.items,sc.planApprovalMap,mergedPlanApprovalMap).slice(),msgs=refreshAskAnswerOnCachedItems(msgs,sc.askAnswerMap,mergedAskAnswerMap),lastPendingAskId=result.lastPendingAskId,lastPendingPlanId=result.lastPendingPlanId,!lastPendingPlanId&&sc.lastPendingPlanId){const prevPlanApproval=sessionPlanApprovalMap[sc.lastPendingPlanId];prevPlanApproval&&"pending"!==prevPlanApproval.status||(lastPendingPlanId=sc.lastPendingPlanId)}if(!lastPendingAskId&&sc.lastPendingAskId){const prevAns=null==mergedAskAnswerMap?void 0:mergedAskAnswerMap[sc.lastPendingAskId];prevAns&&0!==Object.keys(prevAns).length||(lastPendingAskId=sc.lastPendingAskId)}if(sc.lastPendingAskId&&sc.lastPendingAskId!==lastPendingAskId)for(let i=0;i<msgs.length;i++)if(msgs[i].props.lastPendingAskId===sc.lastPendingAskId){msgs[i]=React__default.cloneElement(msgs[i],{lastPendingAskId:null});break}if(sc.lastPendingPlanId&&sc.lastPendingPlanId!==lastPendingPlanId)for(let i=0;i<msgs.length;i++)if(msgs[i].props.lastPendingPlanId===sc.lastPendingPlanId){msgs[i]=React__default.cloneElement(msgs[i],{lastPendingPlanId:null});break}if(result.lastPendingAskId&&result.askOwnerInRange)for(let i=0;i<msgs.length;i++)msgs[i].props.lastPendingAskId===result.lastPendingAskId&&(msgs[i]=React__default.cloneElement(msgs[i],{lastPendingAskId:null}));if(result.lastPendingPlanId&&result.planOwnerInRange)for(let i=0;i<msgs.length;i++)msgs[i].props.lastPendingPlanId===result.lastPendingPlanId&&(msgs[i]=React__default.cloneElement(msgs[i],{lastPendingPlanId:null}));msgs=msgs.concat(result.items)}else{const result=this.renderSessionMessages(session.messages,`s${si}`,resolveModelInfo,tsToIndex,requestCacheTokenMap);msgs=result.items,lastPendingAskId=result.lastPendingAskId,lastPendingPlanId=result.lastPendingPlanId}if(this._sessionItemCache[si]={session:session,msgsLen:session.messages.length,items:msgs,lastPendingAskId:lastPendingAskId,lastPendingPlanId:lastPendingPlanId,planApprovalMap:mergedPlanApprovalMap,askAnswerMap:mergedAskAnswerMap},lrWillOwnAsk&&lastPendingAskId){const _stripAskId=lastPendingAskId;msgs=msgs.map(m=>m.props.lastPendingAskId===_stripAskId?React__default.cloneElement(m,{lastPendingAskId:null}):m),lastPendingAskId=null}if(lrWillOwnPlan&&lastPendingPlanId){const _stripPlanId=lastPendingPlanId;msgs=msgs.map(m=>m.props.lastPendingPlanId===_stripPlanId?React__default.cloneElement(m,{lastPendingPlanId:null}):m),lastPendingPlanId=null}lastPendingPlanId&&(buildLpid=lastPendingPlanId);for(const m of msgs){const msgWallTs=m.props.timestamp,msgLookupTs=m.props.displayTs||m.props.timestamp;for(;subIdx<subAgentEntries.length&&msgWallTs&&subAgentEntries[subIdx].timestamp<=msgWallTs;){const sa=subAgentEntries[subIdx];sa.timestamp&&(tsItemMap[sa.timestamp]=allItems.length);const subCacheTotal=null!=sa.requestIndex?(null==requestCacheTokenMap?void 0:requestCacheTokenMap.get(sa.requestIndex))??0:null;allItems.push(jsxRuntimeExports.jsx(ChatMessage,{role:"sub-agent-chat",content:sa.content,toolResultMap:sa.toolResultMap,label:sa.label,isTeammate:sa.isTeammate,timestamp:sa.timestamp,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,requestIndex:sa.requestIndex,cacheTotalTokens:subCacheTotal,onViewRequest:onViewRequest,onOpenFile:this.handleOpenToolFilePath,isHistoryLog:isHistoryLog},`sub-${sa.requestIndex}-${sa.timestamp}`)),subIdx++}msgLookupTs&&(tsItemMap[msgLookupTs]=allItems.length),allItems.push(m)}for(;subIdx<subAgentEntries.length;){const sa=subAgentEntries[subIdx],nextSessionStart=si<mainAgentSessions.length-1&&(null==(_d2=null==(_c2=mainAgentSessions[si+1].messages)?void 0:_c2[0])?void 0:_d2._timestamp);if(nextSessionStart&&sa.timestamp>nextSessionStart)break;sa.timestamp&&(tsItemMap[sa.timestamp]=allItems.length);const subCacheTotal=null!=sa.requestIndex?(null==requestCacheTokenMap?void 0:requestCacheTokenMap.get(sa.requestIndex))??0:null;allItems.push(jsxRuntimeExports.jsx(ChatMessage,{role:"sub-agent-chat",content:sa.content,toolResultMap:sa.toolResultMap,label:sa.label,isTeammate:sa.isTeammate,timestamp:sa.timestamp,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,requestIndex:sa.requestIndex,cacheTotalTokens:subCacheTotal,onViewRequest:onViewRequest,onOpenFile:this.handleOpenToolFilePath,isHistoryLog:isHistoryLog},`sub-${sa.requestIndex}-${sa.timestamp}`)),subIdx++}if(si===mainAgentSessions.length-1&&(null==(_f2=null==(_e2=session.response)?void 0:_e2.body)?void 0:_f2.content)){const respContent=session.response.body.content;if(Array.isArray(respContent)){const hasInteractiveBlock=respContent.some(b=>"tool_use"===b.type&&("AskUserQuestion"===b.name||"ExitPlanMode"===b.name));if(!(respContent.some(b=>"text"===b.type&&"string"==typeof b.text&&b.text.includes("[SUGGESTION MODE:"))&&!hasInteractiveBlock)){const historyAskIds=new Set;for(const msg of session.messages)if("assistant"===msg.role&&Array.isArray(msg.content))for(const block of msg.content)"tool_use"===block.type&&"AskUserQuestion"===block.name&&historyAskIds.add(block.id);session.entryTimestamp&&(tsItemMap[session.entryTimestamp]=allItems.length);let respLastPendingAskId=null,respLastPendingPlanId=null;const _localAsk=this.state.localAskAnswers||{};for(const block of respContent){if("tool_use"===block.type&&"AskUserQuestion"===block.name){if(historyAskIds.has(block.id))continue;const merged=null==mergedAskAnswerMap?void 0:mergedAskAnswerMap[block.id];if(merged&&Object.keys(merged).length>0)continue;const la=_localAsk[block.id];la&&0!==Object.keys(la).length||(respLastPendingAskId=block.id)}if("tool_use"===block.type&&"ExitPlanMode"===block.name){const approval=sessionPlanApprovalMap[block.id];approval&&"pending"!==approval.status||(respLastPendingPlanId=block.id)}}respLastPendingPlanId&&(buildLpid=respLastPendingPlanId),this._lastResponseAskQuestions=new Set;for(const block of respContent)if("tool_use"===block.type&&"AskUserQuestion"===block.name){const questions=null==(_g2=block.input)?void 0:_g2.questions;if(Array.isArray(questions))for(const q of questions)q.question&&this._lastResponseAskQuestions.add(q.question)}const planApprovalMap=sessionPlanApprovalMap,latestPlanContent=(getToolResultCache(session.messages)||{}).latestPlanContent||null,activePlanPrompt=this.props.cliMode&&this.state.ptyPromptHistory.slice().reverse().find(p=>isPlanApprovalPrompt(p)&&"active"===p.status)||null,activeDangerousPrompt=this.props.cliMode&&!this.state.pendingPermission&&this.state.ptyPromptHistory.slice().reverse().find(p=>isDangerousOperationPrompt(p)&&"active"===p.status)||null,lrContent=respContent.filter(b=>"tool_use"!==b.type||"AskUserQuestion"===b.name&&!historyAskIds.has(b.id)||"ExitPlanMode"===b.name&&!(lrHistoryPlanIds&&lrHistoryPlanIds.has(b.id)));if(!lrContent.some(b=>"text"===b.type?"string"==typeof b.text&&b.text.trim().length>0:"tool_use"===b.type||"thinking"===b.type&&("string"==typeof b.thinking&&b.thinking.trim().length>0)))return;const entryReqIdx=session.entryTimestamp?tsToIndex[session.entryTimestamp]:void 0,entryCacheTotal=null!=entryReqIdx?(null==requestCacheTokenMap?void 0:requestCacheTokenMap.get(entryReqIdx))??0:null;this._lastResponseItems=jsxRuntimeExports.jsxs(React__default.Fragment,{children:[jsxRuntimeExports.jsx(Divider,{className:styles$3_lastResponseDivider,children:jsxRuntimeExports.jsx(Text,{type:"secondary",className:styles$3_lastResponseLabel,children:t("ui.lastResponse")})}),jsxRuntimeExports.jsx(ChatMessage,{role:"assistant",content:lrContent,timestamp:session.entryTimestamp,modelInfo:globalModelInfo,collapseToolResults:collapseToolResults,expandThinking:expandThinking,showFullToolContent:showFullToolContent,toolResultMap:EMPTY_MAP,askAnswerMap:Object.keys(_localAsk).length>0?_localAsk:EMPTY_MAP,planApprovalMap:planApprovalMap,latestPlanContent:latestPlanContent,planFileContents:this.state.planFileContents,lastPendingAskId:respLastPendingAskId,lastPendingPlanId:respLastPendingPlanId,activePlanPrompt:activePlanPrompt,activePtyPlanId:(null==(_h2=this.state.pendingPtyPlan)?void 0:_h2.id)??null,activeDangerousPrompt:activeDangerousPrompt,ptyPrompt:this.state.ptyPrompt,cacheTotalTokens:entryCacheTotal,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onDangerousApprovalClick:this.handlePromptOptionClick,cliMode:this.props.cliMode,onAskQuestionSubmit:this.handleAskQuestionSubmit,onOpenFile:this.handleOpenToolFilePath,isHistoryLog:isHistoryLog},"resp-asst")]},"last-response-group")}}}});const{scrollToTimestamp:scrollToTimestamp}=this.props;return this._scrollTargetIdx=scrollToTimestamp&&null!=tsItemMap[scrollToTimestamp]?tsItemMap[scrollToTimestamp]:null,this._tsItemMap=tsItemMap,this._currentLastPendingPlanId=buildLpid,allItems}_applyMobileSlice(allItems){if(!isMobile)return this._mobileSliceOffset=0,this._totalItemCount=allItems.length,allItems;this._totalItemCount=allItems.length;const limit=(isIOS?150:240)+this._mobileExtraItems;if(allItems.length<=limit)return this._mobileSliceOffset=0,allItems;const offset=allItems.length-limit;if(this._mobileSliceOffset=offset,null!=this._scrollTargetIdx&&(this._scrollTargetIdx-=offset,this._scrollTargetIdx<0&&(this._scrollTargetIdx=null)),this._tsItemMap){const newMap={};for(const[ts,idx]of Object.entries(this._tsItemMap)){const adjusted=idx-offset;adjusted>=0&&(newMap[ts]=adjusted)}this._tsItemMap=newMap}return allItems.slice(offset)}_extractSuggestion(){var _a;const{mainAgentSessions:mainAgentSessions}=this.props;if(!(null==mainAgentSessions?void 0:mainAgentSessions.length))return null;const lastSession=mainAgentSessions[mainAgentSessions.length-1],msgs=null==lastSession?void 0:lastSession.messages;if(!Array.isArray(msgs)||0===msgs.length)return null;const lastUserMsg=msgs[msgs.length-1];if("user"!==(null==lastUserMsg?void 0:lastUserMsg.role))return null;const userContent=lastUserMsg.content;if(!(Array.isArray(userContent)?userContent.some(b=>"text"===b.type&&/^\[SUGGESTION MODE:/i.test((b.text||"").trim())):"string"==typeof userContent&&/^\[SUGGESTION MODE:/im.test(userContent.trim())))return null;const resp=null==lastSession?void 0:lastSession.response;if(!resp)return null;const body2=resp.body;if(!body2)return null;const stop=body2.stop_reason;if("end_turn"!==stop&&"max_tokens"!==stop)return null;const content2=body2.content;if(!Array.isArray(content2))return null;for(let i=content2.length-1;i>=0;i--)if("text"===content2[i].type&&(null==(_a=content2[i].text)?void 0:_a.trim()))return content2[i].text.trim();return null}_updateSuggestion(){const text=this._extractSuggestion();this.setState({inputSuggestion:text||null})}_loadPresets(){var _a,_b;if(!("1"===(null==(_b=null==(_a=this.props.claudeSettings)?void 0:_a.env)?void 0:_b.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS)))return;const data=this.props.preferences;if(!data)return;const dismissed=Array.isArray(data.dismissedBuiltinPresets)?new Set(data.dismissedBuiltinPresets):new Set;let items=[];Array.isArray(data.presetShortcuts)&&(items=data.presetShortcuts.map((item,i)=>"string"==typeof item?{id:Date.now()+i,teamName:"",description:item}:{id:Date.now()+i,teamName:item.teamName||"",description:item.description||"",...item.builtinId?{builtinId:item.builtinId}:{},...item.modified?{modified:!0}:{}}));const existingBuiltinIds=new Set(items.filter(i=>i.builtinId).map(i=>i.builtinId));for(const bp of BUILTIN_PRESETS)dismissed.has(bp.builtinId)||existingBuiltinIds.has(bp.builtinId)||items.unshift({id:Date.now()+Math.random(),builtinId:bp.builtinId,teamName:bp.teamName,description:bp.description});const customExperts=Array.isArray(data.customUltraplanExperts)?data.customUltraplanExperts:[],current=this.state.ultraplanVariant,next={presetItems:items,customUltraplanExperts:customExperts};if("string"==typeof current&¤t.startsWith("custom:")){const id=current.slice(7);customExperts.some(e=>e.id===id)||(next.ultraplanVariant="codeExpert")}this.setState(next)}_stripAnsi(str){return str.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[^[\]](.|$)/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"")}_appendPtyData(raw){const clean=this._stripAnsi(raw);this._ptyBuffer+=clean,this._ptyDataSeq++,this._ptyBuffer.length>4096&&(this._ptyBuffer=this._ptyBuffer.slice(-4096)),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._ptyDebounceTimer=setTimeout(()=>this._detectPrompt(),200)}_detectPrompt(){const buf=this._ptyBuffer.trimEnd();let question=null,options=null;const match1=buf.match(/([^\n]*\?)\s*\n((?:\s*[❯>]?\s*\d+\.\s+[^\n]+\n?){2,})(?:\n[^\d❯>\n][^\n]*|\n)*$/);if(match1){question=match1[1].trim();const optionLines=match1[2].match(/\s*([❯>])?\s*(\d+)\.\s+([^\n]+)/g);optionLines&&(options=optionLines.map(line=>{const m=line.match(/\s*([❯>])?\s*(\d+)\.\s+(.+)/);return{number:parseInt(m[2],10),text:m[3].trim(),selected:!!m[1]}}))}if(!options){const match2=buf.match(/([^\n]+)\n((?:\s+[❯>]?\s+[^\n]+\n?){2,})(?:\n[^\s❯>\n][^\n]*|\n)*$/);if(match2){const candidateQ=match2[1].trim(),lines=match2[2].split("\n").filter(l=>l.trim()),parsed=[];for(const line of lines){const m=line.match(/^\s*([❯>])?\s+(.+)/);m&&m[2].trim()&&parsed.push({number:parsed.length+1,text:m[2].trim(),selected:!!m[1]})}parsed.length>=2&&parsed.some(p=>p.selected)&&(question=candidateQ,options=parsed)}}if(question&&options){if(/^[■\s]*[~\/.:]/.test(question)&&/\//.test(question))return;if(/^[*■✦⏎]/.test(question))return;const prev=this.state.ptyPrompt,prompt={question:question,options:options};if(isDangerousOperationPrompt(prompt)&&!this.state.pendingPermission){const toolInfo=function(buf,question,options){const q=(question||"").toLowerCase(),optTexts=(options||[]).map(o2=>o2.text||"").join(" ").toLowerCase();if(/bash command|run shell command/i.test(buf)){const cmdMatch=buf.match(/(?:Bash command|Run shell command)\s*\n\s*\n((?:\s{4,}.+\n?)+)/i),cmd=cmdMatch?cmdMatch[1].replace(/^\s{4}/gm,"").trim():null;return{toolName:"Bash",input:cmd?{command:cmd}:{description:question}}}const editMatch=q.match(/make this edit to\s+(.+?)\s*\??$/);if(editMatch)return{toolName:"Edit",input:{file_path:editMatch[1]}};const writeMatch=q.match(/write (?:this new file|to)\s+(.+?)\s*\??$/);if(writeMatch)return{toolName:"Write",input:{file_path:writeMatch[1]}};if(/write/i.test(q))return{toolName:"Write",input:{description:question}};const readMatch=q.match(/read\s+(.+?)\s*\??$/)||optTexts.match(/allow reading from\s+(.+?)(?:\s+from this project)?/);return readMatch?{toolName:"Read",input:{file_path:readMatch[1]}}:/fetch|url/i.test(q)?{toolName:"WebFetch",input:{description:question}}:/search/i.test(q)?{toolName:"WebSearch",input:{description:question}}:{toolName:"Tool",input:{description:question}}}(this._ptyBuffer,question,options),id=`pty_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this._currentPtyPrompt=prompt,this.setState(state=>{const history=state.ptyPromptHistory.slice();return history.push({...prompt,status:"pty-routed",selectedNumber:null,timestamp:(new Date).toISOString()}),history.length>200&&history.splice(0,history.length-200),{pendingPermission:{id:id,toolName:toolInfo.toolName,input:toolInfo.input,source:"pty",ptyPrompt:prompt},ptyPromptHistory:history}}),void this.scrollToBottom()}return void(prev&&prev.question===question?(this._currentPtyPrompt=prompt,this.setState({ptyPrompt:prompt})):(this._currentPtyPrompt=prompt,this.setState(state=>{const history=state.ptyPromptHistory.slice();if(state.ptyPrompt){const last=history[history.length-1];last&&"active"===last.status&&(history[history.length-1]={...last,status:"dismissed"})}const ts=(new Date).toISOString(),newEntry={...prompt,status:"active",selectedNumber:null,timestamp:ts};return history.push(newEntry),history.length>200&&history.splice(0,history.length-200),{ptyPrompt:prompt,ptyPromptHistory:history}}),this.scrollToBottom()))}if(this.state.ptyPrompt){if(isPlanApprovalPrompt(this.state.ptyPrompt))return;if(isDangerousOperationPrompt(this.state.ptyPrompt))return;if(this._askSubmitting)return;this._currentPtyPrompt=null,this.setState(state=>{const history=state.ptyPromptHistory.slice(),last=history[history.length-1];return last&&"active"===last.status&&(history[history.length-1]={...last,status:"dismissed"}),{ptyPrompt:null,ptyPromptHistory:history,pendingPtyPlan:null}})}}_clearPtyPrompt(){this._ptyBuffer="",this._currentPtyPrompt=null,this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this.state.ptyPrompt&&this.setState({ptyPrompt:null})}_findPtyOptionNumber(prompt,decision){const options=(null==prompt?void 0:prompt.options)||[];if("allow"===decision){const opt2=options.find(o2=>/^yes$/i.test(o2.text.trim()))||options.find(o2=>/^yes/i.test(o2.text)&&!/allow|session|project/i.test(o2.text));return(null==opt2?void 0:opt2.number)||1}if("allowSession"===decision){const opt2=options.find(o2=>/allow.*(?:project|session|during)/i.test(o2.text));return(null==opt2?void 0:opt2.number)||2}const opt=options.find(o2=>/^no$/i.test(o2.text.trim())||/^no[^a-z]/i.test(o2.text));return(null==opt?void 0:opt.number)||options.length}_planSubmissionSteps(answers){return answers.map((answer,i)=>({...answer,isLast:i===answers.length-1}))}_waitForHookBridge(){if(!this._unmounted){if(this._askHookActive){const answers=this._pendingHookAnswers;return this._pendingHookAnswers=null,void this._submitViaHookBridge(answers)}if(this._askHookWaitRetries=(this._askHookWaitRetries||0)+1,this._askHookWaitRetries>30){const answers=this._pendingHookAnswers;return this._pendingHookAnswers=null,void this._submitViaPty(answers)}this._hookWaitTimer=setTimeout(()=>this._waitForHookBridge(),100)}}_submitViaPty(answers){const ws=this._inputWs;return ws&&ws.readyState===WebSocket.OPEN?(this._askAnswerQueue=this._planSubmissionSteps(answers),this._askSubmitting=!0,this._isMultiQuestionForm=answers.length>1,this._currentPtyPrompt?void this._processNextAskAnswer():(this._askPromptRetries=0,void this._waitForPtyPromptAndSubmit())):(this._askAnswerQueue=this._planSubmissionSteps(answers),this._askSubmitting=!0,this._isMultiQuestionForm=answers.length>1,this._askWsRetries=0,void this._waitForWsAndSubmit())}_waitForWsAndSubmit(){if(this._askWsRetries=(this._askWsRetries||0)+1,this._askWsRetries>30)return this._askSubmitting=!1,void(this._askAnswerQueue=[]);this._inputWs&&this._inputWs.readyState===WebSocket.OPEN?this._currentPtyPrompt?this._processNextAskAnswer():(this._askPromptRetries=0,this._waitForPtyPromptAndSubmit()):this._waitForWsTimer=setTimeout(()=>this._waitForWsAndSubmit(),100)}_waitForPtyPromptAndSubmit(){this._askPromptRetries=(this._askPromptRetries||0)+1,this._askPromptRetries>50||this._currentPtyPrompt?this._processNextAskAnswer():this._waitForPtyTimer=setTimeout(()=>this._waitForPtyPromptAndSubmit(),100)}_processNextAskAnswer(){if(!this._askAnswerQueue||0===this._askAnswerQueue.length)return void(this._askSubmitting=!1);const answer=this._askAnswerQueue.shift();"other"===answer.type&&answer.isMultiSelect?this._submitViaSequentialQueue(answer,{settleMs:500}):"other"===answer.type?this._submitOtherAnswer(answer):"multi"===answer.type?this._submitMultiSelectAnswer(answer):this._submitSingleSelectAnswer(answer)}_submitSingleSelectAnswer(answer){this._submitViaSequentialQueue(answer)}_submitMultiSelectAnswer(answer){this._submitViaSequentialQueue(answer)}_submitOtherAnswer(answer){this._submitViaSequentialQueue(answer)}_abortAskSubmitWithRollback(reason){if(this._askSubmitting=!1,this._askAnswerQueue=[],this._lastClearedPendingAsk){const restored=this._lastClearedPendingAsk;this._lastClearedPendingAsk=null,this.setState({pendingAsk:restored})}const askId=this._lastAskSubmitId;askId&&(this._lastAskSubmitId=null,this.setState(prev=>{const nextLocal={...prev.localAskAnswers||{}};return delete nextLocal[askId],{localAskAnswers:nextLocal}}));try{Modal.warning({title:t("ui.askSubmitRetryHint"),content:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{style:{whiteSpace:"pre-line"},children:t("ui.askSubmitFailedDetail")}),jsxRuntimeExports.jsxs("div",{style:{marginTop:8,fontSize:11,color:"var(--text-muted)"},children:["[reason] ",String(reason||"unknown")]})]})})}catch{try{staticMethods.warning(t("ui.askSubmitRetryHint"))}catch{}}}_submitViaSequentialQueue(answer,opts={}){const ctx=this.context;if(!ctx||!ctx.isOpen||!ctx.isOpen())return void this._abortAskSubmitWithRollback("ws-not-open");const p=this.state.ptyPrompt;if(!!(!(p&&Array.isArray(p.options)&&p.options.length>0)||isPlanApprovalPrompt(p)||isDangerousOperationPrompt(p)))return void this._abortAskSubmitWithRollback("pty-prompt-invalid");const isMultiQuestion=!!this._isMultiQuestionForm,chunks=buildChunksForAnswer(answer,this.state.ptyPrompt,isMultiQuestion),settleMs=opts.settleMs||300,seq=`cv-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(!ctx.send({type:"input-sequential",chunks:chunks,settleMs:settleMs,seq:seq}))return void this._abortAskSubmitWithRollback("ws-send-failed");let unsub=null;unsub=ctx.addMessageHandler(msg=>{if(msg&&"input-sequential-done"===msg.type&&msg.seq===seq){if(unsub){try{unsub()}catch{}unsub=null}this._finishCurrentAskAnswer()}}),setTimeout(()=>{if(unsub){try{unsub()}catch{}unsub=null}this._askSubmitting&&this._finishCurrentAskAnswer()},15e3)}_finishCurrentAskAnswer(){this._currentPtyPrompt=null,this.setState(state=>{const history=state.ptyPromptHistory.slice(),last=history[history.length-1];return last&&"active"===last.status&&(history[history.length-1]={...last,status:"answered"}),{ptyPrompt:null,ptyPromptHistory:history}}),this._askAnswerQueue&&0!==this._askAnswerQueue.length||(this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._lastClearedPendingAsk=null,this._lastAskSubmitId=null),this._askAnswerQueue&&this._askAnswerQueue.length>0?setTimeout(()=>{this._processNextAskAnswer()},500):this._askSubmitting=!1}_submitViaHookBridge(answers,explicitHeadId,explicitQuestions){var _a,_b,_c;const ws=this._inputWs;if(!ws||ws.readyState!==WebSocket.OPEN)return this._askHookActive=!1,this._askHookQuestions=null,void this._submitViaPty(answers);this._askSubmitting=!0;const questions=explicitQuestions||this._askHookQuestions||[],hookAnswers={};for(const answer of answers){const q=questions[answer.questionIndex];if(!q)continue;const questionText=q.question;if("other"===answer.type)hookAnswers[questionText]=answer.text||"";else if("multi"===answer.type){const labels=(answer.selectedIndices||[]).map(i=>{var _a2,_b2;return null==(_b2=null==(_a2=q.options)?void 0:_a2[i])?void 0:_b2.label}).filter(Boolean);hookAnswers[questionText]=labels.join(", ")}else hookAnswers[questionText]=(null==(_b=null==(_a=q.options)?void 0:_a[answer.optionIndex])?void 0:_b.label)||""}const resolvedAskId=(void 0!==explicitHeadId?explicitHeadId:null==(_c=this.state.pendingAsk)?void 0:_c.id)||null,payload={type:"ask-hook-answer",answers:hookAnswers};resolvedAskId&&"__ask__"!==resolvedAskId&&(payload.id=resolvedAskId),ws.send(JSON.stringify(payload)),this._lastClearedPendingAsk=null,this._lastAskSubmitId=null,this._askSubmitting=!1,this._currentPtyPrompt=null,this.setState(state=>{const history=state.ptyPromptHistory.slice(),last=history[history.length-1];return last&&"active"===last.status&&(history[history.length-1]={...last,status:"answered"}),{ptyPrompt:null,ptyPromptHistory:history}}),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)}_snapToInitialPosition(){const terminalPx=468;this.setState({terminalWidth:terminalPx,needsInitialSnap:!1}),localStorage.setItem("cc-viewer-terminal-width",terminalPx.toString())}_renderNavSidebar(showFileExplorerAndGit){var _a;return jsxRuntimeExports.jsxs("div",{className:styles$3_navSidebar,children:[jsxRuntimeExports.jsx("button",{className:this.state.roleFilterOpen?styles$3_navBtnActive:styles$3_navBtn,onClick:()=>this.setState(prev=>prev.roleFilterOpen?{roleFilterOpen:!1,roleFilterSelected:new Set}:{roleFilterOpen:!0}),title:t("ui.roleFilter"),children:jsxRuntimeExports.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"})})}),showFileExplorerAndGit&&jsxRuntimeExports.jsx("button",{className:this.state.fileExplorerOpen?styles$3_navBtnActive:styles$3_navBtn,onClick:()=>{this._setFileExplorerOpen(!this.state.fileExplorerOpen),this.setState({gitChangesOpen:!1})},title:t("ui.fileExplorer"),children:jsxRuntimeExports.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 2h9a2 2 0 0 1 2 2z"})})}),showFileExplorerAndGit&&this.state.hasGit&&jsxRuntimeExports.jsx("button",{className:this.state.gitChangesOpen?styles$3_navBtnActive:styles$3_navBtn,onClick:()=>this.setState(prev=>(this._setFileExplorerOpen(!1),{gitChangesOpen:!prev.gitChangesOpen})),title:t("ui.gitChanges"),children:jsxRuntimeExports.jsx("svg",{width:"24",height:"24",viewBox:"0 0 1024 1024",fill:"currentColor",children:jsxRuntimeExports.jsx("path",{d:"M759.53332137 326.35000897c0-48.26899766-39.4506231-87.33284994-87.87432908-86.6366625-46.95397689 0.69618746-85.08957923 39.14120645-85.39899588 86.09518335-0.23206249 40.68828971 27.53808201 74.87882971 65.13220519 84.47074592 10.82958281 2.78474987 18.41029078 12.37666607 18.64235327 23.51566553 0.38677082 21.11768647-3.40358317 44.40128953-17.24997834 63.81718442-22.20064476 31.17372767-62.42480948 42.46743545-97.93037026 52.44612248-22.43270724 6.26568719-38.75443563 7.89012462-53.14230994 9.28249954-20.42149901 2.01120825-39.76003975 3.94506233-63.89453858 17.79145747-5.10537475 2.93945818-10.13339535 6.18833303-14.85199928 9.74662453-4.09977063 3.09416652-9.90133285 0.15470833-9.90133286-4.95066641V302.60228095c0-9.43720788 5.26008307-18.17822829 13.69168683-22.3553531 28.69839444-14.23316598 48.42370599-43.93716454 48.19164353-78.20505872-0.38677082-48.57841433-41.15241468-87.71962076-89.730829-86.01782918C338.80402918 117.57112321 301.59667683 155.70672553 301.59667683 202.58334827c0 34.03583169 19.64795738 63.50776777 48.1916435 77.66357958 8.43160375 4.17712479 13.69168685 12.76343689 13.69168684 22.12329062v419.02750058c0 9.43720788-5.26008307 18.17822829-13.69168684 22.3553531-28.69839444 14.23316598-48.42370599 43.93716454-48.1916435 78.20505872 0.30941665 48.57841433 41.07506052 87.6422666 89.65347484 86.01782918C437.74000359 906.42887679 474.87000179 868.2159203 474.87000179 821.41665173c0-34.03583169-19.64795738-63.50776777-48.1916435-77.66357958-8.43160375-4.17712479-13.69168685-12.76343689-13.69168684-22.12329062v-14.85199926c0-32.48874844 15.39347842-63.27570528 42.00331048-81.91805854 2.39797906-1.70179159 4.95066642-3.32622901 7.50335379-4.79595812 14.92935344-8.58631209 25.91364457-9.66927037 44.09187287-11.4484161 15.62554091-1.54708326 35.04143581-3.48093734 61.65126786-10.90693699 39.06385228-10.98429114 92.51557887-25.91364457 124.84961898-71.39789238 18.56499911-26.06835292 27.38337367-58.01562219 26.37776956-95.14562041-0.15470833-5.33743724-0.54147915-10.67487447-1.08295828-16.16702004-0.85089578-8.27689543 2.70739569-16.24437421 9.12779121-21.50445729 19.57060322-15.78024923 32.02462345-39.99210223 32.02462345-67.14341343zM351.1033411 202.58334827c0-20.49885317 16.63114503-37.12999821 37.1299982-37.1299982s37.12999821 16.63114503 37.12999821 37.1299982-16.63114503 37.12999821-37.12999821 37.1299982-37.12999821-16.63114503-37.1299982-37.1299982z m74.25999641 618.83330346c0 20.49885317-16.63114503 37.12999821-37.12999821 37.1299982s-37.12999821-16.63114503-37.1299982-37.1299982 16.63114503-37.12999821 37.1299982-37.1299982 37.12999821 16.63114503 37.12999821 37.1299982z m247.53332139-457.93664456c-20.49885317 0-37.12999821-16.63114503-37.1299982-37.1299982s16.63114503-37.12999821 37.1299982-37.12999821 37.12999821 16.63114503 37.1299982 37.12999821-16.63114503 37.12999821-37.1299982 37.1299982z"})})}),jsxRuntimeExports.jsx("div",{className:styles$3_navDivider,"aria-hidden":"true"}),jsxRuntimeExports.jsx(Popover,{content:this.props.getTokenStatsContent||null,trigger:"hover",placement:"rightTop",overlayInnerStyle:{background:"var(--bg-elevated)",border:"1px solid var(--border-hover)",borderRadius:8,padding:"8px 8px",maxHeight:"80vh",overflowY:"auto"},children:jsxRuntimeExports.jsx("button",{className:styles$3_navBtn,title:t("ui.tokenStats"),children:jsxRuntimeExports.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M12 14l4-4"}),jsxRuntimeExports.jsx("path",{d:"M3.34 19a10 10 0 1 1 17.32 0"})]})})}),jsxRuntimeExports.jsx(TeamButton,{requests:this.props.requests,onOpenSession:session=>this.setState({teamModalSession:session}),navBtnClass:styles$3_navBtn}),jsxRuntimeExports.jsx(Popover,{content:this._buildUserPromptNav(),trigger:"hover",placement:"rightTop",overlayStyle:{maxWidth:400},children:jsxRuntimeExports.jsx("button",{className:styles$3_navBtn,title:t("ui.userPromptNav"),children:jsxRuntimeExports.jsx("img",{src:(null==(_a=this.props.userProfile)?void 0:_a.avatar)||defaultAvatarUrl,className:styles$3_navAvatarImg,alt:"User",onError:e=>{e.target.onerror=null,e.target.src=defaultAvatarUrl}})})})]})}_buildUserPromptNav(){const visible=this._currentVisible;if(!visible||0===visible.length)return null;if(this._navCacheVisible===visible&&this._navCacheResult)return this._navCacheResult;const prompts=[],seen=new Set;for(let i=0;i<visible.length;i++){const props=visible[i].props;if(!props||"user"!==props.role)continue;const raw=props.text||"";if(!raw)continue;const text=raw.replace(/\[Image(?:\s*#\d+)?(?::?\s*source)?:\s*[^\]]+\]/gi,"").replace(/"\/tmp\/cc-viewer-uploads\/[^"]+"/g,"").trim();if(!text)continue;const key=text.substring(0,100);if(seen.has(key))continue;seen.add(key);const display=text.length>80?text.substring(0,80)+"...":text;prompts.push({display:display,visibleIdx:i,timestamp:props.timestamp||null})}if(0===prompts.length)return this._navCacheVisible=visible,this._navCacheResult=null,null;const result=jsxRuntimeExports.jsx("div",{className:styles$3_userPromptNavList,children:prompts.map((p,i)=>jsxRuntimeExports.jsx("div",{className:styles$3_userPromptNavItem,onClick:()=>this._scrollToUserPrompt(p.visibleIdx,p.timestamp),children:p.display},p.visibleIdx))});return this._navCacheVisible=visible,this._navCacheResult=result,result}_scrollToUserPrompt(visibleIdx,timestamp){null==visibleIdx||visibleIdx<0||(timestamp?this.setState({highlightTs:timestamp,highlightFading:!1,highlightVisibleIdx:visibleIdx},()=>{this._doScrollToVisibleIdx(visibleIdx),this._bindScrollFade()}):this._doScrollToVisibleIdx(visibleIdx))}_doScrollToVisibleIdx(idx){if(useVirtuoso&&this.virtuosoRef.current)this.virtuosoRef.current.scrollToIndex({index:idx,align:"center",behavior:"smooth"});else{const el=this.containerRef.current;el&&el.children[idx]&&el.children[idx].scrollIntoView({behavior:"smooth",block:"center"})}}render(){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const{mainAgentSessions:mainAgentSessions,cliMode:cliMode,terminalVisible:terminalVisible,onToggleTerminal:onToggleTerminal}=this.props,{allItems:allItems,visibleCount:visibleCount,loading:loading2,terminalWidth:terminalWidth,sidebarWidth:sidebarWidth,lastResponseItems:lastResponseItems}=this.state,streamSpinnerUrl=this._streamSpinnerUrl||shimmerUrl;let snapCurrentLeft=0;if(this.state.isDragging)if("sidebar"===this._dragTarget)snapCurrentLeft=sidebarWidth;else if("terminal"===this._dragTarget){const c=this.innerSplitRef.current;c&&(snapCurrentLeft=c.getBoundingClientRect().width-terminalWidth-5)}const noData=(!mainAgentSessions||0===mainAgentSessions.length)&&(!allItems||0===allItems.length);if(noData&&!cliMode)return this.props.fileLoading?null:jsxRuntimeExports.jsx("div",{className:styles$3_centerEmpty,children:jsxRuntimeExports.jsx(Empty,{description:t("ui.noChat")})});if(loading2&&!cliMode)return jsxRuntimeExports.jsx("div",{className:styles$3_centerEmpty,children:jsxRuntimeExports.jsx(Spin,{size:"large"})});const collectedRolesMap=new Map,userProfile=this.props.userProfile,modelInfo=this._reqScanCache?getModelInfo(this._reqScanCache.modelName):null;for(const item of allItems){if(!item||!item.props)continue;const role=item.props.role;if("user"===role||"plan-prompt"===role)collectedRolesMap.has("user")||collectedRolesMap.set("user",{key:"user",name:(null==userProfile?void 0:userProfile.name)||"User",avatarType:"user",color:"rgba(255,255,255,0.1)",avatarImg:(null==userProfile?void 0:userProfile.avatar)||null});else if("assistant"===role)collectedRolesMap.has("assistant")||collectedRolesMap.set("assistant",{key:"assistant",name:(null==modelInfo?void 0:modelInfo.short)||(null==modelInfo?void 0:modelInfo.name)||"Claude",avatarType:"agent",color:(null==modelInfo?void 0:modelInfo.color)||"rgba(255,255,255,0.1)",avatarSvg:(null==modelInfo?void 0:modelInfo.svg)||null});else if("sub-agent-chat"===role){const label2=item.props.label||"SubAgent",key=`sub:${label2}`;if(!collectedRolesMap.has(key)){const isTeammate2=item.props.isTeammate;let avatarType="sub";if(isTeammate2)avatarType="teammate";else{const match=label2.match(/SubAgent:\s*(\w+)/i),st=match?match[1].toLowerCase():"";"explore"===st||"search"===st?avatarType="sub-search":"plan"===st&&(avatarType="sub-plan")}const tmA=isTeammate2?getTeammateAvatar(label2):null;collectedRolesMap.set(key,{key:key,name:label2.length>12?label2.slice(0,12)+"…":label2,avatarType:avatarType,avatarSvg:tmA?tmA.svg:void 0,color:tmA?tmA.color:"rgba(255,255,255,0.1)"})}}}const collectedRoles=Array.from(collectedRolesMap.values());let filteredItems=allItems;const _selSize=this.state.roleFilterSelected.size;_selSize>0&&_selSize<collectedRoles.length&&(filteredItems=allItems.filter(item=>{if(!item||!item.props)return!0;const role=item.props.role;if("user"===role||"plan-prompt"===role)return this.state.roleFilterSelected.has("user");if("assistant"===role)return this.state.roleFilterSelected.has("assistant");if("sub-agent-chat"===role){const key=`sub:${item.props.label||"SubAgent"}`;return this.state.roleFilterSelected.has(key)}return!1}));const _isFiltering=_selSize>0&&_selSize<collectedRoles.length;let filteredLastResponseItems=lastResponseItems&&_isFiltering&&!this.state.roleFilterSelected.has("assistant")?null:lastResponseItems,streamingLiveItem=null;const _assistantFilteredOut=_isFiltering&&!this.state.roleFilterSelected.has("assistant");if(this.props.streamingLatest&&!_assistantFilteredOut){const sl=this.props.streamingLatest,liveBlocks=(sl.content||[]).filter(b=>"text"===b.type||"thinking"===b.type);if(liveBlocks.some(b=>"text"===b.type?"string"==typeof b.text&&b.text.trim().length>0:"thinking"===b.type&&("string"==typeof b.thinking&&b.thinking.trim().length>0))){const cache=this._reqScanCache,streamingModelInfo=cache?getModelInfo(cache.completedModelName||cache.modelName):null;streamingLiveItem=jsxRuntimeExports.jsx(ChatMessage,{role:"assistant",content:liveBlocks,timestamp:sl.timestamp,modelInfo:streamingModelInfo,collapseToolResults:this.props.collapseToolResults,expandThinking:this.props.expandThinking,showFullToolContent:this.props.showFullToolContent,showTrailingCursor:!0,toolResultMap:EMPTY_MAP,isHistoryLog:this._getIsHistoryLog()},"streaming-live-msg")}}const spinnerNode=this.props.isStreaming||this.state.streamingFading?jsxRuntimeExports.jsx("div",{className:`${styles$3_streamingSpinnerWrap}${!this.props.isStreaming||streamingLiveItem?" "+styles$3_streamingSpinnerHidden:""}`,children:jsxRuntimeExports.jsx("object",{type:"image/svg+xml",data:streamSpinnerUrl,width:"20",height:"20","aria-hidden":"true",tabIndex:-1})}):null,targetIdx=this._scrollTargetIdx,{highlightTs:highlightTs,highlightFading:highlightFading,highlightVisibleIdx:highlightVisibleIdx}=this.state,visible=filteredItems.slice(0,_isFiltering?filteredItems.length:visibleCount);this._currentVisible=visible;const highlightIdx=highlightVisibleIdx>=0&&highlightVisibleIdx<visible.length?highlightVisibleIdx:null!=highlightTs?visible.findIndex(item=>{var _a2,_b2;return((null==(_a2=item.props)?void 0:_a2.displayTs)||(null==(_b2=item.props)?void 0:_b2.timestamp))===highlightTs}):-1,{pendingInput:pendingInput,stickyBottom:stickyBottom,ptyPromptHistory:ptyPromptHistory}=this.state,pendingBubble=cliMode&&pendingInput?jsxRuntimeExports.jsx(ChatMessage,{role:"user",text:pendingInput,timestamp:(new Date).toISOString(),userProfile:this.props.userProfile,isHistoryLog:!1},"pending-input"):null,stickyBtn=stickyBottom?null:jsxRuntimeExports.jsxs("button",{className:styles$3_stickyBottomBtn,onClick:this.handleStickToBottom,children:[this.props.isStreaming&&jsxRuntimeExports.jsx("img",{src:"/assets/loading-pet-12a9GTQC.gif",className:styles$3_loadingPet,alt:""}),jsxRuntimeExports.jsx("span",{children:t("ui.stickyBottom")}),jsxRuntimeExports.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntimeExports.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),loadMoreBtn2=isMobile&&this._mobileSliceOffset>0?jsxRuntimeExports.jsx("div",{className:styles$3_loadMoreWrap,children:jsxRuntimeExports.jsx("button",{className:styles$3_loadMoreBtn,onClick:this.handleLoadMore,children:t("ui.loadMoreHistory",{count:this._mobileSliceOffset})})}):null,roleFilterBar2=this.state.roleFilterOpen&&collectedRoles.length>0?jsxRuntimeExports.jsx(RoleFilterBar,{roles:collectedRoles,selectedRoles:this.state.roleFilterSelected,onToggle:key=>this.setState(prev=>{const next=new Set(prev.roleFilterSelected);return next.has(key)?next.delete(key):next.add(key),{roleFilterSelected:next}})}):null,messageList=noData||loading2?jsxRuntimeExports.jsxs("div",{className:styles$3_messageListWrap,children:[jsxRuntimeExports.jsxs("div",{ref:this.containerRef,className:styles$3_container,children:[!cliMode||loading2?jsxRuntimeExports.jsx("div",{className:styles$3_centerEmpty,children:loading2?jsxRuntimeExports.jsx(Spin,{size:"large"}):jsxRuntimeExports.jsx(Empty,{description:t("ui.noChat")})}):null,pendingBubble]}),stickyBtn]}):jsxRuntimeExports.jsxs("div",{className:styles$3_messageListWrap,onClick:this.handleMdImageClick,children:[roleFilterBar2,this.state.mdLightboxSrc&&jsxRuntimeExports.jsx(ImageLightbox,{src:this.state.mdLightboxSrc,alt:"",onClose:()=>this.setState({mdLightboxSrc:null})}),useVirtuoso?(this._virtuosoHeader=loadMoreBtn2,this._virtuosoFooter=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[spinnerNode,filteredLastResponseItems&&jsxRuntimeExports.jsx("div",{className:streamingLiveItem?styles$3_hideLastResponseDivider:void 0,children:filteredLastResponseItems}),pendingBubble,streamingLiveItem&&(!filteredLastResponseItems&&null!=targetIdx&&targetIdx>=visible.length?jsxRuntimeExports.jsx("div",{ref:this._scrollTargetRef,children:streamingLiveItem},"stream-resp-anchor"):streamingLiveItem)]}),jsxRuntimeExports.jsx(qr,{ref:this.virtuosoRef,className:styles$3_mobileVirtuoso,data:visible,initialTopMostItemIndex:Math.max(0,visible.length-1),followOutput:!!this.state.stickyBottom&&"smooth",atBottomStateChange:atBottom=>this._stickyController.notifyAtBottom(atBottom),atBottomThreshold:60,increaseViewportBy:{top:400,bottom:200},computeItemKey:index=>{var _a2;return(null==(_a2=visible[index])?void 0:_a2.key)||`v-${index}`},itemContent:index=>{const item=visible[index],isScrollTarget=index===targetIdx;let el=item;return index===highlightIdx&&(el=React__default.cloneElement(el,{highlight:highlightFading?"fading":"active"})),isScrollTarget?jsxRuntimeExports.jsx("div",{ref:this._scrollTargetRef,children:el}):el},scrollerRef:ref=>{this._virtuosoScrollerEl=ref,this._stickyController.bind(ref)},context:{header:this._virtuosoHeader,footer:this._virtuosoFooter},components:this._virtuosoComponents||(this._virtuosoComponents={Scroller:VirtuosoScroller,Header:({context:context})=>context.header,Footer:({context:context})=>context.footer})})):jsxRuntimeExports.jsxs("div",{ref:this.containerRef,className:styles$3_container,children:[loadMoreBtn2,visible.map((item,i)=>{const isScrollTarget=i===targetIdx;let el=item;return i===highlightIdx&&(el=React__default.cloneElement(el,{highlight:highlightFading?"fading":"active"})),isScrollTarget?jsxRuntimeExports.jsx("div",{ref:this._scrollTargetRef,children:el},item.key+"-anchor"):el}),spinnerNode,filteredLastResponseItems&&jsxRuntimeExports.jsx("div",{className:streamingLiveItem?styles$3_hideLastResponseDivider:void 0,children:null!=targetIdx&&targetIdx>=visible.length?jsxRuntimeExports.jsx("div",{ref:this._scrollTargetRef,children:filteredLastResponseItems},"last-resp-anchor"):filteredLastResponseItems}),pendingBubble,streamingLiveItem&&(!filteredLastResponseItems&&null!=targetIdx&&targetIdx>=visible.length?jsxRuntimeExports.jsx("div",{ref:this._scrollTargetRef,children:streamingLiveItem},"stream-resp-anchor"):streamingLiveItem)]}),stickyBtn]});return cliMode?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{ref:this.splitContainerRef,className:styles$3_splitContainer,children:[this._renderNavSidebar(!0),jsxRuntimeExports.jsxs("div",{className:styles$3_innerSplitArea,ref:this.innerSplitRef,children:[jsxRuntimeExports.jsx(SnapLineOverlay,{isDragging:this.state.isDragging,activeSnapLine:this.state.activeSnapLine,snapLines:this.state.snapLines,currentLeft:snapCurrentLeft}),this.state.fileExplorerOpen&&jsxRuntimeExports.jsx(FileExplorer,{style:{width:this.state.sidebarWidth},refreshTrigger:this.state.fileExplorerRefresh,onClose:()=>this._setFileExplorerOpen(!1),onFileClick:path=>{tryOpenWithSystem(path,"file-explorer")||this.setState({currentFile:path,currentGitDiff:null,scrollToLine:null})},expandedPaths:this.state.fileExplorerExpandedPaths,onToggleExpand:this.handleToggleExpandPath,currentFile:this.state.currentFile,onAttachToChat:filePath2=>this._addPendingImage(filePath2,"explorer"),onInsertPathToChat:this._handleInsertPathToChat,onFileRenamed:(oldPath,newPath)=>{this.setState(prev=>({currentFile:prev.currentFile===oldPath?newPath:prev.currentFile,fileExplorerRefresh:prev.fileExplorerRefresh+1}))}}),this.state.gitChangesOpen&&jsxRuntimeExports.jsx(GitChanges,{style:{width:this.state.sidebarWidth},refreshTrigger:this.state.gitChangesRefresh,onClose:()=>this.setState({gitChangesOpen:!1}),onFileClick:(repoPath,filePath2,commitHash2)=>{tryOpenWithSystem(repoPath&&"."!==repoPath?`${repoPath}/${filePath2}`:filePath2,"git-changes")||this.setState({currentGitDiff:{repo:repoPath,file:filePath2,commit:commitHash2||null},currentFile:null})},onOpenFile:(repoPath,filePath2)=>{const resolvedPath=repoPath&&"."!==repoPath?`${repoPath}/${filePath2}`:filePath2;if(tryOpenWithSystem(resolvedPath,"git-changes"))return;const parts=resolvedPath.split("/"),ancestors=[];for(let i=1;i<parts.length;i++)ancestors.push(parts.slice(0,i).join("/"));this._setFileExplorerOpen(!0),this.setState(prev=>{const newSet=new Set(prev.fileExplorerExpandedPaths);return ancestors.forEach(p=>newSet.add(p)),{currentGitDiff:null,currentFile:resolvedPath,scrollToLine:null,gitChangesOpen:!1,fileExplorerExpandedPaths:newSet}})}}),(this.state.fileExplorerOpen||this.state.gitChangesOpen)&&jsxRuntimeExports.jsx("div",{className:styles$3_vResizer,onMouseDown:this.handleSidebarMouseDown}),jsxRuntimeExports.jsx("div",{className:styles$3_chatSection,children:jsxRuntimeExports.jsxs("div",{className:styles$3_chatSectionFlex,children:[this.state.currentGitDiff&&jsxRuntimeExports.jsx("div",{className:styles$3_overlayPanel,children:jsxRuntimeExports.jsx(GitDiffView,{filePath:this.state.currentGitDiff.file,repoPath:this.state.currentGitDiff.repo,commitHash:this.state.currentGitDiff.commit||null,onClose:()=>this.setState({currentGitDiff:null}),onOpenFile:(path,line)=>{var _a2;const repo=null==(_a2=this.state.currentGitDiff)?void 0:_a2.repo,resolvedPath=repo&&"."!==repo?`${repo}/${path}`:path;if(tryOpenWithSystem(resolvedPath,"git-diff"))return;const parts=resolvedPath.split("/"),ancestors=[];for(let i=1;i<parts.length;i++)ancestors.push(parts.slice(0,i).join("/"));this._setFileExplorerOpen(!0),this.setState(prev=>{const newSet=new Set(prev.fileExplorerExpandedPaths);return ancestors.forEach(p=>newSet.add(p)),{currentGitDiff:null,currentFile:resolvedPath,scrollToLine:line||1,gitChangesOpen:!1,fileExplorerExpandedPaths:newSet}})}})}),this.state.currentFile&&jsxRuntimeExports.jsx("div",{className:styles$3_overlayPanel,children:isImageFile(this.state.currentFile)?jsxRuntimeExports.jsx(ImageViewer,{filePath:this.state.currentFile,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch(apiUrl("/api/editor-done"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.state.editorSessionId})}).catch(()=>{}),this.setState({currentFile:null,fileVersion:0,editorSessionId:null,editorFilePath:null})}},this.state.fileVersion):jsxRuntimeExports.jsx(FileContentView,{filePath:this.state.currentFile,scrollToLine:this.state.scrollToLine,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch(apiUrl("/api/editor-done"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.state.editorSessionId})}).catch(()=>{}),this.setState({currentFile:null,fileVersion:0,editorSessionId:null,editorFilePath:null})}},this.state.fileVersion)}),messageList,jsxRuntimeExports.jsxs("div",{className:styles$3_inputStack,children:[!this.props.suppressInlineApprovalPanels&&jsxRuntimeExports.jsx(ToolApprovalPanel,{toolName:null==(_a=this.state.pendingPermission)?void 0:_a.toolName,toolInput:null==(_b=this.state.pendingPermission)?void 0:_b.input,requestId:null==(_c=this.state.pendingPermission)?void 0:_c.id,onAllow:this.handlePermissionAllow,onAllowSession:this.props.sdkMode||"pty"===(null==(_d=this.state.pendingPermission)?void 0:_d.source)&&(null==(_g=null==(_f=null==(_e=this.state.pendingPermission)?void 0:_e.ptyPrompt)?void 0:_f.options)?void 0:_g.length)>=3?this.handlePermissionAllowSession:null,onDeny:this.handlePermissionDeny,visible:!!this.state.pendingPermission,autoApproveSeconds:this.props.autoApproveSeconds,onAutoApproveChange:this.props.onAutoApproveChange,modelName:null==(_h=this._reqScanCache)?void 0:_h.modelName,source:null==(_i=this.state.pendingPermission)?void 0:_i.source,queueDepth:this.state.permissionQueue.length}),!this.props.suppressInlineApprovalPanels&&this.state.pendingPlanApproval&&jsxRuntimeExports.jsx(ToolApprovalPanel,{toolName:"ExitPlanMode",toolInput:this.state.pendingPlanApproval.input,requestId:this.state.pendingPlanApproval.id,onAllow:this.handlePlanApprove,onDeny:id=>this.handlePlanReject(id,""),visible:!0}),jsxRuntimeExports.jsx(ChatInputBar,{inputRef:this._inputRef,inputEmpty:this.state.inputEmpty,inputSuggestion:this.state.inputSuggestion,terminalVisible:terminalVisible,onKeyDown:this.handleInputKeyDown,onChange:this.handleInputChange,onSend:this.handleInputSend,onStop:this.handleInputStop,onSuggestionClick:this.handleSuggestionToTerminal,onUploadPath:this.handleUploadPath,presetItems:this.state.presetItems,onPresetSend:this.handlePresetSend,onOpenPresetModal:()=>this.setState({mobilePresetModalVisible:!0}),onOpenUltraPlan:this.state.agentTeamEnabled&&this.props.cliMode?()=>this.setState({ultraplanModalOpen:!0}):null,onClearContext:this.props.cliMode?()=>{Modal.confirm({title:t("ui.chatInput.clearContextConfirm"),okType:"danger",okText:t("ui.chatInput.clearContext"),onOk:()=>{var _a2,_b2;const textarea2=this._inputRef.current;textarea2&&(textarea2.value="/clear",this.setState({inputEmpty:!1,pendingImages:[]},()=>this.handleInputSend()),null==(_b2=(_a2=this.props).onClearContextOptimistic)||_b2.call(_a2))}})}:null,isStreaming:this.props.isStreaming,streamingFading:this.state.streamingFading,pendingImages:this.state.pendingImages,onRemovePendingImage:this._removePendingImage,setContextBarSlot:this.props.setContextBarSlot})]}),jsxRuntimeExports.jsx(UltraPlanModal,{open:this.state.ultraplanModalOpen,variant:this.state.ultraplanVariant,prompt:this.state.ultraplanPrompt,files:this.state.ultraplanFiles,agentTeamEnabled:this.state.agentTeamEnabled,customExperts:this.state.customUltraplanExperts,onClose:()=>this.setState({ultraplanModalOpen:!1}),onVariantChange:v=>this.setState({ultraplanVariant:v}),onPromptChange:t2=>this.setState({ultraplanPrompt:t2}),onSend:this._handleUltraplanSend,onUpload:this._handleUltraplanUpload,onPaste:this._handleUltraplanPaste,onRemoveFile:this._handleUltraplanRemoveFile,onOpenCustomEditor:this._openCustomUltraplanEditor}),jsxRuntimeExports.jsx(CustomUltraplanEditModal,{open:this.state.customUltraplanEditOpen,initial:this.state.customUltraplanEditing,onSave:this._saveCustomUltraplanExpert,onDelete:this._deleteCustomUltraplanExpert,onClose:this._closeCustomUltraplanEditor})]})}),cliMode&&!this.props.sdkMode&&onToggleTerminal&&jsxRuntimeExports.jsx("div",{className:styles$3_terminalToggle,onClick:onToggleTerminal,title:t(terminalVisible?"ui.collapseTerminal":"ui.expandTerminal"),children:jsxRuntimeExports.jsx("svg",{viewBox:"0 0 8 24",width:"8",height:"24",children:terminalVisible?jsxRuntimeExports.jsx("path",{d:"M4 8 L7 12 L4 16",stroke:"currentColor",strokeWidth:"1.5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"}):jsxRuntimeExports.jsx("path",{d:"M4 8 L1 12 L4 16",stroke:"currentColor",strokeWidth:"1.5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})}),terminalVisible&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:styles$3_vResizer,onMouseDown:this.handleSplitMouseDown}),jsxRuntimeExports.jsx("div",{className:styles$3_terminalPanelWrap,style:{width:terminalWidth},children:jsxRuntimeExports.jsx(TerminalPanel,{claudeSettings:this.props.claudeSettings,preferences:this.props.preferences,onUpdatePreferences:this.props.onUpdatePreferences,onUpdateClaudeSettings:this.props.onUpdateClaudeSettings,onEditorOpen:(sessionId,filePath2)=>{this.setState({editorSessionId:sessionId,editorFilePath:filePath2,currentFile:filePath2,currentGitDiff:null,scrollToLine:null,fileVersion:(this.state.fileVersion||0)+1})},onFilePath:path=>{this._addPendingImage(path,"terminal")},pendingImages:this.state.pendingImages,onRemovePendingImage:this._removePendingImage,onClearPendingImages:this._clearPendingImages,modelName:null==(_j=this._reqScanCache)?void 0:_j.modelName,getChatScroller:()=>this._getScrollContainer(),onClearContextOptimistic:this.props.onClearContextOptimistic,setContextBarSlot:this.props.setContextBarSlot})})]})]})]}),jsxRuntimeExports.jsx(TeamModal,{session:this.state.teamModalSession,requests:this.props.requests,mainAgentSessions:this.props.mainAgentSessions,collapseToolResults:this.props.collapseToolResults,expandThinking:this.props.expandThinking,showFullToolContent:this.props.showFullToolContent,userProfile:this.props.userProfile,onViewRequest:this.props.onViewRequest,isHistoryLog:this._getIsHistoryLog(),onClose:()=>this.setState({teamModalSession:null})}),jsxRuntimeExports.jsx(PresetModal,{open:this.state.mobilePresetModalVisible,onClose:()=>this.setState({mobilePresetModalVisible:!1}),items:this.state.presetItems,onItemsChange:items=>this.setState({presetItems:items}),onSavePresets:payload=>{this.props.onUpdatePreferences&&this.props.onUpdatePreferences(payload)}})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:styles$3_splitContainer,children:[this._renderNavSidebar(!1),jsxRuntimeExports.jsx("div",{className:styles$3_navSidebarContent,children:messageList})]}),jsxRuntimeExports.jsx(TeamModal,{session:this.state.teamModalSession,requests:this.props.requests,mainAgentSessions:this.props.mainAgentSessions,collapseToolResults:this.props.collapseToolResults,expandThinking:this.props.expandThinking,showFullToolContent:this.props.showFullToolContent,userProfile:this.props.userProfile,onViewRequest:this.props.onViewRequest,isHistoryLog:this._getIsHistoryLog(),onClose:()=>this.setState({teamModalSession:null})})]})}}__publicField(ChatView,"contextType",TerminalWsContext);const styles$2_backdrop="_backdrop_1mfxv_7",styles$2_modal="_modal_1mfxv_25",styles$2_header="_header_1mfxv_44",styles$2_title="_title_1mfxv_53",styles$2_chip="_chip_1mfxv_59",styles$2_chipAction="_chipAction_1mfxv_70",styles$2_body="_body_1mfxv_83",styles$2_slot="_slot_1mfxv_91",styles$2_slotHidden="_slotHidden_1mfxv_96",styles$2_footer="_footer_1mfxv_100",styles$2_dismissBtn="_dismissBtn_1mfxv_111",styles$2_kindTabs="_kindTabs_1mfxv_127",styles$2_kindTab="_kindTab_1mfxv_127",styles$2_kindTabActive="_kindTabActive_1mfxv_145",KIND_PRIORITY=["ptyPlan","ask"];function _idForKind(kind,payload){var _a,_b,_c,_d;return payload?"ptyPlan"===kind?(null==(_b=null==(_a=payload.ptyPlan)?void 0:_a.ptyPlan)?void 0:_b.id)??null:"ask"===kind?(null==(_d=null==(_c=payload.ask)?void 0:_c.ask)?void 0:_d.id)??null:null:null}function _isDismissed(dismissedSet,kind,id){return!!(id&&dismissedSet instanceof Set)&&dismissedSet.has(`${kind}:${id}`)}const _tr=(key,params,fallback)=>{try{const r=t(key,params);return r&&r!==key?r:fallback}catch{return fallback}};function ApprovalModal({enabled:enabled,soundEnabled:soundEnabled,approvalGlobal:approvalGlobal,dismissedIds:dismissedIds,onDismiss:onDismiss,onJumpTab:onJumpTab,otherTabs:otherTabs,children:children}){const askSlotRef=reactExports.useRef(null),ptyPlanSlotRef=reactExports.useRef(null),[activeKind,setActiveKind]=reactExports.useState(null),[slotsReady,setSlotsReady]=reactExports.useState(!1),lastNotifyKeyRef=reactExports.useRef(""),audioRef=reactExports.useRef(null),visibleKinds=reactExports.useMemo(()=>{if(!enabled||!approvalGlobal)return[];const out=[];for(const k of KIND_PRIORITY){const id=_idForKind(k,approvalGlobal);null==id||_isDismissed(dismissedIds,k,id)||out.push(k)}return out},[enabled,approvalGlobal,dismissedIds]);reactExports.useEffect(()=>{0!==visibleKinds.length?activeKind&&visibleKinds.includes(activeKind)||setActiveKind(visibleKinds[0]):null!==activeKind&&setActiveKind(null)},[visibleKinds,activeKind]),reactExports.useLayoutEffect(()=>{const ready=visibleKinds.length>0&&askSlotRef.current&&ptyPlanSlotRef.current;ready&&!slotsReady&&setSlotsReady(!0),!ready&&slotsReady&&setSlotsReady(!1)});const ctxValue=reactExports.useMemo(()=>({askSlot:slotsReady?askSlotRef.current:null,ptyPlanSlot:slotsReady?ptyPlanSlotRef.current:null,activeAskId:visibleKinds.includes("ask")?_idForKind("ask",approvalGlobal):null,activePtyPlanId:visibleKinds.includes("ptyPlan")?_idForKind("ptyPlan",approvalGlobal):null}),[slotsReady,visibleKinds,approvalGlobal]),handleEsc=reactExports.useCallback(e=>{if("Escape"!==e.key)return;if(!activeKind)return;const id=_idForKind(activeKind,approvalGlobal);null!=id&&onDismiss&&onDismiss(activeKind,id)},[activeKind,approvalGlobal,onDismiss]);reactExports.useEffect(()=>{if(0!==visibleKinds.length)return document.addEventListener("keydown",handleEsc),()=>document.removeEventListener("keydown",handleEsc)},[visibleKinds.length,handleEsc]),reactExports.useEffect(()=>{if(!soundEnabled||0===visibleKinds.length)return;const key=visibleKinds.map(k=>`${k}:${_idForKind(k,approvalGlobal)}`).join("|");if(key!==lastNotifyKeyRef.current){lastNotifyKeyRef.current=key;try{const Ctx=window.AudioContext||window.webkitAudioContext;if(!Ctx)return;audioRef.current||(audioRef.current=new Ctx);const ctx=audioRef.current,now=ctx.currentTime,osc=ctx.createOscillator(),gain=ctx.createGain();osc.type="sine",osc.frequency.setValueAtTime(660,now),osc.frequency.linearRampToValueAtTime(880,now+.18),gain.gain.setValueAtTime(0,now),gain.gain.linearRampToValueAtTime(.18,now+.02),gain.gain.exponentialRampToValueAtTime(1e-4,now+.24),osc.connect(gain).connect(ctx.destination),osc.start(now),osc.stop(now+.26)}catch{}}},[soundEnabled,visibleKinds,approvalGlobal]);const projectName=activeKind?(kind=activeKind,(payload=approvalGlobal)?"ptyPlan"===kind?(null==(_b=null==(_a=payload.ptyPlan)?void 0:_a.ptyPlan)?void 0:_b.projectName)||"":"ask"===kind&&(null==(_d=null==(_c=payload.ask)?void 0:_c.ask)?void 0:_d.projectName)||"":""):"";var kind,payload,_a,_b,_c,_d;const titleKey="ptyPlan"===activeKind?"ui.approval.modal.title.ptyPlan":"ui.approval.modal.title.ask",titleFallback="ptyPlan"===activeKind?"Plan review":"Question",isVisible=visibleKinds.length>0;return jsxRuntimeExports.jsxs(ApprovalPortalContext.Provider,{value:ctxValue,children:[children,isVisible&&jsxRuntimeExports.jsx("div",{className:styles$2_backdrop,onClick:e=>{if(e.target!==e.currentTarget)return;if(!activeKind)return;const id=_idForKind(activeKind,approvalGlobal);null!=id&&onDismiss&&onDismiss(activeKind,id)},role:"dialog","aria-modal":"true",children:jsxRuntimeExports.jsxs("div",{className:styles$2_modal,children:[jsxRuntimeExports.jsxs("div",{className:styles$2_header,children:[jsxRuntimeExports.jsx("span",{className:styles$2_title,children:_tr(titleKey,null,titleFallback)}),projectName&&jsxRuntimeExports.jsx("span",{className:styles$2_chip,children:projectName}),Array.isArray(otherTabs)&&otherTabs.map(ot=>jsxRuntimeExports.jsx("span",{className:`${styles$2_chip} ${styles$2_chipAction}`,onClick:()=>onJumpTab&&onJumpTab(ot.tabId),children:_tr("ui.approval.modal.jumpToSession",{project:ot.projectName||""},`→ ${ot.projectName||"session"}`)},ot.tabId))]}),visibleKinds.length>1&&jsxRuntimeExports.jsx("div",{className:styles$2_kindTabs,children:visibleKinds.map(k=>jsxRuntimeExports.jsx("button",{className:`${styles$2_kindTab} ${k===activeKind?styles$2_kindTabActive:""}`,onClick:()=>setActiveKind(k),children:_tr(`ui.approval.modal.title.${k}`,null,k)},k))}),jsxRuntimeExports.jsxs("div",{className:styles$2_body,children:[jsxRuntimeExports.jsx("div",{ref:ptyPlanSlotRef,className:`${styles$2_slot}${"ptyPlan"!==activeKind?" "+styles$2_slotHidden:""}`}),jsxRuntimeExports.jsx("div",{ref:askSlotRef,className:`${styles$2_slot}${"ask"!==activeKind?" "+styles$2_slotHidden:""}`})]}),jsxRuntimeExports.jsxs("div",{className:styles$2_footer,children:[jsxRuntimeExports.jsx("span",{children:_tr("ui.approval.modal.dismissHint",null,"ESC or click outside to minimise (pending stays)")}),jsxRuntimeExports.jsx("button",{className:styles$2_dismissBtn,onClick:()=>{if(!activeKind)return;const id=_idForKind(activeKind,approvalGlobal);null!=id&&onDismiss&&onDismiss(activeKind,id)},children:_tr("ui.approval.modal.dismiss",null,"Minimise")})]})]})})]})}const styles$1={headerBar:"_headerBar_d1wwj_2",logoWrap:"_logoWrap_d1wwj_10",logoWrapActive:"_logoWrapActive_d1wwj_17",logoImage:"_logoImage_d1wwj_26",logoImageActive:"_logoImageActive_d1wwj_36",compactBtn:"_compactBtn_d1wwj_43",liveTag:"_liveTag_d1wwj_76",headerProjectName:"_headerProjectName_d1wwj_97",liveTagFill:"_liveTagFill_d1wwj_103",liveTagContent:"_liveTagContent_d1wwj_115",liveTagHistory:"_liveTagHistory_d1wwj_122",liveTagText:"_liveTagText_d1wwj_128",countdownStrong:"_countdownStrong_d1wwj_134",qrcodePopover:"_qrcodePopover_d1wwj_139",qrcodeTitle:"_qrcodeTitle_d1wwj_157",qrcodeUrlInput:"_qrcodeUrlInput_d1wwj_164",qrcodeUrlCopy:"_qrcodeUrlCopy_d1wwj_170",settingsGroupBox:"_settingsGroupBox_d1wwj_181",settingsGroupTitle:"_settingsGroupTitle_d1wwj_189",settingsItem:"_settingsItem_d1wwj_198",settingsLabel:"_settingsLabel_d1wwj_205",settingsDivider:"_settingsDivider_d1wwj_209",logDirInput:"_logDirInput_d1wwj_214",tokenStatsEmpty:"_tokenStatsEmpty_d1wwj_224",tokenStatsContainer:"_tokenStatsContainer_d1wwj_231",tokenStatsColumn:"_tokenStatsColumn_d1wwj_237",toolStatsColumn:"_toolStatsColumn_d1wwj_241",modelCard:"_modelCard_d1wwj_246",modelCardSpaced:"_modelCardSpaced_d1wwj_253 _modelCard_d1wwj_246",modelName:"_modelName_d1wwj_259",statsTable:"_statsTable_d1wwj_269",th:"_th_d1wwj_274",td:"_td_d1wwj_284",label:"_label_d1wwj_293",rowBorder:"_rowBorder_d1wwj_303",rebuildTotalRow:"_rebuildTotalRow_d1wwj_315",promptExportBar:"_promptExportBar_d1wwj_324",promptScrollArea:"_promptScrollArea_d1wwj_328",promptEmpty:"_promptEmpty_d1wwj_333",promptTimestamp:"_promptTimestamp_d1wwj_339",textPromptCard:"_textPromptCard_d1wwj_347",preText:"_preText_d1wwj_356",systemCollapse:"_systemCollapse_d1wwj_366",systemLabel:"_systemLabel_d1wwj_373",preSys:"_preSys_d1wwj_378",promptTextarea:"_promptTextarea_d1wwj_388",projectStatsCenter:"_projectStatsCenter_d1wwj_404",projectStatsEmpty:"_projectStatsEmpty_d1wwj_410",projectStatsContent:"_projectStatsContent_d1wwj_417",projectStatsUpdated:"_projectStatsUpdated_d1wwj_423",projectStatsSummary:"_projectStatsSummary_d1wwj_429",projectStatCard:"_projectStatCard_d1wwj_435",projectStatValue:"_projectStatValue_d1wwj_443",projectStatLabel:"_projectStatLabel_d1wwj_451",projectStatsSection:"_projectStatsSection_d1wwj_457",projectStatsSectionTitle:"_projectStatsSectionTitle_d1wwj_463",projectStatsModelCard:"_projectStatsModelCard_d1wwj_471",projectStatsModelHeader:"_projectStatsModelHeader_d1wwj_478",projectStatsModelName:"_projectStatsModelName_d1wwj_487",projectStatsModelCount:"_projectStatsModelCount_d1wwj_493",pluginDirHint:"_pluginDirHint_d1wwj_500",pluginDirPath:"_pluginDirPath_d1wwj_506",pluginList:"_pluginList_d1wwj_519",pluginItem:"_pluginItem_d1wwj_525",pluginInfo:"_pluginInfo_d1wwj_535",pluginName:"_pluginName_d1wwj_543",pluginFile:"_pluginFile_d1wwj_549",pluginHooks:"_pluginHooks_d1wwj_555",pluginHookTag:"_pluginHookTag_d1wwj_562",pluginActions:"_pluginActions_d1wwj_571",pluginEmpty:"_pluginEmpty_d1wwj_579",cachePopover:"_cachePopover_d1wwj_586",cacheScrollArea:"_cacheScrollArea_d1wwj_590",cachePopoverTitle:"_cachePopoverTitle_d1wwj_600",cachePopoverHeader:"_cachePopoverHeader_d1wwj_609",cachePopoverEmpty:"_cachePopoverEmpty_d1wwj_627",cacheSection:"_cacheSection_d1wwj_642",cacheSectionBordered:"_cacheSectionBordered_d1wwj_647",cacheSectionLabel:"_cacheSectionLabel_d1wwj_657",cacheSectionHeader:"_cacheSectionHeader_d1wwj_658",cacheSectionTitle:"_cacheSectionTitle_d1wwj_680",cacheSectionArrow:"_cacheSectionArrow_d1wwj_715",toolChipGrid:"_toolChipGrid_d1wwj_726",toolChipGridVertical:"_toolChipGridVertical_d1wwj_733",cacheToolChip:"_cacheToolChip_d1wwj_741",claudeMdChip:"_claudeMdChip_d1wwj_760",cacheChipBadge:"_cacheChipBadge_d1wwj_787",cacheChipBadgeProject:"_cacheChipBadgeProject_d1wwj_799",cacheChipBadgeGlobal:"_cacheChipBadgeGlobal_d1wwj_804",chipDetailBody:"_chipDetailBody_d1wwj_809",chipDetailEmpty:"_chipDetailEmpty_d1wwj_821",mcpServerGroup:"_mcpServerGroup_d1wwj_826",mcpServerName:"_mcpServerName_d1wwj_830",thLeft:"_thLeft_d1wwj_940",cacheUsageLabel:"_cacheUsageLabel_d1wwj_945",cachePercent:"_cachePercent_d1wwj_953",cacheCalibrationLabel:"_cacheCalibrationLabel_d1wwj_961",calibrationSelect:"_calibrationSelect_d1wwj_969",cachePopoverPlaceholder:"_cachePopoverPlaceholder_d1wwj_975",pluginModalFooter:"_pluginModalFooter_d1wwj_994",pluginModalFooterLeft:"_pluginModalFooterLeft_d1wwj_999",pluginDirLabel:"_pluginDirLabel_d1wwj_1005",pluginEmptyTitle:"_pluginEmptyTitle_d1wwj_1010",pluginEmptyHint:"_pluginEmptyHint_d1wwj_1015",cdnUrlLabel:"_cdnUrlLabel_d1wwj_1021",cdnInput:"_cdnInput_d1wwj_1027",titleIcon:"_titleIcon_d1wwj_1034",qrcodeIcon:"_qrcodeIcon_d1wwj_1043",approvalBell:"_approvalBell_d1wwj_1069",approvalBellBadge:"_approvalBellBadge_d1wwj_1094",currentProcessBtn:"_currentProcessBtn_d1wwj_1112",proxySwapIcon:"_proxySwapIcon_d1wwj_1117",fullWidthSelect:"_fullWidthSelect_d1wwj_1122",proxyProfileTag:"_proxyProfileTag_d1wwj_1127",proxyWarning:"_proxyWarning_d1wwj_1141",proxyList:"_proxyList_d1wwj_1151",proxyItem:"_proxyItem_d1wwj_1157",proxyItemActive:"_proxyItemActive_d1wwj_1169",proxyItemMain:"_proxyItemMain_d1wwj_1174",proxyItemInfo:"_proxyItemInfo_d1wwj_1182",proxyItemNameRow:"_proxyItemNameRow_d1wwj_1188",proxyItemName:"_proxyItemName_d1wwj_1188",proxyItemDetail:"_proxyItemDetail_d1wwj_1200",proxyBuiltinTag:"_proxyBuiltinTag_d1wwj_1209",proxyItemActions:"_proxyItemActions_d1wwj_1219",proxyEditForm:"_proxyEditForm_d1wwj_1225",proxyEditRow:"_proxyEditRow_d1wwj_1233",proxyRequired:"_proxyRequired_d1wwj_1243",proxyEditDivider:"_proxyEditDivider_d1wwj_1248",proxyEditBtns:"_proxyEditBtns_d1wwj_1253",themeToggle:"_themeToggle_d1wwj_1264",themeToggleKnob:"_themeToggleKnob_d1wwj_1292",themeToggleIcon:"_themeToggleIcon_d1wwj_1322",headerRightRow:"_headerRightRow_d1wwj_1327",headerCountdownTag:"_headerCountdownTag_d1wwj_1333",memoryMarkdown:"_memoryMarkdown_d1wwj_1355",memoryStatus:"_memoryStatus_d1wwj_1435",memoryDirHint:"_memoryDirHint_d1wwj_1439"};function parseMemoryLink(hrefRaw){if(!hrefRaw)return{reject:!0};const trimmed=hrefRaw.trim();if(!trimmed)return{reject:!0};if(trimmed.startsWith("#"))return{allow:!0};if(/^[a-z][a-z0-9+.-]*:/i.test(trimmed))return{reject:!0};let candidate;try{candidate=decodeURIComponent(trimmed.split("#")[0].split("?")[0])}catch{return{reject:!0}}return candidate?candidate.startsWith("/")||candidate.startsWith("\\")||candidate.includes("/")||candidate.includes("\\")||".."===candidate||candidate.startsWith(".")?{reject:!0}:/\.md$/i.test(candidate)?{open:candidate}:{reject:!0}:{reject:!0}}const appConfig={calibrationModels:[{label:"auto",value:"auto"},{label:"1M",value:"1m"},{label:"200K",value:"200k"}]},CALIBRATION_MODELS=appConfig.calibrationModels,SUPPORTS_DIRECTORY_UPLOAD="undefined"!=typeof document&&"webkitdirectory"in document.createElement("input");function CachePopoverContent({requests:requests=[],serverCachedContent:serverCachedContent,contextPercent:contextPercent=0,contextTokens:contextTokens=0,fsSkills:fsSkills,memory:memory,claudeMd:claudeMd,calibrationModel:calibrationModel="auto",onCalibrationModelChange:onCalibrationModelChange,onOpenMemoryDetail:onOpenMemoryDetail,onOpenClaudeMd:onOpenClaudeMd,onOpenSkillsModal:onOpenSkillsModal,onRefreshMemory:onRefreshMemory,onSkillImported:onSkillImported,memoryRefreshing:memoryRefreshing=!1}){const skillFileInputRef=reactExports.useRef(null),skillFolderInputRef=reactExports.useRef(null),postSkillImport=async file=>{try{const form=new FormData;form.append("file",file);const resp=await fetch(apiUrl("/api/skills/import"),{method:"POST",body:form}),data=await resp.json().catch(()=>({}));if(!resp.ok){let reason=data.error||resp.statusText;return"INVALID_TYPE"===data.code?reason=t("ui.skills.invalidType"):"MISSING_SKILL_MD"===data.code&&(reason=t("ui.skills.zipMissingSkillMd")),void staticMethods.error(t("ui.skills.uploadFailed",{reason:reason}))}staticMethods.success(t("ui.skills.uploadSuccess")),null==onSkillImported||onSkillImported()}catch(err){staticMethods.error(t("ui.skills.uploadFailed",{reason:(null==err?void 0:err.message)||"network"}))}},[sectionCollapsed,setSectionCollapsed]=reactExports.useState({}),[chipModal,setChipModal]=reactExports.useState(null),lastToolsRef=reactExports.useRef(null),lastParsedTools=reactExports.useRef(null),lastSkillsRef=reactExports.useRef(null),lastChosenForSkills=reactExports.useRef(null),cached=serverCachedContent||extractCachedContent(requests),toolsArr=Array.isArray(null==cached?void 0:cached.tools)?cached.tools:null;let parsed;toolsArr===lastToolsRef.current&&lastParsedTools.current?parsed=lastParsedTools.current:(parsed=function(tools){const builtin=[],mcpByServer=new Map;if(!Array.isArray(tools))return{builtin:builtin,mcpByServer:mcpByServer};for(const raw of tools){if("string"!=typeof raw||!raw)continue;let name="",description="";const nameMatch=raw.match(/<name>([\s\S]*?)<\/name>/);if(nameMatch){name=nameMatch[1].trim();const descMatch=raw.match(/<description>([\s\S]*?)<\/description>/);description=descMatch?descMatch[1].trim():""}else{const colonIdx=raw.indexOf(":");name=colonIdx>=0?raw.slice(0,colonIdx).trim():raw.trim(),description=colonIdx>=0?raw.slice(colonIdx+1).trim():""}if(!name)continue;const mcpMatch=/^mcp__(.+?)__(.+)$/.exec(name);if(mcpMatch){const server=mcpMatch[1],toolName2=mcpMatch[2];mcpByServer.has(server)||mcpByServer.set(server,[]),mcpByServer.get(server).push({name:toolName2,fullName:name,description:description})}else builtin.push({name:name,description:description})}return{builtin:builtin,mcpByServer:mcpByServer}}(toolsArr),lastToolsRef.current=toolsArr,lastParsedTools.current=parsed);const{builtin:builtin,mcpByServer:mcpByServer}=parsed,hasBuiltin=builtin.length>0,hasMcp=mcpByServer.size>0,chosenForSkills=(()=>{if(!Array.isArray(requests)||0===requests.length)return null;if(1===requests.length)return requests[0];for(let i=requests.length-1;i>=0;i--){const r=requests[i];if(r&&"teammate"!==r.type&&"subAgent"!==r.type)return r}return null})();chosenForSkills!==lastChosenForSkills.current&&(lastSkillsRef.current=function(requests){if(!Array.isArray(requests)||0===requests.length)return[];let chosen=null;if(1===requests.length)chosen=requests[0];else for(let i=requests.length-1;i>=0;i--)if(isMainAgent(requests[i])){chosen=requests[i];break}if(!chosen||!chosen.body)return[];const body2=chosen.body;let last=null;if(Array.isArray(body2.system))for(const blk of body2.system)"text"===(null==blk?void 0:blk.type)&&isSkillsReminder(blk.text)&&(last=blk.text);if(Array.isArray(body2.messages))for(const msg of body2.messages){const c=null==msg?void 0:msg.content;if("string"==typeof c)isSkillsReminder(c)&&(last=c);else if(Array.isArray(c))for(const blk of c)"text"===(null==blk?void 0:blk.type)&&isSkillsReminder(blk.text)&&(last=blk.text)}if(!last)return[];const m=/<system-reminder>([\s\S]*?)<\/system-reminder>/i.exec(last);return function(innerText){if("string"!=typeof innerText)return[];const headerIdx=innerText.indexOf("skills are available for use with the Skill tool");if(headerIdx<0)return[];const lineStart=innerText.indexOf("\n",headerIdx);if(lineStart<0)return[];const lines=innerText.slice(lineStart+1).split(/\r?\n/),skills=[];let current=null;const flush=()=>{current&¤t.name&&skills.push(current),current=null};for(const line of lines)if(/^-\s+/.test(line)){flush();const rest=line.replace(/^-\s+/,""),colonSpaceIdx=rest.indexOf(": ");if(colonSpaceIdx>0)current={name:rest.slice(0,colonSpaceIdx).trim(),description:rest.slice(colonSpaceIdx+2).trim()};else{const name=rest.replace(/:\s*$/,"").trim();current={name:name,description:""}}}else if(current&&line.trim())current.description=current.description?current.description+"\n"+line.trim():line.trim();else{if(line.trim())break;flush()}return flush(),skills}(m?m[1]:last)}(requests),lastChosenForSkills.current=chosenForSkills);const historicalSkills=(lastSkillsRef.current||[]).filter(s=>!BUILTIN_SKILL_NAMES.has(s.name)),mergedSkills=function(fsSkills,historicalSkills){if(!Array.isArray(fsSkills))return null;const descMap=new Map((historicalSkills||[]).map(s=>[s.name,s.description])),out=new Map;for(const s of fsSkills){if(!s||!s.enabled||"builtin"===s.source)continue;const name=skillToDisplayName(s);name&&!BUILTIN_SKILL_NAMES.has(name)&&out.set(name,{name:name,description:s.description||descMap.get(name)||""})}return[...out.values()]}(fsSkills,lastSkillsRef.current||[]),skills=null!==mergedSkills?mergedSkills:historicalSkills,hasSkills=skills.length>0,renderChipPopoverContent=description=>description?jsxRuntimeExports.jsx("div",{className:styles$1.chipDetailBody,children:description}):jsxRuntimeExports.jsx("div",{className:`${styles$1.chipDetailBody} ${styles$1.chipDetailEmpty}`,children:t("ui.noDescription")}),renderMcpChip=({name:name,fullName:fullName,description:description})=>isMobile?jsxRuntimeExports.jsx("span",{className:styles$1.cacheToolChip,role:"button",tabIndex:0,onClick:()=>setChipModal({title:fullName,description:description}),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),setChipModal({title:fullName,description:description}))},children:name},fullName):jsxRuntimeExports.jsx(Popover,{title:fullName,content:renderChipPopoverContent(description),overlayStyle:{maxWidth:480},mouseEnterDelay:.2,children:jsxRuntimeExports.jsx("span",{className:styles$1.cacheToolChip,children:name})},fullName),handleMemoryLinkClick=e=>{const a=e.target.closest("a");if(!a)return;const r=parseMemoryLink(a.getAttribute("href")||"");r.allow||(e.preventDefault(),r.open&&(null==onOpenMemoryDetail||onOpenMemoryDetail(r.open)))},builtinBody=jsxRuntimeExports.jsx("div",{className:styles$1.toolChipGrid,children:builtin.map(({name:name,description:description})=>{const title2=[name,description].filter(Boolean).join("\n\n"),chip2=jsxRuntimeExports.jsx("span",{className:styles$1.cacheToolChip,title:title2,children:name});return jsxRuntimeExports.jsx(ConceptHelp,{doc:`Tool-${name}`,children:chip2},name)})}),mcpBody=jsxRuntimeExports.jsx("div",{className:styles$1.toolChipGridVertical,children:Array.from(mcpByServer.entries()).map(([server,tools])=>jsxRuntimeExports.jsxs("div",{className:styles$1.mcpServerGroup,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.mcpServerName,children:[server," (",tools.length,")"]}),jsxRuntimeExports.jsx("div",{className:styles$1.toolChipGrid,children:tools.map(renderMcpChip)})]},server))}),skillsBody=jsxRuntimeExports.jsx("div",{className:styles$1.toolChipGrid,children:skills.map(({name:name,description:description})=>isMobile?jsxRuntimeExports.jsx("span",{className:styles$1.cacheToolChip,role:"button",tabIndex:0,onClick:()=>setChipModal({title:name,description:description}),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),setChipModal({title:name,description:description}))},children:name},name):jsxRuntimeExports.jsx(Popover,{title:name,content:renderChipPopoverContent(description),overlayStyle:{maxWidth:480},mouseEnterDelay:.2,children:jsxRuntimeExports.jsx("span",{className:styles$1.cacheToolChip,children:name})},name))}),skillsAction=onOpenSkillsModal||onSkillImported?jsxRuntimeExports.jsxs(Space,{size:6,children:[onSkillImported&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[isMobile?jsxRuntimeExports.jsx(Button,{size:"small",icon:jsxRuntimeExports.jsx(RefIcon$e,{}),onClick:()=>{var _a;return null==(_a=skillFileInputRef.current)?void 0:_a.click()},children:t("ui.skills.add")}):jsxRuntimeExports.jsx(Dropdown,{trigger:["click"],menu:{items:[...SUPPORTS_DIRECTORY_UPLOAD?[{key:"folder",icon:jsxRuntimeExports.jsx(RefIcon$d,{}),label:t("ui.skills.addFolder"),onClick:()=>{var _a;return null==(_a=skillFolderInputRef.current)?void 0:_a.click()}}]:[],{key:"zip",icon:jsxRuntimeExports.jsx(RefIcon$4,{}),label:t("ui.skills.addZip"),onClick:()=>{var _a;return null==(_a=skillFileInputRef.current)?void 0:_a.click()}},{key:"md",icon:jsxRuntimeExports.jsx(RefIcon$5,{}),label:t("ui.skills.addMd"),onClick:()=>{var _a;return null==(_a=skillFileInputRef.current)?void 0:_a.click()}}]},children:jsxRuntimeExports.jsx(Button,{size:"small",icon:jsxRuntimeExports.jsx(RefIcon$e,{}),children:t("ui.skills.add")})}),jsxRuntimeExports.jsx("input",{type:"file",ref:skillFileInputRef,style:{display:"none"},accept:".zip,.md",onChange:async e=>{var _a;const file=null==(_a=e.target.files)?void 0:_a[0];if(e.target.value="",!file)return;const lower=file.name.toLowerCase();lower.endsWith(".zip")||lower.endsWith(".md")?await postSkillImport(file):staticMethods.error(t("ui.skills.invalidType"))}}),SUPPORTS_DIRECTORY_UPLOAD&&!isMobile&&jsxRuntimeExports.jsx("input",{type:"file",ref:skillFolderInputRef,style:{display:"none"},webkitdirectory:"",directory:"",onChange:async e=>{const fileList2=e.target.files;if(e.target.value="",!fileList2||0===fileList2.length)return;const files=Array.from(fileList2);if(files.some(f=>{const parts=(f.webkitRelativePath||"").split("/");return 2===parts.length&&"skill.md"===parts[1].toLowerCase()}))try{const zip=new(0,(await __vitePreload(async()=>{const{default:__vite_default__}=await import("./jszip.min-DKP-m-LG.js").then(n=>n.j);return{default:__vite_default__}},__vite__mapDeps([9,2]))).default);for(const f of files){const rel=f.webkitRelativePath||f.name;rel&&!rel.includes("..")&&zip.file(rel,f)}const blob=await zip.generateAsync({type:"blob"}),rootName=(files[0].webkitRelativePath||"").split("/")[0]||"skill",zipFile=new File([blob],`${rootName}.zip`,{type:"application/zip"});await postSkillImport(zipFile)}catch(err){staticMethods.error(t("ui.skills.uploadFailed",{reason:(null==err?void 0:err.message)||"pack failed"}))}else staticMethods.error(t("ui.skills.folderMissingSkillMd"))}})]}),onOpenSkillsModal&&jsxRuntimeExports.jsx(Button,{type:"primary",size:"small",icon:jsxRuntimeExports.jsx(RefIcon$1,{}),onClick:()=>onOpenSkillsModal(),children:t("ui.skillManage")})]}):null,memoryCount=(()=>{if(!memory||!memory.exists||!memory.content)return null;const matches=memory.content.match(/\]\(\s*([^)\s]+\.md)(?:\s+"[^"]*")?\s*\)/gi);if(!matches)return 0;const set=new Set;for(const m of matches){const inner2=m.match(/\(\s*([^)\s]+\.md)/i);inner2&&set.add(inner2[1].toLowerCase())}return set.size})(),claudeMdVisible=null===claudeMd||!1===claudeMd||Array.isArray(claudeMd)&&claudeMd.length>0,claudeMdBody=null===claudeMd?jsxRuntimeExports.jsx("div",{className:`${styles$1.cachePopoverEmpty} ${styles$1.memoryStatus}`,children:t("ui.memoryLoading")}):!1===claudeMd?jsxRuntimeExports.jsx("div",{className:`${styles$1.cachePopoverEmpty} ${styles$1.memoryStatus}`,children:t("ui.memoryLoadError")}):Array.isArray(claudeMd)&&0!==claudeMd.length?jsxRuntimeExports.jsx("div",{className:styles$1.toolChipGrid,children:claudeMd.map(entry=>{const scopeLabel="global"===entry.scope?t("ui.claudeMdScopeGlobal"):t("ui.claudeMdScopeProject"),badgeClass="global"===entry.scope?`${styles$1.cacheChipBadge} ${styles$1.cacheChipBadgeGlobal}`:`${styles$1.cacheChipBadge} ${styles$1.cacheChipBadgeProject}`;return jsxRuntimeExports.jsxs("button",{type:"button",className:styles$1.claudeMdChip,title:entry.tail,onClick:()=>null==onOpenClaudeMd?void 0:onOpenClaudeMd(entry.id,entry.tail,entry.scope),children:[jsxRuntimeExports.jsx("span",{className:badgeClass,children:scopeLabel}),jsxRuntimeExports.jsx("span",{children:entry.tail})]},entry.id)})}):null,memoryBody=null===memory?jsxRuntimeExports.jsx("div",{className:`${styles$1.cachePopoverEmpty} ${styles$1.memoryStatus}`,children:t("ui.memoryLoading")}):!1===memory?jsxRuntimeExports.jsx("div",{className:`${styles$1.cachePopoverEmpty} ${styles$1.memoryStatus}`,children:t("ui.memoryLoadError")}):memory.exists?memory.content&&memory.content.trim()?jsxRuntimeExports.jsx("div",{className:styles$1.memoryMarkdown,onClick:handleMemoryLinkClick,dangerouslySetInnerHTML:{__html:renderMarkdown(memory.content)}}):jsxRuntimeExports.jsxs("div",{className:`${styles$1.cachePopoverEmpty} ${styles$1.memoryStatus}`,children:[jsxRuntimeExports.jsx("div",{children:t("ui.memoryEmpty")}),jsxRuntimeExports.jsx("div",{className:styles$1.memoryDirHint,title:memory.indexPath,children:memory.indexPath})]}):jsxRuntimeExports.jsxs("div",{className:`${styles$1.cachePopoverEmpty} ${styles$1.memoryStatus}`,children:[jsxRuntimeExports.jsx("div",{children:t("ui.memoryNotFound")}),jsxRuntimeExports.jsx("div",{className:styles$1.memoryDirHint,title:memory.dir,children:memory.dir})]}),ctxColor=contextPercent>=80?"var(--color-error-light)":contextPercent>=60?"var(--color-warning-light)":"var(--color-success)",cacheUsageText=contextTokens>0?`${(contextTokens/1e3).toFixed(1)}K (${contextPercent}%)`:`${contextPercent}%`;return jsxRuntimeExports.jsxs("div",{className:styles$1.cachePopover,children:[jsxRuntimeExports.jsx("div",{className:styles$1.cachePopoverHeader,children:jsxRuntimeExports.jsxs("div",{className:styles$1.cachePopoverTitle,children:[jsxRuntimeExports.jsx("span",{className:styles$1.cacheUsageLabel,children:t("ui.contextUsage")}),jsxRuntimeExports.jsx("span",{className:styles$1.cachePercent,style:{color:ctxColor},children:cacheUsageText}),jsxRuntimeExports.jsx("span",{className:styles$1.cacheCalibrationLabel,children:t("ui.calibrationModelLabel")}),jsxRuntimeExports.jsx(Select,{size:"small",value:calibrationModel,onChange:onCalibrationModelChange,options:CALIBRATION_MODELS,className:styles$1.calibrationSelect,popupMatchSelectWidth:!1})]})}),jsxRuntimeExports.jsxs("div",{className:styles$1.cacheScrollArea,children:[hasBuiltin&&((sectionKey,titleKey,count,defaultCollapsed,body2,rightAction=null)=>{const state=sectionCollapsed[sectionKey],collapsed=void 0!==state?!!state:defaultCollapsed;return jsxRuntimeExports.jsxs("div",{className:styles$1.cacheSection,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.cacheSectionHeader,children:[jsxRuntimeExports.jsxs("button",{type:"button",className:styles$1.cacheSectionTitle,onClick:()=>setSectionCollapsed(prev=>({...prev,[sectionKey]:!collapsed})),"aria-expanded":!collapsed,children:[jsxRuntimeExports.jsx("span",{className:styles$1.cacheSectionArrow,children:collapsed?"▶":"▼"}),t(titleKey)," (",count,")"]}),rightAction]}),!collapsed&&body2]})})("tools_builtin","ui.builtinTools",builtin.length,!0,builtinBody),hasMcp&&jsxRuntimeExports.jsxs("div",{className:`${styles$1.cacheSection} ${styles$1.cacheSectionBordered}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.cacheSectionLabel,children:[t("ui.mcpTools")," (",Array.from(mcpByServer.values()).reduce((n,arr)=>n+arr.length,0),")"]}),mcpBody]}),hasSkills&&jsxRuntimeExports.jsxs("div",{className:`${styles$1.cacheSection} ${styles$1.cacheSectionBordered}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.cacheSectionHeader,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.cacheSectionLabel,children:[t("ui.loadedSkills")," (",skills.length,")"]}),skills.length>20?jsxRuntimeExports.jsx(Alert,{type:"error",showIcon:!0,banner:!0,message:t("ui.skillsWarnPollution"),style:{marginRight:"auto",padding:"2px 8px",fontSize:11}}):skills.length>10?jsxRuntimeExports.jsx(Alert,{type:"warning",showIcon:!0,banner:!0,message:t("ui.skillsWarnOveruse"),style:{marginRight:"auto",padding:"2px 8px",fontSize:11}}):null,skillsAction]}),skillsBody]}),claudeMdVisible&&jsxRuntimeExports.jsxs("div",{className:`${styles$1.cacheSection} ${styles$1.cacheSectionBordered}`,children:[jsxRuntimeExports.jsx("div",{className:styles$1.cacheSectionHeader,children:jsxRuntimeExports.jsxs("div",{className:styles$1.cacheSectionLabel,children:[t("ui.claudeMdSection"),Array.isArray(claudeMd)?` (${claudeMd.length})`:""]})}),claudeMdBody]}),jsxRuntimeExports.jsxs("div",{className:`${styles$1.cacheSection} ${styles$1.cacheSectionBordered}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.cacheSectionHeader,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.cacheSectionLabel,children:[t("ui.persistentMemory"),null!==memoryCount?` (${memoryCount})`:""]}),onRefreshMemory&&(()=>{const isLoading=null===memory,isMissingFile=memory&&!1===memory.exists,refreshDisabled=isLoading||isMissingFile,tooltipTitle=isLoading?t("ui.memoryLoading"):isMissingFile?t("ui.memoryNotFound"):"",btn=jsxRuntimeExports.jsx(Button,{size:"small",icon:jsxRuntimeExports.jsx(RefIcon$k,{}),loading:memoryRefreshing,disabled:refreshDisabled,onClick:onRefreshMemory,children:t("ui.memoryRefresh")});return tooltipTitle?jsxRuntimeExports.jsx(Tooltip,{title:tooltipTitle,children:jsxRuntimeExports.jsx("span",{children:btn})}):btn})()]}),memoryBody]})]}),chipModal&&jsxRuntimeExports.jsx(Modal,{open:!0,title:chipModal.title,onCancel:()=>setChipModal(null),footer:null,width:"92vw",zIndex:1101,destroyOnClose:!0,children:chipModal.description?jsxRuntimeExports.jsx("div",{className:styles$1.chipDetailBody,children:chipModal.description}):jsxRuntimeExports.jsx("div",{className:`${styles$1.chipDetailBody} ${styles$1.chipDetailEmpty}`,children:t("ui.noDescription")})})]})}function MemoryDetailModal({detail:detail2,onClose:onClose,onOpenMemoryDetail:onOpenMemoryDetail,linkMode:linkMode="memory"}){if(!detail2)return null;const{name:name,content:content2,error:error2,loading:loading2}=detail2,handleLinkClick=e=>{const a=e.target.closest("a");if(!a)return;const hrefRaw=a.getAttribute("href")||"";if("passthrough"===linkMode){if(e.preventDefault(),/^https?:\/\//i.test(hrefRaw)&&"undefined"!=typeof window)try{window.open(hrefRaw,"_blank","noopener,noreferrer")}catch{}return}const r=parseMemoryLink(hrefRaw);r.allow||(e.preventDefault(),r.open&&(null==onOpenMemoryDetail||onOpenMemoryDetail(r.open)))};let body2;return body2=loading2?jsxRuntimeExports.jsx("div",{className:styles$1.cachePopoverEmpty,children:t("ui.memoryLoading")}):error2?jsxRuntimeExports.jsxs("div",{className:styles$1.cachePopoverEmpty,children:[t("ui.memoryLoadError"),": ",error2]}):content2&&content2.trim()?jsxRuntimeExports.jsx("div",{className:styles$1.memoryMarkdown,onClick:handleLinkClick,dangerouslySetInnerHTML:{__html:renderMarkdown(content2)}}):jsxRuntimeExports.jsx("div",{className:styles$1.cachePopoverEmpty,children:t("ui.memoryEmpty")}),jsxRuntimeExports.jsx(Modal,{open:!0,title:name,onCancel:onClose,footer:null,width:720,zIndex:1100,destroyOnClose:!0,children:body2})}const styles={skillsList:"_skillsList_1po3v_4",skillCard:"_skillCard_1po3v_10",skillCardHeader:"_skillCardHeader_1po3v_17",skillCardName:"_skillCardName_1po3v_25",skillCardActions:"_skillCardActions_1po3v_33",skillCardDesc:"_skillCardDesc_1po3v_38",skillsEmpty:"_skillsEmpty_1po3v_46",skillsReadonlySection:"_skillsReadonlySection_1po3v_54",skillsReadonlyLabel:"_skillsReadonlyLabel_1po3v_60",skillCardDisabled:"_skillCardDisabled_1po3v_67",skillCardTitleRow:"_skillCardTitleRow_1po3v_74",skillSourceBadge:"_skillSourceBadge_1po3v_81",skillSource_user:"_skillSource_user_1po3v_91",skillSource_project:"_skillSource_project_1po3v_92",skillSource_plugin:"_skillSource_plugin_1po3v_93",skillSource_builtin:"_skillSource_builtin_1po3v_94"};function reasonToLabel(reason){if(!reason||"stale"===reason||"local_log"===reason)return"";const mHttp=/^http:(\d+)$/.exec(reason);return mHttp?t("ui.skillsLoadError.http",{status:mHttp[1]}):"network"===reason?t("ui.skillsLoadError.network"):reason}function SkillsManagerModal({open:open=!1,onClose:onClose,loading:loading2=!1,error:error2=null,skills:skills=[],toggling:toggling,onToggle:onToggle}){const togglingSet=toggling instanceof Set?toggling:new Set,userOrProject=skills.filter(s=>"user"===s.source||"project"===s.source),pluginSkills=skills.filter(s=>"plugin"===s.source),builtinSkills=skills.filter(s=>"builtin"===s.source);return jsxRuntimeExports.jsx(Modal,{title:t("ui.skillManagerTitle"),open:open,onCancel:onClose,footer:null,width:isMobile?"calc(100vw - 8px)":"min(1200px, calc(100vw - 80px))",zIndex:1100,styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:"16px 20px",...isMobile?{zoom:.6}:{}}},children:loading2?jsxRuntimeExports.jsx("div",{className:styles.skillsEmpty,children:jsxRuntimeExports.jsx(Spin,{})}):error2?jsxRuntimeExports.jsx("div",{className:styles.skillsEmpty,children:t("ui.skillsLoadFailed",{reason:reasonToLabel(error2)||error2})}):0===skills.length?jsxRuntimeExports.jsx("div",{className:styles.skillsEmpty,children:t("ui.noSkillsLoaded")}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[userOrProject.length>0&&jsxRuntimeExports.jsx("div",{className:styles.skillsList,children:userOrProject.map((s,i)=>{const key=`${s.source}-${s.name}`,isToggling=togglingSet.has(key);return jsxRuntimeExports.jsxs("div",{className:`${styles.skillCard} ${s.enabled?"":styles.skillCardDisabled}`,children:[jsxRuntimeExports.jsxs("div",{className:styles.skillCardHeader,children:[jsxRuntimeExports.jsxs("div",{className:styles.skillCardTitleRow,children:[jsxRuntimeExports.jsx("span",{className:`${styles.skillSourceBadge} ${styles["skillSource_"+s.source]}`,children:t("ui.skillSource."+s.source)}),jsxRuntimeExports.jsx("div",{className:styles.skillCardName,children:s.name})]}),jsxRuntimeExports.jsx("div",{className:styles.skillCardActions,children:jsxRuntimeExports.jsx(Switch,{size:"small",checked:s.enabled,loading:isToggling,onChange:()=>onToggle&&onToggle(s)})})]}),s.description&&jsxRuntimeExports.jsx("div",{className:styles.skillCardDesc,children:s.description})]},`${key}-${i}`)})}),pluginSkills.length>0&&jsxRuntimeExports.jsxs("div",{className:styles.skillsReadonlySection,children:[jsxRuntimeExports.jsx("div",{className:styles.skillsReadonlyLabel,children:t("ui.skillsPluginLabel")}),jsxRuntimeExports.jsx("div",{className:styles$1.toolChipGrid,children:pluginSkills.map((s,i)=>{const pluginDisplay=(s.pluginName||"").split("@")[0];return jsxRuntimeExports.jsx(Tooltip,{title:t("ui.skillCannotDisablePlugin",{plugin:pluginDisplay}),children:jsxRuntimeExports.jsx("span",{className:styles$1.cacheToolChip,children:s.name})},`plugin-${s.name}-${i}`)})})]}),builtinSkills.length>0&&jsxRuntimeExports.jsxs("div",{className:styles.skillsReadonlySection,children:[jsxRuntimeExports.jsx("div",{className:styles.skillsReadonlyLabel,children:t("ui.skillsBuiltinLabel")}),jsxRuntimeExports.jsx("div",{className:styles$1.toolChipGrid,children:builtinSkills.map(s=>jsxRuntimeExports.jsx(Tooltip,{title:t("ui.skillCannotDisableBuiltin"),children:jsxRuntimeExports.jsx("span",{className:styles$1.cacheToolChip,children:s.name})},s.name))})]})]})})}function PluginModal({open:open,onClose:onClose}){const context=reactExports.useContext(SettingsContext),fileInputRef=reactExports.useRef(null),[pluginsList,setPluginsList]=reactExports.useState([]),[pluginsDir,setPluginsDir]=reactExports.useState(""),[deleteConfirmVisible,setDeleteConfirmVisible]=reactExports.useState(!1),[deleteTarget,setDeleteTarget]=reactExports.useState(null),[cdnModalVisible,setCdnModalVisible]=reactExports.useState(!1),[cdnUrl,setCdnUrl]=reactExports.useState(""),[cdnLoading,setCdnLoading]=reactExports.useState(!1);reactExports.useEffect(()=>{open&&fetch(apiUrl("/api/plugins")).then(r=>{if(!r.ok)throw new Error(r.status);return r.json()}).then(data=>{setPluginsList(data.plugins||[]),setPluginsDir(data.pluginsDir||"")}).catch(()=>{})},[open]),reactExports.useEffect(()=>{open||(setDeleteConfirmVisible(!1),setDeleteTarget(null),setCdnModalVisible(!1),setCdnUrl(""),setCdnLoading(!1))},[open]);const handleCdnInstall=()=>{if(cdnUrl.trim()){try{new URL(cdnUrl)}catch{return void staticMethods.error(t("ui.plugins.cdnInvalidUrl"))}setCdnLoading(!0),fetch(apiUrl("/api/plugins/install-from-url"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:cdnUrl.trim()})}).then(r=>r.json()).then(data=>{data.error?staticMethods.error(t("ui.plugins.cdnInstallFailed",{reason:data.error})):(staticMethods.success(t("ui.plugins.cdnInstallSuccess")),data.plugins&&(setPluginsList(data.plugins),setPluginsDir(data.pluginsDir||"")),setCdnModalVisible(!1),setCdnUrl(""))}).catch(err=>{staticMethods.error(t("ui.plugins.cdnInstallFailed",{reason:err.message||"Network error"}))}).finally(()=>{setCdnLoading(!1)})}else staticMethods.error(t("ui.plugins.cdnUrlRequired"))};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("input",{ref:fileInputRef,type:"file",accept:".js,.mjs",multiple:!0,style:{display:"none"},onChange:e=>{const fileHandles=e.target.files,resetInput=()=>{fileInputRef.current&&(fileInputRef.current.value="")};if(!fileHandles||0===fileHandles.length)return void resetInput();for(const f of fileHandles)if(!f.name.endsWith(".js")&&!f.name.endsWith(".mjs"))return staticMethods.error(t("ui.plugins.invalidFile")),void resetInput();const readPromises=Array.from(fileHandles).map(f=>new Promise((resolve,reject)=>{const reader=new FileReader;reader.onload=()=>resolve({name:f.name,content:reader.result}),reader.onerror=()=>reject(new Error(`Failed to read ${f.name}`)),reader.readAsText(f)}));Promise.all(readPromises).then(files=>fetch(apiUrl("/api/plugins/upload"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:files})})).then(r=>r.ok?r.json():r.text().then(text=>{try{return JSON.parse(text)}catch{throw new Error(t("ui.plugins.serverError",{status:r.status}))}})).then(data=>{data.error?staticMethods.error(t("ui.plugins.addFailed",{reason:data.error})):data.plugins&&(setPluginsList(data.plugins),setPluginsDir(data.pluginsDir||""),staticMethods.success(t("ui.plugins.addSuccess")))}).catch(err=>{staticMethods.error(err.message)}).finally(()=>{resetInput()})}}),jsxRuntimeExports.jsxs(Modal,{title:jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(RefIcon$c,{className:styles$1.titleIcon}),t("ui.pluginManagement")]}),open:open,onCancel:onClose,footer:jsxRuntimeExports.jsxs("div",{className:styles$1.pluginModalFooter,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.pluginModalFooterLeft,children:[jsxRuntimeExports.jsx(Button,{icon:jsxRuntimeExports.jsx(RefIcon$e,{}),onClick:()=>{var _a;null==(_a=fileInputRef.current)||_a.click()},children:t("ui.plugins.add")}),jsxRuntimeExports.jsx(Button,{icon:jsxRuntimeExports.jsx(RefIcon$8,{}),onClick:()=>{setCdnUrl(""),setCdnLoading(!1),setCdnModalVisible(!0)},children:t("ui.plugins.cdnInstall")})]}),jsxRuntimeExports.jsx(Button,{icon:jsxRuntimeExports.jsx(RefIcon$k,{}),onClick:()=>{fetch(apiUrl("/api/plugins/reload"),{method:"POST"}).then(r=>{if(!r.ok)throw new Error(r.status);return r.json()}).then(data=>{setPluginsList(data.plugins||[]),setPluginsDir(data.pluginsDir||"")}).catch(()=>{})},children:t("ui.plugins.reload")})]}),width:560,styles:{body:isMobile?{zoom:.6}:{}},children:[pluginsDir&&jsxRuntimeExports.jsxs("div",{className:styles$1.pluginDirHint,children:[jsxRuntimeExports.jsxs("span",{className:styles$1.pluginDirLabel,children:[t("ui.plugins.pluginsDir"),":"]})," ",jsxRuntimeExports.jsx("code",{className:styles$1.pluginDirPath,onClick:()=>{navigator.clipboard.writeText(pluginsDir).then(()=>{staticMethods.success(t("ui.copied"))}).catch(()=>{})},children:pluginsDir})]}),0===pluginsList.length?jsxRuntimeExports.jsxs("div",{className:styles$1.pluginEmpty,children:[jsxRuntimeExports.jsx("div",{className:styles$1.pluginEmptyTitle,children:t("ui.plugins.empty")}),jsxRuntimeExports.jsx("div",{className:styles$1.pluginEmptyHint,children:t("ui.plugins.emptyHint")})]}):jsxRuntimeExports.jsx("div",{className:styles$1.pluginList,children:pluginsList.map(p=>jsxRuntimeExports.jsxs("div",{className:styles$1.pluginItem,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.pluginInfo,children:[jsxRuntimeExports.jsx("span",{className:styles$1.pluginName,children:p.name}),jsxRuntimeExports.jsx("span",{className:styles$1.pluginFile,children:p.file}),p.hooks.length>0&&jsxRuntimeExports.jsx("span",{className:styles$1.pluginHooks,children:p.hooks.map(h=>jsxRuntimeExports.jsx("span",{className:styles$1.pluginHookTag,children:h},h))})]}),jsxRuntimeExports.jsxs("div",{className:styles$1.pluginActions,children:[jsxRuntimeExports.jsx(Switch,{size:"small",checked:p.enabled,onChange:checked=>{return name=p.name,enabled=checked,void context._prefsReady.then(()=>{if("function"!=typeof context.updatePreferences)return;const prefs=context.preferences||{};let disabledPlugins=Array.isArray(prefs.disabledPlugins)?[...prefs.disabledPlugins]:[];return enabled?disabledPlugins=disabledPlugins.filter(n=>n!==name):disabledPlugins.includes(name)||disabledPlugins.push(name),context.updatePreferences({disabledPlugins:disabledPlugins}).then(()=>fetch(apiUrl("/api/plugins/reload"),{method:"POST"})).then(r=>{if(!r.ok)throw new Error(r.status);return r.json()}).then(data=>{setPluginsList(data.plugins||[]),setPluginsDir(data.pluginsDir||"")})}).catch(()=>{});var name,enabled}}),jsxRuntimeExports.jsx(Button,{type:"text",size:"small",danger:!0,icon:jsxRuntimeExports.jsx(RefIcon$g,{}),onClick:()=>{return file=p.file,name=p.name,setDeleteTarget({file:file,name:name}),void setDeleteConfirmVisible(!0);var file,name}})]})]},p.file))})]}),jsxRuntimeExports.jsx(Modal,{title:t("ui.plugins.delete"),open:deleteConfirmVisible,onCancel:()=>{setDeleteConfirmVisible(!1),setDeleteTarget(null)},onOk:()=>{const file=null==deleteTarget?void 0:deleteTarget.file;file&&(setDeleteConfirmVisible(!1),setDeleteTarget(null),fetch(apiUrl(`/api/plugins?file=${encodeURIComponent(file)}`),{method:"DELETE"}).then(r=>{if(!r.ok)throw new Error(r.status);return r.json()}).then(data=>{data.plugins&&(setPluginsList(data.plugins),setPluginsDir(data.pluginsDir||""))}).catch(()=>{}))},okType:"danger",okText:"OK",cancelText:"Cancel",styles:{body:isMobile?{zoom:.6}:{}},children:jsxRuntimeExports.jsx("p",{children:deleteTarget?t("ui.plugins.deleteConfirm",{name:deleteTarget.name}):""})}),jsxRuntimeExports.jsx(Modal,{title:jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(RefIcon$8,{className:styles$1.titleIcon}),t("ui.plugins.cdnInstall")]}),open:cdnModalVisible,onCancel:()=>{setCdnModalVisible(!1),setCdnUrl(""),setCdnLoading(!1)},onOk:handleCdnInstall,confirmLoading:cdnLoading,okText:t("ui.plugins.cdnInstallBtn"),cancelText:t("ui.cancel"),width:480,styles:{body:isMobile?{zoom:.6}:{}},children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:styles$1.cdnUrlLabel,children:t("ui.plugins.cdnUrl")}),jsxRuntimeExports.jsx(Input,{placeholder:t("ui.plugins.cdnUrlPlaceholder"),value:cdnUrl,onChange:e=>{setCdnUrl(e.target.value)},onPressEnter:handleCdnInstall,className:styles$1.cdnInput})]})})]})}function ProcessModal({open:open,onClose:onClose}){const[processList,setProcessList]=reactExports.useState([]),[processLoading,setProcessLoading]=reactExports.useState(!1),[killConfirmPid,setKillConfirmPid]=reactExports.useState(null),[killing,setKilling]=reactExports.useState(!1),fetchProcesses=reactExports.useCallback(()=>{setProcessLoading(!0),fetch(apiUrl("/api/ccv-processes")).then(r=>r.json()).then(data=>{setProcessList(data.processes||[]),setProcessLoading(!1)}).catch(()=>{setProcessList([]),setProcessLoading(!1)})},[]);reactExports.useEffect(()=>{open&&fetchProcesses()},[open,fetchProcesses]),reactExports.useEffect(()=>{open||(setKillConfirmPid(null),setKilling(!1))},[open]);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Modal,{title:jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(RefIcon$7,{className:styles$1.titleIcon}),t("ui.processManagement")]}),open:open,onCancel:onClose,footer:jsxRuntimeExports.jsx(Button,{icon:jsxRuntimeExports.jsx(RefIcon$k,{}),onClick:fetchProcesses,loading:processLoading,children:t("ui.processManagement.refresh")}),width:780,styles:{body:isMobile?{zoom:.6}:{}},children:jsxRuntimeExports.jsx(ForwardTable,{dataSource:processList,rowKey:"pid",loading:processLoading,size:"middle",pagination:!1,scroll:{x:"max-content"},columns:[{title:t("ui.processManagement.port"),dataIndex:"port",width:80,render:text=>text?jsxRuntimeExports.jsx("a",{href:`${window.location.protocol}//127.0.0.1:${text}`,target:"_blank",rel:"noopener noreferrer",children:text}):""},{title:"PID",dataIndex:"pid",width:80},{title:t("ui.processManagement.command"),dataIndex:"command",ellipsis:!0},{title:t("ui.processManagement.startTime"),dataIndex:"startTime",width:200},{title:t("ui.processManagement.action"),width:100,render:(_,record)=>record.isCurrent?jsxRuntimeExports.jsx(Button,{size:"small",className:styles$1.currentProcessBtn,children:t("ui.processManagement.current")}):jsxRuntimeExports.jsx(Button,{size:"small",danger:!0,onClick:()=>{return pid=record.pid,void setKillConfirmPid(pid);var pid},children:t("ui.processManagement.kill")})}]})}),jsxRuntimeExports.jsx(Modal,{title:t("ui.processManagement.killConfirm"),open:null!==killConfirmPid,onCancel:()=>{setKillConfirmPid(null)},onOk:()=>{const pid=killConfirmPid;pid&&(setKilling(!0),fetch(apiUrl("/api/ccv-processes/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:pid})}).then(r=>r.json()).then(data=>{data.ok?(staticMethods.success(t("ui.processManagement.killed")),fetchProcesses()):staticMethods.error(data.error||t("ui.processManagement.killFailed"))}).catch(()=>{staticMethods.error(t("ui.processManagement.killFailed"))}).finally(()=>{setKilling(!1),setKillConfirmPid(null)}))},confirmLoading:killing,okType:"danger",styles:{body:isMobile?{zoom:.6}:{}}})]})}const EMPTY_FORM={name:"",baseURL:"",apiKey:"",models:"",activeModel:""};function ProxyModal({open:open,onClose:onClose,proxyProfiles:proxyProfiles,activeProxyId:activeProxyId,defaultConfig:defaultConfig,onProxyProfileChange:onProxyProfileChange}){const[editingProxy,setEditingProxy]=reactExports.useState(null),[editForm,setEditForm]=reactExports.useState(EMPTY_FORM),[deleteConfirmTarget,setDeleteConfirmTarget]=reactExports.useState(null);reactExports.useEffect(()=>{open||(setEditingProxy(null),setEditForm(EMPTY_FORM),setDeleteConfirmTarget(null))},[open]);const profiles=proxyProfiles||[],activeId=activeProxyId||"max",updateField=(field2,value)=>{setEditForm(prev=>({...prev,[field2]:value}))};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Modal,{title:jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(OpenFolderIcon,{apiEndpoint:apiUrl("/api/open-profile-dir"),title:t("ui.proxy.openConfigDir"),size:16})," ",t("ui.proxySwitch")," ",jsxRuntimeExports.jsx(ConceptHelp,{doc:"ProxySwitch",zIndex:1100})]}),open:open,onCancel:onClose,footer:null,width:520,styles:{body:isMobile?{zoom:.6}:{}},children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:styles$1.proxyWarning,children:["⚠️ ",t("ui.proxy.maxWarning")]}),jsxRuntimeExports.jsx("div",{className:styles$1.proxyList,children:profiles.map(p=>{var _a;return jsxRuntimeExports.jsxs("div",{className:`${styles$1.proxyItem} ${p.id===activeId?styles$1.proxyItemActive:""}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.proxyItemMain,onClick:()=>(p=>{p.id!==activeId&&onProxyProfileChange({active:p.id,profiles:profiles})})(p),children:[jsxRuntimeExports.jsx(Radio,{checked:p.id===activeId,style:{marginRight:8}}),jsxRuntimeExports.jsxs("div",{className:styles$1.proxyItemInfo,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.proxyItemNameRow,children:[jsxRuntimeExports.jsx("span",{className:styles$1.proxyItemName,children:p.name}),"max"===p.id&&jsxRuntimeExports.jsx(Tag,{className:styles$1.proxyBuiltinTag,children:t("ui.proxy.builtin")})]}),"max"===p.id&&defaultConfig&&jsxRuntimeExports.jsxs("div",{className:styles$1.proxyItemDetail,children:[(()=>{try{return new URL(defaultConfig.origin).host}catch{return defaultConfig.origin}})(),defaultConfig.authType?` · ${defaultConfig.authType}`:"",defaultConfig.apiKey?` · ${defaultConfig.apiKey}`:"",defaultConfig.model?` · ${defaultConfig.model}`:""]}),"max"!==p.id&&p.baseURL&&jsxRuntimeExports.jsxs("div",{className:styles$1.proxyItemDetail,children:[(()=>{try{return new URL(p.baseURL).host}catch{return p.baseURL}})(),p.activeModel?` · ${p.activeModel}`:(null==(_a=p.models)?void 0:_a.length)?` · ${p.models[0]}`:""]})]})]}),"max"!==p.id&&jsxRuntimeExports.jsxs("div",{className:styles$1.proxyItemActions,children:[jsxRuntimeExports.jsx(Button,{type:"text",size:"small",icon:jsxRuntimeExports.jsx(RefIcon$l,{}),onClick:()=>(p=>{setEditingProxy(p.id),setEditForm({name:p.name||"",baseURL:p.baseURL||"",apiKey:p.apiKey||"",models:(p.models||[]).join(", "),activeModel:p.activeModel||""})})(p)}),jsxRuntimeExports.jsx(Button,{type:"text",size:"small",danger:!0,icon:jsxRuntimeExports.jsx(RefIcon$g,{}),onClick:()=>(p=>{setDeleteConfirmTarget(p)})(p)})]})]},p.id)})}),editingProxy&&jsxRuntimeExports.jsxs("div",{className:styles$1.proxyEditForm,children:[jsxRuntimeExports.jsxs("div",{className:styles$1.proxyEditRow,children:[jsxRuntimeExports.jsxs("label",{children:[t("ui.proxy.name")," ",jsxRuntimeExports.jsx("span",{className:styles$1.proxyRequired,children:"*"})]}),jsxRuntimeExports.jsx(Input,{size:"small",value:editForm.name,onChange:e=>updateField("name",e.target.value)})]}),jsxRuntimeExports.jsxs("div",{className:styles$1.proxyEditRow,children:[jsxRuntimeExports.jsxs("label",{children:[t("ui.proxy.baseURL")," ",jsxRuntimeExports.jsx("span",{className:styles$1.proxyRequired,children:"*"})]}),jsxRuntimeExports.jsx(Input,{size:"small",value:editForm.baseURL,onChange:e=>updateField("baseURL",e.target.value),placeholder:"https://api.example.com"})]}),jsxRuntimeExports.jsxs("div",{className:styles$1.proxyEditRow,children:[jsxRuntimeExports.jsxs("label",{children:[t("ui.proxy.apiKey")," ",jsxRuntimeExports.jsx("span",{className:styles$1.proxyRequired,children:"*"})]}),jsxRuntimeExports.jsx(Input.Password,{size:"small",value:editForm.apiKey,onChange:e=>updateField("apiKey",e.target.value),placeholder:"sk-..."})]}),jsxRuntimeExports.jsx("div",{className:styles$1.proxyEditDivider}),jsxRuntimeExports.jsxs("div",{className:styles$1.proxyEditRow,children:[jsxRuntimeExports.jsx("label",{children:t("ui.proxy.models")}),jsxRuntimeExports.jsx(Input,{size:"small",value:editForm.models,onChange:e=>updateField("models",e.target.value),placeholder:"model-1, model-2"})]}),jsxRuntimeExports.jsxs("div",{className:styles$1.proxyEditRow,children:[jsxRuntimeExports.jsx("label",{children:t("ui.proxy.activeModel")}),jsxRuntimeExports.jsx(Select,{size:"small",className:styles$1.fullWidthSelect,value:editForm.activeModel||void 0,onChange:v=>updateField("activeModel",v),placeholder:t("ui.proxy.activeModel"),children:(editForm.models||"").split(",").map(m=>m.trim()).filter(Boolean).map(m=>jsxRuntimeExports.jsx(Select.Option,{value:m,children:m},m))})]}),jsxRuntimeExports.jsxs("div",{className:styles$1.proxyEditBtns,children:[jsxRuntimeExports.jsx(Button,{size:"small",icon:jsxRuntimeExports.jsx(RefIcon$m,{}),type:"primary",onClick:()=>{var _a,_b,_c;if(!(null==(_a=editForm.name)?void 0:_a.trim())||!(null==(_b=editForm.baseURL)?void 0:_b.trim())||!(null==(_c=editForm.apiKey)?void 0:_c.trim()))return void staticMethods.warning(t("ui.proxy.requiredFields"));const models=(editForm.models||"").split(",").map(m=>m.trim()).filter(Boolean),updated={id:"__new__"===editingProxy?`proxy_${Date.now()}`:editingProxy,name:editForm.name.trim(),baseURL:editForm.baseURL.trim(),apiKey:editForm.apiKey.trim(),models:models,activeModel:editForm.activeModel||models[0]||""};let newProfiles;newProfiles="__new__"===editingProxy?[...profiles,updated]:profiles.map(p=>p.id===editingProxy?{...p,...updated,id:p.id}:p),onProxyProfileChange({active:activeId,profiles:newProfiles}),setEditingProxy(null)},children:t("ui.proxy.save")}),jsxRuntimeExports.jsx(Button,{size:"small",icon:jsxRuntimeExports.jsx(RefIcon$n,{}),onClick:()=>{setEditingProxy(null)},children:t("ui.proxy.cancel")})]})]}),!editingProxy&&jsxRuntimeExports.jsx(Button,{block:!0,type:"dashed",icon:jsxRuntimeExports.jsx(RefIcon$e,{}),style:{marginTop:12},onClick:()=>{setEditingProxy("__new__"),setEditForm(EMPTY_FORM)},children:t("ui.proxy.addProxy")})]})}),jsxRuntimeExports.jsx(Modal,{title:t("ui.proxy.deleteProxy"),open:null!==deleteConfirmTarget,onCancel:()=>{setDeleteConfirmTarget(null)},onOk:()=>{if(!deleteConfirmTarget)return;const newProfiles=profiles.filter(x=>x.id!==deleteConfirmTarget.id),newActive=activeId===deleteConfirmTarget.id?"max":activeId;onProxyProfileChange({active:newActive,profiles:newProfiles}),setDeleteConfirmTarget(null)},okType:"danger",styles:{body:isMobile?{zoom:.6}:{}},children:deleteConfirmTarget&&t("ui.proxy.deleteConfirm",{name:deleteConfirmTarget.name})})]})}export{hasSkillsReminder as $,AppBase as A,ProcessModal as B,ConceptHelp as C,ProxyModal as D,OpenFolderIcon as E,FullFileDiffView as F,ToolApprovalPanel as G,resolveTeammateNames as H,ImageLightbox as I,resolveCalibrationTokens as J,RefIcon$c as K,RefIcon$7 as L,MemoryDetailModal as M,RefIcon$1 as N,OPTIMISTIC_CLEAR_PERCENT as O,PluginModal as P,getModelShort as Q,RefIcon as R,SkillsManagerModal as S,TerminalWsProvider as T,formatRequestTag as U,renderMarkdown as V,restoreSlimmedEntry as W,stripPrivateKeys as X,isClaudeMdReminder as Y,isSkillsReminder as Z,hasClaudeMdReminder as _,ImageViewer as a,extractCachedContent as a0,filterRelevantRequests as a1,findPrevMainAgentTimestamp as a2,buildGitTree as b,FileContentView as c,computeTokenStats as d,computeToolUsageStats as e,fetchAllRepos as f,computeSkillUsageStats as g,computeCacheRebuildStats as h,isImageFile as i,classifyRequest as j,formatTokenCount as k,appConfig as l,isSystemText as m,classifyUserContent as n,isMainAgent as o,styles$p as p,getEffectiveModel as q,AUTO_COMPACT_USABLE_RATIO as r,styles$1 as s,getModelMaxTokens as t,uploadFileAndGetPath as u,ApprovalModal as v,RefIcon$a as w,ChatView as x,TerminalPanel as y,CachePopoverContent as z};
|