cc-viewer 1.6.237 → 1.6.239
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-BjuiwY9Z.js → App-CbEztYyO.js} +1 -1
- package/dist/assets/{MdxEditorPanel-B8olYcJP.js → MdxEditorPanel-BNBDCv3f.js} +1 -1
- package/dist/assets/MemoryDetailModal-Bw69dXta.js +2 -0
- package/dist/assets/{Mobile-DFAB3sUa.js → Mobile-DfVLfTtV.js} +1 -1
- package/dist/assets/{index-BcYTfQp1.js → index-B-JBbq1z.js} +2 -2
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/MemoryDetailModal-B99Qi8vZ.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-Cydvnbop.js","assets/vendor-mdxeditor-lhz8HD2R.js","assets/vendor-antd-COAwO2n0.js","assets/vendor-codemirror-B_arK_ec.js","assets/vendor-markdown-Bpu4AByL.js","assets/MdxEditorPanel-BNBDCv3f.js","assets/index-B-JBbq1z.js","assets/index-sVTuiL15.css","assets/MdxEditorPanel-DvqnmX-m.css"])))=>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,U as Typography,$ as RefIcon$7,i as Button,G as RefIcon$8,S as Spin,O as Empty,Q as List,a0 as Card,a1 as RefIcon$9,w as Space,a2 as Popconfirm,j as RefIcon$a,s as staticMethods,M as Modal,a3 as RefIcon$b,T as Tag,x as Input,R as React__default,Z as Checkbox,P as Popover,n as RefIcon$c,H as ForwardTable,C as ConfigProvider,a4 as theme,J as Tooltip,y as RefIcon$d,c as ReactDOM,u as Collapse,D as Dropdown,g as getDefaultExportFromCjs,a5 as Divider,m as Select,Y as Alert}from"./vendor-antd-COAwO2n0.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-B_arK_ec.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-B-JBbq1z.js";import{_ as __vitePreload}from"./vendor-mdxeditor-lhz8HD2R.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-CR72uTTv.js";var 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$6=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$5=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$4=reactExports.forwardRef(CameraOutlined),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$3=reactExports.forwardRef(DatabaseOutlined),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$2=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$1=reactExports.forwardRef(SaveOutlined),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$q_root="_root_2zmas_2",styles$q_inner="_inner_2zmas_10",styles$q_header="_header_2zmas_17",styles$q_headerTitle="_headerTitle_2zmas_22",styles$q_headerFolderIcon="_headerFolderIcon_2zmas_27",styles$q_headerSubtitle="_headerSubtitle_2zmas_32",styles$q_addButtonRow="_addButtonRow_2zmas_36",styles$q_loadingCenter="_loadingCenter_2zmas_42",styles$q_emptyState="_emptyState_2zmas_47",styles$q_card="_card_2zmas_52",styles$q_cardRow="_cardRow_2zmas_59",styles$q_cardLeft="_cardLeft_2zmas_65",styles$q_cardNameRow="_cardNameRow_2zmas_70",styles$q_cardName="_cardName_2zmas_70",styles$q_cardPath="_cardPath_2zmas_82",styles$q_cardMeta="_cardMeta_2zmas_87",styles$q_dirPathHeader="_dirPathHeader_2zmas_96",styles$q_dirCurrentPath="_dirCurrentPath_2zmas_104",styles$q_dirFolderIcon="_dirFolderIcon_2zmas_113",styles$q_dirList="_dirList_2zmas_118",styles$q_dirListCenter="_dirListCenter_2zmas_124",styles$q_dirItem="_dirItem_2zmas_129",styles$q_dirItemInner="_dirItemInner_2zmas_137",styles$q_dirItemName="_dirItemName_2zmas_145",styles$q_dirGitTag="_dirGitTag_2zmas_153",styles$q_dirFooter="_dirFooter_2zmas_162",styles$q_dirPathInputRow="_dirPathInputRow_2zmas_170",styles$q_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$q_dirPathHeader,children:[jsxRuntimeExports.jsx(Button,{type:"text",icon:jsxRuntimeExports.jsx(RefIcon$6,{}),disabled:!parentPath,onClick:()=>parentPath&&browse(parentPath),size:"small"}),jsxRuntimeExports.jsxs(Text$4,{className:styles$q_dirCurrentPath,children:[jsxRuntimeExports.jsx(RefIcon$7,{className:styles$q_dirFolderIcon}),currentPath]})]}),jsxRuntimeExports.jsx("div",{className:styles$q_dirList,children:loading2?jsxRuntimeExports.jsx("div",{className:styles$q_dirListCenter,children:jsxRuntimeExports.jsx(Spin,{})}):0===dirs.length?jsxRuntimeExports.jsx("div",{className:styles$q_dirListCenter,children:jsxRuntimeExports.jsx(Text$4,{type:"secondary",children:t("ui.workspaces.emptyDir")})}):dirs.map(dir=>jsxRuntimeExports.jsxs("div",{className:styles$q_dirItem,onMouseEnter:e=>e.currentTarget.style.background="var(--bg-elevated)",onMouseLeave:e=>e.currentTarget.style.background="transparent",children:[jsxRuntimeExports.jsxs("div",{className:styles$q_dirItemInner,onClick:()=>browse(dir.path),children:[jsxRuntimeExports.jsx(RefIcon$b,{style:{color:dir.hasGit?"var(--color-primary)":"var(--text-muted)",fontSize:16,flexShrink:0}}),jsxRuntimeExports.jsx(Text$4,{className:styles$q_dirItemName,children:dir.name}),dir.hasGit&&jsxRuntimeExports.jsxs(Tag,{color:"blue",className:styles$q_dirGitTag,children:[jsxRuntimeExports.jsx(RefIcon$5,{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$q_dirFooter,children:[jsxRuntimeExports.jsxs(Button,{type:"primary",ghost:!0,block:!0,icon:jsxRuntimeExports.jsx(RefIcon$7,{}),onClick:()=>onSelect(currentPath),children:[t("ui.workspaces.selectCurrent")," — ",currentPath.split("/").pop()||currentPath]}),jsxRuntimeExports.jsxs("div",{className:styles$q_dirPathInputRow,children:[jsxRuntimeExports.jsx(Input,{size:"small",value:pathInput,onChange:e=>setPathInput(e.target.value),onPressEnter:handleGoTo,placeholder:t("ui.workspaces.pathPlaceholder"),className:styles$q_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$q_root,children:[jsxRuntimeExports.jsxs("div",{className:styles$q_inner,children:[jsxRuntimeExports.jsxs("div",{className:styles$q_header,children:[jsxRuntimeExports.jsxs(Title,{level:3,className:styles$q_headerTitle,children:[jsxRuntimeExports.jsx(RefIcon$7,{className:styles$q_headerFolderIcon}),t("ui.workspaces.title")]}),jsxRuntimeExports.jsx(Text$4,{type:"secondary",className:styles$q_headerSubtitle,children:t("ui.workspaces.subtitle")})]}),jsxRuntimeExports.jsx("div",{className:styles$q_addButtonRow,children:jsxRuntimeExports.jsx(Button,{type:"primary",icon:jsxRuntimeExports.jsx(RefIcon$8,{}),onClick:()=>setBrowseOpen(!0),size:"large",children:t("ui.workspaces.browse")})}),loading2?jsxRuntimeExports.jsx("div",{className:styles$q_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$q_emptyState}):jsxRuntimeExports.jsx(List,{dataSource:workspaces,renderItem:item=>jsxRuntimeExports.jsx(Card,{size:"small",className:styles$q_card,hoverable:!0,onClick:()=>handleLaunch(item,!1),children:jsxRuntimeExports.jsxs("div",{className:styles$q_cardRow,children:[jsxRuntimeExports.jsxs("div",{className:styles$q_cardLeft,children:[jsxRuntimeExports.jsx("div",{className:styles$q_cardNameRow,children:jsxRuntimeExports.jsx(Text$4,{strong:!0,className:styles$q_cardName,children:item.projectName})}),jsxRuntimeExports.jsx(Text$4,{type:"secondary",className:styles$q_cardPath,children:item.path}),jsxRuntimeExports.jsxs("div",{className:styles$q_cardMeta,children:[jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(RefIcon$9,{style:{marginRight:4}}),timeAgo(item.lastUsed)]}),item.logCount>0&&jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx(RefIcon$3,{style:{marginRight:4}}),item.logCount," logs (",formatSize(item.totalSize),")"]})]})]}),jsxRuntimeExports.jsxs(Space,{children:[jsxRuntimeExports.jsx(Button,{type:"primary",icon:jsxRuntimeExports.jsx(RefIcon$2,{}),loading:launching===item.id,onClick:e=>{e.stopPropagation(),handleLaunch(item,!1)},children:t("ui.workspaces.normalLaunch")}),jsxRuntimeExports.jsx(Button,{icon:jsxRuntimeExports.jsx(RefIcon$2,{}),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$a,{}),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$p_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$p_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 _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,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)}}return dirty?{...entry,body:{...entry.body,tools:newTools,system:newSystem}}: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}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:"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1024 1024\" width=\"200\" height=\"200\" overflow=\"visible\"><style><![CDATA[.logo{will-change:d;shape-rendering:geometricPrecision;fill:#D97757;animation:logoWave 3.2s linear infinite;}@keyframes logoWave{8.33%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L404 502 L396 495 L273 418 L143 326 L81 280 L43 257 L20 226 L12 180 L51 141 L104 141 L150 180 L250 257 L381 349 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}16.67%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L392 365 L384 350 L315 227 L238 97 L207 51 L200 20 L238 -34 L261 -42 L315 -34 L338 -19 L369 51 L422 166 L499 319 L522 365 L530 412 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}25%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L525 429 L525 383 L533 298 L548 191 L564 52 L572 14 L595 -32 L633 -55 L664 -40 L687 -1 L687 22 L648 106 L625 252 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}33.33%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L591 349 L607 333 L660 264 L745 157 L783 118 L829 72 L860 49 L914 49 L952 111 L937 172 L876 241 L829 303 L768 387 L722 456 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}41.67%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L721 445 L867 415 L943 399 L1036 384 L1082 407 L1089 430 L1074 468 L974 492 L859 515 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}50%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L762 547 L877 547 L1031 554 L1069 577 L1100 623 L1092 646 L1031 677 L947 662 L755 616 L685 600 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}58.33%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L679 593 L733 646 L833 739 L963 861 L971 892 L956 915 L940 915 L825 831 L779 792 L679 708 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}66.67%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L682 707 L705 737 L828 914 L836 968 L828 983 L797 991 L767 983 L698 883 L621 783 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}75%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L568 696 L537 1064 L522 1080 L483 1095 L452 1072 L437 1034 L452 957 L476 857 L491 780 L506 680 L514 650 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}83.33%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L441 756 L326 910 L241 1002 L218 1010 L180 995 L180 964 L203 933 L326 780 L403 680 L449 618 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}91.67%{d:path('M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L137 828 L76 844 L52 820 L52 782 L68 767 L160 698 Z');}0%,100%{d:path('M198 678 L397 563 L403 550 L211 554 L96 547 L-27 539 L-50 531 L-81 500 L-81 485 L-58 470 L-19 470 L58 477 L173 485 L257 493 L380 508 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z');}}@media (prefers-reduced-motion:reduce){.logo{animation:none;}}]]></style><path class=\"logo\" d=\"M198 678 L397 563 L403 550 L243 550 L147 544 L45 538 L26 531 L0 506 L0 493 L19 480 L51 480 L115 486 L211 493 L282 499 L384 512 L403 512 L403 493 L397 486 L294 422 L186 346 L134 307 L102 288 L83 262 L77 224 L109 192 L154 192 L192 224 L275 288 L384 365 L397 378 L403 371 L397 358 L339 256 L275 147 L250 109 L243 83 L275 38 L294 32 L339 38 L358 51 L384 109 L429 205 L493 333 L512 371 L518 410 L525 422 L531 422 L531 384 L538 314 L550 224 L563 109 L570 77 L589 38 L621 19 L646 32 L666 64 L666 83 L634 154 L614 275 L595 358 L602 358 L614 346 L659 288 L730 198 L762 166 L800 128 L826 109 L870 109 L902 160 L890 211 L838 269 L800 320 L749 390 L710 448 L710 454 L717 454 L838 429 L902 416 L979 403 L1018 422 L1024 442 L1011 474 L928 493 L832 512 L685 544 L749 550 L845 550 L973 557 L1005 576 L1030 614 L1024 634 L973 659 L902 646 L742 608 L685 595 L678 595 L678 602 L723 646 L806 723 L915 826 L922 851 L909 870 L896 870 L800 800 L762 768 L678 698 L672 698 L672 704 L691 730 L794 877 L800 922 L794 934 L768 941 L742 934 L685 851 L621 768 L570 685 L563 691 L538 998 L525 1011 L493 1024 L467 1005 L454 973 L467 909 L486 826 L499 762 L512 678 L518 653 L512 653 L448 736 L352 864 L282 941 L262 947 L230 934 L230 909 L250 883 L352 755 L416 672 L454 621 L454 614 L186 787 L134 800 L115 781 L115 749 L128 736 L205 678 Z\"/></svg>"},{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 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 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-Cydvnbop.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$o={layout:"_layout_rk051_1",header:"_header_rk051_6",content:"_content_rk051_14",mainContainer:"_mainContainer_rk051_19",leftPanel:"_leftPanel_rk051_24",leftPanelHeader:"_leftPanelHeader_rk051_36",leftPanelCount:"_leftPanelCount_rk051_47",leftPanelBody:"_leftPanelBody_rk051_53",rightPanel:"_rightPanel_rk051_58",modalActions:"_modalActions_rk051_64",spinCenter:"_spinCenter_rk051_68",emptyCenter:"_emptyCenter_rk051_73",logListContainer:"_logListContainer_rk051_83",loadingOverlay:"_loadingOverlay_rk051_131",dragOverlay:"_dragOverlay_rk051_144",dragOverlayContent:"_dragOverlayContent_rk051_158",dragIcon:"_dragIcon_rk051_167",loadingText:"_loadingText_rk051_171",mobileLoadingOverlay:"_mobileLoadingOverlay_rk051_177",mobileLoadingSpinner:"_mobileLoadingSpinner_rk051_189",mobileLoadingLabel:"_mobileLoadingLabel_rk051_202",footer:"_footer_rk051_208",footerRight:"_footerRight_rk051_220",footerLink:"_footerLink_rk051_233",footerIcon:"_footerIcon_rk051_245",footerSep:"_footerSep_rk051_250",footerVersion:"_footerVersion_rk051_255",footerVersionNew:"_footerVersionNew_rk051_265",newBadge:"_newBadge_rk051_275",guideContainer:"_guideContainer_rk051_287",guideContent:"_guideContent_rk051_295",guideTitle:"_guideTitle_rk051_300",guideStep:"_guideStep_rk051_307",guideStepNum:"_guideStepNum_rk051_313",guideStepBody:"_guideStepBody_rk051_328",guideText:"_guideText_rk051_333",guideCode:"_guideCode_rk051_340",mobileChatOverlay:"_mobileChatOverlay_rk051_353",mobileChatOverlayVisible:"_mobileChatOverlayVisible_rk051_365",mobileNavBtn:"_mobileNavBtn_rk051_369",mobileChatInner:"_mobileChatInner_rk051_374",mobileGitDiffOverlay:"_mobileGitDiffOverlay_rk051_393",mobileGitDiffOverlayVisible:"_mobileGitDiffOverlayVisible_rk051_405",mobileGitDiffInner:"_mobileGitDiffInner_rk051_409",mobileFileExplorerOverlay:"_mobileFileExplorerOverlay_rk051_429",mobileFileExplorerOverlayVisible:"_mobileFileExplorerOverlayVisible_rk051_441",mobileFileExplorerInner:"_mobileFileExplorerInner_rk051_445",mobileCachePanelOverlay:"_mobileCachePanelOverlay_rk051_465",mobileCachePanelOverlayVisible:"_mobileCachePanelOverlayVisible_rk051_477",mobileCachePanelInner:"_mobileCachePanelInner_rk051_481",mobileCachePanelHeader:"_mobileCachePanelHeader_rk051_500",mobileCachePanelTitle:"_mobileCachePanelTitle_rk051_509",mobileCachePanelClose:"_mobileCachePanelClose_rk051_518",mobileCachePanelBody:"_mobileCachePanelBody_rk051_533",mobileMenuBtn:"_mobileMenuBtn_rk051_556",mobileMenuOverlay:"_mobileMenuOverlay_rk051_573",mobileMenuDropdown:"_mobileMenuDropdown_rk051_579",mobileMenuItem:"_mobileMenuItem_rk051_593",mobileStatsOverlay:"_mobileStatsOverlay_rk051_611",mobileStatsOverlayVisible:"_mobileStatsOverlayVisible_rk051_623",mobileStatsInner:"_mobileStatsInner_rk051_627",mobileLogMgmtOverlay:"_mobileLogMgmtOverlay_rk051_634",mobileLogMgmtOverlayVisible:"_mobileLogMgmtOverlayVisible_rk051_646",mobileLogMgmtHeader:"_mobileLogMgmtHeader_rk051_650",mobileLogMgmtTitle:"_mobileLogMgmtTitle_rk051_659",mobileLogMgmtClose:"_mobileLogMgmtClose_rk051_665",mobileLogMgmtActions:"_mobileLogMgmtActions_rk051_680",mobileLogMgmtBody:"_mobileLogMgmtBody_rk051_688",mobileSettingsOverlay:"_mobileSettingsOverlay_rk051_695",mobileSettingsOverlayVisible:"_mobileSettingsOverlayVisible_rk051_707",mobilePromptOverlay:"_mobilePromptOverlay_rk051_711",mobilePromptOverlayVisible:"_mobilePromptOverlayVisible_rk051_723",mobilePromptBody:"_mobilePromptBody_rk051_727",mobilePromptList:"_mobilePromptList_rk051_735",mobilePromptItem:"_mobilePromptItem_rk051_741",mobilePromptTimestamp:"_mobilePromptTimestamp_rk051_746",mobilePromptCard:"_mobilePromptCard_rk051_753",mobilePromptPreText:"_mobilePromptPreText_rk051_761",tableTimestampCell:"_tableTimestampCell_rk051_771",tablePreviewText:"_tablePreviewText_rk051_775",tablePreviewTextClickable:"_tablePreviewTextClickable_rk051_784",tableTag:"_tableTag_rk051_794",tableActionsCell:"_tableActionsCell_rk051_800",mobileCLIRoot:"_mobileCLIRoot_rk051_806",mobileCLIHeader:"_mobileCLIHeader_rk051_815",mobileCLIHeaderLeft:"_mobileCLIHeaderLeft_rk051_826",mobileCLIStatusLabel:"_mobileCLIStatusLabel_rk051_834",mobileCtxTag:"_mobileCtxTag_rk051_840",mobileCtxTagFill:"_mobileCtxTagFill_rk051_859",mobileCtxTagContent:"_mobileCtxTagContent_rk051_869",mobileCLIHeaderRight:"_mobileCLIHeaderRight_rk051_877",mobileCLIBody:"_mobileCLIBody_rk051_883",mobileSettingsBody:"_mobileSettingsBody_rk051_892",mobileSettingsSectionTitle:"_mobileSettingsSectionTitle_rk051_896",mobileSettingsRow:"_mobileSettingsRow_rk051_903",mobileSettingsLabel:"_mobileSettingsLabel_rk051_911",mobilePromptEmpty:"_mobilePromptEmpty_rk051_917",mobilePromptHeader:"_mobilePromptHeader_rk051_924",mobilePromptCount:"_mobilePromptCount_rk051_932",chatViewWrapper:"_chatViewWrapper_rk051_938",resumeFooterRight:"_resumeFooterRight_rk051_944",resumeFooterLeft:"_resumeFooterLeft_rk051_949",resumeCheckboxOpacity:"_resumeCheckboxOpacity_rk051_953",btnMarginLeft:"_btnMarginLeft_rk051_957",btnMarginRight:"_btnMarginRight_rk051_961",modalTitleInline:"_modalTitleInline_rk051_966",previewPopover:"_previewPopover_rk051_973",previewItem:"_previewItem_rk051_979",previewText:"_previewText_rk051_991"},MAX_SESSIONS=isMobile&&!isPad?30:100,OPTIMISTIC_CLEAR_PERCENT=5;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||null===this._currentSessionId)&&(this._currentSessionId=timestamp);for(let i=0;i<messages.length;i++)!isNewSession&&i<prevCount&&prevMessages[i]._timestamp?messages[i]._timestamp=prevMessages[i]._timestamp:messages[i]._timestamp||(messages[i]._timestamp=timestamp);mainAgentSessions=this.mergeMainAgentSessions(mainAgentSessions,entry,{skipTransientFilter:!0})}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._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=[],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=[]):null===currentSessionId&&(currentSessionId=timestamp);for(let j=timestamps.length;j<count;j++)timestamps.push(timestamp);if(messages.length>0)for(let j=0;j<messages.length;j++)messages[j]._timestamp=timestamps[j];prevUserId=userId,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$o.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$o.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$o.previewPopover,children:arr.map((text,i)=>jsxRuntimeExports.jsx("div",{className:styles$o.previewItem,children:jsxRuntimeExports.jsx("pre",{className:styles$o.previewText,children:text})},i))}),children:jsxRuntimeExports.jsx("span",{className:styles$o.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$o.tableTag,children:v||0})}],{title:t("ui.logSize"),dataIndex:"size",key:"size",width:90,render:v=>jsxRuntimeExports.jsx(Tag,{className:styles$o.tableTag,children:this.formatSize(v)})},{title:t("ui.logActions"),key:"actions",width:mobile?160:180,render:(_,log)=>jsxRuntimeExports.jsxs("span",{className:styles$o.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$c,{}),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?{algorithm:theme.defaultAlgorithm,token:{colorPrimary:"#0969DA",colorBgContainer:"#FFFFFF",colorBgLayout:"#FAFAFA",colorBgElevated:"#FFFFFF",colorBorder:"#E0E0E0",controlOutline:"transparent",controlOutlineWidth:0}}:{algorithm:theme.darkAlgorithm,token:{colorPrimary:"#1668dc",colorBgContainer:"#111",colorBgLayout:"#0a0a0a",colorBgElevated:"#1e1e1e",colorBorder:"#2a2a2a",controlOutline:"transparent",controlOutlineWidth:0}}}}__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$n_mdBlockWrapper="_mdBlockWrapper_7yafy_1",styles$n_actionBar="_actionBar_7yafy_5",styles$n_hoverPad="_hoverPad_7yafy_28",styles$n_hoverPadTop="_hoverPadTop_7yafy_34",styles$n_hoverPadBottom="_hoverPadBottom_7yafy_37",styles$n_actionBtn="_actionBtn_7yafy_46",styles$n_saveAsWrap="_saveAsWrap_7yafy_68",styles$n_saveMenu="_saveMenu_7yafy_72",styles$n_saveMenuItem="_saveMenuItem_7yafy_87",styles$n_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$n_mdBlockWrapper,onMouseEnter:isMobile&&!isPad?void 0:handleMouseEnter,onMouseLeave:isMobile&&!isPad?void 0:handleMouseLeave,children:[jsxRuntimeExports.jsx("div",{className:`chat-md ${className||""} ${trailingCursor?styles$n_streamingTail:""}`,style:style,dangerouslySetInnerHTML:{__html:html}}),(!isMobile||isPad)&&hovered&&jsxRuntimeExports.jsxs("div",{className:styles$n_actionBar,"data-html2canvas-ignore":!0,children:[jsxRuntimeExports.jsx("div",{className:`${styles$n_hoverPad} ${styles$n_hoverPadTop}`,"aria-hidden":"true"}),jsxRuntimeExports.jsxs("div",{className:styles$n_saveAsWrap,onMouseEnter:()=>setSaveMenuOpen(!0),onMouseLeave:()=>setSaveMenuOpen(!1),children:[jsxRuntimeExports.jsx(Tooltip,{title:saveMenuOpen?"":t("ui.saveAs"),mouseEnterDelay:.3,children:jsxRuntimeExports.jsx("span",{className:styles$n_actionBtn,children:jsxRuntimeExports.jsx(RefIcon$c,{})})}),saveMenuOpen&&jsxRuntimeExports.jsxs("div",{className:styles$n_saveMenu,children:[jsxRuntimeExports.jsxs("button",{className:styles$n_saveMenuItem,onClick:handleSaveAs,children:[jsxRuntimeExports.jsx(RefIcon$c,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveAsMd")})]}),jsxRuntimeExports.jsxs("button",{className:styles$n_saveMenuItem,onClick:handleCopy,children:[jsxRuntimeExports.jsx(RefIcon$d,{}),jsxRuntimeExports.jsx("span",{children:t("ui.copyTextContent")})]}),jsxRuntimeExports.jsxs("button",{className:styles$n_saveMenuItem,onClick:handleSaveAsImage,children:[jsxRuntimeExports.jsx(RefIcon$4,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveAsImage")})]}),jsxRuntimeExports.jsxs("button",{className:styles$n_saveMenuItem,onClick:handleSaveToProject,children:[jsxRuntimeExports.jsx(RefIcon$1,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveToProject")})]})]})]}),jsxRuntimeExports.jsx("div",{className:`${styles$n_hoverPad} ${styles$n_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}const styles$m_avatar="_avatar_coyp8_3",styles$m_avatarImg="_avatarImg_coyp8_21",styles$m_messageRow="_messageRow_coyp8_42",styles$m_messageRowEnd="_messageRowEnd_coyp8_48",styles$m_contentCol="_contentCol_coyp8_57",styles$m_contentColLimited="_contentColLimited_coyp8_61",styles$m_labelRow="_labelRow_coyp8_69",styles$m_labelRowEnd="_labelRowEnd_coyp8_76",styles$m_labelRight="_labelRight_coyp8_83",styles$m_labelText="_labelText_coyp8_91",styles$m_timeText="_timeText_coyp8_95",styles$m_timeTextNoMargin="_timeTextNoMargin_coyp8_101",styles$m_cacheContextText="_cacheContextText_coyp8_107",styles$m_labelTextRight="_labelTextRight_coyp8_115",styles$m_bubbleUser="_bubbleUser_coyp8_122 _bubble_coyp8_29",styles$m_bubbleAssistant="_bubbleAssistant_coyp8_134 _bubble_coyp8_29",styles$m_bubbleHighlight="_bubbleHighlight_coyp8_150",styles$m_bubbleHighlightFading="_bubbleHighlightFading_coyp8_154",styles$m_borderSvg="_borderSvg_coyp8_159",styles$m_borderSvgInset="_borderSvgInset_coyp8_168",styles$m_borderSvgFading="_borderSvgFading_coyp8_172",styles$m_borderRect="_borderRect_coyp8_177",styles$m_bubblePlan="_bubblePlan_coyp8_186 _bubble_coyp8_29",styles$m_bubbleSubAgent="_bubbleSubAgent_coyp8_194 _bubble_coyp8_29",styles$m_systemTagLabel="_systemTagLabel_coyp8_214",styles$m_skillLabel="_skillLabel_coyp8_218",styles$m_systemTagPre="_systemTagPre_coyp8_223",styles$m_collapseMargin="_collapseMargin_coyp8_231",styles$m_collapseNoMargin="_collapseNoMargin_coyp8_235",styles$m_collapseStream="_collapseStream_coyp8_240",styles$m_thinkingLabel="_thinkingLabel_coyp8_256",styles$m_thinkingEmptyHint="_thinkingEmptyHint_coyp8_260",styles$m_thinkingEmptyText="_thinkingEmptyText_coyp8_268",styles$m_enableThinkingBtn="_enableThinkingBtn_coyp8_273",styles$m_bashCollapseLabel="_bashCollapseLabel_coyp8_278",styles$m_toolBox="_toolBox_coyp8_285",styles$m_toolLabel="_toolLabel_coyp8_298",styles$m_simplifiedToolLabel="_simplifiedToolLabel_coyp8_302",styles$m_simplifiedToolTag="_simplifiedToolTag_coyp8_311",styles$m_simplifiedToolPopoverContent="_simplifiedToolPopoverContent_coyp8_329",styles$m_codePre="_codePre_coyp8_342",styles$m_pathTag="_pathTag_coyp8_373",styles$m_pathTagClickable="_pathTagClickable_coyp8_378",styles$m_descSpan="_descSpan_coyp8_391",styles$m_secondarySpan="_secondarySpan_coyp8_396",styles$m_patternSpan="_patternSpan_coyp8_400",styles$m_kvContainer="_kvContainer_coyp8_406",styles$m_kvItem="_kvItem_coyp8_411",styles$m_kvKey="_kvKey_coyp8_415",styles$m_kvValue="_kvValue_coyp8_419",styles$m_teammateStatusRow="_teammateStatusRow_coyp8_440",styles$m_teammateStatusRowCenter="_teammateStatusRowCenter_coyp8_446",styles$m_teammateStatusBubble="_teammateStatusBubble_coyp8_452",styles$m_taskNotifUsage="_taskNotifUsage_coyp8_469",styles$m_sendMessageBlock="_sendMessageBlock_coyp8_479",styles$m_sendMessageHeader="_sendMessageHeader_coyp8_487",styles$m_compactLabel="_compactLabel_coyp8_494",styles$m_compactPre="_compactPre_coyp8_499",styles$m_viewRequestBtn="_viewRequestBtn_coyp8_509",styles$m_viewRequestIcon="_viewRequestIcon_coyp8_521",styles$m_optionList="_optionList_coyp8_546",styles$m_questionSpacing="_questionSpacing_coyp8_558",styles$m_askQuestionBox="_askQuestionBox_coyp8_571",styles$m_askQuestionHeader="_askQuestionHeader_coyp8_580",styles$m_askQuestionText="_askQuestionText_coyp8_591",styles$m_askOptionItem="_askOptionItem_coyp8_597",styles$m_askOptionSelected="_askOptionSelected_coyp8_606",styles$m_askOptionDesc="_askOptionDesc_coyp8_611",styles$m_askCheckSvg="_askCheckSvg_coyp8_615",styles$m_planModeBox="_planModeBox_coyp8_622",styles$m_planStatusPending="_planStatusPending_coyp8_632",styles$m_planModeLabel="_planModeLabel_coyp8_637",styles$m_planModePermissions="_planModePermissions_coyp8_642",styles$m_planModePermLabel="_planModePermLabel_coyp8_648",styles$m_planModeHeader="_planModeHeader_coyp8_654",styles$m_planStatusBadge="_planStatusBadge_coyp8_660",styles$m_planStatusApproved="_planStatusApproved_coyp8_668",styles$m_planStatusRejected="_planStatusRejected_coyp8_677",styles$m_planContentPreview="_planContentPreview_coyp8_695",styles$m_planFeedback="_planFeedback_coyp8_708",styles$m_planFeedbackLabel="_planFeedbackLabel_coyp8_717",styles$m_planApprovalActions="_planApprovalActions_coyp8_722",styles$m_planApproveBtn="_planApproveBtn_coyp8_729",styles$m_planRejectBtn="_planRejectBtn_coyp8_744",styles$m_planOptionBtn="_planOptionBtn_coyp8_759",styles$m_dangerApprovalBox="_dangerApprovalBox_coyp8_774",styles$m_dangerApprovalBoxDenied="_dangerApprovalBoxDenied_coyp8_783",styles$m_ultraplanBadge="_ultraplanBadge_coyp8_787",styles$m_dangerApprovalHeader="_dangerApprovalHeader_coyp8_793",styles$m_dangerApprovalIcon="_dangerApprovalIcon_coyp8_799",styles$m_dangerApprovalLabel="_dangerApprovalLabel_coyp8_804",styles$m_dangerApprovalActions="_dangerApprovalActions_coyp8_809",styles$m_dangerApproveBtn="_dangerApproveBtn_coyp8_816",styles$m_dangerRejectBtn="_dangerRejectBtn_coyp8_831",styles$m_dangerOptionBtn="_dangerOptionBtn_coyp8_846",styles$m_dangerDeniedBadge="_dangerDeniedBadge_coyp8_861",styles$m_dangerDeniedDetail="_dangerDeniedDetail_coyp8_872",styles$m_planFeedbackInputWrap="_planFeedbackInputWrap_coyp8_882",styles$m_planFeedbackTextarea="_planFeedbackTextarea_coyp8_886",styles$m_planFeedbackBtnRow="_planFeedbackBtnRow_coyp8_906",styles$m_planFeedbackSendBtn="_planFeedbackSendBtn_coyp8_913",styles$m_planFeedbackCancelBtn="_planFeedbackCancelBtn_coyp8_933",styles$m_askQuestionInteractive="_askQuestionInteractive_coyp8_950",styles$m_askRadioGroup="_askRadioGroup_coyp8_961",styles$m_askRadioItem="_askRadioItem_coyp8_969",styles$m_askRadioItemSelected="_askRadioItemSelected_coyp8_992",styles$m_askRadioDot="_askRadioDot_coyp8_998",styles$m_askOptionBody="_askOptionBody_coyp8_1009",styles$m_askOptionLabel="_askOptionLabel_coyp8_1017",styles$m_askCheckboxGroup="_askCheckboxGroup_coyp8_1036",styles$m_askOtherInput="_askOtherInput_coyp8_1062",styles$m_askSubmitRow="_askSubmitRow_coyp8_1082",styles$m_askSubmitBtn="_askSubmitBtn_coyp8_1088",styles$m_askMarkdownLayout="_askMarkdownLayout_coyp8_1108",styles$m_askOptionsBody="_askOptionsBody_coyp8_1120",styles$m_askMarkdownPreview="_askMarkdownPreview_coyp8_1124",styles$m_chatImageFallback="_chatImageFallback_coyp8_1150",styles$m_chatImageImg="_chatImageImg_coyp8_1155",styles$m_bubbleRelative="_bubbleRelative_coyp8_1166",styles$m_skillSpacer="_skillSpacer_coyp8_1172",styles$m_skillTimeIndent="_skillTimeIndent_coyp8_1179",styles$m_previewPlaceholder="_previewPlaceholder_coyp8_1183";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$m_askQuestionInteractive,children:[jsxRuntimeExports.jsx("svg",{className:`${styles$m_borderSvg} ${styles$m_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$m_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$m_askQuestionHeader,children:q.header}),jsxRuntimeExports.jsx("div",{className:styles$m_askQuestionText,children:q.question})]}),optionsBody=jsxRuntimeExports.jsxs("div",{className:styles$m_askOptionsBody,children:[isMulti?jsxRuntimeExports.jsxs("div",{className:styles$m_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":opt.description?`${opt.label}: ${opt.description}`:opt.label,className:`${styles$m_askRadioItem}${checked?" "+styles$m_askRadioItemSelected:""}`,onClick:activate,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),activate())},children:[jsxRuntimeExports.jsx("span",{className:styles$m_askRadioDot,children:checked?"☑":"☐"}),jsxRuntimeExports.jsxs("span",{className:styles$m_askOptionBody,children:[jsxRuntimeExports.jsx("span",{className:styles$m_askOptionLabel,children:opt.label}),opt.description&&jsxRuntimeExports.jsx("span",{className:styles$m_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$m_askRadioItem}${otherActive[qi]?" "+styles$m_askRadioItemSelected:""}`,onClick:activate,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),activate())},children:[jsxRuntimeExports.jsx("span",{className:styles$m_askRadioDot,children:otherActive[qi]?"☑":"☐"}),jsxRuntimeExports.jsx("span",{className:styles$m_askOptionBody,children:jsxRuntimeExports.jsx("span",{className:styles$m_askOptionLabel,children:t("ui.askOther")})})]})})()]}):jsxRuntimeExports.jsxs("div",{className:styles$m_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":opt.description?`${opt.label}: ${opt.description}`:opt.label,className:`${styles$m_askRadioItem}${isSelected?" "+styles$m_askRadioItemSelected:""}`,onClick:activate,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),activate())},children:[jsxRuntimeExports.jsx("span",{className:styles$m_askRadioDot,children:isSelected?"◉":"○"}),jsxRuntimeExports.jsxs("span",{className:styles$m_askOptionBody,children:[jsxRuntimeExports.jsx("span",{className:styles$m_askOptionLabel,children:opt.label}),opt.description&&jsxRuntimeExports.jsx("span",{className:styles$m_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$m_askRadioItem}${otherActive[qi]?" "+styles$m_askRadioItemSelected:""}`,onClick:activate,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),activate())},children:[jsxRuntimeExports.jsx("span",{className:styles$m_askRadioDot,children:otherActive[qi]?"◉":"○"}),jsxRuntimeExports.jsx("span",{className:styles$m_askOptionBody,children:jsxRuntimeExports.jsx("span",{className:styles$m_askOptionLabel,children:t("ui.askOther")})})]})})()]}),otherActive[qi]&&jsxRuntimeExports.jsx("div",{className:styles$m_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$m_questionSpacing:void 0,children:[headerAndQuestion,hasPreview?jsxRuntimeExports.jsxs("div",{className:styles$m_askMarkdownLayout,children:[optionsBody,jsxRuntimeExports.jsx("div",{className:styles$m_askMarkdownPreview,children:focusedPreview?jsxRuntimeExports.jsx("pre",{children:focusedPreview}):jsxRuntimeExports.jsx("span",{className:styles$m_previewPlaceholder,children:"—"})})]}):optionsBody]},qi)}),jsxRuntimeExports.jsx("div",{className:styles$m_askSubmitRow,children:jsxRuntimeExports.jsx("button",{className:styles$m_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$l_wrapper="_wrapper_vsc0z_1",styles$l_header="_header_vsc0z_13",styles$l_headerRight="_headerRight_vsc0z_20",styles$l_filePath="_filePath_vsc0z_28",styles$l_filePathClickable="_filePathClickable_vsc0z_34",styles$l_toggle="_toggle_vsc0z_46",styles$l_diffSummary="_diffSummary_vsc0z_55",styles$l_diffBody="_diffBody_vsc0z_62",styles$l_gutter="_gutter_vsc0z_72",styles$l_gutterRow="_gutterRow_vsc0z_77",styles$l_lineNumOld="_lineNumOld_vsc0z_82",styles$l_lineNumNew="_lineNumNew_vsc0z_83",styles$l_prefix="_prefix_vsc0z_90",styles$l_codeWrap="_codeWrap_vsc0z_98",styles$l_codeInner="_codeInner_vsc0z_105",styles$l_codeLine="_codeLine_vsc0z_110",styles$l_rowContext="_rowContext_vsc0z_118",styles$l_rowDel="_rowDel_vsc0z_123",styles$l_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$l_rowDel:"add"===type?styles$l_rowAdd:styles$l_rowContext;return jsxRuntimeExports.jsxs("div",{className:styles$l_wrapper,children:[jsxRuntimeExports.jsxs("div",{className:styles$l_header,children:[jsxRuntimeExports.jsxs(Text$3,{className:onOpenFile?styles$l_filePathClickable:styles$l_filePath,children:["Edit: ",jsxRuntimeExports.jsx("span",{onClick:onOpenFile?e=>{e.stopPropagation(),onOpenFile(file_path)}:void 0,children:file_path})]}),jsxRuntimeExports.jsxs("span",{className:styles$l_headerRight,children:[jsxRuntimeExports.jsx(Text$3,{className:styles$l_diffSummary,children:t("ui.diffSummary",{added:added,removed:removed})}),jsxRuntimeExports.jsx(Text$3,{className:styles$l_toggle,onClick:()=>setCollapsed(c=>!c),children:t(collapsed?"ui.expand":"ui.collapse")})]})]}),!collapsed&&jsxRuntimeExports.jsxs("div",{className:styles$l_diffBody,children:[jsxRuntimeExports.jsx("div",{className:styles$l_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$l_gutterRow} ${rowCls(dl.type)}`,children:[jsxRuntimeExports.jsx("span",{className:styles$l_lineNumOld,style:{width:lineNumWidth},children:dl.oldNum??""}),jsxRuntimeExports.jsx("span",{className:styles$l_lineNumNew,style:{width:lineNumWidth},children:dl.newNum??""}),jsxRuntimeExports.jsx("span",{className:styles$l_prefix,children:prefix2})]},i)})}),jsxRuntimeExports.jsx("div",{className:styles$l_codeWrap,children:jsxRuntimeExports.jsx("div",{className:styles$l_codeInner,children:diffLines2.map((dl,i)=>jsxRuntimeExports.jsx("div",{className:`${styles$l_codeLine} ${rowCls(dl.type)}`,children:dl.text},i))})})]})]})}const styles$k_plainResult="_plainResult_hq7oa_1",styles$k_plainTitle="_plainTitle_hq7oa_14",styles$k_plainPre="_plainPre_hq7oa_18",styles$k_codeResult="_codeResult_hq7oa_27",styles$k_codeHeader="_codeHeader_hq7oa_39",styles$k_codeTitle="_codeTitle_hq7oa_51",styles$k_codeToggle="_codeToggle_hq7oa_56",styles$k_codePre="_codePre_hq7oa_63",styles$k_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$k_plainResult,children:[jsxRuntimeExports.jsxs("div",{className:styles$k_codeHeader,children:[jsxRuntimeExports.jsx(Text$2,{type:"secondary",className:styles$k_plainTitle,children:title2}),jsxRuntimeExports.jsx(Text$2,{className:styles$k_codeToggle,onClick:()=>setCollapsed(c=>!c),children:t(collapsed?"ui.expand":"ui.collapse")})]}),!collapsed&&jsxRuntimeExports.jsx("div",{className:`chat-md ${styles$k_markdownBody}`,dangerouslySetInnerHTML:{__html:renderMarkdown(displayText)}})]}):jsxRuntimeExports.jsxs("div",{className:styles$k_plainResult,children:[jsxRuntimeExports.jsxs("div",{className:styles$k_codeHeader,children:[jsxRuntimeExports.jsx(Text$2,{type:"secondary",className:styles$k_plainTitle,children:title2}),jsxRuntimeExports.jsx(Text$2,{className:styles$k_codeToggle,onClick:()=>setCollapsed(c=>!c),children:t(collapsed?"ui.expand":"ui.collapse")})]}),!collapsed&&jsxRuntimeExports.jsx("pre",{className:styles$k_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$k_codeResult}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$k_codeHeader,children:[jsxRuntimeExports.jsxs(Text$2,{className:styles$k_codeTitle,children:[title2,lang?` (${lang})`:""]}),jsxRuntimeExports.jsx(Text$2,{className:styles$k_codeToggle,onClick:()=>setCollapsed(c=>!c),children:t(collapsed?"ui.expand":"ui.collapse")})]}),!collapsed&&jsxRuntimeExports.jsx("pre",{className:`code-highlight ${styles$k_codePre}`,dangerouslySetInnerHTML:{__html:highlighted}})]})}const styles$j={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$j.imageArea))&&doClose()}touchRef.current=null}},[doClose]),handleOverlayClick=reactExports.useCallback(e=>{(e.target===overlayRef.current||e.target.classList.contains(styles$j.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$j.overlay,dragging2&&styles$j.dragging,closing2&&styles$j.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$j.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$j.imageArea,children:error2?jsxRuntimeExports.jsx("div",{className:styles$j.errorMsg,children:"Failed to load image"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[!loaded&&jsxRuntimeExports.jsx("div",{className:styles$j.spinner}),jsxRuntimeExports.jsx("img",{ref:imgRef,className:styles$j.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$j.zoomLabel,children:[Math.round(100*zoom),"%"]})]});return ReactDOM.createPortal(content2,document.body)}const defaultAvatarUrl="/assets/default-avatar-CT9tlZjd.svg",{Text:Text$1}=Typography;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$m_chatImageFallback,children:fallbackText}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("img",{src:src,alt:alt,className:styles$m_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$m_avatar,style:{background:modelInfo.color||"var(--bg-model-avatar)"},dangerouslySetInnerHTML:{__html:svgSource}}):jsxRuntimeExports.jsx("img",{src:"/assets/default-model-avatar-DlbUPjyv.svg",className:styles$m_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$m_viewRequestIcon,title:t("ui.viewRequest"),onClick:e=>{e.stopPropagation(),onViewRequest(requestIndex)},children:jsxRuntimeExports.jsx(ViewRequestIcon,{})}):jsxRuntimeExports.jsx("span",{className:styles$m_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$m_labelRow,children:[jsxRuntimeExports.jsxs(Text$1,{type:"secondary",className:styles$m_labelText,children:[name,extra||""]}),jsxRuntimeExports.jsxs("span",{className:styles$m_labelRight,children:[viewBtn,showCache&&jsxRuntimeExports.jsx(Text$1,{className:styles$m_cacheContextText,title:t("ui.cacheContextTooltip",{value:cacheStr}),children:`[${cacheStr}]`}),timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$m_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.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){if(!ts)return null;try{const d=new Date(ts),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$m_viewRequestBtn,onClick:e=>{e.stopPropagation(),onViewRequest(requestIndex)},children:t("ui.viewRequest")}):jsxRuntimeExports.jsx("span",{className:styles$m_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$m_labelRow,children:[jsxRuntimeExports.jsxs(Text$1,{type:"secondary",className:styles$m_labelText,children:[name,extra||""]}),jsxRuntimeExports.jsxs("span",{className:styles$m_labelRight,children:[this.renderViewRequestBtn(),timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$m_timeText,children:timeStr})]})]})}renderModelAvatar(modelInfo){return(null==modelInfo?void 0:modelInfo.svg)?jsxRuntimeExports.jsx("div",{className:styles$m_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$m_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$m_avatarImg,alt:userProfile.name||"User",onError:e=>{e.target.onerror=null,e.target.src=defaultAvatarUrl}}):jsxRuntimeExports.jsx("img",{src:defaultAvatarUrl,className:styles$m_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$m_systemTagLabel,children:seg.tag}),children:jsxRuntimeExports.jsx("pre",{className:styles$m_systemTagPre,children:seg.content})}],className:styles$m_collapseMargin},i):jsxRuntimeExports.jsx(MarkdownBlock$1,{text:seg.content,trailingCursor:i===lastMdIdx},i))}renderToolCall(tu){var _a,_b;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$m_toolBox,children:[jsxRuntimeExports.jsx(Text$1,{strong:!0,className:styles$m_toolLabel,children:label2}),children]},tu.id),codePre2=text=>jsxRuntimeExports.jsx("pre",{className:styles$m_codePre,children:text}),onOpenFile=this.props.onOpenFile,pathTag2=p=>onOpenFile?jsxRuntimeExports.jsx("span",{className:styles$m_pathTagClickable,onClick:e=>{e.stopPropagation(),onOpenFile(p)},children:p}):jsxRuntimeExports.jsx("span",{className:styles$m_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$m_toolBox,children:[jsxRuntimeExports.jsxs(Text$1,{strong:!0,className:styles$m_toolLabel,children:["Bash",desc?jsxRuntimeExports.jsxs("span",{className:styles$m_descSpan,children:[" — ",desc]}):""]}),jsxRuntimeExports.jsx(Collapse,{ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsxs(Text$1,{type:"secondary",className:styles$m_bashCollapseLabel,children:[t("ui.bashCommand")," (",lineCount," ",t("ui.lines"),")"]}),children:codePre2(cmd)}],className:styles$m_collapseMargin})]},tu.id):box(jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["Bash",desc?jsxRuntimeExports.jsxs("span",{className:styles$m_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$m_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$m_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$m_patternSpan,children:pattern}),path?jsxRuntimeExports.jsxs("span",{className:styles$m_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$m_patternSpan,children:["/",pattern,"/"]}),path?jsxRuntimeExports.jsxs("span",{className:styles$m_secondarySpan,children:[" in ",path]}):"",jsxRuntimeExports.jsx("span",{className:styles$m_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}=this.props,selectedAnswers=(null==askAnswerMap?void 0:askAnswerMap[tu.id])||{},isRejected=!0===selectedAnswers.__rejected__,hasAnswers=!isRejected&&Object.keys(selectedAnswers).length>0;if(!hasAnswers&&!isRejected&&this.props.onAskQuestionSubmit&&tu.id===this.props.lastPendingAskId)return this.renderAskQuestionInteractive(tu.id,questions);const checkSvg=jsxRuntimeExports.jsx("svg",{className:styles$m_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.jsx("div",{className:styles$m_askQuestionBox,children: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$m_questionSpacing:void 0,children:[q.header&&jsxRuntimeExports.jsx("span",{className:styles$m_askQuestionHeader,children:q.header}),jsxRuntimeExports.jsx("div",{className:styles$m_askQuestionText,children:q.question}),jsxRuntimeExports.jsxs("div",{className:styles$m_optionList,children:[q.options&&q.options.map((opt,oi)=>{const selected=isOptionMatch(opt.label);return jsxRuntimeExports.jsxs("div",{className:`${styles$m_askOptionItem}${selected?" "+styles$m_askOptionSelected:""}`,children:[jsxRuntimeExports.jsx("span",{className:styles$m_askRadioDot,children:selected?checkSvg:"○"}),jsxRuntimeExports.jsxs("span",{className:styles$m_askOptionBody,children:[jsxRuntimeExports.jsx("span",{className:styles$m_askOptionLabel,children:opt.label}),opt.description&&jsxRuntimeExports.jsx("span",{className:styles$m_askOptionDesc,children:opt.description})]})]},oi)}),isOtherAnswer&&jsxRuntimeExports.jsxs("div",{className:`${styles$m_askOptionItem} ${styles$m_askOptionSelected}`,children:[jsxRuntimeExports.jsx("span",{className:styles$m_askRadioDot,children:checkSvg}),jsxRuntimeExports.jsx("span",{className:styles$m_askOptionBody,children:jsxRuntimeExports.jsx("span",{className:styles$m_askOptionLabel,children:answer})})]})]})]},qi)})},tu.id)}if("EnterPlanMode"===tu.name)return jsxRuntimeExports.jsx("div",{className:styles$m_planModeBox,children:jsxRuntimeExports.jsx("span",{className:styles$m_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==(_a=b.input)?void 0:_a.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$m_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==(_b=null==detectedPrompt?void 0:detectedPrompt.options)?void 0:_b.length)?detectedPrompt.options:defaultPlanOptions,statusClass="approved"===approval.status?styles$m_planStatusApproved:"rejected"===approval.status?styles$m_planStatusRejected:"ultraplan"===approval.status?styles$m_planStatusApproved:styles$m_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$m_planModeBox} ${statusClass}`,children:[isInteractive&&jsxRuntimeExports.jsx("svg",{className:`${styles$m_borderSvg} ${styles$m_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$m_borderRect})}),jsxRuntimeExports.jsxs("div",{className:styles$m_planModeHeader,children:[jsxRuntimeExports.jsx("span",{className:styles$m_planModeLabel,children:t(isPending?"ui.exitPlanMode":"ui.exitPlanModeResolved")}),!isInteractive&&jsxRuntimeExports.jsxs("span",{className:`${styles$m_planStatusBadge} ${statusClass}`,children:[statusIcon," ",t(statusKey)]})]}),isPending&&planTextContent&&jsxRuntimeExports.jsx("div",{className:styles$m_planContentPreview,children:jsxRuntimeExports.jsx(MarkdownBlock$1,{text:planTextContent})}),prompts.length>0&&jsxRuntimeExports.jsxs("div",{className:styles$m_planModePermissions,children:[jsxRuntimeExports.jsx("div",{className:styles$m_planModePermLabel,children:t("ui.allowedPrompts")}),prompts.map((p,pi)=>jsxRuntimeExports.jsxs("div",{className:styles$m_askOptionItem,children:["• ",p.prompt||p.tool]},pi))]}),isInteractive&&!this.state.planFeedbackInput&&jsxRuntimeExports.jsx("div",{className:styles$m_planApprovalActions,children:this.state.planApprovalSubmitting?jsxRuntimeExports.jsx("button",{className:styles$m_planOptionBtn,disabled:!0,children:t("ui.askSubmitting")}):planOptions.map((opt,optIdx)=>{const txt=(opt.text||"").toLowerCase();let btnCls=styles$m_planOptionBtn;/yes|approve|accept|proceed/i.test(txt)||null==detectedPrompt&&0===optIdx?btnCls=styles$m_planApproveBtn:(/no|reject|deny|feedback/i.test(txt)||null==detectedPrompt&&2===optIdx)&&(btnCls=styles$m_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$m_planFeedbackInputWrap,children:[jsxRuntimeExports.jsx("textarea",{className:styles$m_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$m_planFeedbackBtnRow,children:[jsxRuntimeExports.jsx("button",{className:styles$m_planFeedbackCancelBtn,onClick:()=>this.setState({planFeedbackInput:!1,planFeedbackText:"",planFeedbackOptNumber:null}),children:t("ui.cancel")}),jsxRuntimeExports.jsx("button",{className:styles$m_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$m_planFeedback,children:[jsxRuntimeExports.jsxs("span",{className:styles$m_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$m_teammateStatusRow,children:jsxRuntimeExports.jsx("span",{className:styles$m_teammateStatusBubble,children:display})},tu.id)}if("string"==typeof msg){const header2=inp.summary?`→ ${to} — ${inp.summary}`:`→ ${to}`;return jsxRuntimeExports.jsxs("div",{className:styles$m_sendMessageBlock,children:[jsxRuntimeExports.jsx("div",{className:styles$m_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$m_kvItem,children:[jsxRuntimeExports.jsxs("span",{className:styles$m_kvKey,children:[k,": "]}),jsxRuntimeExports.jsx("span",{className:styles$m_kvValue,children:display})]},k)});return box(toolLabel2,jsxRuntimeExports.jsx("div",{className:styles$m_kvContainer,children:items}))}renderDangerApproval(toolId,dangerPrompt){if(!dangerPrompt)return null;const options=dangerPrompt.options||[];return jsxRuntimeExports.jsxs("div",{className:styles$m_dangerApprovalBox,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_dangerApprovalHeader,children:[jsxRuntimeExports.jsx("span",{className:styles$m_dangerApprovalIcon,children:"⚠"}),jsxRuntimeExports.jsx("span",{className:styles$m_dangerApprovalLabel,children:t("ui.dangerApproval")})]}),jsxRuntimeExports.jsx("div",{className:styles$m_dangerApprovalActions,children:options.map(opt=>{const txt=(opt.text||"").toLowerCase();let btnCls=styles$m_dangerOptionBtn;return/^no/i.test(txt)||/deny/i.test(txt)?btnCls=styles$m_dangerRejectBtn:(/^yes/i.test(txt)||/allow/i.test(txt))&&(btnCls=styles$m_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$m_bubbleHighlight:""}${"fading"===highlight2?" "+styles$m_bubbleHighlightFading:""}`,isUser=bubbleClass===styles$m_bubbleUser;return jsxRuntimeExports.jsxs("div",{className:`${cls} ${styles$m_bubbleRelative}`,children:[("active"===highlight2||"fading"===highlight2)&&jsxRuntimeExports.jsx("svg",{className:`${styles$m_borderSvg}${"fading"===highlight2?" "+styles$m_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$m_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$m_messageRowEnd,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_contentColLimited,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_labelRow,children:[timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$m_timeTextNoMargin,children:timeStr}),this.renderViewRequestBtn(),jsxRuntimeExports.jsxs(Text$1,{type:"secondary",className:styles$m_labelTextRight,children:[userName," — /compact"]})]}),this.renderHighlightBubble(styles$m_bubbleUser,jsxRuntimeExports.jsx(Collapse,{ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsx(Text$1,{className:styles$m_compactLabel,children:"Compact Summary"}),children:jsxRuntimeExports.jsx("pre",{className:styles$m_compactPre,children:text})}],className:styles$m_collapseNoMargin}))]}),this.renderUserAvatar("#1e40af")]}):jsxRuntimeExports.jsxs("div",{className:styles$m_messageRowEnd,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_contentColLimited,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_labelRow,children:[timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$m_timeTextNoMargin,children:timeStr}),this.renderViewRequestBtn(),jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$m_labelTextRight,children:userName})]}),this.renderHighlightBubble(styles$m_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$m_thinkingLabel,children:t("ui.thinking")}),children:isEmpty?jsxRuntimeExports.jsxs("div",{className:styles$m_thinkingEmptyHint,children:[jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$m_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$m_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$m_collapseMargin}${showTC?" "+styles$m_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$m_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$m_simplifiedToolPopoverContent,children:this.renderToolCall(tu)}),mouseEnterDelay:.3,...isMobile&&!isPad?{trigger:"click",...!isIOS&&{getPopupContainer:node=>node.parentElement}}:{},children:jsxRuntimeExports.jsx("span",{className:styles$m_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$m_ultraplanBadge,children:"◇ UltraPlan"}):jsxRuntimeExports.jsxs("div",{className:`${styles$m_dangerApprovalBox} ${styles$m_dangerApprovalBoxDenied}`,children:[jsxRuntimeExports.jsxs("span",{className:styles$m_dangerDeniedBadge,children:["✗ ",t("ui.dangerDenied")]}),tr.resultText&&jsxRuntimeExports.jsx("div",{className:styles$m_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$m_ultraplanBadge,children:"◇ UltraPlan"}):jsxRuntimeExports.jsxs("div",{className:`${styles$m_dangerApprovalBox} ${styles$m_dangerApprovalBoxDenied}`,children:[jsxRuntimeExports.jsxs("span",{className:styles$m_dangerDeniedBadge,children:["✗ ",t("ui.dangerDenied")]}),tr.resultText&&jsxRuntimeExports.jsx("div",{className:styles$m_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$m_messageRow,children:[jsxRuntimeExports.jsx(ModelAvatar,{modelInfo:modelInfo,streaming:!!showTrailingCursor}),jsxRuntimeExports.jsxs("div",{className:styles$m_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$m_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$m_messageRowEnd,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_contentColLimited,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_labelRowEnd,children:[showCache&&jsxRuntimeExports.jsx(Text$1,{className:styles$m_cacheContextText,title:t("ui.cacheContextTooltip",{value:cacheStr}),children:`[${cacheStr}]`}),this.formatTime(this.props.timestamp)&&jsxRuntimeExports.jsx(Text$1,{className:styles$m_timeText,children:this.formatTime(this.props.timestamp)}),this.renderViewRequestBtn(),jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$m_labelTextRight,children:label2||"SubAgent"})]}),this.renderHighlightBubble(styles$m_bubbleAssistant,innerContent)]}),(()=>{const ta=this.props.isTeammate?getTeammateAvatar(label2):null;return jsxRuntimeExports.jsx("div",{className:styles$m_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$m_messageRow,children:[jsxRuntimeExports.jsx("div",{className:styles$m_avatar,style:{background:tmAvatar?tmAvatar.color:"var(--bg-sub-avatar)"},dangerouslySetInnerHTML:{__html:tmAvatar?tmAvatar.svg:getSvgAvatar(this._getSubAvatarType())}}),jsxRuntimeExports.jsxs("div",{className:styles$m_contentCol,children:[this.renderLabel(label2),jsxRuntimeExports.jsx("div",{className:styles$m_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$m_messageRowEnd,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_contentColLimited,children:[jsxRuntimeExports.jsxs("div",{className:styles$m_labelRowEnd,children:[timeStr&&jsxRuntimeExports.jsx(Text$1,{className:styles$m_timeText,children:timeStr}),this.renderViewRequestBtn(),jsxRuntimeExports.jsx(Text$1,{type:"secondary",className:styles$m_labelTextRight,children:label2||"Teammate"})]}),this.renderHighlightBubble(styles$m_bubbleAssistant,jsxRuntimeExports.jsx(MarkdownBlock$1,{text:text||""}))]}),jsxRuntimeExports.jsx("div",{className:styles$m_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$m_teammateStatusRowCenter,children:jsxRuntimeExports.jsx("span",{className:styles$m_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$m_messageRow,children:[this.renderModelAvatar(modelInfo),jsxRuntimeExports.jsxs("div",{className:styles$m_contentColLimited,children:[this.renderLabel((null==modelInfo?void 0:modelInfo.name)||"MainAgent"," (Plan)"),jsxRuntimeExports.jsx("div",{className:styles$m_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$m_messageRow,children:[jsxRuntimeExports.jsx("div",{className:styles$m_skillSpacer}),jsxRuntimeExports.jsx("div",{className:styles$m_contentCol,children:jsxRuntimeExports.jsx(Collapse,{ghost:!0,size:"small",items:[{key:"1",label:jsxRuntimeExports.jsxs("span",{className:styles$m_skillLabel,children:["📦 ",t("ui.skillLoaded"),": ",skillName,timeStr&&jsxRuntimeExports.jsx(Text$1,{className:`${styles$m_timeTextNoMargin} ${styles$m_skillTimeIndent}`,children:timeStr})]}),children:jsxRuntimeExports.jsx(MarkdownBlock$1,{text:text})}],className:styles$m_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$m_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$m_messageRow,children:[this.renderModelAvatar(modelInfo),jsxRuntimeExports.jsxs("div",{className:styles$m_contentCol,children:[this.renderLabel((null==modelInfo?void 0:modelInfo.name)||"MainAgent"),this.renderHighlightBubble(styles$m_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$i_terminalPanel="_terminalPanel_1pg6e_1",styles$i_terminalContainer="_terminalContainer_1pg6e_4",styles$i_terminalHost="_terminalHost_1pg6e_23",styles$i_terminalContainerFocused="_terminalContainerFocused_1pg6e_43",styles$i_pendingFileStrip="_pendingFileStrip_1pg6e_59",styles$i_pendingFileTag="_pendingFileTag_1pg6e_67",styles$i_pendingFileName="_pendingFileName_1pg6e_84",styles$i_pendingFileClose="_pendingFileClose_1pg6e_91",styles$i_pendingImageItem="_pendingImageItem_1pg6e_105",styles$i_pendingImageThumb="_pendingImageThumb_1pg6e_120",styles$i_pendingImageRemove="_pendingImageRemove_1pg6e_127",styles$i_terminalToolbar="_terminalToolbar_1pg6e_162",styles$i_toolbarBtn="_toolbarBtn_1pg6e_177",styles$i_toolbarBtnDisabled="_toolbarBtnDisabled_1pg6e_198",styles$i_virtualKeybar="_virtualKeybar_1pg6e_213",styles$i_virtualKey="_virtualKey_1pg6e_213",styles$i_virtualKeyPressed="_virtualKeyPressed_1pg6e_244",styles$i_vkSeparator="_vkSeparator_1pg6e_251",styles$i_vkAction="_vkAction_1pg6e_260",styles$i_vkTeamLabel="_vkTeamLabel_1pg6e_272",styles$i_vkTeamPreset="_vkTeamPreset_1pg6e_281",styles$i_vkDisabled="_vkDisabled_1pg6e_286",styles$i_presetList="_presetList_1pg6e_292",styles$i_presetRow="_presetRow_1pg6e_300",styles$i_presetRowDragging="_presetRowDragging_1pg6e_312",styles$i_presetRowDragOver="_presetRowDragOver_1pg6e_316",styles$i_dragHandle="_dragHandle_1pg6e_321",styles$i_presetText="_presetText_1pg6e_339",styles$i_presetMenu="_presetMenu_1pg6e_349",styles$i_presetMenuItem="_presetMenuItem_1pg6e_354",styles$i_presetMenuItemMuted="_presetMenuItemMuted_1pg6e_373",styles$i_presetName="_presetName_1pg6e_392",styles$i_presetInput="_presetInput_1pg6e_402",styles$i_presetTextarea="_presetTextarea_1pg6e_418",styles$i_hiddenFileInput="_hiddenFileInput_1pg6e_435",styles$i_popoverEmptyHint="_popoverEmptyHint_1pg6e_439",styles$i_agentTeamDisabledTip="_agentTeamDisabledTip_1pg6e_446",styles$i_toolbarBtnRight="_toolbarBtnRight_1pg6e_452",styles$i_toolbarBtnActive="_toolbarBtnActive_1pg6e_456",styles$i_scratchWrap="_scratchWrap_1pg6e_470",styles$i_scratchTabs="_scratchTabs_1pg6e_468",styles$i_scratchTab="_scratchTab_1pg6e_468",styles$i_scratchTabActive="_scratchTabActive_1pg6e_509",styles$i_scratchTabIcon="_scratchTabIcon_1pg6e_517",styles$i_scratchTabLabel="_scratchTabLabel_1pg6e_526",styles$i_scratchTabClose="_scratchTabClose_1pg6e_533",styles$i_scratchTabAdd="_scratchTabAdd_1pg6e_564",styles$i_scratchPanes="_scratchPanes_1pg6e_468",styles$i_scratchPanesFocused="_scratchPanesFocused_1pg6e_601",styles$i_scratchPane="_scratchPane_1pg6e_468",styles$i_scratchPaneActive="_scratchPaneActive_1pg6e_615",styles$i_scratchResizer="_scratchResizer_1pg6e_621",styles$i_scratchResizerDragging="_scratchResizerDragging_1pg6e_634",styles$i_scratchInner="_scratchInner_1pg6e_35",styles$i_scratchHost="_scratchHost_1pg6e_35",styles$i_presetSectionHeader="_presetSectionHeader_1pg6e_681",styles$i_presetSectionTitle="_presetSectionTitle_1pg6e_685",styles$i_presetListEmptyHint="_presetListEmptyHint_1pg6e_691",styles$i_presetActions="_presetActions_1pg6e_698",styles$i_presetFormField="_presetFormField_1pg6e_704",styles$i_presetFormLabel="_presetFormLabel_1pg6e_708",styles$i_ultraplanPanel="_ultraplanPanel_1pg6e_716",styles$i_ultraplanHeader="_ultraplanHeader_1pg6e_722",styles$i_ultraplanHeaderTitle="_ultraplanHeaderTitle_1pg6e_733",styles$i_ultraplanCloseBtn="_ultraplanCloseBtn_1pg6e_739",styles$i_ultraplanCustomWrap="_ultraplanCustomWrap_1pg6e_758",styles$i_ultraplanCustomTitle="_ultraplanCustomTitle_1pg6e_764",styles$i_ultraplanEditPencil="_ultraplanEditPencil_1pg6e_771",styles$i_ultraplanVariantRow="_ultraplanVariantRow_1pg6e_802",styles$i_ultraplanRoleBtn="_ultraplanRoleBtn_1pg6e_810",styles$i_ultraplanAddExpertBtn="_ultraplanAddExpertBtn_1pg6e_835",styles$i_ultraplanRoleBtnActive="_ultraplanRoleBtnActive_1pg6e_858",styles$i_ultraplanContextWarning="_ultraplanContextWarning_1pg6e_867",styles$i_ultraplanTextarea="_ultraplanTextarea_1pg6e_878",styles$i_ultraplanFooter="_ultraplanFooter_1pg6e_902",styles$i_ultraplanSendBtn="_ultraplanSendBtn_1pg6e_909",styles$i_ultraplanUploadBtn="_ultraplanUploadBtn_1pg6e_931",styles$i_ultraplanFileList="_ultraplanFileList_1pg6e_953",styles$i_ultraplanFileChip="_ultraplanFileChip_1pg6e_960",styles$i_ultraplanFileName="_ultraplanFileName_1pg6e_983",styles$i_ultraplanFileRemove="_ultraplanFileRemove_1pg6e_990",styles$i_ultraplanImageItem="_ultraplanImageItem_1pg6e_1003",styles$i_ultraplanImageThumb="_ultraplanImageThumb_1pg6e_1018",styles$i_ultraplanImageRemove="_ultraplanImageRemove_1pg6e_1025",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$h_helpBtn="_helpBtn_19lpl_1",styles$h_modalBody="_modalBody_19lpl_25",styles$h_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$h_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$h_spinWrap,children:jsxRuntimeExports.jsx(Spin,{})}):jsxRuntimeExports.jsx("div",{className:styles$h_modalBody,dangerouslySetInnerHTML:{__html:html}})})]})}const styles$g={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$g.footer,children:[jsxRuntimeExports.jsx("div",{className:styles$g.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$g.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$g.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$g.field,children:jsxRuntimeExports.jsx("input",{className:styles$g.titleInput,placeholder:t("ui.ultraplan.customTitlePlaceholder"),value:title2,maxLength:30,onChange:e=>setTitle(e.target.value),autoFocus:!0})}),jsxRuntimeExports.jsx("div",{className:styles$g.field,children:jsxRuntimeExports.jsx("textarea",{className:styles$g.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$i_scratchInner,children:jsxRuntimeExports.jsx("div",{ref:this.containerRef,className:styles$i_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$i_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$i_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$i_terminalPanel,children:[jsxRuntimeExports.jsx("div",{className:`${styles$i_terminalContainer}${this.state.terminalFocused?` ${styles$i_terminalContainerFocused}`:""}`,children:jsxRuntimeExports.jsx("div",{ref:this.containerRef,className:styles$i_terminalHost})}),(null==pendingImages?void 0:pendingImages.length)>0&&jsxRuntimeExports.jsx("div",{className:styles$i_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$i_pendingImageItem,children:[jsxRuntimeExports.jsx("img",{src:src,className:styles$i_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$i_pendingImageRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},img.path):jsxRuntimeExports.jsxs("span",{className:styles$i_pendingFileTag,children:[jsxRuntimeExports.jsx("span",{className:styles$i_pendingFileName,children:fileName2}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveFile"),onConfirm:()=>null==onRemovePendingImage?void 0:onRemovePendingImage(i),className:styles$i_pendingFileClose,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},img.path)})}),jsxRuntimeExports.jsx("input",{type:"file",ref:this.fileInputRef,className:styles$i_hiddenFileInput,onChange:this.handleFileUpload}),(!isMobile||isPad)&&jsxRuntimeExports.jsxs("div",{className:styles$i_terminalToolbar,children:[jsxRuntimeExports.jsxs("button",{className:styles$i_toolbarBtn,onClick:()=>{var _a;return null==(_a=this.fileInputRef.current)?void 0:_a.click()},title:t("ui.terminal.upload"),children:[jsxRuntimeExports.jsx(UploadIcon,{}),jsxRuntimeExports.jsx("span",{children:t("ui.terminal.upload")})]}),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$i_presetMenu,children:[jsxRuntimeExports.jsx("button",{className:`${styles$i_presetMenuItem} ${styles$i_presetMenuItemMuted}`,onClick:()=>{this.setState({agentTeamPopoverOpen:!1,presetModalVisible:!0})},children:t("ui.terminal.customShortcuts")}),0===this.state.presetItems.length?jsxRuntimeExports.jsx("div",{className:styles$i_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$i_presetMenuItem,onClick:()=>this.handlePresetSend(desc),title:desc,children:name||desc},item.id)})]}),children:jsxRuntimeExports.jsxs("button",{className:styles$i_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$i_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$i_toolbarBtn} ${styles$i_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$i_ultraplanPanel,children:[jsxRuntimeExports.jsxs("div",{className:styles$i_ultraplanHeader,children:[jsxRuntimeExports.jsxs("span",{className:styles$i_ultraplanHeaderTitle,children:[t("ui.ultraplan.title"),jsxRuntimeExports.jsx(ConceptHelp,{doc:"UltraPlan",zIndex:1100})]}),jsxRuntimeExports.jsx("button",{type:"button",className:styles$i_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$i_ultraplanVariantRow,children:[jsxRuntimeExports.jsxs("button",{className:`${styles$i_ultraplanRoleBtn} ${"codeExpert"===this.state.ultraplanVariant?styles$i_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$i_ultraplanRoleBtn} ${"researchExpert"===this.state.ultraplanVariant?styles$i_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$i_ultraplanCustomWrap,children:[jsxRuntimeExports.jsxs("button",{className:`${styles$i_ultraplanRoleBtn} ${this.state.ultraplanVariant===vkey?styles$i_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$i_ultraplanCustomTitle,children:item.title})]}),jsxRuntimeExports.jsx("span",{className:styles$i_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$i_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.props.modelName||getModelMaxTokens(this.props.modelName)<1e6)&&jsxRuntimeExports.jsx("div",{className:styles$i_ultraplanContextWarning,children:t("ui.ultraplan.contextWarning")}),this.state.ultraplanFiles.length>0&&jsxRuntimeExports.jsx("div",{className:styles$i_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$i_ultraplanImageItem,title:f.name,children:[jsxRuntimeExports.jsx("img",{src:src,className:styles$i_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$i_ultraplanImageRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},i):jsxRuntimeExports.jsxs("span",{className:styles$i_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$i_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$i_ultraplanFileRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},i)})}),jsxRuntimeExports.jsx("textarea",{className:styles$i_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$i_ultraplanFooter,children:[jsxRuntimeExports.jsx("button",{className:styles$i_ultraplanSendBtn,disabled:!this.state.ultraplanPrompt.trim()&&0===this.state.ultraplanFiles.length,onClick:this.handleUltraplanSend,children:t("ui.ultraplan.send")}),jsxRuntimeExports.jsxs("button",{className:styles$i_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$i_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$i_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$i_toolbarBtn} ${styles$i_toolbarBtnDisabled}`,title:t("ui.ultraplan"),children:[jsxRuntimeExports.jsx(UltraplanIcon,{}),jsxRuntimeExports.jsx("span",{children:"UltraPlan"})]})}),(()=>{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.jsxs("button",{className:styles$i_toolbarBtn,title:t("ui.chatInput.clearContext"),children:[jsxRuntimeExports.jsx(TrashIcon,{}),jsxRuntimeExports.jsx("span",{children:t("ui.chatInput.clearContext")})]})})})(),jsxRuntimeExports.jsx("button",{className:`${styles$i_toolbarBtn} ${styles$i_toolbarBtnRight}${this.state.scratchOpen?` ${styles$i_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$i_scratchResizer}${this.state.isDraggingScratch?` ${styles$i_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$i_scratchWrap,children:[jsxRuntimeExports.jsxs("div",{className:styles$i_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$i_scratchTab}${isActive?` ${styles$i_scratchTabActive}`:""}`,onClick:()=>this.handleScratchTabClick(tab.id),title:label2,children:[jsxRuntimeExports.jsx("span",{className:styles$i_scratchTabIcon,children:jsxRuntimeExports.jsx(ScratchTerminalIcon,{})}),jsxRuntimeExports.jsx("span",{className:styles$i_scratchTabLabel,children:label2}),!isLast&&jsxRuntimeExports.jsx("button",{className:styles$i_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$i_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$i_scratchPanes}${this.state.scratchFocused?` ${styles$i_scratchPanesFocused}`:""}`,children:this.state.scratchTabs.map(tab=>{const isActive=tab.id===this.state.activeScratchTabId;return jsxRuntimeExports.jsx("div",{className:`${styles$i_scratchPane}${isActive?` ${styles$i_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$i_virtualKeybar,children:[VIRTUAL_KEYS.map(k=>jsxRuntimeExports.jsx("button",{className:styles$i_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$i_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$i_virtualKey} ${styles$i_vkAction} ${styles$i_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$i_vkTeamLabel,children:name||desc})]},item.id)})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:styles$i_vkSeparator}),jsxRuntimeExports.jsxs("button",{className:`${styles$i_virtualKey} ${styles$i_vkAction} ${styles$i_vkDisabled}`,onTouchStart:this._vkTouchStart,onTouchMove:this._vkTouchMove,onTouchEnd:e=>this._vkTouchEnd(()=>this.handleEnableAgentTeam(),e),children:[jsxRuntimeExports.jsx(AgentTeamIcon,{}),jsxRuntimeExports.jsx("span",{className:styles$i_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$i_presetSectionHeader,children:jsxRuntimeExports.jsx("span",{className:styles$i_presetSectionTitle,children:t("ui.terminal.agentTeamCustom")})}),jsxRuntimeExports.jsx("div",{className:styles$i_presetList,onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:e=>{e.preventDefault(),e.stopPropagation()},children:0===this.state.presetItems.length?jsxRuntimeExports.jsx("div",{className:styles$i_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$i_presetRow} ${isDragging?styles$i_presetRowDragging:""} ${isDragOver?styles$i_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$i_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$i_presetName,title:name,children:name||"—"}),jsxRuntimeExports.jsx("span",{className:styles$i_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$i_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$i_presetFormField,children:[jsxRuntimeExports.jsxs("label",{className:styles$i_presetFormLabel,children:["Team ",t("ui.terminal.teamName")]}),jsxRuntimeExports.jsx("input",{className:styles$i_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$i_presetFormLabel,children:["Team ",t("ui.terminal.teamDesc")]}),jsxRuntimeExports.jsx("textarea",{className:styles$i_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$f_fileExplorer="_fileExplorer_11rd4_1",styles$f_header="_header_11rd4_10",styles$f_headerTitle="_headerTitle_11rd4_20",styles$f_collapseBtn="_collapseBtn_11rd4_31",styles$f_treeContainer="_treeContainer_11rd4_50",styles$f_treeItem="_treeItem_11rd4_56",styles$f_treeItemSelected="_treeItemSelected_11rd4_72",styles$f_arrow="_arrow_11rd4_76",styles$f_icon="_icon_11rd4_85",styles$f_fileName="_fileName_11rd4_95",styles$f_fileNameInput="_fileNameInput_11rd4_100",styles$f_loading="_loading_11rd4_116",styles$f_error="_error_11rd4_122",styles$f_treeItemGitIgnored="_treeItemGitIgnored_11rd4_128",styles$f_treeItemDragging="_treeItemDragging_11rd4_132",styles$f_treeItemDragOver="_treeItemDragOver_11rd4_136",styles$f_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$f_treeItem}${isSelected?" "+styles$f_treeItemSelected:""}${isGitIgnored?" "+styles$f_treeItemGitIgnored:""}${dragging2?" "+styles$f_treeItemDragging:""}${dragOver?" "+styles$f_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$f_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$f_arrowIcon,style:{transform:expanded?"rotate(90deg)":"none"},children:jsxRuntimeExports.jsx("polyline",{points:"9 6 15 12 9 18"})}):""}),jsxRuntimeExports.jsx("span",{className:styles$f_icon,children:getFileIcon(item.name,item.type)}),editing?jsxRuntimeExports.jsx("input",{ref:inputRef,className:styles$f_fileNameInput,value:editName,onChange:e=>setEditName(e.target.value),onKeyDown:handleInputKeyDown,onBlur:submitRename,onClick:e=>e.stopPropagation()}):jsxRuntimeExports.jsx("span",{className:styles$f_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$f_loading,style:{paddingLeft:24+16*depth},children:"..."}),expanded&&error2&&jsxRuntimeExports.jsx("div",{className:styles$f_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$f_fileExplorer,style:style,"data-file-explorer":!0,onDragOver:handleContainerDragOver,onDrop:handleContainerDrop,children:[jsxRuntimeExports.jsxs("div",{className:styles$f_header,children:[jsxRuntimeExports.jsx(Dropdown,{menu:{items:headerMenuItems,onClick:handleHeaderMenuClick},trigger:["contextMenu"],children:jsxRuntimeExports.jsxs("span",{className:styles$f_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$f_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$f_treeContainer,children:[error2&&jsxRuntimeExports.jsx("div",{className:styles$f_error,children:error2}),!items&&!error2&&jsxRuntimeExports.jsx("div",{className:styles$f_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$e_fileContentView="_fileContentView_16e92_1",styles$e_closing="_closing_16e92_20",styles$e_editorBanner="_editorBanner_16e92_35",styles$e_header="_header_16e92_52",styles$e_headerLeft="_headerLeft_16e92_62",styles$e_headerRight="_headerRight_16e92_70",styles$e_backBtn="_backBtn_16e92_77",styles$e_filePath="_filePath_16e92_98",styles$e_fileSize="_fileSize_16e92_106",styles$e_closeBtn="_closeBtn_16e92_113",styles$e_viewToggleBtn="_viewToggleBtn_16e92_133",styles$e_viewToggleActive="_viewToggleActive_16e92_161",styles$e_downloadWrap="_downloadWrap_16e92_167",styles$e_downloadMenu="_downloadMenu_16e92_172",styles$e_downloadMenuItem="_downloadMenuItem_16e92_185",styles$e_markdownPreview="_markdownPreview_16e92_211",styles$e_saveBtn="_saveBtn_16e92_293",styles$e_saveStatus="_saveStatus_16e92_329",styles$e_saveStatusSaved="_saveStatusSaved_16e92_335",styles$e_saveStatusFailed="_saveStatusFailed_16e92_339",styles$e_contentContainer="_contentContainer_16e92_343",styles$e_editorWrapper="_editorWrapper_16e92_352",styles$e_lineNumCol="_lineNumCol_16e92_360",styles$e_lineNumRow="_lineNumRow_16e92_370",styles$e_editorCol="_editorCol_16e92_380",styles$e_loading="_loading_16e92_400",styles$e_error="_error_16e92_410",MdxEditorPanel=reactExports.lazy(()=>__vitePreload(()=>import("./MdxEditorPanel-BNBDCv3f.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$e_lineNumRow,children:i},i));return lines},[lineCount]);return jsxRuntimeExports.jsxs("div",{ref:containerRef,className:`${styles$e_fileContentView}${closing2?` ${styles$e_closing}`:""}`,children:[editorSession&&jsxRuntimeExports.jsx("div",{className:styles$e_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$e_header,children:[jsxRuntimeExports.jsxs("div",{className:styles$e_headerLeft,children:[jsxRuntimeExports.jsx("button",{className:styles$e_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$e_filePath,children:filePath2}),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.jsxs("div",{className:styles$e_headerRight,children:[saveStatusText&&jsxRuntimeExports.jsx("span",{className:`${styles$e_saveStatus} ${"failed"===saveStatus2?styles$e_saveStatusFailed:"saved"===saveStatus2?styles$e_saveStatusSaved:""}`,children:saveStatusText}),isMdFile&&jsxRuntimeExports.jsxs("div",{className:styles$e_downloadWrap,ref:downloadWrapRef,children:[jsxRuntimeExports.jsx("button",{className:styles$e_viewToggleBtn,onClick:()=>setDownloadMenuOpen(v=>!v),title:t("ui.saveAs"),"aria-label":t("ui.saveAs"),"aria-expanded":downloadMenuOpen,children:jsxRuntimeExports.jsx(RefIcon$c,{})}),downloadMenuOpen&&jsxRuntimeExports.jsxs("div",{className:styles$e_downloadMenu,children:[jsxRuntimeExports.jsxs("button",{className:styles$e_downloadMenuItem,onClick:handleSaveAs,children:[jsxRuntimeExports.jsx(RefIcon$c,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveAsMd")})]}),jsxRuntimeExports.jsxs("button",{className:styles$e_downloadMenuItem,onClick:handleCopy,children:[jsxRuntimeExports.jsx(RefIcon$d,{}),jsxRuntimeExports.jsx("span",{children:t("ui.copyTextContent")})]}),jsxRuntimeExports.jsxs("button",{className:styles$e_downloadMenuItem,onClick:handleSaveAsImage,disabled:"markdown"!==viewMode||useMdxEditor,title:"markdown"!==viewMode?t("ui.saveAsImageHintMd"):useMdxEditor?t("ui.mdEditor.saveAsImageDisabled"):void 0,children:[jsxRuntimeExports.jsx(RefIcon$4,{}),jsxRuntimeExports.jsx("span",{children:t("ui.saveAsImage")})]})]})]}),isMdFile&&extensionDetected&&!forceMdxOverride&&mdxFeatureEnabled&&!isMobile&&jsxRuntimeExports.jsx("button",{className:styles$e_viewToggleBtn,onClick:requestForceMdx,title:t("ui.mdEditor.forceGuiEditConfirm"),children:t("ui.mdEditor.forceGuiEdit")}),isMdFile&&!useMdxEditor&&jsxRuntimeExports.jsxs("button",{className:`${styles$e_viewToggleBtn}${"markdown"===viewMode?` ${styles$e_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$e_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$e_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$e_contentContainer,children:[error2&&jsxRuntimeExports.jsx("div",{className:styles$e_error,children:error2}),loading2&&!error2&&jsxRuntimeExports.jsx("div",{className:styles$e_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$e_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$e_markdownPreview,dangerouslySetInnerHTML:{__html:renderMarkdown(isDirty?currentContent:content2)}}),!loading2&&null!==content2&&!("markdown"===viewMode&&isMdFile)&&jsxRuntimeExports.jsxs("div",{className:styles$e_editorWrapper,ref:editorWrapperRef,children:[jsxRuntimeExports.jsx("div",{className:styles$e_lineNumCol,ref:lineNumRef,children:lineNumbers}),jsxRuntimeExports.jsx("div",{className:styles$e_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 styles$d_imageViewer="_imageViewer_cvqfs_1",styles$d_header="_header_cvqfs_8",styles$d_headerLeft="_headerLeft_cvqfs_18",styles$d_headerRight="_headerRight_cvqfs_26",styles$d_backBtn="_backBtn_cvqfs_33",styles$d_closeBtn="_closeBtn_cvqfs_54",styles$d_filePath="_filePath_cvqfs_73",styles$d_fileSize="_fileSize_cvqfs_81",styles$d_toolbar="_toolbar_cvqfs_87",styles$d_toolBtn="_toolBtn_cvqfs_97",styles$d_zoomLabel="_zoomLabel_cvqfs_118",styles$d_canvasArea="_canvasArea_cvqfs_126",styles$d_dragging="_dragging_cvqfs_141",styles$d_imageWrap="_imageWrap_cvqfs_145",styles$d_svgInline="_svgInline_cvqfs_158",styles$d_statusBar="_statusBar_cvqfs_173",styles$d_loading="_loading_cvqfs_185",styles$d_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(purify.sanitize(text,{USE_PROFILES:{svg:!0}}));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$d_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$d_dragging),window.removeEventListener("mousemove",onMove),window.removeEventListener("mouseup",onUp)};window.addEventListener("mousemove",onMove),window.addEventListener("mouseup",onUp)},[offset]);return jsxRuntimeExports.jsxs("div",{className:styles$d_imageViewer,children:[jsxRuntimeExports.jsxs("div",{className:styles$d_header,children:[jsxRuntimeExports.jsxs("div",{className:styles$d_headerLeft,children:[jsxRuntimeExports.jsx("button",{className:styles$d_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$d_filePath,children:filePath2})]}),jsxRuntimeExports.jsxs("div",{className:styles$d_headerRight,children:[fileSize2>0&&jsxRuntimeExports.jsx("span",{className:styles$d_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$d_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$d_toolbar,children:[jsxRuntimeExports.jsx("button",{className:styles$d_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$d_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$d_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$d_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$d_zoomLabel,children:[Math.round(100*zoom),"%"]})]}),jsxRuntimeExports.jsxs("div",{className:styles$d_canvasArea,ref:canvasRef,onWheel:handleWheel,onMouseDown:handleMouseDown,children:[loading2&&!error2&&jsxRuntimeExports.jsx("div",{className:styles$d_loading,children:t("ui.loading")}),error2&&jsxRuntimeExports.jsx("div",{className:styles$d_error,children:error2}),jsxRuntimeExports.jsx("div",{className:styles$d_imageWrap,style:{transform:`translate(${offset.x}px, ${offset.y}px) scale(${zoom})`},children:isSvg&&svgContent?jsxRuntimeExports.jsx("div",{className:styles$d_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$d_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}]}catch{return[]}}return await Promise.all(repoList.map(async repo=>{try{const statusRes=await fetch(apiUrl(`/api/git-status?repo=${encodeURIComponent(repo.path)}`));if(!statusRes.ok)return{...repo,changes:[]};const data=await statusRes.json();return{...repo,changes:data.changes||[],insertions:data.insertions||0,deletions:data.deletions||0}}catch{return{...repo,changes:[],insertions:0,deletions:0}}}))}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$c_gitChanges="_gitChanges_obtg5_1",styles$c_header="_header_obtg5_10",styles$c_headerTitle="_headerTitle_obtg5_19",styles$c_collapseBtn="_collapseBtn_obtg5_27",styles$c_changesContainer="_changesContainer_obtg5_46",styles$c_changeItem="_changeItem_obtg5_52",styles$c_changeItemSelected="_changeItemSelected_obtg5_69",styles$c_dirItem="_dirItem_obtg5_73",styles$c_dirArrow="_dirArrow_obtg5_84",styles$c_dirName="_dirName_obtg5_93",styles$c_status="_status_obtg5_98",styles$c_icon="_icon_obtg5_107",styles$c_fileName="_fileName_obtg5_116",styles$c_actions="_actions_obtg5_122",styles$c_loading="_loading_obtg5_150",styles$c_error="_error_obtg5_156",styles$c_empty="_empty_obtg5_162",styles$c_rotated90="_rotated90_obtg5_169",styles$c_repoHeader="_repoHeader_obtg5_174",styles$c_repoArrow="_repoArrow_obtg5_193",styles$c_repoArrowExpanded="_repoArrowExpanded_obtg5_204",styles$c_repoName="_repoName_obtg5_208",styles$c_repoBadge="_repoBadge_obtg5_215",styles$c_statBadge="_statBadge_obtg5_224",styles$c_statInsert="_statInsert_obtg5_232",styles$c_statDelete="_statDelete_obtg5_236",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}){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$c_dirItem,style:{paddingLeft:8+16*depth},children:[jsxRuntimeExports.jsx("span",{className:styles$c_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$c_rotated90,children:jsxRuntimeExports.jsx("polyline",{points:"9 6 15 12 9 18"})})}),jsxRuntimeExports.jsx("span",{className:styles$c_icon,children:getFileIcon("","directory")}),jsxRuntimeExports.jsx("span",{className:styles$c_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},dir)),files.map(file=>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$c_changeItem} ${selectedFile===file.fullPath&&selectedRepo===repoPath?styles$c_changeItemSelected:""}`,style:{paddingLeft:8+16*(name?depth+1:depth)},onClick:()=>onFileClick&&onFileClick(repoPath,file.fullPath),children:[jsxRuntimeExports.jsx("span",{className:styles$c_icon,children:getFileIcon(file.name)}),jsxRuntimeExports.jsx("span",{className:styles$c_fileName,children:file.name}),jsxRuntimeExports.jsxs("span",{className:styles$c_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"})]})}),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$c_status,style:{color:STATUS_COLORS[file.status]||"#888"},children:STATUS_LABELS[file.status]||file.status})]})},file.fullPath))]})}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),[collapsedRepos,setCollapsedRepos]=reactExports.useState(new Set),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]);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$c_gitChanges,style:style,children:[jsxRuntimeExports.jsxs("div",{className:styles$c_header,children:[jsxRuntimeExports.jsxs("span",{className:styles$c_headerTitle,children:[t("ui.gitChanges"),(totalInsertions>0||totalDeletions>0)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ",jsxRuntimeExports.jsxs("span",{className:`${styles$c_statBadge} ${styles$c_statInsert}`,children:["+",totalInsertions]})," ",jsxRuntimeExports.jsxs("span",{className:`${styles$c_statBadge} ${styles$c_statDelete}`,children:["-",totalDeletions]})]})]}),jsxRuntimeExports.jsx("button",{className:styles$c_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$c_changesContainer,children:[loading2&&jsxRuntimeExports.jsx("div",{className:styles$c_loading,children:"Loading..."}),error2&&jsxRuntimeExports.jsx("div",{className:styles$c_error,children:error2}),!loading2&&!error2&&(!repos||0===repos.length)&&jsxRuntimeExports.jsx("div",{className:styles$c_empty,children:"No changes"}),!loading2&&!error2&&repos&&repos.map(repo=>{const collapsed=collapsedRepos.has(repo.path);return isSingleRepo?jsxRuntimeExports.jsx(TreeDir,{name:"",node:buildGitTree(repo.changes),depth:0,repoPath:repo.path,onFileClick:(rp,fp)=>{setSelectedFile(fp),setSelectedRepo(rp),onFileClick&&onFileClick(rp,fp)},onOpenFile:onOpenFile,onRestore:handleRestore,selectedFile:selectedFile,selectedRepo:selectedRepo},repo.path):jsxRuntimeExports.jsxs(React__default.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:styles$c_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$c_repoArrow} ${collapsed?"":styles$c_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$c_repoName,children:repo.name}),(repo.insertions>0||repo.deletions>0)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("span",{className:`${styles$c_statBadge} ${styles$c_statInsert}`,children:["+",repo.insertions]}),jsxRuntimeExports.jsxs("span",{className:`${styles$c_statBadge} ${styles$c_statDelete}`,children:["-",repo.deletions]})]}),jsxRuntimeExports.jsx("span",{className:styles$c_repoBadge,children:repo.changes.length})]}),!collapsed&&jsxRuntimeExports.jsx(TreeDir,{name:"",node:buildGitTree(repo.changes),depth:1,repoPath:repo.path,onFileClick:(rp,fp)=>{setSelectedFile(fp),setSelectedRepo(rp),onFileClick&&onFileClick(rp,fp)},onOpenFile:onOpenFile,onRestore:handleRestore,selectedFile:selectedFile,selectedRepo:selectedRepo})]},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$b_fullFileDiffView="_fullFileDiffView_1o8kb_1",styles$b_diffSummary="_diffSummary_1o8kb_12",styles$b_addedBadge="_addedBadge_1o8kb_22",styles$b_deletedBadge="_deletedBadge_1o8kb_33",styles$b_codeContainer="_codeContainer_1o8kb_44",styles$b_lineNumberCol="_lineNumberCol_1o8kb_54",styles$b_lineNumRow="_lineNumRow_1o8kb_62",styles$b_oldLineNum="_oldLineNum_1o8kb_67",styles$b_newLineNum="_newLineNum_1o8kb_68",styles$b_lineNumNormal="_lineNumNormal_1o8kb_77",styles$b_lineNumAdd="_lineNumAdd_1o8kb_82",styles$b_lineNumDelete="_lineNumDelete_1o8kb_95",styles$b_codeColWrap="_codeColWrap_1o8kb_108",styles$b_codeCol="_codeCol_1o8kb_108",styles$b_codeInner="_codeInner_1o8kb_122",styles$b_codeLine="_codeLine_1o8kb_127",styles$b_linePrefix="_linePrefix_1o8kb_138",styles$b_lineContent="_lineContent_1o8kb_147",styles$b_lineNormal="_lineNormal_1o8kb_153",styles$b_lineAdd="_lineAdd_1o8kb_157",styles$b_lineDelete="_lineDelete_1o8kb_165",styles$a_miniMap="_miniMap_1ho3j_1",styles$a_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$a_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$a_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$b_fullFileDiffView,children:[jsxRuntimeExports.jsxs("div",{className:styles$b_diffSummary,children:[addedCount>0&&jsxRuntimeExports.jsxs("span",{className:styles$b_addedBadge,children:["+",addedCount]}),deletedCount>0&&jsxRuntimeExports.jsxs("span",{className:styles$b_deletedBadge,children:["-",deletedCount]})]}),jsxRuntimeExports.jsxs("div",{className:styles$b_codeContainer,children:[jsxRuntimeExports.jsx("div",{className:styles$b_lineNumberCol,ref:lineNumScrollRef,children:highlightedDiffLines.map((dl,idx)=>{let numClass=styles$b_lineNumNormal;return"add"===dl.type?numClass=styles$b_lineNumAdd:"del"===dl.type&&(numClass=styles$b_lineNumDelete),jsxRuntimeExports.jsxs("div",{className:`${styles$b_lineNumRow} ${numClass}`,children:[jsxRuntimeExports.jsx("span",{className:styles$b_oldLineNum,children:dl.oldNum??""}),jsxRuntimeExports.jsx("span",{className:styles$b_newLineNum,children:dl.newNum??""})]},idx)})}),jsxRuntimeExports.jsxs("div",{className:styles$b_codeColWrap,children:[jsxRuntimeExports.jsx("div",{className:styles$b_codeCol,ref:codeScrollRef,children:jsxRuntimeExports.jsx("div",{className:styles$b_codeInner,children:highlightedDiffLines.map((dl,idx)=>{let lineClass;lineClass="add"===dl.type?styles$b_lineAdd:"del"===dl.type?styles$b_lineDelete:styles$b_lineNormal;const prefix2="add"===dl.type?"+":"del"===dl.type?"-":" ";return jsxRuntimeExports.jsxs("div",{className:`${styles$b_codeLine} ${lineClass}`,children:[jsxRuntimeExports.jsx("span",{className:styles$b_linePrefix,children:prefix2}),jsxRuntimeExports.jsx("span",{className:styles$b_lineContent,dangerouslySetInnerHTML:{__html:dl.html||" "}})]},idx)})})}),jsxRuntimeExports.jsx(DiffMiniMap,{diffLines:highlightedDiffLines,scrollRef:codeScrollRef})]})]})]})}const styles$9_gitDiffView="_gitDiffView_ypk84_1",styles$9_closing="_closing_ypk84_21",styles$9_header="_header_ypk84_36",styles$9_headerLeft="_headerLeft_ypk84_46",styles$9_backBtn="_backBtn_ypk84_54",styles$9_filePath="_filePath_ypk84_75",styles$9_diffBadge="_diffBadge_ypk84_91",styles$9_headerRight="_headerRight_ypk84_103",styles$9_closeBtn="_closeBtn_ypk84_109",styles$9_contentContainer="_contentContainer_ypk84_129",styles$9_loading="_loading_ypk84_135",styles$9_error="_error_ypk84_144",styles$9_binaryNotice="_binaryNotice_ypk84_155",styles$9_largeFileWarning="_largeFileWarning_ypk84_167",styles$9_fileSize="_fileSize_ypk84_180",styles$9_imagePreviewWrap="_imagePreviewWrap_ypk84_186",styles$9_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,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)}`:"";return fetch(apiUrl(`/api/git-diff?files=${encodeURIComponent(filePath2)}${repoParam}`)).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]);const resolvedPath=repoPath&&"."!==repoPath?`${repoPath}/${filePath2}`:filePath2;return jsxRuntimeExports.jsxs("div",{ref:containerRef,className:`${styles$9_gitDiffView}${closing2?` ${styles$9_closing}`:""}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$9_header,children:[jsxRuntimeExports.jsxs("div",{className:styles$9_headerLeft,children:[jsxRuntimeExports.jsx("button",{className:styles$9_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$9_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$9_diffBadge,children:"DIFF"})]}),jsxRuntimeExports.jsx("div",{className:styles$9_headerRight,children:jsxRuntimeExports.jsx("button",{className:styles$9_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$9_contentContainer,children:[loading2&&jsxRuntimeExports.jsx("div",{className:styles$9_loading,children:t("ui.loading")}),error2&&jsxRuntimeExports.jsx("div",{className:styles$9_error,children:error2}),!loading2&&!error2&&diffData&&jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:diffData.is_large?jsxRuntimeExports.jsxs("div",{className:styles$9_largeFileWarning,children:[jsxRuntimeExports.jsx("p",{children:t("ui.largeFileWarning")}),jsxRuntimeExports.jsxs("p",{className:styles$9_fileSize,children:[t("ui.fileSize"),": ",(diffData.size/1048576).toFixed(2)," MB"]})]}):isImageFile(filePath2)&&!diffData.is_deleted?jsxRuntimeExports.jsxs("div",{className:styles$9_imagePreviewWrap,children:[jsxRuntimeExports.jsx("img",{className:styles$9_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$9_binaryNotice,children:t("ui.binaryFileNotice")}):jsxRuntimeExports.jsx(FullFileDiffView,{file_path:filePath2,old_string:diffData.old_content,new_string:diffData.new_content})})]})]})}const styles$8_panel="_panel_1qfnj_1",styles$8_panelGlobal="_panelGlobal_1qfnj_20",styles$8_toolName="_toolName_1qfnj_41",styles$8_command="_command_1qfnj_45",styles$8_allowBtn="_allowBtn_1qfnj_51",styles$8_allowSessionBtn="_allowSessionBtn_1qfnj_52",styles$8_denyBtn="_denyBtn_1qfnj_53",styles$8_borderSvg="_borderSvg_1qfnj_58",styles$8_borderSvgInset="_borderSvgInset_1qfnj_67",styles$8_borderRect="_borderRect_1qfnj_71",styles$8_exiting="_exiting_1qfnj_90",styles$8_header="_header_1qfnj_94",styles$8_label="_label_1qfnj_108",styles$8_subAgentBadge="_subAgentBadge_1qfnj_115",styles$8_body="_body_1qfnj_126",styles$8_detail="_detail_1qfnj_146",styles$8_actions="_actions_1qfnj_157",styles$8_autoApproveBtn="_autoApproveBtn_1qfnj_163",styles$8_autoApproveActive="_autoApproveActive_1qfnj_181";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$8_panelGlobal:styles$8_panel}${exiting2?` ${styles$8_exiting}`:""}`,onKeyDown:handleKeyDown,children:[jsxRuntimeExports.jsx("svg",{className:`${styles$8_borderSvg} ${styles$8_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$8_borderRect})}),jsxRuntimeExports.jsxs("div",{className:styles$8_header,children:[jsxRuntimeExports.jsx("span",{className:styles$8_toolName,children:toolName2}),"pty"===source2&&jsxRuntimeExports.jsx("span",{className:styles$8_subAgentBadge,children:t("ui.subAgentApproval")}),queueDepth>0&&jsxRuntimeExports.jsx("span",{className:styles$8_subAgentBadge,children:t("ui.permission.queued",{n:queueDepth})}),jsxRuntimeExports.jsx("span",{className:styles$8_label,children:t("ui.permission.approvalRequired")})]}),jsxRuntimeExports.jsxs("div",{className:styles$8_body,children:[jsxRuntimeExports.jsx("pre",{className:styles$8_command,children:displayText}),detailText&&jsxRuntimeExports.jsx("div",{className:styles$8_detail,children:detailText})]}),jsxRuntimeExports.jsxs("div",{className:styles$8_actions,children:[onAutoApproveChange&&jsxRuntimeExports.jsx("button",{className:`${styles$8_autoApproveBtn}${autoApproveSeconds>0?` ${styles$8_autoApproveActive}`:""}`,onClick:handleAutoApproveToggle,children:autoApproveBtnLabel}),jsxRuntimeExports.jsx("button",{className:styles$8_denyBtn,onClick:()=>handleDeny(requestId),children:t("ui.permission.deny")}),onAllowSession&&jsxRuntimeExports.jsx("button",{className:styles$8_allowSessionBtn,onClick:()=>onAllowSession(requestId),children:t("ui.permission.allowSession")}),jsxRuntimeExports.jsx("button",{ref:allowRef,className:styles$8_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}$/,"")})`}const _readResultPool=new Map;function internToolResult(s){return function(s){if("string"!=typeof s||s.length<256)return s;const sig=function(s){return s.length+":"+s.slice(0,64)+":"+s.slice(-64)}(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)}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=isError&&resultText&&/doesn't want to proceed|Permission.*denied|rejected.*tool use|interrupted by user for tool use/i.test(resultText),isUltraplan=isPermissionDenied&&resultText&&/ultraplan/i.test(resultText);if(toolResultMap[block.tool_use_id]={label:label2,toolName:toolName2,toolInput:toolInput,resultText:resultText,isError:isError,isPermissionDenied:isPermissionDenied,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$7_teamActiveSpinner="_teamActiveSpinner_9y80g_1",styles$7_teamPopover="_teamPopover_9y80g_17",styles$7_teamPopoverTitle="_teamPopoverTitle_9y80g_23",styles$7_teamPopoverItem="_teamPopoverItem_9y80g_31",styles$7_teamPopoverName="_teamPopoverName_9y80g_45",styles$7_teamPopoverMeta="_teamPopoverMeta_9y80g_53",styles$7_teamPopoverTime="_teamPopoverTime_9y80g_60",styles$7_teamModalBody="_teamModalBody_9y80g_66",styles$7_teamGanttToggle="_teamGanttToggle_9y80g_76",styles$7_ganttExportBtn="_ganttExportBtn_9y80g_90",styles$7_teamGanttWrap="_teamGanttWrap_9y80g_106",styles$7_teamGanttResizer="_teamGanttResizer_9y80g_115",styles$7_teamGanttRow="_teamGanttRow_9y80g_128",styles$7_teamGanttLabel="_teamGanttLabel_9y80g_135",styles$7_teamGanttTrack="_teamGanttTrack_9y80g_147",styles$7_teamGanttBar="_teamGanttBar_9y80g_156",styles$7_teamGanttDiamond="_teamGanttDiamond_9y80g_164",styles$7_teamGanttArrows="_teamGanttArrows_9y80g_181",styles$7_teamGanttIndicator="_teamGanttIndicator_9y80g_191",styles$7_teamModalLayout="_teamModalLayout_9y80g_203",styles$7_teamAgentCards="_teamAgentCards_9y80g_208",styles$7_teamAgentCard="_teamAgentCard_9y80g_208",styles$7_teamAgentCardActive="_teamAgentCardActive_9y80g_230",styles$7_teamAgentCardHeader="_teamAgentCardHeader_9y80g_234",styles$7_teamAgentAvatar="_teamAgentAvatar_9y80g_240",styles$7_teamAgentName="_teamAgentName_9y80g_258",styles$7_teamAgentType="_teamAgentType_9y80g_267",styles$7_teamAgentStatus="_teamAgentStatus_9y80g_273",styles$7_teamAgentPopover="_teamAgentPopover_9y80g_278",styles$7_teamAgentPopTeammateMsg="_teamAgentPopTeammateMsg_9y80g_283",styles$7_teamAgentPopTmSummary="_teamAgentPopTmSummary_9y80g_291",styles$7_teamAgentPopTmContent="_teamAgentPopTmContent_9y80g_298",styles$7_teamAgentPopTask="_teamAgentPopTask_9y80g_304",styles$7_teamAgentPopMsg="_teamAgentPopMsg_9y80g_313",styles$7_teammateReportEntry="_teammateReportEntry_9y80g_326",styles$7_teammateReportHeader="_teammateReportHeader_9y80g_334",styles$7_teammateReportName="_teammateReportName_9y80g_343",styles$7_teammateReportSummary="_teammateReportSummary_9y80g_349",styles$7_teammateReportBody="_teammateReportBody_9y80g_358",styles$7_teamModalContent="_teamModalContent_9y80g_364",styles$7_teamBtnRelative="_teamBtnRelative_9y80g_372",styles$7_ganttLabelLead="_ganttLabelLead_9y80g_376",styles$7_ganttLabelAgent="_ganttLabelAgent_9y80g_381",styles$7_ganttTimeAxisRow="_ganttTimeAxisRow_9y80g_385",styles$7_ganttTimeAxisTrack="_ganttTimeAxisTrack_9y80g_389",styles$7_ganttTickLabel="_ganttTickLabel_9y80g_395",styles$7_teamPopoverStatus="_teamPopoverStatus_9y80g_403",styles$7_statusConverged="_statusConverged_9y80g_409",styles$7_statusPending="_statusPending_9y80g_415",styles$7_statusPossiblyAlive="_statusPossiblyAlive_9y80g_420",styles$7_statusReused="_statusReused_9y80g_425",styles$7_ganttIndicatorInitial="_ganttIndicatorInitial_9y80g_430",styles$7_teamModalTitle="_teamModalTitle_9y80g_434",styles$7_teamLeadCard="_teamLeadCard_9y80g_439",styles$7_agentNoMessages="_agentNoMessages_9y80g_443",styles$7_teamAgentCardClickable="_teamAgentCardClickable_9y80g_448",styles$7_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$7_statusConverged,tooltipKey:"residue"===rt.state?"ui.teamSession.status.residue":"ui.teamSession.status.converged"};if("possiblyAlive"===rt.state)return{glyph:"⏱",className:styles$7_statusPossiblyAlive,tooltipKey:"ui.teamSession.status.possiblyAlive"};if("reused"===rt.state)return{glyph:"⏱",className:styles$7_statusReused,tooltipKey:"ui.teamSession.status.reused"}}return{glyph:"⏱",className:styles$7_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$7_teamPopover,children:[jsxRuntimeExports.jsxs("div",{className:styles$7_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$7_teamPopoverStatus} ${disp.className||""}`,style:style,children:disp.glyph});return jsxRuntimeExports.jsxs("div",{className:styles$7_teamPopoverItem,onClick:()=>onOpenSession(team),children:[jsxRuntimeExports.jsx(Tooltip,{title:t(disp.tooltipKey),children:statusEl}),jsxRuntimeExports.jsx("span",{className:styles$7_teamPopoverName,children:team.name}),jsxRuntimeExports.jsxs("span",{className:styles$7_teamPopoverMeta,children:[team.teammateCount,"p · ",team.taskCount,"t"]}),jsxRuntimeExports.jsx("span",{className:styles$7_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$7_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$7_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$7_teamGanttToggle,onClick:()=>setGanttOpen(prev=>!prev),children:[ganttOpen?"▼":"▶"," Timeline",ganttOpen&&jsxRuntimeExports.jsx("span",{className:styles$7_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$7_teamGanttWrap,style:ganttHeight?{maxHeight:"none",height:ganttHeight}:void 0,children:[jsxRuntimeExports.jsxs("div",{className:styles$7_teamGanttRow,children:[jsxRuntimeExports.jsx("div",{className:`${styles$7_teamGanttLabel} ${styles$7_ganttLabelLead}`,children:"team-lead"}),jsxRuntimeExports.jsxs("div",{className:styles$7_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$7_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$7_teamGanttDiamond,style:{left:pct(seg.start)+"%",color:dColor},children:"◆"},`d${i}`)})]})]}),teamAgents.map((ag,i)=>jsxRuntimeExports.jsxs("div",{className:styles$7_teamGanttRow,children:[jsxRuntimeExports.jsx("div",{className:`${styles$7_teamGanttLabel} ${styles$7_ganttLabelAgent}`,children:ag.name}),jsxRuntimeExports.jsxs("div",{className:styles$7_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$7_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$7_teamGanttDiamond} ${styles$7_ganttLabelAgent}`,style:{left:pct(ev.ts)+"%"},children:"◆"},`d${ei}`)})]})]},i)),jsxRuntimeExports.jsxs("div",{className:`${styles$7_teamGanttRow} ${styles$7_ganttTimeAxisRow}`,children:[jsxRuntimeExports.jsx("div",{className:styles$7_teamGanttLabel}),jsxRuntimeExports.jsx("div",{className:`${styles$7_teamGanttTrack} ${styles$7_ganttTimeAxisTrack}`,children:ticks.map((tk,i)=>jsxRuntimeExports.jsx("span",{className:styles$7_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$7_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$7_teamGanttIndicator} ${styles$7_ganttIndicatorInitial}`})]}),jsxRuntimeExports.jsx("div",{className:styles$7_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$7_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$7_teamModalLayout,children:[jsxRuntimeExports.jsxs("div",{className:styles$7_teamAgentCards,children:[jsxRuntimeExports.jsxs("div",{className:`${styles$7_teamAgentCard} ${styles$7_teamLeadCard}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$7_teamAgentCardHeader,children:[(null==modelInfo?void 0:modelInfo.svg)?jsxRuntimeExports.jsx("div",{className:styles$7_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$7_teamAgentAvatar,alt:"lead"}),jsxRuntimeExports.jsx("div",{className:styles$7_teamAgentName,children:"team-lead"})]}),jsxRuntimeExports.jsx("div",{className:styles$7_teamAgentType,children:"orchestrator"}),(()=>{const disp=deriveDisplayStatus(session,null),style=disp.colorVar?{color:disp.colorVar}:void 0;return jsxRuntimeExports.jsxs("div",{className:`${styles$7_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$7_teamAgentPopover,children:[ag.teammateMessages&&ag.teammateMessages.length>0&&jsxRuntimeExports.jsx("div",{className:styles$7_teamAgentPopTeammateMsg,children:ag.teammateMessages.map((tm,ti)=>jsxRuntimeExports.jsxs("div",{children:[tm.summary&&jsxRuntimeExports.jsx("div",{className:styles$7_teamAgentPopTmSummary,children:tm.summary}),jsxRuntimeExports.jsx("div",{className:`${styles$7_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$7_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$7_teamAgentPopMsg} chat-md`,dangerouslySetInnerHTML:{__html:renderMarkdown(texts.length>2e3?texts.slice(0,2e3)+"\n\n...":texts)}},mi):null}):jsxRuntimeExports.jsx("div",{className:styles$7_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$7_teamAgentCard} ${styles$7_teamAgentCardClickable} ${activeAgentCard===i?styles$7_teamAgentCardActive:""}`,children:[jsxRuntimeExports.jsxs("div",{className:styles$7_teamAgentCardHeader,children:[(()=>{const _a=getTeammateAvatar(ag.name);return jsxRuntimeExports.jsx("div",{className:styles$7_teamAgentAvatar,style:{background:_a.color},dangerouslySetInnerHTML:{__html:_a.svg}})})(),jsxRuntimeExports.jsx("div",{className:styles$7_teamAgentName,children:ag.name})]}),jsxRuntimeExports.jsx("div",{className:styles$7_teamAgentType,children:ag.type}),jsxRuntimeExports.jsxs("div",{className:styles$7_teamAgentStatus,style:{color:isDone?"var(--color-success)":"var(--color-warning-light)"},children:[isDone?"✓ done":"● working"," ",jsxRuntimeExports.jsxs("span",{className:styles$7_agentStatusDurSuffix,children:["· ",durStr]})]})]})},i)})]}),jsxRuntimeExports.jsxs("div",{className:styles$7_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$7_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$7_teammateReportEntry,children:[jsxRuntimeExports.jsxs("div",{className:styles$7_teammateReportHeader,children:[(()=>{const _a=getTeammateAvatar(entry.agentName);return jsxRuntimeExports.jsx("div",{className:styles$7_teamAgentAvatar,style:{background:_a.color},dangerouslySetInnerHTML:{__html:_a.svg}})})(),jsxRuntimeExports.jsx("span",{className:styles$7_teammateReportName,children:entry.agentName}),jsxRuntimeExports.jsx("span",{className:styles$7_teammateReportSummary,children:entry.summary})]}),jsxRuntimeExports.jsx("div",{className:`${styles$7_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$6_snapLine="_snapLine_1qd8k_1",styles$6_snapLineActive="_snapLineActive_1qd8k_13",styles$6_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$6_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$6_snapLineActive:styles$6_snapLine,style:{left:`${snap.linePosition}px`}},snap.cols)}return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[snapPreview2,snapLineEl]})}const styles$5_roleFilterBar="_roleFilterBar_122ad_1",styles$5_roleChip="_roleChip_122ad_12",styles$5_roleChipActive="_roleChipActive_122ad_12",styles$5_roleAvatar="_roleAvatar_122ad_33",styles$5_roleAvatarImg="_roleAvatarImg_122ad_47",styles$5_roleName="_roleName_122ad_54",styles$5_roleCheck="_roleCheck_122ad_59";function RoleFilterBar({roles:roles,selectedRoles:selectedRoles,onToggle:onToggle,style:style}){return roles&&0!==roles.length?jsxRuntimeExports.jsx("div",{className:styles$5_roleFilterBar,style:style,children:roles.map(r=>{const selected=selectedRoles.has(r.key);return jsxRuntimeExports.jsxs("button",{className:selected?styles$5_roleChipActive:styles$5_roleChip,onClick:()=>onToggle(r.key),children:[r.avatarImg?jsxRuntimeExports.jsx("img",{src:r.avatarImg,className:styles$5_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$5_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$5_roleName,children:r.name}),selected&&jsxRuntimeExports.jsx("span",{className:styles$5_roleCheck,children:"✓"})]},r.key)})}):null}const styles$4_chatInputBar="_chatInputBar_ri6yd_1",styles$4_chatInputWrapper="_chatInputWrapper_ri6yd_7",styles$4_chatTextareaWrap="_chatTextareaWrap_ri6yd_21",styles$4_chatTextarea="_chatTextarea_ri6yd_21",styles$4_chatInputBottom="_chatInputBottom_ri6yd_46",styles$4_plusArea="_plusArea_ri6yd_53",styles$4_plusBtn="_plusBtn_ri6yd_57",styles$4_micBtn="_micBtn_ri6yd_58",styles$4_plusBtnOpen="_plusBtnOpen_ri6yd_73",styles$4_micBtnRecording="_micBtnRecording_ri6yd_84",styles$4_interimPreview="_interimPreview_ri6yd_104",styles$4_plusOverlay="_plusOverlay_ri6yd_123",styles$4_plusMenu="_plusMenu_ri6yd_132",styles$4_plusMenuItem="_plusMenuItem_ri6yd_145",styles$4_plusMenuItemMuted="_plusMenuItemMuted_ri6yd_165",styles$4_presetLabel="_presetLabel_ri6yd_184",styles$4_chatInputHint="_chatInputHint_ri6yd_190",styles$4_sendBtn="_sendBtn_ri6yd_198",styles$4_sendBtnDisabled="_sendBtnDisabled_ri6yd_213",styles$4_ghostText="_ghostText_ri6yd_224",styles$4_suggestionChip="_suggestionChip_ri6yd_240",styles$4_suggestionChipText="_suggestionChipText_ri6yd_256",styles$4_suggestionChipAction="_suggestionChipAction_ri6yd_265",styles$4_imagePreviewStrip="_imagePreviewStrip_ri6yd_272",styles$4_imagePreviewItem="_imagePreviewItem_ri6yd_284",styles$4_imagePreviewThumb="_imagePreviewThumb_ri6yd_299",styles$4_imagePreviewRemove="_imagePreviewRemove_ri6yd_306",styles$4_filePreviewClose="_filePreviewClose_ri6yd_334",styles$4_filePreviewChip="_filePreviewChip_ri6yd_341",styles$4_filePreviewName="_filePreviewName_ri6yd_364",styles$4_streamingSpinner="_streamingSpinner_ri6yd_521",styles$4_sendBtnWrap="_sendBtnWrap_ri6yd_531",styles$4_streamingSvg="_streamingSvg_ri6yd_552",styles$4_streamingSpinnerFading="_streamingSpinnerFading_ri6yd_559",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}){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(),vh=(null==(_a=window.visualViewport)?void 0:_a.height)??window.innerHeight,distFromBottom=Math.max(0,vh-rect.top);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$4_suggestionChip,onClick:onSuggestionClick,children:[jsxRuntimeExports.jsx("span",{className:styles$4_suggestionChipText,children:inputSuggestion}),jsxRuntimeExports.jsx("span",{className:styles$4_suggestionChipAction,children:"↵"})]}):null:jsxRuntimeExports.jsxs("div",{className:styles$4_chatInputBar,ref:rootRef,children:[jsxRuntimeExports.jsxs("div",{className:styles$4_chatInputWrapper,children:[jsxRuntimeExports.jsxs("div",{className:styles$4_chatTextareaWrap,children:[pendingImages&&pendingImages.length>0&&jsxRuntimeExports.jsx("div",{className:styles$4_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$4_imagePreviewItem,children:[jsxRuntimeExports.jsx("img",{src:src,className:styles$4_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$4_imagePreviewRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},img.path):jsxRuntimeExports.jsxs("div",{className:styles$4_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$4_filePreviewName,children:fileName2}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveFile"),onConfirm:()=>null==onRemovePendingImage?void 0:onRemovePendingImage(i),className:styles$4_filePreviewClose,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},img.path)})}),jsxRuntimeExports.jsx("textarea",{ref:inputRef,className:styles$4_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$4_ghostText,children:inputSuggestion}),recording&&interimText&&jsxRuntimeExports.jsx("div",{className:styles$4_interimPreview,children:interimText})]}),jsxRuntimeExports.jsxs("div",{className:styles$4_chatInputBottom,children:[jsxRuntimeExports.jsxs("div",{className:styles$4_plusArea,children:[jsxRuntimeExports.jsx("button",{className:`${styles$4_plusBtn}${plusOpen?` ${styles$4_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$4_plusOverlay,onClick:()=>setPlusOpen(!1)}),jsxRuntimeExports.jsxs("div",{className:styles$4_plusMenu,children:[presetItems&&presetItems.length>0&&onOpenPresetModal&&jsxRuntimeExports.jsxs("button",{className:`${styles$4_plusMenuItem} ${styles$4_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$4_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$4_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$4_presetLabel,children:name||desc})]},item.id)}),onOpenUltraPlan&&jsxRuntimeExports.jsxs("button",{className:styles$4_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$4_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$4_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$4_micBtn}${recording?` ${styles$4_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"})]})}),jsxRuntimeExports.jsx("div",{className:styles$4_chatInputHint,children:isMobile&&!isPad?null:t(inputSuggestion&&inputEmpty?"ui.chatInput.hintTab":"ui.chatInput.hintEnter")}),jsxRuntimeExports.jsxs("div",{className:styles$4_sendBtnWrap,children:[(isStreaming||streamingFading)&&jsxRuntimeExports.jsx("div",{className:`${styles$4_streamingSpinner}${streamingFading?` ${styles$4_streamingSpinnerFading}`:""}`,"aria-hidden":"true",children:jsxRuntimeExports.jsxs("svg",{className:styles$4_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$4_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$4_sendBtn} ${inputEmpty&&!(null==pendingImages?void 0:pendingImages.length)?styles$4_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$i_presetSectionHeader,children:jsxRuntimeExports.jsx("span",{className:styles$i_presetSectionTitle,children:t("ui.terminal.agentTeamCustom")})}),jsxRuntimeExports.jsx("div",{className:styles$i_presetList,onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:e=>{e.preventDefault(),e.stopPropagation()},children:0===items.length?jsxRuntimeExports.jsx("div",{className:styles$i_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$i_presetRow} ${dragIdx.current===idx?styles$i_presetRowDragging:""} ${dragOverIdx.current===idx&&dragIdx.current!==idx?styles$i_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$i_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$i_presetName,title:name,children:name||"—"}),jsxRuntimeExports.jsx("span",{className:styles$i_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$i_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$i_presetFormField,children:[jsxRuntimeExports.jsxs("label",{className:styles$i_presetFormLabel,children:["Team ",t("ui.terminal.teamName")]}),jsxRuntimeExports.jsx("input",{className:styles$i_presetInput,placeholder:t("ui.terminal.teamNamePlaceholder"),value:addName,onChange:e=>setAddName(e.target.value)})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("label",{className:styles$i_presetFormLabel,children:["Team ",t("ui.terminal.teamDesc")]}),jsxRuntimeExports.jsx("textarea",{className:styles$i_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$3_backdrop="_backdrop_1y1ni_1",styles$3_modal="_modal_1y1ni_11",styles$3_header="_header_1y1ni_23",styles$3_title="_title_1y1ni_30",styles$3_closeBtn="_closeBtn_1y1ni_36",styles$3_headerActions="_headerActions_1y1ni_54",styles$3_customWrap="_customWrap_1y1ni_60",styles$3_customTitle="_customTitle_1y1ni_66",styles$3_editPencil="_editPencil_1y1ni_73",styles$3_disabledTip="_disabledTip_1y1ni_104",styles$3_variantRow="_variantRow_1y1ni_111",styles$3_roleBtn="_roleBtn_1y1ni_119",styles$3_roleBtnActive="_roleBtnActive_1y1ni_141",styles$3_addExpertBtn="_addExpertBtn_1y1ni_151",styles$3_contextWarning="_contextWarning_1y1ni_174",styles$3_fileList="_fileList_1y1ni_185",styles$3_fileChip="_fileChip_1y1ni_192",styles$3_fileName="_fileName_1y1ni_215",styles$3_fileRemove="_fileRemove_1y1ni_222",styles$3_imageItem="_imageItem_1y1ni_232",styles$3_imageThumb="_imageThumb_1y1ni_246",styles$3_imageRemove="_imageRemove_1y1ni_253",styles$3_textarea="_textarea_1y1ni_285",styles$3_footer="_footer_1y1ni_309",styles$3_sendBtn="_sendBtn_1y1ni_316",styles$3_uploadBtn="_uploadBtn_1y1ni_338";function UltraPlanModal({open:open,variant:variant,prompt:prompt,files:files,modelName:modelName2,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,lowContext=!modelName2||getModelMaxTokens(modelName2)<1e6,experts=Array.isArray(customExperts)?customExperts:[];return jsxRuntimeExports.jsxs("div",{className:styles$3_backdrop,onClick:onClose,children:[jsxRuntimeExports.jsxs("div",{className:styles$3_modal,onClick:e=>e.stopPropagation(),children:[jsxRuntimeExports.jsxs("div",{className:styles$3_header,children:[jsxRuntimeExports.jsx("span",{className:styles$3_title,children:t("ui.ultraplan.title")}),jsxRuntimeExports.jsx("div",{className:styles$3_headerActions,children:jsxRuntimeExports.jsx("button",{className:styles$3_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$3_variantRow,children:[jsxRuntimeExports.jsxs("button",{className:`${styles$3_roleBtn} ${"codeExpert"===variant?styles$3_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$3_roleBtn} ${"researchExpert"===variant?styles$3_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$3_customWrap,children:[jsxRuntimeExports.jsxs("button",{className:`${styles$3_roleBtn} ${variant===vkey?styles$3_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$3_customTitle,children:item.title})]}),onOpenCustomEditor&&jsxRuntimeExports.jsx("span",{className:styles$3_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$3_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"})})})]}),lowContext&&jsxRuntimeExports.jsx("div",{className:styles$3_contextWarning,children:t("ui.ultraplan.contextWarning")}),files.length>0&&jsxRuntimeExports.jsx("div",{className:styles$3_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$3_imageItem,title:f.name,children:[jsxRuntimeExports.jsx("img",{src:src,className:styles$3_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$3_imageRemove,ariaLabel:t("ui.chatInput.removeImage"),children:"×"})]},i):jsxRuntimeExports.jsxs("span",{className:styles$3_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$3_fileName,children:f.name}),jsxRuntimeExports.jsx(ConfirmRemoveButton,{title:t("ui.chatInput.confirmRemoveFile"),onConfirm:()=>onRemoveFile(i),className:styles$3_fileRemove,ariaLabel:t("ui.chatInput.removeImage"),tag:"span",children:"×"})]},i)})}),jsxRuntimeExports.jsx("textarea",{className:styles$3_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$3_footer,children:[jsxRuntimeExports.jsx("button",{className:styles$3_sendBtn,disabled:!hasContent,onClick:onSend,children:t("ui.ultraplan.send")}),jsxRuntimeExports.jsxs("button",{className:styles$3_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$3_disabledTip,children:t("ui.ultraplan.agentTeamRequired")})]}),lightbox&&jsxRuntimeExports.jsx(ImageLightbox,{src:lightbox.src,alt:lightbox.alt,zIndex:1150,onClose:()=>setLightbox(null)})]})}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 styles$2_centerEmpty="_centerEmpty_118cz_1",styles$2_container="_container_118cz_8",styles$2_mobileVirtuoso="_mobileVirtuoso_118cz_19",styles$2_sessionDividerText="_sessionDividerText_118cz_24",styles$2_lastResponseLabel="_lastResponseLabel_118cz_29",styles$2_splitContainer="_splitContainer_118cz_33",styles$2_chatSection="_chatSection_118cz_40",styles$2_vResizer="_vResizer_118cz_48",styles$2_terminalToggle="_terminalToggle_118cz_62",styles$2_messageListWrap="_messageListWrap_118cz_85",styles$2_stickyBottomBtn="_stickyBottomBtn_118cz_93",styles$2_loadingPet="_loadingPet_118cz_120",styles$2_loadMoreWrap="_loadMoreWrap_118cz_154",styles$2_loadMoreBtn="_loadMoreBtn_118cz_160",styles$2_navSidebar="_navSidebar_118cz_176",styles$2_navBtn="_navBtn_118cz_193",styles$2_navBtnActive="_navBtnActive_118cz_213",styles$2_navDivider="_navDivider_118cz_228",styles$2_navAvatarImg="_navAvatarImg_118cz_241",styles$2_userPromptNavList="_userPromptNavList_118cz_248",styles$2_userPromptNavItem="_userPromptNavItem_118cz_257",styles$2_terminalPanelWrap="_terminalPanelWrap_118cz_277",styles$2_navSidebarContent="_navSidebarContent_118cz_288",styles$2_innerSplitArea="_innerSplitArea_118cz_296",styles$2_chatSectionFlex="_chatSectionFlex_118cz_303",styles$2_inputStack="_inputStack_118cz_313",styles$2_overlayPanel="_overlayPanel_118cz_318",styles$2_streamingSpinnerWrap="_streamingSpinnerWrap_118cz_326",styles$2_streamingSpinnerHidden="_streamingSpinnerHidden_118cz_333",styles$2_sessionDivider="_sessionDivider_118cz_24",styles$2_loadMoreBtnLoading="_loadMoreBtnLoading_118cz_342",styles$2_loadMoreSpinner="_loadMoreSpinner_118cz_350",styles$2_lastResponseDivider="_lastResponseDivider_118cz_364",styles$2_hideLastResponseDivider="_hideLastResponseDivider_118cz_377",{Text:Text}=Typography,useVirtuoso=isMobile&&!isIOS&&!isPad,EMPTY_MAP={},VirtuosoScroller=React__default.forwardRef((props,ref)=>jsxRuntimeExports.jsx("div",{ref:ref,...props,className:styles$2_container}));class ChatView extends React__default.Component{constructor(props){super(props),__publicField(this,"_refreshFollowTarget",scroller=>{scroller&&(this._followTarget=Math.max(0,scroller.scrollHeight-scroller.clientHeight))}),__publicField(this,"_bindVirtuosoResizeObserver",el=>{if(el!==this._virtuosoBoundEl){if(this._virtuosoResizeObserver){try{this._virtuosoResizeObserver.disconnect()}catch{}this._virtuosoResizeObserver=null}if(this._virtuosoBoundEl=el,el&&"undefined"!=typeof ResizeObserver)try{this._virtuosoResizeObserver=new ResizeObserver(()=>this._refreshFollowTarget(el)),this._virtuosoResizeObserver.observe(el),this._refreshFollowTarget(el)}catch{}}}),__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&&(el.scrollTop=el.scrollHeight)}})}),__publicField(this,"_startSmoothStickyFollow",useVirtuoso2=>{const scroller=useVirtuoso2?this._virtuosoScrollerEl:this.containerRef.current;if(!scroller)return;this._stickyScrollLock=!0,this._smoothFollowRafId&&cancelAnimationFrame(this._smoothFollowRafId);const step=()=>{if(this._smoothFollowRafId=null,this._unmounted)return void(this._stickyScrollLock=!1);if(!this.state.stickyBottom)return void(this._stickyScrollLock=!1);const target=this._followTarget,current=scroller.scrollTop,gap=target-current;if(gap<=.5)return scroller.scrollTop=target,void(this._stickyScrollLock=!1);const delta=Math.max(1,Math.min(.35*gap,120));scroller.scrollTop=current+delta,this._smoothFollowRafId=requestAnimationFrame(step)};this._smoothFollowRafId=requestAnimationFrame(()=>{this._smoothFollowRafId=requestAnimationFrame(()=>{this._refreshFollowTarget(scroller),step()})})}),__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){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,"_onTerminalWsMessage",msg=>{var _a,_b,_c;try{"data"===msg.type?this._appendPtyData(msg.data):"exit"===msg.type?this._clearPtyPrompt():"ask-hook-pending"===msg.type?(this._askHookActive=!0,this._askHookQuestions=msg.questions,Array.isArray(msg.questions)&&msg.questions.length>0&&(!this.state.pendingAsk||"__ask__"===this.state.pendingAsk.id)&&this.setState({pendingAsk:{id:"__ask__",questions:msg.questions}})):"ask-hook-timeout"===msg.type?(this._askHookActive=!1,this._askHookQuestions=null,"__ask__"===(null==(_a=this.state.pendingAsk)?void 0:_a.id)&&this.setState({pendingAsk:null})):"sdk-plan-pending"===msg.type?this.setState({pendingPlanApproval:{id:msg.id,input:msg.input}}):"sdk-ask-pending"===msg.type?(this._askHookActive=!0,this._askHookQuestions=msg.questions,this._sdkAskId=msg.id,Array.isArray(msg.questions)&&msg.questions.length>0&&this.setState({pendingAsk:{id:String(msg.id),questions:msg.questions}})):"sdk-ask-timeout"===msg.type?(this._askHookActive=!1,this._askHookQuestions=null,this._sdkAskId=null,this.setState({pendingAsk:null})):"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}}):"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:[]}}):"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)}}):"ask-hook-resolved"===msg.type?(this._askHookActive=!1,this._askHookQuestions=null,"__ask__"===(null==(_b=this.state.pendingAsk)?void 0:_b.id)&&this.setState({pendingAsk:null})):"sdk-ask-resolved"===msg.type?this._sdkAskId===msg.id&&(this._askHookActive=!1,this._askHookQuestions=null,this._sdkAskId=null,this.state.pendingAsk&&this.setState({pendingAsk:null})):"sdk-plan-resolved"===msg.type?(null==(_c=this.state.pendingPlanApproval)?void 0:_c.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;"close"===state&&((null==(_a=this.state.pendingPtyPlan)?void 0:_a.id)&&this._resolvedPlanIds.add(this.state.pendingPtyPlan.id),(this.state.pendingPermission||this.state.pendingPlanApproval||this.state.pendingAsk||this.state.pendingPtyPlan)&&this.setState({pendingPermission:null,permissionQueue:[],pendingPlanApproval:null,pendingAsk:null,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;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==(_a=(q.options||[])[answer.optionIndex])?void 0:_a.label)||""}this._lastClearedPendingAsk=this.state.pendingAsk,this._lastAskSubmitId=askId,this.setState(prev=>({localAskAnswers:{...prev.localAskAnswers||{},[askId]:localAnswers},pendingAsk:null}))}if(this.props.sdkMode){const resolvedId=askId||this._sdkAskId;if(!resolvedId)return this._lastClearedPendingAsk=null,void(this._lastAskSubmitId=null);const ws=this._inputWs;if(ws&&ws.readyState===WebSocket.OPEN){const sdkAnswers={},qs=this._askHookQuestions||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==(_b=(q.options||[])[answer.optionIndex])?void 0:_b.label)||""}ws.send(JSON.stringify({type:"sdk-ask-answer",id:resolvedId,answers:sdkAnswers})),this._sdkAskId=null,this._lastClearedPendingAsk=null,this._lastAskSubmitId=null}else this._lastClearedPendingAsk=null,this._lastAskSubmitId=null;return}if(!this._askHookActive||this._askSubmitting)return this._askHookActive||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)}),__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,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._unmounted=!1}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._bindStickyScroll(),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.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)&&null==this.state.pendingAsk&&prevState.pendingAsk&&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._startSmoothStickyFollow(!0),prevProps.streamingLatest!==this.props.streamingLatest&&this.state.stickyBottom&&this._startSmoothStickyFollow(useVirtuoso),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&&(el.scrollTop=el.scrollHeight)}}),useVirtuoso||this._rebindStickyEl()}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{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}),this.state.pendingAsk&&"undefined"!=typeof window&&(null==(_b=window.tabBridge)?void 0:_b.notifyAskResolved)&&window.tabBridge.notifyAskResolved({id:this.state.pendingAsk.id,tabId:this.props.ownTabId??null})}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(),useVirtuoso||this._unbindStickyScroll(),this._virtuosoResizeObserver){try{this._virtuosoResizeObserver.disconnect()}catch{}this._virtuosoResizeObserver=null,this._virtuosoBoundEl=null}if(this._smoothFollowRafId&&(cancelAnimationFrame(this._smoothFollowRafId),this._smoothFollowRafId=null),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 wasSticky=this.state.stickyBottom;this._stickyScrollLock=!0;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},()=>{this.scrollToBottom(wasSticky),requestAnimationFrame(()=>{this._stickyScrollLock=!1})})}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(stickyOverride){const shouldStick=null!=stickyOverride?stickyOverride: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?scroller.scrollTop=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&&(el.scrollTop=el.scrollHeight)}}}_bindStickyScroll(){this._stickyScrollRafId=null,this._followTarget=0,this._onStickyScroll=()=>{this._stickyScrollLock||this._stickyScrollRafId||(this._stickyScrollRafId=requestAnimationFrame(()=>{this._stickyScrollRafId=null;const el=this.containerRef.current;if(!el)return;const gap=this._followTarget-el.scrollTop;this.state.stickyBottom&&gap>50?this.setState({stickyBottom:!1}):!this.state.stickyBottom&&gap<=10&&this.setState({stickyBottom:!0})}))},this._rebindStickyEl()}_rebindStickyEl(){const el=this.containerRef.current;if(el!==this._stickyBoundEl){if(this._stickyBoundEl&&(this._stickyBoundEl.removeEventListener("scroll",this._onStickyScroll),this._stickyResizeObserver)){try{this._stickyResizeObserver.disconnect()}catch{}this._stickyResizeObserver=null}if(this._stickyBoundEl=el,el&&(el.addEventListener("scroll",this._onStickyScroll,{passive:!0}),this._refreshFollowTarget(el),"undefined"!=typeof ResizeObserver))try{this._stickyResizeObserver=new ResizeObserver(()=>this._refreshFollowTarget(el)),this._stickyResizeObserver.observe(el)}catch{}}}_unbindStickyScroll(){if(this._stickyBoundEl&&this._onStickyScroll&&(this._stickyBoundEl.removeEventListener("scroll",this._onStickyScroll),this._stickyBoundEl=null),this._stickyScrollRafId&&(cancelAnimationFrame(this._stickyScrollRafId),this._stickyScrollRafId=null),this._stickyResizeObserver){try{this._stickyResizeObserver.disconnect()}catch{}this._stickyResizeObserver=null}}_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,reqIdx=ts?tsToIndex[ts]: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,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,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$2_sessionDivider,children:jsxRuntimeExports.jsx(Text,{className:styles$2_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],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$2_loadMoreWrap,children:this.props.loadingMore?jsxRuntimeExports.jsxs("div",{className:`${styles$2_loadMoreBtn} ${styles$2_loadMoreBtnLoading}`,children:[jsxRuntimeExports.jsx("span",{className:styles$2_loadMoreSpinner}),t("ui.loadingMoreHistory")]}):jsxRuntimeExports.jsx("button",{className:styles$2_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$2_sessionDivider,children:jsxRuntimeExports.jsx(Text,{className:styles$2_sessionDividerText,children:"Session"})},`session-div-${si}`)),session._cold){const isLoading=this.props.loadingSessionId===session.sessionId;return void allItems.push(jsxRuntimeExports.jsx("div",{className:styles$2_loadMoreWrap,children:isLoading?jsxRuntimeExports.jsxs("div",{className:`${styles$2_loadMoreBtn} ${styles$2_loadMoreBtnLoading}`,children:[jsxRuntimeExports.jsx("span",{className:styles$2_loadMoreSpinner}),t("ui.loadingMoreHistory")]}):jsxRuntimeExports.jsx("button",{className:styles$2_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 msgTs=m.props.timestamp;for(;subIdx<subAgentEntries.length&&msgTs&&subAgentEntries[subIdx].timestamp<=msgTs;){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++}msgTs&&(tsItemMap[msgTs]=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$2_lastResponseDivider,children:jsxRuntimeExports.jsx(Text,{type:"secondary",className:styles$2_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{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){var _a,_b;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=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)||""}ws.send(JSON.stringify({type:"ask-hook-answer",answers:hookAnswers})),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$2_navSidebar,children:[jsxRuntimeExports.jsx("button",{className:this.state.roleFilterOpen?styles$2_navBtnActive:styles$2_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$2_navBtnActive:styles$2_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$2_navBtnActive:styles$2_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$2_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$2_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$2_navBtn}),jsxRuntimeExports.jsx(Popover,{content:this._buildUserPromptNav(),trigger:"hover",placement:"rightTop",overlayStyle:{maxWidth:400},children:jsxRuntimeExports.jsx("button",{className:styles$2_navBtn,title:t("ui.userPromptNav"),children:jsxRuntimeExports.jsx("img",{src:(null==(_a=this.props.userProfile)?void 0:_a.avatar)||defaultAvatarUrl,className:styles$2_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$2_userPromptNavList,children:prompts.map((p,i)=>jsxRuntimeExports.jsx("div",{className:styles$2_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,_k;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;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$2_centerEmpty,children:jsxRuntimeExports.jsx(Empty,{description:t("ui.noChat")})});if(loading2&&!cliMode)return jsxRuntimeExports.jsx("div",{className:styles$2_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 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;return(null==(_a2=item.props)?void 0:_a2.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$2_stickyBottomBtn,onClick:this.handleStickToBottom,children:[this.props.isStreaming&&jsxRuntimeExports.jsx("img",{src:"/assets/loading-pet-12a9GTQC.gif",className:styles$2_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$2_loadMoreWrap,children:jsxRuntimeExports.jsx("button",{className:styles$2_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$2_messageListWrap,children:[jsxRuntimeExports.jsxs("div",{ref:this.containerRef,className:styles$2_container,children:[!cliMode||loading2?jsxRuntimeExports.jsx("div",{className:styles$2_centerEmpty,children:loading2?jsxRuntimeExports.jsx(Spin,{size:"large"}):jsxRuntimeExports.jsx(Empty,{description:t("ui.noChat")})}):null,pendingBubble]}),stickyBtn]}):jsxRuntimeExports.jsxs("div",{className:styles$2_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:[jsxRuntimeExports.jsx("div",{className:`${styles$2_streamingSpinnerWrap}${!this.props.isStreaming||streamingLiveItem?" "+styles$2_streamingSpinnerHidden:""}`,children:jsxRuntimeExports.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 20 20",children:[jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{id:"ccv-spinnerGrad",x1:"0",y1:"0",x2:"1",y2:"1",children:[jsxRuntimeExports.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"1"}),jsxRuntimeExports.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0.1"})]})}),jsxRuntimeExports.jsx("circle",{cx:"10",cy:"10",r:"7.5",fill:"none",strokeWidth:"2",stroke:"url(#ccv-spinnerGrad)",strokeLinecap:"round",pathLength:"100",strokeDasharray:"75 25",children:jsxRuntimeExports.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 10 10",to:"360 10 10",dur:"0.8s",repeatCount:"indefinite"})})]})}),filteredLastResponseItems&&jsxRuntimeExports.jsx("div",{className:streamingLiveItem?styles$2_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$2_mobileVirtuoso,data:visible,initialTopMostItemIndex:Math.max(0,visible.length-1),followOutput:!!this.state.stickyBottom&&"smooth",atBottomStateChange:atBottom=>{if(!this._stickyScrollLock){if(!atBottom&&this.state.stickyBottom&&this._virtuosoScrollerEl){const s=this._virtuosoScrollerEl;if(s.scrollHeight-s.scrollTop-s.clientHeight<=60)return}atBottom!==this.state.stickyBottom&&this.setState({stickyBottom: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._bindVirtuosoResizeObserver(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$2_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}),jsxRuntimeExports.jsx("div",{className:`${styles$2_streamingSpinnerWrap}${!this.props.isStreaming||streamingLiveItem?" "+styles$2_streamingSpinnerHidden:""}`,children:jsxRuntimeExports.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 20 20",children:[jsxRuntimeExports.jsx("defs",{children:jsxRuntimeExports.jsxs("linearGradient",{id:"ccv-spinnerGrad-desktop",x1:"0",y1:"0",x2:"1",y2:"1",children:[jsxRuntimeExports.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"1"}),jsxRuntimeExports.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0.1"})]})}),jsxRuntimeExports.jsx("circle",{cx:"10",cy:"10",r:"7.5",fill:"none",strokeWidth:"2",stroke:"url(#ccv-spinnerGrad-desktop)",strokeLinecap:"round",pathLength:"100",strokeDasharray:"75 25",children:jsxRuntimeExports.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 10 10",to:"360 10 10",dur:"0.8s",repeatCount:"indefinite"})})]})}),filteredLastResponseItems&&jsxRuntimeExports.jsx("div",{className:streamingLiveItem?styles$2_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$2_splitContainer,children:[this._renderNavSidebar(!0),jsxRuntimeExports.jsxs("div",{className:styles$2_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)=>{tryOpenWithSystem(repoPath&&"."!==repoPath?`${repoPath}/${filePath2}`:filePath2,"git-changes")||this.setState({currentGitDiff:{repo:repoPath,file:filePath2},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$2_vResizer,onMouseDown:this.handleSidebarMouseDown}),jsxRuntimeExports.jsx("div",{className:styles$2_chatSection,children:jsxRuntimeExports.jsxs("div",{className:styles$2_chatSectionFlex,children:[this.state.currentGitDiff&&jsxRuntimeExports.jsx("div",{className:styles$2_overlayPanel,children:jsxRuntimeExports.jsx(GitDiffView,{filePath:this.state.currentGitDiff.file,repoPath:this.state.currentGitDiff.repo,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$2_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$2_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})]}),jsxRuntimeExports.jsx(UltraPlanModal,{open:this.state.ultraplanModalOpen,variant:this.state.ultraplanVariant,prompt:this.state.ultraplanPrompt,files:this.state.ultraplanFiles,modelName:null==(_j=this._reqScanCache)?void 0:_j.modelName,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$2_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$2_vResizer,onMouseDown:this.handleSplitMouseDown}),jsxRuntimeExports.jsx("div",{className:styles$2_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==(_k=this._reqScanCache)?void 0:_k.modelName,getChatScroller:()=>this._getScrollContainer(),onClearContextOptimistic:this.props.onClearContextOptimistic})})]})]})]}),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$2_splitContainer,children:[this._renderNavSidebar(!1),jsxRuntimeExports.jsx("div",{className:styles$2_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$1_backdrop="_backdrop_1mfxv_7",styles$1_modal="_modal_1mfxv_25",styles$1_header="_header_1mfxv_44",styles$1_title="_title_1mfxv_53",styles$1_chip="_chip_1mfxv_59",styles$1_chipAction="_chipAction_1mfxv_70",styles$1_body="_body_1mfxv_83",styles$1_slot="_slot_1mfxv_91",styles$1_slotHidden="_slotHidden_1mfxv_96",styles$1_footer="_footer_1mfxv_100",styles$1_dismissBtn="_dismissBtn_1mfxv_111",styles$1_kindTabs="_kindTabs_1mfxv_127",styles$1_kindTab="_kindTab_1mfxv_127",styles$1_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$1_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$1_modal,children:[jsxRuntimeExports.jsxs("div",{className:styles$1_header,children:[jsxRuntimeExports.jsx("span",{className:styles$1_title,children:_tr(titleKey,null,titleFallback)}),projectName&&jsxRuntimeExports.jsx("span",{className:styles$1_chip,children:projectName}),Array.isArray(otherTabs)&&otherTabs.map(ot=>jsxRuntimeExports.jsx("span",{className:`${styles$1_chip} ${styles$1_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$1_kindTabs,children:visibleKinds.map(k=>jsxRuntimeExports.jsx("button",{className:`${styles$1_kindTab} ${k===activeKind?styles$1_kindTabActive:""}`,onClick:()=>setActiveKind(k),children:_tr(`ui.approval.modal.title.${k}`,null,k)},k))}),jsxRuntimeExports.jsxs("div",{className:styles$1_body,children:[jsxRuntimeExports.jsx("div",{ref:ptyPlanSlotRef,className:`${styles$1_slot}${"ptyPlan"!==activeKind?" "+styles$1_slotHidden:""}`}),jsxRuntimeExports.jsx("div",{ref:askSlotRef,className:`${styles$1_slot}${"ask"!==activeKind?" "+styles$1_slotHidden:""}`})]}),jsxRuntimeExports.jsxs("div",{className:styles$1_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$1_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={headerBar:"_headerBar_pifvb_2",logoWrap:"_logoWrap_pifvb_10",logoWrapActive:"_logoWrapActive_pifvb_17",logoImage:"_logoImage_pifvb_26",logoImageActive:"_logoImageActive_pifvb_36",compactBtn:"_compactBtn_pifvb_43",compactBtnNoBorder:"_compactBtnNoBorder_pifvb_52",liveTag:"_liveTag_pifvb_74",liveTagFill:"_liveTagFill_pifvb_92",liveTagContent:"_liveTagContent_pifvb_104",liveTagHistory:"_liveTagHistory_pifvb_111",liveTagText:"_liveTagText_pifvb_117",countdownStrong:"_countdownStrong_pifvb_122",qrcodePopover:"_qrcodePopover_pifvb_127",qrcodeSection:"_qrcodeSection_pifvb_134",qrcodeTitle:"_qrcodeTitle_pifvb_145",qrcodeUrlInput:"_qrcodeUrlInput_pifvb_152",qrcodeUrlCopy:"_qrcodeUrlCopy_pifvb_158",settingsGroupBox:"_settingsGroupBox_pifvb_169",settingsGroupTitle:"_settingsGroupTitle_pifvb_177",settingsItem:"_settingsItem_pifvb_186",settingsLabel:"_settingsLabel_pifvb_193",settingsDivider:"_settingsDivider_pifvb_197",logDirInput:"_logDirInput_pifvb_202",tokenStatsEmpty:"_tokenStatsEmpty_pifvb_212",tokenStatsContainer:"_tokenStatsContainer_pifvb_219",tokenStatsColumn:"_tokenStatsColumn_pifvb_225",toolStatsColumn:"_toolStatsColumn_pifvb_229",modelCard:"_modelCard_pifvb_234",modelCardSpaced:"_modelCardSpaced_pifvb_241 _modelCard_pifvb_234",modelName:"_modelName_pifvb_247",statsTable:"_statsTable_pifvb_257",th:"_th_pifvb_262",td:"_td_pifvb_272",label:"_label_pifvb_281",rowBorder:"_rowBorder_pifvb_291",rebuildCard:"_rebuildCard_pifvb_295",rebuildTotalRow:"_rebuildTotalRow_pifvb_303",promptExportBar:"_promptExportBar_pifvb_312",promptScrollArea:"_promptScrollArea_pifvb_316",promptEmpty:"_promptEmpty_pifvb_321",promptTimestamp:"_promptTimestamp_pifvb_327",textPromptCard:"_textPromptCard_pifvb_335",preText:"_preText_pifvb_344",systemCollapse:"_systemCollapse_pifvb_354",systemLabel:"_systemLabel_pifvb_361",preSys:"_preSys_pifvb_366",promptTextarea:"_promptTextarea_pifvb_376",projectStatsCenter:"_projectStatsCenter_pifvb_392",projectStatsEmpty:"_projectStatsEmpty_pifvb_398",projectStatsContent:"_projectStatsContent_pifvb_405",projectStatsUpdated:"_projectStatsUpdated_pifvb_411",projectStatsSummary:"_projectStatsSummary_pifvb_417",projectStatCard:"_projectStatCard_pifvb_423",projectStatValue:"_projectStatValue_pifvb_431",projectStatLabel:"_projectStatLabel_pifvb_439",projectStatsSection:"_projectStatsSection_pifvb_445",projectStatsSectionTitle:"_projectStatsSectionTitle_pifvb_451",projectStatsModelCard:"_projectStatsModelCard_pifvb_459",projectStatsModelHeader:"_projectStatsModelHeader_pifvb_466",projectStatsModelName:"_projectStatsModelName_pifvb_475",projectStatsModelCount:"_projectStatsModelCount_pifvb_481",pluginDirHint:"_pluginDirHint_pifvb_488",pluginDirPath:"_pluginDirPath_pifvb_494",pluginList:"_pluginList_pifvb_507",pluginItem:"_pluginItem_pifvb_513",pluginInfo:"_pluginInfo_pifvb_523",pluginName:"_pluginName_pifvb_531",pluginFile:"_pluginFile_pifvb_537",pluginHooks:"_pluginHooks_pifvb_543",pluginHookTag:"_pluginHookTag_pifvb_550",pluginActions:"_pluginActions_pifvb_559",pluginEmpty:"_pluginEmpty_pifvb_567",cachePopover:"_cachePopover_pifvb_574",cacheScrollArea:"_cacheScrollArea_pifvb_578",cachePopoverTitle:"_cachePopoverTitle_pifvb_588",cachePopoverHeader:"_cachePopoverHeader_pifvb_597",cacheCopyBtn:"_cacheCopyBtn_pifvb_603",cachePopoverEmpty:"_cachePopoverEmpty_pifvb_615",cacheTokenInfo:"_cacheTokenInfo_pifvb_621",cacheSection:"_cacheSection_pifvb_630",cacheSectionBordered:"_cacheSectionBordered_pifvb_635",cacheSectionLabel:"_cacheSectionLabel_pifvb_645",cacheSectionHeader:"_cacheSectionHeader_pifvb_646",cacheSectionTitle:"_cacheSectionTitle_pifvb_668",cacheSectionArrow:"_cacheSectionArrow_pifvb_703",toolChipGrid:"_toolChipGrid_pifvb_714",toolChipGridVertical:"_toolChipGridVertical_pifvb_721",cacheToolChip:"_cacheToolChip_pifvb_729",chipDetailBody:"_chipDetailBody_pifvb_746",chipDetailEmpty:"_chipDetailEmpty_pifvb_758",mcpServerGroup:"_mcpServerGroup_pifvb_763",mcpServerName:"_mcpServerName_pifvb_767",skillsList:"_skillsList_pifvb_775",skillCard:"_skillCard_pifvb_781",skillCardHeader:"_skillCardHeader_pifvb_788",skillCardName:"_skillCardName_pifvb_796",skillCardActions:"_skillCardActions_pifvb_804",skillCardDesc:"_skillCardDesc_pifvb_809",skillsEmpty:"_skillsEmpty_pifvb_817",skillsReadonlySection:"_skillsReadonlySection_pifvb_825",skillsReadonlyLabel:"_skillsReadonlyLabel_pifvb_831",skillCardDisabled:"_skillCardDisabled_pifvb_838",skillCardTitleRow:"_skillCardTitleRow_pifvb_845",skillSourceBadge:"_skillSourceBadge_pifvb_852",skillSource_user:"_skillSource_user_pifvb_862",skillSource_project:"_skillSource_project_pifvb_863",skillSource_plugin:"_skillSource_plugin_pifvb_864",skillSource_builtin:"_skillSource_builtin_pifvb_865",cacheCodeBlock:"_cacheCodeBlock_pifvb_871",cacheCodeBlockSystem:"_cacheCodeBlockSystem_pifvb_885",cacheNavBtn:"_cacheNavBtn_pifvb_899",cacheNavList:"_cacheNavList_pifvb_914",cacheNavItem:"_cacheNavItem_pifvb_920",cacheBlockHighlight:"_cacheBlockHighlight_pifvb_936",cacheBlockHighlightFading:"_cacheBlockHighlightFading_pifvb_941",cacheBorderSvg:"_cacheBorderSvg_pifvb_946",cacheBorderSvgFading:"_cacheBorderSvgFading_pifvb_955",cacheBorderRect:"_cacheBorderRect_pifvb_960",cacheDashRotate:"_cacheDashRotate_pifvb_1",thLeft:"_thLeft_pifvb_970",cachePercent:"_cachePercent_pifvb_975",cacheCalibrationLabel:"_cacheCalibrationLabel_pifvb_983",calibrationSelect:"_calibrationSelect_pifvb_991",cachePopoverPlaceholder:"_cachePopoverPlaceholder_pifvb_997",cacheWriteToken:"_cacheWriteToken_pifvb_1002",cacheReadToken:"_cacheReadToken_pifvb_1006",cacheCtxPercent:"_cacheCtxPercent_pifvb_1010",pluginModalFooter:"_pluginModalFooter_pifvb_1016",pluginModalFooterLeft:"_pluginModalFooterLeft_pifvb_1021",pluginDirLabel:"_pluginDirLabel_pifvb_1027",pluginEmptyTitle:"_pluginEmptyTitle_pifvb_1032",pluginEmptyHint:"_pluginEmptyHint_pifvb_1037",cdnUrlLabel:"_cdnUrlLabel_pifvb_1043",cdnInput:"_cdnInput_pifvb_1049",titleIcon:"_titleIcon_pifvb_1056",qrcodeIcon:"_qrcodeIcon_pifvb_1065",iconMirror:"_iconMirror_pifvb_1092",approvalBell:"_approvalBell_pifvb_1097",approvalBellBadge:"_approvalBellBadge_pifvb_1122",disabledMenuItem:"_disabledMenuItem_pifvb_1140",currentProcessBtn:"_currentProcessBtn_pifvb_1145",proxySwapIcon:"_proxySwapIcon_pifvb_1150",fullWidthSelect:"_fullWidthSelect_pifvb_1155",proxyProfileTag:"_proxyProfileTag_pifvb_1160",proxyWarning:"_proxyWarning_pifvb_1174",proxyList:"_proxyList_pifvb_1184",proxyItem:"_proxyItem_pifvb_1190",proxyItemActive:"_proxyItemActive_pifvb_1202",proxyItemMain:"_proxyItemMain_pifvb_1207",proxyItemInfo:"_proxyItemInfo_pifvb_1215",proxyItemNameRow:"_proxyItemNameRow_pifvb_1221",proxyItemName:"_proxyItemName_pifvb_1221",proxyItemDetail:"_proxyItemDetail_pifvb_1233",proxyBuiltinTag:"_proxyBuiltinTag_pifvb_1242",proxyItemActions:"_proxyItemActions_pifvb_1252",proxyEditForm:"_proxyEditForm_pifvb_1258",proxyEditRow:"_proxyEditRow_pifvb_1266",proxyRequired:"_proxyRequired_pifvb_1276",proxyEditDivider:"_proxyEditDivider_pifvb_1281",proxyEditBtns:"_proxyEditBtns_pifvb_1286",themeToggle:"_themeToggle_pifvb_1297",themeToggleKnob:"_themeToggleKnob_pifvb_1325",themeToggleIcon:"_themeToggleIcon_pifvb_1355",headerRightRow:"_headerRightRow_pifvb_1360",headerCountdownTag:"_headerCountdownTag_pifvb_1366",memoryMarkdown:"_memoryMarkdown_pifvb_1388",memoryStatus:"_memoryStatus_pifvb_1468",memoryDirHint:"_memoryDirHint_pifvb_1472"};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:"Opus 4.7 (1M)",value:"opus-4.7-1m",tokens:1e6},{label:"Sonnet 4.6",value:"sonnet-4.6",tokens:2e5},{label:"GLM5",value:"glm5",tokens:2e5},{label:"Kimi K2.5",value:"kimi-k2.5",tokens:2e5},{label:"MiniMax 2.1",value:"minimax-2.1",tokens:2e5},{label:"Qwen 3.5",value:"Qwen 3.5",tokens:2e5}]},IS_MOBILE_PHONE=isMobile&&!isPad,CALIBRATION_MODELS=appConfig.calibrationModels;function CachePopoverContent({requests:requests=[],serverCachedContent:serverCachedContent,contextPercent:contextPercent=0,fsSkills:fsSkills,memory:memory,calibrationModel:calibrationModel="auto",onCalibrationModelChange:onCalibrationModelChange,onOpenMemoryDetail:onOpenMemoryDetail,onOpenSkillsModal:onOpenSkillsModal}){const[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.chipDetailBody,children:description}):jsxRuntimeExports.jsx("div",{className:`${styles.chipDetailBody} ${styles.chipDetailEmpty}`,children:t("ui.noDescription")}),renderMcpChip=({name:name,fullName:fullName,description:description})=>IS_MOBILE_PHONE?jsxRuntimeExports.jsx("span",{className:styles.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.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.toolChipGrid,children:builtin.map(({name:name,description:description})=>{const title2=[name,description].filter(Boolean).join("\n\n"),chip2=jsxRuntimeExports.jsx("span",{className:styles.cacheToolChip,title:title2,children:name});return jsxRuntimeExports.jsx(ConceptHelp,{doc:`Tool-${name}`,children:chip2},name)})}),mcpBody=jsxRuntimeExports.jsx("div",{className:styles.toolChipGridVertical,children:Array.from(mcpByServer.entries()).map(([server,tools])=>jsxRuntimeExports.jsxs("div",{className:styles.mcpServerGroup,children:[jsxRuntimeExports.jsxs("div",{className:styles.mcpServerName,children:[server," (",tools.length,")"]}),jsxRuntimeExports.jsx("div",{className:styles.toolChipGrid,children:tools.map(renderMcpChip)})]},server))}),skillsBody=jsxRuntimeExports.jsx("div",{className:styles.toolChipGrid,children:skills.map(({name:name,description:description})=>IS_MOBILE_PHONE?jsxRuntimeExports.jsx("span",{className:styles.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.cacheToolChip,children:name})},name))}),skillsAction=onOpenSkillsModal?jsxRuntimeExports.jsx(Button,{type:"primary",size:"small",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})(),memoryBody=null===memory?jsxRuntimeExports.jsx("div",{className:`${styles.cachePopoverEmpty} ${styles.memoryStatus}`,children:t("ui.memoryLoading")}):!1===memory?jsxRuntimeExports.jsx("div",{className:`${styles.cachePopoverEmpty} ${styles.memoryStatus}`,children:t("ui.memoryLoadError")}):memory.exists?memory.content&&memory.content.trim()?jsxRuntimeExports.jsx("div",{className:styles.memoryMarkdown,onClick:handleMemoryLinkClick,dangerouslySetInnerHTML:{__html:renderMarkdown(memory.content)}}):jsxRuntimeExports.jsxs("div",{className:`${styles.cachePopoverEmpty} ${styles.memoryStatus}`,children:[jsxRuntimeExports.jsx("div",{children:t("ui.memoryEmpty")}),jsxRuntimeExports.jsx("div",{className:styles.memoryDirHint,title:memory.indexPath,children:memory.indexPath})]}):jsxRuntimeExports.jsxs("div",{className:`${styles.cachePopoverEmpty} ${styles.memoryStatus}`,children:[jsxRuntimeExports.jsx("div",{children:t("ui.memoryNotFound")}),jsxRuntimeExports.jsx("div",{className:styles.memoryDirHint,title:memory.dir,children:memory.dir})]}),ctxColor=contextPercent>=80?"var(--color-error-light)":contextPercent>=60?"var(--color-warning-light)":"var(--color-success)";return jsxRuntimeExports.jsxs("div",{className:styles.cachePopover,children:[jsxRuntimeExports.jsx("div",{className:styles.cachePopoverHeader,children:jsxRuntimeExports.jsxs("div",{className:styles.cachePopoverTitle,children:[jsxRuntimeExports.jsxs("span",{className:styles.cachePercent,style:{color:ctxColor},children:[contextPercent,"%"]}),jsxRuntimeExports.jsx("span",{className:styles.cacheCalibrationLabel,children:t("ui.calibrationModelLabel")}),jsxRuntimeExports.jsx(Select,{size:"small",value:calibrationModel,onChange:onCalibrationModelChange,options:CALIBRATION_MODELS,className:styles.calibrationSelect,popupMatchSelectWidth:!1})]})}),jsxRuntimeExports.jsxs("div",{className:styles.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.cacheSection,children:[jsxRuntimeExports.jsxs("div",{className:styles.cacheSectionHeader,children:[jsxRuntimeExports.jsxs("button",{type:"button",className:styles.cacheSectionTitle,onClick:()=>setSectionCollapsed(prev=>({...prev,[sectionKey]:!collapsed})),"aria-expanded":!collapsed,children:[jsxRuntimeExports.jsx("span",{className:styles.cacheSectionArrow,children:collapsed?"▶":"▼"}),t(titleKey)," (",count,")"]}),rightAction]}),!collapsed&&body2]})})("tools_builtin","ui.builtinTools",builtin.length,!0,builtinBody),hasMcp&&jsxRuntimeExports.jsxs("div",{className:`${styles.cacheSection} ${styles.cacheSectionBordered}`,children:[jsxRuntimeExports.jsxs("div",{className:styles.cacheSectionLabel,children:[t("ui.mcpTools")," (",Array.from(mcpByServer.values()).reduce((n,arr)=>n+arr.length,0),")"]}),mcpBody]}),hasSkills&&jsxRuntimeExports.jsxs("div",{className:`${styles.cacheSection} ${styles.cacheSectionBordered}`,children:[jsxRuntimeExports.jsxs("div",{className:styles.cacheSectionHeader,children:[jsxRuntimeExports.jsxs("div",{className:styles.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]}),jsxRuntimeExports.jsxs("div",{className:`${styles.cacheSection} ${styles.cacheSectionBordered}`,children:[jsxRuntimeExports.jsxs("div",{className:styles.cacheSectionLabel,children:[t("ui.persistentMemory"),null!==memoryCount?` (${memoryCount})`:""]}),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.chipDetailBody,children:chipModal.description}):jsxRuntimeExports.jsx("div",{className:`${styles.chipDetailBody} ${styles.chipDetailEmpty}`,children:t("ui.noDescription")})})]})}function MemoryDetailModal({detail:detail2,onClose:onClose,onOpenMemoryDetail:onOpenMemoryDetail}){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 r=parseMemoryLink(a.getAttribute("href")||"");r.allow||(e.preventDefault(),r.open&&(null==onOpenMemoryDetail||onOpenMemoryDetail(r.open)))};let body2;return body2=loading2?jsxRuntimeExports.jsx("div",{className:styles.cachePopoverEmpty,children:t("ui.memoryLoading")}):error2?jsxRuntimeExports.jsxs("div",{className:styles.cachePopoverEmpty,children:[t("ui.memoryLoadError"),": ",error2]}):content2&&content2.trim()?jsxRuntimeExports.jsx("div",{className:styles.memoryMarkdown,onClick:handleLinkClick,dangerouslySetInnerHTML:{__html:renderMarkdown(content2)}}):jsxRuntimeExports.jsx("div",{className:styles.cachePopoverEmpty,children:t("ui.memoryEmpty")}),jsxRuntimeExports.jsx(Modal,{open:!0,title:name,onCancel:onClose,footer:null,width:720,zIndex:1100,destroyOnClose:!0,children:body2})}export{AppBase as A,ToolApprovalPanel as B,ConceptHelp as C,resolveTeammateNames as D,getModelShort as E,FullFileDiffView as F,formatRequestTag as G,renderMarkdown as H,ImageLightbox as I,restoreSlimmedEntry as J,stripPrivateKeys as K,isClaudeMdReminder as L,MemoryDetailModal as M,isSkillsReminder as N,OPTIMISTIC_CLEAR_PERCENT as O,hasClaudeMdReminder as P,hasSkillsReminder as Q,RefIcon as R,extractCachedContent as S,TerminalWsProvider as T,filterRelevantRequests as U,findPrevMainAgentTimestamp as V,ImageViewer as a,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$o as p,getEffectiveModel as q,getModelMaxTokens as r,styles as s,ApprovalModal as t,uploadFileAndGetPath as u,CachePopoverContent as v,RefIcon$5 as w,ChatView as x,TerminalPanel as y,OpenFolderIcon as z};
|