cc-viewer 1.6.3 → 1.6.4
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.
|
@@ -483,7 +483,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
483
483
|
|
|
484
484
|
|
|
485
485
|
|
|
486
|
-
`)],{type:"text/plain;charset=utf-8"}),s=URL.createObjectURL(r),o=document.createElement("a");o.href=s,o.download=`user-prompts-${new Date().toISOString().slice(0,10)}.txt`,o.click(),URL.revokeObjectURL(s)});gt(this,"handleShowProjectStats",()=>{this.setState({projectStatsVisible:!0,projectStatsLoading:!0}),fetch(Rn("/api/project-stats")).then(n=>{if(!n.ok)throw new Error("not found");return n.json()}).then(n=>this.setState({projectStats:n,projectStatsLoading:!1})).catch(()=>this.setState({projectStats:null,projectStatsLoading:!1}))});gt(this,"fetchPlugins",()=>fetch(Rn("/api/plugins")).then(n=>{if(!n.ok)throw new Error(n.status);return n.json()}).then(n=>{this.setState({pluginsList:n.plugins||[],pluginsDir:n.pluginsDir||""})}).catch(()=>{}));gt(this,"handleShowPlugins",()=>{this.setState({pluginModalVisible:!0}),this.fetchPlugins()});gt(this,"handleTogglePlugin",(n,i)=>{fetch(Rn("/api/preferences")).then(r=>r.json()).then(r=>{let s=Array.isArray(r.disabledPlugins)?[...r.disabledPlugins]:[];return i?s=s.filter(o=>o!==n):s.includes(n)||s.push(n),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabledPlugins:s})})}).then(()=>fetch(Rn("/api/plugins/reload"),{method:"POST"})).then(r=>{if(!r.ok)throw new Error(r.status);return r.json()}).then(r=>{this.setState({pluginsList:r.plugins||[],pluginsDir:r.pluginsDir||""})}).catch(()=>{})});gt(this,"handleDeletePlugin",(n,i)=>{this.setState({deleteConfirmVisible:!0,deleteTarget:{file:n,name:i}})});gt(this,"handleDeletePluginConfirm",()=>{const{file:n}=this.state.deleteTarget||{};n&&(this.setState({deleteConfirmVisible:!1,deleteTarget:null}),fetch(Rn(`/api/plugins?file=${encodeURIComponent(n)}`),{method:"DELETE"}).then(i=>{if(!i.ok)throw new Error(i.status);return i.json()}).then(i=>{i.plugins&&this.setState({pluginsList:i.plugins,pluginsDir:i.pluginsDir||""})}).catch(()=>{}))});gt(this,"handleReloadPlugins",()=>{fetch(Rn("/api/plugins/reload"),{method:"POST"}).then(n=>{if(!n.ok)throw new Error(n.status);return n.json()}).then(n=>{this.setState({pluginsList:n.plugins||[],pluginsDir:n.pluginsDir||""})}).catch(()=>{})});gt(this,"handleAddPlugin",()=>{const n=document.createElement("input");n.type="file",n.accept=".js,.mjs",n.multiple=!0,n.onchange=()=>{const i=n.files;if(!i||i.length===0)return;for(const s of i)if(!s.name.endsWith(".js")&&!s.name.endsWith(".mjs")){ei.error(re("ui.plugins.invalidFile"));return}const r=Array.from(i).map(s=>new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o({name:s.name,content:l.result}),l.onerror=()=>a(new Error(`Failed to read ${s.name}`)),l.readAsText(s)}));Promise.all(r).then(s=>fetch(Rn("/api/plugins/upload"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:s})})).then(s=>s.ok?s.json():s.text().then(o=>{try{return JSON.parse(o)}catch{throw new Error(re("ui.plugins.serverError",{status:s.status}))}})).then(s=>{s.error?ei.error(re("ui.plugins.addFailed",{reason:s.error})):s.plugins&&(this.setState({pluginsList:s.plugins,pluginsDir:s.pluginsDir||""}),ei.success(re("ui.plugins.addSuccess")))}).catch(s=>{ei.error(s.message)})},n.click()});gt(this,"fetchProcesses",()=>{this.setState({processLoading:!0}),fetch(Rn("/api/ccv-processes")).then(n=>n.json()).then(n=>{this.setState({processList:n.processes||[],processLoading:!1})}).catch(()=>{this.setState({processList:[],processLoading:!1})})});gt(this,"handleShowProcesses",()=>{this.setState({processModalVisible:!0}),this.fetchProcesses()});gt(this,"handleKillProcess",n=>{Tr.confirm({title:re("ui.processManagement.killConfirm"),onOk:()=>{fetch(Rn("/api/ccv-processes/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:n})}).then(i=>i.json()).then(i=>{i.ok?(ei.success(re("ui.processManagement.killed")),this.fetchProcesses()):ei.error(i.error||re("ui.processManagement.killFailed"))}).catch(()=>{ei.error(re("ui.processManagement.killFailed"))})}})});this.state={countdownText:"",promptModalVisible:!1,promptData:[],promptViewMode:"original",settingsDrawerVisible:!1,globalSettingsVisible:!1,projectStatsVisible:!1,projectStats:null,projectStatsLoading:!1,localUrl:"",pluginModalVisible:!1,pluginsList:[],pluginsDir:"",deleteConfirmVisible:!1,deleteTarget:null,processModalVisible:!1,processList:[],processLoading:!1,logoDropdownOpen:!1,cacheHighlightIdx:null,cacheHighlightFading:!1},this._rafId=null,this._expiredTimer=null,this.updateCountdown=this.updateCountdown.bind(this)}componentDidMount(){this.startCountdown(),fetch(Rn("/api/local-url")).then(n=>n.json()).then(n=>{n.url&&this.setState({localUrl:n.url})}).catch(()=>{})}componentDidUpdate(n){n.cacheExpireAt!==this.props.cacheExpireAt&&this.startCountdown()}shouldComponentUpdate(n,i){return n.requestCount!==this.props.requestCount||n.viewMode!==this.props.viewMode||n.cacheExpireAt!==this.props.cacheExpireAt||n.cacheType!==this.props.cacheType||n.isLocalLog!==this.props.isLocalLog||n.projectName!==this.props.projectName||n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking||n.expandDiff!==this.props.expandDiff||n.filterIrrelevant!==this.props.filterIrrelevant||n.cliMode!==this.props.cliMode||n.contextWindow!==this.props.contextWindow||i!==this.state}componentWillUnmount(){this._rafId&&cancelAnimationFrame(this._rafId),this._expiredTimer&&clearTimeout(this._expiredTimer),this._cacheFadeClearTimer&&clearTimeout(this._cacheFadeClearTimer),this._cacheUnbindScrollFade()}startCountdown(){if(this._rafId&&cancelAnimationFrame(this._rafId),this._expiredTimer&&clearTimeout(this._expiredTimer),!this.props.cacheExpireAt){this.setState({countdownText:""});return}this._rafId=requestAnimationFrame(this.updateCountdown)}updateCountdown(){const{cacheExpireAt:n}=this.props;if(!n){this.setState({countdownText:""});return}const i=Math.max(0,n-Date.now());if(i<=0){this.setState({countdownText:re("ui.cacheExpired")}),this._expiredTimer=setTimeout(()=>{this.setState({countdownText:""})},5e3);return}const r=Math.ceil(i/1e3);let s;if(r>=60){const o=Math.floor(r/60),a=r%60;s=re("ui.minuteSecond",{m:o,s:String(a).padStart(2,"0")})}else s=re("ui.second",{s:r});this.setState({countdownText:s}),this._rafId=requestAnimationFrame(this.updateCountdown)}static parseSegments(n){const i=[],r=/<([a-zA-Z_][\w-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>/g;let s=0,o;for(;(o=r.exec(n))!==null;){const l=n.slice(s,o.index).trim();l&&i.push({type:"text",content:l});const c=o[1];if(s=o.index+o[0].length,Sd.COMMAND_TAGS.has(c))continue;const u=new RegExp(`^<${c}(?:\\s[^>]*)?>([\\s\\S]*)<\\/${c}>$`),d=o[0].match(u),O=d?d[1].trim():o[0].trim();i.push({type:"system",content:O,label:c})}const a=n.slice(s).trim();return a&&i.push({type:"text",content:a}),i}static extractUserTexts(n){const i=[],r=[];let s=null;for(const o of n)if(o.role==="user"){if(typeof o.content=="string"){const a=o.content.trim();if(!a)continue;if(!Qu(a)){if(/^Implement the following plan:/i.test(a))continue;i.push(a),r.push(a)}}else if(Array.isArray(o.content)){const{commands:a,textBlocks:l}=aT(o.content);a.length>0&&(s=a[a.length-1]);const c=[];for(const d of l)/^Implement the following plan:/i.test((d.text||"").trim())||c.push(d.text.trim());const u=o.content.filter(d=>{var O;return d.type==="text"&&((O=d.text)==null?void 0:O.trim())}).map(d=>d.text.trim());c.length>0&&(i.push(c.join(`
|
|
486
|
+
`)],{type:"text/plain;charset=utf-8"}),s=URL.createObjectURL(r),o=document.createElement("a");o.href=s,o.download=`user-prompts-${new Date().toISOString().slice(0,10)}.txt`,o.click(),URL.revokeObjectURL(s)});gt(this,"handleShowProjectStats",()=>{this.setState({projectStatsVisible:!0,projectStatsLoading:!0}),fetch(Rn("/api/project-stats")).then(n=>{if(!n.ok)throw new Error("not found");return n.json()}).then(n=>this.setState({projectStats:n,projectStatsLoading:!1})).catch(()=>this.setState({projectStats:null,projectStatsLoading:!1}))});gt(this,"fetchPlugins",()=>fetch(Rn("/api/plugins")).then(n=>{if(!n.ok)throw new Error(n.status);return n.json()}).then(n=>{this.setState({pluginsList:n.plugins||[],pluginsDir:n.pluginsDir||""})}).catch(()=>{}));gt(this,"handleShowPlugins",()=>{this.setState({pluginModalVisible:!0}),this.fetchPlugins()});gt(this,"handleTogglePlugin",(n,i)=>{fetch(Rn("/api/preferences")).then(r=>r.json()).then(r=>{let s=Array.isArray(r.disabledPlugins)?[...r.disabledPlugins]:[];return i?s=s.filter(o=>o!==n):s.includes(n)||s.push(n),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabledPlugins:s})})}).then(()=>fetch(Rn("/api/plugins/reload"),{method:"POST"})).then(r=>{if(!r.ok)throw new Error(r.status);return r.json()}).then(r=>{this.setState({pluginsList:r.plugins||[],pluginsDir:r.pluginsDir||""})}).catch(()=>{})});gt(this,"handleDeletePlugin",(n,i)=>{this.setState({deleteConfirmVisible:!0,deleteTarget:{file:n,name:i}})});gt(this,"handleDeletePluginConfirm",()=>{const{file:n}=this.state.deleteTarget||{};n&&(this.setState({deleteConfirmVisible:!1,deleteTarget:null}),fetch(Rn(`/api/plugins?file=${encodeURIComponent(n)}`),{method:"DELETE"}).then(i=>{if(!i.ok)throw new Error(i.status);return i.json()}).then(i=>{i.plugins&&this.setState({pluginsList:i.plugins,pluginsDir:i.pluginsDir||""})}).catch(()=>{}))});gt(this,"handleReloadPlugins",()=>{fetch(Rn("/api/plugins/reload"),{method:"POST"}).then(n=>{if(!n.ok)throw new Error(n.status);return n.json()}).then(n=>{this.setState({pluginsList:n.plugins||[],pluginsDir:n.pluginsDir||""})}).catch(()=>{})});gt(this,"handleAddPlugin",()=>{const n=document.createElement("input");n.type="file",n.accept=".js,.mjs",n.multiple=!0,n.onchange=()=>{const i=n.files;if(!i||i.length===0)return;for(const s of i)if(!s.name.endsWith(".js")&&!s.name.endsWith(".mjs")){ei.error(re("ui.plugins.invalidFile"));return}const r=Array.from(i).map(s=>new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o({name:s.name,content:l.result}),l.onerror=()=>a(new Error(`Failed to read ${s.name}`)),l.readAsText(s)}));Promise.all(r).then(s=>fetch(Rn("/api/plugins/upload"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:s})})).then(s=>s.ok?s.json():s.text().then(o=>{try{return JSON.parse(o)}catch{throw new Error(re("ui.plugins.serverError",{status:s.status}))}})).then(s=>{s.error?ei.error(re("ui.plugins.addFailed",{reason:s.error})):s.plugins&&(this.setState({pluginsList:s.plugins,pluginsDir:s.pluginsDir||""}),ei.success(re("ui.plugins.addSuccess")))}).catch(s=>{ei.error(s.message)})},n.click()});gt(this,"fetchProcesses",()=>{this.setState({processLoading:!0}),fetch(Rn("/api/ccv-processes")).then(n=>n.json()).then(n=>{this.setState({processList:n.processes||[],processLoading:!1})}).catch(()=>{this.setState({processList:[],processLoading:!1})})});gt(this,"handleShowProcesses",()=>{this.setState({processModalVisible:!0}),this.fetchProcesses()});gt(this,"handleKillProcess",n=>{Tr.confirm({title:re("ui.processManagement.killConfirm"),onOk:()=>{fetch(Rn("/api/ccv-processes/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:n})}).then(i=>i.json()).then(i=>{i.ok?(ei.success(re("ui.processManagement.killed")),this.fetchProcesses()):ei.error(i.error||re("ui.processManagement.killFailed"))}).catch(()=>{ei.error(re("ui.processManagement.killFailed"))})}})});this.state={countdownText:"",promptModalVisible:!1,promptData:[],promptViewMode:"original",settingsDrawerVisible:!1,globalSettingsVisible:!1,projectStatsVisible:!1,projectStats:null,projectStatsLoading:!1,localUrl:"",pluginModalVisible:!1,pluginsList:[],pluginsDir:"",deleteConfirmVisible:!1,deleteTarget:null,processModalVisible:!1,processList:[],processLoading:!1,logoDropdownOpen:!1,cacheHighlightIdx:null,cacheHighlightFading:!1},this._rafId=null,this._expiredTimer=null,this.updateCountdown=this.updateCountdown.bind(this)}componentDidMount(){this.startCountdown(),fetch(Rn("/api/local-url")).then(n=>n.json()).then(n=>{n.url&&this.setState({localUrl:n.url})}).catch(()=>{})}componentDidUpdate(n){n.cacheExpireAt!==this.props.cacheExpireAt&&this.startCountdown()}shouldComponentUpdate(n,i){return n.requests!==this.props.requests||n.requestCount!==this.props.requestCount||n.viewMode!==this.props.viewMode||n.cacheExpireAt!==this.props.cacheExpireAt||n.cacheType!==this.props.cacheType||n.isLocalLog!==this.props.isLocalLog||n.projectName!==this.props.projectName||n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking||n.expandDiff!==this.props.expandDiff||n.filterIrrelevant!==this.props.filterIrrelevant||n.cliMode!==this.props.cliMode||n.contextWindow!==this.props.contextWindow||i!==this.state}componentWillUnmount(){this._rafId&&cancelAnimationFrame(this._rafId),this._expiredTimer&&clearTimeout(this._expiredTimer),this._cacheFadeClearTimer&&clearTimeout(this._cacheFadeClearTimer),this._cacheUnbindScrollFade()}startCountdown(){if(this._rafId&&cancelAnimationFrame(this._rafId),this._expiredTimer&&clearTimeout(this._expiredTimer),!this.props.cacheExpireAt){this.setState({countdownText:""});return}this._rafId=requestAnimationFrame(this.updateCountdown)}updateCountdown(){const{cacheExpireAt:n}=this.props;if(!n){this.setState({countdownText:""});return}const i=Math.max(0,n-Date.now());if(i<=0){this.setState({countdownText:re("ui.cacheExpired")}),this._expiredTimer=setTimeout(()=>{this.setState({countdownText:""})},5e3);return}const r=Math.ceil(i/1e3);let s;if(r>=60){const o=Math.floor(r/60),a=r%60;s=re("ui.minuteSecond",{m:o,s:String(a).padStart(2,"0")})}else s=re("ui.second",{s:r});this.setState({countdownText:s}),this._rafId=requestAnimationFrame(this.updateCountdown)}static parseSegments(n){const i=[],r=/<([a-zA-Z_][\w-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>/g;let s=0,o;for(;(o=r.exec(n))!==null;){const l=n.slice(s,o.index).trim();l&&i.push({type:"text",content:l});const c=o[1];if(s=o.index+o[0].length,Sd.COMMAND_TAGS.has(c))continue;const u=new RegExp(`^<${c}(?:\\s[^>]*)?>([\\s\\S]*)<\\/${c}>$`),d=o[0].match(u),O=d?d[1].trim():o[0].trim();i.push({type:"system",content:O,label:c})}const a=n.slice(s).trim();return a&&i.push({type:"text",content:a}),i}static extractUserTexts(n){const i=[],r=[];let s=null;for(const o of n)if(o.role==="user"){if(typeof o.content=="string"){const a=o.content.trim();if(!a)continue;if(!Qu(a)){if(/^Implement the following plan:/i.test(a))continue;i.push(a),r.push(a)}}else if(Array.isArray(o.content)){const{commands:a,textBlocks:l}=aT(o.content);a.length>0&&(s=a[a.length-1]);const c=[];for(const d of l)/^Implement the following plan:/i.test((d.text||"").trim())||c.push(d.text.trim());const u=o.content.filter(d=>{var O;return d.type==="text"&&((O=d.text)==null?void 0:O.trim())}).map(d=>d.text.trim());c.length>0&&(i.push(c.join(`
|
|
487
487
|
`)),r.push(u.join(`
|
|
488
488
|
`)))}}return{userMsgs:i,fullTexts:r,slashCmd:s}}extractUserPrompts(){var a;const{requests:n=[]}=this.props,i=[],r=new Set;let s=null;const o=n.filter(l=>wr(l));for(let l=0;l<o.length;l++){const c=o[l],u=((a=c.body)==null?void 0:a.messages)||[],d=c.timestamp||"",{userMsgs:O,fullTexts:p,slashCmd:g}=Sd.extractUserTexts(u);g&&g!=="/compact"&&g!==s&&i.push({type:"prompt",segments:[{type:"text",content:g}],timestamp:d}),s=g;for(let v=0;v<O.length;v++){const $=O[v];if(r.has($))continue;r.add($);const S=p[v]||$;i.push({type:"prompt",segments:Sd.parseSegments(S),timestamp:d})}}return i}renderTokenStats(){const{requests:n=[]}=this.props,i=DW(n),r=Object.keys(i),s=ZW(n),o=FW(n);if(r.length===0&&s.length===0)return y.jsx("div",{className:se.tokenStatsEmpty,children:"暂无 token 数据"});const a=y.jsx("div",{className:se.tokenStatsColumn,children:r.map(d=>{const O=i[d],p=O.input+O.cacheCreation+O.cacheRead,g=p>0?(O.cacheRead/p*100).toFixed(1):"0.0";return y.jsxs("div",{className:r.length>1?se.modelCardSpaced:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:d}),y.jsx("table",{className:se.statsTable,children:y.jsxs("tbody",{children:[y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:"Token"}),y.jsx("td",{className:se.th,children:"input"}),y.jsx("td",{className:se.th,children:"output"})]}),y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label}),y.jsx("td",{className:se.td,children:$i(p)}),y.jsx("td",{className:se.td,children:$i(O.output)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:"Cache"}),y.jsx("td",{className:se.th,children:"create"}),y.jsx("td",{className:se.th,children:"read"})]}),y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label}),y.jsx("td",{className:se.td,children:$i(O.cacheCreation)}),y.jsx("td",{className:se.td,children:$i(O.cacheRead)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:re("ui.hitRate")}),y.jsxs("td",{colSpan:2,className:se.td,children:[g,"%"]})]})]})})]},d)})}),l=this.renderCacheRebuildStats(),c=s.length>0?y.jsx("div",{className:se.toolStatsColumn,children:y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:re("ui.toolUsageStats")}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"Tool"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[s.map(([d,O])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsxs("td",{className:se.label,children:[d," ",y.jsx(La,{doc:`Tool-${d}`})]}),y.jsx("td",{className:se.td,children:O})]},d)),s.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:s.reduce((d,O)=>d+O[1],0)})]})]})]})]})}):null,u=o.length>0?y.jsx("div",{className:se.toolStatsColumn,children:y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:re("ui.skillUsageStats")}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"Skill"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[o.map(([d,O])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label,children:d}),y.jsx("td",{className:se.td,children:O})]},d)),o.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:o.reduce((d,O)=>d+O[1],0)})]})]})]})]})}):null;return y.jsxs("div",{className:se.tokenStatsContainer,children:[a,l,c,u]})}_cacheUnbindScrollFade(){this._cacheOnScrollFade&&this._cacheScrollEl&&(this._cacheScrollEl.removeEventListener("scroll",this._cacheOnScrollFade),this._cacheOnScrollFade=null)}_cacheBindScrollFade(){this._cacheUnbindScrollFade();const n=this._cacheScrollEl;n&&(this._cacheOnScrollFade=()=>{clearTimeout(this._cacheAutoFadeTimer),this.setState({cacheHighlightFading:!0}),this._cacheFadeClearTimer=setTimeout(()=>{this.setState({cacheHighlightIdx:null,cacheHighlightFading:!1})},3e3),this._cacheUnbindScrollFade()},n.addEventListener("scroll",this._cacheOnScrollFade,{passive:!0}))}scrollToCacheMsg(n){this.props.viewMode==="raw"&&this.props.onNavigateCacheMsg&&this.props.onNavigateCacheMsg(n);const i=this._cacheScrollEl;if(!i)return;const r=i.querySelector(`[data-msg-idx="${n}"]`);if(!r)return;clearTimeout(this._cacheScrollSettleTimer),clearTimeout(this._cacheFadeClearTimer),clearTimeout(this._cacheAutoFadeTimer),clearTimeout(this._cacheHighlightDelayTimer),this._cacheUnbindScrollFade(),this._cacheScrollEndHandler&&i.removeEventListener("scrollend",this._cacheScrollEndHandler),this.setState({cacheHighlightIdx:null,cacheHighlightFading:!1});let s=!1,o=!1;const a=()=>{!s||!o||(this.setState({cacheHighlightIdx:n,cacheHighlightFading:!1}),this._cacheScrollSettleTimer=setTimeout(()=>this._cacheBindScrollFade(),200),this._cacheAutoFadeTimer=setTimeout(()=>{this.state.cacheHighlightIdx===n&&!this.state.cacheHighlightFading&&(this.setState({cacheHighlightFading:!0}),this._cacheFadeClearTimer=setTimeout(()=>{this.setState({cacheHighlightIdx:null,cacheHighlightFading:!1})},3e3),this._cacheUnbindScrollFade())},3e3))};this._cacheScrollEndHandler=()=>{i.removeEventListener("scrollend",this._cacheScrollEndHandler),s=!0,a()},i.addEventListener("scrollend",this._cacheScrollEndHandler,{once:!0}),this._cacheScrollSettleTimer=setTimeout(()=>{i.removeEventListener("scrollend",this._cacheScrollEndHandler),s=!0,a()},800),this._cacheHighlightDelayTimer=setTimeout(()=>{o=!0,a()},500),r.scrollIntoView({behavior:"smooth",block:"center"})}renderCacheContentPopover(n){const{requests:i=[],serverCachedContent:r}=this.props,s=r||GW(i);if(!s||s.system.length===0&&s.messages.length===0&&s.tools.length===0)return y.jsx("div",{className:se.cachePopoverEmpty,children:re("ui.noCachedContent")});const o=(u,d,O)=>{if(d.length===0)return null;const p=u===re("ui.messages");return y.jsxs("div",{className:se.cacheSection,children:[y.jsxs("div",{className:se.cacheSectionTitle,children:[u," (",d.length,")"]}),d.map((g,v)=>{const $=p?{"data-msg-idx":v}:{};let S=O||se.cacheCodeBlock;const _=p&&v===this.state.cacheHighlightIdx;return _&&(S+=" "+(this.state.cacheHighlightFading?se.cacheBlockHighlightFading:se.cacheBlockHighlight)),y.jsxs("pre",{className:S,...$,style:_?{position:"relative"}:void 0,children:[_&&y.jsx("svg",{className:`${se.cacheBorderSvg}${this.state.cacheHighlightFading?" "+se.cacheBorderSvgFading:""}`,preserveAspectRatio:"none",children:y.jsx("rect",{x:"0.5",y:"0.5",width:"calc(100% - 1px)",height:"calc(100% - 1px)",rx:"4",ry:"4",fill:"none",stroke:"#1668dc",strokeWidth:"1",strokeDasharray:"6 4",className:se.cacheBorderRect})}),g]},v)})]})},a=()=>{const u=[];return s.system.length>0&&(u.push(`=== ${re("ui.systemPrompt")} (${s.system.length}) ===`),s.system.forEach(d=>u.push(d))),s.messages.length>0&&(u.push(`
|
|
489
489
|
=== ${re("ui.messages")} (${s.messages.length}) ===`),s.messages.forEach(d=>u.push(d))),s.tools.length>0&&(u.push(`
|
|
@@ -930,7 +930,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),Tn=Pe,Jt=Fe),pt===void
|
|
|
930
930
|
`),lineNums:$}}}}}else if(u.role==="assistant"&&Array.isArray(u.content)){for(const d of u.content)if(d.type==="tool_use"&&d.name==="Edit"&&d.input){const O=d.input.file_path,p=d.input.old_string,g=d.input.new_string;if(O&&p!=null&&g!=null&&s[O]){const v=s[O];r[d.id]={plainText:v.plainText,lineNums:v.lineNums.slice()};const $=v.plainText.indexOf(p);if($>=0){const _=v.plainText.substring(0,$).split(`
|
|
931
931
|
`).length-1,x=p.split(`
|
|
932
932
|
`).length,Q=g.split(`
|
|
933
|
-
`).length,w=Q-x;if(v.plainText=v.plainText.substring(0,$)+g+v.plainText.substring($+p.length),w!==0){const C=v.lineNums[_]||_+1,T=[];for(let z=0;z<Q;z++)T.push(C+z);v.lineNums=[...v.lineNums.slice(0,_),...T,...v.lineNums.slice(_+x).map(z=>z+w)]}}}}}const o={},a={};for(const u of t)if(u.role==="user"&&Array.isArray(u.content)){for(const d of u.content)if(d.type==="tool_result"){const O=e[d.tool_use_id];if(O&&O.name==="AskUserQuestion"){const p=Ep(d);o[d.tool_use_id]=OYe(p)}if(O&&O.name==="ExitPlanMode"){const p=Ep(d);a[d.tool_use_id]=fYe(p)}}}return{toolUseMap:e,toolResultMap:n,readContentMap:i,editSnapshotMap:r,askAnswerMap:o,planApprovalMap:a}}function OYe(t){const e={},n=/"([^"]+)"="([^"]*)"/g;let i;for(;(i=n.exec(t))!==null;)e[i[1]]=i[2];return e}function fYe(t){if(!t)return{status:"pending"};if(/User has approved/i.test(t))return{status:"approved"};if(/User rejected/i.test(t)){const e=t.match(/feedback:\s*(.+)/i)||t.match(/User rejected[^:]*:\s*(.+)/i);return{status:"rejected",feedback:e?e[1].trim():""}}return{status:"pending"}}class C9 extends ne.Component{constructor(n){super(n);gt(this,"handleStickToBottom",()=>{this.setState({stickyBottom:!0},()=>{const n=this.containerRef.current;n&&(n.scrollTop=n.scrollHeight)})});gt(this,"handleLoadMore",()=>{this._mobileExtraItems+=dYe;const n=this.containerRef.current,i=n?n.scrollHeight:0,r=n?n.scrollTop:0,s=this.buildAllItems(),o=this._applyMobileSlice(s);this.setState({allItems:o,visibleCount:o.length},()=>{if(n){const a=n.scrollHeight;n.scrollTop=r+(a-i)}})});gt(this,"handlePromptOptionClick",n=>{const i=this._inputWs;if(!i||i.readyState!==WebSocket.OPEN)return;const r=this.state.ptyPrompt;if(!r)return;const s=r.options,o=s.findIndex(O=>O.number===n);let a=s.findIndex(O=>O.selected);a<0&&(a=0);const l=o-a,c=l>0?"\x1B[B":"\x1B[A",u=Math.abs(l),d=O=>{O<u?(i.send(JSON.stringify({type:"input",data:c})),setTimeout(()=>d(O+1),30)):setTimeout(()=>{i.readyState===WebSocket.OPEN&&i.send(JSON.stringify({type:"input",data:"\r"}))},50)};d(0),this._currentPtyPrompt=null,this.setState(O=>{const p=O.ptyPromptHistory.slice(),g=p[p.length-1];return g&&g.status==="active"&&(p[p.length-1]={...g,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:p}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});gt(this,"handlePlanFeedbackSubmit",(n,i)=>{const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN)return;const s=this.state.ptyPrompt;if(!s)return;const o=s.options,a=o.findIndex(p=>p.number===n);let l=o.findIndex(p=>p.selected);l<0&&(l=0);const c=a-l,u=c>0?"\x1B[B":"\x1B[A",d=Math.abs(c),O=p=>{p<d?(r.send(JSON.stringify({type:"input",data:u})),setTimeout(()=>O(p+1),30)):setTimeout(()=>{r.send(JSON.stringify({type:"input",data:"\r"}));const g=this._ptyBuffer;let v=0;const $=()=>{if(v++,v>20||this._ptyBuffer!==g){r.readyState===WebSocket.OPEN&&(r.send(JSON.stringify({type:"input",data:i})),setTimeout(()=>{r.send(JSON.stringify({type:"input",data:"\r"}))},50));return}setTimeout($,100)};setTimeout($,100)},50)};O(0),this._currentPtyPrompt=null,this.setState(p=>{const g=p.ptyPromptHistory.slice(),v=g[g.length-1];return v&&v.status==="active"&&(g[g.length-1]={...v,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:g}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});gt(this,"handleAskQuestionSubmit",n=>{const i=this._inputWs;if(!i||i.readyState!==WebSocket.OPEN){this._askAnswerQueue=this._planSubmissionSteps(n),this._askSubmitting=!0,this.connectInputWs(),this._askWsRetries=0,this._waitForWsAndSubmit();return}if(this._askAnswerQueue=this._planSubmissionSteps(n),this._askSubmitting=!0,!this._currentPtyPrompt){this._askPromptRetries=0,this._waitForPtyPromptAndSubmit();return}this._processNextAskAnswer()});gt(this,"handleInputSend",()=>{const n=this._inputRef.current;if(!n)return;const i=n.value.trim();i&&this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&(this._inputWs.send(JSON.stringify({type:"input",data:i})),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:i,inputSuggestion:null},()=>this.scrollToBottom()))});gt(this,"handleInputKeyDown",n=>{if(n.key==="Tab"&&this.state.inputSuggestion){n.preventDefault();const i=this._inputRef.current;i&&(i.value=this.state.inputSuggestion,i.style.height="auto",i.style.height=Math.min(i.scrollHeight,120)+"px"),this.setState({inputSuggestion:null,inputEmpty:!1});return}n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleInputSend())});gt(this,"handleInputChange",n=>{const i=n.target;i.style.height="auto",i.style.height=Math.min(i.scrollHeight,120)+"px";const r=!i.value.trim();this.setState({inputEmpty:r}),this.state.inputSuggestion&&!r&&this.setState({inputSuggestion:null})});gt(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()))});gt(this,"handleSplitMouseDown",n=>{n.preventDefault(),this._resizing=!0;const r=!window.location.search.includes("token=");let s=[];if(r){const l=this.innerSplitRef.current;if(l){const u=l.getBoundingClientRect().width,d=7.8,O=[60,80,100,120],p=5;s=O.map(g=>{const v=g*d,$=v+p;if($>u*.75||$<u*.15)return null;const S=u-v-p;return{cols:g,terminalPx:v,linePosition:S}}).filter(g=>g!==null)}}this.setState({isDragging:!0,snapLines:s});const o=l=>{if(!this._resizing)return;const c=this.innerSplitRef.current;if(!c)return;const u=c.getBoundingClientRect(),d=u.width;let O=u.right-l.clientX;O=Math.max(200,Math.min(d*.75,O));let p=null;if(r&&s.length>0){let v=1/0,$=null;for(const S of s){const _=Math.abs(l.clientX-u.left-S.linePosition);_<v&&(v=_,$=S)}$&&v<60&&(p=$)}this.setState({terminalWidth:O,activeSnapLine:p})},a=()=>{if(this._resizing=!1,r&&this.state.activeSnapLine){const l=this.state.activeSnapLine.terminalPx;localStorage.setItem("cc-viewer-terminal-width",l.toString()),this.setState({terminalWidth:l,isDragging:!1,activeSnapLine:null,snapLines:[],needsInitialSnap:!1})}else localStorage.setItem("cc-viewer-terminal-width",this.state.terminalWidth.toString()),this.setState({isDragging:!1,activeSnapLine:null,snapLines:[],needsInitialSnap:!1});document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",a),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",o),document.addEventListener("mouseup",a),document.body.style.cursor="col-resize",document.body.style.userSelect="none"});gt(this,"handleToggleExpandPath",n=>{this.setState(i=>{const r=new Set(i.fileExplorerExpandedPaths);return r.has(n)?r.delete(n):r.add(n),{fileExplorerExpandedPaths:r}})});this.containerRef=ne.createRef(),this.splitContainerRef=ne.createRef(),this.innerSplitRef=ne.createRef();const i=localStorage.getItem("cc-viewer-terminal-width"),r=i?parseFloat(i):null;this.state={visibleCount:0,loading:!1,allItems:[],highlightTs:null,highlightFading:!1,terminalWidth:r||624,needsInitialSnap:r===null,inputEmpty:!0,pendingInput:null,stickyBottom:!0,ptyPrompt:null,ptyPromptHistory:[],inputSuggestion:null,fileExplorerOpen:localStorage.getItem("ccv_fileExplorerOpen")!=="false",currentFile:null,currentGitDiff:null,scrollToLine:null,fileExplorerExpandedPaths:new Set,gitChangesOpen:!1,snapLines:[],activeSnapLine:null,isDragging:!1,fileVersion:0,editorSessionId:null,editorFilePath:null,fileExplorerRefresh:0,gitChangesRefresh:0},this._processedToolIds=new Set,this._fileRefreshTimer=null,this._gitRefreshTimer=null,this._queueTimer=null,this._prevItemsLen=0,this._scrollTargetIdx=null,this._scrollTargetRef=ne.createRef(),this._scrollFadeTimer=null,this._resizing=!1,this._inputWs=null,this._inputRef=ne.createRef(),this._ptyBuffer="",this._ptyDataSeq=0,this._ptyDebounceTimer=null,this._currentPtyPrompt=null,this._mobileExtraItems=0,this._mobileSliceOffset=0,this._totalItemCount=0}_setFileExplorerOpen(n){localStorage.setItem("ccv_fileExplorerOpen",String(n)),this.setState({fileExplorerOpen:n})}_checkToolFileChanges(){var s,o;const n=this.props.mainAgentSessions;if(!n||n.length===0)return;let i=!1,r=!1;for(const a of n){const l=[];if((o=(s=a.response)==null?void 0:s.body)!=null&&o.content&&l.push(a.response.body.content),Array.isArray(a.messages))for(const c of a.messages)c.role==="assistant"&&Array.isArray(c.content)&&l.push(c.content);for(const c of l)for(const u of c){if(u.type!=="tool_use"||!u.id||this._processedToolIds.has(u.id))continue;this._processedToolIds.add(u.id);const d=u.name;let O=u.input;if(typeof O=="string")try{O=JSON.parse(O.replace(/^\[object Object\]/,""))}catch{O={}}d==="Write"?(i=!0,r=!0):d==="Edit"||d==="NotebookEdit"?r=!0:d==="Bash"&&O&&O.command&&uYe(O.command)&&(i=!0,r=!0)}}i&&this.state.fileExplorerOpen&&(clearTimeout(this._fileRefreshTimer),this._fileRefreshTimer=setTimeout(()=>{this.setState(a=>({fileExplorerRefresh:a.fileExplorerRefresh+1}))},500)),r&&this.state.gitChangesOpen&&(clearTimeout(this._gitRefreshTimer),this._gitRefreshTimer=setTimeout(()=>{this.setState(a=>({gitChangesRefresh:a.gitChangesRefresh+1}))},500))}componentDidMount(){this.startRender(),this.props.cliMode&&this.connectInputWs(),this._bindStickyScroll(),this.state.needsInitialSnap&&this.props.cliMode&&this.props.terminalVisible&&this._snapToInitialPosition()}shouldComponentUpdate(n,i){return n.mainAgentSessions!==this.props.mainAgentSessions||n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking||n.scrollToTimestamp!==this.props.scrollToTimestamp||n.cliMode!==this.props.cliMode||n.terminalVisible!==this.props.terminalVisible||n.userProfile!==this.props.userProfile||i!==this.state}componentDidUpdate(n){if(n.mainAgentSessions!==this.props.mainAgentSessions)ki&&(this._mobileExtraItems=0),this.startRender(),this.state.pendingInput&&this.setState({pendingInput:null}),this._updateSuggestion(),this._checkToolFileChanges();else if(n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking){const i=this.buildAllItems(),r=this._applyMobileSlice(i);this.setState({allItems:r,visibleCount:r.length})}if(!n.scrollToTimestamp&&this.props.scrollToTimestamp)if(ki&&this.props.scrollToTimestamp){const i=this.buildAllItems(),r=this._scrollTargetIdx;if(r!=null){const o=nw+this._mobileExtraItems,a=i.length>o?i.length-o:0;r<a&&(this._mobileExtraItems=i.length-r-nw,this._mobileExtraItems<0&&(this._mobileExtraItems=0))}const s=this._applyMobileSlice(i);this.setState({allItems:s,visibleCount:s.length},()=>this.scrollToBottom())}else{const i=this.buildAllItems(),r=this._applyMobileSlice(i);this.setState({allItems:r,visibleCount:r.length},()=>this.scrollToBottom())}ki&&this.props.mobileChatVisible&&!n.mobileChatVisible&&requestAnimationFrame(()=>{const i=this.containerRef.current;i&&(i.scrollTop=i.scrollHeight)}),!n.cliMode&&this.props.cliMode&&this.connectInputWs(),this._rebindStickyEl()}componentWillUnmount(){this._queueTimer&&clearTimeout(this._queueTimer),this._fadeClearTimer&&clearTimeout(this._fadeClearTimer),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._fileRefreshTimer&&clearTimeout(this._fileRefreshTimer),this._gitRefreshTimer&&clearTimeout(this._gitRefreshTimer),this._unbindScrollFade(),this._unbindStickyScroll(),this._inputWs&&(this._inputWs.close(),this._inputWs=null)}startRender(){this._queueTimer&&clearTimeout(this._queueTimer);const n=this.buildAllItems(),i=this._applyMobileSlice(n),r=this._prevItemsLen;this._prevItemsLen=i.length;const s=i.length-r;if(s<=0||r>0&&s<=3){this.setState({allItems:i,visibleCount:i.length,loading:!1},()=>this.scrollToBottom());return}if(i.length>oYe)this.setState({allItems:i,visibleCount:0,loading:!0}),this._queueTimer=setTimeout(()=>{this.setState({visibleCount:i.length,loading:!1},()=>this.scrollToBottom())},300);else{const o=Math.max(0,r);this.setState({allItems:i,visibleCount:o,loading:!1}),this.queueNext(o,i.length)}}queueNext(n,i){n>=i||(this._queueTimer=setTimeout(()=>{this.setState({visibleCount:n+1},()=>{this.scrollToBottom(),this.queueNext(n+1,i)})},hYe()))}_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,i=this.containerRef.current;i&&n.offsetHeight>i.clientHeight?n.scrollIntoView({block:"start",behavior:"instant"}):n.scrollIntoView({block:"center",behavior:"instant"});const r=this.props.scrollToTimestamp;this._scrollTargetRef=ne.createRef(),r&&(this.setState({highlightTs:r,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 i=n.scrollHeight-n.scrollTop-n.clientHeight;this.state.stickyBottom&&i>30?this.setState({stickyBottom:!1}):!this.state.stickyBottom&&i<=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,i,r,s){const{userProfile:o,collapseToolResults:a,expandThinking:l,onViewRequest:c}=this.props,{toolResultMap:u,readContentMap:d,editSnapshotMap:O,askAnswerMap:p,planApprovalMap:g}=P9(n),v=this.props.cliMode&&this.state.ptyPromptHistory.slice().reverse().find(x=>W$(x)&&x.status==="active")||null;let $=null,S=null;for(const x of n)if(x.role==="assistant"&&Array.isArray(x.content))for(const Q of x.content){if(Q.type==="tool_use"&&Q.name==="ExitPlanMode"){const w=g[Q.id];(!w||w.status==="pending")&&($=Q.id)}if(Q.type==="tool_use"&&Q.name==="AskUserQuestion"){const w=p[Q.id];(!w||Object.keys(w).length===0)&&(S=Q.id)}}const _=[];for(let x=0;x<n.length;x++){const Q=n[x],w=Q.content,C=Q._timestamp||null,T=C?s[C]:void 0,z=T!=null&&c?{requestIndex:T,onViewRequest:c}:{};if(Q.role==="user"){if(Array.isArray(w)){const R=w.find(I=>I.type==="text"&&/^\[SUGGESTION MODE:/i.test((I.text||"").trim())),L=w.filter(I=>I.type==="tool_result");if(!(R&&L.length>0)){const{commands:I,textBlocks:E,skillBlocks:X}=aT(w);for(let k=0;k<I.length;k++)_.push(y.jsx(sl,{role:"user",text:I[k],timestamp:C,userProfile:o,modelInfo:r,...z},`${i}-cmd-${x}-${k}`));for(const k of X){const j=k.text.match(/^#\s+(.+)$/m),N=j?j[1]:"Skill";_.push(y.jsx(sl,{role:"skill-loaded",text:k.text,skillName:N,timestamp:C,...z},`${i}-skill-${x}`))}for(let k=0;k<E.length;k++){const j=/^Implement the following plan:/i.test((E[k].text||"").trim());_.push(y.jsx(sl,{role:j?"plan-prompt":"user",text:E[k].text,timestamp:C,userProfile:o,modelInfo:r,...z},`${i}-user-${x}-${k}`))}}}else if(typeof w=="string"&&!Qu(w)){const R=/^Implement the following plan:/i.test(w.trim());_.push(y.jsx(sl,{role:R?"plan-prompt":"user",text:w,timestamp:C,userProfile:o,modelInfo:r,...z},`${i}-user-${x}`))}}else Q.role==="assistant"&&(Array.isArray(w)?_.push(y.jsx(sl,{role:"assistant",content:w,toolResultMap:u,readContentMap:d,editSnapshotMap:O,askAnswerMap:p,planApprovalMap:g,timestamp:C,modelInfo:r,collapseToolResults:a,expandThinking:l,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:v,lastPendingPlanId:$,lastPendingAskId:S,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,...z},`${i}-asst-${x}`)):typeof w=="string"&&_.push(y.jsx(sl,{role:"assistant",content:[{type:"text",text:w}],toolResultMap:u,readContentMap:d,editSnapshotMap:O,askAnswerMap:p,planApprovalMap:g,timestamp:C,modelInfo:r,collapseToolResults:a,expandThinking:l,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:v,lastPendingPlanId:$,lastPendingAskId:S,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,...z},`${i}-asst-${x}`)))}return _}buildAllItems(){var v,$,S,_,x;const{mainAgentSessions:n,requests:i,collapseToolResults:r,expandThinking:s,onViewRequest:o}=this.props;if(!n||n.length===0)return[];const a={};if(i)for(let Q=0;Q<i.length;Q++)wr(i[Q])&&i[Q].timestamp&&(a[i[Q].timestamp]=Q);let l=null;if(i){for(let Q=i.length-1;Q>=0;Q--)if(wr(i[Q])&&((v=i[Q].body)!=null&&v.model)){l=i[Q].body.model;break}}const c=Q0e(l),u=[],d={},O=[];if(i)for(let Q=0;Q<i.length;Q++){const w=i[Q];if(!w.timestamp)continue;const C=zu(w,i[Q+1]);if(C.type==="SubAgent"||C.type==="Teammate"){const T=(S=($=w.response)==null?void 0:$.body)==null?void 0:S.content;if(Array.isArray(T)&&T.length>0){const z=P9(((_=w.body)==null?void 0:_.messages)||[]).toolResultMap,R=C.type==="Teammate";O.push({timestamp:w.timestamp,content:T,toolResultMap:z,label:R?X0e(C.subType,(x=w.body)==null?void 0:x.model):wP(C.type,C.subType),isTeammate:R,requestIndex:Q})}}}let p=0;n.forEach((Q,w)=>{var T,z,R,L;w>0&&u.push(y.jsx(JX,{style:{borderColor:"#333",margin:"16px 0"},children:y.jsx(w9,{className:Nn.sessionDividerText,children:"Session"})},`session-div-${w}`));const C=this.renderSessionMessages(Q.messages,`s${w}`,c,a);for(const I of C){const E=I.props.timestamp;for(;p<O.length&&E&&O[p].timestamp<=E;){const X=O[p];X.timestamp&&(d[X.timestamp]=u.length),u.push(y.jsx(sl,{role:"sub-agent-chat",content:X.content,toolResultMap:X.toolResultMap,label:X.label,isTeammate:X.isTeammate,timestamp:X.timestamp,collapseToolResults:r,expandThinking:s,requestIndex:X.requestIndex,onViewRequest:o},`sub-chat-${p}`)),p++}E&&(d[E]=u.length),u.push(I)}for(;p<O.length;){const I=O[p],E=w<n.length-1&&((z=(T=n[w+1].messages)==null?void 0:T[0])==null?void 0:z._timestamp);if(E&&I.timestamp>E)break;I.timestamp&&(d[I.timestamp]=u.length),u.push(y.jsx(sl,{role:"sub-agent-chat",content:I.content,toolResultMap:I.toolResultMap,label:I.label,isTeammate:I.isTeammate,timestamp:I.timestamp,collapseToolResults:r,expandThinking:s,requestIndex:I.requestIndex,onViewRequest:o},`sub-chat-${p}`)),p++}if(w===n.length-1&&((L=(R=Q.response)==null?void 0:R.body)!=null&&L.content)){const I=Q.response.body.content;if(Array.isArray(I)){u.push(y.jsx(ne.Fragment,{children:y.jsx(JX,{style:{borderColor:"#2a2a2a",margin:"8px 0"},children:y.jsx(w9,{type:"secondary",className:Nn.lastResponseLabel,children:re("ui.lastResponse")})})},"resp-divider")),Q.entryTimestamp&&(d[Q.entryTimestamp]=u.length);let E=null;for(const X of I)X.type==="tool_use"&&X.name==="AskUserQuestion"&&(E=X.id);u.push(y.jsx(sl,{role:"assistant",content:I,timestamp:Q.entryTimestamp,modelInfo:c,collapseToolResults:r,expandThinking:s,toolResultMap:{},askAnswerMap:{},lastPendingAskId:E,cliMode:this.props.cliMode,onAskQuestionSubmit:this.handleAskQuestionSubmit},"resp-asst"))}}});const{scrollToTimestamp:g}=this.props;return this._scrollTargetIdx=g&&d[g]!=null?d[g]:null,this._tsItemMap=d,u}_applyMobileSlice(n){if(!ki)return this._mobileSliceOffset=0,this._totalItemCount=n.length,n;this._totalItemCount=n.length;const i=nw+this._mobileExtraItems;if(n.length<=i)return this._mobileSliceOffset=0,n;const r=n.length-i;if(this._mobileSliceOffset=r,this._scrollTargetIdx!=null&&(this._scrollTargetIdx-=r,this._scrollTargetIdx<0&&(this._scrollTargetIdx=null)),this._tsItemMap){const s={};for(const[o,a]of Object.entries(this._tsItemMap)){const l=a-r;l>=0&&(s[o]=l)}this._tsItemMap=s}return n.slice(r)}_extractSuggestion(){var O;const{mainAgentSessions:n}=this.props;if(!(n!=null&&n.length))return null;const i=n[n.length-1],r=i==null?void 0:i.messages;if(!Array.isArray(r)||r.length===0)return null;const s=r[r.length-1];if((s==null?void 0:s.role)!=="user")return null;const o=s.content;if(!(Array.isArray(o)?o.some(p=>p.type==="text"&&/^\[SUGGESTION MODE:/i.test((p.text||"").trim())):typeof o=="string"&&/^\[SUGGESTION MODE:/im.test(o.trim())))return null;const l=i==null?void 0:i.response;if(!l)return null;const c=l.body;if(!c)return null;const u=c.stop_reason;if(u!=="end_turn"&&u!=="max_tokens")return null;const d=c.content;if(!Array.isArray(d))return null;for(let p=d.length-1;p>=0;p--)if(d[p].type==="text"&&((O=d[p].text)!=null&&O.trim()))return d[p].text.trim();return null}_updateSuggestion(){const n=this._extractSuggestion();this.setState({inputSuggestion:n||null})}connectInputWs(){const i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal`;this._inputWs=new WebSocket(i),this._inputWs.onmessage=r=>{try{const s=JSON.parse(r.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 i=this._stripAnsi(n);this._ptyBuffer+=i,this._ptyDataSeq++,this._ptyBuffer.length>4096&&(this._ptyBuffer=this._ptyBuffer.slice(-4096)),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._ptyDebounceTimer=setTimeout(()=>this._detectPrompt(),200)}_detectPrompt(){const i=this._ptyBuffer.match(/([^\n]*\?)\s*\n((?:\s*[❯>]?\s*\d+\.\s+[^\n]+\n?){2,})$/);if(i){const r=i[1].trim(),o=i[2].match(/\s*([❯>])?\s*(\d+)\.\s+([^\n]+)/g);if(o){const a=o.map(u=>{const d=u.match(/\s*([❯>])?\s*(\d+)\.\s+(.+)/);return{number:parseInt(d[2],10),text:d[3].trim(),selected:!!d[1]}}),l=this.state.ptyPrompt,c={question:r,options:a};l&&l.question===r?(this._currentPtyPrompt=c,this.setState({ptyPrompt:c})):(this._currentPtyPrompt=c,this.setState(u=>{const d=u.ptyPromptHistory.slice();if(u.ptyPrompt){const O=d[d.length-1];O&&O.status==="active"&&(d[d.length-1]={...O,status:"dismissed"})}return d.push({...c,status:"active",selectedNumber:null,timestamp:new Date().toISOString()}),{ptyPrompt:c,ptyPromptHistory:d}}),this.scrollToBottom());return}}if(this.state.ptyPrompt){if(W$(this.state.ptyPrompt)||this._askSubmitting)return;this._currentPtyPrompt=null,this.setState(r=>{const s=r.ptyPromptHistory.slice(),o=s[s.length-1];return o&&o.status==="active"&&(s[s.length-1]={...o,status:"dismissed"}),{ptyPrompt:null,ptyPromptHistory:s}})}}_clearPtyPrompt(){this._ptyBuffer="",this._currentPtyPrompt=null,this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this.state.ptyPrompt&&this.setState({ptyPrompt:null})}_planSubmissionSteps(n){return n.map((i,r)=>({...i,isLast:r===n.length-1}))}_waitForWsAndSubmit(){if(this._askWsRetries=(this._askWsRetries||0)+1,this._askWsRetries>30){this._askSubmitting=!1,this._askAnswerQueue=[];return}if(this._inputWs&&this._inputWs.readyState===WebSocket.OPEN){this._currentPtyPrompt?this._processNextAskAnswer():(this._askPromptRetries=0,this._waitForPtyPromptAndSubmit());return}setTimeout(()=>this._waitForWsAndSubmit(),100)}_waitForPtyPromptAndSubmit(){if(this._askPromptRetries=(this._askPromptRetries||0)+1,this._askPromptRetries>50){this._processNextAskAnswer();return}if(this._currentPtyPrompt){this._processNextAskAnswer();return}setTimeout(()=>this._waitForPtyPromptAndSubmit(),100)}_processNextAskAnswer(){if(!this._askAnswerQueue||this._askAnswerQueue.length===0){this._askSubmitting=!1;return}const n=this._askAnswerQueue.shift();n.type==="other"?this._submitOtherAnswer(n):n.type==="multi"?this._submitMultiSelectAnswer(n):this._submitSingleSelectAnswer(n)}_submitSingleSelectAnswer(n){this._submitViaSequentialQueue(n)}_submitMultiSelectAnswer(n){this._submitViaSequentialQueue(n)}_submitOtherAnswer(n){this._submitViaSequentialQueue(n)}_submitViaSequentialQueue(n){const i=this._inputWs;if(!i||i.readyState!==WebSocket.OPEN){this._askSubmitting=!1;return}const r=this._askAnswerQueue&&this._askAnswerQueue.length>0,s=xBe(n,this.state.ptyPrompt,r),o=a=>{try{JSON.parse(a.data).type==="input-sequential-done"&&(i.removeEventListener("message",o),this._finishCurrentAskAnswer())}catch{}};i.addEventListener("message",o),i.send(JSON.stringify({type:"input-sequential",chunks:s,settleMs:300})),setTimeout(()=>{i.removeEventListener("message",o),this._askSubmitting&&this._finishCurrentAskAnswer()},15e3)}_finishCurrentAskAnswer(){this._currentPtyPrompt=null,this.setState(n=>{const i=n.ptyPromptHistory.slice(),r=i[i.length-1];return r&&r.status==="active"&&(i[i.length-1]={...r,status:"answered"}),{ptyPrompt:null,ptyPromptHistory:i}}),(!this._askAnswerQueue||this._askAnswerQueue.length===0)&&this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._askAnswerQueue&&this._askAnswerQueue.length>0?setTimeout(()=>{this._processNextAskAnswer()},500):this._askSubmitting=!1}_snapToInitialPosition(){this.setState({terminalWidth:468,needsInitialSnap:!1}),localStorage.setItem("cc-viewer-terminal-width","468")}render(){const{mainAgentSessions:n,cliMode:i,terminalVisible:r}=this.props,{allItems:s,visibleCount:o,loading:a,terminalWidth:l}=this.state,c=!n||n.length===0;if(c&&!i)return y.jsx("div",{className:Nn.centerEmpty,children:y.jsx(Lr,{description:re("ui.noChat")})});if(a&&!i)return y.jsx("div",{className:Nn.centerEmpty,children:y.jsx(Da,{size:"large"})});const u=this._scrollTargetIdx,{highlightTs:d,highlightFading:O}=this.state,p=d&&this._tsItemMap&&this._tsItemMap[d]!=null?this._tsItemMap[d]:null,g=s.slice(0,o),{pendingInput:v,stickyBottom:$,ptyPromptHistory:S}=this.state,_=i&&v?y.jsx(sl,{role:"user",text:v,timestamp:new Date().toISOString(),userProfile:this.props.userProfile},"pending-input"):null,x=$?null:y.jsxs("button",{className:Nn.stickyBottomBtn,onClick:this.handleStickToBottom,children:[y.jsx("span",{children:re("ui.stickyBottom")}),y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:y.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),Q=i&&S.length>0?S.filter(T=>!(W$(T)&&T.status==="active")).map((T,z)=>{const R=T.status==="active",L=T.status==="answered";return y.jsxs("div",{className:`${Nn.ptyPromptBubble}${R?"":" "+Nn.ptyPromptResolved}`,children:[y.jsx("div",{className:Nn.ptyPromptQuestion,children:T.question}),y.jsx("div",{className:Nn.ptyPromptOptions,children:T.options.map(I=>{const E=L&&T.selectedNumber===I.number;let X=Nn.ptyPromptOption;return R&&I.selected&&(X=Nn.ptyPromptOptionPrimary),E&&(X=Nn.ptyPromptOptionChosen),!R&&!E&&(X=Nn.ptyPromptOptionDimmed),y.jsxs("button",{className:X,disabled:!R,onClick:R?()=>this.handlePromptOptionClick(I.number):void 0,children:[I.number,". ",I.text]},I.number)})})]},`pty-prompt-${z}`)}):null,w=ki&&this._mobileSliceOffset>0?y.jsx("div",{className:Nn.loadMoreWrap,children:y.jsx("button",{className:Nn.loadMoreBtn,onClick:this.handleLoadMore,children:re("ui.loadMoreHistory",{count:this._mobileSliceOffset})})}):null,C=c||a?y.jsxs("div",{className:Nn.messageListWrap,children:[y.jsxs("div",{ref:this.containerRef,className:Nn.container,children:[!i||a?y.jsx("div",{className:Nn.centerEmpty,children:a?y.jsx(Da,{size:"large"}):y.jsx(Lr,{description:re("ui.noChat")})}):null,_,Q]}),x]}):y.jsxs("div",{className:Nn.messageListWrap,children:[y.jsxs("div",{ref:this.containerRef,className:Nn.container,children:[w,g.map((T,z)=>{const R=z===u,L=z===p;let I=T;return L&&(I=ne.cloneElement(I,{highlight:O?"fading":"active"})),R?y.jsx("div",{ref:this._scrollTargetRef,children:I},T.key+"-anchor"):I}),_,Q]}),x]});return i?y.jsxs("div",{ref:this.splitContainerRef,className:Nn.splitContainer,children:[y.jsxs("div",{className:Nn.navSidebar,children:[y.jsx("button",{className:this.state.fileExplorerOpen?Nn.navBtnActive:Nn.navBtn,onClick:()=>{this._setFileExplorerOpen(!this.state.fileExplorerOpen),this.setState({gitChangesOpen:!1})},title:re("ui.fileExplorer"),children:y.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:y.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 2h9a2 2 0 0 1 2 2z"})})}),y.jsx("button",{className:this.state.gitChangesOpen?Nn.navBtnActive:Nn.navBtn,onClick:()=>this.setState(T=>(this._setFileExplorerOpen(!1),{gitChangesOpen:!T.gitChangesOpen})),title:re("ui.gitChanges"),children:y.jsx("svg",{width:"24",height:"24",viewBox:"0 0 1024 1024",fill:"currentColor",children:y.jsx("path",{d:"M759.53332137 326.35000897c0-48.26899766-39.4506231-87.33284994-87.87432908-86.6366625-46.95397689 0.69618746-85.08957923 39.14120645-85.39899588 86.09518335-0.23206249 40.68828971 27.53808201 74.87882971 65.13220519 84.47074592 10.82958281 2.78474987 18.41029078 12.37666607 18.64235327 23.51566553 0.38677082 21.11768647-3.40358317 44.40128953-17.24997834 63.81718442-22.20064476 31.17372767-62.42480948 42.46743545-97.93037026 52.44612248-22.43270724 6.26568719-38.75443563 7.89012462-53.14230994 9.28249954-20.42149901 2.01120825-39.76003975 3.94506233-63.89453858 17.79145747-5.10537475 2.93945818-10.13339535 6.18833303-14.85199928 9.74662453-4.09977063 3.09416652-9.90133285 0.15470833-9.90133286-4.95066641V302.60228095c0-9.43720788 5.26008307-18.17822829 13.69168683-22.3553531 28.69839444-14.23316598 48.42370599-43.93716454 48.19164353-78.20505872-0.38677082-48.57841433-41.15241468-87.71962076-89.730829-86.01782918C338.80402918 117.57112321 301.59667683 155.70672553 301.59667683 202.58334827c0 34.03583169 19.64795738 63.50776777 48.1916435 77.66357958 8.43160375 4.17712479 13.69168685 12.76343689 13.69168684 22.12329062v419.02750058c0 9.43720788-5.26008307 18.17822829-13.69168684 22.3553531-28.69839444 14.23316598-48.42370599 43.93716454-48.1916435 78.20505872 0.30941665 48.57841433 41.07506052 87.6422666 89.65347484 86.01782918C437.74000359 906.42887679 474.87000179 868.2159203 474.87000179 821.41665173c0-34.03583169-19.64795738-63.50776777-48.1916435-77.66357958-8.43160375-4.17712479-13.69168685-12.76343689-13.69168684-22.12329062v-14.85199926c0-32.48874844 15.39347842-63.27570528 42.00331048-81.91805854 2.39797906-1.70179159 4.95066642-3.32622901 7.50335379-4.79595812 14.92935344-8.58631209 25.91364457-9.66927037 44.09187287-11.4484161 15.62554091-1.54708326 35.04143581-3.48093734 61.65126786-10.90693699 39.06385228-10.98429114 92.51557887-25.91364457 124.84961898-71.39789238 18.56499911-26.06835292 27.38337367-58.01562219 26.37776956-95.14562041-0.15470833-5.33743724-0.54147915-10.67487447-1.08295828-16.16702004-0.85089578-8.27689543 2.70739569-16.24437421 9.12779121-21.50445729 19.57060322-15.78024923 32.02462345-39.99210223 32.02462345-67.14341343zM351.1033411 202.58334827c0-20.49885317 16.63114503-37.12999821 37.1299982-37.1299982s37.12999821 16.63114503 37.12999821 37.1299982-16.63114503 37.12999821-37.12999821 37.1299982-37.12999821-16.63114503-37.1299982-37.1299982z m74.25999641 618.83330346c0 20.49885317-16.63114503 37.12999821-37.12999821 37.1299982s-37.12999821-16.63114503-37.1299982-37.1299982 16.63114503-37.12999821 37.1299982-37.1299982 37.12999821 16.63114503 37.12999821 37.1299982z m247.53332139-457.93664456c-20.49885317 0-37.12999821-16.63114503-37.1299982-37.1299982s16.63114503-37.12999821 37.1299982-37.12999821 37.12999821 16.63114503 37.1299982 37.12999821-16.63114503 37.12999821-37.1299982 37.1299982z"})})})]}),y.jsxs("div",{style:{flex:1,display:"flex",minWidth:0,position:"relative"},ref:this.innerSplitRef,children:[this.state.isDragging&&this.state.activeSnapLine&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const L=T.getBoundingClientRect().width-this.state.terminalWidth-5,I=this.state.activeSnapLine.linePosition,E=Math.min(L,I),X=Math.abs(I-L);return y.jsx("div",{className:Nn.snapPreview,style:{left:`${E}px`,width:`${X}px`}})})(),this.state.isDragging&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const L=T.getBoundingClientRect().width-this.state.terminalWidth-5,I=[...this.state.snapLines].map(k=>({...k,dist:Math.abs(k.linePosition-L)})).sort((k,j)=>k.dist-j.dist);if(I.length===0)return null;const E=I[0],X=this.state.activeSnapLine&&this.state.activeSnapLine.cols===E.cols;return y.jsx("div",{className:X?Nn.snapLineActive:Nn.snapLine,style:{left:`${E.linePosition}px`}},E.cols)})(),this.state.fileExplorerOpen&&y.jsx(hTe,{refreshTrigger:this.state.fileExplorerRefresh,onClose:()=>this._setFileExplorerOpen(!1),onFileClick:T=>this.setState({currentFile:T,currentGitDiff:null,scrollToLine:null}),expandedPaths:this.state.fileExplorerExpandedPaths,onToggleExpand:this.handleToggleExpandPath,currentFile:this.state.currentFile}),this.state.gitChangesOpen&&y.jsx(XWe,{refreshTrigger:this.state.gitChangesRefresh,onClose:()=>this.setState({gitChangesOpen:!1}),onFileClick:T=>this.setState({currentGitDiff:T,currentFile:null})}),y.jsx("div",{className:Nn.chatSection,style:{flex:1,minWidth:0,display:"flex"},children:y.jsxs("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[this.state.currentGitDiff&&y.jsx("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",flexDirection:"column"},children:y.jsx(mBe,{filePath:this.state.currentGitDiff,onClose:()=>this.setState({currentGitDiff:null}),onOpenFile:(T,z)=>{this._setFileExplorerOpen(!0),this.setState({currentGitDiff:null,currentFile:T,scrollToLine:z||1,gitChangesOpen:!1})}})}),this.state.currentFile&&y.jsx("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",flexDirection:"column"},children:lYe(this.state.currentFile)?y.jsx(uWe,{filePath:this.state.currentFile,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch("/api/editor-done",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.state.editorSessionId})}).catch(()=>{}),this.setState({currentFile:null,fileVersion:0,editorSessionId:null,editorFilePath:null})}},this.state.fileVersion):y.jsx(YLe,{filePath:this.state.currentFile,scrollToLine:this.state.scrollToLine,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch("/api/editor-done",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.state.editorSessionId})}).catch(()=>{}),this.setState({currentFile:null,fileVersion:0,editorSessionId:null,editorFilePath:null})}},this.state.fileVersion)}),C,!r&&y.jsxs("div",{className:Nn.chatInputBar,children:[y.jsxs("div",{className:Nn.chatInputWrapper,children:[y.jsxs("div",{className:Nn.chatTextareaWrap,children:[y.jsx("textarea",{ref:this._inputRef,className:Nn.chatTextarea,placeholder:this.state.inputSuggestion?"":re("ui.chatInput.placeholder"),rows:1,onKeyDown:this.handleInputKeyDown,onInput:this.handleInputChange}),this.state.inputSuggestion&&this.state.inputEmpty&&y.jsx("div",{className:Nn.ghostText,children:this.state.inputSuggestion})]}),y.jsx("div",{className:Nn.chatInputHint,children:this.state.inputSuggestion&&this.state.inputEmpty?re("ui.chatInput.hintTab"):re("ui.chatInput.hintEnter")})]}),!ki&&y.jsx("button",{className:Nn.chatSendBtn,onClick:()=>{const T=document.createElement("input");T.type="file",T.onchange=async z=>{var L;const R=(L=z.target.files)==null?void 0:L[0];if(R)try{const E=`"${await WB(R)}"`,X=this._inputRef.current;X&&(X.value=(X.value?X.value+" ":"")+E,X.dispatchEvent(new Event("input",{bubbles:!0})),this.setState({inputEmpty:!1}))}catch(I){console.error("[CC Viewer] Upload failed:",I)}},T.click()},title:re("ui.terminal.upload"),children:y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[y.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),y.jsx("polyline",{points:"17 8 12 3 7 8"}),y.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]})}),y.jsx("button",{className:Nn.chatSendBtn,onClick:this.handleInputSend,disabled:this.state.inputEmpty,title:re("ui.chatInput.send"),children:y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[y.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),y.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),r&&this.state.inputSuggestion&&y.jsxs("div",{className:Nn.suggestionChip,onClick:this.handleSuggestionToTerminal,children:[y.jsx("span",{className:Nn.suggestionChipText,children:this.state.inputSuggestion}),y.jsx("span",{className:Nn.suggestionChipAction,children:"↵"})]})]})}),r&&y.jsxs(y.Fragment,{children:[y.jsx("div",{className:Nn.vResizer,onMouseDown:this.handleSplitMouseDown}),y.jsx("div",{style:{width:l,flexShrink:0,minWidth:200,display:"flex",flexDirection:"column"},children:y.jsx(VB,{onEditorOpen:(T,z)=>{this.setState({editorSessionId:T,editorFilePath:z,currentFile:z,currentGitDiff:null,scrollToLine:null,fileVersion:(this.state.fileVersion||0)+1})},onFilePath:T=>{const z=`"${T}"`;this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:z}))}})})]})]})]}):C}}const pYe="_resizer_yamj2_1",mYe={resizer:pYe};class gYe extends ne.Component{constructor(e){super(e),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this)}handleMouseDown(e){e.preventDefault(),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}handleMouseMove(e){this.props.onResize&&this.props.onResize(e.clientX)}handleMouseUp(){document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}componentWillUnmount(){document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}render(){return y.jsx("div",{onMouseDown:this.handleMouseDown,className:mYe.resizer})}}const vYe="_container_1um1r_1",$Ye="_fileListSection_1um1r_10",SYe="_header_1um1r_19",bYe="_headerTitle_1um1r_28",yYe="_fileCount_1um1r_36",_Ye="_changesContainer_1um1r_44",xYe="_changeItem_1um1r_51",QYe="_changeItemActive_1um1r_68",wYe="_dirItem_1um1r_77",PYe="_dirArrow_1um1r_88",CYe="_dirName_1um1r_97",kYe="_status_1um1r_102",TYe="_icon_1um1r_111",RYe="_fileName_1um1r_120",EYe="_diffSection_1um1r_127",XYe="_diffHeader_1um1r_135",zYe="_diffFilePath_1um1r_145",jYe="_diffBadge_1um1r_155",MYe="_diffContent_1um1r_167",NYe="_diffPlaceholder_1um1r_173",IYe="_statusText_1um1r_184",AYe="_errorText_1um1r_191",LYe="_emptyText_1um1r_198",WYe="_warningText_1um1r_205",Ci={container:vYe,fileListSection:$Ye,header:SYe,headerTitle:bYe,fileCount:yYe,changesContainer:_Ye,changeItem:xYe,changeItemActive:QYe,dirItem:wYe,dirArrow:PYe,dirName:CYe,status:kYe,icon:TYe,fileName:RYe,diffSection:EYe,diffHeader:XYe,diffFilePath:zYe,diffBadge:jYe,diffContent:MYe,diffPlaceholder:NYe,statusText:IYe,errorText:AYe,emptyText:LYe,warningText:WYe},VYe={M:"#e2c08d",A:"#73c991",D:"#f14c4c",R:"#73c991",C:"#73c991",U:"#e2c08d","?":"#73c991","??":"#73c991"},BYe={"??":"U"},YYe={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 UYe(t){const e=t.includes(".")?t.split(".").pop().toLowerCase():"",n=YYe[e]||"#888";return y.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",children:[y.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),y.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function DYe(){return y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"#c09553",stroke:"none",children:y.jsx("path",{d:"M2 6c0-1.1.9-2 2-2h5l2 2h9a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6z"})})}function qYe(t){const e={dirs:{},files:[]};for(const n of t){const i=n.file.split("/");let r=e;for(let s=0;s<i.length-1;s++)r.dirs[i[s]]||(r.dirs[i[s]]={dirs:{},files:[]}),r=r.dirs[i[s]];r.files.push({name:i[i.length-1],status:n.status,fullPath:n.file})}return e}function IZ({name:t,node:e,depth:n,selectedFile:i,onFileClick:r}){const s=Object.keys(e.dirs).sort(),o=[...e.files].sort((a,l)=>a.name.localeCompare(l.name));return y.jsxs(y.Fragment,{children:[t&&y.jsxs("div",{className:Ci.dirItem,style:{paddingLeft:8+n*16},children:[y.jsx("span",{className:Ci.dirArrow,children:y.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:"rotate(90deg)"},children:y.jsx("polyline",{points:"9 6 15 12 9 18"})})}),y.jsx("span",{className:Ci.icon,children:DYe()}),y.jsx("span",{className:Ci.dirName,children:t})]}),s.map(a=>y.jsx(IZ,{name:a,node:e.dirs[a],depth:t?n+1:n,selectedFile:i,onFileClick:r},a)),o.map(a=>y.jsxs("div",{className:`${Ci.changeItem} ${i===a.fullPath?Ci.changeItemActive:""}`,style:{paddingLeft:8+(t?n+1:n)*16},onClick:()=>r&&r(a.fullPath),children:[y.jsx("span",{className:Ci.icon,children:UYe(a.name)}),y.jsx("span",{className:Ci.fileName,children:a.name}),y.jsx("span",{className:Ci.status,style:{color:VYe[a.status]||"#888"},children:BYe[a.status]||a.status})]},a.fullPath))]})}function ZYe({visible:t}){const[e,n]=f.useState(null),[i,r]=f.useState(null),[s,o]=f.useState(!0),[a,l]=f.useState(null),[c,u]=f.useState(null),[d,O]=f.useState(null),[p,g]=f.useState(!1),v=f.useRef(!0);return f.useEffect(()=>{if(v.current=!0,!!t)return o(!0),r(null),fetch(Rn("/api/git-status")).then($=>$.ok?$.json():Promise.reject()).then($=>{v.current&&(n($.changes||[]),o(!1))}).catch(()=>{v.current&&(r("Failed to load git status"),o(!1))}),()=>{v.current=!1}},[t]),f.useEffect(()=>{if(!a){u(null),O(null);return}g(!0),u(null),O(null),fetch(Rn(`/api/git-diff?files=${encodeURIComponent(a)}`)).then($=>{if(!$.ok)throw new Error(`HTTP ${$.status}`);return $.json()}).then($=>{v.current&&($.diffs&&$.diffs[0]?u($.diffs[0]):O("No diff data available"),g(!1))}).catch($=>{v.current&&(O(`${re("ui.fileLoadError")}: ${$.message}`),g(!1))})},[a]),y.jsxs("div",{className:Ci.container,children:[y.jsxs("div",{className:Ci.fileListSection,children:[y.jsxs("div",{className:Ci.header,children:[y.jsx("span",{className:Ci.headerTitle,children:re("ui.gitChanges")}),y.jsx("span",{className:Ci.fileCount,children:e?e.length:0})]}),y.jsxs("div",{className:Ci.changesContainer,children:[s&&y.jsx("div",{className:Ci.statusText,children:"Loading..."}),i&&y.jsx("div",{className:Ci.errorText,children:i}),!s&&!i&&e&&e.length===0&&y.jsx("div",{className:Ci.emptyText,children:"No changes"}),!s&&!i&&e&&e.length>0&&y.jsx(IZ,{name:"",node:qYe(e),depth:0,selectedFile:a,onFileClick:l})]})]}),y.jsx("div",{className:Ci.diffSection,children:a?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:Ci.diffHeader,children:[y.jsx("span",{className:Ci.diffFilePath,children:a}),y.jsx("span",{className:Ci.diffBadge,children:"DIFF"})]}),y.jsxs("div",{className:Ci.diffContent,children:[p&&y.jsx("div",{className:Ci.statusText,children:re("ui.loading")}),d&&y.jsx("div",{className:Ci.errorText,children:d}),!p&&!d&&c&&y.jsx(y.Fragment,{children:c.is_large?y.jsxs("div",{className:Ci.warningText,children:[y.jsx("p",{children:re("ui.largeFileWarning")}),y.jsxs("p",{style:{color:"#888",fontSize:12},children:[re("ui.fileSize"),": ",(c.size/(1024*1024)).toFixed(2)," MB"]})]}):c.is_binary?y.jsx("div",{className:Ci.statusText,style:{fontStyle:"italic"},children:re("ui.binaryFileNotice")}):y.jsx(NZ,{file_path:a,old_string:c.old_content,new_string:c.new_content})})]})]}):y.jsxs("div",{className:Ci.diffPlaceholder,children:[y.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"#333",strokeWidth:"1.5",children:[y.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),y.jsx("circle",{cx:"18",cy:"6",r:"3"}),y.jsx("circle",{cx:"6",cy:"18",r:"3"}),y.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),y.jsx("span",{children:re("ui.mobileGitDiffHint")})]})})]})}const FYe="_container_rkahp_1",GYe="_header_rkahp_9",HYe="_headerTitle_rkahp_18",KYe="_closeBtn_rkahp_24",JYe="_content_rkahp_38",eUe="_empty_rkahp_47",tUe="_fixedTable_rkahp_54",nUe="_ellipsisCell_rkahp_58",su={container:FYe,header:GYe,headerTitle:HYe,closeBtn:KYe,content:JYe,empty:eUe,fixedTable:tUe,ellipsisCell:nUe},iUe=["ttl","system_change","tools_change","model_change","msg_truncated","msg_modified","key_change"],k9={ttl:"cacheLoss.ttl",system_change:"cacheLoss.systemChange",tools_change:"cacheLoss.toolsChange",model_change:"cacheLoss.modelChange",msg_truncated:"cacheLoss.msgTruncated",msg_modified:"cacheLoss.msgModified",key_change:"cacheLoss.keyChange"};function rUe({requests:t=[],visible:e,onClose:n}){if(!e)return null;const{byModel:i,models:r,toolStats:s,skillStats:o,cacheStats:a,activeReasons:l,totalCount:c,totalCache:u,hasCacheStats:d,subAgentEntries:O,hasSubAgentStats:p,isEmpty:g}=f.useMemo(()=>{const v=DW(t),$=Object.keys(v),S=ZW(t),_=FW(t),x=qW(t),Q=iUe.filter(j=>x[j].count>0),w=Q.reduce((j,N)=>j+x[N].count,0),C=Q.reduce((j,N)=>j+x[N].cacheCreate,0),T=Q.length>0,z={};for(let j=0;j<t.length;j++){const N=zu(t[j],t[j+1]);if(N.type==="SubAgent"){const A=N.subType||"Other";z[A]=(z[A]||0)+1}else if(N.type==="Teammate"){const A=N.subType?`Teammate:${N.subType}`:"Teammate";z[A]=(z[A]||0)+1}}const R=Object.entries(z).sort((j,N)=>N[1]-j[1]),L=R.length>0,I={};for(let j=0;j<t.length;j++){const N=zu(t[j],t[j+1]);if(N.type==="Teammate"){const A=N.subType||"Teammate";I[A]=(I[A]||0)+1}}const X=Object.entries(I).sort((j,N)=>N[1]-j[1]).length>0,k=$.length===0&&S.length===0&&!T&&!L&&!X&&_.length===0;return{byModel:v,models:$,toolStats:S,skillStats:_,cacheStats:x,activeReasons:Q,totalCount:w,totalCache:C,hasCacheStats:T,subAgentEntries:R,hasSubAgentStats:L,isEmpty:k}},[t]);return y.jsxs("div",{className:su.container,children:[y.jsxs("div",{className:su.header,children:[y.jsx("span",{className:su.headerTitle,children:re("ui.tokenStats")}),y.jsx("button",{className:su.closeBtn,onClick:n,children:y.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y.jsx("div",{className:su.content,children:g?y.jsx("div",{className:su.empty,children:"—"}):y.jsxs(y.Fragment,{children:[o.length>0&&y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:re("ui.skillUsageStats")}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"Skill"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[o.map(([v,$])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label,children:v}),y.jsx("td",{className:se.td,children:$})]},v)),o.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:o.reduce((v,$)=>v+$[1],0)})]})]})]})]}),p&&y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:re("ui.subAgentStats")}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"SubAgent"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[O.map(([v,$])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label,children:v}),y.jsx("td",{className:se.td,children:$})]},v)),O.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:O.reduce((v,$)=>v+$[1],0)})]})]})]})]}),hasTeammateStats&&y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:"Teammate"}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"Name"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[teammateEntries.map(([v,$])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label,children:v}),y.jsx("td",{className:se.td,children:$})]},v)),teammateEntries.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:teammateEntries.reduce((v,$)=>v+$[1],0)})]})]})]})]}),s.length>0&&y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:re("ui.toolUsageStats")}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"Tool"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[s.map(([v,$])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsxs("td",{className:se.label,children:[v," ",y.jsx(La,{doc:`Tool-${v}`})]}),y.jsx("td",{className:se.td,children:$})]},v)),s.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:s.reduce((v,$)=>v+$[1],0)})]})]})]})]}),d&&y.jsxs("div",{className:se.modelCard,children:[y.jsxs("div",{className:se.modelName,children:["MainAgent",y.jsx(La,{doc:"MainAgent"})," ",re("ui.cacheRebuildStats"),y.jsx(La,{doc:"CacheRebuild"})]}),y.jsxs("table",{className:`${se.statsTable} ${su.fixedTable}`,children:[y.jsxs("colgroup",{children:[y.jsx("col",{style:{width:"50%"}}),y.jsx("col",{style:{width:"25%"}}),y.jsx("col",{style:{width:"25%"}})]}),y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:re("ui.cacheRebuild.reason")}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.cacheCreate")})]})}),y.jsxs("tbody",{children:[l.map(v=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:`${se.label} ${su.ellipsisCell}`,title:re(`ui.${k9[v]}`),children:re(`ui.${k9[v]}`)}),y.jsx("td",{className:se.td,children:a[v].count}),y.jsx("td",{className:se.td,children:$i(a[v].cacheCreate)})]},v)),l.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:c}),y.jsx("td",{className:se.td,children:$i(u)})]})]})]})]}),r.map(v=>{const $=i[v],S=$.input+$.cacheCreation+$.cacheRead,_=S>0?($.cacheRead/S*100).toFixed(1):"0.0";return y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:v}),y.jsx("table",{className:se.statsTable,children:y.jsxs("tbody",{children:[y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:"Token"}),y.jsx("td",{className:se.th,children:"input"}),y.jsx("td",{className:se.th,children:"output"})]}),y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label}),y.jsx("td",{className:se.td,children:$i(S)}),y.jsx("td",{className:se.td,children:$i($.output)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:"Cache"}),y.jsx("td",{className:se.th,children:"create"}),y.jsx("td",{className:se.th,children:"read"})]}),y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label}),y.jsx("td",{className:se.td,children:$i($.cacheCreation)}),y.jsx("td",{className:se.td,children:$i($.cacheRead)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:re("ui.hitRate")}),y.jsxs("td",{colSpan:2,className:se.td,children:[_,"%"]})]})]})})]},v)})]})})]})}const{Text:Ed,Title:sUe}=Ga;function oUe(t){if(!t)return"0 B";const e=["B","KB","MB","GB"];let n=0,i=t;for(;i>=1024&&n<e.length-1;)i/=1024,n++;return`${i.toFixed(n>0?1:0)} ${e[n]}`}function aUe(t){if(!t)return"";const e=Date.now()-new Date(t).getTime(),n=Math.floor(e/6e4);if(n<1)return re("ui.workspaces.justNow");if(n<60)return`${n}m ago`;const i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function lUe({open:t,onClose:e,onSelect:n}){const[i,r]=f.useState(""),[s,o]=f.useState(null),[a,l]=f.useState([]),[c,u]=f.useState(!1),[d,O]=f.useState(""),p=f.useCallback(v=>{u(!0);const $=v?`/api/browse-dir?path=${encodeURIComponent(v)}`:"/api/browse-dir";fetch(Rn($)).then(S=>S.json()).then(S=>{S.error?ei.error(S.error):(r(S.current),o(S.parent),l(S.dirs||[]),O(S.current)),u(!1)}).catch(()=>{ei.error("Failed to browse directory"),u(!1)})},[]);f.useEffect(()=>{t&&p("")},[t,p]);const g=()=>{const v=d.trim();v&&p(v)};return y.jsxs(Tr,{title:re("ui.workspaces.selectDir"),open:t,onCancel:e,footer:null,width:600,styles:{body:{padding:"12px 0"}},children:[y.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"0 16px 10px",borderBottom:"1px solid #2a2a2a"},children:[y.jsx(Sn,{type:"text",icon:y.jsx(Rve,{}),disabled:!s,onClick:()=>s&&p(s),size:"small"}),y.jsxs(Ed,{style:{color:"#e0e0e0",fontSize:13,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[y.jsx(d1,{style:{marginRight:6,color:"#1668dc"}}),i]})]}),y.jsx("div",{style:{maxHeight:400,overflowY:"auto",padding:"4px 0"},children:c?y.jsx("div",{style:{textAlign:"center",padding:40},children:y.jsx(Da,{})}):a.length===0?y.jsx("div",{style:{textAlign:"center",padding:40},children:y.jsx(Ed,{type:"secondary",children:re("ui.workspaces.emptyDir")})}):a.map(v=>y.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 16px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:$=>$.currentTarget.style.background="#1a1a1a",onMouseLeave:$=>$.currentTarget.style.background="transparent",children:[y.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:8,minWidth:0},onClick:()=>p(v.path),children:[y.jsx(vW,{style:{color:v.hasGit?"#1668dc":"#666",fontSize:16,flexShrink:0}}),y.jsx(Ed,{style:{color:"#d0d0d0",fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name}),v.hasGit&&y.jsxs(eo,{color:"blue",style:{fontSize:11,lineHeight:"18px",padding:"0 4px",margin:0,flexShrink:0},children:[y.jsx(TW,{style:{marginRight:2}}),"git"]})]}),y.jsx(Sn,{type:"primary",size:"small",onClick:$=>{$.stopPropagation(),n(v.path)},children:re("ui.workspaces.select")})]},v.path))}),y.jsxs("div",{style:{borderTop:"1px solid #2a2a2a",padding:"10px 16px 4px",display:"flex",flexDirection:"column",gap:8},children:[y.jsxs(Sn,{type:"primary",ghost:!0,block:!0,icon:y.jsx(d1,{}),onClick:()=>n(i),children:[re("ui.workspaces.selectCurrent")," — ",i.split("/").pop()||i]}),y.jsxs("div",{style:{display:"flex",gap:8},children:[y.jsx(Yu,{size:"small",value:d,onChange:v=>O(v.target.value),onPressEnter:g,placeholder:re("ui.workspaces.pathPlaceholder"),style:{flex:1}}),y.jsx(Sn,{size:"small",onClick:g,children:re("ui.workspaces.goTo")})]})]})]})}function cUe({onLaunch:t}){const[e,n]=f.useState([]),[i,r]=f.useState(!0),[s,o]=f.useState(null),[a,l]=f.useState(!1),c=()=>{fetch(Rn("/api/workspaces")).then(p=>p.json()).then(p=>{n(p.workspaces||[]),r(!1)}).catch(()=>r(!1))};f.useEffect(()=>{c()},[]);const u=p=>{l(!1),fetch(Rn("/api/workspaces/add"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p})}).then(g=>g.json()).then(g=>{g.error?ei.error(g.error):c()}).catch(()=>ei.error("Failed to add workspace"))},d=p=>{fetch(Rn(`/api/workspaces/${p}`),{method:"DELETE"}).then(g=>g.json()).then(()=>c()).catch(()=>{})},O=p=>{o(p.id),fetch(Rn("/api/workspaces/launch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p.path})}).then(g=>g.json()).then(g=>{g.error?(ei.error(g.error),o(null)):t({projectName:g.projectName,path:p.path})}).catch(()=>{ei.error("Launch failed"),o(null)})};return y.jsxs("div",{style:{minHeight:"100vh",background:"#0a0a0a",display:"flex",justifyContent:"center",paddingTop:60},children:[y.jsxs("div",{style:{width:"100%",maxWidth:720,padding:"0 24px"},children:[y.jsxs("div",{style:{marginBottom:32,textAlign:"center"},children:[y.jsxs(sUe,{level:3,style:{color:"#e0e0e0",margin:0},children:[y.jsx(d1,{style:{marginRight:8,color:"#1668dc"}}),re("ui.workspaces.title")]}),y.jsx(Ed,{type:"secondary",style:{fontSize:13},children:re("ui.workspaces.subtitle")})]}),y.jsx("div",{style:{marginBottom:20,textAlign:"center"},children:y.jsx(Sn,{type:"primary",icon:y.jsx(o1,{}),onClick:()=>l(!0),size:"large",children:re("ui.workspaces.browse")})}),i?y.jsx("div",{style:{textAlign:"center",padding:60},children:y.jsx(Da,{})}):e.length===0?y.jsx(Lr,{description:y.jsx(Ed,{type:"secondary",children:re("ui.workspaces.empty")}),style:{marginTop:60}}):y.jsx(c1,{dataSource:e,renderItem:p=>y.jsx(Y2,{size:"small",style:{marginBottom:10,background:"#141414",borderColor:"#2a2a2a",cursor:"pointer"},hoverable:!0,onClick:()=>O(p),children:y.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[y.jsxs("div",{style:{flex:1,minWidth:0},children:[y.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:y.jsx(Ed,{strong:!0,style:{color:"#e0e0e0",fontSize:15},children:p.projectName})}),y.jsx(Ed,{type:"secondary",style:{fontSize:12,wordBreak:"break-all"},children:p.path}),y.jsxs("div",{style:{display:"flex",gap:16,marginTop:6,fontSize:12,color:"#666"},children:[y.jsxs("span",{children:[y.jsx(Dde,{style:{marginRight:4}}),aUe(p.lastUsed)]}),p.logCount>0&&y.jsxs("span",{children:[y.jsx(Vve,{style:{marginRight:4}}),p.logCount," logs (",oUe(p.totalSize),")"]})]})]}),y.jsxs(yl,{children:[y.jsx(Sn,{type:"primary",icon:y.jsx(t0e,{}),loading:s===p.id,onClick:g=>{g.stopPropagation(),O(p)},children:re("ui.workspaces.open")}),y.jsx(GL,{title:re("ui.workspaces.confirmRemove"),onConfirm:g=>{g==null||g.stopPropagation(),d(p.id)},onCancel:g=>g==null?void 0:g.stopPropagation(),okText:"Yes",cancelText:"No",children:y.jsx(Sn,{type:"text",danger:!0,icon:y.jsx(O1,{}),onClick:g=>g.stopPropagation()})})]})]})},p.id)})]}),y.jsx(lUe,{open:a,onClose:()=>l(!1),onSelect:u})]})}const uUe="_layout_1a3p0_1",dUe="_header_1a3p0_6",hUe="_content_1a3p0_14",OUe="_mainContainer_1a3p0_19",fUe="_leftPanel_1a3p0_24",pUe="_leftPanelHeader_1a3p0_32",mUe="_leftPanelCount_1a3p0_43",gUe="_leftPanelBody_1a3p0_49",vUe="_rightPanel_1a3p0_54",$Ue="_modalActions_1a3p0_60",SUe="_spinCenter_1a3p0_64",bUe="_emptyCenter_1a3p0_69",yUe="_logListContainer_1a3p0_79",_Ue="_loadingOverlay_1a3p0_127",xUe="_loadingText_1a3p0_140",QUe="_mobileLoadingOverlay_1a3p0_146",wUe="_mobileLoadingSpinner_1a3p0_158",PUe="_mobileLoadingLabel_1a3p0_171",CUe="_footer_1a3p0_177",kUe="_footerRight_1a3p0_188",TUe="_footerText_1a3p0_196",RUe="_footerLink_1a3p0_201",EUe="_footerIcon_1a3p0_213",XUe="_footerDivider_1a3p0_218",zUe="_guideContainer_1a3p0_226",jUe="_guideContent_1a3p0_234",MUe="_guideTitle_1a3p0_239",NUe="_guideStep_1a3p0_246",IUe="_guideStepNum_1a3p0_252",AUe="_guideStepBody_1a3p0_267",LUe="_guideText_1a3p0_272",WUe="_guideCode_1a3p0_279",VUe="_mobileChatOverlay_1a3p0_292",BUe="_mobileChatOverlayVisible_1a3p0_304",YUe="_mobileChatInner_1a3p0_308",UUe="_mobileGitDiffOverlay_1a3p0_316",DUe="_mobileGitDiffOverlayVisible_1a3p0_328",qUe="_mobileGitDiffInner_1a3p0_332",ZUe="_mobileMenuBtn_1a3p0_340",FUe="_mobileMenuOverlay_1a3p0_357",GUe="_mobileMenuDropdown_1a3p0_363",HUe="_mobileMenuItem_1a3p0_377",KUe="_mobileStatsOverlay_1a3p0_395",JUe="_mobileStatsOverlayVisible_1a3p0_407",eDe="_mobileStatsInner_1a3p0_411",tDe="_mobileLogMgmtOverlay_1a3p0_418",nDe="_mobileLogMgmtOverlayVisible_1a3p0_430",iDe="_mobileLogMgmtHeader_1a3p0_434",rDe="_mobileLogMgmtTitle_1a3p0_443",sDe="_mobileLogMgmtClose_1a3p0_449",oDe="_mobileLogMgmtActions_1a3p0_464",aDe="_mobileLogMgmtBody_1a3p0_472",lDe="_mobileSettingsOverlay_1a3p0_479",cDe="_mobileSettingsOverlayVisible_1a3p0_491",uDe="_mobilePromptOverlay_1a3p0_495",dDe="_mobilePromptOverlayVisible_1a3p0_507",hDe="_mobilePromptBody_1a3p0_511",ODe="_mobilePromptList_1a3p0_519",fDe="_mobilePromptItem_1a3p0_525",pDe="_mobilePromptTimestamp_1a3p0_530",mDe="_mobilePromptCard_1a3p0_537",gDe="_mobilePromptPreText_1a3p0_545",vDe="_previewPopover_1a3p0_555",$De="_previewItem_1a3p0_561",SDe="_previewText_1a3p0_573",yt={layout:uUe,header:dUe,content:hUe,mainContainer:OUe,leftPanel:fUe,leftPanelHeader:pUe,leftPanelCount:mUe,leftPanelBody:gUe,rightPanel:vUe,modalActions:$Ue,spinCenter:SUe,emptyCenter:bUe,logListContainer:yUe,loadingOverlay:_Ue,loadingText:xUe,mobileLoadingOverlay:QUe,mobileLoadingSpinner:wUe,mobileLoadingLabel:PUe,footer:CUe,footerRight:kUe,footerText:TUe,footerLink:RUe,footerIcon:EUe,footerDivider:XUe,guideContainer:zUe,guideContent:jUe,guideTitle:MUe,guideStep:NUe,guideStepNum:IUe,guideStepBody:AUe,guideText:LUe,guideCode:WUe,mobileChatOverlay:VUe,mobileChatOverlayVisible:BUe,mobileChatInner:YUe,mobileGitDiffOverlay:UUe,mobileGitDiffOverlayVisible:DUe,mobileGitDiffInner:qUe,mobileMenuBtn:ZUe,mobileMenuOverlay:FUe,mobileMenuDropdown:GUe,mobileMenuItem:HUe,mobileStatsOverlay:KUe,mobileStatsOverlayVisible:JUe,mobileStatsInner:eDe,mobileLogMgmtOverlay:tDe,mobileLogMgmtOverlayVisible:nDe,mobileLogMgmtHeader:iDe,mobileLogMgmtTitle:rDe,mobileLogMgmtClose:sDe,mobileLogMgmtActions:oDe,mobileLogMgmtBody:aDe,mobileSettingsOverlay:lDe,mobileSettingsOverlayVisible:cDe,mobilePromptOverlay:uDe,mobilePromptOverlayVisible:dDe,mobilePromptBody:hDe,mobilePromptList:ODe,mobilePromptItem:fDe,mobilePromptTimestamp:pDe,mobilePromptCard:mDe,mobilePromptPreText:gDe,previewPopover:vDe,previewItem:$De,previewText:SDe},bDe="ccv_entryCache",Vu="entries",H5="cache",K5="ccv_cacheMeta",yDe=1,_De=10080*60*1e3;let Fh=null,Gh=null;function J5(){return Fh?Promise.resolve(Fh):Gh||(Gh=new Promise((t,e)=>{const n=indexedDB.open(bDe,yDe);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Vu)||i.createObjectStore(Vu)},n.onsuccess=()=>{Fh=n.result,Fh.onclose=()=>{Fh=null},Gh=null,t(Fh)},n.onerror=()=>{Gh=null,e(n.error)}}),Gh)}let T9=0;function xDe(t,e){try{const n=e[e.length-1],i=(n==null?void 0:n.timestamp)||null;i&&localStorage.setItem(K5,JSON.stringify({projectName:t,lastTs:i,count:e.length}))}catch{}}function QDe(){try{localStorage.removeItem(K5)}catch{}}function wDe(){try{const t=localStorage.getItem(K5);if(!t)return null;const e=JSON.parse(t);return e!=null&&e.lastTs&&(e==null?void 0:e.count)>0&&(e!=null&&e.projectName)?e:null}catch{return null}}async function iw(t,e){if(!t||!Array.isArray(e)||e.length===0)return;const n=++T9;try{const i=await J5();return n!==T9?void 0:(xDe(t,e),new Promise(r=>{const s=i.transaction(Vu,"readwrite");s.objectStore(Vu).put({projectName:t,entries:e,ts:Date.now()},H5),s.oncomplete=()=>r(),s.onerror=()=>r()}))}catch{}}async function PDe(t){try{const e=await J5();return new Promise(n=>{const r=e.transaction(Vu,"readonly").objectStore(Vu).get(H5);r.onsuccess=()=>{const s=r.result;!s||s.projectName!==t||!Array.isArray(s.entries)||s.entries.length===0?n(null):s.ts&&Date.now()-s.ts>_De?(Yk(),n(null)):n(s.entries)},r.onerror=()=>n(null)})}catch{return null}}async function Yk(){QDe();try{const t=await J5();return new Promise(e=>{const n=t.transaction(Vu,"readwrite");n.objectStore(Vu).delete(H5),n.oncomplete=()=>e(),n.onerror=()=>e()})}catch{}}const mO=class mO extends ne.Component{constructor(n){super(n);gt(this,"_flushPendingEntries",()=>{this._flushRafId=null;const n=this._pendingEntries;this._pendingEntries=[],n.length!==0&&this.setState(i=>{var c,u;const r=[...i.requests];let s=i.cacheExpireAt,o=i.cacheType,a=i.mainAgentSessions;for(const d of n){const O=`${d.timestamp}|${d.url}`,p=this._requestIndexMap.get(O);if(p!==void 0?r[p]=d:(this._requestIndexMap.set(O,r.length),r.push(d)),wr(d)){const g=(u=(c=d.response)==null?void 0:c.body)==null?void 0:u.usage;if(g!=null&&g.cache_creation){const v=g.cache_creation,$=d.timestamp?new Date(d.timestamp).getTime():Date.now();let S=null,_=null;if(v.ephemeral_1h_input_tokens>0?(S=$+3600*1e3,_="1h"):v.ephemeral_5m_input_tokens>0&&(S=$+300*1e3,_="5m"),S&&S>Date.now()){s=S;const x=(g.cache_read_input_tokens||0)+(g.cache_creation_input_tokens||0);o=x>0?$i(x):_,localStorage.setItem("ccv_cacheExpireAt",String(s)),localStorage.setItem("ccv_cacheType",o)}}}if(wr(d)&&d.body&&Array.isArray(d.body.messages)){const g=d.timestamp||new Date().toISOString(),v=a.length>0?a[a.length-1]:null,$=(v==null?void 0:v.messages)||[],S=d.body.messages,_=$.length,x=_>0&&S.length<_*.5&&_-S.length>4;for(let Q=0;Q<S.length;Q++)!x&&Q<_&&$[Q]._timestamp?S[Q]._timestamp=$[Q]._timestamp:S[Q]._timestamp||(S[Q]._timestamp=g);a=this.mergeMainAgentSessions(a,d)}}return this._cacheLossMapSource=null,i.selectedIndex===null&&r.length>0&&(this._autoSelectTimer&&clearTimeout(this._autoSelectTimer),this._autoSelectTimer=setTimeout(()=>{this.setState(d=>{if(d.selectedIndex===null&&d.requests.length>0){const O=d.showAll?d.requests:ra(d.requests);return O.length>0?{selectedIndex:O.length-1}:null}return null})},200)),{requests:r,cacheExpireAt:s,cacheType:o,mainAgentSessions:a}},()=>{ki&&this.state.projectName&&(this._cacheSaveTimer&&clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=setTimeout(()=>{this.state.projectName&&iw(this.state.projectName,this.state.requests)},5e3))})});gt(this,"handleSelectRequest",n=>{this.setState({selectedIndex:n,scrollCenter:!1})});gt(this,"handleViewRequest",n=>{this.setState({viewMode:"raw",selectedIndex:n,scrollCenter:!0})});gt(this,"handleScrollDone",()=>{this.setState({scrollCenter:!1})});gt(this,"handleCacheHighlightDone",()=>{this.setState({pendingCacheHighlight:null})});gt(this,"handleScrollTsDone",()=>{this.setState({chatScrollToTs:null})});gt(this,"handleViewInChat",()=>{this.setState(n=>{const r=(n.showAll?n.requests:ra(n.requests))[n.selectedIndex];if(!r)return null;let s=null;if(wr(r)&&r.timestamp)s=r.timestamp;else{const o=zu(r);if((o.type==="SubAgent"||o.type==="Teammate")&&r.timestamp)s=r.timestamp;else{const a=n.requests.indexOf(r);a>=0&&(s=a6(n.requests,a))}s||ei.info(re("ui.cannotMap"))}return{viewMode:"chat",chatScrollToTs:s}})});gt(this,"handleWorkspaceLaunch",({projectName:n})=>{this._isLocalLog=!1,this._localLogFile=null,this.setState({workspaceMode:!1,projectName:n,viewMode:"chat",cliMode:!0})});gt(this,"handleReturnToWorkspaces",()=>{fetch(Rn("/api/workspaces/stop"),{method:"POST"}).then(()=>{this._rebuildRequestIndex([]),this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null})}).catch(()=>{})});gt(this,"handleToggleViewMode",()=>{this.setState(n=>{const i=n.viewMode==="raw"?"chat":"raw";if(i==="raw"){if(n.selectedIndex===null){const o=n.showAll?n.requests:ra(n.requests);return{viewMode:i,selectedIndex:o.length>0?o.length-1:null,scrollCenter:!0}}return{viewMode:i,scrollCenter:!0}}const r=n.showAll?n.requests:ra(n.requests),s=n.selectedIndex!=null?r[n.selectedIndex]:null;if(s){let o=null;if(wr(s)&&s.timestamp)o=s.timestamp;else{const a=zu(s);if((a.type==="SubAgent"||a.type==="Teammate")&&s.timestamp)o=s.timestamp;else{const l=n.requests.indexOf(s);l>=0&&(o=a6(n.requests,l)),o||ei.info(re("ui.cannotMap"))}}return{viewMode:i,chatScrollToTs:o}}return{viewMode:i,chatScrollToTs:null}})});gt(this,"handleLangChange",()=>{const n=km();this.setState({lang:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:n})}).catch(()=>{})});gt(this,"handleCollapseToolResultsChange",n=>{this.setState({collapseToolResults:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({collapseToolResults:n})}).catch(()=>{})});gt(this,"handleExpandThinkingChange",n=>{this.setState({expandThinking:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandThinking:n})}).catch(()=>{})});gt(this,"handleExpandDiffChange",n=>{this.setState({expandDiff:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandDiff:n})}).catch(()=>{})});gt(this,"handleFilterIrrelevantChange",n=>{this.setState(i=>{const r=!n,s=r?i.requests:ra(i.requests);return{showAll:r,selectedIndex:s.length>0?s.length-1:null}}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filterIrrelevant:n})}).catch(()=>{})});gt(this,"handleExportPromptsTxt",n=>{if(!n||n.length===0)return;const i=[];for(const a of n){const l=[],c=a.timestamp?new Date(a.timestamp).toLocaleString():"";c&&l.push(`${c}:
|
|
933
|
+
`).length,w=Q-x;if(v.plainText=v.plainText.substring(0,$)+g+v.plainText.substring($+p.length),w!==0){const C=v.lineNums[_]||_+1,T=[];for(let z=0;z<Q;z++)T.push(C+z);v.lineNums=[...v.lineNums.slice(0,_),...T,...v.lineNums.slice(_+x).map(z=>z+w)]}}}}}const o={},a={};for(const u of t)if(u.role==="user"&&Array.isArray(u.content)){for(const d of u.content)if(d.type==="tool_result"){const O=e[d.tool_use_id];if(O&&O.name==="AskUserQuestion"){const p=Ep(d);o[d.tool_use_id]=OYe(p)}if(O&&O.name==="ExitPlanMode"){const p=Ep(d);a[d.tool_use_id]=fYe(p)}}}return{toolUseMap:e,toolResultMap:n,readContentMap:i,editSnapshotMap:r,askAnswerMap:o,planApprovalMap:a}}function OYe(t){const e={},n=/"([^"]+)"="([^"]*)"/g;let i;for(;(i=n.exec(t))!==null;)e[i[1]]=i[2];return e}function fYe(t){if(!t)return{status:"pending"};if(/User has approved/i.test(t))return{status:"approved"};if(/User rejected/i.test(t)){const e=t.match(/feedback:\s*(.+)/i)||t.match(/User rejected[^:]*:\s*(.+)/i);return{status:"rejected",feedback:e?e[1].trim():""}}return{status:"pending"}}class C9 extends ne.Component{constructor(n){super(n);gt(this,"handleStickToBottom",()=>{this.setState({stickyBottom:!0},()=>{const n=this.containerRef.current;n&&(n.scrollTop=n.scrollHeight)})});gt(this,"handleLoadMore",()=>{this._mobileExtraItems+=dYe;const n=this.containerRef.current,i=n?n.scrollHeight:0,r=n?n.scrollTop:0,s=this.buildAllItems(),o=this._applyMobileSlice(s);this.setState({allItems:o,visibleCount:o.length},()=>{if(n){const a=n.scrollHeight;n.scrollTop=r+(a-i)}})});gt(this,"handlePromptOptionClick",n=>{const i=this._inputWs;if(!i||i.readyState!==WebSocket.OPEN)return;const r=this.state.ptyPrompt;if(!r)return;const s=r.options,o=s.findIndex(O=>O.number===n);let a=s.findIndex(O=>O.selected);a<0&&(a=0);const l=o-a,c=l>0?"\x1B[B":"\x1B[A",u=Math.abs(l),d=O=>{O<u?(i.send(JSON.stringify({type:"input",data:c})),setTimeout(()=>d(O+1),30)):setTimeout(()=>{i.readyState===WebSocket.OPEN&&i.send(JSON.stringify({type:"input",data:"\r"}))},50)};d(0),this._currentPtyPrompt=null,this.setState(O=>{const p=O.ptyPromptHistory.slice(),g=p[p.length-1];return g&&g.status==="active"&&(p[p.length-1]={...g,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:p}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});gt(this,"handlePlanFeedbackSubmit",(n,i)=>{const r=this._inputWs;if(!r||r.readyState!==WebSocket.OPEN)return;const s=this.state.ptyPrompt;if(!s)return;const o=s.options,a=o.findIndex(p=>p.number===n);let l=o.findIndex(p=>p.selected);l<0&&(l=0);const c=a-l,u=c>0?"\x1B[B":"\x1B[A",d=Math.abs(c),O=p=>{p<d?(r.send(JSON.stringify({type:"input",data:u})),setTimeout(()=>O(p+1),30)):setTimeout(()=>{r.send(JSON.stringify({type:"input",data:"\r"}));const g=this._ptyBuffer;let v=0;const $=()=>{if(v++,v>20||this._ptyBuffer!==g){r.readyState===WebSocket.OPEN&&(r.send(JSON.stringify({type:"input",data:i})),setTimeout(()=>{r.send(JSON.stringify({type:"input",data:"\r"}))},50));return}setTimeout($,100)};setTimeout($,100)},50)};O(0),this._currentPtyPrompt=null,this.setState(p=>{const g=p.ptyPromptHistory.slice(),v=g[g.length-1];return v&&v.status==="active"&&(g[g.length-1]={...v,status:"answered",selectedNumber:n}),{ptyPrompt:null,ptyPromptHistory:g}}),this._ptyBuffer="",this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer)});gt(this,"handleAskQuestionSubmit",n=>{const i=this._inputWs;if(!i||i.readyState!==WebSocket.OPEN){this._askAnswerQueue=this._planSubmissionSteps(n),this._askSubmitting=!0,this.connectInputWs(),this._askWsRetries=0,this._waitForWsAndSubmit();return}if(this._askAnswerQueue=this._planSubmissionSteps(n),this._askSubmitting=!0,!this._currentPtyPrompt){this._askPromptRetries=0,this._waitForPtyPromptAndSubmit();return}this._processNextAskAnswer()});gt(this,"handleInputSend",()=>{const n=this._inputRef.current;if(!n)return;const i=n.value.trim();i&&this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&(this._inputWs.send(JSON.stringify({type:"input",data:i})),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:i,inputSuggestion:null},()=>this.scrollToBottom()))});gt(this,"handleInputKeyDown",n=>{if(n.key==="Tab"&&this.state.inputSuggestion){n.preventDefault();const i=this._inputRef.current;i&&(i.value=this.state.inputSuggestion,i.style.height="auto",i.style.height=Math.min(i.scrollHeight,120)+"px"),this.setState({inputSuggestion:null,inputEmpty:!1});return}n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleInputSend())});gt(this,"handleInputChange",n=>{const i=n.target;i.style.height="auto",i.style.height=Math.min(i.scrollHeight,120)+"px";const r=!i.value.trim();this.setState({inputEmpty:r}),this.state.inputSuggestion&&!r&&this.setState({inputSuggestion:null})});gt(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()))});gt(this,"handleSplitMouseDown",n=>{n.preventDefault(),this._resizing=!0;const r=!window.location.search.includes("token=");let s=[];if(r){const l=this.innerSplitRef.current;if(l){const u=l.getBoundingClientRect().width,d=7.8,O=[60,80,100,120],p=5;s=O.map(g=>{const v=g*d,$=v+p;if($>u*.75||$<u*.15)return null;const S=u-v-p;return{cols:g,terminalPx:v,linePosition:S}}).filter(g=>g!==null)}}this.setState({isDragging:!0,snapLines:s});const o=l=>{if(!this._resizing)return;const c=this.innerSplitRef.current;if(!c)return;const u=c.getBoundingClientRect(),d=u.width;let O=u.right-l.clientX;O=Math.max(200,Math.min(d*.75,O));let p=null;if(r&&s.length>0){let v=1/0,$=null;for(const S of s){const _=Math.abs(l.clientX-u.left-S.linePosition);_<v&&(v=_,$=S)}$&&v<60&&(p=$)}this.setState({terminalWidth:O,activeSnapLine:p})},a=()=>{if(this._resizing=!1,r&&this.state.activeSnapLine){const l=this.state.activeSnapLine.terminalPx;localStorage.setItem("cc-viewer-terminal-width",l.toString()),this.setState({terminalWidth:l,isDragging:!1,activeSnapLine:null,snapLines:[],needsInitialSnap:!1})}else localStorage.setItem("cc-viewer-terminal-width",this.state.terminalWidth.toString()),this.setState({isDragging:!1,activeSnapLine:null,snapLines:[],needsInitialSnap:!1});document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",a),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",o),document.addEventListener("mouseup",a),document.body.style.cursor="col-resize",document.body.style.userSelect="none"});gt(this,"handleToggleExpandPath",n=>{this.setState(i=>{const r=new Set(i.fileExplorerExpandedPaths);return r.has(n)?r.delete(n):r.add(n),{fileExplorerExpandedPaths:r}})});this.containerRef=ne.createRef(),this.splitContainerRef=ne.createRef(),this.innerSplitRef=ne.createRef();const i=localStorage.getItem("cc-viewer-terminal-width"),r=i?parseFloat(i):null;this.state={visibleCount:0,loading:!1,allItems:[],highlightTs:null,highlightFading:!1,terminalWidth:r||624,needsInitialSnap:r===null,inputEmpty:!0,pendingInput:null,stickyBottom:!0,ptyPrompt:null,ptyPromptHistory:[],inputSuggestion:null,fileExplorerOpen:localStorage.getItem("ccv_fileExplorerOpen")!=="false",currentFile:null,currentGitDiff:null,scrollToLine:null,fileExplorerExpandedPaths:new Set,gitChangesOpen:!1,snapLines:[],activeSnapLine:null,isDragging:!1,fileVersion:0,editorSessionId:null,editorFilePath:null,fileExplorerRefresh:0,gitChangesRefresh:0},this._processedToolIds=new Set,this._fileRefreshTimer=null,this._gitRefreshTimer=null,this._queueTimer=null,this._prevItemsLen=0,this._scrollTargetIdx=null,this._scrollTargetRef=ne.createRef(),this._scrollFadeTimer=null,this._resizing=!1,this._inputWs=null,this._inputRef=ne.createRef(),this._ptyBuffer="",this._ptyDataSeq=0,this._ptyDebounceTimer=null,this._currentPtyPrompt=null,this._mobileExtraItems=0,this._mobileSliceOffset=0,this._totalItemCount=0}_setFileExplorerOpen(n){localStorage.setItem("ccv_fileExplorerOpen",String(n)),this.setState({fileExplorerOpen:n})}_checkToolFileChanges(){var s,o;const n=this.props.mainAgentSessions;if(!n||n.length===0)return;let i=!1,r=!1;for(const a of n){const l=[];if((o=(s=a.response)==null?void 0:s.body)!=null&&o.content&&l.push(a.response.body.content),Array.isArray(a.messages))for(const c of a.messages)c.role==="assistant"&&Array.isArray(c.content)&&l.push(c.content);for(const c of l)for(const u of c){if(u.type!=="tool_use"||!u.id||this._processedToolIds.has(u.id))continue;this._processedToolIds.add(u.id);const d=u.name;let O=u.input;if(typeof O=="string")try{O=JSON.parse(O.replace(/^\[object Object\]/,""))}catch{O={}}d==="Write"?(i=!0,r=!0):d==="Edit"||d==="NotebookEdit"?r=!0:d==="Bash"&&O&&O.command&&uYe(O.command)&&(i=!0,r=!0)}}i&&this.state.fileExplorerOpen&&(clearTimeout(this._fileRefreshTimer),this._fileRefreshTimer=setTimeout(()=>{this.setState(a=>({fileExplorerRefresh:a.fileExplorerRefresh+1}))},500)),r&&this.state.gitChangesOpen&&(clearTimeout(this._gitRefreshTimer),this._gitRefreshTimer=setTimeout(()=>{this.setState(a=>({gitChangesRefresh:a.gitChangesRefresh+1}))},500))}componentDidMount(){this.startRender(),this.props.cliMode&&this.connectInputWs(),this._bindStickyScroll(),this.state.needsInitialSnap&&this.props.cliMode&&this.props.terminalVisible&&this._snapToInitialPosition()}shouldComponentUpdate(n,i){return n.requests!==this.props.requests||n.mainAgentSessions!==this.props.mainAgentSessions||n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking||n.scrollToTimestamp!==this.props.scrollToTimestamp||n.cliMode!==this.props.cliMode||n.terminalVisible!==this.props.terminalVisible||n.userProfile!==this.props.userProfile||i!==this.state}componentDidUpdate(n){if(n.mainAgentSessions!==this.props.mainAgentSessions)ki&&(this._mobileExtraItems=0),this.startRender(),this.state.pendingInput&&this.setState({pendingInput:null}),this._updateSuggestion(),this._checkToolFileChanges();else if(n.collapseToolResults!==this.props.collapseToolResults||n.expandThinking!==this.props.expandThinking){const i=this.buildAllItems(),r=this._applyMobileSlice(i);this.setState({allItems:r,visibleCount:r.length})}if(!n.scrollToTimestamp&&this.props.scrollToTimestamp)if(ki&&this.props.scrollToTimestamp){const i=this.buildAllItems(),r=this._scrollTargetIdx;if(r!=null){const o=nw+this._mobileExtraItems,a=i.length>o?i.length-o:0;r<a&&(this._mobileExtraItems=i.length-r-nw,this._mobileExtraItems<0&&(this._mobileExtraItems=0))}const s=this._applyMobileSlice(i);this.setState({allItems:s,visibleCount:s.length},()=>this.scrollToBottom())}else{const i=this.buildAllItems(),r=this._applyMobileSlice(i);this.setState({allItems:r,visibleCount:r.length},()=>this.scrollToBottom())}ki&&this.props.mobileChatVisible&&!n.mobileChatVisible&&requestAnimationFrame(()=>{const i=this.containerRef.current;i&&(i.scrollTop=i.scrollHeight)}),!n.cliMode&&this.props.cliMode&&this.connectInputWs(),this._rebindStickyEl()}componentWillUnmount(){this._queueTimer&&clearTimeout(this._queueTimer),this._fadeClearTimer&&clearTimeout(this._fadeClearTimer),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._fileRefreshTimer&&clearTimeout(this._fileRefreshTimer),this._gitRefreshTimer&&clearTimeout(this._gitRefreshTimer),this._unbindScrollFade(),this._unbindStickyScroll(),this._inputWs&&(this._inputWs.close(),this._inputWs=null)}startRender(){this._queueTimer&&clearTimeout(this._queueTimer);const n=this.buildAllItems(),i=this._applyMobileSlice(n),r=this._prevItemsLen;this._prevItemsLen=i.length;const s=i.length-r;if(s<=0||r>0&&s<=3){this.setState({allItems:i,visibleCount:i.length,loading:!1},()=>this.scrollToBottom());return}if(i.length>oYe)this.setState({allItems:i,visibleCount:0,loading:!0}),this._queueTimer=setTimeout(()=>{this.setState({visibleCount:i.length,loading:!1},()=>this.scrollToBottom())},300);else{const o=Math.max(0,r);this.setState({allItems:i,visibleCount:o,loading:!1}),this.queueNext(o,i.length)}}queueNext(n,i){n>=i||(this._queueTimer=setTimeout(()=>{this.setState({visibleCount:n+1},()=>{this.scrollToBottom(),this.queueNext(n+1,i)})},hYe()))}_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,i=this.containerRef.current;i&&n.offsetHeight>i.clientHeight?n.scrollIntoView({block:"start",behavior:"instant"}):n.scrollIntoView({block:"center",behavior:"instant"});const r=this.props.scrollToTimestamp;this._scrollTargetRef=ne.createRef(),r&&(this.setState({highlightTs:r,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 i=n.scrollHeight-n.scrollTop-n.clientHeight;this.state.stickyBottom&&i>30?this.setState({stickyBottom:!1}):!this.state.stickyBottom&&i<=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,i,r,s){const{userProfile:o,collapseToolResults:a,expandThinking:l,onViewRequest:c}=this.props,{toolResultMap:u,readContentMap:d,editSnapshotMap:O,askAnswerMap:p,planApprovalMap:g}=P9(n),v=this.props.cliMode&&this.state.ptyPromptHistory.slice().reverse().find(x=>W$(x)&&x.status==="active")||null;let $=null,S=null;for(const x of n)if(x.role==="assistant"&&Array.isArray(x.content))for(const Q of x.content){if(Q.type==="tool_use"&&Q.name==="ExitPlanMode"){const w=g[Q.id];(!w||w.status==="pending")&&($=Q.id)}if(Q.type==="tool_use"&&Q.name==="AskUserQuestion"){const w=p[Q.id];(!w||Object.keys(w).length===0)&&(S=Q.id)}}const _=[];for(let x=0;x<n.length;x++){const Q=n[x],w=Q.content,C=Q._timestamp||null,T=C?s[C]:void 0,z=T!=null&&c?{requestIndex:T,onViewRequest:c}:{};if(Q.role==="user"){if(Array.isArray(w)){const R=w.find(I=>I.type==="text"&&/^\[SUGGESTION MODE:/i.test((I.text||"").trim())),L=w.filter(I=>I.type==="tool_result");if(!(R&&L.length>0)){const{commands:I,textBlocks:E,skillBlocks:X}=aT(w);for(let k=0;k<I.length;k++)_.push(y.jsx(sl,{role:"user",text:I[k],timestamp:C,userProfile:o,modelInfo:r,...z},`${i}-cmd-${x}-${k}`));for(const k of X){const j=k.text.match(/^#\s+(.+)$/m),N=j?j[1]:"Skill";_.push(y.jsx(sl,{role:"skill-loaded",text:k.text,skillName:N,timestamp:C,...z},`${i}-skill-${x}`))}for(let k=0;k<E.length;k++){const j=/^Implement the following plan:/i.test((E[k].text||"").trim());_.push(y.jsx(sl,{role:j?"plan-prompt":"user",text:E[k].text,timestamp:C,userProfile:o,modelInfo:r,...z},`${i}-user-${x}-${k}`))}}}else if(typeof w=="string"&&!Qu(w)){const R=/^Implement the following plan:/i.test(w.trim());_.push(y.jsx(sl,{role:R?"plan-prompt":"user",text:w,timestamp:C,userProfile:o,modelInfo:r,...z},`${i}-user-${x}`))}}else Q.role==="assistant"&&(Array.isArray(w)?_.push(y.jsx(sl,{role:"assistant",content:w,toolResultMap:u,readContentMap:d,editSnapshotMap:O,askAnswerMap:p,planApprovalMap:g,timestamp:C,modelInfo:r,collapseToolResults:a,expandThinking:l,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:v,lastPendingPlanId:$,lastPendingAskId:S,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,...z},`${i}-asst-${x}`)):typeof w=="string"&&_.push(y.jsx(sl,{role:"assistant",content:[{type:"text",text:w}],toolResultMap:u,readContentMap:d,editSnapshotMap:O,askAnswerMap:p,planApprovalMap:g,timestamp:C,modelInfo:r,collapseToolResults:a,expandThinking:l,ptyPrompt:this.state.ptyPrompt,activePlanPrompt:v,lastPendingPlanId:$,lastPendingAskId:S,onPlanApprovalClick:this.handlePromptOptionClick,onPlanFeedbackSubmit:this.handlePlanFeedbackSubmit,onAskQuestionSubmit:this.handleAskQuestionSubmit,cliMode:this.props.cliMode,...z},`${i}-asst-${x}`)))}return _}buildAllItems(){var v,$,S,_,x;const{mainAgentSessions:n,requests:i,collapseToolResults:r,expandThinking:s,onViewRequest:o}=this.props;if(!n||n.length===0)return[];const a={};if(i)for(let Q=0;Q<i.length;Q++)wr(i[Q])&&i[Q].timestamp&&(a[i[Q].timestamp]=Q);let l=null;if(i){for(let Q=i.length-1;Q>=0;Q--)if(wr(i[Q])&&((v=i[Q].body)!=null&&v.model)){l=i[Q].body.model;break}}const c=Q0e(l),u=[],d={},O=[];if(i)for(let Q=0;Q<i.length;Q++){const w=i[Q];if(!w.timestamp)continue;const C=zu(w,i[Q+1]);if(C.type==="SubAgent"||C.type==="Teammate"){const T=(S=($=w.response)==null?void 0:$.body)==null?void 0:S.content;if(Array.isArray(T)&&T.length>0){const z=P9(((_=w.body)==null?void 0:_.messages)||[]).toolResultMap,R=C.type==="Teammate";O.push({timestamp:w.timestamp,content:T,toolResultMap:z,label:R?X0e(C.subType,(x=w.body)==null?void 0:x.model):wP(C.type,C.subType),isTeammate:R,requestIndex:Q})}}}let p=0;n.forEach((Q,w)=>{var T,z,R,L;w>0&&u.push(y.jsx(JX,{style:{borderColor:"#333",margin:"16px 0"},children:y.jsx(w9,{className:Nn.sessionDividerText,children:"Session"})},`session-div-${w}`));const C=this.renderSessionMessages(Q.messages,`s${w}`,c,a);for(const I of C){const E=I.props.timestamp;for(;p<O.length&&E&&O[p].timestamp<=E;){const X=O[p];X.timestamp&&(d[X.timestamp]=u.length),u.push(y.jsx(sl,{role:"sub-agent-chat",content:X.content,toolResultMap:X.toolResultMap,label:X.label,isTeammate:X.isTeammate,timestamp:X.timestamp,collapseToolResults:r,expandThinking:s,requestIndex:X.requestIndex,onViewRequest:o},`sub-chat-${p}`)),p++}E&&(d[E]=u.length),u.push(I)}for(;p<O.length;){const I=O[p],E=w<n.length-1&&((z=(T=n[w+1].messages)==null?void 0:T[0])==null?void 0:z._timestamp);if(E&&I.timestamp>E)break;I.timestamp&&(d[I.timestamp]=u.length),u.push(y.jsx(sl,{role:"sub-agent-chat",content:I.content,toolResultMap:I.toolResultMap,label:I.label,isTeammate:I.isTeammate,timestamp:I.timestamp,collapseToolResults:r,expandThinking:s,requestIndex:I.requestIndex,onViewRequest:o},`sub-chat-${p}`)),p++}if(w===n.length-1&&((L=(R=Q.response)==null?void 0:R.body)!=null&&L.content)){const I=Q.response.body.content;if(Array.isArray(I)){u.push(y.jsx(ne.Fragment,{children:y.jsx(JX,{style:{borderColor:"#2a2a2a",margin:"8px 0"},children:y.jsx(w9,{type:"secondary",className:Nn.lastResponseLabel,children:re("ui.lastResponse")})})},"resp-divider")),Q.entryTimestamp&&(d[Q.entryTimestamp]=u.length);let E=null;for(const X of I)X.type==="tool_use"&&X.name==="AskUserQuestion"&&(E=X.id);u.push(y.jsx(sl,{role:"assistant",content:I,timestamp:Q.entryTimestamp,modelInfo:c,collapseToolResults:r,expandThinking:s,toolResultMap:{},askAnswerMap:{},lastPendingAskId:E,cliMode:this.props.cliMode,onAskQuestionSubmit:this.handleAskQuestionSubmit},"resp-asst"))}}});const{scrollToTimestamp:g}=this.props;return this._scrollTargetIdx=g&&d[g]!=null?d[g]:null,this._tsItemMap=d,u}_applyMobileSlice(n){if(!ki)return this._mobileSliceOffset=0,this._totalItemCount=n.length,n;this._totalItemCount=n.length;const i=nw+this._mobileExtraItems;if(n.length<=i)return this._mobileSliceOffset=0,n;const r=n.length-i;if(this._mobileSliceOffset=r,this._scrollTargetIdx!=null&&(this._scrollTargetIdx-=r,this._scrollTargetIdx<0&&(this._scrollTargetIdx=null)),this._tsItemMap){const s={};for(const[o,a]of Object.entries(this._tsItemMap)){const l=a-r;l>=0&&(s[o]=l)}this._tsItemMap=s}return n.slice(r)}_extractSuggestion(){var O;const{mainAgentSessions:n}=this.props;if(!(n!=null&&n.length))return null;const i=n[n.length-1],r=i==null?void 0:i.messages;if(!Array.isArray(r)||r.length===0)return null;const s=r[r.length-1];if((s==null?void 0:s.role)!=="user")return null;const o=s.content;if(!(Array.isArray(o)?o.some(p=>p.type==="text"&&/^\[SUGGESTION MODE:/i.test((p.text||"").trim())):typeof o=="string"&&/^\[SUGGESTION MODE:/im.test(o.trim())))return null;const l=i==null?void 0:i.response;if(!l)return null;const c=l.body;if(!c)return null;const u=c.stop_reason;if(u!=="end_turn"&&u!=="max_tokens")return null;const d=c.content;if(!Array.isArray(d))return null;for(let p=d.length-1;p>=0;p--)if(d[p].type==="text"&&((O=d[p].text)!=null&&O.trim()))return d[p].text.trim();return null}_updateSuggestion(){const n=this._extractSuggestion();this.setState({inputSuggestion:n||null})}connectInputWs(){const i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/terminal`;this._inputWs=new WebSocket(i),this._inputWs.onmessage=r=>{try{const s=JSON.parse(r.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 i=this._stripAnsi(n);this._ptyBuffer+=i,this._ptyDataSeq++,this._ptyBuffer.length>4096&&(this._ptyBuffer=this._ptyBuffer.slice(-4096)),this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._ptyDebounceTimer=setTimeout(()=>this._detectPrompt(),200)}_detectPrompt(){const i=this._ptyBuffer.match(/([^\n]*\?)\s*\n((?:\s*[❯>]?\s*\d+\.\s+[^\n]+\n?){2,})$/);if(i){const r=i[1].trim(),o=i[2].match(/\s*([❯>])?\s*(\d+)\.\s+([^\n]+)/g);if(o){const a=o.map(u=>{const d=u.match(/\s*([❯>])?\s*(\d+)\.\s+(.+)/);return{number:parseInt(d[2],10),text:d[3].trim(),selected:!!d[1]}}),l=this.state.ptyPrompt,c={question:r,options:a};l&&l.question===r?(this._currentPtyPrompt=c,this.setState({ptyPrompt:c})):(this._currentPtyPrompt=c,this.setState(u=>{const d=u.ptyPromptHistory.slice();if(u.ptyPrompt){const O=d[d.length-1];O&&O.status==="active"&&(d[d.length-1]={...O,status:"dismissed"})}return d.push({...c,status:"active",selectedNumber:null,timestamp:new Date().toISOString()}),{ptyPrompt:c,ptyPromptHistory:d}}),this.scrollToBottom());return}}if(this.state.ptyPrompt){if(W$(this.state.ptyPrompt)||this._askSubmitting)return;this._currentPtyPrompt=null,this.setState(r=>{const s=r.ptyPromptHistory.slice(),o=s[s.length-1];return o&&o.status==="active"&&(s[s.length-1]={...o,status:"dismissed"}),{ptyPrompt:null,ptyPromptHistory:s}})}}_clearPtyPrompt(){this._ptyBuffer="",this._currentPtyPrompt=null,this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this.state.ptyPrompt&&this.setState({ptyPrompt:null})}_planSubmissionSteps(n){return n.map((i,r)=>({...i,isLast:r===n.length-1}))}_waitForWsAndSubmit(){if(this._askWsRetries=(this._askWsRetries||0)+1,this._askWsRetries>30){this._askSubmitting=!1,this._askAnswerQueue=[];return}if(this._inputWs&&this._inputWs.readyState===WebSocket.OPEN){this._currentPtyPrompt?this._processNextAskAnswer():(this._askPromptRetries=0,this._waitForPtyPromptAndSubmit());return}setTimeout(()=>this._waitForWsAndSubmit(),100)}_waitForPtyPromptAndSubmit(){if(this._askPromptRetries=(this._askPromptRetries||0)+1,this._askPromptRetries>50){this._processNextAskAnswer();return}if(this._currentPtyPrompt){this._processNextAskAnswer();return}setTimeout(()=>this._waitForPtyPromptAndSubmit(),100)}_processNextAskAnswer(){if(!this._askAnswerQueue||this._askAnswerQueue.length===0){this._askSubmitting=!1;return}const n=this._askAnswerQueue.shift();n.type==="other"?this._submitOtherAnswer(n):n.type==="multi"?this._submitMultiSelectAnswer(n):this._submitSingleSelectAnswer(n)}_submitSingleSelectAnswer(n){this._submitViaSequentialQueue(n)}_submitMultiSelectAnswer(n){this._submitViaSequentialQueue(n)}_submitOtherAnswer(n){this._submitViaSequentialQueue(n)}_submitViaSequentialQueue(n){const i=this._inputWs;if(!i||i.readyState!==WebSocket.OPEN){this._askSubmitting=!1;return}const r=this._askAnswerQueue&&this._askAnswerQueue.length>0,s=xBe(n,this.state.ptyPrompt,r),o=a=>{try{JSON.parse(a.data).type==="input-sequential-done"&&(i.removeEventListener("message",o),this._finishCurrentAskAnswer())}catch{}};i.addEventListener("message",o),i.send(JSON.stringify({type:"input-sequential",chunks:s,settleMs:300})),setTimeout(()=>{i.removeEventListener("message",o),this._askSubmitting&&this._finishCurrentAskAnswer()},15e3)}_finishCurrentAskAnswer(){this._currentPtyPrompt=null,this.setState(n=>{const i=n.ptyPromptHistory.slice(),r=i[i.length-1];return r&&r.status==="active"&&(i[i.length-1]={...r,status:"answered"}),{ptyPrompt:null,ptyPromptHistory:i}}),(!this._askAnswerQueue||this._askAnswerQueue.length===0)&&this._ptyDebounceTimer&&clearTimeout(this._ptyDebounceTimer),this._askAnswerQueue&&this._askAnswerQueue.length>0?setTimeout(()=>{this._processNextAskAnswer()},500):this._askSubmitting=!1}_snapToInitialPosition(){this.setState({terminalWidth:468,needsInitialSnap:!1}),localStorage.setItem("cc-viewer-terminal-width","468")}render(){const{mainAgentSessions:n,cliMode:i,terminalVisible:r}=this.props,{allItems:s,visibleCount:o,loading:a,terminalWidth:l}=this.state,c=!n||n.length===0;if(c&&!i)return y.jsx("div",{className:Nn.centerEmpty,children:y.jsx(Lr,{description:re("ui.noChat")})});if(a&&!i)return y.jsx("div",{className:Nn.centerEmpty,children:y.jsx(Da,{size:"large"})});const u=this._scrollTargetIdx,{highlightTs:d,highlightFading:O}=this.state,p=d&&this._tsItemMap&&this._tsItemMap[d]!=null?this._tsItemMap[d]:null,g=s.slice(0,o),{pendingInput:v,stickyBottom:$,ptyPromptHistory:S}=this.state,_=i&&v?y.jsx(sl,{role:"user",text:v,timestamp:new Date().toISOString(),userProfile:this.props.userProfile},"pending-input"):null,x=$?null:y.jsxs("button",{className:Nn.stickyBottomBtn,onClick:this.handleStickToBottom,children:[y.jsx("span",{children:re("ui.stickyBottom")}),y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:y.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),Q=i&&S.length>0?S.filter(T=>!(W$(T)&&T.status==="active")).map((T,z)=>{const R=T.status==="active",L=T.status==="answered";return y.jsxs("div",{className:`${Nn.ptyPromptBubble}${R?"":" "+Nn.ptyPromptResolved}`,children:[y.jsx("div",{className:Nn.ptyPromptQuestion,children:T.question}),y.jsx("div",{className:Nn.ptyPromptOptions,children:T.options.map(I=>{const E=L&&T.selectedNumber===I.number;let X=Nn.ptyPromptOption;return R&&I.selected&&(X=Nn.ptyPromptOptionPrimary),E&&(X=Nn.ptyPromptOptionChosen),!R&&!E&&(X=Nn.ptyPromptOptionDimmed),y.jsxs("button",{className:X,disabled:!R,onClick:R?()=>this.handlePromptOptionClick(I.number):void 0,children:[I.number,". ",I.text]},I.number)})})]},`pty-prompt-${z}`)}):null,w=ki&&this._mobileSliceOffset>0?y.jsx("div",{className:Nn.loadMoreWrap,children:y.jsx("button",{className:Nn.loadMoreBtn,onClick:this.handleLoadMore,children:re("ui.loadMoreHistory",{count:this._mobileSliceOffset})})}):null,C=c||a?y.jsxs("div",{className:Nn.messageListWrap,children:[y.jsxs("div",{ref:this.containerRef,className:Nn.container,children:[!i||a?y.jsx("div",{className:Nn.centerEmpty,children:a?y.jsx(Da,{size:"large"}):y.jsx(Lr,{description:re("ui.noChat")})}):null,_,Q]}),x]}):y.jsxs("div",{className:Nn.messageListWrap,children:[y.jsxs("div",{ref:this.containerRef,className:Nn.container,children:[w,g.map((T,z)=>{const R=z===u,L=z===p;let I=T;return L&&(I=ne.cloneElement(I,{highlight:O?"fading":"active"})),R?y.jsx("div",{ref:this._scrollTargetRef,children:I},T.key+"-anchor"):I}),_,Q]}),x]});return i?y.jsxs("div",{ref:this.splitContainerRef,className:Nn.splitContainer,children:[y.jsxs("div",{className:Nn.navSidebar,children:[y.jsx("button",{className:this.state.fileExplorerOpen?Nn.navBtnActive:Nn.navBtn,onClick:()=>{this._setFileExplorerOpen(!this.state.fileExplorerOpen),this.setState({gitChangesOpen:!1})},title:re("ui.fileExplorer"),children:y.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:y.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 2h9a2 2 0 0 1 2 2z"})})}),y.jsx("button",{className:this.state.gitChangesOpen?Nn.navBtnActive:Nn.navBtn,onClick:()=>this.setState(T=>(this._setFileExplorerOpen(!1),{gitChangesOpen:!T.gitChangesOpen})),title:re("ui.gitChanges"),children:y.jsx("svg",{width:"24",height:"24",viewBox:"0 0 1024 1024",fill:"currentColor",children:y.jsx("path",{d:"M759.53332137 326.35000897c0-48.26899766-39.4506231-87.33284994-87.87432908-86.6366625-46.95397689 0.69618746-85.08957923 39.14120645-85.39899588 86.09518335-0.23206249 40.68828971 27.53808201 74.87882971 65.13220519 84.47074592 10.82958281 2.78474987 18.41029078 12.37666607 18.64235327 23.51566553 0.38677082 21.11768647-3.40358317 44.40128953-17.24997834 63.81718442-22.20064476 31.17372767-62.42480948 42.46743545-97.93037026 52.44612248-22.43270724 6.26568719-38.75443563 7.89012462-53.14230994 9.28249954-20.42149901 2.01120825-39.76003975 3.94506233-63.89453858 17.79145747-5.10537475 2.93945818-10.13339535 6.18833303-14.85199928 9.74662453-4.09977063 3.09416652-9.90133285 0.15470833-9.90133286-4.95066641V302.60228095c0-9.43720788 5.26008307-18.17822829 13.69168683-22.3553531 28.69839444-14.23316598 48.42370599-43.93716454 48.19164353-78.20505872-0.38677082-48.57841433-41.15241468-87.71962076-89.730829-86.01782918C338.80402918 117.57112321 301.59667683 155.70672553 301.59667683 202.58334827c0 34.03583169 19.64795738 63.50776777 48.1916435 77.66357958 8.43160375 4.17712479 13.69168685 12.76343689 13.69168684 22.12329062v419.02750058c0 9.43720788-5.26008307 18.17822829-13.69168684 22.3553531-28.69839444 14.23316598-48.42370599 43.93716454-48.1916435 78.20505872 0.30941665 48.57841433 41.07506052 87.6422666 89.65347484 86.01782918C437.74000359 906.42887679 474.87000179 868.2159203 474.87000179 821.41665173c0-34.03583169-19.64795738-63.50776777-48.1916435-77.66357958-8.43160375-4.17712479-13.69168685-12.76343689-13.69168684-22.12329062v-14.85199926c0-32.48874844 15.39347842-63.27570528 42.00331048-81.91805854 2.39797906-1.70179159 4.95066642-3.32622901 7.50335379-4.79595812 14.92935344-8.58631209 25.91364457-9.66927037 44.09187287-11.4484161 15.62554091-1.54708326 35.04143581-3.48093734 61.65126786-10.90693699 39.06385228-10.98429114 92.51557887-25.91364457 124.84961898-71.39789238 18.56499911-26.06835292 27.38337367-58.01562219 26.37776956-95.14562041-0.15470833-5.33743724-0.54147915-10.67487447-1.08295828-16.16702004-0.85089578-8.27689543 2.70739569-16.24437421 9.12779121-21.50445729 19.57060322-15.78024923 32.02462345-39.99210223 32.02462345-67.14341343zM351.1033411 202.58334827c0-20.49885317 16.63114503-37.12999821 37.1299982-37.1299982s37.12999821 16.63114503 37.12999821 37.1299982-16.63114503 37.12999821-37.12999821 37.1299982-37.12999821-16.63114503-37.1299982-37.1299982z m74.25999641 618.83330346c0 20.49885317-16.63114503 37.12999821-37.12999821 37.1299982s-37.12999821-16.63114503-37.1299982-37.1299982 16.63114503-37.12999821 37.1299982-37.1299982 37.12999821 16.63114503 37.12999821 37.1299982z m247.53332139-457.93664456c-20.49885317 0-37.12999821-16.63114503-37.1299982-37.1299982s16.63114503-37.12999821 37.1299982-37.12999821 37.12999821 16.63114503 37.1299982 37.12999821-16.63114503 37.12999821-37.1299982 37.1299982z"})})})]}),y.jsxs("div",{style:{flex:1,display:"flex",minWidth:0,position:"relative"},ref:this.innerSplitRef,children:[this.state.isDragging&&this.state.activeSnapLine&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const L=T.getBoundingClientRect().width-this.state.terminalWidth-5,I=this.state.activeSnapLine.linePosition,E=Math.min(L,I),X=Math.abs(I-L);return y.jsx("div",{className:Nn.snapPreview,style:{left:`${E}px`,width:`${X}px`}})})(),this.state.isDragging&&(()=>{const T=this.innerSplitRef.current;if(!T)return null;const L=T.getBoundingClientRect().width-this.state.terminalWidth-5,I=[...this.state.snapLines].map(k=>({...k,dist:Math.abs(k.linePosition-L)})).sort((k,j)=>k.dist-j.dist);if(I.length===0)return null;const E=I[0],X=this.state.activeSnapLine&&this.state.activeSnapLine.cols===E.cols;return y.jsx("div",{className:X?Nn.snapLineActive:Nn.snapLine,style:{left:`${E.linePosition}px`}},E.cols)})(),this.state.fileExplorerOpen&&y.jsx(hTe,{refreshTrigger:this.state.fileExplorerRefresh,onClose:()=>this._setFileExplorerOpen(!1),onFileClick:T=>this.setState({currentFile:T,currentGitDiff:null,scrollToLine:null}),expandedPaths:this.state.fileExplorerExpandedPaths,onToggleExpand:this.handleToggleExpandPath,currentFile:this.state.currentFile}),this.state.gitChangesOpen&&y.jsx(XWe,{refreshTrigger:this.state.gitChangesRefresh,onClose:()=>this.setState({gitChangesOpen:!1}),onFileClick:T=>this.setState({currentGitDiff:T,currentFile:null})}),y.jsx("div",{className:Nn.chatSection,style:{flex:1,minWidth:0,display:"flex"},children:y.jsxs("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[this.state.currentGitDiff&&y.jsx("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",flexDirection:"column"},children:y.jsx(mBe,{filePath:this.state.currentGitDiff,onClose:()=>this.setState({currentGitDiff:null}),onOpenFile:(T,z)=>{this._setFileExplorerOpen(!0),this.setState({currentGitDiff:null,currentFile:T,scrollToLine:z||1,gitChangesOpen:!1})}})}),this.state.currentFile&&y.jsx("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",flexDirection:"column"},children:lYe(this.state.currentFile)?y.jsx(uWe,{filePath:this.state.currentFile,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch("/api/editor-done",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.state.editorSessionId})}).catch(()=>{}),this.setState({currentFile:null,fileVersion:0,editorSessionId:null,editorFilePath:null})}},this.state.fileVersion):y.jsx(YLe,{filePath:this.state.currentFile,scrollToLine:this.state.scrollToLine,editorSession:!!this.state.editorSessionId,onClose:()=>{this.state.editorSessionId&&fetch("/api/editor-done",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.state.editorSessionId})}).catch(()=>{}),this.setState({currentFile:null,fileVersion:0,editorSessionId:null,editorFilePath:null})}},this.state.fileVersion)}),C,!r&&y.jsxs("div",{className:Nn.chatInputBar,children:[y.jsxs("div",{className:Nn.chatInputWrapper,children:[y.jsxs("div",{className:Nn.chatTextareaWrap,children:[y.jsx("textarea",{ref:this._inputRef,className:Nn.chatTextarea,placeholder:this.state.inputSuggestion?"":re("ui.chatInput.placeholder"),rows:1,onKeyDown:this.handleInputKeyDown,onInput:this.handleInputChange}),this.state.inputSuggestion&&this.state.inputEmpty&&y.jsx("div",{className:Nn.ghostText,children:this.state.inputSuggestion})]}),y.jsx("div",{className:Nn.chatInputHint,children:this.state.inputSuggestion&&this.state.inputEmpty?re("ui.chatInput.hintTab"):re("ui.chatInput.hintEnter")})]}),!ki&&y.jsx("button",{className:Nn.chatSendBtn,onClick:()=>{const T=document.createElement("input");T.type="file",T.onchange=async z=>{var L;const R=(L=z.target.files)==null?void 0:L[0];if(R)try{const E=`"${await WB(R)}"`,X=this._inputRef.current;X&&(X.value=(X.value?X.value+" ":"")+E,X.dispatchEvent(new Event("input",{bubbles:!0})),this.setState({inputEmpty:!1}))}catch(I){console.error("[CC Viewer] Upload failed:",I)}},T.click()},title:re("ui.terminal.upload"),children:y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[y.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),y.jsx("polyline",{points:"17 8 12 3 7 8"}),y.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]})}),y.jsx("button",{className:Nn.chatSendBtn,onClick:this.handleInputSend,disabled:this.state.inputEmpty,title:re("ui.chatInput.send"),children:y.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[y.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),y.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),r&&this.state.inputSuggestion&&y.jsxs("div",{className:Nn.suggestionChip,onClick:this.handleSuggestionToTerminal,children:[y.jsx("span",{className:Nn.suggestionChipText,children:this.state.inputSuggestion}),y.jsx("span",{className:Nn.suggestionChipAction,children:"↵"})]})]})}),r&&y.jsxs(y.Fragment,{children:[y.jsx("div",{className:Nn.vResizer,onMouseDown:this.handleSplitMouseDown}),y.jsx("div",{style:{width:l,flexShrink:0,minWidth:200,display:"flex",flexDirection:"column"},children:y.jsx(VB,{onEditorOpen:(T,z)=>{this.setState({editorSessionId:T,editorFilePath:z,currentFile:z,currentGitDiff:null,scrollToLine:null,fileVersion:(this.state.fileVersion||0)+1})},onFilePath:T=>{const z=`"${T}"`;this._inputWs&&this._inputWs.readyState===WebSocket.OPEN&&this._inputWs.send(JSON.stringify({type:"input",data:z}))}})})]})]})]}):C}}const pYe="_resizer_yamj2_1",mYe={resizer:pYe};class gYe extends ne.Component{constructor(e){super(e),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this)}handleMouseDown(e){e.preventDefault(),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}handleMouseMove(e){this.props.onResize&&this.props.onResize(e.clientX)}handleMouseUp(){document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}componentWillUnmount(){document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}render(){return y.jsx("div",{onMouseDown:this.handleMouseDown,className:mYe.resizer})}}const vYe="_container_1um1r_1",$Ye="_fileListSection_1um1r_10",SYe="_header_1um1r_19",bYe="_headerTitle_1um1r_28",yYe="_fileCount_1um1r_36",_Ye="_changesContainer_1um1r_44",xYe="_changeItem_1um1r_51",QYe="_changeItemActive_1um1r_68",wYe="_dirItem_1um1r_77",PYe="_dirArrow_1um1r_88",CYe="_dirName_1um1r_97",kYe="_status_1um1r_102",TYe="_icon_1um1r_111",RYe="_fileName_1um1r_120",EYe="_diffSection_1um1r_127",XYe="_diffHeader_1um1r_135",zYe="_diffFilePath_1um1r_145",jYe="_diffBadge_1um1r_155",MYe="_diffContent_1um1r_167",NYe="_diffPlaceholder_1um1r_173",IYe="_statusText_1um1r_184",AYe="_errorText_1um1r_191",LYe="_emptyText_1um1r_198",WYe="_warningText_1um1r_205",Ci={container:vYe,fileListSection:$Ye,header:SYe,headerTitle:bYe,fileCount:yYe,changesContainer:_Ye,changeItem:xYe,changeItemActive:QYe,dirItem:wYe,dirArrow:PYe,dirName:CYe,status:kYe,icon:TYe,fileName:RYe,diffSection:EYe,diffHeader:XYe,diffFilePath:zYe,diffBadge:jYe,diffContent:MYe,diffPlaceholder:NYe,statusText:IYe,errorText:AYe,emptyText:LYe,warningText:WYe},VYe={M:"#e2c08d",A:"#73c991",D:"#f14c4c",R:"#73c991",C:"#73c991",U:"#e2c08d","?":"#73c991","??":"#73c991"},BYe={"??":"U"},YYe={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 UYe(t){const e=t.includes(".")?t.split(".").pop().toLowerCase():"",n=YYe[e]||"#888";return y.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",children:[y.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),y.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function DYe(){return y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"#c09553",stroke:"none",children:y.jsx("path",{d:"M2 6c0-1.1.9-2 2-2h5l2 2h9a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6z"})})}function qYe(t){const e={dirs:{},files:[]};for(const n of t){const i=n.file.split("/");let r=e;for(let s=0;s<i.length-1;s++)r.dirs[i[s]]||(r.dirs[i[s]]={dirs:{},files:[]}),r=r.dirs[i[s]];r.files.push({name:i[i.length-1],status:n.status,fullPath:n.file})}return e}function IZ({name:t,node:e,depth:n,selectedFile:i,onFileClick:r}){const s=Object.keys(e.dirs).sort(),o=[...e.files].sort((a,l)=>a.name.localeCompare(l.name));return y.jsxs(y.Fragment,{children:[t&&y.jsxs("div",{className:Ci.dirItem,style:{paddingLeft:8+n*16},children:[y.jsx("span",{className:Ci.dirArrow,children:y.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:"rotate(90deg)"},children:y.jsx("polyline",{points:"9 6 15 12 9 18"})})}),y.jsx("span",{className:Ci.icon,children:DYe()}),y.jsx("span",{className:Ci.dirName,children:t})]}),s.map(a=>y.jsx(IZ,{name:a,node:e.dirs[a],depth:t?n+1:n,selectedFile:i,onFileClick:r},a)),o.map(a=>y.jsxs("div",{className:`${Ci.changeItem} ${i===a.fullPath?Ci.changeItemActive:""}`,style:{paddingLeft:8+(t?n+1:n)*16},onClick:()=>r&&r(a.fullPath),children:[y.jsx("span",{className:Ci.icon,children:UYe(a.name)}),y.jsx("span",{className:Ci.fileName,children:a.name}),y.jsx("span",{className:Ci.status,style:{color:VYe[a.status]||"#888"},children:BYe[a.status]||a.status})]},a.fullPath))]})}function ZYe({visible:t}){const[e,n]=f.useState(null),[i,r]=f.useState(null),[s,o]=f.useState(!0),[a,l]=f.useState(null),[c,u]=f.useState(null),[d,O]=f.useState(null),[p,g]=f.useState(!1),v=f.useRef(!0);return f.useEffect(()=>{if(v.current=!0,!!t)return o(!0),r(null),fetch(Rn("/api/git-status")).then($=>$.ok?$.json():Promise.reject()).then($=>{v.current&&(n($.changes||[]),o(!1))}).catch(()=>{v.current&&(r("Failed to load git status"),o(!1))}),()=>{v.current=!1}},[t]),f.useEffect(()=>{if(!a){u(null),O(null);return}g(!0),u(null),O(null),fetch(Rn(`/api/git-diff?files=${encodeURIComponent(a)}`)).then($=>{if(!$.ok)throw new Error(`HTTP ${$.status}`);return $.json()}).then($=>{v.current&&($.diffs&&$.diffs[0]?u($.diffs[0]):O("No diff data available"),g(!1))}).catch($=>{v.current&&(O(`${re("ui.fileLoadError")}: ${$.message}`),g(!1))})},[a]),y.jsxs("div",{className:Ci.container,children:[y.jsxs("div",{className:Ci.fileListSection,children:[y.jsxs("div",{className:Ci.header,children:[y.jsx("span",{className:Ci.headerTitle,children:re("ui.gitChanges")}),y.jsx("span",{className:Ci.fileCount,children:e?e.length:0})]}),y.jsxs("div",{className:Ci.changesContainer,children:[s&&y.jsx("div",{className:Ci.statusText,children:"Loading..."}),i&&y.jsx("div",{className:Ci.errorText,children:i}),!s&&!i&&e&&e.length===0&&y.jsx("div",{className:Ci.emptyText,children:"No changes"}),!s&&!i&&e&&e.length>0&&y.jsx(IZ,{name:"",node:qYe(e),depth:0,selectedFile:a,onFileClick:l})]})]}),y.jsx("div",{className:Ci.diffSection,children:a?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:Ci.diffHeader,children:[y.jsx("span",{className:Ci.diffFilePath,children:a}),y.jsx("span",{className:Ci.diffBadge,children:"DIFF"})]}),y.jsxs("div",{className:Ci.diffContent,children:[p&&y.jsx("div",{className:Ci.statusText,children:re("ui.loading")}),d&&y.jsx("div",{className:Ci.errorText,children:d}),!p&&!d&&c&&y.jsx(y.Fragment,{children:c.is_large?y.jsxs("div",{className:Ci.warningText,children:[y.jsx("p",{children:re("ui.largeFileWarning")}),y.jsxs("p",{style:{color:"#888",fontSize:12},children:[re("ui.fileSize"),": ",(c.size/(1024*1024)).toFixed(2)," MB"]})]}):c.is_binary?y.jsx("div",{className:Ci.statusText,style:{fontStyle:"italic"},children:re("ui.binaryFileNotice")}):y.jsx(NZ,{file_path:a,old_string:c.old_content,new_string:c.new_content})})]})]}):y.jsxs("div",{className:Ci.diffPlaceholder,children:[y.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"#333",strokeWidth:"1.5",children:[y.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),y.jsx("circle",{cx:"18",cy:"6",r:"3"}),y.jsx("circle",{cx:"6",cy:"18",r:"3"}),y.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),y.jsx("span",{children:re("ui.mobileGitDiffHint")})]})})]})}const FYe="_container_rkahp_1",GYe="_header_rkahp_9",HYe="_headerTitle_rkahp_18",KYe="_closeBtn_rkahp_24",JYe="_content_rkahp_38",eUe="_empty_rkahp_47",tUe="_fixedTable_rkahp_54",nUe="_ellipsisCell_rkahp_58",su={container:FYe,header:GYe,headerTitle:HYe,closeBtn:KYe,content:JYe,empty:eUe,fixedTable:tUe,ellipsisCell:nUe},iUe=["ttl","system_change","tools_change","model_change","msg_truncated","msg_modified","key_change"],k9={ttl:"cacheLoss.ttl",system_change:"cacheLoss.systemChange",tools_change:"cacheLoss.toolsChange",model_change:"cacheLoss.modelChange",msg_truncated:"cacheLoss.msgTruncated",msg_modified:"cacheLoss.msgModified",key_change:"cacheLoss.keyChange"};function rUe({requests:t=[],visible:e,onClose:n}){if(!e)return null;const{byModel:i,models:r,toolStats:s,skillStats:o,cacheStats:a,activeReasons:l,totalCount:c,totalCache:u,hasCacheStats:d,subAgentEntries:O,hasSubAgentStats:p,isEmpty:g}=f.useMemo(()=>{const v=DW(t),$=Object.keys(v),S=ZW(t),_=FW(t),x=qW(t),Q=iUe.filter(j=>x[j].count>0),w=Q.reduce((j,N)=>j+x[N].count,0),C=Q.reduce((j,N)=>j+x[N].cacheCreate,0),T=Q.length>0,z={};for(let j=0;j<t.length;j++){const N=zu(t[j],t[j+1]);if(N.type==="SubAgent"){const A=N.subType||"Other";z[A]=(z[A]||0)+1}else if(N.type==="Teammate"){const A=N.subType?`Teammate:${N.subType}`:"Teammate";z[A]=(z[A]||0)+1}}const R=Object.entries(z).sort((j,N)=>N[1]-j[1]),L=R.length>0,I={};for(let j=0;j<t.length;j++){const N=zu(t[j],t[j+1]);if(N.type==="Teammate"){const A=N.subType||"Teammate";I[A]=(I[A]||0)+1}}const X=Object.entries(I).sort((j,N)=>N[1]-j[1]).length>0,k=$.length===0&&S.length===0&&!T&&!L&&!X&&_.length===0;return{byModel:v,models:$,toolStats:S,skillStats:_,cacheStats:x,activeReasons:Q,totalCount:w,totalCache:C,hasCacheStats:T,subAgentEntries:R,hasSubAgentStats:L,isEmpty:k}},[t]);return y.jsxs("div",{className:su.container,children:[y.jsxs("div",{className:su.header,children:[y.jsx("span",{className:su.headerTitle,children:re("ui.tokenStats")}),y.jsx("button",{className:su.closeBtn,onClick:n,children:y.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y.jsx("div",{className:su.content,children:g?y.jsx("div",{className:su.empty,children:"—"}):y.jsxs(y.Fragment,{children:[o.length>0&&y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:re("ui.skillUsageStats")}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"Skill"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[o.map(([v,$])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label,children:v}),y.jsx("td",{className:se.td,children:$})]},v)),o.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:o.reduce((v,$)=>v+$[1],0)})]})]})]})]}),p&&y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:re("ui.subAgentStats")}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"SubAgent"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[O.map(([v,$])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label,children:v}),y.jsx("td",{className:se.td,children:$})]},v)),O.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:O.reduce((v,$)=>v+$[1],0)})]})]})]})]}),hasTeammateStats&&y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:"Teammate"}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"Name"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[teammateEntries.map(([v,$])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label,children:v}),y.jsx("td",{className:se.td,children:$})]},v)),teammateEntries.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:teammateEntries.reduce((v,$)=>v+$[1],0)})]})]})]})]}),s.length>0&&y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:re("ui.toolUsageStats")}),y.jsxs("table",{className:se.statsTable,children:[y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:"Tool"}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")})]})}),y.jsxs("tbody",{children:[s.map(([v,$])=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsxs("td",{className:se.label,children:[v," ",y.jsx(La,{doc:`Tool-${v}`})]}),y.jsx("td",{className:se.td,children:$})]},v)),s.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:s.reduce((v,$)=>v+$[1],0)})]})]})]})]}),d&&y.jsxs("div",{className:se.modelCard,children:[y.jsxs("div",{className:se.modelName,children:["MainAgent",y.jsx(La,{doc:"MainAgent"})," ",re("ui.cacheRebuildStats"),y.jsx(La,{doc:"CacheRebuild"})]}),y.jsxs("table",{className:`${se.statsTable} ${su.fixedTable}`,children:[y.jsxs("colgroup",{children:[y.jsx("col",{style:{width:"50%"}}),y.jsx("col",{style:{width:"25%"}}),y.jsx("col",{style:{width:"25%"}})]}),y.jsx("thead",{children:y.jsxs("tr",{children:[y.jsx("td",{className:se.th,style:{textAlign:"left"},children:re("ui.cacheRebuild.reason")}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.count")}),y.jsx("td",{className:se.th,children:re("ui.cacheRebuild.cacheCreate")})]})}),y.jsxs("tbody",{children:[l.map(v=>y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:`${se.label} ${su.ellipsisCell}`,title:re(`ui.${k9[v]}`),children:re(`ui.${k9[v]}`)}),y.jsx("td",{className:se.td,children:a[v].count}),y.jsx("td",{className:se.td,children:$i(a[v].cacheCreate)})]},v)),l.length>1&&y.jsxs("tr",{className:se.rebuildTotalRow,children:[y.jsx("td",{className:se.label,children:"Total"}),y.jsx("td",{className:se.td,children:c}),y.jsx("td",{className:se.td,children:$i(u)})]})]})]})]}),r.map(v=>{const $=i[v],S=$.input+$.cacheCreation+$.cacheRead,_=S>0?($.cacheRead/S*100).toFixed(1):"0.0";return y.jsxs("div",{className:se.modelCard,children:[y.jsx("div",{className:se.modelName,children:v}),y.jsx("table",{className:se.statsTable,children:y.jsxs("tbody",{children:[y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:"Token"}),y.jsx("td",{className:se.th,children:"input"}),y.jsx("td",{className:se.th,children:"output"})]}),y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label}),y.jsx("td",{className:se.td,children:$i(S)}),y.jsx("td",{className:se.td,children:$i($.output)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:"Cache"}),y.jsx("td",{className:se.th,children:"create"}),y.jsx("td",{className:se.th,children:"read"})]}),y.jsxs("tr",{className:se.rowBorder,children:[y.jsx("td",{className:se.label}),y.jsx("td",{className:se.td,children:$i($.cacheCreation)}),y.jsx("td",{className:se.td,children:$i($.cacheRead)})]}),y.jsxs("tr",{children:[y.jsx("td",{className:se.label,children:re("ui.hitRate")}),y.jsxs("td",{colSpan:2,className:se.td,children:[_,"%"]})]})]})})]},v)})]})})]})}const{Text:Ed,Title:sUe}=Ga;function oUe(t){if(!t)return"0 B";const e=["B","KB","MB","GB"];let n=0,i=t;for(;i>=1024&&n<e.length-1;)i/=1024,n++;return`${i.toFixed(n>0?1:0)} ${e[n]}`}function aUe(t){if(!t)return"";const e=Date.now()-new Date(t).getTime(),n=Math.floor(e/6e4);if(n<1)return re("ui.workspaces.justNow");if(n<60)return`${n}m ago`;const i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function lUe({open:t,onClose:e,onSelect:n}){const[i,r]=f.useState(""),[s,o]=f.useState(null),[a,l]=f.useState([]),[c,u]=f.useState(!1),[d,O]=f.useState(""),p=f.useCallback(v=>{u(!0);const $=v?`/api/browse-dir?path=${encodeURIComponent(v)}`:"/api/browse-dir";fetch(Rn($)).then(S=>S.json()).then(S=>{S.error?ei.error(S.error):(r(S.current),o(S.parent),l(S.dirs||[]),O(S.current)),u(!1)}).catch(()=>{ei.error("Failed to browse directory"),u(!1)})},[]);f.useEffect(()=>{t&&p("")},[t,p]);const g=()=>{const v=d.trim();v&&p(v)};return y.jsxs(Tr,{title:re("ui.workspaces.selectDir"),open:t,onCancel:e,footer:null,width:600,styles:{body:{padding:"12px 0"}},children:[y.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"0 16px 10px",borderBottom:"1px solid #2a2a2a"},children:[y.jsx(Sn,{type:"text",icon:y.jsx(Rve,{}),disabled:!s,onClick:()=>s&&p(s),size:"small"}),y.jsxs(Ed,{style:{color:"#e0e0e0",fontSize:13,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[y.jsx(d1,{style:{marginRight:6,color:"#1668dc"}}),i]})]}),y.jsx("div",{style:{maxHeight:400,overflowY:"auto",padding:"4px 0"},children:c?y.jsx("div",{style:{textAlign:"center",padding:40},children:y.jsx(Da,{})}):a.length===0?y.jsx("div",{style:{textAlign:"center",padding:40},children:y.jsx(Ed,{type:"secondary",children:re("ui.workspaces.emptyDir")})}):a.map(v=>y.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 16px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:$=>$.currentTarget.style.background="#1a1a1a",onMouseLeave:$=>$.currentTarget.style.background="transparent",children:[y.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:8,minWidth:0},onClick:()=>p(v.path),children:[y.jsx(vW,{style:{color:v.hasGit?"#1668dc":"#666",fontSize:16,flexShrink:0}}),y.jsx(Ed,{style:{color:"#d0d0d0",fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name}),v.hasGit&&y.jsxs(eo,{color:"blue",style:{fontSize:11,lineHeight:"18px",padding:"0 4px",margin:0,flexShrink:0},children:[y.jsx(TW,{style:{marginRight:2}}),"git"]})]}),y.jsx(Sn,{type:"primary",size:"small",onClick:$=>{$.stopPropagation(),n(v.path)},children:re("ui.workspaces.select")})]},v.path))}),y.jsxs("div",{style:{borderTop:"1px solid #2a2a2a",padding:"10px 16px 4px",display:"flex",flexDirection:"column",gap:8},children:[y.jsxs(Sn,{type:"primary",ghost:!0,block:!0,icon:y.jsx(d1,{}),onClick:()=>n(i),children:[re("ui.workspaces.selectCurrent")," — ",i.split("/").pop()||i]}),y.jsxs("div",{style:{display:"flex",gap:8},children:[y.jsx(Yu,{size:"small",value:d,onChange:v=>O(v.target.value),onPressEnter:g,placeholder:re("ui.workspaces.pathPlaceholder"),style:{flex:1}}),y.jsx(Sn,{size:"small",onClick:g,children:re("ui.workspaces.goTo")})]})]})]})}function cUe({onLaunch:t}){const[e,n]=f.useState([]),[i,r]=f.useState(!0),[s,o]=f.useState(null),[a,l]=f.useState(!1),c=()=>{fetch(Rn("/api/workspaces")).then(p=>p.json()).then(p=>{n(p.workspaces||[]),r(!1)}).catch(()=>r(!1))};f.useEffect(()=>{c()},[]);const u=p=>{l(!1),fetch(Rn("/api/workspaces/add"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p})}).then(g=>g.json()).then(g=>{g.error?ei.error(g.error):c()}).catch(()=>ei.error("Failed to add workspace"))},d=p=>{fetch(Rn(`/api/workspaces/${p}`),{method:"DELETE"}).then(g=>g.json()).then(()=>c()).catch(()=>{})},O=p=>{o(p.id),fetch(Rn("/api/workspaces/launch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p.path})}).then(g=>g.json()).then(g=>{g.error?(ei.error(g.error),o(null)):t({projectName:g.projectName,path:p.path})}).catch(()=>{ei.error("Launch failed"),o(null)})};return y.jsxs("div",{style:{minHeight:"100vh",background:"#0a0a0a",display:"flex",justifyContent:"center",paddingTop:60},children:[y.jsxs("div",{style:{width:"100%",maxWidth:720,padding:"0 24px"},children:[y.jsxs("div",{style:{marginBottom:32,textAlign:"center"},children:[y.jsxs(sUe,{level:3,style:{color:"#e0e0e0",margin:0},children:[y.jsx(d1,{style:{marginRight:8,color:"#1668dc"}}),re("ui.workspaces.title")]}),y.jsx(Ed,{type:"secondary",style:{fontSize:13},children:re("ui.workspaces.subtitle")})]}),y.jsx("div",{style:{marginBottom:20,textAlign:"center"},children:y.jsx(Sn,{type:"primary",icon:y.jsx(o1,{}),onClick:()=>l(!0),size:"large",children:re("ui.workspaces.browse")})}),i?y.jsx("div",{style:{textAlign:"center",padding:60},children:y.jsx(Da,{})}):e.length===0?y.jsx(Lr,{description:y.jsx(Ed,{type:"secondary",children:re("ui.workspaces.empty")}),style:{marginTop:60}}):y.jsx(c1,{dataSource:e,renderItem:p=>y.jsx(Y2,{size:"small",style:{marginBottom:10,background:"#141414",borderColor:"#2a2a2a",cursor:"pointer"},hoverable:!0,onClick:()=>O(p),children:y.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[y.jsxs("div",{style:{flex:1,minWidth:0},children:[y.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:y.jsx(Ed,{strong:!0,style:{color:"#e0e0e0",fontSize:15},children:p.projectName})}),y.jsx(Ed,{type:"secondary",style:{fontSize:12,wordBreak:"break-all"},children:p.path}),y.jsxs("div",{style:{display:"flex",gap:16,marginTop:6,fontSize:12,color:"#666"},children:[y.jsxs("span",{children:[y.jsx(Dde,{style:{marginRight:4}}),aUe(p.lastUsed)]}),p.logCount>0&&y.jsxs("span",{children:[y.jsx(Vve,{style:{marginRight:4}}),p.logCount," logs (",oUe(p.totalSize),")"]})]})]}),y.jsxs(yl,{children:[y.jsx(Sn,{type:"primary",icon:y.jsx(t0e,{}),loading:s===p.id,onClick:g=>{g.stopPropagation(),O(p)},children:re("ui.workspaces.open")}),y.jsx(GL,{title:re("ui.workspaces.confirmRemove"),onConfirm:g=>{g==null||g.stopPropagation(),d(p.id)},onCancel:g=>g==null?void 0:g.stopPropagation(),okText:"Yes",cancelText:"No",children:y.jsx(Sn,{type:"text",danger:!0,icon:y.jsx(O1,{}),onClick:g=>g.stopPropagation()})})]})]})},p.id)})]}),y.jsx(lUe,{open:a,onClose:()=>l(!1),onSelect:u})]})}const uUe="_layout_1a3p0_1",dUe="_header_1a3p0_6",hUe="_content_1a3p0_14",OUe="_mainContainer_1a3p0_19",fUe="_leftPanel_1a3p0_24",pUe="_leftPanelHeader_1a3p0_32",mUe="_leftPanelCount_1a3p0_43",gUe="_leftPanelBody_1a3p0_49",vUe="_rightPanel_1a3p0_54",$Ue="_modalActions_1a3p0_60",SUe="_spinCenter_1a3p0_64",bUe="_emptyCenter_1a3p0_69",yUe="_logListContainer_1a3p0_79",_Ue="_loadingOverlay_1a3p0_127",xUe="_loadingText_1a3p0_140",QUe="_mobileLoadingOverlay_1a3p0_146",wUe="_mobileLoadingSpinner_1a3p0_158",PUe="_mobileLoadingLabel_1a3p0_171",CUe="_footer_1a3p0_177",kUe="_footerRight_1a3p0_188",TUe="_footerText_1a3p0_196",RUe="_footerLink_1a3p0_201",EUe="_footerIcon_1a3p0_213",XUe="_footerDivider_1a3p0_218",zUe="_guideContainer_1a3p0_226",jUe="_guideContent_1a3p0_234",MUe="_guideTitle_1a3p0_239",NUe="_guideStep_1a3p0_246",IUe="_guideStepNum_1a3p0_252",AUe="_guideStepBody_1a3p0_267",LUe="_guideText_1a3p0_272",WUe="_guideCode_1a3p0_279",VUe="_mobileChatOverlay_1a3p0_292",BUe="_mobileChatOverlayVisible_1a3p0_304",YUe="_mobileChatInner_1a3p0_308",UUe="_mobileGitDiffOverlay_1a3p0_316",DUe="_mobileGitDiffOverlayVisible_1a3p0_328",qUe="_mobileGitDiffInner_1a3p0_332",ZUe="_mobileMenuBtn_1a3p0_340",FUe="_mobileMenuOverlay_1a3p0_357",GUe="_mobileMenuDropdown_1a3p0_363",HUe="_mobileMenuItem_1a3p0_377",KUe="_mobileStatsOverlay_1a3p0_395",JUe="_mobileStatsOverlayVisible_1a3p0_407",eDe="_mobileStatsInner_1a3p0_411",tDe="_mobileLogMgmtOverlay_1a3p0_418",nDe="_mobileLogMgmtOverlayVisible_1a3p0_430",iDe="_mobileLogMgmtHeader_1a3p0_434",rDe="_mobileLogMgmtTitle_1a3p0_443",sDe="_mobileLogMgmtClose_1a3p0_449",oDe="_mobileLogMgmtActions_1a3p0_464",aDe="_mobileLogMgmtBody_1a3p0_472",lDe="_mobileSettingsOverlay_1a3p0_479",cDe="_mobileSettingsOverlayVisible_1a3p0_491",uDe="_mobilePromptOverlay_1a3p0_495",dDe="_mobilePromptOverlayVisible_1a3p0_507",hDe="_mobilePromptBody_1a3p0_511",ODe="_mobilePromptList_1a3p0_519",fDe="_mobilePromptItem_1a3p0_525",pDe="_mobilePromptTimestamp_1a3p0_530",mDe="_mobilePromptCard_1a3p0_537",gDe="_mobilePromptPreText_1a3p0_545",vDe="_previewPopover_1a3p0_555",$De="_previewItem_1a3p0_561",SDe="_previewText_1a3p0_573",yt={layout:uUe,header:dUe,content:hUe,mainContainer:OUe,leftPanel:fUe,leftPanelHeader:pUe,leftPanelCount:mUe,leftPanelBody:gUe,rightPanel:vUe,modalActions:$Ue,spinCenter:SUe,emptyCenter:bUe,logListContainer:yUe,loadingOverlay:_Ue,loadingText:xUe,mobileLoadingOverlay:QUe,mobileLoadingSpinner:wUe,mobileLoadingLabel:PUe,footer:CUe,footerRight:kUe,footerText:TUe,footerLink:RUe,footerIcon:EUe,footerDivider:XUe,guideContainer:zUe,guideContent:jUe,guideTitle:MUe,guideStep:NUe,guideStepNum:IUe,guideStepBody:AUe,guideText:LUe,guideCode:WUe,mobileChatOverlay:VUe,mobileChatOverlayVisible:BUe,mobileChatInner:YUe,mobileGitDiffOverlay:UUe,mobileGitDiffOverlayVisible:DUe,mobileGitDiffInner:qUe,mobileMenuBtn:ZUe,mobileMenuOverlay:FUe,mobileMenuDropdown:GUe,mobileMenuItem:HUe,mobileStatsOverlay:KUe,mobileStatsOverlayVisible:JUe,mobileStatsInner:eDe,mobileLogMgmtOverlay:tDe,mobileLogMgmtOverlayVisible:nDe,mobileLogMgmtHeader:iDe,mobileLogMgmtTitle:rDe,mobileLogMgmtClose:sDe,mobileLogMgmtActions:oDe,mobileLogMgmtBody:aDe,mobileSettingsOverlay:lDe,mobileSettingsOverlayVisible:cDe,mobilePromptOverlay:uDe,mobilePromptOverlayVisible:dDe,mobilePromptBody:hDe,mobilePromptList:ODe,mobilePromptItem:fDe,mobilePromptTimestamp:pDe,mobilePromptCard:mDe,mobilePromptPreText:gDe,previewPopover:vDe,previewItem:$De,previewText:SDe},bDe="ccv_entryCache",Vu="entries",H5="cache",K5="ccv_cacheMeta",yDe=1,_De=10080*60*1e3;let Fh=null,Gh=null;function J5(){return Fh?Promise.resolve(Fh):Gh||(Gh=new Promise((t,e)=>{const n=indexedDB.open(bDe,yDe);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Vu)||i.createObjectStore(Vu)},n.onsuccess=()=>{Fh=n.result,Fh.onclose=()=>{Fh=null},Gh=null,t(Fh)},n.onerror=()=>{Gh=null,e(n.error)}}),Gh)}let T9=0;function xDe(t,e){try{const n=e[e.length-1],i=(n==null?void 0:n.timestamp)||null;i&&localStorage.setItem(K5,JSON.stringify({projectName:t,lastTs:i,count:e.length}))}catch{}}function QDe(){try{localStorage.removeItem(K5)}catch{}}function wDe(){try{const t=localStorage.getItem(K5);if(!t)return null;const e=JSON.parse(t);return e!=null&&e.lastTs&&(e==null?void 0:e.count)>0&&(e!=null&&e.projectName)?e:null}catch{return null}}async function iw(t,e){if(!t||!Array.isArray(e)||e.length===0)return;const n=++T9;try{const i=await J5();return n!==T9?void 0:(xDe(t,e),new Promise(r=>{const s=i.transaction(Vu,"readwrite");s.objectStore(Vu).put({projectName:t,entries:e,ts:Date.now()},H5),s.oncomplete=()=>r(),s.onerror=()=>r()}))}catch{}}async function PDe(t){try{const e=await J5();return new Promise(n=>{const r=e.transaction(Vu,"readonly").objectStore(Vu).get(H5);r.onsuccess=()=>{const s=r.result;!s||s.projectName!==t||!Array.isArray(s.entries)||s.entries.length===0?n(null):s.ts&&Date.now()-s.ts>_De?(Yk(),n(null)):n(s.entries)},r.onerror=()=>n(null)})}catch{return null}}async function Yk(){QDe();try{const t=await J5();return new Promise(e=>{const n=t.transaction(Vu,"readwrite");n.objectStore(Vu).delete(H5),n.oncomplete=()=>e(),n.onerror=()=>e()})}catch{}}const mO=class mO extends ne.Component{constructor(n){super(n);gt(this,"_flushPendingEntries",()=>{this._flushRafId=null;const n=this._pendingEntries;this._pendingEntries=[],n.length!==0&&this.setState(i=>{var c,u;const r=[...i.requests];let s=i.cacheExpireAt,o=i.cacheType,a=i.mainAgentSessions;for(const d of n){const O=`${d.timestamp}|${d.url}`,p=this._requestIndexMap.get(O);if(p!==void 0?r[p]=d:(this._requestIndexMap.set(O,r.length),r.push(d)),wr(d)){const g=(u=(c=d.response)==null?void 0:c.body)==null?void 0:u.usage;if(g!=null&&g.cache_creation){const v=g.cache_creation,$=d.timestamp?new Date(d.timestamp).getTime():Date.now();let S=null,_=null;if(v.ephemeral_1h_input_tokens>0?(S=$+3600*1e3,_="1h"):v.ephemeral_5m_input_tokens>0&&(S=$+300*1e3,_="5m"),S&&S>Date.now()){s=S;const x=(g.cache_read_input_tokens||0)+(g.cache_creation_input_tokens||0);o=x>0?$i(x):_,localStorage.setItem("ccv_cacheExpireAt",String(s)),localStorage.setItem("ccv_cacheType",o)}}}if(wr(d)&&d.body&&Array.isArray(d.body.messages)){const g=d.timestamp||new Date().toISOString(),v=a.length>0?a[a.length-1]:null,$=(v==null?void 0:v.messages)||[],S=d.body.messages,_=$.length,x=_>0&&S.length<_*.5&&_-S.length>4;for(let Q=0;Q<S.length;Q++)!x&&Q<_&&$[Q]._timestamp?S[Q]._timestamp=$[Q]._timestamp:S[Q]._timestamp||(S[Q]._timestamp=g);a=this.mergeMainAgentSessions(a,d)}}return this._cacheLossMapSource=null,i.selectedIndex===null&&r.length>0&&(this._autoSelectTimer&&clearTimeout(this._autoSelectTimer),this._autoSelectTimer=setTimeout(()=>{this.setState(d=>{if(d.selectedIndex===null&&d.requests.length>0){const O=d.showAll?d.requests:ra(d.requests);return O.length>0?{selectedIndex:O.length-1}:null}return null})},200)),{requests:r,cacheExpireAt:s,cacheType:o,mainAgentSessions:a}},()=>{ki&&this.state.projectName&&(this._cacheSaveTimer&&clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=setTimeout(()=>{this.state.projectName&&iw(this.state.projectName,this.state.requests)},5e3))})});gt(this,"handleSelectRequest",n=>{this.setState({selectedIndex:n,scrollCenter:!1})});gt(this,"handleViewRequest",n=>{this.setState({viewMode:"raw",selectedIndex:n,scrollCenter:!0})});gt(this,"handleScrollDone",()=>{this.setState({scrollCenter:!1})});gt(this,"handleCacheHighlightDone",()=>{this.setState({pendingCacheHighlight:null})});gt(this,"handleScrollTsDone",()=>{this.setState({chatScrollToTs:null})});gt(this,"handleViewInChat",()=>{this.setState(n=>{const r=(n.showAll?n.requests:ra(n.requests))[n.selectedIndex];if(!r)return null;let s=null;if(wr(r)&&r.timestamp)s=r.timestamp;else{const o=zu(r);if((o.type==="SubAgent"||o.type==="Teammate")&&r.timestamp)s=r.timestamp;else{const a=n.requests.indexOf(r);a>=0&&(s=a6(n.requests,a))}s||ei.info(re("ui.cannotMap"))}return{viewMode:"chat",chatScrollToTs:s}})});gt(this,"handleWorkspaceLaunch",({projectName:n})=>{this._isLocalLog=!1,this._localLogFile=null,this.setState({workspaceMode:!1,projectName:n,viewMode:"chat",cliMode:!0})});gt(this,"handleReturnToWorkspaces",()=>{fetch(Rn("/api/workspaces/stop"),{method:"POST"}).then(()=>{this._rebuildRequestIndex([]),this.setState({workspaceMode:!0,requests:[],mainAgentSessions:[],projectName:"",selectedIndex:null})}).catch(()=>{})});gt(this,"handleToggleViewMode",()=>{this.setState(n=>{const i=n.viewMode==="raw"?"chat":"raw";if(i==="raw"){if(n.selectedIndex===null){const o=n.showAll?n.requests:ra(n.requests);return{viewMode:i,selectedIndex:o.length>0?o.length-1:null,scrollCenter:!0}}return{viewMode:i,scrollCenter:!0}}const r=n.showAll?n.requests:ra(n.requests),s=n.selectedIndex!=null?r[n.selectedIndex]:null;if(s){let o=null;if(wr(s)&&s.timestamp)o=s.timestamp;else{const a=zu(s);if((a.type==="SubAgent"||a.type==="Teammate")&&s.timestamp)o=s.timestamp;else{const l=n.requests.indexOf(s);l>=0&&(o=a6(n.requests,l)),o||ei.info(re("ui.cannotMap"))}}return{viewMode:i,chatScrollToTs:o}}return{viewMode:i,chatScrollToTs:null}})});gt(this,"handleLangChange",()=>{const n=km();this.setState({lang:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:n})}).catch(()=>{})});gt(this,"handleCollapseToolResultsChange",n=>{this.setState({collapseToolResults:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({collapseToolResults:n})}).catch(()=>{})});gt(this,"handleExpandThinkingChange",n=>{this.setState({expandThinking:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandThinking:n})}).catch(()=>{})});gt(this,"handleExpandDiffChange",n=>{this.setState({expandDiff:n}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expandDiff:n})}).catch(()=>{})});gt(this,"handleFilterIrrelevantChange",n=>{this.setState(i=>{const r=!n,s=r?i.requests:ra(i.requests);return{showAll:r,selectedIndex:s.length>0?s.length-1:null}}),fetch(Rn("/api/preferences"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filterIrrelevant:n})}).catch(()=>{})});gt(this,"handleExportPromptsTxt",n=>{if(!n||n.length===0)return;const i=[];for(const a of n){const l=[],c=a.timestamp?new Date(a.timestamp).toLocaleString():"";c&&l.push(`${c}:
|
|
934
934
|
`);const u=(a.segments||[]).filter(d=>d.type==="text").map(d=>d.content);u.length>0&&l.push(u.join(`
|
|
935
935
|
`)),i.push(l.join(`
|
|
936
936
|
`))}if(i.length===0)return;const r=new Blob([i.join(`
|
package/dist/index.html
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
<title>Claude Code Viewer</title>
|
|
7
7
|
<link rel="icon" href="/favicon.ico?v=1">
|
|
8
8
|
<link rel="shortcut icon" href="/favicon.ico?v=1">
|
|
9
|
-
<script type="module" crossorigin src="/assets/index-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-3VL83o1N.js"></script>
|
|
10
10
|
<link rel="stylesheet" crossorigin href="/assets/index-7ty6PCA6.css">
|
|
11
11
|
</head>
|
|
12
12
|
<body>
|