cc-viewer 1.4.28 → 1.4.29
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.
|
@@ -713,6 +713,6 @@ https://github.com/highlightjs/highlight.js/issues/2277`),un=be,zt=je),tt===void
|
|
|
713
713
|
`);if(o.value!=="")if(o.added)for(let c=0;c<l.length;c++)r.set(i++,{type:"add",oldContent:null});else if(o.removed){const c=l;s+=c.length;const u=n.indexOf(o)+1;if(u<n.length&&n[u].added){const h=n[u].value.replace(/\n$/,"").split(`
|
|
714
714
|
`),p=Math.min(c.length,h.length);for(let m=0;m<p;m++)r.set(i++,{type:"modify",oldContent:c[m]});for(let m=p;m<h.length;m++)r.set(i++,{type:"add",oldContent:null});n.splice(u,1)}}else i+=l.length,s+=l.length}return r}function r8({file_path:e,old_string:t,new_string:n}){const r=f.useRef(null),i=f.useRef(null);f.useEffect(()=>{const b=i.current,y=r.current;if(!b||!y)return;const w=()=>{y.scrollTop=b.scrollTop};return b.addEventListener("scroll",w),()=>b.removeEventListener("scroll",w)});const s=!n||n.trim()==="",o=!t||t.trim()==="",l=f.useMemo(()=>s||o?new Map:$le(t,n),[t,n,s,o]),c=s?t:n,u=c.split(`
|
|
715
715
|
`),h=kle(e),p=f.useMemo(()=>{if(h)try{return an.highlight(c,{language:h}).value.split(`
|
|
716
|
-
`)}catch{return u}return u},[c,h,u]),m=o?u.length:Array.from(l.values()).filter(b=>b.type==="add").length,v=Array.from(l.values()).filter(b=>b.type==="modify").length,_=s?u.length:0;return S.jsxs("div",{className:_r.fullFileDiffView,children:[S.jsxs("div",{className:_r.diffSummary,children:[m>0&&S.jsxs("span",{className:_r.addedBadge,children:["+",m]}),v>0&&S.jsxs("span",{className:_r.modifiedBadge,children:["~",v]}),_>0&&S.jsxs("span",{className:_r.deletedBadge,children:["-",_]})]}),S.jsxs("div",{className:_r.codeContainer,children:[S.jsx("div",{className:_r.lineNumberCol,ref:r,children:p.map((b,y)=>{const w=y+1,x=l.get(w);let E=_r.lineNumNormal;return s?E=_r.lineNumDelete:o?E=_r.lineNumAdd:x&&(E=x.type==="add"?_r.lineNumAdd:_r.lineNumModify),S.jsx("div",{className:E,children:w},y)})}),S.jsx("div",{className:_r.codeCol,ref:i,children:S.jsx("div",{className:_r.codeInner,children:p.map((b,y)=>{const w=y+1,x=l.get(w);let E;return s?E=_r.lineDelete:o?E=_r.lineAdd:x?E=x.type==="add"?_r.lineAdd:_r.lineModify:E=_r.lineNormal,S.jsxs("div",{className:`${_r.codeLine} ${E}`,children:[S.jsx("span",{className:_r.lineContent,dangerouslySetInnerHTML:{__html:b||" "}}),x&&x.oldContent!==null&&S.jsxs("div",{className:_r.oldContentTooltip,children:[S.jsx("div",{className:_r.tooltipLabel,children:"原内容:"}),S.jsx("div",{className:_r.tooltipContent,children:x.oldContent})]})]},y)})})})]})]})}const Rle="_gitDiffView_14i1p_1",Tle="_header_14i1p_9",Nle="_headerLeft_14i1p_19",Mle="_backBtn_14i1p_27",Ole="_filePath_14i1p_48",Ile="_diffBadge_14i1p_57",Ple="_contentContainer_14i1p_69",Lle="_loading_14i1p_75",Ale="_error_14i1p_84",Ble="_binaryNotice_14i1p_95",zle="_largeFileWarning_14i1p_107",jle="_fileSize_14i1p_120",As={gitDiffView:Rle,header:Tle,headerLeft:Nle,backBtn:Mle,filePath:Ole,diffBadge:Ile,contentContainer:Ple,loading:Lle,error:Ale,binaryNotice:Ble,largeFileWarning:zle,fileSize:jle};function Dle({filePath:e,onClose:t}){const[n,r]=f.useState(null),[i,s]=f.useState(null),[o,l]=f.useState(!0),c=f.useRef(!0);return f.useEffect(()=>(c.current=!0,l(!0),r(null),s(null),fetch(`/api/git-diff?files=${encodeURIComponent(e)}`).then(u=>u.ok?u.json():u.json().then(h=>{throw new Error(h.error||"Failed to load diff")}).catch(()=>{throw new Error(`HTTP ${u.status}`)})).then(u=>{c.current&&(u.diffs&&u.diffs[0]?r(u.diffs[0]):s("No diff data available"),l(!1))}).catch(u=>{c.current&&(s(`${he("ui.fileLoadError")}: ${u.message}`),l(!1))}),()=>{c.current=!1}),[e]),S.jsxs("div",{className:As.gitDiffView,children:[S.jsx("div",{className:As.header,children:S.jsxs("div",{className:As.headerLeft,children:[S.jsx("button",{className:As.backBtn,onClick:t,title:he("ui.backToChat"),children:S.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:S.jsx("polyline",{points:"15 18 9 12 15 6"})})}),S.jsx("span",{className:As.filePath,children:e}),S.jsx("span",{className:As.diffBadge,children:"DIFF"})]})}),S.jsxs("div",{className:As.contentContainer,children:[o&&S.jsx("div",{className:As.loading,children:he("ui.loading")}),i&&S.jsx("div",{className:As.error,children:i}),!o&&!i&&n&&S.jsx(S.Fragment,{children:n.is_large?S.jsxs("div",{className:As.largeFileWarning,children:[S.jsx("p",{children:he("ui.largeFileWarning")}),S.jsxs("p",{className:As.fileSize,children:[he("ui.fileSize"),": ",(n.size/(1024*1024)).toFixed(2)," MB"]})]}):n.is_binary?S.jsx("div",{className:As.binaryNotice,children:he("ui.binaryFileNotice")}):S.jsx(r8,{file_path:e,old_string:n.old_content,new_string:n.new_content})})]})]})}const Fle="_centerEmpty_8tuwm_1",Hle="_container_8tuwm_8",Wle="_sessionDividerText_8tuwm_18",Vle="_lastResponseLabel_8tuwm_23",Ule="_splitContainer_8tuwm_27",qle="_chatSection_8tuwm_34",Gle="_vResizer_8tuwm_41",Kle="_snapLine_8tuwm_55",Xle="_snapLineActive_8tuwm_67",Yle="_snapPreview_8tuwm_94",Zle="_chatInputBar_8tuwm_107",Qle="_chatInputWrapper_8tuwm_117",Jle="_chatTextareaWrap_8tuwm_132",ece="_chatTextarea_8tuwm_132",tce="_chatInputHint_8tuwm_156",nce="_chatSendBtn_8tuwm_163",rce="_messageListWrap_8tuwm_192",ice="_stickyBottomBtn_8tuwm_200",sce="_ptyPromptBubble_8tuwm_233",oce="_ptyPromptResolved_8tuwm_242",ace="_ptyPromptQuestion_8tuwm_251",lce="_ptyPromptOptions_8tuwm_258",cce="_ptyPromptOption_8tuwm_258",uce="_ptyPromptOptionPrimary_8tuwm_282",dce="_ptyPromptOptionChosen_8tuwm_300",hce="_ptyPromptOptionDimmed_8tuwm_311",fce="_ghostText_8tuwm_322",pce="_suggestionChip_8tuwm_338",mce="_suggestionChipText_8tuwm_354",gce="_suggestionChipAction_8tuwm_363",vce="_navSidebar_8tuwm_369",_ce="_navBtn_8tuwm_381",bce="_navBtnActive_8tuwm_401",mn={centerEmpty:Fle,container:Hle,sessionDividerText:Wle,lastResponseLabel:Vle,splitContainer:Ule,chatSection:qle,vResizer:Gle,snapLine:Kle,snapLineActive:Xle,snapPreview:Yle,chatInputBar:Zle,chatInputWrapper:Qle,chatTextareaWrap:Jle,chatTextarea:ece,chatInputHint:tce,chatSendBtn:nce,messageListWrap:rce,stickyBottomBtn:ice,ptyPromptBubble:sce,ptyPromptResolved:oce,ptyPromptQuestion:ace,ptyPromptOptions:lce,ptyPromptOption:cce,ptyPromptOptionPrimary:uce,ptyPromptOptionChosen:dce,ptyPromptOptionDimmed:hce,ghostText:fce,suggestionChip:pce,suggestionChipText:mce,suggestionChipAction:gce,navSidebar:vce,navBtn:_ce,navBtnActive:bce},{Text:r3}=Xs,yce=20;function Sce(){return 100+Math.random()*50}function i3(e){var i;const t={};for(const s of e)if(s.role==="assistant"&&Array.isArray(s.content))for(const o of s.content)o.type==="tool_use"&&(t[o.id]=o);const n={},r={};for(const s of e)if(s.role==="user"&&Array.isArray(s.content)){for(const o of s.content)if(o.type==="tool_result"){const l=t[o.tool_use_id];let c=he("ui.toolReturn"),u=null,h=null;if(l)if(u=l.name,h=l.input,l.name==="Task"&&l.input){const m=l.input.subagent_type||"",v=l.input.description||"";c=`SubAgent: ${m}${v?" — "+v:""}`}else c=he("ui.toolReturnNamed",{name:l.name});const p=zR(o);n[o.tool_use_id]={label:c,toolName:u,toolInput:h,resultText:p},l&&l.name==="Read"&&((i=l.input)!=null&&i.file_path)&&(r[l.input.file_path]=p)}}return{toolUseMap:t,toolResultMap:n,readContentMap:r}}class s3 extends J.Component{constructor(n){super(n);St(this,"handleStickToBottom",()=>{this.setState({stickyBottom:!0},()=>{const n=this.containerRef.current;n&&(n.scrollTop=n.scrollHeight)})});St(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(m=>m.number===n);let l=s.findIndex(m=>m.selected);l<0&&(l=0);const c=o-l,u=c>0?"\x1B[B":"\x1B[A",h=Math.abs(c),p=m=>{m<h?(r.send(JSON.stringify({type:"input",data:u})),setTimeout(()=>p(m+1),30)):setTimeout(()=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:"input",data:"\r"}))},50)};p(0),this.setState(m=>{const v=m.ptyPromptHistory.slice(),_=v[v.length-1];return _&&_.status==="active"&&(v[v.length-1]={..._,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:v}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});St(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()))});St(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())});St(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})});St(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()))});St(this,"handleSplitMouseDown",n=>{n.preventDefault(),this._resizing=!0;const i=!window.location.search.includes("token=");let s=[];if(i){const c=this.innerSplitRef.current;if(c){const h=c.getBoundingClientRect().width,p=7.8,m=[60,80,100,120],v=5;s=m.map(_=>{const b=_*p,y=b+v;if(y>h*.75||y<h*.15)return null;const w=h-b-v;return{cols:_,terminalPx:b,linePosition:w}}).filter(_=>_!==null)}}this.setState({isDragging:!0,snapLines:s});const o=c=>{if(!this._resizing)return;const u=this.innerSplitRef.current;if(!u)return;const h=u.getBoundingClientRect(),p=h.width;let m=h.right-c.clientX;m=Math.max(200,Math.min(p*.75,m));let v=null;if(i&&s.length>0){let b=1/0,y=null;for(const w of s){const x=Math.abs(c.clientX-h.left-w.linePosition);x<b&&(b=x,y=w)}y&&b<60&&(v=y)}this.setState({terminalWidth:m,activeSnapLine:v})},l=()=>{if(this._resizing=!1,i&&this.state.activeSnapLine){const c=this.state.activeSnapLine.terminalPx;localStorage.setItem("cc-viewer-terminal-width",c.toString()),this.setState({terminalWidth:c,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",l),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",o),document.addEventListener("mouseup",l),document.body.style.cursor="col-resize",document.body.style.userSelect="none"});St(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=J.createRef(),this.splitContainerRef=J.createRef(),this.innerSplitRef=J.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:!0,currentFile:null,currentGitDiff:null,fileExplorerExpandedPaths:new Set,gitChangesOpen:!1,snapLines:[],activeSnapLine:null,isDragging:!1,fileVersion:0},this._fileChangeWs=null,this._fileChangeDebounceTimer=null,this._queueTimer=null,this._prevItemsLen=0,this._scrollTargetIdx=null,this._scrollTargetRef=J.createRef(),this._scrollFadeTimer=null,this._resizing=!1,this._inputWs=null,this._inputRef=J.createRef(),this._ptyBuffer="",this._ptyDebounceTimer=null}componentDidMount(){this.startRender(),this.props.cliMode&&this.connectInputWs(),this._bindStickyScroll(),this.state.needsInitialSnap&&this.props.cliMode&&this.props.terminalVisible&&this._snapToInitialPosition(),this._setupFileChangeWatcher()}componentDidUpdate(n){if(n.mainAgentSessions!==this.props.mainAgentSessions)this.startRender(),this.state.pendingInput&&this.setState({pendingInput:null}),this._updateSuggestion();else if(n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking){const r=this.buildAllItems();this.setState({allItems:r,visibleCount:r.length})}if(!n.scrollToTimestamp&&this.props.scrollToTimestamp){const r=this.buildAllItems();this.setState({allItems:r,visibleCount:r.length},()=>this.scrollToBottom())}!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._unbindScrollFade(),this._unbindStickyScroll(),this._inputWs&&(this._inputWs.close(),this._inputWs=null),this._fileChangeWs&&(this._fileChangeWs.close(),this._fileChangeWs=null),this._fileChangeDebounceTimer&&(clearTimeout(this._fileChangeDebounceTimer),this._fileChangeDebounceTimer=null)}startRender(){this._queueTimer&&clearTimeout(this._queueTimer);const n=this.buildAllItems(),r=this._prevItemsLen;this._prevItemsLen=n.length;const i=n.length-r;if(i<=0||r>0&&i<=3){this.setState({allItems:n,visibleCount:n.length,loading:!1},()=>this.scrollToBottom());return}if(n.length>yce)this.setState({allItems:n,visibleCount:0,loading:!0}),this._queueTimer=setTimeout(()=>{this.setState({visibleCount:n.length,loading:!1},()=>this.scrollToBottom())},300);else{const s=Math.max(0,r);this.setState({allItems:n,visibleCount:s,loading:!1}),this.queueNext(s,n.length)}}queueNext(n,r){n>=r||(this._queueTimer=setTimeout(()=>{this.setState({visibleCount:n+1},()=>{this.scrollToBottom(),this.queueNext(n+1,r)})},Sce()))}_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=J.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){var _;const{userProfile:o,collapseToolResults:l,expandThinking:c,onViewRequest:u}=this.props,{toolUseMap:h,toolResultMap:p,readContentMap:m}=i3(n),v=[];for(let b=0;b<n.length;b++){const y=n[b],w=y.content,x=y._timestamp||null,E=x?s[x]:void 0,k=E!=null&&u?{requestIndex:E,onViewRequest:u}:{};if(y.role==="user"){if(Array.isArray(w)){const R=w.find(M=>M.type==="text"&&/^\[SUGGESTION MODE:/i.test((M.text||"").trim())),T=w.filter(M=>M.type==="tool_result");if(R&&T.length>0){let M=null,L={};for(const A of T){const z=h[A.tool_use_id];if(z&&z.name==="AskUserQuestion"&&((_=z.input)!=null&&_.questions)){M=z.input.questions;const H=zR(A);try{L=JSON.parse(H).answers||{}}catch{}break}}M&&v.push(S.jsx(ro,{role:"user-selection",questions:M,answers:L,timestamp:x,userProfile:o,...k},`${r}-selection-${b}`))}else{const{commands:M,textBlocks:L,skillBlocks:A}=AR(w);for(let z=0;z<M.length;z++)v.push(S.jsx(ro,{role:"user",text:M[z],timestamp:x,userProfile:o,modelInfo:i,...k},`${r}-cmd-${b}-${z}`));for(const z of A){const H=z.text.match(/^#\s+(.+)$/m),N=H?H[1]:"Skill";v.push(S.jsx(ro,{role:"skill-loaded",text:z.text,skillName:N,timestamp:x,...k},`${r}-skill-${b}`))}for(let z=0;z<L.length;z++){const H=/^Implement the following plan:/i.test((L[z].text||"").trim());v.push(S.jsx(ro,{role:H?"plan-prompt":"user",text:L[z].text,timestamp:x,userProfile:o,modelInfo:i,...k},`${r}-user-${b}-${z}`))}}}else if(typeof w=="string"&&!yy(w)){const R=/^Implement the following plan:/i.test(w.trim());v.push(S.jsx(ro,{role:R?"plan-prompt":"user",text:w,timestamp:x,userProfile:o,modelInfo:i,...k},`${r}-user-${b}`))}}else y.role==="assistant"&&(Array.isArray(w)?v.push(S.jsx(ro,{role:"assistant",content:w,toolResultMap:p,readContentMap:m,timestamp:x,modelInfo:i,collapseToolResults:l,expandThinking:c,...k},`${r}-asst-${b}`)):typeof w=="string"&&v.push(S.jsx(ro,{role:"assistant",content:[{type:"text",text:w}],toolResultMap:p,readContentMap:m,timestamp:x,modelInfo:i,collapseToolResults:l,expandThinking:c,...k},`${r}-asst-${b}`)))}return v}buildAllItems(){var b,y,w,x;const{mainAgentSessions:n,requests:r,collapseToolResults:i,expandThinking:s,onViewRequest:o}=this.props;if(!n||n.length===0)return[];const l={};if(r)for(let E=0;E<r.length;E++)yi(r[E])&&r[E].timestamp&&(l[r[E].timestamp]=E);let c=null;if(r){for(let E=r.length-1;E>=0;E--)if(yi(r[E])&&((b=r[E].body)!=null&&b.model)){c=r[E].body.model;break}}const u=$K(c),h=[],p={},m=[];if(r)for(let E=0;E<r.length;E++){const k=r[E];if(!k.timestamp)continue;const R=jl(k,r[E+1]);if(R.type==="SubAgent"){const T=(w=(y=k.response)==null?void 0:y.body)==null?void 0:w.content;if(Array.isArray(T)&&T.length>0){const M=i3(((x=k.body)==null?void 0:x.messages)||[]).toolResultMap;m.push({timestamp:k.timestamp,content:T,toolResultMap:M,label:Yp(R.type,R.subType),requestIndex:E})}}}let v=0;n.forEach((E,k)=>{var T,M,L,A;k>0&&h.push(S.jsx(G2,{style:{borderColor:"#333",margin:"16px 0"},children:S.jsx(r3,{className:mn.sessionDividerText,children:"Session"})},`session-div-${k}`));const R=this.renderSessionMessages(E.messages,`s${k}`,u,l);for(const z of R){const H=z.props.timestamp;for(;v<m.length&&H&&m[v].timestamp<=H;){const N=m[v];N.timestamp&&(p[N.timestamp]=h.length),h.push(S.jsx(ro,{role:"sub-agent-chat",content:N.content,toolResultMap:N.toolResultMap,label:N.label,timestamp:N.timestamp,collapseToolResults:i,expandThinking:s,requestIndex:N.requestIndex,onViewRequest:o},`sub-chat-${v}`)),v++}H&&(p[H]=h.length),h.push(z)}for(;v<m.length;){const z=m[v],H=k<n.length-1&&((M=(T=n[k+1].messages)==null?void 0:T[0])==null?void 0:M._timestamp);if(H&&z.timestamp>H)break;z.timestamp&&(p[z.timestamp]=h.length),h.push(S.jsx(ro,{role:"sub-agent-chat",content:z.content,toolResultMap:z.toolResultMap,label:z.label,timestamp:z.timestamp,collapseToolResults:i,expandThinking:s,requestIndex:z.requestIndex,onViewRequest:o},`sub-chat-${v}`)),v++}if(k===n.length-1&&((A=(L=E.response)==null?void 0:L.body)!=null&&A.content)){const z=E.response.body.content;Array.isArray(z)&&(h.push(S.jsx(J.Fragment,{children:S.jsx(G2,{style:{borderColor:"#2a2a2a",margin:"8px 0"},children:S.jsx(r3,{type:"secondary",className:mn.lastResponseLabel,children:he("ui.lastResponse")})})},"resp-divider")),E.entryTimestamp&&(p[E.entryTimestamp]=h.length),h.push(S.jsx(ro,{role:"assistant",content:z,timestamp:E.entryTimestamp,modelInfo:u,collapseToolResults:i,expandThinking:s,toolResultMap:{}},"resp-asst")))}});const{scrollToTimestamp:_}=this.props;return this._scrollTargetIdx=_&&p[_]!=null?p[_]:null,this._tsItemMap=p,h}_extractSuggestion(){var c;const{mainAgentSessions:n}=this.props;if(!(n!=null&&n.length))return null;const r=n[n.length-1],i=r==null?void 0:r.response;if(!i)return null;const s=i.body;if(!s)return null;const o=s.stop_reason;if(o!=="end_turn"&&o!=="max_tokens")return null;const l=s.content;if(!Array.isArray(l))return null;for(let u=l.length-1;u>=0;u--)if(l[u].type==="text"&&((c=l[u].text)!=null&&c.trim()))return l[u].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 l=o.map(h=>{const p=h.match(/\s*([❯>])?\s*(\d+)\.\s+(.+)/);return{number:parseInt(p[2],10),text:p[3].trim(),selected:!!p[1]}}),c=this.state.ptyPrompt,u={question:i,options:l};c&&c.question===i?this.setState({ptyPrompt:u}):(this.setState(h=>{const p=h.ptyPromptHistory.slice();if(h.ptyPrompt){const m=p[p.length-1];m&&m.status==="active"&&(p[p.length-1]={...m,status:"dismissed"})}return p.push({...u,status:"active",selectedNumber:null,timestamp:new Date().toISOString()}),{ptyPrompt:u,ptyPromptHistory:p}}),this.scrollToBottom());return}}this.state.ptyPrompt&&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})}_snapToInitialPosition(){this.setState({terminalWidth:468,needsInitialSnap:!1}),localStorage.setItem("cc-viewer-terminal-width","468")}_setupFileChangeWatcher(){try{const r=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal`;this._fileChangeWs=new WebSocket(r),this._fileChangeWs.onmessage=i=>{try{const s=JSON.parse(i.data);if(s.type==="file-change"){const{currentFile:o}=this.state;if(!o)return;const l=h=>h?h.split("/").pop():"",c=l(s.path),u=l(o);c===u&&c&&(this._fileChangeDebounceTimer&&clearTimeout(this._fileChangeDebounceTimer),this._fileChangeDebounceTimer=setTimeout(()=>{s.eventType==="unlink"?this.setState({currentFile:null,fileVersion:0}):(s.eventType==="change"||s.eventType==="add")&&this.setState(h=>({fileVersion:h.fileVersion+1}))},300))}}catch{}},this._fileChangeWs.onerror=()=>{},this._fileChangeWs.onclose=()=>{setTimeout(()=>{this._fileChangeWs!==null&&this._setupFileChangeWatcher()},2e3)}}catch{}}render(){const{mainAgentSessions:n,cliMode:r,terminalVisible:i}=this.props,{allItems:s,visibleCount:o,loading:l,terminalWidth:c}=this.state,u=!n||n.length===0;if(u&&!r)return S.jsx("div",{className:mn.centerEmpty,children:S.jsx(Vi,{description:he("ui.noChat")})});if(l&&!r)return S.jsx("div",{className:mn.centerEmpty,children:S.jsx(ua,{size:"large"})});const h=this._scrollTargetIdx,{highlightTs:p,highlightFading:m}=this.state,v=p&&this._tsItemMap&&this._tsItemMap[p]!=null?this._tsItemMap[p]:null,_=s.slice(0,o),{pendingInput:b,stickyBottom:y,ptyPromptHistory:w}=this.state,x=r&&b?S.jsx(ro,{role:"user",text:b,timestamp:new Date().toISOString(),userProfile:this.props.userProfile},"pending-input"):null,E=y?null:S.jsxs("button",{className:mn.stickyBottomBtn,onClick:this.handleStickToBottom,children:[S.jsx("span",{children:he("ui.stickyBottom")}),S.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:S.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),k=r&&w.length>0?w.map((T,M)=>{const L=T.status==="active",A=T.status==="answered";return S.jsxs("div",{className:`${mn.ptyPromptBubble}${L?"":" "+mn.ptyPromptResolved}`,children:[S.jsx("div",{className:mn.ptyPromptQuestion,children:T.question}),S.jsx("div",{className:mn.ptyPromptOptions,children:T.options.map(z=>{const H=A&&T.selectedNumber===z.number;let N=mn.ptyPromptOption;return L&&z.selected&&(N=mn.ptyPromptOptionPrimary),H&&(N=mn.ptyPromptOptionChosen),!L&&!H&&(N=mn.ptyPromptOptionDimmed),S.jsxs("button",{className:N,disabled:!L,onClick:L?()=>this.handlePromptOptionClick(z.number):void 0,children:[z.number,". ",z.text]},z.number)})})]},`pty-prompt-${M}`)}):null,R=u||l?S.jsxs("div",{className:mn.messageListWrap,children:[S.jsxs("div",{ref:this.containerRef,className:mn.container,children:[!r||l?S.jsx("div",{className:mn.centerEmpty,children:l?S.jsx(ua,{size:"large"}):S.jsx(Vi,{description:he("ui.noChat")})}):null,x,k]}),E]}):S.jsxs("div",{className:mn.messageListWrap,children:[S.jsxs("div",{ref:this.containerRef,className:mn.container,children:[_.map((T,M)=>{const L=M===h,A=M===v;let z=T;return A&&(z=J.cloneElement(z,{highlight:m?"fading":"active"})),L?S.jsx("div",{ref:this._scrollTargetRef,children:z},T.key+"-anchor"):z}),x,k]}),E]});return r?S.jsxs("div",{ref:this.splitContainerRef,className:mn.splitContainer,children:[S.jsxs("div",{className:mn.navSidebar,children:[S.jsx("button",{className:this.state.fileExplorerOpen?mn.navBtnActive:mn.navBtn,onClick:()=>this.setState({fileExplorerOpen:!0,gitChangesOpen:!1,currentFile:null}),title:he("ui.fileExplorer"),children:S.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:S.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"})})}),S.jsx("button",{className:this.state.gitChangesOpen?mn.navBtnActive:mn.navBtn,onClick:()=>this.setState({gitChangesOpen:!0,fileExplorerOpen:!1,currentFile:null}),title:he("ui.gitChanges"),children:S.jsx("svg",{width:"24",height:"24",viewBox:"0 0 1024 1024",fill:"currentColor",children:S.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"})})})]}),S.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 A=T.getBoundingClientRect().width-this.state.terminalWidth-5,z=this.state.activeSnapLine.linePosition,H=Math.min(A,z),N=Math.abs(z-A);return S.jsx("div",{className:mn.snapPreview,style:{left:`${H}px`,width:`${N}px`}})})(),this.state.isDragging&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const A=T.getBoundingClientRect().width-this.state.terminalWidth-5,z=[...this.state.snapLines].map(O=>({...O,dist:Math.abs(O.linePosition-A)})).sort((O,I)=>O.dist-I.dist);if(z.length===0)return null;const H=z[0],N=this.state.activeSnapLine&&this.state.activeSnapLine.cols===H.cols;return S.jsx("div",{className:N?mn.snapLineActive:mn.snapLine,style:{left:`${H.linePosition}px`}},H.cols)})(),this.state.fileExplorerOpen&&S.jsx(Loe,{onClose:()=>this.setState({fileExplorerOpen:!1}),onFileClick:T=>this.setState({currentFile:T,currentGitDiff:null}),expandedPaths:this.state.fileExplorerExpandedPaths,onToggleExpand:this.handleToggleExpandPath,currentFile:this.state.currentFile}),this.state.gitChangesOpen&&S.jsx(nle,{onClose:()=>this.setState({gitChangesOpen:!1}),onFileClick:T=>this.setState({currentGitDiff:T,currentFile:null})}),S.jsx("div",{className:mn.chatSection,style:{flex:1,minWidth:0,display:"flex"},children:S.jsxs("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[this.state.currentGitDiff?S.jsx(Dle,{filePath:this.state.currentGitDiff,onClose:()=>this.setState({currentGitDiff:null})}):this.state.currentFile?S.jsx(Lae,{filePath:this.state.currentFile,onClose:()=>this.setState({currentFile:null,fileVersion:0})},this.state.fileVersion):R,!i&&S.jsxs("div",{className:mn.chatInputBar,children:[S.jsxs("div",{className:mn.chatInputWrapper,children:[S.jsxs("div",{className:mn.chatTextareaWrap,children:[S.jsx("textarea",{ref:this._inputRef,className:mn.chatTextarea,placeholder:this.state.inputSuggestion?"":he("ui.chatInput.placeholder"),rows:1,onKeyDown:this.handleInputKeyDown,onInput:this.handleInputChange}),this.state.inputSuggestion&&this.state.inputEmpty&&S.jsx("div",{className:mn.ghostText,children:this.state.inputSuggestion})]}),S.jsx("div",{className:mn.chatInputHint,children:this.state.inputSuggestion&&this.state.inputEmpty?he("ui.chatInput.hintTab"):he("ui.chatInput.hintEnter")})]}),S.jsx("button",{className:mn.chatSendBtn,onClick:this.handleInputSend,disabled:this.state.inputEmpty,title:he("ui.chatInput.send"),children:S.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[S.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),S.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),i&&this.state.inputSuggestion&&S.jsxs("div",{className:mn.suggestionChip,onClick:this.handleSuggestionToTerminal,children:[S.jsx("span",{className:mn.suggestionChipText,children:this.state.inputSuggestion}),S.jsx("span",{className:mn.suggestionChipAction,children:"↵"})]})]})}),i&&S.jsxs(S.Fragment,{children:[S.jsx("div",{className:mn.vResizer,onMouseDown:this.handleSplitMouseDown}),S.jsx("div",{style:{width:c,flexShrink:0,minWidth:200,display:"flex",flexDirection:"column"},children:S.jsx(bT,{})})]})]})]}):R}}const Cce="_resizer_yamj2_1",wce={resizer:Cce};class xce extends J.Component{constructor(t){super(t),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this)}handleMouseDown(t){t.preventDefault(),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}handleMouseMove(t){this.props.onResize&&this.props.onResize(t.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 S.jsx("div",{onMouseDown:this.handleMouseDown,className:wce.resizer})}}const Ece="_container_1um1r_1",kce="_fileListSection_1um1r_10",$ce="_header_1um1r_19",Rce="_headerTitle_1um1r_28",Tce="_fileCount_1um1r_36",Nce="_changesContainer_1um1r_44",Mce="_changeItem_1um1r_51",Oce="_changeItemActive_1um1r_68",Ice="_dirItem_1um1r_77",Pce="_dirArrow_1um1r_88",Lce="_dirName_1um1r_97",Ace="_status_1um1r_102",Bce="_icon_1um1r_111",zce="_fileName_1um1r_120",jce="_diffSection_1um1r_127",Dce="_diffHeader_1um1r_135",Fce="_diffFilePath_1um1r_145",Hce="_diffBadge_1um1r_155",Wce="_diffContent_1um1r_167",Vce="_diffPlaceholder_1um1r_173",Uce="_statusText_1um1r_184",qce="_errorText_1um1r_191",Gce="_emptyText_1um1r_198",Kce="_warningText_1um1r_205",Jn={container:Ece,fileListSection:kce,header:$ce,headerTitle:Rce,fileCount:Tce,changesContainer:Nce,changeItem:Mce,changeItemActive:Oce,dirItem:Ice,dirArrow:Pce,dirName:Lce,status:Ace,icon:Bce,fileName:zce,diffSection:jce,diffHeader:Dce,diffFilePath:Fce,diffBadge:Hce,diffContent:Wce,diffPlaceholder:Vce,statusText:Uce,errorText:qce,emptyText:Gce,warningText:Kce},Xce={M:"#e2c08d",A:"#73c991",D:"#f14c4c",R:"#73c991",C:"#73c991",U:"#e2c08d","?":"#73c991"},Yce={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 Zce(e){const t=e.includes(".")?e.split(".").pop().toLowerCase():"",n=Yce[t]||"#888";return S.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",children:[S.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),S.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function Qce(){return S.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"#c09553",stroke:"none",children:S.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 Jce(e){const t={dirs:{},files:[]};for(const n of e){const r=n.file.split("/");let i=t;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 t}function i8({name:e,node:t,depth:n,selectedFile:r,onFileClick:i}){const s=Object.keys(t.dirs).sort(),o=[...t.files].sort((l,c)=>l.name.localeCompare(c.name));return S.jsxs(S.Fragment,{children:[e&&S.jsxs("div",{className:Jn.dirItem,style:{paddingLeft:8+n*16},children:[S.jsx("span",{className:Jn.dirArrow,children:S.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:S.jsx("polyline",{points:"9 6 15 12 9 18"})})}),S.jsx("span",{className:Jn.icon,children:Qce()}),S.jsx("span",{className:Jn.dirName,children:e})]}),s.map(l=>S.jsx(i8,{name:l,node:t.dirs[l],depth:e?n+1:n,selectedFile:r,onFileClick:i},l)),o.map(l=>S.jsxs("div",{className:`${Jn.changeItem} ${r===l.fullPath?Jn.changeItemActive:""}`,style:{paddingLeft:8+(e?n+1:n)*16},onClick:()=>i&&i(l.fullPath),children:[S.jsx("span",{className:Jn.icon,children:Zce(l.name)}),S.jsx("span",{className:Jn.fileName,children:l.name}),S.jsx("span",{className:Jn.status,style:{color:Xce[l.status]||"#888"},children:l.status})]},l.fullPath))]})}function eue(){const[e,t]=f.useState(null),[n,r]=f.useState(null),[i,s]=f.useState(!0),[o,l]=f.useState(null),[c,u]=f.useState(null),[h,p]=f.useState(null),[m,v]=f.useState(!1),_=f.useRef(!0);return f.useEffect(()=>(_.current=!0,s(!0),fetch(kn("/api/git-status")).then(b=>b.ok?b.json():Promise.reject()).then(b=>{_.current&&(t(b.changes||[]),s(!1))}).catch(()=>{_.current&&(r("Failed to load git status"),s(!1))}),()=>{_.current=!1}),[]),f.useEffect(()=>{if(!o){u(null),p(null);return}v(!0),u(null),p(null),fetch(kn(`/api/git-diff?files=${encodeURIComponent(o)}`)).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}`);return b.json()}).then(b=>{_.current&&(b.diffs&&b.diffs[0]?u(b.diffs[0]):p("No diff data available"),v(!1))}).catch(b=>{_.current&&(p(`${he("ui.fileLoadError")}: ${b.message}`),v(!1))})},[o]),S.jsxs("div",{className:Jn.container,children:[S.jsxs("div",{className:Jn.fileListSection,children:[S.jsxs("div",{className:Jn.header,children:[S.jsx("span",{className:Jn.headerTitle,children:he("ui.gitChanges")}),S.jsx("span",{className:Jn.fileCount,children:e?e.length:0})]}),S.jsxs("div",{className:Jn.changesContainer,children:[i&&S.jsx("div",{className:Jn.statusText,children:"Loading..."}),n&&S.jsx("div",{className:Jn.errorText,children:n}),!i&&!n&&e&&e.length===0&&S.jsx("div",{className:Jn.emptyText,children:"No changes"}),!i&&!n&&e&&e.length>0&&S.jsx(i8,{name:"",node:Jce(e),depth:0,selectedFile:o,onFileClick:l})]})]}),S.jsx("div",{className:Jn.diffSection,children:o?S.jsxs(S.Fragment,{children:[S.jsxs("div",{className:Jn.diffHeader,children:[S.jsx("span",{className:Jn.diffFilePath,children:o}),S.jsx("span",{className:Jn.diffBadge,children:"DIFF"})]}),S.jsxs("div",{className:Jn.diffContent,children:[m&&S.jsx("div",{className:Jn.statusText,children:he("ui.loading")}),h&&S.jsx("div",{className:Jn.errorText,children:h}),!m&&!h&&c&&S.jsx(S.Fragment,{children:c.is_large?S.jsxs("div",{className:Jn.warningText,children:[S.jsx("p",{children:he("ui.largeFileWarning")}),S.jsxs("p",{style:{color:"#888",fontSize:12},children:[he("ui.fileSize"),": ",(c.size/(1024*1024)).toFixed(2)," MB"]})]}):c.is_binary?S.jsx("div",{className:Jn.statusText,style:{fontStyle:"italic"},children:he("ui.binaryFileNotice")}):S.jsx(r8,{file_path:o,old_string:c.old_content,new_string:c.new_content})})]})]}):S.jsxs("div",{className:Jn.diffPlaceholder,children:[S.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"#333",strokeWidth:"1.5",children:[S.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),S.jsx("circle",{cx:"18",cy:"6",r:"3"}),S.jsx("circle",{cx:"6",cy:"18",r:"3"}),S.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),S.jsx("span",{children:he("ui.mobileGitDiffHint")})]})})]})}const{Text:kl,Title:tue}=Xs;function nue(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=0,r=e;for(;r>=1024&&n<t.length-1;)r/=1024,n++;return`${r.toFixed(n>0?1:0)} ${t[n]}`}function rue(e){if(!e)return"";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return he("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 iue({open:e,onClose:t,onSelect:n}){const[r,i]=f.useState(""),[s,o]=f.useState(null),[l,c]=f.useState([]),[u,h]=f.useState(!1),[p,m]=f.useState(""),v=f.useCallback(b=>{h(!0);const y=b?`/api/browse-dir?path=${encodeURIComponent(b)}`:"/api/browse-dir";fetch(kn(y)).then(w=>w.json()).then(w=>{w.error?dr.error(w.error):(i(w.current),o(w.parent),c(w.dirs||[]),m(w.current)),h(!1)}).catch(()=>{dr.error("Failed to browse directory"),h(!1)})},[]);f.useEffect(()=>{e&&v("")},[e,v]);const _=()=>{const b=p.trim();b&&v(b)};return S.jsxs(Ci,{title:he("ui.workspaces.selectDir"),open:e,onCancel:t,footer:null,width:600,styles:{body:{padding:"12px 0"}},children:[S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"0 16px 10px",borderBottom:"1px solid #2a2a2a"},children:[S.jsx(Cn,{type:"text",icon:S.jsx(DG,{}),disabled:!s,onClick:()=>s&&v(s),size:"small"}),S.jsxs(kl,{style:{color:"#e0e0e0",fontSize:13,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[S.jsx(m1,{style:{marginRight:6,color:"#1668dc"}}),r]})]}),S.jsx("div",{style:{maxHeight:400,overflowY:"auto",padding:"4px 0"},children:u?S.jsx("div",{style:{textAlign:"center",padding:40},children:S.jsx(ua,{})}):l.length===0?S.jsx("div",{style:{textAlign:"center",padding:40},children:S.jsx(kl,{type:"secondary",children:he("ui.workspaces.emptyDir")})}):l.map(b=>S.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 16px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:y=>y.currentTarget.style.background="#1a1a1a",onMouseLeave:y=>y.currentTarget.style.background="transparent",children:[S.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:8,minWidth:0},onClick:()=>v(b.path),children:[S.jsx($q,{style:{color:b.hasGit?"#1668dc":"#666",fontSize:16,flexShrink:0}}),S.jsx(kl,{style:{color:"#d0d0d0",fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.name}),b.hasGit&&S.jsxs(ls,{color:"blue",style:{fontSize:11,lineHeight:"18px",padding:"0 4px",margin:0,flexShrink:0},children:[S.jsx(CR,{style:{marginRight:2}}),"git"]})]}),S.jsx(Cn,{type:"primary",size:"small",onClick:y=>{y.stopPropagation(),n(b.path)},children:he("ui.workspaces.select")})]},b.path))}),S.jsxs("div",{style:{borderTop:"1px solid #2a2a2a",padding:"10px 16px 4px",display:"flex",flexDirection:"column",gap:8},children:[S.jsxs(Cn,{type:"primary",ghost:!0,block:!0,icon:S.jsx(m1,{}),onClick:()=>n(r),children:[he("ui.workspaces.selectCurrent")," — ",r.split("/").pop()||r]}),S.jsxs("div",{style:{display:"flex",gap:8},children:[S.jsx(Gl,{size:"small",value:p,onChange:b=>m(b.target.value),onPressEnter:_,placeholder:he("ui.workspaces.pathPlaceholder"),style:{flex:1}}),S.jsx(Cn,{size:"small",onClick:_,children:he("ui.workspaces.goTo")})]})]})]})}function sue({onLaunch:e}){const[t,n]=f.useState([]),[r,i]=f.useState(!0),[s,o]=f.useState(null),[l,c]=f.useState(!1),u=()=>{fetch(kn("/api/workspaces")).then(v=>v.json()).then(v=>{n(v.workspaces||[]),i(!1)}).catch(()=>i(!1))};f.useEffect(()=>{u()},[]);const h=v=>{c(!1),fetch(kn("/api/workspaces/add"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:v})}).then(_=>_.json()).then(_=>{_.error?dr.error(_.error):u()}).catch(()=>dr.error("Failed to add workspace"))},p=v=>{fetch(kn(`/api/workspaces/${v}`),{method:"DELETE"}).then(_=>_.json()).then(()=>u()).catch(()=>{})},m=v=>{o(v.id),fetch(kn("/api/workspaces/launch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:v.path})}).then(_=>_.json()).then(_=>{_.error?(dr.error(_.error),o(null)):e({projectName:_.projectName,path:v.path})}).catch(()=>{dr.error("Launch failed"),o(null)})};return S.jsxs("div",{style:{minHeight:"100vh",background:"#0a0a0a",display:"flex",justifyContent:"center",paddingTop:60},children:[S.jsxs("div",{style:{width:"100%",maxWidth:720,padding:"0 24px"},children:[S.jsxs("div",{style:{marginBottom:32,textAlign:"center"},children:[S.jsxs(tue,{level:3,style:{color:"#e0e0e0",margin:0},children:[S.jsx(m1,{style:{marginRight:8,color:"#1668dc"}}),he("ui.workspaces.title")]}),S.jsx(kl,{type:"secondary",style:{fontSize:13},children:he("ui.workspaces.subtitle")})]}),S.jsx("div",{style:{marginBottom:20,textAlign:"center"},children:S.jsx(Cn,{type:"primary",icon:S.jsx(Hp,{}),onClick:()=>c(!0),size:"large",children:he("ui.workspaces.browse")})}),r?S.jsx("div",{style:{textAlign:"center",padding:60},children:S.jsx(ua,{})}):t.length===0?S.jsx(Vi,{description:S.jsx(kl,{type:"secondary",children:he("ui.workspaces.empty")}),style:{marginTop:60}}):S.jsx(hu,{dataSource:t,renderItem:v=>S.jsx(fy,{size:"small",style:{marginBottom:10,background:"#141414",borderColor:"#2a2a2a",cursor:"pointer"},hoverable:!0,onClick:()=>m(v),children:S.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[S.jsxs("div",{style:{flex:1,minWidth:0},children:[S.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:S.jsx(kl,{strong:!0,style:{color:"#e0e0e0",fontSize:15},children:v.projectName})}),S.jsx(kl,{type:"secondary",style:{fontSize:12,wordBreak:"break-all"},children:v.path}),S.jsxs("div",{style:{display:"flex",gap:16,marginTop:6,fontSize:12,color:"#666"},children:[S.jsxs("span",{children:[S.jsx(GW,{style:{marginRight:4}}),rue(v.lastUsed)]}),v.logCount>0&&S.jsxs("span",{children:[S.jsx(QG,{style:{marginRight:4}}),v.logCount," logs (",nue(v.totalSize),")"]})]})]}),S.jsxs(To,{children:[S.jsx(Cn,{type:"primary",icon:S.jsx(dK,{}),loading:s===v.id,onClick:_=>{_.stopPropagation(),m(v)},children:he("ui.workspaces.open")}),S.jsx(gR,{title:he("ui.workspaces.confirmRemove"),onConfirm:_=>{_==null||_.stopPropagation(),p(v.id)},onCancel:_=>_==null?void 0:_.stopPropagation(),okText:"Yes",cancelText:"No",children:S.jsx(Cn,{type:"text",danger:!0,icon:S.jsx(bR,{}),onClick:_=>_.stopPropagation()})})]})]})},v.id)})]}),S.jsx(iue,{open:l,onClose:()=>c(!1),onSelect:h})]})}const oue="_layout_1iry8_1",aue="_header_1iry8_6",lue="_content_1iry8_14",cue="_mainContainer_1iry8_19",uue="_leftPanel_1iry8_24",due="_leftPanelHeader_1iry8_32",hue="_leftPanelCount_1iry8_43",fue="_leftPanelBody_1iry8_49",pue="_rightPanel_1iry8_54",mue="_modalActions_1iry8_60",gue="_spinCenter_1iry8_64",vue="_emptyCenter_1iry8_69",_ue="_logCheckbox_1iry8_75",bue="_logListContainer_1iry8_79",yue="_logListItem_1iry8_85",Sue="_logItemRow_1iry8_91",Cue="_logFileName_1iry8_108",wue="_logFileIcon_1iry8_121",xue="_loadingOverlay_1iry8_127",Eue="_loadingText_1iry8_140",kue="_footer_1iry8_146",$ue="_footerRight_1iry8_156",Rue="_footerText_1iry8_164",Tue="_footerLink_1iry8_169",Nue="_footerIcon_1iry8_181",Mue="_footerDivider_1iry8_186",Oue="_guideContainer_1iry8_194",Iue="_guideContent_1iry8_202",Pue="_guideTitle_1iry8_207",Lue="_guideStep_1iry8_214",Aue="_guideStepNum_1iry8_220",Bue="_guideStepBody_1iry8_235",zue="_guideText_1iry8_240",jue="_guideCode_1iry8_247",Due="_mobileChatOverlay_1iry8_260",Fue="_mobileChatOverlayVisible_1iry8_272",Hue="_mobileChatInner_1iry8_276",Wue="_mobileGitDiffOverlay_1iry8_284",Vue="_mobileGitDiffOverlayVisible_1iry8_296",Uue="_mobileGitDiffInner_1iry8_300",Xt={layout:oue,header:aue,content:lue,mainContainer:cue,leftPanel:uue,leftPanelHeader:due,leftPanelCount:hue,leftPanelBody:fue,rightPanel:pue,modalActions:mue,spinCenter:gue,emptyCenter:vue,logCheckbox:_ue,logListContainer:bue,logListItem:yue,logItemRow:Sue,logFileName:Cue,logFileIcon:wue,loadingOverlay:xue,loadingText:Eue,footer:kue,footerRight:$ue,footerText:Rue,footerLink:Tue,footerIcon:Nue,footerDivider:Mue,guideContainer:Oue,guideContent:Iue,guideTitle:Pue,guideStep:Lue,guideStepNum:Aue,guideStepBody:Bue,guideText:zue,guideCode:jue,mobileChatOverlay:Due,mobileChatOverlayVisible:Fue,mobileChatInner:Hue,mobileGitDiffOverlay:Wue,mobileGitDiffOverlayVisible:Vue,mobileGitDiffInner:Uue};class que extends J.Component{constructor(n){super(n);St(this,"handleSelectRequest",n=>{this.setState({selectedIndex:n,scrollCenter:!1})});St(this,"handleViewRequest",n=>{this.setState({viewMode:"raw",selectedIndex:n,scrollCenter:!0})});St(this,"handleViewInChat",()=>{this.setState(n=>{const i=(n.showAll?n.requests:Qo(n.requests))[n.selectedIndex];if(!i)return null;let s=null;if(yi(i)&&i.timestamp)s=i.timestamp;else{if(jl(i).type==="SubAgent"&&i.timestamp)s=i.timestamp;else{const l=n.requests.indexOf(i);l>=0&&(s=SE(n.requests,l))}s||dr.info(he("ui.cannotMap"))}return{viewMode:"chat",chatScrollToTs:s}})});St(this,"handleWorkspaceLaunch",({projectName:n,path:r})=>{this.setState({workspaceMode:!1,projectName:n,viewMode:"chat",cliMode:!0})});St(this,"handleReturnToWorkspaces",()=>{fetch(kn("/api/workspaces/stop"),{method:"POST"}).then(()=>{this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null})}).catch(()=>{})});St(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:Qo(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:Qo(n.requests),s=n.selectedIndex!=null?i[n.selectedIndex]:null;if(s){let o=null;if(yi(s)&&s.timestamp)o=s.timestamp;else if(jl(s).type==="SubAgent"&&s.timestamp)o=s.timestamp;else{const c=n.requests.indexOf(s);c>=0&&(o=SE(n.requests,c)),o||dr.info(he("ui.cannotMap"))}return{viewMode:r,chatScrollToTs:o}}return{viewMode:r,chatScrollToTs:null}})});St(this,"handleLangChange",()=>{const n=Yd();this.setState({lang:n}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:n})}).catch(()=>{})});St(this,"handleCollapseToolResultsChange",n=>{this.setState({collapseToolResults:n}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({collapseToolResults:n})}).catch(()=>{})});St(this,"handleExpandThinkingChange",n=>{this.setState({expandThinking:n}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandThinking:n})}).catch(()=>{})});St(this,"handleExpandDiffChange",n=>{this.setState({expandDiff:n}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandDiff:n})}).catch(()=>{})});St(this,"handleFilterIrrelevantChange",n=>{this.setState(r=>{const i=!n,s=i?r.requests:Qo(r.requests);return{showAll:i,selectedIndex:s.length>0?s.length-1:null}}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filterIrrelevant:n})}).catch(()=>{})});St(this,"handleTabChange",n=>{this.setState({currentTab:n})});St(this,"handleResize",n=>{const r=this.mainContainerRef.current;if(!r)return;const i=r.getBoundingClientRect(),s=n-i.left;s>=250&&s<=800&&this.setState({leftPanelWidth:s})});St(this,"handleImportLocalLogs",()=>{this.setState({importModalVisible:!0,localLogsLoading:!0}),fetch(kn("/api/local-logs")).then(n=>n.json()).then(n=>{const{_currentProject:r,...i}=n;this.setState({localLogs:i,currentProject:r||"",localLogsLoading:!1})}).catch(()=>{this.setState({localLogs:{},localLogsLoading:!1})})});St(this,"handleCloseImportModal",()=>{this.setState({importModalVisible:!1,selectedLogs:new Set})});St(this,"handleToggleLogSelect",(n,r)=>{this.setState(i=>{const s=new Set(i.selectedLogs);return r?s.add(n):s.delete(n),{selectedLogs:s}})});St(this,"handleMergeLogs",()=>{const{selectedLogs:n,localLogs:r,currentProject:i}=this.state;if(n.size<2)return;const s=r[i];if(!s)return;const o=[];if(s.forEach((u,h)=>{n.has(u.file)&&o.push(h)}),o.sort((u,h)=>u-h),n.has(s[0].file)){dr.warning(he("ui.mergeLatestNotAllowed"));return}for(let u=1;u<o.length;u++)if(o[u]-o[u-1]!==1){dr.warning(he("ui.mergeNotConsecutive"));return}if(o.reduce((u,h)=>u+s[h].size,0)>500*1024*1024){dr.warning(he("ui.mergeTooLarge"));return}const c=o.map(u=>s[u].file).reverse();fetch(kn("/api/merge-logs"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:c})}).then(u=>u.json()).then(u=>{u.ok?(dr.success(he("ui.mergeSuccess")),this.setState({selectedLogs:new Set}),this.handleImportLocalLogs()):dr.error(u.error||"Merge failed")}).catch(()=>dr.error("Merge failed"))});St(this,"handleOpenLogFile",n=>{const r=window.location.port||window.location.host.split(":")[1]||"7008";window.open(`${window.location.protocol}//${window.location.hostname}:${r}?logfile=${encodeURIComponent(n)}`,"_blank"),this.setState({importModalVisible:!1})});St(this,"handleResumeChoice",n=>{fetch(kn("/api/resume-choice"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({choice:n})}).catch(r=>console.error("resume-choice failed:",r))});St(this,"handleLoadLocalJsonlFile",()=>{const n=document.createElement("input");n.type="file",n.accept=".jsonl",n.onchange=r=>{const i=r.target.files[0];if(!i)return;if(i.size>500*1024*1024){dr.error(he("ui.fileTooLarge"));return}this.setState({fileLoading:!0,fileLoadingCount:0});const s=new FileReader;s.onload=o=>{try{const c=o.target.result.split(`
|
|
716
|
+
`)}catch{return u}return u},[c,h,u]),m=o?u.length:Array.from(l.values()).filter(b=>b.type==="add").length,v=Array.from(l.values()).filter(b=>b.type==="modify").length,_=s?u.length:0;return S.jsxs("div",{className:_r.fullFileDiffView,children:[S.jsxs("div",{className:_r.diffSummary,children:[m>0&&S.jsxs("span",{className:_r.addedBadge,children:["+",m]}),v>0&&S.jsxs("span",{className:_r.modifiedBadge,children:["~",v]}),_>0&&S.jsxs("span",{className:_r.deletedBadge,children:["-",_]})]}),S.jsxs("div",{className:_r.codeContainer,children:[S.jsx("div",{className:_r.lineNumberCol,ref:r,children:p.map((b,y)=>{const w=y+1,x=l.get(w);let E=_r.lineNumNormal;return s?E=_r.lineNumDelete:o?E=_r.lineNumAdd:x&&(E=x.type==="add"?_r.lineNumAdd:_r.lineNumModify),S.jsx("div",{className:E,children:w},y)})}),S.jsx("div",{className:_r.codeCol,ref:i,children:S.jsx("div",{className:_r.codeInner,children:p.map((b,y)=>{const w=y+1,x=l.get(w);let E;return s?E=_r.lineDelete:o?E=_r.lineAdd:x?E=x.type==="add"?_r.lineAdd:_r.lineModify:E=_r.lineNormal,S.jsxs("div",{className:`${_r.codeLine} ${E}`,children:[S.jsx("span",{className:_r.lineContent,dangerouslySetInnerHTML:{__html:b||" "}}),x&&x.oldContent!==null&&S.jsxs("div",{className:_r.oldContentTooltip,children:[S.jsx("div",{className:_r.tooltipLabel,children:"原内容:"}),S.jsx("div",{className:_r.tooltipContent,children:x.oldContent})]})]},y)})})})]})]})}const Rle="_gitDiffView_14i1p_1",Tle="_header_14i1p_9",Nle="_headerLeft_14i1p_19",Mle="_backBtn_14i1p_27",Ole="_filePath_14i1p_48",Ile="_diffBadge_14i1p_57",Ple="_contentContainer_14i1p_69",Lle="_loading_14i1p_75",Ale="_error_14i1p_84",Ble="_binaryNotice_14i1p_95",zle="_largeFileWarning_14i1p_107",jle="_fileSize_14i1p_120",As={gitDiffView:Rle,header:Tle,headerLeft:Nle,backBtn:Mle,filePath:Ole,diffBadge:Ile,contentContainer:Ple,loading:Lle,error:Ale,binaryNotice:Ble,largeFileWarning:zle,fileSize:jle};function Dle({filePath:e,onClose:t}){const[n,r]=f.useState(null),[i,s]=f.useState(null),[o,l]=f.useState(!0),c=f.useRef(!0);return f.useEffect(()=>(c.current=!0,l(!0),r(null),s(null),fetch(`/api/git-diff?files=${encodeURIComponent(e)}`).then(u=>u.ok?u.json():u.json().then(h=>{throw new Error(h.error||"Failed to load diff")}).catch(()=>{throw new Error(`HTTP ${u.status}`)})).then(u=>{c.current&&(u.diffs&&u.diffs[0]?r(u.diffs[0]):s("No diff data available"),l(!1))}).catch(u=>{c.current&&(s(`${he("ui.fileLoadError")}: ${u.message}`),l(!1))}),()=>{c.current=!1}),[e]),S.jsxs("div",{className:As.gitDiffView,children:[S.jsx("div",{className:As.header,children:S.jsxs("div",{className:As.headerLeft,children:[S.jsx("button",{className:As.backBtn,onClick:t,title:he("ui.backToChat"),children:S.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:S.jsx("polyline",{points:"15 18 9 12 15 6"})})}),S.jsx("span",{className:As.filePath,children:e}),S.jsx("span",{className:As.diffBadge,children:"DIFF"})]})}),S.jsxs("div",{className:As.contentContainer,children:[o&&S.jsx("div",{className:As.loading,children:he("ui.loading")}),i&&S.jsx("div",{className:As.error,children:i}),!o&&!i&&n&&S.jsx(S.Fragment,{children:n.is_large?S.jsxs("div",{className:As.largeFileWarning,children:[S.jsx("p",{children:he("ui.largeFileWarning")}),S.jsxs("p",{className:As.fileSize,children:[he("ui.fileSize"),": ",(n.size/(1024*1024)).toFixed(2)," MB"]})]}):n.is_binary?S.jsx("div",{className:As.binaryNotice,children:he("ui.binaryFileNotice")}):S.jsx(r8,{file_path:e,old_string:n.old_content,new_string:n.new_content})})]})]})}const Fle="_centerEmpty_8tuwm_1",Hle="_container_8tuwm_8",Wle="_sessionDividerText_8tuwm_18",Vle="_lastResponseLabel_8tuwm_23",Ule="_splitContainer_8tuwm_27",qle="_chatSection_8tuwm_34",Gle="_vResizer_8tuwm_41",Kle="_snapLine_8tuwm_55",Xle="_snapLineActive_8tuwm_67",Yle="_snapPreview_8tuwm_94",Zle="_chatInputBar_8tuwm_107",Qle="_chatInputWrapper_8tuwm_117",Jle="_chatTextareaWrap_8tuwm_132",ece="_chatTextarea_8tuwm_132",tce="_chatInputHint_8tuwm_156",nce="_chatSendBtn_8tuwm_163",rce="_messageListWrap_8tuwm_192",ice="_stickyBottomBtn_8tuwm_200",sce="_ptyPromptBubble_8tuwm_233",oce="_ptyPromptResolved_8tuwm_242",ace="_ptyPromptQuestion_8tuwm_251",lce="_ptyPromptOptions_8tuwm_258",cce="_ptyPromptOption_8tuwm_258",uce="_ptyPromptOptionPrimary_8tuwm_282",dce="_ptyPromptOptionChosen_8tuwm_300",hce="_ptyPromptOptionDimmed_8tuwm_311",fce="_ghostText_8tuwm_322",pce="_suggestionChip_8tuwm_338",mce="_suggestionChipText_8tuwm_354",gce="_suggestionChipAction_8tuwm_363",vce="_navSidebar_8tuwm_369",_ce="_navBtn_8tuwm_381",bce="_navBtnActive_8tuwm_401",mn={centerEmpty:Fle,container:Hle,sessionDividerText:Wle,lastResponseLabel:Vle,splitContainer:Ule,chatSection:qle,vResizer:Gle,snapLine:Kle,snapLineActive:Xle,snapPreview:Yle,chatInputBar:Zle,chatInputWrapper:Qle,chatTextareaWrap:Jle,chatTextarea:ece,chatInputHint:tce,chatSendBtn:nce,messageListWrap:rce,stickyBottomBtn:ice,ptyPromptBubble:sce,ptyPromptResolved:oce,ptyPromptQuestion:ace,ptyPromptOptions:lce,ptyPromptOption:cce,ptyPromptOptionPrimary:uce,ptyPromptOptionChosen:dce,ptyPromptOptionDimmed:hce,ghostText:fce,suggestionChip:pce,suggestionChipText:mce,suggestionChipAction:gce,navSidebar:vce,navBtn:_ce,navBtnActive:bce},{Text:r3}=Xs,yce=20;function Sce(){return 100+Math.random()*50}function i3(e){var i;const t={};for(const s of e)if(s.role==="assistant"&&Array.isArray(s.content))for(const o of s.content)o.type==="tool_use"&&(t[o.id]=o);const n={},r={};for(const s of e)if(s.role==="user"&&Array.isArray(s.content)){for(const o of s.content)if(o.type==="tool_result"){const l=t[o.tool_use_id];let c=he("ui.toolReturn"),u=null,h=null;if(l)if(u=l.name,h=l.input,l.name==="Task"&&l.input){const m=l.input.subagent_type||"",v=l.input.description||"";c=`SubAgent: ${m}${v?" — "+v:""}`}else c=he("ui.toolReturnNamed",{name:l.name});const p=zR(o);n[o.tool_use_id]={label:c,toolName:u,toolInput:h,resultText:p},l&&l.name==="Read"&&((i=l.input)!=null&&i.file_path)&&(r[l.input.file_path]=p)}}return{toolUseMap:t,toolResultMap:n,readContentMap:r}}class s3 extends J.Component{constructor(n){super(n);St(this,"handleStickToBottom",()=>{this.setState({stickyBottom:!0},()=>{const n=this.containerRef.current;n&&(n.scrollTop=n.scrollHeight)})});St(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(m=>m.number===n);let l=s.findIndex(m=>m.selected);l<0&&(l=0);const c=o-l,u=c>0?"\x1B[B":"\x1B[A",h=Math.abs(c),p=m=>{m<h?(r.send(JSON.stringify({type:"input",data:u})),setTimeout(()=>p(m+1),30)):setTimeout(()=>{r.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:"input",data:"\r"}))},50)};p(0),this.setState(m=>{const v=m.ptyPromptHistory.slice(),_=v[v.length-1];return _&&_.status==="active"&&(v[v.length-1]={..._,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:v}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});St(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()))});St(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())});St(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})});St(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()))});St(this,"handleSplitMouseDown",n=>{n.preventDefault(),this._resizing=!0;const i=!window.location.search.includes("token=");let s=[];if(i){const c=this.innerSplitRef.current;if(c){const h=c.getBoundingClientRect().width,p=7.8,m=[60,80,100,120],v=5;s=m.map(_=>{const b=_*p,y=b+v;if(y>h*.75||y<h*.15)return null;const w=h-b-v;return{cols:_,terminalPx:b,linePosition:w}}).filter(_=>_!==null)}}this.setState({isDragging:!0,snapLines:s});const o=c=>{if(!this._resizing)return;const u=this.innerSplitRef.current;if(!u)return;const h=u.getBoundingClientRect(),p=h.width;let m=h.right-c.clientX;m=Math.max(200,Math.min(p*.75,m));let v=null;if(i&&s.length>0){let b=1/0,y=null;for(const w of s){const x=Math.abs(c.clientX-h.left-w.linePosition);x<b&&(b=x,y=w)}y&&b<60&&(v=y)}this.setState({terminalWidth:m,activeSnapLine:v})},l=()=>{if(this._resizing=!1,i&&this.state.activeSnapLine){const c=this.state.activeSnapLine.terminalPx;localStorage.setItem("cc-viewer-terminal-width",c.toString()),this.setState({terminalWidth:c,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",l),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",o),document.addEventListener("mouseup",l),document.body.style.cursor="col-resize",document.body.style.userSelect="none"});St(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=J.createRef(),this.splitContainerRef=J.createRef(),this.innerSplitRef=J.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:!0,currentFile:null,currentGitDiff:null,fileExplorerExpandedPaths:new Set,gitChangesOpen:!1,snapLines:[],activeSnapLine:null,isDragging:!1,fileVersion:0},this._fileChangeWs=null,this._fileChangeDebounceTimer=null,this._queueTimer=null,this._prevItemsLen=0,this._scrollTargetIdx=null,this._scrollTargetRef=J.createRef(),this._scrollFadeTimer=null,this._resizing=!1,this._inputWs=null,this._inputRef=J.createRef(),this._ptyBuffer="",this._ptyDebounceTimer=null}componentDidMount(){this.startRender(),this.props.cliMode&&this.connectInputWs(),this._bindStickyScroll(),this.state.needsInitialSnap&&this.props.cliMode&&this.props.terminalVisible&&this._snapToInitialPosition(),this._setupFileChangeWatcher()}componentDidUpdate(n){if(n.mainAgentSessions!==this.props.mainAgentSessions)this.startRender(),this.state.pendingInput&&this.setState({pendingInput:null}),this._updateSuggestion();else if(n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking){const r=this.buildAllItems();this.setState({allItems:r,visibleCount:r.length})}if(!n.scrollToTimestamp&&this.props.scrollToTimestamp){const r=this.buildAllItems();this.setState({allItems:r,visibleCount:r.length},()=>this.scrollToBottom())}!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._unbindScrollFade(),this._unbindStickyScroll(),this._inputWs&&(this._inputWs.close(),this._inputWs=null),this._fileChangeWs&&(this._fileChangeWs.close(),this._fileChangeWs=null),this._fileChangeDebounceTimer&&(clearTimeout(this._fileChangeDebounceTimer),this._fileChangeDebounceTimer=null)}startRender(){this._queueTimer&&clearTimeout(this._queueTimer);const n=this.buildAllItems(),r=this._prevItemsLen;this._prevItemsLen=n.length;const i=n.length-r;if(i<=0||r>0&&i<=3){this.setState({allItems:n,visibleCount:n.length,loading:!1},()=>this.scrollToBottom());return}if(n.length>yce)this.setState({allItems:n,visibleCount:0,loading:!0}),this._queueTimer=setTimeout(()=>{this.setState({visibleCount:n.length,loading:!1},()=>this.scrollToBottom())},300);else{const s=Math.max(0,r);this.setState({allItems:n,visibleCount:s,loading:!1}),this.queueNext(s,n.length)}}queueNext(n,r){n>=r||(this._queueTimer=setTimeout(()=>{this.setState({visibleCount:n+1},()=>{this.scrollToBottom(),this.queueNext(n+1,r)})},Sce()))}_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=J.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){var _;const{userProfile:o,collapseToolResults:l,expandThinking:c,onViewRequest:u}=this.props,{toolUseMap:h,toolResultMap:p,readContentMap:m}=i3(n),v=[];for(let b=0;b<n.length;b++){const y=n[b],w=y.content,x=y._timestamp||null,E=x?s[x]:void 0,k=E!=null&&u?{requestIndex:E,onViewRequest:u}:{};if(y.role==="user"){if(Array.isArray(w)){const R=w.find(M=>M.type==="text"&&/^\[SUGGESTION MODE:/i.test((M.text||"").trim())),T=w.filter(M=>M.type==="tool_result");if(R&&T.length>0){let M=null,L={};for(const A of T){const z=h[A.tool_use_id];if(z&&z.name==="AskUserQuestion"&&((_=z.input)!=null&&_.questions)){M=z.input.questions;const H=zR(A);try{L=JSON.parse(H).answers||{}}catch{}break}}M&&v.push(S.jsx(ro,{role:"user-selection",questions:M,answers:L,timestamp:x,userProfile:o,...k},`${r}-selection-${b}`))}else{const{commands:M,textBlocks:L,skillBlocks:A}=AR(w);for(let z=0;z<M.length;z++)v.push(S.jsx(ro,{role:"user",text:M[z],timestamp:x,userProfile:o,modelInfo:i,...k},`${r}-cmd-${b}-${z}`));for(const z of A){const H=z.text.match(/^#\s+(.+)$/m),N=H?H[1]:"Skill";v.push(S.jsx(ro,{role:"skill-loaded",text:z.text,skillName:N,timestamp:x,...k},`${r}-skill-${b}`))}for(let z=0;z<L.length;z++){const H=/^Implement the following plan:/i.test((L[z].text||"").trim());v.push(S.jsx(ro,{role:H?"plan-prompt":"user",text:L[z].text,timestamp:x,userProfile:o,modelInfo:i,...k},`${r}-user-${b}-${z}`))}}}else if(typeof w=="string"&&!yy(w)){const R=/^Implement the following plan:/i.test(w.trim());v.push(S.jsx(ro,{role:R?"plan-prompt":"user",text:w,timestamp:x,userProfile:o,modelInfo:i,...k},`${r}-user-${b}`))}}else y.role==="assistant"&&(Array.isArray(w)?v.push(S.jsx(ro,{role:"assistant",content:w,toolResultMap:p,readContentMap:m,timestamp:x,modelInfo:i,collapseToolResults:l,expandThinking:c,...k},`${r}-asst-${b}`)):typeof w=="string"&&v.push(S.jsx(ro,{role:"assistant",content:[{type:"text",text:w}],toolResultMap:p,readContentMap:m,timestamp:x,modelInfo:i,collapseToolResults:l,expandThinking:c,...k},`${r}-asst-${b}`)))}return v}buildAllItems(){var b,y,w,x;const{mainAgentSessions:n,requests:r,collapseToolResults:i,expandThinking:s,onViewRequest:o}=this.props;if(!n||n.length===0)return[];const l={};if(r)for(let E=0;E<r.length;E++)yi(r[E])&&r[E].timestamp&&(l[r[E].timestamp]=E);let c=null;if(r){for(let E=r.length-1;E>=0;E--)if(yi(r[E])&&((b=r[E].body)!=null&&b.model)){c=r[E].body.model;break}}const u=$K(c),h=[],p={},m=[];if(r)for(let E=0;E<r.length;E++){const k=r[E];if(!k.timestamp)continue;const R=jl(k,r[E+1]);if(R.type==="SubAgent"){const T=(w=(y=k.response)==null?void 0:y.body)==null?void 0:w.content;if(Array.isArray(T)&&T.length>0){const M=i3(((x=k.body)==null?void 0:x.messages)||[]).toolResultMap;m.push({timestamp:k.timestamp,content:T,toolResultMap:M,label:Yp(R.type,R.subType),requestIndex:E})}}}let v=0;n.forEach((E,k)=>{var T,M,L,A;k>0&&h.push(S.jsx(G2,{style:{borderColor:"#333",margin:"16px 0"},children:S.jsx(r3,{className:mn.sessionDividerText,children:"Session"})},`session-div-${k}`));const R=this.renderSessionMessages(E.messages,`s${k}`,u,l);for(const z of R){const H=z.props.timestamp;for(;v<m.length&&H&&m[v].timestamp<=H;){const N=m[v];N.timestamp&&(p[N.timestamp]=h.length),h.push(S.jsx(ro,{role:"sub-agent-chat",content:N.content,toolResultMap:N.toolResultMap,label:N.label,timestamp:N.timestamp,collapseToolResults:i,expandThinking:s,requestIndex:N.requestIndex,onViewRequest:o},`sub-chat-${v}`)),v++}H&&(p[H]=h.length),h.push(z)}for(;v<m.length;){const z=m[v],H=k<n.length-1&&((M=(T=n[k+1].messages)==null?void 0:T[0])==null?void 0:M._timestamp);if(H&&z.timestamp>H)break;z.timestamp&&(p[z.timestamp]=h.length),h.push(S.jsx(ro,{role:"sub-agent-chat",content:z.content,toolResultMap:z.toolResultMap,label:z.label,timestamp:z.timestamp,collapseToolResults:i,expandThinking:s,requestIndex:z.requestIndex,onViewRequest:o},`sub-chat-${v}`)),v++}if(k===n.length-1&&((A=(L=E.response)==null?void 0:L.body)!=null&&A.content)){const z=E.response.body.content;Array.isArray(z)&&(h.push(S.jsx(J.Fragment,{children:S.jsx(G2,{style:{borderColor:"#2a2a2a",margin:"8px 0"},children:S.jsx(r3,{type:"secondary",className:mn.lastResponseLabel,children:he("ui.lastResponse")})})},"resp-divider")),E.entryTimestamp&&(p[E.entryTimestamp]=h.length),h.push(S.jsx(ro,{role:"assistant",content:z,timestamp:E.entryTimestamp,modelInfo:u,collapseToolResults:i,expandThinking:s,toolResultMap:{}},"resp-asst")))}});const{scrollToTimestamp:_}=this.props;return this._scrollTargetIdx=_&&p[_]!=null?p[_]:null,this._tsItemMap=p,h}_extractSuggestion(){var c;const{mainAgentSessions:n}=this.props;if(!(n!=null&&n.length))return null;const r=n[n.length-1],i=r==null?void 0:r.response;if(!i)return null;const s=i.body;if(!s)return null;const o=s.stop_reason;if(o!=="end_turn"&&o!=="max_tokens")return null;const l=s.content;if(!Array.isArray(l))return null;for(let u=l.length-1;u>=0;u--)if(l[u].type==="text"&&((c=l[u].text)!=null&&c.trim()))return l[u].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 l=o.map(h=>{const p=h.match(/\s*([❯>])?\s*(\d+)\.\s+(.+)/);return{number:parseInt(p[2],10),text:p[3].trim(),selected:!!p[1]}}),c=this.state.ptyPrompt,u={question:i,options:l};c&&c.question===i?this.setState({ptyPrompt:u}):(this.setState(h=>{const p=h.ptyPromptHistory.slice();if(h.ptyPrompt){const m=p[p.length-1];m&&m.status==="active"&&(p[p.length-1]={...m,status:"dismissed"})}return p.push({...u,status:"active",selectedNumber:null,timestamp:new Date().toISOString()}),{ptyPrompt:u,ptyPromptHistory:p}}),this.scrollToBottom());return}}this.state.ptyPrompt&&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})}_snapToInitialPosition(){this.setState({terminalWidth:468,needsInitialSnap:!1}),localStorage.setItem("cc-viewer-terminal-width","468")}_setupFileChangeWatcher(){try{const r=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal`;this._fileChangeWs=new WebSocket(r),this._fileChangeWs.onmessage=i=>{try{const s=JSON.parse(i.data);if(s.type==="file-change"){const{currentFile:o}=this.state;if(!o)return;const l=h=>h?h.split("/").pop():"",c=l(s.path),u=l(o);c===u&&c&&(this._fileChangeDebounceTimer&&clearTimeout(this._fileChangeDebounceTimer),this._fileChangeDebounceTimer=setTimeout(()=>{s.eventType==="unlink"?this.setState({currentFile:null,fileVersion:0}):(s.eventType==="change"||s.eventType==="add")&&this.setState(h=>({fileVersion:h.fileVersion+1}))},300))}}catch{}},this._fileChangeWs.onerror=()=>{},this._fileChangeWs.onclose=()=>{setTimeout(()=>{this._fileChangeWs!==null&&this._setupFileChangeWatcher()},2e3)}}catch{}}render(){const{mainAgentSessions:n,cliMode:r,terminalVisible:i}=this.props,{allItems:s,visibleCount:o,loading:l,terminalWidth:c}=this.state,u=!n||n.length===0;if(u&&!r)return S.jsx("div",{className:mn.centerEmpty,children:S.jsx(Vi,{description:he("ui.noChat")})});if(l&&!r)return S.jsx("div",{className:mn.centerEmpty,children:S.jsx(ua,{size:"large"})});const h=this._scrollTargetIdx,{highlightTs:p,highlightFading:m}=this.state,v=p&&this._tsItemMap&&this._tsItemMap[p]!=null?this._tsItemMap[p]:null,_=s.slice(0,o),{pendingInput:b,stickyBottom:y,ptyPromptHistory:w}=this.state,x=r&&b?S.jsx(ro,{role:"user",text:b,timestamp:new Date().toISOString(),userProfile:this.props.userProfile},"pending-input"):null,E=y?null:S.jsxs("button",{className:mn.stickyBottomBtn,onClick:this.handleStickToBottom,children:[S.jsx("span",{children:he("ui.stickyBottom")}),S.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:S.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),k=r&&w.length>0?w.map((T,M)=>{const L=T.status==="active",A=T.status==="answered";return S.jsxs("div",{className:`${mn.ptyPromptBubble}${L?"":" "+mn.ptyPromptResolved}`,children:[S.jsx("div",{className:mn.ptyPromptQuestion,children:T.question}),S.jsx("div",{className:mn.ptyPromptOptions,children:T.options.map(z=>{const H=A&&T.selectedNumber===z.number;let N=mn.ptyPromptOption;return L&&z.selected&&(N=mn.ptyPromptOptionPrimary),H&&(N=mn.ptyPromptOptionChosen),!L&&!H&&(N=mn.ptyPromptOptionDimmed),S.jsxs("button",{className:N,disabled:!L,onClick:L?()=>this.handlePromptOptionClick(z.number):void 0,children:[z.number,". ",z.text]},z.number)})})]},`pty-prompt-${M}`)}):null,R=u||l?S.jsxs("div",{className:mn.messageListWrap,children:[S.jsxs("div",{ref:this.containerRef,className:mn.container,children:[!r||l?S.jsx("div",{className:mn.centerEmpty,children:l?S.jsx(ua,{size:"large"}):S.jsx(Vi,{description:he("ui.noChat")})}):null,x,k]}),E]}):S.jsxs("div",{className:mn.messageListWrap,children:[S.jsxs("div",{ref:this.containerRef,className:mn.container,children:[_.map((T,M)=>{const L=M===h,A=M===v;let z=T;return A&&(z=J.cloneElement(z,{highlight:m?"fading":"active"})),L?S.jsx("div",{ref:this._scrollTargetRef,children:z},T.key+"-anchor"):z}),x,k]}),E]});return r?S.jsxs("div",{ref:this.splitContainerRef,className:mn.splitContainer,children:[S.jsxs("div",{className:mn.navSidebar,children:[S.jsx("button",{className:this.state.fileExplorerOpen?mn.navBtnActive:mn.navBtn,onClick:()=>this.setState({fileExplorerOpen:!0,gitChangesOpen:!1,currentFile:null}),title:he("ui.fileExplorer"),children:S.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:S.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"})})}),S.jsx("button",{className:this.state.gitChangesOpen?mn.navBtnActive:mn.navBtn,onClick:()=>this.setState({gitChangesOpen:!0,fileExplorerOpen:!1,currentFile:null}),title:he("ui.gitChanges"),children:S.jsx("svg",{width:"24",height:"24",viewBox:"0 0 1024 1024",fill:"currentColor",children:S.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"})})})]}),S.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 A=T.getBoundingClientRect().width-this.state.terminalWidth-5,z=this.state.activeSnapLine.linePosition,H=Math.min(A,z),N=Math.abs(z-A);return S.jsx("div",{className:mn.snapPreview,style:{left:`${H}px`,width:`${N}px`}})})(),this.state.isDragging&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const A=T.getBoundingClientRect().width-this.state.terminalWidth-5,z=[...this.state.snapLines].map(O=>({...O,dist:Math.abs(O.linePosition-A)})).sort((O,I)=>O.dist-I.dist);if(z.length===0)return null;const H=z[0],N=this.state.activeSnapLine&&this.state.activeSnapLine.cols===H.cols;return S.jsx("div",{className:N?mn.snapLineActive:mn.snapLine,style:{left:`${H.linePosition}px`}},H.cols)})(),this.state.fileExplorerOpen&&S.jsx(Loe,{onClose:()=>this.setState({fileExplorerOpen:!1}),onFileClick:T=>this.setState({currentFile:T,currentGitDiff:null}),expandedPaths:this.state.fileExplorerExpandedPaths,onToggleExpand:this.handleToggleExpandPath,currentFile:this.state.currentFile}),this.state.gitChangesOpen&&S.jsx(nle,{onClose:()=>this.setState({gitChangesOpen:!1}),onFileClick:T=>this.setState({currentGitDiff:T,currentFile:null})}),S.jsx("div",{className:mn.chatSection,style:{flex:1,minWidth:0,display:"flex"},children:S.jsxs("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[this.state.currentGitDiff?S.jsx(Dle,{filePath:this.state.currentGitDiff,onClose:()=>this.setState({currentGitDiff:null})}):this.state.currentFile?S.jsx(Lae,{filePath:this.state.currentFile,onClose:()=>this.setState({currentFile:null,fileVersion:0})},this.state.fileVersion):R,!i&&S.jsxs("div",{className:mn.chatInputBar,children:[S.jsxs("div",{className:mn.chatInputWrapper,children:[S.jsxs("div",{className:mn.chatTextareaWrap,children:[S.jsx("textarea",{ref:this._inputRef,className:mn.chatTextarea,placeholder:this.state.inputSuggestion?"":he("ui.chatInput.placeholder"),rows:1,onKeyDown:this.handleInputKeyDown,onInput:this.handleInputChange}),this.state.inputSuggestion&&this.state.inputEmpty&&S.jsx("div",{className:mn.ghostText,children:this.state.inputSuggestion})]}),S.jsx("div",{className:mn.chatInputHint,children:this.state.inputSuggestion&&this.state.inputEmpty?he("ui.chatInput.hintTab"):he("ui.chatInput.hintEnter")})]}),S.jsx("button",{className:mn.chatSendBtn,onClick:this.handleInputSend,disabled:this.state.inputEmpty,title:he("ui.chatInput.send"),children:S.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[S.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),S.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),i&&this.state.inputSuggestion&&S.jsxs("div",{className:mn.suggestionChip,onClick:this.handleSuggestionToTerminal,children:[S.jsx("span",{className:mn.suggestionChipText,children:this.state.inputSuggestion}),S.jsx("span",{className:mn.suggestionChipAction,children:"↵"})]})]})}),i&&S.jsxs(S.Fragment,{children:[S.jsx("div",{className:mn.vResizer,onMouseDown:this.handleSplitMouseDown}),S.jsx("div",{style:{width:c,flexShrink:0,minWidth:200,display:"flex",flexDirection:"column"},children:S.jsx(bT,{})})]})]})]}):R}}const Cce="_resizer_yamj2_1",wce={resizer:Cce};class xce extends J.Component{constructor(t){super(t),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this)}handleMouseDown(t){t.preventDefault(),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}handleMouseMove(t){this.props.onResize&&this.props.onResize(t.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 S.jsx("div",{onMouseDown:this.handleMouseDown,className:wce.resizer})}}const Ece="_container_1um1r_1",kce="_fileListSection_1um1r_10",$ce="_header_1um1r_19",Rce="_headerTitle_1um1r_28",Tce="_fileCount_1um1r_36",Nce="_changesContainer_1um1r_44",Mce="_changeItem_1um1r_51",Oce="_changeItemActive_1um1r_68",Ice="_dirItem_1um1r_77",Pce="_dirArrow_1um1r_88",Lce="_dirName_1um1r_97",Ace="_status_1um1r_102",Bce="_icon_1um1r_111",zce="_fileName_1um1r_120",jce="_diffSection_1um1r_127",Dce="_diffHeader_1um1r_135",Fce="_diffFilePath_1um1r_145",Hce="_diffBadge_1um1r_155",Wce="_diffContent_1um1r_167",Vce="_diffPlaceholder_1um1r_173",Uce="_statusText_1um1r_184",qce="_errorText_1um1r_191",Gce="_emptyText_1um1r_198",Kce="_warningText_1um1r_205",Jn={container:Ece,fileListSection:kce,header:$ce,headerTitle:Rce,fileCount:Tce,changesContainer:Nce,changeItem:Mce,changeItemActive:Oce,dirItem:Ice,dirArrow:Pce,dirName:Lce,status:Ace,icon:Bce,fileName:zce,diffSection:jce,diffHeader:Dce,diffFilePath:Fce,diffBadge:Hce,diffContent:Wce,diffPlaceholder:Vce,statusText:Uce,errorText:qce,emptyText:Gce,warningText:Kce},Xce={M:"#e2c08d",A:"#73c991",D:"#f14c4c",R:"#73c991",C:"#73c991",U:"#e2c08d","?":"#73c991"},Yce={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 Zce(e){const t=e.includes(".")?e.split(".").pop().toLowerCase():"",n=Yce[t]||"#888";return S.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",children:[S.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),S.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function Qce(){return S.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"#c09553",stroke:"none",children:S.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 Jce(e){const t={dirs:{},files:[]};for(const n of e){const r=n.file.split("/");let i=t;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 t}function i8({name:e,node:t,depth:n,selectedFile:r,onFileClick:i}){const s=Object.keys(t.dirs).sort(),o=[...t.files].sort((l,c)=>l.name.localeCompare(c.name));return S.jsxs(S.Fragment,{children:[e&&S.jsxs("div",{className:Jn.dirItem,style:{paddingLeft:8+n*16},children:[S.jsx("span",{className:Jn.dirArrow,children:S.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:S.jsx("polyline",{points:"9 6 15 12 9 18"})})}),S.jsx("span",{className:Jn.icon,children:Qce()}),S.jsx("span",{className:Jn.dirName,children:e})]}),s.map(l=>S.jsx(i8,{name:l,node:t.dirs[l],depth:e?n+1:n,selectedFile:r,onFileClick:i},l)),o.map(l=>S.jsxs("div",{className:`${Jn.changeItem} ${r===l.fullPath?Jn.changeItemActive:""}`,style:{paddingLeft:8+(e?n+1:n)*16},onClick:()=>i&&i(l.fullPath),children:[S.jsx("span",{className:Jn.icon,children:Zce(l.name)}),S.jsx("span",{className:Jn.fileName,children:l.name}),S.jsx("span",{className:Jn.status,style:{color:Xce[l.status]||"#888"},children:l.status})]},l.fullPath))]})}function eue(){const[e,t]=f.useState(null),[n,r]=f.useState(null),[i,s]=f.useState(!0),[o,l]=f.useState(null),[c,u]=f.useState(null),[h,p]=f.useState(null),[m,v]=f.useState(!1),_=f.useRef(!0);return f.useEffect(()=>(_.current=!0,s(!0),fetch(kn("/api/git-status")).then(b=>b.ok?b.json():Promise.reject()).then(b=>{_.current&&(t(b.changes||[]),s(!1))}).catch(()=>{_.current&&(r("Failed to load git status"),s(!1))}),()=>{_.current=!1}),[]),f.useEffect(()=>{if(!o){u(null),p(null);return}v(!0),u(null),p(null),fetch(kn(`/api/git-diff?files=${encodeURIComponent(o)}`)).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}`);return b.json()}).then(b=>{_.current&&(b.diffs&&b.diffs[0]?u(b.diffs[0]):p("No diff data available"),v(!1))}).catch(b=>{_.current&&(p(`${he("ui.fileLoadError")}: ${b.message}`),v(!1))})},[o]),S.jsxs("div",{className:Jn.container,children:[S.jsxs("div",{className:Jn.fileListSection,children:[S.jsxs("div",{className:Jn.header,children:[S.jsx("span",{className:Jn.headerTitle,children:he("ui.gitChanges")}),S.jsx("span",{className:Jn.fileCount,children:e?e.length:0})]}),S.jsxs("div",{className:Jn.changesContainer,children:[i&&S.jsx("div",{className:Jn.statusText,children:"Loading..."}),n&&S.jsx("div",{className:Jn.errorText,children:n}),!i&&!n&&e&&e.length===0&&S.jsx("div",{className:Jn.emptyText,children:"No changes"}),!i&&!n&&e&&e.length>0&&S.jsx(i8,{name:"",node:Jce(e),depth:0,selectedFile:o,onFileClick:l})]})]}),S.jsx("div",{className:Jn.diffSection,children:o?S.jsxs(S.Fragment,{children:[S.jsxs("div",{className:Jn.diffHeader,children:[S.jsx("span",{className:Jn.diffFilePath,children:o}),S.jsx("span",{className:Jn.diffBadge,children:"DIFF"})]}),S.jsxs("div",{className:Jn.diffContent,children:[m&&S.jsx("div",{className:Jn.statusText,children:he("ui.loading")}),h&&S.jsx("div",{className:Jn.errorText,children:h}),!m&&!h&&c&&S.jsx(S.Fragment,{children:c.is_large?S.jsxs("div",{className:Jn.warningText,children:[S.jsx("p",{children:he("ui.largeFileWarning")}),S.jsxs("p",{style:{color:"#888",fontSize:12},children:[he("ui.fileSize"),": ",(c.size/(1024*1024)).toFixed(2)," MB"]})]}):c.is_binary?S.jsx("div",{className:Jn.statusText,style:{fontStyle:"italic"},children:he("ui.binaryFileNotice")}):S.jsx(r8,{file_path:o,old_string:c.old_content,new_string:c.new_content})})]})]}):S.jsxs("div",{className:Jn.diffPlaceholder,children:[S.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"#333",strokeWidth:"1.5",children:[S.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),S.jsx("circle",{cx:"18",cy:"6",r:"3"}),S.jsx("circle",{cx:"6",cy:"18",r:"3"}),S.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),S.jsx("span",{children:he("ui.mobileGitDiffHint")})]})})]})}const{Text:kl,Title:tue}=Xs;function nue(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=0,r=e;for(;r>=1024&&n<t.length-1;)r/=1024,n++;return`${r.toFixed(n>0?1:0)} ${t[n]}`}function rue(e){if(!e)return"";const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return he("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 iue({open:e,onClose:t,onSelect:n}){const[r,i]=f.useState(""),[s,o]=f.useState(null),[l,c]=f.useState([]),[u,h]=f.useState(!1),[p,m]=f.useState(""),v=f.useCallback(b=>{h(!0);const y=b?`/api/browse-dir?path=${encodeURIComponent(b)}`:"/api/browse-dir";fetch(kn(y)).then(w=>w.json()).then(w=>{w.error?dr.error(w.error):(i(w.current),o(w.parent),c(w.dirs||[]),m(w.current)),h(!1)}).catch(()=>{dr.error("Failed to browse directory"),h(!1)})},[]);f.useEffect(()=>{e&&v("")},[e,v]);const _=()=>{const b=p.trim();b&&v(b)};return S.jsxs(Ci,{title:he("ui.workspaces.selectDir"),open:e,onCancel:t,footer:null,width:600,styles:{body:{padding:"12px 0"}},children:[S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"0 16px 10px",borderBottom:"1px solid #2a2a2a"},children:[S.jsx(Cn,{type:"text",icon:S.jsx(DG,{}),disabled:!s,onClick:()=>s&&v(s),size:"small"}),S.jsxs(kl,{style:{color:"#e0e0e0",fontSize:13,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[S.jsx(m1,{style:{marginRight:6,color:"#1668dc"}}),r]})]}),S.jsx("div",{style:{maxHeight:400,overflowY:"auto",padding:"4px 0"},children:u?S.jsx("div",{style:{textAlign:"center",padding:40},children:S.jsx(ua,{})}):l.length===0?S.jsx("div",{style:{textAlign:"center",padding:40},children:S.jsx(kl,{type:"secondary",children:he("ui.workspaces.emptyDir")})}):l.map(b=>S.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 16px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:y=>y.currentTarget.style.background="#1a1a1a",onMouseLeave:y=>y.currentTarget.style.background="transparent",children:[S.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:8,minWidth:0},onClick:()=>v(b.path),children:[S.jsx($q,{style:{color:b.hasGit?"#1668dc":"#666",fontSize:16,flexShrink:0}}),S.jsx(kl,{style:{color:"#d0d0d0",fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.name}),b.hasGit&&S.jsxs(ls,{color:"blue",style:{fontSize:11,lineHeight:"18px",padding:"0 4px",margin:0,flexShrink:0},children:[S.jsx(CR,{style:{marginRight:2}}),"git"]})]}),S.jsx(Cn,{type:"primary",size:"small",onClick:y=>{y.stopPropagation(),n(b.path)},children:he("ui.workspaces.select")})]},b.path))}),S.jsxs("div",{style:{borderTop:"1px solid #2a2a2a",padding:"10px 16px 4px",display:"flex",flexDirection:"column",gap:8},children:[S.jsxs(Cn,{type:"primary",ghost:!0,block:!0,icon:S.jsx(m1,{}),onClick:()=>n(r),children:[he("ui.workspaces.selectCurrent")," — ",r.split("/").pop()||r]}),S.jsxs("div",{style:{display:"flex",gap:8},children:[S.jsx(Gl,{size:"small",value:p,onChange:b=>m(b.target.value),onPressEnter:_,placeholder:he("ui.workspaces.pathPlaceholder"),style:{flex:1}}),S.jsx(Cn,{size:"small",onClick:_,children:he("ui.workspaces.goTo")})]})]})]})}function sue({onLaunch:e}){const[t,n]=f.useState([]),[r,i]=f.useState(!0),[s,o]=f.useState(null),[l,c]=f.useState(!1),u=()=>{fetch(kn("/api/workspaces")).then(v=>v.json()).then(v=>{n(v.workspaces||[]),i(!1)}).catch(()=>i(!1))};f.useEffect(()=>{u()},[]);const h=v=>{c(!1),fetch(kn("/api/workspaces/add"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:v})}).then(_=>_.json()).then(_=>{_.error?dr.error(_.error):u()}).catch(()=>dr.error("Failed to add workspace"))},p=v=>{fetch(kn(`/api/workspaces/${v}`),{method:"DELETE"}).then(_=>_.json()).then(()=>u()).catch(()=>{})},m=v=>{o(v.id),fetch(kn("/api/workspaces/launch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:v.path})}).then(_=>_.json()).then(_=>{_.error?(dr.error(_.error),o(null)):e({projectName:_.projectName,path:v.path})}).catch(()=>{dr.error("Launch failed"),o(null)})};return S.jsxs("div",{style:{minHeight:"100vh",background:"#0a0a0a",display:"flex",justifyContent:"center",paddingTop:60},children:[S.jsxs("div",{style:{width:"100%",maxWidth:720,padding:"0 24px"},children:[S.jsxs("div",{style:{marginBottom:32,textAlign:"center"},children:[S.jsxs(tue,{level:3,style:{color:"#e0e0e0",margin:0},children:[S.jsx(m1,{style:{marginRight:8,color:"#1668dc"}}),he("ui.workspaces.title")]}),S.jsx(kl,{type:"secondary",style:{fontSize:13},children:he("ui.workspaces.subtitle")})]}),S.jsx("div",{style:{marginBottom:20,textAlign:"center"},children:S.jsx(Cn,{type:"primary",icon:S.jsx(Hp,{}),onClick:()=>c(!0),size:"large",children:he("ui.workspaces.browse")})}),r?S.jsx("div",{style:{textAlign:"center",padding:60},children:S.jsx(ua,{})}):t.length===0?S.jsx(Vi,{description:S.jsx(kl,{type:"secondary",children:he("ui.workspaces.empty")}),style:{marginTop:60}}):S.jsx(hu,{dataSource:t,renderItem:v=>S.jsx(fy,{size:"small",style:{marginBottom:10,background:"#141414",borderColor:"#2a2a2a",cursor:"pointer"},hoverable:!0,onClick:()=>m(v),children:S.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[S.jsxs("div",{style:{flex:1,minWidth:0},children:[S.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:S.jsx(kl,{strong:!0,style:{color:"#e0e0e0",fontSize:15},children:v.projectName})}),S.jsx(kl,{type:"secondary",style:{fontSize:12,wordBreak:"break-all"},children:v.path}),S.jsxs("div",{style:{display:"flex",gap:16,marginTop:6,fontSize:12,color:"#666"},children:[S.jsxs("span",{children:[S.jsx(GW,{style:{marginRight:4}}),rue(v.lastUsed)]}),v.logCount>0&&S.jsxs("span",{children:[S.jsx(QG,{style:{marginRight:4}}),v.logCount," logs (",nue(v.totalSize),")"]})]})]}),S.jsxs(To,{children:[S.jsx(Cn,{type:"primary",icon:S.jsx(dK,{}),loading:s===v.id,onClick:_=>{_.stopPropagation(),m(v)},children:he("ui.workspaces.open")}),S.jsx(gR,{title:he("ui.workspaces.confirmRemove"),onConfirm:_=>{_==null||_.stopPropagation(),p(v.id)},onCancel:_=>_==null?void 0:_.stopPropagation(),okText:"Yes",cancelText:"No",children:S.jsx(Cn,{type:"text",danger:!0,icon:S.jsx(bR,{}),onClick:_=>_.stopPropagation()})})]})]})},v.id)})]}),S.jsx(iue,{open:l,onClose:()=>c(!1),onSelect:h})]})}const oue="_layout_1iry8_1",aue="_header_1iry8_6",lue="_content_1iry8_14",cue="_mainContainer_1iry8_19",uue="_leftPanel_1iry8_24",due="_leftPanelHeader_1iry8_32",hue="_leftPanelCount_1iry8_43",fue="_leftPanelBody_1iry8_49",pue="_rightPanel_1iry8_54",mue="_modalActions_1iry8_60",gue="_spinCenter_1iry8_64",vue="_emptyCenter_1iry8_69",_ue="_logCheckbox_1iry8_75",bue="_logListContainer_1iry8_79",yue="_logListItem_1iry8_85",Sue="_logItemRow_1iry8_91",Cue="_logFileName_1iry8_108",wue="_logFileIcon_1iry8_121",xue="_loadingOverlay_1iry8_127",Eue="_loadingText_1iry8_140",kue="_footer_1iry8_146",$ue="_footerRight_1iry8_156",Rue="_footerText_1iry8_164",Tue="_footerLink_1iry8_169",Nue="_footerIcon_1iry8_181",Mue="_footerDivider_1iry8_186",Oue="_guideContainer_1iry8_194",Iue="_guideContent_1iry8_202",Pue="_guideTitle_1iry8_207",Lue="_guideStep_1iry8_214",Aue="_guideStepNum_1iry8_220",Bue="_guideStepBody_1iry8_235",zue="_guideText_1iry8_240",jue="_guideCode_1iry8_247",Due="_mobileChatOverlay_1iry8_260",Fue="_mobileChatOverlayVisible_1iry8_272",Hue="_mobileChatInner_1iry8_276",Wue="_mobileGitDiffOverlay_1iry8_284",Vue="_mobileGitDiffOverlayVisible_1iry8_296",Uue="_mobileGitDiffInner_1iry8_300",Xt={layout:oue,header:aue,content:lue,mainContainer:cue,leftPanel:uue,leftPanelHeader:due,leftPanelCount:hue,leftPanelBody:fue,rightPanel:pue,modalActions:mue,spinCenter:gue,emptyCenter:vue,logCheckbox:_ue,logListContainer:bue,logListItem:yue,logItemRow:Sue,logFileName:Cue,logFileIcon:wue,loadingOverlay:xue,loadingText:Eue,footer:kue,footerRight:$ue,footerText:Rue,footerLink:Tue,footerIcon:Nue,footerDivider:Mue,guideContainer:Oue,guideContent:Iue,guideTitle:Pue,guideStep:Lue,guideStepNum:Aue,guideStepBody:Bue,guideText:zue,guideCode:jue,mobileChatOverlay:Due,mobileChatOverlayVisible:Fue,mobileChatInner:Hue,mobileGitDiffOverlay:Wue,mobileGitDiffOverlayVisible:Vue,mobileGitDiffInner:Uue};class que extends J.Component{constructor(n){super(n);St(this,"handleSelectRequest",n=>{this.setState({selectedIndex:n,scrollCenter:!1})});St(this,"handleViewRequest",n=>{this.setState({viewMode:"raw",selectedIndex:n,scrollCenter:!0})});St(this,"handleViewInChat",()=>{this.setState(n=>{const i=(n.showAll?n.requests:Qo(n.requests))[n.selectedIndex];if(!i)return null;let s=null;if(yi(i)&&i.timestamp)s=i.timestamp;else{if(jl(i).type==="SubAgent"&&i.timestamp)s=i.timestamp;else{const l=n.requests.indexOf(i);l>=0&&(s=SE(n.requests,l))}s||dr.info(he("ui.cannotMap"))}return{viewMode:"chat",chatScrollToTs:s}})});St(this,"handleWorkspaceLaunch",({projectName:n})=>{this._isLocalLog=!1,this._localLogFile=null,this.setState({workspaceMode:!1,projectName:n,viewMode:"chat",cliMode:!0})});St(this,"handleReturnToWorkspaces",()=>{fetch(kn("/api/workspaces/stop"),{method:"POST"}).then(()=>{this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null})}).catch(()=>{})});St(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:Qo(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:Qo(n.requests),s=n.selectedIndex!=null?i[n.selectedIndex]:null;if(s){let o=null;if(yi(s)&&s.timestamp)o=s.timestamp;else if(jl(s).type==="SubAgent"&&s.timestamp)o=s.timestamp;else{const c=n.requests.indexOf(s);c>=0&&(o=SE(n.requests,c)),o||dr.info(he("ui.cannotMap"))}return{viewMode:r,chatScrollToTs:o}}return{viewMode:r,chatScrollToTs:null}})});St(this,"handleLangChange",()=>{const n=Yd();this.setState({lang:n}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:n})}).catch(()=>{})});St(this,"handleCollapseToolResultsChange",n=>{this.setState({collapseToolResults:n}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({collapseToolResults:n})}).catch(()=>{})});St(this,"handleExpandThinkingChange",n=>{this.setState({expandThinking:n}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandThinking:n})}).catch(()=>{})});St(this,"handleExpandDiffChange",n=>{this.setState({expandDiff:n}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandDiff:n})}).catch(()=>{})});St(this,"handleFilterIrrelevantChange",n=>{this.setState(r=>{const i=!n,s=i?r.requests:Qo(r.requests);return{showAll:i,selectedIndex:s.length>0?s.length-1:null}}),fetch(kn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filterIrrelevant:n})}).catch(()=>{})});St(this,"handleTabChange",n=>{this.setState({currentTab:n})});St(this,"handleResize",n=>{const r=this.mainContainerRef.current;if(!r)return;const i=r.getBoundingClientRect(),s=n-i.left;s>=250&&s<=800&&this.setState({leftPanelWidth:s})});St(this,"handleImportLocalLogs",()=>{this.setState({importModalVisible:!0,localLogsLoading:!0}),fetch(kn("/api/local-logs")).then(n=>n.json()).then(n=>{const{_currentProject:r,...i}=n;this.setState({localLogs:i,currentProject:r||"",localLogsLoading:!1})}).catch(()=>{this.setState({localLogs:{},localLogsLoading:!1})})});St(this,"handleCloseImportModal",()=>{this.setState({importModalVisible:!1,selectedLogs:new Set})});St(this,"handleToggleLogSelect",(n,r)=>{this.setState(i=>{const s=new Set(i.selectedLogs);return r?s.add(n):s.delete(n),{selectedLogs:s}})});St(this,"handleMergeLogs",()=>{const{selectedLogs:n,localLogs:r,currentProject:i}=this.state;if(n.size<2)return;const s=r[i];if(!s)return;const o=[];if(s.forEach((u,h)=>{n.has(u.file)&&o.push(h)}),o.sort((u,h)=>u-h),n.has(s[0].file)){dr.warning(he("ui.mergeLatestNotAllowed"));return}for(let u=1;u<o.length;u++)if(o[u]-o[u-1]!==1){dr.warning(he("ui.mergeNotConsecutive"));return}if(o.reduce((u,h)=>u+s[h].size,0)>500*1024*1024){dr.warning(he("ui.mergeTooLarge"));return}const c=o.map(u=>s[u].file).reverse();fetch(kn("/api/merge-logs"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:c})}).then(u=>u.json()).then(u=>{u.ok?(dr.success(he("ui.mergeSuccess")),this.setState({selectedLogs:new Set}),this.handleImportLocalLogs()):dr.error(u.error||"Merge failed")}).catch(()=>dr.error("Merge failed"))});St(this,"handleOpenLogFile",n=>{const r=window.location.port||window.location.host.split(":")[1]||"7008";window.open(`${window.location.protocol}//${window.location.hostname}:${r}?logfile=${encodeURIComponent(n)}`,"_blank"),this.setState({importModalVisible:!1})});St(this,"handleResumeChoice",n=>{fetch(kn("/api/resume-choice"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({choice:n})}).catch(r=>console.error("resume-choice failed:",r))});St(this,"handleLoadLocalJsonlFile",()=>{const n=document.createElement("input");n.type="file",n.accept=".jsonl",n.onchange=r=>{const i=r.target.files[0];if(!i)return;if(i.size>500*1024*1024){dr.error(he("ui.fileTooLarge"));return}this.setState({fileLoading:!0,fileLoadingCount:0});const s=new FileReader;s.onload=o=>{try{const c=o.target.result.split(`
|
|
717
717
|
---
|
|
718
|
-
`).filter(u=>u.trim()).map(u=>{try{return JSON.parse(u)}catch{return null}}).filter(Boolean);if(c.length===0){dr.error(he("ui.noLogs")),this.setState({fileLoading:!1,fileLoadingCount:0});return}this.animateLoadingCount(c.length,()=>{let u=[];for(const p of c)yi(p)&&p.body&&Array.isArray(p.body.messages)&&(u=this.mergeMainAgentSessions(u,p));const h=Qo(c);this._isLocalLog=!0,this._localLogFile=i.name,this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.setState({requests:c,selectedIndex:h.length>0?h.length-1:null,mainAgentSessions:u,importModalVisible:!1,fileLoading:!1,fileLoadingCount:0})})}catch{dr.error(he("ui.noLogs")),this.setState({fileLoading:!1,fileLoadingCount:0})}},s.readAsText(i)},n.click()});const r=parseInt(localStorage.getItem("ccv_cacheExpireAt"),10)||null,i=localStorage.getItem("ccv_cacheType")||null,s=Date.now(),o=r&&r>s?r:null,l=o?i:null;this.state={requests:[],selectedIndex:null,viewMode:"raw",currentTab:"request",cacheExpireAt:o,cacheType:l,leftPanelWidth:380,mainAgentSessions:[],importModalVisible:!1,localLogs:{},localLogsLoading:!1,showAll:!1,lang:Yd(),userProfile:null,projectName:"",resumeModalVisible:!1,resumeFileName:"",collapseToolResults:!0,expandThinking:!0,expandDiff:!1,fileLoading:!1,fileLoadingCount:0,selectedLogs:new Set,githubStars:null,cliMode:!1,terminalVisible:!0,workspaceMode:!1},this.eventSource=null,this._autoSelectTimer=null,this.mainContainerRef=J.createRef()}componentDidMount(){fetch(kn("/api/preferences")).then(i=>i.json()).then(i=>{i.lang&&(wy(i.lang),this.setState({lang:i.lang})),i.collapseToolResults!==void 0&&this.setState({collapseToolResults:!!i.collapseToolResults}),i.expandThinking!==void 0&&this.setState({expandThinking:!!i.expandThinking}),i.expandDiff!==void 0&&this.setState({expandDiff:!!i.expandDiff});const s=i.filterIrrelevant!==void 0?!!i.filterIrrelevant:!0;this.setState({showAll:!s})}).catch(()=>{}),fetch(kn("/api/user-profile")).then(i=>i.json()).then(i=>this.setState({userProfile:i})).catch(()=>{}),fetch(kn("/api/project-name")).then(i=>i.json()).then(i=>this.setState({projectName:i.projectName||""})).catch(()=>{}),fetch("https://api.github.com/repos/weiesky/cc-viewer").then(i=>i.json()).then(i=>{i.stargazers_count!=null&&this.setState({githubStars:i.stargazers_count})}).catch(()=>{}),fetch(kn("/api/cli-mode")).then(i=>i.json()).then(i=>{i.workspaceMode?this.setState({cliMode:!0,workspaceMode:!0,isWorkspaceServer:!0}):i.cliMode&&this.setState({cliMode:!0,viewMode:"chat"})}).catch(()=>{});const r=new URLSearchParams(window.location.search).get("logfile");r?this.loadLocalLogFile(r):this.initSSE()}componentWillUnmount(){this.eventSource&&this.eventSource.close(),this._autoSelectTimer&&clearTimeout(this._autoSelectTimer),this._loadingCountTimer&&cancelAnimationFrame(this._loadingCountTimer)}animateLoadingCount(n,r){const i=Math.min(800,Math.max(300,n*.5)),s=performance.now(),o=l=>{const c=Math.min((l-s)/i,1),u=Math.round(c*n);this.setState({fileLoadingCount:u}),c<1?this._loadingCountTimer=requestAnimationFrame(o):(this._loadingCountTimer=null,r())};this._loadingCountTimer=requestAnimationFrame(o)}initSSE(){this.setState({fileLoading:!0,fileLoadingCount:0});try{this.eventSource=new EventSource(kn("/events")),this.eventSource.onmessage=n=>this.handleEventMessage(n),this.eventSource.addEventListener("resume_prompt",n=>{try{const r=JSON.parse(n.data);this.setState({resumeModalVisible:!0,resumeFileName:r.recentFileName||""})}catch{}}),this.eventSource.addEventListener("resume_resolved",()=>{this.setState({resumeModalVisible:!1,resumeFileName:""})}),this.eventSource.addEventListener("update_completed",n=>{try{const r=JSON.parse(n.data);this.setState({updateInfo:{type:"completed",version:r.version}})}catch{}}),this.eventSource.addEventListener("update_major_available",n=>{try{const r=JSON.parse(n.data);this.setState({updateInfo:{type:"major",version:r.version}})}catch{}}),this.eventSource.addEventListener("full_reload",n=>{try{const r=JSON.parse(n.data);if(Array.isArray(r)){this.assignMessageTimestamps(r);const i=this.buildSessionsFromEntries(r),s=Qo(r);r.length>0?this.animateLoadingCount(r.length,()=>{this.setState({requests:r,selectedIndex:s.length>0?s.length-1:null,mainAgentSessions:i,fileLoading:!1,fileLoadingCount:0})}):this.setState({requests:r,selectedIndex:null,mainAgentSessions:i,fileLoading:!1,fileLoadingCount:0})}else this.setState({fileLoading:!1,fileLoadingCount:0})}catch{this.setState({fileLoading:!1,fileLoadingCount:0})}}),this.eventSource.addEventListener("workspace_started",n=>{try{const r=JSON.parse(n.data);this.setState({workspaceMode:!1,projectName:r.projectName||"",viewMode:"chat",cliMode:!0})}catch{}}),this.eventSource.addEventListener("workspace_stopped",()=>{this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null})}),this.eventSource.onerror=()=>console.error("SSE连接错误")}catch(n){console.error("EventSource初始化失败:",n),this.setState({fileLoading:!1,fileLoadingCount:0})}}loadLocalLogFile(n){this._isLocalLog=!0,this._localLogFile=n,this.setState({fileLoading:!0,fileLoadingCount:0}),fetch(`/api/local-log?file=${encodeURIComponent(n)}`).then(r=>{if(!r.ok)return r.text().then(s=>{throw new Error(`HTTP ${r.status}: ${s}`)});const i=r.headers.get("content-type");return!i||!i.includes("application/json")?r.text().then(s=>{throw new Error(`Invalid content type: ${i}. Response: ${s.substring(0,100)}`)}):r.json()}).then(r=>{Array.isArray(r)?this.animateLoadingCount(r.length,()=>{this.assignMessageTimestamps(r);const i=this.buildSessionsFromEntries(r),s=Qo(r);this.setState({requests:r,selectedIndex:s.length>0?s.length-1:null,mainAgentSessions:i,fileLoading:!1,fileLoadingCount:0})}):this.setState({fileLoading:!1,fileLoadingCount:0})}).catch(r=>{console.error("加载日志文件失败:",r),this.setState({fileLoading:!1,fileLoadingCount:0})})}handleEventMessage(n){try{const r=JSON.parse(n.data);this.setState(i=>{var p,m;const s=[...i.requests],o=s.findIndex(v=>v.timestamp===r.timestamp&&v.url===r.url);o>=0?s[o]=r:s.push(r);let l=i.cacheExpireAt,c=i.cacheType;if(yi(r)){const v=(m=(p=r.response)==null?void 0:p.body)==null?void 0:m.usage;if(v!=null&&v.cache_creation){const _=v.cache_creation,b=r.timestamp?new Date(r.timestamp).getTime():Date.now();let y=null,w=null;if(_.ephemeral_1h_input_tokens>0?(y=b+3600*1e3,w="1h"):_.ephemeral_5m_input_tokens>0&&(y=b+300*1e3,w="5m"),y&&y>Date.now()){l=y;const x=(v.cache_read_input_tokens||0)+(v.cache_creation_input_tokens||0);c=x>0?zr(x):w,localStorage.setItem("ccv_cacheExpireAt",String(l)),localStorage.setItem("ccv_cacheType",c)}}}let u=i.mainAgentSessions;if(yi(r)&&r.body&&Array.isArray(r.body.messages)){const v=r.timestamp||new Date().toISOString(),_=u.length>0?u[u.length-1]:null,b=(_==null?void 0:_.messages)||[],y=r.body.messages,w=b.length,x=w>0&&y.length<w*.5&&w-y.length>4;for(let E=0;E<y.length;E++)!x&&E<w&&b[E]._timestamp?y[E]._timestamp=b[E]._timestamp:y[E]._timestamp||(y[E]._timestamp=v);u=this.mergeMainAgentSessions(i.mainAgentSessions,r)}return i.selectedIndex===null&&s.length>0&&(this._autoSelectTimer&&clearTimeout(this._autoSelectTimer),this._autoSelectTimer=setTimeout(()=>{this.setState(v=>{if(v.selectedIndex===null&&v.requests.length>0){const _=v.showAll?v.requests:Qo(v.requests);return _.length>0?{selectedIndex:_.length-1}:null}return null})},200)),{requests:s,cacheExpireAt:l,cacheType:c,mainAgentSessions:u}})}catch(r){console.error("处理事件消息失败:",r)}}assignMessageTimestamps(n){var s;let r=[],i=null;for(const o of n){if(!yi(o)||!o.body||!Array.isArray(o.body.messages))continue;const l=o.body.messages,c=l.length,u=((s=o.body.metadata)==null?void 0:s.user_id)||null,h=o.timestamp||new Date().toISOString(),p=r.length;p>0&&(c<p*.5&&p-c>4||i&&u&&u!==i)&&(r=[]);for(let v=r.length;v<c;v++)r.push(h);for(let v=0;v<c;v++)l[v]._timestamp=r[v];i=u}}buildSessionsFromEntries(n){let r=[];for(const i of n)yi(i)&&i.body&&Array.isArray(i.body.messages)&&(r=this.mergeMainAgentSessions(r,i));return r}mergeMainAgentSessions(n,r){var p;const i=r.body.messages,s=r.response,o=((p=r.body.metadata)==null?void 0:p.user_id)||null,l=r.timestamp||null;if(n.length===0)return[{userId:o,messages:i,response:s,entryTimestamp:l}];const c=n[n.length-1],u=c.messages?c.messages.length:0,h=u>0&&i.length<u*.5&&u-i.length>4;if(o&&o===c.userId&&!h){const m=[...n];return m[m.length-1]={userId:o,messages:i,response:s,entryTimestamp:l},m}else return[...n,{userId:o,messages:i,response:s,entryTimestamp:l}]}formatTimestamp(n){return!n||n.length<15?n:`${n.slice(0,4)}-${n.slice(4,6)}-${n.slice(6,8)} ${n.slice(9,11)}:${n.slice(11,13)}:${n.slice(13,15)}`}formatSize(n){return n<1024?n+" B":n<1024*1024?(n/1024).toFixed(1)+" KB":(n/(1024*1024)).toFixed(1)+" MB"}render(){const{requests:n,selectedIndex:r,viewMode:i,currentTab:s,cacheExpireAt:o,cacheType:l,leftPanelWidth:c,mainAgentSessions:u,showAll:h,fileLoading:p,fileLoadingCount:m}=this.state,v=h?n:Qo(n),_=r!==null?v[r]:null;if(this.state.workspaceMode)return S.jsx(Vs,{theme:{algorithm:x0.darkAlgorithm,token:{colorBgContainer:"#111",colorBgLayout:"#0a0a0a",colorBgElevated:"#1a1a1a",colorBorder:"#2a2a2a"}},children:S.jsx(sue,{onLaunch:this.handleWorkspaceLaunch})});const b=/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent);return this.state.cliMode&&b?S.jsxs("div",{style:{width:"100vw",height:"100vh",display:"flex",flexDirection:"column",background:"#000"},children:[S.jsxs("div",{style:{padding:"10px 12px",background:"#111",borderBottom:"1px solid #222",display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0},children:[S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[S.jsx(ey,{status:"processing",color:"green"}),S.jsxs("span",{style:{fontSize:12,color:"#aaa"},children:[he("ui.liveMonitoring"),this.state.projectName?`: ${this.state.projectName}`:""]})]}),S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[S.jsx(Cn,{type:"text",size:"small",icon:S.jsx(CR,{}),onClick:()=>this.setState(y=>({mobileGitDiffVisible:!y.mobileGitDiffVisible,mobileChatVisible:!1})),style:{color:this.state.mobileGitDiffVisible?"#fff":"#888",fontSize:12},children:this.state.mobileGitDiffVisible?he("ui.mobileGitDiffExit"):he("ui.mobileGitDiffBrowse")}),S.jsx(Cn,{type:"text",size:"small",icon:S.jsx(wR,{}),onClick:()=>this.setState(y=>({mobileChatVisible:!y.mobileChatVisible,mobileGitDiffVisible:!1})),style:{color:this.state.mobileChatVisible?"#fff":"#888",fontSize:12},children:this.state.mobileChatVisible?he("ui.mobileChatExit"):he("ui.mobileChatBrowse")})]})]}),S.jsxs("div",{style:{flex:1,position:"relative",overflow:"hidden"},children:[S.jsx(bT,{}),S.jsx("div",{className:`${Xt.mobileGitDiffOverlay} ${this.state.mobileGitDiffVisible?Xt.mobileGitDiffOverlayVisible:""}`,children:S.jsx("div",{className:Xt.mobileGitDiffInner,children:S.jsx(eue,{})})}),S.jsx("div",{className:`${Xt.mobileChatOverlay} ${this.state.mobileChatVisible?Xt.mobileChatOverlayVisible:""}`,children:S.jsx(Vs,{theme:{algorithm:x0.darkAlgorithm,token:{colorBgContainer:"#111",colorBgLayout:"#0a0a0a",colorBgElevated:"#1a1a1a",colorBorder:"#2a2a2a"}},children:S.jsx("div",{className:Xt.mobileChatInner,children:S.jsx(s3,{requests:v,mainAgentSessions:u,userProfile:this.state.userProfile,collapseToolResults:this.state.collapseToolResults,expandThinking:this.state.expandThinking,onViewRequest:null,scrollToTimestamp:null,onScrollTsDone:()=>{},cliMode:!1,terminalVisible:!1})})})})]})]}):S.jsxs(Vs,{theme:{algorithm:x0.darkAlgorithm,token:{colorBgContainer:"#111",colorBgLayout:"#0a0a0a",colorBgElevated:"#1a1a1a",colorBorder:"#2a2a2a"}},children:[p&&S.jsx("div",{className:Xt.loadingOverlay,children:S.jsxs("div",{className:Xt.loadingText,children:["Loading...(",m,")"]})}),S.jsxs(Ga,{className:Xt.layout,children:[S.jsx(Ga.Header,{className:Xt.header,children:S.jsx(C1,{requestCount:v.length,requests:v,viewMode:i,cacheExpireAt:o,cacheType:l,onToggleViewMode:this.handleToggleViewMode,onLangChange:this.handleLangChange,onImportLocalLogs:this.handleImportLocalLogs,isLocalLog:!!this._isLocalLog,localLogFile:this._localLogFile,projectName:this.state.projectName,collapseToolResults:this.state.collapseToolResults,onCollapseToolResultsChange:this.handleCollapseToolResultsChange,expandThinking:this.state.expandThinking,onExpandThinkingChange:this.handleExpandThinkingChange,expandDiff:this.state.expandDiff,onExpandDiffChange:this.handleExpandDiffChange,filterIrrelevant:!this.state.showAll,onFilterIrrelevantChange:this.handleFilterIrrelevantChange,updateInfo:this.state.updateInfo,onDismissUpdate:()=>this.setState({updateInfo:null}),cliMode:this.state.cliMode,terminalVisible:this.state.terminalVisible,onToggleTerminal:()=>this.setState(y=>({terminalVisible:!y.terminalVisible})),onReturnToWorkspaces:this.state.cliMode?this.handleReturnToWorkspaces:null})}),S.jsxs(Ga.Content,{className:Xt.content,children:[i==="raw"&&(v.length===0?S.jsx("div",{className:Xt.guideContainer,children:S.jsxs("div",{className:Xt.guideContent,children:[S.jsx("h2",{className:Xt.guideTitle,children:he("ui.guide.title")}),S.jsxs("div",{className:Xt.guideStep,children:[S.jsx("div",{className:Xt.guideStepNum,children:"1"}),S.jsxs("div",{className:Xt.guideStepBody,children:[S.jsx("p",{className:Xt.guideText,children:he("ui.guide.step1")}),S.jsx("code",{className:Xt.guideCode,children:he("ui.guide.exampleQuestion")})]})]}),S.jsxs("div",{className:Xt.guideStep,children:[S.jsx("div",{className:Xt.guideStepNum,children:"2"}),S.jsxs("div",{className:Xt.guideStepBody,children:[S.jsx("p",{className:Xt.guideText,children:he("ui.guide.step2")}),S.jsx("code",{className:Xt.guideCode,children:he("ui.guide.troubleshootCmd")})]})]}),S.jsxs("div",{className:Xt.guideStep,children:[S.jsx("div",{className:Xt.guideStepNum,children:"3"}),S.jsxs("div",{className:Xt.guideStepBody,children:[S.jsx("p",{className:Xt.guideText,children:he("ui.guide.step3")}),S.jsx("code",{className:Xt.guideCode,children:"npm install -g @anthropic-ai/claude-code"})]})]})]})}):S.jsxs("div",{ref:this.mainContainerRef,className:Xt.mainContainer,children:[S.jsxs("div",{className:Xt.leftPanel,style:{width:c},children:[S.jsxs("div",{className:Xt.leftPanelHeader,children:[S.jsx("span",{children:he("ui.requestList")}),S.jsx("span",{className:Xt.leftPanelCount,children:he("ui.totalRequests",{count:v.length})})]}),S.jsx("div",{className:Xt.leftPanelBody,children:S.jsx(CZ,{requests:v,selectedIndex:r,scrollCenter:this.state.scrollCenter,onSelect:this.handleSelectRequest,onScrollDone:()=>this.setState({scrollCenter:!1})})})]}),S.jsx(xce,{onResize:this.handleResize}),S.jsx("div",{className:Xt.rightPanel,children:S.jsx(TJ,{request:_,requests:v,selectedIndex:r,currentTab:s,onTabChange:this.handleTabChange,onViewInChat:this.handleViewInChat,expandDiff:this.state.expandDiff})})]})),S.jsx("div",{style:{display:i==="chat"?"flex":"none",height:"100%",flexDirection:"column"},children:S.jsx(s3,{requests:v,mainAgentSessions:u,userProfile:this.state.userProfile,collapseToolResults:this.state.collapseToolResults,expandThinking:this.state.expandThinking,onViewRequest:this.handleViewRequest,scrollToTimestamp:this.state.chatScrollToTs,onScrollTsDone:()=>this.setState({chatScrollToTs:null}),cliMode:this.state.cliMode,terminalVisible:this.state.terminalVisible})})]}),S.jsx("div",{className:Xt.footer,children:S.jsxs("div",{className:Xt.footerRight,children:[S.jsx("span",{className:Xt.footerText,children:he("ui.footer.starRequest")}),S.jsxs("a",{href:"https://github.com/weiesky/cc-viewer",target:"_blank",rel:"noopener noreferrer",className:Xt.footerLink,children:[S.jsx("svg",{className:Xt.footerIcon,viewBox:"0 0 16 16",fill:"currentColor",children:S.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"})}),"GitHub",this.state.githubStars!=null?` ★ ${this.state.githubStars}`:""]}),S.jsx("span",{className:Xt.footerDivider,children:"|"}),S.jsx("a",{href:"dingtalk://dingtalkclient/action/sendmsg?dingtalk_id=sthk5es",className:Xt.footerLink,children:he("ui.footer.contact")})]})})]}),S.jsx(Ci,{title:he("ui.resume.title"),open:this.state.resumeModalVisible,closable:!1,maskClosable:!1,keyboard:!1,footer:[S.jsx(Cn,{type:"primary",onClick:()=>this.handleResumeChoice("continue"),children:he("ui.resume.continue")},"continue"),S.jsx(Cn,{onClick:()=>this.handleResumeChoice("new"),children:he("ui.resume.new")},"new")],children:S.jsx("p",{children:he("ui.resume.message",{file:this.state.resumeFileName})})}),S.jsxs(Ci,{title:he("ui.importLocalLogs"),open:this.state.importModalVisible,onCancel:this.handleCloseImportModal,footer:null,width:1e3,styles:{body:{maxHeight:"60vh",overflow:"auto"}},children:[S.jsxs("div",{className:Xt.modalActions,children:[S.jsx(Cn,{icon:S.jsx(gK,{}),onClick:this.handleLoadLocalJsonlFile,children:he("ui.loadLocalJsonl")}),S.jsx(Cn,{size:"small",type:this.state.selectedLogs.size>1?"primary":"default",disabled:this.state.selectedLogs.size<2,onClick:this.handleMergeLogs,style:{marginLeft:8},children:he("ui.mergeLogs")})]}),this.state.localLogsLoading?S.jsx("div",{className:Xt.spinCenter,children:S.jsx(ua,{})}):(()=>{const y=this.state.localLogs[this.state.currentProject];return!y||y.length===0?S.jsx("div",{className:Xt.emptyCenter,children:he("ui.noLogs")}):S.jsx("div",{className:Xt.logListContainer,children:S.jsx(hu,{size:"small",dataSource:y,renderItem:w=>S.jsx(hu.Item,{className:Xt.logListItem,onClick:()=>{const x=!this.state.selectedLogs.has(w.file);this.handleToggleLogSelect(w.file,x)},children:S.jsxs("div",{className:Xt.logItemRow,children:[S.jsxs("span",{children:[S.jsx(py,{className:Xt.logCheckbox,checked:this.state.selectedLogs.has(w.file)||!1,onClick:x=>x.stopPropagation(),onChange:x=>{x.stopPropagation(),this.handleToggleLogSelect(w.file,x.target.checked)}}),S.jsx(Od,{className:Xt.logFileIcon}),S.jsx("span",{className:Xt.logFileName,children:this.formatTimestamp(w.timestamp)})]}),S.jsxs("span",{children:[S.jsxs(ls,{style:{background:"#0a0a0a",border:"1px solid #444",color:"#999"},children:[w.turns||0," ",he("ui.turns")]}),S.jsx(ls,{style:{background:"#0a0a0a",border:"1px solid #444",color:"#999"},children:this.formatSize(w.size)}),S.jsx(Cn,{size:"small",type:"primary",onClick:x=>{x.stopPropagation(),this.handleOpenLogFile(w.file)},children:he("ui.openLog")})]})]})})})})})()]})]})}}const Gue=VN.createRoot(document.getElementById("root"));Gue.render(S.jsx(que,{}));
|
|
718
|
+
`).filter(u=>u.trim()).map(u=>{try{return JSON.parse(u)}catch{return null}}).filter(Boolean);if(c.length===0){dr.error(he("ui.noLogs")),this.setState({fileLoading:!1,fileLoadingCount:0});return}this.animateLoadingCount(c.length,()=>{let u=[];for(const p of c)yi(p)&&p.body&&Array.isArray(p.body.messages)&&(u=this.mergeMainAgentSessions(u,p));const h=Qo(c);this._isLocalLog=!0,this._localLogFile=i.name,this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.setState({requests:c,selectedIndex:h.length>0?h.length-1:null,mainAgentSessions:u,importModalVisible:!1,fileLoading:!1,fileLoadingCount:0})})}catch{dr.error(he("ui.noLogs")),this.setState({fileLoading:!1,fileLoadingCount:0})}},s.readAsText(i)},n.click()});const r=parseInt(localStorage.getItem("ccv_cacheExpireAt"),10)||null,i=localStorage.getItem("ccv_cacheType")||null,s=Date.now(),o=r&&r>s?r:null,l=o?i:null;this.state={requests:[],selectedIndex:null,viewMode:"raw",currentTab:"request",cacheExpireAt:o,cacheType:l,leftPanelWidth:380,mainAgentSessions:[],importModalVisible:!1,localLogs:{},localLogsLoading:!1,showAll:!1,lang:Yd(),userProfile:null,projectName:"",resumeModalVisible:!1,resumeFileName:"",collapseToolResults:!0,expandThinking:!0,expandDiff:!1,fileLoading:!1,fileLoadingCount:0,selectedLogs:new Set,githubStars:null,cliMode:!1,terminalVisible:!0,workspaceMode:!1},this.eventSource=null,this._autoSelectTimer=null,this.mainContainerRef=J.createRef()}componentDidMount(){fetch(kn("/api/preferences")).then(i=>i.json()).then(i=>{i.lang&&(wy(i.lang),this.setState({lang:i.lang})),i.collapseToolResults!==void 0&&this.setState({collapseToolResults:!!i.collapseToolResults}),i.expandThinking!==void 0&&this.setState({expandThinking:!!i.expandThinking}),i.expandDiff!==void 0&&this.setState({expandDiff:!!i.expandDiff});const s=i.filterIrrelevant!==void 0?!!i.filterIrrelevant:!0;this.setState({showAll:!s})}).catch(()=>{}),fetch(kn("/api/user-profile")).then(i=>i.json()).then(i=>this.setState({userProfile:i})).catch(()=>{}),fetch(kn("/api/project-name")).then(i=>i.json()).then(i=>this.setState({projectName:i.projectName||""})).catch(()=>{}),fetch("https://api.github.com/repos/weiesky/cc-viewer").then(i=>i.json()).then(i=>{i.stargazers_count!=null&&this.setState({githubStars:i.stargazers_count})}).catch(()=>{}),fetch(kn("/api/cli-mode")).then(i=>i.json()).then(i=>{i.workspaceMode?this.setState({cliMode:!0,workspaceMode:!0,isWorkspaceServer:!0}):i.cliMode&&this.setState({cliMode:!0,viewMode:"chat"})}).catch(()=>{});const r=new URLSearchParams(window.location.search).get("logfile");r?this.loadLocalLogFile(r):this.initSSE()}componentWillUnmount(){this.eventSource&&this.eventSource.close(),this._autoSelectTimer&&clearTimeout(this._autoSelectTimer),this._loadingCountTimer&&cancelAnimationFrame(this._loadingCountTimer)}animateLoadingCount(n,r){this._loadingCountTimer&&(cancelAnimationFrame(this._loadingCountTimer),this._loadingCountTimer=null);const i=Math.min(800,Math.max(300,n*.5)),s=performance.now(),o=l=>{const c=Math.min((l-s)/i,1),u=Math.round(c*n);this.setState({fileLoadingCount:u}),c<1?this._loadingCountTimer=requestAnimationFrame(o):(this._loadingCountTimer=null,r())};this._loadingCountTimer=requestAnimationFrame(o)}initSSE(){this.setState({fileLoading:!0,fileLoadingCount:0});try{this.eventSource=new EventSource(kn("/events")),this.eventSource.onmessage=n=>this.handleEventMessage(n),this.eventSource.addEventListener("resume_prompt",n=>{try{const r=JSON.parse(n.data);this.setState({resumeModalVisible:!0,resumeFileName:r.recentFileName||""})}catch{}}),this.eventSource.addEventListener("resume_resolved",()=>{this.setState({resumeModalVisible:!1,resumeFileName:""})}),this.eventSource.addEventListener("update_completed",n=>{try{const r=JSON.parse(n.data);this.setState({updateInfo:{type:"completed",version:r.version}})}catch{}}),this.eventSource.addEventListener("update_major_available",n=>{try{const r=JSON.parse(n.data);this.setState({updateInfo:{type:"major",version:r.version}})}catch{}}),this.eventSource.addEventListener("full_reload",n=>{try{const r=JSON.parse(n.data);if(Array.isArray(r)){this.assignMessageTimestamps(r);const i=this.buildSessionsFromEntries(r),s=Qo(r);r.length>0?this.animateLoadingCount(r.length,()=>{this.setState({requests:r,selectedIndex:s.length>0?s.length-1:null,mainAgentSessions:i,fileLoading:!1,fileLoadingCount:0})}):this.setState({requests:r,selectedIndex:null,mainAgentSessions:i,fileLoading:!1,fileLoadingCount:0})}else this.setState({fileLoading:!1,fileLoadingCount:0})}catch{this.setState({fileLoading:!1,fileLoadingCount:0})}}),this.eventSource.addEventListener("workspace_started",n=>{try{const r=JSON.parse(n.data);this._loadingCountTimer&&(cancelAnimationFrame(this._loadingCountTimer),this._loadingCountTimer=null),this.setState({workspaceMode:!1,projectName:r.projectName||"",viewMode:"chat",cliMode:!0,requests:[],mainAgentSessions:[],selectedIndex:null})}catch{}}),this.eventSource.addEventListener("workspace_stopped",()=>{this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null})}),this.eventSource.onerror=()=>console.error("SSE连接错误")}catch(n){console.error("EventSource初始化失败:",n),this.setState({fileLoading:!1,fileLoadingCount:0})}}loadLocalLogFile(n){this._isLocalLog=!0,this._localLogFile=n,this.setState({fileLoading:!0,fileLoadingCount:0}),fetch(`/api/local-log?file=${encodeURIComponent(n)}`).then(r=>{if(!r.ok)return r.text().then(s=>{throw new Error(`HTTP ${r.status}: ${s}`)});const i=r.headers.get("content-type");return!i||!i.includes("application/json")?r.text().then(s=>{throw new Error(`Invalid content type: ${i}. Response: ${s.substring(0,100)}`)}):r.json()}).then(r=>{Array.isArray(r)?this.animateLoadingCount(r.length,()=>{this.assignMessageTimestamps(r);const i=this.buildSessionsFromEntries(r),s=Qo(r);this.setState({requests:r,selectedIndex:s.length>0?s.length-1:null,mainAgentSessions:i,fileLoading:!1,fileLoadingCount:0})}):this.setState({fileLoading:!1,fileLoadingCount:0})}).catch(r=>{console.error("加载日志文件失败:",r),this.setState({fileLoading:!1,fileLoadingCount:0})})}handleEventMessage(n){try{const r=JSON.parse(n.data);this.setState(i=>{var p,m;const s=[...i.requests],o=s.findIndex(v=>v.timestamp===r.timestamp&&v.url===r.url);o>=0?s[o]=r:s.push(r);let l=i.cacheExpireAt,c=i.cacheType;if(yi(r)){const v=(m=(p=r.response)==null?void 0:p.body)==null?void 0:m.usage;if(v!=null&&v.cache_creation){const _=v.cache_creation,b=r.timestamp?new Date(r.timestamp).getTime():Date.now();let y=null,w=null;if(_.ephemeral_1h_input_tokens>0?(y=b+3600*1e3,w="1h"):_.ephemeral_5m_input_tokens>0&&(y=b+300*1e3,w="5m"),y&&y>Date.now()){l=y;const x=(v.cache_read_input_tokens||0)+(v.cache_creation_input_tokens||0);c=x>0?zr(x):w,localStorage.setItem("ccv_cacheExpireAt",String(l)),localStorage.setItem("ccv_cacheType",c)}}}let u=i.mainAgentSessions;if(yi(r)&&r.body&&Array.isArray(r.body.messages)){const v=r.timestamp||new Date().toISOString(),_=u.length>0?u[u.length-1]:null,b=(_==null?void 0:_.messages)||[],y=r.body.messages,w=b.length,x=w>0&&y.length<w*.5&&w-y.length>4;for(let E=0;E<y.length;E++)!x&&E<w&&b[E]._timestamp?y[E]._timestamp=b[E]._timestamp:y[E]._timestamp||(y[E]._timestamp=v);u=this.mergeMainAgentSessions(i.mainAgentSessions,r)}return i.selectedIndex===null&&s.length>0&&(this._autoSelectTimer&&clearTimeout(this._autoSelectTimer),this._autoSelectTimer=setTimeout(()=>{this.setState(v=>{if(v.selectedIndex===null&&v.requests.length>0){const _=v.showAll?v.requests:Qo(v.requests);return _.length>0?{selectedIndex:_.length-1}:null}return null})},200)),{requests:s,cacheExpireAt:l,cacheType:c,mainAgentSessions:u}})}catch(r){console.error("处理事件消息失败:",r)}}assignMessageTimestamps(n){var s;let r=[],i=null;for(const o of n){if(!yi(o)||!o.body||!Array.isArray(o.body.messages))continue;const l=o.body.messages,c=l.length,u=((s=o.body.metadata)==null?void 0:s.user_id)||null,h=o.timestamp||new Date().toISOString(),p=r.length;p>0&&(c<p*.5&&p-c>4||i&&u&&u!==i)&&(r=[]);for(let v=r.length;v<c;v++)r.push(h);for(let v=0;v<c;v++)l[v]._timestamp=r[v];i=u}}buildSessionsFromEntries(n){let r=[];for(const i of n)yi(i)&&i.body&&Array.isArray(i.body.messages)&&(r=this.mergeMainAgentSessions(r,i));return r}mergeMainAgentSessions(n,r){var p;const i=r.body.messages,s=r.response,o=((p=r.body.metadata)==null?void 0:p.user_id)||null,l=r.timestamp||null;if(n.length===0)return[{userId:o,messages:i,response:s,entryTimestamp:l}];const c=n[n.length-1],u=c.messages?c.messages.length:0,h=u>0&&i.length<u*.5&&u-i.length>4;if(o&&o===c.userId&&!h){const m=[...n];return m[m.length-1]={userId:o,messages:i,response:s,entryTimestamp:l},m}else return[...n,{userId:o,messages:i,response:s,entryTimestamp:l}]}formatTimestamp(n){return!n||n.length<15?n:`${n.slice(0,4)}-${n.slice(4,6)}-${n.slice(6,8)} ${n.slice(9,11)}:${n.slice(11,13)}:${n.slice(13,15)}`}formatSize(n){return n<1024?n+" B":n<1024*1024?(n/1024).toFixed(1)+" KB":(n/(1024*1024)).toFixed(1)+" MB"}render(){const{requests:n,selectedIndex:r,viewMode:i,currentTab:s,cacheExpireAt:o,cacheType:l,leftPanelWidth:c,mainAgentSessions:u,showAll:h,fileLoading:p,fileLoadingCount:m}=this.state,v=h?n:Qo(n),_=r!==null?v[r]:null;if(this.state.workspaceMode)return S.jsx(Vs,{theme:{algorithm:x0.darkAlgorithm,token:{colorBgContainer:"#111",colorBgLayout:"#0a0a0a",colorBgElevated:"#1a1a1a",colorBorder:"#2a2a2a"}},children:S.jsx(sue,{onLaunch:this.handleWorkspaceLaunch})});const b=/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent);return this.state.cliMode&&b?S.jsxs("div",{style:{width:"100vw",height:"100vh",display:"flex",flexDirection:"column",background:"#000"},children:[S.jsxs("div",{style:{padding:"10px 12px",background:"#111",borderBottom:"1px solid #222",display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0},children:[S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[S.jsx(ey,{status:"processing",color:"green"}),S.jsxs("span",{style:{fontSize:12,color:"#aaa"},children:[he("ui.liveMonitoring"),this.state.projectName?`: ${this.state.projectName}`:""]})]}),S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[S.jsx(Cn,{type:"text",size:"small",icon:S.jsx(CR,{}),onClick:()=>this.setState(y=>({mobileGitDiffVisible:!y.mobileGitDiffVisible,mobileChatVisible:!1})),style:{color:this.state.mobileGitDiffVisible?"#fff":"#888",fontSize:12},children:this.state.mobileGitDiffVisible?he("ui.mobileGitDiffExit"):he("ui.mobileGitDiffBrowse")}),S.jsx(Cn,{type:"text",size:"small",icon:S.jsx(wR,{}),onClick:()=>this.setState(y=>({mobileChatVisible:!y.mobileChatVisible,mobileGitDiffVisible:!1})),style:{color:this.state.mobileChatVisible?"#fff":"#888",fontSize:12},children:this.state.mobileChatVisible?he("ui.mobileChatExit"):he("ui.mobileChatBrowse")})]})]}),S.jsxs("div",{style:{flex:1,position:"relative",overflow:"hidden"},children:[S.jsx(bT,{}),S.jsx("div",{className:`${Xt.mobileGitDiffOverlay} ${this.state.mobileGitDiffVisible?Xt.mobileGitDiffOverlayVisible:""}`,children:S.jsx("div",{className:Xt.mobileGitDiffInner,children:S.jsx(eue,{})})}),S.jsx("div",{className:`${Xt.mobileChatOverlay} ${this.state.mobileChatVisible?Xt.mobileChatOverlayVisible:""}`,children:S.jsx(Vs,{theme:{algorithm:x0.darkAlgorithm,token:{colorBgContainer:"#111",colorBgLayout:"#0a0a0a",colorBgElevated:"#1a1a1a",colorBorder:"#2a2a2a"}},children:S.jsx("div",{className:Xt.mobileChatInner,children:S.jsx(s3,{requests:v,mainAgentSessions:u,userProfile:this.state.userProfile,collapseToolResults:this.state.collapseToolResults,expandThinking:this.state.expandThinking,onViewRequest:null,scrollToTimestamp:null,onScrollTsDone:()=>{},cliMode:!1,terminalVisible:!1})})})})]})]}):S.jsxs(Vs,{theme:{algorithm:x0.darkAlgorithm,token:{colorBgContainer:"#111",colorBgLayout:"#0a0a0a",colorBgElevated:"#1a1a1a",colorBorder:"#2a2a2a"}},children:[p&&S.jsx("div",{className:Xt.loadingOverlay,children:S.jsxs("div",{className:Xt.loadingText,children:["Loading...(",m,")"]})}),S.jsxs(Ga,{className:Xt.layout,children:[S.jsx(Ga.Header,{className:Xt.header,children:S.jsx(C1,{requestCount:v.length,requests:v,viewMode:i,cacheExpireAt:o,cacheType:l,onToggleViewMode:this.handleToggleViewMode,onLangChange:this.handleLangChange,onImportLocalLogs:this.handleImportLocalLogs,isLocalLog:!!this._isLocalLog,localLogFile:this._localLogFile,projectName:this.state.projectName,collapseToolResults:this.state.collapseToolResults,onCollapseToolResultsChange:this.handleCollapseToolResultsChange,expandThinking:this.state.expandThinking,onExpandThinkingChange:this.handleExpandThinkingChange,expandDiff:this.state.expandDiff,onExpandDiffChange:this.handleExpandDiffChange,filterIrrelevant:!this.state.showAll,onFilterIrrelevantChange:this.handleFilterIrrelevantChange,updateInfo:this.state.updateInfo,onDismissUpdate:()=>this.setState({updateInfo:null}),cliMode:this.state.cliMode,terminalVisible:this.state.terminalVisible,onToggleTerminal:()=>this.setState(y=>({terminalVisible:!y.terminalVisible})),onReturnToWorkspaces:this.state.cliMode?this.handleReturnToWorkspaces:null})}),S.jsxs(Ga.Content,{className:Xt.content,children:[i==="raw"&&(v.length===0?S.jsx("div",{className:Xt.guideContainer,children:S.jsxs("div",{className:Xt.guideContent,children:[S.jsx("h2",{className:Xt.guideTitle,children:he("ui.guide.title")}),S.jsxs("div",{className:Xt.guideStep,children:[S.jsx("div",{className:Xt.guideStepNum,children:"1"}),S.jsxs("div",{className:Xt.guideStepBody,children:[S.jsx("p",{className:Xt.guideText,children:he("ui.guide.step1")}),S.jsx("code",{className:Xt.guideCode,children:he("ui.guide.exampleQuestion")})]})]}),S.jsxs("div",{className:Xt.guideStep,children:[S.jsx("div",{className:Xt.guideStepNum,children:"2"}),S.jsxs("div",{className:Xt.guideStepBody,children:[S.jsx("p",{className:Xt.guideText,children:he("ui.guide.step2")}),S.jsx("code",{className:Xt.guideCode,children:he("ui.guide.troubleshootCmd")})]})]}),S.jsxs("div",{className:Xt.guideStep,children:[S.jsx("div",{className:Xt.guideStepNum,children:"3"}),S.jsxs("div",{className:Xt.guideStepBody,children:[S.jsx("p",{className:Xt.guideText,children:he("ui.guide.step3")}),S.jsx("code",{className:Xt.guideCode,children:"npm install -g @anthropic-ai/claude-code"})]})]})]})}):S.jsxs("div",{ref:this.mainContainerRef,className:Xt.mainContainer,children:[S.jsxs("div",{className:Xt.leftPanel,style:{width:c},children:[S.jsxs("div",{className:Xt.leftPanelHeader,children:[S.jsx("span",{children:he("ui.requestList")}),S.jsx("span",{className:Xt.leftPanelCount,children:he("ui.totalRequests",{count:v.length})})]}),S.jsx("div",{className:Xt.leftPanelBody,children:S.jsx(CZ,{requests:v,selectedIndex:r,scrollCenter:this.state.scrollCenter,onSelect:this.handleSelectRequest,onScrollDone:()=>this.setState({scrollCenter:!1})})})]}),S.jsx(xce,{onResize:this.handleResize}),S.jsx("div",{className:Xt.rightPanel,children:S.jsx(TJ,{request:_,requests:v,selectedIndex:r,currentTab:s,onTabChange:this.handleTabChange,onViewInChat:this.handleViewInChat,expandDiff:this.state.expandDiff})})]})),S.jsx("div",{style:{display:i==="chat"?"flex":"none",height:"100%",flexDirection:"column"},children:S.jsx(s3,{requests:v,mainAgentSessions:u,userProfile:this.state.userProfile,collapseToolResults:this.state.collapseToolResults,expandThinking:this.state.expandThinking,onViewRequest:this.handleViewRequest,scrollToTimestamp:this.state.chatScrollToTs,onScrollTsDone:()=>this.setState({chatScrollToTs:null}),cliMode:this.state.cliMode,terminalVisible:this.state.terminalVisible})})]}),S.jsx("div",{className:Xt.footer,children:S.jsxs("div",{className:Xt.footerRight,children:[S.jsx("span",{className:Xt.footerText,children:he("ui.footer.starRequest")}),S.jsxs("a",{href:"https://github.com/weiesky/cc-viewer",target:"_blank",rel:"noopener noreferrer",className:Xt.footerLink,children:[S.jsx("svg",{className:Xt.footerIcon,viewBox:"0 0 16 16",fill:"currentColor",children:S.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"})}),"GitHub",this.state.githubStars!=null?` ★ ${this.state.githubStars}`:""]}),S.jsx("span",{className:Xt.footerDivider,children:"|"}),S.jsx("a",{href:"dingtalk://dingtalkclient/action/sendmsg?dingtalk_id=sthk5es",className:Xt.footerLink,children:he("ui.footer.contact")})]})})]}),S.jsx(Ci,{title:he("ui.resume.title"),open:this.state.resumeModalVisible,closable:!1,maskClosable:!1,keyboard:!1,footer:[S.jsx(Cn,{type:"primary",onClick:()=>this.handleResumeChoice("continue"),children:he("ui.resume.continue")},"continue"),S.jsx(Cn,{onClick:()=>this.handleResumeChoice("new"),children:he("ui.resume.new")},"new")],children:S.jsx("p",{children:he("ui.resume.message",{file:this.state.resumeFileName})})}),S.jsxs(Ci,{title:he("ui.importLocalLogs"),open:this.state.importModalVisible,onCancel:this.handleCloseImportModal,footer:null,width:1e3,styles:{body:{maxHeight:"60vh",overflow:"auto"}},children:[S.jsxs("div",{className:Xt.modalActions,children:[S.jsx(Cn,{icon:S.jsx(gK,{}),onClick:this.handleLoadLocalJsonlFile,children:he("ui.loadLocalJsonl")}),S.jsx(Cn,{size:"small",type:this.state.selectedLogs.size>1?"primary":"default",disabled:this.state.selectedLogs.size<2,onClick:this.handleMergeLogs,style:{marginLeft:8},children:he("ui.mergeLogs")})]}),this.state.localLogsLoading?S.jsx("div",{className:Xt.spinCenter,children:S.jsx(ua,{})}):(()=>{const y=this.state.localLogs[this.state.currentProject];return!y||y.length===0?S.jsx("div",{className:Xt.emptyCenter,children:he("ui.noLogs")}):S.jsx("div",{className:Xt.logListContainer,children:S.jsx(hu,{size:"small",dataSource:y,renderItem:w=>S.jsx(hu.Item,{className:Xt.logListItem,onClick:()=>{const x=!this.state.selectedLogs.has(w.file);this.handleToggleLogSelect(w.file,x)},children:S.jsxs("div",{className:Xt.logItemRow,children:[S.jsxs("span",{children:[S.jsx(py,{className:Xt.logCheckbox,checked:this.state.selectedLogs.has(w.file)||!1,onClick:x=>x.stopPropagation(),onChange:x=>{x.stopPropagation(),this.handleToggleLogSelect(w.file,x.target.checked)}}),S.jsx(Od,{className:Xt.logFileIcon}),S.jsx("span",{className:Xt.logFileName,children:this.formatTimestamp(w.timestamp)})]}),S.jsxs("span",{children:[S.jsxs(ls,{style:{background:"#0a0a0a",border:"1px solid #444",color:"#999"},children:[w.turns||0," ",he("ui.turns")]}),S.jsx(ls,{style:{background:"#0a0a0a",border:"1px solid #444",color:"#999"},children:this.formatSize(w.size)}),S.jsx(Cn,{size:"small",type:"primary",onClick:x=>{x.stopPropagation(),this.handleOpenLogFile(w.file)},children:he("ui.openLog")})]})]})})})})})()]})]})}}const Gue=VN.createRoot(document.getElementById("root"));Gue.render(S.jsx(que,{}));
|
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-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-DVL4r7pF.js"></script>
|
|
10
10
|
<link rel="stylesheet" crossorigin href="/assets/index-BTtdvNJL.css">
|
|
11
11
|
</head>
|
|
12
12
|
<body>
|
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -521,6 +521,14 @@ async function handleRequest(req, res) {
|
|
|
521
521
|
} catch {}
|
|
522
522
|
});
|
|
523
523
|
|
|
524
|
+
// 发送 full_reload 以刷新会话区域
|
|
525
|
+
const entries = readLogFile();
|
|
526
|
+
clients.forEach(client => {
|
|
527
|
+
try {
|
|
528
|
+
client.write(`event: full_reload\ndata: ${JSON.stringify(entries)}\n\n`);
|
|
529
|
+
} catch {}
|
|
530
|
+
});
|
|
531
|
+
|
|
524
532
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
525
533
|
res.end(JSON.stringify({ ok: true, projectName: result.projectName }));
|
|
526
534
|
} catch (err) {
|