cc-viewer 1.5.42 → 1.5.43

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.
@@ -708,7 +708,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),kn=Pe,Jt=Ge),pt===void
708
708
  `),lineNums:$}}}}}else if(u.role==="assistant"&&Array.isArray(u.content)){for(const d of u.content)if(d.type==="tool_use"&&d.name==="Edit"&&d.input){const h=d.input.file_path,p=d.input.old_string,g=d.input.new_string;if(h&&p!=null&&g!=null&&s[h]){const v=s[h];i[d.id]={plainText:v.plainText,lineNums:v.lineNums.slice()};const $=v.plainText.indexOf(p);if($>=0){const _=v.plainText.substring(0,$).split(`
709
709
  `).length-1,Q=p.split(`
710
710
  `).length,x=g.split(`
711
- `).length,w=x-Q;if(v.plainText=v.plainText.substring(0,$)+g+v.plainText.substring($+p.length),w!==0){const C=v.lineNums[_]||_+1,T=[];for(let z=0;z<x;z++)T.push(C+z);v.lineNums=[...v.lineNums.slice(0,_),...T,...v.lineNums.slice(_+Q).map(z=>z+w)]}}}}}const o={},a={};for(const u of t)if(u.role==="user"&&Array.isArray(u.content)){for(const d of u.content)if(d.type==="tool_result"){const h=e[d.tool_use_id];if(h&&h.name==="AskUserQuestion"){const p=Fv(d);o[d.tool_use_id]=gYe(p)}if(h&&h.name==="ExitPlanMode"){const p=Fv(d);a[d.tool_use_id]=vYe(p)}}}return{toolUseMap:e,toolResultMap:n,readContentMap:r,editSnapshotMap:i,askAnswerMap:o,planApprovalMap:a}}function gYe(t){const e={},n=/"([^"]+)"="([^"]*)"/g;let r;for(;(r=n.exec(t))!==null;)e[r[1]]=r[2];return e}function vYe(t){if(!t)return{status:"pending"};if(/User has approved/i.test(t))return{status:"approved"};if(/User rejected/i.test(t)){const e=t.match(/feedback:\s*(.+)/i)||t.match(/User rejected[^:]*:\s*(.+)/i);return{status:"rejected",feedback:e?e[1].trim():""}}return{status:"pending"}}class gM extends ne.Component{constructor(n){super(n);Qt(this,"handleStickToBottom",()=>{this.setState({stickyBottom:!0},()=>{const n=this.containerRef.current;n&&(n.scrollTop=n.scrollHeight)})});Qt(this,"handleLoadMore",()=>{this._mobileExtraItems+=pYe;const n=this.containerRef.current,r=n?n.scrollHeight:0,i=n?n.scrollTop:0,s=this.buildAllItems(),o=this._applyMobileSlice(s);this.setState({allItems:o,visibleCount:o.length},()=>{if(n){const a=n.scrollHeight;n.scrollTop=i+(a-r)}})});Qt(this,"handlePromptOptionClick",n=>{const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN)return;const i=this.state.ptyPrompt;if(!i)return;const s=i.options,o=s.findIndex(h=>h.number===n);let a=s.findIndex(h=>h.selected);a<0&&(a=0);const l=o-a,c=l>0?"\x1B[B":"\x1B[A",u=Math.abs(l),d=h=>{h<u?(r.send(JSON.stringify({type:"input",data:c})),setTimeout(()=>d(h+1),30)):setTimeout(()=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:"input",data:"\r"}))},50)};d(0),this.setState(h=>{const p=h.ptyPromptHistory.slice(),g=p[p.length-1];return g&&g.status==="active"&&(p[p.length-1]={...g,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:p}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});Qt(this,"handlePlanFeedbackSubmit",(n,r)=>{const i=this._inputWs;if(!i||i.readyState!==WebSocket.OPEN)return;const s=this.state.ptyPrompt;if(!s)return;const o=s.options,a=o.findIndex(p=>p.number===n);let l=o.findIndex(p=>p.selected);l<0&&(l=0);const c=a-l,u=c>0?"\x1B[B":"\x1B[A",d=Math.abs(c),h=p=>{p<d?(i.send(JSON.stringify({type:"input",data:u})),setTimeout(()=>h(p+1),30)):setTimeout(()=>{i.send(JSON.stringify({type:"input",data:"\r"}));const g=this._ptyBuffer;let v=0;const $=()=>{if(v++,v>20||this._ptyBuffer!==g){i.readyState===WebSocket.OPEN&&(i.send(JSON.stringify({type:"input",data:r})),setTimeout(()=>{i.send(JSON.stringify({type:"input",data:"\r"}))},50));return}setTimeout($,100)};setTimeout($,100)},50)};h(0),this.setState(p=>{const g=p.ptyPromptHistory.slice(),v=g[g.length-1];return v&&v.status==="active"&&(g[g.length-1]={...v,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:g}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});Qt(this,"handleAskQuestionSubmit",n=>{if(!this._inputWs||this._inputWs.readyState!==WebSocket.OPEN){this._askAnswerQueue=[...n],this._askSubmitting=!0,this.connectInputWs(),this._askWsRetries=0,this._waitForWsAndSubmit();return}if(this._askAnswerQueue=[...n],this._askSubmitting=!0,!this.state.ptyPrompt){this._askPromptRetries=0,this._waitForPtyPromptAndSubmit();return}this._processNextAskAnswer()});Qt(this,"handleInputSend",()=>{const n=this._inputRef.current;if(!n)return;const r=n.value.trim();r&&this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&(this._inputWs.send(JSON.stringify({type:"input",data:r})),setTimeout(()=>{this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:"\r"}))},50),n.value="",n.style.height="auto",this.setState({inputEmpty:!0,pendingInput:r,inputSuggestion:null},()=>this.scrollToBottom()))});Qt(this,"handleInputKeyDown",n=>{if(n.key==="Tab"&&this.state.inputSuggestion){n.preventDefault();const r=this._inputRef.current;r&&(r.value=this.state.inputSuggestion,r.style.height="auto",r.style.height=Math.min(r.scrollHeight,120)+"px"),this.setState({inputSuggestion:null,inputEmpty:!1});return}n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleInputSend())});Qt(this,"handleInputChange",n=>{const r=n.target;r.style.height="auto",r.style.height=Math.min(r.scrollHeight,120)+"px";const i=!r.value.trim();this.setState({inputEmpty:i}),this.state.inputSuggestion&&!i&&this.setState({inputSuggestion:null})});Qt(this,"handleSuggestionToTerminal",()=>{const n=this.state.inputSuggestion;!n||!this._inputWs||this._inputWs.readyState!==WebSocket.OPEN||(this._inputWs.send(JSON.stringify({type:"input",data:n})),setTimeout(()=>{this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:"\r"}))},50),this.setState({inputSuggestion:null,pendingInput:n},()=>this.scrollToBottom()))});Qt(this,"handleSplitMouseDown",n=>{n.preventDefault(),this._resizing=!0;const i=!window.location.search.includes("token=");let s=[];if(i){const l=this.innerSplitRef.current;if(l){const u=l.getBoundingClientRect().width,d=7.8,h=[60,80,100,120],p=5;s=h.map(g=>{const v=g*d,$=v+p;if($>u*.75||$<u*.15)return null;const S=u-v-p;return{cols:g,terminalPx:v,linePosition:S}}).filter(g=>g!==null)}}this.setState({isDragging:!0,snapLines:s});const o=l=>{if(!this._resizing)return;const c=this.innerSplitRef.current;if(!c)return;const u=c.getBoundingClientRect(),d=u.width;let h=u.right-l.clientX;h=Math.max(200,Math.min(d*.75,h));let p=null;if(i&&s.length>0){let v=1/0,$=null;for(const S of s){const _=Math.abs(l.clientX-u.left-S.linePosition);_<v&&(v=_,$=S)}$&&v<60&&(p=$)}this.setState({terminalWidth:h,activeSnapLine:p})},a=()=>{if(this._resizing=!1,i&&this.state.activeSnapLine){const l=this.state.activeSnapLine.terminalPx;localStorage.setItem("cc-viewer-terminal-width",l.toString()),this.setState({terminalWidth:l,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",o),document.removeEventListener("mouseup",a),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",o),document.addEventListener("mouseup",a),document.body.style.cursor="col-resize",document.body.style.userSelect="none"});Qt(this,"handleToggleExpandPath",n=>{this.setState(r=>{const i=new Set(r.fileExplorerExpandedPaths);return i.has(n)?i.delete(n):i.add(n),{fileExplorerExpandedPaths:i}})});this.containerRef=ne.createRef(),this.splitContainerRef=ne.createRef(),this.innerSplitRef=ne.createRef();const r=localStorage.getItem("cc-viewer-terminal-width"),i=r?parseFloat(r):null;this.state={visibleCount:0,loading:!1,allItems:[],highlightTs:null,highlightFading:!1,terminalWidth:i||468,needsInitialSnap:i===null,inputEmpty:!0,pendingInput:null,stickyBottom:!0,ptyPrompt:null,ptyPromptHistory:[],inputSuggestion:null,fileExplorerOpen:localStorage.getItem("ccv_fileExplorerOpen")!=="false",currentFile:null,currentGitDiff:null,scrollToLine:null,fileExplorerExpandedPaths:new Set,gitChangesOpen:!1,snapLines:[],activeSnapLine:null,isDragging:!1,fileVersion:0,editorSessionId:null,editorFilePath:null,fileExplorerRefresh:0,gitChangesRefresh:0},this._processedToolIds=new Set,this._fileRefreshTimer=null,this._gitRefreshTimer=null,this._queueTimer=null,this._prevItemsLen=0,this._scrollTargetIdx=null,this._scrollTargetRef=ne.createRef(),this._scrollFadeTimer=null,this._resizing=!1,this._inputWs=null,this._inputRef=ne.createRef(),this._ptyBuffer="",this._ptyDebounceTimer=null,this._mobileExtraItems=0,this._mobileSliceOffset=0,this._totalItemCount=0}_setFileExplorerOpen(n){localStorage.setItem("ccv_fileExplorerOpen",String(n)),this.setState({fileExplorerOpen:n})}_checkToolFileChanges(){var s,o;const n=this.props.mainAgentSessions;if(!n||n.length===0)return;let r=!1,i=!1;for(const a of n){const l=[];if((o=(s=a.response)==null?void 0:s.body)!=null&&o.content&&l.push(a.response.body.content),Array.isArray(a.messages))for(const c of a.messages)c.role==="assistant"&&Array.isArray(c.content)&&l.push(c.content);for(const c of l)for(const u of c){if(u.type!=="tool_use"||!u.id||this._processedToolIds.has(u.id))continue;this._processedToolIds.add(u.id);const d=u.name;let h=u.input;if(typeof h=="string")try{h=JSON.parse(h.replace(/^\[object Object\]/,""))}catch{h={}}d==="Write"?(r=!0,i=!0):d==="Edit"||d==="NotebookEdit"?i=!0:d==="Bash"&&h&&h.command&&fYe(h.command)&&(r=!0,i=!0)}}r&&this.state.fileExplorerOpen&&(clearTimeout(this._fileRefreshTimer),this._fileRefreshTimer=setTimeout(()=>{this.setState(a=>({fileExplorerRefresh:a.fileExplorerRefresh+1}))},500)),i&&this.state.gitChangesOpen&&(clearTimeout(this._gitRefreshTimer),this._gitRefreshTimer=setTimeout(()=>{this.setState(a=>({gitChangesRefresh:a.gitChangesRefresh+1}))},500))}componentDidMount(){this.startRender(),this.props.cliMode&&this.connectInputWs(),this._bindStickyScroll(),this.state.needsInitialSnap&&this.props.cliMode&&this.props.terminalVisible&&this._snapToInitialPosition()}componentDidUpdate(n){if(n.mainAgentSessions!==this.props.mainAgentSessions)Cr&&(this._mobileExtraItems=0),this.startRender(),this.state.pendingInput&&this.setState({pendingInput:null}),this._updateSuggestion(),this._checkToolFileChanges();else if(n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking){const r=this.buildAllItems(),i=this._applyMobileSlice(r);this.setState({allItems:i,visibleCount:i.length})}if(!n.scrollToTimestamp&&this.props.scrollToTimestamp)if(Cr&&this.props.scrollToTimestamp){const r=this.buildAllItems(),i=this._scrollTargetIdx;if(i!=null){const o=Gx+this._mobileExtraItems,a=r.length>o?r.length-o:0;i<a&&(this._mobileExtraItems=r.length-i-Gx,this._mobileExtraItems<0&&(this._mobileExtraItems=0))}const s=this._applyMobileSlice(r);this.setState({allItems:s,visibleCount:s.length},()=>this.scrollToBottom())}else{const r=this.buildAllItems(),i=this._applyMobileSlice(r);this.setState({allItems:i,visibleCount:i.length},()=>this.scrollToBottom())}Cr&&this.props.mobileChatVisible&&!n.mobileChatVisible&&requestAnimationFrame(()=>{const r=this.containerRef.current;r&&(r.scrollTop=r.scrollHeight)}),!n.cliMode&&this.props.cliMode&&this.connectInputWs(),this._rebindStickyEl()}componentWillUnmount(){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._unbindScrollFade(),this._unbindStickyScroll(),this._inputWs&&(this._inputWs.close(),this._inputWs=null)}startRender(){this._queueTimer&&clearTimeout(this._queueTimer);const n=this.buildAllItems(),r=this._applyMobileSlice(n),i=this._prevItemsLen;this._prevItemsLen=r.length;const s=r.length-i;if(s<=0||i>0&&s<=3){this.setState({allItems:r,visibleCount:r.length,loading:!1},()=>this.scrollToBottom());return}if(r.length>uYe)this.setState({allItems:r,visibleCount:0,loading:!0}),this._queueTimer=setTimeout(()=>{this.setState({visibleCount:r.length,loading:!1},()=>this.scrollToBottom())},300);else{const o=Math.max(0,i);this.setState({allItems:r,visibleCount:o,loading:!1}),this.queueNext(o,r.length)}}queueNext(n,r){n>=r||(this._queueTimer=setTimeout(()=>{this.setState({visibleCount:n+1},()=>{this.scrollToBottom(),this.queueNext(n+1,r)})},mYe()))}_isNearBottom(){const n=this.containerRef.current;return n?n.scrollHeight-n.scrollTop-n.clientHeight<=30:!0}scrollToBottom(){if(this._scrollTargetRef.current){const n=this._scrollTargetRef.current,r=this.containerRef.current;r&&n.offsetHeight>r.clientHeight?n.scrollIntoView({block:"start",behavior:"instant"}):n.scrollIntoView({block:"center",behavior:"instant"});const i=this.props.scrollToTimestamp;this._scrollTargetRef=ne.createRef(),i&&(this.setState({highlightTs:i,highlightFading:!1}),this._bindScrollFade()),this.props.onScrollTsDone&&this.props.onScrollTsDone();return}if(this.state.stickyBottom){const n=this.containerRef.current;n&&(n.scrollTop=n.scrollHeight)}}_bindStickyScroll(){this._stickyScrollRafId=null,this._onStickyScroll=()=>{this._stickyScrollLock||this._stickyScrollRafId||(this._stickyScrollRafId=requestAnimationFrame(()=>{this._stickyScrollRafId=null;const n=this.containerRef.current;if(!n)return;const r=n.scrollHeight-n.scrollTop-n.clientHeight;this.state.stickyBottom&&r>30?this.setState({stickyBottom:!1}):!this.state.stickyBottom&&r<=5&&this.setState({stickyBottom:!0})}))},this._rebindStickyEl()}_rebindStickyEl(){const n=this.containerRef.current;n!==this._stickyBoundEl&&(this._stickyBoundEl&&this._stickyBoundEl.removeEventListener("scroll",this._onStickyScroll),this._stickyBoundEl=n,n&&n.addEventListener("scroll",this._onStickyScroll,{passive:!0}))}_unbindStickyScroll(){this._stickyBoundEl&&this._onStickyScroll&&(this._stickyBoundEl.removeEventListener("scroll",this._onStickyScroll),this._stickyBoundEl=null),this._stickyScrollRafId&&(cancelAnimationFrame(this._stickyScrollRafId),this._stickyScrollRafId=null)}_bindScrollFade(){this._unbindScrollFade();const n=this.containerRef.current;n&&(this._scrollFadeIgnoreFirst=!0,this._onScrollFade=()=>{if(this._scrollFadeIgnoreFirst){this._scrollFadeIgnoreFirst=!1;return}this.setState({highlightFading:!0}),this._fadeClearTimer=setTimeout(()=>{this.setState({highlightTs:null,highlightFading:!1})},2e3),this._unbindScrollFade()},n.addEventListener("scroll",this._onScrollFade,{passive:!0}))}_unbindScrollFade(){this._onScrollFade&&this.containerRef.current&&(this.containerRef.current.removeEventListener("scroll",this._onScrollFade),this._onScrollFade=null)}renderSessionMessages(n,r,i,s){const{userProfile:o,collapseToolResults:a,expandThinking:l,onViewRequest:c}=this.props,{toolResultMap:u,readContentMap:d,editSnapshotMap:h,askAnswerMap:p,planApprovalMap:g}=mM(n),v=this.props.cliMode&&this.state.ptyPromptHistory.slice().reverse().find(Q=>z$(Q)&&Q.status==="active")||null;let $=null,S=null;for(const Q of n)if(Q.role==="assistant"&&Array.isArray(Q.content))for(const x of Q.content){if(x.type==="tool_use"&&x.name==="ExitPlanMode"){const w=g[x.id];(!w||w.status==="pending")&&($=x.id)}if(x.type==="tool_use"&&x.name==="AskUserQuestion"){const w=p[x.id];(!w||Object.keys(w).length===0)&&(S=x.id)}}const _=[];for(let Q=0;Q<n.length;Q++){const x=n[Q],w=x.content,C=x._timestamp||null,T=C?s[C]:void 0,z=T!=null&&c?{requestIndex:T,onViewRequest:c}:{};if(x.role==="user"){if(Array.isArray(w)){const E=w.find(N=>N.type==="text"&&/^\[SUGGESTION MODE:/i.test((N.text||"").trim())),L=w.filter(N=>N.type==="tool_result");if(!(E&&L.length>0)){const{commands:N,textBlocks:X,skillBlocks:R}=tk(w);for(let k=0;k<N.length;k++)_.push(y.jsx(il,{role:"user",text:N[k],timestamp:C,userProfile:o,modelInfo:i,...z},`${r}-cmd-${Q}-${k}`));for(const k of R){const j=k.text.match(/^#\s+(.+)$/m),A=j?j[1]:"Skill";_.push(y.jsx(il,{role:"skill-loaded",text:k.text,skillName:A,timestamp:C,...z},`${r}-skill-${Q}`))}for(let k=0;k<X.length;k++){const j=/^Implement the following plan:/i.test((X[k].text||"").trim());_.push(y.jsx(il,{role:j?"plan-prompt":"user",text:X[k].text,timestamp:C,userProfile:o,modelInfo:i,...z},`${r}-user-${Q}-${k}`))}}}else if(typeof w=="string"&&!rb(w)){const E=/^Implement the following plan:/i.test(w.trim());_.push(y.jsx(il,{role:E?"plan-prompt":"user",text:w,timestamp:C,userProfile:o,modelInfo:i,...z},`${r}-user-${Q}`))}}else x.role==="assistant"&&(Array.isArray(w)?_.push(y.jsx(il,{role:"assistant",content:w,toolResultMap:u,readContentMap:d,editSnapshotMap:h,askAnswerMap:p,planApprovalMap:g,timestamp:C,modelInfo:i,collapseToolResults:a,expandThinking:l,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:v,lastPendingPlanId:$,lastPendingAskId:S,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,...z},`${r}-asst-${Q}`)):typeof w=="string"&&_.push(y.jsx(il,{role:"assistant",content:[{type:"text",text:w}],toolResultMap:u,readContentMap:d,editSnapshotMap:h,askAnswerMap:p,planApprovalMap:g,timestamp:C,modelInfo:i,collapseToolResults:a,expandThinking:l,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:v,lastPendingPlanId:$,lastPendingAskId:S,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,...z},`${r}-asst-${Q}`)))}return _}buildAllItems(){var v,$,S,_;const{mainAgentSessions:n,requests:r,collapseToolResults:i,expandThinking:s,onViewRequest:o}=this.props;if(!n||n.length===0)return[];const a={};if(r)for(let Q=0;Q<r.length;Q++)Ii(r[Q])&&r[Q].timestamp&&(a[r[Q].timestamp]=Q);let l=null;if(r){for(let Q=r.length-1;Q>=0;Q--)if(Ii(r[Q])&&((v=r[Q].body)!=null&&v.model)){l=r[Q].body.model;break}}const c=l0e(l),u=[],d={},h=[];if(r)for(let Q=0;Q<r.length;Q++){const x=r[Q];if(!x.timestamp)continue;const w=Ad(x,r[Q+1]);if(w.type==="SubAgent"){const C=(S=($=x.response)==null?void 0:$.body)==null?void 0:S.content;if(Array.isArray(C)&&C.length>0){const T=mM(((_=x.body)==null?void 0:_.messages)||[]).toolResultMap;h.push({timestamp:x.timestamp,content:C,toolResultMap:T,label:$P(w.type,w.subType),requestIndex:Q})}}}let p=0;n.forEach((Q,x)=>{var C,T,z,E;x>0&&u.push(y.jsx(UX,{style:{borderColor:"#333",margin:"16px 0"},children:y.jsx(pM,{className:Nn.sessionDividerText,children:"Session"})},`session-div-${x}`));const w=this.renderSessionMessages(Q.messages,`s${x}`,c,a);for(const L of w){const N=L.props.timestamp;for(;p<h.length&&N&&h[p].timestamp<=N;){const X=h[p];X.timestamp&&(d[X.timestamp]=u.length),u.push(y.jsx(il,{role:"sub-agent-chat",content:X.content,toolResultMap:X.toolResultMap,label:X.label,timestamp:X.timestamp,collapseToolResults:i,expandThinking:s,requestIndex:X.requestIndex,onViewRequest:o},`sub-chat-${p}`)),p++}N&&(d[N]=u.length),u.push(L)}for(;p<h.length;){const L=h[p],N=x<n.length-1&&((T=(C=n[x+1].messages)==null?void 0:C[0])==null?void 0:T._timestamp);if(N&&L.timestamp>N)break;L.timestamp&&(d[L.timestamp]=u.length),u.push(y.jsx(il,{role:"sub-agent-chat",content:L.content,toolResultMap:L.toolResultMap,label:L.label,timestamp:L.timestamp,collapseToolResults:i,expandThinking:s,requestIndex:L.requestIndex,onViewRequest:o},`sub-chat-${p}`)),p++}if(x===n.length-1&&((E=(z=Q.response)==null?void 0:z.body)!=null&&E.content)){const L=Q.response.body.content;if(Array.isArray(L)){u.push(y.jsx(ne.Fragment,{children:y.jsx(UX,{style:{borderColor:"#2a2a2a",margin:"8px 0"},children:y.jsx(pM,{type:"secondary",className:Nn.lastResponseLabel,children:ie("ui.lastResponse")})})},"resp-divider")),Q.entryTimestamp&&(d[Q.entryTimestamp]=u.length);let N=null;for(const X of L)X.type==="tool_use"&&X.name==="AskUserQuestion"&&(N=X.id);u.push(y.jsx(il,{role:"assistant",content:L,timestamp:Q.entryTimestamp,modelInfo:c,collapseToolResults:i,expandThinking:s,toolResultMap:{},askAnswerMap:{},lastPendingAskId:N,cliMode:this.props.cliMode,onAskQuestionSubmit:this.handleAskQuestionSubmit},"resp-asst"))}}});const{scrollToTimestamp:g}=this.props;return this._scrollTargetIdx=g&&d[g]!=null?d[g]:null,this._tsItemMap=d,u}_applyMobileSlice(n){if(!Cr)return this._mobileSliceOffset=0,this._totalItemCount=n.length,n;this._totalItemCount=n.length;const r=Gx+this._mobileExtraItems;if(n.length<=r)return this._mobileSliceOffset=0,n;const i=n.length-r;if(this._mobileSliceOffset=i,this._scrollTargetIdx!=null&&(this._scrollTargetIdx-=i,this._scrollTargetIdx<0&&(this._scrollTargetIdx=null)),this._tsItemMap){const s={};for(const[o,a]of Object.entries(this._tsItemMap)){const l=a-i;l>=0&&(s[o]=l)}this._tsItemMap=s}return n.slice(i)}_extractSuggestion(){var h;const{mainAgentSessions:n}=this.props;if(!(n!=null&&n.length))return null;const r=n[n.length-1],i=r==null?void 0:r.messages;if(!Array.isArray(i)||i.length===0)return null;const s=i[i.length-1];if((s==null?void 0:s.role)!=="user")return null;const o=s.content;if(!(Array.isArray(o)?o.some(p=>p.type==="text"&&/^\[SUGGESTION MODE:/i.test((p.text||"").trim())):typeof o=="string"&&/^\[SUGGESTION MODE:/im.test(o.trim())))return null;const l=r==null?void 0:r.response;if(!l)return null;const c=l.body;if(!c)return null;const u=c.stop_reason;if(u!=="end_turn"&&u!=="max_tokens")return null;const d=c.content;if(!Array.isArray(d))return null;for(let p=d.length-1;p>=0;p--)if(d[p].type==="text"&&((h=d[p].text)!=null&&h.trim()))return d[p].text.trim();return null}_updateSuggestion(){const n=this._extractSuggestion();this.setState({inputSuggestion:n||null})}connectInputWs(){const r=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal`;this._inputWs=new WebSocket(r),this._inputWs.onmessage=i=>{try{const s=JSON.parse(i.data);s.type==="data"?this._appendPtyData(s.data):s.type==="exit"&&this._clearPtyPrompt()}catch{}},this._inputWs.onclose=()=>{setTimeout(()=>{this.splitContainerRef.current&&this.props.cliMode&&this.connectInputWs()},2e3)}}_stripAnsi(n){return n.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(n){const r=this._stripAnsi(n);this._ptyBuffer+=r,this._ptyBuffer.length>4096&&(this._ptyBuffer=this._ptyBuffer.slice(-4096)),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._ptyDebounceTimer=setTimeout(()=>this._detectPrompt(),200)}_detectPrompt(){const r=this._ptyBuffer.match(/([^\n]*\?)\s*\n((?:\s*[❯>]?\s*\d+\.\s+[^\n]+\n?){2,})$/);if(r){const i=r[1].trim(),o=r[2].match(/\s*([❯>])?\s*(\d+)\.\s+([^\n]+)/g);if(o){const a=o.map(u=>{const d=u.match(/\s*([❯>])?\s*(\d+)\.\s+(.+)/);return{number:parseInt(d[2],10),text:d[3].trim(),selected:!!d[1]}}),l=this.state.ptyPrompt,c={question:i,options:a};l&&l.question===i?this.setState({ptyPrompt:c}):(this.setState(u=>{const d=u.ptyPromptHistory.slice();if(u.ptyPrompt){const h=d[d.length-1];h&&h.status==="active"&&(d[d.length-1]={...h,status:"dismissed"})}return d.push({...c,status:"active",selectedNumber:null,timestamp:new Date().toISOString()}),{ptyPrompt:c,ptyPromptHistory:d}}),this.scrollToBottom());return}}if(this.state.ptyPrompt){if(z$(this.state.ptyPrompt)||this._askSubmitting)return;this.setState(i=>{const s=i.ptyPromptHistory.slice(),o=s[s.length-1];return o&&o.status==="active"&&(s[s.length-1]={...o,status:"dismissed"}),{ptyPrompt:null,ptyPromptHistory:s}})}}_clearPtyPrompt(){this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this.state.ptyPrompt&&this.setState({ptyPrompt:null})}_waitForWsAndSubmit(){if(this._askWsRetries=(this._askWsRetries||0)+1,this._askWsRetries>30){this._askSubmitting=!1,this._askAnswerQueue=[];return}if(this._inputWs&&this._inputWs.readyState===WebSocket.OPEN){this.state.ptyPrompt?this._processNextAskAnswer():(this._askPromptRetries=0,this._waitForPtyPromptAndSubmit());return}setTimeout(()=>this._waitForWsAndSubmit(),100)}_waitForPtyPromptAndSubmit(){if(this._askPromptRetries=(this._askPromptRetries||0)+1,this._askPromptRetries>50){this._processNextAskAnswer();return}if(this.state.ptyPrompt){this._processNextAskAnswer();return}setTimeout(()=>this._waitForPtyPromptAndSubmit(),100)}_processNextAskAnswer(){if(!this._askAnswerQueue||this._askAnswerQueue.length===0){this._askSubmitting=!1;return}const n=this._askAnswerQueue.shift();n.type==="other"?this._submitOtherAnswer(n):n.type==="multi"?this._submitMultiSelectAnswer(n):this._submitSingleSelectAnswer(n)}_submitSingleSelectAnswer(n){const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN){this._askSubmitting=!1;return}const i=this.state.ptyPrompt,s=n.optionIndex+1;let o,a;if(i&&i.options){const h=i.options;o=h.findIndex(p=>p.number===s),o<0&&(o=n.optionIndex),a=h.findIndex(p=>p.selected),a<0&&(a=0)}else o=n.optionIndex,a=0;const l=o-a,c=l>0?"\x1B[B":"\x1B[A",u=Math.abs(l),d=h=>{h<u?(r.send(JSON.stringify({type:"input",data:c})),setTimeout(()=>d(h+1),30)):setTimeout(()=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:"input",data:"\r"})),this._finishCurrentAskAnswer()},50)};d(0)}_submitMultiSelectAnswer(n){const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN){this._askSubmitting=!1;return}const i=this.state.ptyPrompt,s=(n.selectedIndices||[]).slice().sort((l,c)=>l-c);let o=0;i&&i.options&&(o=i.options.findIndex(l=>l.selected),o<0&&(o=0));const a=l=>{if(l>=s.length){setTimeout(()=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:"input",data:"\r"})),this._finishCurrentAskAnswer()},50);return}const c=s[l],u=c-o,d=u>0?"\x1B[B":"\x1B[A",h=Math.abs(u),p=g=>{g<h?(r.send(JSON.stringify({type:"input",data:d})),setTimeout(()=>p(g+1),30)):setTimeout(()=>{r.send(JSON.stringify({type:"input",data:" "})),o=c,setTimeout(()=>a(l+1),50)},50)};p(0)};a(0)}_submitOtherAnswer(n){const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN){this._askSubmitting=!1;return}const i=this.state.ptyPrompt,s=n.optionIndex;let o=0;i&&i.options&&(o=i.options.findIndex(d=>d.selected),o<0&&(o=0));const a=s-o,l=a>0?"\x1B[B":"\x1B[A",c=Math.abs(a),u=d=>{d<c?(r.send(JSON.stringify({type:"input",data:l})),setTimeout(()=>u(d+1),30)):setTimeout(()=>{r.send(JSON.stringify({type:"input",data:"\r"}));const h=this._ptyBuffer;let p=0;const g=()=>{if(p++,p>20||this._ptyBuffer!==h){r.readyState===WebSocket.OPEN&&(r.send(JSON.stringify({type:"input",data:n.text})),setTimeout(()=>{r.send(JSON.stringify({type:"input",data:"\r"})),this._finishCurrentAskAnswer()},50));return}setTimeout(g,100)};setTimeout(g,100)},50)};u(0)}_finishCurrentAskAnswer(){if(this.setState(n=>{const r=n.ptyPromptHistory.slice(),i=r[r.length-1];return i&&i.status==="active"&&(r[r.length-1]={...i,status:"answered"}),{ptyPrompt:null,ptyPromptHistory:r}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._askAnswerQueue&&this._askAnswerQueue.length>0){let n=0;const r=()=>{if(n++,n>100){this._askSubmitting=!1,this._askAnswerQueue=[];return}if(this.state.ptyPrompt){this._processNextAskAnswer();return}setTimeout(r,100)};setTimeout(r,200)}else this._askSubmitting=!1}_snapToInitialPosition(){this.setState({terminalWidth:468,needsInitialSnap:!1}),localStorage.setItem("cc-viewer-terminal-width","468")}render(){const{mainAgentSessions:n,cliMode:r,terminalVisible:i}=this.props,{allItems:s,visibleCount:o,loading:a,terminalWidth:l}=this.state,c=!n||n.length===0;if(c&&!r)return y.jsx("div",{className:Nn.centerEmpty,children:y.jsx(vs,{description:ie("ui.noChat")})});if(a&&!r)return y.jsx("div",{className:Nn.centerEmpty,children:y.jsx(Ua,{size:"large"})});const u=this._scrollTargetIdx,{highlightTs:d,highlightFading:h}=this.state,p=d&&this._tsItemMap&&this._tsItemMap[d]!=null?this._tsItemMap[d]:null,g=s.slice(0,o),{pendingInput:v,stickyBottom:$,ptyPromptHistory:S}=this.state,_=r&&v?y.jsx(il,{role:"user",text:v,timestamp:new Date().toISOString(),userProfile:this.props.userProfile},"pending-input"):null,Q=$?null:y.jsxs("button",{className:Nn.stickyBottomBtn,onClick:this.handleStickToBottom,children:[y.jsx("span",{children:ie("ui.stickyBottom")}),y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:y.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),x=r&&S.length>0?S.filter(T=>!(z$(T)&&T.status==="active")).map((T,z)=>{const E=T.status==="active",L=T.status==="answered";return y.jsxs("div",{className:`${Nn.ptyPromptBubble}${E?"":" "+Nn.ptyPromptResolved}`,children:[y.jsx("div",{className:Nn.ptyPromptQuestion,children:T.question}),y.jsx("div",{className:Nn.ptyPromptOptions,children:T.options.map(N=>{const X=L&&T.selectedNumber===N.number;let R=Nn.ptyPromptOption;return E&&N.selected&&(R=Nn.ptyPromptOptionPrimary),X&&(R=Nn.ptyPromptOptionChosen),!E&&!X&&(R=Nn.ptyPromptOptionDimmed),y.jsxs("button",{className:R,disabled:!E,onClick:E?()=>this.handlePromptOptionClick(N.number):void 0,children:[N.number,". ",N.text]},N.number)})})]},`pty-prompt-${z}`)}):null,w=Cr&&this._mobileSliceOffset>0?y.jsx("div",{className:Nn.loadMoreWrap,children:y.jsx("button",{className:Nn.loadMoreBtn,onClick:this.handleLoadMore,children:ie("ui.loadMoreHistory",{count:this._mobileSliceOffset})})}):null,C=c||a?y.jsxs("div",{className:Nn.messageListWrap,children:[y.jsxs("div",{ref:this.containerRef,className:Nn.container,children:[!r||a?y.jsx("div",{className:Nn.centerEmpty,children:a?y.jsx(Ua,{size:"large"}):y.jsx(vs,{description:ie("ui.noChat")})}):null,_,x]}),Q]}):y.jsxs("div",{className:Nn.messageListWrap,children:[y.jsxs("div",{ref:this.containerRef,className:Nn.container,children:[w,g.map((T,z)=>{const E=z===u,L=z===p;let N=T;return L&&(N=ne.cloneElement(N,{highlight:h?"fading":"active"})),E?y.jsx("div",{ref:this._scrollTargetRef,children:N},T.key+"-anchor"):N}),_,x]}),Q]});return r?y.jsxs("div",{ref:this.splitContainerRef,className:Nn.splitContainer,children:[y.jsxs("div",{className:Nn.navSidebar,children:[y.jsx("button",{className:this.state.fileExplorerOpen?Nn.navBtnActive:Nn.navBtn,onClick:()=>{this._setFileExplorerOpen(!this.state.fileExplorerOpen),this.setState({gitChangesOpen:!1})},title:ie("ui.fileExplorer"),children:y.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:y.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"})})}),y.jsx("button",{className:this.state.gitChangesOpen?Nn.navBtnActive:Nn.navBtn,onClick:()=>this.setState(T=>(this._setFileExplorerOpen(!1),{gitChangesOpen:!T.gitChangesOpen})),title:ie("ui.gitChanges"),children:y.jsx("svg",{width:"24",height:"24",viewBox:"0 0 1024 1024",fill:"currentColor",children:y.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"})})})]}),y.jsxs("div",{style:{flex:1,display:"flex",minWidth:0,position:"relative"},ref:this.innerSplitRef,children:[this.state.isDragging&&this.state.activeSnapLine&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const L=T.getBoundingClientRect().width-this.state.terminalWidth-5,N=this.state.activeSnapLine.linePosition,X=Math.min(L,N),R=Math.abs(N-L);return y.jsx("div",{className:Nn.snapPreview,style:{left:`${X}px`,width:`${R}px`}})})(),this.state.isDragging&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const L=T.getBoundingClientRect().width-this.state.terminalWidth-5,N=[...this.state.snapLines].map(k=>({...k,dist:Math.abs(k.linePosition-L)})).sort((k,j)=>k.dist-j.dist);if(N.length===0)return null;const X=N[0],R=this.state.activeSnapLine&&this.state.activeSnapLine.cols===X.cols;return y.jsx("div",{className:R?Nn.snapLineActive:Nn.snapLine,style:{left:`${X.linePosition}px`}},X.cols)})(),this.state.fileExplorerOpen&&y.jsx(QTe,{refreshTrigger:this.state.fileExplorerRefresh,onClose:()=>this._setFileExplorerOpen(!1),onFileClick:T=>this.setState({currentFile:T,currentGitDiff:null,scrollToLine:null}),expandedPaths:this.state.fileExplorerExpandedPaths,onToggleExpand:this.handleToggleExpandPath,currentFile:this.state.currentFile}),this.state.gitChangesOpen&&y.jsx(ULe,{refreshTrigger:this.state.gitChangesRefresh,onClose:()=>this.setState({gitChangesOpen:!1}),onFileClick:T=>this.setState({currentGitDiff:T,currentFile:null})}),y.jsx("div",{className:Nn.chatSection,style:{flex:1,minWidth:0,display:"flex"},children:y.jsxs("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[this.state.currentGitDiff&&y.jsx("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",flexDirection:"column"},children:y.jsx(CVe,{filePath:this.state.currentGitDiff,onClose:()=>this.setState({currentGitDiff:null}),onOpenFile:(T,z)=>{this._setFileExplorerOpen(!0),this.setState({currentGitDiff:null,currentFile:T,scrollToLine:z||1,gitChangesOpen:!1})}})}),this.state.currentFile&&y.jsx("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",flexDirection:"column"},children:OYe(this.state.currentFile)?y.jsx(yLe,{filePath:this.state.currentFile,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch("/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):y.jsx(nLe,{filePath:this.state.currentFile,scrollToLine:this.state.scrollToLine,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch("/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)}),C,!i&&y.jsxs("div",{className:Nn.chatInputBar,children:[y.jsxs("div",{className:Nn.chatInputWrapper,children:[y.jsxs("div",{className:Nn.chatTextareaWrap,children:[y.jsx("textarea",{ref:this._inputRef,className:Nn.chatTextarea,placeholder:this.state.inputSuggestion?"":ie("ui.chatInput.placeholder"),rows:1,onKeyDown:this.handleInputKeyDown,onInput:this.handleInputChange}),this.state.inputSuggestion&&this.state.inputEmpty&&y.jsx("div",{className:Nn.ghostText,children:this.state.inputSuggestion})]}),y.jsx("div",{className:Nn.chatInputHint,children:this.state.inputSuggestion&&this.state.inputEmpty?ie("ui.chatInput.hintTab"):ie("ui.chatInput.hintEnter")})]}),!Cr&&y.jsx("button",{className:Nn.chatSendBtn,onClick:()=>{const T=document.createElement("input");T.type="file",T.onchange=async z=>{var L;const E=(L=z.target.files)==null?void 0:L[0];if(E)try{const X=`"${await PY(E)}"`,R=this._inputRef.current;R&&(R.value=(R.value?R.value+" ":"")+X,R.dispatchEvent(new Event("input",{bubbles:!0})),this.setState({inputEmpty:!1}))}catch(N){console.error("[CC Viewer] Upload failed:",N)}},T.click()},title:ie("ui.terminal.upload"),children:y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[y.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),y.jsx("polyline",{points:"17 8 12 3 7 8"}),y.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]})}),y.jsx("button",{className:Nn.chatSendBtn,onClick:this.handleInputSend,disabled:this.state.inputEmpty,title:ie("ui.chatInput.send"),children:y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[y.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),y.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),i&&this.state.inputSuggestion&&y.jsxs("div",{className:Nn.suggestionChip,onClick:this.handleSuggestionToTerminal,children:[y.jsx("span",{className:Nn.suggestionChipText,children:this.state.inputSuggestion}),y.jsx("span",{className:Nn.suggestionChipAction,children:"↵"})]})]})}),i&&y.jsxs(y.Fragment,{children:[y.jsx("div",{className:Nn.vResizer,onMouseDown:this.handleSplitMouseDown}),y.jsx("div",{style:{width:l,flexShrink:0,minWidth:200,display:"flex",flexDirection:"column"},children:y.jsx(CY,{onEditorOpen:(T,z)=>{this.setState({editorSessionId:T,editorFilePath:z,currentFile:z,currentGitDiff:null,scrollToLine:null,fileVersion:(this.state.fileVersion||0)+1})},onFilePath:T=>{const z=`"${T}"`;this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:z}))}})})]})]})]}):C}}const $Ye="_resizer_yamj2_1",SYe={resizer:$Ye};class bYe extends ne.Component{constructor(e){super(e),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this)}handleMouseDown(e){e.preventDefault(),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}handleMouseMove(e){this.props.onResize&&this.props.onResize(e.clientX)}handleMouseUp(){document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}componentWillUnmount(){document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}render(){return y.jsx("div",{onMouseDown:this.handleMouseDown,className:SYe.resizer})}}const yYe="_container_1um1r_1",_Ye="_fileListSection_1um1r_10",QYe="_header_1um1r_19",xYe="_headerTitle_1um1r_28",wYe="_fileCount_1um1r_36",PYe="_changesContainer_1um1r_44",CYe="_changeItem_1um1r_51",TYe="_changeItemActive_1um1r_68",kYe="_dirItem_1um1r_77",RYe="_dirArrow_1um1r_88",EYe="_dirName_1um1r_97",XYe="_status_1um1r_102",zYe="_icon_1um1r_111",jYe="_fileName_1um1r_120",MYe="_diffSection_1um1r_127",NYe="_diffHeader_1um1r_135",IYe="_diffFilePath_1um1r_145",AYe="_diffBadge_1um1r_155",LYe="_diffContent_1um1r_167",WYe="_diffPlaceholder_1um1r_173",VYe="_statusText_1um1r_184",YYe="_errorText_1um1r_191",BYe="_emptyText_1um1r_198",UYe="_warningText_1um1r_205",Pr={container:yYe,fileListSection:_Ye,header:QYe,headerTitle:xYe,fileCount:wYe,changesContainer:PYe,changeItem:CYe,changeItemActive:TYe,dirItem:kYe,dirArrow:RYe,dirName:EYe,status:XYe,icon:zYe,fileName:jYe,diffSection:MYe,diffHeader:NYe,diffFilePath:IYe,diffBadge:AYe,diffContent:LYe,diffPlaceholder:WYe,statusText:VYe,errorText:YYe,emptyText:BYe,warningText:UYe},qYe={M:"#e2c08d",A:"#73c991",D:"#f14c4c",R:"#73c991",C:"#73c991",U:"#e2c08d","?":"#73c991","??":"#73c991"},DYe={"??":"U"},ZYe={js:"#e8d44d",jsx:"#61dafb",ts:"#3178c6",tsx:"#3178c6",json:"#999",md:"#519aba",css:"#a86fd9",scss:"#cd6799",html:"#e34c26",py:"#3572a5",go:"#00add8",rs:"#dea584"};function GYe(t){const e=t.includes(".")?t.split(".").pop().toLowerCase():"",n=ZYe[e]||"#888";return y.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",children:[y.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),y.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function FYe(){return y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"#c09553",stroke:"none",children:y.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"})})}function HYe(t){const e={dirs:{},files:[]};for(const n of t){const r=n.file.split("/");let i=e;for(let s=0;s<r.length-1;s++)i.dirs[r[s]]||(i.dirs[r[s]]={dirs:{},files:[]}),i=i.dirs[r[s]];i.files.push({name:r[r.length-1],status:n.status,fullPath:n.file})}return e}function QZ({name:t,node:e,depth:n,selectedFile:r,onFileClick:i}){const s=Object.keys(e.dirs).sort(),o=[...e.files].sort((a,l)=>a.name.localeCompare(l.name));return y.jsxs(y.Fragment,{children:[t&&y.jsxs("div",{className:Pr.dirItem,style:{paddingLeft:8+n*16},children:[y.jsx("span",{className:Pr.dirArrow,children:y.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:"rotate(90deg)"},children:y.jsx("polyline",{points:"9 6 15 12 9 18"})})}),y.jsx("span",{className:Pr.icon,children:FYe()}),y.jsx("span",{className:Pr.dirName,children:t})]}),s.map(a=>y.jsx(QZ,{name:a,node:e.dirs[a],depth:t?n+1:n,selectedFile:r,onFileClick:i},a)),o.map(a=>y.jsxs("div",{className:`${Pr.changeItem} ${r===a.fullPath?Pr.changeItemActive:""}`,style:{paddingLeft:8+(t?n+1:n)*16},onClick:()=>i&&i(a.fullPath),children:[y.jsx("span",{className:Pr.icon,children:GYe(a.name)}),y.jsx("span",{className:Pr.fileName,children:a.name}),y.jsx("span",{className:Pr.status,style:{color:qYe[a.status]||"#888"},children:DYe[a.status]||a.status})]},a.fullPath))]})}function KYe({visible:t}){const[e,n]=f.useState(null),[r,i]=f.useState(null),[s,o]=f.useState(!0),[a,l]=f.useState(null),[c,u]=f.useState(null),[d,h]=f.useState(null),[p,g]=f.useState(!1),v=f.useRef(!0);return f.useEffect(()=>{if(v.current=!0,!!t)return o(!0),i(null),fetch(Rn("/api/git-status")).then($=>$.ok?$.json():Promise.reject()).then($=>{v.current&&(n($.changes||[]),o(!1))}).catch(()=>{v.current&&(i("Failed to load git status"),o(!1))}),()=>{v.current=!1}},[t]),f.useEffect(()=>{if(!a){u(null),h(null);return}g(!0),u(null),h(null),fetch(Rn(`/api/git-diff?files=${encodeURIComponent(a)}`)).then($=>{if(!$.ok)throw new Error(`HTTP ${$.status}`);return $.json()}).then($=>{v.current&&($.diffs&&$.diffs[0]?u($.diffs[0]):h("No diff data available"),g(!1))}).catch($=>{v.current&&(h(`${ie("ui.fileLoadError")}: ${$.message}`),g(!1))})},[a]),y.jsxs("div",{className:Pr.container,children:[y.jsxs("div",{className:Pr.fileListSection,children:[y.jsxs("div",{className:Pr.header,children:[y.jsx("span",{className:Pr.headerTitle,children:ie("ui.gitChanges")}),y.jsx("span",{className:Pr.fileCount,children:e?e.length:0})]}),y.jsxs("div",{className:Pr.changesContainer,children:[s&&y.jsx("div",{className:Pr.statusText,children:"Loading..."}),r&&y.jsx("div",{className:Pr.errorText,children:r}),!s&&!r&&e&&e.length===0&&y.jsx("div",{className:Pr.emptyText,children:"No changes"}),!s&&!r&&e&&e.length>0&&y.jsx(QZ,{name:"",node:HYe(e),depth:0,selectedFile:a,onFileClick:l})]})]}),y.jsx("div",{className:Pr.diffSection,children:a?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:Pr.diffHeader,children:[y.jsx("span",{className:Pr.diffFilePath,children:a}),y.jsx("span",{className:Pr.diffBadge,children:"DIFF"})]}),y.jsxs("div",{className:Pr.diffContent,children:[p&&y.jsx("div",{className:Pr.statusText,children:ie("ui.loading")}),d&&y.jsx("div",{className:Pr.errorText,children:d}),!p&&!d&&c&&y.jsx(y.Fragment,{children:c.is_large?y.jsxs("div",{className:Pr.warningText,children:[y.jsx("p",{children:ie("ui.largeFileWarning")}),y.jsxs("p",{style:{color:"#888",fontSize:12},children:[ie("ui.fileSize"),": ",(c.size/(1024*1024)).toFixed(2)," MB"]})]}):c.is_binary?y.jsx("div",{className:Pr.statusText,style:{fontStyle:"italic"},children:ie("ui.binaryFileNotice")}):y.jsx(_Z,{file_path:a,old_string:c.old_content,new_string:c.new_content})})]})]}):y.jsxs("div",{className:Pr.diffPlaceholder,children:[y.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"#333",strokeWidth:"1.5",children:[y.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),y.jsx("circle",{cx:"18",cy:"6",r:"3"}),y.jsx("circle",{cx:"6",cy:"18",r:"3"}),y.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),y.jsx("span",{children:ie("ui.mobileGitDiffHint")})]})})]})}const JYe="_container_rkahp_1",eBe="_header_rkahp_9",tBe="_headerTitle_rkahp_18",nBe="_closeBtn_rkahp_24",rBe="_content_rkahp_38",iBe="_empty_rkahp_47",sBe="_fixedTable_rkahp_54",oBe="_ellipsisCell_rkahp_58",ou={container:JYe,header:eBe,headerTitle:tBe,closeBtn:nBe,content:rBe,empty:iBe,fixedTable:sBe,ellipsisCell:oBe},aBe=["ttl","system_change","tools_change","model_change","msg_truncated","msg_modified","key_change"],vM={ttl:"cacheLoss.ttl",system_change:"cacheLoss.systemChange",tools_change:"cacheLoss.toolsChange",model_change:"cacheLoss.modelChange",msg_truncated:"cacheLoss.msgTruncated",msg_modified:"cacheLoss.msgModified",key_change:"cacheLoss.keyChange"};function lBe({requests:t=[],visible:e,onClose:n}){if(!e)return null;const{byModel:r,models:i,toolStats:s,skillStats:o,cacheStats:a,activeReasons:l,totalCount:c,totalCache:u,hasCacheStats:d,subAgentEntries:h,hasSubAgentStats:p,isEmpty:g}=f.useMemo(()=>{const v=zW(t),$=Object.keys(v),S=MW(t),_=NW(t),Q=jW(t),x=aBe.filter(X=>Q[X].count>0),w=x.reduce((X,R)=>X+Q[R].count,0),C=x.reduce((X,R)=>X+Q[R].cacheCreate,0),T=x.length>0,z={};for(let X=0;X<t.length;X++){const R=Ad(t[X],t[X+1]);if(R.type==="SubAgent"){const k=R.subType||"Other";z[k]=(z[k]||0)+1}}const E=Object.entries(z).sort((X,R)=>R[1]-X[1]),L=E.length>0,N=$.length===0&&S.length===0&&!T&&!L&&_.length===0;return{byModel:v,models:$,toolStats:S,skillStats:_,cacheStats:Q,activeReasons:x,totalCount:w,totalCache:C,hasCacheStats:T,subAgentEntries:E,hasSubAgentStats:L,isEmpty:N}},[t]);return y.jsxs("div",{className:ou.container,children:[y.jsxs("div",{className:ou.header,children:[y.jsx("span",{className:ou.headerTitle,children:ie("ui.tokenStats")}),y.jsx("button",{className:ou.closeBtn,onClick:n,children:y.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y.jsx("div",{className:ou.content,children:g?y.jsx("div",{className:ou.empty,children:"—"}):y.jsxs(y.Fragment,{children:[o.length>0&&y.jsxs("div",{className:pe.modelCard,children:[y.jsx("div",{className:pe.modelName,children:ie("ui.skillUsageStats")}),y.jsxs("table",{className:pe.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:pe.th,style:{textAlign:"left"},children:"Skill"}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[o.map(([v,$])=>y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:pe.label,children:v}),y.jsx("td",{className:pe.td,children:$})]},v)),o.length>1&&y.jsxs("tr",{className:pe.rebuildTotalRow,children:[y.jsx("td",{className:pe.label,children:"Total"}),y.jsx("td",{className:pe.td,children:o.reduce((v,$)=>v+$[1],0)})]})]})]})]}),p&&y.jsxs("div",{className:pe.modelCard,children:[y.jsx("div",{className:pe.modelName,children:ie("ui.subAgentStats")}),y.jsxs("table",{className:pe.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:pe.th,style:{textAlign:"left"},children:"SubAgent"}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[h.map(([v,$])=>y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:pe.label,children:v}),y.jsx("td",{className:pe.td,children:$})]},v)),h.length>1&&y.jsxs("tr",{className:pe.rebuildTotalRow,children:[y.jsx("td",{className:pe.label,children:"Total"}),y.jsx("td",{className:pe.td,children:h.reduce((v,$)=>v+$[1],0)})]})]})]})]}),s.length>0&&y.jsxs("div",{className:pe.modelCard,children:[y.jsx("div",{className:pe.modelName,children:ie("ui.toolUsageStats")}),y.jsxs("table",{className:pe.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:pe.th,style:{textAlign:"left"},children:"Tool"}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[s.map(([v,$])=>y.jsxs("tr",{className:pe.rowBorder,children:[y.jsxs("td",{className:pe.label,children:[v," ",y.jsx(yc,{doc:`Tool-${v}`})]}),y.jsx("td",{className:pe.td,children:$})]},v)),s.length>1&&y.jsxs("tr",{className:pe.rebuildTotalRow,children:[y.jsx("td",{className:pe.label,children:"Total"}),y.jsx("td",{className:pe.td,children:s.reduce((v,$)=>v+$[1],0)})]})]})]})]}),d&&y.jsxs("div",{className:pe.modelCard,children:[y.jsxs("div",{className:pe.modelName,children:["MainAgent",y.jsx(yc,{doc:"MainAgent"})," ",ie("ui.cacheRebuildStats"),y.jsx(yc,{doc:"CacheRebuild"})]}),y.jsxs("table",{className:`${pe.statsTable} ${ou.fixedTable}`,children:[y.jsxs("colgroup",{children:[y.jsx("col",{style:{width:"50%"}}),y.jsx("col",{style:{width:"25%"}}),y.jsx("col",{style:{width:"25%"}})]}),y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:pe.th,style:{textAlign:"left"},children:ie("ui.cacheRebuild.reason")}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.count")}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.cacheCreate")})]})}),y.jsxs("tbody",{children:[l.map(v=>y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:`${pe.label} ${ou.ellipsisCell}`,title:ie(`ui.${vM[v]}`),children:ie(`ui.${vM[v]}`)}),y.jsx("td",{className:pe.td,children:a[v].count}),y.jsx("td",{className:pe.td,children:Er(a[v].cacheCreate)})]},v)),l.length>1&&y.jsxs("tr",{className:pe.rebuildTotalRow,children:[y.jsx("td",{className:pe.label,children:"Total"}),y.jsx("td",{className:pe.td,children:c}),y.jsx("td",{className:pe.td,children:Er(u)})]})]})]})]}),i.map(v=>{const $=r[v],S=$.input+$.cacheCreation+$.cacheRead,_=S>0?($.cacheRead/S*100).toFixed(1):"0.0";return y.jsxs("div",{className:pe.modelCard,children:[y.jsx("div",{className:pe.modelName,children:v}),y.jsx("table",{className:pe.statsTable,children:y.jsxs("tbody",{children:[y.jsxs("tr",{children:[y.jsx("td",{className:pe.label,children:"Token"}),y.jsx("td",{className:pe.th,children:"input"}),y.jsx("td",{className:pe.th,children:"output"})]}),y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:pe.label}),y.jsx("td",{className:pe.td,children:Er(S)}),y.jsx("td",{className:pe.td,children:Er($.output)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:pe.label,children:"Cache"}),y.jsx("td",{className:pe.th,children:"create"}),y.jsx("td",{className:pe.th,children:"read"})]}),y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:pe.label}),y.jsx("td",{className:pe.td,children:Er($.cacheCreation)}),y.jsx("td",{className:pe.td,children:Er($.cacheRead)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:pe.label,children:ie("ui.hitRate")}),y.jsxs("td",{colSpan:2,className:pe.td,children:[_,"%"]})]})]})})]},v)})]})})]})}const{Text:Pd,Title:cBe}=Ga;function uBe(t){if(!t)return"0 B";const e=["B","KB","MB","GB"];let n=0,r=t;for(;r>=1024&&n<e.length-1;)r/=1024,n++;return`${r.toFixed(n>0?1:0)} ${e[n]}`}function dBe(t){if(!t)return"";const e=Date.now()-new Date(t).getTime(),n=Math.floor(e/6e4);if(n<1)return ie("ui.workspaces.justNow");if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function OBe({open:t,onClose:e,onSelect:n}){const[r,i]=f.useState(""),[s,o]=f.useState(null),[a,l]=f.useState([]),[c,u]=f.useState(!1),[d,h]=f.useState(""),p=f.useCallback(v=>{u(!0);const $=v?`/api/browse-dir?path=${encodeURIComponent(v)}`:"/api/browse-dir";fetch(Rn($)).then(S=>S.json()).then(S=>{S.error?ar.error(S.error):(i(S.current),o(S.parent),l(S.dirs||[]),h(S.current)),u(!1)}).catch(()=>{ar.error("Failed to browse directory"),u(!1)})},[]);f.useEffect(()=>{t&&p("")},[t,p]);const g=()=>{const v=d.trim();v&&p(v)};return y.jsxs(Ti,{title:ie("ui.workspaces.selectDir"),open:t,onCancel:e,footer:null,width:600,styles:{body:{padding:"12px 0"}},children:[y.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"0 16px 10px",borderBottom:"1px solid #2a2a2a"},children:[y.jsx(Sn,{type:"text",icon:y.jsx(gve,{}),disabled:!s,onClick:()=>s&&p(s),size:"small"}),y.jsxs(Pd,{style:{color:"#e0e0e0",fontSize:13,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[y.jsx(i1,{style:{marginRight:6,color:"#1668dc"}}),r]})]}),y.jsx("div",{style:{maxHeight:400,overflowY:"auto",padding:"4px 0"},children:c?y.jsx("div",{style:{textAlign:"center",padding:40},children:y.jsx(Ua,{})}):a.length===0?y.jsx("div",{style:{textAlign:"center",padding:40},children:y.jsx(Pd,{type:"secondary",children:ie("ui.workspaces.emptyDir")})}):a.map(v=>y.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 16px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:$=>$.currentTarget.style.background="#1a1a1a",onMouseLeave:$=>$.currentTarget.style.background="transparent",children:[y.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:8,minWidth:0},onClick:()=>p(v.path),children:[y.jsx(aW,{style:{color:v.hasGit?"#1668dc":"#666",fontSize:16,flexShrink:0}}),y.jsx(Pd,{style:{color:"#d0d0d0",fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name}),v.hasGit&&y.jsxs(eo,{color:"blue",style:{fontSize:11,lineHeight:"18px",padding:"0 4px",margin:0,flexShrink:0},children:[y.jsx($W,{style:{marginRight:2}}),"git"]})]}),y.jsx(Sn,{type:"primary",size:"small",onClick:$=>{$.stopPropagation(),n(v.path)},children:ie("ui.workspaces.select")})]},v.path))}),y.jsxs("div",{style:{borderTop:"1px solid #2a2a2a",padding:"10px 16px 4px",display:"flex",flexDirection:"column",gap:8},children:[y.jsxs(Sn,{type:"primary",ghost:!0,block:!0,icon:y.jsx(i1,{}),onClick:()=>n(r),children:[ie("ui.workspaces.selectCurrent")," — ",r.split("/").pop()||r]}),y.jsxs("div",{style:{display:"flex",gap:8},children:[y.jsx(Wu,{size:"small",value:d,onChange:v=>h(v.target.value),onPressEnter:g,placeholder:ie("ui.workspaces.pathPlaceholder"),style:{flex:1}}),y.jsx(Sn,{size:"small",onClick:g,children:ie("ui.workspaces.goTo")})]})]})]})}function hBe({onLaunch:t}){const[e,n]=f.useState([]),[r,i]=f.useState(!0),[s,o]=f.useState(null),[a,l]=f.useState(!1),c=()=>{fetch(Rn("/api/workspaces")).then(p=>p.json()).then(p=>{n(p.workspaces||[]),i(!1)}).catch(()=>i(!1))};f.useEffect(()=>{c()},[]);const u=p=>{l(!1),fetch(Rn("/api/workspaces/add"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p})}).then(g=>g.json()).then(g=>{g.error?ar.error(g.error):c()}).catch(()=>ar.error("Failed to add workspace"))},d=p=>{fetch(Rn(`/api/workspaces/${p}`),{method:"DELETE"}).then(g=>g.json()).then(()=>c()).catch(()=>{})},h=p=>{o(p.id),fetch(Rn("/api/workspaces/launch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p.path})}).then(g=>g.json()).then(g=>{g.error?(ar.error(g.error),o(null)):t({projectName:g.projectName,path:p.path})}).catch(()=>{ar.error("Launch failed"),o(null)})};return y.jsxs("div",{style:{minHeight:"100vh",background:"#0a0a0a",display:"flex",justifyContent:"center",paddingTop:60},children:[y.jsxs("div",{style:{width:"100%",maxWidth:720,padding:"0 24px"},children:[y.jsxs("div",{style:{marginBottom:32,textAlign:"center"},children:[y.jsxs(cBe,{level:3,style:{color:"#e0e0e0",margin:0},children:[y.jsx(i1,{style:{marginRight:8,color:"#1668dc"}}),ie("ui.workspaces.title")]}),y.jsx(Pd,{type:"secondary",style:{fontSize:13},children:ie("ui.workspaces.subtitle")})]}),y.jsx("div",{style:{marginBottom:20,textAlign:"center"},children:y.jsx(Sn,{type:"primary",icon:y.jsx(J$,{}),onClick:()=>l(!0),size:"large",children:ie("ui.workspaces.browse")})}),r?y.jsx("div",{style:{textAlign:"center",padding:60},children:y.jsx(Ua,{})}):e.length===0?y.jsx(vs,{description:y.jsx(Pd,{type:"secondary",children:ie("ui.workspaces.empty")}),style:{marginTop:60}}):y.jsx(n1,{dataSource:e,renderItem:p=>y.jsx(IT,{size:"small",style:{marginBottom:10,background:"#141414",borderColor:"#2a2a2a",cursor:"pointer"},hoverable:!0,onClick:()=>h(p),children:y.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[y.jsxs("div",{style:{flex:1,minWidth:0},children:[y.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:y.jsx(Pd,{strong:!0,style:{color:"#e0e0e0",fontSize:15},children:p.projectName})}),y.jsx(Pd,{type:"secondary",style:{fontSize:12,wordBreak:"break-all"},children:p.path}),y.jsxs("div",{style:{display:"flex",gap:16,marginTop:6,fontSize:12,color:"#666"},children:[y.jsxs("span",{children:[y.jsx(Ede,{style:{marginRight:4}}),dBe(p.lastUsed)]}),p.logCount>0&&y.jsxs("span",{children:[y.jsx(Cve,{style:{marginRight:4}}),p.logCount," logs (",uBe(p.totalSize),")"]})]})]}),y.jsxs(bl,{children:[y.jsx(Sn,{type:"primary",icon:y.jsx(Wve,{}),loading:s===p.id,onClick:g=>{g.stopPropagation(),h(p)},children:ie("ui.workspaces.open")}),y.jsx(AL,{title:ie("ui.workspaces.confirmRemove"),onConfirm:g=>{g==null||g.stopPropagation(),d(p.id)},onCancel:g=>g==null?void 0:g.stopPropagation(),okText:"Yes",cancelText:"No",children:y.jsx(Sn,{type:"text",danger:!0,icon:y.jsx(o1,{}),onClick:g=>g.stopPropagation()})})]})]})},p.id)})]}),y.jsx(OBe,{open:a,onClose:()=>l(!1),onSelect:u})]})}const fBe="_layout_1a3p0_1",pBe="_header_1a3p0_6",mBe="_content_1a3p0_14",gBe="_mainContainer_1a3p0_19",vBe="_leftPanel_1a3p0_24",$Be="_leftPanelHeader_1a3p0_32",SBe="_leftPanelCount_1a3p0_43",bBe="_leftPanelBody_1a3p0_49",yBe="_rightPanel_1a3p0_54",_Be="_modalActions_1a3p0_60",QBe="_spinCenter_1a3p0_64",xBe="_emptyCenter_1a3p0_69",wBe="_logListContainer_1a3p0_79",PBe="_loadingOverlay_1a3p0_127",CBe="_loadingText_1a3p0_140",TBe="_mobileLoadingOverlay_1a3p0_146",kBe="_mobileLoadingSpinner_1a3p0_158",RBe="_mobileLoadingLabel_1a3p0_171",EBe="_footer_1a3p0_177",XBe="_footerRight_1a3p0_188",zBe="_footerText_1a3p0_196",jBe="_footerLink_1a3p0_201",MBe="_footerIcon_1a3p0_213",NBe="_footerDivider_1a3p0_218",IBe="_guideContainer_1a3p0_226",ABe="_guideContent_1a3p0_234",LBe="_guideTitle_1a3p0_239",WBe="_guideStep_1a3p0_246",VBe="_guideStepNum_1a3p0_252",YBe="_guideStepBody_1a3p0_267",BBe="_guideText_1a3p0_272",UBe="_guideCode_1a3p0_279",qBe="_mobileChatOverlay_1a3p0_292",DBe="_mobileChatOverlayVisible_1a3p0_304",ZBe="_mobileChatInner_1a3p0_308",GBe="_mobileGitDiffOverlay_1a3p0_316",FBe="_mobileGitDiffOverlayVisible_1a3p0_328",HBe="_mobileGitDiffInner_1a3p0_332",KBe="_mobileMenuBtn_1a3p0_340",JBe="_mobileMenuOverlay_1a3p0_357",eUe="_mobileMenuDropdown_1a3p0_363",tUe="_mobileMenuItem_1a3p0_377",nUe="_mobileStatsOverlay_1a3p0_395",rUe="_mobileStatsOverlayVisible_1a3p0_407",iUe="_mobileStatsInner_1a3p0_411",sUe="_mobileLogMgmtOverlay_1a3p0_418",oUe="_mobileLogMgmtOverlayVisible_1a3p0_430",aUe="_mobileLogMgmtHeader_1a3p0_434",lUe="_mobileLogMgmtTitle_1a3p0_443",cUe="_mobileLogMgmtClose_1a3p0_449",uUe="_mobileLogMgmtActions_1a3p0_464",dUe="_mobileLogMgmtBody_1a3p0_472",OUe="_mobileSettingsOverlay_1a3p0_479",hUe="_mobileSettingsOverlayVisible_1a3p0_491",fUe="_mobilePromptOverlay_1a3p0_495",pUe="_mobilePromptOverlayVisible_1a3p0_507",mUe="_mobilePromptBody_1a3p0_511",gUe="_mobilePromptList_1a3p0_519",vUe="_mobilePromptItem_1a3p0_525",$Ue="_mobilePromptTimestamp_1a3p0_530",SUe="_mobilePromptCard_1a3p0_537",bUe="_mobilePromptPreText_1a3p0_545",yUe="_previewPopover_1a3p0_555",_Ue="_previewItem_1a3p0_561",QUe="_previewText_1a3p0_573",bt={layout:fBe,header:pBe,content:mBe,mainContainer:gBe,leftPanel:vBe,leftPanelHeader:$Be,leftPanelCount:SBe,leftPanelBody:bBe,rightPanel:yBe,modalActions:_Be,spinCenter:QBe,emptyCenter:xBe,logListContainer:wBe,loadingOverlay:PBe,loadingText:CBe,mobileLoadingOverlay:TBe,mobileLoadingSpinner:kBe,mobileLoadingLabel:RBe,footer:EBe,footerRight:XBe,footerText:zBe,footerLink:jBe,footerIcon:MBe,footerDivider:NBe,guideContainer:IBe,guideContent:ABe,guideTitle:LBe,guideStep:WBe,guideStepNum:VBe,guideStepBody:YBe,guideText:BBe,guideCode:UBe,mobileChatOverlay:qBe,mobileChatOverlayVisible:DBe,mobileChatInner:ZBe,mobileGitDiffOverlay:GBe,mobileGitDiffOverlayVisible:FBe,mobileGitDiffInner:HBe,mobileMenuBtn:KBe,mobileMenuOverlay:JBe,mobileMenuDropdown:eUe,mobileMenuItem:tUe,mobileStatsOverlay:nUe,mobileStatsOverlayVisible:rUe,mobileStatsInner:iUe,mobileLogMgmtOverlay:sUe,mobileLogMgmtOverlayVisible:oUe,mobileLogMgmtHeader:aUe,mobileLogMgmtTitle:lUe,mobileLogMgmtClose:cUe,mobileLogMgmtActions:uUe,mobileLogMgmtBody:dUe,mobileSettingsOverlay:OUe,mobileSettingsOverlayVisible:hUe,mobilePromptOverlay:fUe,mobilePromptOverlayVisible:pUe,mobilePromptBody:mUe,mobilePromptList:gUe,mobilePromptItem:vUe,mobilePromptTimestamp:$Ue,mobilePromptCard:SUe,mobilePromptPreText:bUe,previewPopover:yUe,previewItem:_Ue,previewText:QUe},xUe="ccv_entryCache",Au="entries",Y5="cache",B5="ccv_cacheMeta",wUe=1,PUe=10080*60*1e3;let UO=null,qO=null;function U5(){return UO?Promise.resolve(UO):qO||(qO=new Promise((t,e)=>{const n=indexedDB.open(xUe,wUe);n.onupgradeneeded=()=>{const r=n.result;r.objectStoreNames.contains(Au)||r.createObjectStore(Au)},n.onsuccess=()=>{UO=n.result,UO.onclose=()=>{UO=null},qO=null,t(UO)},n.onerror=()=>{qO=null,e(n.error)}}),qO)}let $M=0;function CUe(t,e){try{const n=e[e.length-1],r=(n==null?void 0:n.timestamp)||null;r&&localStorage.setItem(B5,JSON.stringify({projectName:t,lastTs:r,count:e.length}))}catch{}}function TUe(){try{localStorage.removeItem(B5)}catch{}}function kUe(){try{const t=localStorage.getItem(B5);if(!t)return null;const e=JSON.parse(t);return e!=null&&e.lastTs&&(e==null?void 0:e.count)>0&&(e!=null&&e.projectName)?e:null}catch{return null}}async function Fx(t,e){if(!t||!Array.isArray(e)||e.length===0)return;const n=++$M;try{const r=await U5();return n!==$M?void 0:(CUe(t,e),new Promise(i=>{const s=r.transaction(Au,"readwrite");s.objectStore(Au).put({projectName:t,entries:e,ts:Date.now()},Y5),s.oncomplete=()=>i(),s.onerror=()=>i()}))}catch{}}async function RUe(t){try{const e=await U5();return new Promise(n=>{const i=e.transaction(Au,"readonly").objectStore(Au).get(Y5);i.onsuccess=()=>{const s=i.result;!s||s.projectName!==t||!Array.isArray(s.entries)||s.entries.length===0?n(null):s.ts&&Date.now()-s.ts>PUe?(I2(),n(null)):n(s.entries)},i.onerror=()=>n(null)})}catch{return null}}async function I2(){TUe();try{const t=await U5();return new Promise(e=>{const n=t.transaction(Au,"readwrite");n.objectStore(Au).delete(Y5),n.oncomplete=()=>e(),n.onerror=()=>e()})}catch{}}const hh=class hh extends ne.Component{constructor(n){super(n);Qt(this,"handleSelectRequest",n=>{this.setState({selectedIndex:n,scrollCenter:!1})});Qt(this,"handleViewRequest",n=>{this.setState({viewMode:"raw",selectedIndex:n,scrollCenter:!0})});Qt(this,"handleViewInChat",()=>{this.setState(n=>{const i=(n.showAll?n.requests:Ra(n.requests))[n.selectedIndex];if(!i)return null;let s=null;if(Ii(i)&&i.timestamp)s=i.timestamp;else{if(Ad(i).type==="SubAgent"&&i.timestamp)s=i.timestamp;else{const a=n.requests.indexOf(i);a>=0&&(s=H8(n.requests,a))}s||ar.info(ie("ui.cannotMap"))}return{viewMode:"chat",chatScrollToTs:s}})});Qt(this,"handleWorkspaceLaunch",({projectName:n})=>{this._isLocalLog=!1,this._localLogFile=null,this.setState({workspaceMode:!1,projectName:n,viewMode:"chat",cliMode:!0})});Qt(this,"handleReturnToWorkspaces",()=>{fetch(Rn("/api/workspaces/stop"),{method:"POST"}).then(()=>{this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null})}).catch(()=>{})});Qt(this,"handleToggleViewMode",()=>{this.setState(n=>{const r=n.viewMode==="raw"?"chat":"raw";if(r==="raw"){if(n.selectedIndex===null){const o=n.showAll?n.requests:Ra(n.requests);return{viewMode:r,selectedIndex:o.length>0?o.length-1:null,scrollCenter:!0}}return{viewMode:r,scrollCenter:!0}}const i=n.showAll?n.requests:Ra(n.requests),s=n.selectedIndex!=null?i[n.selectedIndex]:null;if(s){let o=null;if(Ii(s)&&s.timestamp)o=s.timestamp;else if(Ad(s).type==="SubAgent"&&s.timestamp)o=s.timestamp;else{const l=n.requests.indexOf(s);l>=0&&(o=H8(n.requests,l)),o||ar.info(ie("ui.cannotMap"))}return{viewMode:r,chatScrollToTs:o}}return{viewMode:r,chatScrollToTs:null}})});Qt(this,"handleLangChange",()=>{const n=xm();this.setState({lang:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:n})}).catch(()=>{})});Qt(this,"handleCollapseToolResultsChange",n=>{this.setState({collapseToolResults:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({collapseToolResults:n})}).catch(()=>{})});Qt(this,"handleExpandThinkingChange",n=>{this.setState({expandThinking:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandThinking:n})}).catch(()=>{})});Qt(this,"handleExpandDiffChange",n=>{this.setState({expandDiff:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandDiff:n})}).catch(()=>{})});Qt(this,"handleFilterIrrelevantChange",n=>{this.setState(r=>{const i=!n,s=i?r.requests:Ra(r.requests);return{showAll:i,selectedIndex:s.length>0?s.length-1:null}}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filterIrrelevant:n})}).catch(()=>{})});Qt(this,"handleExportPromptsTxt",n=>{if(!n||n.length===0)return;const r=[];for(const a of n){const l=[],c=a.timestamp?new Date(a.timestamp).toLocaleString():"";c&&l.push(`${c}:
711
+ `).length,w=x-Q;if(v.plainText=v.plainText.substring(0,$)+g+v.plainText.substring($+p.length),w!==0){const C=v.lineNums[_]||_+1,T=[];for(let z=0;z<x;z++)T.push(C+z);v.lineNums=[...v.lineNums.slice(0,_),...T,...v.lineNums.slice(_+Q).map(z=>z+w)]}}}}}const o={},a={};for(const u of t)if(u.role==="user"&&Array.isArray(u.content)){for(const d of u.content)if(d.type==="tool_result"){const h=e[d.tool_use_id];if(h&&h.name==="AskUserQuestion"){const p=Fv(d);o[d.tool_use_id]=gYe(p)}if(h&&h.name==="ExitPlanMode"){const p=Fv(d);a[d.tool_use_id]=vYe(p)}}}return{toolUseMap:e,toolResultMap:n,readContentMap:r,editSnapshotMap:i,askAnswerMap:o,planApprovalMap:a}}function gYe(t){const e={},n=/"([^"]+)"="([^"]*)"/g;let r;for(;(r=n.exec(t))!==null;)e[r[1]]=r[2];return e}function vYe(t){if(!t)return{status:"pending"};if(/User has approved/i.test(t))return{status:"approved"};if(/User rejected/i.test(t)){const e=t.match(/feedback:\s*(.+)/i)||t.match(/User rejected[^:]*:\s*(.+)/i);return{status:"rejected",feedback:e?e[1].trim():""}}return{status:"pending"}}class gM extends ne.Component{constructor(n){super(n);Qt(this,"handleStickToBottom",()=>{this.setState({stickyBottom:!0},()=>{const n=this.containerRef.current;n&&(n.scrollTop=n.scrollHeight)})});Qt(this,"handleLoadMore",()=>{this._mobileExtraItems+=pYe;const n=this.containerRef.current,r=n?n.scrollHeight:0,i=n?n.scrollTop:0,s=this.buildAllItems(),o=this._applyMobileSlice(s);this.setState({allItems:o,visibleCount:o.length},()=>{if(n){const a=n.scrollHeight;n.scrollTop=i+(a-r)}})});Qt(this,"handlePromptOptionClick",n=>{const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN)return;const i=this.state.ptyPrompt;if(!i)return;const s=i.options,o=s.findIndex(h=>h.number===n);let a=s.findIndex(h=>h.selected);a<0&&(a=0);const l=o-a,c=l>0?"\x1B[B":"\x1B[A",u=Math.abs(l),d=h=>{h<u?(r.send(JSON.stringify({type:"input",data:c})),setTimeout(()=>d(h+1),30)):setTimeout(()=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:"input",data:"\r"}))},50)};d(0),this._currentPtyPrompt=null,this.setState(h=>{const p=h.ptyPromptHistory.slice(),g=p[p.length-1];return g&&g.status==="active"&&(p[p.length-1]={...g,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:p}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});Qt(this,"handlePlanFeedbackSubmit",(n,r)=>{const i=this._inputWs;if(!i||i.readyState!==WebSocket.OPEN)return;const s=this.state.ptyPrompt;if(!s)return;const o=s.options,a=o.findIndex(p=>p.number===n);let l=o.findIndex(p=>p.selected);l<0&&(l=0);const c=a-l,u=c>0?"\x1B[B":"\x1B[A",d=Math.abs(c),h=p=>{p<d?(i.send(JSON.stringify({type:"input",data:u})),setTimeout(()=>h(p+1),30)):setTimeout(()=>{i.send(JSON.stringify({type:"input",data:"\r"}));const g=this._ptyBuffer;let v=0;const $=()=>{if(v++,v>20||this._ptyBuffer!==g){i.readyState===WebSocket.OPEN&&(i.send(JSON.stringify({type:"input",data:r})),setTimeout(()=>{i.send(JSON.stringify({type:"input",data:"\r"}))},50));return}setTimeout($,100)};setTimeout($,100)},50)};h(0),this._currentPtyPrompt=null,this.setState(p=>{const g=p.ptyPromptHistory.slice(),v=g[g.length-1];return v&&v.status==="active"&&(g[g.length-1]={...v,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:g}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});Qt(this,"handleAskQuestionSubmit",n=>{if(!this._inputWs||this._inputWs.readyState!==WebSocket.OPEN){this._askAnswerQueue=[...n],this._askSubmitting=!0,this.connectInputWs(),this._askWsRetries=0,this._waitForWsAndSubmit();return}if(this._askAnswerQueue=[...n],this._askSubmitting=!0,!this._currentPtyPrompt){this._askPromptRetries=0,this._waitForPtyPromptAndSubmit();return}this._processNextAskAnswer()});Qt(this,"handleInputSend",()=>{const n=this._inputRef.current;if(!n)return;const r=n.value.trim();r&&this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&(this._inputWs.send(JSON.stringify({type:"input",data:r})),setTimeout(()=>{this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:"\r"}))},50),n.value="",n.style.height="auto",this.setState({inputEmpty:!0,pendingInput:r,inputSuggestion:null},()=>this.scrollToBottom()))});Qt(this,"handleInputKeyDown",n=>{if(n.key==="Tab"&&this.state.inputSuggestion){n.preventDefault();const r=this._inputRef.current;r&&(r.value=this.state.inputSuggestion,r.style.height="auto",r.style.height=Math.min(r.scrollHeight,120)+"px"),this.setState({inputSuggestion:null,inputEmpty:!1});return}n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleInputSend())});Qt(this,"handleInputChange",n=>{const r=n.target;r.style.height="auto",r.style.height=Math.min(r.scrollHeight,120)+"px";const i=!r.value.trim();this.setState({inputEmpty:i}),this.state.inputSuggestion&&!i&&this.setState({inputSuggestion:null})});Qt(this,"handleSuggestionToTerminal",()=>{const n=this.state.inputSuggestion;!n||!this._inputWs||this._inputWs.readyState!==WebSocket.OPEN||(this._inputWs.send(JSON.stringify({type:"input",data:n})),setTimeout(()=>{this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:"\r"}))},50),this.setState({inputSuggestion:null,pendingInput:n},()=>this.scrollToBottom()))});Qt(this,"handleSplitMouseDown",n=>{n.preventDefault(),this._resizing=!0;const i=!window.location.search.includes("token=");let s=[];if(i){const l=this.innerSplitRef.current;if(l){const u=l.getBoundingClientRect().width,d=7.8,h=[60,80,100,120],p=5;s=h.map(g=>{const v=g*d,$=v+p;if($>u*.75||$<u*.15)return null;const S=u-v-p;return{cols:g,terminalPx:v,linePosition:S}}).filter(g=>g!==null)}}this.setState({isDragging:!0,snapLines:s});const o=l=>{if(!this._resizing)return;const c=this.innerSplitRef.current;if(!c)return;const u=c.getBoundingClientRect(),d=u.width;let h=u.right-l.clientX;h=Math.max(200,Math.min(d*.75,h));let p=null;if(i&&s.length>0){let v=1/0,$=null;for(const S of s){const _=Math.abs(l.clientX-u.left-S.linePosition);_<v&&(v=_,$=S)}$&&v<60&&(p=$)}this.setState({terminalWidth:h,activeSnapLine:p})},a=()=>{if(this._resizing=!1,i&&this.state.activeSnapLine){const l=this.state.activeSnapLine.terminalPx;localStorage.setItem("cc-viewer-terminal-width",l.toString()),this.setState({terminalWidth:l,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",o),document.removeEventListener("mouseup",a),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",o),document.addEventListener("mouseup",a),document.body.style.cursor="col-resize",document.body.style.userSelect="none"});Qt(this,"handleToggleExpandPath",n=>{this.setState(r=>{const i=new Set(r.fileExplorerExpandedPaths);return i.has(n)?i.delete(n):i.add(n),{fileExplorerExpandedPaths:i}})});this.containerRef=ne.createRef(),this.splitContainerRef=ne.createRef(),this.innerSplitRef=ne.createRef();const r=localStorage.getItem("cc-viewer-terminal-width"),i=r?parseFloat(r):null;this.state={visibleCount:0,loading:!1,allItems:[],highlightTs:null,highlightFading:!1,terminalWidth:i||468,needsInitialSnap:i===null,inputEmpty:!0,pendingInput:null,stickyBottom:!0,ptyPrompt:null,ptyPromptHistory:[],inputSuggestion:null,fileExplorerOpen:localStorage.getItem("ccv_fileExplorerOpen")!=="false",currentFile:null,currentGitDiff:null,scrollToLine:null,fileExplorerExpandedPaths:new Set,gitChangesOpen:!1,snapLines:[],activeSnapLine:null,isDragging:!1,fileVersion:0,editorSessionId:null,editorFilePath:null,fileExplorerRefresh:0,gitChangesRefresh:0},this._processedToolIds=new Set,this._fileRefreshTimer=null,this._gitRefreshTimer=null,this._queueTimer=null,this._prevItemsLen=0,this._scrollTargetIdx=null,this._scrollTargetRef=ne.createRef(),this._scrollFadeTimer=null,this._resizing=!1,this._inputWs=null,this._inputRef=ne.createRef(),this._ptyBuffer="",this._ptyDebounceTimer=null,this._currentPtyPrompt=null,this._mobileExtraItems=0,this._mobileSliceOffset=0,this._totalItemCount=0}_setFileExplorerOpen(n){localStorage.setItem("ccv_fileExplorerOpen",String(n)),this.setState({fileExplorerOpen:n})}_checkToolFileChanges(){var s,o;const n=this.props.mainAgentSessions;if(!n||n.length===0)return;let r=!1,i=!1;for(const a of n){const l=[];if((o=(s=a.response)==null?void 0:s.body)!=null&&o.content&&l.push(a.response.body.content),Array.isArray(a.messages))for(const c of a.messages)c.role==="assistant"&&Array.isArray(c.content)&&l.push(c.content);for(const c of l)for(const u of c){if(u.type!=="tool_use"||!u.id||this._processedToolIds.has(u.id))continue;this._processedToolIds.add(u.id);const d=u.name;let h=u.input;if(typeof h=="string")try{h=JSON.parse(h.replace(/^\[object Object\]/,""))}catch{h={}}d==="Write"?(r=!0,i=!0):d==="Edit"||d==="NotebookEdit"?i=!0:d==="Bash"&&h&&h.command&&fYe(h.command)&&(r=!0,i=!0)}}r&&this.state.fileExplorerOpen&&(clearTimeout(this._fileRefreshTimer),this._fileRefreshTimer=setTimeout(()=>{this.setState(a=>({fileExplorerRefresh:a.fileExplorerRefresh+1}))},500)),i&&this.state.gitChangesOpen&&(clearTimeout(this._gitRefreshTimer),this._gitRefreshTimer=setTimeout(()=>{this.setState(a=>({gitChangesRefresh:a.gitChangesRefresh+1}))},500))}componentDidMount(){this.startRender(),this.props.cliMode&&this.connectInputWs(),this._bindStickyScroll(),this.state.needsInitialSnap&&this.props.cliMode&&this.props.terminalVisible&&this._snapToInitialPosition()}componentDidUpdate(n){if(n.mainAgentSessions!==this.props.mainAgentSessions)Cr&&(this._mobileExtraItems=0),this.startRender(),this.state.pendingInput&&this.setState({pendingInput:null}),this._updateSuggestion(),this._checkToolFileChanges();else if(n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking){const r=this.buildAllItems(),i=this._applyMobileSlice(r);this.setState({allItems:i,visibleCount:i.length})}if(!n.scrollToTimestamp&&this.props.scrollToTimestamp)if(Cr&&this.props.scrollToTimestamp){const r=this.buildAllItems(),i=this._scrollTargetIdx;if(i!=null){const o=Gx+this._mobileExtraItems,a=r.length>o?r.length-o:0;i<a&&(this._mobileExtraItems=r.length-i-Gx,this._mobileExtraItems<0&&(this._mobileExtraItems=0))}const s=this._applyMobileSlice(r);this.setState({allItems:s,visibleCount:s.length},()=>this.scrollToBottom())}else{const r=this.buildAllItems(),i=this._applyMobileSlice(r);this.setState({allItems:i,visibleCount:i.length},()=>this.scrollToBottom())}Cr&&this.props.mobileChatVisible&&!n.mobileChatVisible&&requestAnimationFrame(()=>{const r=this.containerRef.current;r&&(r.scrollTop=r.scrollHeight)}),!n.cliMode&&this.props.cliMode&&this.connectInputWs(),this._rebindStickyEl()}componentWillUnmount(){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._unbindScrollFade(),this._unbindStickyScroll(),this._inputWs&&(this._inputWs.close(),this._inputWs=null)}startRender(){this._queueTimer&&clearTimeout(this._queueTimer);const n=this.buildAllItems(),r=this._applyMobileSlice(n),i=this._prevItemsLen;this._prevItemsLen=r.length;const s=r.length-i;if(s<=0||i>0&&s<=3){this.setState({allItems:r,visibleCount:r.length,loading:!1},()=>this.scrollToBottom());return}if(r.length>uYe)this.setState({allItems:r,visibleCount:0,loading:!0}),this._queueTimer=setTimeout(()=>{this.setState({visibleCount:r.length,loading:!1},()=>this.scrollToBottom())},300);else{const o=Math.max(0,i);this.setState({allItems:r,visibleCount:o,loading:!1}),this.queueNext(o,r.length)}}queueNext(n,r){n>=r||(this._queueTimer=setTimeout(()=>{this.setState({visibleCount:n+1},()=>{this.scrollToBottom(),this.queueNext(n+1,r)})},mYe()))}_isNearBottom(){const n=this.containerRef.current;return n?n.scrollHeight-n.scrollTop-n.clientHeight<=30:!0}scrollToBottom(){if(this._scrollTargetRef.current){const n=this._scrollTargetRef.current,r=this.containerRef.current;r&&n.offsetHeight>r.clientHeight?n.scrollIntoView({block:"start",behavior:"instant"}):n.scrollIntoView({block:"center",behavior:"instant"});const i=this.props.scrollToTimestamp;this._scrollTargetRef=ne.createRef(),i&&(this.setState({highlightTs:i,highlightFading:!1}),this._bindScrollFade()),this.props.onScrollTsDone&&this.props.onScrollTsDone();return}if(this.state.stickyBottom){const n=this.containerRef.current;n&&(n.scrollTop=n.scrollHeight)}}_bindStickyScroll(){this._stickyScrollRafId=null,this._onStickyScroll=()=>{this._stickyScrollLock||this._stickyScrollRafId||(this._stickyScrollRafId=requestAnimationFrame(()=>{this._stickyScrollRafId=null;const n=this.containerRef.current;if(!n)return;const r=n.scrollHeight-n.scrollTop-n.clientHeight;this.state.stickyBottom&&r>30?this.setState({stickyBottom:!1}):!this.state.stickyBottom&&r<=5&&this.setState({stickyBottom:!0})}))},this._rebindStickyEl()}_rebindStickyEl(){const n=this.containerRef.current;n!==this._stickyBoundEl&&(this._stickyBoundEl&&this._stickyBoundEl.removeEventListener("scroll",this._onStickyScroll),this._stickyBoundEl=n,n&&n.addEventListener("scroll",this._onStickyScroll,{passive:!0}))}_unbindStickyScroll(){this._stickyBoundEl&&this._onStickyScroll&&(this._stickyBoundEl.removeEventListener("scroll",this._onStickyScroll),this._stickyBoundEl=null),this._stickyScrollRafId&&(cancelAnimationFrame(this._stickyScrollRafId),this._stickyScrollRafId=null)}_bindScrollFade(){this._unbindScrollFade();const n=this.containerRef.current;n&&(this._scrollFadeIgnoreFirst=!0,this._onScrollFade=()=>{if(this._scrollFadeIgnoreFirst){this._scrollFadeIgnoreFirst=!1;return}this.setState({highlightFading:!0}),this._fadeClearTimer=setTimeout(()=>{this.setState({highlightTs:null,highlightFading:!1})},2e3),this._unbindScrollFade()},n.addEventListener("scroll",this._onScrollFade,{passive:!0}))}_unbindScrollFade(){this._onScrollFade&&this.containerRef.current&&(this.containerRef.current.removeEventListener("scroll",this._onScrollFade),this._onScrollFade=null)}renderSessionMessages(n,r,i,s){const{userProfile:o,collapseToolResults:a,expandThinking:l,onViewRequest:c}=this.props,{toolResultMap:u,readContentMap:d,editSnapshotMap:h,askAnswerMap:p,planApprovalMap:g}=mM(n),v=this.props.cliMode&&this.state.ptyPromptHistory.slice().reverse().find(Q=>z$(Q)&&Q.status==="active")||null;let $=null,S=null;for(const Q of n)if(Q.role==="assistant"&&Array.isArray(Q.content))for(const x of Q.content){if(x.type==="tool_use"&&x.name==="ExitPlanMode"){const w=g[x.id];(!w||w.status==="pending")&&($=x.id)}if(x.type==="tool_use"&&x.name==="AskUserQuestion"){const w=p[x.id];(!w||Object.keys(w).length===0)&&(S=x.id)}}const _=[];for(let Q=0;Q<n.length;Q++){const x=n[Q],w=x.content,C=x._timestamp||null,T=C?s[C]:void 0,z=T!=null&&c?{requestIndex:T,onViewRequest:c}:{};if(x.role==="user"){if(Array.isArray(w)){const E=w.find(N=>N.type==="text"&&/^\[SUGGESTION MODE:/i.test((N.text||"").trim())),L=w.filter(N=>N.type==="tool_result");if(!(E&&L.length>0)){const{commands:N,textBlocks:X,skillBlocks:R}=tk(w);for(let k=0;k<N.length;k++)_.push(y.jsx(il,{role:"user",text:N[k],timestamp:C,userProfile:o,modelInfo:i,...z},`${r}-cmd-${Q}-${k}`));for(const k of R){const j=k.text.match(/^#\s+(.+)$/m),A=j?j[1]:"Skill";_.push(y.jsx(il,{role:"skill-loaded",text:k.text,skillName:A,timestamp:C,...z},`${r}-skill-${Q}`))}for(let k=0;k<X.length;k++){const j=/^Implement the following plan:/i.test((X[k].text||"").trim());_.push(y.jsx(il,{role:j?"plan-prompt":"user",text:X[k].text,timestamp:C,userProfile:o,modelInfo:i,...z},`${r}-user-${Q}-${k}`))}}}else if(typeof w=="string"&&!rb(w)){const E=/^Implement the following plan:/i.test(w.trim());_.push(y.jsx(il,{role:E?"plan-prompt":"user",text:w,timestamp:C,userProfile:o,modelInfo:i,...z},`${r}-user-${Q}`))}}else x.role==="assistant"&&(Array.isArray(w)?_.push(y.jsx(il,{role:"assistant",content:w,toolResultMap:u,readContentMap:d,editSnapshotMap:h,askAnswerMap:p,planApprovalMap:g,timestamp:C,modelInfo:i,collapseToolResults:a,expandThinking:l,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:v,lastPendingPlanId:$,lastPendingAskId:S,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,...z},`${r}-asst-${Q}`)):typeof w=="string"&&_.push(y.jsx(il,{role:"assistant",content:[{type:"text",text:w}],toolResultMap:u,readContentMap:d,editSnapshotMap:h,askAnswerMap:p,planApprovalMap:g,timestamp:C,modelInfo:i,collapseToolResults:a,expandThinking:l,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:v,lastPendingPlanId:$,lastPendingAskId:S,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,...z},`${r}-asst-${Q}`)))}return _}buildAllItems(){var v,$,S,_;const{mainAgentSessions:n,requests:r,collapseToolResults:i,expandThinking:s,onViewRequest:o}=this.props;if(!n||n.length===0)return[];const a={};if(r)for(let Q=0;Q<r.length;Q++)Ii(r[Q])&&r[Q].timestamp&&(a[r[Q].timestamp]=Q);let l=null;if(r){for(let Q=r.length-1;Q>=0;Q--)if(Ii(r[Q])&&((v=r[Q].body)!=null&&v.model)){l=r[Q].body.model;break}}const c=l0e(l),u=[],d={},h=[];if(r)for(let Q=0;Q<r.length;Q++){const x=r[Q];if(!x.timestamp)continue;const w=Ad(x,r[Q+1]);if(w.type==="SubAgent"){const C=(S=($=x.response)==null?void 0:$.body)==null?void 0:S.content;if(Array.isArray(C)&&C.length>0){const T=mM(((_=x.body)==null?void 0:_.messages)||[]).toolResultMap;h.push({timestamp:x.timestamp,content:C,toolResultMap:T,label:$P(w.type,w.subType),requestIndex:Q})}}}let p=0;n.forEach((Q,x)=>{var C,T,z,E;x>0&&u.push(y.jsx(UX,{style:{borderColor:"#333",margin:"16px 0"},children:y.jsx(pM,{className:Nn.sessionDividerText,children:"Session"})},`session-div-${x}`));const w=this.renderSessionMessages(Q.messages,`s${x}`,c,a);for(const L of w){const N=L.props.timestamp;for(;p<h.length&&N&&h[p].timestamp<=N;){const X=h[p];X.timestamp&&(d[X.timestamp]=u.length),u.push(y.jsx(il,{role:"sub-agent-chat",content:X.content,toolResultMap:X.toolResultMap,label:X.label,timestamp:X.timestamp,collapseToolResults:i,expandThinking:s,requestIndex:X.requestIndex,onViewRequest:o},`sub-chat-${p}`)),p++}N&&(d[N]=u.length),u.push(L)}for(;p<h.length;){const L=h[p],N=x<n.length-1&&((T=(C=n[x+1].messages)==null?void 0:C[0])==null?void 0:T._timestamp);if(N&&L.timestamp>N)break;L.timestamp&&(d[L.timestamp]=u.length),u.push(y.jsx(il,{role:"sub-agent-chat",content:L.content,toolResultMap:L.toolResultMap,label:L.label,timestamp:L.timestamp,collapseToolResults:i,expandThinking:s,requestIndex:L.requestIndex,onViewRequest:o},`sub-chat-${p}`)),p++}if(x===n.length-1&&((E=(z=Q.response)==null?void 0:z.body)!=null&&E.content)){const L=Q.response.body.content;if(Array.isArray(L)){u.push(y.jsx(ne.Fragment,{children:y.jsx(UX,{style:{borderColor:"#2a2a2a",margin:"8px 0"},children:y.jsx(pM,{type:"secondary",className:Nn.lastResponseLabel,children:ie("ui.lastResponse")})})},"resp-divider")),Q.entryTimestamp&&(d[Q.entryTimestamp]=u.length);let N=null;for(const X of L)X.type==="tool_use"&&X.name==="AskUserQuestion"&&(N=X.id);u.push(y.jsx(il,{role:"assistant",content:L,timestamp:Q.entryTimestamp,modelInfo:c,collapseToolResults:i,expandThinking:s,toolResultMap:{},askAnswerMap:{},lastPendingAskId:N,cliMode:this.props.cliMode,onAskQuestionSubmit:this.handleAskQuestionSubmit},"resp-asst"))}}});const{scrollToTimestamp:g}=this.props;return this._scrollTargetIdx=g&&d[g]!=null?d[g]:null,this._tsItemMap=d,u}_applyMobileSlice(n){if(!Cr)return this._mobileSliceOffset=0,this._totalItemCount=n.length,n;this._totalItemCount=n.length;const r=Gx+this._mobileExtraItems;if(n.length<=r)return this._mobileSliceOffset=0,n;const i=n.length-r;if(this._mobileSliceOffset=i,this._scrollTargetIdx!=null&&(this._scrollTargetIdx-=i,this._scrollTargetIdx<0&&(this._scrollTargetIdx=null)),this._tsItemMap){const s={};for(const[o,a]of Object.entries(this._tsItemMap)){const l=a-i;l>=0&&(s[o]=l)}this._tsItemMap=s}return n.slice(i)}_extractSuggestion(){var h;const{mainAgentSessions:n}=this.props;if(!(n!=null&&n.length))return null;const r=n[n.length-1],i=r==null?void 0:r.messages;if(!Array.isArray(i)||i.length===0)return null;const s=i[i.length-1];if((s==null?void 0:s.role)!=="user")return null;const o=s.content;if(!(Array.isArray(o)?o.some(p=>p.type==="text"&&/^\[SUGGESTION MODE:/i.test((p.text||"").trim())):typeof o=="string"&&/^\[SUGGESTION MODE:/im.test(o.trim())))return null;const l=r==null?void 0:r.response;if(!l)return null;const c=l.body;if(!c)return null;const u=c.stop_reason;if(u!=="end_turn"&&u!=="max_tokens")return null;const d=c.content;if(!Array.isArray(d))return null;for(let p=d.length-1;p>=0;p--)if(d[p].type==="text"&&((h=d[p].text)!=null&&h.trim()))return d[p].text.trim();return null}_updateSuggestion(){const n=this._extractSuggestion();this.setState({inputSuggestion:n||null})}connectInputWs(){const r=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal`;this._inputWs=new WebSocket(r),this._inputWs.onmessage=i=>{try{const s=JSON.parse(i.data);s.type==="data"?this._appendPtyData(s.data):s.type==="exit"&&this._clearPtyPrompt()}catch{}},this._inputWs.onclose=()=>{setTimeout(()=>{this.splitContainerRef.current&&this.props.cliMode&&this.connectInputWs()},2e3)}}_stripAnsi(n){return n.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(n){const r=this._stripAnsi(n);this._ptyBuffer+=r,this._ptyBuffer.length>4096&&(this._ptyBuffer=this._ptyBuffer.slice(-4096)),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._ptyDebounceTimer=setTimeout(()=>this._detectPrompt(),200)}_detectPrompt(){const r=this._ptyBuffer.match(/([^\n]*\?)\s*\n((?:\s*[❯>]?\s*\d+\.\s+[^\n]+\n?){2,})$/);if(r){const i=r[1].trim(),o=r[2].match(/\s*([❯>])?\s*(\d+)\.\s+([^\n]+)/g);if(o){const a=o.map(u=>{const d=u.match(/\s*([❯>])?\s*(\d+)\.\s+(.+)/);return{number:parseInt(d[2],10),text:d[3].trim(),selected:!!d[1]}}),l=this.state.ptyPrompt,c={question:i,options:a};l&&l.question===i?(this._currentPtyPrompt=c,this.setState({ptyPrompt:c})):(this._currentPtyPrompt=c,this.setState(u=>{const d=u.ptyPromptHistory.slice();if(u.ptyPrompt){const h=d[d.length-1];h&&h.status==="active"&&(d[d.length-1]={...h,status:"dismissed"})}return d.push({...c,status:"active",selectedNumber:null,timestamp:new Date().toISOString()}),{ptyPrompt:c,ptyPromptHistory:d}}),this.scrollToBottom());return}}if(this.state.ptyPrompt){if(z$(this.state.ptyPrompt)||this._askSubmitting)return;this._currentPtyPrompt=null,this.setState(i=>{const s=i.ptyPromptHistory.slice(),o=s[s.length-1];return o&&o.status==="active"&&(s[s.length-1]={...o,status:"dismissed"}),{ptyPrompt:null,ptyPromptHistory:s}})}}_clearPtyPrompt(){this._ptyBuffer="",this._currentPtyPrompt=null,this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this.state.ptyPrompt&&this.setState({ptyPrompt:null})}_waitForWsAndSubmit(){if(this._askWsRetries=(this._askWsRetries||0)+1,this._askWsRetries>30){this._askSubmitting=!1,this._askAnswerQueue=[];return}if(this._inputWs&&this._inputWs.readyState===WebSocket.OPEN){this._currentPtyPrompt?this._processNextAskAnswer():(this._askPromptRetries=0,this._waitForPtyPromptAndSubmit());return}setTimeout(()=>this._waitForWsAndSubmit(),100)}_waitForPtyPromptAndSubmit(){if(this._askPromptRetries=(this._askPromptRetries||0)+1,this._askPromptRetries>50){this._processNextAskAnswer();return}if(this._currentPtyPrompt){this._processNextAskAnswer();return}setTimeout(()=>this._waitForPtyPromptAndSubmit(),100)}_processNextAskAnswer(){if(!this._askAnswerQueue||this._askAnswerQueue.length===0){this._askSubmitting=!1;return}const n=this._askAnswerQueue.shift();n.type==="other"?this._submitOtherAnswer(n):n.type==="multi"?this._submitMultiSelectAnswer(n):this._submitSingleSelectAnswer(n)}_submitSingleSelectAnswer(n){const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN){this._askSubmitting=!1;return}const i=this.state.ptyPrompt,s=n.optionIndex+1;let o,a;if(i&&i.options){const h=i.options;o=h.findIndex(p=>p.number===s),o<0&&(o=n.optionIndex),a=h.findIndex(p=>p.selected),a<0&&(a=0)}else o=n.optionIndex,a=0;const l=o-a,c=l>0?"\x1B[B":"\x1B[A",u=Math.abs(l),d=h=>{h<u?(r.send(JSON.stringify({type:"input",data:c})),setTimeout(()=>d(h+1),30)):setTimeout(()=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:"input",data:"\r"})),this._finishCurrentAskAnswer()},50)};d(0)}_submitMultiSelectAnswer(n){const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN){this._askSubmitting=!1;return}const i=this.state.ptyPrompt,s=(n.selectedIndices||[]).slice().sort((l,c)=>l-c);let o=0;i&&i.options&&(o=i.options.findIndex(l=>l.selected),o<0&&(o=0));const a=l=>{if(l>=s.length){setTimeout(()=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:"input",data:"\r"})),this._finishCurrentAskAnswer()},50);return}const c=s[l],u=c-o,d=u>0?"\x1B[B":"\x1B[A",h=Math.abs(u),p=g=>{g<h?(r.send(JSON.stringify({type:"input",data:d})),setTimeout(()=>p(g+1),30)):setTimeout(()=>{r.send(JSON.stringify({type:"input",data:" "})),o=c,setTimeout(()=>a(l+1),50)},50)};p(0)};a(0)}_submitOtherAnswer(n){const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN){this._askSubmitting=!1;return}const i=this.state.ptyPrompt,s=n.optionIndex;let o=0;i&&i.options&&(o=i.options.findIndex(d=>d.selected),o<0&&(o=0));const a=s-o,l=a>0?"\x1B[B":"\x1B[A",c=Math.abs(a),u=d=>{d<c?(r.send(JSON.stringify({type:"input",data:l})),setTimeout(()=>u(d+1),30)):setTimeout(()=>{r.send(JSON.stringify({type:"input",data:"\r"}));const h=this._ptyBuffer;let p=0;const g=()=>{if(p++,p>20||this._ptyBuffer!==h){r.readyState===WebSocket.OPEN&&(r.send(JSON.stringify({type:"input",data:n.text})),setTimeout(()=>{r.send(JSON.stringify({type:"input",data:"\r"})),this._finishCurrentAskAnswer()},50));return}setTimeout(g,100)};setTimeout(g,100)},50)};u(0)}_finishCurrentAskAnswer(){if(this._currentPtyPrompt=null,this.setState(n=>{const r=n.ptyPromptHistory.slice(),i=r[r.length-1];return i&&i.status==="active"&&(r[r.length-1]={...i,status:"answered"}),{ptyPrompt:null,ptyPromptHistory:r}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._askAnswerQueue&&this._askAnswerQueue.length>0){let n=0;const r=()=>{if(n++,n>100){this._askSubmitting=!1,this._askAnswerQueue=[];return}if(this._currentPtyPrompt){this._processNextAskAnswer();return}setTimeout(r,100)};setTimeout(r,200)}else this._askSubmitting=!1}_snapToInitialPosition(){this.setState({terminalWidth:468,needsInitialSnap:!1}),localStorage.setItem("cc-viewer-terminal-width","468")}render(){const{mainAgentSessions:n,cliMode:r,terminalVisible:i}=this.props,{allItems:s,visibleCount:o,loading:a,terminalWidth:l}=this.state,c=!n||n.length===0;if(c&&!r)return y.jsx("div",{className:Nn.centerEmpty,children:y.jsx(vs,{description:ie("ui.noChat")})});if(a&&!r)return y.jsx("div",{className:Nn.centerEmpty,children:y.jsx(Ua,{size:"large"})});const u=this._scrollTargetIdx,{highlightTs:d,highlightFading:h}=this.state,p=d&&this._tsItemMap&&this._tsItemMap[d]!=null?this._tsItemMap[d]:null,g=s.slice(0,o),{pendingInput:v,stickyBottom:$,ptyPromptHistory:S}=this.state,_=r&&v?y.jsx(il,{role:"user",text:v,timestamp:new Date().toISOString(),userProfile:this.props.userProfile},"pending-input"):null,Q=$?null:y.jsxs("button",{className:Nn.stickyBottomBtn,onClick:this.handleStickToBottom,children:[y.jsx("span",{children:ie("ui.stickyBottom")}),y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:y.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),x=r&&S.length>0?S.filter(T=>!(z$(T)&&T.status==="active")).map((T,z)=>{const E=T.status==="active",L=T.status==="answered";return y.jsxs("div",{className:`${Nn.ptyPromptBubble}${E?"":" "+Nn.ptyPromptResolved}`,children:[y.jsx("div",{className:Nn.ptyPromptQuestion,children:T.question}),y.jsx("div",{className:Nn.ptyPromptOptions,children:T.options.map(N=>{const X=L&&T.selectedNumber===N.number;let R=Nn.ptyPromptOption;return E&&N.selected&&(R=Nn.ptyPromptOptionPrimary),X&&(R=Nn.ptyPromptOptionChosen),!E&&!X&&(R=Nn.ptyPromptOptionDimmed),y.jsxs("button",{className:R,disabled:!E,onClick:E?()=>this.handlePromptOptionClick(N.number):void 0,children:[N.number,". ",N.text]},N.number)})})]},`pty-prompt-${z}`)}):null,w=Cr&&this._mobileSliceOffset>0?y.jsx("div",{className:Nn.loadMoreWrap,children:y.jsx("button",{className:Nn.loadMoreBtn,onClick:this.handleLoadMore,children:ie("ui.loadMoreHistory",{count:this._mobileSliceOffset})})}):null,C=c||a?y.jsxs("div",{className:Nn.messageListWrap,children:[y.jsxs("div",{ref:this.containerRef,className:Nn.container,children:[!r||a?y.jsx("div",{className:Nn.centerEmpty,children:a?y.jsx(Ua,{size:"large"}):y.jsx(vs,{description:ie("ui.noChat")})}):null,_,x]}),Q]}):y.jsxs("div",{className:Nn.messageListWrap,children:[y.jsxs("div",{ref:this.containerRef,className:Nn.container,children:[w,g.map((T,z)=>{const E=z===u,L=z===p;let N=T;return L&&(N=ne.cloneElement(N,{highlight:h?"fading":"active"})),E?y.jsx("div",{ref:this._scrollTargetRef,children:N},T.key+"-anchor"):N}),_,x]}),Q]});return r?y.jsxs("div",{ref:this.splitContainerRef,className:Nn.splitContainer,children:[y.jsxs("div",{className:Nn.navSidebar,children:[y.jsx("button",{className:this.state.fileExplorerOpen?Nn.navBtnActive:Nn.navBtn,onClick:()=>{this._setFileExplorerOpen(!this.state.fileExplorerOpen),this.setState({gitChangesOpen:!1})},title:ie("ui.fileExplorer"),children:y.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:y.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"})})}),y.jsx("button",{className:this.state.gitChangesOpen?Nn.navBtnActive:Nn.navBtn,onClick:()=>this.setState(T=>(this._setFileExplorerOpen(!1),{gitChangesOpen:!T.gitChangesOpen})),title:ie("ui.gitChanges"),children:y.jsx("svg",{width:"24",height:"24",viewBox:"0 0 1024 1024",fill:"currentColor",children:y.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"})})})]}),y.jsxs("div",{style:{flex:1,display:"flex",minWidth:0,position:"relative"},ref:this.innerSplitRef,children:[this.state.isDragging&&this.state.activeSnapLine&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const L=T.getBoundingClientRect().width-this.state.terminalWidth-5,N=this.state.activeSnapLine.linePosition,X=Math.min(L,N),R=Math.abs(N-L);return y.jsx("div",{className:Nn.snapPreview,style:{left:`${X}px`,width:`${R}px`}})})(),this.state.isDragging&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const L=T.getBoundingClientRect().width-this.state.terminalWidth-5,N=[...this.state.snapLines].map(k=>({...k,dist:Math.abs(k.linePosition-L)})).sort((k,j)=>k.dist-j.dist);if(N.length===0)return null;const X=N[0],R=this.state.activeSnapLine&&this.state.activeSnapLine.cols===X.cols;return y.jsx("div",{className:R?Nn.snapLineActive:Nn.snapLine,style:{left:`${X.linePosition}px`}},X.cols)})(),this.state.fileExplorerOpen&&y.jsx(QTe,{refreshTrigger:this.state.fileExplorerRefresh,onClose:()=>this._setFileExplorerOpen(!1),onFileClick:T=>this.setState({currentFile:T,currentGitDiff:null,scrollToLine:null}),expandedPaths:this.state.fileExplorerExpandedPaths,onToggleExpand:this.handleToggleExpandPath,currentFile:this.state.currentFile}),this.state.gitChangesOpen&&y.jsx(ULe,{refreshTrigger:this.state.gitChangesRefresh,onClose:()=>this.setState({gitChangesOpen:!1}),onFileClick:T=>this.setState({currentGitDiff:T,currentFile:null})}),y.jsx("div",{className:Nn.chatSection,style:{flex:1,minWidth:0,display:"flex"},children:y.jsxs("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[this.state.currentGitDiff&&y.jsx("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",flexDirection:"column"},children:y.jsx(CVe,{filePath:this.state.currentGitDiff,onClose:()=>this.setState({currentGitDiff:null}),onOpenFile:(T,z)=>{this._setFileExplorerOpen(!0),this.setState({currentGitDiff:null,currentFile:T,scrollToLine:z||1,gitChangesOpen:!1})}})}),this.state.currentFile&&y.jsx("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",flexDirection:"column"},children:OYe(this.state.currentFile)?y.jsx(yLe,{filePath:this.state.currentFile,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch("/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):y.jsx(nLe,{filePath:this.state.currentFile,scrollToLine:this.state.scrollToLine,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch("/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)}),C,!i&&y.jsxs("div",{className:Nn.chatInputBar,children:[y.jsxs("div",{className:Nn.chatInputWrapper,children:[y.jsxs("div",{className:Nn.chatTextareaWrap,children:[y.jsx("textarea",{ref:this._inputRef,className:Nn.chatTextarea,placeholder:this.state.inputSuggestion?"":ie("ui.chatInput.placeholder"),rows:1,onKeyDown:this.handleInputKeyDown,onInput:this.handleInputChange}),this.state.inputSuggestion&&this.state.inputEmpty&&y.jsx("div",{className:Nn.ghostText,children:this.state.inputSuggestion})]}),y.jsx("div",{className:Nn.chatInputHint,children:this.state.inputSuggestion&&this.state.inputEmpty?ie("ui.chatInput.hintTab"):ie("ui.chatInput.hintEnter")})]}),!Cr&&y.jsx("button",{className:Nn.chatSendBtn,onClick:()=>{const T=document.createElement("input");T.type="file",T.onchange=async z=>{var L;const E=(L=z.target.files)==null?void 0:L[0];if(E)try{const X=`"${await PY(E)}"`,R=this._inputRef.current;R&&(R.value=(R.value?R.value+" ":"")+X,R.dispatchEvent(new Event("input",{bubbles:!0})),this.setState({inputEmpty:!1}))}catch(N){console.error("[CC Viewer] Upload failed:",N)}},T.click()},title:ie("ui.terminal.upload"),children:y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[y.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),y.jsx("polyline",{points:"17 8 12 3 7 8"}),y.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]})}),y.jsx("button",{className:Nn.chatSendBtn,onClick:this.handleInputSend,disabled:this.state.inputEmpty,title:ie("ui.chatInput.send"),children:y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[y.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),y.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),i&&this.state.inputSuggestion&&y.jsxs("div",{className:Nn.suggestionChip,onClick:this.handleSuggestionToTerminal,children:[y.jsx("span",{className:Nn.suggestionChipText,children:this.state.inputSuggestion}),y.jsx("span",{className:Nn.suggestionChipAction,children:"↵"})]})]})}),i&&y.jsxs(y.Fragment,{children:[y.jsx("div",{className:Nn.vResizer,onMouseDown:this.handleSplitMouseDown}),y.jsx("div",{style:{width:l,flexShrink:0,minWidth:200,display:"flex",flexDirection:"column"},children:y.jsx(CY,{onEditorOpen:(T,z)=>{this.setState({editorSessionId:T,editorFilePath:z,currentFile:z,currentGitDiff:null,scrollToLine:null,fileVersion:(this.state.fileVersion||0)+1})},onFilePath:T=>{const z=`"${T}"`;this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:z}))}})})]})]})]}):C}}const $Ye="_resizer_yamj2_1",SYe={resizer:$Ye};class bYe extends ne.Component{constructor(e){super(e),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this)}handleMouseDown(e){e.preventDefault(),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}handleMouseMove(e){this.props.onResize&&this.props.onResize(e.clientX)}handleMouseUp(){document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}componentWillUnmount(){document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}render(){return y.jsx("div",{onMouseDown:this.handleMouseDown,className:SYe.resizer})}}const yYe="_container_1um1r_1",_Ye="_fileListSection_1um1r_10",QYe="_header_1um1r_19",xYe="_headerTitle_1um1r_28",wYe="_fileCount_1um1r_36",PYe="_changesContainer_1um1r_44",CYe="_changeItem_1um1r_51",TYe="_changeItemActive_1um1r_68",kYe="_dirItem_1um1r_77",RYe="_dirArrow_1um1r_88",EYe="_dirName_1um1r_97",XYe="_status_1um1r_102",zYe="_icon_1um1r_111",jYe="_fileName_1um1r_120",MYe="_diffSection_1um1r_127",NYe="_diffHeader_1um1r_135",IYe="_diffFilePath_1um1r_145",AYe="_diffBadge_1um1r_155",LYe="_diffContent_1um1r_167",WYe="_diffPlaceholder_1um1r_173",VYe="_statusText_1um1r_184",YYe="_errorText_1um1r_191",BYe="_emptyText_1um1r_198",UYe="_warningText_1um1r_205",Pr={container:yYe,fileListSection:_Ye,header:QYe,headerTitle:xYe,fileCount:wYe,changesContainer:PYe,changeItem:CYe,changeItemActive:TYe,dirItem:kYe,dirArrow:RYe,dirName:EYe,status:XYe,icon:zYe,fileName:jYe,diffSection:MYe,diffHeader:NYe,diffFilePath:IYe,diffBadge:AYe,diffContent:LYe,diffPlaceholder:WYe,statusText:VYe,errorText:YYe,emptyText:BYe,warningText:UYe},qYe={M:"#e2c08d",A:"#73c991",D:"#f14c4c",R:"#73c991",C:"#73c991",U:"#e2c08d","?":"#73c991","??":"#73c991"},DYe={"??":"U"},ZYe={js:"#e8d44d",jsx:"#61dafb",ts:"#3178c6",tsx:"#3178c6",json:"#999",md:"#519aba",css:"#a86fd9",scss:"#cd6799",html:"#e34c26",py:"#3572a5",go:"#00add8",rs:"#dea584"};function GYe(t){const e=t.includes(".")?t.split(".").pop().toLowerCase():"",n=ZYe[e]||"#888";return y.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",children:[y.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),y.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function FYe(){return y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"#c09553",stroke:"none",children:y.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"})})}function HYe(t){const e={dirs:{},files:[]};for(const n of t){const r=n.file.split("/");let i=e;for(let s=0;s<r.length-1;s++)i.dirs[r[s]]||(i.dirs[r[s]]={dirs:{},files:[]}),i=i.dirs[r[s]];i.files.push({name:r[r.length-1],status:n.status,fullPath:n.file})}return e}function QZ({name:t,node:e,depth:n,selectedFile:r,onFileClick:i}){const s=Object.keys(e.dirs).sort(),o=[...e.files].sort((a,l)=>a.name.localeCompare(l.name));return y.jsxs(y.Fragment,{children:[t&&y.jsxs("div",{className:Pr.dirItem,style:{paddingLeft:8+n*16},children:[y.jsx("span",{className:Pr.dirArrow,children:y.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:"rotate(90deg)"},children:y.jsx("polyline",{points:"9 6 15 12 9 18"})})}),y.jsx("span",{className:Pr.icon,children:FYe()}),y.jsx("span",{className:Pr.dirName,children:t})]}),s.map(a=>y.jsx(QZ,{name:a,node:e.dirs[a],depth:t?n+1:n,selectedFile:r,onFileClick:i},a)),o.map(a=>y.jsxs("div",{className:`${Pr.changeItem} ${r===a.fullPath?Pr.changeItemActive:""}`,style:{paddingLeft:8+(t?n+1:n)*16},onClick:()=>i&&i(a.fullPath),children:[y.jsx("span",{className:Pr.icon,children:GYe(a.name)}),y.jsx("span",{className:Pr.fileName,children:a.name}),y.jsx("span",{className:Pr.status,style:{color:qYe[a.status]||"#888"},children:DYe[a.status]||a.status})]},a.fullPath))]})}function KYe({visible:t}){const[e,n]=f.useState(null),[r,i]=f.useState(null),[s,o]=f.useState(!0),[a,l]=f.useState(null),[c,u]=f.useState(null),[d,h]=f.useState(null),[p,g]=f.useState(!1),v=f.useRef(!0);return f.useEffect(()=>{if(v.current=!0,!!t)return o(!0),i(null),fetch(Rn("/api/git-status")).then($=>$.ok?$.json():Promise.reject()).then($=>{v.current&&(n($.changes||[]),o(!1))}).catch(()=>{v.current&&(i("Failed to load git status"),o(!1))}),()=>{v.current=!1}},[t]),f.useEffect(()=>{if(!a){u(null),h(null);return}g(!0),u(null),h(null),fetch(Rn(`/api/git-diff?files=${encodeURIComponent(a)}`)).then($=>{if(!$.ok)throw new Error(`HTTP ${$.status}`);return $.json()}).then($=>{v.current&&($.diffs&&$.diffs[0]?u($.diffs[0]):h("No diff data available"),g(!1))}).catch($=>{v.current&&(h(`${ie("ui.fileLoadError")}: ${$.message}`),g(!1))})},[a]),y.jsxs("div",{className:Pr.container,children:[y.jsxs("div",{className:Pr.fileListSection,children:[y.jsxs("div",{className:Pr.header,children:[y.jsx("span",{className:Pr.headerTitle,children:ie("ui.gitChanges")}),y.jsx("span",{className:Pr.fileCount,children:e?e.length:0})]}),y.jsxs("div",{className:Pr.changesContainer,children:[s&&y.jsx("div",{className:Pr.statusText,children:"Loading..."}),r&&y.jsx("div",{className:Pr.errorText,children:r}),!s&&!r&&e&&e.length===0&&y.jsx("div",{className:Pr.emptyText,children:"No changes"}),!s&&!r&&e&&e.length>0&&y.jsx(QZ,{name:"",node:HYe(e),depth:0,selectedFile:a,onFileClick:l})]})]}),y.jsx("div",{className:Pr.diffSection,children:a?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:Pr.diffHeader,children:[y.jsx("span",{className:Pr.diffFilePath,children:a}),y.jsx("span",{className:Pr.diffBadge,children:"DIFF"})]}),y.jsxs("div",{className:Pr.diffContent,children:[p&&y.jsx("div",{className:Pr.statusText,children:ie("ui.loading")}),d&&y.jsx("div",{className:Pr.errorText,children:d}),!p&&!d&&c&&y.jsx(y.Fragment,{children:c.is_large?y.jsxs("div",{className:Pr.warningText,children:[y.jsx("p",{children:ie("ui.largeFileWarning")}),y.jsxs("p",{style:{color:"#888",fontSize:12},children:[ie("ui.fileSize"),": ",(c.size/(1024*1024)).toFixed(2)," MB"]})]}):c.is_binary?y.jsx("div",{className:Pr.statusText,style:{fontStyle:"italic"},children:ie("ui.binaryFileNotice")}):y.jsx(_Z,{file_path:a,old_string:c.old_content,new_string:c.new_content})})]})]}):y.jsxs("div",{className:Pr.diffPlaceholder,children:[y.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"#333",strokeWidth:"1.5",children:[y.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),y.jsx("circle",{cx:"18",cy:"6",r:"3"}),y.jsx("circle",{cx:"6",cy:"18",r:"3"}),y.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),y.jsx("span",{children:ie("ui.mobileGitDiffHint")})]})})]})}const JYe="_container_rkahp_1",eBe="_header_rkahp_9",tBe="_headerTitle_rkahp_18",nBe="_closeBtn_rkahp_24",rBe="_content_rkahp_38",iBe="_empty_rkahp_47",sBe="_fixedTable_rkahp_54",oBe="_ellipsisCell_rkahp_58",ou={container:JYe,header:eBe,headerTitle:tBe,closeBtn:nBe,content:rBe,empty:iBe,fixedTable:sBe,ellipsisCell:oBe},aBe=["ttl","system_change","tools_change","model_change","msg_truncated","msg_modified","key_change"],vM={ttl:"cacheLoss.ttl",system_change:"cacheLoss.systemChange",tools_change:"cacheLoss.toolsChange",model_change:"cacheLoss.modelChange",msg_truncated:"cacheLoss.msgTruncated",msg_modified:"cacheLoss.msgModified",key_change:"cacheLoss.keyChange"};function lBe({requests:t=[],visible:e,onClose:n}){if(!e)return null;const{byModel:r,models:i,toolStats:s,skillStats:o,cacheStats:a,activeReasons:l,totalCount:c,totalCache:u,hasCacheStats:d,subAgentEntries:h,hasSubAgentStats:p,isEmpty:g}=f.useMemo(()=>{const v=zW(t),$=Object.keys(v),S=MW(t),_=NW(t),Q=jW(t),x=aBe.filter(X=>Q[X].count>0),w=x.reduce((X,R)=>X+Q[R].count,0),C=x.reduce((X,R)=>X+Q[R].cacheCreate,0),T=x.length>0,z={};for(let X=0;X<t.length;X++){const R=Ad(t[X],t[X+1]);if(R.type==="SubAgent"){const k=R.subType||"Other";z[k]=(z[k]||0)+1}}const E=Object.entries(z).sort((X,R)=>R[1]-X[1]),L=E.length>0,N=$.length===0&&S.length===0&&!T&&!L&&_.length===0;return{byModel:v,models:$,toolStats:S,skillStats:_,cacheStats:Q,activeReasons:x,totalCount:w,totalCache:C,hasCacheStats:T,subAgentEntries:E,hasSubAgentStats:L,isEmpty:N}},[t]);return y.jsxs("div",{className:ou.container,children:[y.jsxs("div",{className:ou.header,children:[y.jsx("span",{className:ou.headerTitle,children:ie("ui.tokenStats")}),y.jsx("button",{className:ou.closeBtn,onClick:n,children:y.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y.jsx("div",{className:ou.content,children:g?y.jsx("div",{className:ou.empty,children:"—"}):y.jsxs(y.Fragment,{children:[o.length>0&&y.jsxs("div",{className:pe.modelCard,children:[y.jsx("div",{className:pe.modelName,children:ie("ui.skillUsageStats")}),y.jsxs("table",{className:pe.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:pe.th,style:{textAlign:"left"},children:"Skill"}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[o.map(([v,$])=>y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:pe.label,children:v}),y.jsx("td",{className:pe.td,children:$})]},v)),o.length>1&&y.jsxs("tr",{className:pe.rebuildTotalRow,children:[y.jsx("td",{className:pe.label,children:"Total"}),y.jsx("td",{className:pe.td,children:o.reduce((v,$)=>v+$[1],0)})]})]})]})]}),p&&y.jsxs("div",{className:pe.modelCard,children:[y.jsx("div",{className:pe.modelName,children:ie("ui.subAgentStats")}),y.jsxs("table",{className:pe.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:pe.th,style:{textAlign:"left"},children:"SubAgent"}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[h.map(([v,$])=>y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:pe.label,children:v}),y.jsx("td",{className:pe.td,children:$})]},v)),h.length>1&&y.jsxs("tr",{className:pe.rebuildTotalRow,children:[y.jsx("td",{className:pe.label,children:"Total"}),y.jsx("td",{className:pe.td,children:h.reduce((v,$)=>v+$[1],0)})]})]})]})]}),s.length>0&&y.jsxs("div",{className:pe.modelCard,children:[y.jsx("div",{className:pe.modelName,children:ie("ui.toolUsageStats")}),y.jsxs("table",{className:pe.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:pe.th,style:{textAlign:"left"},children:"Tool"}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[s.map(([v,$])=>y.jsxs("tr",{className:pe.rowBorder,children:[y.jsxs("td",{className:pe.label,children:[v," ",y.jsx(yc,{doc:`Tool-${v}`})]}),y.jsx("td",{className:pe.td,children:$})]},v)),s.length>1&&y.jsxs("tr",{className:pe.rebuildTotalRow,children:[y.jsx("td",{className:pe.label,children:"Total"}),y.jsx("td",{className:pe.td,children:s.reduce((v,$)=>v+$[1],0)})]})]})]})]}),d&&y.jsxs("div",{className:pe.modelCard,children:[y.jsxs("div",{className:pe.modelName,children:["MainAgent",y.jsx(yc,{doc:"MainAgent"})," ",ie("ui.cacheRebuildStats"),y.jsx(yc,{doc:"CacheRebuild"})]}),y.jsxs("table",{className:`${pe.statsTable} ${ou.fixedTable}`,children:[y.jsxs("colgroup",{children:[y.jsx("col",{style:{width:"50%"}}),y.jsx("col",{style:{width:"25%"}}),y.jsx("col",{style:{width:"25%"}})]}),y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:pe.th,style:{textAlign:"left"},children:ie("ui.cacheRebuild.reason")}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.count")}),y.jsx("td",{className:pe.th,children:ie("ui.cacheRebuild.cacheCreate")})]})}),y.jsxs("tbody",{children:[l.map(v=>y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:`${pe.label} ${ou.ellipsisCell}`,title:ie(`ui.${vM[v]}`),children:ie(`ui.${vM[v]}`)}),y.jsx("td",{className:pe.td,children:a[v].count}),y.jsx("td",{className:pe.td,children:Er(a[v].cacheCreate)})]},v)),l.length>1&&y.jsxs("tr",{className:pe.rebuildTotalRow,children:[y.jsx("td",{className:pe.label,children:"Total"}),y.jsx("td",{className:pe.td,children:c}),y.jsx("td",{className:pe.td,children:Er(u)})]})]})]})]}),i.map(v=>{const $=r[v],S=$.input+$.cacheCreation+$.cacheRead,_=S>0?($.cacheRead/S*100).toFixed(1):"0.0";return y.jsxs("div",{className:pe.modelCard,children:[y.jsx("div",{className:pe.modelName,children:v}),y.jsx("table",{className:pe.statsTable,children:y.jsxs("tbody",{children:[y.jsxs("tr",{children:[y.jsx("td",{className:pe.label,children:"Token"}),y.jsx("td",{className:pe.th,children:"input"}),y.jsx("td",{className:pe.th,children:"output"})]}),y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:pe.label}),y.jsx("td",{className:pe.td,children:Er(S)}),y.jsx("td",{className:pe.td,children:Er($.output)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:pe.label,children:"Cache"}),y.jsx("td",{className:pe.th,children:"create"}),y.jsx("td",{className:pe.th,children:"read"})]}),y.jsxs("tr",{className:pe.rowBorder,children:[y.jsx("td",{className:pe.label}),y.jsx("td",{className:pe.td,children:Er($.cacheCreation)}),y.jsx("td",{className:pe.td,children:Er($.cacheRead)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:pe.label,children:ie("ui.hitRate")}),y.jsxs("td",{colSpan:2,className:pe.td,children:[_,"%"]})]})]})})]},v)})]})})]})}const{Text:Pd,Title:cBe}=Ga;function uBe(t){if(!t)return"0 B";const e=["B","KB","MB","GB"];let n=0,r=t;for(;r>=1024&&n<e.length-1;)r/=1024,n++;return`${r.toFixed(n>0?1:0)} ${e[n]}`}function dBe(t){if(!t)return"";const e=Date.now()-new Date(t).getTime(),n=Math.floor(e/6e4);if(n<1)return ie("ui.workspaces.justNow");if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function OBe({open:t,onClose:e,onSelect:n}){const[r,i]=f.useState(""),[s,o]=f.useState(null),[a,l]=f.useState([]),[c,u]=f.useState(!1),[d,h]=f.useState(""),p=f.useCallback(v=>{u(!0);const $=v?`/api/browse-dir?path=${encodeURIComponent(v)}`:"/api/browse-dir";fetch(Rn($)).then(S=>S.json()).then(S=>{S.error?ar.error(S.error):(i(S.current),o(S.parent),l(S.dirs||[]),h(S.current)),u(!1)}).catch(()=>{ar.error("Failed to browse directory"),u(!1)})},[]);f.useEffect(()=>{t&&p("")},[t,p]);const g=()=>{const v=d.trim();v&&p(v)};return y.jsxs(Ti,{title:ie("ui.workspaces.selectDir"),open:t,onCancel:e,footer:null,width:600,styles:{body:{padding:"12px 0"}},children:[y.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"0 16px 10px",borderBottom:"1px solid #2a2a2a"},children:[y.jsx(Sn,{type:"text",icon:y.jsx(gve,{}),disabled:!s,onClick:()=>s&&p(s),size:"small"}),y.jsxs(Pd,{style:{color:"#e0e0e0",fontSize:13,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[y.jsx(i1,{style:{marginRight:6,color:"#1668dc"}}),r]})]}),y.jsx("div",{style:{maxHeight:400,overflowY:"auto",padding:"4px 0"},children:c?y.jsx("div",{style:{textAlign:"center",padding:40},children:y.jsx(Ua,{})}):a.length===0?y.jsx("div",{style:{textAlign:"center",padding:40},children:y.jsx(Pd,{type:"secondary",children:ie("ui.workspaces.emptyDir")})}):a.map(v=>y.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 16px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:$=>$.currentTarget.style.background="#1a1a1a",onMouseLeave:$=>$.currentTarget.style.background="transparent",children:[y.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:8,minWidth:0},onClick:()=>p(v.path),children:[y.jsx(aW,{style:{color:v.hasGit?"#1668dc":"#666",fontSize:16,flexShrink:0}}),y.jsx(Pd,{style:{color:"#d0d0d0",fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name}),v.hasGit&&y.jsxs(eo,{color:"blue",style:{fontSize:11,lineHeight:"18px",padding:"0 4px",margin:0,flexShrink:0},children:[y.jsx($W,{style:{marginRight:2}}),"git"]})]}),y.jsx(Sn,{type:"primary",size:"small",onClick:$=>{$.stopPropagation(),n(v.path)},children:ie("ui.workspaces.select")})]},v.path))}),y.jsxs("div",{style:{borderTop:"1px solid #2a2a2a",padding:"10px 16px 4px",display:"flex",flexDirection:"column",gap:8},children:[y.jsxs(Sn,{type:"primary",ghost:!0,block:!0,icon:y.jsx(i1,{}),onClick:()=>n(r),children:[ie("ui.workspaces.selectCurrent")," — ",r.split("/").pop()||r]}),y.jsxs("div",{style:{display:"flex",gap:8},children:[y.jsx(Wu,{size:"small",value:d,onChange:v=>h(v.target.value),onPressEnter:g,placeholder:ie("ui.workspaces.pathPlaceholder"),style:{flex:1}}),y.jsx(Sn,{size:"small",onClick:g,children:ie("ui.workspaces.goTo")})]})]})]})}function hBe({onLaunch:t}){const[e,n]=f.useState([]),[r,i]=f.useState(!0),[s,o]=f.useState(null),[a,l]=f.useState(!1),c=()=>{fetch(Rn("/api/workspaces")).then(p=>p.json()).then(p=>{n(p.workspaces||[]),i(!1)}).catch(()=>i(!1))};f.useEffect(()=>{c()},[]);const u=p=>{l(!1),fetch(Rn("/api/workspaces/add"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p})}).then(g=>g.json()).then(g=>{g.error?ar.error(g.error):c()}).catch(()=>ar.error("Failed to add workspace"))},d=p=>{fetch(Rn(`/api/workspaces/${p}`),{method:"DELETE"}).then(g=>g.json()).then(()=>c()).catch(()=>{})},h=p=>{o(p.id),fetch(Rn("/api/workspaces/launch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p.path})}).then(g=>g.json()).then(g=>{g.error?(ar.error(g.error),o(null)):t({projectName:g.projectName,path:p.path})}).catch(()=>{ar.error("Launch failed"),o(null)})};return y.jsxs("div",{style:{minHeight:"100vh",background:"#0a0a0a",display:"flex",justifyContent:"center",paddingTop:60},children:[y.jsxs("div",{style:{width:"100%",maxWidth:720,padding:"0 24px"},children:[y.jsxs("div",{style:{marginBottom:32,textAlign:"center"},children:[y.jsxs(cBe,{level:3,style:{color:"#e0e0e0",margin:0},children:[y.jsx(i1,{style:{marginRight:8,color:"#1668dc"}}),ie("ui.workspaces.title")]}),y.jsx(Pd,{type:"secondary",style:{fontSize:13},children:ie("ui.workspaces.subtitle")})]}),y.jsx("div",{style:{marginBottom:20,textAlign:"center"},children:y.jsx(Sn,{type:"primary",icon:y.jsx(J$,{}),onClick:()=>l(!0),size:"large",children:ie("ui.workspaces.browse")})}),r?y.jsx("div",{style:{textAlign:"center",padding:60},children:y.jsx(Ua,{})}):e.length===0?y.jsx(vs,{description:y.jsx(Pd,{type:"secondary",children:ie("ui.workspaces.empty")}),style:{marginTop:60}}):y.jsx(n1,{dataSource:e,renderItem:p=>y.jsx(IT,{size:"small",style:{marginBottom:10,background:"#141414",borderColor:"#2a2a2a",cursor:"pointer"},hoverable:!0,onClick:()=>h(p),children:y.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[y.jsxs("div",{style:{flex:1,minWidth:0},children:[y.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:y.jsx(Pd,{strong:!0,style:{color:"#e0e0e0",fontSize:15},children:p.projectName})}),y.jsx(Pd,{type:"secondary",style:{fontSize:12,wordBreak:"break-all"},children:p.path}),y.jsxs("div",{style:{display:"flex",gap:16,marginTop:6,fontSize:12,color:"#666"},children:[y.jsxs("span",{children:[y.jsx(Ede,{style:{marginRight:4}}),dBe(p.lastUsed)]}),p.logCount>0&&y.jsxs("span",{children:[y.jsx(Cve,{style:{marginRight:4}}),p.logCount," logs (",uBe(p.totalSize),")"]})]})]}),y.jsxs(bl,{children:[y.jsx(Sn,{type:"primary",icon:y.jsx(Wve,{}),loading:s===p.id,onClick:g=>{g.stopPropagation(),h(p)},children:ie("ui.workspaces.open")}),y.jsx(AL,{title:ie("ui.workspaces.confirmRemove"),onConfirm:g=>{g==null||g.stopPropagation(),d(p.id)},onCancel:g=>g==null?void 0:g.stopPropagation(),okText:"Yes",cancelText:"No",children:y.jsx(Sn,{type:"text",danger:!0,icon:y.jsx(o1,{}),onClick:g=>g.stopPropagation()})})]})]})},p.id)})]}),y.jsx(OBe,{open:a,onClose:()=>l(!1),onSelect:u})]})}const fBe="_layout_1a3p0_1",pBe="_header_1a3p0_6",mBe="_content_1a3p0_14",gBe="_mainContainer_1a3p0_19",vBe="_leftPanel_1a3p0_24",$Be="_leftPanelHeader_1a3p0_32",SBe="_leftPanelCount_1a3p0_43",bBe="_leftPanelBody_1a3p0_49",yBe="_rightPanel_1a3p0_54",_Be="_modalActions_1a3p0_60",QBe="_spinCenter_1a3p0_64",xBe="_emptyCenter_1a3p0_69",wBe="_logListContainer_1a3p0_79",PBe="_loadingOverlay_1a3p0_127",CBe="_loadingText_1a3p0_140",TBe="_mobileLoadingOverlay_1a3p0_146",kBe="_mobileLoadingSpinner_1a3p0_158",RBe="_mobileLoadingLabel_1a3p0_171",EBe="_footer_1a3p0_177",XBe="_footerRight_1a3p0_188",zBe="_footerText_1a3p0_196",jBe="_footerLink_1a3p0_201",MBe="_footerIcon_1a3p0_213",NBe="_footerDivider_1a3p0_218",IBe="_guideContainer_1a3p0_226",ABe="_guideContent_1a3p0_234",LBe="_guideTitle_1a3p0_239",WBe="_guideStep_1a3p0_246",VBe="_guideStepNum_1a3p0_252",YBe="_guideStepBody_1a3p0_267",BBe="_guideText_1a3p0_272",UBe="_guideCode_1a3p0_279",qBe="_mobileChatOverlay_1a3p0_292",DBe="_mobileChatOverlayVisible_1a3p0_304",ZBe="_mobileChatInner_1a3p0_308",GBe="_mobileGitDiffOverlay_1a3p0_316",FBe="_mobileGitDiffOverlayVisible_1a3p0_328",HBe="_mobileGitDiffInner_1a3p0_332",KBe="_mobileMenuBtn_1a3p0_340",JBe="_mobileMenuOverlay_1a3p0_357",eUe="_mobileMenuDropdown_1a3p0_363",tUe="_mobileMenuItem_1a3p0_377",nUe="_mobileStatsOverlay_1a3p0_395",rUe="_mobileStatsOverlayVisible_1a3p0_407",iUe="_mobileStatsInner_1a3p0_411",sUe="_mobileLogMgmtOverlay_1a3p0_418",oUe="_mobileLogMgmtOverlayVisible_1a3p0_430",aUe="_mobileLogMgmtHeader_1a3p0_434",lUe="_mobileLogMgmtTitle_1a3p0_443",cUe="_mobileLogMgmtClose_1a3p0_449",uUe="_mobileLogMgmtActions_1a3p0_464",dUe="_mobileLogMgmtBody_1a3p0_472",OUe="_mobileSettingsOverlay_1a3p0_479",hUe="_mobileSettingsOverlayVisible_1a3p0_491",fUe="_mobilePromptOverlay_1a3p0_495",pUe="_mobilePromptOverlayVisible_1a3p0_507",mUe="_mobilePromptBody_1a3p0_511",gUe="_mobilePromptList_1a3p0_519",vUe="_mobilePromptItem_1a3p0_525",$Ue="_mobilePromptTimestamp_1a3p0_530",SUe="_mobilePromptCard_1a3p0_537",bUe="_mobilePromptPreText_1a3p0_545",yUe="_previewPopover_1a3p0_555",_Ue="_previewItem_1a3p0_561",QUe="_previewText_1a3p0_573",bt={layout:fBe,header:pBe,content:mBe,mainContainer:gBe,leftPanel:vBe,leftPanelHeader:$Be,leftPanelCount:SBe,leftPanelBody:bBe,rightPanel:yBe,modalActions:_Be,spinCenter:QBe,emptyCenter:xBe,logListContainer:wBe,loadingOverlay:PBe,loadingText:CBe,mobileLoadingOverlay:TBe,mobileLoadingSpinner:kBe,mobileLoadingLabel:RBe,footer:EBe,footerRight:XBe,footerText:zBe,footerLink:jBe,footerIcon:MBe,footerDivider:NBe,guideContainer:IBe,guideContent:ABe,guideTitle:LBe,guideStep:WBe,guideStepNum:VBe,guideStepBody:YBe,guideText:BBe,guideCode:UBe,mobileChatOverlay:qBe,mobileChatOverlayVisible:DBe,mobileChatInner:ZBe,mobileGitDiffOverlay:GBe,mobileGitDiffOverlayVisible:FBe,mobileGitDiffInner:HBe,mobileMenuBtn:KBe,mobileMenuOverlay:JBe,mobileMenuDropdown:eUe,mobileMenuItem:tUe,mobileStatsOverlay:nUe,mobileStatsOverlayVisible:rUe,mobileStatsInner:iUe,mobileLogMgmtOverlay:sUe,mobileLogMgmtOverlayVisible:oUe,mobileLogMgmtHeader:aUe,mobileLogMgmtTitle:lUe,mobileLogMgmtClose:cUe,mobileLogMgmtActions:uUe,mobileLogMgmtBody:dUe,mobileSettingsOverlay:OUe,mobileSettingsOverlayVisible:hUe,mobilePromptOverlay:fUe,mobilePromptOverlayVisible:pUe,mobilePromptBody:mUe,mobilePromptList:gUe,mobilePromptItem:vUe,mobilePromptTimestamp:$Ue,mobilePromptCard:SUe,mobilePromptPreText:bUe,previewPopover:yUe,previewItem:_Ue,previewText:QUe},xUe="ccv_entryCache",Au="entries",Y5="cache",B5="ccv_cacheMeta",wUe=1,PUe=10080*60*1e3;let UO=null,qO=null;function U5(){return UO?Promise.resolve(UO):qO||(qO=new Promise((t,e)=>{const n=indexedDB.open(xUe,wUe);n.onupgradeneeded=()=>{const r=n.result;r.objectStoreNames.contains(Au)||r.createObjectStore(Au)},n.onsuccess=()=>{UO=n.result,UO.onclose=()=>{UO=null},qO=null,t(UO)},n.onerror=()=>{qO=null,e(n.error)}}),qO)}let $M=0;function CUe(t,e){try{const n=e[e.length-1],r=(n==null?void 0:n.timestamp)||null;r&&localStorage.setItem(B5,JSON.stringify({projectName:t,lastTs:r,count:e.length}))}catch{}}function TUe(){try{localStorage.removeItem(B5)}catch{}}function kUe(){try{const t=localStorage.getItem(B5);if(!t)return null;const e=JSON.parse(t);return e!=null&&e.lastTs&&(e==null?void 0:e.count)>0&&(e!=null&&e.projectName)?e:null}catch{return null}}async function Fx(t,e){if(!t||!Array.isArray(e)||e.length===0)return;const n=++$M;try{const r=await U5();return n!==$M?void 0:(CUe(t,e),new Promise(i=>{const s=r.transaction(Au,"readwrite");s.objectStore(Au).put({projectName:t,entries:e,ts:Date.now()},Y5),s.oncomplete=()=>i(),s.onerror=()=>i()}))}catch{}}async function RUe(t){try{const e=await U5();return new Promise(n=>{const i=e.transaction(Au,"readonly").objectStore(Au).get(Y5);i.onsuccess=()=>{const s=i.result;!s||s.projectName!==t||!Array.isArray(s.entries)||s.entries.length===0?n(null):s.ts&&Date.now()-s.ts>PUe?(I2(),n(null)):n(s.entries)},i.onerror=()=>n(null)})}catch{return null}}async function I2(){TUe();try{const t=await U5();return new Promise(e=>{const n=t.transaction(Au,"readwrite");n.objectStore(Au).delete(Y5),n.oncomplete=()=>e(),n.onerror=()=>e()})}catch{}}const hh=class hh extends ne.Component{constructor(n){super(n);Qt(this,"handleSelectRequest",n=>{this.setState({selectedIndex:n,scrollCenter:!1})});Qt(this,"handleViewRequest",n=>{this.setState({viewMode:"raw",selectedIndex:n,scrollCenter:!0})});Qt(this,"handleViewInChat",()=>{this.setState(n=>{const i=(n.showAll?n.requests:Ra(n.requests))[n.selectedIndex];if(!i)return null;let s=null;if(Ii(i)&&i.timestamp)s=i.timestamp;else{if(Ad(i).type==="SubAgent"&&i.timestamp)s=i.timestamp;else{const a=n.requests.indexOf(i);a>=0&&(s=H8(n.requests,a))}s||ar.info(ie("ui.cannotMap"))}return{viewMode:"chat",chatScrollToTs:s}})});Qt(this,"handleWorkspaceLaunch",({projectName:n})=>{this._isLocalLog=!1,this._localLogFile=null,this.setState({workspaceMode:!1,projectName:n,viewMode:"chat",cliMode:!0})});Qt(this,"handleReturnToWorkspaces",()=>{fetch(Rn("/api/workspaces/stop"),{method:"POST"}).then(()=>{this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null})}).catch(()=>{})});Qt(this,"handleToggleViewMode",()=>{this.setState(n=>{const r=n.viewMode==="raw"?"chat":"raw";if(r==="raw"){if(n.selectedIndex===null){const o=n.showAll?n.requests:Ra(n.requests);return{viewMode:r,selectedIndex:o.length>0?o.length-1:null,scrollCenter:!0}}return{viewMode:r,scrollCenter:!0}}const i=n.showAll?n.requests:Ra(n.requests),s=n.selectedIndex!=null?i[n.selectedIndex]:null;if(s){let o=null;if(Ii(s)&&s.timestamp)o=s.timestamp;else if(Ad(s).type==="SubAgent"&&s.timestamp)o=s.timestamp;else{const l=n.requests.indexOf(s);l>=0&&(o=H8(n.requests,l)),o||ar.info(ie("ui.cannotMap"))}return{viewMode:r,chatScrollToTs:o}}return{viewMode:r,chatScrollToTs:null}})});Qt(this,"handleLangChange",()=>{const n=xm();this.setState({lang:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:n})}).catch(()=>{})});Qt(this,"handleCollapseToolResultsChange",n=>{this.setState({collapseToolResults:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({collapseToolResults:n})}).catch(()=>{})});Qt(this,"handleExpandThinkingChange",n=>{this.setState({expandThinking:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandThinking:n})}).catch(()=>{})});Qt(this,"handleExpandDiffChange",n=>{this.setState({expandDiff:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandDiff:n})}).catch(()=>{})});Qt(this,"handleFilterIrrelevantChange",n=>{this.setState(r=>{const i=!n,s=i?r.requests:Ra(r.requests);return{showAll:i,selectedIndex:s.length>0?s.length-1:null}}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filterIrrelevant:n})}).catch(()=>{})});Qt(this,"handleExportPromptsTxt",n=>{if(!n||n.length===0)return;const r=[];for(const a of n){const l=[],c=a.timestamp?new Date(a.timestamp).toLocaleString():"";c&&l.push(`${c}:
712
712
  `);const u=(a.segments||[]).filter(d=>d.type==="text").map(d=>d.content);u.length>0&&l.push(u.join(`
713
713
  `)),r.push(l.join(`
714
714
  `))}if(r.length===0)return;const i=new Blob([r.join(`
package/dist/index.html CHANGED
@@ -6,7 +6,7 @@
6
6
  <title>Claude Code Viewer</title>
7
7
  <link rel="icon" href="/favicon.ico?v=1">
8
8
  <link rel="shortcut icon" href="/favicon.ico?v=1">
9
- <script type="module" crossorigin src="/assets/index-BZF6sLuX.js"></script>
9
+ <script type="module" crossorigin src="/assets/index-DE82wI5t.js"></script>
10
10
  <link rel="stylesheet" crossorigin href="/assets/index-CjyNZk4n.css">
11
11
  </head>
12
12
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.5.42",
3
+ "version": "1.5.43",
4
4
  "description": "Claude Code Logger visualization management tool",
5
5
  "license": "MIT",
6
6
  "main": "server.js",